// extract and sanitize the auth key explicitly
$modules = get_list_of_plugins("auth");
if (in_array($config['auth'], $modules)) {
- $auth = $config['auth'];
+ $auth = $config['auth'];
} else {
notify("Error defining the authentication method");
}
if (preg_match('/^pluginconfig_(.+?)$/', $name, $matches)) {
$plugin = "auth/$auth";
$name = $matches[1];
- if (! set_config($name, $value, $plugin)) {
+ if (! set_config($name, $value, $plugin)) {
notify("Problem saving config $name as $value for plugin $plugin");
}
- } else { // normal handling for
+ } else { // normal handling for
if (! set_config($name, $value)) {
notify("Problem saving config $name as $value");
}
echo "<form target=\"{$CFG->framename}\" name=\"authmenu\" method=\"post\" action=\"auth.php\">";
echo "<input type=\"hidden\" name=\"sesskey\" value=\"".$USER->sesskey."\" />";
print_string("chooseauthmethod","auth");
-
+
echo ' ';
choose_from_menu ($options, "auth", $auth, "","document.location='auth.php?sesskey=$USER->sesskey&auth='+document.authmenu.auth.options[document.authmenu.auth.selectedIndex].value", "");
require_once("$CFG->dirroot/auth/$auth/config.html");
$CFG->pagepath = 'auth/' . $auth;
-
+
echo '<tr><td colspan="3">';
print_heading(get_string('auth_common_settings', 'auth'));
echo '<td/></tr>';
// Good enough for most auth plugins
// but some may want a custom one if they are offering
// other options
-// Note: pluginconfig_ fields have special handling.
+// Note: pluginconfig_ fields have special handling.
function print_auth_lock_options ($auth, $user_fields, $helptext, $retrieveopts, $updateopts) {
echo '<tr><td colspan="3">';
'onlogin' => get_string('update_onlogin', 'auth'));
$updateextoptions = array('0' => get_string('update_never', 'auth'),
'1' => get_string('update_onupdate', 'auth'));
-
+
$pluginconfig = get_config("auth/$auth");
-
+
// helptext is on a field with rowspan
if (empty($helptext)) {
$helptext = ' ';
}
if(empty($pluginconfig->{"field_updatelocal_$field"})) {
$pluginconfig->{"field_updatelocal_$field"} = '';
- }
+ }
if (empty($pluginconfig->{"field_updateremote_$field"})) {
$pluginconfig->{"field_updateremote_$field"} = '';
}
//First of all we check that everything is correct
//Check for trailing slash and backslash in backup_sche_destination
- if (!empty($backup_sche_destination) and
+ if (!empty($backup_sche_destination) and
(substr($backup_sche_destination,-1) == "/" or substr($backup_sche_destination,-1) == "\\")) {
$error = true;
$sche_destination_error = get_string("pathslasherror");
if (isset($a_config[$tocheck])) {
$temp .= "1";
} else {
- $temp .= "0";
+ $temp .= "0";
}
unset($a_config[$tocheck]);
$i++;
foreach ($courses as $course) {
//We check if the course exists in backup_course
$backup_course = get_record("backup_courses","courseid",$course->id);
- //If it doesn't exist, create
+ //If it doesn't exist, create
if (!$backup_course) {
$temp_backup_course->courseid = $course->id;
$newid = insert_record("backup_courses",$temp_backup_course);
//Check for required functions...
if (!function_exists('utf8_encode')) {
notify("You need to add XML support to your PHP installation");
- }
+ }
include ("$CFG->dirroot/backup/config.html");
print_simple_box_end();
require_once($CFG->libdir.'/blocklib.php');
$blockid = required_param('block', PARAM_INT);
-
+
if(($blockrecord = blocks_get_record($blockid)) === false) {
error('This block does not exist');
}
$strconfiguration = get_string('configuration');
$strmanageblocks = get_string('manageblocks');
$strblockname = $block->get_title();
-
+
// $CFG->pagepath is used to generate the body and id attributes for the body tag
// of the page. It is also used to generate the link to the Moodle Docs for this view.
$CFG->pagepath = 'block/' . $block->name() . '/config';
-
+
admin_externalpage_print_header($adminroot);
print_heading(get_string('incompatibleblocks', 'admin'));
$table = new flexible_table('admin-blocks-incompatible');
-
+
$table->define_columns(array('block', 'delete'));
$table->define_headers(array($strname, $strdelete));
$table->define_baseurl($CFG->wwwroot.'/'.$CFG->admin.'/blocks.php');
-
+
$table->set_attribute('cellspacing', '0');
$table->set_attribute('id', 'incompatible');
$table->set_attribute('class', 'generaltable generalbox');
-
+
$table->setup();
foreach ($incompatible as $block) {
}
closedir($dir);
}
-
+
?>
$enrol = optional_param('enrol', $CFG->enrol, PARAM_SAFEDIR);
$CFG->pagepath = 'enrol';
-
+
$adminroot = admin_get_root();
admin_externalpage_setup('enrolment', $adminroot);
if ($frm = data_submitted()) {
if (!confirm_sesskey()) {
error(get_string('confirmsesskeybad', 'error'));
- }
+ }
if (empty($frm->enable)) {
$frm->enable = array();
}
require_once("../config.php");
require_once($CFG->libdir.'/adminlib.php');
-
+
$adminroot = admin_get_root();
admin_externalpage_setup('enrolment', $adminroot);
if ($frm = data_submitted()) {
if (!confirm_sesskey()) {
error(get_string('confirmsesskeybad', 'error'));
- }
+ }
if ($enrolment->process_config($frm)) {
redirect("enrol.php?sesskey=$USER->sesskey", get_string("changessaved"), 1);
}
"document.location='enrol_config.php?enrol='+document.enrolmenu.enrol.options[document.enrolmenu.enrol.selectedIndex].value", "");
echo "</b></p></div>";
-
-/// Print current enrolment type description
+
+/// Print current enrolment type description
print_simple_box_start("center", "80%");
print_heading($options[$enrol]);
print_simple_box_end();
echo "<hr />";
-
+
$enrolment->config_form($frm);
echo "<center><p><input type=\"submit\" value=\"".get_string("savechanges")."\"></p></center>\n";
// $CFG->pagepath is used to generate the body and id attributes for the body tag
// of the page. It is also used to generate the link to the Moodle Docs for this view.
$CFG->pagepath = 'filter/' . $filtername . '/config';
-
+
// get translated strings for use on page
$txt = new Object;
$txt->managefilters = get_string( 'managefilters' );
//==============================
// Display logic
//==============================
-
+
$filtername = ucfirst($filtername);
admin_externalpage_print_header($adminroot);
print_heading( $filtername );
}
function exists() {
if (!$this->is_enabled()) {
- return true;
+ return true;
}
if ($this->status() < 1) {
return true;
function severity() {
if ($this->is_enabled() and $this->status() == 0) {
return SEVERITY_SIGNIFICANT;
- } else {
+ } else {
return SEVERITY_ANNOYANCE;
}
}
global $CFG;
$desc = 'Slasharguments are needed for relative linking in uploaded resources:<ul>';
if (!$this->is_enabled()) {
- $desc .= '<li>slasharguments are <strong>disabled</strong> in Moodle configuration</li>';
+ $desc .= '<li>slasharguments are <strong>disabled</strong> in Moodle configuration</li>';
} else {
- $desc .= '<li>slasharguments are enabled in Moodle configuration</li>';
+ $desc .= '<li>slasharguments are enabled in Moodle configuration</li>';
}
if ($this->status() == -1) {
$desc .= '<li>can not run automatic test, you can verify it <a href="'.$CFG->wwwroot.'/file.php/testslasharguments" target="_blank">here</a> manually</li>';
$solution .= 'Congratulations - everything seems OK now :-D';
}
if ($status < 1) {
- $solution .= '<p>IIS:<ul><li>try to add <code>cgi.fix_pathinfo=1</code> to php.ini</li><li>do NOT enable AllowPathInfoForScriptMappings !!!</li><li>slasharguments may not work when using ISAPI and PHP 4.3.10 and older</li></ul></p>';
- $solution .= '<p>Apache 1:<ul><li>try to add <code>cgi.fix_pathinfo=1</code> to php.ini</li></ul></p>';
- $solution .= '<p>Apache 2:<ul><li>you must add <code>AcceptPathInfo on</code> to php.ini or .htaccess</li><li>try to add <code>cgi.fix_pathinfo=1</code> to php.ini</li></ul></p>';
+ $solution .= '<p>IIS:<ul><li>try to add <code>cgi.fix_pathinfo=1</code> to php.ini</li><li>do NOT enable AllowPathInfoForScriptMappings !!!</li><li>slasharguments may not work when using ISAPI and PHP 4.3.10 and older</li></ul></p>';
+ $solution .= '<p>Apache 1:<ul><li>try to add <code>cgi.fix_pathinfo=1</code> to php.ini</li></ul></p>';
+ $solution .= '<p>Apache 2:<ul><li>you must add <code>AcceptPathInfo on</code> to php.ini or .htaccess</li><li>try to add <code>cgi.fix_pathinfo=1</code> to php.ini</li></ul></p>';
}
return $solution;
}
blocks_execute_action($page, blocks_get_by_page($page), 'add', (int)$admintree->id, false, false);
if ($admintreeinstance = get_record('block_instance', 'pagetype', $page->type, 'pageid', SITEID, 'blockid', $admintree->id)) {
blocks_execute_action($page, blocks_get_by_page($page), 'moveleft', $admintreeinstance, false, false);
- }
+ }
}
set_config('adminblocks_initialised', 1);
}
/// Check for any special upgrades that might need to be run
- if (!empty($CFG->upgrade)) {
+ if (!empty($CFG->upgrade)) {
print_simple_box(get_string("upgrade$CFG->upgrade", "admin",
"$CFG->wwwroot/$CFG->admin/upgrade$CFG->upgrade.php"), "center", '60%');
print_spacer(10,10);
}
/// Print slightly annoying registration button every six months ;-)
-/// You can set the "registered" variable to something far in the future
+/// You can set the "registered" variable to something far in the future
/// if you really want to prevent this. eg 9999999999
if (!isset($CFG->registered) || $CFG->registered < (time() - 3600*24*30*6)) {
$options = array();
$table->cellpadding = 5;
$table->cellspacing = 0;
$table->width = '40%';
-
+
$configdata = '<div class="adminlink"><a href="config.php">'.get_string('configvariables', 'admin').
'</a> - <span class="explanation">'.get_string('adminhelpconfigvariables').'</span></div>';
$configdata .= '<div class="adminlink"><a href="site.php">'.get_string('sitesettings').
'</a> - <span class="explanation">'.get_string('helpcalendarsettings', 'admin').'</span></div>';
$configdata .= '<div class="adminlink"><a href="maintenance.php">'.get_string('sitemaintenancemode', 'admin').
'</a> - <span class="explanation">'.get_string('helpsitemaintenance', 'admin').'</span></div>';
-
+
$table->data[] = array('<strong>'.get_string('configuration').'</strong>', $configdata);
-
+
$userdata = '<div class="adminlink"><a href="auth.php?sesskey='.$USER->sesskey.'">'.get_string("authentication").
'</a> - <span class="explanation">'.get_string('adminhelpauthentication').'</span></div>';
$userdata .= '<div class="adminlink"><a href="user.php">'.get_string('edituser').
$userdata .= '<div class="adminlink"><a href="roles/assign.php?contextid='.$context->id.'">'.
get_string('assignsiteroles').'</a> - <span class="explanation">'.get_string('adminhelpassignsiteroles').
'</span></div>';
-
+
$table->data[] = array('<strong>'.get_string('users').'</strong>', $userdata);
-
+
$coursedata = '<div class="adminlink"><a href="../course/index.php?edit=on&sesskey='.$USER->sesskey.'">'.get_string('managecourses').
'</a> - <span class="explanation">'.get_string('adminhelpcourses').'</span></div>';
$coursedata .= '<div class="adminlink"><a href="enrol.php?sesskey='.$USER->sesskey.'">'.get_string('enrolmentplugins').
'</a> - <span class="explanation">'.get_string('adminhelpenrolments').'</span></div>';
-
-
+
+
$table->data[] = array('<strong>'.get_string('courses').'</strong>', $coursedata);
-
+
$miscdata = '<div class="adminlink"><a href="../files/index.php?id='.$site->id.'">'.get_string('sitefiles').
'</a> - <span class="explanation">'.get_string('adminhelpsitefiles').'</span></div>';
$miscdata .= '<div class="adminlink"><a href="stickyblocks.php">'.get_string('stickyblocks','admin').
$miscdata .= '<div class="adminlink"><a href="xmldb/index.php">'.get_string('xmldbeditor').
'</a> - <span class="explanation">'.get_string('adminhelpxmldbeditor').'</span></div>';
}
-
+
$table->data[] = array('<strong>'.get_string('miscellaneous').'</strong>', $miscdata);
-
-/*
- /// Hooks for Matt Oquists contrib code for repositories and portfolio.
+
+/*
+ /// Hooks for Matt Oquists contrib code for repositories and portfolio.
/// The eventual official versions may not look like this
if (isset($CFG->portfolio) && file_exists("$CFG->dirroot/$CFG->portfolio")) {
$table->data[] = array("<strong><a href=\"../portfolio/\">".get_string('portfolio','portfolio').'</a></
strong>',
'<div class="explanation">'.get_string('adminhelpportfolio','portfolio').'</div>');
}
-
+
if (isset($CFG->repo) && file_exists("$CFG->dirroot/$CFG->repo")) {
$table->data[] = array("<strong><a href=\"../repository/?repoid=1&action=list\">".get_string('repository','
repository').'</a></strong>',
'<div class="explanation">'.get_string('adminhelprepository','repository').'</div>');
}
-*/
-
-
+*/
+
+
print_table($table);
-
+
}
//////////////////////////////////////////////////////////////////////////////////////////////////
echo '</div>';
}
-
+
if (optional_param('dbmigrate')) { // ??? Is this actually used?
print_simple_box_start('center','60%');
require_once($CFG->dirroot.'/admin/utfdbmigrate.php');
$strconfiguration = get_string("configuration");
$strmanagemodules = get_string("managemodules");
$strmodulename = get_string("modulename", $module);
-
+
// $CFG->pagepath is used to generate the body and id attributes for the body tag
// of the page. It is also used to generate the link to the Moodle Docs for this view.
$CFG->pagepath = 'mod/' . $module . '/config';
-
+
admin_externalpage_print_header($adminroot);
print_heading($strmodulename);
admin_externalpage_print_header($adminroot);
print_heading($stractivities);
-
+
$coursesaffected = false;
-
+
/// If data submitted, then process and store.
}
if (!empty($delete) and confirm_sesskey()) {
-
+
$strmodulename = get_string("modulename", "$delete");
if (!$confirm) {
- notice_yesno(get_string("moduledeleteconfirm", "", $strmodulename),
- "modules.php?delete=$delete&confirm=1&sesskey=$USER->sesskey",
+ notice_yesno(get_string("moduledeleteconfirm", "", $strmodulename),
+ "modules.php?delete=$delete&confirm=1&sesskey=$USER->sesskey",
"modules.php");
admin_externalpage_print_footer($adminroot);
exit;
notify("Error occurred while deleting all $strmodulename records in course_modules table");
}
- // Then delete all the logs
+ // Then delete all the logs
if (!delete_records("log", "module", $module->name)) {
notify("Error occurred while deleting all $strmodulename records in log table");
}
}
}
}
- }
+ }
// Delete the capabilities that were defined by this module
capabilities_cleanup('mod/'.$module->name);
-
+
// rebuild_course_cache(); // Because things have changed
$coursesaffected = true;
notice(get_string("moduledeletefiles", "", $a), "modules.php");
}
}
-
+
if ($coursesaffected) {
rebuild_course_cache(); // Because things have changed
}
-
+
/// Get and sort the existing modules
<?PHP // $Id$
// Allows the admin to manage questiontypes
// This page is adapted from modules.php
-
+
// This page is not yet in service, the whole plug-in architecture
// for question types is still under construction.
$strquestions = get_string("questions");
$strquestiontype = get_string("questiontype", 'quiz');
- print_header("$site->shortname: $strquestions", "$site->fullname",
+ print_header("$site->shortname: $strquestions", "$site->fullname",
"<a href=\"index.php\">$stradministration</a> -> ".
"<a href=\"configure.php\">$strconfiguration</a> -> $strquestions");
print_heading($strquestions);
-
+
/// If data submitted, then process and store.
}
if (!empty($delete) and confirm_sesskey()) {
-
+
$strqtypename = get_string("qtypename", "qtype_$delete");
if (!$confirm) {
- notice_yesno(get_string("qtypedeleteconfirm", "admin", $strqtypename),
- "questiontypes.php?delete=$delete&confirm=1&sesskey=$USER->sesskey",
+ notice_yesno(get_string("qtypedeleteconfirm", "admin", $strqtypename),
+ "questiontypes.php?delete=$delete&confirm=1&sesskey=$USER->sesskey",
"questiontypes.php");
print_footer();
exit;
}
}
}
- }
+ }
$a->qtype = $strqtypename;
$a->directory = "$CFG->dirroot/qtype/$delete";
$count = count_records('quiz_questions', 'qtype', $qtype->id);
$delete = $count ? '' : "<a href=\"questiontypes.php?delete=$qtype->name&sesskey=$USER->sesskey\">$strdelete</a>";
-
+
if ($qtype->visible) {
$visible = "<a href=\"questiontypes.php?hide=$qtype->name&sesskey=$USER->sesskey\" title=\"$strhide\">".
"<img src=\"$CFG->pixpath/i/hide.gif\" align=\"middle\" height=\"16\" width=\"16\" border=\"0\" alt=\"\" /></a>";
$strcourseoverview = get_string('courseoverview');
$strnav = '<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/index.php">'.get_string('administration').'</a> -> <a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/report.php">'.$strreports.'</a> -> '.$strcourseoverview;
-
+
$reportoptions = stats_get_report_options($course->id,STATS_MODE_RANKED);
$tableprefix = $CFG->prefix.'stats_';
$earliestday = get_field_sql('SELECT timeend FROM '.$tableprefix.'daily ORDER BY timeend LIMIT 1');
$earliestweek = get_field_sql('SELECT timeend FROM '.$tableprefix.'weekly ORDER BY timeend LIMIT 1');
$earliestmonth = get_field_sql('SELECT timeend FROM '.$tableprefix.'monthly ORDER BY timeend LIMIT 1');
-
+
if (empty($earliestday)) $earliestday = time();
if (empty($earliestweek)) $earliestweek = time();
if (empty($earliestmonth)) $earliestmonth = time();
if (!empty($report) && !empty($time)) {
$param = stats_get_parameters($time,$report,SITEID,STATS_MODE_RANKED);
-
+
$sql = "SELECT courseid,".$param->fields." FROM ".$CFG->prefix.'stats_'.$param->table
." WHERE timeend >= ".$param->timeafter
." GROUP BY courseid "
.$param->extras
." ORDER BY ".$param->orderby
." LIMIT ".$numcourses;
-
+
$courses = get_records_sql($sql);
if (empty($courses)) {
}
echo '<center><img src="'.$CFG->wwwroot.'/'.$CFG->admin.'/report/courseoverview/reportsgraph.php?time='.$time.'&report='.$report.'&numcourses='.$numcourses.'" /></center>';
-
+
$table = new object();
$table->align = array('left','center','center','center');
$table->head = array(get_string('course'),$param->line1);
if (!empty($param->line2)) {
- $table->head[] = $param->line2;
+ $table->head[] = $param->line2;
}
if (!empty($param->line3)) {
$table->head[] = $param->line3;
}
-
+
foreach ($courses as $c) {
$a = array();
$a[] = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$c->courseid.'">'.get_field('course','shortname','id',$c->courseid).'</a>';
}
print_table($table);
}
-
+
admin_externalpage_print_footer($adminroot);
?>
require_login();
require_capability('moodle/site:viewreports', get_context_instance(CONTEXT_SYSTEM, SITEID));
-
+
stats_check_uptodate($course->id);
$param = stats_get_parameters($time,$report,SITEID,STATS_MODE_RANKED);
.$param->extras
." ORDER BY ".$param->orderby
." LIMIT ".$numcourses;
-
+
$courses = get_records_sql($sql);
-
+
if (empty($courses)) {
error(get_string('statsnodata'),$CFG->wwwroot.'/'.$CFG->admin.'/report/course/index.php');
}
-
+
$graph = new graph(750,400);
$graph->y_format['bar1'] = array('colour' => 'blue','bar' => 'fill','legend' => $param->{$param->graphline});
$graph->draw_stack();
-
+
?>
print_heading(get_string('chooselogs') .':');
- print_log_selector_form($course);
+ print_log_selector_form($course);
echo '<br />';
print_heading(get_string('chooselivelogs') .':');
// Options set when the class is created.
var $showpasses;
-
+
// Lang strings. Set in the constructor.
var $strrunonlyfolder;
var $strrunonlyfile;
-
+
var $strseparator;
-
+
/**
* Constructor.
- *
+ *
* @param bool $showpasses Whether this reporter should output anything for passes.
*/
function ExHtmlReporter($showpasses) {
global $CFG;
-
+
$this->HtmlReporter();
$this->showpasses = $showpasses;
-
+
$this->strrunonlyfolder = $this->get_string('runonlyfolder');
$this->strrunonlyfile = $this->get_string('runonlyfile');
$this->strseparator = ' <img src="' . $CFG->pixpath . '/a/r_breadcrumb.gif" class="resize" alt="" /> ';
*/
function _paintPassFail($passorfail, $message) {
global $FULLME, $CFG;
-
+
print_simple_box_start('', '100%', '', 5, $passorfail . ' generalbox');
$url = $this->_htmlEntities($this->_stripParameterFromUrl($FULLME, 'path'));
echo '<b class="', $passorfail, '">', $this->get_string($passorfail), '</b>: ';
print_simple_box_end();
flush();
}
-
+
/**
* Called when a notice needs to be output.
*/
echo $this->get_string('summary', $summarydata);
echo '</div>';
- echo '<div class="performanceinfo">',
+ echo '<div class="performanceinfo">',
$this->get_string('runat', date('<b>d-m-Y H:i T</b>')),
$this->get_string('version', SimpleTestOptions::getVersion()),
'</div>';
}
-
+
/**
* Strip a specified parameter from the query string of a URL, if present.
- * Adds a separator to the end of the URL, so that a new parameter
+ * Adds a separator to the end of the URL, so that a new parameter
* can easily be appended. For example (assuming $param = 'frog'):
- *
+ *
* http://example.com/index.php -> http://example.com/index.php?
* http://example.com/index.php?frog=1 -> http://example.com/index.php?
* http://example.com/index.php?toad=1 -> http://example.com/index.php?toad=1&
* http://example.com/index.php?frog=1&toad=1 -> http://example.com/index.php?toad=1&
- *
+ *
* @param string $url the URL to modify.
* @param string $param the parameter to strip from the URL, if present.
- *
+ *
* @return string The modified URL.
*/
function _stripParameterFromUrl($url, $param) {
if ($file != 'CVS' && !in_array($file_path, $this->ignorefolders)) {
$this->_recurseFolders($file_path);
}
- } elseif (preg_match('/simpletest(\/|\\\\)test.*\.php$/', $file_path) ||
+ } elseif (preg_match('/simpletest(\/|\\\\)test.*\.php$/', $file_path) ||
($this->thorough && preg_match('/simpletest(\/|\\\\)slowtest.*\.php$/', $file_path))) {
$s_count++;
if (!is_null($path)) {
// Create the group of tests.
$test =& new AutoGroupTest($showsearch, $thorough);
-
- // OU specific. We use the _nonproject folder for stuff we want to
+
+ // OU specific. We use the _nonproject folder for stuff we want to
// keep in CVS, but which is not really relevant. It does no harm
// to leave this here.
$test->addIgnoreFolder($CFG->dirroot . '/_nonproject');
-
+
// Make the reporter, which is what displays the results.
$reporter = new ExHtmlReporter($showpasses);
-
+
if ($showsearch) {
print_heading('Searching for test cases');
}
flush();
-
+
// Work out what to test.
if (substr($path, 0, 1) == '/') {
$path = substr($path, 1);
print_simple_box(get_string('pathdoesnotexist', $langfile, $path), '', '', '', '', 'errorbox');
$ok = false;
}
-
+
// If we have something to test, do it.
if ($ok) {
if ($path == $CFG->dirroot) {
}
require_capability('moodle/site:viewreport', get_context_instance(CONTEXT_COURSE, $course->id));
-
- add_to_log($course->id, "course", "report stats", "report/stats/index.php?course=$course->id", $course->id);
+
+ add_to_log($course->id, "course", "report stats", "report/stats/index.php?course=$course->id", $course->id);
stats_check_uptodate($course->id);
-
-
+
+
// $strreports = get_string("reports");
// $strstats = get_string('stats');
//
// <a href=\"{$CFG->wwwroot}/admin/report.php\">$strreports</a> ->
// $strstats";
-// print_header("$course->shortname: $strstats", "$course->fullname",
+// print_header("$course->shortname: $strstats", "$course->fullname",
// $crumb, '', '', true, ' ', $menu);
-
-
+
+
require_once($CFG->dirroot.'/course/report/stats/report.php');
-
+
admin_externalpage_print_footer($adminroot);
?>
<?php
/**
- * this page defines what roles can access (grant user that role and override that roles'
- * capabilities in different context. For example, we can say that Teachers can only grant
+ * this page defines what roles can access (grant user that role and override that roles'
+ * capabilities in different context. For example, we can say that Teachers can only grant
* student role or modify student role's capabilities. Note that you need both the right
* capability moodle/roles:assign or moodle/roles:manage and this database table roles_deny_grant
* to be able to grant roles. If a user has moodle/roles:manage at site level assignment
$site = get_site();
$stradministration = get_string('administration');
$strmanageroles = get_string('manageroles');
-
+
/// form processiong here
/// get all roles
-
+
$roles = get_records('role');
if ($grant = data_submitted()) {
-
+
foreach ($grant as $grole => $val) {
if ($grole == 'dummy') {
- continue;
+ continue;
}
-
+
$string = explode('_', $grole);
$temp[$string[1]][$string[2]] = 1; // if set, means can access
}
}
} else { //if set, means can access, attempt to remove it from db
delete_records('role_allow_assign', 'roleid', $srole->id, 'allowassign', $trole->id);
- }
+ }
}
}
}
$table->cellspacing = 0;
$table->width = '90%';
$table->align[] = 'right';
-
+
/// get all the roles identifier
foreach ($roles as $role) {
$rolesname[] = format_string($role->name);
$roleids[] = $role->id;
$table->align[] = 'center';
$table->wrap[] = 'nowrap';
- }
-
+ }
+
$table->head = array_merge(array(''), $rolesname);
-
+
foreach ($roles as $role) {
$beta = get_box_list($role->id, $roleids);
$table->data[] = array_merge(array(format_string($role->name)), $beta);
}
print_simple_box(get_string('configallowassign', 'admin'), 'center');
-
+
echo '<form action="allowassign.php" method="post">';
print_table($table);
echo '<div class="singlebutton"><input type="submit" value="'.get_string('savechanges').'"/></div>';
echo '<input type="hidden" name="dummy" value="1" />'; // this is needed otherwise we do not know a form has been submitted
echo '</form>';
-
+
admin_externalpage_print_footer($adminroot);
function get_box_list($roleid, $arraylist){
-
+
foreach ($arraylist as $targetid) {
if (get_record('role_allow_assign', 'roleid', $roleid, 'allowassign', $targetid)) {
$array[] = '<input type="checkbox" name="s_'.$roleid.'_'.$targetid.'" value="1" checked="checked"/>';
} else {
- $array[] = '<input type="checkbox" name="s_'.$roleid.'_'.$targetid.'" value="1" />';
+ $array[] = '<input type="checkbox" name="s_'.$roleid.'_'.$targetid.'" value="1" />';
}
}
return $array;
<?php
/**
- * this page defines what roles can override (override roles in different context. For example,
+ * this page defines what roles can override (override roles in different context. For example,
* we can say that Admin can override teacher roles in a course
* To be able to override roles. If a user has moodle/roles:overrde at context level
* and be in the roles_allow_override table.
$site = get_site();
$stradministration = get_string('administration');
$strmanageroles = get_string('manageroles');
-
+
/// form processiong here
/// get all roles
-
+
$roles = get_records('role');
if ($grant = data_submitted()) {
-
+
foreach ($grant as $grole => $val) {
if ($grole == 'dummy') {
- continue;
+ continue;
}
-
+
$string = explode('_', $grole);
$temp[$string[1]][$string[2]] = 1; // if set, means can access
}
}
} else { //if set, means can access, attempt to remove it from db
delete_records('role_allow_override', 'roleid', $srole->id, 'allowoverride', $trole->id);
- }
+ }
}
}
}
/// displaying form here
admin_externalpage_print_header($adminroot);
-
+
$currenttab='allowoverride';
require_once('managetabs.php');
$table->cellspacing = 0;
$table->width = '90%';
$table->align[] = 'right';
-
+
/// get all the roles identifier
foreach ($roles as $role) {
$rolesname[] = format_string($role->name);
$roleids[] = $role->id;
$table->align[] = 'center';
$table->wrap[] = 'nowrap';
- }
-
+ }
+
$table->head = array_merge(array(''), $rolesname);
-
+
foreach ($roles as $role) {
$beta = get_box_list($role->id, $roleids);
$table->data[] = array_merge(array(format_string($role->name)), $beta);
}
print_simple_box(get_string('configallowoverride', 'admin'), 'center');
-
+
echo '<form action="allowoverride.php" method="post">';
print_table($table);
echo '<div class="singlebutton"><input type="submit" value="'.get_string('savechanges').'"/></div>';
// returns array
function get_box_list($roleid, $arraylist){
-
+
foreach ($arraylist as $targetid) {
if (get_record('role_allow_override', 'roleid', $roleid, 'allowoverride', $targetid)) {
$array[] = '<input type="checkbox" name="s_'.$roleid.'_'.$targetid.'" value="1" checked="checked"/>';
} else {
- $array[] = '<input type="checkbox" name="s_'.$roleid.'_'.$targetid.'" value="1" />';
+ $array[] = '<input type="checkbox" name="s_'.$roleid.'_'.$targetid.'" value="1" />';
}
}
return $array;
onFocus="document.studentform.add.disabled=true;
document.studentform.remove.disabled=false;
document.studentform.addselect.selectedIndex=-1;" />
- <?php
+ <?php
foreach ($contextusers as $contextuser) {
$fullname = fullname($contextuser, true);
echo "<option value=\"$contextuser->id\">".$fullname.", ".$contextuser->email."</option>\n";
}
?>
-
+
</select></td>
<td valign="top">
<br />
document.studentform.remove.disabled=true;
document.studentform.removeselect.selectedIndex=-1;">
<?php
-
+
if (!empty($searchusers)) {
echo "<optgroup label=\"$strsearchresults (" . count($searchusers) . ")\">\n";
foreach ($searchusers as $user) {
?>
</select>
<br />
- <input type="text" name="searchtext" size="30" value="<?php p($searchtext, true) ?>"
+ <input type="text" name="searchtext" size="30" value="<?php p($searchtext, true) ?>"
onFocus ="document.studentform.add.disabled=true;
document.studentform.remove.disabled=true;
document.studentform.removeselect.selectedIndex=-1;
$strshowall = get_string('showall');
$strparticipants = get_string('participants');
-
+
/// Make sure this user can assign that role
if ($roleid) {
if (!user_can_assign($context, $roleid)) {
error ('you can not override this role in this context');
- }
+ }
}
if ($userid) {
print_header("$fullname", "$fullname",
"<a href=\"../course/view.php?id=$course->id\">$course->shortname</a> ->
<a href=\"".$CFG->wwwroot."/user/index.php?id=$course->id\">$strparticipants</a> -> <a href=\"".$CFG->wwwroot."/user/view.php?id=".$userid."&course=".$courseid."\">$fullname</a> ->".$straction,
- "", "", true, " ", navmenu($course));
-
- /// site header
+ "", "", true, " ", navmenu($course));
+
+ /// site header
} else {
print_header("$course->fullname: $fullname", "$course->fullname",
- "<a href=\"".$CFG->wwwroot."/user/view.php?id=".$userid."&course=".$courseid."\">$fullname</a> -> $straction", "", "", true, " ", navmenu($course));
+ "<a href=\"".$CFG->wwwroot."/user/view.php?id=".$userid."&course=".$courseid."\">$fullname</a> -> $straction", "", "", true, " ", navmenu($course));
}
-
+
$showroles = 1;
$currenttab = 'assign';
include_once($CFG->dirroot.'/user/tabs.php');
$existinguserarray = array();
if (!$contextusers = get_role_users($roleid, $context)) {
- $contextusers = array();
+ $contextusers = array();
}
foreach ($contextusers as $contextuser) {
$existinguserarray[] = $contextuser->id;
}
-
+
$existinguserlist = implode(',', $existinguserarray);
unset($existinguserarray);
}
}
-
+
if ($roleid) {
/// prints a form to swap roles
echo '<form name="rolesform" action="assign.php" method="post">';
$table->head = array(get_string('roles', 'role'), get_string('users'));
$table->wrap = array('nowrap', 'nowrap');
$table->align = array('right', 'center');
-
+
foreach ($assignableroles as $roleid => $rolename) {
$countusers = 0;
if ($contextusers = get_role_users($roleid, $context)) {
}
$table->data[] = array('<a href="assign.php?contextid='.$context->id.'&roleid='.$roleid.$userparam.'">'.$rolename.'</a>', $countusers);
}
-
+
print_table($table);
}
<br />
<?php print_string('roledescription', 'role'); ?>:
<?php print_textarea($usehtmleditor, 10, 50, 50, 10, 'description', $role->description); ?>
-<p>
+<p>
<table>
<tr>
<td><?php print_string('capability','role') ?></td>
<td><?php print_string('risks','role') ?></td>
</tr>
-<?php
+<?php
// init these 2
$contextlevel = 0;
$component = '';
foreach ($capabilities as $capability) {
- // prints a breaker if component or name or context level
+ // prints a breaker if component or name or context level
if ($capability->component != $component or $capability->contextlevel != $contextlevel) {
echo ('<tr><td colspan="4"><strong>'.
- get_component_string($capability->component, $capability->contextlevel).'</strong></td></tr>');
+ get_component_string($capability->component, $capability->contextlevel).'</strong></td></tr>');
}
// these 2 are used to see to group same mod/core capabilities together
?></td>
</tr>
-<?php } ?>
-</table>
+<?php } ?>
+</table>
</p>
<br />
<input type="submit" value="<?php p($submitlabel); ?>" />
if ($roleid && $action!='delete') {
$role = get_record('role', 'id', $roleid);
- $editingstr = '-> '.get_string('editinga', '', $role->name);
+ $editingstr = '-> '.get_string('editinga', '', $role->name);
} else {
- $editingstr ='';
+ $editingstr ='';
}
admin_externalpage_print_header($adminroot);
switch ($action) {
case 'add':
- $newrole = create_role($name, $shortname, $description);
+ $newrole = create_role($name, $shortname, $description);
$ignore = array('roleid', 'sesskey', 'action', 'name', 'description', 'contextid');
$data = data_submitted();
foreach ($data as $capname => $value) {
- if (in_array($capname, $ignore)) {
+ if (in_array($capname, $ignore)) {
continue;
}
$data = data_submitted();
foreach ($data as $capname => $value) {
- if (in_array($capname, $ignore)) {
+ if (in_array($capname, $ignore)) {
continue;
}
$localoverride->permission = $value;
$localoverride->timemodified = time();
$localoverride->modifierid = $USER->id;
- update_record('role_capabilities', $localoverride);
+ update_record('role_capabilities', $localoverride);
}
} else { // insert a record
assign_capability($capname, $value, $roleid, $sitecontext->id);
$role->id = $roleid;
$role->name = $name;
- $role->description = $description;
+ $role->description = $description;
if (!update_record('role', $role)) {
error('Could not update role!');
break;
case 'delete':
- if ($confirm) { // deletes a role
+ if ($confirm) { // deletes a role
// check for depedencies XXX TODO
echo ('<input type="hidden" name="roleid" value="'.$roleid.'">');
echo ('<input type="hidden" name="sesskey" value="'.sesskey().'">');
echo ('<input type="hidden" name="confirm" value="1">');
- notice_yesno(get_string('deleterolesure', 'role'),
+ notice_yesno(get_string('deleterolesure', 'role'),
'manage.php?action=delete&roleid='.$roleid.'&sesskey='.sesskey().'&confirm=1', 'manage.php');
admin_externalpage_print_footer($adminroot);
exit;
}
- break;
+ break;
/// add possible positioning switch here
default:
- break;
+ break;
}
if ($roleid) {
$action='edit';
$role = get_record('role', 'id', $roleid);
- } else {
- $action='add';
+ } else {
+ $action='add';
$role->name='';
$role->shortname='';
$role->description='';
$table->cellspacing = 0;
$table->width = '90%';
- $table->head = array(get_string('roles', 'role'),
- get_string('description'),
+ $table->head = array(get_string('roles', 'role'),
+ get_string('description'),
get_string('delete'));
/*************************
$table->data[] = array('<a href="manage.php?roleid='.$role->id.'&sesskey='.sesskey().'">'.format_string($role->name).'</a>', format_text($role->description, FORMAT_HTML), '<a href="manage.php?action=delete&roleid='.$role->id.'&sesskey='.sesskey().'">'.$strdelete.'</a>');
- }
+ }
print_table($table);
$options = new object;
// this page deals with the 2 tabs for manage.php and grant.php
$toprow[] = new tabobject('manage', $CFG->wwwroot.'/admin/roles/manage.php', get_string('manageroles', 'role'));
-
+
$toprow[] = new tabobject('allowassign', $CFG->wwwroot.'/admin/roles/allowassign.php', get_string('allowassign', 'role'));
$toprow[] = new tabobject('allowoverride', $CFG->wwwroot.'/admin/roles/allowoverride.php', get_string('allowoverride', 'role'));
-
+
$tabs = array($toprow);
-
+
print_tabs($tabs, $currenttab);
?>
- <form action="override.php" method="post">
+ <form action="override.php" method="post">
<input type="hidden" name="contextid" value="<?php p($contextid) ?>">
<input type="hidden" name="roleid" value="<?php p($roleid) ?>">
<?php
<td><?php print_string('prohibit','role') ?></td>
<td><?php print_string('risks','role') ?></td>
</tr>
- <?php
-
+ <?php
+
// init these 2
$contextlevel = 0;
$component = '';
foreach ($capabilities as $capability) {
- // prints a breaker if component or name or context level
+ // prints a breaker if component or name or context level
if ($capability->component != $component or $capability->contextlevel != $contextlevel) {
- echo ('<tr><td colspan="5"><b>'.get_component_string($capability->component, $capability->contextlevel).'</b></td></tr>');
+ echo ('<tr><td colspan="5"><b>'.get_component_string($capability->component, $capability->contextlevel).'</b></td></tr>');
}
-
+
// these 2 are used to see to group same mod/core capabilities together
$contextlevel = $capability->contextlevel;
$component = $capability->component;
-
+
// check the capability override for this cap, this role in this context
if (isset($localoverrides[$capability->name])) {
$localpermission = $localoverrides[$capability->name]->permission;
} else {
$isallow = 0;
$isprevent = 0;
- $isprohibit = 0;
+ $isprohibit = 0;
}
$isdisabled = $isprohibit || islegacy($capability->name);
-
+
?>
-
+
<tr>
<td><?php echo get_capability_string($capability->name); ?></td>
<td align="center">
- <input type="radio" name="<?php echo $capability->name; ?>" value="0"
- <?php
- if ($localpermission == 0) {echo 'checked="checked"';}
+ <input type="radio" name="<?php echo $capability->name; ?>" value="0"
+ <?php
+ if ($localpermission == 0) {echo 'checked="checked"';}
if ($isdisabled) {echo 'disabled="disabled"';}?> />
</td>
<td align="center" <?php if ($isallow) {echo 'class="capcurrent"';} ?>>
<input type="radio" name="<?php echo $capability->name; ?>"
<?php echo ' value="'.CAP_ALLOW.'"';
- if ($localpermission == CAP_ALLOW) {echo ' checked="checked"';}
+ if ($localpermission == CAP_ALLOW) {echo ' checked="checked"';}
if ($isdisabled) {echo ' disabled="disabled"';}?> />
</td>
<td align="center" <?php if ($isprevent) {echo 'class="capcurrent"';} ?>>
- <input type="radio" name="<?php echo $capability->name; ?>"
+ <input type="radio" name="<?php echo $capability->name; ?>"
<?php echo ' value="'.CAP_PREVENT.'"';
- if ($localpermission == CAP_PREVENT) {echo ' checked="checked"';}
+ if ($localpermission == CAP_PREVENT) {echo ' checked="checked"';}
if ($isdisabled) {echo ' disabled="disabled"';}?> />
</td>
<td align="center" <?php if ($isprohibit) {echo 'class="capcurrent"';} ?>>
<input type="radio" name="<?php echo $capability->name; ?>"
<?php echo ' value="'.CAP_PROHIBIT.'"';
- if ($localpermission == CAP_PROHIBIT) {echo ' checked="checked"';}
+ if ($localpermission == CAP_PROHIBIT) {echo ' checked="checked"';}
if ($isdisabled) {echo ' disabled="disabled"';}?> />
</td>
<td><?php
}
?></td>
</tr>
-
- <?php } ?>
- </table>
+
+ <?php } ?>
+ </table>
<br />
<div align="center"><input type="submit" value="<?php print_string('savechanges') ?>" /></div>
</form>
<?php
-
+
require_once("../../config.php");
-
+
$contextid = required_param('contextid',PARAM_INT); // context id
$roleid = optional_param('roleid', 0, PARAM_INT); // required role id
$userid = optional_param('userid', 0, PARAM_INT); // needed for user tabs
$courseid = optional_param('courseid', 0, PARAM_INT); // needed for user tabs
-
+
if ($courseid) {
- $course = get_record('course', 'id', $courseid);
+ $course = get_record('course', 'id', $courseid);
} else {
$course = $SITE;
}
-
+
$sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
if ($contextid == $sitecontext->id) {
error ('can not override base role capabilities');
$context = get_record('context', 'id', $contextid);
$overridableroles = get_overridable_roles($context);
-
+
/// Make sure this user can override that role
if ($roleid) {
if (!user_can_override($context, $roleid)) {
error ('you can not override this role in this context');
- }
+ }
}
-
+
if ($userid) {
$user = get_record('user', 'id', $userid);
$fullname = fullname($user, has_capability('moodle/site:viewfullnames', $context));
}
-
+
/// Print the header and tabs
if ($context->aggregatelevel == CONTEXT_USER) {
-
+
/// course header
if ($course->id != SITEID) {
print_header("$fullname", "$fullname",
"<a href=\"../course/view.php?id=$course->id\">$course->shortname</a> ->
<a href=\"".$CFG->wwwroot."/user/index.php?id=$course->id\">$strparticipants</a> -> <a href=\"".$CFG->wwwroot."/user/view.php?id=".$userid."&course=".$course->id."\">$fullname</a> -> $straction",
- "", "", true, " ", navmenu($course));
-
- /// site header
+ "", "", true, " ", navmenu($course));
+
+ /// site header
} else {
print_header("$course->fullname: $fullname", "$course->fullname",
- "<a href=\"".$CFG->wwwroot."/user/view.php?id=".$userid."&course=".$course->id."\">$fullname</a> -> $straction", "", "", true, " ", navmenu($course));
+ "<a href=\"".$CFG->wwwroot."/user/view.php?id=".$userid."&course=".$course->id."\">$fullname</a> -> $straction", "", "", true, " ", navmenu($course));
}
$showroles = 1;
$currenttab = 'override';
/// Process incoming role override
if ($data = data_submitted()) {
- $localoverrides = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $context->id",
+ $localoverrides = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $context->id",
'', 'capability, permission, id');
foreach ($data as $capname => $value) {
if ($capname == 'contextid' || $capname == 'roleid') { // ignore contextid and roleid
- continue;
+ continue;
}
-
+
if (isset($localoverrides[$capname])) { // Something exists, so update it
-
+
if ($value == CAP_INHERIT) { // inherit = delete
- delete_records('role_capabilities', 'roleid', $roleid, 'contextid', $contextid,
+ delete_records('role_capabilities', 'roleid', $roleid, 'contextid', $contextid,
'capability', $capname);
} else {
$localoverride = new object;
$localoverride->permission = $value;
$localoverride->timemodified = time();
$localoverride->modifierid = $USER->id;
-
+
if (!update_record('role_capabilities', $localoverride)) {
debugging('Could not update a capability!');
}
}
-
+
} else { // insert a record
-
+
if ($value != CAP_INHERIT) { // Ignore inherits
$override->capability = $capname;
$override->contextid = $contextid;
} else {
$parentcontext = $context; // site level in override??
}
-
+
$r_caps = role_context_capabilities($roleid, $parentcontext);
- $localoverrides = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $context->id",
+ $localoverrides = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $context->id",
'', 'capability, permission, id');
-
+
// Get the capabilities overrideable in this context
if ($capabilities = fetch_context_capabilities($context)) {
print_simple_box_start("center");
} else { // Print overview table
$userparam = (!empty($userid)) ? '&userid='.$userid : '';
-
+
$table->tablealign = 'center';
$table->cellpadding = 5;
$table->cellspacing = 0;
$table->head = array(get_string('roles', 'role'), get_string('overrides', 'role'));
$table->wrap = array('nowrap', 'nowrap');
$table->align = array('right', 'center');
-
+
foreach ($overridableroles as $roleid => $rolename) {
$countusers = 0;
$overridecount = count_records_select('role_capabilities', "roleid = $roleid AND contextid = $context->id");
$table->data[] = array('<a href="override.php?contextid='.$context->id.'&roleid='.$roleid.$userparam.'">'.$rolename.'</a>', $overridecount);
}
-
+
print_table($table);
}
-
+
print_footer($course);
-
+
?>
$blockname = print_context_name($context);
$navigation = $blockname. ' -> '.$straction;
- switch ($blockinstance->pagetype) {
+ switch ($blockinstance->pagetype) {
case 'course-view':
if ($course = get_record('course', 'id', $blockinstance->pageid)) {
if ($course->id != SITEID) {
$toprow[] = new tabobject('update', $CFG->wwwroot.'/course/mod.php?update='.
$context->instanceid.'&return=true&sesskey='.sesskey(), get_string('update'));
- }
+ }
$toprow[] = new tabobject('roles', $CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.
- $context->id, get_string('roles'));
+ $context->id, get_string('roles'));
if (isset($tabsmode)) {
if (!isset($assignableroles)) {
- $assignableroles = get_assignable_roles($context);
+ $assignableroles = get_assignable_roles($context);
}
if (!isset($overridableroles)) {
- $overridableroles = get_overridable_roles($context);
+ $overridableroles = get_overridable_roles($context);
}
$inactive[] = 'roles';
if (!empty($assignableroles)) {
- $secondrow[] = new tabobject('assign',
- $CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.$context->id,
- get_string('assignroles', 'role'),
- get_string('showallroles', 'role'),
- true);
+ $secondrow[] = new tabobject('assign',
+ $CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php?contextid='.$context->id,
+ get_string('assignroles', 'role'),
+ get_string('showallroles', 'role'),
+ true);
}
- if (!empty($overridableroles)) {
- $secondrow[] = new tabobject('override',
+ if (!empty($overridableroles)) {
+ $secondrow[] = new tabobject('override',
$CFG->wwwroot.'/'.$CFG->admin.'/roles/override.php?contextid='.$context->id,
- get_string('overrideroles', 'role'),
- get_string('showallroles', 'role'),
- true);
+ get_string('overrideroles', 'role'),
+ get_string('showallroles', 'role'),
+ true);
}
if ($tabsmode == 'override') {
- $currenttab = 'override';
+ $currenttab = 'override';
} elseif ($tabsmode == 'assign') {
- $currenttab = 'assign';
+ $currenttab = 'assign';
}
} else {
- $inactive[] = '';
+ $inactive[] = '';
}
if (!empty($secondrow)) {
if ($site = get_site()) {
require_login();
-}
+}
page_map_class(PAGE_ADMIN, 'page_admin');
$adminediting = optional_param('adminedit', -1, PARAM_BOOL);
$return = optional_param('return','', PARAM_ALPHA);
-
+
if (!isset($USER->adminediting)) {
$USER->adminediting = false;
}
if (!empty($SITE->fullname)) {
$pageblocks = blocks_setup($PAGE);
- $preferred_width_left = bounded_number(BLOCK_L_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]),
+ $preferred_width_left = bounded_number(BLOCK_L_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]),
BLOCK_L_MAX_WIDTH);
- $preferred_width_right = bounded_number(BLOCK_R_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]),
+ $preferred_width_right = bounded_number(BLOCK_R_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]),
BLOCK_R_MAX_WIDTH);
-
+
// print header stuff
$PAGE->print_header();
$temp->add(new admin_setting_special_frontpagedesc());
$temp->add(new admin_setting_courselist_frontpage(false)); // non-loggedin version of the setting (that's what the parameter is for :) )
$temp->add(new admin_setting_courselist_frontpage(true)); // loggedin version of the setting
-$temp->add(new admin_setting_sitesetcheckbox('numsections', get_string('sitesection'),
+$temp->add(new admin_setting_sitesetcheckbox('numsections', get_string('sitesection'),
get_string('sitesectionhelp','admin'), 1));
-$temp->add(new admin_setting_sitesetselect('newsitems', get_string('newsitemsnumber'),
- '', 3,
+$temp->add(new admin_setting_sitesetselect('newsitems', get_string('newsitemsnumber'),
+ '', 3,
array('0' => '0',
'1' => '1',
'2' => '2',
$temp->add(new admin_setting_configcheckbox('messaging', get_string('messaging', 'admin'), get_string('configmessaging','admin'), 1));
$temp->add(new admin_setting_configcheckbox('allowobjectembed', get_string('allowobjectembed', 'admin'), get_string('configallowobjectembed', 'admin'), 0));
$temp->add(new admin_setting_configcheckbox('enabletrusttext', get_string('enabletrusttext', 'admin'), get_string('configenabletrusttext', 'admin'), 0));
-$temp->add(new admin_setting_configselect('maxeditingtime', get_string('maxeditingtime','admin'), get_string('configmaxeditingtime','admin'), 1800,
+$temp->add(new admin_setting_configselect('maxeditingtime', get_string('maxeditingtime','admin'), get_string('configmaxeditingtime','admin'), 1800,
array(60 => get_string('numminutes', '', 1),
300 => get_string('numminutes', '', 5),
900 => get_string('numminutes', '', 15),
1800 => get_string('numminutes', '', 30),
2700 => get_string('numminutes', '', 45),
3600 => get_string('numminutes', '', 60))));
-$temp->add(new admin_setting_configselect('fullnamedisplay', get_string('fullnamedisplay', 'admin'), get_string('configfullnamedisplay', 'admin'),
+$temp->add(new admin_setting_configselect('fullnamedisplay', get_string('fullnamedisplay', 'admin'), get_string('configfullnamedisplay', 'admin'),
'firstname lastname', array('language' => get_string('language'),
'firstname lastname' => get_string('firstname') . ' + ' . get_string('lastname'),
'lastname firstname' => get_string('lastname') . ' + ' . get_string('firstname'),
$temp->add(new admin_setting_configselect('restrictmodulesfor', get_string('restrictmodulesfor', 'admin'), get_string('configrestrictmodulesfor', 'admin'), 'none', array('none' => 'No courses',
'all' => 'All courses',
'requested' => 'Requested courses')));
-$temp->add(new admin_setting_configcheckbox('restrictbydefault', get_string('restrictbydefault', 'admin'), get_string('configrestrictbydefault', 'admin'), 0));
+$temp->add(new admin_setting_configcheckbox('restrictbydefault', get_string('restrictbydefault', 'admin'), get_string('configrestrictbydefault', 'admin'), 0));
if (!$options = get_records("modules")) {
$options = array();
}
// "systempaths" settingpage
$temp = new admin_settingpage('systempaths', get_string('systempaths','admin'));
-$temp->add(new admin_setting_configselect('gdversion', get_string('gdversion','admin'), get_string('configgdversion', 'admin'), check_gd_version(), array('0' => get_string('gdnot'),
- '1' => get_string('gd1'),
+$temp->add(new admin_setting_configselect('gdversion', get_string('gdversion','admin'), get_string('configgdversion', 'admin'), check_gd_version(), array('0' => get_string('gdnot'),
+ '1' => get_string('gd1'),
'2' => get_string('gd2'))));
$temp->add(new admin_setting_configtext('zip', get_string('pathtozip','admin'), get_string('configzip', 'admin'), '', PARAM_PATH));
$temp->add(new admin_setting_configtext('unzip', get_string('pathtounzip','admin'), get_string('configunzip', 'admin'), '', PARAM_PATH));
$temp->add(new admin_setting_configtext('noreplyaddress', get_string('noreplyaddress', 'admin'), get_string('confignoreplyaddress', 'admin'), 'noreply@' . $_SERVER['HTTP_HOST'], PARAM_NOTAGS));
$temp->add(new admin_setting_configtext('allowemailaddresses', get_string('allowemailaddresses', 'admin'), get_string('configallowemailaddresses', 'admin'), '', PARAM_NOTAGS));
$temp->add(new admin_setting_configtext('denyemailaddresses', get_string('denyemailaddresses', 'admin'), get_string('configdenyemailaddresses', 'admin'), '', PARAM_NOTAGS));
-$temp->add(new admin_setting_configselect('digestmailtime', get_string('digestmailtime', 'admin'), get_string('configdigestmailtime', 'admin'), 17, array('00' => '00',
- '01' => '01',
- '02' => '02',
- '03' => '03',
- '04' => '04',
- '05' => '05',
- '06' => '06',
- '07' => '07',
- '08' => '08',
- '09' => '09',
- '10' => '10',
- '11' => '11',
- '12' => '12',
- '13' => '13',
- '14' => '14',
- '15' => '15',
- '16' => '16',
- '17' => '17',
- '18' => '18',
- '19' => '19',
- '20' => '20',
- '21' => '21',
- '22' => '22',
+$temp->add(new admin_setting_configselect('digestmailtime', get_string('digestmailtime', 'admin'), get_string('configdigestmailtime', 'admin'), 17, array('00' => '00',
+ '01' => '01',
+ '02' => '02',
+ '03' => '03',
+ '04' => '04',
+ '05' => '05',
+ '06' => '06',
+ '07' => '07',
+ '08' => '08',
+ '09' => '09',
+ '10' => '10',
+ '11' => '11',
+ '12' => '12',
+ '13' => '13',
+ '14' => '14',
+ '15' => '15',
+ '16' => '16',
+ '17' => '17',
+ '18' => '18',
+ '19' => '19',
+ '20' => '20',
+ '21' => '21',
+ '22' => '22',
'23' => '23')));
if (!empty($CFG->unicodedb)) { // These options are only available if running under unicodedb
unset($options);
$temp = new admin_settingpage('debugging', get_string('debugging', 'admin'));
$temp->add(new admin_setting_special_debug());
$temp->add(new admin_setting_special_perfdebug());
-$ADMIN->add('server', $temp);
+$ADMIN->add('server', $temp);
// "stats" settingpage
60*60*8 => '8 '.get_string('hours') )));
$temp->add(new admin_setting_configtime('statsruntimestarthour', 'statsruntimestartminute', get_string('statsruntimestart', 'admin'), get_string('configstatsruntimestart', 'admin'), array('h' => 0, 'm' => 0)));
$temp->add(new admin_setting_configtext('statsuserthreshold', get_string('statsuserthreshold', 'admin'), get_string('configstatsuserthreshold', 'admin'), 0, PARAM_INT));
-$ADMIN->add('server', $temp);
+$ADMIN->add('server', $temp);
// "http" settingpage
$temp->add(new admin_Setting_configcheckbox('slasharguments', get_string('slasharguments', 'admin'), get_string('configslasharguments', 'admin'), 1));
$temp->add(new admin_setting_configtext('proxyhost', get_string('proxyhost', 'admin'), get_string('configproxyhost', 'admin'), '', PARAM_HOST));
$temp->add(new admin_setting_configtext('proxyport', get_string('proxyport', 'admin'), get_string('configproxyport', 'admin'), '', PARAM_INT));
-$ADMIN->add('server', $temp);
+$ADMIN->add('server', $temp);
$ADMIN->add('server', new admin_externalpage('sitefiles', get_string('sitefiles'), $CFG->wwwroot . '/files/index.php?id=' . SITEID));
}
$assignableroles = get_assignable_roles($context);
-$temp->add(new admin_setting_configselect('notloggedinroleid', get_string('notloggedinroleid', 'admin'),
+$temp->add(new admin_setting_configselect('notloggedinroleid', get_string('notloggedinroleid', 'admin'),
get_string('confignotloggedinroleid', 'admin'), $guestrole->id, $assignableroles ));
-$temp->add(new admin_setting_configselect('defaultuserroleid', get_string('defaultuserroleid', 'admin'),
+$temp->add(new admin_setting_configselect('defaultuserroleid', get_string('defaultuserroleid', 'admin'),
get_string('configdefaultuserroleid', 'admin'), $guestrole->id, $assignableroles));
-$temp->add(new admin_setting_configselect('defaultcourseroleid', get_string('defaultcourseroleid', 'admin'),
+$temp->add(new admin_setting_configselect('defaultcourseroleid', get_string('defaultcourseroleid', 'admin'),
get_string('configdefaultcourseroleid', 'admin'), $studentrole->id, $assignableroles));
//$temp->add(new admin_setting_configcheckbox('autologinguests', get_string('autologinguests', 'admin'), get_string('configautologinguests', 'admin'), 0));
//$temp->add(new admin_setting_configcheckbox('allusersaresitestudents', get_string('allusersaresitestudents', 'admin'), get_string('configallusersaresitestudents','admin'), 1));
-$temp->add(new admin_setting_configmultiselect('hiddenuserfields', get_string('hiddenuserfields', 'admin'),
- get_string('confighiddenuserfields', 'admin'), array(),
+$temp->add(new admin_setting_configmultiselect('hiddenuserfields', get_string('hiddenuserfields', 'admin'),
+ get_string('confighiddenuserfields', 'admin'), array(),
array('none' => get_string('none'),
'description' => get_string('description'),
'city' => get_string('city'),
<?php // $Id$
-// detects settings that were added during an upgrade, displays a screen for the admin to
+// detects settings that were added during an upgrade, displays a screen for the admin to
// modify them, and then processes modifications
require_once('../config.php');
// first we deal with the case where there are no new settings to be set
if ($newsettingshtml == '') {
- redirect($CFG->wwwroot . '/' . $CFG->admin . '/index.php');
+ redirect($CFG->wwwroot . '/' . $CFG->admin . '/index.php');
die;
}
/**
* Find settings that have not been initialized (e.g. during initial install or an upgrade).
- *
+ *
* Tests each setting's get_setting() method. If the result is NULL, we consider the setting
* to be uninitialized.
*
$return = array_merge($return, find_new_settings($node->children[$entry]));
}
return $return;
- }
+ }
- if (is_a($node, 'admin_settingpage')) {
+ if (is_a($node, 'admin_settingpage')) {
$return = array();
foreach ($node->settings as $setting) {
if ($setting->get_setting() === NULL) {
$return .= output_new_settings_by_page($node->children[$entry]);
}
return $return;
- }
+ }
- if (is_a($node, 'admin_settingpage')) {
+ if (is_a($node, 'admin_settingpage')) {
$newsettings = array();
foreach ($node->settings as $setting) {
if ($setting->get_setting() === NULL) {
$return = '<tr><td colspan="2"><strong>' . $node->visiblename . '</strong></td></tr>';
foreach ($newsettings as $newsetting) {
$return .= $newsetting->output_html();
- }
+ }
}
return $return;
}
2006-07-11 - Important notes
-I've just discovered this some seconds ago, in order
+I've just discovered this some seconds ago, in order
to test properly the XMLDB classes and editor:
1.- PHP 5 required for now. Will change this soon.
2006-07-11 - Initial commit
-This directory contains the XMLDB classes to be used
-under Moodle > 1.7 to store all the DB info in a
+This directory contains the XMLDB classes to be used
+under Moodle > 1.7 to store all the DB info in a
neutral form (classes dir). Also it contains one simple
interface to edit all those structures.
to http://your.server/moodle/admin/xmldb
The edition interface isn't completed yet (it laks 3 more forms
-to edit fields, keys and indexes) and there isn't any lang file
+to edit fields, keys and indexes) and there isn't any lang file
(although I hope everything is really clear).
The edition interface includes one reverse-engineering tool that
"generators" needed in order to use it to create Moodle DB structures
for each RDBMS flavour.
-Once the interface was finished (2-3 days from now) related documentation
-will be sent to http://docs.moodle.org/en/XML_database_schema in order
+Once the interface was finished (2-3 days from now) related documentation
+will be sent to http://docs.moodle.org/en/XML_database_schema in order
to comment/modify/approve the final XML format.
-All the code is, obviously GPL, with its copyrights and so on...
+All the code is, obviously GPL, with its copyrights and so on...
Ciao, Eloy Lafuente (stronk7) :-)
// //
///////////////////////////////////////////////////////////////////////////
-/// This is the main action class. It implements all the basic
+/// This is the main action class. It implements all the basic
/// functionalities to be shared by each action.
class XMLDBAction {
* Constructor to keep PHP5 happy
*/
function __construct() {
- $this->XMLDBAction();
+ $this->XMLDBAction();
}
- /**
- * Init method, every subclass will have its own,
+ /**
+ * Init method, every subclass will have its own,
* always calling the parent one
*/
function init() {
$this->errormsg = NULL;
$this->subaction = NULL;
}
-
+
/**
* returns the type of output of the file
*/
}
/**
- * getPostAtion method, returns the action to launch after executing
+ * getPostAtion method, returns the action to launch after executing
* another one
*/
function getPostAction() {
return $this->postaction;
}
- /**
+ /**
* getTitle method returns the title of the action (that is part
* of the $str array attribute
*/
/**
* main invoke method, it simply sets the postaction attribute
- * if possible
+ * if possible
*/
function invoke() {
global $SESSION;
-
+
/// If we are used any dir, save it in the lastused session object
/// Some actions can use it to perform positioning
if ($lastused = optional_param ('dir', NULL, PARAM_PATH)) {
$SESSION->lastused = stripslashes_safe($lastused);
}
-
+
$this->postaction = optional_param ('postaction', NULL, PARAM_ALPHAEXT);
/// Avoid being recursive
if ($this->title == $this->postaction) {
$result = false;
if (file_exists($actionpath) && is_readable($actionpath)) {
require_once($actionpath);
- if ($xmldb_action = new $action) {
+ if ($xmldb_action = new $action) {
$result = $xmldb_action->invoke();
if ($result) {
if ($xmldb_action->does_generate != ACTION_NONE &&
// //
///////////////////////////////////////////////////////////////////////////
-/// This class will
+/// This class will
class create_xml_file extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$xmlcomment = 'XMLDB file for Moodle ' . dirname($xmlpath);
$xmltable = strtolower(basename(dirname($xmlpath)));
-
+
/// Initial contents
$c = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
$c.= ' <XMLDB PATH="' . $xmlpath . '" VERSION="' . $xmlversion .'" COMMENT="' . $xmlcomment .'">' . "\n";
class delete_field extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
/// Recalculate the hash
$structure->calculateHash(true);
-
+
/// If the hash has changed from the original one, change the version
/// and mark the structure as changed
$origstructure =& $dbdir->xml_file->getStructure();
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class delete_index extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
/// Recalculate the hash
$structure->calculateHash(true);
-
+
/// If the hash has changed from the original one, change the version
/// and mark the structure as changed
$origstructure =& $dbdir->xml_file->getStructure();
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class delete_key extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
/// Recalculate the hash
$structure->calculateHash(true);
-
+
/// If the hash has changed from the original one, change the version
/// and mark the structure as changed
$origstructure =& $dbdir->xml_file->getStructure();
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class delete_sentence extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
/// Recalculate the hash
$structure->calculateHash(true);
-
+
/// If the hash has changed from the original one, change the version
/// and mark the structure as changed
$origstructure =& $dbdir->xml_file->getStructure();
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class delete_statement extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class delete_table extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class delete_xml_file extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class edit_field extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$this->output = $o;
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
/// Register the needed events
- onload=function() {
+ onload=function() {
/// Adjust the form on load
transformForm();
class edit_field_save extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$length > 0 && $length <= 20)) {
$errors[] = $this->str['integerincorrectlength'];
}
- if (!(empty($default) || (is_numeric($default) &&
+ if (!(empty($default) || (is_numeric($default) &&
!empty($default) &&
intval($default)==floatval($default)))) {
$errors[] = $this->str['defaultincorrect'];
$length > 0 && $length <= 20)) {
$errors[] = $this->str['numberincorrectlength'];
}
- if (!(empty($decimals) || (is_numeric($decimals) &&
- !empty($decimals) &&
+ if (!(empty($decimals) || (is_numeric($decimals) &&
+ !empty($decimals) &&
intval($decimals)==floatval($decimals) &&
- $decimals >= 0 &&
+ $decimals >= 0 &&
$decimals < $length))) {
$errors[] = $this->str['numberincorrectdecimals'];
}
- if (!(empty($default) || (is_numeric($default) &&
+ if (!(empty($default) || (is_numeric($default) &&
!empty($default)))) {
$errors[] = $this->str['defaultincorrect'];
}
}
/// Float checks
if ($type == XMLDB_TYPE_FLOAT) {
- if (!(empty($length) || (is_numeric($length) &&
- !empty($length) &&
+ if (!(empty($length) || (is_numeric($length) &&
+ !empty($length) &&
intval($length)==floatval($length) &&
- $length > 0 &&
+ $length > 0 &&
$length <= 20))) {
$errors[] = $this->str['floatincorrectlength'];
}
- if (!(empty($decimals) || (is_numeric($decimals) &&
- !empty($decimals) &&
+ if (!(empty($decimals) || (is_numeric($decimals) &&
+ !empty($decimals) &&
intval($decimals)==floatval($decimals) &&
- $decimals >= 0 &&
+ $decimals >= 0 &&
$decimals < $length))) {
$errors[] = $this->str['floatincorrectdecimals'];
}
- if (!(empty($default) || (is_numeric($default) &&
+ if (!(empty($default) || (is_numeric($default) &&
!empty($default)))) {
$errors[] = $this->str['defaultincorrect'];
}
}
} else {
$enumerr = true;
- }
+ }
if ($enumerr) {
$errors[] = $this->str['enumvaluesincorrect'];
} else {
$tempfield->setDefault($default);
/// Prepare the output
$site = get_site();
- print_header("$site->shortname: XMLDB",
- "$site->fullname",
+ print_header("$site->shortname: XMLDB",
+ "$site->fullname",
"<a href=\"../index.php\">" . $this->str['administration'] . "</a> -> <a href=\"index.php\">XMLDB</a>");
notice ('<p>' .implode(', ', $errors) . '</p>
<p>' . $tempfield->readableInfo(),
$next->setChanged(true);
}
}
-
- /// Set comment
+
+ /// Set comment
$field->setComment($comment);
/// Set the rest of fields
$field->setEnum($enum);
$field->setEnumValues($enumvalues);
$field->setDefault($default);
-
+
/// If the hash has changed from the old one, change the version
/// and mark the structure as changed
$field->calculateHash(true);
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
}
class edit_index extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$this->output = $o;
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class edit_index_save extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$tempindex->setFields($fieldsarr);
/// Prepare the output
$site = get_site();
- print_header("$site->shortname: XMLDB",
- "$site->fullname",
+ print_header("$site->shortname: XMLDB",
+ "$site->fullname",
"<a href=\"../index.php\">" . $this->str['administration'] . "</a> -> <a href=\"index.php\">XMLDB</a>");
notice ('<p>' .implode(', ', $errors) . '</p>
<p>' . $tempindex->readableInfo(),
$next->setChanged(true);
}
}
-
- /// Set comment
+
+ /// Set comment
$index->setComment($comment);
/// Set the rest of fields
$index->setUnique($unique);
$index->setFields($fieldsarr);
-
+
/// If the hash has changed from the old one, change the version
/// and mark the structure as changed
$index->calculateHash(true);
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
}
class edit_key extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$this->output = $o;
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
/// Register the needed events
- onload=function() {
+ onload=function() {
/// Adjust the form on load
transformForm();
class edit_key_save extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
/// Check reftable is not empty
if (empty($reftable)) {
$errors[] = $this->str['noreftablespecified'];
- } else
+ } else
/// Check reffields are not empty
if (empty($reffieldsarr[0])) {
$errors[] = $this->str['noreffieldsspecified'];
- } else
+ } else
/// Check the number of fields is correct
if (count($fieldsarr) != count($reffieldsarr)) {
$errors[] = $this->str['wrongnumberofreffields'];
}
/// Prepare the output
$site = get_site();
- print_header("$site->shortname: XMLDB",
- "$site->fullname",
+ print_header("$site->shortname: XMLDB",
+ "$site->fullname",
"<a href=\"../index.php\">" . $this->str['administration'] . "</a> -> <a href=\"index.php\">XMLDB</a>");
notice ('<p>' .implode(', ', $errors) . '</p>
<p>' . $tempkey->readableInfo(),
$next->setChanged(true);
}
}
-
- /// Set comment
+
+ /// Set comment
$key->setComment($comment);
/// Set the rest of fields
$key->setRefTable($reftable);
$key->setRefFields($reffieldsarr);
}
-
+
/// If the hash has changed from the old one, change the version
/// and mark the structure as changed
$key->calculateHash(true);
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
}
class edit_sentence extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$b .= ' <a href="index.php?action=edit_statement&statement=' . urlencode($statementparam) . '&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '">[' . $this->str['back'] . ']</a>';
$b .= '</p>';
$o .= $b;
-
+
$this->output = $o;
}
-
+
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class edit_sentence_save extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
if ($result && count($fields) != count($values)) {
$errors[] = $this->str['wrongnumberoffieldsorvalues'];
}
-
+
if (!empty($errors)) {
/// Prepare the output
$site = get_site();
- print_header("$site->shortname: XMLDB",
- "$site->fullname",
+ print_header("$site->shortname: XMLDB",
+ "$site->fullname",
"<a href=\"../index.php\">" . $this->str['administration'] . "</a> -> <a href=\"index.php\">XMLDB</a>");
notice ('<p>' .implode(', ', $errors) . '</p>
<p>' . s($sentence),
/// Continue if we aren't under errors
if (empty($errors)) {
$sentences[$sentenceparam] = $sentence;
-
+
/// If the sentence has changed from the old one, change the version
/// and mark the statement and structure as changed
if ($oldsentence != $sentence) {
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
}
class edit_statement extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
///$statement->deleteSentence('changeme');
/// Add the fields list
- $sentences =& $statement->getSentences();
+ $sentences =& $statement->getSentences();
if (!empty($sentences)) {
$o .= '<h3 class="main">' . $this->str['sentences'] . '</h3>';
$o .= '<table id="listfields" border="0" align="center" cellpadding="5" cellspacing="1" class="flexible">';
$b .= '<a href="index.php?action=delete_sentence&sentence=' . $key . '&statement=' . urlencode($statement->getName()) . '&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '">[' . $this->str['delete'] . ']</a>';
$b .= '</td>';
/// Print table row
- $o .= '<tr class="r' . $row . '"><td class="table cell">' . $p . $sentence . $b . '</tr>';
+ $o .= '<tr class="r' . $row . '"><td class="table cell">' . $p . $sentence . $b . '</tr>';
$row = ($row + 1) % 2;
}
$o .= '</table>';
$this->output = $o;
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class edit_statement_save extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
}
}
- /// Set comment
+ /// Set comment
$statement->setComment($comment);
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class edit_table extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$table->deleteIndex('changeme');
/// Add the fields list
- $fields =& $table->getFields();
+ $fields =& $table->getFields();
if (!empty($fields)) {
$o .= '<h3 class="main">' . $this->str['fields'] . '</h3>';
$o .= '<table id="listfields" border="0" align="center" cellpadding="5" cellspacing="1" class="flexible">';
}
$b .= '</td><td class="button cell">';
/// The delete button (if we have more than one and it isn't used
- if (count($fields) > 1 &&
+ if (count($fields) > 1 &&
!$structure->getFieldUses($table->getName(), $field->getName())) {
$b .= '<a href="index.php?action=delete_field&field=' . $field->getName() . '&table=' . $table->getName() . '&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '">[' . $this->str['delete'] . ']</a>';
} else {
/// The readable info
$r = '</td><td class="readableinfo cell">' . $field->readableInfo() . '</td>';
/// Print table row
- $o .= '<tr class="r' . $row . '"><td class="table cell"><a href="index.php?action=view_field_xml&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '&field=' . $field->getName() . '&table=' . $table->getName() . '&select=edited" target="_blank">' . $field->getName() . '</a>' . $b . $r . '</tr>';
+ $o .= '<tr class="r' . $row . '"><td class="table cell"><a href="index.php?action=view_field_xml&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '&field=' . $field->getName() . '&table=' . $table->getName() . '&select=edited" target="_blank">' . $field->getName() . '</a>' . $b . $r . '</tr>';
$row = ($row + 1) % 2;
}
$o .= '</table>';
}
/// Add the keys list
- $keys =& $table->getKeys();
+ $keys =& $table->getKeys();
if (!empty($keys)) {
$o .= '<h3 class="main">' . $this->str['keys'] . '</h3>';
$o .= '<table id="listkeys" border="0" align="center" cellpadding="5" cellspacing="1" class="flexible">';
/// The readable info
$r = '</td><td class="readableinfo cell">' . $key->readableInfo() . '</td>';
/// Print table row
- $o .= '<tr class="r' . $row . '"><td class="table cell"><a href="index.php?action=view_key_xml&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '&key=' . $key->getName() . '&table=' . $table->getName() . '&select=edited" target="_blank">' . $key->getName() . '</a>' . $b . $r .'</tr>';
+ $o .= '<tr class="r' . $row . '"><td class="table cell"><a href="index.php?action=view_key_xml&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '&key=' . $key->getName() . '&table=' . $table->getName() . '&select=edited" target="_blank">' . $key->getName() . '</a>' . $b . $r .'</tr>';
$row = ($row + 1) % 2;
}
$o .= '</table>';
}
/// Add the indexes list
- $indexes =& $table->getIndexes();
+ $indexes =& $table->getIndexes();
if (!empty($indexes)) {
$o .= '<h3 class="main">' . $this->str['indexes'] . '</h3>';
$o .= '<table id="listindexes" border="0" align="center" cellpadding="5" cellspacing="1" class="flexible">';
/// The readable info
$r = '</td><td class="readableinfo cell">' . $index->readableInfo() . '</td>';
/// Print table row
- $o .= '<tr class="r' . $row . '"><td class="table cell"><a href="index.php?action=view_index_xml&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '&index=' . $index->getName() . '&table=' . $table->getName() . '&select=edited" target="_blank">' . $index->getName() . '</a>' . $b . $r .'</tr>';
+ $o .= '<tr class="r' . $row . '"><td class="table cell"><a href="index.php?action=view_index_xml&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '&index=' . $index->getName() . '&table=' . $table->getName() . '&select=edited" target="_blank">' . $index->getName() . '</a>' . $b . $r .'</tr>';
$row = ($row + 1) % 2;
}
$o .= '</table>';
$this->output = $o;
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class edit_table_save extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
}
}
- /// Set comment
+ /// Set comment
$table->setComment($comment);
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class edit_xml_file extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
sort($reserved_words);
$reserved_words = array_unique($reserved_words);
/// Add the tables list
- $tables =& $structure->getTables();
+ $tables =& $structure->getTables();
if ($tables) {
$o .= '<h3 class="main">' . $this->str['tables'] . '</h3>';
$o .= '<table id="listtables" border="0" align="center" cellpadding="5" cellspacing="1" class="flexible">';
}
$b .= '</td>';
/// Print table row
- $o .= '<tr class="r' . $row . '"><td class="table cell"><a href="index.php?action=view_table_xml&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '&table=' . $table->getName() . '&select=edited" target="_blank">' . $table->getName() . '</a>' . $b . '</tr>';
+ $o .= '<tr class="r' . $row . '"><td class="table cell"><a href="index.php?action=view_table_xml&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '&table=' . $table->getName() . '&select=edited" target="_blank">' . $table->getName() . '</a>' . $b . '</tr>';
$row = ($row + 1) % 2;
}
$o .= '</table>';
}
///Add the statements list
- $statements =& $structure->getStatements();
+ $statements =& $structure->getStatements();
if ($statements) {
$o .= '<h3 class="main">' . $this->str['statements'] . '</h3>';
$o .= '<table id="liststatements" border="0" align="center" cellpadding="5" cellspacing="1" class="flexible">';
$b .= '<a href="index.php?action=delete_statement&statement=' . $statement->getName() . '&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '">[' . $this->str['delete'] . ']</a>';
$b .= '</td>';
/// Print statement row
- $o .= '<tr class="r' . $row . '"><td class="statement cell"><a href="index.php?action=view_statement_xml&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '&statement=' . $statement->getName() . '&select=edited" target="_blank">' . $statement->getName() . '</a>' . $b . '</tr>';
+ $o .= '<tr class="r' . $row . '"><td class="statement cell"><a href="index.php?action=view_statement_xml&dir=' . urlencode(str_replace($CFG->dirroot, '', $dirpath)) . '&statement=' . $statement->getName() . '&select=edited" target="_blank">' . $statement->getName() . '</a>' . $b . '</tr>';
$row = ($row + 1) % 2;
}
$o .= '</table>';
class edit_xml_file_save extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
// //
///////////////////////////////////////////////////////////////////////////
-/// This class will check all the db directories existing under the
+/// This class will check all the db directories existing under the
/// current Moodle installation, sending them to the SESSION->dbdirs array
class get_db_directories extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$XMLDB->dbdirs[$dbdir->path]->path_exists = file_exists($dbdir->path); //Update status
}
}
-
+
/// Now, question types (question/type/xxx/db)
if ($plugins = get_list_of_plugins('question/type')) {
foreach ($plugins as $plugin) {
$XMLDB->dbdirs[$dbdir->path]->path_exists = file_exists($dbdir->path); //Update status
}
}
-
+
/// Now, backup/restore stuff (backup/db)
$dbdir = new stdClass;
$dbdir->path = $CFG->dirroot . '/backup/db';
$XMLDB->dbdirs[$dbdir->path]->path_exists = file_exists($dbdir->path); //Update status
}
}
-
+
/// Now, enrolment plugins (enrol/xxx/db)
if ($plugins = get_list_of_plugins('enrol', 'db')) {
foreach ($plugins as $plugin) {
}
/// Sort by key
ksort($XMLDB->dbdirs);
-
+
/// Return ok if arrived here
return true;
}
class load_xml_file extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
class load_xml_files extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
class main_view extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
class move_updown_field extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
/// Table has changed
$table->setChanged(true);
-
+
/// Reorder the fields
$table->orderFields($fields);
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class move_updown_index extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
/// Table has changed
$table->setChanged(true);
-
+
/// Reorder the indexes
$table->orderIndexes($indexes);
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class move_updown_key extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
/// Table has changed
$table->setChanged(true);
-
+
/// Reorder the keys
$table->orderKeys($keys);
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class move_updown_statement extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
/// Statement has changed
$statement->setChanged(true);
-
+
/// Reorder the structure
$structure->orderStatements($statements);
/// Send statements back to structure (the order above break refs)
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class move_updown_table extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
/// Table has changed
$table->setChanged(true);
-
+
/// Reorder the structure
$structure->orderTables($tables);
/// Send tables back to structure (the order above break refs)
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class new_field extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class new_index extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$structure->setChanged(true);
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class new_key extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$structure->setChanged(true);
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class new_sentence extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$structure->setChanged(true);
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class new_statement extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$this->output = $o;
- /// If table, retrofit information and, if everything works,
+ /// If table, retrofit information and, if everything works,
/// go to the table edit action
} else {
/// Get some params (table is mandatory here)
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class new_table extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$structure->addTable($table);
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
// //
///////////////////////////////////////////////////////////////////////////
-/// This class will ask and retrofit all the information from one
+/// This class will ask and retrofit all the information from one
/// mysql table present in the Moodle DB to one XMLDBTable structure
class new_table_from_mysql extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$this->output = $o;
- /// If table, retrofit information and, if everything works,
+ /// If table, retrofit information and, if everything works,
/// go to the table edit action
} else {
/// Get some params (table is mandatory here)
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class revert_changes extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class save_xml_file extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$dirpath = required_param('dir', PARAM_PATH);
$dirpath = $CFG->dirroot . stripslashes_safe($dirpath);
- /// Get the edited dir
+ /// Get the edited dir
if (!empty($XMLDB->editeddirs)) {
if (isset($XMLDB->editeddirs[$dirpath])) {
$editeddir =& $XMLDB->editeddirs[$dirpath];
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
// //
///////////////////////////////////////////////////////////////////////////
-/// This class will
+/// This class will
class template extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class test extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$this->output = $o;
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class unload_xml_file extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
}
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class view_field_xml extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
class view_index_xml extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
class view_key_xml extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
class view_reserved_words extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
}
}
$wronguses[] = $this->str['table'] . ' - ' . $table . ' (' . implode(', ',$list_of_db) . ')';
-
+
}
$dbfields = $db->MetaColumns($dbtable);
if ($dbfields) {
$this->output = $o;
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class view_statement_xml extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
class view_structure_php extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$structure =& $editeddir->xml_file->getStructure();
}
/// ADD YOUR CODE HERE
-
+
$tables =& $structure->getTables();
$table = reset($tables);
$defaulttable = null;
$o = $b;
/// Calculate the popup of commands
- $commands = array('create_table',
+ $commands = array('create_table',
'drop_table',
'rename_table');
foreach ($commands as $command) {
$this->output = $o;
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
}
/**
- * This function will generate all the PHP code needed to
+ * This function will generate all the PHP code needed to
* create one table using XMLDB objects and functions
- *
+ *
* @param XMLDBStructure structure object containing all the info
* @param string table table code to be created
* @return string PHP code to be used to create the table
}
/**
- * This function will generate all the PHP code needed to
+ * This function will generate all the PHP code needed to
* drop one table using XMLDB objects and functions
- *
+ *
* @param XMLDBStructure structure object containing all the info
* @param string table table code to be dropped
* @return string PHP code to be used to drop the table
}
/**
- * This function will generate all the PHP code needed to
+ * This function will generate all the PHP code needed to
* rename one table using XMLDB objects and functions
- *
+ *
* @param XMLDBStructure structure object containing all the info
* @param string table table code to be renamed
* @return string PHP code to be used to rename the table
class view_structure_sql extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$this->output = $o;
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class view_structure_xml extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
class view_table_php extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
/// ADD YOUR CODE HERE
$tableparam = required_param('table', PARAM_PATH);
-
+
$table =& $structure->getTable($tableparam);
$fields = $table->getFields();
$field = reset($fields);
$o .= '<h3 class="main">' . $this->str['table'] . ': ' . s($tableparam) . '</h3>';
/// Calculate the popup of commands
- $commands = array('add_field',
+ $commands = array('add_field',
'drop_field',
'rename_field');
foreach ($commands as $command) {
$this->output = $o;
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
}
/**
- * This function will generate all the PHP code needed to
+ * This function will generate all the PHP code needed to
* create one field using XMLDB objects and functions
- *
+ *
* @param XMLDBStructure structure object containing all the info
* @param string table table name
* @param string field field name to be created
}
/**
- * This function will generate all the PHP code needed to
+ * This function will generate all the PHP code needed to
* drop one field using XMLDB objects and functions
- *
+ *
* @param XMLDBStructure structure object containing all the info
* @param string table table name
* @param string field field name to be dropped
}
/**
- * This function will generate all the PHP code needed to
+ * This function will generate all the PHP code needed to
* rename one field using XMLDB objects and functions
- *
+ *
* @param XMLDBStructure structure object containing all the info
* @param string table table name
* @param string field field name to be renamed
/**
* This function disables some elements from the fields/keys/indexes drop down
*/
-function disablePopupHeads() {
- var popup = document.getElementById("menufieldkeyindex");
- var i = popup.length;
- while (i--) {
- option = popup[i];
- if (option.value == "fieldshead" || option.value == "keyshead" || option.value == "indexeshead") {
- popup[i].disabled = true;
- }
+function disablePopupHeads() {
+ var popup = document.getElementById("menufieldkeyindex");
+ var i = popup.length;
+ while (i--) {
+ option = popup[i];
+ if (option.value == "fieldshead" || option.value == "keyshead" || option.value == "indexeshead") {
+ popup[i].disabled = true;
+ }
}
}
class view_table_sql extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
$this->output = $o;
/// Launch postaction if exists (leave this here!)
- if ($this->getPostAction() && $result) {
+ if ($this->getPostAction() && $result) {
return $this->launch($this->getPostAction());
}
class view_table_xml extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
class view_xml extends XMLDBAction {
- /**
+ /**
* Init method, every subclass will have its own
*/
function init() {
/// Get the file parameter
$file = required_param('file', PARAM_PATH);
$file = $CFG->dirroot . stripslashes_safe($file);
- /// File must be under $CFG->wwwroot and
+ /// File must be under $CFG->wwwroot and
/// under one db directory (simple protection)
if (substr($file, 0, strlen($CFG->dirroot)) == $CFG->dirroot &&
substr(dirname($file), -2, 2) == 'db') {
require_once('../../lib/xmldb/classes/XMLDBIndex.class.php');
require_once('../../lib/xmldb/classes/XMLDBStatement.class.php');
-/// Add Moodle config script (this is loaded AFTER all the rest
+/// Add Moodle config script (this is loaded AFTER all the rest
/// of classes because it starts the SESSION and classes to be
/// stored there MUST be declared before in order to avoid
/// getting "incomplete" objects
$stradministration = get_string('administration');
/// Body of the script, based on action, we delegate the work
- $action = optional_param ('action', 'main_view', PARAM_ALPHAEXT);
+ $action = optional_param ('action', 'main_view', PARAM_ALPHAEXT);
/// Get the action path and invoke it
$actionsroot = "$CFG->dirroot/$CFG->admin/xmldb/actions";
/// Based on getDoesGenerate()
switch ($xmldb_action->getDoesGenerate()) {
case ACTION_GENERATE_HTML:
- /// Define $CFG->javascript to use our custom javascripts.
+ /// Define $CFG->javascript to use our custom javascripts.
/// Save the original one to add it from ours. Global too! :-(
global $standard_javascript;
$standard_javascript = $CFG->javascript; // Save original javascript file
$CFG->javascript = $CFG->dirroot.'/admin/xmldb/javascript.php'; //Use our custom javascript code
/// Go with standard header
- print_header("$site->shortname: XMLDB",
- "$site->fullname",
+ print_header("$site->shortname: XMLDB",
+ "$site->fullname",
"<a href=\"../index.php\">$stradministration</a> -> <a href=\"index.php\">XMLDB</a>");
print_heading($xmldb_action->getTitle());
echo $xmldb_action->getOutput();
error ("Error: wrong action specified ($action)");
}
- if ($xmldb_action->getDoesGenerate() != ACTION_GENERATE_XML) {
+ if ($xmldb_action->getDoesGenerate() != ACTION_GENERATE_XML) {
if (debugging()) {
///print_object($XMLDB);
}
$block_rss_client_capabilities = array(
-
+
'block/rss_client:createprivatefeeds' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'block/rss_client:createsharedfeeds' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'block/rss_client:manageownfeeds' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'block/rss_client:manageanyfeeds' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'admin' => CAP_ALLOW
)
)
-
+
);
?>
\ No newline at end of file
}
}
- if ($capabilities = get_records_select('role_capabilities',
+ if ($capabilities = get_records_select('role_capabilities',
"roleid = $guestrole->id AND contextid = $sitecontext->id")) {
foreach ($capabilities as $capability) {
- $USER->capabilities[$context->id][$capability->capability] = $capability->permission;
+ $USER->capabilities[$context->id][$capability->capability] = $capability->permission;
}
}
/**
* Load default not logged in role capabilities when user is not logged in
- * @return bool
+ * @return bool
*/
function load_notloggedin_role() {
global $CFG, $USER;
}
}
- if ($capabilities = get_records_select('role_capabilities',
+ if ($capabilities = get_records_select('role_capabilities',
"roleid = $CFG->notloggedinroleid AND contextid = $sitecontext->id")) {
foreach ($capabilities as $capability) {
- $USER->capabilities[$sitecontext->id][$capability->capability] = $capability->permission;
+ $USER->capabilities[$sitecontext->id][$capability->capability] = $capability->permission;
}
}
/**
* Load default not logged in role capabilities when user is not logged in
- * @return bool
+ * @return bool
*/
function load_defaultuser_role() {
global $CFG, $USER;
}
}
- if ($capabilities = get_records_select('role_capabilities',
+ if ($capabilities = get_records_select('role_capabilities',
"roleid = $CFG->defaultuserroleid AND contextid = $sitecontext->id")) {
foreach ($capabilities as $capability) {
if (!isset($USER->capabilities[$sitecontext->id][$capability->capability])) { // Don't overwrite
- $USER->capabilities[$sitecontext->id][$capability->capability] = $capability->permission;
+ $USER->capabilities[$sitecontext->id][$capability->capability] = $capability->permission;
}
}
- // SPECIAL EXCEPTION: If the default user role is actually a guest role, then
+ // SPECIAL EXCEPTION: If the default user role is actually a guest role, then
// remove some capabilities so this user doesn't get confused with a REAL guest
if (isset($USER->capabilities[$sitecontext->id]['moodle/legacy:guest']) and $USER->username != 'guest') {
- unset($USER->capabilities[$sitecontext->id]['moodle/legacy:guest']);
+ unset($USER->capabilities[$sitecontext->id]['moodle/legacy:guest']);
unset($USER->capabilities[$sitecontext->id]['moodle/course:view']); // No access to courses by default
}
}
* @return array of contextids
*/
function get_parent_cats($context, $type) {
-
+
$parents = array();
-
+
switch ($type) {
case CONTEXT_COURSECAT:
if (!$cat = get_record('course_categories','id',$context->instanceid)) {
$cat = get_record('course_categories','id',$cat->parent);
}
break;
-
+
case CONTEXT_COURSE:
if (!$course = get_record('course', 'id', $context->instanceid)) {
break;
$cat = get_record('course_categories','id',$cat->parent);
}
break;
-
+
default:
break;
}
* @param string $errorstring - an errorstring
* @param string $stringfile - which stringfile to get it from
*/
-function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
+function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
$errormessage="nopermissions", $stringfile='') {
global $USER;
require_login();
}
}
-
+
/// OK, if they still don't have the capability then print a nice error message
if (!has_capability($capability, $context, $userid, $doanything)) {
if (isset($capabilities[$sitecontext->id]['moodle/site:doanything'])) {
return (0 < $capabilities[$sitecontext->id]['moodle/site:doanything']);
}
-
+
switch ($context->aggregatelevel) {
-
+
case CONTEXT_COURSECAT:
// Check parent cats.
$parentcats = get_parent_cats($context, CONTEXT_COURSECAT);
$usercontexts = array();
if ($context) { // if context is specified
- $usercontexts = get_parent_contexts($context);
+ $usercontexts = get_parent_contexts($context);
} else { // else, we load everything
if ($userroles = get_records('role_assignments','userid',$userid)) {
foreach ($userroles as $userrole) {
if ($capability) {
$capsearch = " AND rc.capability = '$capability' ";
} else {
- $capsearch ="";
+ $capsearch ="";
}
/// Then we use 1 giant SQL to bring out all relevant capabilities.
$SQL = " SELECT rc.capability, c1.id, (c1.aggregatelevel * 100) AS aggrlevel,
SUM(rc.permission) AS sum
FROM
- {$CFG->prefix}role_assignments ra,
+ {$CFG->prefix}role_assignments ra,
{$CFG->prefix}role_capabilities rc,
{$CFG->prefix}context c1
WHERE
ra.roleid=rc.roleid AND
ra.userid=$userid AND
$searchcontexts1
- rc.contextid=$siteinstance->id
+ rc.contextid=$siteinstance->id
$capsearch
GROUP BY
rc.capability, (c1.aggregatelevel * 100), c1.id
{$CFG->prefix}context c2
WHERE
ra.contextid=c1.id AND
- ra.roleid=rc.roleid AND
- ra.userid=$userid AND
- rc.contextid=c2.id AND
+ ra.roleid=rc.roleid AND
+ ra.userid=$userid AND
+ rc.contextid=c2.id AND
$searchcontexts1
$searchcontexts2
rc.contextid != $siteinstance->id
$capsearch
-
+
GROUP BY
rc.capability, (c1.aggregatelevel * 100 + c2.aggregatelevel), c1.id
HAVING
while (!$rs->EOF) {
$array = $rs->fields;
$temprecord = new object;
-
+
foreach ($array as $key=>$val) {
if ($key == 'aggrlevel') {
$temprecord->aggregatelevel = $val;
$rs->MoveNext();
}
}
-
+
/* so up to this point we should have somethign like this
* $capabilities[1] ->aggregatelevel = 1000
->module = SITEID
->capability = do_anything
->id = 1 (id is the context id)
->sum = 0
-
+
* $capabilities[2] ->aggregatelevel = 1000
->module = SITEID
->capability = post_messages
->capability = view_course_activities
->id = 26
->sum = 0 (this is another course)
-
+
* $capabilities[5] ->aggregatelevel = 3050
->module = course
->capability = view_course_activities
$context = get_context_instance_by_id($capability->id);
if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
-
+
if (capability_prohibits($capability->capability, $context, $capability->sum, $usercap)) {
$usercap[$capability->id][$capability->capability] = -9000;
continue;
}
- $usercap[$capability->id][$capability->capability] = $capability->sum;
-
+ $usercap[$capability->id][$capability->capability] = $capability->sum;
+
} else {
if (capability_prohibits($capability->capability, $context, $capability->sum)) { // if any parent or parent's parent is set to prohibit
$USER->capabilities[$capability->id][$capability->capability] = -9000;
continue;
}
-
+
// if no parental prohibit set
// just write to session, i am not sure this is correct yet
// since 3050 shows up after 3000, and 3070 shows up after 3050,
$USER->capabilities[$capability->id][$capability->capability] = $capability->sum;
}
}
-
+
// now we don't care about the huge array anymore, we can dispose it.
unset($capabilities);
-
+
if (!empty($otheruserid)) {
- return $usercap; // return the array
+ return $usercap; // return the array
}
// see array in session to see what it looks like
/*
* Check all the login enrolment information for the given user object
- * by querying the enrolment plugins
+ * by querying the enrolment plugins
*/
function check_enrolment_plugins(&$user) {
global $CFG;
require_once($CFG->dirroot .'/enrol/enrol.class.php');
-
+
if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
$plugins = array($CFG->enrol);
}
// If this capability is set to prohibit.
return true;
}
-
+
if (isset($array)) {
- if (isset($array[$context->id][$capability])
+ if (isset($array[$context->id][$capability])
&& $array[$context->id][$capability] < -8000) {
return true;
- }
+ }
} else {
// Else if set in session.
- if (isset($USER->capabilities[$context->id][$capability])
+ if (isset($USER->capabilities[$context->id][$capability])
&& $USER->capabilities[$context->id][$capability] < -8000) {
return true;
}
}
switch ($context->aggregatelevel) {
-
+
case CONTEXT_SYSTEM:
// By now it's a definite an inherit.
return 0;
*/
function print_capabilities($modid=0) {
global $CFG;
-
+
$capabilities = array();
if ($modid) {
// Call the function that grabs the file and parse.
$cm = get_record('course_modules', 'id', $modid);
$module = get_record('modules', 'id', $cm->module);
-
+
} else {
// Print all capabilities.
foreach ($capabilities as $capability) {
function moodle_install_roles() {
global $CFG, $db;
-
+
// Create a system wide context for assignemnt.
$systemcontext = $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
// Create default/legacy roles and capabilities.
// (1 legacy capability per legacy role at system level).
- $adminrole = create_role(get_string('administrator'), 'admin', get_string('administratordescription'), 'moodle/legacy:admin');
+ $adminrole = create_role(get_string('administrator'), 'admin', get_string('administratordescription'), 'moodle/legacy:admin');
if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
error('Could not assign moodle/site:doanything to the admin role');
}
- $coursecreatorrole = create_role(get_string('coursecreators'), 'coursecreator', get_string('coursecreatorsdescription'), 'moodle/legacy:coursecreator');
- $editteacherrole = create_role(get_string('defaultcourseteacher'), 'editingteacher', get_string('defaultcourseteacherdescription'), 'moodle/legacy:editingteacher');
- $noneditteacherrole = create_role(get_string('noneditingteacher'), 'teacher', get_string('noneditingteacherdescription'), 'moodle/legacy:teacher');
+ $coursecreatorrole = create_role(get_string('coursecreators'), 'coursecreator', get_string('coursecreatorsdescription'), 'moodle/legacy:coursecreator');
+ $editteacherrole = create_role(get_string('defaultcourseteacher'), 'editingteacher', get_string('defaultcourseteacherdescription'), 'moodle/legacy:editingteacher');
+ $noneditteacherrole = create_role(get_string('noneditingteacher'), 'teacher', get_string('noneditingteacherdescription'), 'moodle/legacy:teacher');
$studentrole = create_role(get_string('defaultcoursestudent'), 'student', get_string('defaultcoursestudentdescription'), 'moodle/legacy:student');
$guestrole = create_role(get_string('guest'), 'guest', get_string('guestdescription'), 'moodle/legacy:guest');
// assign above new roles. If a user has both teacher and student role,
// only teacher role is assigned. The assignment should be system level.
$dbtables = $db->MetaTables('TABLES');
-
+
/**
* Upgrade the admins.
* Sort using id ASC, first one is primary admin.
*/
if (in_array($CFG->prefix.'user_admins', $dbtables)) {
- if ($useradmins = get_records_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
+ if ($useradmins = get_records_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
foreach ($useradmins as $admin) {
role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
}
*/
if (in_array($CFG->prefix.'user_students', $dbtables)) {
if ($userstudents = get_records('user_students')) {
- foreach ($userstudents as $student) {
+ foreach ($userstudents as $student) {
// populate the user_lastaccess table
unset($access);
$access->timeaccess = $student->timeaccess;
}
/**
- * Insert the correct records for legacy roles
+ * Insert the correct records for legacy roles
*/
allow_assign($adminrole, $adminrole);
allow_assign($adminrole, $coursecreatorrole);
allow_assign($adminrole, $noneditteacherrole);
- allow_assign($adminrole, $editteacherrole);
+ allow_assign($adminrole, $editteacherrole);
allow_assign($adminrole, $studentrole);
allow_assign($adminrole, $guestrole);
-
+
allow_assign($coursecreatorrole, $noneditteacherrole);
allow_assign($coursecreatorrole, $editteacherrole);
- allow_assign($coursecreatorrole, $studentrole);
+ allow_assign($coursecreatorrole, $studentrole);
allow_assign($coursecreatorrole, $guestrole);
-
- allow_assign($editteacherrole, $noneditteacherrole);
- allow_assign($editteacherrole, $studentrole);
+
+ allow_assign($editteacherrole, $noneditteacherrole);
+ allow_assign($editteacherrole, $studentrole);
allow_assign($editteacherrole, $guestrole);
-
+
/// overrides
allow_override($adminrole, $adminrole);
allow_override($adminrole, $coursecreatorrole);
allow_override($adminrole, $noneditteacherrole);
- allow_override($adminrole, $editteacherrole);
+ allow_override($adminrole, $editteacherrole);
allow_override($adminrole, $studentrole);
- allow_override($adminrole, $guestrole);
+ allow_override($adminrole, $guestrole);
// Should we delete the tables after we are done? Not yet.
* @return boolean - success or failure.
*/
function assign_legacy_capabilities($capability, $legacyperms) {
-
+
foreach ($legacyperms as $type => $perm) {
-
+
$systemcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
-
+
// The legacy capabilities are:
// 'moodle/legacy:guest'
// 'moodle/legacy:student'
// 'moodle/legacy:editingteacher'
// 'moodle/legacy:coursecreator'
// 'moodle/legacy:admin'
-
+
if ($roles = get_roles_with_capability('moodle/legacy:'.$type, CAP_ALLOW)) {
foreach ($roles as $role) {
// Assign a site level capability.
*/
function islegacy($capabilityname) {
if (strstr($capabilityname, 'legacy') === false) {
- return false;
+ return false;
} else {
- return true;
+ return true;
}
}
* @return id or false
*/
function create_role($name, $shortname, $description, $legacy='') {
-
+
// check for duplicate role name
-
+
if ($role = get_record('role','name', $name)) {
- error('there is already a role with this name!');
+ error('there is already a role with this name!');
}
-
+
if ($role = get_record('role','shortname', $shortname)) {
- error('there is already a role with this shortname!');
+ error('there is already a role with this shortname!');
}
$role->name = $name;
$role->shortname = $shortname;
$role->description = $description;
-
- $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
-
+
+ $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
+
if ($id = insert_record('role', $role)) {
- if ($legacy) {
- assign_capability($legacy, CAP_ALLOW, $id, $context->id);
+ if ($legacy) {
+ assign_capability($legacy, CAP_ALLOW, $id, $context->id);
}
-
+
/// By default, users with role:manage at site level
/// should be able to assign users to this new role, and override this new role's capabilities
-
+
// find all admin roles
if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
// foreach admin role
foreach ($adminroles as $arole) {
// write allow_assign and allow_overrid
allow_assign($arole->id, $id);
- allow_override($arole->id, $id);
+ allow_override($arole->id, $id);
}
}
-
+
return $id;
} else {
- return false;
+ return false;
}
-
+
}
/**
* @param permission - int 1,-1 or -1000
*/
function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
-
+
global $USER;
-
+
if (empty($permission) || $permission == 0) { // if permission is not set
- unassign_capability($capability, $roleid, $contextid);
+ unassign_capability($capability, $roleid, $contextid);
}
-
+
$existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
if ($existing and !$overwrite) { // We want to keep whatever is there already
* @return boolean - success or failure
*/
function unassign_capability($capability, $roleid, $contextid=NULL) {
-
+
if (isset($contextid)) {
$status = delete_records('role_capabilities', 'capability', $capability,
'roleid', $roleid, 'contextid', $contextid);
function get_roles_with_capability($capability, $permission=NULL, $context='') {
global $CFG;
-
+
if ($context) {
if ($contexts = get_parent_contexts($context)) {
$listofcontexts = '('.implode(',', $contexts).')';
} else {
$sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
- $listofcontexts = '('.$sitecontext->id.')'; // must be site
- }
+ $listofcontexts = '('.$sitecontext->id.')'; // must be site
+ }
$contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
} else {
$contextstr = '';
}
-
- $selectroles = "SELECT r.*
+
+ $selectroles = "SELECT r.*
FROM {$CFG->prefix}role r,
{$CFG->prefix}role_capabilities rc
WHERE rc.capability = '$capability'
notify('Either userid or groupid must be provided');
return false;
}
-
+
if ($userid && !record_exists('user', 'id', $userid)) {
notify('User does not exist!');
return false;
/// Make sure they have an entry in user_lastaccess for courses they can access
// role_add_lastaccess_entries($userid, $context);
}
-
+
/// now handle metacourse role assignments if in course context
if ($success and $context->aggregatelevel == CONTEXT_COURSE) {
if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0) {
global $USER, $CFG;
-
+
$success = true;
$args = array('roleid', 'userid', 'groupid', 'contextid');
return $success;
}
-/*
- * A convenience function to take care of the common case where you
+/*
+ * A convenience function to take care of the common case where you
* just want to enrol someone using the default role into a course
*
* @param object $course
if (role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
return false;
}
-
+
email_welcome_message_to_user($course, $user);
-
+
add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
return true;
}
}
break;
-
+
case CONTEXT_COURSE: // For a whole course
if ($course = get_record('course', 'id', $context->instanceid)) {
$varprefix = 'moodle';
} else {
$compparts = explode('/', $component);
-
+
if ($compparts[0] == 'block') {
// Blocks are an exception. Blocks directory is 'blocks', and not
// 'block'. So we need to jump through hoops.
}
}
$capabilities = array();
-
+
if (file_exists($defpath)) {
require_once($defpath);
$capabilities = ${$varprefix.'_capabilities'};
*
* Note that the absence of the db/access.php capabilities definition file
* will cause any stored capabilities for the component to be removed from
- * the database.
+ * the database.
*
* @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
* @return boolean
*/
function update_capabilities($component='moodle') {
-
+
$storedcaps = array();
$filecaps = load_capability_def($component);
// Are there new capabilities in the file definition?
$newcaps = array();
-
+
foreach ($filecaps as $filecap => $def) {
- if (!$storedcaps ||
+ if (!$storedcaps ||
($storedcaps && in_array($filecap, $storedcaps) === false)) {
if (!array_key_exists('riskbitmask', $def)) {
$def['riskbitmask'] = 0; // no risk if not specified
$capability->contextlevel = $capdef['contextlevel'];
$capability->component = $component;
$capability->riskbitmask = $capdef['riskbitmask'];
-
+
if (!insert_record('capabilities', $capability, false, 'id')) {
return false;
}
-
+
global $db;
$db->debug= 999;
// Do we need to assign the new capabilities to roles that have the
// definition that we need to delete from the stored capabilities and
// role assignments?
capabilities_cleanup($component, $filecaps);
-
+
return true;
}
* @return int - number of deprecated capabilities that have been removed
*/
function capabilities_cleanup($component, $newcapdef=NULL) {
-
+
$removedcount = 0;
-
+
if ($cachedcaps = get_cached_capabilities($component)) {
foreach ($cachedcaps as $cachedcap) {
if (empty($newcapdef) ||
array_key_exists($cachedcap->name, $newcapdef) === false) {
-
+
// Remove from capabilities cache.
if (!delete_records('capabilities', 'name', $cachedcap->name)) {
error('Could not delete deprecated capability '.$cachedcap->name);
/**
- * Extracts the relevant capabilities given a contextid.
+ * Extracts the relevant capabilities given a contextid.
* All case based, example an instance of forum context.
* Will fetch all forum related capabilities, while course contexts
* Will fetch all capabilities
* `component` varchar(100) NOT NULL,
*/
function fetch_context_capabilities($context) {
-
+
global $CFG;
$sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
-
+
switch ($context->aggregatelevel) {
case CONTEXT_SYSTEM: // all
case CONTEXT_PERSONAL:
$SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
break;
-
+
case CONTEXT_USER:
$SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_USER;
break;
-
+
case CONTEXT_COURSECAT: // all
$SQL = "select * from {$CFG->prefix}capabilities";
break;
case CONTEXT_MODULE: // mod caps
$cm = get_record('course_modules', 'id', $context->instanceid);
$module = get_record('modules', 'id', $cm->module);
-
+
$SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
and component = 'mod/$module->name'";
break;
case CONTEXT_BLOCK: // block caps
$cb = get_record('block_instance', 'id', $context->instanceid);
$block = get_record('block', 'id', $cb->blockid);
-
+
$SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
and component = 'block/$block->name'";
break;
}
// end of special sorting
return $records;
-
+
}
* @return array of capability records from the capabilities table.
*/
function fetch_context_independent_capabilities() {
-
+
$contextindependentcaps = array(
'moodle/site:accessallgroups'
);
$records = array();
-
+
foreach ($contextindependentcaps as $capname) {
$record = get_record('capabilities', 'name', $capname);
array_push($records, $record);
*/
function role_context_capabilities($roleid, $context, $cap='') {
global $CFG;
-
+
$contexts = get_parent_contexts($context);
$contexts[] = $context->id;
$contexts = '('.implode(',', $contexts).')';
-
+
if ($cap) {
$search = " AND rc.capability = '$cap' ";
} else {
- $search = '';
+ $search = '';
}
-
- $SQL = "SELECT rc.*
- FROM {$CFG->prefix}role_capabilities rc,
+
+ $SQL = "SELECT rc.*
+ FROM {$CFG->prefix}role_capabilities rc,
{$CFG->prefix}context c
WHERE rc.contextid in $contexts
AND rc.roleid = $roleid
AND rc.contextid = c.id $search
- ORDER BY c.aggregatelevel DESC,
- rc.capability DESC";
+ ORDER BY c.aggregatelevel DESC,
+ rc.capability DESC";
$capabilities = array();
-
+
if ($records = get_records_sql($SQL)) {
// We are traversing via reverse order.
foreach ($records as $record) {
// If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
$capabilities[$record->capability] = $record->permission;
- }
+ }
}
}
return $capabilities;
}
/**
- * Recursive function which, given a context, find all parent context ids,
+ * Recursive function which, given a context, find all parent context ids,
* and return the array in reverse order, i.e. parent first, then grand
* parent, etc.
* @param object $context
return array($parent->id);
}
break;
-
+
case CONTEXT_USER:
if (!$parent = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
return array();
return array($parent->id);
}
break;
-
+
case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
return array();
*/
function get_related_contexts_string($context) {
if ($parents = get_parent_contexts($context)) {
- return (' IN ('.$context->id.','.implode(',', $parents).')');
+ return (' IN ('.$context->id.','.implode(',', $parents).')');
} else {
return (' ='.$context->id);
}
* @param $capabilityname - e.g. mod/choice:readresponses
*/
function get_capability_string($capabilityname) {
-
+
// Typical capabilityname is mod/choice:readresponses
$names = split('/', $capabilityname);
$stringname = $names[1]; // choice:readresponses
- $components = split(':', $stringname);
+ $components = split(':', $stringname);
$componentname = $components[0]; // choice
switch ($names[0]) {
case 'mod':
$string = get_string($stringname, $componentname);
break;
-
+
case 'block':
$string = get_string($stringname, 'block_'.$componentname);
break;
case 'moodle':
$string = get_string($stringname, 'role');
break;
-
+
case 'enrol':
$string = get_string($stringname, 'enrol_'.$componentname);
- break;
-
+ break;
+
default:
$string = get_string($stringname);
- break;
-
+ break;
+
}
return $string;
}
default:
error ('This is an unknown context!');
return false;
-
+
}
return $string;
}
global $CFG;
$contextlist = get_related_contexts_string($context);
-
+
$sql = "SELECT DISTINCT r.id,
r.name,
r.shortname,
r.sortorder
FROM {$CFG->prefix}role_assignments ra,
- {$CFG->prefix}role r
- WHERE r.id = ra.roleid
+ {$CFG->prefix}role r
+ WHERE r.id = ra.roleid
AND ra.contextid $contextlist
ORDER BY r.sortorder ASC";
-
+
return get_records_sql($sql);
}
-/** this function is used to print roles column in user profile page.
+/** this function is used to print roles column in user profile page.
* @param int userid
* @param int contextid
* @return string
*/
function get_user_roles_in_context($userid, $contextid){
global $CFG;
-
+
$rolestring = '';
$SQL = 'select * from '.$CFG->prefix.'role_assignments ra, '.$CFG->prefix.'role r where ra.userid='.$userid.' and ra.contextid='.$contextid.' and ra.roleid = r.id';
if ($roles = get_records_sql($SQL)) {
foreach ($roles as $userrole) {
$rolestring .= '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$userrole->contextid.'&roleid='.$userrole->roleid.'">'.$userrole->name.'</a>, ';
- }
-
+ }
+
}
return rtrim($rolestring, ', ');
}
// first check if user has override capability
// if not return false;
if (!has_capability('moodle/role:override', $context)) {
- return false;
+ return false;
}
// pull out all active roles of this user from this context(or above)
if ($userroles = get_user_roles($context)) {
}
}
}
-
+
return false;
-
+
}
/**
* @return boolean
*/
function user_can_assign($context, $targetroleid) {
-
+
// first check if user has override capability
// if not return false;
if (!has_capability('moodle/role:assign', $context)) {
- return false;
+ return false;
}
// pull out all active roles of this user from this context(or above)
if ($userroles = get_user_roles($context)) {
}
}
}
-
- return false;
+
+ return false;
}
/**
WHERE ra.userid = '.$userid.
' AND ra.roleid = r.id
AND ra.contextid = c.id
- AND '.$contexts.
+ AND '.$contexts.
' ORDER BY c.aggregatelevel DESC');
}
/**
- * Creates a record in the allow_override table
+ * Creates a record in the allow_override table
* @param int sroleid - source roleid
* @param int troleid - target roleid
* @return int - id or false
}
/**
- * Creates a record in the allow_assign table
+ * Creates a record in the allow_assign table
* @param int sroleid - source roleid
* @param int troleid - target roleid
* @return int - id or false
}
}
}
-
- return $options;
+
+ return $options;
}
/*
* Returns a role object that is the default role for new enrolments
* in a given course
*
- * @param object $course
+ * @param object $course
* @return object $role
*/
function get_default_course_role($course) {
* @param $fields - fields to be pulled
* @param $sort - the sort order
* @param $limitfrom - number of records to skip (offset)
- * @param $limitnum - number of records to fetch
+ * @param $limitnum - number of records to fetch
* @param $groups - single group or array of groups - group(s) user is in
* @param $exceptions - list of users to exclude
*/
-function get_users_by_capability($context, $capability, $fields='', $sort='',
+function get_users_by_capability($context, $capability, $fields='', $sort='',
$limitfrom='', $limitnum='', $groups='', $exceptions='') {
global $CFG;
-
+
/// Sorting out groups
if ($groups) {
$groupjoin = 'INNER JOIN '.$CFG->prefix.'groups_members gm ON gm.userid = ra.userid';
-
+
if (is_array($groups)) {
$groupsql = 'AND gm.groupid IN ('.implode(',', $groups).')';
} else {
- $groupsql = 'AND gm.groupid = '.$groups;
+ $groupsql = 'AND gm.groupid = '.$groups;
}
} else {
$groupjoin = '';
- $groupsql = '';
+ $groupsql = '';
}
-
+
/// Sorting out exceptions
$exceptionsql = $exceptions ? "AND u.id NOT IN ($exceptions)" : '';
$sort = 'ul.timeaccess';
}
- $sortby = $sort ? " ORDER BY $sort " : '';
-
+ $sortby = $sort ? " ORDER BY $sort " : '';
+
/// If context is a course, then construct sql for ul
if ($context->aggregatelevel == CONTEXT_COURSE) {
$courseid = $context->instanceid;
if ($caps[$capability] > 0) { // resolved capability > 0
$validroleids[] = $prole->id;
}
- }
+ }
$roleids = '('.implode(',', $validroleids).')';
/// Construct the main SQL
$select = " SELECT $fields";
- $from = " FROM {$CFG->prefix}user u
- INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
+ $from = " FROM {$CFG->prefix}user u
+ INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON ul.userid = u.id
$groupjoin";
- $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
- AND u.deleted = 0
- AND ra.roleid in $roleids
+ $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
+ AND u.deleted = 0
+ AND ra.roleid in $roleids
$exceptionsql
$coursesql
$groupsql";
- return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
+ return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
}
/**
*/
function get_role_users($roleid, $context, $parent=false) {
global $CFG;
-
+
if ($parent) {
if ($contexts = get_parent_contexts($context)) {
$parentcontexts = 'r.contextid IN ('.implode(',', $contexts).')';
} else {
- $parentcontexts = '';
+ $parentcontexts = '';
}
} else {
- $parentcontexts = '';
- }
-
- $SQL = "select u.*
- from {$CFG->prefix}role_assignments r,
- {$CFG->prefix}user u
- where (r.contextid = $context->id $parentcontexts)
- and r.roleid = $roleid
+ $parentcontexts = '';
+ }
+
+ $SQL = "select u.*
+ from {$CFG->prefix}role_assignments r,
+ {$CFG->prefix}user u
+ where (r.contextid = $context->id $parentcontexts)
+ and r.roleid = $roleid
and u.id = r.userid"; // join now so that we can just use fullname() later
-
+
return get_records_sql($SQL);
}
-/**
+/**
* This function gets the list of courses that this user has a particular capability in
* This is not the most efficient way of doing this
* @param string capability
* @return array
*/
function get_user_capability_course($capability, $userid='') {
-
+
global $USER;
if (!$userid) {
- $userid = $USER->id;
+ $userid = $USER->id;
}
-
+
$usercourses = array();
$courses = get_records_select('course', '', '', 'id, id');
-
+
foreach ($courses as $course) {
if (has_capability($capability, get_context_capability(CONTEXT_COURSE, $course->id))) {
$usercourses[] = $course;
}
}
- return $usercourses;
+ return $usercourses;
}
\ No newline at end of file
* @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
* @param string $dir The directory where the plugins are located (e.g. 'question/questiontypes')
* @param string $return The url to prompt the user to continue to
- */
+ */
function upgrade_plugins($type, $dir, $return) {
global $CFG, $db;
$info->currentmoodle = $CFG->version;
$info->requiremoodle = $plugin->requires;
if (!$updated_plugins) {
- print_header($strpluginsetup, $strpluginsetup, $strpluginsetup, '',
+ print_header($strpluginsetup, $strpluginsetup, $strpluginsetup, '',
'<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
false, ' ', ' ');
}
if (!isset($CFG->$pluginversion)) {
set_config($pluginversion, 0);
}
-
+
if ($CFG->$pluginversion == $plugin->version) {
// do nothing
} else if ($CFG->$pluginversion < $plugin->version) {
if (!$updated_plugins) {
- print_header($strpluginsetup, $strpluginsetup, $strpluginsetup, '',
+ print_header($strpluginsetup, $strpluginsetup, $strpluginsetup, '',
'<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
false, ' ', ' ');
}
$status = install_from_xmldb_file($fullplug . '/db/install.xml'); //New method
} else if (file_exists($fullplug .'/db/'. $CFG->dbtype .'.sql')) {
$status = modify_database($fullplug .'/db/'. $CFG->dbtype .'.sql'); //Old method
- } else {
+ } else {
$status = true;
}
$db->debug = false;
- /// Continue with the instalation, roles and other stuff
+ /// Continue with the instalation, roles and other stuff
if ($status) {
// OK so far, now update the plugins record
set_config($pluginversion, $plugin->version);
* @uses $CFG
* @param string $return The url to prompt the user to continue to
* @todo Finish documenting this function
- */
+ */
function upgrade_activity_modules($return) {
global $CFG, $db;
$info->currentmoodle = $CFG->version;
$info->requiremoodle = $module->requires;
if (!$updated_modules) {
- print_header($strmodulesetup, $strmodulesetup, $strmodulesetup, '',
+ print_header($strmodulesetup, $strmodulesetup, $strmodulesetup, '',
'<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
false, ' ', ' ');
}
}
$module->name = $mod; // The name MUST match the directory
-
+
if ($currmodule = get_record('modules', 'name', $module->name)) {
if ($currmodule->version == $module->version) {
// do nothing
continue;
}
if (!$updated_modules) {
- print_header($strmodulesetup, $strmodulesetup, $strmodulesetup, '',
+ print_header($strmodulesetup, $strmodulesetup, $strmodulesetup, '',
'<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
false, ' ', ' ');
}
}
$updated_modules = true;
-
+
} else {
upgrade_log_start();
error('Version mismatch: '. $module->name .' can\'t downgrade '. $currmodule->version .' -> '. $module->version .' !');
}
-
+
} else { // module not installed yet, so install it
if (!$updated_modules) {
- print_header($strmodulesetup, $strmodulesetup, $strmodulesetup, '',
+ print_header($strmodulesetup, $strmodulesetup, $strmodulesetup, '',
'<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>',
false, ' ', ' ');
}
} else {
error($module->name .' module could not be added to the module list!');
}
- } else {
+ } else {
error($module->name .' tables could NOT be set up successfully!');
}
}
if ( is_readable($fullmod .'/defaults.php')) {
// Insert default values for any important configuration variables
unset($defaults);
- include_once($fullmod .'/defaults.php');
+ include_once($fullmod .'/defaults.php');
if (!empty($defaults)) {
foreach ($defaults as $name => $value) {
if (!isset($CFG->$name)) {
}
}
-/**
+/**
* This function will return FALSE if the lock fails to be set (ie, if it's already locked)
*
* @param string $name ?
/// This file performs the following tasks:
/// -it defines the necessary objects and interfaces to build the Moodle
/// admin hierarchy
-/// -it defines the admin_externalpage_setup(), admin_externalpage_print_header(),
+/// -it defines the admin_externalpage_setup(), admin_externalpage_print_header(),
/// and admin_externalpage_print_footer() functions used on admin pages
/// ADMIN_SETTING OBJECTS
-/// Moodle settings are represented by objects that inherit from the admin_setting
+/// Moodle settings are represented by objects that inherit from the admin_setting
/// class. These objects encapsulate how to read a setting, how to write a new value
/// to a setting, and how to appropriately display the HTML to modify the setting.
/// admin/settings/first.php (at the end of the file) or to some other file in
/// admin/settings:
-/// $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
+/// $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
/// $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
/// Next, in foo.php, your file structure would resemble the following:
* @param string $name The internal name of the part_of_admin_tree we're searching for.
* @return mixed An object reference or a NULL reference.
*/
- function &locate($name) {
- trigger_error('Admin class does not implement method <strong>locate()</strong>', E_USER_WARNING);
- return;
+ function &locate($name) {
+ trigger_error('Admin class does not implement method <strong>locate()</strong>', E_USER_WARNING);
+ return;
}
/**
* @return boolean success.
*/
function prune($name) {
- trigger_error('Admin class does not implement method <strong>prune()</strong>', E_USER_WARNING);
+ trigger_error('Admin class does not implement method <strong>prune()</strong>', E_USER_WARNING);
return;
- }
+ }
/**
* Verifies current user's access to this part_of_admin_tree.
*
* @return bool True if the user has access, false if she doesn't.
*/
- function check_access() {
- trigger_error('Admin class does not implement method <strong>check_access()</strong>', E_USER_WARNING);
- return;
+ function check_access() {
+ trigger_error('Admin class does not implement method <strong>check_access()</strong>', E_USER_WARNING);
+ return;
}
-
+
/**
* Determines the path to $name in the admin tree.
*
* @param array $path Not used on external calls. Defaults to empty array.
* @return mixed If found, an array containing the internal names of each part_of_admin_tree that leads to $name. If not found, NULL.
*/
- function path($name, $path = array()) {
- trigger_error('Admin class does not implement method <strong>path()</strong>', E_USER_WARNING);
- return;
+ function path($name, $path = array()) {
+ trigger_error('Admin class does not implement method <strong>path()</strong>', E_USER_WARNING);
+ return;
}
}
*
* The pseudointerface implemented by any part_of_admin_tree that can be a parent
* to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
- * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
+ * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
* include an add method for adding other part_of_admin_tree objects as children.
*
* @author Vincenzo K. Marcovecchio
* @package admin
*/
class parentable_part_of_admin_tree extends part_of_admin_tree {
-
+
/**
* Adds a part_of_admin_tree object to the admin tree.
*
* @param part_of_admin_tree &$something The object to be added.
* @return bool True on success, false on failure.
*/
- function add($destinationname, &$something) {
- trigger_error('Admin class does not implement method <strong>add()</strong>', E_USER_WARNING);
- return;
+ function add($destinationname, &$something) {
+ trigger_error('Admin class does not implement method <strong>add()</strong>', E_USER_WARNING);
+ return;
}
-
+
}
/**
* The object used to represent folders (a.k.a. categories) in the admin tree block.
- *
+ *
* Each admin_category object contains a number of part_of_admin_tree objects.
*
* @author Vincenzo K. Marcovecchio
* @var mixed An array of part_of_admin_tree objects that are this object's children
*/
var $children;
-
+
/**
* @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
*/
var $name;
-
+
/**
* @var string The displayed name for this category. Usually obtained through get_string()
*/
var $visiblename;
-
+
// constructor for an empty admin category
// $name is the internal name of the category. it MUST be unique in the entire hierarchy
// $visiblename is the displayed name of the category. use a get_string for this
$this->name = $name;
$this->visiblename = $visiblename;
}
-
+
/**
* Finds the path to the part_of_admin_tree called $name.
*
* @return mixed An array of internal names that leads to $name, or NULL if not found.
*/
function path($name, $path = array()) {
-
+
$path[count($path)] = $this->name;
-
+
if ($this->name == $name) {
return $path;
}
-
+
foreach($this->children as $child) {
if ($return = $child->path($name, $path)) {
return $return;
}
}
-
+
return NULL;
-
+
}
/**
* @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
*/
function &locate($name) {
-
+
if ($this->name == $name) {
return $this;
}
-
+
foreach($this->children as $child) {
if ($return =& $child->locate($name)) {
return $return;
foreach($this->children as $precedence => $child) {
if ($child->name == $name) {
// found it!
- unset($this->children[$precedence]);
+ unset($this->children[$precedence]);
return true;
}
if ($this->children[$precedence]->prune($name)) {
* @return bool True if successfully added, false if &$something is not a part_of_admin_tree or if $name is not found.
*/
function add($destinationname, &$something, $precedence = '') {
-
+
if (!is_a($something, 'part_of_admin_tree')) {
return false;
}
}
return true;
}
-
+
unset($entries);
-
+
$entries = array_keys($this->children);
-
+
foreach($entries as $entry) {
$child =& $this->children[$entry];
if (is_a($child, 'parentable_part_of_admin_tree')) {
}
}
}
-
+
return false;
-
+
}
-
+
/**
* Checks if the user has access to anything in this category.
*
* @return bool True if the user has access to atleast one child in this category, false otherwise.
*/
function check_access() {
-
+
$return = false;
foreach ($this->children as $child) {
$return = $return || $child->check_access();
}
-
+
return $return;
-
+
}
-
+
}
/**
*/
class admin_externalpage extends part_of_admin_tree {
- /**
+ /**
* @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects
*/
var $name;
-
+
/**
* @var string The displayed name for this external page. Usually obtained through get_string().
*/
var $visiblename;
-
+
/**
* @var string The external URL that we should link to when someone requests this external page.
*/
var $url;
-
+
/**
* @var string The role capability/permission a user must have to access this external page.
*/
var $role;
-
+
/**
* Constructor for adding an external page into the admin tree.
*
$this->url = $url;
$this->role = $role;
}
-
+
/**
* Finds the path to the part_of_admin_tree called $name.
*
return NULL;
}
}
-
+
/**
* Returns a reference to the part_of_admin_tree object with internal name $name.
*
if (!get_site()) {
return true; // no access check before site is fully set up
}
- $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
+ $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
return has_capability($this->role, $context);
}
*/
class admin_settingpage extends part_of_admin_tree {
- /**
+ /**
* @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects
*/
var $name;
-
+
/**
* @var string The displayed name for this external page. Usually obtained through get_string().
*/
* @var mixed An array of admin_setting objects that are part of this setting page.
*/
var $settings;
-
+
/**
* @var string The role capability/permission a user must have to access this external page.
*/
var $role;
-
+
// see admin_category
function path($name, $path = array()) {
if ($name == $this->name) {
return NULL;
}
}
-
+
// see admin_category
function &locate($name) {
$return = ($this->name == $name ? $this : NULL);
$this->visiblename = $visiblename;
$this->role = $role;
}
-
+
// not the same as add for admin_category. adds an admin_setting to this admin_settingpage. settings appear (on the settingpage) in the order in which they're added
// n.b. each admin_setting in an admin_settingpage must have a unique internal name
// &$setting is the admin_setting object you want to add
}
return false;
}
-
+
// see admin_externalpage
function check_access() {
if (!get_site()) {
return true; // no access check before site is fully set up
}
- $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
+ $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
return has_capability($this->role, $context);
}
-
+
// outputs this page as html in a table (suitable for inclusion in an admin pagetype)
// returns a string of the html
function output_html() {
$this->description = $description;
$this->defaultsetting = $defaultsetting;
}
-
+
function get_setting() {
return NULL; // has to be overridden
}
-
+
function write_setting($data) {
return; // has to be overridden
}
-
+
function output_html() {
return; // has to be overridden
}
-
+
}
global $CFG;
return (isset($CFG->{$this->name}) ? $CFG->{$this->name} : NULL);
}
-
+
// $data is a string
function write_setting($data) {
if (is_string($this->paramtype)) {
global $CFG;
return (isset($CFG->{$this->name}) ? $CFG->{$this->name} : NULL);
}
-
+
function write_setting($data) {
if ($data == '1') {
return (set_config($this->name,1) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
class admin_setting_configselect extends admin_setting {
var $choices;
-
+
function admin_setting_configselect($name, $visiblename, $description, $defaultsetting, $choices) {
$this->choices = $choices;
parent::admin_setting($name, $visiblename, $description, $defaultsetting);
global $CFG;
return (isset($CFG->{$this->name}) ? $CFG->{$this->name} : NULL);
}
-
+
function write_setting($data) {
// check that what we got was in the original choices
// or that the data is the default setting - needed during install when choices can not be constructed yet
if ($data != $this->defaultsetting and ! in_array($data, array_keys($this->choices))) {
return 'Error setting ' . $this->visiblename . '<br />';
}
-
+
return (set_config($this->name, $data) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
}
-
+
function output_html() {
if ($this->get_setting() === NULL) {
$current = $this->defaultsetting;
global $CFG;
return (isset($CFG->{$this->name}) && isset($CFG->{$this->name2}) ? array('h' => $CFG->{$this->name}, 'm' => $CFG->{$this->name2}) : NULL);
}
-
+
function write_setting($data) {
// check that what we got was in the original choices
if (!(in_array($data['h'], array_keys($this->choices)) && in_array($data['m'], array_keys($this->choices2)))) {
return get_string('errorsetting', 'admin') . $this->visiblename . '<br />';
}
-
+
return (set_config($this->name, $data['h']) && set_config($this->name2, $data['m']) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
}
-
+
function output_html() {
if ($this->get_setting() === NULL) {
$currentsetting = $this->defaultsetting;
$return .= '</select> <select name="s_' . $this->name . '[m]">';
foreach ($this->choices2 as $key => $value) {
$return .= '<option value="' . $key . '"' . ($key == $currentsetting['m'] ? ' selected="selected"' : '') . '>' . $value . '</option>';
- }
+ }
$return .= '</select></td></tr><tr><td> </td><td align="left">' . $this->description . '</td></tr>';
return $return;
}
global $CFG;
return (isset($CFG->{$this->name}) ? explode(',', $CFG->{$this->name}) : NULL);;
}
-
+
function write_setting($data) {
foreach ($data as $datum) {
if (! in_array($datum, array_keys($this->choices))) {
return get_string('errorsetting', 'admin') . $this->visiblename . '<br />';
}
}
-
+
return (set_config($this->name, implode(',',$data)) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
}
-
+
function output_html() {
if ($this->get_setting() === NULL) {
$currentsetting = $this->defaultsetting;
}
class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
-
+
function admin_setting_special_adminseesall() {
$name = 'calendar_adminseesall';
$visiblename = get_string('adminseesall', 'admin');
$this->id = SITEID;
parent::admin_setting_configselect($name, $visiblename, $description, $defaultsetting, $choices);
-
+
}
-
+
function get_setting() {
$site = get_site();
return (isset($site->{$this->name}) ? $site->{$this->name} : NULL);
}
-
+
function write_setting($data) {
if (!in_array($data, array_keys($this->choices))) {
return get_string('errorsetting', 'admin') . $this->visiblename . '<br />';
$record->timemodified = time();
return (update_record('course', $record) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
}
-
+
}
$defaults = FRONTPAGECOURSELIST.',,,';
parent::admin_setting_configselect($name, $visiblename, $description, $defaults, $choices);
}
-
+
function get_setting() {
global $CFG;
return (isset($CFG->{$this->name}) ? explode(',', $CFG->{$this->name}) : NULL);
}
-
+
function write_setting($data) {
if (empty($data)) {
$data = array();
}
return (set_config($this->name, implode(',', $data)) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
}
-
+
function output_html() {
if ($this->get_setting() === NULL) {
$currentsetting = $this->defaultsetting;
}
$return = '<tr><td width="100" align="right" valign="top">' . $this->visiblename . '</td><td align="left">';
for ($i = 0; $i < count($this->choices) - 1; $i++) {
- $return .='<select name="s_' . $this->name .'[]">';
+ $return .='<select name="s_' . $this->name .'[]">';
foreach ($this->choices as $key => $value) {
$return .= '<option value="' . $key . '"' . ($key == $currentsetting[$i] ? ' selected="selected"' : '') . '>' . $value . '</option>';
}
}
}
$return .= '</td></tr><tr><td> </td><td align="left">' . $this->description . '</td></tr>';
- return $return;
+ return $return;
}
}
$this->id = SITEID;
parent::admin_setting_configcheckbox($name, $visiblename, $description, $defaultsetting);
-
+
}
-
+
function get_setting() {
$site = get_site();
return (isset($site->{$this->name}) ? $site->{$this->name} : NULL);
}
-
+
function write_setting($data) {
$record = new stdClass();
$record->id = $this->id;
$record->timemodified = time();
return (update_record('course', $record) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
}
-
+
}
class admin_setting_sitesettext extends admin_setting_configtext {
$this->id = SITEID;
parent::admin_setting_configtext($name, $visiblename, $description, $defaultsetting, $paramtype);
-
+
}
-
+
function get_setting() {
$site = get_site();
return (isset($site->{$this->name}) ? $site->{$this->name} : NULL);
} else {
$data = clean_param($data, $this->paramtype);
}
-
+
$record = new stdClass();
$record->id = $this->id;
$record->{$this->name} = $data;
function validate($data) {
return preg_match($this->paramtype, $data);
}
-
+
}
class admin_setting_special_frontpagedesc extends admin_setting {
var $id;
-
+
function admin_setting_special_frontpagedesc() {
$this->id = SITEID;
$name = 'summary';
}
function output_html() {
-
+
if ($this->get_setting() === NULL) {
$currentsetting = $this->defaultsetting;
} else {
$currentsetting = $this->get_setting();
}
-
+
$usehtmleditor = can_use_html_editor();
-
+
$return = '<tr><td width="100" align="right" valign="top">' . $this->visiblename . '</td>' .
'<td>';
-
+
ob_start(); // double-check the number of columns below... might overrun some screen resolutions
print_textarea($usehtmleditor, 20, 40, 0, 0, 's_' . $this->name, $currentsetting);
-
+
if ($usehtmleditor) {
use_html_editor();
- }
+ }
$return .= ob_get_contents();
- ob_end_clean();
+ ob_end_clean();
$return .= '</td></tr><tr><td> </td><td>' . $this->description . '</td></tr>';
return $return;
-
+
}
-
+
function get_setting() {
-
+
$site = get_site();
return (isset($site->{$this->name}) ? $site->{$this->name} : NULL);
-
+
}
-
+
function write_setting($data) {
-
+
$data = addslashes(clean_param($data, PARAM_CLEANHTML));
-
+
$record = new stdClass();
$record->id = $this->id;
$temp = $this->name;
$record->$temp = $data;
$record->timemodified = time();
-
+
return(update_record('course', $record) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
-
+
}
}
'v8' => 'wingdings');
parent::admin_setting($name, $visiblename, $description, $defaults);
}
-
+
function get_setting() {
global $CFG;
if (isset($CFG->editorfontlist)) {
return NULL;
}
}
-
+
function write_setting($data) {
-
+
// there miiight be an easier way to do this :)
// if this is changed, make sure the $defaults array above is modified so that this
// function processes it correctly
-
+
$keys = array();
$values = array();
-
+
foreach ($data as $key => $value) {
if (substr($key,0,1) == 'k') {
$keys[substr($key,1)] = $value;
$values[substr($key,1)] = $value;
}
}
-
+
$result = '';
for ($i = 0; $i < count($keys); $i++) {
if (($keys[$i] !== '') && ($values[$i] !== '')) {
$result .= clean_param($keys[$i],PARAM_NOTAGS) . ':' . clean_param($values[$i], PARAM_NOTAGS) . ';';
}
}
-
+
$result = substr($result, 0, -1); // trim the last semicolon
-
+
return (set_config($this->name, $result) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
}
-
+
function output_html() {
-
+
if ($this->get_setting() === NULL) {
$currentsetting = $this->defaultsetting;
} else {
$currentsetting = $this->get_setting();
}
-
+
$return = '<tr><td width="100" align="right" valign="top">' . $this->visiblename . '</td><td align="left">';
for ($i = 0; $i < count($currentsetting) / 2; $i++) {
$return .= '<input type="text" name="s_editorfontlist[k' . $i . ']" value="' . $currentsetting['k' . $i] . '" size="20" />';
$return .= '<input type="text" name="s_editorfontlist[k' . ($i + 1) . ']" value="" size="20" />';
$return .= ' ';
$return .= '<input type="text" name="s_editorfontlist[v' . ($i + 1) . ']" value="" size="40" />';
- $return .= '</td></tr><tr><td> </td><td align="left">' . $this->description . '</td></tr>';
+ $return .= '</td></tr><tr><td> </td><td align="left">' . $this->description . '</td></tr>';
return $return;
}
-
+
}
class admin_setting_special_editordictionary extends admin_setting_configselect {
if (! is_array($choices)) {
$choices = array('');
}
-
+
parent::admin_setting_configselect($name, $visiblename, $description, '', $choices);
}
/// Get all installed dictionaries in the system
global $CFG;
-
+
// error_reporting(E_ALL); // for debug, final version shouldn't have this...
clearstatcache();
if (!function_exists('popen')) {
return 'Popen function disabled!';
}
-
+
$cmd = $CFG->aspellpath;
$output = '';
$dictionaries = array();
return 'Error! Check your aspell installation!';
}
-
+
}
}
function output_html() {
-
+
global $CFG;
-
+
// checkboxes with input name="$this->name[$key]" value="1"
// we do 15 fields per column
-
+
if ($this->get_setting() === NULL) {
$currentsetting = $this->defaultsetting;
} else {
$currentsetting = $this->get_setting();
}
-
+
$return = '<tr><td width="100" align="right" valign="top">' . $this->visiblename . '</td><td align="left">';
-
+
$return .= '<table><tr><td valign="top" align="right">';
-
+
$count = 0;
-
+
foreach($this->items as $key => $value) {
if ($count % 15 == 0) {
$return .= '</div></td><td valign="top" align="right">';
}
-
+
$return .= ($value == '' ? get_string($key,'editor') : '<img width="18" height="18" src="' . $CFG->wwwroot . '/lib/editor/htmlarea/images/' . $value . '" alt="' . get_string($key,'editor') . '" title="' . get_string($key,'editor') . '" />') . ' ';
$return .= '<input type="checkbox" value="1" name="s_' . $this->name . '[' . $key . ']"' . (in_array($key,$currentsetting) ? ' checked="checked"' : '') . ' /> ';
$count++;
$return .= '<br /><br />';
}
}
-
- $return .= '</td></tr>';
+
+ $return .= '</td></tr>';
$return .= '</table>';
$return .= '</td></tr><tr><td> </td><td align="left">' . $this->description . '</td></tr>';
$backup_config = backup_get_config();
return (isset($backup_config->{$this->name}) ? $backup_config->{$this->name} : NULL);
}
-
+
function write_setting($data) {
// check that what we got was in the original choices
if (! in_array($data, array_keys($this->choices))) {
return get_string('errorsetting', 'admin') . $this->visiblename . '<br />';
}
-
+
return (backup_set_config($this->name, $data) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
}
$description = get_string('backupsavetohelp');
parent::admin_setting_configtext($name, $visiblename, $description, '', PARAM_PATH);
}
-
+
function get_setting() {
$backup_config = backup_get_config();
return (isset($backup_config->{$this->name}) ? $backup_config->{$this->name} : NULL);
}
-
+
function write_setting($data) {
$data = clean_param($data, PARAM_PATH);
if (!empty($data) and (substr($data,-1) == '/' or substr($data,-1) == '\\')) {
return (backup_set_config($this->name, 0) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
}
}
-
+
function get_setting() {
$backup_config = backup_get_config();
return (isset($backup_config->{$this->name}) ? $backup_config->{$this->name} : NULL);
$default = array('h' => 0, 'm' => 0);
parent::admin_setting_configtime($name, $name2, $visiblename, $description, $default);
}
-
+
function get_setting() {
$backup_config = backup_get_config();
return (isset($backup_config->{$this->name}) && isset($backup_config->{$this->name}) ? array($backup_config->{$this->name}, $backup_config->{$this->name2}) : NULL);
}
-
+
function write_setting($data) {
// check that what we got was in the original choices
if (!(in_array($data['h'], array_keys($this->choices)) && in_array($data['m'], array_keys($this->choices2)))) {
return get_string('errorsetting', 'admin') . $this->visiblename . '<br />';
}
-
- return (backup_set_config($this->name, $data['h']) && backup_set_config($this->name2, $data['m']) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
+
+ return (backup_set_config($this->name, $data['h']) && backup_set_config($this->name2, $data['m']) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
}
-
+
}
class admin_setting_special_backupdays extends admin_setting {
$description = get_string('backupschedulehelp');
parent::admin_setting($name, $visiblename, $description, array());
}
-
+
function get_setting() {
$backup_config = backup_get_config();
if (isset($backup_config->{$this->name})) {
return NULL;
}
}
-
+
function output_html() {
-
+
if ($this->get_setting() === NULL) {
$currentsetting = $this->defaultsetting;
} else {
$currentsetting = $this->get_setting();
}
-
+
// rewrite for simplicity
- $currentsetting = $currentsetting['u'] . $currentsetting['m'] . $currentsetting['t'] . $currentsetting['w'] .
+ $currentsetting = $currentsetting['u'] . $currentsetting['m'] . $currentsetting['t'] . $currentsetting['w'] .
$currentsetting['r'] . $currentsetting['f'] . $currentsetting['s'];
-
+
return '<tr><td width="100" align="right" valign="top">' . $this->visiblename . '</td><td align="left">' .
- '<table><tr><td><div align="center"> ' . get_string('sunday', 'calendar') . ' </div></td><td><div align="center"> ' .
+ '<table><tr><td><div align="center"> ' . get_string('sunday', 'calendar') . ' </div></td><td><div align="center"> ' .
get_string('monday', 'calendar') . ' </div></td><td><div align="center"> ' . get_string('tuesday', 'calendar') . ' </div></td><td><div align="center"> ' .
get_string('wednesday', 'calendar') . ' </div></td><td><div align="center"> ' . get_string('thursday', 'calendar') . ' </div></td><td><div align="center"> ' .
get_string('friday', 'calendar') . ' </div></td><td><div align="center"> ' . get_string('saturday', 'calendar') . ' </div></td></tr><tr>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[u]" value="1" ' . (substr($currentsetting,0,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[m]" value="1" ' . (substr($currentsetting,1,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[t]" value="1" ' . (substr($currentsetting,2,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[w]" value="1" ' . (substr($currentsetting,3,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[r]" value="1" ' . (substr($currentsetting,4,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[f]" value="1" ' . (substr($currentsetting,5,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[s]" value="1" ' . (substr($currentsetting,6,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
- '</tr></table>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[u]" value="1" ' . (substr($currentsetting,0,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[m]" value="1" ' . (substr($currentsetting,1,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[t]" value="1" ' . (substr($currentsetting,2,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[w]" value="1" ' . (substr($currentsetting,3,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[r]" value="1" ' . (substr($currentsetting,4,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[f]" value="1" ' . (substr($currentsetting,5,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[s]" value="1" ' . (substr($currentsetting,6,1) == '1' ? 'checked="checked"' : '') . ' /></div></td>' .
+ '</tr></table>' .
'</td></tr><tr><td> </td><td align="left">' . $this->description . '</td></tr>';
-
+
}
-
+
// we're using the array trick (see http://ca.php.net/manual/en/faq.html.php#faq.html.arrays) to get the data passed to use without having to modify
// admin_settingpage (note that admin_settingpage only calls write_setting with the data that matches $this->name... so if we have multiple form fields,
// they MUST go into an array named $this->name, or else we won't receive them here
$week = 'umtwrfs';
$result = array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0);
foreach($data as $key => $value) {
- if ($value == '1') {
+ if ($value == '1') {
$result[strpos($week, $key)] = 1;
}
}
return NULL;
}
}
-
+
function write_setting($data) {
$week = 'umtwrfs';
$result = array(0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0);
foreach($data as $key => $value) {
- if ($value == '1') {
+ if ($value == '1') {
$result[strpos($week, $key)] = 1;
}
}
return (set_config($this->name, bindec(implode('',$result))) ? '' : get_string('errorsetting', 'admin') . $this->visiblename . '<br />');
}
-
+
function output_html() {
if ($this->get_setting() === NULL) {
}
return '<tr><td width="100" align="right" valign="top">' . $this->visiblename . '</td><td align="left">' .
- '<table><tr><td><div align="center"> ' . get_string('sunday', 'calendar') . ' </div></td><td><div align="center"> ' .
+ '<table><tr><td><div align="center"> ' . get_string('sunday', 'calendar') . ' </div></td><td><div align="center"> ' .
get_string('monday', 'calendar') . ' </div></td><td><div align="center"> ' . get_string('tuesday', 'calendar') . ' </div></td><td><div align="center"> ' .
get_string('wednesday', 'calendar') . ' </div></td><td><div align="center"> ' . get_string('thursday', 'calendar') . ' </div></td><td><div align="center"> ' .
get_string('friday', 'calendar') . ' </div></td><td><div align="center"> ' . get_string('saturday', 'calendar') . ' </div></td></tr><tr>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[u]" value="1" ' . ($currentsetting['u'] ? 'checked="checked"' : '') . ' /></div></td>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[m]" value="1" ' . ($currentsetting['m'] ? 'checked="checked"' : '') . ' /></div></td>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[t]" value="1" ' . ($currentsetting['t'] ? 'checked="checked"' : '') . ' /></div></td>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[w]" value="1" ' . ($currentsetting['w'] ? 'checked="checked"' : '') . ' /></div></td>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[r]" value="1" ' . ($currentsetting['r'] ? 'checked="checked"' : '') . ' /></div></td>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[f]" value="1" ' . ($currentsetting['f'] ? 'checked="checked"' : '') . ' /></div></td>' .
- '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[s]" value="1" ' . ($currentsetting['s'] ? 'checked="checked"' : '') . ' /></div></td>' .
- '</tr></table>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[u]" value="1" ' . ($currentsetting['u'] ? 'checked="checked"' : '') . ' /></div></td>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[m]" value="1" ' . ($currentsetting['m'] ? 'checked="checked"' : '') . ' /></div></td>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[t]" value="1" ' . ($currentsetting['t'] ? 'checked="checked"' : '') . ' /></div></td>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[w]" value="1" ' . ($currentsetting['w'] ? 'checked="checked"' : '') . ' /></div></td>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[r]" value="1" ' . ($currentsetting['r'] ? 'checked="checked"' : '') . ' /></div></td>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[f]" value="1" ' . ($currentsetting['f'] ? 'checked="checked"' : '') . ' /></div></td>' .
+ '<td><div align="center"><input type="checkbox" name="s_'. $this->name .'[s]" value="1" ' . ($currentsetting['s'] ? 'checked="checked"' : '') . ' /></div></td>' .
+ '</tr></table>' .
'</td></tr><tr><td> </td><td align="left">' . $this->description . '</td></tr>';
-
+
}
}
} else {
$currentsetting = $this->get_setting();
}
-
+
return '<tr><td width="100" align="right" valign="top">' . $this->visiblename . '</td>' .
'<td align="left"><input type="checkbox" size="50" name="s_'. $this->name .'" value="1" ' . ($currentsetting == 15 ? 'checked="checked"' : '') . ' /></td></tr>' .
'<tr><td> </td><td align="left">' . $this->description . '</td></tr>';
function admin_externalpage_setup($section, $adminroot) {
global $CFG, $PAGE, $USER;
-
+
require_once($CFG->libdir . '/blocklib.php');
require_once($CFG->dirroot . '/'.$CFG->admin.'/pagelib.php');
-
+
page_map_class(PAGE_ADMIN, 'page_admin');
$PAGE = page_create_object(PAGE_ADMIN, 0); // there must be any constant id number
error(get_string('accessdenied', 'admin'));
die;
}
-
+
$adminediting = optional_param('adminedit', -1, PARAM_BOOL);
-
+
if (!isset($USER->adminediting)) {
$USER->adminediting = false;
}
-
+
if ($PAGE->user_allowed_editing()) {
if ($adminediting == 1) {
$USER->adminediting = true;
$USER->adminediting = false;
}
}
-
+
}
function admin_externalpage_print_header($adminroot) {
global $CFG, $PAGE, $SITE;
-
+
if (!empty($SITE->fullname)) {
$pageblocks = blocks_setup($PAGE);
- $preferred_width_left = bounded_number(BLOCK_L_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]),
+ $preferred_width_left = bounded_number(BLOCK_L_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]),
BLOCK_L_MAX_WIDTH);
-
+
$PAGE->print_header();
echo '<table id="layout-table"><tr>';
echo '<td style="width: ' . $preferred_width_left . 'px;" id="left-column">';
}
}
}
-
+
return $ADMIN;
}
apply_default_settings($node->children[$entry]);
}
return;
- }
+ }
- if (is_a($node, 'admin_settingpage')) {
+ if (is_a($node, 'admin_settingpage')) {
foreach ($node->settings as $setting) {
$CFG->{$setting->name} = $setting->defaultsetting;
$setting->write_setting($setting->defaultsetting);
$moodle_capabilities = array(
-
+
'moodle/site:doanything' => array(
'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS | RISK_CONFIG,
'captype' => 'admin',
'contextlevel' => CONTEXT_SYSTEM
),
-
+
'moodle/legacy:guest' => array(
'captype' => 'legacy',
'contextlevel' => CONTEXT_SYSTEM
),
-
-
+
+
'moodle/legacy:student' => array(
'riskbitmask' => RISK_SPAM,
'captype' => 'legacy',
'contextlevel' => CONTEXT_SYSTEM
),
-
-
+
+
'moodle/legacy:teacher' => array(
'riskbitmask' => RISK_SPAM | RISK_PERSONAL,
'captype' => 'legacy',
'contextlevel' => CONTEXT_SYSTEM
),
-
-
+
+
'moodle/legacy:editingteacher' => array(
'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS,
'captype' => 'legacy',
'contextlevel' => CONTEXT_SYSTEM
),
-
-
+
+
'moodle/legacy:coursecreator' => array(
'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS,
'captype' => 'legacy',
'contextlevel' => CONTEXT_SYSTEM
),
-
-
+
+
'moodle/legacy:admin' => array(
'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS | RISK_CONFIG,
'captype' => 'legacy',
'contextlevel' => CONTEXT_SYSTEM
),
-
-
+
+
'moodle/site:config' => array(
-
+
'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS | RISK_CONFIG,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/site:readallmessages' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/site:approvecourse' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/site:import' => array(
-
+
'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/site:backup' => array(
-
+
'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/site:restore' => array(
-
+
'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/site:manageblocks' => array(
-
+
'riskbitmask' => RISK_SPAM | RISK_XSS,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/site:accessallgroups' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/site:viewfullnames' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/site:viewparticipants' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/site:viewreports' => array(
-
+
'riskbitmask' => RISK_PERSONAL,
'captype' => 'read',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/site:trustcontent' => array(
-
+
'riskbitmask' => RISK_XSS,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/user:create' => array(
-
+
'riskbitmask' => RISK_SPAM | RISK_PERSONAL,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/user:delete' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/user:update' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/user:viewdetails' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
),
'moodle/user:viewhiddendetails' => array(
-
+
'riskbitmask' => RISK_PERSONAL,
'captype' => 'read',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/role:assign' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/role:override' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/role:manage' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_SYSTEM,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/category:create' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_COURSECAT,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/category:delete' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_COURSECAT,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/category:update' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_COURSECAT,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/category:visibility' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_COURSECAT,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:create' => array(
-
+
'riskbitmask' => RISK_XSS,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:delete' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:update' => array(
-
+
'riskbitmask' => RISK_XSS,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:view' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:viewhiddenuserfields' => array(
-
+
'riskbitmask' => RISK_PERSONAL,
'captype' => 'read',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:viewhiddencourses' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:visibility' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:managefiles' => array(
-
+
'riskbitmask' => RISK_XSS,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:managequestions' => array(
-
+
'riskbitmask' => RISK_XSS,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:manageactivities' => array(
-
+
'riskbitmask' => RISK_XSS,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:managemetacourse' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:activityvisibility' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:viewhiddenactivities' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:viewparticipants' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:viewscales' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:managescales' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:managegroups' => array(
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:reset' => array(
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/blog:view' => array(
'captype' => 'read',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/blog:create' => array(
'riskbitmask' => RISK_SPAM,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/blog:manageofficialtags' => array(
'riskbitmask' => RISK_SPAM,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/blog:managepersonaltags' => array(
'riskbitmask' => RISK_SPAM,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/blog:manageentries' => array(
'riskbitmask' => RISK_SPAM,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/calendar:manageownentries' => array(
'riskbitmask' => RISK_SPAM,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/calendar:manageentries' => array(
'riskbitmask' => RISK_SPAM,
'admin' => CAP_ALLOW
)
),
-
- // The next 3 might make no sense for some roles, e.g teacher, etc.
+
+ // The next 3 might make no sense for some roles, e.g teacher, etc.
// since the next level up is site. These are more for the parent role
'moodle/user:readuserposts' => array(
'captype' => 'read',
'admin' => CAP_ALLOW
)
),
-
+
'moodle/user:readuserblogs' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_USER,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/user:viewuseractivitiesreport' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_USER,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/user:editprofile' => array(
'riskbitmask' => RISK_SPAM,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/question:import' => array(
'riskbitmask' => RISK_XSS,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/question:export' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/question:managecategory' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/question:manage' => array(
'riskbitmask' => RISK_XSS,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:sectionvisibility' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:useremail' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:viewhiddensections' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:setcurrentsection' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:viewcoursegrades' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/course:managegrades' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
'admin' => CAP_ALLOW
)
),
-
+
'moodle/user:viewusergrades' => array(
'captype' => 'write',
'contextlevel' => CONTEXT_COURSE,
// This library includes all the required functions used to handle the DB
// structure (DDL) independently of the underlying RDBMS in use. All the functions
-// rely on the XMLDBDriver classes to be able to generate the correct SQL
+// rely on the XMLDBDriver classes to be able to generate the correct SQL
// syntax needed by each DB.
//
-// To define any structure to be created we'll use the schema defined
+// To define any structure to be created we'll use the schema defined
// by the XMLDB classes, for tables, fields, indexes, keys and other
// statements instead of direct handling of SQL sentences.
//
/// Add other libraries
require_once($CFG->libdir . '/xmlize.php');
-
+
/**
* Add a new field to a table, or modify an existing one (if oldfield is defined).
* SQL statements, specific for each RDBMS ($CFG->dbtype) and, finally, it
* will execute all those statements against the DB.
*
- * @uses $CFG, $db
+ * @uses $CFG, $db
* @param $file full path to the XML file to be used
* @return boolean (true on success, false on error)
*/
* This function will create the table passed as argument with all its
* fields/keys/indexes/sequences, everything based in the XMLDB object
*
- * @uses $CFG, $db
+ * @uses $CFG, $db
* @param XMLDBTable table object (full specs are required)
* @param boolean continue to specify if must continue on error (true) or stop (false)
* @param boolean feedback to specify to show status info (true) or not (false)
* and all the associated objects (keys, indexes, constaints, sequences, triggers)
* will be dropped too.
*
- * @uses $CFG, $db
+ * @uses $CFG, $db
* @param XMLDBTable table object (just the name is mandatory)
* @param boolean continue to specify if must continue on error (true) or stop (false)
* @param boolean feedback to specify to show status info (true) or not (false)
/**
* This function will add the field to the table passed as arguments
*
- * @uses $CFG, $db
+ * @uses $CFG, $db
* @param XMLDBTable table object (just the name is mandatory)
* @param XMLDBField field object (full specs are required)
* @param boolean continue to specify if must continue on error (true) or stop (false)
/**
* This function will drop the field from the table passed as arguments
*
- * @uses $CFG, $db
+ * @uses $CFG, $db
* @param XMLDBTable table object (just the name is mandatory)
* @param XMLDBField field object (just the name is mandatory)
* @param boolean continue to specify if must continue on error (true) or stop (false)
// //
///////////////////////////////////////////////////////////////////////////
-/// This library contains all the Data Manipulation Language (DML) functions
+/// This library contains all the Data Manipulation Language (DML) functions
/// used to interact with the DB. All the dunctions in this library must be
/// generic and work against the major number of RDBMS possible. This is the
/// list of currently supported and tested DBs: mysql, postresql, mssql, oracle
return true;
}
/**
-* on DBs that support it, commit the transaction
+* on DBs that support it, commit the transaction
*/
function rollback_sql() {
/// Completely general function - it just runs some SQL and reports success.
}
/**
-* on DBs that support it, commit the transaction
+* on DBs that support it, commit the transaction
*/
function commit_sql() {
/// Completely general function - it just runs some SQL and reports success.
*
* @uses $CFG
* @param string $sqlfile The path where a file with sql commands can be found on the server.
- * @param string $sqlstring If no path is supplied then a string with semicolon delimited sql
+ * @param string $sqlstring If no path is supplied then a string with semicolon delimited sql
* commands can be supplied in this argument.
* @return bool Returns true if databse was modified successfully.
*/
*/
function count_records_sql($sql) {
$rs = get_recordset_sql($sql);
-
+
if ($rs) {
return reset($rs->fields);
} else {
- return 0;
+ return 0;
}
}
* The SQL statement should normally only return one record. In debug mode
* you will get a warning if more record is returned (unless you
* set $expectmultiple to true). In non-debug mode, it just returns
- * the first record.
+ * the first record.
*
* @uses $CFG
* @uses $db
* @param string $sql The SQL string you wish to be executed, should normally only return one record.
- * @param bool $expectmultiple If the SQL cannot be written to conviniently return just one record,
+ * @param bool $expectmultiple If the SQL cannot be written to conviniently return just one record,
* set this to true to hide the debug message.
* @param bool $nolimit sometimes appending ' LIMIT 1' to the SQL causes an error. Set this to true
* to stop your SQL being modified. This argument should probably be deprecated.
/// Only a few uses of the 2nd and 3rd parameter have been found
/// I think that we should avoid to use them completely, one
/// record is one record, and everything else should return error.
-/// So the proposal is to change all the uses, (4-5 inside Moodle
+/// So the proposal is to change all the uses, (4-5 inside Moodle
/// Core), drop them from the definition and delete the next two
/// "if" sentences. (eloy, 2006-08-19)
$limitnum = 1;
} else if (debugging()) {
// Debugging mode - don't use a limit of 1, but do change the SQL, because sometimes that
- // causes errors, and in non-debug mode you don't see the error message and it is
+ // causes errors, and in non-debug mode you don't see the error message and it is
// impossible to know what's wrong.
$limitfrom = 0;
$limitnum = 100;
}
if (!$rs = get_recordset_sql($sql, $limitfrom, $limitnum)) {
- return false;
+ return false;
}
-
+
$recordcount = $rs->RecordCount();
if ($recordcount == 0) { // Found no records
- return false;
+ return false;
} else if ($recordcount == 1) { // Found one record
/// DIRTY HACK to retrieve all the ' ' (1 space) fields converted back
* Get a number of records as an ADODB RecordSet.
*
* Selects records from the table $table.
- *
+ *
* If specified, only records where the field $field has value $value are retured.
- *
+ *
* If specified, the results will be sorted as specified by $sort. This
* is added to the SQL as "ORDER BY $sort". Example values of $sort
* mightbe "time ASC" or "time DESC".
- *
+ *
* If $fields is specified, only those fields are returned.
*
- * This function is internal to datalib, and should NEVER should be called directly
+ * This function is internal to datalib, and should NEVER should be called directly
* from general Moodle scripts. Use get_record, get_records etc.
- *
+ *
* If you only want some of the records, specify $limitfrom and $limitnum.
* The query will skip the first $limitfrom records (according to the sort
* order) and then return the next $limitnum records. If either of $limitfrom
* or $limitnum is specified, both must be present.
- *
+ *
* The return value is an ADODB RecordSet object
* @link http://phplens.com/adodb/reference.functions.adorecordset.html
* if the query succeeds. If an error occurrs, false is returned.
} else {
$select = '';
}
-
+
return get_recordset_select($table, $select, $sort, $fields, $limitfrom, $limitnum);
}
*
* If given, $select is used as the SELECT parameter in the SQL query,
* otherwise all records from the table are returned.
- *
- * Other arguments and the return type as for @see function get_recordset.
+ *
+ * Other arguments and the return type as for @see function get_recordset.
*
* @uses $CFG
* @param string $table the table to query.
* Only records where $field takes one of the values $values are returned.
* $values should be a comma-separated list of values, for example "4,5,6,10"
* or "'foo','bar','baz'".
- *
- * Other arguments and the return type as for @see function get_recordset.
+ *
+ * Other arguments and the return type as for @see function get_recordset.
*
* @param string $table the table to query.
* @param string $field a field to check (optional).
/**
* Get a number of records as an ADODB RecordSet. $sql must be a complete SQL query.
- * This function is internal to datalib, and should NEVER should be called directly
+ * This function is internal to datalib, and should NEVER should be called directly
* from general Moodle scripts. Use get_record, get_records etc.
- *
- * The return type is as for @see function get_recordset.
+ *
+ * The return type is as for @see function get_recordset.
*
* @uses $CFG
* @uses $db
/**
* Utility function used by the following 4 methods.
- *
+ *
* @param object an ADODB RecordSet object.
* @return mixed mixed an array of objects, or false if an error occured or the RecordSet was empty.
*/
}
}
-/**
+/**
* This function is used to convert all the Oracle 1-space defaults to the empty string
* like a really DIRTY HACK to allow it to work better until all those NOT NULL DEFAULT ''
* fields will be out from Moodle.
*
* If the query succeeds and returns at least one record, the
* return value is an array of objects, one object for each
- * record found. The array key is the value from the first
+ * record found. The array key is the value from the first
* column of the result set. The object associated with that key
* has a member variable for each column of the results.
*
* Get a number of records as an array of objects.
*
* Return value as for @see function get_records.
- *
+ *
* @param string $sql the SQL select query to execute.
* @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
* @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
/**
* Utility function used by the following 3 methods.
- *
+ *
* @param object an ADODB RecordSet object with two columns.
* @return mixed an associative array, or false if an error occured or the RecordSet was empty.
*/
* Get the first two columns from a number of records as an associative array.
*
* Arguments as for @see function get_recordset.
- *
+ *
* If no errors occur, and at least one records is found, the return value
* is an associative whose keys come from the first field of each record,
* and whose values are the corresponding second fields. If no records are found,
}
/**
- * Get an array of data from one or more fields from a database
+ * Get an array of data from one or more fields from a database
* use to get a column, or a series of distinct values
*
* @uses $CFG
/// Postgres doesn't have the concept of primary key built in
/// and will return the OID which isn't what we want.
-/// The efficient and transaction-safe strategy is to
+/// The efficient and transaction-safe strategy is to
/// move the sequence forward first, and make the insert
/// with an explicit id.
if ( $CFG->dbtype === 'postgres7' && $returnid == true ) {
if ($nextval = (int)get_field_sql("SELECT NEXTVAL('{$CFG->prefix}{$table}_{$primarykey}_seq')")) {
- $dataobject->{$primarykey} = $nextval;
- }
+ $dataobject->{$primarykey} = $nextval;
+ }
}
-/// First basic support of insert for Oracle. As it doesn't
+/// First basic support of insert for Oracle. As it doesn't
/// support autogenerated fields, we rely on the corresponding
/// sequence. It will work automatically, unless we need to
/// return the primary from the function, in this case we
$generator->setPrefix($CFG->prefix);
$seqname = $generator->getNameForObject($table, $primarykey, 'seq');
if ($nextval = (int)get_field_sql("SELECT $seqname.NEXTVAL from dual")) {
- $dataobject->{$primarykey} = $nextval;
+ $dataobject->{$primarykey} = $nextval;
}
}
/// Also, for Oracle DB, empty strings are converted to NULLs in DB
/// What we are going to do is to examine all the data being inserted and if it's
/// an empty string (NULL for Oracle) and the field is defined as NOT NULL, we'll modify
/// such data in the best form possible ("0" for booleans and numbers and " " for the
-/// rest of strings. It isn't optimal, but the only way to do so.
+/// rest of strings. It isn't optimal, but the only way to do so.
/// In the oppsite, when retrieving records from Oracle, we'll decode " " back to
/// empty strings to allow everything to work properly. DIRTY HACK.
if ( $CFG->dbtype === 'oci8po') {
}
/// This only gets triggered with non-Postgres databases
-/// however we have some postgres fallback in case we failed
+/// however we have some postgres fallback in case we failed
/// to find the sequence.
- $id = $db->Insert_ID();
+ $id = $db->Insert_ID();
if ($CFG->dbtype === 'postgres7') {
// try to get the primary key based on id
&& ($rs->RecordCount() == 1) ) {
trigger_error("Retrieved $primarykey from oid on table $table because we could not find the sequence.");
return (integer)reset($rs->fields);
- }
+ }
trigger_error('Failed to retrieve primary key after insert: SELECT '. $primarykey .
' FROM '. $CFG->prefix . $table .' WHERE oid = '. $id);
return false;
/**
* Returns the proper SQL (for the dbms in use) to concatenate $firstname and $lastname
- *
+ *
* @uses $CFG
* @param string $firstname User's first name
* @param string $lastname User's last name
}
}
-/**
+/**
* Returns the proper AS keyword to be used to aliase columns
* SQL defines the keyword as optional and nobody but PG
* seems to require it. This function should be used inside all
/**
* Returns the SQL text to be used to order by one TEXT (clob) column, because
- * some RDBMS doesn't support direct ordering of such fields.
+ * some RDBMS doesn't support direct ordering of such fields.
* Note that the use or queries being ordered by TEXT columns must be minimised,
* because it's really slooooooow.
* @param string fieldname the name of the TEXT field we need to order by
}
}
-/**
+/**
* Prepare a SQL WHERE clause to select records where the given fields match the given values.
- *
+ *
* Prepares a where clause of the form
* WHERE field1 = value1 AND field2 = value2 AND field3 = value3
* except that you need only specify as many arguments (zero to three) as you need.
- *
+ *
* @param string $field1 the first field to check (optional).
* @param string $value1 the value field1 must have (requred if field1 is given, else optional).
* @param string $field2 the second field to check (optional).
// //
///////////////////////////////////////////////////////////////////////////
-/// This file contains all the constants and variables used
+/// This file contains all the constants and variables used
/// by the XMLDB interface
/// First, some constants to be used by actions
/// Now the allowed DB Field Types
define ('XMLDB_TYPE_INCORRECT', 0); //Wrong DB Type
- define ('XMLDB_TYPE_INTEGER', 1); //Integer
- define ('XMLDB_TYPE_NUMBER', 2); //Decimal number
- define ('XMLDB_TYPE_FLOAT', 3); //Floating Point number
+ define ('XMLDB_TYPE_INTEGER', 1); //Integer
+ define ('XMLDB_TYPE_NUMBER', 2); //Decimal number
+ define ('XMLDB_TYPE_FLOAT', 3); //Floating Point number
define ('XMLDB_TYPE_CHAR', 4); //String
define ('XMLDB_TYPE_TEXT', 5); //Text
define ('XMLDB_TYPE_BINARY', 6); //Binary
/// Now the allowed DB Keys
define ('XMLDB_KEY_INCORRECT', 0); //Wrong DB Key
- define ('XMLDB_KEY_PRIMARY', 1); //Primary Keys
+ define ('XMLDB_KEY_PRIMARY', 1); //Primary Keys
define ('XMLDB_KEY_UNIQUE', 2); //Unique Keys
- define ('XMLDB_KEY_FOREIGN', 3); //Foreign Keys
+ define ('XMLDB_KEY_FOREIGN', 3); //Foreign Keys
define ('XMLDB_KEY_CHECK', 4); //Check Constraints - NOT USED!
define ('XMLDB_KEY_FOREIGN_UNIQUE',5); //Foreign Key + Unique Key
/// This class represent one XMLDB Field
class XMLDBField extends XMLDBObject {
-
+
var $type;
var $length;
var $unsigned;
if (isset($xmlarr['@']['DECIMALS'])) {
$decimals = trim($xmlarr['@']['DECIMALS']);
/// Check for integer values
- if ($this->type == XMLDB_TYPE_NUMBER ||
+ if ($this->type == XMLDB_TYPE_NUMBER ||
$this->type == XMLDB_TYPE_FLOAT) {
if (!(is_numeric($decimals)&&(intval($decimals)==floatval($decimals)))) {
$this->errormsg = 'Incorrect DECIMALS attribute for number field';
function getXMLDBFieldType($type) {
$result = XMLDB_TYPE_INCORRECT;
-
+
switch (strtolower($type)) {
case 'int':
$result = XMLDB_TYPE_INTEGER;
function getXMLDBTypeName($type) {
$result = "";
-
+
switch (strtolower($type)) {
case XMLDB_TYPE_INTEGER:
$result = 'int';
}
}
- /**
+ /**
*This function will output the XML text for one field
*/
function xmlOutput() {
$this->type = XMLDB_TYPE_TEXT;
}
/// Calculate the length of the field
- if ($adofield->max_length > 0 &&
+ if ($adofield->max_length > 0 &&
($this->type == XMLDB_TYPE_INTEGER ||
$this->type == XMLDB_TYPE_NUMBER ||
$this->type == XMLDB_TYPE_FLOAT ||
}
/// Calculate the decimals of the field
if ($adofield->max_length > 0 &&
- $adofield->scale &&
+ $adofield->scale &&
($this->type == XMLDB_TYPE_NUMBER ||
$this->type == XMLDB_TYPE_FLOAT)) {
$this->decimals = $adofield->scale;
}
/// Calculate the unsigned field
- if ($adofield->unsigned &&
+ if ($adofield->unsigned &&
($this->type == XMLDB_TYPE_INTEGER ||
$this->type == XMLDB_TYPE_NUMBER ||
$this->type == XMLDB_TYPE_FLOAT)) {
/// Calculate the default field
if ($adofield->has_default) {
$this->default = $adofield->default_value;
- }
+ }
/// Calculate the sequence field
if ($adofield->auto_increment) {
$this->sequence = true;
return $structure;
}
- /**
+ /**
* This function saves the whole XMLDBStructure to its file
*/
function saveXMLFile() {
/// This class represent one XMLDB Index
class XMLDBIndex extends XMLDBObject {
-
+
var $unique;
var $fields;
$this->fields = $fields;
}
- /**
+ /**
* Get the index fields
*/
function &getFields() {
$this->errormsg = 'Undefined UNIQUE attribute';
$result = false;
}
-
+
if (isset($xmlarr['@']['FIELDS'])) {
$fields = strtolower(trim($xmlarr['@']['FIELDS']));
if ($fields) {
}
}
- /**
+ /**
*This function will output the XML text for one index
*/
function xmlOutput() {
return $result;
}
- /**
+ /**
* Shows info in a readable format
*/
function readableInfo() {
/// This class represent one XMLDB Key
class XMLDBKey extends XMLDBObject {
-
+
var $type;
var $fields;
var $reftable;
$this->reffields = $reffields;
}
- /**
+ /**
* Get the key fields
*/
function &getFields() {
/// print_object ($GLOBALS['traverse_array']); //Debug
/// $GLOBALS['traverse_array']=""; //Debug
- /// Process key attributes (name, type, fields, reftable,
+ /// Process key attributes (name, type, fields, reftable,
/// reffields, comment, previous, next)
if (isset($xmlarr['@']['NAME'])) {
$this->name = trim($xmlarr['@']['NAME']);
if (isset($xmlarr['@']['REFTABLE'])) {
/// Check we are in a FK
- if ($this->type == XMLDB_KEY_FOREIGN ||
- $this->type == XMLDB_KEY_FOREIGN_UNIQUE) {
+ if ($this->type == XMLDB_KEY_FOREIGN ||
+ $this->type == XMLDB_KEY_FOREIGN_UNIQUE) {
$reftable = strtolower(trim($xmlarr['@']['REFTABLE']));
if (!$reftable) {
$this->errormsg = 'Empty REFTABLE attribute';
function getXMLDBKeyType($type) {
$result = XMLDB_KEY_INCORRECT;
-
+
switch (strtolower($type)) {
case 'primary':
$result = XMLDB_KEY_PRIMARY;
function getXMLDBKeyName($type) {
$result = '';
-
+
switch (strtolower($type)) {
case XMLDB_KEY_PRIMARY:
$result = 'primary';
}
}
- /**
+ /**
*This function will output the XML text for one key
*/
function xmlOutput() {
case XMLDB_KEY_FOREIGN:
$result .= 'XMLDB_KEY_FOREIGN' . ', ';
break;
- }
+ }
/// The fields
$keyfields = $this->getFields();
if (!empty($keyfields)) {
$result .= 'array(' . "'". implode("', '", $keyfields) . "')";
} else {
$result .= 'null';
- }
+ }
/// The FKs attributes
if ($this->getType() == XMLDB_KEY_FOREIGN) {
/// The reftable
$result .= ", '" . $reftable . "', ";
} else {
$result .= 'null, ';
- }
+ }
/// The reffields
$reffields = $this->getRefFields();
if (!empty($reffields)) {
return $result;
}
- /**
+ /**
* Shows info in a readable format
- */
+ */
function readableInfo() {
$o = '';
/// type
/// are defined
class XMLDBObject {
-
+
var $name;
var $comment;
var $previous;
return $this->changed;
}
- /**
+ /**
* This function returns the comment of one XMLDBObject
*/
function getComment() {
return $this->comment;
}
- /**
+ /**
* This function returns the hash of one XMLDBObject
*/
function getHash() {
return $result;
}
- /**
+ /**
* This function will check that all the elements in one array
* have a consistent info in their previous/next fields
*/
function &findObjectInArray($objectname, $arr) {
foreach ($arr as $i => $object) {
if ($objectname == $object->getName()) {
- return $i;
- }
- }
+ return $i;
+ }
+ }
$null = NULL;
return $null;
}
}
/**
- * Returns one array of elements from one comma separated string,
+ * Returns one array of elements from one comma separated string,
* supporting quoted strings containing commas and concat function calls
*/
function comma2array($string) {
/// (only INSERT is allowed for now)
class XMLDBStatement extends XMLDBObject {
-
+
var $table; // Table we are handling
var $type; // XMLDB_STATEMENT_TYPE
var $sentences; // Collection of sentences in the statement
}
}
}
-
+
/// Finally, set the array of sentences
$this->sentences = $sentencesarr;
function getXMLDBStatementType($type) {
$result = XMLDB_STATEMENT_INCORRECT;
-
+
switch (strtolower($type)) {
case 'insert':
$result = XMLDB_STATEMENT_INSERT;
/// Return the normalized XMLDB_STATEMENT
return $result;
}
-
+
/**
* This function returns the correct name value for the
* XMLDB_STATEMENT_XXX passed as argument
function getXMLDBStatementName($type) {
$result = '';
-
+
switch (strtolower($type)) {
case XMLDB_STATEMENT_INSERT:
$result = 'insert';
}
}
- /**
+ /**
* This function will output the XML text for one statement
*/
function xmlOutput() {
$this->changed = true;
}
- /**
+ /**
* Shows info in a readable format
*/
function readableInfo() {
* This function will return an array of fields from one INSERT sentence
*/
function getFieldsFromInsertSentence($sentence) {
-
+
$fields = array();
/// Get first part from the sentence (before VALUES)
* This function will return an array of values from one INSERT sentence
*/
function getValuesFromInsertSentence($sentence) {
-
+
$values = array();
/// Get second part from the sentence (after VALUES)
/**
* This function will return the code needed to execute a collection
* of sentences present inside one statement for the specified BD
- * and prefix.
+ * and prefix.
* For now it only supports INSERT statements
*/
function getExecuteStatementSQL ($dbtype, $prefix, $statement_end=true) {
/// This class represent one XMLDB structure
class XMLDBStructure extends XMLDBObject {
-
+
var $path;
var $version;
var $tables;
*/
function &getTable($tablename) {
$i = $this->findTableInArray($tablename);
- if ($i !== NULL) {
+ if ($i !== NULL) {
return $this->tables[$i];
}
$null = NULL;
*/
function &getStatement($statementname) {
$i = $this->findStatementInArray($statementname);
- if ($i !== NULL) {
+ if ($i !== NULL) {
return $this->statements[$i];
}
$null = NULL;
return $this->statements;
}
- /**
+ /**
* Set the structure version
*/
function setVersion($version) {
}
}
- /**
+ /**
* Set the tables
*/
function setTables(&$tables) {
$this->tables = $tables;
}
- /**
+ /**
* Set the statements
*/
function setStatements(&$statements) {
}
}
}
-
+
/// Perform some general checks over statements
if ($result && $this->statements) {
/// Check statements names are ok (lowercase, a-z _-)
}
}
- /**
+ /**
* This function will output the XML text for one structure
*/
function xmlOutput() {
/**
* This function returns the number of uses of one table inside
- * a whole XMLDStructure. Useful to detect if the table must be
+ * a whole XMLDStructure. Useful to detect if the table must be
* locked. Return false if no uses are found.
*/
function getTableUses($tablename) {
/**
* This function returns the number of uses of one field inside
- * a whole XMLDBStructure. Useful to detect if the field must be
+ * a whole XMLDBStructure. Useful to detect if the field must be
* locked. Return false if no uses are found.
*/
function getFieldUses($tablename, $fieldname) {
in_array($fieldname, $key->getRefFields())) {
$uses[] = 'table ' . $table->getName() . ' key ' . $key->getName();
}
- }
+ }
}
/// Check if any index in the table is using it
$table = $this->getTable($tablename);
if (in_array($fieldname, $index->getFields())) {
$uses[] = 'table ' . $table->getName() . ' index ' . $index->getName();
}
- }
+ }
}
/// Check if some foreign key in the whole structure is using it
/// By comparing the reftable and refields with the field)
/**
* This function returns the number of uses of one key inside
- * a whole XMLDBStructure. Useful to detect if the key must be
+ * a whole XMLDBStructure. Useful to detect if the key must be
* locked. Return false if no uses are found.
*/
function getKeyUses($tablename, $keyname) {
/**
* This function returns the number of uses of one index inside
- * a whole XMLDBStructure. Useful to detect if the index must be
+ * a whole XMLDBStructure. Useful to detect if the index must be
* locked. Return false if no uses are found.
*/
function getIndexUses($tablename, $indexname) {
}
}
- /**
+ /**
* This function will return all the errors found in one structure
* looking recursively inside each table/statement. Returns
* an array of errors or false
if ($tables = $this->getTables()) {
foreach ($tables as $table) {
if ($tableerrors = $table->getAllErrors()) {
-
+
}
}
/// Add them to the errors array
}
}
- /**
+ /**
* This function will return the SQL code needed to create the table for the specified DB and
* prefix. Just one simple wrapper over generators.
*/
function getCreateStructureSQL ($dbtype, $prefix, $statement_end=true) {
$results = array();
-
+
if ($tables = $this->getTables()) {
foreach ($tables as $table) {
$results = array_merge($results, $table->getCreateTableSQL($dbtype, $prefix, $statement_end));
/// This class represent one XMLDB table
class XMLDBTable extends XMLDBObject {
-
+
var $fields;
var $keys;
var $indexes;
}
}
- /**
+ /**
* This function will output the XML text for one table
*/
function xmlOutput() {
$key->setAttributes($type, $fields, $reftable, $reffields);
$this->addKey($key);
}
-
+
/**
* This function will add one new index to the table with all
* its attributes defined
$index->setAttributes($type, $fields);
$this->addIndex($index);
}
-
- /**
+
+ /**
* This function will return all the errors found in one table
* looking recursively inside each field/key/index. Returns
* an array of errors or false
}
}
- /**
+ /**
* This function will return the SQL code needed to create the table for the specified DB and
* prefix. Just one simple wrapper over generators.
*/
return $results;
}
- /**
+ /**
* This function will return the SQL code needed to create the table for the specified DB and
* prefix. Just one simple wrapper over generators.
*/
return $results;
}
- /**
+ /**
* This function will return the SQL code needed to drop the table for the specified DB and
* prefix. Just one simple wrapper over generators.
*/
return $results;
}
- /**
+ /**
* This function will return the SQL code needed to add one field to the table for the specified DB and
* prefix. Just one simple wrapper over generators.
*/
return $results;
}
- /**
+ /**
* This function will return the SQL code needed to drop one field from the table for the specified DB and
* prefix. Just one simple wrapper over generators.
*/
return $results;
}
- /**
+ /**
* This function will return the SQL code needed to rename one field from the table for the specified DB and
* prefix. Just one simple wrapper over generators.
*/
///////////////////////////////////////////////////////////////////////////
/// This class represent the base generator class where all the
-/// needed functions to generate proper SQL are defined.
+/// needed functions to generate proper SQL are defined.
/// The rest of classes will inherit, by default, the same logic.
/// Functions will be overriden as needed to generate correct SQL.
class XMLDBgenerator {
-/// Please, avoid editing this defaults in this base class!
+/// Please, avoid editing this defaults in this base class!
/// It could change the behaviour of the rest of generators
/// that, by default, inherit this configuration.
/// To change any of them, do it in extended classes instead.
} else {
/// We force default '' for not null char columns without proper default
/// some day this should be out!
- if ($this->default_for_char !== NULL &&
+ if ($this->default_for_char !== NULL &&
$xmldb_field->getType() == XMLDB_TYPE_CHAR &&
$xmldb_field->getNotNull()) {
$default .= ' default ' . "'" . $this->default_for_char . "'";
/**
* Given one correct XMLDBTable and the new name, returns the SQL statements
* to rename it (inside one array)
- */
+ */
function getRenameTableSQL($xmldb_table, $newname) {
$results = array(); //Array where all the sentences will be stored
/**
* Given one correct XMLDBTable and the new name, returns the SQL statements
* to drop it (inside one array)
- */
+ */
function getDropTableSQL($xmldb_table) {
$results = array(); //Array where all the sentences will be stored
foreach($values as $key => $value) {
/// Trim single quotes
$value = trim($value,"'");
- if (stristr($value, 'CONCAT') !== false){
+ if (stristr($value, 'CONCAT') !== false){
/// Look for data between parentesis
preg_match("/CONCAT\s*\((.*)\)$/is", trim($value), $matches);
if (isset($matches[1])) {
}
}
- /**
+ /**
* Given one string (or one array), ends it with statement_end
*/
function getEndedStatements ($input) {
foreach ($input as $key=>$content) {
$input[$key] = $this->getEndedStatements($content);
}
- return $input;
+ return $input;
} else {
$input = trim($input) . $this->statement_end;
return $input;
}
/**
- * Returns the code (array of statements) needed
+ * Returns the code (array of statements) needed
* to create one sequence for the xmldb_table and xmldb_field passes
*/
function getCreateSequenceSQL ($xmldb_table, $xmldb_field) {
/// Some well-know reserved words
$reserved_words = array (
'user', 'scale', 'type', 'comment', 'view', 'value', 'table', 'index', 'key', 'sequence', 'trigger'
- );
+ );
return $reserved_words;
}
/// Some well-known tables to be created without prefix
$tables = array (
'adodb_logsql'
- );
+ );
return $tables;
}
}
return $dbtype;
}
- /**
+ /**
* Returns the code needed to create one enum for the xmldb_table and xmldb_field passes
- */
+ */
function getEnumExtraSQL ($xmldb_table, $xmldb_field) {
-
+
$sql = 'CONSTRAINT ' . $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'ck');
$sql.= ' CHECK (' . $this->getEncQuoted($xmldb_field->getName()) . ' IN (' . implode(', ', $xmldb_field->getEnumValues()) . '))';
/// This file contains the reserved words for MSSQL databases
/// from http://msdn2.microsoft.com/en-us/library/ms189822.aspx
$reserved_words = array (
- 'add', 'all', 'alter', 'and', 'any', 'as', 'asc', 'authorization',
- 'avg', 'backup', 'begin', 'between', 'break', 'browse', 'bulk',
- 'by', 'cascade', 'case', 'check', 'checkpoint', 'close', 'clustered',
- 'coalesce', 'collate', 'column', 'commit', 'committed', 'compute',
- 'confirm', 'constraint', 'contains', 'containstable', 'continue',
- 'controlrow', 'convert', 'count', 'create', 'cross', 'current',
- 'current_date', 'current_time', 'current_timestamp', 'current_user',
- 'cursor', 'database', 'dbcc', 'deallocate', 'declare', 'default', 'delete',
- 'deny', 'desc', 'disk', 'distinct', 'distributed', 'double', 'drop', 'dummy',
- 'dump', 'else', 'end', 'errlvl', 'errorexit', 'escape', 'except', 'exec',
- 'execute', 'exists', 'exit', 'fetch', 'file', 'fillfactor', 'floppy',
- 'for', 'foreign', 'freetext', 'freetexttable', 'from', 'full', 'function',
- 'goto', 'grant', 'group', 'having', 'holdlock', 'identity', 'identitycol',
- 'identity_insert', 'if', 'in', 'index', 'inner', 'insert', 'intersect', 'into',
- 'is', 'isolation', 'join', 'key', 'kill', 'left', 'level', 'like', 'lineno',
- 'load', 'max', 'min', 'mirrorexit', 'national', 'nocheck', 'nonclustered',
- 'not', 'null', 'nullif', 'of', 'off', 'offsets', 'on', 'once', 'only', 'open',
- 'opendatasource', 'openquery', 'openrowset', 'openxml', 'option', 'or', 'order',
- 'outer', 'over', 'percent', 'perm', 'permanent', 'pipe', 'plan', 'precision',
- 'prepare', 'primary', 'print', 'privileges', 'proc', 'procedure', 'processexit',
- 'public', 'raiserror', 'read', 'readtext', 'reconfigure', 'references',
- 'repeatable', 'replication', 'restore', 'restrict', 'return', 'revoke',
- 'right', 'rollback', 'rowcount', 'rowguidcol', 'rule', 'save', 'schema',
- 'select', 'serializable', 'session_user', 'set', 'setuser', 'shutdown', 'some',
- 'statistics', 'sum', 'system_user', 'table', 'tape', 'temp', 'temporary',
- 'textsize', 'then', 'to', 'top', 'tran', 'transaction', 'trigger', 'truncate',
- 'tsequal', 'uncommitted', 'union', 'unique', 'update', 'updatetext', 'use',
- 'user', 'values', 'varying', 'view', 'waitfor', 'when', 'where', 'while',
+ 'add', 'all', 'alter', 'and', 'any', 'as', 'asc', 'authorization',
+ 'avg', 'backup', 'begin', 'between', 'break', 'browse', 'bulk',
+ 'by', 'cascade', 'case', 'check', 'checkpoint', 'close', 'clustered',
+ 'coalesce', 'collate', 'column', 'commit', 'committed', 'compute',
+ 'confirm', 'constraint', 'contains', 'containstable', 'continue',
+ 'controlrow', 'convert', 'count', 'create', 'cross', 'current',
+ 'current_date', 'current_time', 'current_timestamp', 'current_user',
+ 'cursor', 'database', 'dbcc', 'deallocate', 'declare', 'default', 'delete',
+ 'deny', 'desc', 'disk', 'distinct', 'distributed', 'double', 'drop', 'dummy',
+ 'dump', 'else', 'end', 'errlvl', 'errorexit', 'escape', 'except', 'exec',
+ 'execute', 'exists', 'exit', 'fetch', 'file', 'fillfactor', 'floppy',
+ 'for', 'foreign', 'freetext', 'freetexttable', 'from', 'full', 'function',
+ 'goto', 'grant', 'group', 'having', 'holdlock', 'identity', 'identitycol',
+ 'identity_insert', 'if', 'in', 'index', 'inner', 'insert', 'intersect', 'into',
+ 'is', 'isolation', 'join', 'key', 'kill', 'left', 'level', 'like', 'lineno',
+ 'load', 'max', 'min', 'mirrorexit', 'national', 'nocheck', 'nonclustered',
+ 'not', 'null', 'nullif', 'of', 'off', 'offsets', 'on', 'once', 'only', 'open',
+ 'opendatasource', 'openquery', 'openrowset', 'openxml', 'option', 'or', 'order',
+ 'outer', 'over', 'percent', 'perm', 'permanent', 'pipe', 'plan', 'precision',
+ 'prepare', 'primary', 'print', 'privileges', 'proc', 'procedure', 'processexit',
+ 'public', 'raiserror', 'read', 'readtext', 'reconfigure', 'references',
+ 'repeatable', 'replication', 'restore', 'restrict', 'return', 'revoke',
+ 'right', 'rollback', 'rowcount', 'rowguidcol', 'rule', 'save', 'schema',
+ 'select', 'serializable', 'session_user', 'set', 'setuser', 'shutdown', 'some',
+ 'statistics', 'sum', 'system_user', 'table', 'tape', 'temp', 'temporary',
+ 'textsize', 'then', 'to', 'top', 'tran', 'transaction', 'trigger', 'truncate',
+ 'tsequal', 'uncommitted', 'union', 'unique', 'update', 'updatetext', 'use',
+ 'user', 'values', 'varying', 'view', 'waitfor', 'when', 'where', 'while',
'with', 'work', 'writetext'
- );
+ );
return $reserved_words;
}
}
function getCommentSQL ($xmldb_table) {
$comment = '';
-
+
if ($xmldb_table->getComment()) {
$comment .= 'ALTER TABLE ' . $this->getEncQuoted($this->prefix . $xmldb_table->getName());
$comment .= " COMMENT='" . substr($xmldb_table->getComment(), 0, 250) . "'";
'utc_timestamp', 'values', 'varbinary', 'varchar', 'varcharacter',
'varying', 'when', 'where', 'while', 'with', 'write', 'x509',
'xor', 'year_month', 'zerofill'
- );
+ );
return $reserved_words;
}
}
return $dbtype;
}
- /**
+ /**
* Returns the code needed to create one enum for the xmldb_table and xmldb_field passes
- */
+ */
function getEnumExtraSQL ($xmldb_table, $xmldb_field) {
-
+
$sql = 'CONSTRAINT ' . $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'ck');
$sql.= ' CHECK (' . $this->getEncQuoted($xmldb_field->getName()) . ' IN (' . implode(', ', $xmldb_field->getEnumValues()) . '))';
function getCreateSequenceSQL ($xmldb_table, $xmldb_field) {
$sequence_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'seq');
-
+
$sequence = "CREATE SEQUENCE " . $sequence_name;
$sequence.= "\n START WITH 1";
$sequence.= "\n INCREMENT BY 1";
$sequence.= "\n NOMAXVALUE";
$trigger_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'trg');
-
+
$trigger = "CREATE OR REPLACE TRIGGER " . $trigger_name;
$trigger.= "\n BEFORE INSERT";
$trigger.= "\nON " . $this->getEncQuoted($this->prefix . $xmldb_table->getName());
function getDropSequenceSQL ($xmldb_table, $xmldb_field, $include_trigger=false) {
$sequence_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'seq');
-
+
$sequence = "DROP SEQUENCE " . $sequence_name;
$trigger_name = $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'trg');
-
+
$trigger = "DROP TRIGGER " . $trigger_name;
if ($include_trigger) {
'unique', 'update', 'user', 'validate', 'values',
'varchar', 'varchar2', 'view', 'whenever',
'where', 'with'
- );
+ );
return $reserved_words;
}
}
return $dbtype;
}
- /**
+ /**
* Returns the code needed to create one enum for the xmldb_table and xmldb_field passes
- */
+ */
function getEnumExtraSQL ($xmldb_table, $xmldb_field) {
-
+
$sql = 'CONSTRAINT ' . $this->getNameForObject($xmldb_table->getName(), $xmldb_field->getName(), 'ck');
$sql.= ' CHECK (' . $this->getEncQuoted($xmldb_field->getName()) . ' IN (' . implode(', ', $xmldb_field->getEnumValues()) . '))';
/// This file contains the reserved words for PostgreSQL databases
/// http://www.postgresql.org/docs/current/static/sql-keywords-appendix.html
$reserved_words = array (
- 'all', 'analyse', 'analyze', 'and', 'any', 'array', 'as', 'asc',
- 'asymmetric', 'authorization', 'between', 'binary', 'both', 'case',
- 'cast', 'check', 'collate', 'column', 'constraint', 'create', 'cross',
- 'current_date', 'current_role', 'current_time', 'current_timestamp',
- 'current_user', 'default', 'deferrable', 'desc', 'distinct', 'do',
- 'else', 'end', 'except', 'false', 'for', 'foreign', 'freeze', 'from',
- 'full', 'grant', 'group', 'having', 'ilike', 'in', 'initially', 'inner',
- 'intersect', 'into', 'is', 'isnull', 'join', 'leading', 'left', 'like',
- 'limit', 'localtime', 'localtimestamp', 'natural', 'new', 'not',
- 'notnull', 'null', 'off', 'offset', 'old', 'on', 'only', 'or', 'order',
- 'outer', 'overlaps', 'placing', 'primary', 'references', 'right', 'select',
- 'session_user', 'similar', 'some', 'symmetric', 'table', 'then', 'to',
- 'trailing', 'true', 'union', 'unique', 'user', 'using', 'verbose',
+ 'all', 'analyse', 'analyze', 'and', 'any', 'array', 'as', 'asc',
+ 'asymmetric', 'authorization', 'between', 'binary', 'both', 'case',
+ 'cast', 'check', 'collate', 'column', 'constraint', 'create', 'cross',
+ 'current_date', 'current_role', 'current_time', 'current_timestamp',
+ 'current_user', 'default', 'deferrable', 'desc', 'distinct', 'do',
+ 'else', 'end', 'except', 'false', 'for', 'foreign', 'freeze', 'from',
+ 'full', 'grant', 'group', 'having', 'ilike', 'in', 'initially', 'inner',
+ 'intersect', 'into', 'is', 'isnull', 'join', 'leading', 'left', 'like',
+ 'limit', 'localtime', 'localtimestamp', 'natural', 'new', 'not',
+ 'notnull', 'null', 'off', 'offset', 'old', 'on', 'only', 'or', 'order',
+ 'outer', 'overlaps', 'placing', 'primary', 'references', 'right', 'select',
+ 'session_user', 'similar', 'some', 'symmetric', 'table', 'then', 'to',
+ 'trailing', 'true', 'union', 'unique', 'user', 'using', 'verbose',
'when', 'where'
- );
+ );
return $reserved_words;
}
}
<xs:pattern value='[0-9a-z_]{1,30}'/>
</xs:restriction >
</xs:simpleType >
-
+
<xs:simpleType name="fieldType">
<xs:restriction base="xs:NMTOKEN">
<xs:enumeration value="int" />
<xs:pattern value='[0-9a-z_, ]+'/>
</xs:restriction >
</xs:simpleType >
-
+
<xs:simpleType name="keyType">
<xs:restriction base="xs:NMTOKEN">
<xs:enumeration value="primary" />
$mod_assignment_capabilities = array(
-
+
'mod/assignment:view' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/assignment:submit' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/assignment:grade' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
$mod_chat_capabilities = array(
-
+
'mod/chat:chat' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'mod/chat:readlog' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/chat:deletelog' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
)
-
+
);
?>
$mod_choice_capabilities = array(
-
+
'mod/choice:choose' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/choice:readresponses' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/choice:deleteresponses' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/choice:downloadresponses' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
$mod_data_capabilities = array(
-
+
'mod/data:viewentry' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/data:writeentry' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'mod/data:comment' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'mod/data:viewrating' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/data:rate' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/data:approve' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/data:manageentries' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/data:managecomments' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/data:managetemplates' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
'admin' => CAP_ALLOW
)
)
-
+
);
?>
\ No newline at end of file
$mod_exercise_capabilities = array(
-
+
'mod/exercise:assess' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
)
-
+
);
?>
\ No newline at end of file
$mod_forum_capabilities = array(
-
+
'mod/forum:viewforum' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:viewdiscussion' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:viewhiddentimedposts' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:startdiscussion' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:replypost' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:viewrating' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:viewanyrating' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:rate' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:createattachment' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:deleteownpost' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:deleteanypost' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:splitdiscussions' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:movediscussions' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:editanypost' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:viewqandawithoutposting' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:viewsubscribers' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:managesubscriptions' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/forum:throttlingapplies' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
$mod_glossary_capabilities = array(
-
+
'mod/glossary:view' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/glossary:write' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'mod/glossary:manageentries' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/glossary:managecategories' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/glossary:comment' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'mod/glossary:managecomments' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/glossary:import' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
'admin' => CAP_ALLOW
)
),
-
+
'mod/glossary:export' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/glossary:approve' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/glossary:rate' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/glossary:viewrating' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
);
?>
$mod_hotpot_capabilities = array(
-
+
'mod/hotpot:attempt' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/hotpot:viewreport' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/hotpot:grade' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/hotpot:deleteattempt' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
)
-
+
);
?>
\ No newline at end of file
<?php // $Id$
/**
* Capability definitions for the lams module.
- *
+ *
* For naming conventions, see lib/db/access.php.
*/
$mod_lams_capabilities = array(
<?php // $Id$
/**
* Capability definitions for the lesson module.
- *
+ *
* For naming conventions, see lib/db/access.php.
*/
$mod_lesson_capabilities = array(
'mod/lesson:view' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
),
'mod/lesson:edit' => array(
-
+
'riskbitmask' => RISK_XSS,
'captype' => 'write',
),
'mod/lesson:manage' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
<?php // $Id$
/**
* Capability definitions for the quiz module.
- *
+ *
* For naming conventions, see lib/db/access.php.
*/
$mod_quiz_capabilities = array(
// Ability to see that the quiz exists, and the basic information
// about it, for example the start date and time limit.
'mod/quiz:view' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
// Ability to do the quiz as a 'student'.
'mod/quiz:attempt' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
// Edit the quiz settings, add and remove questions.
'mod/quiz:manage' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
// Preview the quiz.
'mod/quiz:preview' => array(
-
+
'captype' => 'write', // Only just a write.
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
// Manually grade and comment on student attempts at a question.
'mod/quiz:grade' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
// View the quiz reports.
'mod/quiz:viewreports' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
// Delete attempts using the overview report.
'mod/quiz:deleteattempts' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
$mod_resource_capabilities = array(
-
+
'mod/resource:view' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
)
-
+
);
?>
$mod_scorm_capabilities = array(
-
+
'mod/scorm:view' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/scorm:viewreport' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/scorm:savetrack' => array(
-
+
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_PREVENT
)
),
-
+
'mod/scorm:viewscores' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_PREVENT
)
)
-
+
);
?>
$mod_survey_capabilities = array(
-
+
'mod/survey:participate' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/survey:readresponses' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
),
-
+
'mod/survey:download' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'admin' => CAP_ALLOW
)
)
-
+
);
?>
\ No newline at end of file
<?php // $Id$
/**
* Capability definitions for the wiki module.
- *
+ *
* For naming conventions, see lib/db/access.php.
*/
$mod_wiki_capabilities = array(
<?php // $Id$
/**
* Capability definitions for the workshop module.
- *
+ *
* For naming conventions, see lib/db/access.php.
*/
$mod_workshop_capabilities = array(
'mod/workshop:view' => array(
-
+
'captype' => 'read',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
),
'mod/workshop:participate' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
),
'mod/workshop:manage' => array(
-
+
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
deleted documents are in fact not removed from the index, but instead just
marked as deleted and not returned in search results. The actual document
still features in the index, and skews sizes. When the index optimiser is
-completed in ZFS, then these deleted documents will be pruned, thus
+completed in ZFS, then these deleted documents will be pruned, thus
correctly modifying the index size.
Additional commenting added.
require_once('../config.php');
require_once("$CFG->dirroot/search/lib.php");
-
+
require_login();
if (!isadmin()) {
error("You need to be an admin user to use this page.", "$CFG->wwwroot/login/index.php");
} //if
-
+
//check for php5 (lib.php)
if (!search_check_php5()) {
$phpversion = phpversion();
mtrace("Sorry, global search requires PHP 5.0.0 or later (currently using version $phpversion)");
exit(0);
- } //if
-
- require_once("$CFG->dirroot/search/indexlib.php");
-
+ } //if
+
+ require_once("$CFG->dirroot/search/indexlib.php");
+
$index = new Zend_Search_Lucene(SEARCH_INDEX_PATH);
$dbcontrol = new IndexDBControl();
$addition_count = 0;
-
+
$indexdate = $CFG->search_indexer_run_date;
-
+
mtrace('<pre>Starting index update (additions)...');
mtrace('Index size before: '.$CFG->search_index_size."\n");
-
+
//get all modules
if ($mods = get_records_select('modules')) {
//append virtual modules onto array
$mods = array_merge($mods, search_get_additional_modules());
-
+
foreach ($mods as $mod) {
//build include file and function names
- $class_file = $CFG->dirroot.'/search/documents/'.$mod->name.'_document.php';
+ $class_file = $CFG->dirroot.'/search/documents/'.$mod->name.'_document.php';
$db_names_function = $mod->name.'_db_names';
$get_document_function = $mod->name.'_single_document';
- $additions = array();
-
+ $additions = array();
+
if (file_exists($class_file)) {
require_once($class_file);
-
+
//if both required functions exist
if (function_exists($db_names_function) and function_exists($get_document_function)) {
mtrace("Checking $mod->name module for additions.");
$values = $db_names_function();
- $where = (isset($values[4])) ? $values[4] : '';
-
+ $where = (isset($values[4])) ? $values[4] : '';
+
//select records in MODULE table, but not in SEARCH_DATABASE_TABLE
$sql = "select id, ".$values[0]." as docid from ".$values[1].
" where id not in".
" (select docid from ".SEARCH_DATABASE_TABLE." where doctype like '$mod->name')".
" and ".$values[2]." > $indexdate".
- " $where";
+ " $where";
+
+ $records = get_records_sql($sql);
- $records = get_records_sql($sql);
-
//foreach record, build a module specific search document using the get_document function
- if (is_array($records)) {
+ if (is_array($records)) {
foreach($records as $record) {
$additions[] = $get_document_function($record->id);
} //foreach
- } //if
-
+ } //if
+
//foreach document, add it to the index and database table
foreach ($additions as $add) {
++$addition_count;
-
+
//object to insert into db
- $dbid = $dbcontrol->addDocument($add);
-
+ $dbid = $dbcontrol->addDocument($add);
+
//synchronise db with index
- $add->addField(Zend_Search_Lucene_Field::Keyword('dbid', $dbid));
-
+ $add->addField(Zend_Search_Lucene_Field::Keyword('dbid', $dbid));
+
mtrace(" Add: $add->title (database id = $add->dbid, moodle instance id = $add->docid)");
-
+
$index->addDocument($add);
} //foreach
-
+
mtrace("Finished $mod->name.\n");
- } //if
+ } //if
} //if
} //foreach
} //if
-
+
//commit changes
$index->commit();
-
+
//update index date and size
set_config("search_indexer_run_date", time());
set_config("search_index_size", (int)$CFG->search_index_size + (int)$addition_count);
<?php
/* cron script to perform all the periodic search tasks
- *
+ *
* delete.php
* updates the index by pruning deleted documents
- *
+ *
* update.php
* updates document info in the index if the document has been modified since indexing
- *
+ *
* add.php
* adds documents created since the last index run
*/
require_once('../config.php');
require_once("$CFG->dirroot/search/lib.php");
-
+
mtrace("<pre>Starting cron...\n");
-
+
mtrace("--DELETE----");
require_once("$CFG->dirroot/search/delete.php");
mtrace("--UPDATE----");
CREATE TABLE prefix_search_documents (
id SERIAL8 PRIMARY KEY,
docid int4 NOT NULL,
- doctype varchar(12) NOT NULL DEFAULT 'none',
- title varchar(100) NOT NULL default '',
- url varchar(100) NOT NULL default '',
+ doctype varchar(12) NOT NULL DEFAULT 'none',
+ title varchar(100) NOT NULL default '',
+ url varchar(100) NOT NULL default '',
docdate timestamp NOT NULL,
- updated timestamp NOT NULL DEFAULT NOW(),
- courseid int4,
+ updated timestamp NOT NULL DEFAULT NOW(),
+ courseid int4,
groupid int4
);
require_once('../config.php');
require_once("$CFG->dirroot/search/lib.php");
-
+
require_login();
if (!isadmin()) {
error("You need to be an admin user to use this page.", "$CFG->wwwroot/login/index.php");
} //if
-
+
//check for php5 (lib.php)
if (!search_check_php5()) {
$phpversion = phpversion();
mtrace("Sorry, global search requires PHP 5.0.0 or later (currently using version $phpversion)");
exit(0);
- } //if
-
- require_once("$CFG->dirroot/search/indexlib.php");
-
+ } //if
+
+ require_once("$CFG->dirroot/search/indexlib.php");
+
$index = new Zend_Search_Lucene(SEARCH_INDEX_PATH);
$dbcontrol = new IndexDBControl();
- $deletion_count = 0;
-
+ $deletion_count = 0;
+
mtrace('<pre>Starting clean-up of removed records...');
mtrace('Index size before: '.$CFG->search_index_size."\n");
-
+
if ($mods = get_records_select('modules')) {
$mods = array_merge($mods, search_get_additional_modules());
-
+
foreach ($mods as $mod) {
//build function names
$class_file = $CFG->dirroot.'/search/documents/'.$mod->name.'_document.php';
$delete_function = $mod->name.'_delete';
$db_names_function = $mod->name.'_db_names';
- $deletions = array();
-
+ $deletions = array();
+
if (file_exists($class_file)) {
require_once($class_file);
-
+
if (function_exists($delete_function) and function_exists($db_names_function)) {
mtrace("Checking $mod->name module for deletions.");
$values = $db_names_function();
-
+
$sql = "select id, docid from ".SEARCH_DATABASE_TABLE.
" where doctype like '$mod->name'".
" and docid not in".
" (select ".$values[0]." from ".$values[1].")";
- $records = get_records_sql($sql);
-
+ $records = get_records_sql($sql);
+
//build an array of all the deleted records
- if (is_array($records)) {
+ if (is_array($records)) {
foreach($records as $record) {
$deletions[] = $delete_function($record->docid);
} //foreach
- } //if
-
- foreach ($deletions as $delete) {
+ } //if
+
+ foreach ($deletions as $delete) {
//find the specific document in the index, using it's docid and doctype as keys
- $doc = $index->find("+docid:$delete +doctype:$mod->name");
-
+ $doc = $index->find("+docid:$delete +doctype:$mod->name");
+
//get the record, should only be one
foreach ($doc as $thisdoc) {
++$deletion_count;
mtrace(" Delete: $thisdoc->title (database id = $thisdoc->dbid, index id = $thisdoc->id, moodle instance id = $thisdoc->docid)");
-
+
//remove it from index and database table
$dbcontrol->delDocument($thisdoc);
- $index->delete($thisdoc->id);
+ $index->delete($thisdoc->id);
} //foreach
} //foreach
-
+
mtrace("Finished $mod->name.\n");
- } //if
+ } //if
} //if
} //foreach
} //if
-
+
//commit changes
$index->commit();
-
+
//update index date and index size
set_config("search_indexer_run_date", time());
set_config("search_index_size", (int)$CFG->search_index_size - (int)$deletion_count);
/* Base search document from which other module/block types can
* extend.
* */
-
- abstract class SearchDocument extends Zend_Search_Lucene_Document {
- public function __construct(&$doc, &$data, $document_type, $course_id, $group_id) {
+
+ abstract class SearchDocument extends Zend_Search_Lucene_Document {
+ public function __construct(&$doc, &$data, $document_type, $course_id, $group_id) {
$this->addField(Zend_Search_Lucene_Field::Keyword('docid', $doc->docid));
$this->addField(Zend_Search_Lucene_Field::Text('title', $doc->title));
$this->addField(Zend_Search_Lucene_Field::Text('author', $doc->author));
$this->addField(Zend_Search_Lucene_Field::UnStored('contents', $doc->contents));
$this->addField(Zend_Search_Lucene_Field::UnIndexed('url', $doc->url));
$this->addField(Zend_Search_Lucene_Field::UnIndexed('date', $doc->date));
-
+
//additional data added on a per-module basis
$this->addField(Zend_Search_Lucene_Field::Binary('data', serialize($data)));
-
+
$this->addField(Zend_Search_Lucene_Field::Keyword('doctype', $document_type));
- $this->addField(Zend_Search_Lucene_Field::Keyword('course_id', $course_id));
- $this->addField(Zend_Search_Lucene_Field::Keyword('group_id', $group_id));
- } //constructor
+ $this->addField(Zend_Search_Lucene_Field::Keyword('course_id', $course_id));
+ $this->addField(Zend_Search_Lucene_Field::Keyword('group_id', $group_id));
+ } //constructor
} //SearchDocument
-
+
?>
\ No newline at end of file
require_once("$CFG->dirroot/search/documents/document.php");
require_once("$CFG->dirroot/mod/forum/lib.php");
-
- class ForumSearchDocument extends SearchDocument {
+
+ class ForumSearchDocument extends SearchDocument {
public function __construct(&$post, $forum_id, $course_id, $group_id) {
- // generic information
+ // generic information
$doc->docid = $post['id'];
$doc->title = $post['subject'];
$doc->author = $post['firstname']." ".$post['lastname'];
$doc->contents = $post['message'];
$doc->date = $post['created'];
-
- $doc->url = forum_make_link($post['discussion'], $post['id']);
-
+
+ $doc->url = forum_make_link($post['discussion'], $post['id']);
+
// module specific information
$data->forum = $forum_id;
$data->discussion = $post['discussion'];
-
+
parent::__construct($doc, $data, SEARCH_TYPE_FORUM, $course_id, $group_id);
- } //constructor
+ } //constructor
} //ForumSearchDocument
-
+
function forum_make_link($discussion_id, $post_id) {
global $CFG;
return $CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion_id.'#'.$post_id;
} //forum_make_link
-
+
function forum_iterator() {
- //no @ = Undefined index: 82 in moodle/lib/datalib.php on line 2671
+ //no @ = Undefined index: 82 in moodle/lib/datalib.php on line 2671
return @get_all_instances_in_courses("forum", get_courses());
} //forum_iterator
-
+
function forum_get_content_for_index(&$forum) {
- $documents = array();
+ $documents = array();
if (!$forum) return $documents;
-
- $posts = forum_get_discussions_fast($forum->id);
+
+ $posts = forum_get_discussions_fast($forum->id);
if (!$posts) return $documents;
-
+
while (!$posts->EOF) {
$post = $posts->fields;
-
+
if (is_array($post)) {
if (strlen($post['message']) > 0 && ($post['deleted'] != 1)) {
$documents[] = new ForumSearchDocument($post, $forum->id, $forum->course, $post['groupid']);
} //if
-
+
if ($children = forum_get_child_posts_fast($post['id'], $forum->id)) {
while (!$children->EOF) {
$child = $children->fields;
} //foreach
} //if
} //if
-
+
$posts->MoveNext();
} //foreach
-
+
return $documents;
} //forum_get_content_for_index
-
+
//returns a single forum search document based on a forum_entry id
function forum_single_document($id) {
$posts = get_recordset('forum_posts', 'id', $id);
$post = $posts->fields;
-
+
$discussions = get_recordset('forum_discussions', 'id', $post['discussion']);
$discussion = $discussions->fields;
-
+
$forums = get_recordset('forum', 'id', $discussion['forum']);
$forum = $forums->fields;
-
+
return new ForumSearchDocument($post, $forum['id'], $forum['course'], $post['groupid']);
- } //forum_single_document
-
+ } //forum_single_document
+
function forum_delete($info) {
- return $info;
+ return $info;
} //forum_delete
-
+
//returns the var names needed to build a sql query for addition/deletions
function forum_db_names() {
//[primary id], [table name], [time created field name], [time modified field name]
- return array('id', 'forum_posts', 'created', 'modified');
- } //forum_db_names
-
+ return array('id', 'forum_posts', 'created', 'modified');
+ } //forum_db_names
+
//reworked faster version from /mod/forum/lib.php
function forum_get_discussions_fast($forum) {
global $CFG, $USER;
-
+
$timelimit='';
-
+
if (!empty($CFG->forum_enabletimedposts)) {
if (!((isadmin() and !empty($CFG->admineditalways)) || isteacher(get_field('forum', 'course', 'id', $forum)))) {
$now = time();
$timelimit .= ')';
}
}
-
+
if ($CFG->dbtype == 'postgres7') {
return get_recordset_sql("SELECT p.id, p.subject, p.discussion, p.message,
- p.deleted, d.groupid, u.firstname, u.lastname
+ p.deleted, d.groupid, u.firstname, u.lastname
FROM {$CFG->prefix}forum_discussions d
JOIN {$CFG->prefix}forum_posts p ON p.discussion = d.id
JOIN {$CFG->prefix}user u ON p.userid = u.id
ORDER BY d.timemodified DESC");
} //else
} //forum_get_discussions_fast
-
+
//reworked faster version from /mod/forum/lib.php
function forum_get_child_posts_fast($parent, $forumid) {
global $CFG;
-
+
return get_recordset_sql("SELECT p.id, p.subject, p.discussion, p.message, p.deleted,
$forumid AS forum, u.firstname, u.lastname
FROM {$CFG->prefix}forum_posts p
WHERE p.parent = '$parent'
ORDER BY p.created ASC");
} //forum_get_child_posts_fast
-
+
?>
\ No newline at end of file
* */
require_once("$CFG->dirroot/search/documents/document.php");
-
- class GlossarySearchDocument extends SearchDocument {
+
+ class GlossarySearchDocument extends SearchDocument {
public function __construct(&$entry, $glossary_id, $course_id, $group_id) {
// generic information; required
$doc->docid = $entry['id'];
$doc->title = $entry['concept'];
$doc->date = $entry['timecreated'];
-
+
$user = get_recordset('user', 'id', $entry['userid'])->fields;
-
+
$doc->author = $user['firstname'].' '.$user['lastname'];
$doc->contents = $entry['definition'];
- $doc->url = glossary_make_link($entry['id']);
-
+ $doc->url = glossary_make_link($entry['id']);
+
// module specific information; optional
$data->glossary = $glossary_id;
-
+
// construct the parent class
parent::__construct($doc, $data, SEARCH_TYPE_GLOSSARY, $course_id, $group_id);
- } //constructor
- } //GlossarySearchDocument
+ } //constructor
+ } //GlossarySearchDocument
function glossary_make_link($entry_id) {
global $CFG;
-
+
//links directly to entry
//return $CFG->wwwroot.'/mod/glossary/showentry.php?eid='.$entry_id;
-
+
//preserve glossary pop-up, be careful where you place your ' and "s
//this function is meant to return a url that is placed between href='[url here]'
- return "$CFG->wwwroot/mod/glossary/showentry.php?eid=$entry_id' onclick='return openpopup(\"/mod/glossary/showentry.php?eid=$entry_id\", \"entry\", \"menubar=0,location=0,scrollbars,resizable,width=600,height=450\", 0);";
- } //glossary_make_link
-
+ return "$CFG->wwwroot/mod/glossary/showentry.php?eid=$entry_id' onclick='return openpopup(\"/mod/glossary/showentry.php?eid=$entry_id\", \"entry\", \"menubar=0,location=0,scrollbars,resizable,width=600,height=450\", 0);";
+ } //glossary_make_link
+
function glossary_iterator() {
- return get_all_instances_in_courses("glossary", get_courses());
+ return get_all_instances_in_courses("glossary", get_courses());
} //glossary_iterator
-
+
function glossary_get_content_for_index(&$glossary) {
$documents = array();
-
- $entries = get_recordset('glossary_entries', 'glossaryid', $glossary->id);
-
+
+ $entries = get_recordset('glossary_entries', 'glossaryid', $glossary->id);
+
while (!$entries->EOF) {
$entry = $entries->fields;
-
+
if ($entry and strlen($entry['definition']) > 0) {
$documents[] = new GlossarySearchDocument($entry, $glossary->id, $glossary->course, -1);
} //if
-
+
$entries->MoveNext();
} //foreach
-
+
return $documents;
} //glossary_get_content_for_index
-
+
//returns a single glossary search document based on a glossary_entry id
function glossary_single_document($id) {
$entries = get_recordset('glossary_entries', 'id', $id);
$entry = $entries->fields;
-
+
$glossaries = get_recordset('glossary', 'id', $entry['glossaryid']);
$glossary = $glossaries->fields;
-
+
return new GlossarySearchDocument($entry, $entry['glossaryid'], $glossary['course'], -1);
- } //glossary_single_document
-
+ } //glossary_single_document
+
//dummy delete function that converts docid from the search table to itself..
//this was here for a reason, but I can't remember it at the moment.
function glossary_delete($info) {
- return $info;
+ return $info;
} //glossary_delete
-
+
//returns the var names needed to build a sql query for addition/deletions
function glossary_db_names() {
//[primary id], [table name], [time created field name], [time modified field name]
- return array('id', 'glossary_entries', 'timecreated', 'timemodified');
- } //glossary_db_names
-
+ return array('id', 'glossary_entries', 'timecreated', 'timemodified');
+ } //glossary_db_names
+
?>
\ No newline at end of file
<?php
require_once("$CFG->dirroot/search/documents/document.php");
-
- class ResourceSearchDocument extends SearchDocument {
+
+ class ResourceSearchDocument extends SearchDocument {
public function __construct(&$resource) {
// generic information; required
$doc->docid = $resource['id'];
$doc->title = strip_tags($resource['name']);
$doc->date = $resource['timemodified'];
-
+
$doc->author = '';
$doc->contents = strip_tags($resource['summary']).' '.strip_tags($resource['alltext']);
- $doc->url = resource_make_link($resource['id']);
-
+ $doc->url = resource_make_link($resource['id']);
+
// module specific information; optional
$data = array();
-
+
// construct the parent class
parent::__construct($doc, $data, SEARCH_TYPE_RESOURCE, $resource['course'], -1);
- } //constructor
- } //ResourceSearchDocument
+ } //constructor
+ } //ResourceSearchDocument
function resource_make_link($resource_id) {
- global $CFG;
- return $CFG->wwwroot.'/mod/resource/view.php?r='.$resource_id;
+ global $CFG;
+ return $CFG->wwwroot.'/mod/resource/view.php?r='.$resource_id;
} //resource_make_link
-
+
function resource_iterator() {
//trick to leave search indexer functionality intact, but allow
//this document to only use the below function to return info
//to be searched
- return array(true);
+ return array(true);
} //resource_iterator
-
+
//this function does not need a content iterator, returns all the info
//itself; remember to fake the iterator array though
function resource_get_content_for_index(&$notneeded) {
$documents = array();
-
+
$resources = get_recordset_sql('SELECT *
FROM `resource`
WHERE alltext NOT LIKE ""
AND alltext NOT LIKE " "
AND alltext NOT LIKE " "
- AND TYPE != "file"');
-
+ AND TYPE != "file"');
+
while (!$resources->EOF) {
$resource = $resources->fields;
-
+
if ($resource) {
$documents[] = new ResourceSearchDocument($resource);
} //if
-
+
$resources->MoveNext();
} //foreach
-
+
return $documents;
} //resource_get_content_for_index
-
+
//returns a single resource search document based on a resource_entry id
function resource_single_document($id) {
$resources = get_recordset_sql('SELECT *
AND alltext NOT LIKE " "
AND alltext NOT LIKE " "
AND TYPE != "file",
- AND id = '.$id);
-
+ AND id = '.$id);
+
$resource = $resources->fields;
-
+
return new ResourceSearchDocument($resource);
- } //resource_single_document
-
+ } //resource_single_document
+
function resource_delete($info) {
- return $info;
+ return $info;
} //resource_delete
-
+
//returns the var names needed to build a sql query for addition/deletions
function resource_db_names() {
//[primary id], [table name], [time created field name], [time modified field name], [additional where conditions for sql]
- return array('id', 'resource', 'timemodified', 'timemodified', "WHERE alltext NOT LIKE '' AND alltext NOT LIKE ' ' AND alltext NOT LIKE ' ' AND TYPE != 'file'");
- } //resource_db_names
-
+ return array('id', 'resource', 'timemodified', 'timemodified', "WHERE alltext NOT LIKE '' AND alltext NOT LIKE ' ' AND alltext NOT LIKE ' ' AND TYPE != 'file'");
+ } //resource_db_names
+
?>
\ No newline at end of file
require_once("$CFG->dirroot/search/documents/document.php");
require_once("$CFG->dirroot/mod/wiki/lib.php");
-
+
/* All the $doc->___ fields are required by the base document class!
* Each and every module that requires search functionality must correctly
* map their internal fields to the five $doc fields (id, title, author, contents
* and url). Any module specific data can be added to the $data object, which is
* serialised into a binary field in the index.
- * */
- class WikiSearchDocument extends SearchDocument {
+ * */
+ class WikiSearchDocument extends SearchDocument {
public function __construct(&$page, $wiki_id, $course_id, $group_id) {
// generic information; required
$doc->docid = $page->id;
$doc->title = $page->pagename;
$doc->date = $page->timemodified;
-
+
//remove '(ip.ip.ip.ip)' from wiki author field
$doc->author = preg_replace('/\(.*?\)/', '', $page->author);
$doc->contents = $page->content;
- $doc->url = wiki_make_link($wiki_id, $page->pagename, $page->version);
-
+ $doc->url = wiki_make_link($wiki_id, $page->pagename, $page->version);
+
// module specific information; optional
$data->version = $page->version;
$data->wiki = $wiki_id;
-
+
// construct the parent class
parent::__construct($doc, $data, SEARCH_TYPE_WIKI, $course_id, $group_id);
- } //constructor
+ } //constructor
} //WikiSearchDocument
-
+
function wiki_name_convert($str) {
return str_replace(' ', '+', $str);
} //wiki_name_convert
function wiki_make_link($wiki_id, $title, $version) {
- global $CFG;
+ global $CFG;
return $CFG->wwwroot.'/mod/wiki/view.php?wid='.$wiki_id.'&page='.wiki_name_convert($title).'&version='.$version;
} //wiki_make_link
-
+
//rescued and converted from ewikimoodlelib.php
//retrieves latest version of a page
- function wiki_get_latest_page(&$entry, $pagename, $version=0) {
+ function wiki_get_latest_page(&$entry, $pagename, $version=0) {
$pagename = "'".addslashes($pagename)."'";
-
+
if ($version > 0 and is_int($version)) {
$version = "AND (version=$version)";
} else {
$version = '';
} //else
-
+
$select = "(pagename=$pagename) AND wiki=".$entry->id." $version ";
$sort = 'version DESC';
-
+
//change this to recordset_select, as per http://docs.moodle.org/en/Datalib_Notes
- if ($result_arr = get_records_select('wiki_pages', $select, $sort, '*', 0, 1)) {
+ if ($result_arr = get_records_select('wiki_pages', $select, $sort, '*', 0, 1)) {
foreach ($result_arr as $obj) {
- $result_obj = $obj;
+ $result_obj = $obj;
} //foreach
} //if
-
+
if (isset($result_obj)) {
$result_obj->meta = @unserialize($result_obj->meta);
return $result_obj;
return false;
} //else
} //wiki_get_latest_page
-
+
//fetches all pages, including old versions
- function wiki_get_pages(&$entry) {
+ function wiki_get_pages(&$entry) {
return get_records('wiki_pages', 'wiki', $entry->id);
} //wiki_get_pages
-
+
//fetches all the latest versions of all the pages
function wiki_get_latest_pages(&$entry) {
//== (My)SQL for this
from wiki_pages group by pagename) as a
on ((wiki_pages.version = a.ver) and
(wiki_pages.pagename like a.pagename)) */
-
- $pages = array();
-
+
+ $pages = array();
+
//http://moodle.org/bugs/bug.php?op=show&bugid=5877&pos=0
- //if ($ids = get_records('wiki_pages', 'wiki', $entry->id, '', 'distinct pagename')) {
+ //if ($ids = get_records('wiki_pages', 'wiki', $entry->id, '', 'distinct pagename')) {
if ($rs = get_recordset('wiki_pages', 'wiki', $entry->id, '', 'distinct pagename')) {
$ids = $rs->GetRows();
- //--
- foreach ($ids as $id) {
+ //--
+ foreach ($ids as $id) {
$pages[] = wiki_get_latest_page($entry, $id[0]);
} //foreach
} else {
return false;
- } //else
-
- return $pages;
+ } //else
+
+ return $pages;
} //wiki_get_latest_pages
-
+
function wiki_iterator() {
- return get_all_instances_in_courses("wiki", get_courses());
+ return get_all_instances_in_courses("wiki", get_courses());
} //wiki_iterator
-
+
function wiki_get_content_for_index(&$wiki) {
$documents = array();
-
- $entries = wiki_get_entries($wiki);
+
+ $entries = wiki_get_entries($wiki);
foreach($entries as $entry) {
//all pages
//$pages = wiki_get_pages($entry);
-
+
//latest pages
$pages = wiki_get_latest_pages($entry);
-
+
if (is_array($pages)) {
foreach($pages as $page) {
if (strlen($page->content) > 0) {
} //foreach
} //if
} //foreach
-
+
return $documents;
- } //wiki_get_content_for_index
-
+ } //wiki_get_content_for_index
+
//returns a single wiki search document based on a wiki_entry id
function wiki_single_document($id) {
$pages = get_recordset('wiki_pages', 'id', $id);
$page = $pages->fields;
-
+
$entries = get_recordset('wiki_entries', 'id', $page['wiki']);
$entry = $entries->fields;
-
+
return new WikiSearchDocument($page, $entry['wikiid'], $entry['course'], $entry['groupid']);
- } //wiki_single_document
-
+ } //wiki_single_document
+
function wiki_delete($info) {
- return $info;
+ return $info;
} //wiki_delete
-
+
//returns the var names needed to build a sql query for addition/deletions
function wiki_db_names() {
//[primary id], [table name], [time created field name], [time modified field name]
- return array('id', 'wiki_pages', 'created', 'lastmodified');
- } //wiki_db_names
-
+ return array('id', 'wiki_pages', 'created', 'lastmodified');
+ } //wiki_db_names
+
?>
\ No newline at end of file
-<?php
+<?php
/* Entry page for /search
* Redirects to query.php, because that is the most likely place a
* user intended to go to when typing moodle.site/search
* */
- header("Location: query.php");
+ header("Location: query.php");
?>
\ No newline at end of file
//this'll take some time, set up the environment
@set_time_limit(0);
@ob_implicit_flush(true);
- @ob_end_flush();
+ @ob_end_flush();
require_once('../config.php');
- require_once("$CFG->dirroot/search/lib.php");
+ require_once("$CFG->dirroot/search/lib.php");
- //only administrators can index the moodle installation, because access to all pages is required
+ //only administrators can index the moodle installation, because access to all pages is required
require_login();
if (!isadmin()) {
error("You need to be an admin user to use this page.", "$CFG->wwwroot/login/index.php");
} //if
-
+
//confirmation flag to prevent accidental reindexing (indexersplash.php is the correct entry point)
$sure = strtolower(optional_param('areyousure', '', PARAM_ALPHA));
-
+
if ($sure != 'yes') {
mtrace("<pre>Sorry, you need to confirm indexing via <a href='indexersplash.php'>indexersplash.php</a>"
.". (<a href='index.php'>Back to query page</a>).</pre>");
-
+
exit(0);
- } //if
-
+ } //if
+
//check for php5 (lib.php)
if (!search_check_php5()) {
$phpversion = phpversion();
mtrace("Sorry, global search requires PHP 5.0.0 or later (currently using version $phpversion)");
exit(0);
} //if
-
+
//php5 found, continue including php5-only files
//require_once("$CFG->dirroot/search/Zend/Search/Lucene.php");
- require_once("$CFG->dirroot/search/indexlib.php");
-
+ require_once("$CFG->dirroot/search/indexlib.php");
+
mtrace('<pre>Server Time: '.date('r',time())."\n");
if ($CFG->search_indexer_busy == '1') {
//turn on busy flag
set_config('search_indexer_busy', '1');
-
+
//paths
$index_path = SEARCH_INDEX_PATH;
$index_db_file = "$CFG->dirroot/search/db/$CFG->dbtype.sql";
- $dbcontrol = new IndexDBControl();
-
+ $dbcontrol = new IndexDBControl();
+
//setup directory in data root
if (!file_exists($index_path)) {
mtrace("Data directory ($index_path) does not exist, attempting to create.");
} else {
mtrace("Using $index_path as data directory.");
} //else
-
+
$index = new Zend_Search_Lucene($index_path, true);
-
+
if (!$dbcontrol->checkDB()) {
search_pexit("Database error. Please check settings/files.");
- } //if
+ } //if
//begin timer
search_stopwatch();
mtrace("Starting activity modules\n");
-
+
//the presence of the required search functions -
// * mod_iterator
// * mod_get_content_for_index
//are the sole basis for including a module in the index at the moment.
-
+
if ($mods = get_records_select('modules' /*'index this module?' where statement*/)) {
- //add virtual modules onto the back of the array
- $mods = array_merge($mods, search_get_additional_modules());
-
- foreach ($mods as $mod) {
- $class_file = $CFG->dirroot.'/search/documents/'.$mod->name.'_document.php';
-
+ //add virtual modules onto the back of the array
+ $mods = array_merge($mods, search_get_additional_modules());
+
+ foreach ($mods as $mod) {
+ $class_file = $CFG->dirroot.'/search/documents/'.$mod->name.'_document.php';
+
if (file_exists($class_file)) {
include_once($class_file);
-
+
//build function names
$iter_function = $mod->name.'_iterator';
$index_function = $mod->name.'_get_content_for_index';
-
+
$counter = 0;
$doc = new stdClass;
-
+
if (function_exists($index_function) && function_exists($iter_function)) {
mtrace("Processing module function $index_function ...");
-
+
foreach ($iter_function() as $i) {
$documents = $index_function($i);
-
+
//begin transaction
-
+
foreach($documents as $document) {
$counter++;
-
+
//object to insert into db
$dbid = $dbcontrol->addDocument($document);
-
+
//synchronise db with index
$document->addField(Zend_Search_Lucene_Field::Keyword('dbid', $dbid));
-
+
//add document to index
- $index->addDocument($document);
-
- //commit every x new documents, and print a status message
+ $index->addDocument($document);
+
+ //commit every x new documents, and print a status message
if (($counter%2000) == 0) {
$index->commit();
mtrace(".. $counter");
} //foreach
//end transaction
-
+
} //foreach
-
- //commit left over documents, and finish up
+
+ //commit left over documents, and finish up
$index->commit();
-
+
mtrace("-- $counter documents indexed");
- mtrace("done.\n");
+ mtrace("done.\n");
} //if
} //if
} //foreach
} //if
-
+
//finished modules
mtrace('Finished activity modules');
search_stopwatch();
-
+
//now blocks...
//
-
+
mtrace(".<br><a href='index.php'>Back to query page</a>.");
mtrace('</pre>');
-
+
//finished, turn busy flag off
set_config("search_indexer_busy", "0");
-
+
//mark the time we last updated
set_config("search_indexer_run_date", time());
-
+
//and the index size
set_config("search_index_size", (int)$index->count());
-
+
?>
\ No newline at end of file
* it is in place to prevent accidental reindexing which can lead to a loss
* of time, amongst other things.
* */
-
+
require_once('../config.php');
- require_once("$CFG->dirroot/search/lib.php");
+ require_once("$CFG->dirroot/search/lib.php");
require_login();
if (!isadmin()) {
error("You need to be an admin user to use this page.", "$CFG->wwwroot/login/index.php");
} //if
-
+
//check for php5 (lib.php)
if (!search_check_php5()) {
$phpversion = phpversion();
mtrace("Sorry, global search requires PHP 5.0.0 or later (currently using version $phpversion)");
exit(0);
} //if
-
- require_once("$CFG->dirroot/search/indexlib.php");
+
+ require_once("$CFG->dirroot/search/indexlib.php");
$indexinfo = new IndexInfo();
-
- if ($indexinfo->valid()) {
+
+ if ($indexinfo->valid()) {
mtrace("<pre>The data directory ($indexinfo->path) contains $indexinfo->filecount files, and\n"
."there are ".$indexinfo->dbcount." records in the <em>search_documents</em> table.\n"
."\n"
."</pre>");
} else {
header('Location: indexer.php?areyousure=yes');
- } //else
+ } //else
?>
\ No newline at end of file
* */
require_once("$CFG->dirroot/search/lib.php");
- require_once("$CFG->dirroot/search/Zend/Search/Lucene.php");
+ require_once("$CFG->dirroot/search/Zend/Search/Lucene.php");
class IndexInfo {
private $path, //index data directory
$types, //array of [document types => count]
$complete, //is index completely formed?
$time; //date index was generated
-
+
public function __construct($path=SEARCH_INDEX_PATH) {
global $CFG, $db;
-
+
$this->path = $path;
-
+
//test to see if there is a valid index on disk, at the specified path
try {
$test_index = new Zend_Search_Lucene($this->path, false);
- $validindex = true;
- } catch(Exception $e) {
+ $validindex = true;
+ } catch(Exception $e) {
$validindex = false;
} //catch
- //retrieve file system info about the index if it is valid
- if ($validindex) {
+ //retrieve file system info about the index if it is valid
+ if ($validindex) {
$this->size = display_size(get_directory_size($this->path));
$index_dir = get_directory_list($this->path, '', false, false);
$this->filecount = count($index_dir);
} //else
$db_exists = false; //for now
-
+
//get all the current tables in moodle
$admin_tables = $db->MetaTables();
-
+
//TODO: use new IndexDBControl class for database checks?
-
+
//check if our search table exists
if (in_array($CFG->prefix.SEARCH_DATABASE_TABLE, $admin_tables)) {
//retrieve database information if it does
$db_exists = true;
-
+
//total documents
$this->dbcount = count_records(SEARCH_DATABASE_TABLE);
//individual document types
$types = search_get_document_types();
sort($types);
-
+
foreach($types as $type) {
$c = count_records(SEARCH_DATABASE_TABLE, 'doctype', $type);
$this->types[$type] = (int)$c;
} else {
$this->dbcount = 0;
$this->types = array();
- } //else
-
+ } //else
+
//check if the busy flag is set
if ($CFG->search_indexer_busy == '1') {
$this->complete = false;
} else {
$this->complete = true;
} //if
-
+
//get the last run date for the indexer
if ($this->valid() && $CFG->search_indexer_run_date) {
$this->time = $CFG->search_indexer_run_date;
$this->time = 0;
} //else
} //__construct
-
+
//returns false on error, and the error message via referenced variable $err
public function valid(&$err=null) {
$err = array();
$ret = true;
-
+
if (!$this->is_valid_dir()) {
$err['dir'] = 'Index directory either contains an invalid index, or nothing at all.';
$ret = false;
} //if
-
+
if (!$this->is_valid_db()) {
$err['db'] = 'Database table is not present, or contains no index records.';
$ret = false;
} //if
-
+
if (!$this->complete) {
$err['index'] = 'Indexing was not successfully completed, please restart it.';
$ret = false;
} //if
-
- return $ret;
+
+ return $ret;
} //valid
-
+
//is the index dir valid
public function is_valid_dir() {
if ($this->filecount > 0) {
return false;
} //else
} //is_valid_dir
-
+
//is the db table valid
public function is_valid_db() {
if ($this->dbcount > 0) {
} else {
return false;
} //else
- } //is_valid_db
-
+ } //is_valid_db
+
//shorthand get method for the class variables
- public function __get($var) {
+ public function __get($var) {
if (in_array($var, array_keys(get_class_vars(get_class($this))))) {
return $this->$var;
} //if
- } //__get
+ } //__get
} //IndexInfo
-
-
- /* DB Index control class
- *
+
+
+ /* DB Index control class
+ *
* Used to control the search index database table
* */
-
- class IndexDBControl {
+
+ class IndexDBControl {
//does the table exist?
public function checkTableExists() {
global $CFG, $db;
-
+
$table = SEARCH_DATABASE_TABLE;
$tables = $db->MetaTables();
-
+
if (in_array($CFG->prefix.$table, $tables)) {
return true;
} else {
return false;
} //else
} //checkTableExists
-
+
//is our database setup valid?
public function checkDB() {
global $CFG, $db;
-
+
$sqlfile = "$CFG->dirroot/search/db/$CFG->dbtype.sql";
- $ret = false;
-
- if ($this->checkTableExists()) {
+ $ret = false;
+
+ if ($this->checkTableExists()) {
execute_sql('drop table '.$CFG->prefix.SEARCH_DATABASE_TABLE, false);
} //if
-
+
ob_start(); //turn output buffering on - to hide modify_database() output
$ret = modify_database($sqlfile, '', false);
ob_end_clean(); //chuck the buffer and resume normal operation
-
+
return $ret;
} //checkDB
-
+
//add a document record to the table
public function addDocument($document=null) {
global $db;
-
+
if ($document == null) {
return false;
} //if
-
- //object to insert into db
+
+ //object to insert into db
$doc->doctype = $document->doctype;
$doc->docid = $document->docid;
$doc->title = search_escape_string($document->title);
- $doc->url = search_escape_string($document->url);
- $doc->update = time();
- $doc->docdate = $document->date;
- $doc->courseid = $document->course_id;
- $doc->groupid = $document->group_id;
-
+ $doc->url = search_escape_string($document->url);
+ $doc->update = time();
+ $doc->docdate = $document->date;
+ $doc->courseid = $document->course_id;
+ $doc->groupid = $document->group_id;
+
//insert summary into db
$id = insert_record(SEARCH_DATABASE_TABLE, $doc);
-
+
return $id;
} //addDocument
-
+
//remove a document record from the index
public function delDocument($document) {
global $db;
-
+
delete_records(SEARCH_DATABASE_TABLE, 'id', $document->dbid);
} //delDocument
} //IndexControl
-
+
?>
\ No newline at end of file
* This file must not contain any PHP 5, because it is used to test for PHP 5
* itself, and needs to be able to be executed on PHP 4 installations.
* */
-
+
define('SEARCH_INDEX_PATH', "$CFG->dataroot/search");
define('SEARCH_DATABASE_TABLE', 'search_documents');
-
- //document types that can be searched
+
+ //document types that can be searched
//define('SEARCH_TYPE_NONE', 'none');
define('SEARCH_TYPE_WIKI', 'wiki');
define('SEARCH_TYPE_FORUM', 'forum');
define('SEARCH_TYPE_GLOSSARY', 'glossary');
define('SEARCH_TYPE_RESOURCE', 'resource');
-
+
//returns all the document type constants
function search_get_document_types($prefix='SEARCH_TYPE') {
$ret = array();
-
+
foreach (get_defined_constants() as $key=>$value) {
if (substr($key, 0, strlen($prefix)) == $prefix) {
$ret[$key] = $value;
} //if
} //foreach
-
+
sort($ret);
-
+
return $ret;
} //search_get_document_types
-
+
// additional virtual modules to index
//
// By adding 'moo' to the extras array, an additional document type
function search_get_additional_modules() {
$extras = array(/* additional keywords go here */);
$ret = array();
-
+
foreach($extras as $extra) {
$temp->name = $extra;
$ret[] = clone($temp);
} //foreach
-
+
return $ret;
- } //search_get_additional_modules
-
+ } //search_get_additional_modules
+
//shortens a url so it can fit on the results page
- function search_shorten_url($url, $length=30) {
+ function search_shorten_url($url, $length=30) {
return substr($url, 0, $length)."...";
} //search_shorten_url
-
+
function search_escape_string($str) {
global $CFG;
-
+
switch ($CFG->dbtype) {
case 'mysql':
$s = mysql_real_escape_string($str);
default:
$s = addslashes($str);
} //switch
-
+
return $s;
} //search_escape_string
- //get a real php 5 version number, using 5.0.0 arbitrarily
+ //get a real php 5 version number, using 5.0.0 arbitrarily
function search_check_php5($feedback=false) {
if (!check_php_version("5.0.0")) {
if ($feedback) {
$phpversion = phpversion();
print_heading("Sorry, global search requires PHP 5.0.0 or later (currently using version $phpversion)");
} //if
-
+
return false;
} else {
return true;
} //else
} //search_check_php5
-
+
//simple timer function, outputs result on 2nd call
function search_stopwatch($cli = false) {
if (!empty($GLOBALS['search_script_start_time'])) {
if (!$cli) print '<em>';
print round(microtime(true) - $GLOBALS['search_script_start_time'], 6).' seconds';
if (!$cli) print '</em>';
-
+
unset($GLOBALS['search_script_start_time']);
} else {
$GLOBALS['search_script_start_time'] = microtime(true);
} //else
} //search_stopwatch
-
+
//print and exit (for debugging)
function search_pexit($str = "") {
if (is_array($str) or is_object($str)) {
} else if ($str) {
print $str."<br>";
} //if
-
+
exit(0);
} //search_pexit
/* The query page - accepts a user-entered query string and returns results.
*
* Queries are boolean-aware, e.g.:
- *
+ *
* '+' term required
* '-' term must not be present
* '' (no modifier) term's presence increases rank, but isn't required
*
* '+author:helen +author:foster'
* All articles written by Helen Foster
- *
+ *
* */
require_once('../config.php');
- require_once("$CFG->dirroot/search/lib.php");
-
+ require_once("$CFG->dirroot/search/lib.php");
+
//check for php5, but don't die yet (see line 52)
- if ($check = search_check_php5()) {
+ if ($check = search_check_php5()) {
require_once("$CFG->dirroot/search/querylib.php");
-
+
$page_number = optional_param('page', -1, PARAM_INT);
- $pages = ($page_number == -1) ? false : true;
- $advanced = (optional_param('a', '0', PARAM_INT) == '1') ? true : false;
- $query_string = optional_param('query_string', '', PARAM_CLEAN);
-
+ $pages = ($page_number == -1) ? false : true;
+ $advanced = (optional_param('a', '0', PARAM_INT) == '1') ? true : false;
+ $query_string = optional_param('query_string', '', PARAM_CLEAN);
+
if ($pages && isset($_SESSION['search_advanced_query'])) {
//if both are set, then we are busy browsing through the result pages of an advanced query
$adv = unserialize($_SESSION['search_advanced_query']);
//chars to strip from strings (whitespace)
$chars = " \t\n\r\0\x0B,-+";
-
+
//retrieve advanced query variables
$adv->mustappear = trim(optional_param('mustappear', '', PARAM_CLEAN), $chars);
$adv->notappear = trim(optional_param('notappear', '', PARAM_CLEAN), $chars);
$adv->module = optional_param('module', '', PARAM_CLEAN);
$adv->title = trim(optional_param('title', '', PARAM_CLEAN), $chars);
$adv->author = trim(optional_param('author', '', PARAM_CLEAN), $chars);
- } //else
-
+ } //else
+
if ($advanced) {
//parse the advanced variables into a query string
//TODO: move out to external query class (QueryParse?)
-
- $query_string = '';
-
+
+ $query_string = '';
+
//get all available module types
- $module_types = array_merge(array('All'), array_values(search_get_document_types()));
+ $module_types = array_merge(array('All'), array_values(search_get_document_types()));
$adv->module = in_array($adv->module, $module_types) ? $adv->module : 'All';
-
- //convert '1 2' into '+1 +2' for required words field
+
+ //convert '1 2' into '+1 +2' for required words field
if (strlen(trim($adv->mustappear)) > 0) {
$query_string = ' +'.implode(' +', preg_split("/[\s,;]+/", $adv->mustappear));
} //if
-
+
//convert '1 2' into '-1 -2' for not wanted words field
if (strlen(trim($adv->notappear)) > 0) {
$query_string .= ' -'.implode(' -', preg_split("/[\s,;]+/", $adv->notappear));
} //if
-
+
//this field is left untouched, apart from whitespace being stripped
- if (strlen(trim($adv->canappear)) > 0) {
+ if (strlen(trim($adv->canappear)) > 0) {
$query_string .= ' '.implode(' ', preg_split("/[\s,;]+/", $adv->canappear));
} //if
-
+
//add module restriction
if ($adv->module != 'All') {
$query_string .= ' +doctype:'.$adv->module;
} //if
-
+
//create title search string
if (strlen(trim($adv->title)) > 0) {
$query_string .= ' +title:'.implode(' +title:', preg_split("/[\s,;]+/", $adv->title));
} //if
-
+
//create author search string
if (strlen(trim($adv->author)) > 0) {
$query_string .= ' +author:'.implode(' +author:', preg_split("/[\s,;]+/", $adv->author));
- } //if
-
+ } //if
+
//save our options if the query is valid
if (!empty($query_string)) {
$_SESSION['search_advanced_query'] = serialize($adv);
- } //if
+ } //if
} //if
-
+
//normalise page number
if ($page_number < 1) {
$page_number = 1;
- } //if
-
+ } //if
+
//run the query against the index
- $sq = new SearchQuery($query_string, $page_number, 10, false);
+ $sq = new SearchQuery($query_string, $page_number, 10, false);
} //if
-
+
if (!$site = get_site()) {
redirect("index.php");
} //if
-
+
$strsearch = "Search"; //get_string();
$strquery = "Enter your search query"; //get_string();
- print_header("$site->shortname: $strsearch: $strquery", "$site->fullname",
+ print_header("$site->shortname: $strsearch: $strquery", "$site->fullname",
"<a href=\"index.php\">$strsearch</a> -> $strquery");
-
+
//keep things pretty, even if php5 isn't available
if (!$check) {
print_heading(search_check_php5(true));
print_footer();
exit(0);
} //if
-
+
print_simple_box_start('center', '100%', '', 20);
print_heading($strquery);
-
+
print_simple_box_start('center', '', '', 20);
-
+
$vars = get_object_vars($adv);
-
+
foreach ($vars as $key => $value) {
$adv->$key = stripslashes(htmlentities($value));
- } //foreach
-
+ } //foreach
+
?>
<form name="query" method="get" action="query.php">
<?php if (!$advanced) { ?>
<input type="text" name="query_string" length="50" value="<?php print stripslashes(htmlentities($query_string)) ?>"/>
- <input type="submit" value="Search"/>
+ <input type="submit" value="Search"/>
<a href="query.php?a=1">Advanced search</a>
<a href="stats.php">Statistics</a>
<?php } else {
- print_simple_box_start('center', '', 'white', 10);
- ?>
+ print_simple_box_start('center', '', 'white', 10);
+ ?>
<input type="hidden" name="a" value="<?php print $advanced; ?>"/>
-
+
<table border="0" cellpadding="3" cellspacing="3">
-
+
<tr>
<td width="240">These words must appear:</td>
<td><input type="text" name="mustappear" length="50" value="<?php print $adv->mustappear; ?>"/></td>
</tr>
-
+
<tr>
<td>These words must not appear:</td>
<td><input type="text" name="notappear" length="50" value="<?php print $adv->notappear; ?>"/></td>
<tr>
<td>These words help improve rank:</td>
<td><input type="text" name="canappear" length="50" value="<?php print $adv->canappear; ?>"/></td>
- </tr>
-
+ </tr>
+
<tr>
<td>Which modules to search?:</td>
<td>
- <select name="module">
+ <select name="module">
<?php foreach($module_types as $mod) {
if ($mod == $adv->module) {
print "<option value='$mod' selected>$mod</option>\n";
</select>
</td>
</tr>
-
+
<tr>
<td>Words in title:</td>
<td><input type="text" name="title" length="50" value="<?php print $adv->title; ?>"/></td>
</tr>
-
+
<tr>
<td>Author name:</td>
<td><input type="text" name="author" length="50" value="<?php print $adv->author; ?>"/></td>
</tr>
-
+
<tr>
<td colspan="3" align="center"><br><input type="submit" value="Search"/></td>
</tr>
-
+
<tr>
<td colspan="3" align="center">
<table border="0" cellpadding="0" cellspacing="0">
</table>
</td>
</tr>
- </table>
+ </table>
<?php
print_simple_box_end();
} //if
print '<div align="center">';
print 'Searching: ';
-
+
if ($sq->is_valid_index()) {
//use cached variable to show up-to-date index size (takes deletions into account)
print $CFG->search_index_size;
} else {
print "0";
} //else
-
+
print ' documents.';
-
+
if (!$sq->is_valid_index() and isadmin()) {
print "<br><br>Admin: There appears to be no index, click <a href='indexersplash.php'>here</a> to create one.";
} //if
print '</div>';
print_simple_box_end();
-
+
if ($sq->is_valid()) {
print_simple_box_start('center', '50%', 'white', 10);
-
- search_stopwatch();
- $hit_count = $sq->count();
-
+
+ search_stopwatch();
+ $hit_count = $sq->count();
+
print "<br>";
print $hit_count." results returned for '".stripslashes($query_string)."'.";
print "<br>";
-
- if ($hit_count > 0) {
- $page_links = $sq->page_numbers();
+
+ if ($hit_count > 0) {
+ $page_links = $sq->page_numbers();
$hits = $sq->results();
-
+
if ($advanced) {
- //if in advanced mode, search options are saved in the session, so
+ //if in advanced mode, search options are saved in the session, so
//we can remove the query string var from the page links, and replace
//it with a=1 (Advanced = on) instead
$page_links = preg_replace("/query_string=[^&]+/", 'a=1', $page_links);
} //if
-
+
print "<ol>";
-
+
foreach ($hits as $listing) {
print "<li value='".($listing->number+1)."'><a href='".$listing->url."'>$listing->title</a><br>\n"
- ."<em>".search_shorten_url($listing->url, 70)."</em><br>\n"
- ."Type: ".$listing->doctype.", score: ".round($listing->score, 3).", author: ".$listing->author."<br>\n"
+ ."<em>".search_shorten_url($listing->url, 70)."</em><br>\n"
+ ."Type: ".$listing->doctype.", score: ".round($listing->score, 3).", author: ".$listing->author."<br>\n"
."<br></li>\n";
} //for
-
+
print "</ol>";
print $page_links;
- } //if
-
+ } //if
+
print_simple_box_end();
?>
<?php
} //if (sq is valid)
-
+
print_simple_box_end();
print_footer();
?>
\ No newline at end of file
class SearchResult {
public $url,
- $title,
+ $title,
$doctype,
$author,
$score,
class SearchCache {
private $mode,
$valid;
-
+
public function __construct($mode='session') {
$accepted_modes = array('session');
-
+
if (in_array($mode, $accepted_modes)) {
$this->mode = $mode;
} else {
$this->mode = 'session';
} //else
-
+
$this->valid = true;
} //constructor
-
+
public function can_cache() {
return $this->valid;
} //can_cache
-
+
public function cache($id=false, $object=false) {
//see if there was a previous query
$last_term = $this->fetch('search_last_term');
-
+
//if this query is different from the last, clear out the last one
if ($id != false and $last_term != $id) {
$this->clear($last_term);
} //if
-
+
//store the new query if id and object are passed in
if ($object and $id) {
$this->store('search_last_term', $id);
$this->store($id, $object);
return true;
//otherwise return the stored results
- } else if ($id and $this->exists($id)) {
+ } else if ($id and $this->exists($id)) {
return $this->fetch($id);
} //else
} //cache
-
+
private function exists($id) {
switch ($this->mode) {
case 'session' :
return isset($_SESSION[$id]);
} //switch
} //exists
-
+
private function clear($id) {
switch ($this->mode) {
case 'session' :
session_unregister($id);
return;
} //switch
- } //clear
-
+ } //clear
+
private function fetch($id) {
switch ($this->mode) {
case 'session' :
return ($this->exists($id)) ? unserialize($_SESSION[$id]) : false;
} //switch
} //fetch
-
+
private function store($id, $object) {
switch ($this->mode) {
case 'session' :
$_SESSION[$id] = serialize($object);
return;
} //switch
- } //store
+ } //store
} //SearchCache
-
-
+
+
class SearchQuery {
private $index,
$term,
- $pagenumber,
+ $pagenumber,
$cache,
$validquery,
- $validindex,
+ $validindex,
$results,
$results_per_page,
$total_results;
-
+
public function __construct($term='', $page=1, $results_per_page=10, $cache=false) {
global $CFG;
-
+
$this->term = $term;
$this->pagenumber = $page;
$this->cache = $cache;
$this->validquery = true;
- $this->validindex = true;
- $this->results_per_page = $results_per_page;
-
+ $this->validindex = true;
+ $this->results_per_page = $results_per_page;
+
$index_path = SEARCH_INDEX_PATH;
-
+
try {
$this->index = new Zend_Search_Lucene($index_path, false);
- } catch(Exception $e) {
- $this->validindex = false;
+ } catch(Exception $e) {
+ $this->validindex = false;
return;
} //catch
-
+
if (empty($this->term)) {
$this->validquery = false;
} else {
$this->set_query($this->term);
- } //else
+ } //else
} //constructor
-
- public function set_query($term='') {
+
+ public function set_query($term='') {
if (!empty($term)) {
$this->term = $term;
} //if
-
+
if (empty($this->term)) {
$this->validquery = false;
} else {
$this->validquery = true;
} //else
-
+
if ($this->validquery and $this->validindex) {
$this->results = $this->get_results();
} else {
$this->results = array();
- } //else
+ } //else
} //set_query
-
+
public function results() {
return $this->results;
} //results
-
+
private function process_results($all=false) {
global $USER;
- $term = strtolower($this->term);
-
+ $term = strtolower($this->term);
+
//experimental - return more results
- $strip_arr = array('author:', 'title:', '+', '-', 'doctype:');
+ $strip_arr = array('author:', 'title:', '+', '-', 'doctype:');
$stripped_term = str_replace($strip_arr, '', $term);
-
+
$hits = $this->index->find($term." title:".$stripped_term." author:".$stripped_term);
//--
-
+
$hitcount = count($hits);
- $this->total_results = $hitcount;
-
+ $this->total_results = $hitcount;
+
if ($hitcount == 0) return array();
-
+
$totalpages = ceil($hitcount/$this->results_per_page);
-
+
if (!$all) {
if ($hitcount < $this->results_per_page) {
$this->pagenumber = 1;
} else if ($this->pagenumber > $totalpages) {
$this->pagenumber =$totalpages;
- } //if
-
+ } //if
+
$start = ($this->pagenumber - 1) * $this->results_per_page;
$end = $start + $this->results_per_page;
-
+
if ($end > $hitcount) {
$end = $hitcount;
- } //if
+ } //if
} else {
$start = 0;
$end = $hitcount;
} //else
-
+
$resultdoc = new SearchResult();
- $resultdocs = array();
-
+ $resultdocs = array();
+
for ($i = $start; $i < $end; $i++) {
$hit = $hits[$i];
-
+
//check permissions on each result
if ($this->can_display($USER, $hit->id, $hit->doctype, $hit->course_id, $hit->group_id)) {
$resultdoc->number = $i;
$resultdoc->score = $hit->score;
$resultdoc->doctype = $hit->doctype;
$resultdoc->author = $hit->author;
-
+
//and store it
- $resultdocs[] = clone($resultdoc);
+ $resultdocs[] = clone($resultdoc);
} //if
} //foreach
-
+
return $resultdocs;
} //process_results
-
+
private function get_results() {
$cache = new SearchCache();
-
- if ($this->cache and $cache->can_cache()) {
+
+ if ($this->cache and $cache->can_cache()) {
if (!($resultdocs = $cache->cache($this->term))) {
$resultdocs = $this->process_results();
//cache the results so we don't have to compute this on every page-load
- $cache->cache($this->term, $resultdocs);
+ $cache->cache($this->term, $resultdocs);
//print "Using new results.";
- } else {
+ } else {
//There was something in the cache, so we're using that to save time
//print "Using cached results.";
- } //else
+ } //else
} else {
//no caching :(
//print "Caching disabled!";
} //else
return $resultdocs;
- } //get_results
-
+ } //get_results
+
public function page_numbers() {
$pages = $this->total_pages();
- $query = htmlentities($this->term);
+ $query = htmlentities($this->term);
$page = $this->pagenumber;
$next = "Next";
$back = "Back";
-
- $ret = "<div align='center' id='search_page_links'>";
-
+
+ $ret = "<div align='center' id='search_page_links'>";
+
//Back is disabled if we're on page 1
if ($page > 1) {
$ret .= "<a href='query.php?query_string=$query&page=".($page-1)."'>< $back</a> ";
} else {
$ret .= "< $back ";
} //else
-
+
//don't <a href> the current page
for ($i = 1; $i <= $pages; $i++) {
if ($page == $i) {
$ret .= "<a href='query.php?query_string=$query&page=$i'>$i</a> ";
} //else
} //for
-
+
//Next disabled if we're on the last page
- if ($page < $pages) {
+ if ($page < $pages) {
$ret .= "<a href='query.php?query_string=$query&page=".($page+1)."'>$next ></a> ";
} else {
$ret .= "$next > ";
} //else
-
- $ret .= "</div>";
-
+
+ $ret .= "</div>";
+
//shorten really long page lists, to stop table distorting width-ways
if (strlen($ret) > 70) {
$start = 4;
- $end = $page - 5;
+ $end = $page - 5;
$ret = preg_replace("/<a\D+\d+\D+>$start<\/a>.*?<a\D+\d+\D+>$end<\/a>/", '...', $ret);
-
+
$start = $page + 5;
- $end = $pages - 3;
+ $end = $pages - 3;
$ret = preg_replace("/<a\D+\d+\D+>$start<\/a>.*?<a\D+\d+\D+>$end<\/a>/", '...', $ret);
} //if
-
+
return $ret;
- } //page_numbers
+ } //page_numbers
- //can the user see this result?
+ //can the user see this result?
private function can_display(&$user, $this_id, $doctype, $course_id, $group_id) {
//this function should return true/false depending on
//whether or not a user can see this resource
//..
//if one of you nice moodlers see this, feel free to
- //implement it for me .. :-P
+ //implement it for me .. :-P
return true;
} //can_display
-
+
public function count() {
return $this->total_results;
} //count
-
+
public function is_valid() {
return ($this->validquery and $this->validindex);
} //is_valid
-
+
public function is_valid_query() {
return $this->validquery;
} //is_valid_query
public function is_valid_index() {
return $this->validindex;
} //is_valid_index
-
+
public function total_pages() {
return ceil($this->count()/$this->results_per_page);
- } //pages
-
+ } //pages
+
public function get_pagenumber() {
return $this->pagenumber;
} //get_pagenumber
-
+
public function get_results_per_page() {
return $this->results_per_page;
- } //get_results_per_page
+ } //get_results_per_page
} //SearchQuery
?>
\ No newline at end of file
<?php
/* Prints some basic statistics about the current index.
*
- * Does some diagnostics if you are logged in as an administrator.
+ * Does some diagnostics if you are logged in as an administrator.
* */
-
- require_once('../config.php');
- require_once("$CFG->dirroot/search/lib.php");
+
+ require_once('../config.php');
+ require_once("$CFG->dirroot/search/lib.php");
//check for php5, but don't die yet
if ($check = search_check_php5()) {
- require_once("$CFG->dirroot/search/indexlib.php");
-
+ require_once("$CFG->dirroot/search/indexlib.php");
+
$indexinfo = new IndexInfo();
} //if
-
+
if (!$site = get_site()) {
redirect("index.php");
} //if
-
+
$strsearch = "Search"; //get_string();
$strquery = "Search statistics"; //get_string();
- print_header("$site->shortname: $strsearch: $strquery", "$site->fullname",
+ print_header("$site->shortname: $strsearch: $strquery", "$site->fullname",
"<a href=\"index.php\">$strsearch</a> -> $strquery");
-
+
//keep things pretty, even if php5 isn't available
if (!$check) {
print_heading(search_check_php5(true));
print_footer();
exit(0);
} //if
-
+
print_simple_box_start('center', '100%', '', 20);
print_heading($strquery);
-
+
print_simple_box_start('center', '', '', 20);
-
+
//this table is only for admins, shows index directory size and location
if (isadmin()) {
$admin_table->tablealign = "center";
$admin_table->cellpadding = 5;
$admin_table->cellspacing = 0;
$admin_table->width = '500';
-
+
$admin_table->data[] = array('<strong>Data directory</strong>', '<em><strong>'.$indexinfo->path.'</strong></em>');
$admin_table->data[] = array('Files in index directory', $indexinfo->filecount);
$admin_table->data[] = array('Total size', $indexinfo->size);
-
+
if ($indexinfo->time > 0) {
$admin_table->data[] = array('Created on', date('r', $indexinfo->time));
} else {
$admin_table->data[] = array('Created on', '-');
} //else
-
+
if (!$indexinfo->valid($errors)) {
$admin_table->data[] = array('<strong>Errors</strong>', ' ');
-
+
foreach ($errors as $key=>$value) {
$admin_table->data[] = array($key.' ... ', $value);
} //foreach
$admin_table->data[] = array('Check DB', 'Check your database for any problems.');
} //if
- $admin_table->data[] = array('Run indexer test', '<a href=\'tests/index.php\'>tests/index.php</a>');
- $admin_table->data[] = array('Run indexer', '<a href=\'indexersplash.php\'>indexersplash.php</a>');
+ $admin_table->data[] = array('Run indexer test', '<a href=\'tests/index.php\'>tests/index.php</a>');
+ $admin_table->data[] = array('Run indexer', '<a href=\'indexersplash.php\'>indexersplash.php</a>');
} //if
} //if
-
+
//this is the standard summary table for normal users, shows document counts
$table->tablealign = "center";
$table->align = array ("right", "left");
$table->cellpadding = 5;
$table->cellspacing = 0;
$table->width = '500';
-
+
$table->data[] = array('<strong>Database</strong>', '<em><strong>search_documents<strong></em>');
-
+
//add extra fields if we're admin
if (isadmin()) {
//don't want to confuse users if the two totals don't match (hint: they should)
$table->data[] = array('Documents in index', $indexinfo->indexcount);
-
+
//*cough* they should match if deletions were actually removed from the index,
//as it turns out, they're only marked as deleted and not returned in search results
$table->data[] = array('Deletions in index', (int)$indexinfo->indexcount - (int)$indexinfo->dbcount);
} //if
-
+
$table->data[] = array('Documents in database', $indexinfo->dbcount);
-
+
foreach($indexinfo->types as $key => $value) {
$table->data[] = array("'$key' documents", $value);
- } //foreach
+ } //foreach
if (isadmin()) {
print_table($admin_table);
print_spacer(20);
} //if
-
+
print_table($table);
-
+
print_simple_box_end();
print_simple_box_end();
print_footer();
* is expected to exist, along with the db schema files and the search data
* directory.
* */
-
+
@set_time_limit(0);
@ob_implicit_flush(true);
- @ob_end_flush();
+ @ob_end_flush();
require_once('../../config.php');
- require_once("$CFG->dirroot/search/lib.php");
+ require_once("$CFG->dirroot/search/lib.php");
require_login();
if (!isadmin()) {
error("You need to be an admin user to use this page.", "$CFG->wwwroot/login/index.php");
} //if
-
+
mtrace('<pre>Server Time: '.date('r',time()));
mtrace("Testing global search capabilities:\n");
-
+
$phpversion = phpversion();
-
- if (!search_check_php5()) {
+
+ if (!search_check_php5()) {
mtrace("ERROR: PHP 5.0.0 or later required (currently using version $phpversion).");
exit(0);
} else {
//fix paths for testing
set_include_path(get_include_path().":../");
require_once("$CFG->dirroot/search/Zend/Search/Lucene.php");
-
+
mtrace("Checking activity modules:\n");
-
+
//the presence of the required search functions -
// * mod_iterator
// * mod_get_content_for_index
//are the sole basis for including a module in the index at the moment.
-
+
if ($mods = get_records_select('modules')) {
$mods = array_merge($mods, search_get_additional_modules());
-
+
foreach ($mods as $mod) {
- $class_file = $CFG->dirroot.'/search/documents/'.$mod->name.'_document.php';
-
+ $class_file = $CFG->dirroot.'/search/documents/'.$mod->name.'_document.php';
+
if (file_exists($class_file)) {
include_once($class_file);
-
+
if (!defined('SEARCH_TYPE_'.strtoupper($mod->name))) {
mtrace("ERROR: Constant 'SEARCH_TYPE_".strtoupper($mod->name)."' is not defined in /search/lib.php");
continue;
} //if
-
+
$iter_function = $mod->name.'_iterator';
$index_function = $mod->name.'_get_content_for_index';
-
+
if (function_exists($index_function) && function_exists($iter_function)) {
if (is_array($iter_function())) {
$documents = $index_function(array_pop($iter_function()));
-
+
if (is_array($documents)) {
mtrace("Success: '$mod->name' module seems to be ready for indexing.");
} else {
} //else
} //foreach
} //if
-
+
//finished modules
mtrace("\nFinished checking activity modules.");
-
+
//now blocks...
//
-
+
mtrace("<br><a href='../index.php'>Back to query page</a> or <a href='../indexersplash.php'>Start indexing</a>.");
mtrace('</pre>');
require_once('../config.php');
require_once("$CFG->dirroot/search/lib.php");
-
+
require_login();
if (!isadmin()) {
error("You need to be an admin user to use this page.", "$CFG->wwwroot/login/index.php");
} //if
-
+
//check for php5 (lib.php)
if (!search_check_php5()) {
$phpversion = phpversion();
mtrace("Sorry, global search requires PHP 5.0.0 or later (currently using version $phpversion)");
exit(0);
- } //if
-
- require_once("$CFG->dirroot/search/indexlib.php");
-
+ } //if
+
+ require_once("$CFG->dirroot/search/indexlib.php");
+
$index = new Zend_Search_Lucene(SEARCH_INDEX_PATH);
$dbcontrol = new IndexDBControl();
$update_count = 0;
-
+
$indexdate = $CFG->search_indexer_run_date;
- mtrace("<pre>Starting index update (updates)...\n");
-
+ mtrace("<pre>Starting index update (updates)...\n");
+
if ($mods = get_records_select('modules')) {
$mods = array_merge($mods, search_get_additional_modules());
-
+
foreach ($mods as $mod) {
$class_file = $CFG->dirroot.'/search/documents/'.$mod->name.'_document.php';
$get_document_function = $mod->name.'_single_document';
$delete_function = $mod->name.'_delete';
$db_names_function = $mod->name.'_db_names';
- $updates = array();
-
+ $updates = array();
+
if (file_exists($class_file)) {
require_once($class_file);
-
+
if (function_exists($delete_function) and function_exists($db_names_function) and function_exists($get_document_function)) {
mtrace("Checking $mod->name module for updates.");
$values = $db_names_function();
-
+
//TODO: check 'in' syntax with other RDBMS' (add and update.php as well)
$sql = "select id, ".$values[0]." as docid from ".$values[1].
" where ".$values[3]." > $indexdate".
" and id in (select docid from ".SEARCH_DATABASE_TABLE.")";
-
- $records = get_records_sql($sql);
-
- if (is_array($records)) {
+
+ $records = get_records_sql($sql);
+
+ if (is_array($records)) {
foreach($records as $record) {
$updates[] = $delete_function($record->docid);
} //foreach
- } //if
-
+ } //if
+
foreach ($updates as $update) {
++$update_count;
-
- //delete old document
- $doc = $index->find("+docid:$update +doctype:$mod->name");
-
+
+ //delete old document
+ $doc = $index->find("+docid:$update +doctype:$mod->name");
+
//get the record, should only be one
- foreach ($doc as $thisdoc) {
+ foreach ($doc as $thisdoc) {
mtrace(" Delete: $thisdoc->title (database id = $thisdoc->dbid, index id = $thisdoc->id, moodle instance id = $thisdoc->docid)");
-
+
$dbcontrol->delDocument($thisdoc);
- $index->delete($thisdoc->id);
+ $index->delete($thisdoc->id);
} //foreach
-
+
//add new modified document back into index
$add = $get_document_function($update);
-
+
//object to insert into db
- $dbid = $dbcontrol->addDocument($add);
-
+ $dbid = $dbcontrol->addDocument($add);
+
//synchronise db with index
- $add->addField(Zend_Search_Lucene_Field::Keyword('dbid', $dbid));
-
+ $add->addField(Zend_Search_Lucene_Field::Keyword('dbid', $dbid));
+
mtrace(" Add: $add->title (database id = $add->dbid, moodle instance id = $add->docid)");
-
- $index->addDocument($add);
+
+ $index->addDocument($add);
} //foreach
-
+
mtrace("Finished $mod->name.\n");
- } //if
+ } //if
} //if
} //foreach
} //if
-
+
//commit changes
$index->commit();
-
+
//update index date
set_config("search_indexer_run_date", time());
- mtrace("Finished $update_count updates.</pre>");
+ mtrace("Finished $update_count updates.</pre>");
?>
\ No newline at end of file