Пример #1
3
 /**
  * Reset contents of all database tables to initial values, reset caches, etc.
  *
  * Note: this is relatively slow (cca 2 seconds for pg and 7 for mysql) - please use with care!
  *
  * @static
  * @param bool $detectchanges
  *      true  - changes in global state and database are reported as errors
  *      false - no errors reported
  *      null  - only critical problems are reported as errors
  * @return void
  */
 public static function reset_all_data($detectchanges = false)
 {
     global $DB, $CFG, $USER, $SITE, $COURSE, $PAGE, $OUTPUT, $SESSION;
     // Stop any message redirection.
     phpunit_util::stop_message_redirection();
     // Stop any message redirection.
     phpunit_util::stop_phpmailer_redirection();
     // Stop any message redirection.
     phpunit_util::stop_event_redirection();
     // We used to call gc_collect_cycles here to ensure desctructors were called between tests.
     // This accounted for 25% of the total time running phpunit - so we removed it.
     // Show any unhandled debugging messages, the runbare() could already reset it.
     self::display_debugging_messages();
     self::reset_debugging();
     // reset global $DB in case somebody mocked it
     $DB = self::get_global_backup('DB');
     if ($DB->is_transaction_started()) {
         // we can not reset inside transaction
         $DB->force_transaction_rollback();
     }
     $resetdb = self::reset_database();
     $warnings = array();
     if ($detectchanges === true) {
         if ($resetdb) {
             $warnings[] = 'Warning: unexpected database modification, resetting DB state';
         }
         $oldcfg = self::get_global_backup('CFG');
         $oldsite = self::get_global_backup('SITE');
         foreach ($CFG as $k => $v) {
             if (!property_exists($oldcfg, $k)) {
                 $warnings[] = 'Warning: unexpected new $CFG->' . $k . ' value';
             } else {
                 if ($oldcfg->{$k} !== $CFG->{$k}) {
                     $warnings[] = 'Warning: unexpected change of $CFG->' . $k . ' value';
                 }
             }
             unset($oldcfg->{$k});
         }
         if ($oldcfg) {
             foreach ($oldcfg as $k => $v) {
                 $warnings[] = 'Warning: unexpected removal of $CFG->' . $k;
             }
         }
         if ($USER->id != 0) {
             $warnings[] = 'Warning: unexpected change of $USER';
         }
         if ($COURSE->id != $oldsite->id) {
             $warnings[] = 'Warning: unexpected change of $COURSE';
         }
     }
     if (ini_get('max_execution_time') != 0) {
         // This is special warning for all resets because we do not want any
         // libraries to mess with timeouts unintentionally.
         // Our PHPUnit integration is not supposed to change it either.
         if ($detectchanges !== false) {
             $warnings[] = 'Warning: max_execution_time was changed to ' . ini_get('max_execution_time');
         }
         set_time_limit(0);
     }
     // restore original globals
     $_SERVER = self::get_global_backup('_SERVER');
     $CFG = self::get_global_backup('CFG');
     $SITE = self::get_global_backup('SITE');
     $_GET = array();
     $_POST = array();
     $_FILES = array();
     $_REQUEST = array();
     $COURSE = $SITE;
     // reinitialise following globals
     $OUTPUT = new bootstrap_renderer();
     $PAGE = new moodle_page();
     $FULLME = null;
     $ME = null;
     $SCRIPT = null;
     // Empty sessison and set fresh new not-logged-in user.
     \core\session\manager::init_empty_session();
     // reset all static caches
     \core\event\manager::phpunit_reset();
     accesslib_clear_all_caches(true);
     get_string_manager()->reset_caches(true);
     reset_text_filters_cache(true);
     events_get_handlers('reset');
     core_text::reset_caches();
     get_message_processors(false, true);
     filter_manager::reset_caches();
     // Reset internal users.
     core_user::reset_internal_users();
     //TODO MDL-25290: add more resets here and probably refactor them to new core function
     // Reset course and module caches.
     if (class_exists('format_base')) {
         // If file containing class is not loaded, there is no cache there anyway.
         format_base::reset_course_cache(0);
     }
     get_fast_modinfo(0, 0, true);
     // Reset other singletons.
     if (class_exists('core_plugin_manager')) {
         core_plugin_manager::reset_caches(true);
     }
     if (class_exists('\\core\\update\\checker')) {
         \core\update\checker::reset_caches(true);
     }
     if (class_exists('\\core\\update\\deployer')) {
         \core\update\deployer::reset_caches(true);
     }
     // purge dataroot directory
     self::reset_dataroot();
     // restore original config once more in case resetting of caches changed CFG
     $CFG = self::get_global_backup('CFG');
     // inform data generator
     self::get_data_generator()->reset();
     // fix PHP settings
     error_reporting($CFG->debug);
     // verify db writes just in case something goes wrong in reset
     if (self::$lastdbwrites != $DB->perf_get_writes()) {
         error_log('Unexpected DB writes in phpunit_util::reset_all_data()');
         self::$lastdbwrites = $DB->perf_get_writes();
     }
     if ($warnings) {
         $warnings = implode("\n", $warnings);
         trigger_error($warnings, E_USER_WARNING);
     }
 }
 protected function definition()
 {
     global $CFG, $OUTPUT;
     $mform =& $this->_form;
     $indicators = $this->_customdata['indicators'];
     $mform->addElement('hidden', 'id', $this->_customdata['id']);
     $mform->setType('id', PARAM_INT);
     // TODO: general course-level report settings.
     $mform->addElement('header', 'general', get_string('pluginname', 'report_engagement'));
     $mform->addElement('header', 'weightings', get_string('weighting', 'report_engagement'));
     $mform->addElement('static', 'weightings_desc', get_string('indicator', 'report_engagement'));
     $mform->addHelpButton('weightings_desc', 'indicator', 'report_engagement');
     foreach ($indicators as $name => $path) {
         $grouparray = array();
         $grouparray[] =& $mform->createElement('text', "weighting_{$name}", '', array('size' => 3));
         $grouparray[] =& $mform->createElement('static', '', '', '%');
         $mform->addGroup($grouparray, "weight_group_{$name}", get_string('pluginname', "engagementindicator_{$name}"), ' ', false);
         $mform->addHelpButton("weight_group_{$name}", 'pluginname', "engagementindicator_{$name}");
         $mform->setType("weighting_{$name}", PARAM_FLOAT);
     }
     $pluginman = core_plugin_manager::instance();
     $instances = get_plugin_list('engagementindicator');
     foreach ($indicators as $name => $path) {
         $plugin = $pluginman->get_plugin_info('engagementindicator_' . $name);
         $file = "{$CFG->dirroot}/mod/engagement/indicator/{$name}/thresholds_form.php";
         if (file_exists($file) && $plugin->is_enabled()) {
             require_once $file;
             $class = "engagementindicator_{$name}_thresholds_form";
             $subform = new $class();
             $mform->addElement('header', 'general', get_string('pluginname', "engagementindicator_{$name}"));
             $subform->definition_inner($mform);
         }
     }
     $this->add_action_buttons();
 }
 /**
  * Constructor.
  * @throws            Command_Exception.
  */
 public function __construct()
 {
     global $DB, $STANDARD_PLUGIN_TYPES;
     // Getting command description.
     $cmd_name = vmoodle_get_string('cmdpluginsetupname', 'vmoodleadminset_plugins');
     $cmd_desc = vmoodle_get_string('cmdpluginsetupdesc', 'vmoodleadminset_plugins');
     $pm = \core_plugin_manager::instance();
     $allplugins = $pm->get_plugins();
     $pluginlist = array();
     foreach ($allplugins as $type => $plugins) {
         foreach ($plugins as $p) {
             if (array_key_exists($type, $STANDARD_PLUGIN_TYPES)) {
                 $pluginlist[$type . '/' . $p->name] = $STANDARD_PLUGIN_TYPES[$type] . ' : ' . $p->displayname;
             }
         }
     }
     asort($pluginlist, SORT_STRING);
     $plugin_param = new Command_Parameter('plugin', 'enum', vmoodle_get_string('pluginparamdesc', 'vmoodleadminset_plugins'), null, $pluginlist);
     $states = array();
     $states['enable'] = vmoodle_get_string('enable', 'vmoodleadminset_plugins');
     $states['disable'] = vmoodle_get_string('disable', 'vmoodleadminset_plugins');
     $state_param = new Command_Parameter('state', 'enum', vmoodle_get_string('pluginstateparamdesc', 'vmoodleadminset_plugins'), null, $states);
     // Creating command.
     parent::__construct($cmd_name, $cmd_desc, array($plugin_param, $state_param));
 }
