Ejemplo n.º 1
3
 /**
  * Reset contents of all database tables to initial values, reset caches, etc.
  *
  * Note: this is relatively slow (cca 2 seconds for pg and 7 for mysql) - please use with care!
  *
  * @static
  * @param bool $detectchanges
  *      true  - changes in global state and database are reported as errors
  *      false - no errors reported
  *      null  - only critical problems are reported as errors
  * @return void
  */
 public static function reset_all_data($detectchanges = false)
 {
     global $DB, $CFG, $USER, $SITE, $COURSE, $PAGE, $OUTPUT, $SESSION;
     // Stop any message redirection.
     phpunit_util::stop_message_redirection();
     // Stop any message redirection.
     phpunit_util::stop_phpmailer_redirection();
     // Stop any message redirection.
     phpunit_util::stop_event_redirection();
     // We used to call gc_collect_cycles here to ensure desctructors were called between tests.
     // This accounted for 25% of the total time running phpunit - so we removed it.
     // Show any unhandled debugging messages, the runbare() could already reset it.
     self::display_debugging_messages();
     self::reset_debugging();
     // reset global $DB in case somebody mocked it
     $DB = self::get_global_backup('DB');
     if ($DB->is_transaction_started()) {
         // we can not reset inside transaction
         $DB->force_transaction_rollback();
     }
     $resetdb = self::reset_database();
     $warnings = array();
     if ($detectchanges === true) {
         if ($resetdb) {
             $warnings[] = 'Warning: unexpected database modification, resetting DB state';
         }
         $oldcfg = self::get_global_backup('CFG');
         $oldsite = self::get_global_backup('SITE');
         foreach ($CFG as $k => $v) {
             if (!property_exists($oldcfg, $k)) {
                 $warnings[] = 'Warning: unexpected new $CFG->' . $k . ' value';
             } else {
                 if ($oldcfg->{$k} !== $CFG->{$k}) {
                     $warnings[] = 'Warning: unexpected change of $CFG->' . $k . ' value';
                 }
             }
             unset($oldcfg->{$k});
         }
         if ($oldcfg) {
             foreach ($oldcfg as $k => $v) {
                 $warnings[] = 'Warning: unexpected removal of $CFG->' . $k;
             }
         }
         if ($USER->id != 0) {
             $warnings[] = 'Warning: unexpected change of $USER';
         }
         if ($COURSE->id != $oldsite->id) {
             $warnings[] = 'Warning: unexpected change of $COURSE';
         }
     }
     if (ini_get('max_execution_time') != 0) {
         // This is special warning for all resets because we do not want any
         // libraries to mess with timeouts unintentionally.
         // Our PHPUnit integration is not supposed to change it either.
         if ($detectchanges !== false) {
             $warnings[] = 'Warning: max_execution_time was changed to ' . ini_get('max_execution_time');
         }
         set_time_limit(0);
     }
     // restore original globals
     $_SERVER = self::get_global_backup('_SERVER');
     $CFG = self::get_global_backup('CFG');
     $SITE = self::get_global_backup('SITE');
     $_GET = array();
     $_POST = array();
     $_FILES = array();
     $_REQUEST = array();
     $COURSE = $SITE;
     // reinitialise following globals
     $OUTPUT = new bootstrap_renderer();
     $PAGE = new moodle_page();
     $FULLME = null;
     $ME = null;
     $SCRIPT = null;
     // Empty sessison and set fresh new not-logged-in user.
     \core\session\manager::init_empty_session();
     // reset all static caches
     \core\event\manager::phpunit_reset();
     accesslib_clear_all_caches(true);
     get_string_manager()->reset_caches(true);
     reset_text_filters_cache(true);
     events_get_handlers('reset');
     core_text::reset_caches();
     get_message_processors(false, true);
     filter_manager::reset_caches();
     // Reset internal users.
     core_user::reset_internal_users();
     //TODO MDL-25290: add more resets here and probably refactor them to new core function
     // Reset course and module caches.
     if (class_exists('format_base')) {
         // If file containing class is not loaded, there is no cache there anyway.
         format_base::reset_course_cache(0);
     }
     get_fast_modinfo(0, 0, true);
     // Reset other singletons.
     if (class_exists('core_plugin_manager')) {
         core_plugin_manager::reset_caches(true);
     }
     if (class_exists('\\core\\update\\checker')) {
         \core\update\checker::reset_caches(true);
     }
     if (class_exists('\\core\\update\\deployer')) {
         \core\update\deployer::reset_caches(true);
     }
     // purge dataroot directory
     self::reset_dataroot();
     // restore original config once more in case resetting of caches changed CFG
     $CFG = self::get_global_backup('CFG');
     // inform data generator
     self::get_data_generator()->reset();
     // fix PHP settings
     error_reporting($CFG->debug);
     // verify db writes just in case something goes wrong in reset
     if (self::$lastdbwrites != $DB->perf_get_writes()) {
         error_log('Unexpected DB writes in phpunit_util::reset_all_data()');
         self::$lastdbwrites = $DB->perf_get_writes();
     }
     if ($warnings) {
         $warnings = implode("\n", $warnings);
         trigger_error($warnings, E_USER_WARNING);
     }
 }
