From 9b6663f87a7e679ffba691cf516191fc840cf978 Mon Sep 17 00:00:00 2001 From: Bharat Mediratta Date: Tue, 24 Nov 2009 19:20:36 -0800 Subject: Update to Kohana r4684 which is now Kohana 2.4 and has substantial changes. --- system/helpers/arr.php | 103 ++---- system/helpers/cookie.php | 87 ++++- system/helpers/date.php | 42 +-- system/helpers/db.php | 49 +++ system/helpers/download.php | 148 +++++---- system/helpers/email.php | 181 ----------- system/helpers/expires.php | 115 ++++--- system/helpers/feed.php | 6 +- system/helpers/file.php | 6 +- system/helpers/form.php | 123 ++----- system/helpers/format.php | 54 +++- system/helpers/html.php | 106 +----- system/helpers/inflector.php | 73 ++++- system/helpers/num.php | 6 +- system/helpers/remote.php | 10 +- system/helpers/request.php | 480 +++++++++++++++++++++++++--- system/helpers/security.php | 11 +- system/helpers/text.php | 218 +++++++++++-- system/helpers/upload.php | 15 +- system/helpers/url.php | 10 +- system/helpers/utf8.php | 746 +++++++++++++++++++++++++++++++++++++++++++ system/helpers/valid.php | 64 ++-- 22 files changed, 1944 insertions(+), 709 deletions(-) create mode 100644 system/helpers/db.php delete mode 100644 system/helpers/email.php create mode 100644 system/helpers/utf8.php (limited to 'system/helpers') 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,19 +102,25 @@ 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. * @@ -151,44 +157,6 @@ class arr_Core { return $array; } - /** - * @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. @@ -263,27 +231,6 @@ class arr_Core { return $array1; } - /** - * 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. * @@ -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 @@ +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 @@ -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 ''."\n"; - } - - /** - * Generates a fieldset closing tag. - * - * @return string - */ - public static function close_fieldset() - { - return ''."\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 ''.$text.''."\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 ''.html::specialchars($value, $double_encode).''; + return ''.htmlspecialchars($value, ENT_QUOTES, Kohana::CHARSET, $double_encode).''; } /** @@ -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 .= ''."\n"; + $sel = in_array($inner_key, $selected) ? ' selected="selected"' : ''; + $input .= ''."\n"; } $input .= ''."\n"; } else { - $attr = array('value' => $key); - if (in_array($key, $selected)) { - $attr['selected'] = 'selected'; - } - $input .= ''."\n"; + $sel = in_array($key, $selected) ? ' selected="selected"' : ''; + $input .= ''."\n"; } } $input .= ''; @@ -416,20 +372,8 @@ class form_Core { { $value = arr::remove('value', $data); } - // $value must be ::purify - - return ''.html::purify($value).''; - } - /** - * Closes an open form tag. - * - * @param string string to be attached after the closing tag - * @return string - */ - public static function close($extra = '') - { - return ''."\n".$extra; + return ''.$value.''; } /** @@ -462,7 +406,7 @@ class form_Core { $text = ucwords(inflector::humanize($data['for'])); } - return ''.html::purify($text).''; + return ''.$text.''; } /** @@ -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,15 +2,32 @@ /** * 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. * @@ -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,46 +21,12 @@ 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', '&', $str); - $str = str_replace(array('<', '>', '\'', '"'), array('<', '>', ''', '"'), $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. * @@ -98,11 +64,11 @@ class html_Core { return // Parsed URL - '' // Title empty? Use the parsed URL - .($escape_title ? html::specialchars((($title === NULL) ? $site_url : $title), FALSE) : (($title === NULL) ? $site_url : $title)).''; + .($escape_title ? htmlspecialchars((($title === NULL) ? $site_url : $title), ENT_QUOTES, Kohana::CHARSET, FALSE) : (($title === NULL) ? $site_url : $title)).''; } /** @@ -118,44 +84,13 @@ class html_Core { { return // Base URL + URI = full URL - '' // Title empty? Use the filename part of the URI .(($title === NULL) ? end(explode('/', $file)) : $title) .''; } - /** - * 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. * @@ -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 = ''; } @@ -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)); @@ -103,6 +123,29 @@ class inflector_Core { * @return string */ 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)); @@ -154,6 +197,24 @@ class inflector_Core { return inflector::$cache[$key] = $str; } + /** + * 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. * @@ -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; @@ -106,6 +168,56 @@ class request_Core { return (request::accepts_at_quality($type, $explicit_check) > 0); } + /** + * 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. @@ -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

and
markup to text. Basically nl2br() on steroids. * * @param string subject + * @param boolean convert single linebreaks to
* @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
- $str = preg_replace('~(?\n", $str); + if ($br === TRUE) + { + $str = preg_replace('~(?\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 + * @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 @@ + + * + * @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 + * + * @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 + * + * @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 $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 + * + * @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 + * + * @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 + * + * @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 + * + * @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 + * + * @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 + * + * @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 + * + * @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 + * + * @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 + * + * @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 + * + * @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 , see http://hsivonen.iki.fi/php-utf8/. + * Slight modifications to fit with phputf8 library by Harry Fuecks . + * + * @param string UTF-8 encoded string + * @return array unicode code points + * @return boolean FALSE if the string is invalid + */ + public static function to_unicode($str) + { + $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 , see http://hsivonen.iki.fi/php-utf8/. + * Slight modifications to fit with phputf8 library by Harry Fuecks . + * + * @param array unicode code points representing a string + * @return string utf8 string of characters + * @return boolean FALSE if a code point cannot be found + */ + public static function from_unicode($arr) + { + 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 -- cgit v1.2.3 From 9285c8c66c530196399eb05bb5561c3fa5538335 Mon Sep 17 00:00:00 2001 From: Bharat Mediratta Date: Mon, 21 Dec 2009 20:05:27 -0800 Subject: Updated Kohana to r4724 --- system/config/cache.php | 3 + system/config/database.php | 3 +- system/core/Kohana.php | 39 +- system/core/Kohana_Exception.php | 4 +- system/helpers/form.php | 28 +- system/helpers/inflector.php | 6 +- system/helpers/request.php | 4 +- system/helpers/security.php | 13 +- system/helpers/text.php | 46 +- system/helpers/url.php | 21 +- system/helpers/utf8.php | 2 +- system/libraries/Cache.php | 87 +- system/libraries/Controller.php | 8 +- system/libraries/Database.php | 23 +- system/libraries/Database_Builder.php | 103 +- system/libraries/Database_Mysql.php | 9 +- system/libraries/Database_Mysqli.php | 32 +- system/libraries/Input.php | 8 +- system/libraries/Kohana_PHP_Exception.php | 4 +- system/libraries/ORM.php | 56 +- system/libraries/Profiler.php | 4 +- system/libraries/Router.php | 10 +- system/libraries/Validation.php | 155 +- system/libraries/drivers/Cache/File.php | 4 +- system/libraries/drivers/Cache/Memcache.php | 7 +- system/libraries/drivers/Cache/Xcache.php | 2 +- system/messages/core.php | 9 +- system/messages/validation/default.php | 17 + system/vendor/Markdown.php | 2909 --------------------------- 29 files changed, 458 insertions(+), 3158 deletions(-) create mode 100644 system/messages/validation/default.php delete mode 100644 system/vendor/Markdown.php (limited to 'system/helpers') diff --git a/system/config/cache.php b/system/config/cache.php index 68682c0a..76af4f6a 100644 --- a/system/config/cache.php +++ b/system/config/cache.php @@ -19,10 +19,13 @@ * thirty minutes. Specific lifetime can also be set when creating a new cache. * Setting this to 0 will never automatically delete caches. * + * prefix - Adds a prefix to all keys and tags. This can have a severe performance impact. + * */ $config['default'] = array ( 'driver' => 'file', 'params' => array('directory' => APPPATH.'cache', 'gc_probability' => 1000), 'lifetime' => 1800, + 'prefix' => NULL ); diff --git a/system/config/database.php b/system/config/database.php index 2e53fa2b..36e4614c 100644 --- a/system/config/database.php +++ b/system/config/database.php @@ -35,7 +35,8 @@ $config['default'] = array 'host' => 'localhost', 'port' => FALSE, 'socket' => FALSE, - 'database' => 'kohana' + 'database' => 'kohana', + 'params' => NULL, ), 'character_set' => 'utf8', 'table_prefix' => '', diff --git a/system/core/Kohana.php b/system/core/Kohana.php index 5258d635..740adb80 100644 --- a/system/core/Kohana.php +++ b/system/core/Kohana.php @@ -2,7 +2,7 @@ /** * Provides Kohana-specific helper functions. This is where the magic happens! * - * $Id: Kohana.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Kohana.php 4724 2009-12-21 16:28:54Z isaiah $ * * @package Core * @author Kohana Team @@ -45,6 +45,9 @@ abstract class Kohana_Core { protected static $internal_cache_key; protected static $internal_cache_encrypt; + // Server API that PHP is using. Allows testing of different APIs. + public static $server_api = PHP_SAPI; + /** * Sets up the PHP environment. Adds error/exception handling, output * buffering, and adds an auto-loading method for loading classes. @@ -162,6 +165,35 @@ abstract class Kohana_Core { // Set and validate the timezone date_default_timezone_set(Kohana::config('locale.timezone')); + // register_globals is enabled + if (ini_get('register_globals')) + { + if (isset($_REQUEST['GLOBALS'])) + { + // Prevent GLOBALS override attacks + exit('Global variable overload attack.'); + } + + // Destroy the REQUEST global + $_REQUEST = array(); + + // These globals are standard and should not be removed + $preserve = array('GLOBALS', '_REQUEST', '_GET', '_POST', '_FILES', '_COOKIE', '_SERVER', '_ENV', '_SESSION'); + + // This loop has the same effect as disabling register_globals + foreach (array_diff(array_keys($GLOBALS), $preserve) as $key) + { + global $$key; + $$key = NULL; + + // Unset the global variable + unset($GLOBALS[$key], $$key); + } + + // Warn the developer about register globals + Kohana_Log::add('debug', 'Disable register_globals! It is evil and deprecated: http://php.net/register_globals'); + } + // Enable Kohana routing Event::add('system.routing', array('Router', 'find_uri')); Event::add('system.routing', array('Router', 'setup')); @@ -602,7 +634,7 @@ abstract class Kohana_Core { header('Content-Encoding: '.$compress); // Sending Content-Length in CGI can result in unexpected behavior - if (stripos(PHP_SAPI, 'cgi') === FALSE) + if (stripos(Kohana::$server_api, 'cgi') === FALSE) { header('Content-Length: '.strlen($output)); } @@ -876,9 +908,6 @@ abstract class Kohana_Core { $group = explode('.', $key, 2); $group = $group[0]; - // Get locale name - $locale = Kohana::config('locale.language.0'); - if ( ! isset(Kohana::$internal_cache['messages'][$group])) { // Messages for this group diff --git a/system/core/Kohana_Exception.php b/system/core/Kohana_Exception.php index cdb06a62..2eb28f75 100644 --- a/system/core/Kohana_Exception.php +++ b/system/core/Kohana_Exception.php @@ -2,7 +2,7 @@ /** * Kohana Exceptions * - * $Id: Kohana_Exception.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Kohana_Exception.php 4692 2009-12-04 15:59:44Z cbandy $ * * @package Core * @author Kohana Team @@ -197,7 +197,7 @@ class Kohana_Exception_Core extends Exception { echo Kohana_Exception::text($e), "\n"; } - if (PHP_SAPI === 'cli') + if (Kohana::$server_api === 'cli') { // Exit with an error status exit(1); diff --git a/system/helpers/form.php b/system/helpers/form.php index 901edc91..4225b1b6 100644 --- a/system/helpers/form.php +++ b/system/helpers/form.php @@ -2,7 +2,7 @@ /** * Form helper class. * - * $Id: form.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: form.php 4699 2009-12-08 18:45:14Z isaiah $ * * @package Core * @author Kohana Team @@ -421,32 +421,6 @@ class form_Core { if (empty($attr)) return ''; - if (isset($attr['name']) AND empty($attr['id']) AND strpos($attr['name'], '[') === FALSE) - { - if ($type === NULL AND ! empty($attr['type'])) - { - // Set the type by the attributes - $type = $attr['type']; - } - - switch ($type) - { - case 'text': - case 'textarea': - case 'password': - case 'select': - case 'checkbox': - case 'file': - case 'image': - case 'button': - case 'submit': - case 'hidden': - // Only specific types of inputs use name to id matching - $attr['id'] = $attr['name']; - break; - } - } - $order = array ( 'action', diff --git a/system/helpers/inflector.php b/system/helpers/inflector.php index 9bd281db..5a2910c0 100644 --- a/system/helpers/inflector.php +++ b/system/helpers/inflector.php @@ -2,7 +2,7 @@ /** * Inflector helper class. * - * $Id: inflector.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: inflector.php 4722 2009-12-19 17:47:34Z isaiah $ * * @package Core * @author Kohana Team @@ -241,9 +241,9 @@ class inflector_Core { } /** - * Makes an underscored or dashed phrase human-reable. + * Makes an underscored or dashed phrase human-readable. * - * @param string phrase to make human-reable + * @param string phrase to make human-readable * @return string */ public static function humanize($str) diff --git a/system/helpers/request.php b/system/helpers/request.php index 4770d64b..31afee4e 100644 --- a/system/helpers/request.php +++ b/system/helpers/request.php @@ -2,7 +2,7 @@ /** * Request helper class. * - * $Id: request.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: request.php 4692 2009-12-04 15:59:44Z cbandy $ * * @package Core * @author Kohana Team @@ -61,7 +61,7 @@ class request_Core { */ public static function protocol() { - if (PHP_SAPI === 'cli') + if (Kohana::$server_api === 'cli') { return NULL; } diff --git a/system/helpers/security.php b/system/helpers/security.php index 9eb82a58..33e5118e 100644 --- a/system/helpers/security.php +++ b/system/helpers/security.php @@ -2,7 +2,7 @@ /** * Security helper class. * - * $Id: security.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: security.php 4698 2009-12-08 18:39:33Z isaiah $ * * @package Core * @author Kohana Team @@ -34,15 +34,4 @@ class security_Core { return preg_replace('#\s]*)["\']?[^>]*)?>#is', '$1', $str); } - /** - * Remove PHP tags from a string. - * - * @param string string to sanitize - * @return string - */ - public static function encode_php_tags($str) - { - return str_replace(array(''), array('<?', '?>'), $str); - } - } // End security \ No newline at end of file diff --git a/system/helpers/text.php b/system/helpers/text.php index 66bcd243..ed7f9cbf 100644 --- a/system/helpers/text.php +++ b/system/helpers/text.php @@ -2,7 +2,7 @@ /** * Text helper class. * - * $Id: text.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: text.php 4689 2009-12-02 01:39:24Z isaiah $ * * @package Core * @author Kohana Team @@ -298,27 +298,37 @@ class text_Core { */ public static function auto_link_urls($text) { - // Finds all http/https/ftp/ftps links that are not part of an existing html anchor - if (preg_match_all('~\b(?)(?:ht|f)tps?://\S+(?:/|\b)~i', $text, $matches)) - { - foreach ($matches[0] as $match) - { - // Replace each link with an anchor - $text = str_replace($match, html::anchor($match), $text); - } - } - // Find all naked www.links.com (without http://) - if (preg_match_all('~\b(? $name)); + throw new Cache_Exception('The :group: group is not defined in your configuration.', array(':group:' => $name)); } if (is_array($config)) @@ -74,7 +74,7 @@ class Cache_Core { // Load the driver if ( ! Kohana::auto_load($driver)) - throw new Kohana_Exception('The :driver: driver for the :class: library could not be found', + throw new Cache_Exception('The :driver: driver for the :class: library could not be found', array(':driver:' => $this->config['driver'], ':class:' => get_class($this))); // Initialize the driver @@ -82,7 +82,7 @@ class Cache_Core { // Validate the driver if ( ! ($this->driver instanceof Cache_Driver)) - throw new Kohana_Exception('The :driver: driver for the :library: library must implement the :interface: interface', + throw new Cache_Exception('The :driver: driver for the :library: library must implement the :interface: interface', array(':driver:' => $this->config['driver'], ':library:' => get_class($this), ':interface:' => 'Cache_Driver')); Kohana_Log::add('debug', 'Cache Library initialized'); @@ -103,6 +103,16 @@ class Cache_Core { $key = array($key => $value); } + if ($this->config['prefix'] !== NULL) + { + $key = $this->add_prefix($key); + + if ($tags !== NULL) + { + $tags = $this->add_prefix($tags, FALSE); + } + } + return $this->driver->set($key, $tags, $lifetime); } @@ -119,6 +129,17 @@ class Cache_Core { $single = TRUE; } + if ($this->config['prefix'] !== NULL) + { + $keys = $this->add_prefix($keys, FALSE); + + if ( ! $single) + { + return $this->strip_prefix($this->driver->get($keys, $single)); + } + + } + return $this->driver->get($keys, $single); } @@ -132,7 +153,15 @@ class Cache_Core { $tags = array($tags); } - return $this->driver->get_tag($tags); + if ($this->config['prefix'] !== NULL) + { + $tags = $this->add_prefix($tags, FALSE); + return $this->strip_prefix($this->driver->get_tag($tags)); + } + else + { + return $this->driver->get_tag($tags); + } } /** @@ -145,6 +174,11 @@ class Cache_Core { $keys = array($keys); } + if ($this->config['prefix'] !== NULL) + { + $keys = $this->add_prefix($keys, FALSE); + } + return $this->driver->delete($keys); } @@ -158,6 +192,11 @@ class Cache_Core { $tags = array($tags); } + if ($this->config['prefix'] !== NULL) + { + $tags = $this->add_prefix($tags, FALSE); + } + return $this->driver->delete_tag($tags); } @@ -168,4 +207,44 @@ class Cache_Core { { return $this->driver->delete_all(); } + + /** + * Add a prefix to keys or tags + */ + protected function add_prefix($array, $to_key = TRUE) + { + $out = array(); + + foreach($array as $key => $value) + { + if ($to_key) + { + $out[$this->config['prefix'].$key] = $value; + } + else + { + $out[$key] = $this->config['prefix'].$value; + } + } + + return $out; + } + + /** + * Strip a prefix to keys or tags + */ + protected function strip_prefix($array) + { + $out = array(); + + $start = strlen($this->config['prefix']); + + foreach($array as $key => $value) + { + $out[substr($key, $start)] = $value; + } + + return $out; + } + } // End Cache Library \ No newline at end of file diff --git a/system/libraries/Controller.php b/system/libraries/Controller.php index da84bfc1..830c06e5 100644 --- a/system/libraries/Controller.php +++ b/system/libraries/Controller.php @@ -3,7 +3,7 @@ * Kohana Controller class. The controller class must be extended to work * properly, so this class is defined as abstract. * - * $Id: Controller.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Controller.php 4721 2009-12-17 23:02:07Z isaiah $ * * @package Core * @author Kohana Team @@ -27,12 +27,6 @@ abstract class Controller_Core { // Set the instance to the first controller loaded Kohana::$instance = $this; } - - // URI should always be available - $this->uri = URI::instance(); - - // Input should always be available - $this->input = Input::instance(); } /** diff --git a/system/libraries/Database.php b/system/libraries/Database.php index d3716c59..38a38fbf 100644 --- a/system/libraries/Database.php +++ b/system/libraries/Database.php @@ -1,9 +1,9 @@ cache instanceof Cache) + if ($this->cache instanceof Cache AND ($type == NULL OR $type == Database::CROSS_REQUEST)) { // Using cross-request Cache library if ($sql === TRUE) @@ -370,7 +373,7 @@ abstract class Database_Core { $this->cache->delete_all(); } } - elseif (is_array($this->cache)) + elseif (is_array($this->cache) AND ($type == NULL OR $type == Database::PER_REQUEST)) { // Using per-request memory cache if ($sql === TRUE) diff --git a/system/libraries/Database_Builder.php b/system/libraries/Database_Builder.php index 5a5a058c..4e6951e7 100644 --- a/system/libraries/Database_Builder.php +++ b/system/libraries/Database_Builder.php @@ -29,6 +29,7 @@ class Database_Builder_Core { protected $columns = array(); protected $values = array(); protected $type; + protected $distinct = FALSE; // TTL for caching (using Cache library) protected $ttl = FALSE; @@ -77,7 +78,8 @@ class Database_Builder_Core { if ($this->type === Database::SELECT) { // SELECT columns FROM table - $sql = 'SELECT '.$this->compile_select(); + $sql = $this->distinct ? 'SELECT DISTINCT ' : 'SELECT '; + $sql .= $this->compile_select(); if ( ! empty($this->from)) { @@ -146,7 +148,13 @@ class Database_Builder_Core { foreach ($this->select as $alias => $name) { - if (is_string($alias)) + if ($name instanceof Database_Builder) + { + // Using a subquery + $name->db = $this->db; + $vals[] = '('.(string) $name.') AS '.$this->db->quote_column($alias); + } + elseif (is_string($alias)) { $vals[] = $this->db->quote_column($name, $alias); } @@ -374,28 +382,48 @@ class Database_Builder_Core { /** * Add conditions to the HAVING clause (AND) * - * @param mixed Column name or array of columns => vals + * @param mixed Column name or array of triplets * @param string Operation to perform * @param mixed Value * @return Database_Builder */ public function and_having($columns, $op = '=', $value = NULL) { - $this->having[] = array('AND' => array($columns, $op, $value)); + if (is_array($columns)) + { + foreach ($columns as $column) + { + $this->having[] = array('AND' => $column); + } + } + else + { + $this->having[] = array('AND' => array($columns, $op, $value)); + } return $this; } /** * Add conditions to the HAVING clause (OR) * - * @param mixed Column name or array of columns => vals + * @param mixed Column name or array of triplets * @param string Operation to perform * @param mixed Value * @return Database_Builder */ public function or_having($columns, $op = '=', $value = NULL) { - $this->having[] = array('OR' => array($columns, $op, $value)); + if (is_array($columns)) + { + foreach ($columns as $column) + { + $this->having[] = array('OR' => $column); + } + } + else + { + $this->having[] = array('OR' => array($columns, $op, $value)); + } return $this; } @@ -408,13 +436,25 @@ class Database_Builder_Core { */ public function order_by($columns, $direction = NULL) { - if (is_string($columns)) + if (is_array($columns)) { - $columns = array($columns => $direction); + foreach ($columns as $column => $direction) + { + if (is_string($column)) + { + $this->order_by[] = array($column => $direction); + } + else + { + // $direction is the column name when the array key is numeric + $this->order_by[] = array($direction => NULL); + } + } + } + else + { + $this->order_by[] = array($columns => $direction); } - - $this->order_by[] = $columns; - return $this; } @@ -542,28 +582,48 @@ class Database_Builder_Core { /** * Add conditions to the WHERE clause (AND) * - * @param mixed Column name or array of columns => vals + * @param mixed Column name or array of triplets * @param string Operation to perform * @param mixed Value * @return Database_Builder */ public function and_where($columns, $op = '=', $value = NULL) { - $this->where[] = array('AND' => array($columns, $op, $value)); + if (is_array($columns)) + { + foreach ($columns as $column) + { + $this->where[] = array('AND' => $column); + } + } + else + { + $this->where[] = array('AND' => array($columns, $op, $value)); + } return $this; } /** * Add conditions to the WHERE clause (OR) * - * @param mixed Column name or array of columns => vals + * @param mixed Column name or array of triplets * @param string Operation to perform * @param mixed Value * @return Database_Builder */ public function or_where($columns, $op = '=', $value = NULL) { - $this->where[] = array('OR' => array($columns, $op, $value)); + if (is_array($columns)) + { + foreach ($columns as $column) + { + $this->where[] = array('OR' => $column); + } + } + else + { + $this->where[] = array('OR' => array($columns, $op, $value)); + } return $this; } @@ -779,6 +839,19 @@ class Database_Builder_Core { return $this; } + /** + * Create a SELECT query and specify selected columns + * + * @param string|array column name or array(alias => column) + * @return Database_Builder + */ + public function select_distinct($columns = NULL) + { + $this->select($columns); + $this->distinct = TRUE; + return $this; + } + /** * Create an UPDATE query * diff --git a/system/libraries/Database_Mysql.php b/system/libraries/Database_Mysql.php index cb531194..a5775037 100644 --- a/system/libraries/Database_Mysql.php +++ b/system/libraries/Database_Mysql.php @@ -2,7 +2,7 @@ /** * MySQL database connection. * - * $Id: Database_Mysql.php 4684 2009-11-18 14:26:48Z isaiah $ + * $Id: Database_Mysql.php 4712 2009-12-10 21:47:09Z cbandy $ * * @package Kohana * @author Kohana Team @@ -31,16 +31,15 @@ class Database_Mysql_Core extends Database { extract($this->config['connection']); - // Set the connection type - $connect = ($this->config['persistent'] === TRUE) ? 'mysql_pconnect' : 'mysql_connect'; - $host = isset($host) ? $host : $socket; $port = isset($port) ? ':'.$port : ''; try { // Connect to the database - $this->connection = $connect($host.$port, $user, $pass, TRUE); + $this->connection = ($this->config['persistent'] === TRUE) + ? mysql_pconnect($host.$port, $user, $pass, $params) + : mysql_connect($host.$port, $user, $pass, TRUE, $params); } catch (Kohana_PHP_Exception $e) { diff --git a/system/libraries/Database_Mysqli.php b/system/libraries/Database_Mysqli.php index 523fcb19..08ed99df 100644 --- a/system/libraries/Database_Mysqli.php +++ b/system/libraries/Database_Mysqli.php @@ -2,7 +2,7 @@ /** * MySQL database connection. * - * $Id: Database_Mysqli.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Database_Mysqli.php 4712 2009-12-10 21:47:09Z cbandy $ * * @package Kohana * @author Kohana Team @@ -29,29 +29,29 @@ class Database_Mysqli_Core extends Database_Mysql { $host = isset($host) ? $host : $socket; - if($this->connection = new mysqli($host, $user, $pass, $database, $port)) { + $mysqli = mysqli_init(); - if (isset($this->config['character_set'])) - { - // Set the character set - $this->set_charset($this->config['character_set']); - } + if ( ! $mysqli->real_connect($host, $user, $pass, $database, $port, $socket, $params)) + throw new Database_Exception('#:errno: :error', + array(':error' => $mysqli->connect_error, ':errno' => $mysqli->connect_errno)); - // Clear password after successful connect - $this->db_config['connection']['pass'] = NULL; + $this->connection = $mysqli; - return $this->connection; + if (isset($this->config['character_set'])) + { + // Set the character set + $this->set_charset($this->config['character_set']); } - - // Unable to connect to the database - throw new Database_Exception('#:errno: :error', - array(':error' => $this->connection->connect_error, - ':errno' => $this->connection->connect_errno)); } public function disconnect() { - return is_object($this->connection) and $this->connection->close(); + if (is_object($this->connection)) + { + $this->connection->close(); + } + + $this->connection = NULL; } public function set_charset($charset) diff --git a/system/libraries/Input.php b/system/libraries/Input.php index 83f0ed17..04403854 100644 --- a/system/libraries/Input.php +++ b/system/libraries/Input.php @@ -2,7 +2,7 @@ /** * Input library. * - * $Id: Input.php 4680 2009-11-10 01:57:00Z isaiah $ + * $Id: Input.php 4720 2009-12-17 21:15:03Z isaiah $ * * @package Core * @author Kohana Team @@ -54,7 +54,7 @@ class Input_Core { $_COOKIE = Input::clean($_COOKIE); $_SERVER = Input::clean($_SERVER); - if (PHP_SAPI == 'cli') + if (Kohana::$server_api === 'cli') { // Convert command line arguments $_SERVER['argv'] = Input::clean($_SERVER['argv']); @@ -311,7 +311,7 @@ class Input_Core { if (trim($data) === '') return $data; - if ($tool === TRUE) + if (is_bool($tool)) { $tool = 'default'; } @@ -371,7 +371,7 @@ class Input_Core { $data = html_entity_decode($data, ENT_COMPAT, 'UTF-8'); // Remove any attribute starting with "on" or xmlns - $data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data); + $data = preg_replace('#(?:on[a-z]+|xmlns)\s*=\s*[\'"\x00-\x20]?[^\'>"]*[\'"\x00-\x20]?\s?#iu', '', $data); // Remove javascript: and vbscript: protocols $data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data); diff --git a/system/libraries/Kohana_PHP_Exception.php b/system/libraries/Kohana_PHP_Exception.php index fca5b30b..019c686b 100644 --- a/system/libraries/Kohana_PHP_Exception.php +++ b/system/libraries/Kohana_PHP_Exception.php @@ -2,7 +2,7 @@ /** * Kohana PHP Error Exceptions * - * $Id: Kohana_PHP_Exception.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Kohana_PHP_Exception.php 4687 2009-11-30 21:59:26Z isaiah $ * * @package Core * @author Kohana Team @@ -89,7 +89,7 @@ class Kohana_PHP_Exception_Core extends Kohana_Exception { */ public static function shutdown_handler() { - if (Kohana_PHP_Exception::$enabled AND $error = error_get_last()) + if (Kohana_PHP_Exception::$enabled AND $error = error_get_last() AND (error_reporting() & $error['type'])) { // Fake an exception for nice debugging Kohana_Exception::handle(new Kohana_PHP_Exception($error['type'], $error['message'], $error['file'], $error['line'])); diff --git a/system/libraries/ORM.php b/system/libraries/ORM.php index eff22fc0..2f2feed5 100644 --- a/system/libraries/ORM.php +++ b/system/libraries/ORM.php @@ -8,7 +8,7 @@ * [ref-orm]: http://wikipedia.org/wiki/Object-relational_mapping * [ref-act]: http://wikipedia.org/wiki/Active_record * - * $Id: ORM.php 4682 2009-11-11 20:53:23Z isaiah $ + * $Id: ORM.php 4711 2009-12-10 20:40:52Z isaiah $ * * @package ORM * @author Kohana Team @@ -102,7 +102,7 @@ class ORM_Core { $this->object_name = strtolower(substr(get_class($this), 0, -6)); $this->object_plural = inflector::plural($this->object_name); - if (!isset($this->sorting)) + if ( ! isset($this->sorting)) { // Default sorting $this->sorting = array($this->primary_key => 'asc'); @@ -119,7 +119,7 @@ class ORM_Core { // Load an object $this->_load_values((array) $id); } - elseif (!empty($id)) + elseif ( ! empty($id)) { // Set the object's primary key, but don't load it until needed $this->object[$this->primary_key] = $id; @@ -234,7 +234,7 @@ class ORM_Core { switch ($num_args) { case 0: - if (in_array($method, array('open', 'close', 'cache'))) + if (in_array($method, array('open', 'and_open', 'or_open', 'close', 'cache'))) { // Should return ORM, not Database $this->db_builder->$method(); @@ -320,12 +320,12 @@ class ORM_Core { } // Foreign key lies in this table (this model belongs_to target model) - $where = array($model->foreign_key(TRUE) => $this->object[$this->foreign_key($column)]); + $where = array($model->foreign_key(TRUE), '=', $this->object[$this->foreign_key($column)]); } else { // Foreign key lies in the target table (this model has_one target model) - $where = array($this->foreign_key($column, $model->table_name) => $this->primary_key_value); + $where = array($this->foreign_key($column, $model->table_name), '=', $this->primary_key_value); } // one<>alias:one relationship @@ -524,16 +524,6 @@ class ORM_Core { unset($this->object[$column], $this->changed[$column], $this->related[$column]); } - /** - * Displays the primary key of a model when it is converted to a string. - * - * @return string - */ - public function __toString() - { - return (string) $this->primary_key_value; - } - /** * Returns the values of this object as an array. * @@ -665,7 +655,7 @@ class ORM_Core { if (is_array($id)) { // Search for all clauses - $this->db_builder->where($id); + $this->db_builder->where(array($id)); } else { @@ -767,6 +757,9 @@ class ORM_Core { ORM_Validation_Exception::handle_validation($this->table_name, $array); } + // Fields may have been modified by filters + $this->object = array_merge($this->object, $array->getArrayCopy()); + // Return validation status return $this; } @@ -782,8 +775,10 @@ class ORM_Core { if ( ! empty($this->changed)) { // Require model validation before saving - if (!$this->_valid) + if ( ! $this->_valid) + { $this->validate(); + } $data = array(); foreach ($this->changed as $column) @@ -881,8 +876,8 @@ class ORM_Core { } // Foreign keys for the join table - $object_fk = $this->foreign_key(NULL); - $related_fk = $model->foreign_key(NULL); + $object_fk = $this->foreign_key($join_table); + $related_fk = $model->foreign_key($join_table); if ( ! empty($added)) { @@ -909,6 +904,12 @@ class ORM_Core { } } + if ($this->saved() === TRUE) + { + // Clear the per-request database cache + $this->db->clear_cache(NULL, Database::PER_REQUEST); + } + return $this; } @@ -933,6 +934,9 @@ class ORM_Core { ->where($this->primary_key, '=', $id) ->execute($this->db); + // Clear the per-request database cache + $this->db->clear_cache(NULL, Database::PER_REQUEST); + return $this->clear(); } @@ -965,6 +969,9 @@ class ORM_Core { return $this; } + // Clear the per-request database cache + $this->db->clear_cache(NULL, Database::PER_REQUEST); + return $this->clear(); } @@ -1154,12 +1161,13 @@ class ORM_Core { * * @chainable * @param string SQL query to clear + * @param integer Type of cache to clear, Database::CROSS_REQUEST or Database::PER_REQUEST * @return ORM */ - public function clear_cache($sql = NULL) + public function clear_cache($sql = NULL, $type = NULL) { // Proxy to database - $this->db->clear_cache($sql); + $this->db->clear_cache($sql, $type); ORM::$column_cache = array(); @@ -1550,9 +1558,9 @@ class ORM_Core { */ protected function load_relations($table, ORM $model) { - $result = db::select(array('id' => $model->foreign_key(NULL))) + $result = db::select(array('id' => $model->foreign_key($table))) ->from($table) - ->where($this->foreign_key(NULL, $table), '=', $this->primary_key_value) + ->where($this->foreign_key($table, $table), '=', $this->primary_key_value) ->execute($this->db) ->as_object(); diff --git a/system/libraries/Profiler.php b/system/libraries/Profiler.php index b7a5ecae..940e365d 100644 --- a/system/libraries/Profiler.php +++ b/system/libraries/Profiler.php @@ -8,7 +8,7 @@ * POST Data - The name and values of any POST data submitted to the current page. * Cookie Data - All cookies sent for the current request. * - * $Id: Profiler.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Profiler.php 4719 2009-12-17 04:31:48Z isaiah $ * * @package Profiler * @author Kohana Team @@ -101,7 +101,7 @@ class Profiler_Core { // Don't display if there's no profiles if (empty(Profiler::$profiles)) - return $output; + return Kohana::$output; $styles = ''; foreach (Profiler::$profiles as $profile) diff --git a/system/libraries/Router.php b/system/libraries/Router.php index 82dbb9b5..18e01af2 100644 --- a/system/libraries/Router.php +++ b/system/libraries/Router.php @@ -2,7 +2,7 @@ /** * Router * - * $Id: Router.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Router.php 4693 2009-12-04 17:11:16Z cbandy $ * * @package Core * @author Kohana Team @@ -38,7 +38,7 @@ class Router_Core { if ( ! empty($_SERVER['QUERY_STRING'])) { // Set the query string to the current query string - Router::$query_string = '?'.trim(urldecode($_SERVER['QUERY_STRING']), '&/'); + Router::$query_string = '?'.urldecode(trim($_SERVER['QUERY_STRING'], '&')); } if (Router::$routes === NULL) @@ -173,7 +173,7 @@ class Router_Core { */ public static function find_uri() { - if (PHP_SAPI === 'cli') + if (Kohana::$server_api === 'cli') { // Command line requires a bit of hacking if (isset($_SERVER['argv'][1])) @@ -181,9 +181,9 @@ class Router_Core { Router::$current_uri = $_SERVER['argv'][1]; // Remove GET string from segments - if (($query = strpos(Router::$current_uri, '?')) !== FALSE) + if (strpos(Router::$current_uri, '?') !== FALSE) { - list (Router::$current_uri, $query) = explode('?', Router::$current_uri, 2); + list(Router::$current_uri, $query) = explode('?', Router::$current_uri, 2); // Parse the query string into $_GET parse_str($query, $_GET); diff --git a/system/libraries/Validation.php b/system/libraries/Validation.php index f340e63c..47f34584 100644 --- a/system/libraries/Validation.php +++ b/system/libraries/Validation.php @@ -2,7 +2,7 @@ /** * Validation library. * - * $Id: Validation.php 4679 2009-11-10 01:45:52Z isaiah $ + * $Id: Validation.php 4713 2009-12-10 22:25:38Z isaiah $ * * @package Validation * @author Kohana Team @@ -26,12 +26,12 @@ class Validation_Core extends ArrayObject { protected $errors = array(); protected $messages = array(); + // Field labels + protected $labels = array(); + // Fields that are expected to be arrays protected $array_fields = array(); - // Checks if there is data to validate. - protected $submitted; - /** * Creates a new Validation instance. * @@ -52,9 +52,6 @@ class Validation_Core extends ArrayObject { */ public function __construct(array $array) { - // The array is submitted if the array is not empty - $this->submitted = ! empty($array); - parent::__construct($array, ArrayObject::ARRAY_AS_PROPS | ArrayObject::STD_PROP_LIST); } @@ -85,21 +82,6 @@ class Validation_Core extends ArrayObject { return $copy; } - /** - * Test if the data has been submitted. - * - * @return boolean - */ - public function submitted($value = NULL) - { - if (is_bool($value)) - { - $this->submitted = $value; - } - - return $this->submitted; - } - /** * Returns an array of all the field names that have filters, rules, or callbacks. * @@ -196,6 +178,42 @@ class Validation_Core extends ArrayObject { return $this; } + /** + * Sets or overwrites the label name for a field. + * + * @param string field name + * @param string label + * @return $this + */ + public function label($field, $label = NULL) + { + if ($label === NULL AND ($field !== TRUE OR $field !== '*') AND ! isset($this->labels[$field])) + { + // Set the field label to the field name + $this->labels[$field] = ucfirst(preg_replace('/[^\pL]+/u', ' ', $field)); + } + elseif ($label !== NULL) + { + // Set the label for this field + $this->labels[$field] = $label; + } + + return $this; + } + + /** + * Sets labels using an array. + * + * @param array list of field => label names + * @return $this + */ + public function labels(array $labels) + { + $this->labels = $labels + $this->labels; + + return $this; + } + /** * Converts a filter, rule, or callback into a fully-qualified callback array. * @@ -338,6 +356,9 @@ class Validation_Core extends ArrayObject { $rules = func_get_args(); $rules = array_slice($rules, 1); + // Set a default field label + $this->label($field); + if ($field === TRUE) { // Use wildcard @@ -412,6 +433,9 @@ class Validation_Core extends ArrayObject { $callbacks = func_get_args(); $callbacks = array_slice($callbacks, 1); + // Set a default field label + $this->label($field); + if ($field === TRUE) { // Use wildcard @@ -471,9 +495,6 @@ class Validation_Core extends ArrayObject { } } - if ($this->submitted === FALSE) - return FALSE; - foreach ($this->rules as $field => $callbacks) { foreach ($callbacks as $callback) @@ -534,6 +555,7 @@ class Validation_Core extends ArrayObject { if (($result == $is_false)) { + $rule = $is_false ? '!'.$rule : $rule; $this->add_error($field, $rule, $args); // Stop validating this field when an error is found @@ -618,46 +640,6 @@ class Validation_Core extends ArrayObject { return $this; } - /** - * Sets or returns the message for an input. - * - * @chainable - * @param string input key - * @param string message to set - * @return string|object - */ - public function message($input = NULL, $message = NULL) - { - if ($message === NULL) - { - if ($input === NULL) - { - $messages = array(); - $keys = array_keys($this->messages); - - foreach ($keys as $input) - { - $messages[] = $this->message($input); - } - - return implode("\n", $messages); - } - - // Return nothing if no message exists - if (empty($this->messages[$input])) - return ''; - - // Return the HTML message string - return $this->messages[$input]; - } - else - { - $this->messages[$input] = $message; - } - - return $this; - } - /** * Return the errors array. * @@ -677,18 +659,49 @@ class Validation_Core extends ArrayObject { } else { - $errors = array(); foreach ($this->errors as $input => $error) { - // Key for this input error - $key = "$file.$input.$error[0]"; + // Locations to check for error messages + $error_locations = array + ( + "validation/{$file}.{$input}.{$error[0]}", + "validation/{$file}.{$input}.default", + "validation/default.{$error[0]}" + ); + + if (($message = Kohana::message($error_locations[0])) !== $error_locations[0]) + { + // Found a message for this field and error + } + elseif (($message = Kohana::message($error_locations[1])) !== $error_locations[1]) + { + // Found a default message for this field + } + elseif (($message = Kohana::message($error_locations[2])) !== $error_locations[2]) + { + // Found a default message for this error + } + else + { + // No message exists, display the path expected + $message = "validation/{$file}.{$input}.{$error[0]}"; + } - if (($errors[$input] = Kohana::message('validation/'.$key, $error[1])) === $key) + // Start the translation values list + $values = array(':field' => __($this->labels[$input])); + + if ( ! empty($error[1])) { - // Get the default error message - $errors[$input] = Kohana::message("$file.$input.default"); + foreach ($error[1] as $key => $value) + { + // Add each parameter as a numbered value, starting from 1 + $values[':param'.($key + 1)] = __($value); + } } + + // Translate the message using the default language + $errors[$input] = __($message, $values); } return $errors; diff --git a/system/libraries/drivers/Cache/File.php b/system/libraries/drivers/Cache/File.php index fc20c22d..d6ec0378 100644 --- a/system/libraries/drivers/Cache/File.php +++ b/system/libraries/drivers/Cache/File.php @@ -183,7 +183,7 @@ class Cache_File_Driver extends Cache_Driver { // Get the id from the filename list($key, $junk) = explode('~', basename($path), 2); - if (($data = $this->get($key)) !== FALSE) + if (($data = $this->get($key, TRUE)) !== FALSE) { // Add the result to the array $result[$key] = $data; @@ -211,7 +211,7 @@ class Cache_File_Driver extends Cache_Driver { // Remove the cache file if ( ! unlink($path)) { - Kohana::log('error', 'Cache: Unable to delete cache file: '.$path); + Kohana_Log::add('error', 'Cache: Unable to delete cache file: '.$path); $success = FALSE; } } diff --git a/system/libraries/drivers/Cache/Memcache.php b/system/libraries/drivers/Cache/Memcache.php index 636191d4..13d61d82 100644 --- a/system/libraries/drivers/Cache/Memcache.php +++ b/system/libraries/drivers/Cache/Memcache.php @@ -17,7 +17,7 @@ class Cache_Memcache_Driver extends Cache_Driver { public function __construct($config) { if ( ! extension_loaded('memcache')) - throw new Kohana_Exception('The memcache PHP extension must be loaded to use this driver.'); + throw new Cache_Exception('The memcache PHP extension must be loaded to use this driver.'); ini_set('memcache.allow_failover', (isset($config['allow_failover']) AND $config['allow_failover']) ? TRUE : FALSE); @@ -79,7 +79,10 @@ class Cache_Memcache_Driver extends Cache_Driver { if ($single) { - return ($items === FALSE OR count($items) > 0) ? current($items) : NULL; + if ($items === FALSE) + return NULL; + + return (count($items) > 0) ? current($items) : NULL; } else { diff --git a/system/libraries/drivers/Cache/Xcache.php b/system/libraries/drivers/Cache/Xcache.php index ad11e6d7..4c08405e 100644 --- a/system/libraries/drivers/Cache/Xcache.php +++ b/system/libraries/drivers/Cache/Xcache.php @@ -16,7 +16,7 @@ class Cache_Xcache_Driver extends Cache_Driver { public function __construct($config) { if ( ! extension_loaded('xcache')) - throw new Kohana_Exception('The xcache PHP extension must be loaded to use this driver.'); + throw new Cache_Exception('The xcache PHP extension must be loaded to use this driver.'); $this->config = $config; } diff --git a/system/messages/core.php b/system/messages/core.php index 4bf6ee8c..64f897e8 100644 --- a/system/messages/core.php +++ b/system/messages/core.php @@ -8,7 +8,6 @@ $messages = array E_PAGE_NOT_FOUND => __('Page Not Found'), // __('The requested page was not found. It may have moved, been deleted, or archived.'), E_DATABASE_ERROR => __('Database Error'), // __('A database error occurred while performing the requested procedure. Please review the database error below for more information.'), E_RECOVERABLE_ERROR => __('Recoverable Error'), // __('An error was detected which prevented the loading of this page. If this problem persists, please contact the website administrator.'), - E_ERROR => __('Fatal Error'), E_COMPILE_ERROR => __('Fatal Error'), E_CORE_ERROR => __('Fatal Error'), @@ -29,4 +28,10 @@ $messages = array 'driver' => 'driver', 'model' => 'model', 'view' => 'view', -); \ No newline at end of file +); + +// E_DEPRECATED is only defined in PHP >= 5.3.0 +if (defined('E_DEPRECATED')) +{ + $messages['errors'][E_DEPRECATED] = __('Deprecated'); +} \ No newline at end of file diff --git a/system/messages/validation/default.php b/system/messages/validation/default.php new file mode 100644 index 00000000..2c59fa06 --- /dev/null +++ b/system/messages/validation/default.php @@ -0,0 +1,17 @@ + 'The :field field is required', + 'length' => 'The :field field must be between :param1 and :param2 characters long', + 'depends_on' => 'The :field field requires the :param1 field', + 'matches' => 'The :field field must be the same as :param1', + 'email' => 'The :field field must be a valid email address', + 'decimal' => 'The :field field must be a decimal with :param1 places', + 'digit' => 'The :field field must be a digit', + 'in_array' => 'The :field field must be one of the available options', + 'alpha_numeric' => 'The :field field must consist only of alphabetical or numeric characters', + 'alpha_dash ' => 'The :field field must consist only of alphabetical, numeric, underscore and dash characters', + 'numeric ' => 'The :field field must be a valid number', + 'url' => 'The :field field must be a valid url', + 'phone' => 'The :field field must be a valid phone number', +); diff --git a/system/vendor/Markdown.php b/system/vendor/Markdown.php deleted file mode 100644 index b649f6c1..00000000 --- a/system/vendor/Markdown.php +++ /dev/null @@ -1,2909 +0,0 @@ - -# -# Original Markdown -# Copyright (c) 2004-2006 John Gruber -# -# - - -define( 'MARKDOWN_VERSION', "1.0.1m" ); # Sat 21 Jun 2008 -define( 'MARKDOWNEXTRA_VERSION', "1.2.3" ); # Wed 31 Dec 2008 - - -# -# Global default settings: -# - -# Change to ">" for HTML output -@define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />"); - -# Define the width of a tab for code blocks. -@define( 'MARKDOWN_TAB_WIDTH', 4 ); - -# Optional title attribute for footnote links and backlinks. -@define( 'MARKDOWN_FN_LINK_TITLE', "" ); -@define( 'MARKDOWN_FN_BACKLINK_TITLE', "" ); - -# Optional class attribute for footnote links and backlinks. -@define( 'MARKDOWN_FN_LINK_CLASS', "" ); -@define( 'MARKDOWN_FN_BACKLINK_CLASS', "" ); - - -# -# WordPress settings: -# - -# Change to false to remove Markdown from posts and/or comments. -@define( 'MARKDOWN_WP_POSTS', true ); -@define( 'MARKDOWN_WP_COMMENTS', true ); - - - -### Standard Function Interface ### - -@define( 'MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser' ); - -function Markdown($text) { -# -# Initialize the parser and return the result of its transform method. -# - # Setup static parser variable. - static $parser; - if (!isset($parser)) { - $parser_class = MARKDOWN_PARSER_CLASS; - $parser = new $parser_class; - } - - # Transform text using parser. - return $parser->transform($text); -} - - -### WordPress Plugin Interface ### - -/* -Plugin Name: Markdown Extra -Plugin URI: http://www.michelf.com/projects/php-markdown/ -Description: Markdown syntax allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by John Gruber. More... -Version: 1.2.2 -Author: Michel Fortin -Author URI: http://www.michelf.com/ -*/ - -if (isset($wp_version)) { - # More details about how it works here: - # - - # Post content and excerpts - # - Remove WordPress paragraph generator. - # - Run Markdown on excerpt, then remove all tags. - # - Add paragraph tag around the excerpt, but remove it for the excerpt rss. - if (MARKDOWN_WP_POSTS) { - remove_filter('the_content', 'wpautop'); - remove_filter('the_content_rss', 'wpautop'); - remove_filter('the_excerpt', 'wpautop'); - add_filter('the_content', 'mdwp_MarkdownPost', 6); - add_filter('the_content_rss', 'mdwp_MarkdownPost', 6); - add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6); - add_filter('get_the_excerpt', 'trim', 7); - add_filter('the_excerpt', 'mdwp_add_p'); - add_filter('the_excerpt_rss', 'mdwp_strip_p'); - - remove_filter('content_save_pre', 'balanceTags', 50); - remove_filter('excerpt_save_pre', 'balanceTags', 50); - add_filter('the_content', 'balanceTags', 50); - add_filter('get_the_excerpt', 'balanceTags', 9); - } - - # Add a footnote id prefix to posts when inside a loop. - function mdwp_MarkdownPost($text) { - static $parser; - if (!$parser) { - $parser_class = MARKDOWN_PARSER_CLASS; - $parser = new $parser_class; - } - if (is_single() || is_page() || is_feed()) { - $parser->fn_id_prefix = ""; - } else { - $parser->fn_id_prefix = get_the_ID() . "."; - } - return $parser->transform($text); - } - - # Comments - # - Remove WordPress paragraph generator. - # - Remove WordPress auto-link generator. - # - Scramble important tags before passing them to the kses filter. - # - Run Markdown on excerpt then remove paragraph tags. - if (MARKDOWN_WP_COMMENTS) { - remove_filter('comment_text', 'wpautop', 30); - remove_filter('comment_text', 'make_clickable'); - add_filter('pre_comment_content', 'Markdown', 6); - add_filter('pre_comment_content', 'mdwp_hide_tags', 8); - add_filter('pre_comment_content', 'mdwp_show_tags', 12); - add_filter('get_comment_text', 'Markdown', 6); - add_filter('get_comment_excerpt', 'Markdown', 6); - add_filter('get_comment_excerpt', 'mdwp_strip_p', 7); - - global $mdwp_hidden_tags, $mdwp_placeholders; - $mdwp_hidden_tags = explode(' ', - '

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

    '.$text.'

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

    \n\n

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

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

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

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

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

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

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

    foo@exampl - # e.com

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

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

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

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

    $value

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

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

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

    $backlink

    "; - } - - $text .= "
  • \n"; - $text .= $footnote . "\n"; - $text .= "
  • \n\n"; - } - - $text .= "\n"; - $text .= "
    "; - } - return $text; - } - function _appendFootnotes_callback($matches) { - $node_id = $this->fn_id_prefix . $matches[1]; - - # Create footnote marker only if it has a corresponding footnote *and* - # the footnote hasn't been used by another marker. - if (isset($this->footnotes[$node_id])) { - # Transfert footnote content to the ordered list. - $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id]; - unset($this->footnotes[$node_id]); - - $num = $this->footnote_counter++; - $attr = " rel=\"footnote\""; - if ($this->fn_link_class != "") { - $class = $this->fn_link_class; - $class = $this->encodeAttribute($class); - $attr .= " class=\"$class\""; - } - if ($this->fn_link_title != "") { - $title = $this->fn_link_title; - $title = $this->encodeAttribute($title); - $attr .= " title=\"$title\""; - } - - $attr = str_replace("%%", $num, $attr); - $node_id = $this->encodeAttribute($node_id); - - return - "". - "$num". - ""; - } - - return "[^".$matches[1]."]"; - } - - - ### Abbreviations ### - - function stripAbbreviations($text) { - # - # Strips abbreviations from text, stores titles in hash references. - # - $less_than_tab = $this->tab_width - 1; - - # Link defs are in the form: [id]*: url "optional title" - $text = preg_replace_callback('{ - ^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?: # abbr_id = $1 - (.*) # text = $2 (no blank lines allowed) - }xm', - array(&$this, '_stripAbbreviations_callback'), - $text); - return $text; - } - function _stripAbbreviations_callback($matches) { - $abbr_word = $matches[1]; - $abbr_desc = $matches[2]; - if ($this->abbr_word_re) - $this->abbr_word_re .= '|'; - $this->abbr_word_re .= preg_quote($abbr_word); - $this->abbr_desciptions[$abbr_word] = trim($abbr_desc); - return ''; # String that will replace the block - } - - - function doAbbreviations($text) { - # - # Find defined abbreviations in text and wrap them in elements. - # - if ($this->abbr_word_re) { - // cannot use the /x modifier because abbr_word_re may - // contain significant spaces: - $text = preg_replace_callback('{'. - '(?abbr_word_re.')'. - '(?![\w\x1A])'. - '}', - array(&$this, '_doAbbreviations_callback'), $text); - } - return $text; - } - function _doAbbreviations_callback($matches) { - $abbr = $matches[0]; - if (isset($this->abbr_desciptions[$abbr])) { - $desc = $this->abbr_desciptions[$abbr]; - if (empty($desc)) { - return $this->hashPart("$abbr"); - } else { - $desc = $this->encodeAttribute($desc); - return $this->hashPart("$abbr"); - } - } else { - return $matches[0]; - } - } - -} - - -/* - -PHP Markdown Extra -================== - -Description ------------ - -This is a PHP port of the original Markdown formatter written in Perl -by John Gruber. This special "Extra" version of PHP Markdown features -further enhancements to the syntax for making additional constructs -such as tables and definition list. - -Markdown is a text-to-HTML filter; it translates an easy-to-read / -easy-to-write structured text format into HTML. Markdown's text format -is most similar to that of plain text email, and supports features such -as headers, *emphasis*, code blocks, blockquotes, and links. - -Markdown's syntax is designed not as a generic markup language, but -specifically to serve as a front-end to (X)HTML. You can use span-level -HTML tags anywhere in a Markdown document, and you can use block level -HTML tags (like
    and as well). - -For more information about Markdown's syntax, see: - - - - -Bugs ----- - -To file bug reports please send email to: - - - -Please include with your report: (1) the example input; (2) the output you -expected; (3) the output Markdown actually produced. - - -Version History ---------------- - -See the readme file for detailed release notes for this version. - - -Copyright and License ---------------------- - -PHP Markdown & Extra -Copyright (c) 2004-2008 Michel Fortin - -All rights reserved. - -Based on Markdown -Copyright (c) 2003-2006 John Gruber - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -* Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -* Neither the name "Markdown" nor the names of its contributors may - be used to endorse or promote products derived from this software - without specific prior written permission. - -This software is provided by the copyright holders and contributors "as -is" and any express or implied warranties, including, but not limited -to, the implied warranties of merchantability and fitness for a -particular purpose are disclaimed. In no event shall the copyright owner -or contributors be liable for any direct, indirect, incidental, special, -exemplary, or consequential damages (including, but not limited to, -procurement of substitute goods or services; loss of use, data, or -profits; or business interruption) however caused and on any theory of -liability, whether in contract, strict liability, or tort (including -negligence or otherwise) arising in any way out of the use of this -software, even if advised of the possibility of such damage. - -*/ -?> \ No newline at end of file -- cgit v1.2.3 From 32d25dafd5b033338b6a9bb8c7c53edab462543a Mon Sep 17 00:00:00 2001 From: Bharat Mediratta Date: Fri, 25 Dec 2009 21:05:39 -0800 Subject: Prevent form::dropdown from overzealously escaping ampersands by applying this diff: http://dev.kohanaframework.org/attachments/1490/form.diff Upstream ticket: http://dev.kohanaframework.org/issues/2463 --- system/helpers/form.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'system/helpers') diff --git a/system/helpers/form.php b/system/helpers/form.php index 4225b1b6..b7c60c24 100644 --- a/system/helpers/form.php +++ b/system/helpers/form.php @@ -246,14 +246,14 @@ class form_Core { $inner_key = (string) $inner_key; $sel = in_array($inner_key, $selected) ? ' selected="selected"' : ''; - $input .= ''."\n"; + $input .= ''."\n"; } $input .= ''."\n"; } else { $sel = in_array($key, $selected) ? ' selected="selected"' : ''; - $input .= ''."\n"; + $input .= ''."\n"; } } $input .= ''; -- cgit v1.2.3