Пример #4
0
 /**
  * Creates a new instance of the portfolio plugin
  *
  * @param string $name name of the instance
  * @param stdClass $data config data for the instance
  * @return portfolio_plugin_base
  */
 protected function enable_plugin($name = 'Instance name', $data = null)
 {
     $data = $data ?: new stdClass();
     $instance = portfolio_static_function($this->pluginname, 'create_instance', $this->pluginname, $name, $data);
     core_plugin_manager::reset_caches();
     return $instance;
 }
Пример #5
0
 /**
  * Allows us to inject items directly into the plugins info tree.
  *
  * Do not forget to call our reset_caches() after using this method to force a new
  * singleton instance.
  *
  * @param string $type plugin type
  * @param string $name plugin name
  * @param \core\plugininfo\base $plugininfo plugin info class
  */
 public function inject_testable_plugininfo($type, $name, \core\plugininfo\base $plugininfo)
 {
     // Let the parent initialize the ->pluginsinfo tree.
     parent::get_plugins();
     // Inject the additional plugin info.
     $this->pluginsinfo[$type][$name] = $plugininfo;
 }
Пример #6
0
 /**
  * Retrieve the list of available filter options.
  *
  * @return  array                   An array whose keys are the valid options
  *                                  And whose values are the values to display
  */
 public static function get_filter_options()
 {
     $manager = \core_plugin_manager::instance();
     $themes = $manager->get_installed_plugins('theme');
     $options = [];
     foreach (array_keys($themes) as $themename) {
         try {
             $theme = \theme_config::load($themename);
         } catch (Exception $e) {
             // Bad theme, just skip it for now.
             continue;
         }
         if ($themename !== $theme->name) {
             // Obsoleted or broken theme, just skip for now.
             continue;
         }
         if ($theme->hidefromselector) {
             // The theme doesn't want to be shown in the theme selector and as theme
             // designer mode is switched off we will respect that decision.
             continue;
         }
         $options[$theme->name] = get_string('pluginname', "theme_{$theme->name}");
     }
     return $options;
 }
Пример #7
0
 /**
  * Gathers and returns the information about all plugins of the given type,
  * either on disk or previously installed.
  *
  * @param string $type the name of the plugintype, eg. mod, auth or workshopform
  * @param string $typerootdir full path to the location of the plugin dir
  * @param string $typeclass the name of the actually called class
  * @param core_plugin_manager $pluginman the plugin manager calling this method
  * @return array of plugintype classes, indexed by the plugin name
  */
 public static function get_plugins($type, $typerootdir, $typeclass, $pluginman)
 {
     $return = array();
     $plugins = $pluginman->get_installed_plugins($type);
     foreach ($plugins as $name => $version) {
         $plugin = new $typeclass();
         $plugin->type = $type;
         $plugin->typerootdir = $typerootdir;
         $plugin->name = $name;
         $plugin->rootdir = null;
         $plugin->displayname = $name;
         $plugin->versiondb = $version;
         $plugin->pluginman = $pluginman;
         $plugin->init_is_standard();
         $return[$name] = $plugin;
     }
     return $return;
 }
Пример #8
0
 public function execute()
 {
     $manager = \core_plugin_manager::instance();
     $types = $manager->get_plugin_types();
     ksort($types);
     foreach ($types as $type => $directory) {
         echo $type . "," . $directory . "\n";
     }
 }
