function get_keypair() { global $DB, $CFG; // We don't generate keys on install/upgrade because we want the USER // record to have an email address, city and country already. if (during_initial_install()) { return true; } if ($CFG->mnet_dispatcher_mode == 'off') { return true; } if (!extension_loaded("openssl")) { return true; } if (!empty($this->keypair)) { return true; } $this->keypair = array(); $keypair = get_config('mnet', 'openssl'); if (!empty($keypair)) { // Explode/Implode is faster than Unserialize/Serialize list($this->keypair['certificate'], $this->keypair['keypair_PEM']) = explode('@@@@@@@@', $keypair); } if ($this->public_key_expires > time()) { $this->keypair['privatekey'] = openssl_pkey_get_private($this->keypair['keypair_PEM']); $this->keypair['publickey'] = openssl_pkey_get_public($this->keypair['certificate']); } else { // Key generation/rotation // 1. Archive the current key (if there is one). $result = get_config('mnet', 'openssl_history'); if (empty($result)) { set_config('openssl_history', serialize(array()), 'mnet'); $openssl_history = array(); } else { $openssl_history = unserialize($result); } if (count($this->keypair)) { $this->keypair['expires'] = $this->public_key_expires; array_unshift($openssl_history, $this->keypair); } // 2. How many old keys do we want to keep? Use array_slice to get // rid of any we don't want $openssl_generations = get_config('mnet', 'openssl_generations'); if (empty($openssl_generations)) { set_config('openssl_generations', 3, 'mnet'); $openssl_generations = 3; } if (count($openssl_history) > $openssl_generations) { $openssl_history = array_slice($openssl_history, 0, $openssl_generations); } set_config('openssl_history', serialize($openssl_history), 'mnet'); // 3. Generate fresh keys $this->replace_keys(); } return true; }
function xmldb_block_iomad_approve_access_install() { global $USER, $DB; // Only do this when we are not installing for the first time, // that is handled elsewhere. if (!during_initial_install()) { // Add this block to the dashboard. // (yes, I know this isn't really what this is for!!) $reportblock = $DB->get_record('block_instances', array('blockname' => 'iomad_reports', 'pagetypepattern' => 'local-iomad-dashboard-index')); $approveblock = $reportblock; $approveblock->blockname = 'iomad_approve_access'; $approveblock->id = null; $DB->insert_record('block_instances', $approveblock); $reportblock = $DB->get_record('block_instances', array('blockname' => 'iomad_reports', 'pagetypepattern' => 'local-iomad-dashboard-index')); $reportblock->defaultweight = $reportblock->defaultweight + 1; $DB->update_record('block_instances', $reportblock); } return true; }
/** * Return the standard string that says whether you are logged in (and switched * roles/logged in as another user). * * @return string HTML fragment. */ public function login_info() { global $USER, $CFG, $DB, $SESSION; if (during_initial_install()) { return ''; } $loginpage = (string) $this->page->url === get_login_url(); $course = $this->page->course; if (session_is_loggedinas()) { $realuser = session_get_realuser(); $fullname = fullname($realuser, true); $realuserinfo = " [<a href=\"{$CFG->wwwroot}/course/loginas.php?id={$course->id}&sesskey=" . sesskey() . "\">{$fullname}</a>] "; } else { $realuserinfo = ''; } $loginurl = get_login_url(); if (empty($course->id)) { // $course->id is not defined during installation return ''; } else { if (isloggedin()) { $context = get_context_instance(CONTEXT_COURSE, $course->id); $fullname = fullname($USER, true); // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page) $username = "******"{$CFG->wwwroot}/user/profile.php?id={$USER->id}\">{$fullname}</a>"; if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id' => $USER->mnethostid))) { $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>"; } if (isguestuser()) { $loggedinas = $realuserinfo . get_string('loggedinasguest'); if (!$loginpage) { $loggedinas .= " (<a href=\"{$loginurl}\">" . get_string('login') . '</a>)'; } } else { if (is_role_switched($course->id)) { // Has switched roles $rolename = ''; if ($role = $DB->get_record('role', array('id' => $USER->access['rsw'][$context->path]))) { $rolename = ': ' . format_string($role->name); } $loggedinas = get_string('loggedinas', 'moodle', $username) . $rolename . " (<a href=\"{$CFG->wwwroot}/course/view.php?id={$course->id}&switchrole=0&sesskey=" . sesskey() . "\">" . get_string('switchrolereturn') . '</a>)'; } else { $loggedinas = $realuserinfo . get_string('loggedinas', 'moodle', $username) . ' ' . " (<a href=\"{$CFG->wwwroot}/login/logout.php?sesskey=" . sesskey() . "\">" . get_string('logout') . '</a>)'; } } } else { $loggedinas = get_string('loggedinnot', 'moodle'); if (!$loginpage) { $loggedinas .= " (<a href=\"{$loginurl}\">" . get_string('login') . '</a>)'; } } } $loggedinas = '<div class="logininfo">' . $loggedinas . '</div>'; if (isset($SESSION->justloggedin)) { unset($SESSION->justloggedin); if (!empty($CFG->displayloginfailures)) { if (!isguestuser()) { if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) { $loggedinas .= ' <div class="loginfailures">'; if (empty($count->accounts)) { $loggedinas .= get_string('failedloginattempts', '', $count); } else { $loggedinas .= get_string('failedloginattemptsall', '', $count); } if (file_exists("{$CFG->dirroot}/report/log/index.php") and has_capability('report/log:view', get_context_instance(CONTEXT_SYSTEM))) { $loggedinas .= ' (<a href="' . $CFG->wwwroot . '/report/log/index.php' . '?chooselog=1&id=1&modid=site_errors">' . get_string('logs') . '</a>)'; } $loggedinas .= '</div>'; } } } } return $loggedinas; }
/** * Method used to check the installed unoconv version. * * @param environment_results $result object to update, if relevant. * @return environment_results|null updated results or null if unoconv path is not executable. */ function check_unoconv_version(environment_results $result) { global $CFG; if (!during_initial_install() && !empty($CFG->pathtounoconv) && file_is_executable(trim($CFG->pathtounoconv))) { $currentversion = 0; $supportedversion = 0.7; $unoconvbin = \escapeshellarg($CFG->pathtounoconv); $command = "{$unoconvbin} --version"; exec($command, $output); // If the command execution returned some output, then get the unoconv version. if ($output) { foreach ($output as $response) { if (preg_match('/unoconv (\\d+\\.\\d+)/', $response, $matches)) { $currentversion = (double) $matches[1]; } } } if ($currentversion < $supportedversion) { $result->setInfo('unoconv version not supported'); $result->setStatus(false); return $result; } } return null; }
/** * Returns list of available updates for the given component. * * This method should be considered as internal API and is supposed to be * called by {@link \core\plugininfo\base::available_updates()} only * to lazy load the data once they are first requested. * * @param string $component frankenstyle name of the plugin * @return null|array array of \core\update\info objects or null */ public function load_available_updates_for_plugin($component) { global $CFG; $provider = \core\update\checker::instance(); if (!$provider->enabled() or during_initial_install()) { return null; } if (isset($CFG->updateminmaturity)) { $minmaturity = $CFG->updateminmaturity; } else { // This can happen during the very first upgrade to 2.3. $minmaturity = MATURITY_STABLE; } return $provider->get_update_info($component, array('minmaturity' => $minmaturity)); }
/** * Return the standard string that says whether you are logged in (and switched * roles/logged in as another user). * @param bool $withlinks if false, then don't include any links in the HTML produced. * If not set, the default is the nologinlinks option from the theme config.php file, * and if that is not set, then links are included. * @return string HTML fragment. */ public function login_info($withlinks = null) { global $USER, $CFG, $DB, $SESSION; if (during_initial_install()) { return ''; } if (is_null($withlinks)) { $withlinks = empty($this->page->layout_options['nologinlinks']); } $loginpage = (string) $this->page->url === get_login_url(); $course = $this->page->course; if (\core\session\manager::is_loggedinas()) { $realuser = \core\session\manager::get_realuser(); $fullname = fullname($realuser, true); if ($withlinks) { $loginastitle = get_string('loginas'); $realuserinfo = " [<a href=\"{$CFG->wwwroot}/course/loginas.php?id={$course->id}&sesskey=" . sesskey() . "\""; $realuserinfo .= "title =\"" . $loginastitle . "\">{$fullname}</a>] "; } else { $realuserinfo = " [{$fullname}] "; } } else { $realuserinfo = ''; } $loginurl = get_login_url(); if (empty($course->id)) { // $course->id is not defined during installation return ''; } else { if (isloggedin()) { $context = context_course::instance($course->id); $fullname = fullname($USER, true); // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page) if ($withlinks) { $linktitle = get_string('viewprofile'); $username = "******"{$CFG->wwwroot}/user/profile.php?id={$USER->id}\" title=\"{$linktitle}\">{$fullname}</a>"; } else { $username = $fullname; } if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id' => $USER->mnethostid))) { if ($withlinks) { $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>"; } else { $username .= " from {$idprovider->name}"; } } if (isguestuser()) { $loggedinas = $realuserinfo . get_string('loggedinasguest'); if (!$loginpage && $withlinks) { $loggedinas .= " (<a href=\"{$loginurl}\">" . get_string('login') . '</a>)'; } } else { if (is_role_switched($course->id)) { // Has switched roles $rolename = ''; if ($role = $DB->get_record('role', array('id' => $USER->access['rsw'][$context->path]))) { $rolename = ': ' . role_get_name($role, $context); } $loggedinas = get_string('loggedinas', 'moodle', $username) . $rolename; if ($withlinks) { $url = new moodle_url('/course/switchrole.php', array('id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $this->page->url->out_as_local_url(false))); $loggedinas .= '(' . html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)) . ')'; } } else { $loggedinas = $realuserinfo . get_string('loggedinas', 'moodle', $username); if ($withlinks) { echo "<i class='fa fa-user hide979 mywhite'></i> "; //****************$loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)'; $loggedinas .= " <span class=\"line-trans\">|</span><a class=\"logtop\" href=\"{$CFG->wwwroot}/login/logout.php?sesskey=" . sesskey() . "\"> " . get_string('logout') . '</a><span class="line-trans"> |</span>'; } } } } else { $loggedinas = get_string('loggedinnot', 'moodle'); if (!$loginpage && $withlinks) { //****************$loggedinas $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)'; echo "<i class='fa fa-lock hide979 mywhite'></i> "; $loggedinas .= " | <a href=\"{$loginurl}\">" . get_string('login') . '</a> |'; } } } $loggedinas = '<div class="logininfo">' . $loggedinas . '</div>'; if (isset($SESSION->justloggedin)) { unset($SESSION->justloggedin); if (!empty($CFG->displayloginfailures)) { if (!isguestuser()) { if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) { $loggedinas .= ' <div class="loginfailures">'; if (empty($count->accounts)) { $loggedinas .= get_string('failedloginattempts', '', $count); } else { $loggedinas .= get_string('failedloginattemptsall', '', $count); } if (file_exists("{$CFG->dirroot}/report/log/index.php") and has_capability('report/log:view', context_system::instance())) { $loggedinas .= ' (<a href="' . $CFG->wwwroot . '/report/log/index.php' . '?chooselog=1&id=1&modid=site_errors">' . get_string('logs') . '</a>)'; } $loggedinas .= '</div>'; } } } } return $loggedinas; }
/** * Returns system context instance. * * @static * @param int $instanceid * @param int $strictness * @param bool $cache * @return context_system context instance */ public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) { global $DB; if ($instanceid != 0) { debugging('context_system::instance(): invalid $id parameter detected, should be 0'); } if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page if (!isset(context::$systemcontext)) { $record = new stdClass(); $record->id = SYSCONTEXTID; $record->contextlevel = CONTEXT_SYSTEM; $record->instanceid = 0; $record->path = '/' . SYSCONTEXTID; $record->depth = 1; context::$systemcontext = new context_system($record); } return context::$systemcontext; } try { // we ignore the strictness completely because system context must except except during install $record = $DB->get_record('context', array('contextlevel' => CONTEXT_SYSTEM), '*', MUST_EXIST); } catch (dml_exception $e) { //table or record does not exist if (!during_initial_install()) { // do not mess with system context after install, it simply must exist throw $e; } $record = null; } if (!$record) { $record = new stdClass(); $record->contextlevel = CONTEXT_SYSTEM; $record->instanceid = 0; $record->depth = 1; $record->path = null; //not known before insert try { if ($DB->count_records('context')) { // contexts already exist, this is very weird, system must be first!!! return null; } if (defined('SYSCONTEXTID')) { // this would happen only in unittest on sites that went through weird 1.7 upgrade $record->id = SYSCONTEXTID; $DB->import_record('context', $record); $DB->get_manager()->reset_sequence('context'); } else { $record->id = $DB->insert_record('context', $record); } } catch (dml_exception $e) { // can not create context - table does not exist yet, sorry return null; } } if ($record->instanceid != 0) { // this is very weird, somebody must be messing with context table debugging('Invalid system context detected'); } if ($record->depth != 1 or $record->path != '/' . $record->id) { // fix path if necessary, initial install or path reset $record->depth = 1; $record->path = '/' . $record->id; $DB->update_record('context', $record); } if (!defined('SYSCONTEXTID')) { define('SYSCONTEXTID', $record->id); } context::$systemcontext = new context_system($record); return context::$systemcontext; }
protected function initialise_standard_body_classes() { global $CFG, $USER; $pagetype = $this->pagetype; if ($pagetype == 'site-index') { $this->_legacyclass = 'course'; } else if (substr($pagetype, 0, 6) == 'admin-') { $this->_legacyclass = 'admin'; } $this->add_body_class($this->_legacyclass); $pathbits = explode('-', trim($pagetype)); for ($i=1;$i<count($pathbits);$i++) { $this->add_body_class('path-'.join('-',array_slice($pathbits, 0, $i))); } $this->add_body_classes(get_browser_version_classes()); $this->add_body_class('dir-' . get_string('thisdirection', 'langconfig')); $this->add_body_class('lang-' . current_language()); $this->add_body_class('yui-skin-sam'); // Make YUI happy, if it is used. $this->add_body_class('yui3-skin-sam'); // Make YUI3 happy, if it is used. $this->add_body_class($this->url_to_class_name($CFG->wwwroot)); $this->add_body_class('pagelayout-' . $this->_pagelayout); // extra class describing current page layout if (!during_initial_install()) { $this->add_body_class('course-' . $this->_course->id); $this->add_body_class('context-' . $this->_context->id); } if (!empty($this->_cm)) { $this->add_body_class('cmid-' . $this->_cm->id); } if (!empty($CFG->allowcategorythemes)) { $this->ensure_category_loaded(); foreach ($this->_categories as $catid => $notused) { $this->add_body_class('category-' . $catid); } } else { $catid = 0; if (is_array($this->_categories)) { $catids = array_keys($this->_categories); $catid = reset($catids); } else if (!empty($this->_course->category)) { $catid = $this->_course->category; } if ($catid) { $this->add_body_class('category-' . $catid); } } if (!isloggedin()) { $this->add_body_class('notloggedin'); } if (!empty($USER->editing)) { $this->add_body_class('editing'); if (optional_param('bui_moveid', false, PARAM_INT)) { $this->add_body_class('blocks-moving'); } } if (!empty($CFG->blocksdrag)) { $this->add_body_class('drag'); } if ($this->_devicetypeinuse != 'default') { $this->add_body_class($this->_devicetypeinuse . 'theme'); } }
/** * Returns a tree of known plugins and information about them * * @param bool $disablecache force reload, cache can be used otherwise * @return array 2D array. The first keys are plugin type names (e.g. qtype); * the second keys are the plugin local name (e.g. multichoice); and * the values are the corresponding objects extending {@link plugininfo_base} */ public function get_plugins($disablecache = false) { if ($disablecache or is_null($this->pluginsinfo)) { $this->pluginsinfo = array(); $plugintypes = get_plugin_types(); $plugintypes = $this->reorder_plugin_types($plugintypes); foreach ($plugintypes as $plugintype => $plugintyperootdir) { if (in_array($plugintype, array('base', 'general'))) { throw new coding_exception('Illegal usage of reserved word for plugin type'); } if (class_exists('plugininfo_' . $plugintype)) { $plugintypeclass = 'plugininfo_' . $plugintype; } else { $plugintypeclass = 'plugininfo_general'; } if (!in_array('plugininfo_base', class_parents($plugintypeclass))) { throw new coding_exception('Class ' . $plugintypeclass . ' must extend plugininfo_base'); } $plugins = call_user_func(array($plugintypeclass, 'get_plugins'), $plugintype, $plugintyperootdir, $plugintypeclass); $this->pluginsinfo[$plugintype] = $plugins; } // TODO: MDL-20438 verify this is the correct solution/replace if (!during_initial_install()) { // append the information about available updates provided by {@link available_update_checker()} $provider = available_update_checker::instance(); foreach ($this->pluginsinfo as $plugintype => $plugins) { foreach ($plugins as $plugininfoholder) { $plugininfoholder->check_available_updates($provider); } } } } return $this->pluginsinfo; }
/** * Add an entry to the config log table. * * These are "action" focussed rather than web server hits, * and provide a way to easily reconstruct changes to Moodle configuration. * * @package core * @category log * @global moodle_database $DB * @global stdClass $USER * @param string $name The name of the configuration change action For example 'filter_active' when activating or deactivating a filter * @param string $oldvalue The config setting's previous value * @param string $value The config setting's new value * @param string $plugin Plugin name, for example a filter name when changing filter configuration * @return void */ function add_to_config_log($name, $oldvalue, $value, $plugin) { global $USER, $DB; $log = new stdClass(); $log->userid = during_initial_install() ? 0 : $USER->id; // 0 as user id during install $log->timemodified = time(); $log->name = $name; $log->oldvalue = $oldvalue; $log->value = $value; $log->plugin = $plugin; $DB->insert_record('config_log', $log); }
/** * Returns HTML for editor form element. * * @return string */ function toHtml() { global $CFG, $PAGE, $OUTPUT; require_once($CFG->dirroot.'/repository/lib.php'); if ($this->_flagFrozen) { return $this->getFrozenHtml(); } $ctx = $this->_options['context']; $id = $this->_attributes['id']; $elname = $this->_attributes['name']; $subdirs = $this->_options['subdirs']; $maxbytes = $this->_options['maxbytes']; $areamaxbytes = $this->_options['areamaxbytes']; $maxfiles = $this->_options['maxfiles']; $changeformat = $this->_options['changeformat']; // TO DO: implement as ajax calls $text = $this->_values['text']; $format = $this->_values['format']; $draftitemid = $this->_values['itemid']; // security - never ever allow guest/not logged in user to upload anything if (isguestuser() or !isloggedin()) { $maxfiles = 0; } $str = $this->_getTabs(); $str .= '<div>'; $editor = editors_get_preferred_editor($format); $strformats = format_text_menu(); $formats = $editor->get_supported_formats(); foreach ($formats as $fid) { $formats[$fid] = $strformats[$fid]; } // get filepicker info // $fpoptions = array(); if ($maxfiles != 0 ) { if (empty($draftitemid)) { // no existing area info provided - let's use fresh new draft area require_once("$CFG->libdir/filelib.php"); $this->setValue(array('itemid'=>file_get_unused_draft_itemid())); $draftitemid = $this->_values['itemid']; } $args = new stdClass(); // need these three to filter repositories list $args->accepted_types = array('web_image'); $args->return_types = $this->_options['return_types']; $args->context = $ctx; $args->env = 'filepicker'; // advimage plugin $image_options = initialise_filepicker($args); $image_options->context = $ctx; $image_options->client_id = uniqid(); $image_options->maxbytes = $this->_options['maxbytes']; $image_options->areamaxbytes = $this->_options['areamaxbytes']; $image_options->env = 'editor'; $image_options->itemid = $draftitemid; // moodlemedia plugin $args->accepted_types = array('video', 'audio'); $media_options = initialise_filepicker($args); $media_options->context = $ctx; $media_options->client_id = uniqid(); $media_options->maxbytes = $this->_options['maxbytes']; $media_options->areamaxbytes = $this->_options['areamaxbytes']; $media_options->env = 'editor'; $media_options->itemid = $draftitemid; // advlink plugin $args->accepted_types = '*'; $link_options = initialise_filepicker($args); $link_options->context = $ctx; $link_options->client_id = uniqid(); $link_options->maxbytes = $this->_options['maxbytes']; $link_options->areamaxbytes = $this->_options['areamaxbytes']; $link_options->env = 'editor'; $link_options->itemid = $draftitemid; $args->accepted_types = array('.vtt'); $subtitle_options = initialise_filepicker($args); $subtitle_options->context = $ctx; $subtitle_options->client_id = uniqid(); $subtitle_options->maxbytes = $this->_options['maxbytes']; $subtitle_options->areamaxbytes = $this->_options['areamaxbytes']; $subtitle_options->env = 'editor'; $subtitle_options->itemid = $draftitemid; $fpoptions['image'] = $image_options; $fpoptions['media'] = $media_options; $fpoptions['link'] = $link_options; $fpoptions['subtitle'] = $subtitle_options; } //If editor is required and tinymce, then set required_tinymce option to initalize tinymce validation. if (($editor instanceof tinymce_texteditor) && !is_null($this->getAttribute('onchange'))) { $this->_options['required'] = true; } // print text area - TODO: add on-the-fly switching, size configuration, etc. $editor->set_text($text); $editor->use_editor($id, $this->_options, $fpoptions); $rows = empty($this->_attributes['rows']) ? 15 : $this->_attributes['rows']; $cols = empty($this->_attributes['cols']) ? 80 : $this->_attributes['cols']; //Apply editor validation if required field $context = []; $context['rows'] = $rows; $context['cols'] = $cols; $context['frozen'] = $this->_flagFrozen; foreach ($this->getAttributes() as $name => $value) { $context[$name] = $value; } $context['hasformats'] = count($formats) > 1; $context['formats'] = []; if (($format === '' || $format === null) && count($formats)) { $format = key($formats); } foreach ($formats as $formatvalue => $formattext) { $context['formats'][] = ['value' => $formatvalue, 'text' => $formattext, 'selected' => ($formatvalue == $format)]; } $context['id'] = $id; $context['value'] = $text; $context['format'] = $format; if (!is_null($this->getAttribute('onblur')) && !is_null($this->getAttribute('onchange'))) { $context['changelistener'] = true; } $str .= $OUTPUT->render_from_template('core_form/editor_textarea', $context); // during moodle installation, user area doesn't exist // so we need to disable filepicker here. if (!during_initial_install() && empty($CFG->adminsetuppending)) { // 0 means no files, -1 unlimited if ($maxfiles != 0 ) { $str .= html_writer::empty_tag('input', array('type' => 'hidden', 'name' => $elname.'[itemid]', 'value' => $draftitemid)); // used by non js editor only $editorurl = new moodle_url("$CFG->wwwroot/repository/draftfiles_manager.php", array( 'action'=>'browse', 'env'=>'editor', 'itemid'=>$draftitemid, 'subdirs'=>$subdirs, 'maxbytes'=>$maxbytes, 'areamaxbytes' => $areamaxbytes, 'maxfiles'=>$maxfiles, 'ctx_id'=>$ctx->id, 'course'=>$PAGE->course->id, 'sesskey'=>sesskey(), )); $str .= '<noscript>'; $str .= "<div><object type='text/html' data='$editorurl' height='160' width='600' style='border:1px solid #000'></object></div>"; $str .= '</noscript>'; } } $str .= '</div>'; return $str; }
/** * Initialise the navigation given the type and id for the branch to expand. * * @param int $branchtype One of navigation_node::TYPE_* * @param int $id * @return array The expandable nodes */ public function initialise() { global $CFG, $DB, $SITE; if ($this->initialised || during_initial_install()) { return $this->expandable; } $this->initialised = true; $this->rootnodes = array(); $this->rootnodes['site'] = $this->add_course($SITE); $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), new moodle_url('/my'), self::TYPE_ROOTNODE, null, 'mycourses'); $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses'); if (function_exists('enrol_user_sees_own_courses')) { // Determine if the user is enrolled in any course. $enrolledinanycourse = enrol_user_sees_own_courses(); if ($enrolledinanycourse) { $this->rootnodes['mycourses']->isexpandable = true; if ($CFG->navshowallcourses) { // When we show all courses we need to show both the my courses and the regular courses branch. $this->rootnodes['courses']->isexpandable = true; } } else { $this->rootnodes['courses']->isexpandable = true; } } $this->expand($this->branchtype, $this->instanceid); }
/** * Return the default setting for this control * * @return array Array of default settings */ public function get_defaultsetting() { global $CFG; if (during_initial_install()) { return null; } $result = array(); foreach ($this->types as $capability) { if ($caproles = get_roles_with_capability($capability, CAP_ALLOW)) { foreach ($caproles as $caprole) { $result[$caprole->id] = 1; } } } return $result; }
/** * Initialise the navigation given the type and id for the branch to expand. * * @param int $branchtype One of navigation_node::TYPE_* * @param int $id * @return array The expandable nodes */ public function initialise($branchtype, $id) { global $CFG, $DB, $SITE, $PAGE; if ($this->initialised || during_initial_install()) { return $this->expandable; } $this->initialised = true; $this->rootnodes = array(); $this->rootnodes['site'] = $this->add_course($SITE); $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses'); // Branchtype will be one of navigation_node::TYPE_* switch ($branchtype) { case self::TYPE_CATEGORY : $this->load_all_categories($id); $limit = 20; if (!empty($CFG->navcourselimit)) { $limit = (int)$CFG->navcourselimit; } $courses = $DB->get_records('course', array('category' => $id), 'sortorder','*', 0, $limit); foreach ($courses as $course) { $this->add_course($course); } break; case self::TYPE_COURSE : $course = $DB->get_record('course', array('id' => $id), '*', MUST_EXIST); try { krystle2_require_course_login($course); //$this->page = $PAGE; $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id)); $coursenode = $this->add_course($course); $this->add_course_essentials($coursenode, $course); if ($this->format_display_course_content($course->format) && $PAGE->course->id == $course->id) { $this->load_course_sections($course, $coursenode); } } catch(require_login_exception $rle) { $coursenode = $this->add_course($course); } break; case self::TYPE_SECTION : $sql = 'SELECT c.*, cs.section AS sectionnumber FROM {course} c LEFT JOIN {course_sections} cs ON cs.course = c.id WHERE cs.id = ?'; $course = $DB->get_record_sql($sql, array($id), MUST_EXIST); try { krystle2_require_course_login($course); //$this->page = $PAGE; $this->page->set_context(get_context_instance(CONTEXT_COURSE, $course->id)); $coursenode = $this->add_course($course); $this->add_course_essentials($coursenode, $course); $sections = $this->load_course_sections($course, $coursenode); if(method_exists($this,'generate_sections_and_activities')) { list($sectionarray, $activities) = $this->generate_sections_and_activities($course); $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, $activities); } else { // pre-Moodle 2.1 $this->load_section_activities($sections[$course->sectionnumber]->sectionnode, $course->sectionnumber, get_fast_modinfo($course)); } } catch(require_login_exception $rle) { $coursenode = $this->add_course($course); } break; case self::TYPE_ACTIVITY : if(method_exists($this,'generate_sections_and_activities')) { $sql = "SELECT c.* FROM {course} c JOIN {course_modules} cm ON cm.course = c.id WHERE cm.id = :cmid"; $params = array('cmid' => $id); $course = $DB->get_record_sql($sql, $params, MUST_EXIST); $modinfo = get_fast_modinfo($course); $cm = $modinfo->get_cm($id); } else { // pre-Moodle 2.1 $cm = get_coursemodule_from_id(false, $id, 0, false, MUST_EXIST); $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST); } try { krystle2_require_course_login($course, true, $cm); //$this->page = $PAGE; $this->page->set_context(get_context_instance(CONTEXT_MODULE, $cm->id)); $coursenode = $this->load_course($course); if(!method_exists($this,'generate_sections_and_activities')) { // pre-Moodle 2.1 $sections = $this->load_course_sections($course, $coursenode); foreach ($sections as $section) { if ($section->id == $cm->section) { $cm->sectionnumber = $section->section; break; } } } if ($course->id == SITEID) { if(method_exists($this,'generate_sections_and_activities')) { // >= 2.1 doesn't seem to have generated the course sections yet, // so we'll do it here to make sure we get the activity node $this->load_course_sections($course, $coursenode); } $modulenode = $this->load_activity($cm, $course, $this->rootnodes['site']->find($cm->id, null)); } else { if(method_exists($this,'generate_sections_and_activities')) { $sections = $this->load_course_sections($course, $coursenode); list($sectionarray, $activities) = $this->generate_sections_and_activities($course); $activities = $this->load_section_activities($sections[$cm->sectionnum]->sectionnode, $cm->sectionnum, $activities); } else { // pre-Moodle 2.1 $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, get_fast_modinfo($course)); } $modulenode = $this->load_activity($cm, $course, $activities[$cm->id]); } } catch(require_login_exception $rle) { $coursenode = $this->add_course($course); } break; default: throw new Exception('Unknown type'); return $this->expandable; } $this->find_expandable($this->expandable); return $this->expandable; }
function toHtml() { global $CFG, $PAGE; require_once $CFG->dirroot . '/repository/lib.php'; if ($this->_flagFrozen) { return $this->getFrozenHtml(); } $ctx = $this->_options['context']; $id = $this->_attributes['id']; $elname = $this->_attributes['name']; $subdirs = $this->_options['subdirs']; $maxbytes = $this->_options['maxbytes']; $maxfiles = $this->_options['maxfiles']; $changeformat = $this->_options['changeformat']; // TO DO: implement as ajax calls $text = $this->_values['text']; $format = $this->_values['format']; $draftitemid = $this->_values['itemid']; // security - never ever allow guest/not logged in user to upload anything if (isguestuser() or !isloggedin()) { $maxfiles = 0; } $str = $this->_getTabs(); $str .= '<div>'; $editor = editors_get_preferred_editor($format); $strformats = format_text_menu(); $formats = $editor->get_supported_formats(); foreach ($formats as $fid) { $formats[$fid] = $strformats[$fid]; } // get filepicker info // $fpoptions = array(); if ($maxfiles != 0) { if (empty($draftitemid)) { // no existing area info provided - let's use fresh new draft area require_once "{$CFG->libdir}/filelib.php"; $this->setValue(array('itemid' => file_get_unused_draft_itemid())); $draftitemid = $this->_values['itemid']; } $args = new stdClass(); // need these three to filter repositories list $args->accepted_types = array('image'); $args->return_types = FILE_INTERNAL | FILE_EXTERNAL; $args->context = $ctx; $args->env = 'filepicker'; // advimage plugin $image_options = initialise_filepicker($args); $image_options->context = $ctx; $image_options->client_id = uniqid(); $image_options->maxbytes = $this->_options['maxbytes']; $image_options->env = 'editor'; $image_options->itemid = $draftitemid; // moodlemedia plugin $args->accepted_types = array('video', 'audio'); $media_options = initialise_filepicker($args); $media_options->context = $ctx; $media_options->client_id = uniqid(); $media_options->maxbytes = $this->_options['maxbytes']; $media_options->env = 'editor'; $media_options->itemid = $draftitemid; // advlink plugin $args->accepted_types = '*'; $link_options = initialise_filepicker($args); $link_options->context = $ctx; $link_options->client_id = uniqid(); $link_options->maxbytes = $this->_options['maxbytes']; $link_options->env = 'editor'; $link_options->itemid = $draftitemid; $fpoptions['image'] = $image_options; $fpoptions['media'] = $media_options; $fpoptions['link'] = $link_options; } //If editor is required and tinymce, then set required_tinymce option to initalize tinymce validation. if ($editor instanceof tinymce_texteditor && !is_null($this->getAttribute('onchange'))) { $this->_options['required'] = true; } /// print text area - TODO: add on-the-fly switching, size configuration, etc. $editor->use_editor($id, $this->_options, $fpoptions); $rows = empty($this->_attributes['rows']) ? 15 : $this->_attributes['rows']; $cols = empty($this->_attributes['cols']) ? 80 : $this->_attributes['cols']; //Apply editor validation if required field $editorrules = ''; if (!is_null($this->getAttribute('onblur')) && !is_null($this->getAttribute('onchange'))) { $editorrules = 'onblur="' . htmlspecialchars($this->getAttribute('onblur')) . '" onchange="' . htmlspecialchars($this->getAttribute('onchange')) . '"'; } $str .= '<div><textarea id="' . $id . '" name="' . $elname . '[text]" rows="' . $rows . '" cols="' . $cols . '"' . $editorrules . '>'; $str .= s($text); $str .= '</textarea></div>'; $str .= '<div>'; if (count($formats) > 1) { $str .= html_writer::select($formats, $elname . '[format]', $format, false); } else { $str .= html_writer::empty_tag('input', array('name' => $elname . '[format]', 'type' => 'hidden', 'value' => array_pop(array_keys($formats)))); } $str .= '</div>'; // during moodle installation, user area doesn't exist // so we need to disable filepicker here. if (!during_initial_install() && empty($CFG->adminsetuppending)) { // 0 means no files, -1 unlimited if ($maxfiles != 0) { $str .= '<input type="hidden" name="' . $elname . '[itemid]" value="' . $draftitemid . '" />'; // used by non js editor only $editorurl = new moodle_url("{$CFG->wwwroot}/repository/draftfiles_manager.php", array('action' => 'browse', 'env' => 'editor', 'itemid' => $draftitemid, 'subdirs' => $subdirs, 'maxbytes' => $maxbytes, 'maxfiles' => $maxfiles, 'ctx_id' => $ctx->id, 'course' => $PAGE->course->id, 'sesskey' => sesskey())); $str .= '<noscript>'; $str .= "<div><object type='text/html' data='{$editorurl}' height='160' width='600' style='border:1px solid #000'></object></div>"; $str .= '</noscript>'; } } $str .= '</div>'; return $str; }
/** IOMAD: * Check if a course is attached to a company AND * the user belongs to a different company. * Otherwise, return true */ public static function iomad_check_course($course) { global $CFG, $DB, $USER; // If we are installing this will be called to build // the basic category tree so just say yes. if (during_initial_install() || is_siteadmin($USER->id)) { return true; } // Try to find the category in company list. if (!empty($course->id) && ($company = $DB->get_record('company_course', array('courseid' => $course->id)))) { // If this is not the user's company then we return false. if ($DB->get_record('company_users', array('userid' => $USER->id, 'companyid' => $company->companyid))) { // User is not assigned to this company - hide the category. return true; } else { return false; } } // Category is visible. return true; }
/** * Construct a user menu, returning HTML that can be echoed out by a * layout file. * * @param stdClass $user A user object, usually $USER. * @param bool $withlinks true if a dropdown should be built. * @return string HTML fragment. */ public function user_menu($user = null, $withlinks = null) { global $USER, $CFG; require_once($CFG->dirroot . '/user/lib.php'); if (is_null($user)) { $user = $USER; } // Note: this behaviour is intended to match that of core_renderer::login_info, // but should not be considered to be good practice; layout options are // intended to be theme-specific. Please don't copy this snippet anywhere else. if (is_null($withlinks)) { $withlinks = empty($this->page->layout_options['nologinlinks']); } // Add a class for when $withlinks is false. $usermenuclasses = 'usermenu'; if (!$withlinks) { $usermenuclasses .= ' withoutlinks'; } $returnstr = ""; // If during initial install, return the empty return string. if (during_initial_install()) { return $returnstr; } $loginpage = $this->is_login_page(); $loginurl = get_login_url(); // If not logged in, show the typical not-logged-in string. if (!isloggedin()) { $returnstr = get_string('loggedinnot', 'moodle'); if (!$loginpage) { $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)'; } return html_writer::div( html_writer::span( $returnstr, 'login' ), $usermenuclasses ); } // If logged in as a guest user, show a string to that effect. if (isguestuser()) { $returnstr = get_string('loggedinasguest'); if (!$loginpage && $withlinks) { $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)'; } return html_writer::div( html_writer::span( $returnstr, 'login' ), $usermenuclasses ); } // Get some navigation opts. $opts = user_get_user_navigation_info($user, $this->page); $avatarclasses = "avatars"; $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current'); $usertextcontents = $opts->metadata['userfullname']; // Other user. if (!empty($opts->metadata['asotheruser'])) { $avatarcontents .= html_writer::span( $opts->metadata['realuseravatar'], 'avatar realuser' ); $usertextcontents = $opts->metadata['realuserfullname']; $usertextcontents .= html_writer::tag( 'span', get_string( 'loggedinas', 'moodle', html_writer::span( $opts->metadata['userfullname'], 'value' ) ), array('class' => 'meta viewingas') ); } // Role. if (!empty($opts->metadata['asotherrole'])) { $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename']))); $usertextcontents .= html_writer::span( $opts->metadata['rolename'], 'meta role role-' . $role ); } // User login failures. if (!empty($opts->metadata['userloginfail'])) { $usertextcontents .= html_writer::span( $opts->metadata['userloginfail'], 'meta loginfailures' ); } // MNet. if (!empty($opts->metadata['asmnetuser'])) { $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername']))); $usertextcontents .= html_writer::span( $opts->metadata['mnetidprovidername'], 'meta mnet mnet-' . $mnet ); } $returnstr .= html_writer::span( html_writer::span($usertextcontents, 'usertext') . html_writer::span($avatarcontents, $avatarclasses), 'userbutton' ); // Create a divider (well, a filler). $divider = new action_menu_filler(); $divider->primary = false; $am = new action_menu(); $am->initialise_js($this->page); $am->set_menu_trigger( $returnstr ); $am->set_alignment(action_menu::TR, action_menu::BR); $am->set_nowrap_on_items(); if ($withlinks) { $navitemcount = count($opts->navitems); $idx = 0; foreach ($opts->navitems as $key => $value) { switch ($value->itemtype) { case 'divider': // If the nav item is a divider, add one and skip link processing. $am->add($divider); break; case 'invalid': // Silently skip invalid entries (should we post a notification?). break; case 'link': // Process this as a link item. $pix = null; if (isset($value->pix) && !empty($value->pix)) { $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall')); } else if (isset($value->imgsrc) && !empty($value->imgsrc)) { $value->title = html_writer::img( $value->imgsrc, $value->title, array('class' => 'iconsmall') ) . $value->title; } $al = new action_menu_link_secondary( $value->url, $pix, $value->title, array('class' => 'icon') ); $am->add($al); break; } $idx++; // Add dividers after the first item and before the last item. if ($idx == 1 || $idx == $navitemcount - 1) { $am->add($divider); } } } return html_writer::div( $this->render($am), $usermenuclasses ); }
/** * Return the default setting for this control * * @return array Array of default settings */ public function get_defaultsetting() { global $CFG; if (during_initial_install()) { return null; } $result = array(); foreach ($this->types as $archetype) { if ($caproles = get_archetype_roles($archetype)) { foreach ($caproles as $caprole) { $result[$caprole->id] = 1; } } } return $result; }
/** * Returns a tree of known plugins and information about them * * @param bool $disablecache force reload, cache can be used otherwise * @return array 2D array. The first keys are plugin type names (e.g. qtype); * the second keys are the plugin local name (e.g. multichoice); and * the values are the corresponding objects extending {@link plugininfo_base} */ public function get_plugins($disablecache = false) { global $CFG; if ($disablecache or is_null($this->pluginsinfo)) { // Hack: include mod and editor subplugin management classes first, // the adminlib.php is supposed to contain extra admin settings too. require_once $CFG->libdir . '/adminlib.php'; foreach (array('mod', 'editor') as $type) { foreach (get_plugin_list($type) as $dir) { if (file_exists("{$dir}/adminlib.php")) { include_once "{$dir}/adminlib.php"; } } } $this->pluginsinfo = array(); $plugintypes = $this->get_plugin_types(); foreach ($plugintypes as $plugintype => $plugintyperootdir) { if (in_array($plugintype, array('base', 'general'))) { throw new coding_exception('Illegal usage of reserved word for plugin type'); } if (class_exists('plugininfo_' . $plugintype)) { $plugintypeclass = 'plugininfo_' . $plugintype; } else { $plugintypeclass = 'plugininfo_general'; } if (!in_array('plugininfo_base', class_parents($plugintypeclass))) { throw new coding_exception('Class ' . $plugintypeclass . ' must extend plugininfo_base'); } $plugins = call_user_func(array($plugintypeclass, 'get_plugins'), $plugintype, $plugintyperootdir, $plugintypeclass); $this->pluginsinfo[$plugintype] = $plugins; } if (empty($CFG->disableupdatenotifications) and !during_initial_install()) { // append the information about available updates provided by {@link available_update_checker()} $provider = available_update_checker::instance(); foreach ($this->pluginsinfo as $plugintype => $plugins) { foreach ($plugins as $plugininfoholder) { $plugininfoholder->check_available_updates($provider); } } } } return $this->pluginsinfo; }
if ($fetchupdates) { // no sesskey support guaranteed here available_update_checker::instance()->fetch(); redirect($PAGE->url); } $output = $PAGE->get_renderer('core', 'admin'); echo $output->upgrade_plugin_check_page(plugin_manager::instance(), available_update_checker::instance(), $version, $showallplugins, new moodle_url($PAGE->url), new moodle_url('/admin/index.php', array('confirmplugincheck' => 1))); die; } } // install/upgrade all plugins and other parts upgrade_noncore(true); } // If this is the first install, indicate that this site is fully configured // except the admin password if (during_initial_install()) { set_config('rolesactive', 1); // after this, during_initial_install will return false. set_config('adminsetuppending', 1); // we need this redirect to setup proper session upgrade_finished("index.php?sessionstarted=1&lang={$CFG->lang}"); } // make sure admin user is created - this is the last step because we need // session to be working properly in order to edit admin account if (!empty($CFG->adminsetuppending)) { $sessionstarted = optional_param('sessionstarted', 0, PARAM_BOOL); if (!$sessionstarted) { redirect("index.php?sessionstarted=1&lang={$CFG->lang}"); } else { $sessionverify = optional_param('sessionverify', 0, PARAM_BOOL); if (!$sessionverify) {
/** * Returns list of known plugins of the given type. * * This method returns the subset of the tree returned by {@link self::get_plugins()}. * If the given type is not known, empty array is returned. * * @param string $type plugin type, e.g. 'mod' or 'workshopallocation' * @return \core\plugininfo\base[] (string)plugin name (e.g. 'workshop') => corresponding subclass of {@link \core\plugininfo\base} */ public function get_plugins_of_type($type) { global $CFG; $this->init_pluginsinfo_property(); if (!array_key_exists($type, $this->pluginsinfo)) { return array(); } if (is_array($this->pluginsinfo[$type])) { return $this->pluginsinfo[$type]; } $types = core_component::get_plugin_types(); if (!isset($types[$type])) { // Orphaned subplugins! $plugintypeclass = self::resolve_plugininfo_class($type); $this->pluginsinfo[$type] = $plugintypeclass::get_plugins($type, null, $plugintypeclass); return $this->pluginsinfo[$type]; } /** @var \core\plugininfo\base $plugintypeclass */ $plugintypeclass = self::resolve_plugininfo_class($type); $plugins = $plugintypeclass::get_plugins($type, $types[$type], $plugintypeclass); $this->pluginsinfo[$type] = $plugins; if (empty($CFG->disableupdatenotifications) and !during_initial_install()) { // Append the information about available updates provided by {@link \core\update\checker()}. $provider = \core\update\checker::instance(); foreach ($plugins as $plugininfoholder) { $plugininfoholder->check_available_updates($provider); } } return $this->pluginsinfo[$type]; }
public function login_info() { global $USER, $CFG, $DB, $SESSION; if (during_initial_install()) { return ''; } $course = $this->page->course; if (empty($course->id)) { // $course->id is not defined during installation return ''; } if (session_is_loggedinas()) { $real_user = session_get_realuser(); $real['name'] = fullname($real_user, true); $real['link'] = html::url("{$CFG->wwwroot}/course/loginas.php", array('id' => $course->id, 'sesskey' => sesskey())); } else { $real = null; } if (!isloggedin()) { return bootsnipp::sign_up_sign_in(new moodle_url('/login/index.php')); } $logout['link'] = html::url("{$CFG->wwwroot}/login/logout.php", array('sesskey' => sesskey())); $logout['name'] = get_string('logout'); $context = get_context_instance(CONTEXT_COURSE, $course->id); $user['name'] = fullname($USER, true); $user['link'] = html::url("{$CFG->wwwroot}/user/profile.php", array('id' => $USER->id)); if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id' => $USER->mnethostid))) { $mnet['link'] = $idprovider->wwwroot; $mnet['name'] = $idprovider->name; } else { $mnet = null; } if (isguestuser()) { $guest['link'] = get_login_url(); $guest['name'] = get_string('login'); return bootsnipp::guest_user($user['name'], $guest, $logout); } if (is_role_switched($course->id)) { if ($role = $DB->get_record('role', array('id' => $USER->access['rsw'][$context->path]))) { $user['name'] .= ': ' . format_string($role->name); } $role_switch['link'] = "{$CFG->wwwroot}/course/view.php?id={$course->id}&switchrole=0&sesskey=" . sesskey(); $role_switch['name'] = get_string('switchrolereturn'); } else { $role_switch = null; } $loginfailures = null; if (isset($SESSION->justloggedin)) { unset($SESSION->justloggedin); if (!empty($CFG->displayloginfailures) && !isguestuser()) { if (file_exists("{$CFG->dirroot}/report/log/index.php") and has_capability('report/log:view', get_context_instance(CONTEXT_SYSTEM))) { if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) { $loginfailures['link'] = "{$CFG->wwwroot}/report/log/index.php?chooselog=1&id=1&modid=site_errors"; if (empty($count->accounts)) { $loginfailures['name'] = get_string('failedloginattempts', '', $count); } else { $loginfailures['name'] = get_string('failedloginattemptsall', '', $count); } } } } } return bootsnipp::signed_in($user, $loginfailures, $mnet, $real, $role_switch, $logout); }
/** * Initialise the site admin navigation. * * @return array An array of the expandable nodes */ public function initialise() { if ($this->initialised || during_initial_install()) { return false; } $this->context = $this->page->context; $this->load_administration_settings(); // Check if local plugins is adding node to site admin. $this->load_local_plugin_settings(); $this->initialised = true; }
/** * Method used to check the usage of slasharguments config and display a warning message. * * @param environment_results $result object to update, if relevant. * @return environment_results|null updated results or null if slasharguments is disabled. */ function check_slasharguments(environment_results $result) { global $CFG; if (!during_initial_install() && empty($CFG->slasharguments)) { $result->setInfo('slasharguments'); $result->setStatus(false); return $result; } return null; }
/** * Given a simple string, this function returns the string * processed by enabled string filters if $CFG->filterall is enabled * * This function should be used to print short strings (non html) that * need filter processing e.g. activity titles, post subjects, * glossary concepts. * * @global object * @global object * @global object * @staticvar bool $strcache * @param string $string The string to be filtered. * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713 * @param array $options options array/object or courseid * @return string */ function format_string($string, $striplinks = true, $options = NULL) { global $CFG, $COURSE, $PAGE; //We'll use a in-memory cache here to speed up repeated strings static $strcache = false; if (empty($CFG->version) or $CFG->version < 2010072800 or during_initial_install()) { // do not filter anything during installation or before upgrade completes return $string = strip_tags($string); } if ($strcache === false or count($strcache) > 2000) { // this number might need some tuning to limit memory usage in cron $strcache = array(); } if (is_numeric($options)) { // legacy courseid usage $options = array('context' => get_context_instance(CONTEXT_COURSE, $options)); } else { $options = (array) $options; // detach object, we can not modify it } if (empty($options['context'])) { // fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-( $options['context'] = $PAGE->context; } else { if (is_numeric($options['context'])) { $options['context'] = get_context_instance_by_id($options['context']); } } if (!$options['context']) { // we did not find any context? weird return $string = strip_tags($string); } //Calculate md5 $md5 = md5($string . '<+>' . $striplinks . '<+>' . $options['context']->id . '<+>' . current_language()); //Fetch from cache if possible if (isset($strcache[$md5])) { return $strcache[$md5]; } // First replace all ampersands not followed by html entity code // Regular expression moved to its own method for easier unit testing $string = replace_ampersands_not_followed_by_entity($string); if (!empty($CFG->filterall)) { $string = filter_manager::instance()->filter_string($string, $options['context']); } // If the site requires it, strip ALL tags from this string if (!empty($CFG->formatstringstriptags)) { $string = strip_tags($string); } else { // Otherwise strip just links if that is required (default) if ($striplinks) { //strip links in string $string = strip_links($string); } $string = clean_text($string); } //Store to cache $strcache[$md5] = $string; return $string; }
/** * Outputs the user menu. * @return custom_menu object */ public function custom_menu_user() { // Die if executed during install. if (during_initial_install()) { return false; } global $USER, $CFG, $DB; $loginurl = get_login_url(); $usermenu = html_writer::start_tag('ul', array('class' => 'nav')); $usermenu .= html_writer::start_tag('li', array('class' => 'dropdown')); if (!isloggedin()) { if ($this->page->pagelayout != 'login') { $userpic = '<em><i class="fa fa-sign-in"></i>' . get_string('login') . '</em>'; $usermenu .= html_writer::link($loginurl, $userpic, array('class' => 'loginurl')); } } else { if (isguestuser()) { $userurl = new moodle_url('#'); $userpic = parent::user_picture($USER, array('link' => false)); $caret = '<i class="fa fa-caret-right"></i>'; $userclass = array('class' => 'dropdown-toggle', 'data-toggle' => 'dropdown'); $usermenu .= html_writer::link($userurl, $userpic . get_string('guest') . $caret, $userclass); // Render direct logout link. $usermenu .= html_writer::start_tag('ul', array('class' => 'dropdown-menu pull-right')); $branchlabel = '<em><i class="fa fa-sign-out"></i>' . get_string('logout') . '</em>'; $branchurl = new moodle_url('/login/logout.php'); $branchurl->param('sesskey', sesskey()); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); // Render Help Link. $usermenu .= $this->theme_essential_render_helplink(); $usermenu .= html_writer::end_tag('ul'); } else { $course = $this->page->course; $context = context_course::instance($course->id); // Output Profile link. $userurl = new moodle_url('#'); $userpic = parent::user_picture($USER, array('link' => false)); $caret = '<i class="fa fa-caret-right"></i>'; $userclass = array('class' => 'dropdown-toggle', 'data-toggle' => 'dropdown'); if (!empty($USER->alternatename)) { $usermenu .= html_writer::link($userurl, $userpic . $USER->alternatename . $caret, $userclass); } else { $usermenu .= html_writer::link($userurl, $userpic . $USER->firstname . $caret, $userclass); } // Start dropdown menu items. $usermenu .= html_writer::start_tag('ul', array('class' => 'dropdown-menu pull-right')); if (\core\session\manager::is_loggedinas()) { $realuser = \core\session\manager::get_realuser(); $branchlabel = '<em><i class="fa fa-key"></i>' . fullname($realuser, true) . get_string('loggedinas', 'theme_essential') . fullname($USER, true) . '</em>'; } else { $branchlabel = '<em><i class="fa fa-user"></i>' . fullname($USER, true) . '</em>'; } $branchurl = new moodle_url('/user/profile.php', array('id' => $USER->id)); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); if (is_mnet_remote_user($USER) && ($idprovider = $DB->get_record('mnet_host', array('id' => $USER->mnethostid)))) { $branchlabel = '<em><i class="fa fa-users"></i>' . get_string('loggedinfrom', 'theme_essential') . $idprovider->name . '</em>'; $branchurl = new moodle_url($idprovider->wwwroot); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } if (is_role_switched($course->id)) { // Has switched roles. $branchlabel = '<em><i class="fa fa-users"></i>' . get_string('switchrolereturn') . '</em>'; $branchurl = new moodle_url('/course/switchrole.php', array('id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $this->page->url->out_as_local_url(false))); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } // Add preferences submenu. $usermenu .= $this->theme_essential_render_preferences($context); $usermenu .= html_writer::empty_tag('hr', array('class' => 'sep')); // Output Calendar link if user is allowed to edit own calendar entries. if (has_capability('moodle/calendar:manageownentries', $context)) { $branchlabel = '<em><i class="fa fa-calendar"></i>' . get_string('pluginname', 'block_calendar_month') . '</em>'; $branchurl = new moodle_url('/calendar/view.php'); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } // Check if messaging is enabled. if (!empty($CFG->messaging)) { $branchlabel = '<em><i class="fa fa-envelope"></i>' . get_string('pluginname', 'block_messages') . '</em>'; $branchurl = new moodle_url('/message/index.php'); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } // Check if user is allowed to manage files. if (has_capability('moodle/user:manageownfiles', $context)) { $branchlabel = '<em><i class="fa fa-file"></i>' . get_string('privatefiles', 'block_private_files') . '</em>'; $branchurl = new moodle_url('/user/files.php'); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } // Check if user is allowed to view discussions. if (has_capability('mod/forum:viewdiscussion', $context)) { $branchlabel = '<em><i class="fa fa-list-alt"></i>' . get_string('forumposts', 'mod_forum') . '</em>'; $branchurl = new moodle_url('/mod/forum/user.php', array('id' => $USER->id)); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); $branchlabel = '<em><i class="fa fa-list"></i>' . get_string('discussions', 'mod_forum') . '</em>'; $branchurl = new moodle_url('/mod/forum/user.php', array('id' => $USER->id, 'mode' => 'discussions')); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); $usermenu .= html_writer::empty_tag('hr', array('class' => 'sep')); } // Output user grade links course sensitive, workaround for frontpage, selecting first enrolled course. if ($course->id == SITEID) { $branchlabel = '<em><i class="fa fa-list-alt"></i>' . get_string('mygrades', 'theme_essential') . '</em>'; $branchurl = new moodle_url('/grade/report/overview/index.php', array('id' => $course->id, 'userid' => $USER->id)); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } else { if (has_capability('gradereport/overview:view', $context)) { $branchlabel = '<em><i class="fa fa-list-alt"></i>' . get_string('mygrades', 'theme_essential') . '</em>'; $branchurl = new moodle_url('/grade/report/overview/index.php', array('id' => $course->id, 'userid' => $USER->id)); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } if (has_capability('gradereport/user:view', $context)) { // In Course also output Course grade links. $branchlabel = '<em><i class="fa fa-list-alt"></i>' . get_string('coursegrades', 'theme_essential') . '</em>'; $branchurl = new moodle_url('/grade/report/user/index.php', array('id' => $course->id, 'userid' => $USER->id)); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } } // Check if badges are enabled. if (!empty($CFG->enablebadges) && has_capability('moodle/badges:manageownbadges', $context)) { $branchlabel = '<em><i class="fa fa-certificate"></i>' . get_string('badges') . '</em>'; $branchurl = new moodle_url('/badges/mybadges.php'); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } $usermenu .= html_writer::empty_tag('hr', array('class' => 'sep')); // Render direct logout link. $branchlabel = '<em><i class="fa fa-sign-out"></i>' . get_string('logout') . '</em>'; if (\core\session\manager::is_loggedinas()) { $branchurl = new moodle_url('/course/loginas.php', array('id' => $course->id, 'sesskey' => sesskey())); } else { $branchurl = new moodle_url('/login/logout.php', array('sesskey' => sesskey())); } $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); // Render Help Link. $usermenu .= $this->theme_essential_render_helplink(); $usermenu .= html_writer::end_tag('ul'); } } $usermenu .= html_writer::end_tag('li'); $usermenu .= html_writer::end_tag('ul'); return $usermenu; }
/** * Check whether a major upgrade is needed. That is defined as an upgrade that * changes something really fundamental in the database, so nothing can possibly * work until the database has been updated, and that is defined by the hard-coded * version number in this function. */ function redirect_if_major_upgrade_required() { global $CFG; $lastmajordbchanges = 2012110201; if (empty($CFG->version) or (int) $CFG->version < $lastmajordbchanges or during_initial_install() or !empty($CFG->adminsetuppending)) { try { @session_get_instance()->terminate_current(); } catch (Exception $e) { // Ignore any errors, redirect to upgrade anyway. } $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php'; @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); @header('Location: ' . $url); echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url)); exit; } }
/** * Mark a context as dirty (with timestamp) so as to force reloading of the context. * * @deprecated since 2.2, use $context->mark_dirty() instead * @see context::mark_dirty() * @param string $path context path */ function mark_context_dirty($path) { global $CFG, $USER, $ACCESSLIB_PRIVATE; debugging('mark_context_dirty() is deprecated, please use $context->mark_dirty() instead.', DEBUG_DEVELOPER); if (during_initial_install()) { return; } // only if it is a non-empty string if (is_string($path) && $path !== '') { set_cache_flag('accesslib/dirtycontexts', $path, 1, time() + $CFG->sessiontimeout); if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) { $ACCESSLIB_PRIVATE->dirtycontexts[$path] = 1; } else { if (CLI_SCRIPT) { $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1); } else { if (isset($USER->access['time'])) { $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time'] - 2); } else { $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1); } // flags not loaded yet, it will be done later in $context->reload_if_dirty() } } } }
/** * Initialise the settings navigation based on the current context * * This function initialises the settings navigation tree for a given context * by calling supporting functions to generate major parts of the tree. * */ public function initialise() { global $DB, $SESSION, $SITE; if (during_initial_install()) { return false; } else { if ($this->initialised) { return true; } } $this->id = 'settingsnav'; $this->context = $this->page->context; $context = $this->context; if ($context->contextlevel == CONTEXT_BLOCK) { $this->load_block_settings(); $context = $context->get_parent_context(); } switch ($context->contextlevel) { case CONTEXT_SYSTEM: if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section' => 'frontpagesettings')))) { $this->load_front_page_settings($context->id == $this->context->id); } break; case CONTEXT_COURSECAT: $this->load_category_settings(); break; case CONTEXT_COURSE: if ($this->page->course->id != $SITE->id) { $this->load_course_settings($context->id == $this->context->id); } else { $this->load_front_page_settings($context->id == $this->context->id); } break; case CONTEXT_MODULE: $this->load_module_settings(); $this->load_course_settings(); break; case CONTEXT_USER: if ($this->page->course->id != $SITE->id) { $this->load_course_settings(); } break; } $settings = $this->load_user_settings($this->page->course->id); if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') || $SESSION->load_navigation_admin)) { $admin = $this->load_administration_settings(); $SESSION->load_navigation_admin = $admin->has_children(); } else { $admin = false; } if ($context->contextlevel == CONTEXT_SYSTEM && $admin) { $admin->force_open(); } else { if ($context->contextlevel == CONTEXT_USER && $settings) { $settings->force_open(); } } // Check if the user is currently logged in as another user if (session_is_loggedinas()) { // Get the actual user, we need this so we can display an informative return link $realuser = session_get_realuser(); // Add the informative return to original user link $url = new moodle_url('/course/loginas.php', array('id' => $this->page->course->id, 'return' => 1, 'sesskey' => sesskey())); $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', '')); } // At this point we give any local plugins the ability to extend/tinker with the navigation settings. $this->load_local_plugin_settings(); foreach ($this->children as $key => $node) { if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count() === 0) { $node->remove(); } } $this->initialised = true; }
/** * Given a simple string, this function returns the string * processed by enabled string filters if $CFG->filterall is enabled * * This function should be used to print short strings (non html) that * need filter processing e.g. activity titles, post subjects, * glossary concepts. * * @staticvar bool $strcache * @param string $string The string to be filtered. Should be plain text, expect * possibly for multilang tags. * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713 * @param array $options options array/object or courseid * @return string */ function format_string($string, $striplinks = true, $options = null) { global $CFG, $PAGE; // We'll use a in-memory cache here to speed up repeated strings. static $strcache = false; if (empty($CFG->version) or $CFG->version < 2013051400 or during_initial_install()) { // Do not filter anything during installation or before upgrade completes. return $string = strip_tags($string); } if ($strcache === false or count($strcache) > 2000) { // This number might need some tuning to limit memory usage in cron. $strcache = array(); } if (is_numeric($options)) { // Legacy courseid usage. $options = array('context' => context_course::instance($options)); } else { // Detach object, we can not modify it. $options = (array) $options; } if (empty($options['context'])) { // Fallback to $PAGE->context this may be problematic in CLI and other non-standard pages :-(. $options['context'] = $PAGE->context; } else { if (is_numeric($options['context'])) { $options['context'] = context::instance_by_id($options['context']); } } if (!$options['context']) { // We did not find any context? weird. return $string = strip_tags($string); } // Calculate md5. $md5 = md5($string . '<+>' . $striplinks . '<+>' . $options['context']->id . '<+>' . current_language()); // Fetch from cache if possible. if (isset($strcache[$md5])) { return $strcache[$md5]; } // First replace all ampersands not followed by html entity code // Regular expression moved to its own method for easier unit testing. $string = replace_ampersands_not_followed_by_entity($string); if (!empty($CFG->filterall)) { $filtermanager = filter_manager::instance(); $filtermanager->setup_page_for_filters($PAGE, $options['context']); // Setup global stuff filters may have. $string = $filtermanager->filter_string($string, $options['context']); } // If the site requires it, strip ALL tags from this string. if (!empty($CFG->formatstringstriptags)) { $string = str_replace(array('<', '>'), array('<', '>'), strip_tags($string)); } else { // Otherwise strip just links if that is required (default). if ($striplinks) { // Strip links in string. $string = strip_links($string); } $string = clean_text($string); } // Store to cache. $strcache[$md5] = $string; return $string; }