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);
     }
     if (!empty($this->_config['connection']['persistent']) and $this->_config['connection']['database'] !== Database_MySQL::$_current_databases[$this->_connection_id]) {
         $this->_select_db($this->_config['connection']['database']);
     }
     if (($result = mysql_query($sql, $this->_connection)) === FALSE) {
         if (isset($benchmark)) {
             Profiler::delete($benchmark);
         }
         throw new Database_Exception(':error [ :query ]', array(':error' => mysql_error($this->_connection), ':query' => $sql), mysql_errno($this->_connection));
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     $this->last_query = $sql;
     if ($type === Database::SELECT) {
         return new Database_MySQL_Result($result, $sql, $as_object, $params);
     } elseif ($type === Database::INSERT) {
         return array(mysql_insert_id($this->_connection), mysql_affected_rows($this->_connection));
     } else {
         return mysql_affected_rows($this->_connection);
     }
 }
 public static function start($nodeName)
 {
     if (defined('PROFILER_SWITCH') && PROFILER_SWITCH == 1) {
         Profiler::enable();
     }
     return Profiler::start($nodeName);
 }
Beispiel #3
0
 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;
 }
Beispiel #4
0
 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;
 }
Beispiel #5
0
/**
 * Start Zend Profiler
 */
function start_zend_profiler()
{
    include APPPATH . 'config' . DIRECTORY_SEPARATOR . 'database.php';
    if ($db[$active_group]['Zend_Db_Profiler_Firebug']) {
        Profiler::start($db[$active_group], Zend_Db_Table_Abstract::getDefaultAdapter());
    }
}
Beispiel #6
0
 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;
 }
Beispiel #7
0
 public function __construct($id = NULL)
 {
     Kohana::$profiling === TRUE && ($bm = Profiler::start('ORM', __FUNCTION__));
     parent::__construct($id);
     $this->after_initialize();
     isset($bm) && Profiler::stop($bm);
 }
Beispiel #8
0
 /**
  * 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();
     }
 }
Beispiel #9
0
 /**
  * 
  * @param Model_Job $job
  * @return void
  */
 public function run(Model_Job $job)
 {
     if (Kohana::$profiling === TRUE) {
         $benchmark = Profiler::start('Rub job', $job->name);
     }
     $this->values(array('job_id' => $job->id))->create();
     $this->set_status(Model_Job::STATUS_RUNNING);
     try {
         $job = $job->job;
         $minion_task = Minion_Task::convert_task_to_class_name($job);
         if (is_array($job)) {
             $passed = call_user_func($job);
         } elseif (class_exists($minion_task)) {
             Minion_Task::factory(array($job))->execute();
             $passed = TRUE;
         } elseif (strpos($job, '::') === FALSE) {
             $function = new ReflectionFunction($job);
             $passed = $function->invoke();
         } else {
             list($class, $method) = explode('::', $job, 2);
             $method = new ReflectionMethod($class, $method);
             $passed = $method->invoke(NULL);
         }
     } catch (Exception $e) {
         $this->failed();
         return;
     }
     $this->complete();
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
 }
