Merge branch '2.0' of github.com:cakephp/cakephp into 2.0

This commit is contained in:
Jeremy Harris 2010-12-05 17:57:44 -08:00
commit 8a7e2609cd
228 changed files with 9587 additions and 9335 deletions

View file

@ -36,19 +36,46 @@
Configure::write('debug', 2);
/**
* CakePHP Log Level:
* Configure the Error handler used to handle errors for your application. By default
* ErrorHandler::handleError() is used. It will display errors using Debugger, when debug > 0
* and log errors with CakeLog when debug = 0.
*
* In case of Production Mode CakePHP gives you the possibility to continue logging errors.
* Options:
*
* The following parameters can be used:
* Boolean: Set true/false to activate/deactivate logging
* Configure::write('log', true);
* - `handler` - callback - The callback to handle errors. You can set this to any callback type,
* including anonymous functions.
* - `level` - int - The level of errors you are interested in capturing.
* - `trace` - boolean - Include stack traces for errors in log files.
*
* Integer: Use built-in PHP constants to set the error level (see error_reporting)
* Configure::write('log', E_ERROR | E_WARNING);
* Configure::write('log', E_ALL ^ E_NOTICE);
* @see ErrorHandler for more information on error handling and configuration.
*/
Configure::write('log', true);
Configure::write('Error', array(
'handler' => 'ErrorHandler::handleError',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true
));
/**
* Configure the Exception handler used for uncaught exceptions. By default,
* ErrorHandler::handleException() is used. It will display a HTML page for the exception, and
* while debug > 0, framework errors like Missing Controller will be displayed. When debug = 0,
* framework errors will be coerced into generic HTTP errors.
*
* Options:
*
* - `handler` - callback - The callback to handle exceptions. You can set this to any callback type,
* including anonymous functions.
* - `renderer` - string - The class responsible for rendering uncaught exceptions. If you choose a custom class you
* should place the file for that class in app/libs. This class needs to implement a render method.
* - `log` - boolean - Should Exceptions be logged?
*
* @see ErrorHandler for more information on exception handling and configuration.
*/
Configure::write('Exception', array(
'handler' => 'ErrorHandler::handleException',
'renderer' => 'ExceptionRenderer',
'log' => true
));
/**
* Application wide charset encoding

View file

@ -35,12 +35,7 @@
* sqlite - SQLite (PHP5 only),
* postgres - PostgreSQL 7 and higher,
* mssql - Microsoft SQL Server 2000 and higher,
* db2 - IBM DB2, Cloudscape, and Apache Derby (http://php.net/ibm-db2)
* oracle - Oracle 8 and higher
* firebird - Firebird/Interbase
* sybase - Sybase ASE
* adodb-[drivername] - ADOdb interface wrapper (see below),
* odbc - ODBC DBO driver
*
* You can add custom database drivers (or override existing drivers) by adding the
* appropriate file to app/models/datasources/dbo. Drivers should be named 'dbo_x.php',
@ -49,12 +44,6 @@
* persistent => true / false
* Determines whether or not the database should use a persistent connection
*
* connect =>
* ADOdb set the connect to one of these
* (http://phplens.com/adodb/supported.databases.html) and
* append it '|p' for persistent connection. (mssql|p for example, or just mssql for not persistent)
* For all other databases, this setting is deprecated.
*
* host =>
* the host you connect to the database. To add a socket or port number, use 'port' => #
*
@ -63,11 +52,11 @@
* on a per-table basis with the Model::$tablePrefix property.
*
* schema =>
* For Postgres and DB2, specifies which schema you would like to use the tables in. Postgres defaults to
* For Postgresspecifies which schema you would like to use the tables in. Postgres defaults to
* 'public', DB2 defaults to empty.
*
* encoding =>
* For MySQL, MySQLi, Postgres and DB2, specifies the character encoding to use when connecting to the
* For MySQL, MySQLi, Postgres specifies the character encoding to use when connecting to the
* database. Uses database default.
*
*/

View file

