Initial commit

This commit is contained in:
mareksebera 2014-09-10 20:20:58 +02:00
commit 3b93da31de
1004 changed files with 265840 additions and 0 deletions

View file

@ -0,0 +1,416 @@
<?php
/**
* CakeNumber Utility.
*
* Methods to make numbers more readable.
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Utility
* @since CakePHP(tm) v 0.10.0.1076
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* Number helper library.
*
* Methods to make numbers more readable.
*
* @package Cake.Utility
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html
*/
class CakeNumber {
/**
* Currencies supported by the helper. You can add additional currency formats
* with CakeNumber::addFormat
*
* @var array
*/
protected static $_currencies = array(
'AUD' => array(
'wholeSymbol' => '$', 'wholePosition' => 'before', 'fractionSymbol' => 'c', 'fractionPosition' => 'after',
'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
'fractionExponent' => 2
),
'CAD' => array(
'wholeSymbol' => '$', 'wholePosition' => 'before', 'fractionSymbol' => 'c', 'fractionPosition' => 'after',
'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
'fractionExponent' => 2
),
'USD' => array(
'wholeSymbol' => '$', 'wholePosition' => 'before', 'fractionSymbol' => 'c', 'fractionPosition' => 'after',
'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
'fractionExponent' => 2
),
'EUR' => array(
'wholeSymbol' => '€', 'wholePosition' => 'before', 'fractionSymbol' => false, 'fractionPosition' => 'after',
'zero' => 0, 'places' => 2, 'thousands' => '.', 'decimals' => ',', 'negative' => '()', 'escape' => true,
'fractionExponent' => 0
),
'GBP' => array(
'wholeSymbol' => '£', 'wholePosition' => 'before', 'fractionSymbol' => 'p', 'fractionPosition' => 'after',
'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
'fractionExponent' => 2
),
'JPY' => array(
'wholeSymbol' => '¥', 'wholePosition' => 'before', 'fractionSymbol' => false, 'fractionPosition' => 'after',
'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
'fractionExponent' => 0
),
);
/**
* Default options for currency formats
*
* @var array
*/
protected static $_currencyDefaults = array(
'wholeSymbol' => '', 'wholePosition' => 'before', 'fractionSymbol' => false, 'fractionPosition' => 'after',
'zero' => '0', 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true,
'fractionExponent' => 2
);
/**
* Default currency used by CakeNumber::currency()
*
* @var string
*/
protected static $_defaultCurrency = 'USD';
/**
* If native number_format() should be used. If >= PHP5.4
*
* @var bool
*/
protected static $_numberFormatSupport = null;
/**
* Formats a number with a level of precision.
*
* @param float $value A floating point number.
* @param int $precision The precision of the returned number.
* @return float Formatted float.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::precision
*/
public static function precision($value, $precision = 3) {
return sprintf("%01.{$precision}f", $value);
}
/**
* Returns a formatted-for-humans file size.
*
* @param int $size Size in bytes
* @return string Human readable size
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize
*/
public static function toReadableSize($size) {
switch (true) {
case $size < 1024:
return __dn('cake', '%d Byte', '%d Bytes', $size, $size);
case round($size / 1024) < 1024:
return __d('cake', '%s KB', self::precision($size / 1024, 0));
case round($size / 1024 / 1024, 2) < 1024:
return __d('cake', '%s MB', self::precision($size / 1024 / 1024, 2));
case round($size / 1024 / 1024 / 1024, 2) < 1024:
return __d('cake', '%s GB', self::precision($size / 1024 / 1024 / 1024, 2));
default:
return __d('cake', '%s TB', self::precision($size / 1024 / 1024 / 1024 / 1024, 2));
}
}
/**
* Converts filesize from human readable string to bytes
*
* @param string $size Size in human readable string like '5MB', '5M', '500B', '50kb' etc.
* @param mixed $default Value to be returned when invalid size was used, for example 'Unknown type'
* @return mixed Number of bytes as integer on success, `$default` on failure if not false
* @throws CakeException On invalid Unit type.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::fromReadableSize
*/
public static function fromReadableSize($size, $default = false) {
if (ctype_digit($size)) {
return (int)$size;
}
$size = strtoupper($size);
$l = -2;
$i = array_search(substr($size, -2), array('KB', 'MB', 'GB', 'TB', 'PB'));
if ($i === false) {
$l = -1;
$i = array_search(substr($size, -1), array('K', 'M', 'G', 'T', 'P'));
}
if ($i !== false) {
$size = substr($size, 0, $l);
return $size * pow(1024, $i + 1);
}
if (substr($size, -1) === 'B' && ctype_digit(substr($size, 0, -1))) {
$size = substr($size, 0, -1);
return (int)$size;
}
if ($default !== false) {
return $default;
}
throw new CakeException(__d('cake_dev', 'No unit type.'));
}
/**
* Formats a number into a percentage string.
*
* Options:
*
* - `multiply`: Multiply the input value by 100 for decimal percentages.
*
* @param float $value A floating point number
* @param int $precision The precision of the returned number
* @param array $options Options
* @return string Percentage string
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toPercentage
*/
public static function toPercentage($value, $precision = 2, $options = array()) {
$options += array('multiply' => false);
if ($options['multiply']) {
$value *= 100;
}
return self::precision($value, $precision) . '%';
}
/**
* Formats a number into a currency format.
*
* @param float $value A floating point number
* @param int $options If integer then places, if string then before, if (,.-) then use it
* or array with places and before keys
* @return string formatted number
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::format
*/
public static function format($value, $options = false) {
$places = 0;
if (is_int($options)) {
$places = $options;
}
$separators = array(',', '.', '-', ':');
$before = $after = null;
if (is_string($options) && !in_array($options, $separators)) {
$before = $options;
}
$thousands = ',';
if (!is_array($options) && in_array($options, $separators)) {
$thousands = $options;
}
$decimals = '.';
if (!is_array($options) && in_array($options, $separators)) {
$decimals = $options;
}
$escape = true;
if (is_array($options)) {
$defaults = array('before' => '$', 'places' => 2, 'thousands' => ',', 'decimals' => '.');
$options += $defaults;
extract($options);
}
$value = self::_numberFormat($value, $places, '.', '');
$out = $before . self::_numberFormat($value, $places, $decimals, $thousands) . $after;
if ($escape) {
return h($out);
}
return $out;
}
/**
* Formats a number into a currency format to show deltas (signed differences in value).
*
* ### Options
*
* - `places` - Number of decimal places to use. ie. 2
* - `fractionExponent` - Fraction exponent of this specific currency. Defaults to 2.
* - `before` - The string to place before whole numbers. ie. '['
* - `after` - The string to place after decimal numbers. ie. ']'
* - `thousands` - Thousands separator ie. ','
* - `decimals` - Decimal separator symbol ie. '.'
*
* @param float $value A floating point number
* @param array $options Options list.
* @return string formatted delta
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::formatDelta
*/
public static function formatDelta($value, $options = array()) {
$places = isset($options['places']) ? $options['places'] : 0;
$value = self::_numberFormat($value, $places, '.', '');
$sign = $value > 0 ? '+' : '';
$options['before'] = isset($options['before']) ? $options['before'] . $sign : $sign;
return self::format($value, $options);
}
/**
* Alternative number_format() to accommodate multibyte decimals and thousands < PHP 5.4
*
* @param float $value Value to format.
* @param int $places Decimal places to use.
* @param string $decimals Decimal position string.
* @param string $thousands Thousands separator string.
* @return string
*/
protected static function _numberFormat($value, $places = 0, $decimals = '.', $thousands = ',') {
if (!isset(self::$_numberFormatSupport)) {
self::$_numberFormatSupport = version_compare(PHP_VERSION, '5.4.0', '>=');
}
if (self::$_numberFormatSupport) {
return number_format($value, $places, $decimals, $thousands);
}
$value = number_format($value, $places, '.', '');
$after = '';
$foundDecimal = strpos($value, '.');
if ($foundDecimal !== false) {
$after = substr($value, $foundDecimal);
$value = substr($value, 0, $foundDecimal);
}
while (($foundThousand = preg_replace('/(\d+)(\d\d\d)/', '\1 \2', $value)) !== $value) {
$value = $foundThousand;
}
$value .= $after;
return strtr($value, array(' ' => $thousands, '.' => $decimals));
}
/**
* Formats a number into a currency format.
*
* ### Options
*
* - `wholeSymbol` - The currency symbol to use for whole numbers,
* greater than 1, or less than -1.
* - `wholePosition` - The position the whole symbol should be placed
* valid options are 'before' & 'after'.
* - `fractionSymbol` - The currency symbol to use for fractional numbers.
* - `fractionPosition` - The position the fraction symbol should be placed
* valid options are 'before' & 'after'.
* - `before` - The currency symbol to place before whole numbers
* ie. '$'. `before` is an alias for `wholeSymbol`.
* - `after` - The currency symbol to place after decimal numbers
* ie. 'c'. Set to boolean false to use no decimal symbol.
* eg. 0.35 => $0.35. `after` is an alias for `fractionSymbol`
* - `zero` - The text to use for zero values, can be a
* string or a number. ie. 0, 'Free!'
* - `places` - Number of decimal places to use. ie. 2
* - `fractionExponent` - Fraction exponent of this specific currency. Defaults to 2.
* - `thousands` - Thousands separator ie. ','
* - `decimals` - Decimal separator symbol ie. '.'
* - `negative` - Symbol for negative numbers. If equal to '()',
* the number will be wrapped with ( and )
* - `escape` - Should the output be escaped for html special characters.
* The default value for this option is controlled by the currency settings.
* By default all currencies contain utf-8 symbols and don't need this changed. If you require
* non HTML encoded symbols you will need to update the settings with the correct bytes.
*
* @param float $value Value to format.
* @param string $currency Shortcut to default options. Valid values are
* 'USD', 'EUR', 'GBP', otherwise set at least 'before' and 'after' options.
* @param array $options Options list.
* @return string Number formatted as a currency.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::currency
*/
public static function currency($value, $currency = null, $options = array()) {
$defaults = self::$_currencyDefaults;
if ($currency === null) {
$currency = self::defaultCurrency();
}
if (isset(self::$_currencies[$currency])) {
$defaults = self::$_currencies[$currency];
} elseif (is_string($currency)) {
$options['before'] = $currency;
}
$options += $defaults;
if (isset($options['before']) && $options['before'] !== '') {
$options['wholeSymbol'] = $options['before'];
}
if (isset($options['after']) && !$options['after'] !== '') {
$options['fractionSymbol'] = $options['after'];
}
$result = $options['before'] = $options['after'] = null;
$symbolKey = 'whole';
$value = (float)$value;
if (!$value) {
if ($options['zero'] !== 0) {
return $options['zero'];
}
} elseif ($value < 1 && $value > -1) {
if ($options['fractionSymbol'] !== false) {
$multiply = pow(10, $options['fractionExponent']);
$value = $value * $multiply;
$options['places'] = null;
$symbolKey = 'fraction';
}
}
$position = $options[$symbolKey . 'Position'] !== 'after' ? 'before' : 'after';
$options[$position] = $options[$symbolKey . 'Symbol'];
$abs = abs($value);
$result = self::format($abs, $options);
if ($value < 0) {
if ($options['negative'] === '()') {
$result = '(' . $result . ')';
} else {
$result = $options['negative'] . $result;
}
}
return $result;
}
/**
* Add a currency format to the Number helper. Makes reusing
* currency formats easier.
*
* {{{ $number->addFormat('NOK', array('before' => 'Kr. ')); }}}
*
* You can now use `NOK` as a shortform when formatting currency amounts.
*
* {{{ $number->currency($value, 'NOK'); }}}
*
* Added formats are merged with the defaults defined in CakeNumber::$_currencyDefaults
* See CakeNumber::currency() for more information on the various options and their function.
*
* @param string $formatName The format name to be used in the future.
* @param array $options The array of options for this format.
* @return void
* @see NumberHelper::currency()
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::addFormat
*/
public static function addFormat($formatName, $options) {
self::$_currencies[$formatName] = $options + self::$_currencyDefaults;
}
/**
* Getter/setter for default currency
*
* @param string $currency Default currency string used by currency() if $currency argument is not provided
* @return string Currency
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::defaultCurrency
*/
public static function defaultCurrency($currency = null) {
if ($currency) {
self::$_defaultCurrency = $currency;
}
return self::$_defaultCurrency;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,371 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Utility
* @since CakePHP(tm) v 0.9.2
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* Included libraries.
*/
App::uses('Model', 'Model');
App::uses('AppModel', 'Model');
App::uses('ConnectionManager', 'Model');
/**
* Class Collections.
*
* A repository for class objects, each registered with a key.
* If you try to add an object with the same key twice, nothing will come of it.
* If you need a second instance of an object, give it another key.
*
* @package Cake.Utility
*/
class ClassRegistry {
/**
* Names of classes with their objects.
*
* @var array
*/
protected $_objects = array();
/**
* Names of class names mapped to the object in the registry.
*
* @var array
*/
protected $_map = array();
/**
* Default constructor parameter settings, indexed by type
*
* @var array
*/
protected $_config = array();
/**
* Return a singleton instance of the ClassRegistry.
*
* @return ClassRegistry instance
*/
public static function getInstance() {
static $instance = array();
if (!$instance) {
$instance[0] = new ClassRegistry();
}
return $instance[0];
}
/**
* Loads a class, registers the object in the registry and returns instance of the object. ClassRegistry::init()
* is used as a factory for models, and handle correct injecting of settings, that assist in testing.
*
* Examples
* Simple Use: Get a Post model instance ```ClassRegistry::init('Post');```
*
* Expanded: ```array('class' => 'ClassName', 'alias' => 'AliasNameStoredInTheRegistry');```
*
* Model Classes can accept optional ```array('id' => $id, 'table' => $table, 'ds' => $ds, 'alias' => $alias);```
*
* When $class is a numeric keyed array, multiple class instances will be stored in the registry,
* no instance of the object will be returned
* {{{
* array(
* array('class' => 'ClassName', 'alias' => 'AliasNameStoredInTheRegistry'),
* array('class' => 'ClassName', 'alias' => 'AliasNameStoredInTheRegistry'),
* array('class' => 'ClassName', 'alias' => 'AliasNameStoredInTheRegistry')
* );
* }}}
*
* @param string|array $class as a string or a single key => value array instance will be created,
* stored in the registry and returned.
* @param bool $strict if set to true it will return false if the class was not found instead
* of trying to create an AppModel
* @return object instance of ClassName.
* @throws CakeException when you try to construct an interface or abstract class.
*/
public static function init($class, $strict = false) {
$_this = ClassRegistry::getInstance();
if (is_array($class)) {
$objects = $class;
if (!isset($class[0])) {
$objects = array($class);
}
} else {
$objects = array(array('class' => $class));
}
$defaults = array();
if (isset($_this->_config['Model'])) {
$defaults = $_this->_config['Model'];
}
$count = count($objects);
$availableDs = null;
foreach ($objects as $settings) {
if (is_numeric($settings)) {
trigger_error(__d('cake_dev', '(ClassRegistry::init() Attempted to create instance of a class with a numeric name'), E_USER_WARNING);
return false;
}
if (is_array($settings)) {
$pluginPath = null;
$settings += $defaults;
$class = $settings['class'];
list($plugin, $class) = pluginSplit($class);
if ($plugin) {
$pluginPath = $plugin . '.';
$settings['plugin'] = $plugin;
}
if (empty($settings['alias'])) {
$settings['alias'] = $class;
}
$alias = $settings['alias'];
$model = $_this->_duplicate($alias, $class);
if ($model) {
$_this->map($alias, $class);
return $model;
}
App::uses($plugin . 'AppModel', $pluginPath . 'Model');
App::uses($class, $pluginPath . 'Model');
if (class_exists($class) || interface_exists($class)) {
$reflection = new ReflectionClass($class);
if ($reflection->isAbstract() || $reflection->isInterface()) {
throw new CakeException(__d('cake_dev', 'Cannot create instance of %s, as it is abstract or is an interface', $class));
}
$testing = isset($settings['testing']) ? $settings['testing'] : false;
if ($testing) {
$settings['ds'] = 'test';
$defaultProperties = $reflection->getDefaultProperties();
if (isset($defaultProperties['useDbConfig'])) {
$useDbConfig = $defaultProperties['useDbConfig'];
if ($availableDs === null) {
$availableDs = array_keys(ConnectionManager::enumConnectionObjects());
}
if (in_array('test_' . $useDbConfig, $availableDs)) {
$useDbConfig = 'test_' . $useDbConfig;
}
if (strpos($useDbConfig, 'test') === 0) {
$settings['ds'] = $useDbConfig;
}
}
}
if ($reflection->getConstructor()) {
$instance = $reflection->newInstance($settings);
} else {
$instance = $reflection->newInstance();
}
if ($strict && !$instance instanceof Model) {
$instance = null;
}
}
if (!isset($instance)) {
$appModel = 'AppModel';
if ($strict) {
return false;
} elseif ($plugin && class_exists($plugin . 'AppModel')) {
$appModel = $plugin . 'AppModel';
}
if (!empty($appModel)) {
$settings['name'] = $class;
$instance = new $appModel($settings);
}
if (!isset($instance)) {
trigger_error(__d('cake_dev', '(ClassRegistry::init() could not create instance of %s', $class), E_USER_WARNING);
return false;
}
}
$_this->map($alias, $class);
}
}
if ($count > 1) {
return true;
}
return $instance;
}
/**
* Add $object to the registry, associating it with the name $key.
*
* @param string $key Key for the object in registry
* @param object $object Object to store
* @return bool True if the object was written, false if $key already exists
*/
public static function addObject($key, $object) {
$_this = ClassRegistry::getInstance();
$key = Inflector::underscore($key);
if (!isset($_this->_objects[$key])) {
$_this->_objects[$key] = $object;
return true;
}
return false;
}
/**
* Remove object which corresponds to given key.
*
* @param string $key Key of object to remove from registry
* @return void
*/
public static function removeObject($key) {
$_this = ClassRegistry::getInstance();
$key = Inflector::underscore($key);
if (isset($_this->_objects[$key])) {
unset($_this->_objects[$key]);
}
}
/**
* Returns true if given key is present in the ClassRegistry.
*
* @param string $key Key to look for
* @return bool true if key exists in registry, false otherwise
*/
public static function isKeySet($key) {
$_this = ClassRegistry::getInstance();
$key = Inflector::underscore($key);
return isset($_this->_objects[$key]) || isset($_this->_map[$key]);
}
/**
* Get all keys from the registry.
*
* @return array Set of keys stored in registry
*/
public static function keys() {
return array_keys(ClassRegistry::getInstance()->_objects);
}
/**
* Return object which corresponds to given key.
*
* @param string $key Key of object to look for
* @return mixed Object stored in registry or boolean false if the object does not exist.
*/
public static function getObject($key) {
$_this = ClassRegistry::getInstance();
$key = Inflector::underscore($key);
$return = false;
if (isset($_this->_objects[$key])) {
$return = $_this->_objects[$key];
} else {
$key = $_this->_getMap($key);
if (isset($_this->_objects[$key])) {
$return = $_this->_objects[$key];
}
}
return $return;
}
/**
* Sets the default constructor parameter for an object type
*
* @param string $type Type of object. If this parameter is omitted, defaults to "Model"
* @param array $param The parameter that will be passed to object constructors when objects
* of $type are created
* @return mixed Void if $param is being set. Otherwise, if only $type is passed, returns
* the previously-set value of $param, or null if not set.
*/
public static function config($type, $param = array()) {
$_this = ClassRegistry::getInstance();
if (empty($param) && is_array($type)) {
$param = $type;
$type = 'Model';
} elseif ($param === null) {
unset($_this->_config[$type]);
} elseif (empty($param) && is_string($type)) {
return isset($_this->_config[$type]) ? $_this->_config[$type] : null;
}
if (isset($_this->_config[$type]['testing'])) {
$param['testing'] = true;
}
$_this->_config[$type] = $param;
}
/**
* Checks to see if $alias is a duplicate $class Object
*
* @param string $alias Alias to check.
* @param string $class Class name.
* @return bool
*/
protected function &_duplicate($alias, $class) {
$duplicate = false;
if ($this->isKeySet($alias)) {
$model = $this->getObject($alias);
if (is_object($model) && ($model instanceof $class || $model->alias === $class)) {
$duplicate = $model;
}
unset($model);
}
return $duplicate;
}
/**
* Add a key name pair to the registry to map name to class in the registry.
*
* @param string $key Key to include in map
* @param string $name Key that is being mapped
* @return void
*/
public static function map($key, $name) {
$_this = ClassRegistry::getInstance();
$key = Inflector::underscore($key);
$name = Inflector::underscore($name);
if (!isset($_this->_map[$key])) {
$_this->_map[$key] = $name;
}
}
/**
* Get all keys from the map in the registry.
*
* @return array Keys of registry's map
*/
public static function mapKeys() {
return array_keys(ClassRegistry::getInstance()->_map);
}
/**
* Return the name of a class in the registry.
*
* @param string $key Key to find in map
* @return string Mapped value
*/
protected function _getMap($key) {
if (isset($this->_map[$key])) {
return $this->_map[$key];
}
}
/**
* Flushes all objects from the ClassRegistry.
*
* @return void
*/
public static function flush() {
$_this = ClassRegistry::getInstance();
$_this->_objects = array();
$_this->_map = array();
}
}

View file

@ -0,0 +1,854 @@
<?php
/**
* Framework debugging and PHP error-handling class
*
* Provides enhanced logging, stack traces, and rendering debug views
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Utility
* @since CakePHP(tm) v 1.2.4560
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CakeLog', 'Log');
App::uses('String', 'Utility');
/**
* Provide custom logging and error handling.
*
* Debugger overrides PHP's default error handling to provide stack traces and enhanced logging
*
* @package Cake.Utility
* @link http://book.cakephp.org/2.0/en/development/debugging.html#debugger-class
*/
class Debugger {
/**
* A list of errors generated by the application.
*
* @var array
*/
public $errors = array();
/**
* The current output format.
*
* @var string
*/
protected $_outputFormat = 'js';
/**
* Templates used when generating trace or error strings. Can be global or indexed by the format
* value used in $_outputFormat.
*
* @var string
*/
protected $_templates = array(
'log' => array(
'trace' => '{:reference} - {:path}, line {:line}',
'error' => "{:error} ({:code}): {:description} in [{:file}, line {:line}]"
),
'js' => array(
'error' => '',
'info' => '',
'trace' => '<pre class="stack-trace">{:trace}</pre>',
'code' => '',
'context' => '',
'links' => array(),
'escapeContext' => true,
),
'html' => array(
'trace' => '<pre class="cake-error trace"><b>Trace</b> <p>{:trace}</p></pre>',
'context' => '<pre class="cake-error context"><b>Context</b> <p>{:context}</p></pre>',
'escapeContext' => true,
),
'txt' => array(
'error' => "{:error}: {:code} :: {:description} on line {:line} of {:path}\n{:info}",
'code' => '',
'info' => ''
),
'base' => array(
'traceLine' => '{:reference} - {:path}, line {:line}',
'trace' => "Trace:\n{:trace}\n",
'context' => "Context:\n{:context}\n",
)
);
/**
* Holds current output data when outputFormat is false.
*
* @var string
*/
protected $_data = array();
/**
* Constructor.
*
*/
public function __construct() {
$docRef = ini_get('docref_root');
if (empty($docRef) && function_exists('ini_set')) {
ini_set('docref_root', 'http://php.net/');
}
if (!defined('E_RECOVERABLE_ERROR')) {
define('E_RECOVERABLE_ERROR', 4096);
}
$e = '<pre class="cake-error">';
$e .= '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-trace\')';
$e .= '.style.display = (document.getElementById(\'{:id}-trace\').style.display == ';
$e .= '\'none\' ? \'\' : \'none\');"><b>{:error}</b> ({:code})</a>: {:description} ';
$e .= '[<b>{:path}</b>, line <b>{:line}</b>]';
$e .= '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">';
$e .= '{:links}{:info}</div>';
$e .= '</pre>';
$this->_templates['js']['error'] = $e;
$t = '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">';
$t .= '{:context}{:code}{:trace}</div>';
$this->_templates['js']['info'] = $t;
$links = array();
$link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-code\')';
$link .= '.style.display = (document.getElementById(\'{:id}-code\').style.display == ';
$link .= '\'none\' ? \'\' : \'none\')">Code</a>';
$links['code'] = $link;
$link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-context\')';
$link .= '.style.display = (document.getElementById(\'{:id}-context\').style.display == ';
$link .= '\'none\' ? \'\' : \'none\')">Context</a>';
$links['context'] = $link;
$this->_templates['js']['links'] = $links;
$this->_templates['js']['context'] = '<pre id="{:id}-context" class="cake-context" ';
$this->_templates['js']['context'] .= 'style="display: none;">{:context}</pre>';
$this->_templates['js']['code'] = '<pre id="{:id}-code" class="cake-code-dump" ';
$this->_templates['js']['code'] .= 'style="display: none;">{:code}</pre>';
$e = '<pre class="cake-error"><b>{:error}</b> ({:code}) : {:description} ';
$e .= '[<b>{:path}</b>, line <b>{:line}]</b></pre>';
$this->_templates['html']['error'] = $e;
$this->_templates['html']['context'] = '<pre class="cake-context"><b>Context</b> ';
$this->_templates['html']['context'] .= '<p>{:context}</p></pre>';
}
/**
* Returns a reference to the Debugger singleton object instance.
*
* @param string $class Debugger class name.
* @return object
*/
public static function getInstance($class = null) {
static $instance = array();
if (!empty($class)) {
if (!$instance || strtolower($class) != strtolower(get_class($instance[0]))) {
$instance[0] = new $class();
}
}
if (!$instance) {
$instance[0] = new Debugger();
}
return $instance[0];
}
/**
* Recursively formats and outputs the contents of the supplied variable.
*
* @param mixed $var the variable to dump
* @param int $depth The depth to output to. Defaults to 3.
* @return void
* @see Debugger::exportVar()
* @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::dump
*/
public static function dump($var, $depth = 3) {
pr(self::exportVar($var, $depth));
}
/**
* Creates an entry in the log file. The log entry will contain a stack trace from where it was called.
* as well as export the variable using exportVar. By default the log is written to the debug log.
*
* @param mixed $var Variable or content to log
* @param int $level type of log to use. Defaults to LOG_DEBUG
* @param int $depth The depth to output to. Defaults to 3.
* @return void
* @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::log
*/
public static function log($var, $level = LOG_DEBUG, $depth = 3) {
$source = self::trace(array('start' => 1)) . "\n";
CakeLog::write($level, "\n" . $source . self::exportVar($var, $depth));
}
/**
* Overrides PHP's default error handling.
*
* @param int $code Code of error
* @param string $description Error description
* @param string $file File on which error occurred
* @param int $line Line that triggered the error
* @param array $context Context
* @return bool true if error was handled
* @deprecated Will be removed in 3.0. This function is superseded by Debugger::outputError().
*/
public static function showError($code, $description, $file = null, $line = null, $context = null) {
$self = Debugger::getInstance();
if (empty($file)) {
$file = '[internal]';
}
if (empty($line)) {
$line = '??';
}
$info = compact('code', 'description', 'file', 'line');
if (!in_array($info, $self->errors)) {
$self->errors[] = $info;
} else {
return;
}
switch ($code) {
case E_PARSE:
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
$error = 'Fatal Error';
$level = LOG_ERR;
break;
case E_WARNING:
case E_USER_WARNING:
case E_COMPILE_WARNING:
case E_RECOVERABLE_ERROR:
$error = 'Warning';
$level = LOG_WARNING;
break;
case E_NOTICE:
case E_USER_NOTICE:
$error = 'Notice';
$level = LOG_NOTICE;
break;
case E_DEPRECATED:
case E_USER_DEPRECATED:
$error = 'Deprecated';
$level = LOG_NOTICE;
break;
default:
return;
}
$data = compact(
'level', 'error', 'code', 'description', 'file', 'path', 'line', 'context'
);
echo $self->outputError($data);
if ($error === 'Fatal Error') {
exit();
}
return true;
}
/**
* Outputs a stack trace based on the supplied options.
*
* ### Options
*
* - `depth` - The number of stack frames to return. Defaults to 999
* - `format` - The format you want the return. Defaults to the currently selected format. If
* format is 'array' or 'points' the return will be an array.
* - `args` - Should arguments for functions be shown? If true, the arguments for each method call
* will be displayed.
* - `start` - The stack frame to start generating a trace from. Defaults to 0
*
* @param array $options Format for outputting stack trace
* @return mixed Formatted stack trace
* @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::trace
*/
public static function trace($options = array()) {
$self = Debugger::getInstance();
$defaults = array(
'depth' => 999,
'format' => $self->_outputFormat,
'args' => false,
'start' => 0,
'scope' => null,
'exclude' => array('call_user_func_array', 'trigger_error')
);
$options = Hash::merge($defaults, $options);
$backtrace = debug_backtrace();
$count = count($backtrace);
$back = array();
$_trace = array(
'line' => '??',
'file' => '[internal]',
'class' => null,
'function' => '[main]'
);
for ($i = $options['start']; $i < $count && $i < $options['depth']; $i++) {
$trace = array_merge(array('file' => '[internal]', 'line' => '??'), $backtrace[$i]);
$signature = $reference = '[main]';
if (isset($backtrace[$i + 1])) {
$next = array_merge($_trace, $backtrace[$i + 1]);
$signature = $reference = $next['function'];
if (!empty($next['class'])) {
$signature = $next['class'] . '::' . $next['function'];
$reference = $signature . '(';
if ($options['args'] && isset($next['args'])) {
$args = array();
foreach ($next['args'] as $arg) {
$args[] = Debugger::exportVar($arg);
}
$reference .= implode(', ', $args);
}
$reference .= ')';
}
}
if (in_array($signature, $options['exclude'])) {
continue;
}
if ($options['format'] === 'points' && $trace['file'] !== '[internal]') {
$back[] = array('file' => $trace['file'], 'line' => $trace['line']);
} elseif ($options['format'] === 'array') {
$back[] = $trace;
} else {
if (isset($self->_templates[$options['format']]['traceLine'])) {
$tpl = $self->_templates[$options['format']]['traceLine'];
} else {
$tpl = $self->_templates['base']['traceLine'];
}
$trace['path'] = self::trimPath($trace['file']);
$trace['reference'] = $reference;
unset($trace['object'], $trace['args']);
$back[] = String::insert($tpl, $trace, array('before' => '{:', 'after' => '}'));
}
}
if ($options['format'] === 'array' || $options['format'] === 'points') {
return $back;
}
return implode("\n", $back);
}
/**
* Shortens file paths by replacing the application base path with 'APP', and the CakePHP core
* path with 'CORE'.
*
* @param string $path Path to shorten
* @return string Normalized path
*/
public static function trimPath($path) {
if (!defined('CAKE_CORE_INCLUDE_PATH') || !defined('APP')) {
return $path;
}
if (strpos($path, APP) === 0) {
return str_replace(APP, 'APP' . DS, $path);
} elseif (strpos($path, CAKE_CORE_INCLUDE_PATH) === 0) {
return str_replace(CAKE_CORE_INCLUDE_PATH, 'CORE', $path);
} elseif (strpos($path, ROOT) === 0) {
return str_replace(ROOT, 'ROOT', $path);
}
return $path;
}
/**
* Grabs an excerpt from a file and highlights a given line of code.
*
* Usage:
*
* `Debugger::excerpt('/path/to/file', 100, 4);`
*
* The above would return an array of 8 items. The 4th item would be the provided line,
* and would be wrapped in `<span class="code-highlight"></span>`. All of the lines
* are processed with highlight_string() as well, so they have basic PHP syntax highlighting
* applied.
*
* @param string $file Absolute path to a PHP file
* @param int $line Line number to highlight
* @param int $context Number of lines of context to extract above and below $line
* @return array Set of lines highlighted
* @see http://php.net/highlight_string
* @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::excerpt
*/
public static function excerpt($file, $line, $context = 2) {
$lines = array();
if (!file_exists($file)) {
return array();
}
$data = file_get_contents($file);
if (empty($data)) {
return $lines;
}
if (strpos($data, "\n") !== false) {
$data = explode("\n", $data);
}
if (!isset($data[$line])) {
return $lines;
}
for ($i = $line - ($context + 1); $i < $line + $context; $i++) {
if (!isset($data[$i])) {
continue;
}
$string = str_replace(array("\r\n", "\n"), "", self::_highlight($data[$i]));
if ($i == $line) {
$lines[] = '<span class="code-highlight">' . $string . '</span>';
} else {
$lines[] = $string;
}
}
return $lines;
}
/**
* Wraps the highlight_string function in case the server API does not
* implement the function as it is the case of the HipHop interpreter
*
* @param string $str the string to convert
* @return string
*/
protected static function _highlight($str) {
if (function_exists('hphp_log') || function_exists('hphp_gettid')) {
return htmlentities($str);
}
$added = false;
if (strpos($str, '<?php') === false) {
$added = true;
$str = "<?php \n" . $str;
}
$highlight = highlight_string($str, true);
if ($added) {
$highlight = str_replace(
'&lt;?php&nbsp;<br />',
'',
$highlight
);
}
return $highlight;
}
/**
* Converts a variable to a string for debug output.
*
* *Note:* The following keys will have their contents
* replaced with `*****`:
*
* - password
* - login
* - host
* - database
* - port
* - prefix
* - schema
*
* This is done to protect database credentials, which could be accidentally
* shown in an error message if CakePHP is deployed in development mode.
*
* @param string $var Variable to convert
* @param int $depth The depth to output to. Defaults to 3.
* @return string Variable as a formatted string
* @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::exportVar
*/
public static function exportVar($var, $depth = 3) {
return self::_export($var, $depth, 0);
}
/**
* Protected export function used to keep track of indentation and recursion.
*
* @param mixed $var The variable to dump.
* @param int $depth The remaining depth.
* @param int $indent The current indentation level.
* @return string The dumped variable.
*/
protected static function _export($var, $depth, $indent) {
switch (self::getType($var)) {
case 'boolean':
return ($var) ? 'true' : 'false';
case 'integer':
return '(int) ' . $var;
case 'float':
return '(float) ' . $var;
case 'string':
if (trim($var) === '') {
return "''";
}
return "'" . $var . "'";
case 'array':
return self::_array($var, $depth - 1, $indent + 1);
case 'resource':
return strtolower(gettype($var));
case 'null':
return 'null';
case 'unknown':
return 'unknown';
default:
return self::_object($var, $depth - 1, $indent + 1);
}
}
/**
* Export an array type object. Filters out keys used in datasource configuration.
*
* The following keys are replaced with ***'s
*
* - password
* - login
* - host
* - database
* - port
* - prefix
* - schema
*
* @param array $var The array to export.
* @param int $depth The current depth, used for recursion tracking.
* @param int $indent The current indentation level.
* @return string Exported array.
*/
protected static function _array(array $var, $depth, $indent) {
$secrets = array(
'password' => '*****',
'login' => '*****',
'host' => '*****',
'database' => '*****',
'port' => '*****',
'prefix' => '*****',
'schema' => '*****'
);
$replace = array_intersect_key($secrets, $var);
$var = $replace + $var;
$out = "array(";
$break = $end = null;
if (!empty($var)) {
$break = "\n" . str_repeat("\t", $indent);
$end = "\n" . str_repeat("\t", $indent - 1);
}
$vars = array();
if ($depth >= 0) {
foreach ($var as $key => $val) {
// Sniff for globals as !== explodes in < 5.4
if ($key === 'GLOBALS' && is_array($val) && isset($val['GLOBALS'])) {
$val = '[recursion]';
} elseif ($val !== $var) {
$val = self::_export($val, $depth, $indent);
}
$vars[] = $break . self::exportVar($key) .
' => ' .
$val;
}
} else {
$vars[] = $break . '[maximum depth reached]';
}
return $out . implode(',', $vars) . $end . ')';
}
/**
* Handles object to string conversion.
*
* @param string $var Object to convert
* @param int $depth The current depth, used for tracking recursion.
* @param int $indent The current indentation level.
* @return string
* @see Debugger::exportVar()
*/
protected static function _object($var, $depth, $indent) {
$out = '';
$props = array();
$className = get_class($var);
$out .= 'object(' . $className . ') {';
if ($depth > 0) {
$end = "\n" . str_repeat("\t", $indent - 1);
$break = "\n" . str_repeat("\t", $indent);
$objectVars = get_object_vars($var);
foreach ($objectVars as $key => $value) {
$value = self::_export($value, $depth - 1, $indent);
$props[] = "$key => " . $value;
}
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
$ref = new ReflectionObject($var);
$filters = array(
ReflectionProperty::IS_PROTECTED => 'protected',
ReflectionProperty::IS_PRIVATE => 'private',
);
foreach ($filters as $filter => $visibility) {
$reflectionProperties = $ref->getProperties($filter);
foreach ($reflectionProperties as $reflectionProperty) {
$reflectionProperty->setAccessible(true);
$property = $reflectionProperty->getValue($var);
$value = self::_export($property, $depth - 1, $indent);
$key = $reflectionProperty->name;
$props[] = sprintf('[%s] %s => %s', $visibility, $key, $value);
}
}
}
$out .= $break . implode($break, $props) . $end;
}
$out .= '}';
return $out;
}
/**
* Get/Set the output format for Debugger error rendering.
*
* @param string $format The format you want errors to be output as.
* Leave null to get the current format.
* @return mixed Returns null when setting. Returns the current format when getting.
* @throws CakeException when choosing a format that doesn't exist.
*/
public static function outputAs($format = null) {
$self = Debugger::getInstance();
if ($format === null) {
return $self->_outputFormat;
}
if ($format !== false && !isset($self->_templates[$format])) {
throw new CakeException(__d('cake_dev', 'Invalid Debugger output format.'));
}
$self->_outputFormat = $format;
}
/**
* Add an output format or update a format in Debugger.
*
* `Debugger::addFormat('custom', $data);`
*
* Where $data is an array of strings that use String::insert() variable
* replacement. The template vars should be in a `{:id}` style.
* An error formatter can have the following keys:
*
* - 'error' - Used for the container for the error message. Gets the following template
* variables: `id`, `error`, `code`, `description`, `path`, `line`, `links`, `info`
* - 'info' - A combination of `code`, `context` and `trace`. Will be set with
* the contents of the other template keys.
* - 'trace' - The container for a stack trace. Gets the following template
* variables: `trace`
* - 'context' - The container element for the context variables.
* Gets the following templates: `id`, `context`
* - 'links' - An array of HTML links that are used for creating links to other resources.
* Typically this is used to create javascript links to open other sections.
* Link keys, are: `code`, `context`, `help`. See the js output format for an
* example.
* - 'traceLine' - Used for creating lines in the stacktrace. Gets the following
* template variables: `reference`, `path`, `line`
*
* Alternatively if you want to use a custom callback to do all the formatting, you can use
* the callback key, and provide a callable:
*
* `Debugger::addFormat('custom', array('callback' => array($foo, 'outputError'));`
*
* The callback can expect two parameters. The first is an array of all
* the error data. The second contains the formatted strings generated using
* the other template strings. Keys like `info`, `links`, `code`, `context` and `trace`
* will be present depending on the other templates in the format type.
*
* @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
* straight HTML output, or 'txt' for unformatted text.
* @param array $strings Template strings, or a callback to be used for the output format.
* @return The resulting format string set.
*/
public static function addFormat($format, array $strings) {
$self = Debugger::getInstance();
if (isset($self->_templates[$format])) {
if (isset($strings['links'])) {
$self->_templates[$format]['links'] = array_merge(
$self->_templates[$format]['links'],
$strings['links']
);
unset($strings['links']);
}
$self->_templates[$format] = array_merge($self->_templates[$format], $strings);
} else {
$self->_templates[$format] = $strings;
}
return $self->_templates[$format];
}
/**
* Switches output format, updates format strings.
* Can be used to switch the active output format:
*
* @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
* straight HTML output, or 'txt' for unformatted text.
* @param array $strings Template strings to be used for the output format.
* @return string
* @deprecated Use Debugger::outputAs() and Debugger::addFormat(). Will be removed
* in 3.0
*/
public static function output($format = null, $strings = array()) {
$self = Debugger::getInstance();
$data = null;
if ($format === null) {
return Debugger::outputAs();
}
if (!empty($strings)) {
return Debugger::addFormat($format, $strings);
}
if ($format === true && !empty($self->_data)) {
$data = $self->_data;
$self->_data = array();
$format = false;
}
Debugger::outputAs($format);
return $data;
}
/**
* Takes a processed array of data from an error and displays it in the chosen format.
*
* @param string $data Data to output.
* @return void
*/
public function outputError($data) {
$defaults = array(
'level' => 0,
'error' => 0,
'code' => 0,
'description' => '',
'file' => '',
'line' => 0,
'context' => array(),
'start' => 2,
);
$data += $defaults;
$files = $this->trace(array('start' => $data['start'], 'format' => 'points'));
$code = '';
$file = null;
if (isset($files[0]['file'])) {
$file = $files[0];
} elseif (isset($files[1]['file'])) {
$file = $files[1];
}
if ($file) {
$code = $this->excerpt($file['file'], $file['line'] - 1, 1);
}
$trace = $this->trace(array('start' => $data['start'], 'depth' => '20'));
$insertOpts = array('before' => '{:', 'after' => '}');
$context = array();
$links = array();
$info = '';
foreach ((array)$data['context'] as $var => $value) {
$context[] = "\${$var} = " . $this->exportVar($value, 3);
}
switch ($this->_outputFormat) {
case false:
$this->_data[] = compact('context', 'trace') + $data;
return;
case 'log':
$this->log(compact('context', 'trace') + $data);
return;
}
$data['trace'] = $trace;
$data['id'] = 'cakeErr' . uniqid();
$tpl = array_merge($this->_templates['base'], $this->_templates[$this->_outputFormat]);
if (isset($tpl['links'])) {
foreach ($tpl['links'] as $key => $val) {
$links[$key] = String::insert($val, $data, $insertOpts);
}
}
if (!empty($tpl['escapeContext'])) {
$context = h($context);
}
$infoData = compact('code', 'context', 'trace');
foreach ($infoData as $key => $value) {
if (empty($value) || !isset($tpl[$key])) {
continue;
}
if (is_array($value)) {
$value = implode("\n", $value);
}
$info .= String::insert($tpl[$key], array($key => $value) + $data, $insertOpts);
}
$links = implode(' ', $links);
if (isset($tpl['callback']) && is_callable($tpl['callback'])) {
return call_user_func($tpl['callback'], $data, compact('links', 'info'));
}
echo String::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts);
}
/**
* Get the type of the given variable. Will return the class name
* for objects.
*
* @param mixed $var The variable to get the type of
* @return string The type of variable.
*/
public static function getType($var) {
if (is_object($var)) {
return get_class($var);
}
if ($var === null) {
return 'null';
}
if (is_string($var)) {
return 'string';
}
if (is_array($var)) {
return 'array';
}
if (is_int($var)) {
return 'integer';
}
if (is_bool($var)) {
return 'boolean';
}
if (is_float($var)) {
return 'float';
}
if (is_resource($var)) {
return 'resource';
}
return 'unknown';
}
/**
* Verifies that the application's salt and cipher seed value has been changed from the default value.
*
* @return void
*/
public static function checkSecurityKeys() {
if (Configure::read('Security.salt') === 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi') {
trigger_error(__d('cake_dev', 'Please change the value of %s in %s to a salt value specific to your application.', '\'Security.salt\'', 'APP/Config/core.php'), E_USER_NOTICE);
}
if (Configure::read('Security.cipherSeed') === '76859309657453542496749683645') {
trigger_error(__d('cake_dev', 'Please change the value of %s in %s to a numeric (digits only) seed value specific to your application.', '\'Security.cipherSeed\'', 'APP/Config/core.php'), E_USER_NOTICE);
}
}
}