Beispiel #10
0
	/**
	 * 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 set_filename($file)
 {
     Kohana::$profiling === TRUE && ($bm = Profiler::start('View', __FUNCTION__));
     $this->_import_options($file);
     if ($this->_viewfile) {
         if (($path = Kohana::find_file('views', $this->_viewfile, $this->_format . '.haml')) === FALSE) {
             if (($path = Kohana::find_file('views', $this->_viewfile, $this->_format . '.php')) !== FALSE) {
                 $this->_file = $path;
             } else {
                 if (is_string($file) && ($path = Kohana::find_file('views', $file)) !== FALSE) {
                     $this->_file = $path;
                 }
             }
             isset($bm) && Profiler::stop($bm);
             return $this;
         }
         $this->_file = $this->_get_compiled_haml($path);
         isset($bm) && Profiler::stop($bm);
         return $this;
     }
     if ($this->_is_inline) {
         $this->_file = $this->_get_compiled_inline_haml($this->_inline_haml);
     }
     isset($bm) && Profiler::stop($bm);
     return $this;
 }
Beispiel #12
0
 /**
  * @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;
 }
Beispiel #13
0
 /**
  * Create new Core object and initialize our own settings
  *
  * @param  string   $text    Text string to filter html
  * @param  integer  $format  Format id [Optional]
  * @param  array    $filter  Array of allowed tags [Optional]
  *
  * @used   Config::load
  * @used   Config::get
  * @used   Profiler::start
  */
 public function __construct($text, $format = 1, array $filter = NULL)
 {
     // Be sure to only profile if it's enabled
     if (Gleez::$profiling) {
         // Start a new benchmark
         $this->benchmark = Profiler::start('Gleez Filter', __FUNCTION__);
     }
     // Load the configuration for this type
     $config = Config::load('inputfilter');
     if ($config->allowed_protocols and is_array($config->allowed_protocols)) {
         $this->allowed_protocols = $config->allowed_protocols;
     }
     if ($config->allowed_tags and is_array($config->allowed_tags)) {
         $this->allowed_tags = $config->allowed_tags;
     }
     if (!array_key_exists($format, $config->formats)) {
         // make sure a valid format id exists, if not set default format id
         $format = (int) $config->get('default_format', 1);
     }
     if (isset($filter['settings']['allowed_html'])) {
         $this->allowed_tags = preg_split('/\\s+|<|>/', $filter['settings']['allowed_html'], -1, PREG_SPLIT_NO_EMPTY);
     }
     $this->_text = (string) $text;
     $this->_config = $config;
     if (Kohana::PRODUCTION !== Kohana::$environment) {
         Log::debug('HTML Filter Library initialized');
     }
 }
Beispiel #14
0
 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();
     }
 }
Beispiel #15
0
 /**
  * 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;
 }
Beispiel #16
0
 public function render()
 {
     $token = Profiler::start(__CLASS__, __FUNCTION__);
     $r = parent::render();
     Profiler::stop($token);
     return $r;
 }
Beispiel #17
0
 /**
  * Attempt to find a page in the CMS, return the response
  *
  * @param  string  The url to load, will be autodetected if needed
  * @return void
  */
 public function action_view($url = NULL)
 {
     if (Kohana::$profiling === TRUE) {
         // Start a new benchmark
         $benchmark = Profiler::start('Kohanut', 'Kohanut Controller');
     }
     // If no $url is passed, default to the server request uri
     if ($url === NULL) {
         $url = $_SERVER['REQUEST_URI'];
     }
     // Trim off Kohana::$base_url
     $url = preg_replace('#^' . Kohana::$base_url . '#', '', $url);
     // Ensure no trailing slash
     $url = preg_replace('/\\/$/', '', $url);
     // Ensure no leading slash
     $url = preg_replace('/^\\//', '', $url);
     // Remove anything ofter a ? or #
     $url = preg_replace('/[\\?#].+/', '', $url);
     // Try to find what to do on this url
     try {
         // Make sure the url is clean. See http://www.faqs.org/rfcs/rfc2396.html see section 2.3
         // TODO - this needs to be better
         if (preg_match("/[^\\/A-Za-z0-9-_\\.!~\\*\\(\\)]/", $url)) {
             Kohana::$log->add('INFO', "Kohanut - Request had unknown characters. '{$url}'");
             throw new Kohanut_Exception("Url request had unknown characters '{$url}'", array(), 404);
         }
         // Check for a redirect on this url
         Sprig::factory('kohanut_redirect', array('url', $url))->go();
         // Find the page that matches this url, and isn't an external link
         $query = DB::select()->where('url', '=', $url)->where('islink', '=', 0);
         $page = Sprig::factory('kohanut_page')->load($query);
         if (!$page->loaded()) {
             // Could not find page in database, throw a 404
             Kohana::$log->add('INFO', "Kohanut - Could not find '{$url}' (404)");
             throw new Kohanut_Exception("Could not find '{$page->url}'", array(), 404);
         }
         // Set the status to 200, rather than 404, which was set by the router with the reflectionexception
         Kohanut::status(200);
         $out = $page->render();
     } catch (Kohanut_Exception $e) {
         // Find the error page
         $error = Sprig::factory('kohanut_page', array('url' => 'error'))->load();
         // If i couldn't find the error page, just give a generic message
         if (!$error->loaded()) {
             Kohanut::status(404);
             $this->request->response = View::factory('kohanut/generic404');
             return;
         }
         // Set the response
         $out = $error->render();
     }
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     // Set the response
     $this->request->response = $out;
 }