Пример #9
0
 public function definition()
 {
     $mform = $this->_form;
     /** @var \core\task\scheduled_task $task */
     $task = $this->_customdata;
     $plugininfo = core_plugin_manager::instance()->get_plugin_info($task->get_component());
     $plugindisabled = $plugininfo && $plugininfo->is_enabled() === false && !$task->get_run_if_component_disabled();
     $lastrun = $task->get_last_run_time() ? userdate($task->get_last_run_time()) : get_string('never');
     $nextrun = $task->get_next_run_time();
     if ($plugindisabled) {
         $nextrun = get_string('plugindisabled', 'tool_task');
     } else {
         if ($task->get_disabled()) {
             $nextrun = get_string('taskdisabled', 'tool_task');
         } else {
             if ($nextrun > time()) {
                 $nextrun = userdate($nextrun);
             } else {
                 $nextrun = get_string('asap', 'tool_task');
             }
         }
     }
     $mform->addElement('static', 'lastrun', get_string('lastruntime', 'tool_task'), $lastrun);
     $mform->addElement('static', 'nextrun', get_string('nextruntime', 'tool_task'), $nextrun);
     $mform->addElement('text', 'minute', get_string('taskscheduleminute', 'tool_task'));
     $mform->setType('minute', PARAM_RAW);
     $mform->addHelpButton('minute', 'taskscheduleminute', 'tool_task');
     $mform->addElement('text', 'hour', get_string('taskschedulehour', 'tool_task'));
     $mform->setType('hour', PARAM_RAW);
     $mform->addHelpButton('hour', 'taskschedulehour', 'tool_task');
     $mform->addElement('text', 'day', get_string('taskscheduleday', 'tool_task'));
     $mform->setType('day', PARAM_RAW);
     $mform->addHelpButton('day', 'taskscheduleday', 'tool_task');
     $mform->addElement('text', 'month', get_string('taskschedulemonth', 'tool_task'));
     $mform->setType('month', PARAM_RAW);
     $mform->addHelpButton('month', 'taskschedulemonth', 'tool_task');
     $mform->addElement('text', 'dayofweek', get_string('taskscheduledayofweek', 'tool_task'));
     $mform->setType('dayofweek', PARAM_RAW);
     $mform->addHelpButton('dayofweek', 'taskscheduledayofweek', 'tool_task');
     $mform->addElement('advcheckbox', 'disabled', get_string('disabled', 'tool_task'));
     $mform->addHelpButton('disabled', 'disabled', 'tool_task');
     $mform->addElement('advcheckbox', 'resettodefaults', get_string('resettasktodefaults', 'tool_task'));
     $mform->addHelpButton('resettodefaults', 'resettasktodefaults', 'tool_task');
     $mform->disabledIf('minute', 'resettodefaults', 'checked');
     $mform->disabledIf('hour', 'resettodefaults', 'checked');
     $mform->disabledIf('day', 'resettodefaults', 'checked');
     $mform->disabledIf('dayofweek', 'resettodefaults', 'checked');
     $mform->disabledIf('month', 'resettodefaults', 'checked');
     $mform->disabledIf('disabled', 'resettodefaults', 'checked');
     $mform->addElement('hidden', 'task', get_class($task));
     $mform->setType('task', PARAM_RAW);
     $mform->addElement('hidden', 'action', 'edit');
     $mform->setType('action', PARAM_ALPHANUMEXT);
     $this->add_action_buttons(true, get_string('savechanges'));
     // Do not use defaults for existing values, the set_data() is the correct way.
     $this->set_data(\core\task\manager::record_from_scheduled_task($task));
 }
 /**
  * Tests the plugininfo class is present and working.
  */
 public function test_plugin_info()
 {
     // This code will throw debugging information if the plugininfo class
     // is missing. Unfortunately it doesn't actually cause the test to
     // fail, but it's obvious when running test at least.
     $pluginmanager = core_plugin_manager::instance();
     $list = $pluginmanager->get_enabled_plugins('availability');
     $this->assertEquals(array('completion', 'date', 'grade', 'group', 'grouping', 'profile'), array_keys($list));
 }
Пример #11
0
 /**
  * Returns a target object, given a name.
  */
 public static function create_target($name, $identifier = '')
 {
     // Sanity check.
     $pluginman = \core_plugin_manager::instance();
     $plugins = $pluginman->get_plugins_of_type('cattarget');
     if (!isset($plugins[$name]) || $plugins[$name]->is_enabled() === false) {
         throw new \moodle_exception("Invalid target.");
     }
     $target = "\\cattarget_{$name}\\{$name}";
     return new $target($identifier);
 }
Пример #12
0
 /**
  * Return a rule object, given a name.
  */
 public static function create_rule($name, $config = null)
 {
     // Sanity check.
     $pluginman = \core_plugin_manager::instance();
     $plugins = $pluginman->get_plugins_of_type('catrule');
     if (!isset($plugins[$name]) || $plugins[$name]->is_enabled() === false) {
         throw new \moodle_exception("Invalid rule.");
     }
     $ruletype = "\\catrule_{$name}\\{$name}";
     return new $ruletype($config);
 }
Пример #13
0
 /**
  * Return a activity object, given a name.
  */
 public static function create_activity($name, $data = '')
 {
     // Sanity check.
     $pluginman = \core_plugin_manager::instance();
     $plugins = $pluginman->get_plugins_of_type('catactivity');
     if (!isset($plugins[$name]) || $plugins[$name]->is_enabled() === false) {
         throw new \moodle_exception("Invalid activity.");
     }
     $activity = "\\catactivity_{$name}\\{$name}";
     return new $activity($data);
 }
Пример #14
0
 /**
  * This function will render one beautiful table with all the scheduled tasks.
  *
  * @param \core\task\scheduled_task[] $tasks - list of all scheduled tasks.
  * @return string HTML to output.
  */
 public function scheduled_tasks_table($tasks)
 {
     global $CFG;
     $table = new html_table();
     $table->head = array(get_string('name'), get_string('component', 'tool_task'), get_string('edit'), get_string('lastruntime', 'tool_task'), get_string('nextruntime', 'tool_task'), get_string('taskscheduleminute', 'tool_task'), get_string('taskschedulehour', 'tool_task'), get_string('taskscheduleday', 'tool_task'), get_string('taskscheduledayofweek', 'tool_task'), get_string('taskschedulemonth', 'tool_task'), get_string('faildelay', 'tool_task'), get_string('default', 'tool_task'));
     $table->attributes['class'] = 'admintable generaltable';
     $data = array();
     $yes = get_string('yes');
     $no = get_string('no');
     $never = get_string('never');
     $asap = get_string('asap', 'tool_task');
     $disabled = get_string('disabled', 'tool_task');
     foreach ($tasks as $task) {
         $customised = $task->is_customised() ? $no : $yes;
         $lastrun = $task->get_last_run_time() ? userdate($task->get_last_run_time()) : $never;
         $nextrun = $task->get_next_run_time();
         if ($task->get_disabled()) {
             $nextrun = $disabled;
         } else {
             if ($nextrun > time()) {
                 $nextrun = userdate($nextrun);
             } else {
                 $nextrun = $asap;
             }
         }
         if (empty($CFG->preventscheduledtaskchanges)) {
             $configureurl = new moodle_url('/admin/tool/task/scheduledtasks.php', array('action' => 'edit', 'task' => get_class($task)));
             $editlink = $this->action_icon($configureurl, new pix_icon('t/edit', get_string('edittaskschedule', 'tool_task', $task->get_name())));
         } else {
             $editlink = $this->render(new pix_icon('t/locked', get_string('scheduledtaskchangesdisabled', 'tool_task')));
         }
         $namecell = new html_table_cell($task->get_name() . "\n" . html_writer::tag('span', '\\' . get_class($task), array('class' => 'task-class')));
         $namecell->header = true;
         $component = $task->get_component();
         list($type, $plugin) = core_component::normalize_component($component);
         if ($type === 'core') {
             $componentcell = new html_table_cell(get_string('corecomponent', 'tool_task'));
         } else {
             if ($plugininfo = core_plugin_manager::instance()->get_plugin_info($component)) {
                 $plugininfo->init_display_name();
                 $componentcell = new html_table_cell($plugininfo->displayname);
             } else {
                 $componentcell = new html_table_cell($component);
             }
         }
         $row = new html_table_row(array($namecell, $componentcell, new html_table_cell($editlink), new html_table_cell($lastrun), new html_table_cell($nextrun), new html_table_cell($task->get_minute()), new html_table_cell($task->get_hour()), new html_table_cell($task->get_day()), new html_table_cell($task->get_day_of_week()), new html_table_cell($task->get_month()), new html_table_cell($task->get_fail_delay()), new html_table_cell($customised)));
         if ($task->get_disabled()) {
             $row->attributes['class'] = 'disabled';
         }
         $data[] = $row;
     }
     $table->data = $data;
     return html_writer::table($table);
 }