615
lib/Cake/Utility/File.php Normal file
View file

@ -0,0 +1,615 @@
<?php
/**
* Convenience class for reading, writing and appending to files.
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Utility
* @since CakePHP(tm) v 0.2.9
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Folder', 'Utility');
/**
* Convenience class for reading, writing and appending to files.
*
* @package Cake.Utility
*/
class File {
/**
* Folder object of the file
*
* @var Folder
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::$Folder
*/
public $Folder = null;
/**
* File name
*
* @var string
* http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::$name
*/
public $name = null;
/**
* File info
*
* @var array
* http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::$info
*/
public $info = array();
/**
* Holds the file handler resource if the file is opened
*
* @var resource
* http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::$handle
*/
public $handle = null;
/**
* Enable locking for file reading and writing
*
* @var bool
* http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::$lock
*/
public $lock = null;
/**
* Path property
*
* Current file's absolute path
*
* @var mixed
* http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::$path
*/
public $path = null;
/**
* Constructor
*
* @param string $path Path to file
* @param bool $create Create file if it does not exist (if true)
* @param int $mode Mode to apply to the folder holding the file
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File
*/
public function __construct($path, $create = false, $mode = 0755) {
$this->Folder = new Folder(dirname($path), $create, $mode);
if (!is_dir($path)) {
$this->name = basename($path);
}
$this->pwd();
$create && !$this->exists() && $this->safe($path) && $this->create();
}
/**
* Closes the current file if it is opened
*/
public function __destruct() {
$this->close();
}
/**
* Creates the file.
*
* @return bool Success
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::create
*/
public function create() {
$dir = $this->Folder->pwd();
if (is_dir($dir) && is_writable($dir) && !$this->exists()) {
if (touch($this->path)) {
return true;
}
}
return false;
}
/**
* Opens the current file with a given $mode
*
* @param string $mode A valid 'fopen' mode string (r|w|a ...)
* @param bool $force If true then the file will be re-opened even if its already opened, otherwise it won't
* @return bool True on success, false on failure
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::open
*/
public function open($mode = 'r', $force = false) {
if (!$force && is_resource($this->handle)) {
return true;
}
if ($this->exists() === false) {
if ($this->create() === false) {
return false;
}
}
$this->handle = fopen($this->path, $mode);
if (is_resource($this->handle)) {
return true;
}
return false;
}
/**
* Return the contents of this file as a string.
*
* @param string $bytes where to start
* @param string $mode A `fread` compatible mode.
* @param bool $force If true then the file will be re-opened even if its already opened, otherwise it won't
* @return mixed string on success, false on failure
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::read
*/
public function read($bytes = false, $mode = 'rb', $force = false) {
if ($bytes === false && $this->lock === null) {
return file_get_contents($this->path);
}
if ($this->open($mode, $force) === false) {
return false;
}
if ($this->lock !== null && flock($this->handle, LOCK_SH) === false) {
return false;
}
if (is_int($bytes)) {
return fread($this->handle, $bytes);
}
$data = '';
while (!feof($this->handle)) {
$data .= fgets($this->handle, 4096);
}
if ($this->lock !== null) {
flock($this->handle, LOCK_UN);
}
if ($bytes === false) {
$this->close();
}
return trim($data);
}
/**
* Sets or gets the offset for the currently opened file.
*
* @param int|bool $offset The $offset in bytes to seek. If set to false then the current offset is returned.
* @param int $seek PHP Constant SEEK_SET | SEEK_CUR | SEEK_END determining what the $offset is relative to
* @return mixed True on success, false on failure (set mode), false on failure or integer offset on success (get mode)
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::offset
*/
public function offset($offset = false, $seek = SEEK_SET) {
if ($offset === false) {
if (is_resource($this->handle)) {
return ftell($this->handle);
}
} elseif ($this->open() === true) {
return fseek($this->handle, $offset, $seek) === 0;
}
return false;
}
/**
* Prepares a ASCII string for writing. Converts line endings to the
* correct terminator for the current platform. If Windows, "\r\n" will be used,
* all other platforms will use "\n"
*
* @param string $data Data to prepare for writing.
* @param bool $forceWindows If true forces usage Windows newline string.
* @return string The with converted line endings.
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::prepare
*/
public static function prepare($data, $forceWindows = false) {
$lineBreak = "\n";
if (DIRECTORY_SEPARATOR === '\\' || $forceWindows === true) {
$lineBreak = "\r\n";
}
return strtr($data, array("\r\n" => $lineBreak, "\n" => $lineBreak, "\r" => $lineBreak));
}
/**
* Write given data to this file.
*
* @param string $data Data to write to this File.
* @param string $mode Mode of writing. {@link http://php.net/fwrite See fwrite()}.
* @param string $force Force the file to open
* @return bool Success
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::write
*/
public function write($data, $mode = 'w', $force = false) {
$success = false;
if ($this->open($mode, $force) === true) {
if ($this->lock !== null) {
if (flock($this->handle, LOCK_EX) === false) {
return false;
}
}
if (fwrite($this->handle, $data) !== false) {
$success = true;
}
if ($this->lock !== null) {
flock($this->handle, LOCK_UN);
}
}
return $success;
}
/**
* Append given data string to this file.
*
* @param string $data Data to write
* @param string $force Force the file to open
* @return bool Success
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::append
*/
public function append($data, $force = false) {
return $this->write($data, 'a', $force);
}
/**
* Closes the current file if it is opened.
*
* @return bool True if closing was successful or file was already closed, otherwise false
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::close
*/
public function close() {
if (!is_resource($this->handle)) {
return true;
}
return fclose($this->handle);
}
/**
* Deletes the file.
*
* @return bool Success
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::delete
*/
public function delete() {
if (is_resource($this->handle)) {
fclose($this->handle);
$this->handle = null;
}
if ($this->exists()) {
return unlink($this->path);
}
return false;
}
/**
* Returns the file info as an array with the following keys:
*
* - dirname
* - basename
* - extension
* - filename
* - filesize
* - mime
*
* @return array File information.
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::info
*/
public function info() {
if (!$this->info) {
$this->info = pathinfo($this->path);
}
if (!isset($this->info['filename'])) {
$this->info['filename'] = $this->name();
}
if (!isset($this->info['filesize'])) {
$this->info['filesize'] = $this->size();
}
if (!isset($this->info['mime'])) {
$this->info['mime'] = $this->mime();
}
return $this->info;
}
/**
* Returns the file extension.
*
* @return string The file extension
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::ext
*/
public function ext() {
if (!$this->info) {
$this->info();
}
if (isset($this->info['extension'])) {
return $this->info['extension'];
}
return false;
}
/**
* Returns the file name without extension.
*
* @return string The file name without extension.
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::name
*/
public function name() {
if (!$this->info) {
$this->info();
}
if (isset($this->info['extension'])) {
return basename($this->name, '.' . $this->info['extension']);
} elseif ($this->name) {
return $this->name;
}
return false;
}
/**
* Makes file name safe for saving
*
* @param string $name The name of the file to make safe if different from $this->name
* @param string $ext The name of the extension to make safe if different from $this->ext
* @return string ext The extension of the file
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::safe
*/
public function safe($name = null, $ext = null) {
if (!$name) {
$name = $this->name;
}
if (!$ext) {
$ext = $this->ext();
}
return preg_replace("/(?:[^\w\.-]+)/", "_", basename($name, $ext));
}
/**
* Get md5 Checksum of file with previous check of Filesize
*
* @param int|bool $maxsize in MB or true to force
* @return string|false md5 Checksum {@link http://php.net/md5_file See md5_file()}, or false in case of an error
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::md5
*/
public function md5($maxsize = 5) {
if ($maxsize === true) {
return md5_file($this->path);
}
$size = $this->size();
if ($size && $size < ($maxsize * 1024) * 1024) {
return md5_file($this->path);
}
return false;
}
/**
* Returns the full path of the file.
*
* @return string Full path to the file
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::pwd
*/
public function pwd() {
if ($this->path === null) {
$this->path = $this->Folder->slashTerm($this->Folder->pwd()) . $this->name;
}
return $this->path;
}
/**
* Returns true if the file exists.
*
* @return bool True if it exists, false otherwise
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::exists
*/
public function exists() {
$this->clearStatCache();
return (file_exists($this->path) && is_file($this->path));
}
/**
* Returns the "chmod" (permissions) of the file.
*
* @return string|false Permissions for the file, or false in case of an error
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::perms
*/
public function perms() {
if ($this->exists()) {
return substr(sprintf('%o', fileperms($this->path)), -4);
}
return false;
}
/**
* Returns the file size
*
* @return int|false Size of the file in bytes, or false in case of an error
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::size
*/
public function size() {
if ($this->exists()) {
return filesize($this->path);
}
return false;
}
/**
* Returns true if the file is writable.
*
* @return bool True if it's writable, false otherwise
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::writable
*/
public function writable() {
return is_writable($this->path);
}
/**
* Returns true if the File is executable.
*
* @return bool True if it's executable, false otherwise
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::executable
*/
public function executable() {
return is_executable($this->path);
}
/**
* Returns true if the file is readable.
*
* @return bool True if file is readable, false otherwise
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::readable
*/
public function readable() {
return is_readable($this->path);
}
/**
* Returns the file's owner.
*
* @return int|false The file owner, or false in case of an error
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::owner
*/
public function owner() {
if ($this->exists()) {
return fileowner($this->path);
}
return false;
}
/**
* Returns the file's group.
*
* @return int|false The file group, or false in case of an error
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::group
*/
public function group() {
if ($this->exists()) {
return filegroup($this->path);
}
return false;
}
/**
* Returns last access time.
*
* @return int|false Timestamp of last access time, or false in case of an error
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::lastAccess
*/
public function lastAccess() {
if ($this->exists()) {
return fileatime($this->path);
}
return false;
}
/**
* Returns last modified time.
*
* @return int|false Timestamp of last modification, or false in case of an error
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::lastChange
*/
public function lastChange() {
if ($this->exists()) {
return filemtime($this->path);
}
return false;
}
/**
* Returns the current folder.
*
* @return Folder Current folder
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::Folder
*/
public function folder() {
return $this->Folder;
}
/**
* Copy the File to $dest
*
* @param string $dest Destination for the copy
* @param bool $overwrite Overwrite $dest if exists
* @return bool Success
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::copy
*/
public function copy($dest, $overwrite = true) {
if (!$this->exists() || is_file($dest) && !$overwrite) {
return false;
}
return copy($this->path, $dest);
}
/**
* Get the mime type of the file. Uses the finfo extension if
* its available, otherwise falls back to mime_content_type
*
* @return false|string The mimetype of the file, or false if reading fails.
*/
public function mime() {
if (!$this->exists()) {
return false;
}
if (function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$finfo = finfo_file($finfo, $this->pwd());
if (!$finfo) {
return false;
}
list($type) = explode(';', $finfo);
return $type;
}
if (function_exists('mime_content_type')) {
return mime_content_type($this->pwd());
}
return false;
}
/**
* Clear PHP's internal stat cache
*
* For 5.3 onwards it's possible to clear cache for just a single file. Passing true
* will clear all the stat cache.
*
* @param bool $all Clear all cache or not
* @return void
*/
public function clearStatCache($all = false) {
if ($all === false && version_compare(PHP_VERSION, '5.3.0') >= 0) {
return clearstatcache(true, $this->path);
}
return clearstatcache();
}
/**
* Searches for a given text and replaces the text if found.
*
* @param string|array $search Text(s) to search for.
* @param string|array $replace Text(s) to replace with.
* @return bool Success
*/
public function replaceText($search, $replace) {
if (!$this->open('r+')) {
return false;
}
if ($this->lock !== null) {
if (flock($this->handle, LOCK_EX) === false) {
return false;
}
}
$replaced = $this->write(str_replace($search, $replace, $this->read()), 'w', true);
if ($this->lock !== null) {
flock($this->handle, LOCK_UN);
}
$this->close();
return $replaced;
}
}