@ -65,13 +65,8 @@
define('WWW_ROOT', dirname(__FILE__) . DS);
}
if (!defined('CORE_PATH')) {
if (function_exists('ini_set') && ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . ROOT . DS . APP_DIR . DS . PATH_SEPARATOR . ini_get('include_path'))) {
define('APP_PATH', null);
define('CORE_PATH', null);
} else {
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
@ -79,7 +74,7 @@
if (isset($_GET['url']) && $_GET['url'] === 'favicon.ico') {
return;
} else {
require CAKE . 'dispatcher.php';
require LIBS . 'dispatcher.php';
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch();
$Dispatcher->dispatch(new CakeRequest(isset($_GET['url']) ? $_GET['url'] : null));
}

View file

@ -65,13 +65,8 @@ if (!defined('WWW_ROOT')) {
define('WWW_ROOT', dirname(__FILE__) . DS);
}
if (!defined('CORE_PATH')) {
if (function_exists('ini_set') && ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . ROOT . DS . APP_DIR . DS . PATH_SEPARATOR . ini_get('include_path'))) {
define('APP_PATH', null);
define('CORE_PATH', null);
} else {
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);

View file

@ -18,7 +18,8 @@
// @license MIT License (http://www.opensource.org/licenses/mit-license.php)
// +--------------------------------------------------------------------------------------------+ //
////////////////////////////////////////////////////////////////////////////////////////////////////
1.3.5
1.3.6

View file

@ -186,11 +186,7 @@ if (!function_exists('sortByKey')) {
if (is_string($double)) {
$charset = $double;
}
if ($charset) {
return htmlspecialchars($text, ENT_QUOTES, $charset, $double);
} else {
return htmlspecialchars($text, ENT_QUOTES, $defaultCharset, $double);
}
return htmlspecialchars($text, ENT_QUOTES, ($charset) ? $charset : $defaultCharset, $double);
}
/**
@ -264,14 +260,14 @@ if (!function_exists('sortByKey')) {
* @link http://book.cakephp.org/view/1130/env
*/
function env($key) {
if ($key == 'HTTPS') {
if ($key === 'HTTPS') {
if (isset($_SERVER['HTTPS'])) {
return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
}
return (strpos(env('SCRIPT_URI'), 'https://') === 0);
}
if ($key == 'SCRIPT_NAME') {
if ($key === 'SCRIPT_NAME') {
if (env('CGI_MODE') && isset($_ENV['SCRIPT_URL'])) {
$key = 'SCRIPT_URL';
}
@ -465,18 +461,24 @@ if (!function_exists('sortByKey')) {
* Returns a translated string if one is found; Otherwise, the submitted message.
*
* @param string $singular Text to translate
* @param boolean $return Set to true to return translated string, or false to echo
* @return mixed translated string if $return is false string will be echoed
* @param mixed $args Array with arguments or multiple arguments in function
* @return mixed translated string
* @link http://book.cakephp.org/view/1121/__
*/
function __($singular) {
function __($singular, $args = null) {
if (!$singular) {
return;
}
if (!class_exists('I18n')) {
App::import('Core', 'i18n');
}
return I18n::translate($singular);
$translated = I18n::translate($singular);
if ($args === null) {
return $translated;
} elseif (!is_array($args)) {
$args = array_slice(func_get_args(), 1);
}
return vsprintf($translated, $args);
}
/**
@ -486,17 +488,23 @@ if (!function_exists('sortByKey')) {
* @param string $singular Singular text to translate
* @param string $plural Plural text
* @param integer $count Count
* @param boolean $return true to return, false to echo
* @return mixed plural form of translated string if $return is false string will be echoed
* @param mixed $args Array with arguments or multiple arguments in function
* @return mixed plural form of translated string
*/
function __n($singular, $plural, $count) {
function __n($singular, $plural, $count, $args = null) {
if (!$singular) {
return;
}
if (!class_exists('I18n')) {
App::import('Core', 'i18n');
}
return I18n::translate($singular, $plural, null, 6, $count);
$translated = I18n::translate($singular, $plural, null, 6, $count);
if ($args === null) {
return $translated;
} elseif (!is_array($args)) {
$args = array_slice(func_get_args(), 3);
}
return vsprintf($translated, $args);
}
/**
@ -504,17 +512,23 @@ if (!function_exists('sortByKey')) {
*
* @param string $domain Domain
* @param string $msg String to translate
* @param string $return true to return, false to echo
* @return translated string if $return is false string will be echoed
* @param mixed $args Array with arguments or multiple arguments in function
* @return translated string
*/
function __d($domain, $msg) {
function __d($domain, $msg, $args = null) {
if (!$msg) {
return;
}
if (!class_exists('I18n')) {
App::import('Core', 'i18n');
}
return I18n::translate($msg, null, $domain);
$translated = I18n::translate($msg, null, $domain);
if ($args === null) {
return $translated;
} elseif (!is_array($args)) {
$args = array_slice(func_get_args(), 2);
}
return vsprintf($translated, $args);
}
/**
@ -526,17 +540,23 @@ if (!function_exists('sortByKey')) {
* @param string $singular Singular string to translate
* @param string $plural Plural
* @param integer $count Count
* @param boolean $return true to return, false to echo
* @return plural form of translated string if $return is false string will be echoed
* @param mixed $args Array with arguments or multiple arguments in function
* @return plural form of translated string
*/
function __dn($domain, $singular, $plural, $count) {
function __dn($domain, $singular, $plural, $count, $args = null) {
if (!$singular) {
return;
}
if (!class_exists('I18n')) {
App::import('Core', 'i18n');
}
return I18n::translate($singular, $plural, $domain, 6, $count);
$translated = I18n::translate($singular, $plural, $domain, 6, $count);
if ($args === null) {
return $translated;
} elseif (!is_array($args)) {
$args = array_slice(func_get_args(), 4);
}
return vsprintf($translated, $args);
}
/**
@ -559,17 +579,23 @@ if (!function_exists('sortByKey')) {
* @param string $domain Domain
* @param string $msg Message to translate
* @param integer $category Category
* @param boolean $return true to return, false to echo
* @return translated string if $return is false string will be echoed
* @param mixed $args Array with arguments or multiple arguments in function
* @return translated string
*/
function __dc($domain, $msg, $category) {
function __dc($domain, $msg, $category, $args = null) {
if (!$msg) {
return;
}
if (!class_exists('I18n')) {
App::import('Core', 'i18n');
}
return I18n::translate($msg, null, $domain, $category);
$translated = I18n::translate($msg, null, $domain, $category);
if ($args === null) {
return $translated;
} elseif (!is_array($args)) {
$args = array_slice(func_get_args(), 3);
}
return vsprintf($translated, $args);
}
/**
@ -596,17 +622,23 @@ if (!function_exists('sortByKey')) {
* @param string $plural Plural
* @param integer $count Count
* @param integer $category Category
* @param boolean $return true to return, false to echo
* @return plural form of translated string if $return is false string will be echoed
* @param mixed $args Array with arguments or multiple arguments in function
* @return plural form of translated string
*/
function __dcn($domain, $singular, $plural, $count, $category) {
function __dcn($domain, $singular, $plural, $count, $category, $args = null) {
if (!$singular) {
return;
}
if (!class_exists('I18n')) {
App::import('Core', 'i18n');
}
return I18n::translate($singular, $plural, $domain, $category, $count);
$translated = I18n::translate($singular, $plural, $domain, $category, $count);
if ($args === null) {
return $translated;
} elseif (!is_array($args)) {
$args = array_slice(func_get_args(), 5);
}
return vsprintf($translated, $args);
}
/**
@ -625,17 +657,23 @@ if (!function_exists('sortByKey')) {
*
* @param string $msg String to translate
* @param integer $category Category
* @param string $return true to return, false to echo
* @return translated string if $return is false string will be echoed
* @param mixed $args Array with arguments or multiple arguments in function
* @return translated string
*/
function __c($msg, $category) {
function __c($msg, $category, $args = null) {
if (!$msg) {
return;
}
if (!class_exists('I18n')) {
App::import('Core', 'i18n');
}
return I18n::translate($msg, null, null, $category);
$translated = I18n::translate($msg, null, null, $category);
if ($args === null) {
return $translated;
} elseif (!is_array($args)) {
$args = array_slice(func_get_args(), 2);
}
return vsprintf($translated, $args);
}
/**

View file

@ -26,14 +26,14 @@ error_reporting(E_ALL & ~E_DEPRECATED);
require CORE_PATH . 'cake' . DS . 'basics.php';
require CORE_PATH . 'cake' . DS . 'config' . DS . 'paths.php';
require LIBS . 'exceptions.php';
require LIBS . 'error' . DS . 'exceptions.php';
require LIBS . 'object.php';
require LIBS . 'inflector.php';
require LIBS . 'app.php';
require LIBS . 'configure.php';
require LIBS . 'set.php';
require LIBS . 'cache.php';
require LIBS . 'error_handler.php';
set_exception_handler(array('ErrorHandler', 'handleException'));
require LIBS . 'error' . DS . 'error_handler.php';
Configure::bootstrap(isset($boot) ? $boot : true);

View file

@ -17,4 +17,4 @@
* @since CakePHP(tm) v 1.1.11.4062
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
return $config['Cake.version'] = '1.3.5';
return $config['Cake.version'] = '1.3.6';

View file

@ -23,3 +23,4 @@
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR. 'shell_dispatcher.php');
return ShellDispatcher::run($argv);

View file

@ -35,17 +35,19 @@ class ConsoleErrorHandler extends ErrorHandler {
* @var filehandle
* @access public
*/
public $stderr;
public static $stderr;
/**
* Class constructor.
* Get the stderr object for the console error handling.
*
* @param Exception $error Exception to handle.
* @param array $messages Error messages
*/
function __construct($error) {
$this->stderr = new ConsoleOutput('php://stderr');
parent::__construct($error);
public static function getStderr() {
if (empty(self::$stderr)) {
self::$stderr = new ConsoleOutput('php://stderr');
}
return self::$stderr;
}
/**
@ -53,58 +55,41 @@ class ConsoleErrorHandler extends ErrorHandler {
*
* @return void
*/
public static function handleException($exception) {
$error = new ConsoleErrorHandler($exception);
$error->render();
public static function handleException(Exception $exception) {
$stderr = self::getStderr();
$stderr->write(sprintf(
__("<error>Error:</error> %s\n%s"),
$exception->getMessage(),
$exception->getTraceAsString()
));
}
/**
* Do nothing, no controllers are needed in the console.
* Handle errors in the console environment.
*
* @return void
*/
protected function _getController($exception) {
return null;
public static function handleError($code, $description, $file = null, $line = null, $context = null) {
if (error_reporting() === 0) {
return;
}
$stderr = self::getStderr();
list($name, $log) = self::_mapErrorCode($code);
$message = __('%s in [%s, line %s]', $description, $file, $line);
$stderr->write(__("<error>%s Error:</error> %s\n", $name, $message));
if (Configure::read('debug') == 0) {
App::import('Core', 'CakeLog');
CakeLog::write($log, $message);
}
}
/**
* Overwrite how _cakeError behaves for console. There is no reason
* to prepare urls as they are not relevant for this.
* undocumented function
*
* @param $error Exception Exception being handled.
* @return void
*/
protected function _cakeError($error) {
$this->_outputMessage();
}
/**
* Override error404 method
*
* @param Exception $error Exception
* @return void
*/
public function error400($error) {
$this->_outputMessage();
}
/**
* Override error500 method
*
* @param Exception $error Exception
* @return void
*/
public function error500($error) {
$this->_outputMessage();
}
/**
* Outputs the exception to STDERR.
*
* @param string $template The name of the template to render.
* @return void
*/
public function _outputMessage($template = null) {
public function render() {
$this->stderr->write(sprintf(
__("<error>Error:</error> %s\n%s"),
$this->error->getMessage(),

View file

@ -51,9 +51,9 @@ class ConsoleInputArgument {
}
/**
* Get the name of the argument
* Get the value of the name attribute.
*
* @return string
* @return string Value of this->_name.
*/
public function name() {
return $this->_name;
@ -75,7 +75,7 @@ class ConsoleInputArgument {
$optional = __(' <comment>(optional)</comment>');
}
if (!empty($this->_choices)) {
$optional .= sprintf(__(' <comment>(choices: %s)</comment>'), implode('|', $this->_choices));
$optional .= __(' <comment>(choices: %s)</comment>', implode('|', $this->_choices));
}
return sprintf('%s%s%s', $name, $this->_help, $optional);
}
@ -141,4 +141,4 @@ class ConsoleInputArgument {
}
return $parent;
}
}
}

View file

@ -56,14 +56,23 @@ class ConsoleInputOption {
}
/**
* Get the name of the argument
* Get the value of the name attribute.
*
* @return string
* @return string Value of this->_name.
*/
public function name() {
return $this->_name;
}
/**
* Get the value of the short attribute.
*
* @return string Value of this->_short.
*/
public function short() {
return $this->_short;
}
/**
* Generate the help for this this option.
*
@ -73,10 +82,10 @@ class ConsoleInputOption {
public function help($width = 0) {
$default = $short = '';
if (!empty($this->_default) && $this->_default !== true) {
$default = sprintf(__(' <comment>(default: %s)</comment>'), $this->_default);
$default = __(' <comment>(default: %s)</comment>', $this->_default);
}
if (!empty($this->_choices)) {
$default .= sprintf(__(' <comment>(choices: %s)</comment>'), implode('|', $this->_choices));
$default .= __(' <comment>(choices: %s)</comment>', implode('|', $this->_choices));
}
if (!empty($this->_short)) {
$short = ', -' . $this->_short;

View file

@ -27,9 +27,7 @@
*/
class ConsoleInputSubcommand {
protected $_name;
protected $_help;
protected $_parser;
protected $_name, $_help, $_parser;
/**
* Make a new Subcommand
@ -56,9 +54,9 @@ class ConsoleInputSubcommand {
}
/**
* Get the name of the subcommand
* Get the value of the name attribute.
*
* @return string
* @return string Value of this->_name.
*/
public function name() {
return $this->_name;

View file

@ -265,18 +265,24 @@ class ConsoleOptionParser {
* @return returns $this.
*/
public function addOption($name, $params = array()) {
$defaults = array(
'name' => $name,
'short' => null,
'help' => '',
'default' => null,
'boolean' => false,
'choices' => array()
);
$options = array_merge($defaults, $params);
$this->_options[$name] = new ConsoleInputOption($options);
if (!empty($options['short'])) {
$this->_shortOptions[$options['short']] = $name;
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, $params);
$option = new ConsoleInputOption($options);
}
$this->_options[$name] = $option;
if ($option->short() !== null) {
$this->_shortOptions[$option->short()] = $name;
}
return $this;
}
@ -299,18 +305,23 @@ class ConsoleOptionParser {
* @return $this.
*/
public function addArgument($name, $params = array()) {
$defaults = array(
'name' => $name,
'help' => '',
'index' => count($this->_args),
'required' => false,
'choices' => array()
);
$options = array_merge($defaults, $params);
$index = $options['index'];
unset($options['index']);
$this->_args[$index] = new ConsoleInputArgument($options);
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;
}
@ -361,13 +372,19 @@ class ConsoleOptionParser {
* @return $this.
*/
public function addSubcommand($name, $params = array()) {
$defaults = array(
'name' => $name,
'help' => '',
'parser' => null
);
$options = array_merge($defaults, $params);
$this->_subcommands[$name] = new ConsoleInputSubcommand($options);
if (is_object($name) && $name instanceof ConsoleInputSubcommand) {
$command = $name;
$name = $command->name();
} else {
$defaults = array(
'name' => $name,
'help' => '',
'parser' => null
);
$options = array_merge($defaults, $params);
$command = new ConsoleInputSubcommand($options);
}
$this->_subcommands[$name] = $command;
return $this;
}
@ -441,7 +458,7 @@ class ConsoleOptionParser {
foreach ($this->_args as $i => $arg) {
if ($arg->isRequired() && !isset($args[$i]) && empty($params['help'])) {
throw new RuntimeException(
sprintf(__('Missing required arguments. %s is required.'), $arg->name())
__('Missing required arguments. %s is required.', $arg->name())
);
}
}
@ -535,7 +552,7 @@ class ConsoleOptionParser {
*/
protected function _parseOption($name, $params) {
if (!isset($this->_options[$name])) {
throw new InvalidArgumentException(sprintf(__('Unknown option `%s`'), $name));
throw new InvalidArgumentException(__('Unknown option `%s`', $name));
}
$option = $this->_options[$name];
$isBoolean = $option->isBoolean();

View file

@ -17,6 +17,8 @@
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'String', false);
/**
* HelpFormatter formats help for console shells. Can format to either
* text or XML formats. Uses ConsoleOptionParser methods to generate help.

View file

@ -80,8 +80,6 @@ class ShellDispatcher {
*/
function __initConstants() {
if (function_exists('ini_set')) {
ini_set('display_errors', '1');
ini_set('error_reporting', E_ALL & ~E_DEPRECATED);
ini_set('html_errors', false);
ini_set('implicit_flush', true);
ini_set('max_execution_time', 0);
@ -90,14 +88,9 @@ class ShellDispatcher {
if (!defined('CAKE_CORE_INCLUDE_PATH')) {
define('DS', DIRECTORY_SEPARATOR);
define('CAKE_CORE_INCLUDE_PATH', dirname(dirname(dirname(__FILE__))));
define('DISABLE_DEFAULT_ERROR_HANDLING', false);
define('CAKEPHP_SHELL', true);
if (!defined('CORE_PATH')) {
if (function_exists('ini_set') && ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . ini_get('include_path'))) {
define('CORE_PATH', null);
} else {
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
}
}
@ -141,13 +134,15 @@ class ShellDispatcher {
$boot = file_exists(ROOT . DS . APP_DIR . DS . 'config' . DS . 'bootstrap.php');
require CORE_PATH . 'cake' . DS . 'bootstrap.php';
require_once CONSOLE_LIBS . 'console_error_handler.php';
set_exception_handler(array('ConsoleErrorHandler', 'handleException'));
if (!file_exists(APP_PATH . 'config' . DS . 'core.php')) {
include_once CAKE_CORE_INCLUDE_PATH . DS . 'cake' . DS . 'console' . DS . 'templates' . DS . 'skel' . DS . 'config' . DS . 'core.php';
App::build();
}
require_once CONSOLE_LIBS . 'console_error_handler.php';
set_exception_handler(array('ConsoleErrorHandler', 'handleException'));
set_error_handler(array('ConsoleErrorHandler', 'handleError'), Configure::read('Error.level'));
if (!defined('FULL_BASE_URL')) {
define('FULL_BASE_URL', '/');
}

View file

@ -78,7 +78,7 @@ class AclShell extends Shell {
$out .= __('your core config to reflect your decision to use') . "\n";
$out .= __('DbAcl before attempting to use this script') . ".\n";
$out .= "--------------------------------------------------\n";
$out .= sprintf(__('Current ACL Classname: %s'), Configure::read('Acl.classname')) . "\n";
$out .= __('Current ACL Classname: %s', Configure::read('Acl.classname')) . "\n";
$out .= "--------------------------------------------------\n";
$this->err($out);
$this->_stop();
@ -94,7 +94,7 @@ class AclShell extends Shell {
if (!in_array($this->command, array('initdb'))) {
$collection = new ComponentCollection();
$this->Acl =& new AclComponent($collection);
$this->Acl = new AclComponent($collection);
$controller = null;
$this->Acl->startup($controller);
}
@ -135,9 +135,9 @@ class AclShell extends Shell {
$data['parent_id'] = $parent;
$this->Acl->{$class}->create();
if ($this->Acl->{$class}->save($data)) {
$this->out(sprintf(__("<success>New %s</success> '%s' created."), $class, $this->args[2]), 2);
$this->out(__("<success>New %s</success> '%s' created.", $class, $this->args[2]), 2);
} else {
$this->err(sprintf(__("There was a problem creating a new %s '%s'."), $class, $this->args[2]));
$this->err(__("There was a problem creating a new %s '%s'.", $class, $this->args[2]));
}
}
@ -152,9 +152,9 @@ class AclShell extends Shell {
$nodeId = $this->_getNodeId($class, $identifier);
if (!$this->Acl->{$class}->delete($nodeId)) {
$this->error(__('Node Not Deleted') . sprintf(__('There was an error deleting the %s. Check that the node exists'), $class) . ".\n");
$this->error(__('Node Not Deleted') . __('There was an error deleting the %s. Check that the node exists', $class) . ".\n");
}
$this->out(sprintf(__('<success>%s deleted.</success>'), $class), 2);
$this->out(__('<success>%s deleted.</success>', $class), 2);
}
/**
@ -176,7 +176,7 @@ class AclShell extends Shell {
if (!$this->Acl->{$class}->save($data)) {
$this->out(__('Error in setting new parent. Please make sure the parent node exists, and is not a descendant of the node specified.'), true);
} else {
$this->out(sprintf(__('Node parent set to %s'), $this->args[2]) . "\n", true);
$this->out(__('Node parent set to %s', $this->args[2]) . "\n", true);
}
}
@ -193,7 +193,7 @@ class AclShell extends Shell {
if (empty($nodes)) {
$this->error(
sprintf(__("Supplied Node '%s' not found"), $this->args[1]),
__("Supplied Node '%s' not found", $this->args[1]),
__('No tree returned.')
);
}
@ -230,9 +230,9 @@ class AclShell extends Shell {
extract($this->__getParams());
if ($this->Acl->check($aro, $aco, $action)) {
$this->out(sprintf(__('%s is <success>allowed</success>.'), $aroName), true);
$this->out(__('%s is <success>allowed</success>.', $aroName), true);
} else {
$this->out(sprintf(__('%s is <error>not allowed</error>.'), $aroName), true);
$this->out(__('%s is <error>not allowed</error>.', $aroName), true);
}
}
@ -305,9 +305,9 @@ class AclShell extends Shell {
if (empty($nodes)) {
if (isset($this->args[1])) {
$this->error(sprintf(__('%s not found'), $this->args[1]), __('No tree returned.'));
$this->error(__('%s not found', $this->args[1]), __('No tree returned.'));
} elseif (isset($this->args[0])) {
$this->error(sprintf(__('%s not found'), $this->args[0]), __('No tree returned.'));
$this->error(__('%s not found', $this->args[0]), __('No tree returned.'));
}
}
$this->out($class . " tree:");
@ -522,7 +522,7 @@ class AclShell extends Shell {
$conditions = array($class . '.' . $key => $this->args[1]);
$possibility = $this->Acl->{$class}->find('all', compact('conditions'));
if (empty($possibility)) {
$this->error(sprintf(__('%s not found'), $this->args[1]), __('No tree returned.'));
$this->error(__('%s not found', $this->args[1]), __('No tree returned.'));
}
return $possibility;
}
@ -558,7 +558,7 @@ class AclShell extends Shell {
if (is_array($identifier)) {
$identifier = var_export($identifier, true);
}
$this->error(sprintf(__('Could not find node using reference "%s"'), $identifier));
$this->error(__('Could not find node using reference "%s"', $identifier));
}
return Set::extract($node, "0.{$class}.id");
}

View file

@ -87,7 +87,7 @@ class ApiShell extends Shell {
}
} else {
$this->error(sprintf(__('%s not found'), $class));
$this->error(__('%s not found', $class));
}
$parsed = $this->__parseClass($path . $file .'.php', $class);
@ -95,7 +95,7 @@ class ApiShell extends Shell {
if (!empty($parsed)) {
if (isset($this->params['method'])) {
if (!isset($parsed[$this->params['method']])) {
$this->err(sprintf(__('%s::%s() could not be found'), $class, $this->params['method']));
$this->err(__('%s::%s() could not be found', $class, $this->params['method']));
$this->_stop();
}
$method = $parsed[$this->params['method']];
@ -200,7 +200,7 @@ class ApiShell extends Shell {
$parsed = array();
if (!include_once($path)) {
$this->err(sprintf(__('%s could not be found'), $path));
$this->err(__('%s could not be found', $path));
}
$reflection = new ReflectionClass($class);

View file

@ -0,0 +1,33 @@
<?php
/**
* AppShell file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.console.shells
* @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/shells/app_shell.php
*
* Add your application-wide methods in the class below, your shells
* will inherit them.
*
* @package cake
* @subpackage cake.cake.console.libs
*/
class AppShell extends Shell {
}

View file

@ -40,7 +40,14 @@ class BakeShell extends Shell {
public $tasks = array('Project', 'DbConfig', 'Model', 'Controller', 'View', 'Plugin', 'Fixture', 'Test');
/**
* Override loadTasks() to handle paths
* The connection being used.
*
* @var string
*/
public $connection = 'default';
/**
* Assign $this->connection to the active task if a connection param is set.
*
*/
public function startup() {
@ -121,7 +128,6 @@ class BakeShell extends Shell {
*
*/
public function all() {
$this->hr();
$this->out('Bake All');
$this->hr();
@ -156,7 +162,6 @@ class BakeShell extends Shell {
$modelBaked = $this->Model->bake($object, false);
if ($modelBaked && $modelExists === false) {
$this->out(sprintf(__('%s Model was baked.'), $model));
if ($this->_checkUnitTest()) {
$this->Model->bakeFixture($model);
$this->Model->bakeTest($model);
@ -167,7 +172,6 @@ class BakeShell extends Shell {
if ($modelExists === true) {
$controller = $this->_controllerName($name);
if ($this->Controller->bake($controller, $this->Controller->bakeActions($controller))) {
$this->out(sprintf(__('%s Controller was baked.'), $name));
if ($this->_checkUnitTest()) {
$this->Controller->bakeTest($controller);
}
@ -175,9 +179,9 @@ class BakeShell extends Shell {
if (App::import('Controller', $controller)) {
$this->View->args = array($controller);
$this->View->execute();
$this->out(sprintf(__('%s Views were baked.'), $name));
}
$this->out(__('Bake All complete'));
$this->out('', 1, Shell::QUIET);
$this->out(__('<success>Bake All complete</success>'), 1, Shell::QUIET);
array_shift($this->args);
} else {
$this->error(__('Bake All could not continue without a valid model'));

View file

@ -111,7 +111,7 @@ class CommandListShell extends Shell {
continue;
}
foreach ($shells as $shell) {
if ($shell !== 'shell.php') {
if ($shell !== 'shell.php' && $shell !== 'app_shell.php') {
$shell = str_replace('.php', '', $shell);
$shellList[$shell][$type] = $type;
}

View file

@ -61,7 +61,7 @@ class ConsoleShell extends Shell {
foreach ($this->models as $model) {
$class = Inflector::camelize(str_replace('.php', '', $model));
$this->models[$model] = $class;
$this->{$class} =& new $class();
$this->{$class} = new $class();
}
$this->out('Model classes:');
$this->out('--------------');
@ -290,7 +290,7 @@ class ConsoleShell extends Shell {
}
break;
case (preg_match("/^routes\s+reload/i", $command, $tmp) == true):
$router =& Router::getInstance();
$router = Router::getInstance();
if (!$this->_loadRoutes()) {
$this->out("There was an error loading the routes config. Please check that the file");
$this->out("exists and is free of parse errors.");
@ -299,7 +299,7 @@ class ConsoleShell extends Shell {
$this->out("Routes configuration reloaded, " . count($router->routes) . " routes connected");
break;
case (preg_match("/^routes\s+show/i", $command, $tmp) == true):
$router =& Router::getInstance();
$router = Router::getInstance();
$this->out(implode("\n", Set::extract($router->routes, '{n}.0')));
break;
case (preg_match("/^route\s+(\(.*\))$/i", $command, $tmp) == true):
@ -335,7 +335,7 @@ class ConsoleShell extends Shell {
* @return boolean True if config reload was a success, otherwise false
*/
protected function _loadRoutes() {
$router =& Router::getInstance();
$router = Router::getInstance();
$router->reload();
extract($router->getNamedExpressions());

View file

@ -99,7 +99,7 @@ class SchemaShell extends Shell {
$name = $plugin;
}
}
$this->Schema =& new CakeSchema(compact('name', 'path', 'file', 'connection', 'plugin'));
$this->Schema = new CakeSchema(compact('name', 'path', 'file', 'connection', 'plugin'));
}
/**
@ -114,7 +114,7 @@ class SchemaShell extends Shell {
$this->_stop();
} else {
$file = $this->Schema->path . DS . $this->params['file'];
$this->err(sprintf(__('Schema file (%s) could not be found.'), $file));
$this->err(__('Schema file (%s) could not be found.', $file));
$this->_stop();
}
}
@ -151,7 +151,7 @@ class SchemaShell extends Shell {
$content['file'] = $this->params['file'];
if ($snapshot === true) {
$Folder =& new Folder($this->Schema->path);
$Folder = new Folder($this->Schema->path);
$result = $Folder->read();
$numToUse = false;
@ -179,7 +179,7 @@ class SchemaShell extends Shell {
}
if ($this->Schema->write($content)) {
$this->out(sprintf(__('Schema file: %s generated'), $content['file']));
$this->out(__('Schema file: %s generated', $content['file']));
$this->_stop();
} else {
$this->err(__('Schema file: %s generated'));
@ -209,7 +209,7 @@ class SchemaShell extends Shell {
$write = $this->params['write'];
}
}
$db =& ConnectionManager::getDataSource($this->Schema->connection);
$db = ConnectionManager::getDataSource($this->Schema->connection);
$contents = "#" . $Schema->name . " sql generated on: " . date('Y-m-d H:i:s') . " : " . time() . "\n\n";
$contents .= $db->dropSchema($Schema) . "\n\n". $db->createSchema($Schema);
@ -218,13 +218,13 @@ class SchemaShell extends Shell {
$write .= '.sql';
}
if (strpos($write, DS) !== false) {
$File =& new File($write, true);
$File = new File($write, true);
} else {
$File =& new File($this->Schema->path . DS . $write, true);
$File = new File($this->Schema->path . DS . $write, true);
}
if ($File->write($contents)) {
$this->out(sprintf(__('SQL dump file created in %s'), $File->pwd()));
$this->out(__('SQL dump file created in %s', $File->pwd()));
$this->_stop();
} else {
$this->err(__('SQL dump could not be created'));
@ -280,10 +280,10 @@ class SchemaShell extends Shell {
$options['file'] = $fileName . '_' . $this->params['snapshot'] . '.php';
}
$Schema =& $this->Schema->load($options);
$Schema = $this->Schema->load($options);
if (!$Schema) {
$this->err(sprintf(__('%s could not be loaded'), $this->Schema->path . DS . $this->Schema->file));
$this->err(__('%s could not be loaded', $this->Schema->path . DS . $this->Schema->file));
$this->_stop();
}
$table = null;
@ -299,8 +299,8 @@ class SchemaShell extends Shell {
*
* @access private
*/
function __create(&$Schema, $table = null) {
$db =& ConnectionManager::getDataSource($this->Schema->connection);
function __create($Schema, $table = null) {
$db = ConnectionManager::getDataSource($this->Schema->connection);
$drop = $create = array();
@ -343,7 +343,7 @@ class SchemaShell extends Shell {
* @access private
*/
function __update(&$Schema, $table = null) {
$db =& ConnectionManager::getDataSource($this->Schema->connection);
$db = ConnectionManager::getDataSource($this->Schema->connection);
$this->out(__('Comparing Database to Schema...'));
$options = array();
@ -390,14 +390,14 @@ class SchemaShell extends Shell {
return;
}
Configure::write('debug', 2);
$db =& ConnectionManager::getDataSource($this->Schema->connection);
$db = ConnectionManager::getDataSource($this->Schema->connection);
foreach ($contents as $table => $sql) {
if (empty($sql)) {
$this->out(sprintf(__('%s is up to date.'), $table));
$this->out(__('%s is up to date.', $table));
} else {
if ($this->__dry === true) {
$this->out(sprintf(__('Dry run for %s :'), $table));
$this->out(__('Dry run for %s :', $table));
$this->out($sql);
} else {
if (!$Schema->before(array($event => $table))) {
@ -413,7 +413,7 @@ class SchemaShell extends Shell {
if (!empty($error)) {
$this->out($error);
} else {
$this->out(sprintf(__('%s updated.'), $table));
$this->out(__('%s updated.', $table));
}
}
}

View file

@ -164,6 +164,14 @@ class Shell extends Object {
if ($this->stdin == null) {
$this->stdin = new ConsoleInput('php://stdin');
}
$parent = get_parent_class($this);
if ($this->tasks !== null && $this->tasks !== false) {
$this->_mergeVars(array('tasks'), $parent, true);
}
if ($this->uses !== null && $this->uses !== false) {
$this->_mergeVars(array('uses'), $parent, false);
}
}
/**
@ -550,7 +558,7 @@ class Shell extends Object {
* @param string $message An optional error message
*/
public function error($title, $message = null) {
$this->err(sprintf(__('<error>Error:</error> %s'), $title));
$this->err(__('<error>Error:</error> %s', $title));
if (!empty($message)) {
$this->err($message);
@ -586,18 +594,18 @@ class Shell extends Object {
$this->out();
if (is_file($path) && $this->interactive === true) {
$this->out(sprintf(__('<warning>File `%s` exists</warning>'), $path));
$this->out(__('<warning>File `%s` exists</warning>', $path));
$key = $this->in(__('Do you want to overwrite?'), array('y', 'n', 'q'), 'n');
if (strtolower($key) == 'q') {
$this->out(__('<error>Quitting</error>.'), 2);
$this->_stop();
} elseif (strtolower($key) != 'y') {
$this->out(sprintf(__('Skip `%s`'), $path), 2);
$this->out(__('Skip `%s`', $path), 2);
return false;
}
} else {
$this->out(sprintf(__('Creating file %s'), $path));
$this->out(__('Creating file %s', $path));
}
if (!class_exists('File')) {
@ -607,10 +615,10 @@ class Shell extends Object {
if ($File = new File($path, true)) {
$data = $File->prepare($contents);
$File->write($data);
$this->out(sprintf(__('<success>Wrote</success> `%s`'), $path));
$this->out(__('<success>Wrote</success> `%s`', $path));
return true;
} else {
$this->err(sprintf(__('<error>Could not write to `%s`</error>.'), $path), 2);
$this->err(__('<error>Could not write to `%s`</error>.', $path), 2);
return false;
}
}

View file

@ -79,7 +79,7 @@ class ControllerTask extends BakeTask {
if (!empty($this->params['admin'])) {
$admin = $this->Project->getPrefix();
if ($admin) {
$this->out(sprintf(__('Adding %s methods'), $admin));
$this->out(__('Adding %s methods', $admin));
$actions .= "\n" . $this->bakeActions($controller, $admin);
}
}
@ -125,7 +125,7 @@ class ControllerTask extends BakeTask {
protected function _interactive() {
$this->interactive = true;
$this->hr();
$this->out(sprintf(__("Bake Controller\nPath: %s"), $this->path));
$this->out(__("Bake Controller\nPath: %s", $this->path));
$this->hr();
if (empty($this->connection)) {
@ -134,7 +134,7 @@ class ControllerTask extends BakeTask {
$controllerName = $this->getName();
$this->hr();
$this->out(sprintf(__('Baking %sController'), $controllerName));
$this->out(__('Baking %sController', $controllerName));
$this->hr();
$helpers = $components = array();
@ -148,7 +148,7 @@ class ControllerTask extends BakeTask {
$question[] = __("Would you like to build your controller interactively?");
if (file_exists($this->path . $controllerFile .'_controller.php')) {
$question[] = sprintf(__("Warning: Choosing no will overwrite the %sController."), $controllerName);
$question[] = __("Warning: Choosing no will overwrite the %sController.", $controllerName);
}
$doItInteractive = $this->in(implode("\n", $question), array('y','n'), 'y');
@ -213,7 +213,7 @@ class ControllerTask extends BakeTask {
$this->hr();
$this->out(__('The following controller will be created:'));
$this->hr();
$this->out(sprintf(__("Controller Name:\n\t%s"), $controllerName));
$this->out(__("Controller Name:\n\t%s", $controllerName));
if (strtolower($useDynamicScaffold) == 'y') {
$this->out("var \$scaffold;");
@ -278,7 +278,7 @@ class ControllerTask extends BakeTask {
$this->_stop();
}
$modelObj =& ClassRegistry::init($currentModelName);
$modelObj = ClassRegistry::init($currentModelName);
$controllerPath = $this->_controllerPath($controllerName);
$pluralName = $this->_pluralName($currentModelName);
$singularName = Inflector::variable($currentModelName);
@ -302,6 +302,8 @@ class ControllerTask extends BakeTask {
* @return string Baked controller
*/
public function bake($controllerName, $actions = '', $helpers = null, $components = null) {
$this->out("\nBaking controller class for $controllerName...", 1, Shell::QUIET);
$isScaffold = ($actions === 'scaffold') ? true : false;
$this->Template->set('plugin', Inflector::camelize($this->plugin));

View file

@ -106,7 +106,7 @@ class DbConfigTask extends Shell {
}
}
$driver = $this->in('Driver:', array('db2', 'firebird', 'mssql', 'mysql', 'mysqli', 'odbc', 'oracle', 'postgres', 'sqlite', 'sybase'), 'mysql');
$driver = $this->in('Driver:', array('db2', 'firebird', 'mssql', 'mysql', 'odbc', 'oracle', 'postgres', 'sqlite', 'sybase'), 'mysql');
$persistent = $this->in('Persistent Connection?', array('y', 'n'), 'n');
if (strtolower($persistent) == 'n') {

View file

@ -114,7 +114,7 @@ class ExtractTask extends Shell {
$this->__paths = explode(',', $this->params['paths']);
} else {
$defaultPath = APP_PATH;
$message = sprintf(__("What is the full path you would like to extract?\nExample: %s\n[Q]uit [D]one"), $this->Dispatch->params['root'] . DS . 'myapp');
$message = __("What is the full path you would like to extract?\nExample: %s\n[Q]uit [D]one", $this->Dispatch->params['root'] . DS . 'myapp');
while (true) {
$response = $this->in($message, null, $defaultPath);
if (strtoupper($response) === 'Q') {
@ -136,7 +136,7 @@ class ExtractTask extends Shell {
if (isset($this->params['output'])) {
$this->__output = $this->params['output'];
} else {
$message = sprintf(__("What is the full path you would like to output?\nExample: %s\n[Q]uit"), $this->__paths[0] . DS . 'locale');
$message = __("What is the full path you would like to output?\nExample: %s\n[Q]uit", $this->__paths[0] . DS . 'locale');
while (true) {
$response = $this->in($message, null, $this->__paths[0] . DS . 'locale');
if (strtoupper($response) === 'Q') {
@ -156,7 +156,7 @@ class ExtractTask extends Shell {
$this->__merge = !(strtolower($this->params['merge']) === 'no');
} else {
$this->out();
$response = $this->in(sprintf(__('Would you like to merge all domains strings into the default.pot file?')), array('y', 'n'), 'n');
$response = $this->in(__('Would you like to merge all domains strings into the default.pot file?'), array('y', 'n'), 'n');
$this->__merge = strtolower($response) === 'y';
}
@ -250,7 +250,7 @@ class ExtractTask extends Shell {
function __extractTokens() {
foreach ($this->__files as $file) {
$this->__file = $file;
$this->out(sprintf(__('Processing %s...'), $file));
$this->out(__('Processing %s...', $file));
$code = file_get_contents($file);
$allTokens = token_get_all($code);
@ -413,11 +413,11 @@ class ExtractTask extends Shell {
$response = '';
while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') {
$this->out();
$response = $this->in(sprintf(__('Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll'), $filename), array('y', 'n', 'a'), 'y');
$response = $this->in(__('Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll', $filename), array('y', 'n', 'a'), 'y');
if (strtoupper($response) === 'N') {
$response = '';
while ($response == '') {
$response = $this->in(sprintf(__("What would you like to name this file?\nExample: %s"), 'new_' . $filename), null, 'new_' . $filename);
$response = $this->in(__("What would you like to name this file?\nExample: %s", 'new_' . $filename), null, 'new_' . $filename);
$File = new File($this->__output . $response);
$filename = $response;
}
@ -485,7 +485,7 @@ class ExtractTask extends Shell {
* @access private
*/
function __markerError($file, $line, $marker, $count) {
$this->out(sprintf(__("Invalid marker content in %s:%s\n* %s("), $file, $line, $marker), true);
$this->out(__("Invalid marker content in %s:%s\n* %s(", $file, $line, $marker), true);
$count += 2;
$tokenCount = count($this->__tokens);
$parenthesis = 1;

View file

@ -166,7 +166,7 @@ class FixtureTask extends BakeTask {
$options['records'] = true;
}
if ($doRecords == 'n') {
$prompt = sprintf(__("Would you like to build this fixture with data from %s's table?"), $modelName);
$prompt = __("Would you like to build this fixture with data from %s's table?", $modelName);
$fromTable = $this->in($prompt, array('y', 'n'), 'n');
if (strtolower($fromTable) == 'y') {
$options['fromTable'] = true;
@ -254,7 +254,7 @@ class FixtureTask extends BakeTask {
$this->Template->set($vars);
$content = $this->Template->generate('classes', 'fixture');
$this->out("\nBaking test fixture for $model...");
$this->out("\nBaking test fixture for $model...", 1, Shell::QUIET);
$this->createFile($path . $filename, $content);
return $content;
}
@ -394,12 +394,12 @@ class FixtureTask extends BakeTask {
$condition = 'WHERE 1=1 LIMIT ' . (isset($this->params['count']) ? $this->params['count'] : 10);
}
App::import('Model', 'Model', false);
$modelObject =& new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
$modelObject = new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
$records = $modelObject->find('all', array(
'conditions' => $condition,
'recursive' => -1
));
$db =& ConnectionManager::getDataSource($modelObject->useDbConfig);
$db = ConnectionManager::getDataSource($modelObject->useDbConfig);
$schema = $modelObject->schema(true);
$out = array();
foreach ($records as $record) {

View file

@ -112,7 +112,7 @@ class ModelTask extends BakeTask {
continue;
}
$modelClass = Inflector::classify($table);
$this->out(sprintf(__('Baking %s'), $modelClass));
$this->out(__('Baking %s', $modelClass));
$object = $this->_getModelObject($modelClass);
if ($this->bake($object, false) && $unitTestExists) {
$this->bakeFixture($modelClass);
@ -131,7 +131,7 @@ class ModelTask extends BakeTask {
if (!$table) {
$table = Inflector::tableize($className);
}
$object =& new Model(array('name' => $className, 'table' => $table, 'ds' => $this->connection));
$object = new Model(array('name' => $className, 'table' => $table, 'ds' => $this->connection));
return $object;
}
@ -180,7 +180,7 @@ class ModelTask extends BakeTask {
}
$currentModelName = $this->getName();
$useTable = $this->getTable($currentModelName);
$db =& ConnectionManager::getDataSource($this->connection);
$db = ConnectionManager::getDataSource($this->connection);
$fullTableName = $db->fullTableName($useTable);
if (in_array($useTable, $this->_tables)) {
@ -190,7 +190,7 @@ class ModelTask extends BakeTask {
$primaryKey = $this->findPrimaryKey($fields);
}
} else {
$this->err(sprintf(__('Table %s does not exist, cannot bake a model without a table.'), $useTable));
$this->err(__('Table %s does not exist, cannot bake a model without a table.', $useTable));
$this->_stop();
return false;
}
@ -218,16 +218,16 @@ class ModelTask extends BakeTask {
$this->out("Name: " . $currentModelName);
if ($this->connection !== 'default') {
$this->out(sprintf(__("DB Config: %s"), $this->connection));
$this->out(__("DB Config: %s", $this->connection));
}
if ($fullTableName !== Inflector::tableize($currentModelName)) {
$this->out(sprintf(__('DB Table: %s'), $fullTableName));
$this->out(__('DB Table: %s', $fullTableName));
}
if ($primaryKey != 'id') {
$this->out(sprintf(__('Primary Key: %s'), $primaryKey));
$this->out(__('Primary Key: %s', $primaryKey));
}
if (!empty($validate)) {
$this->out(sprintf(__('Validation: %s'), print_r($validate, true)));
$this->out(__('Validation: %s', print_r($validate, true)));
}
if (!empty($associations)) {
$this->out(__('Associations:'));
@ -367,8 +367,8 @@ class ModelTask extends BakeTask {
while ($anotherValidator == 'y') {
if ($this->interactive) {
$this->out();
$this->out(sprintf(__('Field: %s'), $fieldName));
$this->out(sprintf(__('Type: %s'), $metaData['type']));
$this->out(__('Field: %s', $fieldName));
$this->out(__('Type: %s', $metaData['type']));
$this->hr();
$this->out(__('Please select one of the following validation options:'));
$this->hr();
@ -378,7 +378,7 @@ class ModelTask extends BakeTask {
for ($i = 1; $i < $defaultChoice; $i++) {
$prompt .= $i . ' - ' . $this->_validations[$i] . "\n";
}
$prompt .= sprintf(__("%s - Do not do any validation on this field.\n"), $defaultChoice);
$prompt .= __("%s - Do not do any validation on this field.\n", $defaultChoice);
$prompt .= __("... or enter in a valid regex validation string.\n");
$methods = array_flip($this->_validations);
@ -646,7 +646,7 @@ class ModelTask extends BakeTask {
$this->hr();
$alias = $this->in(__('What is the alias for this association?'));
$className = $this->in(sprintf(__('What className will %s use?'), $alias), null, $alias );
$className = $this->in(__('What className will %s use?', $alias), null, $alias );
$suggestedForeignKey = null;
if ($assocType == 0) {
@ -742,7 +742,7 @@ class ModelTask extends BakeTask {
$path = $this->getPath();
$filename = $path . Inflector::underscore($name) . '.php';
$this->out("\nBaking model class for $name...");
$this->out("\nBaking model class for $name...", 1, Shell::QUIET);
$this->createFile($filename, $out);
ClassRegistry::flush();
return $out;
@ -793,14 +793,14 @@ class ModelTask extends BakeTask {
}
App::import('Model', 'ConnectionManager', false);
$db =& ConnectionManager::getDataSource($useDbConfig);
$db = ConnectionManager::getDataSource($useDbConfig);
$useTable = Inflector::tableize($modelName);
$fullTableName = $db->fullTableName($useTable, false);
$tableIsGood = false;
if (array_search($useTable, $this->_tables) === false) {
$this->out();
$this->out(sprintf(__("Given your model named '%s',\nCake would expect a database table named '%s'"), $modelName, $fullTableName));
$this->out(__("Given your model named '%s',\nCake would expect a database table named '%s'", $modelName, $fullTableName));
$tableIsGood = $this->in(__('Do you want to use this table?'), array('y','n'), 'y');
}
if (strtolower($tableIsGood) == 'n') {
@ -823,7 +823,7 @@ class ModelTask extends BakeTask {
App::import('Model', 'ConnectionManager', false);
$tables = array();
$db =& ConnectionManager::getDataSource($useDbConfig);
$db = ConnectionManager::getDataSource($useDbConfig);
$db->cacheSources = false;
$usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
if ($usePrefix) {

View file

@ -56,8 +56,8 @@ class PluginTask extends Shell {
$plugin = Inflector::camelize($this->args[0]);
$pluginPath = $this->_pluginPath($plugin);
if (is_dir($pluginPath)) {
$this->out(sprintf(__('Plugin: %s'), $plugin));
$this->out(sprintf(__('Path: %s'), $pluginPath));
$this->out(__('Plugin: %s', $plugin));
$this->out(__('Path: %s', $pluginPath));
} else {
$this->_interactive($plugin);
}
@ -78,7 +78,7 @@ class PluginTask extends Shell {
}
if (!$this->bake($plugin)) {
$this->error(sprintf(__("An error occured trying to bake: %s in %s"), $plugin, $this->path . Inflector::underscore($pluginPath)));
$this->error(__("An error occured trying to bake: %s in %s", $plugin, $this->path . Inflector::underscore($pluginPath)));
}
}
@ -97,14 +97,14 @@ class PluginTask extends Shell {
$this->findPath($pathOptions);
}
$this->hr();
$this->out(sprintf(__("<info>Plugin Name:</info> %s"), $plugin));
$this->out(sprintf(__("<info>Plugin Directory:</info> %s"), $this->path . $pluginPath));
$this->out(__("<info>Plugin Name:</info> %s", $plugin));
$this->out(__("<info>Plugin Directory:</info> %s", $this->path . $pluginPath));
$this->hr();
$looksGood = $this->in(__('Look okay?'), array('y', 'n', 'q'), 'y');
if (strtolower($looksGood) == 'y') {
$Folder =& new Folder($this->path . $pluginPath);
$Folder = new Folder($this->path . $pluginPath);
$directories = array(
'config' . DS . 'schema',
'models' . DS . 'behaviors',
@ -127,7 +127,7 @@ class PluginTask extends Shell {
foreach ($directories as $directory) {
$dirPath = $this->path . $pluginPath . DS . $directory;
$Folder->create($dirPath);
$File =& new File($dirPath . DS . 'empty', true);
$File = new File($dirPath . DS . 'empty', true);
}
foreach ($Folder->messages() as $message) {
@ -156,7 +156,7 @@ class PluginTask extends Shell {
$this->createFile($this->path . $pluginPath . DS . $modelFileName, $out);
$this->hr();
$this->out(sprintf(__('<success>Created:</success> %s in %s'), $plugin, $this->path . $pluginPath), 2);
$this->out(__('<success>Created:</success> %s in %s', $plugin, $this->path . $pluginPath), 2);
}
return true;

View file

@ -68,7 +68,7 @@ class ProjectTask extends Shell {
if ($project) {
$response = false;
while ($response == false && is_dir($project) === true && file_exists($project . 'config' . 'core.php')) {
$prompt = sprintf(__('<warning>A project already exists in this location:</warning> %s Overwrite?'), $project);
$prompt = __('<warning>A project already exists in this location:</warning> %s Overwrite?', $project);
$response = $this->in($prompt, array('y','n'), 'n');
if (strtolower($response) === 'n') {
$response = $project = false;
@ -89,23 +89,23 @@ class ProjectTask extends Shell {
if ($this->securitySalt($path) === true) {
$this->out(__(' * Random hash key created for \'Security.salt\''));
} else {
$this->err(sprintf(__('Unable to generate random hash for \'Security.salt\', you should change it in %s'), CONFIGS . 'core.php'));
$this->err(__('Unable to generate random hash for \'Security.salt\', you should change it in %s', CONFIGS . 'core.php'));
$success = false;
}
if ($this->securityCipherSeed($path) === true) {
$this->out(__(' * Random seed created for \'Security.cipherSeed\''));
} else {
$this->err(sprintf(__('Unable to generate random seed for \'Security.cipherSeed\', you should change it in %s'), CONFIGS . 'core.php'));
$this->err(__('Unable to generate random seed for \'Security.cipherSeed\', you should change it in %s', CONFIGS . 'core.php'));
$success = false;
}
if ($this->corePath($path) === true) {
$this->out(sprintf(__(' * CAKE_CORE_INCLUDE_PATH set to %s in webroot/index.php'), CAKE_CORE_INCLUDE_PATH));
$this->out(sprintf(__(' * CAKE_CORE_INCLUDE_PATH set to %s in webroot/test.php'), CAKE_CORE_INCLUDE_PATH));
$this->out(__(' * CAKE_CORE_INCLUDE_PATH set to %s in webroot/index.php', CAKE_CORE_INCLUDE_PATH));
$this->out(__(' * CAKE_CORE_INCLUDE_PATH set to %s in webroot/test.php', CAKE_CORE_INCLUDE_PATH));
$this->out(__(' * <warning>Remember to check these value after moving to production server</warning>'));
} else {
$this->err(sprintf(__('Unable to set CAKE_CORE_INCLUDE_PATH, you should change it in %s'), $path . 'webroot' .DS .'index.php'));
$this->err(__('Unable to set CAKE_CORE_INCLUDE_PATH, you should change it in %s', $path . 'webroot' .DS .'index.php'));
$success = false;
}
if ($this->consolePath($path) === true) {
@ -117,8 +117,8 @@ class ProjectTask extends Shell {
$Folder = new Folder($path);
if (!$Folder->chmod($path . 'tmp', 0777)) {
$this->err(sprintf(__('Could not set permissions on %s'), $path . DS .'tmp'));
$this->out(sprintf(__('chmod -R 0777 %s'), $path . DS .'tmp'));
$this->err(__('Could not set permissions on %s', $path . DS .'tmp'));
$this->out(__('chmod -R 0777 %s', $path . DS .'tmp'));
$success = false;
}
if ($success) {
@ -146,7 +146,7 @@ class ProjectTask extends Shell {
$skel = $this->params['skel'];
}
while (!$skel) {
$skel = $this->in(sprintf(__("What is the path to the directory layout you wish to copy?\nExample: %s"), APP, null, ROOT . DS . 'myapp' . DS));
$skel = $this->in(__("What is the path to the directory layout you wish to copy?\nExample: %s", APP, null, ROOT . DS . 'myapp' . DS));
if ($skel == '') {
$this->err(__('The directory path you supplied was empty. Please try again.'));
} else {
@ -172,10 +172,10 @@ class ProjectTask extends Shell {
if ($Folder->copy(array('to' => $path, 'skip' => $skip))) {
$this->hr();
$this->out(sprintf(__('<success>Created:</success> %s in %s'), $app, $path));
$this->out(__('<success>Created:</success> %s in %s', $app, $path));
$this->hr();
} else {
$this->err(sprintf(__("<error>Could not create</error> '%s' properly."), $app));
$this->err(__("<error>Could not create</error> '%s' properly.", $app));
return false;
}

View file

@ -59,7 +59,7 @@ class TemplateTask extends Shell {
$separator = DS === '/' ? '/' : '\\\\';
$core = preg_replace('#shells' . $separator . '$#', '', $core);
$paths[] = $core;
$Folder =& new Folder($core . 'templates' . DS . 'default');
$Folder = new Folder($core . 'templates' . DS . 'default');
$contents = $Folder->read();
$themeFolders = $contents[0];
@ -76,14 +76,14 @@ class TemplateTask extends Shell {
$themes = array();
foreach ($paths as $path) {
$Folder =& new Folder($path . 'templates', false);
$Folder = new Folder($path . 'templates', false);
$contents = $Folder->read();
$subDirs = $contents[0];
foreach ($subDirs as $dir) {
if (empty($dir) || preg_match('@^skel$|_skel$@', $dir)) {
continue;
}
$Folder =& new Folder($path . 'templates' . DS . $dir);
$Folder = new Folder($path . 'templates' . DS . $dir);
$contents = $Folder->read();
$subDirs = $contents[0];
if (array_intersect($contents[0], $themeFolders)) {
@ -206,7 +206,7 @@ class TemplateTask extends Shell {
return $templatePath;
}
}
$this->err(sprintf(__('Could not find template for %s'), $filename));
$this->err(__('Could not find template for %s', $filename));
return false;
}
}

View file

@ -19,6 +19,7 @@
*/
include_once dirname(__FILE__) . DS . 'bake.php';
App::import('Model', 'ClassRegistry');
/**
* Task class for creating and updating test files.
@ -91,13 +92,13 @@ class TestTask extends BakeTask {
$this->interactive = true;
$this->hr();
$this->out(__('Bake Tests'));
$this->out(sprintf(__('Path: %s'), $this->path));
$this->out(__('Path: %s', $this->path));
$this->hr();
if ($type) {
$type = Inflector::camelize($type);
if (!in_array($type, $this->classTypes)) {
$this->error(sprintf('Incorrect type provided. Please choose one of %s', implode(', ', $this->classTypes)));
$this->error(__('Incorrect type provided. Please choose one of %s', implode(', ', $this->classTypes)));
}
} else {
$type = $this->getObjectType();
@ -114,8 +115,8 @@ class TestTask extends BakeTask {
*/
public function bake($type, $className) {
if ($this->typeCanDetectFixtures($type) && $this->isLoadableClass($type, $className)) {
$this->out(__('Bake is detecting possible fixtures..'));
$testSubject =& $this->buildTestSubject($type, $className);
$this->out(__('Bake is detecting possible fixtures...'));
$testSubject = $this->buildTestSubject($type, $className);
$this->generateFixtureList($testSubject);
} elseif ($this->interactive) {
$this->getUserFixtures();
@ -133,6 +134,7 @@ class TestTask extends BakeTask {
if ($this->plugin) {
$plugin = $this->plugin . '.';
}
$this->out("\nBaking test case for $className $type...", 1, Shell::QUIET);
$this->Template->set('fixtures', $this->_fixtures);
$this->Template->set('plugin', $plugin);
@ -178,7 +180,7 @@ class TestTask extends BakeTask {
*/
public function getClassName($objectType) {
$options = App::objects(strtolower($objectType));
$this->out(sprintf(__('Choose a %s class'), $objectType));
$this->out(__('Choose a %s class', $objectType));
$keys = array();
foreach ($options as $key => $option) {
$this->out(++$key . '. ' . $option);
@ -228,9 +230,9 @@ class TestTask extends BakeTask {
App::import($type, $class);
$class = $this->getRealClassName($type, $class);
if (strtolower($type) == 'model') {
$instance =& ClassRegistry::init($class);
$instance = ClassRegistry::init($class);
} else {
$instance =& new $class();
$instance = new $class();
}
return $instance;
}

View file

@ -221,7 +221,7 @@ class ViewTask extends BakeTask {
$this->controllerPath = strtolower(Inflector::underscore($this->controllerName));
$prompt = sprintf(__("Would you like bake to build your views interactively?\nWarning: Choosing no will overwrite %s views if it exist."), $this->controllerName);
$prompt = __("Would you like bake to build your views interactively?\nWarning: Choosing no will overwrite %s views if it exist.", $this->controllerName);
$interactive = $this->in($prompt, array('y', 'n'), 'n');
if (strtolower($interactive) == 'n') {
@ -278,15 +278,15 @@ class ViewTask extends BakeTask {
if (!App::import('Controller', $import)) {
$file = $this->controllerPath . '_controller.php';
$this->err(sprintf(__("The file '%s' could not be found.\nIn order to bake a view, you'll need to first create the controller."), $file));
$this->err(__("The file '%s' could not be found.\nIn order to bake a view, you'll need to first create the controller.", $file));
$this->_stop();
}
$controllerClassName = $this->controllerName . 'Controller';
$controllerObj =& new $controllerClassName();
$controllerObj = new $controllerClassName();
$controllerObj->plugin = $this->plugin;
$controllerObj->constructClasses();
$modelClass = $controllerObj->modelClass;
$modelObj =& $controllerObj->{$controllerObj->modelClass};
$modelObj = $controllerObj->{$controllerObj->modelClass};
if ($modelObj) {
$primaryKey = $modelObj->primaryKey;
@ -339,9 +339,9 @@ class ViewTask extends BakeTask {
$this->hr();
$this->out(__('The following view will be created:'));
$this->hr();
$this->out(sprintf(__('Controller Name: %s'), $this->controllerName));
$this->out(sprintf(__('Action Name: %s'), $action));
$this->out(sprintf(__('Path: %s'), $this->params['app'] . DS . $this->controllerPath . DS . Inflector::underscore($action) . ".ctp"));
$this->out(__('Controller Name: %s', $this->controllerName));
$this->out(__('Action Name: %s', $action));
$this->out(__('Path: %s', $this->params['app'] . DS . $this->controllerPath . DS . Inflector::underscore($action) . ".ctp"));
$this->hr();
$looksGood = $this->in(__('Look okay?'), array('y','n'), 'y');
if (strtolower($looksGood) == 'y') {
@ -366,6 +366,7 @@ class ViewTask extends BakeTask {
if (empty($content)) {
return false;
}
$this->out("\nBaking `$action` view file...", 1, Shell::QUIET);
$path = $this->getPath();
$filename = $path . $this->controllerPath . DS . Inflector::underscore($action) . '.ctp';
return $this->createFile($filename, $content);

View file

@ -56,7 +56,7 @@ class TestSuiteShell extends Shell {
))->addOption('log-dbus', array(
'help' => __('Log test execution to DBUS.'),
'default' => false
))->addOption('--coverage-html', array(
))->addOption('coverage-html', array(
'help' => __('<dir> Generate code coverage report in HTML format.'),
'default' => false
))->addOption('coverage-clover', array(
@ -253,6 +253,10 @@ class TestSuiteShell extends Shell {
*/
protected function run($runnerArgs, $options = array()) {
require_once CAKE . 'tests' . DS . 'lib' . DS . 'test_runner.php';
restore_error_handler();
restore_error_handler();
$testCli = new TestRunner($runnerArgs);
$testCli->run($options);
}
@ -280,8 +284,7 @@ class TestSuiteShell extends Shell {
if (empty($testCases)) {
$this->out(__("No test cases available \n\n"));
$this->help();
$this->_stop();
return $this->out($this->OptionParser->help());
}
$this->out($title);

View file

@ -77,7 +77,7 @@
$this->Session->setFlash(__('Invalid <?php echo strtolower($singularHumanName); ?>'));
$this->redirect(array('action' => 'index'));
<?php else: ?>
$this->flash(sprintf(__('Invalid <?php echo strtolower($singularHumanName); ?>')), array('action' => 'index'));
$this->flash(__('Invalid <?php echo strtolower($singularHumanName); ?>'), array('action' => 'index'));
<?php endif; ?>
}
if ($this->request->is('post')) {
@ -123,7 +123,7 @@
$this->Session->setFlash(__('Invalid id for <?php echo strtolower($singularHumanName); ?>'));
$this->redirect(array('action'=>'index'));
<?php else: ?>
$this->flash(sprintf(__('Invalid <?php echo strtolower($singularHumanName); ?>')), array('action' => 'index'));
$this->flash(__('Invalid <?php echo strtolower($singularHumanName); ?>'), array('action' => 'index'));
<?php endif; ?>
}
if ($this-><?php echo $currentModelName; ?>->delete($id)) {

View file

@ -39,7 +39,7 @@ class <?php echo $fullClassName; ?>TestCase extends CakeTestCase {
<?php endif; ?>
public function startTest() {
$this-><?php echo $className . ' =& ' . $construction; ?>
$this-><?php echo $className . ' = ' . $construction; ?>
}
public function endTest() {

View file

@ -47,7 +47,7 @@
<ul>
<?php if (strpos($action, 'add') === false): ?>
<li><?php echo "<?php echo \$this->Form->postLink(__('Delete'), array('action' => 'delete', \$this->Form->value('{$modelClass}.{$primaryKey}')), null, sprintf(__('Are you sure you want to delete # %s?'), \$this->Form->value('{$modelClass}.{$primaryKey}'))); ?>";?></li>
<li><?php echo "<?php echo \$this->Form->postLink(__('Delete'), array('action' => 'delete', \$this->Form->value('{$modelClass}.{$primaryKey}')), null, __('Are you sure you want to delete # %s?', \$this->Form->value('{$modelClass}.{$primaryKey}'))); ?>";?></li>
<?php endif;?>
<li><?php echo "<?php echo \$this->Html->link(__('List " . $pluralHumanName . "'), array('action' => 'index'));?>";?></li>
<?php

View file

@ -24,7 +24,7 @@ endif;
\$settings = Cache::settings();
if (!empty(\$settings)):
echo '<span class=\"notice success\">';
printf(__('The %s is being used for caching. To change the config edit APP/config/core.php '), '<em>'. \$settings['engine'] . 'Engine</em>');
echo __('The %s is being used for caching. To change the config edit APP/config/core.php ', '<em>'. \$settings['engine'] . 'Engine</em>');
echo '</span>';
else:
echo '<span class=\"notice\">';
@ -75,9 +75,9 @@ $output .= "<?php endif;?>\n";
$output .= "<h3><?php echo __('Editing this Page') ?></h3>\n";
$output .= "<p>\n";
$output .= "<?php\n";
$output .= "\tprintf(__('To change the content of this page, edit: %s\n";
$output .= "\techo __('To change the content of this page, edit: %s\n";
$output .= "\t\tTo change its layout, edit: %s\n";
$output .= "\t\tYou can also add some CSS styles for your pages at: %s'),\n";
$output .= "\t\tYou can also add some CSS styles for your pages at: %s',\n";
$output .= "\t\tAPP . 'views' . DS . 'pages' . DS . 'home.ctp.<br />', APP . 'views' . DS . 'layouts' . DS . 'default.ctp.<br />', APP . 'webroot' . DS . 'css');\n";
$output .= "?>\n";
$output .= "</p>\n";

View file

@ -55,7 +55,7 @@
echo "\t\t<td class=\"actions\">\n";
echo "\t\t\t<?php echo \$this->Html->link(__('View'), array('action' => 'view', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?>\n";
echo "\t\t\t<?php echo \$this->Html->link(__('Edit'), array('action' => 'edit', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?>\n";
echo "\t\t\t<?php echo \$this->Form->postLink(__('Delete'), array('action' => 'delete', \${$singularVar}['{$modelClass}']['{$primaryKey}']), null, sprintf(__('Are you sure you want to delete # %s?'), \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?>\n";
echo "\t\t\t<?php echo \$this->Form->postLink(__('Delete'), array('action' => 'delete', \${$singularVar}['{$modelClass}']['{$primaryKey}']), null, __('Are you sure you want to delete # %s?', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?>\n";
echo "\t\t</td>\n";
echo "\t</tr>\n";

View file

@ -46,7 +46,7 @@ foreach ($fields as $field) {
<ul>
<?php
echo "\t\t<li><?php echo \$this->Html->link(__('Edit " . $singularHumanName ."'), array('action' => 'edit', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?> </li>\n";
echo "\t\t<li><?php echo \$this->Form->postLink(__('Delete " . $singularHumanName . "'), array('action' => 'delete', \${$singularVar}['{$modelClass}']['{$primaryKey}']), null, sprintf(__('Are you sure you want to delete # %s?'), \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?> </li>\n";
echo "\t\t<li><?php echo \$this->Form->postLink(__('Delete " . $singularHumanName . "'), array('action' => 'delete', \${$singularVar}['{$modelClass}']['{$primaryKey}']), null, __('Are you sure you want to delete # %s?', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?> </li>\n";
echo "\t\t<li><?php echo \$this->Html->link(__('List " . $pluralHumanName . "'), array('action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$this->Html->link(__('New " . $singularHumanName . "'), array('action' => 'add')); ?> </li>\n";
@ -129,7 +129,7 @@ echo "\t<?php
echo "\t\t\t<td class=\"actions\">\n";
echo "\t\t\t\t<?php echo \$this->Html->link(__('View'), array('controller' => '{$details['controller']}', 'action' => 'view', \${$otherSingularVar}['{$details['primaryKey']}'])); ?>\n";
echo "\t\t\t\t<?php echo \$this->Html->link(__('Edit'), array('controller' => '{$details['controller']}', 'action' => 'edit', \${$otherSingularVar}['{$details['primaryKey']}'])); ?>\n";
echo "\t\t\t\t<?php echo \$this->Form->postLink(__('Delete'), array('controller' => '{$details['controller']}', 'action' => 'delete', \${$otherSingularVar}['{$details['primaryKey']}']), null, sprintf(__('Are you sure you want to delete # %s?'), \${$otherSingularVar}['{$details['primaryKey']}'])); ?>\n";
echo "\t\t\t\t<?php echo \$this->Form->postLink(__('Delete'), array('controller' => '{$details['controller']}', 'action' => 'delete', \${$otherSingularVar}['{$details['primaryKey']}']), null, __('Are you sure you want to delete # %s?', \${$otherSingularVar}['{$details['primaryKey']}'])); ?>\n";
echo "\t\t\t</td>\n";
echo "\t\t</tr>\n";

View file

@ -36,19 +36,46 @@
Configure::write('debug', 2);
/**
* CakePHP Log Level:
* Configure the Error handler used to handle errors for your application. By default
* ErrorHandler::handleError() is used. It will display errors using Debugger, when debug > 0
* and log errors with CakeLog when debug = 0.
*
* In case of Production Mode CakePHP gives you the possibility to continue logging errors.
* Options:
*
* The following parameters can be used:
* Boolean: Set true/false to activate/deactivate logging
* Configure::write('log', true);
* - `handler` - callback - The callback to handle errors. You can set this to any callback type,
* including anonymous functions.
* - `level` - int - The level of errors you are interested in capturing.
* - `trace` - boolean - Include stack traces for errors in log files.
*
* Integer: Use built-in PHP constants to set the error level (see error_reporting)
* Configure::write('log', E_ERROR | E_WARNING);
* Configure::write('log', E_ALL ^ E_NOTICE);
* @see ErrorHandler for more information on error handling and configuration.
*/
Configure::write('log', true);
Configure::write('Error', array(
'handler' => 'ErrorHandler::handleError',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true
));
/**
* Configure the Exception handler used for uncaught exceptions. By default,
* ErrorHandler::handleException() is used. It will display a HTML page for the exception, and
* while debug > 0, framework errors like Missing Controller will be displayed. When debug = 0,
* framework errors will be coerced into generic HTTP errors.
*
* Options:
*
* - `handler` - callback - The callback to handle exceptions. You can set this to any callback type,
* including anonymous functions.
* - `renderer` - string - The class responsible for rendering uncaught exceptions. If you choose a custom class you
* should place the file for that class in app/libs. This class needs to implement a render method.
* - `log` - boolean - Should Exceptions be logged?
*
* @see ErrorHandler for more information on exception handling and configuration.
*/
Configure::write('Exception', array(
'handler' => 'ErrorHandler::handleException',
'renderer' => 'ExceptionRenderer',
'log' => true
));
/**
* Application wide charset encoding
@ -121,14 +148,14 @@
* - `Session.name` - The name of the cookie to use. Defaults to 'CAKEPHP'
* - `Session.timeout` - The number of minutes you want sessions to live for. This timeout is handled by CakePHP
* - `Session.cookieTimeout` - The number of minutes you want session cookies to live for.
* - `Session.checkAgent` - Do you want the user agent to be checked when starting sessions? You might want to set the
* - `Session.checkAgent` - Do you want the user agent to be checked when starting sessions? You might want to set the
* value to false, when dealing with older versions of IE, Chrome Frame or certain web-browsing devices and AJAX
* - `Session.defaults` - The default configuration set to use as a basis for your session.
* There are four builtins: php, cake, cache, database.
* - `Session.handler` - Can be used to enable a custom session handler. Expects an array of of callables,
* that can be used with `session_save_handler`. Using this option will automatically add `session.save_handler`
* to the ini array.
* - `Session.autoRegenerate` - Enabling this setting, turns on automatic regeneration of sessions, and
* - `Session.autoRegenerate` - Enabling this setting, turns on automatic renewal of sessions, and
* sessionids that change frequently. See CakeSession::$requestCountdown.
* - `Session.ini` - An associative array of additional ini values to set.
*

View file

@ -31,16 +31,10 @@
*
* driver => The name of a supported driver; valid options are as follows:
* mysql - MySQL 4 & 5,
* mysqli - MySQL 4 & 5 Improved Interface (PHP5 only),
* sqlite - SQLite (PHP5 only),
* postgres - PostgreSQL 7 and higher,
* mssql - Microsoft SQL Server 2000 and higher,
* db2 - IBM DB2, Cloudscape, and Apache Derby (http://php.net/ibm-db2)
* oracle - Oracle 8 and higher
* firebird - Firebird/Interbase
* sybase - Sybase ASE
* adodb-[drivername] - ADOdb interface wrapper (see below),
* odbc - ODBC DBO driver
*
* You can add custom database drivers (or override existing drivers) by adding the
* appropriate file to app/models/datasources/dbo. Drivers should be named 'dbo_x.php',
@ -49,12 +43,6 @@
* persistent => true / false
* Determines whether or not the database should use a persistent connection
*
* connect =>
* ADOdb set the connect to one of these
* (http://phplens.com/adodb/supported.databases.html) and
* append it '|p' for persistent connection. (mssql|p for example, or just mssql for not persistent)
* For all other databases, this setting is deprecated.
*
* host =>
* the host you connect to the database. To add a socket or port number, use 'port' => #
*
@ -63,11 +51,11 @@
* on a per-table basis with the Model::$tablePrefix property.
*
* schema =>
* For Postgres and DB2, specifies which schema you would like to use the tables in. Postgres defaults to
* For Postgresspecifies which schema you would like to use the tables in. Postgres defaults to
* 'public', DB2 defaults to empty.
*
* encoding =>
* For MySQL, MySQLi, Postgres and DB2, specifies the character encoding to use when connecting to the
* For MySQL, Postgres and Sqlite, specifies the character encoding to use when connecting to the
* database. Uses database default.
*
*/

View file

@ -65,13 +65,8 @@
define('WWW_ROOT', dirname(__FILE__) . DS);
}
if (!defined('CORE_PATH')) {
if (function_exists('ini_set') && ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . ROOT . DS . APP_DIR . DS . PATH_SEPARATOR . ini_get('include_path'))) {
define('APP_PATH', null);
define('CORE_PATH', null);
} else {
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
@ -79,7 +74,7 @@
if (isset($_GET['url']) && $_GET['url'] === 'favicon.ico') {
return;
} else {
require CAKE . 'dispatcher.php';
require LIBS . 'dispatcher.php';
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch();
$Dispatcher->dispatch(new CakeRequest(isset($_GET['url']) ? $_GET['url'] : null));
}

View file

@ -65,13 +65,8 @@ if (!defined('WWW_ROOT')) {
define('WWW_ROOT', dirname(__FILE__) . DS);
}
if (!defined('CORE_PATH')) {
if (function_exists('ini_set') && ini_set('include_path', CAKE_CORE_INCLUDE_PATH . PATH_SEPARATOR . ROOT . DS . APP_DIR . DS . PATH_SEPARATOR . ini_get('include_path'))) {
define('APP_PATH', null);
define('CORE_PATH', null);
} else {
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
if (!include(CORE_PATH . 'cake' . DS . 'bootstrap.php')) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);

889
cake/libs/app.php Normal file
View file

@ -0,0 +1,889 @@
<?php
/**
* App class
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 1.2.0.6001
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* App is responsible for path managment, 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 when you
* call App::import('Controller', 'Posts'); This allows you to split your application up across the filesystem.
*
* ### Inspecting loaded paths
*
* You can inspect the currently loaded paths using `App::path('controller')` for example to see loaded
* controller paths.
*
* ### 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/view/933/The-App-Class
* @package cake
* @subpackage cake.cake.libs
*/
class App {
/**
* List of object types and their properties
*
* @var array
*/
public static $types = array(
'class' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'file' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'model' => array('suffix' => '.php', 'extends' => 'AppModel', 'core' => false),
'behavior' => array('suffix' => '.php', 'extends' => 'ModelBehavior', 'core' => true),
'controller' => array('suffix' => '_controller.php', 'extends' => 'AppController', 'core' => true),
'component' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'lib' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'view' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'helper' => array('suffix' => '.php', 'extends' => 'AppHelper', 'core' => true),
'vendor' => array('suffix' => '', 'extends' => null, 'core' => true),
'shell' => array('suffix' => '.php', 'extends' => 'Shell', 'core' => true),
'plugin' => array('suffix' => '', 'extends' => null, 'core' => true)
);
/**
* List of additional path(s) where model files reside.
*
* @var array
*/
public static $models = array();
/**
* List of additional path(s) where behavior files reside.
*
* @var array
*/
public static $behaviors = array();
/**
* List of additional path(s) where controller files reside.
*
* @var array
*/
public static $controllers = array();
/**
* List of additional path(s) where component files reside.
*
* @var array
*/
public static $components = array();
/**
* List of additional path(s) where datasource files reside.
*
* @var array
*/
public static $datasources = array();
/**
* List of additional path(s) where libs files reside.
*
* @var array
*/
public static $libs = array();
/**
* List of additional path(s) where view files reside.
*
* @var array
*/
public static $views = array();
/**
* List of additional path(s) where helper files reside.
*
* @var array
*/
public static $helpers = array();
/**
* List of additional path(s) where plugins reside.
*
* @var array
*/
public static $plugins = array();
/**
* List of additional path(s) where vendor packages reside.
*
* @var array
*/
public static $vendors = array();
/**
* List of additional path(s) where locale files reside.
*
* @var array
*/
public static $locales = array();
/**
* List of additional path(s) where console shell files reside.
*
* @var array
*/
public static $shells = array();
/**
* 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;
/**
* Determines if $__maps and $__paths cache should be written.
*
* @var boolean
*/
private static $__cache = false;
/**
* Holds key/value pairs of $type => file path.
*
* @var array
*/
private static $__map = array();
/**
* Holds paths for deep searching of files.
*
* @var array
*/
private static $__paths = array();
/**
* Holds loaded files.
*
* @var array
*/
private static $__loaded = array();
/**
* Holds and key => value array of object types.
*
* @var array
*/
private static $__objects = array();
/**
* Used to read information stored path
*
* Usage:
*
* `App::path('models'); will return all paths for models`
*
* @param string $type type of path
* @return string array
*/
public static function path($type) {
if (!isset(self::${$type})) {
return array();
}
return self::${$type};
}
/**
* Build path references. Merges the supplied $paths
* with the base paths and the default core paths.
*
* @param array $paths paths defines in config/bootstrap.php
* @param boolean $reset true will set paths, false merges paths [default] false
* @return void
*/
public static function build($paths = array(), $reset = false) {
$defaults = array(
'models' => array(MODELS),
'behaviors' => array(BEHAVIORS),
'datasources' => array(MODELS . 'datasources'),
'controllers' => array(CONTROLLERS),
'components' => array(COMPONENTS),
'libs' => array(APPLIBS),
'views' => array(VIEWS),
'helpers' => array(HELPERS),
'locales' => array(APP . 'locale' . DS),
'shells' => array(
APP . 'console' . DS . 'shells' . DS,
APP . 'vendors' . DS . 'shells' . DS,
VENDORS . 'shells' . DS
),
'vendors' => array(APP . 'vendors' . DS, VENDORS),
'plugins' => array(APP . 'plugins' . DS)
);
if ($reset == true) {
foreach ($paths as $type => $new) {
self::${$type} = (array)$new;
}
return $paths;
}
$core = self::core();
$app = array('models' => true, 'controllers' => true, 'helpers' => true);
foreach ($defaults as $type => $default) {
$merge = array();
if (isset($app[$type])) {
$merge = array(APP);
}
if (isset($core[$type])) {
$merge = array_merge($merge, (array)$core[$type]);
}
if (empty(self::${$type}) || empty($paths)) {
self::${$type} = $default;
}
if (!empty($paths[$type])) {
$path = array_flip(array_flip(array_merge(
(array)$paths[$type], self::${$type}, $merge
)));
self::${$type} = array_values($path);
} else {
$path = array_flip(array_flip(array_merge(self::${$type}, $merge)));
self::${$type} = array_values($path);
}
}
}
/**
* Get the path that a plugin is on. Searches through the defined plugin paths.
*
* @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) {
$pluginDir = Inflector::underscore($plugin);
for ($i = 0, $length = count(self::$plugins); $i < $length; $i++) {
if (is_dir(self::$plugins[$i] . $pluginDir)) {
return self::$plugins[$i] . $pluginDir . DS ;
}
}
return self::$plugins[0] . $pluginDir . DS;
}
/**
* Find the path that a theme is on. Search through the defined theme paths.
*
* @param string $theme lower_cased theme name to find the path of.
* @return string full path to the theme.
*/
public static function themePath($theme) {
$themeDir = 'themed' . DS . Inflector::underscore($theme);
for ($i = 0, $length = count(self::$views); $i < $length; $i++) {
if (is_dir(self::$views[$i] . $themeDir)) {
return self::$views[$i] . $themeDir . DS ;
}
}
return self::$views[0] . $themeDir . DS;
}
/**
* Returns a key/value list of all paths where core libs are found.
* Passing $type only returns the values for a given value of $key.
*
* @param string $type valid values are: 'model', 'behavior', 'controller', 'component',
* 'view', 'helper', 'datasource', 'libs', and 'cake'
* @return array numeric keyed array of core lib paths
*/
public static function core($type = null) {
static $paths = false;
if (!$paths) {
$paths = array();
$libs = dirname(__FILE__) . DS;
$cake = dirname($libs) . DS;
$path = dirname($cake) . DS;
$paths['cake'][] = $cake;
$paths['libs'][] = $libs;
$paths['models'][] = $libs . 'model' . DS;
$paths['datasources'][] = $libs . 'model' . DS . 'datasources' . DS;
$paths['behaviors'][] = $libs . 'model' . DS . 'behaviors' . DS;
$paths['controllers'][] = $libs . 'controller' . DS;
$paths['components'][] = $libs . 'controller' . DS . 'components' . DS;
$paths['views'][] = $libs . 'view' . DS;
$paths['helpers'][] = $libs . 'view' . DS . 'helpers' . DS;
$paths['plugins'][] = $path . 'plugins' . DS;
$paths['vendors'][] = $path . 'vendors' . DS;
$paths['shells'][] = $cake . 'console' . DS . 'shells' . DS;
// Provide BC path to vendors/shells
$paths['shells'][] = $path . 'vendors' . DS . 'shells' . DS;
}
if ($type && isset($paths[$type])) {
return $paths[$type];
}
return $paths;
}
/**
* Returns an array of objects of the given type.
*
* Example usage:
*
* `App::objects('plugin');` returns `array('DebugKit', 'Blog', 'User');`
*
* @param string $type Type of object, i.e. 'model', 'controller', 'helper', 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) {
$objects = array();
$extension = false;
$name = $type;
if ($type === 'file' && !$path) {
return false;
} elseif ($type === 'file') {
$extension = true;
$name = $type . str_replace(DS, '', $path);
}
if (empty(self::$__objects) && $cache === true) {
self::$__objects = Cache::read('object_map', '_cake_core_');
}
if (!isset(self::$__objects[$name]) || $cache !== true) {
$types = self::$types;
if (!isset($types[$type])) {
return false;
}
$objects = array();
if (empty($path)) {
$path = self::${"{$type}s"};
if (isset($types[$type]['core']) && $types[$type]['core'] === false) {
array_pop($path);
}
}
$items = array();
foreach ((array)$path as $dir) {
if ($dir != APP) {
$items = self::__list($dir, $types[$type]['suffix'], $extension);
$objects = array_merge($items, array_diff($objects, $items));
}
}
if ($type !== 'file') {
foreach ($objects as $key => $value) {
$objects[$key] = Inflector::camelize($value);
}
}
if ($cache === true) {
self::$__cache = true;
}
self::$__objects[$name] = $objects;
}
return self::$__objects[$name];
}
/**
* Allows you to modify the object listings that App maintains inside of it
* Useful for testing
*
* @param string $type Type of object listing you are changing
* @param array $values The values $type should be set to.
* @return void
*/
public static function setObjects($type, $values) {
self::$__objects[$type] = $values;
}
/**
* 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/view/934/Using-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) {
$plugin = $directory = null;
if (is_array($type)) {
extract($type, EXTR_OVERWRITE);
}
if (is_array($parent)) {
extract($parent, EXTR_OVERWRITE);
}
if ($name === null && $file === null) {
$name = $type;
$type = 'Core';
} elseif ($name === null) {
$type = 'File';
}
if (is_array($name)) {
foreach ($name as $class) {
$tempType = $type;
$plugin = null;
if (strpos($class, '.') !== false) {
$value = explode('.', $class);
$count = count($value);
if ($count > 2) {
$tempType = $value[0];
$plugin = $value[1] . '.';
$class = $value[2];
} elseif ($count === 2 && ($type === 'Core' || $type === 'File')) {
$tempType = $value[0];
$class = $value[1];
} else {
$plugin = $value[0] . '.';
$class = $value[1];
}
}
if (!App::import($tempType, $plugin . $class, $parent)) {
return false;
}
}
return true;
}
if ($name != null && strpos($name, '.') !== false) {
list($plugin, $name) = explode('.', $name);
$plugin = Inflector::camelize($plugin);
}
self::$return = $return;
if (isset($ext)) {
$file = Inflector::underscore($name) . ".{$ext}";
}
$ext = self::__settings($type, $plugin, $parent);
$className = $name;
if (strpos($className, '/') !== false) {
$className = substr($className, strrpos($className, '/') + 1);
}
if ($name != null && !class_exists($className . $ext['class'])) {
if ($load = self::__mapped($name . $ext['class'], $type, $plugin)) {
if (self::__load($load)) {
if (self::$return) {
return include($load);
}
return true;
} else {
self::__remove($name . $ext['class'], $type, $plugin);
self::$__cache = true;
}
}
if (!empty($search)) {
self::$search = $search;
} elseif ($plugin) {
self::$search = self::__paths('plugin');
} else {
self::$search = self::__paths($type);
}
$find = $file;
if ($find === null) {
$find = Inflector::underscore($name . $ext['suffix']).'.php';
if ($plugin) {
$paths = self::$search;
foreach ($paths as $key => $value) {
self::$search[$key] = $value . $ext['path'];
}
}
}
if (strtolower($type) !== 'vendor' && empty($search) && self::__load($file)) {
$directory = false;
} else {
$file = $find;
$directory = self::__find($find, true);
}
if ($directory !== null) {
self::$__cache = true;
self::__map($directory . $file, $name . $ext['class'], $type, $plugin);
if (self::$return) {
return include($directory . $file);
}
return true;
}
return false;
}
return true;
}
/**
* Initializes the cache for App, registers a shutdown function.
*
* @return void
*/
public static function init() {
self::$__map = (array)Cache::read('file_map', '_cake_core_');
register_shutdown_function(array('App', 'shutdown'));
}
/**
* Locates the $file in $__paths, searches recursively.
*
* @param string $file full file name
* @param boolean $recursive search $__paths recursively
* @return mixed boolean on fail, $file directory path on success
*/
private static function __find($file, $recursive = true) {
static $appPath = false;
if (empty(self::$search)) {
return null;
} elseif (is_string(self::$search)) {
$this->search = array(self::$search);
}
if (empty(self::$__paths)) {
self::$__paths = Cache::read('dir_map', '_cake_core_');
}
foreach (self::$search as $path) {
if ($appPath === false) {
$appPath = rtrim(APP, DS);
}
$path = rtrim($path, DS);
if ($path === $appPath) {
$recursive = false;
}
if ($recursive === false) {
if (self::__load($path . DS . $file)) {
return $path . DS;
}
continue;
}
if (!isset(self::$__paths[$path])) {
if (!class_exists('Folder')) {
require LIBS . 'folder.php';
}
$Folder = new Folder();
$directories = $Folder->tree($path, array('.svn', '.git', 'CVS', 'tests', 'templates'), 'dir');
sort($directories);
self::$__paths[$path] = $directories;
}
foreach (self::$__paths[$path] as $directory) {
if (self::__load($directory . DS . $file)) {
return $directory . DS;
}
}
}
return null;
}
/**
* Attempts to load $file.
*
* @param string $file full path to file including file name
* @return boolean
* @access private
*/
private static function __load($file) {
if (empty($file)) {
return false;
}
if (!self::$return && isset(self::$__loaded[$file])) {
return true;
}
if (file_exists($file)) {
if (!self::$return) {
require($file);
self::$__loaded[$file] = true;
}
return true;
}
return false;
}
/**
* Maps the $name to the $file.
*
* @param string $file full path to file
* @param string $name unique name for this map
* @param string $type type object being mapped
* @param string $plugin camelized if object is from a plugin, the name of the plugin
* @return void
* @access private
*/
private static function __map($file, $name, $type, $plugin) {
if ($plugin) {
self::$__map['Plugin'][$plugin][$type][$name] = $file;
} else {
self::$__map[$type][$name] = $file;
}
}
/**
* Returns a file's complete path.
*
* @param string $name unique name
* @param string $type type object
* @param string $plugin camelized if object is from a plugin, the name of the plugin
* @return mixed, file path if found, false otherwise
* @access private
*/
private static function __mapped($name, $type, $plugin) {
if ($plugin) {
if (isset(self::$__map['Plugin'][$plugin][$type]) && isset(self::$__map['Plugin'][$plugin][$type][$name])) {
return self::$__map['Plugin'][$plugin][$type][$name];
}
return false;
}
if (isset(self::$__map[$type]) && isset(self::$__map[$type][$name])) {
return self::$__map[$type][$name];
}
return false;
}
/**
* Loads parent classes based on $type.
* Returns a prefix or suffix needed for loading files.
*
* @param string $type type of object
* @param string $plugin camelized name of plugin
* @param boolean $parent false will not attempt to load parent
* @return array
* @access private
*/
private static function __settings($type, $plugin, $parent) {
if (!$parent) {
return array('class' => null, 'suffix' => null, 'path' => null);
}
if ($plugin) {
$pluginPath = Inflector::underscore($plugin);
}
$path = null;
$load = strtolower($type);
switch ($load) {
case 'model':
if (!class_exists('Model')) {
require LIBS . 'model' . DS . 'model.php';
}
if (!class_exists('AppModel')) {
App::import($type, 'AppModel', false);
}
if ($plugin) {
if (!class_exists($plugin . 'AppModel')) {
App::import($type, $plugin . '.' . $plugin . 'AppModel', false, array(), $pluginPath . DS . $pluginPath . '_app_model.php');
}
$path = $pluginPath . DS . 'models' . DS;
}
return array('class' => null, 'suffix' => null, 'path' => $path);
break;
case 'behavior':
if ($plugin) {
$path = $pluginPath . DS . 'models' . DS . 'behaviors' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
case 'datasource':
if ($plugin) {
$path = $pluginPath . DS . 'models' . DS . 'datasources' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
case 'controller':
App::import($type, 'AppController', false);
if ($plugin) {
App::import($type, $plugin . '.' . $plugin . 'AppController', false, array(), $pluginPath . DS . $pluginPath . '_app_controller.php');
$path = $pluginPath . DS . 'controllers' . DS;
}
return array('class' => $type, 'suffix' => $type, 'path' => $path);
break;
case 'component':
App::import('Core', 'Component', false);
if ($plugin) {
$path = $pluginPath . DS . 'controllers' . DS . 'components' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
case 'lib':
if ($plugin) {
$path = $pluginPath . DS . 'libs' . DS;
}
return array('class' => null, 'suffix' => null, 'path' => $path);
break;
case 'view':
App::import('View', 'View', false);
if ($plugin) {
$path = $pluginPath . DS . 'views' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
case 'helper':
if (!class_exists('AppHelper')) {
App::import($type, 'AppHelper', false);
}
if ($plugin) {
$path = $pluginPath . DS . 'views' . DS . 'helpers' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
case 'shell':
if (!class_exists('Shell')) {
App::import($type, 'Shell', false);
}
if (!class_exists('AppShell')) {
App::import($type, 'AppShell', false);
}
if ($plugin) {
$path = $pluginPath . DS . 'console' . DS . 'shells' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
case 'vendor':
if ($plugin) {
$path = $pluginPath . DS . 'vendors' . DS;
}
return array('class' => null, 'suffix' => null, 'path' => $path);
break;
default:
$type = $suffix = $path = null;
break;
}
return array('class' => null, 'suffix' => null, 'path' => null);
}
/**
* Returns default search paths.
*
* @param string $type type of object to be searched
* @return array list of paths
*/
private static function __paths($type) {
$type = strtolower($type);
$paths = array();
if ($type === 'core') {
return App::core('libs');
}
if (isset(self::${$type . 's'})) {
return self::${$type . 's'};
}
return $paths;
}
/**
* Removes file location from map if the file has been deleted.
*
* @param string $name name of object
* @param string $type type of object
* @param string $plugin camelized name of plugin
* @return void
*/
private static function __remove($name, $type, $plugin) {
if ($plugin) {
unset(self::$__map['Plugin'][$plugin][$type][$name]);
} else {
unset(self::$__map[$type][$name]);
}
}
/**
* Returns an array of filenames of PHP files in the given directory.
*
* @param string $path Path to scan for files
* @param string $suffix if false, return only directories. if string, match and return files
* @return array List of directories or files in directory
*/
private static function __list($path, $suffix = false, $extension = false) {
if (!class_exists('Folder')) {
require LIBS . 'folder.php';
}
$items = array();
$Folder = new Folder($path);
$contents = $Folder->read(false, true);
if (is_array($contents)) {
if (!$suffix) {
return $contents[0];
} else {
foreach ($contents[1] as $item) {
if (substr($item, - strlen($suffix)) === $suffix) {
if ($extension) {
$items[] = $item;
} else {
$items[] = substr($item, 0, strlen($item) - strlen($suffix));
}
}
}
}
}
return $items;
}
/**
* Object destructor.
*
* Writes cache file if changes have been made to the $__map or $__paths
*
* @return void
*/
public static function shutdown() {
if (self::$__cache) {
$core = App::core('cake');
unset(self::$__paths[rtrim($core[0], DS)]);
Cache::write('dir_map', array_filter(self::$__paths), '_cake_core_');
Cache::write('file_map', array_filter(self::$__map), '_cake_core_');
Cache::write('object_map', self::$__objects, '_cake_core_');
}
}
}

View file

@ -274,7 +274,7 @@ class Cache {
self::set(null, $config);
if ($success === false && $value !== '') {
trigger_error(
sprintf(__("%s cache was unable to write '%s' to cache", true), $config, $key),
__("%s cache was unable to write '%s' to cache", $config, $key),
E_USER_WARNING
);
}

View file

@ -298,7 +298,7 @@ class FileEngine extends CacheEngine {
$dir = new SplFileInfo($this->settings['path']);
if ($this->_init && !($dir->isDir() && $dir->isWritable())) {
$this->_init = false;
trigger_error(sprintf(__('%s is not writable'), $this->settings['path']), E_USER_WARNING);
trigger_error(__('%s is not writable', $this->settings['path']), E_USER_WARNING);
return false;
}
return true;

View file

@ -78,7 +78,7 @@ class MemcacheEngine extends CacheEngine {
}
if (!isset($this->__Memcache)) {
$return = false;
$this->__Memcache =& new Memcache();
$this->__Memcache = new Memcache();
foreach ($this->settings['servers'] as $server) {
list($host, $port) = $this->_parseServerString($server);
if ($this->__Memcache->addServer($host, $port)) {
@ -153,7 +153,7 @@ class MemcacheEngine extends CacheEngine {
public function increment($key, $offset = 1) {
if ($this->settings['compress']) {
throw new RuntimeException(
sprintf(__('Method increment() not implemented for compressed cache in %s'), __CLASS__)
__('Method increment() not implemented for compressed cache in %s', __CLASS__)
);
}
return $this->__Memcache->increment($key, $offset);
@ -171,7 +171,7 @@ class MemcacheEngine extends CacheEngine {
public function decrement($key, $offset = 1) {
if ($this->settings['compress']) {
throw new RuntimeException(
sprintf(__('Method decrement() not implemented for compressed cache in %s'), __CLASS__)
__('Method decrement() not implemented for compressed cache in %s', __CLASS__)
);
}
return $this->__Memcache->decrement($key, $offset);

View file

@ -99,7 +99,7 @@ class CakeLog {
* @return boolean success of configuration.
* @throws Exception
*/
static function config($key, $config) {
public static function config($key, $config) {
if (empty($config['engine'])) {
throw new Exception(__('Missing logger classname'));
}
@ -134,7 +134,7 @@ class CakeLog {
}
}
if (!class_exists($loggerName)) {
throw new Exception(sprintf(__('Could not load class %s'), $loggerName));
throw new Exception(__('Could not load class %s', $loggerName));
}
return $loggerName;
}
@ -222,54 +222,4 @@ class CakeLog {
}
return true;
}
/**
* An error_handler that will log errors to file using CakeLog::write();
* You can control how verbose and what type of errors this error_handler will
* catch using `Configure::write('log', $value)`. See core.php for more information.
*
*
* @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 void
*/
public static function handleError($code, $description, $file = null, $line = null, $context = null) {
if ($code === 2048 || $code === 8192) {
return;
}
switch ($code) {
case E_PARSE:
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
$error = 'Fatal Error';
$level = LOG_ERROR;
break;
case E_WARNING:
case E_USER_WARNING:
case E_COMPILE_WARNING:
case E_RECOVERABLE_ERROR:
$error = 'Warning';
$level = LOG_WARNING;
break;
case E_NOTICE:
case E_USER_NOTICE:
$error = 'Notice';
$level = LOG_NOTICE;
break;
default:
return;
break;
}
$message = $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
CakeLog::write($level, $message);
}
}
if (!defined('DISABLE_DEFAULT_ERROR_HANDLING')) {
set_error_handler(array('CakeLog', 'handleError'));
}

View file

@ -13,7 +13,6 @@
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
@ -27,6 +26,7 @@ App::import('Core', 'Set');
*
* `$request['controller']` or `$request->controller`.
*
* @package cake.libs
*/
class CakeRequest implements ArrayAccess {
/**
@ -550,7 +550,7 @@ class CakeRequest implements ArrayAccess {
* @param string $name Name of the header you want.
* @return mixed Either false on no header being set or the value of the header.
*/
public function header($name) {
public static function header($name) {
$name = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
if (!empty($_SERVER[$name])) {
return $_SERVER[$name];
@ -582,7 +582,7 @@ class CakeRequest implements ArrayAccess {
* @param int $tldLength Number of segments your tld contains
* @return string Domain name without subdomains.
*/
function domain($tldLength = 1) {
public function domain($tldLength = 1) {
$segments = explode('.', $this->host());
$domain = array_slice($segments, -1 * ($tldLength + 1));
return implode('.', $domain);
@ -594,7 +594,7 @@ class CakeRequest implements ArrayAccess {
* @param int $tldLength Number of segments your tld contains.
* @return array of subdomains.
*/
function subdomains($tldLength = 1) {
public function subdomains($tldLength = 1) {
$segments = explode('.', $this->host());
return array_slice($segments, 0, -1 * ($tldLength + 1));
}
@ -629,6 +629,26 @@ class CakeRequest implements ArrayAccess {
return in_array($type, $acceptTypes);
}
/**
* Get the lanaguages accepted by the client, or check if a specific language is accepted.
*
* @param string $language The language to test.
* @return If a $language is provided, a boolean. Otherwise the array of accepted languages.
*/
public static function acceptLanguage($language = null) {
$accepts = preg_split('/[;,]/', self::header('Accept-Language'));
foreach ($accepts as &$accept) {
$accept = strtolower($accept);
if (strpos($accept, '_') !== false) {
$accept = str_replace('_', '-', $accept);
}
}
if ($language === null) {
return $accepts;
}
return in_array($language, $accepts);
}
/**
* Provides a read/write accessor for `$this->data`. Allows you
* to use a syntax similar to `CakeSession` for reading post data.

View file

@ -141,7 +141,7 @@ class CakeSession {
* @param boolean $start Should session be started right now
*/
public static function init($base = null, $start = true) {
App::import('Core', array('Set', 'Security'));
App::import('Core', 'Security');
self::$time = time();
$checkAgent = Configure::read('Session.checkAgent');
@ -262,12 +262,12 @@ class CakeSession {
public static function delete($name) {
if (self::check($name)) {
if (in_array($name, self::$watchKeys)) {
trigger_error(sprintf(__('Deleting session key {%s}'), $name), E_USER_NOTICE);
trigger_error(__('Deleting session key {%s}', $name), E_USER_NOTICE);
}
self::__overwrite($_SESSION, Set::remove($_SESSION, $name));
return (self::check($name) == false);
}
self::__setError(2, sprintf(__("%s doesn't exist"), $name));
self::__setError(2, __("%s doesn't exist", $name));
return false;
}
@ -278,7 +278,7 @@ class CakeSession {
* @param array $new New set of variable => value
* @access private
*/
function __overwrite(&$old, $new) {
private static function __overwrite(&$old, $new) {
if (!empty($old)) {
foreach ($old as $key => $var) {
if (!isset($new[$key])) {
@ -298,7 +298,7 @@ class CakeSession {
* @return string Error as string
* @access private
*/
function __error($errorNumber) {
private static function __error($errorNumber) {
if (!is_array(self::$error) || !array_key_exists($errorNumber, self::$error)) {
return false;
} else {
@ -452,7 +452,7 @@ class CakeSession {
}
foreach ($write as $key => $val) {
if (in_array($key, self::$watchKeys)) {
trigger_error(sprintf(__('Writing session key {%s}: %s'), $key, Debugger::exportVar($val)), E_USER_NOTICE);
trigger_error(__('Writing session key {%s}: %s', $key, Debugger::exportVar($val)), E_USER_NOTICE);
}
self::__overwrite($_SESSION, Set::insert($_SESSION, $key, $val));
if (Set::classicExtract($_SESSION, $key) !== $val) {
@ -562,7 +562,7 @@ class CakeSession {
App::import('Core', 'session/' . $class);
}
if (!class_exists($class)) {
throw new Exception(sprintf(__('Could not load %s to handle the session.'), $class));
throw new Exception(__('Could not load %s to handle the session.', $class));
}
$handler = new $class();
if ($handler instanceof CakeSessionHandlerInterface) {
@ -650,7 +650,7 @@ class CakeSession {
*
* @return boolean Success
*/
protected function _startSession() {
protected static function _startSession() {
if (headers_sent()) {
if (empty($_SESSION)) {
$_SESSION = array();
@ -723,7 +723,7 @@ class CakeSession {
* @return void
* @access private
*/
function __setError($errorNumber, $errorMessage) {
private static function __setError($errorNumber, $errorMessage) {
if (self::$error === false) {
self::$error = array();
}

View file

@ -64,7 +64,7 @@ class ClassRegistry {
public static function &getInstance() {
static $instance = array();
if (!$instance) {
$instance[0] =& new ClassRegistry();
$instance[0] = new ClassRegistry();
}
return $instance[0];
}
@ -94,7 +94,7 @@ class ClassRegistry {
* @return object instance of ClassName
*/
public static function &init($class, $type = null) {
$_this =& ClassRegistry::getInstance();
$_this = ClassRegistry::getInstance();
$id = $false = false;
$true = true;
@ -129,13 +129,13 @@ class ClassRegistry {
}
$alias = $settings['alias'];
if ($model =& $_this->__duplicate($alias, $class)) {
if ($model = $_this->__duplicate($alias, $class)) {
$_this->map($alias, $class);
return $model;
}
if (class_exists($class) || App::import($type, $pluginPath . $class)) {
${$class} =& new $class($settings);
${$class} = new $class($settings);
} elseif ($type === 'Model') {
if ($plugin && class_exists($plugin . 'AppModel')) {
$appModel = $plugin . 'AppModel';
@ -143,11 +143,11 @@ class ClassRegistry {
$appModel = 'AppModel';
}
$settings['name'] = $class;
${$class} =& new $appModel($settings);
${$class} = new $appModel($settings);
}
if (!isset(${$class})) {
trigger_error(sprintf(__('(ClassRegistry::init() could not create instance of %1$s class %2$s '), $class, $type), E_USER_WARNING);
trigger_error(__('(ClassRegistry::init() could not create instance of %1$s class %2$s ', $class, $type), E_USER_WARNING);
return $false;
}
@ -176,10 +176,10 @@ class ClassRegistry {
* @return boolean True if the object was written, false if $key already exists
*/
public static function addObject($key, &$object) {
$_this =& ClassRegistry::getInstance();
$_this = ClassRegistry::getInstance();
$key = Inflector::underscore($key);
if (!isset($_this->__objects[$key])) {
$_this->__objects[$key] =& $object;
$_this->__objects[$key] = $object;
return true;
}
return false;
@ -192,7 +192,7 @@ class ClassRegistry {
* @return void
*/
public static function removeObject($key) {
$_this =& ClassRegistry::getInstance();
$_this = ClassRegistry::getInstance();
$key = Inflector::underscore($key);
if (isset($_this->__objects[$key])) {
unset($_this->__objects[$key]);
@ -206,7 +206,7 @@ class ClassRegistry {
* @return boolean true if key exists in registry, false otherwise
*/
public static function isKeySet($key) {
$_this =& ClassRegistry::getInstance();
$_this = ClassRegistry::getInstance();
$key = Inflector::underscore($key);
if (isset($_this->__objects[$key])) {
return true;
@ -222,7 +222,7 @@ class ClassRegistry {
* @return array Set of keys stored in registry
*/
public static function keys() {
$_this =& ClassRegistry::getInstance();
$_this = ClassRegistry::getInstance();
return array_keys($_this->__objects);
}
@ -233,15 +233,15 @@ class ClassRegistry {
* @return mixed Object stored in registry or boolean false if the object does not exist.
*/
public static function &getObject($key) {
$_this =& ClassRegistry::getInstance();
$_this = ClassRegistry::getInstance();
$key = Inflector::underscore($key);
$return = false;
if (isset($_this->__objects[$key])) {
$return =& $_this->__objects[$key];
$return = $_this->__objects[$key];
} else {
$key = $_this->__getMap($key);
if (isset($_this->__objects[$key])) {
$return =& $_this->__objects[$key];
$return = $_this->__objects[$key];
}
}
return $return;
@ -257,7 +257,7 @@ class ClassRegistry {
* the previously-set value of $param, or null if not set.
*/
public static function config($type, $param = array()) {
$_this =& ClassRegistry::getInstance();
$_this = ClassRegistry::getInstance();
if (empty($param) && is_array($type)) {
$param = $type;
@ -280,9 +280,9 @@ class ClassRegistry {
private function &__duplicate($alias, $class) {
$duplicate = false;
if ($this->isKeySet($alias)) {
$model =& $this->getObject($alias);
$model = $this->getObject($alias);
if (is_object($model) && (is_a($model, $class) || $model->alias === $class)) {
$duplicate =& $model;
$duplicate = $model;
}
unset($model);
}
@ -296,7 +296,7 @@ class ClassRegistry {
* @param string $name Key that is being mapped
*/
public static function map($key, $name) {
$_this =& ClassRegistry::getInstance();
$_this = ClassRegistry::getInstance();
$key = Inflector::underscore($key);
$name = Inflector::underscore($name);
if (!isset($_this->__map[$key])) {
@ -310,7 +310,7 @@ class ClassRegistry {
* @return array Keys of registry's map
*/
public static function mapKeys() {
$_this =& ClassRegistry::getInstance();
$_this = ClassRegistry::getInstance();
return array_keys($_this->__map);
}
@ -332,7 +332,7 @@ class ClassRegistry {
* @return void
*/
public static function flush() {
$_this =& ClassRegistry::getInstance();
$_this = ClassRegistry::getInstance();
$_this->__objects = array();
$_this->__map = array();
}

View file

@ -0,0 +1,101 @@
<?php
/**
* IniFile
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs.controller.components
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Ini file configuration parser. Since IniFile uses parse_ini_file underneath,
* you should be aware that this class shares the same behavior, especially with
* regards to boolean and null values.
*
* @package cake.config
* @see http://php.net/parse_ini_file
*/
class IniFile implements ArrayAccess {
/**
* Values inside the ini file.
*
* @var array
*/
protected $_values = array();
/**
* Build and construct a new ini file parser, the parser will be a representation of the ini
* file as an object.
*
* @param string $filename Full path to the file to parse.
* @param string $section Only get one section.
*/
public function __construct($filename, $section = null) {
$contents = parse_ini_file($filename, true);
if (!empty($section) && isset($contents[$section])) {
$this->_values = $contents[$section];
} else {
$this->_values = $contents;
}
}
/**
* Get the contents of the ini file as a plain array.
*
* @return array
*/
public function asArray() {
return $this->_values;
}
/**
* Part of ArrayAccess implementation.
*
* @param string $name
*/
public function offsetExists($name) {
return isset($this->_values[$name]);
}
/**
* Part of ArrayAccess implementation.
*
* @param string $name
*/
public function offsetGet($name) {
if (!isset($this->_values[$name])) {
return null;
}
return $this->_values[$name];
}
/**
* Part of ArrayAccess implementation.
*
* @param string $name
*/
public function offsetSet($name, $value) {
throw new LogicException('You cannot modify an IniFile parse result.');
}
/**
* Part of ArrayAccess implementation.
*
* @param string $name
*/
public function offsetUnset($name) {
unset($this->_values[$name]);
}
}

File diff suppressed because it is too large Load diff

View file

@ -93,9 +93,8 @@ class Component extends Object {
*/
public function __get($name) {
if (isset($this->_componentMap[$name]) && !isset($this->{$name})) {
$this->{$name} = $this->_Collection->load(
$this->_componentMap[$name]['class'], $this->_componentMap[$name]['settings'], false
);
$settings = array_merge((array)$this->_componentMap[$name]['settings'], array('enabled' => false));
$this->{$name} = $this->_Collection->load($this->_componentMap[$name]['class'], $settings);
}
if (isset($this->{$name})) {
return $this->{$name};

View file

@ -56,14 +56,15 @@ class ComponentCollection extends ObjectCollection {
/**
* Loads/constructs a component. Will return the instance in the registry if it already exists.
* You can use `$settings['enabled'] = false` to disable callbacks on a component when loading it.
* Callbacks default to on. Disabled component methods work as normal, only callbacks are disabled.
*
* @param string $component Component name to load
* @param array $settings Settings for the component.
* @param boolean $enable Whether or not this component should be enabled by default
* @return Component A component object, Either the existing loaded component or a new one.
* @throws MissingComponentFileException, MissingComponentClassException when the component could not be found
*/
public function load($component, $settings = array(), $enable = true) {
public function load($component, $settings = array()) {
list($plugin, $name) = pluginSplit($component);
if (isset($this->_loaded[$name])) {
return $this->_loaded[$name];
@ -84,6 +85,7 @@ class ComponentCollection extends ObjectCollection {
}
}
$this->_loaded[$name] = new $componentClass($this, $settings);
$enable = isset($settings['enabled']) ? $settings['enabled'] : true;
if ($enable === true) {
$this->_enabled[] = $name;
}

View file

@ -68,7 +68,7 @@ class AclComponent extends Component {
list($plugin, $name) = pluginSplit($name);
$name .= 'Component';
} else {
throw new Exception(sprintf(__('Could not find %s.'), $name));
throw new Exception(__('Could not find %s.', $name));
}
}
$this->adapter($name);
@ -280,8 +280,8 @@ class DbAcl extends Object implements AclInterface {
* @return void
*/
public function initialize($component) {
$component->Aro =& $this->Aro;
$component->Aco =& $this->Aco;
$component->Aro = $this->Aro;
$component->Aco = $this->Aco;
}
/**
@ -316,7 +316,7 @@ class DbAcl extends Object implements AclInterface {
$acoNode = $acoPath[0];
if ($action != '*' && !in_array('_' . $action, $permKeys)) {
trigger_error(sprintf(__("ACO permissions key %s does not exist in DbAcl::check()"), $action), E_USER_NOTICE);
trigger_error(__("ACO permissions key %s does not exist in DbAcl::check()", $action), E_USER_NOTICE);
return false;
}
@ -538,6 +538,15 @@ class IniAcl extends Object implements AclInterface {
*/
public $config = null;
/**
* The Set::classicExtract() path to the user/aro identifier in the
* acl.ini file. This path will be used to extract the string
* representation of a user used in the ini file.
*
* @var string
*/
public $userPath = 'User.username';
/**
* Initialize method
*
@ -599,6 +608,10 @@ class IniAcl extends Object implements AclInterface {
$this->config = $this->readConfigFile(CONFIGS . 'acl.ini.php');
}
$aclConfig = $this->config;
if (is_array($aro)) {
$aro = Set::classicExtract($aro, $this->userPath);
}
if (isset($aclConfig[$aro]['deny'])) {
$userDenies = $this->arrayTrim(explode(",", $aclConfig[$aro]['deny']));
@ -622,7 +635,7 @@ class IniAcl extends Object implements AclInterface {
foreach ($userGroups as $group) {
if (array_key_exists($group, $aclConfig)) {
if (isset($aclConfig[$group]['deny'])) {
$groupDenies=$this->arrayTrim(explode(",", $aclConfig[$group]['deny']));
$groupDenies = $this->arrayTrim(explode(",", $aclConfig[$group]['deny']));
if (array_search($aco, $groupDenies)) {
return false;
@ -645,43 +658,13 @@ class IniAcl extends Object implements AclInterface {
/**
* Parses an INI file and returns an array that reflects the INI file's section structure. Double-quote friendly.
*
* @param string $fileName File
* @param string $filename File
* @return array INI section structure
*/
public function readConfigFile($fileName) {
$fileLineArray = file($fileName);
foreach ($fileLineArray as $fileLine) {
$dataLine = trim($fileLine);
$firstChar = substr($dataLine, 0, 1);
if ($firstChar != ';' && $dataLine != '') {
if ($firstChar == '[' && substr($dataLine, -1, 1) == ']') {
$sectionName = preg_replace('/[\[\]]/', '', $dataLine);
} else {
$delimiter = strpos($dataLine, '=');
if ($delimiter > 0) {
$key = strtolower(trim(substr($dataLine, 0, $delimiter)));
$value = trim(substr($dataLine, $delimiter + 1));
if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
$value = substr($value, 1, -1);
}
$iniSetting[$sectionName][$key]=stripcslashes($value);
} else {
if (!isset($sectionName)) {
$sectionName = '';
}
$iniSetting[$sectionName][strtolower(trim($dataLine))]='';
}
}
}
}
return $iniSetting;
public function readConfigFile($filename) {
App::import('Core', 'config/IniFile');
$iniFile = new IniFile($filename);
return $iniFile->asArray();
}
/**

View file

@ -20,7 +20,8 @@
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('Router', 'Security'), false);
App::import('Core', 'Router', false);
App::import('Core', 'Security', false);
/**
* Authentication control component class
@ -322,7 +323,7 @@ class AuthComponent extends Component {
if (!$this->__setDefaults()) {
return false;
}
$request =& $controller->request;
$request = $controller->request;
$this->request->data = $controller->request->data = $this->hashPasswords($request->data);
$url = '';
@ -520,10 +521,9 @@ class AuthComponent extends Component {
$valid = $this->Acl->check($user, $this->action());
break;
case 'crud':
$this->mapActions();
if (!isset($this->actionMap[$this->request['action']])) {
trigger_error(
sprintf(__('Auth::startup() - Attempted access of un-mapped action "%1$s" in controller "%2$s"'), $this->request['action'], $this->request['controller']),
__('Auth::startup() - Attempted access of un-mapped action "%1$s" in controller "%2$s"', $this->request['action'], $this->request['controller']),
E_USER_WARNING
);
} else {
@ -535,7 +535,6 @@ class AuthComponent extends Component {
}
break;
case 'model':
$this->mapActions();
$action = $this->request['action'];
if (isset($this->actionMap[$action])) {
$action = $this->actionMap[$action];
@ -548,13 +547,13 @@ class AuthComponent extends Component {
$action = $this->action(':action');
}
if (empty($object)) {
trigger_error(sprintf(__('Could not find %s. Set AuthComponent::$object in beforeFilter() or pass a valid object'), get_class($object)), E_USER_WARNING);
trigger_error(__('Could not find %s. Set AuthComponent::$object in beforeFilter() or pass a valid object', get_class($object)), E_USER_WARNING);
return;
}
if (method_exists($object, 'isAuthorized')) {
$valid = $object->isAuthorized($user, $this->action(':controller'), $action);
} elseif ($object) {
trigger_error(sprintf(__('%s::isAuthorized() is not defined.'), get_class($object)), E_USER_WARNING);
trigger_error(__('%s::isAuthorized() is not defined.', get_class($object)), E_USER_WARNING);
}
break;
case null:

View file

@ -810,7 +810,7 @@ class EmailComponent extends Component {
* @access private
*/
function _smtp() {
App::import('Core', array('CakeSocket'));
App::import('Core', 'CakeSocket');
$defaults = array(
'host' => 'localhost',

View file

@ -121,8 +121,8 @@ class RequestHandlerComponent extends Component {
public function initialize(&$controller, $settings = array()) {
$this->request = $controller->request;
$this->response = $controller->response;
if (isset($controller->params['url']['ext'])) {
$this->ext = $controller->params['url']['ext'];
if (isset($this->request->params['url']['ext'])) {
$this->ext = $this->request->params['url']['ext'];
}
if (empty($this->ext)) {
$accepts = $this->request->accepts();

View file

@ -17,7 +17,8 @@
* @since CakePHP(tm) v 0.10.8.2156
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('String', 'Security'));
App::import('Core', 'String', false);
App::import('Core', 'Security', false);
/**
* SecurityComponent
@ -618,10 +619,15 @@ class SecurityComponent extends Component {
}
unset($check['_Token']);
$locked = str_rot13($locked);
if (preg_match('/(\A|;|{|})O\:[0-9]+/', $locked)) {
return false;
}
$lockedFields = array();
$fields = Set::flatten($check);
$fieldList = array_keys($fields);
$locked = unserialize(str_rot13($locked));
$locked = unserialize($locked);
$multi = array();
foreach ($fieldList as $i => $key) {

View file

@ -22,8 +22,8 @@
* Include files
*/
App::import('Core', 'CakeResponse', false);
App::import('Core', 'ClassRegistry', false);
App::import('Controller', 'Component', false);
App::import('Core', 'CakeResponse', false);
App::import('View', 'View', false);
/**
@ -415,23 +415,21 @@ class Controller extends Object {
* @return void
*/
protected function __mergeVars() {
$pluginName = Inflector::camelize($this->plugin);
$pluginController = $pluginName . 'AppController';
$pluginName = $pluginController = $plugin = null;
if (is_subclass_of($this, 'AppController') || is_subclass_of($this, $pluginController)) {
if (!empty($this->plugin)) {
$pluginName = Inflector::camelize($this->plugin);
$pluginController = $pluginName . 'AppController';
if (!is_subclass_of($this, $pluginController)) {
$pluginController = null;
}
$plugin = $pluginName . '.';
}
if (is_subclass_of($this, 'AppController') || !empty($pluginController)) {
$appVars = get_class_vars('AppController');
$uses = $appVars['uses'];
$merge = array('components', 'helpers');
$plugin = null;
if (!empty($this->plugin)) {
$plugin = $pluginName . '.';
if (!is_subclass_of($this, $pluginController)) {
$pluginController = null;
}
} else {
$pluginController = null;
}
if ($uses == $this->uses && !empty($this->uses)) {
if (!in_array($plugin . $this->modelClass, $this->uses)) {
@ -443,50 +441,18 @@ class Controller extends Object {
array_unshift($this->uses, $plugin . $this->modelClass);
}
} elseif ($this->uses !== null || $this->uses !== false) {
$merge[] = 'uses';
}
foreach ($merge as $var) {
if (!empty($appVars[$var]) && is_array($this->{$var})) {
if ($var === 'components') {
$normal = Set::normalize($this->{$var});
$app = Set::normalize($appVars[$var]);
if ($app !== $normal) {
$this->{$var} = Set::merge($app, $normal);
}
} else {
$this->{$var} = Set::merge(
$this->{$var}, array_diff($appVars[$var], $this->{$var})
);
}
}
$this->_mergeVars(array('uses'), 'AppController', false);
}
$this->_mergeVars($merge, 'AppController', true);
}
if ($pluginController && $pluginName != null) {
$appVars = get_class_vars($pluginController);
$uses = $appVars['uses'];
$merge = array('components', 'helpers');
if ($this->uses !== null || $this->uses !== false) {
$merge[] = 'uses';
}
foreach ($merge as $var) {
if (isset($appVars[$var]) && !empty($appVars[$var]) && is_array($this->{$var})) {
if ($var === 'components') {
$normal = Set::normalize($this->{$var});
$app = Set::normalize($appVars[$var]);
if ($app !== $normal) {
$this->{$var} = Set::merge($app, $normal);
}
} else {
$this->{$var} = Set::merge(
$this->{$var}, array_diff($appVars[$var], $this->{$var})
);
}
}
$this->_mergeVars(array('uses'), $pluginController, false);
}
$this->_mergeVars($merge, $pluginController);
}
}
@ -627,7 +593,7 @@ class Controller extends Object {
if ($this->persistModel === true) {
$this->_persist($modelClass, true, $this->{$modelClass});
$registry =& ClassRegistry::getInstance();
$registry = ClassRegistry::getInstance();
$this->_persist($modelClass . 'registry', true, $registry->__objects, 'registry');
}
} else {
@ -766,7 +732,7 @@ class Controller extends Object {
*/
public function isAuthorized() {
trigger_error(sprintf(
__('%s::isAuthorized() is not defined.'), $this->name
__('%sController::isAuthorized() is not defined.'), $this->name
), E_USER_WARNING);
return false;
}
@ -1039,7 +1005,7 @@ class Controller extends Object {
), E_USER_WARNING);
return array();
}
$options = array_merge($this->request->params, $this->params['url'], $this->passedArgs);
$options = array_merge($this->request->params, $this->request->query, $this->passedArgs);
if (isset($this->paginate[$object->alias])) {
$defaults = $this->paginate[$object->alias];
@ -1170,11 +1136,11 @@ class Controller extends Object {
'defaults' => array_merge(array('limit' => 20, 'step' => 1), $defaults),
'options' => $options
);
if (!isset($this->request['paging'])) {
$this->request['paging'] = array();
if (!isset($this->request->params['paging'])) {
$this->request->params['paging'] = array();
}
$this->request['paging'] = array_merge(
(array)$this->request['paging'],
$this->request->params['paging'] = array_merge(
(array)$this->request->params['paging'],
array($object->alias => $paging)
);
@ -1254,5 +1220,3 @@ class Controller extends Object {
return false;
}
}
class MissingModelException extends RuntimeException {}

View file

@ -19,6 +19,7 @@
* @since Cake v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('View', 'Scaffold');
/**
* Scaffolding is a set of automatic actions for starting web development work faster.
@ -455,78 +456,3 @@ class Scaffold {
return $associations;
}
}
/**
* Scaffold View.
*
* @package cake
* @subpackage cake.cake.libs.controller
*/
App::import('View', 'Theme');
/**
* ScaffoldView provides specific view file loading features for scaffolded views.
*
* @package cake.libs.view
*/
class ScaffoldView extends ThemeView {
/**
* Override _getViewFileName Appends special scaffolding views in.
*
* @param string $name name of the view file to get.
* @return string action
*/
protected function _getViewFileName($name = null) {
if ($name === null) {
$name = $this->action;
}
$name = Inflector::underscore($name);
$prefixes = Configure::read('Routing.prefixes');
if (!empty($prefixes)) {
foreach ($prefixes as $prefix) {
if (strpos($name, $prefix . '_') !== false) {
$name = substr($name, strlen($prefix) + 1);
break;
}
}
}
if ($name === 'add') {
$name = 'edit';
}
$scaffoldAction = 'scaffold.' . $name;
if (!is_null($this->subDir)) {
$subDir = strtolower($this->subDir) . DS;
} else {
$subDir = null;
}
$names[] = $this->viewPath . DS . $subDir . $scaffoldAction;
$names[] = 'scaffolds' . DS . $subDir . $name;
$paths = $this->_paths($this->plugin);
$exts = array($this->ext);
if ($this->ext !== '.ctp') {
array_push($exts, '.ctp');
}
foreach ($exts as $ext) {
foreach ($paths as $path) {
foreach ($names as $name) {
if (file_exists($path . $name . $ext)) {
return $path . $name . $ext;
}
}
}
}
if ($name === 'scaffolds' . DS . $subDir . 'error') {
return LIBS . 'view' . DS . 'errors' . DS . 'scaffold_error.ctp';
}
throw new MissingViewException($paths[0] . $name . $this->ext);
}
}

View file

@ -180,7 +180,7 @@ class Debugger {
static $instance = array();
if (!empty($class)) {
if (!$instance || strtolower($class) != strtolower(get_class($instance[0]))) {
$instance[0] = & new $class();
$instance[0] = new $class();
if (Configure::read('debug') > 0) {
Configure::version(); // Make sure the core config is loaded
$instance[0]->helpPath = Configure::read('Cake.Debugger.HelpPath');
@ -189,7 +189,7 @@ class Debugger {
}
if (!$instance) {
$instance[0] =& new Debugger();
$instance[0] = new Debugger();
if (Configure::read('debug') > 0) {
Configure::version(); // Make sure the core config is loaded
$instance[0]->helpPath = Configure::read('Cake.Debugger.HelpPath');
@ -236,12 +236,8 @@ class Debugger {
* @param array $context Context
* @return boolean true if error was handled
*/
public function handleError($code, $description, $file = null, $line = null, $context = null) {
if (error_reporting() == 0 || $code === 2048 || $code === 8192) {
return;
}
$_this =& Debugger::getInstance();
public function showError($code, $description, $file = null, $line = null, $context = null) {
$_this = Debugger::getInstance();
if (empty($file)) {
$file = '[internal]';
@ -295,13 +291,7 @@ class Debugger {
$data = compact(
'level', 'error', 'code', 'helpID', 'description', 'file', 'path', 'line', 'context'
);
echo self::_output($data);
if (Configure::read('log')) {
$tpl = $_this->_templates['log']['error'];
$options = array('before' => '{:', 'after' => '}');
CakeLog::write($level, String::insert($tpl, $data, $options));
}
echo $_this->outputError($data);
if ($error == 'Fatal Error') {
exit();
@ -327,7 +317,7 @@ class Debugger {
* @link http://book.cakephp.org/view/1191/Using-the-Debugger-Class
*/
public static function trace($options = array()) {
$_this =& Debugger::getInstance();
$_this = Debugger::getInstance();
$defaults = array(
'depth' => 999,
'format' => $_this->_outputFormat,
@ -551,7 +541,7 @@ class Debugger {
* @param array $strings Template strings to be used for the output format.
*/
public function output($format = null, $strings = array()) {
$_this =& Debugger::getInstance();
$_this = Debugger::getInstance();
$data = null;
if (is_null($format)) {
@ -585,11 +575,12 @@ class Debugger {
}
/**
* Renders error messages
* Takes a processed array of data from an error and displays it in the chosen format.
*
* @param array $data Data about the current error
* @param string $data
* @return void
*/
protected function _output($data = array()) {
public function outputError($data) {
$defaults = array(
'level' => 0,
'error' => 0,
@ -598,13 +589,14 @@ class Debugger {
'description' => '',
'file' => '',
'line' => 0,
'context' => array()
'context' => array(),
'start' => 2
);
$data += $defaults;
$files = $this->trace(array('start' => 2, 'format' => 'points'));
$files = $this->trace(array('start' => $data['start'], 'format' => 'points'));
$code = $this->excerpt($files[0]['file'], $files[0]['line'] - 1, 1);
$trace = $this->trace(array('start' => 2, 'depth' => '20'));
$trace = $this->trace(array('start' => $data['start'], 'depth' => '20'));
$insertOpts = array('before' => '{:', 'after' => '}');
$context = array();
$links = array();
@ -672,20 +664,4 @@ class Debugger {
}
}
/**
* Invokes the given debugger object as the current error handler, taking over control from the
* previous handler in a stack-like hierarchy.
*
* @param object $debugger A reference to the Debugger object
* @access public
* @static
* @link http://book.cakephp.org/view/1191/Using-the-Debugger-Class
*/
function invoke(&$debugger) {
set_error_handler(array(&$debugger, 'handleError'));
}
}
if (!defined('DISABLE_DEFAULT_ERROR_HANDLING')) {
Debugger::invoke(Debugger::getInstance());
}

View file

@ -24,35 +24,21 @@
/**
* List of helpers to include
*/
App::import('Core', array('Router', 'CakeRequest', 'CakeResponse'));
App::import('Core', 'Router', false);
App::import('Core', 'CakeRequest', false);
App::import('Core', 'CakeResponse', false);
App::import('Controller', 'Controller', false);
/**
* Dispatcher translates URLs to controller-action-paramter triads.
*
* Dispatches the request, creating appropriate models and controllers.
* 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
* @subpackage cake.cake
*/
class Dispatcher {
/**
* Base URL
*
* @var string
* @access public
*/
public $base = false;
/**
* webroot path
*
* @var string
* @access public
*/
public $webroot = '/';
/**
* Current URL
*
@ -61,14 +47,6 @@ class Dispatcher {
*/
public $here = false;
/**
* the params for this request
*
* @var string
* @access public
*/
public $params = null;
/**
* The request object
*
@ -97,40 +75,32 @@ class Dispatcher {
}
/**
* Dispatches and invokes given URL, handing over control to the involved controllers, and then renders the
* results (if autoRender is set).
* 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.
*
* If no controller of given name can be found, invoke() shows error messages in
* the form of Missing Controllers information. It does the same with Actions (methods of Controllers are called
* Actions).
* 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.
*
* @param mixed $url Either a string url or a CakeRequest object information to work on. If $url is a string
* It will be used to create the request object.
* 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 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($url = null, $additionalParams = array()) {
if (is_array($url)) {
$url = $this->_extractParams($url, $additionalParams);
}
if ($url instanceof CakeRequest) {
$request = $url;
} else {
$request = new CakeRequest($url);
}
public function dispatch(CakeRequest $request, $additionalParams = array()) {
$this->here = $request->here;
if ($this->asset($request->url) || $this->cached($request->url)) {
return;
}
$request = $this->parseParams($request, $additionalParams);
$this->request = $request;
$controller = $this->_getController();
$controller = $this->_getController($request);
if (!is_object($controller)) {
Router::setRequestInfo($request);
@ -138,6 +108,27 @@ class Dispatcher {
'controller' => Inflector::camelize($request->params['controller']) . 'Controller'
));
}
Router::setRequestInfo($request);
if ($this->_isPrivateAction($request)) {
throw new PrivateActionException(array(
'controller' => Inflector::camelize($request->params['controller']) . "Controller",
'action' => $request->params['action']
));
}
return $this->_invoke($controller, $request);
}
/**
* Check if the request's action is marked as private, with an underscore, of if the request is attempting to
* directly accessing a prefixed action.
*
* @param CakeRequest $request The request to check
* @return boolean
*/
protected function _isPrivateAction($request) {
$privateAction = $request->params['action'][0] === '_';
$prefixes = Router::prefixes();
@ -149,17 +140,7 @@ class Dispatcher {
$privateAction = in_array($prefix, $prefixes);
}
}
Router::setRequestInfo($request);
if ($privateAction) {
throw new PrivateActionException(array(
'controller' => Inflector::camelize($request->params['controller']) . "Controller",
'action' => $request->params['action']
));
}
return $this->_invoke($controller, $request);
return $privateAction;
}
/**
@ -167,18 +148,17 @@ class Dispatcher {
* 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 object $controller Controller to invoke
* @param array $params Parameters with at least the 'action' to invoke
* @param boolean $missingAction Set to true if missing action should be rendered, false otherwise
* @param Controller $controller Controller to invoke
* @param CakeRequest $request The request object to invoke the controller for.
* @return string Output as sent by controller
* @throws MissingActionException when the action being called is missing.
*/
protected function _invoke(&$controller, $request) {
protected function _invoke(Controller $controller, CakeRequest $request) {
$controller->constructClasses();
$controller->startupProcess();
$methods = array_flip($controller->methods);
if (!isset($methods[$request->params['action']])) {
if ($controller->scaffold !== false) {
App::import('Controller', 'Scaffold', false);
@ -189,7 +169,7 @@ class Dispatcher {
'action' => $request->params['action']
));
}
$result =& call_user_func_array(array(&$controller, $request->params['action']), $request->params['pass']);
$result = call_user_func_array(array(&$controller, $request->params['action']), $request->params['pass']);
$response = $controller->getResponse();
if ($controller->autoRender) {
@ -206,32 +186,20 @@ class Dispatcher {
}
/**
* Sets the params when $url is passed as an array to Object::requestAction();
* Merges the $url and $additionalParams and creates a string url.
* 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 array $url Array or request parameters
* @param array $additionalParams Array of additional parameters.
* @return string $url The generated url string.
*/
protected function _extractParams($url, $additionalParams = array()) {
$defaults = array('pass' => array(), 'named' => array(), 'form' => array());
$params = array_merge($defaults, $url, $additionalParams);
$this->params = $params;
$params += array('base' => false, 'url' => array());
return ltrim(Router::reverse($params), '/');
}
/**
* Returns array of GET and POST parameters. GET parameters are taken from given URL.
*
* @param CakeRequest $fromUrl CakeRequest object to mine for parameter information.
* @return array Parameters found in POST and GET.
* @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()) {
$namedExpressions = Router::getNamedExpressions();
extract($namedExpressions);
include CONFIGS . 'routes.php';
if (count(Router::$routes) > 0) {
$namedExpressions = Router::getNamedExpressions();
extract($namedExpressions);
include CONFIGS . 'routes.php';
}
$params = Router::parse($request->url);
$request->addParams($params);
@ -248,17 +216,15 @@ class Dispatcher {
* @param array $params Array of parameters
* @return mixed name of controller if not loaded, or object if loaded
*/
protected function &_getController() {
$controller = false;
$ctrlClass = $this->__loadController($this->request);
protected function _getController($request) {
$ctrlClass = $this->_loadController($request);
if (!$ctrlClass) {
return $controller;
return false;
}
$ctrlClass .= 'Controller';
if (class_exists($ctrlClass)) {
$controller = new $ctrlClass($this->request);
return new $ctrlClass($request);
}
return $controller;
}
/**
@ -266,9 +232,8 @@ class Dispatcher {
*
* @param array $params Array of parameters
* @return string|bool Name of controller class name
* @access private
*/
function __loadController($request) {
protected function _loadController($request) {
$pluginName = $pluginPath = $controller = null;
if (!empty($request->params['plugin'])) {
$pluginName = $controller = Inflector::camelize($request->params['plugin']);

View file

@ -0,0 +1,216 @@
<?php
/**
* Error handler
*
* Provides Error Capturing for Framework errors.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 0.10.5.1732
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
*
* 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 superseed 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/libs.
*
* 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
* @subpackage cake.cake.libs
* @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.
*
* @return void
* @see http://php.net/manual/en/function.set-exception-handler.php
*/
public static function handleException(Exception $exception) {
App::import('Core', 'error/ExceptionRenderer');
$config = Configure::read('Exception');
if (!empty($config['log'])) {
if (!class_exists('CakeLog')) {
require LIBS . 'cake_log.php';
}
CakeLog::write(LOG_ERR, '[' . get_class($exception) . '] ' . $exception->getMessage());
}
if ($config['renderer'] !== 'ExceptionRenderer') {
App::import('Lib', $config['renderer']);
}
$error = new $config['renderer']($exception);
$error->render();
}
/**
* 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) {
if (!class_exists('Debugger')) {
require LIBS . 'debugger.php';
}
$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 {
if (!class_exists('CakeLog')) {
require LIBS . 'cake_log.php';
}
$message = $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
if (!empty($errorConfig['trace'])) {
if (!class_exists('Debugger')) {
require LIBS . 'debugger.php';
}
$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 int $code Error code to map
* @return array Array of error word, and log location.
*/
protected static function _mapErrorCode($code) {
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);
}
}

View file

@ -1,8 +1,9 @@
<?php
/**
* Error handler
* Exception Renderer
*
* Provides Error Capturing for Framework errors.
* Provides Exception rendering features. Which allow exceptions to be rendered
* as HTML pages.
*
* PHP 5
*
@ -16,43 +17,38 @@
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 0.10.5.1732
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Error Handler.
* 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 ErrorHandler does not know about it will be treated as a 500 error.
* and it is a type that ExceptionHandler does not know about it will be treated as a 500 error.
*
* ### Implementing application specific exception handling
* ### Implementing application specific exception rendering
*
* You can implement application specific exception handling in one of a few ways:
*
* - Create a AppController::appError();
* - Create an AppError class.
* - 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 an AppError class
* #### Using a subclass of ExceptionRenderer
*
* This approach gives more flexibility and power in how you handle exceptions. You can create
* `app/libs/app_error.php` and create a class called `AppError`. The core ErrorHandler class
* will attempt to construct this class and let it handle the exception. This provides a more
* flexible way to handle exceptions in your application.
*
* Finally, in your `app/config/bootstrap.php` you can configure use `set_exception_handler()`
* to take total control over application exception handling.
* 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/libs`.
*
* @package cake
* @subpackage cake.cake.libs
*/
class ErrorHandler {
class ExceptionRenderer {
/**
* Controller instance.
@ -118,7 +114,7 @@ class ErrorHandler {
if (Configure::read('debug') == 0) {
$parentClass = get_parent_class($this);
if ($parentClass != 'ErrorHandler') {
if ($parentClass != __CLASS__) {
$method = 'error400';
}
$parentMethods = (array)get_class_methods($parentClass);
@ -157,34 +153,15 @@ class ErrorHandler {
return $controller;
}
/**
* 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 ErrorHandler.
*
* @return void
* @see http://php.net/manual/en/function.set-exception-handler.php
*/
public static function handleException(Exception $exception) {
if (file_exists(APP . 'app_error.php') || class_exists('AppError')) {
if (!class_exists('AppError')) {
require(APP . 'app_error.php');
}
$AppError = new AppError($exception);
return $AppError->render();
}
$error = new ErrorHandler($exception);
$error->render();
}
/**
* Renders the response for the exception.
*
* @return void
*/
public function render() {
call_user_func_array(array($this, $this->method), array($this->error));
if ($this->method) {
call_user_func_array(array($this, $this->method), array($this->error));
}
}
/**
@ -254,4 +231,4 @@ class ErrorHandler {
$this->controller->afterFilter();
$this->controller->response->send();
}
}
}

View file

@ -174,7 +174,7 @@ class CakeException extends RuntimeException {
public function __construct($message, $code = 500) {
if (is_array($message)) {
$this->_attributes = $message;
$message = vsprintf(__($this->_messageTemplate), $message);
$message = __($this->_messageTemplate, $message);
}
parent::__construct($message, $code);
}
@ -301,6 +301,8 @@ class MissingHelperClassException extends CakeException {
/**
* Runtime Exceptions for ConnectionManager
*
* @package cake.libs
*/
class MissingDatabaseException extends CakeException {
protected $_messageTemplate = 'Database connection "%s" could not be found.';
@ -368,3 +370,12 @@ class MissingShellFileException extends CakeException {
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.libs
*/
class MissingModelException extends CakeException {
protected $_messageTemplate = 'Model %s could not be found.';
}

View file

@ -93,7 +93,7 @@ class File {
* @access private
*/
function __construct($path, $create = false, $mode = 0755) {
$this->Folder =& new Folder(dirname($path), $create, $mode);
$this->Folder = new Folder(dirname($path), $create, $mode);
if (!is_dir($path)) {
$this->name = basename($path);
}

View file

@ -244,7 +244,7 @@ class Folder {
* @static
*/
function isWindowsPath($path) {
return (bool)preg_match('/^[A-Z]:\\\\/i', $path);
return (preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) == '\\\\');
}
/**
@ -256,7 +256,7 @@ class Folder {
* @static
*/
function isAbsolute($path) {
return !empty($path) && ($path[0] === '/' || preg_match('/^[A-Z]:\\\\/i', $path));
return !empty($path) && ($path[0] === '/' || preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) == '\\\\');
}
/**
@ -359,11 +359,11 @@ class Folder {
if ($recursive === false && is_dir($path)) {
if (@chmod($path, intval($mode, 8))) {
$this->__messages[] = sprintf(__('%s changed to %s'), $path, $mode);
$this->__messages[] = __('%s changed to %s', $path, $mode);
return true;
}
$this->__errors[] = sprintf(__('%s NOT changed to %s'), $path, $mode);
$this->__errors[] = __('%s NOT changed to %s', $path, $mode);
return false;
}
@ -380,9 +380,9 @@ class Folder {
}
if (@chmod($fullpath, intval($mode, 8))) {
$this->__messages[] = sprintf(__('%s changed to %s'), $fullpath, $mode);
$this->__messages[] = __('%s changed to %s', $fullpath, $mode);
} else {
$this->__errors[] = sprintf(__('%s NOT changed to %s'), $fullpath, $mode);
$this->__errors[] = __('%s NOT changed to %s', $fullpath, $mode);
}
}
}
@ -467,7 +467,7 @@ class Folder {
}
if (is_file($pathname)) {
$this->__errors[] = sprintf(__('%s is a file'), $pathname);
$this->__errors[] = __('%s is a file', $pathname);
return false;
}
$pathname = rtrim($pathname, DS);
@ -478,11 +478,11 @@ class Folder {
$old = umask(0);
if (mkdir($pathname, $mode)) {
umask($old);
$this->__messages[] = sprintf(__('%s created'), $pathname);
$this->__messages[] = __('%s created', $pathname);
return true;
} else {
umask($old);
$this->__errors[] = sprintf(__('%s NOT created'), $pathname);
$this->__errors[] = __('%s NOT created', $pathname);
return false;
}
}
@ -555,9 +555,9 @@ class Folder {
}
if (is_file($file) === true) {
if (@unlink($file)) {
$this->__messages[] = sprintf(__('%s removed'), $file);
$this->__messages[] = __('%s removed', $file);
} else {
$this->__errors[] = sprintf(__('%s NOT removed'), $file);
$this->__errors[] = __('%s NOT removed', $file);
}
} elseif (is_dir($file) === true && $this->delete($file) === false) {
return false;
@ -566,10 +566,10 @@ class Folder {
}
$path = substr($path, 0, strlen($path) - 1);
if (rmdir($path) === false) {
$this->__errors[] = sprintf(__('%s NOT removed'), $path);
$this->__errors[] = __('%s NOT removed', $path);
return false;
} else {
$this->__messages[] = sprintf(__('%s removed'), $path);
$this->__messages[] = __('%s removed', $path);
}
}
return true;
@ -604,7 +604,7 @@ class Folder {
$mode = $options['mode'];
if (!$this->cd($fromDir)) {
$this->__errors[] = sprintf(__('%s not found'), $fromDir);
$this->__errors[] = __('%s not found', $fromDir);
return false;
}
@ -613,7 +613,7 @@ class Folder {
}
if (!is_writable($toDir)) {
$this->__errors[] = sprintf(__('%s not writable'), $toDir);
$this->__errors[] = __('%s not writable', $toDir);
return false;
}
@ -627,9 +627,9 @@ class Folder {
if (copy($from, $to)) {
chmod($to, intval($mode, 8));
touch($to, filemtime($from));
$this->__messages[] = sprintf(__('%s copied to %s'), $from, $to);
$this->__messages[] = __('%s copied to %s', $from, $to);
} else {
$this->__errors[] = sprintf(__('%s NOT copied to %s'), $from, $to);
$this->__errors[] = __('%s NOT copied to %s', $from, $to);
}
}
@ -640,11 +640,11 @@ class Folder {
$old = umask(0);
chmod($to, $mode);
umask($old);
$this->__messages[] = sprintf(__('%s created'), $to);
$this->__messages[] = __('%s created', $to);
$options = array_merge($options, array('to'=> $to, 'from'=> $from));
$this->copy($options);
} else {
$this->__errors[] = sprintf(__('%s not created'), $to);
$this->__errors[] = __('%s not created', $to);
}
}
}

View file

@ -17,7 +17,8 @@
* @since CakePHP(tm) v 1.2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('CakeSocket', 'Set', 'Router'));
App::import('Core', 'CakeSocket');
App::import('Core', 'Router');
/**
* Cake network socket connection class.
@ -146,12 +147,12 @@ class HttpSocket extends CakeSocket {
* You can use a url string to set the url and use default configurations for
* all other options:
*
* `$http =& new HttpSockect('http://cakephp.org/');`
* `$http = new HttpSockect('http://cakephp.org/');`
*
* Or use an array to configure multiple options:
*
* {{{
* $http =& new HttpSocket(array(
* $http = new HttpSocket(array(
* 'host' => 'cakephp.org',
* 'timeout' => 20
* ));
@ -527,7 +528,7 @@ class HttpSocket extends CakeSocket {
if (!is_callable(array(&$this, $decodeMethod))) {
if (!$this->quirksMode) {
trigger_error(sprintf(__('HttpSocket::_decodeBody - Unknown encoding: %s. Activate quirks mode to surpress error.'), h($encoding)), E_USER_WARNING);
trigger_error(__('HttpSocket::_decodeBody - Unknown encoding: %s. Activate quirks mode to surpress error.', h($encoding)), E_USER_WARNING);
}
return array('body' => $body, 'header' => false);
}
@ -824,7 +825,7 @@ class HttpSocket extends CakeSocket {
$request['uri'] = $this->_buildUri($request['uri'], '/%path?%query');
if (!$this->quirksMode && $request['uri'] === '*' && !in_array($request['method'], $asteriskMethods)) {
trigger_error(sprintf(__('HttpSocket::_buildRequestLine - The "*" asterisk character is only allowed for the following methods: %s. Activate quirks mode to work outside of HTTP/1.1 specs.'), join(',', $asteriskMethods)), E_USER_WARNING);
trigger_error(__('HttpSocket::_buildRequestLine - The "*" asterisk character is only allowed for the following methods: %s. Activate quirks mode to work outside of HTTP/1.1 specs.', implode(',', $asteriskMethods)), E_USER_WARNING);
return false;
}
return $request['method'].' '.$request['uri'].' '.$versionToken.$this->lineBreak;

View file

@ -21,7 +21,8 @@
/**
* Included libraries.
*/
App::import('Core', array('l10n', 'Multibyte'));
App::import('Core', 'L10n');
App::import('Core', 'Multibyte');
/**
* I18n handles translation of Text and time format strings.
@ -92,8 +93,8 @@ class I18n {
public static function &getInstance() {
static $instance = array();
if (!$instance) {
$instance[0] =& new I18n();
$instance[0]->l10n =& new L10n();
$instance[0] = new I18n();
$instance[0]->l10n = new L10n();
}
return $instance[0];
}
@ -110,7 +111,7 @@ class I18n {
* @return string translated string.
*/
public static function translate($singular, $plural = null, $domain = null, $category = 6, $count = null) {
$_this =& I18n::getInstance();
$_this = I18n::getInstance();
if (strpos($singular, "\r\n") !== false) {
$singular = str_replace("\r\n", "\n", $singular);
@ -139,11 +140,11 @@ class I18n {
$_this->domain = $domain . '_' . $_this->l10n->lang;
if (empty($_this->__domains[$domain][$_this->__lang])) {
if (!isset($_this->__domains[$domain][$_this->__lang])) {
$_this->__domains[$domain][$_this->__lang] = Cache::read($_this->domain, '_cake_core_');
}
if (empty($_this->__domains[$domain][$_this->__lang][$_this->category])) {
if (!isset($_this->__domains[$domain][$_this->__lang][$_this->category])) {
$_this->__bindTextDomain($domain);
Cache::write($_this->domain, $_this->__domains[$domain][$_this->__lang], '_cake_core_');
}
@ -190,7 +191,7 @@ class I18n {
* @return void
*/
public static function clear() {
$self =& I18n::getInstance();
$self = I18n::getInstance();
$self->__domains = array();
}
@ -200,7 +201,7 @@ class I18n {
* @return array
*/
public static function domains() {
$self =& I18n::getInstance();
$self = I18n::getInstance();
return $self->__domains;
}

View file

@ -17,6 +17,7 @@
* @since CakePHP(tm) v 1.2.0.4116
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'CakeRequest');
/**
* Localization
@ -407,13 +408,8 @@ class L10n {
* @access private
*/
function __autoLanguage() {
$_detectableLanguages = preg_split('/[,;]/', env('HTTP_ACCEPT_LANGUAGE'));
$_detectableLanguages = CakeRequest::acceptLanguage();
foreach ($_detectableLanguages as $key => $langKey) {
$langKey = strtolower($langKey);
if (strpos($langKey, '_') !== false) {
$langKey = str_replace('_', '-', $langKey);
}
if (isset($this->__l10nCatalog[$langKey])) {
$this->__setLanguage($langKey);
return true;

View file

@ -67,9 +67,6 @@ class FileLog implements CakeLogInterface {
$filename = $this->_path . $type . '.log';
}
$output = date('Y-m-d H:i:s') . ' ' . ucfirst($type) . ': ' . $message . "\n";
$log = new SplFileObject($filename, 'a+');
if ($log->isWritable()) {
return $log->fwrite($output);
}
return file_put_contents($filename, $output, FILE_APPEND);
}
}

View file

@ -53,7 +53,7 @@ class MagicDb extends Object {
if (is_array($magicDb) || strpos($magicDb, '# FILE_ID DB') === 0) {
$data = $magicDb;
} else {
$File =& new File($magicDb);
$File = new File($magicDb);
if (!$File->exists()) {
return false;
}
@ -155,7 +155,7 @@ class MagicDb extends Object {
}
$matches = array();
$MagicFileResource =& new MagicFileResource($file);
$MagicFileResource = new MagicFileResource($file);
foreach ($this->db['database'] as $format) {
$magic = $format[0];
$match = $MagicFileResource->test($magic);
@ -201,7 +201,7 @@ class MagicFileResource extends Object{
*/
public function __construct($file) {
if (file_exists($file)) {
$this->resource =& new File($file);
$this->resource = new File($file);
} else {
$this->resource = $file;
}

View file

@ -64,8 +64,8 @@ class BehaviorCollection extends ObjectCollection {
$this->modelName = $modelName;
if (!empty($behaviors)) {
foreach (Set::normalize($behaviors) as $behavior => $config) {
$this->load($behavior, $config);
foreach (BehaviorCollection::normalizeObjectArray($behaviors) as $behavior => $config) {
$this->load($config['class'], $config['settings']);
}
}
}
@ -81,15 +81,16 @@ class BehaviorCollection extends ObjectCollection {
}
/**
* Loads a behavior into the collection.
* 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.
*
* @param string $behavior CamelCased name of the behavior to load
* @param array $config Behavior configuration parameters
* @param boolean $enable Whether or not this helper should be enabled by default
* @return boolean True on success, false on failure
* @throws MissingBehaviorFileException or MissingBehaviorClassException when a behavior could not be found.
*/
public function load($behavior, $config = array(), $enable = true) {
public function load($behavior, $config = array()) {
list($plugin, $name) = pluginSplit($behavior);
$class = $name . 'Behavior';
@ -202,7 +203,7 @@ class BehaviorCollection extends ObjectCollection {
$call = null;
if ($strict && !$found) {
trigger_error(sprintf(__("BehaviorCollection::dispatchMethod() - Method %s not found in any attached behavior"), $method), E_USER_WARNING);
trigger_error(__("BehaviorCollection::dispatchMethod() - Method %s not found in any attached behavior", $method), E_USER_WARNING);
return null;
} elseif ($found) {
$methods = array_combine($methods, array_values($this->__methods));

View file

@ -56,7 +56,7 @@ class AclBehavior extends ModelBehavior {
}
$model->{$type} = ClassRegistry::init($type);
if (!method_exists($model, 'parentNode')) {
trigger_error(sprintf(__('Callback parentNode() not defined in %s'), $model->alias), E_USER_WARNING);
trigger_error(__('Callback parentNode() not defined in %s', $model->alias), E_USER_WARNING);
}
}

View file

@ -121,7 +121,7 @@ class ContainableBehavior extends ModelBehavior {
$mandatory = array();
foreach ($containments['models'] as $name => $model) {
$instance =& $model['instance'];
$instance = $model['instance'];
$needed = $this->fieldDependencies($instance, $map, false);
if (!empty($needed)) {
$mandatory = array_merge($mandatory, $needed);
@ -354,7 +354,7 @@ class ContainableBehavior extends ModelBehavior {
if (!isset($Model->{$name}) || !is_object($Model->{$name})) {
if ($throwErrors) {
trigger_error(sprintf(__('Model "%s" is not associated with model "%s"'), $Model->alias, $name), E_USER_WARNING);
trigger_error(__('Model "%s" is not associated with model "%s"', $Model->alias, $name), E_USER_WARNING);
}
continue;
}
@ -431,7 +431,7 @@ class ContainableBehavior extends ModelBehavior {
public function containmentsMap($containments) {
$map = array();
foreach ($containments['models'] as $name => $model) {
$instance =& $model['instance'];
$instance = $model['instance'];
foreach ($this->types as $type) {
foreach ($instance->{$type} as $assoc => $options) {
if (isset($model['keep'][$assoc])) {

View file

@ -52,10 +52,10 @@ class TranslateBehavior extends ModelBehavior {
* @return mixed
*/
public function setup(&$model, $config = array()) {
$db =& ConnectionManager::getDataSource($model->useDbConfig);
$db = ConnectionManager::getDataSource($model->useDbConfig);
if (!$db->connected) {
trigger_error(
sprintf(__('Datasource %s for TranslateBehavior of model %s is not connected'), $model->useDbConfig, $model->alias),
__('Datasource %s for TranslateBehavior of model %s is not connected', $model->useDbConfig, $model->alias),
E_USER_ERROR
);
return false;
@ -87,12 +87,13 @@ class TranslateBehavior extends ModelBehavior {
* @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 =& ConnectionManager::getDataSource($model->useDbConfig);
$RuntimeModel =& $this->translateModel($model);
$db = ConnectionManager::getDataSource($model->useDbConfig);
$RuntimeModel = $this->translateModel($model);
if (!empty($RuntimeModel->tablePrefix)) {
$tablePrefix = $RuntimeModel->tablePrefix;
} else {
@ -113,48 +114,28 @@ class TranslateBehavior extends ModelBehavior {
);
return $query;
}
$autoFields = false;
if (empty($query['fields'])) {
$query['fields'] = array($model->alias.'.*');
$recursive = $model->recursive;
if (isset($query['recursive'])) {
$recursive = $query['recursive'];
}
if ($recursive >= 0) {
foreach (array('hasOne', 'belongsTo') as $type) {
foreach ($model->{$type} as $key => $value) {
if (empty($value['fields'])) {
$query['fields'][] = $key.'.*';
} else {
foreach ($value['fields'] as $field) {
$query['fields'][] = $key.'.'.$field;
}
}
}
}
}
$autoFields = true;
}
$fields = array_merge($this->settings[$model->alias], $this->runtime[$model->alias]['fields']);
$addFields = array();
if (is_array($query['fields'])) {
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']) || $autoFields || in_array($model->alias.'.'.$field, $query['fields']) || in_array($field, $query['fields'])) {
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 $field) {
foreach (array($field, $model->alias.'.'.$field) as $_field) {
$key = array_search($_field, $query['fields']);
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]);
@ -163,7 +144,10 @@ class TranslateBehavior extends ModelBehavior {
if (is_array($locale)) {
foreach ($locale as $_locale) {
$query['fields'][] = 'I18n__'.$field.'__'.$_locale.'.content';
$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,
@ -171,13 +155,16 @@ class TranslateBehavior extends ModelBehavior {
'conditions' => array(
$model->alias . '.' . $model->primaryKey => $db->identifier("I18n__{$field}__{$_locale}.foreign_key"),
'I18n__'.$field.'__'.$_locale.'.model' => $model->name,
'I18n__'.$field.'__'.$_locale.'.'.$RuntimeModel->displayField => $field,
'I18n__'.$field.'__'.$_locale.'.'.$RuntimeModel->displayField => $aliasField,
'I18n__'.$field.'__'.$_locale.'.locale' => $_locale
)
);
}
} else {
$query['fields'][] = 'I18n__'.$field.'.content';
$model->virtualFields['i18n_'.$field] = 'I18n__'.$field.'.content';
if (!empty($query['fields'])) {
$query['fields'][] = 'i18n_'.$field;
}
$query['joins'][] = array(
'type' => 'LEFT',
'alias' => 'I18n__'.$field,
@ -185,7 +172,7 @@ class TranslateBehavior extends ModelBehavior {
'conditions' => array(
$model->alias . '.' . $model->primaryKey => $db->identifier("I18n__{$field}.foreign_key"),
'I18n__'.$field.'.model' => $model->name,
'I18n__'.$field.'.'.$RuntimeModel->displayField => $field
'I18n__'.$field.'.'.$RuntimeModel->displayField => $aliasField
)
);
@ -197,9 +184,6 @@ class TranslateBehavior extends ModelBehavior {
}
}
}
if (is_array($query['fields'])) {
$query['fields'] = array_merge($query['fields']);
}
$this->runtime[$model->alias]['beforeFind'] = $addFields;
return $query;
}
@ -213,7 +197,8 @@ class TranslateBehavior extends ModelBehavior {
* @return array Modified results
*/
public function afterFind(&$model, $results, $primary) {
$this->runtime[$model->alias]['fields'] = array();
$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'])) {
@ -221,28 +206,30 @@ class TranslateBehavior extends ModelBehavior {
}
$beforeFind = $this->runtime[$model->alias]['beforeFind'];
foreach ($results as $key => $row) {
$results[$key][$model->alias]['locale'] = (is_array($locale)) ? @$locale[0] : $locale;
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;
foreach ($beforeFind as $field) {
if (is_array($locale)) {
foreach ($locale as $_locale) {
if (!isset($results[$key][$model->alias][$field]) && !empty($results[$key]['I18n__'.$field.'__'.$_locale]['content'])) {
$results[$key][$model->alias][$field] = $results[$key]['I18n__'.$field.'__'.$_locale]['content'];
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($results[$key]['I18n__'.$field.'__'.$_locale]);
unset($row[$model->alias]['i18n_'.$field.'_'.$_locale]);
}
if (!isset($results[$key][$model->alias][$field])) {
$results[$key][$model->alias][$field] = '';
if (!isset($row[$model->alias][$aliasField])) {
$row[$model->alias][$aliasField] = '';
}
} else {
$value = '';
if (!empty($results[$key]['I18n__'.$field]['content'])) {
$value = $results[$key]['I18n__'.$field]['content'];
if (!empty($row[$model->alias]['i18n_' . $field])) {
$value = $row[$model->alias]['i18n_' . $field];
}
$results[$key][$model->alias][$field] = $value;
unset($results[$key]['I18n__'.$field]);
$row[$model->alias][$aliasField] = $value;
unset($row[$model->alias]['i18n_' . $field]);
}
}
}
@ -381,8 +368,7 @@ class TranslateBehavior extends ModelBehavior {
} elseif (empty($model->translateTable) && empty($model->translateModel)) {
$this->runtime[$model->alias]['model']->setSource('i18n');
}
$model =& $this->runtime[$model->alias]['model'];
return $model;
return $this->runtime[$model->alias]['model'];
}
/**
@ -439,7 +425,7 @@ class TranslateBehavior extends ModelBehavior {
foreach (array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany') as $type) {
if (isset($model->{$type}[$association]) || isset($model->__backAssociation[$type][$association])) {
trigger_error(
sprintf(__('Association %s is already binded to model %s'), $association, $model->alias),
__('Association %s is already binded to model %s', $association, $model->alias),
E_USER_ERROR
);
return false;

View file

@ -65,7 +65,7 @@ class TreeBehavior extends ModelBehavior {
if (in_array($settings['scope'], $Model->getAssociated('belongsTo'))) {
$data = $Model->getAssociated($settings['scope']);
$parent =& $Model->{$settings['scope']};
$parent = $Model->{$settings['scope']};
$settings['scope'] = $Model->alias . '.' . $data['foreignKey'] . ' = ' . $parent->alias . '.' . $parent->primaryKey;
$settings['recursive'] = 0;
}
@ -599,7 +599,7 @@ class TreeBehavior extends ModelBehavior {
$this->_setParent($Model, $array[$Model->alias][$parent]);
}
} else {
$db =& ConnectionManager::getDataSource($Model->useDbConfig);
$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) {
@ -702,7 +702,7 @@ class TreeBehavior extends ModelBehavior {
$parentNode[$right] = $node[$right] + 1;
}
$db =& ConnectionManager::getDataSource($Model->useDbConfig);
$db = ConnectionManager::getDataSource($Model->useDbConfig);
$Model->updateAll(
array($parent => $db->value($node[$parent], $parent)),
array($Model->escapeField($parent) => $node[$Model->primaryKey])
@ -888,7 +888,7 @@ class TreeBehavior extends ModelBehavior {
* @access private
*/
function __getMax($Model, $scope, $right, $recursive = -1, $created = false) {
$db =& ConnectionManager::getDataSource($Model->useDbConfig);
$db = ConnectionManager::getDataSource($Model->useDbConfig);
if ($created) {
if (is_string($scope)) {
$scope .= " AND {$Model->alias}.{$Model->primaryKey} <> ";
@ -916,7 +916,7 @@ class TreeBehavior extends ModelBehavior {
* @access private
*/
function __getMin($Model, $scope, $left, $recursive = -1) {
$db =& ConnectionManager::getDataSource($Model->useDbConfig);
$db = ConnectionManager::getDataSource($Model->useDbConfig);
$name = $Model->alias . '.' . $left;
list($edge) = array_values($Model->find('first', array(
'conditions' => $scope,

View file

@ -17,7 +17,8 @@
* @since CakePHP(tm) v 1.2.0.5550
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('Model', 'ConnectionManager'));
App::import('Core', 'Model');
App::import('Core', 'ConnectionManager');
/**
* Base Class for Schema management
@ -94,11 +95,7 @@ class CakeSchema extends Object {
}
if (empty($options['path'])) {
if (is_dir(CONFIGS . 'schema')) {
$this->path = CONFIGS . 'schema';
} else {
$this->path = CONFIGS . 'sql';
}
$this->path = CONFIGS . 'schema';
}
$options = array_merge(get_object_vars($this), $options);
@ -160,7 +157,7 @@ class CakeSchema extends Object {
* @param array $options schema object properties
* @return array Set of name and tables
*/
public function &load($options = array()) {
public function load($options = array()) {
if (is_string($options)) {
$options = array('path' => $options);
}
@ -182,8 +179,8 @@ class CakeSchema extends Object {
$Schema = new $class($options);
return $Schema;
}
$false = false;
return $false;
return false;
}
/**
@ -298,7 +295,9 @@ class CakeSchema extends Object {
$systemTables = array(
'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n'
);
if (get_class($Object) === 'AppModel') {
continue;
}
if (in_array($table, $systemTables)) {
$tables[$Object->table] = $this->__columns($Object);
$tables[$Object->table]['indexes'] = $db->index($Object);
@ -586,7 +585,7 @@ class CakeSchema extends Object {
$value['key'] = 'primary';
}
if (!isset($db->columns[$value['type']])) {
trigger_error(sprintf(__('Schema generation error: invalid column type %s does not exist in DBO'), $value['type']), E_USER_NOTICE);
trigger_error(__('Schema generation error: invalid column type %s does not exist in DBO', $value['type']), E_USER_NOTICE);
continue;
} else {
$defaultCol = $db->columns[$value['type']];

View file

@ -60,7 +60,7 @@ class ConnectionManager {
*/
function __construct() {
if (class_exists('DATABASE_CONFIG')) {
$this->config =& new DATABASE_CONFIG();
$this->config = new DATABASE_CONFIG();
$this->_getConnectionObjects();
}
}
@ -74,7 +74,7 @@ class ConnectionManager {
static $instance = array();
if (!$instance) {
$instance[0] =& new ConnectionManager();
$instance[0] = new ConnectionManager();
}
return $instance[0];
@ -87,15 +87,15 @@ class ConnectionManager {
* @return object Instance
*/
public static function &getDataSource($name) {
$_this =& ConnectionManager::getInstance();
$_this = ConnectionManager::getInstance();
if (!empty($_this->_dataSources[$name])) {
$return =& $_this->_dataSources[$name];
$return = $_this->_dataSources[$name];
return $return;
}
if (empty($_this->_connectionsEnum[$name])) {
trigger_error(sprintf(__("ConnectionManager::getDataSource - Non-existent data source %s"), $name), E_USER_ERROR);
trigger_error(__("ConnectionManager::getDataSource - Non-existent data source %s", $name), E_USER_ERROR);
$null = null;
return $null;
}
@ -103,14 +103,14 @@ class ConnectionManager {
$class = $conn['classname'];
if ($_this->loadDataSource($name) === null) {
trigger_error(sprintf(__("ConnectionManager::getDataSource - Could not load class %s"), $class), E_USER_ERROR);
trigger_error(__("ConnectionManager::getDataSource - Could not load class %s", $class), E_USER_ERROR);
$null = null;
return $null;
}
$_this->_dataSources[$name] =& new $class($_this->config->{$name});
$_this->_dataSources[$name] = new $class($_this->config->{$name});
$_this->_dataSources[$name]->configKeyName = $name;
$return =& $_this->_dataSources[$name];
$return = $_this->_dataSources[$name];
return $return;
}
@ -120,7 +120,7 @@ class ConnectionManager {
* @return array List of available connections
*/
public static function sourceList() {
$_this =& ConnectionManager::getInstance();
$_this = ConnectionManager::getInstance();
return array_keys($_this->_dataSources);
}
@ -134,7 +134,7 @@ class ConnectionManager {
* in the ConnectionManager.
*/
public static function getSourceName(&$source) {
$_this =& ConnectionManager::getInstance();
$_this = ConnectionManager::getInstance();
foreach ($_this->_dataSources as $name => $ds) {
if ($ds == $source) {
return $name;
@ -152,7 +152,7 @@ class ConnectionManager {
* @return boolean True on success, null on failure or false if the class is already loaded
*/
public static function loadDataSource($connName) {
$_this =& ConnectionManager::getInstance();
$_this = ConnectionManager::getInstance();
if (is_array($connName)) {
$conn = $connName;
@ -172,7 +172,7 @@ class ConnectionManager {
$class = "{$conn['plugin']}.{$conn['classname']}";
if (!App::import('Datasource', $class, !is_null($conn['plugin']))) {
trigger_error(sprintf(__('ConnectionManager::loadDataSource - Unable to import DataSource class %s'), $class), E_USER_ERROR);
trigger_error(__('ConnectionManager::loadDataSource - Unable to import DataSource class %s', $class), E_USER_ERROR);
return null;
}
return true;
@ -185,7 +185,7 @@ class ConnectionManager {
* (as defined in Connections), and the value is an array with keys 'filename' and 'classname'.
*/
public static function enumConnectionObjects() {
$_this =& ConnectionManager::getInstance();
$_this = ConnectionManager::getInstance();
return $_this->_connectionsEnum;
}
@ -197,7 +197,7 @@ class ConnectionManager {
* @return object A reference to the DataSource object, or null if creation failed
*/
public static function &create($name = '', $config = array()) {
$_this =& ConnectionManager::getInstance();
$_this = ConnectionManager::getInstance();
if (empty($name) || empty($config) || array_key_exists($name, $_this->_connectionsEnum)) {
$null = null;
@ -205,7 +205,7 @@ class ConnectionManager {
}
$_this->config->{$name} = $config;
$_this->_connectionsEnum[$name] = $_this->__connectionData($config);
$return =& $_this->getDataSource($name);
$return = $_this->getDataSource($name);
return $return;
}

View file

@ -263,7 +263,7 @@ class DataSource extends Object {
* @param Model $model
* @return array Array of Metadata for the $model
*/
public function describe(&$model) {
public function describe($model) {
if ($this->cacheSources === false) {
return null;
}
@ -286,7 +286,7 @@ class DataSource extends Object {
*
* @return boolean Returns true if a transaction is not in progress
*/
public function begin(&$model) {
public function begin() {
return !$this->_transactionStarted;
}
@ -295,7 +295,7 @@ class DataSource extends Object {
*
* @return boolean Returns true if a transaction is in progress
*/
public function commit(&$model) {
public function commit() {
return $this->_transactionStarted;
}
@ -304,7 +304,7 @@ class DataSource extends Object {
*
* @return boolean Returns true if a transaction is in progress
*/
public function rollback(&$model) {
public function rollback() {
return $this->_transactionStarted;
}
@ -328,7 +328,7 @@ class DataSource extends Object {
* @param array $values An Array of values to save.
* @return boolean success
*/
public function create(&$model, $fields = null, $values = null) {
public function create($model, $fields = null, $values = null) {
return false;
}
@ -341,7 +341,7 @@ class DataSource extends Object {
* @param array $queryData An array of query data used to find the data you want
* @return mixed
*/
public function read(&$model, $queryData = array()) {
public function read($model, $queryData = array()) {
return false;
}
@ -355,7 +355,7 @@ class DataSource extends Object {
* @param array $values Array of values to be update $fields to.
* @return boolean Success
*/
public function update(&$model, $fields = null, $values = null) {
public function update($model, $fields = null, $values = null) {
return false;
}
@ -367,7 +367,7 @@ class DataSource extends Object {
* @param Model $model The model class having record(s) deleted
* @param mixed $id Primary key of the model
*/
public function delete(&$model, $id = null) {
public function delete($model, $id = null) {
if ($id == null) {
$id = $model->id;
}
@ -556,7 +556,7 @@ class DataSource extends Object {
* @param string $key Key name to make
* @return string Key name for model.
*/
public function resolveKey(&$model, $key) {
public function resolveKey($model, $key) {
return $model->alias . $key;
}

View file

@ -227,7 +227,7 @@ class DboMssql extends DboSource {
* @param Model $model Model object to describe
* @return array Fields in table. Keys are name and type
*/
function describe(&$model) {
function describe($model) {
$cache = parent::describe($model);
if ($cache != null) {
@ -317,7 +317,7 @@ class DboMssql extends DboSource {
* @param mixed $fields
* @return array
*/
function fields(&$model, $alias = null, $fields = array(), $quote = true) {
function fields($model, $alias = null, $fields = array(), $quote = true) {
if (empty($alias)) {
$alias = $model->alias;
}
@ -383,7 +383,7 @@ class DboMssql extends DboSource {
* @param mixed $conditions
* @return array
*/
function create(&$model, $fields = null, $values = null) {
function create($model, $fields = null, $values = null) {
if (!empty($values)) {
$fields = array_combine($fields, $values);
}
@ -413,7 +413,7 @@ class DboMssql extends DboSource {
* @param mixed $conditions
* @return array
*/
function update(&$model, $fields = array(), $values = null, $conditions = null) {
function update($model, $fields = array(), $values = null, $conditions = null) {
if (!empty($values)) {
$fields = array_combine($fields, $values);
}
@ -667,7 +667,7 @@ class DboMssql extends DboSource {
* @param boolean $cache Enables returning/storing cached query results
* @return array Array of resultset rows, or false if no rows matched
*/
function read(&$model, $queryData = array(), $recursive = null) {
function read($model, $queryData = array(), $recursive = null) {
$results = parent::read($model, $queryData, $recursive);
$this->__fieldMappings = array();
return $results;

View file

@ -19,19 +19,42 @@
*/
/**
* Provides common base for MySQL & MySQLi connections
* MySQL DBO driver object
*
* Provides connection and SQL generation for MySQL RDMS
*
* @package cake
* @subpackage cake.cake.libs.model.datasources.dbo
*/
class DboMysqlBase extends DboSource {
class DboMysql extends DboSource {
/**
* Description property.
* Datasource description
*
* @var string
*/
public $description = "MySQL DBO Base Driver";
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
@ -110,49 +133,190 @@ class DboMysqlBase extends DboSource {
'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
*/
function connect() {
$config = $this->config;
$this->connected = false;
try {
$flags = array(
PDO::ATTR_PERSISTENT => $config['persistent'],
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true
);
if (!empty($config['encoding'])) {
$flags[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . $config['encoding'];
}
$this->_connection = new PDO(
"mysql:{$config['host']};port={$config['port']};dbname={$config['database']}",
$config['login'],
$config['password'],
$flags
);
$this->connected = true;
} catch (PDOException $e) {
$this->errors[] = $e->getMessage();
}
$this->_useAlias = (bool)version_compare($this->getVersion(), "4.1", ">=");
return $this->connected;
}
/**
* Check whether the MySQL extension is installed/loaded
*
* @return boolean
*/
function enabled() {
return in_array('mysql', PDO::getAvailableDrivers());
}
/**
* Returns an array of sources (tables) in the database.
*
* @return array Array of tablenames in the database
*/
function listSources($data = null) {
$cache = parent::listSources();
if ($cache != null) {
return $cache;
}
$result = $this->_execute('SHOW TABLES FROM ' . $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
*/
function resultSet($results) {
$this->map = array();
$numFields = $results->columnCount();
$index = 0;
$j = 0;
while ($j < $numFields) {
$column = $results->getColumnMeta($j);
if (!empty($column['table']) && strpos($column['name'], $this->virtualFieldSeparator) === false) {
$this->map[$index++] = array($column['table'], $column['name']);
} else {
$this->map[$index++] = array(0, $column['name']);
}
$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
*/
function fetchResult() {
if ($row = $this->_result->fetch()) {
$resultRow = array();
foreach ($this->map as $col => $meta) {
list($table, $column) = $meta;
$resultRow[$table][$column] = $row[$col];
}
return $resultRow;
} else {
$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 string $tableName Name of database table to inspect
* @param mixed $tableName Name of database table to inspect or model instance
* @return array Fields in table. Keys are name and type
*/
function describe(&$model) {
function describe($model) {
$cache = parent::describe($model);
if ($cache != null) {
return $cache;
}
$fields = false;
$cols = $this->query('SHOW FULL COLUMNS FROM ' . $this->fullTableName($model));
$cols = $this->_execute('SHOW FULL COLUMNS FROM ' . $this->fullTableName($model));
foreach ($cols as $column) {
$colKey = array_keys($column);
if (isset($column[$colKey[0]]) && !isset($column[0])) {
$column[0] = $column[$colKey[0]];
$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];
}
if (isset($column[0])) {
$fields[$column[0]['Field']] = array(
'type' => $this->column($column[0]['Type']),
'null' => ($column[0]['Null'] == 'YES' ? true : false),
'default' => $column[0]['Default'],
'length' => $this->length($column[0]['Type']),
);
if (!empty($column[0]['Key']) && isset($this->index[$column[0]['Key']])) {
$fields[$column[0]['Field']]['key'] = $this->index[$column[0]['Key']];
foreach ($this->fieldParameters as $name => $value) {
if (!empty($column->{$value['column']})) {
$fields[$column->Field][$name] = $column->{$value['column']};
}
foreach ($this->fieldParameters as $name => $value) {
if (!empty($column[0][$value['column']])) {
$fields[$column[0]['Field']][$name] = $column[0][$value['column']];
}
}
if (isset($fields[$column[0]['Field']]['collate'])) {
$charset = $this->getCharsetName($fields[$column[0]['Field']]['collate']);
if ($charset) {
$fields[$column[0]['Field']]['charset'] = $charset;
}
}
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;
}
@ -165,7 +329,7 @@ class DboMysqlBase extends DboSource {
* @param mixed $conditions
* @return array
*/
function update(&$model, $fields = array(), $values = null, $conditions = null) {
function update($model, $fields = array(), $values = null, $conditions = null) {
if (!$this->_useAlias) {
return parent::update($model, $fields, $values, $conditions);
}
@ -207,7 +371,7 @@ class DboMysqlBase extends DboSource {
* @param mixed $conditions
* @return boolean Success
*/
function delete(&$model, $conditions = null) {
function delete($model, $conditions = null) {
if (!$this->_useAlias) {
return parent::delete($model, $conditions);
}
@ -249,26 +413,26 @@ class DboMysqlBase extends DboSource {
function index($model) {
$index = array();
$table = $this->fullTableName($model);
$old = version_compare($this->getVersion(), '4.1', '<=');
if ($table) {
$indexes = $this->query('SHOW INDEX FROM ' . $table);
if (isset($indexes[0]['STATISTICS'])) {
$keys = Set::extract($indexes, '{n}.STATISTICS');
} else {
$keys = Set::extract($indexes, '{n}.0');
}
foreach ($keys as $i => $key) {
if (!isset($index[$key['Key_name']])) {
$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[$key['Key_name']]['column'] = $key['Column_name'];
$index[$key['Key_name']]['unique'] = intval($key['Non_unique'] == 0);
$index[$idx->Key_name]['column'] = $idx->Column_name;
$index[$idx->Key_name]['unique'] = intval($idx->Non_unique == 0);
} else {
if (!is_array($index[$key['Key_name']]['column'])) {
$col[] = $index[$key['Key_name']]['column'];
if (!empty($index[$idx->Key_name]['column']) && !is_array($index[$idx->Key_name]['column'])) {
$col[] = $index[$idx->Key_name]['column'];
}
$col[] = $key['Column_name'];
$index[$key['Key_name']]['column'] = $col;
$col[] = $idx->Column_name;
$index[$idx->Key_name]['column'] = $col;
}
}
$indices->closeCursor();
}
return $index;
}
@ -336,16 +500,12 @@ class DboMysqlBase extends DboSource {
/**
* Generate a MySQL "drop table" statement for the given Schema object
*
* @param object $schema An instance of a subclass of CakeSchema
* @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
*/
function dropSchema($schema, $table = null) {
if (!is_a($schema, 'CakeSchema')) {
trigger_error(__('Invalid schema object'), E_USER_WARNING);
return null;
}
function dropSchema(CakeSchema $schema, $table = null) {
$out = '';
foreach ($schema->tables as $curTable => $columns) {
if (!$table || $table == $curTable) {
@ -412,21 +572,6 @@ class DboMysqlBase extends DboSource {
return $alter;
}
/**
* Inserts multiple values into a table
*
* @param string $table
* @param string $fields
* @param array $values
*/
function insertMulti($table, $fields, $values) {
$table = $this->fullTableName($table);
if (is_array($fields)) {
$fields = implode(', ', array_map(array(&$this, 'name'), $fields));
}
$values = implode(', ', $values);
$this->query("INSERT INTO {$table} ({$fields}) VALUES {$values}");
}
/**
* Returns an detailed array of sources (tables) in the database.
*
@ -435,23 +580,29 @@ class DboMysqlBase extends DboSource {
*/
function listDetailedSources($name = null) {
$condition = '';
$params = array();
if (is_string($name)) {
$condition = ' LIKE ' . $this->value($name);
$condition = ' WHERE name = ?' ;
$params = array($name);
}
$result = $this->query('SHOW TABLE STATUS FROM ' . $this->name($this->config['database']) . $condition . ';');
$result = $this->_execute('SHOW TABLE STATUS ' . $condition, $params);
if (!$result) {
$result->closeCursor();
return array();
} else {
$tables = array();
foreach ($result as $row) {
$tables[$row['TABLES']['Name']] = $row['TABLES'];
if (!empty($row['TABLES']['Collation'])) {
$charset = $this->getCharsetName($row['TABLES']['Collation']);
while ($row = $result->fetch()) {
$tables[$row->Name] = (array) $row;
unset($tables[$row->Name]['queryString']);
if (!empty($row->Collation)) {
$charset = $this->getCharsetName($row->Collation);
if ($charset) {
$tables[$row['TABLES']['Name']]['charset'] = $charset;
$tables[$row->Name]['charset'] = $charset;
}
}
}
$result->closeCursor();
if (is_string($name)) {
return $tables[$name];
}
@ -507,292 +658,3 @@ class DboMysqlBase extends DboSource {
return 'text';
}
}
/**
* MySQL DBO driver object
*
* Provides connection and SQL generation for MySQL RDMS
*
* @package cake
* @subpackage cake.cake.libs.model.datasources.dbo
*/
class DboMysql extends DboMysqlBase {
/**
* 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'
);
/**
* Connects to the database using options in the given configuration array.
*
* @return boolean True if the database could be connected, else false
*/
function connect() {
$config = $this->config;
$this->connected = false;
if (!$config['persistent']) {
$this->connection = mysql_connect($config['host'] . ':' . $config['port'], $config['login'], $config['password'], true);
$config['connect'] = 'mysql_connect';
} else {
$this->connection = mysql_pconnect($config['host'] . ':' . $config['port'], $config['login'], $config['password']);
}
if (mysql_select_db($config['database'], $this->connection)) {
$this->connected = true;
}
if (!empty($config['encoding'])) {
$this->setEncoding($config['encoding']);
}
$this->_useAlias = (bool)version_compare(mysql_get_server_info($this->connection), "4.1", ">=");
return $this->connected;
}
/**
* Check whether the MySQL extension is installed/loaded
*
* @return boolean
*/
function enabled() {
return extension_loaded('mysql');
}
/**
* Disconnects from database.
*
* @return boolean True if the database could be disconnected, else false
*/
function disconnect() {
if (isset($this->results) && is_resource($this->results)) {
mysql_free_result($this->results);
}
$this->connected = !@mysql_close($this->connection);
return !$this->connected;
}
/**
* Executes given SQL statement.
*
* @param string $sql SQL statement
* @return resource Result resource identifier
*/
protected function _execute($sql) {
return mysql_query($sql, $this->connection);
}
/**
* Returns an array of sources (tables) in the database.
*
* @return array Array of tablenames in the database
*/
function listSources() {
$cache = parent::listSources();
if ($cache != null) {
return $cache;
}
$result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']) . ';');
if (!$result) {
return array();
} else {
$tables = array();
while ($line = mysql_fetch_row($result)) {
$tables[] = $line[0];
}
parent::listSources($tables);
return $tables;
}
}
/**
* 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
* @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
* @return string Quoted and escaped data
*/
function value($data, $column = null, $safe = false) {
$parent = parent::value($data, $column, $safe);
if ($parent != null) {
return $parent;
}
if ($data === null || (is_array($data) && empty($data))) {
return 'NULL';
}
if ($data === '' && $column !== 'integer' && $column !== 'float' && $column !== 'boolean') {
return "''";
}
if (empty($column)) {
$column = $this->introspectType($data);
}
switch ($column) {
case 'boolean':
return $this->boolean((bool)$data);
break;
case 'integer':
case 'float':
if ($data === '') {
return 'NULL';
}
if (is_float($data)) {
return sprintf('%F', $data);
}
if ((is_int($data) || $data === '0') || (
is_numeric($data) && strpos($data, ',') === false &&
$data[0] != '0' && strpos($data, 'e') === false)
) {
return $data;
}
default:
return "'" . mysql_real_escape_string($data, $this->connection) . "'";
break;
}
}
/**
* Returns a formatted error message from previous database operation.
*
* @return string Error message with error number
*/
function lastError() {
if (mysql_errno($this->connection)) {
return mysql_errno($this->connection).': '.mysql_error($this->connection);
}
return null;
}
/**
* Returns number of affected rows in previous database operation. If no previous operation exists,
* this returns false.
*
* @return integer Number of affected rows
*/
function lastAffected() {
if ($this->_result) {
return mysql_affected_rows($this->connection);
}
return null;
}
/**
* Returns number of rows in previous resultset. If no previous resultset exists,
* this returns false.
*
* @return integer Number of rows in resultset
*/
function lastNumRows() {
if ($this->hasResult()) {
return mysql_num_rows($this->_result);
}
return null;
}
/**
* Returns the ID generated from the previous INSERT operation.
*
* @param unknown_type $source
* @return in
*/
function lastInsertId($source = null) {
$id = $this->fetchRow('SELECT LAST_INSERT_ID() AS insertID', false);
if ($id !== false && !empty($id) && !empty($id[0]) && isset($id[0]['insertID'])) {
return $id[0]['insertID'];
}
return null;
}
/**
* Enter description here...
*
* @param unknown_type $results
*/
function resultSet(&$results) {
if (isset($this->results) && is_resource($this->results) && $this->results != $results) {
mysql_free_result($this->results);
}
$this->results =& $results;
$this->map = array();
$numFields = mysql_num_fields($results);
$index = 0;
$j = 0;
while ($j < $numFields) {
$column = mysql_fetch_field($results, $j);
if (!empty($column->table) && strpos($column->name, $this->virtualFieldSeparator) === false) {
$this->map[$index++] = array($column->table, $column->name);
} else {
$this->map[$index++] = array(0, $column->name);
}
$j++;
}
}
/**
* Fetches the next row from the current result set
*
* @return unknown
*/
function fetchResult() {
if ($row = mysql_fetch_row($this->results)) {
$resultRow = array();
$i = 0;
foreach ($row as $index => $field) {
list($table, $column) = $this->map[$index];
$resultRow[$table][$column] = $row[$index];
$i++;
}
return $resultRow;
} else {
return false;
}
}
/**
* Gets the database encoding
*
* @return string The database encoding
*/
function getEncoding() {
return mysql_client_encoding($this->connection);
}
/**
* Query charset by collation
*
* @param string $name Collation name
* @return string Character set name
*/
function getCharsetName($name) {
if ((bool)version_compare(mysql_get_server_info($this->connection), "5", ">=")) {
$cols = $this->query('SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME= ' . $this->value($name) . ';');
if (isset($cols[0]['COLLATIONS']['CHARACTER_SET_NAME'])) {
return $cols[0]['COLLATIONS']['CHARACTER_SET_NAME'];
}
}
return false;
}
}

View file

@ -1,336 +0,0 @@
<?php
/**
* MySQLi layer for DBO
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake.libs.model.datasources.dbo
* @since CakePHP(tm) v 1.1.4.2974
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Datasource', 'DboMysql');
/**
* MySQLi DBO driver object
*
* Provides connection and SQL generation for MySQL RDMS using PHP's MySQLi Interface
*
* @package cake
* @subpackage cake.cake.libs.model.datasources.dbo
*/
class DboMysqli extends DboMysqlBase {
/**
* Datasource Description
*
* @var string
*/
public $description = "Mysqli DBO Driver";
/**
* Base configuration settings for Mysqli driver
*
* @var array
*/
protected $_baseConfig = array(
'persistent' => true,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'cake',
'port' => '3306'
);
/**
* Connects to the database using options in the given configuration array.
*
* @return boolean True if the database could be connected, else false
*/
function connect() {
$config = $this->config;
$this->connected = false;
if (is_numeric($config['port'])) {
$config['socket'] = null;
} else {
$config['socket'] = $config['port'];
$config['port'] = null;
}
$this->connection = mysqli_connect($config['host'], $config['login'], $config['password'], $config['database'], $config['port'], $config['socket']);
if ($this->connection !== false) {
$this->connected = true;
}
$this->_useAlias = (bool)version_compare(mysqli_get_server_info($this->connection), "4.1", ">=");
if (!empty($config['encoding'])) {
$this->setEncoding($config['encoding']);
}
return $this->connected;
}
/**
* Check that MySQLi is installed/enabled
*
* @return boolean
*/
function enabled() {
return extension_loaded('mysqli');
}
/**
* Disconnects from database.
*
* @return boolean True if the database could be disconnected, else false
*/
function disconnect() {
if (isset($this->results) && is_resource($this->results)) {
mysqli_free_result($this->results);
}
$this->connected = !@mysqli_close($this->connection);
return !$this->connected;
}
/**
* Executes given SQL statement.
*
* @param string $sql SQL statement
* @return resource Result resource identifier
*/
protected function _execute($sql) {
if (preg_match('/^\s*call/i', $sql)) {
return $this->_executeProcedure($sql);
}
return mysqli_query($this->connection, $sql);
}
/**
* Executes given SQL statement (procedure call).
*
* @param string $sql SQL statement (procedure call)
* @return resource Result resource identifier for first recordset
*/
protected function _executeProcedure($sql) {
$answer = mysqli_multi_query($this->connection, $sql);
$firstResult = mysqli_store_result($this->connection);
if (mysqli_more_results($this->connection)) {
while ($lastResult = mysqli_next_result($this->connection));
}
return $firstResult;
}
/**
* Returns an array of sources (tables) in the database.
*
* @return array Array of tablenames in the database
*/
function listSources() {
$cache = parent::listSources();
if ($cache !== null) {
return $cache;
}
$result = $this->_execute('SHOW TABLES FROM ' . $this->name($this->config['database']) . ';');
if (!$result) {
return array();
}
$tables = array();
while ($line = mysqli_fetch_row($result)) {
$tables[] = $line[0];
}
parent::listSources($tables);
return $tables;
}
/**
* 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
* @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
* @return string Quoted and escaped data
*/
function value($data, $column = null, $safe = false) {
$parent = parent::value($data, $column, $safe);
if ($parent != null) {
return $parent;
}
if ($data === null || (is_array($data) && empty($data))) {
return 'NULL';
}
if ($data === '' && $column !== 'integer' && $column !== 'float' && $column !== 'boolean') {
return "''";
}
if (empty($column)) {
$column = $this->introspectType($data);
}
switch ($column) {
case 'boolean':
return $this->boolean((bool)$data);
break;
case 'integer' :
case 'float' :
case null :
if ($data === '') {
return 'NULL';
}
if ((is_int($data) || is_float($data) || $data === '0') || (
is_numeric($data) && strpos($data, ',') === false &&
$data[0] != '0' && strpos($data, 'e') === false)) {
return $data;
}
default:
$data = "'" . mysqli_real_escape_string($this->connection, $data) . "'";
break;
}
return $data;
}
/**
* Returns a formatted error message from previous database operation.
*
* @return string Error message with error number
*/
function lastError() {
if (mysqli_errno($this->connection)) {
return mysqli_errno($this->connection).': '.mysqli_error($this->connection);
}
return null;
}
/**
* Returns number of affected rows in previous database operation. If no previous operation exists,
* this returns false.
*
* @return integer Number of affected rows
*/
function lastAffected() {
if ($this->_result) {
return mysqli_affected_rows($this->connection);
}
return null;
}
/**
* Returns number of rows in previous resultset. If no previous resultset exists,
* this returns false.
*
* @return integer Number of rows in resultset
*/
function lastNumRows() {
if ($this->hasResult()) {
return mysqli_num_rows($this->_result);
}
return null;
}
/**
* Returns the ID generated from the previous INSERT operation.
*
* @param unknown_type $source
* @return in
*/
function lastInsertId($source = null) {
$id = $this->fetchRow('SELECT LAST_INSERT_ID() AS insertID', false);
if ($id !== false && !empty($id) && !empty($id[0]) && isset($id[0]['insertID'])) {
return $id[0]['insertID'];
}
return null;
}
/**
* Enter description here...
*
* @param unknown_type $results
*/
function resultSet(&$results) {
if (isset($this->results) && is_resource($this->results) && $this->results != $results) {
mysqli_free_result($this->results);
}
$this->results =& $results;
$this->map = array();
$numFields = mysqli_num_fields($results);
$index = 0;
$j = 0;
while ($j < $numFields) {
$column = mysqli_fetch_field_direct($results, $j);
if (!empty($column->table)) {
$this->map[$index++] = array($column->table, $column->name);
} else {
$this->map[$index++] = array(0, $column->name);
}
$j++;
}
}
/**
* Fetches the next row from the current result set
*
* @return unknown
*/
function fetchResult() {
if ($row = mysqli_fetch_row($this->results)) {
$resultRow = array();
foreach ($row as $index => $field) {
$table = $column = null;
if (count($this->map[$index]) === 2) {
list($table, $column) = $this->map[$index];
}
$resultRow[$table][$column] = $row[$index];
}
return $resultRow;
}
return false;
}
/**
* Gets the database encoding
*
* @return string The database encoding
*/
function getEncoding() {
return mysqli_client_encoding($this->connection);
}
/**
* Query charset by collation
*
* @param string $name Collation name
* @return string Character set name
*/
function getCharsetName($name) {
if ((bool)version_compare(mysqli_get_server_info($this->connection), "5", ">=")) {
$cols = $this->query('SELECT CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLLATIONS WHERE COLLATION_NAME= ' . $this->value($name) . ';');
if (isset($cols[0]['COLLATIONS']['CHARACTER_SET_NAME'])) {
return $cols[0]['COLLATIONS']['CHARACTER_SET_NAME'];
}
}
return false;
}
/**
* Checks if the result is valid
*
* @return boolean True if the result is valid, else false
*/
function hasResult() {
return is_object($this->_result);
}
}

View file

@ -478,7 +478,7 @@ class DboOracle extends DboSource {
* @param object instance of a model to inspect
* @return array Fields in table. Keys are name and type
*/
public function describe(&$model) {
public function describe($model) {
$table = $this->fullTableName($model, false);
if (!empty($model->sequence)) {
@ -974,11 +974,11 @@ class DboOracle extends DboSource {
* @param integer $recursive Number of levels of association
* @param array $stack
*/
function queryAssociation(&$model, &$linkModel, $type, $association, $assocData, &$queryData, $external = false, &$resultSet, $recursive, $stack) {
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 (!isset($resultSet) || !is_array($resultSet)) {
if (Configure::read('debug') > 0) {
echo '<div style = "font: Verdana bold 12px; color: #FF0000">' . sprintf(__('SQL Error in model %s:'), $model->alias) . ' ';
echo '<div style = "font: Verdana bold 12px; color: #FF0000">' . __('SQL Error in model %s:', $model->alias) . ' ';
if (isset($this->error) && $this->error != null) {
echo $this->error;
}
@ -1121,16 +1121,12 @@ class DboOracle extends DboSource {
/**
* Generate a "drop table" statement for the given Schema object
*
* @param object $schema An instance of a subclass of CakeSchema
* @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
*/
function dropSchema($schema, $table = null) {
if (!is_a($schema, 'CakeSchema')) {
trigger_error(__('Invalid schema object'), E_USER_WARNING);
return null;
}
function dropSchema(CakeSchema $schema, $table = null) {
$out = '';
foreach ($schema->tables as $curTable => $columns) {

View file

@ -112,23 +112,29 @@ class DboPostgres extends DboSource {
*/
function connect() {
$config = $this->config;
$conn = "host='{$config['host']}' port='{$config['port']}' dbname='{$config['database']}' ";
$conn .= "user='{$config['login']}' password='{$config['password']}'";
if (!$config['persistent']) {
$this->connection = pg_connect($conn, PGSQL_CONNECT_FORCE_NEW);
} else {
$this->connection = pg_pconnect($conn);
}
$this->connected = false;
try {
$flags = array(
PDO::ATTR_PERSISTENT => $config['persistent']
);
$this->_connection = new PDO(
"pgsql:host={$config['host']};port={$config['port']};dbname={$config['database']}",
$config['login'],
$config['password'],
$flags
);
if ($this->connection) {
$this->connected = true;
$this->_execute("SET search_path TO " . $config['schema']);
}
if (!empty($config['encoding'])) {
$this->setEncoding($config['encoding']);
if (!empty($config['encoding'])) {
$this->setEncoding($config['encoding']);
}
if (!empty($config['schema'])) {
$this->_execute('SET search_path TO ' . $config['schema']);
}
} catch (PDOException $e) {
$this->errors[] = $e->getMessage();
}
return $this->connected;
}
@ -138,33 +144,7 @@ class DboPostgres extends DboSource {
* @return boolean
*/
function enabled() {
return extension_loaded('pgsql');
}
/**
* Disconnects from database.
*
* @return boolean True if the database could be disconnected, else false
*/
function disconnect() {
if ($this->hasResult()) {
pg_free_result($this->_result);
}
if (is_resource($this->connection)) {
$this->connected = !pg_close($this->connection);
} else {
$this->connected = false;
}
return !$this->connected;
}
/**
* Executes given SQL statement.
*
* @param string $sql SQL statement
* @return resource Result resource identifier
*/
function _execute($sql) {
return pg_query($this->connection, $sql);
return in_array('pgsql', PDO::getAvailableDrivers());
}
/**
@ -172,7 +152,7 @@ class DboPostgres extends DboSource {
*
* @return array Array of tablenames in the database
*/
function listSources() {
function listSources($data = null) {
$cache = parent::listSources();
if ($cache != null) {
@ -180,18 +160,20 @@ class DboPostgres extends DboSource {
}
$schema = $this->config['schema'];
$sql = "SELECT table_name as name FROM INFORMATION_SCHEMA.tables WHERE table_schema = '{$schema}';";
$result = $this->fetchAll($sql, false);
$sql = "SELECT table_name as name FROM INFORMATION_SCHEMA.tables WHERE table_schema = ?";
$result = $this->_execute($sql, array($schema));
if (!$result) {
$result->closeCursor();
return array();
} else {
$tables = array();
foreach ($result as $item) {
$tables[] = $item[0]['name'];
$tables[] = $item->name;
}
$result->closeCursor();
parent::listSources($tables);
return $tables;
}
@ -203,67 +185,62 @@ class DboPostgres extends DboSource {
* @param string $tableName Name of database table to inspect
* @return array Fields in table. Keys are name and type
*/
function &describe(&$model) {
function describe($model) {
$fields = parent::describe($model);
$table = $this->fullTableName($model, false);
$this->_sequenceMap[$table] = array();
if ($fields === null) {
$cols = $this->fetchAll(
$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 = " . $this->value($table) . " AND table_schema = " .
$this->value($this->config['schema'])." ORDER BY position",
false
WHERE table_name = ? AND table_schema = ? ORDER BY position",
array($table, $this->config['schema'])
);
foreach ($cols as $column) {
$colKey = array_keys($column);
if (isset($column[$colKey[0]]) && !isset($column[0])) {
$column[0] = $column[$colKey[0]];
}
if (isset($column[0])) {
$c = $column[0];
if (!empty($c['char_length'])) {
$length = intval($c['char_length']);
} elseif (!empty($c['oct_length'])) {
if ($c['type'] == 'character varying') {
$length = null;
$c['type'] = 'text';
} else {
$length = intval($c['oct_length']);
}
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 = $this->length($c['type']);
$length = intval($c->oct_length);
}
$fields[$c['name']] = array(
'type' => $this->column($c['type']),
'null' => ($c['null'] == 'NO' ? false : true),
'default' => preg_replace(
"/^'(.*)'$/",
"$1",
preg_replace('/::.*/', '', $c['default'])
),
'length' => $length
);
if ($c['name'] == $model->primaryKey) {
$fields[$c['name']]['key'] = 'primary';
if ($fields[$c['name']]['type'] !== 'string') {
$fields[$c['name']]['length'] = 11;
} 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['name']] = $seq[1];
}
}
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];
}
}
}
@ -272,93 +249,11 @@ class DboPostgres extends DboSource {
if (isset($model->sequence)) {
$this->_sequenceMap[$table][$model->primaryKey] = $model->sequence;
}
$cols->closeCursor();
return $fields;
}
/**
* 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
* @param boolean $read Value to be used in READ or WRITE context
* @return string Quoted and escaped
* @todo Add logic that formats/escapes data based on column type
*/
function value($data, $column = null, $read = true) {
$parent = parent::value($data, $column);
if ($parent != null) {
return $parent;
}
if ($data === null || (is_array($data) && empty($data))) {
return 'NULL';
}
if (empty($column)) {
$column = $this->introspectType($data);
}
switch($column) {
case 'binary':
$data = pg_escape_bytea($data);
break;
case 'boolean':
if ($data === true || $data === 't' || $data === 'true') {
return 'TRUE';
} elseif ($data === false || $data === 'f' || $data === 'false') {
return 'FALSE';
}
return (!empty($data) ? 'TRUE' : 'FALSE');
break;
case 'float':
if (is_float($data)) {
$data = sprintf('%F', $data);
}
case 'inet':
case 'integer':
case 'date':
case 'datetime':
case 'timestamp':
case 'time':
if ($data === '') {
return $read ? 'NULL' : 'DEFAULT';
}
default:
$data = pg_escape_string($data);
break;
}
return "'" . $data . "'";
}
/**
* Returns a formatted error message from previous database operation.
*
* @return string Error message
*/
function lastError() {
$error = pg_last_error($this->connection);
return ($error) ? $error : null;
}
/**
* Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
*
* @return integer Number of affected rows
*/
function lastAffected() {
return ($this->_result) ? pg_affected_rows($this->_result) : false;
}
/**
* Returns number of rows in previous resultset. If no previous resultset exists,
* this returns false.
*
* @return integer Number of rows in resultset
*/
function lastNumRows() {
return ($this->_result) ? pg_num_rows($this->_result) : false;
}
/**
* Returns the ID generated from the previous INSERT operation.
*
@ -368,8 +263,7 @@ class DboPostgres extends DboSource {
*/
function lastInsertId($source, $field = 'id') {
$seq = $this->getSequence($source, $field);
$data = $this->fetchRow("SELECT currval('{$seq}') as max");
return $data[0]['max'];
return $this->_connection->lastInsertId($seq);
}
/**
@ -394,20 +288,22 @@ class DboPostgres extends DboSource {
* 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 integer $reset If -1, sequences are dropped, if 0 (default), sequences are reset,
* @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) {
public function truncate($table, $reset = true) {
$table = $this->fullTableName($table, false);
if (!isset($this->_sequenceMap[$table])) {
$cache = $this->cacheSources;
$this->cacheSources = false;
$this->describe($table);
$this->cacheSources = $cache;
}
if (parent::truncate($table)) {
$table = $this->fullTableName($table, false);
if (isset($this->_sequenceMap[$table]) && $reset !== 1) {
if (isset($this->_sequenceMap[$table]) && $reset) {
foreach ($this->_sequenceMap[$table] as $field => $sequence) {
if ($reset === 0) {
$this->execute("ALTER SEQUENCE \"{$sequence}\" RESTART WITH 1");
} elseif ($reset === -1) {
$this->execute("DROP SEQUENCE IF EXISTS \"{$sequence}\"");
}
$this->_execute("ALTER SEQUENCE \"{$sequence}\" RESTART WITH 1");
}
}
return true;
@ -436,7 +332,7 @@ class DboPostgres extends DboSource {
* @param mixed $fields
* @return array
*/
function fields(&$model, $alias = null, $fields = array(), $quote = true) {
function fields($model, $alias = null, $fields = array(), $quote = true) {
if (empty($alias)) {
$alias = $model->alias;
}
@ -447,7 +343,7 @@ class DboPostgres extends DboSource {
}
$count = count($fields);
if ($count >= 1 && strpos($fields[0], 'COUNT(*)') === false) {
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])) {
@ -781,20 +677,18 @@ class DboPostgres extends DboSource {
* @param unknown_type $results
*/
function resultSet(&$results) {
$this->results =& $results;
$this->map = array();
$num_fields = pg_num_fields($results);
$numFields = $results->columnCount();
$index = 0;
$j = 0;
while ($j < $num_fields) {
$columnName = pg_field_name($results, $j);
if (strpos($columnName, '__')) {
$parts = explode('__', $columnName);
$this->map[$index++] = array($parts[0], $parts[1]);
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, $columnName);
$this->map[$index++] = array(0, $column['name'], $column['native_type']);
}
$j++;
}
@ -806,12 +700,11 @@ class DboPostgres extends DboSource {
* @return unknown
*/
function fetchResult() {
if ($row = pg_fetch_row($this->results)) {
if ($row = $this->_result->fetch()) {
$resultRow = array();
foreach ($row as $index => $field) {
list($table, $column) = $this->map[$index];
$type = pg_field_type($this->results, $index);
foreach ($this->map as $index => $meta) {
list($table, $column, $type) = $meta;
switch ($type) {
case 'bool':
@ -819,7 +712,7 @@ class DboPostgres extends DboSource {
break;
case 'binary':
case 'bytea':
$resultRow[$table][$column] = pg_unescape_bytea($row[$index]);
$resultRow[$table][$column] = stream_get_contents($row[$index]);
break;
default:
$resultRow[$table][$column] = $row[$index];
@ -828,6 +721,7 @@ class DboPostgres extends DboSource {
}
return $resultRow;
} else {
$this->_result->closeCursor();
return false;
}
}
@ -835,24 +729,33 @@ class DboPostgres extends DboSource {
/**
* Translates between PHP boolean values and PostgreSQL boolean values
*
* @param mixed $data Value to be translated
* @param boolean $quote True to quote value, false otherwise
* @return mixed Converted boolean value
* @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
*/
function boolean($data, $quote = true) {
switch (true) {
case ($data === true || $data === false):
return $data;
$result = $data;
break;
case ($data === 't' || $data === 'f'):
return ($data === 't');
$result = ($data === 't');
break;
case ($data === 'true' || $data === 'false'):
return ($data === 'true');
$result = ($data === 'true');
break;
case ($data === 'TRUE' || $data === 'FALSE'):
return ($data === 'TRUE');
$result = ($data === 'TRUE');
break;
default:
return (bool)$data;
$result = (bool) $data;
break;
}
if ($quote) {
return ($result) ? 'TRUE' : 'FALSE';
}
return (int) $result;
}
/**
@ -862,7 +765,10 @@ class DboPostgres extends DboSource {
* @return boolean True on success, false on failure
*/
function setEncoding($enc) {
return pg_set_client_encoding($this->connection, $enc) == 0;
if ($this->_execute('SET NAMES ?', array($enc))) {
return true;
}
return false;
}
/**
@ -871,7 +777,7 @@ class DboPostgres extends DboSource {
* @return string The database encoding
*/
function getEncoding() {
return pg_client_encoding($this->connection);
$cosa = $this->_execute('SHOW client_encoding')->fetch();
}
/**

View file

@ -19,11 +19,11 @@
*/
/**
* DBO implementation for the SQLite DBMS.
* DBO implementation for the SQLite3 DBMS.
*
* Long description for class
* A DboSource adapter for SQLite 3 using PDO
*
* @package cake
* @package datasources
* @subpackage cake.cake.libs.model.datasources.dbo
*/
class DboSqlite extends DboSource {
@ -32,63 +32,48 @@ class DboSqlite extends DboSource {
* Datasource Description
*
* @var string
* @access public
*/
public $description = "SQLite DBO Driver";
var $description = "SQLite DBO Driver";
/**
* Opening quote for quoted identifiers
* Quote Start
*
* @var string
* @access public
*/
public $startQuote = '"';
var $startQuote = '"';
/**
* Closing quote for quoted identifiers
* Quote End
*
* @var string
* @access public
*/
public $endQuote = '"';
var $endQuote = '"';
/**
* Keeps the transaction statistics of CREATE/UPDATE/DELETE queries
* Base configuration settings for SQLite3 driver
*
* @var array
* @access protected
* @access public
*/
protected $_queryStats = array();
/**
* Base configuration settings for SQLite driver
*
* @var array
*/
protected $_baseConfig = array(
'persistent' => true,
var $_baseConfig = array(
'persistent' => false,
'database' => null
);
/**
* Index of basic SQL commands
* SQLite3 column definition
*
* @var array
* @access protected
* @access public
*/
protected $_commands = array(
'begin' => 'BEGIN TRANSACTION',
'commit' => 'COMMIT TRANSACTION',
'rollback' => 'ROLLBACK TRANSACTION'
);
/**
* SQLite column definition
*
* @var array
*/
public $columns = array(
'primary_key' => array('name' => 'integer primary key'),
var $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' => 11, 'formatter' => 'intval'),
'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'),
@ -104,12 +89,12 @@ class DboSqlite extends DboSource {
* @var array
* @access public
*/
public $fieldParameters = array(
var $fieldParameters = array(
'collate' => array(
'value' => 'COLLATE',
'quote' => false,
'join' => ' ',
'column' => 'Collate',
'join' => ' ',
'column' => 'Collate',
'position' => 'afterDefault',
'options' => array(
'BINARY', 'NOCASE', 'RTRIM'
@ -122,83 +107,46 @@ class DboSqlite extends DboSource {
*
* @param array $config Configuration array for connecting
* @return mixed
* @access public
*/
function connect() {
$config = $this->config;
if (!$config['persistent']) {
$this->connection = sqlite_open($config['database']);
} else {
$this->connection = sqlite_popen($config['database']);
$flags = array(PDO::ATTR_PERSISTENT => $config['persistent']);
try {
$this->_connection = new PDO('sqlite:' . $config['database'], null, null, $flags);
$this->_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connected = true;
}
$this->connected = is_resource($this->connection);
if ($this->connected) {
$this->_execute('PRAGMA count_changes = 1;');
catch(PDOException $e) {
$this->errors[] = $e->getMessage();
}
return $this->connected;
}
/**
* Check that SQLite is enabled/installed
* Check whether the MySQL extension is installed/loaded
*
* @return boolean
*/
function enabled() {
return extension_loaded('sqlite');
}
/**
* Disconnects from database.
*
* @return boolean True if the database could be disconnected, else false
*/
function disconnect() {
@sqlite_close($this->connection);
$this->connected = false;
return $this->connected;
}
/**
* Executes given SQL statement.
*
* @param string $sql SQL statement
* @return resource Result resource identifier
*/
function _execute($sql) {
$result = sqlite_query($this->connection, $sql);
if (preg_match('/^(INSERT|UPDATE|DELETE)/', $sql)) {
$this->resultSet($result);
list($this->_queryStats) = $this->fetchResult();
}
return $result;
}
/**
* Overrides DboSource::execute() to correctly handle query statistics
*
* @param string $sql
* @return unknown
*/
function execute($sql) {
$result = parent::execute($sql);
$this->_queryStats = array();
return $result;
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.
*
* @return array Array of tablenames in the database
* @access public
*/
function listSources() {
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 (empty($result)) {
if (!$result || empty($result)) {
return array();
} else {
$tables = array();
@ -216,72 +164,40 @@ class DboSqlite extends DboSource {
*
* @param string $tableName Name of database table to inspect
* @return array Fields in table. Keys are name and type
* @access public
*/
function describe(&$model) {
function describe($model) {
$cache = parent::describe($model);
if ($cache != null) {
return $cache;
}
$fields = array();
$result = $this->fetchAll('PRAGMA table_info(' . $this->fullTableName($model) . ')');
$result = $this->_execute('PRAGMA table_info(' . $model->tablePrefix . $model->table . ')');
foreach ($result as $column) {
$fields[$column[0]['name']] = array(
'type' => $this->column($column[0]['type']),
'null' => !$column[0]['notnull'],
'default' => $column[0]['dflt_value'],
'length' => $this->length($column[0]['type'])
$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[0]['pk'] == 1) {
$colLength = $this->length($column[0]['type']);
$fields[$column[0]['name']] = array(
'type' => $fields[$column[0]['name']]['type'],
'null' => false,
'default' => $column[0]['dflt_value'],
'key' => $this->index['PRI'],
'length'=> ($colLength != null) ? $colLength : 11
);
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($model->tablePrefix . $model->table, $fields);
return $fields;
}
/**
* 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
* @return string Quoted and escaped
*/
function value($data, $column = null, $safe = false) {
$parent = parent::value($data, $column, $safe);
if ($parent != null) {
return $parent;
}
if ($data === null) {
return 'NULL';
}
if ($data === '' && $column !== 'integer' && $column !== 'float' && $column !== 'boolean') {
return "''";
}
switch ($column) {
case 'boolean':
$data = $this->boolean((bool)$data);
break;
case 'integer':
case 'float':
if ($data === '') {
return 'NULL';
}
default:
$data = sqlite_escape_string($data);
break;
}
return "'" . $data . "'";
}
/**
* Generates and executes an SQL UPDATE statement for given model, fields, and values.
*
@ -290,8 +206,9 @@ class DboSqlite extends DboSource {
* @param array $values
* @param mixed $conditions
* @return array
* @access public
*/
function update(&$model, $fields = array(), $values = null, $conditions = null) {
function update($model, $fields = array(), $values = null, $conditions = null) {
if (empty($values) && !empty($fields)) {
foreach ($fields as $field => $value) {
if (strpos($field, $model->alias . '.') !== false) {
@ -302,8 +219,7 @@ class DboSqlite extends DboSource {
}
}
}
$result = parent::update($model, $fields, $values, $conditions);
return $result;
return parent::update($model, $fields, $values, $conditions);
}
/**
@ -312,60 +228,11 @@ class DboSqlite extends DboSource {
*
* @param mixed $table A string or model class representing the table to be truncated
* @return boolean SQL TRUNCATE TABLE statement, false if not applicable.
* @access public
*/
public function truncate($table) {
return $this->execute('DELETE From ' . $this->fullTableName($table));
}
/**
* Returns a formatted error message from previous database operation.
*
* @return string Error message
*/
function lastError() {
$error = sqlite_last_error($this->connection);
if ($error) {
return $error.': '.sqlite_error_string($error);
}
return null;
}
/**
* Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
*
* @return integer Number of affected rows
*/
function lastAffected() {
if (!empty($this->_queryStats)) {
foreach (array('rows inserted', 'rows updated', 'rows deleted') as $key) {
if (array_key_exists($key, $this->_queryStats)) {
return $this->_queryStats[$key];
}
}
}
return false;
}
/**
* Returns number of rows in previous resultset. If no previous resultset exists,
* this returns false.
*
* @return integer Number of rows in resultset
*/
function lastNumRows() {
if ($this->hasResult()) {
sqlite_num_rows($this->_result);
}
return false;
}
/**
* Returns the ID generated from the previous INSERT operation.
*
* @return int
*/
function lastInsertId() {
return sqlite_last_insert_rowid($this->connection);
function truncate($table) {
$this->_execute('DELETE FROM sqlite_sequence where name=' . $this->fullTableName($table));
return $this->execute('DELETE FROM ' . $this->fullTableName($table));
}
/**
@ -373,6 +240,7 @@ class DboSqlite extends DboSource {
*
* @param string $real Real database-layer column type (i.e. "varchar(255)")
* @return string Abstract column type (i.e. "string")
* @access public
*/
function column($real) {
if (is_array($real)) {
@ -385,9 +253,7 @@ class DboSqlite extends DboSource {
$col = strtolower(str_replace(')', '', $real));
$limit = null;
if (strpos($col, '(') !== false) {
list($col, $limit) = explode('(', $col);
}
@list($col, $limit) = explode('(', $col);
if (in_array($col, array('text', 'integer', 'float', 'boolean', 'timestamp', 'date', 'datetime', 'time'))) {
return $col;
@ -398,29 +264,55 @@ class DboSqlite extends DboSource {
if (in_array($col, array('blob', 'clob'))) {
return 'binary';
}
if (strpos($col, 'numeric') !== false) {
if (strpos($col, 'numeric') !== false || strpos($col, 'decimal') !== false) {
return 'float';
}
return 'text';
}
/**
* Enter description here...
* Generate ResultSet
*
* @param unknown_type $results
* @param mixed $results
* @access public
*/
function resultSet(&$results) {
$this->results =& $results;
function resultSet($results) {
$this->results = $results;
$this->map = array();
$fieldCount = sqlite_num_fields($results);
$index = $j = 0;
$num_fields = $results->columnCount();
$index = 0;
$j = 0;
while ($j < $fieldCount) {
$columnName = str_replace('"', '', sqlite_field_name($results, $j));
//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 = stripos($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 (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);
}
if (strpos($columnName, '.')) {
$parts = explode('.', $columnName);
$this->map[$index++] = array($parts[0], $parts[1]);
$this->map[$index++] = array(trim($parts[0]), trim($parts[1]));
} else {
$this->map[$index++] = array(0, $columnName);
}
@ -431,34 +323,30 @@ class DboSqlite extends DboSource {
/**
* Fetches the next row from the current result set
*
* @return unknown
* @return mixed array with results fetched and mapped to column names or false if there is no results left to fetch
*/
function fetchResult() {
if ($row = sqlite_fetch_array($this->results, SQLITE_ASSOC)) {
if ($row = $this->_result->fetch()) {
$resultRow = array();
$i = 0;
foreach ($row as $index => $field) {
if (strpos($index, '.')) {
list($table, $column) = explode('.', str_replace('"', '', $index));
$resultRow[$table][$column] = $row[$index];
} else {
$resultRow[0][str_replace('"', '', $index)] = $row[$index];
}
$i++;
foreach ($this->map as $col => $meta) {
list($table, $column) = $meta;
$resultRow[$table][$column] = $row[$col];
}
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
* @access public
*/
function limit($limit, $offset = null) {
if ($limit) {
@ -479,8 +367,9 @@ class DboSqlite extends DboSource {
* 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'.
* where options can be 'default', 'length', or 'key'.
* @return string
* @access public
*/
function buildColumn($column) {
$name = $type = null;
@ -488,12 +377,12 @@ class DboSqlite extends DboSource {
extract($column);
if (empty($name) || empty($type)) {
trigger_error(__('Column name or type not defined in schema'), E_USER_WARNING);
trigger_error('Column name or type not defined in schema', E_USER_WARNING);
return null;
}
if (!isset($this->columns[$type])) {
trigger_error(sprintf(__('Column type %s does not exist'), $type), E_USER_WARNING);
trigger_error(__('Column type %s does not exist', $type), E_USER_WARNING);
return null;
}
@ -509,6 +398,7 @@ class DboSqlite extends DboSource {
* Sets the database encoding
*
* @param string $enc Database encoding
* @access public
*/
function setEncoding($enc) {
if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) {
@ -521,6 +411,7 @@ class DboSqlite extends DboSource {
* Gets the database encoding
*
* @return string The database encoding
* @access public
*/
function getEncoding() {
return $this->fetchRow('PRAGMA encoding');
@ -532,6 +423,7 @@ class DboSqlite extends DboSource {
* @param array $indexes
* @param string $table
* @return string
* @access public
*/
function buildIndex($indexes, $table = null) {
$join = array();
@ -547,11 +439,12 @@ class DboSqlite extends DboSource {
$out .= 'UNIQUE ';
}
if (is_array($value['column'])) {
$value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
$value['column'] = join(', ', array_map(array(&$this, 'name'), $value['column']));
} else {
$value['column'] = $this->name($value['column']);
}
$out .= "INDEX {$name} ON {$table}({$value['column']});";
$t = trim($table, '"');
$out .= "INDEX {$t}_{$name} ON {$table}({$value['column']});";
$join[] = $out;
}
return $join;
@ -563,13 +456,17 @@ class DboSqlite extends DboSource {
*
* @param string $model Name of model to inspect
* @return array Fields in table. Keys are column and unique
* @access public
*/
function index(&$model) {
function index($model) {
$index = array();
$table = $this->fullTableName($model);
if ($table) {
$indexes = $this->query('PRAGMA index_list(' . $table . ')');
$tableInfo = $this->query('PRAGMA table_info(' . $table . ')');
if (is_bool($indexes)) {
return array();
}
foreach ($indexes as $i => $info) {
$key = array_pop($info);
$keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")');
@ -600,16 +497,17 @@ class DboSqlite extends DboSource {
* @param string $type
* @param array $data
* @return string
* @access public
*/
function renderStatement($type, $data) {
switch (strtolower($type)) {
case 'schema':
extract($data);
foreach (array('columns', 'indexes') as $var) {
if (is_array(${$var})) {
${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
}
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;
@ -618,4 +516,32 @@ class DboSqlite extends DboSource {
break;
}
}
/**
* PDO deals in objects, not resources, so overload accordingly.
*
* @return boolean
* @access public
*/
function hasResult() {
return is_object($this->_result);
}
/**
* Generate a "drop table" statement for the given Schema object
*
* @param object $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;
}
}

View file

@ -17,7 +17,7 @@
* @since CakePHP(tm) v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('Set', 'String'));
App::import('Core', 'String');
/**
* DboSource
@ -88,6 +88,14 @@ class DboSource extends DataSource {
*/
private $__sqlOps = array('like', 'ilike', 'or', 'not', 'in', 'between', 'regexp', 'similar to');
/**
* Indicates the level of nested transactions
*
* @var integer
* @access protected
*/
protected $_transactionNesting = 0;
/**
* Index of basic SQL commands
*
@ -160,18 +168,42 @@ class DboSource extends DataSource {
}
/**
* Prepares a value, or an array of values for database queries by quoting and escaping them.
* Disconnects from database.
*
* @param mixed $data A value or an array of values to prepare.
* @param string $column The column into which this data will be inserted
* @param boolean $read Value to be used in READ or WRITE context
* @return mixed Prepared value or array of values.
* @return boolean True if the database could be disconnected, else false
*/
public function value($data, $column = null, $read = true) {
function disconnect() {
if ($this->_result instanceof PDOStatement) {
$this->_result->closeCursor();
}
unset($this->_connection);
$this->connected = false;
return !$this->connected;
}
/**
* 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
* @param boolean $safe Whether or not numeric data should be handled automagically if no column data is provided
* @return string Quoted and escaped data
*/
function value($data, $column = null, $safe = false) {
if (is_array($data) && !empty($data)) {
return array_map(
array(&$this, 'value'),
$data, array_fill(0, count($data), $column), array_fill(0, count($data), $read)
$data, array_fill(0, count($data), $column), array_fill(0, count($data), $safe)
);
} elseif (is_object($data) && isset($data->type)) {
if ($data->type == 'identifier') {
@ -181,11 +213,45 @@ class DboSource extends DataSource {
}
} elseif (in_array($data, array('{$__cakeID__$}', '{$__cakeForeignKey__$}'), true)) {
return $data;
} else {
return null;
}
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), 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 sprintf('%F', $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
*
@ -218,9 +284,9 @@ class DboSource extends DataSource {
* @param string $sql SQL statement
* @return boolean
*/
public function rawQuery($sql) {
public function rawQuery($sql, $params = array()) {
$this->took = $this->error = $this->numRows = false;
return $this->execute($sql);
return $this->execute($sql, $params);
}
/**
@ -230,28 +296,23 @@ class DboSource extends DataSource {
*
* ### Options
*
* - stats - Collect meta data stats for this query. Stats include time take, rows affected,
* any errors, and number of rows returned. Defaults to `true`.
* - 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()) {
$defaults = array('stats' => true, 'log' => $this->fullDebug);
$options = array_merge($defaults, $options);
public function execute($sql, $options = array(), $params = array()) {
$options = $options + array('log' => $this->fullDebug);
$this->error = null;
$t = microtime(true);
$this->_result = $this->_execute($sql);
if ($options['stats']) {
$this->took = round((microtime(true) - $t) * 1000, 0);
$this->affected = $this->lastAffected();
$this->error = $this->lastError();
$this->numRows = $this->lastNumRows();
}
$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);
}
@ -262,6 +323,83 @@ class DboSource extends DataSource {
return $this->_result;
}
/**
* Executes given SQL statement.
*
* @param string $sql SQL statement
* @param array $params list of params to be bound to query
* @return PDOStatement if query executes with no problem, true as the result of a succesfull
* query returning no rows, suchs as a CREATE statement, false otherwise
*/
protected function _execute($sql, $params = 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);
$query->setFetchMode(PDO::FETCH_LAZY);
if (!$query->execute($params)) {
$this->_results = $query;
$this->error = $this->lastError($query);
$query->closeCursor();
return false;
}
if (!$query->columnCount()) {
$query->closeCursor();
return true;
}
return $query;
} catch (PDOException $e) {
$this->_results = null;
$this->error = $e->getMessage();
return false;
}
}
/**
* 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
*/
function lastError(PDOStatement $query = null) {
$error = $query->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.
*
* @return integer Number of affected rows
*/
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.
*
* @return integer Number of rows in resultset
*/
function lastNumRows($source = null) {
return $this->lastAffected($source);
}
/**
* DataSource Query abstraction
*
@ -278,14 +416,14 @@ class DboSource extends DataSource {
if (count($args) == 1) {
return $this->fetchAll($args[0]);
} elseif (count($args) > 1 && (strpos(strtolower($args[0]), 'findby') === 0 || strpos(strtolower($args[0]), 'findallby') === 0)) {
} elseif (count($args) > 1 && (strpos($args[0], 'findBy') === 0 || strpos($args[0], 'findAllBy') === 0)) {
$params = $args[1];
if (strpos(strtolower($args[0]), 'findby') === 0) {
$all = false;
if (strpos($args[0], 'findBy') === 0) {
$all = false;
$field = Inflector::underscore(preg_replace('/^findBy/i', '', $args[0]));
} else {
$all = true;
$all = true;
$field = Inflector::underscore(preg_replace('/^findAllBy/i', '', $args[0]));
}
@ -352,8 +490,7 @@ class DboSource extends DataSource {
} else {
$cache = true;
}
$args[1] = array_map(array(&$this, 'value'), $args[1]);
return $this->fetchAll(String::insert($args[0], $args[1]), $cache);
return $this->fetchAll($args[0], $args[1], array('cache' => $cache));
}
}
}
@ -386,16 +523,31 @@ class DboSource extends DataSource {
* 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
*
* @param string $sql SQL statement
* @param boolean $cache Enables returning/storing cached query results
* @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, $cache = true, $modelName = null) {
if ($cache && ($cached = $this->getQueryCache($sql)) !== false) {
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();
}
$defaults = array('cache' => true);
$options = $options + $defaults;
$cache = $options['cache'];
if ($cache && ($cached = $this->getQueryCache($sql, $params)) !== false) {
return $cached;
}
if ($this->execute($sql)) {
if ($result = $this->execute($sql, array(), $params)) {
$out = array();
$first = $this->fetchRow();
@ -407,9 +559,10 @@ class DboSource extends DataSource {
$out[] = $item;
}
if ($cache) {
$this->_writeQueryCache($sql, $out);
if (!is_bool($result) && $cache) {
$this->_writeQueryCache($sql, $out, $params);
}
if (empty($out) && is_bool($this->_result)) {
return $this->_result;
}
@ -576,7 +729,7 @@ class DboSource extends DataSource {
* @return boolean True if the result is valid else false
*/
public function hasResult() {
return is_resource($this->_result);
return is_a($this->_result, 'PDOStatement');
}
/**
@ -612,7 +765,7 @@ class DboSource extends DataSource {
if (PHP_SAPI != 'cli') {
App::import('Core', 'View');
$controller = null;
$View =& new View($controller, false);
$View = new View($controller, false);
$View->set('logs', array($this->configKeyName => $log));
echo $View->element('sql_dump', array('_forced_from_dbo_' => true));
} else {
@ -662,7 +815,7 @@ class DboSource extends DataSource {
if ($error) {
trigger_error('<span style="color:Red;text-align:left"><b>' . __('SQL Error:') . "</b> {$this->error}</span>", E_USER_WARNING);
} else {
$out = ('<small>[' . sprintf(__('Aff:%s Num:%s Took:%sms'), $this->affected, $this->numRows, $this->took) . ']</small>');
$out = ('<small>[' . __('Aff:%s Num:%s Took:%sms', $this->affected, $this->numRows, $this->took) . ']</small>');
}
pr(sprintf('<p style="text-align:left"><b>' . __('Query:') . '</b> %s %s</p>', $sql, $out));
}
@ -701,7 +854,7 @@ class DboSource extends DataSource {
* be used to generate values.
* @return boolean Success
*/
public function create(&$model, $fields = null, $values = null) {
public function create($model, $fields = null, $values = null) {
$id = null;
if ($fields == null) {
@ -749,7 +902,7 @@ class DboSource extends DataSource {
* @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, $queryData = array(), $recursive = null) {
public function read($model, $queryData = array(), $recursive = null) {
$queryData = $this->__scrubQueryData($queryData);
$null = null;
@ -784,7 +937,7 @@ class DboSource extends DataSource {
foreach ($_associations as $type) {
foreach ($model->{$type} as $assoc => $assocData) {
$linkModel =& $model->{$assoc};
$linkModel = $model->{$assoc};
$external = isset($assocData['external']);
if ($model->useDbConfig == $linkModel->useDbConfig) {
@ -795,9 +948,9 @@ class DboSource extends DataSource {
}
}
$query = $this->generateAssociationQuery($model, $null, null, null, null, $queryData, false, $null);
$query = trim($this->generateAssociationQuery($model, $null, null, null, null, $queryData, false, $null));
$resultSet = $this->fetchAll($query, $model->cacheQueries, $model->alias);
$resultSet = $this->fetchAll($query, $model->cacheQueries);
if ($resultSet === false) {
$model->onError();
@ -809,16 +962,16 @@ class DboSource extends DataSource {
if ($model->recursive > -1) {
foreach ($_associations as $type) {
foreach ($model->{$type} as $assoc => $assocData) {
$linkModel =& $model->{$assoc};
$linkModel = $model->{$assoc};
if (empty($linkedModels[$type . '/' . $assoc])) {
if ($model->useDbConfig == $linkModel->useDbConfig) {
$db =& $this;
$db = $this;
} else {
$db =& ConnectionManager::getDataSource($linkModel->useDbConfig);
$db = ConnectionManager::getDataSource($linkModel->useDbConfig);
}
} elseif ($model->recursive > 1 && ($type == 'belongsTo' || $type == 'hasOne')) {
$db =& $this;
$db = $this;
}
if (isset($db) && method_exists($db, 'queryAssociation')) {
@ -893,11 +1046,11 @@ class DboSource extends DataSource {
* @param integer $recursive Number of levels of association
* @param array $stack
*/
public function queryAssociation(&$model, &$linkModel, $type, $association, $assocData, &$queryData, $external = false, &$resultSet, $recursive, $stack) {
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 (!isset($resultSet) || !is_array($resultSet)) {
if (Configure::read('debug') > 0) {
echo '<div style = "font: Verdana bold 12px; color: #FF0000">' . sprintf(__('SQL Error in model %s:'), $model->alias) . ' ';
echo '<div style = "font: Verdana bold 12px; color: #FF0000">' . __('SQL Error in model %s:', $model->alias) . ' ';
if (isset($this->error) && $this->error != null) {
echo $this->error;
}
@ -924,14 +1077,14 @@ class DboSource extends DataSource {
if ($recursive > 0) {
foreach ($linkModel->associations() as $type1) {
foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
$deepModel =& $linkModel->{$assoc1};
$deepModel = $linkModel->{$assoc1};
$tmpStack = $stack;
$tmpStack[] = $assoc1;
if ($linkModel->useDbConfig === $deepModel->useDbConfig) {
$db =& $this;
$db = $this;
} else {
$db =& ConnectionManager::getDataSource($deepModel->useDbConfig);
$db = ConnectionManager::getDataSource($deepModel->useDbConfig);
}
$db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
}
@ -966,7 +1119,7 @@ class DboSource extends DataSource {
$q = $this->insertQueryData($query, null, $association, $assocData, $model, $linkModel, $stack);
if ($q != false) {
$fetch = $this->fetchAll($q, $model->cacheQueries, $model->alias);
$fetch = $this->fetchAll($q, $model->cacheQueries);
} else {
$fetch = null;
}
@ -978,7 +1131,7 @@ class DboSource extends DataSource {
if ($type !== 'hasAndBelongsToMany') {
$q = $this->insertQueryData($query, $resultSet[$i], $association, $assocData, $model, $linkModel, $stack);
if ($q != false) {
$fetch = $this->fetchAll($q, $model->cacheQueries, $model->alias);
$fetch = $this->fetchAll($q, $model->cacheQueries);
} else {
$fetch = null;
}
@ -993,15 +1146,15 @@ class DboSource extends DataSource {
if ($recursive > 0) {
foreach ($linkModel->associations() as $type1) {
foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
$deepModel =& $linkModel->{$assoc1};
$deepModel = $linkModel->{$assoc1};
if (($type1 === 'belongsTo') || ($deepModel->alias === $model->alias && $type === 'belongsTo') || ($deepModel->alias != $model->alias)) {
$tmpStack = $stack;
$tmpStack[] = $assoc1;
if ($linkModel->useDbConfig == $deepModel->useDbConfig) {
$db =& $this;
$db = $this;
} else {
$db =& ConnectionManager::getDataSource($deepModel->useDbConfig);
$db = ConnectionManager::getDataSource($deepModel->useDbConfig);
}
$db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
}
@ -1053,7 +1206,7 @@ class DboSource extends DataSource {
if (count($ids) > 1) {
$query = str_replace('= (', 'IN (', $query);
}
return $this->fetchAll($query, $model->cacheQueries, $model->alias);
return $this->fetchAll($query, $model->cacheQueries);
}
/**
@ -1189,7 +1342,7 @@ class DboSource extends DataSource {
* @param array $resultSet
* @return mixed
*/
public function generateAssociationQuery(&$model, &$linkModel, $type, $association = null, $assocData = array(), &$queryData, $external = false, &$resultSet) {
public function generateAssociationQuery($model, &$linkModel, $type, $association = null, $assocData = array(), &$queryData, $external = false, &$resultSet) {
$queryData = $this->__scrubQueryData($queryData);
$assocData = $this->__scrubQueryData($assocData);
@ -1422,7 +1575,7 @@ class DboSource extends DataSource {
* @access public
* @see DboSource::renderStatement()
*/
public function buildStatement($query, &$model) {
public function buildStatement($query, $model) {
$query = array_merge(array('offset' => null, 'joins' => array()), $query);
if (!empty($query['joins'])) {
$count = count($query['joins']);
@ -1541,7 +1694,7 @@ class DboSource extends DataSource {
* @param mixed $conditions
* @return boolean Success
*/
public function update(&$model, $fields = array(), $values = null, $conditions = null) {
public function update($model, $fields = array(), $values = null, $conditions = null) {
if ($values == null) {
$combined = $fields;
} else {
@ -1575,7 +1728,7 @@ class DboSource extends DataSource {
* @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) {
protected function _prepareUpdateFields($model, $fields, $quoteValues = true, $alias = false) {
$quotedAlias = $this->startQuote . $model->alias . $this->endQuote;
$updates = array();
@ -1618,7 +1771,7 @@ class DboSource extends DataSource {
* @param mixed $conditions
* @return boolean Success
*/
public function delete(&$model, $conditions = null) {
public function delete($model, $conditions = null) {
$alias = $joins = null;
$table = $this->fullTableName($model);
$conditions = $this->_matchRecords($model, $conditions);
@ -1642,7 +1795,7 @@ class DboSource extends DataSource {
* @param mixed $conditions
* @return array List of record IDs
*/
protected function _matchRecords(&$model, $conditions = null) {
protected function _matchRecords($model, $conditions = null) {
if ($conditions === true) {
$conditions = $this->conditions(true);
} elseif ($conditions === null) {
@ -1718,7 +1871,7 @@ class DboSource extends DataSource {
* @param array $params Function parameters (any values must be quoted manually)
* @return string An SQL calculation function
*/
public function calculate(&$model, $func, $params = array()) {
public function calculate($model, $func, $params = array()) {
$params = (array)$params;
switch (strtolower($func)) {
@ -1764,14 +1917,14 @@ class DboSource extends DataSource {
/**
* Begin a transaction
*
* @param model $model
* @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(&$model) {
if (parent::begin($model) && $this->execute($this->_commands['begin'])) {
public function begin() {
if ($this->_transactionStarted || $this->_connection->beginTransaction()) {
$this->_transactionStarted = true;
$this->_transactionNesting++;
return true;
}
return false;
@ -1780,14 +1933,18 @@ class DboSource extends DataSource {
/**
* Commit a transaction
*
* @param model $model
* @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(&$model) {
if (parent::commit($model) && $this->execute($this->_commands['commit'])) {
$this->_transactionStarted = false;
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;
@ -1796,19 +1953,29 @@ class DboSource extends DataSource {
/**
* Rollback a transaction
*
* @param model $model
* @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(&$model) {
if (parent::rollback($model) && $this->execute($this->_commands['rollback'])) {
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 unknown_type $source
* @return in
*/
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
@ -1823,7 +1990,7 @@ class DboSource extends DataSource {
* @see DboSource::update()
* @see DboSource::conditions()
*/
public function defaultConditions(&$model, $conditions, $useAlias = true) {
public function defaultConditions($model, $conditions, $useAlias = true) {
if (!empty($conditions)) {
return $conditions;
}
@ -1882,7 +2049,7 @@ class DboSource extends DataSource {
* @param mixed $fields virtual fields to be used on query
* @return array
*/
protected function _constructVirtualFields(&$model, $alias, $fields) {
protected function _constructVirtualFields($model, $alias, $fields) {
$virtual = array();
foreach ($fields as $field) {
$virtualField = $this->name($alias . $this->virtualFieldSeparator . $field);
@ -1901,7 +2068,7 @@ class DboSource extends DataSource {
* @param boolean $quote If false, returns fields array unquoted
* @return array
*/
public function fields(&$model, $alias = null, $fields = array(), $quote = true) {
public function fields($model, $alias = null, $fields = array(), $quote = true) {
if (empty($alias)) {
$alias = $model->alias;
}
@ -2194,7 +2361,7 @@ class DboSource extends DataSource {
* @return string
* @access private
*/
function __parseKey(&$model, $key, $value) {
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));
@ -2445,7 +2612,7 @@ class DboSource extends DataSource {
* @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) {
public function hasAny($Model, $sql) {
$sql = $this->conditions($sql);
$table = $this->fullTableName($Model);
$alias = $this->alias . $this->name($Model->alias);
@ -2524,7 +2691,7 @@ class DboSource extends DataSource {
* Translates between PHP boolean values and Database (faked) boolean values
*
* @param mixed $data Value to be translated
* @return mixed Converted boolean value
* @return int Converted boolean value
*/
public function boolean($data) {
if ($data === true || $data === false) {
@ -2533,7 +2700,7 @@ class DboSource extends DataSource {
}
return 0;
} else {
return !empty($data);
return (int) !empty($data);
}
}
@ -2546,13 +2713,18 @@ class DboSource extends DataSource {
*/
public function insertMulti($table, $fields, $values) {
$table = $this->fullTableName($table);
if (is_array($fields)) {
$fields = implode(', ', array_map(array(&$this, 'name'), $fields));
}
$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++) {
$this->query("INSERT INTO {$table} ({$fields}) VALUES {$values[$x]}");
$statement->execute($values[$x]);
$statement->closeCursor();
}
return $this->commit();
}
/**
@ -2629,16 +2801,12 @@ class DboSource extends DataSource {
/**
* Generate a "drop table" statement for the given Schema object
*
* @param object $schema An instance of a subclass of CakeSchema
* @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($schema, $table = null) {
if (!is_a($schema, 'CakeSchema')) {
trigger_error(__('Invalid schema object'), E_USER_WARNING);
return null;
}
public function dropSchema(CakeSchema $schema, $table = null) {
$out = '';
foreach ($schema->tables as $curTable => $columns) {
@ -2666,7 +2834,7 @@ class DboSource extends DataSource {
}
if (!isset($this->columns[$type])) {
trigger_error(sprintf(__('Column type %s does not exist'), $type), E_USER_WARNING);
trigger_error(__('Column type %s does not exist', $type), E_USER_WARNING);
return null;
}
@ -2867,11 +3035,12 @@ class DboSource extends DataSource {
*
* @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) {
if (strpos(trim(strtolower($sql)), 'select') !== false) {
$this->_queryCache[$sql] = $data;
protected function _writeQueryCache($sql, $data, $params = array()) {
if (preg_match('/^\s*select/i', $sql)) {
$this->_queryCache[$sql][serialize($params)] = $data;
}
}
@ -2879,11 +3048,15 @@ class DboSource extends DataSource {
* 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 = null) {
public function getQueryCache($sql, $params = array()) {
if (isset($this->_queryCache[$sql]) && preg_match('/^\s*select/i', $sql)) {
return $this->_queryCache[$sql];
$serialized = serialize($params);
if (isset($this->_queryCache[$sql][$serialized])) {
return $this->_queryCache[$sql][$serialized];
}
}
return false;
}

View file

@ -138,7 +138,7 @@ class AclNode extends AppModel {
$model = ClassRegistry::init(array('class' => $name, 'alias' => $name));
if (empty($model)) {
trigger_error(sprintf(__("Model class '%s' not found in AclNode::node() when trying to bind %s object"), $type, $this->alias), E_USER_WARNING);
trigger_error(__("Model class '%s' not found in AclNode::node() when trying to bind %s object", $type, $this->alias), E_USER_WARNING);
return null;
}
@ -183,7 +183,7 @@ class AclNode extends AppModel {
$result = $db->read($this, $queryData, -1);
if (!$result) {
trigger_error(sprintf(__("AclNode::node() - Couldn't find %s node identified by \"%s\""), $type, print_r($ref, true)), E_USER_WARNING);
trigger_error(__("AclNode::node() - Couldn't find %s node identified by \"%s\"", $type, print_r($ref, true)), E_USER_WARNING);
}
}
return $result;

View file

@ -23,7 +23,9 @@
/**
* Included libs
*/
App::import('Core', array('ClassRegistry', 'Validation', 'Set', 'String'));
App::import('Core', 'ClassRegistry', false);
App::import('Core', 'Validation', false);
App::import('Core', 'String', false);
App::import('Model', 'BehaviorCollection', false);
App::import('Model', 'ModelBehavior', false);
App::import('Model', 'ConnectionManager', false);
@ -438,27 +440,15 @@ class Model extends Object {
}
if (is_subclass_of($this, 'AppModel')) {
$appVars = get_class_vars('AppModel');
$merge = array('_findMethods');
if ($this->actsAs !== null || $this->actsAs !== false) {
$merge[] = 'actsAs';
}
$parentClass = get_parent_class($this);
if (strtolower($parentClass) !== 'appmodel') {
$parentVars = get_class_vars($parentClass);
foreach ($merge as $var) {
if (isset($parentVars[$var]) && !empty($parentVars[$var])) {
$appVars[$var] = Set::merge($appVars[$var], $parentVars[$var]);
}
}
}
foreach ($merge as $var) {
if (isset($appVars[$var]) && !empty($appVars[$var]) && is_array($this->{$var})) {
$this->{$var} = Set::merge($appVars[$var], $this->{$var});
}
if ($parentClass !== 'AppModel') {
$this->_mergeVars($merge, $parentClass);
}
$this->_mergeVars($merge, 'AppModel');
}
$this->Behaviors = new BehaviorCollection();
@ -629,9 +619,9 @@ class Model extends Object {
*
* 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)
@ -914,9 +904,6 @@ class Model extends Object {
$dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
$timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec');
$db = $this->getDataSource();
$format = $db->columns[$type]['format'];
$date = array();
if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] != 12 && 'pm' == $data['meridian']) {
@ -959,9 +946,13 @@ class Model extends Object {
}
}
}
$date = str_replace(array_keys($date), array_values($date), $format);
$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;
return $date->format($format);
}
}
return $data;
@ -1459,15 +1450,11 @@ class Model extends Object {
foreach ((array)$data as $row) {
if ((is_string($row) && (strlen($row) == 36 || strlen($row) == 16)) || is_numeric($row)) {
$values = array(
$db->value($id, $this->getColumnType($this->primaryKey)),
$db->value($row)
);
$values = array($id, $row);
if ($isUUID && $primaryAdded) {
$values[] = $db->value(String::uuid());
$values[] = String::uuid();
}
$values = implode(',', $values);
$newValues[] = "({$values})";
$newValues[] = $values;
unset($values);
} elseif (isset($row[$this->hasAndBelongsToMany[$assoc]['associationForeignKey']])) {
$newData[] = $row;
@ -1506,7 +1493,6 @@ class Model extends Object {
}
if (!empty($newValues)) {
$fields = implode(',', $fields);
$db->insertMulti($this->{$join}, $fields, $newValues);
}
}
@ -1636,7 +1622,7 @@ class Model extends Object {
}
if ($options['atomic'] && $options['validate'] !== 'only') {
$db->begin($this);
$transactionBegun = $db->begin($this);
}
if (Set::numeric(array_keys($data))) {
@ -1676,8 +1662,12 @@ class Model extends Object {
break;
default:
if ($options['atomic']) {
if ($validates && ($db->commit($this) !== false)) {
return true;
if ($validates) {
if ($transactionBegun) {
return $db->commit($this) !== false;
} else {
return true;
}
}
$db->rollback($this);
return false;
@ -1787,7 +1777,11 @@ class Model extends Object {
default:
if ($options['atomic']) {
if ($validates) {
return ($db->commit($this) !== false);
if ($transactionBegun) {
return $db->commit($this) !== false;
} else {
return true;
}
} else {
$db->rollback($this);
}
@ -1870,7 +1864,7 @@ class Model extends Object {
));
}
if ($db->delete($this)) {
if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
if (!empty($this->belongsTo)) {
$this->updateCounterCache($keys[$this->alias]);
}
@ -2640,7 +2634,7 @@ class Model extends Object {
} elseif (!is_array($validator['rule'])) {
$valid = preg_match($rule, $data[$fieldName]);
} elseif (Configure::read('debug') > 0) {
trigger_error(sprintf(__('Could not find validation handler %s for %s'), $rule, $fieldName), E_USER_WARNING);
trigger_error(__('Could not find validation handler %s for %s', $rule, $fieldName), E_USER_WARNING);
}
if (!$valid || (is_string($valid) && strlen($valid) > 0)) {
@ -2949,7 +2943,7 @@ class Model extends Object {
return array($with, array_unique(array_merge($assoc[$with], $keys)));
}
trigger_error(
sprintf(__('Invalid join model settings in %s'), $model->alias),
__('Invalid join model settings in %s', $model->alias),
E_USER_WARNING
);
}

View file

@ -59,7 +59,7 @@ class ModelBehavior extends Object {
* @param object $model Model using this behavior
* @param array $config Configuration settings for $model
*/
public function setup(&$model, $config = array()) { }
public function setup($model, $config = array()) { }
/**
* Clean up any initialization this behavior has done on a model. Called when a behavior is dynamically
@ -69,7 +69,7 @@ class ModelBehavior extends Object {
* @access public
* @see BehaviorCollection::detach()
*/
function cleanup(&$model) {
function cleanup($model) {
if (isset($this->settings[$model->alias])) {
unset($this->settings[$model->alias]);
}
@ -83,7 +83,7 @@ class ModelBehavior extends Object {
* @return mixed False if the operation should abort. An array will replace the value of $query.
* @access public
*/
public function beforeFind(&$model, $query) { }
public function beforeFind($model, $query) { }
/**
* After find callback. Can be used to modify any results returned by find and findAll.
@ -94,7 +94,7 @@ class ModelBehavior extends Object {
* @return mixed An array value will replace the value of $results - any other value will be ignored.
* @access public
*/
public function afterFind(&$model, $results, $primary) { }
public function afterFind($model, $results, $primary) { }
/**
* Before validate callback
@ -103,7 +103,7 @@ class ModelBehavior extends Object {
* @return mixed False if the operation should abort. Any other result will continue.
* @access public
*/
public function beforeValidate(&$model) { }
public function beforeValidate($model) { }
/**
* Before save callback
@ -112,7 +112,7 @@ class ModelBehavior extends Object {
* @return mixed False if the operation should abort. Any other result will continue.
* @access public
*/
public function beforeSave(&$model) { }
public function beforeSave($model) { }
/**
* After save callback
@ -120,7 +120,7 @@ class ModelBehavior extends Object {
* @param object $model Model using this behavior
* @param boolean $created True if this save created a new record
*/
public function afterSave(&$model, $created) { }
public function afterSave($model, $created) { }
/**
* Before delete callback
@ -130,14 +130,14 @@ class ModelBehavior extends Object {
* @return mixed False if the operation should abort. Any other result will continue.
* @access public
*/
public function beforeDelete(&$model, $cascade = true) { }
public function beforeDelete($model, $cascade = true) { }
/**
* After delete callback
*
* @param object $model Model using this behavior
*/
public function afterDelete(&$model) { }
public function afterDelete($model) { }
/**
* DataSource error callback
@ -145,7 +145,7 @@ class ModelBehavior extends Object {
* @param object $model Model using this behavior
* @param string $error Error generated in DataSource
*/
public function onError(&$model, $error) { }
public function onError($model, $error) { }
/**
* If $model's whitelist property is non-empty, $field will be added to it.
@ -158,7 +158,7 @@ class ModelBehavior extends Object {
* @access protected
* @return void
*/
function _addToWhitelist(&$model, $field) {
function _addToWhitelist($model, $field) {
if (is_array($field)) {
foreach ($field as $f) {
$this->_addToWhitelist($model, $f);

View file

@ -67,7 +67,7 @@ class Object {
return false;
}
if (!class_exists('dispatcher')) {
require CAKE . 'dispatcher.php';
require LIBS . 'dispatcher.php';
}
if (in_array('return', $extra, true)) {
$extra = array_merge($extra, array('return' => 0, 'autoRender' => 1));
@ -75,9 +75,21 @@ class Object {
if (is_array($url) && !isset($extra['url'])) {
$extra['url'] = array();
}
$params = array_merge(array('autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1), $extra);
$dispatcher = new Dispatcher;
return $dispatcher->dispatch($url, $params);
$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();
return $dispatcher->dispatch($request, $extra);
}
/**
@ -186,6 +198,36 @@ class Object {
}
}
/**
* 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 sting $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});
}
}
}
/**
* You should choose a unique name for the persistent file
*

View file

@ -38,12 +38,14 @@ abstract class ObjectCollection {
/**
* Loads a new object onto the collection. Can throw a variety of exceptions
*
* Implementations of this class support a `$options['callbacks']` flag which enables/disables
* a loaded object.
*
* @param string $name Name of object to load.
* @param array $options Array of configuration options for the object to be constructed.
* @param boolean $enable Whether or not this helper should be enabled by default
* @return object the constructed object
*/
abstract public function load($name, $options = array(), $enable = true);
abstract public function load($name, $options = array());
/**
* Trigger a callback method on every object in the collection.

View file

@ -506,7 +506,7 @@ class Router {
* @return array Returns an array containing the altered URL and the parsed extension.
* @access private
*/
function __parseExtension($url) {
private static function __parseExtension($url) {
$ext = null;
if (self::$_parseExtensions) {
@ -563,7 +563,7 @@ class Router {
* @return void
* @access private
*/
function __connectDefaultRoutes() {
private static function __connectDefaultRoutes() {
if ($plugins = App::objects('plugin')) {
App::import('Core', 'route/PluginShortRoute');
foreach ($plugins as $key => $value) {
@ -886,10 +886,9 @@ class Router {
*
* @param array $url A url that didn't match any routes
* @return string A generated url for the array
* @access protected
* @see Router::url()
*/
function _handleNoRoute($url) {
protected static function _handleNoRoute($url) {
$named = $args = array();
$skip = array_merge(
array('bare', 'action', 'controller', 'plugin', 'prefix'),

View file

@ -714,11 +714,11 @@ class Validation {
protected static function _pass($method, $check, $classPrefix) {
$className = ucwords($classPrefix) . 'Validation';
if (!class_exists($className)) {
trigger_error(sprintf(__('Could not find %s class, unable to complete validation.', true), $className), E_USER_WARNING);
trigger_error(__('Could not find %s class, unable to complete validation.', $className), E_USER_WARNING);
return false;
}
if (!method_exists($className, $method)) {
trigger_error(sprintf(__('Method %s does not exist on %s unable to complete validation.', true), $method, $className), E_USER_WARNING);
trigger_error(__('Method %s does not exist on %s unable to complete validation.', $method, $className), E_USER_WARNING);
return false;
}
$check = (array)$check;

View file

@ -17,14 +17,14 @@
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<h2><?php printf(__('Missing Method in %s'), $controller); ?></h2>
<h2><?php echo __('Missing Method in %s', $controller); ?></h2>
<p class="error">
<strong><?php echo __('Error'); ?>: </strong>
<?php printf(__('The action %1$s is not defined in controller %2$s'), '<em>' . $action . '</em>', '<em>' . $controller . '</em>'); ?>
<?php echo __('The action %1$s is not defined in controller %2$s', '<em>' . $action . '</em>', '<em>' . $controller . '</em>'); ?>
</p>
<p class="error">
<strong><?php echo __('Error'); ?>: </strong>
<?php printf(__('Create %1$s%2$s in file: %3$s.'), '<em>' . $controller . '::</em>', '<em>' . $action . '()</em>', APP_DIR . DS . 'controllers' . DS . Inflector::underscore($controller) . '.php'); ?>
<?php echo __('Create %1$s%2$s in file: %3$s.', '<em>' . $controller . '::</em>', '<em>' . $action . '()</em>', APP_DIR . DS . 'controllers' . DS . Inflector::underscore($controller) . '.php'); ?>
</p>
<pre>
&lt;?php
@ -40,6 +40,6 @@ class <?php echo $controller;?> extends AppController {
</pre>
<p class="notice">
<strong><?php echo __('Notice'); ?>: </strong>
<?php printf(__('If you want to customize this error message, create %s'), APP_DIR . DS . 'views' . DS . 'errors' . DS . 'missing_action.ctp'); ?>
<?php echo __('If you want to customize this error message, create %s', APP_DIR . DS . 'views' . DS . 'errors' . DS . 'missing_action.ctp'); ?>
</p>
<?php echo $this->element('exception_stack_trace'); ?>

View file

@ -20,11 +20,11 @@
<h2><?php echo __('Missing Behavior Class'); ?></h2>
<p class="error">
<strong><?php echo __('Error'); ?>: </strong>
<?php printf(__('The behavior class <em>%s</em> can not be found or does not exist.'), $class); ?>
<?php echo __('The behavior class <em>%s</em> can not be found or does not exist.', $class); ?>
</p>
<p class="error">
<strong><?php echo __('Error'); ?>: </strong>
<?php printf(__('Create the class below in file: %s'), APP_DIR . DS . 'models' . DS . 'behaviors' . DS . $file); ?>
<?php echo __('Create the class below in file: %s', APP_DIR . DS . 'models' . DS . 'behaviors' . DS . $file); ?>
</p>
<pre>
&lt;?php
@ -35,7 +35,7 @@ class <?php echo $class;?> extends ModelBehavior {
</pre>
<p class="notice">
<strong><?php echo __('Notice'); ?>: </strong>
<?php printf(__('If you want to customize this error message, create %s'), APP_DIR . DS . 'views' . DS . 'errors' . DS . 'missing_behavior_class.ctp'); ?>
<?php echo __('If you want to customize this error message, create %s', APP_DIR . DS . 'views' . DS . 'errors' . DS . 'missing_behavior_class.ctp'); ?>
</p>
<?php echo $this->element('exception_stack_trace'); ?>

Some files were not shown because too many files have changed in this diff Show more