Пример #15
0
 /**
  * Finds all plugins the user can instantiate in the context. The result may include missing plugins.
  * Calls {@link \mod_dataform\plugininfo\dataformview::is_instantiable()}.
  * Returns an associative list $pluginname => $pluginname, or null if no plugin is instantiable.
  *
  * @param context $context Either course or dataform (module) context.
  * @return array|null
  */
 public static function get_instantiable_plugins($context)
 {
     $return = array();
     if (!($plugins = \core_plugin_manager::instance()->get_plugins_of_type('dataformview'))) {
         return null;
     }
     foreach ($plugins as $name => $plugin) {
         if ($plugin->is_instantiable($context)) {
             $return[$name] = $name;
         }
     }
     return $return;
 }
Пример #16
0
 /**
  * Return a list of datatypes this target supports.
  *
  * @return array An array of valid datatypes.
  */
 public function get_supported_activities()
 {
     $pluginman = \core_plugin_manager::instance();
     $plugins = $pluginman->get_plugins_of_type('catactivity');
     $rules = array();
     foreach ($plugins as $plugin) {
         if ($plugin->is_enabled() === false) {
             continue;
         }
         $rules[] = $plugin->name;
     }
     return $rules;
 }
Пример #17
0
 /**
  * Return a datatype object, given a name.
  */
 public static function create_datatype($name, $data = '')
 {
     // Sanity check.
     $pluginman = \core_plugin_manager::instance();
     $plugins = $pluginman->get_plugins_of_type('catdatatype');
     if (!isset($plugins[$name]) || $plugins[$name]->is_enabled() === false) {
         throw new \moodle_exception("Invalid datatype.");
     }
     $datatype = "\\catdatatype_{$name}\\{$name}";
     $datatype = new $datatype($data);
     $datatype->name = $name;
     return $datatype;
 }
Пример #18
0
 /**
  * Get a list of valid rules.
  *
  * @return array [string]
  * @throws \invalid_parameter_exception
  */
 public static function get_rules()
 {
     $pluginman = \core_plugin_manager::instance();
     $plugins = $pluginman->get_plugins_of_type('catrule');
     $rules = array();
     foreach ($plugins as $plugin) {
         if ($plugin->is_enabled() === false) {
             continue;
         }
         $rules[$plugin->name] = get_string('prettyname', "{$plugin->type}_{$plugin->name}");
     }
     return $rules;
 }
Пример #19
0
 public static function get_services($plugin)
 {
     $services = array();
     $pluginmanager = \core_plugin_manager::instance();
     $plugininfo = $pluginmanager->get_plugin_info($plugin);
     if (is_null($plugininfo)) {
         return;
     }
     $defsfile = $plugininfo->rootdir . '/db/local_nagios.php';
     if (!file_exists($defsfile)) {
         return;
     }
     include $defsfile;
     return $services;
 }
Пример #20
0
 public static function get_enabled_plugins()
 {
     global $DB;
     // Get all available plugins.
     $plugins = \core_plugin_manager::instance()->get_installed_plugins('availability');
     if (!$plugins) {
         return array();
     }
     // Check they are enabled using get_config (which is cached and hopefully fast).
     $enabled = array();
     foreach ($plugins as $plugin => $version) {
         $disabled = get_config('availability_' . $plugin, 'disabled');
         if (empty($disabled)) {
             $enabled[$plugin] = $plugin;
         }
     }
     return $enabled;
 }
Пример #21
0
/**
 * Perform the post-install procedures.
 */