833
lib/Cake/Utility/Folder.php Normal file
View file

@ -0,0 +1,833 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Utility
* @since CakePHP(tm) v 0.2.9
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* Folder structure browser, lists folders and files.
* Provides an Object interface for Common directory related tasks.
*
* @package Cake.Utility
*/
class Folder {
/**
* Default scheme for Folder::copy
* Recursively merges subfolders with the same name
*
* @var string
*/
const MERGE = 'merge';
/**
* Overwrite scheme for Folder::copy
* subfolders with the same name will be replaced
*
* @var string
*/
const OVERWRITE = 'overwrite';
/**
* Skip scheme for Folder::copy
* if a subfolder with the same name exists it will be skipped
*
* @var string
*/
const SKIP = 'skip';
/**
* Path to Folder.
*
* @var string
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::$path
*/
public $path = null;
/**
* Sortedness. Whether or not list results
* should be sorted by name.
*
* @var bool
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::$sort
*/
public $sort = false;
/**
* Mode to be used on create. Does nothing on windows platforms.
*
* @var int
* http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::$mode
*/
public $mode = 0755;
/**
* Holds messages from last method.
*
* @var array
*/
protected $_messages = array();
/**
* Holds errors from last method.
*
* @var array
*/
protected $_errors = array();
/**
* Holds array of complete directory paths.
*
* @var array
*/
protected $_directories;
/**
* Holds array of complete file paths.
*
* @var array
*/
protected $_files;
/**
* Constructor.
*
* @param string $path Path to folder
* @param bool $create Create folder if not found
* @param string|bool $mode Mode (CHMOD) to apply to created folder, false to ignore
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder
*/
public function __construct($path = false, $create = false, $mode = false) {
if (empty($path)) {
$path = TMP;
}
if ($mode) {
$this->mode = $mode;
}
if (!file_exists($path) && $create === true) {
$this->create($path, $this->mode);
}
if (!Folder::isAbsolute($path)) {
$path = realpath($path);
}
if (!empty($path)) {
$this->cd($path);
}
}
/**
* Return current path.
*
* @return string Current path
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::pwd
*/
public function pwd() {
return $this->path;
}
/**
* Change directory to $path.
*
* @param string $path Path to the directory to change to
* @return string The new path. Returns false on failure
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::cd
*/
public function cd($path) {
$path = $this->realpath($path);
if (is_dir($path)) {
return $this->path = $path;
}
return false;
}
/**
* Returns an array of the contents of the current directory.
* The returned array holds two arrays: One of directories and one of files.
*
* @param bool $sort Whether you want the results sorted, set this and the sort property
* to false to get unsorted results.
* @param array|bool $exceptions Either an array or boolean true will not grab dot files
* @param bool $fullPath True returns the full path
* @return mixed Contents of current directory as an array, an empty array on failure
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::read
*/
public function read($sort = true, $exceptions = false, $fullPath = false) {
$dirs = $files = array();
if (!$this->pwd()) {
return array($dirs, $files);
}
if (is_array($exceptions)) {
$exceptions = array_flip($exceptions);
}
$skipHidden = isset($exceptions['.']) || $exceptions === true;
try {
$iterator = new DirectoryIterator($this->path);
} catch (Exception $e) {
return array($dirs, $files);
}
foreach ($iterator as $item) {
if ($item->isDot()) {
continue;
}
$name = $item->getFileName();
if ($skipHidden && $name[0] === '.' || isset($exceptions[$name])) {
continue;
}
if ($fullPath) {
$name = $item->getPathName();
}
if ($item->isDir()) {
$dirs[] = $name;
} else {
$files[] = $name;
}
}
if ($sort || $this->sort) {
sort($dirs);
sort($files);
}
return array($dirs, $files);
}
/**
* Returns an array of all matching files in current directory.
*
* @param string $regexpPattern Preg_match pattern (Defaults to: .*)
* @param bool $sort Whether results should be sorted.
* @return array Files that match given pattern
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::find
*/
public function find($regexpPattern = '.*', $sort = false) {
list(, $files) = $this->read($sort);
return array_values(preg_grep('/^' . $regexpPattern . '$/i', $files));
}
/**
* Returns an array of all matching files in and below current directory.
*
* @param string $pattern Preg_match pattern (Defaults to: .*)
* @param bool $sort Whether results should be sorted.
* @return array Files matching $pattern
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::findRecursive
*/
public function findRecursive($pattern = '.*', $sort = false) {
if (!$this->pwd()) {
return array();
}
$startsOn = $this->path;
$out = $this->_findRecursive($pattern, $sort);
$this->cd($startsOn);
return $out;
}
/**
* Private helper function for findRecursive.
*
* @param string $pattern Pattern to match against
* @param bool $sort Whether results should be sorted.
* @return array Files matching pattern
*/
protected function _findRecursive($pattern, $sort = false) {
list($dirs, $files) = $this->read($sort);
$found = array();
foreach ($files as $file) {
if (preg_match('/^' . $pattern . '$/i', $file)) {
$found[] = Folder::addPathElement($this->path, $file);
}
}
$start = $this->path;
foreach ($dirs as $dir) {
$this->cd(Folder::addPathElement($start, $dir));
$found = array_merge($found, $this->findRecursive($pattern, $sort));
}
return $found;
}
/**
* Returns true if given $path is a Windows path.
*
* @param string $path Path to check
* @return bool true if windows path, false otherwise
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::isWindowsPath
*/
public static function isWindowsPath($path) {
return (preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) === '\\\\');
}
/**
* Returns true if given $path is an absolute path.
*
* @param string $path Path to check
* @return bool true if path is absolute.
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::isAbsolute
*/
public static function isAbsolute($path) {
return !empty($path) && ($path[0] === '/' || preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) === '\\\\');
}
/**
* Returns a correct set of slashes for given $path. (\\ for Windows paths and / for other paths.)
*
* @param string $path Path to check
* @return string Set of slashes ("\\" or "/")
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::normalizePath
*/
public static function normalizePath($path) {
return Folder::correctSlashFor($path);
}
/**
* Returns a correct set of slashes for given $path. (\\ for Windows paths and / for other paths.)
*
* @param string $path Path to check
* @return string Set of slashes ("\\" or "/")
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::correctSlashFor
*/
public static function correctSlashFor($path) {
return (Folder::isWindowsPath($path)) ? '\\' : '/';
}
/**
* Returns $path with added terminating slash (corrected for Windows or other OS).
*
* @param string $path Path to check
* @return string Path with ending slash
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::slashTerm
*/
public static function slashTerm($path) {
if (Folder::isSlashTerm($path)) {
return $path;
}
return $path . Folder::correctSlashFor($path);
}
/**
* Returns $path with $element added, with correct slash in-between.
*
* @param string $path Path
* @param string|array $element Element to add at end of path
* @return string Combined path
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::addPathElement
*/
public static function addPathElement($path, $element) {
$element = (array)$element;
array_unshift($element, rtrim($path, DS));
return implode(DS, $element);
}
/**
* Returns true if the File is in a given CakePath.
*
* @param string $path The path to check.
* @return bool
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::inCakePath
*/
public function inCakePath($path = '') {
$dir = substr(Folder::slashTerm(ROOT), 0, -1);
$newdir = $dir . $path;
return $this->inPath($newdir);
}
/**
* Returns true if the File is in given path.
*
* @param string $path The path to check that the current pwd() resides with in.
* @param bool $reverse Reverse the search, check that pwd() resides within $path.
* @return bool
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::inPath
*/
public function inPath($path = '', $reverse = false) {
$dir = Folder::slashTerm($path);
$current = Folder::slashTerm($this->pwd());
if (!$reverse) {
$return = preg_match('/^(.*)' . preg_quote($dir, '/') . '(.*)/', $current);
} else {
$return = preg_match('/^(.*)' . preg_quote($current, '/') . '(.*)/', $dir);
}
return (bool)$return;
}
/**
* Change the mode on a directory structure recursively. This includes changing the mode on files as well.
*
* @param string $path The path to chmod
* @param int $mode octal value 0755
* @param bool $recursive chmod recursively, set to false to only change the current directory.
* @param array $exceptions array of files, directories to skip
* @return bool Returns TRUE on success, FALSE on failure
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::chmod
*/
public function chmod($path, $mode = false, $recursive = true, $exceptions = array()) {
if (!$mode) {
$mode = $this->mode;
}
if ($recursive === false && is_dir($path)) {
//@codingStandardsIgnoreStart
if (@chmod($path, intval($mode, 8))) {
//@codingStandardsIgnoreEnd
$this->_messages[] = __d('cake_dev', '%s changed to %s', $path, $mode);
return true;
}
$this->_errors[] = __d('cake_dev', '%s NOT changed to %s', $path, $mode);
return false;
}
if (is_dir($path)) {
$paths = $this->tree($path);
foreach ($paths as $type) {
foreach ($type as $fullpath) {
$check = explode(DS, $fullpath);
$count = count($check);
if (in_array($check[$count - 1], $exceptions)) {
continue;
}
//@codingStandardsIgnoreStart
if (@chmod($fullpath, intval($mode, 8))) {
//@codingStandardsIgnoreEnd
$this->_messages[] = __d('cake_dev', '%s changed to %s', $fullpath, $mode);
} else {
$this->_errors[] = __d('cake_dev', '%s NOT changed to %s', $fullpath, $mode);
}
}
}
if (empty($this->_errors)) {
return true;
}
}
return false;
}
/**
* Returns an array of nested directories and files in each directory
*
* @param string $path the directory path to build the tree from
* @param array|bool $exceptions Either an array of files/folder to exclude
* or boolean true to not grab dot files/folders
* @param string $type either 'file' or 'dir'. null returns both files and directories
* @return mixed array of nested directories and files in each directory
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::tree
*/
public function tree($path = null, $exceptions = false, $type = null) {
if (!$path) {
$path = $this->path;
}
$files = array();
$directories = array($path);
if (is_array($exceptions)) {
$exceptions = array_flip($exceptions);
}
$skipHidden = false;
if ($exceptions === true) {
$skipHidden = true;
} elseif (isset($exceptions['.'])) {
$skipHidden = true;
unset($exceptions['.']);
}
try {
$directory = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME | RecursiveDirectoryIterator::CURRENT_AS_SELF);
$iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
} catch (Exception $e) {
if ($type === null) {
return array(array(), array());
}
return array();
}
foreach ($iterator as $itemPath => $fsIterator) {
if ($skipHidden) {
$subPathName = $fsIterator->getSubPathname();
if ($subPathName{0} === '.' || strpos($subPathName, DS . '.') !== false) {
continue;
}
}
$item = $fsIterator->current();
if (!empty($exceptions) && isset($exceptions[$item->getFilename()])) {
continue;
}
if ($item->isFile()) {
$files[] = $itemPath;
} elseif ($item->isDir() && !$item->isDot()) {
$directories[] = $itemPath;
}
}
if ($type === null) {
return array($directories, $files);
}
if ($type === 'dir') {
return $directories;
}
return $files;
}
/**
* Create a directory structure recursively. Can be used to create
* deep path structures like `/foo/bar/baz/shoe/horn`
*
* @param string $pathname The directory structure to create
* @param int $mode octal value 0755
* @return bool Returns TRUE on success, FALSE on failure
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::create
*/
public function create($pathname, $mode = false) {
if (is_dir($pathname) || empty($pathname)) {
return true;
}
if (!$mode) {
$mode = $this->mode;
}
if (is_file($pathname)) {
$this->_errors[] = __d('cake_dev', '%s is a file', $pathname);
return false;
}
$pathname = rtrim($pathname, DS);
$nextPathname = substr($pathname, 0, strrpos($pathname, DS));
if ($this->create($nextPathname, $mode)) {
if (!file_exists($pathname)) {
$old = umask(0);
if (mkdir($pathname, $mode)) {
umask($old);
$this->_messages[] = __d('cake_dev', '%s created', $pathname);
return true;
}
umask($old);
$this->_errors[] = __d('cake_dev', '%s NOT created', $pathname);
return false;
}
}
return false;
}
/**
* Returns the size in bytes of this Folder and its contents.
*
* @return int size in bytes of current folder
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::dirsize
*/
public function dirsize() {
$size = 0;
$directory = Folder::slashTerm($this->path);
$stack = array($directory);
$count = count($stack);
for ($i = 0, $j = $count; $i < $j; ++$i) {
if (is_file($stack[$i])) {
$size += filesize($stack[$i]);
} elseif (is_dir($stack[$i])) {
$dir = dir($stack[$i]);
if ($dir) {
while (false !== ($entry = $dir->read())) {
if ($entry === '.' || $entry === '..') {
continue;
}
$add = $stack[$i] . $entry;
if (is_dir($stack[$i] . $entry)) {
$add = Folder::slashTerm($add);
}
$stack[] = $add;
}
$dir->close();
}
}
$j = count($stack);
}
return $size;
}
/**
* Recursively Remove directories if the system allows.
*
* @param string $path Path of directory to delete
* @return bool Success
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::delete
*/
public function delete($path = null) {
if (!$path) {
$path = $this->pwd();
}
if (!$path) {
return null;
}
$path = Folder::slashTerm($path);
if (is_dir($path)) {
try {
$directory = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::CURRENT_AS_SELF);
$iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::CHILD_FIRST);
} catch (Exception $e) {
return false;
}
foreach ($iterator as $item) {
$filePath = $item->getPathname();
if ($item->isFile() || $item->isLink()) {
//@codingStandardsIgnoreStart
if (@unlink($filePath)) {
//@codingStandardsIgnoreEnd
$this->_messages[] = __d('cake_dev', '%s removed', $filePath);
} else {
$this->_errors[] = __d('cake_dev', '%s NOT removed', $filePath);
}
} elseif ($item->isDir() && !$item->isDot()) {
//@codingStandardsIgnoreStart
if (@rmdir($filePath)) {
//@codingStandardsIgnoreEnd
$this->_messages[] = __d('cake_dev', '%s removed', $filePath);
} else {
$this->_errors[] = __d('cake_dev', '%s NOT removed', $filePath);
return false;
}
}
}
$path = rtrim($path, DS);
//@codingStandardsIgnoreStart
if (@rmdir($path)) {
//@codingStandardsIgnoreEnd
$this->_messages[] = __d('cake_dev', '%s removed', $path);
} else {
$this->_errors[] = __d('cake_dev', '%s NOT removed', $path);
return false;
}
}
return true;
}
/**
* Recursive directory copy.
*
* ### Options
*
* - `to` The directory to copy to.
* - `from` The directory to copy from, this will cause a cd() to occur, changing the results of pwd().
* - `mode` The mode to copy the files/directories with.
* - `skip` Files/directories to skip.
* - `scheme` Folder::MERGE, Folder::OVERWRITE, Folder::SKIP
*
* @param array|string $options Either an array of options (see above) or a string of the destination directory.
* @return bool Success
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::copy
*/
public function copy($options) {
if (!$this->pwd()) {
return false;
}
$to = null;
if (is_string($options)) {
$to = $options;
$options = array();
}
$options += array('to' => $to, 'from' => $this->path, 'mode' => $this->mode, 'skip' => array(), 'scheme' => Folder::MERGE);
$fromDir = $options['from'];
$toDir = $options['to'];
$mode = $options['mode'];
if (!$this->cd($fromDir)) {
$this->_errors[] = __d('cake_dev', '%s not found', $fromDir);
return false;
}
if (!is_dir($toDir)) {
$this->create($toDir, $mode);
}
if (!is_writable($toDir)) {
$this->_errors[] = __d('cake_dev', '%s not writable', $toDir);
return false;
}
$exceptions = array_merge(array('.', '..', '.svn'), $options['skip']);
//@codingStandardsIgnoreStart
if ($handle = @opendir($fromDir)) {
//@codingStandardsIgnoreEnd
while (($item = readdir($handle)) !== false) {
$to = Folder::addPathElement($toDir, $item);
if (($options['scheme'] != Folder::SKIP || !is_dir($to)) && !in_array($item, $exceptions)) {
$from = Folder::addPathElement($fromDir, $item);
if (is_file($from)) {
if (copy($from, $to)) {
chmod($to, intval($mode, 8));
touch($to, filemtime($from));
$this->_messages[] = __d('cake_dev', '%s copied to %s', $from, $to);
} else {
$this->_errors[] = __d('cake_dev', '%s NOT copied to %s', $from, $to);
}
}
if (is_dir($from) && file_exists($to) && $options['scheme'] === Folder::OVERWRITE) {
$this->delete($to);
}
if (is_dir($from) && !file_exists($to)) {
$old = umask(0);
if (mkdir($to, $mode)) {
umask($old);
$old = umask(0);
chmod($to, $mode);
umask($old);
$this->_messages[] = __d('cake_dev', '%s created', $to);
$options = array('to' => $to, 'from' => $from) + $options;
$this->copy($options);
} else {
$this->_errors[] = __d('cake_dev', '%s not created', $to);
}
} elseif (is_dir($from) && $options['scheme'] === Folder::MERGE) {
$options = array('to' => $to, 'from' => $from) + $options;
$this->copy($options);
}
}
}
closedir($handle);
} else {
return false;
}
if (!empty($this->_errors)) {
return false;
}
return true;
}
/**
* Recursive directory move.
*
* ### Options
*
* - `to` The directory to copy to.
* - `from` The directory to copy from, this will cause a cd() to occur, changing the results of pwd().
* - `chmod` The mode to copy the files/directories with.
* - `skip` Files/directories to skip.
* - `scheme` Folder::MERGE, Folder::OVERWRITE, Folder::SKIP
*
* @param array $options (to, from, chmod, skip, scheme)
* @return bool Success
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::move
*/
public function move($options) {
$to = null;
if (is_string($options)) {
$to = $options;
$options = (array)$options;
}
$options += array('to' => $to, 'from' => $this->path, 'mode' => $this->mode, 'skip' => array());
if ($this->copy($options)) {
if ($this->delete($options['from'])) {
return (bool)$this->cd($options['to']);
}
}
return false;
}
/**
* get messages from latest method
*
* @param bool $reset Reset message stack after reading
* @return array
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::messages
*/
public function messages($reset = true) {
$messages = $this->_messages;
if ($reset) {
$this->_messages = array();
}
return $messages;
}
/**
* get error from latest method
*
* @param bool $reset Reset error stack after reading
* @return array
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::errors
*/
public function errors($reset = true) {
$errors = $this->_errors;
if ($reset) {
$this->_errors = array();
}
return $errors;
}
/**
* Get the real path (taking ".." and such into account)
*
* @param string $path Path to resolve
* @return string The resolved path
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::realpath
*/
public function realpath($path) {
$path = str_replace('/', DS, trim($path));
if (strpos($path, '..') === false) {
if (!Folder::isAbsolute($path)) {
$path = Folder::addPathElement($this->path, $path);
}
return $path;
}
$parts = explode(DS, $path);
$newparts = array();
$newpath = '';
if ($path[0] === DS) {
$newpath = DS;
}
while (($part = array_shift($parts)) !== null) {
if ($part === '.' || $part === '') {
continue;
}
if ($part === '..') {
if (!empty($newparts)) {
array_pop($newparts);
continue;
}
return false;
}
$newparts[] = $part;
}
$newpath .= implode(DS, $newparts);
return Folder::slashTerm($newpath);
}
/**
* Returns true if given $path ends in a slash (i.e. is slash-terminated).
*
* @param string $path Path to check
* @return bool true if path ends with slash, false otherwise
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::isSlashTerm
*/
public static function isSlashTerm($path) {
$lastChar = $path[strlen($path) - 1];
return $lastChar === '/' || $lastChar === '\\';
}
}

