/** * Launches a test module for web inspection of results * @param string $module * @return boolean */ function WebLauncher($module) { jf::$ErrorHandler->UnsetErrorHandler(); $this->LoadFramework(); self::$TestSuite = new \PHPUnit_Framework_TestSuite(); self::$TestFiles[] = $this->ModuleFile($module); self::$TestSuite->addTestFile(self::$TestFiles[0]); $result = new \PHPUnit_Framework_TestResult(); $listener = new TestListener(); $result->addListener($listener); $Profiler = new Profiler(); if (function_exists("xdebug_start_code_coverage")) { xdebug_start_code_coverage(); } self::$TestSuite->run($result); if (function_exists("xdebug_start_code_coverage")) { $Coverage = xdebug_get_code_coverage(); } else { $Coverage = null; } $Profiler->Stop(); $listener->Finish(); $this->OutputResult($result, $Profiler, $Coverage); return true; }
static function admin_page_bottom($theme) { if (Session::instance()->get("profiler", false)) { $profiler = new Profiler(); $profiler->render(); } }
public function testSqlNumRows() { // Simulate three queries $this->profiler->sqlProfiler("some query"); $this->profiler->sqlProfiler("some query"); $this->profiler->sqlProfiler("some query"); // Do not stop the profilers, jump right to the assertions // How evil! self::assertEquals(3, $this->profiler->getNumQueries()); }
static function admin_page_bottom($theme) { $session = Session::instance(); if ($session->get("profiler", false)) { $profiler = new Profiler(); $profiler->render(); } if ($session->get("l10n_mode", false)) { return L10n_Client_Controller::l10n_form(); } }
/** * @param string $name * @param array $request * @param array $responseKeys * @throws Exception * @return object */ public function execute($name, $request, $responseKeys) { $start = microtime(1); $fce = saprfc_function_discover($this->connection, $name); if (!$fce) { throw new Exception("Error discovering " . $name, 1); } foreach ($request as $k => $v) { if (is_array($v)) { foreach ($v as $index => $row) { if (is_object($row)) { $row = get_object_vars($row); } foreach ($row as $row_key => $row_value) { $row[$row_key] = $this->encodeString($row_value); } saprfc_table_insert($fce, $k, $row, $index + 1); } } else { saprfc_request($fce, $k, $this->encodeString($v)); } } $result = saprfc_call_and_receive($fce); if ($result != SAPRFC_OK) { $message = isset($this->errors[$result]) ? $this->errors[$result] : 'Unknown error'; if ($this->profiler) { $this->profiler->register((object) array('name' => $name, 'request' => $request, 'success' => false, 'message' => $message, 'time' => microtime(1) - $start)); } throw new Exception($message); } $response = array(); foreach ($responseKeys as $table) { $count = saprfc_table_rows($fce, $table); if ($count == -1) { // responseKeys param $data = $this->decodeString(saprfc_export($fce, $table)); } else { // responseKeys table $data = array(); for ($i = 1; $i <= $count; $i++) { $row = saprfc_table_read($fce, $table, $i); foreach ($row as $k => $v) { $row[$k] = $this->decodeString($v); } $data[] = (object) $row; } } $response[$table] = $data; } if ($this->profiler) { $this->profiler->register((object) array('name' => $name, 'request' => (object) $request, 'response' => (object) $response, 'success' => true, 'time' => microtime(1) - $start)); } return (object) $response; }
/** * Run script * */ public function run() { try { $content = $this->_factory->getModel('crawlerModel')->crawl($this->_args); //array of data to render $result = array(); $sortArr = array(); foreach ($content as $key => $data) { $time = $data['time']; Profiler::start($key); $renderData = TagCounterHelper::count($data['content'], 'img'); Profiler::stop($key); $time += Profiler::fetch($key); array_push($result, array($key, (int) $renderData['img'], $time)); array_push($sortArr, $renderData['img']); } array_multisort($sortArr, SORT_DESC, $result); if (!empty($result)) { array_unshift($result, $this->_tableHeaders); } ViewHelper::getRenderer()->process(array('grid' => $result)); } catch (Exception $e) { echo $e->getMessage(); } }
/** * Overload Sprig::delete() to update child articles * to become children of the uncategorized subcategory */ public function delete(Database_Query_Builder_Delete $query = NULL) { Kohana::$log->add(Kohana::DEBUG, 'Beginning subcategory deletion for subcategory_id='.$this->id); if (Kohana::$profiling === TRUE) { $benchmark = Profiler::start('blog', 'delete subcategory'); } $uncategorized = Sprig::factory('subcategory', array('name'=>'uncategorized'))->load(); // Modify category IDs for all child articles try { DB::update('articles')->value('subcategory_id', $uncategorized->id) ->where('subcategory_id', '=', $this->id)->execute(); } catch (Database_Exception $e) { Kohana::$log->add(Kohana::ERROR, 'Exception occured while modifying deleted subcategory\'s articles. '.$e->getMessage()); return $this; } if (isset($benchmark)) { Profiler::stop($benchmark); } return parent::delete($query); }
public function query($type, $sql, $as_object) { if (isset($this->_config['connection']) === true) { $this->database = $this->_config['connection']['database']; } $result = parent::query($type, $sql, false); if ($type === Database::SELECT) { $table = array(); if (count($result) > 0) { foreach ($result->current() as $key => $data) { $table[0][] = $key; } $result->rewind(); foreach ($result as $row) { $table[] = $row; } $result->rewind(); } else { $table[] = array('No', 'rows'); } $group = Profiler::groups(); $group = Profiler::total($group['database (default)'][$sql][0]); FirePHP::getInstance()->table($this->database . ' : (' . number_format($group[0], 6) . 's) ' . $sql, $table); } elseif ($type === Database::INSERT) { FirePHP::getInstance()->info($this->database . ' : Insert id: ' . $result[0] . ' Affected rows: ' . $result[1]); } else { FirePHP::getInstance()->info($this->database . ' : Affected rows: ' . $result[0]); } return $result; }
/** * Returns the translation table for a given language. * * // Get all defined Spanish messages * $messages = I18n::load('es-es'); * * После генерации таблицы происходит создание Javascript файла с таблицей * перевода для загружаемого языка. * * @param string $lang language to load * @return array */ public static function load($lang) { $table = parent::load($lang); $filename = Kohana::$cache_dir . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, array('i18n', NULL)) . $lang . '.js'; if (!file_exists($filename) or file_exists($filename) and time() - filemtime($filename) > Date::DAY) { if (Kohana::$profiling === TRUE and class_exists('Profiler', FALSE)) { // Start a new benchmark $benchmark = Profiler::start('i18n', 'Generate file for lang - ' . $lang); } try { // Create the log file file_put_contents($filename, '// Auto generated i18n lang file for lang ' . $lang . ". Created on " . date('Y-m-d H:i:s') . "\n"); file_put_contents($filename, 'cms.addTranslation(' . json_encode($table) . ');', FILE_APPEND); // Allow anyone to write to log files chmod($filename, 0777); } catch (Exception $e) { // do something } if (isset($benchmark)) { // Stop the benchmark Profiler::stop($benchmark); } } return $table; }
public function __construct($id = NULL) { Kohana::$profiling === TRUE && ($bm = Profiler::start('ORM', __FUNCTION__)); parent::__construct($id); $this->after_initialize(); isset($bm) && Profiler::stop($bm); }
/** * Cache data. * * @return void */ public static function cache() { if (!Profiler::show('cache')) { return; } $queries = Cache::$queries; $table = new Profiler_Table(); $table->add_column(); $table->add_column('kp-column kp-data'); $table->add_column('kp-column kp-data'); $table->add_column('kp-column kp-data'); $table->add_row(array('Cache', 'Gets', 'Sets', 'Deletes'), 'kp-title', 'background-color: #E0FFE0'); text::alternate(); $total_gets = $total_sets = $total_deletes = 0; $total_requests = array(); foreach ($queries as $type => $requests) { foreach ($requests as $query) { if (!isset($total_requests[$query])) { $total_requests[$query] = array('gets' => 0, 'sets' => 0, 'deletes' => 0); } $total_requests[$query][$type]++; } } foreach ($total_requests as $query => $types) { $data = array($query, $types['gets'], $types['sets'], $types['deletes']); $class = text::alternate('', 'kp-altrow'); $table->add_row($data, $class); $total_gets += $types['gets']; $total_sets += $types['sets']; $total_deletes += $types['deletes']; } $data = array('Total: ' . count($total_requests), $total_gets, $total_sets, $total_deletes); $table->add_row($data, 'kp-totalrow'); Profiler::add($table); }
public function stopQuery() { if ($this->benchmark) { \Profiler::stop($this->benchmark); $this->benchmark = null; } }
public static function get_smarty() { if (isset(self::$smarty)) { return self::$smarty; } $token = Kohana::$profiling ? Profiler::start('smarty', 'load smarty') : false; $config = Kohana::config('smarty'); try { include $config->smarty_class_file; } catch (Exception $e) { throw new Kohana_Exception('Could not load Smarty class file'); } $smarty = new Smarty(); // deal with initial config $smarty->php_handling = constant($config->php_handling); // deal with main config foreach ($config->smarty_config as $key => $value) { $smarty->{$key} = $value; } // check we can write to the compiled templates directory if (!is_writeable($smarty->compile_dir)) { self::create_dir($smarty->compile_dir, 'Smarty compiled template'); } // if smarty caching is enabled, check we can write to the cache directory if ($smarty->caching && !is_writeable($smarty->cache_dir)) { self::create_dir($smarty->cache_dir, 'Smarty cache'); } self::$smarty = $smarty; $token ? Profiler::stop($token) : null; return $smarty; }
public function action_change() { //トークンの生成 $this->action_csrf(); //バリデーション定義 $val = Validation::forge(); $val->add('password', '「現在のパスワード」')->add_rule('required')->add_rule('min_length', 8)->add_rule('max_length', 12); $val->add('newpassword', '「新しいパスワード」または、「(新)パスワード再入力」')->add_rule('required')->add_rule('min_length', 8)->add_rule('max_length', 12); $this->action_category(); if (Input::post()) { if (Security::check_token()) { if ($val->run()) { $username = Auth::get_screen_name(); //現在のパスワード $old_password = Input::post('password'); //新しいパスワード $new_password = Input::post('newpassword'); //パスワードを変更するメソッド Auth::change_password($old_password, $new_password, $username); $this->message = 'パスワードが変更されました。'; $view = View::forge('changepass/ChangePass', $this->data); $view->set_global('message', $this->message, false); $view->set_global('error', $this->error, false); } else { $this->error = $val->error(); $view = View::forge('changepass/ChangePass', $this->data); $view->set_global('message', $this->message, false); $view->set_global('error', $this->error, false); } } else { Profiler::mark('CSRF攻撃'); } } return $view; }
/** * Main execution point * * @param null|string $code Confirmation code passed to the page * @throws PermissionsError * @throws ReadOnlyError * @throws UserNotLoggedIn */ function execute($code) { // Ignore things like master queries/connections on GET requests. // It's very convenient to just allow formless link usage. $trxProfiler = Profiler::instance()->getTransactionProfiler(); $this->setHeaders(); $this->checkReadOnly(); $this->checkPermissions(); // This could also let someone check the current email address, so // require both permissions. if (!$this->getUser()->isAllowed('viewmyprivateinfo')) { throw new PermissionsError('viewmyprivateinfo'); } if ($code === null || $code === '') { $this->requireLogin('confirmemail_needlogin'); if (Sanitizer::validateEmail($this->getUser()->getEmail())) { $this->showRequestForm(); } else { $this->getOutput()->addWikiMsg('confirmemail_noemail'); } } else { $old = $trxProfiler->setSilenced(true); $this->attemptConfirm($code); $trxProfiler->setSilenced($old); } }
/** * The Symphony constructor initialises the class variables of Symphony. * It will set the DateTime settings, define new date constants and initialise * the correct Language for the currently logged in Author. If magic quotes * are enabled, Symphony will sanitize the `$_SERVER`, `$_COOKIE`, * `$_GET` and `$_POST` arrays. The constructor loads in * the initial Configuration values from the `CONFIG` file */ protected function __construct() { self::$Profiler = Profiler::instance(); self::$Profiler->sample('Engine Initialisation'); if (get_magic_quotes_gpc()) { General::cleanArray($_SERVER); General::cleanArray($_COOKIE); General::cleanArray($_GET); General::cleanArray($_POST); } $this->initialiseConfiguration(); define_safe('__SYM_DATE_FORMAT__', self::Configuration()->get('date_format', 'region')); define_safe('__SYM_TIME_FORMAT__', self::Configuration()->get('time_format', 'region')); define_safe('__SYM_DATETIME_FORMAT__', __SYM_DATE_FORMAT__ . self::Configuration()->get('datetime_separator', 'region') . __SYM_TIME_FORMAT__); DateTimeObj::setSettings(self::Configuration()->get('region')); // Initialize language management Lang::initialize(); $this->initialiseLog(); GenericExceptionHandler::initialise(self::Log()); GenericErrorHandler::initialise(self::Log()); $this->initialiseDatabase(); $this->initialiseExtensionManager(); $this->initialiseCookie(); // If the user is not a logged in Author, turn off the verbose error messages. if (!self::isLoggedIn() && is_null($this->Author)) { GenericExceptionHandler::$enabled = false; } // Set system language Lang::set(self::$Configuration->get('lang', 'symphony')); }
/** * purge is slightly weird because it can be either formed or formless depending * on user permissions */ public function show() { $this->setHeaders(); // This will throw exceptions if there's a problem $this->checkCanExecute($this->getUser()); $user = $this->getUser(); if ($user->pingLimiter('purge')) { // TODO: Display actionthrottledtext return; } if ($user->isAllowed('purge')) { // This will update the database immediately, even on HTTP GET. // Lots of uses may exist for this feature, so just ignore warnings. Profiler::instance()->getTransactionProfiler()->resetExpectations(); $this->redirectParams = wfArrayToCgi(array_diff_key($this->getRequest()->getQueryValues(), ['title' => null, 'action' => null])); if ($this->onSubmit([])) { $this->onSuccess(); } } else { $this->redirectParams = $this->getRequest()->getVal('redirectparams', ''); $form = $this->getForm(); if ($form->show()) { $this->onSuccess(); } } }
/** * Get singleton instance * @return Profiler */ public static function getInstance() { if (!isset(self::$instance)) { self::$instance = new Profiler(); } return self::$instance; }
public function __construct($file = null, array $data = null) { $token = Kohana::$profiling ? Profiler::start('renderer', 'new kohana view') : false; $this->_config = Kohana::config('render'); parent::__construct($file, $data); $token ? Profiler::stop($token) : null; }
/** * The Symphony constructor initialises the class variables of Symphony. * It will set the DateTime settings, define new date constants and initialise * the correct Language for the currently logged in Author. If magic quotes * are enabled, Symphony will sanitize the `$_SERVER`, `$_COOKIE`, * `$_GET` and `$_POST` arrays. The constructor loads in * the initial Configuration values from the `CONFIG` file */ protected function __construct() { $this->Profiler = Profiler::instance(); $this->Profiler->sample('Engine Initialisation'); if (get_magic_quotes_gpc()) { General::cleanArray($_SERVER); General::cleanArray($_COOKIE); General::cleanArray($_GET); General::cleanArray($_POST); } // Includes the existing CONFIG file and initialises the Configuration // by setting the values with the setArray function. include CONFIG; self::$Configuration = new Configuration(true); self::$Configuration->setArray($settings); DateTimeObj::setDefaultTimezone(self::$Configuration->get('timezone', 'region')); define_safe('__SYM_DATE_FORMAT__', self::$Configuration->get('date_format', 'region')); define_safe('__SYM_TIME_FORMAT__', self::$Configuration->get('time_format', 'region')); define_safe('__SYM_DATETIME_FORMAT__', __SYM_DATE_FORMAT__ . self::$Configuration->get('datetime_separator', 'region') . __SYM_TIME_FORMAT__); // Initialize language management Lang::initialize(); $this->initialiseLog(); GenericExceptionHandler::initialise(self::$Log); GenericErrorHandler::initialise(self::$Log, self::$Configuration->get('strict_error_handling', 'symphony')); $this->initialiseDatabase(); $this->initialiseExtensionManager(); $this->initialiseCookie(); // If the user is not a logged in Author, turn off the verbose error // messages. if (!self::isLoggedIn() && is_null($this->Author)) { GenericExceptionHandler::$enabled = false; } // Set system language Lang::set(self::$Configuration->get('lang', 'symphony')); }
public function execute($db = 'default') { if (!is_object($db)) { // Get the database instance $db = Database::instance($db); } // Import the SQL locally $sql = $this->_sql; if (!empty($this->_values)) { // Quote all of the values $values = array_map(array($db, 'quote'), $this->_values); // Replace the values in the SQL $sql = strtr($sql, $values); } if ($this->profile === TRUE) { // Start profiling this query $token = Profiler::start('database (' . (string) $db . ')', $sql); } // Load the result $result = $db->query($this->_type, $sql); if (isset($token)) { // Stop profiling Profiler::stop($token); } return $result; }
public function serve($content, $modified = false) { $cache_last_modified = $modified ? time() : filemtime($this->path); $header_modified_since = strtotime(\Input::server('HTTP_IF_MODIFIED_SINCE', 0)); $status = 200; // Set the response headers for cache etc $headers = array('Cache-Control' => 'public', 'Last-Modified' => gmdate('D, d M Y H:i:s', $cache_last_modified) . ' GMT', 'Content-Type' => $this->content_type, 'X-UA-Compatible' => 'IE=edge'); // Still call the before method on the controller... is this a good idea? Perhaps not. /* if (isset($this->request) && $controller = $this->request->controller_instance) { if (method_exists($controller, 'before')) $controller->before($content); } */ // Return 304 not modified if the content hasn't changed, but only if the profiler isn't enabled. if (!\Fuel::$profiling) { $headers['Content-Length'] = strlen($content); if ($header_modified_since >= $cache_last_modified) { header('HTTP/1.1 304 Not Modified'); exit; } } // Send the response \Response::forge($content, $status, $headers)->send(true); if (\Fuel::$profiling) { \Profiler::mark('CMF Cache Served'); } exit; }
/** * @param string $function * @param mixed $parameters .... */ public function measure_runtime() { $arr = func_get_args(); $fn = array_shift($arr); if (is_array($fn)) { $cl_name = get_class($fn[0]); $fn_name = $fn[1]; } elseif (0 === strpos(strtolower($fn), 'self::')) { $fn_name = explode('::', $fn); $cl_name = get_class(); $fn_name = $fn_name[1]; } elseif (0 === strpos(strtolower($fn), 'parent::')) { $fn_name = explode('::', $fn); $cl_name = get_parent_class(get_class()); $fn_name = $fn_name[1]; } else { $fn_name = explode('::', $fn); $cl_name = $fn_name[0]; $fn_name = $fn_name[1]; } $time = microtime(true); if (Kohana::$profiling === TRUE) { $benchmark = Profiler::start($cl_name, $fn_name); } $response = call_user_func_array($fn, $arr); $time = (microtime(true) - $time) * 1000; if (isset($benchmark)) { // Stop the benchmark Profiler::stop($benchmark); } ORM::factory('Rest_Metric')->millisec($cl_name . '/' . $fn_name, ceil($time)); return $response; }
public function query($type, $sql, $as_object = FALSE, array $params = NULL) { $this->_connection or $this->connect(); if (JsonApiApplication::$profiling) { $benchmark = Profiler::start("Database ({$this->_instance})", $sql); } try { $result = $this->_connection->query($sql); } catch (Exception $e) { if (isset($benchmark)) { Profiler::delete($benchmark); } throw new Database_Exception(':error [ :query ]', array(':error' => $e->getMessage(), ':query' => $sql), $e->getCode()); } if (isset($benchmark)) { Profiler::stop($benchmark); } $this->last_query = $sql; if ($type === Database::SELECT) { if ($as_object === FALSE) { $result->setFetchMode(PDO::FETCH_ASSOC); } elseif (is_string($as_object)) { $result->setFetchMode(PDO::FETCH_CLASS, $as_object, $params); } else { $result->setFetchMode(PDO::FETCH_CLASS, 'stdClass'); } $result = $result->fetchAll(); return new Database_Result_Cached($result, $sql, $as_object, $params); } elseif ($type === Database::INSERT) { return array($this->_connection->lastInsertId(), $result->rowCount()); } else { return $result->rowCount(); } }
public function render() { $token = Profiler::start(__CLASS__, __FUNCTION__); $r = parent::render(); Profiler::stop($token); return $r; }
/** * Override the default Symphony constructor to initialise the Log, Config * and Database objects for installation/update. This allows us to use the * normal accessors. */ protected function __construct() { self::$Profiler = Profiler::instance(); self::$Profiler->sample('Engine Initialisation'); if (get_magic_quotes_gpc()) { General::cleanArray($_SERVER); General::cleanArray($_COOKIE); General::cleanArray($_GET); General::cleanArray($_POST); } // Include the default Config for installation. include INSTALL . '/includes/config_default.php'; static::initialiseConfiguration($settings); // Initialize date/time define_safe('__SYM_DATE_FORMAT__', self::Configuration()->get('date_format', 'region')); define_safe('__SYM_TIME_FORMAT__', self::Configuration()->get('time_format', 'region')); define_safe('__SYM_DATETIME_FORMAT__', __SYM_DATE_FORMAT__ . self::Configuration()->get('datetime_separator', 'region') . __SYM_TIME_FORMAT__); DateTimeObj::setSettings(self::Configuration()->get('region')); // Initialize Language, Logs and Database static::initialiseLang(); static::initialiseLog(INSTALL_LOGS . '/install'); static::initialiseDatabase(); // Initialize error handlers GenericExceptionHandler::initialise(Symphony::Log()); GenericErrorHandler::initialise(Symphony::Log()); }
public static function lookup($hostname) { self::init(); Profiler::StartTimer("DNSResolver::lookup()", 2); $data = DataManager::singleton(); $records = $apc = NULL; $cachekey = "dnsresolver.lookup.{$hostname}"; if (self::$cache && !empty($data->caches["apc"]) && $data->caches["apc"]["default"]->enabled) { $apc = $data->caches["apc"]["default"]; $cached = $apc->get($cachekey); if ($cached !== false) { $records = unserialize($cached); Logger::Info("DNSResolver: found '{$hostname}' in APC cache"); } } if ($records === NULL) { Logger::Info("DNSResolver: Looking up '{$hostname}'"); foreach (self::$search as $suffix) { $fqdn = $hostname . (!empty($suffix) ? "." . $suffix : ""); $records = dns_get_record($fqdn, DNS_A); if (!empty($records)) { break; } } if (self::$cache && !empty($records) && $apc !== NULL && $apc->enabled) { $ttl = any(self::$ttl, $records[0]["ttl"]); $apc->set($cachekey, serialize($records), array("lifetime" => $ttl)); } } Profiler::StopTimer("DNSResolver::lookup()"); return $records; }
function wfSetupDump() { global $wgProfileToDatabase, $wgProfileSampleRate; // Override disabled profiling in maintenance scripts Profiler::setInstance(new Profiler()); $wgProfileToDatabase = false; $wgProfileSampleRate = 1; }
/** * @param array $params * @see Xhprof::__construct() */ public function __construct(array $params = []) { parent::__construct($params); $flags = isset($params['flags']) ? $params['flags'] : 0; $options = isset($params['exclude']) ? ['ignored_functions' => $params['exclude']] : []; Xhprof::enable($flags, $options); $this->sprofiler = new SectionProfiler(); }
/** * Roll back a transaction and return to autocommit mode. * * @return \Micro\Database\Adapter\AdapterAbstract */ public function rollBack() { $this->_connect(); $q = $this->_profiler->queryStart('rollback', \Micro\Database\Profiler::TRANSACTION); $this->_rollBack(); $this->_profiler->queryEnd($q); return $this; }