code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
<?php /** * Bake Template for Controller action generation. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Console.Templates.default.actions * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> /** * <?php echo $admin ?>index method * * @return void */ public function <?php echo $admin ?>index() { $this-><?php echo $currentModelName ?>->recursive = 0; $this->set('<?php echo $pluralName ?>', $this->paginate()); } /** * <?php echo $admin ?>view method * * @param string $id * @return void */ public function <?php echo $admin ?>view($id = null) { $this-><?php echo $currentModelName; ?>->id = $id; if (!$this-><?php echo $currentModelName; ?>->exists()) { throw new NotFoundException(__('Invalid <?php echo strtolower($singularHumanName); ?>')); } $this->set('<?php echo $singularName; ?>', $this-><?php echo $currentModelName; ?>->read(null, $id)); } <?php $compact = array(); ?> /** * <?php echo $admin ?>add method * * @return void */ public function <?php echo $admin ?>add() { if ($this->request->is('post')) { $this-><?php echo $currentModelName; ?>->create(); if ($this-><?php echo $currentModelName; ?>->save($this->request->data)) { <?php if ($wannaUseSession): ?> $this->Session->setFlash(__('The <?php echo strtolower($singularHumanName); ?> has been saved')); $this->redirect(array('action' => 'index')); <?php else: ?> $this->flash(__('<?php echo ucfirst(strtolower($currentModelName)); ?> saved.'), array('action' => 'index')); <?php endif; ?> } else { <?php if ($wannaUseSession): ?> $this->Session->setFlash(__('The <?php echo strtolower($singularHumanName); ?> could not be saved. Please, try again.')); <?php endif; ?> } } <?php foreach (array('belongsTo', 'hasAndBelongsToMany') as $assoc): foreach ($modelObj->{$assoc} as $associationName => $relation): if (!empty($associationName)): $otherModelName = $this->_modelName($associationName); $otherPluralName = $this->_pluralName($associationName); echo "\t\t\${$otherPluralName} = \$this->{$currentModelName}->{$otherModelName}->find('list');\n"; $compact[] = "'{$otherPluralName}'"; endif; endforeach; endforeach; if (!empty($compact)): echo "\t\t\$this->set(compact(".join(', ', $compact)."));\n"; endif; ?> } <?php $compact = array(); ?> /** * <?php echo $admin ?>edit method * * @param string $id * @return void */ public function <?php echo $admin; ?>edit($id = null) { $this-><?php echo $currentModelName; ?>->id = $id; if (!$this-><?php echo $currentModelName; ?>->exists()) { throw new NotFoundException(__('Invalid <?php echo strtolower($singularHumanName); ?>')); } if ($this->request->is('post') || $this->request->is('put')) { if ($this-><?php echo $currentModelName; ?>->save($this->request->data)) { <?php if ($wannaUseSession): ?> $this->Session->setFlash(__('The <?php echo strtolower($singularHumanName); ?> has been saved')); $this->redirect(array('action' => 'index')); <?php else: ?> $this->flash(__('The <?php echo strtolower($singularHumanName); ?> has been saved.'), array('action' => 'index')); <?php endif; ?> } else { <?php if ($wannaUseSession): ?> $this->Session->setFlash(__('The <?php echo strtolower($singularHumanName); ?> could not be saved. Please, try again.')); <?php endif; ?> } } else { $this->request->data = $this-><?php echo $currentModelName; ?>->read(null, $id); } <?php foreach (array('belongsTo', 'hasAndBelongsToMany') as $assoc): foreach ($modelObj->{$assoc} as $associationName => $relation): if (!empty($associationName)): $otherModelName = $this->_modelName($associationName); $otherPluralName = $this->_pluralName($associationName); echo "\t\t\${$otherPluralName} = \$this->{$currentModelName}->{$otherModelName}->find('list');\n"; $compact[] = "'{$otherPluralName}'"; endif; endforeach; endforeach; if (!empty($compact)): echo "\t\t\$this->set(compact(".join(', ', $compact)."));\n"; endif; ?> } /** * <?php echo $admin ?>delete method * * @param string $id * @return void */ public function <?php echo $admin; ?>delete($id = null) { if (!$this->request->is('post')) { throw new MethodNotAllowedException(); } $this-><?php echo $currentModelName; ?>->id = $id; if (!$this-><?php echo $currentModelName; ?>->exists()) { throw new NotFoundException(__('Invalid <?php echo strtolower($singularHumanName); ?>')); } if ($this-><?php echo $currentModelName; ?>->delete()) { <?php if ($wannaUseSession): ?> $this->Session->setFlash(__('<?php echo ucfirst(strtolower($singularHumanName)); ?> deleted')); $this->redirect(array('action'=>'index')); <?php else: ?> $this->flash(__('<?php echo ucfirst(strtolower($singularHumanName)); ?> deleted'), array('action' => 'index')); <?php endif; ?> } <?php if ($wannaUseSession): ?> $this->Session->setFlash(__('<?php echo ucfirst(strtolower($singularHumanName)); ?> was not deleted')); <?php else: ?> $this->flash(__('<?php echo ucfirst(strtolower($singularHumanName)); ?> was not deleted'), array('action' => 'index')); <?php endif; ?> $this->redirect(array('action' => 'index')); }
0001-bee
trunk/cakephp2/lib/Cake/Console/Templates/default/actions/controller_actions.ctp
PHP
gpl3
5,658
<?php /** * Controller bake template file * * Allows templating of Controllers generated from bake. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Console.Templates.default.classes * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ echo "<?php\n"; echo "App::uses('{$plugin}AppController', '{$pluginPath}Controller');\n"; ?> /** * <?php echo $controllerName; ?> Controller * <?php if (!$isScaffold) { $defaultModel = Inflector::singularize($controllerName); echo " * @property {$defaultModel} \${$defaultModel}\n"; if (!empty($components)) { foreach ($components as $component) { echo " * @property {$component}Component \${$component}\n"; } } } ?> */ class <?php echo $controllerName; ?>Controller extends <?php echo $plugin; ?>AppController { <?php if ($isScaffold): ?> /** * Scaffold * * @var mixed */ public $scaffold; <?php else: ?> <?php if (count($helpers)): echo "/**\n * Helpers\n *\n * @var array\n */\n"; echo "\tvar \$helpers = array("; for ($i = 0, $len = count($helpers); $i < $len; $i++): if ($i != $len - 1): echo "'" . Inflector::camelize($helpers[$i]) . "', "; else: echo "'" . Inflector::camelize($helpers[$i]) . "'"; endif; endfor; echo ");\n"; endif; if (count($components)): echo "/**\n * Components\n *\n * @var array\n */\n"; echo "\tpublic \$components = array("; for ($i = 0, $len = count($components); $i < $len; $i++): if ($i != $len - 1): echo "'" . Inflector::camelize($components[$i]) . "', "; else: echo "'" . Inflector::camelize($components[$i]) . "'"; endif; endfor; echo ");\n"; endif; echo $actions; endif; ?> }
0001-bee
trunk/cakephp2/lib/Cake/Console/Templates/default/classes/controller.ctp
PHP
gpl3
2,085
<?php /** * Model template file. * * Used by bake to create new Model files. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Console.Templates.default.classes * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ echo "<?php\n"; echo "App::uses('{$plugin}AppModel', '{$pluginPath}Model');\n"; ?> /** * <?php echo $name ?> Model * <?php foreach (array('hasOne', 'belongsTo', 'hasMany', 'hasAndBelongsToMany') as $assocType) { if (!empty($associations[$assocType])) { foreach ($associations[$assocType] as $relation) { echo " * @property {$relation['className']} \${$relation['alias']}\n"; } } } ?> */ class <?php echo $name ?> extends <?php echo $plugin; ?>AppModel { <?php if ($useDbConfig != 'default'): ?> /** * Use database config * * @var string */ public $useDbConfig = '<?php echo $useDbConfig; ?>'; <?php endif;?> <?php if ($useTable && $useTable !== Inflector::tableize($name)): $table = "'$useTable'"; echo "/**\n * Use table\n *\n * @var mixed False or table name\n */\n"; echo "\tpublic \$useTable = $table;\n"; endif; if ($primaryKey !== 'id'): ?> /** * Primary key field * * @var string */ public $primaryKey = '<?php echo $primaryKey; ?>'; <?php endif; if ($displayField): ?> /** * Display field * * @var string */ public $displayField = '<?php echo $displayField; ?>'; <?php endif; if (!empty($validate)): echo "/**\n * Validation rules\n *\n * @var array\n */\n"; echo "\tpublic \$validate = array(\n"; foreach ($validate as $field => $validations): echo "\t\t'$field' => array(\n"; foreach ($validations as $key => $validator): echo "\t\t\t'$key' => array(\n"; echo "\t\t\t\t'rule' => array('$validator'),\n"; echo "\t\t\t\t//'message' => 'Your custom message here',\n"; echo "\t\t\t\t//'allowEmpty' => false,\n"; echo "\t\t\t\t//'required' => false,\n"; echo "\t\t\t\t//'last' => false, // Stop validation after this rule\n"; echo "\t\t\t\t//'on' => 'create', // Limit validation to 'create' or 'update' operations\n"; echo "\t\t\t),\n"; endforeach; echo "\t\t),\n"; endforeach; echo "\t);\n"; endif; foreach ($associations as $assoc): if (!empty($assoc)): ?> //The Associations below have been created with all possible keys, those that are not needed can be removed <?php break; endif; endforeach; foreach (array('hasOne', 'belongsTo') as $assocType): if (!empty($associations[$assocType])): $typeCount = count($associations[$assocType]); echo "\n/**\n * $assocType associations\n *\n * @var array\n */"; echo "\n\tpublic \$$assocType = array("; foreach ($associations[$assocType] as $i => $relation): $out = "\n\t\t'{$relation['alias']}' => array(\n"; $out .= "\t\t\t'className' => '{$relation['className']}',\n"; $out .= "\t\t\t'foreignKey' => '{$relation['foreignKey']}',\n"; $out .= "\t\t\t'conditions' => '',\n"; $out .= "\t\t\t'fields' => '',\n"; $out .= "\t\t\t'order' => ''\n"; $out .= "\t\t)"; if ($i + 1 < $typeCount) { $out .= ","; } echo $out; endforeach; echo "\n\t);\n"; endif; endforeach; if (!empty($associations['hasMany'])): $belongsToCount = count($associations['hasMany']); echo "\n/**\n * hasMany associations\n *\n * @var array\n */"; echo "\n\tpublic \$hasMany = array("; foreach ($associations['hasMany'] as $i => $relation): $out = "\n\t\t'{$relation['alias']}' => array(\n"; $out .= "\t\t\t'className' => '{$relation['className']}',\n"; $out .= "\t\t\t'foreignKey' => '{$relation['foreignKey']}',\n"; $out .= "\t\t\t'dependent' => false,\n"; $out .= "\t\t\t'conditions' => '',\n"; $out .= "\t\t\t'fields' => '',\n"; $out .= "\t\t\t'order' => '',\n"; $out .= "\t\t\t'limit' => '',\n"; $out .= "\t\t\t'offset' => '',\n"; $out .= "\t\t\t'exclusive' => '',\n"; $out .= "\t\t\t'finderQuery' => '',\n"; $out .= "\t\t\t'counterQuery' => ''\n"; $out .= "\t\t)"; if ($i + 1 < $belongsToCount) { $out .= ","; } echo $out; endforeach; echo "\n\t);\n\n"; endif; if (!empty($associations['hasAndBelongsToMany'])): $habtmCount = count($associations['hasAndBelongsToMany']); echo "\n/**\n * hasAndBelongsToMany associations\n *\n * @var array\n */"; echo "\n\tpublic \$hasAndBelongsToMany = array("; foreach ($associations['hasAndBelongsToMany'] as $i => $relation): $out = "\n\t\t'{$relation['alias']}' => array(\n"; $out .= "\t\t\t'className' => '{$relation['className']}',\n"; $out .= "\t\t\t'joinTable' => '{$relation['joinTable']}',\n"; $out .= "\t\t\t'foreignKey' => '{$relation['foreignKey']}',\n"; $out .= "\t\t\t'associationForeignKey' => '{$relation['associationForeignKey']}',\n"; $out .= "\t\t\t'unique' => true,\n"; $out .= "\t\t\t'conditions' => '',\n"; $out .= "\t\t\t'fields' => '',\n"; $out .= "\t\t\t'order' => '',\n"; $out .= "\t\t\t'limit' => '',\n"; $out .= "\t\t\t'offset' => '',\n"; $out .= "\t\t\t'finderQuery' => '',\n"; $out .= "\t\t\t'deleteQuery' => '',\n"; $out .= "\t\t\t'insertQuery' => ''\n"; $out .= "\t\t)"; if ($i + 1 < $habtmCount) { $out .= ","; } echo $out; endforeach; echo "\n\t);\n\n"; endif; ?> }
0001-bee
trunk/cakephp2/lib/Cake/Console/Templates/default/classes/model.ctp
PHP
gpl3
5,557
<?php /** * Fixture Template file * * Fixture Template used when baking fixtures with bake * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Console.Templates.default.classes * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <?php echo '<?php' . "\n"; ?> /* <?php echo $model; ?> Fixture generated on: <?php echo date('Y-m-d H:i:s') . " : ". time(); ?> */ /** * <?php echo $model; ?>Fixture * */ class <?php echo $model; ?>Fixture extends CakeTestFixture { <?php if ($table): ?> /** * Table name * * @var string */ public $table = '<?php echo $table; ?>'; <?php endif; ?> <?php if ($import): ?> /** * Import * * @var array */ public $import = <?php echo $import; ?>; <?php endif; ?> <?php if ($schema): ?> /** * Fields * * @var array */ public $fields = <?php echo $schema; ?>; <?php endif;?> <?php if ($records): ?> /** * Records * * @var array */ public $records = <?php echo $records; ?>; <?php endif;?> }
0001-bee
trunk/cakephp2/lib/Cake/Console/Templates/default/classes/fixture.ctp
PHP
gpl3
1,415
<?php /** * Test Case bake template * * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Console.Templates.default.classes * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ echo "<?php\n"; echo "/* ". $className ." Test cases generated on: " . date('Y-m-d H:i:s') . " : ". time() . "*/\n"; ?> App::uses('<?php echo $fullClassName; ?>', '<?php echo $realType; ?>'); <?php if ($mock and strtolower($type) == 'controller'): ?> /** * Test<?php echo $fullClassName; ?> * */ class Test<?php echo $fullClassName; ?> extends <?php echo $fullClassName; ?> { /** * Auto render * * @var boolean */ public $autoRender = false; /** * Redirect action * * @param mixed $url * @param mixed $status * @param boolean $exit * @return void */ public function redirect($url, $status = null, $exit = true) { $this->redirectUrl = $url; } } <?php endif; ?> /** * <?php echo $fullClassName; ?> Test Case * */ class <?php echo $fullClassName; ?>TestCase extends CakeTestCase { <?php if (!empty($fixtures)): ?> /** * Fixtures * * @var array */ public $fixtures = array('<?php echo join("', '", $fixtures); ?>'); <?php endif; ?> /** * setUp method * * @return void */ public function setUp() { parent::setUp(); $this-><?php echo $className . ' = ' . $construction; ?> } /** * tearDown method * * @return void */ public function tearDown() { unset($this-><?php echo $className;?>); parent::tearDown(); } <?php foreach ($methods as $method): ?> /** * test<?php echo Inflector::classify($method); ?> method * * @return void */ public function test<?php echo Inflector::classify($method); ?>() { } <?php endforeach;?> }
0001-bee
trunk/cakephp2/lib/Cake/Console/Templates/default/classes/test.ctp
PHP
gpl3
2,126
<?php /** * ConsoleOptionParser file * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('TaskCollection', 'Console'); App::uses('ConsoleOutput', 'Console'); App::uses('ConsoleInput', 'Console'); App::uses('ConsoleInputSubcommand', 'Console'); App::uses('ConsoleInputOption', 'Console'); App::uses('ConsoleInputArgument', 'Console'); App::uses('ConsoleOptionParser', 'Console'); App::uses('HelpFormatter', 'Console'); /** * Handles parsing the ARGV in the command line and provides support * for GetOpt compatible option definition. Provides a builder pattern implementation * for creating shell option parsers. * * ### Options * * Named arguments come in two forms, long and short. Long arguments are preceded * by two - and give a more verbose option name. i.e. `--version`. Short arguments are * preceded by one - and are only one character long. They usually match with a long option, * and provide a more terse alternative. * * ### Using Options * * Options can be defined with both long and short forms. By using `$parser->addOption()` * you can define new options. The name of the option is used as its long form, and you * can supply an additional short form, with the `short` option. Short options should * only be one letter long. Using more than one letter for a short option will raise an exception. * * Calling options can be done using syntax similar to most *nix command line tools. Long options * cane either include an `=` or leave it out. * * `cake myshell command --connection default --name=something` * * Short options can be defined signally or in groups. * * `cake myshell command -cn` * * Short options can be combined into groups as seen above. Each letter in a group * will be treated as a separate option. The previous example is equivalent to: * * `cake myshell command -c -n` * * Short options can also accept values: * * `cake myshell command -c default` * * ### Positional arguments * * If no positional arguments are defined, all of them will be parsed. If you define positional * arguments any arguments greater than those defined will cause exceptions. Additionally you can * declare arguments as optional, by setting the required param to false. * * `$parser->addArgument('model', array('required' => false));` * * ### Providing Help text * * By providing help text for your positional arguments and named arguments, the ConsoleOptionParser * can generate a help display for you. You can view the help for shells by using the `--help` or `-h` switch. * * @package Cake.Console */ class ConsoleOptionParser { /** * Description text - displays before options when help is generated * * @see ConsoleOptionParser::description() * @var string */ protected $_description = null; /** * Epilog text - displays after options when help is generated * * @see ConsoleOptionParser::epilog() * @var string */ protected $_epilog = null; /** * Option definitions. * * @see ConsoleOptionParser::addOption() * @var array */ protected $_options = array(); /** * Map of short -> long options, generated when using addOption() * * @var string */ protected $_shortOptions = array(); /** * Positional argument definitions. * * @see ConsoleOptionParser::addArgument() * @var array */ protected $_args = array(); /** * Subcommands for this Shell. * * @see ConsoleOptionParser::addSubcommand() * @var array */ protected $_subcommands = array(); /** * Command name. * * @var string */ protected $_command = ''; /** * Construct an OptionParser so you can define its behavior * * @param string $command The command name this parser is for. The command name is used for generating help. * @param boolean $defaultOptions Whether you want the verbose and quiet options set. Setting * this to false will prevent the addition of `--verbose` & `--quiet` options. */ public function __construct($command = null, $defaultOptions = true) { $this->command($command); $this->addOption('help', array( 'short' => 'h', 'help' => __d('cake_console', 'Display this help.'), 'boolean' => true )); if ($defaultOptions) { $this->addOption('verbose', array( 'short' => 'v', 'help' => __d('cake_console', 'Enable verbose output.'), 'boolean' => true ))->addOption('quiet', array( 'short' => 'q', 'help' => __d('cake_console', 'Enable quiet output.'), 'boolean' => true )); } } /** * Static factory method for creating new OptionParsers so you can chain methods off of them. * * @param string $command The command name this parser is for. The command name is used for generating help. * @param boolean $defaultOptions Whether you want the verbose and quiet options set. * @return ConsoleOptionParser */ public static function create($command, $defaultOptions = true) { return new ConsoleOptionParser($command, $defaultOptions); } /** * Build a parser from an array. Uses an array like * * {{{ * $spec = array( * 'description' => 'text', * 'epilog' => 'text', * 'arguments' => array( * // list of arguments compatible with addArguments. * ), * 'options' => array( * // list of options compatible with addOptions * ), * 'subcommands' => array( * // list of subcommands to add. * ) * ); * }}} * * @param array $spec The spec to build the OptionParser with. * @return ConsoleOptionParser */ public static function buildFromArray($spec) { $parser = new ConsoleOptionParser($spec['command']); if (!empty($spec['arguments'])) { $parser->addArguments($spec['arguments']); } if (!empty($spec['options'])) { $parser->addOptions($spec['options']); } if (!empty($spec['subcommands'])) { $parser->addSubcommands($spec['subcommands']); } if (!empty($spec['description'])) { $parser->description($spec['description']); } if (!empty($spec['epilog'])) { $parser->epilog($spec['epilog']); } return $parser; } /** * Get or set the command name for shell/task. * * @param string $text The text to set, or null if you want to read * @return mixed If reading, the value of the command. If setting $this will be returned */ public function command($text = null) { if ($text !== null) { $this->_command = Inflector::underscore($text); return $this; } return $this->_command; } /** * Get or set the description text for shell/task. * * @param mixed $text The text to set, or null if you want to read. If an array the * text will be imploded with "\n" * @return mixed If reading, the value of the description. If setting $this will be returned */ public function description($text = null) { if ($text !== null) { if (is_array($text)) { $text = implode("\n", $text); } $this->_description = $text; return $this; } return $this->_description; } /** * Get or set an epilog to the parser. The epilog is added to the end of * the options and arguments listing when help is generated. * * @param mixed $text Text when setting or null when reading. If an array the text will be imploded with "\n" * @return mixed If reading, the value of the epilog. If setting $this will be returned. */ public function epilog($text = null) { if ($text !== null) { if (is_array($text)) { $text = implode("\n", $text); } $this->_epilog = $text; return $this; } return $this->_epilog; } /** * Add an option to the option parser. Options allow you to define optional or required * parameters for your console application. Options are defined by the parameters they use. * * ### Options * * - `short` - The single letter variant for this option, leave undefined for none. * - `help` - Help text for this option. Used when generating help for the option. * - `default` - The default value for this option. Defaults are added into the parsed params when the * attached option is not provided or has no value. Using default and boolean together will not work. * are added into the parsed parameters when the option is undefined. Defaults to null. * - `boolean` - The option uses no value, its just a boolean switch. Defaults to false. * If an option is defined as boolean, it will always be added to the parsed params. If no present * it will be false, if present it will be true. * - `choices` A list of valid choices for this option. If left empty all values are valid.. * An exception will be raised when parse() encounters an invalid value. * * @param mixed $name The long name you want to the value to be parsed out as when options are parsed. * Will also accept an instance of ConsoleInputOption * @param array $options An array of parameters that define the behavior of the option * @return ConsoleOptionParser $this. */ public function addOption($name, $options = array()) { if (is_object($name) && $name instanceof ConsoleInputOption) { $option = $name; $name = $option->name(); } else { $defaults = array( 'name' => $name, 'short' => null, 'help' => '', 'default' => null, 'boolean' => false, 'choices' => array() ); $options = array_merge($defaults, $options); $option = new ConsoleInputOption($options); } $this->_options[$name] = $option; if ($option->short() !== null) { $this->_shortOptions[$option->short()] = $name; } return $this; } /** * Add a positional argument to the option parser. * * ### Params * * - `help` The help text to display for this argument. * - `required` Whether this parameter is required. * - `index` The index for the arg, if left undefined the argument will be put * onto the end of the arguments. If you define the same index twice the first * option will be overwritten. * - `choices` A list of valid choices for this argument. If left empty all values are valid.. * An exception will be raised when parse() encounters an invalid value. * * @param mixed $name The name of the argument. Will also accept an instance of ConsoleInputArgument * @param array $params Parameters for the argument, see above. * @return ConsoleOptionParser $this. */ public function addArgument($name, $params = array()) { if (is_object($name) && $name instanceof ConsoleInputArgument) { $arg = $name; $index = count($this->_args); } else { $defaults = array( 'name' => $name, 'help' => '', 'index' => count($this->_args), 'required' => false, 'choices' => array() ); $options = array_merge($defaults, $params); $index = $options['index']; unset($options['index']); $arg = new ConsoleInputArgument($options); } $this->_args[$index] = $arg; return $this; } /** * Add multiple arguments at once. Take an array of argument definitions. * The keys are used as the argument names, and the values as params for the argument. * * @param array $args Array of arguments to add. * @see ConsoleOptionParser::addArgument() * @return ConsoleOptionParser $this */ public function addArguments(array $args) { foreach ($args as $name => $params) { $this->addArgument($name, $params); } return $this; } /** * Add multiple options at once. Takes an array of option definitions. * The keys are used as option names, and the values as params for the option. * * @param array $options Array of options to add. * @see ConsoleOptionParser::addOption() * @return ConsoleOptionParser $this */ public function addOptions(array $options) { foreach ($options as $name => $params) { $this->addOption($name, $params); } return $this; } /** * Append a subcommand to the subcommand list. * Subcommands are usually methods on your Shell, but can also be used to document Tasks. * * ### Options * * - `help` - Help text for the subcommand. * - `parser` - A ConsoleOptionParser for the subcommand. This allows you to create method * specific option parsers. When help is generated for a subcommand, if a parser is present * it will be used. * * @param mixed $name Name of the subcommand. Will also accept an instance of ConsoleInputSubcommand * @param array $options Array of params, see above. * @return ConsoleOptionParser $this. */ public function addSubcommand($name, $options = array()) { if (is_object($name) && $name instanceof ConsoleInputSubcommand) { $command = $name; $name = $command->name(); } else { $defaults = array( 'name' => $name, 'help' => '', 'parser' => null ); $options = array_merge($defaults, $options); $command = new ConsoleInputSubcommand($options); } $this->_subcommands[$name] = $command; return $this; } /** * Add multiple subcommands at once. * * @param array $commands Array of subcommands. * @return ConsoleOptionParser $this */ public function addSubcommands(array $commands) { foreach ($commands as $name => $params) { $this->addSubcommand($name, $params); } return $this; } /** * Gets the arguments defined in the parser. * * @return array Array of argument descriptions */ public function arguments() { return $this->_args; } /** * Get the defined options in the parser. * * @return array */ public function options() { return $this->_options; } /** * Get the array of defined subcommands * * @return array */ public function subcommands() { return $this->_subcommands; } /** * Parse the argv array into a set of params and args. If $command is not null * and $command is equal to a subcommand that has a parser, that parser will be used * to parse the $argv * * @param array $argv Array of args (argv) to parse. * @param string $command The subcommand to use. If this parameter is a subcommand, that has a parser, * That parser will be used to parse $argv instead. * @return Array array($params, $args) * @throws ConsoleException When an invalid parameter is encountered. */ public function parse($argv, $command = null) { if (isset($this->_subcommands[$command]) && $this->_subcommands[$command]->parser()) { return $this->_subcommands[$command]->parser()->parse($argv); } $params = $args = array(); $this->_tokens = $argv; while ($token = array_shift($this->_tokens)) { if (substr($token, 0, 2) == '--') { $params = $this->_parseLongOption($token, $params); } elseif (substr($token, 0, 1) == '-') { $params = $this->_parseShortOption($token, $params); } else { $args = $this->_parseArg($token, $args); } } foreach ($this->_args as $i => $arg) { if ($arg->isRequired() && !isset($args[$i]) && empty($params['help'])) { throw new ConsoleException( __d('cake_console', 'Missing required arguments. %s is required.', $arg->name()) ); } } foreach ($this->_options as $option) { $name = $option->name(); $isBoolean = $option->isBoolean(); $default = $option->defaultValue(); if ($default !== null && !isset($params[$name]) && !$isBoolean) { $params[$name] = $default; } if ($isBoolean && !isset($params[$name])) { $params[$name] = false; } } return array($params, $args); } /** * Gets formatted help for this parser object. * Generates help text based on the description, options, arguments, subcommands and epilog * in the parser. * * @param string $subcommand If present and a valid subcommand that has a linked parser. * That subcommands help will be shown instead. * @param string $format Define the output format, can be text or xml * @param integer $width The width to format user content to. Defaults to 72 * @return string Generated help. */ public function help($subcommand = null, $format = 'text', $width = 72) { if ( isset($this->_subcommands[$subcommand]) && $this->_subcommands[$subcommand]->parser() instanceof self ) { $subparser = $this->_subcommands[$subcommand]->parser(); $subparser->command($this->command() . ' ' . $subparser->command()); return $subparser->help(null, $format, $width); } $formatter = new HelpFormatter($this); if ($format == 'text' || $format === true) { return $formatter->text($width); } elseif ($format == 'xml') { return $formatter->xml(); } } /** * Parse the value for a long option out of $this->_tokens. Will handle * options with an `=` in them. * * @param string $option The option to parse. * @param array $params The params to append the parsed value into * @return array Params with $option added in. */ protected function _parseLongOption($option, $params) { $name = substr($option, 2); if (strpos($name, '=') !== false) { list($name, $value) = explode('=', $name, 2); array_unshift($this->_tokens, $value); } return $this->_parseOption($name, $params); } /** * Parse the value for a short option out of $this->_tokens * If the $option is a combination of multiple shortcuts like -otf * they will be shifted onto the token stack and parsed individually. * * @param string $option The option to parse. * @param array $params The params to append the parsed value into * @return array Params with $option added in. */ protected function _parseShortOption($option, $params) { $key = substr($option, 1); if (strlen($key) > 1) { $flags = str_split($key); $key = $flags[0]; for ($i = 1, $len = count($flags); $i < $len; $i++) { array_unshift($this->_tokens, '-' . $flags[$i]); } } if (!isset($this->_shortOptions[$key])) { throw new ConsoleException(__d('cake_console', 'Unknown short option `%s`', $key)); } $name = $this->_shortOptions[$key]; return $this->_parseOption($name, $params); } /** * Parse an option by its name index. * * @param string $name The name to parse. * @param array $params The params to append the parsed value into * @return array Params with $option added in. * @throws ConsoleException */ protected function _parseOption($name, $params) { if (!isset($this->_options[$name])) { throw new ConsoleException(__d('cake_console', 'Unknown option `%s`', $name)); } $option = $this->_options[$name]; $isBoolean = $option->isBoolean(); $nextValue = $this->_nextToken(); if (!$isBoolean && !empty($nextValue) && !$this->_optionExists($nextValue)) { array_shift($this->_tokens); $value = $nextValue; } elseif ($isBoolean) { $value = true; } else { $value = $option->defaultValue(); } if ($option->validChoice($value)) { $params[$name] = $value; return $params; } } /** * Check to see if $name has an option (short/long) defined for it. * * @param string $name The name of the option. * @return boolean */ protected function _optionExists($name) { if (substr($name, 0, 2) === '--') { return isset($this->_options[substr($name, 2)]); } if ($name{0} === '-' && $name{1} !== '-') { return isset($this->_shortOptions[$name{1}]); } return false; } /** * Parse an argument, and ensure that the argument doesn't exceed the number of arguments * and that the argument is a valid choice. * * @param string $argument The argument to append * @param array $args The array of parsed args to append to. * @return array Args * @throws ConsoleException */ protected function _parseArg($argument, $args) { if (empty($this->_args)) { array_push($args, $argument); return $args; } $next = count($args); if (!isset($this->_args[$next])) { throw new ConsoleException(__d('cake_console', 'Too many arguments.')); } if ($this->_args[$next]->validChoice($argument)) { array_push($args, $argument); return $args; } } /** * Find the next token in the argv set. * * @return string next token or '' */ protected function _nextToken() { return isset($this->_tokens[0]) ? $this->_tokens[0] : ''; } }
0001-bee
trunk/cakephp2/lib/Cake/Console/ConsoleOptionParser.php
PHP
gpl3
20,140
<?php /** * AppShell file * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * This is a placeholder class. * Create the same file in app/Console/Command/AppShell.php * * Add your application-wide methods in the class below, your shells * will inherit them. * * @package Cake.Console */ class AppShell extends Shell { }
0001-bee
trunk/cakephp2/lib/Cake/Console/AppShell.php
PHP
gpl3
840
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: :: Bake is a shell script for running CakePHP bake script :: PHP 5 :: :: CakePHP(tm) : Rapid Development Framework (http://cakephp.org) :: Copyright 2005-2011, Cake Software Foundation, Inc. :: :: Licensed under The MIT License :: Redistributions of files must retain the above copyright notice. :: :: @copyright Copyright 2005-2011, Cake Software Foundation, Inc. :: @link http://cakephp.org CakePHP(tm) Project :: @package cake.console :: @since CakePHP(tm) v 1.2.0.5012 :: @license MIT License (http://www.opensource.org/licenses/mit-license.php) :: :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: In order for this script to work as intended, the cake\console\ folder must be in your PATH @echo. @echo off SET app=%0 SET lib=%~dp0 php -q "%lib%cake.php" -working "%CD% " %* echo. exit /B %ERRORLEVEL%
0001-bee
trunk/cakephp2/lib/Cake/Console/cake.bat
Batchfile
gpl3
973
#!/bin/bash ################################################################################ # # Bake is a shell script for running CakePHP bake script # PHP 5 # # CakePHP(tm) : Rapid Development Framework (http://cakephp.org) # Copyright 2005-2011, Cake Software Foundation, Inc. # # Licensed under The MIT License # Redistributions of files must retain the above copyright notice. # # @copyright Copyright 2005-2011, Cake Software Foundation, Inc. # @link http://cakephp.org CakePHP(tm) Project # @package cake.console # @since CakePHP(tm) v 1.2.0.5012 # @license MIT License (http://www.opensource.org/licenses/mit-license.php) # ################################################################################ LIB=$(cd -P -- "$(dirname -- "$0")" && pwd -P) && LIB=$LIB/$(basename -- "$0") while [ -h "$LIB" ]; do DIR=$(dirname -- "$LIB") SYM=$(readlink "$LIB") LIB=$(cd "$DIR" && cd $(dirname -- "$SYM") && pwd)/$(basename -- "$SYM") done LIB=$(dirname -- "$LIB")/ APP=`pwd` exec php -q "$LIB"cake.php -working "$APP" "$@" exit;
0001-bee
trunk/cakephp2/lib/Cake/Console/cake
Shell
gpl3
1,062
<?php /** * ErrorHandler for Console Shells * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('ErrorHandler', 'Error'); App::uses('ConsoleOutput', 'Console'); App::uses('CakeLog', 'Log'); /** * Error Handler for Cake console. Does simple printing of the * exception that occurred and the stack trace of the error. * * @package Cake.Console */ class ConsoleErrorHandler { /** * Standard error stream. * * @var ConsoleOutput */ public static $stderr; /** * Get the stderr object for the console error handling. * * @return ConsoleOutput */ public static function getStderr() { if (empty(self::$stderr)) { self::$stderr = new ConsoleOutput('php://stderr'); } return self::$stderr; } /** * Handle a exception in the console environment. Prints a message to stderr. * * @param Exception $exception The exception to handle * @return void */ public function handleException(Exception $exception) { $stderr = self::getStderr(); $stderr->write(__d('cake_console', "<error>Error:</error> %s\n%s", $exception->getMessage(), $exception->getTraceAsString() )); $this->_stop($exception->getCode() ? $exception->getCode() : 1); } /** * Handle errors in the console environment. Writes errors to stderr, * and logs messages if Configure::read('debug') is 0. * * @param integer $code Error code * @param string $description Description of the error. * @param string $file The file the error occurred in. * @param integer $line The line the error occurred on. * @param array $context The backtrace of the error. * @return void */ public function handleError($code, $description, $file = null, $line = null, $context = null) { if (error_reporting() === 0) { return; } $stderr = self::getStderr(); list($name, $log) = ErrorHandler::mapErrorCode($code); $message = __d('cake_console', '%s in [%s, line %s]', $description, $file, $line); $stderr->write(__d('cake_console', "<error>%s Error:</error> %s\n", $name, $message)); if (Configure::read('debug') == 0) { CakeLog::write($log, $message); } } /** * Wrapper for exit(), used for testing. * * @param $code int The exit code. */ protected function _stop($code = 0) { exit($code); } }
0001-bee
trunk/cakephp2/lib/Cake/Console/ConsoleErrorHandler.php
PHP
gpl3
2,727
<?php /** * Default routes that CakePHP provides as catch all routes. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Connects the default, built-in routes, including prefix and plugin routes. The following routes are created * in the order below: * * For each of the Routing.prefixes the following routes are created. Routes containing `:plugin` are only * created when your application has one or more plugins. * * - `/:prefix/:plugin` a plugin shortcut route. * - `/:prefix/:plugin/:action/*` a plugin shortcut route. * - `/:prefix/:plugin/:controller` * - `/:prefix/:plugin/:controller/:action/*` * - `/:prefix/:controller` * - `/:prefix/:controller/:action/*` * * If plugins are found in your application the following routes are created: * * - `/:plugin` a plugin shortcut route. * - `/:plugin/:action/*` a plugin shortcut route. * - `/:plugin/:controller` * - `/:plugin/:controller/:action/*` * * And lastly the following catch-all routes are connected. * * - `/:controller' * - `/:controller/:action/*' * * You can disable the connection of default routes by deleting the require inside APP/Config/routes.php. */ $prefixes = Router::prefixes(); if ($plugins = CakePlugin::loaded()) { App::uses('PluginShortRoute', 'Routing/Route'); foreach ($plugins as $key => $value) { $plugins[$key] = Inflector::underscore($value); } $pluginPattern = implode('|', $plugins); $match = array('plugin' => $pluginPattern); $shortParams = array('routeClass' => 'PluginShortRoute', 'plugin' => $pluginPattern); foreach ($prefixes as $prefix) { $params = array('prefix' => $prefix, $prefix => true); $indexParams = $params + array('action' => 'index'); Router::connect("/{$prefix}/:plugin", $indexParams, $shortParams); Router::connect("/{$prefix}/:plugin/:controller", $indexParams, $match); Router::connect("/{$prefix}/:plugin/:controller/:action/*", $params, $match); } Router::connect('/:plugin', array('action' => 'index'), $shortParams); Router::connect('/:plugin/:controller', array('action' => 'index'), $match); Router::connect('/:plugin/:controller/:action/*', array(), $match); } foreach ($prefixes as $prefix) { $params = array('prefix' => $prefix, $prefix => true); $indexParams = $params + array('action' => 'index'); Router::connect("/{$prefix}/:controller", $indexParams); Router::connect("/{$prefix}/:controller/:action/*", $params); } Router::connect('/:controller', array('action' => 'index')); Router::connect('/:controller/:action/*'); $namedConfig = Router::namedConfig(); if ($namedConfig['rules'] === false) { Router::connectNamed(true); } unset($namedConfig, $params, $indexParams, $prefix, $prefixes, $shortParams, $match, $pluginPattern, $plugins, $key, $value);
0001-bee
trunk/cakephp2/lib/Cake/Config/routes.php
PHP
gpl3
3,313
<?php /** * Core Configurations. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config * @since CakePHP(tm) v 1.1.11.4062 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ return $config['Cake.version'] = '2.0.0';
0001-bee
trunk/cakephp2/lib/Cake/Config/config.php
PHP
gpl3
664
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+1F00 through U+1FFF * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['1f00_1fff'][] = array('upper' => 7944, 'status' => 'C', 'lower' => array(7936, 953)); /* GREEK CAPITAL LETTER ALPHA WITH PSILI */ $config['1f00_1fff'][] = array('upper' => 7945, 'status' => 'C', 'lower' => array(7937)); /* GREEK CAPITAL LETTER ALPHA WITH DASIA */ $config['1f00_1fff'][] = array('upper' => 7946, 'status' => 'C', 'lower' => array(7938)); /* GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA */ $config['1f00_1fff'][] = array('upper' => 7947, 'status' => 'C', 'lower' => array(7939)); /* GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA */ $config['1f00_1fff'][] = array('upper' => 7948, 'status' => 'C', 'lower' => array(7940)); /* GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA */ $config['1f00_1fff'][] = array('upper' => 7949, 'status' => 'C', 'lower' => array(7941)); /* GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA */ $config['1f00_1fff'][] = array('upper' => 7950, 'status' => 'C', 'lower' => array(7942)); /* GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 7951, 'status' => 'C', 'lower' => array(7943)); /* GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 7960, 'status' => 'C', 'lower' => array(7952)); /* GREEK CAPITAL LETTER EPSILON WITH PSILI */ $config['1f00_1fff'][] = array('upper' => 7961, 'status' => 'C', 'lower' => array(7953)); /* GREEK CAPITAL LETTER EPSILON WITH DASIA */ $config['1f00_1fff'][] = array('upper' => 7962, 'status' => 'C', 'lower' => array(7954)); /* GREEK CAPITAL LETTER EPSILON WITH PSILI AND VARIA */ $config['1f00_1fff'][] = array('upper' => 7963, 'status' => 'C', 'lower' => array(7955)); /* GREEK CAPITAL LETTER EPSILON WITH DASIA AND VARIA */ $config['1f00_1fff'][] = array('upper' => 7964, 'status' => 'C', 'lower' => array(7956)); /* GREEK CAPITAL LETTER EPSILON WITH PSILI AND OXIA */ $config['1f00_1fff'][] = array('upper' => 7965, 'status' => 'C', 'lower' => array(7957)); /* GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA */ $config['1f00_1fff'][] = array('upper' => 7976, 'status' => 'C', 'lower' => array(7968)); /* GREEK CAPITAL LETTER ETA WITH PSILI */ $config['1f00_1fff'][] = array('upper' => 7977, 'status' => 'C', 'lower' => array(7969)); /* GREEK CAPITAL LETTER ETA WITH DASIA */ $config['1f00_1fff'][] = array('upper' => 7978, 'status' => 'C', 'lower' => array(7970)); /* GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA */ $config['1f00_1fff'][] = array('upper' => 7979, 'status' => 'C', 'lower' => array(7971)); /* GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA */ $config['1f00_1fff'][] = array('upper' => 7980, 'status' => 'C', 'lower' => array(7972)); /* GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA */ $config['1f00_1fff'][] = array('upper' => 7981, 'status' => 'C', 'lower' => array(7973)); /* GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA */ $config['1f00_1fff'][] = array('upper' => 7982, 'status' => 'C', 'lower' => array(7974)); /* GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 7983, 'status' => 'C', 'lower' => array(7975)); /* GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 7992, 'status' => 'C', 'lower' => array(7984)); /* GREEK CAPITAL LETTER IOTA WITH PSILI */ $config['1f00_1fff'][] = array('upper' => 7993, 'status' => 'C', 'lower' => array(7985)); /* GREEK CAPITAL LETTER IOTA WITH DASIA */ $config['1f00_1fff'][] = array('upper' => 7994, 'status' => 'C', 'lower' => array(7986)); /* GREEK CAPITAL LETTER IOTA WITH PSILI AND VARIA */ $config['1f00_1fff'][] = array('upper' => 7995, 'status' => 'C', 'lower' => array(7987)); /* GREEK CAPITAL LETTER IOTA WITH DASIA AND VARIA */ $config['1f00_1fff'][] = array('upper' => 7996, 'status' => 'C', 'lower' => array(7988)); /* GREEK CAPITAL LETTER IOTA WITH PSILI AND OXIA */ $config['1f00_1fff'][] = array('upper' => 7997, 'status' => 'C', 'lower' => array(7989)); /* GREEK CAPITAL LETTER IOTA WITH DASIA AND OXIA */ $config['1f00_1fff'][] = array('upper' => 7998, 'status' => 'C', 'lower' => array(7990)); /* GREEK CAPITAL LETTER IOTA WITH PSILI AND PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 7999, 'status' => 'C', 'lower' => array(7991)); /* GREEK CAPITAL LETTER IOTA WITH DASIA AND PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 8008, 'status' => 'C', 'lower' => array(8000)); /* GREEK CAPITAL LETTER OMICRON WITH PSILI */ $config['1f00_1fff'][] = array('upper' => 8009, 'status' => 'C', 'lower' => array(8001)); /* GREEK CAPITAL LETTER OMICRON WITH DASIA */ $config['1f00_1fff'][] = array('upper' => 8010, 'status' => 'C', 'lower' => array(8002)); /* GREEK CAPITAL LETTER OMICRON WITH PSILI AND VARIA */ $config['1f00_1fff'][] = array('upper' => 8011, 'status' => 'C', 'lower' => array(8003)); /* GREEK CAPITAL LETTER OMICRON WITH DASIA AND VARIA */ $config['1f00_1fff'][] = array('upper' => 8012, 'status' => 'C', 'lower' => array(8004)); /* GREEK CAPITAL LETTER OMICRON WITH PSILI AND OXIA */ $config['1f00_1fff'][] = array('upper' => 8013, 'status' => 'C', 'lower' => array(8005)); /* GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA */ $config['1f00_1fff'][] = array('upper' => 8016, 'status' => 'F', 'lower' => array(965, 787)); /* GREEK SMALL LETTER UPSILON WITH PSILI */ $config['1f00_1fff'][] = array('upper' => 8018, 'status' => 'F', 'lower' => array(965, 787, 768)); /* GREEK SMALL LETTER UPSILON WITH PSILI AND VARIA */ $config['1f00_1fff'][] = array('upper' => 8020, 'status' => 'F', 'lower' => array(965, 787, 769)); /* GREEK SMALL LETTER UPSILON WITH PSILI AND OXIA */ $config['1f00_1fff'][] = array('upper' => 8022, 'status' => 'F', 'lower' => array(965, 787, 834)); /* GREEK SMALL LETTER UPSILON WITH PSILI AND PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 8025, 'status' => 'C', 'lower' => array(8017)); /* GREEK CAPITAL LETTER UPSILON WITH DASIA */ $config['1f00_1fff'][] = array('upper' => 8027, 'status' => 'C', 'lower' => array(8019)); /* GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA */ $config['1f00_1fff'][] = array('upper' => 8029, 'status' => 'C', 'lower' => array(8021)); /* GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA */ $config['1f00_1fff'][] = array('upper' => 8031, 'status' => 'C', 'lower' => array(8023)); /* GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 8040, 'status' => 'C', 'lower' => array(8032)); /* GREEK CAPITAL LETTER OMEGA WITH PSILI */ $config['1f00_1fff'][] = array('upper' => 8041, 'status' => 'C', 'lower' => array(8033)); /* GREEK CAPITAL LETTER OMEGA WITH DASIA */ $config['1f00_1fff'][] = array('upper' => 8042, 'status' => 'C', 'lower' => array(8034)); /* GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA */ $config['1f00_1fff'][] = array('upper' => 8043, 'status' => 'C', 'lower' => array(8035)); /* GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA */ $config['1f00_1fff'][] = array('upper' => 8044, 'status' => 'C', 'lower' => array(8036)); /* GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA */ $config['1f00_1fff'][] = array('upper' => 8045, 'status' => 'C', 'lower' => array(8037)); /* GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA */ $config['1f00_1fff'][] = array('upper' => 8046, 'status' => 'C', 'lower' => array(8038)); /* GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 8047, 'status' => 'C', 'lower' => array(8039)); /* GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 8064, 'status' => 'F', 'lower' => array(7936, 953)); /* GREEK SMALL LETTER ALPHA WITH PSILI AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8065, 'status' => 'F', 'lower' => array(7937, 953)); /* GREEK SMALL LETTER ALPHA WITH DASIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8066, 'status' => 'F', 'lower' => array(7938, 953)); /* GREEK SMALL LETTER ALPHA WITH PSILI AND VARIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8067, 'status' => 'F', 'lower' => array(7939, 953)); /* GREEK SMALL LETTER ALPHA WITH DASIA AND VARIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8068, 'status' => 'F', 'lower' => array(7940, 953)); /* GREEK SMALL LETTER ALPHA WITH PSILI AND OXIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8069, 'status' => 'F', 'lower' => array(7941, 953)); /* GREEK SMALL LETTER ALPHA WITH DASIA AND OXIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8070, 'status' => 'F', 'lower' => array(7942, 953)); /* GREEK SMALL LETTER ALPHA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8071, 'status' => 'F', 'lower' => array(7943, 953)); /* GREEK SMALL LETTER ALPHA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8072, 'status' => 'F', 'lower' => array(7936, 953)); /* GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8072, 'status' => 'S', 'lower' => array(8064)); /* GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8073, 'status' => 'F', 'lower' => array(7937, 953)); /* GREEK CAPITAL LETTER ALPHA WITH DASIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8073, 'status' => 'S', 'lower' => array(8065)); /* GREEK CAPITAL LETTER ALPHA WITH DASIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8074, 'status' => 'F', 'lower' => array(7938, 953)); /* GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8074, 'status' => 'S', 'lower' => array(8066)); /* GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8075, 'status' => 'F', 'lower' => array(7939, 953)); /* GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8075, 'status' => 'S', 'lower' => array(8067)); /* GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8076, 'status' => 'F', 'lower' => array(7940, 953)); /* GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8076, 'status' => 'S', 'lower' => array(8068)); /* GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8077, 'status' => 'F', 'lower' => array(7941, 953)); /* GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8077, 'status' => 'S', 'lower' => array(8069)); /* GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8078, 'status' => 'F', 'lower' => array(7942, 953)); /* GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8078, 'status' => 'S', 'lower' => array(8070)); /* GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8079, 'status' => 'F', 'lower' => array(7943, 953)); /* GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8079, 'status' => 'S', 'lower' => array(8071)); /* GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8080, 'status' => 'F', 'lower' => array(7968, 953)); /* GREEK SMALL LETTER ETA WITH PSILI AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8081, 'status' => 'F', 'lower' => array(7969, 953)); /* GREEK SMALL LETTER ETA WITH DASIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8082, 'status' => 'F', 'lower' => array(7970, 953)); /* GREEK SMALL LETTER ETA WITH PSILI AND VARIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8083, 'status' => 'F', 'lower' => array(7971, 953)); /* GREEK SMALL LETTER ETA WITH DASIA AND VARIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8084, 'status' => 'F', 'lower' => array(7972, 953)); /* GREEK SMALL LETTER ETA WITH PSILI AND OXIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8085, 'status' => 'F', 'lower' => array(7973, 953)); /* GREEK SMALL LETTER ETA WITH DASIA AND OXIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8086, 'status' => 'F', 'lower' => array(7974, 953)); /* GREEK SMALL LETTER ETA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8087, 'status' => 'F', 'lower' => array(7975, 953)); /* GREEK SMALL LETTER ETA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8088, 'status' => 'F', 'lower' => array(7968, 953)); /* GREEK CAPITAL LETTER ETA WITH PSILI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8088, 'status' => 'S', 'lower' => array(8080)); /* GREEK CAPITAL LETTER ETA WITH PSILI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8089, 'status' => 'F', 'lower' => array(7969, 953)); /* GREEK CAPITAL LETTER ETA WITH DASIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8089, 'status' => 'S', 'lower' => array(8081)); /* GREEK CAPITAL LETTER ETA WITH DASIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8090, 'status' => 'F', 'lower' => array(7970, 953)); /* GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8090, 'status' => 'S', 'lower' => array(8082)); /* GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8091, 'status' => 'F', 'lower' => array(7971, 953)); /* GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8091, 'status' => 'S', 'lower' => array(8083)); /* GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8092, 'status' => 'F', 'lower' => array(7972, 953)); /* GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8092, 'status' => 'S', 'lower' => array(8084)); /* GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8093, 'status' => 'F', 'lower' => array(7973, 953)); /* GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8093, 'status' => 'S', 'lower' => array(8085)); /* GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8094, 'status' => 'F', 'lower' => array(7974, 953)); /* GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8094, 'status' => 'S', 'lower' => array(8086)); /* GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8095, 'status' => 'F', 'lower' => array(7975, 953)); /* GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8095, 'status' => 'S', 'lower' => array(8087)); /* GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8096, 'status' => 'F', 'lower' => array(8032, 953)); /* GREEK SMALL LETTER OMEGA WITH PSILI AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8097, 'status' => 'F', 'lower' => array(8033, 953)); /* GREEK SMALL LETTER OMEGA WITH DASIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8098, 'status' => 'F', 'lower' => array(8034, 953)); /* GREEK SMALL LETTER OMEGA WITH PSILI AND VARIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8099, 'status' => 'F', 'lower' => array(8035, 953)); /* GREEK SMALL LETTER OMEGA WITH DASIA AND VARIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8100, 'status' => 'F', 'lower' => array(8036, 953)); /* GREEK SMALL LETTER OMEGA WITH PSILI AND OXIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8101, 'status' => 'F', 'lower' => array(8037, 953)); /* GREEK SMALL LETTER OMEGA WITH DASIA AND OXIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8102, 'status' => 'F', 'lower' => array(8038, 953)); /* GREEK SMALL LETTER OMEGA WITH PSILI AND PERISPOMENI AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8103, 'status' => 'F', 'lower' => array(8039, 953)); /* GREEK SMALL LETTER OMEGA WITH DASIA AND PERISPOMENI AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8104, 'status' => 'F', 'lower' => array(8032, 953)); /* GREEK CAPITAL LETTER OMEGA WITH PSILI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8104, 'status' => 'S', 'lower' => array(8096)); /* GREEK CAPITAL LETTER OMEGA WITH PSILI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8105, 'status' => 'F', 'lower' => array(8033, 953)); /* GREEK CAPITAL LETTER OMEGA WITH DASIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8105, 'status' => 'S', 'lower' => array(8097)); /* GREEK CAPITAL LETTER OMEGA WITH DASIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8106, 'status' => 'F', 'lower' => array(8034, 953)); /* GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8106, 'status' => 'S', 'lower' => array(8098)); /* GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8107, 'status' => 'F', 'lower' => array(8035, 953)); /* GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8107, 'status' => 'S', 'lower' => array(8099)); /* GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8108, 'status' => 'F', 'lower' => array(8036, 953)); /* GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8108, 'status' => 'S', 'lower' => array(8100)); /* GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8109, 'status' => 'F', 'lower' => array(8037, 953)); /* GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8109, 'status' => 'S', 'lower' => array(8101)); /* GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8110, 'status' => 'F', 'lower' => array(8038, 953)); /* GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8110, 'status' => 'S', 'lower' => array(8102)); /* GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8111, 'status' => 'F', 'lower' => array(8039, 953)); /* GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8111, 'status' => 'S', 'lower' => array(8103)); /* GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8114, 'status' => 'F', 'lower' => array(8048, 953)); /* GREEK SMALL LETTER ALPHA WITH VARIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8115, 'status' => 'F', 'lower' => array(945, 953)); /* GREEK SMALL LETTER ALPHA WITH YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8116, 'status' => 'F', 'lower' => array(940, 953)); /* GREEK SMALL LETTER ALPHA WITH OXIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8118, 'status' => 'F', 'lower' => array(945, 834)); /* GREEK SMALL LETTER ALPHA WITH PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 8119, 'status' => 'F', 'lower' => array(945, 834, 953)); /* GREEK SMALL LETTER ALPHA WITH PERISPOMENI AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8120, 'status' => 'C', 'lower' => array(8112)); /* GREEK CAPITAL LETTER ALPHA WITH VRACHY */ $config['1f00_1fff'][] = array('upper' => 8121, 'status' => 'C', 'lower' => array(8113)); /* GREEK CAPITAL LETTER ALPHA WITH MACRON */ $config['1f00_1fff'][] = array('upper' => 8122, 'status' => 'C', 'lower' => array(8048)); /* GREEK CAPITAL LETTER ALPHA WITH VARIA */ $config['1f00_1fff'][] = array('upper' => 8123, 'status' => 'C', 'lower' => array(8049)); /* GREEK CAPITAL LETTER ALPHA WITH OXIA */ $config['1f00_1fff'][] = array('upper' => 8124, 'status' => 'F', 'lower' => array(945, 953)); /* GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8124, 'status' => 'S', 'lower' => array(8115)); /* GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8126, 'status' => 'C', 'lower' => array(953)); /* GREEK PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8130, 'status' => 'F', 'lower' => array(8052, 953)); /* GREEK SMALL LETTER ETA WITH VARIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8131, 'status' => 'F', 'lower' => array(951, 953)); /* GREEK SMALL LETTER ETA WITH YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8132, 'status' => 'F', 'lower' => array(942, 953)); /* GREEK SMALL LETTER ETA WITH OXIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8134, 'status' => 'F', 'lower' => array(951, 834)); /* GREEK SMALL LETTER ETA WITH PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 8135, 'status' => 'F', 'lower' => array(951, 834, 953)); /* GREEK SMALL LETTER ETA WITH PERISPOMENI AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8136, 'status' => 'C', 'lower' => array(8050)); /* GREEK CAPITAL LETTER EPSILON WITH VARIA */ $config['1f00_1fff'][] = array('upper' => 8137, 'status' => 'C', 'lower' => array(8051)); /* GREEK CAPITAL LETTER EPSILON WITH OXIA */ $config['1f00_1fff'][] = array('upper' => 8138, 'status' => 'C', 'lower' => array(8052)); /* GREEK CAPITAL LETTER ETA WITH VARIA */ $config['1f00_1fff'][] = array('upper' => 8139, 'status' => 'C', 'lower' => array(8053)); /* GREEK CAPITAL LETTER ETA WITH OXIA */ $config['1f00_1fff'][] = array('upper' => 8140, 'status' => 'F', 'lower' => array(951, 953)); /* GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8140, 'status' => 'S', 'lower' => array(8131)); /* GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8146, 'status' => 'F', 'lower' => array(953, 776, 768)); /* GREEK SMALL LETTER IOTA WITH DIALYTIKA AND VARIA */ $config['1f00_1fff'][] = array('upper' => 8147, 'status' => 'F', 'lower' => array(953, 776, 769)); /* GREEK SMALL LETTER IOTA WITH DIALYTIKA AND OXIA */ $config['1f00_1fff'][] = array('upper' => 8150, 'status' => 'F', 'lower' => array(953, 834)); /* GREEK SMALL LETTER IOTA WITH PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 8151, 'status' => 'F', 'lower' => array(953, 776, 834)); /* GREEK SMALL LETTER IOTA WITH DIALYTIKA AND PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 8152, 'status' => 'C', 'lower' => array(8144)); /* GREEK CAPITAL LETTER IOTA WITH VRACHY */ $config['1f00_1fff'][] = array('upper' => 8153, 'status' => 'C', 'lower' => array(8145)); /* GREEK CAPITAL LETTER IOTA WITH MACRON */ $config['1f00_1fff'][] = array('upper' => 8154, 'status' => 'C', 'lower' => array(8054)); /* GREEK CAPITAL LETTER IOTA WITH VARIA */ $config['1f00_1fff'][] = array('upper' => 8155, 'status' => 'C', 'lower' => array(8055)); /* GREEK CAPITAL LETTER IOTA WITH OXIA */ $config['1f00_1fff'][] = array('upper' => 8162, 'status' => 'F', 'lower' => array(965, 776, 768)); /* GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND VARIA */ $config['1f00_1fff'][] = array('upper' => 8163, 'status' => 'F', 'lower' => array(965, 776, 769)); /* GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND OXIA */ $config['1f00_1fff'][] = array('upper' => 8164, 'status' => 'F', 'lower' => array(961, 787)); /* GREEK SMALL LETTER RHO WITH PSILI */ $config['1f00_1fff'][] = array('upper' => 8166, 'status' => 'F', 'lower' => array(965, 834)); /* GREEK SMALL LETTER UPSILON WITH PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 8167, 'status' => 'F', 'lower' => array(965, 776, 834)); /* GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 8168, 'status' => 'C', 'lower' => array(8160)); /* GREEK CAPITAL LETTER UPSILON WITH VRACHY */ $config['1f00_1fff'][] = array('upper' => 8169, 'status' => 'C', 'lower' => array(8161)); /* GREEK CAPITAL LETTER UPSILON WITH MACRON */ $config['1f00_1fff'][] = array('upper' => 8170, 'status' => 'C', 'lower' => array(8058)); /* GREEK CAPITAL LETTER UPSILON WITH VARIA */ $config['1f00_1fff'][] = array('upper' => 8171, 'status' => 'C', 'lower' => array(8059)); /* GREEK CAPITAL LETTER UPSILON WITH OXIA */ $config['1f00_1fff'][] = array('upper' => 8172, 'status' => 'C', 'lower' => array(8165)); /* GREEK CAPITAL LETTER RHO WITH DASIA */ $config['1f00_1fff'][] = array('upper' => 8178, 'status' => 'F', 'lower' => array(8060, 953)); /* GREEK SMALL LETTER OMEGA WITH VARIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8179, 'status' => 'F', 'lower' => array(969, 953)); /* GREEK SMALL LETTER OMEGA WITH YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8180, 'status' => 'F', 'lower' => array(974, 953)); /* GREEK SMALL LETTER OMEGA WITH OXIA AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8182, 'status' => 'F', 'lower' => array(969, 834)); /* GREEK SMALL LETTER OMEGA WITH PERISPOMENI */ $config['1f00_1fff'][] = array('upper' => 8183, 'status' => 'F', 'lower' => array(969, 834, 953)); /* GREEK SMALL LETTER OMEGA WITH PERISPOMENI AND YPOGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8184, 'status' => 'C', 'lower' => array(8056)); /* GREEK CAPITAL LETTER OMICRON WITH VARIA */ $config['1f00_1fff'][] = array('upper' => 8185, 'status' => 'C', 'lower' => array(8057)); /* GREEK CAPITAL LETTER OMICRON WITH OXIA */ $config['1f00_1fff'][] = array('upper' => 8186, 'status' => 'C', 'lower' => array(8060)); /* GREEK CAPITAL LETTER OMEGA WITH VARIA */ $config['1f00_1fff'][] = array('upper' => 8187, 'status' => 'C', 'lower' => array(8061)); /* GREEK CAPITAL LETTER OMEGA WITH OXIA */ $config['1f00_1fff'][] = array('upper' => 8188, 'status' => 'F', 'lower' => array(969, 953)); /* GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI */ $config['1f00_1fff'][] = array('upper' => 8188, 'status' => 'S', 'lower' => array(8179)); /* GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/1f00_1fff.php
PHP
gpl3
28,470
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+0500 through U+052F * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['0500_052f'][] = array('upper' => 1280, 'status' => 'C', 'lower' => array(1281)); /* CYRILLIC CAPITAL LETTER KOMI DE */ $config['0500_052f'][] = array('upper' => 1282, 'status' => 'C', 'lower' => array(1283)); /* CYRILLIC CAPITAL LETTER KOMI DJE */ $config['0500_052f'][] = array('upper' => 1284, 'status' => 'C', 'lower' => array(1285)); /* CYRILLIC CAPITAL LETTER KOMI ZJE */ $config['0500_052f'][] = array('upper' => 1286, 'status' => 'C', 'lower' => array(1287)); /* CYRILLIC CAPITAL LETTER KOMI DZJE */ $config['0500_052f'][] = array('upper' => 1288, 'status' => 'C', 'lower' => array(1289)); /* CYRILLIC CAPITAL LETTER KOMI LJE */ $config['0500_052f'][] = array('upper' => 1290, 'status' => 'C', 'lower' => array(1291)); /* CYRILLIC CAPITAL LETTER KOMI NJE */ $config['0500_052f'][] = array('upper' => 1292, 'status' => 'C', 'lower' => array(1293)); /* CYRILLIC CAPITAL LETTER KOMI SJE */ $config['0500_052f'][] = array('upper' => 1294, 'status' => 'C', 'lower' => array(1295)); /* CYRILLIC CAPITAL LETTER KOMI TJE */ $config['0500_052f'][] = array('upper' => 1296, 'status' => 'C', 'lower' => array(1297)); /* CYRILLIC CAPITAL LETTER ZE */ $config['0500_052f'][] = array('upper' => 1298, 'status' => 'C', 'lower' => array(1299)); /* CYRILLIC CAPITAL LETTER El with hook */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/0500_052f.php
PHP
gpl3
3,124
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+2C60 through U+2C7F * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['2c60_2c7f'][] = array('upper' => 11360, 'status' => 'C', 'lower' => array(11361)); /* LATIN CAPITAL LETTER L WITH DOUBLE BAR */ $config['2c60_2c7f'][] = array('upper' => 11362, 'status' => 'C', 'lower' => array(619)); /* LATIN CAPITAL LETTER L WITH MIDDLE TILDE */ $config['2c60_2c7f'][] = array('upper' => 11363, 'status' => 'C', 'lower' => array(7549)); /* LATIN CAPITAL LETTER P WITH STROKE */ $config['2c60_2c7f'][] = array('upper' => 11364, 'status' => 'C', 'lower' => array(637)); /* LATIN CAPITAL LETTER R WITH TAIL */ $config['2c60_2c7f'][] = array('upper' => 11367, 'status' => 'C', 'lower' => array(11368)); /* LATIN CAPITAL LETTER H WITH DESCENDER */ $config['2c60_2c7f'][] = array('upper' => 11369, 'status' => 'C', 'lower' => array(11370)); /* LATIN CAPITAL LETTER K WITH DESCENDER */ $config['2c60_2c7f'][] = array('upper' => 11371, 'status' => 'C', 'lower' => array(11372)); /* LATIN CAPITAL LETTER Z WITH DESCENDER */ $config['2c60_2c7f'][] = array('upper' => 11381, 'status' => 'C', 'lower' => array(11382)); /* LATIN CAPITAL LETTER HALF H */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/2c60_2c7f.php
PHP
gpl3
2,905
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+1E00 through U+1EFF * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['1e00_1eff'][] = array('upper' => 7680, 'status' => 'C', 'lower' => array(7681)); /* LATIN CAPITAL LETTER A WITH RING BELOW */ $config['1e00_1eff'][] = array('upper' => 7682, 'status' => 'C', 'lower' => array(7683)); /* LATIN CAPITAL LETTER B WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7684, 'status' => 'C', 'lower' => array(7685)); /* LATIN CAPITAL LETTER B WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7686, 'status' => 'C', 'lower' => array(7687)); /* LATIN CAPITAL LETTER B WITH LINE BELOW */ $config['1e00_1eff'][] = array('upper' => 7688, 'status' => 'C', 'lower' => array(7689)); /* LATIN CAPITAL LETTER C WITH CEDILLA AND ACUTE */ $config['1e00_1eff'][] = array('upper' => 7690, 'status' => 'C', 'lower' => array(7691)); /* LATIN CAPITAL LETTER D WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7692, 'status' => 'C', 'lower' => array(7693)); /* LATIN CAPITAL LETTER D WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7694, 'status' => 'C', 'lower' => array(7695)); /* LATIN CAPITAL LETTER D WITH LINE BELOW */ $config['1e00_1eff'][] = array('upper' => 7696, 'status' => 'C', 'lower' => array(7697)); /* LATIN CAPITAL LETTER D WITH CEDILLA */ $config['1e00_1eff'][] = array('upper' => 7698, 'status' => 'C', 'lower' => array(7699)); /* LATIN CAPITAL LETTER D WITH CIRCUMFLEX BELOW */ $config['1e00_1eff'][] = array('upper' => 7700, 'status' => 'C', 'lower' => array(7701)); /* LATIN CAPITAL LETTER E WITH MACRON AND GRAVE */ $config['1e00_1eff'][] = array('upper' => 7702, 'status' => 'C', 'lower' => array(7703)); /* LATIN CAPITAL LETTER E WITH MACRON AND ACUTE */ $config['1e00_1eff'][] = array('upper' => 7704, 'status' => 'C', 'lower' => array(7705)); /* LATIN CAPITAL LETTER E WITH CIRCUMFLEX BELOW */ $config['1e00_1eff'][] = array('upper' => 7706, 'status' => 'C', 'lower' => array(7707)); /* LATIN CAPITAL LETTER E WITH TILDE BELOW */ $config['1e00_1eff'][] = array('upper' => 7708, 'status' => 'C', 'lower' => array(7709)); /* LATIN CAPITAL LETTER E WITH CEDILLA AND BREVE */ $config['1e00_1eff'][] = array('upper' => 7710, 'status' => 'C', 'lower' => array(7711)); /* LATIN CAPITAL LETTER F WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7712, 'status' => 'C', 'lower' => array(7713)); /* LATIN CAPITAL LETTER G WITH MACRON */ $config['1e00_1eff'][] = array('upper' => 7714, 'status' => 'C', 'lower' => array(7715)); /* LATIN CAPITAL LETTER H WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7716, 'status' => 'C', 'lower' => array(7717)); /* LATIN CAPITAL LETTER H WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7718, 'status' => 'C', 'lower' => array(7719)); /* LATIN CAPITAL LETTER H WITH DIAERESIS */ $config['1e00_1eff'][] = array('upper' => 7720, 'status' => 'C', 'lower' => array(7721)); /* LATIN CAPITAL LETTER H WITH CEDILLA */ $config['1e00_1eff'][] = array('upper' => 7722, 'status' => 'C', 'lower' => array(7723)); /* LATIN CAPITAL LETTER H WITH BREVE BELOW */ $config['1e00_1eff'][] = array('upper' => 7724, 'status' => 'C', 'lower' => array(7725)); /* LATIN CAPITAL LETTER I WITH TILDE BELOW */ $config['1e00_1eff'][] = array('upper' => 7726, 'status' => 'C', 'lower' => array(7727)); /* LATIN CAPITAL LETTER I WITH DIAERESIS AND ACUTE */ $config['1e00_1eff'][] = array('upper' => 7728, 'status' => 'C', 'lower' => array(7729)); /* LATIN CAPITAL LETTER K WITH ACUTE */ $config['1e00_1eff'][] = array('upper' => 7730, 'status' => 'C', 'lower' => array(7731)); /* LATIN CAPITAL LETTER K WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7732, 'status' => 'C', 'lower' => array(7733)); /* LATIN CAPITAL LETTER K WITH LINE BELOW */ $config['1e00_1eff'][] = array('upper' => 7734, 'status' => 'C', 'lower' => array(7735)); /* LATIN CAPITAL LETTER L WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7736, 'status' => 'C', 'lower' => array(7737)); /* LATIN CAPITAL LETTER L WITH DOT BELOW AND MACRON */ $config['1e00_1eff'][] = array('upper' => 7738, 'status' => 'C', 'lower' => array(7739)); /* LATIN CAPITAL LETTER L WITH LINE BELOW */ $config['1e00_1eff'][] = array('upper' => 7740, 'status' => 'C', 'lower' => array(7741)); /* LATIN CAPITAL LETTER L WITH CIRCUMFLEX BELOW */ $config['1e00_1eff'][] = array('upper' => 7742, 'status' => 'C', 'lower' => array(7743)); /* LATIN CAPITAL LETTER M WITH ACUTE */ $config['1e00_1eff'][] = array('upper' => 7744, 'status' => 'C', 'lower' => array(7745)); /* LATIN CAPITAL LETTER M WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7746, 'status' => 'C', 'lower' => array(7747)); /* LATIN CAPITAL LETTER M WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7748, 'status' => 'C', 'lower' => array(7749)); /* LATIN CAPITAL LETTER N WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7750, 'status' => 'C', 'lower' => array(7751)); /* LATIN CAPITAL LETTER N WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7752, 'status' => 'C', 'lower' => array(7753)); /* LATIN CAPITAL LETTER N WITH LINE BELOW */ $config['1e00_1eff'][] = array('upper' => 7754, 'status' => 'C', 'lower' => array(7755)); /* LATIN CAPITAL LETTER N WITH CIRCUMFLEX BELOW */ $config['1e00_1eff'][] = array('upper' => 7756, 'status' => 'C', 'lower' => array(7757)); /* LATIN CAPITAL LETTER O WITH TILDE AND ACUTE */ $config['1e00_1eff'][] = array('upper' => 7758, 'status' => 'C', 'lower' => array(7759)); /* LATIN CAPITAL LETTER O WITH TILDE AND DIAERESIS */ $config['1e00_1eff'][] = array('upper' => 7760, 'status' => 'C', 'lower' => array(7761)); /* LATIN CAPITAL LETTER O WITH MACRON AND GRAVE */ $config['1e00_1eff'][] = array('upper' => 7762, 'status' => 'C', 'lower' => array(7763)); /* LATIN CAPITAL LETTER O WITH MACRON AND ACUTE */ $config['1e00_1eff'][] = array('upper' => 7764, 'status' => 'C', 'lower' => array(7765)); /* LATIN CAPITAL LETTER P WITH ACUTE */ $config['1e00_1eff'][] = array('upper' => 7766, 'status' => 'C', 'lower' => array(7767)); /* LATIN CAPITAL LETTER P WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7768, 'status' => 'C', 'lower' => array(7769)); /* LATIN CAPITAL LETTER R WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7770, 'status' => 'C', 'lower' => array(7771)); /* LATIN CAPITAL LETTER R WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7772, 'status' => 'C', 'lower' => array(7773)); /* LATIN CAPITAL LETTER R WITH DOT BELOW AND MACRON */ $config['1e00_1eff'][] = array('upper' => 7774, 'status' => 'C', 'lower' => array(7775)); /* LATIN CAPITAL LETTER R WITH LINE BELOW */ $config['1e00_1eff'][] = array('upper' => 7776, 'status' => 'C', 'lower' => array(7777)); /* LATIN CAPITAL LETTER S WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7778, 'status' => 'C', 'lower' => array(7779)); /* LATIN CAPITAL LETTER S WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7780, 'status' => 'C', 'lower' => array(7781)); /* LATIN CAPITAL LETTER S WITH ACUTE AND DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7782, 'status' => 'C', 'lower' => array(7783)); /* LATIN CAPITAL LETTER S WITH CARON AND DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7784, 'status' => 'C', 'lower' => array(7785)); /* LATIN CAPITAL LETTER S WITH DOT BELOW AND DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7786, 'status' => 'C', 'lower' => array(7787)); /* LATIN CAPITAL LETTER T WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7788, 'status' => 'C', 'lower' => array(7789)); /* LATIN CAPITAL LETTER T WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7790, 'status' => 'C', 'lower' => array(7791)); /* LATIN CAPITAL LETTER T WITH LINE BELOW */ $config['1e00_1eff'][] = array('upper' => 7792, 'status' => 'C', 'lower' => array(7793)); /* LATIN CAPITAL LETTER T WITH CIRCUMFLEX BELOW */ $config['1e00_1eff'][] = array('upper' => 7794, 'status' => 'C', 'lower' => array(7795)); /* LATIN CAPITAL LETTER U WITH DIAERESIS BELOW */ $config['1e00_1eff'][] = array('upper' => 7796, 'status' => 'C', 'lower' => array(7797)); /* LATIN CAPITAL LETTER U WITH TILDE BELOW */ $config['1e00_1eff'][] = array('upper' => 7798, 'status' => 'C', 'lower' => array(7799)); /* LATIN CAPITAL LETTER U WITH CIRCUMFLEX BELOW */ $config['1e00_1eff'][] = array('upper' => 7800, 'status' => 'C', 'lower' => array(7801)); /* LATIN CAPITAL LETTER U WITH TILDE AND ACUTE */ $config['1e00_1eff'][] = array('upper' => 7802, 'status' => 'C', 'lower' => array(7803)); /* LATIN CAPITAL LETTER U WITH MACRON AND DIAERESIS */ $config['1e00_1eff'][] = array('upper' => 7804, 'status' => 'C', 'lower' => array(7805)); /* LATIN CAPITAL LETTER V WITH TILDE */ $config['1e00_1eff'][] = array('upper' => 7806, 'status' => 'C', 'lower' => array(7807)); /* LATIN CAPITAL LETTER V WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7808, 'status' => 'C', 'lower' => array(7809)); /* LATIN CAPITAL LETTER W WITH GRAVE */ $config['1e00_1eff'][] = array('upper' => 7810, 'status' => 'C', 'lower' => array(7811)); /* LATIN CAPITAL LETTER W WITH ACUTE */ $config['1e00_1eff'][] = array('upper' => 7812, 'status' => 'C', 'lower' => array(7813)); /* LATIN CAPITAL LETTER W WITH DIAERESIS */ $config['1e00_1eff'][] = array('upper' => 7814, 'status' => 'C', 'lower' => array(7815)); /* LATIN CAPITAL LETTER W WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7816, 'status' => 'C', 'lower' => array(7817)); /* LATIN CAPITAL LETTER W WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7818, 'status' => 'C', 'lower' => array(7819)); /* LATIN CAPITAL LETTER X WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7820, 'status' => 'C', 'lower' => array(7821)); /* LATIN CAPITAL LETTER X WITH DIAERESIS */ $config['1e00_1eff'][] = array('upper' => 7822, 'status' => 'C', 'lower' => array(7823)); /* LATIN CAPITAL LETTER Y WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7824, 'status' => 'C', 'lower' => array(7825)); /* LATIN CAPITAL LETTER Z WITH CIRCUMFLEX */ $config['1e00_1eff'][] = array('upper' => 7826, 'status' => 'C', 'lower' => array(7827)); /* LATIN CAPITAL LETTER Z WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7828, 'status' => 'C', 'lower' => array(7829)); /* LATIN CAPITAL LETTER Z WITH LINE BELOW */ //$config['1e00_1eff'][] = array('upper' => 7830, 'status' => 'F', 'lower' => array(104, 817)); /* LATIN SMALL LETTER H WITH LINE BELOW */ //$config['1e00_1eff'][] = array('upper' => 7831, 'status' => 'F', 'lower' => array(116, 776)); /* LATIN SMALL LETTER T WITH DIAERESIS */ //$config['1e00_1eff'][] = array('upper' => 7832, 'status' => 'F', 'lower' => array(119, 778)); /* LATIN SMALL LETTER W WITH RING ABOVE */ //$config['1e00_1eff'][] = array('upper' => 7833, 'status' => 'F', 'lower' => array(121, 778)); /* LATIN SMALL LETTER Y WITH RING ABOVE */ //$config['1e00_1eff'][] = array('upper' => 7834, 'status' => 'F', 'lower' => array(97, 702)); /* LATIN SMALL LETTER A WITH RIGHT HALF RING */ //$config['1e00_1eff'][] = array('upper' => 7835, 'status' => 'C', 'lower' => array(7777)); /* LATIN SMALL LETTER LONG S WITH DOT ABOVE */ $config['1e00_1eff'][] = array('upper' => 7840, 'status' => 'C', 'lower' => array(7841)); /* LATIN CAPITAL LETTER A WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7842, 'status' => 'C', 'lower' => array(7843)); /* LATIN CAPITAL LETTER A WITH HOOK ABOVE */ $config['1e00_1eff'][] = array('upper' => 7844, 'status' => 'C', 'lower' => array(7845)); /* LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE */ $config['1e00_1eff'][] = array('upper' => 7846, 'status' => 'C', 'lower' => array(7847)); /* LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE */ $config['1e00_1eff'][] = array('upper' => 7848, 'status' => 'C', 'lower' => array(7849)); /* LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE */ $config['1e00_1eff'][] = array('upper' => 7850, 'status' => 'C', 'lower' => array(7851)); /* LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE */ $config['1e00_1eff'][] = array('upper' => 7852, 'status' => 'C', 'lower' => array(7853)); /* LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7854, 'status' => 'C', 'lower' => array(7855)); /* LATIN CAPITAL LETTER A WITH BREVE AND ACUTE */ $config['1e00_1eff'][] = array('upper' => 7856, 'status' => 'C', 'lower' => array(7857)); /* LATIN CAPITAL LETTER A WITH BREVE AND GRAVE */ $config['1e00_1eff'][] = array('upper' => 7858, 'status' => 'C', 'lower' => array(7859)); /* LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE */ $config['1e00_1eff'][] = array('upper' => 7860, 'status' => 'C', 'lower' => array(7861)); /* LATIN CAPITAL LETTER A WITH BREVE AND TILDE */ $config['1e00_1eff'][] = array('upper' => 7862, 'status' => 'C', 'lower' => array(7863)); /* LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7864, 'status' => 'C', 'lower' => array(7865)); /* LATIN CAPITAL LETTER E WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7866, 'status' => 'C', 'lower' => array(7867)); /* LATIN CAPITAL LETTER E WITH HOOK ABOVE */ $config['1e00_1eff'][] = array('upper' => 7868, 'status' => 'C', 'lower' => array(7869)); /* LATIN CAPITAL LETTER E WITH TILDE */ $config['1e00_1eff'][] = array('upper' => 7870, 'status' => 'C', 'lower' => array(7871)); /* LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND ACUTE */ $config['1e00_1eff'][] = array('upper' => 7872, 'status' => 'C', 'lower' => array(7873)); /* LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND GRAVE */ $config['1e00_1eff'][] = array('upper' => 7874, 'status' => 'C', 'lower' => array(7875)); /* LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE */ $config['1e00_1eff'][] = array('upper' => 7876, 'status' => 'C', 'lower' => array(7877)); /* LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND TILDE */ $config['1e00_1eff'][] = array('upper' => 7878, 'status' => 'C', 'lower' => array(7879)); /* LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7880, 'status' => 'C', 'lower' => array(7881)); /* LATIN CAPITAL LETTER I WITH HOOK ABOVE */ $config['1e00_1eff'][] = array('upper' => 7882, 'status' => 'C', 'lower' => array(7883)); /* LATIN CAPITAL LETTER I WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7884, 'status' => 'C', 'lower' => array(7885)); /* LATIN CAPITAL LETTER O WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7886, 'status' => 'C', 'lower' => array(7887)); /* LATIN CAPITAL LETTER O WITH HOOK ABOVE */ $config['1e00_1eff'][] = array('upper' => 7888, 'status' => 'C', 'lower' => array(7889)); /* LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND ACUTE */ $config['1e00_1eff'][] = array('upper' => 7890, 'status' => 'C', 'lower' => array(7891)); /* LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND GRAVE */ $config['1e00_1eff'][] = array('upper' => 7892, 'status' => 'C', 'lower' => array(7893)); /* LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE */ $config['1e00_1eff'][] = array('upper' => 7894, 'status' => 'C', 'lower' => array(7895)); /* LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND TILDE */ $config['1e00_1eff'][] = array('upper' => 7896, 'status' => 'C', 'lower' => array(7897)); /* LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7898, 'status' => 'C', 'lower' => array(7899)); /* LATIN CAPITAL LETTER O WITH HORN AND ACUTE */ $config['1e00_1eff'][] = array('upper' => 7900, 'status' => 'C', 'lower' => array(7901)); /* LATIN CAPITAL LETTER O WITH HORN AND GRAVE */ $config['1e00_1eff'][] = array('upper' => 7902, 'status' => 'C', 'lower' => array(7903)); /* LATIN CAPITAL LETTER O WITH HORN AND HOOK ABOVE */ $config['1e00_1eff'][] = array('upper' => 7904, 'status' => 'C', 'lower' => array(7905)); /* LATIN CAPITAL LETTER O WITH HORN AND TILDE */ $config['1e00_1eff'][] = array('upper' => 7906, 'status' => 'C', 'lower' => array(7907)); /* LATIN CAPITAL LETTER O WITH HORN AND DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7908, 'status' => 'C', 'lower' => array(7909)); /* LATIN CAPITAL LETTER U WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7910, 'status' => 'C', 'lower' => array(7911)); /* LATIN CAPITAL LETTER U WITH HOOK ABOVE */ $config['1e00_1eff'][] = array('upper' => 7912, 'status' => 'C', 'lower' => array(7913)); /* LATIN CAPITAL LETTER U WITH HORN AND ACUTE */ $config['1e00_1eff'][] = array('upper' => 7914, 'status' => 'C', 'lower' => array(7915)); /* LATIN CAPITAL LETTER U WITH HORN AND GRAVE */ $config['1e00_1eff'][] = array('upper' => 7916, 'status' => 'C', 'lower' => array(7917)); /* LATIN CAPITAL LETTER U WITH HORN AND HOOK ABOVE */ $config['1e00_1eff'][] = array('upper' => 7918, 'status' => 'C', 'lower' => array(7919)); /* LATIN CAPITAL LETTER U WITH HORN AND TILDE */ $config['1e00_1eff'][] = array('upper' => 7920, 'status' => 'C', 'lower' => array(7921)); /* LATIN CAPITAL LETTER U WITH HORN AND DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7922, 'status' => 'C', 'lower' => array(7923)); /* LATIN CAPITAL LETTER Y WITH GRAVE */ $config['1e00_1eff'][] = array('upper' => 7924, 'status' => 'C', 'lower' => array(7925)); /* LATIN CAPITAL LETTER Y WITH DOT BELOW */ $config['1e00_1eff'][] = array('upper' => 7926, 'status' => 'C', 'lower' => array(7927)); /* LATIN CAPITAL LETTER Y WITH HOOK ABOVE */ $config['1e00_1eff'][] = array('upper' => 7928, 'status' => 'C', 'lower' => array(7929)); /* LATIN CAPITAL LETTER Y WITH TILDE */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/1e00_1eff.php
PHP
gpl3
19,226
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+0100 through U+017F * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['0100_017f'][] = array('upper' => 256, 'status' => 'C', 'lower' => array(257)); /* LATIN CAPITAL LETTER A WITH MACRON */ $config['0100_017f'][] = array('upper' => 258, 'status' => 'C', 'lower' => array(259)); /* LATIN CAPITAL LETTER A WITH BREVE */ $config['0100_017f'][] = array('upper' => 260, 'status' => 'C', 'lower' => array(261)); /* LATIN CAPITAL LETTER A WITH OGONEK */ $config['0100_017f'][] = array('upper' => 262, 'status' => 'C', 'lower' => array(263)); /* LATIN CAPITAL LETTER C WITH ACUTE */ $config['0100_017f'][] = array('upper' => 264, 'status' => 'C', 'lower' => array(265)); /* LATIN CAPITAL LETTER C WITH CIRCUMFLEX */ $config['0100_017f'][] = array('upper' => 266, 'status' => 'C', 'lower' => array(267)); /* LATIN CAPITAL LETTER C WITH DOT ABOVE */ $config['0100_017f'][] = array('upper' => 268, 'status' => 'C', 'lower' => array(269)); /* LATIN CAPITAL LETTER C WITH CARON */ $config['0100_017f'][] = array('upper' => 270, 'status' => 'C', 'lower' => array(271)); /* LATIN CAPITAL LETTER D WITH CARON */ $config['0100_017f'][] = array('upper' => 272, 'status' => 'C', 'lower' => array(273)); /* LATIN CAPITAL LETTER D WITH STROKE */ $config['0100_017f'][] = array('upper' => 274, 'status' => 'C', 'lower' => array(275)); /* LATIN CAPITAL LETTER E WITH MACRON */ $config['0100_017f'][] = array('upper' => 276, 'status' => 'C', 'lower' => array(277)); /* LATIN CAPITAL LETTER E WITH BREVE */ $config['0100_017f'][] = array('upper' => 278, 'status' => 'C', 'lower' => array(279)); /* LATIN CAPITAL LETTER E WITH DOT ABOVE */ $config['0100_017f'][] = array('upper' => 280, 'status' => 'C', 'lower' => array(281)); /* LATIN CAPITAL LETTER E WITH OGONEK */ $config['0100_017f'][] = array('upper' => 282, 'status' => 'C', 'lower' => array(283)); /* LATIN CAPITAL LETTER E WITH CARON */ $config['0100_017f'][] = array('upper' => 284, 'status' => 'C', 'lower' => array(285)); /* LATIN CAPITAL LETTER G WITH CIRCUMFLEX */ $config['0100_017f'][] = array('upper' => 286, 'status' => 'C', 'lower' => array(287)); /* LATIN CAPITAL LETTER G WITH BREVE */ $config['0100_017f'][] = array('upper' => 288, 'status' => 'C', 'lower' => array(289)); /* LATIN CAPITAL LETTER G WITH DOT ABOVE */ $config['0100_017f'][] = array('upper' => 290, 'status' => 'C', 'lower' => array(291)); /* LATIN CAPITAL LETTER G WITH CEDILLA */ $config['0100_017f'][] = array('upper' => 292, 'status' => 'C', 'lower' => array(293)); /* LATIN CAPITAL LETTER H WITH CIRCUMFLEX */ $config['0100_017f'][] = array('upper' => 294, 'status' => 'C', 'lower' => array(295)); /* LATIN CAPITAL LETTER H WITH STROKE */ $config['0100_017f'][] = array('upper' => 296, 'status' => 'C', 'lower' => array(297)); /* LATIN CAPITAL LETTER I WITH TILDE */ $config['0100_017f'][] = array('upper' => 298, 'status' => 'C', 'lower' => array(299)); /* LATIN CAPITAL LETTER I WITH MACRON */ $config['0100_017f'][] = array('upper' => 300, 'status' => 'C', 'lower' => array(301)); /* LATIN CAPITAL LETTER I WITH BREVE */ $config['0100_017f'][] = array('upper' => 302, 'status' => 'C', 'lower' => array(303)); /* LATIN CAPITAL LETTER I WITH OGONEK */ $config['0100_017f'][] = array('upper' => 304, 'status' => 'F', 'lower' => array(105, 775)); /* LATIN CAPITAL LETTER I WITH DOT ABOVE */ $config['0100_017f'][] = array('upper' => 304, 'status' => 'T', 'lower' => array(105)); /* LATIN CAPITAL LETTER I WITH DOT ABOVE */ $config['0100_017f'][] = array('upper' => 306, 'status' => 'C', 'lower' => array(307)); /* LATIN CAPITAL LIGATURE IJ */ $config['0100_017f'][] = array('upper' => 308, 'status' => 'C', 'lower' => array(309)); /* LATIN CAPITAL LETTER J WITH CIRCUMFLEX */ $config['0100_017f'][] = array('upper' => 310, 'status' => 'C', 'lower' => array(311)); /* LATIN CAPITAL LETTER K WITH CEDILLA */ $config['0100_017f'][] = array('upper' => 313, 'status' => 'C', 'lower' => array(314)); /* LATIN CAPITAL LETTER L WITH ACUTE */ $config['0100_017f'][] = array('upper' => 315, 'status' => 'C', 'lower' => array(316)); /* LATIN CAPITAL LETTER L WITH CEDILLA */ $config['0100_017f'][] = array('upper' => 317, 'status' => 'C', 'lower' => array(318)); /* LATIN CAPITAL LETTER L WITH CARON */ $config['0100_017f'][] = array('upper' => 319, 'status' => 'C', 'lower' => array(320)); /* LATIN CAPITAL LETTER L WITH MIDDLE DOT */ $config['0100_017f'][] = array('upper' => 321, 'status' => 'C', 'lower' => array(322)); /* LATIN CAPITAL LETTER L WITH STROKE */ $config['0100_017f'][] = array('upper' => 323, 'status' => 'C', 'lower' => array(324)); /* LATIN CAPITAL LETTER N WITH ACUTE */ $config['0100_017f'][] = array('upper' => 325, 'status' => 'C', 'lower' => array(326)); /* LATIN CAPITAL LETTER N WITH CEDILLA */ $config['0100_017f'][] = array('upper' => 327, 'status' => 'C', 'lower' => array(328)); /* LATIN CAPITAL LETTER N WITH CARON */ $config['0100_017f'][] = array('upper' => 329, 'status' => 'F', 'lower' => array(700, 110)); /* LATIN SMALL LETTER N PRECEDED BY APOSTROPHE */ $config['0100_017f'][] = array('upper' => 330, 'status' => 'C', 'lower' => array(331)); /* LATIN CAPITAL LETTER ENG */ $config['0100_017f'][] = array('upper' => 332, 'status' => 'C', 'lower' => array(333)); /* LATIN CAPITAL LETTER O WITH MACRON */ $config['0100_017f'][] = array('upper' => 334, 'status' => 'C', 'lower' => array(335)); /* LATIN CAPITAL LETTER O WITH BREVE */ $config['0100_017f'][] = array('upper' => 336, 'status' => 'C', 'lower' => array(337)); /* LATIN CAPITAL LETTER O WITH DOUBLE ACUTE */ $config['0100_017f'][] = array('upper' => 338, 'status' => 'C', 'lower' => array(339)); /* LATIN CAPITAL LIGATURE OE */ $config['0100_017f'][] = array('upper' => 340, 'status' => 'C', 'lower' => array(341)); /* LATIN CAPITAL LETTER R WITH ACUTE */ $config['0100_017f'][] = array('upper' => 342, 'status' => 'C', 'lower' => array(343)); /* LATIN CAPITAL LETTER R WITH CEDILLA */ $config['0100_017f'][] = array('upper' => 344, 'status' => 'C', 'lower' => array(345)); /* LATIN CAPITAL LETTER R WITH CARON */ $config['0100_017f'][] = array('upper' => 346, 'status' => 'C', 'lower' => array(347)); /* LATIN CAPITAL LETTER S WITH ACUTE */ $config['0100_017f'][] = array('upper' => 348, 'status' => 'C', 'lower' => array(349)); /* LATIN CAPITAL LETTER S WITH CIRCUMFLEX */ $config['0100_017f'][] = array('upper' => 350, 'status' => 'C', 'lower' => array(351)); /* LATIN CAPITAL LETTER S WITH CEDILLA */ $config['0100_017f'][] = array('upper' => 352, 'status' => 'C', 'lower' => array(353)); /* LATIN CAPITAL LETTER S WITH CARON */ $config['0100_017f'][] = array('upper' => 354, 'status' => 'C', 'lower' => array(355)); /* LATIN CAPITAL LETTER T WITH CEDILLA */ $config['0100_017f'][] = array('upper' => 356, 'status' => 'C', 'lower' => array(357)); /* LATIN CAPITAL LETTER T WITH CARON */ $config['0100_017f'][] = array('upper' => 358, 'status' => 'C', 'lower' => array(359)); /* LATIN CAPITAL LETTER T WITH STROKE */ $config['0100_017f'][] = array('upper' => 360, 'status' => 'C', 'lower' => array(361)); /* LATIN CAPITAL LETTER U WITH TILDE */ $config['0100_017f'][] = array('upper' => 362, 'status' => 'C', 'lower' => array(363)); /* LATIN CAPITAL LETTER U WITH MACRON */ $config['0100_017f'][] = array('upper' => 364, 'status' => 'C', 'lower' => array(365)); /* LATIN CAPITAL LETTER U WITH BREVE */ $config['0100_017f'][] = array('upper' => 366, 'status' => 'C', 'lower' => array(367)); /* LATIN CAPITAL LETTER U WITH RING ABOVE */ $config['0100_017f'][] = array('upper' => 368, 'status' => 'C', 'lower' => array(369)); /* LATIN CAPITAL LETTER U WITH DOUBLE ACUTE */ $config['0100_017f'][] = array('upper' => 370, 'status' => 'C', 'lower' => array(371)); /* LATIN CAPITAL LETTER U WITH OGONEK */ $config['0100_017f'][] = array('upper' => 372, 'status' => 'C', 'lower' => array(373)); /* LATIN CAPITAL LETTER W WITH CIRCUMFLEX */ $config['0100_017f'][] = array('upper' => 374, 'status' => 'C', 'lower' => array(375)); /* LATIN CAPITAL LETTER Y WITH CIRCUMFLEX */ $config['0100_017f'][] = array('upper' => 376, 'status' => 'C', 'lower' => array(255)); /* LATIN CAPITAL LETTER Y WITH DIAERESIS */ $config['0100_017f'][] = array('upper' => 377, 'status' => 'C', 'lower' => array(378)); /* LATIN CAPITAL LETTER Z WITH ACUTE */ $config['0100_017f'][] = array('upper' => 379, 'status' => 'C', 'lower' => array(380)); /* LATIN CAPITAL LETTER Z WITH DOT ABOVE */ $config['0100_017f'][] = array('upper' => 381, 'status' => 'C', 'lower' => array(382)); /* LATIN CAPITAL LETTER Z WITH CARON */ $config['0100_017f'][] = array('upper' => 383, 'status' => 'C', 'lower' => array(115)); /* LATIN SMALL LETTER LONG S */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/0100_017f.php
PHP
gpl3
10,385
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+2460 through U+24FF * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['2460_24ff'][] = array('upper' => 9398, 'status' => 'C', 'lower' => array(9424)); /* CIRCLED LATIN CAPITAL LETTER A */ $config['2460_24ff'][] = array('upper' => 9399, 'status' => 'C', 'lower' => array(9425)); /* CIRCLED LATIN CAPITAL LETTER B */ $config['2460_24ff'][] = array('upper' => 9400, 'status' => 'C', 'lower' => array(9426)); /* CIRCLED LATIN CAPITAL LETTER C */ $config['2460_24ff'][] = array('upper' => 9401, 'status' => 'C', 'lower' => array(9427)); /* CIRCLED LATIN CAPITAL LETTER D */ $config['2460_24ff'][] = array('upper' => 9402, 'status' => 'C', 'lower' => array(9428)); /* CIRCLED LATIN CAPITAL LETTER E */ $config['2460_24ff'][] = array('upper' => 9403, 'status' => 'C', 'lower' => array(9429)); /* CIRCLED LATIN CAPITAL LETTER F */ $config['2460_24ff'][] = array('upper' => 9404, 'status' => 'C', 'lower' => array(9430)); /* CIRCLED LATIN CAPITAL LETTER G */ $config['2460_24ff'][] = array('upper' => 9405, 'status' => 'C', 'lower' => array(9431)); /* CIRCLED LATIN CAPITAL LETTER H */ $config['2460_24ff'][] = array('upper' => 9406, 'status' => 'C', 'lower' => array(9432)); /* CIRCLED LATIN CAPITAL LETTER I */ $config['2460_24ff'][] = array('upper' => 9407, 'status' => 'C', 'lower' => array(9433)); /* CIRCLED LATIN CAPITAL LETTER J */ $config['2460_24ff'][] = array('upper' => 9408, 'status' => 'C', 'lower' => array(9434)); /* CIRCLED LATIN CAPITAL LETTER K */ $config['2460_24ff'][] = array('upper' => 9409, 'status' => 'C', 'lower' => array(9435)); /* CIRCLED LATIN CAPITAL LETTER L */ $config['2460_24ff'][] = array('upper' => 9410, 'status' => 'C', 'lower' => array(9436)); /* CIRCLED LATIN CAPITAL LETTER M */ $config['2460_24ff'][] = array('upper' => 9411, 'status' => 'C', 'lower' => array(9437)); /* CIRCLED LATIN CAPITAL LETTER N */ $config['2460_24ff'][] = array('upper' => 9412, 'status' => 'C', 'lower' => array(9438)); /* CIRCLED LATIN CAPITAL LETTER O */ $config['2460_24ff'][] = array('upper' => 9413, 'status' => 'C', 'lower' => array(9439)); /* CIRCLED LATIN CAPITAL LETTER P */ $config['2460_24ff'][] = array('upper' => 9414, 'status' => 'C', 'lower' => array(9440)); /* CIRCLED LATIN CAPITAL LETTER Q */ $config['2460_24ff'][] = array('upper' => 9415, 'status' => 'C', 'lower' => array(9441)); /* CIRCLED LATIN CAPITAL LETTER R */ $config['2460_24ff'][] = array('upper' => 9416, 'status' => 'C', 'lower' => array(9442)); /* CIRCLED LATIN CAPITAL LETTER S */ $config['2460_24ff'][] = array('upper' => 9417, 'status' => 'C', 'lower' => array(9443)); /* CIRCLED LATIN CAPITAL LETTER T */ $config['2460_24ff'][] = array('upper' => 9418, 'status' => 'C', 'lower' => array(9444)); /* CIRCLED LATIN CAPITAL LETTER U */ $config['2460_24ff'][] = array('upper' => 9419, 'status' => 'C', 'lower' => array(9445)); /* CIRCLED LATIN CAPITAL LETTER V */ $config['2460_24ff'][] = array('upper' => 9420, 'status' => 'C', 'lower' => array(9446)); /* CIRCLED LATIN CAPITAL LETTER W */ $config['2460_24ff'][] = array('upper' => 9421, 'status' => 'C', 'lower' => array(9447)); /* CIRCLED LATIN CAPITAL LETTER X */ $config['2460_24ff'][] = array('upper' => 9422, 'status' => 'C', 'lower' => array(9448)); /* CIRCLED LATIN CAPITAL LETTER Y */ $config['2460_24ff'][] = array('upper' => 9423, 'status' => 'C', 'lower' => array(9449)); /* CIRCLED LATIN CAPITAL LETTER Z */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/2460_24ff.php
PHP
gpl3
5,138
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+0400 through U+04FF * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['0400_04ff'][] = array('upper' => 1024, 'status' => 'C', 'lower' => array(1104)); /* CYRILLIC CAPITAL LETTER IE WITH GRAVE */ $config['0400_04ff'][] = array('upper' => 1025, 'status' => 'C', 'lower' => array(1105)); /* CYRILLIC CAPITAL LETTER IO */ $config['0400_04ff'][] = array('upper' => 1026, 'status' => 'C', 'lower' => array(1106)); /* CYRILLIC CAPITAL LETTER DJE */ $config['0400_04ff'][] = array('upper' => 1027, 'status' => 'C', 'lower' => array(1107)); /* CYRILLIC CAPITAL LETTER GJE */ $config['0400_04ff'][] = array('upper' => 1028, 'status' => 'C', 'lower' => array(1108)); /* CYRILLIC CAPITAL LETTER UKRAINIAN IE */ $config['0400_04ff'][] = array('upper' => 1029, 'status' => 'C', 'lower' => array(1109)); /* CYRILLIC CAPITAL LETTER DZE */ $config['0400_04ff'][] = array('upper' => 1030, 'status' => 'C', 'lower' => array(1110)); /* CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I */ $config['0400_04ff'][] = array('upper' => 1031, 'status' => 'C', 'lower' => array(1111)); /* CYRILLIC CAPITAL LETTER YI */ $config['0400_04ff'][] = array('upper' => 1032, 'status' => 'C', 'lower' => array(1112)); /* CYRILLIC CAPITAL LETTER JE */ $config['0400_04ff'][] = array('upper' => 1033, 'status' => 'C', 'lower' => array(1113)); /* CYRILLIC CAPITAL LETTER LJE */ $config['0400_04ff'][] = array('upper' => 1034, 'status' => 'C', 'lower' => array(1114)); /* CYRILLIC CAPITAL LETTER NJE */ $config['0400_04ff'][] = array('upper' => 1035, 'status' => 'C', 'lower' => array(1115)); /* CYRILLIC CAPITAL LETTER TSHE */ $config['0400_04ff'][] = array('upper' => 1036, 'status' => 'C', 'lower' => array(1116)); /* CYRILLIC CAPITAL LETTER KJE */ $config['0400_04ff'][] = array('upper' => 1037, 'status' => 'C', 'lower' => array(1117)); /* CYRILLIC CAPITAL LETTER I WITH GRAVE */ $config['0400_04ff'][] = array('upper' => 1038, 'status' => 'C', 'lower' => array(1118)); /* CYRILLIC CAPITAL LETTER SHORT U */ $config['0400_04ff'][] = array('upper' => 1039, 'status' => 'C', 'lower' => array(1119)); /* CYRILLIC CAPITAL LETTER DZHE */ $config['0400_04ff'][] = array('upper' => 1040, 'status' => 'C', 'lower' => array(1072)); /* CYRILLIC CAPITAL LETTER A */ $config['0400_04ff'][] = array('upper' => 1041, 'status' => 'C', 'lower' => array(1073)); /* CYRILLIC CAPITAL LETTER BE */ $config['0400_04ff'][] = array('upper' => 1042, 'status' => 'C', 'lower' => array(1074)); /* CYRILLIC CAPITAL LETTER VE */ $config['0400_04ff'][] = array('upper' => 1043, 'status' => 'C', 'lower' => array(1075)); /* CYRILLIC CAPITAL LETTER GHE */ $config['0400_04ff'][] = array('upper' => 1044, 'status' => 'C', 'lower' => array(1076)); /* CYRILLIC CAPITAL LETTER DE */ $config['0400_04ff'][] = array('upper' => 1045, 'status' => 'C', 'lower' => array(1077)); /* CYRILLIC CAPITAL LETTER IE */ $config['0400_04ff'][] = array('upper' => 1046, 'status' => 'C', 'lower' => array(1078)); /* CYRILLIC CAPITAL LETTER ZHE */ $config['0400_04ff'][] = array('upper' => 1047, 'status' => 'C', 'lower' => array(1079)); /* CYRILLIC CAPITAL LETTER ZE */ $config['0400_04ff'][] = array('upper' => 1048, 'status' => 'C', 'lower' => array(1080)); /* CYRILLIC CAPITAL LETTER I */ $config['0400_04ff'][] = array('upper' => 1049, 'status' => 'C', 'lower' => array(1081)); /* CYRILLIC CAPITAL LETTER SHORT I */ $config['0400_04ff'][] = array('upper' => 1050, 'status' => 'C', 'lower' => array(1082)); /* CYRILLIC CAPITAL LETTER KA */ $config['0400_04ff'][] = array('upper' => 1051, 'status' => 'C', 'lower' => array(1083)); /* CYRILLIC CAPITAL LETTER EL */ $config['0400_04ff'][] = array('upper' => 1052, 'status' => 'C', 'lower' => array(1084)); /* CYRILLIC CAPITAL LETTER EM */ $config['0400_04ff'][] = array('upper' => 1053, 'status' => 'C', 'lower' => array(1085)); /* CYRILLIC CAPITAL LETTER EN */ $config['0400_04ff'][] = array('upper' => 1054, 'status' => 'C', 'lower' => array(1086)); /* CYRILLIC CAPITAL LETTER O */ $config['0400_04ff'][] = array('upper' => 1055, 'status' => 'C', 'lower' => array(1087)); /* CYRILLIC CAPITAL LETTER PE */ $config['0400_04ff'][] = array('upper' => 1056, 'status' => 'C', 'lower' => array(1088)); /* CYRILLIC CAPITAL LETTER ER */ $config['0400_04ff'][] = array('upper' => 1057, 'status' => 'C', 'lower' => array(1089)); /* CYRILLIC CAPITAL LETTER ES */ $config['0400_04ff'][] = array('upper' => 1058, 'status' => 'C', 'lower' => array(1090)); /* CYRILLIC CAPITAL LETTER TE */ $config['0400_04ff'][] = array('upper' => 1059, 'status' => 'C', 'lower' => array(1091)); /* CYRILLIC CAPITAL LETTER U */ $config['0400_04ff'][] = array('upper' => 1060, 'status' => 'C', 'lower' => array(1092)); /* CYRILLIC CAPITAL LETTER EF */ $config['0400_04ff'][] = array('upper' => 1061, 'status' => 'C', 'lower' => array(1093)); /* CYRILLIC CAPITAL LETTER HA */ $config['0400_04ff'][] = array('upper' => 1062, 'status' => 'C', 'lower' => array(1094)); /* CYRILLIC CAPITAL LETTER TSE */ $config['0400_04ff'][] = array('upper' => 1063, 'status' => 'C', 'lower' => array(1095)); /* CYRILLIC CAPITAL LETTER CHE */ $config['0400_04ff'][] = array('upper' => 1064, 'status' => 'C', 'lower' => array(1096)); /* CYRILLIC CAPITAL LETTER SHA */ $config['0400_04ff'][] = array('upper' => 1065, 'status' => 'C', 'lower' => array(1097)); /* CYRILLIC CAPITAL LETTER SHCHA */ $config['0400_04ff'][] = array('upper' => 1066, 'status' => 'C', 'lower' => array(1098)); /* CYRILLIC CAPITAL LETTER HARD SIGN */ $config['0400_04ff'][] = array('upper' => 1067, 'status' => 'C', 'lower' => array(1099)); /* CYRILLIC CAPITAL LETTER YERU */ $config['0400_04ff'][] = array('upper' => 1068, 'status' => 'C', 'lower' => array(1100)); /* CYRILLIC CAPITAL LETTER SOFT SIGN */ $config['0400_04ff'][] = array('upper' => 1069, 'status' => 'C', 'lower' => array(1101)); /* CYRILLIC CAPITAL LETTER E */ $config['0400_04ff'][] = array('upper' => 1070, 'status' => 'C', 'lower' => array(1102)); /* CYRILLIC CAPITAL LETTER YU */ $config['0400_04ff'][] = array('upper' => 1071, 'status' => 'C', 'lower' => array(1103)); /* CYRILLIC CAPITAL LETTER YA */ $config['0400_04ff'][] = array('upper' => 1120, 'status' => 'C', 'lower' => array(1121)); /* CYRILLIC CAPITAL LETTER OMEGA */ $config['0400_04ff'][] = array('upper' => 1122, 'status' => 'C', 'lower' => array(1123)); /* CYRILLIC CAPITAL LETTER YAT */ $config['0400_04ff'][] = array('upper' => 1124, 'status' => 'C', 'lower' => array(1125)); /* CYRILLIC CAPITAL LETTER IOTIFIED E */ $config['0400_04ff'][] = array('upper' => 1126, 'status' => 'C', 'lower' => array(1127)); /* CYRILLIC CAPITAL LETTER LITTLE YUS */ $config['0400_04ff'][] = array('upper' => 1128, 'status' => 'C', 'lower' => array(1129)); /* CYRILLIC CAPITAL LETTER IOTIFIED LITTLE YUS */ $config['0400_04ff'][] = array('upper' => 1130, 'status' => 'C', 'lower' => array(1131)); /* CYRILLIC CAPITAL LETTER BIG YUS */ $config['0400_04ff'][] = array('upper' => 1132, 'status' => 'C', 'lower' => array(1133)); /* CYRILLIC CAPITAL LETTER IOTIFIED BIG YUS */ $config['0400_04ff'][] = array('upper' => 1134, 'status' => 'C', 'lower' => array(1135)); /* CYRILLIC CAPITAL LETTER KSI */ $config['0400_04ff'][] = array('upper' => 1136, 'status' => 'C', 'lower' => array(1137)); /* CYRILLIC CAPITAL LETTER PSI */ $config['0400_04ff'][] = array('upper' => 1138, 'status' => 'C', 'lower' => array(1139)); /* CYRILLIC CAPITAL LETTER FITA */ $config['0400_04ff'][] = array('upper' => 1140, 'status' => 'C', 'lower' => array(1141)); /* CYRILLIC CAPITAL LETTER IZHITSA */ $config['0400_04ff'][] = array('upper' => 1142, 'status' => 'C', 'lower' => array(1143)); /* CYRILLIC CAPITAL LETTER IZHITSA WITH DOUBLE GRAVE ACCENT */ $config['0400_04ff'][] = array('upper' => 1144, 'status' => 'C', 'lower' => array(1145)); /* CYRILLIC CAPITAL LETTER UK */ $config['0400_04ff'][] = array('upper' => 1146, 'status' => 'C', 'lower' => array(1147)); /* CYRILLIC CAPITAL LETTER ROUND OMEGA */ $config['0400_04ff'][] = array('upper' => 1148, 'status' => 'C', 'lower' => array(1149)); /* CYRILLIC CAPITAL LETTER OMEGA WITH TITLO */ $config['0400_04ff'][] = array('upper' => 1150, 'status' => 'C', 'lower' => array(1151)); /* CYRILLIC CAPITAL LETTER OT */ $config['0400_04ff'][] = array('upper' => 1152, 'status' => 'C', 'lower' => array(1153)); /* CYRILLIC CAPITAL LETTER KOPPA */ $config['0400_04ff'][] = array('upper' => 1162, 'status' => 'C', 'lower' => array(1163)); /* CYRILLIC CAPITAL LETTER SHORT I WITH TAIL */ $config['0400_04ff'][] = array('upper' => 1164, 'status' => 'C', 'lower' => array(1165)); /* CYRILLIC CAPITAL LETTER SEMISOFT SIGN */ $config['0400_04ff'][] = array('upper' => 1166, 'status' => 'C', 'lower' => array(1167)); /* CYRILLIC CAPITAL LETTER ER WITH TICK */ $config['0400_04ff'][] = array('upper' => 1168, 'status' => 'C', 'lower' => array(1169)); /* CYRILLIC CAPITAL LETTER GHE WITH UPTURN */ $config['0400_04ff'][] = array('upper' => 1170, 'status' => 'C', 'lower' => array(1171)); /* CYRILLIC CAPITAL LETTER GHE WITH STROKE */ $config['0400_04ff'][] = array('upper' => 1172, 'status' => 'C', 'lower' => array(1173)); /* CYRILLIC CAPITAL LETTER GHE WITH MIDDLE HOOK */ $config['0400_04ff'][] = array('upper' => 1174, 'status' => 'C', 'lower' => array(1175)); /* CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER */ $config['0400_04ff'][] = array('upper' => 1176, 'status' => 'C', 'lower' => array(1177)); /* CYRILLIC CAPITAL LETTER ZE WITH DESCENDER */ $config['0400_04ff'][] = array('upper' => 1178, 'status' => 'C', 'lower' => array(1179)); /* CYRILLIC CAPITAL LETTER KA WITH DESCENDER */ $config['0400_04ff'][] = array('upper' => 1180, 'status' => 'C', 'lower' => array(1181)); /* CYRILLIC CAPITAL LETTER KA WITH VERTICAL STROKE */ $config['0400_04ff'][] = array('upper' => 1182, 'status' => 'C', 'lower' => array(1183)); /* CYRILLIC CAPITAL LETTER KA WITH STROKE */ $config['0400_04ff'][] = array('upper' => 1184, 'status' => 'C', 'lower' => array(1185)); /* CYRILLIC CAPITAL LETTER BASHKIR KA */ $config['0400_04ff'][] = array('upper' => 1186, 'status' => 'C', 'lower' => array(1187)); /* CYRILLIC CAPITAL LETTER EN WITH DESCENDER */ $config['0400_04ff'][] = array('upper' => 1188, 'status' => 'C', 'lower' => array(1189)); /* CYRILLIC CAPITAL LIGATURE EN GHE */ $config['0400_04ff'][] = array('upper' => 1190, 'status' => 'C', 'lower' => array(1191)); /* CYRILLIC CAPITAL LETTER PE WITH MIDDLE HOOK */ $config['0400_04ff'][] = array('upper' => 1192, 'status' => 'C', 'lower' => array(1193)); /* CYRILLIC CAPITAL LETTER ABKHASIAN HA */ $config['0400_04ff'][] = array('upper' => 1194, 'status' => 'C', 'lower' => array(1195)); /* CYRILLIC CAPITAL LETTER ES WITH DESCENDER */ $config['0400_04ff'][] = array('upper' => 1196, 'status' => 'C', 'lower' => array(1197)); /* CYRILLIC CAPITAL LETTER TE WITH DESCENDER */ $config['0400_04ff'][] = array('upper' => 1198, 'status' => 'C', 'lower' => array(1199)); /* CYRILLIC CAPITAL LETTER STRAIGHT U */ $config['0400_04ff'][] = array('upper' => 1200, 'status' => 'C', 'lower' => array(1201)); /* CYRILLIC CAPITAL LETTER STRAIGHT U WITH STROKE */ $config['0400_04ff'][] = array('upper' => 1202, 'status' => 'C', 'lower' => array(1203)); /* CYRILLIC CAPITAL LETTER HA WITH DESCENDER */ $config['0400_04ff'][] = array('upper' => 1204, 'status' => 'C', 'lower' => array(1205)); /* CYRILLIC CAPITAL LIGATURE TE TSE */ $config['0400_04ff'][] = array('upper' => 1206, 'status' => 'C', 'lower' => array(1207)); /* CYRILLIC CAPITAL LETTER CHE WITH DESCENDER */ $config['0400_04ff'][] = array('upper' => 1208, 'status' => 'C', 'lower' => array(1209)); /* CYRILLIC CAPITAL LETTER CHE WITH VERTICAL STROKE */ $config['0400_04ff'][] = array('upper' => 1210, 'status' => 'C', 'lower' => array(1211)); /* CYRILLIC CAPITAL LETTER SHHA */ $config['0400_04ff'][] = array('upper' => 1212, 'status' => 'C', 'lower' => array(1213)); /* CYRILLIC CAPITAL LETTER ABKHASIAN CHE */ $config['0400_04ff'][] = array('upper' => 1214, 'status' => 'C', 'lower' => array(1215)); /* CYRILLIC CAPITAL LETTER ABKHASIAN CHE WITH DESCENDER */ $config['0400_04ff'][] = array('upper' => 1216, 'status' => 'C', 'lower' => array(1231)); /* CYRILLIC LETTER PALOCHKA */ $config['0400_04ff'][] = array('upper' => 1217, 'status' => 'C', 'lower' => array(1218)); /* CYRILLIC CAPITAL LETTER ZHE WITH BREVE */ $config['0400_04ff'][] = array('upper' => 1219, 'status' => 'C', 'lower' => array(1220)); /* CYRILLIC CAPITAL LETTER KA WITH HOOK */ $config['0400_04ff'][] = array('upper' => 1221, 'status' => 'C', 'lower' => array(1222)); /* CYRILLIC CAPITAL LETTER EL WITH TAIL */ $config['0400_04ff'][] = array('upper' => 1223, 'status' => 'C', 'lower' => array(1224)); /* CYRILLIC CAPITAL LETTER EN WITH HOOK */ $config['0400_04ff'][] = array('upper' => 1225, 'status' => 'C', 'lower' => array(1226)); /* CYRILLIC CAPITAL LETTER EN WITH TAIL */ $config['0400_04ff'][] = array('upper' => 1227, 'status' => 'C', 'lower' => array(1228)); /* CYRILLIC CAPITAL LETTER KHAKASSIAN CHE */ $config['0400_04ff'][] = array('upper' => 1229, 'status' => 'C', 'lower' => array(1230)); /* CYRILLIC CAPITAL LETTER EM WITH TAIL */ $config['0400_04ff'][] = array('upper' => 1232, 'status' => 'C', 'lower' => array(1233)); /* CYRILLIC CAPITAL LETTER A WITH BREVE */ $config['0400_04ff'][] = array('upper' => 1234, 'status' => 'C', 'lower' => array(1235)); /* CYRILLIC CAPITAL LETTER A WITH DIAERESIS */ $config['0400_04ff'][] = array('upper' => 1236, 'status' => 'C', 'lower' => array(1237)); /* CYRILLIC CAPITAL LIGATURE A IE */ $config['0400_04ff'][] = array('upper' => 1238, 'status' => 'C', 'lower' => array(1239)); /* CYRILLIC CAPITAL LETTER IE WITH BREVE */ $config['0400_04ff'][] = array('upper' => 1240, 'status' => 'C', 'lower' => array(1241)); /* CYRILLIC CAPITAL LETTER SCHWA */ $config['0400_04ff'][] = array('upper' => 1242, 'status' => 'C', 'lower' => array(1243)); /* CYRILLIC CAPITAL LETTER SCHWA WITH DIAERESIS */ $config['0400_04ff'][] = array('upper' => 1244, 'status' => 'C', 'lower' => array(1245)); /* CYRILLIC CAPITAL LETTER ZHE WITH DIAERESIS */ $config['0400_04ff'][] = array('upper' => 1246, 'status' => 'C', 'lower' => array(1247)); /* CYRILLIC CAPITAL LETTER ZE WITH DIAERESIS */ $config['0400_04ff'][] = array('upper' => 1248, 'status' => 'C', 'lower' => array(1249)); /* CYRILLIC CAPITAL LETTER ABKHASIAN DZE */ $config['0400_04ff'][] = array('upper' => 1250, 'status' => 'C', 'lower' => array(1251)); /* CYRILLIC CAPITAL LETTER I WITH MACRON */ $config['0400_04ff'][] = array('upper' => 1252, 'status' => 'C', 'lower' => array(1253)); /* CYRILLIC CAPITAL LETTER I WITH DIAERESIS */ $config['0400_04ff'][] = array('upper' => 1254, 'status' => 'C', 'lower' => array(1255)); /* CYRILLIC CAPITAL LETTER O WITH DIAERESIS */ $config['0400_04ff'][] = array('upper' => 1256, 'status' => 'C', 'lower' => array(1257)); /* CYRILLIC CAPITAL LETTER BARRED O */ $config['0400_04ff'][] = array('upper' => 1258, 'status' => 'C', 'lower' => array(1259)); /* CYRILLIC CAPITAL LETTER BARRED O WITH DIAERESIS */ $config['0400_04ff'][] = array('upper' => 1260, 'status' => 'C', 'lower' => array(1261)); /* CYRILLIC CAPITAL LETTER E WITH DIAERESIS */ $config['0400_04ff'][] = array('upper' => 1262, 'status' => 'C', 'lower' => array(1263)); /* CYRILLIC CAPITAL LETTER U WITH MACRON */ $config['0400_04ff'][] = array('upper' => 1264, 'status' => 'C', 'lower' => array(1265)); /* CYRILLIC CAPITAL LETTER U WITH DIAERESIS */ $config['0400_04ff'][] = array('upper' => 1266, 'status' => 'C', 'lower' => array(1267)); /* CYRILLIC CAPITAL LETTER U WITH DOUBLE ACUTE */ $config['0400_04ff'][] = array('upper' => 1268, 'status' => 'C', 'lower' => array(1269)); /* CYRILLIC CAPITAL LETTER CHE WITH DIAERESIS */ $config['0400_04ff'][] = array('upper' => 1270, 'status' => 'C', 'lower' => array(1271)); /* CYRILLIC CAPITAL LETTER GHE WITH DESCENDER */ $config['0400_04ff'][] = array('upper' => 1272, 'status' => 'C', 'lower' => array(1273)); /* CYRILLIC CAPITAL LETTER YERU WITH DIAERESIS */ $config['0400_04ff'][] = array('upper' => 1274, 'status' => 'C', 'lower' => array(1275)); /* CYRILLIC CAPITAL LETTER GHE WITH STROKE AND HOOK */ $config['0400_04ff'][] = array('upper' => 1276, 'status' => 'C', 'lower' => array(1277)); /* CYRILLIC CAPITAL LETTER HA WITH HOOK */ $config['0400_04ff'][] = array('upper' => 1278, 'status' => 'C', 'lower' => array(1279)); /* CYRILLIC CAPITAL LETTER HA WITH STROKE */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/0400_04ff.php
PHP
gpl3
18,061
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+FF00 through U+FFEF * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['ff00_ffef'][] = array('upper' => 65313, 'status' => 'C', 'lower' => array(65345)); /* FULLWIDTH LATIN CAPITAL LETTER A */ $config['ff00_ffef'][] = array('upper' => 65314, 'status' => 'C', 'lower' => array(65346)); /* FULLWIDTH LATIN CAPITAL LETTER B */ $config['ff00_ffef'][] = array('upper' => 65315, 'status' => 'C', 'lower' => array(65347)); /* FULLWIDTH LATIN CAPITAL LETTER C */ $config['ff00_ffef'][] = array('upper' => 65316, 'status' => 'C', 'lower' => array(65348)); /* FULLWIDTH LATIN CAPITAL LETTER D */ $config['ff00_ffef'][] = array('upper' => 65317, 'status' => 'C', 'lower' => array(65349)); /* FULLWIDTH LATIN CAPITAL LETTER E */ $config['ff00_ffef'][] = array('upper' => 65318, 'status' => 'C', 'lower' => array(65350)); /* FULLWIDTH LATIN CAPITAL LETTER F */ $config['ff00_ffef'][] = array('upper' => 65319, 'status' => 'C', 'lower' => array(65351)); /* FULLWIDTH LATIN CAPITAL LETTER G */ $config['ff00_ffef'][] = array('upper' => 65320, 'status' => 'C', 'lower' => array(65352)); /* FULLWIDTH LATIN CAPITAL LETTER H */ $config['ff00_ffef'][] = array('upper' => 65321, 'status' => 'C', 'lower' => array(65353)); /* FULLWIDTH LATIN CAPITAL LETTER I */ $config['ff00_ffef'][] = array('upper' => 65322, 'status' => 'C', 'lower' => array(65354)); /* FULLWIDTH LATIN CAPITAL LETTER J */ $config['ff00_ffef'][] = array('upper' => 65323, 'status' => 'C', 'lower' => array(65355)); /* FULLWIDTH LATIN CAPITAL LETTER K */ $config['ff00_ffef'][] = array('upper' => 65324, 'status' => 'C', 'lower' => array(65356)); /* FULLWIDTH LATIN CAPITAL LETTER L */ $config['ff00_ffef'][] = array('upper' => 65325, 'status' => 'C', 'lower' => array(65357)); /* FULLWIDTH LATIN CAPITAL LETTER M */ $config['ff00_ffef'][] = array('upper' => 65326, 'status' => 'C', 'lower' => array(65358)); /* FULLWIDTH LATIN CAPITAL LETTER N */ $config['ff00_ffef'][] = array('upper' => 65327, 'status' => 'C', 'lower' => array(65359)); /* FULLWIDTH LATIN CAPITAL LETTER O */ $config['ff00_ffef'][] = array('upper' => 65328, 'status' => 'C', 'lower' => array(65360)); /* FULLWIDTH LATIN CAPITAL LETTER P */ $config['ff00_ffef'][] = array('upper' => 65329, 'status' => 'C', 'lower' => array(65361)); /* FULLWIDTH LATIN CAPITAL LETTER Q */ $config['ff00_ffef'][] = array('upper' => 65330, 'status' => 'C', 'lower' => array(65362)); /* FULLWIDTH LATIN CAPITAL LETTER R */ $config['ff00_ffef'][] = array('upper' => 65331, 'status' => 'C', 'lower' => array(65363)); /* FULLWIDTH LATIN CAPITAL LETTER S */ $config['ff00_ffef'][] = array('upper' => 65332, 'status' => 'C', 'lower' => array(65364)); /* FULLWIDTH LATIN CAPITAL LETTER T */ $config['ff00_ffef'][] = array('upper' => 65333, 'status' => 'C', 'lower' => array(65365)); /* FULLWIDTH LATIN CAPITAL LETTER U */ $config['ff00_ffef'][] = array('upper' => 65334, 'status' => 'C', 'lower' => array(65366)); /* FULLWIDTH LATIN CAPITAL LETTER V */ $config['ff00_ffef'][] = array('upper' => 65335, 'status' => 'C', 'lower' => array(65367)); /* FULLWIDTH LATIN CAPITAL LETTER W */ $config['ff00_ffef'][] = array('upper' => 65336, 'status' => 'C', 'lower' => array(65368)); /* FULLWIDTH LATIN CAPITAL LETTER X */ $config['ff00_ffef'][] = array('upper' => 65337, 'status' => 'C', 'lower' => array(65369)); /* FULLWIDTH LATIN CAPITAL LETTER Y */ $config['ff00_ffef'][] = array('upper' => 65338, 'status' => 'C', 'lower' => array(65370)); /* FULLWIDTH LATIN CAPITAL LETTER Z */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/ff00_ffef.php
PHP
gpl3
5,242
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+2C80 through U+2CFF * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['2c80_2cff'][] = array('upper' => 11392, 'status' => 'C', 'lower' => array(11393)); /* COPTIC CAPITAL LETTER ALFA */ $config['2c80_2cff'][] = array('upper' => 11394, 'status' => 'C', 'lower' => array(11395)); /* COPTIC CAPITAL LETTER VIDA */ $config['2c80_2cff'][] = array('upper' => 11396, 'status' => 'C', 'lower' => array(11397)); /* COPTIC CAPITAL LETTER GAMMA */ $config['2c80_2cff'][] = array('upper' => 11398, 'status' => 'C', 'lower' => array(11399)); /* COPTIC CAPITAL LETTER DALDA */ $config['2c80_2cff'][] = array('upper' => 11400, 'status' => 'C', 'lower' => array(11401)); /* COPTIC CAPITAL LETTER EIE */ $config['2c80_2cff'][] = array('upper' => 11402, 'status' => 'C', 'lower' => array(11403)); /* COPTIC CAPITAL LETTER SOU */ $config['2c80_2cff'][] = array('upper' => 11404, 'status' => 'C', 'lower' => array(11405)); /* COPTIC CAPITAL LETTER ZATA */ $config['2c80_2cff'][] = array('upper' => 11406, 'status' => 'C', 'lower' => array(11407)); /* COPTIC CAPITAL LETTER HATE */ $config['2c80_2cff'][] = array('upper' => 11408, 'status' => 'C', 'lower' => array(11409)); /* COPTIC CAPITAL LETTER THETHE */ $config['2c80_2cff'][] = array('upper' => 11410, 'status' => 'C', 'lower' => array(11411)); /* COPTIC CAPITAL LETTER IAUDA */ $config['2c80_2cff'][] = array('upper' => 11412, 'status' => 'C', 'lower' => array(11413)); /* COPTIC CAPITAL LETTER KAPA */ $config['2c80_2cff'][] = array('upper' => 11414, 'status' => 'C', 'lower' => array(11415)); /* COPTIC CAPITAL LETTER LAULA */ $config['2c80_2cff'][] = array('upper' => 11416, 'status' => 'C', 'lower' => array(11417)); /* COPTIC CAPITAL LETTER MI */ $config['2c80_2cff'][] = array('upper' => 11418, 'status' => 'C', 'lower' => array(11419)); /* COPTIC CAPITAL LETTER NI */ $config['2c80_2cff'][] = array('upper' => 11420, 'status' => 'C', 'lower' => array(11421)); /* COPTIC CAPITAL LETTER KSI */ $config['2c80_2cff'][] = array('upper' => 11422, 'status' => 'C', 'lower' => array(11423)); /* COPTIC CAPITAL LETTER O */ $config['2c80_2cff'][] = array('upper' => 11424, 'status' => 'C', 'lower' => array(11425)); /* COPTIC CAPITAL LETTER PI */ $config['2c80_2cff'][] = array('upper' => 11426, 'status' => 'C', 'lower' => array(11427)); /* COPTIC CAPITAL LETTER RO */ $config['2c80_2cff'][] = array('upper' => 11428, 'status' => 'C', 'lower' => array(11429)); /* COPTIC CAPITAL LETTER SIMA */ $config['2c80_2cff'][] = array('upper' => 11430, 'status' => 'C', 'lower' => array(11431)); /* COPTIC CAPITAL LETTER TAU */ $config['2c80_2cff'][] = array('upper' => 11432, 'status' => 'C', 'lower' => array(11433)); /* COPTIC CAPITAL LETTER UA */ $config['2c80_2cff'][] = array('upper' => 11434, 'status' => 'C', 'lower' => array(11435)); /* COPTIC CAPITAL LETTER FI */ $config['2c80_2cff'][] = array('upper' => 11436, 'status' => 'C', 'lower' => array(11437)); /* COPTIC CAPITAL LETTER KHI */ $config['2c80_2cff'][] = array('upper' => 11438, 'status' => 'C', 'lower' => array(11439)); /* COPTIC CAPITAL LETTER PSI */ $config['2c80_2cff'][] = array('upper' => 11440, 'status' => 'C', 'lower' => array(11441)); /* COPTIC CAPITAL LETTER OOU */ $config['2c80_2cff'][] = array('upper' => 11442, 'status' => 'C', 'lower' => array(11443)); /* COPTIC CAPITAL LETTER DIALECT-P ALEF */ $config['2c80_2cff'][] = array('upper' => 11444, 'status' => 'C', 'lower' => array(11445)); /* COPTIC CAPITAL LETTER OLD COPTIC AIN */ $config['2c80_2cff'][] = array('upper' => 11446, 'status' => 'C', 'lower' => array(11447)); /* COPTIC CAPITAL LETTER CRYPTOGRAMMIC EIE */ $config['2c80_2cff'][] = array('upper' => 11448, 'status' => 'C', 'lower' => array(11449)); /* COPTIC CAPITAL LETTER DIALECT-P KAPA */ $config['2c80_2cff'][] = array('upper' => 11450, 'status' => 'C', 'lower' => array(11451)); /* COPTIC CAPITAL LETTER DIALECT-P NI */ $config['2c80_2cff'][] = array('upper' => 11452, 'status' => 'C', 'lower' => array(11453)); /* COPTIC CAPITAL LETTER CRYPTOGRAMMIC NI */ $config['2c80_2cff'][] = array('upper' => 11454, 'status' => 'C', 'lower' => array(11455)); /* COPTIC CAPITAL LETTER OLD COPTIC OOU */ $config['2c80_2cff'][] = array('upper' => 11456, 'status' => 'C', 'lower' => array(11457)); /* COPTIC CAPITAL LETTER SAMPI */ $config['2c80_2cff'][] = array('upper' => 11458, 'status' => 'C', 'lower' => array(11459)); /* COPTIC CAPITAL LETTER CROSSED SHEI */ $config['2c80_2cff'][] = array('upper' => 11460, 'status' => 'C', 'lower' => array(11461)); /* COPTIC CAPITAL LETTER OLD COPTIC SHEI */ $config['2c80_2cff'][] = array('upper' => 11462, 'status' => 'C', 'lower' => array(11463)); /* COPTIC CAPITAL LETTER OLD COPTIC ESH */ $config['2c80_2cff'][] = array('upper' => 11464, 'status' => 'C', 'lower' => array(11465)); /* COPTIC CAPITAL LETTER AKHMIMIC KHEI */ $config['2c80_2cff'][] = array('upper' => 11466, 'status' => 'C', 'lower' => array(11467)); /* COPTIC CAPITAL LETTER DIALECT-P HORI */ $config['2c80_2cff'][] = array('upper' => 11468, 'status' => 'C', 'lower' => array(11469)); /* COPTIC CAPITAL LETTER OLD COPTIC HORI */ $config['2c80_2cff'][] = array('upper' => 11470, 'status' => 'C', 'lower' => array(11471)); /* COPTIC CAPITAL LETTER OLD COPTIC HA */ $config['2c80_2cff'][] = array('upper' => 11472, 'status' => 'C', 'lower' => array(11473)); /* COPTIC CAPITAL LETTER L-SHAPED HA */ $config['2c80_2cff'][] = array('upper' => 11474, 'status' => 'C', 'lower' => array(11475)); /* COPTIC CAPITAL LETTER OLD COPTIC HEI */ $config['2c80_2cff'][] = array('upper' => 11476, 'status' => 'C', 'lower' => array(11477)); /* COPTIC CAPITAL LETTER OLD COPTIC HAT */ $config['2c80_2cff'][] = array('upper' => 11478, 'status' => 'C', 'lower' => array(11479)); /* COPTIC CAPITAL LETTER OLD COPTIC GANGIA */ $config['2c80_2cff'][] = array('upper' => 11480, 'status' => 'C', 'lower' => array(11481)); /* COPTIC CAPITAL LETTER OLD COPTIC DJA */ $config['2c80_2cff'][] = array('upper' => 11482, 'status' => 'C', 'lower' => array(11483)); /* COPTIC CAPITAL LETTER OLD COPTIC SHIMA */ $config['2c80_2cff'][] = array('upper' => 11484, 'status' => 'C', 'lower' => array(11485)); /* COPTIC CAPITAL LETTER OLD NUBIAN SHIMA */ $config['2c80_2cff'][] = array('upper' => 11486, 'status' => 'C', 'lower' => array(11487)); /* COPTIC CAPITAL LETTER OLD NUBIAN NGI */ $config['2c80_2cff'][] = array('upper' => 11488, 'status' => 'C', 'lower' => array(11489)); /* COPTIC CAPITAL LETTER OLD NUBIAN NYI */ $config['2c80_2cff'][] = array('upper' => 11490, 'status' => 'C', 'lower' => array(11491)); /* COPTIC CAPITAL LETTER OLD NUBIAN WAU */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/2c80_2cff.php
PHP
gpl3
8,316
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+0180 through U+024F * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['0180_024F'][] = array('upper' => 385, 'status' => 'C', 'lower' => array(595)); /* LATIN CAPITAL LETTER B WITH HOOK */ $config['0180_024F'][] = array('upper' => 386, 'status' => 'C', 'lower' => array(387)); /* LATIN CAPITAL LETTER B WITH TOPBAR */ $config['0180_024F'][] = array('upper' => 388, 'status' => 'C', 'lower' => array(389)); /* LATIN CAPITAL LETTER TONE SIX */ $config['0180_024F'][] = array('upper' => 390, 'status' => 'C', 'lower' => array(596)); /* LATIN CAPITAL LETTER OPEN O */ $config['0180_024F'][] = array('upper' => 391, 'status' => 'C', 'lower' => array(392)); /* LATIN CAPITAL LETTER C WITH HOOK */ $config['0180_024F'][] = array('upper' => 393, 'status' => 'C', 'lower' => array(598)); /* LATIN CAPITAL LETTER AFRICAN D */ $config['0180_024F'][] = array('upper' => 394, 'status' => 'C', 'lower' => array(599)); /* LATIN CAPITAL LETTER D WITH HOOK */ $config['0180_024F'][] = array('upper' => 395, 'status' => 'C', 'lower' => array(396)); /* LATIN CAPITAL LETTER D WITH TOPBAR */ $config['0180_024F'][] = array('upper' => 398, 'status' => 'C', 'lower' => array(477)); /* LATIN CAPITAL LETTER REVERSED E */ $config['0180_024F'][] = array('upper' => 399, 'status' => 'C', 'lower' => array(601)); /* LATIN CAPITAL LETTER SCHWA */ $config['0180_024F'][] = array('upper' => 400, 'status' => 'C', 'lower' => array(603)); /* LATIN CAPITAL LETTER OPEN E */ $config['0180_024F'][] = array('upper' => 401, 'status' => 'C', 'lower' => array(402)); /* LATIN CAPITAL LETTER F WITH HOOK */ $config['0180_024F'][] = array('upper' => 403, 'status' => 'C', 'lower' => array(608)); /* LATIN CAPITAL LETTER G WITH HOOK */ $config['0180_024F'][] = array('upper' => 404, 'status' => 'C', 'lower' => array(611)); /* LATIN CAPITAL LETTER GAMMA */ $config['0180_024F'][] = array('upper' => 406, 'status' => 'C', 'lower' => array(617)); /* LATIN CAPITAL LETTER IOTA */ $config['0180_024F'][] = array('upper' => 407, 'status' => 'C', 'lower' => array(616)); /* LATIN CAPITAL LETTER I WITH STROKE */ $config['0180_024F'][] = array('upper' => 408, 'status' => 'C', 'lower' => array(409)); /* LATIN CAPITAL LETTER K WITH HOOK */ $config['0180_024F'][] = array('upper' => 412, 'status' => 'C', 'lower' => array(623)); /* LATIN CAPITAL LETTER TURNED M */ $config['0180_024F'][] = array('upper' => 413, 'status' => 'C', 'lower' => array(626)); /* LATIN CAPITAL LETTER N WITH LEFT HOOK */ $config['0180_024F'][] = array('upper' => 415, 'status' => 'C', 'lower' => array(629)); /* LATIN CAPITAL LETTER O WITH MIDDLE TILDE */ $config['0180_024F'][] = array('upper' => 416, 'status' => 'C', 'lower' => array(417)); /* LATIN CAPITAL LETTER O WITH HORN */ $config['0180_024F'][] = array('upper' => 418, 'status' => 'C', 'lower' => array(419)); /* LATIN CAPITAL LETTER OI */ $config['0180_024F'][] = array('upper' => 420, 'status' => 'C', 'lower' => array(421)); /* LATIN CAPITAL LETTER P WITH HOOK */ $config['0180_024F'][] = array('upper' => 422, 'status' => 'C', 'lower' => array(640)); /* LATIN LETTER YR */ $config['0180_024F'][] = array('upper' => 423, 'status' => 'C', 'lower' => array(424)); /* LATIN CAPITAL LETTER TONE TWO */ $config['0180_024F'][] = array('upper' => 425, 'status' => 'C', 'lower' => array(643)); /* LATIN CAPITAL LETTER ESH */ $config['0180_024F'][] = array('upper' => 428, 'status' => 'C', 'lower' => array(429)); /* LATIN CAPITAL LETTER T WITH HOOK */ $config['0180_024F'][] = array('upper' => 430, 'status' => 'C', 'lower' => array(648)); /* LATIN CAPITAL LETTER T WITH RETROFLEX HOOK */ $config['0180_024F'][] = array('upper' => 431, 'status' => 'C', 'lower' => array(432)); /* LATIN CAPITAL LETTER U WITH HORN */ $config['0180_024F'][] = array('upper' => 433, 'status' => 'C', 'lower' => array(650)); /* LATIN CAPITAL LETTER UPSILON */ $config['0180_024F'][] = array('upper' => 434, 'status' => 'C', 'lower' => array(651)); /* LATIN CAPITAL LETTER V WITH HOOK */ $config['0180_024F'][] = array('upper' => 435, 'status' => 'C', 'lower' => array(436)); /* LATIN CAPITAL LETTER Y WITH HOOK */ $config['0180_024F'][] = array('upper' => 437, 'status' => 'C', 'lower' => array(438)); /* LATIN CAPITAL LETTER Z WITH STROKE */ $config['0180_024F'][] = array('upper' => 439, 'status' => 'C', 'lower' => array(658)); /* LATIN CAPITAL LETTER EZH */ $config['0180_024F'][] = array('upper' => 440, 'status' => 'C', 'lower' => array(441)); /* LATIN CAPITAL LETTER EZH REVERSED */ $config['0180_024F'][] = array('upper' => 444, 'status' => 'C', 'lower' => array(445)); /* LATIN CAPITAL LETTER TONE FIVE */ $config['0180_024F'][] = array('upper' => 452, 'status' => 'C', 'lower' => array(454)); /* LATIN CAPITAL LETTER DZ WITH CARON */ $config['0180_024F'][] = array('upper' => 453, 'status' => 'C', 'lower' => array(454)); /* LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON */ $config['0180_024F'][] = array('upper' => 455, 'status' => 'C', 'lower' => array(457)); /* LATIN CAPITAL LETTER LJ */ $config['0180_024F'][] = array('upper' => 456, 'status' => 'C', 'lower' => array(457)); /* LATIN CAPITAL LETTER L WITH SMALL LETTER J */ $config['0180_024F'][] = array('upper' => 458, 'status' => 'C', 'lower' => array(460)); /* LATIN CAPITAL LETTER NJ */ $config['0180_024F'][] = array('upper' => 459, 'status' => 'C', 'lower' => array(460)); /* LATIN CAPITAL LETTER N WITH SMALL LETTER J */ $config['0180_024F'][] = array('upper' => 461, 'status' => 'C', 'lower' => array(462)); /* LATIN CAPITAL LETTER A WITH CARON */ $config['0180_024F'][] = array('upper' => 463, 'status' => 'C', 'lower' => array(464)); /* LATIN CAPITAL LETTER I WITH CARON */ $config['0180_024F'][] = array('upper' => 465, 'status' => 'C', 'lower' => array(466)); /* LATIN CAPITAL LETTER O WITH CARON */ $config['0180_024F'][] = array('upper' => 467, 'status' => 'C', 'lower' => array(468)); /* LATIN CAPITAL LETTER U WITH CARON */ $config['0180_024F'][] = array('upper' => 469, 'status' => 'C', 'lower' => array(470)); /* LATIN CAPITAL LETTER U WITH DIAERESIS AND MACRON */ $config['0180_024F'][] = array('upper' => 471, 'status' => 'C', 'lower' => array(472)); /* LATIN CAPITAL LETTER U WITH DIAERESIS AND ACUTE */ $config['0180_024F'][] = array('upper' => 473, 'status' => 'C', 'lower' => array(474)); /* LATIN CAPITAL LETTER U WITH DIAERESIS AND CARON */ $config['0180_024F'][] = array('upper' => 475, 'status' => 'C', 'lower' => array(476)); /* LATIN CAPITAL LETTER U WITH DIAERESIS AND GRAVE */ $config['0180_024F'][] = array('upper' => 478, 'status' => 'C', 'lower' => array(479)); /* LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON */ $config['0180_024F'][] = array('upper' => 480, 'status' => 'C', 'lower' => array(481)); /* LATIN CAPITAL LETTER A WITH DOT ABOVE AND MACRON */ $config['0180_024F'][] = array('upper' => 482, 'status' => 'C', 'lower' => array(483)); /* LATIN CAPITAL LETTER AE WITH MACRON */ $config['0180_024F'][] = array('upper' => 484, 'status' => 'C', 'lower' => array(485)); /* LATIN CAPITAL LETTER G WITH STROKE */ $config['0180_024F'][] = array('upper' => 486, 'status' => 'C', 'lower' => array(487)); /* LATIN CAPITAL LETTER G WITH CARON */ $config['0180_024F'][] = array('upper' => 488, 'status' => 'C', 'lower' => array(489)); /* LATIN CAPITAL LETTER K WITH CARON */ $config['0180_024F'][] = array('upper' => 490, 'status' => 'C', 'lower' => array(491)); /* LATIN CAPITAL LETTER O WITH OGONEK */ $config['0180_024F'][] = array('upper' => 492, 'status' => 'C', 'lower' => array(493)); /* LATIN CAPITAL LETTER O WITH OGONEK AND MACRON */ $config['0180_024F'][] = array('upper' => 494, 'status' => 'C', 'lower' => array(495)); /* LATIN CAPITAL LETTER EZH WITH CARON */ $config['0180_024F'][] = array('upper' => 496, 'status' => 'F', 'lower' => array(106, 780)); /* LATIN SMALL LETTER J WITH CARON */ $config['0180_024F'][] = array('upper' => 497, 'status' => 'C', 'lower' => array(499)); /* LATIN CAPITAL LETTER DZ */ $config['0180_024F'][] = array('upper' => 498, 'status' => 'C', 'lower' => array(499)); /* LATIN CAPITAL LETTER D WITH SMALL LETTER Z */ $config['0180_024F'][] = array('upper' => 500, 'status' => 'C', 'lower' => array(501)); /* LATIN CAPITAL LETTER G WITH ACUTE */ $config['0180_024F'][] = array('upper' => 502, 'status' => 'C', 'lower' => array(405)); /* LATIN CAPITAL LETTER HWAIR */ $config['0180_024F'][] = array('upper' => 503, 'status' => 'C', 'lower' => array(447)); /* LATIN CAPITAL LETTER WYNN */ $config['0180_024F'][] = array('upper' => 504, 'status' => 'C', 'lower' => array(505)); /* LATIN CAPITAL LETTER N WITH GRAVE */ $config['0180_024F'][] = array('upper' => 506, 'status' => 'C', 'lower' => array(507)); /* LATIN CAPITAL LETTER A WITH RING ABOVE AND ACUTE */ $config['0180_024F'][] = array('upper' => 508, 'status' => 'C', 'lower' => array(509)); /* LATIN CAPITAL LETTER AE WITH ACUTE */ $config['0180_024F'][] = array('upper' => 510, 'status' => 'C', 'lower' => array(511)); /* LATIN CAPITAL LETTER O WITH STROKE AND ACUTE */ $config['0180_024F'][] = array('upper' => 512, 'status' => 'C', 'lower' => array(513)); /* LATIN CAPITAL LETTER A WITH DOUBLE GRAVE */ $config['0180_024F'][] = array('upper' => 514, 'status' => 'C', 'lower' => array(515)); /* LATIN CAPITAL LETTER A WITH INVERTED BREVE */ $config['0180_024F'][] = array('upper' => 516, 'status' => 'C', 'lower' => array(517)); /* LATIN CAPITAL LETTER E WITH DOUBLE GRAVE */ $config['0180_024F'][] = array('upper' => 518, 'status' => 'C', 'lower' => array(519)); /* LATIN CAPITAL LETTER E WITH INVERTED BREVE */ $config['0180_024F'][] = array('upper' => 520, 'status' => 'C', 'lower' => array(521)); /* LATIN CAPITAL LETTER I WITH DOUBLE GRAVE */ $config['0180_024F'][] = array('upper' => 522, 'status' => 'C', 'lower' => array(523)); /* LATIN CAPITAL LETTER I WITH INVERTED BREVE */ $config['0180_024F'][] = array('upper' => 524, 'status' => 'C', 'lower' => array(525)); /* LATIN CAPITAL LETTER O WITH DOUBLE GRAVE */ $config['0180_024F'][] = array('upper' => 526, 'status' => 'C', 'lower' => array(527)); /* LATIN CAPITAL LETTER O WITH INVERTED BREVE */ $config['0180_024F'][] = array('upper' => 528, 'status' => 'C', 'lower' => array(529)); /* LATIN CAPITAL LETTER R WITH DOUBLE GRAVE */ $config['0180_024F'][] = array('upper' => 530, 'status' => 'C', 'lower' => array(531)); /* LATIN CAPITAL LETTER R WITH INVERTED BREVE */ $config['0180_024F'][] = array('upper' => 532, 'status' => 'C', 'lower' => array(533)); /* LATIN CAPITAL LETTER U WITH DOUBLE GRAVE */ $config['0180_024F'][] = array('upper' => 534, 'status' => 'C', 'lower' => array(535)); /* LATIN CAPITAL LETTER U WITH INVERTED BREVE */ $config['0180_024F'][] = array('upper' => 536, 'status' => 'C', 'lower' => array(537)); /* LATIN CAPITAL LETTER S WITH COMMA BELOW */ $config['0180_024F'][] = array('upper' => 538, 'status' => 'C', 'lower' => array(539)); /* LATIN CAPITAL LETTER T WITH COMMA BELOW */ $config['0180_024F'][] = array('upper' => 540, 'status' => 'C', 'lower' => array(541)); /* LATIN CAPITAL LETTER YOGH */ $config['0180_024F'][] = array('upper' => 542, 'status' => 'C', 'lower' => array(543)); /* LATIN CAPITAL LETTER H WITH CARON */ $config['0180_024F'][] = array('upper' => 544, 'status' => 'C', 'lower' => array(414)); /* LATIN CAPITAL LETTER N WITH LONG RIGHT LEG */ $config['0180_024F'][] = array('upper' => 546, 'status' => 'C', 'lower' => array(547)); /* LATIN CAPITAL LETTER OU */ $config['0180_024F'][] = array('upper' => 548, 'status' => 'C', 'lower' => array(549)); /* LATIN CAPITAL LETTER Z WITH HOOK */ $config['0180_024F'][] = array('upper' => 550, 'status' => 'C', 'lower' => array(551)); /* LATIN CAPITAL LETTER A WITH DOT ABOVE */ $config['0180_024F'][] = array('upper' => 552, 'status' => 'C', 'lower' => array(553)); /* LATIN CAPITAL LETTER E WITH CEDILLA */ $config['0180_024F'][] = array('upper' => 554, 'status' => 'C', 'lower' => array(555)); /* LATIN CAPITAL LETTER O WITH DIAERESIS AND MACRON */ $config['0180_024F'][] = array('upper' => 556, 'status' => 'C', 'lower' => array(557)); /* LATIN CAPITAL LETTER O WITH TILDE AND MACRON */ $config['0180_024F'][] = array('upper' => 558, 'status' => 'C', 'lower' => array(559)); /* LATIN CAPITAL LETTER O WITH DOT ABOVE */ $config['0180_024F'][] = array('upper' => 560, 'status' => 'C', 'lower' => array(561)); /* LATIN CAPITAL LETTER O WITH DOT ABOVE AND MACRON */ $config['0180_024F'][] = array('upper' => 562, 'status' => 'C', 'lower' => array(563)); /* LATIN CAPITAL LETTER Y WITH MACRON */ $config['0180_024F'][] = array('upper' => 570, 'status' => 'C', 'lower' => array(11365)); /* LATIN CAPITAL LETTER A WITH STROKE */ $config['0180_024F'][] = array('upper' => 571, 'status' => 'C', 'lower' => array(572)); /* LATIN CAPITAL LETTER C WITH STROKE */ $config['0180_024F'][] = array('upper' => 573, 'status' => 'C', 'lower' => array(410)); /* LATIN CAPITAL LETTER L WITH BAR */ $config['0180_024F'][] = array('upper' => 574, 'status' => 'C', 'lower' => array(11366)); /* LATIN CAPITAL LETTER T WITH DIAGONAL STROKE */ $config['0180_024F'][] = array('upper' => 577, 'status' => 'C', 'lower' => array(578)); /* LATIN CAPITAL LETTER GLOTTAL STOP */ $config['0180_024F'][] = array('upper' => 579, 'status' => 'C', 'lower' => array(384)); /* LATIN CAPITAL LETTER B WITH STROKE */ $config['0180_024F'][] = array('upper' => 580, 'status' => 'C', 'lower' => array(649)); /* LATIN CAPITAL LETTER U BAR */ $config['0180_024F'][] = array('upper' => 581, 'status' => 'C', 'lower' => array(652)); /* LATIN CAPITAL LETTER TURNED V */ $config['0180_024F'][] = array('upper' => 582, 'status' => 'C', 'lower' => array(583)); /* LATIN CAPITAL LETTER E WITH STROKE */ $config['0180_024F'][] = array('upper' => 584, 'status' => 'C', 'lower' => array(585)); /* LATIN CAPITAL LETTER J WITH STROKE */ $config['0180_024F'][] = array('upper' => 586, 'status' => 'C', 'lower' => array(587)); /* LATIN CAPITAL LETTER SMALL Q WITH HOOK TAIL */ $config['0180_024F'][] = array('upper' => 588, 'status' => 'C', 'lower' => array(589)); /* LATIN CAPITAL LETTER R WITH STROKE */ $config['0180_024F'][] = array('upper' => 590, 'status' => 'C', 'lower' => array(591)); /* LATIN CAPITAL LETTER Y WITH STROKE */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/0180_024F.php
PHP
gpl3
15,873
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+2100 through U+214F * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['2100_214f'][] = array('upper' => 8486, 'status' => 'C', 'lower' => array(969)); /* OHM SIGN */ $config['2100_214f'][] = array('upper' => 8490, 'status' => 'C', 'lower' => array(107)); /* KELVIN SIGN */ $config['2100_214f'][] = array('upper' => 8491, 'status' => 'C', 'lower' => array(229)); /* ANGSTROM SIGN */ $config['2100_214f'][] = array('upper' => 8498, 'status' => 'C', 'lower' => array(8526)); /* TURNED CAPITAL F */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/2100_214f.php
PHP
gpl3
2,269
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+0530 through U+058F * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['0530_058f'][] = array('upper' => 1329, 'status' => 'C', 'lower' => array(1377)); /* ARMENIAN CAPITAL LETTER AYB */ $config['0530_058f'][] = array('upper' => 1330, 'status' => 'C', 'lower' => array(1378)); /* ARMENIAN CAPITAL LETTER BEN */ $config['0530_058f'][] = array('upper' => 1331, 'status' => 'C', 'lower' => array(1379)); /* ARMENIAN CAPITAL LETTER GIM */ $config['0530_058f'][] = array('upper' => 1332, 'status' => 'C', 'lower' => array(1380)); /* ARMENIAN CAPITAL LETTER DA */ $config['0530_058f'][] = array('upper' => 1333, 'status' => 'C', 'lower' => array(1381)); /* ARMENIAN CAPITAL LETTER ECH */ $config['0530_058f'][] = array('upper' => 1334, 'status' => 'C', 'lower' => array(1382)); /* ARMENIAN CAPITAL LETTER ZA */ $config['0530_058f'][] = array('upper' => 1335, 'status' => 'C', 'lower' => array(1383)); /* ARMENIAN CAPITAL LETTER EH */ $config['0530_058f'][] = array('upper' => 1336, 'status' => 'C', 'lower' => array(1384)); /* ARMENIAN CAPITAL LETTER ET */ $config['0530_058f'][] = array('upper' => 1337, 'status' => 'C', 'lower' => array(1385)); /* ARMENIAN CAPITAL LETTER TO */ $config['0530_058f'][] = array('upper' => 1338, 'status' => 'C', 'lower' => array(1386)); /* ARMENIAN CAPITAL LETTER ZHE */ $config['0530_058f'][] = array('upper' => 1339, 'status' => 'C', 'lower' => array(1387)); /* ARMENIAN CAPITAL LETTER INI */ $config['0530_058f'][] = array('upper' => 1340, 'status' => 'C', 'lower' => array(1388)); /* ARMENIAN CAPITAL LETTER LIWN */ $config['0530_058f'][] = array('upper' => 1341, 'status' => 'C', 'lower' => array(1389)); /* ARMENIAN CAPITAL LETTER XEH */ $config['0530_058f'][] = array('upper' => 1342, 'status' => 'C', 'lower' => array(1390)); /* ARMENIAN CAPITAL LETTER CA */ $config['0530_058f'][] = array('upper' => 1343, 'status' => 'C', 'lower' => array(1391)); /* ARMENIAN CAPITAL LETTER KEN */ $config['0530_058f'][] = array('upper' => 1344, 'status' => 'C', 'lower' => array(1392)); /* ARMENIAN CAPITAL LETTER HO */ $config['0530_058f'][] = array('upper' => 1345, 'status' => 'C', 'lower' => array(1393)); /* ARMENIAN CAPITAL LETTER JA */ $config['0530_058f'][] = array('upper' => 1346, 'status' => 'C', 'lower' => array(1394)); /* ARMENIAN CAPITAL LETTER GHAD */ $config['0530_058f'][] = array('upper' => 1347, 'status' => 'C', 'lower' => array(1395)); /* ARMENIAN CAPITAL LETTER CHEH */ $config['0530_058f'][] = array('upper' => 1348, 'status' => 'C', 'lower' => array(1396)); /* ARMENIAN CAPITAL LETTER MEN */ $config['0530_058f'][] = array('upper' => 1349, 'status' => 'C', 'lower' => array(1397)); /* ARMENIAN CAPITAL LETTER YI */ $config['0530_058f'][] = array('upper' => 1350, 'status' => 'C', 'lower' => array(1398)); /* ARMENIAN CAPITAL LETTER NOW */ $config['0530_058f'][] = array('upper' => 1351, 'status' => 'C', 'lower' => array(1399)); /* ARMENIAN CAPITAL LETTER SHA */ $config['0530_058f'][] = array('upper' => 1352, 'status' => 'C', 'lower' => array(1400)); /* ARMENIAN CAPITAL LETTER VO */ $config['0530_058f'][] = array('upper' => 1353, 'status' => 'C', 'lower' => array(1401)); /* ARMENIAN CAPITAL LETTER CHA */ $config['0530_058f'][] = array('upper' => 1354, 'status' => 'C', 'lower' => array(1402)); /* ARMENIAN CAPITAL LETTER PEH */ $config['0530_058f'][] = array('upper' => 1355, 'status' => 'C', 'lower' => array(1403)); /* ARMENIAN CAPITAL LETTER JHEH */ $config['0530_058f'][] = array('upper' => 1356, 'status' => 'C', 'lower' => array(1404)); /* ARMENIAN CAPITAL LETTER RA */ $config['0530_058f'][] = array('upper' => 1357, 'status' => 'C', 'lower' => array(1405)); /* ARMENIAN CAPITAL LETTER SEH */ $config['0530_058f'][] = array('upper' => 1358, 'status' => 'C', 'lower' => array(1406)); /* ARMENIAN CAPITAL LETTER VEW */ $config['0530_058f'][] = array('upper' => 1359, 'status' => 'C', 'lower' => array(1407)); /* ARMENIAN CAPITAL LETTER TIWN */ $config['0530_058f'][] = array('upper' => 1360, 'status' => 'C', 'lower' => array(1408)); /* ARMENIAN CAPITAL LETTER REH */ $config['0530_058f'][] = array('upper' => 1361, 'status' => 'C', 'lower' => array(1409)); /* ARMENIAN CAPITAL LETTER CO */ $config['0530_058f'][] = array('upper' => 1362, 'status' => 'C', 'lower' => array(1410)); /* ARMENIAN CAPITAL LETTER YIWN */ $config['0530_058f'][] = array('upper' => 1363, 'status' => 'C', 'lower' => array(1411)); /* ARMENIAN CAPITAL LETTER PIWR */ $config['0530_058f'][] = array('upper' => 1364, 'status' => 'C', 'lower' => array(1412)); /* ARMENIAN CAPITAL LETTER KEH */ $config['0530_058f'][] = array('upper' => 1365, 'status' => 'C', 'lower' => array(1413)); /* ARMENIAN CAPITAL LETTER OH */ $config['0530_058f'][] = array('upper' => 1366, 'status' => 'C', 'lower' => array(1414)); /* ARMENIAN CAPITAL LETTER FEH */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/0530_058f.php
PHP
gpl3
6,542
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+0080 through U+00FF * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['0080_00ff'][] = array('upper' => 181, 'status' => 'C', 'lower' => array(956)); $config['0080_00ff'][] = array('upper' => 924, 'status' => 'C', 'lower' => array(181)); $config['0080_00ff'][] = array('upper' => 192, 'status' => 'C', 'lower' => array(224)); /* LATIN CAPITAL LETTER A WITH GRAVE */ $config['0080_00ff'][] = array('upper' => 193, 'status' => 'C', 'lower' => array(225)); /* LATIN CAPITAL LETTER A WITH ACUTE */ $config['0080_00ff'][] = array('upper' => 194, 'status' => 'C', 'lower' => array(226)); /* LATIN CAPITAL LETTER A WITH CIRCUMFLEX */ $config['0080_00ff'][] = array('upper' => 195, 'status' => 'C', 'lower' => array(227)); /* LATIN CAPITAL LETTER A WITH TILDE */ $config['0080_00ff'][] = array('upper' => 196, 'status' => 'C', 'lower' => array(228)); /* LATIN CAPITAL LETTER A WITH DIAERESIS */ $config['0080_00ff'][] = array('upper' => 197, 'status' => 'C', 'lower' => array(229)); /* LATIN CAPITAL LETTER A WITH RING ABOVE */ $config['0080_00ff'][] = array('upper' => 198, 'status' => 'C', 'lower' => array(230)); /* LATIN CAPITAL LETTER AE */ $config['0080_00ff'][] = array('upper' => 199, 'status' => 'C', 'lower' => array(231)); /* LATIN CAPITAL LETTER C WITH CEDILLA */ $config['0080_00ff'][] = array('upper' => 200, 'status' => 'C', 'lower' => array(232)); /* LATIN CAPITAL LETTER E WITH GRAVE */ $config['0080_00ff'][] = array('upper' => 201, 'status' => 'C', 'lower' => array(233)); /* LATIN CAPITAL LETTER E WITH ACUTE */ $config['0080_00ff'][] = array('upper' => 202, 'status' => 'C', 'lower' => array(234)); /* LATIN CAPITAL LETTER E WITH CIRCUMFLEX */ $config['0080_00ff'][] = array('upper' => 203, 'status' => 'C', 'lower' => array(235)); /* LATIN CAPITAL LETTER E WITH DIAERESIS */ $config['0080_00ff'][] = array('upper' => 204, 'status' => 'C', 'lower' => array(236)); /* LATIN CAPITAL LETTER I WITH GRAVE */ $config['0080_00ff'][] = array('upper' => 205, 'status' => 'C', 'lower' => array(237)); /* LATIN CAPITAL LETTER I WITH ACUTE */ $config['0080_00ff'][] = array('upper' => 206, 'status' => 'C', 'lower' => array(238)); /* LATIN CAPITAL LETTER I WITH CIRCUMFLEX */ $config['0080_00ff'][] = array('upper' => 207, 'status' => 'C', 'lower' => array(239)); /* LATIN CAPITAL LETTER I WITH DIAERESIS */ $config['0080_00ff'][] = array('upper' => 208, 'status' => 'C', 'lower' => array(240)); /* LATIN CAPITAL LETTER ETH */ $config['0080_00ff'][] = array('upper' => 209, 'status' => 'C', 'lower' => array(241)); /* LATIN CAPITAL LETTER N WITH TILDE */ $config['0080_00ff'][] = array('upper' => 210, 'status' => 'C', 'lower' => array(242)); /* LATIN CAPITAL LETTER O WITH GRAVE */ $config['0080_00ff'][] = array('upper' => 211, 'status' => 'C', 'lower' => array(243)); /* LATIN CAPITAL LETTER O WITH ACUTE */ $config['0080_00ff'][] = array('upper' => 212, 'status' => 'C', 'lower' => array(244)); /* LATIN CAPITAL LETTER O WITH CIRCUMFLEX */ $config['0080_00ff'][] = array('upper' => 213, 'status' => 'C', 'lower' => array(245)); /* LATIN CAPITAL LETTER O WITH TILDE */ $config['0080_00ff'][] = array('upper' => 214, 'status' => 'C', 'lower' => array(246)); /* LATIN CAPITAL LETTER O WITH DIAERESIS */ $config['0080_00ff'][] = array('upper' => 216, 'status' => 'C', 'lower' => array(248)); /* LATIN CAPITAL LETTER O WITH STROKE */ $config['0080_00ff'][] = array('upper' => 217, 'status' => 'C', 'lower' => array(249)); /* LATIN CAPITAL LETTER U WITH GRAVE */ $config['0080_00ff'][] = array('upper' => 218, 'status' => 'C', 'lower' => array(250)); /* LATIN CAPITAL LETTER U WITH ACUTE */ $config['0080_00ff'][] = array('upper' => 219, 'status' => 'C', 'lower' => array(251)); /* LATIN CAPITAL LETTER U WITH CIRCUMFLEX */ $config['0080_00ff'][] = array('upper' => 220, 'status' => 'C', 'lower' => array(252)); /* LATIN CAPITAL LETTER U WITH DIAERESIS */ $config['0080_00ff'][] = array('upper' => 221, 'status' => 'C', 'lower' => array(253)); /* LATIN CAPITAL LETTER Y WITH ACUTE */ $config['0080_00ff'][] = array('upper' => 222, 'status' => 'C', 'lower' => array(254)); /* LATIN CAPITAL LETTER THORN */ $config['0080_00ff'][] = array('upper' => 223, 'status' => 'F', 'lower' => array(115, 115)); /* LATIN SMALL LETTER SHARP S */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/0080_00ff.php
PHP
gpl3
6,005
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+2C00 through U+2C5F * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['2c00_2c5f'][] = array('upper' => 11264, 'status' => 'C', 'lower' => array(11312)); /* GLAGOLITIC CAPITAL LETTER AZU */ $config['2c00_2c5f'][] = array('upper' => 11265, 'status' => 'C', 'lower' => array(11313)); /* GLAGOLITIC CAPITAL LETTER BUKY */ $config['2c00_2c5f'][] = array('upper' => 11266, 'status' => 'C', 'lower' => array(11314)); /* GLAGOLITIC CAPITAL LETTER VEDE */ $config['2c00_2c5f'][] = array('upper' => 11267, 'status' => 'C', 'lower' => array(11315)); /* GLAGOLITIC CAPITAL LETTER GLAGOLI */ $config['2c00_2c5f'][] = array('upper' => 11268, 'status' => 'C', 'lower' => array(11316)); /* GLAGOLITIC CAPITAL LETTER DOBRO */ $config['2c00_2c5f'][] = array('upper' => 11269, 'status' => 'C', 'lower' => array(11317)); /* GLAGOLITIC CAPITAL LETTER YESTU */ $config['2c00_2c5f'][] = array('upper' => 11270, 'status' => 'C', 'lower' => array(11318)); /* GLAGOLITIC CAPITAL LETTER ZHIVETE */ $config['2c00_2c5f'][] = array('upper' => 11271, 'status' => 'C', 'lower' => array(11319)); /* GLAGOLITIC CAPITAL LETTER DZELO */ $config['2c00_2c5f'][] = array('upper' => 11272, 'status' => 'C', 'lower' => array(11320)); /* GLAGOLITIC CAPITAL LETTER ZEMLJA */ $config['2c00_2c5f'][] = array('upper' => 11273, 'status' => 'C', 'lower' => array(11321)); /* GLAGOLITIC CAPITAL LETTER IZHE */ $config['2c00_2c5f'][] = array('upper' => 11274, 'status' => 'C', 'lower' => array(11322)); /* GLAGOLITIC CAPITAL LETTER INITIAL IZHE */ $config['2c00_2c5f'][] = array('upper' => 11275, 'status' => 'C', 'lower' => array(11323)); /* GLAGOLITIC CAPITAL LETTER I */ $config['2c00_2c5f'][] = array('upper' => 11276, 'status' => 'C', 'lower' => array(11324)); /* GLAGOLITIC CAPITAL LETTER DJERVI */ $config['2c00_2c5f'][] = array('upper' => 11277, 'status' => 'C', 'lower' => array(11325)); /* GLAGOLITIC CAPITAL LETTER KAKO */ $config['2c00_2c5f'][] = array('upper' => 11278, 'status' => 'C', 'lower' => array(11326)); /* GLAGOLITIC CAPITAL LETTER LJUDIJE */ $config['2c00_2c5f'][] = array('upper' => 11279, 'status' => 'C', 'lower' => array(11327)); /* GLAGOLITIC CAPITAL LETTER MYSLITE */ $config['2c00_2c5f'][] = array('upper' => 11280, 'status' => 'C', 'lower' => array(11328)); /* GLAGOLITIC CAPITAL LETTER NASHI */ $config['2c00_2c5f'][] = array('upper' => 11281, 'status' => 'C', 'lower' => array(11329)); /* GLAGOLITIC CAPITAL LETTER ONU */ $config['2c00_2c5f'][] = array('upper' => 11282, 'status' => 'C', 'lower' => array(11330)); /* GLAGOLITIC CAPITAL LETTER POKOJI */ $config['2c00_2c5f'][] = array('upper' => 11283, 'status' => 'C', 'lower' => array(11331)); /* GLAGOLITIC CAPITAL LETTER RITSI */ $config['2c00_2c5f'][] = array('upper' => 11284, 'status' => 'C', 'lower' => array(11332)); /* GLAGOLITIC CAPITAL LETTER SLOVO */ $config['2c00_2c5f'][] = array('upper' => 11285, 'status' => 'C', 'lower' => array(11333)); /* GLAGOLITIC CAPITAL LETTER TVRIDO */ $config['2c00_2c5f'][] = array('upper' => 11286, 'status' => 'C', 'lower' => array(11334)); /* GLAGOLITIC CAPITAL LETTER UKU */ $config['2c00_2c5f'][] = array('upper' => 11287, 'status' => 'C', 'lower' => array(11335)); /* GLAGOLITIC CAPITAL LETTER FRITU */ $config['2c00_2c5f'][] = array('upper' => 11288, 'status' => 'C', 'lower' => array(11336)); /* GLAGOLITIC CAPITAL LETTER HERU */ $config['2c00_2c5f'][] = array('upper' => 11289, 'status' => 'C', 'lower' => array(11337)); /* GLAGOLITIC CAPITAL LETTER OTU */ $config['2c00_2c5f'][] = array('upper' => 11290, 'status' => 'C', 'lower' => array(11338)); /* GLAGOLITIC CAPITAL LETTER PE */ $config['2c00_2c5f'][] = array('upper' => 11291, 'status' => 'C', 'lower' => array(11339)); /* GLAGOLITIC CAPITAL LETTER SHTA */ $config['2c00_2c5f'][] = array('upper' => 11292, 'status' => 'C', 'lower' => array(11340)); /* GLAGOLITIC CAPITAL LETTER TSI */ $config['2c00_2c5f'][] = array('upper' => 11293, 'status' => 'C', 'lower' => array(11341)); /* GLAGOLITIC CAPITAL LETTER CHRIVI */ $config['2c00_2c5f'][] = array('upper' => 11294, 'status' => 'C', 'lower' => array(11342)); /* GLAGOLITIC CAPITAL LETTER SHA */ $config['2c00_2c5f'][] = array('upper' => 11295, 'status' => 'C', 'lower' => array(11343)); /* GLAGOLITIC CAPITAL LETTER YERU */ $config['2c00_2c5f'][] = array('upper' => 11296, 'status' => 'C', 'lower' => array(11344)); /* GLAGOLITIC CAPITAL LETTER YERI */ $config['2c00_2c5f'][] = array('upper' => 11297, 'status' => 'C', 'lower' => array(11345)); /* GLAGOLITIC CAPITAL LETTER YATI */ $config['2c00_2c5f'][] = array('upper' => 11298, 'status' => 'C', 'lower' => array(11346)); /* GLAGOLITIC CAPITAL LETTER SPIDERY HA */ $config['2c00_2c5f'][] = array('upper' => 11299, 'status' => 'C', 'lower' => array(11347)); /* GLAGOLITIC CAPITAL LETTER YU */ $config['2c00_2c5f'][] = array('upper' => 11300, 'status' => 'C', 'lower' => array(11348)); /* GLAGOLITIC CAPITAL LETTER SMALL YUS */ $config['2c00_2c5f'][] = array('upper' => 11301, 'status' => 'C', 'lower' => array(11349)); /* GLAGOLITIC CAPITAL LETTER SMALL YUS WITH TAIL */ $config['2c00_2c5f'][] = array('upper' => 11302, 'status' => 'C', 'lower' => array(11350)); /* GLAGOLITIC CAPITAL LETTER YO */ $config['2c00_2c5f'][] = array('upper' => 11303, 'status' => 'C', 'lower' => array(11351)); /* GLAGOLITIC CAPITAL LETTER IOTATED SMALL YUS */ $config['2c00_2c5f'][] = array('upper' => 11304, 'status' => 'C', 'lower' => array(11352)); /* GLAGOLITIC CAPITAL LETTER BIG YUS */ $config['2c00_2c5f'][] = array('upper' => 11305, 'status' => 'C', 'lower' => array(11353)); /* GLAGOLITIC CAPITAL LETTER IOTATED BIG YUS */ $config['2c00_2c5f'][] = array('upper' => 11306, 'status' => 'C', 'lower' => array(11354)); /* GLAGOLITIC CAPITAL LETTER FITA */ $config['2c00_2c5f'][] = array('upper' => 11307, 'status' => 'C', 'lower' => array(11355)); /* GLAGOLITIC CAPITAL LETTER IZHITSA */ $config['2c00_2c5f'][] = array('upper' => 11308, 'status' => 'C', 'lower' => array(11356)); /* GLAGOLITIC CAPITAL LETTER SHTAPIC */ $config['2c00_2c5f'][] = array('upper' => 11309, 'status' => 'C', 'lower' => array(11357)); /* GLAGOLITIC CAPITAL LETTER TROKUTASTI A */ $config['2c00_2c5f'][] = array('upper' => 11310, 'status' => 'C', 'lower' => array(11358)); /* GLAGOLITIC CAPITAL LETTER LATINATE MYSLITE */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/2c00_2c5f.php
PHP
gpl3
8,000
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+2150 through U+218F * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['2150_218f'][] = array('upper' => 8544, 'status' => 'C', 'lower' => array(8560)); /* ROMAN NUMERAL ONE */ $config['2150_218f'][] = array('upper' => 8545, 'status' => 'C', 'lower' => array(8561)); /* ROMAN NUMERAL TWO */ $config['2150_218f'][] = array('upper' => 8546, 'status' => 'C', 'lower' => array(8562)); /* ROMAN NUMERAL THREE */ $config['2150_218f'][] = array('upper' => 8547, 'status' => 'C', 'lower' => array(8563)); /* ROMAN NUMERAL FOUR */ $config['2150_218f'][] = array('upper' => 8548, 'status' => 'C', 'lower' => array(8564)); /* ROMAN NUMERAL FIVE */ $config['2150_218f'][] = array('upper' => 8549, 'status' => 'C', 'lower' => array(8565)); /* ROMAN NUMERAL SIX */ $config['2150_218f'][] = array('upper' => 8550, 'status' => 'C', 'lower' => array(8566)); /* ROMAN NUMERAL SEVEN */ $config['2150_218f'][] = array('upper' => 8551, 'status' => 'C', 'lower' => array(8567)); /* ROMAN NUMERAL EIGHT */ $config['2150_218f'][] = array('upper' => 8552, 'status' => 'C', 'lower' => array(8568)); /* ROMAN NUMERAL NINE */ $config['2150_218f'][] = array('upper' => 8553, 'status' => 'C', 'lower' => array(8569)); /* ROMAN NUMERAL TEN */ $config['2150_218f'][] = array('upper' => 8554, 'status' => 'C', 'lower' => array(8570)); /* ROMAN NUMERAL ELEVEN */ $config['2150_218f'][] = array('upper' => 8555, 'status' => 'C', 'lower' => array(8571)); /* ROMAN NUMERAL TWELVE */ $config['2150_218f'][] = array('upper' => 8556, 'status' => 'C', 'lower' => array(8572)); /* ROMAN NUMERAL FIFTY */ $config['2150_218f'][] = array('upper' => 8557, 'status' => 'C', 'lower' => array(8573)); /* ROMAN NUMERAL ONE HUNDRED */ $config['2150_218f'][] = array('upper' => 8558, 'status' => 'C', 'lower' => array(8574)); /* ROMAN NUMERAL FIVE HUNDRED */ $config['2150_218f'][] = array('upper' => 8559, 'status' => 'C', 'lower' => array(8575)); /* ROMAN NUMERAL ONE THOUSAND */ $config['2150_218f'][] = array('upper' => 8579, 'status' => 'C', 'lower' => array(8580)); /* ROMAN NUMERAL REVERSED ONE HUNDRED */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/2150_218f.php
PHP
gpl3
3,834
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+0080 through U+00FF * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.6833 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['0250_02af'][] = array('upper' => 422, 'status' => 'C', 'lower' => array(640));
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/0250_02af.php
PHP
gpl3
1,924
<?php /** * Case Folding Properties. * * Provides case mapping of Unicode characters for code points U+0370 through U+03FF * * @see http://www.unicode.org/Public/UNIDATA/UCD.html * @see http://www.unicode.org/Public/UNIDATA/CaseFolding.txt * @see http://www.unicode.org/reports/tr21/tr21-5.html * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Config.unicode.casefolding * @since CakePHP(tm) v 1.2.0.5691 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * The upper field is the decimal value of the upper case character * * The lower filed is an array of the decimal values that form the lower case version of a character. * * The status field is: * C: common case folding, common mappings shared by both simple and full mappings. * F: full case folding, mappings that cause strings to grow in length. Multiple characters are separated by spaces. * S: simple case folding, mappings to single characters where different from F. * T: special case for uppercase I and dotted uppercase I * - For non-Turkic languages, this mapping is normally not used. * - For Turkic languages (tr, az), this mapping can be used instead of the normal mapping for these characters. * Note that the Turkic mappings do not maintain canonical equivalence without additional processing. * See the discussions of case mapping in the Unicode Standard for more information. */ $config['0370_03ff'][] = array('upper' => 902, 'status' => 'C', 'lower' => array(940)); /* GREEK CAPITAL LETTER ALPHA WITH TONOS */ $config['0370_03ff'][] = array('upper' => 904, 'status' => 'C', 'lower' => array(941)); /* GREEK CAPITAL LETTER EPSILON WITH TONOS */ $config['0370_03ff'][] = array('upper' => 905, 'status' => 'C', 'lower' => array(942)); /* GREEK CAPITAL LETTER ETA WITH TONOS */ $config['0370_03ff'][] = array('upper' => 906, 'status' => 'C', 'lower' => array(943)); /* GREEK CAPITAL LETTER IOTA WITH TONOS */ $config['0370_03ff'][] = array('upper' => 908, 'status' => 'C', 'lower' => array(972)); /* GREEK CAPITAL LETTER OMICRON WITH TONOS */ $config['0370_03ff'][] = array('upper' => 910, 'status' => 'C', 'lower' => array(973)); /* GREEK CAPITAL LETTER UPSILON WITH TONOS */ $config['0370_03ff'][] = array('upper' => 911, 'status' => 'C', 'lower' => array(974)); /* GREEK CAPITAL LETTER OMEGA WITH TONOS */ //$config['0370_03ff'][] = array('upper' => 912, 'status' => 'F', 'lower' => array(953, 776, 769)); /* GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS */ $config['0370_03ff'][] = array('upper' => 913, 'status' => 'C', 'lower' => array(945)); /* GREEK CAPITAL LETTER ALPHA */ $config['0370_03ff'][] = array('upper' => 914, 'status' => 'C', 'lower' => array(946)); /* GREEK CAPITAL LETTER BETA */ $config['0370_03ff'][] = array('upper' => 915, 'status' => 'C', 'lower' => array(947)); /* GREEK CAPITAL LETTER GAMMA */ $config['0370_03ff'][] = array('upper' => 916, 'status' => 'C', 'lower' => array(948)); /* GREEK CAPITAL LETTER DELTA */ $config['0370_03ff'][] = array('upper' => 917, 'status' => 'C', 'lower' => array(949)); /* GREEK CAPITAL LETTER EPSILON */ $config['0370_03ff'][] = array('upper' => 918, 'status' => 'C', 'lower' => array(950)); /* GREEK CAPITAL LETTER ZETA */ $config['0370_03ff'][] = array('upper' => 919, 'status' => 'C', 'lower' => array(951)); /* GREEK CAPITAL LETTER ETA */ $config['0370_03ff'][] = array('upper' => 920, 'status' => 'C', 'lower' => array(952)); /* GREEK CAPITAL LETTER THETA */ $config['0370_03ff'][] = array('upper' => 921, 'status' => 'C', 'lower' => array(953)); /* GREEK CAPITAL LETTER IOTA */ $config['0370_03ff'][] = array('upper' => 922, 'status' => 'C', 'lower' => array(954)); /* GREEK CAPITAL LETTER KAPPA */ $config['0370_03ff'][] = array('upper' => 923, 'status' => 'C', 'lower' => array(955)); /* GREEK CAPITAL LETTER LAMDA */ $config['0370_03ff'][] = array('upper' => 924, 'status' => 'C', 'lower' => array(956)); /* GREEK CAPITAL LETTER MU */ $config['0370_03ff'][] = array('upper' => 925, 'status' => 'C', 'lower' => array(957)); /* GREEK CAPITAL LETTER NU */ $config['0370_03ff'][] = array('upper' => 926, 'status' => 'C', 'lower' => array(958)); /* GREEK CAPITAL LETTER XI */ $config['0370_03ff'][] = array('upper' => 927, 'status' => 'C', 'lower' => array(959)); /* GREEK CAPITAL LETTER OMICRON */ $config['0370_03ff'][] = array('upper' => 928, 'status' => 'C', 'lower' => array(960)); /* GREEK CAPITAL LETTER PI */ $config['0370_03ff'][] = array('upper' => 929, 'status' => 'C', 'lower' => array(961)); /* GREEK CAPITAL LETTER RHO */ $config['0370_03ff'][] = array('upper' => 931, 'status' => 'C', 'lower' => array(963)); /* GREEK CAPITAL LETTER SIGMA */ $config['0370_03ff'][] = array('upper' => 932, 'status' => 'C', 'lower' => array(964)); /* GREEK CAPITAL LETTER TAU */ $config['0370_03ff'][] = array('upper' => 933, 'status' => 'C', 'lower' => array(965)); /* GREEK CAPITAL LETTER UPSILON */ $config['0370_03ff'][] = array('upper' => 934, 'status' => 'C', 'lower' => array(966)); /* GREEK CAPITAL LETTER PHI */ $config['0370_03ff'][] = array('upper' => 935, 'status' => 'C', 'lower' => array(967)); /* GREEK CAPITAL LETTER CHI */ $config['0370_03ff'][] = array('upper' => 936, 'status' => 'C', 'lower' => array(968)); /* GREEK CAPITAL LETTER PSI */ $config['0370_03ff'][] = array('upper' => 937, 'status' => 'C', 'lower' => array(969)); /* GREEK CAPITAL LETTER OMEGA */ $config['0370_03ff'][] = array('upper' => 938, 'status' => 'C', 'lower' => array(970)); /* GREEK CAPITAL LETTER IOTA WITH DIALYTIKA */ $config['0370_03ff'][] = array('upper' => 939, 'status' => 'C', 'lower' => array(971)); /* GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA */ $config['0370_03ff'][] = array('upper' => 944, 'status' => 'F', 'lower' => array(965, 776, 769)); /* GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS */ $config['0370_03ff'][] = array('upper' => 962, 'status' => 'C', 'lower' => array(963)); /* GREEK SMALL LETTER FINAL SIGMA */ $config['0370_03ff'][] = array('upper' => 976, 'status' => 'C', 'lower' => array(946)); /* GREEK BETA SYMBOL */ $config['0370_03ff'][] = array('upper' => 977, 'status' => 'C', 'lower' => array(952)); /* GREEK THETA SYMBOL */ $config['0370_03ff'][] = array('upper' => 981, 'status' => 'C', 'lower' => array(966)); /* GREEK PHI SYMBOL */ $config['0370_03ff'][] = array('upper' => 982, 'status' => 'C', 'lower' => array(960)); /* GREEK PI SYMBOL */ $config['0370_03ff'][] = array('upper' => 984, 'status' => 'C', 'lower' => array(985)); /* GREEK LETTER ARCHAIC KOPPA */ $config['0370_03ff'][] = array('upper' => 986, 'status' => 'C', 'lower' => array(987)); /* GREEK LETTER STIGMA */ $config['0370_03ff'][] = array('upper' => 988, 'status' => 'C', 'lower' => array(989)); /* GREEK LETTER DIGAMMA */ $config['0370_03ff'][] = array('upper' => 990, 'status' => 'C', 'lower' => array(991)); /* GREEK LETTER KOPPA */ $config['0370_03ff'][] = array('upper' => 992, 'status' => 'C', 'lower' => array(993)); /* GREEK LETTER SAMPI */ $config['0370_03ff'][] = array('upper' => 994, 'status' => 'C', 'lower' => array(995)); /* COPTIC CAPITAL LETTER SHEI */ $config['0370_03ff'][] = array('upper' => 996, 'status' => 'C', 'lower' => array(997)); /* COPTIC CAPITAL LETTER FEI */ $config['0370_03ff'][] = array('upper' => 998, 'status' => 'C', 'lower' => array(999)); /* COPTIC CAPITAL LETTER KHEI */ $config['0370_03ff'][] = array('upper' => 1000, 'status' => 'C', 'lower' => array(1001)); /* COPTIC CAPITAL LETTER HORI */ $config['0370_03ff'][] = array('upper' => 1002, 'status' => 'C', 'lower' => array(1003)); /* COPTIC CAPITAL LETTER GANGIA */ $config['0370_03ff'][] = array('upper' => 1004, 'status' => 'C', 'lower' => array(1005)); /* COPTIC CAPITAL LETTER SHIMA */ $config['0370_03ff'][] = array('upper' => 1006, 'status' => 'C', 'lower' => array(1007)); /* COPTIC CAPITAL LETTER DEI */ $config['0370_03ff'][] = array('upper' => 1008, 'status' => 'C', 'lower' => array(954)); /* GREEK KAPPA SYMBOL */ $config['0370_03ff'][] = array('upper' => 1009, 'status' => 'C', 'lower' => array(961)); /* GREEK RHO SYMBOL */ $config['0370_03ff'][] = array('upper' => 1012, 'status' => 'C', 'lower' => array(952)); /* GREEK CAPITAL THETA SYMBOL */ $config['0370_03ff'][] = array('upper' => 1013, 'status' => 'C', 'lower' => array(949)); /* GREEK LUNATE EPSILON SYMBOL */ $config['0370_03ff'][] = array('upper' => 1015, 'status' => 'C', 'lower' => array(1016)); /* GREEK CAPITAL LETTER SHO */ $config['0370_03ff'][] = array('upper' => 1017, 'status' => 'C', 'lower' => array(1010)); /* GREEK CAPITAL LUNATE SIGMA SYMBOL */ $config['0370_03ff'][] = array('upper' => 1018, 'status' => 'C', 'lower' => array(1019)); /* GREEK CAPITAL LETTER SAN */ $config['0370_03ff'][] = array('upper' => 1021, 'status' => 'C', 'lower' => array(891)); /* GREEK CAPITAL REVERSED LUNATE SIGMA SYMBOL */ $config['0370_03ff'][] = array('upper' => 1022, 'status' => 'C', 'lower' => array(892)); /* GREEK CAPITAL DOTTED LUNATE SIGMA SYMBOL */ $config['0370_03ff'][] = array('upper' => 1023, 'status' => 'C', 'lower' => array(893)); /* GREEK CAPITAL REVERSED DOTTED LUNATE SIGMA SYMBOL */
0001-bee
trunk/cakephp2/lib/Cake/Config/unicode/casefolding/0370_03ff.php
PHP
gpl3
9,495
<?php /** * Parses the request URL into controller, action, and parameters. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Routing * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('CakeRequest', 'Network'); App::uses('CakeRoute', 'Routing/Route'); /** * Parses the request URL into controller, action, and parameters. Uses the connected routes * to match the incoming url string to parameters that will allow the request to be dispatched. Also * handles converting parameter lists into url strings, using the connected routes. Routing allows you to decouple * the way the world interacts with your application (urls) and the implementation (controllers and actions). * * ### Connecting routes * * Connecting routes is done using Router::connect(). When parsing incoming requests or reverse matching * parameters, routes are enumerated in the order they were connected. You can modify the order of connected * routes using Router::promote(). For more information on routes and how to connect them see Router::connect(). * * ### Named parameters * * Named parameters allow you to embed key:value pairs into path segments. This allows you create hash * structures using urls. You can define how named parameters work in your application using Router::connectNamed() * * @package Cake.Routing */ class Router { /** * Array of routes connected with Router::connect() * * @var array */ public static $routes = array(); /** * List of action prefixes used in connected routes. * Includes admin prefix * * @var array */ protected static $_prefixes = array(); /** * Directive for Router to parse out file extensions for mapping to Content-types. * * @var boolean */ protected static $_parseExtensions = false; /** * List of valid extensions to parse from a URL. If null, any extension is allowed. * * @var array */ protected static $_validExtensions = array(); /** * 'Constant' regular expression definitions for named route elements * */ const ACTION = 'index|show|add|create|edit|update|remove|del|delete|view|item'; const YEAR = '[12][0-9]{3}'; const MONTH = '0[1-9]|1[012]'; const DAY = '0[1-9]|[12][0-9]|3[01]'; const ID = '[0-9]+'; const UUID = '[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}'; /** * Named expressions * * @var array */ protected static $_namedExpressions = array( 'Action' => Router::ACTION, 'Year' => Router::YEAR, 'Month' => Router::MONTH, 'Day' => Router::DAY, 'ID' => Router::ID, 'UUID' => Router::UUID ); /** * Stores all information necessary to decide what named arguments are parsed under what conditions. * * @var string */ protected static $_namedConfig = array( 'default' => array('page', 'fields', 'order', 'limit', 'recursive', 'sort', 'direction', 'step'), 'greedyNamed' => true, 'separator' => ':', 'rules' => false, ); /** * The route matching the URL of the current request * * @var array */ protected static $_currentRoute = array(); /** * Default HTTP request method => controller action map. * * @var array */ protected static $_resourceMap = array( array('action' => 'index', 'method' => 'GET', 'id' => false), array('action' => 'view', 'method' => 'GET', 'id' => true), array('action' => 'add', 'method' => 'POST', 'id' => false), array('action' => 'edit', 'method' => 'PUT', 'id' => true), array('action' => 'delete', 'method' => 'DELETE', 'id' => true), array('action' => 'edit', 'method' => 'POST', 'id' => true) ); /** * List of resource-mapped controllers * * @var array */ protected static $_resourceMapped = array(); /** * Maintains the request object stack for the current request. * This will contain more than one request object when requestAction is used. * * @var array */ protected static $_requests = array(); /** * Initial state is popualated the first time reload() is called which is at the bottom * of this file. This is a cheat as get_class_vars() returns the value of static vars even if they * have changed. * * @var array */ protected static $_initialState = array(); /** * Sets the Routing prefixes. * * @return void */ protected static function _setPrefixes() { $routing = Configure::read('Routing'); if (!empty($routing['prefixes'])) { self::$_prefixes = array_merge(self::$_prefixes, (array)$routing['prefixes']); } } /** * Gets the named route elements for use in app/Config/routes.php * * @return array Named route elements * @see Router::$_namedExpressions */ public static function getNamedExpressions() { return self::$_namedExpressions; } /** * Connects a new Route in the router. * * Routes are a way of connecting request urls to objects in your application. At their core routes * are a set or regular expressions that are used to match requests to destinations. * * Examples: * * `Router::connect('/:controller/:action/*');` * * The first parameter will be used as a controller name while the second is used as the action name. * the '/*' syntax makes this route greedy in that it will match requests like `/posts/index` as well as requests * like `/posts/edit/1/foo/bar`. * * `Router::connect('/home-page', array('controller' => 'pages', 'action' => 'display', 'home'));` * * The above shows the use of route parameter defaults. And providing routing parameters for a static route. * * {{{ * Router::connect( * '/:lang/:controller/:action/:id', * array(), * array('id' => '[0-9]+', 'lang' => '[a-z]{3}') * ); * }}} * * Shows connecting a route with custom route parameters as well as providing patterns for those parameters. * Patterns for routing parameters do not need capturing groups, as one will be added for each route params. * * $options offers four 'special' keys. `pass`, `named`, `persist` and `routeClass` * have special meaning in the $options array. * * `pass` is used to define which of the routed parameters should be shifted into the pass array. Adding a * parameter to pass will remove it from the regular route array. Ex. `'pass' => array('slug')` * * `persist` is used to define which route parameters should be automatically included when generating * new urls. You can override persistent parameters by redefining them in a url or remove them by * setting the parameter to `false`. Ex. `'persist' => array('lang')` * * `routeClass` is used to extend and change how individual routes parse requests and handle reverse routing, * via a custom routing class. Ex. `'routeClass' => 'SlugRoute'` * * `named` is used to configure named parameters at the route level. This key uses the same options * as Router::connectNamed() * * @param string $route A string describing the template of the route * @param array $defaults An array describing the default route parameters. These parameters will be used by default * and can supply routing parameters that are not dynamic. See above. * @param array $options An array matching the named elements in the route to regular expressions which that * element should match. Also contains additional parameters such as which routed parameters should be * shifted into the passed arguments, supplying patterns for routing parameters and supplying the name of a * custom routing class. * @see routes * @return array Array of routes * @throws RouterException */ public static function connect($route, $defaults = array(), $options = array()) { foreach (self::$_prefixes as $prefix) { if (isset($defaults[$prefix])) { $defaults['prefix'] = $prefix; break; } } if (isset($defaults['prefix'])) { self::$_prefixes[] = $defaults['prefix']; self::$_prefixes = array_keys(array_flip(self::$_prefixes)); } $defaults += array('plugin' => null); if (empty($options['action'])) { $defaults += array('action' => 'index'); } $routeClass = 'CakeRoute'; if (isset($options['routeClass'])) { $routeClass = $options['routeClass']; if (!is_subclass_of($routeClass, 'CakeRoute')) { throw new RouterException(__d('cake_dev', 'Route classes must extend CakeRoute')); } unset($options['routeClass']); if ($routeClass == 'RedirectRoute' && isset($defaults['redirect'])) { $defaults = $defaults['redirect']; } } self::$routes[] = new $routeClass($route, $defaults, $options); return self::$routes; } /** * Connects a new redirection Route in the router. * * Redirection routes are different from normal routes as they perform an actual * header redirection if a match is found. The redirection can occur within your * application or redirect to an outside location. * * Examples: * * `Router::redirect('/home/*', array('controller' => 'posts', 'action' => 'view', array('persist' => true));` * * Redirects /home/* to /posts/view and passes the parameters to /posts/view. Using an array as the * redirect destination allows you to use other routes to define where a url string should be redirected to. * * `Router::redirect('/posts/*', 'http://google.com', array('status' => 302));` * * Redirects /posts/* to http://google.com with a HTTP status of 302 * * ### Options: * * - `status` Sets the HTTP status (default 301) * - `persist` Passes the params to the redirected route, if it can. This is useful with greedy routes, * routes that end in `*` are greedy. As you can remap urls and not loose any passed/named args. * * @param string $route A string describing the template of the route * @param array $url A url to redirect to. Can be a string or a Cake array-based url * @param array $options An array matching the named elements in the route to regular expressions which that * element should match. Also contains additional parameters such as which routed parameters should be * shifted into the passed arguments. As well as supplying patterns for routing parameters. * @see routes * @return array Array of routes */ public static function redirect($route, $url, $options = array()) { App::uses('RedirectRoute', 'Routing/Route'); $options['routeClass'] = 'RedirectRoute'; if (is_string($url)) { $url = array('redirect' => $url); } return self::connect($route, $url, $options); } /** * Specifies what named parameters CakePHP should be parsing out of incoming urls. By default * CakePHP will parse every named parameter out of incoming URLs. However, if you want to take more * control over how named parameters are parsed you can use one of the following setups: * * Do not parse any named parameters: * * {{{ Router::connectNamed(false); }}} * * Parse only default parameters used for CakePHP's pagination: * * {{{ Router::connectNamed(false, array('default' => true)); }}} * * Parse only the page parameter if its value is a number: * * {{{ Router::connectNamed(array('page' => '[\d]+'), array('default' => false, 'greedy' => false)); }}} * * Parse only the page parameter no matter what. * * {{{ Router::connectNamed(array('page'), array('default' => false, 'greedy' => false)); }}} * * Parse only the page parameter if the current action is 'index'. * * {{{ * Router::connectNamed( * array('page' => array('action' => 'index')), * array('default' => false, 'greedy' => false) * ); * }}} * * Parse only the page parameter if the current action is 'index' and the controller is 'pages'. * * {{{ * Router::connectNamed( * array('page' => array('action' => 'index', 'controller' => 'pages')), * array('default' => false, 'greedy' => false) * ); * }}} * * ### Options * * - `greedy` Setting this to true will make Router parse all named params. Setting it to false will * parse only the connected named params. * - `default` Set this to true to merge in the default set of named parameters. * - `reset` Set to true to clear existing rules and start fresh. * - `separator` Change the string used to separate the key & value in a named parameter. Defaults to `:` * * @param array $named A list of named parameters. Key value pairs are accepted where values are * either regex strings to match, or arrays as seen above. * @param array $options Allows to control all settings: separator, greedy, reset, default * @return array */ public static function connectNamed($named, $options = array()) { if (isset($options['separator'])) { self::$_namedConfig['separator'] = $options['separator']; unset($options['separator']); } if ($named === true || $named === false) { $options = array_merge(array('default' => $named, 'reset' => true, 'greedy' => $named), $options); $named = array(); } else { $options = array_merge(array('default' => false, 'reset' => false, 'greedy' => true), $options); } if ($options['reset'] == true || self::$_namedConfig['rules'] === false) { self::$_namedConfig['rules'] = array(); } if ($options['default']) { $named = array_merge($named, self::$_namedConfig['default']); } foreach ($named as $key => $val) { if (is_numeric($key)) { self::$_namedConfig['rules'][$val] = true; } else { self::$_namedConfig['rules'][$key] = $val; } } self::$_namedConfig['greedyNamed'] = $options['greedy']; return self::$_namedConfig; } /** * Gets the current named parameter configuration values. * * @return array * @see Router::$_namedConfig */ public static function namedConfig() { return self::$_namedConfig; } /** * Creates REST resource routes for the given controller(s). When creating resource routes * for a plugin, by default the prefix will be changed to the lower_underscore version of the plugin * name. By providing a prefix you can override this behavior. * * ### Options: * * - 'id' - The regular expression fragment to use when matching IDs. By default, matches * integer values and UUIDs. * - 'prefix' - URL prefix to use for the generated routes. Defaults to '/'. * * @param mixed $controller A controller name or array of controller names (i.e. "Posts" or "ListItems") * @param array $options Options to use when generating REST routes * @return array Array of mapped resources */ public static function mapResources($controller, $options = array()) { $hasPrefix = isset($options['prefix']); $options = array_merge(array( 'prefix' => '/', 'id' => self::ID . '|' . self::UUID ), $options); $prefix = $options['prefix']; foreach ((array)$controller as $name) { list($plugin, $name) = pluginSplit($name); $urlName = Inflector::underscore($name); $plugin = Inflector::underscore($plugin); if ($plugin && !$hasPrefix) { $prefix = '/' . $plugin . '/'; } foreach (self::$_resourceMap as $params) { $url = $prefix . $urlName . (($params['id']) ? '/:id' : ''); Router::connect($url, array( 'plugin' => $plugin, 'controller' => $urlName, 'action' => $params['action'], '[method]' => $params['method'] ), array('id' => $options['id'], 'pass' => array('id')) ); } self::$_resourceMapped[] = $urlName; } return self::$_resourceMapped; } /** * Returns the list of prefixes used in connected routes * * @return array A list of prefixes used in connected routes */ public static function prefixes() { return self::$_prefixes; } /** * Parses given URL string. Returns 'routing' parameters for that url. * * @param string $url URL to be parsed * @return array Parsed elements from URL */ public static function parse($url) { $ext = null; $out = array(); if ($url && strpos($url, '/') !== 0) { $url = '/' . $url; } if (strpos($url, '?') !== false) { $url = substr($url, 0, strpos($url, '?')); } extract(self::_parseExtension($url)); for ($i = 0, $len = count(self::$routes); $i < $len; $i++) { $route =& self::$routes[$i]; if (($r = $route->parse($url)) !== false) { self::$_currentRoute[] =& $route; $out = $r; break; } } if (isset($out['prefix'])) { $out['action'] = $out['prefix'] . '_' . $out['action']; } if (!empty($ext) && !isset($out['ext'])) { $out['ext'] = $ext; } return $out; } /** * Parses a file extension out of a URL, if Router::parseExtensions() is enabled. * * @param string $url * @return array Returns an array containing the altered URL and the parsed extension. */ protected static function _parseExtension($url) { $ext = null; if (self::$_parseExtensions) { if (preg_match('/\.[0-9a-zA-Z]*$/', $url, $match) === 1) { $match = substr($match[0], 1); if (empty(self::$_validExtensions)) { $url = substr($url, 0, strpos($url, '.' . $match)); $ext = $match; } else { foreach (self::$_validExtensions as $name) { if (strcasecmp($name, $match) === 0) { $url = substr($url, 0, strpos($url, '.' . $name)); $ext = $match; break; } } } } } return compact('ext', 'url'); } /** * Takes parameter and path information back from the Dispatcher, sets these * parameters as the current request parameters that are merged with url arrays * created later in the request. * * Nested requests will create a stack of requests. You can remove requests using * Router::popRequest(). This is done automatically when using Object::requestAction(). * * Will accept either a CakeRequest object or an array of arrays. Support for * accepting arrays may be removed in the future. * * @param CakeRequest|array $request Parameters and path information or a CakeRequest object. * @return void */ public static function setRequestInfo($request) { if ($request instanceof CakeRequest) { self::$_requests[] = $request; } else { $requestObj = new CakeRequest(); $request += array(array(), array()); $request[0] += array('controller' => false, 'action' => false, 'plugin' => null); $requestObj->addParams($request[0])->addPaths($request[1]); self::$_requests[] = $requestObj; } } /** * Pops a request off of the request stack. Used when doing requestAction * * @return CakeRequest The request removed from the stack. * @see Router::setRequestInfo() * @see Object::requestAction() */ public static function popRequest() { return array_pop(self::$_requests); } /** * Get the either the current request object, or the first one. * * @param boolean $current Whether you want the request from the top of the stack or the first one. * @return CakeRequest or null. */ public static function getRequest($current = false) { if ($current) { return self::$_requests[count(self::$_requests) - 1]; } return isset(self::$_requests[0]) ? self::$_requests[0] : null; } /** * Gets parameter information * * @param boolean $current Get current request parameter, useful when using requestAction * @return array Parameter information */ public static function getParams($current = false) { if ($current) { return self::$_requests[count(self::$_requests) - 1]->params; } if (isset(self::$_requests[0])) { return self::$_requests[0]->params; } return array(); } /** * Gets URL parameter by name * * @param string $name Parameter name * @param boolean $current Current parameter, useful when using requestAction * @return string Parameter value */ public static function getParam($name = 'controller', $current = false) { $params = Router::getParams($current); if (isset($params[$name])) { return $params[$name]; } return null; } /** * Gets path information * * @param boolean $current Current parameter, useful when using requestAction * @return array */ public static function getPaths($current = false) { if ($current) { return self::$_requests[count(self::$_requests) - 1]; } if (!isset(self::$_requests[0])) { return array('base' => null); } return array('base' => self::$_requests[0]->base); } /** * Reloads default Router settings. Resets all class variables and * removes all connected routes. * * @return void */ public static function reload() { if (empty(self::$_initialState)) { self::$_initialState = get_class_vars('Router'); self::_setPrefixes(); return; } foreach (self::$_initialState as $key => $val) { if ($key != '_initialState') { self::${$key} = $val; } } self::_setPrefixes(); } /** * Promote a route (by default, the last one added) to the beginning of the list * * @param integer $which A zero-based array index representing the route to move. For example, * if 3 routes have been added, the last route would be 2. * @return boolean Returns false if no route exists at the position specified by $which. */ public static function promote($which = null) { if ($which === null) { $which = count(self::$routes) - 1; } if (!isset(self::$routes[$which])) { return false; } $route =& self::$routes[$which]; unset(self::$routes[$which]); array_unshift(self::$routes, $route); return true; } /** * Finds URL for specified action. * * Returns an URL pointing to a combination of controller and action. Param * $url can be: * * - Empty - the method will find address to actual controller/action. * - '/' - the method will find base URL of application. * - A combination of controller/action - the method will find url for it. * * There are a few 'special' parameters that can change the final URL string that is generated * * - `base` - Set to false to remove the base path from the generated url. If your application * is not in the root directory, this can be used to generate urls that are 'cake relative'. * cake relative urls are required when using requestAction. * - `?` - Takes an array of query string parameters * - `#` - Allows you to set url hash fragments. * - `full_base` - If true the `FULL_BASE_URL` constant will be prepended to generated urls. * * @param mixed $url Cake-relative URL, like "/products/edit/92" or "/presidents/elect/4" * or an array specifying any of the following: 'controller', 'action', * and/or 'plugin', in addition to named arguments (keyed array elements), * and standard URL arguments (indexed array elements) * @param mixed $full If (bool) true, the full base URL will be prepended to the result. * If an array accepts the following keys * - escape - used when making urls embedded in html escapes query string '&' * - full - if true the full base URL will be prepended. * @return string Full translated URL with base path. */ public static function url($url = null, $full = false) { $params = array('plugin' => null, 'controller' => null, 'action' => 'index'); if (is_bool($full)) { $escape = false; } else { extract($full + array('escape' => false, 'full' => false)); } $path = array('base' => null); if (!empty(self::$_requests)) { $request = self::$_requests[count(self::$_requests) - 1]; $params = $request->params; $path = array('base' => $request->base, 'here' => $request->here); } $base = $path['base']; $extension = $output = $q = $frag = null; if (empty($url)) { $output = isset($path['here']) ? $path['here'] : '/'; if ($full && defined('FULL_BASE_URL')) { $output = FULL_BASE_URL . $output; } return $output; } elseif (is_array($url)) { if (isset($url['base']) && $url['base'] === false) { $base = null; unset($url['base']); } if (isset($url['full_base']) && $url['full_base'] === true) { $full = true; unset($url['full_base']); } if (isset($url['?'])) { $q = $url['?']; unset($url['?']); } if (isset($url['#'])) { $frag = '#' . urlencode($url['#']); unset($url['#']); } if (isset($url['ext'])) { $extension = '.' . $url['ext']; unset($url['ext']); } if (empty($url['action'])) { if (empty($url['controller']) || $params['controller'] === $url['controller']) { $url['action'] = $params['action']; } else { $url['action'] = 'index'; } } $prefixExists = (array_intersect_key($url, array_flip(self::$_prefixes))); foreach (self::$_prefixes as $prefix) { if (!empty($params[$prefix]) && !$prefixExists) { $url[$prefix] = true; } elseif (isset($url[$prefix]) && !$url[$prefix]) { unset($url[$prefix]); } if (isset($url[$prefix]) && strpos($url['action'], $prefix . '_') === 0) { $url['action'] = substr($url['action'], strlen($prefix) + 1); } } $url += array('controller' => $params['controller'], 'plugin' => $params['plugin']); $match = false; for ($i = 0, $len = count(self::$routes); $i < $len; $i++) { $originalUrl = $url; if (isset(self::$routes[$i]->options['persist'], $params)) { $url = self::$routes[$i]->persistParams($url, $params); } if ($match = self::$routes[$i]->match($url)) { $output = trim($match, '/'); break; } $url = $originalUrl; } if ($match === false) { $output = self::_handleNoRoute($url); } } else { if ( (strpos($url, '://') || (strpos($url, 'javascript:') === 0) || (strpos($url, 'mailto:') === 0)) || (!strncmp($url, '#', 1)) ) { return $url; } if (substr($url, 0, 1) === '/') { $output = substr($url, 1); } else { foreach (self::$_prefixes as $prefix) { if (isset($params[$prefix])) { $output .= $prefix . '/'; break; } } if (!empty($params['plugin']) && $params['plugin'] !== $params['controller']) { $output .= Inflector::underscore($params['plugin']) . '/'; } $output .= Inflector::underscore($params['controller']) . '/' . $url; } } $protocol = preg_match('#^[a-z][a-z0-9+-.]*\://#i', $output); if ($protocol === 0) { $output = str_replace('//', '/', $base . '/' . $output); if ($full && defined('FULL_BASE_URL')) { $output = FULL_BASE_URL . $output; } if (!empty($extension)) { $output = rtrim($output, '/'); } } return $output . $extension . self::queryString($q, array(), $escape) . $frag; } /** * A special fallback method that handles url arrays that cannot match * any defined routes. * * @param array $url A url that didn't match any routes * @return string A generated url for the array * @see Router::url() */ protected static function _handleNoRoute($url) { $named = $args = $query = array(); $skip = array_merge( array('bare', 'action', 'controller', 'plugin', 'prefix'), self::$_prefixes ); $keys = array_values(array_diff(array_keys($url), $skip)); $count = count($keys); // Remove this once parsed URL parameters can be inserted into 'pass' for ($i = 0; $i < $count; $i++) { $key = $keys[$i]; if (is_numeric($keys[$i])) { $args[] = $url[$key]; } else { $named[$key] = $url[$key]; } } list($args, $named) = array(Set::filter($args, true), Set::filter($named, true)); foreach (self::$_prefixes as $prefix) { if (!empty($url[$prefix])) { $url['action'] = str_replace($prefix . '_', '', $url['action']); break; } } if (empty($named) && empty($args) && empty($query) && (!isset($url['action']) || $url['action'] === 'index')) { $url['action'] = null; } $urlOut = array_filter(array($url['controller'], $url['action'])); if (isset($url['plugin'])) { array_unshift($urlOut, $url['plugin']); } foreach (self::$_prefixes as $prefix) { if (isset($url[$prefix])) { array_unshift($urlOut, $prefix); break; } } $output = implode('/', $urlOut); if (!empty($args)) { $output .= '/' . implode('/', $args); } if (!empty($named)) { foreach ($named as $name => $value) { if (is_array($value)) { $flattend = Set::flatten($value, ']['); foreach ($flattend as $namedKey => $namedValue) { $output .= '/' . $name . "[$namedKey]" . self::$_namedConfig['separator'] . $namedValue; } } else { $output .= '/' . $name . self::$_namedConfig['separator'] . $value; } } } if (!empty($query)) { $output .= Router::queryString($query); } return $output; } /** * Generates a well-formed querystring from $q * * @param string|array $q Query string Either a string of already compiled query string arguments or * an array of arguments to convert into a query string. * @param array $extra Extra querystring parameters. * @param boolean $escape Whether or not to use escaped & * @return array */ public static function queryString($q, $extra = array(), $escape = false) { if (empty($q) && empty($extra)) { return null; } $join = '&'; if ($escape === true) { $join = '&amp;'; } $out = ''; if (is_array($q)) { $q = array_merge($extra, $q); } else { $out = $q; $q = $extra; } $out .= http_build_query($q, null, $join); if (isset($out[0]) && $out[0] != '?') { $out = '?' . $out; } return $out; } /** * Reverses a parsed parameter array into a string. Works similarly to Router::url(), but * Since parsed URL's contain additional 'pass' and 'named' as well as 'url.url' keys. * Those keys need to be specially handled in order to reverse a params array into a string url. * * This will strip out 'autoRender', 'bare', 'requested', and 'return' param names as those * are used for CakePHP internals and should not normally be part of an output url. * * @param CakeRequest|array $params The params array or CakeRequest object that needs to be reversed. * @param boolean $full Set to true to include the full url including the protocol when reversing * the url. * @return string The string that is the reversed result of the array */ public static function reverse($params, $full = false) { if ($params instanceof CakeRequest) { $url = $params->query; $params = $params->params; } else { $url = $params['url']; } $pass = isset($params['pass']) ? $params['pass'] : array(); $named = isset($params['named']) ? $params['named'] : array(); unset( $params['pass'], $params['named'], $params['paging'], $params['models'], $params['url'], $url['url'], $params['autoRender'], $params['bare'], $params['requested'], $params['return'], $params['_Token'] ); $params = array_merge($params, $pass, $named); if (!empty($url)) { $params['?'] = $url; } return Router::url($params, $full); } /** * Normalizes a URL for purposes of comparison. Will strip the base path off * and replace any double /'s. It will not unify the casing and underscoring * of the input value. * * @param mixed $url URL to normalize Either an array or a string url. * @return string Normalized URL */ public static function normalize($url = '/') { if (is_array($url)) { $url = Router::url($url); } elseif (preg_match('/^[a-z\-]+:\/\//', $url)) { return $url; } $request = Router::getRequest(); if (!empty($request->base) && stristr($url, $request->base)) { $url = preg_replace('/^' . preg_quote($request->base, '/') . '/', '', $url, 1); } $url = '/' . $url; while (strpos($url, '//') !== false) { $url = str_replace('//', '/', $url); } $url = preg_replace('/(?:(\/$))/', '', $url); if (empty($url)) { return '/'; } return $url; } /** * Returns the route matching the current request URL. * * @return CakeRoute Matching route object. */ public static function &requestRoute() { return self::$_currentRoute[0]; } /** * Returns the route matching the current request (useful for requestAction traces) * * @return CakeRoute Matching route object. */ public static function &currentRoute() { return self::$_currentRoute[count(self::$_currentRoute) - 1]; } /** * Removes the plugin name from the base URL. * * @param string $base Base URL * @param string $plugin Plugin name * @return string base url with plugin name removed if present */ public static function stripPlugin($base, $plugin = null) { if ($plugin != null) { $base = preg_replace('/(?:' . $plugin . ')/', '', $base); $base = str_replace('//', '', $base); $pos1 = strrpos($base, '/'); $char = strlen($base) - 1; if ($pos1 === $char) { $base = substr($base, 0, $char); } } return $base; } /** * Instructs the router to parse out file extensions from the URL. For example, * http://example.com/posts.rss would yield an file extension of "rss". * The file extension itself is made available in the controller as * $this->params['url']['ext'], and is used by the RequestHandler component to * automatically switch to alternate layouts and templates, and load helpers * corresponding to the given content, i.e. RssHelper. * * A list of valid extension can be passed to this method, i.e. Router::parseExtensions('rss', 'xml'); * If no parameters are given, anything after the first . (dot) after the last / in the URL will be * parsed, excluding querystring parameters (i.e. ?q=...). * * @return void */ public static function parseExtensions() { self::$_parseExtensions = true; if (func_num_args() > 0) { self::$_validExtensions = func_get_args(); } } /** * Get the list of extensions that can be parsed by Router. To add more * extensions use Router::parseExtensions() * * @return array Array of extensions Router is configured to parse. */ public static function extensions() { return self::$_validExtensions; } } //Save the initial state Router::reload();
0001-bee
trunk/cakephp2/lib/Cake/Routing/Router.php
PHP
gpl3
33,681
<?php /** * Dispatcher takes the URL information, parses it for paramters and * tells the involved controllers what to do. * * This is the heart of Cake's operation. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Routing * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * List of helpers to include */ App::uses('Router', 'Routing'); App::uses('CakeRequest', 'Network'); App::uses('CakeResponse', 'Network'); App::uses('Controller', 'Controller'); App::uses('Scaffold', 'Controller'); App::uses('View', 'View'); App::uses('Debugger', 'Utility'); /** * Dispatcher converts Requests into controller actions. It uses the dispatched Request * to locate and load the correct controller. If found, the requested action is called on * the controller. * * @package Cake.Routing */ class Dispatcher { /** * Constructor. * * @param string $base The base directory for the application. Writes `App.base` to Configure. */ public function __construct($base = false) { if ($base !== false) { Configure::write('App.base', $base); } } /** * Dispatches and invokes given Request, handing over control to the involved controller. If the controller is set * to autoRender, via Controller::$autoRender, then Dispatcher will render the view. * * Actions in CakePHP can be any public method on a controller, that is not declared in Controller. If you * want controller methods to be public and in-accesible by URL, then prefix them with a `_`. * For example `public function _loadPosts() { }` would not be accessible via URL. Private and protected methods * are also not accessible via URL. * * If no controller of given name can be found, invoke() will throw an exception. * If the controller is found, and the action is not found an exception will be thrown. * * @param CakeRequest $request Request object to dispatch. * @param CakeResponse $response Response object to put the results of the dispatch into. * @param array $additionalParams Settings array ("bare", "return") which is melded with the GET and POST params * @return boolean Success * @throws MissingControllerException, MissingActionException, PrivateActionException if any of those error states * are encountered. */ public function dispatch(CakeRequest $request, CakeResponse $response, $additionalParams = array()) { if ($this->asset($request->url, $response) || $this->cached($request->here)) { return; } $request = $this->parseParams($request, $additionalParams); Router::setRequestInfo($request); $controller = $this->_getController($request, $response); if (!($controller instanceof Controller)) { throw new MissingControllerException(array( 'class' => Inflector::camelize($request->params['controller']) . 'Controller', 'plugin' => empty($request->params['plugin']) ? null : Inflector::camelize($request->params['plugin']) )); } return $this->_invoke($controller, $request, $response); } /** * Initializes the components and models a controller will be using. * Triggers the controller action, and invokes the rendering if Controller::$autoRender is true and echo's the output. * Otherwise the return value of the controller action are returned. * * @param Controller $controller Controller to invoke * @param CakeRequest $request The request object to invoke the controller for. * @param CakeResponse $response The response object to receive the output * @return void */ protected function _invoke(Controller $controller, CakeRequest $request, CakeResponse $response) { $controller->constructClasses(); $controller->startupProcess(); $render = true; $result = $controller->invokeAction($request); if ($result instanceof CakeResponse) { $render = false; $response = $result; } if ($render && $controller->autoRender) { $response = $controller->render(); } elseif ($response->body() === null) { $response->body($result); } $controller->shutdownProcess(); if (isset($request->params['return'])) { return $response->body(); } $response->send(); } /** * Applies Routing and additionalParameters to the request to be dispatched. * If Routes have not been loaded they will be loaded, and app/Config/routes.php will be run. * * @param CakeRequest $request CakeRequest object to mine for parameter information. * @param array $additionalParams An array of additional parameters to set to the request. * Useful when Object::requestAction() is involved * @return CakeRequest The request object with routing params set. */ public function parseParams(CakeRequest $request, $additionalParams = array()) { if (count(Router::$routes) == 0) { $namedExpressions = Router::getNamedExpressions(); extract($namedExpressions); $this->_loadRoutes(); } $params = Router::parse($request->url); $request->addParams($params); if (!empty($additionalParams)) { $request->addParams($additionalParams); } return $request; } /** * Get controller to use, either plugin controller or application controller * * @param CakeRequest $request Request object * @param CakeResponse $response Response for the controller. * @return mixed name of controller if not loaded, or object if loaded */ protected function _getController($request, $response) { $ctrlClass = $this->_loadController($request); if (!$ctrlClass) { return false; } $reflection = new ReflectionClass($ctrlClass); if ($reflection->isAbstract() || $reflection->isInterface()) { return false; } return $reflection->newInstance($request, $response); } /** * Load controller and return controller classname * * @param CakeRequest $request * @return string|bool Name of controller class name */ protected function _loadController($request) { $pluginName = $pluginPath = $controller = null; if (!empty($request->params['plugin'])) { $pluginName = $controller = Inflector::camelize($request->params['plugin']); $pluginPath = $pluginName . '.'; } if (!empty($request->params['controller'])) { $controller = Inflector::camelize($request->params['controller']); } if ($pluginPath . $controller) { $class = $controller . 'Controller'; App::uses('AppController', 'Controller'); App::uses($pluginName . 'AppController', $pluginPath . 'Controller'); App::uses($class, $pluginPath . 'Controller'); if (class_exists($class)) { return $class; } } return false; } /** * Loads route configuration * * @return void */ protected function _loadRoutes() { include APP . 'Config' . DS . 'routes.php'; } /** * Outputs cached dispatch view cache * * @param string $path Requested URL path * @return string|boolean False if is not cached or output */ public function cached($path) { if (Configure::read('Cache.check') === true) { if ($path == '/') { $path = 'home'; } $path = strtolower(Inflector::slug($path)); $filename = CACHE . 'views' . DS . $path . '.php'; if (!file_exists($filename)) { $filename = CACHE . 'views' . DS . $path . '_index.php'; } if (file_exists($filename)) { App::uses('ThemeView', 'View'); $controller = null; $view = new ThemeView($controller); return $view->renderCache($filename, microtime(true)); } } return false; } /** * Checks if a requested asset exists and sends it to the browser * * @param string $url Requested URL * @param CakeResponse $response The response object to put the file contents in. * @return boolean True on success if the asset file was found and sent */ public function asset($url, CakeResponse $response) { if (strpos($url, '..') !== false || strpos($url, '.') === false) { return false; } $filters = Configure::read('Asset.filter'); $isCss = ( strpos($url, 'ccss/') === 0 || preg_match('#^(theme/([^/]+)/ccss/)|(([^/]+)(?<!css)/ccss)/#i', $url) ); $isJs = ( strpos($url, 'cjs/') === 0 || preg_match('#^/((theme/[^/]+)/cjs/)|(([^/]+)(?<!js)/cjs)/#i', $url) ); if (($isCss && empty($filters['css'])) || ($isJs && empty($filters['js']))) { $response->statusCode(404); $response->send(); return true; } elseif ($isCss) { include WWW_ROOT . DS . $filters['css']; return true; } elseif ($isJs) { include WWW_ROOT . DS . $filters['js']; return true; } $pathSegments = explode('.', $url); $ext = array_pop($pathSegments); $parts = explode('/', $url); $assetFile = null; if ($parts[0] === 'theme') { $themeName = $parts[1]; unset($parts[0], $parts[1]); $fileFragment = implode(DS, $parts); $path = App::themePath($themeName) . 'webroot' . DS; if (file_exists($path . $fileFragment)) { $assetFile = $path . $fileFragment; } } else { $plugin = Inflector::camelize($parts[0]); if (CakePlugin::loaded($plugin)) { unset($parts[0]); $fileFragment = implode(DS, $parts); $pluginWebroot = CakePlugin::path($plugin) . 'webroot' . DS; if (file_exists($pluginWebroot . $fileFragment)) { $assetFile = $pluginWebroot . $fileFragment; } } } if ($assetFile !== null) { $this->_deliverAsset($response, $assetFile, $ext); return true; } return false; } /** * Sends an asset file to the client * * @param CakeResponse $response The response object to use. * @param string $assetFile Path to the asset file in the file system * @param string $ext The extension of the file to determine its mime type * @return void */ protected function _deliverAsset(CakeResponse $response, $assetFile, $ext) { ob_start(); $compressionEnabled = Configure::read('Asset.compress') && $response->compress(); if ($response->type($ext) == $ext) { $contentType = 'application/octet-stream'; $agent = env('HTTP_USER_AGENT'); if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent) || preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) { $contentType = 'application/octetstream'; } $response->type($contentType); } $response->cache(filemtime($assetFile)); $response->send(); ob_clean(); if ($ext === 'css' || $ext === 'js') { include($assetFile); } else { readfile($assetFile); } if ($compressionEnabled) { ob_end_flush(); } } }
0001-bee
trunk/cakephp2/lib/Cake/Routing/Dispatcher.php
PHP
gpl3
10,635
<?php App::uses('CakeResponse', 'Network'); App::uses('CakeRoute', 'Routing/Route'); /** * Redirect route will perform an immediate redirect. Redirect routes * are useful when you want to have Routing layer redirects occur in your * application, for when URLs move. * * PHP5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Routing.Route * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ class RedirectRoute extends CakeRoute { /** * A CakeResponse object * * @var CakeResponse */ public $response = null; /** * The location to redirect to. Either a string or a cake array url. * * @var mixed */ public $redirect; /** * Constructor * * @param string $template Template string with parameter placeholders * @param array $defaults Array of defaults for the route. * @param array $options Array of additional options for the Route */ public function __construct($template, $defaults = array(), $options = array()) { parent::__construct($template, $defaults, $options); $this->redirect = (array)$defaults; } /** * Parses a string url into an array. Parsed urls will result in an automatic * redirection * * @param string $url The url to parse * @return boolean False on failure */ public function parse($url) { $params = parent::parse($url); if (!$params) { return false; } if (!$this->response) { $this->response = new CakeResponse(); } $redirect = $this->redirect; if (count($this->redirect) == 1 && !isset($this->redirect['controller'])) { $redirect = $this->redirect[0]; } if (isset($this->options['persist']) && is_array($redirect)) { $redirect += array('named' => $params['named'], 'pass' => $params['pass'], 'url' => array()); $redirect = Router::reverse($redirect); } $status = 301; if (isset($this->options['status']) && ($this->options['status'] >= 300 && $this->options['status'] < 400)) { $status = $this->options['status']; } $this->response->header(array('Location' => Router::url($redirect, true))); $this->response->statusCode($status); $this->response->send(); } /** * There is no reverse routing redirection routes * * @param array $url Array of parameters to convert to a string. * @return mixed either false or a string url. */ public function match($url) { return false; } }
0001-bee
trunk/cakephp2/lib/Cake/Routing/Route/RedirectRoute.php
PHP
gpl3
2,755
<?php /** * A single Route used by the Router to connect requests to * parameter maps. * * Not normally created as a standalone. Use Router::connect() to create * Routes for your application. * * PHP5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Routing.Route * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ class CakeRoute { /** * An array of named segments in a Route. * `/:controller/:action/:id` has 3 key elements * * @var array */ public $keys = array(); /** * An array of additional parameters for the Route. * * @var array */ public $options = array(); /** * Default parameters for a Route * * @var array */ public $defaults = array(); /** * The routes template string. * * @var string */ public $template = null; /** * Is this route a greedy route? Greedy routes have a `/*` in their * template * * @var string */ protected $_greedy = false; /** * The compiled route regular expresssion * * @var string */ protected $_compiledRoute = null; /** * HTTP header shortcut map. Used for evaluating header-based route expressions. * * @var array */ protected $_headerMap = array( 'type' => 'content_type', 'method' => 'request_method', 'server' => 'server_name' ); /** * Constructor for a Route * * @param string $template Template string with parameter placeholders * @param array $defaults Array of defaults for the route. * @param array $options Array of additional options for the Route */ public function __construct($template, $defaults = array(), $options = array()) { $this->template = $template; $this->defaults = (array)$defaults; $this->options = (array)$options; } /** * Check if a Route has been compiled into a regular expression. * * @return boolean */ public function compiled() { return !empty($this->_compiledRoute); } /** * Compiles the route's regular expression. Modifies defaults property so all necessary keys are set * and populates $this->names with the named routing elements. * * @return array Returns a string regular expression of the compiled route. */ public function compile() { if ($this->compiled()) { return $this->_compiledRoute; } $this->_writeRoute(); return $this->_compiledRoute; } /** * Builds a route regular expression. Uses the template, defaults and options * properties to compile a regular expression that can be used to parse request strings. * * @return void */ protected function _writeRoute() { if (empty($this->template) || ($this->template === '/')) { $this->_compiledRoute = '#^/*$#'; $this->keys = array(); return; } $route = $this->template; $names = $routeParams = array(); $parsed = preg_quote($this->template, '#'); preg_match_all('#:([A-Za-z0-9_-]+[A-Z0-9a-z])#', $route, $namedElements); foreach ($namedElements[1] as $i => $name) { $search = '\\' . $namedElements[0][$i]; if (isset($this->options[$name])) { $option = null; if ($name !== 'plugin' && array_key_exists($name, $this->defaults)) { $option = '?'; } $slashParam = '/\\' . $namedElements[0][$i]; if (strpos($parsed, $slashParam) !== false) { $routeParams[$slashParam] = '(?:/(?P<' . $name . '>' . $this->options[$name] . ')' . $option . ')' . $option; } else { $routeParams[$search] = '(?:(?P<' . $name . '>' . $this->options[$name] . ')' . $option . ')' . $option; } } else { $routeParams[$search] = '(?:(?P<' . $name . '>[^/]+))'; } $names[] = $name; } if (preg_match('#\/\*$#', $route)) { $parsed = preg_replace('#/\\\\\*$#', '(?:/(?P<_args_>.*))?', $parsed); $this->_greedy = true; } krsort($routeParams); $parsed = str_replace(array_keys($routeParams), array_values($routeParams), $parsed); $this->_compiledRoute = '#^' . $parsed . '[/]*$#'; $this->keys = $names; //remove defaults that are also keys. They can cause match failures foreach ($this->keys as $key) { unset($this->defaults[$key]); } } /** * Checks to see if the given URL can be parsed by this route. * If the route can be parsed an array of parameters will be returned; if not * false will be returned. String urls are parsed if they match a routes regular expression. * * @param string $url The url to attempt to parse. * @return mixed Boolean false on failure, otherwise an array or parameters */ public function parse($url) { if (!$this->compiled()) { $this->compile(); } if (!preg_match($this->_compiledRoute, $url, $route)) { return false; } foreach ($this->defaults as $key => $val) { if ($key[0] === '[' && preg_match('/^\[(\w+)\]$/', $key, $header)) { if (isset($this->_headerMap[$header[1]])) { $header = $this->_headerMap[$header[1]]; } else { $header = 'http_' . $header[1]; } $header = strtoupper($header); $val = (array)$val; $h = false; foreach ($val as $v) { if (env($header) === $v) { $h = true; } } if (!$h) { return false; } } } array_shift($route); $count = count($this->keys); for ($i = 0; $i <= $count; $i++) { unset($route[$i]); } $route['pass'] = $route['named'] = array(); // Assign defaults, set passed args to pass foreach ($this->defaults as $key => $value) { if (isset($route[$key])) { continue; } if (is_integer($key)) { $route['pass'][] = $value; continue; } $route[$key] = $value; } if (isset($route['_args_'])) { list($pass, $named) = $this->_parseArgs($route['_args_'], $route); $route['pass'] = array_merge($route['pass'], $pass); $route['named'] = $named; unset($route['_args_']); } // restructure 'pass' key route params if (isset($this->options['pass'])) { $j = count($this->options['pass']); while($j--) { if (isset($route[$this->options['pass'][$j]])) { array_unshift($route['pass'], $route[$this->options['pass'][$j]]); } } } return $route; } /** * Parse passed and Named parameters into a list of passed args, and a hash of named parameters. * The local and global configuration for named parameters will be used. * * @param string $args A string with the passed & named params. eg. /1/page:2 * @param string $context The current route context, which should contain controller/action keys. * @return array Array of ($pass, $named) */ protected function _parseArgs($args, $context) { $pass = $named = array(); $args = explode('/', $args); $namedConfig = Router::namedConfig(); $greedy = $namedConfig['greedyNamed']; $rules = $namedConfig['rules']; if (!empty($this->options['named'])) { $greedy = isset($this->options['greedyNamed']) && $this->options['greedyNamed'] === true; foreach ((array)$this->options['named'] as $key => $val) { if (is_numeric($key)) { $rules[$val] = true; continue; } $rules[$key] = $val; } } foreach ($args as $param) { if (empty($param) && $param !== '0' && $param !== 0) { continue; } $separatorIsPresent = strpos($param, $namedConfig['separator']) !== false; if ((!isset($this->options['named']) || !empty($this->options['named'])) && $separatorIsPresent) { list($key, $val) = explode($namedConfig['separator'], $param, 2); $hasRule = isset($rules[$key]); $passIt = (!$hasRule && !$greedy) || ($hasRule && !$this->_matchNamed($val, $rules[$key], $context)); if ($passIt) { $pass[] = $param; } else { if (preg_match_all('/\[([A-Za-z0-9_-]+)?\]/', $key, $matches, PREG_SET_ORDER)) { $matches = array_reverse($matches); $parts = explode('[', $key); $key = array_shift($parts); $arr = $val; foreach ($matches as $match) { if (empty($match[1])) { $arr = array($arr); } else { $arr = array( $match[1] => $arr ); } } $val = $arr; } $named = array_merge_recursive($named, array($key => $val)); } } else { $pass[] = $param; } } return array($pass, $named); } /** * Return true if a given named $param's $val matches a given $rule depending on $context. Currently implemented * rule types are controller, action and match that can be combined with each other. * * @param string $val The value of the named parameter * @param array $rule The rule(s) to apply, can also be a match string * @param string $context An array with additional context information (controller / action) * @return boolean */ protected function _matchNamed($val, $rule, $context) { if ($rule === true || $rule === false) { return $rule; } if (is_string($rule)) { $rule = array('match' => $rule); } if (!is_array($rule)) { return false; } $controllerMatches = ( !isset($rule['controller'], $context['controller']) || in_array($context['controller'], (array)$rule['controller']) ); if (!$controllerMatches) { return false; } $actionMatches = ( !isset($rule['action'], $context['action']) || in_array($context['action'], (array)$rule['action']) ); if (!$actionMatches) { return false; } return (!isset($rule['match']) || preg_match('/' . $rule['match'] . '/', $val)); } /** * Apply persistent parameters to a url array. Persistant parameters are a special * key used during route creation to force route parameters to persist when omitted from * a url array. * * @param array $url The array to apply persistent parameters to. * @param array $params An array of persistent values to replace persistent ones. * @return array An array with persistent parameters applied. */ public function persistParams($url, $params) { foreach ($this->options['persist'] as $persistKey) { if (array_key_exists($persistKey, $params) && !isset($url[$persistKey])) { $url[$persistKey] = $params[$persistKey]; } } return $url; } /** * Attempt to match a url array. If the url matches the route parameters and settings, then * return a generated string url. If the url doesn't match the route parameters, false will be returned. * This method handles the reverse routing or conversion of url arrays into string urls. * * @param array $url An array of parameters to check matching with. * @return mixed Either a string url for the parameters if they match or false. */ public function match($url) { if (!$this->compiled()) { $this->compile(); } $defaults = $this->defaults; if (isset($defaults['prefix'])) { $url['prefix'] = $defaults['prefix']; } //check that all the key names are in the url $keyNames = array_flip($this->keys); if (array_intersect_key($keyNames, $url) !== $keyNames) { return false; } // Missing defaults is a fail. if (array_diff_key($defaults, $url) !== array()) { return false; } $namedConfig = Router::namedConfig(); $greedyNamed = $namedConfig['greedyNamed']; $allowedNamedParams = $namedConfig['rules']; $named = $pass = array(); foreach ($url as $key => $value) { // keys that exist in the defaults and have different values is a match failure. $defaultExists = array_key_exists($key, $defaults); if ($defaultExists && $defaults[$key] != $value) { return false; } elseif ($defaultExists) { continue; } // If the key is a routed key, its not different yet. if (array_key_exists($key, $keyNames)) { continue; } // pull out passed args $numeric = is_numeric($key); if ($numeric && isset($defaults[$key]) && $defaults[$key] == $value) { continue; } elseif ($numeric) { $pass[] = $value; unset($url[$key]); continue; } // pull out named params if named params are greedy or a rule exists. if ( ($greedyNamed || isset($allowedNamedParams[$key])) && ($value !== false && $value !== null) ) { $named[$key] = $value; continue; } // keys that don't exist are different. if (!$defaultExists && !empty($value)) { return false; } } //if a not a greedy route, no extra params are allowed. if (!$this->_greedy && (!empty($pass) || !empty($named))) { return false; } //check patterns for routed params if (!empty($this->options)) { foreach ($this->options as $key => $pattern) { if (array_key_exists($key, $url) && !preg_match('#^' . $pattern . '$#', $url[$key])) { return false; } } } return $this->_writeUrl(array_merge($url, compact('pass', 'named'))); } /** * Converts a matching route array into a url string. Composes the string url using the template * used to create the route. * * @param array $params The params to convert to a string url. * @return string Composed route string. */ protected function _writeUrl($params) { if (isset($params['prefix'], $params['action'])) { $params['action'] = str_replace($params['prefix'] . '_', '', $params['action']); unset($params['prefix']); } if (is_array($params['pass'])) { $params['pass'] = implode('/', $params['pass']); } $namedConfig = Router::namedConfig(); $separator = $namedConfig['separator']; if (!empty($params['named']) && is_array($params['named'])) { $named = array(); foreach ($params['named'] as $key => $value) { if (is_array($value)) { foreach ($value as $namedKey => $namedValue) { $named[] = $key . "[$namedKey]" . $separator . $namedValue; } } else { $named[] = $key . $separator . $value; } } $params['pass'] = $params['pass'] . '/' . implode('/', $named); } $out = $this->template; $search = $replace = array(); foreach ($this->keys as $key) { $string = null; if (isset($params[$key])) { $string = $params[$key]; } elseif (strpos($out, $key) != strlen($out) - strlen($key)) { $key .= '/'; } $search[] = ':' . $key; $replace[] = $string; } $out = str_replace($search, $replace, $out); if (strpos($this->template, '*')) { $out = str_replace('*', $params['pass'], $out); } $out = str_replace('//', '/', $out); return $out; } }
0001-bee
trunk/cakephp2/lib/Cake/Routing/Route/CakeRoute.php
PHP
gpl3
14,384
<?php App::uses('CakeRoute', 'Routing/Route'); /** * Plugin short route, that copies the plugin param to the controller parameters * It is used for supporting /:plugin routes. * * PHP5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Routing.Route * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ class PluginShortRoute extends CakeRoute { /** * Parses a string url into an array. If a plugin key is found, it will be copied to the * controller parameter * * @param string $url The url to parse * @return mixed false on failure, or an array of request parameters */ public function parse($url) { $params = parent::parse($url); if (!$params) { return false; } $params['controller'] = $params['plugin']; return $params; } /** * Reverse route plugin shortcut urls. If the plugin and controller * are not the same the match is an auto fail. * * @param array $url Array of parameters to convert to a string. * @return mixed either false or a string url. */ public function match($url) { if (isset($url['controller']) && isset($url['plugin']) && $url['plugin'] != $url['controller']) { return false; } $this->defaults['controller'] = $url['controller']; $result = parent::match($url); unset($this->defaults['controller']); return $result; } }
0001-bee
trunk/cakephp2/lib/Cake/Routing/Route/PluginShortRoute.php
PHP
gpl3
1,751
<?php /** * Configure class * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Core * @since CakePHP(tm) v 1.0.0.2363 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Set', 'Utility'); /** * Configuration class. Used for managing runtime configuration information. * * Provides features for reading and writing to the runtime configuration, as well * as methods for loading additional configuration files or storing runtime configuration * for future use. * * @package Cake.Core * @link http://book.cakephp.org/2.0/en/development/configuration.html#configure-class */ class Configure { /** * Array of values currently stored in Configure. * * @var array */ protected static $_values = array( 'debug' => 0 ); /** * Configured reader classes, used to load config files from resources * * @var array * @see Configure::load() */ protected static $_readers = array(); /** * Initializes configure and runs the bootstrap process. * Bootstrapping includes the following steps: * * - Setup App array in Configure. * - Include app/Config/core.php. * - Configure core cache configurations. * - Load App cache files. * - Include app/Config/bootstrap.php. * - Setup error/exception handlers. * * @param boolean $boot * @return void */ public static function bootstrap($boot = true) { if ($boot) { self::write('App', array( 'base' => false, 'baseUrl' => false, 'dir' => APP_DIR, 'webroot' => WEBROOT_DIR, 'www_root' => WWW_ROOT )); if (!include(APP . 'Config' . DS . 'core.php')) { trigger_error(__d('cake_dev', "Can't find application core file. Please create %score.php, and make sure it is readable by PHP.", APP . 'Config' . DS), E_USER_ERROR); } App::$bootstrapping = false; App::init(); App::build(); if (!include(APP . 'Config' . DS . 'bootstrap.php')) { trigger_error(__d('cake_dev', "Can't find application bootstrap file. Please create %sbootstrap.php, and make sure it is readable by PHP.", APP . 'Config' . DS), E_USER_ERROR); } $level = -1; if (isset(self::$_values['Error']['level'])) { error_reporting(self::$_values['Error']['level']); $level = self::$_values['Error']['level']; } if (!empty(self::$_values['Error']['handler'])) { set_error_handler(self::$_values['Error']['handler'], $level); } if (!empty(self::$_values['Exception']['handler'])) { set_exception_handler(self::$_values['Exception']['handler']); } } } /** * Used to store a dynamic variable in Configure. * * Usage: * {{{ * Configure::write('One.key1', 'value of the Configure::One[key1]'); * Configure::write(array('One.key1' => 'value of the Configure::One[key1]')); * Configure::write('One', array( * 'key1' => 'value of the Configure::One[key1]', * 'key2' => 'value of the Configure::One[key2]' * ); * * Configure::write(array( * 'One.key1' => 'value of the Configure::One[key1]', * 'One.key2' => 'value of the Configure::One[key2]' * )); * }}} * * @link http://book.cakephp.org/2.0/en/development/configuration.html#Configure::write * @param array $config Name of var to write * @param mixed $value Value to set for var * @return boolean True if write was successful */ public static function write($config, $value = null) { if (!is_array($config)) { $config = array($config => $value); } foreach ($config as $name => $value) { if (strpos($name, '.') === false) { self::$_values[$name] = $value; } else { $names = explode('.', $name, 4); switch (count($names)) { case 2: self::$_values[$names[0]][$names[1]] = $value; break; case 3: self::$_values[$names[0]][$names[1]][$names[2]] = $value; break; case 4: $names = explode('.', $name, 2); if (!isset(self::$_values[$names[0]])) { self::$_values[$names[0]] = array(); } self::$_values[$names[0]] = Set::insert(self::$_values[$names[0]], $names[1], $value); break; } } } if (isset($config['debug']) && function_exists('ini_set')) { if (self::$_values['debug']) { ini_set('display_errors', 1); } else { ini_set('display_errors', 0); } } return true; } /** * Used to read information stored in Configure. Its not * possible to store `null` values in Configure. * * Usage: * {{{ * Configure::read('Name'); will return all values for Name * Configure::read('Name.key'); will return only the value of Configure::Name[key] * }}} * * @linkhttp://book.cakephp.org/2.0/en/development/configuration.html#Configure::read * @param string $var Variable to obtain. Use '.' to access array elements. * @return mixed value stored in configure, or null. */ public static function read($var = null) { if ($var === null) { return self::$_values; } if (isset(self::$_values[$var])) { return self::$_values[$var]; } if (strpos($var, '.') !== false) { $names = explode('.', $var, 3); $var = $names[0]; } if (!isset(self::$_values[$var])) { return null; } switch (count($names)) { case 2: if (isset(self::$_values[$var][$names[1]])) { return self::$_values[$var][$names[1]]; } break; case 3: if (isset(self::$_values[$var][$names[1]][$names[2]])) { return self::$_values[$var][$names[1]][$names[2]]; } if (!isset(self::$_values[$var][$names[1]])) { return null; } return Set::classicExtract(self::$_values[$var][$names[1]], $names[2]); break; } return null; } /** * Used to delete a variable from Configure. * * Usage: * {{{ * Configure::delete('Name'); will delete the entire Configure::Name * Configure::delete('Name.key'); will delete only the Configure::Name[key] * }}} * * @link http://book.cakephp.org/2.0/en/development/configuration.html#Configure::delete * @param string $var the var to be deleted * @return void */ public static function delete($var = null) { if (strpos($var, '.') === false) { unset(self::$_values[$var]); return; } $names = explode('.', $var, 2); self::$_values[$names[0]] = Set::remove(self::$_values[$names[0]], $names[1]); } /** * Add a new reader to Configure. Readers allow you to read configuration * files in various formats/storage locations. CakePHP comes with two built-in readers * PhpReader and IniReader. You can also implement your own reader classes in your application. * * To add a new reader to Configure: * * `Configure::config('ini', new IniReader());` * * @param string $name The name of the reader being configured. This alias is used later to * read values from a specific reader. * @param ConfigReaderInterface $reader The reader to append. * @return void */ public static function config($name, ConfigReaderInterface $reader) { self::$_readers[$name] = $reader; } /** * Gets the names of the configured reader objects. * * @param string $name * @return array Array of the configured reader objects. */ public static function configured($name = null) { if ($name) { return isset(self::$_readers[$name]); } return array_keys(self::$_readers); } /** * Remove a configured reader. This will unset the reader * and make any future attempts to use it cause an Exception. * * @param string $name Name of the reader to drop. * @return boolean Success */ public static function drop($name) { if (!isset(self::$_readers[$name])) { return false; } unset(self::$_readers[$name]); return true; } /** * Loads stored configuration information from a resource. You can add * config file resource readers with `Configure::config()`. * * Loaded configuration information will be merged with the current * runtime configuration. You can load configuration files from plugins * by preceding the filename with the plugin name. * * `Configure::load('Users.user', 'default')` * * Would load the 'user' config file using the default config reader. You can load * app config files by giving the name of the resource you want loaded. * * `Configure::load('setup', 'default');` * * If using `default` config and no reader has been configured for it yet, * one will be automatically created using PhpReader * * @link http://book.cakephp.org/2.0/en/development/configuration.html#Configure::load * @param string $key name of configuration resource to load. * @param string $config Name of the configured reader to use to read the resource identified by $key. * @param boolean $merge if config files should be merged instead of simply overridden * @return mixed false if file not found, void if load successful. * @throws ConfigureException Will throw any exceptions the reader raises. */ public static function load($key, $config = 'default', $merge = true) { if (!isset(self::$_readers[$config])) { if ($config === 'default') { App::uses('PhpReader', 'Configure'); self::$_readers[$config] = new PhpReader(); } else { return false; } } $values = self::$_readers[$config]->read($key); if ($merge) { $keys = array_keys($values); foreach ($keys as $key) { if (($c = self::read($key)) && is_array($values[$key]) && is_array($c)) { $values[$key] = array_merge_recursive($c, $values[$key]); } } } return self::write($values); } /** * Used to determine the current version of CakePHP. * * Usage `Configure::version();` * * @return string Current version of CakePHP */ public static function version() { if (!isset(self::$_values['Cake']['version'])) { require CAKE . 'Config' . DS . 'config.php'; self::write($config); } return self::$_values['Cake']['version']; } /** * Used to write runtime configuration into Cache. Stored runtime configuration can be * restored using `Configure::restore()`. These methods can be used to enable configuration managers * frontends, or other GUI type interfaces for configuration. * * @param string $name The storage name for the saved configuration. * @param string $cacheConfig The cache configuration to save into. Defaults to 'default' * @param array $data Either an array of data to store, or leave empty to store all values. * @return boolean Success */ public static function store($name, $cacheConfig = 'default', $data = null) { if ($data === null) { $data = self::$_values; } return Cache::write($name, $data, $cacheConfig); } /** * Restores configuration data stored in the Cache into configure. Restored * values will overwrite existing ones. * * @param string $name Name of the stored config file to load. * @param string $cacheConfig Name of the Cache configuration to read from. * @return boolean Success. */ public static function restore($name, $cacheConfig = 'default') { $values = Cache::read($name, $cacheConfig); if ($values) { return self::write($values); } return false; } } /** * An interface for creating objects compatible with Configure::load() * * @package Cake.Core */ interface ConfigReaderInterface { /** * Read method is used for reading configuration information from sources. * These sources can either be static resources like files, or dynamic ones like * a database, or other datasource. * * @param string $key * @return array An array of data to merge into the runtime configuration */ public function read($key); }
0001-bee
trunk/cakephp2/lib/Cake/Core/Configure.php
PHP
gpl3
11,769
<?php /** * App class * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Core * @since CakePHP(tm) v 1.2.0.6001 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * App is responsible for path management, class location and class loading. * * ### Adding paths * * You can add paths to the search indexes App uses to find classes using `App::build()`. Adding * additional controller paths for example would alter where CakePHP looks for controllers. * This allows you to split your application up across the filesystem. * * ### Packages * * CakePHP is organized around the idea of packages, each class belongs to a package or folder where other * classes reside. You can configure each package location in your application using `App::build('APackage/SubPackage', $paths)` * to inform the framework where should each class be loaded. Almost every class in the CakePHP framework can be swapped * by your own compatible implementation. If you wish to use you own class instead of the classes the framework provides, * just add the class to your libs folder mocking the directory location of where CakePHP expects to find it. * * For instance if you'd like to use your own HttpSocket class, put it under * * app/Network/Http/HttpSocket.php * * ### Inspecting loaded paths * * You can inspect the currently loaded paths using `App::path('Controller')` for example to see loaded * controller paths. * * It is also possible to inspect paths for plugin classes, for instance, to see a plugin's helpers you would call * `App::path('View/Helper', 'MyPlugin')` * * ### Locating plugins and themes * * Plugins and Themes can be located with App as well. Using App::pluginPath('DebugKit') for example, will * give you the full path to the DebugKit plugin. App::themePath('purple'), would give the full path to the * `purple` theme. * * ### Inspecting known objects * * You can find out which objects App knows about using App::objects('Controller') for example to find * which application controllers App knows about. * * @link http://book.cakephp.org/2.0/en/core-utility-libraries/app.html * @package Cake.Core */ class App { /** * Append paths * * @constant APPEND */ const APPEND = 'append'; /** * Prepend paths * * @constant PREPEND */ const PREPEND = 'prepend'; /** * Reset paths instead of merging * * @constant RESET */ const RESET = true; /** * List of object types and their properties * * @var array */ public static $types = array( 'class' => array('extends' => null, 'core' => true), 'file' => array('extends' => null, 'core' => true), 'model' => array('extends' => 'AppModel', 'core' => false), 'behavior' => array('suffix' => 'Behavior', 'extends' => 'Model/ModelBehavior', 'core' => true), 'controller' => array('suffix' => 'Controller', 'extends' => 'AppController', 'core' => true), 'component' => array('suffix' => 'Component', 'extends' => null, 'core' => true), 'lib' => array('extends' => null, 'core' => true), 'view' => array('suffix' => 'View', 'extends' => null, 'core' => true), 'helper' => array('suffix' => 'Helper', 'extends' => 'AppHelper', 'core' => true), 'vendor' => array('extends' => null, 'core' => true), 'shell' => array('suffix' => 'Shell', 'extends' => 'Shell', 'core' => true), 'plugin' => array('extends' => null, 'core' => true) ); /** * Paths to search for files. * * @var array */ public static $search = array(); /** * Whether or not to return the file that is loaded. * * @var boolean */ public static $return = false; /** * Holds key/value pairs of $type => file path. * * @var array */ protected static $_map = array(); /** * Holds and key => value array of object types. * * @var array */ protected static $_objects = array(); /** * Holds the location of each class * * @var array */ protected static $_classMap = array(); /** * Holds the possible paths for each package name * * @var array */ protected static $_packages = array(); /** * Holds the templates for each customizable package path in the application * * @var array */ protected static $_packageFormat = array(); /** * Maps an old style CakePHP class type to the corresponding package * * @var array */ public static $legacy = array( 'models' => 'Model', 'behaviors' => 'Model/Behavior', 'datasources' => 'Model/Datasource', 'controllers' => 'Controller', 'components' => 'Controller/Component', 'views' => 'View', 'helpers' => 'View/Helper', 'shells' => 'Console/Command', 'libs' => 'Lib', 'vendors' => 'Vendor', 'plugins' => 'Plugin', ); /** * Indicates whether the class cache should be stored again because of an addition to it * * @var boolean */ protected static $_cacheChange = false; /** * Indicates whether the object cache should be stored again because of an addition to it * * @var boolean */ protected static $_objectCacheChange = false; /** * Indicates the the Application is in the bootstrapping process. Used to better cache * loaded classes while the cache libraries have not been yet initialized * * @var boolean */ public static $bootstrapping = false; /** * Used to read information stored path * * Usage: * * `App::path('Model'); will return all paths for models` * * `App::path('Model/Datasource', 'MyPlugin'); will return the path for datasources under the 'MyPlugin' plugin` * * @param string $type type of path * @param string $plugin name of plugin * @return string array */ public static function path($type, $plugin = null) { if (!empty(self::$legacy[$type])) { $type = self::$legacy[$type]; } if (!empty($plugin)) { $path = array(); $pluginPath = self::pluginPath($plugin); $packageFormat= self::_packageFormat(); if (!empty($packageFormat[$type])) { foreach ($packageFormat[$type] as $f) { $path[] = sprintf($f, $pluginPath); } } $path[] = $pluginPath . 'Lib' . DS . $type . DS; return $path; } if (!isset(self::$_packages[$type])) { return array(); } return self::$_packages[$type]; } /** * Get all the currently loaded paths from App. Useful for inspecting * or storing all paths App knows about. For a paths to a specific package * use App::path() * * @return array An array of packages and their associated paths. */ public static function paths() { return self::$_packages; } /** * Sets up each package location on the file system. You can configure multiple search paths * for each package, those will be used to look for files one folder at a time in the specified order * All paths should be terminated with a Directory separator * * Usage: * * `App::build(array(Model' => array('/a/full/path/to/models/'))); will setup a new search path for the Model package` * * `App::build(array('Model' => array('/path/to/models/')), App::RESET); will setup the path as the only valid path for searching models` * * `App::build(array('View/Helper' => array('/path/to/helpers/', '/another/path/'))); will setup multiple search paths for helpers` * * If reset is set to true, all loaded plugins will be forgotten and they will be needed to be loaded again. * * @param array $paths associative array with package names as keys and a list of directories for new search paths * @param mixed $mode App::RESET will set paths, App::APPEND with append paths, App::PREPEND will prepend paths, [default] App::PREPEND * @return void */ public static function build($paths = array(), $mode = App::PREPEND) { //Provides Backwards compatibility for old-style package names $legacyPaths = array(); foreach ($paths as $type => $path) { if (!empty(self::$legacy[$type])) { $type = self::$legacy[$type]; } $legacyPaths[$type] = $path; } $paths = $legacyPaths; if ($mode === App::RESET) { foreach ($paths as $type => $new) { self::$_packages[$type] = (array)$new; self::objects($type, null, false); } return; } $packageFormat = self::_packageFormat(); $defaults = array(); foreach ($packageFormat as $package => $format) { foreach ($format as $f) { $defaults[$package][] = sprintf($f, APP); } } if (empty($paths)) { self::$_packages = $defaults; return; } foreach ($defaults as $type => $default) { if (!empty(self::$_packages[$type])) { $path = self::$_packages[$type]; } if (!empty($paths[$type])) { $newPath = (array)$paths[$type]; if ($mode === App::PREPEND) { $path = array_merge($newPath, $path); } else { $path = array_merge($path, $newPath); } $path = array_values(array_unique($path)); } self::$_packages[$type] = $path; } } /** * Gets the path that a plugin is on. Searches through the defined plugin paths. * * Usage: * * `App::pluginPath('MyPlugin'); will return the full path to 'MyPlugin' plugin'` * * @param string $plugin CamelCased/lower_cased plugin name to find the path of. * @return string full path to the plugin. */ public static function pluginPath($plugin) { return CakePlugin::path($plugin); } /** * Finds the path that a theme is on. Searches through the defined theme paths. * * Usage: * * `App::themePath('MyTheme'); will return the full path to the 'MyTheme' theme` * * @param string $theme theme name to find the path of. * @return string full path to the theme. */ public static function themePath($theme) { $themeDir = 'Themed' . DS . Inflector::camelize($theme); foreach (self::$_packages['View'] as $path) { if (is_dir($path . $themeDir)) { return $path . $themeDir . DS ; } } return self::$_packages['View'][0] . $themeDir . DS; } /** * Returns the full path to a package inside the CakePHP core * * Usage: * * `App::core('Cache/Engine'); will return the full path to the cache engines package` * * @param string $type * @return string full path to package */ public static function core($type) { return array(CAKE . str_replace('/', DS, $type) . DS); } /** * Returns an array of objects of the given type. * * Example usage: * * `App::objects('plugin');` returns `array('DebugKit', 'Blog', 'User');` * * `App::objects('Controller');` returns `array('PagesController', 'BlogController');` * * You can also search only within a plugin's objects by using the plugin dot * syntax. * * `App::objects('MyPlugin.Model');` returns `array('MyPluginPost', 'MyPluginComment');` * * When scanning directories, files and directories beginning with `.` will be excluded as these * are commonly used by version control systems. * * @param string $type Type of object, i.e. 'Model', 'Controller', 'View/Helper', 'file', 'class' or 'plugin' * @param mixed $path Optional Scan only the path given. If null, paths for the chosen type will be used. * @param boolean $cache Set to false to rescan objects of the chosen type. Defaults to true. * @return mixed Either false on incorrect / miss. Or an array of found objects. */ public static function objects($type, $path = null, $cache = true) { $extension = '/\.php$/'; $includeDirectories = false; $name = $type; if ($type === 'plugin') { $type = 'plugins'; } if ($type == 'plugins') { $extension = '/.*/'; $includeDirectories = true; } list($plugin, $type) = pluginSplit($type); if (isset(self::$legacy[$type . 's'])) { $type = self::$legacy[$type . 's']; } if ($type === 'file' && !$path) { return false; } elseif ($type === 'file') { $extension = '/\.php$/'; $name = $type . str_replace(DS, '', $path); } if (empty(self::$_objects) && $cache === true) { self::$_objects = Cache::read('object_map', '_cake_core_'); } $cacheLocation = empty($plugin) ? 'app' : $plugin; if ($cache !== true || !isset(self::$_objects[$cacheLocation][$name])) { $objects = array(); if (empty($path)) { $path = self::path($type, $plugin); } foreach ((array)$path as $dir) { if ($dir != APP && is_dir($dir)) { $files = new RegexIterator(new DirectoryIterator($dir), $extension); foreach ($files as $file) { $fileName = basename($file); if (!$file->isDot() && $fileName[0] !== '.') { $isDir = $file->isDir() ; if ($isDir && $includeDirectories) { $objects[] = $fileName; } elseif (!$includeDirectories && !$isDir) { $objects[] = substr($fileName, 0, -4); } } } } } if ($type !== 'file') { foreach ($objects as $key => $value) { $objects[$key] = Inflector::camelize($value); } } sort($objects); if ($plugin) { return $objects; } self::$_objects[$cacheLocation][$name] = $objects; if ($cache) { self::$_objectCacheChange = true; } } return self::$_objects[$cacheLocation][$name]; } /** * Declares a package for a class. This package location will be used * by the automatic class loader if the class is tried to be used * * Usage: * * `App::uses('MyCustomController', 'Controller');` will setup the class to be found under Controller package * * `App::uses('MyHelper', 'MyPlugin.View/Helper');` will setup the helper class to be found in plugin's helper package * * @param string $className the name of the class to configure package for * @param string $location the package name * @return void */ public static function uses($className, $location) { self::$_classMap[$className] = $location; } /** * Method to handle the automatic class loading. It will look for each class' package * defined using App::uses() and with this information it will resolve the package name to a full path * to load the class from. File name for each class should follow the class name. For instance, * if a class is name `MyCustomClass` the file name should be `MyCustomClass.php` * * @param string $className the name of the class to load * @return boolean */ public static function load($className) { if (!isset(self::$_classMap[$className])) { return false; } if ($file = self::_mapped($className)) { return include $file; } $parts = explode('.', self::$_classMap[$className], 2); list($plugin, $package) = count($parts) > 1 ? $parts : array(null, current($parts)); $paths = self::path($package, $plugin); if (empty($plugin)) { $appLibs = empty(self::$_packages['Lib']) ? APPLIBS : current(self::$_packages['Lib']); $paths[] = $appLibs . $package . DS; $paths[] = CAKE . $package . DS; } foreach ($paths as $path) { $file = $path . $className . '.php'; if (file_exists($file)) { self::_map($file, $className); return include $file; } } //To help apps migrate to 2.0 old style file names are allowed foreach ($paths as $path) { $underscored = Inflector::underscore($className); $tries = array($path . $underscored . '.php'); $parts = explode('_', $underscored); if (count($parts) > 1) { array_pop($parts); $tries[] = $path . implode('_', $parts) . '.php'; } foreach ($tries as $file) { if (file_exists($file)) { self::_map($file, $className); return include $file; } } } return false; } /** * Returns the package name where a class was defined to be located at * * @param string $className name of the class to obtain the package name from * @return string package name or null if not declared */ public static function location($className) { if (!empty(self::$_classMap[$className])) { return self::$_classMap[$className]; } return null; } /** * Finds classes based on $name or specific file(s) to search. Calling App::import() will * not construct any classes contained in the files. It will only find and require() the file. * * @link http://book.cakephp.org/2.0/en/core-utility-libraries/app.html#including-files-with-app-import * @param mixed $type The type of Class if passed as a string, or all params can be passed as * an single array to $type, * @param string $name Name of the Class or a unique name for the file * @param mixed $parent boolean true if Class Parent should be searched, accepts key => value * array('parent' => $parent ,'file' => $file, 'search' => $search, 'ext' => '$ext'); * $ext allows setting the extension of the file name * based on Inflector::underscore($name) . ".$ext"; * @param array $search paths to search for files, array('path 1', 'path 2', 'path 3'); * @param string $file full name of the file to search for including extension * @param boolean $return, return the loaded file, the file must have a return * statement in it to work: return $variable; * @return boolean true if Class is already in memory or if file is found and loaded, false if not */ public static function import($type = null, $name = null, $parent = true, $search = array(), $file = null, $return = false) { $ext = null; if (is_array($type)) { extract($type, EXTR_OVERWRITE); } if (is_array($parent)) { extract($parent, EXTR_OVERWRITE); } if ($name == null && $file == null) { return false; } if (is_array($name)) { foreach ($name as $class) { if (!App::import(compact('type', 'parent', 'search', 'file', 'return') + array('name' => $class))) { return false; } } return true; } $originalType = strtolower($type); $specialPackage = in_array($originalType, array('file', 'vendor')); if (!$specialPackage && isset(self::$legacy[$originalType . 's'])) { $type = self::$legacy[$originalType . 's']; } list($plugin, $name) = pluginSplit($name); if (!empty($plugin)) { if (!CakePlugin::loaded($plugin)) { return false; } } if (!$specialPackage) { return self::_loadClass($name, $plugin, $type, $originalType, $parent); } if ($originalType == 'file' && !empty($file)) { return self::_loadFile($name, $plugin, $search, $file, $return); } if ($originalType == 'vendor') { return self::_loadVendor($name, $plugin, $file, $ext); } return false; } /** * Helper function to include classes * This is a compatibility wrapper around using App::uses() and automatic class loading * * @param string $name unique name of the file for identifying it inside the application * @param string $plugin camel cased plugin name if any * @param string $type name of the packed where the class is located * @param string $originalType type name as supplied initially by the user * @param boolean $parent whether to load the class parent or not * @return boolean true indicating the successful load and existence of the class */ protected static function _loadClass($name, $plugin, $type, $originalType, $parent) { if ($type == 'Console/Command' && $name == 'Shell') { $type = 'Console'; } else if (isset(self::$types[$originalType]['suffix'])) { $suffix = self::$types[$originalType]['suffix']; $name .= ($suffix == $name) ? '' : $suffix; } if ($parent && isset(self::$types[$originalType]['extends'])) { $extends = self::$types[$originalType]['extends']; $extendType = $type; if (strpos($extends, '/') !== false) { $parts = explode('/', $extends); $extends = array_pop($parts); $extendType = implode('/', $parts); } App::uses($extends, $extendType); if ($plugin && in_array($originalType, array('controller', 'model'))) { App::uses($plugin . $extends, $plugin . '.' .$type); } } if ($plugin) { $plugin .= '.'; } $name = Inflector::camelize($name); App::uses($name, $plugin . $type); return class_exists($name); } /** * Helper function to include single files * * @param string $name unique name of the file for identifying it inside the application * @param string $plugin camel cased plugin name if any * @param array $search list of paths to search the file into * @param string $file filename if known, the $name param will be used otherwise * @param boolean $return whether this function should return the contents of the file after being parsed by php or just a success notice * @return mixed if $return contents of the file after php parses it, boolean indicating success otherwise */ protected function _loadFile($name, $plugin, $search, $file, $return) { $mapped = self::_mapped($name, $plugin); if ($mapped) { $file = $mapped; } else if (!empty($search)) { foreach ($search as $path) { $found = false; if (file_exists($path . $file)) { $file = $path . $file; $found = true; break; } if (empty($found)) { $file = false; } } } if (!empty($file) && file_exists($file)) { self::_map($file, $name, $plugin); $returnValue = include $file; if ($return) { return $returnValue; } return (bool) $returnValue; } return false; } /** * Helper function to load files from vendors folders * * @param string $name unique name of the file for identifying it inside the application * @param string $plugin camel cased plugin name if any * @param string $file file name if known * @param string $ext file extension if known * @return boolean true if the file was loaded successfully, false otherwise */ protected function _loadVendor($name, $plugin, $file, $ext) { if ($mapped = self::_mapped($name, $plugin)) { return (bool) include_once($mapped); } $fileTries = array(); $paths = ($plugin) ? App::path('vendors', $plugin) : App::path('vendors'); if (empty($ext)) { $ext = 'php'; } if (empty($file)) { $fileTries[] = $name . '.' . $ext; $fileTries[] = Inflector::underscore($name) . '.' . $ext; } else { $fileTries[] = $file; } foreach ($fileTries as $file) { foreach ($paths as $path) { if (file_exists($path . $file)) { self::_map($path . $file, $name, $plugin); return (bool) include($path . $file); } } } return false; } /** * Initializes the cache for App, registers a shutdown function. * * @return void */ public static function init() { self::$_map += (array)Cache::read('file_map', '_cake_core_'); self::$_objects += (array)Cache::read('object_map', '_cake_core_'); register_shutdown_function(array('App', 'shutdown')); self::uses('CakePlugin', 'Core'); } /** * Maps the $name to the $file. * * @param string $file full path to file * @param string $name unique name for this map * @param string $plugin camelized if object is from a plugin, the name of the plugin * @return void */ protected static function _map($file, $name, $plugin = null) { if ($plugin) { self::$_map['Plugin'][$plugin][$name] = $file; } else { self::$_map[$name] = $file; } if (!self::$bootstrapping) { self::$_cacheChange = true; } } /** * Returns a file's complete path. * * @param string $name unique name * @param string $plugin camelized if object is from a plugin, the name of the plugin * @return mixed file path if found, false otherwise */ protected static function _mapped($name, $plugin = null) { if ($plugin) { if (isset(self::$_map['Plugin'][$plugin][$name])) { return self::$_map['Plugin'][$plugin][$name]; } return false; } if (isset(self::$_map[$name])) { return self::$_map[$name]; } return false; } protected static function _packageFormat() { if (empty(self::$_packageFormat)) { self::$_packageFormat = array( 'Model' => array( '%s' . 'Model' . DS, '%s' . 'models' . DS ), 'Model/Behavior' => array( '%s' . 'Model' . DS . 'Behavior' . DS, '%s' . 'models' . DS . 'behaviors' . DS ), 'Model/Datasource' => array( '%s' . 'Model' . DS . 'Datasource' . DS, '%s' . 'models' . DS . 'datasources' . DS ), 'Model/Datasource/Database' => array( '%s' . 'Model' . DS . 'Datasource' . DS . 'Database' . DS, '%s' . 'models' . DS . 'datasources' . DS . 'database' . DS ), 'Model/Datasource/Session' => array( '%s' . 'Model' . DS . 'Datasource' . DS . 'Session' . DS, '%s' . 'models' . DS . 'datasources' . DS . 'session' . DS ), 'Controller' => array( '%s' . 'Controller' . DS, '%s' . 'controllers' . DS ), 'Controller/Component' => array( '%s' . 'Controller' . DS . 'Component' . DS, '%s' . 'controllers' . DS . 'components' . DS ), 'Controller/Component/Auth' => array( '%s' . 'Controller' . DS . 'Component' . DS . 'Auth' . DS, '%s' . 'controllers' . DS . 'components' . DS . 'auth' . DS ), 'View' => array( '%s' . 'View' . DS, '%s' . 'views' . DS ), 'View/Helper' => array( '%s' . 'View' . DS . 'Helper' . DS, '%s' . 'views' . DS . 'helpers' . DS ), 'Console' => array( '%s' . 'Console' . DS, '%s' . 'console' . DS ), 'Console/Command' => array( '%s' . 'Console' . DS . 'Command' . DS, '%s' . 'console' . DS . 'shells' . DS, ), 'Console/Command/Task' => array( '%s' . 'Console' . DS . 'Command' . DS . 'Task' . DS, '%s' . 'console' . DS . 'shells' . DS . 'tasks' . DS ), 'Lib' => array( '%s' . 'Lib' . DS, '%s' . 'libs' . DS ), 'locales' => array( '%s' . 'Locale' . DS, '%s' . 'locale' . DS ), 'Vendor' => array( '%s' . 'Vendor' . DS, VENDORS ), 'Plugin' => array( APP . 'Plugin' . DS, APP . 'plugins' . DS, dirname(dirname(CAKE)) . DS . 'plugins' . DS ) ); } return self::$_packageFormat; } /** * Object destructor. * * Writes cache file if changes have been made to the $_map * * @return void */ public static function shutdown() { if (self::$_cacheChange) { Cache::write('file_map', array_filter(self::$_map), '_cake_core_'); } if (self::$_objectCacheChange) { Cache::write('object_map', self::$_objects, '_cake_core_'); } } }
0001-bee
trunk/cakephp2/lib/Cake/Core/App.php
PHP
gpl3
26,183
<?php /** * Object class, allowing __construct and __destruct in PHP4. * * Also includes methods for logging and the special method RequestAction, * to call other Controllers' Actions from anywhere. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Core * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Set', 'Utility'); /** * Object class provides a few generic methods used in several subclasses. * * Also includes methods for logging and the special method RequestAction, * to call other Controllers' Actions from anywhere. * * @package Cake.Core */ class Object { /** * constructor, no-op * */ public function __construct() { } /** * Object-to-string conversion. * Each class can override this method as necessary. * * @return string The name of this class */ public function toString() { $class = get_class($this); return $class; } /** * Calls a controller's method from any location. Can be used to connect controllers together * or tie plugins into a main application. requestAction can be used to return rendered views * or fetch the return value from controller actions. * * @param mixed $url String or array-based url. * @param array $extra if array includes the key "return" it sets the AutoRender to true. * @return mixed Boolean true or false on success/failure, or contents * of rendered action if 'return' is set in $extra. */ public function requestAction($url, $extra = array()) { if (empty($url)) { return false; } App::uses('Dispatcher', 'Routing'); if (($index = array_search('return', $extra)) !== false) { $extra['return'] = 0; $extra['autoRender'] = 1; unset($extra[$index]); } if (is_array($url) && !isset($extra['url'])) { $extra['url'] = array(); } $extra = array_merge(array('autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1), $extra); if (is_string($url)) { $request = new CakeRequest($url); } elseif (is_array($url)) { $params = $url + array('pass' => array(), 'named' => array(), 'base' => false); $params = array_merge($params, $extra); $request = new CakeRequest(Router::reverse($params), false); if (isset($params['data'])) { $request->data = $params['data']; } } $dispatcher = new Dispatcher(); $result = $dispatcher->dispatch($request, new CakeResponse(), $extra); Router::popRequest(); return $result; } /** * Calls a method on this object with the given parameters. Provides an OO wrapper * for `call_user_func_array` * * @param string $method Name of the method to call * @param array $params Parameter list to use when calling $method * @return mixed Returns the result of the method call */ public function dispatchMethod($method, $params = array()) { switch (count($params)) { case 0: return $this->{$method}(); case 1: return $this->{$method}($params[0]); case 2: return $this->{$method}($params[0], $params[1]); case 3: return $this->{$method}($params[0], $params[1], $params[2]); case 4: return $this->{$method}($params[0], $params[1], $params[2], $params[3]); case 5: return $this->{$method}($params[0], $params[1], $params[2], $params[3], $params[4]); default: return call_user_func_array(array(&$this, $method), $params); break; } } /** * Stop execution of the current script. Wraps exit() making * testing easier. * * @param integer|string $status see http://php.net/exit for values * @return void */ protected function _stop($status = 0) { exit($status); } /** * Convience method to write a message to CakeLog. See CakeLog::write() * for more information on writing to logs. * * @param string $msg Log message * @param integer $type Error type constant. Defined in app/Config/core.php. * @return boolean Success of log write */ public function log($msg, $type = LOG_ERROR) { if (!class_exists('CakeLog')) { require CAKE . 'cake_log.php'; } if (!is_string($msg)) { $msg = print_r($msg, true); } return CakeLog::write($type, $msg); } /** * Allows setting of multiple properties of the object in a single line of code. Will only set * properties that are part of a class declaration. * * @param array $properties An associative array containing properties and corresponding values. * @return void */ protected function _set($properties = array()) { if (is_array($properties) && !empty($properties)) { $vars = get_object_vars($this); foreach ($properties as $key => $val) { if (array_key_exists($key, $vars)) { $this->{$key} = $val; } } } } /** * Merges this objects $property with the property in $class' definition. * This classes value for the property will be merged on top of $class' * * This provides some of the DRY magic CakePHP provides. If you want to shut it off, redefine * this method as an empty function. * * @param array $properties The name of the properties to merge. * @param string $class The class to merge the property with. * @param boolean $normalize Set to true to run the properties through Set::normalize() before merging. * @return void */ protected function _mergeVars($properties, $class, $normalize = true) { $classProperties = get_class_vars($class); foreach ($properties as $var) { if ( isset($classProperties[$var]) && !empty($classProperties[$var]) && is_array($this->{$var}) && $this->{$var} != $classProperties[$var] ) { if ($normalize) { $classProperties[$var] = Set::normalize($classProperties[$var]); $this->{$var} = Set::normalize($this->{$var}); } $this->{$var} = Set::merge($classProperties[$var], $this->{$var}); } } } }
0001-bee
trunk/cakephp2/lib/Cake/Core/Object.php
PHP
gpl3
6,144
<?php /** * CakePlugin class * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Core * @since CakePHP(tm) v 2.0.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * CakePlugin class * * @package Cake.Core * @link http://book.cakephp.org/2.0/en/plugins.html */ class CakePlugin { /** * Holds a list of all loaded plugins and their configuration * * @var array */ protected static $_plugins = array(); /** * Loads a plugin and optionally loads bootstrapping, routing files or loads a initialization function * * Examples: * * `CakePlugin::load('DebugKit')` will load the DebugKit plugin and will not load any bootstrap nor route files * `CakePlugin::load('DebugKit', array('bootstrap' => true, 'routes' => true))` will load the bootstrap.php and routes.php files * `CakePlugin::load('DebugKit', array('bootstrap' => false, 'routes' => true))` will load routes.php file but not bootstrap.php * `CakePlugin::load('DebugKit', array('bootstrap' => array('config1', 'config2')))` will load config1.php and config2.php files * `CakePlugin::load('DebugKit', array('bootstrap' => 'aCallableMethod'))` will run the aCallableMethod function to initialize it * * Bootstrap initialization functions can be expressed as a PHP callback type, including closures. Callbacks will receive two * parameters (plugin name, plugin configuration) * * It is also possible to load multiple plugins at once. Examples: * * `CakePlugin::load(array('DebugKit', 'ApiGenerator'))` will load the DebugKit and ApiGenerator plugins * `CakePlugin::load(array('DebugKit', 'ApiGenerator'), array('bootstrap' => true))` will load bootstrap file for both plugins * * {{{ * CakePlugin::load(array( * 'DebugKit' => array('routes' => true), * 'ApiGenerator' * ), array('bootstrap' => true)) * }}} * * Will only load the bootstrap for ApiGenerator and only the routes for DebugKit * * @param mixed $plugin name of the plugin to be loaded in CamelCase format or array or plugins to load * @param array $config configuration options for the plugin * @throws MissingPluginException if the folder for the plugin to be loaded is not found * @return void */ public static function load($plugin, $config = array()) { if (is_array($plugin)) { foreach ($plugin as $name => $conf) { list($name, $conf) = (is_numeric($name)) ? array($conf, $config) : array($name, $conf); self::load($name, $conf); } return; } $config += array('bootstrap' => false, 'routes' => false); if (empty($config['path'])) { foreach (App::path('plugins') as $path) { if (is_dir($path . $plugin)) { self::$_plugins[$plugin] = $config + array('path' => $path . $plugin . DS); break; } //Backwards compatibility to make easier to migrate to 2.0 $underscored = Inflector::underscore($plugin); if (is_dir($path . $underscored)) { self::$_plugins[$plugin] = $config + array('path' => $path . $underscored . DS); break; } } } else { self::$_plugins[$plugin] = $config; } if (empty(self::$_plugins[$plugin]['path'])) { throw new MissingPluginException(array('plugin' => $plugin)); } if (!empty(self::$_plugins[$plugin]['bootstrap'])) { self::bootstrap($plugin); } } /** * Will load all the plugins located in the configured plugins folders * If passed an options array, it will be used as a common default for all plugins to be loaded * It is possible to set specific defaults for each plugins in the options array. Examples: * * {{{ * CakePlugin::loadAll(array( * array('bootstrap' => true), * 'DebugKit' => array('routes' => true), * )) * }}} * * The above example will load the bootstrap file for all plugins, but for DebugKit it will only load the routes file * and will not look for any bootstrap script. * * @param array $options * @return void */ public static function loadAll($options = array()) { $plugins = App::objects('plugins'); foreach ($plugins as $p) { $opts = isset($options[$p]) ? $options[$p] : null; if ($opts === null && isset($options[0])) { $opts = $options[0]; } self::load($p, (array) $opts); } } /** * Returns the filesystem path for a plugin * * @param string $plugin name of the plugin in CamelCase format * @return string path to the plugin folder * @throws MissingPluginException if the folder for plugin was not found or plugin has not been loaded */ public static function path($plugin) { if (empty(self::$_plugins[$plugin])) { throw new MissingPluginException(array('plugin' => $plugin)); } return self::$_plugins[$plugin]['path']; } /** * Loads the bootstrapping files for a plugin, or calls the initialization setup in the configuration * * @param string $plugin name of the plugin * @return mixed * @see CakePlugin::load() for examples of bootstrap configuration */ public static function bootstrap($plugin) { $config = self::$_plugins[$plugin]; if ($config['bootstrap'] === false) { return false; } if (is_callable($config['bootstrap'])) { return call_user_func_array($config['bootstrap'], array($plugin, $config)); } $path = self::path($plugin); if ($config['bootstrap'] === true) { return include($path . 'Config' . DS . 'bootstrap.php'); } $bootstrap = (array)$config['bootstrap']; foreach ($bootstrap as $file) { include $path . 'Config' . DS . $file . '.php'; } return true; } /** * Loads the routes file for a plugin, or all plugins configured to load their respective routes file * * @param string $plugin name of the plugin, if null will operate on all plugins having enabled the * loading of routes files * @return boolean */ public static function routes($plugin = null) { if ($plugin === null) { foreach (self::loaded() as $p) { self::routes($p); } return true; } $config = self::$_plugins[$plugin]; if ($config['routes'] === false) { return false; } return (bool) include self::path($plugin) . 'Config' . DS . 'routes.php'; } /** * Retruns true if the plugin $plugin is already loaded * If plugin is null, it will return a list of all loaded plugins * * @param string $plugin * @return mixed boolean true if $plugin is already loaded. * If $plugin is null, returns a list of plugins that have been loaded */ public static function loaded($plugin = null) { if ($plugin) { return isset(self::$_plugins[$plugin]); } $return = array_keys(self::$_plugins); sort($return); return $return; } /** * Forgets a loaded plugin or all of them if first parameter is null * * @param string $plugin name of the plugin to forget * @return void */ public static function unload($plugin = null) { if (is_null($plugin)) { self::$_plugins = array(); } else { unset(self::$_plugins[$plugin]); } } }
0001-bee
trunk/cakephp2/lib/Cake/Core/CakePlugin.php
PHP
gpl3
7,242
<?php /** * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Load Model and AppModel */ App::uses('AppModel', 'Model'); /** * Action for Access Control Object * * @package Cake.Model */ class AcoAction extends AppModel { /** * Model name * * @var string */ public $name = 'AcoAction'; /** * ACO Actions belong to ACOs * * @var array */ public $belongsTo = array('Aco'); }
0001-bee
trunk/cakephp2/lib/Cake/Model/AcoAction.php
PHP
gpl3
933
<?php /** * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Load Model and AppModel */ App::uses('AppModel', 'Model'); /** * ACL Node * * * @package Cake.Model */ class AclNode extends AppModel { /** * Explicitly disable in-memory query caching for ACL models * * @var boolean */ public $cacheQueries = false; /** * ACL models use the Tree behavior * * @var array */ public $actsAs = array('Tree' => array('type' => 'nested')); /** * Constructor * */ public function __construct() { $config = Configure::read('Acl.database'); if (isset($config)) { $this->useDbConfig = $config; } parent::__construct(); } /** * Retrieves the Aro/Aco node for this model * * @param mixed $ref Array with 'model' and 'foreign_key', model object, or string value * @return array Node found in database */ public function node($ref = null) { $db = $this->getDataSource(); $type = $this->alias; $result = null; if (!empty($this->useTable)) { $table = $this->useTable; } else { $table = Inflector::pluralize(Inflector::underscore($type)); } if (empty($ref)) { return null; } elseif (is_string($ref)) { $path = explode('/', $ref); $start = $path[0]; unset($path[0]); $queryData = array( 'conditions' => array( $db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft"), $db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght")), 'fields' => array('id', 'parent_id', 'model', 'foreign_key', 'alias'), 'joins' => array(array( 'table' => $table, 'alias' => "{$type}0", 'type' => 'LEFT', 'conditions' => array("{$type}0.alias" => $start) )), 'order' => $db->name("{$type}.lft") . ' DESC' ); foreach ($path as $i => $alias) { $j = $i - 1; $queryData['joins'][] = array( 'table' => $table, 'alias' => "{$type}{$i}", 'type' => 'LEFT', 'conditions' => array( $db->name("{$type}{$i}.lft") . ' > ' . $db->name("{$type}{$j}.lft"), $db->name("{$type}{$i}.rght") . ' < ' . $db->name("{$type}{$j}.rght"), $db->name("{$type}{$i}.alias") . ' = ' . $db->value($alias, 'string'), $db->name("{$type}{$j}.id") . ' = ' . $db->name("{$type}{$i}.parent_id") ) ); $queryData['conditions'] = array('or' => array( $db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft") . ' AND ' . $db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght"), $db->name("{$type}.lft") . ' <= ' . $db->name("{$type}{$i}.lft") . ' AND ' . $db->name("{$type}.rght") . ' >= ' . $db->name("{$type}{$i}.rght")) ); } $result = $db->read($this, $queryData, -1); $path = array_values($path); if ( !isset($result[0][$type]) || (!empty($path) && $result[0][$type]['alias'] != $path[count($path) - 1]) || (empty($path) && $result[0][$type]['alias'] != $start) ) { return false; } } elseif (is_object($ref) && is_a($ref, 'Model')) { $ref = array('model' => $ref->alias, 'foreign_key' => $ref->id); } elseif (is_array($ref) && !(isset($ref['model']) && isset($ref['foreign_key']))) { $name = key($ref); $model = ClassRegistry::init(array('class' => $name, 'alias' => $name)); if (empty($model)) { trigger_error(__d('cake_dev', "Model class '%s' not found in AclNode::node() when trying to bind %s object", $type, $this->alias), E_USER_WARNING); return null; } $tmpRef = null; if (method_exists($model, 'bindNode')) { $tmpRef = $model->bindNode($ref); } if (empty($tmpRef)) { $ref = array('model' => $name, 'foreign_key' => $ref[$name][$model->primaryKey]); } else { if (is_string($tmpRef)) { return $this->node($tmpRef); } $ref = $tmpRef; } } if (is_array($ref)) { if (is_array(current($ref)) && is_string(key($ref))) { $name = key($ref); $ref = current($ref); } foreach ($ref as $key => $val) { if (strpos($key, $type) !== 0 && strpos($key, '.') === false) { unset($ref[$key]); $ref["{$type}0.{$key}"] = $val; } } $queryData = array( 'conditions' => $ref, 'fields' => array('id', 'parent_id', 'model', 'foreign_key', 'alias'), 'joins' => array(array( 'table' => $table, 'alias' => "{$type}0", 'type' => 'LEFT', 'conditions' => array( $db->name("{$type}.lft") . ' <= ' . $db->name("{$type}0.lft"), $db->name("{$type}.rght") . ' >= ' . $db->name("{$type}0.rght") ) )), 'order' => $db->name("{$type}.lft") . ' DESC' ); $result = $db->read($this, $queryData, -1); if (!$result) { trigger_error(__d('cake_dev', "AclNode::node() - Couldn't find %s node identified by \"%s\"", $type, print_r($ref, true)), E_USER_WARNING); } } return $result; } }
0001-bee
trunk/cakephp2/lib/Cake/Model/AclNode.php
PHP
gpl3
5,279
<?php /** * Datasource connection manager * * Provides an interface for loading and enumerating connections defined in app/Config/database.php * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model * @since CakePHP(tm) v 0.10.x.1402 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('DataSource', 'Model/Datasource'); /** * Manages loaded instances of DataSource objects * * @package Cake.Model */ class ConnectionManager { /** * Holds a loaded instance of the Connections object * * @var DATABASE_CONFIG */ public static $config = null; /** * Holds instances DataSource objects * * @var array */ protected static $_dataSources = array(); /** * Contains a list of all file and class names used in Connection settings * * @var array */ protected static $_connectionsEnum = array(); /** * Indicates if the init code for this class has already been executed * * @var boolean */ protected static $_init = false; /** * Loads connections configuration. * * @return void */ protected static function _init() { include_once APP . 'Config' . DS . 'database.php'; if (class_exists('DATABASE_CONFIG')) { self::$config = new DATABASE_CONFIG(); } self::$_init = true; } /** * Gets a reference to a DataSource object * * @param string $name The name of the DataSource, as defined in app/Config/database.php * @return DataSource Instance * @throws MissingDatasourceConfigException * @throws MissingDatasourceException */ public static function getDataSource($name) { if (empty(self::$_init)) { self::_init(); } if (!empty(self::$_dataSources[$name])) { $return = self::$_dataSources[$name]; return $return; } if (empty(self::$_connectionsEnum[$name])) { self::_getConnectionObject($name); } self::loadDataSource($name); $conn = self::$_connectionsEnum[$name]; $class = $conn['classname']; self::$_dataSources[$name] = new $class(self::$config->{$name}); self::$_dataSources[$name]->configKeyName = $name; return self::$_dataSources[$name]; } /** * Gets the list of available DataSource connections * This will only return the datasources instantiated by this manager * It differs from enumConnectionObjects, since the latter will return all configured connections * * @return array List of available connections */ public static function sourceList() { if (empty(self::$_init)) { self::_init(); } return array_keys(self::$_dataSources); } /** * Gets a DataSource name from an object reference. * * @param DataSource $source DataSource object * @return string Datasource name, or null if source is not present * in the ConnectionManager. */ public static function getSourceName($source) { if (empty(self::$_init)) { self::_init(); } foreach (self::$_dataSources as $name => $ds) { if ($ds === $source) { return $name; } } return null; } /** * Loads the DataSource class for the given connection name * * @param mixed $connName A string name of the connection, as defined in app/Config/database.php, * or an array containing the filename (without extension) and class name of the object, * to be found in app/Model/Datasource/ or lib/Cake/Model/Datasource/. * @return boolean True on success, null on failure or false if the class is already loaded * @throws MissingDatasourceException */ public static function loadDataSource($connName) { if (empty(self::$_init)) { self::_init(); } if (is_array($connName)) { $conn = $connName; } else { $conn = self::$_connectionsEnum[$connName]; } if (class_exists($conn['classname'], false)) { return false; } $plugin = $package = null; if (!empty($conn['plugin'])) { $plugin = $conn['plugin'] . '.'; } if (!empty($conn['package'])) { $package = '/' . $conn['package']; } App::uses($conn['classname'], $plugin . 'Model/Datasource' . $package); if (!class_exists($conn['classname'])) { throw new MissingDatasourceException(array( 'class' => $conn['classname'], 'plugin' => substr($plugin, 0, -1) )); } return true; } /** * Return a list of connections * * @return array An associative array of elements where the key is the connection name * (as defined in Connections), and the value is an array with keys 'filename' and 'classname'. */ public static function enumConnectionObjects() { if (empty(self::$_init)) { self::_init(); } return (array) self::$config; } /** * Dynamically creates a DataSource object at runtime, with the given name and settings * * @param string $name The DataSource name * @param array $config The DataSource configuration settings * @return DataSource A reference to the DataSource object, or null if creation failed */ public static function create($name = '', $config = array()) { if (empty(self::$_init)) { self::_init(); } if (empty($name) || empty($config) || array_key_exists($name, self::$_connectionsEnum)) { return null; } self::$config->{$name} = $config; self::$_connectionsEnum[$name] = self::_connectionData($config); $return = self::getDataSource($name); return $return; } /** * Removes a connection configuration at runtime given its name * * @param string $name the connection name as it was created * @return boolean success if connection was removed, false if it does not exist */ public static function drop($name) { if (empty(self::$_init)) { self::_init(); } if (!isset(self::$config->{$name})) { return false; } unset(self::$_connectionsEnum[$name], self::$_dataSources[$name], self::$config->{$name}); return true; } /** * Gets a list of class and file names associated with the user-defined DataSource connections * * @param string $name Connection name * @return void * @throws MissingDatasourceConfigException */ protected static function _getConnectionObject($name) { if (!empty(self::$config->{$name})) { self::$_connectionsEnum[$name] = self::_connectionData(self::$config->{$name}); } else { throw new MissingDatasourceConfigException(array('config' => $name)); } } /** * Returns the file, class name, and parent for the given driver. * * @param array $config Array with connection configuration. Key 'datasource' is required * @return array An indexed array with: filename, classname, plugin and parent */ protected static function _connectionData($config) { $package = $classname = $plugin = null; list($plugin, $classname) = pluginSplit($config['datasource']); if (strpos($classname, '/') !== false) { $package = dirname($classname); $classname = basename($classname); } return compact('package', 'classname', 'plugin'); } }
0001-bee
trunk/cakephp2/lib/Cake/Model/ConnectionManager.php
PHP
gpl3
7,185
<?php /** * Behavior for binding management. * * Behavior to simplify manipulating a model's bindings when doing a find operation * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model.Behavior * @since CakePHP(tm) v 1.2.0.5669 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Behavior to allow for dynamic and atomic manipulation of a Model's associations used for a find call. Most useful for limiting * the amount of associations and data returned. * * @package Cake.Model.Behavior * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html */ class ContainableBehavior extends ModelBehavior { /** * Types of relationships available for models * * @var array */ public $types = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'); /** * Runtime configuration for this behavior * * @var array */ public $runtime = array(); /** * Initiate behavior for the model using specified settings. * * Available settings: * * - recursive: (boolean, optional) set to true to allow containable to automatically * determine the recursiveness level needed to fetch specified models, * and set the model recursiveness to this level. setting it to false * disables this feature. DEFAULTS TO: true * - notices: (boolean, optional) issues E_NOTICES for bindings referenced in a * containable call that are not valid. DEFAULTS TO: true * - autoFields: (boolean, optional) auto-add needed fields to fetch requested * bindings. DEFAULTS TO: true * * @param Model $Model Model using the behavior * @param array $settings Settings to override for model. * @return void */ public function setup($Model, $settings = array()) { if (!isset($this->settings[$Model->alias])) { $this->settings[$Model->alias] = array('recursive' => true, 'notices' => true, 'autoFields' => true); } $this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], $settings); } /** * Runs before a find() operation. Used to allow 'contain' setting * as part of the find call, like this: * * `Model->find('all', array('contain' => array('Model1', 'Model2')));` * * {{{ * Model->find('all', array('contain' => array( * 'Model1' => array('Model11', 'Model12'), * 'Model2', * 'Model3' => array( * 'Model31' => 'Model311', * 'Model32', * 'Model33' => array('Model331', 'Model332') * ))); * }}} * * @param Model $Model Model using the behavior * @param array $query Query parameters as set by cake * @return array */ public function beforeFind($Model, $query) { $reset = (isset($query['reset']) ? $query['reset'] : true); $noContain = ( (isset($this->runtime[$Model->alias]['contain']) && empty($this->runtime[$Model->alias]['contain'])) || (isset($query['contain']) && empty($query['contain'])) ); $contain = array(); if (isset($this->runtime[$Model->alias]['contain'])) { $contain = $this->runtime[$Model->alias]['contain']; unset($this->runtime[$Model->alias]['contain']); } if (isset($query['contain'])) { $contain = array_merge($contain, (array)$query['contain']); } if ( $noContain || !$contain || in_array($contain, array(null, false), true) || (isset($contain[0]) && $contain[0] === null) ) { if ($noContain) { $query['recursive'] = -1; } return $query; } if ((isset($contain[0]) && is_bool($contain[0])) || is_bool(end($contain))) { $reset = is_bool(end($contain)) ? array_pop($contain) : array_shift($contain); } $containments = $this->containments($Model, $contain); $map = $this->containmentsMap($containments); $mandatory = array(); foreach ($containments['models'] as $name => $model) { $instance = $model['instance']; $needed = $this->fieldDependencies($instance, $map, false); if (!empty($needed)) { $mandatory = array_merge($mandatory, $needed); } if ($contain) { $backupBindings = array(); foreach ($this->types as $relation) { if (!empty($instance->__backAssociation[$relation])) { $backupBindings[$relation] = $instance->__backAssociation[$relation]; } else { $backupBindings[$relation] = $instance->{$relation}; } } foreach ($this->types as $type) { $unbind = array(); foreach ($instance->{$type} as $assoc => $options) { if (!isset($model['keep'][$assoc])) { $unbind[] = $assoc; } } if (!empty($unbind)) { if (!$reset && empty($instance->__backOriginalAssociation)) { $instance->__backOriginalAssociation = $backupBindings; } $instance->unbindModel(array($type => $unbind), $reset); } foreach ($instance->{$type} as $assoc => $options) { if (isset($model['keep'][$assoc]) && !empty($model['keep'][$assoc])) { if (isset($model['keep'][$assoc]['fields'])) { $model['keep'][$assoc]['fields'] = $this->fieldDependencies($containments['models'][$assoc]['instance'], $map, $model['keep'][$assoc]['fields']); } if (!$reset && empty($instance->__backOriginalAssociation)) { $instance->__backOriginalAssociation = $backupBindings; } else if ($reset) { $instance->__backAssociation[$type] = $backupBindings[$type]; } $instance->{$type}[$assoc] = array_merge($instance->{$type}[$assoc], $model['keep'][$assoc]); } if (!$reset) { $instance->__backInnerAssociation[] = $assoc; } } } } } if ($this->settings[$Model->alias]['recursive']) { $query['recursive'] = (isset($query['recursive'])) ? $query['recursive'] : $containments['depth']; } $autoFields = ($this->settings[$Model->alias]['autoFields'] && !in_array($Model->findQueryType, array('list', 'count')) && !empty($query['fields'])); if (!$autoFields) { return $query; } $query['fields'] = (array)$query['fields']; foreach (array('hasOne', 'belongsTo') as $type) { if (!empty($Model->{$type})) { foreach ($Model->{$type} as $assoc => $data) { if ($Model->useDbConfig == $Model->{$assoc}->useDbConfig && !empty($data['fields'])) { foreach ((array) $data['fields'] as $field) { $query['fields'][] = (strpos($field, '.') === false ? $assoc . '.' : '') . $field; } } } } } if (!empty($mandatory[$Model->alias])) { foreach ($mandatory[$Model->alias] as $field) { if ($field == '--primaryKey--') { $field = $Model->primaryKey; } else if (preg_match('/^.+\.\-\-[^-]+\-\-$/', $field)) { list($modelName, $field) = explode('.', $field); if ($Model->useDbConfig == $Model->{$modelName}->useDbConfig) { $field = $modelName . '.' . ( ($field === '--primaryKey--') ? $Model->$modelName->primaryKey : $field ); } else { $field = null; } } if ($field !== null) { $query['fields'][] = $field; } } } $query['fields'] = array_unique($query['fields']); return $query; } /** * Unbinds all relations from a model except the specified ones. Calling this function without * parameters unbinds all related models. * * @param Model $Model Model on which binding restriction is being applied * @return void * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html#using-containable */ public function contain($Model) { $args = func_get_args(); $contain = call_user_func_array('am', array_slice($args, 1)); $this->runtime[$Model->alias]['contain'] = $contain; } /** * Permanently restore the original binding settings of given model, useful * for restoring the bindings after using 'reset' => false as part of the * contain call. * * @param Model $Model Model on which to reset bindings * @return void */ public function resetBindings($Model) { if (!empty($Model->__backOriginalAssociation)) { $Model->__backAssociation = $Model->__backOriginalAssociation; unset($Model->__backOriginalAssociation); } $Model->resetAssociations(); if (!empty($Model->__backInnerAssociation)) { $assocs = $Model->__backInnerAssociation; $Model->__backInnerAssociation = array(); foreach ($assocs as $currentModel) { $this->resetBindings($Model->$currentModel); } } } /** * Process containments for model. * * @param Model $Model Model on which binding restriction is being applied * @param array $contain Parameters to use for restricting this model * @param array $containments Current set of containments * @param boolean $throwErrors Wether unexisting bindings show throw errors * @return array Containments */ public function containments($Model, $contain, $containments = array(), $throwErrors = null) { $options = array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery'); $keep = array(); $depth = array(); if ($throwErrors === null) { $throwErrors = (empty($this->settings[$Model->alias]) ? true : $this->settings[$Model->alias]['notices']); } foreach ((array)$contain as $name => $children) { if (is_numeric($name)) { $name = $children; $children = array(); } if (preg_match('/(?<!\.)\(/', $name)) { $name = str_replace('(', '.(', $name); } if (strpos($name, '.') !== false) { $chain = explode('.', $name); $name = array_shift($chain); $children = array(implode('.', $chain) => $children); } $children = (array)$children; foreach ($children as $key => $val) { if (is_string($key) && is_string($val) && !in_array($key, $options, true)) { $children[$key] = (array) $val; } } $keys = array_keys($children); if ($keys && isset($children[0])) { $keys = array_merge(array_values($children), $keys); } foreach ($keys as $i => $key) { if (is_array($key)) { continue; } $optionKey = in_array($key, $options, true); if (!$optionKey && is_string($key) && preg_match('/^[a-z(]/', $key) && (!isset($Model->{$key}) || !is_object($Model->{$key}))) { $option = 'fields'; $val = array($key); if ($key{0} == '(') { $val = preg_split('/\s*,\s*/', substr(substr($key, 1), 0, -1)); } elseif (preg_match('/ASC|DESC$/', $key)) { $option = 'order'; $val = $Model->{$name}->alias.'.'.$key; } elseif (preg_match('/[ =!]/', $key)) { $option = 'conditions'; $val = $Model->{$name}->alias.'.'.$key; } $children[$option] = is_array($val) ? $val : array($val); $newChildren = null; if (!empty($name) && !empty($children[$key])) { $newChildren = $children[$key]; } unset($children[$key], $children[$i]); $key = $option; $optionKey = true; if (!empty($newChildren)) { $children = Set::merge($children, $newChildren); } } if ($optionKey && isset($children[$key])) { if (!empty($keep[$name][$key]) && is_array($keep[$name][$key])) { $keep[$name][$key] = array_merge((isset($keep[$name][$key]) ? $keep[$name][$key] : array()), (array) $children[$key]); } else { $keep[$name][$key] = $children[$key]; } unset($children[$key]); } } if (!isset($Model->{$name}) || !is_object($Model->{$name})) { if ($throwErrors) { trigger_error(__d('cake_dev', 'Model "%s" is not associated with model "%s"', $Model->alias, $name), E_USER_WARNING); } continue; } $containments = $this->containments($Model->{$name}, $children, $containments); $depths[] = $containments['depth'] + 1; if (!isset($keep[$name])) { $keep[$name] = array(); } } if (!isset($containments['models'][$Model->alias])) { $containments['models'][$Model->alias] = array('keep' => array(),'instance' => &$Model); } $containments['models'][$Model->alias]['keep'] = array_merge($containments['models'][$Model->alias]['keep'], $keep); $containments['depth'] = empty($depths) ? 0 : max($depths); return $containments; } /** * Calculate needed fields to fetch the required bindings for the given model. * * @param Model $Model Model * @param array $map Map of relations for given model * @param mixed $fields If array, fields to initially load, if false use $Model as primary model * @return array Fields */ public function fieldDependencies($Model, $map, $fields = array()) { if ($fields === false) { foreach ($map as $parent => $children) { foreach ($children as $type => $bindings) { foreach ($bindings as $dependency) { if ($type == 'hasAndBelongsToMany') { $fields[$parent][] = '--primaryKey--'; } else if ($type == 'belongsTo') { $fields[$parent][] = $dependency . '.--primaryKey--'; } } } } return $fields; } if (empty($map[$Model->alias])) { return $fields; } foreach ($map[$Model->alias] as $type => $bindings) { foreach ($bindings as $dependency) { $innerFields = array(); switch ($type) { case 'belongsTo': $fields[] = $Model->{$type}[$dependency]['foreignKey']; break; case 'hasOne': case 'hasMany': $innerFields[] = $Model->$dependency->primaryKey; $fields[] = $Model->primaryKey; break; } if (!empty($innerFields) && !empty($Model->{$type}[$dependency]['fields'])) { $Model->{$type}[$dependency]['fields'] = array_unique(array_merge($Model->{$type}[$dependency]['fields'], $innerFields)); } } } return array_unique($fields); } /** * Build the map of containments * * @param array $containments Containments * @return array Built containments */ public function containmentsMap($containments) { $map = array(); foreach ($containments['models'] as $name => $model) { $instance = $model['instance']; foreach ($this->types as $type) { foreach ($instance->{$type} as $assoc => $options) { if (isset($model['keep'][$assoc])) { $map[$name][$type] = isset($map[$name][$type]) ? array_merge($map[$name][$type], (array)$assoc) : (array)$assoc; } } } } return $map; } }
0001-bee
trunk/cakephp2/lib/Cake/Model/Behavior/ContainableBehavior.php
PHP
gpl3
14,424
<?php /** * ACL behavior class. * * Enables objects to easily tie into an ACL system * * PHP 5 * * CakePHP : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP Project * @package Cake.Model.Behavior * @since CakePHP v 1.2.0.4487 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AclNode', 'Model'); /** * ACL behavior * * @package Cake.Model.Behavior * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/acl.html */ class AclBehavior extends ModelBehavior { /** * Maps ACL type options to ACL models * * @var array */ protected $_typeMaps = array('requester' => 'Aro', 'controlled' => 'Aco', 'both' => array('Aro', 'Aco')); /** * Sets up the configuration for the model, and loads ACL models if they haven't been already * * @param Model $model * @param array $config * @return void */ public function setup($model, $config = array()) { if (isset($config[0])) { $config['type'] = $config[0]; unset($config[0]); } $this->settings[$model->name] = array_merge(array('type' => 'controlled'), $config); $this->settings[$model->name]['type'] = strtolower($this->settings[$model->name]['type']); $types = $this->_typeMaps[$this->settings[$model->name]['type']]; if (!is_array($types)) { $types = array($types); } foreach ($types as $type) { $model->{$type} = ClassRegistry::init($type); } if (!method_exists($model, 'parentNode')) { trigger_error(__d('cake_dev', 'Callback parentNode() not defined in %s', $model->alias), E_USER_WARNING); } } /** * Retrieves the Aro/Aco node for this model * * @param Model $model * @param mixed $ref * @param string $type Only needed when Acl is set up as 'both', specify 'Aro' or 'Aco' to get the correct node * @return array * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/acl.html#node */ public function node($model, $ref = null, $type = null) { if (empty($type)) { $type = $this->_typeMaps[$this->settings[$model->name]['type']]; if (is_array($type)) { trigger_error(__d('cake_dev', 'AclBehavior is setup with more then one type, please specify type parameter for node()'), E_USER_WARNING); return null; } } if (empty($ref)) { $ref = array('model' => $model->name, 'foreign_key' => $model->id); } return $model->{$type}->node($ref); } /** * Creates a new ARO/ACO node bound to this record * * @param Model $model * @param boolean $created True if this is a new record * @return void */ public function afterSave($model, $created) { $types = $this->_typeMaps[$this->settings[$model->name]['type']]; if (!is_array($types)) { $types = array($types); } foreach ($types as $type) { $parent = $model->parentNode(); if (!empty($parent)) { $parent = $this->node($model, $parent, $type); } $data = array( 'parent_id' => isset($parent[0][$type]['id']) ? $parent[0][$type]['id'] : null, 'model' => $model->name, 'foreign_key' => $model->id ); if (!$created) { $node = $this->node($model, null, $type); $data['id'] = isset($node[0][$type]['id']) ? $node[0][$type]['id'] : null; } $model->{$type}->create(); $model->{$type}->save($data); } } /** * Destroys the ARO/ACO node bound to the deleted record * * @param Model $model * @return void */ public function afterDelete($model) { $types = $this->_typeMaps[$this->settings[$model->name]['type']]; if (!is_array($types)) { $types = array($types); } foreach ($types as $type) { $node = Set::extract($this->node($model, null, $type), "0.{$type}.id"); if (!empty($node)) { $model->{$type}->delete($node); } } } }
0001-bee
trunk/cakephp2/lib/Cake/Model/Behavior/AclBehavior.php
PHP
gpl3
3,997
<?php /** * Translate behavior * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model.Behavior * @since CakePHP(tm) v 1.2.0.4525 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('I18n', 'I18n'); /** * Translate behavior * * @package Cake.Model.Behavior * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/translate.html */ class TranslateBehavior extends ModelBehavior { /** * Used for runtime configuration of model * * @var array */ public $runtime = array(); /** * Callback * * $config for TranslateBehavior should be * array( 'fields' => array('field_one', * 'field_two' => 'FieldAssoc', 'field_three')) * * With above example only one permanent hasMany will be joined (for field_two * as FieldAssoc) * * $config could be empty - and translations configured dynamically by * bindTranslation() method * * @param Model $model Model the behavior is being attached to. * @param array $config Array of configuration information. * @return mixed */ public function setup($model, $config = array()) { $db = ConnectionManager::getDataSource($model->useDbConfig); if (!$db->connected) { trigger_error( __d('cake_dev', 'Datasource %s for TranslateBehavior of model %s is not connected', $model->useDbConfig, $model->alias), E_USER_ERROR ); return false; } $this->settings[$model->alias] = array(); $this->runtime[$model->alias] = array('fields' => array()); $this->translateModel($model); return $this->bindTranslation($model, $config, false); } /** * Cleanup Callback unbinds bound translations and deletes setting information. * * @param Model $model Model being detached. * @return void */ public function cleanup($model) { $this->unbindTranslation($model); unset($this->settings[$model->alias]); unset($this->runtime[$model->alias]); } /** * beforeFind Callback * * @param Model $model Model find is being run on. * @param array $query Array of Query parameters. * @return array Modified query */ public function beforeFind($model, $query) { $this->runtime[$model->alias]['virtualFields'] = $model->virtualFields; $locale = $this->_getLocale($model); if (empty($locale)) { return $query; } $db = $model->getDataSource(); $RuntimeModel = $this->translateModel($model); if (!empty($RuntimeModel->tablePrefix)) { $tablePrefix = $RuntimeModel->tablePrefix; } else { $tablePrefix = $db->config['prefix']; } $joinTable = new StdClass(); $joinTable->tablePrefix = $tablePrefix; $joinTable->table = $RuntimeModel->table; if (is_string($query['fields']) && 'COUNT(*) AS '.$db->name('count') == $query['fields']) { $query['fields'] = 'COUNT(DISTINCT('.$db->name($model->alias . '.' . $model->primaryKey) . ')) ' . $db->alias . 'count'; $query['joins'][] = array( 'type' => 'INNER', 'alias' => $RuntimeModel->alias, 'table' => $joinTable, 'conditions' => array( $model->alias . '.' . $model->primaryKey => $db->identifier($RuntimeModel->alias.'.foreign_key'), $RuntimeModel->alias.'.model' => $model->name, $RuntimeModel->alias.'.locale' => $locale ) ); return $query; } $fields = array_merge($this->settings[$model->alias], $this->runtime[$model->alias]['fields']); $addFields = array(); if (empty($query['fields'])) { $addFields = $fields; } else if (is_array($query['fields'])) { foreach ($fields as $key => $value) { $field = (is_numeric($key)) ? $value : $key; if (in_array($model->alias.'.*', $query['fields']) || in_array($model->alias.'.'.$field, $query['fields']) || in_array($field, $query['fields'])) { $addFields[] = $field; } } } $this->runtime[$model->alias]['virtualFields'] = $model->virtualFields; if ($addFields) { foreach ($addFields as $_f => $field) { $aliasField = is_numeric($_f) ? $field : $_f; foreach (array($aliasField, $model->alias.'.'.$aliasField) as $_field) { $key = array_search($_field, (array)$query['fields']); if ($key !== false) { unset($query['fields'][$key]); } } if (is_array($locale)) { foreach ($locale as $_locale) { $model->virtualFields['i18n_'.$field.'_'.$_locale] = 'I18n__'.$field.'__'.$_locale.'.content'; if (!empty($query['fields'])) { $query['fields'][] = 'i18n_'.$field.'_'.$_locale; } $query['joins'][] = array( 'type' => 'LEFT', 'alias' => 'I18n__'.$field.'__'.$_locale, 'table' => $joinTable, 'conditions' => array( $model->alias . '.' . $model->primaryKey => $db->identifier("I18n__{$field}__{$_locale}.foreign_key"), 'I18n__'.$field.'__'.$_locale.'.model' => $model->name, 'I18n__'.$field.'__'.$_locale.'.'.$RuntimeModel->displayField => $aliasField, 'I18n__'.$field.'__'.$_locale.'.locale' => $_locale ) ); } } else { $model->virtualFields['i18n_'.$field] = 'I18n__'.$field.'.content'; if (!empty($query['fields'])) { $query['fields'][] = 'i18n_'.$field; } $query['joins'][] = array( 'type' => 'INNER', 'alias' => 'I18n__'.$field, 'table' => $joinTable, 'conditions' => array( $model->alias . '.' . $model->primaryKey => $db->identifier("I18n__{$field}.foreign_key"), 'I18n__'.$field.'.model' => $model->name, 'I18n__'.$field.'.'.$RuntimeModel->displayField => $aliasField, 'I18n__'.$field.'.locale' => $locale ) ); } } } $this->runtime[$model->alias]['beforeFind'] = $addFields; return $query; } /** * afterFind Callback * * @param Model $model Model find was run on * @param array $results Array of model results. * @param boolean $primary Did the find originate on $model. * @return array Modified results */ public function afterFind($model, $results, $primary) { $model->virtualFields = $this->runtime[$model->alias]['virtualFields']; $this->runtime[$model->alias]['virtualFields'] = $this->runtime[$model->alias]['fields'] = array(); $locale = $this->_getLocale($model); if (empty($locale) || empty($results) || empty($this->runtime[$model->alias]['beforeFind'])) { return $results; } $beforeFind = $this->runtime[$model->alias]['beforeFind']; foreach ($results as $key => &$row) { $results[$key][$model->alias]['locale'] = (is_array($locale)) ? current($locale) : $locale; foreach ($beforeFind as $_f => $field) { $aliasField = is_numeric($_f) ? $field : $_f; if (is_array($locale)) { foreach ($locale as $_locale) { if (!isset($row[$model->alias][$aliasField]) && !empty($row[$model->alias]['i18n_'.$field.'_'.$_locale])) { $row[$model->alias][$aliasField] = $row[$model->alias]['i18n_'.$field.'_'.$_locale]; $row[$model->alias]['locale'] = $_locale; } unset($row[$model->alias]['i18n_'.$field.'_'.$_locale]); } if (!isset($row[$model->alias][$aliasField])) { $row[$model->alias][$aliasField] = ''; } } else { $value = ''; if (!empty($row[$model->alias]['i18n_' . $field])) { $value = $row[$model->alias]['i18n_' . $field]; } $row[$model->alias][$aliasField] = $value; unset($row[$model->alias]['i18n_' . $field]); } } } return $results; } /** * beforeValidate Callback * * @param Model $model Model invalidFields was called on. * @return boolean */ public function beforeValidate($model) { $locale = $this->_getLocale($model); if (empty($locale)) { return true; } $fields = array_merge($this->settings[$model->alias], $this->runtime[$model->alias]['fields']); $tempData = array(); foreach ($fields as $key => $value) { $field = (is_numeric($key)) ? $value : $key; if (isset($model->data[$model->alias][$field])) { $tempData[$field] = $model->data[$model->alias][$field]; if (is_array($model->data[$model->alias][$field])) { if (is_string($locale) && !empty($model->data[$model->alias][$field][$locale])) { $model->data[$model->alias][$field] = $model->data[$model->alias][$field][$locale]; } else { $values = array_values($model->data[$model->alias][$field]); $model->data[$model->alias][$field] = $values[0]; } } } } $this->runtime[$model->alias]['beforeSave'] = $tempData; return true; } /** * afterSave Callback * * @param Model $model Model the callback is called on * @param boolean $created Whether or not the save created a record. * @return void */ public function afterSave($model, $created) { if (!isset($this->runtime[$model->alias]['beforeSave'])) { return true; } $locale = $this->_getLocale($model); $tempData = $this->runtime[$model->alias]['beforeSave']; unset($this->runtime[$model->alias]['beforeSave']); $conditions = array('model' => $model->alias, 'foreign_key' => $model->id); $RuntimeModel = $this->translateModel($model); foreach ($tempData as $field => $value) { unset($conditions['content']); $conditions['field'] = $field; if (is_array($value)) { $conditions['locale'] = array_keys($value); } else { $conditions['locale'] = $locale; if (is_array($locale)) { $value = array($locale[0] => $value); } else { $value = array($locale => $value); } } $translations = $RuntimeModel->find('list', array('conditions' => $conditions, 'fields' => array($RuntimeModel->alias . '.locale', $RuntimeModel->alias . '.id'))); foreach ($value as $_locale => $_value) { $RuntimeModel->create(); $conditions['locale'] = $_locale; $conditions['content'] = $_value; if (array_key_exists($_locale, $translations)) { $RuntimeModel->save(array($RuntimeModel->alias => array_merge($conditions, array('id' => $translations[$_locale])))); } else { $RuntimeModel->save(array($RuntimeModel->alias => $conditions)); } } } } /** * afterDelete Callback * * @param Model $model Model the callback was run on. * @return void */ public function afterDelete($model) { $RuntimeModel = $this->translateModel($model); $conditions = array('model' => $model->alias, 'foreign_key' => $model->id); $RuntimeModel->deleteAll($conditions); } /** * Get selected locale for model * * @param Model $model Model the locale needs to be set/get on. * @return mixed string or false */ protected function _getLocale($model) { if (!isset($model->locale) || is_null($model->locale)) { $I18n = I18n::getInstance(); $I18n->l10n->get(Configure::read('Config.language')); $model->locale = $I18n->l10n->locale; } return $model->locale; } /** * Get instance of model for translations. * * If the model has a translateModel property set, this will be used as the class * name to find/use. If no translateModel property is found 'I18nModel' will be used. * * @param Model $model Model to get a translatemodel for. * @return Model */ public function translateModel($model) { if (!isset($this->runtime[$model->alias]['model'])) { if (!isset($model->translateModel) || empty($model->translateModel)) { $className = 'I18nModel'; } else { $className = $model->translateModel; } $this->runtime[$model->alias]['model'] = ClassRegistry::init($className, 'Model'); } if (!empty($model->translateTable) && $model->translateTable !== $this->runtime[$model->alias]['model']->useTable) { $this->runtime[$model->alias]['model']->setSource($model->translateTable); } elseif (empty($model->translateTable) && empty($model->translateModel)) { $this->runtime[$model->alias]['model']->setSource('i18n'); } return $this->runtime[$model->alias]['model']; } /** * Bind translation for fields, optionally with hasMany association for * fake field * * @param Model $model instance of model * @param string|array $fields string with field or array(field1, field2=>AssocName, field3) * @param boolean $reset * @return boolean */ public function bindTranslation($model, $fields, $reset = true) { if (is_string($fields)) { $fields = array($fields); } $associations = array(); $RuntimeModel = $this->translateModel($model); $default = array('className' => $RuntimeModel->alias, 'foreignKey' => 'foreign_key'); foreach ($fields as $key => $value) { if (is_numeric($key)) { $field = $value; $association = null; } else { $field = $key; $association = $value; } if (array_key_exists($field, $this->settings[$model->alias])) { unset($this->settings[$model->alias][$field]); } elseif (in_array($field, $this->settings[$model->alias])) { $this->settings[$model->alias] = array_merge(array_diff_assoc($this->settings[$model->alias], array($field))); } if (array_key_exists($field, $this->runtime[$model->alias]['fields'])) { unset($this->runtime[$model->alias]['fields'][$field]); } elseif (in_array($field, $this->runtime[$model->alias]['fields'])) { $this->runtime[$model->alias]['fields'] = array_merge(array_diff_assoc($this->runtime[$model->alias]['fields'], array($field))); } if (is_null($association)) { if ($reset) { $this->runtime[$model->alias]['fields'][] = $field; } else { $this->settings[$model->alias][] = $field; } } else { if ($reset) { $this->runtime[$model->alias]['fields'][$field] = $association; } else { $this->settings[$model->alias][$field] = $association; } foreach (array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany') as $type) { if (isset($model->{$type}[$association]) || isset($model->__backAssociation[$type][$association])) { trigger_error( __d('cake_dev', 'Association %s is already binded to model %s', $association, $model->alias), E_USER_ERROR ); return false; } } $associations[$association] = array_merge($default, array('conditions' => array( 'model' => $model->alias, $RuntimeModel->displayField => $field ))); } } if (!empty($associations)) { $model->bindModel(array('hasMany' => $associations), $reset); } return true; } /** * Unbind translation for fields, optionally unbinds hasMany association for * fake field * * @param Model $model instance of model * @param mixed $fields string with field, or array(field1, field2=>AssocName, field3), or null for * unbind all original translations * @return boolean */ public function unbindTranslation($model, $fields = null) { if (empty($fields) && empty($this->settings[$model->alias])) { return false; } if (empty($fields)) { return $this->unbindTranslation($model, $this->settings[$model->alias]); } if (is_string($fields)) { $fields = array($fields); } $RuntimeModel = $this->translateModel($model); $associations = array(); foreach ($fields as $key => $value) { if (is_numeric($key)) { $field = $value; $association = null; } else { $field = $key; $association = $value; } if (array_key_exists($field, $this->settings[$model->alias])) { unset($this->settings[$model->alias][$field]); } elseif (in_array($field, $this->settings[$model->alias])) { $this->settings[$model->alias] = array_merge(array_diff_assoc($this->settings[$model->alias], array($field))); } if (array_key_exists($field, $this->runtime[$model->alias]['fields'])) { unset($this->runtime[$model->alias]['fields'][$field]); } elseif (in_array($field, $this->runtime[$model->alias]['fields'])) { $this->runtime[$model->alias]['fields'] = array_merge(array_diff_assoc($this->runtime[$model->alias]['fields'], array($field))); } if (!is_null($association) && (isset($model->hasMany[$association]) || isset($model->__backAssociation['hasMany'][$association]))) { $associations[] = $association; } } if (!empty($associations)) { $model->unbindModel(array('hasMany' => $associations), false); } return true; } } /** * @package Cake.Model.Behavior */ class I18nModel extends AppModel { /** * Model name * * @var string */ public $name = 'I18nModel'; /** * Table name * * @var string */ public $useTable = 'i18n'; /** * Display field * * @var string */ public $displayField = 'field'; }
0001-bee
trunk/cakephp2/lib/Cake/Model/Behavior/TranslateBehavior.php
PHP
gpl3
16,602
<?php /** * Tree behavior class. * * Enables a model object to act as a node-based tree. * * PHP 5 * * CakePHP : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP Project * @package Cake.Model.Behavior * @since CakePHP v 1.2.0.4487 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Tree Behavior. * * Enables a model object to act as a node-based tree. Using Modified Preorder Tree Traversal * * @see http://en.wikipedia.org/wiki/Tree_traversal * @package Cake.Model.Behavior * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html */ class TreeBehavior extends ModelBehavior { /** * Errors * * @var array */ public $errors = array(); /** * Defaults * * @var array */ protected $_defaults = array( 'parent' => 'parent_id', 'left' => 'lft', 'right' => 'rght', 'scope' => '1 = 1', 'type' => 'nested', '__parentChange' => false, 'recursive' => -1 ); /** * Initiate Tree behavior * * @param Model $Model instance of model * @param array $config array of configuration settings. * @return void */ public function setup($Model, $config = array()) { if (isset($config[0])) { $config['type'] = $config[0]; unset($config[0]); } $settings = array_merge($this->_defaults, $config); if (in_array($settings['scope'], $Model->getAssociated('belongsTo'))) { $data = $Model->getAssociated($settings['scope']); $parent = $Model->{$settings['scope']}; $settings['scope'] = $Model->alias . '.' . $data['foreignKey'] . ' = ' . $parent->alias . '.' . $parent->primaryKey; $settings['recursive'] = 0; } $this->settings[$Model->alias] = $settings; } /** * After save method. Called after all saves * * Overriden to transparently manage setting the lft and rght fields if and only if the parent field is included in the * parameters to be saved. * * @param Model $Model Model instance. * @param boolean $created indicates whether the node just saved was created or updated * @return boolean true on success, false on failure */ public function afterSave($Model, $created) { extract($this->settings[$Model->alias]); if ($created) { if ((isset($Model->data[$Model->alias][$parent])) && $Model->data[$Model->alias][$parent]) { return $this->_setParent($Model, $Model->data[$Model->alias][$parent], $created); } } elseif ($__parentChange) { $this->settings[$Model->alias]['__parentChange'] = false; return $this->_setParent($Model, $Model->data[$Model->alias][$parent]); } } /** * Before delete method. Called before all deletes * * Will delete the current node and all children using the deleteAll method and sync the table * * @param Model $Model Model instance * @param boolean $cascade * @return boolean true to continue, false to abort the delete */ public function beforeDelete($Model, $cascade = true) { extract($this->settings[$Model->alias]); list($name, $data) = array($Model->alias, $Model->read()); $data = $data[$name]; if (!$data[$right] || !$data[$left]) { return true; } $diff = $data[$right] - $data[$left] + 1; if ($diff > 2) { if (is_string($scope)) { $scope = array($scope); } $scope[]["{$Model->alias}.{$left} BETWEEN ? AND ?"] = array($data[$left] + 1, $data[$right] - 1); $Model->deleteAll($scope); } $this->_sync($Model, $diff, '-', '> ' . $data[$right]); return true; } /** * Before save method. Called before all saves * * Overriden to transparently manage setting the lft and rght fields if and only if the parent field is included in the * parameters to be saved. For newly created nodes with NO parent the left and right field values are set directly by * this method bypassing the setParent logic. * * @since 1.2 * @param Model $Model Model instance * @return boolean true to continue, false to abort the save */ public function beforeSave($Model) { extract($this->settings[$Model->alias]); $this->_addToWhitelist($Model, array($left, $right)); if (!$Model->id) { if (array_key_exists($parent, $Model->data[$Model->alias]) && $Model->data[$Model->alias][$parent]) { $parentNode = $Model->find('first', array( 'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]), 'fields' => array($Model->primaryKey, $right), 'recursive' => $recursive )); if (!$parentNode) { return false; } list($parentNode) = array_values($parentNode); $Model->data[$Model->alias][$left] = 0; //$parentNode[$right]; $Model->data[$Model->alias][$right] = 0; //$parentNode[$right] + 1; } else { $edge = $this->_getMax($Model, $scope, $right, $recursive); $Model->data[$Model->alias][$left] = $edge + 1; $Model->data[$Model->alias][$right] = $edge + 2; } } elseif (array_key_exists($parent, $Model->data[$Model->alias])) { if ($Model->data[$Model->alias][$parent] != $Model->field($parent)) { $this->settings[$Model->alias]['__parentChange'] = true; } if (!$Model->data[$Model->alias][$parent]) { $Model->data[$Model->alias][$parent] = null; $this->_addToWhitelist($Model, $parent); } else { $values = $Model->find('first', array( 'conditions' => array($scope,$Model->escapeField() => $Model->id), 'fields' => array($Model->primaryKey, $parent, $left, $right ), 'recursive' => $recursive) ); if ($values === false) { return false; } list($node) = array_values($values); $parentNode = $Model->find('first', array( 'conditions' => array($scope, $Model->escapeField() => $Model->data[$Model->alias][$parent]), 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive )); if (!$parentNode) { return false; } list($parentNode) = array_values($parentNode); if (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) { return false; } elseif ($node[$Model->primaryKey] == $parentNode[$Model->primaryKey]) { return false; } } } return true; } /** * Get the number of child nodes * * If the direct parameter is set to true, only the direct children are counted (based upon the parent_id field) * If false is passed for the id parameter, all top level nodes are counted, or all nodes are counted. * * @param Model $Model Model instance * @param mixed $id The ID of the record to read or false to read all top level nodes * @param boolean $direct whether to count direct, or all, children * @return integer number of child nodes * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::childCount */ public function childCount($Model, $id = null, $direct = false) { if (is_array($id)) { extract (array_merge(array('id' => null), $id)); } if ($id === null && $Model->id) { $id = $Model->id; } elseif (!$id) { $id = null; } extract($this->settings[$Model->alias]); if ($direct) { return $Model->find('count', array('conditions' => array($scope, $Model->escapeField($parent) => $id))); } if ($id === null) { return $Model->find('count', array('conditions' => $scope)); } elseif ($Model->id === $id && isset($Model->data[$Model->alias][$left]) && isset($Model->data[$Model->alias][$right])) { $data = $Model->data[$Model->alias]; } else { $data = $Model->find('first', array('conditions' => array($scope, $Model->escapeField() => $id), 'recursive' => $recursive)); if (!$data) { return 0; } $data = $data[$Model->alias]; } return ($data[$right] - $data[$left] - 1) / 2; } /** * Get the child nodes of the current model * * If the direct parameter is set to true, only the direct children are returned (based upon the parent_id field) * If false is passed for the id parameter, top level, or all (depending on direct parameter appropriate) are counted. * * @param Model $Model Model instance * @param mixed $id The ID of the record to read * @param boolean $direct whether to return only the direct, or all, children * @param mixed $fields Either a single string of a field name, or an array of field names * @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC") defaults to the tree order * @param integer $limit SQL LIMIT clause, for calculating items per page. * @param integer $page Page number, for accessing paged data * @param integer $recursive The number of levels deep to fetch associated records * @return array Array of child nodes * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::children */ public function children($Model, $id = null, $direct = false, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) { if (is_array($id)) { extract (array_merge(array('id' => null), $id)); } $overrideRecursive = $recursive; if ($id === null && $Model->id) { $id = $Model->id; } elseif (!$id) { $id = null; } $name = $Model->alias; extract($this->settings[$Model->alias]); if (!is_null($overrideRecursive)) { $recursive = $overrideRecursive; } if (!$order) { $order = $Model->alias . '.' . $left . ' asc'; } if ($direct) { $conditions = array($scope, $Model->escapeField($parent) => $id); return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive')); } if (!$id) { $conditions = $scope; } else { $result = array_values((array)$Model->find('first', array( 'conditions' => array($scope, $Model->escapeField() => $id), 'fields' => array($left, $right), 'recursive' => $recursive ))); if (empty($result) || !isset($result[0])) { return array(); } $conditions = array($scope, $Model->escapeField($right) . ' <' => $result[0][$right], $Model->escapeField($left) . ' >' => $result[0][$left] ); } return $Model->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive')); } /** * A convenience method for returning a hierarchical array used for HTML select boxes * * @param Model $Model Model instance * @param mixed $conditions SQL conditions as a string or as an array('field' =>'value',...) * @param string $keyPath A string path to the key, i.e. "{n}.Post.id" * @param string $valuePath A string path to the value, i.e. "{n}.Post.title" * @param string $spacer The character or characters which will be repeated * @param integer $recursive The number of levels deep to fetch associated records * @return array An associative array of records, where the id is the key, and the display field is the value * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::generateTreeList */ public function generateTreeList($Model, $conditions = null, $keyPath = null, $valuePath = null, $spacer = '_', $recursive = null) { $overrideRecursive = $recursive; extract($this->settings[$Model->alias]); if (!is_null($overrideRecursive)) { $recursive = $overrideRecursive; } if ($keyPath == null && $valuePath == null && $Model->hasField($Model->displayField)) { $fields = array($Model->primaryKey, $Model->displayField, $left, $right); } else { $fields = null; } if ($keyPath == null) { $keyPath = '{n}.' . $Model->alias . '.' . $Model->primaryKey; } if ($valuePath == null) { $valuePath = array('{0}{1}', '{n}.tree_prefix', '{n}.' . $Model->alias . '.' . $Model->displayField); } elseif (is_string($valuePath)) { $valuePath = array('{0}{1}', '{n}.tree_prefix', $valuePath); } else { $valuePath[0] = '{' . (count($valuePath) - 1) . '}' . $valuePath[0]; $valuePath[] = '{n}.tree_prefix'; } $order = $Model->alias . '.' . $left . ' asc'; $results = $Model->find('all', compact('conditions', 'fields', 'order', 'recursive')); $stack = array(); foreach ($results as $i => $result) { while ($stack && ($stack[count($stack) - 1] < $result[$Model->alias][$right])) { array_pop($stack); } $results[$i]['tree_prefix'] = str_repeat($spacer,count($stack)); $stack[] = $result[$Model->alias][$right]; } if (empty($results)) { return array(); } return Set::combine($results, $keyPath, $valuePath); } /** * Get the parent node * * reads the parent id and returns this node * * @param Model $Model Model instance * @param mixed $id The ID of the record to read * @param string|array $fields * @param integer $recursive The number of levels deep to fetch associated records * @return array|boolean Array of data for the parent node * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getParentNode */ public function getParentNode($Model, $id = null, $fields = null, $recursive = null) { if (is_array($id)) { extract (array_merge(array('id' => null), $id)); } $overrideRecursive = $recursive; if (empty ($id)) { $id = $Model->id; } extract($this->settings[$Model->alias]); if (!is_null($overrideRecursive)) { $recursive = $overrideRecursive; } $parentId = $Model->find('first', array('conditions' => array($Model->primaryKey => $id), 'fields' => array($parent), 'recursive' => -1)); if ($parentId) { $parentId = $parentId[$Model->alias][$parent]; $parent = $Model->find('first', array('conditions' => array($Model->escapeField() => $parentId), 'fields' => $fields, 'recursive' => $recursive)); return $parent; } return false; } /** * Get the path to the given node * * @param Model $Model Model instance * @param mixed $id The ID of the record to read * @param mixed $fields Either a single string of a field name, or an array of field names * @param integer $recursive The number of levels deep to fetch associated records * @return array Array of nodes from top most parent to current node * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getPath */ public function getPath($Model, $id = null, $fields = null, $recursive = null) { if (is_array($id)) { extract (array_merge(array('id' => null), $id)); } $overrideRecursive = $recursive; if (empty ($id)) { $id = $Model->id; } extract($this->settings[$Model->alias]); if (!is_null($overrideRecursive)) { $recursive = $overrideRecursive; } $result = $Model->find('first', array('conditions' => array($Model->escapeField() => $id), 'fields' => array($left, $right), 'recursive' => $recursive)); if ($result) { $result = array_values($result); } else { return null; } $item = $result[0]; $results = $Model->find('all', array( 'conditions' => array($scope, $Model->escapeField($left) . ' <=' => $item[$left], $Model->escapeField($right) . ' >=' => $item[$right]), 'fields' => $fields, 'order' => array($Model->escapeField($left) => 'asc'), 'recursive' => $recursive )); return $results; } /** * Reorder the node without changing the parent. * * If the node is the last child, or is a top level node with no subsequent node this method will return false * * @param Model $Model Model instance * @param mixed $id The ID of the record to move * @param integer|boolean $number how many places to move the node or true to move to last position * @return boolean true on success, false on failure * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveDown */ public function moveDown($Model, $id = null, $number = 1) { if (is_array($id)) { extract (array_merge(array('id' => null), $id)); } if (!$number) { return false; } if (empty ($id)) { $id = $Model->id; } extract($this->settings[$Model->alias]); list($node) = array_values($Model->find('first', array( 'conditions' => array($scope, $Model->escapeField() => $id), 'fields' => array($Model->primaryKey, $left, $right, $parent), 'recursive' => $recursive ))); if ($node[$parent]) { list($parentNode) = array_values($Model->find('first', array( 'conditions' => array($scope, $Model->escapeField() => $node[$parent]), 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive ))); if (($node[$right] + 1) == $parentNode[$right]) { return false; } } $nextNode = $Model->find('first', array( 'conditions' => array($scope, $Model->escapeField($left) => ($node[$right] + 1)), 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive) ); if ($nextNode) { list($nextNode) = array_values($nextNode); } else { return false; } $edge = $this->_getMax($Model, $scope, $right, $recursive); $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right]); $this->_sync($Model, $nextNode[$left] - $node[$left], '-', 'BETWEEN ' . $nextNode[$left] . ' AND ' . $nextNode[$right]); $this->_sync($Model, $edge - $node[$left] - ($nextNode[$right] - $nextNode[$left]), '-', '> ' . $edge); if (is_int($number)) { $number--; } if ($number) { $this->moveDown($Model, $id, $number); } return true; } /** * Reorder the node without changing the parent. * * If the node is the first child, or is a top level node with no previous node this method will return false * * @param Model $Model Model instance * @param mixed $id The ID of the record to move * @param integer|boolean $number how many places to move the node, or true to move to first position * @return boolean true on success, false on failure * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::moveUp */ public function moveUp($Model, $id = null, $number = 1) { if (is_array($id)) { extract (array_merge(array('id' => null), $id)); } if (!$number) { return false; } if (empty ($id)) { $id = $Model->id; } extract($this->settings[$Model->alias]); list($node) = array_values($Model->find('first', array( 'conditions' => array($scope, $Model->escapeField() => $id), 'fields' => array($Model->primaryKey, $left, $right, $parent ), 'recursive' => $recursive ))); if ($node[$parent]) { list($parentNode) = array_values($Model->find('first', array( 'conditions' => array($scope, $Model->escapeField() => $node[$parent]), 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive ))); if (($node[$left] - 1) == $parentNode[$left]) { return false; } } $previousNode = $Model->find('first', array( 'conditions' => array($scope, $Model->escapeField($right) => ($node[$left] - 1)), 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive )); if ($previousNode) { list($previousNode) = array_values($previousNode); } else { return false; } $edge = $this->_getMax($Model, $scope, $right, $recursive); $this->_sync($Model, $edge - $previousNode[$left] +1, '+', 'BETWEEN ' . $previousNode[$left] . ' AND ' . $previousNode[$right]); $this->_sync($Model, $node[$left] - $previousNode[$left], '-', 'BETWEEN ' .$node[$left] . ' AND ' . $node[$right]); $this->_sync($Model, $edge - $previousNode[$left] - ($node[$right] - $node[$left]), '-', '> ' . $edge); if (is_int($number)) { $number--; } if ($number) { $this->moveUp($Model, $id, $number); } return true; } /** * Recover a corrupted tree * * The mode parameter is used to specify the source of info that is valid/correct. The opposite source of data * will be populated based upon that source of info. E.g. if the MPTT fields are corrupt or empty, with the $mode * 'parent' the values of the parent_id field will be used to populate the left and right fields. The missingParentAction * parameter only applies to "parent" mode and determines what to do if the parent field contains an id that is not present. * * @todo Could be written to be faster, *maybe*. Ideally using a subquery and putting all the logic burden on the DB. * @param Model $Model Model instance * @param string $mode parent or tree * @param mixed $missingParentAction 'return' to do nothing and return, 'delete' to * delete, or the id of the parent to set as the parent_id * @return boolean true on success, false on failure * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::recover */ public function recover($Model, $mode = 'parent', $missingParentAction = null) { if (is_array($mode)) { extract (array_merge(array('mode' => 'parent'), $mode)); } extract($this->settings[$Model->alias]); $Model->recursive = $recursive; if ($mode == 'parent') { $Model->bindModel(array('belongsTo' => array('VerifyParent' => array( 'className' => $Model->alias, 'foreignKey' => $parent, 'fields' => array($Model->primaryKey, $left, $right, $parent), )))); $missingParents = $Model->find('list', array( 'recursive' => 0, 'conditions' => array($scope, array( 'NOT' => array($Model->escapeField($parent) => null), $Model->VerifyParent->escapeField() => null )) )); $Model->unbindModel(array('belongsTo' => array('VerifyParent'))); if ($missingParents) { if ($missingParentAction == 'return') { foreach ($missingParents as $id => $display) { $this->errors[] = 'cannot find the parent for ' . $Model->alias . ' with id ' . $id . '(' . $display . ')'; } return false; } elseif ($missingParentAction == 'delete') { $Model->deleteAll(array($Model->primaryKey => array_flip($missingParents))); } else { $Model->updateAll(array($parent => $missingParentAction), array($Model->escapeField($Model->primaryKey) => array_flip($missingParents))); } } $count = 1; foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey), 'order' => $left)) as $array) { $Model->id = $array[$Model->alias][$Model->primaryKey]; $lft = $count++; $rght = $count++; $Model->save(array($left => $lft, $right => $rght), array('callbacks' => false)); } foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) { $Model->create(); $Model->id = $array[$Model->alias][$Model->primaryKey]; $this->_setParent($Model, $array[$Model->alias][$parent]); } } else { $db = ConnectionManager::getDataSource($Model->useDbConfig); foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) { $path = $this->getPath($Model, $array[$Model->alias][$Model->primaryKey]); if ($path == null || count($path) < 2) { $parentId = null; } else { $parentId = $path[count($path) - 2][$Model->alias][$Model->primaryKey]; } $Model->updateAll(array($parent => $db->value($parentId, $parent)), array($Model->escapeField() => $array[$Model->alias][$Model->primaryKey])); } } return true; } /** * Reorder method. * * Reorders the nodes (and child nodes) of the tree according to the field and direction specified in the parameters. * This method does not change the parent of any node. * * Requires a valid tree, by default it verifies the tree before beginning. * * Options: * * - 'id' id of record to use as top node for reordering * - 'field' Which field to use in reordeing defaults to displayField * - 'order' Direction to order either DESC or ASC (defaults to ASC) * - 'verify' Whether or not to verify the tree before reorder. defaults to true. * * @param Model $Model Model instance * @param array $options array of options to use in reordering. * @return boolean true on success, false on failure * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::reorder */ public function reorder($Model, $options = array()) { $options = array_merge(array('id' => null, 'field' => $Model->displayField, 'order' => 'ASC', 'verify' => true), $options); extract($options); if ($verify && !$this->verify($Model)) { return false; } $verify = false; extract($this->settings[$Model->alias]); $fields = array($Model->primaryKey, $field, $left, $right); $sort = $field . ' ' . $order; $nodes = $this->children($Model, $id, true, $fields, $sort, null, null, $recursive); $cacheQueries = $Model->cacheQueries; $Model->cacheQueries = false; if ($nodes) { foreach ($nodes as $node) { $id = $node[$Model->alias][$Model->primaryKey]; $this->moveDown($Model, $id, true); if ($node[$Model->alias][$left] != $node[$Model->alias][$right] - 1) { $this->reorder($Model, compact('id', 'field', 'order', 'verify')); } } } $Model->cacheQueries = $cacheQueries; return true; } /** * Remove the current node from the tree, and reparent all children up one level. * * If the parameter delete is false, the node will become a new top level node. Otherwise the node will be deleted * after the children are reparented. * * @param Model $Model Model instance * @param mixed $id The ID of the record to remove * @param boolean $delete whether to delete the node after reparenting children (if any) * @return boolean true on success, false on failure * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::removeFromTree */ public function removeFromTree($Model, $id = null, $delete = false) { if (is_array($id)) { extract (array_merge(array('id' => null), $id)); } extract($this->settings[$Model->alias]); list($node) = array_values($Model->find('first', array( 'conditions' => array($scope, $Model->escapeField() => $id), 'fields' => array($Model->primaryKey, $left, $right, $parent), 'recursive' => $recursive ))); if ($node[$right] == $node[$left] + 1) { if ($delete) { return $Model->delete($id); } else { $Model->id = $id; return $Model->saveField($parent, null); } } elseif ($node[$parent]) { list($parentNode) = array_values($Model->find('first', array( 'conditions' => array($scope, $Model->escapeField() => $node[$parent]), 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive ))); } else { $parentNode[$right] = $node[$right] + 1; } $db = ConnectionManager::getDataSource($Model->useDbConfig); $Model->updateAll( array($parent => $db->value($node[$parent], $parent)), array($Model->escapeField($parent) => $node[$Model->primaryKey]) ); $this->_sync($Model, 1, '-', 'BETWEEN ' . ($node[$left] + 1) . ' AND ' . ($node[$right] - 1)); $this->_sync($Model, 2, '-', '> ' . ($node[$right])); $Model->id = $id; if ($delete) { $Model->updateAll( array( $Model->escapeField($left) => 0, $Model->escapeField($right) => 0, $Model->escapeField($parent) => null ), array($Model->escapeField() => $id) ); return $Model->delete($id); } else { $edge = $this->_getMax($Model, $scope, $right, $recursive); if ($node[$right] == $edge) { $edge = $edge - 2; } $Model->id = $id; return $Model->save( array($left => $edge + 1, $right => $edge + 2, $parent => null), array('callbacks' => false) ); } } /** * Check if the current tree is valid. * * Returns true if the tree is valid otherwise an array of (type, incorrect left/right index, message) * * @param Model $Model Model instance * @return mixed true if the tree is valid or empty, otherwise an array of (error type [index, node], * [incorrect left/right index,node id], message) * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::verify */ public function verify($Model) { extract($this->settings[$Model->alias]); if (!$Model->find('count', array('conditions' => $scope))) { return true; } $min = $this->_getMin($Model, $scope, $left, $recursive); $edge = $this->_getMax($Model, $scope, $right, $recursive); $errors = array(); for ($i = $min; $i <= $edge; $i++) { $count = $Model->find('count', array('conditions' => array( $scope, 'OR' => array($Model->escapeField($left) => $i, $Model->escapeField($right) => $i) ))); if ($count != 1) { if ($count == 0) { $errors[] = array('index', $i, 'missing'); } else { $errors[] = array('index', $i, 'duplicate'); } } } $node = $Model->find('first', array('conditions' => array($scope, $Model->escapeField($right) . '< ' . $Model->escapeField($left)), 'recursive' => 0)); if ($node) { $errors[] = array('node', $node[$Model->alias][$Model->primaryKey], 'left greater than right.'); } $Model->bindModel(array('belongsTo' => array('VerifyParent' => array( 'className' => $Model->alias, 'foreignKey' => $parent, 'fields' => array($Model->primaryKey, $left, $right, $parent) )))); foreach ($Model->find('all', array('conditions' => $scope, 'recursive' => 0)) as $instance) { if (is_null($instance[$Model->alias][$left]) || is_null($instance[$Model->alias][$right])) { $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'has invalid left or right values'); } elseif ($instance[$Model->alias][$left] == $instance[$Model->alias][$right]) { $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'left and right values identical'); } elseif ($instance[$Model->alias][$parent]) { if (!$instance['VerifyParent'][$Model->primaryKey]) { $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'The parent node ' . $instance[$Model->alias][$parent] . ' doesn\'t exist'); } elseif ($instance[$Model->alias][$left] < $instance['VerifyParent'][$left]) { $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'left less than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').'); } elseif ($instance[$Model->alias][$right] > $instance['VerifyParent'][$right]) { $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'right greater than parent (node ' . $instance['VerifyParent'][$Model->primaryKey] . ').'); } } elseif ($Model->find('count', array('conditions' => array($scope, $Model->escapeField($left) . ' <' => $instance[$Model->alias][$left], $Model->escapeField($right) . ' >' => $instance[$Model->alias][$right]), 'recursive' => 0))) { $errors[] = array('node', $instance[$Model->alias][$Model->primaryKey], 'The parent field is blank, but has a parent'); } } if ($errors) { return $errors; } return true; } /** * Sets the parent of the given node * * The force parameter is used to override the "don't change the parent to the current parent" logic in the event * of recovering a corrupted table, or creating new nodes. Otherwise it should always be false. In reality this * method could be private, since calling save with parent_id set also calls setParent * * @param Model $Model Model instance * @param mixed $parentId * @param boolean $created * @return boolean true on success, false on failure */ protected function _setParent($Model, $parentId = null, $created = false) { extract($this->settings[$Model->alias]); list($node) = array_values($Model->find('first', array( 'conditions' => array($scope, $Model->escapeField() => $Model->id), 'fields' => array($Model->primaryKey, $parent, $left, $right), 'recursive' => $recursive ))); $edge = $this->_getMax($Model, $scope, $right, $recursive, $created); if (empty ($parentId)) { $this->_sync($Model, $edge - $node[$left] + 1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created); $this->_sync($Model, $node[$right] - $node[$left] + 1, '-', '> ' . $node[$left], $created); } else { $values = $Model->find('first', array( 'conditions' => array($scope, $Model->escapeField() => $parentId), 'fields' => array($Model->primaryKey, $left, $right), 'recursive' => $recursive )); if ($values === false) { return false; } $parentNode = array_values($values); if (empty($parentNode) || empty($parentNode[0])) { return false; } $parentNode = $parentNode[0]; if (($Model->id == $parentId)) { return false; } elseif (($node[$left] < $parentNode[$left]) && ($parentNode[$right] < $node[$right])) { return false; } if (empty ($node[$left]) && empty ($node[$right])) { $this->_sync($Model, 2, '+', '>= ' . $parentNode[$right], $created); $result = $Model->save( array($left => $parentNode[$right], $right => $parentNode[$right] + 1, $parent => $parentId), array('validate' => false, 'callbacks' => false) ); $Model->data = $result; } else { $this->_sync($Model, $edge - $node[$left] +1, '+', 'BETWEEN ' . $node[$left] . ' AND ' . $node[$right], $created); $diff = $node[$right] - $node[$left] + 1; if ($node[$left] > $parentNode[$left]) { if ($node[$right] < $parentNode[$right]) { $this->_sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created); $this->_sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created); } else { $this->_sync($Model, $diff, '+', 'BETWEEN ' . $parentNode[$right] . ' AND ' . $node[$right], $created); $this->_sync($Model, $edge - $parentNode[$right] + 1, '-', '> ' . $edge, $created); } } else { $this->_sync($Model, $diff, '-', 'BETWEEN ' . $node[$right] . ' AND ' . ($parentNode[$right] - 1), $created); $this->_sync($Model, $edge - $parentNode[$right] + $diff + 1, '-', '> ' . $edge, $created); } } } return true; } /** * get the maximum index value in the table. * * @param Model $Model * @param string $scope * @param string $right * @param integer $recursive * @param boolean $created * @return integer */ protected function _getMax($Model, $scope, $right, $recursive = -1, $created = false) { $db = ConnectionManager::getDataSource($Model->useDbConfig); if ($created) { if (is_string($scope)) { $scope .= " AND {$Model->alias}.{$Model->primaryKey} <> "; $scope .= $db->value($Model->id, $Model->getColumnType($Model->primaryKey)); } else { $scope['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id; } } $name = $Model->alias . '.' . $right; list($edge) = array_values($Model->find('first', array( 'conditions' => $scope, 'fields' => $db->calculate($Model, 'max', array($name, $right)), 'recursive' => $recursive ))); return (empty($edge[$right])) ? 0 : $edge[$right]; } /** * get the minimum index value in the table. * * @param Model $Model * @param string $scope * @param string $left * @param integer $recursive * @return integer */ protected function _getMin($Model, $scope, $left, $recursive = -1) { $db = ConnectionManager::getDataSource($Model->useDbConfig); $name = $Model->alias . '.' . $left; list($edge) = array_values($Model->find('first', array( 'conditions' => $scope, 'fields' => $db->calculate($Model, 'min', array($name, $left)), 'recursive' => $recursive ))); return (empty($edge[$left])) ? 0 : $edge[$left]; } /** * Table sync method. * * Handles table sync operations, Taking account of the behavior scope. * * @param Model $Model * @param integer $shift * @param string $dir * @param array $conditions * @param boolean $created * @param string $field * @return void */ protected function _sync($Model, $shift, $dir = '+', $conditions = array(), $created = false, $field = 'both') { $ModelRecursive = $Model->recursive; extract($this->settings[$Model->alias]); $Model->recursive = $recursive; if ($field == 'both') { $this->_sync($Model, $shift, $dir, $conditions, $created, $left); $field = $right; } if (is_string($conditions)) { $conditions = array("{$Model->alias}.{$field} {$conditions}"); } if (($scope != '1 = 1' && $scope !== true) && $scope) { $conditions[] = $scope; } if ($created) { $conditions['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id; } $Model->updateAll(array($Model->alias . '.' . $field => $Model->escapeField($field) . ' ' . $dir . ' ' . $shift), $conditions); $Model->recursive = $ModelRecursive; } }
0001-bee
trunk/cakephp2/lib/Cake/Model/Behavior/TreeBehavior.php
PHP
gpl3
36,363
<?php /** * Application model for Cake. * * This file is application-wide model file. You can put all * application-wide model-related methods here. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Model', 'Model'); /** * Application model for Cake. * * This is a placeholder class. * Create the same file in app/Model/AppModel.php * Add your application-wide methods to the class, your models will inherit them. * * @package Cake.Model */ class AppModel extends Model { }
0001-bee
trunk/cakephp2/lib/Cake/Model/AppModel.php
PHP
gpl3
1,036
<?php /** * DataSource base class * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model.Datasource * @since CakePHP(tm) v 0.10.5.1790 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * DataSource base class * * @package Cake.Model.Datasource */ class DataSource extends Object { /** * Are we connected to the DataSource? * * @var boolean */ public $connected = false; /** * The default configuration of a specific DataSource * * @var array */ protected $_baseConfig = array(); /** * Holds references to descriptions loaded by the DataSource * * @var array */ protected $_descriptions = array(); /** * Holds a list of sources (tables) contained in the DataSource * * @var array */ protected $_sources = null; /** * The DataSource configuration * * @var array */ public $config = array(); /** * Whether or not this DataSource is in the middle of a transaction * * @var boolean */ protected $_transactionStarted = false; /** * Whether or not source data like available tables and schema descriptions * should be cached * * @var boolean */ public $cacheSources = true; /** * Constructor. * * @param array $config Array of configuration information for the datasource. */ public function __construct($config = array()) { parent::__construct(); $this->setConfig($config); } /** * Caches/returns cached results for child instances * * @param mixed $data * @return array Array of sources available in this datasource. */ public function listSources($data = null) { if ($this->cacheSources === false) { return null; } if ($this->_sources !== null) { return $this->_sources; } $key = ConnectionManager::getSourceName($this) . '_' . $this->config['database'] . '_list'; $key = preg_replace('/[^A-Za-z0-9_\-.+]/', '_', $key); $sources = Cache::read($key, '_cake_model_'); if (empty($sources)) { $sources = $data; Cache::write($key, $data, '_cake_model_'); } return $this->_sources = $sources; } /** * Returns a Model description (metadata) or null if none found. * * @param Model|string $model * @return array Array of Metadata for the $model */ public function describe($model) { if ($this->cacheSources === false) { return null; } if (is_string($model)) { $table = $model; } else { $table = $model->tablePrefix . $model->table; } if (isset($this->_descriptions[$table])) { return $this->_descriptions[$table]; } $cache = $this->_cacheDescription($table); if ($cache !== null) { $this->_descriptions[$table] =& $cache; return $cache; } return null; } /** * Begin a transaction * * @return boolean Returns true if a transaction is not in progress */ public function begin() { return !$this->_transactionStarted; } /** * Commit a transaction * * @return boolean Returns true if a transaction is in progress */ public function commit() { return $this->_transactionStarted; } /** * Rollback a transaction * * @return boolean Returns true if a transaction is in progress */ public function rollback() { return $this->_transactionStarted; } /** * Converts column types to basic types * * @param string $real Real column type (i.e. "varchar(255)") * @return string Abstract column type (i.e. "string") */ public function column($real) { return false; } /** * Used to create new records. The "C" CRUD. * * To-be-overridden in subclasses. * * @param Model $model The Model to be created. * @param array $fields An Array of fields to be saved. * @param array $values An Array of values to save. * @return boolean success */ public function create(Model $model, $fields = null, $values = null) { return false; } /** * Used to read records from the Datasource. The "R" in CRUD * * To-be-overridden in subclasses. * * @param Model $model The model being read. * @param array $queryData An array of query data used to find the data you want * @return mixed */ public function read(Model $model, $queryData = array()) { return false; } /** * Update a record(s) in the datasource. * * To-be-overridden in subclasses. * * @param Model $model Instance of the model class being updated * @param array $fields Array of fields to be updated * @param array $values Array of values to be update $fields to. * @return boolean Success */ public function update(Model $model, $fields = null, $values = null) { return false; } /** * Delete a record(s) in the datasource. * * To-be-overridden in subclasses. * * @param Model $model The model class having record(s) deleted * @param mixed $conditions The conditions to use for deleting. * @return void */ public function delete(Model $model, $id = null) { return false; } /** * Returns the ID generated from the previous INSERT operation. * * @param mixed $source * @return mixed Last ID key generated in previous INSERT */ public function lastInsertId($source = null) { return false; } /** * Returns the number of rows returned by last operation. * * @param mixed $source * @return integer Number of rows returned by last operation */ public function lastNumRows($source = null) { return false; } /** * Returns the number of rows affected by last query. * * @param mixed $source * @return integer Number of rows affected by last query. */ public function lastAffected($source = null) { return false; } /** * Check whether the conditions for the Datasource being available * are satisfied. Often used from connect() to check for support * before establishing a connection. * * @return boolean Whether or not the Datasources conditions for use are met. */ public function enabled() { return true; } /** * Sets the configuration for the DataSource. * Merges the $config information with the _baseConfig and the existing $config property. * * @param array $config The configuration array * @return void */ public function setConfig($config = array()) { $this->config = array_merge($this->_baseConfig, $this->config, $config); } /** * Cache the DataSource description * * @param string $object The name of the object (model) to cache * @param mixed $data The description of the model, usually a string or array * @return mixed */ protected function _cacheDescription($object, $data = null) { if ($this->cacheSources === false) { return null; } if ($data !== null) { $this->_descriptions[$object] =& $data; } $key = ConnectionManager::getSourceName($this) . '_' . $object; $cache = Cache::read($key, '_cake_model_'); if (empty($cache)) { $cache = $data; Cache::write($key, $cache, '_cake_model_'); } return $cache; } /** * Replaces `{$__cakeID__$}` and `{$__cakeForeignKey__$}` placeholders in query data. * * @param string $query Query string needing replacements done. * @param array $data Array of data with values that will be inserted in placeholders. * @param string $association Name of association model being replaced * @param array $assocData * @param Model $model Instance of the model to replace $__cakeID__$ * @param Model $linkModel Instance of model to replace $__cakeForeignKey__$ * @param array $stack * @return string String of query data with placeholders replaced. * @todo Remove and refactor $assocData, ensure uses of the method have the param removed too. */ public function insertQueryData($query, $data, $association, $assocData, Model $model, Model $linkModel, $stack) { $keys = array('{$__cakeID__$}', '{$__cakeForeignKey__$}'); foreach ($keys as $key) { $val = null; $type = null; if (strpos($query, $key) !== false) { switch ($key) { case '{$__cakeID__$}': if (isset($data[$model->alias]) || isset($data[$association])) { if (isset($data[$model->alias][$model->primaryKey])) { $val = $data[$model->alias][$model->primaryKey]; } elseif (isset($data[$association][$model->primaryKey])) { $val = $data[$association][$model->primaryKey]; } } else { $found = false; foreach (array_reverse($stack) as $assoc) { if (isset($data[$assoc]) && isset($data[$assoc][$model->primaryKey])) { $val = $data[$assoc][$model->primaryKey]; $found = true; break; } } if (!$found) { $val = ''; } } $type = $model->getColumnType($model->primaryKey); break; case '{$__cakeForeignKey__$}': foreach ($model->associations() as $id => $name) { foreach ($model->$name as $assocName => $assoc) { if ($assocName === $association) { if (isset($assoc['foreignKey'])) { $foreignKey = $assoc['foreignKey']; $assocModel = $model->$assocName; $type = $assocModel->getColumnType($assocModel->primaryKey); if (isset($data[$model->alias][$foreignKey])) { $val = $data[$model->alias][$foreignKey]; } elseif (isset($data[$association][$foreignKey])) { $val = $data[$association][$foreignKey]; } else { $found = false; foreach (array_reverse($stack) as $assoc) { if (isset($data[$assoc]) && isset($data[$assoc][$foreignKey])) { $val = $data[$assoc][$foreignKey]; $found = true; break; } } if (!$found) { $val = ''; } } } break 3; } } } break; } if (empty($val) && $val !== '0') { return false; } $query = str_replace($key, $this->value($val, $type), $query); } } return $query; } /** * To-be-overridden in subclasses. * * @param Model $model Model instance * @param string $key Key name to make * @return string Key name for model. */ public function resolveKey(Model $model, $key) { return $model->alias . $key; } /** * Closes the current datasource. * */ public function __destruct() { if ($this->_transactionStarted) { $this->rollback(); } if ($this->connected) { $this->close(); } } }
0001-bee
trunk/cakephp2/lib/Cake/Model/Datasource/DataSource.php
PHP
gpl3
10,532
<?php /** * Database Session save handler. Allows saving session information into a model. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model.Datasource.Session * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * DatabaseSession provides methods to be used with CakeSession. * * @package Cake.Model.Datasource.Session */ class DatabaseSession implements CakeSessionHandlerInterface { /** * Reference to the model handling the session data * * @var Model */ protected $_model; /** * Number of seconds to mark the session as expired * * @var int */ protected $_timeout; /** * Constructor. Looks at Session configuration information and * sets up the session model. * */ public function __construct() { $modelName = Configure::read('Session.handler.model'); if (empty($modelName)) { $settings = array( 'class' =>'Session', 'alias' => 'Session', 'table' => 'cake_sessions', ); } else { $settings = array( 'class' =>$modelName, 'alias' => 'Session', ); } $this->_model = ClassRegistry::init($settings); $this->_timeout = Configure::read('Session.timeout') * 60; } /** * Method called on open of a database session. * * @return boolean Success */ public function open() { return true; } /** * Method called on close of a database session. * * @return boolean Success */ public function close() { $probability = mt_rand(1, 150); if ($probability <= 3) { $this->gc(); } return true; } /** * Method used to read from a database session. * * @param mixed $id The key of the value to read * @return mixed The value of the key or false if it does not exist */ public function read($id) { $row = $this->_model->find('first', array( 'conditions' => array($this->_model->primaryKey => $id) )); if (empty($row[$this->_model->alias]['data'])) { return false; } return $row[$this->_model->alias]['data']; } /** * Helper function called on write for database sessions. * * @param integer $id ID that uniquely identifies session in database * @param mixed $data The value of the data to be saved. * @return boolean True for successful write, false otherwise. */ public function write($id, $data) { if (!$id) { return false; } $expires = time() + $this->_timeout; $record = compact('id', 'data', 'expires'); $record[$this->_model->primaryKey] = $id; return $this->_model->save($record); } /** * Method called on the destruction of a database session. * * @param integer $id ID that uniquely identifies session in database * @return boolean True for successful delete, false otherwise. */ public function destroy($id) { return $this->_model->delete($id); } /** * Helper function called on gc for database sessions. * * @param integer $expires Timestamp (defaults to current time) * @return boolean Success */ public function gc($expires = null) { if (!$expires) { $expires = time(); } return $this->_model->deleteAll(array($this->_model->alias . ".expires <" => $expires), false, false); } /** * Closes the session before the objects handling it become unavailable * * @return void */ public function __destruct() { session_write_close(); } }
0001-bee
trunk/cakephp2/lib/Cake/Model/Datasource/Session/DatabaseSession.php
PHP
gpl3
3,693
<?php /** * Cache Session save handler. Allows saving session information into Cache. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model.Datasource.Session * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Cache', 'Cache'); /** * CacheSession provides method for saving sessions into a Cache engine. Used with CakeSession * * @package Cake.Model.Datasource.Session * @see CakeSession for configuration information. */ class CacheSession implements CakeSessionHandlerInterface { /** * Method called on open of a database session. * * @return boolean Success */ public function open() { return true; } /** * Method called on close of a database session. * * @return boolean Success */ public function close() { $probability = mt_rand(1, 150); if ($probability <= 3) { Cache::gc(); } return true; } /** * Method used to read from a database session. * * @param mixed $id The key of the value to read * @return mixed The value of the key or false if it does not exist */ public function read($id) { return Cache::read($id, Configure::read('Session.handler.config')); } /** * Helper function called on write for database sessions. * * @param integer $id ID that uniquely identifies session in database * @param mixed $data The value of the data to be saved. * @return boolean True for successful write, false otherwise. */ public function write($id, $data) { return Cache::write($id, $data, Configure::read('Session.handler.config')); } /** * Method called on the destruction of a database session. * * @param integer $id ID that uniquely identifies session in database * @return boolean True for successful delete, false otherwise. */ public function destroy($id) { return Cache::delete($id, Configure::read('Session.handler.config')); } /** * Helper function called on gc for database sessions. * * @param integer $expires Timestamp (defaults to current time) * @return boolean Success */ public function gc($expires = null) { return Cache::gc(); } /** * Closes the session before the objects handling it become unavailable * * @return void */ public function __destruct() { session_write_close(); } }
0001-bee
trunk/cakephp2/lib/Cake/Model/Datasource/Session/CacheSession.php
PHP
gpl3
2,678
<?php /** * Dbo Source * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model.Datasource * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('DataSource', 'Model/Datasource'); App::uses('String', 'Utility'); App::uses('View', 'View'); /** * DboSource * * Creates DBO-descendant objects from a given db connection configuration * * @package Cake.Model.Datasource */ class DboSource extends DataSource { /** * Description string for this Database Data Source. * * @var string */ public $description = "Database Data Source"; /** * index definition, standard cake, primary, index, unique * * @var array */ public $index = array('PRI' => 'primary', 'MUL' => 'index', 'UNI' => 'unique'); /** * Database keyword used to assign aliases to identifiers. * * @var string */ public $alias = 'AS '; /** * Caches result from query parsing operations. Cached results for both DboSource::name() and * DboSource::conditions() will be stored here. Method caching uses `crc32()` which is * fast but can collisions more easily than other hashing algorithms. If you have problems * with collisions, set DboSource::$cacheMethods to false. * * @var array */ public static $methodCache = array(); /** * Whether or not to cache the results of DboSource::name() and DboSource::conditions() * into the memory cache. Set to false to disable the use of the memory cache. * * @var boolean. */ public $cacheMethods = true; /** * Print full query debug info? * * @var boolean */ public $fullDebug = false; /** * String to hold how many rows were affected by the last SQL operation. * * @var string */ public $affected = null; /** * Number of rows in current resultset * * @var integer */ public $numRows = null; /** * Time the last query took * * @var integer */ public $took = null; /** * Result * * @var array */ protected $_result = null; /** * Queries count. * * @var integer */ protected $_queriesCnt = 0; /** * Total duration of all queries. * * @var integer */ protected $_queriesTime = null; /** * Log of queries executed by this DataSource * * @var array */ protected $_queriesLog = array(); /** * Maximum number of items in query log * * This is to prevent query log taking over too much memory. * * @var integer Maximum number of queries in the queries log. */ protected $_queriesLogMax = 200; /** * Caches serialzed results of executed queries * * @var array Maximum number of queries in the queries log. */ protected $_queryCache = array(); /** * A reference to the physical connection of this DataSource * * @var array */ protected $_connection = null; /** * The DataSource configuration key name * * @var string */ public $configKeyName = null; /** * The starting character that this DataSource uses for quoted identifiers. * * @var string */ public $startQuote = null; /** * The ending character that this DataSource uses for quoted identifiers. * * @var string */ public $endQuote = null; /** * The set of valid SQL operations usable in a WHERE statement * * @var array */ protected $_sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', 'regexp', 'similar to'); /** * Indicates the level of nested transactions * * @var integer */ protected $_transactionNesting = 0; /** * Index of basic SQL commands * * @var array */ protected $_commands = array( 'begin' => 'BEGIN', 'commit' => 'COMMIT', 'rollback' => 'ROLLBACK' ); /** * Separator string for virtualField composition * * @var string */ public $virtualFieldSeparator = '__'; /** * List of table engine specific parameters used on table creating * * @var array */ public $tableParameters = array(); /** * List of engine specific additional field parameters used on table creating * * @var array */ public $fieldParameters = array(); /** * Indicates whether there was a change on the cached results on the methods of this class * This will be used for storing in a more persistent cache * * @var boolean */ protected $_methodCacheChange = false; /** * Constructor * * @param array $config Array of configuration information for the Datasource. * @param boolean $autoConnect Whether or not the datasource should automatically connect. */ public function __construct($config = null, $autoConnect = true) { if (!isset($config['prefix'])) { $config['prefix'] = ''; } parent::__construct($config); $this->fullDebug = Configure::read('debug') > 1; if (!$this->enabled()) { throw new MissingConnectionException(array( 'class' => get_class($this) )); } if ($autoConnect) { $this->connect(); } } /** * Reconnects to database server with optional new settings * * @param array $config An array defining the new configuration settings * @return boolean True on success, false on failure */ public function reconnect($config = array()) { $this->disconnect(); $this->setConfig($config); $this->_sources = null; return $this->connect(); } /** * Disconnects from database. * * @return boolean True if the database could be disconnected, else false */ public function disconnect() { if ($this->_result instanceof PDOStatement) { $this->_result->closeCursor(); } unset($this->_connection); $this->connected = false; return true; } /** * Get the underlying connection object. * * @return PDOConnection */ public function getConnection() { return $this->_connection; } /** * Returns a quoted and escaped string of $data for use in an SQL statement. * * @param string $data String to be prepared for use in an SQL statement * @param string $column The column into which this data will be inserted * @return string Quoted and escaped data */ public function value($data, $column = null) { if (is_array($data) && !empty($data)) { return array_map( array(&$this, 'value'), $data, array_fill(0, count($data), $column) ); } elseif (is_object($data) && isset($data->type, $data->value)) { if ($data->type == 'identifier') { return $this->name($data->value); } elseif ($data->type == 'expression') { return $data->value; } } elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) { return $data; } if ($data === null || (is_array($data) && empty($data))) { return 'NULL'; } if (empty($column)) { $column = $this->introspectType($data); } switch ($column) { case 'binary': return $this->_connection->quote($data, PDO::PARAM_LOB); break; case 'boolean': return $this->_connection->quote($this->boolean($data, true), PDO::PARAM_BOOL); break; case 'string': case 'text': return $this->_connection->quote($data, PDO::PARAM_STR); default: if ($data === '') { return 'NULL'; } if (is_float($data)) { return str_replace(',', '.', strval($data)); } if ((is_int($data) || $data === '0') || ( is_numeric($data) && strpos($data, ',') === false && $data[0] != '0' && strpos($data, 'e') === false) ) { return $data; } return $this->_connection->quote($data); break; } } /** * Returns an object to represent a database identifier in a query. Expression objects * are not sanitized or esacped. * * @param string $identifier A SQL expression to be used as an identifier * @return stdClass An object representing a database identifier to be used in a query */ public function identifier($identifier) { $obj = new stdClass(); $obj->type = 'identifier'; $obj->value = $identifier; return $obj; } /** * Returns an object to represent a database expression in a query. Expression objects * are not sanitized or esacped. * * @param string $expression An arbitrary SQL expression to be inserted into a query. * @return stdClass An object representing a database expression to be used in a query */ public function expression($expression) { $obj = new stdClass(); $obj->type = 'expression'; $obj->value = $expression; return $obj; } /** * Executes given SQL statement. * * @param string $sql SQL statement * @param array $params Additional options for the query. * @return boolean */ public function rawQuery($sql, $params = array()) { $this->took = $this->numRows = false; return $this->execute($sql, $params); } /** * Queries the database with given SQL statement, and obtains some metadata about the result * (rows affected, timing, any errors, number of rows in resultset). The query is also logged. * If Configure::read('debug') is set, the log is shown all the time, else it is only shown on errors. * * ### Options * * - log - Whether or not the query should be logged to the memory log. * * @param string $sql * @param array $options * @param array $params values to be bided to the query * @return mixed Resource or object representing the result set, or false on failure */ public function execute($sql, $options = array(), $params = array()) { $options += array('log' => $this->fullDebug); $t = microtime(true); $this->_result = $this->_execute($sql, $params); if ($options['log']) { $this->took = round((microtime(true) - $t) * 1000, 0); $this->numRows = $this->affected = $this->lastAffected(); $this->logQuery($sql); } return $this->_result; } /** * Executes given SQL statement. * * @param string $sql SQL statement * @param array $params list of params to be bound to query * @param array $prepareOptions Options to be used in the prepare statement * @return mixed PDOStatement if query executes with no problem, true as the result of a successful, false on error * query returning no rows, suchs as a CREATE statement, false otherwise */ protected function _execute($sql, $params = array(), $prepareOptions = array()) { $sql = trim($sql); if (preg_match('/^(?:CREATE|ALTER|DROP)/i', $sql)) { $statements = array_filter(explode(';', $sql)); if (count($statements) > 1) { $result = array_map(array($this, '_execute'), $statements); return array_search(false, $result) === false; } } try { $query = $this->_connection->prepare($sql, $prepareOptions); $query->setFetchMode(PDO::FETCH_LAZY); if (!$query->execute($params)) { $this->_results = $query; $query->closeCursor(); return false; } if (!$query->columnCount()) { $query->closeCursor(); return true; } return $query; } catch (PDOException $e) { if (isset($query->queryString)) { $e->queryString = $query->queryString; } else { $e->queryString = $sql; } throw $e; } } /** * Returns a formatted error message from previous database operation. * * @param PDOStatement $query the query to extract the error from if any * @return string Error message with error number */ public function lastError(PDOStatement $query = null) { if ($query) { $error = $query->errorInfo(); } else { $error = $this->_connection->errorInfo(); } if (empty($error[2])) { return null; } return $error[1] . ': ' . $error[2]; } /** * Returns number of affected rows in previous database operation. If no previous operation exists, * this returns false. * * @param mixed $source * @return integer Number of affected rows */ public function lastAffected($source = null) { if ($this->hasResult()) { return $this->_result->rowCount(); } return null; } /** * Returns number of rows in previous resultset. If no previous resultset exists, * this returns false. * * @param mixed $source Not used * @return integer Number of rows in resultset */ public function lastNumRows($source = null) { return $this->lastAffected(); } /** * DataSource Query abstraction * * @return resource Result resource identifier. */ public function query() { $args = func_get_args(); $fields = null; $order = null; $limit = null; $page = null; $recursive = null; if (count($args) === 1) { return $this->fetchAll($args[0]); } elseif (count($args) > 1 && (strpos($args[0], 'findBy') === 0 || strpos($args[0], 'findAllBy') === 0)) { $params = $args[1]; if (substr($args[0], 0, 6) === 'findBy') { $all = false; $field = Inflector::underscore(substr($args[0], 6)); } else { $all = true; $field = Inflector::underscore(substr($args[0], 9)); } $or = (strpos($field, '_or_') !== false); if ($or) { $field = explode('_or_', $field); } else { $field = explode('_and_', $field); } $off = count($field) - 1; if (isset($params[1 + $off])) { $fields = $params[1 + $off]; } if (isset($params[2 + $off])) { $order = $params[2 + $off]; } if (!array_key_exists(0, $params)) { return false; } $c = 0; $conditions = array(); foreach ($field as $f) { $conditions[$args[2]->alias . '.' . $f] = $params[$c++]; } if ($or) { $conditions = array('OR' => $conditions); } if ($all) { if (isset($params[3 + $off])) { $limit = $params[3 + $off]; } if (isset($params[4 + $off])) { $page = $params[4 + $off]; } if (isset($params[5 + $off])) { $recursive = $params[5 + $off]; } return $args[2]->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive')); } else { if (isset($params[3 + $off])) { $recursive = $params[3 + $off]; } return $args[2]->find('first', compact('conditions', 'fields', 'order', 'recursive')); } } else { if (isset($args[1]) && $args[1] === true) { return $this->fetchAll($args[0], true); } else if (isset($args[1]) && !is_array($args[1]) ) { return $this->fetchAll($args[0], false); } else if (isset($args[1]) && is_array($args[1])) { $offset = 0; if (isset($args[2])) { $cache = $args[2]; } else { $cache = true; } return $this->fetchAll($args[0], $args[1], array('cache' => $cache)); } } } /** * Returns a row from current resultset as an array * * @param string $sql Some SQL to be executed. * @return array The fetched row as an array */ public function fetchRow($sql = null) { if (is_string($sql) && strlen($sql) > 5 && !$this->execute($sql)) { return null; } if ($this->hasResult()) { $this->resultSet($this->_result); $resultRow = $this->fetchResult(); if (isset($resultRow[0])) { $this->fetchVirtualField($resultRow); } return $resultRow; } else { return null; } } /** * Returns an array of all result rows for a given SQL query. * Returns false if no rows matched. * * * ### Options * * - `cache` - Returns the cached version of the query, if exists and stores the result in cache. * This is a non-persistent cache, and only lasts for a single request. This option * defaults to true. If you are directly calling this method, you can disable caching * by setting $options to `false` * * @param string $sql SQL statement * @param array $params parameters to be bound as values for the SQL statement * @param array $options additional options for the query. * @return array Array of resultset rows, or false if no rows matched */ public function fetchAll($sql, $params = array(), $options = array()) { if (is_string($options)) { $options = array('modelName' => $options); } if (is_bool($params)) { $options['cache'] = $params; $params = array(); } $options += array('cache' => true); $cache = $options['cache']; if ($cache && ($cached = $this->getQueryCache($sql, $params)) !== false) { return $cached; } if ($result = $this->execute($sql, array(), $params)) { $out = array(); if ($this->hasResult()) { $first = $this->fetchRow(); if ($first != null) { $out[] = $first; } while ($item = $this->fetchResult()) { if (isset($item[0])) { $this->fetchVirtualField($item); } $out[] = $item; } } if (!is_bool($result) && $cache) { $this->_writeQueryCache($sql, $out, $params); } if (empty($out) && is_bool($this->_result)) { return $this->_result; } return $out; } return false; } /** * Fetches the next row from the current result set * * @return boolean */ public function fetchResult() { return false; } /** * Modifies $result array to place virtual fields in model entry where they belongs to * * @param array $result Reference to the fetched row * @return void */ public function fetchVirtualField(&$result) { if (isset($result[0]) && is_array($result[0])) { foreach ($result[0] as $field => $value) { if (strpos($field, $this->virtualFieldSeparator) === false) { continue; } list($alias, $virtual) = explode($this->virtualFieldSeparator, $field); if (!ClassRegistry::isKeySet($alias)) { return; } $model = ClassRegistry::getObject($alias); if ($model->isVirtualField($virtual)) { $result[$alias][$virtual] = $value; unset($result[0][$field]); } } if (empty($result[0])) { unset($result[0]); } } } /** * Returns a single field of the first of query results for a given SQL query, or false if empty. * * @param string $name Name of the field * @param string $sql SQL query * @return mixed Value of field read. */ public function field($name, $sql) { $data = $this->fetchRow($sql); if (empty($data[$name])) { return false; } return $data[$name]; } /** * Empties the method caches. * These caches are used by DboSource::name() and DboSource::conditions() * * @return void */ public function flushMethodCache() { $this->_methodCacheChange = true; self::$methodCache = array(); } /** * Cache a value into the methodCaches. Will respect the value of DboSource::$cacheMethods. * Will retrieve a value from the cache if $value is null. * * If caching is disabled and a write is attempted, the $value will be returned. * A read will either return the value or null. * * @param string $method Name of the method being cached. * @param string $key The keyname for the cache operation. * @param mixed $value The value to cache into memory. * @return mixed Either null on failure, or the value if its set. */ public function cacheMethod($method, $key, $value = null) { if ($this->cacheMethods === false) { return $value; } if (empty(self::$methodCache)) { self::$methodCache = Cache::read('method_cache', '_cake_core_'); } if ($value === null) { return (isset(self::$methodCache[$method][$key])) ? self::$methodCache[$method][$key] : null; } $this->_methodCacheChange = true; return self::$methodCache[$method][$key] = $value; } /** * Returns a quoted name of $data for use in an SQL statement. * Strips fields out of SQL functions before quoting. * * Results of this method are stored in a memory cache. This improves performance, but * because the method uses a simple hashing algorithm it can infrequently have collisions. * Setting DboSource::$cacheMethods to false will disable the memory cache. * * @param mixed $data Either a string with a column to quote. An array of columns to quote or an * object from DboSource::expression() or DboSource::identifier() * @return string SQL field */ public function name($data) { if (is_object($data) && isset($data->type)) { return $data->value; } if ($data === '*') { return '*'; } if (is_array($data)) { foreach ($data as $i => $dataItem) { $data[$i] = $this->name($dataItem); } return $data; } $cacheKey = crc32($this->startQuote.$data.$this->endQuote); if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) { return $return; } $data = trim($data); if (preg_match('/^[\w-]+(?:\.[^ \*]*)*$/', $data)) { // string, string.string if (strpos($data, '.') === false) { // string return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote); } $items = explode('.', $data); return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . implode($this->endQuote . '.' . $this->startQuote, $items) . $this->endQuote ); } if (preg_match('/^[\w-]+\.\*$/', $data)) { // string.* return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . str_replace('.*', $this->endQuote . '.*', $data) ); } if (preg_match('/^([\w-]+)\((.*)\)$/', $data, $matches)) { // Functions return $this->cacheMethod(__FUNCTION__, $cacheKey, $matches[1] . '(' . $this->name($matches[2]) . ')' ); } if ( preg_match('/^([\w-]+(\.[\w-]+|\(.*\))*)\s+' . preg_quote($this->alias) . '\s*([\w-]+)$/i', $data, $matches )) { return $this->cacheMethod( __FUNCTION__, $cacheKey, preg_replace( '/\s{2,}/', ' ', $this->name($matches[1]) . ' ' . $this->alias . ' ' . $this->name($matches[3]) ) ); } if (preg_match('/^[\w-_\s]*[\w-_]+/', $data)) { return $this->cacheMethod(__FUNCTION__, $cacheKey, $this->startQuote . $data . $this->endQuote); } return $this->cacheMethod(__FUNCTION__, $cacheKey, $data); } /** * Checks if the source is connected to the database. * * @return boolean True if the database is connected, else false */ public function isConnected() { return $this->connected; } /** * Checks if the result is valid * * @return boolean True if the result is valid else false */ public function hasResult() { return is_a($this->_result, 'PDOStatement'); } /** * Get the query log as an array. * * @param boolean $sorted Get the queries sorted by time taken, defaults to false. * @param boolean $clear If True the existing log will cleared. * @return array Array of queries run as an array */ public function getLog($sorted = false, $clear = true) { if ($sorted) { $log = sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC); } else { $log = $this->_queriesLog; } if ($clear) { $this->_queriesLog = array(); } return array('log' => $log, 'count' => $this->_queriesCnt, 'time' => $this->_queriesTime); } /** * Outputs the contents of the queries log. If in a non-CLI environment the sql_log element * will be rendered and output. If in a CLI environment, a plain text log is generated. * * @param boolean $sorted Get the queries sorted by time taken, defaults to false. * @return void */ public function showLog($sorted = false) { $log = $this->getLog($sorted, false); if (empty($log['log'])) { return; } if (PHP_SAPI != 'cli') { $controller = null; $View = new View($controller, false); $View->set('logs', array($this->configKeyName => $log)); echo $View->element('sql_dump', array('_forced_from_dbo_' => true)); } else { foreach ($log['log'] as $k => $i) { print (($k + 1) . ". {$i['query']}\n"); } } } /** * Log given SQL query. * * @param string $sql SQL statement * @return void */ public function logQuery($sql) { $this->_queriesCnt++; $this->_queriesTime += $this->took; $this->_queriesLog[] = array( 'query' => $sql, 'affected' => $this->affected, 'numRows' => $this->numRows, 'took' => $this->took ); if (count($this->_queriesLog) > $this->_queriesLogMax) { array_pop($this->_queriesLog); } } /** * Gets full table name including prefix * * @param mixed $model Either a Model object or a string table name. * @param boolean $quote Whether you want the table name quoted. * @return string Full quoted table name */ public function fullTableName($model, $quote = true) { if (is_object($model)) { $table = $model->tablePrefix . $model->table; } elseif (isset($this->config['prefix'])) { $table = $this->config['prefix'] . strval($model); } else { $table = strval($model); } if ($quote) { return $this->name($table); } return $table; } /** * The "C" in CRUD * * Creates new records in the database. * * @param Model $model Model object that the record is for. * @param array $fields An array of field names to insert. If null, $model->data will be * used to generate field names. * @param array $values An array of values with keys matching the fields. If null, $model->data will * be used to generate values. * @return boolean Success */ public function create(Model $model, $fields = null, $values = null) { $id = null; if ($fields == null) { unset($fields, $values); $fields = array_keys($model->data); $values = array_values($model->data); } $count = count($fields); for ($i = 0; $i < $count; $i++) { $valueInsert[] = $this->value($values[$i], $model->getColumnType($fields[$i])); } for ($i = 0; $i < $count; $i++) { $fieldInsert[] = $this->name($fields[$i]); if ($fields[$i] == $model->primaryKey) { $id = $values[$i]; } } $query = array( 'table' => $this->fullTableName($model), 'fields' => implode(', ', $fieldInsert), 'values' => implode(', ', $valueInsert) ); if ($this->execute($this->renderStatement('create', $query))) { if (empty($id)) { $id = $this->lastInsertId($this->fullTableName($model, false), $model->primaryKey); } $model->setInsertID($id); $model->id = $id; return true; } $model->onError(); return false; } /** * The "R" in CRUD * * Reads record(s) from the database. * * @param Model $model A Model object that the query is for. * @param array $queryData An array of queryData information containing keys similar to Model::find() * @param integer $recursive Number of levels of association * @return mixed boolean false on error/failure. An array of results on success. */ public function read(Model $model, $queryData = array(), $recursive = null) { $queryData = $this->_scrubQueryData($queryData); $null = null; $array = array(); $linkedModels = array(); $bypass = false; if ($recursive === null && isset($queryData['recursive'])) { $recursive = $queryData['recursive']; } if (!is_null($recursive)) { $_recursive = $model->recursive; $model->recursive = $recursive; } if (!empty($queryData['fields'])) { $bypass = true; $queryData['fields'] = $this->fields($model, null, $queryData['fields']); } else { $queryData['fields'] = $this->fields($model); } $_associations = $model->associations(); if ($model->recursive == -1) { $_associations = array(); } elseif ($model->recursive == 0) { unset($_associations[2], $_associations[3]); } foreach ($_associations as $type) { foreach ($model->{$type} as $assoc => $assocData) { $linkModel = $model->{$assoc}; $external = isset($assocData['external']); $linkModel->getDataSource(); if ($model->useDbConfig === $linkModel->useDbConfig) { if ($bypass) { $assocData['fields'] = false; } if (true === $this->generateAssociationQuery($model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null)) { $linkedModels[$type . '/' . $assoc] = true; } } } } $query = trim($this->generateAssociationQuery($model, null, null, null, null, $queryData, false, $null)); $resultSet = $this->fetchAll($query, $model->cacheQueries); if ($resultSet === false) { $model->onError(); return false; } $filtered = $this->_filterResults($resultSet, $model); if ($model->recursive > -1) { foreach ($_associations as $type) { foreach ($model->{$type} as $assoc => $assocData) { $linkModel = $model->{$assoc}; if (!isset($linkedModels[$type . '/' . $assoc])) { if ($model->useDbConfig === $linkModel->useDbConfig) { $db = $this; } else { $db = ConnectionManager::getDataSource($linkModel->useDbConfig); } } elseif ($model->recursive > 1 && ($type === 'belongsTo' || $type === 'hasOne')) { $db = $this; } if (isset($db) && method_exists($db, 'queryAssociation')) { $stack = array($assoc); $db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1, $stack); unset($db); if ($type === 'hasMany') { $filtered[] = $assoc; } } } } $this->_filterResults($resultSet, $model, $filtered); } if (!is_null($recursive)) { $model->recursive = $_recursive; } return $resultSet; } /** * Passes association results thru afterFind filters of corresponding model * * @param array $results Reference of resultset to be filtered * @param Model $model Instance of model to operate against * @param array $filtered List of classes already filtered, to be skipped * @return array Array of results that have been filtered through $model->afterFind */ protected function _filterResults(&$results, Model $model, $filtered = array()) { $current = current($results); if (!is_array($current)) { return array(); } $keys = array_diff(array_keys($current), $filtered, array($model->alias)); $filtering = array(); foreach ($keys as $className) { if (!isset($model->{$className}) || !is_object($model->{$className})) { continue; } $linkedModel = $model->{$className}; $filtering[] = $className; foreach ($results as &$result) { $data = $linkedModel->afterFind(array(array($className => $result[$className])), false); if (isset($data[0][$className])) { $result[$className] = $data[0][$className]; } } } return $filtering; } /** * Queries associations. Used to fetch results on recursive models. * * @param Model $model Primary Model object * @param Model $linkModel Linked model that * @param string $type Association type, one of the model association types ie. hasMany * @param string $association * @param array $assocData * @param array $queryData * @param boolean $external Whether or not the association query is on an external datasource. * @param array $resultSet Existing results * @param integer $recursive Number of levels of association * @param array $stack * @return mixed */ public function queryAssociation($model, &$linkModel, $type, $association, $assocData, &$queryData, $external = false, &$resultSet, $recursive, $stack) { if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) { if (!is_array($resultSet)) { throw new CakeException(__d('cake_dev', 'Error in Model %s', get_class($model))); } if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) { $ins = $fetch = array(); foreach ($resultSet as &$result) { if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) { $ins[] = $in; } } if (!empty($ins)) { $ins = array_unique($ins); $fetch = $this->fetchAssociated($model, $query, $ins); } if (!empty($fetch) && is_array($fetch)) { if ($recursive > 0) { foreach ($linkModel->associations() as $type1) { foreach ($linkModel->{$type1} as $assoc1 => $assocData1) { $deepModel = $linkModel->{$assoc1}; $tmpStack = $stack; $tmpStack[] = $assoc1; if ($linkModel->useDbConfig === $deepModel->useDbConfig) { $db = $this; } else { $db = ConnectionManager::getDataSource($deepModel->useDbConfig); } $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack); } } } } $this->_filterResults($fetch, $model); return $this->_mergeHasMany($resultSet, $fetch, $association, $model, $linkModel); } elseif ($type === 'hasAndBelongsToMany') { $ins = $fetch = array(); foreach ($resultSet as &$result) { if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) { $ins[] = $in; } } if (!empty($ins)) { $ins = array_unique($ins); if (count($ins) > 1) { $query = str_replace('{$__cakeID__$}', '(' .implode(', ', $ins) .')', $query); $query = str_replace('= (', 'IN (', $query); } else { $query = str_replace('{$__cakeID__$}', $ins[0], $query); } $query = str_replace(' WHERE 1 = 1', '', $query); } $foreignKey = $model->hasAndBelongsToMany[$association]['foreignKey']; $joinKeys = array($foreignKey, $model->hasAndBelongsToMany[$association]['associationForeignKey']); list($with, $habtmFields) = $model->joinModel($model->hasAndBelongsToMany[$association]['with'], $joinKeys); $habtmFieldsCount = count($habtmFields); $q = $this->insertQueryData($query, null, $association, $assocData, $model, $linkModel, $stack); if ($q !== false) { $fetch = $this->fetchAll($q, $model->cacheQueries); } else { $fetch = null; } } $modelAlias = $model->alias; $modelPK = $model->primaryKey; foreach ($resultSet as &$row) { if ($type !== 'hasAndBelongsToMany') { $q = $this->insertQueryData($query, $row, $association, $assocData, $model, $linkModel, $stack); if ($q !== false) { $fetch = $this->fetchAll($q, $model->cacheQueries); } else { $fetch = null; } } $selfJoin = $linkModel->name === $model->name; if (!empty($fetch) && is_array($fetch)) { if ($recursive > 0) { foreach ($linkModel->associations() as $type1) { foreach ($linkModel->{$type1} as $assoc1 => $assocData1) { $deepModel = $linkModel->{$assoc1}; if ($type1 === 'belongsTo' || ($deepModel->alias === $modelAlias && $type === 'belongsTo') || ($deepModel->alias !== $modelAlias)) { $tmpStack = $stack; $tmpStack[] = $assoc1; if ($linkModel->useDbConfig == $deepModel->useDbConfig) { $db = $this; } else { $db = ConnectionManager::getDataSource($deepModel->useDbConfig); } $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack); } } } } if ($type === 'hasAndBelongsToMany') { $uniqueIds = $merge = array(); foreach ($fetch as $j => $data) { if (isset($data[$with]) && $data[$with][$foreignKey] === $row[$modelAlias][$modelPK]) { if ($habtmFieldsCount <= 2) { unset($data[$with]); } $merge[] = $data; } } if (empty($merge) && !isset($row[$association])) { $row[$association] = $merge; } else { $this->_mergeAssociation($row, $merge, $association, $type); } } else { $this->_mergeAssociation($row, $fetch, $association, $type, $selfJoin); } if (isset($row[$association])) { $row[$association] = $linkModel->afterFind($row[$association], false); } } else { $tempArray[0][$association] = false; $this->_mergeAssociation($row, $tempArray, $association, $type, $selfJoin); } } } } /** * A more efficient way to fetch associations. Woohoo! * * @param Model $model Primary model object * @param string $query Association query * @param array $ids Array of IDs of associated records * @return array Association results */ public function fetchAssociated($model, $query, $ids) { $query = str_replace('{$__cakeID__$}', implode(', ', $ids), $query); if (count($ids) > 1) { $query = str_replace('= (', 'IN (', $query); } return $this->fetchAll($query, $model->cacheQueries); } /** * mergeHasMany - Merge the results of hasMany relations. * * * @param array $resultSet Data to merge into * @param array $merge Data to merge * @param string $association Name of Model being Merged * @param Model $model Model being merged onto * @param Model $linkModel Model being merged * @return void */ protected function _mergeHasMany(&$resultSet, $merge, $association, $model, $linkModel) { $modelAlias = $model->alias; $modelPK = $model->primaryKey; $modelFK = $model->hasMany[$association]['foreignKey']; foreach ($resultSet as &$result) { if (!isset($result[$modelAlias])) { continue; } $merged = array(); foreach ($merge as $data) { if ($result[$modelAlias][$modelPK] === $data[$association][$modelFK]) { if (count($data) > 1) { $data = array_merge($data[$association], $data); unset($data[$association]); foreach ($data as $key => $name) { if (is_numeric($key)) { $data[$association][] = $name; unset($data[$key]); } } $merged[] = $data; } else { $merged[] = $data[$association]; } } } $result = Set::pushDiff($result, array($association => $merged)); } } /** * Merge association of merge into data * * @param array $data * @param array $merge * @param string $association * @param string $type * @param boolean $selfJoin * @return void */ protected function _mergeAssociation(&$data, &$merge, $association, $type, $selfJoin = false) { if (isset($merge[0]) && !isset($merge[0][$association])) { $association = Inflector::pluralize($association); } if ($type === 'belongsTo' || $type === 'hasOne') { if (isset($merge[$association])) { $data[$association] = $merge[$association][0]; } else { if (count($merge[0][$association]) > 1) { foreach ($merge[0] as $assoc => $data2) { if ($assoc !== $association) { $merge[0][$association][$assoc] = $data2; } } } if (!isset($data[$association])) { if ($merge[0][$association] != null) { $data[$association] = $merge[0][$association]; } else { $data[$association] = array(); } } else { if (is_array($merge[0][$association])) { foreach ($data[$association] as $k => $v) { if (!is_array($v)) { $dataAssocTmp[$k] = $v; } } foreach ($merge[0][$association] as $k => $v) { if (!is_array($v)) { $mergeAssocTmp[$k] = $v; } } $dataKeys = array_keys($data); $mergeKeys = array_keys($merge[0]); if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) { $data[$association][$association] = $merge[0][$association]; } else { $diff = Set::diff($dataAssocTmp, $mergeAssocTmp); $data[$association] = array_merge($merge[0][$association], $diff); } } elseif ($selfJoin && array_key_exists($association, $merge[0])) { $data[$association] = array_merge($data[$association], array($association => array())); } } } } else { if (isset($merge[0][$association]) && $merge[0][$association] === false) { if (!isset($data[$association])) { $data[$association] = array(); } } else { foreach ($merge as $i => $row) { if (count($row) === 1) { if (empty($data[$association]) || (isset($data[$association]) && !in_array($row[$association], $data[$association]))) { $data[$association][] = $row[$association]; } } elseif (!empty($row)) { $tmp = array_merge($row[$association], $row); unset($tmp[$association]); $data[$association][] = $tmp; } } } } } /** * Generates an array representing a query or part of a query from a single model or two associated models * * @param Model $model * @param Model $linkModel * @param string $type * @param string $association * @param array $assocData * @param array $queryData * @param boolean $external * @param array $resultSet * @return mixed */ public function generateAssociationQuery($model, $linkModel, $type, $association = null, $assocData = array(), &$queryData, $external = false, &$resultSet) { $queryData = $this->_scrubQueryData($queryData); $assocData = $this->_scrubQueryData($assocData); $modelAlias = $model->alias; if (empty($queryData['fields'])) { $queryData['fields'] = $this->fields($model, $modelAlias); } elseif (!empty($model->hasMany) && $model->recursive > -1) { $assocFields = $this->fields($model, $modelAlias, array("{$modelAlias}.{$model->primaryKey}")); $passedFields = $queryData['fields']; if (count($passedFields) === 1) { if (strpos($passedFields[0], $assocFields[0]) === false && !preg_match('/^[a-z]+\(/i', $passedFields[0])) { $queryData['fields'] = array_merge($passedFields, $assocFields); } else { $queryData['fields'] = $passedFields; } } else { $queryData['fields'] = array_merge($passedFields, $assocFields); } unset($assocFields, $passedFields); } if ($linkModel === null) { return $this->buildStatement( array( 'fields' => array_unique($queryData['fields']), 'table' => $this->fullTableName($model), 'alias' => $modelAlias, 'limit' => $queryData['limit'], 'offset' => $queryData['offset'], 'joins' => $queryData['joins'], 'conditions' => $queryData['conditions'], 'order' => $queryData['order'], 'group' => $queryData['group'] ), $model ); } if ($external && !empty($assocData['finderQuery'])) { return $assocData['finderQuery']; } $self = $model->name === $linkModel->name; $fields = array(); if ($external || (in_array($type, array('hasOne', 'belongsTo')) && $assocData['fields'] !== false)) { $fields = $this->fields($linkModel, $association, $assocData['fields']); } if (empty($assocData['offset']) && !empty($assocData['page'])) { $assocData['offset'] = ($assocData['page'] - 1) * $assocData['limit']; } $assocData['limit'] = $this->limit($assocData['limit'], $assocData['offset']); switch ($type) { case 'hasOne': case 'belongsTo': $conditions = $this->_mergeConditions( $assocData['conditions'], $this->getConstraint($type, $model, $linkModel, $association, array_merge($assocData, compact('external', 'self'))) ); if (!$self && $external) { foreach ($conditions as $key => $condition) { if (is_numeric($key) && strpos($condition, $modelAlias . '.') !== false) { unset($conditions[$key]); } } } if ($external) { $query = array_merge($assocData, array( 'conditions' => $conditions, 'table' => $this->fullTableName($linkModel), 'fields' => $fields, 'alias' => $association, 'group' => null )); $query += array('order' => $assocData['order'], 'limit' => $assocData['limit']); } else { $join = array( 'table' => $linkModel, 'alias' => $association, 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT', 'conditions' => trim($this->conditions($conditions, true, false, $model)) ); $queryData['fields'] = array_merge($queryData['fields'], $fields); if (!empty($assocData['order'])) { $queryData['order'][] = $assocData['order']; } if (!in_array($join, $queryData['joins'])) { $queryData['joins'][] = $join; } return true; } break; case 'hasMany': $assocData['fields'] = $this->fields($linkModel, $association, $assocData['fields']); if (!empty($assocData['foreignKey'])) { $assocData['fields'] = array_merge($assocData['fields'], $this->fields($linkModel, $association, array("{$association}.{$assocData['foreignKey']}"))); } $query = array( 'conditions' => $this->_mergeConditions($this->getConstraint('hasMany', $model, $linkModel, $association, $assocData), $assocData['conditions']), 'fields' => array_unique($assocData['fields']), 'table' => $this->fullTableName($linkModel), 'alias' => $association, 'order' => $assocData['order'], 'limit' => $assocData['limit'], 'group' => null ); break; case 'hasAndBelongsToMany': $joinFields = array(); $joinAssoc = null; if (isset($assocData['with']) && !empty($assocData['with'])) { $joinKeys = array($assocData['foreignKey'], $assocData['associationForeignKey']); list($with, $joinFields) = $model->joinModel($assocData['with'], $joinKeys); $joinTbl = $model->{$with}; $joinAlias = $joinTbl; if (is_array($joinFields) && !empty($joinFields)) { $joinAssoc = $joinAlias = $model->{$with}->alias; $joinFields = $this->fields($model->{$with}, $joinAlias, $joinFields); } else { $joinFields = array(); } } else { $joinTbl = $assocData['joinTable']; $joinAlias = $this->fullTableName($assocData['joinTable']); } $query = array( 'conditions' => $assocData['conditions'], 'limit' => $assocData['limit'], 'table' => $this->fullTableName($linkModel), 'alias' => $association, 'fields' => array_merge($this->fields($linkModel, $association, $assocData['fields']), $joinFields), 'order' => $assocData['order'], 'group' => null, 'joins' => array(array( 'table' => $joinTbl, 'alias' => $joinAssoc, 'conditions' => $this->getConstraint('hasAndBelongsToMany', $model, $linkModel, $joinAlias, $assocData, $association) )) ); break; } if (isset($query)) { return $this->buildStatement($query, $model); } return null; } /** * Returns a conditions array for the constraint between two models * * @param string $type Association type * @param Model $model Model object * @param string $linkModel * @param string $alias * @param array $assoc * @param string $alias2 * @return array Conditions array defining the constraint between $model and $association */ public function getConstraint($type, $model, $linkModel, $alias, $assoc, $alias2 = null) { $assoc += array('external' => false, 'self' => false); if (empty($assoc['foreignKey'])) { return array(); } switch (true) { case ($assoc['external'] && $type === 'hasOne'): return array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}'); case ($assoc['external'] && $type === 'belongsTo'): return array("{$alias}.{$linkModel->primaryKey}" => '{$__cakeForeignKey__$}'); case (!$assoc['external'] && $type === 'hasOne'): return array("{$alias}.{$assoc['foreignKey']}" => $this->identifier("{$model->alias}.{$model->primaryKey}")); case (!$assoc['external'] && $type === 'belongsTo'): return array("{$model->alias}.{$assoc['foreignKey']}" => $this->identifier("{$alias}.{$linkModel->primaryKey}")); case ($type === 'hasMany'): return array("{$alias}.{$assoc['foreignKey']}" => array('{$__cakeID__$}')); case ($type === 'hasAndBelongsToMany'): return array( array("{$alias}.{$assoc['foreignKey']}" => '{$__cakeID__$}'), array("{$alias}.{$assoc['associationForeignKey']}" => $this->identifier("{$alias2}.{$linkModel->primaryKey}")) ); } return array(); } /** * Builds and generates a JOIN statement from an array. Handles final clean-up before conversion. * * @param array $join An array defining a JOIN statement in a query * @return string An SQL JOIN statement to be used in a query * @see DboSource::renderJoinStatement() * @see DboSource::buildStatement() */ public function buildJoinStatement($join) { $data = array_merge(array( 'type' => null, 'alias' => null, 'table' => 'join_table', 'conditions' => array() ), $join); if (!empty($data['alias'])) { $data['alias'] = $this->alias . $this->name($data['alias']); } if (!empty($data['conditions'])) { $data['conditions'] = trim($this->conditions($data['conditions'], true, false)); } if (!empty($data['table'])) { $data['table'] = $this->fullTableName($data['table']); } return $this->renderJoinStatement($data); } /** * Builds and generates an SQL statement from an array. Handles final clean-up before conversion. * * @param array $query An array defining an SQL query * @param Model $model The model object which initiated the query * @return string An executable SQL statement * @see DboSource::renderStatement() */ public function buildStatement($query, $model) { $query = array_merge(array('offset' => null, 'joins' => array()), $query); if (!empty($query['joins'])) { $count = count($query['joins']); for ($i = 0; $i < $count; $i++) { if (is_array($query['joins'][$i])) { $query['joins'][$i] = $this->buildJoinStatement($query['joins'][$i]); } } } return $this->renderStatement('select', array( 'conditions' => $this->conditions($query['conditions'], true, true, $model), 'fields' => implode(', ', $query['fields']), 'table' => $query['table'], 'alias' => $this->alias . $this->name($query['alias']), 'order' => $this->order($query['order'], 'ASC', $model), 'limit' => $this->limit($query['limit'], $query['offset']), 'joins' => implode(' ', $query['joins']), 'group' => $this->group($query['group'], $model) )); } /** * Renders a final SQL JOIN statement * * @param array $data * @return string */ public function renderJoinStatement($data) { extract($data); return trim("{$type} JOIN {$table} {$alias} ON ({$conditions})"); } /** * Renders a final SQL statement by putting together the component parts in the correct order * * @param string $type type of query being run. e.g select, create, update, delete, schema, alter. * @param array $data Array of data to insert into the query. * @return string Rendered SQL expression to be run. */ public function renderStatement($type, $data) { extract($data); $aliases = null; switch (strtolower($type)) { case 'select': return "SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}"; case 'create': return "INSERT INTO {$table} ({$fields}) VALUES ({$values})"; case 'update': if (!empty($alias)) { $aliases = "{$this->alias}{$alias} {$joins} "; } return "UPDATE {$table} {$aliases}SET {$fields} {$conditions}"; case 'delete': if (!empty($alias)) { $aliases = "{$this->alias}{$alias} {$joins} "; } return "DELETE {$alias} FROM {$table} {$aliases}{$conditions}"; case 'schema': foreach (array('columns', 'indexes', 'tableParameters') as $var) { if (is_array(${$var})) { ${$var} = "\t" . join(",\n\t", array_filter(${$var})); } else { ${$var} = ''; } } if (trim($indexes) !== '') { $columns .= ','; } return "CREATE TABLE {$table} (\n{$columns}{$indexes}){$tableParameters};"; case 'alter': return; } } /** * Merges a mixed set of string/array conditions * * @param mixed $query * @param mixed $assoc * @return array */ protected function _mergeConditions($query, $assoc) { if (empty($assoc)) { return $query; } if (is_array($query)) { return array_merge((array)$assoc, $query); } if (!empty($query)) { $query = array($query); if (is_array($assoc)) { $query = array_merge($query, $assoc); } else { $query[] = $assoc; } return $query; } return $assoc; } /** * Generates and executes an SQL UPDATE statement for given model, fields, and values. * For databases that do not support aliases in UPDATE queries. * * @param Model $model * @param array $fields * @param array $values * @param mixed $conditions * @return boolean Success */ public function update(Model $model, $fields = array(), $values = null, $conditions = null) { if ($values == null) { $combined = $fields; } else { $combined = array_combine($fields, $values); } $fields = implode(', ', $this->_prepareUpdateFields($model, $combined, empty($conditions))); $alias = $joins = null; $table = $this->fullTableName($model); $conditions = $this->_matchRecords($model, $conditions); if ($conditions === false) { return false; } $query = compact('table', 'alias', 'joins', 'fields', 'conditions'); if (!$this->execute($this->renderStatement('update', $query))) { $model->onError(); return false; } return true; } /** * Quotes and prepares fields and values for an SQL UPDATE statement * * @param Model $model * @param array $fields * @param boolean $quoteValues If values should be quoted, or treated as SQL snippets * @param boolean $alias Include the model alias in the field name * @return array Fields and values, quoted and preparted */ protected function _prepareUpdateFields($model, $fields, $quoteValues = true, $alias = false) { $quotedAlias = $this->startQuote . $model->alias . $this->endQuote; $updates = array(); foreach ($fields as $field => $value) { if ($alias && strpos($field, '.') === false) { $quoted = $model->escapeField($field); } elseif (!$alias && strpos($field, '.') !== false) { $quoted = $this->name(str_replace($quotedAlias . '.', '', str_replace( $model->alias . '.', '', $field ))); } else { $quoted = $this->name($field); } if ($value === null) { $updates[] = $quoted . ' = NULL'; continue; } $update = $quoted . ' = '; if ($quoteValues) { $update .= $this->value($value, $model->getColumnType($field)); } elseif (!$alias) { $update .= str_replace($quotedAlias . '.', '', str_replace( $model->alias . '.', '', $value )); } else { $update .= $value; } $updates[] = $update; } return $updates; } /** * Generates and executes an SQL DELETE statement. * For databases that do not support aliases in UPDATE queries. * * @param Model $model * @param mixed $conditions * @return boolean Success */ public function delete(Model $model, $conditions = null) { $alias = $joins = null; $table = $this->fullTableName($model); $conditions = $this->_matchRecords($model, $conditions); if ($conditions === false) { return false; } if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) { $model->onError(); return false; } return true; } /** * Gets a list of record IDs for the given conditions. Used for multi-record updates and deletes * in databases that do not support aliases in UPDATE/DELETE queries. * * @param Model $model * @param mixed $conditions * @return array List of record IDs */ protected function _matchRecords($model, $conditions = null) { if ($conditions === true) { $conditions = $this->conditions(true); } elseif ($conditions === null) { $conditions = $this->conditions($this->defaultConditions($model, $conditions, false), true, true, $model); } else { $noJoin = true; foreach ($conditions as $field => $value) { $originalField = $field; if (strpos($field, '.') !== false) { list($alias, $field) = explode('.', $field); $field = ltrim($field, $this->startQuote); $field = rtrim($field, $this->endQuote); } if (!$model->hasField($field)) { $noJoin = false; break; } if ($field !== $originalField) { $conditions[$field] = $value; unset($conditions[$originalField]); } } if ($noJoin === true) { return $this->conditions($conditions); } $idList = $model->find('all', array( 'fields' => "{$model->alias}.{$model->primaryKey}", 'conditions' => $conditions )); if (empty($idList)) { return false; } $conditions = $this->conditions(array( $model->primaryKey => Set::extract($idList, "{n}.{$model->alias}.{$model->primaryKey}") )); } return $conditions; } /** * Returns an array of SQL JOIN fragments from a model's associations * * @param Model $model * @return array */ protected function _getJoins($model) { $join = array(); $joins = array_merge($model->getAssociated('hasOne'), $model->getAssociated('belongsTo')); foreach ($joins as $assoc) { if (isset($model->{$assoc}) && $model->useDbConfig == $model->{$assoc}->useDbConfig && $model->{$assoc}->getDataSource()) { $assocData = $model->getAssociated($assoc); $join[] = $this->buildJoinStatement(array( 'table' => $model->{$assoc}, 'alias' => $assoc, 'type' => isset($assocData['type']) ? $assocData['type'] : 'LEFT', 'conditions' => trim($this->conditions( $this->_mergeConditions($assocData['conditions'], $this->getConstraint($assocData['association'], $model, $model->{$assoc}, $assoc, $assocData)), true, false, $model )) )); } } return $join; } /** * Returns an SQL calculation, i.e. COUNT() or MAX() * * @param Model $model * @param string $func Lowercase name of SQL function, i.e. 'count' or 'max' * @param array $params Function parameters (any values must be quoted manually) * @return string An SQL calculation function */ public function calculate($model, $func, $params = array()) { $params = (array)$params; switch (strtolower($func)) { case 'count': if (!isset($params[0])) { $params[0] = '*'; } if (!isset($params[1])) { $params[1] = 'count'; } if (is_object($model) && $model->isVirtualField($params[0])){ $arg = $this->_quoteFields($model->getVirtualField($params[0])); } else { $arg = $this->name($params[0]); } return 'COUNT(' . $arg . ') AS ' . $this->name($params[1]); case 'max': case 'min': if (!isset($params[1])) { $params[1] = $params[0]; } if (is_object($model) && $model->isVirtualField($params[0])) { $arg = $this->_quoteFields($model->getVirtualField($params[0])); } else { $arg = $this->name($params[0]); } return strtoupper($func) . '(' . $arg . ') AS ' . $this->name($params[1]); break; } } /** * Deletes all the records in a table and resets the count of the auto-incrementing * primary key, where applicable. * * @param mixed $table A string or model class representing the table to be truncated * @return boolean SQL TRUNCATE TABLE statement, false if not applicable. */ public function truncate($table) { return $this->execute('TRUNCATE TABLE ' . $this->fullTableName($table)); } /** * Begin a transaction * * @return boolean True on success, false on fail * (i.e. if the database/model does not support transactions, * or a transaction has not started). */ public function begin() { if ($this->_transactionStarted || $this->_connection->beginTransaction()) { $this->_transactionStarted = true; $this->_transactionNesting++; return true; } return false; } /** * Commit a transaction * * @return boolean True on success, false on fail * (i.e. if the database/model does not support transactions, * or a transaction has not started). */ public function commit() { if ($this->_transactionStarted) { $this->_transactionNesting--; if ($this->_transactionNesting <= 0) { $this->_transactionStarted = false; $this->_transactionNesting = 0; return $this->_connection->commit(); } return true; } return false; } /** * Rollback a transaction * * @return boolean True on success, false on fail * (i.e. if the database/model does not support transactions, * or a transaction has not started). */ public function rollback() { if ($this->_transactionStarted && $this->_connection->rollBack()) { $this->_transactionStarted = false; $this->_transactionNesting = 0; return true; } return false; } /** * Returns the ID generated from the previous INSERT operation. * * @param mixed $source * @return mixed */ public function lastInsertId($source = null) { return $this->_connection->lastInsertId(); } /** * Creates a default set of conditions from the model if $conditions is null/empty. * If conditions are supplied then they will be returned. If a model doesn't exist and no conditions * were provided either null or false will be returned based on what was input. * * @param Model $model * @param mixed $conditions Array of conditions, conditions string, null or false. If an array of conditions, * or string conditions those conditions will be returned. With other values the model's existance will be checked. * If the model doesn't exist a null or false will be returned depending on the input value. * @param boolean $useAlias Use model aliases rather than table names when generating conditions * @return mixed Either null, false, $conditions or an array of default conditions to use. * @see DboSource::update() * @see DboSource::conditions() */ public function defaultConditions($model, $conditions, $useAlias = true) { if (!empty($conditions)) { return $conditions; } $exists = $model->exists(); if (!$exists && $conditions !== null) { return false; } elseif (!$exists) { return null; } $alias = $model->alias; if (!$useAlias) { $alias = $this->fullTableName($model, false); } return array("{$alias}.{$model->primaryKey}" => $model->getID()); } /** * Returns a key formatted like a string Model.fieldname(i.e. Post.title, or Country.name) * * @param Model $model * @param string $key * @param string $assoc * @return string */ public function resolveKey(Model $model, $key, $assoc = null) { if (empty($assoc)) { $assoc = $model->alias; } if (strpos('.', $key) !== false) { return $this->name($model->alias) . '.' . $this->name($key); } return $key; } /** * Private helper method to remove query metadata in given data array. * * @param array $data * @return array */ protected function _scrubQueryData($data) { static $base = null; if ($base === null) { $base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array()); } return (array)$data + $base; } /** * Converts model virtual fields into sql expressions to be fetched later * * @param Model $model * @param string $alias Alias tablename * @param mixed $fields virtual fields to be used on query * @return array */ protected function _constructVirtualFields($model, $alias, $fields) { $virtual = array(); foreach ($fields as $field) { $virtualField = $this->name($alias . $this->virtualFieldSeparator . $field); $expression = $this->_quoteFields($model->getVirtualField($field)); $virtual[] = '(' . $expression . ") {$this->alias} {$virtualField}"; } return $virtual; } /** * Generates the fields list of an SQL query. * * @param Model $model * @param string $alias Alias tablename * @param mixed $fields * @param boolean $quote If false, returns fields array unquoted * @return array */ public function fields($model, $alias = null, $fields = array(), $quote = true) { if (empty($alias)) { $alias = $model->alias; } $virtualFields = $model->getVirtualField(); $cacheKey = array( $alias, get_class($model), $model->alias, $virtualFields, $fields, $quote ); $cacheKey = md5(serialize($cacheKey)); if ($return = $this->cacheMethod(__FUNCTION__, $cacheKey)) { return $return; } $allFields = empty($fields); if ($allFields) { $fields = array_keys($model->schema()); } elseif (!is_array($fields)) { $fields = String::tokenize($fields); } $fields = array_values(array_filter($fields)); $allFields = $allFields || in_array('*', $fields) || in_array($model->alias . '.*', $fields); $virtual = array(); if (!empty($virtualFields)) { $virtualKeys = array_keys($virtualFields); foreach ($virtualKeys as $field) { $virtualKeys[] = $model->alias . '.' . $field; } $virtual = ($allFields) ? $virtualKeys : array_intersect($virtualKeys, $fields); foreach ($virtual as $i => $field) { if (strpos($field, '.') !== false) { $virtual[$i] = str_replace($model->alias . '.', '', $field); } $fields = array_diff($fields, array($field)); } $fields = array_values($fields); } if (!$quote) { if (!empty($virtual)) { $fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual)); } return $fields; } $count = count($fields); if ($count >= 1 && !in_array($fields[0], array('*', 'COUNT(*)'))) { for ($i = 0; $i < $count; $i++) { if (is_string($fields[$i]) && in_array($fields[$i], $virtual)) { unset($fields[$i]); continue; } if (is_object($fields[$i]) && isset($fields[$i]->type) && $fields[$i]->type === 'expression') { $fields[$i] = $fields[$i]->value; } elseif (preg_match('/^\(.*\)\s' . $this->alias . '.*/i', $fields[$i])){ continue; } elseif (!preg_match('/^.+\\(.*\\)/', $fields[$i])) { $prepend = ''; if (strpos($fields[$i], 'DISTINCT') !== false) { $prepend = 'DISTINCT '; $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i])); } $dot = strpos($fields[$i], '.'); if ($dot === false) { $prefix = !( strpos($fields[$i], ' ') !== false || strpos($fields[$i], '(') !== false ); $fields[$i] = $this->name(($prefix ? $alias . '.' : '') . $fields[$i]); } else { $value = array(); if (strpos($fields[$i], ',') === false) { $build = explode('.', $fields[$i]); if (!Set::numeric($build)) { $fields[$i] = $this->name(implode('.', $build)); } } } $fields[$i] = $prepend . $fields[$i]; } elseif (preg_match('/\(([\.\w]+)\)/', $fields[$i], $field)) { if (isset($field[1])) { if (strpos($field[1], '.') === false) { $field[1] = $this->name($alias . '.' . $field[1]); } else { $field[0] = explode('.', $field[1]); if (!Set::numeric($field[0])) { $field[0] = implode('.', array_map(array(&$this, 'name'), $field[0])); $fields[$i] = preg_replace('/\(' . $field[1] . '\)/', '(' . $field[0] . ')', $fields[$i], 1); } } } } } } if (!empty($virtual)) { $fields = array_merge($fields, $this->_constructVirtualFields($model, $alias, $virtual)); } return $this->cacheMethod(__FUNCTION__, $cacheKey, array_unique($fields)); } /** * Creates a WHERE clause by parsing given conditions data. If an array or string * conditions are provided those conditions will be parsed and quoted. If a boolean * is given it will be integer cast as condition. Null will return 1 = 1. * * Results of this method are stored in a memory cache. This improves performance, but * because the method uses a simple hashing algorithm it can infrequently have collisions. * Setting DboSource::$cacheMethods to false will disable the memory cache. * * @param mixed $conditions Array or string of conditions, or any value. * @param boolean $quoteValues If true, values should be quoted * @param boolean $where If true, "WHERE " will be prepended to the return value * @param Model $model A reference to the Model instance making the query * @return string SQL fragment */ public function conditions($conditions, $quoteValues = true, $where = true, $model = null) { $clause = $out = ''; if ($where) { $clause = ' WHERE '; } if (is_array($conditions) && !empty($conditions)) { $out = $this->conditionKeysToString($conditions, $quoteValues, $model); if (empty($out)) { return $clause . ' 1 = 1'; } return $clause . implode(' AND ', $out); } if (is_bool($conditions)) { return $clause . (int)$conditions . ' = 1'; } if (empty($conditions) || trim($conditions) === '') { return $clause . '1 = 1'; } $clauses = '/^WHERE\\x20|^GROUP\\x20BY\\x20|^HAVING\\x20|^ORDER\\x20BY\\x20/i'; if (preg_match($clauses, $conditions, $match)) { $clause = ''; } $conditions = $this->_quoteFields($conditions); return $clause . $conditions; } /** * Creates a WHERE clause by parsing given conditions array. Used by DboSource::conditions(). * * @param array $conditions Array or string of conditions * @param boolean $quoteValues If true, values should be quoted * @param Model $model A reference to the Model instance making the query * @return string SQL fragment */ public function conditionKeysToString($conditions, $quoteValues = true, $model = null) { $out = array(); $data = $columnType = null; $bool = array('and', 'or', 'not', 'and not', 'or not', 'xor', '||', '&&'); foreach ($conditions as $key => $value) { $join = ' AND '; $not = null; if (is_array($value)) { $valueInsert = ( !empty($value) && (substr_count($key, '?') === count($value) || substr_count($key, ':') === count($value)) ); } if (is_numeric($key) && empty($value)) { continue; } elseif (is_numeric($key) && is_string($value)) { $out[] = $not . $this->_quoteFields($value); } elseif ((is_numeric($key) && is_array($value)) || in_array(strtolower(trim($key)), $bool)) { if (in_array(strtolower(trim($key)), $bool)) { $join = ' ' . strtoupper($key) . ' '; } else { $key = $join; } $value = $this->conditionKeysToString($value, $quoteValues, $model); if (strpos($join, 'NOT') !== false) { if (strtoupper(trim($key)) === 'NOT') { $key = 'AND ' . trim($key); } $not = 'NOT '; } if (empty($value[1])) { if ($not) { $out[] = $not . '(' . $value[0] . ')'; } else { $out[] = $value[0] ; } } else { $out[] = '(' . $not . '(' . implode(') ' . strtoupper($key) . ' (', $value) . '))'; } } else { if (is_object($value) && isset($value->type)) { if ($value->type === 'identifier') { $data .= $this->name($key) . ' = ' . $this->name($value->value); } elseif ($value->type === 'expression') { if (is_numeric($key)) { $data .= $value->value; } else { $data .= $this->name($key) . ' = ' . $value->value; } } } elseif (is_array($value) && !empty($value) && !$valueInsert) { $keys = array_keys($value); if ($keys === array_values($keys)) { $count = count($value); if ($count === 1) { $data = $this->_quoteFields($key) . ' = ('; } else { $data = $this->_quoteFields($key) . ' IN ('; } if ($quoteValues) { if (is_object($model)) { $columnType = $model->getColumnType($key); } $data .= implode(', ', $this->value($value, $columnType)); } $data .= ')'; } else { $ret = $this->conditionKeysToString($value, $quoteValues, $model); if (count($ret) > 1) { $data = '(' . implode(') AND (', $ret) . ')'; } elseif (isset($ret[0])) { $data = $ret[0]; } } } elseif (is_numeric($key) && !empty($value)) { $data = $this->_quoteFields($value); } else { $data = $this->_parseKey($model, trim($key), $value); } if ($data != null) { $out[] = $data; $data = null; } } } return $out; } /** * Extracts a Model.field identifier and an SQL condition operator from a string, formats * and inserts values, and composes them into an SQL snippet. * * @param Model $model Model object initiating the query * @param string $key An SQL key snippet containing a field and optional SQL operator * @param mixed $value The value(s) to be inserted in the string * @return string */ protected function _parseKey($model, $key, $value) { $operatorMatch = '/^(((' . implode(')|(', $this->_sqlOps); $operatorMatch .= ')\\x20?)|<[>=]?(?![^>]+>)\\x20?|[>=!]{1,3}(?!<)\\x20?)/is'; $bound = (strpos($key, '?') !== false || (is_array($value) && strpos($key, ':') !== false)); if (strpos($key, ' ') === false) { $operator = '='; } else { list($key, $operator) = explode(' ', trim($key), 2); if (!preg_match($operatorMatch, trim($operator)) && strpos($operator, ' ') !== false) { $key = $key . ' ' . $operator; $split = strrpos($key, ' '); $operator = substr($key, $split); $key = substr($key, 0, $split); } } $virtual = false; if (is_object($model) && $model->isVirtualField($key)) { $key = $this->_quoteFields($model->getVirtualField($key)); $virtual = true; } $type = is_object($model) ? $model->getColumnType($key) : null; $null = $value === null || (is_array($value) && empty($value)); if (strtolower($operator) === 'not') { $data = $this->conditionKeysToString( array($operator => array($key => $value)), true, $model ); return $data[0]; } $value = $this->value($value, $type); if (!$virtual && $key !== '?') { $isKey = (strpos($key, '(') !== false || strpos($key, ')') !== false); $key = $isKey ? $this->_quoteFields($key) : $this->name($key); } if ($bound) { return String::insert($key . ' ' . trim($operator), $value); } if (!preg_match($operatorMatch, trim($operator))) { $operator .= ' ='; } $operator = trim($operator); if (is_array($value)) { $value = implode(', ', $value); switch ($operator) { case '=': $operator = 'IN'; break; case '!=': case '<>': $operator = 'NOT IN'; break; } $value = "({$value})"; } elseif ($null || $value === 'NULL') { switch ($operator) { case '=': $operator = 'IS'; break; case '!=': case '<>': $operator = 'IS NOT'; break; } } if ($virtual) { return "({$key}) {$operator} {$value}"; } return "{$key} {$operator} {$value}"; } /** * Quotes Model.fields * * @param string $conditions * @return string or false if no match */ protected function _quoteFields($conditions) { $start = $end = null; $original = $conditions; if (!empty($this->startQuote)) { $start = preg_quote($this->startQuote); } if (!empty($this->endQuote)) { $end = preg_quote($this->endQuote); } $conditions = str_replace(array($start, $end), '', $conditions); $conditions = preg_replace_callback('/(?:[\'\"][^\'\"\\\]*(?:\\\.[^\'\"\\\]*)*[\'\"])|([a-z0-9_' . $start . $end . ']*\\.[a-z0-9_' . $start . $end . ']*)/i', array(&$this, '_quoteMatchedField'), $conditions); if ($conditions !== null) { return $conditions; } return $original; } /** * Auxiliary function to quote matches `Model.fields` from a preg_replace_callback call * * @param string $match matched string * @return string quoted strig */ protected function _quoteMatchedField($match) { if (is_numeric($match[0])) { return $match[0]; } return $this->name($match[0]); } /** * Returns a limit statement in the correct format for the particular database. * * @param integer $limit Limit of results returned * @param integer $offset Offset from which to start results * @return string SQL limit/offset statement */ public function limit($limit, $offset = null) { if ($limit) { $rt = ''; if (!strpos(strtolower($limit), 'limit')) { $rt = ' LIMIT'; } if ($offset) { $rt .= ' ' . $offset . ','; } $rt .= ' ' . $limit; return $rt; } return null; } /** * Returns an ORDER BY clause as a string. * * @param array|string $keys Field reference, as a key (i.e. Post.title) * @param string $direction Direction (ASC or DESC) * @param Model $model model reference (used to look for virtual field) * @return string ORDER BY clause */ public function order($keys, $direction = 'ASC', $model = null) { if (!is_array($keys)) { $keys = array($keys); } $keys = array_filter($keys); $result = array(); while (!empty($keys)) { list($key, $dir) = each($keys); array_shift($keys); if (is_numeric($key)) { $key = $dir; $dir = $direction; } if (is_string($key) && strpos($key, ',') !== false && !preg_match('/\(.+\,.+\)/', $key)) { $key = array_map('trim', explode(',', $key)); } if (is_array($key)) { //Flatten the array $key = array_reverse($key, true); foreach ($key as $k => $v) { if (is_numeric($k)) { array_unshift($keys, $v); } else { $keys = array($k => $v) + $keys; } } continue; } elseif (is_object($key) && isset($key->type) && $key->type === 'expression') { $result[] = $key->value; continue; } if (preg_match('/\\x20(ASC|DESC).*/i', $key, $_dir)) { $dir = $_dir[0]; $key = preg_replace('/\\x20(ASC|DESC).*/i', '', $key); } $key = trim($key); if (is_object($model) && $model->isVirtualField($key)) { $key = '(' . $this->_quoteFields($model->getVirtualField($key)) . ')'; } if (strpos($key, '.')) { $key = preg_replace_callback('/([a-zA-Z0-9_-]{1,})\\.([a-zA-Z0-9_-]{1,})/', array(&$this, '_quoteMatchedField'), $key); } if (!preg_match('/\s/', $key) && strpos($key, '.') === false) { $key = $this->name($key); } $key .= ' ' . trim($dir); $result[] = $key; } if (!empty($result)) { return ' ORDER BY ' . implode(', ', $result); } return ''; } /** * Create a GROUP BY SQL clause * * @param string $group Group By Condition * @param Model $model * @return string string condition or null */ public function group($group, $model = null) { if ($group) { if (!is_array($group)) { $group = array($group); } foreach($group as $index => $key) { if (is_object($model) && $model->isVirtualField($key)) { $group[$index] = '(' . $model->getVirtualField($key) . ')'; } } $group = implode(', ', $group); return ' GROUP BY ' . $this->_quoteFields($group); } return null; } /** * Disconnects database, kills the connection and says the connection is closed. * * @return void */ public function close() { $this->disconnect(); } /** * Checks if the specified table contains any record matching specified SQL * * @param Model $Model Model to search * @param string $sql SQL WHERE clause (condition only, not the "WHERE" part) * @return boolean True if the table has a matching record, else false */ public function hasAny($Model, $sql) { $sql = $this->conditions($sql); $table = $this->fullTableName($Model); $alias = $this->alias . $this->name($Model->alias); $where = $sql ? "{$sql}" : ' WHERE 1 = 1'; $id = $Model->escapeField(); $out = $this->fetchRow("SELECT COUNT({$id}) {$this->alias}count FROM {$table} {$alias}{$where}"); if (is_array($out)) { return $out[0]['count']; } return false; } /** * Gets the length of a database-native column description, or null if no length * * @param string $real Real database-layer column type (i.e. "varchar(255)") * @return mixed An integer or string representing the length of the column, or null for unknown length. */ public function length($real) { if (!preg_match_all('/([\w\s]+)(?:\((\d+)(?:,(\d+))?\))?(\sunsigned)?(\szerofill)?/', $real, $result)) { $col = str_replace(array(')', 'unsigned'), '', $real); $limit = null; if (strpos($col, '(') !== false) { list($col, $limit) = explode('(', $col); } if ($limit !== null) { return intval($limit); } return null; } $types = array( 'int' => 1, 'tinyint' => 1, 'smallint' => 1, 'mediumint' => 1, 'integer' => 1, 'bigint' => 1 ); list($real, $type, $length, $offset, $sign, $zerofill) = $result; $typeArr = $type; $type = $type[0]; $length = $length[0]; $offset = $offset[0]; $isFloat = in_array($type, array('dec', 'decimal', 'float', 'numeric', 'double')); if ($isFloat && $offset) { return $length . ',' . $offset; } if (($real[0] == $type) && (count($real) === 1)) { return null; } if (isset($types[$type])) { $length += $types[$type]; if (!empty($sign)) { $length--; } } elseif (in_array($type, array('enum', 'set'))) { $length = 0; foreach ($typeArr as $key => $enumValue) { if ($key === 0) { continue; } $tmpLength = strlen($enumValue); if ($tmpLength > $length) { $length = $tmpLength; } } } return intval($length); } /** * Translates between PHP boolean values and Database (faked) boolean values * * @param mixed $data Value to be translated * @param boolean $quote * @return string|boolean Converted boolean value */ public function boolean($data, $quote = false) { if ($quote) { return !empty($data) ? '1' : '0'; } return !empty($data); } /** * Inserts multiple values into a table * * @param string $table * @param string $fields * @param array $values * @return boolean */ public function insertMulti($table, $fields, $values) { $table = $this->fullTableName($table); $holder = implode(',', array_fill(0, count($fields), '?')); $fields = implode(', ', array_map(array(&$this, 'name'), $fields)); $count = count($values); $sql = "INSERT INTO {$table} ({$fields}) VALUES ({$holder})"; $statement = $this->_connection->prepare($sql); $this->begin(); for ($x = 0; $x < $count; $x++) { $statement->execute($values[$x]); $statement->closeCursor(); } return $this->commit(); } /** * Returns an array of the indexes in given datasource name. * * @param string $model Name of model to inspect * @return array Fields in table. Keys are column and unique */ public function index($model) { return false; } /** * Generate a database-native schema for the given Schema object * * @param Model $schema An instance of a subclass of CakeSchema * @param string $tableName Optional. If specified only the table name given will be generated. * Otherwise, all tables defined in the schema are generated. * @return string */ public function createSchema($schema, $tableName = null) { if (!is_a($schema, 'CakeSchema')) { trigger_error(__d('cake_dev', 'Invalid schema object'), E_USER_WARNING); return null; } $out = ''; foreach ($schema->tables as $curTable => $columns) { if (!$tableName || $tableName == $curTable) { $cols = $colList = $indexes = $tableParameters = array(); $primary = null; $table = $this->fullTableName($curTable); foreach ($columns as $name => $col) { if (is_string($col)) { $col = array('type' => $col); } if (isset($col['key']) && $col['key'] === 'primary') { $primary = $name; } if ($name !== 'indexes' && $name !== 'tableParameters') { $col['name'] = $name; if (!isset($col['type'])) { $col['type'] = 'string'; } $cols[] = $this->buildColumn($col); } elseif ($name === 'indexes') { $indexes = array_merge($indexes, $this->buildIndex($col, $table)); } elseif ($name === 'tableParameters') { $tableParameters = array_merge($tableParameters, $this->buildTableParameters($col, $table)); } } if (empty($indexes) && !empty($primary)) { $col = array('PRIMARY' => array('column' => $primary, 'unique' => 1)); $indexes = array_merge($indexes, $this->buildIndex($col, $table)); } $columns = $cols; $out .= $this->renderStatement('schema', compact('table', 'columns', 'indexes', 'tableParameters')) . "\n\n"; } } return $out; } /** * Generate a alter syntax from CakeSchema::compare() * * @param mixed $compare * @param string $table * @return boolean */ public function alterSchema($compare, $table = null) { return false; } /** * Generate a "drop table" statement for the given Schema object * * @param CakeSchema $schema An instance of a subclass of CakeSchema * @param string $table Optional. If specified only the table name given will be generated. * Otherwise, all tables defined in the schema are generated. * @return string */ public function dropSchema(CakeSchema $schema, $table = null) { $out = ''; foreach ($schema->tables as $curTable => $columns) { if (!$table || $table == $curTable) { $out .= 'DROP TABLE ' . $this->fullTableName($curTable) . ";\n"; } } return $out; } /** * Generate a database-native column schema string * * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]), * where options can be 'default', 'length', or 'key'. * @return string */ public function buildColumn($column) { $name = $type = null; extract(array_merge(array('null' => true), $column)); if (empty($name) || empty($type)) { trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING); return null; } if (!isset($this->columns[$type])) { trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING); return null; } $real = $this->columns[$type]; $out = $this->name($name) . ' ' . $real['name']; if (isset($column['length'])) { $length = $column['length']; } elseif (isset($column['limit'])) { $length = $column['limit']; } elseif (isset($real['length'])) { $length = $real['length']; } elseif (isset($real['limit'])) { $length = $real['limit']; } if (isset($length)) { $out .= '(' . $length . ')'; } if (($column['type'] === 'integer' || $column['type'] === 'float' ) && isset($column['default']) && $column['default'] === '') { $column['default'] = null; } $out = $this->_buildFieldParameters($out, $column, 'beforeDefault'); if (isset($column['key']) && $column['key'] === 'primary' && $type === 'integer') { $out .= ' ' . $this->columns['primary_key']['name']; } elseif (isset($column['key']) && $column['key'] === 'primary') { $out .= ' NOT NULL'; } elseif (isset($column['default']) && isset($column['null']) && $column['null'] === false) { $out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL'; } elseif (isset($column['default'])) { $out .= ' DEFAULT ' . $this->value($column['default'], $type); } elseif ($type !== 'timestamp' && !empty($column['null'])) { $out .= ' DEFAULT NULL'; } elseif ($type === 'timestamp' && !empty($column['null'])) { $out .= ' NULL'; } elseif (isset($column['null']) && $column['null'] === false) { $out .= ' NOT NULL'; } if ($type === 'timestamp' && isset($column['default']) && strtolower($column['default']) === 'current_timestamp') { $out = str_replace(array("'CURRENT_TIMESTAMP'", "'current_timestamp'"), 'CURRENT_TIMESTAMP', $out); } return $this->_buildFieldParameters($out, $column, 'afterDefault'); } /** * Build the field parameters, in a position * * @param string $columnString The partially built column string * @param array $columnData The array of column data. * @param string $position The position type to use. 'beforeDefault' or 'afterDefault' are common * @return string a built column with the field parameters added. */ protected function _buildFieldParameters($columnString, $columnData, $position) { foreach ($this->fieldParameters as $paramName => $value) { if (isset($columnData[$paramName]) && $value['position'] == $position) { if (isset($value['options']) && !in_array($columnData[$paramName], $value['options'])) { continue; } $val = $columnData[$paramName]; if ($value['quote']) { $val = $this->value($val); } $columnString .= ' ' . $value['value'] . $value['join'] . $val; } } return $columnString; } /** * Format indexes for create table * * @param array $indexes * @param string $table * @return array */ public function buildIndex($indexes, $table = null) { $join = array(); foreach ($indexes as $name => $value) { $out = ''; if ($name === 'PRIMARY') { $out .= 'PRIMARY '; $name = null; } else { if (!empty($value['unique'])) { $out .= 'UNIQUE '; } $name = $this->startQuote . $name . $this->endQuote; } if (is_array($value['column'])) { $out .= 'KEY ' . $name . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')'; } else { $out .= 'KEY ' . $name . ' (' . $this->name($value['column']) . ')'; } $join[] = $out; } return $join; } /** * Read additional table parameters * * @param string $name * @return array */ public function readTableParameters($name) { $parameters = array(); if (method_exists($this, 'listDetailedSources')) { $currentTableDetails = $this->listDetailedSources($name); foreach ($this->tableParameters as $paramName => $parameter) { if (!empty($parameter['column']) && !empty($currentTableDetails[$parameter['column']])) { $parameters[$paramName] = $currentTableDetails[$parameter['column']]; } } } return $parameters; } /** * Format parameters for create table * * @param array $parameters * @param string $table * @return array */ public function buildTableParameters($parameters, $table = null) { $result = array(); foreach ($parameters as $name => $value) { if (isset($this->tableParameters[$name])) { if ($this->tableParameters[$name]['quote']) { $value = $this->value($value); } $result[] = $this->tableParameters[$name]['value'] . $this->tableParameters[$name]['join'] . $value; } } return $result; } /** * Guesses the data type of an array * * @param string $value * @return void */ public function introspectType($value) { if (!is_array($value)) { if (is_bool($value)) { return 'boolean'; } if (is_float($value) && floatval($value) === $value) { return 'float'; } if (is_int($value) && intval($value) === $value) { return 'integer'; } if (is_string($value) && strlen($value) > 255) { return 'text'; } return 'string'; } $isAllFloat = $isAllInt = true; $containsFloat = $containsInt = $containsString = false; foreach ($value as $key => $valElement) { $valElement = trim($valElement); if (!is_float($valElement) && !preg_match('/^[\d]+\.[\d]+$/', $valElement)) { $isAllFloat = false; } else { $containsFloat = true; continue; } if (!is_int($valElement) && !preg_match('/^[\d]+$/', $valElement)) { $isAllInt = false; } else { $containsInt = true; continue; } $containsString = true; } if ($isAllFloat) { return 'float'; } if ($isAllInt) { return 'integer'; } if ($containsInt && !$containsString) { return 'integer'; } return 'string'; } /** * Writes a new key for the in memory sql query cache * * @param string $sql SQL query * @param mixed $data result of $sql query * @param array $params query params bound as values * @return void */ protected function _writeQueryCache($sql, $data, $params = array()) { if (preg_match('/^\s*select/i', $sql)) { $this->_queryCache[$sql][serialize($params)] = $data; } } /** * Returns the result for a sql query if it is already cached * * @param string $sql SQL query * @param array $params query params bound as values * @return mixed results for query if it is cached, false otherwise */ public function getQueryCache($sql, $params = array()) { if (isset($this->_queryCache[$sql]) && preg_match('/^\s*select/i', $sql)) { $serialized = serialize($params); if (isset($this->_queryCache[$sql][$serialized])) { return $this->_queryCache[$sql][$serialized]; } } return false; } /** * Used for storing in cache the results of the in-memory methodCache * */ public function __destruct() { if ($this->_methodCacheChange) { Cache::write('method_cache', self::$methodCache, '_cake_core_'); } } }
0001-bee
trunk/cakephp2/lib/Cake/Model/Datasource/DboSource.php
PHP
gpl3
90,773
<?php /** * MySQL layer for DBO * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model.Datasource.Database * @since CakePHP(tm) v 0.10.5.1790 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('DboSource', 'Model/Datasource'); /** * MySQL DBO driver object * * Provides connection and SQL generation for MySQL RDMS * * @package Cake.Model.Datasource.Database */ class Mysql extends DboSource { /** * Datasource description * * @var string */ public $description = "MySQL DBO Driver"; /** * Base configuration settings for MySQL driver * * @var array */ protected $_baseConfig = array( 'persistent' => true, 'host' => 'localhost', 'login' => 'root', 'password' => '', 'database' => 'cake', 'port' => '3306' ); /** * Reference to the PDO object connection * * @var PDO $_connection */ protected $_connection = null; /** * Start quote * * @var string */ public $startQuote = "`"; /** * End quote * * @var string */ public $endQuote = "`"; /** * use alias for update and delete. Set to true if version >= 4.1 * * @var boolean */ protected $_useAlias = true; /** * Index of basic SQL commands * * @var array */ protected $_commands = array( 'begin' => 'START TRANSACTION', 'commit' => 'COMMIT', 'rollback' => 'ROLLBACK' ); /** * List of engine specific additional field parameters used on table creating * * @var array */ public $fieldParameters = array( 'charset' => array('value' => 'CHARACTER SET', 'quote' => false, 'join' => ' ', 'column' => false, 'position' => 'beforeDefault'), 'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => ' ', 'column' => 'Collation', 'position' => 'beforeDefault'), 'comment' => array('value' => 'COMMENT', 'quote' => true, 'join' => ' ', 'column' => 'Comment', 'position' => 'afterDefault') ); /** * List of table engine specific parameters used on table creating * * @var array */ public $tableParameters = array( 'charset' => array('value' => 'DEFAULT CHARSET', 'quote' => false, 'join' => '=', 'column' => 'charset'), 'collate' => array('value' => 'COLLATE', 'quote' => false, 'join' => '=', 'column' => 'Collation'), 'engine' => array('value' => 'ENGINE', 'quote' => false, 'join' => '=', 'column' => 'Engine') ); /** * MySQL column definition * * @var array */ public $columns = array( 'primary_key' => array('name' => 'NOT NULL AUTO_INCREMENT'), 'string' => array('name' => 'varchar', 'limit' => '255'), 'text' => array('name' => 'text'), 'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'), 'float' => array('name' => 'float', 'formatter' => 'floatval'), 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'), 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'), 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'), 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'), 'binary' => array('name' => 'blob'), 'boolean' => array('name' => 'tinyint', 'limit' => '1') ); /** * Connects to the database using options in the given configuration array. * * @return boolean True if the database could be connected, else false * @throws MissingConnectionException */ public function connect() { $config = $this->config; $this->connected = false; try { $flags = array( PDO::ATTR_PERSISTENT => $config['persistent'], PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); if (!empty($config['encoding'])) { $flags[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $config['encoding']; } if (empty($config['unix_socket'])) { $dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}"; } else { $dsn = "mysql:unix_socket={$config['unix_socket']};dbname={$config['database']}"; } $this->_connection = new PDO( $dsn, $config['login'], $config['password'], $flags ); $this->connected = true; } catch (PDOException $e) { throw new MissingConnectionException(array('class' => $e->getMessage())); } $this->_useAlias = (bool)version_compare($this->getVersion(), "4.1", ">="); return $this->connected; } /** * Check whether the MySQL extension is installed/loaded * * @return boolean */ public function enabled() { return in_array('mysql', PDO::getAvailableDrivers()); } /** * Returns an array of sources (tables) in the database. * * @param mixed $data * @return array Array of tablenames in the database */ public function listSources($data = null) { $cache = parent::listSources(); if ($cache != null) { return $cache; } $result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database'])); if (!$result) { $result->closeCursor(); return array(); } else { $tables = array(); while ($line = $result->fetch()) { $tables[] = $line[0]; } $result->closeCursor(); parent::listSources($tables); return $tables; } } /** * Builds a map of the columns contained in a result * * @param PDOStatement $results * @return void */ public function resultSet($results) { $this->map = array(); $numFields = $results->columnCount(); $index = 0; while ($numFields-- > 0) { $column = $results->getColumnMeta($index); if (empty($column['native_type'])) { $type = ($column['len'] == 1) ? 'boolean' : 'string'; } else { $type = $column['native_type']; } if (!empty($column['table']) && strpos($column['name'], $this->virtualFieldSeparator) === false) { $this->map[$index++] = array($column['table'], $column['name'], $type); } else { $this->map[$index++] = array(0, $column['name'], $type); } } } /** * Fetches the next row from the current result set * * @return mixed array with results fetched and mapped to column names or false if there is no results left to fetch */ public function fetchResult() { if ($row = $this->_result->fetch()) { $resultRow = array(); foreach ($this->map as $col => $meta) { list($table, $column, $type) = $meta; $resultRow[$table][$column] = $row[$col]; if ($type === 'boolean' && $row[$col] !== null) { $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]); } } return $resultRow; } $this->_result->closeCursor(); return false; } /** * Gets the database encoding * * @return string The database encoding */ public function getEncoding() { return $this->_execute('SHOW VARIABLES LIKE ?', array('character_set_client'))->fetchObject()->Value; } /** * Gets the version string of the database server * * @return string The database encoding */ public function getVersion() { return $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION); } /** * Query charset by collation * * @param string $name Collation name * @return string Character set name */ public function getCharsetName($name) { if ((bool)version_compare($this->getVersion(), "5", ">=")) { $r = $this->_execute('SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME = ?', array($name)); $cols = $r->fetch(); if (isset($cols['CHARACTER_SET_NAME'])) { return $cols['CHARACTER_SET_NAME']; } } return false; } /** * Returns an array of the fields in given table name. * * @param Model|string $model Name of database table to inspect or model instance * @return array Fields in table. Keys are name and type * @throws CakeException */ public function describe($model) { $cache = parent::describe($model); if ($cache != null) { return $cache; } $table = $this->fullTableName($model); $fields = false; $cols = $this->_execute('SHOW FULL COLUMNS FROM ' . $table); if (!$cols) { throw new CakeException(__d('cake_dev', 'Could not describe table for %s', $table)); } foreach ($cols as $column) { $fields[$column->Field] = array( 'type' => $this->column($column->Type), 'null' => ($column->Null === 'YES' ? true : false), 'default' => $column->Default, 'length' => $this->length($column->Type), ); if (!empty($column->Key) && isset($this->index[$column->Key])) { $fields[$column->Field]['key'] = $this->index[$column->Key]; } foreach ($this->fieldParameters as $name => $value) { if (!empty($column->{$value['column']})) { $fields[$column->Field][$name] = $column->{$value['column']}; } } if (isset($fields[$column->Field]['collate'])) { $charset = $this->getCharsetName($fields[$column->Field]['collate']); if ($charset) { $fields[$column->Field]['charset'] = $charset; } } } $this->_cacheDescription($this->fullTableName($model, false), $fields); $cols->closeCursor(); return $fields; } /** * Generates and executes an SQL UPDATE statement for given model, fields, and values. * * @param Model $model * @param array $fields * @param array $values * @param mixed $conditions * @return array */ public function update(Model $model, $fields = array(), $values = null, $conditions = null) { if (!$this->_useAlias) { return parent::update($model, $fields, $values, $conditions); } if ($values == null) { $combined = $fields; } else { $combined = array_combine($fields, $values); } $alias = $joins = false; $fields = $this->_prepareUpdateFields($model, $combined, empty($conditions), !empty($conditions)); $fields = implode(', ', $fields); $table = $this->fullTableName($model); if (!empty($conditions)) { $alias = $this->name($model->alias); if ($model->name == $model->alias) { $joins = implode(' ', $this->_getJoins($model)); } } $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model); if ($conditions === false) { return false; } if (!$this->execute($this->renderStatement('update', compact('table', 'alias', 'joins', 'fields', 'conditions')))) { $model->onError(); return false; } return true; } /** * Generates and executes an SQL DELETE statement for given id/conditions on given model. * * @param Model $model * @param mixed $conditions * @return boolean Success */ public function delete(Model $model, $conditions = null) { if (!$this->_useAlias) { return parent::delete($model, $conditions); } $alias = $this->name($model->alias); $table = $this->fullTableName($model); $joins = implode(' ', $this->_getJoins($model)); if (empty($conditions)) { $alias = $joins = false; } $complexConditions = false; foreach ((array)$conditions as $key => $value) { if (strpos($key, $model->alias) === false) { $complexConditions = true; break; } } if (!$complexConditions) { $joins = false; } $conditions = $this->conditions($this->defaultConditions($model, $conditions, $alias), true, true, $model); if ($conditions === false) { return false; } if ($this->execute($this->renderStatement('delete', compact('alias', 'table', 'joins', 'conditions'))) === false) { $model->onError(); return false; } return true; } /** * Sets the database encoding * * @param string $enc Database encoding * @return boolean */ public function setEncoding($enc) { return $this->_execute('SET NAMES ' . $enc) !== false; } /** * Returns an array of the indexes in given datasource name. * * @param string $model Name of model to inspect * @return array Fields in table. Keys are column and unique */ public function index($model) { $index = array(); $table = $this->fullTableName($model); $old = version_compare($this->getVersion(), '4.1', '<='); if ($table) { $indices = $this->_execute('SHOW INDEX FROM ' . $table); while ($idx = $indices->fetch()) { if ($old) { $idx = (object) current((array)$idx); } if (!isset($index[$idx->Key_name]['column'])) { $col = array(); $index[$idx->Key_name]['column'] = $idx->Column_name; $index[$idx->Key_name]['unique'] = intval($idx->Non_unique == 0); } else { if (!empty($index[$idx->Key_name]['column']) && !is_array($index[$idx->Key_name]['column'])) { $col[] = $index[$idx->Key_name]['column']; } $col[] = $idx->Column_name; $index[$idx->Key_name]['column'] = $col; } } $indices->closeCursor(); } return $index; } /** * Generate a MySQL Alter Table syntax for the given Schema comparison * * @param array $compare Result of a CakeSchema::compare() * @param string $table * @return array Array of alter statements to make. */ public function alterSchema($compare, $table = null) { if (!is_array($compare)) { return false; } $out = ''; $colList = array(); foreach ($compare as $curTable => $types) { $indexes = $tableParameters = $colList = array(); if (!$table || $table == $curTable) { $out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n"; foreach ($types as $type => $column) { if (isset($column['indexes'])) { $indexes[$type] = $column['indexes']; unset($column['indexes']); } if (isset($column['tableParameters'])) { $tableParameters[$type] = $column['tableParameters']; unset($column['tableParameters']); } switch ($type) { case 'add': foreach ($column as $field => $col) { $col['name'] = $field; $alter = 'ADD ' . $this->buildColumn($col); if (isset($col['after'])) { $alter .= ' AFTER ' . $this->name($col['after']); } $colList[] = $alter; } break; case 'drop': foreach ($column as $field => $col) { $col['name'] = $field; $colList[] = 'DROP ' . $this->name($field); } break; case 'change': foreach ($column as $field => $col) { if (!isset($col['name'])) { $col['name'] = $field; } $colList[] = 'CHANGE ' . $this->name($field) . ' ' . $this->buildColumn($col); } break; } } $colList = array_merge($colList, $this->_alterIndexes($curTable, $indexes)); $colList = array_merge($colList, $this->_alterTableParameters($curTable, $tableParameters)); $out .= "\t" . implode(",\n\t", $colList) . ";\n\n"; } } return $out; } /** * Generate a MySQL "drop table" statement for the given Schema object * * @param CakeSchema $schema An instance of a subclass of CakeSchema * @param string $table Optional. If specified only the table name given will be generated. * Otherwise, all tables defined in the schema are generated. * @return string */ public function dropSchema(CakeSchema $schema, $table = null) { $out = ''; foreach ($schema->tables as $curTable => $columns) { if (!$table || $table === $curTable) { $out .= 'DROP TABLE IF EXISTS ' . $this->fullTableName($curTable) . ";\n"; } } return $out; } /** * Generate MySQL table parameter alteration statementes for a table. * * @param string $table Table to alter parameters for. * @param array $parameters Parameters to add & drop. * @return array Array of table property alteration statementes. * @todo Implement this method. */ protected function _alterTableParameters($table, $parameters) { if (isset($parameters['change'])) { return $this->buildTableParameters($parameters['change']); } return array(); } /** * Generate MySQL index alteration statements for a table. * * @param string $table Table to alter indexes for * @param array $indexes Indexes to add and drop * @return array Index alteration statements */ protected function _alterIndexes($table, $indexes) { $alter = array(); if (isset($indexes['drop'])) { foreach($indexes['drop'] as $name => $value) { $out = 'DROP '; if ($name == 'PRIMARY') { $out .= 'PRIMARY KEY'; } else { $out .= 'KEY ' . $name; } $alter[] = $out; } } if (isset($indexes['add'])) { foreach ($indexes['add'] as $name => $value) { $out = 'ADD '; if ($name == 'PRIMARY') { $out .= 'PRIMARY '; $name = null; } else { if (!empty($value['unique'])) { $out .= 'UNIQUE '; } } if (is_array($value['column'])) { $out .= 'KEY '. $name .' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')'; } else { $out .= 'KEY '. $name .' (' . $this->name($value['column']) . ')'; } $alter[] = $out; } } return $alter; } /** * Returns an detailed array of sources (tables) in the database. * * @param string $name Table name to get parameters * @return array Array of tablenames in the database */ public function listDetailedSources($name = null) { $condition = ''; $params = array(); if (is_string($name)) { $condition = ' WHERE name = ' . $this->value($name); $params = array($name); } $result = $this->_connection->query('SHOW TABLE STATUS ' . $condition, PDO::FETCH_ASSOC); if (!$result) { $result->closeCursor(); return array(); } else { $tables = array(); foreach ($result as $row) { $tables[$row['Name']] = (array) $row; unset($tables[$row['Name']]['queryString']); if (!empty($row['Collation'])) { $charset = $this->getCharsetName($row['Collation']); if ($charset) { $tables[$row['Name']]['charset'] = $charset; } } } $result->closeCursor(); if (is_string($name) && isset($tables[$name])) { return $tables[$name]; } return $tables; } } /** * Converts database-layer column types to basic types * * @param string $real Real database-layer column type (i.e. "varchar(255)") * @return string Abstract column type (i.e. "string") */ public function column($real) { if (is_array($real)) { $col = $real['name']; if (isset($real['limit'])) { $col .= '(' . $real['limit'] . ')'; } return $col; } $col = str_replace(')', '', $real); $limit = $this->length($real); if (strpos($col, '(') !== false) { list($col, $vals) = explode('(', $col); } if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) { return $col; } if (($col === 'tinyint' && $limit == 1) || $col === 'boolean') { return 'boolean'; } if (strpos($col, 'int') !== false) { return 'integer'; } if (strpos($col, 'char') !== false || $col === 'tinytext') { return 'string'; } if (strpos($col, 'text') !== false) { return 'text'; } if (strpos($col, 'blob') !== false || $col === 'binary') { return 'binary'; } if (strpos($col, 'float') !== false || strpos($col, 'double') !== false || strpos($col, 'decimal') !== false) { return 'float'; } if (strpos($col, 'enum') !== false) { return "enum($vals)"; } return 'text'; } }
0001-bee
trunk/cakephp2/lib/Cake/Model/Datasource/Database/Mysql.php
PHP
gpl3
19,245
<?php /** * MS SQL Server layer for DBO * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model.Datasource.Database * @since CakePHP(tm) v 0.10.5.1790 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('DboSource', 'Model/Datasource'); /** * Dbo driver for SQLServer * * A Dbo driver for SQLServer 2008 and higher. Requires the `sqlsrv` * and `pdo_sqlsrv` extensions to be enabled. * * @package Cake.Model.Datasource.Database */ class Sqlserver extends DboSource { /** * Driver description * * @var string */ public $description = "SQL Server DBO Driver"; /** * Starting quote character for quoted identifiers * * @var string */ public $startQuote = "["; /** * Ending quote character for quoted identifiers * * @var string */ public $endQuote = "]"; /** * Creates a map between field aliases and numeric indexes. Workaround for the * SQL Server driver's 30-character column name limitation. * * @var array */ protected $_fieldMappings = array(); /** * Storing the last affected value * * @var mixed */ protected $_lastAffected = false; /** * Base configuration settings for MS SQL driver * * @var array */ protected $_baseConfig = array( 'persistent' => true, 'host' => 'localhost\SQLEXPRESS', 'login' => '', 'password' => '', 'database' => 'cake' ); /** * MS SQL column definition * * @var array */ public $columns = array( 'primary_key' => array('name' => 'IDENTITY (1, 1) NOT NULL'), 'string' => array('name' => 'nvarchar', 'limit' => '255'), 'text' => array('name' => 'nvarchar', 'limit' => 'MAX'), 'integer' => array('name' => 'int', 'formatter' => 'intval'), 'float' => array('name' => 'numeric', 'formatter' => 'floatval'), 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'), 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'), 'time' => array('name' => 'datetime', 'format' => 'H:i:s', 'formatter' => 'date'), 'date' => array('name' => 'datetime', 'format' => 'Y-m-d', 'formatter' => 'date'), 'binary' => array('name' => 'varbinary'), 'boolean' => array('name' => 'bit') ); /** * Index of basic SQL commands * * @var array */ protected $_commands = array( 'begin' => 'BEGIN TRANSACTION', 'commit' => 'COMMIT', 'rollback' => 'ROLLBACK' ); /** * Magic column name used to provide pagination support for SQLServer 2008 * which lacks proper limit/offset support. */ const ROW_COUNTER = '_cake_page_rownum_'; /** * The version of SQLServer being used. If greater than 11 * Normal limit offset statements will be used * * @var string */ protected $_version; /** * Connects to the database using options in the given configuration array. * * @return boolean True if the database could be connected, else false * @throws MissingConnectionException */ public function connect() { $config = $this->config; $this->connected = false; try { $flags = array( PDO::ATTR_PERSISTENT => $config['persistent'], PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); if (!empty($config['encoding'])) { $flags[PDO::SQLSRV_ATTR_ENCODING] = $config['encoding']; } $this->_connection = new PDO( "sqlsrv:server={$config['host']};Database={$config['database']}", $config['login'], $config['password'], $flags ); $this->connected = true; } catch (PDOException $e) { throw new MissingConnectionException(array('class' => $e->getMessage())); } $this->_version = $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION); return $this->connected; } /** * Check that PDO SQL Server is installed/loaded * * @return boolean */ public function enabled() { return in_array('sqlsrv', PDO::getAvailableDrivers()); } /** * Returns an array of sources (tables) in the database. * * @param mixed $data * @return array Array of tablenames in the database */ public function listSources($data = null) { $cache = parent::listSources(); if ($cache !== null) { return $cache; } $result = $this->_execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'"); if (!$result) { $result->closeCursor(); return array(); } else { $tables = array(); while ($line = $result->fetch()) { $tables[] = $line[0]; } $result->closeCursor(); parent::listSources($tables); return $tables; } } /** * Returns an array of the fields in given table name. * * @param Model|string $model Model object to describe, or a string table name. * @return array Fields in table. Keys are name and type * @throws CakeException */ public function describe($model) { $cache = parent::describe($model); if ($cache != null) { return $cache; } $fields = array(); $table = $this->fullTableName($model, false); $cols = $this->_execute( "SELECT COLUMN_NAME as Field, DATA_TYPE as Type, COL_LENGTH('" . $table . "', COLUMN_NAME) as Length, IS_NULLABLE As [Null], COLUMN_DEFAULT as [Default], COLUMNPROPERTY(OBJECT_ID('" . $table . "'), COLUMN_NAME, 'IsIdentity') as [Key], NUMERIC_SCALE as Size FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" . $table . "'" ); if (!$cols) { throw new CakeException(__d('cake_dev', 'Could not describe table for %s', $table)); } foreach ($cols as $column) { $field = $column->Field; $fields[$field] = array( 'type' => $this->column($column), 'null' => ($column->Null === 'YES' ? true : false), 'default' => preg_replace("/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/", "$1", $column->Default), 'length' => $this->length($column), 'key' => ($column->Key == '1') ? 'primary' : false ); if ($fields[$field]['default'] === 'null') { $fields[$field]['default'] = null; } else { $this->value($fields[$field]['default'], $fields[$field]['type']); } if ($fields[$field]['key'] !== false && $fields[$field]['type'] == 'integer') { $fields[$field]['length'] = 11; } elseif ($fields[$field]['key'] === false) { unset($fields[$field]['key']); } if (in_array($fields[$field]['type'], array('date', 'time', 'datetime', 'timestamp'))) { $fields[$field]['length'] = null; } if ($fields[$field]['type'] == 'float' && !empty($column->Size)) { $fields[$field]['length'] = $fields[$field]['length'] . ',' . $column->Size; } } $this->_cacheDescription($table, $fields); $cols->closeCursor(); return $fields; } /** * Generates the fields list of an SQL query. * * @param Model $model * @param string $alias Alias tablename * @param array $fields * @param boolean $quote * @return array */ public function fields($model, $alias = null, $fields = array(), $quote = true) { if (empty($alias)) { $alias = $model->alias; } $fields = parent::fields($model, $alias, $fields, false); $count = count($fields); if ($count >= 1 && strpos($fields[0], 'COUNT(*)') === false) { $result = array(); for ($i = 0; $i < $count; $i++) { $prepend = ''; if (strpos($fields[$i], 'DISTINCT') !== false) { $prepend = 'DISTINCT '; $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i])); } if (!preg_match('/\s+AS\s+/i', $fields[$i])) { if (substr($fields[$i], -1) == '*') { if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') { $build = explode('.', $fields[$i]); $AssociatedModel = $model->{$build[0]}; } else { $AssociatedModel = $model; } $_fields = $this->fields($AssociatedModel, $AssociatedModel->alias, array_keys($AssociatedModel->schema())); $result = array_merge($result, $_fields); continue; } if (strpos($fields[$i], '.') === false) { $this->_fieldMappings[$alias . '__' . $fields[$i]] = $alias . '.' . $fields[$i]; $fieldName = $this->name($alias . '.' . $fields[$i]); $fieldAlias = $this->name($alias . '__' . $fields[$i]); } else { $build = explode('.', $fields[$i]); $this->_fieldMappings[$build[0] . '__' .$build[1]] = $fields[$i]; $fieldName = $this->name($build[0] . '.' . $build[1]); $fieldAlias = $this->name(preg_replace("/^\[(.+)\]$/", "$1", $build[0]) . '__' . $build[1]); } if ($model->getColumnType($fields[$i]) == 'datetime') { $fieldName = "CONVERT(VARCHAR(20), {$fieldName}, 20)"; } $fields[$i] = "{$fieldName} AS {$fieldAlias}"; } $result[] = $prepend . $fields[$i]; } return $result; } else { return $fields; } } /** * Generates and executes an SQL INSERT statement for given model, fields, and values. * Removes Identity (primary key) column from update data before returning to parent, if * value is empty. * * @param Model $model * @param array $fields * @param array $values * @return array */ public function create(Model $model, $fields = null, $values = null) { if (!empty($values)) { $fields = array_combine($fields, $values); } $primaryKey = $this->_getPrimaryKey($model); if (array_key_exists($primaryKey, $fields)) { if (empty($fields[$primaryKey])) { unset($fields[$primaryKey]); } else { $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' ON'); } } $result = parent::create($model, array_keys($fields), array_values($fields)); if (array_key_exists($primaryKey, $fields) && !empty($fields[$primaryKey])) { $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' OFF'); } return $result; } /** * Generates and executes an SQL UPDATE statement for given model, fields, and values. * Removes Identity (primary key) column from update data before returning to parent. * * @param Model $model * @param array $fields * @param array $values * @param mixed $conditions * @return array */ public function update(Model $model, $fields = array(), $values = null, $conditions = null) { if (!empty($values)) { $fields = array_combine($fields, $values); } if (isset($fields[$model->primaryKey])) { unset($fields[$model->primaryKey]); } if (empty($fields)) { return true; } return parent::update($model, array_keys($fields), array_values($fields), $conditions); } /** * Returns a limit statement in the correct format for the particular database. * * @param integer $limit Limit of results returned * @param integer $offset Offset from which to start results * @return string SQL limit/offset statement */ public function limit($limit, $offset = null) { if ($limit) { $rt = ''; if (!strpos(strtolower($limit), 'top') || strpos(strtolower($limit), 'top') === 0) { $rt = ' TOP'; } $rt .= ' ' . $limit; if (is_int($offset) && $offset > 0) { $rt = ' OFFSET ' . intval($offset) . ' ROWS FETCH FIRST ' . intval($limit) . ' ROWS ONLY'; } return $rt; } return null; } /** * Converts database-layer column types to basic types * * @param mixed $real Either the string value of the fields type. * or the Result object from Sqlserver::describe() * @return string Abstract column type (i.e. "string") */ public function column($real) { $limit = null; $col = $real; if (is_object($real) && isset($real->Field)) { $limit = $real->Length; $col = $real->Type; } if ($col == 'datetime2') { return 'datetime'; } if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) { return $col; } if ($col == 'bit') { return 'boolean'; } if (strpos($col, 'int') !== false) { return 'integer'; } if (strpos($col, 'char') !== false && $limit == -1) { return 'text'; } if (strpos($col, 'char') !== false) { return 'string'; } if (strpos($col, 'text') !== false) { return 'text'; } if (strpos($col, 'binary') !== false || $col == 'image') { return 'binary'; } if (in_array($col, array('float', 'real', 'decimal', 'numeric'))) { return 'float'; } return 'text'; } /** * Handle SQLServer specific length properties. * SQLServer handles text types as nvarchar/varchar with a length of -1. * * @param mixed $length Either the length as a string, or a Column descriptor object. * @return mixed null|integer with length of column. */ public function length($length) { if (is_object($length) && isset($length->Length)) { if ($length->Length == -1 && strpos($length->Type, 'char') !== false) { return null; } if (in_array($length->Type, array('nchar', 'nvarchar'))) { return floor($length->Length / 2); } return $length->Length; } return parent::length($length); } /** * Builds a map of the columns contained in a result * * @param PDOStatement $results * @return void */ public function resultSet($results) { $this->map = array(); $numFields = $results->columnCount(); $index = 0; while ($numFields-- > 0) { $column = $results->getColumnMeta($index); $name = $column['name']; if (strpos($name, '__')) { if (isset($this->_fieldMappings[$name]) && strpos($this->_fieldMappings[$name], '.')) { $map = explode('.', $this->_fieldMappings[$name]); } elseif (isset($this->_fieldMappings[$name])) { $map = array(0, $this->_fieldMappings[$name]); } else { $map = array(0, $name); } } else { $map = array(0, $name); } $map[] = ($column['sqlsrv:decl_type'] == 'bit') ? 'boolean' : $column['native_type']; $this->map[$index++] = $map; } } /** * Builds final SQL statement * * @param string $type Query type * @param array $data Query data * @return string */ public function renderStatement($type, $data) { switch (strtolower($type)) { case 'select': extract($data); $fields = trim($fields); if (strpos($limit, 'TOP') !== false && strpos($fields, 'DISTINCT ') === 0) { $limit = 'DISTINCT ' . trim($limit); $fields = substr($fields, 9); } // hack order as SQLServer requires an order if there is a limit. if ($limit && !$order) { $order = 'ORDER BY (SELECT NULL)'; } // For older versions use the subquery version of pagination. if (version_compare($this->_version, '11', '<') && preg_match('/FETCH\sFIRST\s+([0-9]+)/i', $limit, $offset)) { preg_match('/OFFSET\s*(\d+)\s*.*?(\d+)\s*ROWS/', $limit, $limitOffset); $limit = 'TOP ' . intval($limitOffset[2]); $page = intval($limitOffset[1] / $limitOffset[2]); $offset = intval($limitOffset[2] * $page); $rowCounter = self::ROW_COUNTER; return " SELECT {$limit} * FROM ( SELECT {$fields}, ROW_NUMBER() OVER ({$order}) AS {$rowCounter} FROM {$table} {$alias} {$joins} {$conditions} {$group} ) AS _cake_paging_ WHERE _cake_paging_.{$rowCounter} > {$offset} ORDER BY _cake_paging_.{$rowCounter} "; } elseif (strpos($limit, 'FETCH') !== false) { return "SELECT {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order} {$limit}"; } else { return "SELECT {$limit} {$fields} FROM {$table} {$alias} {$joins} {$conditions} {$group} {$order}"; } break; case "schema": extract($data); foreach ($indexes as $i => $index) { if (preg_match('/PRIMARY KEY/', $index)) { unset($indexes[$i]); break; } } foreach (array('columns', 'indexes') as $var) { if (is_array(${$var})) { ${$var} = "\t" . implode(",\n\t", array_filter(${$var})); } } return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}"; break; default: return parent::renderStatement($type, $data); break; } } /** * Returns a quoted and escaped string of $data for use in an SQL statement. * * @param string $data String to be prepared for use in an SQL statement * @param string $column The column into which this data will be inserted * @return string Quoted and escaped data */ public function value($data, $column = null) { if (is_array($data) || is_object($data)) { return parent::value($data, $column); } elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) { return $data; } if (empty($column)) { $column = $this->introspectType($data); } switch ($column) { case 'string': case 'text': return 'N' . $this->_connection->quote($data, PDO::PARAM_STR); default: return parent::value($data, $column); } } /** * Returns an array of all result rows for a given SQL query. * Returns false if no rows matched. * * @param Model $model * @param array $queryData * @param integer $recursive * @return array Array of resultset rows, or false if no rows matched */ public function read(Model $model, $queryData = array(), $recursive = null) { $results = parent::read($model, $queryData, $recursive); $this->_fieldMappings = array(); return $results; } /** * Fetches the next row from the current result set. * Eats the magic ROW_COUNTER variable. * * @return mixed */ public function fetchResult() { if ($row = $this->_result->fetch()) { $resultRow = array(); foreach ($this->map as $col => $meta) { list($table, $column, $type) = $meta; if ($table === 0 && $column === self::ROW_COUNTER) { continue; } $resultRow[$table][$column] = $row[$col]; if ($type === 'boolean' && !is_null($row[$col])) { $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]); } } return $resultRow; } $this->_result->closeCursor(); return false; } /** * Inserts multiple values into a table * * @param string $table * @param string $fields * @param array $values * @return void */ public function insertMulti($table, $fields, $values) { $primaryKey = $this->_getPrimaryKey($table); $hasPrimaryKey = $primaryKey != null && ( (is_array($fields) && in_array($primaryKey, $fields) || (is_string($fields) && strpos($fields, $this->startQuote . $primaryKey . $this->endQuote) !== false)) ); if ($hasPrimaryKey) { $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($table) . ' ON'); } $table = $this->fullTableName($table); $fields = implode(', ', array_map(array(&$this, 'name'), $fields)); $this->begin(); foreach ($values as $value) { $holder = implode(', ', array_map(array(&$this, 'value'), $value)); $this->_execute("INSERT INTO {$table} ({$fields}) VALUES ({$holder})"); } $this->commit(); if ($hasPrimaryKey) { $this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($table) . ' OFF'); } } /** * Generate a database-native column schema string * * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]), * where options can be 'default', 'length', or 'key'. * @return string */ public function buildColumn($column) { $result = preg_replace('/(int|integer)\([0-9]+\)/i', '$1', parent::buildColumn($column)); if (strpos($result, 'DEFAULT NULL') !== false) { if (isset($column['default']) && $column['default'] === '') { $result = str_replace('DEFAULT NULL', "DEFAULT ''", $result); } else { $result = str_replace('DEFAULT NULL', 'NULL', $result); } } elseif (array_keys($column) == array('type', 'name')) { $result .= ' NULL'; } elseif (strpos($result, "DEFAULT N'")) { $result = str_replace("DEFAULT N'", "DEFAULT '", $result); } return $result; } /** * Format indexes for create table * * @param array $indexes * @param string $table * @return string */ public function buildIndex($indexes, $table = null) { $join = array(); foreach ($indexes as $name => $value) { if ($name == 'PRIMARY') { $join[] = 'PRIMARY KEY (' . $this->name($value['column']) . ')'; } else if (isset($value['unique']) && $value['unique']) { $out = "ALTER TABLE {$table} ADD CONSTRAINT {$name} UNIQUE"; if (is_array($value['column'])) { $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column'])); } else { $value['column'] = $this->name($value['column']); } $out .= "({$value['column']});"; $join[] = $out; } } return $join; } /** * Makes sure it will return the primary key * * @param mixed $model Model instance of table name * @return string */ protected function _getPrimaryKey($model) { if (!is_object($model)) { $model = new Model(false, $model); } $schema = $this->describe($model); foreach ($schema as $field => $props) { if (isset($props['key']) && $props['key'] == 'primary') { return $field; } } return null; } /** * Returns number of affected rows in previous database operation. If no previous operation exists, * this returns false. * * @param mixed $source * @return integer Number of affected rows */ public function lastAffected($source = null) { $affected = parent::lastAffected(); if ($affected === null && $this->_lastAffected !== false) { return $this->_lastAffected; } return $affected; } /** * Executes given SQL statement. * * @param string $sql SQL statement * @param array $params list of params to be bound to query (supported only in select) * @param array $prepareOptions Options to be used in the prepare statement * @return mixed PDOStatement if query executes with no problem, true as the result of a succesfull, false on error * query returning no rows, suchs as a CREATE statement, false otherwise */ protected function _execute($sql, $params = array(), $prepareOptions = array()) { $this->_lastAffected = false; if (strncasecmp($sql, 'SELECT', 6) == 0) { $prepareOptions += array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL); return parent::_execute($sql, $params, $prepareOptions); } try { $this->_lastAffected = $this->_connection->exec($sql); if ($this->_lastAffected === false) { $this->_results = null; $error = $this->_connection->errorInfo(); $this->error = $error[2]; return false; } return true; } catch (PDOException $e) { if (isset($query->queryString)) { $e->queryString = $query->queryString; } else { $e->queryString = $sql; } throw $e; } } /** * Generate a "drop table" statement for the given Schema object * * @param CakeSchema $schema An instance of a subclass of CakeSchema * @param string $table Optional. If specified only the table name given will be generated. * Otherwise, all tables defined in the schema are generated. * @return string */ public function dropSchema(CakeSchema $schema, $table = null) { $out = ''; foreach ($schema->tables as $curTable => $columns) { if (!$table || $table == $curTable) { $t = $this->fullTableName($curTable); $out .= "IF OBJECT_ID('" . $this->fullTableName($curTable, false). "', 'U') IS NOT NULL DROP TABLE " . $this->fullTableName($curTable) . ";\n"; } } return $out; } }
0001-bee
trunk/cakephp2/lib/Cake/Model/Datasource/Database/Sqlserver.php
PHP
gpl3
23,196
<?php /** * SQLite layer for DBO * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model.Datasource.Database * @since CakePHP(tm) v 0.9.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('DboSource', 'Model/Datasource'); /** * DBO implementation for the SQLite3 DBMS. * * A DboSource adapter for SQLite 3 using PDO * * @package Cake.Model.Datasource.Database */ class Sqlite extends DboSource { /** * Datasource Description * * @var string */ public $description = "SQLite DBO Driver"; /** * Quote Start * * @var string */ public $startQuote = '"'; /** * Quote End * * @var string */ public $endQuote = '"'; /** * Base configuration settings for SQLite3 driver * * @var array */ protected $_baseConfig = array( 'persistent' => false, 'database' => null ); /** * SQLite3 column definition * * @var array */ public $columns = array( 'primary_key' => array('name' => 'integer primary key autoincrement'), 'string' => array('name' => 'varchar', 'limit' => '255'), 'text' => array('name' => 'text'), 'integer' => array('name' => 'integer', 'limit' => null, 'formatter' => 'intval'), 'float' => array('name' => 'float', 'formatter' => 'floatval'), 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'), 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'), 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'), 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'), 'binary' => array('name' => 'blob'), 'boolean' => array('name' => 'boolean') ); /** * List of engine specific additional field parameters used on table creating * * @var array */ public $fieldParameters = array( 'collate' => array( 'value' => 'COLLATE', 'quote' => false, 'join' => ' ', 'column' => 'Collate', 'position' => 'afterDefault', 'options' => array( 'BINARY', 'NOCASE', 'RTRIM' ) ), ); /** * Connects to the database using config['database'] as a filename. * * @return boolean * @throws MissingConnectionException */ public function connect() { $config = $this->config; $flags = array( PDO::ATTR_PERSISTENT => $config['persistent'], PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); try { $this->_connection = new PDO('sqlite:' . $config['database'], null, null, $flags); $this->connected = true; } catch(PDOException $e) { throw new MissingConnectionException(array('class' => $e->getMessage())); } return $this->connected; } /** * Check whether the MySQL extension is installed/loaded * * @return boolean */ public function enabled() { return in_array('sqlite', PDO::getAvailableDrivers()); } /** * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits. * * @param mixed $data * @return array Array of tablenames in the database */ public function listSources($data = null) { $cache = parent::listSources(); if ($cache != null) { return $cache; } $result = $this->fetchAll("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;", false); if (!$result || empty($result)) { return array(); } else { $tables = array(); foreach ($result as $table) { $tables[] = $table[0]['name']; } parent::listSources($tables); return $tables; } return array(); } /** * Returns an array of the fields in given table name. * * @param Model|string $model Either the model or table name you want described. * @return array Fields in table. Keys are name and type */ public function describe($model) { $cache = parent::describe($model); if ($cache != null) { return $cache; } $table = $this->fullTableName($model); $fields = array(); $result = $this->_execute('PRAGMA table_info(' . $table . ')'); foreach ($result as $column) { $column = (array) $column; $default = ($column['dflt_value'] === 'NULL') ? null : trim($column['dflt_value'], "'"); $fields[$column['name']] = array( 'type' => $this->column($column['type']), 'null' => !$column['notnull'], 'default' => $default, 'length' => $this->length($column['type']) ); if ($column['pk'] == 1) { $fields[$column['name']]['key'] = $this->index['PRI']; $fields[$column['name']]['null'] = false; if (empty($fields[$column['name']]['length'])) { $fields[$column['name']]['length'] = 11; } } } $result->closeCursor(); $this->_cacheDescription($table, $fields); return $fields; } /** * Generates and executes an SQL UPDATE statement for given model, fields, and values. * * @param Model $model * @param array $fields * @param array $values * @param mixed $conditions * @return array */ public function update(Model $model, $fields = array(), $values = null, $conditions = null) { if (empty($values) && !empty($fields)) { foreach ($fields as $field => $value) { if (strpos($field, $model->alias . '.') !== false) { unset($fields[$field]); $field = str_replace($model->alias . '.', "", $field); $field = str_replace($model->alias . '.', "", $field); $fields[$field] = $value; } } } return parent::update($model, $fields, $values, $conditions); } /** * Deletes all the records in a table and resets the count of the auto-incrementing * primary key, where applicable. * * @param mixed $table A string or model class representing the table to be truncated * @return boolean SQL TRUNCATE TABLE statement, false if not applicable. */ public function truncate($table) { $this->_execute('DELETE FROM sqlite_sequence where name=' . $this->fullTableName($table)); return $this->execute('DELETE FROM ' . $this->fullTableName($table)); } /** * Converts database-layer column types to basic types * * @param string $real Real database-layer column type (i.e. "varchar(255)") * @return string Abstract column type (i.e. "string") */ public function column($real) { if (is_array($real)) { $col = $real['name']; if (isset($real['limit'])) { $col .= '('.$real['limit'].')'; } return $col; } $col = strtolower(str_replace(')', '', $real)); $limit = null; @list($col, $limit) = explode('(', $col); if (in_array($col, array('text', 'integer', 'float', 'boolean', 'timestamp', 'date', 'datetime', 'time'))) { return $col; } if (strpos($col, 'varchar') !== false) { return 'string'; } if (in_array($col, array('blob', 'clob'))) { return 'binary'; } if (strpos($col, 'numeric') !== false || strpos($col, 'decimal') !== false) { return 'float'; } return 'text'; } /** * Generate ResultSet * * @param mixed $results * @return void */ public function resultSet($results) { $this->results = $results; $this->map = array(); $num_fields = $results->columnCount(); $index = 0; $j = 0; //PDO::getColumnMeta is experimental and does not work with sqlite3, // so try to figure it out based on the querystring $querystring = $results->queryString; if (stripos($querystring, 'SELECT') === 0) { $last = strripos($querystring, 'FROM'); if ($last !== false) { $selectpart = substr($querystring, 7, $last - 8); $selects = explode(',', $selectpart); } } elseif (strpos($querystring, 'PRAGMA table_info') === 0) { $selects = array('cid', 'name', 'type', 'notnull', 'dflt_value', 'pk'); } elseif(strpos($querystring, 'PRAGMA index_list') === 0) { $selects = array('seq', 'name', 'unique'); } elseif(strpos($querystring, 'PRAGMA index_info') === 0) { $selects = array('seqno', 'cid', 'name'); } while ($j < $num_fields) { if (!isset($selects[$j])) { $j++; continue; } if (preg_match('/\bAS\s+(.*)/i', $selects[$j], $matches)) { $columnName = trim($matches[1],'"'); } else { $columnName = trim(str_replace('"', '', $selects[$j])); } if (strpos($selects[$j], 'DISTINCT') === 0) { $columnName = str_ireplace('DISTINCT', '', $columnName); } $metaType = false; try { $metaData = (array)$results->getColumnMeta($j); if (!empty($metaData['sqlite:decl_type'])) { $metaType = trim($metaData['sqlite:decl_type']); } } catch (Exception $e) {} if (strpos($columnName, '.')) { $parts = explode('.', $columnName); $this->map[$index++] = array(trim($parts[0]), trim($parts[1]), $metaType); } else { $this->map[$index++] = array(0, $columnName, $metaType); } $j++; } } /** * Fetches the next row from the current result set * * @return mixed array with results fetched and mapped to column names or false if there is no results left to fetch */ public function fetchResult() { if ($row = $this->_result->fetch()) { $resultRow = array(); foreach ($this->map as $col => $meta) { list($table, $column, $type) = $meta; $resultRow[$table][$column] = $row[$col]; if ($type == 'boolean' && !is_null($row[$col])) { $resultRow[$table][$column] = $this->boolean($resultRow[$table][$column]); } } return $resultRow; } else { $this->_result->closeCursor(); return false; } } /** * Returns a limit statement in the correct format for the particular database. * * @param integer $limit Limit of results returned * @param integer $offset Offset from which to start results * @return string SQL limit/offset statement */ public function limit($limit, $offset = null) { if ($limit) { $rt = ''; if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) { $rt = ' LIMIT'; } $rt .= ' ' . $limit; if ($offset) { $rt .= ' OFFSET ' . $offset; } return $rt; } return null; } /** * Generate a database-native column schema string * * @param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]), * where options can be 'default', 'length', or 'key'. * @return string */ public function buildColumn($column) { $name = $type = null; $column = array_merge(array('null' => true), $column); extract($column); if (empty($name) || empty($type)) { trigger_error(__d('cake_dev', 'Column name or type not defined in schema'), E_USER_WARNING); return null; } if (!isset($this->columns[$type])) { trigger_error(__d('cake_dev', 'Column type %s does not exist', $type), E_USER_WARNING); return null; } $real = $this->columns[$type]; $out = $this->name($name) . ' ' . $real['name']; if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') { return $this->name($name) . ' ' . $this->columns['primary_key']['name']; } return parent::buildColumn($column); } /** * Sets the database encoding * * @param string $enc Database encoding * @return boolean */ public function setEncoding($enc) { if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) { return false; } return $this->_execute("PRAGMA encoding = \"{$enc}\"") !== false; } /** * Gets the database encoding * * @return string The database encoding */ public function getEncoding() { return $this->fetchRow('PRAGMA encoding'); } /** * Removes redundant primary key indexes, as they are handled in the column def of the key. * * @param array $indexes * @param string $table * @return string */ public function buildIndex($indexes, $table = null) { $join = array(); foreach ($indexes as $name => $value) { if ($name == 'PRIMARY') { continue; } $out = 'CREATE '; if (!empty($value['unique'])) { $out .= 'UNIQUE '; } if (is_array($value['column'])) { $value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column'])); } else { $value['column'] = $this->name($value['column']); } $t = trim($table, '"'); $out .= "INDEX {$t}_{$name} ON {$table}({$value['column']});"; $join[] = $out; } return $join; } /** * Overrides DboSource::index to handle SQLite indexe introspection * Returns an array of the indexes in given table name. * * @param string $model Name of model to inspect * @return array Fields in table. Keys are column and unique */ public function index($model) { $index = array(); $table = $this->fullTableName($model); if ($table) { $indexes = $this->query('PRAGMA index_list(' . $table . ')'); if (is_bool($indexes)) { return array(); } foreach ($indexes as $i => $info) { $key = array_pop($info); $keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")'); foreach ($keyInfo as $keyCol) { if (!isset($index[$key['name']])) { $col = array(); if (preg_match('/autoindex/', $key['name'])) { $key['name'] = 'PRIMARY'; } $index[$key['name']]['column'] = $keyCol[0]['name']; $index[$key['name']]['unique'] = intval($key['unique'] == 1); } else { if (!is_array($index[$key['name']]['column'])) { $col[] = $index[$key['name']]['column']; } $col[] = $keyCol[0]['name']; $index[$key['name']]['column'] = $col; } } } } return $index; } /** * Overrides DboSource::renderStatement to handle schema generation with SQLite-style indexes * * @param string $type * @param array $data * @return string */ public function renderStatement($type, $data) { switch (strtolower($type)) { case 'schema': extract($data); if (is_array($columns)) { $columns = "\t" . join(",\n\t", array_filter($columns)); } if (is_array($indexes)) { $indexes = "\t" . join("\n\t", array_filter($indexes)); } return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}"; break; default: return parent::renderStatement($type, $data); break; } } /** * PDO deals in objects, not resources, so overload accordingly. * * @return boolean */ public function hasResult() { return is_object($this->_result); } /** * Generate a "drop table" statement for the given Schema object * * @param CakeSchema $schema An instance of a subclass of CakeSchema * @param string $table Optional. If specified only the table name given will be generated. * Otherwise, all tables defined in the schema are generated. * @return string */ public function dropSchema(CakeSchema $schema, $table = null) { $out = ''; foreach ($schema->tables as $curTable => $columns) { if (!$table || $table == $curTable) { $out .= 'DROP TABLE IF EXISTS ' . $this->fullTableName($curTable) . ";\n"; } } return $out; } }
0001-bee
trunk/cakephp2/lib/Cake/Model/Datasource/Database/Sqlite.php
PHP
gpl3
14,954
<?php /** * PostgreSQL layer for DBO. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model.Datasource.Database * @since CakePHP(tm) v 0.9.1.114 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('DboSource', 'Model/Datasource'); /** * PostgreSQL layer for DBO. * * Long description for class * * @package Cake.Model.Datasource.Database */ class Postgres extends DboSource { /** * Driver description * * @var string */ public $description = "PostgreSQL DBO Driver"; /** * Index of basic SQL commands * * @var array */ protected $_commands = array( 'begin' => 'BEGIN', 'commit' => 'COMMIT', 'rollback' => 'ROLLBACK' ); /** * Base driver configuration settings. Merged with user settings. * * @var array */ protected $_baseConfig = array( 'persistent' => true, 'host' => 'localhost', 'login' => 'root', 'password' => '', 'database' => 'cake', 'schema' => 'public', 'port' => 5432, 'encoding' => '' ); /** * Columns * * @var array */ public $columns = array( 'primary_key' => array('name' => 'serial NOT NULL'), 'string' => array('name' => 'varchar', 'limit' => '255'), 'text' => array('name' => 'text'), 'integer' => array('name' => 'integer', 'formatter' => 'intval'), 'float' => array('name' => 'float', 'formatter' => 'floatval'), 'datetime' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'), 'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'), 'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'), 'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'), 'binary' => array('name' => 'bytea'), 'boolean' => array('name' => 'boolean'), 'number' => array('name' => 'numeric'), 'inet' => array('name' => 'inet') ); /** * Starting Quote * * @var string */ public $startQuote = '"'; /** * Ending Quote * * @var string */ public $endQuote = '"'; /** * Contains mappings of custom auto-increment sequences, if a table uses a sequence name * other than what is dictated by convention. * * @var array */ protected $_sequenceMap = array(); /** * Connects to the database using options in the given configuration array. * * @return boolean True if successfully connected. * @throws MissingConnectionException */ public function connect() { $config = $this->config; $this->connected = false; try { $flags = array( PDO::ATTR_PERSISTENT => $config['persistent'], PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); $this->_connection = new PDO( "pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']}", $config['login'], $config['password'], $flags ); $this->connected = true; if (!empty($config['encoding'])) { $this->setEncoding($config['encoding']); } if (!empty($config['schema'])) { $this->_execute('SET search_path TO ' . $config['schema']); } } catch (PDOException $e) { throw new MissingConnectionException(array('class' => $e->getMessage())); } return $this->connected; } /** * Check if PostgreSQL is enabled/loaded * * @return boolean */ public function enabled() { return in_array('pgsql', PDO::getAvailableDrivers()); } /** * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits. * * @param mixed $data * @return array Array of tablenames in the database */ public function listSources($data = null) { $cache = parent::listSources(); if ($cache != null) { return $cache; } $schema = $this->config['schema']; $sql = "SELECT table_name as name FROM INFORMATION_SCHEMA.tables WHERE table_schema = ?"; $result = $this->_execute($sql, array($schema)); if (!$result) { return array(); } else { $tables = array(); foreach ($result as $item) { $tables[] = $item->name; } $result->closeCursor(); parent::listSources($tables); return $tables; } } /** * Returns an array of the fields in given table name. * * @param Model|string $model Name of database table to inspect * @return array Fields in table. Keys are name and type */ public function describe($model) { $fields = parent::describe($model); $table = $this->fullTableName($model, false); $this->_sequenceMap[$table] = array(); $cols = null; if ($fields === null) { $cols = $this->_execute( "SELECT DISTINCT column_name AS name, data_type AS type, is_nullable AS null, column_default AS default, ordinal_position AS position, character_maximum_length AS char_length, character_octet_length AS oct_length FROM information_schema.columns WHERE table_name = ? AND table_schema = ? ORDER BY position", array($table, $this->config['schema']) ); foreach ($cols as $c) { $type = $c->type; if (!empty($c->oct_length) && $c->char_length === null) { if ($c->type == 'character varying') { $length = null; $type = 'text'; } else { $length = intval($c->oct_length); } } elseif (!empty($c->char_length)) { $length = intval($c->char_length); } else { $length = $this->length($c->type); } if (empty($length)) { $length = null; } $fields[$c->name] = array( 'type' => $this->column($type), 'null' => ($c->null == 'NO' ? false : true), 'default' => preg_replace( "/^'(.*)'$/", "$1", preg_replace('/::.*/', '', $c->default) ), 'length' => $length ); if ($model instanceof Model) { if ($c->name == $model->primaryKey) { $fields[$c->name]['key'] = 'primary'; if ($fields[$c->name]['type'] !== 'string') { $fields[$c->name]['length'] = 11; } } } if ( $fields[$c->name]['default'] == 'NULL' || preg_match('/nextval\([\'"]?([\w.]+)/', $c->default, $seq) ) { $fields[$c->name]['default'] = null; if (!empty($seq) && isset($seq[1])) { $this->_sequenceMap[$table][$c->default] = $seq[1]; } } if ($fields[$c->name]['type'] == 'boolean' && !empty($fields[$c->name]['default'])) { $fields[$c->name]['default'] = constant($fields[$c->name]['default']); } } $this->_cacheDescription($table, $fields); } if (isset($model->sequence)) { $this->_sequenceMap[$table][$model->primaryKey] = $model->sequence; } if ($cols) { $cols->closeCursor(); } return $fields; } /** * Returns the ID generated from the previous INSERT operation. * * @param string $source Name of the database table * @param string $field Name of the ID database field. Defaults to "id" * @return integer */ public function lastInsertId($source = null, $field = 'id') { $seq = $this->getSequence($source, $field); return $this->_connection->lastInsertId($seq); } /** * Gets the associated sequence for the given table/field * * @param mixed $table Either a full table name (with prefix) as a string, or a model object * @param string $field Name of the ID database field. Defaults to "id" * @return string The associated sequence name from the sequence map, defaults to "{$table}_{$field}_seq" */ public function getSequence($table, $field = 'id') { if (is_object($table)) { $table = $this->fullTableName($table, false); } if (isset($this->_sequenceMap[$table]) && isset($this->_sequenceMap[$table][$field])) { return $this->_sequenceMap[$table][$field]; } else { return "{$table}_{$field}_seq"; } } /** * Deletes all the records in a table and drops all associated auto-increment sequences * * @param mixed $table A string or model class representing the table to be truncated * @param boolean $reset true for resseting the sequence, false to leave it as is. * and if 1, sequences are not modified * @return boolean SQL TRUNCATE TABLE statement, false if not applicable. */ public function truncate($table, $reset = 0) { $table = $this->fullTableName($table, false); if (!isset($this->_sequenceMap[$table])) { $cache = $this->cacheSources; $this->cacheSources = false; $this->describe($table); $this->cacheSources = $cache; } if ($this->execute('DELETE FROM ' . $this->fullTableName($table))) { $table = $this->fullTableName($table, false); if (isset($this->_sequenceMap[$table]) && $reset !== 1) { foreach ($this->_sequenceMap[$table] as $field => $sequence) { $this->_execute("ALTER SEQUENCE \"{$sequence}\" RESTART WITH 1"); } } return true; } return false; } /** * Prepares field names to be quoted by parent * * @param string $data * @return string SQL field */ public function name($data) { if (is_string($data)) { $data = str_replace('"__"', '__', $data); } return parent::name($data); } /** * Generates the fields list of an SQL query. * * @param Model $model * @param string $alias Alias tablename * @param mixed $fields * @param boolean $quote * @return array */ public function fields($model, $alias = null, $fields = array(), $quote = true) { if (empty($alias)) { $alias = $model->alias; } $fields = parent::fields($model, $alias, $fields, false); if (!$quote) { return $fields; } $count = count($fields); if ($count >= 1 && !preg_match('/^\s*COUNT\(\*/', $fields[0])) { $result = array(); for ($i = 0; $i < $count; $i++) { if (!preg_match('/^.+\\(.*\\)/', $fields[$i]) && !preg_match('/\s+AS\s+/', $fields[$i])) { if (substr($fields[$i], -1) == '*') { if (strpos($fields[$i], '.') !== false && $fields[$i] != $alias . '.*') { $build = explode('.', $fields[$i]); $AssociatedModel = $model->{$build[0]}; } else { $AssociatedModel = $model; } $_fields = $this->fields($AssociatedModel, $AssociatedModel->alias, array_keys($AssociatedModel->schema())); $result = array_merge($result, $_fields); continue; } $prepend = ''; if (strpos($fields[$i], 'DISTINCT') !== false) { $prepend = 'DISTINCT '; $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i])); } if (strrpos($fields[$i], '.') === false) { $fields[$i] = $prepend . $this->name($alias) . '.' . $this->name($fields[$i]) . ' AS ' . $this->name($alias . '__' . $fields[$i]); } else { $build = explode('.', $fields[$i]); $fields[$i] = $prepend . $this->name($build[0]) . '.' . $this->name($build[1]) . ' AS ' . $this->name($build[0] . '__' . $build[1]); } } else { $fields[$i] = preg_replace_callback('/\(([\s\.\w]+)\)/', array(&$this, '_quoteFunctionField'), $fields[$i]); } $result[] = $fields[$i]; } return $result; } return $fields; } /** * Auxiliary function to quote matched `(Model.fields)` from a preg_replace_callback call * * @param string $match matched string * @return string quoted strig */ protected function _quoteFunctionField($match) { $prepend = ''; if (strpos($match[1], 'DISTINCT') !== false) { $prepend = 'DISTINCT '; $match[1] = trim(str_replace('DISTINCT', '', $match[1])); } if (strpos($match[1], '.') === false) { $match[1] = $this->name($match[1]); } else { $parts = explode('.', $match[1]); if (!Set::numeric($parts)) { $match[1] = $this->name($match[1]); } } return '(' . $prepend .$match[1] . ')'; } /** * Returns an array of the indexes in given datasource name. * * @param string $model Name of model to inspect * @return array Fields in table. Keys are column and unique */ public function index($model) { $index = array(); $table = $this->fullTableName($model, false); if ($table) { $indexes = $this->query("SELECT c2.relname, i.indisprimary, i.indisunique, i.indisclustered, i.indisvalid, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) as statement, c2.reltablespace FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i WHERE c.oid = ( SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname ~ '^(" . $table . ")$' AND pg_catalog.pg_table_is_visible(c.oid) AND n.nspname ~ '^(" . $this->config['schema'] . ")$' ) AND c.oid = i.indrelid AND i.indexrelid = c2.oid ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname", false); foreach ($indexes as $i => $info) { $key = array_pop($info); if ($key['indisprimary']) { $key['relname'] = 'PRIMARY'; } $col = array(); preg_match('/\(([^\)]+)\)/', $key['statement'], $indexColumns); $parsedColumn = $indexColumns[1]; if (strpos($indexColumns[1], ',') !== false) { $parsedColumn = explode(', ', $indexColumns[1]); } $index[$key['relname']]['unique'] = $key['indisunique']; $index[$key['relname']]['column'] = $parsedColumn; } } return $index; } /** * Alter the Schema of a table. * * @param array $compare Results of CakeSchema::compare() * @param string $table name of the table * @return array */ public function alterSchema($compare, $table = null) { if (!is_array($compare)) { return false; } $out = ''; $colList = array(); foreach ($compare as $curTable => $types) { $indexes = $colList = array(); if (!$table || $table == $curTable) { $out .= 'ALTER TABLE ' . $this->fullTableName($curTable) . " \n"; foreach ($types as $type => $column) { if (isset($column['indexes'])) { $indexes[$type] = $column['indexes']; unset($column['indexes']); } switch ($type) { case 'add': foreach ($column as $field => $col) { $col['name'] = $field; $colList[] = 'ADD COLUMN '.$this->buildColumn($col); } break; case 'drop': foreach ($column as $field => $col) { $col['name'] = $field; $colList[] = 'DROP COLUMN '.$this->name($field); } break; case 'change': foreach ($column as $field => $col) { if (!isset($col['name'])) { $col['name'] = $field; } $fieldName = $this->name($field); $default = isset($col['default']) ? $col['default'] : null; $nullable = isset($col['null']) ? $col['null'] : null; unset($col['default'], $col['null']); $colList[] = 'ALTER COLUMN '. $fieldName .' TYPE ' . str_replace(array($fieldName, 'NOT NULL'), '', $this->buildColumn($col)); if (isset($nullable)) { $nullable = ($nullable) ? 'DROP NOT NULL' : 'SET NOT NULL'; $colList[] = 'ALTER COLUMN '. $fieldName .' ' . $nullable; } if (isset($default)) { $colList[] = 'ALTER COLUMN '. $fieldName .' SET DEFAULT ' . $this->value($default, $col['type']); } else { $colList[] = 'ALTER COLUMN '. $fieldName .' DROP DEFAULT'; } } break; } } if (isset($indexes['drop']['PRIMARY'])) { $colList[] = 'DROP CONSTRAINT ' . $curTable . '_pkey'; } if (isset($indexes['add']['PRIMARY'])) { $cols = $indexes['add']['PRIMARY']['column']; if (is_array($cols)) { $cols = implode(', ', $cols); } $colList[] = 'ADD PRIMARY KEY (' . $cols . ')'; } if (!empty($colList)) { $out .= "\t" . implode(",\n\t", $colList) . ";\n\n"; } else { $out = ''; } $out .= implode(";\n\t", $this->_alterIndexes($curTable, $indexes)); } } return $out; } /** * Generate PostgreSQL index alteration statements for a table. * * @param string $table Table to alter indexes for * @param array $indexes Indexes to add and drop * @return array Index alteration statements */ protected function _alterIndexes($table, $indexes) { $alter = array(); if (isset($indexes['drop'])) { foreach($indexes['drop'] as $name => $value) { $out = 'DROP '; if ($name == 'PRIMARY') { continue; } else { $out .= 'INDEX ' . $name; } $alter[] = $out; } } if (isset($indexes['add'])) { foreach ($indexes['add'] as $name => $value) { $out = 'CREATE '; if ($name == 'PRIMARY') { continue; } else { if (!empty($value['unique'])) { $out .= 'UNIQUE '; } $out .= 'INDEX '; } if (is_array($value['column'])) { $out .= $name . ' ON ' . $table . ' (' . implode(', ', array_map(array(&$this, 'name'), $value['column'])) . ')'; } else { $out .= $name . ' ON ' . $table . ' (' . $this->name($value['column']) . ')'; } $alter[] = $out; } } return $alter; } /** * Returns a limit statement in the correct format for the particular database. * * @param integer $limit Limit of results returned * @param integer $offset Offset from which to start results * @return string SQL limit/offset statement */ public function limit($limit, $offset = null) { if ($limit) { $rt = ''; if (!strpos(strtolower($limit), 'limit') || strpos(strtolower($limit), 'limit') === 0) { $rt = ' LIMIT'; } $rt .= ' ' . $limit; if ($offset) { $rt .= ' OFFSET ' . $offset; } return $rt; } return null; } /** * Converts database-layer column types to basic types * * @param string $real Real database-layer column type (i.e. "varchar(255)") * @return string Abstract column type (i.e. "string") */ public function column($real) { if (is_array($real)) { $col = $real['name']; if (isset($real['limit'])) { $col .= '(' . $real['limit'] . ')'; } return $col; } $col = str_replace(')', '', $real); $limit = null; if (strpos($col, '(') !== false) { list($col, $limit) = explode('(', $col); } $floats = array( 'float', 'float4', 'float8', 'double', 'double precision', 'decimal', 'real', 'numeric' ); switch (true) { case (in_array($col, array('date', 'time', 'inet', 'boolean'))): return $col; case (strpos($col, 'timestamp') !== false): return 'datetime'; case (strpos($col, 'time') === 0): return 'time'; case (strpos($col, 'int') !== false && $col != 'interval'): return 'integer'; case (strpos($col, 'char') !== false || $col == 'uuid'): return 'string'; case (strpos($col, 'text') !== false): return 'text'; case (strpos($col, 'bytea') !== false): return 'binary'; case (in_array($col, $floats)): return 'float'; default: return 'text'; break; } } /** * Gets the length of a database-native column description, or null if no length * * @param string $real Real database-layer column type (i.e. "varchar(255)") * @return integer An integer representing the length of the column */ public function length($real) { $col = str_replace(array(')', 'unsigned'), '', $real); $limit = null; if (strpos($col, '(') !== false) { list($col, $limit) = explode('(', $col); } if ($col == 'uuid') { return 36; } if ($limit != null) { return intval($limit); } return null; } /** * resultSet method * * @param array $results * @return void */ public function resultSet(&$results) { $this->map = array(); $numFields = $results->columnCount(); $index = 0; $j = 0; while ($j < $numFields) { $column = $results->getColumnMeta($j); if (strpos($column['name'], '__')) { list($table, $name) = explode('__', $column['name']); $this->map[$index++] = array($table, $name, $column['native_type']); } else { $this->map[$index++] = array(0, $column['name'], $column['native_type']); } $j++; } } /** * Fetches the next row from the current result set * * @return array */ public function fetchResult() { if ($row = $this->_result->fetch()) { $resultRow = array(); foreach ($this->map as $index => $meta) { list($table, $column, $type) = $meta; switch ($type) { case 'bool': $resultRow[$table][$column] = is_null($row[$index]) ? null : $this->boolean($row[$index]); break; case 'binary': case 'bytea': $resultRow[$table][$column] = stream_get_contents($row[$index]); break; default: $resultRow[$table][$column] = $row[$index]; break; } } return $resultRow; } else { $this->_result->closeCursor(); return false; } } /** * Translates between PHP boolean values and PostgreSQL boolean values * * @param mixed $data Value to be translated * @param boolean $quote true to quote a boolean to be used in a query, flase to return the boolean value * @return boolean Converted boolean value */ public function boolean($data, $quote = false) { switch (true) { case ($data === true || $data === false): $result = $data; break; case ($data === 't' || $data === 'f'): $result = ($data === 't'); break; case ($data === 'true' || $data === 'false'): $result = ($data === 'true'); break; case ($data === 'TRUE' || $data === 'FALSE'): $result = ($data === 'TRUE'); break; default: $result = (bool) $data; break; } if ($quote) { return ($result) ? 'TRUE' : 'FALSE'; } return (bool) $result; } /** * Sets the database encoding * * @param mixed $enc Database encoding * @return boolean True on success, false on failure */ public function setEncoding($enc) { return $this->_execute('SET NAMES ' . $this->value($enc)) !== false; } /** * Gets the database encoding * * @return string The database encoding */ public function getEncoding() { $result = $this->_execute('SHOW client_encoding')->fetch(); if ($result === false) { return false; } return (isset($result['client_encoding'])) ? $result['client_encoding'] : false; } /** * Generate a Postgres-native column schema string * * @param array $column An array structured like the following: * array('name'=>'value', 'type'=>'value'[, options]), * where options can be 'default', 'length', or 'key'. * @return string */ public function buildColumn($column) { $col = $this->columns[$column['type']]; if (!isset($col['length']) && !isset($col['limit'])) { unset($column['length']); } $out = preg_replace('/integer\([0-9]+\)/', 'integer', parent::buildColumn($column)); $out = str_replace('integer serial', 'serial', $out); if (strpos($out, 'timestamp DEFAULT')) { if (isset($column['null']) && $column['null']) { $out = str_replace('DEFAULT NULL', '', $out); } else { $out = str_replace('DEFAULT NOT NULL', '', $out); } } if (strpos($out, 'DEFAULT DEFAULT')) { if (isset($column['null']) && $column['null']) { $out = str_replace('DEFAULT DEFAULT', 'DEFAULT NULL', $out); } elseif (in_array($column['type'], array('integer', 'float'))) { $out = str_replace('DEFAULT DEFAULT', 'DEFAULT 0', $out); } elseif ($column['type'] == 'boolean') { $out = str_replace('DEFAULT DEFAULT', 'DEFAULT FALSE', $out); } } return $out; } /** * Format indexes for create table * * @param array $indexes * @param string $table * @return string */ public function buildIndex($indexes, $table = null) { $join = array(); if (!is_array($indexes)) { return array(); } foreach ($indexes as $name => $value) { if ($name == 'PRIMARY') { $out = 'PRIMARY KEY (' . $this->name($value['column']) . ')'; } else { $out = 'CREATE '; if (!empty($value['unique'])) { $out .= 'UNIQUE '; } if (is_array($value['column'])) { $value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column'])); } else { $value['column'] = $this->name($value['column']); } $out .= "INDEX {$name} ON {$table}({$value['column']});"; } $join[] = $out; } return $join; } /** * Overrides DboSource::renderStatement to handle schema generation with Postgres-style indexes * * @param string $type * @param array $data * @return string */ public function renderStatement($type, $data) { switch (strtolower($type)) { case 'schema': extract($data); foreach ($indexes as $i => $index) { if (preg_match('/PRIMARY KEY/', $index)) { unset($indexes[$i]); $columns[] = $index; break; } } $join = array('columns' => ",\n\t", 'indexes' => "\n"); foreach (array('columns', 'indexes') as $var) { if (is_array(${$var})) { ${$var} = implode($join[$var], array_filter(${$var})); } } return "CREATE TABLE {$table} (\n\t{$columns}\n);\n{$indexes}"; break; default: return parent::renderStatement($type, $data); break; } } }
0001-bee
trunk/cakephp2/lib/Cake/Model/Datasource/Database/Postgres.php
PHP
gpl3
24,832
<?php /** * Session class for Cake. * * Cake abstracts the handling of sessions. * There are several convenient methods to access session information. * This class is the implementation of those methods. * They are mostly used by the Session Component. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model.Datasource * @since CakePHP(tm) v .0.10.0.1222 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Set', 'Utility'); App::uses('Security', 'Utility'); /** * Session class for Cake. * * Cake abstracts the handling of sessions. There are several convenient methods to access session information. * This class is the implementation of those methods. They are mostly used by the Session Component. * * @package Cake.Model.Datasource */ class CakeSession { /** * True if the Session is still valid * * @var boolean */ public static $valid = false; /** * Error messages for this session * * @var array */ public static $error = false; /** * User agent string * * @var string */ protected static $_userAgent = ''; /** * Path to where the session is active. * * @var string */ public static $path = '/'; /** * Error number of last occurred error * * @var integer */ public static $lastError = null; /** * 'Security.level' setting, "high", "medium", or "low". * * @var string */ public static $security = null; /** * Start time for this session. * * @var integer */ public static $time = false; /** * Cookie lifetime * * @var integer */ public static $cookieLifeTime; /** * Time when this session becomes invalid. * * @var integer */ public static $sessionTime = false; /** * Current Session id * * @var string */ public static $id = null; /** * Hostname * * @var string */ public static $host = null; /** * Session timeout multiplier factor * * @var integer */ public static $timeout = null; /** * Number of requests that can occur during a session time without the session being renewed. * This feature is only used when `Session.harden` is set to true. * * @var integer * @see CakeSession::_checkValid() */ public static $requestCountdown = 10; /** * Constructor. * * @param string $base The base path for the Session * @param boolean $start Should session be started right now * @return void */ public static function init($base = null, $start = true) { self::$time = time(); $checkAgent = Configure::read('Session.checkAgent'); if (($checkAgent === true || $checkAgent === null) && env('HTTP_USER_AGENT') != null) { self::$_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt')); } self::_setPath($base); self::_setHost(env('HTTP_HOST')); } /** * Setup the Path variable * * @param string $base base path * @return void */ protected static function _setPath($base = null) { if (empty($base)) { self::$path = '/'; return; } if (strpos($base, 'index.php') !== false) { $base = str_replace('index.php', '', $base); } if (strpos($base, '?') !== false) { $base = str_replace('?', '', $base); } self::$path = $base; } /** * Set the host name * * @param string $host Hostname * @return void */ protected static function _setHost($host) { self::$host = $host; if (strpos(self::$host, ':') !== false) { self::$host = substr(self::$host, 0, strpos(self::$host, ':')); } } /** * Starts the Session. * * @return boolean True if session was started */ public static function start() { if (self::started()) { return true; } $id = self::id(); session_write_close(); self::_configureSession(); self::_startSession(); if (!$id && self::started()) { self::_checkValid(); } self::$error = false; return self::started(); } /** * Determine if Session has been started. * * @return boolean True if session has been started. */ public static function started() { return isset($_SESSION) && session_id(); } /** * Returns true if given variable is set in session. * * @param string $name Variable name to check for * @return boolean True if variable is there */ public static function check($name = null) { if (!self::started() && !self::start()) { return false; } if (empty($name)) { return false; } $result = Set::classicExtract($_SESSION, $name); return isset($result); } /** * Returns the Session id * * @param string $id * @return string Session id */ public static function id($id = null) { if ($id) { self::$id = $id; session_id(self::$id); } if (self::started()) { return session_id(); } return self::$id; } /** * Removes a variable from session. * * @param string $name Session variable to remove * @return boolean Success */ public static function delete($name) { if (self::check($name)) { self::_overwrite($_SESSION, Set::remove($_SESSION, $name)); return (self::check($name) == false); } self::_setError(2, __d('cake_dev', "%s doesn't exist", $name)); return false; } /** * Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself * * @param array $old Set of old variables => values * @param array $new New set of variable => value * @return void */ protected static function _overwrite(&$old, $new) { if (!empty($old)) { foreach ($old as $key => $var) { if (!isset($new[$key])) { unset($old[$key]); } } } foreach ($new as $key => $var) { $old[$key] = $var; } } /** * Return error description for given error number. * * @param integer $errorNumber Error to set * @return string Error as string */ protected static function _error($errorNumber) { if (!is_array(self::$error) || !array_key_exists($errorNumber, self::$error)) { return false; } else { return self::$error[$errorNumber]; } } /** * Returns last occurred error as a string, if any. * * @return mixed Error description as a string, or false. */ public static function error() { if (self::$lastError) { return self::_error(self::$lastError); } return false; } /** * Returns true if session is valid. * * @return boolean Success */ public static function valid() { if (self::read('Config')) { if (self::_validAgentAndTime() && self::$error === false) { self::$valid = true; } else { self::$valid = false; self::_setError(1, 'Session Highjacking Attempted !!!'); } } return self::$valid; } /** * Tests that the user agent is valid and that the session hasn't 'timed out'. * Since timeouts are implemented in CakeSession it checks the current self::$time * against the time the session is set to expire. The User agent is only checked * if Session.checkAgent == true. * * @return boolean */ protected static function _validAgentAndTime() { $config = self::read('Config'); $validAgent = ( Configure::read('Session.checkAgent') === false || self::$_userAgent == $config['userAgent'] ); return ($validAgent && self::$time <= $config['time']); } /** * Get / Set the userAgent * * @param string $userAgent Set the userAgent * @return void */ public static function userAgent($userAgent = null) { if ($userAgent) { self::$_userAgent = $userAgent; } return self::$_userAgent; } /** * Returns given session variable, or all of them, if no parameters given. * * @param mixed $name The name of the session variable (or a path as sent to Set.extract) * @return mixed The value of the session variable */ public static function read($name = null) { if (!self::started() && !self::start()) { return false; } if (is_null($name)) { return self::_returnSessionVars(); } if (empty($name)) { return false; } $result = Set::classicExtract($_SESSION, $name); if (!is_null($result)) { return $result; } self::_setError(2, "$name doesn't exist"); return null; } /** * Returns all session variables. * * @return mixed Full $_SESSION array, or false on error. */ protected static function _returnSessionVars() { if (!empty($_SESSION)) { return $_SESSION; } self::_setError(2, 'No Session vars set'); return false; } /** * Writes value to given session variable name. * * @param mixed $name Name of variable * @param string $value Value to write * @return boolean True if the write was successful, false if the write failed */ public static function write($name, $value = null) { if (!self::started() && !self::start()) { return false; } if (empty($name)) { return false; } $write = $name; if (!is_array($name)) { $write = array($name => $value); } foreach ($write as $key => $val) { self::_overwrite($_SESSION, Set::insert($_SESSION, $key, $val)); if (Set::classicExtract($_SESSION, $key) !== $val) { return false; } } return true; } /** * Helper method to destroy invalid sessions. * * @return void */ public static function destroy() { if (self::started()) { session_destroy(); } self::clear(); } /** * Clears the session, the session id, and renew's the session. * * @return void */ public static function clear() { $_SESSION = null; self::$id = null; self::start(); self::renew(); } /** * Helper method to initialize a session, based on Cake core settings. * * Sessions can be configured with a few shortcut names as well as have any number of ini settings declared. * * @return void * @throws CakeSessionException Throws exceptions when ini_set() fails. */ protected static function _configureSession() { $sessionConfig = Configure::read('Session'); $iniSet = function_exists('ini_set'); if (isset($sessionConfig['defaults'])) { $defaults = self::_defaultConfig($sessionConfig['defaults']); if ($defaults) { $sessionConfig = Set::merge($defaults, $sessionConfig); } } if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS')) { $sessionConfig['ini']['session.cookie_secure'] = 1; } if (isset($sessionConfig['timeout']) && !isset($sessionConfig['cookieTimeout'])) { $sessionConfig['cookieTimeout'] = $sessionConfig['timeout']; } if (!isset($sessionConfig['ini']['session.cookie_lifetime'])) { $sessionConfig['ini']['session.cookie_lifetime'] = $sessionConfig['cookieTimeout'] * 60; } if (!isset($sessionConfig['ini']['session.name'])) { $sessionConfig['ini']['session.name'] = $sessionConfig['cookie']; } if (!empty($sessionConfig['handler'])) { $sessionConfig['ini']['session.save_handler'] = 'user'; } if (empty($_SESSION)) { if (!empty($sessionConfig['ini']) && is_array($sessionConfig['ini'])) { foreach ($sessionConfig['ini'] as $setting => $value) { if (ini_set($setting, $value) === false) { throw new CakeSessionException(sprintf( __d('cake_dev', 'Unable to configure the session, setting %s failed.'), $setting )); } } } } if (!empty($sessionConfig['handler']) && !isset($sessionConfig['handler']['engine'])) { call_user_func_array('session_set_save_handler', $sessionConfig['handler']); } if (!empty($sessionConfig['handler']['engine'])) { $handler = self::_getHandler($sessionConfig['handler']['engine']); session_set_save_handler( array($handler, 'open'), array($handler, 'close'), array($handler, 'read'), array($handler, 'write'), array($handler, 'destroy'), array($handler, 'gc') ); } Configure::write('Session', $sessionConfig); self::$sessionTime = self::$time + ($sessionConfig['timeout'] * 60); } /** * Find the handler class and make sure it implements the correct interface. * * @param string $handler * @return void * @throws CakeSessionException */ protected static function _getHandler($handler) { list($plugin, $class) = pluginSplit($handler, true); App::uses($class, $plugin . 'Model/Datasource/Session'); if (!class_exists($class)) { throw new CakeSessionException(__d('cake_dev', 'Could not load %s to handle the session.', $class)); } $handler = new $class(); if ($handler instanceof CakeSessionHandlerInterface) { return $handler; } throw new CakeSessionException(__d('cake_dev', 'Chosen SessionHandler does not implement CakeSessionHandlerInterface it cannot be used with an engine key.')); } /** * Get one of the prebaked default session configurations. * * @param string $name * @return boolean|array */ protected static function _defaultConfig($name) { $defaults = array( 'php' => array( 'cookie' => 'CAKEPHP', 'timeout' => 240, 'cookieTimeout' => 240, 'ini' => array( 'session.use_trans_sid' => 0, 'session.cookie_path' => self::$path, 'session.save_handler' => 'files' ) ), 'cake' => array( 'cookie' => 'CAKEPHP', 'timeout' => 240, 'cookieTimeout' => 240, 'ini' => array( 'session.use_trans_sid' => 0, 'url_rewriter.tags' => '', 'session.serialize_handler' => 'php', 'session.use_cookies' => 1, 'session.cookie_path' => self::$path, 'session.auto_start' => 0, 'session.save_path' => TMP . 'sessions', 'session.save_handler' => 'files' ) ), 'cache' => array( 'cookie' => 'CAKEPHP', 'timeout' => 240, 'cookieTimeout' => 240, 'ini' => array( 'session.use_trans_sid' => 0, 'url_rewriter.tags' => '', 'session.auto_start' => 0, 'session.use_cookies' => 1, 'session.cookie_path' => self::$path, 'session.save_handler' => 'user', ), 'handler' => array( 'engine' => 'CacheSession', 'config' => 'default' ) ), 'database' => array( 'cookie' => 'CAKEPHP', 'timeout' => 240, 'cookieTimeout' => 240, 'ini' => array( 'session.use_trans_sid' => 0, 'url_rewriter.tags' => '', 'session.auto_start' => 0, 'session.use_cookies' => 1, 'session.cookie_path' => self::$path, 'session.save_handler' => 'user', 'session.serialize_handler' => 'php', ), 'handler' => array( 'engine' => 'DatabaseSession', 'model' => 'Session' ) ) ); if (isset($defaults[$name])) { return $defaults[$name]; } return false; } /** * Helper method to start a session * * @return boolean Success */ protected static function _startSession() { if (headers_sent()) { if (empty($_SESSION)) { $_SESSION = array(); } } elseif (!isset($_SESSION)) { session_cache_limiter ("must-revalidate"); session_start(); header ('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"'); } else { session_start(); } return true; } /** * Helper method to create a new session. * * @return void */ protected static function _checkValid() { if (!self::started() && !self::start()) { self::$valid = false; return false; } if ($config = self::read('Config')) { $sessionConfig = Configure::read('Session'); if (self::_validAgentAndTime()) { $time = $config['time']; self::write('Config.time', self::$sessionTime); if (isset($sessionConfig['autoRegenerate']) && $sessionConfig['autoRegenerate'] === true) { $check = $config['countdown']; $check -= 1; self::write('Config.countdown', $check); if (time() > ($time - ($sessionConfig['timeout'] * 60) + 2) || $check < 1) { self::renew(); self::write('Config.countdown', self::$requestCountdown); } } self::$valid = true; } else { self::destroy(); self::$valid = false; self::_setError(1, 'Session Highjacking Attempted !!!'); } } else { self::write('Config.userAgent', self::$_userAgent); self::write('Config.time', self::$sessionTime); self::write('Config.countdown', self::$requestCountdown); self::$valid = true; } } /** * Restarts this session. * * @return void */ public static function renew() { if (session_id()) { if (session_id() != '' || isset($_COOKIE[session_name()])) { setcookie(Configure::read('Session.cookie'), '', time() - 42000, self::$path); } session_regenerate_id(true); } } /** * Helper method to set an internal error message. * * @param integer $errorNumber Number of the error * @param string $errorMessage Description of the error * @return void */ protected static function _setError($errorNumber, $errorMessage) { if (self::$error === false) { self::$error = array(); } self::$error[$errorNumber] = $errorMessage; self::$lastError = $errorNumber; } } /** * Interface for Session handlers. Custom session handler classes should implement * this interface as it allows CakeSession know how to map methods to session_set_save_handler() * * @package Cake.Model.Datasource */ interface CakeSessionHandlerInterface { /** * Method called on open of a session. * * @return boolean Success */ public function open(); /** * Method called on close of a session. * * @return boolean Success */ public function close(); /** * Method used to read from a session. * * @param mixed $id The key of the value to read * @return mixed The value of the key or false if it does not exist */ public function read($id); /** * Helper function called on write for sessions. * * @param integer $id ID that uniquely identifies session in database * @param mixed $data The value of the data to be saved. * @return boolean True for successful write, false otherwise. */ public function write($id, $data); /** * Method called on the destruction of a session. * * @param integer $id ID that uniquely identifies session in database * @return boolean True for successful delete, false otherwise. */ public function destroy($id); /** * Run the Garbage collection on the session storage. This method should vacuum all * expired or dead sessions. * * @param integer $expires Timestamp (defaults to current time) * @return boolean Success */ public function gc($expires = null); } // Initialize the session CakeSession::init();
0001-bee
trunk/cakephp2/lib/Cake/Model/Datasource/CakeSession.php
PHP
gpl3
18,324
<?php /** * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Load Model and AppModel */ App::uses('AppModel', 'Model'); /** * Permissions linking AROs with ACOs * * @package Cake.Model */ class Permission extends AppModel { /** * Model name * * @var string */ public $name = 'Permission'; /** * Explicitly disable in-memory query caching * * @var boolean */ public $cacheQueries = false; /** * Override default table name * * @var string */ public $useTable = 'aros_acos'; /** * Permissions link AROs with ACOs * * @var array */ public $belongsTo = array('Aro', 'Aco'); /** * No behaviors for this model * * @var array */ public $actsAs = null; /** * Constructor, used to tell this model to use the * database configured for ACL */ public function __construct() { $config = Configure::read('Acl.database'); if (!empty($config)) { $this->useDbConfig = $config; } parent::__construct(); } }
0001-bee
trunk/cakephp2/lib/Cake/Model/Permission.php
PHP
gpl3
1,485
<?php /** * Object-relational mapper. * * DBO-backed object data model, for mapping database tables to Cake objects. * * PHP versions 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model * @since CakePHP(tm) v 0.10.0.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Included libs */ App::uses('ClassRegistry', 'Utility'); App::uses('Validation', 'Utility'); App::uses('String', 'Utility'); App::uses('BehaviorCollection', 'Model'); App::uses('ModelBehavior', 'Model'); App::uses('ConnectionManager', 'Model'); App::uses('Xml', 'Utility'); /** * Object-relational mapper. * * DBO-backed object data model. * Automatically selects a database table name based on a pluralized lowercase object class name * (i.e. class 'User' => table 'users'; class 'Man' => table 'men') * The table is required to have at least 'id auto_increment' primary key. * * @package Cake.Model * @link http://book.cakephp.org/2.0/en/models.html */ class Model extends Object { /** * The name of the DataSource connection that this Model uses * * The value must be an attribute name that you defined in `app/Config/database.php` * or created using `ConnectionManager::create()`. * * @var string * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#usedbconfig */ public $useDbConfig = 'default'; /** * Custom database table name, or null/false if no table association is desired. * * @var string * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#useTable */ public $useTable = null; /** * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements. * * This field is also used in `find('list')` when called with no extra parameters in the fields list * * @var string * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#displayField */ public $displayField = null; /** * Value of the primary key ID of the record that this model is currently pointing to. * Automatically set after database insertions. * * @var mixed */ public $id = false; /** * Container for the data that this model gets from persistent storage (usually, a database). * * @var array * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#data */ public $data = array(); /** * Table name for this Model. * * @var string */ public $table = false; /** * The name of the primary key field for this model. * * @var string * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#primaryKey */ public $primaryKey = null; /** * Field-by-field table metadata. * * @var array */ protected $_schema = null; /** * List of validation rules. It must be an array with the field name as key and using * as value one of the following possibilities * * ### Validating using regular expressions * * {{{ * public $validate = array( * 'name' => '/^[a-z].+$/i' * ); * }}} * * ### Validating using methods (no parameters) * * {{{ * public $validate = array( * 'name' => 'notEmpty' * ); * }}} * * ### Validating using methods (with parameters) * * {{{ * public $validate = array( * 'age' => array( * 'rule' => array('between', 5, 25) * ) * ); * }}} * * ### Validating using custom method * * {{{ * public $validate = array( * 'password' => array( * 'rule' => array('customValidation') * ) * ); * public function customValidation($data) { * // $data will contain array('password' => 'value') * if (isset($this->data[$this->alias]['password2'])) { * return $this->data[$this->alias]['password2'] === current($data); * } * return true; * } * }}} * * ### Validations with messages * * The messages will be used in Model::$validationErrors and can be used in the FormHelper * * {{{ * public $validate = array( * 'age' => array( * 'rule' => array('between', 5, 25), * 'message' => array('The age must be between %d and %d.') * ) * ); * }}} * * ### Multiple validations to the same field * * {{{ * public $validate = array( * 'login' => array( * array( * 'rule' => 'alphaNumeric', * 'message' => 'Only alphabets and numbers allowed', * 'last' => true * ), * array( * 'rule' => array('minLength', 8), * 'message' => array('Minimum length of %d characters') * ) * ) * ); * }}} * * ### Valid keys in validations * * - `rule`: String with method name, regular expression (started by slash) or array with method and parameters * - `message`: String with the message or array if have multiple parameters. See http://php.net/sprintf * - `last`: Boolean value to indicate if continue validating the others rules if the current fail [Default: true] * - `required`: Boolean value to indicate if the field must be present on save * - `allowEmpty`: Boolean value to indicate if the field can be empty * - `on`: Possible values: `update`, `create`. Indicate to apply this rule only on update or create * * @var array * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#validate * @link http://book.cakephp.org/2.0/en/models/data-validation.html */ public $validate = array(); /** * List of validation errors. * * @var array */ public $validationErrors = array(); /** * Name of the validation string domain to use when translating validation errors. * * @var string */ public $validationDomain = null; /** * Database table prefix for tables in model. * * @var string * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#tableprefix */ public $tablePrefix = null; /** * Name of the model. * * @var string * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#name */ public $name = null; /** * Alias name for model. * * @var string */ public $alias = null; /** * List of table names included in the model description. Used for associations. * * @var array */ public $tableToModel = array(); /** * Whether or not to cache queries for this model. This enables in-memory * caching only, the results are not stored beyond the current request. * * @var boolean * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#cacheQueries */ public $cacheQueries = false; /** * Detailed list of belongsTo associations. * * ### Basic usage * * `public $belongsTo = array('Group', 'Department');` * * ### Detailed configuration * * {{{ * public $belongsTo = array( * 'Group', * 'Department' => array( * 'className' => 'Department', * 'foreignKey' => 'department_id' * ) * ); * }}} * * ### Possible keys in association * * - `className`: the classname of the model being associated to the current model. * If you’re defining a ‘Profile belongsTo User’ relationship, the className key should equal ‘User.’ * - `foreignKey`: the name of the foreign key found in the current model. This is * especially handy if you need to define multiple belongsTo relationships. The default * value for this key is the underscored, singular name of the other model, suffixed with ‘_id’. * - `conditions`: An SQL fragment used to filter related model records. It’s good * practice to use model names in SQL fragments: “User.active = 1” is always * better than just “active = 1.” * - `type`: the type of the join to use in the SQL query, default is LEFT which * may not fit your needs in all situations, INNER may be helpful when you want * everything from your main and associated models or nothing at all!(effective * when used with some conditions of course). (NB: type value is in lower case - i.e. left, inner) * - `fields`: A list of fields to be retrieved when the associated model data is * fetched. Returns all fields by default. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows. * - `counterCache`: If set to true the associated Model will automatically increase or * decrease the “[singular_model_name]_count” field in the foreign table whenever you do * a save() or delete(). If its a string then its the field name to use. The value in the * counter field represents the number of related rows. * - `counterScope`: Optional conditions array to use for updating counter cache field. * * @var array * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto */ public $belongsTo = array(); /** * Detailed list of hasOne associations. * * ### Basic usage * * `public $hasOne = array('Profile', 'Address');` * * ### Detailed configuration * * {{{ * public $hasOne = array( * 'Profile', * 'Address' => array( * 'className' => 'Address', * 'foreignKey' => 'user_id' * ) * ); * }}} * * ### Possible keys in association * * - `className`: the classname of the model being associated to the current model. * If you’re defining a ‘User hasOne Profile’ relationship, the className key should equal ‘Profile.’ * - `foreignKey`: the name of the foreign key found in the other model. This is * especially handy if you need to define multiple hasOne relationships. * The default value for this key is the underscored, singular name of the * current model, suffixed with ‘_id’. In the example above it would default to 'user_id'. * - `conditions`: An SQL fragment used to filter related model records. It’s good * practice to use model names in SQL fragments: “Profile.approved = 1” is * always better than just “approved = 1.” * - `fields`: A list of fields to be retrieved when the associated model data is * fetched. Returns all fields by default. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows. * - `dependent`: When the dependent key is set to true, and the model’s delete() * method is called with the cascade parameter set to true, associated model * records are also deleted. In this case we set it true so that deleting a * User will also delete her associated Profile. * * @var array * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone */ public $hasOne = array(); /** * Detailed list of hasMany associations. * * ### Basic usage * * `public $hasMany = array('Comment', 'Task');` * * ### Detailed configuration * * {{{ * public $hasMany = array( * 'Comment', * 'Task' => array( * 'className' => 'Task', * 'foreignKey' => 'user_id' * ) * ); * }}} * * ### Possible keys in association * * - `className`: the classname of the model being associated to the current model. * If you’re defining a ‘User hasMany Comment’ relationship, the className key should equal ‘Comment.’ * - `foreignKey`: the name of the foreign key found in the other model. This is * especially handy if you need to define multiple hasMany relationships. The default * value for this key is the underscored, singular name of the actual model, suffixed with ‘_id’. * - `conditions`: An SQL fragment used to filter related model records. It’s good * practice to use model names in SQL fragments: “Comment.status = 1” is always * better than just “status = 1.” * - `fields`: A list of fields to be retrieved when the associated model data is * fetched. Returns all fields by default. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows. * - `limit`: The maximum number of associated rows you want returned. * - `offset`: The number of associated rows to skip over (given the current * conditions and order) before fetching and associating. * - `dependent`: When dependent is set to true, recursive model deletion is * possible. In this example, Comment records will be deleted when their * associated User record has been deleted. * - `exclusive`: When exclusive is set to true, recursive model deletion does * the delete with a deleteAll() call, instead of deleting each entity separately. * This greatly improves performance, but may not be ideal for all circumstances. * - `finderQuery`: A complete SQL query CakePHP can use to fetch associated model * records. This should be used in situations that require very custom results. * * @var array * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany */ public $hasMany = array(); /** * Detailed list of hasAndBelongsToMany associations. * * ### Basic usage * * `public $hasAndBelongsToMany = array('Role', 'Address');` * * ### Detailed configuration * * {{{ * public $hasAndBelongsToMany = array( * 'Role', * 'Address' => array( * 'className' => 'Address', * 'foreignKey' => 'user_id', * 'associationForeignKey' => 'address_id', * 'joinTable' => 'addresses_users' * ) * ); * }}} * * ### Possible keys in association * * - `className`: the classname of the model being associated to the current model. * If you're defining a ‘Recipe HABTM Tag' relationship, the className key should equal ‘Tag.' * - `joinTable`: The name of the join table used in this association (if the * current table doesn't adhere to the naming convention for HABTM join tables). * - `with`: Defines the name of the model for the join table. By default CakePHP * will auto-create a model for you. Using the example above it would be called * RecipesTag. By using this key you can override this default name. The join * table model can be used just like any "regular" model to access the join table directly. * - `foreignKey`: the name of the foreign key found in the current model. * This is especially handy if you need to define multiple HABTM relationships. * The default value for this key is the underscored, singular name of the * current model, suffixed with ‘_id'. * - `associationForeignKey`: the name of the foreign key found in the other model. * This is especially handy if you need to define multiple HABTM relationships. * The default value for this key is the underscored, singular name of the other * model, suffixed with ‘_id'. * - `unique`: If true (default value) cake will first delete existing relationship * records in the foreign keys table before inserting new ones, when updating a * record. So existing associations need to be passed again when updating. * - `conditions`: An SQL fragment used to filter related model records. It's good * practice to use model names in SQL fragments: "Comment.status = 1" is always * better than just "status = 1." * - `fields`: A list of fields to be retrieved when the associated model data is * fetched. Returns all fields by default. * - `order`: An SQL fragment that defines the sorting order for the returned associated rows. * - `limit`: The maximum number of associated rows you want returned. * - `offset`: The number of associated rows to skip over (given the current * conditions and order) before fetching and associating. * - `finderQuery`, `deleteQuery`, `insertQuery`: A complete SQL query CakePHP * can use to fetch, delete, or create new associated model records. This should * be used in situations that require very custom results. * * @var array * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm */ public $hasAndBelongsToMany = array(); /** * List of behaviors to load when the model object is initialized. Settings can be * passed to behaviors by using the behavior name as index. Eg: * * public $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1')) * * @var array * @link http://book.cakephp.org/2.0/en/models/behaviors.html#using-behaviors */ public $actsAs = null; /** * Holds the Behavior objects currently bound to this model. * * @var BehaviorCollection */ public $Behaviors = null; /** * Whitelist of fields allowed to be saved. * * @var array */ public $whitelist = array(); /** * Whether or not to cache sources for this model. * * @var boolean */ public $cacheSources = true; /** * Type of find query currently executing. * * @var string */ public $findQueryType = null; /** * Number of associations to recurse through during find calls. Fetches only * the first level by default. * * @var integer * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive */ public $recursive = 1; /** * The column name(s) and direction(s) to order find results by default. * * public $order = "Post.created DESC"; * public $order = array("Post.view_count DESC", "Post.rating DESC"); * * @var string * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#order */ public $order = null; /** * Array of virtual fields this model has. Virtual fields are aliased * SQL expressions. Fields added to this property will be read as other fields in a model * but will not be saveable. * * `public $virtualFields = array('two' => '1 + 1');` * * Is a simplistic example of how to set virtualFields * * @var array * @link http://book.cakephp.org/2.0/en/models/model-attributes.html#virtualfields */ public $virtualFields = array(); /** * Default list of association keys. * * @var array */ protected $_associationKeys = array( 'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'), 'hasOne' => array('className', 'foreignKey','conditions', 'fields','order', 'dependent'), 'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'), 'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery') ); /** * Holds provided/generated association key names and other data for all associations. * * @var array */ protected $_associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'); /** * Holds model associations temporarily to allow for dynamic (un)binding. * * @var array */ public $__backAssociation = array(); /** * Back inner association * * @var array */ public $__backInnerAssociation = array(); /** * Back original association * * @var array */ public $__backOriginalAssociation = array(); /** * Back containable association * * @var array */ public $__backContainableAssociation = array(); /** * The ID of the model record that was last inserted. * * @var integer */ protected $_insertID = null; /** * Has the datasource been configured. * * @var boolean * @see Model::getDataSource */ protected $_sourceConfigured = false; /** * List of valid finder method options, supplied as the first parameter to find(). * * @var array */ public $findMethods = array( 'all' => true, 'first' => true, 'count' => true, 'neighbors' => true, 'list' => true, 'threaded' => true ); /** * Constructor. Binds the model's database table to the object. * * If `$id` is an array it can be used to pass several options into the model. * * - id - The id to start the model on. * - table - The table to use for this model. * - ds - The connection name this model is connected to. * - name - The name of the model eg. Post. * - alias - The alias of the model, this is used for registering the instance in the `ClassRegistry`. * eg. `ParentThread` * * ### Overriding Model's __construct method. * * When overriding Model::__construct() be careful to include and pass in all 3 of the * arguments to `parent::__construct($id, $table, $ds);` * * ### Dynamically creating models * * You can dynamically create model instances using the $id array syntax. * * {{{ * $Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2')); * }}} * * Would create a model attached to the posts table on connection2. Dynamic model creation is useful * when you want a model object that contains no associations or attached behaviors. * * @param mixed $id Set this ID for this model on startup, can also be an array of options, see above. * @param string $table Name of database table to use. * @param string $ds DataSource connection name. */ public function __construct($id = false, $table = null, $ds = null) { parent::__construct(); if (is_array($id)) { extract(array_merge( array( 'id' => $this->id, 'table' => $this->useTable, 'ds' => $this->useDbConfig, 'name' => $this->name, 'alias' => $this->alias ), $id )); } if ($this->name === null) { $this->name = (isset($name) ? $name : get_class($this)); } if ($this->alias === null) { $this->alias = (isset($alias) ? $alias : $this->name); } if ($this->primaryKey === null) { $this->primaryKey = 'id'; } ClassRegistry::addObject($this->alias, $this); $this->id = $id; unset($id); if ($table === false) { $this->useTable = false; } elseif ($table) { $this->useTable = $table; } if ($ds !== null) { $this->useDbConfig = $ds; } if (is_subclass_of($this, 'AppModel')) { $merge = array('findMethods'); if ($this->actsAs !== null || $this->actsAs !== false) { $merge[] = 'actsAs'; } $parentClass = get_parent_class($this); if ($parentClass !== 'AppModel') { $this->_mergeVars($merge, $parentClass); } $this->_mergeVars($merge, 'AppModel'); } $this->Behaviors = new BehaviorCollection(); if ($this->useTable !== false) { if ($this->useTable === null) { $this->useTable = Inflector::tableize($this->name); } if ($this->displayField == null) { unset($this->displayField); } $this->table = $this->useTable; $this->tableToModel[$this->table] = $this->alias; } elseif ($this->table === false) { $this->table = Inflector::tableize($this->name); } $this->_createLinks(); $this->Behaviors->init($this->alias, $this->actsAs); } /** * Handles custom method calls, like findBy<field> for DB models, * and custom RPC calls for remote data sources. * * @param string $method Name of method to call. * @param array $params Parameters for the method. * @return mixed Whatever is returned by called method */ public function __call($method, $params) { $result = $this->Behaviors->dispatchMethod($this, $method, $params); if ($result !== array('unhandled')) { return $result; } $return = $this->getDataSource()->query($method, $params, $this); return $return; } /** * Handles the lazy loading of model associations by lookin in the association arrays for the requested variable * * @param string $name variable tested for existance in class * @return boolean true if the variable exists (if is a not loaded model association it will be created), false otherwise */ public function __isset($name) { $className = false; foreach ($this->_associations as $type) { if (isset($name, $this->{$type}[$name])) { $className = empty($this->{$type}[$name]['className']) ? $name : $this->{$type}[$name]['className']; break; } elseif (isset($name, $this->__backAssociation[$type][$name])) { $className = empty($this->__backAssociation[$type][$name]['className']) ? $name : $this->__backAssociation[$type][$name]['className']; break; } else if ($type == 'hasAndBelongsToMany') { foreach ($this->{$type} as $k => $relation) { if (empty($relation['with'])) { continue; } if (is_array($relation['with'])) { if (key($relation['with']) === $name) { $className = $name; } } else { list($plugin, $class) = pluginSplit($relation['with']); if ($class === $name) { $className = $relation['with']; } } if ($className) { $assocKey = $k; $dynamic = !empty($relation['dynamicWith']); break(2); } } } } if (!$className) { return false; } list($plugin, $className) = pluginSplit($className); if (!ClassRegistry::isKeySet($className) && !empty($dynamic)) { $this->{$className} = new AppModel(array( 'name' => $className, 'table' => $this->hasAndBelongsToMany[$assocKey]['joinTable'], 'ds' => $this->useDbConfig )); } else { $this->_constructLinkedModel($name, $className, $plugin); } if (!empty($assocKey)) { $this->hasAndBelongsToMany[$assocKey]['joinTable'] = $this->{$name}->table; if (count($this->{$name}->schema()) <= 2 && $this->{$name}->primaryKey !== false) { $this->{$name}->primaryKey = $this->hasAndBelongsToMany[$assocKey]['foreignKey']; } } return true; } /** * Returns the value of the requested variable if it can be set by __isset() * * @param string $name variable requested for it's value or reference * @return mixed value of requested variable if it is set */ public function __get($name) { if ($name === 'displayField') { return $this->displayField = $this->hasField(array('title', 'name', $this->primaryKey)); } if (isset($this->{$name})) { return $this->{$name}; } } /** * Bind model associations on the fly. * * If `$reset` is false, association will not be reset * to the originals defined in the model * * Example: Add a new hasOne binding to the Profile model not * defined in the model source code: * * `$this->User->bindModel( array('hasOne' => array('Profile')) );` * * Bindings that are not made permanent will be reset by the next Model::find() call on this * model. * * @param array $params Set of bindings (indexed by binding type) * @param boolean $reset Set to false to make the binding permanent * @return boolean Success * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly */ public function bindModel($params, $reset = true) { foreach ($params as $assoc => $model) { if ($reset === true && !isset($this->__backAssociation[$assoc])) { $this->__backAssociation[$assoc] = $this->{$assoc}; } foreach ($model as $key => $value) { $assocName = $key; if (is_numeric($key)) { $assocName = $value; $value = array(); } $modelName = $assocName; $this->{$assoc}[$assocName] = $value; if (property_exists($this, $assocName)) { unset($this->{$assocName}); } if ($reset === false && isset($this->__backAssociation[$assoc])) { $this->__backAssociation[$assoc][$assocName] = $value; } } } $this->_createLinks(); return true; } /** * Turn off associations on the fly. * * If $reset is false, association will not be reset * to the originals defined in the model * * Example: Turn off the associated Model Support request, * to temporarily lighten the User model: * * `$this->User->unbindModel( array('hasMany' => array('Supportrequest')) );` * * unbound models that are not made permanent will reset with the next call to Model::find() * * @param array $params Set of bindings to unbind (indexed by binding type) * @param boolean $reset Set to false to make the unbinding permanent * @return boolean Success * @link http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly */ public function unbindModel($params, $reset = true) { foreach ($params as $assoc => $models) { if ($reset === true && !isset($this->__backAssociation[$assoc])) { $this->__backAssociation[$assoc] = $this->{$assoc}; } foreach ($models as $model) { if ($reset === false && isset($this->__backAssociation[$assoc][$model])) { unset($this->__backAssociation[$assoc][$model]); } unset($this->{$assoc}[$model]); } } return true; } /** * Create a set of associations. * * @return void */ protected function _createLinks() { foreach ($this->_associations as $type) { if (!is_array($this->{$type})) { $this->{$type} = explode(',', $this->{$type}); foreach ($this->{$type} as $i => $className) { $className = trim($className); unset ($this->{$type}[$i]); $this->{$type}[$className] = array(); } } if (!empty($this->{$type})) { foreach ($this->{$type} as $assoc => $value) { $plugin = null; if (is_numeric($assoc)) { unset ($this->{$type}[$assoc]); $assoc = $value; $value = array(); if (strpos($assoc, '.') !== false) { list($plugin, $assoc) = pluginSplit($assoc); $this->{$type}[$assoc] = array('className' => $plugin. '.' . $assoc); } else { $this->{$type}[$assoc] = $value; } } $this->_generateAssociation($type, $assoc); } } } } /** * Protected helper method to create associated models of a given class. * * @param string $assoc Association name * @param string $className Class name * @param string $plugin name of the plugin where $className is located * examples: public $hasMany = array('Assoc' => array('className' => 'ModelName')); * usage: $this->Assoc->modelMethods(); * * public $hasMany = array('ModelName'); * usage: $this->ModelName->modelMethods(); * @return void */ protected function _constructLinkedModel($assoc, $className = null, $plugin = null) { if (empty($className)) { $className = $assoc; } if (!isset($this->{$assoc}) || $this->{$assoc}->name !== $className) { if ($plugin) { $plugin .= '.'; } $model = array('class' => $plugin . $className, 'alias' => $assoc); $this->{$assoc} = ClassRegistry::init($model); if ($plugin) { ClassRegistry::addObject($plugin . $className, $this->{$assoc}); } if ($assoc) { $this->tableToModel[$this->{$assoc}->table] = $assoc; } } } /** * Build an array-based association from string. * * @param string $type 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany' * @param string $assocKey * @return void */ protected function _generateAssociation($type, $assocKey) { $class = $assocKey; $dynamicWith = false; foreach ($this->_associationKeys[$type] as $key) { if (!isset($this->{$type}[$assocKey][$key]) || $this->{$type}[$assocKey][$key] === null) { $data = ''; switch ($key) { case 'fields': $data = ''; break; case 'foreignKey': $data = (($type == 'belongsTo') ? Inflector::underscore($assocKey) : Inflector::singularize($this->table)) . '_id'; break; case 'associationForeignKey': $data = Inflector::singularize($this->{$class}->table) . '_id'; break; case 'with': $data = Inflector::camelize(Inflector::singularize($this->{$type}[$assocKey]['joinTable'])); $dynamicWith = true; break; case 'joinTable': $tables = array($this->table, $this->{$class}->table); sort ($tables); $data = $tables[0] . '_' . $tables[1]; break; case 'className': $data = $class; break; case 'unique': $data = true; break; } $this->{$type}[$assocKey][$key] = $data; } if ($dynamicWith) { $this->{$type}[$assocKey]['dynamicWith'] = true; } } } /** * Sets a custom table for your controller class. Used by your controller to select a database table. * * @param string $tableName Name of the custom table * @throws MissingTableException when database table $tableName is not found on data source * @return void */ public function setSource($tableName) { $this->setDataSource($this->useDbConfig); $db = ConnectionManager::getDataSource($this->useDbConfig); $db->cacheSources = ($this->cacheSources && $db->cacheSources); if (method_exists($db, 'listSources')) { $sources = $db->listSources(); if (is_array($sources) && !in_array(strtolower($this->tablePrefix . $tableName), array_map('strtolower', $sources))) { throw new MissingTableException(array( 'table' => $this->tablePrefix . $tableName, 'class' => $this->alias )); } $this->_schema = null; } $this->table = $this->useTable = $tableName; $this->tableToModel[$this->table] = $this->alias; } /** * This function does two things: * * 1. it scans the array $one for the primary key, * and if that's found, it sets the current id to the value of $one[id]. * For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object. * 2. Returns an array with all of $one's keys and values. * (Alternative indata: two strings, which are mangled to * a one-item, two-dimensional array using $one for a key and $two as its value.) * * @param mixed $one Array or string of data * @param string $two Value string for the alternative indata method * @return array Data with all of $one's keys and values * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html */ public function set($one, $two = null) { if (!$one) { return; } if (is_object($one)) { if ($one instanceof SimpleXMLElement || $one instanceof DOMNode) { $one = $this->_normalizeXmlData(Xml::toArray($one)); } else { $one = Set::reverse($one); } } if (is_array($one)) { $data = $one; if (empty($one[$this->alias])) { if ($this->getAssociated(key($one)) === null) { $data = array($this->alias => $one); } } } else { $data = array($this->alias => array($one => $two)); } foreach ($data as $modelName => $fieldSet) { if (is_array($fieldSet)) { foreach ($fieldSet as $fieldName => $fieldValue) { if (isset($this->validationErrors[$fieldName])) { unset ($this->validationErrors[$fieldName]); } if ($modelName === $this->alias) { if ($fieldName === $this->primaryKey) { $this->id = $fieldValue; } } if (is_array($fieldValue) || is_object($fieldValue)) { $fieldValue = $this->deconstruct($fieldName, $fieldValue); } $this->data[$modelName][$fieldName] = $fieldValue; } } } return $data; } /** * Normalize Xml::toArray() to use in Model::save() * * @param array $xml XML as array * @return array */ protected function _normalizeXmlData(array $xml) { $return = array(); foreach ($xml as $key => $value) { if (is_array($value)) { $return[Inflector::camelize($key)] = $this->_normalizeXmlData($value); } elseif ($key[0] === '@') { $return[substr($key, 1)] = $value; } else { $return[$key] = $value; } } return $return; } /** * Deconstructs a complex data type (array or object) into a single field value. * * @param string $field The name of the field to be deconstructed * @param mixed $data An array or object to be deconstructed into a field * @return mixed The resulting data that should be assigned to a field */ public function deconstruct($field, $data) { if (!is_array($data)) { return $data; } $copy = $data; $type = $this->getColumnType($field); if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) { $useNewDate = (isset($data['year']) || isset($data['month']) || isset($data['day']) || isset($data['hour']) || isset($data['minute'])); $dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec'); $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec'); $date = array(); if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] != 12 && 'pm' == $data['meridian']) { $data['hour'] = $data['hour'] + 12; } if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) { $data['hour'] = '00'; } if ($type == 'time') { foreach ($timeFields as $key => $val) { if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') { $data[$val] = '00'; } elseif ($data[$val] === '') { $data[$val] = ''; } else { $data[$val] = sprintf('%02d', $data[$val]); } if (!empty($data[$val])) { $date[$key] = $data[$val]; } else { return null; } } } if ($type == 'datetime' || $type == 'timestamp' || $type == 'date') { foreach ($dateFields as $key => $val) { if ($val == 'hour' || $val == 'min' || $val == 'sec') { if (!isset($data[$val]) || $data[$val] === '0' || $data[$val] === '00') { $data[$val] = '00'; } else { $data[$val] = sprintf('%02d', $data[$val]); } } if (!isset($data[$val]) || isset($data[$val]) && (empty($data[$val]) || $data[$val][0] === '-')) { return null; } if (isset($data[$val]) && !empty($data[$val])) { $date[$key] = $data[$val]; } } } $format = $this->getDataSource()->columns[$type]['format']; $day = empty($date['Y']) ? null : $date['Y'] . '-' . $date['m'] . '-' . $date['d'] . ' '; $hour = empty($date['H']) ? null : $date['H'] . ':' . $date['i'] . ':' . $date['s']; $date = new DateTime($day . $hour); if ($useNewDate && !empty($date)) { return $date->format($format); } } return $data; } /** * Returns an array of table metadata (column names and types) from the database. * $field => keys(type, null, default, key, length, extra) * * @param mixed $field Set to true to reload schema, or a string to return a specific field * @return array Array of table metadata */ public function schema($field = false) { if (!is_array($this->_schema) || $field === true) { $db = $this->getDataSource(); $db->cacheSources = ($this->cacheSources && $db->cacheSources); if (method_exists($db, 'describe') && $this->useTable !== false) { $this->_schema = $db->describe($this); } elseif ($this->useTable === false) { $this->_schema = array(); } } if (is_string($field)) { if (isset($this->_schema[$field])) { return $this->_schema[$field]; } else { return null; } } return $this->_schema; } /** * Returns an associative array of field names and column types. * * @return array Field types indexed by field name */ public function getColumnTypes() { $columns = $this->schema(); if (empty($columns)) { trigger_error(__d('cake_dev', '(Model::getColumnTypes) Unable to build model field data. If you are using a model without a database table, try implementing schema()'), E_USER_WARNING); } $cols = array(); foreach ($columns as $field => $values) { $cols[$field] = $values['type']; } return $cols; } /** * Returns the column type of a column in the model. * * @param string $column The name of the model column * @return string Column type */ public function getColumnType($column) { $db = $this->getDataSource(); $cols = $this->schema(); $model = null; $column = str_replace(array($db->startQuote, $db->endQuote), '', $column); if (strpos($column, '.')) { list($model, $column) = explode('.', $column); } if ($model != $this->alias && isset($this->{$model})) { return $this->{$model}->getColumnType($column); } if (isset($cols[$column]) && isset($cols[$column]['type'])) { return $cols[$column]['type']; } return null; } /** * Returns true if the supplied field exists in the model's database table. * * @param mixed $name Name of field to look for, or an array of names * @param boolean $checkVirtual checks if the field is declared as virtual * @return mixed If $name is a string, returns a boolean indicating whether the field exists. * If $name is an array of field names, returns the first field that exists, * or false if none exist. */ public function hasField($name, $checkVirtual = false) { if (is_array($name)) { foreach ($name as $n) { if ($this->hasField($n, $checkVirtual)) { return $n; } } return false; } if ($checkVirtual && !empty($this->virtualFields)) { if ($this->isVirtualField($name)) { return true; } } if (empty($this->_schema)) { $this->schema(); } if ($this->_schema != null) { return isset($this->_schema[$name]); } return false; } /** * Check that a method is callable on a model. This will check both the model's own methods, its * inherited methods and methods that could be callable through behaviors. * * @param string $method The method to be called. * @return boolean True on method being callable. */ public function hasMethod($method) { if (method_exists($this, $method)) { return true; } if ($this->Behaviors->hasMethod($method)) { return true; } return false; } /** * Returns true if the supplied field is a model Virtual Field * * @param string $field Name of field to look for * @return boolean indicating whether the field exists as a model virtual field. */ public function isVirtualField($field) { if (empty($this->virtualFields) || !is_string($field)) { return false; } if (isset($this->virtualFields[$field])) { return true; } if (strpos($field, '.') !== false) { list($model, $field) = explode('.', $field); if ($model == $this->alias && isset($this->virtualFields[$field])) { return true; } } return false; } /** * Returns the expression for a model virtual field * * @param string $field Name of field to look for * @return mixed If $field is string expression bound to virtual field $field * If $field is null, returns an array of all model virtual fields * or false if none $field exist. */ public function getVirtualField($field = null) { if ($field == null) { return empty($this->virtualFields) ? false : $this->virtualFields; } if ($this->isVirtualField($field)) { if (strpos($field, '.') !== false) { list($model, $field) = explode('.', $field); } return $this->virtualFields[$field]; } return false; } /** * Initializes the model for writing a new record, loading the default values * for those fields that are not defined in $data, and clearing previous validation errors. * Especially helpful for saving data in loops. * * @param mixed $data Optional data array to assign to the model after it is created. If null or false, * schema data defaults are not merged. * @param boolean $filterKey If true, overwrites any primary key input with an empty value * @return array The current Model::data; after merging $data and/or defaults from database * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array */ public function create($data = array(), $filterKey = false) { $defaults = array(); $this->id = false; $this->data = array(); $this->validationErrors = array(); if ($data !== null && $data !== false) { foreach ($this->schema() as $field => $properties) { if ($this->primaryKey !== $field && isset($properties['default']) && $properties['default'] !== '') { $defaults[$field] = $properties['default']; } } $this->set($defaults); $this->set($data); } if ($filterKey) { $this->set($this->primaryKey, false); } return $this->data; } /** * Returns a list of fields from the database, and sets the current model * data (Model::$data) with the record found. * * @param mixed $fields String of single fieldname, or an array of fieldnames. * @param mixed $id The ID of the record to read * @return array Array of database fields, or false if not found * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read */ public function read($fields = null, $id = null) { $this->validationErrors = array(); if ($id != null) { $this->id = $id; } $id = $this->id; if (is_array($this->id)) { $id = $this->id[0]; } if ($id !== null && $id !== false) { $this->data = $this->find('first', array( 'conditions' => array($this->alias . '.' . $this->primaryKey => $id), 'fields' => $fields )); return $this->data; } else { return false; } } /** * Returns the contents of a single field given the supplied conditions, in the * supplied order. * * @param string $name Name of field to get * @param array $conditions SQL conditions (defaults to NULL) * @param string $order SQL ORDER BY fragment * @return string field contents, or false if not found * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field */ public function field($name, $conditions = null, $order = null) { if ($conditions === null && $this->id !== false) { $conditions = array($this->alias . '.' . $this->primaryKey => $this->id); } if ($this->recursive >= 1) { $recursive = -1; } else { $recursive = $this->recursive; } $fields = $name; if ($data = $this->find('first', compact('conditions', 'fields', 'order', 'recursive'))) { if (strpos($name, '.') === false) { if (isset($data[$this->alias][$name])) { return $data[$this->alias][$name]; } } else { $name = explode('.', $name); if (isset($data[$name[0]][$name[1]])) { return $data[$name[0]][$name[1]]; } } if (isset($data[0]) && count($data[0]) > 0) { return array_shift($data[0]); } } else { return false; } } /** * Saves the value of a single field to the database, based on the current * model ID. * * @param string $name Name of the table field * @param mixed $value Value of the field * @param array $validate See $options param in Model::save(). Does not respect 'fieldList' key if passed * @return boolean See Model::save() * @see Model::save() * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read */ public function saveField($name, $value, $validate = false) { $id = $this->id; $this->create(false); if (is_array($validate)) { $options = array_merge(array('validate' => false, 'fieldList' => array($name)), $validate); } else { $options = array('validate' => $validate, 'fieldList' => array($name)); } return $this->save(array($this->alias => array($this->primaryKey => $id, $name => $value)), $options); } /** * Saves model data (based on white-list, if supplied) to the database. By * default, validation occurs before save. * * @param array $data Data to save. * @param mixed $validate Either a boolean, or an array. * If a boolean, indicates whether or not to validate before saving. * If an array, allows control of validate, callbacks, and fieldList * @param array $fieldList List of fields to allow to be written * @return mixed On success Model::$data if its not empty or true, false on failure * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html */ public function save($data = null, $validate = true, $fieldList = array()) { $defaults = array('validate' => true, 'fieldList' => array(), 'callbacks' => true); $_whitelist = $this->whitelist; $fields = array(); if (!is_array($validate)) { $options = array_merge($defaults, compact('validate', 'fieldList', 'callbacks')); } else { $options = array_merge($defaults, $validate); } if (!empty($options['fieldList'])) { $this->whitelist = $options['fieldList']; } elseif ($options['fieldList'] === null) { $this->whitelist = array(); } $this->set($data); if (empty($this->data) && !$this->hasField(array('created', 'updated', 'modified'))) { return false; } foreach (array('created', 'updated', 'modified') as $field) { $keyPresentAndEmpty = ( isset($this->data[$this->alias]) && array_key_exists($field, $this->data[$this->alias]) && $this->data[$this->alias][$field] === null ); if ($keyPresentAndEmpty) { unset($this->data[$this->alias][$field]); } } $exists = $this->exists(); $dateFields = array('modified', 'updated'); if (!$exists) { $dateFields[] = 'created'; } if (isset($this->data[$this->alias])) { $fields = array_keys($this->data[$this->alias]); } if ($options['validate'] && !$this->validates($options)) { $this->whitelist = $_whitelist; return false; } $db = $this->getDataSource(); foreach ($dateFields as $updateCol) { if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) { $default = array('formatter' => 'date'); $colType = array_merge($default, $db->columns[$this->getColumnType($updateCol)]); if (!array_key_exists('format', $colType)) { $time = strtotime('now'); } else { $time = $colType['formatter']($colType['format']); } if (!empty($this->whitelist)) { $this->whitelist[] = $updateCol; } $this->set($updateCol, $time); } } if ($options['callbacks'] === true || $options['callbacks'] === 'before') { $result = $this->Behaviors->trigger('beforeSave', array(&$this, $options), array( 'break' => true, 'breakOn' => array(false, null) )); if (!$result || !$this->beforeSave($options)) { $this->whitelist = $_whitelist; return false; } } if (empty($this->data[$this->alias][$this->primaryKey])) { unset($this->data[$this->alias][$this->primaryKey]); } $fields = $values = array(); foreach ($this->data as $n => $v) { if (isset($this->hasAndBelongsToMany[$n])) { if (isset($v[$n])) { $v = $v[$n]; } $joined[$n] = $v; } else { if ($n === $this->alias) { foreach (array('created', 'updated', 'modified') as $field) { if (array_key_exists($field, $v) && empty($v[$field])) { unset($v[$field]); } } foreach ($v as $x => $y) { if ($this->hasField($x) && (empty($this->whitelist) || in_array($x, $this->whitelist))) { list($fields[], $values[]) = array($x, $y); } } } } } $count = count($fields); if (!$exists && $count > 0) { $this->id = false; } $success = true; $created = false; if ($count > 0) { $cache = $this->_prepareUpdateFields(array_combine($fields, $values)); if (!empty($this->id)) { $success = (bool)$db->update($this, $fields, $values); } else { $fInfo = $this->schema($this->primaryKey); $isUUID = ($fInfo['length'] == 36 && ($fInfo['type'] === 'string' || $fInfo['type'] === 'binary') ); if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) { if (array_key_exists($this->primaryKey, $this->data[$this->alias])) { $j = array_search($this->primaryKey, $fields); $values[$j] = String::uuid(); } else { list($fields[], $values[]) = array($this->primaryKey, String::uuid()); } } if (!$db->create($this, $fields, $values)) { $success = $created = false; } else { $created = true; } } if ($success && !empty($this->belongsTo)) { $this->updateCounterCache($cache, $created); } } if (!empty($joined) && $success === true) { $this->_saveMulti($joined, $this->id, $db); } if ($success && $count > 0) { if (!empty($this->data)) { $success = $this->data; if ($created) { $this->data[$this->alias][$this->primaryKey] = $this->id; } } if ($options['callbacks'] === true || $options['callbacks'] === 'after') { $this->Behaviors->trigger('afterSave', array(&$this, $created, $options)); $this->afterSave($created); } if (!empty($this->data)) { $success = Set::merge($success, $this->data); } $this->data = false; $this->_clearCache(); $this->validationErrors = array(); } $this->whitelist = $_whitelist; return $success; } /** * Saves model hasAndBelongsToMany data to the database. * * @param array $joined Data to save * @param mixed $id ID of record in this model * @param DataSource $db * @return void */ protected function _saveMulti($joined, $id, $db) { foreach ($joined as $assoc => $data) { if (isset($this->hasAndBelongsToMany[$assoc])) { list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']); $keyInfo = $this->{$join}->schema($this->{$join}->primaryKey); $isUUID = !empty($this->{$join}->primaryKey) && ( $keyInfo['length'] == 36 && ( $keyInfo['type'] === 'string' || $keyInfo['type'] === 'binary' ) ); $newData = $newValues = array(); $primaryAdded = false; $fields = array( $db->name($this->hasAndBelongsToMany[$assoc]['foreignKey']), $db->name($this->hasAndBelongsToMany[$assoc]['associationForeignKey']) ); $idField = $db->name($this->{$join}->primaryKey); if ($isUUID && !in_array($idField, $fields)) { $fields[] = $idField; $primaryAdded = true; } foreach ((array)$data as $row) { if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) { $values = array($id, $row); if ($isUUID && $primaryAdded) { $values[] = String::uuid(); } $newValues[] = $values; unset($values); } elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) { $newData[] = $row; } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) { $newData[] = $row[$join]; } } if ($this->hasAndBelongsToMany[$assoc]['unique']) { $conditions = array( $join . '.' . $this->hasAndBelongsToMany[$assoc]['foreignKey'] => $id ); if (!empty($this->hasAndBelongsToMany[$assoc]['conditions'])) { $conditions = array_merge($conditions, (array)$this->hasAndBelongsToMany[$assoc]['conditions']); } $links = $this->{$join}->find('all', array( 'conditions' => $conditions, 'recursive' => empty($this->hasAndBelongsToMany[$assoc]['conditions']) ? -1 : 0, 'fields' => $this->hasAndBelongsToMany[$assoc]['associationForeignKey'] )); $associationForeignKey = "{$join}." . $this->hasAndBelongsToMany[$assoc]['associationForeignKey']; $oldLinks = Set::extract($links, "{n}.{$associationForeignKey}"); if (!empty($oldLinks)) { $conditions[$associationForeignKey] = $oldLinks; $db->delete($this->{$join}, $conditions); } } if (!empty($newData)) { foreach ($newData as $data) { $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $id; $this->{$join}->create($data); $this->{$join}->save(); } } if (!empty($newValues)) { $db->insertMulti($this->{$join}, $fields, $newValues); } } } } /** * Updates the counter cache of belongsTo associations after a save or delete operation * * @param array $keys Optional foreign key data, defaults to the information $this->data * @param boolean $created True if a new record was created, otherwise only associations with * 'counterScope' defined get updated * @return void */ public function updateCounterCache($keys = array(), $created = false) { $keys = empty($keys) ? $this->data[$this->alias] : $keys; $keys['old'] = isset($keys['old']) ? $keys['old'] : array(); foreach ($this->belongsTo as $parent => $assoc) { if (!empty($assoc['counterCache'])) { if (!is_array($assoc['counterCache'])) { if (isset($assoc['counterScope'])) { $assoc['counterCache'] = array($assoc['counterCache'] => $assoc['counterScope']); } else { $assoc['counterCache'] = array($assoc['counterCache'] => array()); } } $foreignKey = $assoc['foreignKey']; $fkQuoted = $this->escapeField($assoc['foreignKey']); foreach ($assoc['counterCache'] as $field => $conditions) { if (!is_string($field)) { $field = Inflector::underscore($this->alias) . '_count'; } if (!$this->{$parent}->hasField($field)) { continue; } if ($conditions === true) { $conditions = array(); } else { $conditions = (array)$conditions; } if (!array_key_exists($foreignKey, $keys)) { $keys[$foreignKey] = $this->field($foreignKey); } $recursive = (empty($conditions) ? -1 : 0); if (isset($keys['old'][$foreignKey])) { if ($keys['old'][$foreignKey] != $keys[$foreignKey]) { $conditions[$fkQuoted] = $keys['old'][$foreignKey]; $count = intval($this->find('count', compact('conditions', 'recursive'))); $this->{$parent}->updateAll( array($field => $count), array($this->{$parent}->escapeField() => $keys['old'][$foreignKey]) ); } } $conditions[$fkQuoted] = $keys[$foreignKey]; if ($recursive === 0) { $conditions = array_merge($conditions, (array)$conditions); } $count = intval($this->find('count', compact('conditions', 'recursive'))); $this->{$parent}->updateAll( array($field => $count), array($this->{$parent}->escapeField() => $keys[$foreignKey]) ); } } } } /** * Helper method for Model::updateCounterCache(). Checks the fields to be updated for * * @param array $data The fields of the record that will be updated * @return array Returns updated foreign key values, along with an 'old' key containing the old * values, or empty if no foreign keys are updated. */ protected function _prepareUpdateFields($data) { $foreignKeys = array(); foreach ($this->belongsTo as $assoc => $info) { if ($info['counterCache']) { $foreignKeys[$assoc] = $info['foreignKey']; } } $included = array_intersect($foreignKeys, array_keys($data)); if (empty($included) || empty($this->id)) { return array(); } $old = $this->find('first', array( 'conditions' => array($this->primaryKey => $this->id), 'fields' => array_values($included), 'recursive' => -1 )); return array_merge($data, array('old' => $old[$this->alias])); } /** * Backwards compatible passtrough method for: * saveMany(), validateMany(), saveAssociated() and validateAssociated() * * Saves multiple individual records for a single model; Also works with a single record, as well as * all its associated records. * * #### Options * * - validate: Set to false to disable validation, true to validate each record before saving, * 'first' to validate *all* records before any are saved (default), * or 'only' to only validate the records, but not save them. * - atomic: If true (default), will attempt to save all records in a single transaction. * Should be set to false if database/table does not support transactions. * - fieldList: Equivalent to the $fieldList parameter in Model::save() * * @param array $data Record data to save. This can be either a numerically-indexed array (for saving multiple * records of the same type), or an array indexed by association name. * @param array $options Options to use when saving record data, See $options above. * @return mixed If atomic: True on success, or false on failure. * Otherwise: array similar to the $data array passed, but values are set to true/false * depending on whether each record saved successfully. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array */ public function saveAll($data = null, $options = array()) { $options = array_merge(array('validate' => 'first'), $options); if (Set::numeric(array_keys($data))) { if ($options['validate'] === 'only') { return $this->validateMany($data, $options); } return $this->saveMany($data, $options); } if ($options['validate'] === 'only') { $validatesAssoc = $this->validateAssociated($data, $options); if (isset($this->validationErrors[$this->alias]) && $this->validationErrors[$this->alias] === false) { return false; } return $validatesAssoc; } return $this->saveAssociated($data, $options); } /** * Saves multiple individual records for a single model * * #### Options * * - validate: Set to false to disable validation, true to validate each record before saving, * 'first' to validate *all* records before any are saved (default), * - atomic: If true (default), will attempt to save all records in a single transaction. * Should be set to false if database/table does not support transactions. * - fieldList: Equivalent to the $fieldList parameter in Model::save() * * @param array $data Record data to save. This should be a numerically-indexed array * @param array $options Options to use when saving record data, See $options above. * @return mixed If atomic: True on success, or false on failure. * Otherwise: array similar to the $data array passed, but values are set to true/false * depending on whether each record saved successfully. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array */ public function saveMany($data = null, $options = array()) { if (empty($data)) { $data = $this->data; } $options = array_merge(array('validate' => 'first', 'atomic' => true), $options); $this->validationErrors = $validationErrors = array(); if (empty($data) && $options['validate'] !== false) { $result = $this->save($data, $options); return !empty($result); } if ($options['validate'] === 'first') { $validates = $this->validateMany($data, $options); if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) { return $validates; } } if ($options['atomic']) { $db = $this->getDataSource(); $transactionBegun = $db->begin($this); } $return = array(); foreach ($data as $key => $record) { $validates = ($this->create(null) !== null && $this->save($record, $options)); if (!$validates) { $validationErrors[$key] = $this->validationErrors; } if (!$options['atomic']) { $return[] = $validates; } elseif (!$validates) { break; } } $this->validationErrors = $validationErrors; if (!$options['atomic']) { return $return; } if ($validates) { if ($transactionBegun) { return $db->commit($this) !== false; } else { return true; } } $db->rollback($this); return false; } /** * Validates multiple individual records for a single model * * #### Options * * - atomic: If true (default), returns boolean. If false returns array. * - fieldList: Equivalent to the $fieldList parameter in Model::save() * * @param array $data Record data to validate. This should be a numerically-indexed array * @param array $options Options to use when validating record data (see above), See also $options of validates(). * @return boolean True on success, or false on failure. * @return mixed If atomic: True on success, or false on failure. * Otherwise: array similar to the $data array passed, but values are set to true/false * depending on whether each record validated successfully. */ public function validateMany($data, $options = array()) { $options = array_merge(array('atomic' => true), $options); $this->validationErrors = $validationErrors = $return = array(); foreach ($data as $key => $record) { $validates = $this->create($record) && $this->validates($options); if (!$validates) { $validationErrors[$key] = $this->validationErrors; } $return[] = $validates; } $this->validationErrors = $validationErrors; if (!$options['atomic']) { return $return; } if (empty($this->validationErrors)) { return true; } return false; } /** * Saves a single record, as well as all its directly associated records. * * #### Options * * - validate: Set to false to disable validation, true to validate each record before saving, * 'first' to validate *all* records before any are saved (default), * - atomic: If true (default), will attempt to save all records in a single transaction. * Should be set to false if database/table does not support transactions. * - fieldList: Equivalent to the $fieldList parameter in Model::save() * * @param array $data Record data to save. This should be an array indexed by association name. * @param array $options Options to use when saving record data, See $options above. * @return mixed If atomic: True on success, or false on failure. * Otherwise: array similar to the $data array passed, but values are set to true/false * depending on whether each record saved successfully. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array */ public function saveAssociated($data = null, $options = array()) { if (empty($data)) { $data = $this->data; } $options = array_merge(array('validate' => true, 'atomic' => true), $options); $this->validationErrors = $validationErrors = array(); if (empty($data) && $options['validate'] !== false) { $result = $this->save($data, $options); return !empty($result); } if ($options['validate'] === 'first') { $validates = $this->validateAssociated($data, $options); if ((!$validates && $options['atomic']) || (!$options['atomic'] && in_array(false, $validates, true))) { return $validates; } } if ($options['atomic']) { $db = $this->getDataSource(); $transactionBegun = $db->begin($this); } $associations = $this->getAssociated(); $return = array(); $validates = true; foreach ($data as $association => $values) { if (isset($associations[$association]) && $associations[$association] === 'belongsTo') { if ($this->{$association}->create(null) !== null && $this->{$association}->save($values, $options)) { $data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id; } else { $validationErrors[$association] = $this->{$association}->validationErrors; $validates = false; } $return[$association][] = $validates; } } if ($validates && !($this->create(null) !== null && $this->save($data, $options))) { $validationErrors[$this->alias] = $this->validationErrors; $validates = false; } $return[$this->alias] = $validates; foreach ($data as $association => $values) { if (!$validates) { break; } if (isset($associations[$association])) { $type = $associations[$association]; switch ($type) { case 'hasOne': $values[$this->{$type}[$association]['foreignKey']] = $this->id; if (!($this->{$association}->create(null) !== null && $this->{$association}->save($values, $options))) { $validationErrors[$association] = $this->{$association}->validationErrors; $validates = false; } $return[$association][] = $validates; break; case 'hasMany': foreach ($values as $i => $value) { $values[$i][$this->{$type}[$association]['foreignKey']] = $this->id; } $_return = $this->{$association}->saveMany($values, array_merge($options, array('atomic' => false))); if (in_array(false, $_return, true)) { $validationErrors[$association] = $this->{$association}->validationErrors; $validates = false; } $return[$association] = $_return; break; } } } $this->validationErrors = $validationErrors; if (isset($validationErrors[$this->alias])) { $this->validationErrors = $validationErrors[$this->alias]; } if (!$options['atomic']) { return $return; } if ($validates) { if ($transactionBegun) { return $db->commit($this) !== false; } else { return true; } } $db->rollback($this); return false; } /** * Validates a single record, as well as all its directly associated records. * * #### Options * * - atomic: If true (default), returns boolean. If false returns array. * - fieldList: Equivalent to the $fieldList parameter in Model::save() * * @param array $data Record data to validate. This should be an array indexed by association name. * @param array $options Options to use when validating record data (see above), See also $options of validates(). * @return array|boolean If atomic: True on success, or false on failure. * Otherwise: array similar to the $data array passed, but values are set to true/false * depending on whether each record validated successfully. */ public function validateAssociated($data, $options = array()) { $options = array_merge(array('atomic' => true), $options); $this->validationErrors = $validationErrors = $return = array(); if (!($this->create($data) && $this->validates($options))) { $validationErrors[$this->alias] = $this->validationErrors; $return[$this->alias] = false; } else { $return[$this->alias] = true; } $associations = $this->getAssociated(); $validates = true; foreach ($data as $association => $values) { if (isset($associations[$association])) { if (in_array($associations[$association], array('belongsTo', 'hasOne'))) { $validates = $this->{$association}->create($values) && $this->{$association}->validates($options); $return[$association][] = $validates; } elseif($associations[$association] === 'hasMany') { $validates = $this->{$association}->validateMany($values, $options); $return[$association] = $validates; } if (!$validates || (is_array($validates) && in_array(false, $validates, true))) { $validationErrors[$association] = $this->{$association}->validationErrors; } } } $this->validationErrors = $validationErrors; if (isset($validationErrors[$this->alias])) { $this->validationErrors = $validationErrors[$this->alias]; } if (!$options['atomic']) { return $return; } if ($return[$this->alias] === false || !empty($this->validationErrors)) { return false; } return true; } /** * Updates multiple model records based on a set of conditions. * * @param array $fields Set of fields and values, indexed by fields. * Fields are treated as SQL snippets, to insert literal values manually escape your data. * @param mixed $conditions Conditions to match, true for all records * @return boolean True on success, false on failure * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions */ public function updateAll($fields, $conditions = true) { return $this->getDataSource()->update($this, $fields, null, $conditions); } /** * Removes record for given ID. If no ID is given, the current ID is used. Returns true on success. * * @param mixed $id ID of record to delete * @param boolean $cascade Set to true to delete records that depend on this record * @return boolean True on success * @link http://book.cakephp.org/2.0/en/models/deleting-data.html */ public function delete($id = null, $cascade = true) { if (!empty($id)) { $this->id = $id; } $id = $this->id; if ($this->beforeDelete($cascade)) { $filters = $this->Behaviors->trigger( 'beforeDelete', array(&$this, $cascade), array('break' => true, 'breakOn' => array(false, null)) ); if (!$filters || !$this->exists()) { return false; } $db = $this->getDataSource(); $this->_deleteDependent($id, $cascade); $this->_deleteLinks($id); $this->id = $id; $updateCounterCache = false; if (!empty($this->belongsTo)) { foreach ($this->belongsTo as $parent => $assoc) { if (!empty($assoc['counterCache'])) { $updateCounterCache = true; break; } } $keys = $this->find('first', array( 'fields' => $this->_collectForeignKeys(), 'conditions' => array($this->alias . '.' . $this->primaryKey => $id), 'recursive' => -1, 'callbacks' => false )); } if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) { if ($updateCounterCache) { $this->updateCounterCache($keys[$this->alias]); } $this->Behaviors->trigger('afterDelete', array(&$this)); $this->afterDelete(); $this->_clearCache(); $this->id = false; return true; } } return false; } /** * Cascades model deletes through associated hasMany and hasOne child records. * * @param string $id ID of record that was deleted * @param boolean $cascade Set to true to delete records that depend on this record * @return void */ protected function _deleteDependent($id, $cascade) { if (!empty($this->__backAssociation)) { $savedAssociatons = $this->__backAssociation; $this->__backAssociation = array(); } foreach (array_merge($this->hasMany, $this->hasOne) as $assoc => $data) { if ($data['dependent'] === true && $cascade === true) { $model = $this->{$assoc}; $conditions = array($model->escapeField($data['foreignKey']) => $id); if ($data['conditions']) { $conditions = array_merge((array)$data['conditions'], $conditions); } $model->recursive = -1; if (isset($data['exclusive']) && $data['exclusive']) { $model->deleteAll($conditions); } else { $records = $model->find('all', array( 'conditions' => $conditions, 'fields' => $model->primaryKey )); if (!empty($records)) { foreach ($records as $record) { $model->delete($record[$model->alias][$model->primaryKey]); } } } } } if (isset($savedAssociatons)) { $this->__backAssociation = $savedAssociatons; } } /** * Cascades model deletes through HABTM join keys. * * @param string $id ID of record that was deleted * @return void */ protected function _deleteLinks($id) { foreach ($this->hasAndBelongsToMany as $assoc => $data) { list($plugin, $joinModel) = pluginSplit($data['with']); $records = $this->{$joinModel}->find('all', array( 'conditions' => array($this->{$joinModel}->escapeField($data['foreignKey']) => $id), 'fields' => $this->{$joinModel}->primaryKey, 'recursive' => -1, 'callbacks' => false )); if (!empty($records)) { foreach ($records as $record) { $this->{$joinModel}->delete($record[$this->{$joinModel}->alias][$this->{$joinModel}->primaryKey]); } } } } /** * Deletes multiple model records based on a set of conditions. * * @param mixed $conditions Conditions to match * @param boolean $cascade Set to true to delete records that depend on this record * @param boolean $callbacks Run callbacks * @return boolean True on success, false on failure * @link http://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall */ public function deleteAll($conditions, $cascade = true, $callbacks = false) { if (empty($conditions)) { return false; } $db = $this->getDataSource(); if (!$cascade && !$callbacks) { return $db->delete($this, $conditions); } else { $ids = $this->find('all', array_merge(array( 'fields' => "{$this->alias}.{$this->primaryKey}", 'recursive' => 0), compact('conditions')) ); if ($ids === false) { return false; } $ids = Set::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}"); if (empty($ids)) { return true; } if ($callbacks) { $_id = $this->id; $result = true; foreach ($ids as $id) { $result = ($result && $this->delete($id, $cascade)); } $this->id = $_id; return $result; } else { foreach ($ids as $id) { $this->_deleteLinks($id); if ($cascade) { $this->_deleteDependent($id, $cascade); } } return $db->delete($this, array($this->alias . '.' . $this->primaryKey => $ids)); } } } /** * Collects foreign keys from associations. * * @param string $type * @return array */ protected function _collectForeignKeys($type = 'belongsTo') { $result = array(); foreach ($this->{$type} as $assoc => $data) { if (isset($data['foreignKey']) && is_string($data['foreignKey'])) { $result[$assoc] = $data['foreignKey']; } } return $result; } /** * Returns true if a record with the currently set ID exists. * * Internally calls Model::getID() to obtain the current record ID to verify, * and then performs a Model::find('count') on the currently configured datasource * to ascertain the existence of the record in persistent storage. * * @return boolean True if such a record exists */ public function exists() { if ($this->getID() === false) { return false; } $conditions = array($this->alias . '.' . $this->primaryKey => $this->getID()); $query = array('conditions' => $conditions, 'recursive' => -1, 'callbacks' => false); return ($this->find('count', $query) > 0); } /** * Returns true if a record that meets given conditions exists. * * @param array $conditions SQL conditions array * @return boolean True if such a record exists */ public function hasAny($conditions = null) { return ($this->find('count', array('conditions' => $conditions, 'recursive' => -1)) != false); } /** * Queries the datasource and returns a result set array. * * Also used to perform notation finds, where the first argument is type of find operation to perform * (all / first / count / neighbors / list / threaded ), * second parameter options for finding ( indexed array, including: 'conditions', 'limit', * 'recursive', 'page', 'fields', 'offset', 'order') * * Eg: * {{{ * find('all', array( * 'conditions' => array('name' => 'Thomas Anderson'), * 'fields' => array('name', 'email'), * 'order' => 'field3 DESC', * 'recursive' => 2, * 'group' => 'type' * )); * }}} * * In addition to the standard query keys above, you can provide Datasource, and behavior specific * keys. For example, when using a SQL based datasource you can use the joins key to specify additional * joins that should be part of the query. * * {{{ * find('all', array( * 'conditions' => array('name' => 'Thomas Anderson'), * 'joins' => array( * array( * 'alias' => 'Thought', * 'table' => 'thoughts', * 'type' => 'LEFT', * 'conditions' => '`Thought`.`person_id` = `Person`.`id`' * ) * ) * )); * }}} * * Behaviors and find types can also define custom finder keys which are passed into find(). * * Specifying 'fields' for notation 'list': * * - If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value. * - If a single field is specified, 'id' is used for key and specified field is used for value. * - If three fields are specified, they are used (in order) for key, value and group. * - Otherwise, first and second fields are used for key and value. * * Note: find(list) + database views have issues with MySQL 5.0. Try upgrading to MySQL 5.1 if you * have issues with database views. * @param string $type Type of find operation (all / first / count / neighbors / list / threaded) * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks) * @return array Array of records * @link http://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall */ public function find($type = 'first', $query = array()) { $this->findQueryType = $type; $this->id = $this->getID(); $query = $this->buildQuery($type, $query); if (is_null($query)) { return null; } $results = $this->getDataSource()->read($this, $query); $this->resetAssociations(); if ($query['callbacks'] === true || $query['callbacks'] === 'after') { $results = $this->_filterResults($results); } $this->findQueryType = null; if ($type === 'all') { return $results; } else { if ($this->findMethods[$type] === true) { return $this->{'_find' . ucfirst($type)}('after', $query, $results); } } } /** * Builds the query array that is used by the data source to generate the query to fetch the data. * * @param string $type Type of find operation (all / first / count / neighbors / list / threaded) * @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks) * @return array Query array or null if it could not be build for some reasons * @see Model::find() */ public function buildQuery($type = 'first', $query = array()) { $query = array_merge( array( 'conditions' => null, 'fields' => null, 'joins' => array(), 'limit' => null, 'offset' => null, 'order' => null, 'page' => 1, 'group' => null, 'callbacks' => true, ), (array)$query ); if ($type !== 'all') { if ($this->findMethods[$type] === true) { $query = $this->{'_find' . ucfirst($type)}('before', $query); } } if (!is_numeric($query['page']) || intval($query['page']) < 1) { $query['page'] = 1; } if ($query['page'] > 1 && !empty($query['limit'])) { $query['offset'] = ($query['page'] - 1) * $query['limit']; } if ($query['order'] === null && $this->order !== null) { $query['order'] = $this->order; } $query['order'] = array($query['order']); if ($query['callbacks'] === true || $query['callbacks'] === 'before') { $return = $this->Behaviors->trigger( 'beforeFind', array(&$this, $query), array('break' => true, 'breakOn' => array(false, null), 'modParams' => 1) ); $query = (is_array($return)) ? $return : $query; if ($return === false) { return null; } $return = $this->beforeFind($query); $query = (is_array($return)) ? $return : $query; if ($return === false) { return null; } } return $query; } /** * Handles the before/after filter logic for find('first') operations. Only called by Model::find(). * * @param string $state Either "before" or "after" * @param array $query * @param array $results * @return array * @see Model::find() */ protected function _findFirst($state, $query, $results = array()) { if ($state === 'before') { $query['limit'] = 1; return $query; } elseif ($state === 'after') { if (empty($results[0])) { return false; } return $results[0]; } } /** * Handles the before/after filter logic for find('count') operations. Only called by Model::find(). * * @param string $state Either "before" or "after" * @param array $query * @param array $results * @return integer The number of records found, or false * @see Model::find() */ protected function _findCount($state, $query, $results = array()) { if ($state === 'before') { $db = $this->getDataSource(); if (empty($query['fields'])) { $query['fields'] = $db->calculate($this, 'count'); } elseif (is_string($query['fields']) && !preg_match('/count/i', $query['fields'])) { $query['fields'] = $db->calculate($this, 'count', array( $db->expression($query['fields']), 'count' )); } $query['order'] = false; return $query; } elseif ($state === 'after') { foreach (array(0, $this->alias) as $key) { if (isset($results[0][$key]['count'])) { if (($count = count($results)) > 1) { return $count; } else { return intval($results[0][$key]['count']); } } } return false; } } /** * Handles the before/after filter logic for find('list') operations. Only called by Model::find(). * * @param string $state Either "before" or "after" * @param array $query * @param array $results * @return array Key/value pairs of primary keys/display field values of all records found * @see Model::find() */ protected function _findList($state, $query, $results = array()) { if ($state === 'before') { if (empty($query['fields'])) { $query['fields'] = array("{$this->alias}.{$this->primaryKey}", "{$this->alias}.{$this->displayField}"); $list = array("{n}.{$this->alias}.{$this->primaryKey}", "{n}.{$this->alias}.{$this->displayField}", null); } else { if (!is_array($query['fields'])) { $query['fields'] = String::tokenize($query['fields']); } if (count($query['fields']) === 1) { if (strpos($query['fields'][0], '.') === false) { $query['fields'][0] = $this->alias . '.' . $query['fields'][0]; } $list = array("{n}.{$this->alias}.{$this->primaryKey}", '{n}.' . $query['fields'][0], null); $query['fields'] = array("{$this->alias}.{$this->primaryKey}", $query['fields'][0]); } elseif (count($query['fields']) === 3) { for ($i = 0; $i < 3; $i++) { if (strpos($query['fields'][$i], '.') === false) { $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i]; } } $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], '{n}.' . $query['fields'][2]); } else { for ($i = 0; $i < 2; $i++) { if (strpos($query['fields'][$i], '.') === false) { $query['fields'][$i] = $this->alias . '.' . $query['fields'][$i]; } } $list = array('{n}.' . $query['fields'][0], '{n}.' . $query['fields'][1], null); } } if (!isset($query['recursive']) || $query['recursive'] === null) { $query['recursive'] = -1; } list($query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath']) = $list; return $query; } elseif ($state === 'after') { if (empty($results)) { return array(); } $lst = $query['list']; return Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']); } } /** * Detects the previous field's value, then uses logic to find the 'wrapping' * rows and return them. * * @param string $state Either "before" or "after" * @param mixed $query * @param array $results * @return array */ protected function _findNeighbors($state, $query, $results = array()) { if ($state === 'before') { extract($query); $conditions = (array)$conditions; if (isset($field) && isset($value)) { if (strpos($field, '.') === false) { $field = $this->alias . '.' . $field; } } else { $field = $this->alias . '.' . $this->primaryKey; $value = $this->id; } $query['conditions'] = array_merge($conditions, array($field . ' <' => $value)); $query['order'] = $field . ' DESC'; $query['limit'] = 1; $query['field'] = $field; $query['value'] = $value; return $query; } elseif ($state === 'after') { extract($query); unset($query['conditions'][$field . ' <']); $return = array(); if (isset($results[0])) { $prevVal = Set::extract('/' . str_replace('.', '/', $field), $results[0]); $query['conditions'][$field . ' >='] = $prevVal[0]; $query['conditions'][$field . ' !='] = $value; $query['limit'] = 2; } else { $return['prev'] = null; $query['conditions'][$field . ' >'] = $value; $query['limit'] = 1; } $query['order'] = $field . ' ASC'; $return2 = $this->find('all', $query); if (!array_key_exists('prev', $return)) { $return['prev'] = $return2[0]; } if (count($return2) === 2) { $return['next'] = $return2[1]; } elseif (count($return2) === 1 && !$return['prev']) { $return['next'] = $return2[0]; } else { $return['next'] = null; } return $return; } } /** * In the event of ambiguous results returned (multiple top level results, with different parent_ids) * top level results with different parent_ids to the first result will be dropped * * @param mixed $state * @param mixed $query * @param array $results * @return array Threaded results */ protected function _findThreaded($state, $query, $results = array()) { if ($state === 'before') { return $query; } elseif ($state === 'after') { $return = $idMap = array(); $ids = Set::extract($results, '{n}.' . $this->alias . '.' . $this->primaryKey); foreach ($results as $result) { $result['children'] = array(); $id = $result[$this->alias][$this->primaryKey]; $parentId = $result[$this->alias]['parent_id']; if (isset($idMap[$id]['children'])) { $idMap[$id] = array_merge($result, (array)$idMap[$id]); } else { $idMap[$id] = array_merge($result, array('children' => array())); } if (!$parentId || !in_array($parentId, $ids)) { $return[] =& $idMap[$id]; } else { $idMap[$parentId]['children'][] =& $idMap[$id]; } } if (count($return) > 1) { $ids = array_unique(Set::extract('/' . $this->alias . '/parent_id', $return)); if (count($ids) > 1) { $root = $return[0][$this->alias]['parent_id']; foreach ($return as $key => $value) { if ($value[$this->alias]['parent_id'] != $root) { unset($return[$key]); } } } } return $return; } } /** * Passes query results through model and behavior afterFilter() methods. * * @param array $results Results to filter * @param boolean $primary If this is the primary model results (results from model where the find operation was performed) * @return array Set of filtered results */ protected function _filterResults($results, $primary = true) { $return = $this->Behaviors->trigger( 'afterFind', array(&$this, $results, $primary), array('modParams' => 1) ); if ($return !== true) { $results = $return; } return $this->afterFind($results, $primary); } /** * This resets the association arrays for the model back * to those originally defined in the model. Normally called at the end * of each call to Model::find() * * @return boolean Success */ public function resetAssociations() { if (!empty($this->__backAssociation)) { foreach ($this->_associations as $type) { if (isset($this->__backAssociation[$type])) { $this->{$type} = $this->__backAssociation[$type]; } } $this->__backAssociation = array(); } foreach ($this->_associations as $type) { foreach ($this->{$type} as $key => $name) { if (property_exists($this, $key) && !empty($this->{$key}->__backAssociation)) { $this->{$key}->resetAssociations(); } } } $this->__backAssociation = array(); return true; } /** * Returns false if any fields passed match any (by default, all if $or = false) of their matching values. * * @param array $fields Field/value pairs to search (if no values specified, they are pulled from $this->data) * @param boolean $or If false, all fields specified must match in order for a false return value * @return boolean False if any records matching any fields are found */ public function isUnique($fields, $or = true) { if (!is_array($fields)) { $fields = func_get_args(); if (is_bool($fields[count($fields) - 1])) { $or = $fields[count($fields) - 1]; unset($fields[count($fields) - 1]); } } foreach ($fields as $field => $value) { if (is_numeric($field)) { unset($fields[$field]); $field = $value; if (isset($this->data[$this->alias][$field])) { $value = $this->data[$this->alias][$field]; } else { $value = null; } } if (strpos($field, '.') === false) { unset($fields[$field]); $fields[$this->alias . '.' . $field] = $value; } } if ($or) { $fields = array('or' => $fields); } if (!empty($this->id)) { $fields[$this->alias . '.' . $this->primaryKey . ' !='] = $this->id; } return ($this->find('count', array('conditions' => $fields, 'recursive' => -1)) == 0); } /** * Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method. * * @param string $sql,... SQL statement * @return array Resultset * @link http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query */ public function query($sql) { $params = func_get_args(); $db = $this->getDataSource(); return call_user_func_array(array(&$db, 'query'), $params); } /** * Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations * that use the 'with' key as well. Since _saveMulti is incapable of exiting a save operation. * * Will validate the currently set data. Use Model::set() or Model::create() to set the active data. * * @param string $options An optional array of custom options to be made available in the beforeValidate callback * @return boolean True if there are no errors */ public function validates($options = array()) { $errors = $this->invalidFields($options); if (empty($errors) && $errors !== false) { $errors = $this->_validateWithModels($options); } if (is_array($errors)) { return count($errors) === 0; } return $errors; } /** * Returns an array of fields that have failed validation. On the current model. * * @param string $options An optional array of custom options to be made available in the beforeValidate callback * @return array Array of invalid fields * @see Model::validates() */ public function invalidFields($options = array()) { if ( !$this->Behaviors->trigger( 'beforeValidate', array(&$this, $options), array('break' => true, 'breakOn' => false) ) || $this->beforeValidate($options) === false ) { return false; } if (!isset($this->validate) || empty($this->validate)) { return $this->validationErrors; } $data = $this->data; $methods = array_map('strtolower', get_class_methods($this)); $behaviorMethods = array_keys($this->Behaviors->methods()); if (isset($data[$this->alias])) { $data = $data[$this->alias]; } elseif (!is_array($data)) { $data = array(); } $exists = $this->exists(); $_validate = $this->validate; $whitelist = $this->whitelist; if (!empty($options['fieldList'])) { $whitelist = $options['fieldList']; } if (!empty($whitelist)) { $validate = array(); foreach ((array)$whitelist as $f) { if (!empty($this->validate[$f])) { $validate[$f] = $this->validate[$f]; } } $this->validate = $validate; } $validationDomain = $this->validationDomain; if (empty($validationDomain)) { $validationDomain = 'default'; } foreach ($this->validate as $fieldName => $ruleSet) { if (!is_array($ruleSet) || (is_array($ruleSet) && isset($ruleSet['rule']))) { $ruleSet = array($ruleSet); } $default = array( 'allowEmpty' => null, 'required' => null, 'rule' => 'blank', 'last' => true, 'on' => null ); foreach ($ruleSet as $index => $validator) { if (!is_array($validator)) { $validator = array('rule' => $validator); } $validator = array_merge($default, $validator); if ( empty($validator['on']) || ($validator['on'] == 'create' && !$exists) || ($validator['on'] == 'update' && $exists )) { $valid = true; $requiredFail = ( (!isset($data[$fieldName]) && $validator['required'] === true) || ( isset($data[$fieldName]) && (empty($data[$fieldName]) && !is_numeric($data[$fieldName])) && $validator['allowEmpty'] === false ) ); if (!$requiredFail && array_key_exists($fieldName, $data)) { if (empty($data[$fieldName]) && $data[$fieldName] != '0' && $validator['allowEmpty'] === true) { break; } if (is_array($validator['rule'])) { $rule = $validator['rule'][0]; unset($validator['rule'][0]); $ruleParams = array_merge(array($data[$fieldName]), array_values($validator['rule'])); } else { $rule = $validator['rule']; $ruleParams = array($data[$fieldName]); } if (in_array(strtolower($rule), $methods)) { $ruleParams[] = $validator; $ruleParams[0] = array($fieldName => $ruleParams[0]); $valid = $this->dispatchMethod($rule, $ruleParams); } elseif (in_array($rule, $behaviorMethods) || in_array(strtolower($rule), $behaviorMethods)) { $ruleParams[] = $validator; $ruleParams[0] = array($fieldName => $ruleParams[0]); $valid = $this->Behaviors->dispatchMethod($this, $rule, $ruleParams); } elseif (method_exists('Validation', $rule)) { $valid = call_user_func_array(array('Validation', $rule), $ruleParams); } elseif (!is_array($validator['rule'])) { $valid = preg_match($rule, $data[$fieldName]); } elseif (Configure::read('debug') > 0) { trigger_error(__d('cake_dev', 'Could not find validation handler %s for %s', $rule, $fieldName), E_USER_WARNING); } } if ($requiredFail || !$valid || (is_string($valid) && strlen($valid) > 0)) { if (is_string($valid)) { $message = $valid; } elseif (isset($validator['message'])) { $args = null; if (is_array($validator['message'])) { $message = $validator['message'][0]; $args = array_slice($validator['message'], 1); } else { $message = $validator['message']; } if (is_array($validator['rule']) && $args === null) { $args = array_slice($ruleSet[$index]['rule'], 1); } $message = __d($validationDomain, $message, $args); } elseif (is_string($index)) { if (is_array($validator['rule'])) { $args = array_slice($ruleSet[$index]['rule'], 1); $message = __d($validationDomain, $index, $args); } else { $message = __d($validationDomain, $index); } } elseif (!$requiredFail && is_numeric($index) && count($ruleSet) > 1) { $message = $index + 1; } else { $message = __d('cake_dev', 'This field cannot be left blank'); } $this->invalidate($fieldName, $message); if ($validator['last']) { break; } } } } } $this->validate = $_validate; return $this->validationErrors; } /** * Runs validation for hasAndBelongsToMany associations that have 'with' keys * set. And data in the set() data set. * * @param array $options Array of options to use on Valdation of with models * @return boolean Failure of validation on with models. * @see Model::validates() */ protected function _validateWithModels($options) { $valid = true; foreach ($this->hasAndBelongsToMany as $assoc => $association) { if (empty($association['with']) || !isset($this->data[$assoc])) { continue; } list($join) = $this->joinModel($this->hasAndBelongsToMany[$assoc]['with']); $data = $this->data[$assoc]; $newData = array(); foreach ((array)$data as $row) { if (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) { $newData[] = $row; } elseif (isset($row[$join]) && isset($row[$join][$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) { $newData[] = $row[$join]; } } if (empty($newData)) { continue; } foreach ($newData as $data) { $data[$this->hasAndBelongsToMany[$assoc]['foreignKey']] = $this->id; $this->{$join}->create($data); $valid = ($valid && $this->{$join}->validates($options)); } } return $valid; } /** * Marks a field as invalid, optionally setting the name of validation * rule (in case of multiple validation for field) that was broken. * * @param string $field The name of the field to invalidate * @param mixed $value Name of validation rule that was not failed, or validation message to * be returned. If no validation key is provided, defaults to true. * @return void */ public function invalidate($field, $value = true) { if (!is_array($this->validationErrors)) { $this->validationErrors = array(); } $this->validationErrors[$field] []= $value; } /** * Returns true if given field name is a foreign key in this model. * * @param string $field Returns true if the input string ends in "_id" * @return boolean True if the field is a foreign key listed in the belongsTo array. */ public function isForeignKey($field) { $foreignKeys = array(); if (!empty($this->belongsTo)) { foreach ($this->belongsTo as $assoc => $data) { $foreignKeys[] = $data['foreignKey']; } } return in_array($field, $foreignKeys); } /** * Escapes the field name and prepends the model name. Escaping is done according to the * current database driver's rules. * * @param string $field Field to escape (e.g: id) * @param string $alias Alias for the model (e.g: Post) * @return string The name of the escaped field for this Model (i.e. id becomes `Post`.`id`). */ public function escapeField($field = null, $alias = null) { if (empty($alias)) { $alias = $this->alias; } if (empty($field)) { $field = $this->primaryKey; } $db = $this->getDataSource(); if (strpos($field, $db->name($alias) . '.') === 0) { return $field; } return $db->name($alias . '.' . $field); } /** * Returns the current record's ID * * @param integer $list Index on which the composed ID is located * @return mixed The ID of the current record, false if no ID */ public function getID($list = 0) { if (empty($this->id) || (is_array($this->id) && isset($this->id[0]) && empty($this->id[0]))) { return false; } if (!is_array($this->id)) { return $this->id; } if (empty($this->id)) { return false; } if (isset($this->id[$list]) && !empty($this->id[$list])) { return $this->id[$list]; } elseif (isset($this->id[$list])) { return false; } foreach ($this->id as $id) { return $id; } return false; } /** * Returns the ID of the last record this model inserted. * * @return mixed Last inserted ID */ public function getLastInsertID() { return $this->getInsertID(); } /** * Returns the ID of the last record this model inserted. * * @return mixed Last inserted ID */ public function getInsertID() { return $this->_insertID; } /** * Sets the ID of the last record this model inserted * * @param mixed $id Last inserted ID * @return void */ public function setInsertID($id) { $this->_insertID = $id; } /** * Returns the number of rows returned from the last query. * * @return integer Number of rows */ public function getNumRows() { return $this->getDataSource()->lastNumRows(); } /** * Returns the number of rows affected by the last query. * * @return integer Number of rows */ public function getAffectedRows() { return $this->getDataSource()->lastAffected(); } /** * Sets the DataSource to which this model is bound. * * @param string $dataSource The name of the DataSource, as defined in app/Config/database.php * @return boolean True on success * @throws MissingConnectionException */ public function setDataSource($dataSource = null) { $oldConfig = $this->useDbConfig; if ($dataSource != null) { $this->useDbConfig = $dataSource; } $db = ConnectionManager::getDataSource($this->useDbConfig); if (!empty($oldConfig) && isset($db->config['prefix'])) { $oldDb = ConnectionManager::getDataSource($oldConfig); if (!isset($this->tablePrefix) || (!isset($oldDb->config['prefix']) || $this->tablePrefix == $oldDb->config['prefix'])) { $this->tablePrefix = $db->config['prefix']; } } elseif (isset($db->config['prefix'])) { $this->tablePrefix = $db->config['prefix']; } if (empty($db) || !is_object($db)) { throw new MissingConnectionException(array('class' => $this->name)); } } /** * Gets the DataSource to which this model is bound. * * @return DataSource A DataSource object */ public function getDataSource() { if (!$this->_sourceConfigured && $this->useTable !== false) { $this->_sourceConfigured = true; $this->setSource($this->useTable); } return ConnectionManager::getDataSource($this->useDbConfig); } /** * Get associations * * @return array */ public function associations() { return $this->_associations; } /** * Gets all the models with which this model is associated. * * @param string $type Only result associations of this type * @return array Associations */ public function getAssociated($type = null) { if ($type == null) { $associated = array(); foreach ($this->_associations as $assoc) { if (!empty($this->{$assoc})) { $models = array_keys($this->{$assoc}); foreach ($models as $m) { $associated[$m] = $assoc; } } } return $associated; } elseif (in_array($type, $this->_associations)) { if (empty($this->{$type})) { return array(); } return array_keys($this->{$type}); } else { $assoc = array_merge( $this->hasOne, $this->hasMany, $this->belongsTo, $this->hasAndBelongsToMany ); if (array_key_exists($type, $assoc)) { foreach ($this->_associations as $a) { if (isset($this->{$a}[$type])) { $assoc[$type]['association'] = $a; break; } } return $assoc[$type]; } return null; } } /** * Gets the name and fields to be used by a join model. This allows specifying join fields * in the association definition. * * @param string|array $assoc The model to be joined * @param array $keys Any join keys which must be merged with the keys queried * @return array */ public function joinModel($assoc, $keys = array()) { if (is_string($assoc)) { list(, $assoc) = pluginSplit($assoc); return array($assoc, array_keys($this->{$assoc}->schema())); } elseif (is_array($assoc)) { $with = key($assoc); return array($with, array_unique(array_merge($assoc[$with], $keys))); } trigger_error( __d('cake_dev', 'Invalid join model settings in %s', $model->alias), E_USER_WARNING ); } /** * Called before each find operation. Return false if you want to halt the find * call, otherwise return the (modified) query data. * * @param array $queryData Data used to execute this query, i.e. conditions, order, etc. * @return mixed true if the operation should continue, false if it should abort; or, modified * $queryData to continue with new $queryData * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeFind-1049 */ public function beforeFind($queryData) { return true; } /** * Called after each find operation. Can be used to modify any results returned by find(). * Return value should be the (modified) results. * * @param mixed $results The results of the find operation * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association) * @return mixed Result of the find operation * @link http://book.cakephp.org/view/1048/Callback-Methods#afterFind-1050 */ public function afterFind($results, $primary = false) { return $results; } /** * Called before each save operation, after validation. Return a non-true result * to halt the save. * * @param array $options * @return boolean True if the operation should continue, false if it should abort * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeSave-1052 */ public function beforeSave($options = array()) { return true; } /** * Called after each successful save operation. * * @param boolean $created True if this save created a new record * @return void * @link http://book.cakephp.org/view/1048/Callback-Methods#afterSave-1053 */ public function afterSave($created) { } /** * Called before every deletion operation. * * @param boolean $cascade If true records that depend on this record will also be deleted * @return boolean True if the operation should continue, false if it should abort * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeDelete-1054 */ public function beforeDelete($cascade = true) { return true; } /** * Called after every deletion operation. * * @return void * @link http://book.cakephp.org/view/1048/Callback-Methods#afterDelete-1055 */ public function afterDelete() { } /** * Called during validation operations, before validation. Please note that custom * validation rules can be defined in $validate. * * @param array $options Options passed from model::save(), see $options of model::save(). * @return boolean True if validate operation should continue, false to abort * @link http://book.cakephp.org/view/1048/Callback-Methods#beforeValidate-1051 */ public function beforeValidate($options = array()) { return true; } /** * Called when a DataSource-level error occurs. * * @return void * @link http://book.cakephp.org/view/1048/Callback-Methods#onError-1056 */ public function onError() { } /** * Clears cache for this model. * * @param string $type If null this deletes cached views if Cache.check is true * Will be used to allow deleting query cache also * @return boolean true on delete * @todo */ protected function _clearCache($type = null) { if ($type === null) { if (Configure::read('Cache.check') === true) { $assoc[] = strtolower(Inflector::pluralize($this->alias)); $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($this->alias))); foreach ($this->_associations as $key => $association) { foreach ($this->$association as $key => $className) { $check = strtolower(Inflector::pluralize($className['className'])); if (!in_array($check, $assoc)) { $assoc[] = strtolower(Inflector::pluralize($className['className'])); $assoc[] = strtolower(Inflector::underscore(Inflector::pluralize($className['className']))); } } } clearCache($assoc); return true; } } else { //Will use for query cache deleting } } }
0001-bee
trunk/cakephp2/lib/Cake/Model/Model.php
PHP
gpl3
108,855
<?php /** * Schema database management for CakePHP. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model * @since CakePHP(tm) v 1.2.0.5550 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Model', 'Model'); App::uses('AppModel', 'Model'); App::uses('ConnectionManager', 'Model'); /** * Base Class for Schema management * * @package Cake.Model */ class CakeSchema extends Object { /** * Name of the schema * * @var string */ public $name = null; /** * Path to write location * * @var string */ public $path = null; /** * File to write * * @var string */ public $file = 'schema.php'; /** * Connection used for read * * @var string */ public $connection = 'default'; /** * plugin name. * * @var string */ public $plugin = null; /** * Set of tables * * @var array */ public $tables = array(); /** * Constructor * * @param array $options optional load object properties */ public function __construct($options = array()) { parent::__construct(); if (empty($options['name'])) { $this->name = preg_replace('/schema$/i', '', get_class($this)); } if (!empty($options['plugin'])) { $this->plugin = $options['plugin']; } if (strtolower($this->name) === 'cake') { $this->name = Inflector::camelize(Inflector::slug(Configure::read('App.dir'))); } if (empty($options['path'])) { $this->path = APP . 'Config' . DS . 'Schema'; } $options = array_merge(get_object_vars($this), $options); $this->build($options); } /** * Builds schema object properties * * @param array $data loaded object properties * @return void */ public function build($data) { $file = null; foreach ($data as $key => $val) { if (!empty($val)) { if (!in_array($key, array('plugin', 'name', 'path', 'file', 'connection', 'tables', '_log'))) { if ($key[0] === '_') { continue; } $this->tables[$key] = $val; unset($this->{$key}); } elseif ($key !== 'tables') { if ($key === 'name' && $val !== $this->name && !isset($data['file'])) { $file = Inflector::underscore($val) . '.php'; } $this->{$key} = $val; } } } if (file_exists($this->path . DS . $file) && is_file($this->path . DS . $file)) { $this->file = $file; } elseif (!empty($this->plugin)) { $this->path = CakePlugin::path($this->plugin) . 'Config' . DS . 'Schema'; } } /** * Before callback to be implemented in subclasses * * @param array $event schema object properties * @return boolean Should process continue */ public function before($event = array()) { return true; } /** * After callback to be implemented in subclasses * * @param array $event schema object properties * @return void */ public function after($event = array()) { } /** * Reads database and creates schema tables * * @param array $options schema object properties * @return array Set of name and tables */ public function load($options = array()) { if (is_string($options)) { $options = array('path' => $options); } $this->build($options); extract(get_object_vars($this)); $class = $name .'Schema'; if (!class_exists($class)) { if (file_exists($path . DS . $file) && is_file($path . DS . $file)) { require_once($path . DS . $file); } elseif (file_exists($path . DS . 'schema.php') && is_file($path . DS . 'schema.php')) { require_once($path . DS . 'schema.php'); } } if (class_exists($class)) { $Schema = new $class($options); return $Schema; } return false; } /** * Reads database and creates schema tables * * Options * * - 'connection' - the db connection to use * - 'name' - name of the schema * - 'models' - a list of models to use, or false to ignore models * * @param array $options schema object properties * @return array Array indexed by name and tables */ public function read($options = array()) { extract(array_merge( array( 'connection' => $this->connection, 'name' => $this->name, 'models' => true, ), $options )); $db = ConnectionManager::getDataSource($connection); if (isset($this->plugin)) { App::uses($this->plugin . 'AppModel', $this->plugin . '.Model'); } $tables = array(); $currentTables = $db->listSources(); $prefix = null; if (isset($db->config['prefix'])) { $prefix = $db->config['prefix']; } if (!is_array($models) && $models !== false) { if (isset($this->plugin)) { $models = App::objects($this->plugin . '.Model', null, false); } else { $models = App::objects('Model'); } } if (is_array($models)) { foreach ($models as $model) { $importModel = $model; $plugin = null; if ($model == 'AppModel') { continue; } if (isset($this->plugin)) { if ($model == $this->plugin . 'AppModel') { continue; } $importModel = $model; $plugin = $this->plugin . '.'; } App::uses($importModel, $plugin . 'Model'); if (!class_exists($importModel)) { continue; } $vars = get_class_vars($model); if (empty($vars['useDbConfig']) || $vars['useDbConfig'] != $connection) { continue; } $Object = ClassRegistry::init(array('class' => $model, 'ds' => $connection)); $db = $Object->getDataSource(); if (is_object($Object) && $Object->useTable !== false) { $fulltable = $table = $db->fullTableName($Object, false); if ($prefix && strpos($table, $prefix) !== 0) { continue; } $table = $this->_noPrefixTable($prefix, $table); if (in_array($fulltable, $currentTables)) { $key = array_search($fulltable, $currentTables); if (empty($tables[$table])) { $tables[$table] = $this->_columns($Object); $tables[$table]['indexes'] = $db->index($Object); $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable); unset($currentTables[$key]); } if (!empty($Object->hasAndBelongsToMany)) { foreach ($Object->hasAndBelongsToMany as $Assoc => $assocData) { if (isset($assocData['with'])) { $class = $assocData['with']; } if (is_object($Object->$class)) { $withTable = $db->fullTableName($Object->$class, false); if ($prefix && strpos($withTable, $prefix) !== 0) { continue; } if (in_array($withTable, $currentTables)) { $key = array_search($withTable, $currentTables); $noPrefixWith = $this->_noPrefixTable($prefix, $withTable); $tables[$noPrefixWith] = $this->_columns($Object->$class); $tables[$noPrefixWith]['indexes'] = $db->index($Object->$class); $tables[$noPrefixWith]['tableParameters'] = $db->readTableParameters($withTable); unset($currentTables[$key]); } } } } } } } } if (!empty($currentTables)) { foreach ($currentTables as $table) { if ($prefix) { if (strpos($table, $prefix) !== 0) { continue; } $table = $this->_noPrefixTable($prefix, $table); } $Object = new AppModel(array( 'name' => Inflector::classify($table), 'table' => $table, 'ds' => $connection )); $systemTables = array( 'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n' ); if (in_array($table, $systemTables)) { $tables[$Object->table] = $this->_columns($Object); $tables[$Object->table]['indexes'] = $db->index($Object); $tables[$Object->table]['tableParameters'] = $db->readTableParameters($table); } elseif ($models === false) { $tables[$table] = $this->_columns($Object); $tables[$table]['indexes'] = $db->index($Object); $tables[$table]['tableParameters'] = $db->readTableParameters($table); } else { $tables['missing'][$table] = $this->_columns($Object); $tables['missing'][$table]['indexes'] = $db->index($Object); $tables['missing'][$table]['tableParameters'] = $db->readTableParameters($table); } } } ksort($tables); return compact('name', 'tables'); } /** * Writes schema file from object or options * * @param mixed $object schema object or options array * @param array $options schema object properties to override object * @return mixed false or string written to file */ public function write($object, $options = array()) { if (is_object($object)) { $object = get_object_vars($object); $this->build($object); } if (is_array($object)) { $options = $object; unset($object); } extract(array_merge( get_object_vars($this), $options )); $out = "class {$name}Schema extends CakeSchema {\n"; if ($path !== $this->path) { $out .= "\tvar \$path = '{$path}';\n\n"; } if ($file !== $this->file) { $out .= "\tvar \$file = '{$file}';\n\n"; } if ($connection !== 'default') { $out .= "\tvar \$connection = '{$connection}';\n\n"; } $out .= "\tfunction before(\$event = array()) {\n\t\treturn true;\n\t}\n\n\tfunction after(\$event = array()) {\n\t}\n\n"; if (empty($tables)) { $this->read(); } foreach ($tables as $table => $fields) { if (!is_numeric($table) && $table !== 'missing') { $out .= $this->generateTable($table, $fields); } } $out .= "}\n"; $file = new SplFileObject($path . DS . $file, 'w+'); $content = "<?php \n/* {$name} schema generated on: " . date('Y-m-d H:i:s') . " : ". time() . "*/\n{$out}?>"; if ($file->fwrite($content)) { return $content; } return false; } /** * Generate the code for a table. Takes a table name and $fields array * Returns a completed variable declaration to be used in schema classes * * @param string $table Table name you want returned. * @param array $fields Array of field information to generate the table with. * @return string Variable declaration for a schema class */ public function generateTable($table, $fields) { $out = "\tvar \${$table} = array(\n"; if (is_array($fields)) { $cols = array(); foreach ($fields as $field => $value) { if ($field != 'indexes' && $field != 'tableParameters') { if (is_string($value)) { $type = $value; $value = array('type'=> $type); } $col = "\t\t'{$field}' => array('type' => '" . $value['type'] . "', "; unset($value['type']); $col .= join(', ', $this->_values($value)); } elseif ($field == 'indexes') { $col = "\t\t'indexes' => array("; $props = array(); foreach ((array)$value as $key => $index) { $props[] = "'{$key}' => array(" . join(', ', $this->_values($index)) . ")"; } $col .= join(', ', $props); } elseif ($field == 'tableParameters') { $col = "\t\t'tableParameters' => array("; $props = array(); foreach ((array)$value as $key => $param) { $props[] = "'{$key}' => '$param'"; } $col .= join(', ', $props); } $col .= ")"; $cols[] = $col; } $out .= join(",\n", $cols); } $out .= "\n\t);\n"; return $out; } /** * Compares two sets of schemas * * @param mixed $old Schema object or array * @param mixed $new Schema object or array * @return array Tables (that are added, dropped, or changed) */ public function compare($old, $new = null) { if (empty($new)) { $new = $this; } if (is_array($new)) { if (isset($new['tables'])) { $new = $new['tables']; } } else { $new = $new->tables; } if (is_array($old)) { if (isset($old['tables'])) { $old = $old['tables']; } } else { $old = $old->tables; } $tables = array(); foreach ($new as $table => $fields) { if ($table == 'missing') { continue; } if (!array_key_exists($table, $old)) { $tables[$table]['add'] = $fields; } else { $diff = $this->_arrayDiffAssoc($fields, $old[$table]); if (!empty($diff)) { $tables[$table]['add'] = $diff; } $diff = $this->_arrayDiffAssoc($old[$table], $fields); if (!empty($diff)) { $tables[$table]['drop'] = $diff; } } foreach ($fields as $field => $value) { if (!empty($old[$table][$field])) { $diff = $this->_arrayDiffAssoc($value, $old[$table][$field]); if (!empty($diff) && $field !== 'indexes' && $field !== 'tableParameters') { $tables[$table]['change'][$field] = array_merge($old[$table][$field], $diff); } } if (isset($tables[$table]['add'][$field]) && $field !== 'indexes' && $field !== 'tableParameters') { $wrapper = array_keys($fields); if ($column = array_search($field, $wrapper)) { if (isset($wrapper[$column - 1])) { $tables[$table]['add'][$field]['after'] = $wrapper[$column - 1]; } } } } if (isset($old[$table]['indexes']) && isset($new[$table]['indexes'])) { $diff = $this->_compareIndexes($new[$table]['indexes'], $old[$table]['indexes']); if ($diff) { if (!isset($tables[$table])) { $tables[$table] = array(); } if (isset($diff['drop'])) { $tables[$table]['drop']['indexes'] = $diff['drop']; } if ($diff && isset($diff['add'])) { $tables[$table]['add']['indexes'] = $diff['add']; } } } if (isset($old[$table]['tableParameters']) && isset($new[$table]['tableParameters'])) { $diff = $this->_compareTableParameters($new[$table]['tableParameters'], $old[$table]['tableParameters']); if ($diff) { $tables[$table]['change']['tableParameters'] = $diff; } } } return $tables; } /** * Extended array_diff_assoc noticing change from/to NULL values * * It behaves almost the same way as array_diff_assoc except for NULL values: if * one of the values is not NULL - change is detected. It is useful in situation * where one value is strval('') ant other is strval(null) - in string comparing * methods this results as EQUAL, while it is not. * * @param array $array1 Base array * @param array $array2 Corresponding array checked for equality * @return array Difference as array with array(keys => values) from input array * where match was not found. */ protected function _arrayDiffAssoc($array1, $array2) { $difference = array(); foreach ($array1 as $key => $value) { if (!array_key_exists($key, $array2)) { $difference[$key] = $value; continue; } $correspondingValue = $array2[$key]; if (is_null($value) !== is_null($correspondingValue)) { $difference[$key] = $value; continue; } if (is_bool($value) !== is_bool($correspondingValue)) { $difference[$key] = $value; continue; } $compare = strval($value); $correspondingValue = strval($correspondingValue); if ($compare === $correspondingValue) { continue; } $difference[$key] = $value; } return $difference; } /** * Formats Schema columns from Model Object * * @param array $values options keys(type, null, default, key, length, extra) * @return array Formatted values */ protected function _values($values) { $vals = array(); if (is_array($values)) { foreach ($values as $key => $val) { if (is_array($val)) { $vals[] = "'{$key}' => array('" . implode("', '", $val) . "')"; } else if (!is_numeric($key)) { $val = var_export($val, true); $vals[] = "'{$key}' => {$val}"; } } } return $vals; } /** * Formats Schema columns from Model Object * * @param array $Obj model object * @return array Formatted columns */ protected function _columns(&$Obj) { $db = $Obj->getDataSource(); $fields = $Obj->schema(true); $columns = $props = array(); foreach ($fields as $name => $value) { if ($Obj->primaryKey == $name) { $value['key'] = 'primary'; } if (!isset($db->columns[$value['type']])) { trigger_error(__d('cake_dev', 'Schema generation error: invalid column type %s does not exist in DBO', $value['type']), E_USER_NOTICE); continue; } else { $defaultCol = $db->columns[$value['type']]; if (isset($defaultCol['limit']) && $defaultCol['limit'] == $value['length']) { unset($value['length']); } elseif (isset($defaultCol['length']) && $defaultCol['length'] == $value['length']) { unset($value['length']); } unset($value['limit']); } if (isset($value['default']) && ($value['default'] === '' || $value['default'] === false)) { unset($value['default']); } if (empty($value['length'])) { unset($value['length']); } if (empty($value['key'])) { unset($value['key']); } $columns[$name] = $value; } return $columns; } /** * Compare two schema files table Parameters * * @param array $new New indexes * @param array $old Old indexes * @return mixed False on failure, or an array of parameters to add & drop. */ protected function _compareTableParameters($new, $old) { if (!is_array($new) || !is_array($old)) { return false; } $change = $this->_arrayDiffAssoc($new, $old); return $change; } /** * Compare two schema indexes * * @param array $new New indexes * @param array $old Old indexes * @return mixed false on failure or array of indexes to add and drop */ protected function _compareIndexes($new, $old) { if (!is_array($new) || !is_array($old)) { return false; } $add = $drop = array(); $diff = $this->_arrayDiffAssoc($new, $old); if (!empty($diff)) { $add = $diff; } $diff = $this->_arrayDiffAssoc($old, $new); if (!empty($diff)) { $drop = $diff; } foreach ($new as $name => $value) { if (isset($old[$name])) { $newUnique = isset($value['unique']) ? $value['unique'] : 0; $oldUnique = isset($old[$name]['unique']) ? $old[$name]['unique'] : 0; $newColumn = $value['column']; $oldColumn = $old[$name]['column']; $diff = false; if ($newUnique != $oldUnique) { $diff = true; } elseif (is_array($newColumn) && is_array($oldColumn)) { $diff = ($newColumn !== $oldColumn); } elseif (is_string($newColumn) && is_string($oldColumn)) { $diff = ($newColumn != $oldColumn); } else { $diff = true; } if ($diff) { $drop[$name] = null; $add[$name] = $value; } } } return array_filter(compact('add', 'drop')); } /** * Trim the table prefix from the full table name, and return the prefix-less table * * @param string $prefix Table prefix * @param string $table Full table name * @return string Prefix-less table name */ protected function _noPrefixTable($prefix, $table) { return preg_replace('/^' . preg_quote($prefix) . '/', '', $table); } }
0001-bee
trunk/cakephp2/lib/Cake/Model/CakeSchema.php
PHP
gpl3
18,815
<?php /** * Model behaviors base class. * * Adds methods and automagic functionality to Cake Models. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model * @since CakePHP(tm) v 1.2.0.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Model behavior base class. * * Defines the Behavior interface, and contains common model interaction functionality. Behaviors * allow you to simulate mixins, and create resuable blocks of application logic, that can be reused across * several models. Behaviors also provide a way to hook into model callbacks and augment their behavior. * * ### Mixin methods * * Behaviors can provide mixin like features by declaring public methods. These methods should expect * the model instance to be shifted onto the parameter list. * * {{{ * function doSomething($model, $arg1, $arg2) { * //do something * } * }}} * * Would be called like `$this->Model->doSomething($arg1, $arg2);`. * * ### Mapped methods * * Behaviors can also define mapped methods. Mapped methods use pattern matching for method invocation. This * allows you to create methods similar to Model::findAllByXXX methods on your behaviors. Mapped methods need to * be declared in your behaviors `$mapMethods` array. The method signature for a mapped method is slightly different * than a normal behavior mixin method. * * {{{ * public $mapMethods = array('/do(\w+)/' => 'doSomething'); * * function doSomething($model, $method, $arg1, $arg2) { * //do something * } * }}} * * The above will map every doXXX() method call to the behavior. As you can see, the model is * still the first parameter, but the called method name will be the 2nd parameter. This allows * you to munge the method name for additional information, much like Model::findAllByXX. * * @package Cake.Model * @see Model::$actsAs * @see BehaviorCollection::load() */ class ModelBehavior extends Object { /** * Contains configuration settings for use with individual model objects. This * is used because if multiple models use this Behavior, each will use the same * object instance. Individual model settings should be stored as an * associative array, keyed off of the model name. * * @var array * @see Model::$alias */ public $settings = array(); /** * Allows the mapping of preg-compatible regular expressions to public or * private methods in this class, where the array key is a /-delimited regular * expression, and the value is a class method. Similar to the functionality of * the findBy* / findAllBy* magic methods. * * @var array */ public $mapMethods = array(); /** * Setup this behavior with the specified configuration settings. * * @param Model $model Model using this behavior * @param array $config Configuration settings for $model * @return void */ public function setup($model, $config = array()) { } /** * Clean up any initialization this behavior has done on a model. Called when a behavior is dynamically * detached from a model using Model::detach(). * * @param Model $model Model using this behavior * @return void * @see BehaviorCollection::detach() */ public function cleanup($model) { if (isset($this->settings[$model->alias])) { unset($this->settings[$model->alias]); } } /** * beforeFind can be used to cancel find operations, or modify the query that will be executed. * By returning null/false you can abort a find. By returning an array you can modify/replace the query * that is going to be run. * * @param Model $model Model using this behavior * @param array $query Data used to execute this query, i.e. conditions, order, etc. * @return boolean|array False or null will abort the operation. You can return an array to replace the * $query that will be eventually run. */ public function beforeFind($model, $query) { return true; } /** * After find callback. Can be used to modify any results returned by find. * * @param Model $model Model using this behavior * @param mixed $results The results of the find operation * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association) * @return mixed An array value will replace the value of $results - any other value will be ignored. */ public function afterFind($model, $results, $primary) { } /** * beforeValidate is called before a model is validated, you can use this callback to * add behavior validation rules into a models validate array. Returning false * will allow you to make the validation fail. * * @param Model $model Model using this behavior * @return mixed False or null will abort the operation. Any other result will continue. */ public function beforeValidate($model) { return true; } /** * beforeSave is called before a model is saved. Returning false from a beforeSave callback * will abort the save operation. * * @param Model $model Model using this behavior * @return mixed False if the operation should abort. Any other result will continue. */ public function beforeSave($model) { return true; } /** * afterSave is called after a model is saved. * * @param Model $model Model using this behavior * @param boolean $created True if this save created a new record * @return boolean */ public function afterSave($model, $created) { return true; } /** * Before delete is called before any delete occurs on the attached model, but after the model's * beforeDelete is called. Returning false from a beforeDelete will abort the delete. * * @param Model $model Model using this behavior * @param boolean $cascade If true records that depend on this record will also be deleted * @return mixed False if the operation should abort. Any other result will continue. */ public function beforeDelete($model, $cascade = true) { return true; } /** * After delete is called after any delete occurs on the attached model. * * @param Model $model Model using this behavior * @return void */ public function afterDelete($model) { } /** * DataSource error callback * * @param Model $model Model using this behavior * @param string $error Error generated in DataSource * @return void */ public function onError($model, $error) { } /** * If $model's whitelist property is non-empty, $field will be added to it. * Note: this method should *only* be used in beforeValidate or beforeSave to ensure * that it only modifies the whitelist for the current save operation. Also make sure * you explicitly set the value of the field which you are allowing. * * @param Model $model Model using this behavior * @param string $field Field to be added to $model's whitelist * @return void */ protected function _addToWhitelist($model, $field) { if (is_array($field)) { foreach ($field as $f) { $this->_addToWhitelist($model, $f); } return; } if (!empty($model->whitelist) && !in_array($field, $model->whitelist)) { $model->whitelist[] = $field; } } }
0001-bee
trunk/cakephp2/lib/Cake/Model/ModelBehavior.php
PHP
gpl3
7,421
<?php /** * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Load Model and AppModel */ App::uses('AppModel', 'Model'); /** * Access Request Object * * @package Cake.Model */ class Aro extends AclNode { /** * Model name * * @var string */ public $name = 'Aro'; /** * AROs are linked to ACOs by means of Permission * * @var array */ public $hasAndBelongsToMany = array('Aco' => array('with' => 'Permission')); }
0001-bee
trunk/cakephp2/lib/Cake/Model/Aro.php
PHP
gpl3
973
<?php /** * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Load Model and AppModel */ App::uses('AppModel', 'Model'); /** * Access Control Object * * @package Cake.Model */ class Aco extends AclNode { /** * Model name * * @var string */ public $name = 'Aco'; /** * Binds to ARO nodes through permissions settings * * @var array */ public $hasAndBelongsToMany = array('Aro' => array('with' => 'Permission')); }
0001-bee
trunk/cakephp2/lib/Cake/Model/Aco.php
PHP
gpl3
973
<?php /** * BehaviorCollection * * Provides managment and interface for interacting with collections of behaviors. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Model * @since CakePHP(tm) v 1.2.0.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('ObjectCollection', 'Utility'); /** * Model behavior collection class. * * Defines the Behavior interface, and contains common model interaction functionality. * * @package Cake.Model */ class BehaviorCollection extends ObjectCollection { /** * Stores a reference to the attached name * * @var string */ public $modelName = null; /** * Keeps a list of all methods of attached behaviors * * @var array */ protected $_methods = array(); /** * Keeps a list of all methods which have been mapped with regular expressions * * @var array */ protected $_mappedMethods = array(); /** * Attaches a model object and loads a list of behaviors * * @todo Make this method a constructor instead.. * @param string $modelName * @param array $behaviors * @return void */ public function init($modelName, $behaviors = array()) { $this->modelName = $modelName; if (!empty($behaviors)) { foreach (BehaviorCollection::normalizeObjectArray($behaviors) as $behavior => $config) { $this->load($config['class'], $config['settings']); } } } /** * Backwards compatible alias for load() * * @param string $behavior * @param array $config * @return void * @deprecated Replaced with load() */ public function attach($behavior, $config = array()) { return $this->load($behavior, $config); } /** * Loads a behavior into the collection. You can use use `$config['enabled'] = false` * to load a behavior with callbacks disabled. By default callbacks are enabled. Disable behaviors * can still be used as normal. * * You can alias your behavior as an existing behavior by setting the 'className' key, i.e., * {{{ * public $actsAs = array( * 'Tree' => array( * 'className' => 'AliasedTree' * ); * ); * }}} * All calls to the `Tree` behavior would use `AliasedTree` instead. * * @param string $behavior CamelCased name of the behavior to load * @param array $config Behavior configuration parameters * @return boolean True on success, false on failure * @throws MissingBehaviorException when a behavior could not be found. */ public function load($behavior, $config = array()) { if (is_array($config) && isset($config['className'])) { $alias = $behavior; $behavior = $config['className']; } list($plugin, $name) = pluginSplit($behavior, true); if (!isset($alias)) { $alias = $name; } $class = $name . 'Behavior'; App::uses($class, $plugin . 'Model/Behavior'); if (!class_exists($class)) { throw new MissingBehaviorException(array( 'class' => $class, 'plugin' => substr($plugin, 0, -1) )); } if (!isset($this->{$alias})) { if (ClassRegistry::isKeySet($class)) { $this->_loaded[$alias] = ClassRegistry::getObject($class); } else { $this->_loaded[$alias] = new $class(); ClassRegistry::addObject($class, $this->_loaded[$alias]); if (!empty($plugin)) { ClassRegistry::addObject($plugin . '.' . $class, $this->_loaded[$alias]); } } } elseif (isset($this->_loaded[$alias]->settings) && isset($this->_loaded[$alias]->settings[$this->modelName])) { if ($config !== null && $config !== false) { $config = array_merge($this->_loaded[$alias]->settings[$this->modelName], $config); } else { $config = array(); } } if (empty($config)) { $config = array(); } $this->_loaded[$alias]->setup(ClassRegistry::getObject($this->modelName), $config); foreach ($this->_loaded[$alias]->mapMethods as $method => $methodAlias) { $this->_mappedMethods[$method] = array($alias, $methodAlias); } $methods = get_class_methods($this->_loaded[$alias]); $parentMethods = array_flip(get_class_methods('ModelBehavior')); $callbacks = array( 'setup', 'cleanup', 'beforeFind', 'afterFind', 'beforeSave', 'afterSave', 'beforeDelete', 'afterDelete', 'onError' ); foreach ($methods as $m) { if (!isset($parentMethods[$m])) { $methodAllowed = ( $m[0] != '_' && !array_key_exists($m, $this->_methods) && !in_array($m, $callbacks) ); if ($methodAllowed) { $this->_methods[$m] = array($alias, $m); } } } $configDisabled = isset($config['enabled']) && $config['enabled'] === false; if (!in_array($alias, $this->_enabled) && !$configDisabled) { $this->enable($alias); } elseif ($configDisabled) { $this->disable($alias); } return true; } /** * Detaches a behavior from a model * * @param string $name CamelCased name of the behavior to unload * @return void */ public function unload($name) { list($plugin, $name) = pluginSplit($name); if (isset($this->_loaded[$name])) { $this->_loaded[$name]->cleanup(ClassRegistry::getObject($this->modelName)); unset($this->_loaded[$name]); } foreach ($this->_methods as $m => $callback) { if (is_array($callback) && $callback[0] == $name) { unset($this->_methods[$m]); } } $this->_enabled = array_values(array_diff($this->_enabled, (array)$name)); } /** * Backwards compatible alias for unload() * * @param string $name Name of behavior * @return void * @deprecated Use unload instead. */ public function detach($name) { return $this->unload($name); } /** * Dispatches a behavior method. Will call either normal methods or mapped methods. * * If a method is not handeled by the BehaviorCollection, and $strict is false, a * special return of `array('unhandled')` will be returned to signal the method was not found. * * @param Model $model The model the method was originally called on. * @param string $method The method called. * @param array $params Parameters for the called method. * @param boolean $strict If methods are not found, trigger an error. * @return array All methods for all behaviors attached to this object */ public function dispatchMethod($model, $method, $params = array(), $strict = false) { $method = $this->hasMethod($method, true); if ($strict && empty($method)) { trigger_error(__d('cake_dev', "BehaviorCollection::dispatchMethod() - Method %s not found in any attached behavior", $method), E_USER_WARNING); return null; } if (empty($method)) { return array('unhandled'); } if (count($method) === 3) { array_unshift($params, $method[2]); unset($method[2]); } return call_user_func_array( array($this->_loaded[$method[0]], $method[1]), array_merge(array(&$model), $params) ); } /** * Gets the method list for attached behaviors, i.e. all public, non-callback methods. * This does not include mappedMethods. * * @return array All public methods for all behaviors attached to this collection */ public function methods() { return $this->_methods; } /** * Check to see if a behavior in this collection implements the provided method. Will * also check mappedMethods. * * @param string $method The method to find. * @param boolean $callback Return the callback for the method. * @return mixed If $callback is false, a boolean will be returnned, if its true, an array * containing callback information will be returnned. For mapped methods the array will have 3 elements. */ public function hasMethod($method, $callback = false) { if (isset($this->_methods[$method])) { return $callback ? $this->_methods[$method] : true; } foreach ($this->_mappedMethods as $pattern => $target) { if (preg_match($pattern . 'i', $method)) { if ($callback) { $target[] = $method; return $target; } return true; } } return false; } }
0001-bee
trunk/cakephp2/lib/Cake/Model/BehaviorCollection.php
PHP
gpl3
8,163
<?php /** * Basic Cake functionality. * * Handles loading of core files needed on every request * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ define('TIME_START', microtime(true)); if (!defined('E_DEPRECATED')) { define('E_DEPRECATED', 8192); } error_reporting(E_ALL & ~E_DEPRECATED); if (!defined('CAKE_CORE_INCLUDE_PATH')) { define('CAKE_CORE_INCLUDE_PATH', dirname(dirname(__FILE__))); } if (!defined('CORE_PATH')) { define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS); } if (!defined('WEBROOT_DIR')) { define('WEBROOT_DIR', 'webroot'); } /** * Path to the cake directory. */ define('CAKE', CORE_PATH . 'Cake' . DS); /** * Path to the application's directory. */ if (!defined('APP')) { define('APP', ROOT.DS.APP_DIR.DS); } /** * Path to the application's libs directory. */ define('APPLIBS', APP.'Lib'.DS); /** * Path to the public CSS directory. */ define('CSS', WWW_ROOT.'css'.DS); /** * Path to the public JavaScript directory. */ define('JS', WWW_ROOT.'js'.DS); /** * Path to the public images directory. */ define('IMAGES', WWW_ROOT.'img'.DS); /** * Path to the tests directory. */ if (!defined('TESTS')) { define('TESTS', APP.'Test'.DS); } /** * Path to the temporary files directory. */ if (!defined('TMP')) { define('TMP', APP.'tmp'.DS); } /** * Path to the logs directory. */ define('LOGS', TMP.'logs'.DS); /** * Path to the cache files directory. It can be shared between hosts in a multi-server setup. */ define('CACHE', TMP.'cache'.DS); /** * Path to the vendors directory. */ if (!defined('VENDORS')) { define('VENDORS', ROOT . DS . 'vendors' . DS); } /** * Web path to the public images directory. */ if (!defined('IMAGES_URL')) { define('IMAGES_URL', 'img/'); } /** * Web path to the CSS files directory. */ if (!defined('CSS_URL')) { define('CSS_URL', 'css/'); } /** * Web path to the js files directory. */ if (!defined('JS_URL')) { define('JS_URL', 'js/'); } require CAKE . 'basics.php'; require CAKE . 'Core' . DS .'App.php'; require CAKE . 'Error' . DS . 'exceptions.php'; spl_autoload_register(array('App', 'load')); App::uses('ErrorHandler', 'Error'); App::uses('Configure', 'Core'); App::uses('Cache', 'Cache'); App::uses('Object', 'Core'); App::$bootstrapping = true; Configure::bootstrap(isset($boot) ? $boot : true); /** * Full url prefix */ if (!defined('FULL_BASE_URL')) { $s = null; if (env('HTTPS')) { $s ='s'; } $httpHost = env('HTTP_HOST'); if (isset($httpHost)) { define('FULL_BASE_URL', 'http'.$s.'://'.$httpHost); } unset($httpHost, $s); }
0001-bee
trunk/cakephp2/lib/Cake/bootstrap.php
PHP
gpl3
3,093
<?php /** * Caching for CakePHP. * * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Cache * @since CakePHP(tm) v 1.2.0.4933 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Inflector', 'Utility'); /** * Cache provides a consistent interface to Caching in your application. It allows you * to use several different Cache engines, without coupling your application to a specific * implementation. It also allows you to change out cache storage or configuration without effecting * the rest of your application. * * You can configure Cache engines in your application's `bootstrap.php` file. A sample configuration would * be * * {{{ * Cache::config('shared', array( * 'engine' => 'Apc', * 'prefix' => 'my_app_' * )); * }}} * * This would configure an APC cache engine to the 'shared' alias. You could then read and write * to that cache alias by using it for the `$config` parameter in the various Cache methods. In * general all Cache operations are supported by all cache engines. However, Cache::increment() and * Cache::decrement() are not supported by File caching. * * @package Cake.Cache */ class Cache { /** * Cache configuration stack * Keeps the permanent/default settings for each cache engine. * These settings are used to reset the engines after temporary modification. * * @var array */ protected static $_config = array(); /** * Whether to reset the settings with the next call to Cache::set(); * * @var array */ protected static $_reset = false; /** * Engine instances keyed by configuration name. * * @var array */ protected static $_engines = array(); /** * Set the cache configuration to use. config() can * both create new configurations, return the settings for already configured * configurations. * * To create a new configuration, or to modify an existing configuration permanently: * * `Cache::config('my_config', array('engine' => 'File', 'path' => TMP));` * * If you need to modify a configuration temporarily, use Cache::set(). * To get the settings for a configuration: * * `Cache::config('default');` * * There are 5 built-in caching engines: * * - `FileEngine` - Uses simple files to store content. Poor performance, but good for * storing large objects, or things that are not IO sensitive. * - `ApcEngine` - Uses the APC object cache, one of the fastest caching engines. * - `MemcacheEngine` - Uses the PECL::Memcache extension and Memcached for storage. * Fast reads/writes, and benefits from memcache being distributed. * - `XcacheEngine` - Uses the Xcache extension, an alternative to APC. * - `WincacheEngine` - Uses Windows Cache Extension for PHP. Supports wincache 1.1.0 and higher. * * The following keys are used in core cache engines: * * - `duration` Specify how long items in this cache configuration last. * - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace * with either another cache config or annother application. * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable * cache::gc from ever being called automatically. * - `servers' Used by memcache. Give the address of the memcached servers to use. * - `compress` Used by memcache. Enables memcache's compressed format. * - `serialize` Used by FileCache. Should cache objects be serialized first. * - `path` Used by FileCache. Path to where cachefiles should be saved. * - `lock` Used by FileCache. Should files be locked before writing to them? * - `user` Used by Xcache. Username for XCache * - `password` Used by Xcache. Password for XCache * * @see app/Config/core.php for configuration settings * @param string $name Name of the configuration * @param array $settings Optional associative array of settings passed to the engine * @return array(engine, settings) on success, false on failure * @throws CacheException */ public static function config($name = null, $settings = array()) { if (is_array($name)) { $settings = $name; } $current = array(); if (isset(self::$_config[$name])) { $current = self::$_config[$name]; } if (!empty($settings)) { self::$_config[$name] = array_merge($current, $settings); } if (empty(self::$_config[$name]['engine'])) { return false; } $engine = self::$_config[$name]['engine']; if (!isset(self::$_engines[$name])) { self::_buildEngine($name); $settings = self::$_config[$name] = self::settings($name); } elseif ($settings = self::set(self::$_config[$name], null, $name)) { self::$_config[$name] = $settings; } return compact('engine', 'settings'); } /** * Finds and builds the instance of the required engine class. * * @param string $name Name of the config array that needs an engine instance built * @return boolean * @throws CacheException */ protected static function _buildEngine($name) { $config = self::$_config[$name]; list($plugin, $class) = pluginSplit($config['engine'], true); $cacheClass = $class . 'Engine'; App::uses($cacheClass, $plugin . 'Cache/Engine'); if (!class_exists($cacheClass)) { return false; } $cacheClass = $class . 'Engine'; if (!is_subclass_of($cacheClass, 'CacheEngine')) { throw new CacheException(__d('cake_dev', 'Cache engines must use CacheEngine as a base class.')); } self::$_engines[$name] = new $cacheClass(); if (self::$_engines[$name]->init($config)) { if (self::$_engines[$name]->settings['probability'] && time() % self::$_engines[$name]->settings['probability'] === 0) { self::$_engines[$name]->gc(); } return true; } return false; } /** * Returns an array containing the currently configured Cache settings. * * @return array Array of configured Cache config names. */ public static function configured() { return array_keys(self::$_config); } /** * Drops a cache engine. Deletes the cache configuration information * If the deleted configuration is the last configuration using an certain engine, * the Engine instance is also unset. * * @param string $name A currently configured cache config you wish to remove. * @return boolean success of the removal, returns false when the config does not exist. */ public static function drop($name) { if (!isset(self::$_config[$name])) { return false; } unset(self::$_config[$name], self::$_engines[$name]); return true; } /** * Temporarily change the settings on a cache config. The settings will persist for the next write * operation (write, decrement, increment, clear). Any reads that are done before the write, will * use the modified settings. If `$settings` is empty, the settings will be reset to the * original configuration. * * Can be called with 2 or 3 parameters. To set multiple values at once. * * `Cache::set(array('duration' => '+30 minutes'), 'my_config');` * * Or to set one value. * * `Cache::set('duration', '+30 minutes', 'my_config');` * * To reset a config back to the originally configured values. * * `Cache::set(null, 'my_config');` * * @param mixed $settings Optional string for simple name-value pair or array * @param string $value Optional for a simple name-value pair * @param string $config The configuration name you are changing. Defaults to 'default' * @return array Array of settings. */ public static function set($settings = array(), $value = null, $config = 'default') { if (is_array($settings) && $value !== null) { $config = $value; } if (!isset(self::$_config[$config]) || !isset(self::$_engines[$config])) { return false; } if (!empty($settings)) { self::$_reset = true; } if (self::$_reset === true) { if (empty($settings)) { self::$_reset = false; $settings = self::$_config[$config]; } else { if (is_string($settings) && $value !== null) { $settings = array($settings => $value); } $settings = array_merge(self::$_config[$config], $settings); if (isset($settings['duration']) && !is_numeric($settings['duration'])) { $settings['duration'] = strtotime($settings['duration']) - time(); } } self::$_engines[$config]->settings = $settings; } return self::settings($config); } /** * Garbage collection * * Permanently remove all expired and deleted data * * @param string $config The config name you wish to have garbage collected. Defaults to 'default' * @return void */ public static function gc($config = 'default') { self::$_engines[$config]->gc(); } /** * Write data for key into cache. Will automatically use the currently * active cache configuration. To set the currently active configuration use * Cache::config() * * ### Usage: * * Writing to the active cache config: * * `Cache::write('cached_data', $data);` * * Writing to a specific cache config: * * `Cache::write('cached_data', $data, 'long_term');` * * @param string $key Identifier for the data * @param mixed $value Data to be cached - anything except a resource * @param string $config Optional string configuration name to write to. Defaults to 'default' * @return boolean True if the data was successfully cached, false on failure */ public static function write($key, $value, $config = 'default') { $settings = self::settings($config); if (empty($settings)) { return null; } if (!self::isInitialized($config)) { return false; } $key = self::$_engines[$config]->key($key); if (!$key || is_resource($value)) { return false; } $success = self::$_engines[$config]->write($settings['prefix'] . $key, $value, $settings['duration']); self::set(null, $config); if ($success === false && $value !== '') { trigger_error( __d('cake_dev', "%s cache was unable to write '%s' to %s cache", $config, $key, self::$_engines[$config]->settings['engine'] ), E_USER_WARNING ); } return $success; } /** * Read a key from the cache. Will automatically use the currently * active cache configuration. To set the currently active configuration use * Cache::config() * * ### Usage: * * Reading from the active cache configuration. * * `Cache::read('my_data');` * * Reading from a specific cache configuration. * * `Cache::read('my_data', 'long_term');` * * @param string $key Identifier for the data * @param string $config optional name of the configuration to use. Defaults to 'default' * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it */ public static function read($key, $config = 'default') { $settings = self::settings($config); if (empty($settings)) { return null; } if (!self::isInitialized($config)) { return false; } $key = self::$_engines[$config]->key($key); if (!$key) { return false; } return self::$_engines[$config]->read($settings['prefix'] . $key); } /** * Increment a number under the key and return incremented value. * * @param string $key Identifier for the data * @param integer $offset How much to add * @param string $config Optional string configuration name. Defaults to 'default' * @return mixed new value, or false if the data doesn't exist, is not integer, * or if there was an error fetching it. */ public static function increment($key, $offset = 1, $config = 'default') { $settings = self::settings($config); if (empty($settings)) { return null; } if (!self::isInitialized($config)) { return false; } $key = self::$_engines[$config]->key($key); if (!$key || !is_integer($offset) || $offset < 0) { return false; } $success = self::$_engines[$config]->increment($settings['prefix'] . $key, $offset); self::set(null, $config); return $success; } /** * Decrement a number under the key and return decremented value. * * @param string $key Identifier for the data * @param integer $offset How much to subtract * @param string $config Optional string configuration name. Defaults to 'default' * @return mixed new value, or false if the data doesn't exist, is not integer, * or if there was an error fetching it */ public static function decrement($key, $offset = 1, $config = 'default') { $settings = self::settings($config); if (empty($settings)) { return null; } if (!self::isInitialized($config)) { return false; } $key = self::$_engines[$config]->key($key); if (!$key || !is_integer($offset) || $offset < 0) { return false; } $success = self::$_engines[$config]->decrement($settings['prefix'] . $key, $offset); self::set(null, $config); return $success; } /** * Delete a key from the cache. * * ### Usage: * * Deleting from the active cache configuration. * * `Cache::delete('my_data');` * * Deleting from a specific cache configuration. * * `Cache::delete('my_data', 'long_term');` * * @param string $key Identifier for the data * @param string $config name of the configuration to use. Defaults to 'default' * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed */ public static function delete($key, $config = 'default') { $settings = self::settings($config); if (empty($settings)) { return null; } if (!self::isInitialized($config)) { return false; } $key = self::$_engines[$config]->key($key); if (!$key) { return false; } $success = self::$_engines[$config]->delete($settings['prefix'] . $key); self::set(null, $config); return $success; } /** * Delete all keys from the cache. * * @param boolean $check if true will check expiration, otherwise delete all * @param string $config name of the configuration to use. Defaults to 'default' * @return boolean True if the cache was successfully cleared, false otherwise */ public static function clear($check = false, $config = 'default') { if (!self::isInitialized($config)) { return false; } $success = self::$_engines[$config]->clear($check); self::set(null, $config); return $success; } /** * Check if Cache has initialized a working config for the given name. * * @param string $config name of the configuration to use. Defaults to 'default' * @return boolean Whether or not the config name has been initialized. */ public static function isInitialized($config = 'default') { if (Configure::read('Cache.disable')) { return false; } return isset(self::$_engines[$config]); } /** * Return the settings for the named cache engine. * * @param string $name Name of the configuration to get settings for. Defaults to 'default' * @return array list of settings for this engine * @see Cache::config() */ public static function settings($name = 'default') { if (!empty(self::$_engines[$name])) { return self::$_engines[$name]->settings(); } return array(); } } /** * Storage engine for CakePHP caching * * @package Cake.Cache */ abstract class CacheEngine { /** * Settings of current engine instance * * @var array */ public $settings = array(); /** * Initialize the cache engine * * Called automatically by the cache frontend * * @param array $settings Associative array of parameters for the engine * @return boolean True if the engine has been successfully initialized, false if not */ public function init($settings = array()) { $this->settings = array_merge( array('prefix' => 'cake_', 'duration'=> 3600, 'probability'=> 100), $this->settings, $settings ); if (!is_numeric($this->settings['duration'])) { $this->settings['duration'] = strtotime($this->settings['duration']) - time(); } return true; } /** * Garbage collection * * Permanently remove all expired and deleted data * @return void */ public function gc() { } /** * Write value for a key into cache * * @param string $key Identifier for the data * @param mixed $value Data to be cached * @param mixed $duration How long to cache for. * @return boolean True if the data was successfully cached, false on failure */ abstract public function write($key, $value, $duration); /** * Read a key from the cache * * @param string $key Identifier for the data * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it */ abstract public function read($key); /** * Increment a number under the key and return incremented value * * @param string $key Identifier for the data * @param integer $offset How much to add * @return New incremented value, false otherwise */ abstract public function increment($key, $offset = 1); /** * Decrement a number under the key and return decremented value * * @param string $key Identifier for the data * @param integer $offset How much to subtract * @return New incremented value, false otherwise */ abstract public function decrement($key, $offset = 1); /** * Delete a key from the cache * * @param string $key Identifier for the data * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed */ abstract public function delete($key); /** * Delete all keys from the cache * * @param boolean $check if true will check expiration, otherwise delete all * @return boolean True if the cache was successfully cleared, false otherwise */ abstract public function clear($check); /** * Cache Engine settings * * @return array settings */ public function settings() { return $this->settings; } /** * Generates a safe key for use with cache engine storage engines. * * @param string $key the key passed over * @return mixed string $key or false */ public function key($key) { if (empty($key)) { return false; } $key = Inflector::underscore(str_replace(array(DS, '/', '.'), '_', strval($key))); return $key; } }
0001-bee
trunk/cakephp2/lib/Cake/Cache/Cache.php
PHP
gpl3
18,214
<?php /** * APC storage engine for cache. * * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Cache.Engine * @since CakePHP(tm) v 1.2.0.4933 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * APC storage engine for cache * * @package Cake.Cache.Engine */ class ApcEngine extends CacheEngine { /** * Initialize the Cache Engine * * Called automatically by the cache frontend * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array()); * * @param array $settings array of setting for the engine * @return boolean True if the engine has been successfully initialized, false if not * @see CacheEngine::__defaults */ public function init($settings = array()) { parent::init(array_merge(array('engine' => 'Apc', 'prefix' => Inflector::slug(APP_DIR) . '_'), $settings)); return function_exists('apc_cache_info'); } /** * Write data for key into cache * * @param string $key Identifier for the data * @param mixed $value Data to be cached * @param integer $duration How long to cache the data, in seconds * @return boolean True if the data was successfully cached, false on failure */ public function write($key, $value, $duration) { if ($duration == 0) { $expires = 0; } else { $expires = time() + $duration; } apc_store($key.'_expires', $expires, $duration); return apc_store($key, $value, $duration); } /** * Read a key from the cache * * @param string $key Identifier for the data * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it */ public function read($key) { $time = time(); $cachetime = intval(apc_fetch($key.'_expires')); if ($cachetime !== 0 && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) { return false; } return apc_fetch($key); } /** * Increments the value of an integer cached key * * @param string $key Identifier for the data * @param integer $offset How much to increment * @return New incremented value, false otherwise */ public function increment($key, $offset = 1) { return apc_inc($key, $offset); } /** * Decrements the value of an integer cached key * * @param string $key Identifier for the data * @param integer $offset How much to subtract * @return New decremented value, false otherwise */ public function decrement($key, $offset = 1) { return apc_dec($key, $offset); } /** * Delete a key from the cache * * @param string $key Identifier for the data * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed */ public function delete($key) { return apc_delete($key); } /** * Delete all keys from the cache. This will clear every cache config using APC. * * @param boolean $check If true, nothing will be cleared, as entries are removed * from APC as they expired. This flag is really only used by FileEngine. * @return boolean True Returns true. */ public function clear($check) { if ($check) { return true; } $info = apc_cache_info('user'); $cacheKeys = $info['cache_list']; unset($info); foreach ($cacheKeys as $key) { if (strpos($key['info'], $this->settings['prefix']) === 0) { apc_delete($key['info']); } } return true; } }
0001-bee
trunk/cakephp2/lib/Cake/Cache/Engine/ApcEngine.php
PHP
gpl3
3,743
<?php /** * File Storage engine for cache. Filestorage is the slowest cache storage * to read and write. However, it is good for servers that don't have other storage * engine available, or have content which is not performance sensitive. * * You can configure a FileEngine cache, using Cache::config() * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since CakePHP(tm) v 1.2.0.4933 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * File Storage engine for cache * * @package Cake.Cache.Engine */ class FileEngine extends CacheEngine { /** * Instance of SplFileObject class * * @var File */ protected $_File = null; /** * Settings * * - path = absolute path to cache directory, default => CACHE * - prefix = string prefix for filename, default => cake_ * - lock = enable file locking on write, default => false * - serialize = serialize the data, default => true * * @var array * @see CacheEngine::__defaults */ public $settings = array(); /** * True unless FileEngine::__active(); fails * * @var boolean */ protected $_init = true; /** * Initialize the Cache Engine * * Called automatically by the cache frontend * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array()); * * @param array $settings array of setting for the engine * @return boolean True if the engine has been successfully initialized, false if not */ public function init($settings = array()) { parent::init(array_merge( array( 'engine' => 'File', 'path' => CACHE, 'prefix'=> 'cake_', 'lock'=> true, 'serialize'=> true, 'isWindows' => false, 'mask' => 0664 ), $settings )); if (DS === '\\') { $this->settings['isWindows'] = true; } if (substr($this->settings['path'], -1) !== DS) { $this->settings['path'] .= DS; } return $this->_active(); } /** * Garbage collection. Permanently remove all expired and deleted data * * @return boolean True if garbage collection was succesful, false on failure */ public function gc() { return $this->clear(true); } /** * Write data for key into cache * * @param string $key Identifier for the data * @param mixed $data Data to be cached * @param mixed $duration How long to cache the data, in seconds * @return boolean True if the data was successfully cached, false on failure */ public function write($key, $data, $duration) { if ($data === '' || !$this->_init) { return false; } if ($this->_setKey($key, true) === false) { return false; } $lineBreak = "\n"; if ($this->settings['isWindows']) { $lineBreak = "\r\n"; } if (!empty($this->settings['serialize'])) { if ($this->settings['isWindows']) { $data = str_replace('\\', '\\\\\\\\', serialize($data)); } else { $data = serialize($data); } } $expires = time() + $duration; $contents = $expires . $lineBreak . $data . $lineBreak; if ($this->settings['lock']) { $this->_File->flock(LOCK_EX); } $success = $this->_File->ftruncate(0) && $this->_File->fwrite($contents) && $this->_File->fflush(); if ($this->settings['lock']) { $this->_File->flock(LOCK_UN); } return $success; } /** * Read a key from the cache * * @param string $key Identifier for the data * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it */ public function read($key) { if (!$this->_init || $this->_setKey($key) === false) { return false; } if ($this->settings['lock']) { $this->_File->flock(LOCK_SH); } $this->_File->rewind(); $time = time(); $cachetime = intval($this->_File->current()); if ($cachetime !== false && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) { if ($this->settings['lock']) { $this->_File->flock(LOCK_UN); } return false; } $data = ''; $this->_File->next(); while ($this->_File->valid()) { $data .= $this->_File->current(); $this->_File->next(); } if ($this->settings['lock']) { $this->_File->flock(LOCK_UN); } $data = trim($data); if ($data !== '' && !empty($this->settings['serialize'])) { if ($this->settings['isWindows']) { $data = str_replace('\\\\\\\\', '\\', $data); } $data = unserialize((string)$data); } return $data; } /** * Delete a key from the cache * * @param string $key Identifier for the data * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed */ public function delete($key) { if ($this->_setKey($key) === false || !$this->_init) { return false; } $path = $this->_File->getRealPath(); $this->_File = null; return unlink($path); } /** * Delete all values from the cache * * @param boolean $check Optional - only delete expired cache items * @return boolean True if the cache was successfully cleared, false otherwise */ public function clear($check) { if (!$this->_init) { return false; } $dir = dir($this->settings['path']); if ($check) { $now = time(); $threshold = $now - $this->settings['duration']; } $prefixLength = strlen($this->settings['prefix']); while (($entry = $dir->read()) !== false) { if (substr($entry, 0, $prefixLength) !== $this->settings['prefix']) { continue; } if ($this->_setKey($entry) === false) { continue; } if ($check) { $mtime = $this->_File->getMTime(); if ($mtime > $threshold) { continue; } $expires = (int)$this->_File->current(); if ($expires > $now) { continue; } } $path = $this->_File->getRealPath(); $this->_File = null; if (file_exists($path)) { unlink($path); } } $dir->close(); return true; } /** * Not implemented * * @param string $key * @param integer $offset * @return void * @throws CacheException */ public function decrement($key, $offset = 1) { throw new CacheException(__d('cake_dev', 'Files cannot be atomically decremented.')); } /** * Not implemented * * @param string $key * @param integer $offset * @return void * @throws CacheException */ public function increment($key, $offset = 1) { throw new CacheException(__d('cake_dev', 'Files cannot be atomically incremented.')); } /** * Sets the current cache key this class is managing, and creates a writable SplFileObject * for the cache file the key is refering to. * * @param string $key The key * @param boolean $createKey Whether the key should be created if it doesn't exists, or not * @return boolean true if the cache key could be set, false otherwise */ protected function _setKey($key, $createKey = false) { $path = new SplFileInfo($this->settings['path'] . $key); if (!$createKey && !$path->isFile()) { return false; } if (empty($this->_File) || $this->_File->getBaseName() !== $key) { $exists = file_exists($path->getPathname()); try { $this->_File = $path->openFile('c+'); } catch (Exception $e) { trigger_error($e->getMessage(), E_USER_WARNING); return false; } unset($path); if (!$exists && !chmod($this->_File->getPathname(), (int) $this->settings['mask'])) { trigger_error(__d( 'cake_dev', 'Could not apply permission mask "%s" on cache file "%s"', array($this->_File->getPathname(), $this->settings['mask'])), E_USER_WARNING); } } return true; } /** * Determine is cache directory is writable * * @return boolean */ protected function _active() { $dir = new SplFileInfo($this->settings['path']); if ($this->_init && !($dir->isDir() && $dir->isWritable())) { $this->_init = false; trigger_error(__d('cake_dev', '%s is not writable', $this->settings['path']), E_USER_WARNING); return false; } return true; } }
0001-bee
trunk/cakephp2/lib/Cake/Cache/Engine/FileEngine.php
PHP
gpl3
8,161
<?php /** * Wincache storage engine for cache. * * Supports wincache 1.1.0 and higher. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Cache.Engine * @since CakePHP(tm) v 1.2.0.4933 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Wincache storage engine for cache * * @package Cake.Cache.Engine */ class WincacheEngine extends CacheEngine { /** * Initialize the Cache Engine * * Called automatically by the cache frontend * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array()); * * @param array $settings array of setting for the engine * @return boolean True if the engine has been successfully initialized, false if not * @see CacheEngine::__defaults */ public function init($settings = array()) { parent::init(array_merge(array( 'engine' => 'Wincache', 'prefix' => Inflector::slug(APP_DIR) . '_'), $settings)); return function_exists('wincache_ucache_info'); } /** * Write data for key into cache * * @param string $key Identifier for the data * @param mixed $value Data to be cached * @param integer $duration How long to cache the data, in seconds * @return boolean True if the data was successfully cached, false on failure */ public function write($key, $value, $duration) { $expires = time() + $duration; $data = array( $key . '_expires' => $expires, $key => $value ); $result = wincache_ucache_set($data, null, $duration); return empty($result); } /** * Read a key from the cache * * @param string $key Identifier for the data * @return mixed The cached data, or false if the data doesn't exist, has expired, or if * there was an error fetching it */ public function read($key) { $time = time(); $cachetime = intval(wincache_ucache_get($key . '_expires')); if ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime) { return false; } return wincache_ucache_get($key); } /** * Increments the value of an integer cached key * * @param string $key Identifier for the data * @param integer $offset How much to increment * @return New incremented value, false otherwise */ public function increment($key, $offset = 1) { return wincache_ucache_inc($key, $offset); } /** * Decrements the value of an integer cached key * * @param string $key Identifier for the data * @param integer $offset How much to subtract * @return New decremented value, false otherwise */ public function decrement($key, $offset = 1) { return wincache_ucache_dec($key, $offset); } /** * Delete a key from the cache * * @param string $key Identifier for the data * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed */ public function delete($key) { return wincache_ucache_delete($key); } /** * Delete all keys from the cache. This will clear every * item in the cache matching the cache config prefix. * * @param boolean $check If true, nothing will be cleared, as entries will * naturally expire in wincache.. * @return boolean True Returns true. */ public function clear($check) { if ($check) { return true; } $info = wincache_ucache_info(); $cacheKeys = $info['ucache_entries']; unset($info); foreach ($cacheKeys as $key) { if (strpos($key['key_name'], $this->settings['prefix']) === 0) { wincache_ucache_delete($key['key_name']); } } return true; } }
0001-bee
trunk/cakephp2/lib/Cake/Cache/Engine/WincacheEngine.php
PHP
gpl3
3,870
<?php /** * Memcache storage engine for cache * * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Cache.Engine * @since CakePHP(tm) v 1.2.0.4933 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Memcache storage engine for cache. Memcache has some limitations in the amount of * control you have over expire times far in the future. See MemcacheEngine::write() for * more information. * * @package Cake.Cache.Engine */ class MemcacheEngine extends CacheEngine { /** * Memcache wrapper. * * @var Memcache */ protected $_Memcache = null; /** * Settings * * - servers = string or array of memcache servers, default => 127.0.0.1. If an * array MemcacheEngine will use them as a pool. * - compress = boolean, default => false * * @var array */ public $settings = array(); /** * Initialize the Cache Engine * * Called automatically by the cache frontend * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array()); * * @param array $settings array of setting for the engine * @return boolean True if the engine has been successfully initialized, false if not */ public function init($settings = array()) { if (!class_exists('Memcache')) { return false; } parent::init(array_merge(array( 'engine'=> 'Memcache', 'prefix' => Inflector::slug(APP_DIR) . '_', 'servers' => array('127.0.0.1'), 'compress'=> false, 'persistent' => true ), $settings) ); if ($this->settings['compress']) { $this->settings['compress'] = MEMCACHE_COMPRESSED; } if (!is_array($this->settings['servers'])) { $this->settings['servers'] = array($this->settings['servers']); } if (!isset($this->_Memcache)) { $return = false; $this->_Memcache = new Memcache(); foreach ($this->settings['servers'] as $server) { list($host, $port) = $this->_parseServerString($server); if ($this->_Memcache->addServer($host, $port, $this->settings['persistent'])) { $return = true; } } return $return; } return true; } /** * Parses the server address into the host/port. Handles both IPv6 and IPv4 * addresses and Unix sockets * * @param string $server The server address string. * @return array Array containing host, port */ protected function _parseServerString($server) { if ($server[0] == 'u') { return array($server, 0); } if (substr($server, 0, 1) == '[') { $position = strpos($server, ']:'); if ($position !== false) { $position++; } } else { $position = strpos($server, ':'); } $port = 11211; $host = $server; if ($position !== false) { $host = substr($server, 0, $position); $port = substr($server, $position + 1); } return array($host, $port); } /** * Write data for key into cache. When using memcache as your cache engine * remember that the Memcache pecl extension does not support cache expiry times greater * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring. * * @param string $key Identifier for the data * @param mixed $value Data to be cached * @param integer $duration How long to cache the data, in seconds * @return boolean True if the data was successfully cached, false on failure * @see http://php.net/manual/en/memcache.set.php */ public function write($key, $value, $duration) { if ($duration > 30 * DAY) { $duration = 0; } return $this->_Memcache->set($key, $value, $this->settings['compress'], $duration); } /** * Read a key from the cache * * @param string $key Identifier for the data * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it */ public function read($key) { return $this->_Memcache->get($key); } /** * Increments the value of an integer cached key * * @param string $key Identifier for the data * @param integer $offset How much to increment * @return New incremented value, false otherwise * @throws CacheException when you try to increment with compress = true */ public function increment($key, $offset = 1) { if ($this->settings['compress']) { throw new CacheException( __d('cake_dev', 'Method increment() not implemented for compressed cache in %s', __CLASS__) ); } return $this->_Memcache->increment($key, $offset); } /** * Decrements the value of an integer cached key * * @param string $key Identifier for the data * @param integer $offset How much to subtract * @return New decremented value, false otherwise * @throws CacheException when you try to decrement with compress = true */ public function decrement($key, $offset = 1) { if ($this->settings['compress']) { throw new CacheException( __d('cake_dev', 'Method decrement() not implemented for compressed cache in %s', __CLASS__) ); } return $this->_Memcache->decrement($key, $offset); } /** * Delete a key from the cache * * @param string $key Identifier for the data * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed */ public function delete($key) { return $this->_Memcache->delete($key); } /** * Delete all keys from the cache * * @param boolean $check * @return boolean True if the cache was successfully cleared, false otherwise */ public function clear($check) { if ($check) { return true; } foreach ($this->_Memcache->getExtendedStats('slabs') as $slabs) { foreach (array_keys($slabs) as $slabId) { if (!is_numeric($slabId)) { continue; } foreach ($this->_Memcache->getExtendedStats('cachedump', $slabId) as $stats) { if (!is_array($stats)) { continue; } foreach (array_keys($stats) as $key) { if (strpos($key, $this->settings['prefix']) === 0) { $this->_Memcache->delete($key); } } } } } return true; } /** * Connects to a server in connection pool * * @param string $host host ip address or name * @param integer $port Server port * @return boolean True if memcache server was connected */ public function connect($host, $port = 11211) { if ($this->_Memcache->getServerStatus($host, $port) === 0) { if ($this->_Memcache->connect($host, $port)) { return true; } return false; } return true; } }
0001-bee
trunk/cakephp2/lib/Cake/Cache/Engine/MemcacheEngine.php
PHP
gpl3
6,719
<?php /** * Xcache storage engine for cache. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Cache.Engine * @since CakePHP(tm) v 1.2.0.4947 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Xcache storage engine for cache * * @link http://trac.lighttpd.net/xcache/ Xcache * @package Cake.Cache.Engine */ class XcacheEngine extends CacheEngine { /** * Settings * * - PHP_AUTH_USER = xcache.admin.user, default cake * - PHP_AUTH_PW = xcache.admin.password, default cake * * @var array */ public $settings = array(); /** * Initialize the Cache Engine * * Called automatically by the cache frontend * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array()); * * @param array $settings array of setting for the engine * @return boolean True if the engine has been successfully initialized, false if not */ public function init($settings = array()) { parent::init(array_merge(array( 'engine' => 'Xcache', 'prefix' => Inflector::slug(APP_DIR) . '_', 'PHP_AUTH_USER' => 'user', 'PHP_AUTH_PW' => 'password' ), $settings) ); return function_exists('xcache_info'); } /** * Write data for key into cache * * @param string $key Identifier for the data * @param mixed $value Data to be cached * @param integer $duration How long to cache the data, in seconds * @return boolean True if the data was successfully cached, false on failure */ public function write($key, $value, $duration) { $expires = time() + $duration; xcache_set($key . '_expires', $expires, $duration); return xcache_set($key, $value, $duration); } /** * Read a key from the cache * * @param string $key Identifier for the data * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it */ public function read($key) { if (xcache_isset($key)) { $time = time(); $cachetime = intval(xcache_get($key . '_expires')); if ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime) { return false; } return xcache_get($key); } return false; } /** * Increments the value of an integer cached key * If the cache key is not an integer it will be treated as 0 * * @param string $key Identifier for the data * @param integer $offset How much to increment * @return New incremented value, false otherwise */ public function increment($key, $offset = 1) { return xcache_inc($key, $offset); } /** * Decrements the value of an integer cached key. * If the cache key is not an integer it will be treated as 0 * * @param string $key Identifier for the data * @param integer $offset How much to subtract * @return New decremented value, false otherwise */ public function decrement($key, $offset = 1) { return xcache_dec($key, $offset); } /** * Delete a key from the cache * * @param string $key Identifier for the data * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed */ public function delete($key) { return xcache_unset($key); } /** * Delete all keys from the cache * * @param boolean $check * @return boolean True if the cache was successfully cleared, false otherwise */ public function clear($check) { $this->_auth(); $max = xcache_count(XC_TYPE_VAR); for ($i = 0; $i < $max; $i++) { xcache_clear_cache(XC_TYPE_VAR, $i); } $this->_auth(true); return true; } /** * Populates and reverses $_SERVER authentication values * Makes necessary changes (and reverting them back) in $_SERVER * * This has to be done because xcache_clear_cache() needs to pass Basic Http Auth * (see xcache.admin configuration settings) * * @param boolean $reverse Revert changes * @return void */ protected function _auth($reverse = false) { static $backup = array(); $keys = array('PHP_AUTH_USER' => 'user', 'PHP_AUTH_PW' => 'password'); foreach ($keys as $key => $setting) { if ($reverse) { if (isset($backup[$key])) { $_SERVER[$key] = $backup[$key]; unset($backup[$key]); } else { unset($_SERVER[$key]); } } else { $value = env($key); if (!empty($value)) { $backup[$key] = $value; } if (!empty($this->settings[$setting])) { $_SERVER[$key] = $this->settings[$setting]; } else if (!empty($this->settings[$key])) { $_SERVER[$key] = $this->settings[$key]; } else { $_SERVER[$key] = $value; } } } } }
0001-bee
trunk/cakephp2/lib/Cake/Cache/Engine/XcacheEngine.php
PHP
gpl3
4,915
<?php /** * Exceptions file. Contains the various exceptions CakePHP will throw until they are * moved into their permanent location. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests * @package Cake.Error * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Parent class for all of the HTTP related exceptions in CakePHP. * All HTTP status/error related exceptions should extend this class so * catch blocks can be specifically typed. * * @package Cake.Error */ if (!class_exists('HttpException')) { class HttpException extends RuntimeException { } } /** * Represents an HTTP 400 error. * * @package Cake.Error */ class BadRequestException extends HttpException { /** * Constructor * * @param string $message If no message is given 'Bad Request' will be the message * @param string $code Status code, defaults to 400 */ public function __construct($message = null, $code = 400) { if (empty($message)) { $message = 'Bad Request'; } parent::__construct($message, $code); } } /** * Represents an HTTP 401 error. * * @package Cake.Error */ class UnauthorizedException extends HttpException { /** * Constructor * * @param string $message If no message is given 'Unauthorized' will be the message * @param string $code Status code, defaults to 401 */ public function __construct($message = null, $code = 401) { if (empty($message)) { $message = 'Unauthorized'; } parent::__construct($message, $code); } } /** * Represents an HTTP 403 error. * * @package Cake.Error */ class ForbiddenException extends HttpException { /** * Constructor * * @param string $message If no message is given 'Forbidden' will be the message * @param string $code Status code, defaults to 403 */ public function __construct($message = null, $code = 403) { if (empty($message)) { $message = 'Forbidden'; } parent::__construct($message, $code); } } /** * Represents an HTTP 404 error. * * @package Cake.Error */ class NotFoundException extends HttpException { /** * Constructor * * @param string $message If no message is given 'Not Found' will be the message * @param string $code Status code, defaults to 404 */ public function __construct($message = null, $code = 404) { if (empty($message)) { $message = 'Not Found'; } parent::__construct($message, $code); } } /** * Represents an HTTP 405 error. * * @package Cake.Error */ class MethodNotAllowedException extends HttpException { /** * Constructor * * @param string $message If no message is given 'Method Not Allowed' will be the message * @param string $code Status code, defaults to 405 */ public function __construct($message = null, $code = 405) { if (empty($message)) { $message = 'Method Not Allowed'; } parent::__construct($message, $code); } } /** * Represents an HTTP 500 error. * * @package Cake.Error */ class InternalErrorException extends HttpException { /** * Constructor * * @param string $message If no message is given 'Internal Server Error' will be the message * @param string $code Status code, defaults to 500 */ public function __construct($message = null, $code = 500) { if (empty($message)) { $message = 'Internal Server Error'; } parent::__construct($message, $code); } } /** * CakeException is used a base class for CakePHP's internal exceptions. * In general framework errors are interpreted as 500 code errors. * * @package Cake.Error */ class CakeException extends RuntimeException { /** * Array of attributes that are passed in from the constructor, and * made available in the view when a development error is displayed. * * @var array */ protected $_attributes = array(); /** * Template string that has attributes sprintf()'ed into it. * * @var string */ protected $_messageTemplate = ''; /** * Constructor. * * Allows you to create exceptions that are treated as framework errors and disabled * when debug = 0. * * @param mixed $message Either the string of the error message, or an array of attributes * that are made available in the view, and sprintf()'d into CakeException::$_messageTemplate * @param string $code The code of the error, is also the HTTP status code for the error. */ public function __construct($message, $code = 500) { if (is_array($message)) { $this->_attributes = $message; $message = __d('cake_dev', $this->_messageTemplate, $message); } parent::__construct($message, $code); } /** * Get the passed in attributes * * @return array */ public function getAttributes() { return $this->_attributes; } } /** * Missing Controller exception - used when a controller * cannot be found. * * @package Cake.Error */ class MissingControllerException extends CakeException { protected $_messageTemplate = 'Controller class %s could not be found.'; public function __construct($message, $code = 404) { parent::__construct($message, $code); } } /** * Missing Action exception - used when a controller action * cannot be found. * * @package Cake.Error */ class MissingActionException extends CakeException { protected $_messageTemplate = 'Action %s::%s() could not be found.'; public function __construct($message, $code = 404) { parent::__construct($message, $code); } } /** * Private Action exception - used when a controller action * starts with a `_`. * * @package Cake.Error */ class PrivateActionException extends CakeException { protected $_messageTemplate = 'Private Action %s::%s() is not directly accessible.'; public function __construct($message, $code = 404, Exception $previous = null) { parent::__construct($message, $code, $previous); } } /** * Used when a component cannot be found. * * @package Cake.Error */ class MissingComponentException extends CakeException { protected $_messageTemplate = 'Component class %s could not be found.'; } /** * Used when a behavior cannot be found. * * @package Cake.Error */ class MissingBehaviorException extends CakeException { protected $_messageTemplate = 'Behavior class %s could not be found.'; } /** * Used when a view file cannot be found. * * @package Cake.Error */ class MissingViewException extends CakeException { protected $_messageTemplate = 'View file "%s" is missing.'; } /** * Used when a layout file cannot be found. * * @package Cake.Error */ class MissingLayoutException extends CakeException { protected $_messageTemplate = 'Layout file "%s" is missing.'; } /** * Used when a helper cannot be found. * * @package Cake.Error */ class MissingHelperException extends CakeException { protected $_messageTemplate = 'Helper class %s could not be found.'; } /** * Runtime Exceptions for ConnectionManager * * @package Cake.Error */ class MissingDatabaseException extends CakeException { protected $_messageTemplate = 'Database connection "%s" could not be found.'; } /** * Used when no connections can be found. * * @package Cake.Error */ class MissingConnectionException extends CakeException { protected $_messageTemplate = 'Database connection "%s" is missing, or could not be created.'; } /** * Used when a Task cannot be found. * * @package Cake.Error */ class MissingTaskException extends CakeException { protected $_messageTemplate = 'Task class %s could not be found.'; } /** * Used when a shell method cannot be found. * * @package Cake.Error */ class MissingShellMethodException extends CakeException { protected $_messageTemplate = "Unknown command %1\$s %2\$s.\nFor usage try `cake %1\$s --help`"; } /** * Used when a shell cannot be found. * * @package Cake.Error */ class MissingShellException extends CakeException { protected $_messageTemplate = 'Shell class %s could not be found.'; } /** * Exception class to be thrown when a datasource configuration is not found * * @package Cake.Error */ class MissingDatasourceConfigException extends CakeException { protected $_messageTemplate = 'The datasource configuration "%s" was not found in database.php'; } /** * Used when a datasource cannot be found. * * @package Cake.Error */ class MissingDatasourceException extends CakeException { protected $_messageTemplate = 'Datasource class %s could not be found.'; } /** * Exception class to be thrown when a database table is not found in the datasource * * @package Cake.Error */ class MissingTableException extends CakeException { protected $_messageTemplate = 'Database table %s for model %s was not found.'; } /** * Exception raised when a Model could not be found. * * @package Cake.Error */ class MissingModelException extends CakeException { protected $_messageTemplate = 'Model %s could not be found.'; } /** * Exception raised when a test loader could not be found * * @package Cake.Error */ class MissingTestLoaderException extends CakeException { protected $_messageTemplate = 'Test loader %s could not be found.'; } /** * Exception raised when a plugin could not be found * * @package Cake.Error */ class MissingPluginException extends CakeException { protected $_messageTemplate = 'Plugin %s could not be found.'; } /** * Exception class for Cache. This exception will be thrown from Cache when it * encounters an error. * * @package Cake.Error */ class CacheException extends CakeException { } /** * Exception class for Router. This exception will be thrown from Router when it * encounters an error. * * @package Cake.Error */ class RouterException extends CakeException { } /** * Exception class for CakeLog. This exception will be thrown from CakeLog when it * encounters an error. * * @package Cake.Error */ class CakeLogException extends CakeException { } /** * Exception class for CakeSession. This exception will be thrown from CakeSession when it * encounters an error. * * @package Cake.Error */ class CakeSessionException extends CakeException { } /** * Exception class for Configure. This exception will be thrown from Configure when it * encounters an error. * * @package Cake.Error */ class ConfigureException extends CakeException { } /** * Exception class for Socket. This exception will be thrown from CakeSocket, CakeEmail, HttpSocket * SmtpTransport and HttpResponse when it encounters an error. * * @package Cake.Error */ class SocketException extends CakeException { } /** * Exception class for Xml. This exception will be thrown from Xml when it * encounters an error. * * @package Cake.Error */ class XmlException extends CakeException { } /** * Exception class for Console libraries. This exception will be thrown from Console library * classes when they encounter an error. * * @package Cake.Error */ class ConsoleException extends CakeException { }
0001-bee
trunk/cakephp2/lib/Cake/Error/exceptions.php
PHP
gpl3
11,398
<?php /** * Exception Renderer * * Provides Exception rendering features. Which allow exceptions to be rendered * as HTML pages. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Error * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Sanitize', 'Utility'); App::uses('Router', 'Routing'); App::uses('CakeResponse', 'Network'); /** * Exception Renderer. * * Captures and handles all unhandled exceptions. Displays helpful framework errors when debug > 1. * When debug < 1 a CakeException will render 404 or 500 errors. If an uncaught exception is thrown * and it is a type that ExceptionHandler does not know about it will be treated as a 500 error. * * ### Implementing application specific exception rendering * * You can implement application specific exception handling in one of a few ways: * * - Create a AppController::appError(); * - Create a subclass of ExceptionRenderer and configure it to be the `Exception.renderer` * * #### Using AppController::appError(); * * This controller method is called instead of the default exception handling. It receives the * thrown exception as its only argument. You should implement your error handling in that method. * * #### Using a subclass of ExceptionRenderer * * Using a subclass of ExceptionRenderer gives you full control over how Exceptions are rendered, you * can configure your class in your core.php, with `Configure::write('Exception.renderer', 'MyClass');` * You should place any custom exception renderers in `app/Lib/Error`. * * @package Cake.Error */ class ExceptionRenderer { /** * Controller instance. * * @var Controller */ public $controller = null; /** * template to render for CakeException * * @var string */ public $template = ''; /** * The method corresponding to the Exception this object is for. * * @var string */ public $method = ''; /** * The exception being handled. * * @var Exception */ public $error = null; /** * Creates the controller to perform rendering on the error response. * If the error is a CakeException it will be converted to either a 400 or a 500 * code error depending on the code used to construct the error. * * @param Exception $exception Exception */ public function __construct(Exception $exception) { $this->controller = $this->_getController($exception); if (method_exists($this->controller, 'apperror')) { return $this->controller->appError($exception); } $method = $template = Inflector::variable(str_replace('Exception', '', get_class($exception))); $code = $exception->getCode(); $methodExists = method_exists($this, $method); if ($exception instanceof CakeException && !$methodExists) { $method = '_cakeError'; if (empty($template)) { $template = 'error500'; } if ($template == 'internalError') { $template = 'error500'; } } elseif ($exception instanceof PDOException) { $method = 'pdoError'; $template = 'pdo_error'; $code = 500; } elseif (!$methodExists) { $method = 'error500'; if ($code >= 400 && $code < 500) { $method = 'error400'; } } if (Configure::read('debug') == 0) { $parentClass = get_parent_class($this); if ($parentClass != __CLASS__) { $method = 'error400'; } $parentMethods = (array)get_class_methods($parentClass); if (in_array($method, $parentMethods)) { $method = 'error400'; } if ($code == 500) { $method = 'error500'; } } $this->template = $template; $this->method = $method; $this->error = $exception; } /** * Get the controller instance to handle the exception. * Override this method in subclasses to customize the controller used. * This method returns the built in `CakeErrorController` normally, or if an error is repeated * a bare controller will be used. * * @param Exception $exception The exception to get a controller for. * @return Controller */ protected function _getController($exception) { App::uses('CakeErrorController', 'Controller'); if (!$request = Router::getRequest(false)) { $request = new CakeRequest(); } $response = new CakeResponse(array('charset' => Configure::read('App.encoding'))); try { $controller = new CakeErrorController($request, $response); } catch (Exception $e) { $controller = new Controller($request, $response); $controller->viewPath = 'Errors'; } return $controller; } /** * Renders the response for the exception. * * @return void */ public function render() { if ($this->method) { call_user_func_array(array($this, $this->method), array($this->error)); } } /** * Generic handler for the internal framework errors CakePHP can generate. * * @param CakeException $error * @return void */ protected function _cakeError(CakeException $error) { $url = $this->controller->request->here(); $code = ($error->getCode() >= 400 && $error->getCode() < 506) ? $error->getCode() : 500; $this->controller->response->statusCode($code); $this->controller->set(array( 'code' => $code, 'url' => h($url), 'name' => $error->getMessage(), 'error' => $error, )); try { $this->controller->set($error->getAttributes()); $this->_outputMessage($this->template); } catch (Exception $e) { $this->_outputMessageSafe('error500'); } } /** * Convenience method to display a 400 series page. * * @param Exception $error * @return void */ public function error400($error) { $message = $error->getMessage(); if (Configure::read('debug') == 0 && $error instanceof CakeException) { $message = __('Not Found'); } $url = $this->controller->request->here(); $this->controller->response->statusCode($error->getCode()); $this->controller->set(array( 'name' => $message, 'url' => h($url), 'error' => $error, )); $this->_outputMessage('error400'); } /** * Convenience method to display a 500 page. * * @param Exception $error * @return void */ public function error500($error) { $url = $this->controller->request->here(); $code = ($error->getCode() > 500 && $error->getCode() < 506) ? $error->getCode() : 500; $this->controller->response->statusCode($code); $this->controller->set(array( 'name' => __('An Internal Error Has Occurred'), 'message' => h($url), 'error' => $error, )); $this->_outputMessage('error500'); } /** * Convenience method to display a PDOException. * * @param PDOException $error * @return void */ public function pdoError(PDOException $error) { $url = $this->controller->request->here(); $code = 500; $this->controller->response->statusCode($code); $this->controller->set(array( 'code' => $code, 'url' => h($url), 'name' => $error->getMessage(), 'error' => $error, )); try { $this->_outputMessage($this->template); } catch (Exception $e) { $this->_outputMessageSafe('error500'); } } /** * Generate the response using the controller object. * * @param string $template The template to render. * @return void */ protected function _outputMessage($template) { $this->controller->render($template); $this->controller->afterFilter(); $this->controller->response->send(); } /** * A safer way to render error messages, replaces all helpers, with basics * and doesn't call component methods. * * @param string $template The template to render * @return void */ protected function _outputMessageSafe($template) { $this->controller->helpers = array('Form', 'Html', 'Session'); $this->controller->render($template); $this->controller->response->send(); } }
0001-bee
trunk/cakephp2/lib/Cake/Error/ExceptionRenderer.php
PHP
gpl3
8,012
<?php /** * Error handler * * Provides Error Capturing for Framework errors. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Error * @since CakePHP(tm) v 0.10.5.1732 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Debugger', 'Utility'); App::uses('CakeLog', 'Log'); App::uses('ExceptionRenderer', 'Error'); App::uses('AppController', 'Controller'); /** * * Error Handler provides basic error and exception handling for your application. It captures and * handles all unhandled exceptions and errors. Displays helpful framework errors when debug > 1. * * ### Uncaught exceptions * * When debug < 1 a CakeException will render 404 or 500 errors. If an uncaught exception is thrown * and it is a type that ErrorHandler does not know about it will be treated as a 500 error. * * ### Implementing application specific exception handling * * You can implement application specific exception handling in one of a few ways. Each approach * gives you different amounts of control over the exception handling process. * * - Set Configure::write('Exception.handler', 'YourClass::yourMethod'); * - Create AppController::appError(); * - Set Configure::write('Exception.renderer', 'YourClass'); * * #### Create your own Exception handler with `Exception.handler` * * This gives you full control over the exception handling process. The class you choose should be * loaded in your app/Config/bootstrap.php, so its available to handle any exceptions. You can * define the handler as any callback type. Using Exception.handler overrides all other exception * handling settings and logic. * * #### Using `AppController::appError();` * * This controller method is called instead of the default exception rendering. It receives the * thrown exception as its only argument. You should implement your error handling in that method. * Using AppController::appError(), will supersede any configuration for Exception.renderer. * * #### Using a custom renderer with `Exception.renderer` * * If you don't want to take control of the exception handling, but want to change how exceptions are * rendered you can use `Exception.renderer` to choose a class to render exception pages. By default * `ExceptionRenderer` is used. Your custom exception renderer class should be placed in app/Error. * * Your custom renderer should expect an exception in its constructor, and implement a render method. * Failing to do so will cause additional errors. * * #### Logging exceptions * * Using the built-in exception handling, you can log all the exceptions * that are dealt with by ErrorHandler by setting `Exception.log` to true in your core.php. * Enabling this will log every exception to CakeLog and the configured loggers. * * ### PHP errors * * Error handler also provides the built in features for handling php errors (trigger_error). * While in debug mode, errors will be output to the screen using debugger. While in production mode, * errors will be logged to CakeLog. You can control which errors are logged by setting * `Error.level` in your core.php. * * #### Logging errors * * When ErrorHandler is used for handling errors, you can enable error logging by setting `Error.log` to true. * This will log all errors to the configured log handlers. * * #### Controlling what errors are logged/displayed * * You can control which errors are logged / displayed by ErrorHandler by setting `Error.level`. Setting this * to one or a combination of a few of the E_* constants will only enable the specified errors. * * e.g. `Configure::write('Error.level', E_ALL & ~E_NOTICE);` * * Would enable handling for all non Notice errors. * * @package Cake.Error * @see ExceptionRenderer for more information on how to customize exception rendering. */ class ErrorHandler { /** * Set as the default exception handler by the CakePHP bootstrap process. * * This will either use an AppError class if your application has one, * or use the default ExceptionRenderer. * * @param Exception $exception * @return void * @see http://php.net/manual/en/function.set-exception-handler.php */ public static function handleException(Exception $exception) { $config = Configure::read('Exception'); if (!empty($config['log'])) { $message = sprintf("[%s] %s\n%s", get_class($exception), $exception->getMessage(), $exception->getTraceAsString() ); CakeLog::write(LOG_ERR, $message); } $renderer = $config['renderer']; if ($renderer !== 'ExceptionRenderer') { list($plugin, $renderer) = pluginSplit($renderer, true); App::uses($renderer, $plugin . 'Error'); } try { $error = new $renderer($exception); $error->render(); } catch (Exception $e) { set_error_handler(Configure::read('Error.handler')); // Should be using configured ErrorHandler Configure::write('Error.trace', false); // trace is useless here since it's internal $message = sprintf("[%s] %s\n%s", // Keeping same message format get_class($e), $e->getMessage(), $e->getTraceAsString() ); trigger_error($message, E_USER_ERROR); } } /** * Set as the default error handler by CakePHP. Use Configure::write('Error.handler', $callback), to use your own * error handling methods. This function will use Debugger to display errors when debug > 0. And * will log errors to CakeLog, when debug == 0. * * You can use Configure::write('Error.level', $value); to set what type of errors will be handled here. * Stack traces for errors can be enabled with Configure::write('Error.trace', true); * * @param integer $code Code of error * @param string $description Error description * @param string $file File on which error occurred * @param integer $line Line that triggered the error * @param array $context Context * @return boolean true if error was handled */ public static function handleError($code, $description, $file = null, $line = null, $context = null) { if (error_reporting() === 0) { return false; } $errorConfig = Configure::read('Error'); list($error, $log) = self::mapErrorCode($code); $debug = Configure::read('debug'); if ($debug) { $data = array( 'level' => $log, 'code' => $code, 'error' => $error, 'description' => $description, 'file' => $file, 'line' => $line, 'context' => $context, 'start' => 2, 'path' => Debugger::trimPath($file) ); return Debugger::getInstance()->outputError($data); } else { $message = $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']'; if (!empty($errorConfig['trace'])) { $trace = Debugger::trace(array('start' => 1, 'format' => 'log')); $message .= "\nTrace:\n" . $trace . "\n"; } return CakeLog::write($log, $message); } } /** * Map an error code into an Error word, and log location. * * @param integer $code Error code to map * @return array Array of error word, and log location. */ public static function mapErrorCode($code) { $error = $log = null; switch ($code) { case E_PARSE: case E_ERROR: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_USER_ERROR: $error = 'Fatal Error'; $log = LOG_ERROR; break; case E_WARNING: case E_USER_WARNING: case E_COMPILE_WARNING: case E_RECOVERABLE_ERROR: $error = 'Warning'; $log = LOG_WARNING; break; case E_NOTICE: case E_USER_NOTICE: $error = 'Notice'; $log = LOG_NOTICE; break; case E_STRICT: $error = 'Strict'; $log = LOG_NOTICE; break; case E_DEPRECATED: $error = 'Deprecated'; $log = LOG_NOTICE; break; } return array($error, $log); } }
0001-bee
trunk/cakephp2/lib/Cake/Error/ErrorHandler.php
PHP
gpl3
8,117
<?php /** * Logging. * * Log messages to text files. * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Log * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Set up error level constants to be used within the framework if they are not defined within the * system. * */ if (!defined('LOG_WARNING')) { define('LOG_WARNING', 3); } if (!defined('LOG_NOTICE')) { define('LOG_NOTICE', 4); } if (!defined('LOG_DEBUG')) { define('LOG_DEBUG', 5); } if (!defined('LOG_INFO')) { define('LOG_INFO', 6); } /** * Logs messages to configured Log adapters. One or more adapters can be configured * using CakeLogs's methods. If you don't configure any adapters, and write to the logs * a default FileLog will be autoconfigured for you. * * ### Configuring Log adapters * * You can configure log adapters in your applications `bootstrap.php` file. A sample configuration * would look like: * * `CakeLog::config('my_log', array('engine' => 'FileLog'));` * * See the documentation on CakeLog::config() for more detail. * * ### Writing to the log * * You write to the logs using CakeLog::write(). See its documentation for more information. * * @package Cake.Log */ class CakeLog { /** * An array of connected streams. * Each stream represents a callable that will be called when write() is called. * * @var array */ protected static $_streams = array(); /** * Configure and add a new logging stream to CakeLog * You can use add loggers from app/Log/Engine use app.loggername, or any plugin/Log/Engine using plugin.loggername. * * ### Usage: * * {{{ * CakeLog::config('second_file', array( * 'engine' => 'FileLog', * 'path' => '/var/logs/my_app/' * )); * }}} * * Will configure a FileLog instance to use the specified path. All options that are not `engine` * are passed onto the logging adapter, and handled there. Any class can be configured as a logging * adapter as long as it implements the methods in CakeLogInterface. * * @param string $key The keyname for this logger, used to remove the logger later. * @param array $config Array of configuration information for the logger * @return boolean success of configuration. * @throws CakeLogException */ public static function config($key, $config) { if (empty($config['engine'])) { throw new CakeLogException(__d('cake_dev', 'Missing logger classname')); } $loggerName = $config['engine']; unset($config['engine']); $className = self::_getLogger($loggerName); $logger = new $className($config); if (!$logger instanceof CakeLogInterface) { throw new CakeLogException(sprintf( __d('cake_dev', 'logger class %s does not implement a write method.'), $loggerName )); } self::$_streams[$key] = $logger; return true; } /** * Attempts to import a logger class from the various paths it could be on. * Checks that the logger class implements a write method as well. * * @param string $loggerName the plugin.className of the logger class you want to build. * @return mixed boolean false on any failures, string of classname to use if search was successful. * @throws CakeLogException */ protected static function _getLogger($loggerName) { list($plugin, $loggerName) = pluginSplit($loggerName, true); App::uses($loggerName, $plugin . 'Log/Engine'); if (!class_exists($loggerName)) { throw new CakeLogException(__d('cake_dev', 'Could not load class %s', $loggerName)); } return $loggerName; } /** * Returns the keynames of the currently active streams * * @return array Array of configured log streams. */ public static function configured() { return array_keys(self::$_streams); } /** * Removes a stream from the active streams. Once a stream has been removed * it will no longer have messages sent to it. * * @param string $streamName Key name of a configured stream to remove. * @return void */ public static function drop($streamName) { unset(self::$_streams[$streamName]); } /** * Configures the automatic/default stream a FileLog. * * @return void */ protected static function _autoConfig() { self::_getLogger('FileLog'); self::$_streams['default'] = new FileLog(array('path' => LOGS)); } /** * Writes the given message and type to all of the configured log adapters. * Configured adapters are passed both the $type and $message variables. $type * is one of the following strings/values. * * ### Types: * * - `LOG_WARNING` => 'warning', * - `LOG_NOTICE` => 'notice', * - `LOG_INFO` => 'info', * - `LOG_DEBUG` => 'debug', * - `LOG_ERR` => 'error', * - `LOG_ERROR` => 'error' * * ### Usage: * * Write a message to the 'warning' log: * * `CakeLog::write('warning', 'Stuff is broken here');` * * @param string $type Type of message being written * @param string $message Message content to log * @return boolean Success */ public static function write($type, $message) { if (!defined('LOG_ERROR')) { define('LOG_ERROR', 2); } if (!defined('LOG_ERR')) { define('LOG_ERR', LOG_ERROR); } $levels = array( LOG_WARNING => 'warning', LOG_NOTICE => 'notice', LOG_INFO => 'info', LOG_DEBUG => 'debug', LOG_ERR => 'error', LOG_ERROR => 'error' ); if (is_int($type) && isset($levels[$type])) { $type = $levels[$type]; } if (empty(self::$_streams)) { self::_autoConfig(); } foreach (self::$_streams as $logger) { $logger->write($type, $message); } return true; } }
0001-bee
trunk/cakephp2/lib/Cake/Log/CakeLog.php
PHP
gpl3
5,923
<?php /** * File Storage stream for Logging * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project * @package Cake.Log.Engine * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('CakeLogInterface', 'Log'); /** * File Storage stream for Logging. Writes logs to different files * based on the type of log it is. * * @package Cake.Log.Engine */ class FileLog implements CakeLogInterface { /** * Path to save log files on. * * @var string */ protected $_path = null; /** * Constructs a new File Logger. * * Options * * - `path` the path to save logs on. * * @param array $options Options for the FileLog, see above. */ public function __construct($options = array()) { $options += array('path' => LOGS); $this->_path = $options['path']; } /** * Implements writing to log files. * * @param string $type The type of log you are making. * @param string $message The message you want to log. * @return boolean success of write. */ public function write($type, $message) { $debugTypes = array('notice', 'info', 'debug'); if ($type == 'error' || $type == 'warning') { $filename = $this->_path . 'error.log'; } elseif (in_array($type, $debugTypes)) { $filename = $this->_path . 'debug.log'; } else { $filename = $this->_path . $type . '.log'; } $output = date('Y-m-d H:i:s') . ' ' . ucfirst($type) . ': ' . $message . "\n"; return file_put_contents($filename, $output, FILE_APPEND); } }
0001-bee
trunk/cakephp2/lib/Cake/Log/Engine/FileLog.php
PHP
gpl3
1,940
<?php /** * CakeLogInterface * * PHP 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package Cake.Log * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * CakeLogStreamInterface is the interface that should be implemented * by all classes that are going to be used as Log streams. * * @package Cake.Log */ interface CakeLogInterface { /** * Write method to handle writes being made to the Logger * * @param string $type * @param string $message * @return void */ public function write($type, $message); }
0001-bee
trunk/cakephp2/lib/Cake/Log/CakeLogInterface.php
PHP
gpl3
981
<html> <head> <title>Busloop - It's happening</title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script> <link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'> <style> body{ padding: 0; margin: 0; background-image: url(graphics/texture-1.png); font-family: 'Open Sans Condensed'; } #powerlay{ position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: -webkit-radial-gradient(circle, #fff, #0d56a6); background: -moz-radial-gradient(circle, #fff, #0d56a6); opacity: .3; -moz-opacity: .3; } #splash{ position: absolute; width: 100%; display: none; } #footer{ position: fixed; width: 100%; bottom: 35px; color: #555; font-size: .9em; } p.big{ font-size: 1.5em; } #stripes{ position: fixed; width: 100%; bottom: 0px; } #stripe1{ opacity: .8; -moz-opacity: .8; height: 20px; background: #ffc873; } #stripe2{ opacity: .8; -moz-opacity: .8; height: 10px; background: #ffb440; background: #ff9a00; } </style> <script> $(document).ready(function(){ $('#splash').css('top',(0.8*window.innerHeight/2-$('#splash').outerHeight()/2)+'px').fadeIn() }) </script> </head> <body> <div id="powerlay"></div> <div id="splash" align="center"> <img src="graphics/busloop.png" /> <p class="big" style="color:#0d56a6"> Welcome to Busloop, we're making public transit better. </p> </div> <div id="stripes"> <div id="stripe1"></div> <div id="stripe2"></div> </div> <div id="footer" align="center"> 2011&ndash; Busloop, Inc. 1946 W 13th Avenue Vancouver, BC. </div> </body>
00-00-bl
index.html
HTML
mit
1,812
<html> <head> <title>Busloop - It's happening</title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script> <link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'> <style> body{ padding: 0; margin: 0; background-image: url(graphics/texture-1.png); font-family: 'Open Sans Condensed'; } #powerlay{ position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: -webkit-radial-gradient(circle, #fff, #0d56a6); background: -moz-radial-gradient(circle, #fff, #000); opacity: .2; -moz-opacity: .2; } #splash{ position: absolute; width: 100%; display: none; } #footer{ position: fixed; width: 100%; bottom: 35px; color: #555; font-size: .9em; } p.big{ font-size: 1.5em; } #stripes{ position: fixed; width: 100%; bottom: 0px; } #stripe1{ opacity: .8; height: 20px; background: #ffc873; } #stripe2{ opacity: .8; height: 10px; background: #ffb440; background: #ff9a00; } </style> <script> $(document).ready(function(){ $('#splash').css('top',(0.8*window.innerHeight/2-$('#splash').outerHeight()/2)+'px').fadeIn() }) </script> </head> <body> <div id="powerlay"></div> <div id="splash" align="center"> <img src="graphics/busloop.png" /> <p class="big" style="color:#0d56a6"> Unlike the B-Line, we're in Stealth Mode. </p> </div> <div id="stripes"> <div id="stripe1"></div> <div id="stripe2"></div> </div> <div id="footer" align="center"> 2011&ndash; Busloop, Inc. 1946 W 13th Avenune, Vancouver, BC. </div> </body>
00-00-bl
design-prototype.html
HTML
mit
1,753
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; namespace Control { public partial class ctrlLyDoThanhLy : DevExpress.XtraEditors.XtraUserControl { public ctrlLyDoThanhLy() { InitializeComponent(); } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlLyDoThanhLy.cs
C#
asf20
422
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using BUS; using DTO; namespace Control { public partial class ctrlLapTheDocGia : DevExpress.XtraEditors.XtraUserControl { public ctrlLapTheDocGia() { InitializeComponent(); //format date ngày sinh this.dateNgaySinh.Properties.DisplayFormat.FormatString = "dd/MM/yyyy"; this.dateNgaySinh.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgaySinh.Properties.EditFormat.FormatString = "dd/MM/yyyy"; this.dateNgaySinh.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgaySinh.Properties.Mask.EditMask = "dd/MM/yyyy"; //format date ngày lập thẻ this.dateNgayLapThe.Properties.DisplayFormat.FormatString = "dd/MM/yyyy"; this.dateNgayLapThe.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayLapThe.Properties.EditFormat.FormatString = "dd/MM/yyyy"; this.dateNgayLapThe.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayLapThe.Properties.Mask.EditMask = "dd/MM/yyyy"; //format ngày hết hạn this.dateNgayHetHan.Properties.DisplayFormat.FormatString = "dd/MM/yyyy"; this.dateNgayHetHan.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayHetHan.Properties.EditFormat.FormatString = "dd/MM/yyyy"; this.dateNgayHetHan.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayHetHan.Properties.Mask.EditMask = "dd/MM/yyyy"; //Đọc lên hạn sử dụng thẻ hanSuDung = (int)ThamSoBUS.HanSuDung().GiaTri; } #region "Biến cục bộ" int hanSuDung = 0; #endregion private void ctrlLapTheDocGia_Load(object sender, EventArgs e) { //Load ds loại độc giả lookUpLoaiDocGia.Properties.DataSource = LoaiDocGiaBUS.DocDanhSach(); //set thuộc tính displaymemeber và valuemember lookUpLoaiDocGia.Properties.DisplayMember = "TenLoaiDocGia"; lookUpLoaiDocGia.Properties.ValueMember = "MaLoaiDocGia"; //chọn phần tử đầu tiên lookUpLoaiDocGia.ItemIndex = 0; //Vừa gõ vừa tìm => mấy anh dev bảo cái này ko work T_T //lookUpLoaiDocGia.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoComplete; //lookUpLoaiDocGia.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard; //set giá trị ban đầu cho các date ngày lập thẻ và ngày hết hạn dateNgayLapThe.DateTime = DateTime.Today; //set tên nhân viên txtTenNhanVien.Text = session.tenNhanVien; //set date ngày sinh = today dateNgaySinh.DateTime = DateTime.Today; } //mỗi lần ngày lập thay đổi thì ngày hết hạn cũng thay đổi private void dateNgayLapThe_DateTimeChanged(object sender, EventArgs e) { dateNgayHetHan.DateTime = dateNgayLapThe.DateTime.AddMonths(hanSuDung); } private void LamMoi() { //đưa textbox về rỗn memoDiaChi.Text = ""; txtEmail.Text = ""; txtHoTenDocGia.Text = ""; //chọn phần tử đầu tiên cho lookup lookUpLoaiDocGia.ItemIndex = 0; //set lại ngày tháng dateNgaySinh.DateTime = DateTime.Today; dateNgayLapThe.DateTime = DateTime.Today; } private void btnDongY_Click(object sender, EventArgs e) { //kiểm tra if (KiemTra() == false) return; try { //Lấy thông tin loại độc giả từ lookup loại độc giả LoaiDocGiaDTO dtoLoaiDocGia = (LoaiDocGiaDTO)lookUpLoaiDocGia.GetSelectedDataRow(); //tạo dto độc giả DocGiaDTO dto = new DocGiaDTO { TenDocGia = txtHoTenDocGia.Text.Trim(), DiaChi = memoDiaChi.Text.Trim(), Email = txtEmail.Text.Trim(), MaNhanVien = session.maNhanVien, NgayHetHan = dateNgayHetHan.DateTime, NgayLapThe = dateNgayLapThe.DateTime, NgaySinh = dateNgaySinh.DateTime, TienNo = 0, MaloaiDocGia = dtoLoaiDocGia.MaLoaiDocGia }; //thực hiện thêm DocGiaBUS.Them(dto); //refresh LamMoi(); //show thông báo MessageBox.Show("Thêm thành công!!!"); } catch (Exception ex) { //show lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private bool KiemTra() { if (txtHoTenDocGia.Text.Trim() == "") { MessageBox.Show("Họ tên không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (memoDiaChi.Text.Trim() == "") { MessageBox.Show("Địa chỉ không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (txtEmail.Text.Trim() == "") { MessageBox.Show("Email không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlLapTheDocGia.cs
C#
asf20
6,371
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; namespace Control { public partial class ctrlQuanLyNhanVien : DevExpress.XtraEditors.XtraUserControl { public ctrlQuanLyNhanVien() { InitializeComponent(); } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlQuanLyNhanVien.cs
C#
asf20
428
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using BUS; using DTO; namespace Control { public partial class ctrlChucVu : DevExpress.XtraEditors.XtraUserControl { public ctrlChucVu() { InitializeComponent(); #region "Config thuộc tính cho gridview" //không cho phép thêm dòng this.gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép xóa dòng this.gridView1.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép chỉnh sửa trên grid this.gridView1.OptionsBehavior.Editable = false; //Thêm bộ lọc this.gridView1.OptionsFind.AlwaysVisible = true; //Không cho hiển thị menu khi bấm phím phải chuột vào header this.gridView1.OptionsMenu.EnableColumnMenu = false; //không hiển thị "Drag a column header to group by that column" this.gridView1.OptionsView.ShowGroupPanel = false; //Chọn vị trí khi thêm dòng mới (chỉ sử dụng khi edit trên grid) //this.gridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom; #endregion } #region "Properties" List<ChucVuDTO> list = null; #endregion private void ctrlChucVu_Load(object sender, EventArgs e) { //load dữ liệu vào grid gridView_LoadDuLieu(); } private void gridView_LoadDuLieu() { //Đọc dữ liệu đưa lên grid list = ChucVuBUS.DocDanhSach(); //gán datasource gridControl1.DataSource = list; //gridView1.DataSource = list;// không thực hiện được vì read only } private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e) { txtTenChucVu.Text = (string)gridView1.GetRowCellValue(e.FocusedRowHandle, gridColumnTenChucVu); } private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { //thêm dữ liệu vào cho cột số thứ tự if (e.Column == gridColumnSTT) e.DisplayText = (e.RowHandle + 1).ToString(); } private bool KiemTra() { //không cho textbox tenChucVu để trống if (txtTenChucVu.Text.Trim() == "") { MessageBox.Show("Tên bằng cấp không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } private void btnThem_Click(object sender, EventArgs e) { //kiểm tra textbox có để trống hay không, ... if (KiemTra() == false) return; try { //tạo dto ChucVuDTO dto = new ChucVuDTO { TenChucVu = txtTenChucVu.Text }; //đưa xuống bus ChucVuBUS.Them(dto, list); //Đưa dữ liệu vừa thêm vào list list.Add(dto); //load lại grid gridControl1.RefreshDataSource(); //hiển thị thông báo thành công MessageBox.Show("Thêm thành công!!!"); } catch (Exception ex) { //hiển thị thông báo lỗi nếu bị lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnXoa_Click(object sender, EventArgs e) { try { //lấy dòng đang được chọn trên grid ChucVuDTO dto = (ChucVuDTO)gridView1.GetRow(gridView1.FocusedRowHandle); //đưa xuống bus ChucVuBUS.Xoa(dto); //xóa khỏi list list.Remove(dto); //Bỏ dữ liệu vừa xóa ra khỏi grid gridControl1.RefreshDataSource(); //gridView1.DeleteRow(gridView1.FocusedRowHandle); //load lại grid //gridView_LoadDuLieu(); //hiển thị thông báo thành công MessageBox.Show("Xóa thành công!!!"); } catch (Exception ex) { //báo lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnCapNhat_Click(object sender, EventArgs e) { //kiểm tra textbox có để trống hay không, ... if (KiemTra() == false) return; try { //lấy dòng đang được chọn trên grid ChucVuDTO dtoChucVu = (ChucVuDTO)gridView1.GetRow(gridView1.FocusedRowHandle); //lấy mã dòng đang được chọn trên grid //int maChucVu = (int)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridColumnMaChucVu); //tạo dto ChucVuDTO dto = new ChucVuDTO { MaChucVu = dtoChucVu.MaChucVu, TenChucVu = txtTenChucVu.Text.Trim() }; //đưa xuống bus ChucVuBUS.CapNhat(dto, list); //nếu như cập nhật thành công thi sửa lại dòng dữ liệu trên grid //sửa lại trên list list[gridView1.FocusedRowHandle].TenChucVu = dto.TenChucVu; gridControl1.RefreshDataSource(); //gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridColumnTenChucVu, txtTenChucVu.Text.Trim()); //load lại grid //gridView_LoadDuLieu(); //hiển thị thông báo thành công MessageBox.Show("Cập nhật thành công!!!"); } catch (Exception ex) { //báo lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlChucVu.cs
C#
asf20
6,750
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; namespace Control { public partial class ctrlTinhHinhMuonSachTheoTheLoai : DevExpress.XtraEditors.XtraUserControl { public ctrlTinhHinhMuonSachTheoTheLoai() { InitializeComponent(); //format date this.dateThoiGian.Properties.DisplayFormat.FormatString = "MM/yyyy"; this.dateThoiGian.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateThoiGian.Properties.EditFormat.FormatString = "MM/yyyy"; this.dateThoiGian.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateThoiGian.Properties.Mask.EditMask = "MM/yyyy"; } private void ctrlTinhHinhMuonSachTheoTheLoai_Load(object sender, EventArgs e) { dateThoiGian.DateTime = DateTime.Today; } private void btnXemBaoCao_Click(object sender, EventArgs e) { int Thang = dateThoiGian.DateTime.Month; int Nam = dateThoiGian.DateTime.Year; rptTinhHinhMuonSachTheoTheLoai rpt = new rptTinhHinhMuonSachTheoTheLoai(); rpt.SetParameterValue("Nam", Nam); rpt.SetParameterValue("Thang", Thang); crystalReportViewer1.ReportSource = rpt; } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlTinhHinhMuonSachTheoTheLoai.cs
C#
asf20
1,540
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using DTO; using BUS; namespace Control { public partial class ctrlThanhLySach : DevExpress.XtraEditors.XtraUserControl { public ctrlThanhLySach() { InitializeComponent(); //format lại ngày tháng this.dateNgayThanhLy.Properties.DisplayFormat.FormatString = "dd/MM/yyyy"; this.dateNgayThanhLy.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayThanhLy.Properties.EditFormat.FormatString = "dd/MM/yyyy"; this.dateNgayThanhLy.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayThanhLy.Properties.Mask.EditMask = "dd/MM/yyyy"; //setting grid //không cho phép thêm dòng this.gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép xóa dòng this.gridView1.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép chỉnh sửa trên grid this.gridView1.OptionsBehavior.Editable = false; //Thêm bộ lọc //this.gridView1.OptionsFind.AlwaysVisible = true; //Không cho hiển thị menu khi bấm phím phải chuột vào header this.gridView1.OptionsMenu.EnableColumnMenu = false; //không hiển thị "Drag a column header to group by that column" this.gridView1.OptionsView.ShowGroupPanel = false; } #region "Biến toàn cục" List<ChiTietPhieuThanhLyDTO> listSachThanhLy = new List<ChiTietPhieuThanhLyDTO>(); #endregion private void ctrlThanhLySach_Load(object sender, EventArgs e) { //ngày thanh lý dateNgayThanhLy.DateTime = DateTime.Today; //tên nhân viên txtTenNhanVien.Text = session.tenNhanVien; //load ds sách lookUpTenSach.Properties.DataSource = SachBUS.DocDanhSach(3); lookUpTenSach.Properties.DisplayMember = "TenSach"; lookUpTenSach.Properties.ValueMember = "MaSach"; //load ds sách repositoryItemLookUpEdit2 repositoryItemLookUpEdit2.Properties.DataSource = SachBUS.DocDanhSach(3); repositoryItemLookUpEdit2.Properties.DisplayMember = "TenSach"; repositoryItemLookUpEdit2.Properties.ValueMember = "MaSach"; //load tình trạng lookUpTinhTrangSach.Properties.DataSource = TinhTrangBUS.DocDanhSach(); lookUpTinhTrangSach.Properties.DisplayMember = "TenTinhTrang"; lookUpTinhTrangSach.Properties.ValueMember = "MaTinhTrang"; //load lý do lookUpLyDoThanhLy.Properties.DataSource = LyDoThanhLyBUS.DocDanhSach(); lookUpLyDoThanhLy.Properties.DisplayMember = "TenLyDo"; lookUpLyDoThanhLy.Properties.ValueMember = "MaLyDo"; //load lý do repositoryItemLookUpEdit1 repositoryItemLookUpEdit1.Properties.DataSource = LyDoThanhLyBUS.DocDanhSach(); repositoryItemLookUpEdit1.Properties.DisplayMember = "TenLyDo"; repositoryItemLookUpEdit1.Properties.ValueMember = "MaLyDo"; //gán datasource cho grid gridControl1.DataSource = listSachThanhLy; } private void lookUpTenSach_EditValueChanged(object sender, EventArgs e) { try { //lấy datarow SachDTO dto = (SachDTO)lookUpTenSach.GetSelectedDataRow(); //set value cho tình trạng lookUpTinhTrangSach.EditValue = dto.MaTinhTrang; } catch { } } private void btnThemVaoDanhSach_Click(object sender, EventArgs e) { try { //lấy sách SachDTO dtoSach = (SachDTO)lookUpTenSach.GetSelectedDataRow(); //lấy lý do LyDoThanhLyDTO dtoLyDo = (LyDoThanhLyDTO)lookUpLyDoThanhLy.GetSelectedDataRow(); //không chọn 1 trong 2 if (dtoSach == null || dtoLyDo == null) return; //tạo dto chi tiết ChiTietPhieuThanhLyDTO dtoChiTiet = new ChiTietPhieuThanhLyDTO { MaChiTietPhieuThanhLy = 0, MaPhieuThanhLy = 0, MaLyDo = dtoLyDo.MaLyDo, MaSach = dtoSach.MaSach }; //nếu sách đã được thêm foreach (ChiTietPhieuThanhLyDTO ct in listSachThanhLy) if (ct.MaSach == dtoChiTiet.MaSach) return; //thêm vào danh sách chi tiết và load lại grid listSachThanhLy.Add(dtoChiTiet); gridControl1.RefreshDataSource(); } catch { } } private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { //thêm dữ liệu vào cho cột số thứ tự if (e.Column == gridColumnSTT) e.DisplayText = (e.RowHandle + 1).ToString(); } private void gridView1_KeyDown(object sender, KeyEventArgs e) { //loại 1 cuốn sách ra khỏi list if (e.KeyCode == Keys.Delete) { ChiTietPhieuThanhLyDTO dto = (ChiTietPhieuThanhLyDTO)gridView1.GetRow(gridView1.FocusedRowHandle); listSachThanhLy.Remove(dto); gridControl1.RefreshDataSource(); } } private void btnThanhLy_Click(object sender, EventArgs e) { if (KiemTra() == false) return; try { //tạo dto phiếu thanh lý PhieuThanhLyDTO dtoPhieu = new PhieuThanhLyDTO { MaNhanVien = session.maNhanVien, NgayThanhLy = dateNgayThanhLy.DateTime }; //đưa xuống csdl PhieuThanhLyBUS.Them(dtoPhieu, listSachThanhLy); //làm mới LamMoi(); //thông báo thành công MessageBox.Show("Thành công!!!"); } catch (Exception ex) { //thảy lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private bool KiemTra() { //MessageBox.Show("", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); //return false; if (listSachThanhLy.Count == 0) { MessageBox.Show("Không có sách thanh lý", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } private void LamMoi() { lookUpTenSach.Properties.DataSource = null; // lookUpTenSach.Properties.DataSource = SachBUS.DocDanhSach(3); // lookUpTenSach_EditValueChanged(null, null); // repositoryItemLookUpEdit2.DataSource = null; // repositoryItemLookUpEdit2.DataSource = SachBUS.DocDanhSach(3); // listSachThanhLy.Clear(); // gridControl1.RefreshDataSource(); } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlThanhLySach.cs
C#
asf20
8,048
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using BUS; using DTO; using System.Collections; namespace Control { public partial class ctrlTraCuu : DevExpress.XtraEditors.XtraUserControl { public ctrlTraCuu() { InitializeComponent(); //setting grid //không cho phép thêm dòng this.gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép xóa dòng this.gridView1.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép chỉnh sửa trên grid this.gridView1.OptionsBehavior.Editable = false; //Thêm bộ lọc //this.gridView1.OptionsFind.AlwaysVisible = true; //Không cho hiển thị menu khi bấm phím phải chuột vào header this.gridView1.OptionsMenu.EnableColumnMenu = false; //không hiển thị "Drag a column header to group by that column" this.gridView1.OptionsView.ShowGroupPanel = false; //format nam xuat ban this.dateNamXuatBan.Properties.DisplayFormat.FormatString = "yyyy"; this.dateNamXuatBan.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNamXuatBan.Properties.EditFormat.FormatString = "yyyy"; this.dateNamXuatBan.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNamXuatBan.Properties.Mask.EditMask = "yyyy"; } private void checkTenSach_CheckedChanged(object sender, EventArgs e) { if (checkTenSach.Checked) txtTenSach.Enabled = true; else txtTenSach.Enabled = false; } private void checkNhaXuatBan_CheckedChanged(object sender, EventArgs e) { if (checkNhaXuatBan.Checked) txtNhaXuatBan.Enabled = true; else txtNhaXuatBan.Enabled = false; } private void checkTheLoai_CheckedChanged(object sender, EventArgs e) { if (checkTheLoai.Checked) lookUpTheLoai.Enabled = true; else lookUpTheLoai.Enabled = false; } private void checkNamXuatBan_CheckedChanged(object sender, EventArgs e) { if (checkNamXuatBan.Checked) dateNamXuatBan.Enabled = true; else dateNamXuatBan.Enabled = false; } private void checkTenTacGia_CheckedChanged(object sender, EventArgs e) { if (checkTenTacGia.Checked) txtTenTacGia.Enabled = true; else txtTenTacGia.Enabled = false; } private void checkTinhTrang_CheckedChanged(object sender, EventArgs e) { if (checkTinhTrang.Checked) lookUpTinhTrang.Enabled = true; else lookUpTinhTrang.Enabled = false; } private void ctrlTraCuu_Load(object sender, EventArgs e) { //uncheck cho tất cả checkbox checkTenSach_CheckedChanged(null, null); checkNhaXuatBan_CheckedChanged(null, null); checkTheLoai_CheckedChanged(null, null); checkNamXuatBan_CheckedChanged(null, null); checkTenTacGia_CheckedChanged(null, null); checkTinhTrang_CheckedChanged(null, null); //load tình trạng lookUpTinhTrang.Properties.DataSource = TinhTrangBUS.DocDanhSach(); lookUpTinhTrang.Properties.DisplayMember = "TenTinhTrang"; lookUpTinhTrang.Properties.ValueMember = "MaTinhTrang"; //load thể loại lookUpTheLoai.Properties.DataSource = TheLoaiSachBUS.DocDanhSach(); lookUpTheLoai.Properties.DisplayMember = "TenTheLoai"; lookUpTheLoai.Properties.ValueMember = "MaTheLoai"; //load tình trạng repositoryItemLookUpEdit3 repositoryItemLookUpEdit3.DataSource = TinhTrangBUS.DocDanhSach(); repositoryItemLookUpEdit3.DisplayMember = "TenTinhTrang"; repositoryItemLookUpEdit3.ValueMember = "MaTinhTrang"; //load thể loại repositoryItemLookUpEdit2 repositoryItemLookUpEdit2.DataSource = TheLoaiSachBUS.DocDanhSach(); repositoryItemLookUpEdit2.DisplayMember = "TenTheLoai"; repositoryItemLookUpEdit2.ValueMember = "MaTheLoai"; //load sách repositoryItemLookUpEdit1 repositoryItemLookUpEdit1.DataSource = SachBUS.DocDanhSach(1); repositoryItemLookUpEdit1.DisplayMember = "TenSach"; repositoryItemLookUpEdit1.ValueMember = "MaSach"; } private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { //thêm dữ liệu vào cho cột số thứ tự if (e.Column == colSTT) e.DisplayText = (e.RowHandle + 1).ToString(); } private void btnTraCuu_Click(object sender, EventArgs e) { if (KiemTra() == false) return; //tạo đối tượng lưu thông tin tra cứu SachDTO s = new SachDTO { TenSach = "", NhaXuatBan = "", TenTacGia = "", MaTheLoai = 0, NamXuatBan = 0, MaTinhTrang = 0 }; //kiểm tra giao diện và thêm vào dữ liệu if (checkTenSach.Checked) s.TenSach = txtTenSach.Text; if (checkNhaXuatBan.Checked) s.NhaXuatBan = txtNhaXuatBan.Text; if (checkTheLoai.Checked) s.MaTheLoai = (int)lookUpTheLoai.EditValue; if (checkNamXuatBan.Checked) s.NamXuatBan = dateNamXuatBan.DateTime.Year; if (checkTenTacGia.Checked) s.TenTacGia = txtTenTacGia.Text; if (checkTinhTrang.Checked) s.MaTinhTrang = (int)lookUpTinhTrang.EditValue; //đọc dữ liệu lên grid gridControl1.DataSource = SachBUS.TraCuu(s); } private bool KiemTra() { if (checkTheLoai.Checked) if (lookUpTheLoai.ItemIndex == -1) { MessageBox.Show("Chưa chọn thể loại", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (checkTinhTrang.Checked) if (lookUpTinhTrang.ItemIndex == -1) { MessageBox.Show("Chưa chọn tình trạng", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlTraCuu.cs
C#
asf20
7,333
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using BUS; using DTO; namespace Control { public partial class ctrlGhiNhanMatSach : DevExpress.XtraEditors.XtraUserControl { public ctrlGhiNhanMatSach() { InitializeComponent(); //format lại ngày tháng this.dateNgayGhiNhan.Properties.DisplayFormat.FormatString = "dd/MM/yyyy"; this.dateNgayGhiNhan.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayGhiNhan.Properties.EditFormat.FormatString = "dd/MM/yyyy"; this.dateNgayGhiNhan.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayGhiNhan.Properties.Mask.EditMask = "dd/MM/yyyy"; //chỉ cho nhập số trên textbox tiền phạt this.txtTienPhat.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric; } private void ctrlGhiNhanMatSach_Load(object sender, EventArgs e) { //load ds độc giả lookUpMaTheDocGia.Properties.DataSource = DocGiaBUS.DocDanhSach(); lookUpMaTheDocGia.Properties.DisplayMember = "MaDocGia"; lookUpMaTheDocGia.Properties.ValueMember = "MaDocGia"; //load ds sách lookUpTenSach.Properties.DisplayMember = "TenSach"; lookUpTenSach.Properties.ValueMember = "MaSach"; //gán datetime dateNgayGhiNhan.DateTime = DateTime.Today; //đọc lên nhân viên txtTenNhanVien.Text = session.tenNhanVien; } private void lookUpMaThe_EditValueChanged(object sender, EventArgs e) { try { //Lấy thông tin từ lookup DocGiaDTO dto = (DocGiaDTO)lookUpMaTheDocGia.GetSelectedDataRow(); //gán vào text họ tên độc giả txtHoTenDocGia.Text = dto.TenDocGia; //đọc thông tin sách độc giả đang mượn lookUpTenSach.Properties.DataSource = PhieuMuonSachBUS.SachDangMuon(dto.MaDocGia); //clear textbox sách cũ txtTriGia.Text = ""; //reset tiền phạt txtTienPhat.Text = "0"; } catch { } } private void lookUpTenSach_EditValueChanged(object sender, EventArgs e) { try { //Lấy thông tin từ lookup SachDTO dto = (SachDTO)lookUpTenSach.GetSelectedDataRow(); //Đọc thông tin lên textbox txtTriGia.Text = dto.TriGia.ToString(); } catch { } } private void LamMoi() { //refresh về null lookUpTenSach.Properties.DataSource = null; //reload lookUpMaThe_EditValueChanged(null, null); } private void btnDongY_Click(object sender, EventArgs e) { if (KiemTra() == false) return; try { //Lấy thông tin độc giả từ lookup DocGiaDTO dtoDocGia = (DocGiaDTO)lookUpMaTheDocGia.GetSelectedDataRow(); dtoDocGia.TienNo = dtoDocGia.TienNo + float.Parse(txtTienPhat.Text); //cập nhật tiền nợ xuống csdl DocGiaBUS.CapNhatTienNo(dtoDocGia); //Lấy thông tin sách từ lookup SachDTO dtoSach = (SachDTO)lookUpTenSach.GetSelectedDataRow(); //cập nhật tình trạng sách SachBUS.GhiNhanMatSach(dtoSach); //thêm phiếu ghi nhận mất sách PhieuGhiNhanMatSachDTO dtoPhieu = new PhieuGhiNhanMatSachDTO { MaDocGia = dtoDocGia.MaDocGia, MaNhanVien = session.maNhanVien, MaPhieuGhiNhan = 0, MaSach = dtoSach.MaSach, NgayGhiNhan = dateNgayGhiNhan.DateTime, Tienphat = float.Parse(txtTienPhat.Text) }; //tạo phiếu xuống csdl PhieuGhiNhanMatSachBUS.Them(dtoPhieu); //refresh LamMoi(); //thành công MessageBox.Show("Ghi nhận thành công!!!"); } catch (Exception ex) { //báo lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private bool KiemTra() { //MessageBox.Show("", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); //return false; if (lookUpMaTheDocGia.ItemIndex == -1) { MessageBox.Show("Chưa chọn thẻ độc giả", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (lookUpTenSach.ItemIndex == -1) { MessageBox.Show("Không có sách được chọn", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (float.Parse(txtTienPhat.Text) == 0) { MessageBox.Show("Số tiền phạt không để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); txtTienPhat.Focus(); return false; } if (float.Parse(txtTienPhat.Text) < float.Parse(txtTriGia.Text)) { MessageBox.Show("Tiền phạt không được nhỏ hơn trị giá sách", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); txtTienPhat.Focus(); return false; } return true; } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlGhiNhanMatSach.cs
C#
asf20
6,324
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; namespace Control { public partial class ctrlQuanLyDocGia : DevExpress.XtraEditors.XtraUserControl { public ctrlQuanLyDocGia() { InitializeComponent(); } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlQuanLyDocGia.cs
C#
asf20
424
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using BUS; using DTO; namespace Control { public partial class ctrlThayDoiQuyDinh : DevExpress.XtraEditors.XtraUserControl { public ctrlThayDoiQuyDinh() { InitializeComponent(); //chỉ cho nhập số trên textbox tiền trả trễ this.txtTienPhatTraTre.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric; } private void ctrlThayDoiQuyDinh_Load(object sender, EventArgs e) { //load tham số txtTuoiToiThieu.Text = ThamSoBUS.TuoiToiThieu().GiaTri.ToString(); txtTuoiToiDa.Text = ThamSoBUS.TuoiToiDa().GiaTri.ToString(); txtHanSuDung.Text = ThamSoBUS.HanSuDung().GiaTri.ToString(); txtKhoangCachNamXuatBan.Text = ThamSoBUS.KhoangCachNamXuatBan().GiaTri.ToString(); txtSoSachMuonToiDa.Text = ThamSoBUS.SoSachMuonToiDa().GiaTri.ToString(); txtThoiGianMuonToiDa.Text = ThamSoBUS.ThoiGianMuonToiDa().GiaTri.ToString(); txtTienPhatTraTre.Text = ThamSoBUS.TienPhatTraTre().GiaTri.ToString(); } private void txtTuoiToiThieu_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar)) e.Handled = true; } private void btnDongY_Click(object sender, EventArgs e) { //kiểm tra if (KiemTra() == false) return; try { //cập nhật ThamSoBUS.CapNhat_TuoiToiThieu(float.Parse(txtTuoiToiThieu.Text)); ThamSoBUS.CapNhat_TuoiToiDa(float.Parse(txtTuoiToiDa.Text)); ThamSoBUS.CapNhat_HanSuDung(float.Parse(txtHanSuDung.Text)); ThamSoBUS.CapNhat_KhoangCachNamXuatBan(float.Parse(txtKhoangCachNamXuatBan.Text)); ThamSoBUS.CapNhat_SoSachMuonToiDa(float.Parse(txtSoSachMuonToiDa.Text)); ThamSoBUS.CapNhat_ThoiGianMuonToiDa(float.Parse(txtThoiGianMuonToiDa.Text)); ThamSoBUS.CapNhat_TienPhatTraTre(float.Parse(txtTienPhatTraTre.Text)); //show thông báo MessageBox.Show("Cập nhật thành công!!!"); } catch (Exception ex) { //show lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private bool KiemTra() { if (txtTuoiToiThieu.Text.Trim() == "") { MessageBox.Show("Tuổi tối thiếu không để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (txtTuoiToiDa.Text.Trim() == "") { MessageBox.Show("Tuổi tối đa không để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (txtHanSuDung.Text.Trim() == "") { MessageBox.Show("Hạn sử dụng không để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (txtKhoangCachNamXuatBan.Text.Trim() == "") { MessageBox.Show("Khoảng cách năm xuất bản không để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (txtSoSachMuonToiDa.Text.Trim() == "") { MessageBox.Show("Số sách mượn tối đa không để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (txtThoiGianMuonToiDa.Text.Trim() == "") { MessageBox.Show("Thời gian mượn tối đa không để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (txtTienPhatTraTre.Text == "0") { MessageBox.Show("Tiền phạt trả trễ phải khác 0", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlThayDoiQuyDinh.cs
C#
asf20
4,591
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using BUS; using DTO; namespace Control { public partial class ctrlBangCap : DevExpress.XtraEditors.XtraUserControl { public ctrlBangCap() { InitializeComponent(); #region "Config thuộc tính cho gridview" //không cho phép thêm dòng this.gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép xóa dòng this.gridView1.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép chỉnh sửa trên grid this.gridView1.OptionsBehavior.Editable = false; //Thêm bộ lọc this.gridView1.OptionsFind.AlwaysVisible = true; //Không cho hiển thị menu khi bấm phím phải chuột vào header this.gridView1.OptionsMenu.EnableColumnMenu = false; //không hiển thị "Drag a column header to group by that column" this.gridView1.OptionsView.ShowGroupPanel = false; //Chọn vị trí khi thêm dòng mới (chỉ sử dụng khi edit trên grid) //this.gridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom; #endregion } #region "Properties" List<BangCapDTO> list = null; #endregion private void ctrlBangCap_Load(object sender, EventArgs e) { //load dữ liệu vào grid gridView_LoadDuLieu(); } private void gridView_LoadDuLieu() { //Đọc dữ liệu đưa lên grid list = BangCapBUS.DocDanhSach(); //gán datasource gridControl1.DataSource = list; //gridView1.DataSource = list;// không thực hiện được vì read only } private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { //thêm dữ liệu vào cho cột số thứ tự if (e.Column == gridColumnSTT) e.DisplayText = (e.RowHandle + 1).ToString(); } //Hiển thị dữ liệu từ grid vào textbox private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e) { txtTenBangCap.Text = (string)gridView1.GetRowCellValue(e.FocusedRowHandle, gridColumnTenBangCap); } private bool KiemTra() { //không cho textbox tenbangcap để trống if (txtTenBangCap.Text.Trim() == "") { MessageBox.Show("Tên bằng cấp không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } private void btnThem_Click(object sender, EventArgs e) { //kiểm tra textbox có để trống hay không, ... if (KiemTra() == false) return; try { //tạo dto BangCapDTO dto = new BangCapDTO { TenBangCap = txtTenBangCap.Text }; //đưa xuống bus BangCapBUS.Them(dto,list); //Đưa dữ liệu vừa thêm vào list list.Add(dto); //load lại grid gridControl1.RefreshDataSource(); //hiển thị thông báo thành công MessageBox.Show("Thêm thành công!!!"); } catch (Exception ex) { //hiển thị thông báo lỗi nếu bị lỗi MessageBox.Show(ex.Message,"Lỗi!!!",MessageBoxButtons.OK,MessageBoxIcon.Error); } } private void btnXoa_Click(object sender, EventArgs e) { try { //lấy dòng đang được chọn trên grid BangCapDTO dto = (BangCapDTO)gridView1.GetRow(gridView1.FocusedRowHandle); //đưa xuống bus BangCapBUS.Xoa(dto); //xóa khỏi list list.Remove(dto); //Bỏ dữ liệu vừa xóa ra khỏi grid gridControl1.RefreshDataSource(); //gridView1.DeleteRow(gridView1.FocusedRowHandle); //load lại grid //gridView_LoadDuLieu(); //hiển thị thông báo thành công MessageBox.Show("Xóa thành công!!!"); } catch (Exception ex) { //báo lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnCapNhat_Click(object sender, EventArgs e) { //kiểm tra textbox có để trống hay không, ... if (KiemTra() == false) return; try { //lấy dòng đang được chọn trên grid BangCapDTO dtoBangCap = (BangCapDTO)gridView1.GetRow(gridView1.FocusedRowHandle); //lấy mã dòng đang được chọn trên grid //int maBangCap = (int)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridColumnMaBangCap); //tạo dto BangCapDTO dto = new BangCapDTO { MaBangCap = dtoBangCap.MaBangCap, TenBangCap = txtTenBangCap.Text.Trim() }; //đưa xuống bus BangCapBUS.CapNhat(dto, list); //nếu như cập nhật thành công thi sửa lại dòng dữ liệu trên grid //sửa lại trên list list[gridView1.FocusedRowHandle].TenBangCap = dto.TenBangCap; gridControl1.RefreshDataSource(); //gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridColumnTenBangCap, txtTenBangCap.Text.Trim()); //load lại grid //gridView_LoadDuLieu(); //hiển thị thông báo thành công MessageBox.Show("Cập nhật thành công!!!"); } catch (Exception ex) { //báo lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } //Đưa chuột ra khỏi textbox private void txtTenBangCap_Leave(object sender, EventArgs e) { //if (txtTenBangCap.Text.Trim() == "") //{ // dxErrorProvider1.SetError(this.txtTenBangCap, "Tên bằng cấp khác rỗng"); //} } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlBangCap.cs
C#
asf20
7,208
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using DTO; using BUS; namespace Control { public partial class ctrlChoMuonSach : DevExpress.XtraEditors.XtraUserControl { public ctrlChoMuonSach() { InitializeComponent(); //setting grid //không cho phép thêm dòng this.gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép xóa dòng this.gridView1.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép chỉnh sửa trên grid this.gridView1.OptionsBehavior.Editable = false; //Thêm bộ lọc //this.gridView1.OptionsFind.AlwaysVisible = true; //Không cho hiển thị menu khi bấm phím phải chuột vào header this.gridView1.OptionsMenu.EnableColumnMenu = false; //không hiển thị "Drag a column header to group by that column" this.gridView1.OptionsView.ShowGroupPanel = false; //setting lại date ngày mượn this.dateNgayMuon.Properties.DisplayFormat.FormatString = "dd/MM/yyyy"; this.dateNgayMuon.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayMuon.Properties.EditFormat.FormatString = "dd/MM/yyyy"; this.dateNgayMuon.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayMuon.Properties.Mask.EditMask = "dd/MM/yyyy"; //date ngày hết hạn this.dateNgayHetHan.Properties.DisplayFormat.FormatString = "dd/MM/yyyy"; this.dateNgayHetHan.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayHetHan.Properties.EditFormat.FormatString = "dd/MM/yyyy"; this.dateNgayHetHan.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayHetHan.Properties.Mask.EditMask = "dd/MM/yyyy"; //date hạn sử dụng this.dateHanSuDungThe.Properties.DisplayFormat.FormatString = "dd/MM/yyyy"; this.dateHanSuDungThe.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateHanSuDungThe.Properties.EditFormat.FormatString = "dd/MM/yyyy"; this.dateHanSuDungThe.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateHanSuDungThe.Properties.Mask.EditMask = "dd/MM/yyyy"; //ẩn nút chi tiết btnChiTietSachMuonQuaHan.Visible = false; btnChiTietSachDangMuon.Visible = false; //đọc lên tham số thoiGianMuonToiDa = (int)ThamSoBUS.ThoiGianMuonToiDa().GiaTri; soSachMuonToiDa = (int)ThamSoBUS.SoSachMuonToiDa().GiaTri; //ngày mượn khởi tạo là hôm nay dateNgayMuon.DateTime = DateTime.Today; } #region "Biến cục bộ" List<SachDTO> listSachMuon = new List<SachDTO>(); List<SachDTO> listSachMuonQuaHan = null; List<SachDTO> listSachDangMuon = null; int thoiGianMuonToiDa = 0; int soSachMuonToiDa = 0; #endregion private void ctrlChoMuonSach_Load(object sender, EventArgs e) { //load ds độc giả lookUpMaTheDocGia.Properties.DataSource = DocGiaBUS.DocDanhSach(); lookUpMaTheDocGia.Properties.DisplayMember = "MaDocGia"; lookUpMaTheDocGia.Properties.ValueMember = "MaDocGia"; //load ds sách lookUpTenSach.Properties.DataSource = SachBUS.DocDanhSach(2); lookUpTenSach.Properties.DisplayMember = "TenSach"; lookUpTenSach.Properties.ValueMember = "MaSach"; //load tình trạng lookUpTinhTrang.Properties.DataSource = TinhTrangBUS.DocDanhSach(); lookUpTinhTrang.Properties.DisplayMember = "TenTinhTrang"; lookUpTinhTrang.Properties.ValueMember = "MaTinhTrang"; //Load thể loại cho grid repositoryItemLookUpEdit1.DataSource = TheLoaiSachBUS.DocDanhSach(); repositoryItemLookUpEdit1.DisplayMember = "TenTheLoai"; repositoryItemLookUpEdit1.ValueMember = "MaTheLoai"; //gán datasource cho grid gridControl1.DataSource = listSachMuon; } private void lookUpMaThe_EditValueChanged(object sender, EventArgs e) { try { //Lấy thông tin từ lookup DocGiaDTO dto = (DocGiaDTO)lookUpMaTheDocGia.GetSelectedDataRow(); //gán vào text họ tên độc giả txtHoTenDocGia.Text = dto.TenDocGia; //gán ngày hết hạn dateHanSuDungThe.DateTime = dto.NgayHetHan; //public static int Compare( //DateTime t1, //DateTime t2 //) //Condition //Less than zero => t1 is earlier than t2. //Zero => t1 is the same as t2. //Greater than zero => t1 is later than t2. //đọc lên các cuốn sách độc giả đang mượn listSachDangMuon = PhieuMuonSachBUS.SachDangMuon(dto.MaDocGia); //đưa vào textbox txtSoSachDangMuon.Text = listSachDangMuon.Count.ToString(); //nếu độc giả có mượn sách thì hiện nút chi tiết sách mượn if (listSachDangMuon.Count > 0) btnChiTietSachDangMuon.Visible = true; else btnChiTietSachDangMuon.Visible = false; //đọc lên số sách mượn quá hạn listSachMuonQuaHan = PhieuMuonSachBUS.SachMuonQuaHan(dto.MaDocGia); //gán textbox txtSoSachMuonQuaHan.Text = listSachMuonQuaHan.Count.ToString(); //nếu có sách mượn quá hạn thì hiện nút chi tiết lên if (listSachMuonQuaHan.Count > 0) { btnChiTietSachMuonQuaHan.Visible = true; } else { btnChiTietSachMuonQuaHan.Visible = false; } } catch { } } //hiển thị sách mượn quá hạn private void btnChiTietSachMuonQuaHan_Click(object sender, EventArgs e) { string ds = ""; foreach (SachDTO s in listSachMuonQuaHan) { ds += s.TenSach + "\r\n"; } MessageBox.Show(ds); } //hiển thị sách đang mượn private void btnChiTietSachDangMuon_Click(object sender, EventArgs e) { string ds = ""; foreach (SachDTO s in listSachDangMuon) { ds += s.TenSach + "\r\n"; } MessageBox.Show(ds); } //đọc lên ngày hết hạn khi thay đổi ngày mượn private void dateNgayMuon_DateTimeChanged(object sender, EventArgs e) { dateNgayHetHan.DateTime = dateNgayMuon.DateTime.AddDays(thoiGianMuonToiDa); } private void lookUpTenSach_EditValueChanged(object sender, EventArgs e) { try { //lấy datarow SachDTO dto = (SachDTO)lookUpTenSach.GetSelectedDataRow(); //gán vào các textbox txtNamXuatBan.Text = dto.NamXuatBan.ToString(); txtNhaXuatBan.Text = dto.NhaXuatBan; txtTenTacGia.Text = dto.TenTacGia; lookUpTinhTrang.EditValue = dto.MaTinhTrang; } catch { } } private void btnThemVaoDanhSach_Click(object sender, EventArgs e) { try { //lấy datarow SachDTO dto = (SachDTO)lookUpTenSach.GetSelectedDataRow(); //tránh trường hợp chưa chọn sách đã bấm thêm if (dto == null) return; //nếu sách có trong list rồi thì khỏi thêm if (listSachMuon.Contains(dto)) return; //nếu sách khác tình trạng "chưa cho mượn" thì không cho vào ds if (dto.MaTinhTrang != 1) { MessageBox.Show("Không thể mượn sách này", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //đưa vào list listSachMuon.Add(dto); //Refresh source gridControl1.RefreshDataSource(); } catch { } } private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { //thêm dữ liệu vào cho cột số thứ tự if (e.Column == gridColumnSTT) e.DisplayText = (e.RowHandle + 1).ToString(); } //bấm delete trên grid sẽ bỏ dòng đang được chọn private void gridView1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete) { SachDTO dto = (SachDTO)gridView1.GetRow(gridView1.FocusedRowHandle); listSachMuon.Remove(dto); gridControl1.RefreshDataSource(); } } private void LamMoi() { //set lại ngày mượn dateNgayMuon.DateTime = DateTime.Today; //clear grid listSachMuon.Clear(); gridControl1.RefreshDataSource(); //load lại các lookUp lookUpMaThe_EditValueChanged(null, null); //đọc lại sách từ csdl lookUpTenSach.Properties.DataSource = null; // lookUpTenSach.Properties.DataSource = SachBUS.DocDanhSach(2); lookUpTenSach_EditValueChanged(null, null); } private void btnLapPhieu_Click(object sender, EventArgs e) { if (KiemTra() == false) return; try { //Lấy thông tin từ lookup DocGiaDTO docgia = (DocGiaDTO)lookUpMaTheDocGia.GetSelectedDataRow(); //Tạo phiếu mượn sách PhieuMuonSachDTO dto = new PhieuMuonSachDTO { MaDocGia = docgia.MaDocGia, NgayHetHan = dateNgayHetHan.DateTime, NgayMuon = dateNgayMuon.DateTime }; //thực hiện thêm PhieuMuonSachBUS.Them(dto,listSachMuon); //refresh LamMoi(); //thông báo thành công MessageBox.Show("Thành công!!!"); } catch (Exception ex) { //thảy lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private bool KiemTra() { //MessageBox.Show("", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); //return false; if (lookUpMaTheDocGia.ItemIndex == -1) { MessageBox.Show("Chưa chọn thẻ độc giả", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (DateTime.Compare(dateHanSuDungThe.DateTime, DateTime.Today) <= 0) { MessageBox.Show("Thẻ độc giả đã hết hạn", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (listSachMuonQuaHan.Count > 0) { MessageBox.Show("Độc giả có sách mượn quá hạn", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (listSachMuon.Count == 0) { MessageBox.Show("Không có sách trong danh sách sách mượn", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if ((listSachMuon.Count + listSachDangMuon.Count) > soSachMuonToiDa) { MessageBox.Show("Độc giả chỉ được mượn tối đa " + soSachMuonToiDa + " cuốn sách", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } //tạo errorprovider private void dateHanSuDungThe_EditValueChanged(object sender, EventArgs e) { if (DateTime.Compare(dateHanSuDungThe.DateTime, DateTime.Today) <= 0) dxErrorProvider1.SetError(dateHanSuDungThe, "Thẻ đã hết hạn"); else dxErrorProvider1.SetError(dateHanSuDungThe, ""); } private void txtSoSachMuonQuaHan_EditValueChanged(object sender, EventArgs e) { if (listSachMuonQuaHan.Count > 0) dxErrorProvider1.SetError(txtSoSachMuonQuaHan, "Có sách mượn quá hạn"); else dxErrorProvider1.SetError(txtSoSachMuonQuaHan, ""); } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlChoMuonSach.cs
C#
asf20
14,160
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Control")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SUPEZCHICKEN")] [assembly: AssemblyProduct("Control")] [assembly: AssemblyCopyright("Copyright © SUPEZCHICKEN 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("38c808d0-4ec3-4b97-8229-875ec2576fbf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/Properties/AssemblyInfo.cs
C#
asf20
1,450
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using System.Diagnostics; using CrystalDecisions.Shared; using System.Configuration; using CrystalDecisions.CrystalReports.Engine; namespace Control { public partial class ctrlDocGiaNoTienPhat : DevExpress.XtraEditors.XtraUserControl { public ctrlDocGiaNoTienPhat() { InitializeComponent(); //format date this.dateThoiGian.Properties.DisplayFormat.FormatString = "dd/MM/yyyy"; this.dateThoiGian.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateThoiGian.Properties.EditFormat.FormatString = "dd/MM/yyyy"; this.dateThoiGian.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateThoiGian.Properties.Mask.EditMask = "dd/MM/yyyy"; } private void ctrlDocGiaNoTienPhat_Load(object sender, EventArgs e) { dateThoiGian.DateTime = DateTime.Today; } private void btnXemBaoCao_Click(object sender, EventArgs e) { rptDocGiaNoTienPhat rpt = new rptDocGiaNoTienPhat(); rpt.SetParameterValue("Ngay", dateThoiGian.DateTime); crystalReportViewer1.ReportSource = rpt; } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlDocGiaNoTienPhat.cs
C#
asf20
1,493
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using BUS; using DTO; namespace Control { public partial class ctrlTiepNhanSachMoi : DevExpress.XtraEditors.XtraUserControl { public ctrlTiepNhanSachMoi() { InitializeComponent(); //format năm xuất bản this.dateNamXuatBan.Properties.DisplayFormat.FormatString = "yyyy"; this.dateNamXuatBan.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNamXuatBan.Properties.EditFormat.FormatString = "yyyy"; this.dateNamXuatBan.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNamXuatBan.Properties.Mask.EditMask = "yyyy"; //chỉ cho nhập số trên textbox trị giá this.txtTriGia.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric; //format ngày nhập this.dateNgayNhap.Properties.DisplayFormat.FormatString = "dd/MM/yyyy"; this.dateNgayNhap.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayNhap.Properties.EditFormat.FormatString = "dd/MM/yyyy"; this.dateNgayNhap.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayNhap.Properties.Mask.EditMask = "dd/MM/yyyy"; } private void ctrlTiepNhanSachMoi_Load(object sender, EventArgs e) { //set date nam xuat ban dateNamXuatBan.DateTime = DateTime.Today; //set date ngay nhap dateNgayNhap.DateTime = DateTime.Today; //load thể loại lookUpTheLoai.Properties.DataSource = TheLoaiSachBUS.DocDanhSach(); lookUpTheLoai.Properties.DisplayMember = "TenTheLoai"; lookUpTheLoai.Properties.ValueMember = "MaTheLoai"; lookUpTheLoai.ItemIndex = 0; //load tình trạng lookUpTinhTrang.Properties.DataSource = TinhTrangBUS.DocDanhSach(); lookUpTinhTrang.Properties.DisplayMember = "TenTinhTrang"; lookUpTinhTrang.Properties.ValueMember = "MaTinhTrang"; lookUpTinhTrang.ItemIndex = 0; //set nhân viên txtTenNhanVien.Text = session.tenNhanVien; } private void LamMoi() { //set textbox txtTenSach.Text = ""; txtTenTacGia.Text = ""; txtNhaXuatBan.Text = ""; txtTriGia.Text = ""; //set lookUp lookUpTheLoai.ItemIndex = 0; //set date time dateNamXuatBan.DateTime = DateTime.Today; dateNgayNhap.DateTime = DateTime.Today; } private void btnDongY_Click(object sender, EventArgs e) { if (KiemTra() == false) return; try { //Lấy thông tin thể loại và tình trạng TheLoaiSachDTO dtoTheLoai = (TheLoaiSachDTO)lookUpTheLoai.GetSelectedDataRow(); TinhTrangDTO dtoTinhTrang = (TinhTrangDTO)lookUpTinhTrang.GetSelectedDataRow(); //tạo mới một dto sách SachDTO dto = new SachDTO { MaNhanVien = session.maNhanVien, MaTheLoai = dtoTheLoai.MaTheLoai, MaTinhTrang = dtoTinhTrang.MaTinhTrang, NamXuatBan = dateNamXuatBan.DateTime.Year, NgayNhap = dateNgayNhap.DateTime, NhaXuatBan = txtNhaXuatBan.Text.Trim(), TenSach = txtTenSach.Text.Trim(), TenTacGia = txtTenTacGia.Text.Trim(), TriGia = float.Parse(txtTriGia.Text) }; //thực hiện thêm SachBUS.Them(dto); //refresh LamMoi(); //show thông báo MessageBox.Show("Thêm thành công!!!"); } catch (Exception ex) { //show lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private bool KiemTra() { if (txtTenSach.Text.Trim() == "") { MessageBox.Show("Tên sách không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (txtTenTacGia.Text.Trim() == "") { MessageBox.Show("Tác giả không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (txtNhaXuatBan.Text.Trim() == "") { MessageBox.Show("Nhà xuất bản không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (txtTriGia.Text.Trim() == "") { MessageBox.Show("Trị giá không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlTiepNhanSachMoi.cs
C#
asf20
5,647
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using BUS; using DTO; namespace Control { public partial class ctrlBoPhan : DevExpress.XtraEditors.XtraUserControl { public ctrlBoPhan() { InitializeComponent(); #region "Config thuộc tính cho gridview" //không cho phép thêm dòng this.gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép xóa dòng this.gridView1.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép chỉnh sửa trên grid this.gridView1.OptionsBehavior.Editable = false; //Thêm bộ lọc this.gridView1.OptionsFind.AlwaysVisible = true; //Không cho hiển thị menu khi bấm phím phải chuột vào header this.gridView1.OptionsMenu.EnableColumnMenu = false; //không hiển thị "Drag a column header to group by that column" this.gridView1.OptionsView.ShowGroupPanel = false; //Chọn vị trí khi thêm dòng mới (chỉ sử dụng khi edit trên grid) //this.gridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom; #endregion } #region "Properties" List<BoPhanDTO> list = null; #endregion private void ctrlBoPhan_Load(object sender, EventArgs e) { //load dữ liệu vào grid gridView_LoadDuLieu(); } private void gridView_LoadDuLieu() { //Đọc dữ liệu đưa lên grid list = BoPhanBUS.DocDanhSach(); //gán datasource gridControl1.DataSource = list; //gridView1.DataSource = list;// không thực hiện được vì read only } private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { //thêm dữ liệu vào cho cột số thứ tự if (e.Column == gridColumnSTT) e.DisplayText = (e.RowHandle + 1).ToString(); } private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e) { txtTenBoPhan.Text = (string)gridView1.GetRowCellValue(e.FocusedRowHandle, gridColumnTenBoPhan); } private bool KiemTra() { //không cho textbox tenBoPhan để trống if (txtTenBoPhan.Text.Trim() == "") { MessageBox.Show("Tên bộ phận không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } private void btnThem_Click(object sender, EventArgs e) { if (KiemTra() == false) return; try { //tạo dto BoPhanDTO dto = new BoPhanDTO { TenBoPhan = txtTenBoPhan.Text }; //đưa xuống bus BoPhanBUS.Them(dto, list); //Đưa dữ liệu vừa thêm vào list list.Add(dto); //load lại grid gridControl1.RefreshDataSource(); //hiển thị thông báo thành công MessageBox.Show("Thêm thành công!!!"); } catch (Exception ex) { //hiển thị thông báo lỗi nếu bị lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnXoa_Click(object sender, EventArgs e) { try { //lấy dòng đang được chọn trên grid BoPhanDTO dto = (BoPhanDTO)gridView1.GetRow(gridView1.FocusedRowHandle); //đưa xuống bus BoPhanBUS.Xoa(dto); //xóa khỏi list list.Remove(dto); //Bỏ dữ liệu vừa xóa ra khỏi grid gridControl1.RefreshDataSource(); //gridView1.DeleteRow(gridView1.FocusedRowHandle); //load lại grid //gridView_LoadDuLieu(); //hiển thị thông báo thành công MessageBox.Show("Xóa thành công!!!"); } catch (Exception ex) { //báo lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnCapNhat_Click(object sender, EventArgs e) { //kiểm tra textbox có để trống hay không, ... if (KiemTra() == false) return; try { //lấy dòng đang được chọn trên grid BoPhanDTO dtoBoPhan = (BoPhanDTO)gridView1.GetRow(gridView1.FocusedRowHandle); //lấy mã dòng đang được chọn trên grid //int maBoPhan = (int)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridColumnMaBoPhan); //tạo dto BoPhanDTO dto = new BoPhanDTO { MaBoPhan = dtoBoPhan.MaBoPhan, TenBoPhan = txtTenBoPhan.Text.Trim() }; //đưa xuống bus BoPhanBUS.CapNhat(dto, list); //nếu như cập nhật thành công thi sửa lại dòng dữ liệu trên grid //sửa lại trên list list[gridView1.FocusedRowHandle].TenBoPhan = dto.TenBoPhan; gridControl1.RefreshDataSource(); //gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridColumnTenBoPhan, txtTenBoPhan.Text.Trim()); //load lại grid //gridView_LoadDuLieu(); //hiển thị thông báo thành công MessageBox.Show("Cập nhật thành công!!!"); } catch (Exception ex) { //báo lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlBoPhan.cs
C#
asf20
6,669
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; namespace Control { public partial class ctrlTheLoaiSach : DevExpress.XtraEditors.XtraUserControl { public ctrlTheLoaiSach() { InitializeComponent(); } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlTheLoaiSach.cs
C#
asf20
422
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using BUS; using DTO; namespace Control { public partial class ctrlTiepNhanNhanVien : DevExpress.XtraEditors.XtraUserControl { public ctrlTiepNhanNhanVien() { InitializeComponent(); //Dùng memoedit thay cho text để dùng multiline //Dùng lookupedit thay cho comboboxedit để có thể gán datasource //setting ngày tháng this.dateNgaySinh.Properties.DisplayFormat.FormatString = "dd/MM/yyyy"; this.dateNgaySinh.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgaySinh.Properties.EditFormat.FormatString = "dd/MM/yyyy"; this.dateNgaySinh.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgaySinh.Properties.Mask.EditMask = "dd/MM/yyyy"; //lấy dữ liệu để kiểm tra mật khẩu doDaiMatKhauToiThieu = (int)ThamSoBUS.DoDaiMatKhauToiThieu().GiaTri; doDaiMatKhauToiDa = (int)ThamSoBUS.DoDaiMatKhauToiDa().GiaTri; } #region "Biến cục bộ" bool matKhauHopLe = false; bool tenTaiKhoanHopLe = false; int doDaiMatKhauToiThieu = 0; int doDaiMatKhauToiDa = 0; #endregion private void ctrlTiepNhanNhanVien_Load(object sender, EventArgs e) { //set dateNgaySinh = today dateNgaySinh.DateTime = DateTime.Today; //Load bằng cấp lookUpBangCap.Properties.DataSource = BangCapBUS.DocDanhSach(); lookUpBangCap.Properties.DisplayMember = "TenBangCap"; lookUpBangCap.Properties.ValueMember = "MaBangCap"; lookUpBangCap.ItemIndex = 0; //Load chức vụ lookUpChucVu.Properties.DataSource = ChucVuBUS.DocDanhSach(); lookUpChucVu.Properties.DisplayMember = "TenChucVu"; lookUpChucVu.Properties.ValueMember = "MaChucVu"; lookUpChucVu.ItemIndex = 0; //Load bộ phận lookUpBoPhan.Properties.DataSource = BoPhanBUS.DocDanhSach(); lookUpBoPhan.Properties.DisplayMember = "TenBoPhan"; lookUpBoPhan.Properties.ValueMember = "MaBoPhan"; lookUpBoPhan.ItemIndex = 0; } //không cho gõ chữ trong textbox số điện thoại private void txtDienThoai_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar)) e.Handled = true; //!Char.IsControl(e.KeyChar) cho phép gõ các ký tự điều khiển (các phím mũi tên,Delete,Insert,backspace,space bar) //dùng Regex //if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+")) // e.Handled = true; } //kiểm tra tên tài khoản đã sử dụng chưa private void txtTenTaiKhoan_EditValueChanged(object sender, EventArgs e) { //true : đã tồn tại //false : chưa tồn tại if (NhanVienBUS.KiemTraTaiKhoan(txtTenTaiKhoan.Text.Trim()) == true) { //không hợp lệ tenTaiKhoanHopLe = false; dxErrorProvider1.SetError(txtTenTaiKhoan, "Tên tài khoản đã tồn tại"); } else { //hợp lệ tenTaiKhoanHopLe = true; dxErrorProvider1.SetError(txtTenTaiKhoan, ""); } } //kiểm tra độ dài mật khẩu hợp lệ private void txtMatKhau_EditValueChanged(object sender, EventArgs e) { int mk = txtMatKhau.Text.Trim().Length; if (mk < doDaiMatKhauToiThieu || mk > doDaiMatKhauToiDa) { //chưa hợp lệ matKhauHopLe = false; dxErrorProvider1.SetError(txtMatKhau, "Độ dài mật khẩu phải > " + doDaiMatKhauToiThieu + " và < " + doDaiMatKhauToiDa); } else { //hợp lệ matKhauHopLe = true; dxErrorProvider1.SetError(txtMatKhau, ""); } } private void btnDongY_Click(object sender, EventArgs e) { if (KiemTra() == false) return; try { //Lấy thông tin bằng cấp BangCapDTO dtoBangCap = (BangCapDTO)lookUpBangCap.GetSelectedDataRow(); //Lấy thông tin bộ phận BoPhanDTO dtoBoPhan = (BoPhanDTO)lookUpBoPhan.GetSelectedDataRow(); //Lấy thông tin chức vụ ChucVuDTO dtoChucVu = (ChucVuDTO)lookUpChucVu.GetSelectedDataRow(); //tạo dto nhân viên NhanVienDTO dto = new NhanVienDTO { DiaChi = memoDiaChi.Text.Trim(), DienThoai = txtDienThoai.Text.Trim(), MaBangCap = dtoBangCap.MaBangCap, MaBoPhan = dtoBoPhan.MaBoPhan, MaChucVu = dtoChucVu.MaChucVu, MatKhau = txtMatKhau.Text.Trim(), NgaySinh = dateNgaySinh.DateTime, TenNhanVien = txtHoTen.Text.Trim(), TenTaiKhoan = txtTenTaiKhoan.Text.Trim(), }; //thực hiện thêm NhanVienBUS.Them(dto); //refresh lại dữ liệu LamMoi(); //show thông báo MessageBox.Show("Thêm thành công!!!"); } catch (Exception ex) { //show lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private bool KiemTra() { if (txtHoTen.Text.Trim() == "") { MessageBox.Show("Họ tên không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (memoDiaChi.Text.Trim() == "") { MessageBox.Show("Địa chỉ không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (txtDienThoai.Text.Trim() == "") { MessageBox.Show("Số điện thoại không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (txtTenTaiKhoan.Text.Trim() == "") { MessageBox.Show("Tên tài khoản không được để trống", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (tenTaiKhoanHopLe == false) { MessageBox.Show("Tên tài khoản đã tồn tại", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (matKhauHopLe == false) { MessageBox.Show("Mật khẩu không hợp lệ", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } private void LamMoi() { //set lại giá trị cho ngày sinh dateNgaySinh.DateTime = DateTime.Today; //trống các textbox txtHoTen.Text = ""; memoDiaChi.Text = ""; txtDienThoai.Text = ""; txtTenTaiKhoan.Text = ""; txtMatKhau.Text = ""; //set lại index lookUpBangCap.ItemIndex = 0; lookUpBoPhan.ItemIndex = 0; lookUpChucVu.ItemIndex = 0; } //private void txtDienThoai_TextChanged(object sender, EventArgs e) //{ // //không cho phép paste không chứa số // if (txtDienThoai.Text != "") // { // string soDienThoai = ""; // for (int i = 0; i < txtDienThoai.Text.Length; i++) // { // if (char.IsDigit(txtDienThoai.Text[i])) // { // soDienThoai = soDienThoai += txtDienThoai.Text[i]; // } // } // txtDienThoai.Text = soDienThoai; // } //} } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlTiepNhanNhanVien.cs
C#
asf20
9,009
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; namespace Control { public partial class ctrlLoaiDocGia : DevExpress.XtraEditors.XtraUserControl { public ctrlLoaiDocGia() { InitializeComponent(); } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlLoaiDocGia.cs
C#
asf20
420
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using BUS; using DTO; namespace Control { public partial class ctrlNhanTraSach : DevExpress.XtraEditors.XtraUserControl { public ctrlNhanTraSach() { InitializeComponent(); //setting grid sách mượn //không cho phép thêm dòng this.gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép xóa dòng this.gridView1.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép chỉnh sửa trên grid this.gridView1.OptionsBehavior.Editable = false; //Thêm bộ lọc //this.gridView1.OptionsFind.AlwaysVisible = true; //Không cho hiển thị menu khi bấm phím phải chuột vào header this.gridView1.OptionsMenu.EnableColumnMenu = false; //không hiển thị "Drag a column header to group by that column" this.gridView1.OptionsView.ShowGroupPanel = false; //setting grid sách trả //không cho phép thêm dòng this.gridView2.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép xóa dòng this.gridView2.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.False; //không cho phép chỉnh sửa trên grid this.gridView2.OptionsBehavior.Editable = false; //Thêm bộ lọc //this.gridView1.OptionsFind.AlwaysVisible = true; //Không cho hiển thị menu khi bấm phím phải chuột vào header this.gridView2.OptionsMenu.EnableColumnMenu = false; //không hiển thị "Drag a column header to group by that column" this.gridView2.OptionsView.ShowGroupPanel = false; //setting date ngày trả this.dateNgayTra.Properties.DisplayFormat.FormatString = "dd/MM/yyyy"; this.dateNgayTra.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayTra.Properties.EditFormat.FormatString = "dd/MM/yyyy"; this.dateNgayTra.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; this.dateNgayTra.Properties.Mask.EditMask = "dd/MM/yyyy"; } #region "Biến cục bộ" List<ChiTietPhieuTraDTO> listSachMuon = null; List<ChiTietPhieuTraDTO> listSachTra = new List<ChiTietPhieuTraDTO>(); #endregion private void ctrlNhanTraSach_Load(object sender, EventArgs e) { //load ds độc giả lookUpMaThe.Properties.DataSource = DocGiaBUS.DocDanhSach(); lookUpMaThe.Properties.DisplayMember = "MaDocGia"; lookUpMaThe.Properties.ValueMember = "MaDocGia"; //ngày trả = ngày hiện hành dateNgayTra.DateTime = DateTime.Today; //set datasource cho grid sách trả gridControl2.DataSource = listSachTra; } private void lookUpMaThe_EditValueChanged(object sender, EventArgs e) { try { //Lấy thông tin từ lookup DocGiaDTO dto = (DocGiaDTO)lookUpMaThe.GetSelectedDataRow(); //gán vào text họ tên độc giả txtHoTenDocGia.Text = dto.TenDocGia; //đọc lên sách độc giả mượn listSachMuon = PhieuTraSachBUS.SachDangMuon(dto.MaDocGia); //gán dữ liệu cho grid sách mượn gridControl1.DataSource = listSachMuon; //load lại grid gridControl1.RefreshDataSource(); //đọc tiền nợ độc giả txtTienDangNo.Text = dto.TienNo.ToString(); //load tiền phạt kì này txtTienKyNay.Text = "0"; //load tổng nợ txtTongNo.Text = (float.Parse(txtTienDangNo.Text) + float.Parse(txtTienKyNay.Text)).ToString(); //refresh lại grid sách trả listSachTra.Clear(); gridControl2.RefreshDataSource(); } catch { } } private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { //thêm dữ liệu vào cho cột số thứ tự if (e.Column == gridColumnSTTSachMuon) e.DisplayText = (e.RowHandle + 1).ToString(); } private void gridView2_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { //thêm dữ liệu vào cho cột số thứ tự if (e.Column == gridColumnSTTSachTra) e.DisplayText = (e.RowHandle + 1).ToString(); } private void btnThemVaoDanhSach_Click(object sender, EventArgs e) { //lấy từ grid sách mượn ChiTietPhieuTraDTO dto = (ChiTietPhieuTraDTO)gridView1.GetRow(gridView1.FocusedRowHandle); //không có sách thêm if (dto == null) return; //thêm vào list trả listSachTra.Add(dto); gridControl1.RefreshDataSource(); //loại khỏi list mượn listSachMuon.Remove(dto); gridControl2.RefreshDataSource(); //chỉnh lại tiền phạt kỳ này txtTienKyNay.Text = (float.Parse(txtTienKyNay.Text) + dto.TienPhat).ToString(); } private void txtTienKyNay_EditValueChanged(object sender, EventArgs e) { //load tổng nợ txtTongNo.Text = (float.Parse(txtTienDangNo.Text) + float.Parse(txtTienKyNay.Text)).ToString(); } private void btnLapPhieu_Click(object sender, EventArgs e) { if (KiemTra() == false) return; try { //lấy độc giả DocGiaDTO dtoDocGia = (DocGiaDTO)lookUpMaThe.GetSelectedDataRow(); //cập nhật lại tiền nợ độc giả dtoDocGia.TienNo = float.Parse(txtTongNo.Text); DocGiaBUS.CapNhatTienNo(dtoDocGia); //tạo mới phiếu trả PhieuTraSachDTO dtoPhieuTra = new PhieuTraSachDTO { MaDocGia = dtoDocGia.MaDocGia, NgayTraSach = dateNgayTra.DateTime, TienPhatKyNay = float.Parse(txtTienKyNay.Text) }; //thêm vào csdl PhieuTraSachBUS.Them(dtoPhieuTra, listSachTra); //refresh btnLamMoi_Click(null, null); //thành công MessageBox.Show("Thành công!!!"); } catch (Exception ex) { //báo lỗi MessageBox.Show(ex.Message, "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private bool KiemTra() { //MessageBox.Show("", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); //return false; if (lookUpMaThe.ItemIndex == -1) { MessageBox.Show("Chưa chọn thẻ độc giả", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (listSachTra.Count == 0) { MessageBox.Show("Không có sách trong danh sách trả", "Lỗi!!!", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; } private void btnLamMoi_Click(object sender, EventArgs e) { //load lại refresh lookup lookUpMaThe_EditValueChanged(null, null); //refresh lại grid sách trả //listSachTra.Clear(); //gridControl2.RefreshDataSource(); } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/ctrlNhanTraSach.cs
C#
asf20
8,565
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Reflection; namespace QuanLyThuVien { public abstract class ExcelFileWriter<T> { private Microsoft.Office.Interop.Excel.Application _excelApplication = null; private Microsoft.Office.Interop.Excel.Workbooks _workBooks = null; private Microsoft.Office.Interop.Excel._Workbook _workBook = null; private object _value = Missing.Value; private Microsoft.Office.Interop.Excel.Sheets _excelSheets = null; private Microsoft.Office.Interop.Excel._Worksheet _excelSheet = null; private Microsoft.Office.Interop.Excel.Range _excelRange = null; private Microsoft.Office.Interop.Excel.Font _excelFont = null; protected int colNumber, rowNumber; /// <summary> /// User have to set the names of header in the derived class /// </summary> public abstract object[] Headers { get;set;} /// <summary> /// user have to parse the data from the list and pass each data along with the /// column and row name to the base fun, FillExcelWithData(). /// </summary> /// <param name="list"></param> public abstract void FillRowData(List<T> list); /// <summary> /// get the data of object which will be saved to the excel sheet /// </summary> public abstract object[,] ExcelData { get;} /// <summary> /// get the no of columns /// </summary> public int ColumnCount { get { return colNumber; } } /// <summary> /// get the now of rows to fill /// </summary> public int RowCount { get { return rowNumber; } } /// <summary> /// user can override this to make the headers not be in bold. /// by default it is true /// </summary> protected virtual bool BoldHeaders { get { return true; } } /// <summary> /// api through which data from the list can be write to an excel /// kind of a Template Method Pattern is used here /// </summary> /// <param name="fileName"></param> /// <param name="holdingsList"></param> public void WriteDataToExcel(string fileName, List<T> list, string startColumnOfHeader, string endColumnOfHeader, string startColumnOfData) { this.ActivateExcel(); this.FillRowData(list); this.FillExcelWithData(startColumnOfData); this.FillHeaderColumn(Headers, startColumnOfHeader, endColumnOfHeader); ///this.Open(); //_excelApplication.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); this.SaveExcel(fileName); //Start(fileName); } /// <summary> /// activate the excel application /// </summary> /// protected virtual void ActivateExcel() { _excelApplication = new Microsoft.Office.Interop.Excel.Application(); _workBooks = (Microsoft.Office.Interop.Excel.Workbooks)_excelApplication.Workbooks; _workBook = (Microsoft.Office.Interop.Excel._Workbook)(_workBooks.Add(_value)); _excelSheets = (Microsoft.Office.Interop.Excel.Sheets)_workBook.Worksheets; _excelSheet = (Microsoft.Office.Interop.Excel._Worksheet)(_excelSheets.get_Item(1)); } /// <summary> /// fill the header columns for the range specified and make it bold if specified /// </summary> /// <param name="headers"></param> /// <param name="startColumn"></param> /// <param name="endColumn"></param> protected void FillHeaderColumn(object[] headers, string startColumn, string endColumn) { _excelRange = _excelSheet.get_Range(startColumn, endColumn); _excelRange.set_Value(_value, headers); if (BoldHeaders == true) { this.BoldRow(startColumn, endColumn); } _excelRange.EntireColumn.AutoFit(); } /// <summary> /// Fill the excel sheet with data along with the position specified /// </summary> /// <param name="columnrow"></param> /// <param name="data"></param> private void FillExcelWithData(string startColumn) { _excelRange = _excelSheet.get_Range(startColumn, _value); _excelRange = _excelRange.get_Resize(RowCount + 1, ColumnCount); _excelRange.set_Value(Missing.Value, ExcelData); _excelRange.EntireColumn.AutoFit(); } /// <summary> /// save the excel sheet to the location with file name /// </summary> /// <param name="fileName"></param> protected virtual void SaveExcel(string fileName) { _workBook.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, _value, _value, _value, _value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, _value, _value, _value, _value, null); _workBook.Close(false, _value, _value); _excelApplication.Quit(); } /// <summary> /// make the range of rows bold /// </summary> /// <param name="row1"></param> /// <param name="row2"></param> private void BoldRow(string row1, string row2) { _excelRange = _excelSheet.get_Range(row1, row2); _excelFont = _excelRange.Font; _excelFont.Bold = true; } protected virtual void Merge(int col1, int row1, int col2, int row2) { _excelRange = _excelSheet.get_Range(_excelSheet.Cells[col1, row1], _excelSheet.Cells[col1, row2]); _excelRange.Merge(true); } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/Excel/ExcelFileWriter.cs
C#
asf20
6,333
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Data; namespace QuanLyThuVien { public class ExcelWrite : ExcelFileWriter<String> { public ExcelWrite(int rowNumber, int colNumber) { this.rowNumber = rowNumber; this.colNumber = colNumber; } public ExcelWrite() { this.rowNumber = 0; this.colNumber = 0; } public object[,] myExcelData; private object[] _headers; public override object[] Headers { get { return _headers; } set { _headers = value; } } public override void FillRowData(List<String> list) { myExcelData = new object[RowCount + 1, ColumnCount]; for (int row = 0; row < RowCount; row++) { for (int col = 0; col < ColumnCount; col++) { myExcelData[row, col] = list[row * ColumnCount + col]; } } } public List<String> DGVToExcel(DataGridView dgv) { List<String> myList = new List<String>(); //doc du lieu tu datagridview bo vao excel for (int i = 0; i < dgv.RowCount; i++) { for (int j = 0; j < dgv.ColumnCount; j++) { if(dgv.Rows[i].Cells[j].Value != null) myList.Add(dgv.Rows[i].Cells[j].Value.ToString()); else myList.Add(""); } } colNumber = dgv.ColumnCount; rowNumber = dgv.RowCount; List<object> header = new List<object>(); for (int i = 0; i < dgv.ColumnCount; i++) { header.Add(dgv.Columns[i].HeaderText); } Headers = new object[header.Count]; header.CopyTo(Headers); return myList; } public override object[,] ExcelData { get { return myExcelData; } } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/Excel/ExcelWrite.cs
C#
asf20
2,348
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.OleDb; namespace QuanLyThuVien { public class ExcelRead { public static DataTable getSheet(String filePath, String sheetName) { String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + filePath + "; Extended Properties=Excel 8.0;"; OleDbConnection objConn = new OleDbConnection(sConnectionString); objConn.Open(); OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + sheetName + "$]", objConn); OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(); objAdapter1.SelectCommand = objCmdSelect; DataTable dt = new DataTable(); objAdapter1.Fill(dt); objConn.Close(); return dt; } } }
1042044-1042122-nmcnpm
trunk/Source/QuanLyThuVien/Control/Excel/ExcelRead.cs
C#
asf20
938