function xmldb_tool_usertours_install()
{
    global $DB;
    $localplugin = core_plugin_manager::instance()->get_plugin_info('local_usertours');
    if ($localplugin) {
        // If the old local plugin was previously installed, copy over the data from the old tables.
        // The 'comment' field was renamed to 'description' in:
        // * 3.0 version 2015111604
        // * 3.1 version 2016052303
        // We need to attempt to fetch comment for these older versions.
        $hasdescription = $localplugin->versiondb < 2016052301 && $localplugin->versiondb >= 2015111604;
        $hasdescription = $hasdescription || $localplugin->versiondb > 2016052303;
        $tours = $DB->get_recordset('usertours_tours');
        $mapping = [];
        foreach ($tours as $tour) {
            if (!$hasdescription) {
                if (property_exists($tour, 'comment')) {
                    $tour->description = $tour->comment;
                    unset($tour->comment);
                } else {
                    $tour->description = '';
                }
            }
            $mapping[$tour->id] = $DB->insert_record('tool_usertours_tours', $tour);
        }
        $tours->close();
        $steps = $DB->get_recordset('usertours_steps');
        foreach ($steps as $step) {
            if (!isset($mapping[$step->tourid])) {
                // Skip this one. It has somehow become orphaned.
                continue;
            }
            $step->tourid = $mapping[$step->tourid];
            $DB->insert_record('tool_usertours_steps', $step);
        }
        $steps->close();
        // Delete the old records.
        $DB->delete_records('usertours_steps', null);
        $DB->delete_records('usertours_tours', null);
    }
    // Update the tours shipped with Moodle.
    manager::update_shipped_tours();
}
Пример #22
0
function report_engagement_get_course_summary($courseid)
{
    global $CFG, $DB;
    $risks = array();
    // TODO: We want this to rely on enabled indicators in the course...
    $pluginman = core_plugin_manager::instance();
    $instances = get_plugin_list('engagementindicator');
    $weightings = $DB->get_records_menu('report_engagement', array('course' => $courseid), '', 'indicator, weight');
    if (!$weightings && count($instances)) {
        // Setup default weightings, all equal.
        $weight = sprintf('%.2f', 1 / count($instances));
        foreach ($instances as $name => $path) {
            $record = new stdClass();
            $record->course = $courseid;
            $record->indicator = $name;
            $record->weight = $weight;
            $record->configdata = null;
            $wid = $DB->insert_record('report_engagement', $record);
            $weightings[$name] = $weight;
        }
    }
    foreach ($instances as $name => $path) {
        $plugin = $pluginman->get_plugin_info('engagementindicator_' . $name);
        if ($plugin->is_enabled() && file_exists("{$path}/indicator.class.php")) {
            require_once "{$path}/indicator.class.php";
            $classname = "indicator_{$name}";
            $indicator = new $classname($courseid);
            $indicatorrisks = $indicator->get_course_risks();
            $weight = isset($weightings[$name]) ? $weightings[$name] : 0;
            foreach ($indicatorrisks as $userid => $risk) {
                if (!isset($risks[$userid])) {
                    $risks[$userid] = 0;
                }
                $risks[$userid] += $risk->risk * $weight;
            }
        }
    }
    return $risks;
}
Пример #23
0
 /**
  * Obtains a raw list of player objects that includes objects regardless
  * of whether they are disabled or not, and without sorting.
  *
  * You can override this in a subclass if you need to add additional_
  * players.
  *
  * The return array is be indexed by player name to make it easier to
  * remove players in a subclass.
  *
  * @return array $players Array of core_media_player objects in any order
  */
 protected function get_players_raw()
 {
     $plugins = core_plugin_manager::instance()->get_plugins_of_type('media');
     $rv = [];
     foreach ($plugins as $name => $dir) {
         $classname = "media_" . $name . "_plugin";
         if (class_exists($classname)) {
             $rv[$name] = new $classname();
         }
     }
     return $rv;
 }
Пример #24
0
 /**
  * Decodes availability structure.
  *
  * This function also validates the retrieved data as follows:
  * 1. Data that does not meet the API-defined structure causes a
  *    coding_exception (this should be impossible unless there is
  *    a system bug or somebody manually hacks the database).
  * 2. Data that meets the structure but cannot be implemented (e.g.
  *    reference to missing plugin or to module that doesn't exist) is
  *    either silently discarded (if $lax is true) or causes a
  *    coding_exception (if $lax is false).
  *
  * @see decode_availability
  * @param \stdClass $structure Structure (decoded from JSON)
  * @param boolean $lax If true, throw exceptions only for invalid structure
  * @param boolean $root If true, this is the root tree
  * @return tree Availability tree
  * @throws \coding_exception If data is not valid structure
  */
 public function __construct($structure, $lax = false, $root = true)
 {
     $this->root = $root;
     // Check object.
     if (!is_object($structure)) {
         throw new \coding_exception('Invalid availability structure (not object)');
     }
     // Extract operator.
     if (!isset($structure->op)) {
         throw new \coding_exception('Invalid availability structure (missing ->op)');
     }
     $this->op = $structure->op;
     if (!in_array($this->op, array(self::OP_AND, self::OP_OR, self::OP_NOT_AND, self::OP_NOT_OR), true)) {
         throw new \coding_exception('Invalid availability structure (unknown ->op)');
     }
     // For root tree, get show options.
     $this->show = true;
     $this->showchildren = null;
     if ($root) {
         if ($this->op === self::OP_AND || $this->op === self::OP_NOT_OR) {
             // Per-child show options.
             if (!isset($structure->showc)) {
                 throw new \coding_exception('Invalid availability structure (missing ->showc)');
             }
             if (!is_array($structure->showc)) {
                 throw new \coding_exception('Invalid availability structure (->showc not array)');
             }
             foreach ($structure->showc as $value) {
                 if (!is_bool($value)) {
                     throw new \coding_exception('Invalid availability structure (->showc value not bool)');
                 }
             }
             // Set it empty now - add corresponding ones later.
             $this->showchildren = array();
         } else {
             // Entire tree show option. (Note: This is because when you use
             // OR mode, say you have A OR B, the user does not meet conditions
             // for either A or B. A is set to 'show' and B is set to 'hide'.
             // But they don't have either, so how do we know which one to do?
             // There might as well be only one value.)
             if (!isset($structure->show)) {
                 throw new \coding_exception('Invalid availability structure (missing ->show)');
             }
             if (!is_bool($structure->show)) {
                 throw new \coding_exception('Invalid availability structure (->show not bool)');
             }
             $this->show = $structure->show;
         }
     }
     // Get list of enabled plugins.
     $pluginmanager = \core_plugin_manager::instance();
     $enabled = $pluginmanager->get_enabled_plugins('availability');
     // For unit tests, also allow the mock plugin type (even though it
     // isn't configured in the code as a proper plugin).
     if (PHPUNIT_TEST) {
         $enabled['mock'] = true;
     }
     // Get children.
     if (!isset($structure->c)) {
         throw new \coding_exception('Invalid availability structure (missing ->c)');
     }
     if (!is_array($structure->c)) {
         throw new \coding_exception('Invalid availability structure (->c not array)');
     }
     if (is_array($this->showchildren) && count($structure->showc) != count($structure->c)) {
         throw new \coding_exception('Invalid availability structure (->c, ->showc mismatch)');
     }
     $this->children = array();
     foreach ($structure->c as $index => $child) {
         if (!is_object($child)) {
             throw new \coding_exception('Invalid availability structure (child not object)');
         }
         // First see if it's a condition. These have a defined type.
         if (isset($child->type)) {
             // Look for a plugin of this type.
             $classname = '\\availability_' . $child->type . '\\condition';
             if (!array_key_exists($child->type, $enabled)) {
                 if ($lax) {
                     // On load of existing settings, ignore if class
                     // doesn't exist.
                     continue;
                 } else {
                     throw new \coding_exception('Unknown condition type: ' . $child->type);
                 }
             }
             $this->children[] = new $classname($child);
         } else {
             // Not a condition. Must be a subtree.
             $this->children[] = new tree($child, $lax, false);
         }
         if (!is_null($this->showchildren)) {
             $this->showchildren[] = $structure->showc[$index];
         }
     }
 }
