function footer() { global $jinzora_url, $this_pgm, $version, $root_dir, $show_page_load_time, $skin, $show_jinzora_footer, $jzSERVICES, $cms_mode; // First let's make sure they didn't turn the footer off if ($show_jinzora_footer) { $display = new jzDisplay(); $smarty = smartySetup(); $smarty->assign('jinzora_url', $jinzora_url); $smarty->assign('link_title', $this_pgm . " " . $version); $poweredby = $root_dir . '/style/' . $skin . '/powered-by-small.gif'; if (!file_exists($poweredby)) { $poweredby = $root_dir . '/style/images/powered-by-small.gif'; } $smarty->assign('logo', $poweredby); $smarty->assign('page_load_time', ""); if ($show_page_load_time == "true" and $_SESSION['jz_load_time'] != "") { // Ok, let's get the difference $diff = round(microtime_diff($_SESSION['jz_load_time'], microtime()), 3); if ($cms_mode == "false") { $page_load = '<span class="jz_artistDesc">'; } $page_load .= word("Page generated in") . ": " . $diff . " " . word("seconds"); if ($cms_mode == "false") { $page_load .= "</span>"; } $smarty->assign('page_load_time', $page_load); } // Now let's display $smarty->display(SMARTY_ROOT . 'templates/slick/block-footer.tpl'); } $jzSERVICES->cmsClose(); }
private function _draw_rec($parent, $top, $height, $level = 0) { if (!isset($this->sections[$parent['name']])) { $this->sections[$parent['name']] = array_pop($this->html_colors); } $color = $this->sections[$parent['name']]; $left = 10 * $level; echo '<div style="border: solid white 1px; background: ' . $color . '; position: absolute; top:' . $top . 'px; left:' . $left . 'px; height:' . $height . 'px; width: 16px;" onmouseover="info(\'' . $color . '\',\'' . $parent['name'] . '\',\'' . intval(100000 * $parent['time']) / 100 . '\',\'' . $parent['queries'] . '\', \'\')" onmouseout="noInfo()"></div>'; foreach ($parent['children'] as $child) { $child_top = $top + $height * microtime_diff($parent['microtime_start'], $child['microtime_start']) / $parent['time']; $child_height = $height * $child['time'] / $parent['time']; $this->_draw_rec($child, $child_top, $child_height, $level + 1); } }
/** * Execute cron tasks */ function cron_run() { global $DB, $CFG, $OUTPUT; if (CLI_MAINTENANCE) { echo "CLI maintenance mode active, cron execution suspended.\n"; exit(1); } if (moodle_needs_upgrading()) { echo "Moodle upgrade pending, cron execution suspended.\n"; exit(1); } require_once $CFG->libdir . '/adminlib.php'; require_once $CFG->libdir . '/gradelib.php'; if (!empty($CFG->showcronsql)) { $DB->set_debug(true); } if (!empty($CFG->showcrondebugging)) { set_debugging(DEBUG_DEVELOPER, true); } set_time_limit(0); $starttime = microtime(); // Increase memory limit raise_memory_limit(MEMORY_EXTRA); // Emulate normal session - we use admin accoutn by default cron_setup_user(); // Start output log $timenow = time(); mtrace("Server Time: " . date('r', $timenow) . "\n\n"); // Run cleanup core cron jobs, but not every time since they aren't too important. // These don't have a timer to reduce load, so we'll use a random number // to randomly choose the percentage of times we should run these jobs. $random100 = rand(0, 100); if ($random100 < 20) { // Approximately 20% of the time. mtrace("Running clean-up tasks..."); cron_trace_time_and_memory(); // Delete users who haven't confirmed within required period if (!empty($CFG->deleteunconfirmed)) { $cuttime = $timenow - $CFG->deleteunconfirmed * 3600; $rs = $DB->get_recordset_sql("SELECT *\n FROM {user}\n WHERE confirmed = 0 AND firstaccess > 0\n AND firstaccess < ?", array($cuttime)); foreach ($rs as $user) { delete_user($user); // we MUST delete user properly first $DB->delete_records('user', array('id' => $user->id)); // this is a bloody hack, but it might work mtrace(" Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})"); } $rs->close(); } // Delete users who haven't completed profile within required period if (!empty($CFG->deleteincompleteusers)) { $cuttime = $timenow - $CFG->deleteincompleteusers * 3600; $rs = $DB->get_recordset_sql("SELECT *\n FROM {user}\n WHERE confirmed = 1 AND lastaccess > 0\n AND lastaccess < ? AND deleted = 0\n AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime)); foreach ($rs as $user) { if (isguestuser($user) or is_siteadmin($user)) { continue; } delete_user($user); mtrace(" Deleted not fully setup user {$user->username} ({$user->id})"); } $rs->close(); } // Delete old logs to save space (this might need a timer to slow it down...) if (!empty($CFG->loglifetime)) { // value in days $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24; $DB->delete_records_select("log", "time < ?", array($loglifetime)); mtrace(" Deleted old log records"); } // Delete old backup_controllers and logs. $loglifetime = get_config('backup', 'loglifetime'); if (!empty($loglifetime)) { // Value in days. $loglifetime = $timenow - $loglifetime * 3600 * 24; // Delete child records from backup_logs. $DB->execute("DELETE FROM {backup_logs}\n WHERE EXISTS (\n SELECT 'x'\n FROM {backup_controllers} bc\n WHERE bc.backupid = {backup_logs}.backupid\n AND bc.timecreated < ?)", array($loglifetime)); // Delete records from backup_controllers. $DB->execute("DELETE FROM {backup_controllers}\n WHERE timecreated < ?", array($loglifetime)); mtrace(" Deleted old backup records"); } // Delete old cached texts if (!empty($CFG->cachetext)) { // Defined in config.php $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime)); mtrace(" Deleted old cache_text records"); } if (!empty($CFG->usetags)) { require_once $CFG->dirroot . '/tag/lib.php'; tag_cron(); mtrace(' Executed tag cron'); } // Context maintenance stuff context_helper::cleanup_instances(); mtrace(' Cleaned up context instances'); context_helper::build_all_paths(false); // If you suspect that the context paths are somehow corrupt // replace the line below with: context_helper::build_all_paths(true); mtrace(' Built context paths'); // Remove expired cache flags gc_cache_flags(); mtrace(' Cleaned cache flags'); // Cleanup messaging if (!empty($CFG->messagingdeletereadnotificationsdelay)) { $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay; $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime' => $notificationdeletetime)); mtrace(' Cleaned up read notifications'); } mtrace(' Deleting temporary files...'); cron_delete_from_temp(); // Cleanup user password reset records // Delete any reset request records which are expired by more than a day. // (We keep recently expired requests around so we can give a different error msg to users who // are trying to user a recently expired reset attempt). $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800; $earliestvalid = time() - $pwresettime - DAYSECS; $DB->delete_records_select('user_password_resets', "timerequested < ?", array($earliestvalid)); mtrace(' Cleaned up old password reset records'); mtrace("...finished clean-up tasks"); } // End of occasional clean-up tasks // Send login failures notification - brute force protection in moodle is weak, // we should at least send notices early in each cron execution if (notify_login_failures()) { mtrace(' Notified login failures'); } // Make sure all context instances are properly created - they may be required in auth, enrol, etc. context_helper::create_instances(); mtrace(' Created missing context instances'); // Session gc. mtrace("Running session gc tasks..."); \core\session\manager::gc(); mtrace("...finished stale session cleanup"); // Run the auth cron, if any before enrolments // because it might add users that will be needed in enrol plugins $auths = get_enabled_auth_plugins(); mtrace("Running auth crons if required..."); cron_trace_time_and_memory(); foreach ($auths as $auth) { $authplugin = get_auth_plugin($auth); if (method_exists($authplugin, 'cron')) { mtrace("Running cron for auth/{$auth}..."); $authplugin->cron(); if (!empty($authplugin->log)) { mtrace($authplugin->log); } } unset($authplugin); } // Generate new password emails for users - ppl expect these generated asap if ($DB->count_records('user_preferences', array('name' => 'create_password', 'value' => '1'))) { mtrace('Creating passwords for new users...'); $usernamefields = get_all_user_name_fields(true, 'u'); $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email,\n {$usernamefields}, u.username, u.lang,\n p.id as prefid\n FROM {user} u\n JOIN {user_preferences} p ON u.id=p.userid\n WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin' AND u.deleted = 0"); // note: we can not send emails to suspended accounts foreach ($newusers as $newuser) { // Use a low cost factor when generating bcrypt hash otherwise // hashing would be slow when emailing lots of users. Hashes // will be automatically updated to a higher cost factor the first // time the user logs in. if (setnew_password_and_mail($newuser, true)) { unset_user_preference('create_password', $newuser); set_user_preference('auth_forcepasswordchange', 1, $newuser); } else { trigger_error("Could not create and mail new user password!"); } } $newusers->close(); } // It is very important to run enrol early // because other plugins depend on correct enrolment info. mtrace("Running enrol crons if required..."); $enrols = enrol_get_plugins(true); foreach ($enrols as $ename => $enrol) { // do this for all plugins, disabled plugins might want to cleanup stuff such as roles if (!$enrol->is_cron_required()) { continue; } mtrace("Running cron for enrol_{$ename}..."); cron_trace_time_and_memory(); $enrol->cron(); $enrol->set_config('lastcron', time()); } // Run all cron jobs for each module mtrace("Starting activity modules"); get_mailer('buffer'); if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { foreach ($mods as $mod) { $libfile = "{$CFG->dirroot}/mod/{$mod->name}/lib.php"; if (file_exists($libfile)) { include_once $libfile; $cron_function = $mod->name . "_cron"; if (function_exists($cron_function)) { mtrace("Processing module function {$cron_function} ...", ''); cron_trace_time_and_memory(); $pre_dbqueries = null; $pre_dbqueries = $DB->perf_get_queries(); $pre_time = microtime(1); if ($cron_function()) { $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id)); } if (isset($pre_dbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pre_time) . " seconds"); } // Reset possible changes by modules to time_limit. MDL-11597 @set_time_limit(0); mtrace("done."); } } } } get_mailer('close'); mtrace("Finished activity modules"); mtrace("Starting blocks"); if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { // We will need the base class. require_once $CFG->dirroot . '/blocks/moodleblock.class.php'; foreach ($blocks as $block) { $blockfile = $CFG->dirroot . '/blocks/' . $block->name . '/block_' . $block->name . '.php'; if (file_exists($blockfile)) { require_once $blockfile; $classname = 'block_' . $block->name; $blockobj = new $classname(); if (method_exists($blockobj, 'cron')) { mtrace("Processing cron function for " . $block->name . '....', ''); cron_trace_time_and_memory(); if ($blockobj->cron()) { $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id)); } // Reset possible changes by blocks to time_limit. MDL-11597 @set_time_limit(0); mtrace('done.'); } } } } mtrace('Finished blocks'); mtrace('Starting admin reports'); cron_execute_plugin_type('report'); mtrace('Finished admin reports'); mtrace('Starting main gradebook job...'); cron_trace_time_and_memory(); grade_cron(); mtrace('done.'); mtrace('Starting processing the event queue...'); cron_trace_time_and_memory(); events_cron(); mtrace('done.'); if ($CFG->enablecompletion) { // Completion cron mtrace('Starting the completion cron...'); cron_trace_time_and_memory(); require_once $CFG->dirroot . '/completion/cron.php'; completion_cron(); mtrace('done'); } if ($CFG->enableportfolios) { // Portfolio cron mtrace('Starting the portfolio cron...'); cron_trace_time_and_memory(); require_once $CFG->libdir . '/portfoliolib.php'; portfolio_cron(); mtrace('done'); } //now do plagiarism checks require_once $CFG->libdir . '/plagiarismlib.php'; plagiarism_cron(); mtrace('Starting course reports'); cron_execute_plugin_type('coursereport'); mtrace('Finished course reports'); // run gradebook import/export/report cron mtrace('Starting gradebook plugins'); cron_execute_plugin_type('gradeimport'); cron_execute_plugin_type('gradeexport'); cron_execute_plugin_type('gradereport'); mtrace('Finished gradebook plugins'); // run calendar cron require_once "{$CFG->dirroot}/calendar/lib.php"; calendar_cron(); // Run external blog cron if needed if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) { require_once $CFG->dirroot . '/blog/lib.php'; mtrace("Fetching external blog entries...", ''); cron_trace_time_and_memory(); $sql = "timefetched < ? OR timefetched = 0"; $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime)); foreach ($externalblogs as $eb) { blog_sync_external_entries($eb); } mtrace('done.'); } // Run blog associations cleanup if (!empty($CFG->enableblogs) && $CFG->useblogassociations) { require_once $CFG->dirroot . '/blog/lib.php'; // delete entries whose contextids no longer exists mtrace("Deleting blog associations linked to non-existent contexts...", ''); cron_trace_time_and_memory(); $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})'); mtrace('done.'); } // Run question bank clean-up. mtrace("Starting the question bank cron...", ''); cron_trace_time_and_memory(); require_once $CFG->libdir . '/questionlib.php'; question_bank::cron(); mtrace('done.'); //Run registration updated cron mtrace(get_string('siteupdatesstart', 'hub')); cron_trace_time_and_memory(); require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php'; $registrationmanager = new registration_manager(); $registrationmanager->cron(); mtrace(get_string('siteupdatesend', 'hub')); // If enabled, fetch information about available updates and eventually notify site admins if (empty($CFG->disableupdatenotifications)) { $updateschecker = \core\update\checker::instance(); $updateschecker->cron(); } //cleanup old session linked tokens //deletes the session linked tokens that are over a day old. mtrace("Deleting session linked tokens more than one day old...", ''); cron_trace_time_and_memory(); $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED)); mtrace('done.'); // all other plugins cron_execute_plugin_type('message', 'message plugins'); cron_execute_plugin_type('filter', 'filters'); cron_execute_plugin_type('editor', 'editors'); cron_execute_plugin_type('format', 'course formats'); cron_execute_plugin_type('profilefield', 'profile fields'); cron_execute_plugin_type('webservice', 'webservices'); cron_execute_plugin_type('repository', 'repository plugins'); cron_execute_plugin_type('qbehaviour', 'question behaviours'); cron_execute_plugin_type('qformat', 'question import/export formats'); cron_execute_plugin_type('qtype', 'question types'); cron_execute_plugin_type('plagiarism', 'plagiarism plugins'); cron_execute_plugin_type('theme', 'themes'); cron_execute_plugin_type('tool', 'admin tools'); // and finally run any local cronjobs, if any if ($locals = core_component::get_plugin_list('local')) { mtrace('Processing customized cron scripts ...', ''); // new cron functions in lib.php first cron_execute_plugin_type('local'); // legacy cron files are executed directly foreach ($locals as $local => $localdir) { if (file_exists("{$localdir}/cron.php")) { include "{$localdir}/cron.php"; } } mtrace('done.'); } mtrace('Running cache cron routines'); cache_helper::cron(); mtrace('done.'); // Run automated backups if required - these may take a long time to execute require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php'; require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php'; backup_cron_automated_helper::run_automated_backup(); // Run stats as at the end because they are known to take very long time on large sites if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) { require_once $CFG->dirroot . '/lib/statslib.php'; // check we're not before our runtime $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60; if (time() > $timetocheck) { // process configured number of days as max (defaulting to 31) $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays); if (stats_cron_daily($maxdays)) { if (stats_cron_weekly()) { if (stats_cron_monthly()) { stats_clean_old(); } } } @set_time_limit(0); } else { mtrace('Next stats run after:' . userdate($timetocheck)); } } // Run badges review cron. mtrace("Starting badges cron..."); require_once $CFG->dirroot . '/badges/cron.php'; badge_cron(); mtrace('done.'); // cleanup file trash - not very important $fs = get_file_storage(); $fs->cron(); mtrace("Cron script completed correctly"); gc_collect_cycles(); mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.'); $difftime = microtime_diff($starttime, microtime()); mtrace("Execution took " . $difftime . " seconds"); }
/** * 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; }
/** *** 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. *** **/ function get_performance_info() { global $CFG, $PERF, $rcache; $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'] . ' '; if (!empty($PERF->dbqueries)) { $info['dbqueries'] = $PERF->dbqueries; $info['html'] .= '<span class="dbqueries">DB queries ' . $info['dbqueries'] . '</span> '; $info['txt'] .= 'dbqueries: ' . $info['dbqueries'] . ' '; } if (!empty($PERF->logwrites)) { $info['logwrites'] = $PERF->logwrites; $info['html'] .= '<span class="logwrites">Log writes ' . $info['logwrites'] . '</span> '; $info['txt'] .= 'logwrites: ' . $info['logwrites'] . ' '; } 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; }
/** * 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; }
function footer($node = false) { global $root_dir, $jinzora_skin, $img_check, $img_check_none, $jzUSER, $version, $jinzora_url, $show_page_load_time, $allow_lang_choice, $allow_style_choice, $allow_interface_change, $image_dir, $jzSERVICES, $jzUSER, $cms_mode, $allow_theme_change; if ($node === false) { $node = new jzMediaNode(); } $display = new jzDisplay(); ?> <table width="100%" cellspacing="0" cellpadding="0"><tr height="2" style="background-image: url('<?php echo $image_dir; ?> row-spacer.gif');"><td width="100%"></td></tr></table> <table width="100%" cellspacing="0" cellpadding="1"> <tr class="and_head1"> <td width="50%"> <?php if ($allow_interface_change == "true") { $display->interfaceDropdown(); } ?> </td> <td width="50%" align="right"> <?php // Now let's show the admin tools if ($allow_lang_choice == "true") { $display->languageDropdown(); } else { if ($jzUSER->getSetting('admin')) { $display->systemToolsDropdown($node); } } ?> </td> </tr> <tr> <td> <?php if ($allow_style_choice == "true") { $display->styleDropdown(); } ?> </td> <td align="right"> <?php if ($jzUSER->getSetting('admin') && $allow_lang_choice == "true") { $display->systemToolsDropdown($node); } else { echo ' '; } ?> </td> </table> <table width="100%" cellspacing="0" cellpadding="0"><tr height="2" style="background-image: url('<?php echo $image_dir; ?> row-spacer.gif');"><td width="100%"></td></tr></table> <table width="100%" cellspacing="0" cellpadding="3"> <tr class="and_head1"> <td width="100%" align="center"> <?php if ($cms_mode == "false") { $display->loginLink(); } if ($jzUSER->getSetting('edit_prefs') !== false) { if ($cms_mode == "false") { echo " | "; } //echo " - "; $display->popupLink("preferences"); } ?> <br><br> powered by <a href="<?php echo $jinzora_url; ?> ">Jinzora</a> version <?php echo $version; ?> <br><br> <?php if ($show_page_load_time == "true" and $_SESSION['jz_load_time'] != "") { // Ok, let's get the difference $diff = round(microtime_diff($_SESSION['jz_load_time'], microtime()), 3); echo '<br><span class="jz_artistDesc">' . word("generated in") . ": " . $diff . " " . word("seconds") . "</span> <br><br>"; } ?> </td> </tr> </table> <table width="100%" cellspacing="0" cellpadding="0"><tr height="2" style="background-image: url('<?php echo $image_dir; ?> row-spacer.gif');"><td width="100%"></td></tr></table> </td></tr></table> <?php $jzSERVICES->cmsClose(); }
function create_clickreport_table(&$hotpot, &$cm, &$course, &$users, &$attempts, &$questions, &$options, &$tables) { global $CFG; $is_html = $options['reportformat'] == 'htm'; // time and date format strings // date format strings $strftimetime = '%H:%M:%S'; $strftimedate = get_string('strftimedate'); // get the current time and max execution time $start_report_time = microtime(); $max_execution_time = ini_get('max_execution_time'); $correct = get_string('reportcorrectsymbol', 'hotpot'); $wrong = get_string('reportwrongsymbol', 'hotpot'); $nottried = get_string('reportnottriedsymbol', 'hotpot'); // shortcuts for font tags $blank = $is_html ? ' ' : ""; // store question count $questioncount = count($questions); // array to map columns onto question ids ($col => $id) $questionids = array_keys($questions); // store exercise type $exercisetype = $this->get_exercisetype($questions, $questionids, $blank); // initialize details ('events' must go last) $details = array('checks', 'status', 'answers', 'changes', 'hints', 'clues', 'events'); // initialize $table unset($table); $table->border = 1; $table->width = '100%'; // initialize legend, if necessary if (!empty($options['reportshowlegend'])) { $table->legend = array(); } // start $table headings $this->set_head($options, $table, 'exercise'); $this->set_head($options, $table, 'user'); $this->set_head($options, $table, 'attempt'); $this->set_head($options, $table, 'click'); // store clicktype column number $clicktype_col = count($table->head) - 1; // finish $table headings $this->set_head($options, $table, 'details', $exercisetype, $details, $questioncount); $this->set_head($options, $table, 'totals', $exercisetype); // set align and wrap $this->set_align_and_wrap($table); // is link to review allowed? $allow_review = $is_html && (has_capability('mod/hotpot:viewreport', get_context_instance(CONTEXT_COURSE, $course->id)) || $hotpot->review); // initialize array of data values $this->data = array(); // set exercise data values $this->set_data_exercise($cm, $course, $hotpot, $questions, $questionids, $questioncount, $blank); // add details of users' responses foreach ($users as $user) { $this->set_data_user($options, $course, $user); unset($clickreportid); foreach ($user->attempts as $attempt) { // initialize totals for $click = array('qnumber' => array(), 'correct' => array(), 'wrong' => array(), 'answers' => array(), 'hints' => array(), 'clues' => array(), 'changes' => array(), 'checks' => array(), 'events' => array(), 'score' => array(), 'weighting' => array()); $clicktypes = array(); // is the start of a new attempt? // (clicks in the same attempt have the same clickreportid) if (!isset($clickreportid) || $clickreportid != $attempt->clickreportid) { $clickcount = 1; $clickreportid = $attempt->clickreportid; // initialize totals for all clicks in this attempt $clicks = $click; // $click has just been initialized $this->set_data_attempt($attempt, $strftimedate, $strftimetime, $blank); } $cells = array(); $this->set_data($cells, 'exercise'); $this->set_data($cells, 'user'); $this->set_data($cells, 'attempt'); // get responses to questions in this attempt foreach ($attempt->responses as $response) { // set $q(uestion number) $q = array_search($response->question, $questionids); $click['qnumber'][$q] = true; // was this question answered correctly? if ($answer = hotpot_strings($response->correct)) { // mark the question as correctly answered if (empty($clicks['correct'][$q])) { $click['correct'][$q] = true; $clicks['correct'][$q] = true; } // unset 'wrong' flags, if necessary if (isset($click['wrong'][$q])) { unset($click['wrong'][$q]); } if (isset($clicks['wrong'][$q])) { unset($clicks['wrong'][$q]); } // otherwise, was the question answered wrongly? } else { if ($answer = hotpot_strings($response->wrong)) { // mark the question as wrongly answered $click['wrong'][$q] = true; $clicks['wrong'][$q] = true; } else { // not correct or wrong (curious?!) unset($answer); } } if (!empty($click['correct'][$q]) || !empty($click['wrong'][$q])) { $click['score'][$q] = $response->score; $clicks['score'][$q] = $response->score; $weighting = isset($response->weighting) ? $response->weighting : 100; $click['weighting'][$q] = $weighting; $clicks['weighting'][$q] = $weighting; } foreach ($details as $detail) { switch ($detail) { case 'answers': if (isset($answer) && is_string($answer) && !empty($answer)) { $click[$detail][$q] = $answer; } break; case 'hints': case 'clues': case 'checks': if (isset($response->{$detail}) && is_numeric($response->{$detail}) && $response->{$detail} > 0) { if (!isset($click[$detail][$q]) || $click[$detail][$q] < $response->{$detail}) { $click[$detail][$q] = $response->{$detail}; } } break; } } // end foreach $detail } // end foreach $response $click['types'] = array(); $this->data['details'] = array(); foreach ($details as $detail) { for ($q = 0; $q < $questioncount; $q++) { switch ($detail) { case 'status': if (isset($clicks['correct'][$q])) { $this->data['details'][] = $correct; } else { if (isset($clicks['wrong'][$q])) { $this->data['details'][] = $wrong; } else { if (isset($click['qnumber'][$q])) { $this->data['details'][] = $nottried; } else { // this question did not appear in this attempt $this->data['details'][] = $blank; } } } break; case 'answers': case 'hints': case 'clues': case 'checks': if (!isset($clicks[$detail][$q])) { if (!isset($click[$detail][$q])) { $this->data['details'][] = $blank; } else { $clicks[$detail][$q] = $click[$detail][$q]; if ($detail == 'answers') { $this->set_legend($table, $q, $click[$detail][$q], $questions[$questionids[$q]]); } $this->data['details'][] = $click[$detail][$q]; $this->update_event_count($click, $detail, $q); } } else { if (!isset($click[$detail][$q])) { $this->data['details'][] = $blank; } else { $difference = ''; if ($detail == 'answers') { if ($click[$detail][$q] != $clicks[$detail][$q]) { $pattern = '/^' . preg_quote($clicks[$detail][$q], '/') . ',/'; $difference = preg_replace($pattern, '', $click[$detail][$q], 1); } } else { // hints, clues, checks if ($click[$detail][$q] > $clicks[$detail][$q]) { $difference = $click[$detail][$q] - $clicks[$detail][$q]; } } if ($difference) { $clicks[$detail][$q] = $click[$detail][$q]; $click[$detail][$q] = $difference; if ($detail == 'answers') { $this->set_legend($table, $q, $difference, $questions[$questionids[$q]]); } $this->data['details'][] = $difference; $this->update_event_count($click, $detail, $q); } else { unset($click[$detail][$q]); $this->data['details'][] = $blank; } } } break; case 'changes': case 'events': if (empty($click[$detail][$q])) { $this->data['details'][] = $blank; } else { $this->data['details'][] = $click[$detail][$q]; } break; default: // do nothing break; } // end switch } // for $q } // foreach $detail // set data cell values for $this->set_data_click($allow_review ? '<a href="review.php?hp=' . $hotpot->id . '&attempt=' . $attempt->id . '">' . $clickcount . '</a>' : $clickcount, trim(userdate($attempt->timefinish, $strftimetime)), $exercisetype, $click); $this->set_data($cells, 'click'); $this->set_data($cells, 'details'); $this->set_data_totals($click, $clicks, $questioncount, $blank, $attempt); $this->set_data($cells, 'totals'); $table->data[] = $cells; $clickcount++; } // end foreach $attempt // insert 'tabledivider' between users $table->data[] = 'hr'; } // end foreach $user // remove final 'hr' from data rows array_pop($table->data); if ($is_html && $CFG->hotpot_showtimes) { $count = count($users); $duration = sprintf("%0.3f", microtime_diff($start_report_time, microtime())); print "{$count} users processed in {$duration} seconds (" . sprintf("%0.3f", $duration / $count) . ' secs/user)<hr size="1" noshade="noshade" />' . "\n"; } $tables[] =& $table; $this->create_legend_table($tables, $table); }
/** * Execute cron tasks */ function cron_run() { global $DB, $CFG, $OUTPUT; if (CLI_MAINTENANCE) { echo "CLI maintenance mode active, cron execution suspended.\n"; exit(1); } if (moodle_needs_upgrading()) { echo "Moodle upgrade pending, cron execution suspended.\n"; exit(1); } require_once $CFG->libdir . '/adminlib.php'; if (!empty($CFG->showcronsql)) { $DB->set_debug(true); } if (!empty($CFG->showcrondebugging)) { set_debugging(DEBUG_DEVELOPER, true); } core_php_time_limit::raise(); $starttime = microtime(); // Increase memory limit raise_memory_limit(MEMORY_EXTRA); // Emulate normal session - we use admin accoutn by default cron_setup_user(); // Start output log $timenow = time(); mtrace("Server Time: " . date('r', $timenow) . "\n\n"); // Run all scheduled tasks. while (!\core\task\manager::static_caches_cleared_since($timenow) && ($task = \core\task\manager::get_next_scheduled_task($timenow))) { mtrace("Execute scheduled task: " . $task->get_name()); cron_trace_time_and_memory(); $predbqueries = null; $predbqueries = $DB->perf_get_queries(); $pretime = microtime(1); try { get_mailer('buffer'); $task->execute(); if ($DB->is_transaction_started()) { throw new coding_exception("Task left transaction open"); } if (isset($predbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pretime) . " seconds"); } mtrace("Scheduled task complete: " . $task->get_name()); \core\task\manager::scheduled_task_complete($task); } catch (Exception $e) { if ($DB && $DB->is_transaction_started()) { error_log('Database transaction aborted automatically in ' . get_class($task)); $DB->force_transaction_rollback(); } if (isset($predbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pretime) . " seconds"); } mtrace("Scheduled task failed: " . $task->get_name() . "," . $e->getMessage()); if ($CFG->debugdeveloper) { if (!empty($e->debuginfo)) { mtrace("Debug info:"); mtrace($e->debuginfo); } mtrace("Backtrace:"); mtrace(format_backtrace($e->getTrace(), true)); } \core\task\manager::scheduled_task_failed($task); } get_mailer('close'); unset($task); } // Run all adhoc tasks. while (!\core\task\manager::static_caches_cleared_since($timenow) && ($task = \core\task\manager::get_next_adhoc_task($timenow))) { mtrace("Execute adhoc task: " . get_class($task)); cron_trace_time_and_memory(); $predbqueries = null; $predbqueries = $DB->perf_get_queries(); $pretime = microtime(1); try { get_mailer('buffer'); $task->execute(); if ($DB->is_transaction_started()) { throw new coding_exception("Task left transaction open"); } if (isset($predbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pretime) . " seconds"); } mtrace("Adhoc task complete: " . get_class($task)); \core\task\manager::adhoc_task_complete($task); } catch (Exception $e) { if ($DB && $DB->is_transaction_started()) { error_log('Database transaction aborted automatically in ' . get_class($task)); $DB->force_transaction_rollback(); } if (isset($predbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pretime) . " seconds"); } mtrace("Adhoc task failed: " . get_class($task) . "," . $e->getMessage()); if ($CFG->debugdeveloper) { if (!empty($e->debuginfo)) { mtrace("Debug info:"); mtrace($e->debuginfo); } mtrace("Backtrace:"); mtrace(format_backtrace($e->getTrace(), true)); } \core\task\manager::adhoc_task_failed($task); } get_mailer('close'); unset($task); } mtrace("Cron script completed correctly"); gc_collect_cycles(); mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.'); $difftime = microtime_diff($starttime, microtime()); mtrace("Execution took " . $difftime . " seconds"); }
/** * This is it - the start of rendering of a website page. * Take in all inputs, sends them to the correct functions to process, gathers up all the outputs, sticks them together and echoes them. */ function do_site() { // More SEO redirection (monikers) // Does this URL arrangement support monikers? $url_id = get_param('id', NULL, true); if ($url_id !== NULL && url_monikers_enabled()) { $type = get_param('type', 'misc'); $looking_for = '_SEARCH:' . get_page_name() . ':' . $type . ':_WILD'; $hooks = find_all_hooks('systems', 'content_meta_aware'); $ob_info = NULL; foreach (array_keys($hooks) as $hook) { require_code('hooks/systems/content_meta_aware/' . filter_naughty($hook)); $ob = object_factory('Hook_content_meta_aware_' . $hook, true); if ($ob === NULL) { continue; } $ob_info = $ob->info(); $ob_info['view_pagelink_pattern'] = preg_replace('#:[^:]*$#', ':_WILD', $ob_info['view_pagelink_pattern']); if ($ob_info['view_pagelink_pattern'] == $looking_for && $ob_info['support_url_monikers']) { if (is_numeric($url_id)) { $correct_moniker = find_id_moniker(array('page' => get_page_name(), 'type' => get_param('type', 'misc'), 'id' => $url_id)); if ($correct_moniker !== NULL && $correct_moniker != $url_id && count($_POST) == 0) { header('HTTP/1.0 301 Moved Permanently'); $_new_url = build_url(array('page' => '_SELF', 'id' => $correct_moniker), '_SELF', NULL, true); $new_url = $_new_url->evaluate(); header('Location: ' . $new_url); exit; } } else { // See if it is deprecated if (strpos(get_db_type(), 'mysql') !== false) { $monikers = $GLOBALS['SITE_DB']->query_select('url_id_monikers USE INDEX (uim_moniker)', array('m_resource_id', 'm_deprecated'), array('m_resource_page' => get_page_name(), 'm_resource_type' => get_param('type', 'misc'), 'm_moniker' => $url_id)); } else { $monikers = $GLOBALS['SITE_DB']->query_select('url_id_monikers', array('m_resource_id', 'm_deprecated'), array('m_resource_page' => get_page_name(), 'm_resource_type' => get_param('type', 'misc'), 'm_moniker' => $url_id)); } if (!array_key_exists(0, $monikers)) { warn_exit(do_lang_tempcode('MISSING_RESOURCE')); } $deprecated = $monikers[0]['m_deprecated'] == 1; if ($deprecated && count($_POST) == 0) { $correct_moniker = find_id_moniker(array('page' => get_page_name(), 'type' => get_param('type', 'misc'), 'id' => $monikers[0]['m_resource_id'])); header('HTTP/1.0 301 Moved Permanently'); $_new_url = build_url(array('page' => '_SELF', 'id' => $correct_moniker), '_SELF', NULL, true); $new_url = $_new_url->evaluate(); header('Location: ' . $new_url); exit; } else { $_GET['id'] = $monikers[0]['m_resource_id']; // We need to know the ID number rather than the moniker } } break; } } } // Any messages to output? if (get_param_integer('redirected', 0) == 1) { $messages = $GLOBALS['SITE_DB']->query_select('messages_to_render', array('r_message', 'r_type'), array('r_session_id' => get_session_id()), 'ORDER BY r_time DESC'); foreach ($messages as $message) { if ($GLOBALS['XSS_DETECT']) { ocp_mark_as_escaped($message['r_message']); } attach_message(protect_from_escaping($message['r_message']), $message['r_type']); } if (count($messages) != 0) { $GLOBALS['SITE_DB']->query('DELETE FROM ' . $GLOBALS['SITE_DB']->get_table_prefix() . 'messages_to_render WHERE r_session_id=' . strval((int) get_session_id()) . ' OR r_time<' . strval(time() - 60 * 60)); } } if (in_safe_mode()) { $disable_safe_mode_url = get_self_url(true, true, array('keep_safe_mode' => NULL)); attach_message(do_lang_tempcode('CURRENTLY_HAS_KEEP_SAFE_MODE', escape_html($disable_safe_mode_url)), 'notice'); } if (get_param_integer('keep_fatalistic', 0) == 1) { $disable_fatalistic_url = get_self_url(true, true, array('keep_fatalistic' => NULL)); attach_message(do_lang_tempcode('CURRENTLY_HAS_KEEP_FATALISTIC', escape_html($disable_fatalistic_url)), 'notice'); } $special_page_type = get_param('special_page_type', 'view'); global $ZONE; $keep_markers = get_param_integer('keep_markers', 0); $show_edit_links = get_param_integer('show_edit_links', 0); global $KEEP_MARKERS, $SHOW_EDIT_LINKS; $KEEP_MARKERS = $keep_markers == 1 || $special_page_type == 'show_markers'; if ($KEEP_MARKERS && !headers_sent()) { header('Content-type: text/html; charset=' . get_charset()); } $SHOW_EDIT_LINKS = $show_edit_links == 1 || $special_page_type == 'show_edit_links'; $out_evaluated = NULL; if ($special_page_type != 'view' && $special_page_type != 'show_markers') { require_code('view_modes'); initialise_special_page_types($special_page_type); } // Set up Xdebug profiling if ($special_page_type == 'profile') { if (function_exists('xdebug_start_profiling')) { xdebug_start_profiling(); } // xdebug 1 style if (ini_get('xdebug.profiler_enable') != '1') { attach_message(escape_html('Profiling must be enabled in php.ini'), 'warn'); } // xdebug 2 style if (!is_writable_wrap(ini_get('xdebug.profiler_output_dir'))) { attach_message(escape_html('xdebug.profiler_output_dir needs setting to a writable directory'), 'warn'); } } // Allow the site to be closed $site_closed = get_option('site_closed'); if ($site_closed == '1' && !has_specific_permission(get_member(), 'access_closed_site') && !$GLOBALS['IS_ACTUALLY_ADMIN']) { require_code('site2'); closed_site(); } // Work out which page we're viewing global $PAGE; $PAGE = get_page_name(); $doing_special_page_type = $special_page_type != 'view' && $special_page_type != 'show_markers' && $special_page_type != 'show_edit_links' && $special_page_type != 'memory' && (has_specific_permission(get_member(), 'view_profiling_modes') || $GLOBALS['IS_ACTUALLY_ADMIN']); // Load up our frames into strings. Note that the header and the footer are fixed already. $middle = request_page($PAGE, true); global $CYCLES; $CYCLES = array(); // Here we reset some Tempcode environmental stuff, because template compilation or preprocessing may have dirtied things if ($middle === NULL || $middle->is_definitely_empty()) { $GLOBALS['HTTP_STATUS_CODE'] = '404'; if (!headers_sent()) { if (!browser_matches('ie') && strpos(ocp_srv('SERVER_SOFTWARE'), 'IIS') === false) { header('HTTP/1.0 404 Not Found'); } } $title = get_page_title('ERROR_OCCURRED'); $text = do_lang_tempcode('NO_PAGE_OUTPUT'); $middle = warn_screen($title, $text, false); } // Extra stuff we can tag on (like messages) $additional = new ocp_tempcode(); $site_closed = get_option('site_closed'); // May have been JUST changed in page load - think Setup Wizard if ($site_closed == '1' && $PAGE != 'login' && $PAGE != 'join' && get_param_integer('wide_high', 0) == 0) { $additional->attach(do_template('ADDITIONAL', array('_GUID' => '03a41a91606b3ad05330e7d6f3e741c1', 'TYPE' => 'notice', 'MESSAGE' => do_lang_tempcode(has_specific_permission(get_member(), 'access_closed_site') ? 'SITE_SPECIAL_ACCESS' : 'SITE_SPECIAL_ACCESS_SU')))); } if ($GLOBALS['IS_ACTUALLY_ADMIN']) { $unsu_link = get_self_url(true, true, array('keep_su' => NULL)); $su_username = $GLOBALS['FORUM_DRIVER']->get_username(get_member()); $additional->attach(do_template('ADDITIONAL', array('_GUID' => '13a41a91606b3ad05330e7d6f3e741c1', 'TYPE' => 'notice', 'MESSAGE' => do_lang_tempcode('USING_SU', escape_html($unsu_link), escape_html($su_username))))); } $out = new ocp_tempcode(); // This is important - it makes sure the tempcode tree appears nicely $middle->handle_symbol_preprocessing(); // Due to the '->evaluate()' below, plus so that some symbol preprocessing can be passed into header $out->attach(do_header()); if (function_exists('memory_get_usage') && get_param('special_page_type', '') == 'memory') { if (function_exists('memory_get_peak_usage')) { $memory_usage = memory_get_peak_usage(); } else { $memory_usage = memory_get_usage(); } $additional->attach(do_template('ADDITIONAL', array('_GUID' => 'd605c0d111742a8cd2d4ef270a1e5fe1', 'TYPE' => 'inform', 'MESSAGE' => do_lang_tempcode('MEMORY_USAGE', float_format(round(floatval($memory_usage) / 1024.0 / 1024.0, 2)))))); } // Whack it into our global template global $ATTACHED_MESSAGES; $global_template = 'GLOBAL'; if (get_option('show_docs') == '0') { $GLOBALS['HELPER_PANEL_TUTORIAL'] = ''; } $helper_panel_pic = $GLOBALS['HELPER_PANEL_PIC']; if ($helper_panel_pic != '') { if (find_theme_image($helper_panel_pic, true) == '') { $helper_panel_pic = ''; } } $global = do_template($global_template, array('HELPER_PANEL_TUTORIAL' => $GLOBALS['HELPER_PANEL_TUTORIAL'], 'HELPER_PANEL_HTML' => $GLOBALS['HELPER_PANEL_HTML'], 'HELPER_PANEL_TEXT' => $GLOBALS['HELPER_PANEL_TEXT'], 'HELPER_PANEL_PIC' => $helper_panel_pic, 'MIDDLE' => $doing_special_page_type ? $middle : $middle->evaluate(), 'MESSAGE_TOP' => $ATTACHED_MESSAGES, 'MESSAGE' => $additional, 'BREADCRUMBS' => breadcrumbs())); unset($middle); $out->attach($global); $out->attach(do_footer()); $out->handle_symbol_preprocessing(); if (get_value('xhtml_strict') === '1') { $out = make_xhtml_strict($out); } // Validation $novalidate = get_param_integer('keep_novalidate', get_param_integer('novalidate', 0)); $show_edit_links = get_param_integer('show_edit_links', 0); if ((in_array(ocp_srv('HTTP_HOST'), array('localhost', 'test.ocportal.com')) || $GLOBALS['FORUM_DRIVER']->is_staff(get_member())) && ($special_page_type == 'code' || $novalidate == 0 && get_option('validation') == '1') && $GLOBALS['REFRESH_URL'][0] == '' && $show_edit_links == 0) { require_code('view_modes'); $out_evaluated = $out->evaluate(NULL, false); do_xhtml_validation($out_evaluated, $special_page_type == 'code' && get_param_integer('preview_mode', NULL) === NULL, get_param_integer('preview_mode', 0)); } // Cacheing for spiders if (running_script('index') && count($_POST) == 0 && isset($GLOBALS['SITE_INFO']['fast_spider_cache']) && $GLOBALS['SITE_INFO']['fast_spider_cache'] == '1' && is_guest()) { $bot_type = get_bot_type(); if (($bot_type !== NULL || isset($GLOBALS['SITE_INFO']['any_guest_cached_too']) && $GLOBALS['SITE_INFO']['any_guest_cached_too'] == '1') && can_fast_spider_cache()) { $fast_cache_path = get_custom_file_base() . '/persistant_cache/' . md5(serialize(get_self_url_easy())); if ($bot_type === NULL) { $fast_cache_path .= '__non-bot'; } if (!array_key_exists('js_on', $_COOKIE)) { $fast_cache_path .= '__no-js'; } if (is_mobile()) { $fast_cache_path .= '_mobile'; } $fast_cache_path .= '.gcd'; if (!is_dir(get_custom_file_base() . '/persistant_cache/')) { if (@mkdir(get_custom_file_base() . '/persistant_cache/', 0777)) { fix_permissions(get_custom_file_base() . '/persistant_cache/', 0777); sync_file(get_custom_file_base() . '/persistant_cache/'); } else { intelligent_write_error($fast_cache_path); } } $out_evaluated = $out->evaluate(NULL, false); $myfile = @fopen($fast_cache_path, 'wb') or intelligent_write_error($fast_cache_path); if (function_exists('gzencode')) { fwrite($myfile, gzencode($out_evaluated, 9)); } else { fwrite($myfile, $out_evaluated); } fclose($myfile); fix_permissions($fast_cache_path); sync_file($fast_cache_path); } } if ($doing_special_page_type) { special_page_types($special_page_type, $out, $out_evaluated); } // We calculated the time before outputting so that latency and bandwidth do not adversely affect the result global $PAGE_START_TIME, $PAGE_STRING; $page_generation_time = microtime_diff($PAGE_START_TIME, microtime(false)); if (!$GLOBALS['QUICK_REDIRECT']) { if ($out_evaluated !== NULL) { echo $out_evaluated; } else { $GLOBALS['FINISHING_OUTPUT'] = true; $out->evaluate_echo(); } } // Finally, stats if ($PAGE_STRING !== NULL) { log_stats($PAGE_STRING, intval($page_generation_time)); } // When someone hits the Admin Zone front page. if ($ZONE['zone_name'] == 'adminzone' && get_page_name() == 'start') { // Security feature admins can turn on require_code('notifications'); $current_username = $GLOBALS['FORUM_DRIVER']->get_username(get_member()); $subject = do_lang('AFA_NOTIFICATION_MAIL_SUBJECT', $current_username, get_site_name(), get_ip_address()); $mail = do_lang('AFA_NOTIFICATION_MAIL', comcode_escape(get_site_name()), comcode_escape($current_username), comcode_escape(get_ip_address())); dispatch_notification('adminzone_frontpage_accessed', NULL, $subject, $mail); // Track very basic details of what sites use ocPortal. You can remove if you like. if (preg_match('#^localhost[\\.\\:$]?#', ocp_srv('HTTP_HOST')) == 0) { global $EXPIRE, $KEY; $timeout_before = @ini_get('default_socket_timeout'); @ini_set('default_socket_timeout', '3'); http_download_file('http://ocportal.com/user.php?url=' . urlencode(get_base_url()) . '&name=' . urlencode(get_site_name()) . '®istered=2&key=' . ($KEY === NULL ? '' : strval($KEY)) . '&expire=' . ($EXPIRE === NULL ? '' : strval($EXPIRE)) . '&version=' . urlencode(ocp_version_full()), NULL, false); @ini_set('default_socket_timeout', $timeout_before); } } // Little disk space check $last_space_check = get_value('last_space_check'); if ($last_space_check === NULL || intval($last_space_check) < time() - 60 * 60 * 3) { set_value('last_space_check', strval(time())); $low_space_check = intval(get_option('low_space_check')) * 1024 * 1024; $disk_space = @disk_free_space(get_file_base()); if (is_integer($disk_space) && $disk_space < $low_space_check) { require_code('notifications'); $subject = do_lang('LOW_DISK_SPACE_SUBJECT', NULL, NULL, NULL, get_site_default_lang()); $message = do_lang('LOW_DISK_SPACE_MAIL', strval(intval(round($disk_space / 1024 / 1024))), NULL, NULL, get_site_default_lang()); dispatch_notification('low_disk_space', NULL, $subject, $message, NULL, A_FROM_SYSTEM_PRIVILEGED); } } //exit(); }
/** * cron - goes through all the feeds. If the feed has a skipuntil value * that is less than the current time cron will attempt to retrieve it * with the cache duration set to 0 in order to force the retrieval of * the item and refresh the cache. * * If a feed fails then the skipuntil time of that feed is set to be * later than the next expected cron time. The amount of time will * increase each time the fetch fails until the maximum is reached. * * If a feed that has been failing is successfully retrieved it will * go back to being handled as though it had never failed. * * CRON should therefor process requests for permanently broken RSS * feeds infrequently, and temporarily unavailable feeds will be tried * less often until they become available again. * * @return boolean Always returns true */ function cron() { global $CFG, $DB; require_once $CFG->libdir . '/simplepie/moodle_simplepie.php'; // Get the legacy cron time, strangely the cron property of block_base // does not seem to get set. This means we must retrive it here. $this->cron = $DB->get_field('block', 'cron', array('name' => 'rss_client')); // We are going to measure execution times $starttime = microtime(); $starttimesec = time(); // Fetch all site feeds. $rs = $DB->get_recordset('block_rss_client'); $counter = 0; mtrace(''); foreach ($rs as $rec) { mtrace(' ' . $rec->url . ' ', ''); // Skip feed if it failed recently. if ($starttimesec < $rec->skipuntil) { mtrace('skipping until ' . userdate($rec->skipuntil)); continue; } // Fetch the rss feed, using standard simplepie caching // so feeds will be renewed only if cache has expired core_php_time_limit::raise(60); $feed = new moodle_simplepie(); // set timeout for longer than normal to be agressive at // fetching feeds if possible.. $feed->set_timeout(40); $feed->set_cache_duration(0); $feed->set_feed_url($rec->url); $feed->init(); if ($feed->error()) { // Skip this feed (for an ever-increasing time if it keeps failing). $rec->skiptime = $this->calculate_skiptime($rec->skiptime); $rec->skipuntil = time() + $rec->skiptime; $DB->update_record('block_rss_client', $rec); mtrace("Error: could not load/find the RSS feed - skipping for {$rec->skiptime} seconds."); } else { mtrace('ok'); // It worked this time, so reset the skiptime. if ($rec->skiptime > 0) { $rec->skiptime = 0; $rec->skipuntil = 0; $DB->update_record('block_rss_client', $rec); } // Only increase the counter when a feed is sucesfully refreshed. $counter++; } } $rs->close(); // Show times mtrace($counter . ' feeds refreshed (took ' . microtime_diff($starttime, microtime()) . ' seconds)'); return true; }
<?php if (!defined(JZ_SECURE_ACCESS)) { die('Security breach detected.'); } $smarty->assign('jinzora_url', $jinzora_url); $smarty->assign('version', $version); $smarty->assign('image_dir', $image_dir); $smarty->assign('page_load', ""); if ($show_page_load_time == "true" and $_SESSION['jz_load_time'] != "") { // Ok, let's get the difference $diff = round(microtime_diff($_SESSION['jz_load_time'], microtime()), 3); $smarty->assign('page_load', $diff . " " . word("seconds") . " "); } if ($jzUSER->getID() == $jzUSER->lookupUID('NOBODY')) { $smarty->assign("logged_in", false); } else { $smarty->assign("logged_in", true); } $smarty->assign('username', $jzUSER->getName()); $smarty->assign('word_logged_in', word("Logged in as")); jzTemplate($smarty, "footer"); $jzSERVICES->cmsClose();
/** * 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; }
function get_statistic($t = 0, $m = 0, $q = 0, $l = 0) { global $AVE_DB; $s = ''; if ($t) { $s .= "\n<br>Время генерации: " . number_format(microtime_diff(START_MICROTIME, microtime()), 3, ',', ' ') . ' сек.'; } if ($m && function_exists('memory_get_peak_usage')) { $s .= "\n<br>Пиковое значение " . number_format(memory_get_peak_usage() / 1024, 0, ',', ' ') . 'Kb'; } // if ($q) $s .= "\n<br>Количество запросов: " . $AVE_DB->DBStatisticGet('count') . ' шт. за ' . number_format($AVE_DB->DBStatisticGet('time')*1000, 3, ',', '.') . ' мксек.'; // if ($l) $s .= "\n<br><div style=\"text-align:left;padding-left:30px\"><small><ol>" . $AVE_DB->DBStatisticGet('list') . '</ol></small></div>'; if ($q && !defined('SQL_PROFILING_DISABLE')) { $s .= "\n<br>Количество запросов: " . $AVE_DB->DBProfilesGet('count') . ' шт. за ' . $AVE_DB->DBProfilesGet('time') . ' сек.'; } if ($l && !defined('SQL_PROFILING_DISABLE')) { $s .= $AVE_DB->DBProfilesGet('list'); } return $s; }
/** * Test times for get_parent using recursive get_parent alfresco calls * @uses $CFG, $DB */ public function test_get_parent_path_tree() { global $CFG, $DB; $this->resetAfterTest(true); $this->setup_test_data_xml(); $options = array( 'ajax' => false, 'name' => 'elis files phpunit test', 'type' => 'elisfiles' ); $repo = new repository_elisfiles('elisfiles', context_system::instance(), $options); // Make sure we connected to the repository successfully. if (empty($repo->elis_files)) { $this->markTestSkipped('Repository not configured or enabled'); } // set up the storage for the full path of the path's UUIDs to validate against $expectedpath = array(); // create folder, get uuid, get path via get_parent_path and elis_files_folder structure // for first folder, create under moodle, then create under the previous folder... $parentfolderuuid = $repo->elis_files->get_root()->uuid; $times = array(); for ($i = 1; $i <= 20; $i++) { $currentfolder = FOLDER_NAME_PREFIX.$i; $currentfolderuuid = $repo->elis_files->create_dir($currentfolder, $parentfolderuuid, '', true); // add the parent folder to our expected sequence of UUIDs $expectedpath[] = repository_elisfiles::build_encodedpath($parentfolderuuid); // elis_files_folder_structure get_parent_path test $starttime = microtime(); $folders = elis_files_folder_structure(); $altrecursivepath = array(); $repo->get_parent_path($currentfolderuuid, $altrecursivepath, 0, 0, 0, 0, 'tree'); $endtime = time(); $structuretime = microtime_diff($starttime, microtime()); // validate the count $this->assertEquals($i, count($altrecursivepath)); // validate the encoded folder UUIDs // look over the expected path parts foreach ($expectedpath as $pathindex => $expectedpart) { // obtain the matching part from the actual return value $resultpart = $altrecursivepath[$pathindex]; $this->assertEquals($expectedpart, $resultpart['path']); } // NOTE: add this back in if we are testing performance $times[] = $times[] = "Folder: $currentfolder and time: $structuretime"; // or nested folders $parentfolderuuid = $currentfolderuuid; } }
} if ($object->IsWYSIWYG() && $object->WYSIWYGActive()) { $bodytext .= $object->WYSIWYGGenerateBody(); $headertext .= $object->WYSIWYGGenerateHeader($htmlresult); $formtext .= $object->WYSIWYGPageForm(); $formsubmittext .= $object->WYSIWYGPageFormSubmit(); //break; } else { if ($object->IsSyntaxHighlighter() && $object->SyntaxActive()) { $bodytext .= $object->SyntaxGenerateBody(); $headertext .= $object->SyntaxGenerateHeader($htmlresult); $formtext .= $object->SyntaxPageForm(); $formsubmittext .= $object->SyntaxPageFormSubmit(); // break; } } } } $htmlresult = $themeObject->postprocess($htmlresult); $htmlresult = str_replace('<!-- THIS IS WHERE HEADER STUFF SHOULD GO -->', $headertext, $htmlresult); $htmlresult = str_replace('##FORMSUBMITSTUFFGOESHERE##', ' ' . $formtext, $htmlresult); $htmlresult = str_replace('##INLINESUBMITSTUFFGOESHERE##', ' ' . $formsubmittext, $htmlresult); $htmlresult = str_replace('##BODYSUBMITSTUFFGOESHERE##', ' ' . $bodytext, $htmlresult); echo $htmlresult; $db = cmsms()->GetDb(); $endtime = microtime(); $memory = function_exists('memory_get_usage') ? memory_get_usage() : 0; $memory_net = $memory - $orig_memory; $memory_peak = function_exists('memory_get_peak_usage') ? memory_get_peak_usage() : 0; echo "<!-- " . microtime_diff($starttime, $endtime) . " / " . (isset($db->query_count) ? $db->query_count : '') . " / {$memory_net} / {$memory} / {$memory_peak} -->\n"; # vim:ts=4 sw=4 noet
/** * Cron functions. * * @package core * @subpackage admin * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ function cron_run() { global $DB, $CFG, $OUTPUT; if (CLI_MAINTENANCE) { echo "CLI maintenance mode active, cron execution suspended.\n"; exit(1); } if (moodle_needs_upgrading()) { echo "Moodle upgrade pending, cron execution suspended.\n"; exit(1); } require_once $CFG->libdir . '/adminlib.php'; require_once $CFG->libdir . '/gradelib.php'; if (!empty($CFG->showcronsql)) { $DB->set_debug(true); } if (!empty($CFG->showcrondebugging)) { $CFG->debug = DEBUG_DEVELOPER; $CFG->debugdisplay = true; } set_time_limit(0); $starttime = microtime(); /// increase memory limit raise_memory_limit(MEMORY_EXTRA); /// emulate normal session cron_setup_user(); /// Start output log $timenow = time(); mtrace("Server Time: " . date('r', $timenow) . "\n\n"); /// Session gc mtrace("Cleaning up stale sessions"); session_gc(); /// Run all cron jobs for each module mtrace("Starting activity modules"); get_mailer('buffer'); if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { foreach ($mods as $mod) { $libfile = "{$CFG->dirroot}/mod/{$mod->name}/lib.php"; if (file_exists($libfile)) { include_once $libfile; $cron_function = $mod->name . "_cron"; if (function_exists($cron_function)) { mtrace("Processing module function {$cron_function} ...", ''); $pre_dbqueries = null; $pre_dbqueries = $DB->perf_get_queries(); $pre_time = microtime(1); if ($cron_function()) { $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id)); } if (isset($pre_dbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pre_time) . " seconds"); } /// Reset possible changes by modules to time_limit. MDL-11597 @set_time_limit(0); mtrace("done."); } } } } get_mailer('close'); mtrace("Finished activity modules"); mtrace("Starting blocks"); if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { // we will need the base class. require_once $CFG->dirroot . '/blocks/moodleblock.class.php'; foreach ($blocks as $block) { $blockfile = $CFG->dirroot . '/blocks/' . $block->name . '/block_' . $block->name . '.php'; if (file_exists($blockfile)) { require_once $blockfile; $classname = 'block_' . $block->name; $blockobj = new $classname(); if (method_exists($blockobj, 'cron')) { mtrace("Processing cron function for " . $block->name . '....', ''); if ($blockobj->cron()) { $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id)); } /// Reset possible changes by blocks to time_limit. MDL-11597 @set_time_limit(0); mtrace('done.'); } } } } mtrace('Finished blocks'); //now do plagiarism checks require_once $CFG->libdir . '/plagiarismlib.php'; plagiarism_cron(); mtrace("Starting quiz reports"); if ($reports = $DB->get_records_select('quiz_report', "cron > 0 AND ((? - lastcron) > cron)", array($timenow))) { foreach ($reports as $report) { $cronfile = "{$CFG->dirroot}/mod/quiz/report/{$report->name}/cron.php"; if (file_exists($cronfile)) { include_once $cronfile; $cron_function = 'quiz_report_' . $report->name . "_cron"; if (function_exists($cron_function)) { mtrace("Processing quiz report cron function {$cron_function} ...", ''); $pre_dbqueries = null; $pre_dbqueries = $DB->perf_get_queries(); $pre_time = microtime(1); if ($cron_function()) { $DB->set_field('quiz_report', "lastcron", $timenow, array("id" => $report->id)); } if (isset($pre_dbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pre_time) . " seconds"); } mtrace("done."); } } } } mtrace("Finished quiz reports"); mtrace('Starting admin reports'); // Admin reports do not have a database table that lists them. Instead a // report includes cron.php with function report_reportname_cron() if it wishes // to be cronned. It is up to cron.php to handle e.g. if it only needs to // actually do anything occasionally. $reports = get_plugin_list('report'); foreach ($reports as $report => $reportdir) { $cronfile = $reportdir . '/cron.php'; if (file_exists($cronfile)) { require_once $cronfile; $cronfunction = 'report_' . $report . '_cron'; mtrace('Processing cron function for ' . $report . '...', ''); $pre_dbqueries = null; $pre_dbqueries = $DB->perf_get_queries(); $pre_time = microtime(true); $cronfunction(); if (isset($pre_dbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries"); mtrace("... used " . round(microtime(true) - $pre_time, 2) . " seconds"); } mtrace('done.'); } } mtrace('Finished admin reports'); mtrace('Starting main gradebook job ...'); grade_cron(); mtrace('done.'); mtrace('Starting processing the event queue...'); events_cron(); mtrace('done.'); if ($CFG->enablecompletion) { // Completion cron mtrace('Starting the completion cron...'); require_once $CFG->libdir . '/completion/cron.php'; completion_cron(); mtrace('done'); } if ($CFG->enableportfolios) { // Portfolio cron mtrace('Starting the portfolio cron...'); require_once $CFG->libdir . '/portfoliolib.php'; portfolio_cron(); mtrace('done'); } /// Run all core cron jobs, but not every time since they aren't too important. /// These don't have a timer to reduce load, so we'll use a random number /// to randomly choose the percentage of times we should run these jobs. srand((double) microtime() * 10000000); $random100 = rand(0, 100); if ($random100 < 20) { // Approximately 20% of the time. mtrace("Running clean-up tasks..."); /// Delete users who haven't confirmed within required period if (!empty($CFG->deleteunconfirmed)) { $cuttime = $timenow - $CFG->deleteunconfirmed * 3600; $rs = $DB->get_recordset_sql("SELECT id, firstname, lastname\n FROM {user}\n WHERE confirmed = 0 AND firstaccess > 0\n AND firstaccess < ?", array($cuttime)); foreach ($rs as $user) { if ($DB->delete_records('user', array('id' => $user->id))) { mtrace("Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})"); } } $rs->close(); } flush(); /// Delete users who haven't completed profile within required period if (!empty($CFG->deleteincompleteusers)) { $cuttime = $timenow - $CFG->deleteincompleteusers * 3600; $rs = $DB->get_recordset_sql("SELECT id, username\n FROM {user}\n WHERE confirmed = 1 AND lastaccess > 0\n AND lastaccess < ? AND deleted = 0\n AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime)); foreach ($rs as $user) { if (delete_user($user)) { mtrace("Deleted not fully setup user {$user->username} ({$user->id})"); } } $rs->close(); } flush(); /// Delete old logs to save space (this might need a timer to slow it down...) if (!empty($CFG->loglifetime)) { // value in days $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24; if ($DB->delete_records_select("log", "time < ?", array($loglifetime))) { mtrace("Deleted old log records"); } } flush(); // Delete old backup_controllers and logs if (!empty($CFG->loglifetime)) { // value in days $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24; // Delete child records from backup_logs $DB->execute("DELETE FROM {backup_logs}\n WHERE EXISTS (\n SELECT 'x'\n FROM {backup_controllers} bc\n WHERE bc.backupid = {backup_logs}.backupid\n AND bc.timecreated < ?)", array($loglifetime)); // Delete records from backup_controllers $DB->execute("DELETE FROM {backup_controllers}\n WHERE timecreated < ?", array($loglifetime)); mtrace("Deleted old backup records"); } flush(); /// Delete old cached texts if (!empty($CFG->cachetext)) { // Defined in config.php $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites if ($DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime))) { mtrace("Deleted old cache_text records"); } } flush(); if (!empty($CFG->notifyloginfailures)) { notify_login_failures(); mtrace('Notified login failured'); } flush(); // // generate new password emails for users // mtrace('checking for create_password'); if ($DB->count_records('user_preferences', array('name' => 'create_password', 'value' => '1'))) { mtrace('creating passwords for new users'); $newusers = $DB->get_records_sql("SELECT u.id as id, u.email, u.firstname,\n u.lastname, u.username,\n p.id as prefid\n FROM {user} u\n JOIN {user_preferences} p ON u.id=p.userid\n WHERE p.name='create_password' AND p.value='1' AND u.email !='' "); foreach ($newusers as $newuserid => $newuser) { // email user if (setnew_password_and_mail($newuser)) { // remove user pref $DB->delete_records('user_preferences', array('id' => $newuser->prefid)); } else { trigger_error("Could not create and mail new user password!"); } } } if (!empty($CFG->usetags)) { require_once $CFG->dirroot . '/tag/lib.php'; tag_cron(); mtrace('Executed tag cron'); } // Accesslib stuff cleanup_contexts(); mtrace('Cleaned up contexts'); gc_cache_flags(); mtrace('Cleaned cache flags'); // If you suspect that the context paths are somehow corrupt // replace the line below with: build_context_path(true); build_context_path(); mtrace('Built context paths'); if (!empty($CFG->messagingdeletereadnotificationsdelay)) { $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay; $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime' => $notificationdeletetime)); mtrace('Cleaned up read notifications'); } mtrace("Finished clean-up tasks..."); } // End of occasional clean-up tasks // Run automated backups if required. require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php'; require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php'; backup_cron_automated_helper::run_automated_backup(); /// Run the auth cron, if any /// before enrolments because it might add users that will be needed in enrol plugins $auths = get_enabled_auth_plugins(); mtrace("Running auth crons if required..."); foreach ($auths as $auth) { $authplugin = get_auth_plugin($auth); if (method_exists($authplugin, 'cron')) { mtrace("Running cron for auth/{$auth}..."); $authplugin->cron(); if (!empty($authplugin->log)) { mtrace($authplugin->log); } } unset($authplugin); } mtrace("Running enrol crons if required..."); $enrols = enrol_get_plugins(true); foreach ($enrols as $ename => $enrol) { // do this for all plugins, disabled plugins might want to cleanup stuff such as roles if (!$enrol->is_cron_required()) { continue; } mtrace("Running cron for enrol_{$ename}..."); $enrol->cron(); $enrol->set_config('lastcron', time()); } if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) { require_once $CFG->dirroot . '/lib/statslib.php'; // check we're not before our runtime $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60; if (time() > $timetocheck) { // process configured number of days as max (defaulting to 31) $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays); if (stats_cron_daily($maxdays)) { if (stats_cron_weekly()) { if (stats_cron_monthly()) { stats_clean_old(); } } } @set_time_limit(0); } else { mtrace('Next stats run after:' . userdate($timetocheck)); } } // run gradebook import/export/report cron if ($gradeimports = get_plugin_list('gradeimport')) { foreach ($gradeimports as $gradeimport => $plugindir) { if (file_exists($plugindir . '/lib.php')) { require_once $plugindir . '/lib.php'; $cron_function = 'grade_import_' . $gradeimport . '_cron'; if (function_exists($cron_function)) { mtrace("Processing gradebook import function {$cron_function} ...", ''); $cron_function(); } } } } if ($gradeexports = get_plugin_list('gradeexport')) { foreach ($gradeexports as $gradeexport => $plugindir) { if (file_exists($plugindir . '/lib.php')) { require_once $plugindir . '/lib.php'; $cron_function = 'grade_export_' . $gradeexport . '_cron'; if (function_exists($cron_function)) { mtrace("Processing gradebook export function {$cron_function} ...", ''); $cron_function(); } } } } if ($gradereports = get_plugin_list('gradereport')) { foreach ($gradereports as $gradereport => $plugindir) { if (file_exists($plugindir . '/lib.php')) { require_once $plugindir . '/lib.php'; $cron_function = 'grade_report_' . $gradereport . '_cron'; if (function_exists($cron_function)) { mtrace("Processing gradebook report function {$cron_function} ...", ''); $cron_function(); } } } } // Run external blog cron if needed if ($CFG->useexternalblogs) { require_once $CFG->dirroot . '/blog/lib.php'; mtrace("Fetching external blog entries...", ''); $sql = "timefetched < ? OR timefetched = 0"; $externalblogs = $DB->get_records_select('blog_external', $sql, array(mktime() - $CFG->externalblogcrontime)); foreach ($externalblogs as $eb) { blog_sync_external_entries($eb); } } // Run blog associations cleanup if ($CFG->useblogassociations) { require_once $CFG->dirroot . '/blog/lib.php'; // delete entries whose contextids no longer exists mtrace("Deleting blog associations linked to non-existent contexts...", ''); $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})'); } //Run registration updated cron mtrace(get_string('siteupdatesstart', 'hub')); require_once $CFG->dirroot . '/admin/registration/lib.php'; $registrationmanager = new registration_manager(); $registrationmanager->cron(); mtrace(get_string('siteupdatesend', 'hub')); // cleanup file trash $fs = get_file_storage(); $fs->cron(); //cleanup old session linked tokens //deletes the session linked tokens that are over a day old. mtrace("Deleting session linked tokens more than one day old...", ''); $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED)); mtrace('done.'); // run any customized cronjobs, if any if ($locals = get_plugin_list('local')) { mtrace('Processing customized cron scripts ...', ''); foreach ($locals as $local => $localdir) { if (file_exists("{$localdir}/cron.php")) { include "{$localdir}/cron.php"; } } mtrace('done.'); } mtrace("Cron script completed correctly"); $difftime = microtime_diff($starttime, microtime()); mtrace("Execution took " . $difftime . " seconds"); }
/** * Debug function to display $var nicely in html. * * @param mixed $var * @param string $title (optional) * @param boolean $echo_to_screen (optional) * @return string */ function debug_display($var, $title = "", $echo_to_screen = true, $use_html = true) { $variables =& cmsms()->variables; $starttime = microtime(); if (isset($variables['starttime'])) { $starttime = $variables['starttime']; } else { $variables['starttime'] = $starttime; } $titleText = "Debug: "; if ($title) { $titleText = "Debug display of '{$title}':"; } $titleText .= '(' . microtime_diff($starttime, microtime()) . ')'; if (function_exists('memory_get_usage')) { $titleText .= ' - (usage: ' . memory_get_usage() . ')'; } $memory_peak = function_exists('memory_get_peak_usage') ? memory_get_peak_usage() : ''; if ($memory_peak) { $titleText .= ' - (peak: ' . $memory_peak . ')'; } ob_start(); if ($use_html) { echo "<div><b>{$titleText}</b>\n"; } else { echo "{$titleText}\n"; } if (FALSE == empty($var)) { if ($use_html) { echo '<pre>'; } if (is_array($var)) { echo "Number of elements: " . count($var) . "\n"; print_r($var); } elseif (is_object($var)) { print_r($var); } elseif (is_string($var)) { if ($use_html) { print_r(htmlentities(str_replace("\t", ' ', $var))); } else { print_r($var); } } elseif (is_bool($var)) { echo $var === true ? 'true' : 'false'; } else { print_r($var); } if ($use_html) { echo '</pre>'; } } if ($use_html) { echo "</div>\n"; } $output = ob_get_contents(); ob_end_clean(); if ($echo_to_screen) { echo $output; } return $output; }
/** *** get_performance_info() pairs up with init_performance_info() *** loaded in init.php. Returns an array with 'html' and 'txt' *** values ready for use, and each of the individual stats provided *** separately as well. *** **/ function get_performance_info() { if (!get_config('perftofoot') && !get_config('perftolog')) { return array(); } global $PERF; $info = array(); $info['realtime'] = microtime_diff($PERF->starttime, microtime()); if (function_exists('memory_get_usage')) { $info['memory_total'] = memory_get_usage(); $info['memory_growth'] = memory_get_usage() - $PERF->startmemory; } $inc = get_included_files(); $info['includecount'] = count($inc); $info['dbreads'] = $PERF->dbreads; $info['dbwrites'] = $PERF->dbwrites; $info['dbcached'] = $PERF->dbcached; if (function_exists('posix_times')) { $ptimes = posix_times(); if (is_array($ptimes)) { foreach ($ptimes as $key => $val) { $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key]; } } } // 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 { log_debug('PERF: Could not parse uptime output!'); } } } if (!empty($server_load)) { $info['serverload'] = $server_load; } else { $info['serverload'] = 'unknown'; } return $info; }
} $display = isPermitted($module, $now_action); } } if ($display == "no") { echo "<table border='0' cellpadding='5' cellspacing='0' width='100%' height='450px'><tr><td align='center'>"; echo "<div style='border: 3px solid rgb(153, 153, 153); background-color: rgb(255, 255, 255); width: 55%; position: relative; z-index: 10000000;'>\n\n\t\t<table border='0' cellpadding='5' cellspacing='0' width='98%'>\n\t\t<tbody><tr>\n\t\t<td rowspan='2' width='11%'><img src='themes/{$theme}/images/denied.gif' ></td>\n\t\t<td style='border-bottom: 1px solid rgb(204, 204, 204);' nowrap='nowrap' width='70%'><span class='genHeaderSmall'>" . $app_strings["LBL_PERMISSION"] . "</span></td>\n\t\t</tr>\n\t\t<tr>\n\t\t<td class='small' align='right' nowrap='nowrap'>\t\t\t \t\n\t\t<a href='javascript:window.history.back();'>" . $app_strings["LBL_GO_BACK"] . "</a><br>\t\t\t\t\t\t\t\t \t\t\t\t\t\t </td>\n\t\t</tr>\n\t\t</tbody></table> \n\t\t</div>"; echo "</td></tr></table>"; $skipFooters = true; } else { include $root_directory . $currentModuleFile; } if (!$skipFooters) { echo "<table align='center'><tr><td align='center'>"; if ($calculate_response_time) { $endTime = microtime(); $deltaTime = microtime_diff($startTime, $endTime); $webTime = $deltaTime - $connectTime - $queryTime; echo 'Server response time: ' . $deltaTime . ' seconds.<br>'; echo 'Server response connect time: ' . $connectTime . ' seconds.<br>'; echo 'Server response query time: ' . $queryTime . ' seconds.<br>'; echo 'Server response connect times: ' . $connectTimes . ' times.<br>'; echo 'Server response query times: ' . $queryTimes . ' times.<br>'; echo 'Server response web time: ' . $webTime . ' seconds.<br>'; if (function_exists('memory_get_peak_usage')) { echo "Peak memory usage: " . memory_get_peak_usage(true) / 1024 / 1024 . " MB<br>"; } } echo "</td></tr></table>\n"; include $root_directory . 'themes/' . $theme . '/footer.php'; }
/** * 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; }
/** * Run scheduled tasks according to a cron spec. * * uses $CFG, $DB */ function local_eliscore_cron() { global $CFG, $DB; require $CFG->dirroot . '/local/eliscore/lib/tasklib.php'; $timenow = time(); // get all tasks that are (over-)due $params = array('timenow' => $timenow); $tasks = $DB->get_recordset_select('local_eliscore_sched_tasks', 'nextruntime <= :timenow', $params, 'nextruntime ASC'); $numtasks = $DB->count_records_select('local_eliscore_sched_tasks', 'nextruntime <= :timenow', $params); // Check if the maximum cron run time is overridden $remtime = ELIS_TASKS_CRONSECS; if (isset($CFG->elistaskscronsecs) && is_int($CFG->elistaskscronsecs) && 0 < $CFG->elistaskscronsecs) { $remtime = $CFG->elistaskscronsecs; } if (empty($tasks) || !$tasks->valid()) { return; } foreach ($tasks as $task) { $starttime = microtime(); mtrace("Running {$task->callfunction}({$task->taskname}) from {$task->plugin}..."); if ($task->enddate !== null && $task->enddate < $timenow) { mtrace('* Cancelling task: past end date'); $DB->delete_records('local_eliscore_sched_tasks', array('id' => $task->id)); --$numtasks; continue; } // Check for blocking tasks. if (!empty($task->blocked) && $timenow < $task->blocked) { // Task is still running - do not start another instance of it. mtrace("{$task->plugin}: Previous {$task->taskname} process has not yet completed - aborting!"); continue; } // FIXME: check if task is locked // See if some other cron has already run the function while we were // doing something else -- if so, skip it. $nextrun = $DB->get_field('local_eliscore_sched_tasks', 'nextruntime', array('id' => $task->id)); if ($nextrun > $timenow) { mtrace('* Skipped (someone else already ran it)'); --$numtasks; continue; } // calculate the next run time $newtask = new stdClass(); $newtask->id = $task->id; $newtask->lastruntime = time(); $newtask->nextruntime = cron_next_run_time($newtask->lastruntime, (array) $task); // see if we have any runs left if ($task->runsremaining !== null) { $newtask->runsremaining = $task->runsremaining - 1; if ($newtask->runsremaining <= 0) { mtrace('* Cancelling task: no runs left'); $DB->delete_records('local_eliscore_sched_tasks', array('id' => $task->id)); } else { $DB->update_record('local_eliscore_sched_tasks', $newtask); } } else { $DB->update_record('local_eliscore_sched_tasks', $newtask); } // load the file and call the function if ($task->callfile) { $callfile = $CFG->dirroot . $task->callfile; if (!is_readable($callfile)) { mtrace('* Skipped (file not found)'); --$numtasks; continue; } require_once $callfile; } $starttask = time(); $denom = $numtasks > 0 ? $numtasks-- : 1; // prevent div by 0 $runtime = floor((double) $remtime / (double) $denom); call_user_func(unserialize($task->callfunction), $task->taskname, $runtime); $remtime -= time() - $starttask; $difftime = microtime_diff($starttime, microtime()); mtrace("* {$difftime} seconds"); // TBD: exit if over cron processing time if ($remtime <= 0) { break; } } }
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) { if (!function_exists('sqlsrv_connect')) { return null; } global $connectTime, $connectTimes; $startTime1 = microtime(); $connectionInfo = array("Database" => $argDatabasename, 'UID' => $argUsername, 'PWD' => $argPassword, "CharacterSet" => "UTF-8"); if ($this->debug) { error_log("<hr>connecting... hostname: {$argHostname} params: " . var_export($connectionInfo, true)); } //if ($this->debug) error_log("<hr>_connectionID before: ".serialize($this->_connectionID)); if (!($this->_connectionID = sqlsrv_connect($argHostname, $connectionInfo))) { if ($this->debug) { error_log("<hr><b>errors</b>: " . print_r(sqlsrv_errors(), true)); } return false; } $endTime1 = microtime(); $deltaTime1 = microtime_diff($startTime1, $endTime1); $connectTime += $deltaTime1; $connectTimes = $connectTimes + 1; //if ($this->debug) error_log(" _connectionID after: ".serialize($this->_connectionID)); //if ($this->debug) error_log("<hr>defined functions: <pre>".var_export(get_defined_functions(),true)."</pre>"); return true; }
function cron() { global $CFG; /// We are going to measure execution times $starttime = microtime(); /// And we have one initial $status $status = true; /// We require some stuff require_once $CFG->libdir . '/rsslib.php'; require_once MAGPIE_DIR . 'rss_fetch.inc'; if (!defined('MAGPIE_OUTPUT_ENCODING')) { define('MAGPIE_OUTPUT_ENCODING', 'utf-8'); // see bug 3107 } /// Fetch all site feeds. $rs = get_recordset('block_rss_client'); $counter = 0; mtrace(''); while ($rec = rs_fetch_next_record($rs)) { mtrace(' ' . $rec->url . ' ', ''); /// Fetch the rss feed, using standard magpie caching /// so feeds will be renewed only if cache has expired // sometimes the cron times out on moodle.org during fetching, // there is a 5s limit in magpie which should work, but does not sometimes :-( @set_time_limit(60); if ($rss = fetch_rss($rec->url)) { mtrace('ok'); } else { mtrace('error'); $status = false; } $counter++; } rs_close($rs); /// Show times mtrace($counter . ' feeds refreshed (took ' . microtime_diff($starttime, microtime()) . ' seconds)'); /// And return $status return $status; }
/** * 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; }
$ct = 'text/html'; } header("Content-Type: {$ct}; charset=" . get_encoding()); echo $html; @ob_flush(); $endtime = microtime(); $db =& cmsms()->GetDb(); if ($config['debug'] == TRUE || isset($config['show_performance_info']) && $showtemplate == true) { $memory = function_exists('memory_get_usage') ? memory_get_usage() : 0; $memory = $memory - $orig_memory; $memory_peak = function_exists('memory_get_peak_usage') ? memory_get_peak_usage() : 0; if (!is_sitedown() && $config["debug"] == true) { echo "<p>Generated in " . microtime_diff($starttime, $endtime) . " seconds by CMS Made Simple using " . (isset($db->query_count) ? $db->query_count : '') . " SQL queries and {$memory} bytes of memory (peak memory usage was {$memory_peak})</p>"; } else { if (isset($config['show_performance_info']) && $showtemplate == true) { $txt = microtime_diff($starttime, $endtime) . " / " . (isset($db->query_count) ? $db->query_count : '') . " / {$memory} / {$memory_peak}"; debug_display($txt); echo '<!-- ' . $txt . " -->\n"; } } } if (is_sitedown() || $config['debug'] == true) { $smarty->clear_compiled_tpl(); } if (!is_sitedown() && $config["debug"] == true) { #$db->LogSQL(false); // turn off logging # output summary of SQL logging results #$perf = NewPerfMonitor($db); #echo $perf->SuspiciousSQL(); #echo $perf->ExpensiveSQL(); #echo $sql_queries;
/** * cron - goes through all feeds and retrieves them with the cache * duration set to 0 in order to force the retrieval of the item and * refresh the cache * * @return boolean true if all feeds were retrieved succesfully */ function cron() { global $CFG, $DB; require_once $CFG->libdir . '/simplepie/moodle_simplepie.php'; // We are going to measure execution times $starttime = microtime(); // And we have one initial $status $status = true; // Fetch all site feeds. $rs = $DB->get_recordset('block_rss_client'); $counter = 0; mtrace(''); foreach ($rs as $rec) { mtrace(' ' . $rec->url . ' ', ''); // Fetch the rss feed, using standard simplepie caching // so feeds will be renewed only if cache has expired @set_time_limit(60); $feed = new moodle_simplepie(); // set timeout for longer than normal to be agressive at // fetching feeds if possible.. $feed->set_timeout(40); $feed->set_cache_duration(0); $feed->set_feed_url($rec->url); $feed->init(); if ($feed->error()) { mtrace('error'); mtrace('SimplePie failed with error:' . $feed->error()); $status = false; } else { mtrace('ok'); } $counter++; } $rs->close(); // Show times mtrace($counter . ' feeds refreshed (took ' . microtime_diff($starttime, microtime()) . ' seconds)'); // And return $status return $status; }
$ids = join(',', array_keys($ids)); $totals[$hotpot->id]->detailcount = $DB->count_records_select('hotpot_details', "attempt IN ({$ids})"); } } } // message strings for main table $strusers = get_string('users'); $strupdate = get_string('update'); $strregrade = get_string('regrade', 'hotpot'); $strneverclosed = get_string('neverclosed', 'hotpot'); $strregraderequired = get_string('regraderequired', 'hotpot'); // column headings and attributes $table->head = array(); $table->align = array(); if (!empty($CFG->hotpot_showtimes)) { print '<H3>' . sprintf("%0.3f", microtime_diff($start, microtime())) . ' secs' . "</H3>\n"; } switch ($course->format) { case 'weeks': $title = get_string("week"); break; case 'topics': $title = get_string("topic"); break; default: $title = ''; break; } if ($title) { array_push($table->head, $title); array_push($table->align, "center");
} } if ($gradereports = get_list_of_plugins('grade/report')) { foreach ($gradereports as $gradereport) { if (file_exists($CFG->dirroot . '/grade/report/' . $gradereport . '/lib.php')) { require_once $CFG->dirroot . '/grade/report/' . $gradereport . '/lib.php'; $cron_function = 'grade_report_' . $gradereport . '_cron'; if (function_exists($cron_function)) { mtrace("Processing gradebook report function {$cron_function} ...", ''); $cron_function; } } } } // run any customized cronjobs, if any // looking for functions in lib/local/cron.php if (file_exists($CFG->dirroot . '/local/cron.php')) { mtrace('Processing customized cron script ...', ''); include_once $CFG->dirroot . '/local/cron.php'; mtrace('done.'); } //Unset session variables and destroy it @session_unset(); @session_destroy(); mtrace("Cron script completed correctly"); $difftime = microtime_diff($starttime, microtime()); mtrace("Execution took " . $difftime . " seconds"); /// finish the IE hack if (check_browser_version('MSIE')) { echo "</xmp>"; }
} } $result = $GLOBALS['db']->query("SELECT team_set_id, team_id FROM team_sets_teams"); $team_sets = array(); while ($row = $GLOBALS['db']->fetchByAssoc($result)) { $team_sets[$row['team_set_id']][] = $row['team_id']; } DataTool::$team_sets_array = $team_sets; } echo "DONE\n"; } endTransaction(); if (!empty($GLOBALS['queryFP'])) { fclose($GLOBALS['queryFP']); } echo "Total Time: " . microtime_diff($_SESSION['startTime'], microtime()) . "\n"; echo "Core Records Inserted: " . $_SESSION['processedRecords'] . "\n"; echo "Total Records Inserted: " . $_SESSION['allProcessedRecords'] . "\n"; // BEGIN Activity Stream populating if (!empty($_SESSION['as_populate'])) { $activityStreamOptions = array('activities_per_module_record' => !empty($_SESSION['as_number']) ? $_SESSION['as_number'] : 10, 'insertion_buffer_size' => !empty($_SESSION['as_buffer']) ? $_SESSION['as_buffer'] : 1000, 'last_n_records' => !empty($_SESSION['as_last_rec']) ? $_SESSION['as_last_rec'] : 0); if (!empty($GLOBALS['beanList']['Activities'])) { echo "\nPopulating Activity Stream\n"; $timer = microtime(1); require_once 'Tidbit/Generator/ActivityGenerator.php'; $tga = new TidbitActivityGenerator(); $tga->userCount = $GLOBALS['modules']['Users']; $tga->activitiesPerModuleRecord = $activityStreamOptions['activities_per_module_record']; $tga->modules = $GLOBALS['modules']; $tga->db = $GLOBALS['db']; $tga->insertionBufferSize = $activityStreamOptions['insertion_buffer_size'];