Modules
Kohana_Core
Contains the most low-level helpers methods in Kohana:
- Environment initialization
- Locating files within the cascading filesystem
- Auto-loading and transparent extension of classes
- Variable and path debugging
Class declared in SYSPATH/classes/kohana/core.php on line 16.
Constants
Properties
Constants
VERSION
string(6) "3.0.10"CODENAME
string(10) "Hierofalco"ERROR
string(5) "ERROR"DEBUG
string(5) "DEBUG"INFO
string(4) "INFO"CRITICAL
string(8) "CRITICAL"STRACE
string(6) "STRACE"ALERT
string(5) "ALERT"PRODUCTION
string(10) "production"STAGING
string(7) "staging"TESTING
string(7) "testing"DEVELOPMENT
string(11) "development"FILE_SECURITY
string(60) "<?php defined('SYSPATH') or die('No direct script access.');"FILE_CACHE
string(26) ":header // :name :data "
Properties
public static
string$base_urlBase URL to the application. Set by Kohana::init
string(5) "/3.0/"public static
string$cache_dirCache directory, used by Kohana::cache. Set by Kohana::init
string(37) "/var/www/guides/3.0/application/cache"public static
integer$cache_lifeDefault lifetime for caching, in seconds, used by Kohana::cache. Set by Kohana::init
integer 60
public static
boolean$cachingWhether to use internal caching for Kohana::find_file, does not apply to Kohana::cache. Set by Kohana::init
bool FALSE
public static
string$charsetCharacter set of input and output. Set by Kohana::init
string(5) "utf-8"public static
Kohana_Config$configconfig object
object Kohana_Config()
public static
boolean$debug_escape_quotesescape quotes in Kohana::debug?
bool FALSE
public static
string$environmentCurrent environment name
string(11) "development"public static
string$error_viewError rendering view when Kohana catches PHP errors and exceptions. Set by Kohana::init
string(12) "kohana/error"public static
boolean$errorsEnable Kohana catching and displaying PHP errors and exceptions. Set by Kohana::init
bool TRUE
public static
string$index_fileApplication index file, added to links generated by Kohana. Set by Kohana::init
string(0) ""public static
boolean$is_cliTrue if Kohana is running from the command line
bool FALSE
public static
boolean$is_windowsTrue if Kohana is running on windows
bool FALSE
public static
Kohana_Log$loglogging object
object Kohana_Log()
public static
boolean$log_errorsShould errors and exceptions be logged
bool FALSE
public static
boolean$magic_quotesTrue if magic quotes is enabled.
bool FALSE
public static
array$php_errorsCodes to turn PHP error codes into readable names.
array(9) ( 1 => string(11) "Fatal Error" 256 => string(10) "User Error" 4 => string(11) "Parse Error" 2 => string(7) "Warning" 512 => string(12) "User Warning" 2048 => string(6) "Strict" 8 => string(6) "Notice" 4096 => string(17) "Recoverable Error" 8192 => string(10) "Deprecated" )
public static
boolean$profilingWhether to enable profiling. Set by Kohana::init
bool TRUE
public static
boolean$safe_modeTRUE if PHP safe mode is on
bool FALSE
public static
array$shutdown_errorsTypes of errors to display at shutdown
array(3) ( 0 => integer 4 1 => integer 1 2 => integer 256 )
protected static
array$_filesFile path cache, used when caching is true in Kohana::init
array(0)protected static
boolean$_files_changedHas the file path cache changed during this execution? Used internally when when caching is true in Kohana::init
bool FALSE
protected static
boolean$_initHas Kohana::init been called?
bool TRUE
protected static
array$_modulesCurrently active modules
array(9) ( "auth" => string(33) "/var/www/guides/3.0/modules/auth/" "cache" => string(34) "/var/www/guides/3.0/modules/cache/" "codebench" => string(38) "/var/www/guides/3.0/modules/codebench/" "database" => string(37) "/var/www/guides/3.0/modules/database/" "image" => string(34) "/var/www/guides/3.0/modules/image/" "orm" => string(32) "/var/www/guides/3.0/modules/orm/" "oauth" => string(34) "/var/www/guides/3.0/modules/oauth/" "pagination" => string(39) "/var/www/guides/3.0/modules/pagination/" "userguide" => string(38) "/var/www/guides/3.0/modules/userguide/" )
protected static
array$_pathsInclude paths that are used to find files
array(11) ( 0 => string(32) "/var/www/guides/3.0/application/" 1 => string(33) "/var/www/guides/3.0/modules/auth/" 2 => string(34) "/var/www/guides/3.0/modules/cache/" 3 => string(38) "/var/www/guides/3.0/modules/codebench/" 4 => string(37) "/var/www/guides/3.0/modules/database/" 5 => string(34) "/var/www/guides/3.0/modules/image/" 6 => string(32) "/var/www/guides/3.0/modules/orm/" 7 => string(34) "/var/www/guides/3.0/modules/oauth/" 8 => string(39) "/var/www/guides/3.0/modules/pagination/" 9 => string(38) "/var/www/guides/3.0/modules/userguide/" 10 => string(27) "/var/www/guides/3.0/system/" )
Methods
public static auto_load( string $class ) (defined in Kohana_Core)
Provides auto-loading support of classes that follow Kohana's class naming conventions. See Loading Classes for more information.
Class names are converted to file names by making the class name lowercase and converting underscores to slashes:
// Loads classes/my/class/name.php
Kohana::auto_load('My_Class_Name');
You should never have to call this function, as simply calling a class will cause it to be called.
This function must be enabled as an autoloader in the bootstrap:
spl_autoload_register(array('Kohana', 'auto_load'));
Parameters
-
string$class required - Class name
Return Values
boolean
Source Code
public static function auto_load($class)
{
try
{
// Transform the class name into a path
$file = str_replace('_', '/', strtolower($class));
if ($path = Kohana::find_file('classes', $file))
{
// Load the class file
require $path;
// Class has been found
return TRUE;
}
// Class is not in the filesystem
return FALSE;
}
catch (Exception $e)
{
Kohana::exception_handler($e);
die;
}
}
public static cache( string $name [, mixed $data = NULL , integer $lifetime = NULL ] ) (defined in Kohana_Core)
Provides simple file-based caching for strings and arrays:
// Set the "foo" cache
Kohana::cache('foo', 'hello, world');
// Get the "foo" cache
$foo = Kohana::cache('foo');
All caches are stored as PHP code, generated with var_export. Caching objects may not work as expected. Storing references or an object or array that has recursion will cause an E_FATAL.
The cache directory and default cache lifetime is set by Kohana::init
Parameters
-
string$name required - Name of the cache -
mixed$data = NULL - Data to cache -
integer$lifetime = NULL - Number of seconds the cache is valid for
Tags
Return Values
mixed- For gettingboolean- For setting
Source Code
public static function cache($name, $data = NULL, $lifetime = NULL)
{
// Cache file is a hash of the name
$file = sha1($name).'.txt';
// Cache directories are split by keys to prevent filesystem overload
$dir = Kohana::$cache_dir.DIRECTORY_SEPARATOR.$file[0].$file[1].DIRECTORY_SEPARATOR;
if ($lifetime === NULL)
{
// Use the default lifetime
$lifetime = Kohana::$cache_life;
}
if ($data === NULL)
{
if (is_file($dir.$file))
{
if ((time() - filemtime($dir.$file)) < $lifetime)
{
// Return the cache
try
{
return unserialize(file_get_contents($dir.$file));
}
catch (Exception $e)
{
// Cache is corrupt, let return happen normally.
}
}
else
{
try
{
// Cache has expired
unlink($dir.$file);
}
catch (Exception $e)
{
// Cache has mostly likely already been deleted,
// let return happen normally.
}
}
}
// Cache not found
return NULL;
}
if ( ! is_dir($dir))
{
// Create the cache directory
mkdir($dir, 0777, TRUE);
// Set permissions (must be manually set to fix umask issues)
chmod($dir, 0777);
}
// Force the data to be a string
$data = serialize($data);
try
{
// Write the cache
return (bool) file_put_contents($dir.$file, $data, LOCK_EX);
}
catch (Exception $e)
{
// Failed to write cache
return FALSE;
}
}
public static config( string $group ) (defined in Kohana_Core)
Returns the configuration array for the requested group. See configuration files for more information.
// Get all the configuration in config/database.php
$config = Kohana::config('database');
// Get only the default connection configuration
$default = Kohana::config('database.default')
// Get only the hostname of the default connection
$host = Kohana::config('database.default.connection.hostname')
Parameters
-
string$group required - Group name
Return Values
Kohana_Config
Source Code
public static function config($group)
{
static $config;
if (strpos($group, '.') !== FALSE)
{
// Split the config group and path
list ($group, $path) = explode('.', $group, 2);
}
if ( ! isset($config[$group]))
{
// Load the config group into the cache
$config[$group] = Kohana::$config->load($group);
}
if (isset($path))
{
return Arr::path($config[$group], $path, NULL, '.');
}
else
{
return $config[$group];
}
}
public static debug( ) (defined in Kohana_Core)
Returns an HTML string of debugging information about any number of variables, each wrapped in a "pre" tag:
// Displays the type and value of each variable
echo Kohana::debug($foo, $bar, $baz);
Return Values
string
Source Code
public static function debug()
{
if (func_num_args() === 0)
return;
// Get all passed variables
$variables = func_get_args();
$output = array();
foreach ($variables as $var)
{
$output[] = Kohana::_dump($var, 1024);
}
return '<pre class="debug">'.implode("\n", $output).'</pre>';
}
public static debug_path( string $file ) (defined in Kohana_Core)
Removes application, system, modpath, or docroot from a filename, replacing them with the plain text equivalents. Useful for debugging when you want to display a shorter path.
// Displays SYSPATH/classes/kohana.php
echo Kohana::debug_path(Kohana::find_file('classes', 'kohana'));
Parameters
-
string$file required - Path to debug
Return Values
string
Source Code
public static function debug_path($file)
{
if (strpos($file, APPPATH) === 0)
{
$file = 'APPPATH'.DIRECTORY_SEPARATOR.substr($file, strlen(APPPATH));
}
elseif (strpos($file, SYSPATH) === 0)
{
$file = 'SYSPATH'.DIRECTORY_SEPARATOR.substr($file, strlen(SYSPATH));
}
elseif (strpos($file, MODPATH) === 0)
{
$file = 'MODPATH'.DIRECTORY_SEPARATOR.substr($file, strlen(MODPATH));
}
elseif (strpos($file, DOCROOT) === 0)
{
$file = 'DOCROOT'.DIRECTORY_SEPARATOR.substr($file, strlen(DOCROOT));
}
return $file;
}
public static debug_source( string $file , integer $line_number [, integer $padding = integer 5 ] ) (defined in Kohana_Core)
Returns an HTML string, highlighting a specific line of a file, with some number of lines padded above and below.
// Highlights the current line of the current file
echo Kohana::debug_source(__FILE__, __LINE__);
Parameters
-
string$file required - File to open -
integer$line_number required - Line number to highlight -
integer$padding = integer 5 - Number of padding lines
Return Values
string- Source of fileFALSE- File is unreadable
Source Code
public static function debug_source($file, $line_number, $padding = 5)
{
if ( ! $file OR ! is_file($file) OR ! is_readable($file))
{
// Continuing will cause errors
return FALSE;
}
// Open the file and set the line position
$file = fopen($file, 'r');
$line = 0;
// Set the reading range
$range = array('start' => $line_number - $padding, 'end' => $line_number + $padding);
// Set the zero-padding amount for line numbers
$format = '% '.strlen($range['end']).'d';
$source = '';
while (($row = fgets($file)) !== FALSE)
{
// Increment the line number
if (++$line > $range['end'])
break;
if ($line >= $range['start'])
{
// Make the row safe for output
$row = htmlspecialchars($row, ENT_NOQUOTES, Kohana::$charset);
// Trim whitespace and sanitize the row
$row = '<span class="number">'.sprintf($format, $line).'</span> '.$row;
if ($line === $line_number)
{
// Apply highlighting to this row
$row = '<span class="line highlight">'.$row.'</span>';
}
else
{
$row = '<span class="line">'.$row.'</span>';
}
// Add to the captured source
$source .= $row;
}
}
// Close the file
fclose($file);
return '<pre class="source"><code>'.$source.'</code></pre>';
}
public static deinit( ) (defined in Kohana_Core)
Cleans up the environment:
- Restore the previous error and exception handlers
- Destroy the Kohana::$log and Kohana::$config objects
Return Values
void
Source Code
public static function deinit()
{
if (Kohana::$_init)
{
// Removed the autoloader
spl_autoload_unregister(array('Kohana', 'auto_load'));
if (Kohana::$errors)
{
// Go back to the previous error handler
restore_error_handler();
// Go back to the previous exception handler
restore_exception_handler();
}
// Destroy objects created by init
Kohana::$log = Kohana::$config = NULL;
// Reset internal storage
Kohana::$_modules = Kohana::$_files = array();
Kohana::$_paths = array(APPPATH, SYSPATH);
// Reset file cache status
Kohana::$_files_changed = FALSE;
// Kohana is no longer initialized
Kohana::$_init = FALSE;
}
}
public static dump( mixed $value [, integer $length = integer 128 ] ) (defined in Kohana_Core)
Returns an HTML string of information about a single variable.
Borrows heavily on concepts from the Debug class of Nette.
Parameters
-
mixed$value required - Variable to dump -
integer$length = integer 128 - Maximum length of strings
Return Values
string
Source Code
public static function dump($value, $length = 128)
{
return Kohana::_dump($value, $length);
}
public static error_handler( ) (defined in Kohana_Core)
PHP error handler, converts all errors into ErrorExceptions. This handler respects error_reporting settings.
Tags
Return Values
TRUE
Source Code
public static function error_handler($code, $error, $file = NULL, $line = NULL)
{
if (error_reporting() & $code)
{
// This error is not suppressed by current error reporting settings
// Convert the error into an ErrorException
throw new ErrorException($error, $code, 0, $file, $line);
}
// Do not execute the PHP error handler
return TRUE;
}
public static exception_handler( object $e ) (defined in Kohana_Core)
Inline exception handler, displays the error message, source of the exception, and the stack trace of the error.
Parameters
-
object$e required - Exception object
Tags
Return Values
boolean
Source Code
public static function exception_handler(Exception $e)
{
try
{
// Get the exception information
$type = get_class($e);
$code = $e->getCode();
$message = $e->getMessage();
$file = $e->getFile();
$line = $e->getLine();
// Create a text version of the exception
$error = Kohana::exception_text($e);
if (is_object(Kohana::$log))
{
// Add this exception to the log
Kohana::$log->add(Kohana::ERROR, $error);
// Make sure the logs are written
Kohana::$log->write();
}
if (Kohana::$is_cli)
{
// Just display the text of the exception
echo "\n{$error}\n";
return TRUE;
}
// Get the exception backtrace
$trace = $e->getTrace();
if ($e instanceof ErrorException)
{
if (isset(Kohana::$php_errors[$code]))
{
// Use the human-readable error name
$code = Kohana::$php_errors[$code];
}
if (version_compare(PHP_VERSION, '5.3', '<'))
{
// Workaround for a bug in ErrorException::getTrace() that exists in
// all PHP 5.2 versions. @see http://bugs.php.net/bug.php?id=45895
for ($i = count($trace) - 1; $i > 0; --$i)
{
if (isset($trace[$i - 1]['args']))
{
// Re-position the args
$trace[$i]['args'] = $trace[$i - 1]['args'];
// Remove the args
unset($trace[$i - 1]['args']);
}
}
}
}
if ( ! headers_sent())
{
// Make sure the proper content type is sent with a 500 status
header('Content-Type: text/html; charset='.Kohana::$charset, TRUE, 500);
}
// Start an output buffer
ob_start();
// Include the exception HTML
include Kohana::find_file('views', Kohana::$error_view);
// Display the contents of the output buffer
echo ob_get_clean();
return TRUE;
}
catch (Exception $e)
{
// Clean the output buffer if one exists
ob_get_level() and ob_clean();
// Display the exception text
echo Kohana::exception_text($e), "\n";
// Exit with an error status
exit(1);
}
}
public static exception_text( object $e ) (defined in Kohana_Core)
Get a single line of text representing the exception:
Error [ Code ]: Message ~ File [ Line ]
Parameters
-
object$e required - Exception
Return Values
string
Source Code
public static function exception_text(Exception $e)
{
return sprintf('%s [ %s ]: %s ~ %s [ %d ]',
get_class($e), $e->getCode(), strip_tags($e->getMessage()), Kohana::debug_path($e->getFile()), $e->getLine());
}
public static find_file( string $dir , string $file [, string $ext = NULL , boolean $array = bool FALSE ] ) (defined in Kohana_Core)
Searches for a file in the Cascading Filesystem, and returns the path to the file that has the highest precedence, so that it can be included.
When searching the "config", "messages", or "i18n" directories, or when
the $array flag is set to true, an array of all the files that match
that path in the Cascading Filesystem will be returned.
These files will return arrays which must be merged together.
If no extension is given, the default extension (EXT set in
index.php) will be used.
// Returns an absolute path to views/template.php
Kohana::find_file('views', 'template');
// Returns an absolute path to media/css/style.css
Kohana::find_file('media', 'css/style', 'css');
// Returns an array of all the "mimes" configuration files
Kohana::find_file('config', 'mimes');
Parameters
-
string$dir required - Directory name (views, i18n, classes, extensions, etc.) -
string$file required - Filename with subdirectory -
string$ext = NULL - Extension to search for -
boolean$array = bool FALSE - Return an array of files?
Return Values
array- A list of files when $array is TRUEstring- Single file path
Source Code
public static function find_file($dir, $file, $ext = NULL, $array = FALSE)
{
if ($ext === NULL)
{
// Use the default extension
$ext = EXT;
}
elseif ($ext)
{
// Prefix the extension with a period
$ext = ".{$ext}";
}
else
{
// Use no extension
$ext = '';
}
// Create a partial path of the filename
$path = $dir.DIRECTORY_SEPARATOR.$file.$ext;
if (Kohana::$caching === TRUE AND isset(Kohana::$_files[$path.($array ? '_array' : '_path')]))
{
// This path has been cached
return Kohana::$_files[$path.($array ? '_array' : '_path')];
}
if (Kohana::$profiling === TRUE AND class_exists('Profiler', FALSE))
{
// Start a new benchmark
$benchmark = Profiler::start('Kohana', __FUNCTION__);
}
if ($array OR $dir === 'config' OR $dir === 'i18n' OR $dir === 'messages')
{
// Include paths must be searched in reverse
$paths = array_reverse(Kohana::$_paths);
// Array of files that have been found
$found = array();
foreach ($paths as $dir)
{
if (is_file($dir.$path))
{
// This path has a file, add it to the list
$found[] = $dir.$path;
}
}
}
else
{
// The file has not been found yet
$found = FALSE;
foreach (Kohana::$_paths as $dir)
{
if (is_file($dir.$path))
{
// A path has been found
$found = $dir.$path;
// Stop searching
break;
}
}
}
if (Kohana::$caching === TRUE)
{
// Add the path to the cache
Kohana::$_files[$path.($array ? '_array' : '_path')] = $found;
// Files have been changed
Kohana::$_files_changed = TRUE;
}
if (isset($benchmark))
{
// Stop the benchmark
Profiler::stop($benchmark);
}
return $found;
}
public static globals( ) (defined in Kohana_Core)
Reverts the effects of the register_globals PHP setting by unsetting
all global varibles except for the default super globals (GPCS, etc),
which is a potential security hole.
This is called automatically by Kohana::init if register_globals is
on.
Return Values
void
Source Code
public static function globals()
{
if (isset($_REQUEST['GLOBALS']) OR isset($_FILES['GLOBALS']))
{
// Prevent malicious GLOBALS overload attack
echo "Global variable overload attack detected! Request aborted.\n";
// Exit with an error status
exit(1);
}
// Get the variable names of all globals
$global_variables = array_keys($GLOBALS);
// Remove the standard global variables from the list
$global_variables = array_diff($global_variables, array(
'_COOKIE',
'_ENV',
'_GET',
'_FILES',
'_POST',
'_REQUEST',
'_SERVER',
'_SESSION',
'GLOBALS',
));
foreach ($global_variables as $name)
{
// Unset the global variable, effectively disabling register_globals
unset($GLOBALS[$name]);
}
}
public static include_paths( ) (defined in Kohana_Core)
Returns the the currently active include paths, including the application, system, and each module's path.
Return Values
array
Source Code
public static function include_paths()
{
return Kohana::$_paths;
}
public static init( [ array $settings = NULL ] ) (defined in Kohana_Core)
Initializes the environment:
- Disables register_globals and magic_quotes_gpc
- Determines the current environment
- Set global settings
- Sanitizes GET, POST, and COOKIE variables
- Converts GET, POST, and COOKIE variables to the global character set
The following settings can be set:
| Type | Setting | Description | Default Value |
|---|---|---|---|
string |
base_url | The base URL for your application. This should be the relative path from your DOCROOT to your index.php file, in other words, if Kohana is in a subfolder, set this to the subfolder name, otherwise leave it as the default. The leading slash is required, trailing slash is optional. |
"/" |
string |
index_file | The name of the front controller. This is used by Kohana to generate relative urls like HTML::anchor() and URL::base(). This is usually index.php. To remove index.php from your urls, set this to FALSE. |
"index.php" |
string |
charset | Character set used for all input and output | "utf-8" |
string |
cache_dir | Kohana's cache directory. Used by Kohana::cache for simple internal caching, like Fragments and [caching database queries](this should link somewhere). This has nothing to do with the Cache module. | APPPATH."cache" |
integer |
cache_life | Lifetime, in seconds, of items cached by Kohana::cache | 60 |
boolean |
errors | Should Kohana catch PHP errors and uncaught Exceptions and show the error_view. See Error Handling for more info. Recommended setting: TRUE while developing, FALSE on production servers. |
TRUE |
string |
error_view | The view to use to display errors. Only used when errors is TRUE. |
"kohana/error" |
boolean |
profile | Whether to enable the Profiler. Recommended setting: TRUE while developing, FALSE on production servers. |
TRUE |
boolean |
caching | Cache file locations to speed up Kohana::find_file. This has nothing to do with Kohana::cache, Fragments or the Cache module. Recommended setting: FALSE while developing, TRUE on production servers. |
FALSE |
Parameters
-
array$settings = NULL - Array of settings. See above.
Tags
Return Values
void
Source Code
public static function init(array $settings = NULL)
{
if (Kohana::$_init)
{
// Do not allow execution twice
return;
}
// Kohana is now initialized
Kohana::$_init = TRUE;
if (isset($settings['profile']))
{
// Enable profiling
Kohana::$profiling = (bool) $settings['profile'];
}
// Start an output buffer
ob_start();
if (defined('E_DEPRECATED'))
{
// E_DEPRECATED only exists in PHP >= 5.3.0
Kohana::$php_errors[E_DEPRECATED] = 'Deprecated';
}
if (isset($settings['errors']))
{
// Enable error handling
Kohana::$errors = (bool) $settings['errors'];
}
if (Kohana::$errors === TRUE)
{
// Enable Kohana exception handling, adds stack traces and error source.
set_exception_handler(array('Kohana', 'exception_handler'));
// Enable Kohana error handling, converts all PHP errors to exceptions.
set_error_handler(array('Kohana', 'error_handler'));
}
// Enable the Kohana shutdown handler, which catches E_FATAL errors.
register_shutdown_function(array('Kohana', 'shutdown_handler'));
if (isset($settings['error_view']))
{
if ( ! Kohana::find_file('views', $settings['error_view']))
{
throw new Kohana_Exception('Error view file does not exist: views/:file', array(
':file' => $settings['error_view'],
));
}
// Change the default error rendering
Kohana::$error_view = (string) $settings['error_view'];
}
if (ini_get('register_globals'))
{
// Reverse the effects of register_globals
Kohana::globals();
}
// Determine if we are running in a command line environment
Kohana::$is_cli = (PHP_SAPI === 'cli');
// Determine if we are running in a Windows environment
Kohana::$is_windows = (DIRECTORY_SEPARATOR === '\\');
// Determine if we are running in safe mode
Kohana::$safe_mode = (bool) ini_get('safe_mode');
if (isset($settings['cache_dir']))
{
if ( ! is_dir($settings['cache_dir']))
{
try
{
// Create the cache directory
mkdir($settings['cache_dir'], 0755, TRUE);
// Set permissions (must be manually set to fix umask issues)
chmod($settings['cache_dir'], 0755);
}
catch (Exception $e)
{
throw new Kohana_Exception('Could not create cache directory :dir',
array(':dir' => Kohana::debug_path($settings['cache_dir'])));
}
}
// Set the cache directory path
Kohana::$cache_dir = realpath($settings['cache_dir']);
}
else
{
// Use the default cache directory
Kohana::$cache_dir = APPPATH.'cache';
}
if ( ! is_writable(Kohana::$cache_dir))
{
throw new Kohana_Exception('Directory :dir must be writable',
array(':dir' => Kohana::debug_path(Kohana::$cache_dir)));
}
if (isset($settings['cache_life']))
{
// Set the default cache lifetime
Kohana::$cache_life = (int) $settings['cache_life'];
}
if (isset($settings['caching']))
{
// Enable or disable internal caching
Kohana::$caching = (bool) $settings['caching'];
}
if (Kohana::$caching === TRUE)
{
// Load the file path cache
Kohana::$_files = Kohana::cache('Kohana::find_file()');
}
if (isset($settings['charset']))
{
// Set the system character set
Kohana::$charset = strtolower($settings['charset']);
}
if (function_exists('mb_internal_encoding'))
{
// Set the MB extension encoding to the same character set
mb_internal_encoding(Kohana::$charset);
}
if (isset($settings['base_url']))
{
// Set the base URL
Kohana::$base_url = rtrim($settings['base_url'], '/').'/';
}
if (isset($settings['index_file']))
{
// Set the index file
Kohana::$index_file = trim($settings['index_file'], '/');
}
// Determine if the extremely evil magic quotes are enabled
Kohana::$magic_quotes = (bool) get_magic_quotes_gpc();
// Sanitize all request variables
$_GET = Kohana::sanitize($_GET);
$_POST = Kohana::sanitize($_POST);
$_COOKIE = Kohana::sanitize($_COOKIE);
// Load the logger
Kohana::$log = Kohana_Log::instance();
// Load the config
Kohana::$config = Kohana_Config::instance();
}
public static list_files( [ string $directory = NULL , array $paths = NULL ] ) (defined in Kohana_Core)
Recursively finds all of the files in the specified directory at any location in the Cascading Filesystem, and returns an array of all the files found, sorted alphabetically.
// Find all view files.
$views = Kohana::list_files('views');
Parameters
-
string$directory = NULL - Directory name -
array$paths = NULL - List of paths to search
Return Values
array
Source Code
public static function list_files($directory = NULL, array $paths = NULL)
{
if ($directory !== NULL)
{
// Add the directory separator
$directory .= DIRECTORY_SEPARATOR;
}
if ($paths === NULL)
{
// Use the default paths
$paths = Kohana::$_paths;
}
// Create an array for the files
$found = array();
foreach ($paths as $path)
{
if (is_dir($path.$directory))
{
// Create a new directory iterator
$dir = new DirectoryIterator($path.$directory);
foreach ($dir as $file)
{
// Get the file name
$filename = $file->getFilename();
if ($filename[0] === '.' OR $filename[strlen($filename)-1] === '~')
{
// Skip all hidden files and UNIX backup files
continue;
}
// Relative filename is the array key
$key = $directory.$filename;
if ($file->isDir())
{
if ($sub_dir = Kohana::list_files($key, $paths))
{
if (isset($found[$key]))
{
// Append the sub-directory list
$found[$key] += $sub_dir;
}
else
{
// Create a new sub-directory list
$found[$key] = $sub_dir;
}
}
}
else
{
if ( ! isset($found[$key]))
{
// Add new files to the list
$found[$key] = realpath($file->getPathName());
}
}
}
}
}
// Sort the results alphabetically
ksort($found);
return $found;
}
public static load( string $file ) (defined in Kohana_Core)
Loads a file within a totally empty scope and returns the output:
$foo = Kohana::load('foo.php');
Parameters
-
string$file required
Return Values
mixed
Source Code
public static function load($file)
{
return include $file;
}
public static message( string $file [, string $path = NULL , mixed $default = NULL ] ) (defined in Kohana_Core)
Get a message from a file. Messages are arbitary strings that are stored
in the messages/ directory and reference by a key. Translation is not
performed on the returned values. See message files
for more information.
// Get "username" from messages/text.php
$username = Kohana::message('text', 'username');
Parameters
-
string$file required - File name -
string$path = NULL - Key path to get -
mixed$default = NULL - Default value if the path does not exist
Tags
Return Values
string- Message string for the given patharray- Complete message list, when no path is specified
Source Code
public static function message($file, $path = NULL, $default = NULL)
{
static $messages;
if ( ! isset($messages[$file]))
{
// Create a new message list
$messages[$file] = array();
if ($files = Kohana::find_file('messages', $file))
{
foreach ($files as $f)
{
// Combine all the messages recursively
$messages[$file] = Arr::merge($messages[$file], Kohana::load($f));
}
}
}
if ($path === NULL)
{
// Return all of the messages
return $messages[$file];
}
else
{
// Get a message using the path
return Arr::path($messages[$file], $path, $default);
}
}
public static modules( [ array $modules = NULL ] ) (defined in Kohana_Core)
Changes the currently enabled modules. Module paths may be relative or absolute, but must point to a directory:
Kohana::modules(array('modules/foo', MODPATH.'bar'));
Parameters
-
array$modules = NULL - List of module paths
Return Values
array- Enabled modules
Source Code
public static function modules(array $modules = NULL)
{
if ($modules === NULL)
{
// Not changing modules, just return the current set
return Kohana::$_modules;
}
// Start a new list of include paths, APPPATH first
$paths = array(APPPATH);
foreach ($modules as $name => $path)
{
if (is_dir($path))
{
// Add the module to include paths
$paths[] = $modules[$name] = realpath($path).DIRECTORY_SEPARATOR;
}
else
{
// This module is invalid, remove it
unset($modules[$name]);
}
}
// Finish the include paths by adding SYSPATH
$paths[] = SYSPATH;
// Set the new include paths
Kohana::$_paths = $paths;
// Set the current module list
Kohana::$_modules = $modules;
foreach (Kohana::$_modules as $path)
{
$init = $path.'init'.EXT;
if (is_file($init))
{
// Include the module initialization file once
require_once $init;
}
}
return Kohana::$_modules;
}
public static sanitize( mixed $value ) (defined in Kohana_Core)
Recursively sanitizes an input variable:
- Strips slashes if magic quotes are enabled
- Normalizes all newlines to LF
Parameters
-
mixed$value required - Any variable
Return Values
mixed- Sanitized variable
Source Code
public static function sanitize($value)
{
if (is_array($value) OR is_object($value))
{
foreach ($value as $key => $val)
{
// Recursively clean each value
$value[$key] = Kohana::sanitize($val);
}
}
elseif (is_string($value))
{
if (Kohana::$magic_quotes === TRUE)
{
// Remove slashes added by magic quotes
$value = stripslashes($value);
}
if (strpos($value, "\r") !== FALSE)
{
// Standardize newlines
$value = str_replace(array("\r\n", "\r"), "\n", $value);
}
}
return $value;
}
public static shutdown_handler( ) (defined in Kohana_Core)
Catches errors that are not caught by the error handler, such as E_PARSE.
Tags
Return Values
void
Source Code
public static function shutdown_handler()
{
if ( ! Kohana::$_init)
{
// Do not execute when not active
return;
}
try
{
if (Kohana::$caching === TRUE AND Kohana::$_files_changed === TRUE)
{
// Write the file path cache
Kohana::cache('Kohana::find_file()', Kohana::$_files);
}
}
catch (Exception $e)
{
// Pass the exception to the handler
Kohana::exception_handler($e);
}
if (Kohana::$errors AND $error = error_get_last() AND in_array($error['type'], Kohana::$shutdown_errors))
{
// Clean the output buffer
ob_get_level() and ob_clean();
// Fake an exception for nice debugging
Kohana::exception_handler(new ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line']));
// Shutdown now to avoid a "death loop"
exit(1);
}
}
public static trace( [ string $trace = NULL ] ) (defined in Kohana_Core)
Returns an array of HTML strings that represent each step in the backtrace.
// Displays the entire current backtrace
echo implode('<br/>', Kohana::trace());
Parameters
-
string$trace = NULL - Path to debug
Return Values
string
Source Code
public static function trace(array $trace = NULL)
{
if ($trace === NULL)
{
// Start a new trace
$trace = debug_backtrace();
}
// Non-standard function calls
$statements = array('include', 'include_once', 'require', 'require_once');
$output = array();
foreach ($trace as $step)
{
if ( ! isset($step['function']))
{
// Invalid trace step
continue;
}
if (isset($step['file']) AND isset($step['line']))
{
// Include the source of this step
$source = Kohana::debug_source($step['file'], $step['line']);
}
if (isset($step['file']))
{
$file = $step['file'];
if (isset($step['line']))
{
$line = $step['line'];
}
}
// function()
$function = $step['function'];
if (in_array($step['function'], $statements))
{
if (empty($step['args']))
{
// No arguments
$args = array();
}
else
{
// Sanitize the file path
$args = array(Kohana::debug_path($step['args'][0]));
}
}
elseif (isset($step['args']))
{
if ( ! function_exists($step['function']) OR strpos($step['function'], '{closure}') !== FALSE)
{
// Introspection on closures or language constructs in a stack trace is impossible
$params = NULL;
}
else
{
if (isset($step['class']))
{
if (method_exists($step['class'], $step['function']))
{
$reflection = new ReflectionMethod($step['class'], $step['function']);
}
else
{
$reflection = new ReflectionMethod($step['class'], '__call');
}
}
else
{
$reflection = new ReflectionFunction($step['function']);
}
// Get the function parameters
$params = $reflection->getParameters();
}
$args = array();
foreach ($step['args'] as $i => $arg)
{
if (isset($params[$i]))
{
// Assign the argument by the parameter name
$args[$params[$i]->name] = $arg;
}
else
{
// Assign the argument by number
$args[$i] = $arg;
}
}
}
if (isset($step['class']))
{
// Class->method() or Class::method()
$function = $step['class'].$step['type'].$step['function'];
}
$output[] = array(
'function' => $function,
'args' => isset($args) ? $args : NULL,
'file' => isset($file) ? $file : NULL,
'line' => isset($line) ? $line : NULL,
'source' => isset($source) ? $source : NULL,
);
unset($function, $args, $file, $line, $source);
}
return $output;
}
protected static _dump( mixed & $var [, integer $length = integer 128 , integer $level = integer 0 ] ) (defined in Kohana_Core)
Helper for Kohana::dump(), handles recursion in arrays and objects.
Parameters
-
byref mixed$var required - Variable to dump -
integer$length = integer 128 - Maximum length of strings -
integer$level = integer 0 - Recursion level (internal)
Return Values
string
Source Code
protected static function _dump( & $var, $length = 128, $level = 0)
{
if ($var === NULL)
{
return '<small>NULL</small>';
}
elseif (is_bool($var))
{
return '<small>bool</small> '.($var ? 'TRUE' : 'FALSE');
}
elseif (is_float($var))
{
return '<small>float</small> '.$var;
}
elseif (is_resource($var))
{
if (($type = get_resource_type($var)) === 'stream' AND $meta = stream_get_meta_data($var))
{
$meta = stream_get_meta_data($var);
if (isset($meta['uri']))
{
$file = $meta['uri'];
if (function_exists('stream_is_local'))
{
// Only exists on PHP >= 5.2.4
if (stream_is_local($file))
{
$file = Kohana::debug_path($file);
}
}
return '<small>resource</small><span>('.$type.')</span> '.htmlspecialchars($file, ENT_NOQUOTES, Kohana::$charset);
}
}
else
{
return '<small>resource</small><span>('.$type.')</span>';
}
}
elseif (is_string($var))
{
// Clean invalid multibyte characters. iconv is only invoked
// if there are non ASCII characters in the string, so this
// isn't too much of a hit.
$var = UTF8::clean($var, Kohana::$charset);
if (UTF8::strlen($var) > $length)
{
// Encode the truncated string
$str = htmlspecialchars(UTF8::substr($var, 0, $length), ENT_NOQUOTES, Kohana::$charset).' …';
}
else
{
// Encode the string
$str = htmlspecialchars($var, ENT_NOQUOTES, Kohana::$charset);
}
if (Kohana::$debug_escape_quotes)
{
// Escape strings (for syntax highlighters, mostly)
$str = str_replace('"', '\\"', $str);
}
return '<small>string</small><span>('.strlen($var).')</span> "'.$str.'"';
}
elseif (is_array($var))
{
$output = array();
// Indentation for this variable
$space = str_repeat($s = ' ', $level);
static $marker;
if ($marker === NULL)
{
// Make a unique marker
$marker = uniqid("\x00");
}
if (empty($var))
{
// Do nothing
}
elseif (isset($var[$marker]))
{
$output[] = "(\n$space$s*RECURSION*\n$space)";
}
elseif ($level < 5)
{
$output[] = "<span>(";
$var[$marker] = TRUE;
foreach ($var as $key => & $val)
{
if ($key === $marker) continue;
if ( ! is_int($key))
{
$key = '"'.htmlspecialchars($key, ENT_NOQUOTES, self::$charset).'"';
}
$output[] = "$space$s$key => ".Kohana::_dump($val, $length, $level + 1);
}
unset($var[$marker]);
$output[] = "$space)</span>";
}
else
{
// Depth too great
$output[] = "(\n$space$s...\n$space)";
}
return '<small>array</small><span>('.count($var).')</span> '.implode("\n", $output);
}
elseif (is_object($var))
{
// Copy the object as an array
$array = (array) $var;
$output = array();
// Indentation for this variable
$space = str_repeat($s = ' ', $level);
$hash = spl_object_hash($var);
// Objects that are being dumped
static $objects = array();
if (empty($var))
{
// Do nothing
}
elseif (isset($objects[$hash]))
{
$output[] = "{\n$space$s*RECURSION*\n$space}";
}
elseif ($level < 10)
{
$output[] = "<code>{";
$objects[$hash] = TRUE;
foreach ($array as $key => & $val)
{
if ($key[0] === "\x00")
{
// Determine if the access is protected or protected
$access = '<small>'.(($key[1] === '*') ? 'protected' : 'private').'</small>';
// Remove the access level from the variable name
$key = substr($key, strrpos($key, "\x00") + 1);
}
else
{
$access = '<small>public</small>';
}
$output[] = "$space$s$access $key => ".Kohana::_dump($val, $length, $level + 1);
}
unset($objects[$hash]);
$output[] = "$space}</code>";
}
else
{
// Depth too great
$output[] = "{\n$space$s...\n$space}";
}
return '<small>object</small> <span>'.get_class($var).'('.count($array).')</span> '.implode("\n", $output);
}
else
{
return '<small>'.gettype($var).'</small> '.htmlspecialchars(print_r($var, TRUE), ENT_NOQUOTES, Kohana::$charset);
}
}