1059
lib/Cake/Utility/Hash.php Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,572 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Utility
* @since CakePHP(tm) v 0.2.9
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* Pluralize and singularize English words.
*
* Inflector pluralizes and singularizes English nouns.
* Used by CakePHP's naming conventions throughout the framework.
*
* @package Cake.Utility
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html
*/
class Inflector {
/**
* Plural inflector rules
*
* @var array
*/
protected static $_plural = array(
'rules' => array(
'/(s)tatus$/i' => '\1\2tatuses',
'/(quiz)$/i' => '\1zes',
'/^(ox)$/i' => '\1\2en',
'/([m|l])ouse$/i' => '\1ice',
'/(matr|vert|ind)(ix|ex)$/i' => '\1ices',
'/(x|ch|ss|sh)$/i' => '\1es',
'/([^aeiouy]|qu)y$/i' => '\1ies',
'/(hive)$/i' => '\1s',
'/(?:([^f])fe|([lre])f)$/i' => '\1\2ves',
'/sis$/i' => 'ses',
'/([ti])um$/i' => '\1a',
'/(p)erson$/i' => '\1eople',
'/(m)an$/i' => '\1en',
'/(c)hild$/i' => '\1hildren',
'/(buffal|tomat)o$/i' => '\1\2oes',
'/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|vir)us$/i' => '\1i',
'/us$/i' => 'uses',
'/(alias)$/i' => '\1es',
'/(ax|cris|test)is$/i' => '\1es',
'/s$/' => 's',
'/^$/' => '',
'/$/' => 's',
),
'uninflected' => array(
'.*[nrlm]ese',
'.*deer',
'.*fish',
'.*measles',
'.*ois',
'.*pox',
'.*sheep',
'people',
'feedback',
'stadia'
),
'irregular' => array(
'atlas' => 'atlases',
'beef' => 'beefs',
'brief' => 'briefs',
'brother' => 'brothers',
'cafe' => 'cafes',
'child' => 'children',
'cookie' => 'cookies',
'corpus' => 'corpuses',
'cow' => 'cows',
'ganglion' => 'ganglions',
'genie' => 'genies',
'genus' => 'genera',
'graffito' => 'graffiti',
'hoof' => 'hoofs',
'loaf' => 'loaves',
'man' => 'men',
'money' => 'monies',
'mongoose' => 'mongooses',
'move' => 'moves',
'mythos' => 'mythoi',
'niche' => 'niches',
'numen' => 'numina',
'occiput' => 'occiputs',
'octopus' => 'octopuses',
'opus' => 'opuses',
'ox' => 'oxen',
'penis' => 'penises',
'person' => 'people',
'sex' => 'sexes',
'soliloquy' => 'soliloquies',
'testis' => 'testes',
'trilby' => 'trilbys',
'turf' => 'turfs',
'potato' => 'potatoes',
'hero' => 'heroes',
'tooth' => 'teeth',
'goose' => 'geese',
'foot' => 'feet'
)
);
/**
* Singular inflector rules
*
* @var array
*/
protected static $_singular = array(
'rules' => array(
'/(s)tatuses$/i' => '\1\2tatus',
'/^(.*)(menu)s$/i' => '\1\2',
'/(quiz)zes$/i' => '\\1',
'/(matr)ices$/i' => '\1ix',
'/(vert|ind)ices$/i' => '\1ex',
'/^(ox)en/i' => '\1',
'/(alias)(es)*$/i' => '\1',
'/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|viri?)i$/i' => '\1us',
'/([ftw]ax)es/i' => '\1',
'/(cris|ax|test)es$/i' => '\1is',
'/(shoe)s$/i' => '\1',
'/(o)es$/i' => '\1',
'/ouses$/' => 'ouse',
'/([^a])uses$/' => '\1us',
'/([m|l])ice$/i' => '\1ouse',
'/(x|ch|ss|sh)es$/i' => '\1',
'/(m)ovies$/i' => '\1\2ovie',
'/(s)eries$/i' => '\1\2eries',
'/([^aeiouy]|qu)ies$/i' => '\1y',
'/(tive)s$/i' => '\1',
'/(hive)s$/i' => '\1',
'/(drive)s$/i' => '\1',
'/([le])ves$/i' => '\1f',
'/([^rfoa])ves$/i' => '\1fe',
'/(^analy)ses$/i' => '\1sis',
'/(analy|diagno|^ba|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis',
'/([ti])a$/i' => '\1um',
'/(p)eople$/i' => '\1\2erson',
'/(m)en$/i' => '\1an',
'/(c)hildren$/i' => '\1\2hild',
'/(n)ews$/i' => '\1\2ews',
'/eaus$/' => 'eau',
'/^(.*us)$/' => '\\1',
'/s$/i' => ''
),
'uninflected' => array(
'.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*sheep', '.*ss', 'feedback'
),
'irregular' => array(
'foes' => 'foe',
)
);
/**
* Words that should not be inflected
*
* @var array
*/
protected static $_uninflected = array(
'Amoyese', 'bison', 'Borghese', 'bream', 'breeches', 'britches', 'buffalo', 'cantus',
'carp', 'chassis', 'clippers', 'cod', 'coitus', 'Congoese', 'contretemps', 'corps',
'debris', 'diabetes', 'djinn', 'eland', 'elk', 'equipment', 'Faroese', 'flounder',
'Foochowese', 'gallows', 'Genevese', 'Genoese', 'Gilbertese', 'graffiti',
'headquarters', 'herpes', 'hijinks', 'Hottentotese', 'information', 'innings',
'jackanapes', 'Kiplingese', 'Kongoese', 'Lucchese', 'mackerel', 'Maltese', '.*?media',
'metadata', 'mews', 'moose', 'mumps', 'Nankingese', 'news', 'nexus', 'Niasese',
'Pekingese', 'Piedmontese', 'pincers', 'Pistoiese', 'pliers', 'Portuguese',
'proceedings', 'rabies', 'research', 'rice', 'rhinoceros', 'salmon', 'Sarawakese', 'scissors',
'sea[- ]bass', 'series', 'Shavese', 'shears', 'siemens', 'species', 'swine', 'testes',
'trousers', 'trout', 'tuna', 'Vermontese', 'Wenchowese', 'whiting', 'wildebeest',
'Yengeese'
);
/**
* Default map of accented and special characters to ASCII characters
*
* @var array
*/
protected static $_transliteration = array(
'/À|Á|Â|Ã|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A',
'/Æ|Ǽ/' => 'AE',
'/Ä/' => 'Ae',
'/Ç|Ć|Ĉ|Ċ|Č/' => 'C',
'/Ð|Ď|Đ/' => 'D',
'/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě/' => 'E',
'/Ĝ|Ğ|Ġ|Ģ|Ґ/' => 'G',
'/Ĥ|Ħ/' => 'H',
'/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ|І/' => 'I',
'/IJ/' => 'IJ',
'/Ĵ/' => 'J',
'/Ķ/' => 'K',
'/Ĺ|Ļ|Ľ|Ŀ|Ł/' => 'L',
'/Ñ|Ń|Ņ|Ň/' => 'N',
'/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ/' => 'O',
'/Œ/' => 'OE',
'/Ö/' => 'Oe',
'/Ŕ|Ŗ|Ř/' => 'R',
'/Ś|Ŝ|Ş|Ș|Š/' => 'S',
'/ẞ/' => 'SS',
'/Ţ|Ț|Ť|Ŧ/' => 'T',
'/Þ/' => 'TH',
'/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ/' => 'U',
'/Ü/' => 'Ue',
'/Ŵ/' => 'W',
'/Ý|Ÿ|Ŷ/' => 'Y',
'/Є/' => 'Ye',
'/Ї/' => 'Yi',
'/Ź|Ż|Ž/' => 'Z',
'/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a',
'/ä|æ|ǽ/' => 'ae',
'/ç|ć|ĉ|ċ|č/' => 'c',
'/ð|ď|đ/' => 'd',
'/è|é|ê|ë|ē|ĕ|ė|ę|ě/' => 'e',
'/ƒ/' => 'f',
'/ĝ|ğ|ġ|ģ|ґ/' => 'g',
'/ĥ|ħ/' => 'h',
'/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı|і/' => 'i',
'/ij/' => 'ij',
'/ĵ/' => 'j',
'/ķ/' => 'k',
'/ĺ|ļ|ľ|ŀ|ł/' => 'l',
'/ñ|ń|ņ|ň|ʼn/' => 'n',
'/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º/' => 'o',
'/ö|œ/' => 'oe',
'/ŕ|ŗ|ř/' => 'r',
'/ś|ŝ|ş|ș|š|ſ/' => 's',
'/ß/' => 'ss',
'/ţ|ț|ť|ŧ/' => 't',
'/þ/' => 'th',
'/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ/' => 'u',
'/ü/' => 'ue',
'/ŵ/' => 'w',
'/ý|ÿ|ŷ/' => 'y',
'/є/' => 'ye',
'/ї/' => 'yi',
'/ź|ż|ž/' => 'z',
);
/**
* Method cache array.
*
* @var array
*/
protected static $_cache = array();
/**
* The initial state of Inflector so reset() works.
*
* @var array
*/
protected static $_initialState = array();
/**
* Cache inflected values, and return if already available
*
* @param string $type Inflection type
* @param string $key Original value
* @param string $value Inflected value
* @return string Inflected value, from cache
*/
protected static function _cache($type, $key, $value = false) {
$key = '_' . $key;
$type = '_' . $type;
if ($value !== false) {
self::$_cache[$type][$key] = $value;
return $value;
}
if (!isset(self::$_cache[$type][$key])) {
return false;
}
return self::$_cache[$type][$key];
}
/**
* Clears Inflectors inflected value caches. And resets the inflection
* rules to the initial values.
*
* @return void
*/
public static function reset() {
if (empty(self::$_initialState)) {
self::$_initialState = get_class_vars('Inflector');
return;
}
foreach (self::$_initialState as $key => $val) {
if ($key !== '_initialState') {
self::${$key} = $val;
}
}
}
/**
* Adds custom inflection $rules, of either 'plural', 'singular' or 'transliteration' $type.
*
* ### Usage:
*
* {{{
* Inflector::rules('plural', array('/^(inflect)or$/i' => '\1ables'));
* Inflector::rules('plural', array(
* 'rules' => array('/^(inflect)ors$/i' => '\1ables'),
* 'uninflected' => array('dontinflectme'),
* 'irregular' => array('red' => 'redlings')
* ));
* Inflector::rules('transliteration', array('/å/' => 'aa'));
* }}}
*
* @param string $type The type of inflection, either 'plural', 'singular' or 'transliteration'
* @param array $rules Array of rules to be added.
* @param bool $reset If true, will unset default inflections for all
* new rules that are being defined in $rules.
* @return void
*/
public static function rules($type, $rules, $reset = false) {
$var = '_' . $type;
switch ($type) {
case 'transliteration':
if ($reset) {
self::$_transliteration = $rules;
} else {
self::$_transliteration = $rules + self::$_transliteration;
}
break;
default:
foreach ($rules as $rule => $pattern) {
if (is_array($pattern)) {
if ($reset) {
self::${$var}[$rule] = $pattern;
} else {
if ($rule === 'uninflected') {
self::${$var}[$rule] = array_merge($pattern, self::${$var}[$rule]);
} else {
self::${$var}[$rule] = $pattern + self::${$var}[$rule];
}
}
unset($rules[$rule], self::${$var}['cache' . ucfirst($rule)]);
if (isset(self::${$var}['merged'][$rule])) {
unset(self::${$var}['merged'][$rule]);
}
if ($type === 'plural') {
self::$_cache['pluralize'] = self::$_cache['tableize'] = array();
} elseif ($type === 'singular') {
self::$_cache['singularize'] = array();
}
}
}
self::${$var}['rules'] = $rules + self::${$var}['rules'];
}
}
/**
* Return $word in plural form.
*
* @param string $word Word in singular
* @return string Word in plural
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::pluralize
*/
public static function pluralize($word) {
if (isset(self::$_cache['pluralize'][$word])) {
return self::$_cache['pluralize'][$word];
}
if (!isset(self::$_plural['merged']['irregular'])) {
self::$_plural['merged']['irregular'] = self::$_plural['irregular'];
}
if (!isset(self::$_plural['merged']['uninflected'])) {
self::$_plural['merged']['uninflected'] = array_merge(self::$_plural['uninflected'], self::$_uninflected);
}
if (!isset(self::$_plural['cacheUninflected']) || !isset(self::$_plural['cacheIrregular'])) {
self::$_plural['cacheUninflected'] = '(?:' . implode('|', self::$_plural['merged']['uninflected']) . ')';
self::$_plural['cacheIrregular'] = '(?:' . implode('|', array_keys(self::$_plural['merged']['irregular'])) . ')';
}
if (preg_match('/(.*)\\b(' . self::$_plural['cacheIrregular'] . ')$/i', $word, $regs)) {
self::$_cache['pluralize'][$word] = $regs[1] . substr($word, 0, 1) . substr(self::$_plural['merged']['irregular'][strtolower($regs[2])], 1);
return self::$_cache['pluralize'][$word];
}
if (preg_match('/^(' . self::$_plural['cacheUninflected'] . ')$/i', $word, $regs)) {
self::$_cache['pluralize'][$word] = $word;
return $word;
}
foreach (self::$_plural['rules'] as $rule => $replacement) {
if (preg_match($rule, $word)) {
self::$_cache['pluralize'][$word] = preg_replace($rule, $replacement, $word);
return self::$_cache['pluralize'][$word];
}
}
}
/**
* Return $word in singular form.
*
* @param string $word Word in plural
* @return string Word in singular
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::singularize
*/
public static function singularize($word) {
if (isset(self::$_cache['singularize'][$word])) {
return self::$_cache['singularize'][$word];
}
if (!isset(self::$_singular['merged']['uninflected'])) {
self::$_singular['merged']['uninflected'] = array_merge(
self::$_singular['uninflected'],
self::$_uninflected
);
}
if (!isset(self::$_singular['merged']['irregular'])) {
self::$_singular['merged']['irregular'] = array_merge(
self::$_singular['irregular'],
array_flip(self::$_plural['irregular'])
);
}
if (!isset(self::$_singular['cacheUninflected']) || !isset(self::$_singular['cacheIrregular'])) {
self::$_singular['cacheUninflected'] = '(?:' . implode('|', self::$_singular['merged']['uninflected']) . ')';
self::$_singular['cacheIrregular'] = '(?:' . implode('|', array_keys(self::$_singular['merged']['irregular'])) . ')';
}
if (preg_match('/(.*)\\b(' . self::$_singular['cacheIrregular'] . ')$/i', $word, $regs)) {
self::$_cache['singularize'][$word] = $regs[1] . substr($word, 0, 1) . substr(self::$_singular['merged']['irregular'][strtolower($regs[2])], 1);
return self::$_cache['singularize'][$word];
}
if (preg_match('/^(' . self::$_singular['cacheUninflected'] . ')$/i', $word, $regs)) {
self::$_cache['singularize'][$word] = $word;
return $word;
}
foreach (self::$_singular['rules'] as $rule => $replacement) {
if (preg_match($rule, $word)) {
self::$_cache['singularize'][$word] = preg_replace($rule, $replacement, $word);
return self::$_cache['singularize'][$word];
}
}
self::$_cache['singularize'][$word] = $word;
return $word;
}
/**
* Returns the given lower_case_and_underscored_word as a CamelCased word.
*
* @param string $lowerCaseAndUnderscoredWord Word to camelize
* @return string Camelized word. LikeThis.
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::camelize
*/
public static function camelize($lowerCaseAndUnderscoredWord) {
if (!($result = self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord))) {
$result = str_replace(' ', '', Inflector::humanize($lowerCaseAndUnderscoredWord));
self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord, $result);
}
return $result;
}
/**
* Returns the given camelCasedWord as an underscored_word.
*
* @param string $camelCasedWord Camel-cased word to be "underscorized"
* @return string Underscore-syntaxed version of the $camelCasedWord
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::underscore
*/
public static function underscore($camelCasedWord) {
if (!($result = self::_cache(__FUNCTION__, $camelCasedWord))) {
$result = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $camelCasedWord));
self::_cache(__FUNCTION__, $camelCasedWord, $result);
}
return $result;
}
/**
* Returns the given underscored_word_group as a Human Readable Word Group.
* (Underscores are replaced by spaces and capitalized following words.)
*
* @param string $lowerCaseAndUnderscoredWord String to be made more readable
* @return string Human-readable string
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::humanize
*/
public static function humanize($lowerCaseAndUnderscoredWord) {
if (!($result = self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord))) {
$result = ucwords(str_replace('_', ' ', $lowerCaseAndUnderscoredWord));
self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord, $result);
}
return $result;
}
/**
* Returns corresponding table name for given model $className. ("people" for the model class "Person").
*
* @param string $className Name of class to get database table name for
* @return string Name of the database table for given class
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::tableize
*/
public static function tableize($className) {
if (!($result = self::_cache(__FUNCTION__, $className))) {
$result = Inflector::pluralize(Inflector::underscore($className));
self::_cache(__FUNCTION__, $className, $result);
}
return $result;
}
/**
* Returns Cake model class name ("Person" for the database table "people".) for given database table.
*
* @param string $tableName Name of database table to get class name for
* @return string Class name
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::classify
*/
public static function classify($tableName) {
if (!($result = self::_cache(__FUNCTION__, $tableName))) {
$result = Inflector::camelize(Inflector::singularize($tableName));
self::_cache(__FUNCTION__, $tableName, $result);
}
return $result;
}
/**
* Returns camelBacked version of an underscored string.
*
* @param string $string String to convert.
* @return string in variable form
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::variable
*/
public static function variable($string) {
if (!($result = self::_cache(__FUNCTION__, $string))) {
$camelized = Inflector::camelize(Inflector::underscore($string));
$replace = strtolower(substr($camelized, 0, 1));
$result = preg_replace('/\\w/', $replace, $camelized, 1);
self::_cache(__FUNCTION__, $string, $result);
}
return $result;
}
/**
* Returns a string with all spaces converted to underscores (by default), accented
* characters converted to non-accented characters, and non word characters removed.
*
* @param string $string the string you want to slug
* @param string $replacement will replace keys in map
* @return string
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::slug
*/
public static function slug($string, $replacement = '_') {
$quotedReplacement = preg_quote($replacement, '/');
$merge = array(
'/[^\s\p{Zs}\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ',
'/[\s\p{Zs}]+/mu' => $replacement,
sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '',
);
$map = self::$_transliteration + $merge;
return preg_replace(array_keys($map), array_values($map), $string);
}
}
// Store the initial state
Inflector::reset();