Beispiel #18
0
 /**
  * Renders the Debug Toolbar
  *
  * @static
  * @return bool|string
  */
 public static function render()
 {
     if (!self::is_enabled()) {
         return FALSE;
     }
     $token = Profiler::start('custom', self::$benchmark_name);
     $template = new View('toolbar');
     $config = Kohana::$config->load('debug_toolbar');
     // Database panel
     if ($config->panels['database'] === TRUE) {
         $queries = self::get_queries();
         $template->set('queries', $queries['data'])->set('query_count', $queries['count'])->set('total_time', $queries['time'])->set('total_memory', $queries['memory']);
     }
     // Files panel
     if ($config->panels['files'] === TRUE) {
         $template->set('files', self::get_files());
     }
     // Modules panel
     if ($config->panels['modules'] === TRUE) {
         $template->set('modules', self::get_modules());
     }
     // Routes panel
     if ($config->panels['routes'] === TRUE) {
         $template->set('routes', self::get_routes());
     }
     // Custom data
     if ($config->panels['customs'] === TRUE) {
         $template->set('customs', self::get_customs());
     }
     // FirePHP
     if ($config->firephp_enabled === TRUE) {
         self::firephp();
     }
     // Set alignment for toolbar
     switch ($config->align) {
         case 'right':
         case 'center':
         case 'left':
             $template->set('align', $config->align);
             break;
         default:
             $template->set('align', 'left');
     }
     // Javascript for toolbar
     $template->set('scripts', file_get_contents(Kohana::find_file('views', 'toolbar', 'js')));
     // CSS for toolbar
     $styles = file_get_contents(Kohana::find_file('views', 'toolbar', 'css'));
     Profiler::stop($token);
     // Benchmarks panel
     if ($config->panels['benchmarks'] === TRUE) {
         $template->set('benchmarks', self::get_benchmarks());
     }
     $template->set('styles', $styles);
     echo $template->render();
 }
Beispiel #19
0
 /**
  * Processes the request, executing the controller action that handles this
  * request, determined by the [Route].
  *
  * 1. Before the controller action is called, the [Controller::before] method
  * will be called.
  * 2. Next the controller action will be called.
  * 3. After the controller action is called, the [Controller::after] method
  * will be called.
  *
  * By default, the output from the controller is captured and returned, and
  * no headers are sent.
  *
  *     $request->execute();
  *
  * @param   Request $request A request object
  * @return  Response
  * @throws  Kohana_Exception
  * @uses    [Kohana::$profiling]
  * @uses    [Profiler]
  */
 public function execute(Request $request)
 {
     // Check for cache existance
     if ($this->_cache instanceof Cache and ($response = $this->cache_response($request)) instanceof Response) {
         return $response;
     }
     if (Kohana::$profiling) {
         // Set the benchmark name
         $benchmark = '"' . $request->uri() . '"';
         if ($request !== Request::$initial and Request::$current) {
             // Add the parent request uri
             $benchmark .= ' « "' . Request::$current->uri() . '"';
         }
         // Start benchmarking
         $benchmark = Profiler::start('Requests', $benchmark);
     }
     // Store the current active request and replace current with new request
     $previous = Request::$current;
     Request::$current = $request;
     // Resolve the POST fields
     if ($post = $request->post()) {
         $request->body(http_build_query($post, NULL, '&'))->headers('content-type', 'application/x-www-form-urlencoded');
     }
     try {
         // If PECL_HTTP is present, use extension to complete request
         if (extension_loaded('http')) {
             $this->_http_execute($request);
         } elseif (extension_loaded('curl')) {
             $this->_curl_execute($request);
         } else {
             $this->_native_execute($request);
         }
     } catch (Exception $e) {
         // Restore the previous request
         Request::$current = $previous;
         if (isset($benchmark)) {
             // Delete the benchmark, it is invalid
             Profiler::delete($benchmark);
         }
         // Re-throw the exception
         throw $e;
     }
     // Restore the previous request
     Request::$current = $previous;
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     // Cache the response if cache is available
     if ($this->_cache instanceof Cache) {
         $this->cache_response($request, $request->response());
     }
     // Return the response
     return $request->response();
 }
