summaryrefslogtreecommitdiff
path: root/system/helpers
diff options
context:
space:
mode:
authorBharat Mediratta <bharat@menalto.com>2009-11-24 19:20:36 -0800
committerBharat Mediratta <bharat@menalto.com>2009-11-24 19:20:36 -0800
commit9b6663f87a7e679ffba691cf516191fc840cf978 (patch)
tree20cf9f3aaf93b4ba69d282dcf10d259db4a752de /system/helpers
parent82ee5f9d338017c69331b2907f37a468ced8c66e (diff)
Update to Kohana r4684 which is now Kohana 2.4 and has substantial
changes.
Diffstat (limited to 'system/helpers')
-rw-r--r--system/helpers/arr.php103
-rw-r--r--system/helpers/cookie.php87
-rw-r--r--system/helpers/date.php42
-rw-r--r--system/helpers/db.php49
-rw-r--r--system/helpers/download.php148
-rw-r--r--system/helpers/email.php181
-rw-r--r--system/helpers/expires.php115
-rw-r--r--system/helpers/feed.php6
-rw-r--r--system/helpers/file.php6
-rw-r--r--system/helpers/form.php123
-rw-r--r--system/helpers/format.php54
-rw-r--r--system/helpers/html.php106
-rw-r--r--system/helpers/inflector.php73
-rw-r--r--system/helpers/num.php6
-rw-r--r--system/helpers/remote.php10
-rw-r--r--system/helpers/request.php480
-rw-r--r--system/helpers/security.php11
-rw-r--r--system/helpers/text.php218
-rw-r--r--system/helpers/upload.php15
-rw-r--r--system/helpers/url.php10
-rw-r--r--system/helpers/utf8.php746
-rw-r--r--system/helpers/valid.php64
22 files changed, 1944 insertions, 709 deletions
diff --git a/system/helpers/arr.php b/system/helpers/arr.php
index 9570c4b5..a1bde230 100644
--- a/system/helpers/arr.php
+++ b/system/helpers/arr.php
@@ -2,12 +2,12 @@
/**
* Array helper class.
*
- * $Id: arr.php 4346 2009-05-11 17:08:15Z zombor $
+ * $Id: arr.php 4680 2009-11-10 01:57:00Z 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
*/
class arr_Core {
@@ -102,20 +102,26 @@ class arr_Core {
$found = array();
foreach ($keys as $key)
{
- if (isset($search[$key]))
- {
- $found[$key] = $search[$key];
- }
- else
- {
- $found[$key] = NULL;
- }
+ $found[$key] = isset($search[$key]) ? $search[$key] : NULL;
}
return $found;
}
/**
+ * Get the value of array[key]. If it doesn't exist, return default.
+ *
+ * @param array array to search
+ * @param string key name
+ * @param mixed default value
+ * @return mixed
+ */
+ public static function get(array $array, $key, $default = NULL)
+ {
+ return isset($array[$key]) ? $array[$key] : $default;
+ }
+
+ /**
* Because PHP does not have this function.
*
* @param array array to unshift
@@ -152,44 +158,6 @@ class arr_Core {
}
/**
- * @param mixed $needle the value to search for
- * @param array $haystack an array of values to search in
- * @param boolean $sort sort the array now
- * @return integer|FALSE the index of the match or FALSE when not found
- */
- public static function binary_search($needle, $haystack, $sort = FALSE)
- {
- if ($sort)
- {
- sort($haystack);
- }
-
- $high = count($haystack) - 1;
- $low = 0;
-
- while ($low <= $high)
- {
- $mid = ($low + $high) >> 1;
-
- if ($haystack[$mid] < $needle)
- {
- $low = $mid + 1;
- }
- elseif ($haystack[$mid] > $needle)
- {
- $high = $mid - 1;
- }
- else
- {
- return $mid;
- }
- }
-
- return FALSE;
- }
-
-
- /**
* Emulates array_merge_recursive, but appends numeric keys and replaces
* associative keys, instead of appending all keys.
*
@@ -264,27 +232,6 @@ class arr_Core {
}
/**
- * Fill an array with a range of numbers.
- *
- * @param integer stepping
- * @param integer ending number
- * @return array
- */
- public static function range($step = 10, $max = 100)
- {
- if ($step < 1)
- return array();
-
- $array = array();
- for ($i = $step; $i <= $max; $i += $step)
- {
- $array[$i] = $i;
- }
-
- return $array;
- }
-
- /**
* Recursively convert an array to an object.
*
* @param array array to convert
@@ -309,4 +256,20 @@ class arr_Core {
return $object;
}
+ /**
+ * Returns specific key/column from an array of objects.
+ *
+ * @param string|integer $key The key or column number to pluck from each object.
+ * @param array $array The array of objects to pluck from.
+ * @return array
+ */
+ public static function pluck($key, $array)
+ {
+ $result = array();
+ foreach ($array as $i => $object)
+ {
+ $result[$i] = isset($object[$key]) ? $object[$key] : NULL;
+ }
+ return $result;
+ }
} // End arr
diff --git a/system/helpers/cookie.php b/system/helpers/cookie.php
index 901b6d86..8a2e3659 100644
--- a/system/helpers/cookie.php
+++ b/system/helpers/cookie.php
@@ -2,12 +2,12 @@
/**
* Cookie helper class.
*
- * $Id: cookie.php 3769 2008-12-15 00:48:56Z zombor $
+ * $Id: cookie.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
*/
class cookie_Core {
@@ -42,8 +42,13 @@ class cookie_Core {
}
}
- // Expiration timestamp
- $expire = ($expire == 0) ? 0 : time() + (int) $expire;
+ if ($expire !== 0)
+ {
+ // The expiration is expected to be a UNIX timestamp
+ $expire += time();
+ }
+
+ $value = cookie::salt($name, $value).'~'.$value;
return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
}
@@ -56,9 +61,51 @@ class cookie_Core {
* @param boolean use XSS cleaning on the value
* @return string
*/
- public static function get($name, $default = NULL, $xss_clean = FALSE)
+ public static function get($name = NULL, $default = NULL, $xss_clean = FALSE)
{
- return Input::instance()->cookie($name, $default, $xss_clean);
+ // Return an array of all the cookies if we don't have a name
+ if ($name === NULL)
+ {
+ $cookies = array();
+
+ foreach($_COOKIE AS $key => $value)
+ {
+ $cookies[$key] = cookie::get($key, $default, $xss_clean);
+ }
+ return $cookies;
+ }
+
+ if ( ! isset($_COOKIE[$name]))
+ {
+ return $default;
+ }
+
+ // Get the cookie value
+ $cookie = $_COOKIE[$name];
+
+ // Find the position of the split between salt and contents
+ $split = strlen(cookie::salt($name, NULL));
+
+ if (isset($cookie[$split]) AND $cookie[$split] === '~')
+ {
+ // Separate the salt and the value
+ list ($hash, $value) = explode('~', $cookie, 2);
+
+ if (cookie::salt($name, $value) === $hash)
+ {
+ if ($xss_clean === TRUE AND Kohana::config('core.global_xss_filtering') === FALSE)
+ {
+ return Input::instance()->xss_clean($value);
+ }
+ // Cookie signature is valid
+ return $value;
+ }
+
+ // The cookie signature is invalid, delete it
+ cookie::delete($name);
+ }
+
+ return $default;
}
/**
@@ -71,9 +118,6 @@ class cookie_Core {
*/
public static function delete($name, $path = NULL, $domain = NULL)
{
- if ( ! isset($_COOKIE[$name]))
- return FALSE;
-
// Delete the cookie from globals
unset($_COOKIE[$name]);
@@ -81,4 +125,27 @@ class cookie_Core {
return cookie::set($name, '', -86400, $path, $domain, FALSE, FALSE);
}
+ /**
+ * Generates a salt string for a cookie based on the name and value.
+ *
+ * @param string $name name of cookie
+ * @param string $value value of cookie
+ * @return string sha1 hash
+ */
+ public static function salt($name, $value)
+ {
+ // Determine the user agent
+ $agent = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : 'unknown';
+
+ // Cookie salt.
+ $salt = Kohana::config('cookie.salt');
+
+ return sha1($agent.$name.$value.$salt);
+ }
+
+ final private function __construct()
+ {
+ // Static class.
+ }
+
} // End cookie \ No newline at end of file
diff --git a/system/helpers/date.php b/system/helpers/date.php
index 7d5a9ab6..af7e85bd 100644
--- a/system/helpers/date.php
+++ b/system/helpers/date.php
@@ -2,12 +2,12 @@
/**
* Date helper class.
*
- * $Id: date.php 4316 2009-05-04 01:03:54Z kiall $
+ * $Id: date.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
*/
class date_Core {
@@ -57,36 +57,28 @@ class date_Core {
* Returns the offset (in seconds) between two time zones.
* @see http://php.net/timezones
*
- * @param string timezone that to find the offset of
+ * @param string timezone to find the offset of
* @param string|boolean timezone used as the baseline
+ * @param string time at which to calculate
* @return integer
*/
- public static function offset($remote, $local = TRUE)
+ public static function offset($remote, $local = TRUE, $when = 'now')
{
- static $offsets;
-
- // Default values
- $remote = (string) $remote;
- $local = ($local === TRUE) ? date_default_timezone_get() : (string) $local;
-
- // Cache key name
- $cache = $remote.$local;
-
- if (empty($offsets[$cache]))
+ if ($local === TRUE)
{
- // Create timezone objects
- $remote = new DateTimeZone($remote);
- $local = new DateTimeZone($local);
+ $local = date_default_timezone_get();
+ }
- // Create date objects from timezones
- $time_there = new DateTime('now', $remote);
- $time_here = new DateTime('now', $local);
+ // Create timezone objects
+ $remote = new DateTimeZone($remote);
+ $local = new DateTimeZone($local);
- // Find the offset
- $offsets[$cache] = $remote->getOffset($time_there) - $local->getOffset($time_here);
- }
+ // Create date objects from timezones
+ $time_there = new DateTime($when, $remote);
+ $time_here = new DateTime($when, $local);
- return $offsets[$cache];
+ // Find the offset
+ return $remote->getOffset($time_there) - $local->getOffset($time_here);
}
/**
diff --git a/system/helpers/db.php b/system/helpers/db.php
new file mode 100644
index 00000000..ce7583b7
--- /dev/null
+++ b/system/helpers/db.php
@@ -0,0 +1,49 @@
+<?php defined('SYSPATH') or die('No direct script access.');
+/**
+ * Database helper class.
+ *
+ * $Id: $
+ *
+ * @package Core
+ * @author Kohana Team
+ * @copyright (c) 2007-2009 Kohana Team
+ * @license http://kohanaphp.com/license
+ */
+ class db_Core {
+
+ public static function query($sql)
+ {
+ return new Database_Query($sql);
+ }
+
+ public static function build($database = 'default')
+ {
+ return new Database_Builder($database);
+ }
+
+ public static function select($columns = NULL)
+ {
+ return db::build()->select($columns);
+ }
+
+ public static function insert($table = NULL, $set = NULL)
+ {
+ return db::build()->insert($table, $set);
+ }
+
+ public static function update($table = NULL, $set = NULL, $where = NULL)
+ {
+ return db::build()->update($table, $set, $where);
+ }
+
+ public static function delete($table = NULL, $where = NULL)
+ {
+ return db::build()->delete($table, $where);
+ }
+
+ public static function expr($expression)
+ {
+ return new Database_Expression($expression);
+ }
+
+} // End db
diff --git a/system/helpers/download.php b/system/helpers/download.php
index 49fed42c..58a7ab94 100644
--- a/system/helpers/download.php
+++ b/system/helpers/download.php
@@ -2,104 +2,136 @@
/**
* Download helper class.
*
- * $Id: download.php 3769 2008-12-15 00:48:56Z zombor $
+ * $Id: download.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
*/
class download_Core {
/**
- * Force a download of a file to the user's browser. This function is
- * binary-safe and will work with any MIME type that Kohana is aware of.
+ * Send headers necessary to invoke a "Save As" dialog
+ *
+ * @link http://support.microsoft.com/kb/260519
+ * @link http://greenbytes.de/tech/tc2231/
+ *
+ * @param string file name
+ * @return string file name as it was sent
+ */
+ public static function dialog($filename)
+ {
+ $filename = basename($filename);
+
+ header('Content-Disposition: attachment; filename="'.$filename.'"');
+
+ return $filename;
+ }
+
+ /**
+ * Send the contents of a file or a data string with the proper MIME type and exit.
+ *
+ * @uses exit()
+ * @uses Kohana::close_buffers()
*
* @param string a file path or file name
- * @param mixed data to be sent if the filename does not exist
- * @param string suggested filename to display in the download
+ * @param string optional data to send
* @return void
*/
- public static function force($filename = NULL, $data = NULL, $nicename = NULL)
+ public static function send($filename, $data = NULL)
{
- if (empty($filename))
- return FALSE;
-
- if (is_file($filename))
+ if ($data === NULL)
{
- // Get the real path
- $filepath = str_replace('\\', '/', realpath($filename));
+ $filepath = realpath($filename);
- // Set filesize
+ $filename = basename($filepath);
$filesize = filesize($filepath);
-
- // Get filename
- $filename = substr(strrchr('/'.$filepath, '/'), 1);
-
- // Get extension
- $extension = strtolower(substr(strrchr($filepath, '.'), 1));
}
else
{
- // Get filesize
+ $filename = basename($filename);
$filesize = strlen($data);
+ }
- // Make sure the filename does not have directory info
- $filename = substr(strrchr('/'.$filename, '/'), 1);
+ // Retrieve MIME type by extension
+ $mime = Kohana::config('mimes.'.strtolower(substr(strrchr($filename, '.'), 1)));
+ $mime = empty($mime) ? 'application/octet-stream' : $mime[0];
- // Get extension
- $extension = strtolower(substr(strrchr($filename, '.'), 1));
- }
+ // Close output buffers
+ Kohana::close_buffers(FALSE);
+
+ // Clear any output
+ Event::add('system.display', create_function('', 'Kohana::$output = "";'));
- // Get the mime type of the file
- $mime = Kohana::config('mimes.'.$extension);
+ // Send headers
+ header("Content-Type: $mime");
+ header('Content-Length: '.sprintf('%d', $filesize));
+ header('Content-Transfer-Encoding: binary');
- if (empty($mime))
+ // Send data
+ if ($data === NULL)
{
- // Set a default mime if none was found
- $mime = array('application/octet-stream');
+ $handle = fopen($filepath, 'rb');
+
+ fpassthru($handle);
+ fclose($handle);
+ }
+ else
+ {
+ echo $data;
}
- // Generate the server headers
- header('Content-Type: '.$mime[0]);
- header('Content-Disposition: attachment; filename="'.(empty($nicename) ? $filename : $nicename).'"');
- header('Content-Transfer-Encoding: binary');
- header('Content-Length: '.sprintf('%d', $filesize));
+ exit;
+ }
+
+ /**
+ * Force the download of a file by the user's browser by preventing any
+ * caching. Contains a workaround for Internet Explorer.
+ *
+ * @link http://support.microsoft.com/kb/316431
+ * @link http://support.microsoft.com/kb/812935
+ *
+ * @uses download::dialog()
+ * @uses download::send()
+ *
+ * @param string a file path or file name
+ * @param mixed data to be sent if the filename does not exist
+ * @param string suggested filename to display in the download
+ * @return void
+ */
+ public static function force($filename = NULL, $data = NULL, $nicename = NULL)
+ {
+ download::dialog(empty($nicename) ? $filename : $nicename);
- // More caching prevention
- header('Expires: 0');
+ // Prevent caching
+ header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
- if (Kohana::user_agent('browser') === 'Internet Explorer')
+ if (request::user_agent('browser') === 'Internet Explorer' AND request::user_agent('version') <= '6.0')
{
- // Send IE headers
+ // HTTP 1.0
+ header('Pragma:');
+
+ // HTTP 1.1 with IE extensions
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
- header('Pragma: public');
}
else
{
- // Send normal headers
+ // HTTP 1.0
header('Pragma: no-cache');
- }
- // Clear the output buffer
- Kohana::close_buffers(FALSE);
+ // HTTP 1.1
+ header('Cache-Control: no-cache, max-age=0');
+ }
- if (isset($filepath))
+ if (is_file($filename))
{
- // Open the file
- $handle = fopen($filepath, 'rb');
-
- // Send the file data
- fpassthru($handle);
-
- // Close the file
- fclose($handle);
+ download::send($filename);
}
else
{
- // Send the file data
- echo $data;
+ download::send($filename, $data);
}
}
-} // End download \ No newline at end of file
+} // End download
diff --git a/system/helpers/email.php b/system/helpers/email.php
deleted file mode 100644
index fb222d0c..00000000
--- a/system/helpers/email.php
+++ /dev/null
@@ -1,181 +0,0 @@
-<?php defined('SYSPATH') OR die('No direct access allowed.');
-/**
- * Email helper class.
- *
- * $Id: email.php 3769 2008-12-15 00:48:56Z zombor $
- *
- * @package Core
- * @author Kohana Team
- * @copyright (c) 2007-2008 Kohana Team
- * @license http://kohanaphp.com/license.html
- */
-class email_Core {
-
- // SwiftMailer instance
- protected static $mail;
-
- /**
- * Creates a SwiftMailer instance.
- *
- * @param string DSN connection string
- * @return object Swift object
- */
- public static function connect($config = NULL)
- {
- if ( ! class_exists('Swift', FALSE))
- {
- // Load SwiftMailer
- require Kohana::find_file('vendor', 'swift/Swift');
-
- // Register the Swift ClassLoader as an autoload
- spl_autoload_register(array('Swift_ClassLoader', 'load'));
- }
-
- // Load default configuration
- ($config === NULL) and $config = Kohana::config('email');
-
- switch ($config['driver'])
- {
- case 'smtp':
- // Set port
- $port = empty($config['options']['port']) ? NULL : (int) $config['options']['port'];
-
- if (empty($config['options']['encryption']))
- {
- // No encryption
- $encryption = Swift_Connection_SMTP::ENC_OFF;
- }
- else
- {
- // Set encryption
- switch (strtolower($config['options']['encryption']))
- {
- case 'tls': $encryption = Swift_Connection_SMTP::ENC_TLS; break;
- case 'ssl': $encryption = Swift_Connection_SMTP::ENC_SSL; break;
- }
- }
-
- // Create a SMTP connection
- $connection = new Swift_Connection_SMTP($config['options']['hostname'], $port, $encryption);
-
- // Do authentication, if part of the DSN
- empty($config['options']['username']) or $connection->setUsername($config['options']['username']);
- empty($config['options']['password']) or $connection->setPassword($config['options']['password']);
-
- if ( ! empty($config['options']['auth']))
- {
- // Get the class name and params
- list ($class, $params) = arr::callback_string($config['options']['auth']);
-
- if ($class === 'PopB4Smtp')
- {
- // Load the PopB4Smtp class manually, due to its odd filename
- require Kohana::find_file('vendor', 'swift/Swift/Authenticator/$PopB4Smtp$');
- }
-
- // Prepare the class name for auto-loading
- $class = 'Swift_Authenticator_'.$class;
-
- // Attach the authenticator
- $connection->attachAuthenticator(($params === NULL) ? new $class : new $class($params[0]));
- }
-
- // Set the timeout to 5 seconds
- $connection->setTimeout(empty($config['options']['timeout']) ? 5 : (int) $config['options']['timeout']);
- break;
- case 'sendmail':
- // Create a sendmail connection
- $connection = new Swift_Connection_Sendmail
- (
- empty($config['options']) ? Swift_Connection_Sendmail::AUTO_DETECT : $config['options']
- );
-
- // Set the timeout to 5 seconds
- $connection->setTimeout(5);
- break;
- default:
- // Use the native connection
- $connection = new Swift_Connection_NativeMail($config['options']);
- break;
- }
-
- // Create the SwiftMailer instance
- return email::$mail = new Swift($connection);
- }
-
- /**
- * Send an email message.
- *
- * @param string|array recipient email (and name), or an array of To, Cc, Bcc names
- * @param string|array sender email (and name)
- * @param string message subject
- * @param string message body
- * @param boolean send email as HTML
- * @return integer number of emails sent
- */
- public static function send($to, $from, $subject, $message, $html = FALSE)
- {
- // Connect to SwiftMailer
- (email::$mail === NULL) and email::connect();
-
- // Determine the message type
- $html = ($html === TRUE) ? 'text/html' : 'text/plain';
-
- // Create the message
- $message = new Swift_Message($subject, $message, $html, '8bit', 'utf-8');
-
- if (is_string($to))
- {
- // Single recipient
- $recipients = new Swift_Address($to);
- }
- elseif (is_array($to))
- {
- if (isset($to[0]) AND isset($to[1]))
- {
- // Create To: address set
- $to = array('to' => $to);
- }
-
- // Create a list of recipients
- $recipients = new Swift_RecipientList;
-
- foreach ($to as $method => $set)
- {
- if ( ! in_array($method, array('to', 'cc', 'bcc')))
- {
- // Use To: by default
- $method = 'to';
- }
-
- // Create method name
- $method = 'add'.ucfirst($method);
-
- if (is_array($set))
- {
- // Add a recipient with name
- $recipients->$method($set[0], $set[1]);
- }
- else
- {
- // Add a recipient without name
- $recipients->$method($set);
- }
- }
- }
-
- if (is_string($from))
- {
- // From without a name
- $from = new Swift_Address($from);
- }
- elseif (is_array($from))
- {
- // From with a name
- $from = new Swift_Address($from[0], $from[1]);
- }
-
- return email::$mail->send($message, $recipients, $from);
- }
-
-} // End email \ No newline at end of file
diff --git a/system/helpers/expires.php b/system/helpers/expires.php
index c43cc0cc..ce0482c8 100644
--- a/system/helpers/expires.php
+++ b/system/helpers/expires.php
@@ -2,54 +2,49 @@
/**
* Controls headers that effect client caching of pages
*
- * $Id: expires.php 4272 2009-04-25 21:47:26Z zombor $
+ * $Id: expires.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
*/
class expires_Core {
/**
- * Sets the amount of time before a page expires
+ * Sets the amount of time before content expires
*
- * @param integer Seconds before the page expires
- * @return boolean
+ * @param integer Seconds before the content expires
+ * @return integer Timestamp when the content expires
*/
public static function set($seconds = 60)
{
- if (expires::check_headers())
- {
- $now = $expires = time();
+ $now = time();
+ $expires = $now + $seconds;
- // Set the expiration timestamp
- $expires += $seconds;
+ header('Last-Modified: '.gmdate('D, d M Y H:i:s T', $now));
- // Send headers
- header('Last-Modified: '.gmdate('D, d M Y H:i:s T', $now));
- header('Expires: '.gmdate('D, d M Y H:i:s T', $expires));
- header('Cache-Control: max-age='.$seconds);
+ // HTTP 1.0
+ header('Expires: '.gmdate('D, d M Y H:i:s T', $expires));
- return $expires;
- }
+ // HTTP 1.1
+ header('Cache-Control: max-age='.$seconds);
- return FALSE;
+ return $expires;
}
/**
- * Checks to see if a page should be updated or send Not Modified status
+ * Parses the If-Modified-Since header
*
- * @param integer Seconds added to the modified time received to calculate what should be sent
- * @return bool FALSE when the request needs to be updated
+ * @return integer|boolean Timestamp or FALSE when header is lacking or malformed
*/
- public static function check($seconds = 60)
+ public static function get()
{
- if ( ! empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) AND expires::check_headers())
+ if ( ! empty($_SERVER['HTTP_IF_MODIFIED_SINCE']))
{
+ // Some versions of IE6 append "; length=####"
if (($strpos = strpos($_SERVER['HTTP_IF_MODIFIED_SINCE'], ';')) !== FALSE)
{
- // IE6 and perhaps other IE versions send length too, compensate here
$mod_time = substr($_SERVER['HTTP_IF_MODIFIED_SINCE'], 0, $strpos);
}
else
@@ -57,55 +52,69 @@ class expires_Core {
$mod_time = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
}
- $mod_time = strtotime($mod_time);
- $mod_time_diff = $mod_time + $seconds - time();
+ return strtotime($mod_time);
+ }
+
+ return FALSE;
+ }
- if ($mod_time_diff > 0)
+ /**
+ * Checks to see if content should be updated otherwise sends Not Modified status
+ * and exits.
+ *
+ * @uses exit()
+ * @uses expires::get()
+ *
+ * @param integer Maximum age of the content in seconds
+ * @return integer|boolean Timestamp of the If-Modified-Since header or FALSE when header is lacking or malformed
+ */
+ public static function check($seconds = 60)
+ {
+ if ($last_modified = expires::get())
+ {
+ $expires = $last_modified + $seconds;
+ $max_age = $expires - time();
+
+ if ($max_age > 0)
{
- // Re-send headers
- header('Last-Modified: '.gmdate('D, d M Y H:i:s T', $mod_time));
- header('Expires: '.gmdate('D, d M Y H:i:s T', time() + $mod_time_diff));
- header('Cache-Control: max-age='.$mod_time_diff);
- header('Status: 304 Not Modified', TRUE, 304);
+ // Content has not expired
+ header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified');
+ header('Last-Modified: '.gmdate('D, d M Y H:i:s T', $last_modified));
+
+ // HTTP 1.0
+ header('Expires: '.gmdate('D, d M Y H:i:s T', $expires));
- // Prevent any output
- Event::add('system.display', array('expires', 'prevent_output'));
+ // HTTP 1.1
+ header('Cache-Control: max-age='.$max_age);
+
+ // Clear any output
+ Event::add('system.display', create_function('', 'Kohana::$output = "";'));
- // Exit to prevent other output
exit;
}
}
- return FALSE;
+ return $last_modified;
}
/**
- * Check headers already created to not step on download or Img_lib's feet
+ * Check if expiration headers are already set
*
* @return boolean
*/
- public static function check_headers()
+ public static function headers_set()
{
foreach (headers_list() as $header)
{
- if ((session_cache_limiter() == '' AND stripos($header, 'Last-Modified:') === 0)
- OR stripos($header, 'Expires:') === 0)
+ if (strncasecmp($header, 'Expires:', 8) === 0
+ OR strncasecmp($header, 'Cache-Control:', 14) === 0
+ OR strncasecmp($header, 'Last-Modified:', 14) === 0)
{
- return FALSE;
+ return TRUE;
}
}
- return TRUE;
- }
-
- /**
- * Prevent any output from being displayed. Executed during system.display.
- *
- * @return void
- */
- public static function prevent_output()
- {
- Kohana::$output = '';
+ return FALSE;
}
-} // End expires \ No newline at end of file
+} // End expires
diff --git a/system/helpers/feed.php b/system/helpers/feed.php
index 74bb2f6b..4aab1dcd 100644
--- a/system/helpers/feed.php
+++ b/system/helpers/feed.php
@@ -2,12 +2,12 @@
/**
* Feed helper class.
*
- * $Id: feed.php 4152 2009-04-03 23:26:23Z ixmatus $
+ * $Id: feed.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
*/
class feed_Core {
diff --git a/system/helpers/file.php b/system/helpers/file.php
index b1b71740..0d4a7980 100644
--- a/system/helpers/file.php
+++ b/system/helpers/file.php
@@ -2,12 +2,12 @@
/**
* File helper class.
*
- * $Id: file.php 3769 2008-12-15 00:48:56Z zombor $
+ * $Id: file.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
*/
class file_Core {
diff --git a/system/helpers/form.php b/system/helpers/form.php
index 815eef84..901edc91 100644
--- a/system/helpers/form.php
+++ b/system/helpers/form.php
@@ -2,12 +2,12 @@
/**
* Form helper class.
*
- * $Id: form.php 4291 2009-04-29 22:51:58Z kiall $
+ * $Id: form.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
*/
class form_Core {
@@ -17,9 +17,10 @@ class form_Core {
* @param string form action attribute
* @param array extra attributes
* @param array hidden fields to be created immediately after the form tag
+ * @param string non-default protocol, eg: https
* @return string
*/
- public static function open($action = NULL, $attr = array(), $hidden = NULL)
+ public static function open($action = NULL, $attr = array(), $hidden = NULL, $protocol = NULL)
{
// Make sure that the method is always set
empty($attr['method']) and $attr['method'] = 'post';
@@ -33,12 +34,12 @@ class form_Core {
if ($action === NULL)
{
// Use the current URL as the default action
- $action = url::site(Router::$complete_uri);
+ $action = url::site(Router::$complete_uri, $protocol);
}
elseif (strpos($action, '://') === FALSE)
{
// Make the action URI into a URL
- $action = url::site($action);
+ $action = url::site($action, $protocol);
}
// Set action
@@ -70,72 +71,23 @@ class form_Core {
}
/**
- * Generates a fieldset opening tag.
+ * Creates a HTML form hidden input tag.
*
- * @param array html attributes
- * @param string a string to be attached to the end of the attributes
- * @return string
- */
- public static function open_fieldset($data = NULL, $extra = '')
- {
- return '<fieldset'.html::attributes((array) $data).' '.$extra.'>'."\n";
- }
-
- /**
- * Generates a fieldset closing tag.
- *
- * @return string
- */
- public static function close_fieldset()
- {
- return '</fieldset>'."\n";
- }
-
- /**
- * Generates a legend tag for use with a fieldset.
- *
- * @param string legend text
- * @param array HTML attributes
- * @param string a string to be attached to the end of the attributes
- * @return string
- */
- public static function legend($text = '', $data = NULL, $extra = '')
- {
- return '<legend'.form::attributes((array) $data).' '.$extra.'>'.$text.'</legend>'."\n";
- }
-
- /**
- * Generates hidden form fields.
- * You can pass a simple key/value string or an associative array with multiple values.
- *
- * @param string|array input name (string) or key/value pairs (array)
- * @param string input value, if using an input name
+ * @param string|array input name or an array of HTML attributes
+ * @param string input value, when using a name
+ * @param string a string to be attached to the end of the attributes
* @return string
*/
- public static function hidden($data, $value = '')
+ public static function hidden($data, $value = '', $extra = '')
{
if ( ! is_array($data))
{
- $data = array
- (
- $data => $value
- );
+ $data = array('name' => $data);
}
- $input = '';
- foreach ($data as $name => $value)
- {
- $attr = array
- (
- 'type' => 'hidden',
- 'name' => $name,
- 'value' => $value
- );
-
- $input .= form::input($attr)."\n";
- }
+ $data['type'] = 'hidden';
- return $input;
+ return form::input($data, $value, $extra);
}
/**
@@ -219,13 +171,23 @@ class form_Core {
$data = array('name' => $data);
}
+ if ( ! isset($data['rows']))
+ {
+ $data['rows'] = '';
+ }
+
+ if ( ! isset($data['cols']))
+ {
+ $data['cols'] = '';
+ }
+
// Use the value from $data if possible, or use $value
$value = isset($data['value']) ? $data['value'] : $value;
// Value is not part of the attributes
unset($data['value']);
- return '<textarea'.form::attributes($data, 'textarea').' '.$extra.'>'.html::specialchars($value, $double_encode).'</textarea>';
+ return '<textarea'.form::attributes($data, 'textarea').' '.$extra.'>'.htmlspecialchars($value, ENT_QUOTES, Kohana::CHARSET, $double_encode).'</textarea>';
}
/**
@@ -283,21 +245,15 @@ class form_Core {
// Inner key should always be a string
$inner_key = (string) $inner_key;
- $attr = array('value' => $inner_key);
- if (in_array($inner_key, $selected)) {
- $attr['selected'] = 'selected';
- }
- $input .= '<option '.html::attributes($attr).'>'.html::purify($inner_val).'</option>'."\n";
+ $sel = in_array($inner_key, $selected) ? ' selected="selected"' : '';
+ $input .= '<option value="'.$inner_key.'"'.$sel.'>'.htmlspecialchars($inner_val, ENT_QUOTES, Kohana::CHARSET).'</option>'."\n";
}
$input .= '</optgroup>'."\n";
}
else
{
- $attr = array('value' => $key);
- if (in_array($key, $selected)) {
- $attr['selected'] = 'selected';
- }
- $input .= '<option '.html::attributes($attr).'>'.html::purify($val).'</option>'."\n";
+ $sel = in_array($key, $selected) ? ' selected="selected"' : '';
+ $input .= '<option value="'.$key.'"'.$sel.'>'.htmlspecialchars($val, ENT_QUOTES, Kohana::CHARSET).'</option>'."\n";
}
}
$input .= '</select>';
@@ -416,20 +372,8 @@ class form_Core {
{
$value = arr::remove('value', $data);
}
- // $value must be ::purify
-
- return '<button'.form::attributes($data, 'button').' '.$extra.'>'.html::purify($value).'</button>';
- }
- /**
- * Closes an open form tag.
- *
- * @param string string to be attached after the closing tag
- * @return string
- */
- public static function close($extra = '')
- {
- return '</form>'."\n".$extra;
+ return '<button'.form::attributes($data, 'button').' '.$extra.'>'.$value.'</button>';
}
/**
@@ -462,7 +406,7 @@ class form_Core {
$text = ucwords(inflector::humanize($data['for']));
}
- return '<label'.form::attributes($data).' '.$extra.'>'.html::purify($text).'</label>';
+ return '<label'.form::attributes($data).' '.$extra.'>'.$text.'</label>';
}
/**
@@ -496,6 +440,7 @@ class form_Core {
case 'image':
case 'button':
case 'submit':
+ case 'hidden':
// Only specific types of inputs use name to id matching
$attr['id'] = $attr['name'];
break;
@@ -546,4 +491,4 @@ class form_Core {
return html::attributes(array_merge($sorted, $attr));
}
-} // End form \ No newline at end of file
+} // End form
diff --git a/system/helpers/format.php b/system/helpers/format.php
index fb8a0294..9351afda 100644
--- a/system/helpers/format.php
+++ b/system/helpers/format.php
@@ -2,16 +2,33 @@
/**
* Format helper class.
*
- * $Id: format.php 4070 2009-03-11 20:37:38Z Geert $
+ * $Id: format.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
*/
class format_Core {
/**
+ * Formats a number according to the current locale.
+ *
+ * @param float
+ * @param int|boolean number of fractional digits or TRUE to use the locale default
+ * @return string
+ */
+ public static function number($number, $decimals = 0)
+ {
+ $locale = localeconv();
+
+ if ($decimals === TRUE)
+ return number_format($number, $locale['frac_digits'], $locale['decimal_point'], $locale['thousands_sep']);
+
+ return number_format($number, $decimals, $locale['decimal_point'], $locale['thousands_sep']);
+ }
+
+ /**
* Formats a phone number according to the specified format.
*
* @param string phone number
@@ -63,4 +80,35 @@ class format_Core {
return $str;
}
+ /**
+ * Normalizes a hexadecimal HTML color value. All values will be converted
+ * to lowercase, have a "#" prepended and contain six characters.
+ *
+ * @param string hexadecimal HTML color value
+ * @return string
+ */
+ public static function color($str = '')
+ {
+ // Reject invalid values
+ if ( ! valid::color($str))
+ return '';
+
+ // Convert to lowercase
+ $str = strtolower($str);
+
+ // Prepend "#"
+ if ($str[0] !== '#')
+ {
+ $str = '#'.$str;
+ }
+
+ // Expand short notation
+ if (strlen($str) === 4)
+ {
+ $str = '#'.$str[1].$str[1].$str[2].$str[2].$str[3].$str[3];
+ }
+
+ return $str;
+ }
+
} // End format \ No newline at end of file
diff --git a/system/helpers/html.php b/system/helpers/html.php
index 2c609567..2d759ac0 100644
--- a/system/helpers/html.php
+++ b/system/helpers/html.php
@@ -2,12 +2,12 @@
/**
* HTML helper class.
*
- * $Id: html.php 4376 2009-06-01 11:40:39Z samsoir $
+ * $Id: html.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
*/
class html_Core {
@@ -21,47 +21,13 @@ class html_Core {
* @param boolean encode existing entities
* @return string
*/
- public static function specialchars($str, $double_encode = TRUE)
+ public static function chars($str, $double_encode = TRUE)
{
- // Force the string to be a string
- $str = (string) $str;
-
- // Do encode existing HTML entities (default)
- if ($double_encode === TRUE)
- {
- $str = htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
- }
- else
- {
- // Do not encode existing HTML entities
- // From PHP 5.2.3 this functionality is built-in, otherwise use a regex
- if (version_compare(PHP_VERSION, '5.2.3', '>='))
- {
- $str = htmlspecialchars($str, ENT_QUOTES, 'UTF-8', FALSE);
- }
- else
- {
- $str = preg_replace('/&(?!(?:#\d++|[a-z]++);)/ui', '&amp;', $str);
- $str = str_replace(array('<', '>', '\'', '"'), array('&lt;', '&gt;', '&#39;', '&quot;'), $str);
- }
- }
-
- return $str;
+ // Return HTML entities using the Kohana charset
+ return htmlspecialchars($str, ENT_QUOTES, Kohana::CHARSET, $double_encode);
}
/**
- * Perform a html::specialchars() with additional URL specific encoding.
- *
- * @param string string to convert
- * @param boolean encode existing entities
- * @return string
- */
- public static function specialurlencode($str, $double_encode = TRUE)
- {
- return str_replace(' ', '%20', html::specialchars($str, $double_encode));
- }
-
- /**
* Create HTML link anchors.
*
* @param string URL or URI string
@@ -98,11 +64,11 @@ class html_Core {
return
// Parsed URL
- '<a href="'.html::specialurlencode($site_url, FALSE).'"'
+ '<a href="'.htmlspecialchars($site_url, ENT_QUOTES, Kohana::CHARSET, FALSE).'"'
// Attributes empty? Use an empty string
.(is_array($attributes) ? html::attributes($attributes) : '').'>'
// Title empty? Use the parsed URL
- .($escape_title ? html::specialchars((($title === NULL) ? $site_url : $title), FALSE) : (($title === NULL) ? $site_url : $title)).'</a>';
+ .($escape_title ? htmlspecialchars((($title === NULL) ? $site_url : $title), ENT_QUOTES, Kohana::CHARSET, FALSE) : (($title === NULL) ? $site_url : $title)).'</a>';
}
/**
@@ -118,7 +84,7 @@ class html_Core {
{
return
// Base URL + URI = full URL
- '<a href="'.html::specialurlencode(url::base(FALSE, $protocol).$file, FALSE).'"'
+ '<a href="'.htmlspecialchars(url::base(FALSE, $protocol).$file, ENT_QUOTES, Kohana::CHARSET, FALSE).'"'
// Attributes empty? Use an empty string
.(is_array($attributes) ? html::attributes($attributes) : '').'>'
// Title empty? Use the filename part of the URI
@@ -126,37 +92,6 @@ class html_Core {
}
/**
- * Similar to anchor, but with the protocol parameter first.
- *
- * @param string link protocol
- * @param string URI or URL to link to
- * @param string link text
- * @param array HTML anchor attributes
- * @return string
- */
- public static function panchor($protocol, $uri, $title = NULL, $attributes = FALSE)
- {
- return html::anchor($uri, $title, $attributes, $protocol);
- }
-
- /**
- * Create an array of anchors from an array of link/title pairs.
- *
- * @param array link/title pairs
- * @return array
- */
- public static function anchor_array(array $array)
- {
- $anchors = array();
- foreach ($array as $link => $title)
- {
- // Create list of anchors
- $anchors[] = html::anchor($link, $title);
- }
- return $anchors;
- }
-
- /**
* Generates an obfuscated version of an email address.
*
* @param string email address
@@ -286,7 +221,7 @@ class html_Core {
*/
public static function stylesheet($style, $media = FALSE, $index = FALSE)
{
- return html::link($style, 'stylesheet', 'text/css', '.css', $media, $index);
+ return html::link($style, 'stylesheet', 'text/css', $media, $index);
}
/**
@@ -295,12 +230,11 @@ class html_Core {
* @param string|array filename
* @param string|array relationship
* @param string|array mimetype
- * @param string specifies suffix of the file
* @param string|array specifies on what device the document will be displayed
* @param boolean include the index_page in the link
* @return string
*/
- public static function link($href, $rel, $type, $suffix = FALSE, $media = FALSE, $index = FALSE)
+ public static function link($href, $rel, $type, $media = FALSE, $index = FALSE)
{
$compiled = '';
@@ -312,7 +246,7 @@ class html_Core {
$_type = is_array($type) ? array_shift($type) : $type;
$_media = is_array($media) ? array_shift($media) : $media;
- $compiled .= html::link($_href, $_rel, $_type, $suffix, $_media, $index);
+ $compiled .= html::link($_href, $_rel, $_type, $_media, $index);
}
}
else
@@ -323,14 +257,6 @@ class html_Core {
$href = url::base($index).$href;
}
- $length = strlen($suffix);
-
- if ( $length > 0 AND substr_compare($href, $suffix, -$length, $length, FALSE) !== 0)
- {
- // Add the defined suffix
- $href .= $suffix;
- }
-
$attr = array
(
'rel' => $rel,
@@ -376,12 +302,6 @@ class html_Core {
$script = url::base((bool) $index).$script;
}
- if (substr_compare($script, '.js', -3, 3, FALSE) !== 0)
- {
- // Add the javascript suffix
- $script .= '.js';
- }
-
$compiled = '<script type="text/javascript" src="'.$script.'"></script>';
}
@@ -437,7 +357,7 @@ class html_Core {
$compiled = '';
foreach ($attrs as $key => $val)
{
- $compiled .= ' '.$key.'="'.html::specialchars($val).'"';
+ $compiled .= ' '.$key.'="'.htmlspecialchars($val, ENT_QUOTES, Kohana::CHARSET).'"';
}
return $compiled;
diff --git a/system/helpers/inflector.php b/system/helpers/inflector.php
index 1e4fee23..9bd281db 100644
--- a/system/helpers/inflector.php
+++ b/system/helpers/inflector.php
@@ -2,12 +2,12 @@
/**
* Inflector helper class.
*
- * $Id: inflector.php 4072 2009-03-13 17:20:38Z jheathco $
+ * $Id: inflector.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
*/
class inflector_Core {
@@ -45,7 +45,27 @@ class inflector_Core {
* @param integer number of things
* @return string
*/
- public static function singular($str, $count = NULL)
+ public static function singular($str, $count = NULL) {
+ $parts = explode('_', $str);
+
+ $last = inflector::_singular(array_pop($parts), $count);
+
+ $pre = implode('_', $parts);
+ if (strlen($pre))
+ $pre .= '_';
+
+ return $pre.$last;
+ }
+
+
+ /**
+ * Makes a plural word singular.
+ *
+ * @param string word to singularize
+ * @param integer number of things
+ * @return string
+ */
+ public static function _singular($str, $count = NULL)
{
// Remove garbage
$str = strtolower(trim($str));
@@ -104,6 +124,29 @@ class inflector_Core {
*/
public static function plural($str, $count = NULL)
{
+ if ( ! $str)
+ return $str;
+
+ $parts = explode('_', $str);
+
+ $last = inflector::_plural(array_pop($parts), $count);
+
+ $pre = implode('_', $parts);
+ if (strlen($pre))
+ $pre .= '_';
+
+ return $pre.$last;
+ }
+
+
+ /**
+ * Makes a singular word plural.
+ *
+ * @param string word to pluralize
+ * @return string
+ */
+ public static function _plural($str, $count = NULL)
+ {
// Remove garbage
$str = strtolower(trim($str));
@@ -155,6 +198,24 @@ class inflector_Core {
}
/**
+ * Makes a word possessive.
+ *
+ * @param string word to to make possessive
+ * @return string
+ */
+ public static function possessive($string)
+ {
+ $length = strlen($string);
+
+ if (substr($string, $length - 1, $length) == 's')
+ {
+ return $string.'\'';
+ }
+
+ return $string.'\'s';
+ }
+
+ /**
* Makes a phrase camel case.
*
* @param string phrase to camelize
@@ -176,7 +237,7 @@ class inflector_Core {
*/
public static function underscore($str)
{
- return preg_replace('/\s+/', '_', trim($str));
+ return trim(preg_replace('/[\s_]+/', '_', $str), '_');
}
/**
@@ -187,7 +248,7 @@ class inflector_Core {
*/
public static function humanize($str)
{
- return preg_replace('/[_-]+/', ' ', trim($str));
+ return trim(preg_replace('/[_-\s]+/', ' ', $str));
}
} // End inflector \ No newline at end of file
diff --git a/system/helpers/num.php b/system/helpers/num.php
index 3eb5d5ac..42f13bec 100644
--- a/system/helpers/num.php
+++ b/system/helpers/num.php
@@ -2,12 +2,12 @@
/**
* Number helper class.
*
- * $Id: num.php 3769 2008-12-15 00:48:56Z zombor $
+ * $Id: num.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
*/
class num_Core {
diff --git a/system/helpers/remote.php b/system/helpers/remote.php
index f9e0267f..37995cdb 100644
--- a/system/helpers/remote.php
+++ b/system/helpers/remote.php
@@ -2,12 +2,12 @@
/**
* Remote url/file helper.
*
- * $Id: remote.php 3769 2008-12-15 00:48:56Z zombor $
+ * $Id: remote.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
*/
class remote_Core {
@@ -35,7 +35,7 @@ class remote_Core {
$CRLF = "\r\n";
// Send request
- fwrite($remote, 'HEAD '.$url['path'].' HTTP/1.0'.$CRLF);
+ fwrite($remote, 'HEAD '.$url['path'].(isset($url['query']) ? '?'.$url['query'] : '').' HTTP/1.0'.$CRLF);
fwrite($remote, 'Host: '.$url['host'].$CRLF);
fwrite($remote, 'Connection: close'.$CRLF);
fwrite($remote, 'User-Agent: Kohana Framework (+http://kohanaphp.com/)'.$CRLF);
@@ -63,4 +63,4 @@ class remote_Core {
return isset($response) ? $response : FALSE;
}
-} // End remote \ No newline at end of file
+} // End remote
diff --git a/system/helpers/request.php b/system/helpers/request.php
index 4203d0e5..4770d64b 100644
--- a/system/helpers/request.php
+++ b/system/helpers/request.php
@@ -2,35 +2,48 @@
/**
* Request helper class.
*
- * $Id: request.php 4355 2009-05-15 17:18:28Z kiall $
+ * $Id: request.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
*/
class request_Core {
// Possible HTTP methods
protected static $http_methods = array('get', 'head', 'options', 'post', 'put', 'delete');
- // Content types from client's HTTP Accept request header (array)
+ // Character sets from client's HTTP Accept-Charset request header
+ protected static $accept_charsets;
+
+ // Content codings from client's HTTP Accept-Encoding request header
+ protected static $accept_encodings;
+
+ // Language tags from client's HTTP Accept-Language request header
+ protected static $accept_languages;
+
+ // Content types from client's HTTP Accept request header
protected static $accept_types;
+ // The current user agent and its parsed attributes
+ protected static $user_agent;
+
/**
* Returns the HTTP referrer, or the default if the referrer is not set.
*
* @param mixed default to return
+ * @param bool Remove base URL
* @return string
*/
- public static function referrer($default = FALSE)
+ public static function referrer($default = FALSE, $remove_base = FALSE)
{
if ( ! empty($_SERVER['HTTP_REFERER']))
{
// Set referrer
$ref = $_SERVER['HTTP_REFERER'];
- if (strpos($ref, url::base(FALSE)) === 0)
+ if ($remove_base === TRUE AND (strpos($ref, url::base(FALSE)) === 0))
{
// Remove the base URL from the referrer
$ref = substr($ref, strlen(url::base(FALSE)));
@@ -84,10 +97,59 @@ class request_Core {
$method = strtolower($_SERVER['REQUEST_METHOD']);
if ( ! in_array($method, request::$http_methods))
- throw new Kohana_Exception('request.unknown_method', $method);
+ throw new Kohana_Exception('Invalid request method :method:', array(':method:' => $method));
return $method;
- }
+ }
+
+ /**
+ * Retrieves current user agent information
+ * keys: browser, version, platform, mobile, robot
+ *
+ * @param string key
+ * @return mixed NULL or the parsed value
+ */
+ public static function user_agent($key = 'agent')
+ {
+ // Retrieve raw user agent without parsing
+ if ($key === 'agent')
+ {
+ if (request::$user_agent === NULL)
+ return request::$user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? trim($_SERVER['HTTP_USER_AGENT']) : '';
+
+ if (is_array(request::$user_agent))
+ return request::$user_agent['agent'];
+
+ return request::$user_agent;
+ }
+
+ if ( ! is_array(request::$user_agent))
+ {
+ request::$user_agent['agent'] = isset($_SERVER['HTTP_USER_AGENT']) ? trim($_SERVER['HTTP_USER_AGENT']) : '';
+
+ // Parse the user agent and extract basic information
+ foreach (Kohana::config('user_agents') as $type => $data)
+ {
+ foreach ($data as $fragment => $name)
+ {
+ if (stripos(request::$user_agent['agent'], $fragment) !== FALSE)
+ {
+ if ($type === 'browser' AND preg_match('|'.preg_quote($fragment).'[^0-9.]*+([0-9.][0-9.a-z]*)|i', request::$user_agent['agent'], $match))
+ {
+ // Set the browser version
+ request::$user_agent['version'] = $match[1];
+ }
+
+ // Set the agent name
+ request::$user_agent[$type] = $name;
+ break;
+ }
+ }
+ }
+ }
+
+ return isset(request::$user_agent[$key]) ? request::$user_agent[$key] : NULL;
+ }
/**
* Returns boolean of whether client accepts content type.
@@ -98,7 +160,7 @@ class request_Core {
*/
public static function accepts($type = NULL, $explicit_check = FALSE)
{
- request::parse_accept_header();
+ request::parse_accept_content_header();
if ($type === NULL)
return request::$accept_types;
@@ -107,6 +169,56 @@ class request_Core {
}
/**
+ * Returns boolean indicating if the client accepts a charset
+ *
+ * @param string
+ * @return boolean
+ */
+ public static function accepts_charset($charset = NULL)
+ {
+ request::parse_accept_charset_header();
+
+ if ($charset === NULL)
+ return request::$accept_charsets;
+
+ return (request::accepts_charset_at_quality($charset) > 0);
+ }
+
+ /**
+ * Returns boolean indicating if the client accepts an encoding
+ *
+ * @param string
+ * @param boolean set to TRUE to disable wildcard checking
+ * @return boolean
+ */
+ public static function accepts_encoding($encoding = NULL, $explicit_check = FALSE)
+ {
+ request::parse_accept_encoding_header();
+
+ if ($encoding === NULL)
+ return request::$accept_encodings;
+
+ return (request::accepts_encoding_at_quality($encoding, $explicit_check) > 0);
+ }
+
+ /**
+ * Returns boolean indicating if the client accepts a language tag
+ *
+ * @param string language tag
+ * @param boolean set to TRUE to disable prefix and wildcard checking
+ * @return boolean
+ */
+ public static function accepts_language($tag = NULL, $explicit_check = FALSE)
+ {
+ request::parse_accept_language_header();
+
+ if ($tag === NULL)
+ return request::$accept_languages;
+
+ return (request::accepts_language_at_quality($tag, $explicit_check) > 0);
+ }
+
+ /**
* Compare the q values for given array of content types and return the one with the highest value.
* If items are found to have the same q value, the first one encountered in the given array wins.
* If all items in the given array have a q value of 0, FALSE is returned.
@@ -117,24 +229,103 @@ class request_Core {
*/
public static function preferred_accept($types, $explicit_check = FALSE)
{
- // Initialize
- $mime_types = array();
$max_q = 0;
$preferred = FALSE;
- // Load q values for all given content types
- foreach (array_unique($types) as $type)
+ foreach ($types as $type)
+ {
+ $q = request::accepts_at_quality($type, $explicit_check);
+
+ if ($q > $max_q)
+ {
+ $max_q = $q;
+ $preferred = $type;
+ }
+ }
+
+ return $preferred;
+ }
+
+ /**
+ * Compare the q values for a given array of character sets and return the
+ * one with the highest value. If items are found to have the same q value,
+ * the first one encountered takes precedence. If all items in the given
+ * array have a q value of 0, FALSE is returned.
+ *
+ * @param array character sets
+ * @return mixed
+ */
+ public static function preferred_charset($charsets)
+ {
+ $max_q = 0;
+ $preferred = FALSE;
+
+ foreach ($charsets as $charset)
+ {
+ $q = request::accepts_charset_at_quality($charset);
+
+ if ($q > $max_q)
+ {
+ $max_q = $q;
+ $preferred = $charset;
+ }
+ }
+
+ return $preferred;
+ }
+
+ /**
+ * Compare the q values for a given array of encodings and return the one with
+ * the highest value. If items are found to have the same q value, the first
+ * one encountered takes precedence. If all items in the given array have
+ * a q value of 0, FALSE is returned.
+ *
+ * @param array encodings
+ * @param boolean set to TRUE to disable wildcard checking
+ * @return mixed
+ */
+ public static function preferred_encoding($encodings, $explicit_check = FALSE)
+ {
+ $max_q = 0;
+ $preferred = FALSE;
+
+ foreach ($encodings as $encoding)
{
- $mime_types[$type] = request::accepts_at_quality($type, $explicit_check);
+ $q = request::accepts_encoding_at_quality($encoding, $explicit_check);
+
+ if ($q > $max_q)
+ {
+ $max_q = $q;
+ $preferred = $encoding;
+ }
}
- // Look for the highest q value
- foreach ($mime_types as $type => $q)
+ return $preferred;
+ }
+
+ /**
+ * Compare the q values for a given array of language tags and return the
+ * one with the highest value. If items are found to have the same q value,
+ * the first one encountered takes precedence. If all items in the given
+ * array have a q value of 0, FALSE is returned.
+ *
+ * @param array language tags
+ * @param boolean set to TRUE to disable prefix and wildcard checking
+ * @return mixed
+ */
+ public static function preferred_language($tags, $explicit_check = FALSE)
+ {
+ $max_q = 0;
+ $preferred = FALSE;
+
+ foreach ($tags as $tag)
{
+ $q = request::accepts_language_at_quality($tag, $explicit_check);
+
if ($q > $max_q)
{
$max_q = $q;
- $preferred = $type;
+ $preferred = $tag;
}
}
@@ -142,18 +333,18 @@ class request_Core {
}
/**
- * Returns quality factor at which the client accepts content type.
+ * Returns quality factor at which the client accepts content type
*
* @param string content type (e.g. "image/jpg", "jpg")
* @param boolean set to TRUE to disable wildcard checking
* @return integer|float
*/
- public static function accepts_at_quality($type = NULL, $explicit_check = FALSE)
+ public static function accepts_at_quality($type, $explicit_check = FALSE)
{
- request::parse_accept_header();
+ request::parse_accept_content_header();
// Normalize type
- $type = strtolower((string) $type);
+ $type = strtolower($type);
// General content type (e.g. "jpg")
if (strpos($type, '/') === FALSE)
@@ -178,62 +369,251 @@ class request_Core {
if (isset(request::$accept_types[$type[0]][$type[1]]))
return request::$accept_types[$type[0]][$type[1]];
- // Wildcard match (if not checking explicitly)
- if ($explicit_check === FALSE AND isset(request::$accept_types[$type[0]]['*']))
- return request::$accept_types[$type[0]]['*'];
+ if ($explicit_check === FALSE)
+ {
+ // Wildcard match
+ if (isset(request::$accept_types[$type[0]]['*']))
+ return request::$accept_types[$type[0]]['*'];
- // Catch-all wildcard match (if not checking explicitly)
- if ($explicit_check === FALSE AND isset(request::$accept_types['*']['*']))
- return request::$accept_types['*']['*'];
+ // Catch-all wildcard match
+ if (isset(request::$accept_types['*']['*']))
+ return request::$accept_types['*']['*'];
+ }
// Content type not accepted
return 0;
}
/**
- * Parses client's HTTP Accept request header, and builds array structure representing it.
+ * Returns quality factor at which the client accepts a charset
+ *
+ * @param string charset (e.g., "ISO-8859-1", "utf-8")
+ * @return integer|float
+ */
+ public static function accepts_charset_at_quality($charset)
+ {
+ request::parse_accept_charset_header();
+
+ // Normalize charset
+ $charset = strtolower($charset);
+
+ // Exact match
+ if (isset(request::$accept_charsets[$charset]))
+ return request::$accept_charsets[$charset];
+
+ if (isset(request::$accept_charsets['*']))
+ return request::$accept_charsets['*'];
+
+ if ($charset === 'iso-8859-1')
+ return 1;
+
+ return 0;
+ }
+
+ /**
+ * Returns quality factor at which the client accepts an encoding
+ *
+ * @param string encoding (e.g., "gzip", "deflate")
+ * @param boolean set to TRUE to disable wildcard checking
+ * @return integer|float
+ */
+ public static function accepts_encoding_at_quality($encoding, $explicit_check = FALSE)
+ {
+ request::parse_accept_encoding_header();
+
+ // Normalize encoding
+ $encoding = strtolower($encoding);
+
+ // Exact match
+ if (isset(request::$accept_encodings[$encoding]))
+ return request::$accept_encodings[$encoding];
+
+ if ($explicit_check === FALSE)
+ {
+ if (isset(request::$accept_encodings['*']))
+ return request::$accept_encodings['*'];
+
+ if ($encoding === 'identity')
+ return 1;
+ }
+
+ return 0;
+ }
+
+ /**
+ * Returns quality factor at which the client accepts a language
+ *
+ * @param string tag (e.g., "en", "en-us", "fr-ca")
+ * @param boolean set to TRUE to disable prefix and wildcard checking
+ * @return integer|float
+ */
+ public static function accepts_language_at_quality($tag, $explicit_check = FALSE)
+ {
+ request::parse_accept_language_header();
+
+ $tag = explode('-', strtolower($tag), 2);
+
+ if (isset(request::$accept_languages[$tag[0]]))
+ {
+ if (isset($tag[1]))
+ {
+ // Exact match
+ if (isset(request::$accept_languages[$tag[0]][$tag[1]]))
+ return request::$accept_languages[$tag[0]][$tag[1]];
+
+ // A prefix matches
+ if ($explicit_check === FALSE AND isset(request::$accept_languages[$tag[0]]['*']))
+ return request::$accept_languages[$tag[0]]['*'];
+ }
+ else
+ {
+ // No subtags
+ if (isset(request::$accept_languages[$tag[0]]['*']))
+ return request::$accept_languages[$tag[0]]['*'];
+ }
+ }
+
+ if ($explicit_check === FALSE AND isset(request::$accept_languages['*']))
+ return request::$accept_languages['*'];
+
+ return 0;
+ }
+
+ /**
+ * Parses a HTTP Accept or Accept-* header for q values
*
- * @return void
+ * @param string header data
+ * @return array
+ */
+ protected static function parse_accept_header($header)
+ {
+ $result = array();
+
+ // Remove linebreaks and parse the HTTP Accept header
+ foreach (explode(',', str_replace(array("\r", "\n"), '', strtolower($header))) as $entry)
+ {
+ // Explode each entry in content type and possible quality factor
+ $entry = explode(';', trim($entry), 2);
+
+ $q = (isset($entry[1]) AND preg_match('~\bq\s*+=\s*+([.0-9]+)~', $entry[1], $match)) ? (float) $match[1] : 1;
+
+ // Overwrite entries with a smaller q value
+ if ( ! isset($result[$entry[0]]) OR $q > $result[$entry[0]])
+ {
+ $result[$entry[0]] = $q;
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * Parses a client's HTTP Accept-Charset header
*/
- protected static function parse_accept_header()
+ protected static function parse_accept_charset_header()
{
// Run this function just once
- if (request::$accept_types !== NULL)
+ if (request::$accept_charsets !== NULL)
return;
- // Initialize accept_types array
- request::$accept_types = array();
+ // No HTTP Accept-Charset header found
+ if (empty($_SERVER['HTTP_ACCEPT_CHARSET']))
+ {
+ // Accept everything
+ request::$accept_charsets['*'] = 1;
+ }
+ else
+ {
+ request::$accept_charsets = request::parse_accept_header($_SERVER['HTTP_ACCEPT_CHARSET']);
+ }
+ }
+
+ /**
+ * Parses a client's HTTP Accept header
+ */
+ protected static function parse_accept_content_header()
+ {
+ // Run this function just once
+ if (request::$accept_types !== NULL)
+ return;
// No HTTP Accept header found
if (empty($_SERVER['HTTP_ACCEPT']))
{
// Accept everything
request::$accept_types['*']['*'] = 1;
- return;
}
-
- // Remove linebreaks and parse the HTTP Accept header
- foreach (explode(',', str_replace(array("\r", "\n"), '', $_SERVER['HTTP_ACCEPT'])) as $accept_entry)
+ else
{
- // Explode each entry in content type and possible quality factor
- $accept_entry = explode(';', trim($accept_entry), 2);
+ request::$accept_types = array();
+
+ foreach (request::parse_accept_header($_SERVER['HTTP_ACCEPT']) as $type => $q)
+ {
+ // Explode each content type (e.g. "text/html")
+ $type = explode('/', $type, 2);
+
+ // Skip invalid content types
+ if ( ! isset($type[1]))
+ continue;
+
+ request::$accept_types[$type[0]][$type[1]] = $q;
+ }
+ }
+ }
+
+ /**
+ * Parses a client's HTTP Accept-Encoding header
+ */
+ protected static function parse_accept_encoding_header()
+ {
+ // Run this function just once
+ if (request::$accept_encodings !== NULL)
+ return;
- // Explode each content type (e.g. "text/html")
- $type = explode('/', $accept_entry[0], 2);
+ // No HTTP Accept-Encoding header found
+ if ( ! isset($_SERVER['HTTP_ACCEPT_ENCODING']))
+ {
+ // Accept everything
+ request::$accept_encodings['*'] = 1;
+ }
+ elseif ($_SERVER['HTTP_ACCEPT_ENCODING'] === '')
+ {
+ // Accept only identity
+ request::$accept_encodings['identity'] = 1;
+ }
+ else
+ {
+ request::$accept_encodings = request::parse_accept_header($_SERVER['HTTP_ACCEPT_ENCODING']);
+ }
+ }
- // Skip invalid content types
- if ( ! isset($type[1]))
- continue;
+ /**
+ * Parses a client's HTTP Accept-Language header
+ */
+ protected static function parse_accept_language_header()
+ {
+ // Run this function just once
+ if (request::$accept_languages !== NULL)
+ return;
- // Assume a default quality factor of 1 if no custom q value found
- $q = (isset($accept_entry[1]) AND preg_match('~\bq\s*+=\s*+([.0-9]+)~', $accept_entry[1], $match)) ? (float) $match[1] : 1;
+ // No HTTP Accept-Language header found
+ if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE']))
+ {
+ // Accept everything
+ request::$accept_languages['*'] = 1;
+ }
+ else
+ {
+ request::$accept_languages = array();
- // Populate accept_types array
- if ( ! isset(request::$accept_types[$type[0]][$type[1]]) OR $q > request::$accept_types[$type[0]][$type[1]])
+ foreach (request::parse_accept_header($_SERVER['HTTP_ACCEPT_LANGUAGE']) as $tag => $q)
{
- request::$accept_types[$type[0]][$type[1]] = $q;
+ // Explode each language (e.g. "en-us")
+ $tag = explode('-', $tag, 2);
+
+ request::$accept_languages[$tag[0]][isset($tag[1]) ? $tag[1] : '*'] = $q;
}
}
}
-} // End request \ No newline at end of file
+} // End request
diff --git a/system/helpers/security.php b/system/helpers/security.php
index cd48d2e0..9eb82a58 100644
--- a/system/helpers/security.php
+++ b/system/helpers/security.php
@@ -2,12 +2,12 @@
/**
* Security helper class.
*
- * $Id: security.php 3769 2008-12-15 00:48:56Z zombor $
+ * $Id: security.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
*/
class security_Core {
@@ -15,11 +15,12 @@ class security_Core {
* Sanitize a string with the xss_clean method.
*
* @param string string to sanitize
+ * @param string xss_clean method to use ('htmlpurifier' or defaults to built-in method)
* @return string
*/
- public static function xss_clean($str)
+ public static function xss_clean($str, $tool = NULL)
{
- return Input::instance()->xss_clean($str);
+ return Input::instance()->xss_clean($str, $tool);
}
/**
diff --git a/system/helpers/text.php b/system/helpers/text.php
index d0e573ec..66bcd243 100644
--- a/system/helpers/text.php
+++ b/system/helpers/text.php
@@ -2,12 +2,12 @@
/**
* Text helper class.
*
- * $Id: text.php 3769 2008-12-15 00:48:56Z zombor $
+ * $Id: text.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
*/
class text_Core {
@@ -52,7 +52,7 @@ class text_Core {
$limit = (int) $limit;
- if (trim($str) === '' OR utf8::strlen($str) <= $limit)
+ if (trim($str) === '' OR mb_strlen($str) <= $limit)
return $str;
if ($limit <= 0)
@@ -60,7 +60,7 @@ class text_Core {
if ($preserve_words == FALSE)
{
- return rtrim(utf8::substr($str, 0, $limit)).$end_char;
+ return rtrim(mb_substr($str, 0, $limit)).$end_char;
}
preg_match('/^.{'.($limit - 1).'}\S*/us', $str, $matches);
@@ -128,7 +128,7 @@ class text_Core {
break;
default:
$pool = (string) $type;
- $utf8 = ! utf8::is_ascii($pool);
+ $utf8 = ! text::is_ascii($pool);
break;
}
@@ -183,7 +183,7 @@ class text_Core {
* @param boolean replace words across word boundries (space, period, etc)
* @return string
*/
- public static function censor($str, $badwords, $replacement = '#', $replace_partial_words = FALSE)
+ public static function censor($str, $badwords, $replacement = '#', $replace_partial_words = TRUE)
{
foreach ((array) $badwords as $key => $badword)
{
@@ -192,7 +192,7 @@ class text_Core {
$regex = '('.implode('|', $badwords).')';
- if ($replace_partial_words == TRUE)
+ if ($replace_partial_words === FALSE)
{
// Just using \b isn't sufficient when we need to replace a badword that already contains word boundaries itself
$regex = '(?<=\b|\s|^)'.$regex.'(?=\b|\s|$)';
@@ -200,10 +200,10 @@ class text_Core {
$regex = '!'.$regex.'!ui';
- if (utf8::strlen($replacement) == 1)
+ if (mb_strlen($replacement) == 1)
{
$regex .= 'e';
- return preg_replace($regex, 'str_repeat($replacement, utf8::strlen(\'$1\'))', $str);
+ return preg_replace($regex, 'str_repeat($replacement, mb_strlen(\'$1\'))', $str);
}
return preg_replace($regex, $replacement, $str);
@@ -235,15 +235,59 @@ class text_Core {
}
/**
- * Converts text email addresses and anchors into links.
+ * An alternative to the php levenshtein() function that work out the
+ * distance between 2 words using the Damerau–Levenshtein algorithm.
+ * Credit: http://forums.devnetwork.net/viewtopic.php?f=50&t=89094
*
- * @param string text to auto link
- * @return string
+ * @see http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance
+ * @param string first word
+ * @param string second word
+ * @return int distance between words
*/
- public static function auto_link($text)
+ public static function distance($string1, $string2)
{
- // Auto link emails first to prevent problems with "www.domain.com@example.com"
- return text::auto_link_urls(text::auto_link_emails($text));
+ $string1_length = strlen($string1);
+ $string2_length = strlen($string2);
+
+ // Here we start building the table of values
+ $matrix = array();
+
+ // String1 length + 1 = rows.
+ for ($i = 0; $i <= $string1_length; ++$i)
+ {
+ $matrix[$i][0] = $i;
+ }
+
+ // String2 length + 1 columns.
+ for ($j = 0; $j <= $string2_length; ++$j)
+ {
+ $matrix[0][$j] = $j;
+ }
+
+ for ($i = 1; $i <= $string1_length; ++$i)
+ {
+ for ($j = 1; $j <= $string2_length; ++$j)
+ {
+ $cost = substr($string1, $i - 1, 1) == substr($string2, $j - 1, 1) ? 0 : 1;
+
+ $matrix[$i][$j] = min(
+ $matrix[$i - 1][$j] + 1, // deletion
+ $matrix[$i][$j - 1] + 1, // insertion
+ $matrix[$i - 1][$j - 1] + $cost // substitution
+ );
+
+ if ($i > 1 && $j > 1 && (substr($string1, $i - 1, 1) == substr($string2, $j - 2, 1))
+ && (substr($string1, $i - 2, 1) == substr($string2, $j - 1, 1)))
+ {
+ $matrix[$i][$j] = min(
+ $matrix[$i][$j],
+ $matrix[$i - 2][$j - 2] + $cost // transposition
+ );
+ }
+ }
+ }
+
+ return $matrix[$string1_length][$string2_length];
}
/**
@@ -304,9 +348,10 @@ class text_Core {
* Automatically applies <p> and <br /> markup to text. Basically nl2br() on steroids.
*
* @param string subject
+ * @param boolean convert single linebreaks to <br />
* @return string
*/
- public static function auto_p($str)
+ public static function auto_p($str, $br = TRUE)
{
// Trim whitespace
if (($str = trim($str)) === '')
@@ -343,7 +388,10 @@ class text_Core {
}
// Convert single linebreaks to <br />
- $str = preg_replace('~(?<!\n)\n(?!\n)~', "<br />\n", $str);
+ if ($br === TRUE)
+ {
+ $str = preg_replace('~(?<!\n)\n(?!\n)~', "<br />\n", $str);
+ }
return $str;
}
@@ -368,13 +416,13 @@ class text_Core {
// IEC prefixes (binary)
if ($si == FALSE OR strpos($force_unit, 'i') !== FALSE)
{
- $units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
+ $units = array(__('B'), __('KiB'), __('MiB'), __('GiB'), __('TiB'), __('PiB'));
$mod = 1024;
}
// SI prefixes (decimal)
else
{
- $units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB');
+ $units = array(__('B'), __('kB'), __('MB'), __('GB'), __('TB'), __('PB'));
$mod = 1000;
}
@@ -407,4 +455,134 @@ class text_Core {
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.
+ *
+ * @see http://sourceforge.net/projects/phputf8/
+ * @copyright (c) 2007-2009 Kohana Team
+ * @copyright (c) 2005 Harry Fuecks
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
+ *
+ * @param string string to check
+ * @return bool
+ */
+ public static function is_ascii($str)
+ {
+ return is_string($str) AND ! preg_match('/[^\x00-\x7F]/S', $str);
+ }
+
+ /**
+ * Strips out device control codes in the ASCII range.
+ *
+ * @see http://sourceforge.net/projects/phputf8/
+ * @copyright (c) 2007-2009 Kohana Team
+ * @copyright (c) 2005 Harry Fuecks
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
+ *
+ * @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.
+ *
+ * @see http://sourceforge.net/projects/phputf8/
+ * @copyright (c) 2007-2009 Kohana Team
+ * @copyright (c) 2005 Harry Fuecks
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
+ *
+ * @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 <andi@splitbrain.org>
+ * @see http://sourceforge.net/projects/phputf8/
+ * @copyright (c) 2007-2009 Kohana Team
+ * @copyright (c) 2005 Harry Fuecks
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
+ *
+ * @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)
+ {
+ static $UTF8_LOWER_ACCENTS = NULL;
+ static $UTF8_UPPER_ACCENTS = NULL;
+
+ if ($case <= 0)
+ {
+ if ($UTF8_LOWER_ACCENTS === NULL)
+ {
+ $UTF8_LOWER_ACCENTS = array(
+ 'à' => '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', 'ı' => 'i',
+ );
+ }
+
+ $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', 'İ' => 'I',
+ );
+ }
+
+ $str = str_replace(
+ array_keys($UTF8_UPPER_ACCENTS),
+ array_values($UTF8_UPPER_ACCENTS),
+ $str
+ );
+ }
+
+ return $str;
+ }
+
} // End text \ No newline at end of file
diff --git a/system/helpers/upload.php b/system/helpers/upload.php
index 422e9e8d..3aec2ac4 100644
--- a/system/helpers/upload.php
+++ b/system/helpers/upload.php
@@ -3,12 +3,12 @@
* Upload helper class for working with the global $_FILES
* array and Validation library.
*
- * $Id: upload.php 3769 2008-12-15 00:48:56Z zombor $
+ * $Id: upload.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
*/
class upload_Core {
@@ -54,7 +54,7 @@ class upload_Core {
}
if ( ! is_writable($directory))
- throw new Kohana_Exception('upload.not_writable', $directory);
+ throw new Kohana_Exception('The upload destination folder, :dir:, does not appear to be writable.', array(':dir:' => $directory));
if (is_uploaded_file($file['tmp_name']) AND move_uploaded_file($file['tmp_name'], $filename = $directory.$filename))
{
@@ -118,11 +118,8 @@ class upload_Core {
// Get the default extension of the file
$extension = strtolower(substr(strrchr($file['name'], '.'), 1));
- // Get the mime types for the extension
- $mime_types = Kohana::config('mimes.'.$extension);
-
- // Make sure there is an extension, that the extension is allowed, and that mime types exist
- return ( ! empty($extension) AND in_array($extension, $allowed_types) AND is_array($mime_types));
+ // Make sure there is an extension and that the extension is allowed
+ return ( ! empty($extension) AND in_array($extension, $allowed_types));
}
/**
diff --git a/system/helpers/url.php b/system/helpers/url.php
index 56f6db4b..6c2a6c66 100644
--- a/system/helpers/url.php
+++ b/system/helpers/url.php
@@ -2,12 +2,12 @@
/**
* URL helper class.
*
- * $Id: url.php 4479 2009-07-23 04:51:22Z ixmatus $
+ * $Id: url.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
*/
class url_Core {
@@ -15,7 +15,7 @@ class url_Core {
* Fetches the current URI.
*
* @param boolean include the query string
- * @param boolean include the suffix
+ * @param boolean include the suffix
* @return string
*/
public static function current($qs = FALSE, $suffix = FALSE)
@@ -167,7 +167,7 @@ class url_Core {
$separator = ($separator === '-') ? '-' : '_';
// Replace accented characters by their unaccented equivalents
- $title = utf8::transliterate_to_ascii($title);
+ $title = text::transliterate_to_ascii($title);
// Remove all characters that are not the separator, a-z, 0-9, or whitespace
$title = preg_replace('/[^'.$separator.'a-z0-9\s]+/', '', strtolower($title));
diff --git a/system/helpers/utf8.php b/system/helpers/utf8.php
new file mode 100644
index 00000000..20c6878c
--- /dev/null
+++ b/system/helpers/utf8.php
@@ -0,0 +1,746 @@
+<?php defined('SYSPATH') OR die('No direct access allowed.');
+/**
+ * A port of phputf8 to a unified file/class.
+ *
+ * This file is licensed differently from the rest of Kohana. As a port of
+ * phputf8, which is LGPL software, this file is released under the LGPL.
+ *
+ * PCRE needs to be compiled with UTF-8 support (--enable-utf8).
+ * Support for Unicode properties is highly recommended (--enable-unicode-properties).
+ * @see http://php.net/manual/reference.pcre.pattern.modifiers.php
+ *
+ * string functions.
+ * @see http://php.net/mbstring
+ *
+ * $Id$
+ *
+ * @package Core
+ * @author Kohana Team
+ * @copyright (c) 2007-2009 Kohana Team
+ * @copyright (c) 2005 Harry Fuecks
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
+ */
+
+class utf8 {
+
+ /**
+ * Replaces text within a portion of a UTF-8 string.
+ * @see http://php.net/substr_replace
+ *
+ * @author Harry Fuecks <hfuecks@gmail.com>
+ *
+ * @param string input string
+ * @param string replacement string
+ * @param integer offset
+ * @return string
+ */
+ public static function substr_replace($str, $replacement, $offset, $length = NULL)
+ {
+ if (text::is_ascii($str))
+ return ($length === NULL) ? substr_replace($str, $replacement, $offset) : substr_replace($str, $replacement, $offset, $length);
+
+ $length = ($length === NULL) ? mb_strlen($str) : (int) $length;
+ preg_match_all('/./us', $str, $str_array);
+ preg_match_all('/./us', $replacement, $replacement_array);
+
+ array_splice($str_array[0], $offset, $length, $replacement_array[0]);
+ return implode('', $str_array[0]);
+ }
+
+ /**
+ * Makes a UTF-8 string's first character uppercase.
+ * @see http://php.net/ucfirst
+ *
+ * @author Harry Fuecks <hfuecks@gmail.com>
+ *
+ * @param string mixed case string
+ * @return string
+ */
+ public static function ucfirst($str)
+ {
+ if (text::is_ascii($str))
+ return ucfirst($str);
+
+ preg_match('/^(.?)(.*)$/us', $str, $matches);
+ return mb_strtoupper($matches[1]).$matches[2];
+ }
+
+ /**
+ * Case-insensitive UTF-8 string comparison.
+ * @see http://php.net/strcasecmp
+ *
+ * @author Harry Fuecks <hfuecks@gmail.com>
+ *
+ * @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 (text::is_ascii($str1) AND text::is_ascii($str2))
+ return strcasecmp($str1, $str2);
+
+ $str1 = mb_strtolower($str1);
+ $str2 = mb_strtolower($str2);
+ return strcmp($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 <hfuecks@gmail.com
+ *
+ * @param string|array text to replace
+ * @param string|array replacement text
+ * @param string|array subject text
+ * @param integer number of matched and replaced needles will be returned via this parameter which is passed by reference
+ * @return string if the input was a string
+ * @return array if the input was an array
+ */
+ public static function str_ireplace($search, $replace, $str, & $count = NULL)
+ {
+ if (text::is_ascii($search) AND text::is_ascii($replace) AND text::is_ascii($str))
+ return str_ireplace($search, $replace, $str, $count);
+
+ if (is_array($str))
+ {
+ foreach ($str as $key => $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 = mb_strtolower($search);
+ $str_lower = mb_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;
+ }
+
+ /**
+ * Case-insenstive UTF-8 version of strstr. Returns all of input string
+ * from the first occurrence of needle to the end.
+ * @see http://php.net/stristr
+ *
+ * @author Harry Fuecks <hfuecks@gmail.com>
+ *
+ * @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 (text::is_ascii($str) AND text::is_ascii($search))
+ return stristr($str, $search);
+
+ if ($search == '')
+ return $str;
+
+ $str_lower = mb_strtolower($str);
+ $search_lower = mb_strtolower($search);
+
+ preg_match('/^(.*?)'.preg_quote($search, '/').'/s', $str_lower, $matches);
+
+ if (isset($matches[1]))
+ return substr($str, strlen($matches[1]));
+
+ return FALSE;
+ }
+
+ /**
+ * Finds the length of the initial segment matching mask.
+ * @see http://php.net/strspn
+ *
+ * @author Harry Fuecks <hfuecks@gmail.com>
+ *
+ * @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 ($str == '' OR $mask == '')
+ return 0;
+
+ if (text::is_ascii($str) AND text::is_ascii($mask))
+ return ($offset === NULL) ? strspn($str, $mask) : (($length === NULL) ? strspn($str, $mask, $offset) : strspn($str, $mask, $offset, $length));
+
+ if ($offset !== NULL OR $length !== NULL)
+ {
+ $str = mb_substr($str, $offset, $length);
+ }
+
+ // Escape these characters: - [ ] . : \ ^ /
+ // The . and : are escaped to prevent possible warnings about POSIX regex elements
+ $mask = preg_replace('#[-[\].:\\\\^/]#', '\\\\$0', $mask);
+ preg_match('/^[^'.$mask.']+/u', $str, $matches);
+
+ return isset($matches[0]) ? mb_strlen($matches[0]) : 0;
+ }
+
+ /**
+ * Finds the length of the initial segment not matching mask.
+ * @see http://php.net/strcspn
+ *
+ * @author Harry Fuecks <hfuecks@gmail.com>
+ *
+ * @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 ($str == '' OR $mask == '')
+ return 0;
+
+ if (text::is_ascii($str) AND text::is_ascii($mask))
+ return ($offset === NULL) ? strcspn($str, $mask) : (($length === NULL) ? strcspn($str, $mask, $offset) : strcspn($str, $mask, $offset, $length));
+
+ if ($str !== NULL OR $length !== NULL)
+ {
+ $str = mb_substr($str, $offset, $length);
+ }
+
+ // Escape these characters: - [ ] . : \ ^ /
+ // The . and : are escaped to prevent possible warnings about POSIX regex elements
+ $mask = preg_replace('#[-[\].:\\\\^/]#', '\\\\$0', $mask);
+ preg_match('/^[^'.$mask.']+/u', $str, $matches);
+
+ return isset($matches[0]) ? mb_strlen($matches[0]) : 0;
+ }
+
+ /**
+ * Pads a UTF-8 string to a certain length with another string.
+ * @see http://php.net/str_pad
+ *
+ * @author Harry Fuecks <hfuecks@gmail.com>
+ *
+ * @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 (text::is_ascii($str) AND text::is_ascii($pad_str))
+ {
+ return str_pad($str, $final_str_length, $pad_str, $pad_type);
+ }
+
+ $str_length = mb_strlen($str);
+
+ if ($final_str_length <= 0 OR $final_str_length <= $str_length)
+ {
+ return $str;
+ }
+
+ $pad_str_length = mb_strlen($pad_str);
+ $pad_length = $final_str_length - $str_length;
+
+ if ($pad_type == STR_PAD_RIGHT)
+ {
+ $repeat = ceil($pad_length / $pad_str_length);
+ return mb_substr($str.str_repeat($pad_str, $repeat), 0, $final_str_length);
+ }
+
+ if ($pad_type == STR_PAD_LEFT)
+ {
+ $repeat = ceil($pad_length / $pad_str_length);
+ return mb_substr(str_repeat($pad_str, $repeat), 0, floor($pad_length)).$str;
+ }
+
+ if ($pad_type == STR_PAD_BOTH)
+ {
+ $pad_length /= 2;
+ $pad_length_left = floor($pad_length);
+ $pad_length_right = ceil($pad_length);
+ $repeat_left = ceil($pad_length_left / $pad_str_length);
+ $repeat_right = ceil($pad_length_right / $pad_str_length);
+
+ $pad_left = mb_substr(str_repeat($pad_str, $repeat_left), 0, $pad_length_left);
+ $pad_right = mb_substr(str_repeat($pad_str, $repeat_right), 0, $pad_length_left);
+ return $pad_left.$str.$pad_right;
+ }
+
+ trigger_error('utf8::str_pad: Unknown padding type (' . $pad_type . ')', E_USER_ERROR);
+ }
+
+ /**
+ * Converts a UTF-8 string to an array.
+ * @see http://php.net/str_split
+ *
+ * @author Harry Fuecks <hfuecks@gmail.com>
+ *
+ * @param string input string
+ * @param integer maximum length of each chunk
+ * @return array
+ */
+ public static function str_split($str, $split_length = 1)
+ {
+ $split_length = (int) $split_length;
+
+ if (text::is_ascii($str))
+ {
+ return str_split($str, $split_length);
+ }
+
+ if ($split_length < 1)
+ {
+ return FALSE;
+ }
+
+ if (mb_strlen($str) <= $split_length)
+ {
+ return array($str);
+ }
+
+ preg_match_all('/.{'.$split_length.'}|[^\x00]{1,'.$split_length.'}$/us', $str, $matches);
+
+ return $matches[0];
+ }
+
+ /**
+ * Reverses a UTF-8 string.
+ * @see http://php.net/strrev
+ *
+ * @author Harry Fuecks <hfuecks@gmail.com>
+ *
+ * @param string string to be reversed
+ * @return string
+ */
+ public static function strrev($str)
+ {
+ if (text::is_ascii($str))
+ return strrev($str);
+
+ preg_match_all('/./us', $str, $matches);
+ return implode('', array_reverse($matches[0]));
+ }
+
+ /**
+ * Strips whitespace (or other UTF-8 characters) from the beginning and
+ * end of a string.
+ * @see http://php.net/trim
+ *
+ * @author Andreas Gohr <andi@splitbrain.org>
+ *
+ * @param string input string
+ * @param string string of characters to remove
+ * @return string
+ */
+ public static function trim($str, $charlist = NULL)
+ {
+ if ($charlist === NULL)
+ return trim($str);
+
+ return utf8::ltrim(utf8::rtrim($str, $charlist), $charlist);
+ }
+
+ /**
+ * Strips whitespace (or other UTF-8 characters) from the beginning of a string.
+ * @see http://php.net/ltrim
+ *
+ * @author Andreas Gohr <andi@splitbrain.org>
+ *
+ * @param string input string
+ * @param string string of characters to remove
+ * @return string
+ */
+ public static function ltrim($str, $charlist = NULL)
+ {
+ if ($charlist === NULL)
+ return ltrim($str);
+
+ if (text::is_ascii($charlist))
+ return ltrim($str, $charlist);
+
+ $charlist = preg_replace('#[-\[\]:\\\\^/]#', '\\\\$0', $charlist);
+
+ return preg_replace('/^['.$charlist.']+/u', '', $str);
+ }
+
+ /**
+ * Strips whitespace (or other UTF-8 characters) from the end of a string.
+ * @see http://php.net/rtrim
+ *
+ * @author Andreas Gohr <andi@splitbrain.org>
+ *
+ * @param string input string
+ * @param string string of characters to remove
+ * @return string
+ */
+ public static function rtrim($str, $charlist = NULL)
+ {
+ if ($charlist === NULL)
+ return rtrim($str);
+
+ if (text::is_ascii($charlist))
+ return rtrim($str, $charlist);
+
+ $charlist = preg_replace('#[-\[\]:\\\\^/]#', '\\\\$0', $charlist);
+
+ return preg_replace('/['.$charlist.']++$/uD', '', $str);
+ }
+
+ /**
+ * Returns the unicode ordinal for a character.
+ * @see http://php.net/ord
+ *
+ * @author Harry Fuecks <hfuecks@gmail.com>
+ *
+ * @param string UTF-8 encoded character
+ * @return integer
+ */
+ public static function ord($chr)
+ {
+ $ord0 = ord($chr);
+
+ if ($ord0 >= 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;
+ }
+ }
+
+ /**
+ * 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 <hsivonen@iki.fi>, see http://hsivonen.iki.fi/php-utf8/.
+ * Slight modifications to fit with phputf8 library by Harry Fuecks <hfuecks@gmail.com>.
+ *
+ * @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)
+ {
+ $mState = 0; // cached expected number of octets after the current octet until the beginning of the next UTF8 character sequence
+ $mUcs4 = 0; // cached Unicode character
+ $mBytes = 1; // cached expected number of octets in the current sequence
+
+ $out = array();
+
+ $len = strlen($str);
+
+ for ($i = 0; $i < $len; $i++)
+ {
+ $in = ord($str[$i]);
+
+ if ($mState == 0)
+ {
+ // When mState is zero we expect either a US-ASCII character or a
+ // multi-octet sequence.
+ if (0 == (0x80 & $in))
+ {
+ // US-ASCII, pass straight through.
+ $out[] = $in;
+ $mBytes = 1;
+ }
+ elseif (0xC0 == (0xE0 & $in))
+ {
+ // First octet of 2 octet sequence
+ $mUcs4 = $in;
+ $mUcs4 = ($mUcs4 & 0x1F) << 6;
+ $mState = 1;
+ $mBytes = 2;
+ }
+ elseif (0xE0 == (0xF0 & $in))
+ {
+ // First octet of 3 octet sequence
+ $mUcs4 = $in;
+ $mUcs4 = ($mUcs4 & 0x0F) << 12;
+ $mState = 2;
+ $mBytes = 3;
+ }
+ elseif (0xF0 == (0xF8 & $in))
+ {
+ // First octet of 4 octet sequence
+ $mUcs4 = $in;
+ $mUcs4 = ($mUcs4 & 0x07) << 18;
+ $mState = 3;
+ $mBytes = 4;
+ }
+ elseif (0xF8 == (0xFC & $in))
+ {
+ // First octet of 5 octet sequence.
+ //
+ // This is illegal because the encoded codepoint must be either
+ // (a) not the shortest form or
+ // (b) outside the Unicode range of 0-0x10FFFF.
+ // Rather than trying to resynchronize, we will carry on until the end
+ // of the sequence and let the later error handling code catch it.
+ $mUcs4 = $in;
+ $mUcs4 = ($mUcs4 & 0x03) << 24;
+ $mState = 4;
+ $mBytes = 5;
+ }
+ elseif (0xFC == (0xFE & $in))
+ {
+ // First octet of 6 octet sequence, see comments for 5 octet sequence.
+ $mUcs4 = $in;
+ $mUcs4 = ($mUcs4 & 1) << 30;
+ $mState = 5;
+ $mBytes = 6;
+ }
+ else
+ {
+ // Current octet is neither in the US-ASCII range nor a legal first octet of a multi-octet sequence.
+ trigger_error('utf8::to_unicode: Illegal sequence identifier in UTF-8 at byte '.$i, E_USER_WARNING);
+ return FALSE;
+ }
+ }
+ else
+ {
+ // When mState is non-zero, we expect a continuation of the multi-octet sequence
+ if (0x80 == (0xC0 & $in))
+ {
+ // Legal continuation
+ $shift = ($mState - 1) * 6;
+ $tmp = $in;
+ $tmp = ($tmp & 0x0000003F) << $shift;
+ $mUcs4 |= $tmp;
+
+ // End of the multi-octet sequence. mUcs4 now contains the final Unicode codepoint to be output
+ if (0 == --$mState)
+ {
+ // Check for illegal sequences and codepoints
+
+ // From Unicode 3.1, non-shortest form is illegal
+ if (((2 == $mBytes) AND ($mUcs4 < 0x0080)) OR
+ ((3 == $mBytes) AND ($mUcs4 < 0x0800)) OR
+ ((4 == $mBytes) AND ($mUcs4 < 0x10000)) OR
+ (4 < $mBytes) OR
+ // From Unicode 3.2, surrogate characters are illegal
+ (($mUcs4 & 0xFFFFF800) == 0xD800) OR
+ // Codepoints outside the Unicode range are illegal
+ ($mUcs4 > 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;
+ }
+
+ /**
+ * 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 <hsivonen@iki.fi>, see http://hsivonen.iki.fi/php-utf8/.
+ * Slight modifications to fit with phputf8 library by Harry Fuecks <hfuecks@gmail.com>.
+ *
+ * @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)
+ {
+ ob_start();
+
+ $keys = array_keys($arr);
+
+ foreach ($keys as $k)
+ {
+ // ASCII range (including control chars)
+ if (($arr[$k] >= 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;
+ }
+
+} // End utf8 \ No newline at end of file
diff --git a/system/helpers/valid.php b/system/helpers/valid.php
index 8a3583b2..cffcd7c0 100644
--- a/system/helpers/valid.php
+++ b/system/helpers/valid.php
@@ -2,12 +2,12 @@
/**
* Validation helper class.
*
- * $Id: valid.php 4367 2009-05-27 21:23:57Z samsoir $
+ * $Id: valid.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
*/
class valid_Core {
@@ -161,13 +161,13 @@ class valid_Core {
for ($i = $length - 1; $i >= 0; $i -= 2)
{
// Add up every 2nd digit, starting from the right
- $checksum += $number[$i];
+ $checksum += substr($number, $i, 1);
}
for ($i = $length - 2; $i >= 0; $i -= 2)
{
// Add up every 2nd digit doubled, starting from the right
- $double = $number[$i] * 2;
+ $double = substr($number, $i, 1) * 2;
// Subtract 9 from the double where value is greater than 10
$checksum += ($double >= 10) ? $double - 9 : $double;
@@ -199,7 +199,7 @@ class valid_Core {
/**
* Tests if a string is a valid date string.
- *
+ *
* @param string date to check
* @return boolean
*/
@@ -269,7 +269,7 @@ class valid_Core {
*
* @see Uses locale conversion to allow decimal point to be locale specific.
* @see http://www.php.net/manual/en/function.localeconv.php
- *
+ *
* @param string input string
* @return boolean
*/
@@ -281,21 +281,35 @@ class valid_Core {
}
/**
- * Checks whether a string is a valid text. Letters, numbers, whitespace,
- * dashes, periods, and underscores are allowed.
+ * Tests if an integer is within a range.
*
- * @param string text to check
+ * @param integer number to check
+ * @param array valid range of input
* @return boolean
*/
- public static function standard_text($str)
+ public static function range($number, array $range)
{
- // pL matches letters
- // pN matches numbers
- // pZ matches whitespace
- // pPc matches underscores
- // pPd matches dashes
- // pPo matches normal puncuation
- return (bool) preg_match('/^[\pL\pN\pZ\p{Pc}\p{Pd}\p{Po}]++$/uD', (string) $str);
+ // Invalid by default
+ $status = FALSE;
+
+ if (is_int($number) OR ctype_digit($number))
+ {
+ if (count($range) > 1)
+ {
+ if ($number >= $range[0] AND $number <= $range[1])
+ {
+ // Number is within the required range
+ $status = TRUE;
+ }
+ }
+ elseif ($number >= $range[0])
+ {
+ // Number is greater than the minimum
+ $status = TRUE;
+ }
+ }
+
+ return $status;
}
/**
@@ -335,4 +349,18 @@ class valid_Core {
return (bool) preg_match($pattern, (string) $str);
}
+ /**
+ * Checks if a string is a proper hexadecimal HTML color value. The validation
+ * is quite flexible as it does not require an initial "#" and also allows for
+ * the short notation using only three instead of six hexadecimal characters.
+ * You may want to normalize these values with format::color().
+ *
+ * @param string input string
+ * @return boolean
+ */
+ public static function color($str)
+ {
+ return (bool) preg_match('/^#?+[0-9a-f]{3}(?:[0-9a-f]{3})?$/iD', $str);
+ }
+
} // End valid \ No newline at end of file