Ejemplo n.º 2
0
 /**
  * Tests that the filter applies the required changes.
  *
  * @return void
  */
 public function test_filter()
 {
     $this->resetAfterTest(true);
     $this->setAdminUser();
     filter_manager::reset_caches();
     filter_set_global_state('data', TEXTFILTER_ON);
     $course1 = $this->getDataGenerator()->create_course();
     $coursecontext1 = context_course::instance($course1->id);
     $course2 = $this->getDataGenerator()->create_course();
     $coursecontext2 = context_course::instance($course2->id);
     $sitecontext = context_course::instance(SITEID);
     $site = get_site();
     $this->add_simple_database_instance($site, array('SiteEntry'));
     $this->add_simple_database_instance($course1, array('CourseEntry'));
     $html = '<p>I like CourseEntry and SiteEntry</p>';
     // Testing at course level (both site and course).
     $filtered = format_text($html, FORMAT_HTML, array('context' => $coursecontext1));
     $this->assertRegExp('/title=(\'|")CourseEntry(\'|")/', $filtered);
     $this->assertRegExp('/title=(\'|")SiteEntry(\'|")/', $filtered);
     // Testing at site level (only site).
     $filtered = format_text($html, FORMAT_HTML, array('context' => $sitecontext));
     $this->assertNotRegExp('/title=(\'|")CourseEntry(\'|")/', $filtered);
     $this->assertRegExp('/title=(\'|")SiteEntry(\'|")/', $filtered);
     // Changing to another course to test the caches invalidation (only site).
     $filtered = format_text($html, FORMAT_HTML, array('context' => $coursecontext2));
     $this->assertNotRegExp('/title=(\'|")CourseEntry(\'|")/', $filtered);
     $this->assertRegExp('/title=(\'|")SiteEntry(\'|")/', $filtered);
 }
Ejemplo n.º 3
0
 /**
  * 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);
 }
Ejemplo n.º 4
0
/**
 * 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);
}
Ejemplo n.º 5
0
/**
 * 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);
}
 public function test_filter_external_file()
 {
     global $CFG;
     $this->resetAfterTest(true);
     $this->setAdminUser();
     filter_manager::reset_caches();
     filter_set_global_state('viewerjs', TEXTFILTER_ON);
     $course1 = $this->getDataGenerator()->create_course();
     $coursecontext1 = context_course::instance($course1->id);
     $url = 'http://www.example.org/frog.ppt';
     $html = '<a href= "' . $url . '">Link</a>';
     $this->assertContains($url, format_text($html, FORMAT_HTML, array('context' => $coursecontext1)), 'did not transform external url');
     $url = 'http://www.example.org/frog.pdf';
     $html = '<a href= "' . $url . '">Link</a>';
     $this->assertContains($url, format_text($html, FORMAT_HTML, array('context' => $coursecontext1)), 'did not transform external url even though it had a supported extension');
 }
Ejemplo n.º 7
0
 /**
  * Test ampersands.
  */
 public function test_ampersands()
 {
     global $CFG;
     $this->resetAfterTest(true);
     // Enable glossary filter at top level.
     filter_set_global_state('glossary', TEXTFILTER_ON);
     $CFG->glossary_linkentries = 1;
     // Create a test course.
     $course = $this->getDataGenerator()->create_course();
     $context = context_course::instance($course->id);
     // Create a glossary.
     $glossary = $this->getDataGenerator()->create_module('glossary', array('course' => $course->id, 'mainglossary' => 1));
     // Create two entries with ampersands and one normal entry.
     /** @var mod_glossary_generator $generator */
     $generator = $this->getDataGenerator()->get_plugin_generator('mod_glossary');
     $normal = $generator->create_content($glossary, array('concept' => 'normal'));
     $amp1 = $generator->create_content($glossary, array('concept' => 'A&B'));
     $amp2 = $generator->create_content($glossary, array('concept' => 'C&amp;D'));
     filter_manager::reset_caches();
     \mod_glossary\local\concept_cache::reset_caches();
     // Format text with all three entries in HTML.
     $html = '<p>A&amp;B C&amp;D normal</p>';
     $filtered = format_text($html, FORMAT_HTML, array('context' => $context));
     // Find all the glossary links in the result.
     $matches = array();
     preg_match_all('~eid=([0-9]+).*?title="(.*?)"~', $filtered, $matches);
     // There should be 3 glossary links.
     $this->assertEquals(3, count($matches[1]));
     $this->assertEquals($amp1->id, $matches[1][0]);
     $this->assertEquals($amp2->id, $matches[1][1]);
     $this->assertEquals($normal->id, $matches[1][2]);
     // Check text and escaping of title attribute.
     $this->assertEquals($glossary->name . ': A&amp;B', $matches[2][0]);
     $this->assertEquals($glossary->name . ': C&amp;D', $matches[2][1]);
     $this->assertEquals($glossary->name . ': normal', $matches[2][2]);
 }