View file

@ -0,0 +1,339 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* Deals with Collections of objects. Keeping registries of those objects,
* loading and constructing new objects and triggering callbacks. Each subclass needs
* to implement its own load() functionality.
*
* All core subclasses of ObjectCollection by convention loaded objects are stored
* in `$this->_loaded`. Enabled objects are stored in `$this->_enabled`. In addition,
* they all support an `enabled` option that controls the enabled/disabled state of the object
* when loaded.
*
* @package Cake.Utility
* @since CakePHP(tm) v 2.0
*/
abstract class ObjectCollection {
/**
* List of the currently-enabled objects
*
* @var array
*/
protected $_enabled = array();
/**
* A hash of loaded objects, indexed by name
*
* @var array
*/
protected $_loaded = array();
/**
* Default object priority. A non zero integer.
*
* @var int
*/
public $defaultPriority = 10;
/**
* Loads a new object onto the collection. Can throw a variety of exceptions
*
* Implementations of this class support a `$options['enabled']` flag which enables/disables
* a loaded object.
*
* @param string $name Name of object to load.
* @param array $options Array of configuration options for the object to be constructed.
* @return object the constructed object
*/
abstract public function load($name, $options = array());
/**
* Trigger a callback method on every object in the collection.
* Used to trigger methods on objects in the collection. Will fire the methods in the
* order they were attached.
*
* ### Options
*
* - `breakOn` Set to the value or values you want the callback propagation to stop on.
* Can either be a scalar value, or an array of values to break on. Defaults to `false`.
*
* - `break` Set to true to enabled breaking. When a trigger is broken, the last returned value
* will be returned. If used in combination with `collectReturn` the collected results will be returned.
* Defaults to `false`.
*
* - `collectReturn` Set to true to collect the return of each object into an array.
* This array of return values will be returned from the trigger() call. Defaults to `false`.
*
* - `modParams` Allows each object the callback gets called on to modify the parameters to the next object.
* Setting modParams to an integer value will allow you to modify the parameter with that index.
* Any non-null value will modify the parameter index indicated.
* Defaults to false.
*
* @param string|CakeEvent $callback Method to fire on all the objects. Its assumed all the objects implement
* the method you are calling. If an instance of CakeEvent is provided, then then Event name will parsed to
* get the callback name. This is done by getting the last word after any dot in the event name
* (eg. `Model.afterSave` event will trigger the `afterSave` callback)
* @param array $params Array of parameters for the triggered callback.
* @param array $options Array of options.
* @return mixed Either the last result or all results if collectReturn is on.
* @throws CakeException when modParams is used with an index that does not exist.
*/
public function trigger($callback, $params = array(), $options = array()) {
if (empty($this->_enabled)) {
return true;
}
if ($callback instanceof CakeEvent) {
$event = $callback;
if (is_array($event->data)) {
$params =& $event->data;
}
if (empty($event->omitSubject)) {
$subject = $event->subject();
}
foreach (array('break', 'breakOn', 'collectReturn', 'modParams') as $opt) {
if (isset($event->{$opt})) {
$options[$opt] = $event->{$opt};
}
}
$parts = explode('.', $event->name());
$callback = array_pop($parts);
}
$options += array(
'break' => false,
'breakOn' => false,
'collectReturn' => false,
'modParams' => false
);
$collected = array();
$list = array_keys($this->_enabled);
if ($options['modParams'] !== false && !isset($params[$options['modParams']])) {
throw new CakeException(__d('cake_dev', 'Cannot use modParams with indexes that do not exist.'));
}
$result = null;
foreach ($list as $name) {
$result = call_user_func_array(array($this->_loaded[$name], $callback), compact('subject') + $params);
if ($options['collectReturn'] === true) {
$collected[] = $result;
}
if (
$options['break'] && ($result === $options['breakOn'] ||
(is_array($options['breakOn']) && in_array($result, $options['breakOn'], true)))
) {
return $result;
} elseif ($options['modParams'] !== false && !in_array($result, array(true, false, null), true)) {
$params[$options['modParams']] = $result;
}
}
if ($options['modParams'] !== false) {
return $params[$options['modParams']];
}
return $options['collectReturn'] ? $collected : $result;
}
/**
* Provide public read access to the loaded objects
*
* @param string $name Name of property to read
* @return mixed
*/
public function __get($name) {
if (isset($this->_loaded[$name])) {
return $this->_loaded[$name];
}
return null;
}
/**
* Provide isset access to _loaded
*
* @param string $name Name of object being checked.
* @return bool
*/
public function __isset($name) {
return isset($this->_loaded[$name]);
}
/**
* Enables callbacks on an object or array of objects
*
* @param string|array $name CamelCased name of the object(s) to enable (string or array)
* @param bool $prioritize Prioritize enabled list after enabling object(s)
* @return void
*/
public function enable($name, $prioritize = true) {
$enabled = false;
foreach ((array)$name as $object) {
if (isset($this->_loaded[$object]) && !isset($this->_enabled[$object])) {
$priority = $this->defaultPriority;
if (isset($this->_loaded[$object]->settings['priority'])) {
$priority = $this->_loaded[$object]->settings['priority'];
}
$this->_enabled[$object] = array($priority);
$enabled = true;
}
}
if ($prioritize && $enabled) {
$this->prioritize();
}
}
/**
* Prioritize list of enabled object
*
* @return array Prioritized list of object
*/
public function prioritize() {
$i = 1;
foreach ($this->_enabled as $name => $priority) {
$priority[1] = $i++;
$this->_enabled[$name] = $priority;
}
asort($this->_enabled);
return $this->_enabled;
}
/**
* Set priority for an object or array of objects
*
* @param string|array $name CamelCased name of the object(s) to enable (string or array)
* If string the second param $priority is used else it should be an associative array
* with keys as object names and values as priorities to set.
* @param int|null $priority Integer priority to set or null for default
* @return void
*/
public function setPriority($name, $priority = null) {
if (is_string($name)) {
$name = array($name => $priority);
}
foreach ($name as $object => $objectPriority) {
if (isset($this->_loaded[$object])) {
if ($objectPriority === null) {
$objectPriority = $this->defaultPriority;
}
$this->_loaded[$object]->settings['priority'] = $objectPriority;
if (isset($this->_enabled[$object])) {
$this->_enabled[$object] = array($objectPriority);
}
}
}
$this->prioritize();
}
/**
* Disables callbacks on a object or array of objects. Public object methods are still
* callable as normal.
*
* @param string|array $name CamelCased name of the objects(s) to disable (string or array)
* @return void
*/
public function disable($name) {
foreach ((array)$name as $object) {
unset($this->_enabled[$object]);
}
}
/**
* Gets the list of currently-enabled objects, or, the current status of a single objects
*
* @param string $name Optional. The name of the object to check the status of. If omitted,
* returns an array of currently-enabled object
* @return mixed If $name is specified, returns the boolean status of the corresponding object.
* Otherwise, returns an array of all enabled objects.
*/
public function enabled($name = null) {
if (!empty($name)) {
return isset($this->_enabled[$name]);
}
return array_keys($this->_enabled);
}
/**
* Gets the list of attached objects, or, whether the given object is attached
*
* @param string $name Optional. The name of the object to check the status of. If omitted,
* returns an array of currently-attached objects
* @return mixed If $name is specified, returns the boolean status of the corresponding object.
* Otherwise, returns an array of all attached objects.
* @deprecated Will be removed in 3.0. Use loaded instead.
*/
public function attached($name = null) {
return $this->loaded($name);
}
/**
* Gets the list of loaded objects, or, whether the given object is loaded
*
* @param string $name Optional. The name of the object to check the status of. If omitted,
* returns an array of currently-loaded objects
* @return mixed If $name is specified, returns the boolean status of the corresponding object.
* Otherwise, returns an array of all loaded objects.
*/
public function loaded($name = null) {
if (!empty($name)) {
return isset($this->_loaded[$name]);
}
return array_keys($this->_loaded);
}
/**
* Name of the object to remove from the collection
*
* @param string $name Name of the object to delete.
* @return void
*/
public function unload($name) {
list(, $name) = pluginSplit($name);
unset($this->_loaded[$name], $this->_enabled[$name]);
}
/**
* Adds or overwrites an instantiated object to the collection
*
* @param string $name Name of the object
* @param Object $object The object to use
* @return array Loaded objects
*/
public function set($name = null, $object = null) {
if (!empty($name) && !empty($object)) {
list(, $name) = pluginSplit($name);
$this->_loaded[$name] = $object;
}
return $this->_loaded;
}
/**
* Normalizes an object array, creates an array that makes lazy loading
* easier
*
* @param array $objects Array of child objects to normalize.
* @return array Array of normalized objects.
*/
public static function normalizeObjectArray($objects) {
$normal = array();
foreach ($objects as $i => $objectName) {
$options = array();
if (!is_int($i)) {
$options = (array)$objectName;
$objectName = $i;
}
list(, $name) = pluginSplit($objectName);
$normal[$name] = array('class' => $objectName, 'settings' => $options);
}
return $normal;
}
}