Пример #25
0
 /**
  * Return XHTML to display control
  *
  * @param mixed $data Unused
  * @param string $query
  * @return string highlight
  */
 public function output_html($data, $query = '')
 {
     global $CFG, $OUTPUT;
     $return = '';
     $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
     $return .= $OUTPUT->box_start('generalbox formatsui');
     $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
     // display strings
     $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
     $txt->uninstall = get_string('uninstallplugin', 'core_admin');
     $txt->updown = "{$txt->up}/{$txt->down}";
     $table = new html_table();
     $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
     $table->align = array('left', 'center', 'center', 'center', 'center');
     $table->attributes['class'] = 'manageformattable generaltable admintable';
     $table->data = array();
     $cnt = 0;
     $defaultformat = get_config('moodlecourse', 'format');
     $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
     foreach ($formats as $format) {
         $url = new moodle_url('/admin/courseformats.php', array('sesskey' => sesskey(), 'format' => $format->name));
         $isdefault = '';
         $class = '';
         if ($format->is_enabled()) {
             $strformatname = $format->displayname;
             if ($defaultformat === $format->name) {
                 $hideshow = $txt->default;
             } else {
                 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')), $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
             }
         } else {
             $strformatname = $format->displayname;
             $class = 'dimmed_text';
             $hideshow = html_writer::link($url->out(false, array('action' => 'enable')), $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
         }
         $updown = '';
         if ($cnt) {
             $updown .= html_writer::link($url->out(false, array('action' => 'up')), $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))) . '';
         } else {
             $updown .= $spacer;
         }
         if ($cnt < count($formats) - 1) {
             $updown .= '&nbsp;' . html_writer::link($url->out(false, array('action' => 'down')), $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
         } else {
             $updown .= $spacer;
         }
         $cnt++;
         $settings = '';
         if ($format->get_settings_url()) {
             $settings = html_writer::link($format->get_settings_url(), $txt->settings);
         }
         $uninstall = '';
         if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_' . $format->name, 'manage')) {
             $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
         }
         $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
         if ($class) {
             $row->attributes['class'] = $class;
         }
         $table->data[] = $row;
     }
     $return .= html_writer::table($table);
     $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
     $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
     $return .= $OUTPUT->box_end();
     return highlight($query, $return);
 }
Пример #26
0
 /**
  * Get the full list of observers for the system.
  *
  * @return array An array of observers in the system.
  */
 public static function get_observer_list()
 {
     $events = \core\event\manager::get_all_observers();
     foreach ($events as $key => $observers) {
         foreach ($observers as $observerskey => $observer) {
             $events[$key][$observerskey]->parentplugin = \core_plugin_manager::instance()->get_parent_of_subplugin($observer->plugintype);
         }
     }
     return $events;
 }
