MDL-11561 - remove unused variable merged from MOODLE_19_STABLE
[moodle.git] / lib / adminlib.php
CommitLineData
a4e10845 1<?php
88a7228a 2
3/**
4 * adminlib.php - Contains functions that only administrators will ever need to use
5 *
a4e10845 6 * @author Martin Dougiamas and many others
88a7228a 7 * @version $Id$
8 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
9 * @package moodlecore
10 */
11
8ddcdd86 12function upgrade_main_savepoint($result, $version) {
13 global $CFG;
14
15 if ($result) {
16 if ($CFG->version >= $version) {
17 // something really wrong is going on in main upgrade script
220a90c5 18 error("Upgrade savepoint: Can not upgrade main version from $CFG->version to $version.");
8ddcdd86 19 }
20 set_config('version', $version);
21 } else {
22 notify ("Upgrade savepoint: Error during main upgrade to version $version");
23 }
24}
25
26function upgrade_mod_savepoint($result, $version, $type) {
27 //TODO
28}
29
30function upgrade_plugin_savepoint($result, $version, $type, $dir) {
31 //TODO
32}
33
34function upgrade_backup_savepoint($result, $version) {
35 //TODO
36}
37
38function upgrade_blocks_savepoint($result, $version, $type) {
39 //TODO
40}
41
88a7228a 42/**
ead29342 43 * Upgrade plugins
88a7228a 44 *
45 * @uses $db
46 * @uses $CFG
ead29342 47 * @param string $type The type of plugins that should be updated (e.g. 'enrol', 'qtype')
48 * @param string $dir The directory where the plugins are located (e.g. 'question/questiontypes')
49 * @param string $return The url to prompt the user to continue to
eef868d1 50 */
ead29342 51function upgrade_plugins($type, $dir, $return) {
e69ef14b 52 global $CFG, $db;
173cc1c3 53
15999a93 54/// Let's know if the header has been printed, so the funcion is being called embedded in an outer page
55 $embedded = defined('HEADER_PRINTED');
56
bb7053f3 57 $plugs = get_list_of_plugins($dir);
583fad99 58 $updated_plugins = false;
59 $strpluginsetup = get_string('pluginsetup');
60
ead29342 61 foreach ($plugs as $plug) {
173cc1c3 62
ead29342 63 $fullplug = $CFG->dirroot .'/'.$dir.'/'. $plug;
173cc1c3 64
ead29342 65 unset($plugin);
173cc1c3 66
bbbf2d40 67 if (is_readable($fullplug .'/version.php')) {
ead29342 68 include_once($fullplug .'/version.php'); // defines $plugin with version etc
173cc1c3 69 } else {
70 continue; // Nothing to do.
71 }
72
e79a09a2 73 $oldupgrade = false;
74 $newupgrade = false;
7c006e34 75 if (is_readable($fullplug . '/db/'. $CFG->dbtype . '.php')) {
76 include_once($fullplug . '/db/'. $CFG->dbtype . '.php'); // defines old upgrading function
e79a09a2 77 $oldupgrade = true;
78 }
db8bd7a6 79 if (is_readable($fullplug . '/db/upgrade.php')) {
7c006e34 80 include_once($fullplug . '/db/upgrade.php'); // defines new upgrading function
e79a09a2 81 $newupgrade = true;
82 }
83
ead29342 84 if (!isset($plugin)) {
173cc1c3 85 continue;
86 }
87
ead29342 88 if (!empty($plugin->requires)) {
89 if ($plugin->requires > $CFG->version) {
acdd790f 90 $info = new object();
ead29342 91 $info->pluginname = $plug;
92 $info->pluginversion = $plugin->version;
173cc1c3 93 $info->currentmoodle = $CFG->version;
ead29342 94 $info->requiremoodle = $plugin->requires;
15999a93 95 if (!$updated_plugins && !$embedded) {
0be6f678 96 print_header($strpluginsetup, $strpluginsetup,
97 build_navigation(array(array('name' => $strpluginsetup, 'link' => null, 'type' => 'misc'))), '',
371a32e3 98 upgrade_get_javascript(), false, '&nbsp;', '&nbsp;');
583fad99 99 }
100 upgrade_log_start();
ead29342 101 notify(get_string('pluginrequirementsnotmet', 'error', $info));
583fad99 102 $updated_plugins = true;
173cc1c3 103 continue;
104 }
105 }
106
ead29342 107 $plugin->name = $plug; // The name MUST match the directory
173cc1c3 108
ead29342 109 $pluginversion = $type.'_'.$plug.'_version';
173cc1c3 110
ead29342 111 if (!isset($CFG->$pluginversion)) {
112 set_config($pluginversion, 0);
173cc1c3 113 }
eef868d1 114
ead29342 115 if ($CFG->$pluginversion == $plugin->version) {
173cc1c3 116 // do nothing
ead29342 117 } else if ($CFG->$pluginversion < $plugin->version) {
15999a93 118 if (!$updated_plugins && !$embedded) {
0be6f678 119 print_header($strpluginsetup, $strpluginsetup,
120 build_navigation(array(array('name' => $strpluginsetup, 'link' => null, 'type' => 'misc'))), '',
371a32e3 121 upgrade_get_javascript(), false, '&nbsp;', '&nbsp;');
173cc1c3 122 }
e79a09a2 123 $updated_plugins = true;
583fad99 124 upgrade_log_start();
05b42119 125 print_heading($dir.'/'. $plugin->name .' plugin needs upgrading');
e79a09a2 126 $db->debug = true;
127 @set_time_limit(0); // To allow slow databases to complete the long SQL
128
d87a9d73 129 if ($CFG->$pluginversion == 0) { // It's a new install of this plugin
e79a09a2 130 /// Both old .sql files and new install.xml are supported
131 /// but we priorize install.xml (XMLDB) if present
132 $status = false;
db8bd7a6 133 if (file_exists($fullplug . '/db/install.xml')) {
450cf307 134 $status = install_from_xmldb_file($fullplug . '/db/install.xml'); //New method
e79a09a2 135 } else if (file_exists($fullplug .'/db/'. $CFG->dbtype .'.sql')) {
136 $status = modify_database($fullplug .'/db/'. $CFG->dbtype .'.sql'); //Old method
eef868d1 137 } else {
7c006e34 138 $status = true;
d87a9d73 139 }
e79a09a2 140
141 $db->debug = false;
eef868d1 142 /// Continue with the instalation, roles and other stuff
e79a09a2 143 if ($status) {
3f59a54e 144 /// OK so far, now update the plugins record
e79a09a2 145 set_config($pluginversion, $plugin->version);
3f59a54e 146
147 /// Install capabilities
ae628043 148 if (!update_capabilities($type.'/'.$plug)) {
3f59a54e 149 error('Could not set up the capabilities for '.$plugin->name.'!');
e79a09a2 150 }
3f59a54e 151 /// Install events
0856223c 152 events_update_definition($type.'/'.$plug);
3f59a54e 153
154 /// Run local install function if there is one
155 if (is_readable($fullplug .'/lib.php')) {
9ba38673 156 include_once($fullplug .'/lib.php');
3f59a54e 157 $installfunction = $plugin->name.'_install';
158 if (function_exists($installfunction)) {
159 if (! $installfunction() ) {
160 notify('Encountered a problem running install function for '.$module->name.'!');
161 }
162 }
163 }
9ba38673 164
e79a09a2 165 notify(get_string('modulesuccess', '', $plugin->name), 'notifysuccess');
166 } else {
167 notify('Installing '. $plugin->name .' FAILED!');
168 }
d87a9d73 169 } else { // Upgrade existing install
e79a09a2 170 /// Run de old and new upgrade functions for the module
171 $oldupgrade_function = $type.'_'.$plugin->name .'_upgrade';
172 $newupgrade_function = 'xmldb_' . $type.'_'.$plugin->name .'_upgrade';
173
174 /// First, the old function if exists
175 $oldupgrade_status = true;
176 if ($oldupgrade && function_exists($oldupgrade_function)) {
177 $db->debug = true;
178 $oldupgrade_status = $oldupgrade_function($CFG->$pluginversion);
179 } else if ($oldupgrade) {
180 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
181 $fullplug . '/db/' . $CFG->dbtype . '.php');
182 }
183
184 /// Then, the new function if exists and the old one was ok
185 $newupgrade_status = true;
186 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
187 $db->debug = true;
188 $newupgrade_status = $newupgrade_function($CFG->$pluginversion);
189 } else if ($newupgrade) {
190 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
191 $fullplug . '/db/upgrade.php');
192 }
193
194 $db->debug=false;
195 /// Now analyze upgrade results
196 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
197 // OK so far, now update the plugins record
198 set_config($pluginversion, $plugin->version);
ae628043 199 if (!update_capabilities($type.'/'.$plug)) {
e79a09a2 200 error('Could not update '.$plugin->name.' capabilities!');
d87a9d73 201 }
0856223c 202 events_update_definition($type.'/'.$plug);
e79a09a2 203 notify(get_string('modulesuccess', '', $plugin->name), 'notifysuccess');
204 } else {
205 notify('Upgrading '. $plugin->name .' from '. $CFG->$pluginversion .' to '. $plugin->version .' FAILED!');
173cc1c3 206 }
207 }
d87a9d73 208 echo '<hr />';
173cc1c3 209 } else {
583fad99 210 upgrade_log_start();
ead29342 211 error('Version mismatch: '. $plugin->name .' can\'t downgrade '. $CFG->$pluginversion .' -> '. $plugin->version .' !');
173cc1c3 212 }
213 }
214
583fad99 215 upgrade_log_finish();
216
15999a93 217 if ($updated_plugins && !$embedded) {
173cc1c3 218 print_continue($return);
acdd790f 219 print_footer('none');
173cc1c3 220 die;
221 }
222}
223
88a7228a 224/**
225 * Find and check all modules and load them up or upgrade them if necessary
226 *
227 * @uses $db
228 * @uses $CFG
229 * @param string $return The url to prompt the user to continue to
230 * @todo Finish documenting this function
eef868d1 231 */
173cc1c3 232function upgrade_activity_modules($return) {
173cc1c3 233
e69ef14b 234 global $CFG, $db;
173cc1c3 235
88a7228a 236 if (!$mods = get_list_of_plugins('mod') ) {
237 error('No modules installed!');
173cc1c3 238 }
239
583fad99 240 $updated_modules = false;
241 $strmodulesetup = get_string('modulesetup');
242
173cc1c3 243 foreach ($mods as $mod) {
244
88a7228a 245 if ($mod == 'NEWMODULE') { // Someone has unzipped the template, ignore it
173cc1c3 246 continue;
247 }
248
88a7228a 249 $fullmod = $CFG->dirroot .'/mod/'. $mod;
173cc1c3 250
251 unset($module);
252
88a7228a 253 if ( is_readable($fullmod .'/version.php')) {
254 include_once($fullmod .'/version.php'); // defines $module with version etc
173cc1c3 255 } else {
88a7228a 256 notify('Module '. $mod .': '. $fullmod .'/version.php was not readable');
173cc1c3 257 continue;
258 }
259
d6eb06b6 260 $oldupgrade = false;
261 $newupgrade = false;
7c006e34 262 if ( is_readable($fullmod .'/db/' . $CFG->dbtype . '.php')) {
263 include_once($fullmod .'/db/' . $CFG->dbtype . '.php'); // defines old upgrading function
d6eb06b6 264 $oldupgrade = true;
265 }
db8bd7a6 266 if ( is_readable($fullmod . '/db/upgrade.php')) {
7c006e34 267 include_once($fullmod . '/db/upgrade.php'); // defines new upgrading function
d6eb06b6 268 $newupgrade = true;
173cc1c3 269 }
270
271 if (!isset($module)) {
272 continue;
273 }
274
275 if (!empty($module->requires)) {
276 if ($module->requires > $CFG->version) {
acdd790f 277 $info = new object();
173cc1c3 278 $info->modulename = $mod;
279 $info->moduleversion = $module->version;
280 $info->currentmoodle = $CFG->version;
281 $info->requiremoodle = $module->requires;
583fad99 282 if (!$updated_modules) {
0be6f678 283 print_header($strmodulesetup, $strmodulesetup,
284 build_navigation(array(array('name' => $strmodulesetup, 'link' => null, 'type' => 'misc'))), '',
371a32e3 285 upgrade_get_javascript(), false, '&nbsp;', '&nbsp;');
583fad99 286 }
287 upgrade_log_start();
173cc1c3 288 notify(get_string('modulerequirementsnotmet', 'error', $info));
583fad99 289 $updated_modules = true;
173cc1c3 290 continue;
291 }
292 }
293
294 $module->name = $mod; // The name MUST match the directory
eef868d1 295
11e4a24b 296 include_once($fullmod.'/lib.php'); // defines upgrading and/or installing functions
297
88a7228a 298 if ($currmodule = get_record('modules', 'name', $module->name)) {
173cc1c3 299 if ($currmodule->version == $module->version) {
300 // do nothing
301 } else if ($currmodule->version < $module->version) {
d6eb06b6 302 /// If versions say that we need to upgrade but no upgrade files are available, notify and continue
303 if (!$oldupgrade && !$newupgrade) {
304 notify('Upgrade files ' . $mod . ': ' . $fullmod . '/db/' . $CFG->dbtype . '.php or ' .
305 $fullmod . '/db/upgrade.php were not readable');
306 continue;
307 }
583fad99 308 if (!$updated_modules) {
0be6f678 309 print_header($strmodulesetup, $strmodulesetup,
310 build_navigation(array(array('name' => $strmodulesetup, 'link' => null, 'type' => 'misc'))), '',
371a32e3 311 upgrade_get_javascript(), false, '&nbsp;', '&nbsp;');
173cc1c3 312 }
583fad99 313 upgrade_log_start();
88a7228a 314 print_heading($module->name .' module needs upgrading');
d6eb06b6 315
316 /// Run de old and new upgrade functions for the module
317 $oldupgrade_function = $module->name . '_upgrade';
318 $newupgrade_function = 'xmldb_' . $module->name . '_upgrade';
319
320 /// First, the old function if exists
321 $oldupgrade_status = true;
322 if ($oldupgrade && function_exists($oldupgrade_function)) {
323 $db->debug = true;
324 $oldupgrade_status = $oldupgrade_function($currmodule->version, $module);
8bc9ebc4 325 if (!$oldupgrade_status) {
326 notify ('Upgrade function ' . $oldupgrade_function .
220a90c5 327 ' did not complete successfully.');
8bc9ebc4 328 }
ba05965e 329 } else if ($oldupgrade) {
d6eb06b6 330 notify ('Upgrade function ' . $oldupgrade_function . ' was not available in ' .
331 $mod . ': ' . $fullmod . '/db/' . $CFG->dbtype . '.php');
d6eb06b6 332 }
333
334 /// Then, the new function if exists and the old one was ok
335 $newupgrade_status = true;
ba05965e 336 if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) {
d6eb06b6 337 $db->debug = true;
338 $newupgrade_status = $newupgrade_function($currmodule->version, $module);
8bc9ebc4 339 } else if ($newupgrade && $oldupgrade_status) {
d6eb06b6 340 notify ('Upgrade function ' . $newupgrade_function . ' was not available in ' .
341 $mod . ': ' . $fullmod . '/db/upgrade.php');
d6eb06b6 342 }
343
e79a09a2 344 $db->debug=false;
d6eb06b6 345 /// Now analyze upgrade results
668896e5 346 if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed
d6eb06b6 347 // OK so far, now update the modules record
348 $module->id = $currmodule->id;
349 if (! update_record('modules', $module)) {
350 error('Could not update '. $module->name .' record in modules table!');
173cc1c3 351 }
d6eb06b6 352 remove_dir($CFG->dataroot . '/cache', true); // flush cache
353 notify(get_string('modulesuccess', '', $module->name), 'notifysuccess');
354 echo '<hr />';
355 } else {
d6eb06b6 356 notify('Upgrading '. $module->name .' from '. $currmodule->version .' to '. $module->version .' FAILED!');
173cc1c3 357 }
bbbf2d40 358
d6eb06b6 359 /// Update the capabilities table?
bbbf2d40 360 if (!update_capabilities('mod/'.$module->name)) {
361 error('Could not update '.$module->name.' capabilities!');
362 }
0856223c 363 events_update_definition('mod/'.$module->name);
bbbf2d40 364
173cc1c3 365 $updated_modules = true;
eef868d1 366
173cc1c3 367 } else {
583fad99 368 upgrade_log_start();
88a7228a 369 error('Version mismatch: '. $module->name .' can\'t downgrade '. $currmodule->version .' -> '. $module->version .' !');
173cc1c3 370 }
eef868d1 371
173cc1c3 372 } else { // module not installed yet, so install it
583fad99 373 if (!$updated_modules) {
0be6f678 374 print_header($strmodulesetup, $strmodulesetup,
375 build_navigation(array(array('name' => $strmodulesetup, 'link' => null, 'type' => 'misc'))), '',
371a32e3 376 upgrade_get_javascript(), false, '&nbsp;', '&nbsp;');
173cc1c3 377 }
583fad99 378 upgrade_log_start();
173cc1c3 379 print_heading($module->name);
380 $updated_modules = true;
381 $db->debug = true;
382 @set_time_limit(0); // To allow slow databases to complete the long SQL
d6eb06b6 383
384 /// Both old .sql files and new install.xml are supported
385 /// but we priorize install.xml (XMLDB) if present
db8bd7a6 386 if (file_exists($fullmod . '/db/install.xml')) {
d6eb06b6 387 $status = install_from_xmldb_file($fullmod . '/db/install.xml'); //New method
388 } else {
389 $status = modify_database($fullmod .'/db/'. $CFG->dbtype .'.sql'); //Old method
390 }
391
e79a09a2 392 $db->debug = false;
11e4a24b 393
394 /// Continue with the installation, roles and other stuff
d6eb06b6 395 if ($status) {
88a7228a 396 if ($module->id = insert_record('modules', $module)) {
11e4a24b 397
9ba38673 398 /// Capabilities
bbbf2d40 399 if (!update_capabilities('mod/'.$module->name)) {
400 error('Could not set up the capabilities for '.$module->name.'!');
401 }
9ba38673 402
11e4a24b 403 /// Events
0856223c 404 events_update_definition('mod/'.$module->name);
11e4a24b 405
406 /// Run local install function if there is one
407 $installfunction = $module->name.'_install';
408 if (function_exists($installfunction)) {
409 if (! $installfunction() ) {
410 notify('Encountered a problem running install function for '.$module->name.'!');
411 }
412 }
413
a8f68426 414 notify(get_string('modulesuccess', '', $module->name), 'notifysuccess');
88a7228a 415 echo '<hr />';
173cc1c3 416 } else {
88a7228a 417 error($module->name .' module could not be added to the module list!');
173cc1c3 418 }
eef868d1 419 } else {
88a7228a 420 error($module->name .' tables could NOT be set up successfully!');
173cc1c3 421 }
422 }
e5bd4e58 423
424 /// Check submodules of this module if necessary
425
e5bd4e58 426 $submoduleupgrade = $module->name.'_upgrade_submodules';
427 if (function_exists($submoduleupgrade)) {
428 $submoduleupgrade();
429 }
430
431
432 /// Run any defaults or final code that is necessary for this module
433
a5c0990e 434 if ( is_readable($fullmod .'/defaults.php')) {
435 // Insert default values for any important configuration variables
9e6e7502 436 unset($defaults);
220a90c5 437 include($fullmod .'/defaults.php'); // include here means execute, not library include
f9a2e515 438 if (!empty($defaults)) {
439 foreach ($defaults as $name => $value) {
440 if (!isset($CFG->$name)) {
441 set_config($name, $value);
442 }
a5c0990e 443 }
444 }
445 }
173cc1c3 446 }
447
583fad99 448 upgrade_log_finish(); // finish logging if started
449
450 if ($updated_modules) {
173cc1c3 451 print_continue($return);
acdd790f 452 print_footer('none');
173cc1c3 453 die;
454 }
455}
456
eef868d1 457/**
f3221af9 458 * This function will return FALSE if the lock fails to be set (ie, if it's already locked)
80be7ee3 459 *
460 * @param string $name ?
461 * @param bool $value ?
462 * @param int $staleafter ?
463 * @param bool $clobberstale ?
464 * @todo Finish documenting this function
f3221af9 465 */
466function set_cron_lock($name,$value=true,$staleafter=7200,$clobberstale=false) {
467
468 if (empty($name)) {
469 mtrace("Tried to get a cron lock for a null fieldname");
470 return false;
471 }
472
473 if (empty($value)) {
474 set_config($name,0);
475 return true;
476 }
477
478 if ($config = get_record('config','name',$name)) {
479 if (empty($config->value)) {
480 set_config($name,time());
481 } else {
482 // check for stale.
483 if ((time() - $staleafter) > $config->value) {
484 mtrace("STALE LOCKFILE FOR $name - was $config->value");
485 if (!empty($clobberstale)) {
486 set_config($name,time());
487 return true;
488 }
489 } else {
490 return false; // was not stale - ie, we're ok to still be running.
491 }
492 }
493 }
494 else {
495 set_config($name,time());
496 }
497 return true;
498}
a597f8a8 499
fb06b255 500function print_progress($done, $total, $updatetime=5, $sleeptime=1, $donetext='') {
a597f8a8 501 static $starttime;
502 static $lasttime;
503
26ea4888 504 if ($total < 2) { // No need to show anything
505 return;
506 }
507
a597f8a8 508 if (empty($starttime)) {
509 $starttime = $lasttime = time();
510 $lasttime = $starttime - $updatetime;
511 echo '<table width="500" cellpadding="0" cellspacing="0" align="center"><tr><td width="500">';
72da5046 512 echo '<div id="bar'.$total.'" style="border-style:solid;border-width:1px;width:500px;height:50px;">';
513 echo '<div id="slider'.$total.'" style="border-style:solid;border-width:1px;height:48px;width:10px;background-color:green;"></div>';
a597f8a8 514 echo '</div>';
72da5046 515 echo '<div id="text'.$total.'" align="center" style="width:500px;"></div>';
a597f8a8 516 echo '</td></tr></table>';
517 echo '</div>';
518 }
519
a597f8a8 520 $now = time();
521
522 if ($done && (($now - $lasttime) >= $updatetime)) {
523 $elapsedtime = $now - $starttime;
524 $projectedtime = (int)(((float)$total / (float)$done) * $elapsedtime) - $elapsedtime;
76317c73 525 $percentage = round((float)$done / (float)$total, 2);
a597f8a8 526 $width = (int)(500 * $percentage);
527
fb06b255 528 if ($projectedtime > 10) {
529 $projectedtext = ' Ending: '.format_time($projectedtime);
530 } else {
531 $projectedtext = '';
532 }
533
a597f8a8 534 echo '<script>';
aae37b63 535 echo 'document.getElementById("text'.$total.'").innerHTML = "'.addslashes($donetext).' ('.$done.'/'.$total.') '.$projectedtext.'";'."\n";
536 echo 'document.getElementById("slider'.$total.'").style.width = \''.$width.'px\';'."\n";
a597f8a8 537 echo '</script>';
538
539 $lasttime = $now;
540 sleep($sleeptime);
541 }
542}
583fad99 543
371a32e3 544function upgrade_get_javascript() {
545 global $CFG;
546
547 if (!empty($_SESSION['installautopilot'])) {
548 $linktoscrolltoerrors = '<script type="text/javascript">var installautopilot = true;</script>'."\n";
549 } else {
550 $linktoscrolltoerrors = '<script type="text/javascript">var installautopilot = false;</script>'."\n";
551 }
552 $linktoscrolltoerrors .= '<script type="text/javascript" src="' . $CFG->wwwroot . '/lib/scroll_to_errors.js"></script>';
553
554 return $linktoscrolltoerrors;
555}
ad6226fb 556
557function create_admin_user() {
558 global $CFG, $USER;
559
560 if (empty($CFG->rolesactive)) { // No admin user yet.
561
562 $user = new object();
563 $user->auth = 'manual';
564 $user->firstname = get_string('admin');
565 $user->lastname = get_string('user');
566 $user->username = 'admin';
567 $user->password = hash_internal_user_password('admin');
568 $user->email = 'root@localhost';
569 $user->confirmed = 1;
570 $user->mnethostid = $CFG->mnet_localhost_id;
571 $user->lang = $CFG->lang;
572 $user->maildisplay = 1;
573 $user->timemodified = time();
574
575 if (!$user->id = insert_record('user', $user)) {
576 error('SERIOUS ERROR: Could not create admin user record !!!');
577 }
578
579 if (!$user = get_record('user', 'id', $user->id)) { // Double check.
580 error('User ID was incorrect (can\'t find it)');
581 }
582
583 // Assign the default admin roles to the new user.
584 if (!$adminroles = get_roles_with_capability('moodle/legacy:admin', CAP_ALLOW)) {
585 error('No admin role could be found');
586 }
84c8ede0 587 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
ad6226fb 588 foreach ($adminroles as $adminrole) {
589 role_assign($adminrole->id, $user->id, 0, $sitecontext->id);
590 }
591
592 set_config('rolesactive', 1);
593
594 // Log the user in.
595 $USER = get_complete_user_data('username', 'admin');
596 $USER->newadminuser = 1;
597 load_all_capabilities();
598
599 redirect("$CFG->wwwroot/user/editadvanced.php?id=$user->id"); // Edit thyself
600 } else {
601 error('Can not create admin!');
602 }
603}
604
583fad99 605////////////////////////////////////////////////
606/// upgrade logging functions
607////////////////////////////////////////////////
608
609$upgradeloghandle = false;
26c91c73 610$upgradelogbuffer = '';
611// I did not find out how to use static variable in callback function,
612// the problem was that I could not flush the static buffer :-(
613global $upgradeloghandle, $upgradelogbuffer;
583fad99 614
615/**
616 * Check if upgrade is already running.
617 *
618 * If anything goes wrong due to missing call to upgrade_log_finish()
619 * just restart the browser.
620 *
621 * @param string warning message indicating upgrade is already running
622 * @param int page reload timeout
623 */
624function upgrade_check_running($message, $timeout) {
625 if (!empty($_SESSION['upgraderunning'])) {
626 print_header();
627 redirect(me(), $message, $timeout);
628 }
629}
630
631/**
632 * Start logging of output into file (if not disabled) and
633 * prevent aborting and concurrent execution of upgrade script.
634 *
635 * Please note that you can not write into session variables after calling this function!
636 *
637 * This function may be called repeatedly.
638 */
639function upgrade_log_start() {
426a369b 640 global $CFG, $upgradeloghandle;
583fad99 641
642 if (!empty($_SESSION['upgraderunning'])) {
643 return; // logging already started
644 }
645
646 @ignore_user_abort(true); // ignore if user stops or otherwise aborts page loading
647 $_SESSION['upgraderunning'] = 1; // set upgrade indicator
426a369b 648 if (empty($CFG->dbsessions)) { // workaround for bug in adodb, db session can not be restarted
649 session_write_close(); // from now on user can reload page - will be displayed warning
650 }
583fad99 651 make_upload_directory('upgradelogs');
652 ob_start('upgrade_log_callback', 2); // function for logging to disk; flush each line of text ASAP
dedb2304 653 register_shutdown_function('upgrade_log_finish'); // in case somebody forgets to stop logging
583fad99 654}
655
656/**
657 * Terminate logging of output, flush all data, allow script aborting
658 * and reopen session for writing. Function error() does terminate the logging too.
659 *
660 * Please make sure that each upgrade_log_start() is properly terminated by
661 * this function or error().
662 *
663 * This function may be called repeatedly.
664 */
665function upgrade_log_finish() {
426a369b 666 global $CFG, $upgradeloghandle, $upgradelogbuffer;
583fad99 667
668 if (empty($_SESSION['upgraderunning'])) {
669 return; // logging already terminated
670 }
671
672 @ob_end_flush();
26c91c73 673 if ($upgradelogbuffer !== '') {
674 @fwrite($upgradeloghandle, $upgradelogbuffer);
40896537 675 $upgradelogbuffer = '';
26c91c73 676 }
677 if ($upgradeloghandle and ($upgradeloghandle !== 'error')) {
678 @fclose($upgradeloghandle);
40896537 679 $upgradeloghandle = false;
26c91c73 680 }
426a369b 681 if (empty($CFG->dbsessions)) {
682 @session_start(); // ignore header errors, we only need to reopen session
683 }
583fad99 684 $_SESSION['upgraderunning'] = 0; // clear upgrade indicator
685 if (connection_aborted()) {
686 die;
687 }
688 @ignore_user_abort(false);
689}
690
691/**
692 * Callback function for logging into files. Not more than one file is created per minute,
693 * upgrade session (terminated by upgrade_log_finish()) is always stored in one file.
694 *
695 * This function must not output any characters or throw warnigns and errors!
696 */
697function upgrade_log_callback($string) {
26c91c73 698 global $CFG, $upgradeloghandle, $upgradelogbuffer;
583fad99 699
700 if (empty($CFG->disableupgradelogging) and ($string != '') and ($upgradeloghandle !== 'error')) {
701 if ($upgradeloghandle or ($upgradeloghandle = @fopen($CFG->dataroot.'/upgradelogs/upg_'.date('Ymd-Hi').'.html', 'a'))) {
26c91c73 702 $upgradelogbuffer .= $string;
703 if (strlen($upgradelogbuffer) > 2048) { // 2kB write buffer
704 @fwrite($upgradeloghandle, $upgradelogbuffer);
705 $upgradelogbuffer = '';
706 }
583fad99 707 } else {
708 $upgradeloghandle = 'error';
709 }
710 }
711 return $string;
712}
713
57e35f32 714/**
715 * Try to verify that dataroot is not accessible from web.
716 * It is not 100% correct but might help to reduce number of vulnerable sites.
717 *
718 * Protection from httpd.conf and .htaccess is not detected properly.
719 */
720function is_dataroot_insecure() {
721 global $CFG;
722
723 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
724
725 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
726 $rp = strrev(trim($rp, '/'));
727 $rp = explode('/', $rp);
728 foreach($rp as $r) {
729 if (strpos($siteroot, '/'.$r.'/') === 0) {
730 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
731 } else {
732 break; // probably alias root
733 }
734 }
735
736 $siteroot = strrev($siteroot);
737 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
738
739 if (strpos($dataroot, $siteroot) === 0) {
740 return true;
741 }
742 return false;
743}
6e4dc10f 744
745/// =============================================================================================================
746/// administration tree classes and functions
747
748
749// n.b. documentation is still in progress for this code
750
751/// INTRODUCTION
752
753/// This file performs the following tasks:
754/// -it defines the necessary objects and interfaces to build the Moodle
755/// admin hierarchy
eef868d1 756/// -it defines the admin_externalpage_setup(), admin_externalpage_print_header(),
6e4dc10f 757/// and admin_externalpage_print_footer() functions used on admin pages
758
759/// ADMIN_SETTING OBJECTS
760
eef868d1 761/// Moodle settings are represented by objects that inherit from the admin_setting
6e4dc10f 762/// class. These objects encapsulate how to read a setting, how to write a new value
763/// to a setting, and how to appropriately display the HTML to modify the setting.
764
765/// ADMIN_SETTINGPAGE OBJECTS
766
767/// The admin_setting objects are then grouped into admin_settingpages. The latter
768/// appear in the Moodle admin tree block. All interaction with admin_settingpage
769/// objects is handled by the admin/settings.php file.
770
771/// ADMIN_EXTERNALPAGE OBJECTS
772
773/// There are some settings in Moodle that are too complex to (efficiently) handle
774/// with admin_settingpages. (Consider, for example, user management and displaying
775/// lists of users.) In this case, we use the admin_externalpage object. This object
776/// places a link to an external PHP file in the admin tree block.
777
778/// If you're using an admin_externalpage object for some settings, you can take
779/// advantage of the admin_externalpage_* functions. For example, suppose you wanted
780/// to add a foo.php file into admin. First off, you add the following line to
781/// admin/settings/first.php (at the end of the file) or to some other file in
782/// admin/settings:
783
eef868d1 784/// $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
6e4dc10f 785/// $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
786
787/// Next, in foo.php, your file structure would resemble the following:
788
789/// require_once('.../config.php');
790/// require_once($CFG->libdir.'/adminlib.php');
1ae083e4 791/// admin_externalpage_setup('foo');
6e4dc10f 792/// // functionality like processing form submissions goes here
1ae083e4 793/// admin_externalpage_print_header();
6e4dc10f 794/// // your HTML goes here
1ae083e4 795/// admin_externalpage_print_footer();
6e4dc10f 796
797/// The admin_externalpage_setup() function call ensures the user is logged in,
798/// and makes sure that they have the proper role permission to access the page.
799
800/// The admin_externalpage_print_header() function prints the header (it figures
801/// out what category and subcategories the page is classified under) and ensures
802/// that you're using the admin pagelib (which provides the admin tree block and
803/// the admin bookmarks block).
804
805/// The admin_externalpage_print_footer() function properly closes the tables
806/// opened up by the admin_externalpage_print_header() function and prints the
807/// standard Moodle footer.
808
809/// ADMIN_CATEGORY OBJECTS
810
811/// Above and beyond all this, we have admin_category objects. These objects
812/// appear as folders in the admin tree block. They contain admin_settingpage's,
813/// admin_externalpage's, and other admin_category's.
814
815/// OTHER NOTES
816
817/// admin_settingpage's, admin_externalpage's, and admin_category's all inherit
818/// from part_of_admin_tree (a pseudointerface). This interface insists that
819/// a class has a check_access method for access permissions, a locate method
220a90c5 820/// used to find a specific node in the admin tree and find parent path.
6e4dc10f 821
822/// admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
823/// interface ensures that the class implements a recursive add function which
824/// accepts a part_of_admin_tree object and searches for the proper place to
825/// put it. parentable_part_of_admin_tree implies part_of_admin_tree.
826
827/// Please note that the $this->name field of any part_of_admin_tree must be
828/// UNIQUE throughout the ENTIRE admin tree.
829
830/// The $this->name field of an admin_setting object (which is *not* part_of_
831/// admin_tree) must be unique on the respective admin_settingpage where it is
832/// used.
833
834
6e4dc10f 835/// CLASS DEFINITIONS /////////////////////////////////////////////////////////
836
837/**
838 * Pseudointerface for anything appearing in the admin tree
839 *
840 * The pseudointerface that is implemented by anything that appears in the admin tree
841 * block. It forces inheriting classes to define a method for checking user permissions
842 * and methods for finding something in the admin tree.
843 *
844 * @author Vincenzo K. Marcovecchio
845 * @package admin
846 */
847class part_of_admin_tree {
848
849 /**
850 * Finds a named part_of_admin_tree.
851 *
852 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
853 * and not parentable_part_of_admin_tree, then this function should only check if
854 * $this->name matches $name. If it does, it should return a reference to $this,
855 * otherwise, it should return a reference to NULL.
856 *
857 * If a class inherits parentable_part_of_admin_tree, this method should be called
858 * recursively on all child objects (assuming, of course, the parent object's name
859 * doesn't match the search criterion).
860 *
861 * @param string $name The internal name of the part_of_admin_tree we're searching for.
862 * @return mixed An object reference or a NULL reference.
863 */
eef868d1 864 function &locate($name) {
865 trigger_error('Admin class does not implement method <strong>locate()</strong>', E_USER_WARNING);
866 return;
6e4dc10f 867 }
4672d955 868
869 /**
870 * Removes named part_of_admin_tree.
871 *
872 * @param string $name The internal name of the part_of_admin_tree we want to remove.
a8a66c96 873 * @return bool success.
4672d955 874 */
875 function prune($name) {
eef868d1 876 trigger_error('Admin class does not implement method <strong>prune()</strong>', E_USER_WARNING);
4672d955 877 return;
eef868d1 878 }
4672d955 879
220a90c5 880 /**
881 * Search using query
882 * @param strin query
883 * @return mixed array-object structure of found settings and pages
884 */
885 function search($query) {
886 trigger_error('Admin class does not implement method <strong>search()</strong>', E_USER_WARNING);
887 return;
888 }
889
6e4dc10f 890 /**
891 * Verifies current user's access to this part_of_admin_tree.
892 *
893 * Used to check if the current user has access to this part of the admin tree or
894 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
895 * then this method is usually just a call to has_capability() in the site context.
896 *
897 * If a class inherits parentable_part_of_admin_tree, this method should return the
898 * logical OR of the return of check_access() on all child objects.
899 *
900 * @return bool True if the user has access, false if she doesn't.
901 */
eef868d1 902 function check_access() {
903 trigger_error('Admin class does not implement method <strong>check_access()</strong>', E_USER_WARNING);
904 return;
6e4dc10f 905 }
eef868d1 906
a8a66c96 907 /**
908 * Mostly usefull for removing of some parts of the tree in admin tree block.
909 *
910 * @return True is hidden from normal list view
911 */
912 function is_hidden() {
913 trigger_error('Admin class does not implement method <strong>is_hidden()</strong>', E_USER_WARNING);
914 return;
915 }
6e4dc10f 916}
917
918/**
919 * Pseudointerface implemented by any part_of_admin_tree that has children.
920 *
921 * The pseudointerface implemented by any part_of_admin_tree that can be a parent
922 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
eef868d1 923 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
6e4dc10f 924 * include an add method for adding other part_of_admin_tree objects as children.
925 *
926 * @author Vincenzo K. Marcovecchio
927 * @package admin
928 */
929class parentable_part_of_admin_tree extends part_of_admin_tree {
eef868d1 930
6e4dc10f 931 /**
932 * Adds a part_of_admin_tree object to the admin tree.
933 *
934 * Used to add a part_of_admin_tree object to this object or a child of this
935 * object. $something should only be added if $destinationname matches
936 * $this->name. If it doesn't, add should be called on child objects that are
937 * also parentable_part_of_admin_tree's.
938 *
939 * @param string $destinationname The internal name of the new parent for $something.
940 * @param part_of_admin_tree &$something The object to be added.
941 * @return bool True on success, false on failure.
942 */
220a90c5 943 function add($destinationname, $something) {
eef868d1 944 trigger_error('Admin class does not implement method <strong>add()</strong>', E_USER_WARNING);
945 return;
6e4dc10f 946 }
eef868d1 947
6e4dc10f 948}
949
950/**
951 * The object used to represent folders (a.k.a. categories) in the admin tree block.
eef868d1 952 *
6e4dc10f 953 * Each admin_category object contains a number of part_of_admin_tree objects.
954 *
955 * @author Vincenzo K. Marcovecchio
956 * @package admin
957 */
958class admin_category extends parentable_part_of_admin_tree {
959
960 /**
961 * @var mixed An array of part_of_admin_tree objects that are this object's children
962 */
963 var $children;
eef868d1 964
6e4dc10f 965 /**
966 * @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
967 */
968 var $name;
eef868d1 969
6e4dc10f 970 /**
971 * @var string The displayed name for this category. Usually obtained through get_string()
972 */
973 var $visiblename;
eef868d1 974
a8a66c96 975 /**
976 * @var bool Should this category be hidden in admin tree block?
977 */
978 var $hidden;
979
220a90c5 980 /**
981 * paths
982 */
983 var $path;
984 var $visiblepath;
6e4dc10f 985
986 /**
987 * Constructor for an empty admin category
988 *
989 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
990 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
a8a66c96 991 * @param bool $hidden hide category in admin tree block
6e4dc10f 992 */
220a90c5 993 function admin_category($name, $visiblename, $hidden=false) {
994 $this->children = array();
995 $this->name = $name;
6e4dc10f 996 $this->visiblename = $visiblename;
220a90c5 997 $this->hidden = $hidden;
6e4dc10f 998 }
eef868d1 999
6e4dc10f 1000 /**
220a90c5 1001 * Returns a reference to the part_of_admin_tree object with internal name $name.
6e4dc10f 1002 *
220a90c5 1003 * @param string $name The internal name of the object we want.
1004 * @param bool $findpath initialize path and visiblepath arrays
1005 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
6e4dc10f 1006 */
220a90c5 1007 function &locate($name, $findpath=false) {
6e4dc10f 1008 if ($this->name == $name) {
220a90c5 1009 if ($findpath) {
1010 $this->visiblepath[] = $this->visiblename;
1011 $this->path[] = $this->name;
1012 }
1013 return $this;
6e4dc10f 1014 }
eef868d1 1015
220a90c5 1016 $return = NULL;
1017 foreach($this->children as $childid=>$unused) {
1018 if ($return =& $this->children[$childid]->locate($name, $findpath)) {
1019 break;
6e4dc10f 1020 }
1021 }
eef868d1 1022
220a90c5 1023 if (!is_null($return) and $findpath) {
1024 $return->visiblepath[] = $this->visiblename;
1025 $return->path[] = $this->name;
1026 }
eef868d1 1027
220a90c5 1028 return $return;
6e4dc10f 1029 }
1030
1031 /**
220a90c5 1032 * Search using query
1033 * @param strin query
1034 * @return mixed array-object structure of found settings and pages
6e4dc10f 1035 */
220a90c5 1036 function search($query) {
1037 $result = array();
1038 foreach ($this->children as $child) {
1039 $result = array_merge($result, $child->search($query));
6e4dc10f 1040 }
220a90c5 1041 return $result;
6e4dc10f 1042 }
1043
4672d955 1044 /**
1045 * Removes part_of_admin_tree object with internal name $name.
1046 *
1047 * @param string $name The internal name of the object we want to remove.
a8a66c96 1048 * @return bool success
4672d955 1049 */
1050 function prune($name) {
1051
1052 if ($this->name == $name) {
1053 return false; //can not remove itself
1054 }
1055
1056 foreach($this->children as $precedence => $child) {
1057 if ($child->name == $name) {
1058 // found it!
eef868d1 1059 unset($this->children[$precedence]);
4672d955 1060 return true;
1061 }
1062 if ($this->children[$precedence]->prune($name)) {
1063 return true;
1064 }
1065 }
1066 return false;
1067 }
1068
6e4dc10f 1069 /**
1070 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
1071 *
220a90c5 1072 * @param string $destinationame The internal name of the immediate parent that we want for $something.
1073 * @param mixed $something A part_of_admin_tree or setting instanceto be added.
1074 * @return bool True if successfully added, false if $something can not be added.
6e4dc10f 1075 */
220a90c5 1076 function add($parentname, $something) {
1077 $parent =& $this->locate($parentname);
1078 if (is_null($parent)) {
1079 debugging('parent does not exist!');
6e4dc10f 1080 return false;
1081 }
1082
220a90c5 1083 if (is_a($something, 'part_of_admin_tree')) {
1084 if (!is_a($parent, 'parentable_part_of_admin_tree')) {
1085 debugging('error - parts of tree can be inserted only into parentable parts');
1086 return false;
6e4dc10f 1087 }
220a90c5 1088 $parent->children[] = $something;
6e4dc10f 1089 return true;
eef868d1 1090
220a90c5 1091 } else {
1092 debugging('error - can not add this element');
1093 return false;
6e4dc10f 1094 }
eef868d1 1095
6e4dc10f 1096 }
eef868d1 1097
6e4dc10f 1098 /**
1099 * Checks if the user has access to anything in this category.
1100 *
1101 * @return bool True if the user has access to atleast one child in this category, false otherwise.
1102 */
1103 function check_access() {
6e4dc10f 1104 foreach ($this->children as $child) {
220a90c5 1105 if ($child->check_access()) {
1106 return true;
1107 }
6e4dc10f 1108 }
220a90c5 1109 return false;
6e4dc10f 1110 }
eef868d1 1111
a8a66c96 1112 /**
1113 * Is this category hidden in admin tree block?
1114 *
1115 * @return bool True if hidden
1116 */
1117 function is_hidden() {
1118 return $this->hidden;
1119 }
6e4dc10f 1120}
1121
220a90c5 1122class admin_root extends admin_category {
1123 /**
1124 * list of errors
1125 */
1126 var $errors;
1127
1128 /**
1129 * search query
1130 */
1131 var $search;
1132
1133 /**
1134 * full tree flag - true means all settings required, false onlypages required
1135 */
1136 var $fulltree;
1137
1138
1139 function admin_root() {
1140 parent::admin_category('root', get_string('administration'), false);
1141 $this->errors = array();
1142 $this->search = '';
1143 $this->fulltree = true;
1144 }
1145}
1146
6e4dc10f 1147/**
1148 * Links external PHP pages into the admin tree.
1149 *
1150 * See detailed usage example at the top of this document (adminlib.php)
1151 *
1152 * @author Vincenzo K. Marcovecchio
1153 * @package admin
1154 */
1155class admin_externalpage extends part_of_admin_tree {
1156
eef868d1 1157 /**
6e4dc10f 1158 * @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects
1159 */
1160 var $name;
eef868d1 1161
6e4dc10f 1162 /**
1163 * @var string The displayed name for this external page. Usually obtained through get_string().
1164 */
1165 var $visiblename;
eef868d1 1166
6e4dc10f 1167 /**
1168 * @var string The external URL that we should link to when someone requests this external page.
1169 */
1170 var $url;
eef868d1 1171
6e4dc10f 1172 /**
1173 * @var string The role capability/permission a user must have to access this external page.
1174 */
2ce38b70 1175 var $req_capability;
eef868d1 1176
84c8ede0 1177 /**
1178 * @var object The context in which capability/permission should be checked, default is site context.
1179 */
1180 var $context;
1181
a8a66c96 1182 /**
1183 * @var bool hidden in admin tree block.
1184 */
1185 var $hidden;
1186
220a90c5 1187 /**
1188 * visible path
1189 */
1190 var $path;
1191 var $visiblepath;
1192
6e4dc10f 1193 /**
1194 * Constructor for adding an external page into the admin tree.
1195 *
1196 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1197 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1198 * @param string $url The external URL that we should link to when someone requests this external page.
38d2d43b 1199 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
6e4dc10f 1200 */
220a90c5 1201 function admin_externalpage($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1202 $this->name = $name;
6e4dc10f 1203 $this->visiblename = $visiblename;
220a90c5 1204 $this->url = $url;
38d2d43b 1205 if (is_array($req_capability)) {
1206 $this->req_capability = $req_capability;
1207 } else {
1208 $this->req_capability = array($req_capability);
1209 }
220a90c5 1210 $this->hidden = $hidden;
84c8ede0 1211 $this->context = $context;
6e4dc10f 1212 }
eef868d1 1213
6e4dc10f 1214 /**
1215 * Returns a reference to the part_of_admin_tree object with internal name $name.
1216 *
1217 * @param string $name The internal name of the object we want.
1218 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1219 */
220a90c5 1220 function &locate($name, $findpath=false) {
1221 if ($this->name == $name) {
1222 if ($findpath) {
1223 $this->visiblepath = array($this->visiblename);
1224 $this->path = array($this->name);
1225 }
1226 return $this;
1227 } else {
1228 $return = NULL;
1229 return $return;
1230 }
6e4dc10f 1231 }
4672d955 1232
1233 function prune($name) {
1234 return false;
1235 }
1236
220a90c5 1237 /**
1238 * Search using query
1239 * @param strin query
1240 * @return mixed array-object structure of found settings and pages
1241 */
1242 function search($query) {
1243 $textlib = textlib_get_instance();
1244
1245 $found = false;
1246 if (strpos(strtolower($this->name), $query) !== false) {
1247 $found = true;
1248 } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1249 $found = true;
1250 }
1251 if ($found) {
1252 $result = new object();
1253 $result->page = $this;
1254 $result->settings = array();
1255 return array($this->name => $result);
1256 } else {
1257 return array();
1258 }
1259 }
1260
6e4dc10f 1261 /**
2ce38b70 1262 * Determines if the current user has access to this external page based on $this->req_capability.
6e4dc10f 1263 * @return bool True if user has access, false otherwise.
1264 */
1265 function check_access() {
1266 if (!get_site()) {
1267 return true; // no access check before site is fully set up
1268 }
84c8ede0 1269 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
38d2d43b 1270 foreach($this->req_capability as $cap) {
1271 if (has_capability($cap, $context)) {
1272 return true;
1273 }
1274 }
1275 return false;
6e4dc10f 1276 }
1277
a8a66c96 1278 /**
1279 * Is this external page hidden in admin tree block?
1280 *
1281 * @return bool True if hidden
1282 */
1283 function is_hidden() {
1284 return $this->hidden;
1285 }
1286
6e4dc10f 1287}
1288
1289/**
1290 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1291 *
1292 * @author Vincenzo K. Marcovecchio
1293 * @package admin
1294 */
1295class admin_settingpage extends part_of_admin_tree {
1296
eef868d1 1297 /**
6e4dc10f 1298 * @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects
1299 */
1300 var $name;
eef868d1 1301
6e4dc10f 1302 /**
1303 * @var string The displayed name for this external page. Usually obtained through get_string().
1304 */
1305 var $visiblename;
1306 /**
1307 * @var mixed An array of admin_setting objects that are part of this setting page.
1308 */
1309 var $settings;
eef868d1 1310
6e4dc10f 1311 /**
1312 * @var string The role capability/permission a user must have to access this external page.
1313 */
2ce38b70 1314 var $req_capability;
eef868d1 1315
84c8ede0 1316 /**
1317 * @var object The context in which capability/permission should be checked, default is site context.
1318 */
1319 var $context;
1320
a8a66c96 1321 /**
1322 * @var bool hidden in admin tree block.
1323 */
1324 var $hidden;
1325
220a90c5 1326 /**
1327 * paths
1328 */
1329 var $path;
1330 var $visiblepath;
1331
1332 // see admin_externalpage
1333 function admin_settingpage($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1334 $this->settings = new object();
1335 $this->name = $name;
1336 $this->visiblename = $visiblename;
1337 if (is_array($req_capability)) {
1338 $this->req_capability = $req_capability;
6e4dc10f 1339 } else {
220a90c5 1340 $this->req_capability = array($req_capability);
6e4dc10f 1341 }
220a90c5 1342 $this->hidden = $hidden;
1343 $this->context = $context;
6e4dc10f 1344 }
eef868d1 1345
6e4dc10f 1346 // see admin_category
220a90c5 1347 function &locate($name, $findpath=false) {
1348 if ($this->name == $name) {
1349 if ($findpath) {
1350 $this->visiblepath = array($this->visiblename);
1351 $this->path = array($this->name);
1352 }
1353 return $this;
1354 } else {
1355 $return = NULL;
1356 return $return;
1357 }
6e4dc10f 1358 }
4672d955 1359
220a90c5 1360 function search($query) {
1361 $found = array();
4672d955 1362
220a90c5 1363 foreach ($this->settings as $setting) {
1364 if ($setting->is_related($query)) {
1365 $found[] = $setting;
1366 }
1367 }
1368
1369 if ($found) {
1370 $result = new object();
1371 $result->page = $this;
1372 $result->settings = $found;
1373 return array($this->name => $result);
1374 }
1375
1376 $textlib = textlib_get_instance();
1377
1378 $found = false;
1379 if (strpos(strtolower($this->name), $query) !== false) {
1380 $found = true;
1381 } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1382 $found = true;
1383 }
1384 if ($found) {
1385 $result = new object();
1386 $result->page = $this;
1387 $result->settings = array();
1388 return array($this->name => $result);
38d2d43b 1389 } else {
220a90c5 1390 return array();
38d2d43b 1391 }
6e4dc10f 1392 }
eef868d1 1393
220a90c5 1394 function prune($name) {
6e4dc10f 1395 return false;
1396 }
eef868d1 1397
220a90c5 1398 /**
1399 * 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
1400 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1401 * @param object $setting is the admin_setting object you want to add
1402 * @return true if successful, false if not
1403 */
1404 function add($setting) {
1405 if (!is_a($setting, 'admin_setting')) {
1406 debugging('error - not a setting instance');
1407 return false;
1408 }
1409
1410 $this->settings->{$setting->name} = $setting;
1411 return true;
1412 }
1413
6e4dc10f 1414 // see admin_externalpage
1415 function check_access() {
1416 if (!get_site()) {
1417 return true; // no access check before site is fully set up
1418 }
84c8ede0 1419 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
38d2d43b 1420 foreach($this->req_capability as $cap) {
1421 if (has_capability($cap, $context)) {
1422 return true;
1423 }
1424 }
1425 return false;
6e4dc10f 1426 }
eef868d1 1427
220a90c5 1428 /**
1429 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1430 * returns a string of the html
1431 */
6e4dc10f 1432 function output_html() {
220a90c5 1433 $adminroot =& admin_get_root();
1434 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
6e4dc10f 1435 foreach($this->settings as $setting) {
220a90c5 1436 $fullname = $setting->get_full_name();
1437 if (array_key_exists($fullname, $adminroot->errors)) {
1438 $data = $adminroot->errors[$fullname]->data;
6e4dc10f 1439 } else {
220a90c5 1440 $data = $setting->get_setting();
1441 if (is_null($data)) {
1442 $data = $setting->get_defaultsetting();
1443 }
6e4dc10f 1444 }
220a90c5 1445 $return .= $setting->output_html($data);
6e4dc10f 1446 }
220a90c5 1447 $return .= '</fieldset>';
6e4dc10f 1448 return $return;
1449 }
1450
a8a66c96 1451 /**
1452 * Is this settigns page hidden in admin tree block?
1453 *
1454 * @return bool True if hidden
1455 */
1456 function is_hidden() {
1457 return $this->hidden;
1458 }
1459
6e4dc10f 1460}
1461
1462
220a90c5 1463/**
1464 * Admin settings class. Only exists on setting pages.
1465 * Read & write happens at this level; no authentication.
1466 */
6e4dc10f 1467class admin_setting {
1468
1469 var $name;
1470 var $visiblename;
1471 var $description;
1472 var $defaultsetting;
220a90c5 1473 var $updatedcallback;
1474 var $plugin; // null means main config table
6e4dc10f 1475
220a90c5 1476 /**
1477 * Constructor
1478 * @param $name string unique ascii name
1479 * @param $visiblename string localised name
1480 * @param strin $description localised long description
1481 * @param mixed $defaultsetting string or array depending on implementation
1482 */
6e4dc10f 1483 function admin_setting($name, $visiblename, $description, $defaultsetting) {
220a90c5 1484 $this->name = $name;
1485 $this->visiblename = $visiblename;
1486 $this->description = $description;
6e4dc10f 1487 $this->defaultsetting = $defaultsetting;
1488 }
eef868d1 1489
220a90c5 1490 function get_full_name() {
1491 return 's_'.$this->plugin.'_'.$this->name;
1492 }
1493
1494 function get_id() {
1495 return 'id_s_'.$this->plugin.'_'.$this->name;
1496 }
1497
1498 function config_read($name) {
1499 global $CFG;
1500 if ($this->plugin === 'backup') {
1501 require_once($CFG->dirroot.'/backup/lib.php');
1502 $backupconfig = backup_get_config();
1503 if (isset($backupconfig->$name)) {
1504 return $backupconfig->$name;
1505 } else {
1506 return NULL;
1507 }
1508
1509 } else if (!empty($this->plugin)) {
1510 $value = get_config($this->plugin, $name);
1511 return $value === false ? NULL : $value;
1512
1513 } else {
1514 if (isset($CFG->$name)) {
1515 return $CFG->$name;
1516 } else {
1517 return NULL;
1518 }
1519 }
1520 }
1521
1522 function config_write($name, $value) {
1523 global $CFG;
1524 if ($this->plugin === 'backup') {
1525 require_once($CFG->dirroot.'/backup/lib.php');
1526 return (boolean)backup_set_config($name, $value);
1527 } else {
1528 return (boolean)set_config($name, $value, $this->plugin);
1529 }
1530 }
1531
1532 /**
1533 * Returns current value of this setting
1534 * @return mixed array or string depending on instance, NULL means not set yet
1535 */
6e4dc10f 1536 function get_setting() {
220a90c5 1537 // has to be overridden
1538 return NULL;
6e4dc10f 1539 }
eef868d1 1540
220a90c5 1541 /**
1542 * Returns default setting if exists
1543 * @return mixed array or string depending on instance; NULL means no default, user must supply
1544 */
8e5da17a 1545 function get_defaultsetting() {
1546 return $this->defaultsetting;
1547 }
1548
220a90c5 1549 /**
1550 * Store new setting
1551 * @param mixed string or array, must not be NULL
1552 * @return '' if ok, string error message otherwise
1553 */
6e4dc10f 1554 function write_setting($data) {
220a90c5 1555 // should be overridden
1556 return '';
6e4dc10f 1557 }
eef868d1 1558
220a90c5 1559 /**
1560 * Return part of form with setting
1561 * @param mixed data array or string depending on setting
1562 * @return string
1563 */
1564 function output_html($data) {
1565 // should be overridden
1566 return;
1567 }
1568
1569 /**
1570 * function called if setting updated - cleanup, cache reset, etc.
1571 */
1572 function set_updatedcallback($functionname) {
1573 $this->updatedcallback = $functionname;
1574 }
1575
1576 /**
1577 * Is setting related to query text - used when searching
1578 * @param string $query
1579 * @return bool
1580 */
1581 function is_related($query) {
1582 if (strpos(strtolower($this->name), $query) !== false) {
1583 return true;
1584 }
1585 $textlib = textlib_get_instance();
1586 if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1587 return true;
1588 }
1589 if (strpos($textlib->strtolower($this->description), $query) !== false) {
1590 return true;
1591 }
1592 return false;
6e4dc10f 1593 }
220a90c5 1594}
eef868d1 1595
220a90c5 1596/**
1597 * Dummy settings class - workaround for keeping empty categories visible
1598 */
1599class admin_setting_dummy extends admin_setting {
1600 function admin_setting_dummy() {
1601 parent::admin_setting('dummy', 'dummy', 'dummy', NULL);
1602 }
6e4dc10f 1603}
1604
220a90c5 1605/**
1606 * No setting - just heading and text.
1607 */
1608class admin_setting_heading extends admin_setting {
1609 /**
1610 * not a setting, just text
1611 * @param string $name of setting
1612 * @param string $heading heading
1613 * @param string $information text in box
1614 */
1615 function admin_setting_heading($name, $heading, $information) {
1616 parent::admin_setting($name, $heading, $information, '');
1617 }
1618
1619 function get_setting() {
1620 return true;
1621 }
1622
1623 function get_defaultsetting() {
1624 return true;
1625 }
1626
1627 function write_setting($data) {
1628 // do not write any setting
1629 return '';
1630 }
1631
1632 function output_html($data) {
1633 $return = '';
1634 if ($this->visiblename != '') {
1635 $return .= print_heading('<a name="'.$this->name.'">'.$this->visiblename.'</a>', '', 3, 'main', true);
1636 }
1637 if ($this->description != '') {
1638 $return .= print_box($this->description, 'generalbox formsettingheading', '', true);
1639 }
1640 return $return;
1641 }
1642}
6e4dc10f 1643
220a90c5 1644/**
1645 * The most flexibly setting, user is typing text
1646 */
6e4dc10f 1647class admin_setting_configtext extends admin_setting {
1648
1649 var $paramtype;
1650
220a90c5 1651 /**
1652 * config text contructor
1653 * @param string $name of setting
1654 * @param string $visiblename localised
1655 * @param string $description long localised info
1656 * @param string $defaultsetting
1657 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
1658 */
50999a0b 1659 function admin_setting_configtext($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW) {
6e4dc10f 1660 $this->paramtype = $paramtype;
1661 parent::admin_setting($name, $visiblename, $description, $defaultsetting);
1662 }
1663
1664 function get_setting() {
220a90c5 1665 return $this->config_read($this->name);
6e4dc10f 1666 }
eef868d1 1667
6e4dc10f 1668 function write_setting($data) {
220a90c5 1669 // $data is a string
9e24fbd1 1670 if (!$this->validate($data)) {
220a90c5 1671 return get_string('validateerror', 'admin');
c235598d 1672 }
220a90c5 1673 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 1674 }
1675
c235598d 1676 function validate($data) {
9e24fbd1 1677 if (is_string($this->paramtype)) {
1678 return preg_match($this->paramtype, $data);
1679 } else if ($this->paramtype === PARAM_RAW) {
1680 return true;
1681 } else {
1682 $cleaned = clean_param($data, $this->paramtype);
1683 return ("$data" == "$cleaned"); // implicit conversion to string is needed to do exact comparison
1684 }
c235598d 1685 }
1686
220a90c5 1687 function output_html($data) {
1688 $default = $this->get_defaultsetting();
1689
1690 if (!is_null($default)) {
1691 if ($default === '') {
1692 $default = get_string('emptysettingvalue', 'admin');
1693 }
1694 $defaultinfo = '<span class="defaultinfo">'.get_string('defaultsettinginfo', 'admin', s($default)).'</span>';
1695 } else {
1696 $defaultinfo = '';
1697 }
1698
1699 if ($this->paramtype === PARAM_INT) {
1700 $paramclass = 'class="number"';
c8218a42 1701 } else {
220a90c5 1702 $paramclass = '';
c8218a42 1703 }
220a90c5 1704
1705 return format_admin_setting($this, $this->visiblename,
1706 '<div class="form-text">'
1707 .'<input type="text" '.$paramclass.' id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'
1708 .$defaultinfo.'</div>',
6153cf58 1709 $this->description);
6e4dc10f 1710 }
6e4dc10f 1711}
1712
220a90c5 1713/**
1714 * General text area without html editor.
1715 */
1716class admin_setting_configtextarea extends admin_setting_configtext {
1717 var $rows;
1718 var $cols;
eba8cd63 1719
28764710 1720 function admin_setting_configtextarea($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
220a90c5 1721 $this->rows = $rows;
1722 $this->cols = $cols;
eba8cd63 1723 parent::admin_setting_configtext($name, $visiblename, $description, $defaultsetting, $paramtype);
1724 }
1725
220a90c5 1726 function output_html($data) {
1727 $default = $this->get_defaultsetting();
1728
1729 if (!is_null($default)) {
1730 if ($default === '') {
1731 $default = get_string('emptysettingvalue', 'admin');
1732 }
1733 $defaultinfo = '<div class="defaultinfo">'.get_string('defaultsettinginfo', 'admin', '<br />'.format_text($default, FORMAT_PLAIN)).'</div>';
eba8cd63 1734 } else {
220a90c5 1735 $defaultinfo = '';
eba8cd63 1736 }
220a90c5 1737
1738 return format_admin_setting($this, $this->visiblename,
1739 '<div class="form-textarea" ><textarea rows="'.$this->rows.'" cols="'.$this->cols.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'">'.s($data).'</textarea>'.$defaultinfo.'</div>',
1740 $this->description);
1741 }
1742}
1743
1744/**
1745 * Password field, allows unmasking of password
1746 */
1747class admin_setting_configpasswordunmask extends admin_setting_configtext {
1748 /**
1749 * Constructor
1750 * @param string $name of setting
1751 * @param string $visiblename localised
1752 * @param string $description long localised info
1753 * @param string $defaultsetting default password
1754 */
1755 function admin_setting_configpasswordunmask($name, $visiblename, $description, $defaultsetting) {
1756 parent::admin_setting_configtext($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
1757 }
1758
1759 function output_html($data) {
1760 $id = $this->get_id();
1761 $unmask = get_string('unmaskpassword', 'form');
1762 $unmaskjs = '<script type="text/javascript">
eba8cd63 1763//<![CDATA[
220a90c5 1764document.write(\'<span class="unmask"><input id="'.$id.'unmask" value="1" type="checkbox" onclick="unmaskPassword(\\\''.$id.'\\\')"/><label for="'.$id.'unmask">'.addslashes_js($unmask).'<\/label><\/span>\');
eba8cd63 1765//]]>
1766</script>';
220a90c5 1767 return format_admin_setting($this, $this->visiblename,
1768 '<div class="form-password"><input type="password" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$unmaskjs.'</div>',
1769 $this->description);
1770 }
1771}
1772
1773/**
1774 * Path to executable file
1775 */
1776class admin_setting_configexecutable extends admin_setting_configtext {
1777 /**
1778 * Constructor
1779 * @param string $name of setting
1780 * @param string $visiblename localised
1781 * @param string $description long localised info
1782 * @param string $defautpath default path
1783 */
1784 function admin_setting_configexecutable($name, $visiblename, $description, $defaultpath) {
1785 parent::admin_setting_configtext($name, $visiblename, $description, $defaultpath, PARAM_RAW);
1786 }
1787
1788 function output_html($data) {
1789 $default = $this->get_defaultsetting();
1790
1791 if (!is_null($default)) {
1792 if ($default === '') {
1793 $default = get_string('emptysettingvalue', 'admin');
1794 }
1795 $defaultinfo = '<span class="defaultinfo">'.get_string('defaultsettinginfo', 'admin', s($default)).'</span>';
1796 } else {
1797 $defaultinfo = '';
1798 }
1799
1800 if ($data) {
1801 if (file_exists($data) and is_executable($data)) {
1802 $executable = '<span class="pathok">&#x2714;</span>';
1803 } else {
1804 $executable = '<span class="patherror">&#x2718;</span>';
1805 }
1806 } else {
1807 $executable = '';
1808 }
1809
1810 return format_admin_setting($this, $this->visiblename,
1811 '<div class="form-executable">'
1812 .'<input type="text" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable
1813 .$defaultinfo.'</div>',
eba8cd63 1814 $this->description);
1815 }
220a90c5 1816}
1817
1818/**
1819 * Path to directory
1820 */
1821class admin_setting_configdirectory extends admin_setting_configtext {
1822 /**
1823 * Constructor
1824 * @param string $name of setting
1825 * @param string $visiblename localised
1826 * @param string $description long localised info
1827 * @param string $defaultdirectory default directory location
1828 */
1829 function admin_setting_configdirectory($name, $visiblename, $description, $defaultdirectory) {
1830 parent::admin_setting_configtext($name, $visiblename, $description, $defaultdirectory, PARAM_RAW);
1831 }
1832
1833 function output_html($data) {
1834 $default = $this->get_defaultsetting();
1835
1836 if (!is_null($default)) {
1837 if ($default === '') {
1838 $default = get_string('emptysettingvalue', 'admin');
1839 }
1840 $defaultinfo = '<span class="defaultinfo">'.get_string('defaultsettinginfo', 'admin', s($default)).'</span>';
1841 } else {
1842 $defaultinfo = '';
1843 }
1844
1845 if ($data) {
1846 if (file_exists($data) and is_dir($data)) {
1847 $executable = '<span class="pathok">&#x2714;</span>';
1848 } else {
1849 $executable = '<span class="patherror">&#x2718;</span>';
1850 }
1851 } else {
1852 $executable = '';
1853 }
9ba38673 1854
220a90c5 1855 return format_admin_setting($this, $this->visiblename,
1856 '<div class="form-directory">'
1857 .'<input type="text" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable
1858 .$defaultinfo.'</div>',
1859 $this->description);
1860 }
eba8cd63 1861}
1862
220a90c5 1863/**
1864 * Checkbox
1865 */
6e4dc10f 1866class admin_setting_configcheckbox extends admin_setting {
220a90c5 1867 var $yes;
1868 var $no;
6e4dc10f 1869
220a90c5 1870 /**
1871 * Constructor
1872 * @param string $name of setting
1873 * @param string $visiblename localised
1874 * @param string $description long localised info
1875 * @param string $defaultsetting
1876 * @param string $yes value used when checked
1877 * @param string $no value used when not checked
1878 */
1879 function admin_setting_configcheckbox($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
6e4dc10f 1880 parent::admin_setting($name, $visiblename, $description, $defaultsetting);
220a90c5 1881 $this->yes = (string)$yes;
1882 $this->no = (string)$no;
6e4dc10f 1883 }
1884
1885 function get_setting() {
220a90c5 1886 return $this->config_read($this->name);
6e4dc10f 1887 }
eef868d1 1888
6e4dc10f 1889 function write_setting($data) {
220a90c5 1890 if ((string)$data === $this->yes) { // convert to strings before comparison
1891 $data = $this->yes;
6e4dc10f 1892 } else {
220a90c5 1893 $data = $this->no;
6e4dc10f 1894 }
220a90c5 1895 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 1896 }
1897
220a90c5 1898 function output_html($data) {
1899 $default = $this->get_defaultsetting();
1900
1901 if (!is_null($default)) {
1902 if ((string)$default === $this->yes) {
1903 $str = get_string('checkboxyes', 'admin');
1904 } else {
1905 $str = get_string('checkboxno', 'admin');
1906 }
1907 $defaultinfo = '<span class="defaultinfo">'.get_string('defaultsettinginfo', 'admin', $str).'</span>';
c8218a42 1908 } else {
220a90c5 1909 $defaultinfo = '';
c8218a42 1910 }
220a90c5 1911
1912 if ((string)$data === $this->yes) { // convert to strings before comparison
1913 $checked = 'checked="checked"';
1914 } else {
1915 $checked = '';
1916 }
1917
1918 return format_admin_setting($this, $this->visiblename,
1919 '<div class="form-checkbox" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
1920 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' />'
1921 .$defaultinfo.'</div>',
6153cf58 1922 $this->description);
6e4dc10f 1923 }
6e4dc10f 1924}
1925
220a90c5 1926/**
1927 * Multiple checkboxes, each represents different value, stored in csv format
1928 */
1929class admin_setting_configmulticheckbox extends admin_setting {
6e4dc10f 1930 var $choices;
eef868d1 1931
220a90c5 1932 /**
1933 * Constructor
1934 * @param string $name of setting
1935 * @param string $visiblename localised
1936 * @param string $description long localised info
1937 * @param array $defaultsetting array of selected
1938 * @param array $choices array of $value=>$label for each checkbox
1939 */
1940 function admin_setting_configmulticheckbox($name, $visiblename, $description, $defaultsetting, $choices) {
6e4dc10f 1941 $this->choices = $choices;
1942 parent::admin_setting($name, $visiblename, $description, $defaultsetting);
1943 }
1944
0a784551 1945 /**
1946 * This function may be used in ancestors for lazy loading of choices
220a90c5 1947 * @return true if loaded, false if error
0a784551 1948 */
1949 function load_choices() {
1950 /*
220a90c5 1951 if (is_array($this->choices)) {
1952 return true;
0a784551 1953 }
1954 .... load choices here
1955 */
220a90c5 1956 return true;
1957 }
1958
1959 /**
1960 * Is setting related to query text - used when searching
1961 * @param string $query
1962 * @return bool
1963 */
1964 function is_related($query) {
1965 if (!$this->load_choices() or empty($this->choices)) {
1966 return false;
1967 }
1968 if (parent::is_related($query)) {
1969 return true;
1970 }
1971
1972 $textlib = textlib_get_instance();
1973 foreach ($this->choices as $desc) {
1974 if (strpos($textlib->strtolower($desc), $query) !== false) {
1975 return true;
1976 }
1977 }
1978 return false;
0a784551 1979 }
1980
6e4dc10f 1981 function get_setting() {
220a90c5 1982 $result = $this->config_read($this->name);
1983 if (is_null($result)) {
1984 return NULL;
1985 }
1986 if ($result === '') {
1987 return array();
1988 }
1989 return explode(',', $result);
6e4dc10f 1990 }
eef868d1 1991
6e4dc10f 1992 function write_setting($data) {
220a90c5 1993 if (!is_array($data)) {
1994 return ''; // ignore it
1995 }
1996 if (!$this->load_choices() or empty($this->choices)) {
1997 return '';
1998 }
1999 unset($data['xxxxx']);
2000 $result = array();
2001 foreach ($data as $key => $value) {
2002 if ($value and array_key_exists($key, $this->choices)) {
2003 $result[] = $key;
2004 }
2005 }
2006 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
6e4dc10f 2007 }
eef868d1 2008
220a90c5 2009 function output_html($data) {
2010 if (!$this->load_choices() or empty($this->choices)) {
2011 return '';
2012 }
2013 $default = $this->get_defaultsetting();
2014 if (is_null($default)) {
2015 $default = array();
2016 }
2017 if (is_null($data)) {
2018 foreach ($default as $key=>$value) {
2019 if ($value) {
2020 $current[] = $value;
2021 }
2022 }
2023 }
2024
2025 $options = array();
2026 $defaults = array();
2027 foreach($this->choices as $key=>$description) {
2028 if (in_array($key, $data)) {
2029 $checked = 'checked="checked"';
2030 } else {
2031 $checked = '';
2032 }
2033 if (!empty($default[$key])) {
2034 $defaults[] = $description;
2035 }
2036
2037 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2038 .'<label for="'.$this->get_id().'_'.$key.'">'.$description.'</label>';
2039 }
2040
2041 if (!empty($defaults)) {
2042 $defaultinfo = '<div class="defaultinfo">'.get_string('defaultsettinginfo', 'admin', implode(', ', $defaults)).'</div>';
c8218a42 2043 } else {
220a90c5 2044 $defaultinfo = '';
c8218a42 2045 }
220a90c5 2046
2047 $return = '<div class="form-multicheckbox">';
2048 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2049 if ($options) {
2050 $return .= '<ul>';
2051 foreach ($options as $option) {
2052 $return .= '<li>'.$option.'</li>';
2053 }
2054 $return .= '</ul>';
6e4dc10f 2055 }
220a90c5 2056 $return .= $defaultinfo.'</div>';
6153cf58 2057
220a90c5 2058 return format_admin_setting($this, $this->visiblename, $return, $this->description, false);
6e4dc10f 2059 }
6e4dc10f 2060}
2061
220a90c5 2062/**
2063 * Multiple checkboxes 2, value stored as string 00101011
2064 */
2065class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2066 function get_setting() {
2067 $result = $this->config_read($this->name);
2068 if (is_null($result)) {
2069 return NULL;
2070 }
2071 if (!$this->load_choices()) {
2072 return NULL;
2073 }
2074 $result = str_pad($result, count($this->choices), '0');
2075 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2076 $setting = array();
2077 foreach ($this->choices as $key=>$unused) {
2078 $value = array_shift($result);
2079 if ($value) {
2080 $setting[] = $key;
2081 }
2082 }
2083 return $setting;
2084 }
6e4dc10f 2085
220a90c5 2086 function write_setting($data) {
2087 if (!is_array($data)) {
2088 return ''; // ignore it
2089 }
2090 if (!$this->load_choices() or empty($this->choices)) {
2091 return '';
2092 }
2093 $result = '';
2094 foreach ($this->choices as $key=>$unused) {
2095 if (!empty($data[$key])) {
2096 $result .= '1';
2097 } else {
2098 $result .= '0';
2099 }
2100 }
2101 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2102 }
2103}
2104
2105/**
2106 * Select one value from list
2107 */
2108class admin_setting_configselect extends admin_setting {
6e4dc10f 2109 var $choices;
6e4dc10f 2110
220a90c5 2111 /**
2112 * Constructor
2113 * @param string $name of setting
2114 * @param string $visiblename localised
2115 * @param string $description long localised info
2116 * @param string $defaultsetting
2117 * @param array $choices array of $value=>$label for each selection
2118 */
2119 function admin_setting_configselect($name, $visiblename, $description, $defaultsetting, $choices) {
2120 $this->choices = $choices;
2121 parent::admin_setting($name, $visiblename, $description, $defaultsetting);
2122 }
2123
2124 /**
2125 * This function may be used in ancestors for lazy loading of choices
2126 * @return true if loaded, false if error
2127 */
2128 function load_choices() {
2129 /*
2130 if (is_array($this->choices)) {
2131 return true;
6e4dc10f 2132 }
220a90c5 2133 .... load choices here
2134 */
2135 return true;
6e4dc10f 2136 }
2137
2138 function get_setting() {
220a90c5 2139 return $this->config_read($this->name);
6e4dc10f 2140 }
eef868d1 2141
6e4dc10f 2142 function write_setting($data) {
220a90c5 2143 if (!$this->load_choices() or empty($this->choices)) {
2144 return '';
2145 }
2146 if (!array_key_exists($data, $this->choices)) {
2147 return ''; // ignore it
2148 }
eef868d1 2149
220a90c5 2150 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2151 }
eef868d1 2152
220a90c5 2153 function output_html($data) {
2154 if (!$this->load_choices() or empty($this->choices)) {
2155 return '';
2156 }
2157 $default = $this->get_defaultsetting();
2158
2159 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2160 $defaultinfo = '<span class="defaultinfo">'.get_string('defaultsettinginfo', 'admin', s($this->choices[$default])).'</span>';
cc73de71 2161 } else {
220a90c5 2162 $defaultinfo = '';
6e4dc10f 2163 }
220a90c5 2164
2165 $return = '<div class="form-select"><select id="'.$this->get_id().'" name="'.$this->get_full_name().'">';
6e4dc10f 2166 foreach ($this->choices as $key => $value) {
220a90c5 2167 // the string cast is needed because key may be integer - 0 is equal to most strings!
2168 $return .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
eef868d1 2169 }
220a90c5 2170 $return .= '</select>'.$defaultinfo.'</div>';
2171
2172 return format_admin_setting($this, $this->visiblename, $return, $this->description);
6e4dc10f 2173 }
2174
2175}
2176
220a90c5 2177/**
2178 * Select multiple items from list
2179 */
6e4dc10f 2180class admin_setting_configmultiselect extends admin_setting_configselect {
220a90c5 2181 /**
2182 * Constructor
2183 * @param string $name of setting
2184 * @param string $visiblename localised
2185 * @param string $description long localised info
2186 * @param array $defaultsetting array of selected items
2187 * @param array $choices array of $value=>$label for each list item
2188 */
6e4dc10f 2189 function admin_setting_configmultiselect($name, $visiblename, $description, $defaultsetting, $choices) {
2190 parent::admin_setting_configselect($name, $visiblename, $description, $defaultsetting, $choices);
2191 }
2192
2193 function get_setting() {
220a90c5 2194 $result = $this->config_read($this->name);
2195 if (is_null($result)) {
d7933a55 2196 return NULL;
2197 }
220a90c5 2198 if ($result === '') {
2199 return array();
2200 }
2201 return explode(',', $result);
6e4dc10f 2202 }
eef868d1 2203
6e4dc10f 2204 function write_setting($data) {
220a90c5 2205 if (!is_array($data)) {
2206 return ''; //ignore it
2207 }
2208 if (!$this->load_choices() or empty($this->choices)) {
2209 return '';
2210 }
2211
2212 $save = array();
2213 foreach ($data as $value) {
2214 if (!array_key_exists($value, $this->choices)) {
2215 continue; // ignore it
2216 }
2217 $save[] = $value;
2218 }
2219
2220 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2221 }
2222
2223 /**
2224 * Is setting related to query text - used when searching
2225 * @param string $query
2226 * @return bool
2227 */
2228 function is_related($query) {
2229 if (!$this->load_choices() or empty($this->choices)) {
2230 return false;
2231 }
2232 if (parent::is_related($query)) {
2233 return true;
2234 }
2235
2236 $textlib = textlib_get_instance();
2237 foreach ($this->choices as $desc) {
2238 if (strpos($textlib->strtolower($desc), $query) !== false) {
2239 return true;
2240 }
2241 }
2242 return false;
2243 }
2244
2245 function output_html($data) {
2246 if (!$this->load_choices() or empty($this->choices)) {
2247 return '';
2248 }
2249 $choices = $this->choices;
2250 $default = $this->get_defaultsetting();
2251 if (is_null($default)) {
2252 $default = array();
2253 }
2254 if (is_null($data)) {
d7933a55 2255 $data = array();
2256 }
220a90c5 2257
2258 $defaults = array();
2259 $return = '<div class="form-select"><select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="10" multiple="multiple">';
2260 foreach ($this->choices as $key => $description) {
2261 if (in_array($key, $data)) {
2262 $selected = 'selected="selected"';
2263 } else {
2264 $selected = '';
2265 }
2266 if (in_array($key, $default)) {
2267 $defaults[] = $description;
6e4dc10f 2268 }
220a90c5 2269
2270 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2271 }
2272
2273 if (!empty($defaults)) {
2274 $defaultinfo = '<div class="defaultinfo">'.get_string('defaultsettinginfo', 'admin', implode(', ', $defaults)).'</div>';
2275 } else {
2276 $defaultinfo = '';
6e4dc10f 2277 }
eef868d1 2278
220a90c5 2279 $return .= '</select>'.$defaultinfo.'</div>';
2280 return format_admin_setting($this, $this->visiblename, $return, $this->description);
6e4dc10f 2281 }
220a90c5 2282}
eef868d1 2283
220a90c5 2284/**
2285 * Time selector
2286 * this is a liiitle bit messy. we're using two selects, but we're returning
2287 * them as an array named after $name (so we only use $name2 internally for the setting)
2288 */
2289class admin_setting_configtime extends admin_setting {
2290 var $name2;
2291
2292 /**
2293 * Constructor
2294 * @param string $hoursname setting for hours
2295 * @param string $minutesname setting for hours
2296 * @param string $visiblename localised
2297 * @param string $description long localised info
2298 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
2299 */
2300 function admin_setting_configtime($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
2301 $this->name2 = $minutesname;
2302 parent::admin_setting($hoursname, $visiblename, $description, $defaultsetting);
2303 }
2304
2305 function get_setting() {
2306 $result1 = $this->config_read($this->name);
2307 $result2 = $this->config_read($this->name2);
2308 if (is_null($result1) or is_null($result2)) {
2309 return NULL;
2310 }
2311
2312 return array('h' => $result1, 'm' => $result2);
2313 }
2314
2315 function write_setting($data) {
2316 if (!is_array($data)) {
2317 return '';
2318 }
2319
2320 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
2321 return ($result ? '' : get_string('errorsetting', 'admin'));
2322 }
2323
2324 function output_html($data) {
2325 $default = $this->get_defaultsetting();
2326
2327 if (is_array($default)) {
2328 $defaultinfo = '<span class="defaultinfo">'.get_string('defaultsettinginfo', 'admin', $default['h'].':'.$default['m']).'</span>';
cc73de71 2329 } else {
220a90c5 2330 $defaultinfo = '';
6e4dc10f 2331 }
220a90c5 2332
2333 $return = '<div class="form-time">'.
2334 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
2335 for ($i = 0; $i < 24; $i++) {
2336 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
6e4dc10f 2337 }
220a90c5 2338 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
2339 for ($i = 0; $i < 60; $i += 5) {
2340 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2341 }
2342 $return .= '</select>'.$defaultinfo.'</div>';
2343 return format_admin_setting($this, $this->visiblename, $return, $this->description, false);
6e4dc10f 2344 }
2345
2346}
2347
220a90c5 2348/**
2349 * Special checkbox for calendar - resets SESSION vars.
2350 */
6e4dc10f 2351class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
6e4dc10f 2352 function admin_setting_special_adminseesall() {
220a90c5 2353 parent::admin_setting_configcheckbox('calendar_adminseesall', get_string('adminseesall', 'admin'),
2354 get_string('helpadminseesall', 'admin'), '0');
6e4dc10f 2355 }
2356
2357 function write_setting($data) {
2358 global $SESSION;
2359 unset($SESSION->cal_courses_shown);
220a90c5 2360 return parent::write_setting($data);
6e4dc10f 2361 }
2362}
2363
220a90c5 2364/**
2365 * Special select for frontpage - stores data in course table
2366 */
6e4dc10f 2367class admin_setting_sitesetselect extends admin_setting_configselect {
6e4dc10f 2368 function get_setting() {
2369 $site = get_site();
220a90c5 2370 return $site->{$this->name};
6e4dc10f 2371 }
eef868d1 2372
6e4dc10f 2373 function write_setting($data) {
2374 if (!in_array($data, array_keys($this->choices))) {
220a90c5 2375 return get_string('errorsetting', 'admin');
6e4dc10f 2376 }
2377 $record = new stdClass();
220a90c5 2378 $record->id = SITEID;
2379 $temp = $this->name;
2380 $record->$temp = $data;
6e4dc10f 2381 $record->timemodified = time();
220a90c5 2382 return (update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2383 }
eef868d1 2384
6e4dc10f 2385}
2386
220a90c5 2387/**
2388 * Special select - lists on the frontpage - hacky
2389 */
2390class admin_setting_courselist_frontpage extends admin_setting {
2391 var $choices;
6e4dc10f 2392
e0f6e995 2393 function admin_setting_courselist_frontpage($loggedin) {
6e4dc10f 2394 global $CFG;
220a90c5 2395 require_once($CFG->dirroot.'/course/lib.php');
2396 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
2397 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
2398 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
2399 $defaults = array(FRONTPAGECOURSELIST);
2400 parent::admin_setting($name, $visiblename, $description, $defaults);
6e4dc10f 2401 }
eef868d1 2402
220a90c5 2403 function load_choices() {
2404 if (is_array($this->choices)) {
2405 return true;
2406 }
2407 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
2408 FRONTPAGECOURSELIST => get_string('frontpagecourselist'),
2409 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
2410 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
2411 'none' => get_string('none'));
2412 if ($this->name == 'frontpage' and count_records('course') > FRONTPAGECOURSELIMIT) {
2413 unset($this->choices[FRONTPAGECOURSELIST]);
2414 }
2415 return true;
2416 }
6e4dc10f 2417 function get_setting() {
220a90c5 2418 $result = $this->config_read($this->name);
2419 if (is_null($result)) {
2420 return NULL;
2421 }
2422 if ($result === '') {
2423 return array();
2424 }
2425 return explode(',', $result);
6e4dc10f 2426 }
eef868d1 2427
6e4dc10f 2428 function write_setting($data) {
220a90c5 2429 if (!is_array($data)) {
2430 return '';
6e4dc10f 2431 }
220a90c5 2432 $this->load_choices();
2433 $save = array();
6e4dc10f 2434 foreach($data as $datum) {
220a90c5 2435 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
2436 continue;
6e4dc10f 2437 }
220a90c5 2438 $save[$datum] = $datum; // no duplicates
6e4dc10f 2439 }
220a90c5 2440 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2441 }
eef868d1 2442
220a90c5 2443 function output_html($data) {
2444 $this->load_choices();
2445 $currentsetting = array();
2446 foreach ($data as $key) {
2447 if ($key != 'none' and array_key_exists($key, $this->choices)) {
2448 $currentsetting[] = $key; // already selected first
6e4dc10f 2449 }
2450 }
220a90c5 2451
0a7e84c3 2452 $return = '<div class="form-group">';
6e4dc10f 2453 for ($i = 0; $i < count($this->choices) - 1; $i++) {
220a90c5 2454 if (!array_key_exists($i, $currentsetting)) {
2455 $currentsetting[$i] = 'none'; //none
2456 }
2457 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
6e4dc10f 2458 foreach ($this->choices as $key => $value) {
220a90c5 2459 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
6e4dc10f 2460 }
2461 $return .= '</select>';
2462 if ($i !== count($this->choices) - 2) {
975211bb 2463 $return .= '<br />';
6e4dc10f 2464 }
2465 }
0a7e84c3 2466 $return .= '</div>';
2467
220a90c5 2468 return format_admin_setting($this, $this->visiblename, $return, $this->description, false);
6e4dc10f 2469 }
2470}
2471
220a90c5 2472/**
2473 * Special checkbox for frontpage - stores data in course table
2474 */
6e4dc10f 2475class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
6e4dc10f 2476 function get_setting() {
2477 $site = get_site();
8e5da17a 2478 return $site->{$this->name};
6e4dc10f 2479 }
eef868d1 2480
6e4dc10f 2481 function write_setting($data) {
220a90c5 2482 $record = new object();
2483 $record->id = SITEID;
2484 $record->{$this->name} = ($data == '1' ? 1 : 0);
2485 $record->timemodified = time();
2486 return (update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2487 }
6e4dc10f 2488}
2489
220a90c5 2490/**
2491 * Special text for frontpage - stores data in course table.
2492 * Empty string means not set here. Manual setting is required.
2493 */
6e4dc10f 2494class admin_setting_sitesettext extends admin_setting_configtext {
6e4dc10f 2495 function get_setting() {
2496 $site = get_site();
8e5da17a 2497 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
6e4dc10f 2498 }
90cfbd0a 2499
b89639f9 2500 function validate($data) {
b0abd282 2501 $cleaned = stripslashes(clean_param($data, PARAM_MULTILANG));
b89639f9 2502 if ($cleaned == '') {
2503 return false; // can not be empty
2504 }
220a90c5 2505 return ($data == $cleaned);
b89639f9 2506 }
2507
6e4dc10f 2508 function write_setting($data) {
b89639f9 2509 $data = trim($data);
9e24fbd1 2510 if (!$this->validate($data)) {
220a90c5 2511 return get_string('required');
90cfbd0a 2512 }
eef868d1 2513
220a90c5 2514 $record = new object();
2515 $record->id = SITEID;
87fa8a17 2516 $record->{$this->name} = addslashes($data);
220a90c5 2517 $record->timemodified = time();
2518 return (update_record('course', $record) ? '' : get_string('dbupdatefailed', 'error'));
6e4dc10f 2519 }
6e4dc10f 2520}
2521
220a90c5 2522/**
2523 * Special text editor for site description.
2524 */
6e4dc10f 2525class admin_setting_special_frontpagedesc extends admin_setting {
6e4dc10f 2526 function admin_setting_special_frontpagedesc() {
220a90c5 2527 parent::admin_setting('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
6e4dc10f 2528 }
eef868d1 2529
6e4dc10f 2530 function get_setting() {
6e4dc10f 2531 $site = get_site();
c626c2f4 2532 return $site->{$this->name};
2533 }
eef868d1 2534
6e4dc10f 2535 function write_setting($data) {
c626c2f4 2536 $record = new object();
220a90c5 2537 $record->id = SITEID;
c626c2f4 2538 $record->{$this->name} = addslashes($data);
2539 $record->timemodified = time();
220a90c5 2540 return(update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2541 }
2542
220a90c5 2543 function output_html($data) {
2544 global $CFG;
6e4dc10f 2545
220a90c5 2546 $CFG->adminusehtmleditor = can_use_html_editor();
2547 $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true).'</div>';
2548
2549 return format_admin_setting($this, $this->visiblename, $return, $this->description, false);
2550 }
2551}
6e4dc10f 2552
2553class admin_setting_special_editorfontlist extends admin_setting {
2554
2555 var $items;
2556
2557 function admin_setting_special_editorfontlist() {
2558 global $CFG;
2559 $name = 'editorfontlist';
2560 $visiblename = get_string('editorfontlist', 'admin');
2561 $description = get_string('configeditorfontlist', 'admin');
6e4dc10f 2562 $defaults = array('k0' => 'Trebuchet',
2563 'v0' => 'Trebuchet MS,Verdana,Arial,Helvetica,sans-serif',
2564 'k1' => 'Arial',
2565 'v1' => 'arial,helvetica,sans-serif',
2566 'k2' => 'Courier New',
2567 'v2' => 'courier new,courier,monospace',
2568 'k3' => 'Georgia',
2569 'v3' => 'georgia,times new roman,times,serif',
2570 'k4' => 'Tahoma',
2571 'v4' => 'tahoma,arial,helvetica,sans-serif',
2572 'k5' => 'Times New Roman',
2573 'v5' => 'times new roman,times,serif',
2574 'k6' => 'Verdana',
2575 'v6' => 'verdana,arial,helvetica,sans-serif',
2576 'k7' => 'Impact',
2577 'v7' => 'impact',
2578 'k8' => 'Wingdings',
2579 'v8' => 'wingdings');
2580 parent::admin_setting($name, $visiblename, $description, $defaults);
2581 }
eef868d1 2582
6e4dc10f 2583 function get_setting() {
cc73de71 2584 global $CFG;
220a90c5 2585 $result = $this->config_read($this->name);
2586 if (is_null($result)) {
cc73de71 2587 return NULL;
2588 }
220a90c5 2589 $i = 0;
2590 $currentsetting = array();
2591 $items = explode(';', $result);
2592 foreach ($items as $item) {
2593 $item = explode(':', $item);
2594 $currentsetting['k'.$i] = $item[0];
2595 $currentsetting['v'.$i] = $item[1];
2596 $i++;
2597 }
2598 return $currentsetting;
6e4dc10f 2599 }
eef868d1 2600
6e4dc10f 2601 function write_setting($data) {
eef868d1 2602
6e4dc10f 2603 // there miiight be an easier way to do this :)
2604 // if this is changed, make sure the $defaults array above is modified so that this
2605 // function processes it correctly
eef868d1 2606
6e4dc10f 2607 $keys = array();
2608 $values = array();
eef868d1 2609
6e4dc10f 2610 foreach ($data as $key => $value) {
2611 if (substr($key,0,1) == 'k') {
2612 $keys[substr($key,1)] = $value;
2613 } elseif (substr($key,0,1) == 'v') {
2614 $values[substr($key,1)] = $value;
2615 }
2616 }
eef868d1 2617
220a90c5 2618 $result = array();
6e4dc10f 2619 for ($i = 0; $i < count($keys); $i++) {
2620 if (($keys[$i] !== '') && ($values[$i] !== '')) {
220a90c5 2621 $result[] = clean_param($keys[$i],PARAM_NOTAGS).':'.clean_param($values[$i], PARAM_NOTAGS);
6e4dc10f 2622 }
2623 }
eef868d1 2624
220a90c5 2625 return ($this->config_write($this->name, implode(';', $result)) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2626 }
eef868d1 2627
220a90c5 2628 function output_html($data) {
2629 $fullname = $this->get_full_name();
1beed35f 2630 $return = '<div class="form-group">';
220a90c5 2631 for ($i = 0; $i < count($data) / 2; $i++) {
2632 $return .= '<input type="text" class="form-text" name="'.$fullname.'[k'.$i.']" value="'.$data['k'.$i].'" />';
6e4dc10f 2633 $return .= '&nbsp;&nbsp;';
220a90c5 2634 $return .= '<input type="text" class="form-text" name="'.$fullname.'[v'.$i.']" value="'.$data['v'.$i].'" /><br />';
6e4dc10f 2635 }
220a90c5 2636 $return .= '<input type="text" class="form-text" name="'.$fullname.'[k'.$i.']" value="" />';
6e4dc10f 2637 $return .= '&nbsp;&nbsp;';
220a90c5 2638 $return .= '<input type="text" class="form-text" name="'.$fullname.'[v'.$i.']" value="" /><br />';
2639 $return .= '<input type="text" class="form-text" name="'.$fullname.'[k'.($i + 1).']" value="" />';
6e4dc10f 2640 $return .= '&nbsp;&nbsp;';
220a90c5 2641 $return .= '<input type="text" class="form-text" name="'.$fullname.'[v'.($i + 1).']" value="" />';
1beed35f 2642 $return .= '</div>';
6153cf58 2643
220a90c5 2644 return format_admin_setting($this, $this->visiblename, $return, $this->description, false);
6e4dc10f 2645 }
eef868d1 2646
6e4dc10f 2647}
2648
93c61c18 2649class admin_setting_emoticons extends admin_setting {
2650
2651 var $items;
2652
2653 function admin_setting_emoticons() {
2654 global $CFG;
2655 $name = 'emoticons';
2656 $visiblename = get_string('emoticons', 'admin');
2657 $description = get_string('configemoticons', 'admin');
2658 $defaults = array('k0' => ':-)',
2659 'v0' => 'smiley',
2660 'k1' => ':)',
2661 'v1' => 'smiley',
2662 'k2' => ':-D',
2663 'v2' => 'biggrin',
2664 'k3' => ';-)',
2665 'v3' => 'wink',
2666 'k4' => ':-/',
2667 'v4' => 'mixed',
2668 'k5' => 'V-.',
2669 'v5' => 'thoughtful',
2670 'k6' => ':-P',
2671 'v6' => 'tongueout',
2672 'k7' => 'B-)',
2673 'v7' => 'cool',
2674 'k8' => '^-)',
2675 'v8' => 'approve',
2676 'k9' => '8-)',
2677 'v9' => 'wideeyes',
2678 'k10' => ':o)',
2679 'v10' => 'clown',
2680 'k11' => ':-(',
2681 'v11' => 'sad',
2682 'k12' => ':(',
2683 'v12' => 'sad',
2684 'k13' => '8-.',
2685 'v13' => 'shy',
2686 'k14' => ':-I',
2687 'v14' => 'blush',
2688 'k15' => ':-X',
2689 'v15' => 'kiss',
2690 'k16' => '8-o',
2691 'v16' => 'surprise',
2692 'k17' => 'P-|',
2693 'v17' => 'blackeye',
2694 'k18' => '8-[',
2695 'v18' => 'angry',
2696 'k19' => 'xx-P',
2697 'v19' => 'dead',
2698 'k20' => '|-.',
2699 'v20' => 'sleepy',
2700 'k21' => '}-]',
2701 'v21' => 'evil',
2702 'k22' => '(h)',
2703 'v22' => 'heart',
2704 'k23' => '(heart)',
2705 'v23' => 'heart',
2706 'k24' => '(y)',
2707 'v24' => 'yes',
2708 'k25' => '(n)',
2709 'v25' => 'no',
2710 'k26' => '(martin)',
2711 'v26' => 'martin',
2712 'k27' => '( )',
2713 'v27' => 'egg');
2714 parent::admin_setting($name, $visiblename, $description, $defaults);
2715 }
2716
2717 function get_setting() {
2718 global $CFG;
220a90c5 2719 $result = $this->config_read($this->name);
2720 if (is_null($result)) {
93c61c18 2721 return NULL;
2722 }
220a90c5 2723 $i = 0;
2724 $currentsetting = array();
2725 $items = explode('{;}', $result);
2726 foreach ($items as $item) {
2727 $item = explode('{:}', $item);
2728 $currentsetting['k'.$i] = $item[0];
2729 $currentsetting['v'.$i] = $item[1];
2730 $i++;
2731 }
2732 return $currentsetting;
93c61c18 2733 }
2734
2735 function write_setting($data) {
2736
2737 // there miiight be an easier way to do this :)
2738 // if this is changed, make sure the $defaults array above is modified so that this
2739 // function processes it correctly
2740
2741 $keys = array();
2742 $values = array();
2743
2744 foreach ($data as $key => $value) {
2745 if (substr($key,0,1) == 'k') {
2746 $keys[substr($key,1)] = $value;
2747 } elseif (substr($key,0,1) == 'v') {
2748 $values[substr($key,1)] = $value;
2749 }
2750 }
2751
220a90c5 2752 $result = array();
93c61c18 2753 for ($i = 0; $i < count($keys); $i++) {
2754 if (($keys[$i] !== '') && ($values[$i] !== '')) {
220a90c5 2755 $result[] = clean_param($keys[$i],PARAM_NOTAGS).'{:}'.clean_param($values[$i], PARAM_NOTAGS);
93c61c18 2756 }
2757 }
2758
220a90c5 2759 return ($this->config_write($this->name, implode('{;}', $result)) ? '' : get_string('errorsetting', 'admin').$this->visiblename.'<br />');
93c61c18 2760 }
2761
220a90c5 2762 function output_html($data) {
2763 $fullname = $this->get_full_name();
93c61c18 2764 $return = '<div class="form-group">';
220a90c5 2765 for ($i = 0; $i < count($data) / 2; $i++) {
2766 $return .= '<input type="text" class="form-text" name="'.$fullname.'[k'.$i.']" value="'.$data['k'.$i].'" />';
93c61c18 2767 $return .= '&nbsp;&nbsp;';
220a90c5 2768 $return .= '<input type="text" class="form-text" name="'.$fullname.'[v'.$i.']" value="'.$data['v'.$i].'" /><br />';
93c61c18 2769 }
220a90c5 2770 $return .= '<input type="text" class="form-text" name="'.$fullname.'[k'.$i.']" value="" />';
93c61c18 2771 $return .= '&nbsp;&nbsp;';
220a90c5 2772 $return .= '<input type="text" class="form-text" name="'.$fullname.'[v'.$i.']" value="" /><br />';
2773 $return .= '<input type="text" class="form-text" name="'.$fullname.'[k'.($i + 1).']" value="" />';
93c61c18 2774 $return .= '&nbsp;&nbsp;';
220a90c5 2775 $return .= '<input type="text" class="form-text" name="'.$fullname.'[v'.($i + 1).']" value="" />';
93c61c18 2776 $return .= '</div>';
2777
220a90c5 2778 return format_admin_setting($this, $this->visiblename, $return, $this->description, false);
93c61c18 2779 }
2780
2781}
2782
220a90c5 2783/**
2784 * Setting for spellchecker language selection.
2785 */
6e4dc10f 2786class admin_setting_special_editordictionary extends admin_setting_configselect {
2787
2788 function admin_setting_special_editordictionary() {
2789 $name = 'editordictionary';
2790 $visiblename = get_string('editordictionary','admin');
2791 $description = get_string('configeditordictionary', 'admin');
220a90c5 2792 parent::admin_setting_configselect($name, $visiblename, $description, '', NULL);
6e4dc10f 2793 }
2794
220a90c5 2795 function load_choices() {
2796 // function borrowed from the old moodle/admin/editor.php, slightly modified
2797 // Get all installed dictionaries in the system
2798 if (is_array($this->choices)) {
2799 return true;
2800 }
2801
2802 $this->choices = array();
6e4dc10f 2803
2804 global $CFG;
eef868d1 2805
6e4dc10f 2806 clearstatcache();
2807
2808 // If aspellpath isn't set don't even bother ;-)
2809 if (empty($CFG->aspellpath)) {
220a90c5 2810 $this->choices['error'] = 'Empty aspell path!';
2811 return true;
6e4dc10f 2812 }
2813
2814 // Do we have access to popen function?
2815 if (!function_exists('popen')) {
220a90c5 2816 $this->choices['error'] = 'Popen function disabled!';
2817 return true;
6e4dc10f 2818 }
eef868d1 2819
6e4dc10f 2820 $cmd = $CFG->aspellpath;
2821 $output = '';
2822 $dictionaries = array();
6e4dc10f 2823
220a90c5 2824 if(!($handle = @popen(escapeshellarg($cmd).' dump dicts', 'r'))) {
2825 $this->choices['error'] = 'Couldn\'t create handle!';
6e4dc10f 2826 }
2827
2828 while(!feof($handle)) {
2829 $output .= fread($handle, 1024);
2830 }
2831 @pclose($handle);
2832
2833 $dictionaries = explode(chr(10), $output);
220a90c5 2834 foreach ($dictionaries as $dict) {
2835 if (empty($dict)) {
2836 continue;
6e4dc10f 2837 }
220a90c5 2838 $this->choices[$dict] = $dict;
6e4dc10f 2839 }
2840
220a90c5 2841 if (empty($this->choices)) {
2842 $this->choices['error'] = 'Error! Check your aspell installation!';
6e4dc10f 2843 }
220a90c5 2844 return true;
6e4dc10f 2845 }
6e4dc10f 2846}
2847
2848
2849class admin_setting_special_editorhidebuttons extends admin_setting {
6e4dc10f 2850 var $items;
2851
2852 function admin_setting_special_editorhidebuttons() {
220a90c5 2853 parent::admin_setting('editorhidebuttons', get_string('editorhidebuttons', 'admin'),
2854 get_string('confeditorhidebuttons', 'admin'), array());
6e4dc10f 2855 // weird array... buttonname => buttonimage (assume proper path appended). if you leave buttomimage blank, text will be printed instead
2856 $this->items = array('fontname' => '',
2857 'fontsize' => '',
2858 'formatblock' => '',
2859 'bold' => 'ed_format_bold.gif',
2860 'italic' => 'ed_format_italic.gif',
2861 'underline' => 'ed_format_underline.gif',
2862 'strikethrough' => 'ed_format_strike.gif',
2863 'subscript' => 'ed_format_sub.gif',
2864 'superscript' => 'ed_format_sup.gif',
2865 'copy' => 'ed_copy.gif',
2866 'cut' => 'ed_cut.gif',
2867 'paste' => 'ed_paste.gif',
2868 'clean' => 'ed_wordclean.gif',
2869 'undo' => 'ed_undo.gif',
2870 'redo' => 'ed_redo.gif',
2871 'justifyleft' => 'ed_align_left.gif',
2872 'justifycenter' => 'ed_align_center.gif',
2873 'justifyright' => 'ed_align_right.gif',
2874 'justifyfull' => 'ed_align_justify.gif',
2875 'lefttoright' => 'ed_left_to_right.gif',
2876 'righttoleft' => 'ed_right_to_left.gif',
2877 'insertorderedlist' => 'ed_list_num.gif',
2878 'insertunorderedlist' => 'ed_list_bullet.gif',
2879 'outdent' => 'ed_indent_less.gif',
2880 'indent' => 'ed_indent_more.gif',
2881 'forecolor' => 'ed_color_fg.gif',
2882 'hilitecolor' => 'ed_color_bg.gif',
2883 'inserthorizontalrule' => 'ed_hr.gif',
2884 'createanchor' => 'ed_anchor.gif',
2885 'createlink' => 'ed_link.gif',
2886 'unlink' => 'ed_unlink.gif',
2887 'insertimage' => 'ed_image.gif',
2888 'inserttable' => 'insert_table.gif',
2889 'insertsmile' => 'em.icon.smile.gif',
2890 'insertchar' => 'icon_ins_char.gif',
2891 'spellcheck' => 'spell-check.gif',
2892 'htmlmode' => 'ed_html.gif',
2893 'popupeditor' => 'fullscreen_maximize.gif',
2894 'search_replace' => 'ed_replace.gif');
2895 }
2896
2897 function get_setting() {
220a90c5 2898 $result = $this->config_read($this->name);
2899 if (is_null($result)) {
2900 return NULL;
2901 }
2902 if ($result === '') {
2903 return array();
2904 }
2905 return explode(',', $result);
6e4dc10f 2906 }
2907
2908 function write_setting($data) {
220a90c5 2909 if (!is_array($data)) {
2910 return ''; // ignore it
2911 }
2912 unset($data['xxxxx']);
6e4dc10f 2913 $result = array();
220a90c5 2914
6e4dc10f 2915 foreach ($data as $key => $value) {
2916 if (!in_array($key, array_keys($this->items))) {
220a90c5 2917 return get_string('errorsetting', 'admin');
6e4dc10f 2918 }
2919 if ($value == '1') {
2920 $result[] = $key;
2921 }
2922 }
220a90c5 2923 return ($this->config_write($this->name, implode(' ', $result)) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2924 }
2925
220a90c5 2926 function output_html($data) {
eef868d1 2927
6e4dc10f 2928 global $CFG;
eef868d1 2929
6e4dc10f 2930 // checkboxes with input name="$this->name[$key]" value="1"
2931 // we do 15 fields per column
eef868d1 2932
1beed35f 2933 $return = '<div class="form-group">';
2934 $return .= '<table><tr><td valign="top" align="right">';
220a90c5 2935 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
eef868d1 2936
6e4dc10f 2937 $count = 0;
eef868d1 2938
6e4dc10f 2939 foreach($this->items as $key => $value) {
8ddbd7a6 2940 if ($count % 15 == 0 and $count != 0) {
2941 $return .= '</td><td valign="top" align="right">';
6e4dc10f 2942 }
eef868d1 2943
220a90c5 2944 $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').'" />').'&nbsp;';
2945 $return .= '<input type="checkbox" class="form-checkbox" value="1" id="'.$this->get_id().$key.'" name="'.$this->get_full_name().'['.$key.']"'.(in_array($key,$data) ? ' checked="checked"' : '').' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
6e4dc10f 2946 $count++;
2947 if ($count % 15 != 0) {
2948 $return .= '<br /><br />';
2949 }
2950 }
eef868d1 2951
2952 $return .= '</td></tr>';
6e4dc10f 2953 $return .= '</table>';
1beed35f 2954 $return .= '</div>';
6e4dc10f 2955
220a90c5 2956 return format_admin_setting($this, $this->visiblename, $return, $this->description, false);
6e4dc10f 2957 }
6e4dc10f 2958}
2959
220a90c5 2960/**
2961 * Special setting for limiting of the list of available languages.
2962 */
4642650f 2963class admin_setting_langlist extends admin_setting_configtext {
2964 function admin_setting_langlist() {
2965 parent::admin_setting_configtext('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
2966 }
2967
2968 function write_setting($data) {
2969 $return = parent::write_setting($data);
2970 get_list_of_languages(true);//refresh the list
2971 return $return;
2972 }
2973}
2974
220a90c5 2975/**
2976 * Course category selection
2977 */
2978class admin_settings_coursecat_select extends admin_setting_configselect {
2979 function admin_settings_coursecat_select($name, $visiblename, $description, $defaultsetting) {
2980 parent::admin_setting_configselect($name, $visiblename, $description, $defaultsetting, NULL);
2981 }
6153cf58 2982
220a90c5 2983 function load_choices() {
2984 global $CFG;
2985 require_once($CFG->dirroot.'/course/lib.php');
2986 if (is_array($this->choices)) {
2987 return true;
2988 }
2989 $this->choices = make_categories_options();
2990 return true;
2991 }
2992}
eef868d1 2993
220a90c5 2994class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
2995 function admin_setting_special_backupdays() {
2996 parent::admin_setting_configmulticheckbox2('backup_sche_weekdays', get_string('schedule'), get_string('backupschedulehelp'), array(), NULL);
2997 $this->plugin = 'backup';
6e4dc10f 2998 }
eef868d1 2999
220a90c5 3000 function load_choices() {
3001 if (is_array($this->choices)) {
3002 return true;
3003 }
3004 $this->choices = array();
3005 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3006 foreach ($days as $day) {
3007 $this->choices[$day] = get_string($day, 'calendar');
6e4dc10f 3008 }
220a90c5 3009 return true;
6e4dc10f 3010 }
3011}
3012
220a90c5 3013/**
3014 * Special debug setting
3015 */
ee437bbc 3016class admin_setting_special_debug extends admin_setting_configselect {
6e4dc10f 3017 function admin_setting_special_debug() {
220a90c5 3018 parent::admin_setting_configselect('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
6e4dc10f 3019 }
3020
220a90c5 3021 function load_choices() {
3022 if (is_array($this->choices)) {
3023 return true;
ee437bbc 3024 }
220a90c5 3025 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
3026 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
3027 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
3028 DEBUG_ALL => get_string('debugall', 'admin'),
3029 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
3030 return true;
6e4dc10f 3031 }
6e4dc10f 3032}
3033
3034
3035class admin_setting_special_calendar_weekend extends admin_setting {
6e4dc10f 3036 function admin_setting_special_calendar_weekend() {
3037 $name = 'calendar_weekend';
3038 $visiblename = get_string('calendar_weekend', 'admin');
3039 $description = get_string('helpweekenddays', 'admin');
5eaa6aa0 3040 $default = array ('0', '6'); // Saturdays and Sundays
b91b1f92 3041 parent::admin_setting($name, $visiblename, $description, $default);
6e4dc10f 3042 }
3043
3044 function get_setting() {
220a90c5 3045 $result = $this->config_read($this->name);
3046 if (is_null($result)) {
3047 return NULL;
3048 }
3049 if ($result === '') {
3050 return array();
3051 }
3052 $settings = array();
3053 for ($i=0; $i<7; $i++) {
3054 if ($result & (1 << $i)) {
3055 $setting[] = $i;
3056 }
3057 }
3058 return $setting;
6e4dc10f 3059 }
eef868d1 3060
6e4dc10f 3061 function write_setting($data) {
220a90c5 3062 if (!is_array($data)) {
3063 return '';
3064 }
3065 unset($data['xxxxx']);
4af8d5d3 3066 $result = 0;
220a90c5 3067 foreach($data as $index) {
3068 $result |= 1 << $index;
6e4dc10f 3069 }
220a90c5 3070 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 3071 }
eef868d1 3072
220a90c5 3073 function output_html($data) {
4af8d5d3 3074 // The order matters very much because of the implied numeric keys
3075 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3076 $return = '<table><thead><tr>';
220a90c5 3077 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
4af8d5d3 3078 foreach($days as $index => $day) {
220a90c5 3079 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
4af8d5d3 3080 }
3081 $return .= '</tr></thead><tbody><tr>';
3082 foreach($days as $index => $day) {
220a90c5 3083 $return .= '<td><input type="checkbox" class="form-checkbox" id="'.$this->get_id().$index.'" name="'.$this->get_full_name().'[]" value="'.$index.'" '.(in_array("$index", $data) ? 'checked="checked"' : '').' /></td>';
4af8d5d3 3084 }
3085 $return .= '</tr></tbody></table>';
6153cf58 3086
220a90c5 3087 return format_admin_setting($this, $this->visiblename, $return, $this->description, false);
eef868d1 3088
6e4dc10f 3089 }
6e4dc10f 3090}
3091
220a90c5 3092
3d5c00b3 3093/**
220a90c5 3094 * Graded roles in gradebook
5a412dbf 3095 */
220a90c5 3096class admin_setting_special_gradebookroles extends admin_setting_configmulticheckbox {
0909d44e 3097 function admin_setting_special_gradebookroles() {
220a90c5 3098 parent::admin_setting_configmulticheckbox('gradebookroles', get_string('gradebookroles', 'admin'),
3099 get_string('configgradebookroles', 'admin'), NULL, NULL);
5a412dbf 3100 }
3101
220a90c5 3102 function load_choices() {
5a412dbf 3103 global $CFG;
220a90c5 3104 if (empty($CFG->rolesactive)) {
3105 return false;
3106 }
3107 if (is_array($this->choices)) {
3108 return true;
3109 }
3110 if ($roles = get_records('role')) {
3111 $this->choices = array();
3112 foreach($roles as $role) {
3113 $this->choices[$role->id] = format_string($role->name);
60f7d402 3114 }
220a90c5 3115 return true;
5a412dbf 3116 } else {
220a90c5 3117 return false;
5a412dbf 3118 }
3119 }
3120
220a90c5 3121 function get_defaultsetting() {
3122 global $CFG;
3123 if (empty($CFG->rolesactive)) {
3124 return NULL;
3125 }
3126 $result = array();
3127 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
3128 foreach ($studentroles as $studentrole) {
3129 $result[$studentrole->id] = '1';
5a412dbf 3130 }
73afaf5b 3131 }
220a90c5 3132 return $result;
5a412dbf 3133 }
220a90c5 3134}
5a412dbf 3135
220a90c5 3136/**
3137 * Which roles to show on course decription page
3138 */
3139class admin_setting_special_coursemanager extends admin_setting_configmulticheckbox {
3140 function admin_setting_special_coursemanager() {
3141 parent::admin_setting_configmulticheckbox('coursemanager', get_string('coursemanager', 'admin'),
3142 get_string('configcoursemanager', 'admin'), NULL, NULL);
3143 }
5a412dbf 3144
220a90c5 3145 function load_choices() {
3146 if (is_array($this->choices)) {
3147 return true;
5a412dbf 3148 }
5a412dbf 3149 if ($roles = get_records('role')) {
220a90c5 3150 $this->choices = array();
3151 foreach($roles as $role) {
3152 $this->choices[$role->id] = format_string($role->name);
5a412dbf 3153 }
220a90c5 3154 return true;
5a412dbf 3155 }
220a90c5 3156 return false;
3157 }
73afaf5b 3158
220a90c5 3159 function get_defaultsetting() {
3160 global $CFG;
3161 if (empty($CFG->rolesactive)) {
3162 return NULL;
3163 }
3164 $result = array();
3165 if ($teacherroles = get_roles_with_capability('moodle/legacy:editingteacher', CAP_ALLOW)) {
3166 foreach ($teacherroles as $teacherrole) {
3167 $result[$teacherrole->id] = '1';
3168 }
3169 }
3170 return $result;
3171 }
3172}
5a412dbf 3173
220a90c5 3174/**
3175 * Primary grade export plugin - has state tracking.
3176 */
3177class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
3178 function admin_setting_special_gradeexport() {
3179 parent::admin_setting_configmulticheckbox('gradeexport', get_string('gradeexport', 'admin'),
3180 get_string('configgradeexport', 'admin'), array(), NULL);
5a412dbf 3181 }
3182
220a90c5 3183 function load_choices() {
3184 if (is_array($this->choices)) {
3185 return true;
3186 }
3187 $this->choices = array();
3188
3189 if ($plugins = get_list_of_plugins('grade/export')) {
3190 foreach($plugins as $plugin) {
3191 $this->choices[$plugin] = get_string('modulename', 'gradeexport_'.$plugin);
3192 }
3193 }
3194 return true;
3195 }
5a412dbf 3196}
6e4dc10f 3197
220a90c5 3198/**
3199 * Grade category settings
d42c64ba 3200 */
220a90c5 3201class admin_setting_gradecat_combo extends admin_setting {
d42c64ba 3202
220a90c5 3203 var $choices;
3204
3205 function admin_setting_gradecat_combo($name, $visiblename, $description, $defaultsetting, $choices) {
3206 $this->choices = $choices;
3207 parent::admin_setting($name, $visiblename, $description, $defaultsetting);
d42c64ba 3208 }
3209
3210 function get_setting() {
d42c64ba 3211 global $CFG;
220a90c5 3212
3213 $value = $this->config_read($this->name);
3214 $flag = $this->config_read($this->name.'_flag');
3215
3216 if (is_null($value) or is_null($flag)) {
3217 return NULL;
d42c64ba 3218 }
220a90c5 3219
3220 $flag = (int)$flag;
3221 $forced = (boolean)(1 & $flag); // first bit
3222 $adv = (boolean)(2 & $flag); // second bit
3223
3224 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
d42c64ba 3225 }
3226
3227 function write_setting($data) {
220a90c5 3228 global $CFG;
d42c64ba 3229
220a90c5 3230 $value = $data['value'];
3231 $forced = empty($data['forced']) ? 0 : 1;
3232 $adv = empty($data['adv']) ? 0 : 2;
3233 $flag = ($forced | $adv); //bitwise or
3234
3235 if (!in_array($value, array_keys($this->choices))) {
3236 return 'Error setting ';
3237 }
3238
3239 $oldvalue = $this->config_read($this->name);
3240 $oldflag = (int)$this->config_read($this->name.'_flag');
3241 $oldforced = (1 & $oldflag); // first bit
3242
3243 $result1 = $this->config_write($this->name, $value);
3244 $result2 = $this->config_write($this->name.'_flag', $flag);
3245
3246 // force regrade if needed
3247 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
3248 require_once($CFG->libdir.'/gradelib.php');
3249 grade_category::updated_forced_settings();
3250 }
3251
3252 if ($result1 and $result2) {
3253 return '';
d42c64ba 3254 } else {
220a90c5 3255 return get_string('errorsetting', 'admin');
d42c64ba 3256 }
3257 }
3258
220a90c5 3259 function output_html($data) {
3260 $value = $data['value'];
3261 $forced = !empty($data['forced']);
3262 $adv = !empty($data['adv']);
d42c64ba 3263
220a90c5 3264 $return = '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
3265 foreach ($this->choices as $key => $val) {
3266 // the string cast is needed because key may be integer - 0 is equal to most strings!
3267 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
3268 }
3269 $return .= '</select>';
3270 $return .= '</label><input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
3271 .'<label for="'.$this->get_id().'force">'.get_string('force');
3272 $return .= '</label><input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
3273 .'<label for="'.$this->get_id().'adv">'.get_string('advanced');
3274
3275 return format_admin_setting($this, $this->visiblename, $return, $this->description);
3276 }
3277}
3278
3279
3280/**
3281 * Selection of grade report in user profiles
3282 */
3283class admin_setting_grade_profilereport extends admin_setting_configselect {
3284 function admin_setting_grade_profilereport() {
3285 parent::admin_setting_configselect('grade_profilereport', get_string('profilereport', 'grades'), get_string('configprofilereport', 'grades'), 'user', null);
3286 }
3287
3288 function load_choices() {
3289 if (is_array($this->choices)) {
3290 return true;
3291 }
3292 $this->choices = array();
3293
3294 global $CFG;
3295 require_once($CFG->libdir.'/gradelib.php');
3296
3297 foreach (get_list_of_plugins('grade/report') as $plugin) {
3298 if (file_exists($CFG->dirroot.'/grade/report/'.$plugin.'/lib.php')) {
3299 require_once($CFG->dirroot.'/grade/report/'.$plugin.'/lib.php');
3300 $functionname = 'grade_report_'.$plugin.'_profilereport';
3301 if (function_exists($functionname)) {
3302 $this->choices[$plugin] = get_string('modulename', 'gradereport_'.$plugin, NULL, $CFG->dirroot.'/grade/report/'.$plugin.'/lang/');
d42c64ba 3303 }
d42c64ba 3304 }
d42c64ba 3305 }
220a90c5 3306 return true;
d42c64ba 3307 }
3308}
3309
220a90c5 3310/**
3311 * Special class for register auth selection
76127f37 3312 */
220a90c5 3313class admin_setting_special_registerauth extends admin_setting_configselect {
3314 function admin_setting_special_registerauth() {
3315 parent::admin_setting_configselect('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), 'email', null);
76127f37 3316 }
3317
220a90c5 3318 function get_defaultsettings() {
3319 $this->load_choices();
3320 if (array_key_exists($this->defaultsetting, $this->choices)) {
3321 return $this->defaultsetting;
3322 } else {
3323 return '';
3324 }
3325 }
76127f37 3326
220a90c5 3327 function load_choices() {
76127f37 3328 global $CFG;
220a90c5 3329
3330 if (is_array($this->choices)) {
3331 return true;
3332 }
3333 $this->choices = array();
3334 $this->choices[''] = get_string('disable');
3335
3336 $authsenabled = get_enabled_auth_plugins(true);
3337
3338 foreach ($authsenabled as $auth) {
3339 $authplugin = get_auth_plugin($auth);
3340 if (!$authplugin->can_signup()) {
3341 continue;
76127f37 3342 }
220a90c5 3343 // Get the auth title (from core or own auth lang files)
3344 $authtitle = get_string("auth_{$auth}title", "auth");
3345 if ($authtitle == "[[auth_{$auth}title]]") {
3346 $authtitle = get_string("auth_{$auth}title", "auth_{$auth}");
3347 }
3348 $this->choices[$auth] = $authtitle;
76127f37 3349 }
220a90c5 3350 return true;
76127f37 3351 }
220a90c5 3352}
76127f37 3353
220a90c5 3354/**
3355 * Module manage page
3356 */
3357class admin_page_managemods extends admin_externalpage {
3358 function admin_page_managemods() {
3359 global $CFG;
3360 parent::admin_externalpage('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
3361 }
76127f37 3362
220a90c5 3363 function search($query) {
3364 if (parent::search($query)) {
3365 return true;
3366 }
3367
3368 $found = false;
3369 if ($modules = get_records('modules')) {
3370 $textlib = textlib_get_instance();
3371 foreach ($modules as $module) {
3372 if (strpos($module->name, $query) !== false) {
3373 $found = true;
3374 break;
3375 }
3376 $strmodulename = get_string('modulename', $module->name);
3377 if (strpos($textlib->strtolower($strmodulename), $query) !== false) {
3378 $found = true;
3379 break;
76127f37 3380 }
3381 }
220a90c5 3382 }
3383 if ($found) {
3384 $result = new object();
3385 $result->page = $this;
3386 $result->settings = array();
3387 return array($this->name => $result);
76127f37 3388 } else {
220a90c5 3389 return array();
76127f37 3390 }
3391 }
220a90c5 3392}
76127f37 3393
220a90c5 3394/**
3395 * Blocks manage page
3396 */
3397class admin_page_manageblocks extends admin_externalpage {
3398 function admin_page_manageblocks() {
3399 global $CFG;
3400 parent::admin_externalpage('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
3401 }
76127f37 3402
220a90c5 3403 function search($query) {
3404 global $CFG;
3405 if (parent::search($query)) {
3406 return true;
3407 }
3408
3409 $found = false;
3410 if (!empty($CFG->blocks_version) and $blocks = get_records('block')) {
3411 $textlib = textlib_get_instance();
3412 foreach ($blocks as $block) {
3413 if (strpos($block->name, $query) !== false) {
3414 $found = true;
3415 break;
76127f37 3416 }
220a90c5 3417 $strblockname = get_string('blockname', 'block_'.$block->name);
3418 if (strpos($textlib->strtolower($strblockname), $query) !== false) {
3419 $found = true;
3420 break;
76127f37 3421 }
76127f37 3422 }
76127f37 3423 }
220a90c5 3424 if ($found) {
3425 $result = new object();
3426 $result->page = $this;
3427 $result->settings = array();
3428 return array($this->name => $result);
3429 } else {
3430 return array();
3431 }
76127f37 3432 }
3433}
3434
220a90c5 3435/**
3436 * Special class for authentication administration.
3437 */
3438class admin_setting_manageauths extends admin_setting {
3439 function admin_setting_manageauths() {
3440 parent::admin_setting('authsui', get_string('authsettings', 'admin'), '', '');
3441 }
76127f37 3442
220a90c5 3443 function get_setting() {
3444 return true;
3445 }
76127f37 3446