Beispiel #20
0
 public function testServerDataFromProfilerToProfile()
 {
     $serverData = array('foo' => 'bar');
     // Currently, $_SERVER data is hardcoded empty array, @see Profiler::stop:r256
     $profiler = new Profiler();
     $profiler->start();
     $profile = $profiler->stop();
     // Override $_SERVER for tests
     $profile->setServerData($serverData);
     $this->assertEquals($serverData, $profile->getServerData());
 }
Beispiel #21
0
 /**
  * Processes the request, executing the controller. Before the routed action
  * is run, the before() method will be called, which allows the controller
  * to overload the action based on the request parameters. After the action
  * is run, the after() method will be called, for post-processing.
  *
  * By default, the output from the controller is captured and returned, and
  * no headers are sent.
  *
  * @return  $this
  */
 public function execute()
 {
     // Create the class prefix
     $prefix = 'controller_';
     if (!empty($this->directory)) {
         // Add the directory name to the class prefix
         $prefix .= str_replace(array('\\', '/'), '_', trim($this->directory, '/')) . '_';
     }
     if (Kohana::$profiling === TRUE) {
         // Start benchmarking
         $benchmark = Profiler::start('Requests', $this->uri);
     }
     try {
         // Load the controller using reflection
         $class = new ReflectionClass($prefix . $this->controller);
         if ($class->isAbstract()) {
             throw new Kohana_Exception('Cannot create instances of abstract :controller', array(':controller' => $prefix . $this->controller));
         }
         // Create a new instance of the controller
         $controller = $class->newInstance($this);
         // Execute the "before action" method
         $class->getMethod('before')->invoke($controller);
         // Determine the action to use
         $action = empty($this->action) ? Route::$default_action : $this->action;
         // Ensure the action exists, and use __call() if it doesn't
         if ($class->hasMethod('action_' . $action)) {
             // Execute the main action with the parameters
             $class->getMethod('action_' . $action)->invokeArgs($controller, $this->_params);
         } else {
             $class->getMethod('__call')->invokeArgs($controller, array($action, $this->_params));
         }
         // Execute the "after action" method
         $class->getMethod('after')->invoke($controller);
     } catch (Exception $e) {
         if (isset($benchmark)) {
             // Delete the benchmark, it is invalid
             Profiler::delete($benchmark);
         }
         if ($e instanceof ReflectionException) {
             // Reflection will throw exceptions for missing classes or actions
             $this->status = 404;
         } else {
             // All other exceptions are PHP/server errors
             $this->status = 500;
         }
         // Re-throw the exception
         throw $e;
     }
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     return $this;
 }
 public function friends()
 {
     if (Kohana::$profiling === TRUE) {
         $benchmark = Profiler::start('Kohana_Facebook', 'facebook->api(/me/friends)');
     }
     $result = $this->_facebook->api('/me/friends');
     if (isset($benchmark)) {
         // Stop the benchmark
         Profiler::stop($benchmark);
     }
     return $result['data'];
 }
Beispiel #23
0
 public function render(array $params = array())
 {
     if (Kohana::$profiling === TRUE) {
         $benchmark = Profiler::start('Widget render', $this->name);
     }
     $this->_fetch_template();
     $this->set_params($params);
     return $this->_fetch_render();
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
 }