Ejemplo n.º 8
0
/**
 * 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);
}
Ejemplo n.º 9
0
/**
 * 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;
}
Ejemplo n.º 10
0
/**
 * 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;
}
Ejemplo n.º 11
0
 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);
 }
 /**
  * Test a categories ability to resort courses.
  */
 public function test_resort_courses()
 {
     $this->resetAfterTest(true);
     $generator = $this->getDataGenerator();
     $category = $generator->create_category();
     $course1 = $generator->create_course(array('category' => $category->id, 'idnumber' => '006-01', 'shortname' => 'Biome Study', 'fullname' => '<span lang="ar" class="multilang">' . 'دراسة منطقة إحيائية' . '</span><span lang="en" class="multilang">Biome Study</span>', 'timecreated' => '1000000001'));
     $course2 = $generator->create_course(array('category' => $category->id, 'idnumber' => '007-02', 'shortname' => 'Chemistry Revision', 'fullname' => 'Chemistry Revision', 'timecreated' => '1000000002'));
     $course3 = $generator->create_course(array('category' => $category->id, 'idnumber' => '007-03', 'shortname' => 'Swiss Rolls and Sunflowers', 'fullname' => 'Aarkvarks guide to Swiss Rolls and Sunflowers', 'timecreated' => '1000000003'));
     $course4 = $generator->create_course(array('category' => $category->id, 'idnumber' => '006-04', 'shortname' => 'Scratch', 'fullname' => '<a href="test.php">Basic Scratch</a>', 'timecreated' => '1000000004'));
     $c1 = (int) $course1->id;
     $c2 = (int) $course2->id;
     $c3 = (int) $course3->id;
     $c4 = (int) $course4->id;
     $coursecat = coursecat::get($category->id);
     $this->assertTrue($coursecat->resort_courses('idnumber'));
     $this->assertSame(array($c1, $c4, $c2, $c3), array_keys($coursecat->get_courses()));
     $this->assertTrue($coursecat->resort_courses('shortname'));
     $this->assertSame(array($c1, $c2, $c4, $c3), array_keys($coursecat->get_courses()));
     $this->assertTrue($coursecat->resort_courses('timecreated'));
     $this->assertSame(array($c1, $c2, $c3, $c4), array_keys($coursecat->get_courses()));
     try {
         // Enable the multilang filter and set it to apply to headings and content.
         filter_manager::reset_caches();
         filter_set_global_state('multilang', TEXTFILTER_ON);
         filter_set_applies_to_strings('multilang', true);
         $expected = array($c3, $c4, $c1, $c2);
     } catch (coding_exception $ex) {
         $expected = array($c3, $c4, $c2, $c1);
     }
     $this->assertTrue($coursecat->resort_courses('fullname'));
     $this->assertSame($expected, array_keys($coursecat->get_courses()));
 }