Пример #27
0
        $undeletable = '';
    } else {
        if (in_array($blockname, $undeletableblocktypes)) {
            $undeletable = '<a href="blocks.php?unprotect=' . $blockid . '&amp;sesskey=' . sesskey() . '" title="' . $strunprotect . '">' . '<img src="' . $OUTPUT->pix_url('t/unlock') . '" class="iconsmall" alt="' . $strunprotect . '" /></a>';
        } else {
            $undeletable = '<a href="blocks.php?protect=' . $blockid . '&amp;sesskey=' . sesskey() . '" title="' . $strprotect . '">' . '<img src="' . $OUTPUT->pix_url('t/lock') . '" class="iconsmall" alt="' . $strprotect . '" /></a>';
        }
    }
    $row = array($strblockname, $blocklist, $version, $visible, $undeletable, $settings, $uninstall);
    $table->add_data($row, $class);
}
$table->print_html();
if (!empty($incompatible)) {
    echo $OUTPUT->heading(get_string('incompatibleblocks', 'blockstable', 'admin'));
    $table = new flexible_table('admin-blocks-incompatible');
    $table->define_columns(array('block', 'uninstall'));
    $table->define_headers(array($strname, $struninstall));
    $table->define_baseurl($CFG->wwwroot . '/' . $CFG->admin . '/blocks.php');
    $table->set_attribute('class', 'incompatibleblockstable generaltable');
    $table->setup();
    foreach ($incompatible as $block) {
        if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('block_' . $block->name, 'manage')) {
            $uninstall = html_writer::link($uninstallurl, $struninstall);
        } else {
            $uninstall = '';
        }
        $table->add_data(array($block->name, $uninstall));
    }
    $table->print_html();
}
echo $OUTPUT->footer();
Пример #28
0
 /**
  * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
  * what can be shown/done
  *
  * @param int $courseid The current course' id
  * @param int $userid The user id to load for
  * @param string $gstitle The string to pass to get_string for the branch title
  * @return navigation_node|false
  */
 protected function generate_user_settings($courseid, $userid, $gstitle = 'usercurrentsettings')
 {
     global $DB, $CFG, $USER, $SITE;
     if ($courseid != $SITE->id) {
         if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
             $course = $this->page->course;
         } else {
             $select = context_helper::get_preload_record_columns_sql('ctx');
             $sql = "SELECT c.*, {$select}\n                          FROM {course} c\n                          JOIN {context} ctx ON c.id = ctx.instanceid\n                         WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
             $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
             $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
             context_helper::preload_from_record($course);
         }
     } else {
         $course = $SITE;
     }
     $coursecontext = context_course::instance($course->id);
     // Course context
     $systemcontext = context_system::instance();
     $currentuser = $USER->id == $userid;
     if ($currentuser) {
         $user = $USER;
         $usercontext = context_user::instance($user->id);
         // User context
     } else {
         $select = context_helper::get_preload_record_columns_sql('ctx');
         $sql = "SELECT u.*, {$select}\n                      FROM {user} u\n                      JOIN {context} ctx ON u.id = ctx.instanceid\n                     WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
         $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
         $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
         if (!$user) {
             return false;
         }
         context_helper::preload_from_record($user);
         // Check that the user can view the profile
         $usercontext = context_user::instance($user->id);
         // User context
         $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
         if ($course->id == $SITE->id) {
             if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) {
                 // Reduce possibility of "browsing" userbase at site level
                 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
                 return false;
             }
         } else {
             $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
             $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
             if (!$canviewusercourse && !$canviewuser || !$userisenrolled) {
                 return false;
             }
             $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
             if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
                 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
                 if ($courseid == $this->page->course->id) {
                     $mygroups = get_fast_modinfo($this->page->course)->groups;
                 } else {
                     $mygroups = groups_get_user_groups($courseid);
                 }
                 $usergroups = groups_get_user_groups($courseid, $userid);
                 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
                     return false;
                 }
             }
         }
     }
     $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
     $key = $gstitle;
     $prefurl = new moodle_url('/user/preferences.php');
     if ($gstitle != 'usercurrentsettings') {
         $key .= $userid;
         $prefurl->param('userid', $userid);
     }
     // Add a user setting branch.
     if ($gstitle == 'usercurrentsettings') {
         $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
         // This should be set to false as we don't want to show this to the user. It's only for generating the correct
         // breadcrumb.
         $dashboard->display = false;
         if (get_home_page() == HOMEPAGE_MY) {
             $dashboard->mainnavonly = true;
         }
         $iscurrentuser = $user->id == $USER->id;
         $baseargs = array('id' => $user->id);
         if ($course->id != $SITE->id && !$iscurrentuser) {
             $baseargs['course'] = $course->id;
             $issitecourse = false;
         } else {
             // Load all categories and get the context for the system.
             $issitecourse = true;
         }
         // Add the user profile to the dashboard.
         $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php', array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
         if (!empty($CFG->navadduserpostslinks)) {
             // Add nodes for forum posts and discussions if the user can view either or both
             // There are no capability checks here as the content of the page is based
             // purely on the forums the current user has access too.
             $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
             $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
             $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
         }
         // Add blog nodes.
         if (!empty($CFG->enableblogs)) {
             if (!$this->cache->cached('userblogoptions' . $user->id)) {
                 require_once $CFG->dirroot . '/blog/lib.php';
                 // Get all options for the user.
                 $options = blog_get_options_for_user($user);
                 $this->cache->set('userblogoptions' . $user->id, $options);
             } else {
                 $options = $this->cache->{'userblogoptions' . $user->id};
             }
             if (count($options) > 0) {
                 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
                 foreach ($options as $type => $option) {
                     if ($type == "rss") {
                         $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
                     } else {
                         $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
                     }
                 }
             }
         }
         // Add the messages link.
         // It is context based so can appear in the user's profile and in course participants information.
         if (!empty($CFG->messaging)) {
             $messageargs = array('user1' => $USER->id);
             if ($USER->id != $user->id) {
                 $messageargs['user2'] = $user->id;
             }
             if ($course->id != $SITE->id) {
                 $messageargs['viewing'] = MESSAGE_VIEW_COURSE . $course->id;
             }
             $url = new moodle_url('/message/index.php', $messageargs);
             $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
         }
         // Add the "My private files" link.
         // This link doesn't have a unique display for course context so only display it under the user's profile.
         if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
             $url = new moodle_url('/user/files.php');
             $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING);
         }
         // Add a node to view the users notes if permitted.
         if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
             $url = new moodle_url('/notes/index.php', array('user' => $user->id));
             if ($coursecontext->instanceid != SITEID) {
                 $url->param('course', $coursecontext->instanceid);
             }
             $profilenode->add(get_string('notes', 'notes'), $url);
         }
         // Show the grades node.
         if ($issitecourse && $iscurrentuser || has_capability('moodle/user:viewdetails', $usercontext)) {
             require_once $CFG->dirroot . '/user/lib.php';
             // Set the grades node to link to the "Grades" page.
             if ($course->id == SITEID) {
                 $url = user_mygrades_url($user->id, $course->id);
             } else {
                 // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
                 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
             }
             $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
         }
         // Let plugins hook into user navigation.
         $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
         foreach ($pluginsfunction as $plugintype => $plugins) {
             if ($plugintype != 'report') {
                 foreach ($plugins as $pluginfunction) {
                     $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
                 }
             }
         }
         $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
         $dashboard->add_node($usersetting);
     } else {
         $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
         $usersetting->display = false;
     }
     $usersetting->id = 'usersettings';
     // Check if the user has been deleted.
     if ($user->deleted) {
         if (!has_capability('moodle/user:update', $coursecontext)) {
             // We can't edit the user so just show the user deleted message.
             $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
         } else {
             // We can edit the user so show the user deleted message and link it to the profile.
             if ($course->id == $SITE->id) {
                 $profileurl = new moodle_url('/user/profile.php', array('id' => $user->id));
             } else {
                 $profileurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id));
             }
             $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
         }
         return true;
     }
     $userauthplugin = false;
     if (!empty($user->auth)) {
         $userauthplugin = get_auth_plugin($user->auth);
     }
     $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
     // Add the profile edit link.
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
             $url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
         } else {
             if (has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user) || $currentuser && has_capability('moodle/user:editownprofile', $systemcontext)) {
                 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
                     $url = $userauthplugin->edit_profile_url();
                     if (empty($url)) {
                         $url = new moodle_url('/user/edit.php', array('id' => $user->id, 'course' => $course->id));
                     }
                     $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
                 }
             }
         }
     }
     // Change password link.
     if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
         $passwordchangeurl = $userauthplugin->change_password_url();
         if (empty($passwordchangeurl)) {
             $passwordchangeurl = new moodle_url('/login/change_password.php', array('id' => $course->id));
         }
         $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
     }
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
         }
     }
     $pluginmanager = core_plugin_manager::instance();
     $enabled = $pluginmanager->get_enabled_plugins('mod');
     if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
         }
     }
     $editors = editors_get_enabled();
     if (count($editors) > 1) {
         if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
             if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
                 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
                 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
             }
         }
     }
     // Add "Course preferences" link.
     if (isloggedin() && !isguestuser($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/course.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('coursepreferences'), $url, self::TYPE_SETTING, null, 'coursepreferences');
         }
     }
     // View the roles settings.
     if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage'), $usercontext)) {
         $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
         $url = new moodle_url('/admin/roles/usersroles.php', array('userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
         $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
         if (!empty($assignableroles)) {
             $url = new moodle_url('/admin/roles/assign.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
         }
         if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH)) > 0) {
             $url = new moodle_url('/admin/roles/permissions.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
         }
         $url = new moodle_url('/admin/roles/check.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
     }
     // Repositories.
     if (!$this->cache->cached('contexthasrepos' . $usercontext->id)) {
         require_once $CFG->dirroot . '/repository/lib.php';
         $editabletypes = repository::get_editable_types($usercontext);
         $haseditabletypes = !empty($editabletypes);
         unset($editabletypes);
         $this->cache->set('contexthasrepos' . $usercontext->id, $haseditabletypes);
     } else {
         $haseditabletypes = $this->cache->{'contexthasrepos' . $usercontext->id};
     }
     if ($haseditabletypes) {
         $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
         $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
     }
     // Portfolio.
     if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
         require_once $CFG->libdir . '/portfoliolib.php';
         if (portfolio_has_visible_instances()) {
             $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfolio.php', array('courseid' => $course->id));
             $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfoliologs.php', array('courseid' => $course->id));
             $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
         }
     }
     $enablemanagetokens = false;
     if (!empty($CFG->enablerssfeeds)) {
         $enablemanagetokens = true;
     } else {
         if (!is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', context_system::instance())) {
             $enablemanagetokens = true;
         }
     }
     // Security keys.
     if ($currentuser && $enablemanagetokens) {
         $url = new moodle_url('/user/managetoken.php', array('sesskey' => sesskey()));
         $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
     }
     // Messaging.
     if ($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext) || !isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id)) {
         $url = new moodle_url('/message/edit.php', array('id' => $user->id));
         $useraccount->add(get_string('messaging', 'message'), $url, self::TYPE_SETTING);
     }
     // Blogs.
     if ($currentuser && !empty($CFG->enableblogs)) {
         $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
         if (has_capability('moodle/blog:view', $systemcontext)) {
             $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
         }
         if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', $systemcontext)) {
             $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
             $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
         }
         // Remove the blog node if empty.
         $blog->trim_if_empty();
     }
     // Badges.
     if ($currentuser && !empty($CFG->enablebadges)) {
         $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
         if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
             $url = new moodle_url('/badges/mybadges.php');
             $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
         }
         $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'), navigation_node::TYPE_SETTING);
         if (!empty($CFG->badges_allowexternalbackpack)) {
             $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), navigation_node::TYPE_SETTING);
         }
     }
     // Let plugins hook into user settings navigation.
     $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
     foreach ($pluginsfunction as $plugintype => $plugins) {
         foreach ($plugins as $pluginfunction) {
             $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
         }
     }
     return $usersetting;
 }