Beispiel #24
0
 private function _execute_request($url)
 {
     if (Kohana::$profiling) {
         $benchmark = Profiler::start("Helper ({$this})", $this->_url);
     }
     $request = Request::factory($url);
     $response = $request->execute();
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     return $response->body();
 }
 public function query($type, $sql, $as_object)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     try {
         $result = $this->_connection->query($sql);
     } catch (\Exception $e) {
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         if ($type !== \DB::SELECT && $this->_trans_enabled) {
             // If we are using transactions, throwing an exception would defeat the purpose
             // We need to log the failures for transaction status
             if (!is_array($this->trans_errors)) {
                 $this->trans_errors = array();
             }
             $this->trans_errors[] = $e->getMessage() . ' with query: "' . $sql . '"';
             return false;
         } else {
             // Convert the exception in a database exception
             throw new \Database_Exception($e->getMessage() . ' with query: "' . $sql . '"');
         }
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === \DB::SELECT) {
         // Convert the result into an array, as PDOStatement::rowCount is not reliable
         if ($as_object === FALSE) {
             $result->setFetchMode(\PDO::FETCH_ASSOC);
         } elseif (is_string($as_object)) {
             $result->setFetchMode(\PDO::FETCH_CLASS, $as_object);
         } else {
             $result->setFetchMode(\PDO::FETCH_CLASS, 'stdClass');
         }
         $result = $result->fetchAll();
         // Return an iterator of results
         return new \Database_Result_Cached($result, $sql, $as_object);
     } elseif ($type === \DB::INSERT) {
         // Return a list of insert id and rows created
         return array($this->_connection->lastInsertId(), $result->rowCount());
     } else {
         // Return the number of rows affected
         return $result->rowCount();
     }
 }
 public function query($type, $sql, $as_object = FALSE, array $params = NULL)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     if (!empty($this->_config['profiling'])) {
         // Benchmark this query for the current instance
         $benchmark = Profiler::start("Database ({$this->_instance})", $sql);
     }
     // Detect type Database::INSERT and ensure last id is captured
     if ($type === Database::INSERT) {
         // We need to do some magic here to get the insert ID
         // this is a glorious hack!
         $sql_statement = (string) $sql;
         // Locate VALUES
         $values = strpos($sql, 'VALUES');
         // Insert the lastInsertId logic
         $sql = substr($sql_statement, 0, $values) . 'output inserted.identitycol AS lastInsertId ' . substr($sql_statement, $values);
     }
     // Execute the query
     if (($result = sqlsrv_query($this->_connection, $sql, $params, array('Scrollable' => SQLSRV_CURSOR_KEYSET))) === FALSE) {
         // If something went wrong
         if (isset($benchmark)) {
             // This benchmark is worthless
             Profiler::delete($benchmark);
         }
         // Get the errors
         $error = sqlsrv_errors(SQLSRV_ERR_ERRORS);
         // Throw an exception
         throw new Database_Sqlsrv_Exception(':error [ :query ]', array(':error' => $error[0]['message'], ':query' => $sql), $error[0]['code']);
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     // Set the last query
     $this->last_query = $sql;
     if ($type === Database::SELECT) {
         // Return an iterator of results
         return new Database_Sqlsrv_Result($result, $sql, $as_object);
     } elseif ($type === Database::INSERT) {
         // Get the last insert id
         if (($insert_id = sqlsrv_fetch_array($result)) === FALSE) {
             // Get the errors
             $error = sqlsrv_errors(SQLSRV_ERR_ERRORS);
             // Throw an exception
             throw new Database_Sqlsrv_Exception(':error [ :query ]', array(':error' => 'Unable to get the last inserted row ID from driver', ':query' => $sql), $error[0]['code']);
         }
         return array($insert_id['lastInsertId'], sqlsrv_rows_affected($result));
     } else {
         // Return the number of rows affected
         return sqlsrv_rows_affected($result);
     }
 }
Beispiel #27
0
 /**
  * Dispatches an event to observer's callback
  *
  * @param Event $event
  * @return Observer
  */
 public function dispatch(Event $event)
 {
     if (!$this->isValidFor($event)) {
         return $this;
     }
     $callback = $this->getCallback();
     $this->setEvent($event);
     $_profilerKey = 'OBSERVER: ' . (is_object($callback[0]) ? get_class($callback[0]) : (string) $callback[0]) . ' -> ' . $callback[1];
     Profiler::start($_profilerKey);
     call_user_func($callback, $this);
     Profiler::stop($_profilerKey);
     return $this;
 }
Beispiel #28
0
 /**
  * Wrap requested view inside module and render
  *
  * @return  string
  */
 public function render($file = null)
 {
     // Start benchmark
     if (Kohana::$profiling === true and class_exists('Profiler', false)) {
         $benchmark = Profiler::start('View', __METHOD__ . '(' . $this->_name . ')');
     }
     $module = (string) View::factory('generic/mod', array('class' => 'mod ' . Arr::get_once($this->_data, 'mod_class', strtr(basename($this->_file, '.php'), '_', '-')), 'id' => Arr::get_once($this->_data, 'mod_id'), 'actions' => isset($this->_data['mod_actions']) ? (string) View::factory('generic/actions', array('actions' => Arr::get_once($this->_data, 'mod_actions'))) : null, 'actions2' => isset($this->_data['mod_actions2']) ? (string) View::factory('generic/actions', array('actions' => Arr::get_once($this->_data, 'mod_actions2'))) : null, 'title' => Arr::get_once($this->_data, 'mod_title'), 'subtitle' => Arr::get_once($this->_data, 'mod_subtitle'), 'pagination' => Arr::get_once($this->_data, 'pagination'), 'content' => parent::render($file)));
     // Stop benchmark
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     return $module;
 }