/**
 * 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;
}
Ejemplo n.º 14
0
/**
* 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;
}
Ejemplo n.º 15
0
 /**
  * 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();
 }
Ejemplo n.º 16
0
 /**
  * Reset contents of all database tables to initial values, reset caches, etc.
  */
 public static function reset_all_data()
 {
     // Reset database.
     self::reset_database();
     // Purge dataroot directory.
     self::reset_dataroot();
     // Reset all static caches.
     accesslib_clear_all_caches(true);
     // Reset the nasty strings list used during the last test.
     nasty_strings::reset_used_strings();
     filter_manager::reset_caches();
     // Reset course and module caches.
     if (class_exists('format_base')) {
         // If file containing class is not loaded, there is no cache there anyway.
         format_base::reset_course_cache(0);
     }
     get_fast_modinfo(0, 0, true);
     // Inform data generator.
     self::get_data_generator()->reset();
     // Initialise $CFG with default values. This is needed for behat cli process, so we don't have modified
     // $CFG values from the old run. @see set_config.
     initialise_cfg();
 }
Ejemplo n.º 17
0
 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);
 }
Ejemplo n.º 18
0
/**
 * 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);
}
Ejemplo n.º 19
0
/**
 * 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;
}
Ejemplo n.º 20
0
 public function apply_filter_chain($text, $filterchain)
 {
     return parent::apply_filter_chain($text, $filterchain);
 }
 /**
  * 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);
 }
Ejemplo n.º 22
0
 /**
  * Tests the get_mimetype_description function.
  */
 public function test_get_mimetype_description()
 {
     $this->resetAfterTest();
     // Test example type (.doc).
     $this->assertEquals(get_string('application/msword', 'mimetypes'), get_mimetype_description(array('filename' => 'test.doc')));
     // Test an unknown file type.
     $this->assertEquals(get_string('document/unknown', 'mimetypes'), get_mimetype_description(array('filename' => 'test.frog')));
     // Test a custom filetype with no lang string specified.
     core_filetypes::add_type('frog', 'application/x-frog', 'document');
     $this->assertEquals('application/x-frog', get_mimetype_description(array('filename' => 'test.frog')));
     // Test custom description.
     core_filetypes::update_type('frog', 'frog', 'application/x-frog', 'document', array(), '', 'Froggy file');
     $this->assertEquals('Froggy file', get_mimetype_description(array('filename' => 'test.frog')));
     // Test custom description using multilang filter.
     filter_manager::reset_caches();
     filter_set_global_state('multilang', TEXTFILTER_ON);
     filter_set_applies_to_strings('multilang', true);
     core_filetypes::update_type('frog', 'frog', 'application/x-frog', 'document', array(), '', '<span lang="en" class="multilang">Green amphibian</span>' . '<span lang="fr" class="multilang">Amphibian vert</span>');
     $this->assertEquals('Green amphibian', get_mimetype_description(array('filename' => 'test.frog')));
 }
