/.project
/.buildpath
/.cache
+/phpunit.xml
\ No newline at end of file
@header('Content-Type: text/plain; charset=utf-8');
}
+// we do not want html markup in emulated CLI
+@ini_set('html_errors', 'off');
+
// execute the cron
cron_run();
}
// at this stage there can be only one admin unless more were added by install - users may change username, so do not rely on that
- $adminuser = get_complete_user_data('id', reset(explode(',', $CFG->siteadmins)));
+ $adminids = explode(',', $CFG->siteadmins);
+ $adminuser = get_complete_user_data('id', reset($adminids));
if ($adminuser->password === 'adminsetuppending') {
// prevent installation hijacking
if ($mnet_peer && !empty($mnet_peer->deleted)) {
$radioarray = array();
- $radioarray[] = MoodleQuickForm::createElement('static', 'deletedinfo', '',
+ $radioarray[] = $mform->createElement('static', 'deletedinfo', '',
$OUTPUT->container(get_string('deletedhostinfo', 'mnet'), 'deletedhostinfo'));
- $radioarray[] = MoodleQuickForm::createElement('radio', 'deleted', '', get_string('yes'), 1);
- $radioarray[] = MoodleQuickForm::createElement('radio', 'deleted', '', get_string('no'), 0);
+ $radioarray[] = $mform->createElement('radio', 'deleted', '', get_string('yes'), 1);
+ $radioarray[] = $mform->createElement('radio', 'deleted', '', get_string('no'), 0);
$mform->addGroup($radioarray, 'radioar', get_string('deleted'), array(' ', ' '), false);
} else {
$mform->addElement('hidden', 'deleted');
// security first
require_login($course, false, $cm);
+$safeoverridesonly = false;
if (!has_capability('moodle/role:override', $context)) {
require_capability('moodle/role:safeoverride', $context);
+ $safeoverridesonly = true;
}
$PAGE->set_url($url);
$PAGE->set_context($context);
}
// If we are actually overriding a role, create the table object, and save changes if appropriate.
-$overridestable = new override_permissions_table_advanced($context, $roleid, false);
+$overridestable = new override_permissions_table_advanced($context, $roleid, $safeoverridesonly);
$overridestable->read_submitted_permissions();
if (optional_param('savechanges', false, PARAM_BOOL) && confirm_sesskey()) {
$ADMIN->add('security', $temp);
- // "modulesecurity" settingpage
- $temp = new admin_settingpage('modulesecurity', new lang_string('modulesecurity', 'admin'));
- $temp->add(new admin_setting_configselect('restrictmodulesfor', new lang_string('restrictmodulesfor', 'admin'), new lang_string('configrestrictmodulesfor', 'admin'), 'none', array('none' => new lang_string('nocourses'),
- 'all' => new lang_string('fulllistofcourses'),
- 'requested' => new lang_string('requestedcourses'))));
- $temp->add(new admin_setting_configcheckbox('restrictbydefault', new lang_string('restrictbydefault', 'admin'), new lang_string('configrestrictbydefault', 'admin'), 0));
- $temp->add(new admin_setting_configmultiselect_modules('defaultallowedmodules',
- new lang_string('defaultallowedmodules', 'admin'),
- new lang_string('configdefaultallowedmodules', 'admin')));
- $ADMIN->add('security', $temp);
-
-
-
// "notifications" settingpage
$temp = new admin_settingpage('notifications', new lang_string('notifications', 'admin'));
$temp->add(new admin_setting_configselect('displayloginfailures', new lang_string('displayloginfailures', 'admin'), new lang_string('configdisplayloginfailures', 'admin'), '', array('' => new lang_string('nobody'),
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * PHPUnit related utilities.
+ *
+ * Exit codes:
+ * 0 - success
+ * 1 - general error
+ * 130 - coding error
+ * 131 - configuration problem
+ * 133 - drop existing data before installing
+ *
+ * @package tool_phpunit
+ * @copyright 2012 Petr Skoda {@link http://skodak.org}
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+define('PHPUNIT_CLI_UTIL', true);
+
+require(__DIR__ . '/../../../../lib/phpunit/bootstrap.php');
+require_once($CFG->libdir.'/phpunit/lib.php');
+require_once($CFG->libdir.'/adminlib.php');
+require_once($CFG->libdir.'/upgradelib.php');
+require_once($CFG->libdir.'/clilib.php');
+require_once($CFG->libdir.'/pluginlib.php');
+require_once($CFG->libdir.'/installlib.php');
+
+// now get cli options
+list($options, $unrecognized) = cli_get_params(
+ array(
+ 'drop' => false,
+ 'install' => false,
+ 'buildconfig' => false,
+ 'help' => false,
+ ),
+ array(
+ 'h' => 'help'
+ )
+);
+
+if ($unrecognized) {
+ $unrecognized = implode("\n ", $unrecognized);
+ cli_error(get_string('cliunknowoption', 'admin', $unrecognized));
+}
+
+$drop = $options['drop'];
+$install = $options['install'];
+$buildconfig = $options['buildconfig'];
+
+if ($options['help'] or (!$drop and !$install and !$buildconfig)) {
+ $help = "Various PHPUnit utility functions
+
+Options:
+--drop Drop database and dataroot
+--install Install database
+--buildconfig Build /phpunit.xml from /phpunit.xml.dist that includes suites for all plugins and core
+
+-h, --help Print out this help
+
+Example:
+\$/usr/bin/php lib/phpunit/tool.php
+";
+ echo $help;
+ die;
+}
+
+if ($buildconfig) {
+ phpunit_util::build_config_file();
+ exit(0);
+
+} else if ($drop) {
+ phpunit_util::drop_site();
+ // note: we must stop here because $CFG is messed up and we can not reinstall, sorry
+ exit(0);
+
+} else if ($install) {
+ phpunit_util::install_site();
+ exit(0);
+}
--- /dev/null
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * PHPUnit info
+ *
+ * @package tool_phpunit
+ * @copyright 2012 Petr Skoda {@link http://skodak.org}
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+define('NO_OUTPUT_BUFFERING', true);
+
+require(dirname(__FILE__) . '/../../../config.php');
+require_once($CFG->libdir.'/adminlib.php');
+
+admin_externalpage_setup('toolphpunit');
+
+echo $OUTPUT->header();
+echo $OUTPUT->heading(get_string('pluginname', 'tool_phpunit'));
+echo $OUTPUT->box_start();
+
+$info = file_get_contents("$CFG->libdir/phpunit/readme.md");
+echo markdown_to_html($info);
+
+echo $OUTPUT->box_end();
+echo $OUTPUT->footer();
\ No newline at end of file
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
- * Jabber message processor - lib file
+ * Strings for component 'tool_phpunit'
*
- * @package message_jabber
- * @copyright 2008 Luis Rodrigues
- * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
+ * @package tool_phpunit
+ * @copyright 2012 Petr Skoda {@link http://skodak.org}
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-/**
- * Register the processor.
- */
-function jabber_install(){
- global $DB;
-
- $result = true;
-
- $provider = new stdClass();
- $provider->name = 'jabber';
- $DB->insert_record('message_processors', $provider);
- return $result;
-}
+$string['pluginname'] = 'PHPUnit tests';
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
- * Email message processor library file
+ * PHPunit integration
*
- * @package message_email
- * @copyright 2008 Luis Rodrigues and Martin Dougiamas
+ * @package tool_phpunit
+ * @copyright 2012 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-/**
- * Register the processor
- */
-function email_install(){
- global $DB;
- $result = true;
- $provider = new stdClass();
- $provider->name = 'email';
- $DB->insert_record('message_processors', $provider);
- return $result;
-}
+defined('MOODLE_INTERNAL') || die;
+
+$ADMIN->add('development', new admin_externalpage('toolphpunit', get_string('pluginname', 'tool_phpunit'), "$CFG->wwwroot/$CFG->admin/tool/phpunit/index.php"));
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
- * Popup message processor - lib file
+ * Plugin version info
*
- * @package message_popup
- * @copyright 2008 Luis Rodrigues
- * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
+ * @package tool_phpunit
+ * @copyright 2012 Petr Skoda {@link http://skodak.org}
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-/**
- * Register the popup message processor
- */
-function popup_install(){
- global $DB;
-
- $result = true;
+defined('MOODLE_INTERNAL') || die();
- $provider = new stdClass();
- $provider->name = 'popup';
- $DB->insert_record('message_processors', $provider);
- return $result;
-}
+$plugin->version = 2012030800; // The current plugin version (Date: YYYYMMDDXX)
+$plugin->requires = 2012030100; // Requires this Moodle version
+$plugin->component = 'tool_phpunit'; // Full name of the plugin (used for diagnostics)
require(dirname(__FILE__) . '/../../../config.php');
require_once($CFG->libdir.'/adminlib.php');
+
+// unfortunately outdated SimpleTest is not E_STRICT compatible
+$CFG->debug = ($CFG->debug & ~E_STRICT);
+error_reporting($CFG->debug);
+
require_once('simpletestlib.php');
require_once('simpletestcoveragelib.php');
require_once('ex_simple_test.php');
require(dirname(__FILE__) . '/../../../config.php');
require_once($CFG->libdir.'/adminlib.php');
-require_once('simpletestlib.php');
-require_once('simpletestcoveragelib.php');
-require_once('ex_simple_test.php');
-require_once('ex_reporter.php');
// Always run the unit tests in developer debug mode.
-$CFG->debug = DEBUG_DEVELOPER;
+// unfortunately outdated SimpleTest is not E_STRICT compatible
+$CFG->debug = (DEBUG_DEVELOPER & ~E_STRICT);
error_reporting($CFG->debug);
raise_memory_limit(MEMORY_EXTRA);
+require_once('simpletestlib.php');
+require_once('simpletestcoveragelib.php');
+require_once('ex_simple_test.php');
+require_once('ex_reporter.php');
+
// page parameters
$path = optional_param('path', null, PARAM_PATH);
$showpasses = optional_param('showpasses', false, PARAM_BOOL);
var $sesskey_protected; // Actions must be protected by sesskey mechanism
- /**
- * Constructor
- */
- function XMLDBAction() {
- $this->init();
- }
-
/**
* Constructor to keep PHP5 happy
*/
function __construct() {
- $this->XMLDBAction();
+ $this->init();
}
/**
// Based on type, disable some items
switch (typeField.value) {
case '1': // XMLDB_TYPE_INTEGER
- lengthTip.innerHTML = ' 1...20';
+ lengthTip.innerHTML = ' 1...20'; // Hardcoded xmldb_field::INTEGER_MAX_LENGTH, yes!
lengthField.disabled = false;
decimalsTip.innerHTML = '';
decimalsField.disabled = true;
decimalsField.value = '';
break;
case '2': // XMLDB_TYPE_NUMBER
- lengthTip.innerHTML = ' 1...20';
+ lengthTip.innerHTML = ' 1...20'; // Hardcoded xmldb_field::NUMBER_MAX_LENGTH, yes!
lengthField.disabled = false;
decimalsTip.innerHTML = ' 0...length or empty';
break;
case '3': // XMLDB_TYPE_FLOAT
- lengthTip.innerHTML = ' 1...20 or empty';
+ lengthTip.innerHTML = ' 1...20 or empty'; // Hardcoded xmldb_field::FLOAT_MAX_LENGTH, yes!
lengthField.disabled = false;
decimalsTip.innerHTML = ' 0...length or empty';
break;
case '4': // XMLDB_TYPE_CHAR
- lengthTip.innerHTML = ' 1...1333'; // Hardcoded, yes!
+ lengthTip.innerHTML = ' 1...1333'; // Hardcoded xmldb_field::CHAR_MAX_LENGTH, yes!
lengthField.disabled = false;
decimalsTip.innerHTML = '';
decimalsField.disabled = true;
$tableparam = strtolower(required_param('table', PARAM_PATH));
$fieldparam = strtolower(required_param('field', PARAM_PATH));
- $name = substr(trim(strtolower(optional_param('name', $fieldparam, PARAM_PATH))),0,30);
+ $name = substr(trim(strtolower(optional_param('name', $fieldparam, PARAM_PATH))),0,xmldb_field::NAME_MAX_LENGTH);
$comment = required_param('comment', PARAM_CLEAN);
$comment = trim($comment);
// Integer checks
if ($type == XMLDB_TYPE_INTEGER) {
if (!(is_numeric($length) && !empty($length) && intval($length)==floatval($length) &&
- $length > 0 && $length <= 20)) {
+ $length > 0 && $length <= xmldb_field::INTEGER_MAX_LENGTH)) {
$errors[] = $this->str['integerincorrectlength'];
}
if (!(empty($default) || (is_numeric($default) &&
// Number checks
if ($type == XMLDB_TYPE_NUMBER) {
if (!(is_numeric($length) && !empty($length) && intval($length)==floatval($length) &&
- $length > 0 && $length <= 20)) {
+ $length > 0 && $length <= xmldb_field::NUMBER_MAX_LENGTH)) {
$errors[] = $this->str['numberincorrectlength'];
}
if (!(empty($decimals) || (is_numeric($decimals) &&
!empty($length) &&
intval($length)==floatval($length) &&
$length > 0 &&
- $length <= 20))) {
+ $length <= xmldb_field::FLOAT_MAX_LENGTH))) {
$errors[] = $this->str['floatincorrectlength'];
}
if (!(empty($decimals) || (is_numeric($decimals) &&
$dirpath = $CFG->dirroot . $dirpath;
$tableparam = strtolower(required_param('table', PARAM_PATH));
- $name = substr(trim(strtolower(required_param('name', PARAM_PATH))),0,28);
+ $name = substr(trim(strtolower(required_param('name', PARAM_PATH))),0,xmldb_table::NAME_MAX_LENGTH);
$comment = required_param('comment', PARAM_CLEAN);
$comment = $comment;
$mform->setType('id', PARAM_INT);
if (!empty($service->id)) {
- $buttonlabel = get_string('editaservice', 'webservice');
+ $buttonlabel = get_string('savechanges');
} else {
$buttonlabel = get_string('addaservice', 'webservice');
}
* @param object object with submitted configuration settings (without system magic quotes)
* @param array $err array of error messages
*/
- function validate_form(&$form, &$err) {
+ function validate_form($form, &$err) {
$certificate_path = trim($form->certificate_path);
if ($form->certificate_check && empty($certificate_path)) {
$err['certificate_path'] = get_string('auth_cas_certificate_path_empty', 'auth_cas');
$help .= '<hr />';
$help .= get_string('auth_updateremote_ldap', 'auth');
-print_auth_lock_options('cas', $user_fields, $help, true, true);
+print_auth_lock_options($this->authtype, $user_fields, $help, true, true);
?>
</table>
<?php
-print_auth_lock_options('db', $user_fields, get_string('auth_dbextrafields', 'auth_db'), true, true);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_dbextrafields', 'auth_db'), true, true);
?>
</table>
if ($user->confirmed) {
return AUTH_CONFIRM_ALREADY;
- } else if ($user->auth != 'email') {
+ } else if ($user->auth != $this->authtype) {
return AUTH_CONFIRM_ERROR;
} else if ($user->secret == $confirmsecret) { // They have provided the secret key to get in
</tr>
<?php
-print_auth_lock_options('email', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
</table>
<?php
-print_auth_lock_options('fc', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
</table>
<?php
-print_auth_lock_options('imap', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
</table>
$help .= '<hr />';
$help .= get_string('auth_updateremote_ldap', 'auth');
-print_auth_lock_options('ldap', $user_fields, $help, true, true);
+print_auth_lock_options($this->authtype, $user_fields, $help, true, true);
?>
</table>
<table cellspacing="0" cellpadding="5" border="0">
<?php
-print_auth_lock_options('manual', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
</table>
<?php
}
-// print_auth_lock_options('mnet', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+// print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
</table>
<?php
-print_auth_lock_options('nntp', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
</table>
<table cellspacing="0" cellpadding="5" border="0">
<?php
-print_auth_lock_options('none', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
</table>
<table cellspacing="0" cellpadding="5" border="0">
<?php
-print_auth_lock_options('pam', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
</table>
<?php
-print_auth_lock_options('pop3', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
+print_auth_lock_options($this->authtype, $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
</table>
<?php
-print_auth_lock_options('shibboleth', $user_fields, '<!-- empty help -->', true, false);
+print_auth_lock_options($this->authtype, $user_fields, '<!-- empty help -->', true, false);
?>
</table>
'visible', 'hiddensections', 'groupmode', 'groupmodeforce',
'defaultgroupingid', 'lang', 'theme',
'timecreated', 'timemodified',
- 'requested', 'restrictmodules',
+ 'requested',
'enablecompletion', 'completionstartonenrol', 'completionnotify'));
$category = new backup_nested_element('category', array('id'), array(
$tag = new backup_nested_element('tag', array('id'), array(
'name', 'rawname'));
- $allowedmodules = new backup_nested_element('allowed_modules');
-
- $module = new backup_nested_element('module', array(), array('modulename'));
-
// attach format plugin structure to $course element, only one allowed
$this->add_plugin_structure('format', $course, false);
$course->add_child($tags);
$tags->add_child($tag);
- $course->add_child($allowedmodules);
- $allowedmodules->add_child($module);
-
// Set the sources
$courserec = $DB->get_record('course', array('id' => $this->task->get_courseid()));
backup_helper::is_sqlparam('course'),
backup::VAR_PARENTID));
- $module->set_source_sql('SELECT m.name AS modulename
- FROM {modules} m
- JOIN {course_allowed_modules} cam ON m.id = cam.module
- WHERE course = ?', array(backup::VAR_COURSEID));
-
// Some annotations
$course->annotate_ids('grouping', 'defaultgroupingid');
* the course record (never inserting)
*/
class restore_course_structure_step extends restore_structure_step {
+ /**
+ * @var bool this gets set to true by {@link process_course()} if we are
+ * restoring an old coures that used the legacy 'module security' feature.
+ * If so, we have to do more work in {@link after_execute()}.
+ */
+ protected $legacyrestrictmodules = false;
+
+ /**
+ * @var array Used when {@link $legacyrestrictmodules} is true. This is an
+ * array with array keys the module names ('forum', 'quiz', etc.). These are
+ * the modules that are allowed according to the data in the backup file.
+ * In {@link after_execute()} we then have to prevent adding of all the other
+ * types of activity.
+ */
+ protected $legacyallowedmodules = array();
protected function define_structure() {
$data->hiddensections = 0;
}
- // Only restrict modules if original course was and target site too for new courses
- $data->restrictmodules = $data->restrictmodules && !empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all';
+ // Set legacyrestrictmodules to true if the course was resticting modules. If so
+ // then we will need to process restricted modules after execution.
+ $this->legacyrestrictmodules = !empty($data->restrictmodules);
$data->startdate= $this->apply_date_offset($data->startdate);
if ($data->defaultgroupingid) {
}
public function process_allowed_module($data) {
- global $CFG, $DB;
-
$data = (object)$data;
- // only if enabled by admin setting
- if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor == 'all') {
- $available = get_plugin_list('mod');
- $mname = $data->modulename;
- if (array_key_exists($mname, $available)) {
- if ($module = $DB->get_record('modules', array('name' => $mname, 'visible' => 1))) {
- $rec = new stdclass();
- $rec->course = $this->get_courseid();
- $rec->module = $module->id;
- if (!$DB->record_exists('course_allowed_modules', (array)$rec)) {
- $DB->insert_record('course_allowed_modules', $rec);
- }
- }
- }
+ // Backwards compatiblity support for the data that used to be in the
+ // course_allowed_modules table.
+ if ($this->legacyrestrictmodules) {
+ $this->legacyallowedmodules[$data->modulename] = 1;
}
}
protected function after_execute() {
+ global $DB;
+
// Add course related files, without itemid to match
$this->add_related_files('course', 'summary', null);
$this->add_related_files('course', 'legacy', null);
+
+ // Deal with legacy allowed modules.
+ if ($this->legacyrestrictmodules) {
+ $context = context_course::instance($this->get_courseid());
+
+ list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
+ list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
+ foreach ($managerroleids as $roleid) {
+ unset($roleids[$roleid]);
+ }
+
+ foreach (get_plugin_list('mod') as $modname => $notused) {
+ if (isset($this->legacyallowedmodules[$modname])) {
+ // Module is allowed, no worries.
+ continue;
+ }
+
+ $capability = 'mod/' . $modname . ':addinstance';
+ foreach ($roleids as $roleid) {
+ assign_capability($capability, CAP_PREVENT, $roleid, $context);
+ }
+ }
+ }
}
}
return $this->content;
}
- $glossaryid = $this->config->glossary;
-
- $course = $this->page->course;
-
require_once($CFG->dirroot.'/course/lib.php');
+ $course = $this->page->course;
$modinfo = get_fast_modinfo($course);
+ $glossaryid = $this->config->glossary;
+ $cm = $modinfo->instances['glossary'][$glossaryid];
+
+ if (!has_capability('mod/glossary:view', get_context_instance(CONTEXT_MODULE, $cm->id))) {
+ return '';
+ }
if (!isset($modinfo->instances['glossary'][$glossaryid])) {
// we can get here if the glossary has been deleted, so
return $this->content;
}
- $cm = $modinfo->instances['glossary'][$glossaryid];
-
if (empty($this->config->cache)) {
$this->config->cache = '';
}
return $cm->instance;
}
- function instance_config_save($data) {
+ function instance_config_save($data, $nolongerused = false) {
if (empty($data->quizid)) {
$data->quizid = $this->get_owning_quiz();
}
if ($events !== false) {
- $modinfo =& get_fast_modinfo($COURSE);
+ $modinfo = get_fast_modinfo($COURSE);
foreach($events as $event) {
$table = new html_table();
$table->attributes = array('class'=>'calendarmonth calendartable');
+ $time = make_timestamp($calendar->year, $calendar->month);
+ $table->summary = get_string('calendarheading', 'calendar', userdate($time, get_string('strftimemonthyear')));
$table->data = array();
$header = new html_table_row();
$c->format = $u->cformat;
$c->timecreated = $u->ctimecreated;
$url = new moodle_url('/user/view.php', array('id'=>$u->id, 'course'=>$this->courseid));
- $c->profileurl = $url->out();
+ $c->profileurl = $url->out(false);
$c->fullname = fullname($u);
$c->time = userdate($c->timecreated, get_string('strftimerecent', 'langconfig'));
$c->content = format_text($c->content, $c->format, $formatoptions);
// $CFG->tempdir = '/var/www/moodle/temp';
// $CFG->cachedir = '/var/www/moodle/cache';
//
+// Some filesystems such as NFS may not support file locking operations.
+// Locking resolves race conditions and is strongly recommended for production servers.
+// $CFG->preventfilelocking = false;
+//
// If $CFG->langstringcache is enabled (which should always be in production
// environment), Moodle keeps aggregated strings in its own internal format
// optimised for performance. By default, this on-disk cache is created in
// Example:
// $CFG->forced_plugin_settings = array('pluginname' => array('settingname' => 'value', 'secondsetting' => 'othervalue'),
// 'otherplugin' => array('mysetting' => 'myvalue', 'thesetting' => 'thevalue'));
-
+//
+//=========================================================================
+// 9. PHPUNIT SUPPORT
+//=========================================================================
+// $CFG->phpunit_prefix = 'phpu_';
+// $CFG->phpunit_dataroot = '/home/example/phpu_moodledata';
+// $CFG->phpunit_directorypermissions = 02777; // optional
//=========================================================================
// ALL DONE! To continue installation, visit your main page with a browser
<?php
- // Displays the top level category or all courses
- // In editing mode, allows the admin to edit a category,
- // and rearrange courses
-
- require_once("../config.php");
- require_once("lib.php");
-
- $id = required_param('id', PARAM_INT); // Category id
- $page = optional_param('page', 0, PARAM_INT); // which page to show
- $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT); // how many per page
- $categoryedit = optional_param('categoryedit', -1, PARAM_BOOL);
- $hide = optional_param('hide', 0, PARAM_INT);
- $show = optional_param('show', 0, PARAM_INT);
- $moveup = optional_param('moveup', 0, PARAM_INT);
- $movedown = optional_param('movedown', 0, PARAM_INT);
- $moveto = optional_param('moveto', 0, PARAM_INT);
- $resort = optional_param('resort', 0, PARAM_BOOL);
-
- $site = get_site();
-
- if (empty($id)) {
- print_error("unknowcategory");
- }
-
- $PAGE->set_category_by_id($id);
- $urlparams = array('id' => $id);
- if ($page) {
- $urlparams['page'] = $page;
- }
- if ($perpage) {
- $urlparams['perpage'] = $perpage;
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Displays the top level category or all courses
+ * In editing mode, allows the admin to edit a category,
+ * and rearrange courses
+ *
+ * @package core
+ * @subpackage course
+ * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+require_once("../config.php");
+require_once($CFG->dirroot.'/course/lib.php');
+
+$id = required_param('id', PARAM_INT); // Category id
+$page = optional_param('page', 0, PARAM_INT); // which page to show
+$perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT); // how many per page
+$categoryedit = optional_param('categoryedit', -1, PARAM_BOOL);
+$hide = optional_param('hide', 0, PARAM_INT);
+$show = optional_param('show', 0, PARAM_INT);
+$moveup = optional_param('moveup', 0, PARAM_INT);
+$movedown = optional_param('movedown', 0, PARAM_INT);
+$moveto = optional_param('moveto', 0, PARAM_INT);
+$resort = optional_param('resort', 0, PARAM_BOOL);
+$sesskey = optional_param('sesskey', '', PARAM_RAW);
+
+if (empty($id)) {
+ print_error("unknowcategory");
+}
+
+$PAGE->set_category_by_id($id);
+$PAGE->set_url(new moodle_url('/course/category.php', array('id' => $id)));
+// This is sure to be the category context
+$context = $PAGE->context;
+// And the object has been loaded for us no need for another DB call
+$category = $PAGE->category;
+
+$canedit = can_edit_in_category($category->id);
+if ($canedit) {
+ if ($categoryedit !== -1) {
+ $USER->editing = $categoryedit;
}
- $PAGE->set_url(new moodle_url('/course/category.php', array('id' => $id)));
- navigation_node::override_active_url($PAGE->url);
- $context = $PAGE->context;
- $category = $PAGE->category;
-
- $canedit = can_edit_in_category($category->id);
- if ($canedit) {
- if ($categoryedit !== -1) {
- $USER->editing = $categoryedit;
- }
+ require_login();
+ $editingon = $PAGE->user_is_editing();
+} else {
+ if ($CFG->forcelogin) {
require_login();
- $editingon = $PAGE->user_is_editing();
- } else {
- if ($CFG->forcelogin) {
- require_login();
+ }
+ $editingon = false;
+}
+
+if (!$category->visible) {
+ require_capability('moodle/category:viewhiddencategories', $context);
+}
+
+$canmanage = has_capability('moodle/category:manage', $context);
+$sesskeyprovided = !empty($sesskey) && confirm_sesskey($sesskey);
+
+// Process any category actions.
+if ($canmanage && $resort && $sesskeyprovided) {
+ // Resort the category if requested
+ if ($courses = get_courses($category->id, "fullname ASC", 'c.id,c.fullname,c.sortorder')) {
+ $i = 1;
+ foreach ($courses as $course) {
+ $DB->set_field('course', 'sortorder', $category->sortorder+$i, array('id'=>$course->id));
+ $i++;
}
- $editingon = false;
+ fix_course_sortorder(); // should not be needed
}
+}
- if (!$category->visible) {
- require_capability('moodle/category:viewhiddencategories', $context);
- }
+// Process any course actions.
+if ($editingon && $sesskeyprovided) {
- // Process any category actions.
- if (has_capability('moodle/category:manage', $context)) {
- /// Resort the category if requested
- if ($resort and confirm_sesskey()) {
- if ($courses = get_courses($category->id, "fullname ASC", 'c.id,c.fullname,c.sortorder')) {
- $i = 1;
- foreach ($courses as $course) {
- $DB->set_field('course', 'sortorder', $category->sortorder+$i, array('id'=>$course->id));
- $i++;
- }
- fix_course_sortorder(); // should not be needed
- }
+ // Move a specified course to a new category
+ if (!empty($moveto) and $data = data_submitted()) {
+ // Some courses are being moved
+ // user must have category update in both cats to perform this
+ require_capability('moodle/category:manage', $context);
+ require_capability('moodle/category:manage', get_context_instance(CONTEXT_COURSECAT, $moveto));
+
+ if (!$destcategory = $DB->get_record('course_categories', array('id' => $data->moveto))) {
+ print_error('cannotfindcategory', '', '', $data->moveto);
}
- }
- // Process any course actions.
- if ($editingon) {
- /// Move a specified course to a new category
- if (!empty($moveto) and $data = data_submitted() and confirm_sesskey()) { // Some courses are being moved
- // user must have category update in both cats to perform this
- require_capability('moodle/category:manage', $context);
- require_capability('moodle/category:manage', get_context_instance(CONTEXT_COURSECAT, $moveto));
-
- if (!$destcategory = $DB->get_record('course_categories', array('id' => $data->moveto))) {
- print_error('cannotfindcategory', '', '', $data->moveto);
- }
+ $courses = array();
+ foreach ($data as $key => $value) {
+ if (preg_match('/^c\d+$/', $key)) {
+ $courseid = substr($key, 1);
+ array_push($courses, $courseid);
- $courses = array();
- foreach ($data as $key => $value) {
- if (preg_match('/^c\d+$/', $key)) {
- $courseid = substr($key, 1);
- array_push($courses, $courseid);
-
- // check this course's category
- if ($movingcourse = $DB->get_record('course', array('id'=>$courseid))) {
- if ($movingcourse->category != $id ) {
- print_error('coursedoesnotbelongtocategory');
- }
- } else {
- print_error('cannotfindcourse');
+ // check this course's category
+ if ($movingcourse = $DB->get_record('course', array('id'=>$courseid))) {
+ if ($movingcourse->category != $id ) {
+ print_error('coursedoesnotbelongtocategory');
}
+ } else {
+ print_error('cannotfindcourse');
}
}
- move_courses($courses, $data->moveto);
}
+ move_courses($courses, $data->moveto);
+ }
- /// Hide or show a course
- if ((!empty($hide) or !empty($show)) and confirm_sesskey()) {
- if (!empty($hide)) {
- $course = $DB->get_record('course', array('id' => $hide));
- $visible = 0;
- } else {
- $course = $DB->get_record('course', array('id' => $show));
- $visible = 1;
- }
+ // Hide or show a course
+ if (!empty($hide) or !empty($show)) {
+ if (!empty($hide)) {
+ $course = $DB->get_record('course', array('id' => $hide));
+ $visible = 0;
+ } else {
+ $course = $DB->get_record('course', array('id' => $show));
+ $visible = 1;
+ }
- if ($course) {
- $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
- require_capability('moodle/course:visibility', $coursecontext);
- $DB->set_field('course', 'visible', $visible, array('id' => $course->id));
- $DB->set_field('course', 'visibleold', $visible, array('id' => $course->id)); // we set the old flag when user manually changes visibility of course
- }
+ if ($course) {
+ $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
+ require_capability('moodle/course:visibility', $coursecontext);
+ // Set the visibility of the course
+ $DB->set_field('course', 'visible', $visible, array('id' => $course->id));
+ // we set the old flag when user manually changes visibility of course
+ $DB->set_field('course', 'visibleold', $visible, array('id' => $course->id));
}
+ }
- /// Move a course up or down
- if ((!empty($moveup) or !empty($movedown)) and confirm_sesskey()) {
- require_capability('moodle/category:manage', $context);
+ // Move a course up or down
+ if (!empty($moveup) or !empty($movedown)) {
+ require_capability('moodle/category:manage', $context);
- // Ensure the course order has continuous ordering
- fix_course_sortorder();
- $swapcourse = NULL;
+ // Ensure the course order has continuous ordering
+ fix_course_sortorder();
+ $swapcourse = NULL;
- if (!empty($moveup)) {
- if ($movecourse = $DB->get_record('course', array('id' => $moveup))) {
- $swapcourse = $DB->get_record('course', array('sortorder' => $movecourse->sortorder - 1));
- }
- } else {
- if ($movecourse = $DB->get_record('course', array('id' => $movedown))) {
- $swapcourse = $DB->get_record('course', array('sortorder' => $movecourse->sortorder + 1));
- }
+ if (!empty($moveup)) {
+ if ($movecourse = $DB->get_record('course', array('id' => $moveup))) {
+ $swapcourse = $DB->get_record('course', array('sortorder' => $movecourse->sortorder - 1));
}
- if ($swapcourse and $movecourse) {
- // check course's category
- if ($movecourse->category != $id) {
- print_error('coursedoesnotbelongtocategory');
- }
- $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $movecourse->id));
- $DB->set_field('course', 'sortorder', $movecourse->sortorder, array('id' => $swapcourse->id));
+ } else {
+ if ($movecourse = $DB->get_record('course', array('id' => $movedown))) {
+ $swapcourse = $DB->get_record('course', array('sortorder' => $movecourse->sortorder + 1));
}
}
-
- } // End of editing stuff
-
- // Print headings
- $numcategories = $DB->count_records('course_categories');
-
- $stradministration = get_string('administration');
- $strcategories = get_string('categories');
- $strcategory = get_string('category');
- $strcourses = get_string('courses');
-
- if ($editingon && can_edit_in_category()) {
- // Integrate into the admin tree only if the user can edit categories at the top level,
- // otherwise the admin block does not appear to this user, and you get an error.
- require_once($CFG->libdir . '/adminlib.php');
- admin_externalpage_setup('coursemgmt', '', $urlparams, $CFG->wwwroot . '/course/category.php');
- $PAGE->set_context($context); // Ensure that we are actually showing blocks etc for the cat context
-
- $settingsnode = $PAGE->settingsnav->find_active_node();
- if ($settingsnode) {
- $settingsnode->make_inactive();
- $settingsnode->force_open();
- $PAGE->navbar->add($settingsnode->text, $settingsnode->action);
+ if ($swapcourse and $movecourse) {
+ // check course's category
+ if ($movecourse->category != $id) {
+ print_error('coursedoesnotbelongtocategory');
+ }
+ $DB->set_field('course', 'sortorder', $swapcourse->sortorder, array('id' => $movecourse->id));
+ $DB->set_field('course', 'sortorder', $movecourse->sortorder, array('id' => $swapcourse->id));
}
- echo $OUTPUT->header();
- } else {
- $PAGE->set_title("$site->shortname: $category->name");
- $PAGE->set_heading($site->fullname);
- $PAGE->set_button(print_course_search('', true, 'navbar'));
- $PAGE->set_pagelayout('coursecategory');
- echo $OUTPUT->header();
}
+} // End of editing stuff
+
+// Prepare the standard URL params for this page. We'll need them later.
+$urlparams = array('id' => $id);
+if ($page) {
+ $urlparams['page'] = $page;
+}
+if ($perpage) {
+ $urlparams['perpage'] = $perpage;
+}
+
+// Begin output
+if ($editingon && can_edit_in_category()) {
+ // Integrate into the admin tree only if the user can edit categories at the top level,
+ // otherwise the admin block does not appear to this user, and you get an error.
+ require_once($CFG->libdir . '/adminlib.php');
+ admin_externalpage_setup('coursemgmt', '', $urlparams, $CFG->wwwroot . '/course/category.php');
+ $PAGE->set_context($context); // Ensure that we are actually showing blocks etc for the cat context
+
+ $settingsnode = $PAGE->settingsnav->find_active_node();
+ if ($settingsnode) {
+ $settingsnode->make_inactive();
+ $settingsnode->force_open();
+ $PAGE->navbar->add($settingsnode->text, $settingsnode->action);
+ }
+ echo $OUTPUT->header();
+} else {
+ $site = get_site();
+ $PAGE->set_title("$site->shortname: $category->name");
+ $PAGE->set_heading($site->fullname);
+ $PAGE->set_button(print_course_search('', true, 'navbar'));
+ $PAGE->set_pagelayout('coursecategory');
+ echo $OUTPUT->header();
+}
+
/// Print the category selector
- $displaylist = array();
- $notused = array();
- make_categories_list($displaylist, $notused);
+$displaylist = array();
+$notused = array();
+make_categories_list($displaylist, $notused);
- echo '<div class="categorypicker">';
- $select = new single_select(new moodle_url('category.php'), 'id', $displaylist, $category->id, null, 'switchcategory');
- $select->set_label($strcategories.':');
- echo $OUTPUT->render($select);
- echo '</div>';
+echo '<div class="categorypicker">';
+$select = new single_select(new moodle_url('/course/category.php'), 'id', $displaylist, $category->id, null, 'switchcategory');
+$select->set_label(get_string('categories').':');
+echo $OUTPUT->render($select);
+echo '</div>';
/// Print current category description
- if (!$editingon && $category->description) {
- echo $OUTPUT->box_start();
- $options = new stdClass;
- $options->noclean = true;
- $options->para = false;
- $options->overflowdiv = true;
- if (!isset($category->descriptionformat)) {
- $category->descriptionformat = FORMAT_MOODLE;
- }
- $text = file_rewrite_pluginfile_urls($category->description, 'pluginfile.php', $context->id, 'coursecat', 'description', null);
- echo format_text($text, $category->descriptionformat, $options);
- echo $OUTPUT->box_end();
+if (!$editingon && $category->description) {
+ echo $OUTPUT->box_start();
+ $options = new stdClass;
+ $options->noclean = true;
+ $options->para = false;
+ $options->overflowdiv = true;
+ if (!isset($category->descriptionformat)) {
+ $category->descriptionformat = FORMAT_MOODLE;
}
-
- if ($editingon && has_capability('moodle/category:manage', $context)) {
- echo $OUTPUT->container_start('buttons');
-
- // Print button to update this category
- $options = array('id' => $category->id);
- echo $OUTPUT->single_button(new moodle_url('/course/editcategory.php', $options), get_string('editcategorythis'), 'get');
-
- // Print button for creating new categories
- $options = array('parent' => $category->id);
- echo $OUTPUT->single_button(new moodle_url('/course/editcategory.php', $options), get_string('addsubcategory'), 'get');
-
- echo $OUTPUT->container_end();
+ $text = file_rewrite_pluginfile_urls($category->description, 'pluginfile.php', $context->id, 'coursecat', 'description', null);
+ echo format_text($text, $category->descriptionformat, $options);
+ echo $OUTPUT->box_end();
+}
+
+if ($editingon && $canmanage) {
+ echo $OUTPUT->container_start('buttons');
+
+ // Print button to update this category
+ $url = new moodle_url('/course/editcategory.php', array('id' => $category->id));
+ echo $OUTPUT->single_button($url, get_string('editcategorythis'), 'get');
+
+ // Print button for creating new categories
+ $url = new moodle_url('/course/editcategory.php', array('parent' => $category->id));
+ echo $OUTPUT->single_button($url, get_string('addsubcategory'), 'get');
+
+ echo $OUTPUT->container_end();
+}
+
+// Print out all the sub-categories
+// In order to view hidden subcategories the user must have the viewhiddencategories
+// capability in the current category.
+if (has_capability('moodle/category:viewhiddencategories', $context)) {
+ $categorywhere = '';
+} else {
+ $categorywhere = 'AND cc.visible = 1';
+}
+// We're going to preload the context for the subcategory as we know that we
+// need it later on for formatting.
+
+$ctxselect = context_helper::get_preload_record_columns_sql('ctx');
+$sql = "SELECT cc.*, $ctxselect
+ FROM {course_categories} cc
+ JOIN {context} ctx ON cc.id = ctx.instanceid
+ WHERE cc.parent = :parentid AND
+ ctx.contextlevel = :contextlevel
+ $categorywhere
+ ORDER BY cc.sortorder ASC";
+$subcategories = $DB->get_recordset_sql($sql, array('parentid' => $category->id, 'contextlevel' => CONTEXT_COURSECAT));
+// Prepare a table to display the sub categories.
+$table = new html_table;
+$table->attributes = array('border' => '0', 'cellspacing' => '2', 'cellpadding' => '4', 'class' => 'generalbox boxaligncenter category_subcategories');
+$table->head = array(new lang_string('subcategories'));
+$table->data = array();
+$baseurl = new moodle_url('/course/category.php');
+foreach ($subcategories as $subcategory) {
+ // Preload the context we will need it to format the category name shortly.
+ context_helper::preload_from_record($subcategory);
+ $context = get_context_instance(CONTEXT_COURSECAT, $subcategory->id);
+ // Prepare the things we need to create a link to the subcategory
+ $attributes = $subcategory->visible ? array() : array('class' => 'dimmed');
+ $text = format_string($subcategory->name, true, array('context' => $context));
+ // Add the subcategory to the table
+ $baseurl->param('id', $subcategory->id);
+ $table->data[] = array(html_writer::link($baseurl, $text, $attributes));
+}
+
+$subcategorieswereshown = (count($table->data) > 0);
+if ($subcategorieswereshown) {
+ echo html_writer::table($table);
+}
+
+// Print out all the courses
+$courses = get_courses_page($category->id, 'c.sortorder ASC',
+ 'c.id,c.sortorder,c.shortname,c.fullname,c.summary,c.visible',
+ $totalcount, $page*$perpage, $perpage);
+$numcourses = count($courses);
+
+if (!$courses) {
+ if (empty($subcategorieswereshown)) {
+ echo $OUTPUT->heading(get_string("nocoursesyet"));
}
-/// Print out all the sub-categories
- if ($subcategories = $DB->get_records('course_categories', array('parent' => $category->id), 'sortorder ASC')) {
- $firstentry = true;
- foreach ($subcategories as $subcategory) {
- if ($subcategory->visible || has_capability('moodle/category:viewhiddencategories', $context)) {
- $subcategorieswereshown = true;
- if ($firstentry) {
- echo '<table border="0" cellspacing="2" cellpadding="4" class="generalbox boxaligncenter">';
- echo '<tr><th scope="col">'.get_string('subcategories').'</th></tr>';
- echo '<tr><td style="white-space: nowrap">';
- $firstentry = false;
- }
- $catlinkcss = $subcategory->visible ? '' : ' class="dimmed" ';
- echo '<a '.$catlinkcss.' href="category.php?id='.$subcategory->id.'">'.
- format_string($subcategory->name, true, array('context' => get_context_instance(CONTEXT_COURSECAT, $subcategory->id))).'</a><br />';
- }
- }
- if (!$firstentry) {
- echo '</td></tr></table>';
- echo '<br />';
- }
- }
+} else if ($numcourses <= COURSE_MAX_SUMMARIES_PER_PAGE and !$page and !$editingon) {
+ echo $OUTPUT->box_start('courseboxes');
+ print_courses($category);
+ echo $OUTPUT->box_end();
-/// Print out all the courses
- $courses = get_courses_page($category->id, 'c.sortorder ASC',
- 'c.id,c.sortorder,c.shortname,c.fullname,c.summary,c.visible',
- $totalcount, $page*$perpage, $perpage);
- $numcourses = count($courses);
+} else {
+ echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "/course/category.php?id=$category->id&perpage=$perpage");
- if (!$courses) {
- if (empty($subcategorieswereshown)) {
- echo $OUTPUT->heading(get_string("nocoursesyet"));
- }
+ echo '<form id="movecourses" action="category.php" method="post"><div>';
+ echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
+ echo '<table border="0" cellspacing="2" cellpadding="4" class="generalbox boxaligncenter"><tr>';
+ echo '<th class="header" scope="col">'.get_string('courses').'</th>';
+ if ($editingon) {
+ echo '<th class="header" scope="col">'.get_string('edit').'</th>';
+ echo '<th class="header" scope="col">'.get_string('select').'</th>';
+ } else {
+ echo '<th class="header" scope="col"> </th>';
+ }
+ echo '</tr>';
- } else if ($numcourses <= COURSE_MAX_SUMMARIES_PER_PAGE and !$page and !$editingon) {
- echo $OUTPUT->box_start('courseboxes');
- print_courses($category);
- echo $OUTPUT->box_end();
+ $count = 0;
+ $abletomovecourses = false; // for now
- } else {
- echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "/course/category.php?id=$category->id&perpage=$perpage");
-
- $strcourses = get_string('courses');
- $strselect = get_string('select');
- $stredit = get_string('edit');
- $strdelete = get_string('delete');
- $strbackup = get_string('backup');
- $strrestore = get_string('restore');
- $strmoveup = get_string('moveup');
- $strmovedown = get_string('movedown');
- $strupdate = get_string('update');
- $strhide = get_string('hide');
- $strshow = get_string('show');
- $strsummary = get_string('summary');
- $strsettings = get_string('settings');
-
-
- echo '<form id="movecourses" action="category.php" method="post"><div>';
- echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
- echo '<table border="0" cellspacing="2" cellpadding="4" class="generalbox boxaligncenter"><tr>';
- echo '<th class="header" scope="col">'.$strcourses.'</th>';
- if ($editingon) {
- echo '<th class="header" scope="col">'.$stredit.'</th>';
- echo '<th class="header" scope="col">'.$strselect.'</th>';
+ // Checking if we are at the first or at the last page, to allow courses to
+ // be moved up and down beyond the paging border
+ if ($totalcount > $perpage) {
+ $atfirstpage = ($page == 0);
+ if ($perpage > 0) {
+ $atlastpage = (($page + 1) == ceil($totalcount / $perpage));
} else {
- echo '<th class="header" scope="col"> </th>';
+ $atlastpage = true;
}
- echo '</tr>';
+ } else {
+ $atfirstpage = true;
+ $atlastpage = true;
+ }
+ $baseurl = new moodle_url('/course/category.php', $urlparams + array('sesskey' => sesskey()));
+ foreach ($courses as $acourse) {
+ $coursecontext = get_context_instance(CONTEXT_COURSE, $acourse->id);
- $count = 0;
- $abletomovecourses = false; // for now
+ $count++;
+ $up = ($count > 1 || !$atfirstpage);
+ $down = ($count < $numcourses || !$atlastpage);
- // Checking if we are at the first or at the last page, to allow courses to
- // be moved up and down beyond the paging border
- if ($totalcount > $perpage) {
- $atfirstpage = ($page == 0);
- if ($perpage > 0) {
- $atlastpage = (($page + 1) == ceil($totalcount / $perpage));
- } else {
- $atlastpage = true;
+ $linkcss = $acourse->visible ? '' : ' class="dimmed" ';
+ echo '<tr>';
+ $coursename = get_course_display_name_for_list($acourse);
+ echo '<td><a '.$linkcss.' href="view.php?id='.$acourse->id.'">'. format_string($coursename) .'</a></td>';
+ if ($editingon) {
+ echo '<td>';
+ if (has_capability('moodle/course:update', $coursecontext)) {
+ $url = new moodle_url('/course/edit.php', array('id' => $acourse->id, 'category' => $id, 'returnto' => 'category'));
+ echo $OUTPUT->action_icon($url, new pix_icon('t/edit', get_string('settings')));
}
- } else {
- $atfirstpage = true;
- $atlastpage = true;
- }
- foreach ($courses as $acourse) {
- $coursecontext = get_context_instance(CONTEXT_COURSE, $acourse->id);
-
- $count++;
- $up = ($count > 1 || !$atfirstpage);
- $down = ($count < $numcourses || !$atlastpage);
-
- $linkcss = $acourse->visible ? '' : ' class="dimmed" ';
- echo '<tr>';
- $coursename = get_course_display_name_for_list($acourse);
- echo '<td><a '.$linkcss.' href="view.php?id='.$acourse->id.'">'. format_string($coursename) .'</a></td>';
- if ($editingon) {
- echo '<td>';
- if (has_capability('moodle/course:update', $coursecontext)) {
- echo $OUTPUT->action_icon(new moodle_url('/course/edit.php',
- array('id' => $acourse->id, 'category' => $id, 'returnto' => 'category')),
- new pix_icon('t/edit', $strsettings));
- }
+ // role assignment link
+ if (has_capability('moodle/course:enrolreview', $coursecontext)) {
+ $url = new moodle_url('/enrol/users.php', array('id' => $acourse->id));
+ echo $OUTPUT->action_icon($url, new pix_icon('i/users', get_string('enrolledusers', 'enrol')));
+ }
- // role assignment link
- if (has_capability('moodle/course:enrolreview', $coursecontext)) {
- echo $OUTPUT->action_icon(new moodle_url('/enrol/users.php', array('id' => $acourse->id)),
- new pix_icon('i/users', get_string('enrolledusers', 'enrol')));
- }
+ if (can_delete_course($acourse->id)) {
+ $url = new moodle_url('/course/delete.php', array('id' => $acourse->id));
+ echo $OUTPUT->action_icon($url, new pix_icon('t/delete', get_string('delete')));
+ }
- if (can_delete_course($acourse->id)) {
- echo $OUTPUT->action_icon(new moodle_url('/course/delete.php', array('id' => $acourse->id)),
- new pix_icon('t/delete', $strdelete));
+ // MDL-8885, users with no capability to view hidden courses, should not be able to lock themselves out
+ if (has_capability('moodle/course:visibility', $coursecontext) && has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
+ if (!empty($acourse->visible)) {
+ $url = new moodle_url($baseurl, array('hide' => $acourse->id));
+ echo $OUTPUT->action_icon($url, new pix_icon('t/hide', get_string('hide')));
+ } else {
+ $url = new moodle_url($baseurl, array('show' => $acourse->id));
+ echo $OUTPUT->action_icon($url, new pix_icon('t/show', get_string('show')));
}
+ }
- // MDL-8885, users with no capability to view hidden courses, should not be able to lock themselves out
- if (has_capability('moodle/course:visibility', $coursecontext) && has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
- if (!empty($acourse->visible)) {
- echo $OUTPUT->action_icon(new moodle_url('/course/category.php',
- array('id' => $category->id, 'page' => $page, 'perpage' => $perpage,
- 'hide' => $acourse->id, 'sesskey' => sesskey())),
- new pix_icon('t/hide', $strhide));
- } else {
- echo $OUTPUT->action_icon(new moodle_url('/course/category.php',
- array('id' => $category->id, 'page' => $page, 'perpage' => $perpage,
- 'show' => $acourse->id, 'sesskey' => sesskey())),
- new pix_icon('t/show', $strshow));
- }
- }
+ if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
+ $url = new moodle_url('/backup/backup.php', array('id' => $acourse->id));
+ echo $OUTPUT->action_icon($url, new pix_icon('t/backup', get_string('backup')));
+ }
- if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
- echo $OUTPUT->action_icon(new moodle_url('/backup/backup.php', array('id' => $acourse->id)),
- new pix_icon('t/backup', $strbackup));
- }
+ if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
+ $url = new moodle_url('/backup/restorefile.php', array('contextid' => $coursecontext->id));
+ echo $OUTPUT->action_icon($url, new pix_icon('t/restore', get_string('restore')));
+ }
- if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
- echo $OUTPUT->action_icon(new moodle_url('/backup/restorefile.php', array('contextid' => $coursecontext->id)),
- new pix_icon('t/restore', $strrestore));
+ if ($canmanage) {
+ if ($up) {
+ $url = new moodle_url($baseurl, array('moveup' => $acourse->id));
+ echo $OUTPUT->action_icon($url, new pix_icon('t/up', get_string('moveup')));
}
- if (has_capability('moodle/category:manage', $context)) {
- if ($up) {
- echo $OUTPUT->action_icon(new moodle_url('/course/category.php',
- array('id' => $category->id, 'page' => $page, 'perpage' => $perpage,
- 'moveup' => $acourse->id, 'sesskey' => sesskey())),
- new pix_icon('t/up', $strmoveup));
- }
-
- if ($down) {
- echo $OUTPUT->action_icon(new moodle_url('/course/category.php',
- array('id' => $category->id, 'page' => $page, 'perpage' => $perpage,
- 'movedown' => $acourse->id, 'sesskey' => sesskey())),
- new pix_icon('t/down', $strmovedown));
- }
- $abletomovecourses = true;
+ if ($down) {
+ $url = new moodle_url($baseurl, array('movedown' => $acourse->id));
+ echo $OUTPUT->action_icon($url, new pix_icon('t/down', get_string('movedown')));
}
+ $abletomovecourses = true;
+ }
- echo '</td>';
- echo '<td align="center">';
- echo '<input type="checkbox" name="c'.$acourse->id.'" />';
- echo '</td>';
- } else {
- echo '<td align="right">';
- // print enrol info
- if ($icons = enrol_get_course_info_icons($acourse)) {
- foreach ($icons as $pix_icon) {
- echo $OUTPUT->render($pix_icon);
- }
- }
- if (!empty($acourse->summary)) {
- $link = new moodle_url("/course/info.php?id=$acourse->id");
- echo $OUTPUT->action_link($link, '<img alt="'.get_string('info').'" class="icon" src="'.$OUTPUT->pix_url('i/info') . '" />',
- new popup_action('click', $link, 'courseinfo'), array('title'=>$strsummary));
+ echo '</td>';
+ echo '<td align="center">';
+ echo '<input type="checkbox" name="c'.$acourse->id.'" />';
+ echo '</td>';
+ } else {
+ echo '<td align="right">';
+ // print enrol info
+ if ($icons = enrol_get_course_info_icons($acourse)) {
+ foreach ($icons as $pix_icon) {
+ echo $OUTPUT->render($pix_icon);
}
- echo "</td>";
}
- echo "</tr>";
- }
-
- if ($abletomovecourses) {
- $movetocategories = array();
- $notused = array();
- make_categories_list($movetocategories, $notused, 'moodle/category:manage');
- $movetocategories[$category->id] = get_string('moveselectedcoursesto');
- echo '<tr><td colspan="3" align="right">';
- echo html_writer::select($movetocategories, 'moveto', $category->id, null, array('id'=>'movetoid'));
- $PAGE->requires->js_init_call('M.util.init_select_autosubmit', array('movecourses', 'movetoid', false));
- echo '<input type="hidden" name="id" value="'.$category->id.'" />';
- echo '</td></tr>';
+ if (!empty($acourse->summary)) {
+ $url = new moodle_url("/course/info.php?id=$acourse->id");
+ echo $OUTPUT->action_link($url, '<img alt="'.get_string('info').'" class="icon" src="'.$OUTPUT->pix_url('i/info') . '" />',
+ new popup_action('click', $url, 'courseinfo'), array('title'=>get_string('summary')));
+ }
+ echo "</td>";
}
-
- echo '</table>';
- echo '</div></form>';
- echo '<br />';
+ echo "</tr>";
}
- echo '<div class="buttons">';
- if (has_capability('moodle/category:manage', $context) and $numcourses > 1) {
- /// Print button to re-sort courses by name
- unset($options);
- $options['id'] = $category->id;
- $options['resort'] = 'name';
- $options['sesskey'] = sesskey();
- echo $OUTPUT->single_button(new moodle_url('category.php', $options), get_string('resortcoursesbyname'), 'get');
+ if ($abletomovecourses) {
+ $movetocategories = array();
+ $notused = array();
+ make_categories_list($movetocategories, $notused, 'moodle/category:manage');
+ $movetocategories[$category->id] = get_string('moveselectedcoursesto');
+ echo '<tr><td colspan="3" align="right">';
+ echo html_writer::select($movetocategories, 'moveto', $category->id, null, array('id'=>'movetoid'));
+ $PAGE->requires->js_init_call('M.util.init_select_autosubmit', array('movecourses', 'movetoid', false));
+ echo '<input type="hidden" name="id" value="'.$category->id.'" />';
+ echo '</td></tr>';
}
- if (has_capability('moodle/course:create', $context)) {
- /// Print button to create a new course
- unset($options);
- $options['category'] = $category->id;
- $options['returnto'] = 'category';
- echo $OUTPUT->single_button(new moodle_url('edit.php', $options), get_string('addnewcourse'), 'get');
- }
+ echo '</table>';
+ echo '</div></form>';
+ echo '<br />';
+}
- if (!empty($CFG->enablecourserequests) && $category->id == $CFG->defaultrequestcategory) {
- print_course_request_buttons(get_context_instance(CONTEXT_SYSTEM));
- }
- echo '</div>';
+echo '<div class="buttons">';
+if ($canmanage and $numcourses > 1) {
+ // Print button to re-sort courses by name
+ $url = new moodle_url('/course/category.php', array('id' => $category->id, 'resort' => 'name', 'sesskey' => sesskey()));
+ echo $OUTPUT->single_button($url, get_string('resortcoursesbyname'), 'get');
+}
+
+if (has_capability('moodle/course:create', $context)) {
+ // Print button to create a new course
+ $url = new moodle_url('/course/edit.php', array('category' => $category->id, 'returnto' => 'category'));
+ echo $OUTPUT->single_button($url, get_string('addnewcourse'), 'get');
+}
- print_course_search();
+if (!empty($CFG->enablecourserequests) && $category->id == $CFG->defaultrequestcategory) {
+ print_course_request_buttons(get_context_instance(CONTEXT_SYSTEM));
+}
+echo '</div>';
- echo $OUTPUT->footer();
+print_course_search();
+echo $OUTPUT->footer();
// Prepare course and the editor
$editoroptions = array('maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes'=>$CFG->maxbytes, 'trusttext'=>false, 'noclean'=>true);
if (!empty($course)) {
- $allowedmods = array();
- if ($am = $DB->get_records('course_allowed_modules', array('course'=>$course->id))) {
- foreach ($am as $m) {
- $allowedmods[] = $m->module;
- }
- } else {
- // this happens in case we edit course created before enabling module restrictions or somebody disabled everything :-(
- if (empty($course->restrictmodules) and !empty($CFG->defaultallowedmodules)) {
- $allowedmods = explode(',', $CFG->defaultallowedmodules);
- }
- }
- $course->allowedmods = $allowedmods;
//add context for editor
$editoroptions['context'] = $coursecontext;
$course = file_prepare_standard_editor($course, 'summary', $editoroptions, $coursecontext, 'course', 'summary', 0);
$mform->setDefault('completionstartonenrol',0);
}
-//--------------------------------------------------------------------------------
- if (has_capability('moodle/site:config', $systemcontext)) {
- if (((!empty($course->requested) && $CFG->restrictmodulesfor == 'requested') || $CFG->restrictmodulesfor == 'all')) {
- $mform->addElement('header', '', get_string('restrictmodules'));
-
- $options = array();
- $options['0'] = get_string('no');
- $options['1'] = get_string('yes');
- $mform->addElement('select', 'restrictmodules', get_string('restrictmodules'), $options);
- if (!empty($CFG->restrictbydefault)) {
- $mform->setDefault('restrictmodules', 1);
- }
-
- $mods = array(0=>get_string('allownone'));
- $allmods = $DB->get_records_menu('modules', array('visible' => 1),
- 'name', 'id, name');
- foreach ($allmods as $key => $value) {
- // Add module to list unless it cannot be added by users anyway
- if (plugin_supports('mod', $value, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER) !==
- MOD_ARCHETYPE_SYSTEM) {
- $mods[$key] = get_string('pluginname', $value);
- }
- }
- $mform->addElement('select', 'allowedmods', get_string('to'), $mods, array('multiple'=>'multiple', 'size'=>'10'));
- $mform->disabledIf('allowedmods', 'restrictmodules', 'eq', 0);
- // defaults are already in $course
- } else {
- // remove any mod restriction
- $mform->addElement('hidden', 'restrictmodules', 0);
- $mform->setType('restrictmodules', PARAM_INT);
- }
- } else {
- $mform->addElement('hidden', 'restrictmodules');
- $mform->setType('restrictmodules', PARAM_INT);
- if (empty($course->id)) {
- $mform->setConstant('restrictmodules', (int)($CFG->restrictmodulesfor == 'all'));
- } else {
- // keep previous
- $mform->setConstant('restrictmodules', $course->restrictmodules);
- }
- }
-
/// customizable role names in this course
//--------------------------------------------------------------------------------
$mform->addElement('header','rolerenaming', get_string('rolerenaming'));
<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
/**
* Page for creating or editing course category name/parent/description.
* When called with an id parameter, edits the category with that id.
* Otherwise it creates a new category with default parent from the parent
* parameter, which may be 0.
+ *
+ * @package core
+ * @subpackage course
+ * @copyright 2007 Nicolas Connault
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('../config.php');
redirect('category.php?id='.$newcategory->id.'&categoryedit=on');
}
+// Unfortunately the navigation never generates correctly for this page because technically
+// this page doesn't actually exist on the navigation you get here through the course
+// management page.
+try {
+ // First up we'll try to make the course management page active seeing as that is
+ // where the user thinks they are.
+ // The big prolem here is that the course management page is a common page
+ // for both editing users and common users.
+ $PAGE->settingsnav->get('root')->get('courses')->get('coursemgmt')->make_active();
+} catch (Exception $ex) {
+ // Failing that we'll override the URL, not as accurate and chances are things
+ // won't be 100% correct all the time but should work most times.
+ navigation_node::override_active_url(new moodle_url('/course/index.php', array('categoryedit' => 'on')));
+}
+
$PAGE->set_title($title);
$PAGE->set_heading($fullname);
echo $OUTPUT->header();
$tempcat->context = get_context_instance(CONTEXT_COURSECAT, $tempcat->id);
mark_context_dirty('/'.SYSCONTEXTID);
fix_course_sortorder(); // Required to build course_categories.depth and .path.
+ set_config('defaultrequestcategory', $tempcat->id);
}
/// Move a category to a new parent if required
print_category_edit($cat, $displaylist, $parentslist, $depth+1, $up, $down);
}
}
-}
\ No newline at end of file
+}
/// Next, have there been any modifications to the course structure?
- $modinfo =& get_fast_modinfo($course);
+ $modinfo = get_fast_modinfo($course);
$changelist = array();
}
}
-function update_restricted_mods($course, $mods) {
- global $DB;
-
-/// Delete all the current restricted list
- $DB->delete_records('course_allowed_modules', array('course'=>$course->id));
-
- if (empty($course->restrictmodules)) {
- return; // We're done
- }
-
-/// Insert the new list of restricted mods
- foreach ($mods as $mod) {
- if ($mod == 0) {
- continue; // this is the 'allow none' option
- }
- $am = new stdClass();
- $am->course = $course->id;
- $am->module = $mod;
- $DB->insert_record('course_allowed_modules',$am);
- }
-}
-
/**
- * This function will take an int (module id) or a string (module name)
- * and return true or false, whether it's allowed in the given course (object)
- * $mod is not allowed to be an object, as the field for the module id is inconsistent
- * depending on where in the code it's called from (sometimes $mod->id, sometimes $mod->module)
+ * Is the user allowed to add this type of module to this course?
+ * @param object $course the course settings. Only $course->id is used.
+ * @param string $modname the module name. E.g. 'forum' or 'quiz'.
+ * @return bool whether the current user is allowed to add this type of module to this course.
*/
-
-function course_allowed_module($course,$mod) {
+function course_allowed_module($course, $modname) {
global $DB;
- if (empty($course->restrictmodules)) {
- return true;
+ if (is_numeric($modname)) {
+ throw new coding_exception('Function course_allowed_module no longer
+ supports numeric module ids. Please update your code to pass the module name.');
}
- // Admins and admin-like people who can edit everything can also add anything.
- // Originally there was a course:update test only, but it did not match the test in course edit form
- if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
- return true;
- }
+ $capability = 'mod/' . $modname . ':addinstance';
+ if (!get_capability_info($capability)) {
+ // Debug warning that the capability does not exist, but no more than once per page.
+ static $warned = array();
+ $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER);
+ if (!isset($warned[$modname]) && $archetype !== MOD_ARCHETYPE_SYSTEM) {
+ debugging('The module ' . $modname . ' does not define the standard capability ' .
+ $capability , DEBUG_DEVELOPER);
+ $warned[$modname] = 1;
+ }
- if (is_numeric($mod)) {
- $modid = $mod;
- } else if (is_string($mod)) {
- $modid = $DB->get_field('modules', 'id', array('name'=>$mod));
- }
- if (empty($modid)) {
- return false;
+ // If the capability does not exist, the module can always be added.
+ return true;
}
- return $DB->record_exists('course_allowed_modules', array('course'=>$course->id, 'module'=>$modid));
+ $coursecontext = context_course::instance($course->id);
+ return has_capability($capability, $coursecontext);
}
/**
fix_course_sortorder();
- // update module restrictions
- if ($course->restrictmodules) {
- if (isset($data->allowedmods)) {
- update_restricted_mods($course, $data->allowedmods);
- } else {
- if (!empty($CFG->defaultallowedmodules)) {
- update_restricted_mods($course, explode(',', $CFG->defaultallowedmodules));
- }
- }
- }
-
// new context created - better mark it as dirty
mark_context_dirty($context->path);
// Test for and remove blocks which aren't appropriate anymore
blocks_remove_inappropriate($course);
- // update module restrictions
- if (isset($data->allowedmods)) {
- update_restricted_mods($course, $data->allowedmods);
- }
-
// Save any custom role names.
save_local_role_names($course->id, $data);
// Set misc settings
$data->requested = 1;
- if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) {
- $data->restrictmodules = 1;
- }
// Apply course default settings
$data->format = $courseconfig->format;
$cw = get_course_section($section, $course->id);
- if (!course_allowed_module($course, $module->id)) {
+ if (!course_allowed_module($course, $module->name)) {
print_error('moduledisable');
}
$mform->display();
-$modinfo =& get_fast_modinfo($course);
+$modinfo = get_fast_modinfo($course);
get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
if (has_capability('moodle/course:viewhiddensections', $context)) {
$mform->addElement('header', 'rolesheader', get_string('roles'));
$roles = get_assignable_roles(get_context_instance(CONTEXT_COURSE, $COURSE->id));
+ $roles[0] = get_string('noroles', 'role');
+ $roles = array_reverse($roles, true);
+
$mform->addElement('select', 'unenrol_users', get_string('unenrolroleusers', 'enrol'), $roles, array('multiple' => 'multiple'));
$mform->addElement('checkbox', 'reset_roles_overrides', get_string('deletecourseoverrides', 'role'));
$mform->setAdvanced('reset_roles_overrides');
<?php
-
-/// Displays external information about a course
-
- require_once("../config.php");
- require_once("lib.php");
-
- $search = optional_param('search', '', PARAM_RAW); // search words
- $page = optional_param('page', 0, PARAM_INT); // which page to show
- $perpage = optional_param('perpage', 10, PARAM_INT); // how many per page
- $moveto = optional_param('moveto', 0, PARAM_INT); // move to category
- $edit = optional_param('edit', -1, PARAM_BOOL);
- $hide = optional_param('hide', 0, PARAM_INT);
- $show = optional_param('show', 0, PARAM_INT);
- $blocklist = optional_param('blocklist', 0, PARAM_INT);
- $modulelist= optional_param('modulelist', '', PARAM_PLUGIN);
-
- $PAGE->set_url('/course/search.php', compact('search', 'page', 'perpage', 'blocklist', 'modulelist', 'edit'));
- $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM));
- $search = trim(strip_tags($search)); // trim & clean raw searched string
-
- if ($search) {
- $searchterms = explode(" ", $search); // Search for words independently
- foreach ($searchterms as $key => $searchterm) {
- if (strlen($searchterm) < 2) {
- unset($searchterms[$key]);
- }
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Displays external information about a course
+ * @package core
+ * @category course
+ * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+require_once("../config.php");
+require_once($CFG->dirroot.'/course/lib.php');
+
+$search = optional_param('search', '', PARAM_RAW); // search words
+$page = optional_param('page', 0, PARAM_INT); // which page to show
+$perpage = optional_param('perpage', 10, PARAM_INT); // how many per page
+$moveto = optional_param('moveto', 0, PARAM_INT); // move to category
+$edit = optional_param('edit', -1, PARAM_BOOL);
+$hide = optional_param('hide', 0, PARAM_INT);
+$show = optional_param('show', 0, PARAM_INT);
+$blocklist = optional_param('blocklist', 0, PARAM_INT);
+$modulelist= optional_param('modulelist', '', PARAM_PLUGIN);
+
+// List of minimum capabilities which user need to have for editing/moving course
+$capabilities = array('moodle/course:create', 'moodle/category:manage');
+
+// List of category id's in which current user has course:create and category:manage capability.
+$usercatlist = array();
+
+// List of parent category id's
+$catparentlist = array();
+
+// Populate usercatlist with list of category id's with required capabilities.
+make_categories_list($usercatlist, $catparentlist, $capabilities);
+
+$search = trim(strip_tags($search)); // trim & clean raw searched string
+if ($search) {
+ $searchterms = explode(" ", $search); // Search for words independently
+ foreach ($searchterms as $key => $searchterm) {
+ if (strlen($searchterm) < 2) {
+ unset($searchterms[$key]);
}
- $search = trim(implode(" ", $searchterms));
}
+ $search = trim(implode(" ", $searchterms));
+}
- $site = get_site();
+$site = get_site();
- $urlparams = array();
- foreach (array('search', 'page', 'blocklist', 'modulelist') as $param) {
- if (!empty($$param)) {
- $urlparams[$param] = $$param;
- }
+$urlparams = array();
+foreach (array('search', 'page', 'blocklist', 'modulelist', 'edit') as $param) {
+ if (!empty($$param)) {
+ $urlparams[$param] = $$param;
}
- if ($perpage != 10) {
- $urlparams['perpage'] = $perpage;
+}
+if ($perpage != 10) {
+ $urlparams['perpage'] = $perpage;
+}
+$PAGE->set_url('/course/search.php', $urlparams);
+$PAGE->set_context(context_system::instance());
+$PAGE->set_pagelayout('standard');
+
+if ($CFG->forcelogin) {
+ require_login();
+}
+
+// Editing is possible if user has system or category level create and manage capability
+if (can_edit_in_category() || !empty($usercatlist)) {
+ if ($edit !== -1) {
+ $USER->editing = $edit;
}
- $PAGE->set_url('/course/search.php', $urlparams);
- $PAGE->set_context(get_context_instance(CONTEXT_SYSTEM));
- $PAGE->set_pagelayout('standard');
+ $adminediting = $PAGE->user_is_editing();
- if ($CFG->forcelogin) {
- require_login();
+ // Set perpage if user can edit in category
+ if ($perpage != 99999) {
+ $perpage = 30;
}
-
- if (can_edit_in_category()) {
- if ($edit !== -1) {
- $USER->editing = $edit;
+} else {
+ $adminediting = false;
+}
+
+// Editing functions
+if (has_capability('moodle/course:visibility', context_system::instance())) {
+ // Hide or show a course
+ if (($hide || $show) && confirm_sesskey()) {
+ if ($hide) {
+ $course = $DB->get_record("course", array("id" => $hide));
+ $visible = 0;
+ } else {
+ $course = $DB->get_record("course", array("id" => $show));
+ $visible = 1;
}
- $adminediting = $PAGE->user_is_editing();
- } else {
- $adminediting = false;
- }
-
-/// Editing functions
- if (has_capability('moodle/course:visibility', get_context_instance(CONTEXT_SYSTEM))) {
- /// Hide or show a course
- if ($hide or $show and confirm_sesskey()) {
- if ($hide) {
- $course = $DB->get_record("course", array("id"=>$hide));
- $visible = 0;
- } else {
- $course = $DB->get_record("course", array("id"=>$show));
- $visible = 1;
- }
- if ($course) {
- $DB->set_field("course", "visible", $visible, array("id"=>$course->id));
- }
+ if ($course) {
+ $DB->set_field("course", "visible", $visible, array("id" => $course->id));
}
}
+}
+
+$displaylist = array();
+$parentlist = array();
+make_categories_list($displaylist, $parentlist);
+
+$strcourses = new lang_string("courses");
+$strsearch = new lang_string("search");
+$strsearchresults = new lang_string("searchresults");
+$strcategory = new lang_string("category");
+$strselect = new lang_string("select");
+$strselectall = new lang_string("selectall");
+$strdeselectall = new lang_string("deselectall");
+$stredit = new lang_string("edit");
+$strfrontpage = new lang_string('frontpage', 'admin');
+$strnovalidcourses = new lang_string('novalidcourses');
+
+if (empty($search) and empty($blocklist) and empty($modulelist) and empty($moveto) and ($edit != -1)) {
+ $PAGE->navbar->add($strcourses, new moodle_url('/course/index.php'));
+ $PAGE->navbar->add($strsearch);
+ $PAGE->set_title("$site->fullname : $strsearch");
+ $PAGE->set_heading($site->fullname);
- $capabilities = array('moodle/course:create', 'moodle/category:manage');
- if (has_any_capability($capabilities, get_context_instance(CONTEXT_SYSTEM)) && ($perpage != 99999)) {
- $perpage = 30;
- }
+ echo $OUTPUT->header();
+ echo $OUTPUT->box_start();
+ echo "<center>";
+ echo "<br />";
+ print_course_search("", false, "plain");
+ echo "<br /><p>";
+ print_string("searchhelp");
+ echo "</p>";
+ echo "</center>";
+ echo $OUTPUT->box_end();
+ echo $OUTPUT->footer();
+ exit;
+}
- $displaylist = array();
- $parentlist = array();
- make_categories_list($displaylist, $parentlist);
-
- $strcourses = get_string("courses");
- $strsearch = get_string("search");
- $strsearchresults = get_string("searchresults");
- $strcategory = get_string("category");
- $strselect = get_string("select");
- $strselectall = get_string("selectall");
- $strdeselectall = get_string("deselectall");
- $stredit = get_string("edit");
- $strfrontpage = get_string('frontpage', 'admin');
- $strnovalidcourses = get_string('novalidcourses');
-
- if (empty($search) and empty($blocklist) and empty($modulelist)) {
- $PAGE->navbar->add($strcourses, new moodle_url('/course/index.php'));
- $PAGE->navbar->add($strsearch);
- $PAGE->set_title("$site->fullname : $strsearch");
- $PAGE->set_heading($site->fullname);
-
- echo $OUTPUT->header();
- echo $OUTPUT->box_start();
- echo "<center>";
- echo "<br />";
- print_course_search("", false, "plain");
- echo "<br /><p>";
- print_string("searchhelp");
- echo "</p>";
- echo "</center>";
- echo $OUTPUT->box_end();
- echo $OUTPUT->footer();
- exit;
+$courses = array();
+if (!empty($moveto) and $data = data_submitted() and confirm_sesskey()) { // Some courses are being moved
+ if (!$destcategory = $DB->get_record("course_categories", array("id" => $moveto))) {
+ print_error('cannotfindcategory', '', '', $moveto);
}
- if (!empty($moveto) and $data = data_submitted() and confirm_sesskey()) { // Some courses are being moved
- if (! $destcategory = $DB->get_record("course_categories", array("id"=>$data->moveto))) {
- print_error('cannotfindcategory', '', '', $data->moveto);
- }
-
- $courses = array();
- foreach ( $data as $key => $value ) {
- if (preg_match('/^c\d+$/', $key)) {
- array_push($courses, substr($key, 1));
+ // User should have manage and create capablity on destination category.
+ require_capability('moodle/category:manage', context_coursecat::instance($moveto));
+ require_capability('moodle/course:create', context_coursecat::instance($moveto));
+
+ foreach ( $data as $key => $value ) {
+ if (preg_match('/^c\d+$/', $key)) {
+ $courseid = substr($key, 1);
+ // user must have category:manage and course:create capability for the course to be moved.
+ $coursecontext = context_course::instance($courseid);
+ foreach ($capabilities as $capability) {
+ // Require capability here will result in a fatal error should the user not
+ // have the requried category ensuring that no moves occur if they are
+ // trying to move multiple courses.
+ require_capability($capability, $coursecontext);
+ array_push($courses, $courseid);
}
}
- move_courses($courses, $data->moveto);
}
-
- // get list of courses containing blocks if required
- if (!empty($blocklist) and confirm_sesskey()) {
- $blockname = $DB->get_field('block', 'name', array('id' => $blocklist));
- $courses = array();
- $courses = $DB->get_records_sql("
- SELECT * FROM {course} WHERE id IN (
- SELECT DISTINCT ctx.instanceid
- FROM {context} ctx
- JOIN {block_instances} bi ON bi.parentcontextid = ctx.id
- WHERE ctx.contextlevel = " . CONTEXT_COURSE . " AND bi.blockname = ?)",
- array($blockname));
- $totalcount = count($courses);
- //Keep only chunk of array which you want to display
- if ($totalcount > $perpage) {
- $courses = array_chunk($courses, $perpage, true);
- $courses = $courses[$page];
- }
- foreach ($courses as $course) {
- $courses[$course->id] = $course;
- }
+ move_courses($courses, $moveto);
+}
+
+// get list of courses containing blocks if required
+if (!empty($blocklist) and confirm_sesskey()) {
+ $blockname = $DB->get_field('block', 'name', array('id' => $blocklist));
+ $courses = array();
+ $courses = $DB->get_records_sql("
+ SELECT * FROM {course} WHERE id IN (
+ SELECT DISTINCT ctx.instanceid
+ FROM {context} ctx
+ JOIN {block_instances} bi ON bi.parentcontextid = ctx.id
+ WHERE ctx.contextlevel = " . CONTEXT_COURSE . " AND bi.blockname = ?)",
+ array($blockname));
+ $totalcount = count($courses);
+ // Keep only chunk of array which you want to display
+ if ($totalcount > $perpage) {
+ $courses = array_chunk($courses, $perpage, true);
+ $courses = $courses[$page];
}
- // get list of courses containing modules if required
- elseif (!empty($modulelist) and confirm_sesskey()) {
- $modulename = $modulelist;
- $sql = "SELECT DISTINCT c.id FROM {".$modulelist."} module, {course} c"
- ." WHERE module.course=c.id";
-
- $courseids = $DB->get_records_sql($sql);
- $courses = array();
- if (!empty($courseids)) {
- $firstcourse = $page*$perpage;
- $lastcourse = $page*$perpage + $perpage -1;
- $i = 0;
- foreach ($courseids as $courseid) {
- if ($i>= $firstcourse && $i<=$lastcourse) {
- $courses[$courseid->id] = $DB->get_record('course', array('id'=> $courseid->id));
- }
- $i++;
+ foreach ($courses as $course) {
+ $courses[$course->id] = $course;
+ }
+} elseif (!empty($modulelist) and confirm_sesskey()) { // get list of courses containing modules
+ $modulename = $modulelist;
+ $sql = "SELECT DISTINCT c.id FROM {".$modulelist."} module, {course} c"
+ ." WHERE module.course=c.id";
+
+ $courseids = $DB->get_records_sql($sql);
+ $courses = array();
+ if (!empty($courseids)) {
+ $firstcourse = $page*$perpage;
+ $lastcourse = $page*$perpage + $perpage -1;
+ $i = 0;
+ foreach ($courseids as $courseid) {
+ if ($i >= $firstcourse && $i <= $lastcourse) {
+ $courses[$courseid->id] = $DB->get_record('course', array('id'=> $courseid->id));
}
- $totalcount = count($courseids);
- }
- else {
- $totalcount = 0;
+ $i++;
}
+ $totalcount = count($courseids);
}
else {
- $courses = get_courses_search($searchterms, "fullname ASC",
- $page, $perpage, $totalcount);
+ $totalcount = 0;
}
-
- $searchform = print_course_search($search, true, "navbar");
-
- if (!empty($courses) && has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM))) {
- $searchform = '';
- // not sure if this capability is the best here
- if (has_capability('moodle/category:manage', get_context_instance(CONTEXT_SYSTEM))) {
- if ($PAGE->user_is_editing()) {
- $string = get_string("turneditingoff");
- $edit = "off";
- } else {
- $string = get_string("turneditingon");
- $edit = "on";
- }
-
- $aurl = new moodle_url("$CFG->wwwroot/course/search.php", array(
- 'edit' => $edit,
- 'sesskey' => sesskey(),
- 'search' => $search,
- 'page' => $page,
- 'perpage' => $perpage));
- $searchform = $OUTPUT->single_button($aurl, $string, 'get');
- }
+} else if (!empty($searchterm)) {
+ // Donot do search for empty search request.
+ $courses = get_courses_search($searchterms, "fullname ASC", $page, $perpage, $totalcount);
+}
+
+$searchform = '';
+// Turn editing should be visible if user have system or category level capability
+if (!empty($courses) && (can_edit_in_category() || !empty($usercatlist))) {
+ if ($PAGE->user_is_editing()) {
+ $string = new lang_string("turneditingoff");
+ $edit = "off";
+ } else {
+ $string = new lang_string("turneditingon");
+ $edit = "on";
}
-
- $PAGE->navbar->add($strcourses, new moodle_url('/course/index.php'));
- $PAGE->navbar->add($strsearch, new moodle_url('/course/search.php'));
- if (!empty($search)) {
- $PAGE->navbar->add(s($search));
+ $params = array_merge($urlparams, array('sesskey' => sesskey(), 'edit' => $edit));
+ $aurl = new moodle_url("$CFG->wwwroot/course/search.php", $params);
+ $searchform = $OUTPUT->single_button($aurl, $string, 'get');
+} else {
+ $searchform = print_course_search($search, true, "navbar");
+}
+
+$PAGE->navbar->add($strcourses, new moodle_url('/course/index.php'));
+$PAGE->navbar->add($strsearch, new moodle_url('/course/search.php'));
+if (!empty($search)) {
+ $PAGE->navbar->add(s($search));
+}
+$PAGE->set_title("$site->fullname : $strsearchresults");
+$PAGE->set_heading($site->fullname);
+$PAGE->set_button($searchform);
+
+echo $OUTPUT->header();
+
+$lastcategory = -1;
+if ($courses) {
+ echo $OUTPUT->heading("$strsearchresults: $totalcount");
+ $encodedsearch = urlencode($search);
+
+ // add the module/block parameter to the paging bar if they exists
+ $modulelink = "";
+ if (!empty($modulelist) and confirm_sesskey()) {
+ $modulelink = "&modulelist=".$modulelist."&sesskey=".sesskey();
+ } else if (!empty($blocklist) and confirm_sesskey()) {
+ $modulelink = "&blocklist=".$blocklist."&sesskey=".sesskey();
}
- $PAGE->set_title("$site->fullname : $strsearchresults");
- $PAGE->set_heading($site->fullname);
- $PAGE->set_button($searchform);
- echo $OUTPUT->header();
+ print_navigation_bar($totalcount, $page, $perpage, $encodedsearch, $modulelink);
- $lastcategory = -1;
- if ($courses) {
- echo $OUTPUT->heading("$strsearchresults: $totalcount");
- $encodedsearch = urlencode($search);
-
- // add the module/block parameter to the paging bar if they exists
- $modulelink = "";
+ // Show list of courses
+ if (!$adminediting) { //Not editing mode
+ foreach ($courses as $course) {
+ // front page don't belong to any category and block can exist.
+ if ($course->category > 0) {
+ $course->summary .= "<br /><p class=\"category\">";
+ $course->summary .= "$strcategory: <a href=\"category.php?id=$course->category\">";
+ $course->summary .= $displaylist[$course->category];
+ $course->summary .= "</a></p>";
+ }
+ print_course($course, $search);
+ echo $OUTPUT->spacer(array('height'=>5, 'width'=>5, 'br'=>true)); // should be done with CSS instead
+ }
+ } else {
+ // Editing mode
+ echo "<form id=\"movecourses\" action=\"search.php\" method=\"post\">\n";
+ echo "<div><input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />\n";
+ echo "<input type=\"hidden\" name=\"search\" value=\"".s($search)."\" />\n";
+ echo "<input type=\"hidden\" name=\"page\" value=\"$page\" />\n";
+ echo "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" /></div>\n";
if (!empty($modulelist) and confirm_sesskey()) {
- $modulelink = "&modulelist=".$modulelist."&sesskey=".sesskey();
+ echo "<input type=\"hidden\" name=\"modulelist\" value=\"$modulelist\" /></div>\n";
} else if (!empty($blocklist) and confirm_sesskey()) {
- $modulelink = "&blocklist=".$blocklist."&sesskey=".sesskey();
+ echo "<input type=\"hidden\" name=\"blocklist\" value=\"$blocklist\" /></div>\n";
}
+ echo "<table border=\"0\" cellspacing=\"2\" cellpadding=\"4\" class=\"generalbox boxaligncenter\">\n<tr>\n";
+ echo "<th scope=\"col\">$strcourses</th>\n";
+ echo "<th scope=\"col\">$strcategory</th>\n";
+ echo "<th scope=\"col\">$strselect</th>\n";
+ echo "<th scope=\"col\">$stredit</th></tr>\n";
- print_navigation_bar($totalcount, $page, $perpage, $encodedsearch, $modulelink);
+ foreach ($courses as $course) {
- if (!$adminediting) {
- foreach ($courses as $course) {
+ $coursecontext = context_course::instance($course->id);
- $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
+ $linkcss = $course->visible ? "" : " class=\"dimmed\" ";
- $course->summary .= "<br /><p class=\"category\">";
- $course->summary .= "$strcategory: <a href=\"category.php?id=$course->category\">";
- $course->summary .= $displaylist[$course->category];
- $course->summary .= "</a></p>";
- print_course($course, $search);
- echo $OUTPUT->spacer(array('height'=>5, 'width'=>5, 'br'=>true)); // should be done with CSS instead
+ // are we displaying the front page (courseid=1)?
+ if ($course->id == 1) {
+ echo "<tr>\n";
+ echo "<td><a href=\"$CFG->wwwroot\">$strfrontpage</a></td>\n";
+
+ // can't do anything else with the front page
+ echo " <td> </td>\n"; // category place
+ echo " <td> </td>\n"; // select place
+ echo " <td> </td>\n"; // edit place
+ echo "</tr>\n";
+ continue;
}
- } else {
- /// Show editing UI.
- echo "<form id=\"movecourses\" action=\"search.php\" method=\"post\">\n";
- echo "<div><input type=\"hidden\" name=\"sesskey\" value=\"".sesskey()."\" />\n";
- echo "<input type=\"hidden\" name=\"search\" value=\"".s($search)."\" />\n";
- echo "<input type=\"hidden\" name=\"page\" value=\"$page\" />\n";
- echo "<input type=\"hidden\" name=\"perpage\" value=\"$perpage\" /></div>\n";
- echo "<table border=\"0\" cellspacing=\"2\" cellpadding=\"4\" class=\"generalbox boxaligncenter\">\n<tr>\n";
- echo "<th scope=\"col\">$strcourses</th>\n";
- echo "<th scope=\"col\">$strcategory</th>\n";
- echo "<th scope=\"col\">$strselect</th>\n";
- echo "<th scope=\"col\">$stredit</th></tr>\n";
-
- foreach ($courses as $course) {
-
- $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
-
- $linkcss = $course->visible ? "" : " class=\"dimmed\" ";
-
- // are we displaying the front page (courseid=1)?
- if ($course->id == 1) {
- echo "<tr>\n";
- echo "<td><a href=\"$CFG->wwwroot\">$strfrontpage</a></td>\n";
-
- // can't do anything else with the front page
- echo " <td> </td>\n"; // category place
- echo " <td> </td>\n"; // select place
- echo " <td> </td>\n"; // edit place
- echo "</tr>\n";
- continue;
- }
- echo "<tr>\n";
- echo "<td><a $linkcss href=\"view.php?id=$course->id\">"
- . highlight($search, format_string($course->fullname)) . "</a></td>\n";
- echo "<td>".$displaylist[$course->category]."</td>\n";
- echo "<td>\n";
-
- // this is ok since this will get inherited from course category context
- // if it is set
- if (has_capability('moodle/category:manage', $coursecontext)) {
- echo "<input type=\"checkbox\" name=\"c$course->id\" />\n";
- } else {
- echo "<input type=\"checkbox\" name=\"c$course->id\" disabled=\"disabled\" />\n";
- }
+ echo "<tr>\n";
+ echo "<td><a $linkcss href=\"view.php?id=$course->id\">"
+ . highlight($search, format_string($course->fullname)) . "</a></td>\n";
+ echo "<td>".$displaylist[$course->category]."</td>\n";
+ echo "<td>\n";
- echo "</td>\n";
- echo "<td>\n";
+ // If user has all required capabilities to move course then show selectable checkbox
+ if (has_all_capabilities($capabilities, $coursecontext)) {
+ echo "<input type=\"checkbox\" name=\"c$course->id\" />\n";
+ } else {
+ echo "<input type=\"checkbox\" name=\"c$course->id\" disabled=\"disabled\" />\n";
+ }
- // checks whether user can update course settings
- if (has_capability('moodle/course:update', $coursecontext)) {
- echo "<a title=\"".get_string("settings")."\" href=\"$CFG->wwwroot/course/edit.php?id=$course->id\">\n<img".
- " src=\"" . $OUTPUT->pix_url('t/edit') . "\" class=\"iconsmall\" alt=\"".get_string("settings")."\" /></a>\n ";
- }
+ echo "</td>\n";
+ echo "<td>\n";
- // checks whether user can do role assignment
- if (has_capability('moodle/course:enrolreview', $coursecontext)) {
- echo'<a title="'.get_string('enrolledusers', 'enrol').'" href="'.$CFG->wwwroot.'/enrol/users.php?id='.$course->id.'">';
- echo '<img src="'.$OUTPUT->pix_url('i/users') . '" class="iconsmall" alt="'.get_string('enrolledusers', 'enrol').'" /></a> ' . "\n";
- }
+ // checks whether user can update course settings
+ if (has_capability('moodle/course:update', $coursecontext)) {
+ echo "<a title=\"".get_string("settings")."\" href=\"$CFG->wwwroot/course/edit.php?id=$course->id\">\n<img".
+ " src=\"" . $OUTPUT->pix_url('t/edit') . "\" class=\"iconsmall\" alt=\"".get_string("settings")."\" /></a>\n ";
+ }
- // checks whether user can delete course
- if (has_capability('moodle/course:delete', $coursecontext)) {
- echo "<a title=\"".get_string("delete")."\" href=\"delete.php?id=$course->id\">\n<img".
- " src=\"" . $OUTPUT->pix_url('t/delete') . "\" class=\"iconsmall\" alt=\"".get_string("delete")."\" /></a>\n ";
- }
+ // checks whether user can do role assignment
+ if (has_capability('moodle/course:enrolreview', $coursecontext)) {
+ echo'<a title="'.get_string('enrolledusers', 'enrol').'" href="'.$CFG->wwwroot.'/enrol/users.php?id='.$course->id.'">';
+ echo '<img src="'.$OUTPUT->pix_url('i/users') . '" class="iconsmall" alt="'.get_string('enrolledusers', 'enrol').'" /></a> ' . "\n";
+ }
- // checks whether user can change visibility
- if (has_capability('moodle/course:visibility', $coursecontext)) {
- if (!empty($course->visible)) {
- echo "<a title=\"".get_string("hide")."\" href=\"search.php?search=$encodedsearch&perpage=$perpage&page=$page&hide=$course->id&sesskey=".sesskey()."\">\n<img".
- " src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"".get_string("hide")."\" /></a>\n ";
- } else {
- echo "<a title=\"".get_string("show")."\" href=\"search.php?search=$encodedsearch&perpage=$perpage&page=$page&show=$course->id&sesskey=".sesskey()."\">\n<img".
- " src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"".get_string("show")."\" /></a>\n ";
- }
- }
+ // checks whether user can delete course
+ if (has_capability('moodle/course:delete', $coursecontext)) {
+ echo "<a title=\"".get_string("delete")."\" href=\"delete.php?id=$course->id\">\n<img".
+ " src=\"" . $OUTPUT->pix_url('t/delete') . "\" class=\"iconsmall\" alt=\"".get_string("delete")."\" /></a>\n ";
+ }
- // checks whether user can do site backup
- if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
- $backupurl = new moodle_url('/backup/backup.php', array('id' => $course->id));
- echo "<a title=\"".get_string("backup")."\" href=\"".$backupurl."\">\n<img".
- " src=\"" . $OUTPUT->pix_url('t/backup') . "\" class=\"iconsmall\" alt=\"".get_string("backup")."\" /></a>\n ";
+ // checks whether user can change visibility
+ if (has_capability('moodle/course:visibility', $coursecontext)) {
+ if (!empty($course->visible)) {
+ echo "<a title=\"".get_string("hide")."\" href=\"search.php?search=$encodedsearch&perpage=$perpage&page=$page&hide=$course->id&sesskey=".sesskey()."\">\n<img".
+ " src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"".get_string("hide")."\" /></a>\n ";
+ } else {
+ echo "<a title=\"".get_string("show")."\" href=\"search.php?search=$encodedsearch&perpage=$perpage&page=$page&show=$course->id&sesskey=".sesskey()."\">\n<img".
+ " src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"".get_string("show")."\" /></a>\n ";
}
+ }
- // checks whether user can do restore
- if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
- $restoreurl = new moodle_url('/backup/restorefile.php', array('contextid' => $coursecontext->id));
- echo "<a title=\"".get_string("restore")."\" href=\"".$restoreurl."\">\n<img".
- " src=\"" . $OUTPUT->pix_url('t/restore') . "\" class=\"iconsmall\" alt=\"".get_string("restore")."\" /></a>\n ";
- }
+ // checks whether user can do site backup
+ if (has_capability('moodle/backup:backupcourse', $coursecontext)) {
+ $backupurl = new moodle_url('/backup/backup.php', array('id' => $course->id));
+ echo "<a title=\"".get_string("backup")."\" href=\"".$backupurl."\">\n<img".
+ " src=\"" . $OUTPUT->pix_url('t/backup') . "\" class=\"iconsmall\" alt=\"".get_string("backup")."\" /></a>\n ";
+ }
- echo "</td>\n</tr>\n";
+ // checks whether user can do restore
+ if (has_capability('moodle/restore:restorecourse', $coursecontext)) {
+ $restoreurl = new moodle_url('/backup/restorefile.php', array('contextid' => $coursecontext->id));
+ echo "<a title=\"".get_string("restore")."\" href=\"".$restoreurl."\">\n<img".
+ " src=\"" . $OUTPUT->pix_url('t/restore') . "\" class=\"iconsmall\" alt=\"".get_string("restore")."\" /></a>\n ";
}
- echo "<tr>\n<td colspan=\"4\" style=\"text-align:center\">\n";
- echo "<br />";
- echo "<input type=\"button\" onclick=\"checkall()\" value=\"$strselectall\" />\n";
- echo "<input type=\"button\" onclick=\"checknone()\" value=\"$strdeselectall\" />\n";
- echo html_writer::select($displaylist, 'moveto', '', array(''=>get_string('moveselectedcoursesto')), array('id'=>'movetoid'));
- $PAGE->requires->js_init_call('M.util.init_select_autosubmit', array('movecourses', 'movetoid', false));
- echo "</td>\n</tr>\n";
- echo "</table>\n</form>";
+ echo "</td>\n</tr>\n";
}
+ echo "<tr>\n<td colspan=\"4\" style=\"text-align:center\">\n";
+ echo "<br />";
+ echo "<input type=\"button\" onclick=\"checkall()\" value=\"$strselectall\" />\n";
+ echo "<input type=\"button\" onclick=\"checknone()\" value=\"$strdeselectall\" />\n";
+ // Select box should only show categories in which user has min capability to move course.
+ echo html_writer::select($usercatlist, 'moveto', '', array(''=>get_string('moveselectedcoursesto')), array('id'=>'movetoid'));
+ $PAGE->requires->js_init_call('M.util.init_select_autosubmit', array('movecourses', 'movetoid', false));
+ echo "</td>\n</tr>\n";
+ echo "</table>\n</form>";
- print_navigation_bar($totalcount,$page,$perpage,$encodedsearch,$modulelink);
-
- } else {
- if (!empty($search)) {
- echo $OUTPUT->heading(get_string("nocoursesfound",'', s($search)));
- }
- else {
- echo $OUTPUT->heading( $strnovalidcourses );
- }
}
- echo "<br /><br />";
-
- print_course_search($search);
+ print_navigation_bar($totalcount,$page,$perpage,$encodedsearch,$modulelink);
- echo $OUTPUT->footer();
-
- /**
- * Print a list navigation bar
- * Display page numbers, and a link for displaying all entries
- * @param integer $totalcount - number of entry to display
- * @param integer $page - page number
- * @param integer $perpage - number of entry per page
- * @param string $encodedsearch
- * @param string $modulelink - module name
- */
- function print_navigation_bar($totalcount,$page,$perpage,$encodedsearch,$modulelink) {
- global $OUTPUT;
- echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "search.php?search=$encodedsearch".$modulelink."&perpage=$perpage");
-
- //display
- if ($perpage != 99999 && $totalcount > $perpage) {
- echo "<center><p>";
- echo "<a href=\"search.php?search=$encodedsearch".$modulelink."&perpage=99999\">".get_string("showall", "", $totalcount)."</a>";
- echo "</p></center>";
- } else if ($perpage === 99999) {
- $defaultperpage = 10;
- //If user has course:create or category:manage capability the show 30 records.
- $capabilities = array('moodle/course:create', 'moodle/category:manage');
- if (has_any_capability($capabilities, get_context_instance(CONTEXT_SYSTEM))) {
- $defaultperpage = 30;
- }
-
- echo "<center><p>";
- echo "<a href=\"search.php?search=$encodedsearch".$modulelink."&perpage=".$defaultperpage."\">".get_string("showperpage", "", $defaultperpage)."</a>";
- echo "</p></center>";
- }
+} else {
+ if (!empty($search)) {
+ echo $OUTPUT->heading(get_string("nocoursesfound",'', s($search)));
}
+ else {
+ echo $OUTPUT->heading($strnovalidcourses);
+ }
+}
+
+echo "<br /><br />";
+
+print_course_search($search);
+
+echo $OUTPUT->footer();
+
+/**
+ * Print a list navigation bar
+ * Display page numbers, and a link for displaying all entries
+ * @param int $totalcount number of entry to display
+ * @param int $page page number
+ * @param int $perpage number of entry per page
+ * @param string $encodedsearch
+ * @param string $modulelink module name
+ */
+function print_navigation_bar($totalcount, $page, $perpage, $encodedsearch, $modulelink) {
+ global $OUTPUT;
+ echo $OUTPUT->paging_bar($totalcount, $page, $perpage, "search.php?search=$encodedsearch".$modulelink."&perpage=$perpage");
+
+ // display
+ if ($perpage != 99999 && $totalcount > $perpage) {
+ echo "<center><p>";
+ echo "<a href=\"search.php?search=$encodedsearch".$modulelink."&perpage=99999\">".get_string("showall", "", $totalcount)."</a>";
+ echo "</p></center>";
+ } else if ($perpage === 99999) {
+ $defaultperpage = 10;
+ // If user has course:create or category:manage capability the show 30 records.
+ $capabilities = array('moodle/course:create', 'moodle/category:manage');
+ if (has_any_capability($capabilities, context_system::instance())) {
+ $defaultperpage = 30;
+ }
-
+ echo "<center><p>";
+ echo "<a href=\"search.php?search=$encodedsearch".$modulelink."&perpage=".$defaultperpage."\">".get_string("showperpage", "", $defaultperpage)."</a>";
+ echo "</p></center>";
+ }
+}
\ No newline at end of file
// Course wrapper start.
echo html_writer::start_tag('div', array('class'=>'course-content'));
- $modinfo =& get_fast_modinfo($COURSE);
+ $modinfo = get_fast_modinfo($COURSE);
get_all_mods($course->id, $mods, $modnames, $modnamesplural, $modnamesused);
foreach($mods as $modid=>$unused) {
if (!isset($modinfo->cms[$modid])) {
rebuild_course_cache($course->id);
- $modinfo =& get_fast_modinfo($COURSE);
+ $modinfo = get_fast_modinfo($COURSE);
debugging('Rebuilding course cache', DEBUG_DEVELOPER);
break;
}
}
$preventfullunenrol = empty($externalcourses);
if ($preventfullunenrol and $unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
- if ($verbose) {
- mtrace(' Preventing unenrolment of all current users, because it might result in major data loss, there has to be at least one record in external enrol table, sorry.');
- }
+ mtrace(' Preventing unenrolment of all current users, because it might result in major data loss, there has to be at least one record in external enrol table, sorry.');
}
// first find all existing courses with enrol instance
$nothingtodo = false;
}
- if ($nothingtodo === true) {
+ if (($nothingtodo === true) || (!has_capability('mod/glossary:view', $this->context))) {
return $text;
}
* @param string type "extra" or "weight": the type of the column hosting the weight input
* @return string HTML
*/
- function get_weight_input($item, $type) {
+ static function get_weight_input($item, $type) {
global $OUTPUT;
if (!is_object($item) || get_class($item) !== 'grade_item') {
//Trims trailing zeros
//Used on the 'categories and items' page for grade items settings like aggregation co-efficient
//Grader report has its own decimal place settings so they are handled elsewhere
- function format_number($number) {
+ static function format_number($number) {
$formatted = rtrim(format_float($number, 4),'0');
if (substr($formatted, -1)=='.') { //if last char is the decimal point
$formatted .= '0';
if (!empty($features['includeseparator'])) {
$radio = array();
- $radio[] = &MoodleQuickForm::createElement('radio', 'separator', null, get_string('septab', 'grades'), 'tab');
- $radio[] = &MoodleQuickForm::createElement('radio', 'separator', null, get_string('sepcomma', 'grades'), 'comma');
+ $radio[] = $mform->createElement('radio', 'separator', null, get_string('septab', 'grades'), 'tab');
+ $radio[] = $mform->createElement('radio', 'separator', null, get_string('sepcomma', 'grades'), 'comma');
$mform->addGroup($radio, 'separator', get_string('separator', 'grades'), ' ', false);
$mform->setDefault('separator', 'comma');
}
if (!empty($features['includeseparator'])) {
$radio = array();
- $radio[] = &MoodleQuickForm::createElement('radio', 'separator', null, get_string('septab', 'grades'), 'tab');
- $radio[] = &MoodleQuickForm::createElement('radio', 'separator', null, get_string('sepcomma', 'grades'), 'comma');
+ $radio[] = $mform->createElement('radio', 'separator', null, get_string('septab', 'grades'), 'tab');
+ $radio[] = $mform->createElement('radio', 'separator', null, get_string('sepcomma', 'grades'), 'comma');
$mform->addGroup($radio, 'separator', get_string('separator', 'grades'), ' ', false);
$mform->setDefault('separator', 'comma');
}
$courseid = required_param('id', PARAM_INT); // course id
$page = optional_param('page', 0, PARAM_INT); // active page
-$perpageurl = optional_param('perpage', 0, PARAM_INT);
$edit = optional_param('edit', -1, PARAM_BOOL); // sticky editting mode
$sortitemid = optional_param('sortitemid', 0, PARAM_ALPHANUM); // sort by which grade item
$warnings = array();
}
-
-// Override perpage if set in URL
-if ($perpageurl) {
- $report->user_prefs['studentsperpage'] = $perpageurl;
-}
-
// final grades MUST be loaded after the processing
$report->load_users();
$numusers = $report->get_numusers();
echo '<input type="hidden" value="'.s($courseid).'" name="id" />';
echo '<input type="hidden" value="'.sesskey().'" name="sesskey" />';
echo '<input type="hidden" value="grader" name="report"/>';
+ echo '<input type="hidden" value="'.$page.'" name="page"/>';
echo $reporthtml;
echo '<div class="submit"><input type="submit" value="'.s(get_string('update')).'" /></div>';
echo '</div></form>';
$this->baseurl = new moodle_url('index.php', array('id' => $this->courseid));
- $studentsperpage = $this->get_pref('studentsperpage');
- if (!empty($studentsperpage)) {
- $this->baseurl->params(array('perpage' => $studentsperpage, 'page' => $this->page));
+ if (!empty($this->page)) {
+ $this->baseurl->params(array('page' => $this->page));
}
- $this->pbarurl = new moodle_url('/grade/report/grader/index.php', array('id' => $this->courseid, 'perpage' => $studentsperpage));
+ $this->pbarurl = new moodle_url('/grade/report/grader/index.php', array('id' => $this->courseid));
$this->setup_groups();
foreach ($this->gtree->items as $itemid=>$unused) {
// emulate grade element
- $item =& $this->gtree->get_item($itemid);
+ $item = $this->gtree->get_item($itemid);
$eid = $this->gtree->get_item_eid($item);
$element = $this->gtree->locate_element($eid);
// This script used to support group delete, but that has been moved. In case
// anyone still links to it, let's redirect to the new script.
-if($delete) {
- redirect('delete.php?courseid='.$courseid.'&groups='.$id);
+if ($delete) {
+ debugging('Deleting a group through group/group.php is deprecated and will be removed soon. Please use group/delete.php instead');
+ redirect(new moodle_url('delete.php', array('courseid' => $courseid, 'groups' => $id)));
}
+
if ($id) {
if (!$group = $DB->get_record('groups', array('id'=>$id))) {
print_error('invalidgroupid');
$returnurl = $CFG->wwwroot.'/group/index.php?id='.$course->id.'&group='.$id;
-if ($id and $delete) {
- if (!$confirm) {
- $PAGE->set_title(get_string('deleteselectedgroup', 'group'));
- $PAGE->set_heading($course->fullname . ': '. get_string('deleteselectedgroup', 'group'));
- echo $OUTPUT->header();
- $optionsyes = array('id'=>$id, 'delete'=>1, 'courseid'=>$courseid, 'sesskey'=>sesskey(), 'confirm'=>1);
- $optionsno = array('id'=>$courseid);
- $formcontinue = new single_button(new moodle_url('group.php', $optionsyes), get_string('yes'), 'get');
- $formcancel = new single_button(new moodle_url($baseurl, $optionsno), get_string('no'), 'get');
- echo $OUTPUT->confirm(get_string('deletegroupconfirm', 'group', $group->name), $formcontinue, $formcancel);
- echo $OUTPUT->footer();
- die;
-
- } else if (confirm_sesskey()){
- if (groups_delete_group($id)) {
- redirect('index.php?id='.$course->id);
- } else {
- print_error('erroreditgroup', 'group', $returnurl);
- }
- }
-}
-
// Prepare the description editor: We do support files for group descriptions
$editoroptions = array('maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$course->maxbytes, 'trust'=>false, 'context'=>$context, 'noclean'=>true);
if (!empty($group->id)) {
$group = $DB->get_record('groups', array('id'=>$groupid), '*', MUST_EXIST);
$course = $DB->get_record('course', array('id'=>$group->courseid), '*', MUST_EXIST);
-$PAGE->set_url('/groups/members.php', array('id'=>$groupid));
+$PAGE->set_url('/group/members.php', array('group'=>$groupid));
$PAGE->set_pagelayout('standard');
require_login($course);
$string['errorsinenvironment'] = '环境检查失败!';
$string['installation'] = '安装';
$string['langdownloaderror'] = '很不幸,无法下载“{$a}”语言包。安装过程将以英文继续。';
-$string['memorylimithelp'] = '<p>您的服务器的PHP内存限制是${a}。</p>
+$string['memorylimithelp'] = '<p>您服务器的PHP内存限制是{$a}。</p>
<p>这会使Moodle在将来运行是碰到内存问题,特别是您安装了很多模块并且/或者有很多用户。</p>
-<p>我们建议可能的话把限制设定的高一些,譬如16M。有几种方法可以做到这一点:</p>
+<p>我们建议可能的话把限制设定的高一些,譬如40M。有几种方法可以做到这一点:</p>
<ol>
<li>如果可以,重新编译PHP并使用<i>--enable-memory-limit</i>选项。这允许Moodle自己设定内存限制。</li>
-<li>如果可以访问php.ini文件,您可以修改<b>memory_limit</b>的设置为其它值如16M。如果您无法访问,可以让您的管理员帮您修改一下。</li>
+<li>如果可以访问php.ini文件,您可以修改<b>memory_limit</b>的设置为其它值,如40M。如果您无法访问,可以让您的管理员帮您修改一下。</li>
<li>在一些PHP服务器上,您可以在Moodle目录中创建一个.htaccess文件并包含如下内容:
-<blockquote>php_value memory_limit 16M</blockquote>
+<blockquote>php_value memory_limit 40M</blockquote>
<p>然而,在一些服务器上这会让<b>所有</b>PHP页面无法正常工作(在访问页面时会有错误),因此您可能不得不删除.htaccess文件。</p></li>
</ol>';
$string['paths'] = '路径';
';
$string['welcomep10'] = '{$a->installername} ({$a->installerversion})';
$string['welcomep20'] = '您看到这个页面表明您已经成功地在您的计算机上安装了<strong>{$a->packname} {$a->packversion}</strong>。恭喜您!';
-$string['welcomep30'] = '<strong>{$a->installername}</strong>包含了可以创建<strong>Moodle</strong>运行环境的应用程序:';
+$string['welcomep30'] = '<strong>{$a->installername}</strong>的此发行版包含了可以创建<strong>Moodle</strong>运行环境的应用程序:';
$string['welcomep40'] = '这个软件包还包含了<strong>Moodle {$a->moodlerelease} ({$a->moodleversion})</strong>。';
$string['welcomep50'] = '使用本软件包中包含的应用程序时应遵循它们各自的授权协议。整个<strong>{$a->installername}</strong>软件包都是<a href="http://www.opensource.org/docs/definition_plain.html">开源</a>的,并且遵循<a href="http://www.gnu.org/copyleft/gpl.html">GPL</a>授权协议发布。';
-$string['welcomep60'] = '接下来的页面会引导您通过一系列步骤在您的计算机上安装配置好<strong>Moodle</strong>。您可以接受缺省的设置后,或者根据需要修改它们。';
+$string['welcomep60'] = '接下来的页面会引导您通过一系列步骤在您的计算机上安装并配置好<strong>Moodle</strong>。您可以接受缺省的设置,或者根据需要修改它们。';
$string['welcomep70'] = '点击“向后”按钮以继续<strong>Moodle</strong>的安装过程。';
$string['wwwroot'] = '网站地址';
$string['configdebugpageinfo'] = 'Enable if you want page information printed in page footer.';
$string['configdebugsmtp'] = 'Enable verbose debug information during sending of email messages to SMTP server.';
$string['configdebugvalidators'] = 'Enable if you want to have links to external validator servers in page footer. You may need to create new user with username <em>w3cvalidator</em>, and enable guest access. These changes may allow unauthorized access to server, do not enable on production sites!';
-$string['configdefaultallowedmodules'] = 'For the courses which fall into the above category, which modules do you want to allow by default <b>when the course is created</b>?';
$string['configdefaulthomepage'] = 'This determines the home page for logged in users';
$string['configdefaultrequestcategory'] = 'Courses requested by users will be automatically placed in this category.';
$string['configdefaultrequestedcategory'] = 'Default category to put courses that were requested into, if they\'re approved.';
$string['configrequestedteachername'] = 'Word for teacher used in requested courses';
$string['configrequestedteachersname'] = 'Word for teachers used in requested courses';
$string['configrequiremodintro'] = 'Disable this option if you do not want to force users to enter description of each activity.';
-$string['configrestrictbydefault'] = 'Should new courses that are created that fall into the above category have their modules restricted by default?';
-$string['configrestrictmodulesfor'] = 'Which courses should have <b>the setting</b> for disabling some activity modules? Note that this setting only applies to teachers, administrators will still be able to add any activity to a course.';
$string['configrunclamavonupload'] = 'When enabled, clam AV will be used to scan all uploaded files.';
$string['configrunclamonupload'] = 'Run clam AV on file upload? You will need a correct path in pathtoclam for this to work. (Clam AV is a free virus scanner that you can get from http://www.clamav.net/)';
$string['configuserquota'] = 'The maximum number of bytes that a user can store in their own private file area. {$a->bytes} bytes == {$a->displaysize}';
$string['debugstringids'] = 'Show origin of languages strings';
$string['debugstringids_desc'] = 'This option is designed to help translators. When this option is enabled, if you add the parameter strings=1 to a request URL, it will show the language file and string id beside each string that is output.';
$string['debugvalidators'] = 'Show validator links';
-$string['defaultallowedmodules'] = 'Default allowed modules';
$string['defaultcity'] = 'Default city';
$string['defaultcity_help'] = 'A city entered here will be the default city when creating new user accounts.';
$string['defaulthomepage'] = 'Default home page for users';
$string['purgecachesfinished']= 'All caches were purged.';
$string['restorernewroleid'] = 'Restorers\' role in courses';
$string['restorernewroleid_help'] = 'If the user does not already have the permission to manage the newly restored course, the user is automatically assigned this role and enrolled if necessary. Select "None" if you do not want restorers to be able to manage every restored course.';
-$string['restrictbydefault'] = 'Restrict modules by default';
-$string['restrictmodulesfor'] = 'Restrict modules for';
$string['reverseproxy'] = 'Reverse proxy';
$string['riskconfig'] = 'Users could change site configuration and behaviour';
$string['riskconfigshort'] = 'Configuration risk';
$string['backuptype'] = 'Type';
$string['backuptypeactivity'] = 'Activity';
$string['backuptypecourse'] = 'Course';
+$string['backuptypesection'] = 'Section';
$string['backupversion'] = 'Backup version';
$string['cannotfindassignablerole'] = 'The {$a} role in the backup file cannot be mapped to any of the roles that you are allowed to assign.';
$string['choosefilefromcoursebackup'] = 'Course backup area';
$string['blogentrybyuser'] = 'Blog entry by {$a}';
$string['blogpreferences'] = 'Blog preferences';
$string['blogs'] = 'Blogs';
+$string['blogscourse'] = 'Course blogs';
+$string['blogssite'] = 'Site blogs';
$string['blogtags'] = 'Blog tags';
$string['cannotviewcourseblog'] = 'You do not have the required permissions to view blogs in this course';
$string['cannotviewcourseorgroupblog'] = 'You do not have the required permissions to view blogs in this course/group';
$string['settingssaved'] = 'Your settings have been saved';
$string['showmessagewindow'] = 'Popup window on new message';
$string['strftimedaydatetime'] = '%A, %d %B %Y, %I:%M %p';
+$string['thisconversation'] = 'this conversation';
$string['timenosee'] = 'Minutes since I was last seen online';
$string['timesent'] = 'Time sent';
$string['touserdoesntexist'] = 'You can not send a message to a user id ({$a}) that doesn\'t exist';
$string['restoreusersprecheck'] = 'Checking user data';
$string['restoreusersprecheckerror'] = 'Some problems were detected when checking user data';
$string['restricted'] = 'Restricted';
-$string['restrictmodules'] = 'Restrict activity modules?';
$string['returningtosite'] = 'Returning to this web site?';
$string['returntooriginaluser'] = 'Return to {$a}';
$string['revert'] = 'Revert';
*/
function accesslib_clear_all_caches_for_unit_testing() {
global $UNITTEST, $USER;
- if (empty($UNITTEST->running)) {
+ if (empty($UNITTEST->running) and !PHPUNITTEST) {
throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
}
image.setAttribute('src', imgSrc);
image.setAttribute('alt', text);
- //image.setAttribute('title', '');
container.appendChild(image);
if (attributes != null) {
}
$output .= " main.portal.icons['spacerimg']='".$OUTPUT->pix_url('spacer')."';\n";
$output .= " main.portal.icons['marker']='".$OUTPUT->pix_url('i/marker')."';\n";
+ $output .= " main.portal.icons['marked']='".$OUTPUT->pix_url('i/marked')."';\n";
$output .= " main.portal.icons['ihide']='".$OUTPUT->pix_url('i/hide')."';\n";
$output .= " main.portal.icons['move_2d']='".$OUTPUT->pix_url('i/move_2d')."';\n";
$output .= " main.portal.icons['show']='".$OUTPUT->pix_url('t/show')."';\n";
}
if (main.getString('courseformat', this.sectionId) != "weeks" && this.sectionId > 0) {
- var highlightbutton = main.mk_button('div', main.portal.icons['marker'], main.getString('marker', this.sectionId));
+ var highlightbutton = '';
+ //If current topic, then initalised as marked else marker
+ if (YAHOO.util.Dom.hasClass(this.getEl(),'current')) {
+ highlightbutton = main.mk_button('div', main.portal.icons['marked'], main.getString('marked', this.sectionId));
+ } else {
+ highlightbutton = main.mk_button('div', main.portal.icons['marker'], main.getString('marker', this.sectionId));
+ }
YAHOO.util.Event.addListener(highlightbutton, 'click', this.mk_marker, this, true);
commandContainer.appendChild(highlightbutton);
this.highlightButton = highlightbutton;
YAHOO.util.Dom.removeClass(this.getEl(), 'hidden');
this.viewButton.childNodes[0].src = this.viewButton.childNodes[0].src.replace(/show/i, 'hide');
this.viewButton.childNodes[0].alt = this.viewButton.childNodes[0].alt.replace(strshow, strhide);
- this.viewButton.childNodes[0].title = this.viewButton.childNodes[0].title.replace(strshow, strhide); //IE hack.
+ // mk_button set title only in ie, so check before setting it
+ if (this.viewButton.childNodes[0].title) {
+ this.viewButton.childNodes[0].title = this.viewButton.childNodes[0].title.replace(strshow, strhide); //IE hack.
+ }
this.viewButton.title = this.viewButton.title.replace(strshow, strhide);
this.hidden = false;
YAHOO.util.Dom.addClass(this.getEl(), 'hidden');
this.viewButton.childNodes[0].src = this.viewButton.childNodes[0].src.replace(/hide/i, 'show');
this.viewButton.childNodes[0].alt = this.viewButton.childNodes[0].alt.replace(strhide, strshow);
- this.viewButton.childNodes[0].title = this.viewButton.childNodes[0].title.replace(strhide, strshow); //IE hack.
+ if (this.viewButton.childNodes[0].title) {
+ this.viewButton.childNodes[0].title = this.viewButton.childNodes[0].title.replace(strhide, strshow); //IE hack.
+ }
this.viewButton.title = this.viewButton.title.replace(strhide, strshow);
this.hidden = true;
section_class.prototype.toggle_highlight = function() {
+ var strmarker = main.portal.strings['marker'];
+ var strmarked = main.portal.strings['marked'];
+
if (this.highlighted) {
YAHOO.util.Dom.removeClass(this.getEl(), 'current');
+ this.highlightButton.childNodes[0].src = main.portal.icons['marker'];
+ this.highlightButton.childNodes[0].alt = strmarker;
+ // mk_button set title only in ie, so check before setting it
+ if (this.highlightButton.childNodes[0].title) {
+ this.highlightButton.childNodes[0].title = strmarker; //for IE
+ }
+ this.highlightButton.title = strmarker;
this.highlighted = false;
} else {
YAHOO.util.Dom.addClass(this.getEl(), 'current');
+ this.highlightButton.childNodes[0].src = main.portal.icons['marked'];
+ this.highlightButton.childNodes[0].alt = strmarked;
+ if (this.highlightButton.childNodes[0].title) {
+ this.highlightButton.childNodes[0].title = strmarked; //for IE
+ }
+ this.highlightButton.title = strmarked;
this.highlighted = true;
}
};
* @param object object with submitted configuration settings (without system magic quotes)
* @param array $err array of error messages
*/
- function validate_form(&$form, &$err) {
+ function validate_form($form, &$err) {
//override if needed
}
$pageformat = $this->page->pagetype;
foreach($allblocks as $block) {
+ if (!$bi = block_instance($block->name)) {
+ continue;
+ }
if ($block->visible &&
- (block_method_result($block->name, 'instance_allow_multiple') || !$this->is_block_present($block->name)) &&
+ ($bi->instance_allow_multiple() || !$this->is_block_present($block->name)) &&
blocks_name_allowed_in_format($block->name, $pageformat) &&
- block_method_result($block->name, 'user_can_addto', $this->page)) {
+ $bi->user_can_addto($this->page)) {
$this->addableblocks[$block->name] = $block;
}
}
function blocks_name_allowed_in_format($name, $pageformat) {
$accept = NULL;
$maxdepth = -1;
- $formats = block_method_result($name, 'applicable_formats');
+ if (!$bi = block_instance($name)) {
+ return false;
+ }
+
+ $formats = $bi->applicable_formats();
if (!$formats) {
$formats = array();
}
}
}
+ /**
+ * Aggregate activity completion state
+ *
+ * @param int $type Aggregation type (COMPLETION_* constant)
+ * @param bool $old Old state
+ * @param bool $new New state
+ * @return bool
+ */
+ public static function aggregate_completion_states($type, $old, $new) {
+ if ($type == COMPLETION_AND) {
+ return $old && $new;
+ } else {
+ return $old || $new;
+ }
+ }
+
/**
* This is to be used only for system errors (things that shouldn't happen)
* and not user-level errors.
require_once($CFG->dirroot . '/blog/lib.php');
mtrace("Fetching external blog entries...", '');
$sql = "timefetched < ? OR timefetched = 0";
- $externalblogs = $DB->get_records_select('blog_external', $sql, array(mktime() - $CFG->externalblogcrontime));
+ $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
foreach ($externalblogs as $eb) {
blog_sync_external_entries($eb);
list($name, $value) = array_map('trim', $bits);
}
if (isset($name) && isset($value) && $name !== '' && $value !== '') {
- $style = css_style::init($name, $value);
+ $style = css_style::init_automatic($name, $value);
}
} else if ($style instanceof css_style) {
// Clone the style as it may be coming from another rule and we don't
* @param string $value The value of the style.
* @return css_style_generic
*/
- public static function init($name, $value) {
+ public static function init_automatic($name, $value) {
$specificclass = 'css_style_'.preg_replace('#[^a-zA-Z0-9]+#', '', $name);
if (class_exists($specificclass)) {
return $specificclass::init($value);
* @param string separator name
* @return string encoded delimiter char
*/
- function get_encoded_delimiter($delimiter_name) {
+ static function get_encoded_delimiter($delimiter_name) {
global $CFG;
if ($delimiter_name == 'cfg' and isset($CFG->CSV_ENCODE)) {
return $CFG->CSV_ENCODE;
* @param string who imports?
* @return int iid
*/
- function get_new_iid($type) {
+ static function get_new_iid($type) {
global $USER;
$filename = make_temp_directory('csvimport/'.$type.'/'.$USER->id);
<FIELD NAME="theme" TYPE="char" LENGTH="50" NOTNULL="true" SEQUENCE="false" PREVIOUS="lang" NEXT="timecreated"/>
<FIELD NAME="timecreated" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="theme" NEXT="timemodified"/>
<FIELD NAME="timemodified" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="timecreated" NEXT="requested"/>
- <FIELD NAME="requested" TYPE="int" LENGTH="1" NOTNULL="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="timemodified" NEXT="restrictmodules"/>
- <FIELD NAME="restrictmodules" TYPE="int" LENGTH="1" NOTNULL="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="requested" NEXT="enablecompletion"/>
- <FIELD NAME="enablecompletion" TYPE="int" LENGTH="1" NOTNULL="true" DEFAULT="0" SEQUENCE="false" COMMENT="1 = allow use of 'completion' progress-tracking on this course. 0 = disable completion tracking on this course." PREVIOUS="restrictmodules" NEXT="completionstartonenrol"/>
+ <FIELD NAME="requested" TYPE="int" LENGTH="1" NOTNULL="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="timemodified" NEXT="enablecompletion"/>
+ <FIELD NAME="enablecompletion" TYPE="int" LENGTH="1" NOTNULL="true" DEFAULT="0" SEQUENCE="false" COMMENT="1 = allow use of 'completion' progress-tracking on this course. 0 = disable completion tracking on this course." PREVIOUS="requested" NEXT="completionstartonenrol"/>
<FIELD NAME="completionstartonenrol" TYPE="int" LENGTH="1" NOTNULL="true" DEFAULT="0" SEQUENCE="false" COMMENT="1 = allow use of 'activty completion' progress-tracking on this course. 0 = disable activity completion tracking on this course." PREVIOUS="enablecompletion" NEXT="completionnotify"/>
<FIELD NAME="completionnotify" TYPE="int" LENGTH="1" NOTNULL="true" DEFAULT="0" SEQUENCE="false" COMMENT="Notify users when they complete this course" PREVIOUS="completionstartonenrol"/>
</FIELDS>
<INDEX NAME="course_section" UNIQUE="false" FIELDS="course, section"/>
</INDEXES>
</TABLE>
- <TABLE NAME="course_request" COMMENT="course requests" PREVIOUS="course_sections" NEXT="course_allowed_modules">
+ <TABLE NAME="course_request" COMMENT="course requests" PREVIOUS="course_sections" NEXT="filter_active">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true" NEXT="fullname"/>
<FIELD NAME="fullname" TYPE="char" LENGTH="254" NOTNULL="true" SEQUENCE="false" PREVIOUS="id" NEXT="shortname"/>
<INDEX NAME="shortname" UNIQUE="false" FIELDS="shortname"/>
</INDEXES>
</TABLE>
- <TABLE NAME="course_allowed_modules" COMMENT="allowed modules foreach course" PREVIOUS="course_request" NEXT="filter_active">
- <FIELDS>
- <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true" NEXT="course"/>
- <FIELD NAME="course" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="id" NEXT="module"/>
- <FIELD NAME="module" TYPE="int" LENGTH="10" NOTNULL="true" DEFAULT="0" SEQUENCE="false" PREVIOUS="course"/>
- </FIELDS>
- <KEYS>
- <KEY NAME="primary" TYPE="primary" FIELDS="id"/>
- </KEYS>
- <INDEXES>
- <INDEX NAME="course" UNIQUE="false" FIELDS="course" NEXT="module"/>
- <INDEX NAME="module" UNIQUE="false" FIELDS="module" PREVIOUS="course"/>
- </INDEXES>
- </TABLE>
- <TABLE NAME="filter_active" COMMENT="Stores information about which filters are active in which contexts. Also the filter sort order. See get_active_filters in lib/filterlib.php for how this data is used." PREVIOUS="course_allowed_modules" NEXT="filter_config">
+ <TABLE NAME="filter_active" COMMENT="Stores information about which filters are active in which contexts. Also the filter sort order. See get_active_filters in lib/filterlib.php for how this data is used." PREVIOUS="course_request" NEXT="filter_config">
<FIELDS>
<FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" SEQUENCE="true" NEXT="filter"/>
<FIELD NAME="filter" TYPE="char" LENGTH="32" NOTNULL="true" SEQUENCE="false" COMMENT="The filter internal name, like 'filter/tex' or 'mod/glossary'." PREVIOUS="id" NEXT="contextid"/>
upgrade_main_savepoint(true, 2012030900.01);
}
+ if ($oldversion < 2012031500.01) {
+ // Upgrade old course_allowed_modules data to be permission overrides.
+ if ($CFG->restrictmodulesfor === 'all') {
+ $courses = $DB->get_records_menu('course', array(), 'id', 'id, 1');
+ } else if ($CFG->restrictmodulesfor === 'requested') {
+ $courses = $DB->get_records_menu('course', array('retrictmodules' => 1), 'id', 'id, 1');
+ } else {
+ $courses = array();
+ }
+
+ if (!$dbman->table_exists('course_allowed_modules')) {
+ // Upgrade must already have been run on this server. This might happen,
+ // for example, during development of these changes.
+ $courses = array();
+ }
+
+ $modidtoname = $DB->get_records_menu('modules', array(), 'id', 'id, name');
+
+ $coursecount = count($courses);
+ if ($coursecount) {
+ $pbar = new progress_bar('allowedmods', 500, true);
+ $transaction = $DB->start_delegated_transaction();
+ }
+
+ $i = 0;
+ foreach ($courses as $courseid => $notused) {
+ $i += 1;
+ upgrade_set_timeout(60); // 1 minute per course should be fine.
+
+ $allowedmoduleids = $DB->get_records_menu('course_allowed_modules',
+ array('course' => $courseid), 'module', 'module, 1');
+ if (empty($allowedmoduleids)) {
+ // This seems to be the best match for backwards compatibility,
+ // not necessarily with the old code in course_allowed_module function,
+ // but with the code that used to be in the coures settings form.
+ $allowedmoduleids = explode(',', $CFG->defaultallowedmodules);
+ $allowedmoduleids = array_combine($allowedmoduleids, $allowedmoduleids);
+ }
+
+ $context = context_course::instance($courseid);
+
+ list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
+ list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
+ foreach ($managerroleids as $roleid) {
+ unset($roleids[$roleid]);
+ }
+
+ foreach ($modidtoname as $modid => $modname) {
+ if (isset($allowedmoduleids[$modid])) {
+ // Module is allowed, no worries.
+ continue;
+ }
+
+ $capability = 'mod/' . $modname . ':addinstance';
+ foreach ($roleids as $roleid) {
+ assign_capability($capability, CAP_PREVENT, $roleid, $context);
+ }
+ }
+
+ $pbar->update($i, $coursecount, "Upgrading legacy course_allowed_modules data - $i/$coursecount.");
+ }
+
+ if ($coursecount) {
+ $transaction->allow_commit();
+ }
+
+ upgrade_main_savepoint(true, 2012031500.01);
+ }
+
+ if ($oldversion < 2012031500.02) {
+
+ // Define field retrictmodules to be dropped from course
+ $table = new xmldb_table('course');
+ $field = new xmldb_field('restrictmodules');
+
+ // Conditionally launch drop field requested
+ if ($dbman->field_exists($table, $field)) {
+ $dbman->drop_field($table, $field);
+ }
+
+ upgrade_main_savepoint(true, 2012031500.02);
+ }
+
+ if ($oldversion < 2012031500.03) {
+
+ // Define table course_allowed_modules to be dropped
+ $table = new xmldb_table('course_allowed_modules');
+
+ // Conditionally launch drop table for course_allowed_modules
+ if ($dbman->table_exists($table)) {
+ $dbman->drop_table($table);
+ }
+
+ upgrade_main_savepoint(true, 2012031500.03);
+ }
+
+ if ($oldversion < 2012031500.04) {
+ // Clean up the old admin settings.
+ unset_config('restrictmodulesfor');
+ unset_config('restrictbydefault');
+ unset_config('defaultallowedmodules');
+
+ upgrade_main_savepoint(true, 2012031500.04);
+ }
return true;
}
-
/**
* Reset a sequence to the id field of a table.
- * @param string $table Name of table.
- * @throws ddl_exception|ddl_table_missing_exception Exception thrown upon reset errors.
+ * @param string|xmldb_table $table Name of table.
+ * @throws ddl_exception thrown upon reset errors.
*/
public function reset_sequence($table) {
if (!is_string($table) and !($table instanceof xmldb_table)) {
throw new ddl_exception('ddlunknownerror', NULL, 'incorrect table parameter!');
}
- /// Check the table exists
- if (!$this->table_exists($table)) {
- throw new ddl_table_missing_exception($table);
- }
+ // Do not test if table exists because it is slow
if (!$sqlarr = $this->generator->getResetSequenceSQL($table)) {
throw new ddl_exception('ddlunknownerror', null, 'table reset sequence sql not generated');
$xmldb_field_clone = clone($xmldb_field);
/// Change the name of the field to perform the change
- $xmldb_field_clone->setName($xmldb_field_clone->getName() . ' ' . $newname);
+ $xmldb_field_clone->setName($newname);
$fieldsql = $this->getFieldSQL($xmldb_table, $xmldb_field_clone);
- $sql = 'ALTER TABLE ' . $this->getTableName($xmldb_table) . ' CHANGE ' . $fieldsql;
+ $sql = 'ALTER TABLE ' . $this->getTableName($xmldb_table) . ' CHANGE ' .
+ $xmldb_field->getName() . ' ' . $fieldsql;
return array($sql);
}
die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
+global $CFG;
+
require_once($CFG->libdir . '/adminlib.php');
class ddl_test extends UnitTestCase {
private $tables = array();
private $records= array();
+ /** @var moodle_database */
private $tdb;
public static $includecoverage = array('lib/ddl');
public static $excludecoverage = array('lib/ddl/simpletest');
$this->assertTrue($e instanceof ddl_exception);
}
+ // long table name names - the largest allowed
+ $table = new xmldb_table('abcdef____0123456789_____xyz');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '2');
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ $dbman->create_table($table);
+ $this->assertTrue($dbman->table_exists($table));
+ $dbman->drop_table($table);
+
+ // table name is too long
+ $table = new xmldb_table('abcdef____0123456789_____xyz9');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '2');
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ try {
+ $dbman->create_table($table);
+ $this->fail('Exception expected');
+ } catch (Exception $e) {
+ $this->assertIdentical(get_class($e), 'coding_exception');
+ }
+
+ // invalid table name
+ $table = new xmldb_table('abCD');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '2');
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ try {
+ $dbman->create_table($table);
+ $this->fail('Exception expected');
+ } catch (Exception $e) {
+ $this->assertIdentical(get_class($e), 'coding_exception');
+ }
+
+
+ // weird column names - the largest allowed
+ $table = new xmldb_table('test_table3');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('abcdef____0123456789_______xyz', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '2');
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ $dbman->create_table($table);
+ $this->assertTrue($dbman->table_exists($table));
+ $dbman->drop_table($table);
+
+ // Too long field name - max 30
+ $table = new xmldb_table('test_table4');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('abcdeabcdeabcdeabcdeabcdeabcdez', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '2');
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ try {
+ $dbman->create_table($table);
+ $this->fail('Exception expected');
+ } catch (Exception $e) {
+ $this->assertIdentical(get_class($e), 'coding_exception');
+ }
+
+ // Invalid field name
+ $table = new xmldb_table('test_table4');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('abCD', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '2');
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ try {
+ $dbman->create_table($table);
+ $this->fail('Exception expected');
+ } catch (Exception $e) {
+ $this->assertIdentical(get_class($e), 'coding_exception');
+ }
+
+ // Invalid integer length
+ $table = new xmldb_table('test_table4');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('course', XMLDB_TYPE_INTEGER, '21', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '2');
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ try {
+ $dbman->create_table($table);
+ $this->fail('Exception expected');
+ } catch (Exception $e) {
+ $this->assertIdentical(get_class($e), 'coding_exception');
+ }
+
+ // Invalid integer default
+ $table = new xmldb_table('test_table4');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 'x');
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ try {
+ $dbman->create_table($table);
+ $this->fail('Exception expected');
+ } catch (Exception $e) {
+ $this->assertIdentical(get_class($e), 'coding_exception');
+ }
+
+ // Invalid decimal length
+ $table = new xmldb_table('test_table4');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('num', XMLDB_TYPE_NUMBER, '21,10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ try {
+ $dbman->create_table($table);
+ $this->fail('Exception expected');
+ } catch (Exception $e) {
+ $this->assertIdentical(get_class($e), 'coding_exception');
+ }
+
+ // Invalid decimal decimals
+ $table = new xmldb_table('test_table4');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('num', XMLDB_TYPE_NUMBER, '10,11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ try {
+ $dbman->create_table($table);
+ $this->fail('Exception expected');
+ } catch (Exception $e) {
+ $this->assertIdentical(get_class($e), 'coding_exception');
+ }
+
+ // Invalid decimal default
+ $table = new xmldb_table('test_table4');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('num', XMLDB_TYPE_NUMBER, '10,5', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 'x');
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ try {
+ $dbman->create_table($table);
+ $this->fail('Exception expected');
+ } catch (Exception $e) {
+ $this->assertIdentical(get_class($e), 'coding_exception');
+ }
+
+ // Invalid float length
+ $table = new xmldb_table('test_table4');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('num', XMLDB_TYPE_FLOAT, '21,10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ try {
+ $dbman->create_table($table);
+ $this->fail('Exception expected');
+ } catch (Exception $e) {
+ $this->assertIdentical(get_class($e), 'coding_exception');
+ }
+
+ // Invalid float decimals
+ $table = new xmldb_table('test_table4');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('num', XMLDB_TYPE_FLOAT, '10,11', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ try {
+ $dbman->create_table($table);
+ $this->fail('Exception expected');
+ } catch (Exception $e) {
+ $this->assertIdentical(get_class($e), 'coding_exception');
+ }
+
+ // Invalid float default
+ $table = new xmldb_table('test_table4');
+ $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
+ $table->add_field('num', XMLDB_TYPE_FLOAT, '10,5', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 'x');
+ $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
+ $table->setComment("This is a test'n drop table. You can drop it safely");
+
+ $this->tables[$table->getName()] = $table;
+
+ try {
+ $dbman->create_table($table);
+ $this->fail('Exception expected');
+ } catch (Exception $e) {
+ $this->assertIdentical(get_class($e), 'coding_exception');
+ }
+
}
/**
* by any of its comments, indexes and sequence creation SQL statements.
*/
public function getCreateTableSQL($xmldb_table) {
+ if ($error = $xmldb_table->validateDefinition()) {
+ throw new coding_exception($error);
+ }
$results = array(); //Array where all the sentences will be stored
}
-/// Deprecated DDL functions, to be removed soon ///
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @return bool
- */
-function table_exists($table) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- return $DB->get_manager()->table_exists($table);
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $field
- * @return bool
- */
-function field_exists($table, $field) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- return $DB->get_manager()->field_exists($table, $field);
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $index
- * @return bool
- */
-function find_index_name($table, $index) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- return $DB->get_manager()->find_index_name($table, $index);
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $index
- * @return bool
- */
-function index_exists($table, $index) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- return $DB->get_manager()->index_exists($table, $index);
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $xmldb_key
- * @return bool
- */
-function find_key_name($table, $xmldb_key) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- return $DB->get_manager()->find_key_name($table, $xmldb_key);
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @return bool
- */
-function drop_table($table) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->drop_table($table);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $file
- * @return bool
- */
-function install_from_xmldb_file($file) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->install_from_xmldb_file($file);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @return bool
- */
-function create_table($table) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->create_table($table);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @return bool
- */
-function create_temp_table($table) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->create_temp_table($table);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $newname
- * @return bool
- */
-function rename_table($table, $newname) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->rename_table($table, $newname);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $field
- * @return bool
- */
-function add_field($table, $field) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->add_field($table, $field);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $field
- * @return bool
- */
-function drop_field($table, $field) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->drop_field($table, $field);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $field
- * @return bool
- */
-function change_field_type($table, $field) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->change_field_type($table, $field);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $field
- * @return bool
- */
-function change_field_precision($table, $field) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->change_field_precision($table, $field);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $field
- * @return bool
- */
-function change_field_unsigned($table, $field) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->change_field_unsigned($table, $field);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $field
- * @return bool
- */
-function change_field_notnull($table, $field) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->change_field_notnull($table, $field);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $field
- * @return bool
- */
-function change_field_default($table, $field) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->change_field_default($table, $field);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $field
- * @param string $newname
- * @return bool
- */
-function rename_field($table, $field, $newname) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->rename_field($table, $field, $newname);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $key
- * @return bool
- */
-function add_key($table, $key) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->add_key($table, $key);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $key
- * @return bool
- */
-function drop_key($table, $key) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->drop_key($table, $key);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $key
- * @param string $newname
- * @return bool
- */
-function rename_key($table, $key, $newname) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->rename_key($table, $key, $newname);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $index
- * @return bool
- */
-function add_index($table, $index) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->add_index($table, $index);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $index
- * @return bool
- */
-function drop_index($table, $index) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->drop_index($table, $index);
- return true;
-}
-
-/**
- * @deprecated
- * @global object
- * @param string $table
- * @param string $index
- * @param string $newname
- * @return bool
- */
-function rename_index($table, $index, $newname) {
- global $DB;
- debugging('Deprecated ddllib function used!');
- $DB->get_manager()->rename_index($table, $index, $newname);
- return true;
-}
-
-
//////////////////////////
/// removed functions ////
//////////////////////////
-/**
- * @deprecated
- * @param mixed $mixed
- * @return void Throws an error and does nothing
- */
-function stripslashes_safe($mixed) {
- error('stripslashes_safe() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $var
- * @return void Throws an error and does nothing
- */
-function stripslashes_recursive($var) {
- error('stripslashes_recursive() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $dataobject
- * @return void Throws an error and does nothing
- */
-function addslashes_object($dataobject) {
- error('addslashes_object() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $var
- * @return void Throws an error and does nothing
- */
-function addslashes_recursive($var) {
- error('addslashes_recursive() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $command
- * @param bool $feedback
- * @return void Throws an error and does nothing
- */
-function execute_sql($command, $feedback=true) {
- error('execute_sql() not available anymore');
-}
-/**
- * @deprecated use $DB->record_exists_select() instead
- * @see moodle_database::record_exists_select()
- * @param mixed $table
- * @param mixed $select
- * @return void Throws an error and does nothing
- */
-function record_exists_select($table, $select='') {
- error('record_exists_select() not available anymore');
-}
-/**
- * @deprecated use $DB->record_exists_sql() instead
- * @see moodle_database::record_exists_sql()
- * @param mixed $sql
- * @return void Throws an error and does nothing
- */
-function record_exists_sql($sql) {
- error('record_exists_sql() not available anymore');
-}
-/**
- * @deprecated use $DB->count_records_select() instead
- * @see moodle_database::count_records_select()
- * @param mixed $table
- * @param mixed $select
- * @param mixed $countitem
- * @return void Throws an error and does nothing
- */
-function count_records_select($table, $select='', $countitem='COUNT(*)') {
- error('count_records_select() not available anymore');
-}
-/**
- * @deprecated use $DB->count_records_sql() instead
- * @see moodle_database::count_records_sql()
- * @param mixed $sql
- * @return void Throws an error and does nothing
- */
-function count_records_sql($sql) {
- error('count_records_sql() not available anymore');
-}
-/**
- * @deprecated use $DB->get_record_sql() instead
- * @see moodle_database::get_record_sql()
- * @param mixed $sql
- * @param bool $expectmultiple
- * @param bool $nolimit
- * @return void Throws an error and does nothing
- */
-function get_record_sql($sql, $expectmultiple=false, $nolimit=false) {
- error('get_record_sql() not available anymore');
-}
-/**
- * @deprecated use $DB->get_record_select() instead
- * @see moodle_database::get_record_select()
- * @param mixed $table
- * @param mixed $select
- * @param mixed $fields
- * @return void Throws an error and does nothing
- */
-function get_record_select($table, $select='', $fields='*') {
- error('get_record_select() not available anymore');
-}
-/**
- * @deprecated use $DB->get_recordset() instead
- * @see moodle_database::get_recordset()
- * @param mixed $table
- * @param mixed $field
- * @param mixed $value
- * @param mixed $sort
- * @param mixed $fields
- * @param mixed $limitfrom
- * @param mixed $limitnum
- * @return void Throws an error and does nothing
- */
-function get_recordset($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
- error('get_recordset() not available anymore');
-}
-/**
- * @deprecated use $DB->get_recordset_sql() instead
- * @see moodle_database::get_recordset_sql()
- * @param mixed $sql
- * @param mixed $limitfrom
- * @param mixed $limitnum
- * @return void Throws an error and does nothing
- */
-function get_recordset_sql($sql, $limitfrom=null, $limitnum=null) {
- error('get_recordset_sql() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $rs
- * @return void Throws an error and does nothing
- */
-function rs_fetch_record(&$rs) {
- error('rs_fetch_record() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $rs
- * @return void Throws an error and does nothing
- */
-function rs_next_record(&$rs) {
- error('rs_next_record() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $rs
- * @return void Throws an error and does nothing
- */
-function rs_fetch_next_record(&$rs) {
- error('rs_fetch_next_record() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $rs
- * @return void Throws an error and does nothing
- */
-function rs_EOF($rs) {
- error('rs_EOF() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $rs
- * @return void Throws an error and does nothing
- */
-function rs_close(&$rs) {
- error('rs_close() not available anymore');
-}
-/**
- * @deprecated use $DB->get_records_select() instead
- * @see moodle_database::get_records_select()
- * @param mixed $table
- * @param mixed $select
- * @param mixed $sort
- * @param mixed $fields
- * @param mixed $limitfrom
- * @param mixed $limitnum
- * @return void Throws an error and does nothing
- */
-function get_records_select($table, $select='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
- error('get_records_select() not available anymore');
-}
-/**
- * @deprecated use $DB->get_field_select() instead
- * @see moodle_database::get_field_select()
- * @param mixed $table
- * @param mixed $return
- * @param mixed $select
- * @return void Throws an error and does nothing
- */
-function get_field_select($table, $return, $select) {
- error('get_field_select() not available anymore');
-}
-/**
- * @deprecated use $DB->get_field_sql() instead
- * @see moodle_database::get_field_sql()
- * @param mixed $sql
- * @return void Throws an error and does nothing
- */
-function get_field_sql($sql) {
- error('get_field_sql() not available anymore');
-}
-/**
- * @deprecated use $DB->delete_records_select() instead
- * @see moodle_database::delete_records_select()
- * @param mixed $sql
- * @param mixed $select
- * @return void Throws an error and does nothing
- */
-function delete_records_select($table, $select='') {
- error('get_field_sql() not available anymore');
-}
-/**
- * @deprecated
- * @return void Throws an error and does nothing
- */
-function configure_dbconnection() {
- error('configure_dbconnection() removed');
-}
-/**
- * @deprecated
- * @param mixed $field
- * @return void Throws an error and does nothing
- */
-function sql_max($field) {
- error('sql_max() removed - use normal sql MAX() instead');
-}
-/**
- * @deprecated
- * @return void Throws an error and does nothing
- */
-function sql_as() {
- error('sql_as() removed - do not use AS for tables at all');
-}
-/**
- * @deprecated
- * @param mixed $page
- * @param mixed $recordsperpage
- * @return void Throws an error and does nothing
- */
-function sql_paging_limit($page, $recordsperpage) {
- error('Function sql_paging_limit() is deprecated. Replace it with the correct use of limitfrom, limitnum parameters');
-}
-/**
- * @deprecated
- * @return void Throws an error and does nothing
- */
-function db_uppercase() {
- error('upper() removed - use normal sql UPPER()');
-}
-/**
- * @deprecated
- * @return void Throws an error and does nothing
- */
-function db_lowercase() {
- error('upper() removed - use normal sql LOWER()');
-}
-/**
- * @deprecated
- * @param mixed $sqlfile
- * @param mixed $sqlstring
- * @return void Throws an error and does nothing
- */
-function modify_database($sqlfile='', $sqlstring='') {
- error('modify_database() removed - use new XMLDB functions');
-}
-/**
- * @deprecated
- * @param mixed $field1
- * @param mixed $value1
- * @param mixed $field2
- * @param mixed $value2
- * @param mixed $field3
- * @param mixed $value3
- * @return void Throws an error and does nothing
- */
-function where_clause($field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
- error('where_clause() removed - use new functions with $conditions parameter');
-}
-/**
- * @deprecated
- * @param mixed $sqlarr
- * @param mixed $continue
- * @param mixed $feedback
- * @return void Throws an error and does nothing
- */
-function execute_sql_arr($sqlarr, $continue=true, $feedback=true) {
- error('execute_sql_arr() removed');
-}
-/**
- * @deprecated use $DB->get_records_list() instead
- * @see moodle_database::get_records_list()
- * @param mixed $table
- * @param mixed $field
- * @param mixed $values
- * @param mixed $sort
- * @param mixed $fields
- * @param mixed $limitfrom
- * @param mixed $limitnum
- * @return void Throws an error and does nothing
- */
-function get_records_list($table, $field='', $values='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
- error('get_records_list() removed');
-}
-/**
- * @deprecated use $DB->get_recordset_list() instead
- * @see moodle_database::get_recordset_list()
- * @param mixed $table
- * @param mixed $field
- * @param mixed $values
- * @param mixed $sort
- * @param mixed $fields
- * @param mixed $limitfrom
- * @param mixed $limitnum
- * @return void Throws an error and does nothing
- */
-function get_recordset_list($table, $field='', $values='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
- error('get_recordset_list() removed');
-}
-/**
- * @deprecated use $DB->get_records_menu() instead
- * @see moodle_database::get_records_menu()
- * @param mixed $table
- * @param mixed $field
- * @param mixed $value
- * @param mixed $sort
- * @param mixed $fields
- * @param mixed $limitfrom
- * @param mixed $limitnum
- * @return void Throws an error and does nothing
- */
-function get_records_menu($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
- error('get_records_menu() removed');
-}
-/**
- * @deprecated use $DB->get_records_select_menu() instead
- * @see moodle_database::get_records_select_menu()
- * @param mixed $table
- * @param mixed $select
- * @param mixed $sort
- * @param mixed $fields
- * @param mixed $limitfrom
- * @param mixed $limitnum
- * @return void Throws an error and does nothing
- */
-function get_records_select_menu($table, $select='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
- error('get_records_select_menu() removed');
-}
-/**
- * @deprecated use $DB->get_records_sql_menu() instead
- * @see moodle_database::get_records_sql_menu()
- * @param mixed $sql
- * @param mixed $limitfrom
- * @param mixed $limitnum
- * @return void Throws an error and does nothing
- */
-function get_records_sql_menu($sql, $limitfrom='', $limitnum='') {
- error('get_records_sql_menu() removed');
-}
-/**
- * @deprecated
- * @param mixed $table
- * @param mixed $column
- * @return void Throws an error and does nothing
- */
-function column_type($table, $column) {
- error('column_type() removed');
-}
-/**
- * @deprecated
- * @param mixed $rs
- * @return void Throws an error and does nothing
- */
-function recordset_to_menu($rs) {
- error('recordset_to_menu() removed');
-}
-/**
- * @deprecated
- * @param mixed $records
- * @param mixed $field1
- * @param mixed $field2
- * @return void Throws an error and does nothing
- */
-function records_to_menu($records, $field1, $field2) {
- error('records_to_menu() removed');
-}
-/**
- * @deprecated use $DB->set_field_select() instead
- * @see moodle_database::set_field_select()
- * @param mixed $table
- * @param mixed $newfield
- * @param mixed $newvalue
- * @param mixed $select
- * @param mixed $localcall
- * @return void Throws an error and does nothing
- */
-function set_field_select($table, $newfield, $newvalue, $select, $localcall = false) {
- error('set_field_select() removed');
-}
-/**
- * @deprecated use $DB->get_fieldset_select() instead
- * @see moodle_database::get_fieldset_select()
- * @param mixed $table
- * @param mixed $return
- * @param mixed $select
- * @return void Throws an error and does nothing
- */
-function get_fieldset_select($table, $return, $select) {
- error('get_fieldset_select() removed');
-}
-/**
- * @deprecated use $DB->get_fieldset_sql() instead
- * @see moodle_database::get_fieldset_sql()
- * @param mixed $sql
- * @return void Throws an error and does nothing
- */
-function get_fieldset_sql($sql) {
- error('get_fieldset_sql() removed');
-}
-/**
- * @deprecated use $DB->sql_like() instead
- * @see moodle_database::sql_like()
- * @return void Throws an error and does nothing
- */
-function sql_ilike() {
- error('sql_ilike() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $first
- * @param mixed $last
- * @return void Throws an error and does nothing
- */
-function sql_fullname($first='firstname', $last='lastname') {
- error('sql_fullname() not available anymore');
-}
-/**
- * @deprecated
- * @return void Throws an error and does nothing
- */
-function sql_concat() {
- error('sql_concat() not available anymore');
-}
-/**
- * @deprecated
- * @return void Throws an error and does nothing
- */
-function sql_empty() {
- error('sql_empty() not available anymore');
-}
-/**
- * @deprecated
- * @return void Throws an error and does nothing
- */
-function sql_substr() {
- error('sql_substr() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $int1
- * @param mixed $int2
- * @return void Throws an error and does nothing
- */
-function sql_bitand($int1, $int2) {
- error('sql_bitand() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $int1
- * @return void Throws an error and does nothing
- */
-function sql_bitnot($int1) {
- error('sql_bitnot() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $int1
- * @param mixed $int2
- * @return void Throws an error and does nothing
- */
-function sql_bitor($int1, $int2) {
- error('sql_bitor() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $int1
- * @param mixed $int2
- * @return void Throws an error and does nothing
- */
-function sql_bitxor($int1, $int2) {
- error('sql_bitxor() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $fieldname
- * @param mixed $text
- * @return void Throws an error and does nothing
- */
-function sql_cast_char2int($fieldname, $text=false) {
- error('sql_cast_char2int() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $fieldname
- * @param mixed $numchars
- * @return void Throws an error and does nothing
- */
-function sql_compare_text($fieldname, $numchars=32) {
- error('sql_compare_text() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $fieldname
- * @param mixed $numchars
- * @return void Throws an error and does nothing
- */
-function sql_order_by_text($fieldname, $numchars=32) {
- error('sql_order_by_text() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $fieldname
- * @return void Throws an error and does nothing
- */
-function sql_length($fieldname) {
- error('sql_length() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $separator
- * @param mixed $elements
- * @return void Throws an error and does nothing
- */
-function sql_concat_join($separator="' '", $elements=array()) {
- error('sql_concat_join() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $tablename
- * @param mixed $fieldname
- * @param mixed $nullablefield
- * @param mixed $textfield
- * @return void Throws an error and does nothing
- */
-function sql_isempty($tablename, $fieldname, $nullablefield, $textfield) {
- error('sql_isempty() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $tablename
- * @param mixed $fieldname
- * @param mixed $nullablefield
- * @param mixed $textfield
- * @return void Throws an error and does nothing
- */
-function sql_isnotempty($tablename, $fieldname, $nullablefield, $textfield) {
- error('sql_isnotempty() not available anymore');
-}
-/**
- * @deprecated
- * @return void Throws an error and does nothing
- */
-function begin_sql() {
- error('begin_sql() not available anymore');
-}
-/**
- * @deprecated
- * @return void Throws an error and does nothing
- */
-function commit_sql() {
- error('commit_sql() not available anymore');
-}
-/**
- * @deprecated
- * @return void Throws an error and does nothing
- */
-function rollback_sql() {
- error('rollback_sql() not available anymore');
-}
-/**
- * @deprecated use $DB->insert_record() instead
- * @see moodle_database::insert_record()
- * @param mixed $table
- * @param mixed $dataobject
- * @param mixed $returnid
- * @param mixed $primarykey
- * @return void Throws an error and does nothing
- */
-function insert_record($table, $dataobject, $returnid=true, $primarykey='id') {
- error('insert_record() not available anymore');
-}
-/**
- * @deprecated use $DB->update_record() instead
- * @see moodle_database::update_record()
- * @param mixed $table
- * @param mixed $dataobject
- * @return void Throws an error and does nothing
- */
-function update_record($table, $dataobject) {
- error('update_record() not available anymore');
-}
-/**
- * @deprecated use $DB->get_records() instead
- * @see moodle_database::get_records()
- * @param mixed $table
- * @param mixed $field
- * @param mixed $value
- * @param mixed $sort
- * @param mixed $fields
- * @param mixed $limitfrom
- * @param mixed $limitnum
- *
- * @return void Throws an error and does nothing
- */
-function get_records($table, $field='', $value='', $sort='', $fields='*', $limitfrom='', $limitnum='') {
- error('get_records() not available anymore');
-}
-/**
- * @deprecated use $DB->get_record() instead
- * @see moodle_database::get_record()
- * @param mixed $table
- * @param mixed $field1
- * @param mixed $value1
- * @param mixed $field2
- * @param mixed $value2
- * @param mixed $field3
- * @param mixed $value3
- * @param mixed $fields
- * @return void Throws an error and does nothing
- */
-function get_record($table, $field1, $value1, $field2='', $value2='', $field3='', $value3='', $fields='*') {
- error('get_record() not available anymore');
-}
-/**
- * @deprecated use $DB->set_field() instead
- * @see moodle_database::set_field()
- * @param mixed $table
- * @param mixed $newfield
- * @param mixed $newvalue
- * @param mixed $field1
- * @param mixed $value1
- * @param mixed $field2
- * @param mixed $value2
- * @param mixed $field3
- * @param mixed $value3
- * @return void Throws an error and does nothing
- */
-function set_field($table, $newfield, $newvalue, $field1, $value1, $field2='', $value2='', $field3='', $value3='') {
- error('set_field() not available anymore');
-}
-/**
- * @deprecated use $DB->count_records() instead
- * @see moodle_database::count_records()
- * @param mixed $table
- * @param mixed $field1
- * @param mixed $value1
- * @param mixed $field2
- * @param mixed $value2
- * @param mixed $field3
- * @param mixed $value3
- * @return void Throws an error and does nothing
- */
-function count_records($table, $field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
- error('count_records() not available anymore');
-}
-/**
- * @deprecated use $DB->record_exists() instead
- * @see moodle_database::record_exists()
- * @param mixed $table
- * @param mixed $field1
- * @param mixed $value1
- * @param mixed $field2
- * @param mixed $value2
- * @param mixed $field3
- * @param mixed $value3
- * @return void Throws an error and does nothing
- */
-function record_exists($table, $field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
- error('record_exists() not available anymore');
-}
-/**
- * @deprecated use $DB->delete_records() instead
- * @see moodle_database::delete_records()
- * @param mixed $table
- * @param mixed $field1
- * @param mixed $value1
- * @param mixed $field2
- * @param mixed $value2
- * @param mixed $field3
- * @param mixed $value3
- * @return void Throws an error and does nothing
- */
-function delete_records($table, $field1='', $value1='', $field2='', $value2='', $field3='', $value3='') {
- error('delete_records() not available anymore');
-}
-/**
- * @deprecated use $DB->get_field() instead
- * @see moodle_database::get_field()
- * @param mixed $table
- * @param mixed $return
- * @param mixed $field1
- * @param mixed $value1
- * @param mixed $field2
- * @param mixed $value2
- * @param mixed $field3
- * @param mixed $value3
- * @return void Throws an error and does nothing
- */
-function get_field($table, $return, $field1, $value1, $field2='', $value2='', $field3='', $value3='') {
- error('get_field() not available anymore');
-}
-/**
- * @deprecated
- * @param mixed $table
- * @param mixed $oldfield
- * @param mixed $field
- * @param mixed $type
- * @param mixed $size
- * @param mixed $signed
- * @param mixed $default
- * @param mixed $null
- * @param mixed $after
- * @return void Throws an error and does nothing
- */
-function table_column($table, $oldfield, $field, $type='integer', $size='10',
- $signed='unsigned', $default='0', $null='not null', $after='') {
- error('table_column() was removed, please use new ddl functions');
-}
/**
* @deprecated
* @param mixed $name
return "\$".$this->fix_sql_params_i;
}
+ /**
+ * Detects object parameters and throws exception if found
+ * @param mixed $value
+ * @return void
+ */
+ protected function detect_objects($value) {
+ if (is_object($value)) {
+ throw new coding_exception('Invalid database query parameter value', 'Objects are are not allowed: '.get_class($value));
+ }
+ }
+
/**
* Normalizes sql query parameters and verifies parameters.
* @param string $sql The query or part of it.
// convert table names
$sql = $this->fix_table_names($sql);
- // cast booleans to 1/0 int
+ // cast booleans to 1/0 int and detect forbidden objects
foreach ($params as $key => $value) {
+ $this->detect_objects($value);
$params[$key] = is_bool($value) ? (int)$value : $value;
}
return $text;
}
- /**
- * Returns the proper SQL to do LIKE in a case-insensitive way.
- *
- * Note the LIKE are case sensitive for Oracle. Oracle 10g is required to use
- * the case insensitive search using regexp_like() or NLS_COMP=LINGUISTIC :-(
- * See http://docs.moodle.org/en/XMLDB_Problems#Case-insensitive_searches
- *
- * @deprecated since Moodle 2.0 MDL-23925 - please do not use this function any more.
- * @todo MDL-31280 to remove deprecated functions prior to 2.3 release.
- * @return string Do not use this function!
- * @see sql_like()
- */
- public function sql_ilike() {
- debugging('sql_ilike() is deprecated, please use sql_like() instead');
- return 'LIKE';
- }
-
/**
* Returns the proper SQL to do CONCAT between the elements(fieldnames) passed.
*