Beispiel #29
0
 /**
  * Получение карты сайта
  * 
  * @param boolean $include_hidden Включить скрытые страницы
  * @return Model_Page_Sitemap
  */
 public static function get($include_hidden = FALSE)
 {
     if (Kohana::$profiling) {
         $benchmark = Profiler::start('Sitemap', __METHOD__);
     }
     $status = (bool) $include_hidden ? 1 : 0;
     if (!array_key_exists($status, Model_Page_Sitemap::$_sitemap)) {
         $pages = ORM::factory('page')->order_by('parent_id', 'asc')->order_by('position', 'asc');
         if ((bool) $include_hidden === FALSE) {
             $pages->where('status_id', 'in', array(Model_Page::STATUS_PASSWORD_PROTECTED, Model_Page::STATUS_PUBLISHED));
         }
         $res_pages = $pages->find_all();
         $_pages = array();
         foreach ($res_pages as $page) {
             $_pages[$page->id] = $page->as_array();
             $_pages[$page->id]['uri'] = '';
             $_pages[$page->id]['url'] = '';
             $_pages[$page->id]['slug'] = $page->slug;
             $_pages[$page->id]['level'] = 0;
             $_pages[$page->id]['is_active'] = TRUE;
         }
         $pages = array();
         foreach ($_pages as &$page) {
             $pages[$page['parent_id']][] =& $page;
         }
         foreach ($_pages as &$page) {
             if (isset($pages[$page['id']])) {
                 foreach ($pages[$page['id']] as &$_page) {
                     $_page['level'] = $page['level'] + 1;
                     $_page['parent'] = $page;
                     $_page['uri'] = $page['uri'] . '/' . $_page['slug'];
                     $_page['url'] = URL::frontend($_page['uri']);
                     $_page['is_active'] = URL::match($_page['uri']);
                     if (empty($_page['layout_file'])) {
                         $_page['layout_file'] = $page['layout_file'];
                     }
                     if ($_page['is_active']) {
                         $page['is_active'] = TRUE;
                     }
                 }
                 $page['childs'] = $pages[$page['id']];
             }
         }
         Model_Page_Sitemap::$_sitemap[$status] = new Sitemap(reset($pages));
     }
     if (isset($benchmark)) {
         Profiler::stop($benchmark);
     }
     return clone Model_Page_Sitemap::$_sitemap[$status];
 }
Beispiel #30
0
 /**
  * Creates an html list of all classes sorted by category (or package if no category)
  *
  * @return   string   the html for the menu
  */
 public static function menu()
 {
     $menu = Cache::instance()->get('kodocMenu');
     if ($menu !== NULL) {
         return View::factory('userguide/api/menu')->bind('menu', $menu);
     }
     $profiler = Profiler::start('Userguide', 'build menu');
     $classes = Kodoc::classes();
     foreach ($classes as $class) {
         if (isset($classes['kohana_' . $class])) {
             // Remove extended classes
             unset($classes['kohana_' . $class]);
         }
         if (isset($classes['kodicms_' . $class])) {
             // Remove extended classes
             unset($classes['kodicms_' . $class]);
         }
     }
     ksort($classes);
     $menu = array();
     $route = Route::get('docs/api');
     foreach ($classes as $class) {
         $class = Kodoc_Class::factory($class);
         // Test if we should show this class
         if (!Kodoc::show_class($class)) {
             continue;
         }
         $link = HTML::anchor($route->uri(array('class' => $class->class->name)), $class->class->name);
         if (isset($class->tags['package'])) {
             foreach ($class->tags['package'] as $package) {
                 if (isset($class->tags['category'])) {
                     foreach ($class->tags['category'] as $category) {
                         $menu[$package][$category][] = $link;
                     }
                 } else {
                     $menu[$package]['Base'][] = $link;
                 }
             }
         } else {
             $menu['[Unknown]']['Base'][] = $link;
         }
     }
     // Sort the packages
     ksort($menu);
     Cache::instance()->set('kodocMenu', $menu, Date::DAY);
     if (isset($profiler)) {
         Profiler::stop($profiler);
     }
     return View::factory('userguide/api/menu')->bind('menu', $menu);
 }