Ejemplo n.º 23
0
/**
 * 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('&lt;', '&gt;'), 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;
}
Ejemplo n.º 24
0
 /**
  * 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 (&#0160;) in a JCloze WordList
     if (hotpot_textlib('entities_to_utf8', '&#0160;') == '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 (&nbsp;) in Moodle <= 2.0
     $twobyte = chr(194) . chr(160);
     $fourbyte = chr(195) . chr(130) . $twobyte;
     if (hotpot_textlib('entities_to_utf8', '&nbsp;') == $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);
 }
Ejemplo n.º 25
0
/**
 * 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;
}
Ejemplo n.º 26
0
 /**
  * Reset contents of all database tables to initial values, reset caches, etc.
  *
  * Note: this is relatively slow (cca 2 seconds for pg and 7 for mysql) - please use with care!
  *
  * @static
  * @param bool $logchanges log changes in global state and database in error log
  * @return void
  */
 public static function reset_all_data($logchanges = false)
 {
     global $DB, $CFG, $USER, $SITE, $COURSE, $PAGE, $OUTPUT, $SESSION;
     // Stop any message redirection.
     phpunit_util::stop_message_redirection();
     // Release memory and indirectly call destroy() methods to release resource handles, etc.
     gc_collect_cycles();
     // Show any unhandled debugging messages, the runbare() could already reset it.
     self::display_debugging_messages();
     self::reset_debugging();
     // reset global $DB in case somebody mocked it
     $DB = self::get_global_backup('DB');
     if ($DB->is_transaction_started()) {
         // we can not reset inside transaction
         $DB->force_transaction_rollback();
     }
     $resetdb = self::reset_database();
     $warnings = array();
     if ($logchanges) {
         if ($resetdb) {
             $warnings[] = 'Warning: unexpected database modification, resetting DB state';
         }
         $oldcfg = self::get_global_backup('CFG');
         $oldsite = self::get_global_backup('SITE');
         foreach ($CFG as $k => $v) {
             if (!property_exists($oldcfg, $k)) {
                 $warnings[] = 'Warning: unexpected new $CFG->' . $k . ' value';
             } else {
                 if ($oldcfg->{$k} !== $CFG->{$k}) {
                     $warnings[] = 'Warning: unexpected change of $CFG->' . $k . ' value';
                 }
             }
             unset($oldcfg->{$k});
         }
         if ($oldcfg) {
             foreach ($oldcfg as $k => $v) {
                 $warnings[] = 'Warning: unexpected removal of $CFG->' . $k;
             }
         }
         if ($USER->id != 0) {
             $warnings[] = 'Warning: unexpected change of $USER';
         }
         if ($COURSE->id != $oldsite->id) {
             $warnings[] = 'Warning: unexpected change of $COURSE';
         }
     }
     // restore original globals
     $_SERVER = self::get_global_backup('_SERVER');
     $CFG = self::get_global_backup('CFG');
     $SITE = self::get_global_backup('SITE');
     $COURSE = $SITE;
     // reinitialise following globals
     $OUTPUT = new bootstrap_renderer();
     $PAGE = new moodle_page();
     $FULLME = null;
     $ME = null;
     $SCRIPT = null;
     $SESSION = new stdClass();
     $_SESSION['SESSION'] =& $SESSION;
     // set fresh new not-logged-in user
     $user = new stdClass();
     $user->id = 0;
     $user->mnethostid = $CFG->mnet_localhost_id;
     session_set_user($user);
     // reset all static caches
     accesslib_clear_all_caches(true);
     get_string_manager()->reset_caches(true);
     reset_text_filters_cache(true);
     events_get_handlers('reset');
     textlib::reset_caches();
     if (class_exists('repository')) {
         repository::reset_caches();
     }
     filter_manager::reset_caches();
     //TODO MDL-25290: add more resets here and probably refactor them to new core function
     // Reset course and module caches.
     if (class_exists('format_base')) {
         // If file containing class is not loaded, there is no cache there anyway.
         format_base::reset_course_cache(0);
     }
     get_fast_modinfo(0, 0, true);
     // Reset other singletons.
     if (class_exists('plugin_manager')) {
         plugin_manager::reset_caches(true);
     }
     if (class_exists('available_update_checker')) {
         available_update_checker::reset_caches(true);
     }
     if (class_exists('available_update_deployer')) {
         available_update_deployer::reset_caches(true);
     }
     // purge dataroot directory
     self::reset_dataroot();
     // restore original config once more in case resetting of caches changed CFG
     $CFG = self::get_global_backup('CFG');
     // inform data generator
     self::get_data_generator()->reset();
     // fix PHP settings
     error_reporting($CFG->debug);
     // verify db writes just in case something goes wrong in reset
     if (self::$lastdbwrites != $DB->perf_get_writes()) {
         error_log('Unexpected DB writes in phpunit_util::reset_all_data()');
         self::$lastdbwrites = $DB->perf_get_writes();
     }
     if ($warnings) {
         $warnings = implode("\n", $warnings);
         trigger_error($warnings, E_USER_WARNING);
     }
 }
// 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');
Ejemplo n.º 28
0
 /**
  * Reset contents of all database tables to initial values, reset caches, etc.
  */
 public static function reset_all_data()
 {
     // Reset database.
     self::reset_database();
     // Purge dataroot directory.
     self::reset_dataroot();
     // Reset all static caches.
     accesslib_clear_all_caches(true);
     // Reset the nasty strings list used during the last test.
     nasty_strings::reset_used_strings();
     filter_manager::reset_caches();
     // Reset course and module caches.
     if (class_exists('format_base')) {
         // If file containing class is not loaded, there is no cache there anyway.
         format_base::reset_course_cache(0);
     }
     get_fast_modinfo(0, 0, true);
     // Inform data generator.
     self::get_data_generator()->reset();
 }
Ejemplo n.º 29
0
 /**
  * @param string $string
  * @param object $context
  * @return mixed
  */
 public function filter_string($string, $context)
 {
     $this->stringsfiltered++;
     return parent::filter_string($string, $context);
 }
Ejemplo n.º 30
0
/**
 * 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;
}