View file

@ -0,0 +1,269 @@
<?php
/**
* Washes strings from unwanted noise.
*
* Helpful methods to make unsafe strings usable.
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Utility
* @since CakePHP(tm) v 0.10.0.1076
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConnectionManager', 'Model');
/**
* Data Sanitization.
*
* Removal of alphanumeric characters, SQL-safe slash-added strings, HTML-friendly strings,
* and all of the above on arrays.
*
* @package Cake.Utility
* @deprecated Deprecated since version 2.4
*/
class Sanitize {
/**
* Removes any non-alphanumeric characters.
*
* @param string $string String to sanitize
* @param array $allowed An array of additional characters that are not to be removed.
* @return string Sanitized string
*/
public static function paranoid($string, $allowed = array()) {
$allow = null;
if (!empty($allowed)) {
foreach ($allowed as $value) {
$allow .= "\\$value";
}
}
if (!is_array($string)) {
return preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $string);
}
$cleaned = array();
foreach ($string as $key => $clean) {
$cleaned[$key] = preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $clean);
}
return $cleaned;
}
/**
* Makes a string SQL-safe.
*
* @param string $string String to sanitize
* @param string $connection Database connection being used
* @return string SQL safe string
*/
public static function escape($string, $connection = 'default') {
if (is_numeric($string) || $string === null || is_bool($string)) {
return $string;
}
$db = ConnectionManager::getDataSource($connection);
$string = $db->value($string, 'string');
$start = 1;
if ($string{0} === 'N') {
$start = 2;
}
return substr(substr($string, $start), 0, -1);
}
/**
* Returns given string safe for display as HTML. Renders entities.
*
* strip_tags() does not validating HTML syntax or structure, so it might strip whole passages
* with broken HTML.
*
* ### Options:
*
* - remove (boolean) if true strips all HTML tags before encoding
* - charset (string) the charset used to encode the string
* - quotes (int) see http://php.net/manual/en/function.htmlentities.php
* - double (boolean) double encode html entities
*
* @param string $string String from where to strip tags
* @param array $options Array of options to use.
* @return string Sanitized string
*/
public static function html($string, $options = array()) {
static $defaultCharset = false;
if ($defaultCharset === false) {
$defaultCharset = Configure::read('App.encoding');
if ($defaultCharset === null) {
$defaultCharset = 'UTF-8';
}
}
$defaults = array(
'remove' => false,
'charset' => $defaultCharset,
'quotes' => ENT_QUOTES,
'double' => true
);
$options += $defaults;
if ($options['remove']) {
$string = strip_tags($string);
}
return htmlentities($string, $options['quotes'], $options['charset'], $options['double']);
}
/**
* Strips extra whitespace from output
*
* @param string $str String to sanitize
* @return string whitespace sanitized string
*/
public static function stripWhitespace($str) {
return preg_replace('/\s{2,}/u', ' ', preg_replace('/[\n\r\t]+/', '', $str));
}
/**
* Strips image tags from output
*
* @param string $str String to sanitize
* @return string Sting with images stripped.
*/
public static function stripImages($str) {
$preg = array(
'/(<a[^>]*>)(<img[^>]+alt=")([^"]*)("[^>]*>)(<\/a>)/i' => '$1$3$5<br />',
'/(<img[^>]+alt=")([^"]*)("[^>]*>)/i' => '$2<br />',
'/<img[^>]*>/i' => ''
);
return preg_replace(array_keys($preg), array_values($preg), $str);
}
/**
* Strips scripts and stylesheets from output
*
* @param string $str String to sanitize
* @return string String with <link>, <img>, <script>, <style> elements and html comments removed.
*/
public static function stripScripts($str) {
$regex =
'/(<link[^>]+rel="[^"]*stylesheet"[^>]*>|' .
'<img[^>]*>|style="[^"]*")|' .
'<script[^>]*>.*?<\/script>|' .
'<style[^>]*>.*?<\/style>|' .
'<!--.*?-->/is';
return preg_replace($regex, '', $str);
}
/**
* Strips extra whitespace, images, scripts and stylesheets from output
*
* @param string $str String to sanitize
* @return string sanitized string
*/
public static function stripAll($str) {
return Sanitize::stripScripts(
Sanitize::stripImages(
Sanitize::stripWhitespace($str)
)
);
}
/**
* Strips the specified tags from output. First parameter is string from
* where to remove tags. All subsequent parameters are tags.
*
* Ex.`$clean = Sanitize::stripTags($dirty, 'b', 'p', 'div');`
*
* Will remove all `<b>`, `<p>`, and `<div>` tags from the $dirty string.
*
* @param string $str String to sanitize.
* @return string sanitized String
*/
public static function stripTags($str) {
$params = func_get_args();
for ($i = 1, $count = count($params); $i < $count; $i++) {
$str = preg_replace('/<' . $params[$i] . '\b[^>]*>/i', '', $str);
$str = preg_replace('/<\/' . $params[$i] . '[^>]*>/i', '', $str);
}
return $str;
}
/**
* Sanitizes given array or value for safe input. Use the options to specify
* the connection to use, and what filters should be applied (with a boolean
* value). Valid filters:
*
* - odd_spaces - removes any non space whitespace characters
* - encode - Encode any html entities. Encode must be true for the `remove_html` to work.
* - dollar - Escape `$` with `\$`
* - carriage - Remove `\r`
* - unicode -
* - escape - Should the string be SQL escaped.
* - backslash -
* - remove_html - Strip HTML with strip_tags. `encode` must be true for this option to work.
*
* @param string|array $data Data to sanitize
* @param string|array $options If string, DB connection being used, otherwise set of options
* @return mixed Sanitized data
*/
public static function clean($data, $options = array()) {
if (empty($data)) {
return $data;
}
if (!is_array($options)) {
$options = array('connection' => $options);
}
$options += array(
'connection' => 'default',
'odd_spaces' => true,
'remove_html' => false,
'encode' => true,
'dollar' => true,
'carriage' => true,
'unicode' => true,
'escape' => true,
'backslash' => true
);
if (is_array($data)) {
foreach ($data as $key => $val) {
$data[$key] = Sanitize::clean($val, $options);
}
return $data;
}
if ($options['odd_spaces']) {
$data = str_replace(chr(0xCA), '', $data);
}
if ($options['encode']) {
$data = Sanitize::html($data, array('remove' => $options['remove_html']));
}
if ($options['dollar']) {
$data = str_replace("\\\$", "$", $data);
}
if ($options['carriage']) {
$data = str_replace("\r", "", $data);
}
if ($options['unicode']) {
$data = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $data);
}
if ($options['escape']) {
$data = Sanitize::escape($data, $options['connection']);
}
if ($options['backslash']) {
$data = preg_replace("/\\\(?!&amp;#|\?#)/", "\\", $data);
}
return $data;
}
}

View file

