From 9b6663f87a7e679ffba691cf516191fc840cf978 Mon Sep 17 00:00:00 2001 From: Bharat Mediratta Date: Tue, 24 Nov 2009 19:20:36 -0800 Subject: Update to Kohana r4684 which is now Kohana 2.4 and has substantial changes. --- system/core/Benchmark.php | 9 +- system/core/Bootstrap.php | 58 -- system/core/Event.php | 81 +- system/core/Kohana.php | 1166 ++++++--------------------- system/core/Kohana_Config.php | 331 ++++++++ system/core/Kohana_Exception.php | 619 ++++++++++++++ system/core/utf8.php | 743 ----------------- system/core/utf8/from_unicode.php | 68 -- system/core/utf8/ltrim.php | 22 - system/core/utf8/ord.php | 88 -- system/core/utf8/rtrim.php | 22 - system/core/utf8/str_ireplace.php | 70 -- system/core/utf8/str_pad.php | 54 -- system/core/utf8/str_split.php | 33 - system/core/utf8/strcasecmp.php | 19 - system/core/utf8/strcspn.php | 30 - system/core/utf8/stristr.php | 28 - system/core/utf8/strlen.php | 21 - system/core/utf8/strpos.php | 30 - system/core/utf8/strrev.php | 18 - system/core/utf8/strrpos.php | 30 - system/core/utf8/strspn.php | 30 - system/core/utf8/strtolower.php | 84 -- system/core/utf8/strtoupper.php | 84 -- system/core/utf8/substr.php | 75 -- system/core/utf8/substr_replace.php | 22 - system/core/utf8/to_unicode.php | 141 ---- system/core/utf8/transliterate_to_ascii.php | 77 -- system/core/utf8/trim.php | 17 - system/core/utf8/ucfirst.php | 18 - system/core/utf8/ucwords.php | 26 - 31 files changed, 1230 insertions(+), 2884 deletions(-) delete mode 100644 system/core/Bootstrap.php create mode 100644 system/core/Kohana_Config.php create mode 100644 system/core/Kohana_Exception.php delete mode 100644 system/core/utf8.php delete mode 100644 system/core/utf8/from_unicode.php delete mode 100644 system/core/utf8/ltrim.php delete mode 100644 system/core/utf8/ord.php delete mode 100644 system/core/utf8/rtrim.php delete mode 100644 system/core/utf8/str_ireplace.php delete mode 100644 system/core/utf8/str_pad.php delete mode 100644 system/core/utf8/str_split.php delete mode 100644 system/core/utf8/strcasecmp.php delete mode 100644 system/core/utf8/strcspn.php delete mode 100644 system/core/utf8/stristr.php delete mode 100644 system/core/utf8/strlen.php delete mode 100644 system/core/utf8/strpos.php delete mode 100644 system/core/utf8/strrev.php delete mode 100644 system/core/utf8/strrpos.php delete mode 100644 system/core/utf8/strspn.php delete mode 100644 system/core/utf8/strtolower.php delete mode 100644 system/core/utf8/strtoupper.php delete mode 100644 system/core/utf8/substr.php delete mode 100644 system/core/utf8/substr_replace.php delete mode 100644 system/core/utf8/to_unicode.php delete mode 100644 system/core/utf8/transliterate_to_ascii.php delete mode 100644 system/core/utf8/trim.php delete mode 100644 system/core/utf8/ucfirst.php delete mode 100644 system/core/utf8/ucwords.php (limited to 'system/core') diff --git a/system/core/Benchmark.php b/system/core/Benchmark.php index ce230f11..4b2f78b0 100644 --- a/system/core/Benchmark.php +++ b/system/core/Benchmark.php @@ -2,12 +2,12 @@ /** * Simple benchmarking. * - * $Id: Benchmark.php 4149 2009-04-01 13:32:50Z Shadowhand $ + * $Id: Benchmark.php 4679 2009-11-10 01:45:52Z isaiah $ * * @package Core * @author Kohana Team - * @copyright (c) 2007 Kohana Team - * @license http://kohanaphp.com/license.html + * @copyright (c) 2007-2009 Kohana Team + * @license http://kohanaphp.com/license */ final class Benchmark { @@ -22,6 +22,9 @@ final class Benchmark { */ public static function start($name) { + if (isset(self::$marks[$name]) AND self::$marks[$name][0]['stop'] === FALSE) + throw new Kohana_Exception('A benchmark named :name is already running.', array(':name' => $name)); + if ( ! isset(self::$marks[$name])) { self::$marks[$name] = array(); diff --git a/system/core/Bootstrap.php b/system/core/Bootstrap.php deleted file mode 100644 index edfb086d..00000000 --- a/system/core/Bootstrap.php +++ /dev/null @@ -1,58 +0,0 @@ - $event_callback) + foreach (Event::$events[$name] as $i => $event_callback) { if ($callback === $event_callback) { - unset(self::$events[$name][$i]); + unset(Event::$events[$name][$i]); } } } @@ -198,24 +199,24 @@ final class Event { */ public static function run($name, & $data = NULL) { - if ( ! empty(self::$events[$name])) + if ( ! empty(Event::$events[$name])) { // So callbacks can access Event::$data - self::$data =& $data; - $callbacks = self::get($name); + Event::$data =& $data; + $callbacks = Event::get($name); foreach ($callbacks as $callback) { - call_user_func($callback); + call_user_func_array($callback, array(&$data)); } // Do this to prevent data from getting 'stuck' $clear_data = ''; - self::$data =& $clear_data; + Event::$data =& $clear_data; } // The event has been run! - self::$has_run[$name] = $name; + Event::$has_run[$name] = $name; } /** @@ -226,7 +227,7 @@ final class Event { */ public static function has_run($name) { - return isset(self::$has_run[$name]); + return isset(Event::$has_run[$name]); } } // End Event \ No newline at end of file diff --git a/system/core/Kohana.php b/system/core/Kohana.php index 8027975d..5258d635 100644 --- a/system/core/Kohana.php +++ b/system/core/Kohana.php @@ -2,60 +2,48 @@ /** * Provides Kohana-specific helper functions. This is where the magic happens! * - * $Id: Kohana.php 4372 2009-05-28 17:00:34Z ixmatus $ + * $Id: Kohana.php 4679 2009-11-10 01:45:52Z isaiah $ * * @package Core * @author Kohana Team - * @copyright (c) 2007-2008 Kohana Team - * @license http://kohanaphp.com/license.html + * @copyright (c) 2007-2009 Kohana Team + * @license http://kohanaphp.com/license */ -final class Kohana { + +// Test of Kohana is running in Windows +define('KOHANA_IS_WIN', DIRECTORY_SEPARATOR === '\\'); + +abstract class Kohana_Core { + + const VERSION = '2.4'; + const CODENAME = 'no_codename'; + const CHARSET = 'UTF-8'; + const LOCALE = 'en_US'; // The singleton instance of the controller public static $instance; // Output buffering level - private static $buffer_level; - - // Will be set to TRUE when an exception is caught - public static $has_error = FALSE; + protected static $buffer_level; // The final output that will displayed by Kohana public static $output = ''; - // The current user agent - public static $user_agent; - // The current locale public static $locale; - // Configuration - private static $configuration; - // Include paths - private static $include_paths; - - // Logged messages - private static $log; + protected static $include_paths; // Cache lifetime - private static $cache_lifetime; - - // Log levels - private static $log_levels = array - ( - 'error' => 1, - 'alert' => 2, - 'info' => 3, - 'debug' => 4, - ); + protected static $cache_lifetime; // Internal caches and write status - private static $internal_cache = array(); - private static $write_cache; - private static $internal_cache_path; - private static $internal_cache_key; - private static $internal_cache_encrypt; + protected static $internal_cache = array(); + protected static $write_cache; + protected static $internal_cache_path; + protected static $internal_cache_key; + protected static $internal_cache_encrypt; /** * Sets up the PHP environment. Adds error/exception handling, output @@ -75,10 +63,12 @@ final class Kohana { { static $run; - // This function can only be run once + // Only run this function once if ($run === TRUE) return; + $run = TRUE; + // Start the environment setup benchmark Benchmark::start(SYSTEM_BENCHMARK.'_environment_setup'); @@ -91,89 +81,86 @@ final class Kohana { // Define database error constant define('E_DATABASE_ERROR', 44); - if (self::$cache_lifetime = self::config('core.internal_cache')) + // Set the default charset for mb_* functions + mb_internal_encoding(Kohana::CHARSET); + + if (Kohana_Config::instance()->loaded() === FALSE) + { + // Re-parse the include paths + Kohana::include_paths(TRUE); + } + + if (Kohana::$cache_lifetime = Kohana::config('core.internal_cache')) { // Are we using encryption for caches? - self::$internal_cache_encrypt = self::config('core.internal_cache_encrypt'); - - if(self::$internal_cache_encrypt===TRUE) + Kohana::$internal_cache_encrypt = Kohana::config('core.internal_cache_encrypt'); + + if(Kohana::$internal_cache_encrypt===TRUE) { - self::$internal_cache_key = self::config('core.internal_cache_key'); - + Kohana::$internal_cache_key = Kohana::config('core.internal_cache_key'); + // Be sure the key is of acceptable length for the mcrypt algorithm used - self::$internal_cache_key = substr(self::$internal_cache_key, 0, 24); + Kohana::$internal_cache_key = substr(Kohana::$internal_cache_key, 0, 24); } - + // Set the directory to be used for the internal cache - if ( ! self::$internal_cache_path = self::config('core.internal_cache_path')) + if ( ! Kohana::$internal_cache_path = Kohana::config('core.internal_cache_path')) { - self::$internal_cache_path = APPPATH.'cache/'; + Kohana::$internal_cache_path = APPPATH.'cache/'; } // Load cached configuration and language files - self::$internal_cache['configuration'] = self::cache('configuration', self::$cache_lifetime); - self::$internal_cache['language'] = self::cache('language', self::$cache_lifetime); + Kohana::$internal_cache['configuration'] = Kohana::cache('configuration', Kohana::$cache_lifetime); + Kohana::$internal_cache['language'] = Kohana::cache('language', Kohana::$cache_lifetime); // Load cached file paths - self::$internal_cache['find_file_paths'] = self::cache('find_file_paths', self::$cache_lifetime); + Kohana::$internal_cache['find_file_paths'] = Kohana::cache('find_file_paths', Kohana::$cache_lifetime); // Enable cache saving - Event::add('system.shutdown', array(__CLASS__, 'internal_cache_save')); - } - - // Disable notices and "strict" errors - $ER = error_reporting(~E_NOTICE & ~E_STRICT); - - // Set the user agent - self::$user_agent = ( ! empty($_SERVER['HTTP_USER_AGENT']) ? trim($_SERVER['HTTP_USER_AGENT']) : ''); - - if (function_exists('date_default_timezone_set')) - { - $timezone = self::config('locale.timezone'); - - // Set default timezone, due to increased validation of date settings - // which cause massive amounts of E_NOTICEs to be generated in PHP 5.2+ - date_default_timezone_set(empty($timezone) ? date_default_timezone_get() : $timezone); + Event::add('system.shutdown', array('Kohana', 'internal_cache_save')); } - // Restore error reporting - error_reporting($ER); - // Start output buffering - ob_start(array(__CLASS__, 'output_buffer')); + ob_start(array('Kohana', 'output_buffer')); // Save buffering level - self::$buffer_level = ob_get_level(); + Kohana::$buffer_level = ob_get_level(); // Set autoloader spl_autoload_register(array('Kohana', 'auto_load')); - // Set error handler - set_error_handler(array('Kohana', 'exception_handler')); - - // Set exception handler - set_exception_handler(array('Kohana', 'exception_handler')); + // Register a shutdown function to handle system.shutdown events + register_shutdown_function(array('Kohana', 'shutdown')); // Send default text/html UTF-8 header - header('Content-Type: text/html; charset=UTF-8'); + header('Content-Type: text/html; charset='.Kohana::CHARSET); + + // Load i18n + new I18n; + + // Enable exception handling + Kohana_Exception::enable(); + + // Enable error handling + Kohana_PHP_Exception::enable(); // Load locales - $locales = self::config('locale.language'); + $locales = Kohana::config('locale.language'); - // Make first locale UTF-8 - $locales[0] .= '.UTF-8'; + // Make first locale the defined Kohana charset + $locales[0] .= '.'.Kohana::CHARSET; // Set locale information - self::$locale = setlocale(LC_ALL, $locales); + Kohana::$locale = setlocale(LC_ALL, $locales); - if (self::$configuration['core']['log_threshold'] > 0) - { - // Set the log directory - self::log_directory(self::$configuration['core']['log_directory']); + // Default to the default locale when none of the user defined ones where accepted + Kohana::$locale = ! Kohana::$locale ? Kohana::LOCALE.'.'.Kohana::CHARSET : Kohana::$locale; - // Enable log writing at shutdown - register_shutdown_function(array(__CLASS__, 'log_save')); - } + // Set locale for the I18n system + I18n::set_locale(Kohana::$locale); + + // Set and validate the timezone + date_default_timezone_set(Kohana::config('locale.timezone')); // Enable Kohana routing Event::add('system.routing', array('Router', 'find_uri')); @@ -183,15 +170,12 @@ final class Kohana { Event::add('system.execute', array('Kohana', 'instance')); // Enable Kohana 404 pages - Event::add('system.404', array('Kohana', 'show_404')); - - // Enable Kohana output handling - Event::add('system.shutdown', array('Kohana', 'shutdown')); + Event::add('system.404', array('Kohana_404_Exception', 'trigger')); - if (self::config('core.enable_hooks') === TRUE) + if (Kohana::config('core.enable_hooks') === TRUE) { // Find all the hook files - $hooks = self::list_files('hooks', TRUE); + $hooks = Kohana::list_files('hooks', TRUE); foreach ($hooks as $file) { @@ -200,13 +184,38 @@ final class Kohana { } } - // Setup is complete, prevent it from being run again - $run = TRUE; - // Stop the environment setup routine Benchmark::stop(SYSTEM_BENCHMARK.'_environment_setup'); } + /** + * Cleans up the PHP environment. Disables error/exception handling and the + * auto-loading method and closes the output buffer. + * + * This method does not need to be called during normal system execution, + * however in some advanced situations it can be helpful. @see #1781 + * + * @return void + */ + public static function cleanup() + { + static $run; + + // Only run this function once + if ($run === TRUE) + return; + + $run = TRUE; + + Kohana_Exception::disable(); + + Kohana_PHP_Exception::disable(); + + spl_autoload_unregister(array('Kohana', 'auto_load')); + + Kohana::close_buffers(); + } + /** * Loads the controller and initializes it. Runs the pre_controller, * post_controller_constructor, and post_controller events. Triggers @@ -218,12 +227,12 @@ final class Kohana { */ public static function & instance() { - if (self::$instance === NULL) + if (Kohana::$instance === NULL) { Benchmark::start(SYSTEM_BENCHMARK.'_controller_setup'); // Include the Controller file - require Router::$controller_path; + require_once Router::$controller_path; try { @@ -297,7 +306,7 @@ final class Kohana { Benchmark::stop(SYSTEM_BENCHMARK.'_controller_execution'); } - return self::$instance; + return Kohana::$instance; } /** @@ -312,279 +321,44 @@ final class Kohana { if ($process === TRUE) { // Add APPPATH as the first path - self::$include_paths = array(APPPATH); + Kohana::$include_paths = array(APPPATH); - foreach (self::$configuration['core']['modules'] as $path) + foreach (Kohana::config('core.modules') as $path) { if ($path = str_replace('\\', '/', realpath($path))) { // Add a valid path - self::$include_paths[] = $path.'/'; + Kohana::$include_paths[] = $path.'/'; } } // Add SYSPATH as the last path - self::$include_paths[] = SYSPATH; - - // Local fix for Kohana Ticket:2276 - self::$internal_cache['find_file_paths'] = array(); - if ( ! isset(self::$write_cache['find_file_paths'])) - { - // Write cache at shutdown - self::$write_cache['find_file_paths'] = TRUE; - } - } - - return self::$include_paths; - } - - /** - * Get a config item or group. - * - * @param string item name - * @param boolean force a forward slash (/) at the end of the item - * @param boolean is the item required? - * @return mixed - */ - public static function config($key, $slash = FALSE, $required = TRUE) - { - if (self::$configuration === NULL) - { - // Load core configuration - self::$configuration['core'] = self::config_load('core'); - - // Re-parse the include paths - self::include_paths(TRUE); - } - - // Get the group name from the key - $group = explode('.', $key, 2); - $group = $group[0]; + Kohana::$include_paths[] = SYSPATH; - if ( ! isset(self::$configuration[$group])) - { - // Load the configuration group - self::$configuration[$group] = self::config_load($group, $required); - } - - // Get the value of the key string - $value = self::key_string(self::$configuration, $key); - - if ($slash === TRUE AND is_string($value) AND $value !== '') - { - // Force the value to end with "/" - $value = rtrim($value, '/').'/'; - } - - return $value; - } - - /** - * Sets a configuration item, if allowed. - * - * @param string config key string - * @param string config value - * @return boolean - */ - public static function config_set($key, $value) - { - // Do this to make sure that the config array is already loaded - self::config($key); - - if (substr($key, 0, 7) === 'routes.') - { - // Routes cannot contain sub keys due to possible dots in regex - $keys = explode('.', $key, 2); - } - else - { - // Convert dot-noted key string to an array - $keys = explode('.', $key); - } - - // Used for recursion - $conf =& self::$configuration; - $last = count($keys) - 1; - - foreach ($keys as $i => $k) - { - if ($i === $last) + // Clear cached include paths + self::$internal_cache['find_file_paths'] = array(); + if ( ! isset(self::$write_cache['find_file_paths'])) { - $conf[$k] = $value; + // Write cache at shutdown + self::$write_cache['find_file_paths'] = TRUE; } - else - { - $conf =& $conf[$k]; - } - } - if ($key === 'core.modules') - { - // Reprocess the include paths - self::include_paths(TRUE); } - return TRUE; + return Kohana::$include_paths; } /** - * Load a config file. + * Get a config item or group proxies Kohana_Config. * - * @param string config filename, without extension - * @param boolean is the file required? - * @return array - */ - public static function config_load($name, $required = TRUE) - { - if ($name === 'core') - { - // Load the application configuration file - require APPPATH.'config/config'.EXT; - - if ( ! isset($config['site_domain'])) - { - // Invalid config file - die('Your Kohana application configuration file is not valid.'); - } - - return $config; - } - - if (isset(self::$internal_cache['configuration'][$name])) - return self::$internal_cache['configuration'][$name]; - - // Load matching configs - $configuration = array(); - - if ($files = self::find_file('config', $name, $required)) - { - foreach ($files as $file) - { - require $file; - - if (isset($config) AND is_array($config)) - { - // Merge in configuration - $configuration = array_merge($configuration, $config); - } - } - } - - if ( ! isset(self::$write_cache['configuration'])) - { - // Cache has changed - self::$write_cache['configuration'] = TRUE; - } - - return self::$internal_cache['configuration'][$name] = $configuration; - } - - /** - * Clears a config group from the cached configuration. - * - * @param string config group - * @return void - */ - public static function config_clear($group) - { - // Remove the group from config - unset(self::$configuration[$group], self::$internal_cache['configuration'][$group]); - - if ( ! isset(self::$write_cache['configuration'])) - { - // Cache has changed - self::$write_cache['configuration'] = TRUE; - } - } - - /** - * Add a new message to the log. - * - * @param string type of message - * @param string message text - * @return void - */ - public static function log($type, $message) - { - if (self::$log_levels[$type] <= self::$configuration['core']['log_threshold']) - { - $message = array(date('Y-m-d H:i:s P'), $type, $message); - - // Run the system.log event - Event::run('system.log', $message); - - self::$log[] = $message; - } - } - - /** - * Save all currently logged messages. - * - * @return void - */ - public static function log_save() - { - if (empty(self::$log) OR self::$configuration['core']['log_threshold'] < 1) - return; - - // Filename of the log - $filename = self::log_directory().date('Y-m-d').'.log'.EXT; - - if ( ! is_file($filename)) - { - // Write the SYSPATH checking header - file_put_contents($filename, - ''.PHP_EOL.PHP_EOL); - - // Prevent external writes - chmod($filename, 0644); - } - - // Messages to write - $messages = array(); - - do - { - // Load the next mess - list ($date, $type, $text) = array_shift(self::$log); - - // Add a new message line - $messages[] = $date.' --- '.$type.': '.$text; - } - while ( ! empty(self::$log)); - - // Write messages to log file - file_put_contents($filename, implode(PHP_EOL, $messages).PHP_EOL, FILE_APPEND); - } - - /** - * Get or set the logging directory. - * - * @param string new log directory - * @return string + * @param string item name + * @param boolean force a forward slash (/) at the end of the item + * @param boolean is the item required? + * @return mixed */ - public static function log_directory($dir = NULL) + public static function config($key, $slash = FALSE, $required = FALSE) { - static $directory; - - if ( ! empty($dir)) - { - // Get the directory path - $dir = realpath($dir); - - if (is_dir($dir) AND is_writable($dir)) - { - // Change the log directory - $directory = str_replace('\\', '/', $dir).'/'; - } - else - { - // Log directory is invalid - throw new Kohana_Exception('core.log_dir_unwritable', $dir); - } - } - - return $directory; + return Kohana_Config::instance()->get($key,$slash,$required); } /** @@ -599,7 +373,7 @@ final class Kohana { { if ($lifetime > 0) { - $path = self::$internal_cache_path.'kohana_'.$name; + $path = Kohana::$internal_cache_path.'kohana_'.$name; if (is_file($path)) { @@ -607,17 +381,17 @@ final class Kohana { if ((time() - filemtime($path)) < $lifetime) { // Cache is valid! Now, do we need to decrypt it? - if(self::$internal_cache_encrypt===TRUE) + if(Kohana::$internal_cache_encrypt===TRUE) { $data = file_get_contents($path); - + $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); - - $decrypted_text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, self::$internal_cache_key, $data, MCRYPT_MODE_ECB, $iv); - + + $decrypted_text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, Kohana::$internal_cache_key, $data, MCRYPT_MODE_ECB, $iv); + $cache = unserialize($decrypted_text); - + // If the key changed, delete the cache file if(!$cache) unlink($path); @@ -656,7 +430,7 @@ final class Kohana { if ($lifetime < 1) return FALSE; - $path = self::$internal_cache_path.'kohana_'.$name; + $path = Kohana::$internal_cache_path.'kohana_'.$name; if ($data === NULL) { @@ -666,15 +440,15 @@ final class Kohana { else { // Using encryption? Encrypt the data when we write it - if(self::$internal_cache_encrypt===TRUE) + if(Kohana::$internal_cache_encrypt===TRUE) { // Encrypt and write data to cache file $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); - + // Serialize and encrypt! - $encrypted_text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, self::$internal_cache_key, serialize($data), MCRYPT_MODE_ECB, $iv); - + $encrypted_text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, Kohana::$internal_cache_key, serialize($data), MCRYPT_MODE_ECB, $iv); + return (bool) file_put_contents($path, $encrypted_text); } else @@ -699,15 +473,16 @@ final class Kohana { // Run the send_headers event Event::run('system.send_headers'); } - - self::$output = $output; - + + // Set final output + Kohana::$output = $output; + // Set and return the final output - return self::$output; + return Kohana::$output; } /** - * Closes all open output buffers, either by flushing or cleaning, and stores the Kohana + * Closes all open output buffers, either by flushing or cleaning, and stores * output buffer for display during shutdown. * * @param boolean disable to clear buffers, rather than flushing @@ -715,12 +490,12 @@ final class Kohana { */ public static function close_buffers($flush = TRUE) { - if (ob_get_level() >= self::$buffer_level) + if (ob_get_level() >= Kohana::$buffer_level) { // Set the close function $close = ($flush === TRUE) ? 'ob_end_flush' : 'ob_end_clean'; - while (ob_get_level() > self::$buffer_level) + while (ob_get_level() > Kohana::$buffer_level) { // Flush or clean the buffer $close(); @@ -738,14 +513,25 @@ final class Kohana { */ public static function shutdown() { + static $run; + + // Only run this function once + if ($run === TRUE) + return; + + $run = TRUE; + + // Run system.shutdown event + Event::run('system.shutdown'); + // Close output buffers - self::close_buffers(TRUE); + Kohana::close_buffers(TRUE); // Run the output event - Event::run('system.display', self::$output); + Event::run('system.display', Kohana::$output); // Render the final output - self::render(self::$output); + Kohana::render(Kohana::$output); } /** @@ -756,7 +542,7 @@ final class Kohana { */ public static function render($output) { - if (self::config('core.render_stats') === TRUE) + if (Kohana::config('core.render_stats') === TRUE) { // Fetch memory usage in MB $memory = function_exists('memory_get_usage') ? (memory_get_usage() / 1024 / 1024) : 0; @@ -776,8 +562,8 @@ final class Kohana { ), array ( - KOHANA_VERSION, - KOHANA_CODENAME, + KOHANA::VERSION, + KOHANA::CODENAME, $benchmark['time'], number_format($memory, 2).'MB', count(get_included_files()), @@ -786,215 +572,44 @@ final class Kohana { ); } - if ($level = self::config('core.output_compression') AND ini_get('output_handler') !== 'ob_gzhandler' AND (int) ini_get('zlib.output_compression') === 0) + if ($level = Kohana::config('core.output_compression') AND ini_get('output_handler') !== 'ob_gzhandler' AND (int) ini_get('zlib.output_compression') === 0) { - if ($level < 1 OR $level > 9) - { - // Normalize the level to be an integer between 1 and 9. This - // step must be done to prevent gzencode from triggering an error - $level = max(1, min($level, 9)); - } - - if (stripos(@$_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE) + if ($compress = request::preferred_encoding(array('gzip','deflate'), TRUE)) { - $compress = 'gzip'; - } - elseif (stripos(@$_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate') !== FALSE) - { - $compress = 'deflate'; - } - } + if ($level < 1 OR $level > 9) + { + // Normalize the level to be an integer between 1 and 9. This + // step must be done to prevent gzencode from triggering an error + $level = max(1, min($level, 9)); + } - if (isset($compress) AND $level > 0) - { - switch ($compress) - { - case 'gzip': + if ($compress === 'gzip') + { // Compress output using gzip $output = gzencode($output, $level); - break; - case 'deflate': + } + elseif ($compress === 'deflate') + { // Compress output using zlib (HTTP deflate) $output = gzdeflate($output, $level); - break; - } - - // This header must be sent with compressed content to prevent - // browser caches from breaking - header('Vary: Accept-Encoding'); - - // Send the content encoding header - header('Content-Encoding: '.$compress); + } - // Sending Content-Length in CGI can result in unexpected behavior - if (stripos(PHP_SAPI, 'cgi') === FALSE) - { - header('Content-Length: '.strlen($output)); - } - } + // This header must be sent with compressed content to prevent + // browser caches from breaking + header('Vary: Accept-Encoding'); - echo $output; - } + // Send the content encoding header + header('Content-Encoding: '.$compress); - /** - * Displays a 404 page. - * - * @throws Kohana_404_Exception - * @param string URI of page - * @param string custom template - * @return void - */ - public static function show_404($page = FALSE, $template = FALSE) - { - throw new Kohana_404_Exception($page, $template); - } - - /** - * Dual-purpose PHP error and exception handler. Uses the kohana_error_page - * view to display the message. - * - * @param integer|object exception object or error code - * @param string error message - * @param string filename - * @param integer line number - * @return void - */ - public static function exception_handler($exception, $message = NULL, $file = NULL, $line = NULL) - { - try - { - // PHP errors have 5 args, always - $PHP_ERROR = (func_num_args() === 5); - - // Test to see if errors should be displayed - if ($PHP_ERROR AND (error_reporting() & $exception) === 0) - return; - - // This is useful for hooks to determine if a page has an error - self::$has_error = TRUE; - - // Error handling will use exactly 5 args, every time - if ($PHP_ERROR) - { - $code = $exception; - $type = 'PHP Error'; - $template = 'kohana_error_page'; - } - else - { - $code = $exception->getCode(); - $type = get_class($exception); - $message = $exception->getMessage(); - $file = $exception->getFile(); - $line = $exception->getLine(); - $template = ($exception instanceof Kohana_Exception) ? $exception->getTemplate() : 'kohana_error_page'; - } - - if (is_numeric($code)) - { - $codes = self::lang('errors'); - - if ( ! empty($codes[$code])) - { - list($level, $error, $description) = $codes[$code]; - } - else - { - $level = 1; - $error = $PHP_ERROR ? 'Unknown Error' : get_class($exception); - $description = ''; - } - } - else - { - // Custom error message, this will never be logged - $level = 5; - $error = $code; - $description = ''; - } - - // Remove the DOCROOT from the path, as a security precaution - $file = str_replace('\\', '/', realpath($file)); - $file = preg_replace('|^'.preg_quote(DOCROOT).'|', '', $file); - - if ($level <= self::$configuration['core']['log_threshold']) - { - // Log the error - self::log('error', self::lang('core.uncaught_exception', $type, $message, $file, $line)); - } - - if ($PHP_ERROR) - { - $description = self::lang('errors.'.E_RECOVERABLE_ERROR); - $description = is_array($description) ? $description[2] : ''; - - if ( ! headers_sent()) + // Sending Content-Length in CGI can result in unexpected behavior + if (stripos(PHP_SAPI, 'cgi') === FALSE) { - // Send the 500 header - header('HTTP/1.1 500 Internal Server Error'); + header('Content-Length: '.strlen($output)); } } - else - { - if (method_exists($exception, 'sendHeaders') AND ! headers_sent()) - { - // Send the headers if they have not already been sent - $exception->sendHeaders(); - } - } - - // Close all output buffers except for Kohana - while (ob_get_level() > self::$buffer_level) - { - ob_end_clean(); - } - - // Test if display_errors is on - if (self::$configuration['core']['display_errors'] === TRUE) - { - if ( ! IN_PRODUCTION AND $line != FALSE) - { - // Remove the first entry of debug_backtrace(), it is the exception_handler call - $trace = $PHP_ERROR ? array_slice(debug_backtrace(), 1) : $exception->getTrace(); - - // Beautify backtrace - $trace = self::backtrace($trace); - } - - // Load the error - require self::find_file('views', empty($template) ? 'kohana_error_page' : $template); - } - else - { - // Get the i18n messages - $error = self::lang('core.generic_error'); - $message = self::lang('core.errors_disabled', url::site(), url::site(Router::$current_uri)); - - // Load the errors_disabled view - require self::find_file('views', 'kohana_error_disabled'); - } - - if ( ! Event::has_run('system.shutdown')) - { - // Run the shutdown even to ensure a clean exit - Event::run('system.shutdown'); - } - - // Turn off error reporting - error_reporting(0); - exit; - } - catch (Exception $e) - { - if (IN_PRODUCTION) - { - die('Fatal Error'); - } - else - { - die('Fatal Error: '.$e->getMessage().' File: '.$e->getFile().' Line: '.$e->getLine()); - } } + + echo $output; } /** @@ -1006,7 +621,7 @@ final class Kohana { */ public static function auto_load($class) { - if (class_exists($class, FALSE)) + if (class_exists($class, FALSE) OR interface_exists($class, FALSE)) return TRUE; if (($suffix = strrpos($class, '_')) > 0) @@ -1051,7 +666,7 @@ final class Kohana { $file = $class; } - if ($filename = self::find_file($type, $file)) + if ($filename = Kohana::find_file($type, $file)) { // Load the class require $filename; @@ -1062,7 +677,7 @@ final class Kohana { return FALSE; } - if ($filename = self::find_file($type, self::$configuration['core']['extension_prefix'].$class)) + if ($filename = Kohana::find_file($type, Kohana::config('core.extension_prefix').$class)) { // Load the class extension require $filename; @@ -1121,16 +736,16 @@ final class Kohana { // Search path $search = $directory.'/'.$filename.$ext; - if (isset(self::$internal_cache['find_file_paths'][$search])) - return self::$internal_cache['find_file_paths'][$search]; + if (isset(Kohana::$internal_cache['find_file_paths'][$search])) + return Kohana::$internal_cache['find_file_paths'][$search]; // Load include paths - $paths = self::$include_paths; + $paths = Kohana::$include_paths; // Nothing found, yet $found = NULL; - if ($directory === 'config' OR $directory === 'i18n') + if ($directory === 'config' OR $directory === 'messages' OR $directory === 'i18n') { // Search in reverse, for merging $paths = array_reverse($paths); @@ -1167,7 +782,7 @@ final class Kohana { $directory = 'core.'.inflector::singular($directory); // If the file is required, throw an exception - throw new Kohana_Exception('core.resource_not_found', self::lang($directory), $filename); + throw new Kohana_Exception('The requested :resource:, :file:, could not be found', array(':resource:' => Kohana::message($directory), ':file:' =>$filename)); } else { @@ -1176,13 +791,13 @@ final class Kohana { } } - if ( ! isset(self::$write_cache['find_file_paths'])) + if ( ! isset(Kohana::$write_cache['find_file_paths'])) { // Write cache at shutdown - self::$write_cache['find_file_paths'] = TRUE; + Kohana::$write_cache['find_file_paths'] = TRUE; } - return self::$internal_cache['find_file_paths'][$search] = $found; + return Kohana::$internal_cache['find_file_paths'][$search] = $found; } /** @@ -1190,45 +805,54 @@ final class Kohana { * * @param string directory to search * @param boolean list all files to the maximum depth? + * @param string list all files having extension $ext * @param string full path to search (used for recursion, *never* set this manually) * @return array filenames and directories */ - public static function list_files($directory, $recursive = FALSE, $path = FALSE) + public static function list_files($directory, $recursive = FALSE, $ext = EXT, $path = FALSE) { $files = array(); if ($path === FALSE) { - $paths = array_reverse(self::include_paths()); + $paths = array_reverse(Kohana::include_paths()); foreach ($paths as $path) { // Recursively get and merge all files - $files = array_merge($files, self::list_files($directory, $recursive, $path.$directory)); + $files = array_merge($files, Kohana::list_files($directory, $recursive, $ext, $path.$directory)); } } else { $path = rtrim($path, '/').'/'; - if (is_readable($path)) + if (is_readable($path) AND $items = glob($path.'*')) { - $items = (array) glob($path.'*'); + $ext_pos = 0 - strlen($ext); - if ( ! empty($items)) + foreach ($items as $index => $item) { - foreach ($items as $index => $item) - { - $files[] = $item = str_replace('\\', '/', $item); + $item = str_replace('\\', '/', $item); + if (is_dir($item)) + { // Handle recursion - if (is_dir($item) AND $recursive == TRUE) + if ($recursive === TRUE) { // Filename should only be the basename $item = pathinfo($item, PATHINFO_BASENAME); // Append sub-directory search - $files = array_merge($files, self::list_files($directory, TRUE, $path.$item)); + $files = array_merge($files, Kohana::list_files($directory, TRUE, $ext, $path.$item)); + } + } + else + { + // File extension must match + if ($ext_pos === 0 OR substr($item, $ext_pos) === $ext) + { + $files[] = $item; } } } @@ -1238,59 +862,48 @@ final class Kohana { return $files; } + /** - * Fetch an i18n language item. + * Fetch a message item. * * @param string language key to fetch * @param array additional information to insert into the line * @return string i18n language string, or the requested key if the i18n item is not found */ - public static function lang($key, $args = array()) + public static function message($key, $args = array()) { // Extract the main group from the key $group = explode('.', $key, 2); $group = $group[0]; // Get locale name - $locale = self::config('locale.language.0'); + $locale = Kohana::config('locale.language.0'); - if ( ! isset(self::$internal_cache['language'][$locale][$group])) + if ( ! isset(Kohana::$internal_cache['messages'][$group])) { // Messages for this group $messages = array(); - if ($files = self::find_file('i18n', $locale.'/'.$group)) + if ($file = Kohana::find_file('messages', $group)) { - foreach ($files as $file) - { - include $file; - - // Merge in configuration - if ( ! empty($lang) AND is_array($lang)) - { - foreach ($lang as $k => $v) - { - $messages[$k] = $v; - } - } - } + include $file[0]; } - if ( ! isset(self::$write_cache['language'])) + if ( ! isset(Kohana::$write_cache['messages'])) { // Write language cache - self::$write_cache['language'] = TRUE; + Kohana::$write_cache['messages'] = TRUE; } - self::$internal_cache['language'][$locale][$group] = $messages; + Kohana::$internal_cache['messages'][$group] = $messages; } // Get the line from cache - $line = self::key_string(self::$internal_cache['language'][$locale], $key); + $line = Kohana::key_string(Kohana::$internal_cache['messages'], $key); if ($line === NULL) { - self::log('error', 'Missing i18n entry '.$key.' for language '.$locale); + Kohana_Log::add('error', 'Missing messages entry '.$key.' for message '.$group); // Return the key string as fallback return $key; @@ -1426,121 +1039,6 @@ final class Kohana { } } - /** - * Retrieves current user agent information: - * keys: browser, version, platform, mobile, robot, referrer, languages, charsets - * tests: is_browser, is_mobile, is_robot, accept_lang, accept_charset - * - * @param string key or test name - * @param string used with "accept" tests: user_agent(accept_lang, en) - * @return array languages and charsets - * @return string all other keys - * @return boolean all tests - */ - public static function user_agent($key = 'agent', $compare = NULL) - { - static $info; - - // Return the raw string - if ($key === 'agent') - return self::$user_agent; - - if ($info === NULL) - { - // Parse the user agent and extract basic information - $agents = self::config('user_agents'); - - foreach ($agents as $type => $data) - { - foreach ($data as $agent => $name) - { - if (stripos(self::$user_agent, $agent) !== FALSE) - { - if ($type === 'browser' AND preg_match('|'.preg_quote($agent).'[^0-9.]*+([0-9.][0-9.a-z]*)|i', self::$user_agent, $match)) - { - // Set the browser version - $info['version'] = $match[1]; - } - - // Set the agent name - $info[$type] = $name; - break; - } - } - } - } - - if (empty($info[$key])) - { - switch ($key) - { - case 'is_robot': - case 'is_browser': - case 'is_mobile': - // A boolean result - $return = ! empty($info[substr($key, 3)]); - break; - case 'languages': - $return = array(); - if ( ! empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) - { - if (preg_match_all('/[-a-z]{2,}/', strtolower(trim($_SERVER['HTTP_ACCEPT_LANGUAGE'])), $matches)) - { - // Found a result - $return = $matches[0]; - } - } - break; - case 'charsets': - $return = array(); - if ( ! empty($_SERVER['HTTP_ACCEPT_CHARSET'])) - { - if (preg_match_all('/[-a-z0-9]{2,}/', strtolower(trim($_SERVER['HTTP_ACCEPT_CHARSET'])), $matches)) - { - // Found a result - $return = $matches[0]; - } - } - break; - case 'referrer': - if ( ! empty($_SERVER['HTTP_REFERER'])) - { - // Found a result - $return = trim($_SERVER['HTTP_REFERER']); - } - break; - } - - // Cache the return value - isset($return) and $info[$key] = $return; - } - - if ( ! empty($compare)) - { - // The comparison must always be lowercase - $compare = strtolower($compare); - - switch ($key) - { - case 'accept_lang': - // Check if the lange is accepted - return in_array($compare, self::user_agent('languages')); - break; - case 'accept_charset': - // Check if the charset is accepted - return in_array($compare, self::user_agent('charsets')); - break; - default: - // Invalid comparison - return FALSE; - break; - } - } - - // Return the key, if set - return isset($info[$key]) ? $info[$key] : NULL; - } - /** * Quick debugging of any variable. Any number of parameters can be set. * @@ -1557,76 +1055,13 @@ final class Kohana { foreach ($params as $var) { - $output[] = '
('.gettype($var).') '.html::specialchars(print_r($var, TRUE)).'
'; + $value = is_bool($var) ? ($var ? 'true' : 'false') : print_r($var, TRUE); + $output[] = '
('.gettype($var).') '.htmlspecialchars($value, ENT_QUOTES, Kohana::CHARSET).'
'; } return implode("\n", $output); } - /** - * Displays nice backtrace information. - * @see http://php.net/debug_backtrace - * - * @param array backtrace generated by an exception or debug_backtrace - * @return string - */ - public static function backtrace($trace) - { - if ( ! is_array($trace)) - return; - - // Final output - $output = array(); - - foreach ($trace as $entry) - { - $temp = '
  • '; - - if (isset($entry['file'])) - { - $temp .= self::lang('core.error_file_line', preg_replace('!^'.preg_quote(DOCROOT).'!', '', $entry['file']), $entry['line']); - } - - $temp .= '
    ';
    -
    -			if (isset($entry['class']))
    -			{
    -				// Add class and call type
    -				$temp .= $entry['class'].$entry['type'];
    -			}
    -
    -			// Add function
    -			$temp .= $entry['function'].'( ';
    -
    -			// Add function args
    -			if (isset($entry['args']) AND is_array($entry['args']))
    -			{
    -				// Separator starts as nothing
    -				$sep = '';
    -
    -				while ($arg = array_shift($entry['args']))
    -				{
    -					if (is_string($arg) AND is_file($arg))
    -					{
    -						// Remove docroot from filename
    -						$arg = preg_replace('!^'.preg_quote(DOCROOT).'!', '', $arg);
    -					}
    -
    -					$temp .= $sep.html::specialchars(print_r($arg, TRUE));
    -
    -					// Change separator to a comma
    -					$sep = ', ';
    -				}
    -			}
    -
    -			$temp .= ' )
  • '; - - $output[] = $temp; - } - - return ''; - } - /** * Saves the internal caches: configuration, include paths, etc. * @@ -1634,21 +1069,21 @@ final class Kohana { */ public static function internal_cache_save() { - if ( ! is_array(self::$write_cache)) + if ( ! is_array(Kohana::$write_cache)) return FALSE; // Get internal cache names - $caches = array_keys(self::$write_cache); + $caches = array_keys(Kohana::$write_cache); // Nothing written $written = FALSE; foreach ($caches as $cache) { - if (isset(self::$internal_cache[$cache])) + if (isset(Kohana::$internal_cache[$cache])) { // Write the cache file - self::cache_save($cache, self::$internal_cache[$cache], self::$configuration['core']['internal_cache']); + Kohana::cache_save($cache, Kohana::$internal_cache[$cache], Kohana::config('core.internal_cache')); // A cache has been written $written = TRUE; @@ -1659,138 +1094,3 @@ final class Kohana { } } // End Kohana - -/** - * Creates a generic i18n exception. - */ -class Kohana_Exception extends Exception { - - // Template file - protected $template = 'kohana_error_page'; - - // Header - protected $header = FALSE; - - // Error code - protected $code = E_KOHANA; - - /** - * Set exception message. - * - * @param string i18n language key for the message - * @param array addition line parameters - */ - public function __construct($error) - { - $args = array_slice(func_get_args(), 1); - - // Fetch the error message - $message = Kohana::lang($error, $args); - - if ($message === $error OR empty($message)) - { - // Unable to locate the message for the error - $message = 'Unknown Exception: '.$error; - } - - // Sets $this->message the proper way - parent::__construct($message); - } - - /** - * Magic method for converting an object to a string. - * - * @return string i18n message - */ - public function __toString() - { - return (string) $this->message; - } - - /** - * Fetch the template name. - * - * @return string - */ - public function getTemplate() - { - return $this->template; - } - - /** - * Sends an Internal Server Error header. - * - * @return void - */ - public function sendHeaders() - { - // Send the 500 header - header('HTTP/1.1 500 Internal Server Error'); - } - -} // End Kohana Exception - -/** - * Creates a custom exception. - */ -class Kohana_User_Exception extends Kohana_Exception { - - /** - * Set exception title and message. - * - * @param string exception title string - * @param string exception message string - * @param string custom error template - */ - public function __construct($title, $message, $template = FALSE) - { - Exception::__construct($message); - - $this->code = $title; - - if ($template !== FALSE) - { - $this->template = $template; - } - } - -} // End Kohana PHP Exception - -/** - * Creates a Page Not Found exception. - */ -class Kohana_404_Exception extends Kohana_Exception { - - protected $code = E_PAGE_NOT_FOUND; - - /** - * Set internal properties. - * - * @param string URL of page - * @param string custom error template - */ - public function __construct($page = FALSE, $template = FALSE) - { - if ($page === FALSE) - { - // Construct the page URI using Router properties - $page = Router::$current_uri.Router::$url_suffix.Router::$query_string; - } - - Exception::__construct(Kohana::lang('core.page_not_found', $page)); - - $this->template = $template; - } - - /** - * Sends "File Not Found" headers, to emulate server behavior. - * - * @return void - */ - public function sendHeaders() - { - // Send the 404 header - header('HTTP/1.1 404 File Not Found'); - } - -} // End Kohana 404 Exception diff --git a/system/core/Kohana_Config.php b/system/core/Kohana_Config.php new file mode 100644 index 00000000..f961f391 --- /dev/null +++ b/system/core/Kohana_Config.php @@ -0,0 +1,331 @@ +array( + ), 'internal_cache'=>FALSE + )); + $core_config = $config->get('core'); + Kohana_Config::$instance = new Kohana_Config($core_config); + } + + // Return the Kohana_Config driver requested + return Kohana_Config::$instance; + } + + /** + * The drivers for this object + * + * @var Kohana_Config_Driver + */ + protected $drivers; + + /** + * Kohana_Config constructor to load the supplied driver. + * Enforces the singleton pattern. + * + * @param string driver + * @access protected + */ + protected function __construct(array $core_config) + { + $drivers = $core_config['config_drivers']; + + //remove array if it's found in config + if (in_array('array', $drivers)) + unset($drivers[array_search('array', $drivers)]); + + //add array at the very end + $this->drivers = $drivers = array_merge($drivers, array( + 'array' + )); + + foreach ($this->drivers as & $driver) + { + // Create the driver name + $driver = 'Config_'.ucfirst($driver).'_Driver'; + + // Ensure the driver loads correctly + if (!Kohana::auto_load($driver)) + throw new Kohana_Exception('The :driver: driver for the :library: library could not be found.', array( + ':driver:' => $driver, ':library:' => get_class($this) + )); + + // Load the new driver + $driver = new $driver($core_config); + + // Ensure the new driver is valid + if (!$driver instanceof Config_Driver) + throw new Kohana_Exception('The :driver: driver for the :library: library must implement the :interface: interface', array( + ':driver:' => $driver, ':library:' => get_class($this), ':interface:' => 'Config_Driver' + )); + } + } + + /** + * Gets a value from the configuration driver + * + * @param string key + * @param bool slash + * @param bool required + * @return mixed + * @access public + */ + public function get($key, $slash = FALSE, $required = FALSE) + { + foreach ($this->drivers as $driver) + { + try + { + return $driver->get($key, $slash, $required); + } + catch (Kohana_Config_Exception $e) + { + //if it's the last driver in the list and it threw an exception, re throw it + if ($driver === $this->drivers[(count($this->drivers) - 1)]) + throw $e; + } + } + } + + /** + * Sets a value to the configuration drivers + * + * @param string key + * @param mixed value + * @return bool + * @access public + */ + public function set($key, $value) + { + foreach ($this->drivers as $driver) + { + try + { + $driver->set($key, $value); + } + catch (Kohana_Config_Exception $e) + { + //if it's the last driver in the list and it threw an exception, re throw it + if ($driver === $this->drivers[(count($this->drivers) - 1)]) + throw $e; + } + } + return TRUE; + } + + /** + * Clears a group from configuration + * + * @param string group + * @return bool + * @access public + */ + public function clear($group) + { + foreach ($this->drivers as $driver) + { + try + { + $driver->clear($group); + } + catch (Kohana_Config_Exception $e) + { + //if it's the last driver in the list and it threw an exception, re throw it + if ($driver === $this->drivers[(count($this->drivers) - 1)]) + throw $e; + } + } + return TRUE; + } + + /** + * Loads a configuration group + * + * @param string group + * @param bool required + * @return array + * @access public + */ + public function load($group, $required = FALSE) + { + foreach ($this->drivers as $driver) + { + try + { + return $driver->load($group, $required); + } + catch (Kohana_Config_Exception $e) + { + //if it's the last driver in the list and it threw an exception, re throw it + if ($driver === $this->drivers[(count($this->drivers) - 1)]) + throw $e; + } + } + } + + /** + * Returns true or false if any config has been loaded(either manually or from cache) + * + * @return boolean + */ + public function loaded() + { + return $this->drivers[(count($this->drivers) - 1)]->loaded; + } + + /** + * The following allows access using + * array syntax. + * + * @example $config['core.site_domain'] + */ + + /** + * Allows access to configuration settings + * using the ArrayAccess interface + * + * @param string key + * @return mixed + * @access public + */ + public function offsetGet($key) + { + foreach ($this->drivers as $driver) + { + try + { + return $driver->get($key); + } + catch (Kohana_Config_Exception $e) + { + //if it's the last driver in the list and it threw an exception, re throw it + if ($driver === $this->drivers[(count($this->drivers) - 1)]) + throw $e; + } + } + } + + /** + * Allows access to configuration settings + * using the ArrayAccess interface + * + * @param string key + * @param mixed value + * @return bool + * @access public + */ + public function offsetSet($key, $value) + { + foreach ($this->drivers as $driver) + { + try + { + $driver->set($key, $value); + } + catch (Kohana_Config_Exception $e) + { + //if it's the last driver in the list and it threw an exception, re throw it + if ($driver === $this->drivers[(count($this->drivers) - 1)]) + throw $e; + } + } + return TRUE; + } + + /** + * Allows access to configuration settings + * using the ArrayAccess interface + * + * @param string key + * @return bool + * @access public + */ + public function offsetExists($key) + { + foreach ($this->drivers as $driver) + { + try + { + return $driver->setting_exists($key); + } + catch (Kohana_Config_Exception $e) + { + //if it's the last driver in the list and it threw an exception, re throw it + if ($driver === $this->drivers[(count($this->drivers) - 1)]) + throw $e; + } + } + } + + /** + * Allows access to configuration settings + * using the ArrayAccess interface + * + * @param string key + * @return bool + * @access public + */ + public function offsetUnset($key) + { + foreach ($this->drivers as $driver) + { + try + { + return $driver->set($key, NULL); + } + catch (Kohana_Config_Exception $e) + { + //if it's the last driver in the list and it threw an exception, re throw it + if ($driver === $this->drivers[(count($this->drivers) - 1)]) + throw $e; + } + } + return TRUE; + } +} // End KohanaConfig + +class Kohana_Config_Exception extends Kohana_Exception {} diff --git a/system/core/Kohana_Exception.php b/system/core/Kohana_Exception.php new file mode 100644 index 00000000..cdb06a62 --- /dev/null +++ b/system/core/Kohana_Exception.php @@ -0,0 +1,619 @@ +instance_identifier = uniqid(); + + // Translate the error message + $message = __($message, $variables); + + // Sets $this->message the proper way + parent::__construct($message, $code); + } + + /** + * Enable Kohana exception handling. + * + * @uses Kohana_Exception::$template + * @return void + */ + public static function enable() + { + if ( ! Kohana_Exception::$enabled) + { + set_exception_handler(array('Kohana_Exception', 'handle')); + + Kohana_Exception::$enabled = TRUE; + } + } + + /** + * Disable Kohana exception handling. + * + * @return void + */ + public static function disable() + { + if (Kohana_Exception::$enabled) + { + restore_exception_handler(); + + Kohana_Exception::$enabled = FALSE; + } + } + + /** + * Get a single line of text representing the exception: + * + * Error [ Code ]: Message ~ File [ Line ] + * + * @param object Exception + * @return string + */ + public static function text($e) + { + return sprintf('%s [ %s ]: %s ~ %s [ %d ]', + get_class($e), $e->getCode(), strip_tags($e->getMessage()), Kohana_Exception::debug_path($e->getFile()), $e->getLine()); + } + + /** + * exception handler, displays the error message, source of the + * exception, and the stack trace of the error. + * + * @uses Kohana::message() + * @uses Kohana_Exception::text() + * @param object exception object + * @return void + */ + public static function handle(Exception $e) + { + try + { + // Get the exception information + $type = get_class($e); + $code = $e->getCode(); + $message = $e->getMessage(); + + // Create a text version of the exception + $error = Kohana_Exception::text($e); + + // Add this exception to the log + Kohana_Log::add('error', $error); + + // Manually save logs after exceptions + Kohana_Log::save(); + + if (Kohana::config('core.display_errors') === FALSE) + { + // Do not show the details + $file = $line = NULL; + $trace = array(); + + $template = '_disabled'; + } + else + { + $file = $e->getFile(); + $line = $e->getLine(); + $trace = $e->getTrace(); + + $template = ''; + } + + if ($e instanceof Kohana_Exception) + { + $template = $e->getTemplate().$template; + + if ( ! headers_sent()) + { + $e->sendHeaders(); + } + + // Use the human-readable error name + $code = Kohana::message('core.errors.'.$code); + } + else + { + $template = Kohana_Exception::$template.$template; + + if ( ! headers_sent()) + { + header('HTTP/1.1 500 Internal Server Error'); + } + + if ($e instanceof ErrorException) + { + // Use the human-readable error name + $code = Kohana::message('core.errors.'.$e->getSeverity()); + + 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/45895 + for ($i = count($trace) - 1; $i > 0; --$i) + { + if (isset($trace[$i - 1]['args'])) + { + // Re-position the arguments + $trace[$i]['args'] = $trace[$i - 1]['args']; + + unset($trace[$i - 1]['args']); + } + } + } + } + } + + // Clean the output buffer if one exists + ob_get_level() and ob_clean(); + + if ($template = Kohana::find_file('views', $template)) + { + include $template; + } + } + 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"; + } + + if (PHP_SAPI === 'cli') + { + // Exit with an error status + exit(1); + } + } + + /** + * Returns the template for this exception. + * + * @uses Kohana_Exception::$template + * @return string + */ + public function getTemplate() + { + return Kohana_Exception::$template; + } + + /** + * Sends an Internal Server Error header. + * + * @return void + */ + public function sendHeaders() + { + // Send the 500 header + header('HTTP/1.1 500 Internal Server Error'); + } + + /** + * Returns an HTML string of information about a single variable. + * + * Borrows heavily on concepts from the Debug class of {@link http://nettephp.com/ Nette}. + * + * @param mixed variable to dump + * @param integer maximum length of strings + * @return string + */ + public static function dump($value, $length = 128) + { + return Kohana_Exception::_dump($value, $length); + } + + /** + * Helper for Kohana_Exception::dump(), handles recursion in arrays and objects. + * + * @param mixed variable to dump + * @param integer maximum length of strings + * @param integer recursion level (internal) + * @return string + */ + private static function _dump( & $var, $length = 128, $level = 0) + { + if ($var === NULL) + { + return 'NULL'; + } + elseif (is_bool($var)) + { + return 'bool '.($var ? 'TRUE' : 'FALSE'); + } + elseif (is_float($var)) + { + return 'float '.$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_Exception::debug_path($file); + } + } + + return 'resource('.$type.') '.htmlspecialchars($file, ENT_NOQUOTES, Kohana::CHARSET); + } + } + else + { + return 'resource('.$type.')'; + } + } + elseif (is_string($var)) + { + if (strlen($var) > $length) + { + // Encode the truncated string + $str = htmlspecialchars(substr($var, 0, $length), ENT_NOQUOTES, Kohana::CHARSET).' …'; + } + else + { + // Encode the string + $str = htmlspecialchars($var, ENT_NOQUOTES, Kohana::CHARSET); + } + + return 'string('.strlen($var).') "'.$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[] = "("; + + $var[$marker] = TRUE; + foreach ($var as $key => & $val) + { + if ($key === $marker) continue; + if ( ! is_int($key)) + { + $key = '"'.$key.'"'; + } + + $output[] = "$space$s$key => ".Kohana_Exception::_dump($val, $length, $level + 1); + } + unset($var[$marker]); + + $output[] = "$space)"; + } + else + { + // Depth too great + $output[] = "(\n$space$s...\n$space)"; + } + + return 'array('.count($var).') '.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 < 5) + { + $output[] = "{"; + + $objects[$hash] = TRUE; + foreach ($array as $key => & $val) + { + if ($key[0] === "\x00") + { + // Determine if the access is private or protected + $access = ''.($key[1] === '*' ? 'protected' : 'private').''; + + // Remove the access level from the variable name + $key = substr($key, strrpos($key, "\x00") + 1); + } + else + { + $access = 'public'; + } + + $output[] = "$space$s$access $key => ".Kohana_Exception::_dump($val, $length, $level + 1); + } + unset($objects[$hash]); + + $output[] = "$space}"; + } + else + { + // Depth too great + $output[] = "{\n$space$s...\n$space}"; + } + + return 'object '.get_class($var).'('.count($array).') '.implode("\n", $output); + } + else + { + return ''.gettype($var).' '.htmlspecialchars(print_r($var, TRUE), ENT_NOQUOTES, Kohana::CHARSET); + } + } + + /** + * Removes APPPATH, SYSPATH, MODPATH, and DOCROOT from filenames, replacing + * them with the plain text equivalents. + * + * @param string path to sanitize + * @return string + */ + public static function debug_path($file) + { + if (strpos($file, APPPATH) === 0) + { + $file = 'APPPATH/'.substr($file, strlen(APPPATH)); + } + elseif (strpos($file, SYSPATH) === 0) + { + $file = 'SYSPATH/'.substr($file, strlen(SYSPATH)); + } + elseif (strpos($file, MODPATH) === 0) + { + $file = 'MODPATH/'.substr($file, strlen(MODPATH)); + } + elseif (strpos($file, DOCROOT) === 0) + { + $file = 'DOCROOT/'.substr($file, strlen(DOCROOT)); + } + + return $file; + } + + /** + * Returns an array of lines from a file. + * + * // Returns the current line of the current file + * echo Kohana_Exception::debug_source(__FILE__, __LINE__); + * + * @param string file to open + * @param integer line number to find + * @param integer number of padding lines + * @return array + */ + public static function debug_source($file, $line_number, $padding = 5) + { + // Make sure we can read the source file + if ( ! is_readable($file)) + return array(); + + // 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 = array(); + while (($row = fgets($file)) !== FALSE) + { + // Increment the line number + if (++$line > $range['end']) + break; + + if ($line >= $range['start']) + { + $source[sprintf($format, $line)] = $row; + } + } + + // Close the file + fclose($file); + + return $source; + } + + /** + * Returns an array of strings that represent each step in the backtrace. + * + * @param array trace to analyze + * @return array + */ + public static function trace($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_Exception::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($step['args'][0]); + } + } + elseif (isset($step['args'])) + { + if ($step['function'] === '{closure}') + { + // Introspection on closures 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; + } + +} // End Kohana Exception diff --git a/system/core/utf8.php b/system/core/utf8.php deleted file mode 100644 index 9f20f421..00000000 --- a/system/core/utf8.php +++ /dev/null @@ -1,743 +0,0 @@ -PCRE has not been compiled with UTF-8 support. '. - 'See PCRE Pattern Modifiers '. - 'for more information. This application cannot be run without UTF-8 support.', - E_USER_ERROR - ); -} - -if ( ! extension_loaded('iconv')) -{ - trigger_error - ( - 'The iconv extension is not loaded. '. - 'Without iconv, strings cannot be properly translated to UTF-8 from user input. '. - 'This application cannot be run without UTF-8 support.', - E_USER_ERROR - ); -} - -if (extension_loaded('mbstring') AND (ini_get('mbstring.func_overload') & MB_OVERLOAD_STRING)) -{ - trigger_error - ( - 'The mbstring extension is overloading PHP\'s native string functions. '. - 'Disable this by setting mbstring.func_overload to 0, 1, 4 or 5 in php.ini or a .htaccess file.'. - 'This application cannot be run without UTF-8 support.', - E_USER_ERROR - ); -} - -// Check PCRE support for Unicode properties such as \p and \X. -$ER = error_reporting(0); -define('PCRE_UNICODE_PROPERTIES', (bool) preg_match('/^\pL$/u', 'ñ')); -error_reporting($ER); - -// SERVER_UTF8 ? use mb_* functions : use non-native functions -if (extension_loaded('mbstring')) -{ - mb_internal_encoding('UTF-8'); - define('SERVER_UTF8', TRUE); -} -else -{ - define('SERVER_UTF8', FALSE); -} - -// Convert all global variables to UTF-8. -$_GET = utf8::clean($_GET); -$_POST = utf8::clean($_POST); -$_COOKIE = utf8::clean($_COOKIE); -$_SERVER = utf8::clean($_SERVER); - -if (PHP_SAPI == 'cli') -{ - // Convert command line arguments - $_SERVER['argv'] = utf8::clean($_SERVER['argv']); -} - -final class utf8 { - - // Called methods - static $called = array(); - - /** - * Recursively cleans arrays, objects, and strings. Removes ASCII control - * codes and converts to UTF-8 while silently discarding incompatible - * UTF-8 characters. - * - * @param string string to clean - * @return string - */ - public static function clean($str) - { - if (is_array($str) OR is_object($str)) - { - foreach ($str as $key => $val) - { - // Recursion! - $str[self::clean($key)] = self::clean($val); - } - } - elseif (is_string($str) AND $str !== '') - { - // Remove control characters - $str = self::strip_ascii_ctrl($str); - - if ( ! self::is_ascii($str)) - { - // Disable notices - $ER = error_reporting(~E_NOTICE); - - // iconv is expensive, so it is only used when needed - $str = iconv('UTF-8', 'UTF-8//IGNORE', $str); - - // Turn notices back on - error_reporting($ER); - } - } - - return $str; - } - - /** - * Tests whether a string contains only 7bit ASCII bytes. This is used to - * determine when to use native functions or UTF-8 functions. - * - * @param string string to check - * @return bool - */ - public static function is_ascii($str) - { - return ! preg_match('/[^\x00-\x7F]/S', $str); - } - - /** - * Strips out device control codes in the ASCII range. - * - * @param string string to clean - * @return string - */ - public static function strip_ascii_ctrl($str) - { - return preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $str); - } - - /** - * Strips out all non-7bit ASCII bytes. - * - * @param string string to clean - * @return string - */ - public static function strip_non_ascii($str) - { - return preg_replace('/[^\x00-\x7F]+/S', '', $str); - } - - /** - * Replaces special/accented UTF-8 characters by ASCII-7 'equivalents'. - * - * @author Andreas Gohr - * - * @param string string to transliterate - * @param integer -1 lowercase only, +1 uppercase only, 0 both cases - * @return string - */ - public static function transliterate_to_ascii($str, $case = 0) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _transliterate_to_ascii($str, $case); - } - - /** - * Returns the length of the given string. - * @see http://php.net/strlen - * - * @param string string being measured for length - * @return integer - */ - public static function strlen($str) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _strlen($str); - } - - /** - * Finds position of first occurrence of a UTF-8 string. - * @see http://php.net/strlen - * - * @author Harry Fuecks - * - * @param string haystack - * @param string needle - * @param integer offset from which character in haystack to start searching - * @return integer position of needle - * @return boolean FALSE if the needle is not found - */ - public static function strpos($str, $search, $offset = 0) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _strpos($str, $search, $offset); - } - - /** - * Finds position of last occurrence of a char in a UTF-8 string. - * @see http://php.net/strrpos - * - * @author Harry Fuecks - * - * @param string haystack - * @param string needle - * @param integer offset from which character in haystack to start searching - * @return integer position of needle - * @return boolean FALSE if the needle is not found - */ - public static function strrpos($str, $search, $offset = 0) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _strrpos($str, $search, $offset); - } - - /** - * Returns part of a UTF-8 string. - * @see http://php.net/substr - * - * @author Chris Smith - * - * @param string input string - * @param integer offset - * @param integer length limit - * @return string - */ - public static function substr($str, $offset, $length = NULL) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _substr($str, $offset, $length); - } - - /** - * Replaces text within a portion of a UTF-8 string. - * @see http://php.net/substr_replace - * - * @author Harry Fuecks - * - * @param string input string - * @param string replacement string - * @param integer offset - * @return string - */ - public static function substr_replace($str, $replacement, $offset, $length = NULL) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _substr_replace($str, $replacement, $offset, $length); - } - - /** - * Makes a UTF-8 string lowercase. - * @see http://php.net/strtolower - * - * @author Andreas Gohr - * - * @param string mixed case string - * @return string - */ - public static function strtolower($str) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _strtolower($str); - } - - /** - * Makes a UTF-8 string uppercase. - * @see http://php.net/strtoupper - * - * @author Andreas Gohr - * - * @param string mixed case string - * @return string - */ - public static function strtoupper($str) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _strtoupper($str); - } - - /** - * Makes a UTF-8 string's first character uppercase. - * @see http://php.net/ucfirst - * - * @author Harry Fuecks - * - * @param string mixed case string - * @return string - */ - public static function ucfirst($str) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _ucfirst($str); - } - - /** - * Makes the first character of every word in a UTF-8 string uppercase. - * @see http://php.net/ucwords - * - * @author Harry Fuecks - * - * @param string mixed case string - * @return string - */ - public static function ucwords($str) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _ucwords($str); - } - - /** - * Case-insensitive UTF-8 string comparison. - * @see http://php.net/strcasecmp - * - * @author Harry Fuecks - * - * @param string string to compare - * @param string string to compare - * @return integer less than 0 if str1 is less than str2 - * @return integer greater than 0 if str1 is greater than str2 - * @return integer 0 if they are equal - */ - public static function strcasecmp($str1, $str2) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _strcasecmp($str1, $str2); - } - - /** - * Returns a string or an array with all occurrences of search in subject (ignoring case). - * replaced with the given replace value. - * @see http://php.net/str_ireplace - * - * @note It's not fast and gets slower if $search and/or $replace are arrays. - * @author Harry Fuecks - * - * @param string input string - * @param string needle - * @return string matched substring if found - * @return boolean FALSE if the substring was not found - */ - public static function stristr($str, $search) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _stristr($str, $search); - } - - /** - * Finds the length of the initial segment matching mask. - * @see http://php.net/strspn - * - * @author Harry Fuecks - * - * @param string input string - * @param string mask for search - * @param integer start position of the string to examine - * @param integer length of the string to examine - * @return integer length of the initial segment that contains characters in the mask - */ - public static function strspn($str, $mask, $offset = NULL, $length = NULL) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _strspn($str, $mask, $offset, $length); - } - - /** - * Finds the length of the initial segment not matching mask. - * @see http://php.net/strcspn - * - * @author Harry Fuecks - * - * @param string input string - * @param string mask for search - * @param integer start position of the string to examine - * @param integer length of the string to examine - * @return integer length of the initial segment that contains characters not in the mask - */ - public static function strcspn($str, $mask, $offset = NULL, $length = NULL) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _strcspn($str, $mask, $offset, $length); - } - - /** - * Pads a UTF-8 string to a certain length with another string. - * @see http://php.net/str_pad - * - * @author Harry Fuecks - * - * @param string input string - * @param integer desired string length after padding - * @param string string to use as padding - * @param string padding type: STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH - * @return string - */ - public static function str_pad($str, $final_str_length, $pad_str = ' ', $pad_type = STR_PAD_RIGHT) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _str_pad($str, $final_str_length, $pad_str, $pad_type); - } - - /** - * Converts a UTF-8 string to an array. - * @see http://php.net/str_split - * - * @author Harry Fuecks - * - * @param string input string - * @param integer maximum length of each chunk - * @return array - */ - public static function str_split($str, $split_length = 1) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _str_split($str, $split_length); - } - - /** - * Reverses a UTF-8 string. - * @see http://php.net/strrev - * - * @author Harry Fuecks - * - * @param string string to be reversed - * @return string - */ - public static function strrev($str) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _strrev($str); - } - - /** - * Strips whitespace (or other UTF-8 characters) from the beginning and - * end of a string. - * @see http://php.net/trim - * - * @author Andreas Gohr - * - * @param string input string - * @param string string of characters to remove - * @return string - */ - public static function trim($str, $charlist = NULL) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _trim($str, $charlist); - } - - /** - * Strips whitespace (or other UTF-8 characters) from the beginning of a string. - * @see http://php.net/ltrim - * - * @author Andreas Gohr - * - * @param string input string - * @param string string of characters to remove - * @return string - */ - public static function ltrim($str, $charlist = NULL) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _ltrim($str, $charlist); - } - - /** - * Strips whitespace (or other UTF-8 characters) from the end of a string. - * @see http://php.net/rtrim - * - * @author Andreas Gohr - * - * @param string input string - * @param string string of characters to remove - * @return string - */ - public static function rtrim($str, $charlist = NULL) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _rtrim($str, $charlist); - } - - /** - * Returns the unicode ordinal for a character. - * @see http://php.net/ord - * - * @author Harry Fuecks - * - * @param string UTF-8 encoded character - * @return integer - */ - public static function ord($chr) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _ord($chr); - } - - /** - * Takes an UTF-8 string and returns an array of ints representing the Unicode characters. - * Astral planes are supported i.e. the ints in the output can be > 0xFFFF. - * Occurrances of the BOM are ignored. Surrogates are not allowed. - * - * The Original Code is Mozilla Communicator client code. - * The Initial Developer of the Original Code is Netscape Communications Corporation. - * Portions created by the Initial Developer are Copyright (C) 1998 the Initial Developer. - * Ported to PHP by Henri Sivonen , see http://hsivonen.iki.fi/php-utf8/. - * Slight modifications to fit with phputf8 library by Harry Fuecks . - * - * @param string UTF-8 encoded string - * @return array unicode code points - * @return boolean FALSE if the string is invalid - */ - public static function to_unicode($str) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _to_unicode($str); - } - - /** - * Takes an array of ints representing the Unicode characters and returns a UTF-8 string. - * Astral planes are supported i.e. the ints in the input can be > 0xFFFF. - * Occurrances of the BOM are ignored. Surrogates are not allowed. - * - * The Original Code is Mozilla Communicator client code. - * The Initial Developer of the Original Code is Netscape Communications Corporation. - * Portions created by the Initial Developer are Copyright (C) 1998 the Initial Developer. - * Ported to PHP by Henri Sivonen , see http://hsivonen.iki.fi/php-utf8/. - * Slight modifications to fit with phputf8 library by Harry Fuecks . - * - * @param array unicode code points representing a string - * @return string utf8 string of characters - * @return boolean FALSE if a code point cannot be found - */ - public static function from_unicode($arr) - { - if ( ! isset(self::$called[__FUNCTION__])) - { - require SYSPATH.'core/utf8/'.__FUNCTION__.EXT; - - // Function has been called - self::$called[__FUNCTION__] = TRUE; - } - - return _from_unicode($arr); - } - -} // End utf8 \ No newline at end of file diff --git a/system/core/utf8/from_unicode.php b/system/core/utf8/from_unicode.php deleted file mode 100644 index 66c6742d..00000000 --- a/system/core/utf8/from_unicode.php +++ /dev/null @@ -1,68 +0,0 @@ -= 0) AND ($arr[$k] <= 0x007f)) - { - echo chr($arr[$k]); - } - // 2 byte sequence - elseif ($arr[$k] <= 0x07ff) - { - echo chr(0xc0 | ($arr[$k] >> 6)); - echo chr(0x80 | ($arr[$k] & 0x003f)); - } - // Byte order mark (skip) - elseif ($arr[$k] == 0xFEFF) - { - // nop -- zap the BOM - } - // Test for illegal surrogates - elseif ($arr[$k] >= 0xD800 AND $arr[$k] <= 0xDFFF) - { - // Found a surrogate - trigger_error('utf8::from_unicode: Illegal surrogate at index: '.$k.', value: '.$arr[$k], E_USER_WARNING); - return FALSE; - } - // 3 byte sequence - elseif ($arr[$k] <= 0xffff) - { - echo chr(0xe0 | ($arr[$k] >> 12)); - echo chr(0x80 | (($arr[$k] >> 6) & 0x003f)); - echo chr(0x80 | ($arr[$k] & 0x003f)); - } - // 4 byte sequence - elseif ($arr[$k] <= 0x10ffff) - { - echo chr(0xf0 | ($arr[$k] >> 18)); - echo chr(0x80 | (($arr[$k] >> 12) & 0x3f)); - echo chr(0x80 | (($arr[$k] >> 6) & 0x3f)); - echo chr(0x80 | ($arr[$k] & 0x3f)); - } - // Out of range - else - { - trigger_error('utf8::from_unicode: Codepoint out of Unicode range at index: '.$k.', value: '.$arr[$k], E_USER_WARNING); - return FALSE; - } - } - - $result = ob_get_contents(); - ob_end_clean(); - return $result; -} diff --git a/system/core/utf8/ltrim.php b/system/core/utf8/ltrim.php deleted file mode 100644 index 556fe07f..00000000 --- a/system/core/utf8/ltrim.php +++ /dev/null @@ -1,22 +0,0 @@ -= 0 AND $ord0 <= 127) - { - return $ord0; - } - - if ( ! isset($chr[1])) - { - trigger_error('Short sequence - at least 2 bytes expected, only 1 seen', E_USER_WARNING); - return FALSE; - } - - $ord1 = ord($chr[1]); - - if ($ord0 >= 192 AND $ord0 <= 223) - { - return ($ord0 - 192) * 64 + ($ord1 - 128); - } - - if ( ! isset($chr[2])) - { - trigger_error('Short sequence - at least 3 bytes expected, only 2 seen', E_USER_WARNING); - return FALSE; - } - - $ord2 = ord($chr[2]); - - if ($ord0 >= 224 AND $ord0 <= 239) - { - return ($ord0 - 224) * 4096 + ($ord1 - 128) * 64 + ($ord2 - 128); - } - - if ( ! isset($chr[3])) - { - trigger_error('Short sequence - at least 4 bytes expected, only 3 seen', E_USER_WARNING); - return FALSE; - } - - $ord3 = ord($chr[3]); - - if ($ord0 >= 240 AND $ord0 <= 247) - { - return ($ord0 - 240) * 262144 + ($ord1 - 128) * 4096 + ($ord2-128) * 64 + ($ord3 - 128); - } - - if ( ! isset($chr[4])) - { - trigger_error('Short sequence - at least 5 bytes expected, only 4 seen', E_USER_WARNING); - return FALSE; - } - - $ord4 = ord($chr[4]); - - if ($ord0 >= 248 AND $ord0 <= 251) - { - return ($ord0 - 248) * 16777216 + ($ord1-128) * 262144 + ($ord2 - 128) * 4096 + ($ord3 - 128) * 64 + ($ord4 - 128); - } - - if ( ! isset($chr[5])) - { - trigger_error('Short sequence - at least 6 bytes expected, only 5 seen', E_USER_WARNING); - return FALSE; - } - - if ($ord0 >= 252 AND $ord0 <= 253) - { - return ($ord0 - 252) * 1073741824 + ($ord1 - 128) * 16777216 + ($ord2 - 128) * 262144 + ($ord3 - 128) * 4096 + ($ord4 - 128) * 64 + (ord($chr[5]) - 128); - } - - if ($ord0 >= 254 AND $ord0 <= 255) - { - trigger_error('Invalid UTF-8 with surrogate ordinal '.$ord0, E_USER_WARNING); - return FALSE; - } -} \ No newline at end of file diff --git a/system/core/utf8/rtrim.php b/system/core/utf8/rtrim.php deleted file mode 100644 index efa0e19d..00000000 --- a/system/core/utf8/rtrim.php +++ /dev/null @@ -1,22 +0,0 @@ - $val) - { - $str[$key] = utf8::str_ireplace($search, $replace, $val, $count); - } - return $str; - } - - if (is_array($search)) - { - $keys = array_keys($search); - - foreach ($keys as $k) - { - if (is_array($replace)) - { - if (array_key_exists($k, $replace)) - { - $str = utf8::str_ireplace($search[$k], $replace[$k], $str, $count); - } - else - { - $str = utf8::str_ireplace($search[$k], '', $str, $count); - } - } - else - { - $str = utf8::str_ireplace($search[$k], $replace, $str, $count); - } - } - return $str; - } - - $search = utf8::strtolower($search); - $str_lower = utf8::strtolower($str); - - $total_matched_strlen = 0; - $i = 0; - - while (preg_match('/(.*?)'.preg_quote($search, '/').'/s', $str_lower, $matches)) - { - $matched_strlen = strlen($matches[0]); - $str_lower = substr($str_lower, $matched_strlen); - - $offset = $total_matched_strlen + strlen($matches[1]) + ($i * (strlen($replace) - 1)); - $str = substr_replace($str, $replace, $offset, strlen($search)); - - $total_matched_strlen += $matched_strlen; - $i++; - } - - $count += $i; - return $str; -} diff --git a/system/core/utf8/str_pad.php b/system/core/utf8/str_pad.php deleted file mode 100644 index aab4ccc7..00000000 --- a/system/core/utf8/str_pad.php +++ /dev/null @@ -1,54 +0,0 @@ -0x0061, 0x03A6=>0x03C6, 0x0162=>0x0163, 0x00C5=>0x00E5, 0x0042=>0x0062, - 0x0139=>0x013A, 0x00C1=>0x00E1, 0x0141=>0x0142, 0x038E=>0x03CD, 0x0100=>0x0101, - 0x0490=>0x0491, 0x0394=>0x03B4, 0x015A=>0x015B, 0x0044=>0x0064, 0x0393=>0x03B3, - 0x00D4=>0x00F4, 0x042A=>0x044A, 0x0419=>0x0439, 0x0112=>0x0113, 0x041C=>0x043C, - 0x015E=>0x015F, 0x0143=>0x0144, 0x00CE=>0x00EE, 0x040E=>0x045E, 0x042F=>0x044F, - 0x039A=>0x03BA, 0x0154=>0x0155, 0x0049=>0x0069, 0x0053=>0x0073, 0x1E1E=>0x1E1F, - 0x0134=>0x0135, 0x0427=>0x0447, 0x03A0=>0x03C0, 0x0418=>0x0438, 0x00D3=>0x00F3, - 0x0420=>0x0440, 0x0404=>0x0454, 0x0415=>0x0435, 0x0429=>0x0449, 0x014A=>0x014B, - 0x0411=>0x0431, 0x0409=>0x0459, 0x1E02=>0x1E03, 0x00D6=>0x00F6, 0x00D9=>0x00F9, - 0x004E=>0x006E, 0x0401=>0x0451, 0x03A4=>0x03C4, 0x0423=>0x0443, 0x015C=>0x015D, - 0x0403=>0x0453, 0x03A8=>0x03C8, 0x0158=>0x0159, 0x0047=>0x0067, 0x00C4=>0x00E4, - 0x0386=>0x03AC, 0x0389=>0x03AE, 0x0166=>0x0167, 0x039E=>0x03BE, 0x0164=>0x0165, - 0x0116=>0x0117, 0x0108=>0x0109, 0x0056=>0x0076, 0x00DE=>0x00FE, 0x0156=>0x0157, - 0x00DA=>0x00FA, 0x1E60=>0x1E61, 0x1E82=>0x1E83, 0x00C2=>0x00E2, 0x0118=>0x0119, - 0x0145=>0x0146, 0x0050=>0x0070, 0x0150=>0x0151, 0x042E=>0x044E, 0x0128=>0x0129, - 0x03A7=>0x03C7, 0x013D=>0x013E, 0x0422=>0x0442, 0x005A=>0x007A, 0x0428=>0x0448, - 0x03A1=>0x03C1, 0x1E80=>0x1E81, 0x016C=>0x016D, 0x00D5=>0x00F5, 0x0055=>0x0075, - 0x0176=>0x0177, 0x00DC=>0x00FC, 0x1E56=>0x1E57, 0x03A3=>0x03C3, 0x041A=>0x043A, - 0x004D=>0x006D, 0x016A=>0x016B, 0x0170=>0x0171, 0x0424=>0x0444, 0x00CC=>0x00EC, - 0x0168=>0x0169, 0x039F=>0x03BF, 0x004B=>0x006B, 0x00D2=>0x00F2, 0x00C0=>0x00E0, - 0x0414=>0x0434, 0x03A9=>0x03C9, 0x1E6A=>0x1E6B, 0x00C3=>0x00E3, 0x042D=>0x044D, - 0x0416=>0x0436, 0x01A0=>0x01A1, 0x010C=>0x010D, 0x011C=>0x011D, 0x00D0=>0x00F0, - 0x013B=>0x013C, 0x040F=>0x045F, 0x040A=>0x045A, 0x00C8=>0x00E8, 0x03A5=>0x03C5, - 0x0046=>0x0066, 0x00DD=>0x00FD, 0x0043=>0x0063, 0x021A=>0x021B, 0x00CA=>0x00EA, - 0x0399=>0x03B9, 0x0179=>0x017A, 0x00CF=>0x00EF, 0x01AF=>0x01B0, 0x0045=>0x0065, - 0x039B=>0x03BB, 0x0398=>0x03B8, 0x039C=>0x03BC, 0x040C=>0x045C, 0x041F=>0x043F, - 0x042C=>0x044C, 0x00DE=>0x00FE, 0x00D0=>0x00F0, 0x1EF2=>0x1EF3, 0x0048=>0x0068, - 0x00CB=>0x00EB, 0x0110=>0x0111, 0x0413=>0x0433, 0x012E=>0x012F, 0x00C6=>0x00E6, - 0x0058=>0x0078, 0x0160=>0x0161, 0x016E=>0x016F, 0x0391=>0x03B1, 0x0407=>0x0457, - 0x0172=>0x0173, 0x0178=>0x00FF, 0x004F=>0x006F, 0x041B=>0x043B, 0x0395=>0x03B5, - 0x0425=>0x0445, 0x0120=>0x0121, 0x017D=>0x017E, 0x017B=>0x017C, 0x0396=>0x03B6, - 0x0392=>0x03B2, 0x0388=>0x03AD, 0x1E84=>0x1E85, 0x0174=>0x0175, 0x0051=>0x0071, - 0x0417=>0x0437, 0x1E0A=>0x1E0B, 0x0147=>0x0148, 0x0104=>0x0105, 0x0408=>0x0458, - 0x014C=>0x014D, 0x00CD=>0x00ED, 0x0059=>0x0079, 0x010A=>0x010B, 0x038F=>0x03CE, - 0x0052=>0x0072, 0x0410=>0x0430, 0x0405=>0x0455, 0x0402=>0x0452, 0x0126=>0x0127, - 0x0136=>0x0137, 0x012A=>0x012B, 0x038A=>0x03AF, 0x042B=>0x044B, 0x004C=>0x006C, - 0x0397=>0x03B7, 0x0124=>0x0125, 0x0218=>0x0219, 0x00DB=>0x00FB, 0x011E=>0x011F, - 0x041E=>0x043E, 0x1E40=>0x1E41, 0x039D=>0x03BD, 0x0106=>0x0107, 0x03AB=>0x03CB, - 0x0426=>0x0446, 0x00DE=>0x00FE, 0x00C7=>0x00E7, 0x03AA=>0x03CA, 0x0421=>0x0441, - 0x0412=>0x0432, 0x010E=>0x010F, 0x00D8=>0x00F8, 0x0057=>0x0077, 0x011A=>0x011B, - 0x0054=>0x0074, 0x004A=>0x006A, 0x040B=>0x045B, 0x0406=>0x0456, 0x0102=>0x0103, - 0x039B=>0x03BB, 0x00D1=>0x00F1, 0x041D=>0x043D, 0x038C=>0x03CC, 0x00C9=>0x00E9, - 0x00D0=>0x00F0, 0x0407=>0x0457, 0x0122=>0x0123, - ); - } - - $uni = utf8::to_unicode($str); - - if ($uni === FALSE) - return FALSE; - - for ($i = 0, $c = count($uni); $i < $c; $i++) - { - if (isset($UTF8_UPPER_TO_LOWER[$uni[$i]])) - { - $uni[$i] = $UTF8_UPPER_TO_LOWER[$uni[$i]]; - } - } - - return utf8::from_unicode($uni); -} \ No newline at end of file diff --git a/system/core/utf8/strtoupper.php b/system/core/utf8/strtoupper.php deleted file mode 100644 index f3ded739..00000000 --- a/system/core/utf8/strtoupper.php +++ /dev/null @@ -1,84 +0,0 @@ -0x0041, 0x03C6=>0x03A6, 0x0163=>0x0162, 0x00E5=>0x00C5, 0x0062=>0x0042, - 0x013A=>0x0139, 0x00E1=>0x00C1, 0x0142=>0x0141, 0x03CD=>0x038E, 0x0101=>0x0100, - 0x0491=>0x0490, 0x03B4=>0x0394, 0x015B=>0x015A, 0x0064=>0x0044, 0x03B3=>0x0393, - 0x00F4=>0x00D4, 0x044A=>0x042A, 0x0439=>0x0419, 0x0113=>0x0112, 0x043C=>0x041C, - 0x015F=>0x015E, 0x0144=>0x0143, 0x00EE=>0x00CE, 0x045E=>0x040E, 0x044F=>0x042F, - 0x03BA=>0x039A, 0x0155=>0x0154, 0x0069=>0x0049, 0x0073=>0x0053, 0x1E1F=>0x1E1E, - 0x0135=>0x0134, 0x0447=>0x0427, 0x03C0=>0x03A0, 0x0438=>0x0418, 0x00F3=>0x00D3, - 0x0440=>0x0420, 0x0454=>0x0404, 0x0435=>0x0415, 0x0449=>0x0429, 0x014B=>0x014A, - 0x0431=>0x0411, 0x0459=>0x0409, 0x1E03=>0x1E02, 0x00F6=>0x00D6, 0x00F9=>0x00D9, - 0x006E=>0x004E, 0x0451=>0x0401, 0x03C4=>0x03A4, 0x0443=>0x0423, 0x015D=>0x015C, - 0x0453=>0x0403, 0x03C8=>0x03A8, 0x0159=>0x0158, 0x0067=>0x0047, 0x00E4=>0x00C4, - 0x03AC=>0x0386, 0x03AE=>0x0389, 0x0167=>0x0166, 0x03BE=>0x039E, 0x0165=>0x0164, - 0x0117=>0x0116, 0x0109=>0x0108, 0x0076=>0x0056, 0x00FE=>0x00DE, 0x0157=>0x0156, - 0x00FA=>0x00DA, 0x1E61=>0x1E60, 0x1E83=>0x1E82, 0x00E2=>0x00C2, 0x0119=>0x0118, - 0x0146=>0x0145, 0x0070=>0x0050, 0x0151=>0x0150, 0x044E=>0x042E, 0x0129=>0x0128, - 0x03C7=>0x03A7, 0x013E=>0x013D, 0x0442=>0x0422, 0x007A=>0x005A, 0x0448=>0x0428, - 0x03C1=>0x03A1, 0x1E81=>0x1E80, 0x016D=>0x016C, 0x00F5=>0x00D5, 0x0075=>0x0055, - 0x0177=>0x0176, 0x00FC=>0x00DC, 0x1E57=>0x1E56, 0x03C3=>0x03A3, 0x043A=>0x041A, - 0x006D=>0x004D, 0x016B=>0x016A, 0x0171=>0x0170, 0x0444=>0x0424, 0x00EC=>0x00CC, - 0x0169=>0x0168, 0x03BF=>0x039F, 0x006B=>0x004B, 0x00F2=>0x00D2, 0x00E0=>0x00C0, - 0x0434=>0x0414, 0x03C9=>0x03A9, 0x1E6B=>0x1E6A, 0x00E3=>0x00C3, 0x044D=>0x042D, - 0x0436=>0x0416, 0x01A1=>0x01A0, 0x010D=>0x010C, 0x011D=>0x011C, 0x00F0=>0x00D0, - 0x013C=>0x013B, 0x045F=>0x040F, 0x045A=>0x040A, 0x00E8=>0x00C8, 0x03C5=>0x03A5, - 0x0066=>0x0046, 0x00FD=>0x00DD, 0x0063=>0x0043, 0x021B=>0x021A, 0x00EA=>0x00CA, - 0x03B9=>0x0399, 0x017A=>0x0179, 0x00EF=>0x00CF, 0x01B0=>0x01AF, 0x0065=>0x0045, - 0x03BB=>0x039B, 0x03B8=>0x0398, 0x03BC=>0x039C, 0x045C=>0x040C, 0x043F=>0x041F, - 0x044C=>0x042C, 0x00FE=>0x00DE, 0x00F0=>0x00D0, 0x1EF3=>0x1EF2, 0x0068=>0x0048, - 0x00EB=>0x00CB, 0x0111=>0x0110, 0x0433=>0x0413, 0x012F=>0x012E, 0x00E6=>0x00C6, - 0x0078=>0x0058, 0x0161=>0x0160, 0x016F=>0x016E, 0x03B1=>0x0391, 0x0457=>0x0407, - 0x0173=>0x0172, 0x00FF=>0x0178, 0x006F=>0x004F, 0x043B=>0x041B, 0x03B5=>0x0395, - 0x0445=>0x0425, 0x0121=>0x0120, 0x017E=>0x017D, 0x017C=>0x017B, 0x03B6=>0x0396, - 0x03B2=>0x0392, 0x03AD=>0x0388, 0x1E85=>0x1E84, 0x0175=>0x0174, 0x0071=>0x0051, - 0x0437=>0x0417, 0x1E0B=>0x1E0A, 0x0148=>0x0147, 0x0105=>0x0104, 0x0458=>0x0408, - 0x014D=>0x014C, 0x00ED=>0x00CD, 0x0079=>0x0059, 0x010B=>0x010A, 0x03CE=>0x038F, - 0x0072=>0x0052, 0x0430=>0x0410, 0x0455=>0x0405, 0x0452=>0x0402, 0x0127=>0x0126, - 0x0137=>0x0136, 0x012B=>0x012A, 0x03AF=>0x038A, 0x044B=>0x042B, 0x006C=>0x004C, - 0x03B7=>0x0397, 0x0125=>0x0124, 0x0219=>0x0218, 0x00FB=>0x00DB, 0x011F=>0x011E, - 0x043E=>0x041E, 0x1E41=>0x1E40, 0x03BD=>0x039D, 0x0107=>0x0106, 0x03CB=>0x03AB, - 0x0446=>0x0426, 0x00FE=>0x00DE, 0x00E7=>0x00C7, 0x03CA=>0x03AA, 0x0441=>0x0421, - 0x0432=>0x0412, 0x010F=>0x010E, 0x00F8=>0x00D8, 0x0077=>0x0057, 0x011B=>0x011A, - 0x0074=>0x0054, 0x006A=>0x004A, 0x045B=>0x040B, 0x0456=>0x0406, 0x0103=>0x0102, - 0x03BB=>0x039B, 0x00F1=>0x00D1, 0x043D=>0x041D, 0x03CC=>0x038C, 0x00E9=>0x00C9, - 0x00F0=>0x00D0, 0x0457=>0x0407, 0x0123=>0x0122, - ); - } - - $uni = utf8::to_unicode($str); - - if ($uni === FALSE) - return FALSE; - - for ($i = 0, $c = count($uni); $i < $c; $i++) - { - if (isset($UTF8_LOWER_TO_UPPER[$uni[$i]])) - { - $uni[$i] = $UTF8_LOWER_TO_UPPER[$uni[$i]]; - } - } - - return utf8::from_unicode($uni); -} \ No newline at end of file diff --git a/system/core/utf8/substr.php b/system/core/utf8/substr.php deleted file mode 100644 index daf66b81..00000000 --- a/system/core/utf8/substr.php +++ /dev/null @@ -1,75 +0,0 @@ -= $strlen OR ($length < 0 AND $length <= $offset - $strlen)) - return ''; - - // Whole string - if ($offset == 0 AND ($length === NULL OR $length >= $strlen)) - return $str; - - // Build regex - $regex = '^'; - - // Create an offset expression - if ($offset > 0) - { - // PCRE repeating quantifiers must be less than 65536, so repeat when necessary - $x = (int) ($offset / 65535); - $y = (int) ($offset % 65535); - $regex .= ($x == 0) ? '' : '(?:.{65535}){'.$x.'}'; - $regex .= ($y == 0) ? '' : '.{'.$y.'}'; - } - - // Create a length expression - if ($length === NULL) - { - $regex .= '(.*)'; // No length set, grab it all - } - // Find length from the left (positive length) - elseif ($length > 0) - { - // Reduce length so that it can't go beyond the end of the string - $length = min($strlen - $offset, $length); - - $x = (int) ($length / 65535); - $y = (int) ($length % 65535); - $regex .= '('; - $regex .= ($x == 0) ? '' : '(?:.{65535}){'.$x.'}'; - $regex .= '.{'.$y.'})'; - } - // Find length from the right (negative length) - else - { - $x = (int) (-$length / 65535); - $y = (int) (-$length % 65535); - $regex .= '(.*)'; - $regex .= ($x == 0) ? '' : '(?:.{65535}){'.$x.'}'; - $regex .= '.{'.$y.'}'; - } - - preg_match('/'.$regex.'/us', $str, $matches); - return $matches[1]; -} \ No newline at end of file diff --git a/system/core/utf8/substr_replace.php b/system/core/utf8/substr_replace.php deleted file mode 100644 index 45e2d2a3..00000000 --- a/system/core/utf8/substr_replace.php +++ /dev/null @@ -1,22 +0,0 @@ - 0x10FFFF)) - { - trigger_error('utf8::to_unicode: Illegal sequence or codepoint in UTF-8 at byte '.$i, E_USER_WARNING); - return FALSE; - } - - if (0xFEFF != $mUcs4) - { - // BOM is legal but we don't want to output it - $out[] = $mUcs4; - } - - // Initialize UTF-8 cache - $mState = 0; - $mUcs4 = 0; - $mBytes = 1; - } - } - else - { - // ((0xC0 & (*in) != 0x80) AND (mState != 0)) - // Incomplete multi-octet sequence - trigger_error('utf8::to_unicode: Incomplete multi-octet sequence in UTF-8 at byte '.$i, E_USER_WARNING); - return FALSE; - } - } - } - - return $out; -} \ No newline at end of file diff --git a/system/core/utf8/transliterate_to_ascii.php b/system/core/utf8/transliterate_to_ascii.php deleted file mode 100644 index 07461fbb..00000000 --- a/system/core/utf8/transliterate_to_ascii.php +++ /dev/null @@ -1,77 +0,0 @@ - 'a', 'ô' => 'o', 'ď' => 'd', 'ḟ' => 'f', 'ë' => 'e', 'š' => 's', 'ơ' => 'o', - 'ß' => 'ss', 'ă' => 'a', 'ř' => 'r', 'ț' => 't', 'ň' => 'n', 'ā' => 'a', 'ķ' => 'k', - 'ŝ' => 's', 'ỳ' => 'y', 'ņ' => 'n', 'ĺ' => 'l', 'ħ' => 'h', 'ṗ' => 'p', 'ó' => 'o', - 'ú' => 'u', 'ě' => 'e', 'é' => 'e', 'ç' => 'c', 'ẁ' => 'w', 'ċ' => 'c', 'õ' => 'o', - 'ṡ' => 's', 'ø' => 'o', 'ģ' => 'g', 'ŧ' => 't', 'ș' => 's', 'ė' => 'e', 'ĉ' => 'c', - 'ś' => 's', 'î' => 'i', 'ű' => 'u', 'ć' => 'c', 'ę' => 'e', 'ŵ' => 'w', 'ṫ' => 't', - 'ū' => 'u', 'č' => 'c', 'ö' => 'o', 'è' => 'e', 'ŷ' => 'y', 'ą' => 'a', 'ł' => 'l', - 'ų' => 'u', 'ů' => 'u', 'ş' => 's', 'ğ' => 'g', 'ļ' => 'l', 'ƒ' => 'f', 'ž' => 'z', - 'ẃ' => 'w', 'ḃ' => 'b', 'å' => 'a', 'ì' => 'i', 'ï' => 'i', 'ḋ' => 'd', 'ť' => 't', - 'ŗ' => 'r', 'ä' => 'a', 'í' => 'i', 'ŕ' => 'r', 'ê' => 'e', 'ü' => 'u', 'ò' => 'o', - 'ē' => 'e', 'ñ' => 'n', 'ń' => 'n', 'ĥ' => 'h', 'ĝ' => 'g', 'đ' => 'd', 'ĵ' => 'j', - 'ÿ' => 'y', 'ũ' => 'u', 'ŭ' => 'u', 'ư' => 'u', 'ţ' => 't', 'ý' => 'y', 'ő' => 'o', - 'â' => 'a', 'ľ' => 'l', 'ẅ' => 'w', 'ż' => 'z', 'ī' => 'i', 'ã' => 'a', 'ġ' => 'g', - 'ṁ' => 'm', 'ō' => 'o', 'ĩ' => 'i', 'ù' => 'u', 'į' => 'i', 'ź' => 'z', 'á' => 'a', - 'û' => 'u', 'þ' => 'th', 'ð' => 'dh', 'æ' => 'ae', 'µ' => 'u', 'ĕ' => 'e', - ); - } - - $str = str_replace( - array_keys($UTF8_LOWER_ACCENTS), - array_values($UTF8_LOWER_ACCENTS), - $str - ); - } - - if ($case >= 0) - { - if ($UTF8_UPPER_ACCENTS === NULL) - { - $UTF8_UPPER_ACCENTS = array( - 'À' => 'A', 'Ô' => 'O', 'Ď' => 'D', 'Ḟ' => 'F', 'Ë' => 'E', 'Š' => 'S', 'Ơ' => 'O', - 'Ă' => 'A', 'Ř' => 'R', 'Ț' => 'T', 'Ň' => 'N', 'Ā' => 'A', 'Ķ' => 'K', 'Ĕ' => 'E', - 'Ŝ' => 'S', 'Ỳ' => 'Y', 'Ņ' => 'N', 'Ĺ' => 'L', 'Ħ' => 'H', 'Ṗ' => 'P', 'Ó' => 'O', - 'Ú' => 'U', 'Ě' => 'E', 'É' => 'E', 'Ç' => 'C', 'Ẁ' => 'W', 'Ċ' => 'C', 'Õ' => 'O', - 'Ṡ' => 'S', 'Ø' => 'O', 'Ģ' => 'G', 'Ŧ' => 'T', 'Ș' => 'S', 'Ė' => 'E', 'Ĉ' => 'C', - 'Ś' => 'S', 'Î' => 'I', 'Ű' => 'U', 'Ć' => 'C', 'Ę' => 'E', 'Ŵ' => 'W', 'Ṫ' => 'T', - 'Ū' => 'U', 'Č' => 'C', 'Ö' => 'O', 'È' => 'E', 'Ŷ' => 'Y', 'Ą' => 'A', 'Ł' => 'L', - 'Ų' => 'U', 'Ů' => 'U', 'Ş' => 'S', 'Ğ' => 'G', 'Ļ' => 'L', 'Ƒ' => 'F', 'Ž' => 'Z', - 'Ẃ' => 'W', 'Ḃ' => 'B', 'Å' => 'A', 'Ì' => 'I', 'Ï' => 'I', 'Ḋ' => 'D', 'Ť' => 'T', - 'Ŗ' => 'R', 'Ä' => 'A', 'Í' => 'I', 'Ŕ' => 'R', 'Ê' => 'E', 'Ü' => 'U', 'Ò' => 'O', - 'Ē' => 'E', 'Ñ' => 'N', 'Ń' => 'N', 'Ĥ' => 'H', 'Ĝ' => 'G', 'Đ' => 'D', 'Ĵ' => 'J', - 'Ÿ' => 'Y', 'Ũ' => 'U', 'Ŭ' => 'U', 'Ư' => 'U', 'Ţ' => 'T', 'Ý' => 'Y', 'Ő' => 'O', - 'Â' => 'A', 'Ľ' => 'L', 'Ẅ' => 'W', 'Ż' => 'Z', 'Ī' => 'I', 'Ã' => 'A', 'Ġ' => 'G', - 'Ṁ' => 'M', 'Ō' => 'O', 'Ĩ' => 'I', 'Ù' => 'U', 'Į' => 'I', 'Ź' => 'Z', 'Á' => 'A', - 'Û' => 'U', 'Þ' => 'Th', 'Ð' => 'Dh', 'Æ' => 'Ae', - ); - } - - $str = str_replace( - array_keys($UTF8_UPPER_ACCENTS), - array_values($UTF8_UPPER_ACCENTS), - $str - ); - } - - return $str; -} \ No newline at end of file diff --git a/system/core/utf8/trim.php b/system/core/utf8/trim.php deleted file mode 100644 index 7434102a..00000000 --- a/system/core/utf8/trim.php +++ /dev/null @@ -1,17 +0,0 @@ - Date: Mon, 21 Dec 2009 20:05:27 -0800 Subject: Updated Kohana to r4724 --- system/config/cache.php | 3 + system/config/database.php | 3 +- system/core/Kohana.php | 39 +- system/core/Kohana_Exception.php | 4 +- system/helpers/form.php | 28 +- system/helpers/inflector.php | 6 +- system/helpers/request.php | 4 +- system/helpers/security.php | 13 +- system/helpers/text.php | 46 +- system/helpers/url.php | 21 +- system/helpers/utf8.php | 2 +- system/libraries/Cache.php | 87 +- system/libraries/Controller.php | 8 +- system/libraries/Database.php | 23 +- system/libraries/Database_Builder.php | 103 +- system/libraries/Database_Mysql.php | 9 +- system/libraries/Database_Mysqli.php | 32 +- system/libraries/Input.php | 8 +- system/libraries/Kohana_PHP_Exception.php | 4 +- system/libraries/ORM.php | 56 +- system/libraries/Profiler.php | 4 +- system/libraries/Router.php | 10 +- system/libraries/Validation.php | 155 +- system/libraries/drivers/Cache/File.php | 4 +- system/libraries/drivers/Cache/Memcache.php | 7 +- system/libraries/drivers/Cache/Xcache.php | 2 +- system/messages/core.php | 9 +- system/messages/validation/default.php | 17 + system/vendor/Markdown.php | 2909 --------------------------- 29 files changed, 458 insertions(+), 3158 deletions(-) create mode 100644 system/messages/validation/default.php delete mode 100644 system/vendor/Markdown.php (limited to 'system/core') diff --git a/system/config/cache.php b/system/config/cache.php index 68682c0a..76af4f6a 100644 --- a/system/config/cache.php +++ b/system/config/cache.php @@ -19,10 +19,13 @@ * thirty minutes. Specific lifetime can also be set when creating a new cache. * Setting this to 0 will never automatically delete caches. * + * prefix - Adds a prefix to all keys and tags. This can have a severe performance impact. + * */ $config['default'] = array ( 'driver' => 'file', 'params' => array('directory' => APPPATH.'cache', 'gc_probability' => 1000), 'lifetime' => 1800, + 'prefix' => NULL ); diff --git a/system/config/database.php b/system/config/database.php index 2e53fa2b..36e4614c 100644 --- a/system/config/database.php +++ b/system/config/database.php @@ -35,7 +35,8 @@ $config['default'] = array 'host' => 'localhost', 'port' => FALSE, 'socket' => FALSE, - 'database' => 'kohana' + 'database' => 'kohana', + 'params' => NULL, ), 'character_set' => 'utf8', 'table_prefix' => '', diff --git a/system/core/Kohana.php b/system/core/Kohana.php index 5258d635..740adb80 100644 --- a/system/core/Kohana.php +++ b/system/core/Kohana.php @@ -2,7 +2,7 @@ /** * Provides Kohana-specific helper functions. This is where the magic happens! * - * $Id: Kohana.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Kohana.php 4724 2009-12-21 16:28:54Z isaiah $ * * @package Core * @author Kohana Team @@ -45,6 +45,9 @@ abstract class Kohana_Core { protected static $internal_cache_key; protected static $internal_cache_encrypt; + // Server API that PHP is using. Allows testing of different APIs. + public static $server_api = PHP_SAPI; + /** * Sets up the PHP environment. Adds error/exception handling, output * buffering, and adds an auto-loading method for loading classes. @@ -162,6 +165,35 @@ abstract class Kohana_Core { // Set and validate the timezone date_default_timezone_set(Kohana::config('locale.timezone')); + // register_globals is enabled + if (ini_get('register_globals')) + { + if (isset($_REQUEST['GLOBALS'])) + { + // Prevent GLOBALS override attacks + exit('Global variable overload attack.'); + } + + // Destroy the REQUEST global + $_REQUEST = array(); + + // These globals are standard and should not be removed + $preserve = array('GLOBALS', '_REQUEST', '_GET', '_POST', '_FILES', '_COOKIE', '_SERVER', '_ENV', '_SESSION'); + + // This loop has the same effect as disabling register_globals + foreach (array_diff(array_keys($GLOBALS), $preserve) as $key) + { + global $$key; + $$key = NULL; + + // Unset the global variable + unset($GLOBALS[$key], $$key); + } + + // Warn the developer about register globals + Kohana_Log::add('debug', 'Disable register_globals! It is evil and deprecated: http://php.net/register_globals'); + } + // Enable Kohana routing Event::add('system.routing', array('Router', 'find_uri')); Event::add('system.routing', array('Router', 'setup')); @@ -602,7 +634,7 @@ abstract class Kohana_Core { header('Content-Encoding: '.$compress); // Sending Content-Length in CGI can result in unexpected behavior - if (stripos(PHP_SAPI, 'cgi') === FALSE) + if (stripos(Kohana::$server_api, 'cgi') === FALSE) { header('Content-Length: '.strlen($output)); } @@ -876,9 +908,6 @@ abstract class Kohana_Core { $group = explode('.', $key, 2); $group = $group[0]; - // Get locale name - $locale = Kohana::config('locale.language.0'); - if ( ! isset(Kohana::$internal_cache['messages'][$group])) { // Messages for this group diff --git a/system/core/Kohana_Exception.php b/system/core/Kohana_Exception.php index cdb06a62..2eb28f75 100644 --- a/system/core/Kohana_Exception.php +++ b/system/core/Kohana_Exception.php @@ -2,7 +2,7 @@ /** * Kohana Exceptions * - * $Id: Kohana_Exception.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Kohana_Exception.php 4692 2009-12-04 15:59:44Z cbandy $ * * @package Core * @author Kohana Team @@ -197,7 +197,7 @@ class Kohana_Exception_Core extends Exception { echo Kohana_Exception::text($e), "\n"; } - if (PHP_SAPI === 'cli') + if (Kohana::$server_api === 'cli') { // Exit with an error status exit(1); diff --git a/system/helpers/form.php b/system/helpers/form.php index 901edc91..4225b1b6 100644 --- a/system/helpers/form.php +++ b/system/helpers/form.php @@ -2,7 +2,7 @@ /** * Form helper class. * - * $Id: form.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: form.php 4699 2009-12-08 18:45:14Z isaiah $ * * @package Core * @author Kohana Team @@ -421,32 +421,6 @@ class form_Core { if (empty($attr)) return ''; - if (isset($attr['name']) AND empty($attr['id']) AND strpos($attr['name'], '[') === FALSE) - { - if ($type === NULL AND ! empty($attr['type'])) - { - // Set the type by the attributes - $type = $attr['type']; - } - - switch ($type) - { - case 'text': - case 'textarea': - case 'password': - case 'select': - case 'checkbox': - case 'file': - case 'image': - case 'button': - case 'submit': - case 'hidden': - // Only specific types of inputs use name to id matching - $attr['id'] = $attr['name']; - break; - } - } - $order = array ( 'action', diff --git a/system/helpers/inflector.php b/system/helpers/inflector.php index 9bd281db..5a2910c0 100644 --- a/system/helpers/inflector.php +++ b/system/helpers/inflector.php @@ -2,7 +2,7 @@ /** * Inflector helper class. * - * $Id: inflector.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: inflector.php 4722 2009-12-19 17:47:34Z isaiah $ * * @package Core * @author Kohana Team @@ -241,9 +241,9 @@ class inflector_Core { } /** - * Makes an underscored or dashed phrase human-reable. + * Makes an underscored or dashed phrase human-readable. * - * @param string phrase to make human-reable + * @param string phrase to make human-readable * @return string */ public static function humanize($str) diff --git a/system/helpers/request.php b/system/helpers/request.php index 4770d64b..31afee4e 100644 --- a/system/helpers/request.php +++ b/system/helpers/request.php @@ -2,7 +2,7 @@ /** * Request helper class. * - * $Id: request.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: request.php 4692 2009-12-04 15:59:44Z cbandy $ * * @package Core * @author Kohana Team @@ -61,7 +61,7 @@ class request_Core { */ public static function protocol() { - if (PHP_SAPI === 'cli') + if (Kohana::$server_api === 'cli') { return NULL; } diff --git a/system/helpers/security.php b/system/helpers/security.php index 9eb82a58..33e5118e 100644 --- a/system/helpers/security.php +++ b/system/helpers/security.php @@ -2,7 +2,7 @@ /** * Security helper class. * - * $Id: security.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: security.php 4698 2009-12-08 18:39:33Z isaiah $ * * @package Core * @author Kohana Team @@ -34,15 +34,4 @@ class security_Core { return preg_replace('#\s]*)["\']?[^>]*)?>#is', '$1', $str); } - /** - * Remove PHP tags from a string. - * - * @param string string to sanitize - * @return string - */ - public static function encode_php_tags($str) - { - return str_replace(array(''), array('<?', '?>'), $str); - } - } // End security \ No newline at end of file diff --git a/system/helpers/text.php b/system/helpers/text.php index 66bcd243..ed7f9cbf 100644 --- a/system/helpers/text.php +++ b/system/helpers/text.php @@ -2,7 +2,7 @@ /** * Text helper class. * - * $Id: text.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: text.php 4689 2009-12-02 01:39:24Z isaiah $ * * @package Core * @author Kohana Team @@ -298,27 +298,37 @@ class text_Core { */ public static function auto_link_urls($text) { - // Finds all http/https/ftp/ftps links that are not part of an existing html anchor - if (preg_match_all('~\b(?)(?:ht|f)tps?://\S+(?:/|\b)~i', $text, $matches)) - { - foreach ($matches[0] as $match) - { - // Replace each link with an anchor - $text = str_replace($match, html::anchor($match), $text); - } - } - // Find all naked www.links.com (without http://) - if (preg_match_all('~\b(? $name)); + throw new Cache_Exception('The :group: group is not defined in your configuration.', array(':group:' => $name)); } if (is_array($config)) @@ -74,7 +74,7 @@ class Cache_Core { // Load the driver if ( ! Kohana::auto_load($driver)) - throw new Kohana_Exception('The :driver: driver for the :class: library could not be found', + throw new Cache_Exception('The :driver: driver for the :class: library could not be found', array(':driver:' => $this->config['driver'], ':class:' => get_class($this))); // Initialize the driver @@ -82,7 +82,7 @@ class Cache_Core { // Validate the driver if ( ! ($this->driver instanceof Cache_Driver)) - throw new Kohana_Exception('The :driver: driver for the :library: library must implement the :interface: interface', + throw new Cache_Exception('The :driver: driver for the :library: library must implement the :interface: interface', array(':driver:' => $this->config['driver'], ':library:' => get_class($this), ':interface:' => 'Cache_Driver')); Kohana_Log::add('debug', 'Cache Library initialized'); @@ -103,6 +103,16 @@ class Cache_Core { $key = array($key => $value); } + if ($this->config['prefix'] !== NULL) + { + $key = $this->add_prefix($key); + + if ($tags !== NULL) + { + $tags = $this->add_prefix($tags, FALSE); + } + } + return $this->driver->set($key, $tags, $lifetime); } @@ -119,6 +129,17 @@ class Cache_Core { $single = TRUE; } + if ($this->config['prefix'] !== NULL) + { + $keys = $this->add_prefix($keys, FALSE); + + if ( ! $single) + { + return $this->strip_prefix($this->driver->get($keys, $single)); + } + + } + return $this->driver->get($keys, $single); } @@ -132,7 +153,15 @@ class Cache_Core { $tags = array($tags); } - return $this->driver->get_tag($tags); + if ($this->config['prefix'] !== NULL) + { + $tags = $this->add_prefix($tags, FALSE); + return $this->strip_prefix($this->driver->get_tag($tags)); + } + else + { + return $this->driver->get_tag($tags); + } } /** @@ -145,6 +174,11 @@ class Cache_Core { $keys = array($keys); } + if ($this->config['prefix'] !== NULL) + { + $keys = $this->add_prefix($keys, FALSE); + } + return $this->driver->delete($keys); } @@ -158,6 +192,11 @@ class Cache_Core { $tags = array($tags); } + if ($this->config['prefix'] !== NULL) + { + $tags = $this->add_prefix($tags, FALSE); + } + return $this->driver->delete_tag($tags); } @@ -168,4 +207,44 @@ class Cache_Core { { return $this->driver->delete_all(); } + + /** + * Add a prefix to keys or tags + */ + protected function add_prefix($array, $to_key = TRUE) + { + $out = array(); + + foreach($array as $key => $value) + { + if ($to_key) + { + $out[$this->config['prefix'].$key] = $value; + } + else + { + $out[$key] = $this->config['prefix'].$value; + } + } + + return $out; + } + + /** + * Strip a prefix to keys or tags + */ + protected function strip_prefix($array) + { + $out = array(); + + $start = strlen($this->config['prefix']); + + foreach($array as $key => $value) + { + $out[substr($key, $start)] = $value; + } + + return $out; + } + } // End Cache Library \ No newline at end of file diff --git a/system/libraries/Controller.php b/system/libraries/Controller.php index da84bfc1..830c06e5 100644 --- a/system/libraries/Controller.php +++ b/system/libraries/Controller.php @@ -3,7 +3,7 @@ * Kohana Controller class. The controller class must be extended to work * properly, so this class is defined as abstract. * - * $Id: Controller.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Controller.php 4721 2009-12-17 23:02:07Z isaiah $ * * @package Core * @author Kohana Team @@ -27,12 +27,6 @@ abstract class Controller_Core { // Set the instance to the first controller loaded Kohana::$instance = $this; } - - // URI should always be available - $this->uri = URI::instance(); - - // Input should always be available - $this->input = Input::instance(); } /** diff --git a/system/libraries/Database.php b/system/libraries/Database.php index d3716c59..38a38fbf 100644 --- a/system/libraries/Database.php +++ b/system/libraries/Database.php @@ -1,9 +1,9 @@ cache instanceof Cache) + if ($this->cache instanceof Cache AND ($type == NULL OR $type == Database::CROSS_REQUEST)) { // Using cross-request Cache library if ($sql === TRUE) @@ -370,7 +373,7 @@ abstract class Database_Core { $this->cache->delete_all(); } } - elseif (is_array($this->cache)) + elseif (is_array($this->cache) AND ($type == NULL OR $type == Database::PER_REQUEST)) { // Using per-request memory cache if ($sql === TRUE) diff --git a/system/libraries/Database_Builder.php b/system/libraries/Database_Builder.php index 5a5a058c..4e6951e7 100644 --- a/system/libraries/Database_Builder.php +++ b/system/libraries/Database_Builder.php @@ -29,6 +29,7 @@ class Database_Builder_Core { protected $columns = array(); protected $values = array(); protected $type; + protected $distinct = FALSE; // TTL for caching (using Cache library) protected $ttl = FALSE; @@ -77,7 +78,8 @@ class Database_Builder_Core { if ($this->type === Database::SELECT) { // SELECT columns FROM table - $sql = 'SELECT '.$this->compile_select(); + $sql = $this->distinct ? 'SELECT DISTINCT ' : 'SELECT '; + $sql .= $this->compile_select(); if ( ! empty($this->from)) { @@ -146,7 +148,13 @@ class Database_Builder_Core { foreach ($this->select as $alias => $name) { - if (is_string($alias)) + if ($name instanceof Database_Builder) + { + // Using a subquery + $name->db = $this->db; + $vals[] = '('.(string) $name.') AS '.$this->db->quote_column($alias); + } + elseif (is_string($alias)) { $vals[] = $this->db->quote_column($name, $alias); } @@ -374,28 +382,48 @@ class Database_Builder_Core { /** * Add conditions to the HAVING clause (AND) * - * @param mixed Column name or array of columns => vals + * @param mixed Column name or array of triplets * @param string Operation to perform * @param mixed Value * @return Database_Builder */ public function and_having($columns, $op = '=', $value = NULL) { - $this->having[] = array('AND' => array($columns, $op, $value)); + if (is_array($columns)) + { + foreach ($columns as $column) + { + $this->having[] = array('AND' => $column); + } + } + else + { + $this->having[] = array('AND' => array($columns, $op, $value)); + } return $this; } /** * Add conditions to the HAVING clause (OR) * - * @param mixed Column name or array of columns => vals + * @param mixed Column name or array of triplets * @param string Operation to perform * @param mixed Value * @return Database_Builder */ public function or_having($columns, $op = '=', $value = NULL) { - $this->having[] = array('OR' => array($columns, $op, $value)); + if (is_array($columns)) + { + foreach ($columns as $column) + { + $this->having[] = array('OR' => $column); + } + } + else + { + $this->having[] = array('OR' => array($columns, $op, $value)); + } return $this; } @@ -408,13 +436,25 @@ class Database_Builder_Core { */ public function order_by($columns, $direction = NULL) { - if (is_string($columns)) + if (is_array($columns)) { - $columns = array($columns => $direction); + foreach ($columns as $column => $direction) + { + if (is_string($column)) + { + $this->order_by[] = array($column => $direction); + } + else + { + // $direction is the column name when the array key is numeric + $this->order_by[] = array($direction => NULL); + } + } + } + else + { + $this->order_by[] = array($columns => $direction); } - - $this->order_by[] = $columns; - return $this; } @@ -542,28 +582,48 @@ class Database_Builder_Core { /** * Add conditions to the WHERE clause (AND) * - * @param mixed Column name or array of columns => vals + * @param mixed Column name or array of triplets * @param string Operation to perform * @param mixed Value * @return Database_Builder */ public function and_where($columns, $op = '=', $value = NULL) { - $this->where[] = array('AND' => array($columns, $op, $value)); + if (is_array($columns)) + { + foreach ($columns as $column) + { + $this->where[] = array('AND' => $column); + } + } + else + { + $this->where[] = array('AND' => array($columns, $op, $value)); + } return $this; } /** * Add conditions to the WHERE clause (OR) * - * @param mixed Column name or array of columns => vals + * @param mixed Column name or array of triplets * @param string Operation to perform * @param mixed Value * @return Database_Builder */ public function or_where($columns, $op = '=', $value = NULL) { - $this->where[] = array('OR' => array($columns, $op, $value)); + if (is_array($columns)) + { + foreach ($columns as $column) + { + $this->where[] = array('OR' => $column); + } + } + else + { + $this->where[] = array('OR' => array($columns, $op, $value)); + } return $this; } @@ -779,6 +839,19 @@ class Database_Builder_Core { return $this; } + /** + * Create a SELECT query and specify selected columns + * + * @param string|array column name or array(alias => column) + * @return Database_Builder + */ + public function select_distinct($columns = NULL) + { + $this->select($columns); + $this->distinct = TRUE; + return $this; + } + /** * Create an UPDATE query * diff --git a/system/libraries/Database_Mysql.php b/system/libraries/Database_Mysql.php index cb531194..a5775037 100644 --- a/system/libraries/Database_Mysql.php +++ b/system/libraries/Database_Mysql.php @@ -2,7 +2,7 @@ /** * MySQL database connection. * - * $Id: Database_Mysql.php 4684 2009-11-18 14:26:48Z isaiah $ + * $Id: Database_Mysql.php 4712 2009-12-10 21:47:09Z cbandy $ * * @package Kohana * @author Kohana Team @@ -31,16 +31,15 @@ class Database_Mysql_Core extends Database { extract($this->config['connection']); - // Set the connection type - $connect = ($this->config['persistent'] === TRUE) ? 'mysql_pconnect' : 'mysql_connect'; - $host = isset($host) ? $host : $socket; $port = isset($port) ? ':'.$port : ''; try { // Connect to the database - $this->connection = $connect($host.$port, $user, $pass, TRUE); + $this->connection = ($this->config['persistent'] === TRUE) + ? mysql_pconnect($host.$port, $user, $pass, $params) + : mysql_connect($host.$port, $user, $pass, TRUE, $params); } catch (Kohana_PHP_Exception $e) { diff --git a/system/libraries/Database_Mysqli.php b/system/libraries/Database_Mysqli.php index 523fcb19..08ed99df 100644 --- a/system/libraries/Database_Mysqli.php +++ b/system/libraries/Database_Mysqli.php @@ -2,7 +2,7 @@ /** * MySQL database connection. * - * $Id: Database_Mysqli.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Database_Mysqli.php 4712 2009-12-10 21:47:09Z cbandy $ * * @package Kohana * @author Kohana Team @@ -29,29 +29,29 @@ class Database_Mysqli_Core extends Database_Mysql { $host = isset($host) ? $host : $socket; - if($this->connection = new mysqli($host, $user, $pass, $database, $port)) { + $mysqli = mysqli_init(); - if (isset($this->config['character_set'])) - { - // Set the character set - $this->set_charset($this->config['character_set']); - } + if ( ! $mysqli->real_connect($host, $user, $pass, $database, $port, $socket, $params)) + throw new Database_Exception('#:errno: :error', + array(':error' => $mysqli->connect_error, ':errno' => $mysqli->connect_errno)); - // Clear password after successful connect - $this->db_config['connection']['pass'] = NULL; + $this->connection = $mysqli; - return $this->connection; + if (isset($this->config['character_set'])) + { + // Set the character set + $this->set_charset($this->config['character_set']); } - - // Unable to connect to the database - throw new Database_Exception('#:errno: :error', - array(':error' => $this->connection->connect_error, - ':errno' => $this->connection->connect_errno)); } public function disconnect() { - return is_object($this->connection) and $this->connection->close(); + if (is_object($this->connection)) + { + $this->connection->close(); + } + + $this->connection = NULL; } public function set_charset($charset) diff --git a/system/libraries/Input.php b/system/libraries/Input.php index 83f0ed17..04403854 100644 --- a/system/libraries/Input.php +++ b/system/libraries/Input.php @@ -2,7 +2,7 @@ /** * Input library. * - * $Id: Input.php 4680 2009-11-10 01:57:00Z isaiah $ + * $Id: Input.php 4720 2009-12-17 21:15:03Z isaiah $ * * @package Core * @author Kohana Team @@ -54,7 +54,7 @@ class Input_Core { $_COOKIE = Input::clean($_COOKIE); $_SERVER = Input::clean($_SERVER); - if (PHP_SAPI == 'cli') + if (Kohana::$server_api === 'cli') { // Convert command line arguments $_SERVER['argv'] = Input::clean($_SERVER['argv']); @@ -311,7 +311,7 @@ class Input_Core { if (trim($data) === '') return $data; - if ($tool === TRUE) + if (is_bool($tool)) { $tool = 'default'; } @@ -371,7 +371,7 @@ class Input_Core { $data = html_entity_decode($data, ENT_COMPAT, 'UTF-8'); // Remove any attribute starting with "on" or xmlns - $data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data); + $data = preg_replace('#(?:on[a-z]+|xmlns)\s*=\s*[\'"\x00-\x20]?[^\'>"]*[\'"\x00-\x20]?\s?#iu', '', $data); // Remove javascript: and vbscript: protocols $data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data); diff --git a/system/libraries/Kohana_PHP_Exception.php b/system/libraries/Kohana_PHP_Exception.php index fca5b30b..019c686b 100644 --- a/system/libraries/Kohana_PHP_Exception.php +++ b/system/libraries/Kohana_PHP_Exception.php @@ -2,7 +2,7 @@ /** * Kohana PHP Error Exceptions * - * $Id: Kohana_PHP_Exception.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Kohana_PHP_Exception.php 4687 2009-11-30 21:59:26Z isaiah $ * * @package Core * @author Kohana Team @@ -89,7 +89,7 @@ class Kohana_PHP_Exception_Core extends Kohana_Exception { */ public static function shutdown_handler() { - if (Kohana_PHP_Exception::$enabled AND $error = error_get_last()) + if (Kohana_PHP_Exception::$enabled AND $error = error_get_last() AND (error_reporting() & $error['type'])) { // Fake an exception for nice debugging Kohana_Exception::handle(new Kohana_PHP_Exception($error['type'], $error['message'], $error['file'], $error['line'])); diff --git a/system/libraries/ORM.php b/system/libraries/ORM.php index eff22fc0..2f2feed5 100644 --- a/system/libraries/ORM.php +++ b/system/libraries/ORM.php @@ -8,7 +8,7 @@ * [ref-orm]: http://wikipedia.org/wiki/Object-relational_mapping * [ref-act]: http://wikipedia.org/wiki/Active_record * - * $Id: ORM.php 4682 2009-11-11 20:53:23Z isaiah $ + * $Id: ORM.php 4711 2009-12-10 20:40:52Z isaiah $ * * @package ORM * @author Kohana Team @@ -102,7 +102,7 @@ class ORM_Core { $this->object_name = strtolower(substr(get_class($this), 0, -6)); $this->object_plural = inflector::plural($this->object_name); - if (!isset($this->sorting)) + if ( ! isset($this->sorting)) { // Default sorting $this->sorting = array($this->primary_key => 'asc'); @@ -119,7 +119,7 @@ class ORM_Core { // Load an object $this->_load_values((array) $id); } - elseif (!empty($id)) + elseif ( ! empty($id)) { // Set the object's primary key, but don't load it until needed $this->object[$this->primary_key] = $id; @@ -234,7 +234,7 @@ class ORM_Core { switch ($num_args) { case 0: - if (in_array($method, array('open', 'close', 'cache'))) + if (in_array($method, array('open', 'and_open', 'or_open', 'close', 'cache'))) { // Should return ORM, not Database $this->db_builder->$method(); @@ -320,12 +320,12 @@ class ORM_Core { } // Foreign key lies in this table (this model belongs_to target model) - $where = array($model->foreign_key(TRUE) => $this->object[$this->foreign_key($column)]); + $where = array($model->foreign_key(TRUE), '=', $this->object[$this->foreign_key($column)]); } else { // Foreign key lies in the target table (this model has_one target model) - $where = array($this->foreign_key($column, $model->table_name) => $this->primary_key_value); + $where = array($this->foreign_key($column, $model->table_name), '=', $this->primary_key_value); } // one<>alias:one relationship @@ -524,16 +524,6 @@ class ORM_Core { unset($this->object[$column], $this->changed[$column], $this->related[$column]); } - /** - * Displays the primary key of a model when it is converted to a string. - * - * @return string - */ - public function __toString() - { - return (string) $this->primary_key_value; - } - /** * Returns the values of this object as an array. * @@ -665,7 +655,7 @@ class ORM_Core { if (is_array($id)) { // Search for all clauses - $this->db_builder->where($id); + $this->db_builder->where(array($id)); } else { @@ -767,6 +757,9 @@ class ORM_Core { ORM_Validation_Exception::handle_validation($this->table_name, $array); } + // Fields may have been modified by filters + $this->object = array_merge($this->object, $array->getArrayCopy()); + // Return validation status return $this; } @@ -782,8 +775,10 @@ class ORM_Core { if ( ! empty($this->changed)) { // Require model validation before saving - if (!$this->_valid) + if ( ! $this->_valid) + { $this->validate(); + } $data = array(); foreach ($this->changed as $column) @@ -881,8 +876,8 @@ class ORM_Core { } // Foreign keys for the join table - $object_fk = $this->foreign_key(NULL); - $related_fk = $model->foreign_key(NULL); + $object_fk = $this->foreign_key($join_table); + $related_fk = $model->foreign_key($join_table); if ( ! empty($added)) { @@ -909,6 +904,12 @@ class ORM_Core { } } + if ($this->saved() === TRUE) + { + // Clear the per-request database cache + $this->db->clear_cache(NULL, Database::PER_REQUEST); + } + return $this; } @@ -933,6 +934,9 @@ class ORM_Core { ->where($this->primary_key, '=', $id) ->execute($this->db); + // Clear the per-request database cache + $this->db->clear_cache(NULL, Database::PER_REQUEST); + return $this->clear(); } @@ -965,6 +969,9 @@ class ORM_Core { return $this; } + // Clear the per-request database cache + $this->db->clear_cache(NULL, Database::PER_REQUEST); + return $this->clear(); } @@ -1154,12 +1161,13 @@ class ORM_Core { * * @chainable * @param string SQL query to clear + * @param integer Type of cache to clear, Database::CROSS_REQUEST or Database::PER_REQUEST * @return ORM */ - public function clear_cache($sql = NULL) + public function clear_cache($sql = NULL, $type = NULL) { // Proxy to database - $this->db->clear_cache($sql); + $this->db->clear_cache($sql, $type); ORM::$column_cache = array(); @@ -1550,9 +1558,9 @@ class ORM_Core { */ protected function load_relations($table, ORM $model) { - $result = db::select(array('id' => $model->foreign_key(NULL))) + $result = db::select(array('id' => $model->foreign_key($table))) ->from($table) - ->where($this->foreign_key(NULL, $table), '=', $this->primary_key_value) + ->where($this->foreign_key($table, $table), '=', $this->primary_key_value) ->execute($this->db) ->as_object(); diff --git a/system/libraries/Profiler.php b/system/libraries/Profiler.php index b7a5ecae..940e365d 100644 --- a/system/libraries/Profiler.php +++ b/system/libraries/Profiler.php @@ -8,7 +8,7 @@ * POST Data - The name and values of any POST data submitted to the current page. * Cookie Data - All cookies sent for the current request. * - * $Id: Profiler.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Profiler.php 4719 2009-12-17 04:31:48Z isaiah $ * * @package Profiler * @author Kohana Team @@ -101,7 +101,7 @@ class Profiler_Core { // Don't display if there's no profiles if (empty(Profiler::$profiles)) - return $output; + return Kohana::$output; $styles = ''; foreach (Profiler::$profiles as $profile) diff --git a/system/libraries/Router.php b/system/libraries/Router.php index 82dbb9b5..18e01af2 100644 --- a/system/libraries/Router.php +++ b/system/libraries/Router.php @@ -2,7 +2,7 @@ /** * Router * - * $Id: Router.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Router.php 4693 2009-12-04 17:11:16Z cbandy $ * * @package Core * @author Kohana Team @@ -38,7 +38,7 @@ class Router_Core { if ( ! empty($_SERVER['QUERY_STRING'])) { // Set the query string to the current query string - Router::$query_string = '?'.trim(urldecode($_SERVER['QUERY_STRING']), '&/'); + Router::$query_string = '?'.urldecode(trim($_SERVER['QUERY_STRING'], '&')); } if (Router::$routes === NULL) @@ -173,7 +173,7 @@ class Router_Core { */ public static function find_uri() { - if (PHP_SAPI === 'cli') + if (Kohana::$server_api === 'cli') { // Command line requires a bit of hacking if (isset($_SERVER['argv'][1])) @@ -181,9 +181,9 @@ class Router_Core { Router::$current_uri = $_SERVER['argv'][1]; // Remove GET string from segments - if (($query = strpos(Router::$current_uri, '?')) !== FALSE) + if (strpos(Router::$current_uri, '?') !== FALSE) { - list (Router::$current_uri, $query) = explode('?', Router::$current_uri, 2); + list(Router::$current_uri, $query) = explode('?', Router::$current_uri, 2); // Parse the query string into $_GET parse_str($query, $_GET); diff --git a/system/libraries/Validation.php b/system/libraries/Validation.php index f340e63c..47f34584 100644 --- a/system/libraries/Validation.php +++ b/system/libraries/Validation.php @@ -2,7 +2,7 @@ /** * Validation library. * - * $Id: Validation.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Validation.php 4713 2009-12-10 22:25:38Z isaiah $ * * @package Validation * @author Kohana Team @@ -26,12 +26,12 @@ class Validation_Core extends ArrayObject { protected $errors = array(); protected $messages = array(); + // Field labels + protected $labels = array(); + // Fields that are expected to be arrays protected $array_fields = array(); - // Checks if there is data to validate. - protected $submitted; - /** * Creates a new Validation instance. * @@ -52,9 +52,6 @@ class Validation_Core extends ArrayObject { */ public function __construct(array $array) { - // The array is submitted if the array is not empty - $this->submitted = ! empty($array); - parent::__construct($array, ArrayObject::ARRAY_AS_PROPS | ArrayObject::STD_PROP_LIST); } @@ -85,21 +82,6 @@ class Validation_Core extends ArrayObject { return $copy; } - /** - * Test if the data has been submitted. - * - * @return boolean - */ - public function submitted($value = NULL) - { - if (is_bool($value)) - { - $this->submitted = $value; - } - - return $this->submitted; - } - /** * Returns an array of all the field names that have filters, rules, or callbacks. * @@ -196,6 +178,42 @@ class Validation_Core extends ArrayObject { return $this; } + /** + * Sets or overwrites the label name for a field. + * + * @param string field name + * @param string label + * @return $this + */ + public function label($field, $label = NULL) + { + if ($label === NULL AND ($field !== TRUE OR $field !== '*') AND ! isset($this->labels[$field])) + { + // Set the field label to the field name + $this->labels[$field] = ucfirst(preg_replace('/[^\pL]+/u', ' ', $field)); + } + elseif ($label !== NULL) + { + // Set the label for this field + $this->labels[$field] = $label; + } + + return $this; + } + + /** + * Sets labels using an array. + * + * @param array list of field => label names + * @return $this + */ + public function labels(array $labels) + { + $this->labels = $labels + $this->labels; + + return $this; + } + /** * Converts a filter, rule, or callback into a fully-qualified callback array. * @@ -338,6 +356,9 @@ class Validation_Core extends ArrayObject { $rules = func_get_args(); $rules = array_slice($rules, 1); + // Set a default field label + $this->label($field); + if ($field === TRUE) { // Use wildcard @@ -412,6 +433,9 @@ class Validation_Core extends ArrayObject { $callbacks = func_get_args(); $callbacks = array_slice($callbacks, 1); + // Set a default field label + $this->label($field); + if ($field === TRUE) { // Use wildcard @@ -471,9 +495,6 @@ class Validation_Core extends ArrayObject { } } - if ($this->submitted === FALSE) - return FALSE; - foreach ($this->rules as $field => $callbacks) { foreach ($callbacks as $callback) @@ -534,6 +555,7 @@ class Validation_Core extends ArrayObject { if (($result == $is_false)) { + $rule = $is_false ? '!'.$rule : $rule; $this->add_error($field, $rule, $args); // Stop validating this field when an error is found @@ -618,46 +640,6 @@ class Validation_Core extends ArrayObject { return $this; } - /** - * Sets or returns the message for an input. - * - * @chainable - * @param string input key - * @param string message to set - * @return string|object - */ - public function message($input = NULL, $message = NULL) - { - if ($message === NULL) - { - if ($input === NULL) - { - $messages = array(); - $keys = array_keys($this->messages); - - foreach ($keys as $input) - { - $messages[] = $this->message($input); - } - - return implode("\n", $messages); - } - - // Return nothing if no message exists - if (empty($this->messages[$input])) - return ''; - - // Return the HTML message string - return $this->messages[$input]; - } - else - { - $this->messages[$input] = $message; - } - - return $this; - } - /** * Return the errors array. * @@ -677,18 +659,49 @@ class Validation_Core extends ArrayObject { } else { - $errors = array(); foreach ($this->errors as $input => $error) { - // Key for this input error - $key = "$file.$input.$error[0]"; + // Locations to check for error messages + $error_locations = array + ( + "validation/{$file}.{$input}.{$error[0]}", + "validation/{$file}.{$input}.default", + "validation/default.{$error[0]}" + ); + + if (($message = Kohana::message($error_locations[0])) !== $error_locations[0]) + { + // Found a message for this field and error + } + elseif (($message = Kohana::message($error_locations[1])) !== $error_locations[1]) + { + // Found a default message for this field + } + elseif (($message = Kohana::message($error_locations[2])) !== $error_locations[2]) + { + // Found a default message for this error + } + else + { + // No message exists, display the path expected + $message = "validation/{$file}.{$input}.{$error[0]}"; + } - if (($errors[$input] = Kohana::message('validation/'.$key, $error[1])) === $key) + // Start the translation values list + $values = array(':field' => __($this->labels[$input])); + + if ( ! empty($error[1])) { - // Get the default error message - $errors[$input] = Kohana::message("$file.$input.default"); + foreach ($error[1] as $key => $value) + { + // Add each parameter as a numbered value, starting from 1 + $values[':param'.($key + 1)] = __($value); + } } + + // Translate the message using the default language + $errors[$input] = __($message, $values); } return $errors; diff --git a/system/libraries/drivers/Cache/File.php b/system/libraries/drivers/Cache/File.php index fc20c22d..d6ec0378 100644 --- a/system/libraries/drivers/Cache/File.php +++ b/system/libraries/drivers/Cache/File.php @@ -183,7 +183,7 @@ class Cache_File_Driver extends Cache_Driver { // Get the id from the filename list($key, $junk) = explode('~', basename($path), 2); - if (($data = $this->get($key)) !== FALSE) + if (($data = $this->get($key, TRUE)) !== FALSE) { // Add the result to the array $result[$key] = $data; @@ -211,7 +211,7 @@ class Cache_File_Driver extends Cache_Driver { // Remove the cache file if ( ! unlink($path)) { - Kohana::log('error', 'Cache: Unable to delete cache file: '.$path); + Kohana_Log::add('error', 'Cache: Unable to delete cache file: '.$path); $success = FALSE; } } diff --git a/system/libraries/drivers/Cache/Memcache.php b/system/libraries/drivers/Cache/Memcache.php index 636191d4..13d61d82 100644 --- a/system/libraries/drivers/Cache/Memcache.php +++ b/system/libraries/drivers/Cache/Memcache.php @@ -17,7 +17,7 @@ class Cache_Memcache_Driver extends Cache_Driver { public function __construct($config) { if ( ! extension_loaded('memcache')) - throw new Kohana_Exception('The memcache PHP extension must be loaded to use this driver.'); + throw new Cache_Exception('The memcache PHP extension must be loaded to use this driver.'); ini_set('memcache.allow_failover', (isset($config['allow_failover']) AND $config['allow_failover']) ? TRUE : FALSE); @@ -79,7 +79,10 @@ class Cache_Memcache_Driver extends Cache_Driver { if ($single) { - return ($items === FALSE OR count($items) > 0) ? current($items) : NULL; + if ($items === FALSE) + return NULL; + + return (count($items) > 0) ? current($items) : NULL; } else { diff --git a/system/libraries/drivers/Cache/Xcache.php b/system/libraries/drivers/Cache/Xcache.php index ad11e6d7..4c08405e 100644 --- a/system/libraries/drivers/Cache/Xcache.php +++ b/system/libraries/drivers/Cache/Xcache.php @@ -16,7 +16,7 @@ class Cache_Xcache_Driver extends Cache_Driver { public function __construct($config) { if ( ! extension_loaded('xcache')) - throw new Kohana_Exception('The xcache PHP extension must be loaded to use this driver.'); + throw new Cache_Exception('The xcache PHP extension must be loaded to use this driver.'); $this->config = $config; } diff --git a/system/messages/core.php b/system/messages/core.php index 4bf6ee8c..64f897e8 100644 --- a/system/messages/core.php +++ b/system/messages/core.php @@ -8,7 +8,6 @@ $messages = array E_PAGE_NOT_FOUND => __('Page Not Found'), // __('The requested page was not found. It may have moved, been deleted, or archived.'), E_DATABASE_ERROR => __('Database Error'), // __('A database error occurred while performing the requested procedure. Please review the database error below for more information.'), E_RECOVERABLE_ERROR => __('Recoverable Error'), // __('An error was detected which prevented the loading of this page. If this problem persists, please contact the website administrator.'), - E_ERROR => __('Fatal Error'), E_COMPILE_ERROR => __('Fatal Error'), E_CORE_ERROR => __('Fatal Error'), @@ -29,4 +28,10 @@ $messages = array 'driver' => 'driver', 'model' => 'model', 'view' => 'view', -); \ No newline at end of file +); + +// E_DEPRECATED is only defined in PHP >= 5.3.0 +if (defined('E_DEPRECATED')) +{ + $messages['errors'][E_DEPRECATED] = __('Deprecated'); +} \ No newline at end of file diff --git a/system/messages/validation/default.php b/system/messages/validation/default.php new file mode 100644 index 00000000..2c59fa06 --- /dev/null +++ b/system/messages/validation/default.php @@ -0,0 +1,17 @@ + 'The :field field is required', + 'length' => 'The :field field must be between :param1 and :param2 characters long', + 'depends_on' => 'The :field field requires the :param1 field', + 'matches' => 'The :field field must be the same as :param1', + 'email' => 'The :field field must be a valid email address', + 'decimal' => 'The :field field must be a decimal with :param1 places', + 'digit' => 'The :field field must be a digit', + 'in_array' => 'The :field field must be one of the available options', + 'alpha_numeric' => 'The :field field must consist only of alphabetical or numeric characters', + 'alpha_dash ' => 'The :field field must consist only of alphabetical, numeric, underscore and dash characters', + 'numeric ' => 'The :field field must be a valid number', + 'url' => 'The :field field must be a valid url', + 'phone' => 'The :field field must be a valid phone number', +); diff --git a/system/vendor/Markdown.php b/system/vendor/Markdown.php deleted file mode 100644 index b649f6c1..00000000 --- a/system/vendor/Markdown.php +++ /dev/null @@ -1,2909 +0,0 @@ - -# -# Original Markdown -# Copyright (c) 2004-2006 John Gruber -# -# - - -define( 'MARKDOWN_VERSION', "1.0.1m" ); # Sat 21 Jun 2008 -define( 'MARKDOWNEXTRA_VERSION', "1.2.3" ); # Wed 31 Dec 2008 - - -# -# Global default settings: -# - -# Change to ">" for HTML output -@define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />"); - -# Define the width of a tab for code blocks. -@define( 'MARKDOWN_TAB_WIDTH', 4 ); - -# Optional title attribute for footnote links and backlinks. -@define( 'MARKDOWN_FN_LINK_TITLE', "" ); -@define( 'MARKDOWN_FN_BACKLINK_TITLE', "" ); - -# Optional class attribute for footnote links and backlinks. -@define( 'MARKDOWN_FN_LINK_CLASS', "" ); -@define( 'MARKDOWN_FN_BACKLINK_CLASS', "" ); - - -# -# WordPress settings: -# - -# Change to false to remove Markdown from posts and/or comments. -@define( 'MARKDOWN_WP_POSTS', true ); -@define( 'MARKDOWN_WP_COMMENTS', true ); - - - -### Standard Function Interface ### - -@define( 'MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser' ); - -function Markdown($text) { -# -# Initialize the parser and return the result of its transform method. -# - # Setup static parser variable. - static $parser; - if (!isset($parser)) { - $parser_class = MARKDOWN_PARSER_CLASS; - $parser = new $parser_class; - } - - # Transform text using parser. - return $parser->transform($text); -} - - -### WordPress Plugin Interface ### - -/* -Plugin Name: Markdown Extra -Plugin URI: http://www.michelf.com/projects/php-markdown/ -Description: Markdown syntax allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by John Gruber. More... -Version: 1.2.2 -Author: Michel Fortin -Author URI: http://www.michelf.com/ -*/ - -if (isset($wp_version)) { - # More details about how it works here: - # - - # Post content and excerpts - # - Remove WordPress paragraph generator. - # - Run Markdown on excerpt, then remove all tags. - # - Add paragraph tag around the excerpt, but remove it for the excerpt rss. - if (MARKDOWN_WP_POSTS) { - remove_filter('the_content', 'wpautop'); - remove_filter('the_content_rss', 'wpautop'); - remove_filter('the_excerpt', 'wpautop'); - add_filter('the_content', 'mdwp_MarkdownPost', 6); - add_filter('the_content_rss', 'mdwp_MarkdownPost', 6); - add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6); - add_filter('get_the_excerpt', 'trim', 7); - add_filter('the_excerpt', 'mdwp_add_p'); - add_filter('the_excerpt_rss', 'mdwp_strip_p'); - - remove_filter('content_save_pre', 'balanceTags', 50); - remove_filter('excerpt_save_pre', 'balanceTags', 50); - add_filter('the_content', 'balanceTags', 50); - add_filter('get_the_excerpt', 'balanceTags', 9); - } - - # Add a footnote id prefix to posts when inside a loop. - function mdwp_MarkdownPost($text) { - static $parser; - if (!$parser) { - $parser_class = MARKDOWN_PARSER_CLASS; - $parser = new $parser_class; - } - if (is_single() || is_page() || is_feed()) { - $parser->fn_id_prefix = ""; - } else { - $parser->fn_id_prefix = get_the_ID() . "."; - } - return $parser->transform($text); - } - - # Comments - # - Remove WordPress paragraph generator. - # - Remove WordPress auto-link generator. - # - Scramble important tags before passing them to the kses filter. - # - Run Markdown on excerpt then remove paragraph tags. - if (MARKDOWN_WP_COMMENTS) { - remove_filter('comment_text', 'wpautop', 30); - remove_filter('comment_text', 'make_clickable'); - add_filter('pre_comment_content', 'Markdown', 6); - add_filter('pre_comment_content', 'mdwp_hide_tags', 8); - add_filter('pre_comment_content', 'mdwp_show_tags', 12); - add_filter('get_comment_text', 'Markdown', 6); - add_filter('get_comment_excerpt', 'Markdown', 6); - add_filter('get_comment_excerpt', 'mdwp_strip_p', 7); - - global $mdwp_hidden_tags, $mdwp_placeholders; - $mdwp_hidden_tags = explode(' ', - '

     
  • '); - $mdwp_placeholders = explode(' ', str_rot13( - 'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '. - 'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli')); - } - - function mdwp_add_p($text) { - if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) { - $text = '

    '.$text.'

    '; - $text = preg_replace('{\n{2,}}', "

    \n\n

    ", $text); - } - return $text; - } - - function mdwp_strip_p($t) { return preg_replace('{}i', '', $t); } - - function mdwp_hide_tags($text) { - global $mdwp_hidden_tags, $mdwp_placeholders; - return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text); - } - function mdwp_show_tags($text) { - global $mdwp_hidden_tags, $mdwp_placeholders; - return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text); - } -} - - -### bBlog Plugin Info ### - -function identify_modifier_markdown() { - return array( - 'name' => 'markdown', - 'type' => 'modifier', - 'nicename' => 'PHP Markdown Extra', - 'description' => 'A text-to-HTML conversion tool for web writers', - 'authors' => 'Michel Fortin and John Gruber', - 'licence' => 'GPL', - 'version' => MARKDOWNEXTRA_VERSION, - 'help' => 'Markdown syntax allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by John Gruber. More...', - ); -} - - -### Smarty Modifier Interface ### - -function smarty_modifier_markdown($text) { - return Markdown($text); -} - - -### Textile Compatibility Mode ### - -# Rename this file to "classTextile.php" and it can replace Textile everywhere. - -if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) { - # Try to include PHP SmartyPants. Should be in the same directory. - @include_once 'smartypants.php'; - # Fake Textile class. It calls Markdown instead. - class Textile { - function TextileThis($text, $lite='', $encode='') { - if ($lite == '' && $encode == '') $text = Markdown($text); - if (function_exists('SmartyPants')) $text = SmartyPants($text); - return $text; - } - # Fake restricted version: restrictions are not supported for now. - function TextileRestricted($text, $lite='', $noimage='') { - return $this->TextileThis($text, $lite); - } - # Workaround to ensure compatibility with TextPattern 4.0.3. - function blockLite($text) { return $text; } - } -} - - - -# -# Markdown Parser Class -# - -class Markdown_Parser { - - # Regex to match balanced [brackets]. - # Needed to insert a maximum bracked depth while converting to PHP. - var $nested_brackets_depth = 6; - var $nested_brackets_re; - - var $nested_url_parenthesis_depth = 4; - var $nested_url_parenthesis_re; - - # Table of hash values for escaped characters: - var $escape_chars = '\`*_{}[]()>#+-.!'; - var $escape_chars_re; - - # Change to ">" for HTML output. - var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX; - var $tab_width = MARKDOWN_TAB_WIDTH; - - # Change to `true` to disallow markup or entities. - var $no_markup = false; - var $no_entities = false; - - # Predefined urls and titles for reference links and images. - var $predef_urls = array(); - var $predef_titles = array(); - - - function Markdown_Parser() { - # - # Constructor function. Initialize appropriate member variables. - # - $this->_initDetab(); - $this->prepareItalicsAndBold(); - - $this->nested_brackets_re = - str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth). - str_repeat('\])*', $this->nested_brackets_depth); - - $this->nested_url_parenthesis_re = - str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth). - str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth); - - $this->escape_chars_re = '['.preg_quote($this->escape_chars).']'; - - # Sort document, block, and span gamut in ascendent priority order. - asort($this->document_gamut); - asort($this->block_gamut); - asort($this->span_gamut); - } - - - # Internal hashes used during transformation. - var $urls = array(); - var $titles = array(); - var $html_hashes = array(); - - # Status flag to avoid invalid nesting. - var $in_anchor = false; - - - function setup() { - # - # Called before the transformation process starts to setup parser - # states. - # - # Clear global hashes. - $this->urls = $this->predef_urls; - $this->titles = $this->predef_titles; - $this->html_hashes = array(); - - $in_anchor = false; - } - - function teardown() { - # - # Called after the transformation process to clear any variable - # which may be taking up memory unnecessarly. - # - $this->urls = array(); - $this->titles = array(); - $this->html_hashes = array(); - } - - - function transform($text) { - # - # Main function. Performs some preprocessing on the input text - # and pass it through the document gamut. - # - $this->setup(); - - # Remove UTF-8 BOM and marker character in input, if present. - $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text); - - # Standardize line endings: - # DOS to Unix and Mac to Unix - $text = preg_replace('{\r\n?}', "\n", $text); - - # Make sure $text ends with a couple of newlines: - $text .= "\n\n"; - - # Convert all tabs to spaces. - $text = $this->detab($text); - - # Turn block-level HTML blocks into hash entries - $text = $this->hashHTMLBlocks($text); - - # Strip any lines consisting only of spaces and tabs. - # This makes subsequent regexen easier to write, because we can - # match consecutive blank lines with /\n+/ instead of something - # contorted like /[ ]*\n+/ . - $text = preg_replace('/^[ ]+$/m', '', $text); - - # Run document gamut methods. - foreach ($this->document_gamut as $method => $priority) { - $text = $this->$method($text); - } - - $this->teardown(); - - return $text . "\n"; - } - - var $document_gamut = array( - # Strip link definitions, store in hashes. - "stripLinkDefinitions" => 20, - - "runBasicBlockGamut" => 30, - ); - - - function stripLinkDefinitions($text) { - # - # Strips link definitions from text, stores the URLs and titles in - # hash references. - # - $less_than_tab = $this->tab_width - 1; - - # Link defs are in the form: ^[id]: url "optional title" - $text = preg_replace_callback('{ - ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1 - [ ]* - \n? # maybe *one* newline - [ ]* - ? # url = $2 - [ ]* - \n? # maybe one newline - [ ]* - (?: - (?<=\s) # lookbehind for whitespace - ["(] - (.*?) # title = $3 - [")] - [ ]* - )? # title is optional - (?:\n+|\Z) - }xm', - array(&$this, '_stripLinkDefinitions_callback'), - $text); - return $text; - } - function _stripLinkDefinitions_callback($matches) { - $link_id = strtolower($matches[1]); - $this->urls[$link_id] = $matches[2]; - $this->titles[$link_id] =& $matches[3]; - return ''; # String that will replace the block - } - - - function hashHTMLBlocks($text) { - if ($this->no_markup) return $text; - - $less_than_tab = $this->tab_width - 1; - - # Hashify HTML blocks: - # We only want to do this for block-level HTML tags, such as headers, - # lists, and tables. That's because we still want to wrap

    s around - # "paragraphs" that are wrapped in non-block-level tags, such as anchors, - # phrase emphasis, and spans. The list of tags we're looking for is - # hard-coded: - # - # * List "a" is made of tags which can be both inline or block-level. - # These will be treated block-level when the start tag is alone on - # its line, otherwise they're not matched here and will be taken as - # inline later. - # * List "b" is made of tags which are always block-level; - # - $block_tags_a_re = 'ins|del'; - $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'. - 'script|noscript|form|fieldset|iframe|math'; - - # Regular expression for the content of a block tag. - $nested_tags_level = 4; - $attr = ' - (?> # optional tag attributes - \s # starts with whitespace - (?> - [^>"/]+ # text outside quotes - | - /+(?!>) # slash not followed by ">" - | - "[^"]*" # text inside double quotes (tolerate ">") - | - \'[^\']*\' # text inside single quotes (tolerate ">") - )* - )? - '; - $content = - str_repeat(' - (?> - [^<]+ # content without tag - | - <\2 # nested opening tag - '.$attr.' # attributes - (?> - /> - | - >', $nested_tags_level). # end of opening tag - '.*?'. # last level nested tag content - str_repeat(' - # closing nested tag - ) - | - <(?!/\2\s*> # other tags with a different name - ) - )*', - $nested_tags_level); - $content2 = str_replace('\2', '\3', $content); - - # First, look for nested blocks, e.g.: - #

    - #
    - # tags for inner block must be indented. - #
    - #
    - # - # The outermost tags must start at the left margin for this to match, and - # the inner nested divs must be indented. - # We need to do this before the next, more liberal match, because the next - # match will start at the first `
    ` and stop at the first `
    `. - $text = preg_replace_callback('{(?> - (?> - (?<=\n\n) # Starting after a blank line - | # or - \A\n? # the beginning of the doc - ) - ( # save in $1 - - # Match from `\n` to `\n`, handling nested tags - # in between. - - [ ]{0,'.$less_than_tab.'} - <('.$block_tags_b_re.')# start tag = $2 - '.$attr.'> # attributes followed by > and \n - '.$content.' # content, support nesting - # the matching end tag - [ ]* # trailing spaces/tabs - (?=\n+|\Z) # followed by a newline or end of document - - | # Special version for tags of group a. - - [ ]{0,'.$less_than_tab.'} - <('.$block_tags_a_re.')# start tag = $3 - '.$attr.'>[ ]*\n # attributes followed by > - '.$content2.' # content, support nesting - # the matching end tag - [ ]* # trailing spaces/tabs - (?=\n+|\Z) # followed by a newline or end of document - - | # Special case just for
    . It was easier to make a special - # case than to make the other regex more complicated. - - [ ]{0,'.$less_than_tab.'} - <(hr) # start tag = $2 - '.$attr.' # attributes - /?> # the matching end tag - [ ]* - (?=\n{2,}|\Z) # followed by a blank line or end of document - - | # Special case for standalone HTML comments: - - [ ]{0,'.$less_than_tab.'} - (?s: - - ) - [ ]* - (?=\n{2,}|\Z) # followed by a blank line or end of document - - | # PHP and ASP-style processor instructions ( - ) - [ ]* - (?=\n{2,}|\Z) # followed by a blank line or end of document - - ) - )}Sxmi', - array(&$this, '_hashHTMLBlocks_callback'), - $text); - - return $text; - } - function _hashHTMLBlocks_callback($matches) { - $text = $matches[1]; - $key = $this->hashBlock($text); - return "\n\n$key\n\n"; - } - - - function hashPart($text, $boundary = 'X') { - # - # Called whenever a tag must be hashed when a function insert an atomic - # element in the text stream. Passing $text to through this function gives - # a unique text-token which will be reverted back when calling unhash. - # - # The $boundary argument specify what character should be used to surround - # the token. By convension, "B" is used for block elements that needs not - # to be wrapped into paragraph tags at the end, ":" is used for elements - # that are word separators and "X" is used in the general case. - # - # Swap back any tag hash found in $text so we do not have to `unhash` - # multiple times at the end. - $text = $this->unhash($text); - - # Then hash the block. - static $i = 0; - $key = "$boundary\x1A" . ++$i . $boundary; - $this->html_hashes[$key] = $text; - return $key; # String that will replace the tag. - } - - - function hashBlock($text) { - # - # Shortcut function for hashPart with block-level boundaries. - # - return $this->hashPart($text, 'B'); - } - - - var $block_gamut = array( - # - # These are all the transformations that form block-level - # tags like paragraphs, headers, and list items. - # - "doHeaders" => 10, - "doHorizontalRules" => 20, - - "doLists" => 40, - "doCodeBlocks" => 50, - "doBlockQuotes" => 60, - ); - - function runBlockGamut($text) { - # - # Run block gamut tranformations. - # - # We need to escape raw HTML in Markdown source before doing anything - # else. This need to be done for each block, and not only at the - # begining in the Markdown function since hashed blocks can be part of - # list items and could have been indented. Indented blocks would have - # been seen as a code block in a previous pass of hashHTMLBlocks. - $text = $this->hashHTMLBlocks($text); - - return $this->runBasicBlockGamut($text); - } - - function runBasicBlockGamut($text) { - # - # Run block gamut tranformations, without hashing HTML blocks. This is - # useful when HTML blocks are known to be already hashed, like in the first - # whole-document pass. - # - foreach ($this->block_gamut as $method => $priority) { - $text = $this->$method($text); - } - - # Finally form paragraph and restore hashed blocks. - $text = $this->formParagraphs($text); - - return $text; - } - - - function doHorizontalRules($text) { - # Do Horizontal Rules: - return preg_replace( - '{ - ^[ ]{0,3} # Leading space - ([-*_]) # $1: First marker - (?> # Repeated marker group - [ ]{0,2} # Zero, one, or two spaces. - \1 # Marker character - ){2,} # Group repeated at least twice - [ ]* # Tailing spaces - $ # End of line. - }mx', - "\n".$this->hashBlock("empty_element_suffix")."\n", - $text); - } - - - var $span_gamut = array( - # - # These are all the transformations that occur *within* block-level - # tags like paragraphs, headers, and list items. - # - # Process character escapes, code spans, and inline HTML - # in one shot. - "parseSpan" => -30, - - # Process anchor and image tags. Images must come first, - # because ![foo][f] looks like an anchor. - "doImages" => 10, - "doAnchors" => 20, - - # Make links out of things like `` - # Must come after doAnchors, because you can use < and > - # delimiters in inline links like [this](). - "doAutoLinks" => 30, - "encodeAmpsAndAngles" => 40, - - "doItalicsAndBold" => 50, - "doHardBreaks" => 60, - ); - - function runSpanGamut($text) { - # - # Run span gamut tranformations. - # - foreach ($this->span_gamut as $method => $priority) { - $text = $this->$method($text); - } - - return $text; - } - - - function doHardBreaks($text) { - # Do hard breaks: - return preg_replace_callback('/ {2,}\n/', - array(&$this, '_doHardBreaks_callback'), $text); - } - function _doHardBreaks_callback($matches) { - return $this->hashPart("empty_element_suffix\n"); - } - - - function doAnchors($text) { - # - # Turn Markdown link shortcuts into XHTML tags. - # - if ($this->in_anchor) return $text; - $this->in_anchor = true; - - # - # First, handle reference-style links: [link text] [id] - # - $text = preg_replace_callback('{ - ( # wrap whole match in $1 - \[ - ('.$this->nested_brackets_re.') # link text = $2 - \] - - [ ]? # one optional space - (?:\n[ ]*)? # one optional newline followed by spaces - - \[ - (.*?) # id = $3 - \] - ) - }xs', - array(&$this, '_doAnchors_reference_callback'), $text); - - # - # Next, inline-style links: [link text](url "optional title") - # - $text = preg_replace_callback('{ - ( # wrap whole match in $1 - \[ - ('.$this->nested_brackets_re.') # link text = $2 - \] - \( # literal paren - [ ]* - (?: - <(\S*)> # href = $3 - | - ('.$this->nested_url_parenthesis_re.') # href = $4 - ) - [ ]* - ( # $5 - ([\'"]) # quote char = $6 - (.*?) # Title = $7 - \6 # matching quote - [ ]* # ignore any spaces/tabs between closing quote and ) - )? # title is optional - \) - ) - }xs', - array(&$this, '_DoAnchors_inline_callback'), $text); - - # - # Last, handle reference-style shortcuts: [link text] - # These must come last in case you've also got [link test][1] - # or [link test](/foo) - # -// $text = preg_replace_callback('{ -// ( # wrap whole match in $1 -// \[ -// ([^\[\]]+) # link text = $2; can\'t contain [ or ] -// \] -// ) -// }xs', -// array(&$this, '_doAnchors_reference_callback'), $text); - - $this->in_anchor = false; - return $text; - } - function _doAnchors_reference_callback($matches) { - $whole_match = $matches[1]; - $link_text = $matches[2]; - $link_id =& $matches[3]; - - if ($link_id == "") { - # for shortcut links like [this][] or [this]. - $link_id = $link_text; - } - - # lower-case and turn embedded newlines into spaces - $link_id = strtolower($link_id); - $link_id = preg_replace('{[ ]?\n}', ' ', $link_id); - - if (isset($this->urls[$link_id])) { - $url = $this->urls[$link_id]; - $url = $this->encodeAttribute($url); - - $result = "titles[$link_id] ) ) { - $title = $this->titles[$link_id]; - $title = $this->encodeAttribute($title); - $result .= " title=\"$title\""; - } - - $link_text = $this->runSpanGamut($link_text); - $result .= ">$link_text"; - $result = $this->hashPart($result); - } - else { - $result = $whole_match; - } - return $result; - } - function _doAnchors_inline_callback($matches) { - $whole_match = $matches[1]; - $link_text = $this->runSpanGamut($matches[2]); - $url = $matches[3] == '' ? $matches[4] : $matches[3]; - $title =& $matches[7]; - - $url = $this->encodeAttribute($url); - - $result = "encodeAttribute($title); - $result .= " title=\"$title\""; - } - - $link_text = $this->runSpanGamut($link_text); - $result .= ">$link_text"; - - return $this->hashPart($result); - } - - - function doImages($text) { - # - # Turn Markdown image shortcuts into tags. - # - # - # First, handle reference-style labeled images: ![alt text][id] - # - $text = preg_replace_callback('{ - ( # wrap whole match in $1 - !\[ - ('.$this->nested_brackets_re.') # alt text = $2 - \] - - [ ]? # one optional space - (?:\n[ ]*)? # one optional newline followed by spaces - - \[ - (.*?) # id = $3 - \] - - ) - }xs', - array(&$this, '_doImages_reference_callback'), $text); - - # - # Next, handle inline images: ![alt text](url "optional title") - # Don't forget: encode * and _ - # - $text = preg_replace_callback('{ - ( # wrap whole match in $1 - !\[ - ('.$this->nested_brackets_re.') # alt text = $2 - \] - \s? # One optional whitespace character - \( # literal paren - [ ]* - (?: - <(\S*)> # src url = $3 - | - ('.$this->nested_url_parenthesis_re.') # src url = $4 - ) - [ ]* - ( # $5 - ([\'"]) # quote char = $6 - (.*?) # title = $7 - \6 # matching quote - [ ]* - )? # title is optional - \) - ) - }xs', - array(&$this, '_doImages_inline_callback'), $text); - - return $text; - } - function _doImages_reference_callback($matches) { - $whole_match = $matches[1]; - $alt_text = $matches[2]; - $link_id = strtolower($matches[3]); - - if ($link_id == "") { - $link_id = strtolower($alt_text); # for shortcut links like ![this][]. - } - - $alt_text = $this->encodeAttribute($alt_text); - if (isset($this->urls[$link_id])) { - $url = $this->encodeAttribute($this->urls[$link_id]); - $result = "\"$alt_text\"";titles[$link_id])) { - $title = $this->titles[$link_id]; - $title = $this->encodeAttribute($title); - $result .= " title=\"$title\""; - } - $result .= $this->empty_element_suffix; - $result = $this->hashPart($result); - } - else { - # If there's no such link ID, leave intact: - $result = $whole_match; - } - - return $result; - } - function _doImages_inline_callback($matches) { - $whole_match = $matches[1]; - $alt_text = $matches[2]; - $url = $matches[3] == '' ? $matches[4] : $matches[3]; - $title =& $matches[7]; - - $alt_text = $this->encodeAttribute($alt_text); - $url = $this->encodeAttribute($url); - $result = "\"$alt_text\"";encodeAttribute($title); - $result .= " title=\"$title\""; # $title already quoted - } - $result .= $this->empty_element_suffix; - - return $this->hashPart($result); - } - - - function doHeaders($text) { - # Setext-style headers: - # Header 1 - # ======== - # - # Header 2 - # -------- - # - $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx', - array(&$this, '_doHeaders_callback_setext'), $text); - - # atx-style headers: - # # Header 1 - # ## Header 2 - # ## Header 2 with closing hashes ## - # ... - # ###### Header 6 - # - $text = preg_replace_callback('{ - ^(\#{1,6}) # $1 = string of #\'s - [ ]* - (.+?) # $2 = Header text - [ ]* - \#* # optional closing #\'s (not counted) - \n+ - }xm', - array(&$this, '_doHeaders_callback_atx'), $text); - - return $text; - } - function _doHeaders_callback_setext($matches) { - # Terrible hack to check we haven't found an empty list item. - if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1])) - return $matches[0]; - - $level = $matches[2]{0} == '=' ? 1 : 2; - $block = "".$this->runSpanGamut($matches[1]).""; - return "\n" . $this->hashBlock($block) . "\n\n"; - } - function _doHeaders_callback_atx($matches) { - $level = strlen($matches[1]); - $block = "".$this->runSpanGamut($matches[2]).""; - return "\n" . $this->hashBlock($block) . "\n\n"; - } - - - function doLists($text) { - # - # Form HTML ordered (numbered) and unordered (bulleted) lists. - # - $less_than_tab = $this->tab_width - 1; - - # Re-usable patterns to match list item bullets and number markers: - $marker_ul_re = '[*+-]'; - $marker_ol_re = '\d+[.]'; - $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; - - $markers_relist = array($marker_ul_re, $marker_ol_re); - - foreach ($markers_relist as $marker_re) { - # Re-usable pattern to match any entirel ul or ol list: - $whole_list_re = ' - ( # $1 = whole list - ( # $2 - [ ]{0,'.$less_than_tab.'} - ('.$marker_re.') # $3 = first list item marker - [ ]+ - ) - (?s:.+?) - ( # $4 - \z - | - \n{2,} - (?=\S) - (?! # Negative lookahead for another list item marker - [ ]* - '.$marker_re.'[ ]+ - ) - ) - ) - '; // mx - - # We use a different prefix before nested lists than top-level lists. - # See extended comment in _ProcessListItems(). - - if ($this->list_level) { - $text = preg_replace_callback('{ - ^ - '.$whole_list_re.' - }mx', - array(&$this, '_doLists_callback'), $text); - } - else { - $text = preg_replace_callback('{ - (?:(?<=\n)\n|\A\n?) # Must eat the newline - '.$whole_list_re.' - }mx', - array(&$this, '_doLists_callback'), $text); - } - } - - return $text; - } - function _doLists_callback($matches) { - # Re-usable patterns to match list item bullets and number markers: - $marker_ul_re = '[*+-]'; - $marker_ol_re = '\d+[.]'; - $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; - - $list = $matches[1]; - $list_type = preg_match("/$marker_ul_re/", $matches[3]) ? "ul" : "ol"; - - $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re ); - - $list .= "\n"; - $result = $this->processListItems($list, $marker_any_re); - - $result = $this->hashBlock("<$list_type>\n" . $result . ""); - return "\n". $result ."\n\n"; - } - - var $list_level = 0; - - function processListItems($list_str, $marker_any_re) { - # - # Process the contents of a single ordered or unordered list, splitting it - # into individual list items. - # - # The $this->list_level global keeps track of when we're inside a list. - # Each time we enter a list, we increment it; when we leave a list, - # we decrement. If it's zero, we're not in a list anymore. - # - # We do this because when we're not inside a list, we want to treat - # something like this: - # - # I recommend upgrading to version - # 8. Oops, now this line is treated - # as a sub-list. - # - # As a single paragraph, despite the fact that the second line starts - # with a digit-period-space sequence. - # - # Whereas when we're inside a list (or sub-list), that line will be - # treated as the start of a sub-list. What a kludge, huh? This is - # an aspect of Markdown's syntax that's hard to parse perfectly - # without resorting to mind-reading. Perhaps the solution is to - # change the syntax rules such that sub-lists must start with a - # starting cardinal number; e.g. "1." or "a.". - - $this->list_level++; - - # trim trailing blank lines: - $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); - - $list_str = preg_replace_callback('{ - (\n)? # leading line = $1 - (^[ ]*) # leading whitespace = $2 - ('.$marker_any_re.' # list marker and space = $3 - (?:[ ]+|(?=\n)) # space only required if item is not empty - ) - ((?s:.*?)) # list item text = $4 - (?:(\n+(?=\n))|\n) # tailing blank line = $5 - (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n)))) - }xm', - array(&$this, '_processListItems_callback'), $list_str); - - $this->list_level--; - return $list_str; - } - function _processListItems_callback($matches) { - $item = $matches[4]; - $leading_line =& $matches[1]; - $leading_space =& $matches[2]; - $marker_space = $matches[3]; - $tailing_blank_line =& $matches[5]; - - if ($leading_line || $tailing_blank_line || - preg_match('/\n{2,}/', $item)) - { - # Replace marker with the appropriate whitespace indentation - $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item; - $item = $this->runBlockGamut($this->outdent($item)."\n"); - } - else { - # Recursion for sub-lists: - $item = $this->doLists($this->outdent($item)); - $item = preg_replace('/\n+$/', '', $item); - $item = $this->runSpanGamut($item); - } - - return "
  • " . $item . "
  • \n"; - } - - - function doCodeBlocks($text) { - # - # Process Markdown `
    ` blocks.
    -	#
    -		$text = preg_replace_callback('{
    -				(?:\n\n|\A\n?)
    -				(	            # $1 = the code block -- one or more lines, starting with a space/tab
    -				  (?>
    -					[ ]{'.$this->tab_width.'}  # Lines must start with a tab or a tab-width of spaces
    -					.*\n+
    -				  )+
    -				)
    -				((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z)	# Lookahead for non-space at line-start, or end of doc
    -			}xm',
    -			array(&$this, '_doCodeBlocks_callback'), $text);
    -
    -		return $text;
    -	}
    -	function _doCodeBlocks_callback($matches) {
    -		$codeblock = $matches[1];
    -
    -		$codeblock = $this->outdent($codeblock);
    -		$codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
    -
    -		# trim leading newlines and trailing newlines
    -		$codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
    -
    -		$codeblock = "
    $codeblock\n
    "; - return "\n\n".$this->hashBlock($codeblock)."\n\n"; - } - - - function makeCodeSpan($code) { - # - # Create a code span markup for $code. Called from handleSpanToken. - # - $code = htmlspecialchars(trim($code), ENT_NOQUOTES); - return $this->hashPart("$code"); - } - - - var $em_relist = array( - '' => '(?:(? '(?<=\S)(? '(?<=\S)(? '(?:(? '(?<=\S)(? '(?<=\S)(? '(?:(? '(?<=\S)(? '(?<=\S)(?em_relist as $em => $em_re) { - foreach ($this->strong_relist as $strong => $strong_re) { - # Construct list of allowed token expressions. - $token_relist = array(); - if (isset($this->em_strong_relist["$em$strong"])) { - $token_relist[] = $this->em_strong_relist["$em$strong"]; - } - $token_relist[] = $em_re; - $token_relist[] = $strong_re; - - # Construct master expression from list. - $token_re = '{('. implode('|', $token_relist) .')}'; - $this->em_strong_prepared_relist["$em$strong"] = $token_re; - } - } - } - - function doItalicsAndBold($text) { - $token_stack = array(''); - $text_stack = array(''); - $em = ''; - $strong = ''; - $tree_char_em = false; - - while (1) { - # - # Get prepared regular expression for seraching emphasis tokens - # in current context. - # - $token_re = $this->em_strong_prepared_relist["$em$strong"]; - - # - # Each loop iteration seach for the next emphasis token. - # Each token is then passed to handleSpanToken. - # - $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); - $text_stack[0] .= $parts[0]; - $token =& $parts[1]; - $text =& $parts[2]; - - if (empty($token)) { - # Reached end of text span: empty stack without emitting. - # any more emphasis. - while ($token_stack[0]) { - $text_stack[1] .= array_shift($token_stack); - $text_stack[0] .= array_shift($text_stack); - } - break; - } - - $token_len = strlen($token); - if ($tree_char_em) { - # Reached closing marker while inside a three-char emphasis. - if ($token_len == 3) { - # Three-char closing marker, close em and strong. - array_shift($token_stack); - $span = array_shift($text_stack); - $span = $this->runSpanGamut($span); - $span = "$span"; - $text_stack[0] .= $this->hashPart($span); - $em = ''; - $strong = ''; - } else { - # Other closing marker: close one em or strong and - # change current token state to match the other - $token_stack[0] = str_repeat($token{0}, 3-$token_len); - $tag = $token_len == 2 ? "strong" : "em"; - $span = $text_stack[0]; - $span = $this->runSpanGamut($span); - $span = "<$tag>$span"; - $text_stack[0] = $this->hashPart($span); - $$tag = ''; # $$tag stands for $em or $strong - } - $tree_char_em = false; - } else if ($token_len == 3) { - if ($em) { - # Reached closing marker for both em and strong. - # Closing strong marker: - for ($i = 0; $i < 2; ++$i) { - $shifted_token = array_shift($token_stack); - $tag = strlen($shifted_token) == 2 ? "strong" : "em"; - $span = array_shift($text_stack); - $span = $this->runSpanGamut($span); - $span = "<$tag>$span"; - $text_stack[0] .= $this->hashPart($span); - $$tag = ''; # $$tag stands for $em or $strong - } - } else { - # Reached opening three-char emphasis marker. Push on token - # stack; will be handled by the special condition above. - $em = $token{0}; - $strong = "$em$em"; - array_unshift($token_stack, $token); - array_unshift($text_stack, ''); - $tree_char_em = true; - } - } else if ($token_len == 2) { - if ($strong) { - # Unwind any dangling emphasis marker: - if (strlen($token_stack[0]) == 1) { - $text_stack[1] .= array_shift($token_stack); - $text_stack[0] .= array_shift($text_stack); - } - # Closing strong marker: - array_shift($token_stack); - $span = array_shift($text_stack); - $span = $this->runSpanGamut($span); - $span = "$span"; - $text_stack[0] .= $this->hashPart($span); - $strong = ''; - } else { - array_unshift($token_stack, $token); - array_unshift($text_stack, ''); - $strong = $token; - } - } else { - # Here $token_len == 1 - if ($em) { - if (strlen($token_stack[0]) == 1) { - # Closing emphasis marker: - array_shift($token_stack); - $span = array_shift($text_stack); - $span = $this->runSpanGamut($span); - $span = "$span"; - $text_stack[0] .= $this->hashPart($span); - $em = ''; - } else { - $text_stack[0] .= $token; - } - } else { - array_unshift($token_stack, $token); - array_unshift($text_stack, ''); - $em = $token; - } - } - } - return $text_stack[0]; - } - - - function doBlockQuotes($text) { - $text = preg_replace_callback('/ - ( # Wrap whole match in $1 - (?> - ^[ ]*>[ ]? # ">" at the start of a line - .+\n # rest of the first line - (.+\n)* # subsequent consecutive lines - \n* # blanks - )+ - ) - /xm', - array(&$this, '_doBlockQuotes_callback'), $text); - - return $text; - } - function _doBlockQuotes_callback($matches) { - $bq = $matches[1]; - # trim one level of quoting - trim whitespace-only lines - $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq); - $bq = $this->runBlockGamut($bq); # recurse - - $bq = preg_replace('/^/m', " ", $bq); - # These leading spaces cause problem with
     content, 
    -		# so we need to fix that:
    -		$bq = preg_replace_callback('{(\s*
    .+?
    )}sx', - array(&$this, '_DoBlockQuotes_callback2'), $bq); - - return "\n". $this->hashBlock("
    \n$bq\n
    ")."\n\n"; - } - function _doBlockQuotes_callback2($matches) { - $pre = $matches[1]; - $pre = preg_replace('/^ /m', '', $pre); - return $pre; - } - - - function formParagraphs($text) { - # - # Params: - # $text - string to process with html

    tags - # - # Strip leading and trailing lines: - $text = preg_replace('/\A\n+|\n+\z/', '', $text); - - $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY); - - # - # Wrap

    tags and unhashify HTML blocks - # - foreach ($grafs as $key => $value) { - if (!preg_match('/^B\x1A[0-9]+B$/', $value)) { - # Is a paragraph. - $value = $this->runSpanGamut($value); - $value = preg_replace('/^([ ]*)/', "

    ", $value); - $value .= "

    "; - $grafs[$key] = $this->unhash($value); - } - else { - # Is a block. - # Modify elements of @grafs in-place... - $graf = $value; - $block = $this->html_hashes[$graf]; - $graf = $block; -// if (preg_match('{ -// \A -// ( # $1 =
    tag -//
    ]* -// \b -// markdown\s*=\s* ([\'"]) # $2 = attr quote char -// 1 -// \2 -// [^>]* -// > -// ) -// ( # $3 = contents -// .* -// ) -// (
    ) # $4 = closing tag -// \z -// }xs', $block, $matches)) -// { -// list(, $div_open, , $div_content, $div_close) = $matches; -// -// # We can't call Markdown(), because that resets the hash; -// # that initialization code should be pulled into its own sub, though. -// $div_content = $this->hashHTMLBlocks($div_content); -// -// # Run document gamut methods on the content. -// foreach ($this->document_gamut as $method => $priority) { -// $div_content = $this->$method($div_content); -// } -// -// $div_open = preg_replace( -// '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open); -// -// $graf = $div_open . "\n" . $div_content . "\n" . $div_close; -// } - $grafs[$key] = $graf; - } - } - - return implode("\n\n", $grafs); - } - - - function encodeAttribute($text) { - # - # Encode text for a double-quoted HTML attribute. This function - # is *not* suitable for attributes enclosed in single quotes. - # - $text = $this->encodeAmpsAndAngles($text); - $text = str_replace('"', '"', $text); - return $text; - } - - - function encodeAmpsAndAngles($text) { - # - # Smart processing for ampersands and angle brackets that need to - # be encoded. Valid character entities are left alone unless the - # no-entities mode is set. - # - if ($this->no_entities) { - $text = str_replace('&', '&', $text); - } else { - # Ampersand-encoding based entirely on Nat Irons's Amputator - # MT plugin: - $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/', - '&', $text);; - } - # Encode remaining <'s - $text = str_replace('<', '<', $text); - - return $text; - } - - - function doAutoLinks($text) { - $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i', - array(&$this, '_doAutoLinks_url_callback'), $text); - - # Email addresses: - $text = preg_replace_callback('{ - < - (?:mailto:)? - ( - [-.\w\x80-\xFF]+ - \@ - [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+ - ) - > - }xi', - array(&$this, '_doAutoLinks_email_callback'), $text); - - return $text; - } - function _doAutoLinks_url_callback($matches) { - $url = $this->encodeAttribute($matches[1]); - $link = "$url"; - return $this->hashPart($link); - } - function _doAutoLinks_email_callback($matches) { - $address = $matches[1]; - $link = $this->encodeEmailAddress($address); - return $this->hashPart($link); - } - - - function encodeEmailAddress($addr) { - # - # Input: an email address, e.g. "foo@example.com" - # - # Output: the email address as a mailto link, with each character - # of the address encoded as either a decimal or hex entity, in - # the hopes of foiling most address harvesting spam bots. E.g.: - # - #

    foo@exampl - # e.com

    - # - # Based by a filter by Matthew Wickline, posted to BBEdit-Talk. - # With some optimizations by Milian Wolff. - # - $addr = "mailto:" . $addr; - $chars = preg_split('/(? $char) { - $ord = ord($char); - # Ignore non-ascii chars. - if ($ord < 128) { - $r = ($seed * (1 + $key)) % 100; # Pseudo-random function. - # roughly 10% raw, 45% hex, 45% dec - # '@' *must* be encoded. I insist. - if ($r > 90 && $char != '@') /* do nothing */; - else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';'; - else $chars[$key] = '&#'.$ord.';'; - } - } - - $addr = implode('', $chars); - $text = implode('', array_slice($chars, 7)); # text without `mailto:` - $addr = "$text"; - - return $addr; - } - - - function parseSpan($str) { - # - # Take the string $str and parse it into tokens, hashing embeded HTML, - # escaped characters and handling code spans. - # - $output = ''; - - $span_re = '{ - ( - \\\\'.$this->escape_chars_re.' - | - (?no_markup ? '' : ' - | - # comment - | - <\?.*?\?> | <%.*?%> # processing instruction - | - <[/!$]?[-a-zA-Z0-9:]+ # regular tags - (?> - \s - (?>[^"\'>]+|"[^"]*"|\'[^\']*\')* - )? - > - ').' - ) - }xs'; - - while (1) { - # - # Each loop iteration seach for either the next tag, the next - # openning code span marker, or the next escaped character. - # Each token is then passed to handleSpanToken. - # - $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE); - - # Create token from text preceding tag. - if ($parts[0] != "") { - $output .= $parts[0]; - } - - # Check if we reach the end. - if (isset($parts[1])) { - $output .= $this->handleSpanToken($parts[1], $parts[2]); - $str = $parts[2]; - } - else { - break; - } - } - - return $output; - } - - - function handleSpanToken($token, &$str) { - # - # Handle $token provided by parseSpan by determining its nature and - # returning the corresponding value that should replace it. - # - switch ($token{0}) { - case "\\": - return $this->hashPart("&#". ord($token{1}). ";"); - case "`": - # Search for end marker in remaining text. - if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm', - $str, $matches)) - { - $str = $matches[2]; - $codespan = $this->makeCodeSpan($matches[1]); - return $this->hashPart($codespan); - } - return $token; // return as text since no ending marker found. - default: - return $this->hashPart($token); - } - } - - - function outdent($text) { - # - # Remove one level of line-leading tabs or spaces - # - return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text); - } - - - # String length function for detab. `_initDetab` will create a function to - # hanlde UTF-8 if the default function does not exist. - var $utf8_strlen = 'mb_strlen'; - - function detab($text) { - # - # Replace tabs with the appropriate amount of space. - # - # For each line we separate the line in blocks delemited by - # tab characters. Then we reconstruct every line by adding the - # appropriate number of space between each blocks. - - $text = preg_replace_callback('/^.*\t.*$/m', - array(&$this, '_detab_callback'), $text); - - return $text; - } - function _detab_callback($matches) { - $line = $matches[0]; - $strlen = $this->utf8_strlen; # strlen function for UTF-8. - - # Split in blocks. - $blocks = explode("\t", $line); - # Add each blocks to the line. - $line = $blocks[0]; - unset($blocks[0]); # Do not add first block twice. - foreach ($blocks as $block) { - # Calculate amount of space, insert spaces, insert block. - $amount = $this->tab_width - - $strlen($line, 'UTF-8') % $this->tab_width; - $line .= str_repeat(" ", $amount) . $block; - } - return $line; - } - function _initDetab() { - # - # Check for the availability of the function in the `utf8_strlen` property - # (initially `mb_strlen`). If the function is not available, create a - # function that will loosely count the number of UTF-8 characters with a - # regular expression. - # - if (function_exists($this->utf8_strlen)) return; - $this->utf8_strlen = create_function('$text', 'return preg_match_all( - "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/", - $text, $m);'); - } - - - function unhash($text) { - # - # Swap back in all the tags hashed by _HashHTMLBlocks. - # - return preg_replace_callback('/(.)\x1A[0-9]+\1/', - array(&$this, '_unhash_callback'), $text); - } - function _unhash_callback($matches) { - return $this->html_hashes[$matches[0]]; - } - -} - - -# -# Markdown Extra Parser Class -# - -class MarkdownExtra_Parser extends Markdown_Parser { - - # Prefix for footnote ids. - var $fn_id_prefix = ""; - - # Optional title attribute for footnote links and backlinks. - var $fn_link_title = MARKDOWN_FN_LINK_TITLE; - var $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE; - - # Optional class attribute for footnote links and backlinks. - var $fn_link_class = MARKDOWN_FN_LINK_CLASS; - var $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS; - - # Predefined abbreviations. - var $predef_abbr = array(); - - - function MarkdownExtra_Parser() { - # - # Constructor function. Initialize the parser object. - # - # Add extra escapable characters before parent constructor - # initialize the table. - $this->escape_chars .= ':|'; - - # Insert extra document, block, and span transformations. - # Parent constructor will do the sorting. - $this->document_gamut += array( - "doFencedCodeBlocks" => 5, - "stripFootnotes" => 15, - "stripAbbreviations" => 25, - "appendFootnotes" => 50, - ); - $this->block_gamut += array( - "doFencedCodeBlocks" => 5, - "doTables" => 15, - "doDefLists" => 45, - ); - $this->span_gamut += array( - "doFootnotes" => 5, - "doAbbreviations" => 70, - ); - - parent::Markdown_Parser(); - } - - - # Extra variables used during extra transformations. - var $footnotes = array(); - var $footnotes_ordered = array(); - var $abbr_desciptions = array(); - var $abbr_word_re = ''; - - # Give the current footnote number. - var $footnote_counter = 1; - - - function setup() { - # - # Setting up Extra-specific variables. - # - parent::setup(); - - $this->footnotes = array(); - $this->footnotes_ordered = array(); - $this->abbr_desciptions = array(); - $this->abbr_word_re = ''; - $this->footnote_counter = 1; - - foreach ($this->predef_abbr as $abbr_word => $abbr_desc) { - if ($this->abbr_word_re) - $this->abbr_word_re .= '|'; - $this->abbr_word_re .= preg_quote($abbr_word); - $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); - } - } - - function teardown() { - # - # Clearing Extra-specific variables. - # - $this->footnotes = array(); - $this->footnotes_ordered = array(); - $this->abbr_desciptions = array(); - $this->abbr_word_re = ''; - - parent::teardown(); - } - - - ### HTML Block Parser ### - - # Tags that are always treated as block tags: - var $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend'; - - # Tags treated as block tags only if the opening tag is alone on it's line: - var $context_block_tags_re = 'script|noscript|math|ins|del'; - - # Tags where markdown="1" default to span mode: - var $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address'; - - # Tags which must not have their contents modified, no matter where - # they appear: - var $clean_tags_re = 'script|math'; - - # Tags that do not need to be closed. - var $auto_close_tags_re = 'hr|img'; - - - function hashHTMLBlocks($text) { - # - # Hashify HTML Blocks and "clean tags". - # - # We only want to do this for block-level HTML tags, such as headers, - # lists, and tables. That's because we still want to wrap

    s around - # "paragraphs" that are wrapped in non-block-level tags, such as anchors, - # phrase emphasis, and spans. The list of tags we're looking for is - # hard-coded. - # - # This works by calling _HashHTMLBlocks_InMarkdown, which then calls - # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1" - # attribute is found whitin a tag, _HashHTMLBlocks_InHTML calls back - # _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag. - # These two functions are calling each other. It's recursive! - # - # - # Call the HTML-in-Markdown hasher. - # - list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text); - - return $text; - } - function _hashHTMLBlocks_inMarkdown($text, $indent = 0, - $enclosing_tag_re = '', $span = false) - { - # - # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags. - # - # * $indent is the number of space to be ignored when checking for code - # blocks. This is important because if we don't take the indent into - # account, something like this (which looks right) won't work as expected: - # - #

    - #
    - # Hello World. <-- Is this a Markdown code block or text? - #
    <-- Is this a Markdown code block or a real tag? - #
    - # - # If you don't like this, just don't indent the tag on which - # you apply the markdown="1" attribute. - # - # * If $enclosing_tag_re is not empty, stops at the first unmatched closing - # tag with that name. Nested tags supported. - # - # * If $span is true, text inside must treated as span. So any double - # newline will be replaced by a single newline so that it does not create - # paragraphs. - # - # Returns an array of that form: ( processed text , remaining text ) - # - if ($text === '') return array('', ''); - - # Regex to check for the presense of newlines around a block tag. - $newline_before_re = '/(?:^\n?|\n\n)*$/'; - $newline_after_re = - '{ - ^ # Start of text following the tag. - (?>[ ]*)? # Optional comment. - [ ]*\n # Must be followed by newline. - }xs'; - - # Regex to match any tag. - $block_tag_re = - '{ - ( # $2: Capture hole tag. - # Tag name. - '.$this->block_tags_re.' | - '.$this->context_block_tags_re.' | - '.$this->clean_tags_re.' | - (?!\s)'.$enclosing_tag_re.' - ) - (?: - (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name. - (?> - ".*?" | # Double quotes (can contain `>`) - \'.*?\' | # Single quotes (can contain `>`) - .+? # Anything but quotes and `>`. - )*? - )? - > # End of tag. - | - # HTML Comment - | - <\?.*?\?> | <%.*?%> # Processing instruction - | - # CData Block - | - # Code span marker - `+ - '. ( !$span ? ' # If not in span. - | - # Indented code block - (?> ^[ ]*\n? | \n[ ]*\n ) - [ ]{'.($indent+4).'}[^\n]* \n - (?> - (?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n - )* - | - # Fenced code block marker - (?> ^ | \n ) - [ ]{'.($indent).'}~~~+[ ]*\n - ' : '' ). ' # End (if not is span). - ) - }xs'; - - - $depth = 0; # Current depth inside the tag tree. - $parsed = ""; # Parsed text that will be returned. - - # - # Loop through every tag until we find the closing tag of the parent - # or loop until reaching the end of text if no parent tag specified. - # - do { - # - # Split the text using the first $tag_match pattern found. - # Text before pattern will be first in the array, text after - # pattern will be at the end, and between will be any catches made - # by the pattern. - # - $parts = preg_split($block_tag_re, $text, 2, - PREG_SPLIT_DELIM_CAPTURE); - - # If in Markdown span mode, add a empty-string span-level hash - # after each newline to prevent triggering any block element. - if ($span) { - $void = $this->hashPart("", ':'); - $newline = "$void\n"; - $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void; - } - - $parsed .= $parts[0]; # Text before current tag. - - # If end of $text has been reached. Stop loop. - if (count($parts) < 3) { - $text = ""; - break; - } - - $tag = $parts[1]; # Tag to handle. - $text = $parts[2]; # Remaining text after current tag. - $tag_re = preg_quote($tag); # For use in a regular expression. - - # - # Check for: Code span marker - # - if ($tag{0} == "`") { - # Find corresponding end marker. - $tag_re = preg_quote($tag); - if (preg_match('{^(?>.+?|\n(?!\n))*?(?.*\n)+?'.$tag_re.' *\n}', $text, - $matches)) - { - # End marker found: pass text unchanged until marker. - $parsed .= $tag . $matches[0]; - $text = substr($text, strlen($matches[0])); - } - else { - # No end marker: just skip it. - $parsed .= $tag; - } - } - } - # - # Check for: Opening Block level tag or - # Opening Context Block tag (like ins and del) - # used as a block tag (tag is alone on it's line). - # - else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) || - ( preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) && - preg_match($newline_before_re, $parsed) && - preg_match($newline_after_re, $text) ) - ) - { - # Need to parse tag and following text using the HTML parser. - list($block_text, $text) = - $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true); - - # Make sure it stays outside of any paragraph by adding newlines. - $parsed .= "\n\n$block_text\n\n"; - } - # - # Check for: Clean tag (like script, math) - # HTML Comments, processing instructions. - # - else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) || - $tag{1} == '!' || $tag{1} == '?') - { - # Need to parse tag and following text using the HTML parser. - # (don't check for markdown attribute) - list($block_text, $text) = - $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false); - - $parsed .= $block_text; - } - # - # Check for: Tag with same name as enclosing tag. - # - else if ($enclosing_tag_re !== '' && - # Same name as enclosing tag. - preg_match('{^= 0); - - return array($parsed, $text); - } - function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) { - # - # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags. - # - # * Calls $hash_method to convert any blocks. - # * Stops when the first opening tag closes. - # * $md_attr indicate if the use of the `markdown="1"` attribute is allowed. - # (it is not inside clean tags) - # - # Returns an array of that form: ( processed text , remaining text ) - # - if ($text === '') return array('', ''); - - # Regex to match `markdown` attribute inside of a tag. - $markdown_attr_re = ' - { - \s* # Eat whitespace before the `markdown` attribute - markdown - \s*=\s* - (?> - (["\']) # $1: quote delimiter - (.*?) # $2: attribute value - \1 # matching delimiter - | - ([^\s>]*) # $3: unquoted attribute value - ) - () # $4: make $3 always defined (avoid warnings) - }xs'; - - # Regex to match any tag. - $tag_re = '{ - ( # $2: Capture hole tag. - - ".*?" | # Double quotes (can contain `>`) - \'.*?\' | # Single quotes (can contain `>`) - .+? # Anything but quotes and `>`. - )*? - )? - > # End of tag. - | - # HTML Comment - | - <\?.*?\?> | <%.*?%> # Processing instruction - | - # CData Block - ) - }xs'; - - $original_text = $text; # Save original text in case of faliure. - - $depth = 0; # Current depth inside the tag tree. - $block_text = ""; # Temporary text holder for current text. - $parsed = ""; # Parsed text that will be returned. - - # - # Get the name of the starting tag. - # (This pattern makes $base_tag_name_re safe without quoting.) - # - if (preg_match('/^<([\w:$]*)\b/', $text, $matches)) - $base_tag_name_re = $matches[1]; - - # - # Loop through every tag until we find the corresponding closing tag. - # - do { - # - # Split the text using the first $tag_match pattern found. - # Text before pattern will be first in the array, text after - # pattern will be at the end, and between will be any catches made - # by the pattern. - # - $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); - - if (count($parts) < 3) { - # - # End of $text reached with unbalenced tag(s). - # In that case, we return original text unchanged and pass the - # first character as filtered to prevent an infinite loop in the - # parent function. - # - return array($original_text{0}, substr($original_text, 1)); - } - - $block_text .= $parts[0]; # Text before current tag. - $tag = $parts[1]; # Tag to handle. - $text = $parts[2]; # Remaining text after current tag. - - # - # Check for: Auto-close tag (like
    ) - # Comments and Processing Instructions. - # - if (preg_match('{^auto_close_tags_re.')\b}', $tag) || - $tag{1} == '!' || $tag{1} == '?') - { - # Just add the tag to the block as if it was text. - $block_text .= $tag; - } - else { - # - # Increase/decrease nested tag count. Only do so if - # the tag's name match base tag's. - # - if (preg_match('{^mode = $attr_m[2] . $attr_m[3]; - $span_mode = $this->mode == 'span' || $this->mode != 'block' && - preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag); - - # Calculate indent before tag. - if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) { - $strlen = $this->utf8_strlen; - $indent = $strlen($matches[1], 'UTF-8'); - } else { - $indent = 0; - } - - # End preceding block with this tag. - $block_text .= $tag; - $parsed .= $this->$hash_method($block_text); - - # Get enclosing tag name for the ParseMarkdown function. - # (This pattern makes $tag_name_re safe without quoting.) - preg_match('/^<([\w:$]*)\b/', $tag, $matches); - $tag_name_re = $matches[1]; - - # Parse the content using the HTML-in-Markdown parser. - list ($block_text, $text) - = $this->_hashHTMLBlocks_inMarkdown($text, $indent, - $tag_name_re, $span_mode); - - # Outdent markdown text. - if ($indent > 0) { - $block_text = preg_replace("/^[ ]{1,$indent}/m", "", - $block_text); - } - - # Append tag content to parsed text. - if (!$span_mode) $parsed .= "\n\n$block_text\n\n"; - else $parsed .= "$block_text"; - - # Start over a new block. - $block_text = ""; - } - else $block_text .= $tag; - } - - } while ($depth > 0); - - # - # Hash last block text that wasn't processed inside the loop. - # - $parsed .= $this->$hash_method($block_text); - - return array($parsed, $text); - } - - - function hashClean($text) { - # - # Called whenever a tag must be hashed when a function insert a "clean" tag - # in $text, it pass through this function and is automaticaly escaped, - # blocking invalid nested overlap. - # - return $this->hashPart($text, 'C'); - } - - - function doHeaders($text) { - # - # Redefined to add id attribute support. - # - # Setext-style headers: - # Header 1 {#header1} - # ======== - # - # Header 2 {#header2} - # -------- - # - $text = preg_replace_callback( - '{ - (^.+?) # $1: Header text - (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # $2: Id attribute - [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer - }mx', - array(&$this, '_doHeaders_callback_setext'), $text); - - # atx-style headers: - # # Header 1 {#header1} - # ## Header 2 {#header2} - # ## Header 2 with closing hashes ## {#header3} - # ... - # ###### Header 6 {#header2} - # - $text = preg_replace_callback('{ - ^(\#{1,6}) # $1 = string of #\'s - [ ]* - (.+?) # $2 = Header text - [ ]* - \#* # optional closing #\'s (not counted) - (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # id attribute - [ ]* - \n+ - }xm', - array(&$this, '_doHeaders_callback_atx'), $text); - - return $text; - } - function _doHeaders_attr($attr) { - if (empty($attr)) return ""; - return " id=\"$attr\""; - } - function _doHeaders_callback_setext($matches) { - if ($matches[3] == '-' && preg_match('{^- }', $matches[1])) - return $matches[0]; - $level = $matches[3]{0} == '=' ? 1 : 2; - $attr = $this->_doHeaders_attr($id =& $matches[2]); - $block = "".$this->runSpanGamut($matches[1]).""; - return "\n" . $this->hashBlock($block) . "\n\n"; - } - function _doHeaders_callback_atx($matches) { - $level = strlen($matches[1]); - $attr = $this->_doHeaders_attr($id =& $matches[3]); - $block = "".$this->runSpanGamut($matches[2]).""; - return "\n" . $this->hashBlock($block) . "\n\n"; - } - - - function doTables($text) { - # - # Form HTML tables. - # - $less_than_tab = $this->tab_width - 1; - # - # Find tables with leading pipe. - # - # | Header 1 | Header 2 - # | -------- | -------- - # | Cell 1 | Cell 2 - # | Cell 3 | Cell 4 - # - $text = preg_replace_callback(' - { - ^ # Start of a line - [ ]{0,'.$less_than_tab.'} # Allowed whitespace. - [|] # Optional leading pipe (present) - (.+) \n # $1: Header row (at least one pipe) - - [ ]{0,'.$less_than_tab.'} # Allowed whitespace. - [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline - - ( # $3: Cells - (?> - [ ]* # Allowed whitespace. - [|] .* \n # Row content. - )* - ) - (?=\n|\Z) # Stop at final double newline. - }xm', - array(&$this, '_doTable_leadingPipe_callback'), $text); - - # - # Find tables without leading pipe. - # - # Header 1 | Header 2 - # -------- | -------- - # Cell 1 | Cell 2 - # Cell 3 | Cell 4 - # - $text = preg_replace_callback(' - { - ^ # Start of a line - [ ]{0,'.$less_than_tab.'} # Allowed whitespace. - (\S.*[|].*) \n # $1: Header row (at least one pipe) - - [ ]{0,'.$less_than_tab.'} # Allowed whitespace. - ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline - - ( # $3: Cells - (?> - .* [|] .* \n # Row content - )* - ) - (?=\n|\Z) # Stop at final double newline. - }xm', - array(&$this, '_DoTable_callback'), $text); - - return $text; - } - function _doTable_leadingPipe_callback($matches) { - $head = $matches[1]; - $underline = $matches[2]; - $content = $matches[3]; - - # Remove leading pipe for each row. - $content = preg_replace('/^ *[|]/m', '', $content); - - return $this->_doTable_callback(array($matches[0], $head, $underline, $content)); - } - function _doTable_callback($matches) { - $head = $matches[1]; - $underline = $matches[2]; - $content = $matches[3]; - - # Remove any tailing pipes for each line. - $head = preg_replace('/[|] *$/m', '', $head); - $underline = preg_replace('/[|] *$/m', '', $underline); - $content = preg_replace('/[|] *$/m', '', $content); - - # Reading alignement from header underline. - $separators = preg_split('/ *[|] */', $underline); - foreach ($separators as $n => $s) { - if (preg_match('/^ *-+: *$/', $s)) $attr[$n] = ' align="right"'; - else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"'; - else if (preg_match('/^ *:-+ *$/', $s)) $attr[$n] = ' align="left"'; - else $attr[$n] = ''; - } - - # Parsing span elements, including code spans, character escapes, - # and inline HTML tags, so that pipes inside those gets ignored. - $head = $this->parseSpan($head); - $headers = preg_split('/ *[|] */', $head); - $col_count = count($headers); - - # Write column headers. - $text = "\n"; - $text .= "\n"; - $text .= "\n"; - foreach ($headers as $n => $header) - $text .= " ".$this->runSpanGamut(trim($header))."\n"; - $text .= "\n"; - $text .= "\n"; - - # Split content by row. - $rows = explode("\n", trim($content, "\n")); - - $text .= "\n"; - foreach ($rows as $row) { - # Parsing span elements, including code spans, character escapes, - # and inline HTML tags, so that pipes inside those gets ignored. - $row = $this->parseSpan($row); - - # Split row by cell. - $row_cells = preg_split('/ *[|] */', $row, $col_count); - $row_cells = array_pad($row_cells, $col_count, ''); - - $text .= "\n"; - foreach ($row_cells as $n => $cell) - $text .= " ".$this->runSpanGamut(trim($cell))."\n"; - $text .= "\n"; - } - $text .= "\n"; - $text .= "
    "; - - return $this->hashBlock($text) . "\n"; - } - - - function doDefLists($text) { - # - # Form HTML definition lists. - # - $less_than_tab = $this->tab_width - 1; - - # Re-usable pattern to match any entire dl list: - $whole_list_re = '(?> - ( # $1 = whole list - ( # $2 - [ ]{0,'.$less_than_tab.'} - ((?>.*\S.*\n)+) # $3 = defined term - \n? - [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition - ) - (?s:.+?) - ( # $4 - \z - | - \n{2,} - (?=\S) - (?! # Negative lookahead for another term - [ ]{0,'.$less_than_tab.'} - (?: \S.*\n )+? # defined term - \n? - [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition - ) - (?! # Negative lookahead for another definition - [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition - ) - ) - ) - )'; // mx - - $text = preg_replace_callback('{ - (?>\A\n?|(?<=\n\n)) - '.$whole_list_re.' - }mx', - array(&$this, '_doDefLists_callback'), $text); - - return $text; - } - function _doDefLists_callback($matches) { - # Re-usable patterns to match list item bullets and number markers: - $list = $matches[1]; - - # Turn double returns into triple returns, so that we can make a - # paragraph for the last item in a list, if necessary: - $result = trim($this->processDefListItems($list)); - $result = "
    \n" . $result . "\n
    "; - return $this->hashBlock($result) . "\n\n"; - } - - - function processDefListItems($list_str) { - # - # Process the contents of a single definition list, splitting it - # into individual term and definition list items. - # - $less_than_tab = $this->tab_width - 1; - - # trim trailing blank lines: - $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); - - # Process definition terms. - $list_str = preg_replace_callback('{ - (?>\A\n?|\n\n+) # leading line - ( # definition terms = $1 - [ ]{0,'.$less_than_tab.'} # leading whitespace - (?![:][ ]|[ ]) # negative lookahead for a definition - # mark (colon) or more whitespace. - (?> \S.* \n)+? # actual term (not whitespace). - ) - (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed - # with a definition mark. - }xm', - array(&$this, '_processDefListItems_callback_dt'), $list_str); - - # Process actual definitions. - $list_str = preg_replace_callback('{ - \n(\n+)? # leading line = $1 - ( # marker space = $2 - [ ]{0,'.$less_than_tab.'} # whitespace before colon - [:][ ]+ # definition mark (colon) - ) - ((?s:.+?)) # definition text = $3 - (?= \n+ # stop at next definition mark, - (?: # next term or end of text - [ ]{0,'.$less_than_tab.'} [:][ ] | -
    | \z - ) - ) - }xm', - array(&$this, '_processDefListItems_callback_dd'), $list_str); - - return $list_str; - } - function _processDefListItems_callback_dt($matches) { - $terms = explode("\n", trim($matches[1])); - $text = ''; - foreach ($terms as $term) { - $term = $this->runSpanGamut(trim($term)); - $text .= "\n
    " . $term . "
    "; - } - return $text . "\n"; - } - function _processDefListItems_callback_dd($matches) { - $leading_line = $matches[1]; - $marker_space = $matches[2]; - $def = $matches[3]; - - if ($leading_line || preg_match('/\n{2,}/', $def)) { - # Replace marker with the appropriate whitespace indentation - $def = str_repeat(' ', strlen($marker_space)) . $def; - $def = $this->runBlockGamut($this->outdent($def . "\n\n")); - $def = "\n". $def ."\n"; - } - else { - $def = rtrim($def); - $def = $this->runSpanGamut($this->outdent($def)); - } - - return "\n
    " . $def . "
    \n"; - } - - - function doFencedCodeBlocks($text) { - # - # Adding the fenced code block syntax to regular Markdown: - # - # ~~~ - # Code block - # ~~~ - # - $less_than_tab = $this->tab_width; - - $text = preg_replace_callback('{ - (?:\n|\A) - # 1: Opening marker - ( - ~{3,} # Marker: three tilde or more. - ) - [ ]* \n # Whitespace and newline following marker. - - # 2: Content - ( - (?> - (?!\1 [ ]* \n) # Not a closing marker. - .*\n+ - )+ - ) - - # Closing marker. - \1 [ ]* \n - }xm', - array(&$this, '_doFencedCodeBlocks_callback'), $text); - - return $text; - } - function _doFencedCodeBlocks_callback($matches) { - $codeblock = $matches[2]; - $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES); - $codeblock = preg_replace_callback('/^\n+/', - array(&$this, '_doFencedCodeBlocks_newlines'), $codeblock); - $codeblock = "
    $codeblock
    "; - return "\n\n".$this->hashBlock($codeblock)."\n\n"; - } - function _doFencedCodeBlocks_newlines($matches) { - return str_repeat("empty_element_suffix", - strlen($matches[0])); - } - - - # - # Redefining emphasis markers so that emphasis by underscore does not - # work in the middle of a word. - # - var $em_relist = array( - '' => '(?:(? '(?<=\S)(? '(?<=\S)(? '(?:(? '(?<=\S)(? '(?<=\S)(? '(?:(? '(?<=\S)(? '(?<=\S)(? tags - # - # Strip leading and trailing lines: - $text = preg_replace('/\A\n+|\n+\z/', '', $text); - - $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY); - - # - # Wrap

    tags and unhashify HTML blocks - # - foreach ($grafs as $key => $value) { - $value = trim($this->runSpanGamut($value)); - - # Check if this should be enclosed in a paragraph. - # Clean tag hashes & block tag hashes are left alone. - $is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value); - - if ($is_p) { - $value = "

    $value

    "; - } - $grafs[$key] = $value; - } - - # Join grafs in one text, then unhash HTML tags. - $text = implode("\n\n", $grafs); - - # Finish by removing any tag hashes still present in $text. - $text = $this->unhash($text); - - return $text; - } - - - ### Footnotes - - function stripFootnotes($text) { - # - # Strips link definitions from text, stores the URLs and titles in - # hash references. - # - $less_than_tab = $this->tab_width - 1; - - # Link defs are in the form: [^id]: url "optional title" - $text = preg_replace_callback('{ - ^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?: # note_id = $1 - [ ]* - \n? # maybe *one* newline - ( # text = $2 (no blank lines allowed) - (?: - .+ # actual text - | - \n # newlines but - (?!\[\^.+?\]:\s)# negative lookahead for footnote marker. - (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed - # by non-indented content - )* - ) - }xm', - array(&$this, '_stripFootnotes_callback'), - $text); - return $text; - } - function _stripFootnotes_callback($matches) { - $note_id = $this->fn_id_prefix . $matches[1]; - $this->footnotes[$note_id] = $this->outdent($matches[2]); - return ''; # String that will replace the block - } - - - function doFootnotes($text) { - # - # Replace footnote references in $text [^id] with a special text-token - # which will be replaced by the actual footnote marker in appendFootnotes. - # - if (!$this->in_anchor) { - $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text); - } - return $text; - } - - - function appendFootnotes($text) { - # - # Append footnote list to text. - # - $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}', - array(&$this, '_appendFootnotes_callback'), $text); - - if (!empty($this->footnotes_ordered)) { - $text .= "\n\n"; - $text .= "
    \n"; - $text .= "fn_backlink_class != "") { - $class = $this->fn_backlink_class; - $class = $this->encodeAttribute($class); - $attr .= " class=\"$class\""; - } - if ($this->fn_backlink_title != "") { - $title = $this->fn_backlink_title; - $title = $this->encodeAttribute($title); - $attr .= " title=\"$title\""; - } - $num = 0; - - while (!empty($this->footnotes_ordered)) { - $footnote = reset($this->footnotes_ordered); - $note_id = key($this->footnotes_ordered); - unset($this->footnotes_ordered[$note_id]); - - $footnote .= "\n"; # Need to append newline before parsing. - $footnote = $this->runBlockGamut("$footnote\n"); - $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}', - array(&$this, '_appendFootnotes_callback'), $footnote); - - $attr = str_replace("%%", ++$num, $attr); - $note_id = $this->encodeAttribute($note_id); - - # Add backlink to last paragraph; create new paragraph if needed. - $backlink = ""; - if (preg_match('{

    $}', $footnote)) { - $footnote = substr($footnote, 0, -4) . " $backlink

    "; - } else { - $footnote .= "\n\n

    $backlink

    "; - } - - $text .= "
  • \n"; - $text .= $footnote . "\n"; - $text .= "
  • \n\n"; - } - - $text .= "\n"; - $text .= "
    "; - } - return $text; - } - function _appendFootnotes_callback($matches) { - $node_id = $this->fn_id_prefix . $matches[1]; - - # Create footnote marker only if it has a corresponding footnote *and* - # the footnote hasn't been used by another marker. - if (isset($this->footnotes[$node_id])) { - # Transfert footnote content to the ordered list. - $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id]; - unset($this->footnotes[$node_id]); - - $num = $this->footnote_counter++; - $attr = " rel=\"footnote\""; - if ($this->fn_link_class != "") { - $class = $this->fn_link_class; - $class = $this->encodeAttribute($class); - $attr .= " class=\"$class\""; - } - if ($this->fn_link_title != "") { - $title = $this->fn_link_title; - $title = $this->encodeAttribute($title); - $attr .= " title=\"$title\""; - } - - $attr = str_replace("%%", $num, $attr); - $node_id = $this->encodeAttribute($node_id); - - return - "". - "$num". - ""; - } - - return "[^".$matches[1]."]"; - } - - - ### Abbreviations ### - - function stripAbbreviations($text) { - # - # Strips abbreviations from text, stores titles in hash references. - # - $less_than_tab = $this->tab_width - 1; - - # Link defs are in the form: [id]*: url "optional title" - $text = preg_replace_callback('{ - ^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?: # abbr_id = $1 - (.*) # text = $2 (no blank lines allowed) - }xm', - array(&$this, '_stripAbbreviations_callback'), - $text); - return $text; - } - function _stripAbbreviations_callback($matches) { - $abbr_word = $matches[1]; - $abbr_desc = $matches[2]; - if ($this->abbr_word_re) - $this->abbr_word_re .= '|'; - $this->abbr_word_re .= preg_quote($abbr_word); - $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); - return ''; # String that will replace the block - } - - - function doAbbreviations($text) { - # - # Find defined abbreviations in text and wrap them in elements. - # - if ($this->abbr_word_re) { - // cannot use the /x modifier because abbr_word_re may - // contain significant spaces: - $text = preg_replace_callback('{'. - '(?abbr_word_re.')'. - '(?![\w\x1A])'. - '}', - array(&$this, '_doAbbreviations_callback'), $text); - } - return $text; - } - function _doAbbreviations_callback($matches) { - $abbr = $matches[0]; - if (isset($this->abbr_desciptions[$abbr])) { - $desc = $this->abbr_desciptions[$abbr]; - if (empty($desc)) { - return $this->hashPart("$abbr"); - } else { - $desc = $this->encodeAttribute($desc); - return $this->hashPart("$abbr"); - } - } else { - return $matches[0]; - } - } - -} - - -/* - -PHP Markdown Extra -================== - -Description ------------ - -This is a PHP port of the original Markdown formatter written in Perl -by John Gruber. This special "Extra" version of PHP Markdown features -further enhancements to the syntax for making additional constructs -such as tables and definition list. - -Markdown is a text-to-HTML filter; it translates an easy-to-read / -easy-to-write structured text format into HTML. Markdown's text format -is most similar to that of plain text email, and supports features such -as headers, *emphasis*, code blocks, blockquotes, and links. - -Markdown's syntax is designed not as a generic markup language, but -specifically to serve as a front-end to (X)HTML. You can use span-level -HTML tags anywhere in a Markdown document, and you can use block level -HTML tags (like
    and as well). - -For more information about Markdown's syntax, see: - - - - -Bugs ----- - -To file bug reports please send email to: - - - -Please include with your report: (1) the example input; (2) the output you -expected; (3) the output Markdown actually produced. - - -Version History ---------------- - -See the readme file for detailed release notes for this version. - - -Copyright and License ---------------------- - -PHP Markdown & Extra -Copyright (c) 2004-2008 Michel Fortin - -All rights reserved. - -Based on Markdown -Copyright (c) 2003-2006 John Gruber - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -* Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -* Neither the name "Markdown" nor the names of its contributors may - be used to endorse or promote products derived from this software - without specific prior written permission. - -This software is provided by the copyright holders and contributors "as -is" and any express or implied warranties, including, but not limited -to, the implied warranties of merchantability and fitness for a -particular purpose are disclaimed. In no event shall the copyright owner -or contributors be liable for any direct, indirect, incidental, special, -exemplary, or consequential damages (including, but not limited to, -procurement of substitute goods or services; loss of use, data, or -profits; or business interruption) however caused and on any theory of -liability, whether in contract, strict liability, or tort (including -negligence or otherwise) arising in any way out of the use of this -software, even if advised of the possibility of such damage. - -*/ -?> \ No newline at end of file -- cgit v1.2.3 From 3e8e13bd2533ff7e3493b27c8a8587dfb65e1b26 Mon Sep 17 00:00:00 2001 From: Bharat Mediratta Date: Wed, 23 Dec 2009 12:42:57 -0800 Subject: Updated Kohana to r4728 --- system/core/Kohana.php | 7 ++--- system/core/Kohana_Exception.php | 26 ++++++++++-------- system/libraries/Input.php | 31 +-------------------- system/messages/core.php | 37 ------------------------- system/messages/kohana/core.php | 37 +++++++++++++++++++++++++ system/messages/validation/default.php | 42 ++++++++++++++++------------ system/views/kohana/error.php | 50 +++++++++++++++++----------------- 7 files changed, 104 insertions(+), 126 deletions(-) delete mode 100644 system/messages/core.php create mode 100644 system/messages/kohana/core.php (limited to 'system/core') diff --git a/system/core/Kohana.php b/system/core/Kohana.php index 740adb80..29ca708c 100644 --- a/system/core/Kohana.php +++ b/system/core/Kohana.php @@ -2,7 +2,7 @@ /** * Provides Kohana-specific helper functions. This is where the magic happens! * - * $Id: Kohana.php 4724 2009-12-21 16:28:54Z isaiah $ + * $Id: Kohana.php 4726 2009-12-23 18:58:53Z isaiah $ * * @package Core * @author Kohana Team @@ -810,11 +810,8 @@ abstract class Kohana_Core { { if ($required === TRUE) { - // Directory i18n key - $directory = 'core.'.inflector::singular($directory); - // If the file is required, throw an exception - throw new Kohana_Exception('The requested :resource:, :file:, could not be found', array(':resource:' => Kohana::message($directory), ':file:' =>$filename)); + throw new Kohana_Exception('The requested :resource:, :file:, could not be found', array(':resource:' => __($directory), ':file:' =>$filename)); } else { diff --git a/system/core/Kohana_Exception.php b/system/core/Kohana_Exception.php index 2eb28f75..0cbc472c 100644 --- a/system/core/Kohana_Exception.php +++ b/system/core/Kohana_Exception.php @@ -2,7 +2,7 @@ /** * Kohana Exceptions * - * $Id: Kohana_Exception.php 4692 2009-12-04 15:59:44Z cbandy $ + * $Id: Kohana_Exception.php 4726 2009-12-23 18:58:53Z isaiah $ * * @package Core * @author Kohana Team @@ -119,7 +119,7 @@ class Kohana_Exception_Core extends Exception { // Manually save logs after exceptions Kohana_Log::save(); - if (Kohana::config('core.display_errors') === FALSE) + if (Kohana::config('kohana/core.display_errors') === FALSE) { // Do not show the details $file = $line = NULL; @@ -146,7 +146,7 @@ class Kohana_Exception_Core extends Exception { } // Use the human-readable error name - $code = Kohana::message('core.errors.'.$code); + $code = Kohana::message('kohana/core.errors.'.$code); } else { @@ -160,7 +160,7 @@ class Kohana_Exception_Core extends Exception { if ($e instanceof ErrorException) { // Use the human-readable error name - $code = Kohana::message('core.errors.'.$e->getSeverity()); + $code = Kohana::message('kohana/core.errors.'.$e->getSeverity()); if (version_compare(PHP_VERSION, '5.3', '<')) { @@ -233,11 +233,12 @@ class Kohana_Exception_Core extends Exception { * * @param mixed variable to dump * @param integer maximum length of strings + * @param integer maximum levels of recursion * @return string */ - public static function dump($value, $length = 128) + public static function dump($value, $length = 128, $max_level = 5) { - return Kohana_Exception::_dump($value, $length); + return Kohana_Exception::_dump($value, $length, $max_level); } /** @@ -245,10 +246,11 @@ class Kohana_Exception_Core extends Exception { * * @param mixed variable to dump * @param integer maximum length of strings - * @param integer recursion level (internal) + * @param integer maximum levels of recursion + * @param integer current recursion level (internal) * @return string */ - private static function _dump( & $var, $length = 128, $level = 0) + private static function _dump( & $var, $length = 128, $max_level = 5, $level = 0) { if ($var === NULL) { @@ -327,7 +329,7 @@ class Kohana_Exception_Core extends Exception { { $output[] = "(\n$space$s*RECURSION*\n$space)"; } - elseif ($level < 5) + elseif ($level <= $max_level) { $output[] = "("; @@ -340,7 +342,7 @@ class Kohana_Exception_Core extends Exception { $key = '"'.$key.'"'; } - $output[] = "$space$s$key => ".Kohana_Exception::_dump($val, $length, $level + 1); + $output[] = "$space$s$key => ".Kohana_Exception::_dump($val, $length, $max_level, $level + 1); } unset($var[$marker]); @@ -377,7 +379,7 @@ class Kohana_Exception_Core extends Exception { { $output[] = "{\n$space$s*RECURSION*\n$space}"; } - elseif ($level < 5) + elseif ($level <= $max_level) { $output[] = "{"; @@ -397,7 +399,7 @@ class Kohana_Exception_Core extends Exception { $access = 'public'; } - $output[] = "$space$s$access $key => ".Kohana_Exception::_dump($val, $length, $level + 1); + $output[] = "$space$s$access $key => ".Kohana_Exception::_dump($val, $length, $max_level, $level + 1); } unset($objects[$hash]); diff --git a/system/libraries/Input.php b/system/libraries/Input.php index 04403854..7a277317 100644 --- a/system/libraries/Input.php +++ b/system/libraries/Input.php @@ -2,7 +2,7 @@ /** * Input library. * - * $Id: Input.php 4720 2009-12-17 21:15:03Z isaiah $ + * $Id: Input.php 4727 2009-12-23 19:03:05Z isaiah $ * * @package Core * @author Kohana Team @@ -79,35 +79,6 @@ class Input_Core { Kohana_Log::add('debug', 'Disable magic_quotes_gpc! It is evil and deprecated: http://php.net/magic_quotes'); } - // register_globals is enabled - if (ini_get('register_globals')) - { - if (isset($_REQUEST['GLOBALS'])) - { - // Prevent GLOBALS override attacks - exit('Global variable overload attack.'); - } - - // Destroy the REQUEST global - $_REQUEST = array(); - - // These globals are standard and should not be removed - $preserve = array('GLOBALS', '_REQUEST', '_GET', '_POST', '_FILES', '_COOKIE', '_SERVER', '_ENV', '_SESSION'); - - // This loop has the same effect as disabling register_globals - foreach (array_diff(array_keys($GLOBALS), $preserve) as $key) - { - global $$key; - $$key = NULL; - - // Unset the global variable - unset($GLOBALS[$key], $$key); - } - - // Warn the developer about register globals - Kohana_Log::add('debug', 'Disable register_globals! It is evil and deprecated: http://php.net/register_globals'); - } - if (is_array($_GET)) { foreach ($_GET as $key => $val) diff --git a/system/messages/core.php b/system/messages/core.php deleted file mode 100644 index 64f897e8..00000000 --- a/system/messages/core.php +++ /dev/null @@ -1,37 +0,0 @@ - array - ( - E_KOHANA => __('Framework Error'), // __('Please check the Kohana documentation for information about the following error.'), - E_PAGE_NOT_FOUND => __('Page Not Found'), // __('The requested page was not found. It may have moved, been deleted, or archived.'), - E_DATABASE_ERROR => __('Database Error'), // __('A database error occurred while performing the requested procedure. Please review the database error below for more information.'), - E_RECOVERABLE_ERROR => __('Recoverable Error'), // __('An error was detected which prevented the loading of this page. If this problem persists, please contact the website administrator.'), - E_ERROR => __('Fatal Error'), - E_COMPILE_ERROR => __('Fatal Error'), - E_CORE_ERROR => __('Fatal Error'), - E_USER_ERROR => __('Fatal Error'), - E_PARSE => __('Syntax Error'), - E_WARNING => __('Warning Message'), - E_COMPILE_WARNING => __('Warning Message'), - E_CORE_WARNING => __('Warning Message'), - E_USER_WARNING => __('Warning Message'), - E_STRICT => __('Strict Mode Error'), - E_NOTICE => __('Runtime Message'), - E_USER_NOTICE => __('Runtime Message'), - ), - 'config' => 'config file', - 'controller' => 'controller', - 'helper' => 'helper', - 'library' => 'library', - 'driver' => 'driver', - 'model' => 'model', - 'view' => 'view', -); - -// E_DEPRECATED is only defined in PHP >= 5.3.0 -if (defined('E_DEPRECATED')) -{ - $messages['errors'][E_DEPRECATED] = __('Deprecated'); -} \ No newline at end of file diff --git a/system/messages/kohana/core.php b/system/messages/kohana/core.php new file mode 100644 index 00000000..1361809b --- /dev/null +++ b/system/messages/kohana/core.php @@ -0,0 +1,37 @@ + array + ( + E_KOHANA => 'Framework Error', + E_PAGE_NOT_FOUND => 'Page Not Found', + E_DATABASE_ERROR => 'Database Error', + E_RECOVERABLE_ERROR => 'Recoverable Error', + E_ERROR => 'Fatal Error', + E_COMPILE_ERROR => 'Fatal Error', + E_CORE_ERROR => 'Fatal Error', + E_USER_ERROR => 'Fatal Error', + E_PARSE => 'Syntax Error', + E_WARNING => 'Warning Message', + E_COMPILE_WARNING => 'Warning Message', + E_CORE_WARNING => 'Warning Message', + E_USER_WARNING => 'Warning Message', + E_STRICT => 'Strict Mode Error', + E_NOTICE => 'Runtime Message', + E_USER_NOTICE => 'Runtime Message', + ), +); + +// E_DEPRECATED is only defined in PHP >= 5.3.0 +if (defined('E_DEPRECATED')) +{ + $messages['errors'][E_DEPRECATED] = 'Deprecated'; +} \ No newline at end of file diff --git a/system/messages/validation/default.php b/system/messages/validation/default.php index 2c59fa06..88580a6b 100644 --- a/system/messages/validation/default.php +++ b/system/messages/validation/default.php @@ -1,17 +1,25 @@ - 'The :field field is required', - 'length' => 'The :field field must be between :param1 and :param2 characters long', - 'depends_on' => 'The :field field requires the :param1 field', - 'matches' => 'The :field field must be the same as :param1', - 'email' => 'The :field field must be a valid email address', - 'decimal' => 'The :field field must be a decimal with :param1 places', - 'digit' => 'The :field field must be a digit', - 'in_array' => 'The :field field must be one of the available options', - 'alpha_numeric' => 'The :field field must consist only of alphabetical or numeric characters', - 'alpha_dash ' => 'The :field field must consist only of alphabetical, numeric, underscore and dash characters', - 'numeric ' => 'The :field field must be a valid number', - 'url' => 'The :field field must be a valid url', - 'phone' => 'The :field field must be a valid phone number', -); + 'The :field field is required', + 'length' => 'The :field field must be between :param1 and :param2 characters long', + 'depends_on' => 'The :field field requires the :param1 field', + 'matches' => 'The :field field must be the same as :param1', + 'email' => 'The :field field must be a valid email address', + 'decimal' => 'The :field field must be a decimal with :param1 places', + 'digit' => 'The :field field must be a digit', + 'in_array' => 'The :field field must be one of the available options', + 'alpha_numeric' => 'The :field field must consist only of alphabetical or numeric characters', + 'alpha_dash ' => 'The :field field must consist only of alphabetical, numeric, underscore and dash characters', + 'numeric ' => 'The :field field must be a valid number', + 'url' => 'The :field field must be a valid url', + 'phone' => 'The :field field must be a valid phone number', +); diff --git a/system/views/kohana/error.php b/system/views/kohana/error.php index b40c0f8a..aa6770c4 100644 --- a/system/views/kohana/error.php +++ b/system/views/kohana/error.php @@ -3,7 +3,7 @@ $error_id = uniqid('error'); ?>