Пример #29
0
 /**
  * Helper method to render the information about the available plugin update
  *
  * @param core_plugin_manager $pluginman plugin manager instance
  * @param \core\update\info $updateinfo information about the available update for the plugin
  */
 protected function plugin_available_update_info(core_plugin_manager $pluginman, \core\update\info $updateinfo)
 {
     $boxclasses = 'pluginupdateinfo';
     $info = array();
     if (isset($updateinfo->release)) {
         $info[] = html_writer::div(get_string('updateavailable_release', 'core_plugin', $updateinfo->release), 'info release');
     }
     if (isset($updateinfo->maturity)) {
         $info[] = html_writer::div(get_string('maturity' . $updateinfo->maturity, 'core_admin'), 'info maturity');
         $boxclasses .= ' maturity' . $updateinfo->maturity;
     }
     if (isset($updateinfo->download)) {
         $info[] = html_writer::div(html_writer::link($updateinfo->download, get_string('download')), 'info download');
     }
     if (isset($updateinfo->url)) {
         $info[] = html_writer::div(html_writer::link($updateinfo->url, get_string('updateavailable_moreinfo', 'core_plugin')), 'info more');
     }
     $box = html_writer::start_div($boxclasses);
     $box .= html_writer::div(get_string('updateavailable', 'core_plugin', $updateinfo->version), 'version');
     $box .= html_writer::div(implode(html_writer::span(' ', 'separator'), $info), 'infos');
     if ($pluginman->is_remote_plugin_installable($updateinfo->component, $updateinfo->version, $reason)) {
         $box .= $this->output->single_button(new moodle_url($this->page->url, array('installupdate' => $updateinfo->component, 'installupdateversion' => $updateinfo->version)), get_string('updateavailableinstall', 'core_admin'), 'post', array('class' => 'singlebutton updateavailableinstall'));
     } else {
         $reasonhelp = $this->info_remote_plugin_not_installable($reason);
         if ($reasonhelp) {
             $box .= html_writer::div($reasonhelp, 'reasonhelp updateavailableinstall');
         }
     }
     $box .= html_writer::end_div();
     return $box;
 }
Пример #30
0
    $ADMIN->add('cache', new admin_externalpage('cachetestperformance', new lang_string('testperformance', 'cache'), $CFG->wwwroot . '/cache/testperformance.php'));
    $ADMIN->add('cache', new admin_category('cachestores', new lang_string('cachestores', 'cache')));
    foreach (core_component::get_plugin_list('cachestore') as $plugin => $path) {
        $settingspath = $path . '/settings.php';
        if (file_exists($settingspath)) {
            $settings = new admin_settingpage('cachestore_' . $plugin . '_settings', new lang_string('pluginname', 'cachestore_' . $plugin), 'moodle/site:config');
            include $settingspath;
            $ADMIN->add('cachestores', $settings);
        }
    }
}
// Add Calendar type settings.
if ($hassiteconfig) {
    $ADMIN->add('modules', new admin_category('calendartype', new lang_string('calendartypes', 'calendar')));
    foreach (core_component::get_plugin_list_with_file('calendartype', 'settings.php') as $plugin => $settingspath) {
        $settings = new admin_settingpage('calendartype_' . $plugin . '_settings', new lang_string('pluginname', 'calendartype_' . $plugin), 'moodle/site:config');
        include $settingspath;
        $ADMIN->add('calendartype', $settings);
    }
}
/// Add all local plugins - must be always last!
if ($hassiteconfig) {
    $ADMIN->add('modules', new admin_category('localplugins', new lang_string('localplugins')));
    $ADMIN->add('localplugins', new admin_externalpage('managelocalplugins', new lang_string('localpluginsmanage'), $CFG->wwwroot . '/' . $CFG->admin . '/localplugins.php'));
}
// Extend settings for each local plugin. Note that their settings may be in any part of the
// settings tree and may be visible not only for administrators.
foreach (core_plugin_manager::instance()->get_plugins_of_type('local') as $plugin) {
    /** @var \core\plugininfo\local $plugin */
    $plugin->load_settings($ADMIN, null, $hassiteconfig);
}