@ -0,0 +1,384 @@
<?php
/**
* Core Security
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Utility
* @since CakePHP(tm) v .0.10.0.1233
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('String', 'Utility');
/**
* Security Library contains utility methods related to security
*
* @package Cake.Utility
*/
class Security {
/**
* Default hash method
*
* @var string
*/
public static $hashType = null;
/**
* Default cost
*
* @var string
*/
public static $hashCost = '10';
/**
* Get allowed minutes of inactivity based on security level.
*
* @deprecated Exists for backwards compatibility only, not used by the core
* @return int Allowed inactivity in minutes
*/
public static function inactiveMins() {
switch (Configure::read('Security.level')) {
case 'high':
return 10;
case 'medium':
return 100;
case 'low':
default:
return 300;
}
}
/**
* Generate authorization hash.
*
* @return string Hash
*/
public static function generateAuthKey() {
return Security::hash(String::uuid());
}
/**
* Validate authorization hash.
*
* @param string $authKey Authorization hash
* @return bool Success
*/
public static function validateAuthKey($authKey) {
return true;
}
/**
* Create a hash from string using given method or fallback on next available method.
*
* #### Using Blowfish
*
* - Creating Hashes: *Do not supply a salt*. Cake handles salt creation for
* you ensuring that each hashed password will have a *unique* salt.
* - Comparing Hashes: Simply pass the originally hashed password as the salt.
* The salt is prepended to the hash and php handles the parsing automagically.
* For convenience the `BlowfishPasswordHasher` class is available for use with
* the AuthComponent.
* - Do NOT use a constant salt for blowfish!
*
* Creating a blowfish/bcrypt hash:
*
* {{{
* $hash = Security::hash($password, 'blowfish');
* }}}
*
* @param string $string String to hash
* @param string $type Method to use (sha1/sha256/md5/blowfish)
* @param mixed $salt If true, automatically prepends the application's salt
* value to $string (Security.salt). If you are using blowfish the salt
* must be false or a previously generated salt.
* @return string Hash
* @link http://book.cakephp.org/2.0/en/core-utility-libraries/security.html#Security::hash
*/
public static function hash($string, $type = null, $salt = false) {
if (empty($type)) {
$type = self::$hashType;
}
$type = strtolower($type);
if ($type === 'blowfish') {
return self::_crypt($string, $salt);
}
if ($salt) {
if (!is_string($salt)) {
$salt = Configure::read('Security.salt');
}
$string = $salt . $string;
}
if (!$type || $type === 'sha1') {
if (function_exists('sha1')) {
return sha1($string);
}
$type = 'sha256';
}
if ($type === 'sha256' && function_exists('mhash')) {
return bin2hex(mhash(MHASH_SHA256, $string));
}
if (function_exists('hash')) {
return hash($type, $string);
}
return md5($string);
}
/**
* Sets the default hash method for the Security object. This affects all objects using
* Security::hash().
*
* @param string $hash Method to use (sha1/sha256/md5/blowfish)
* @return void
* @see Security::hash()
*/
public static function setHash($hash) {
self::$hashType = $hash;
}
/**
* Sets the cost for they blowfish hash method.
*
* @param int $cost Valid values are 4-31
* @return void
*/
public static function setCost($cost) {
if ($cost < 4 || $cost > 31) {
trigger_error(__d(
'cake_dev',
'Invalid value, cost must be between %s and %s',
array(4, 31)
), E_USER_WARNING);
return null;
}
self::$hashCost = $cost;
}
/**
* Runs $text through a XOR cipher.
*
* *Note* This is not a cryptographically strong method and should not be used
* for sensitive data. Additionally this method does *not* work in environments
* where suhosin is enabled.
*
* Instead you should use Security::rijndael() when you need strong
* encryption.
*
* @param string $text Encrypted string to decrypt, normal string to encrypt
* @param string $key Key to use
* @return string Encrypted/Decrypted string
* @deprecated Will be removed in 3.0.
*/
public static function cipher($text, $key) {
if (empty($key)) {
trigger_error(__d('cake_dev', 'You cannot use an empty key for %s', 'Security::cipher()'), E_USER_WARNING);
return '';
}
srand(Configure::read('Security.cipherSeed'));
$out = '';
$keyLength = strlen($key);
for ($i = 0, $textLength = strlen($text); $i < $textLength; $i++) {
$j = ord(substr($key, $i % $keyLength, 1));
while ($j--) {
rand(0, 255);
}
$mask = rand(0, 255);
$out .= chr(ord(substr($text, $i, 1)) ^ $mask);
}
srand();
return $out;
}
/**
* Encrypts/Decrypts a text using the given key using rijndael method.
*
* Prior to 2.3.1, a fixed initialization vector was used. This was not
* secure. This method now uses a random iv, and will silently upgrade values when
* they are re-encrypted.
*
* @param string $text Encrypted string to decrypt, normal string to encrypt
* @param string $key Key to use as the encryption key for encrypted data.
* @param string $operation Operation to perform, encrypt or decrypt
* @return string Encrypted/Decrypted string
*/
public static function rijndael($text, $key, $operation) {
if (empty($key)) {
trigger_error(__d('cake_dev', 'You cannot use an empty key for %s', 'Security::rijndael()'), E_USER_WARNING);
return '';
}
if (empty($operation) || !in_array($operation, array('encrypt', 'decrypt'))) {
trigger_error(__d('cake_dev', 'You must specify the operation for Security::rijndael(), either encrypt or decrypt'), E_USER_WARNING);
return '';
}
if (strlen($key) < 32) {
trigger_error(__d('cake_dev', 'You must use a key larger than 32 bytes for Security::rijndael()'), E_USER_WARNING);
return '';
}
$algorithm = MCRYPT_RIJNDAEL_256;
$mode = MCRYPT_MODE_CBC;
$ivSize = mcrypt_get_iv_size($algorithm, $mode);
$cryptKey = substr($key, 0, 32);
if ($operation === 'encrypt') {
$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
return $iv . '$$' . mcrypt_encrypt($algorithm, $cryptKey, $text, $mode, $iv);
}
// Backwards compatible decrypt with fixed iv
if (substr($text, $ivSize, 2) !== '$$') {
$iv = substr($key, strlen($key) - 32, 32);
return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0");
}
$iv = substr($text, 0, $ivSize);
$text = substr($text, $ivSize + 2);
return rtrim(mcrypt_decrypt($algorithm, $cryptKey, $text, $mode, $iv), "\0");
}
/**
* Generates a pseudo random salt suitable for use with php's crypt() function.
* The salt length should not exceed 27. The salt will be composed of
* [./0-9A-Za-z]{$length}.
*
* @param int $length The length of the returned salt
* @return string The generated salt
*/
protected static function _salt($length = 22) {
$salt = str_replace(
array('+', '='),
'.',
base64_encode(sha1(uniqid(Configure::read('Security.salt'), true), true))
);
return substr($salt, 0, $length);
}
/**
* One way encryption using php's crypt() function. To use blowfish hashing see ``Security::hash()``
*
* @param string $password The string to be encrypted.
* @param mixed $salt false to generate a new salt or an existing salt.
* @return string The hashed string or an empty string on error.
*/
protected static function _crypt($password, $salt = false) {
if ($salt === false) {
$salt = self::_salt(22);
$salt = vsprintf('$2a$%02d$%s', array(self::$hashCost, $salt));
}
$invalidCipher = (
strpos($salt, '$2y$') !== 0 &&
strpos($salt, '$2x$') !== 0 &&
strpos($salt, '$2a$') !== 0
);
if ($salt === true || $invalidCipher || strlen($salt) < 29) {
trigger_error(__d(
'cake_dev',
'Invalid salt: %s for %s Please visit http://www.php.net/crypt and read the appropriate section for building %s salts.',
array($salt, 'blowfish', 'blowfish')
), E_USER_WARNING);
return '';
}
return crypt($password, $salt);
}
/**
* Encrypt a value using AES-256.
*
* *Caveat* You cannot properly encrypt/decrypt data with trailing null bytes.
* Any trailing null bytes will be removed on decryption due to how PHP pads messages
* with nulls prior to encryption.
*
* @param string $plain The value to encrypt.
* @param string $key The 256 bit/32 byte key to use as a cipher key.
* @param string $hmacSalt The salt to use for the HMAC process. Leave null to use Security.salt.
* @return string Encrypted data.
* @throws CakeException On invalid data or key.
*/
public static function encrypt($plain, $key, $hmacSalt = null) {
self::_checkKey($key, 'encrypt()');
if ($hmacSalt === null) {
$hmacSalt = Configure::read('Security.salt');
}
// Generate the encryption and hmac key.
$key = substr(hash('sha256', $key . $hmacSalt), 0, 32);
$algorithm = MCRYPT_RIJNDAEL_128;
$mode = MCRYPT_MODE_CBC;
$ivSize = mcrypt_get_iv_size($algorithm, $mode);
$iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
$ciphertext = $iv . mcrypt_encrypt($algorithm, $key, $plain, $mode, $iv);
$hmac = hash_hmac('sha256', $ciphertext, $key);
return $hmac . $ciphertext;
}
/**
* Check the encryption key for proper length.
*
* @param string $key Key to check.
* @param string $method The method the key is being checked for.
* @return void
* @throws CakeException When key length is not 256 bit/32 bytes
*/
protected static function _checkKey($key, $method) {
if (strlen($key) < 32) {
throw new CakeException(__d('cake_dev', 'Invalid key for %s, key must be at least 256 bits (32 bytes) long.', $method));
}
}
/**
* Decrypt a value using AES-256.
*
* @param string $cipher The ciphertext to decrypt.
* @param string $key The 256 bit/32 byte key to use as a cipher key.
* @param string $hmacSalt The salt to use for the HMAC process. Leave null to use Security.salt.
* @return string Decrypted data. Any trailing null bytes will be removed.
* @throws CakeException On invalid data or key.
*/
public static function decrypt($cipher, $key, $hmacSalt = null) {
self::_checkKey($key, 'decrypt()');
if (empty($cipher)) {
throw new CakeException(__d('cake_dev', 'The data to decrypt cannot be empty.'));
}
if ($hmacSalt === null) {
$hmacSalt = Configure::read('Security.salt');
}
// Generate the encryption and hmac key.
$key = substr(hash('sha256', $key . $hmacSalt), 0, 32);
// Split out hmac for comparison
$macSize = 64;
$hmac = substr($cipher, 0, $macSize);
$cipher = substr($cipher, $macSize);
$compareHmac = hash_hmac('sha256', $cipher, $key);
if ($hmac !== $compareHmac) {
return false;
}
$algorithm = MCRYPT_RIJNDAEL_128;
$mode = MCRYPT_MODE_CBC;
$ivSize = mcrypt_get_iv_size($algorithm, $mode);
$iv = substr($cipher, 0, $ivSize);
$cipher = substr($cipher, $ivSize);
$plain = mcrypt_decrypt($algorithm, $key, $cipher, $mode, $iv);
return rtrim($plain, "\0");
}
}

1112
lib/Cake/Utility/Set.php Normal file

File diff suppressed because it is too large Load diff

689
lib/Cake/Utility/String.php Normal file
View file

@ -0,0 +1,689 @@
<?php
/**
* String handling methods.
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Utility
* @since CakePHP(tm) v 1.2.0.5551
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* String handling methods.
*
* @package Cake.Utility
*/
class String {
/**
* Generate a random UUID
*
* @see http://www.ietf.org/rfc/rfc4122.txt
* @return RFC 4122 UUID
*/
public static function uuid() {
$node = env('SERVER_ADDR');
if (strpos($node, ':') !== false) {
if (substr_count($node, '::')) {
$node = str_replace(
'::', str_repeat(':0000', 8 - substr_count($node, ':')) . ':', $node
);
}
$node = explode(':', $node);
$ipSix = '';
foreach ($node as $id) {
$ipSix .= str_pad(base_convert($id, 16, 2), 16, 0, STR_PAD_LEFT);
}
$node = base_convert($ipSix, 2, 10);
if (strlen($node) < 38) {
$node = null;
} else {
$node = crc32($node);
}
} elseif (empty($node)) {
$host = env('HOSTNAME');
if (empty($host)) {
$host = env('HOST');
}
if (!empty($host)) {
$ip = gethostbyname($host);
if ($ip === $host) {
$node = crc32($host);
} else {
$node = ip2long($ip);
}
}
} elseif ($node !== '127.0.0.1') {
$node = ip2long($node);
} else {
$node = null;
}
if (empty($node)) {
$node = crc32(Configure::read('Security.salt'));
}
if (function_exists('hphp_get_thread_id')) {
$pid = hphp_get_thread_id();
} elseif (function_exists('zend_thread_id')) {
$pid = zend_thread_id();
} else {
$pid = getmypid();
}
if (!$pid || $pid > 65535) {
$pid = mt_rand(0, 0xfff) | 0x4000;
}
list($timeMid, $timeLow) = explode(' ', microtime());
return sprintf(
"%08x-%04x-%04x-%02x%02x-%04x%08x", (int)$timeLow, (int)substr($timeMid, 2) & 0xffff,
mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3f) | 0x80, mt_rand(0, 0xff), $pid, $node
);
}
/**
* Tokenizes a string using $separator, ignoring any instance of $separator that appears between
* $leftBound and $rightBound.
*
* @param string $data The data to tokenize.
* @param string $separator The token to split the data on.
* @param string $leftBound The left boundary to ignore separators in.
* @param string $rightBound The right boundary to ignore separators in.
* @return mixed Array of tokens in $data or original input if empty.
*/
public static function tokenize($data, $separator = ',', $leftBound = '(', $rightBound = ')') {
if (empty($data)) {
return array();
}
$depth = 0;
$offset = 0;
$buffer = '';
$results = array();
$length = strlen($data);
$open = false;
while ($offset <= $length) {
$tmpOffset = -1;
$offsets = array(
strpos($data, $separator, $offset),
strpos($data, $leftBound, $offset),
strpos($data, $rightBound, $offset)
);
for ($i = 0; $i < 3; $i++) {
if ($offsets[$i] !== false && ($offsets[$i] < $tmpOffset || $tmpOffset == -1)) {
$tmpOffset = $offsets[$i];
}
}
if ($tmpOffset !== -1) {
$buffer .= substr($data, $offset, ($tmpOffset - $offset));
if (!$depth && $data{$tmpOffset} == $separator) {
$results[] = $buffer;
$buffer = '';
} else {
$buffer .= $data{$tmpOffset};
}
if ($leftBound != $rightBound) {
if ($data{$tmpOffset} == $leftBound) {
$depth++;
}
if ($data{$tmpOffset} == $rightBound) {
$depth--;
}
} else {
if ($data{$tmpOffset} == $leftBound) {
if (!$open) {
$depth++;
$open = true;
} else {
$depth--;
}
}
}
$offset = ++$tmpOffset;
} else {
$results[] = $buffer . substr($data, $offset);
$offset = $length + 1;
}
}
if (empty($results) && !empty($buffer)) {
$results[] = $buffer;
}
if (!empty($results)) {
return array_map('trim', $results);
}
return array();
}
/**
* Replaces variable placeholders inside a $str with any given $data. Each key in the $data array
* corresponds to a variable placeholder name in $str.
* Example: `String::insert(':name is :age years old.', array('name' => 'Bob', '65'));`
* Returns: Bob is 65 years old.
*
* Available $options are:
*
* - before: The character or string in front of the name of the variable placeholder (Defaults to `:`)
* - after: The character or string after the name of the variable placeholder (Defaults to null)
* - escape: The character or string used to escape the before character / string (Defaults to `\`)
* - format: A regex to use for matching variable placeholders. Default is: `/(?<!\\)\:%s/`
* (Overwrites before, after, breaks escape / clean)
* - clean: A boolean or array with instructions for String::cleanInsert
*
* @param string $str A string containing variable placeholders
* @param array $data A key => val array where each key stands for a placeholder variable name
* to be replaced with val
* @param array $options An array of options, see description above
* @return string
*/
public static function insert($str, $data, $options = array()) {
$defaults = array(
'before' => ':', 'after' => null, 'escape' => '\\', 'format' => null, 'clean' => false
);
$options += $defaults;
$format = $options['format'];
$data = (array)$data;
if (empty($data)) {
return ($options['clean']) ? String::cleanInsert($str, $options) : $str;
}
if (!isset($format)) {
$format = sprintf(
'/(?<!%s)%s%%s%s/',
preg_quote($options['escape'], '/'),
str_replace('%', '%%', preg_quote($options['before'], '/')),
str_replace('%', '%%', preg_quote($options['after'], '/'))
);
}
if (strpos($str, '?') !== false && is_numeric(key($data))) {
$offset = 0;
while (($pos = strpos($str, '?', $offset)) !== false) {
$val = array_shift($data);
$offset = $pos + strlen($val);
$str = substr_replace($str, $val, $pos, 1);
}
return ($options['clean']) ? String::cleanInsert($str, $options) : $str;
}
asort($data);
$dataKeys = array_keys($data);
$hashKeys = array_map('crc32', $dataKeys);
$tempData = array_combine($dataKeys, $hashKeys);
krsort($tempData);
foreach ($tempData as $key => $hashVal) {
$key = sprintf($format, preg_quote($key, '/'));
$str = preg_replace($key, $hashVal, $str);
}
$dataReplacements = array_combine($hashKeys, array_values($data));
foreach ($dataReplacements as $tmpHash => $tmpValue) {
$tmpValue = (is_array($tmpValue)) ? '' : $tmpValue;
$str = str_replace($tmpHash, $tmpValue, $str);
}
if (!isset($options['format']) && isset($options['before'])) {
$str = str_replace($options['escape'] . $options['before'], $options['before'], $str);
}
return ($options['clean']) ? String::cleanInsert($str, $options) : $str;
}
/**
* Cleans up a String::insert() formatted string with given $options depending on the 'clean' key in
* $options. The default method used is text but html is also available. The goal of this function
* is to replace all whitespace and unneeded markup around placeholders that did not get replaced
* by String::insert().
*
* @param string $str String to clean.
* @param array $options Options list.
* @return string
* @see String::insert()
*/
public static function cleanInsert($str, $options) {
$clean = $options['clean'];
if (!$clean) {
return $str;
}
if ($clean === true) {
$clean = array('method' => 'text');
}
if (!is_array($clean)) {
$clean = array('method' => $options['clean']);
}
switch ($clean['method']) {
case 'html':
$clean = array_merge(array(
'word' => '[\w,.]+',
'andText' => true,
'replacement' => '',
), $clean);
$kleenex = sprintf(
'/[\s]*[a-z]+=(")(%s%s%s[\s]*)+\\1/i',
preg_quote($options['before'], '/'),
$clean['word'],
preg_quote($options['after'], '/')
);
$str = preg_replace($kleenex, $clean['replacement'], $str);
if ($clean['andText']) {
$options['clean'] = array('method' => 'text');
$str = String::cleanInsert($str, $options);
}
break;
case 'text':
$clean = array_merge(array(
'word' => '[\w,.]+',
'gap' => '[\s]*(?:(?:and|or)[\s]*)?',
'replacement' => '',
), $clean);
$kleenex = sprintf(
'/(%s%s%s%s|%s%s%s%s)/',
preg_quote($options['before'], '/'),
$clean['word'],
preg_quote($options['after'], '/'),
$clean['gap'],
$clean['gap'],
preg_quote($options['before'], '/'),
$clean['word'],
preg_quote($options['after'], '/')
);
$str = preg_replace($kleenex, $clean['replacement'], $str);
break;
}
return $str;
}
/**
* Wraps text to a specific width, can optionally wrap at word breaks.
*
* ### Options
*
* - `width` The width to wrap to. Defaults to 72.
* - `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
* - `indent` String to indent with. Defaults to null.
* - `indentAt` 0 based index to start indenting at. Defaults to 0.
*
* @param string $text The text to format.
* @param array|int $options Array of options to use, or an integer to wrap the text to.
* @return string Formatted text.
*/
public static function wrap($text, $options = array()) {
if (is_numeric($options)) {
$options = array('width' => $options);
}
$options += array('width' => 72, 'wordWrap' => true, 'indent' => null, 'indentAt' => 0);
if ($options['wordWrap']) {
$wrapped = self::wordWrap($text, $options['width'], "\n");
} else {
$wrapped = trim(chunk_split($text, $options['width'] - 1, "\n"));
}
if (!empty($options['indent'])) {
$chunks = explode("\n", $wrapped);
for ($i = $options['indentAt'], $len = count($chunks); $i < $len; $i++) {
$chunks[$i] = $options['indent'] . $chunks[$i];
}
$wrapped = implode("\n", $chunks);
}
return $wrapped;
}
/**
* Unicode aware version of wordwrap.
*
* @param string $text The text to format.
* @param int $width The width to wrap to. Defaults to 72.
* @param string $break The line is broken using the optional break parameter. Defaults to '\n'.
* @param bool $cut If the cut is set to true, the string is always wrapped at the specified width.
* @return string Formatted text.
*/
public static function wordWrap($text, $width = 72, $break = "\n", $cut = false) {
if ($cut) {
$parts = array();
while (mb_strlen($text) > 0) {
$part = mb_substr($text, 0, $width);
$parts[] = trim($part);
$text = trim(mb_substr($text, mb_strlen($part)));
}
return implode($break, $parts);
}
$parts = array();
while (mb_strlen($text) > 0) {
if ($width >= mb_strlen($text)) {
$parts[] = trim($text);
break;
}
$part = mb_substr($text, 0, $width);
$nextChar = mb_substr($text, $width, 1);
if ($nextChar !== ' ') {
$breakAt = mb_strrpos($part, ' ');
if ($breakAt === false) {
$breakAt = mb_strpos($text, ' ', $width);
}
if ($breakAt === false) {
$parts[] = trim($text);
break;
}
$part = mb_substr($text, 0, $breakAt);
}
$part = trim($part);
$parts[] = $part;
$text = trim(mb_substr($text, mb_strlen($part)));
}
return implode($break, $parts);
}
/**
* Highlights a given phrase in a text. You can specify any expression in highlighter that
* may include the \1 expression to include the $phrase found.
*
* ### Options:
*
* - `format` The piece of html with that the phrase will be highlighted
* - `html` If true, will ignore any HTML tags, ensuring that only the correct text is highlighted
* - `regex` a custom regex rule that is used to match words, default is '|$tag|iu'
*
* @param string $text Text to search the phrase in.
* @param string|array $phrase The phrase or phrases that will be searched.
* @param array $options An array of html attributes and options.
* @return string The highlighted text
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::highlight
*/
public static function highlight($text, $phrase, $options = array()) {
if (empty($phrase)) {
return $text;
}
$defaults = array(
'format' => '<span class="highlight">\1</span>',
'html' => false,
'regex' => "|%s|iu"
);
$options += $defaults;
extract($options);
if (is_array($phrase)) {
$replace = array();
$with = array();
foreach ($phrase as $key => $segment) {
$segment = '(' . preg_quote($segment, '|') . ')';
if ($html) {
$segment = "(?![^<]+>)$segment(?![^<]+>)";
}
$with[] = (is_array($format)) ? $format[$key] : $format;
$replace[] = sprintf($options['regex'], $segment);
}
return preg_replace($replace, $with, $text);
}
$phrase = '(' . preg_quote($phrase, '|') . ')';
if ($html) {
$phrase = "(?![^<]+>)$phrase(?![^<]+>)";
}
return preg_replace(sprintf($options['regex'], $phrase), $format, $text);
}
/**
* Strips given text of all links (<a href=....).
*
* @param string $text Text
* @return string The text without links
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::stripLinks
*/
public static function stripLinks($text) {
return preg_replace('|<a\s+[^>]+>|im', '', preg_replace('|<\/a>|im', '', $text));
}
/**
* Truncates text starting from the end.
*
* Cuts a string to the length of $length and replaces the first characters
* with the ellipsis if the text is longer than length.
*
* ### Options:
*
* - `ellipsis` Will be used as Beginning and prepended to the trimmed string
* - `exact` If false, $text will not be cut mid-word
*
* @param string $text String to truncate.
* @param int $length Length of returned string, including ellipsis.
* @param array $options An array of options.
* @return string Trimmed string.
*/
public static function tail($text, $length = 100, $options = array()) {
$defaults = array(
'ellipsis' => '...', 'exact' => true
);
$options += $defaults;
extract($options);
if (!function_exists('mb_strlen')) {
class_exists('Multibyte');
}
if (mb_strlen($text) <= $length) {
return $text;
}
$truncate = mb_substr($text, mb_strlen($text) - $length + mb_strlen($ellipsis));
if (!$exact) {
$spacepos = mb_strpos($truncate, ' ');
$truncate = $spacepos === false ? '' : trim(mb_substr($truncate, $spacepos));
}
return $ellipsis . $truncate;
}
/**
* Truncates text.
*
* Cuts a string to the length of $length and replaces the last characters
* with the ellipsis if the text is longer than length.
*
* ### Options:
*
* - `ellipsis` Will be used as Ending and appended to the trimmed string (`ending` is deprecated)
* - `exact` If false, $text will not be cut mid-word
* - `html` If true, HTML tags would be handled correctly
*
* @param string $text String to truncate.
* @param int $length Length of returned string, including ellipsis.
* @param array $options An array of html attributes and options.
* @return string Trimmed string.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::truncate
*/
public static function truncate($text, $length = 100, $options = array()) {
$defaults = array(
'ellipsis' => '...', 'exact' => true, 'html' => false
);
if (isset($options['ending'])) {
$defaults['ellipsis'] = $options['ending'];
} elseif (!empty($options['html']) && Configure::read('App.encoding') === 'UTF-8') {
$defaults['ellipsis'] = "\xe2\x80\xa6";
}
$options += $defaults;
extract($options);
if (!function_exists('mb_strlen')) {
class_exists('Multibyte');
}
if ($html) {
if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
return $text;
}
$totalLength = mb_strlen(strip_tags($ellipsis));
$openTags = array();
$truncate = '';
preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
foreach ($tags as $tag) {
if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) {
if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) {
array_unshift($openTags, $tag[2]);
} elseif (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) {
$pos = array_search($closeTag[1], $openTags);
if ($pos !== false) {
array_splice($openTags, $pos, 1);
}
}
}
$truncate .= $tag[1];
$contentLength = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3]));
if ($contentLength + $totalLength > $length) {
$left = $length - $totalLength;
$entitiesLength = 0;
if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE)) {
foreach ($entities[0] as $entity) {
if ($entity[1] + 1 - $entitiesLength <= $left) {
$left--;
$entitiesLength += mb_strlen($entity[0]);
} else {
break;
}
}
}
$truncate .= mb_substr($tag[3], 0, $left + $entitiesLength);
break;
} else {
$truncate .= $tag[3];
$totalLength += $contentLength;
}
if ($totalLength >= $length) {
break;
}
}
} else {
if (mb_strlen($text) <= $length) {
return $text;
}
$truncate = mb_substr($text, 0, $length - mb_strlen($ellipsis));
}
if (!$exact) {
$spacepos = mb_strrpos($truncate, ' ');
if ($html) {
$truncateCheck = mb_substr($truncate, 0, $spacepos);
$lastOpenTag = mb_strrpos($truncateCheck, '<');
$lastCloseTag = mb_strrpos($truncateCheck, '>');
if ($lastOpenTag > $lastCloseTag) {
preg_match_all('/<[\w]+[^>]*>/s', $truncate, $lastTagMatches);
$lastTag = array_pop($lastTagMatches[0]);
$spacepos = mb_strrpos($truncate, $lastTag) + mb_strlen($lastTag);
}
$bits = mb_substr($truncate, $spacepos);
preg_match_all('/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER);
if (!empty($droppedTags)) {
if (!empty($openTags)) {
foreach ($droppedTags as $closingTag) {
if (!in_array($closingTag[1], $openTags)) {
array_unshift($openTags, $closingTag[1]);
}
}
} else {
foreach ($droppedTags as $closingTag) {
$openTags[] = $closingTag[1];
}
}
}
}
$truncate = mb_substr($truncate, 0, $spacepos);
}
$truncate .= $ellipsis;
if ($html) {
foreach ($openTags as $tag) {
$truncate .= '</' . $tag . '>';
}
}
return $truncate;
}
/**
* Extracts an excerpt from the text surrounding the phrase with a number of characters on each side
* determined by radius.
*
* @param string $text String to search the phrase in
* @param string $phrase Phrase that will be searched for
* @param int $radius The amount of characters that will be returned on each side of the founded phrase
* @param string $ellipsis Ending that will be appended
* @return string Modified string
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::excerpt
*/
public static function excerpt($text, $phrase, $radius = 100, $ellipsis = '...') {
if (empty($text) || empty($phrase)) {
return self::truncate($text, $radius * 2, array('ellipsis' => $ellipsis));
}
$append = $prepend = $ellipsis;
$phraseLen = mb_strlen($phrase);
$textLen = mb_strlen($text);
$pos = mb_strpos(mb_strtolower($text), mb_strtolower($phrase));
if ($pos === false) {
return mb_substr($text, 0, $radius) . $ellipsis;
}
$startPos = $pos - $radius;
if ($startPos <= 0) {
$startPos = 0;
$prepend = '';
}
$endPos = $pos + $phraseLen + $radius;
if ($endPos >= $textLen) {
$endPos = $textLen;
$append = '';
}
$excerpt = mb_substr($text, $startPos, $endPos - $startPos);
$excerpt = $prepend . $excerpt . $append;
return $excerpt;
}
/**
* Creates a comma separated list where the last two items are joined with 'and', forming natural English
*
* @param array $list The list to be joined
* @param string $and The word used to join the last and second last items together with. Defaults to 'and'
* @param string $separator The separator used to join all the other items together. Defaults to ', '
* @return string The glued together string.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::toList
*/
public static function toList($list, $and = 'and', $separator = ', ') {
if (count($list) > 1) {
return implode($separator, array_slice($list, null, -1)) . ' ' . $and . ' ' . array_pop($list);
}
return array_pop($list);
}
}

