public function bench(RestServer $rest) { $rest->getResponse()->appendResponse("It took " . round(xdebug_time_index(), 5) . " seconds\n"); $rest->getResponse()->appendResponse("Used " . round(xdebug_memory_usage() / 1024, 5) . "Kb of Memory\n"); $rest->getResponse()->appendResponse("Used at peak " . round(xdebug_peak_memory_usage() / 1024, 5) . "Kb of Memory\n"); return $rest; }
public function getScriptDuration() { if (function_exists('xdebug_time_index')) { return sprintf("%0.2f", xdebug_time_index()); } else { return 'n/a'; } }
public static function benchIt() { if (function_exists('xdebug_time_index')) { return xdebug_time_index(); } else { return microtime(); } }
/** * @param \Civi\API\Event\RespondEvent $event * API response event. */ public function onApiRespond(\Civi\API\Event\RespondEvent $event) { $apiRequest = $event->getApiRequest(); $result = $event->getResponse(); if (function_exists('xdebug_time_index') && \CRM_Utils_Array::value('debug', $apiRequest['params']) && is_array($result)) { $result['xdebug']['peakMemory'] = xdebug_peak_memory_usage(); $result['xdebug']['memory'] = xdebug_memory_usage(); $result['xdebug']['timeIndex'] = xdebug_time_index(); $event->setResponse($result); } }
/** * Add an assertion to the test * * @param string $label * @param boolean $status * @param string $filename * @param int $line * @throws \RuntimeException * @return \Unitest\Result */ public function assert($label, $status, $filename, $line) { if (!function_exists('xdebug_time_index')) { $message = "Xdebug is required to use Unitest"; throw new \RuntimeException($message, 500); } if (false === $status) { ++$this->failed; } $this->assertions[] = new Assert($label, $status, $filename, $line, xdebug_time_index()); return $this; }
/** * Weird little script to trigger an xdebug info box. * I use this to test for bottlenecks before I discovered cache grind. I'll leave it in incase I need it for something. * * @param string $msg A message, useful for identifying a break point. */ function xdebugInfo ($msg = false) { if ($init['debug']) { trigger_error( '[xdbInfo] ' . ($msg ? '<span style="color:white;background-color:#D60;">' . $msg . '</span> | ' : null) . ' Mem: <span style="color:white;background-color:#D60;">' . Round( (xdebug_memory_usage() / 1000), 2) . ' Kb</span>, Time: <span style="color:white;background-color:#D60;">' . str_pad( Round(xdebug_time_index(), 4), 6, '0') . 'secs</span>', E_USER_WARNING); } }
function doDefault() { /* {{{ 导入过滤模块,并初始化 */ importModule("Filter.Filter"); $fl = new Filter(); /* }}} */ /* {{{ 过滤测试测试文本 */ $content = "大家好.有人认识李洪志吗? 学过法轮功的吗?"; echo "<b>原语句:</b> ", $content, "<br />"; /* }}} */ /* {{{ 检测是否含有非法关键字 */ $show = $fl->isForbidden($content); if ($show) { echo "<br />含有非法关键字!<br /><br />"; } else { echo "<br />没有有非法关键字!<br /><br />"; } /* }}} */ /* {{{ 过滤文本 */ $start = xdebug_time_index(); $show = $fl->clean($content); echo "<b>过滤后的:</b>", $show, "<br />"; echo "用时: ", xdebug_time_index() - $start, "<br />"; /* }}} */ /* {{{ 过滤文本, 指定替换的格式 */ $start = xdebug_time_index(); $show = $fl->clean($content, "×"); echo "<br /><b>指定替换内容过滤:</b> ", $show, "<br />"; echo "用时: ", xdebug_time_index() - $start, "<br />"; /* }}} */ /* {{{ 并手工指定关键字再过滤文本 */ $start = xdebug_time_index(); $fl->setKey(array('大家好')); $show = $fl->clean($content); echo "<br /><b>手工指定关键字过滤:</b> ", $show, "<br />"; echo "用时: ", xdebug_time_index() - $start, "<br />"; /* }}} */ /* {{{ 模糊过滤文本 */ $start = xdebug_time_index(); $ff = new Filter(); $content = "start:李 洪 志-测-试- f-!u-c=k, f**k:end"; echo "<br /><b>原语句:</b> ", $content, "<br />"; $show = $ff->fuzzyClean($content, "*", 2); //其中2为深度,默认值,值越大清理越干净,误杀越多,消耗资源越多. echo "<b>模糊过滤后:</b> ", $show, "<br />"; echo "用时: ", xdebug_time_index() - $start, "<br />"; /* }}} */ }
} function test_intersect($list1, $list2) { return count(array_intersect($list1, $list2)); } function test_order_dicto_while($list, $elem) { $start = 0; $end = count($list); while ($start < $end) { $middle = (int) (($start + $end) / 2); if ($list[$middle] == $elem || $list[$start] == $elem) { return true; } if ($elem > $list[$middle]) { $start = $middle + 1; } else { $end = $middle - 1; } } return false; } $list1 = file('./list1.txt'); $list2 = file('./list2.txt'); $elem = 9682; //if (test_order_dicto_while(file('./orderList.txt'), $elem)) echo "find : $elem"; else echo "not found $elem"; if (array_search($elem, file('./orderList.txt'))) { } //echo test_foreach($list1, $list2); printf("duration : %f", xdebug_time_index());
/** * Print common footer : * conf->global->MAIN_HTML_FOOTER * conf->global->MAIN_GOOGLE_AN_ID * conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"] * conf->logbuffer * * @param string $zone 'private' (for private pages) or 'public' (for public pages) * @return void */ function printCommonFooter($zone = 'private') { global $conf, $hookmanager; global $micro_start_time; if ($zone == 'private') { print "\n" . '<!-- Common footer for private page -->' . "\n"; } else { print "\n" . '<!-- Common footer for public page -->' . "\n"; } if (!empty($conf->global->MAIN_HTML_FOOTER)) { print $conf->global->MAIN_HTML_FOOTER . "\n"; } print "\n"; if (!empty($conf->use_javascript_ajax)) { print '<script type="text/javascript" language="javascript">jQuery(document).ready(function() {' . "\n"; print '<!-- If page_y set, we set scollbar with it -->' . "\n"; print "page_y=getParameterByName('page_y', 0);"; print "if (page_y > 0) \$('html, body').scrollTop(page_y);"; print '<!-- Set handler to add page_y param on some a href links -->' . "\n"; print 'jQuery(".reposition").click(function() { var page_y = $(document).scrollTop(); /* alert(page_y); */ this.href=this.href+\'&page_y=\'+page_y; });' . "\n"; print '});' . "\n"; print '</script>' . "\n"; } // Google Analytics (need Google module) if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) { if (empty($conf->dol_use_jmobile)) { print "\n"; print '<script type="text/javascript">' . "\n"; print ' var _gaq = _gaq || [];' . "\n"; print ' _gaq.push([\'_setAccount\', \'' . $conf->global->MAIN_GOOGLE_AN_ID . '\']);' . "\n"; print ' _gaq.push([\'_trackPageview\']);' . "\n"; print '' . "\n"; print ' (function() {' . "\n"; print ' var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;' . "\n"; print ' ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';' . "\n"; print ' var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);' . "\n"; print ' })();' . "\n"; print '</script>' . "\n"; } } // End of tuning if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) { print "\n" . '<script type="text/javascript">' . "\n"; print 'window.console && console.log("'; if (!empty($conf->global->MEMCACHED_SERVER)) { print 'MEMCACHED_SERVER=' . $conf->global->MEMCACHED_SERVER . ' - '; } print 'MAIN_OPTIMIZE_SPEED=' . (isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off'); if ($micro_start_time) { $micro_end_time = microtime(true); print ' - Build time: ' . ceil(1000 * ($micro_end_time - $micro_start_time)) . ' ms'; } if (function_exists("memory_get_usage")) { print ' - Mem: ' . memory_get_usage(); } if (function_exists("xdebug_memory_usage")) { print ' - XDebug time: ' . ceil(1000 * xdebug_time_index()) . ' ms'; print ' - XDebug mem: ' . xdebug_memory_usage(); print ' - XDebug mem peak: ' . xdebug_peak_memory_usage(); } if (function_exists("zend_loader_file_encoded")) { print ' - Zend encoded file: ' . (zend_loader_file_encoded() ? 'yes' : 'no'); } print '");' . "\n"; print '</script>' . "\n"; // Add Xdebug coverage of code if (defined('XDEBUGCOVERAGE')) { print_r(xdebug_get_code_coverage()); } } // If there is some logs in buffer to show if (count($conf->logbuffer)) { print "\n"; print "<!-- Start of log output\n"; //print '<div class="hidden">'."\n"; foreach ($conf->logbuffer as $logline) { print $logline . "<br>\n"; } //print '</div>'."\n"; print "End of log output -->\n"; } $parameters = array(); $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks }
/** * Get time using microtime or xdebug */ private function _getTime() { if ($this->_xdebug) { return xdebug_time_index(); } return microtime(false); }
if (file_exists($settings_file)) { include $settings_file; } $BaseTemplate->template_path = SKINS_PATH; Template::Set('MODULE_NAV_INC', $NAVBAR); Template::Set('MODULE_HEAD_INC', $HTMLHead); ob_start(); MainController::RunAllActions(); $page_content = ob_get_clean(); $BaseTemplate->Set('title', MainController::$page_title . ' - ' . SITE_NAME); $BaseTemplate->Set('page_title', MainController::$page_title . ' - ' . SITE_NAME); if (file_exists(SKINS_PATH . '/layout.tpl')) { $BaseTemplate->Set('page_htmlhead', Template::Get('core_htmlhead.tpl', true)); $BaseTemplate->Set('page_htmlreq', Template::Get('core_htmlreq.tpl', true)); $BaseTemplate->Set('page_content', $page_content); $BaseTemplate->ShowTemplate('layout.tpl'); } else { # It's a template sammich! $BaseTemplate->ShowTemplate('header.tpl'); echo $page_content; $BaseTemplate->ShowTemplate('footer.tpl'); } # Force connection close DB::close(); if (Config::Get('XDEBUG_BENCHMARK')) { $run_time = xdebug_time_index(); $memory_end = xdebug_memory_usage(); echo 'TOTAL MEMORY: ' . ($memory_end - $memory_start) . '<br />'; echo 'PEAK: ' . xdebug_peak_memory_usage() . '<br />'; echo 'RUN TIME: ' . $run_time . '<br />'; }
/** * Display debug info gathered along the execution * * @return void */ public static function showDebugInfo() { global $Language; echo '<div id="footer_debug_separator"/>'; echo '<div id="footer_debug">'; echo '<div class="alert alert-info"> <h4> Development useful information! </h4> The section above will show you some useful information about Tuleap for development purpose. </div>'; echo '<div id="footer_debug_content">'; $debug_compute_tile = microtime(true) - $GLOBALS['debug_time_start']; if (function_exists('xdebug_time_index')) { $xdebug_time_index = xdebug_time_index(); } $query_time = 0; foreach ($GLOBALS['DBSTORE'] as $d) { foreach ($d['trace'] as $trace) { $query_time += $trace[2] - $trace[1]; } } $purifier = Codendi_HTMLPurifier::instance(); echo '<span class="debug">' . $Language->getText('include_layout', 'query_count') . ": "; echo $GLOBALS['DEBUG_DAO_QUERY_COUNT'] . "</span>"; $percent = (int) ($GLOBALS['DEBUG_TIME_IN_PRE'] * 100 / $debug_compute_tile); $sql_percent = (int) ($query_time * 100 / $debug_compute_tile); echo '<table border=1><thead><tr><th></th><th>Page generated in</th></tr></thead><tbody>'; echo '<tr><td>pre.php</td><td>' . number_format(1000 * $GLOBALS['DEBUG_TIME_IN_PRE'], 0, '.', "'") . ' ms (' . $percent . '%)</td>'; echo '<tr><td>remaining</td><td>' . number_format(1000 * ($debug_compute_tile - $GLOBALS['DEBUG_TIME_IN_PRE']), 0, '.', "'") . ' ms</td>'; echo '<tr><td><b>total</td><td><b>' . number_format(1000 * $debug_compute_tile, 0, '.', "'") . ' ms</td>'; if (function_exists('xdebug_time_index')) { echo '<tr><td>xdebug</td><td>' . number_format(1000 * $xdebug_time_index, 0, '.', "'") . ' ms</tr>'; } echo '<tr><td>sql</td><td>' . number_format(1000 * $query_time, 0, '.', "'") . ' ms (' . $sql_percent . '%)</tr>'; echo '</tbody></table>'; if (function_exists('xdebug_get_profiler_filename')) { if ($file = xdebug_get_profiler_filename()) { echo '<div>Profiler info has been written in: ' . $file . '</div>'; } } $hook_params = array(); EventManager::instance()->processEvent('layout_footer_debug', $hook_params); //Display the config // Uncomment this only if you know what you are doing. This may lead to sensitive information leakage /!\ //echo '<fieldset><legend id="footer_debug_config" class="'. Toggler::getClassname('footer_debug_config') .'">Config:</legend>'; //echo '<pre>'; //Config::dump(); //echo '</pre>'; //echo '</fieldset>'; // Display all queries used to generate the page echo '<fieldset><legend id="footer_debug_allqueries" class="' . Toggler::getClassname('footer_debug_allqueries') . '">All queries:</legend>'; echo '<pre>'; $queries = array(); $queries_by_time_taken = array(); $i = 0; foreach ($GLOBALS['QUERIES'] as $sql) { $t = 0; foreach ($GLOBALS['DBSTORE'][md5($sql)]['trace'] as $trace) { $t += $trace[2] - $trace[1]; } $q = array('sql' => $purifier->purify($sql), 'total time' => number_format(1000 * $t, 0, '.', "'") . ' ms'); $queries[] = $q; $queries_by_time_taken[] = array('n°' => $i++, 't' => $t) + $q; } print_r($queries); echo '</pre>'; echo '</fieldset>'; // Display all queries used to generate the page ordered by time taken usort($queries_by_time_taken, array(__CLASS__, 'sort_queries_by_time_taken')); echo '<fieldset><legend id="footer_debug_allqueries_time_taken" class="' . Toggler::getClassname('footer_debug_allqueries_time_taken') . '">All queries by time taken:</legend>'; echo '<table border="1" style="border-collapse:collapse" cellpadding="2" cellspacing="0">'; echo '<thead><tr><th>n°</th><th style="white-space:nowrap;">time taken</th><th>sum</th><th>sql</th></tr></thead>'; $i = 0; $sum = 0; foreach ($queries_by_time_taken as $q) { echo '<tr valign="top" class="' . html_get_alt_row_color($i++) . '">'; echo '<td>' . $q['n°'] . '</td>'; echo '<td style="white-space:nowrap;">' . $q['total time'] . '</td>'; echo '<td style="white-space:nowrap;">' . number_format(1000 * ($sum += $q['t']), 0, '.', "'") . ' ms' . '</td>'; echo '<td><pre>' . $q['sql'] . '</pre></td>'; echo '</tr>'; } echo '</table>'; echo '</fieldset>'; echo '<fieldset><legend id="footer_debug_queriespaths" class="' . Toggler::getClassname('footer_dubug_queriespaths') . '">Path of all queries:</legend>'; $max = 0; foreach ($GLOBALS['DBSTORE'] as $d) { foreach ($d['trace'] as $trace) { $time_taken = 1000 * round($trace[2] - $trace[1], 3); if ($max < $time_taken) { $max = $time_taken; } } } $paths = array(); $time = $GLOBALS['debug_time_start']; foreach ($GLOBALS['DBSTORE'] as $d) { foreach ($d['trace'] as $trace) { $time_taken = 1000 * round($trace[2] - $trace[1], 3); self::_debug_backtrace_rec($paths, array_reverse($trace[0]), '[' . 1000 * round($trace[1] - $GLOBALS['debug_time_start'], 3) . '/' . $time_taken . '] ' . ($time_taken >= $max ? ' <span style="background:yellow; padding-left:4px; padding-right:4px; color:red;">top!</span> ' : '') . $purifier->purify($d['sql'])); } } echo '<table>'; self::_debug_display_paths($paths, false); echo '</table>'; echo '</fieldset>'; //Print the backtrace of specific queries /* echo '<pre>'; $specific_queries = array(48,49); $i = 0; foreach($GLOBALS['DBSTORE'] as $d) { //echo $i ."\t". $d['sql'] ."\n"; if (in_array($i++, $specific_queries)) { $traces = $d['trace'][0]; foreach($traces as $trace) { echo '<code>'. $trace['file']. ' #'. $trace['line'] .' ('. (isset($trace['class']) ? $trace['class'] .'::' : '') . $trace['function'] ."</code>\n"; } echo "\n"; } } echo '</pre>'; /**/ // Display queries executed more than once $title_displayed = false; foreach ($GLOBALS['DBSTORE'] as $key => $value) { if ($GLOBALS['DBSTORE'][$key]['nb'] > 1) { if (!$title_displayed) { echo '<fieldset><legend>Queries executed more than once :</legend>'; $title_displayed = true; } echo "<fieldset>"; echo '<legend id="footer_debug_doublequery_' . $key . '" class="' . Toggler::getClassname('footer_debug_doublequery_' . $key) . '">'; echo '<b>Run ' . $GLOBALS['DBSTORE'][$key]['nb'] . " times: </b>"; echo $purifier->purify($GLOBALS['DBSTORE'][$key]['sql']) . "\n"; echo '</legend>'; self::_debug_backtraces($GLOBALS['DBSTORE'][$key]['trace']); echo "</fieldset>"; } } if ($title_displayed) { echo '</fieldset>'; } echo '<fieldset>'; echo '<legend id="footer_debug_session" class="' . Toggler::getClassname('footer_debug_session') . '">Session</legend>'; echo "<div>"; echo '<a href="#" onclick="new Ajax.Updater(\'footer_debug_session_data\', \'/include/debug_session.php?reload\');return false;">reload</a>'; echo ' | '; echo '<a href="#" onclick="new Ajax.Updater(\'footer_debug_session_data\', \'/include/debug_session.php?reset\');return false;">reset</a>'; echo '<pre id="footer_debug_session_data">' . print_r($_SESSION, 1) . '</pre>'; echo "</div>"; echo '</fieldset>'; echo "</pre>\n"; echo '</div>'; echo '</div>'; }
echo 'End usage : ' . cConvertMem($memNow) . '<br/>'; echo 'Mem usage : ' . cConvertMem($memNow - $mem) . '<br/>'; echo 'Peak mem : ' . cConvertMem(xdebug_peak_memory_usage()) . '<br/>'; echo 'Time : ' . (xdebug_time_index() - $tm) . '<br/>'; echo 'Query : ' . $db->getTicker(); echo '</pre>'; // Log average page load jimport('joomla.filesystem.file'); $content = JFile::read(COMMUNITY_COM_PATH . DS . 'access.log'); $params = new JParameter($content); $today = strftime('%Y-%m-%d'); $loadTime = $params->get($today, 0); if ($loadTime > 0) { $loadTime = ($loadTime + (xdebug_time_index() - $tm)) / 2; } else { $loadTime = xdebug_time_index() - $tm; } $params->set($today, $loadTime); JFile::write(COMMUNITY_COM_PATH . DS . 'access.log', $params->toString()); } echo getJomSocialPoweredByLink(); // getTriggerCount // $appLib = CAppPlugins::getInstance(); // echo 'Trigger count: '. $appLib->triggerCount . '<br/>'; // $time_end = microtime(true); // $time = $time_end - $time_start; // echo $time; } /** * Entry poitn for all ajax call */
/** * Print common footer : * conf->global->MAIN_HTML_FOOTER * conf->global->MAIN_GOOGLE_AN_ID * DOL_TUNING * conf->logbuffer * * @param string $zone 'private' (for private pages) or 'public' (for public pages) * @return void */ function printCommonFooter($zone = 'private') { global $conf; global $micro_start_time; if ($zone == 'private') { print "\n" . '<!-- Common footer for private page -->' . "\n"; } else { print "\n" . '<!-- Common footer for public page -->' . "\n"; } if (!empty($conf->global->MAIN_HTML_FOOTER)) { print $conf->global->MAIN_HTML_FOOTER . "\n"; } // Google Analytics (need Google module) if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) { if (empty($conf->dol_use_jmobile)) { print "\n"; print '<script type="text/javascript">' . "\n"; print ' var _gaq = _gaq || [];' . "\n"; print ' _gaq.push([\'_setAccount\', \'' . $conf->global->MAIN_GOOGLE_AN_ID . '\']);' . "\n"; print ' _gaq.push([\'_trackPageview\']);' . "\n"; print '' . "\n"; print ' (function() {' . "\n"; print ' var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;' . "\n"; print ' ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';' . "\n"; print ' var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);' . "\n"; print ' })();' . "\n"; print '</script>' . "\n"; } } // End of tuning if (!empty($_SERVER['DOL_TUNING']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) { print "\n" . '<script type="text/javascript">' . "\n"; print 'window.console && console.log("'; if (!empty($conf->global->MEMCACHED_SERVER)) { print 'MEMCACHED_SERVER=' . $conf->global->MEMCACHED_SERVER . ' - '; } print 'MAIN_OPTIMIZE_SPEED=' . (isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off'); if ($micro_start_time) { $micro_end_time = dol_microtime_float(true); print ' - Build time: ' . ceil(1000 * ($micro_end_time - $micro_start_time)) . ' ms'; } if (function_exists("memory_get_usage")) { print ' - Mem: ' . memory_get_usage(); } if (function_exists("xdebug_memory_usage")) { print ' - XDebug time: ' . ceil(1000 * xdebug_time_index()) . ' ms'; print ' - XDebug mem: ' . xdebug_memory_usage(); print ' - XDebug mem peak: ' . xdebug_peak_memory_usage(); } if (function_exists("zend_loader_file_encoded")) { print ' - Zend encoded file: ' . (zend_loader_file_encoded() ? 'yes' : 'no'); } print '");' . "\n"; print '</script>' . "\n"; // Add Xdebug coverage of code if (defined('XDEBUGCOVERAGE')) { var_dump(xdebug_get_code_coverage()); } } // If there is some logs in buffer to show if (count($conf->logbuffer)) { print "\n"; print "<!-- Start of log output\n"; //print '<div class="hidden">'."\n"; foreach ($conf->logbuffer as $logline) { print $logline . "<br>\n"; } //print '</div>'."\n"; print "End of log output -->\n"; } }
<?php $before = xdebug_time_index(); for ($i = 0; $i < 250000; $i++) { } $after = xdebug_time_index(); var_dump($before); var_dump($after); var_dump($after - $before >= 0);
/** * Prepare template for render from View * * @throws \Exception if template path is incorrect */ public function output() { $template = $this->template; $data = $this->data; $css = $this->css; $js = $this->js; $title = $this->title; ob_start(); try { if (!file_exists(APP . "Templates/_pages/{$template}.html")) { throw new \Exception("The required Template ({$template}) not exist."); } require APP . 'Templates/_shared/header.html'; require APP . "Templates/_pages/{$template}.html"; require APP . 'Templates/_shared/footer.html'; } catch (\Exception $e) { echo 'Template exception: ', $e->getMessage(), "\n"; } //only for debug, return time execution and memory usage echo '<!-- Memory: '; echo round(xdebug_memory_usage() / 1024, 2), ' ('; echo round(xdebug_peak_memory_usage() / 1024, 2), ') KByte - Time: '; echo xdebug_time_index(); echo ' Seconds -->'; ob_end_flush(); }
function xdebug_profiler_shutdown_cb() { $is_xmlhttprequest = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'; if (isset($_REQUEST['XDEBUG_PROFILE'])) { $used_memory = xdebug_memory_usage(); $sizename = array(" Bytes", " KB", " MB", " GB"); $used_memory = round($used_memory / pow(1024, $i = floor(log($used_memory, 1024))), 2) . $sizename[$i]; $elapsed_time = round(xdebug_time_index() * 1000, 3); $profile = xdebug_get_profiler_filename(); $profile_id = md5($profile); /* Show result box */ if (!$is_xmlhttprequest) { if ($profile === false) { $path = ini_get('xdebug.profiler_output_dir'); if ($path != '') { $reason = is_dir($path) ? 'Directory is not writeable' : (file_exists($path) ? "'{$path}' is not directory" : "'{$path}' does not exist"); $output = sprintf('Error: Could not create profile dump in %s<br />(Reason: %s)', $path, $reason); } else { $output = 'Error: xdebug.profiler_output_dir is not set'; } } else { $output = "\n<b>Page generated in</b> {$elapsed_time} ms <b>Used memory:</b> {$used_memory}\n<b>Profiler dump:</b> <a href='/download.php?file={$profile}'>{$profile}</a>\n"; if ($_REQUEST['XDEBUG_PROFILE'] == 'long') { $output .= shell_exec("/usr/bin/callgrind_annotate --inclusive=yes --tree=both {$profile}"); } } echo <<<DATA <div style="position: absolute; top: 0; z-index: 5000; border: dashed black 1px; background-color: #fff;" id="xdebug_profile_{$profile_id}"> <a href="#" style="font-size: 11px;" onclick="javascript: document.getElementById('xdebug_profile_{$profile_id}').style.display = 'none'; return false;">[close]</a> <pre style="padding: 5px;">{$output}</pre> <a href="#" style="font-size: 11px;" onclick="javascript: document.getElementById('xdebug_profile_{$profile_id}').style.display = 'none'; return false;">[close]</a> </div> DATA; } } /* Output box with toggles to enable/disable profiler and annotation */ if (!$is_xmlhttprequest) { $profiler = isset($_REQUEST['XDEBUG_PROFILE']) ? array('enabled' => 1, 'checked' => 'checked="checked"', 'display' => 'inline') : array('enabled' => 0, 'checked' => '', 'display' => 'none'); $profiler['checked_annotate'] = isset($_REQUEST['XDEBUG_PROFILE']) && $_REQUEST['XDEBUG_PROFILE'] == 'long' ? 'checked="checked"' : ''; echo <<<DATA <!-- XDEBUG Dynamic Profiler --> <script type="text/javascript"> <!-- var xdebug_Profiler = {$profiler['enabled']}; function xdebug_setCookie(value) { if (value == '') document.cookie = "XDEBUG_PROFILE=; path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT"; else document.cookie = "XDEBUG_PROFILE=" + value + "; path=/; expires=Fri, 01-Jan-2038 00:00:01 GMT"; } function xdebug_toggleProfiler(output) { var annotate = document.getElementById('xdebug_profiler_annotate'); if (xdebug_Profiler) { xdebug_setCookie(''); xdebug_Profiler = 0; annotate.style.display = 'none'; } else { xdebug_setCookie(output); xdebug_Profiler = 1; annotate.style.display = 'inline'; } return xdebug_Profiler; } // --> </script> <div style="padding: 5px; border: dashed black 1px; background-color: #fff; z-index: 1000; position: absolute; top: 0px; right: 5px; " id="xdebug_profile_enable_cookie"> <label for="xdebug_toggler" style="vertical-align: top">Toggle Profiler</label> <input id="xdebug_toggler" type="checkbox" onclick="this.checked = xdebug_toggleProfiler(this.value);" value="short" {$profiler['checked']} /> <div id="xdebug_profiler_annotate" style="display: {$profiler['display']}"> <label for="xdebug_annotate" style="vertical-align: top">Annotate</label> <input id="xdebug_annotate" type="checkbox" onclick="xdebug_setCookie((this.checked)?this.value:'short');" value="long" {$profiler['checked_annotate']} /> </div> </div> DATA; } }
function llxFooter($foot = '') { global $conf, $langs, $dolibarr_auto_user, $micro_start_time; // Core error message if (defined("MAIN_CORE_ERROR") && constant("MAIN_CORE_ERROR") == 1) { // Ajax version if ($conf->use_javascript_ajax) { $title = img_warning() . ' ' . $langs->trans('CoreErrorTitle'); print ajax_dialog($title, $langs->trans('CoreErrorMessage')); } else { $msg = img_warning() . ' ' . $langs->trans('CoreErrorMessage'); print '<div class="error">' . $msg . '</div>'; } define("MAIN_CORE_ERROR", 0); } print "\n\n"; if (preg_match('/^smartphone/', $conf->smart_menu) && isset($conf->browser->phone)) { print '</div> <!-- end div data-role="content" -->' . "\n"; print '</div> <!-- end div data-role="page" -->' . "\n"; } print '</div> <!-- end div class="fiche" -->' . "\n"; print "\n" . '</td></tr></table> <!-- end right area -->' . "\n"; if ($conf->use_javascript_ajax && !empty($conf->global->MAIN_MENU_USE_JQUERY_LAYOUT)) { print '</div></div> <!-- end main layout -->' . "\n"; } print "\n"; if ($foot) { print '<!-- ' . $foot . ' -->' . "\n"; } if (!empty($conf->global->MAIN_HTML_FOOTER)) { print $conf->global->MAIN_HTML_FOOTER . "\n"; } // If there is some logs in buffer to show if (sizeof($conf->logbuffer)) { print "\n"; print "<!-- Start of log output\n"; //print '<div class="hidden">'."\n"; foreach ($conf->logbuffer as $logline) { print $logline . "<br>\n"; } //print '</div>'."\n"; print "End of log output -->\n"; } // End of tuning if (!empty($_SERVER['DOL_TUNING'])) { $micro_end_time = dol_microtime_float(true); print "\n" . '<script type="text/javascript">console.log("'; if (!empty($conf->global->MEMCACHED_SERVER)) { print 'MEMCACHED_SERVER=' . $conf->global->MEMCACHED_SERVER . ' - '; } print 'MAIN_OPTIMIZE_SPEED=' . (isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off'); print ' - Build time: ' . ceil(1000 * ($micro_end_time - $micro_start_time)) . ' ms'; if (function_exists("memory_get_usage")) { print ' - Mem: ' . memory_get_usage(); } if (function_exists("xdebug_memory_usage")) { print ' - XDebug time: ' . ceil(1000 * xdebug_time_index()) . ' ms'; print ' - XDebug mem: ' . xdebug_memory_usage(); print ' - XDebug mem peak: ' . xdebug_peak_memory_usage(); } if (function_exists("zend_loader_file_encoded")) { print ' - Zend encoded file: ' . (zend_loader_file_encoded() ? 'yes' : 'no'); } print '")</script>' . "\n"; // Add Xdebug coverage of code if (defined('XDEBUGCOVERAGE')) { var_dump(xdebug_get_code_coverage()); } } print "</body>\n"; print "</html>\n"; }
/** * Debug output found at the bottom of the site when debug mode is enabled. * * @static * @return mixed Only returns something if the installer is being used and in that case it returns FALSE */ public static function getDetails() { if (defined('PHPFOX_INSTALLER')) { return false; } // SQL $iSqlCount = 0; $fSum = 0.0; $fLimit = 0.05 * 128; $iSqlMemory = 0; $aKeywords = array('SELECT', 'SELECT ', 'FROM', 'FROM ', 'WHERE ', 'UPDATE ', 'OFFSET', ' AS ', 'UNION ALL', 'INNER JOIN ', 'LEFT JOIN ', 'INSERT INTO ', 'SHOW COLUMNS ', 'ON', 'SET', 'USING', 'USE INDEX', 'JOIN ', 'ORDER BY', 'DESC', 'LIMIT', 'DELETE'); $oRequest = Phpfox_Request::instance(); $oFile = Phpfox_File::instance(); $aReplaces = array_map(array('self', '_addKeywordSyntax'), $aKeywords); $sDriver = Phpfox::getParam(array('db', 'driver')); $sSql = ''; $bIsCmd = PHP_SAPI == 'cli' || defined('PHPFOX_IS_AJAX') && PHPFOX_IS_AJAX; if (!isset(self::$_aDebugHistory['sql'])) { self::$_aDebugHistory['sql'] = array(); } // Fresh install, no need to display sql debug if ($sDriver == 'DATABASE_DRIVER') { self::$_aDebugHistory['sql'] = array(); } foreach (self::$_aDebugHistory['sql'] as $aLine) { if (!isset($aLine['sql'])) { continue; } $iSqlCount++; $sExtra = Phpfox_Database::instance()->sqlReport($aLine['sql']); if ($bIsCmd) { $sSql .= "\n ----------------- \n Rows: " . $aLine['rows'] . " Slave: " . ($aLine['slave'] ? 'Yes' : 'No') . " \n " . $aLine['sql'] . " \n\n"; } else { if ($aLine['time'] == '0.0000000') { $aLine['time'] = '0.0000001'; } $sColor = sprintf('%02X', min(255, $fLimit / $aLine['time'])); $aLine['sql'] = str_replace($aKeywords, $aReplaces, htmlspecialchars($aLine['sql'])); $sSql .= '<div class="nDebugInfo"> <span style="background-color: #FF' . $sColor . $sColor . '; color:#000; padding:2px;">' . $aLine['time'] . '</span> | <b>Memory Before:</b> ' . $oFile->filesize($aLine['memory_before']) . ' | <b>Memory After:</b> ' . $oFile->filesize($aLine['memory_after']) . ' | <b>Memory Used:</b> ' . $oFile->filesize($aLine['memory_after'] - $aLine['memory_before']) . ' | <b>Rows:</b> ' . $aLine['rows'] . ' | <b>Slave:</b> ' . ($aLine['slave'] ? 'Yes' : 'No') . ' </div>'; $sSql .= '<div class="nDebugItems">' . self::_parseSQL($aLine['sql']) . '' . $sExtra . '</div>'; } $fSum += $aLine['time']; $iSqlMemory += $aLine['memory_after'] - $aLine['memory_before']; } // General Stats $iTotalTime = sprintf('%0.7f', array_sum(explode(' ', microtime())) - PHPFOX_TIME_START); $iTotalSqlTime = sprintf('%0.7f', $fSum); $sDebugReturn = '<div id="js_main_debug_holder">'; if (!defined('PHPFOX_MEM_END')) { define('PHPFOX_MEM_END', memory_get_usage()); } if (PHPFOX_DEBUG_LEVEL === 1) { $sDebugReturn .= '<div style="font-size:9pt; text-align:center; padding-bottom:50px;">Page generated in ' . round($iTotalTime, 4) . ' seconds with ' . $iSqlCount . ' queries and GZIP ' . (Phpfox::getParam('core.use_gzip') ? 'enabled' : 'disabled') . ' on ' . $_SERVER['SERVER_ADDR'] . '.</div>'; } elseif (PHPFOX_DEBUG_LEVEL === 2 || PHPFOX_DEBUG_LEVEL === 3) { $bSlaveEnabled = Phpfox::getParam(array('db', 'slave')); $aStats = array('Version' => PhpFox::getVersion(), 'Product Code Name' => PhpFox::getCodeName(), '1' => '', 'Total Time' => $iTotalTime, 'PHP General Time' => $iTotalTime - $iTotalSqlTime, 'GZIP' => Phpfox::getParam('core.use_gzip') ? 'enabled' : 'disabled', '2' => '', 'Driver Version' => $sDriver == 'DATABASE_DRIVER' ? 'N/A' : Phpfox_Database::instance()->getServerInfo(), 'SQL Time' => $iTotalSqlTime, 'SQL Queries' => $iSqlCount, 'SQL Memory Usage' => $oFile->filesize($iSqlMemory), 'SQL Slave Enabled' => $bSlaveEnabled ? 'Yes' : 'No', 'SQL Total Slaves' => $bSlaveEnabled ? count(Phpfox::getParam(array('db', 'slave_servers'))) : 'N/A', 'SQL Slave Server' => $bSlaveEnabled ? Phpfox_Database::instance()->sSlaveServer : 'N/A', '3' => '', 'Total Memory Usage' => $oFile->filesize(PHPFOX_MEM_END), 'Total Memory Usage (Including Debug)' => $oFile->filesize(memory_get_usage()), 'Memory Limit' => $oFile->filesize(self::_getUsableMemory()) . ' (' . @ini_get('memory_limit') . ')', '4' => '', 'Load Balancing Enabled' => Phpfox::getParam(array('balancer', 'enabled')) ? 'Yes' : 'No', 'Requests From' => $oRequest->getServer('SERVER_ADDR'), 'Server ID#' => $oRequest->getServer('PHPFOX_SERVER_ID'), '5' => '', 'Server Time Stamp' => date('F j, Y, g:i a', PHPFOX_TIME), 'PHP Version' => PHP_VERSION, 'PHP Sapi' => php_sapi_name(), 'PHP safe_mode' => PHPFOX_SAFE_MODE ? 'true' : 'false', 'PHP open_basedir' => PHPFOX_OPEN_BASE_DIR ? 'true' : 'false', 'Operating System' => PHP_OS, '6' => '', 'Cache' => Phpfox::getParam('core.cache_storage')); if (extension_loaded('xdebug')) { $aXdebug = array('4' => '', 'xDebug File Name' => xdebug_get_profiler_filename(), 'xDebug Total Time' => xdebug_time_index()); $aStats = array_merge($aStats, $aXdebug); } $sDebugStats = ''; foreach ($aStats as $sStatTitle => $mStatValue) { if (!$mStatValue) { $sDebugStats .= $bIsCmd ? "\n" : "<br />"; } else { $sDebugStats .= $bIsCmd ? "" . $sStatTitle . ": " . $mStatValue . "\n" : "<div class=\"nDebugLeft\">" . $sStatTitle . ":</div><div>" . $mStatValue . "</div>\n<div class=\"nClear\"></div>\n"; } } $aCookies = array(); $sCookiePrefix = Phpfox::getParam('core.session_prefix'); $iPrefixLength = strlen($sCookiePrefix); foreach ($_COOKIE as $sKey => $sValue) { if (substr($sKey, 0, $iPrefixLength) != $sCookiePrefix) { continue; } $aCookies[$sKey] = $sValue; } if ($bIsCmd) { $sDebugReturn .= $sDebugStats; $sDebugReturn .= "##############################################"; } else { $sDebugReturn .= ' <div id="n_debug"> <div id="n_debug_header"> phpFox Developers Debug <a href="#" onclick="if (getCookie(\'js_console\')) { deleteCookie(\'js_console\'); $(\'#firebug_no_console\').remove(); } else { setCookie(\'js_console\', \'1\', 365); p(\'Enabled JavaScript Console\'); } return false;">Toggle JavaScript Console</a> </div> <div class="nDebugItem"><a href="#" onclick="if (getCookie(\'phpfox_debug_detail\')) { deleteCookie(\'phpfox_debug_detail\'); $(\'#phpfox_debug_detail\').slideDown(); } else { $(\'#phpfox_debug_detail\').slideUp(); setCookie(\'phpfox_debug_detail\', \'1\', 365); } return false;">Debug Details</a></div> <div class="nDebugContent nDebugContentShell" id="phpfox_debug_detail"' . (Phpfox::getCookie('phpfox_debug_detail') ? ' style="display:none;"' : '') . '> <div class="nDebugContentShell"> ' . $sDebugStats . ' </div> </div> '; } if (PHPFOX_DEBUG_LEVEL === 3) { if ($bIsCmd) { $sDebugReturn .= $sSql; $sDebugReturn .= "##############################################"; } else { $sDebugReturn .= ' <div class="nDebugItem">SQL Queries</div> <div class="nDebugContent nDebugContentShell" style="height:400px;"> ' . $sSql . ' </div> '; } } /* <div class="nDebugItem">Debug History</div> <div class="nDebugContent nDebugContentShell" style="height:200px;"> <pre>'. self::_loadData(self::$_aDebugHistory) .'</pre> </div> */ if (!$bIsCmd) { $sDebugReturn .= ' <div class="nDebugItem"><a href="#" onclick="if (getCookie(\'phpfox_debug_session\')) { deleteCookie(\'phpfox_debug_session\'); $(\'#phpfox_debug_session\').slideDown(); } else { $(\'#phpfox_debug_session\').slideUp(); setCookie(\'phpfox_debug_session\', \'1\', 365); } return false;">Session</a></div> <div class="nDebugContent nDebugContentShell" id="phpfox_debug_session"' . (Phpfox::getCookie('phpfox_debug_session') ? ' style="display:none;"' : '') . '> <pre>' . self::_loadData($_SESSION[Phpfox::getParam('core.session_prefix')]) . '</pre> </div> <div class="nDebugItem"><a href="#" onclick="if (getCookie(\'phpfox_debug_cookie\')) { deleteCookie(\'phpfox_debug_cookie\'); $(\'#phpfox_debug_cookie\').slideDown(); } else { $(\'#phpfox_debug_cookie\').slideUp(); setCookie(\'phpfox_debug_cookie\', \'1\', 365); } return false;">Cookie</a></div> <div class="nDebugContent nDebugContentShell" id="phpfox_debug_cookie"' . (Phpfox::getCookie('phpfox_debug_cookie') ? ' style="display:none;"' : '') . '> <pre>' . self::_loadData($aCookies) . '</pre> </div> </div> '; } } $sDebugReturn .= '</div>'; if (defined('PHPFOX_DEBUG_SHOW_FIXED')) { $sDebugReturn .= '<div style="position:fixed; bottom:0px; right:5px; background:#fff; border:1px #dfdfdf solid; width:200px; padding:5px; font-size:16px;"> Generated in: ' . round($iTotalTime, 4) . ' <br /> SQL: ' . $iSqlCount . ' (' . $iTotalSqlTime . ') <br /> Server: ' . $_SERVER['SERVER_ADDR'] . ' </div>'; } return $sDebugReturn; }
private static function debugInfo() { $global_vars = implode(', ', array_keys($GLOBALS)); $res = '<div id="debug"><div>' . '<p>memory usage: ' . memory_get_usage() . ' (' . files::size(memory_get_usage()) . ')</p>'; if (function_exists('xdebug_get_profiler_filename')) { $res .= '<p>Elapsed time: ' . xdebug_time_index() . ' seconds</p>'; $prof_file = xdebug_get_profiler_filename(); if ($prof_file) { $res .= '<p>Profiler file : ' . xdebug_get_profiler_filename() . '</p>'; } else { $prof_url = http::getSelfURI(); $prof_url .= strpos($prof_url, '?') === false ? '?' : '&'; $prof_url .= 'XDEBUG_PROFILE'; $res .= '<p><a href="' . html::escapeURL($prof_url) . '">Trigger profiler</a></p>'; } /* xdebug configuration: zend_extension = /.../xdebug.so xdebug.auto_trace = On xdebug.trace_format = 0 xdebug.trace_options = 1 xdebug.show_mem_delta = On xdebug.profiler_enable = 0 xdebug.profiler_enable_trigger = 1 xdebug.profiler_output_dir = /tmp xdebug.profiler_append = 0 xdebug.profiler_output_name = timestamp */ } $res .= '<p>Global vars: ' . $global_vars . '</p>' . '</div></div>'; return $res; }
?> </div> <!--Comment Form Submit Button--> <div class="form-group"> <?php echo $this->tag->submitButton(array('添加', 'class' => 'btn btn-primary form-control')); ?> </div> <?php echo $this->tag->endform(); ?> </div> </div> </div> </div> <div class="container"> <div class="row"> <?php echo xdebug_time_index(); ?> </div> </div> </body> </html>
$baseImg = getImageObject(array('width' => 1, 'height' => 1, 'background' => 'none')); $baseImg->addEffect('PhotoStack', array('images' => $imgs, 'resize_height' => 150, 'padding' => 0, 'background' => 'blue', 'type' => 'rounded')); $baseImg->applyEffects(); $baseImg->display(); $time = xdebug_time_index() - $time; $memory = xdebug_peak_memory_usage(); logThis($test, $time, $memory); break; case 'testPolaroidstackTransparentBG': $time = xdebug_time_index(); $imgs = array(getImageObject(array('filename' => 'img1.jpg')), getImageObject(array('filename' => 'img2.jpg')), getImageObject(array('filename' => 'img3.jpg'))); $baseImg = getImageObject(array('width' => 1, 'height' => 1, 'background' => 'none')); $baseImg->addEffect('PhotoStack', array('images' => $imgs, 'resize_height' => 150, 'padding' => 0, 'background' => 'none', 'type' => 'polaroid')); $baseImg->applyEffects(); $baseImg->display(); $time = xdebug_time_index() - $time; $memory = xdebug_peak_memory_usage(); logThis($test, $time, $memory); break; case 'testPolaroidstackBlueBG': $imgs = array(getImageObject(array('filename' => 'img1.jpg')), getImageObject(array('filename' => 'img2.jpg')), getImageObject(array('filename' => 'img3.jpg'))); $baseImg = getImageObject(array('width' => 1, 'height' => 1, 'background' => 'none')); $baseImg->addEffect('PhotoStack', array('images' => $imgs, 'resize_height' => 150, 'padding' => 0, 'background' => 'blue', 'type' => 'polaroid')); $baseImg->applyEffects(); $baseImg->display(); break; } } catch (Exception $e) { $logger->err($e); header('Content-Type: image/png'); readfile('error.png');
static function execute_time() { if (function_exists('xdebug_time_index')) { $ex_time = xdebug_time_index(); } else { $stime = explode(' ', SYS_START_TIME); $etime = explode(' ', microtime()); $ex_time = number_format($etime[1] + $etime[0] - $stime[1] - $stime[0], 6); } return $ex_time; }
var_dump($validator->isValid('TEXU3070079')); echo '<hr />'; echo '<h1>Example of invalid check digit : TEXU3070070</h1>'; // example of invalid container number, will return an empty array $codeSegment = $validator->validate('TEXU3070070'); print_r($codeSegment); var_dump($validator->isValid('TEXU3070070')); // get error messages var_dump($validator->getErrorMessages()); echo '<hr />'; echo '<h1>Example of getting owner code, product group code, registration digit and check digit from valid container number : TEXU3070079</h1>'; // validate() or isValid() must be called before getting segmentCode if ($validator->isValid('TEXU3070079')) { echo 'Owner code: ' . implode('', $validator->getOwnerCode()) . '<br />'; echo 'Product group code: ' . $validator->getProductGroupCode() . '<br />'; echo 'Registration digit: ' . implode('', $validator->getRegistrationDigit()) . '<br />'; echo 'Check digit: ' . $validator->getCheckDigit() . '<br />'; } echo '<hr />'; echo '<h1>Example of creating check digit from container number without check digit: TEXU307007</h1>'; echo $validator->createCheckDigit('TEXU307007'); echo '<hr />'; echo '<h1>Example of generating container number from 1 to 100</h1>'; $start = xdebug_time_index(); // parameters are (left to right): owner code, product group code, number from, number to var_dump($validator->generate('TEX', 'U', 1, 100)); $end = xdebug_time_index(); echo "\n Time to generate: " . ($end - $start) . " s"; echo '<hr />'; $end_all = xdebug_time_index(); echo "\n <h1>Time of all example: " . ($end_all - $start_all) . " s</h1>";
/** * Rendering function on Shutdown of XDEBUG. */ public static function render() { // Start XDEBUG Tracing and Coverage if (self::isXdebugActive()) { /* * This is the CSS for XDebug Fatal Error */ echo '<!-- Disable XDebug Mode to remove this!--> <style type="text/css"> /*<![CDATA[*/ table.xdebug-error { font-size: 12px; width: 95%; margin: 0 auto 10px auto; border-color: #666; border-collapse: collapse; border-style: outset; color: #222222; } .xdebug-error th { background: none repeat scroll 0 0 #E03937; border: 1px inset #BF0000; font-weight: bold; padding: 3px; font-size: 16px; } .xdebug-error td { background: none repeat scroll 0 0 #FFFFCC; border: 1px solid grey; padding: 2px 2px 2px 5px; vertical-align: top; } .xdebug-error tr:hover td { background: #ffff88; } .xdebug-error span { display: none; } /** Custom Styles not related to XDEBUG **/ .toggle { font-size: 12px; color: white; float: left; } /*]]>*/ </style>'; /* * Reset for hardcoded bgcolor attributes in the "xdebug-error" table. * This will select all <td> elements and reset the bgcolor attribute on each element. */ echo "<script type=\"text/javascript\">\n var xdebugErrorTable = document.getElementsByClassName('xdebug-error');\n if (xdebugErrorTable.length > 0) {\n var xdebugErrorTableTds =\n document.getElementsByClassName('xdebug-error')[0].getElementsByTagName('td');\n for (var i = 0; i < xdebugErrorTableTds.length; i++) {\n xdebugErrorTableTds[i].setAttribute('bgcolor', '');\n }\n }"; /* * Visibility Toggle + Toggle Text Change */ echo 'function toggleXDebugTable(a) {document.getElementById(a).style.display=="none" ?(document.getElementById(a).style.display="table", document.getElementById("toggle-icon-"+a).innerHTML="▼") :(document.getElementById(a).style.display="none", document.getElementById("toggle-icon-"+a).innerHTML="►")};'; echo '</script>'; /* * This is the CSS for XDebug Console via xdebug_dump_superglobals() */ echo '<!-- Disable XDebug Mode to remove this!--> <style type="text/css"> /*<![CDATA[*/ /* center outer div */ #x-debug { width: 95%; padding:20px 0px 10px 0px; background: #EFEFEF; border: 1px solid #333; margin: 0 auto; /* centering */ margin-top: 15px; margin-bottom: 15px; } table.xdebug-console, table.xdebug-superglobals { width: 100%; background: none repeat scroll 0 0 #FFFFCC; border-width: 1px; border-style: outset; border-color: #BF0000; border-collapse: collapse; color: #222; font: 12px tahoma,verdana,arial,sans-serif; margin-top: 5px; margin-bottom: 8px; } table.xdebug-console th, table.xdebug-superglobals th { border: 1px inset #BF0000; padding: 3px; padding-bottom: 3px; font-weight: bold; background: #E03937; text-align: left; } .xdebug-superglobals td { border: 1px solid grey; padding: 2px; padding-left: 5px; vertical-align:top; } table.xdebug-console td { border: 1px inset grey; padding: 2px; padding-left: 5px; } table.xdebug-console td.td1 {width: 30%; padding-left:20px; color:#FF0000; } table.xdebug-console td.td2 {width: 70%;} table.xdebug-console tr:hover td, table.xdebug-superglobals tr:hover td { background: #ffff88; } fieldset.xdebug-console { background: none repeat scroll 0 0 #ccc; border: 1px solid #666666; font: 12px tahoma,verdana,arial,sans-serif; margin: 35px; padding: 10px; width: 95%; } fieldset.xdebug-console legend { background: #fff; border: 1px solid #333; font-weight: bold; padding: 5px 15px; color: #222; float: left; margin-top: -23px; margin-bottom: 10px; } fieldset.xdebug-console pre { margin: 2px; text-align: left; width: 100%; } /*]]>*/ </style> <!--[if IE]> <style type="text/css"> fieldset.xdebug-console legend { position:relative; top: -0.2em; } </style> <![endif]-->'; echo '<fieldset class="xdebug-console"><legend>XDebug Console</legend>'; echo xdebug_dump_superglobals(); echo '<table class="xdebug-console">'; echo '<tr><th>Name</th><th>Value</th></tr>'; echo '<tr>'; echo '<td class="td1">Time to execute</td>'; echo '<td class="td2">' . round(xdebug_time_index(), 4) . ' seconds</td>'; echo '</tr><tr>'; echo '<td class="td1">Memory Usage (before)</td>'; echo '<td class="td2">' . self::$xdebug_memory_before . ' MB</td>'; echo '</tr><tr>'; echo '<td class="td1">Memory Usage by ' . APPLICATION_NAME . ' </td>'; echo '<td class="td2">' . self::roundMB(xdebug_memory_usage()) . ' MB</td>'; echo '</tr><tr>'; echo '<td class="td1">Memory Peak</td>'; echo '<td class="td2">' . self::roundMB(xdebug_peak_memory_usage()) . ' MB</td>'; echo '</tr>'; // stop tracings and var_dump #var_dump(xdebug_get_code_coverage()); echo '</table>'; self::showConstants(); #self::showBrowserInfo(); self::showHttpHeaders(); echo '</table>'; echo '</fieldset>'; /* * Reset for hardcoded bgcolor attributes in the "xdebug-superglobals" table. * This will select all <td> elements and reset the bgcolor attribute on each element. */ echo "<script type=\"text/javascript\">\n var xdebugTds = document.getElementsByClassName('xdebug-superglobals')[0].getElementsByTagName('td');\n for (var i = 0; i < xdebugTds.length; i++) {xdebugTds[i].setAttribute('bgcolor', '');}\n xdebugTds[0].setAttribute('width', '30%');\n </script>"; } }
public static function easybug() { self::$var['bug']['runsql'] = 0; if (!self::$var['ajax'] && function_exists('xdebug_time_index')) { self::$var['bug']['runsec'] = function_exists('xdebug_time_index') ? number_format(xdebug_time_index(), 6) : number_format(dmicrotime() - RUNFIRSTTIME, 6); $html = '<p>' . self::$var['bug']['runsec'] . 's, runsize: ' . xdebug_memory_usage() . 'Kb, runavgsize: ' . xdebug_peak_memory_usage() . 'Kb, runsql:' . var_export(self::$var['bug']['runsql'], true) . '</p>'; echo $html; } else { self::$var['bug']['runsec'] = number_format(dmicrotime() - self::$var['starttime'], 6); self::$var['bug']['runmemory'] = intval(return_bytes(memory_get_usage() / (1024 * 1024) . 'k')); self::$var['bug']['runsql'] = Factory_Db::countSqlNum(); } }
$stk2 = new stack2(); echo $stk2->c(); } function b() { var_dump(xdebug_get_function_stack()); // Displays the function's call flow or stack. } } class stack2 { function c() { $stk = new stack(); //Call to class "Stack" echo $stk->b(); } } $a = ''; $stk = new stack(); $res = $stk->a($a); xdebug_print_function_stack('Your Message'); //To Print "Your Message" text in a message. /* Used to Findout the time taken to execute code. */ echo '<br><br>' . xdebug_time_index() . '<br>'; //Display the start time. for ($i = 0; $i < 100; $i++) { // anything. } echo xdebug_time_index() . '<br><br>'; //Display the end time.
/** * @param string $entity * type of entities to deal with * @param string $action * create, get, delete or some special action name. * @param array $params * array to be passed to function * @param null $extra * * @return array|int */ function civicrm_api($entity, $action, $params, $extra = NULL) { $apiRequest = array(); $apiRequest['entity'] = CRM_Utils_String::munge($entity); $apiRequest['action'] = CRM_Utils_String::munge($action); $apiRequest['version'] = civicrm_get_api_version($params); $apiRequest['params'] = $params; $apiRequest['extra'] = $extra; $apiWrappers = array(CRM_Utils_API_HTMLInputCoder::singleton(), CRM_Utils_API_NullOutputCoder::singleton(), CRM_Utils_API_ReloadOption::singleton(), CRM_Utils_API_MatchOption::singleton()); CRM_Utils_Hook::apiWrappers($apiWrappers, $apiRequest); try { require_once 'api/v3/utils.php'; require_once 'api/Exception.php'; if (!is_array($params)) { throw new API_Exception('Input variable `params` is not an array', 2000); } _civicrm_api3_initialize(); $errorScope = CRM_Core_TemporaryErrorScope::useException(); // look up function, file, is_generic $apiRequest += _civicrm_api_resolve($apiRequest); if (strtolower($action) == 'create' || strtolower($action) == 'delete' || strtolower($action) == 'submit') { $apiRequest['is_transactional'] = 1; $transaction = new CRM_Core_Transaction(); } // support multi-lingual requests if ($language = CRM_Utils_Array::value('option.language', $params)) { _civicrm_api_set_locale($language); } _civicrm_api3_api_check_permission($apiRequest['entity'], $apiRequest['action'], $apiRequest['params']); $fields = _civicrm_api3_api_getfields($apiRequest); // we do this before we _civicrm_api3_swap_out_aliases($apiRequest, $fields); if (strtolower($action) != 'getfields') { if (empty($apiRequest['params']['id'])) { $apiRequest['params'] = array_merge(_civicrm_api3_getdefaults($apiRequest, $fields), $apiRequest['params']); } //if 'id' is set then only 'version' will be checked but should still be checked for consistency civicrm_api3_verify_mandatory($apiRequest['params'], NULL, _civicrm_api3_getrequired($apiRequest, $fields)); } // For input filtering, process $apiWrappers in forward order foreach ($apiWrappers as $apiWrapper) { $apiRequest = $apiWrapper->fromApiInput($apiRequest); } $function = $apiRequest['function']; if ($apiRequest['function'] && $apiRequest['is_generic']) { // Unlike normal API implementations, generic implementations require explicit // knowledge of the entity and action (as well as $params). Bundle up these bits // into a convenient data structure. $result = $function($apiRequest); } elseif ($apiRequest['function'] && !$apiRequest['is_generic']) { _civicrm_api3_validate_fields($apiRequest['entity'], $apiRequest['action'], $apiRequest['params'], $fields); $result = isset($extra) ? $function($apiRequest['params'], $extra) : $function($apiRequest['params']); } else { return civicrm_api3_create_error("API (" . $apiRequest['entity'] . ", " . $apiRequest['action'] . ") does not exist (join the API team and implement it!)"); } // For output filtering, process $apiWrappers in reverse order foreach (array_reverse($apiWrappers) as $apiWrapper) { $result = $apiWrapper->toApiOutput($apiRequest, $result); } if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) { if ($result['is_error'] === 0) { return 1; } else { return 0; } } if (!empty($apiRequest['params']['format.only_id']) && isset($result['id'])) { return $result['id']; } if (CRM_Utils_Array::value('is_error', $result, 0) == 0) { _civicrm_api_call_nested_api($apiRequest['params'], $result, $apiRequest['action'], $apiRequest['entity'], $apiRequest['version']); } if (function_exists('xdebug_time_index') && CRM_Utils_Array::value('debug', $apiRequest['params']) && is_array($result)) { $result['xdebug']['peakMemory'] = xdebug_peak_memory_usage(); $result['xdebug']['memory'] = xdebug_memory_usage(); $result['xdebug']['timeIndex'] = xdebug_time_index(); } return $result; } catch (PEAR_Exception $e) { if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) { return 0; } $error = $e->getCause(); if ($error instanceof DB_Error) { $data["error_code"] = DB::errorMessage($error->getCode()); $data["sql"] = $error->getDebugInfo(); } if (!empty($apiRequest['params']['debug'])) { if (method_exists($e, 'getUserInfo')) { $data['debug_info'] = $error->getUserInfo(); } if (method_exists($e, 'getExtraData')) { $data['debug_info'] = $data + $error->getExtraData(); } $data['trace'] = $e->getTraceAsString(); } else { $data['tip'] = "add debug=1 to your API call to have more info about the error"; } $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest); if (!empty($apiRequest['is_transactional'])) { $transaction->rollback(); } return $err; } catch (API_Exception $e) { if (!isset($apiRequest)) { $apiRequest = array(); } if (CRM_Utils_Array::value('format.is_success', CRM_Utils_Array::value('params', $apiRequest)) == 1) { return 0; } $data = $e->getExtraParams(); $data['entity'] = CRM_Utils_Array::value('entity', $apiRequest); $data['action'] = CRM_Utils_Array::value('action', $apiRequest); $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode()); if (CRM_Utils_Array::value('debug', CRM_Utils_Array::value('params', $apiRequest)) && empty($data['trace'])) { $err['trace'] = $e->getTraceAsString(); } if (!empty($apiRequest['is_transactional'])) { $transaction->rollback(); } return $err; } catch (Exception $e) { if (CRM_Utils_Array::value('format.is_success', $apiRequest['params']) == 1) { return 0; } $data = array(); $err = civicrm_api3_create_error($e->getMessage(), $data, $apiRequest, $e->getCode()); if (!empty($apiRequest['params']['debug'])) { $err['trace'] = $e->getTraceAsString(); } if (!empty($apiRequest['is_transactional'])) { $transaction->rollback(); } return $err; } }
/** * Log a message * * @param string $message The message to be logged * @param int $loglevel The log level */ function log($message, $loglevel = MIDCOM_LOG_DEBUG) { if (!$this->_enabled || $this->_loglevel < $loglevel) { return; } $file = fopen($this->_filename, 'a+'); if (function_exists('xdebug_memory_usage')) { static $lastmem = 0; $curmem = xdebug_memory_usage(); $delta = $curmem - $lastmem; $lastmem = $curmem; $prefix = sprintf("%s (%012.9f, %9s, %7s):\t", date('M d Y H:i:s'), xdebug_time_index(), number_format($curmem, 0, ',', '.'), number_format($delta, 0, ',', '.')); } else { $prefix = date('M d Y H:i:s') . "\t"; } if (array_key_exists($loglevel, $this->_loglevels)) { $prefix .= '[' . $this->_loglevels[$loglevel] . '] '; } //find the proper caller $bt = debug_backtrace(false); $prefix .= $this->_get_caller($bt); fputs($file, $prefix . trim($message) . "\n"); fclose($file); if ($this->firephp && !_midcom_headers_sent()) { try { $log_method = $this->_loglevels[$loglevel]; if ($loglevel == MIDCOM_LOG_DEBUG) { $log_method = 'log'; } if ($loglevel == MIDCOM_LOG_CRIT) { $log_method = 'error'; } $this->firephp->{$log_method}($message); } catch (Exception $e) { // Ignore FirePHP errors for now } } }
/** * Send HTTP response body and create performance.log * */ public function reply($data) { $this->response->sendHeader(); echo $data; if (function_exists("xdebug_time_index")) { $filename = 'app/log/performance.log'; $time = $this->getRequestURI() . " took " . round(xdebug_time_index(), 5) . " seconds\n"; $time .= "Used " . round(xdebug_memory_usage() / 1024, 5) . "Kb of Memory\n"; $time .= "Used at peak " . round(xdebug_peak_memory_usage() / 1024, 5) . "Kb of Memory\n"; if (is_writeable($filename)) { file_put_contents($filename, $time); } } }