/** * Helper method to apply filters to some text and return the result. * @param string $text the text to filter. * @param array $skipfilters any filters not to apply, even if they are configured. * @return string the filtered text. */ protected function filter_text($text, $skipfilters) { global $PAGE; $filtermanager = filter_manager::instance(); $filtermanager->setup_page_for_filters($PAGE, $PAGE->context); $filteroptions = array('originalformat' => FORMAT_HTML, 'noclean' => false); return $filtermanager->filter_text($text, $PAGE->context, $filteroptions, $skipfilters); }
/** * Given some text in HTML format, this function will pass it * through any filters that have been configured for this context. * * @deprecated use the text formatting in a standard way instead, * this was abused mostly for embedding of attachments * * @param string $text The text to be passed through format filters * @param int $courseid The current course. * @return string the filtered string. */ function filter_text($text, $courseid = NULL) { global $CFG, $COURSE; if (!$courseid) { $courseid = $COURSE->id; } if (!($context = get_context_instance(CONTEXT_COURSE, $courseid))) { return $text; } return filter_manager::instance()->filter_text($text, $context); }
/** * Given some text in HTML format, this function will pass it * through any filters that have been configured for this context. * * @deprecated use the text formatting in a standard way instead, * this was abused mostly for embedding of attachments * * @param string $text The text to be passed through format filters * @param int $courseid The current course. * @return string the filtered string. */ function filter_text($text, $courseid = NULL) { global $CFG, $COURSE; if (!$courseid) { $courseid = $COURSE->id; } if (!($context = context_course::instance($courseid, IGNORE_MISSING))) { return $text; } return filter_manager::instance()->filter_text($text, $context); }
/** * Given some text in HTML format, this function will pass it * through any filters that have been configured for this context. * * @param string $text The text to be passed through format filters * @param int $courseid The current course. * @return string the filtered string. */ function filter_text($text, $courseid = NULL) { global $CFG, $COURSE, $PAGE; if (empty($courseid)) { $courseid = $COURSE->id; // (copied from format_text) } $context = $PAGE->context; return filter_manager::instance()->filter_text($text, $context, $courseid); }
public function test_external_format_string() { $this->resetAfterTest(); $settings = external_settings::get_instance(); $currentraw = $settings->get_raw(); $currentfilter = $settings->get_filter(); // Enable multilang filter to on content and heading. filter_set_global_state('multilang', TEXTFILTER_ON); filter_set_applies_to_strings('multilang', 1); $filtermanager = filter_manager::instance(); $filtermanager->reset_caches(); $settings->set_raw(true); $settings->set_filter(true); $context = context_system::instance(); $test = '<span lang="en" class="multilang">EN</span><span lang="fr" class="multilang">FR</span> ' . '<script>hi</script> <h3>there</h3>!'; $correct = $test; $this->assertSame($correct, external_format_string($test, $context->id)); $settings->set_raw(false); $settings->set_filter(false); $test = '<span lang="en" class="multilang">EN</span><span lang="fr" class="multilang">FR</span> ' . '<script>hi</script> <h3>there</h3>?'; $correct = 'ENFR hi there?'; $this->assertSame($correct, external_format_string($test, $context->id)); $settings->set_filter(true); $test = '<span lang="en" class="multilang">EN</span><span lang="fr" class="multilang">FR</span> ' . '<script>hi</script> <h3>there</h3>@'; $correct = 'EN hi there@'; $this->assertSame($correct, external_format_string($test, $context->id)); // Filters can be opted out. $test = '<span lang="en" class="multilang">EN</span><span lang="fr" class="multilang">FR</span> ' . '<script>hi</script> <h3>there</h3>%'; $correct = 'ENFR hi there%'; $this->assertSame($correct, external_format_string($test, $context->id, false, ['filter' => false])); $settings->set_raw($currentraw); $settings->set_filter($currentfilter); }
/** * get_performance_info() pairs up with init_performance_info() * loaded in setup.php. Returns an array with 'html' and 'txt' * values ready for use, and each of the individual stats provided * separately as well. * * @global object * @global object * @global object * @return array */ function get_performance_info() { global $CFG, $PERF, $DB, $PAGE; $info = array(); $info['html'] = ''; // holds userfriendly HTML representation $info['txt'] = me() . ' '; // holds log-friendly representation $info['realtime'] = microtime_diff($PERF->starttime, microtime()); $info['html'] .= '<span class="timeused">' . $info['realtime'] . ' secs</span> '; $info['txt'] .= 'time: ' . $info['realtime'] . 's '; if (function_exists('memory_get_usage')) { $info['memory_total'] = memory_get_usage(); $info['memory_growth'] = memory_get_usage() - $PERF->startmemory; $info['html'] .= '<span class="memoryused">RAM: ' . display_size($info['memory_total']) . '</span> '; $info['txt'] .= 'memory_total: ' . $info['memory_total'] . 'B (' . display_size($info['memory_total']) . ') memory_growth: ' . $info['memory_growth'] . 'B (' . display_size($info['memory_growth']) . ') '; } if (function_exists('memory_get_peak_usage')) { $info['memory_peak'] = memory_get_peak_usage(); $info['html'] .= '<span class="memoryused">RAM peak: ' . display_size($info['memory_peak']) . '</span> '; $info['txt'] .= 'memory_peak: ' . $info['memory_peak'] . 'B (' . display_size($info['memory_peak']) . ') '; } $inc = get_included_files(); //error_log(print_r($inc,1)); $info['includecount'] = count($inc); $info['html'] .= '<span class="included">Included ' . $info['includecount'] . ' files</span> '; $info['txt'] .= 'includecount: ' . $info['includecount'] . ' '; $filtermanager = filter_manager::instance(); if (method_exists($filtermanager, 'get_performance_summary')) { list($filterinfo, $nicenames) = $filtermanager->get_performance_summary(); $info = array_merge($filterinfo, $info); foreach ($filterinfo as $key => $value) { $info['html'] .= "<span class='{$key}'>{$nicenames[$key]}: {$value} </span> "; $info['txt'] .= "{$key}: {$value} "; } } $stringmanager = get_string_manager(); if (method_exists($stringmanager, 'get_performance_summary')) { list($filterinfo, $nicenames) = $stringmanager->get_performance_summary(); $info = array_merge($filterinfo, $info); foreach ($filterinfo as $key => $value) { $info['html'] .= "<span class='{$key}'>{$nicenames[$key]}: {$value} </span> "; $info['txt'] .= "{$key}: {$value} "; } } $jsmodules = $PAGE->requires->get_loaded_modules(); if ($jsmodules) { $yuicount = 0; $othercount = 0; $details = ''; foreach ($jsmodules as $module => $backtraces) { if (strpos($module, 'yui') === 0) { $yuicount += 1; } else { $othercount += 1; } $details .= "<div class='yui-module'><p>{$module}</p>"; foreach ($backtraces as $backtrace) { $details .= "<div class='backtrace'>{$backtrace}</div>"; } $details .= '</div>'; } $info['html'] .= "<span class='includedyuimodules'>Included YUI modules: {$yuicount}</span> "; $info['txt'] .= "includedyuimodules: {$yuicount} "; $info['html'] .= "<span class='includedjsmodules'>Other JavaScript modules: {$othercount}</span> "; $info['txt'] .= "includedjsmodules: {$othercount} "; // Slightly odd to output the details in a display: none div. The point // Is that it takes a lot of space, and if you care you can reveal it // using firebug. $info['html'] .= '<div id="yui-module-debug" class="notifytiny">' . $details . '</div>'; } if (!empty($PERF->logwrites)) { $info['logwrites'] = $PERF->logwrites; $info['html'] .= '<span class="logwrites">Log DB writes ' . $info['logwrites'] . '</span> '; $info['txt'] .= 'logwrites: ' . $info['logwrites'] . ' '; } $info['dbqueries'] = $DB->perf_get_reads() . '/' . ($DB->perf_get_writes() - $PERF->logwrites); $info['html'] .= '<span class="dbqueries">DB reads/writes: ' . $info['dbqueries'] . '</span> '; $info['txt'] .= 'db reads/writes: ' . $info['dbqueries'] . ' '; if (!empty($PERF->profiling) && $PERF->profiling) { require_once $CFG->dirroot . '/lib/profilerlib.php'; $info['html'] .= '<span class="profilinginfo">' . Profiler::get_profiling(array('-R')) . '</span>'; } if (function_exists('posix_times')) { $ptimes = posix_times(); if (is_array($ptimes)) { foreach ($ptimes as $key => $val) { $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key]; } $info['html'] .= "<span class=\"posixtimes\">ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']}</span> "; $info['txt'] .= "ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']} "; } } // Grab the load average for the last minute // /proc will only work under some linux configurations // while uptime is there under MacOSX/Darwin and other unices if (is_readable('/proc/loadavg') && ($loadavg = @file('/proc/loadavg'))) { list($server_load) = explode(' ', $loadavg[0]); unset($loadavg); } else { if (function_exists('is_executable') && is_executable('/usr/bin/uptime') && ($loadavg = `/usr/bin/uptime`)) { if (preg_match('/load averages?: (\\d+[\\.,:]\\d+)/', $loadavg, $matches)) { $server_load = $matches[1]; } else { trigger_error('Could not parse uptime output!'); } } } if (!empty($server_load)) { $info['serverload'] = $server_load; $info['html'] .= '<span class="serverload">Load average: ' . $info['serverload'] . '</span> '; $info['txt'] .= "serverload: {$info['serverload']} "; } // Display size of session if session started if (session_id()) { $info['sessionsize'] = display_size(strlen(session_encode())); $info['html'] .= '<span class="sessionsize">Session: ' . $info['sessionsize'] . '</span> '; $info['txt'] .= "Session: {$info['sessionsize']} "; } /* if (isset($rcache->hits) && isset($rcache->misses)) { $info['rcachehits'] = $rcache->hits; $info['rcachemisses'] = $rcache->misses; $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '. "{$rcache->hits}/{$rcache->misses}</span> "; $info['txt'] .= 'rcache: '. "{$rcache->hits}/{$rcache->misses} "; }*/ $info['html'] = '<div class="performanceinfo siteinfo">' . $info['html'] . '</div>'; return $info; }
/** * get_performance_info() pairs up with init_performance_info() * loaded in setup.php. Returns an array with 'html' and 'txt' * values ready for use, and each of the individual stats provided * separately as well. * * @return array */ function get_performance_info() { global $CFG, $PERF, $DB, $PAGE; $info = array(); $info['html'] = ''; // Holds userfriendly HTML representation. $info['txt'] = me() . ' '; // Holds log-friendly representation. $info['realtime'] = microtime_diff($PERF->starttime, microtime()); $info['html'] .= '<span class="timeused">' . $info['realtime'] . ' secs</span> '; $info['txt'] .= 'time: ' . $info['realtime'] . 's '; if (function_exists('memory_get_usage')) { $info['memory_total'] = memory_get_usage(); $info['memory_growth'] = memory_get_usage() - $PERF->startmemory; $info['html'] .= '<span class="memoryused">RAM: ' . display_size($info['memory_total']) . '</span> '; $info['txt'] .= 'memory_total: ' . $info['memory_total'] . 'B (' . display_size($info['memory_total']) . ') memory_growth: ' . $info['memory_growth'] . 'B (' . display_size($info['memory_growth']) . ') '; } if (function_exists('memory_get_peak_usage')) { $info['memory_peak'] = memory_get_peak_usage(); $info['html'] .= '<span class="memoryused">RAM peak: ' . display_size($info['memory_peak']) . '</span> '; $info['txt'] .= 'memory_peak: ' . $info['memory_peak'] . 'B (' . display_size($info['memory_peak']) . ') '; } $inc = get_included_files(); $info['includecount'] = count($inc); $info['html'] .= '<span class="included">Included ' . $info['includecount'] . ' files</span> '; $info['txt'] .= 'includecount: ' . $info['includecount'] . ' '; if (!empty($CFG->early_install_lang) or empty($PAGE)) { // We can not track more performance before installation or before PAGE init, sorry. return $info; } $filtermanager = filter_manager::instance(); if (method_exists($filtermanager, 'get_performance_summary')) { list($filterinfo, $nicenames) = $filtermanager->get_performance_summary(); $info = array_merge($filterinfo, $info); foreach ($filterinfo as $key => $value) { $info['html'] .= "<span class='{$key}'>{$nicenames[$key]}: {$value} </span> "; $info['txt'] .= "{$key}: {$value} "; } } $stringmanager = get_string_manager(); if (method_exists($stringmanager, 'get_performance_summary')) { list($filterinfo, $nicenames) = $stringmanager->get_performance_summary(); $info = array_merge($filterinfo, $info); foreach ($filterinfo as $key => $value) { $info['html'] .= "<span class='{$key}'>{$nicenames[$key]}: {$value} </span> "; $info['txt'] .= "{$key}: {$value} "; } } $jsmodules = $PAGE->requires->get_loaded_modules(); if ($jsmodules) { $yuicount = 0; $othercount = 0; $details = ''; foreach ($jsmodules as $module => $backtraces) { if (strpos($module, 'yui') === 0) { $yuicount += 1; } else { $othercount += 1; } if (!empty($CFG->yuimoduledebug)) { // Hidden feature for developers working on YUI module infrastructure. $details .= "<div class='yui-module'><p>{$module}</p>"; foreach ($backtraces as $backtrace) { $details .= "<div class='backtrace'>{$backtrace}</div>"; } $details .= '</div>'; } } $info['html'] .= "<span class='includedyuimodules'>Included YUI modules: {$yuicount}</span> "; $info['txt'] .= "includedyuimodules: {$yuicount} "; $info['html'] .= "<span class='includedjsmodules'>Other JavaScript modules: {$othercount}</span> "; $info['txt'] .= "includedjsmodules: {$othercount} "; if ($details) { $info['html'] .= '<div id="yui-module-debug" class="notifytiny">' . $details . '</div>'; } } if (!empty($PERF->logwrites)) { $info['logwrites'] = $PERF->logwrites; $info['html'] .= '<span class="logwrites">Log DB writes ' . $info['logwrites'] . '</span> '; $info['txt'] .= 'logwrites: ' . $info['logwrites'] . ' '; } $info['dbqueries'] = $DB->perf_get_reads() . '/' . ($DB->perf_get_writes() - $PERF->logwrites); $info['html'] .= '<span class="dbqueries">DB reads/writes: ' . $info['dbqueries'] . '</span> '; $info['txt'] .= 'db reads/writes: ' . $info['dbqueries'] . ' '; if (function_exists('posix_times')) { $ptimes = posix_times(); if (is_array($ptimes)) { foreach ($ptimes as $key => $val) { $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key]; } $info['html'] .= "<span class=\"posixtimes\">ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']}</span> "; $info['txt'] .= "ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']} "; } } // Grab the load average for the last minute. // /proc will only work under some linux configurations // while uptime is there under MacOSX/Darwin and other unices. if (is_readable('/proc/loadavg') && ($loadavg = @file('/proc/loadavg'))) { list($serverload) = explode(' ', $loadavg[0]); unset($loadavg); } else { if (function_exists('is_executable') && is_executable('/usr/bin/uptime') && ($loadavg = `/usr/bin/uptime`)) { if (preg_match('/load averages?: (\\d+[\\.,:]\\d+)/', $loadavg, $matches)) { $serverload = $matches[1]; } else { trigger_error('Could not parse uptime output!'); } } } if (!empty($serverload)) { $info['serverload'] = $serverload; $info['html'] .= '<span class="serverload">Load average: ' . $info['serverload'] . '</span> '; $info['txt'] .= "serverload: {$info['serverload']} "; } // Display size of session if session started. if ($si = \core\session\manager::get_performance_info()) { $info['sessionsize'] = $si['size']; $info['html'] .= $si['html']; $info['txt'] .= $si['txt']; } if ($stats = cache_helper::get_stats()) { $html = '<span class="cachesused">'; $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>'; $text = 'Caches used (hits/misses/sets): '; $hits = 0; $misses = 0; $sets = 0; foreach ($stats as $definition => $stores) { $html .= '<span class="cache-definition-stats">'; $html .= '<span class="cache-definition-stats-heading">' . $definition . '</span>'; $text .= "{$definition} {"; foreach ($stores as $store => $data) { $hits += $data['hits']; $misses += $data['misses']; $sets += $data['sets']; if ($data['hits'] == 0 and $data['misses'] > 0) { $cachestoreclass = 'nohits'; } else { if ($data['hits'] < $data['misses']) { $cachestoreclass = 'lowhits'; } else { $cachestoreclass = 'hihits'; } } $text .= "{$store}({$data['hits']}/{$data['misses']}/{$data['sets']}) "; $html .= "<span class=\"cache-store-stats {$cachestoreclass}\">{$store}: {$data['hits']} / {$data['misses']} / {$data['sets']}</span>"; } $html .= '</span>'; $text .= '} '; } $html .= "<span class='cache-total-stats'>Total: {$hits} / {$misses} / {$sets}</span>"; $html .= '</span> '; $info['cachesused'] = "{$hits} / {$misses} / {$sets}"; $info['html'] .= $html; $info['txt'] .= $text . '. '; } else { $info['cachesused'] = '0 / 0 / 0'; $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>'; $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 '; } $info['html'] = '<div class="performanceinfo siteinfo">' . $info['html'] . '</div>'; return $info; }
// GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Renders text with the active filters and returns it. Used to create previews of computings * using whatever tex filters are enabled. * * @package atto_computing * @copyright 2014 Geoffrey Rowland <*****@*****.**> * Based on @package atto_equation * @copyright 2013 Damyon Wiese <*****@*****.**> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define('AJAX_SCRIPT', true); require_once dirname(__FILE__) . '/../../../../../config.php'; $contextid = required_param('contextid', PARAM_INT); list($context, $course, $cm) = get_context_info_array($contextid); $PAGE->set_url('/lib/editor/atto/plugins/computing/ajax.php'); $PAGE->set_context($context); require_login($course, false, $cm); require_sesskey(); $action = required_param('action', PARAM_ALPHA); if ($action === 'filtertext') { $text = required_param('text', PARAM_RAW); $result = filter_manager::instance()->filter_text($text, $context); echo $OUTPUT->header(); echo $result; die; } print_error('invalidarguments');
/** * get_performance_info() pairs up with init_performance_info() * loaded in setup.php. Returns an array with 'html' and 'txt' * values ready for use, and each of the individual stats provided * separately as well. * * @global object * @global object * @global object * @return array */ function get_performance_info() { global $CFG, $PERF, $DB, $PAGE; $info = array(); $info['html'] = ''; // holds userfriendly HTML representation $info['txt'] = me() . ' '; // holds log-friendly representation $info['realtime'] = microtime_diff($PERF->starttime, microtime()); $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> '; $info['txt'] .= 'time: '.$info['realtime'].'s '; if (function_exists('memory_get_usage')) { $info['memory_total'] = memory_get_usage(); $info['memory_growth'] = memory_get_usage() - $PERF->startmemory; $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> '; $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') '; } if (function_exists('memory_get_peak_usage')) { $info['memory_peak'] = memory_get_peak_usage(); $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> '; $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') '; } $inc = get_included_files(); //error_log(print_r($inc,1)); $info['includecount'] = count($inc); $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> '; $info['txt'] .= 'includecount: '.$info['includecount'].' '; $filtermanager = filter_manager::instance(); if (method_exists($filtermanager, 'get_performance_summary')) { list($filterinfo, $nicenames) = $filtermanager->get_performance_summary(); $info = array_merge($filterinfo, $info); foreach ($filterinfo as $key => $value) { $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> "; $info['txt'] .= "$key: $value "; } } $stringmanager = get_string_manager(); if (method_exists($stringmanager, 'get_performance_summary')) { list($filterinfo, $nicenames) = $stringmanager->get_performance_summary(); $info = array_merge($filterinfo, $info); foreach ($filterinfo as $key => $value) { $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> "; $info['txt'] .= "$key: $value "; } } $jsmodules = $PAGE->requires->get_loaded_modules(); if ($jsmodules) { $yuicount = 0; $othercount = 0; $details = ''; foreach ($jsmodules as $module => $backtraces) { if (strpos($module, 'yui') === 0) { $yuicount += 1; } else { $othercount += 1; } if (!empty($CFG->yuimoduledebug)) { // hidden feature for developers working on YUI module infrastructure $details .= "<div class='yui-module'><p>$module</p>"; foreach ($backtraces as $backtrace) { $details .= "<div class='backtrace'>$backtrace</div>"; } $details .= '</div>'; } } $info['html'] .= "<span class='includedyuimodules'>Included YUI modules: $yuicount</span> "; $info['txt'] .= "includedyuimodules: $yuicount "; $info['html'] .= "<span class='includedjsmodules'>Other JavaScript modules: $othercount</span> "; $info['txt'] .= "includedjsmodules: $othercount "; if ($details) { $info['html'] .= '<div id="yui-module-debug" class="notifytiny">'.$details.'</div>'; } } if (!empty($PERF->logwrites)) { $info['logwrites'] = $PERF->logwrites; $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> '; $info['txt'] .= 'logwrites: '.$info['logwrites'].' '; } $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites); $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> '; $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' '; if (function_exists('posix_times')) { $ptimes = posix_times(); if (is_array($ptimes)) { foreach ($ptimes as $key => $val) { $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key]; } $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> "; $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] "; } } // Grab the load average for the last minute // /proc will only work under some linux configurations // while uptime is there under MacOSX/Darwin and other unices if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) { list($server_load) = explode(' ', $loadavg[0]); unset($loadavg); } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) { if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) { $server_load = $matches[1]; } else { trigger_error('Could not parse uptime output!'); } } if (!empty($server_load)) { $info['serverload'] = $server_load; $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> '; $info['txt'] .= "serverload: {$info['serverload']} "; } // Display size of session if session started if (session_id()) { $info['sessionsize'] = display_size(strlen(session_encode())); $info['html'] .= '<span class="sessionsize">Session: ' . $info['sessionsize'] . '</span> '; $info['txt'] .= "Session: {$info['sessionsize']} "; } /* if (isset($rcache->hits) && isset($rcache->misses)) { $info['rcachehits'] = $rcache->hits; $info['rcachemisses'] = $rcache->misses; $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '. "{$rcache->hits}/{$rcache->misses}</span> "; $info['txt'] .= 'rcache: '. "{$rcache->hits}/{$rcache->misses} "; }*/ if ($stats = cache_helper::get_stats()) { $html = '<span class="cachesused">'; $html .= '<span class="cache-stats-heading">Caches interaction by definition then store</span>'; $text = 'Caches used (hits/misses/sets): '; $hits = 0; $misses = 0; $sets = 0; foreach ($stats as $definition => $stores) { $html .= '<span class="cache-definition-stats">'.$definition.'</span>'; $text .= "$definition {"; foreach ($stores as $store => $data) { $hits += $data['hits']; $misses += $data['misses']; $sets += $data['sets']; $text .= "$store($data[hits]/$data[misses]/$data[sets]) "; $html .= "<span class='cache-store-stats'>$store: $data[hits] / $data[misses] / $data[sets]</span>"; } $text .= '} '; } $html .= "<span class='cache-total-stats'>Total Hits / Misses / Sets : $hits / $misses / $sets</span>"; $html .= '</span> '; $info['cachesused'] = "$hits / $misses / $sets"; $info['html'] .= $html; $info['txt'] .= $text.'. '; } else { $info['cachesused'] = '0 / 0 / 0'; $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>'; $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 '; } $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>'; return $info; }
/** * get_performance_info() pairs up with init_performance_info() * loaded in setup.php. Returns an array with 'html' and 'txt' * values ready for use, and each of the individual stats provided * separately as well. * * @return array */ function get_performance_info() { global $CFG, $PERF, $DB, $PAGE; $info = array(); $info['txt'] = me() . ' '; // Holds log-friendly representation. $info['html'] = ''; if (!empty($CFG->themedesignermode)) { // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on. $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>'; } $info['html'] .= '<ul class="list-unstyled m-l-1">'; // Holds userfriendly HTML representation. $info['realtime'] = microtime_diff($PERF->starttime, microtime()); $info['html'] .= '<li class="timeused">' . $info['realtime'] . ' secs</li> '; $info['txt'] .= 'time: ' . $info['realtime'] . 's '; if (function_exists('memory_get_usage')) { $info['memory_total'] = memory_get_usage(); $info['memory_growth'] = memory_get_usage() - $PERF->startmemory; $info['html'] .= '<li class="memoryused">RAM: ' . display_size($info['memory_total']) . '</li> '; $info['txt'] .= 'memory_total: ' . $info['memory_total'] . 'B (' . display_size($info['memory_total']) . ') memory_growth: ' . $info['memory_growth'] . 'B (' . display_size($info['memory_growth']) . ') '; } if (function_exists('memory_get_peak_usage')) { $info['memory_peak'] = memory_get_peak_usage(); $info['html'] .= '<li class="memoryused">RAM peak: ' . display_size($info['memory_peak']) . '</li> '; $info['txt'] .= 'memory_peak: ' . $info['memory_peak'] . 'B (' . display_size($info['memory_peak']) . ') '; } $inc = get_included_files(); $info['includecount'] = count($inc); $info['html'] .= '<li class="included">Included ' . $info['includecount'] . ' files</li> '; $info['txt'] .= 'includecount: ' . $info['includecount'] . ' '; if (!empty($CFG->early_install_lang) or empty($PAGE)) { // We can not track more performance before installation or before PAGE init, sorry. return $info; } $filtermanager = filter_manager::instance(); if (method_exists($filtermanager, 'get_performance_summary')) { list($filterinfo, $nicenames) = $filtermanager->get_performance_summary(); $info = array_merge($filterinfo, $info); foreach ($filterinfo as $key => $value) { $info['html'] .= "<li class='{$key}'>{$nicenames[$key]}: {$value} </li> "; $info['txt'] .= "{$key}: {$value} "; } } $stringmanager = get_string_manager(); if (method_exists($stringmanager, 'get_performance_summary')) { list($filterinfo, $nicenames) = $stringmanager->get_performance_summary(); $info = array_merge($filterinfo, $info); foreach ($filterinfo as $key => $value) { $info['html'] .= "<li class='{$key}'>{$nicenames[$key]}: {$value} </li> "; $info['txt'] .= "{$key}: {$value} "; } } if (!empty($PERF->logwrites)) { $info['logwrites'] = $PERF->logwrites; $info['html'] .= '<li class="logwrites">Log DB writes ' . $info['logwrites'] . '</li> '; $info['txt'] .= 'logwrites: ' . $info['logwrites'] . ' '; } $info['dbqueries'] = $DB->perf_get_reads() . '/' . ($DB->perf_get_writes() - $PERF->logwrites); $info['html'] .= '<li class="dbqueries">DB reads/writes: ' . $info['dbqueries'] . '</li> '; $info['txt'] .= 'db reads/writes: ' . $info['dbqueries'] . ' '; $info['dbtime'] = round($DB->perf_get_queries_time(), 5); $info['html'] .= '<li class="dbtime">DB queries time: ' . $info['dbtime'] . ' secs</li> '; $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's '; if (function_exists('posix_times')) { $ptimes = posix_times(); if (is_array($ptimes)) { foreach ($ptimes as $key => $val) { $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key]; } $info['html'] .= "<li class=\"posixtimes\">ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']}</li> "; $info['txt'] .= "ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']} "; } } // Grab the load average for the last minute. // /proc will only work under some linux configurations // while uptime is there under MacOSX/Darwin and other unices. if (is_readable('/proc/loadavg') && ($loadavg = @file('/proc/loadavg'))) { list($serverload) = explode(' ', $loadavg[0]); unset($loadavg); } else { if (function_exists('is_executable') && is_executable('/usr/bin/uptime') && ($loadavg = `/usr/bin/uptime`)) { if (preg_match('/load averages?: (\\d+[\\.,:]\\d+)/', $loadavg, $matches)) { $serverload = $matches[1]; } else { trigger_error('Could not parse uptime output!'); } } } if (!empty($serverload)) { $info['serverload'] = $serverload; $info['html'] .= '<li class="serverload">Load average: ' . $info['serverload'] . '</li> '; $info['txt'] .= "serverload: {$info['serverload']} "; } // Display size of session if session started. if ($si = \core\session\manager::get_performance_info()) { $info['sessionsize'] = $si['size']; $info['html'] .= $si['html']; $info['txt'] .= $si['txt']; } if ($stats = cache_helper::get_stats()) { $html = '<ul class="cachesused list-unstyled m-l-1">'; $html .= '<li class="cache-stats-heading">Caches used (hits/misses/sets)</li>'; $text = 'Caches used (hits/misses/sets): '; $hits = 0; $misses = 0; $sets = 0; foreach ($stats as $definition => $details) { switch ($details['mode']) { case cache_store::MODE_APPLICATION: $modeclass = 'application'; $mode = ' <span title="application cache">[a]</span>'; break; case cache_store::MODE_SESSION: $modeclass = 'session'; $mode = ' <span title="session cache">[s]</span>'; break; case cache_store::MODE_REQUEST: $modeclass = 'request'; $mode = ' <span title="request cache">[r]</span>'; break; } $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 cache-mode-' . $modeclass . '">'; $html .= '<li class="cache-definition-stats-heading p-t-1">' . $definition . $mode . '</li>'; $text .= "{$definition} {"; foreach ($details['stores'] as $store => $data) { $hits += $data['hits']; $misses += $data['misses']; $sets += $data['sets']; if ($data['hits'] == 0 and $data['misses'] > 0) { $cachestoreclass = 'nohits text-danger'; } else { if ($data['hits'] < $data['misses']) { $cachestoreclass = 'lowhits text-warning'; } else { $cachestoreclass = 'hihits text-success'; } } $text .= "{$store}({$data['hits']}/{$data['misses']}/{$data['sets']}) "; $html .= "<li class=\"cache-store-stats {$cachestoreclass}\">{$store}: {$data['hits']} / {$data['misses']} / {$data['sets']}</li>"; } $html .= '</ul>'; $text .= '} '; } $html .= '</ul> '; $html .= "<div class='cache-total-stats row'>Total: {$hits} / {$misses} / {$sets}</div>"; $info['cachesused'] = "{$hits} / {$misses} / {$sets}"; $info['html'] .= $html; $info['txt'] .= $text . '. '; } else { $info['cachesused'] = '0 / 0 / 0'; $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>'; $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 '; } $info['html'] = '<div class="performanceinfo siteinfo">' . $info['html'] . '</div>'; return $info; }
/** * filter_text_bodycontent */ function filter_text_bodycontent() { // prevent faulty conversion of HTML entities with leading zero in Moodle <= 2.5 // specifically, this affects non-breaking spaces ( ) in a JCloze WordList if (hotpot_textlib('entities_to_utf8', ' ') == 'p') { $this->bodycontent = preg_replace('/(?<=&#)0+([0-9]+)(?=;)/', '$1', $this->bodycontent); } // convert entities to utf8 $this->bodycontent = hotpot_textlib('entities_to_utf8', $this->bodycontent); // fix faulty conversion of non-breaking space ( ) in Moodle <= 2.0 $twobyte = chr(194) . chr(160); $fourbyte = chr(195) . chr(130) . $twobyte; if (hotpot_textlib('entities_to_utf8', ' ') == $fourbyte) { $this->bodycontent = str_replace($fourbyte, $twobyte, $this->bodycontent); } // we will skip these tags and everything they contain $tags = array('audio' => '</audio>', 'button' => '</button>', 'embed' => '</embed>', 'object' => '</object>', 'script' => '</script>', 'style' => '</style>', 'video' => '</video>', '!--' => '-->', '' => '>'); // cache the lengths of the tag strings $len = array(); foreach ($tags as $tag => $end) { $len[$tag] = strlen($tag); $len[$end] = strlen($end); } // array to store start and end positions // of $texts passed to the Moodle filters $texts = array(); // detect start and end of all $texts[$i] = $ii; // $i : start position // $ii : end position $i = 0; $i_max = strlen($this->bodycontent); while ($i < $i_max) { $ii = strpos($this->bodycontent, '<', $i); if ($ii === false) { $ii = $i_max; } $texts[$i] = $ii; if ($i < $i_max) { foreach ($tags as $tag => $end) { if ($len[$tag] == 0 || substr($this->bodycontent, $ii + 1, $len[$tag]) == $tag) { $char = substr($this->bodycontent, $ii + $len[$tag] + 1, 1); if ($len[$tag] == 0 || $char == ' ' || $char == '>') { if ($ii = strpos($this->bodycontent, $end, $ii + $len[$tag])) { $ii += $len[$end]; } else { $ii = $i_max; // no end tag - shouldn't happen !! } break; // foreach loop } } } } $i = $ii; } unset($tags, $len); // reverse the $texts array (preserve keys) $texts = array_reverse($texts, true); // cache filter and context $filter = filter_manager::instance(); $context = $this->hotpot->context; // setup filter (Moodle >= 2.3) if (method_exists($filter, 'setup_page_for_filters')) { $filter->setup_page_for_filters($this->page, $context); } // whitespace and punctuation chars $trimchars = "\t\n\r !\"#\$%&'()*+,-./:;<=>?@[\\]^_`{¦}~\v"; // filter all $texts foreach ($texts as $i => $ii) { $len = $ii - $i; $text = substr($this->bodycontent, $i, $len); // ignore strings that contain only whitespace and punctuation if (trim($text, $trimchars)) { $text = $filter->filter_text($text, $context); $this->bodycontent = substr_replace($this->bodycontent, $text, $i, $len); } } // convert back to HTML entities $this->bodycontent = hotpot_textlib('utf8_to_entities', $this->bodycontent); }
/** * Method for use by Moodle core to set up the theme. Do not * use this in your own code. * * Make sure the right theme for this page is loaded. Tell our * blocks_manager about the theme block regions, and then, if * we are $PAGE, set up the global $OUTPUT. * * @return void */ public function initialise_theme_and_output() { global $OUTPUT, $PAGE, $SITE, $CFG; if (!empty($this->_wherethemewasinitialised)) { return; } if (!during_initial_install()) { // Detect PAGE->context mess. $this->magic_get_context(); } if (!$this->_course && !during_initial_install()) { $this->set_course($SITE); } if (is_null($this->_theme)) { $themename = $this->resolve_theme(); $this->_theme = theme_config::load($themename); } $this->_theme->setup_blocks($this->pagelayout, $this->blocks); if ($this->_theme->enable_dock && !empty($CFG->allowblockstodock)) { $this->requires->strings_for_js(array('addtodock', 'undockitem', 'dockblock', 'undockblock', 'undockall', 'hidedockpanel', 'hidepanel'), 'block'); $this->requires->string_for_js('thisdirectionvertical', 'langconfig'); $this->requires->yui_module('moodle-core-dock-loader', 'M.core.dock.loader.initLoader'); } if ($this === $PAGE) { $target = null; if ($this->pagelayout === 'maintenance') { // If the page is using the maintenance layout then we're going to force target to maintenance. // This leads to a special core renderer that is designed to block access to API's that are likely unavailable for this // page layout. $target = RENDERER_TARGET_MAINTENANCE; } $OUTPUT = $this->get_renderer('core', null, $target); } if (!during_initial_install()) { $filtermanager = filter_manager::instance(); $filtermanager->setup_page_for_globally_available_filters($this); } $this->_wherethemewasinitialised = debug_backtrace(); }
/** * Given some text in HTML format, this function will pass it * through any filters that have been configured for this context. * * @deprecated use the text formatting in a standard way instead (http://docs.moodle.org/dev/Output_functions) * this was abused mostly for embedding of attachments * @todo final deprecation of this function in MDL-40607 * @param string $text The text to be passed through format filters * @param int $courseid The current course. * @return string the filtered string. */ function filter_text($text, $courseid = NULL) { global $CFG, $COURSE; debugging('filter_text() is deprecated, use format_text(), format_string() etc instead.', DEBUG_DEVELOPER); if (!$courseid) { $courseid = $COURSE->id; } if (!($context = context_course::instance($courseid, IGNORE_MISSING))) { return $text; } return filter_manager::instance()->filter_text($text, $context); }
public function test_filter_manager_instance() { set_config('perfdebug', 7); filter_manager::reset_caches(); $filterman = filter_manager::instance(); $this->assertInstanceOf('filter_manager', $filterman); $this->assertNotInstanceOf('performance_measuring_filter_manager', $filterman); set_config('perfdebug', 15); filter_manager::reset_caches(); $filterman = filter_manager::instance(); $this->assertInstanceOf('filter_manager', $filterman); $this->assertInstanceOf('performance_measuring_filter_manager', $filterman); }
/** * Renders a timeline post. * * @param object $course * @param object $post * @param object $completion * @param array $authors the already retrieved authors for posts and comments * @return string HTML for post */ protected function render_timeline_post($course, $post, $completion, $authors) { global $USER; $coursecontext = context_course::instance($post->courseid); list($postauthor, $l) = $this->get_timeline_author($post->fromuserid, $authors); $o = html_writer::tag('div', $l, array('class' => 'tl-leftcol')); // ... determine group for headline. if (empty($post->togroupid)) { $to = get_string('allparticipants'); } else { $groups = groups_get_all_groups($post->courseid); $to = isset($groups[$post->togroupid]) ? get_string('group') . ' ' . $groups[$post->togroupid]->name : get_string('nonexistinggroup', 'format_socialwall'); } $date = userdate($post->timecreated); $authorspan = html_writer::tag('span', fullname($postauthor), array('class' => 'tl-authorname')); $headline = get_string('postedonto', 'format_socialwall', array('author' => $authorspan, 'date' => $date, 'to' => $to)); // ... add delete icon, if delete is possible. $candeletepost = ($post->fromuserid == $USER->id and has_capability('format/socialwall:deleteownpost', $coursecontext)); $candeletepost = ($candeletepost or has_capability('format/socialwall:deleteanypost', $coursecontext)); if ($candeletepost) { $urlparams = array('courseid' => $post->courseid, 'action' => 'deletepost', 'pid' => $post->id, 'sesskey' => sesskey()); $url = new moodle_url('/course/format/socialwall/action.php', $urlparams); $deletelink = html_writer::link($url, $this->output->pix_icon('t/delete', get_string('delete'))); $headline .= html_writer::tag('span', $deletelink, array('class' => 'tl-action-icons')); } // ... add edit icon, if edting is allowed. $caneditpost = ($post->fromuserid == $USER->id and has_capability('format/socialwall:updateownpost', $coursecontext)); $caneditpost = ($caneditpost or has_capability('format/socialwall:updateanypost', $coursecontext)); if ($caneditpost) { $url = new moodle_url('/course/view.php', array('id' => $post->courseid, 'postid' => $post->id)); $editlink = html_writer::link($url, $this->output->pix_icon('t/editstring', get_string('edit'))); $headline .= html_writer::tag('span', $editlink, array('class' => 'tl-action-icons')); } // ... if (!empty($post->posttext)) { // ...user with cap format/socialwall:posthtml should be able to html. $headline .= html_writer::tag('div', format_text($post->posttext), array('class' => 'tl-posttext')); } if (!empty($post->attaches)) { $modinfo = get_fast_modinfo($post->courseid); $modulehtml = ''; foreach ($post->attaches as $attachment) { $cm = $modinfo->get_cm($attachment->coursemoduleid); $modulehtml .= $this->courserenderer->course_section_cm_list_item($course, $completion, $cm, 0); if (isset($post->grades[$attachment->coursemoduleid])) { $modulehtml .= $this->render_timeline_grades($authors, $post->grades[$attachment->coursemoduleid]); } } if (!empty($modulehtml)) { $headline .= html_writer::tag('ul', $modulehtml, array('class' => 'section tl-postattachment')); } } $p = ''; if (has_capability('format/socialwall:lockcomment', $coursecontext)) { $class = !empty($post->locked) ? 'locked' : 'unlocked'; $urlparams = array('courseid' => $post->courseid, 'postid' => $post->id, 'action' => 'lockpost', 'locked' => empty($post->locked), 'sesskey' => sesskey()); $url = new moodle_url('/course/format/socialwall/action.php', $urlparams); if (!empty($post->locked)) { $pixicon = $this->output->pix_icon('lockedpost', get_string('unlockpost', 'format_socialwall'), 'format_socialwall'); } else { $pixicon = $this->output->pix_icon('unlockedpost', get_string('lockpost', 'format_socialwall'), 'format_socialwall'); } $link = html_writer::link($url, $pixicon, array('id' => 'lockpost_' . $post->id, 'class' => $class)); $p .= html_writer::tag('div', $link, array('class' => 'tl-locked')); } if (has_capability('format/socialwall:makesticky', $coursecontext)) { $urlparams = array('courseid' => $post->courseid, 'postid' => $post->id, 'action' => 'makesticky', 'sticky' => empty($post->sticky), 'sesskey' => sesskey()); $url = new moodle_url('/course/format/socialwall/action.php', $urlparams); if (!empty($post->sticky)) { $pixicon = $this->output->pix_icon('stickypost', get_string('makeunsticky', 'format_socialwall'), 'format_socialwall'); } else { $pixicon = $this->output->pix_icon('unstickypost', get_string('makesticky', 'format_socialwall'), 'format_socialwall'); } $link = html_writer::link($url, $pixicon); $p .= html_writer::tag('div', $link, array('class' => 'tl-sticky')); } else { // ...cannot edit stickyness of post. if (!empty($post->sticky)) { $pixicon = $this->output->pix_icon('stickypost', get_string('sticky', 'format_socialwall'), 'format_socialwall'); $p .= html_writer::tag('div', $pixicon, array('class' => 'tl-sticky')); } } if ($post->timecreated != $post->timemodified) { $c = html_writer::tag('div', get_string('edited', 'format_socialwall'), array('class' => 'tl-edited')); $editedago = $this->render_timeline_comment_ago($post->timemodified); $c .= html_writer::tag('div', "[{$editedago}]", array('class' => 'tl-edited-ago')); $p .= html_writer::tag('div', $c, array('class' => 'tl-edited-wrapper')); } $p .= html_writer::tag('div', $headline); $countoutput = ''; if (!empty($course->enablelikes) and has_capability('format/socialwall:viewlikes', $coursecontext)) { $countlikessstr = get_string('countlikes', 'format_socialwall', $post->countlikes); $countoutput .= html_writer::tag('span', $countlikessstr, array('id' => 'tlcountlikes_' . $post->id)); } $countcommentsstr = get_string('countcomments', 'format_socialwall', $post->countcomments); $countoutput .= html_writer::tag('span', $countcommentsstr, array('id' => 'tlcountcomments_' . $post->id)); $actionarea = html_writer::tag('div', $countoutput, array('class' => 'tl-counts')); $stralldiscussions = get_string('showalldicussions', 'format_socialwall'); $showalldiscussions = $l = html_writer::link('#', $stralldiscussions, array('id' => 'tlshowalldiscussions_' . $post->id)); $actionlink = html_writer::tag('div', $showalldiscussions, array('style' => 'float:right')); if (!empty($course->enablelikes) and has_capability('format/socialwall:like', $coursecontext)) { $class = !empty($post->userlike) ? 'likenomore' : 'like'; $urlparams = array('courseid' => $post->courseid, 'postid' => $post->id, 'action' => 'likepost', 'userlike' => empty($post->userlike), 'sesskey' => sesskey()); $url = new moodle_url('/course/format/socialwall/action.php', $urlparams); $urlparams = array('class' => $class, 'id' => "userlike_{$post->id}"); $actionlink .= html_writer::link($url, get_string($class, 'format_socialwall'), $urlparams); } $actionarea .= $this->render_timeline_comments_form($actionlink, $coursecontext, $post); $p .= html_writer::tag('div', $actionarea, array('class' => 'tl-post-actionarea')); // ... print out all comments. $c = $this->render_timeline_comments($post, $authors, $coursecontext, $course); $p .= html_writer::tag('ul', $c, array('class' => 'tl-comments', 'id' => 'tlcomments_' . $post->id . '_0')); $morecommentscount = $post->countcomments - $course->tlnumcomments; if ($morecommentscount > 0) { $url = new moodle_url('/course/format/socialwall/action.php'); $strmore = get_string('showallcomments', 'format_socialwall', $morecommentscount); $l = html_writer::link('#', $strmore, array('id' => 'tlshowall_' . $post->id)); $p .= html_writer::tag('div', $l, array('class' => 'tl-showall')); } $o .= html_writer::tag('div', $p, array('class' => 'tl-text')); $text = html_writer::tag('li', $o, array('class' => 'tl-post')); return filter_manager::instance()->filter_text($text, $coursecontext); }
/** * get_performance_info() pairs up with init_performance_info() * loaded in setup.php. Returns an array with 'html' and 'txt' * values ready for use, and each of the individual stats provided * separately as well. * * @return array */ function get_performance_info() { global $CFG, $PERF, $DB, $PAGE; $info = array(); $info['html'] = ''; // Holds userfriendly HTML representation. $info['txt'] = me() . ' '; // Holds log-friendly representation. $info['realtime'] = microtime_diff($PERF->starttime, microtime()); $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> '; $info['txt'] .= 'time: '.$info['realtime'].'s '; if (function_exists('memory_get_usage')) { $info['memory_total'] = memory_get_usage(); $info['memory_growth'] = memory_get_usage() - $PERF->startmemory; $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> '; $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '. $info['memory_growth'].'B ('.display_size($info['memory_growth']).') '; } if (function_exists('memory_get_peak_usage')) { $info['memory_peak'] = memory_get_peak_usage(); $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> '; $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') '; } $inc = get_included_files(); $info['includecount'] = count($inc); $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> '; $info['txt'] .= 'includecount: '.$info['includecount'].' '; if (!empty($CFG->early_install_lang) or empty($PAGE)) { // We can not track more performance before installation or before PAGE init, sorry. return $info; } $filtermanager = filter_manager::instance(); if (method_exists($filtermanager, 'get_performance_summary')) { list($filterinfo, $nicenames) = $filtermanager->get_performance_summary(); $info = array_merge($filterinfo, $info); foreach ($filterinfo as $key => $value) { $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> "; $info['txt'] .= "$key: $value "; } } $stringmanager = get_string_manager(); if (method_exists($stringmanager, 'get_performance_summary')) { list($filterinfo, $nicenames) = $stringmanager->get_performance_summary(); $info = array_merge($filterinfo, $info); foreach ($filterinfo as $key => $value) { $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> "; $info['txt'] .= "$key: $value "; } } if (!empty($PERF->logwrites)) { $info['logwrites'] = $PERF->logwrites; $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> '; $info['txt'] .= 'logwrites: '.$info['logwrites'].' '; } $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites); $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> '; $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' '; $info['dbtime'] = round($DB->perf_get_queries_time(), 5); $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> '; $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's '; if (function_exists('posix_times')) { $ptimes = posix_times(); if (is_array($ptimes)) { foreach ($ptimes as $key => $val) { $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key]; } $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> "; $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] "; } } // Grab the load average for the last minute. // /proc will only work under some linux configurations // while uptime is there under MacOSX/Darwin and other unices. if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) { list($serverload) = explode(' ', $loadavg[0]); unset($loadavg); } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) { if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) { $serverload = $matches[1]; } else { trigger_error('Could not parse uptime output!'); } } if (!empty($serverload)) { $info['serverload'] = $serverload; $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> '; $info['txt'] .= "serverload: {$info['serverload']} "; } // Display size of session if session started. if ($si = \core\session\manager::get_performance_info()) { $info['sessionsize'] = $si['size']; $info['html'] .= $si['html']; $info['txt'] .= $si['txt']; } if ($stats = cache_helper::get_stats()) { $html = '<span class="cachesused">'; $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>'; $text = 'Caches used (hits/misses/sets): '; $hits = 0; $misses = 0; $sets = 0; foreach ($stats as $definition => $stores) { $html .= '<span class="cache-definition-stats">'; $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>'; $text .= "$definition {"; foreach ($stores as $store => $data) { $hits += $data['hits']; $misses += $data['misses']; $sets += $data['sets']; if ($data['hits'] == 0 and $data['misses'] > 0) { $cachestoreclass = 'nohits'; } else if ($data['hits'] < $data['misses']) { $cachestoreclass = 'lowhits'; } else { $cachestoreclass = 'hihits'; } $text .= "$store($data[hits]/$data[misses]/$data[sets]) "; $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>"; } $html .= '</span>'; $text .= '} '; } $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>"; $html .= '</span> '; $info['cachesused'] = "$hits / $misses / $sets"; $info['html'] .= $html; $info['txt'] .= $text.'. '; } else { $info['cachesused'] = '0 / 0 / 0'; $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>'; $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 '; } $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>'; return $info; }
/** * 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; }
/** * get_performance_info() pairs up with init_performance_info() * loaded in setup.php. Returns an array with 'html' and 'txt' * values ready for use, and each of the individual stats provided * separately as well. * * @global object * @global object * @global object * @return array */ function get_performance_info() { global $CFG, $PERF, $DB; $info = array(); $info['html'] = ''; // holds userfriendly HTML representation $info['txt'] = me() . ' '; // holds log-friendly representation $info['realtime'] = microtime_diff($PERF->starttime, microtime()); $info['html'] .= '<span class="timeused">' . $info['realtime'] . ' secs</span> '; $info['txt'] .= 'time: ' . $info['realtime'] . 's '; if (function_exists('memory_get_usage')) { $info['memory_total'] = memory_get_usage(); $info['memory_growth'] = memory_get_usage() - $PERF->startmemory; $info['html'] .= '<span class="memoryused">RAM: ' . display_size($info['memory_total']) . '</span> '; $info['txt'] .= 'memory_total: ' . $info['memory_total'] . 'B (' . display_size($info['memory_total']) . ') memory_growth: ' . $info['memory_growth'] . 'B (' . display_size($info['memory_growth']) . ') '; } if (function_exists('memory_get_peak_usage')) { $info['memory_peak'] = memory_get_peak_usage(); $info['html'] .= '<span class="memoryused">RAM peak: ' . display_size($info['memory_peak']) . '</span> '; $info['txt'] .= 'memory_peak: ' . $info['memory_peak'] . 'B (' . display_size($info['memory_peak']) . ') '; } $inc = get_included_files(); //error_log(print_r($inc,1)); $info['includecount'] = count($inc); $info['html'] .= '<span class="included">Included ' . $info['includecount'] . ' files</span> '; $info['txt'] .= 'includecount: ' . $info['includecount'] . ' '; $filtermanager = filter_manager::instance(); if (method_exists($filtermanager, 'get_performance_summary')) { list($filterinfo, $nicenames) = $filtermanager->get_performance_summary(); $info = array_merge($filterinfo, $info); foreach ($filterinfo as $key => $value) { $info['html'] .= "<span class='{$key}'>{$nicenames[$key]}: {$value} </span> "; $info['txt'] .= "{$key}: {$value} "; } } if (!empty($PERF->logwrites)) { $info['logwrites'] = $PERF->logwrites; $info['html'] .= '<span class="logwrites">Log DB writes ' . $info['logwrites'] . '</span> '; $info['txt'] .= 'logwrites: ' . $info['logwrites'] . ' '; } $info['dbqueries'] = $DB->perf_get_reads() . '/' . ($DB->perf_get_writes() - $PERF->logwrites); $info['html'] .= '<span class="dbqueries">DB reads/writes: ' . $info['dbqueries'] . '</span> '; $info['txt'] .= 'db reads/writes: ' . $info['dbqueries'] . ' '; if (!empty($PERF->profiling) && $PERF->profiling) { require_once $CFG->dirroot . '/lib/profilerlib.php'; $info['html'] .= '<span class="profilinginfo">' . Profiler::get_profiling(array('-R')) . '</span>'; } if (function_exists('posix_times')) { $ptimes = posix_times(); if (is_array($ptimes)) { foreach ($ptimes as $key => $val) { $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key]; } $info['html'] .= "<span class=\"posixtimes\">ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']}</span> "; $info['txt'] .= "ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']} "; } } // Grab the load average for the last minute // /proc will only work under some linux configurations // while uptime is there under MacOSX/Darwin and other unices if (is_readable('/proc/loadavg') && ($loadavg = @file('/proc/loadavg'))) { list($server_load) = explode(' ', $loadavg[0]); unset($loadavg); } else { if (function_exists('is_executable') && is_executable('/usr/bin/uptime') && ($loadavg = `/usr/bin/uptime`)) { if (preg_match('/load averages?: (\\d+[\\.,:]\\d+)/', $loadavg, $matches)) { $server_load = $matches[1]; } else { trigger_error('Could not parse uptime output!'); } } } if (!empty($server_load)) { $info['serverload'] = $server_load; $info['html'] .= '<span class="serverload">Load average: ' . $info['serverload'] . '</span> '; $info['txt'] .= "serverload: {$info['serverload']} "; } /* if (isset($rcache->hits) && isset($rcache->misses)) { $info['rcachehits'] = $rcache->hits; $info['rcachemisses'] = $rcache->misses; $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '. "{$rcache->hits}/{$rcache->misses}</span> "; $info['txt'] .= 'rcache: '. "{$rcache->hits}/{$rcache->misses} "; }*/ $info['html'] = '<div class="performanceinfo">' . $info['html'] . '</div>'; return $info; }
/** * 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; }
/** * filter_text * * @param string $text * @return string */ public static function filter_text($text) { global $COURSE, $PAGE; $filter = filter_manager::instance(); if (method_exists($filter, 'setup_page_for_filters')) { // Moodle >= 2.3 $filter->setup_page_for_filters($PAGE, $PAGE->context); } return $filter->filter_text($text, $PAGE->context); }