File diff suppressed because it is too large Load diff

393
lib/Cake/Utility/Xml.php Normal file
View file

@ -0,0 +1,393 @@
<?php
/**
* XML handling for Cake.
*
* The methods in these classes enable the datasources that use XML to work.
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Utility
* @since CakePHP v .0.10.3.1400
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('HttpSocket', 'Network/Http');
/**
* XML handling for CakePHP.
*
* The methods in these classes enable the datasources that use XML to work.
*
* @package Cake.Utility
*/
class Xml {
/**
* Initialize SimpleXMLElement or DOMDocument from a given XML string, file path, URL or array.
*
* ### Usage:
*
* Building XML from a string:
*
* `$xml = Xml::build('<example>text</example>');`
*
* Building XML from string (output DOMDocument):
*
* `$xml = Xml::build('<example>text</example>', array('return' => 'domdocument'));`
*
* Building XML from a file path:
*
* `$xml = Xml::build('/path/to/an/xml/file.xml');`
*
* Building from a remote URL:
*
* `$xml = Xml::build('http://example.com/example.xml');`
*
* Building from an array:
*
* {{{
* $value = array(
* 'tags' => array(
* 'tag' => array(
* array(
* 'id' => '1',
* 'name' => 'defect'
* ),
* array(
* 'id' => '2',
* 'name' => 'enhancement'
* )
* )
* )
* );
* $xml = Xml::build($value);
* }}}
*
* When building XML from an array ensure that there is only one top level element.
*
* ### Options
*
* - `return` Can be 'simplexml' to return object of SimpleXMLElement or 'domdocument' to return DOMDocument.
* - `loadEntities` Defaults to false. Set to true to enable loading of `<!ENTITY` definitions. This
* is disabled by default for security reasons.
* - If using array as input, you can pass `options` from Xml::fromArray.
*
* @param string|array $input XML string, a path to a file, a URL or an array
* @param array $options The options to use
* @return SimpleXMLElement|DOMDocument SimpleXMLElement or DOMDocument
* @throws XmlException
*/
public static function build($input, $options = array()) {
if (!is_array($options)) {
$options = array('return' => (string)$options);
}
$defaults = array(
'return' => 'simplexml',
'loadEntities' => false,
);
$options += $defaults;
if (is_array($input) || is_object($input)) {
return self::fromArray((array)$input, $options);
} elseif (strpos($input, '<') !== false) {
return self::_loadXml($input, $options);
} elseif (file_exists($input)) {
return self::_loadXml(file_get_contents($input), $options);
} elseif (strpos($input, 'http://') === 0 || strpos($input, 'https://') === 0) {
try {
$socket = new HttpSocket(array('request' => array('redirect' => 10)));
$response = $socket->get($input);
if (!$response->isOk()) {
throw new XmlException(__d('cake_dev', 'XML cannot be read.'));
}
return self::_loadXml($response->body, $options);
} catch (SocketException $e) {
throw new XmlException(__d('cake_dev', 'XML cannot be read.'));
}
} elseif (!is_string($input)) {
throw new XmlException(__d('cake_dev', 'Invalid input.'));
}
throw new XmlException(__d('cake_dev', 'XML cannot be read.'));
}
/**
* Parse the input data and create either a SimpleXmlElement object or a DOMDocument.
*
* @param string $input The input to load.
* @param array $options The options to use. See Xml::build()
* @return SimpleXmlElement|DOMDocument
* @throws XmlException
*/
protected static function _loadXml($input, $options) {
$hasDisable = function_exists('libxml_disable_entity_loader');
$internalErrors = libxml_use_internal_errors(true);
if ($hasDisable && !$options['loadEntities']) {
libxml_disable_entity_loader(true);
}
try {
if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
$xml = new SimpleXMLElement($input, LIBXML_NOCDATA);
} else {
$xml = new DOMDocument();
$xml->loadXML($input);
}
} catch (Exception $e) {
$xml = null;
}
if ($hasDisable && !$options['loadEntities']) {
libxml_disable_entity_loader(false);
}
libxml_use_internal_errors($internalErrors);
if ($xml === null) {
throw new XmlException(__d('cake_dev', 'Xml cannot be read.'));
}
return $xml;
}
/**
* Transform an array into a SimpleXMLElement
*
* ### Options
*
* - `format` If create childs ('tags') or attributes ('attribute').
* - `pretty` Returns formatted Xml when set to `true`. Defaults to `false`
* - `version` Version of XML document. Default is 1.0.
* - `encoding` Encoding of XML document. If null remove from XML header. Default is the some of application.
* - `return` If return object of SimpleXMLElement ('simplexml') or DOMDocument ('domdocument'). Default is SimpleXMLElement.
*
* Using the following data:
*
* {{{
* $value = array(
* 'root' => array(
* 'tag' => array(
* 'id' => 1,
* 'value' => 'defect',
* '@' => 'description'
* )
* )
* );
* }}}
*
* Calling `Xml::fromArray($value, 'tags');` Will generate:
*
* `<root><tag><id>1</id><value>defect</value>description</tag></root>`
*
* And calling `Xml::fromArray($value, 'attribute');` Will generate:
*
* `<root><tag id="1" value="defect">description</tag></root>`
*
* @param array $input Array with data
* @param array $options The options to use
* @return SimpleXMLElement|DOMDocument SimpleXMLElement or DOMDocument
* @throws XmlException
*/
public static function fromArray($input, $options = array()) {
if (!is_array($input) || count($input) !== 1) {
throw new XmlException(__d('cake_dev', 'Invalid input.'));
}
$key = key($input);
if (is_int($key)) {
throw new XmlException(__d('cake_dev', 'The key of input must be alphanumeric'));
}
if (!is_array($options)) {
$options = array('format' => (string)$options);
}
$defaults = array(
'format' => 'tags',
'version' => '1.0',
'encoding' => Configure::read('App.encoding'),
'return' => 'simplexml',
'pretty' => false
);
$options += $defaults;
$dom = new DOMDocument($options['version'], $options['encoding']);
if ($options['pretty']) {
$dom->formatOutput = true;
}
self::_fromArray($dom, $dom, $input, $options['format']);
$options['return'] = strtolower($options['return']);
if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
return new SimpleXMLElement($dom->saveXML());
}
return $dom;
}
/**
* Recursive method to create childs from array
*
* @param DOMDocument $dom Handler to DOMDocument
* @param DOMElement $node Handler to DOMElement (child)
* @param array &$data Array of data to append to the $node.
* @param string $format Either 'attribute' or 'tags'. This determines where nested keys go.
* @return void
* @throws XmlException
*/
protected static function _fromArray($dom, $node, &$data, $format) {
if (empty($data) || !is_array($data)) {
return;
}
foreach ($data as $key => $value) {
if (is_string($key)) {
if (!is_array($value)) {
if (is_bool($value)) {
$value = (int)$value;
} elseif ($value === null) {
$value = '';
}
$isNamespace = strpos($key, 'xmlns:');
if ($isNamespace !== false) {
$node->setAttributeNS('http://www.w3.org/2000/xmlns/', $key, $value);
continue;
}
if ($key[0] !== '@' && $format === 'tags') {
$child = null;
if (!is_numeric($value)) {
// Escape special characters
// http://www.w3.org/TR/REC-xml/#syntax
// https://bugs.php.net/bug.php?id=36795
$child = $dom->createElement($key, '');
$child->appendChild(new DOMText($value));
} else {
$child = $dom->createElement($key, $value);
}
$node->appendChild($child);
} else {
if ($key[0] === '@') {
$key = substr($key, 1);
}
$attribute = $dom->createAttribute($key);
$attribute->appendChild($dom->createTextNode($value));
$node->appendChild($attribute);
}
} else {
if ($key[0] === '@') {
throw new XmlException(__d('cake_dev', 'Invalid array'));
}
if (is_numeric(implode('', array_keys($value)))) { // List
foreach ($value as $item) {
$itemData = compact('dom', 'node', 'key', 'format');
$itemData['value'] = $item;
self::_createChild($itemData);
}
} else { // Struct
self::_createChild(compact('dom', 'node', 'key', 'value', 'format'));
}
}
} else {
throw new XmlException(__d('cake_dev', 'Invalid array'));
}
}
}
/**
* Helper to _fromArray(). It will create childs of arrays
*
* @param array $data Array with informations to create childs
* @return void
*/
protected static function _createChild($data) {
extract($data);
$childNS = $childValue = null;
if (is_array($value)) {
if (isset($value['@'])) {
$childValue = (string)$value['@'];
unset($value['@']);
}
if (isset($value['xmlns:'])) {
$childNS = $value['xmlns:'];
unset($value['xmlns:']);
}
} elseif (!empty($value) || $value === 0) {
$childValue = (string)$value;
}
$child = $dom->createElement($key);
if ($childValue !== null) {
$child->appendChild($dom->createTextNode($childValue));
}
if ($childNS) {
$child->setAttribute('xmlns', $childNS);
}
self::_fromArray($dom, $child, $value, $format);
$node->appendChild($child);
}
/**
* Returns this XML structure as a array.
*
* @param SimpleXMLElement|DOMDocument|DOMNode $obj SimpleXMLElement, DOMDocument or DOMNode instance
* @return array Array representation of the XML structure.
* @throws XmlException
*/
public static function toArray($obj) {
if ($obj instanceof DOMNode) {
$obj = simplexml_import_dom($obj);
}
if (!($obj instanceof SimpleXMLElement)) {
throw new XmlException(__d('cake_dev', 'The input is not instance of SimpleXMLElement, DOMDocument or DOMNode.'));
}
$result = array();
$namespaces = array_merge(array('' => ''), $obj->getNamespaces(true));
self::_toArray($obj, $result, '', array_keys($namespaces));
return $result;
}
/**
* Recursive method to toArray
*
* @param SimpleXMLElement $xml SimpleXMLElement object
* @param array &$parentData Parent array with data
* @param string $ns Namespace of current child
* @param array $namespaces List of namespaces in XML
* @return void
*/
protected static function _toArray($xml, &$parentData, $ns, $namespaces) {
$data = array();
foreach ($namespaces as $namespace) {
foreach ($xml->attributes($namespace, true) as $key => $value) {
if (!empty($namespace)) {
$key = $namespace . ':' . $key;
}
$data['@' . $key] = (string)$value;
}
foreach ($xml->children($namespace, true) as $child) {
self::_toArray($child, $data, $namespace, $namespaces);
}
}
$asString = trim((string)$xml);
if (empty($data)) {
$data = $asString;
} elseif (strlen($asString) > 0) {
$data['@'] = $asString;
}
if (!empty($ns)) {
$ns .= ':';
}
$name = $ns . $xml->getName();
if (isset($parentData[$name])) {
if (!is_array($parentData[$name]) || !isset($parentData[$name][0])) {
$parentData[$name] = array($parentData[$name]);
}
$parentData[$name][] = $data;
} else {
$parentData[$name] = $data;
}
}
}