Renaming branched version directory

git-svn-id: https://svn.cakephp.org/repo/branches/1.1.x.x@3085 3807eeeb-6ff5-0310-8944-8be069107fe0
This commit is contained in:
phpnut 2006-06-14 18:02:37 +00:00
parent e5c074a0dc
commit 9d19dee879
45 changed files with 2935 additions and 2406 deletions

View file

@ -6,4 +6,4 @@
// +---------------------------------------------------------------------------------------------------+ // // +---------------------------------------------------------------------------------------------------+ //
/////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
1.1.2.2955 1.1.4.3083

View file

@ -17,11 +17,11 @@ background:#003d4c;
a{ a{
color:#003d4c; color:#003d4c;
text-decoration:none; text-decoration:underline;
} }
a:hover{ a:hover{
color:#003d4c; color:#003d4c;
text-decoration:underline; text-decoration:none;
} }
a img{ a img{
@ -77,6 +77,7 @@ padding:0 2em;
#container{ #container{
text-align:left; text-align:left;
margin-left:0px; margin-left:0px;
min-width: 960px;
} }
#header{ #header{
@ -189,9 +190,8 @@ background:url(images/nav_item_bg.gif) no-repeat bottom left;
table { table {
width: 100%; width: 100%;
border: 0px; border: 1px solid #003d4c;
color:#333; color:#333;
border: 1px solid #ccc;
background-color: #fff; background-color: #fff;
clear:both; clear:both;
padding: 0; padding: 0;
@ -205,7 +205,7 @@ th {
border-right: 1px solid #003d4c; border-right: 1px solid #003d4c;
border-bottom: 1px solid #003d4c; border-bottom: 1px solid #003d4c;
text-align: center; text-align: center;
padding:2px; padding:1px;
} }
table tr td { table tr td {
border-right: 1px solid #ccc; border-right: 1px solid #ccc;
@ -240,20 +240,29 @@ dd {
vertical-align:top; vertical-align:top;
} }
/* scaffold buttons */ /* notices and errors */
p.error, error_message {
color: #e32000;
font-size: 18px;
background-color: #fff;
margin: 8px 4px;
}
p.error em {
font-size: 18px;
color: #003d4c;
}
.notice { .notice {
color: #DB8101; color: #656565;
background-color: #ddd; font-size: 14px;
background-color: #f4f4f4;
padding: 4px;
display:block; display:block;
padding: 1em;
} }
.tip { .tip {
color: #DB8101; color: #e32000;
background-color: #ddd; background-color: #ddd;
display: block;
padding: 1em;
} }
@ -263,6 +272,3 @@ ul.actions {
margin-left: 10px; margin-left: 10px;
width: 200px; width: 200px;
} }
li {
list-style-image: url("images/arrow.gif");
}

View file

@ -129,12 +129,6 @@ form div label.labelCheckbox, form div label.labelRadio {
form div fieldset label.labelCheckbox, form div fieldset label.labelRadio { form div fieldset label.labelCheckbox, form div fieldset label.labelRadio {
margin: 0px 0px 5px 0px; margin: 0px 0px 5px 0px;
} }
p.error {
color: #DB8101;
background-color: #DBA941;
font-size: 14px;
padding: 1em;
}
form div input, form div select, form div textarea { form div input, form div select, form div textarea {
padding: 1px 3px; padding: 1px 3px;

View file

@ -129,6 +129,8 @@
} else { } else {
return false; return false;
} }
} else {
return true;
} }
} }
/** /**
@ -252,13 +254,126 @@
if (file_exists($file)) { if (file_exists($file)) {
require($file); require($file);
return true; return true;
} elseif (file_exists(APP . 'plugins' . DS . $plugin . DS . 'controllers' . DS . $plugin . '_controller.php')) } elseif (file_exists(APP . 'plugins' . DS . $plugin . DS . 'controllers' . DS . $plugin . '_controller.php')) {
{
require(APP . 'plugins' . DS . $plugin . DS . 'controllers' . DS . $plugin . '_controller.php'); require(APP . 'plugins' . DS . $plugin . DS . 'controllers' . DS . $plugin . '_controller.php');
return true; return true;
} else { } else {
return false; return false;
} }
} else {
return true;
}
}
/**
* Loads a helper
*
* @param string $name Name of helper
* @return boolean Success
*/
function loadHelper($name) {
$paths = Configure::getInstance();
if ($name === null) {
return true;
}
if (!class_exists($name . 'Helper')) {
$name=Inflector::underscore($name);
foreach($paths->helperPaths as $path) {
if (file_exists($path . $name . '.php')) {
require($path . $name . '.php');
return true;
}
}
if ($helper_fn = fileExistsInPath(LIBS . 'view' . DS . 'helpers' . DS . $name . '.php')) {
if (file_exists($helper_fn)) {
require($helper_fn);
return true;
} else {
return false;
}
}
} else {
return true;
}
}
/**
* Loads a plugin's helper
*
* @param string $plugin Name of plugin
* @param string $helper Name of helper to load
* @return boolean Success
*/
function loadPluginHelper($plugin, $helper) {
if (!class_exists($helper . 'Helper')) {
$helper = Inflector::underscore($helper);
$file = APP . 'plugins' . DS . $plugin . DS . 'views' . DS . 'helpers' . DS . $helper . '.php';
if (file_exists($file)) {
require($file);
return true;
} else {
return false;
}
} else {
return true;
}
}
/**
* Loads a component
*
* @param string $name Name of component
* @return boolean Success
*/
function loadComponent($name) {
$paths = Configure::getInstance();
if ($name === null) {
return true;
}
if (!class_exists($name . 'Component')) {
$name=Inflector::underscore($name);
foreach($paths->componentPaths as $path) {
if (file_exists($path . $name . '.php')) {
require($path . $name . '.php');
return true;
}
}
if ($component_fn = fileExistsInPath(LIBS . 'controller' . DS . 'components' . DS . $name . '.php')) {
if (file_exists($component_fn)) {
require($component_fn);
return true;
} else {
return false;
}
}
} else {
return true;
}
}
/**
* Loads a plugin's component
*
* @param string $plugin Name of plugin
* @param string $helper Name of component to load
* @return boolean Success
*/
function loadPluginComponent($plugin, $component) {
if (!class_exists($component . 'Component')) {
$component = Inflector::underscore($component);
$file = APP . 'plugins' . DS . $plugin . DS . 'controllers' . DS . 'components' . DS . $component . '.php';
if (file_exists($file)) {
require($file);
return true;
} else {
return false;
}
} else {
return true;
} }
} }
/** /**
@ -344,7 +459,7 @@
*/ */
function debug($var = false, $showHtml = false) { function debug($var = false, $showHtml = false) {
if (DEBUG) { if (DEBUG) {
print "\n<pre>\n"; print "\n<pre class=\"cake_debug\">\n";
ob_start(); ob_start();
print_r($var); print_r($var);
$var = ob_get_clean(); $var = ob_get_clean();
@ -886,7 +1001,7 @@
if (!is_dir($path)) { if (!is_dir($path)) {
return chmod($path, $mode); return chmod($path, $mode);
} }
$di = opendir($path); $dir = opendir($path);
while($file = readdir($dir)) { while($file = readdir($dir)) {
if ($file != '.' && $file != '..') { if ($file != '.' && $file != '..') {
@ -911,4 +1026,24 @@
return false; return false;
} }
} }
/**
* removed the plugin name from the base url
*
* @param string $base
* @param string $plugin
* @return base url with plugin name removed if present
*/
function strip_plugin($base, $plugin){
if ($plugin != null) {
$base = preg_replace('/' . $plugin . '/', '', $base);
$base = str_replace('//', '', $base);
$pos1 = strrpos($base, '/');
$char = strlen($base) - 1;
if ($pos1 == $char) {
$base = substr($base, 0, $char);
}
}
return $base;
}
?> ?>

View file

@ -105,6 +105,9 @@ blockend = "</div>"
; Tag template for a CSS link tag. ; Tag template for a CSS link tag.
css = "<link rel="%s" type="text/css" href="%s" %s/>" css = "<link rel="%s" type="text/css" href="%s" %s/>"
; Tag template for a CSS tag block.
style = "<style type="text/css"%s>%s</style>"
; Tag template for a charset meta-tag. ; Tag template for a charset meta-tag.
charset = "<meta http-equiv="Content-Type" content="text/html; charset=%s" />" charset = "<meta http-equiv="Content-Type" content="text/html; charset=%s" />"

View file

@ -89,10 +89,7 @@ class Dispatcher extends Object {
if(!class_exists($ctrlClass)) { if(!class_exists($ctrlClass)) {
if (!loadController($ctrlName)) { if (!loadController($ctrlName)) {
$plugin = $ctrlName;
$pluginName = Inflector::camelize($params['action']); $pluginName = Inflector::camelize($params['action']);
$pluginClass = $pluginName.'Controller';
if (!loadPluginController(Inflector::underscore($ctrlName), $pluginName)) { if (!loadPluginController(Inflector::underscore($ctrlName), $pluginName)) {
if(preg_match('/([\\.]+)/', $ctrlName)) { if(preg_match('/([\\.]+)/', $ctrlName)) {
return $this->cakeError('error404', array( return $this->cakeError('error404', array(
@ -104,10 +101,19 @@ class Dispatcher extends Object {
$missingController = true; $missingController = true;
} }
} else { } else {
$params['plugin'] = Inflector::underscore($ctrlName);
}
}
}
}
if(isset($params['plugin'])){
$plugin = $params['plugin'];
$pluginName = Inflector::camelize($params['action']);
$pluginClass = $pluginName.'Controller';
$ctrlClass = $pluginClass; $ctrlClass = $pluginClass;
$oldAction = $params['action']; $oldAction = $params['action'];
$params = $this->_restructureParams($params); $params = $this->_restructureParams($params);
$plugin = Inflector::underscore($ctrlName);
$this->plugin = $plugin; $this->plugin = $plugin;
loadPluginModels($plugin); loadPluginModels($plugin);
$this->base = $this->base.'/'.Inflector::underscore($ctrlName); $this->base = $this->base.'/'.Inflector::underscore($ctrlName);
@ -115,16 +121,12 @@ class Dispatcher extends Object {
if(empty($params['controller']) || !class_exists($pluginClass)) { if(empty($params['controller']) || !class_exists($pluginClass)) {
$params['controller'] = Inflector::underscore($ctrlName); $params['controller'] = Inflector::underscore($ctrlName);
$ctrlClass = $ctrlName.'Controller'; $ctrlClass = $ctrlName.'Controller';
if (!is_null($params['action'])) { if (!is_null($params['action'])) {
array_unshift($params['pass'], $params['action']); array_unshift($params['pass'], $params['action']);
} }
$params['action'] = $oldAction; $params['action'] = $oldAction;
} }
} }
}
}
}
if(defined('CAKE_ADMIN')) { if(defined('CAKE_ADMIN')) {
if(isset($params[CAKE_ADMIN])) { if(isset($params[CAKE_ADMIN])) {

View file

@ -56,6 +56,20 @@ class Configure extends Object{
* @access public * @access public
*/ */
var $modelPaths = array(); var $modelPaths = array();
/**
* Enter description here...
*
* @var array
* @access public
*/
var $helperPaths = array();
/**
* Enter description here...
*
* @var array
* @access public
*/
var $componentPaths = array();
/** /**
* Return a singleton instance of Configure. * Return a singleton instance of Configure.
* *
@ -81,7 +95,7 @@ class Configure extends Object{
$_this->modelPaths[] = MODELS; $_this->modelPaths[] = MODELS;
if (isset($modelPaths)) { if (isset($modelPaths)) {
foreach($modelPaths as $value) { foreach($modelPaths as $value) {
$this->modelPaths[] = $value; $_this->modelPaths[] = $value;
} }
} }
} }
@ -97,7 +111,7 @@ class Configure extends Object{
$_this->viewPaths[] = VIEWS . 'errors' . DS; $_this->viewPaths[] = VIEWS . 'errors' . DS;
if (isset($viewPaths)) { if (isset($viewPaths)) {
foreach($viewPaths as $value) { foreach($viewPaths as $value) {
$this->viewPaths[] = $value; $_this->viewPaths[] = $value;
} }
} }
} }
@ -112,7 +126,37 @@ class Configure extends Object{
$_this->controllerPaths[] = CONTROLLERS; $_this->controllerPaths[] = CONTROLLERS;
if (isset($controllerPaths)) { if (isset($controllerPaths)) {
foreach($controllerPaths as $value) { foreach($controllerPaths as $value) {
$this->controllerPaths[] = $value; $_this->controllerPaths[] = $value;
}
}
}
/**
* Sets the var helperPaths
*
* @param array $helperPaths
* @access private
*/
function __buildHelperPaths($helperPaths) {
$_this =& Configure::getInstance();
$_this->helperPaths[] = HELPERS;
if (isset($helperPaths)) {
foreach($helperPaths as $value) {
$_this->helperPaths[] = $value;
}
}
}
/**
* Sets the var componentPaths
*
* @param array $componentPaths
* @access private
*/
function __buildComponentPaths($componentPaths) {
$_this =& Configure::getInstance();
$_this->componentPaths[] = COMPONENTS;
if (isset($componentPaths)) {
foreach($componentPaths as $value) {
$_this->componentPaths[] = $value;
} }
} }
} }
@ -128,10 +172,15 @@ class Configure extends Object{
$modelPaths = null; $modelPaths = null;
$viewPaths = null; $viewPaths = null;
$controllerPaths = null; $controllerPaths = null;
$helperPaths = null;
$componentPaths = null;
require APP_PATH . 'config' . DS . 'bootstrap.php'; require APP_PATH . 'config' . DS . 'bootstrap.php';
$_this->__buildModelPaths($modelPaths); $_this->__buildModelPaths($modelPaths);
$_this->__buildViewPaths($viewPaths); $_this->__buildViewPaths($viewPaths);
$_this->__buildControllerPaths($controllerPaths); $_this->__buildControllerPaths($controllerPaths);
$_this->__buildHelperPaths($helperPaths);
$_this->__buildComponentPaths($componentPaths);
} }
} }
?> ?>

View file

@ -1,6 +1,5 @@
<?php <?php
/* SVN FILE: $Id$ */ /* SVN FILE: $Id$ */
/** /**
* *
* *
@ -25,7 +24,6 @@
* @lastmodified $Date$ * @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
/** /**
* *
* *
@ -33,14 +31,12 @@
* @subpackage cake.cake.libs.controller * @subpackage cake.cake.libs.controller
*/ */
class Component extends Object { class Component extends Object {
/** /**
* Enter description here... * Enter description here...
* *
* @var unknown_type * @var unknown_type
*/ */
var $components = array(); var $components = array();
/** /**
* Enter description here... * Enter description here...
* *
@ -53,16 +49,14 @@ class Component extends Object{
* *
* @return Component * @return Component
*/ */
function Component(&$controller) { function __construct(&$controller) {
$this->controller =& $controller; $this->controller =& $controller;
if ($this->controller->components !== false) { if ($this->controller->components !== false) {
$loaded = array(); $loaded = array();
$loaded = $this->_loadComponents($loaded, $this->controller->components); $loaded = $this->_loadComponents($loaded, $this->controller->components);
foreach(array_keys($loaded)as $component) { foreach(array_keys($loaded)as $component) {
$tempComponent =& $loaded[$component]; $tempComponent =& $loaded[$component];
if (isset($tempComponent->components) && is_array($tempComponent->components)) { if (isset($tempComponent->components) && is_array($tempComponent->components)) {
foreach($tempComponent->components as $subComponent) { foreach($tempComponent->components as $subComponent) {
$this->controller->{$component}->{$subComponent} =& $loaded[$subComponent]; $this->controller->{$component}->{$subComponent} =& $loaded[$subComponent];
@ -71,7 +65,6 @@ class Component extends Object{
} }
} }
} }
/** /**
* Enter description here... * Enter description here...
* *
@ -81,59 +74,46 @@ class Component extends Object{
*/ */
function &_loadComponents(&$loaded, $components) { function &_loadComponents(&$loaded, $components) {
foreach($components as $component) { foreach($components as $component) {
if (in_array($component, array_keys($loaded)) !== true) {
$componentFn=Inflector::underscore($component) . '.php';
if (file_exists(
APP . 'plugins' . DS . $this->controller->plugin . DS . 'controllers' . DS . 'components' . DS . $componentFn)) {
$componentFn = APP . 'plugins' . DS . $this->controller->plugin . DS . 'controllers' . DS
. 'components' . DS . $componentFn;
} else if(file_exists(COMPONENTS . $componentFn)) {
$componentFn = COMPONENTS . $componentFn;
} else if($componentFn
= fileExistsInPath(LIBS . 'controller' . DS . 'components' . DS . $componentFn)) {
}
$componentCn = $component . 'Component'; $componentCn = $component . 'Component';
if (is_file($componentFn)) { if (in_array($component, array_keys($loaded)) !== true) {
if (!class_exists($componentCn)) { if (!class_exists($componentCn)) {
require_once $componentFn; if (is_null($this->controller->plugin) || !loadPluginComponent($this->controller->plugin, $component)) {
if (!loadComponent($component)) {
return $this->cakeError('missingComponentFile', array(array(
'className' => $this->controller->name,
'component' => $component,
'file' => Inflector::underscore($componentCn) . '.php',
'base' => $this->controller->base
)));
}
}
if (!class_exists($componentCn)) {
$componentFn = Inflector::underscore($component) . '.php';
return $this->cakeError('missingComponentClass', array(array(
'className' => $this->controller->name,
'component' => $component,
'file' => $componentFn,
'base' => $this->controller->base
)));
}
} }
if (class_exists($componentCn) === true) {
if ($componentCn == 'SessionComponent') { if ($componentCn == 'SessionComponent') {
$param = $this->controller->base . '/'; $param = $this->controller->base . '/';
} else { } else {
$param = null; $param = null;
} }
$this->controller->{$component} =& new $componentCn($param); $this->controller->{$component} =& new $componentCn($param);
$loaded[$component] =& $this->controller->{$component}; $loaded[$component] =& $this->controller->{$component};
if (isset($this->controller->{$component}->components) && is_array($this->controller->{$component}->components)) {
if (isset($this->controller->{$component}->components) $loaded =& $this->_loadComponents($loaded, $this->controller->{$component}->components);
&& is_array($this->controller->{$component}->components)) {
$loaded = &$this->_loadComponents($loaded,
$this->controller->{$component}->components);
}
} else {
return $this->cakeError('missingComponentClass',
array(array('className' => $this->controller->name,
'component' => $component,
'file' => $componentFn,
'base' => $this->controller->base)));
}
} else {
return $this->cakeError('missingComponentFile',
array(array('className' => $this->controller->name,
'component' => $component,
'file' => $componentFn,
'base' => $this->controller->base)));
} }
} }
} }
return $loaded; return $loaded;
} }
} }
?> ?>

View file

@ -37,6 +37,7 @@
* @subpackage cake.cake.libs.controller.components * @subpackage cake.cake.libs.controller.components
*/ */
class AclComponent extends Object { class AclComponent extends Object {
var $_instance = null; var $_instance = null;
var $controller = true; var $controller = true;
@ -47,7 +48,6 @@ class AclComponent extends Object{
function __construct() { function __construct() {
$this->getACL(); $this->getACL();
} }
/** /**
* Static function used to gain an instance of the correct ACL class. * Static function used to gain an instance of the correct ACL class.
* *
@ -62,14 +62,12 @@ class AclComponent extends Object{
return $this->_instance; return $this->_instance;
} }
/** /**
* Empty class defintion, to be overridden in subclasses. * Empty class defintion, to be overridden in subclasses.
* *
*/ */
function _initACL() { function _initACL() {
} }
/** /**
* Pass-thru function for ACL check instance. * Pass-thru function for ACL check instance.
* *
@ -78,7 +76,6 @@ class AclComponent extends Object{
function check($aro, $aco, $action = "*") { function check($aro, $aco, $action = "*") {
return $this->_instance->check($aro, $aco, $action); return $this->_instance->check($aro, $aco, $action);
} }
/** /**
* Pass-thru function for ACL allow instance. * Pass-thru function for ACL allow instance.
* *
@ -87,7 +84,6 @@ class AclComponent extends Object{
function allow($aro, $aco, $action = "*") { function allow($aro, $aco, $action = "*") {
return $this->_instance->allow($aro, $aco, $action); return $this->_instance->allow($aro, $aco, $action);
} }
/** /**
* Pass-thru function for ACL deny instance. * Pass-thru function for ACL deny instance.
* *
@ -96,7 +92,6 @@ class AclComponent extends Object{
function deny($aro, $aco, $action = "*") { function deny($aro, $aco, $action = "*") {
return $this->_instance->deny($aro, $aco, $action); return $this->_instance->deny($aro, $aco, $action);
} }
/** /**
* Pass-thru function for ACL inherit instance. * Pass-thru function for ACL inherit instance.
* *
@ -105,7 +100,6 @@ class AclComponent extends Object{
function inherit($aro, $aco, $action = "*") { function inherit($aro, $aco, $action = "*") {
return $this->_instance->inherit($aro, $aco, $action); return $this->_instance->inherit($aro, $aco, $action);
} }
/** /**
* Pass-thru function for ACL grant instance. * Pass-thru function for ACL grant instance.
* *
@ -114,7 +108,6 @@ class AclComponent extends Object{
function grant($aro, $aco, $action = "*") { function grant($aro, $aco, $action = "*") {
return $this->_instance->grant($aro, $aco, $action); return $this->_instance->grant($aro, $aco, $action);
} }
/** /**
* Pass-thru function for ACL grant instance. * Pass-thru function for ACL grant instance.
* *
@ -123,7 +116,6 @@ class AclComponent extends Object{
function revoke($aro, $aco, $action = "*") { function revoke($aro, $aco, $action = "*") {
return $this->_instance->revoke($aro, $aco, $action); return $this->_instance->revoke($aro, $aco, $action);
} }
/** /**
* Pass-thru function for ACL getAro instance. * Pass-thru function for ACL getAro instance.
* *
@ -132,7 +124,6 @@ class AclComponent extends Object{
function getAro($id) { function getAro($id) {
return $this->_instance->getAro($id); return $this->_instance->getAro($id);
} }
/** /**
* Pass-thru function for ACL getAco instance. * Pass-thru function for ACL getAco instance.
* *
@ -142,4 +133,5 @@ class AclComponent extends Object{
return $this->_instance->getAco($id); return $this->_instance->getAco($id);
} }
} }
?> ?>

View file

@ -29,7 +29,6 @@
*/ */
uses('controller' . DS . 'components' . DS . 'acl_base'); uses('controller' . DS . 'components' . DS . 'acl_base');
uses('controller' . DS . 'components' . DS . 'dbacl' . DS . 'models' . DS . 'aclnode'); uses('controller' . DS . 'components' . DS . 'dbacl' . DS . 'models' . DS . 'aclnode');
uses('controller' . DS . 'components' . DS . 'dbacl' . DS . 'models' . DS . 'aco'); uses('controller' . DS . 'components' . DS . 'dbacl' . DS . 'models' . DS . 'aco');
uses('controller' . DS . 'components' . DS . 'dbacl' . DS . 'models' . DS . 'acoaction'); uses('controller' . DS . 'components' . DS . 'dbacl' . DS . 'models' . DS . 'acoaction');
@ -51,7 +50,6 @@ class DB_ACL extends AclBase{
*/ */
function __construct() { function __construct() {
} }
/** /**
* Enter description here... * Enter description here...
* *
@ -72,11 +70,15 @@ class DB_ACL extends AclBase{
$permKeys = $this->_getAcoKeys($Perms->loadInfo()); $permKeys = $this->_getAcoKeys($Perms->loadInfo());
$aroPath = $Aro->getPath($aro); $aroPath = $Aro->getPath($aro);
$tmpAcoPath = $Aco->getPath($aco); $tmpAcoPath = $Aco->getPath($aco);
if ($tmpAcoPath === null) {
return false;
}
$acoPath = array(); $acoPath = array();
if ($action != '*' && !in_array('_' . $action, $permKeys)) { if ($action != '*' && !in_array('_' . $action, $permKeys)) {
trigger_error('ACO permissions key "' . $action . '" does not exist in DB_ACL::check()', trigger_error('ACO permissions key "' . $action . '" does not exist in DB_ACL::check()', E_USER_NOTICE);
E_USER_NOTICE);
return false; return false;
} }
@ -85,9 +87,11 @@ class DB_ACL extends AclBase{
} }
for($i = count($aroPath) - 1; $i >= 0; $i--) { for($i = count($aroPath) - 1; $i >= 0; $i--) {
$perms = $Perms->findAll(array('ArosAco.aro_id' => $aroPath[$i]['Aro']['id'], $perms = $Perms->findAll(array(
'ArosAco.aro_id' => $aroPath[$i]['Aro']['id'],
'ArosAco.aco_id' => $acoPath), null, 'ArosAco.aco_id' => $acoPath), null,
'Aco.lft asc'); 'Aco.lft asc'
);
if ($perms == null || count($perms) == 0) { if ($perms == null || count($perms) == 0) {
continue; continue;
@ -105,25 +109,22 @@ class DB_ACL extends AclBase{
return true; return true;
} else { } else {
switch($perm['ArosAco']['_' . $action]) switch($perm['ArosAco']['_' . $action]) {
{ case -1:
case -1: return false; return false;
case 0: case 0:
continue; continue;
break; break;
case 1:
case 1: return true; return true;
break;
} }
} }
} }
} }
} }
return false; return false;
} }
/** /**
* Allow * Allow
* *
@ -165,10 +166,8 @@ class DB_ACL extends AclBase{
if ($perms['link'] != null && count($perms['link']) > 0) { if ($perms['link'] != null && count($perms['link']) > 0) {
$save['id'] = $perms['link'][0]['ArosAco']['id']; $save['id'] = $perms['link'][0]['ArosAco']['id'];
} }
return $Perms->save(array('ArosAco' => $save)); return $Perms->save(array('ArosAco' => $save));
} }
/** /**
* Deny * Deny
* *
@ -177,7 +176,6 @@ class DB_ACL extends AclBase{
function deny($aro, $aco, $action = "*") { function deny($aro, $aco, $action = "*") {
return $this->allow($aro, $aco, $action, -1); return $this->allow($aro, $aco, $action, -1);
} }
/** /**
* Inherit * Inherit
* *
@ -186,7 +184,6 @@ class DB_ACL extends AclBase{
function inherit($aro, $aco, $action = "*") { function inherit($aro, $aco, $action = "*") {
return $this->allow($aro, $aco, $action, 0); return $this->allow($aro, $aco, $action, 0);
} }
/** /**
* Allow alias * Allow alias
* *
@ -195,7 +192,6 @@ class DB_ACL extends AclBase{
function grant($aro, $aco, $action = "*") { function grant($aro, $aco, $action = "*") {
return $this->allow($aro, $aco, $action); return $this->allow($aro, $aco, $action);
} }
/** /**
* Deny alias * Deny alias
* *
@ -204,7 +200,6 @@ class DB_ACL extends AclBase{
function revoke($aro, $aco, $action = "*") { function revoke($aro, $aco, $action = "*") {
return $this->deny($aro, $aco, $action); return $this->deny($aro, $aco, $action);
} }
/** /**
* Get an ARO object from the given id or alias * Get an ARO object from the given id or alias
* *
@ -214,7 +209,6 @@ class DB_ACL extends AclBase{
function getAro($id = null) { function getAro($id = null) {
return $this->__getObject($id, 'Aro'); return $this->__getObject($id, 'Aro');
} }
/** /**
* Get an ACO object from the given id or alias * Get an ACO object from the given id or alias
* *
@ -224,9 +218,8 @@ class DB_ACL extends AclBase{
function getAco($id = null) { function getAco($id = null) {
return $this->__getObject($id, 'Aco'); return $this->__getObject($id, 'Aco');
} }
/** /**
* Privaate method * Private method
* *
*/ */
function __getObject($id = null, $object) { function __getObject($id = null, $object) {
@ -239,7 +232,6 @@ class DB_ACL extends AclBase{
if (is_numeric($id)) { if (is_numeric($id)) {
$key = 'user_id'; $key = 'user_id';
if ($object == 'Aco') { if ($object == 'Aco') {
$key = 'object_id'; $key = 'object_id';
} }
@ -253,7 +245,6 @@ class DB_ACL extends AclBase{
$obj->id = $tmp[$object]['id']; $obj->id = $tmp[$object]['id'];
return $obj; return $obj;
} }
/** /**
* Get an array of access-control links between the given Aro and Aco * Get an array of access-control links between the given Aro and Aco
* *
@ -272,17 +263,19 @@ class DB_ACL extends AclBase{
$obj['Aro'] = $obj['Aro']['Aro']; $obj['Aro'] = $obj['Aro']['Aro'];
$obj['Aco'] = $obj['Aco']['Aco']; $obj['Aco'] = $obj['Aco']['Aco'];
if ($obj['Aro'] == null || count($obj['Aro']) == 0 || $obj['Aco'] == null || count($obj['Aco']) == 0) if ($obj['Aro'] == null || count($obj['Aro']) == 0 || $obj['Aco'] == null || count($obj['Aco']) == 0) {
{
return false; return false;
} }
return array('aro' => $obj['Aro']['id'], return array(
'aro' => $obj['Aro']['id'],
'aco' => $obj['Aco']['id'], 'aco' => $obj['Aco']['id'],
'link' => $Link->findAll(array('ArosAco.aro_id' => $obj['Aro']['id'], 'link' => $Link->findAll(array(
'ArosAco.aco_id' => $obj['Aco']['id']))); 'ArosAco.aro_id' => $obj['Aro']['id'],
'ArosAco.aco_id' => $obj['Aco']['id']
))
);
} }
/** /**
* Enter description here... * Enter description here...
* *
@ -298,8 +291,8 @@ class DB_ACL extends AclBase{
$newKeys[] = $key['name']; $newKeys[] = $key['name'];
} }
} }
return $newKeys; return $newKeys;
} }
} }
?> ?>

View file

@ -69,10 +69,12 @@ class AclNode extends AppModel {
$parent = $parent[$class]; $parent = $parent[$class];
$this->_syncTable(1, $parent['lft'], $parent['lft']); $this->_syncTable(1, $parent['lft'], $parent['lft']);
} }
$return = $this->save(array($class => array($secondary_id => $link_id, $return = $this->save(array($class => array(
$secondary_id => $link_id,
'alias' => $alias, 'alias' => $alias,
'lft' => $parent['lft'] + 1, 'lft' => $parent['lft'] + 1,
'rght' => $parent['lft'] + 2))); 'rght' => $parent['lft'] + 2
)));
$this->id = $this->getLastInsertID(); $this->id = $this->getLastInsertID();
return $return; return $return;
} }
@ -103,9 +105,7 @@ class AclNode extends AppModel {
$object = $object[$class]; $object = $object[$class];
$parent = $this->getParent($id); $parent = $this->getParent($id);
if (($parent == null && $parent_id == null) if (($parent == null && $parent_id == null) || ($parent_id == $parent[$class][$secondary_id] && $parent_id != null) || ($parent_id == $parent[$class]['alias'] && $parent_id != null)) {
|| ($parent_id == $parent[$class][$secondary_id] && $parent_id != null)
|| ($parent_id == $parent[$class]['alias'] && $parent_id != null)) {
return false; return false;
} }
@ -245,4 +245,5 @@ class AclNode extends AppModel {
return $vars; return $vars;
} }
} }
?> ?>

View file

@ -38,7 +38,12 @@
*/ */
class ArosAco extends AppModel { class ArosAco extends AppModel {
/**
* Enter description here...
*
* @var unknown_type
*/
var $cacheQueries = false;
/** /**
* Enter description here... * Enter description here...
* *

View file

@ -38,6 +38,11 @@ uses('controller/components/acl_base');
*/ */
class INI_ACL extends AclBase{ class INI_ACL extends AclBase{
/**
* Array with configuration, parsed from ini file
*/
var $config = null;
/** /**
* The constructor must be overridden, as AclBase is abstract. * The constructor must be overridden, as AclBase is abstract.
* *
@ -54,7 +59,10 @@ class INI_ACL extends AclBase{
* @return boolean * @return boolean
*/ */
function check($aro, $aco, $aco_action = null) { function check($aro, $aco, $aco_action = null) {
$aclConfig=$this->readConfigFile(CONFIGS . 'acl.ini.php'); if ($this->config == null) {
$this->config = $this->readConfigFile(CONFIGS . 'acl.ini.php');
}
$aclConfig = $this->config;
//First, if the user is specifically denied, then DENY //First, if the user is specifically denied, then DENY
if (isset($aclConfig[$aro]['deny'])) { if (isset($aclConfig[$aro]['deny'])) {

View file

@ -47,18 +47,17 @@ class RequestHandlerComponent extends Object{
var $disableStartup = false; var $disableStartup = false;
var $__requestContent = array('js' => 'text/javascript', var $__requestContent = array(
'js' => 'text/javascript',
'css' => 'text/css', 'css' => 'text/css',
'html' => 'text/html', 'html' => 'text/html',
'form' => 'application/x-www-form-urlencoded', 'form' => 'application/x-www-form-urlencoded',
'file' => 'multipart/form-data', 'file' => 'multipart/form-data',
'xhtml' => array('application/xhtml+xml', 'xhtml' => array('application/xhtml+xml', 'application/xhtml', 'text/xhtml'),
'application/xhtml', 'xml' => array('application/xml', 'text/xml'),
'text/xhtml'),
'xml' => array('application/xml',
'text/xml'),
'rss' => 'application/rss+xml', 'rss' => 'application/rss+xml',
'atom' => 'application/atom+xml'); 'atom' => 'application/atom+xml'
);
var $__acceptTypes = array(); var $__acceptTypes = array();
@ -71,10 +70,8 @@ class RequestHandlerComponent extends Object{
$this->__acceptTypes[$i] = $type[0]; $this->__acceptTypes[$i] = $type[0];
} }
} }
parent::__construct(); parent::__construct();
} }
/** /**
* Startup * Startup
* *
@ -85,10 +82,8 @@ class RequestHandlerComponent extends Object{
if ($this->disableStartup) { if ($this->disableStartup) {
return; return;
} }
$this->setAjax($controller); $this->setAjax($controller);
} }
/** /**
* Sets a controller's layout based on whether or not the current call is Ajax * Sets a controller's layout based on whether or not the current call is Ajax
* *
@ -103,7 +98,6 @@ class RequestHandlerComponent extends Object{
header ('Content-Type: text/html; charset=UTF-8'); header ('Content-Type: text/html; charset=UTF-8');
} }
} }
/** /**
* Returns true if the current call is from Ajax, false otherwise * Returns true if the current call is from Ajax, false otherwise
* *
@ -116,7 +110,6 @@ class RequestHandlerComponent extends Object{
return false; return false;
} }
} }
/** /**
* Returns true if the current call accepts an XML response, false otherwise * Returns true if the current call accepts an XML response, false otherwise
* *
@ -125,7 +118,6 @@ class RequestHandlerComponent extends Object{
function isXml() { function isXml() {
return $this->accepts('xml'); return $this->accepts('xml');
} }
/** /**
* Returns true if the current call accepts an RSS response, false otherwise * Returns true if the current call accepts an RSS response, false otherwise
* *
@ -134,7 +126,6 @@ class RequestHandlerComponent extends Object{
function isRss() { function isRss() {
return $this->accepts('rss'); return $this->accepts('rss');
} }
/** /**
* Returns true if the current call accepts an RSS response, false otherwise * Returns true if the current call accepts an RSS response, false otherwise
* *
@ -143,7 +134,6 @@ class RequestHandlerComponent extends Object{
function isAtom() { function isAtom() {
return $this->accepts('atom'); return $this->accepts('atom');
} }
/** /**
* Returns true if the current call a POST request * Returns true if the current call a POST request
* *
@ -152,7 +142,6 @@ class RequestHandlerComponent extends Object{
function isPost() { function isPost() {
return (strtolower(env('REQUEST_METHOD')) == 'post'); return (strtolower(env('REQUEST_METHOD')) == 'post');
} }
/** /**
* Returns true if the current call a PUT request * Returns true if the current call a PUT request
* *
@ -161,7 +150,6 @@ class RequestHandlerComponent extends Object{
function isPut() { function isPut() {
return (strtolower(env('REQUEST_METHOD')) == 'put'); return (strtolower(env('REQUEST_METHOD')) == 'put');
} }
/** /**
* Returns true if the current call a GET request * Returns true if the current call a GET request
* *
@ -170,7 +158,6 @@ class RequestHandlerComponent extends Object{
function isGet() { function isGet() {
return (strtolower(env('REQUEST_METHOD')) == 'get'); return (strtolower(env('REQUEST_METHOD')) == 'get');
} }
/** /**
* Returns true if the current call a DELETE request * Returns true if the current call a DELETE request
* *
@ -179,7 +166,6 @@ class RequestHandlerComponent extends Object{
function isDelete() { function isDelete() {
return (strtolower(env('REQUEST_METHOD')) == 'delete'); return (strtolower(env('REQUEST_METHOD')) == 'delete');
} }
/** /**
* Gets Prototype version if call is Ajax, otherwise empty string. * Gets Prototype version if call is Ajax, otherwise empty string.
* The Prototype library sets a special "Prototype version" HTTP header. * The Prototype library sets a special "Prototype version" HTTP header.
@ -190,10 +176,8 @@ class RequestHandlerComponent extends Object{
if (env('HTTP_X_PROTOTYPE_VERSION') != null) { if (env('HTTP_X_PROTOTYPE_VERSION') != null) {
return env('HTTP_X_PROTOTYPE_VERSION'); return env('HTTP_X_PROTOTYPE_VERSION');
} }
return false; return false;
} }
/** /**
* Adds/sets the Content-type(s) for the given name * Adds/sets the Content-type(s) for the given name
* *
@ -204,7 +188,6 @@ class RequestHandlerComponent extends Object{
function setContent($name, $type) { function setContent($name, $type) {
$this->__requestContent[$name] = $type; $this->__requestContent[$name] = $type;
} }
/** /**
* Gets the server name from which this request was referred * Gets the server name from which this request was referred
* *
@ -218,10 +201,8 @@ class RequestHandlerComponent extends Object{
if (env('HTTP_X_FORWARDED_HOST') != null) { if (env('HTTP_X_FORWARDED_HOST') != null) {
$sess_host = env('HTTP_X_FORWARDED_HOST'); $sess_host = env('HTTP_X_FORWARDED_HOST');
} }
return trim(preg_replace('/:.*/', '', $sess_host)); return trim(preg_replace('/:.*/', '', $sess_host));
} }
/** /**
* Gets remote client IP * Gets remote client IP
* *
@ -245,10 +226,8 @@ class RequestHandlerComponent extends Object{
$ipaddr = preg_replace('/,.*/', '', $tmpipaddr); $ipaddr = preg_replace('/,.*/', '', $tmpipaddr);
} }
} }
return trim($ipaddr); return trim($ipaddr);
} }
/** /**
* Returns true if user agent string matches a mobile web browser * Returns true if user agent string matches a mobile web browser
* *
@ -257,7 +236,6 @@ class RequestHandlerComponent extends Object{
function isMobile() { function isMobile() {
return (preg_match('/' . REQUEST_MOBILE_UA . '/i', env('HTTP_USER_AGENT')) > 0); return (preg_match('/' . REQUEST_MOBILE_UA . '/i', env('HTTP_USER_AGENT')) > 0);
} }
/** /**
* Strips extra whitespace from output * Strips extra whitespace from output
* *
@ -267,7 +245,6 @@ class RequestHandlerComponent extends Object{
$r = preg_replace('/[\n\r\t]+/', '', $str); $r = preg_replace('/[\n\r\t]+/', '', $str);
return preg_replace('/\s{2,}/', ' ', $r); return preg_replace('/\s{2,}/', ' ', $r);
} }
/** /**
* Strips image tags from output * Strips image tags from output
* *
@ -279,19 +256,14 @@ class RequestHandlerComponent extends Object{
$str = preg_replace('/<img[^>]*>/i', '', $str); $str = preg_replace('/<img[^>]*>/i', '', $str);
return $str; return $str;
} }
/** /**
* Strips scripts and stylesheets from output * Strips scripts and stylesheets from output
* *
* @param string $str * @param string $str
*/ */
function stripScripts($str) { function stripScripts($str) {
return preg_replace( return preg_replace('/(<link[^>]+rel="[^"]*stylesheet"[^>]*>|<img[^>]*>|style="[^"]*")|<script[^>]*>.*?<\/script>|<style[^>]*>.*?<\/style>|<!--.*?-->/i', '', $str);
'/(<link[^>]+rel="[^"]*stylesheet"[^>]*>|<img[^>]*>|style="[^"]*")|<script[^>]*>.*?<\/script>|<style[^>]*>.*?<\/style>|<!--.*?-->/i',
'',
$str);
} }
/** /**
* Strips extra whitespace, images, scripts and stylesheets from output * Strips extra whitespace, images, scripts and stylesheets from output
* *
@ -303,7 +275,6 @@ class RequestHandlerComponent extends Object{
$str = $this->stripScripts($str); $str = $this->stripScripts($str);
return $str; return $str;
} }
/** /**
* Strips the specified tags from output * Strips the specified tags from output
* *
@ -320,7 +291,6 @@ class RequestHandlerComponent extends Object{
$str = preg_replace('/<' . $params[$i] . '[^>]*>/i', '', $str); $str = preg_replace('/<' . $params[$i] . '[^>]*>/i', '', $str);
$str = preg_replace('/<\/' . $params[$i] . '[^>]*>/i', '', $str); $str = preg_replace('/<\/' . $params[$i] . '[^>]*>/i', '', $str);
} }
return $str; return $str;
} }
@ -344,7 +314,6 @@ class RequestHandlerComponent extends Object{
return true; return true;
} }
} }
return false; return false;
} else if(is_string($type)) { } else if(is_string($type)) {
// If client only accepts */*, then assume default HTML browser // If client only accepts */*, then assume default HTML browser
@ -371,7 +340,6 @@ class RequestHandlerComponent extends Object{
} }
} }
} }
/** /**
* Determines which content types the client prefers * Determines which content types the client prefers
* *
@ -385,4 +353,5 @@ class RequestHandlerComponent extends Object{
} }
} }
} }
?> ?>

View file

@ -47,7 +47,19 @@ class SessionComponent extends Object{
$this->CakeSession = new CakeSession($base); $this->CakeSession = new CakeSession($base);
parent::__construct(); parent::__construct();
} }
/**
* Startup method. Copies controller data locally for rendering flash messages.
*
*/
function startup(&$controller) {
$this->base = $controller->base;
$this->webroot = $controller->webroot;
$this->here = $controller->here;
$this->params = $controller->params;
$this->action = $controller->action;
$this->data = $controller->data;
$this->plugin = $controller->plugin;
}
/** /**
* Enter description here... * Enter description here...
* *
@ -60,7 +72,6 @@ class SessionComponent extends Object{
function write($name, $value) { function write($name, $value) {
return $this->CakeSession->writeSessionVar($name, $value); return $this->CakeSession->writeSessionVar($name, $value);
} }
/** /**
* Enter description here... * Enter description here...
* *
@ -73,7 +84,6 @@ class SessionComponent extends Object{
function read($name = null) { function read($name = null) {
return $this->CakeSession->readSessionVar($name); return $this->CakeSession->readSessionVar($name);
} }
/** /**
* Enter description here... * Enter description here...
* *
@ -85,7 +95,6 @@ class SessionComponent extends Object{
function del($name) { function del($name) {
return $this->CakeSession->delSessionVar($name); return $this->CakeSession->delSessionVar($name);
} }
/** /**
* Enter description here... * Enter description here...
* @param unknown_type $name * @param unknown_type $name
@ -94,7 +103,6 @@ class SessionComponent extends Object{
function delete($name) { function delete($name) {
return $this->del($name); return $this->del($name);
} }
/** /**
* Enter description here... * Enter description here...
* *
@ -106,7 +114,6 @@ class SessionComponent extends Object{
function check($name) { function check($name) {
return $this->CakeSession->checkSessionVar($name); return $this->CakeSession->checkSessionVar($name);
} }
/** /**
* Enter description here... * Enter description here...
* *
@ -117,7 +124,6 @@ class SessionComponent extends Object{
function error() { function error() {
return $this->CakeSession->getLastError(); return $this->CakeSession->getLastError();
} }
/** /**
* Enter description here... * Enter description here...
* *
@ -137,15 +143,21 @@ class SessionComponent extends Object{
} else { } else {
$ctrl = null; $ctrl = null;
$view = new View($ctrl); $view = new View($ctrl);
$view->base = $this->base;
$view->webroot = $this->webroot;
$view->here = $this->here;
$view->params = $this->params;
$view->action = $this->action;
$view->data = $this->data;
$view->plugin = $this->plugin;
$view->helpers = array('Html');
$view->layout = $layout; $view->layout = $layout;
$view->pageTitle = ''; $view->pageTitle = '';
$view->_viewVars = $params; $view->_viewVars = $params;
$out = $view->renderLayout($flashMessage); $out = $view->renderLayout($flashMessage);
} }
$this->write('Message.' . $key, $out); $this->write('Message.' . $key, $out);
} }
/** /**
* Use like this. $this->Session->flash(); * Use like this. $this->Session->flash();
* *
@ -160,7 +172,6 @@ class SessionComponent extends Object{
return false; return false;
} }
} }
/** /**
* Enter description here... * Enter description here...
* *
@ -172,7 +183,6 @@ class SessionComponent extends Object{
function renew() { function renew() {
$this->CakeSession->renew(); $this->CakeSession->renew();
} }
/** /**
* Enter description here... * Enter description here...
* *
@ -185,7 +195,6 @@ class SessionComponent extends Object{
function valid() { function valid() {
return $this->CakeSession->isValid(); return $this->CakeSession->isValid();
} }
/** /**
* Enter description here... * Enter description here...
* *
@ -197,4 +206,5 @@ class SessionComponent extends Object{
$this->CakeSession->destroyInvalid(); $this->CakeSession->destroyInvalid();
} }
} }
?> ?>

View file

@ -54,6 +54,12 @@ class Controller extends Object{
* @var string Current URL * @var string Current URL
*/ */
var $here = null; var $here = null;
/**
* The webroot of the application
*
* @var string
*/
var $webroot = null;
/** /**
* Action to be performed. * Action to be performed.
* *
@ -75,6 +81,20 @@ class Controller extends Object{
* @access protected * @access protected
*/ */
var $helpers = array('Html'); var $helpers = array('Html');
/**
* Parameters received in the current request, i.e. GET and POST data
*
* @var array
* @access public
*/
var $params = array();
/**
* POST'ed model data
*
* @var array
* @access public
*/
var $data = array();
/** /**
* Enter description here... * Enter description here...
* *
@ -208,9 +228,7 @@ class Controller extends Object{
if (is_subclass_of($this, 'AppController')) { if (is_subclass_of($this, 'AppController')) {
$appVars = get_class_vars('AppController'); $appVars = get_class_vars('AppController');
foreach(array('components', foreach(array('components', 'helpers', 'uses') as $var) {
'helpers',
'uses')as $var) {
if (isset($appVars[$var]) && !empty($appVars[$var]) && is_array($this->{$var})) { if (isset($appVars[$var]) && !empty($appVars[$var]) && is_array($this->{$var})) {
$diff = array_diff($appVars[$var], $this->{$var}); $diff = array_diff($appVars[$var], $this->{$var});
$this->{$var} = array_merge($this->{$var}, $diff); $this->{$var} = array_merge($this->{$var}, $diff);
@ -306,11 +324,12 @@ class Controller extends Object{
function redirect($url, $status = null) { function redirect($url, $status = null) {
$this->autoRender = false; $this->autoRender = false;
$pos = strpos($url, '://'); $pos = strpos($url, '://');
$base = strip_plugin($this->base, $this->plugin);
if ($pos === false) { if ($pos === false) {
if (strpos($url, '/') !== 0) { if (strpos($url, '/') !== 0) {
$url = '/' . $url; $url = '/' . $url;
} }
$url = $this->base . $url; $url = $base . $url;
} }
if (function_exists('session_write_close')) { if (function_exists('session_write_close')) {
@ -318,7 +337,8 @@ class Controller extends Object{
} }
if ($status != null) { if ($status != null) {
$codes = array(100 => "HTTP/1.1 100 Continue", $codes = array(
100 => "HTTP/1.1 100 Continue",
101 => "HTTP/1.1 101 Switching Protocols", 101 => "HTTP/1.1 101 Switching Protocols",
200 => "HTTP/1.1 200 OK", 200 => "HTTP/1.1 200 OK",
201 => "HTTP/1.1 201 Created", 201 => "HTTP/1.1 201 Created",
@ -356,7 +376,8 @@ class Controller extends Object{
501 => "HTTP/1.1 501 Not Implemented", 501 => "HTTP/1.1 501 Not Implemented",
502 => "HTTP/1.1 502 Bad Gateway", 502 => "HTTP/1.1 502 Bad Gateway",
503 => "HTTP/1.1 503 Service Unavailable", 503 => "HTTP/1.1 503 Service Unavailable",
504 => "HTTP/1.1 504 Gateway Time-out"); 504 => "HTTP/1.1 504 Gateway Time-out"
);
if (isset($codes[$status])) { if (isset($codes[$status])) {
header($codes[$status]); header($codes[$status]);
@ -440,15 +461,10 @@ class Controller extends Object{
*/ */
function render($action = null, $layout = null, $file = null) { function render($action = null, $layout = null, $file = null) {
$viewClass = $this->view; $viewClass = $this->view;
if ($this->view != 'View' && !class_exists($viewClass)) { if ($this->view != 'View') {
$viewClass = $this->view . 'View'; $viewClass = $this->view . 'View';
loadView($this->view); loadView($this->view);
} }
if ($this->view != 'View') {
$viewClass = $this->view . 'View';
}
$this->beforeRender(); $this->beforeRender();
$this->_viewClass =& new $viewClass($this); $this->_viewClass =& new $viewClass($this);
@ -472,6 +488,7 @@ class Controller extends Object{
function referer($default = null, $local = false) { function referer($default = null, $local = false) {
$ref = env('HTTP_REFERER'); $ref = env('HTTP_REFERER');
$base = FULL_BASE_URL . $this->webroot; $base = FULL_BASE_URL . $this->webroot;
if ($ref != null && (defined(FULL_BASE_URL) || FULL_BASE_URL)) { if ($ref != null && (defined(FULL_BASE_URL) || FULL_BASE_URL)) {
if (strpos($ref, $base) === 0) { if (strpos($ref, $base) === 0) {
return substr($ref, strlen($base) - 1); return substr($ref, strlen($base) - 1);
@ -864,4 +881,5 @@ class Controller extends Object{
return false; return false;
} }
} }
?> ?>

View file

@ -103,7 +103,7 @@ class File extends Object{
* @return boolean Success * @return boolean Success
*/ */
function write($data, $mode = 'w') { function write($data, $mode = 'w') {
$fil = $this->getFullPath(); $file = $this->getFullPath();
if (!($handle = fopen($file, $mode))) { if (!($handle = fopen($file, $mode))) {
print ("[File] Could not open $file with mode $mode!"); print ("[File] Could not open $file with mode $mode!");
return false; return false;

View file

@ -48,7 +48,6 @@ class ConnectionManager extends Object{
* @access public * @access public
*/ */
var $config = null; var $config = null;
/** /**
* Holds instances DataSource objects * Holds instances DataSource objects
* *
@ -56,7 +55,6 @@ class ConnectionManager extends Object{
* @access private * @access private
*/ */
var $_dataSources = array(); var $_dataSources = array();
/** /**
* Contains a list of all file and class names used in Connection settings * Contains a list of all file and class names used in Connection settings
* *
@ -64,7 +62,6 @@ class ConnectionManager extends Object{
* @access private * @access private
*/ */
var $_connectionsEnum = array(); var $_connectionsEnum = array();
/** /**
* Constructor. * Constructor.
* *
@ -74,7 +71,6 @@ class ConnectionManager extends Object{
$this->config = new DATABASE_CONFIG(); $this->config = new DATABASE_CONFIG();
} }
} }
/** /**
* Gets a reference to the ConnectionManger object instance * Gets a reference to the ConnectionManger object instance
* *
@ -89,7 +85,6 @@ class ConnectionManager extends Object{
return $instance[0]; return $instance[0];
} }
/** /**
* Gets a reference to a DataSource object * Gets a reference to a DataSource object
* *
@ -104,7 +99,6 @@ class ConnectionManager extends Object{
} }
$connections = $_this->enumConnectionObjects(); $connections = $_this->enumConnectionObjects();
if (in_array($name, array_keys($connections))) { if (in_array($name, array_keys($connections))) {
$conn = $connections[$name]; $conn = $connections[$name];
$class = $conn['classname']; $class = $conn['classname'];
@ -112,14 +106,29 @@ class ConnectionManager extends Object{
$_this->_dataSources[$name] =& new $class($_this->config->{$name}); $_this->_dataSources[$name] =& new $class($_this->config->{$name});
$_this->_dataSources[$name]->configKeyName = $name; $_this->_dataSources[$name]->configKeyName = $name;
} else { } else {
trigger_error("ConnectionManager::getDataSource - Non-existent data source {$name}", trigger_error("ConnectionManager::getDataSource - Non-existent data source {$name}", E_USER_ERROR);
E_USER_ERROR);
return null; return null;
} }
return $_this->_dataSources[$name]; return $_this->_dataSources[$name];
} }
/**
* Gets a DataSource name from an object reference
*
* @param object $source
* @return string
*/
function getSourceName(&$source) {
$_this =& ConnectionManager::getInstance();
$names = array_keys($_this->_dataSources);
for ($i = 0; $i < count($names); $i++) {
if ($_this->_dataSources[$names[$i]] === $source) {
return $names[$i];
}
}
return null;
}
/** /**
* Loads the DataSource class for the given connection name * Loads the DataSource class for the given connection name
* *
@ -127,6 +136,7 @@ class ConnectionManager extends Object{
* @return boolean True on success, false on failure or if the class is already loaded * @return boolean True on success, false on failure or if the class is already loaded
*/ */
function loadDataSource($connName) { function loadDataSource($connName) {
$_this =& ConnectionManager::getInstance(); $_this =& ConnectionManager::getInstance();
$connections = $_this->enumConnectionObjects(); $connections = $_this->enumConnectionObjects();
$conn = $connections[$connName]; $conn = $connections[$connName];
@ -138,13 +148,12 @@ class ConnectionManager extends Object{
if (fileExistsInPath(LIBS . 'model' . DS . $conn['filename'] . '.php')) { if (fileExistsInPath(LIBS . 'model' . DS . $conn['filename'] . '.php')) {
require (LIBS . 'model' . DS . $conn['filename'] . '.php'); require (LIBS . 'model' . DS . $conn['filename'] . '.php');
} else if(file_exists(MODELS . $conn['filename'] . '.php')) { } else if(file_exists(MODELS . $conn['filename'] . '.php')) {
require (MODELS . $conn['filename'] . '.php'); require (MODELS . 'datasources' . DS . $conn['filename'] . '.php');
} else { } else {
trigger_error('Unable to load DataSource file ' . $conn['filename'] . '.php', E_USER_ERROR); trigger_error('Unable to load DataSource file ' . $conn['filename'] . '.php', E_USER_ERROR);
return null; return null;
} }
} }
/** /**
* Gets a list of class and file names associated with the user-defined DataSource connections * Gets a list of class and file names associated with the user-defined DataSource connections
* *
@ -157,25 +166,25 @@ class ConnectionManager extends Object{
if (!empty($_this->_connectionsEnum)) { if (!empty($_this->_connectionsEnum)) {
return $_this->_connectionsEnum; return $_this->_connectionsEnum;
} }
$connections = get_object_vars($_this->config); $connections = get_object_vars($_this->config);
if ($connections != null) { if ($connections != null) {
foreach($connections as $name => $config) { foreach($connections as $name => $config) {
if (isset($config['driver']) && $config['driver'] != null && $config['driver'] != '') {
$filename='dbo_' . $config['driver']; if (!isset($config['datasource'])) {
$classname=Inflector::camelize(strtolower('DBO_' . $config['driver'])); $config['datasource'] = 'dbo';
}
if (isset($config['driver']) && $config['driver'] != null && !empty($config['driver'])) {
$filename = $config['datasource'] . DS . $config['datasource'] . '_' . $config['driver'];
$classname = Inflector::camelize(strtolower($config['datasource'] . '_' . $config['driver']));
} else { } else {
$filename = $config['datasource'] . '_source'; $filename = $config['datasource'] . '_source';
$classname = Inflector::camelize(strtolower($config['datasource'] . '_source')); $classname = Inflector::camelize(strtolower($config['datasource'] . '_source'));
} }
$_this->_connectionsEnum[$name] = array('filename' => $filename, 'classname' => $classname);
// TODO 2.0: Change 'dbo' to $config['datasource']
$filename='dbo' . DS . $filename;
$_this->_connectionsEnum[$name]=array('filename' => $filename,
'classname' => $classname);
} }
return $this->_connectionsEnum; return $this->_connectionsEnum;
} else { } else {
$this->cakeError('missingConnection', array(array('className' => 'ConnectionManager'))); $this->cakeError('missingConnection', array(array('className' => 'ConnectionManager')));

View file

@ -222,7 +222,7 @@ class DataSource extends Object{
*/ */
function __cacheDescription($object, $data = null) { function __cacheDescription($object, $data = null) {
if (DEBUG > 0) { if (DEBUG > 0) {
$expires = "+10 seconds"; $expires = "+15 seconds";
} else { } else {
$expires = "+999 days"; $expires = "+999 days";
} }
@ -233,7 +233,7 @@ class DataSource extends Object{
} else { } else {
$cache = null; $cache = null;
} }
$new = cache('models' . DS . strtolower(get_class($this)) . '_' . $object, $cache, $expires); $new = cache('models' . DS . ConnectionManager::getSourceName($this) . '_' . $object, $cache, $expires);
if ($new != null) { if ($new != null) {
$new = unserialize($new); $new = unserialize($new);
@ -276,7 +276,7 @@ class DataSource extends Object{
if (isset($this->__descriptions[$model->table])) { if (isset($this->__descriptions[$model->table])) {
return $this->__descriptions[$model->table]; return $this->__descriptions[$model->table];
} }
$cache=$this->__cacheDescription($model->table); $cache = $this->__cacheDescription($model->tablePrefix.$model->table);
if ($cache !== null) { if ($cache !== null) {
$this->__descriptions[$model->table] =& $cache; $this->__descriptions[$model->table] =& $cache;
@ -355,10 +355,10 @@ class DataSource extends Object{
* @param unknown_type $assocData * @param unknown_type $assocData
* @param Model $model * @param Model $model
* @param Model $linkModel * @param Model $linkModel
* @param unknown_type $index * @param array $stack
* @return unknown * @return unknown
*/ */
function insertQueryData($query, $data, $association, $assocData, &$model, &$linkModel, $index) { function insertQueryData($query, $data, $association, $assocData, &$model, &$linkModel, $stack) {
$keys = array('{$__cakeID__$}', '{$__cakeForeignKey__$}'); $keys = array('{$__cakeID__$}', '{$__cakeForeignKey__$}');
foreach($keys as $key) { foreach($keys as $key) {
@ -367,10 +367,22 @@ class DataSource extends Object{
if (strpos($query, $key) !== false) { if (strpos($query, $key) !== false) {
switch($key) { switch($key) {
case '{$__cakeID__$}': case '{$__cakeID__$}':
if (isset($data[$index][$model->name])) { if (isset($data[$model->name]) || isset($data[$association])) {
if (isset($data[$index][$model->name][$model->primaryKey])) { if (isset($data[$model->name][$model->primaryKey])) {
$val = $data[$index][$model->name][$model->primaryKey]; $val = $data[$model->name][$model->primaryKey];
} elseif (isset($data[$association][$model->primaryKey])) {
$val = $data[$association][$model->primaryKey];
}
} else { } else {
$found = false;
foreach (array_reverse($stack) as $assoc) {
if (isset($data[$assoc]) && isset($data[$assoc][$model->primaryKey])) {
$val = $data[$assoc][$model->primaryKey];
$found = true;
break;
}
}
if (!$found) {
$val = ''; $val = '';
} }
} }
@ -382,8 +394,22 @@ class DataSource extends Object{
if (isset($assoc['foreignKey'])) { if (isset($assoc['foreignKey'])) {
$foreignKey = $assoc['foreignKey']; $foreignKey = $assoc['foreignKey'];
if (isset($data[$index][$model->name][$foreignKey])) { if (isset($data[$model->name][$foreignKey])) {
$val = $data[$index][$model->name][$foreignKey]; $val = $data[$model->name][$foreignKey];
} elseif (isset($data[$association][$foreignKey])) {
$val = $data[$association][$foreignKey];
} else {
$found = false;
foreach (array_reverse($stack) as $assoc) {
if (isset($data[$assoc]) && isset($data[$assoc][$model->primaryKey])) {
$val = $data[$assoc][$model->primaryKey];
$found = true;
break;
}
}
if (!$found) {
$val = '';
}
} }
} }
break 3; break 3;
@ -442,13 +468,6 @@ class DataSource extends Object{
} }
return $data; return $data;
} }
/**
* To-be-overridden in subclasses.
*
*/
function buildSchemaQuery($schema) {
die ("Implement in DBO");
}
/** /**
* Closes the current datasource. * Closes the current datasource.
* *

View file

@ -129,7 +129,7 @@ class DboSource extends DataSource {
} }
if (DEBUG > 0) { if (DEBUG > 0) {
$expires = "+10 seconds"; $expires = "+30 seconds";
} else { } else {
$expires = "+999 days"; $expires = "+999 days";
} }
@ -137,7 +137,7 @@ class DboSource extends DataSource {
if ($data != null) { if ($data != null) {
$data = serialize($data); $data = serialize($data);
} }
$filename = strtolower(get_class($this)) . '_' . $this->config['database'] . '_list'; $filename = ConnectionManager::getSourceName($this) . '_' . $this->config['database'] . '_list';
$new = cache('models' . DS . $filename, $data, $expires); $new = cache('models' . DS . $filename, $data, $expires);
if ($new != null) { if ($new != null) {
@ -345,7 +345,7 @@ class DboSource extends DataSource {
} else { } else {
$text = 'query'; $text = 'query';
} }
print ("<table border = \"0\">\n<caption>{$this->_queriesCnt} {$text} took {$this->_queriesTime} ms</caption>\n"); print ("<table id=\"cakeSqlLog\" border = \"0\">\n<caption>{$this->_queriesCnt} {$text} took {$this->_queriesTime} ms</caption>\n");
print ("<thead>\n<tr><th>Nr</th><th>Query</th><th>Error</th><th>Affected</th><th>Num. rows</th><th>Took (ms)</th></tr>\n</thead>\n<tbody>\n"); print ("<thead>\n<tr><th>Nr</th><th>Query</th><th>Error</th><th>Affected</th><th>Num. rows</th><th>Took (ms)</th></tr>\n</thead>\n<tbody>\n");
foreach($log as $k => $i) { foreach($log as $k => $i) {
@ -524,7 +524,8 @@ class DboSource extends DataSource {
} }
if (isset($db) && $db != null) { if (isset($db) && $db != null) {
$db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1); $stack = array($assoc);
$db->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1, $stack);
unset($db); unset($db);
} }
} }
@ -546,26 +547,34 @@ class DboSource extends DataSource {
* @return unknown * @return unknown
*/ */
function __filterResults(&$results, &$model, $filtered = array()) { function __filterResults(&$results, &$model, $filtered = array()) {
$filtering = array(); $filtering = array();
$associations = am($model->belongsTo, $model->hasOne, $model->hasMany, $model->hasAndBelongsToMany); $associations = am($model->belongsTo, $model->hasOne, $model->hasMany, $model->hasAndBelongsToMany);
$count = count($results); $count = count($results);
for($i = 0; $i < $count; $i++) { for($i = 0; $i < $count; $i++) {
if (is_array($results[$i])) { if (is_array($results[$i])) {
$keys = array_keys($results[$i]); $keys = array_keys($results[$i]);
$count2 = count($keys); $count2 = count($keys);
for($j = 0; $j < $count2; $j++) { for($j = 0; $j < $count2; $j++) {
$key = $keys[$j];
if ($model->name != $key && !in_array($key, $filtered)) { $key = $keys[$j];
if (isset($associations[$key])) {
$className = $associations[$key]['className'];
} else {
$className = $key;
}
if ($model->name != $className && !in_array($key, $filtered)) {
if (!in_array($key, $filtering)) { if (!in_array($key, $filtering)) {
$filtering[] = $key; $filtering[] = $key;
} }
if (isset($model->{$key}) && is_object($model->{$key})) { if (isset($model->{$className}) && is_object($model->{$className})) {
$data = $model->{$key}->afterFind(array(array($key => $results[$i][$key]))); $data = $model->{$className}->afterFind(array(array($key => $results[$i][$key])));
} else { } else {
$data = $model->{$associations[$key]['className']}->afterFind(array(array($key => $results[$i][$key]))); $data = $model->{$className}->afterFind(array(array($key => $results[$i][$key])));
} }
$results[$i][$key] = $data[0][$key]; $results[$i][$key] = $data[0][$key];
} }
@ -586,8 +595,9 @@ class DboSource extends DataSource {
* @param unknown_type $external * @param unknown_type $external
* @param unknown_type $resultSet * @param unknown_type $resultSet
* @param integer $recursive Number of levels of association * @param integer $recursive Number of levels of association
* @param array $stack
*/ */
function queryAssociation(&$model, &$linkModel, $type, $association, $assocData, &$queryData, $external = false, &$resultSet, $recursive) { function queryAssociation(&$model, &$linkModel, $type, $association, $assocData, &$queryData, $external = false, &$resultSet, $recursive, $stack) {
$query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet); $query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet);
if ($query) { if ($query) {
@ -601,12 +611,14 @@ class DboSource extends DataSource {
} }
return null; return null;
} }
$count = count($resultSet);
$count = count($resultSet);
for($i = 0; $i < $count; $i++) { for($i = 0; $i < $count; $i++) {
$row =& $resultSet[$i]; $row =& $resultSet[$i];
$q = $this->insertQueryData($query, $resultSet, $association, $assocData, $model, $linkModel, $i); $q = $this->insertQueryData($query, $resultSet[$i], $association, $assocData, $model, $linkModel, $stack);
$fetch = $this->fetchAll($q, $model->cacheQueries, $model->name); $fetch = $this->fetchAll($q, $model->cacheQueries, $model->name);
if (!empty($fetch) && is_array($fetch)) { if (!empty($fetch) && is_array($fetch)) {
if ($recursive > 0) { if ($recursive > 0) {
foreach($linkModel->__associations as $type1) { foreach($linkModel->__associations as $type1) {
@ -614,7 +626,9 @@ class DboSource extends DataSource {
$deepModel =& $linkModel->{$assocData1['className']}; $deepModel =& $linkModel->{$assocData1['className']};
if ($deepModel->name != $model->name) { if ($deepModel->name != $model->name) {
$this->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1); $tmpStack = $stack;
$tmpStack[] = $assoc1;
$this->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
} }
} }
} }
@ -637,6 +651,7 @@ class DboSource extends DataSource {
* @param unknown_type $type * @param unknown_type $type
*/ */
function __mergeAssociation(&$data, $merge, $association, $type) { function __mergeAssociation(&$data, $merge, $association, $type) {
if (isset($merge[0]) && !isset($merge[0][$association])) { if (isset($merge[0]) && !isset($merge[0][$association])) {
$association = Inflector::pluralize($association); $association = Inflector::pluralize($association);
} }
@ -711,7 +726,7 @@ class DboSource extends DataSource {
$sql = $queryData['selfJoin'][0]; $sql = $queryData['selfJoin'][0];
$sql .= ' ' . join(' ', $queryData['joins']); $sql .= ' ' . join(' ', $queryData['joins']);
$sql .= $this->conditions($queryData['conditions']) . ' ' . $this->order($queryData['order']); $sql .= $this->conditions($queryData['conditions']) . ' ' . $this->order($queryData['order']);
$sql .= ' ' . $this->limit($queryData['limit']); $sql .= ' ' . $this->limit($queryData['limit'], $queryData['offset']);
$result = preg_replace('/FROM/', $replace, $sql); $result = preg_replace('/FROM/', $replace, $sql);
return $result; return $result;
} }
@ -730,8 +745,11 @@ class DboSource extends DataSource {
* @return unknown * @return unknown
*/ */
function generateAssociationQuery(&$model, &$linkModel, $type, $association = null, $assocData = array(), &$queryData, $external = false, &$resultSet) { function generateAssociationQuery(&$model, &$linkModel, $type, $association = null, $assocData = array(), &$queryData, $external = false, &$resultSet) {
$this->__scrubQueryData($queryData); $this->__scrubQueryData($queryData);
$this->__scrubQueryData($assocData);
$joinedOnSelf = false; $joinedOnSelf = false;
if ($linkModel == null) { if ($linkModel == null) {
if (array_key_exists('selfJoin', $queryData)) { if (array_key_exists('selfJoin', $queryData)) {
return $this->generateSelfAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet); return $this->generateSelfAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet);
@ -746,7 +764,7 @@ class DboSource extends DataSource {
$sql = 'SELECT '; $sql = 'SELECT ';
if ($this->goofyLimit) { if ($this->goofyLimit) {
$sql .= $this->limit($queryData['limit']); $sql .= $this->limit($queryData['limit'], $queryData['offset']);
} }
$sql .= ' ' . join(', ', $this->fields($model, $model->name, $queryData['fields'])) . $joinFields . ' FROM '; $sql .= ' ' . join(', ', $this->fields($model, $model->name, $queryData['fields'])) . $joinFields . ' FROM ';
$sql .= $this->fullTableName($model) . ' ' . $this->alias; $sql .= $this->fullTableName($model) . ' ' . $this->alias;
@ -754,7 +772,7 @@ class DboSource extends DataSource {
$sql .= $this->conditions($queryData['conditions']) . ' ' . $this->order($queryData['order']); $sql .= $this->conditions($queryData['conditions']) . ' ' . $this->order($queryData['order']);
if (!$this->goofyLimit) { if (!$this->goofyLimit) {
$sql .= ' ' . $this->limit($queryData['limit']); $sql .= ' ' . $this->limit($queryData['limit'], $queryData['offset']);
} }
} }
return $sql; return $sql;
@ -779,7 +797,7 @@ class DboSource extends DataSource {
$limit = ''; $limit = '';
if (isset($queryData['limit']) && !empty($queryData['limit'])) { if (isset($queryData['limit']) && !empty($queryData['limit'])) {
$limit = $this->limit($queryData['limit']); $limit = $this->limit($queryData['limit'], $queryData['offset']);
} }
$sql = 'SELECT '; $sql = 'SELECT ';
@ -851,7 +869,7 @@ class DboSource extends DataSource {
if ($external) { if ($external) {
$limit = ''; $limit = '';
if (isset($assocData['limit'])) { if (isset($assocData['limit'])) {
$limit = $this->limit($assocData['limit']); $limit = $this->limit($assocData['limit'], $queryData['offset']);
} }
if (!isset($assocData['fields'])) { if (!isset($assocData['fields'])) {
@ -905,11 +923,20 @@ class DboSource extends DataSource {
if (isset($assocData['conditions']) && !empty($assocData['conditions'])) { if (isset($assocData['conditions']) && !empty($assocData['conditions'])) {
if (is_array($queryData['conditions'])) { if (is_array($queryData['conditions'])) {
$queryData['conditions'] = array_merge($assocData['conditions'], $queryData['conditions']); $queryData['conditions'] = array_merge((array)$assocData['conditions'], $queryData['conditions']);
} else {
if (!empty($queryData['conditions'])){
$queryData['conditions'] = array($queryData['conditions']);
if (is_array($assocData['conditions'])){
array_merge($queryData['conditions'],$assocData['conditions']);
} else {
$queryData['conditions'][] = $assocData['conditions'];
}
} else { } else {
$queryData['conditions'] = $assocData['conditions']; $queryData['conditions'] = $assocData['conditions'];
} }
} }
}
if (!in_array($sql, $queryData['joins'])) { if (!in_array($sql, $queryData['joins'])) {
$queryData['joins'][] = $sql; $queryData['joins'][] = $sql;
@ -925,7 +952,7 @@ class DboSource extends DataSource {
$limit = ''; $limit = '';
if (isset($assocData['limit'])) { if (isset($assocData['limit'])) {
$limit = $this->limit($assocData['limit']); $limit = $this->limit($assocData['limit'], $queryData['offset']);
} }
$conditions = $assocData['conditions']; $conditions = $assocData['conditions'];
@ -966,7 +993,7 @@ class DboSource extends DataSource {
$limit = ''; $limit = '';
if (isset($assocData['limit'])) { if (isset($assocData['limit'])) {
$limit = $this->limit($assocData['limit']); $limit = $this->limit($assocData['limit'], $queryData['offset']);
} }
$sql = 'SELECT '; $sql = 'SELECT ';
@ -1005,9 +1032,14 @@ class DboSource extends DataSource {
function update(&$model, $fields = array(), $values = array()) { function update(&$model, $fields = array(), $values = array()) {
$updates = array(); $updates = array();
$combined = array_combine($fields, $values); $combined = array_combine($fields, $values);
foreach($combined as $field => $value) { foreach($combined as $field => $value) {
if ($value === null) {
$updates[] = $this->name($field) . ' = NULL';
} else {
$updates[] = $this->name($field) . ' = ' . $this->value($value, $model->getColumnType($field)); $updates[] = $this->name($field) . ' = ' . $this->value($value, $model->getColumnType($field));
} }
}
$sql = 'UPDATE ' . $this->fullTableName($model); $sql = 'UPDATE ' . $this->fullTableName($model);
$sql .= ' SET ' . join(',', $updates); $sql .= ' SET ' . join(',', $updates);
$sql .= ' WHERE ' . $this->name($model->primaryKey) . ' = ' . $this->value($model->getID(), $model->getColumnType($model->primaryKey)); $sql .= ' WHERE ' . $this->name($model->primaryKey) . ' = ' . $this->value($model->getID(), $model->getColumnType($model->primaryKey));
@ -1091,6 +1123,10 @@ class DboSource extends DataSource {
if (!isset($data['limit'])) { if (!isset($data['limit'])) {
$data['limit'] = ''; $data['limit'] = '';
} }
if (!isset($data['offset'])) {
$data['offset'] = null;
}
} }
/** /**
* Generates the fields list of an SQL query. * Generates the fields list of an SQL query.
@ -1193,30 +1229,34 @@ class DboSource extends DataSource {
} }
function conditionKeysToString($conditions) { function conditionKeysToString($conditions) {
$data = null;
$out = array(); $out = array();
$operator = null;
$bool = array('and', 'or', 'and not', 'or not', 'xor', '||', '&&'); $bool = array('and', 'or', 'and not', 'or not', 'xor', '||', '&&');
foreach($conditions as $key => $value) { foreach($conditions as $key => $value) {
if (in_array(strtolower(trim($key)), $bool)) { if (in_array(strtolower(trim($key)), $bool)) {
$out[] = '(' . join(') ' . $key . ' (', $this->conditionKeysToString($value)) . ')'; $out[] = '(' . join(') ' . $key . ' (', $this->conditionKeysToString($value)) . ')';
} else { } else {
if (is_array($value)) { if (is_array($value) && !empty($value)) {
$data = $this->name($key) . ' IN (';
$keys = array_keys($value);
if ($keys[0] === 0) {
$data = $this->name($key) . ' IN (';
foreach($value as $valElement) { foreach($value as $valElement) {
$data .= $this->value($valElement) . ', '; $data .= $this->value($valElement) . ', ';
} }
$data[strlen($data) - 2] = ')'; $data[strlen($data) - 2] = ')';
} else {
$out[] = '(' . join(') AND (', $this->conditionKeysToString($value)) . ')';
}
} elseif(is_numeric($key)) { } elseif(is_numeric($key)) {
$data = ' ' . $value; $data = ' ' . $value;
} elseif($value === null) { } elseif($value === null) {
$data = $this->name($key) . ' = NULL'; $data = $this->name($key) . ' = NULL';
} elseif($value === '') { } elseif($value === '') {
$data = $this->name($key) . " = ''"; $data = $this->name($key) . " = ''";
} elseif(preg_match( } elseif(preg_match('/^([a-z]*\\([a-z0-9]*\\)\\x20?|(?:like\\x20)|(?:or\\x20)|(?:between\\x20)|(?:regexp\\x20)|[<> = !]{1,3}\\x20?)?(.*)/i', $value, $match)) {
'/^([a-z]*\\([a-z0-9]*\\)\\x20?|(?:like\\x20)|(?:or\\x20)|(?:between\\x20)|(?:regexp\\x20)|[<> = !]{1,3}\\x20?)?(.*)/i', $value, $match)) {
if (preg_match('/(\\x20[\\w]*\\x20)/', $key, $regs)) { if (preg_match('/(\\x20[\\w]*\\x20)/', $key, $regs)) {
$clause = $regs['1']; $clause = $regs['1'];
$key = preg_replace('/' . $regs['1'] . '/', '', $key); $key = preg_replace('/' . $regs['1'] . '/', '', $key);
@ -1238,7 +1278,9 @@ class DboSource extends DataSource {
} }
} }
$out[] = $operator . $data; if ($data != null) {
$out[] = $data;
}
} }
} }
return $out; return $out;
@ -1370,8 +1412,14 @@ class DboSource extends DataSource {
if ($this->fullDebug) { if ($this->fullDebug) {
$this->showLog(); $this->showLog();
} }
$this->_conn = NULL; $this->disconnect();
$this->connected = false; }
/**
* To-be-overridden in subclasses.
*
*/
function buildSchemaQuery($schema) {
die ("Implement in DBO");
} }
/** /**
* Destructor. Closes connection to the database. * Destructor. Closes connection to the database.
@ -1392,7 +1440,8 @@ class DboSource extends DataSource {
* @return boolean True if the table has a matching record, else false * @return boolean True if the table has a matching record, else false
*/ */
function hasAny($model, $sql) { function hasAny($model, $sql) {
$out = $this->one("SELECT COUNT(*) " . $this->alias . "count FROM " . $this->fullTableName($model) . ($sql ? ' ' . $sql : '')); $sql = $this->conditions($sql);
$out = $this->one("SELECT COUNT(*) " . $this->alias . "count FROM " . $this->fullTableName($model) . ' ' . ($sql ? ' ' . $sql : 'WHERE 1 = 1'));
if (is_array($out)) { if (is_array($out)) {
return $out[0]['count']; return $out[0]['count'];

View file

@ -0,0 +1,452 @@
<?php
/* SVN FILE: $Id$ */
/**
* MySQLi layer for DBO
*
* Long description for file
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework <http://www.cakephp.org/>
* Copyright (c) 2006, Cake Software Foundation, Inc.
* 1785 E. Sahara Avenue, Suite 490-204
* Las Vegas, Nevada 89104
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
* @package cake
* @subpackage cake.cake.libs.model.dbo
* @since CakePHP v 1.1.4.2974
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
/**
* Include DBO.
*/
uses('model'.DS.'datasources'.DS.'dbo_source');
/**
* Short description for class.
*
* Long description for class
*
* @package cake
* @subpackage cake.cake.libs.model.dbo
*/
class DboMysqli extends DboSource {
/**
* Enter description here...
*
* @var unknown_type
*/
var $description = "Mysqli DBO Driver";
/**
* Enter description here...
*
* @var unknown_type
*/
var $startQuote = "`";
/**
* Enter description here...
*
* @var unknown_type
*/
var $endQuote = "`";
/**
* Base configuration settings for Mysqli driver
*
* @var array
*/
var $_baseConfig = array('persistent' => true,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'cake',
'port' => '3306',
'connect' => 'mysqli_pconnect');
/**
* Mysqli column definition
*
* @var array
*/
var $columns = array('primary_key' => array('name' => 'int(11) DEFAULT NULL auto_increment'),
'string' => array('name' => 'varchar', 'limit' => '255'),
'text' => array('name' => 'text'),
'integer' => array('name' => 'int', 'limit' => '11', 'formatter' => 'intval'),
'float' => array('name' => 'float', 'formatter' => 'floatval'),
'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'time' => array('name' => 'time', 'format' => 'H:i:s', 'formatter' => 'date'),
'date' => array('name' => 'date', 'format' => 'Y-m-d', 'formatter' => 'date'),
'binary' => array('name' => 'blob'),
'boolean' => array('name' => 'tinyint', 'limit' => '1'));
/**
* Connects to the database using options in the given configuration array.
*
* @return boolean True if the database could be connected, else false
*/
function connect() {
$config = $this->config;
$connect = $config['connect'];
$this->connected = false;
if (!$config['persistent']) {
$this->connection = mysqli_connect($config['host'], $config['login'], $config['password'], true);
} else {
$this->connection = $connect($config['host'], $config['login'], $config['password']);
}
if (mysqli_select_db($this->connection, $config['database'])) {
$this->connected = true;
}
return $this->connected;
}
/**
* Disconnects from database.
*
* @return boolean True if the database could be disconnected, else false
*/
function disconnect() {
$this->connected = !@mysqli_close($this->connection);
return !$this->connected;
}
/**
* Executes given SQL statement.
*
* @param string $sql SQL statement
* @return resource Result resource identifier
* @access protected
*/
function _execute($sql) {
return mysqli_query($this->connection, $sql);
}
/**
* Returns a row from given resultset as an array .
*
* @param bool $assoc Associative array only, or both?
* @return array The fetched row as an array
*/
function fetchRow($assoc = false) {
if(is_resource($this->_result)) {
$this->resultSet($this->_result);
$resultRow = $this->fetchResult();
return $resultRow;
} else {
return null;
}
}
/**
* 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->config['database'] . ';');
if (!$result) {
return array();
} else {
$tables = array();
while ($line = mysqli_fetch_array($result)) {
$tables[] = $line[0];
}
parent::listSources($tables);
return $tables;
}
}
/**
* Returns an array of the fields in given table name.
*
* @param string $tableName Name of database table to inspect
* @return array Fields in table. Keys are name and type
*/
function describe(&$model) {
$cache = parent::describe($model);
if ($cache != null) {
return $cache;
}
$fields = false;
$cols = $this->_execute('DESCRIBE ' . $this->fullTableName($model));
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])) {
$fields[] = array('name' => $column[0]['Field'], 'type' => $this->column($column[0]['Type']), 'null' => $column[0]['Null']);
}
}
$this->__cacheDescription($model->tablePrefix.$model->table, $fields);
return $fields;
}
/**
* Returns a quoted name of $data for use in an SQL statement.
*
* @param string $data Name (table.field) to be prepared for use in an SQL statement
* @return string Quoted for MySQL
*/
function name($data) {
if ($data == '*') {
return '*';
}
$pos = strpos($data, '`');
if ($pos === false) {
$data = '`'. str_replace('.', '`.`', $data) .'`';
}
return $data;
}
/**
* 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) {
return 'NULL';
}
if($data == '') {
return "''";
}
switch ($column) {
case 'boolean':
$data = $this->boolean((bool)$data);
break;
default:
if (ini_get('magic_quotes_gpc') == 1) {
$data = stripslashes($data);
}
$data = mysqli_real_escape_string($this->connection, $data);
break;
}
return "'" . $data . "'";
}
/**
* Begin a transaction
*
* @param unknown_type $model
* @return boolean True on success, false on fail
* (i.e. if the database/model does not support transactions).
*/
function begin(&$model) {
if (parent::begin($model)) {
if ($this->execute('START TRANSACTION')) {
$this->__transactionStarted = true;
return true;
}
}
return false;
}
/**
* Commit a transaction
*
* @param unknown_type $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).
*/
function commit(&$model) {
if (parent::commit($model)) {
$this->__transactionStarted;
return $this->execute('COMMIT');
}
return false;
}
/**
* Rollback a transaction
*
* @param unknown_type $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).
*/
function rollback(&$model) {
if (parent::rollback($model)) {
return $this->execute('ROLLBACK');
}
return false;
}
/**
* 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 int 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 int Number of rows in resultset
*/
function lastNumRows() {
if ($this->_result and is_resource($this->_result)) {
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 = mysqli_insert_id($this->connection);
if ($id) {
return $id;
}
$data = $this->fetchAll('SELECT LAST_INSERT_ID() as id From '.$source);
if ($data && isset($data[0]['id'])) {
return $data[0]['id'];
}
}
/**
* Converts database-layer column types to basic types
*
* @param string $real Real database-layer column type (i.e. "varchar(255)")
* @return string Abstract column type (i.e. "string")
*/
function column($real) {
if (is_array($real)) {
$col = $real['name'];
if (isset($real['limit']))
{
$col .= '('.$real['limit'].')';
}
return $col;
}
$col = r(')', '', $real);
$limit = null;
@list($col, $limit) = explode('(', $col);
if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
return $col;
}
if ($col == 'tinyint' && $limit == '1') {
return 'boolean';
}
if (strpos($col, 'int') !== false) {
return 'integer';
}
if (strpos($col, 'char') !== false || $col == 'tinytext') {
return 'string';
}
if (strpos($col, 'text') !== false) {
return 'text';
}
if (strpos($col, 'blob') !== false) {
return 'binary';
}
if (in_array($col, array('float', 'double', 'decimal'))) {
return 'float';
}
if (strpos($col, 'enum') !== false) {
return "enum($limit)";
}
return 'text';
}
/**
* Enter description here...
*
* @param unknown_type $results
*/
function resultSet(&$results) {
$this->results =& $results;
$this->map = array();
$num_fields = mysqli_num_fields($results);
$index = 0;
$j = 0;
while ($j < $num_fields) {
$column = mysqli_fetch_field($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();
$i = 0;
foreach ($row as $index => $field) {
list($table, $column) = $this->map[$index];
$resultRow[$table][$column] = $row[$index];
$i++;
}
return $resultRow;
} else {
return false;
}
}
/**
* Enter description here...
*
* @param unknown_type $schema
* @return unknown
*/
function buildSchemaQuery($schema) {
$search = array('{AUTOINCREMENT}', '{PRIMARY}', '{UNSIGNED}', '{FULLTEXT}',
'{FULLTEXT_MYSQL}', '{BOOLEAN}', '{UTF_8}');
$replace = array('int(11) not null auto_increment', 'primary key', 'unsigned',
'FULLTEXT', 'FULLTEXT', 'enum (\'true\', \'false\') NOT NULL default \'true\'',
'/*!40100 CHARACTER SET utf8 COLLATE utf8_unicode_ci */');
$query = trim(r($search, $replace, $schema));
return $query;
}
}
?>

View file

@ -72,7 +72,9 @@ class DboOdbc extends DboSource{
var $_baseConfig = array('persistent' => true, var $_baseConfig = array('persistent' => true,
'login' => 'root', 'login' => 'root',
'password' => '', 'password' => '',
'database' => 'cake'); 'database' => 'cake',
'connect' => 'odbc_pconnect'
);
/** /**
* Enter description here... * Enter description here...
@ -148,28 +150,39 @@ class DboOdbc extends DboSource{
return null; return null;
} }
} }
/** /**
* Returns an array of sources (tables) in the database. * Returns an array of sources (tables) in the database.
* *
* @return array Array of tablenames in the database * @return array Array of tablenames in the database
*/ */
function listSources() { function listSources() {
$cache = parent::listSources();
if ($cache != null) {
return $cache;
}
/*$result = odbc_tables($this->connection);
if (function_exists('odbc_fetch_row')) {
echo 'GOOD';
} else {
echo 'BAD';
}*/
$result = odbc_tables($this->connection); $result = odbc_tables($this->connection);
if (!$result) {
return array();
} else {
$tables = array(); $tables = array();
while (odbc_fetch_row($result)) {
while($line = odbc_fetch_array($result)) { array_push($tables, odbc_result($result, "TABLE_NAME"));
$tables[] = strtolower($line['TABLE_NAME']);
} }
foreach( $tables as $t ) {
echo "$t\n";
}
parent::listSources($tables);
return $tables; return $tables;
} }
}
/** /**
* Returns an array of the fields in given table name. * Returns an array of the fields in given table name.
* *

View file

@ -359,7 +359,6 @@ class Model extends Object{
$return = $db->query($method, $params, $this); $return = $db->query($method, $params, $this);
return true; return true;
} }
/** /**
* Bind model associations on the fly. * Bind model associations on the fly.
* *
@ -386,7 +385,6 @@ class Model extends Object{
} }
return true; return true;
} }
/** /**
* Turn off associations on the fly. * Turn off associations on the fly.
* *
@ -404,7 +402,6 @@ class Model extends Object{
} }
return true; return true;
} }
/** /**
* Private helper method to create a set of associations. * Private helper method to create a set of associations.
* *
@ -458,16 +455,15 @@ class Model extends Object{
$colKey = Inflector::underscore($className); $colKey = Inflector::underscore($className);
if (ClassRegistry::isKeySet($colKey)) { if (ClassRegistry::isKeySet($colKey)) {
$this->{$className} = ClassRegistry::getObject($colKey); $this->{$className} =& ClassRegistry::getObject($colKey);
} else { } else {
$this->{$className} = new $className(); $this->{$className} =& new $className();
} }
$this->alias[$assoc] = $this->{$className}->table; $this->alias[$assoc] = $this->{$className}->table;
$this->tableToModel[$this->{$className}->table] = $className; $this->tableToModel[$this->{$className}->table] = $className;
$this->modelToTable[$className] = $this->{$className}->table; $this->modelToTable[$className] = $this->{$className}->table;
} }
/** /**
* Build array-based association from string. * Build array-based association from string.
* *
@ -524,7 +520,6 @@ class Model extends Object{
} }
} }
} }
/** /**
* Sets a custom table for your controller class. Used by your controller to select a database table. * Sets a custom table for your controller class. Used by your controller to select a database table.
* *
@ -558,7 +553,6 @@ class Model extends Object{
$this->loadInfo(); $this->loadInfo();
} }
} }
/** /**
* This function does two things: 1) it scans the array $one for the primary key, * This function does two things: 1) it scans the array $one for the primary key,
* and if that's found, it sets the current id to the value of $one[id]. * and if that's found, it sets the current id to the value of $one[id].
@ -602,7 +596,6 @@ class Model extends Object{
} }
return $data; return $data;
} }
/** /**
* Returns an array of table metadata (column names and types) from the database. * Returns an array of table metadata (column names and types) from the database.
* *
@ -616,7 +609,6 @@ class Model extends Object{
} }
return $this->_tableInfo; return $this->_tableInfo;
} }
/** /**
* Returns an associative array of field names and column types. * Returns an associative array of field names and column types.
* *
@ -633,7 +625,6 @@ class Model extends Object{
} }
return $cols; return $cols;
} }
/** /**
* Returns the column type of a column in the model * Returns the column type of a column in the model
* *
@ -653,7 +644,6 @@ class Model extends Object{
} }
return null; return null;
} }
/** /**
* Returns true if this Model has given field in its database table. * Returns true if this Model has given field in its database table.
* *
@ -670,7 +660,6 @@ class Model extends Object{
} }
return null; return null;
} }
/** /**
* Initializes the model for writing a new record. * Initializes the model for writing a new record.
* *
@ -682,7 +671,6 @@ class Model extends Object{
$this->data = array(); $this->data = array();
return true; return true;
} }
/** /**
* Deprecated * Deprecated
* *
@ -690,7 +678,6 @@ class Model extends Object{
function setId($id) { function setId($id) {
$this->id = $id; $this->id = $id;
} }
/** /**
* Deprecated. Use query() instead. * Deprecated. Use query() instead.
* *
@ -698,7 +685,6 @@ class Model extends Object{
function findBySql($sql) { function findBySql($sql) {
return $this->query($sql); return $this->query($sql);
} }
/** /**
* Returns a list of fields from the database * Returns a list of fields from the database
* *
@ -727,7 +713,6 @@ class Model extends Object{
return false; return false;
} }
} }
/** /**
* Returns contents of a field in a query matching given conditions. * Returns contents of a field in a query matching given conditions.
* *
@ -762,7 +747,6 @@ class Model extends Object{
return false; return false;
} }
} }
/** /**
* Saves a single field to the database. * Saves a single field to the database.
* *
@ -774,7 +758,6 @@ class Model extends Object{
function saveField($name, $value, $validate = false) { function saveField($name, $value, $validate = false) {
return $this->save(array($this->name => array($name => $value)), $validate); return $this->save(array($this->name => array($name => $value)), $validate);
} }
/** /**
* Saves model data to the database. * Saves model data to the database.
* By default, validation occurs before save. * By default, validation occurs before save.
@ -842,14 +825,12 @@ class Model extends Object{
$values[] = date('Y-m-d H:i:s'); $values[] = date('Y-m-d H:i:s');
} }
if ($this->hasField('modified') if ($this->hasField('modified') && !in_array('modified', $fields) && ($whitelist && in_array('modified', $fieldList) || !$whitelist)) {
&& !in_array('modified', $fields) && ($whitelist && in_array('modified', $fieldList) || !$whitelist)) {
$fields[] = 'modified'; $fields[] = 'modified';
$values[] = date('Y-m-d H:i:s'); $values[] = date('Y-m-d H:i:s');
} }
if ($this->hasField('updated') if ($this->hasField('updated') && !in_array('updated', $fields) && ($whitelist && in_array('updated', $fieldList) || !$whitelist)) {
&& !in_array('updated', $fields) && ($whitelist && in_array('updated', $fieldList) || !$whitelist)) {
$fields[] = 'updated'; $fields[] = 'updated';
$values[] = date('Y-m-d H:i:s'); $values[] = date('Y-m-d H:i:s');
} }
@ -900,7 +881,6 @@ class Model extends Object{
return false; return false;
} }
} }
/** /**
* Saves model hasAndBelongsToMany data to the database. * Saves model hasAndBelongsToMany data to the database.
* *
@ -943,18 +923,18 @@ class Model extends Object{
for($count = 0; $count < $total; $count++) { for($count = 0; $count < $total; $count++) {
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
$db->execute("DELETE FROM {$joinTable[$count]} WHERE {$mainKey[$count]} = '{$id}'"); $table = $db->name($db->fullTableName($joinTable[$count]));
$db->execute("DELETE FROM {$table} WHERE {$mainKey[$count]} = '{$id}'");
if (!empty($newValue[$count])) { if (!empty($newValue[$count])) {
$secondCount = count($newValue[$count]); $secondCount = count($newValue[$count]);
for($x = 0; $x < $secondCount; $x++) { for($x = 0; $x < $secondCount; $x++) {
$db->execute("INSERT INTO {$joinTable[$count]} ({$fields[$count]}) VALUES {$newValue[$count][$x]}"); $db->execute("INSERT INTO {$table} ({$fields[$count]}) VALUES {$newValue[$count][$x]}");
} }
} }
} }
} }
/** /**
* Synonym for del(). * Synonym for del().
* *
@ -962,10 +942,9 @@ class Model extends Object{
* @see function del * @see function del
* @return boolean True on success * @return boolean True on success
*/ */
function remove($id = null) { function remove($id = null, $cascade = true) {
return $this->del($id); return $this->del($id, $cascade);
} }
/** /**
* Removes record for given id. If no id is given, the current id is used. Returns true on success. * Removes record for given id. If no id is given, the current id is used. Returns true on success.
* *
@ -995,7 +974,6 @@ class Model extends Object{
return false; return false;
} }
/** /**
* Alias for del() * Alias for del()
* *
@ -1005,7 +983,6 @@ class Model extends Object{
function delete($id = null, $cascade = true) { function delete($id = null, $cascade = true) {
return $this->del($id, $cascade); return $this->del($id, $cascade);
} }
/** /**
* Cascades model deletes to hasMany relationships. * Cascades model deletes to hasMany relationships.
* *
@ -1027,7 +1004,6 @@ class Model extends Object{
} }
} }
} }
/** /**
* Cascades model deletes to hasOne relationships. * Cascades model deletes to hasOne relationships.
* *
@ -1049,7 +1025,6 @@ class Model extends Object{
} }
} }
} }
/** /**
* Cascades model deletes to HABTM join keys. * Cascades model deletes to HABTM join keys.
* *
@ -1059,13 +1034,10 @@ class Model extends Object{
*/ */
function _deleteMulti($id) { function _deleteMulti($id) {
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
foreach($this->hasAndBelongsToMany as $assoc => $data) { foreach($this->hasAndBelongsToMany as $assoc => $data) {
$db->execute("DELETE FROM " . $db->name($data['joinTable']) . " WHERE " $db->execute("DELETE FROM " . $db->name($db->fullTableName($data['joinTable'])) . " WHERE " . $db->name($data['foreignKey']) . " = '{$id}'");
. $db->name($data['foreignKey']) . " = '{$id}'");
} }
} }
/** /**
* Returns true if a record with set id exists. * Returns true if a record with set id exists.
* *
@ -1080,12 +1052,10 @@ class Model extends Object{
} }
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
return $db->hasAny($this, $db->conditions(array($this->primaryKey => $id))); return $db->hasAny($this, array($this->primaryKey => $id));
} }
return false; return false;
} }
/** /**
* Returns true if a record that meets given conditions exists * Returns true if a record that meets given conditions exists
* *
@ -1095,7 +1065,6 @@ class Model extends Object{
function hasAny($conditions = null) { function hasAny($conditions = null) {
return ($this->findCount($conditions) != false); return ($this->findCount($conditions) != false);
} }
/** /**
* Return a single row as a resultset array. * Return a single row as a resultset array.
* By using the $recursive parameter, the call can access further "levels of association" than * By using the $recursive parameter, the call can access further "levels of association" than
@ -1116,7 +1085,6 @@ class Model extends Object{
return $data[0]; return $data[0];
} }
/** /**
* Returns a resultset array with specified fields from database matching given conditions. * Returns a resultset array with specified fields from database matching given conditions.
* By using the $recursive parameter, the call can access further "levels of association" than * By using the $recursive parameter, the call can access further "levels of association" than
@ -1131,20 +1099,15 @@ class Model extends Object{
* @return array Array of records * @return array Array of records
*/ */
function findAll($conditions = null, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) { function findAll($conditions = null, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) {
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
$this->id = $this->getID(); $this->id = $this->getID();
$offset = 0; $offset = null;
if ($page > 1) { if ($page > 1 && $limit != null) {
$offset = ($page - 1) * $limit; $offset = ($page - 1) * $limit;
} }
$limit_str = '';
if ($limit) {
$limit_str = $db->limit($limit, $offset);
}
if ($order == null) { if ($order == null) {
$order = array(); $order = array();
} else { } else {
@ -1154,8 +1117,10 @@ class Model extends Object{
$queryData = array('conditions' => $conditions, $queryData = array('conditions' => $conditions,
'fields' => $fields, 'fields' => $fields,
'joins' => array(), 'joins' => array(),
'limit' => $limit_str, 'limit' => $limit,
'order' => $order); 'offset' => $offset,
'order' => $order
);
if (!$this->beforeFind($queryData)) { if (!$this->beforeFind($queryData)) {
return null; return null;
@ -1169,7 +1134,6 @@ class Model extends Object{
return $return; return $return;
} }
/** /**
* Method is called only when bindTo<ModelName>() is used. * Method is called only when bindTo<ModelName>() is used.
* This resets the association arrays for the model back * This resets the association arrays for the model back
@ -1188,7 +1152,6 @@ class Model extends Object{
unset ($this->__backAssociation); unset ($this->__backAssociation);
return true; return true;
} }
/** /**
* Runs a direct query against the bound DataSource, and returns the result. * Runs a direct query against the bound DataSource, and returns the result.
* *
@ -1213,7 +1176,6 @@ class Model extends Object{
return $data; return $data;
} }
/** /**
* Returns number of rows matching given SQL condition. * Returns number of rows matching given SQL condition.
* *
@ -1231,7 +1193,6 @@ class Model extends Object{
return false; return false;
} }
/** /**
* Special findAll variation for tables joined to themselves. * Special findAll variation for tables joined to themselves.
* The table needs the fields id and parent_id to work. * The table needs the fields id and parent_id to work.
@ -1245,7 +1206,6 @@ class Model extends Object{
function findAllThreaded($conditions = null, $fields = null, $sort = null) { function findAllThreaded($conditions = null, $fields = null, $sort = null) {
return $this->__doThread(Model::findAll($conditions, $fields, $sort), null); return $this->__doThread(Model::findAll($conditions, $fields, $sort), null);
} }
/** /**
* Private, recursive helper method for findAllThreaded. * Private, recursive helper method for findAllThreaded.
* *
@ -1260,8 +1220,7 @@ class Model extends Object{
$sizeOf = sizeof($data); $sizeOf = sizeof($data);
for($ii = 0; $ii < $sizeOf; $ii++) { for($ii = 0; $ii < $sizeOf; $ii++) {
if (($data[$ii][$this->name]['parent_id'] == $root) if (($data[$ii][$this->name]['parent_id'] == $root) || (($root === null) && ($data[$ii][$this->name]['parent_id'] == '0'))) {
|| (($root === null) && ($data[$ii][$this->name]['parent_id'] == '0'))) {
$tmp = $data[$ii]; $tmp = $data[$ii];
if (isset($data[$ii][$this->name][$this->primaryKey])) { if (isset($data[$ii][$this->name][$this->primaryKey])) {
@ -1276,7 +1235,6 @@ class Model extends Object{
return $out; return $out;
} }
/** /**
* Returns an array with keys "prev" and "next" that holds the id's of neighbouring data, * Returns an array with keys "prev" and "next" that holds the id's of neighbouring data,
* which is useful when creating paged lists. * which is useful when creating paged lists.
@ -1306,7 +1264,6 @@ class Model extends Object{
return array('prev' => $prev, 'next' => $next); return array('prev' => $prev, 'next' => $next);
} }
/** /**
* Returns a resultset for given SQL statement. Generic SQL queries should be made with this method. * Returns a resultset for given SQL statement. Generic SQL queries should be made with this method.
* *
@ -1318,22 +1275,16 @@ class Model extends Object{
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
return call_user_func_array(array(&$db, 'query'), $params); return call_user_func_array(array(&$db, 'query'), $params);
} }
/** /**
* Returns true if all fields pass validation, otherwise false. * Returns true if all fields pass validation, otherwise false.
* *
* @param array $data POST data * @param array $data POST data
* @return boolean True if there are no errors * @return boolean True if there are no errors
*/ */
function validates($data = null) { function validates($data = array()) {
if ($data == null) {
$data = $this->data;
}
$errors = $this->invalidFields($data); $errors = $this->invalidFields($data);
return count($errors) == 0; return count($errors) == 0;
} }
/** /**
* Returns an array of invalid fields. * Returns an array of invalid fields.
* *
@ -1341,6 +1292,10 @@ class Model extends Object{
* @return array Array of invalid fields * @return array Array of invalid fields
*/ */
function invalidFields($data = array()) { function invalidFields($data = array()) {
if (empty($data)) {
$data = $this->data;
}
if (!$this->beforeValidate()) { if (!$this->beforeValidate()) {
return false; return false;
} }
@ -1351,8 +1306,7 @@ class Model extends Object{
if (!empty($data)) { if (!empty($data)) {
$data = $data; $data = $data;
} } elseif (isset($this->data)) {
elseif (isset($this->data)){
$data = $this->data; $data = $this->data;
} }
@ -1367,7 +1321,6 @@ class Model extends Object{
} }
return $this->validationErrors; return $this->validationErrors;
} }
/** /**
* Sets a field as invalid * Sets a field as invalid
* *
@ -1378,10 +1331,8 @@ class Model extends Object{
if (!is_array($this->validationErrors)) { if (!is_array($this->validationErrors)) {
$this->validationErrors = array(); $this->validationErrors = array();
} }
$this->validationErrors[$field] = 1; $this->validationErrors[$field] = 1;
} }
/** /**
* Returns true if given field name is a foreign key in this Model. * Returns true if given field name is a foreign key in this Model.
* *
@ -1396,10 +1347,8 @@ class Model extends Object{
$foreignKeys[] = $data['foreignKey']; $foreignKeys[] = $data['foreignKey'];
} }
} }
return (bool)(in_array($field, $foreignKeys)); return (bool)(in_array($field, $foreignKeys));
} }
/** /**
* Gets the display field for this model * Gets the display field for this model
* *
@ -1408,7 +1357,6 @@ class Model extends Object{
function getDisplayField() { function getDisplayField() {
return $this->displayField; return $this->displayField;
} }
/** /**
* Returns a resultset array with specified fields from database matching given conditions. * Returns a resultset array with specified fields from database matching given conditions.
* Method can be used to generate option lists for SELECT elements. * Method can be used to generate option lists for SELECT elements.
@ -1423,10 +1371,10 @@ class Model extends Object{
function generateList($conditions = null, $order = null, $limit = null, $keyPath = null, $valuePath = null) { function generateList($conditions = null, $order = null, $limit = null, $keyPath = null, $valuePath = null) {
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
if ($keyPath == null && $valuePath == null) { if ($keyPath == null && $valuePath == null && $this->hasField($this->displayField)) {
$fields = array($this->primaryKey, $this->displayField); $fields = array($this->primaryKey, $this->displayField);
} else { } else {
$fields = '*'; $fields = null;
} }
$result = $this->findAll($conditions, $fields, $order, $limit, 1, 0); $result = $this->findAll($conditions, $fields, $order, $limit, 1, 0);
@ -1447,7 +1395,6 @@ class Model extends Object{
return $return; return $return;
} }
} }
/** /**
* Escapes the field name and prepends the model name. Escaping will be done according to the current database driver's rules. * Escapes the field name and prepends the model name. Escaping will be done according to the current database driver's rules.
* *
@ -1458,7 +1405,6 @@ class Model extends Object{
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
return $db->name($this->name) . '.' . $db->name($field); return $db->name($this->name) . '.' . $db->name($field);
} }
/** /**
* Returns the current record's ID * Returns the current record's ID
* *
@ -1484,7 +1430,6 @@ class Model extends Object{
return false; return false;
} }
/** /**
* Returns the ID of the last record this Model inserted * Returns the ID of the last record this Model inserted
* *
@ -1493,7 +1438,6 @@ class Model extends Object{
function getLastInsertID() { function getLastInsertID() {
return $this->getInsertID(); return $this->getInsertID();
} }
/** /**
* Returns the ID of the last record this Model inserted * Returns the ID of the last record this Model inserted
* *
@ -1502,7 +1446,6 @@ class Model extends Object{
function getInsertID() { function getInsertID() {
return $this->__insertID; return $this->__insertID;
} }
/** /**
* Returns the number of rows returned from the last query * Returns the number of rows returned from the last query
* *
@ -1513,7 +1456,6 @@ class Model extends Object{
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
return $db->lastNumRows(); return $db->lastNumRows();
} }
/** /**
* Returns the number of rows affected by the last query * Returns the number of rows affected by the last query
* *
@ -1524,7 +1466,6 @@ class Model extends Object{
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
return $db->lastAffected(); return $db->lastAffected();
} }
/** /**
* Sets the DataSource to which this model is bound * Sets the DataSource to which this model is bound
* *
@ -1546,7 +1487,6 @@ class Model extends Object{
return $this->cakeError('missingConnection', array(array('className' => $this->name))); return $this->cakeError('missingConnection', array(array('className' => $this->name)));
} }
} }
/** /**
* Before find callback * Before find callback
* *
@ -1556,7 +1496,6 @@ class Model extends Object{
function beforeFind(&$queryData) { function beforeFind(&$queryData) {
return true; return true;
} }
/** /**
* After find callback. Can be used to modify any results returned by find and findAll. * After find callback. Can be used to modify any results returned by find and findAll.
* *
@ -1566,7 +1505,6 @@ class Model extends Object{
function afterFind($results) { function afterFind($results) {
return $results; return $results;
} }
/** /**
* Before save callback * Before save callback
* *
@ -1575,7 +1513,6 @@ class Model extends Object{
function beforeSave() { function beforeSave() {
return true; return true;
} }
/** /**
* After save callback * After save callback
* *
@ -1584,7 +1521,6 @@ class Model extends Object{
function afterSave() { function afterSave() {
return true; return true;
} }
/** /**
* Before delete callback * Before delete callback
* *
@ -1593,7 +1529,6 @@ class Model extends Object{
function beforeDelete() { function beforeDelete() {
return true; return true;
} }
/** /**
* After delete callback * After delete callback
* *
@ -1602,7 +1537,6 @@ class Model extends Object{
function afterDelete() { function afterDelete() {
return true; return true;
} }
/** /**
* Before validate callback * Before validate callback
* *
@ -1611,7 +1545,6 @@ class Model extends Object{
function beforeValidate() { function beforeValidate() {
return true; return true;
} }
/** /**
* Private method. Clears cache for this model * Private method. Clears cache for this model
* *
@ -1640,7 +1573,6 @@ class Model extends Object{
//Will use for query cache deleting //Will use for query cache deleting
} }
} }
/** /**
* Called when serializing a model * Called when serializing a model
* *

View file

@ -341,7 +341,6 @@ class Model extends Object{
} }
} }
} }
/** /**
* Handles custom method calls, like findBy<field> for DB models, * Handles custom method calls, like findBy<field> for DB models,
* and custom RPC calls for remote data sources * and custom RPC calls for remote data sources
@ -355,7 +354,6 @@ class Model extends Object{
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
return $db->query($method, $params, $this); return $db->query($method, $params, $this);
} }
/** /**
* Bind model associations on the fly. * Bind model associations on the fly.
* *
@ -382,7 +380,6 @@ class Model extends Object{
} }
return true; return true;
} }
/** /**
* Turn off associations on the fly. * Turn off associations on the fly.
* *
@ -400,7 +397,6 @@ class Model extends Object{
} }
return true; return true;
} }
/** /**
* Private helper method to create a set of associations. * Private helper method to create a set of associations.
* *
@ -442,7 +438,6 @@ class Model extends Object{
$this->__generateAssociation($type); $this->__generateAssociation($type);
} }
} }
/** /**
* Private helper method to create associated models of given class. * Private helper method to create associated models of given class.
* @param string $assoc * @param string $assoc
@ -463,7 +458,6 @@ class Model extends Object{
$this->tableToModel[$this->{$className}->table] = $className; $this->tableToModel[$this->{$className}->table] = $className;
$this->modelToTable[$className] = $this->{$className}->table; $this->modelToTable[$className] = $this->{$className}->table;
} }
/** /**
* Build array-based association from string. * Build array-based association from string.
* *
@ -520,7 +514,6 @@ class Model extends Object{
} }
} }
} }
/** /**
* Sets a custom table for your controller class. Used by your controller to select a database table. * Sets a custom table for your controller class. Used by your controller to select a database table.
* *
@ -554,7 +547,6 @@ class Model extends Object{
$this->loadInfo(); $this->loadInfo();
} }
} }
/** /**
* This function does two things: 1) it scans the array $one for the primary key, * This function does two things: 1) it scans the array $one for the primary key,
* and if that's found, it sets the current id to the value of $one[id]. * and if that's found, it sets the current id to the value of $one[id].
@ -598,7 +590,6 @@ class Model extends Object{
} }
return $data; return $data;
} }
/** /**
* Returns an array of table metadata (column names and types) from the database. * Returns an array of table metadata (column names and types) from the database.
* *
@ -612,7 +603,6 @@ class Model extends Object{
} }
return $this->_tableInfo; return $this->_tableInfo;
} }
/** /**
* Returns an associative array of field names and column types. * Returns an associative array of field names and column types.
* *
@ -629,7 +619,6 @@ class Model extends Object{
} }
return $cols; return $cols;
} }
/** /**
* Returns the column type of a column in the model * Returns the column type of a column in the model
* *
@ -649,7 +638,6 @@ class Model extends Object{
} }
return null; return null;
} }
/** /**
* Returns true if this Model has given field in its database table. * Returns true if this Model has given field in its database table.
* *
@ -666,7 +654,6 @@ class Model extends Object{
} }
return null; return null;
} }
/** /**
* Initializes the model for writing a new record. * Initializes the model for writing a new record.
* *
@ -678,7 +665,6 @@ class Model extends Object{
$this->data = array(); $this->data = array();
return true; return true;
} }
/** /**
* Deprecated * Deprecated
* *
@ -686,7 +672,6 @@ class Model extends Object{
function setId($id) { function setId($id) {
$this->id = $id; $this->id = $id;
} }
/** /**
* Deprecated. Use query() instead. * Deprecated. Use query() instead.
* *
@ -694,7 +679,6 @@ class Model extends Object{
function findBySql($sql) { function findBySql($sql) {
return $this->query($sql); return $this->query($sql);
} }
/** /**
* Returns a list of fields from the database * Returns a list of fields from the database
* *
@ -838,14 +822,12 @@ class Model extends Object{
$values[] = date('Y-m-d H:i:s'); $values[] = date('Y-m-d H:i:s');
} }
if ($this->hasField('modified') if ($this->hasField('modified') && !in_array('modified', $fields) && ($whitelist && in_array('modified', $fieldList) || !$whitelist)) {
&& !in_array('modified', $fields) && ($whitelist && in_array('modified', $fieldList) || !$whitelist)) {
$fields[] = 'modified'; $fields[] = 'modified';
$values[] = date('Y-m-d H:i:s'); $values[] = date('Y-m-d H:i:s');
} }
if ($this->hasField('updated') if ($this->hasField('updated') && !in_array('updated', $fields) && ($whitelist && in_array('updated', $fieldList) || !$whitelist)) {
&& !in_array('updated', $fields) && ($whitelist && in_array('updated', $fieldList) || !$whitelist)) {
$fields[] = 'updated'; $fields[] = 'updated';
$values[] = date('Y-m-d H:i:s'); $values[] = date('Y-m-d H:i:s');
} }
@ -896,7 +878,6 @@ class Model extends Object{
return false; return false;
} }
} }
/** /**
* Saves model hasAndBelongsToMany data to the database. * Saves model hasAndBelongsToMany data to the database.
* *
@ -939,18 +920,18 @@ class Model extends Object{
for($count = 0; $count < $total; $count++) { for($count = 0; $count < $total; $count++) {
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
$db->execute("DELETE FROM {$joinTable[$count]} WHERE {$mainKey[$count]} = '{$id}'"); $table = $db->name($db->fullTableName($joinTable[$count]));
$db->execute("DELETE FROM {$table} WHERE {$mainKey[$count]} = '{$id}'");
if (!empty($newValue[$count])) { if (!empty($newValue[$count])) {
$secondCount = count($newValue[$count]); $secondCount = count($newValue[$count]);
for($x = 0; $x < $secondCount; $x++) { for($x = 0; $x < $secondCount; $x++) {
$db->execute("INSERT INTO {$joinTable[$count]} ({$fields[$count]}) VALUES {$newValue[$count][$x]}"); $db->execute("INSERT INTO {$table} ({$fields[$count]}) VALUES {$newValue[$count][$x]}");
} }
} }
} }
} }
/** /**
* Synonym for del(). * Synonym for del().
* *
@ -958,10 +939,9 @@ class Model extends Object{
* @see function del * @see function del
* @return boolean True on success * @return boolean True on success
*/ */
function remove($id = null) { function remove($id = null, $cascade = true) {
return $this->del($id); return $this->del($id, $cascade);
} }
/** /**
* Removes record for given id. If no id is given, the current id is used. Returns true on success. * Removes record for given id. If no id is given, the current id is used. Returns true on success.
* *
@ -991,7 +971,6 @@ class Model extends Object{
return false; return false;
} }
/** /**
* Alias for del() * Alias for del()
* *
@ -1001,7 +980,6 @@ class Model extends Object{
function delete($id = null, $cascade = true) { function delete($id = null, $cascade = true) {
return $this->del($id, $cascade); return $this->del($id, $cascade);
} }
/** /**
* Cascades model deletes to hasMany relationships. * Cascades model deletes to hasMany relationships.
* *
@ -1023,7 +1001,6 @@ class Model extends Object{
} }
} }
} }
/** /**
* Cascades model deletes to hasOne relationships. * Cascades model deletes to hasOne relationships.
* *
@ -1045,7 +1022,6 @@ class Model extends Object{
} }
} }
} }
/** /**
* Cascades model deletes to HABTM join keys. * Cascades model deletes to HABTM join keys.
* *
@ -1055,13 +1031,10 @@ class Model extends Object{
*/ */
function _deleteMulti($id) { function _deleteMulti($id) {
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
foreach($this->hasAndBelongsToMany as $assoc => $data) { foreach($this->hasAndBelongsToMany as $assoc => $data) {
$db->execute("DELETE FROM " . $db->name($data['joinTable']) . " WHERE " $db->execute("DELETE FROM " . $db->name($db->fullTableName($data['joinTable'])) . " WHERE " . $db->name($data['foreignKey']) . " = '{$id}'");
. $db->name($data['foreignKey']) . " = '{$id}'");
} }
} }
/** /**
* Returns true if a record with set id exists. * Returns true if a record with set id exists.
* *
@ -1076,12 +1049,10 @@ class Model extends Object{
} }
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
return $db->hasAny($this, $db->conditions(array($this->primaryKey => $id))); return $db->hasAny($this, array($this->primaryKey => $id));
} }
return false; return false;
} }
/** /**
* Returns true if a record that meets given conditions exists * Returns true if a record that meets given conditions exists
* *
@ -1091,7 +1062,6 @@ class Model extends Object{
function hasAny($conditions = null) { function hasAny($conditions = null) {
return ($this->findCount($conditions) != false); return ($this->findCount($conditions) != false);
} }
/** /**
* Return a single row as a resultset array. * Return a single row as a resultset array.
* By using the $recursive parameter, the call can access further "levels of association" than * By using the $recursive parameter, the call can access further "levels of association" than
@ -1112,7 +1082,6 @@ class Model extends Object{
return $data[0]; return $data[0];
} }
/** /**
* Returns a resultset array with specified fields from database matching given conditions. * Returns a resultset array with specified fields from database matching given conditions.
* By using the $recursive parameter, the call can access further "levels of association" than * By using the $recursive parameter, the call can access further "levels of association" than
@ -1127,20 +1096,15 @@ class Model extends Object{
* @return array Array of records * @return array Array of records
*/ */
function findAll($conditions = null, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) { function findAll($conditions = null, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) {
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
$this->id = $this->getID(); $this->id = $this->getID();
$offset = 0; $offset = null;
if ($page > 1) { if ($page > 1 && $limit != null) {
$offset = ($page - 1) * $limit; $offset = ($page - 1) * $limit;
} }
$limit_str = '';
if ($limit) {
$limit_str = $db->limit($limit, $offset);
}
if ($order == null) { if ($order == null) {
$order = array(); $order = array();
} else { } else {
@ -1150,8 +1114,10 @@ class Model extends Object{
$queryData = array('conditions' => $conditions, $queryData = array('conditions' => $conditions,
'fields' => $fields, 'fields' => $fields,
'joins' => array(), 'joins' => array(),
'limit' => $limit_str, 'limit' => $limit,
'order' => $order); 'offset' => $offset,
'order' => $order
);
if (!$this->beforeFind($queryData)) { if (!$this->beforeFind($queryData)) {
return null; return null;
@ -1165,7 +1131,6 @@ class Model extends Object{
return $return; return $return;
} }
/** /**
* Method is called only when bindTo<ModelName>() is used. * Method is called only when bindTo<ModelName>() is used.
* This resets the association arrays for the model back * This resets the association arrays for the model back
@ -1184,7 +1149,6 @@ class Model extends Object{
unset ($this->__backAssociation); unset ($this->__backAssociation);
return true; return true;
} }
/** /**
* Runs a direct query against the bound DataSource, and returns the result. * Runs a direct query against the bound DataSource, and returns the result.
* *
@ -1209,7 +1173,6 @@ class Model extends Object{
return $data; return $data;
} }
/** /**
* Returns number of rows matching given SQL condition. * Returns number of rows matching given SQL condition.
* *
@ -1227,7 +1190,6 @@ class Model extends Object{
return false; return false;
} }
/** /**
* Special findAll variation for tables joined to themselves. * Special findAll variation for tables joined to themselves.
* The table needs the fields id and parent_id to work. * The table needs the fields id and parent_id to work.
@ -1241,7 +1203,6 @@ class Model extends Object{
function findAllThreaded($conditions = null, $fields = null, $sort = null) { function findAllThreaded($conditions = null, $fields = null, $sort = null) {
return $this->__doThread(Model::findAll($conditions, $fields, $sort), null); return $this->__doThread(Model::findAll($conditions, $fields, $sort), null);
} }
/** /**
* Private, recursive helper method for findAllThreaded. * Private, recursive helper method for findAllThreaded.
* *
@ -1256,8 +1217,7 @@ class Model extends Object{
$sizeOf = sizeof($data); $sizeOf = sizeof($data);
for($ii = 0; $ii < $sizeOf; $ii++) { for($ii = 0; $ii < $sizeOf; $ii++) {
if (($data[$ii][$this->name]['parent_id'] == $root) if (($data[$ii][$this->name]['parent_id'] == $root) || (($root === null) && ($data[$ii][$this->name]['parent_id'] == '0'))) {
|| (($root === null) && ($data[$ii][$this->name]['parent_id'] == '0'))) {
$tmp = $data[$ii]; $tmp = $data[$ii];
if (isset($data[$ii][$this->name][$this->primaryKey])) { if (isset($data[$ii][$this->name][$this->primaryKey])) {
@ -1272,7 +1232,6 @@ class Model extends Object{
return $out; return $out;
} }
/** /**
* Returns an array with keys "prev" and "next" that holds the id's of neighbouring data, * Returns an array with keys "prev" and "next" that holds the id's of neighbouring data,
* which is useful when creating paged lists. * which is useful when creating paged lists.
@ -1302,7 +1261,6 @@ class Model extends Object{
return array('prev' => $prev, 'next' => $next); return array('prev' => $prev, 'next' => $next);
} }
/** /**
* Returns a resultset for given SQL statement. Generic SQL queries should be made with this method. * Returns a resultset for given SQL statement. Generic SQL queries should be made with this method.
* *
@ -1314,22 +1272,16 @@ class Model extends Object{
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
return call_user_func_array(array(&$db, 'query'), $params); return call_user_func_array(array(&$db, 'query'), $params);
} }
/** /**
* Returns true if all fields pass validation, otherwise false. * Returns true if all fields pass validation, otherwise false.
* *
* @param array $data POST data * @param array $data POST data
* @return boolean True if there are no errors * @return boolean True if there are no errors
*/ */
function validates($data = null) { function validates($data = array()) {
if ($data == null) {
$data = $this->data;
}
$errors = $this->invalidFields($data); $errors = $this->invalidFields($data);
return count($errors) == 0; return count($errors) == 0;
} }
/** /**
* Returns an array of invalid fields. * Returns an array of invalid fields.
* *
@ -1337,6 +1289,10 @@ class Model extends Object{
* @return array Array of invalid fields * @return array Array of invalid fields
*/ */
function invalidFields($data = array()) { function invalidFields($data = array()) {
if (empty($data)) {
$data = $this->data;
}
if (!$this->beforeValidate()) { if (!$this->beforeValidate()) {
return false; return false;
} }
@ -1347,8 +1303,7 @@ class Model extends Object{
if (!empty($data)) { if (!empty($data)) {
$data = $data; $data = $data;
} } elseif (isset($this->data)) {
elseif (isset($this->data)){
$data = $this->data; $data = $this->data;
} }
@ -1363,7 +1318,6 @@ class Model extends Object{
} }
return $this->validationErrors; return $this->validationErrors;
} }
/** /**
* Sets a field as invalid * Sets a field as invalid
* *
@ -1374,10 +1328,8 @@ class Model extends Object{
if (!is_array($this->validationErrors)) { if (!is_array($this->validationErrors)) {
$this->validationErrors = array(); $this->validationErrors = array();
} }
$this->validationErrors[$field] = 1; $this->validationErrors[$field] = 1;
} }
/** /**
* Returns true if given field name is a foreign key in this Model. * Returns true if given field name is a foreign key in this Model.
* *
@ -1392,10 +1344,8 @@ class Model extends Object{
$foreignKeys[] = $data['foreignKey']; $foreignKeys[] = $data['foreignKey'];
} }
} }
return (bool)(in_array($field, $foreignKeys)); return (bool)(in_array($field, $foreignKeys));
} }
/** /**
* Gets the display field for this model * Gets the display field for this model
* *
@ -1404,7 +1354,6 @@ class Model extends Object{
function getDisplayField() { function getDisplayField() {
return $this->displayField; return $this->displayField;
} }
/** /**
* Returns a resultset array with specified fields from database matching given conditions. * Returns a resultset array with specified fields from database matching given conditions.
* Method can be used to generate option lists for SELECT elements. * Method can be used to generate option lists for SELECT elements.
@ -1419,10 +1368,10 @@ class Model extends Object{
function generateList($conditions = null, $order = null, $limit = null, $keyPath = null, $valuePath = null) { function generateList($conditions = null, $order = null, $limit = null, $keyPath = null, $valuePath = null) {
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
if ($keyPath == null && $valuePath == null) { if ($keyPath == null && $valuePath == null && $this->hasField($this->displayField)) {
$fields = array($this->primaryKey, $this->displayField); $fields = array($this->primaryKey, $this->displayField);
} else { } else {
$fields = '*'; $fields = null;
} }
$result = $this->findAll($conditions, $fields, $order, $limit, 1, 0); $result = $this->findAll($conditions, $fields, $order, $limit, 1, 0);
@ -1443,7 +1392,6 @@ class Model extends Object{
return $return; return $return;
} }
} }
/** /**
* Escapes the field name and prepends the model name. Escaping will be done according to the current database driver's rules. * Escapes the field name and prepends the model name. Escaping will be done according to the current database driver's rules.
* *
@ -1454,7 +1402,6 @@ class Model extends Object{
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
return $db->name($this->name) . '.' . $db->name($field); return $db->name($this->name) . '.' . $db->name($field);
} }
/** /**
* Returns the current record's ID * Returns the current record's ID
* *
@ -1480,7 +1427,6 @@ class Model extends Object{
return false; return false;
} }
/** /**
* Returns the ID of the last record this Model inserted * Returns the ID of the last record this Model inserted
* *
@ -1489,7 +1435,6 @@ class Model extends Object{
function getLastInsertID() { function getLastInsertID() {
return $this->getInsertID(); return $this->getInsertID();
} }
/** /**
* Returns the ID of the last record this Model inserted * Returns the ID of the last record this Model inserted
* *
@ -1498,7 +1443,6 @@ class Model extends Object{
function getInsertID() { function getInsertID() {
return $this->__insertID; return $this->__insertID;
} }
/** /**
* Returns the number of rows returned from the last query * Returns the number of rows returned from the last query
* *
@ -1509,7 +1453,6 @@ class Model extends Object{
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
return $db->lastNumRows(); return $db->lastNumRows();
} }
/** /**
* Returns the number of rows affected by the last query * Returns the number of rows affected by the last query
* *
@ -1520,7 +1463,6 @@ class Model extends Object{
$db =& ConnectionManager::getDataSource($this->useDbConfig); $db =& ConnectionManager::getDataSource($this->useDbConfig);
return $db->lastAffected(); return $db->lastAffected();
} }
/** /**
* Sets the DataSource to which this model is bound * Sets the DataSource to which this model is bound
* *
@ -1542,7 +1484,6 @@ class Model extends Object{
return $this->cakeError('missingConnection', array(array('className' => $this->name))); return $this->cakeError('missingConnection', array(array('className' => $this->name)));
} }
} }
/** /**
* Before find callback * Before find callback
* *
@ -1552,7 +1493,6 @@ class Model extends Object{
function beforeFind(&$queryData) { function beforeFind(&$queryData) {
return true; return true;
} }
/** /**
* After find callback. Can be used to modify any results returned by find and findAll. * After find callback. Can be used to modify any results returned by find and findAll.
* *
@ -1562,7 +1502,6 @@ class Model extends Object{
function afterFind($results) { function afterFind($results) {
return $results; return $results;
} }
/** /**
* Before save callback * Before save callback
* *
@ -1571,7 +1510,6 @@ class Model extends Object{
function beforeSave() { function beforeSave() {
return true; return true;
} }
/** /**
* After save callback * After save callback
* *
@ -1580,7 +1518,6 @@ class Model extends Object{
function afterSave() { function afterSave() {
return true; return true;
} }
/** /**
* Before delete callback * Before delete callback
* *
@ -1589,7 +1526,6 @@ class Model extends Object{
function beforeDelete() { function beforeDelete() {
return true; return true;
} }
/** /**
* After delete callback * After delete callback
* *
@ -1598,7 +1534,6 @@ class Model extends Object{
function afterDelete() { function afterDelete() {
return true; return true;
} }
/** /**
* Before validate callback * Before validate callback
* *
@ -1607,7 +1542,6 @@ class Model extends Object{
function beforeValidate() { function beforeValidate() {
return true; return true;
} }
/** /**
* Private method. Clears cache for this model * Private method. Clears cache for this model
* *
@ -1636,7 +1570,6 @@ class Model extends Object{
//Will use for query cache deleting //Will use for query cache deleting
} }
} }
/** /**
* Called when serializing a model * Called when serializing a model
* *

View file

@ -84,6 +84,9 @@ class Object{
function requestAction($url, $extra = array()) { function requestAction($url, $extra = array()) {
if (!empty($url)) { if (!empty($url)) {
$dispatcher =& new Dispatcher(); $dispatcher =& new Dispatcher();
if(isset($this->plugin)){
$extra['plugin'] = $this->plugin;
}
if (in_array('return', $extra)) { if (in_array('return', $extra)) {
$extra['return'] = 0; $extra['return'] = 0;
$extra['bare'] = 1; $extra['bare'] = 1;

View file

@ -426,8 +426,8 @@ class CakeSession extends Object{
$table = $db->fullTableName(CAKE_SESSION_TABLE); $table = $db->fullTableName(CAKE_SESSION_TABLE);
$row = $db->query("SELECT " . $db->name($table.'.data') . " FROM " . $db->name($table) . " WHERE " . $db->name($table.'.id') . " = " . $db->value($key), false); $row = $db->query("SELECT " . $db->name($table.'.data') . " FROM " . $db->name($table) . " WHERE " . $db->name($table.'.id') . " = " . $db->value($key), false);
if ($row && $row[0][$table]['data']) { if ($row && $row[0][CAKE_SESSION_TABLE]['data']) {
return $row[0][$table]['data']; return $row[0][CAKE_SESSION_TABLE]['data'];
} else { } else {
return false; return false;
} }
@ -527,7 +527,7 @@ class CakeSession extends Object{
$factor = 10; $factor = 10;
break; break;
case 'medium': case 'medium':
$facto = 100; $factor = 100;
break; break;
case 'low': case 'low':
$factor = 300; $factor = 300;
@ -538,17 +538,17 @@ class CakeSession extends Object{
} }
$expires = time() + CAKE_SESSION_TIMEOUT * $factor; $expires = time() + CAKE_SESSION_TIMEOUT * $factor;
$row = $db->query("SELECT COUNT(id) AS count FROM " . $db->name($table) . " WHERE " $row = $db->query("SELECT COUNT(id) AS count FROM " . $db->name($table) . " WHERE "
. $db->name($table.'.id') . " = " . $db->name('id') . " = "
. $db->value($key), false); . $db->value($key), false);
if ($row[0][0]['count'] > 0) { if ($row[0][0]['count'] > 0) {
$db->execute("UPDATE " . $db->name($table) . " SET " . $db->name('data') . " = " $db->execute("UPDATE " . $db->name($table) . " SET " . $db->name('data') . " = "
. $db->value($value) . ", " . $db->name($table.'.expires') . " = " . $db->value($value) . ", " . $db->name('expires') . " = "
. $db->value($expires) . " WHERE " . $db->name($table.'.id') . " = " . $db->value($expires) . " WHERE " . $db->name('id') . " = "
. $db->value($key)); . $db->value($key));
} else { } else {
$db->execute("INSERT INTO " . $db->name($table) . " (" . $db->name('data') . "," $db->execute("INSERT INTO " . $db->name($table) . " (" . $db->name('data') . ","
. $db->name($table.'.expires') . "," . $db->name($table.'.id') . $db->name('expires') . "," . $db->name('id')
. ") VALUES (" . $db->value($value) . ", " . $db->value($expires) . ", " . ") VALUES (" . $db->value($value) . ", " . $db->value($expires) . ", "
. $db->value($key) . ")"); . $db->value($key) . ")");
} }

View file

@ -37,13 +37,6 @@
* @subpackage cake.cake.libs.view * @subpackage cake.cake.libs.view
*/ */
class Helper extends Object { class Helper extends Object {
/*************************************************************************
* Public variables
*************************************************************************/
/**#@+
* @access public
*/
/** /**
* Holds tag templates. * Holds tag templates.
@ -52,17 +45,6 @@ class Helper extends Object{
* @var array * @var array
*/ */
var $tags = array(); var $tags = array();
/**#@-*/
/*************************************************************************
* Public methods
*************************************************************************/
/**#@+
* @access public
*/
/** /**
* Parses tag templates into $this->tags. * Parses tag templates into $this->tags.
* *
@ -74,12 +56,10 @@ class Helper extends Object{
if (file_exists(APP . 'config' . DS . 'tags.ini.php')) { if (file_exists(APP . 'config' . DS . 'tags.ini.php')) {
$appConfig = $this->readConfigFile(APP . 'config' . DS . 'tags.ini.php'); $appConfig = $this->readConfigFile(APP . 'config' . DS . 'tags.ini.php');
$cakeConfig=array_merge($cakeConfig, $appConfig); $cakeConfig = am($cakeConfig, $appConfig);
} }
return $cakeConfig; return $cakeConfig;
} }
/** /**
* Decides whether to output or return a string. * Decides whether to output or return a string.
* *
@ -100,7 +80,6 @@ class Helper extends Object{
return $str; return $str;
} }
} }
/** /**
* Assigns values to tag templates. * Assigns values to tag templates.
* *
@ -161,7 +140,6 @@ class Helper extends Object{
*/ */
function afterRender() { function afterRender() {
} }
/**#@-*/
} }
?> ?>

View file

@ -654,8 +654,8 @@ class AjaxHelper extends Helper {
case 'requestHeaders': case 'requestHeaders':
$keys = array(); $keys = array();
foreach ($value as $key => $val) { foreach ($value as $key => $val) {
$keys[] = '"' . $key . '"'; $keys[] = "'" . $key . "'";
$keys[] = '"' . $val . '"'; $keys[] = "'" . $val . "'";
} }
$js_options['requestHeaders'] = '[' . join(', ', $keys) . ']'; $js_options['requestHeaders'] = '[' . join(', ', $keys) . ']';
break; break;
@ -762,13 +762,18 @@ class AjaxHelper extends Helper {
function afterRender() { function afterRender() {
if (env('HTTP_X_UPDATE') != null && count($this->__ajaxBuffer) > 0) { if (env('HTTP_X_UPDATE') != null && count($this->__ajaxBuffer) > 0) {
$data = array(); $data = array();
$divs = explode(' ', env('HTTP_X_UPDATE'));
foreach ($this->__ajaxBuffer as $key => $val) { foreach ($this->__ajaxBuffer as $key => $val) {
if (in_array($key, $divs)) {
$data[] = $key . ':"' . rawurlencode($val) . '"'; $data[] = $key . ':"' . rawurlencode($val) . '"';
} }
}
$out = 'var __ajaxUpdater__ = {' . join(', ', $data) . '};' . "\n"; $out = 'var __ajaxUpdater__ = {' . join(', ', $data) . '};' . "\n";
$out .= 'for (n in __ajaxUpdater__) { if (typeof __ajaxUpdater__[n] == "string" && $(n)) Element.update($(n), unescape(__ajaxUpdater__[n])); }'; $out .= 'for (n in __ajaxUpdater__) { if (typeof __ajaxUpdater__[n] == "string" && $(n)) Element.update($(n), unescape(__ajaxUpdater__[n])); }';
@ob_end_clean();
e($this->Javascript->codeBlock($out)); e($this->Javascript->codeBlock($out));
exit(); exit();
} }

View file

@ -1,6 +1,5 @@
<?php <?php
/* SVN FILE: $Id$ */ /* SVN FILE: $Id$ */
/** /**
* Automatic generation of HTML FORMs from given data. * Automatic generation of HTML FORMs from given data.
* *
@ -27,27 +26,22 @@
* @lastmodified $Date$ * @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
/** /**
* Tag template for a div with a class attribute. * Tag template for a div with a class attribute.
*/ */
define('TAG_DIV', '<div class="%s">%s</div>'); define('TAG_DIV', '<div class="%s">%s</div>');
/** /**
* Tag template for a paragraph with a class attribute. * Tag template for a paragraph with a class attribute.
*/ */
define('TAG_P_CLASS', '<p class="%s">%s</p>'); define('TAG_P_CLASS', '<p class="%s">%s</p>');
/** /**
* Tag template for a label with a for attribute. * Tag template for a label with a for attribute.
*/ */
define('TAG_LABEL', '<label for="%s">%s</label>'); define('TAG_LABEL', '<label for="%s">%s</label>');
/** /**
* Tag template for a fieldset with a legend tag inside. * Tag template for a fieldset with a legend tag inside.
*/ */
define('TAG_FIELDSET', '<fieldset><legend>%s</legend>%s</label>'); define('TAG_FIELDSET', '<fieldset><legend>%s</legend>%s</label>');
/** /**
* Form helper library. * Form helper library.
* *
@ -65,7 +59,6 @@ class FormHelper extends Helper{
*/ */
function FormHelper() { function FormHelper() {
} }
/** /**
* Returns a formatted error message for given FORM field, NULL if no errors. * Returns a formatted error message for given FORM field, NULL if no errors.
* *
@ -82,7 +75,6 @@ class FormHelper extends Helper{
return false; return false;
} }
} }
/** /**
* Returns a formatted LABEL element for HTML FORMs. * Returns a formatted LABEL element for HTML FORMs.
* *
@ -93,7 +85,6 @@ class FormHelper extends Helper{
function labelTag($tagName, $text) { function labelTag($tagName, $text) {
return sprintf(TAG_LABEL, strtolower(str_replace('/', '_', $tagName)), $text); return sprintf(TAG_LABEL, strtolower(str_replace('/', '_', $tagName)), $text);
} }
/** /**
* Returns a formatted DIV tag for HTML FORMs. * Returns a formatted DIV tag for HTML FORMs.
* *
@ -104,7 +95,6 @@ class FormHelper extends Helper{
function divTag($class, $text) { function divTag($class, $text) {
return sprintf(TAG_DIV, $class, $text); return sprintf(TAG_DIV, $class, $text);
} }
/** /**
* Returns a formatted P tag with class for HTML FORMs. * Returns a formatted P tag with class for HTML FORMs.
* *
@ -115,7 +105,6 @@ class FormHelper extends Helper{
function pTag($class, $text) { function pTag($class, $text) {
return sprintf(TAG_P_CLASS, $class, $text); return sprintf(TAG_P_CLASS, $class, $text);
} }
/** /**
* Returns a formatted INPUT tag for HTML FORMs. * Returns a formatted INPUT tag for HTML FORMs.
* *
@ -127,32 +116,25 @@ class FormHelper extends Helper{
* @param array $htmlOptions HTML options array. * @param array $htmlOptions HTML options array.
* @return string The formatted INPUT element, with a label and wrapped in a div. * @return string The formatted INPUT element, with a label and wrapped in a div.
*/ */
function generateInputDiv($tagName, $prompt, $required = false, $errorMsg = null, $size = 20, function generateInputDiv($tagName, $prompt, $required = false, $errorMsg = null, $size = 20, $htmlOptions = null) {
$htmlOptions = null) {
$htmlOptions['id'] = strtolower(str_replace('/', '_', $tagName)); $htmlOptions['id'] = strtolower(str_replace('/', '_', $tagName));
$htmlAttributes = $htmlOptions; $htmlAttributes = $htmlOptions;
$htmlAttributes['size'] = $size; $htmlAttributes['size'] = $size;
$str = $this->Html->input($tagName, $htmlAttributes); $str = $this->Html->input($tagName, $htmlAttributes);
$strLabel = $this->labelTag($tagName, $prompt); $strLabel = $this->labelTag($tagName, $prompt);
$divClass = "optional"; $divClass = "optional";
if ($required) { if ($required) {
$divClass = "required"; $divClass = "required";
} }
$strError = "";
$strError = ""; // initialize the error to empty.
if ($this->isFieldError($tagName)) { if ($this->isFieldError($tagName)) {
// if it was an error that occured, then add the error message, and append " error" to the div tag.
$strError = $this->pTag('error', $errorMsg); $strError = $this->pTag('error', $errorMsg);
$divClass = sprintf("%s error", $divClass); $divClass = sprintf("%s error", $divClass);
} }
$divTagInside = sprintf("%s %s %s", $strError, $strLabel, $str); $divTagInside = sprintf("%s %s %s", $strError, $strLabel, $str);
return $this->divTag($divClass, $divTagInside); return $this->divTag($divClass, $divTagInside);
} }
/** /**
* Returns a formatted CHECKBOX tag inside a DIV for HTML FORMs. * Returns a formatted CHECKBOX tag inside a DIV for HTML FORMs.
* *
@ -163,32 +145,24 @@ class FormHelper extends Helper{
* @param array $htmlOptions HTML options array. * @param array $htmlOptions HTML options array.
* @return string The formatted checkbox div * @return string The formatted checkbox div
*/ */
function generateCheckboxDiv($tagName, $prompt, $required = false, $errorMsg = null, $htmlOptions = null) function generateCheckboxDiv($tagName, $prompt, $required = false, $errorMsg = null, $htmlOptions = null) {
{
$htmlOptions['class'] = "inputCheckbox"; $htmlOptions['class'] = "inputCheckbox";
$htmlOptions['id'] = strtolower(str_replace('/', '_', $tagName)); $htmlOptions['id'] = strtolower(str_replace('/', '_', $tagName));
;
$str = $this->Html->checkbox($tagName, null, $htmlOptions); $str = $this->Html->checkbox($tagName, null, $htmlOptions);
$strLabel = $this->labelTag($tagName, $prompt); $strLabel = $this->labelTag($tagName, $prompt);
$divClass = "optional"; $divClass = "optional";
if ($required) {
if ($required)
$divClass = "required"; $divClass = "required";
}
$strError=""; // initialize the error to empty. $strError = "";
if ($this->isFieldError($tagName)) { if ($this->isFieldError($tagName)) {
// if it was an error that occured, then add the error message, and append " error" to the div tag.
$strError = $this->pTag('error', $errorMsg); $strError = $this->pTag('error', $errorMsg);
$divClass = sprintf("%s error", $divClass); $divClass = sprintf("%s error", $divClass);
} }
$divTagInside = sprintf("%s %s %s", $strError, $strLabel, $str); $divTagInside = sprintf("%s %s %s", $strError, $strLabel, $str);
return $this->divTag($divClass, $divTagInside); return $this->divTag($divClass, $divTagInside);
} }
/** /**
* Returns a formatted date option element for HTML FORMs. * Returns a formatted date option element for HTML FORMs.
* *
@ -201,34 +175,24 @@ class FormHelper extends Helper{
* @param array $htmlOptions HTML options array * @param array $htmlOptions HTML options array
* @return string Date option wrapped in a div. * @return string Date option wrapped in a div.
*/ */
function generateDate($tagName, $prompt, $required = false, $errorMsg = null, $size = 20, $htmlOptions = function generateDate($tagName, $prompt, $required = false, $errorMsg = null, $size = 20, $htmlOptions = null, $selected = null) {
null,
$selected = null) {
$htmlOptions['id']=strtolower(str_replace('/', '_', $tagName)); $htmlOptions['id']=strtolower(str_replace('/', '_', $tagName));
;
$str = $this->Html->dateTimeOptionTag($tagName, 'MDY', 'NONE', $selected, $htmlOptions); $str = $this->Html->dateTimeOptionTag($tagName, 'MDY', 'NONE', $selected, $htmlOptions);
$strLabel = $this->labelTag($tagName, $prompt); $strLabel = $this->labelTag($tagName, $prompt);
$divClass = "optional"; $divClass = "optional";
if ($required) {
if ($required)
$divClass = "required"; $divClass = "required";
}
$strError=""; // initialize the error to empty. $strError = "";
if ($this->isFieldError($tagName)) { if ($this->isFieldError($tagName)) {
// if it was an error that occured, then add the error message, and append " error" to the div tag.
$strError = $this->pTag('error', $errorMsg); $strError = $this->pTag('error', $errorMsg);
$divClass = sprintf("%s error", $divClass); $divClass = sprintf("%s error", $divClass);
} }
$divTagInside = sprintf("%s %s %s", $strError, $strLabel, $str); $divTagInside = sprintf("%s %s %s", $strError, $strLabel, $str);
$requiredDiv = $this->divTag($divClass, $divTagInside); $requiredDiv = $this->divTag($divClass, $divTagInside);
return $this->divTag("date", $requiredDiv); return $this->divTag("date", $requiredDiv);
} }
/** /**
* Returns a formatted datetime option element for HTML FORMs. * Returns a formatted datetime option element for HTML FORMs.
* *
@ -242,33 +206,24 @@ class FormHelper extends Helper{
* @param array $selected Selected index in the dateTimeOption tag. * @param array $selected Selected index in the dateTimeOption tag.
* @return string The formatted datetime option element wrapped in a div. * @return string The formatted datetime option element wrapped in a div.
*/ */
function generateDateTime($tagName, $prompt, $required = false, $errorMsg = null, $size = 20, function generateDateTime($tagName, $prompt, $required = false, $errorMsg = null, $size = 20, $htmlOptions = null, $selected = null) {
$htmlOptions = null, $selected = null) {
$htmlOptions['id']=strtolower(str_replace('/', '_', $tagName)); $htmlOptions['id']=strtolower(str_replace('/', '_', $tagName));
;
$str = $this->Html->dateTimeOptionTag($tagName, 'MDY', '12', $selected, $htmlOptions); $str = $this->Html->dateTimeOptionTag($tagName, 'MDY', '12', $selected, $htmlOptions);
$strLabel = $this->labelTag($tagName, $prompt); $strLabel = $this->labelTag($tagName, $prompt);
$divClass = "optional"; $divClass = "optional";
if ($required) {
if ($required)
$divClass = "required"; $divClass = "required";
}
$strError=""; // initialize the error to empty. $strError = "";
if ($this->isFieldError($tagName)) { if ($this->isFieldError($tagName)) {
// if it was an error that occured, then add the error message, and append " error" to the div tag.
$strError = $this->pTag('error', $errorMsg); $strError = $this->pTag('error', $errorMsg);
$divClass = sprintf("%s error", $divClass); $divClass = sprintf("%s error", $divClass);
} }
$divTagInside = sprintf("%s %s %s", $strError, $strLabel, $str); $divTagInside = sprintf("%s %s %s", $strError, $strLabel, $str);
$requiredDiv = $this->divTag($divClass, $divTagInside); $requiredDiv = $this->divTag($divClass, $divTagInside);
return $this->divTag("date", $requiredDiv); return $this->divTag("date", $requiredDiv);
} }
/** /**
* Returns a formatted TEXTAREA inside a DIV for use with HTML forms. * Returns a formatted TEXTAREA inside a DIV for use with HTML forms.
* *
@ -281,33 +236,27 @@ class FormHelper extends Helper{
* @param array $htmlOptions HTML options array. * @param array $htmlOptions HTML options array.
* @return string The formatted TEXTAREA element, wrapped in a div. * @return string The formatted TEXTAREA element, wrapped in a div.
*/ */
function generateAreaDiv($tagName, $prompt, $required = false, $errorMsg = null, $cols = 60, $rows = 10, function generateAreaDiv($tagName, $prompt, $required = false, $errorMsg = null, $cols = 60, $rows = 10, $htmlOptions = null) {
$htmlOptions = null) {
$htmlOptions['id'] = strtolower(str_replace('/', '_', $tagName)); $htmlOptions['id'] = strtolower(str_replace('/', '_', $tagName));
$htmlAttributes = $htmlOptions; $htmlAttributes = $htmlOptions;
$htmlAttributes['cols'] = $cols; $htmlAttributes['cols'] = $cols;
$htmlAttributes['rows'] = $rows; $htmlAttributes['rows'] = $rows;
$str = $this->Html->textarea($tagName, $htmlAttributes); $str = $this->Html->textarea($tagName, $htmlAttributes);
$strLabel = $this->labelTag($tagName, $prompt); $strLabel = $this->labelTag($tagName, $prompt);
$divClass = "optional"; $divClass = "optional";
if ($required) if ($required) {
$divClass="required"; $divClass="required";
}
$strError=""; // initialize the error to empty. $strError = "";
if ($this->isFieldError($tagName)) { if ($this->isFieldError($tagName)) {
// if it was an error that occured, then add the error message, and append " error" to the div tag.
$strError = $this->pTag('error', $errorMsg); $strError = $this->pTag('error', $errorMsg);
$divClass = sprintf("%s error", $divClass); $divClass = sprintf("%s error", $divClass);
} }
$divTagInside = sprintf("%s %s %s", $strError, $strLabel, $str); $divTagInside = sprintf("%s %s %s", $strError, $strLabel, $str);
return $this->divTag($divClass, $divTagInside); return $this->divTag($divClass, $divTagInside);
} }
/** /**
* Returns a formatted SELECT tag for HTML FORMs. * Returns a formatted SELECT tag for HTML FORMs.
* *
@ -321,31 +270,24 @@ class FormHelper extends Helper{
* @param string $errorMsg Text that will appear if an error has occurred * @param string $errorMsg Text that will appear if an error has occurred
* @return string The formatted INPUT element, wrapped in a div * @return string The formatted INPUT element, wrapped in a div
*/ */
function generateSelectDiv($tagName, $prompt, $options, $selected = null, $selectAttr = null, function generateSelectDiv($tagName, $prompt, $options, $selected = null, $selectAttr = null, $optionAttr = null, $required = false, $errorMsg = null) {
$optionAttr = null, $required = false, $errorMsg = null) {
$selectAttr['id'] = strtolower(str_replace('/', '_', $tagName)); $selectAttr['id'] = strtolower(str_replace('/', '_', $tagName));
$str = $this->Html->selectTag($tagName, $options, $selected, $selectAttr, $optionAttr); $str = $this->Html->selectTag($tagName, $options, $selected, $selectAttr, $optionAttr);
$strLabel = $this->labelTag($tagName, $prompt); $strLabel = $this->labelTag($tagName, $prompt);
$divClass = "optional"; $divClass = "optional";
if ($required) { if ($required) {
$divClass = "required"; $divClass = "required";
} }
$strError = "";
$strError=""; // initialize the error to empty.
if ($this->isFieldError($tagName)) { if ($this->isFieldError($tagName)) {
// if it was an error that occured, then add the error message, and append " error" to the div tag.
$strError=$this->pTag('error', $errorMsg); $strError=$this->pTag('error', $errorMsg);
$divClass=sprintf("%s error", $divClass); $divClass=sprintf("%s error", $divClass);
} }
$divTagInside = sprintf("%s %s %s", $strError, $strLabel, $str); $divTagInside = sprintf("%s %s %s", $strError, $strLabel, $str);
return $this->divTag($divClass, $divTagInside); return $this->divTag($divClass, $divTagInside);
} }
/** /**
* Returns a formatted submit widget for HTML FORMs. * Returns a formatted submit widget for HTML FORMs.
* *
@ -356,7 +298,6 @@ class FormHelper extends Helper{
function generateSubmitDiv($displayText, $htmlOptions = null) { function generateSubmitDiv($displayText, $htmlOptions = null) {
return $this->divTag('submit', $this->Html->submitTag($displayText, $htmlOptions)); return $this->divTag('submit', $this->Html->submitTag($displayText, $htmlOptions));
} }
/** /**
* Generates a form to go onto a HtmlHelper object. * Generates a form to go onto a HtmlHelper object.
* *
@ -369,6 +310,7 @@ class FormHelper extends Helper{
foreach($fields as $field) { foreach($fields as $field) {
if (isset($field['type'])) { if (isset($field['type'])) {
if (!isset($field['required'])) { if (!isset($field['required'])) {
$field['required'] = false; $field['required'] = false;
} }
@ -385,29 +327,18 @@ class FormHelper extends Helper{
$field['htmlOptions']['READONLY'] = "readonly"; $field['htmlOptions']['READONLY'] = "readonly";
} }
switch($field['type']) switch($field['type']) {
{
case "input": case "input":
if (!isset($field['size'])) { if (!isset($field['size'])) {
$field['size'] = 40; $field['size'] = 40;
} }
$strFormFields = $strFormFields . $this->generateInputDiv($field['tagName'], $field['prompt'],
$strFormFields= $field['required'], $field['errorMsg'], $field['size'], $field['htmlOptions']);
$strFormFields . $this->generateInputDiv($field['tagName'], $field['prompt'],
$field['required'],
$field['errorMsg'], $field['size'],
$field['htmlOptions']);
break; break;
case "checkbox": case "checkbox":
$strFormFields= $strFormFields = $strFormFields . $this->generateCheckboxDiv($field['tagName'], $field['prompt'],
$strFormFields . $this->generateCheckboxDiv($field['tagName'], $field['prompt'], $field['required'], $field['errorMsg'], $field['htmlOptions']);
$field['required'],
$field['errorMsg'],
$field['htmlOptions']);
break; break;
case "select": case "select":
case "selectMultiple": case "selectMultiple":
if ("selectMultiple" == $field['type']) { if ("selectMultiple" == $field['type']) {
@ -434,17 +365,9 @@ class FormHelper extends Helper{
if (!isset($field['options'])) { if (!isset($field['options'])) {
$field['options'] = null; $field['options'] = null;
} }
$strFormFields = $strFormFields . $this->generateSelectDiv($field['tagName'], $field['prompt'], $field['options'],
$strFormFields= $field['selected'], $field['selectAttr'], $field['optionsAttr'], $field['required'], $field['errorMsg']);
$strFormFields . $this->generateSelectDiv($field['tagName'], $field['prompt'],
$field['options'],
$field['selected'],
$field['selectAttr'],
$field['optionsAttr'],
$field['required'],
$field['errorMsg']);
break; break;
case "area": case "area":
if (!isset($field['rows'])) { if (!isset($field['rows'])) {
$field['rows'] = 10; $field['rows'] = 10;
@ -453,54 +376,39 @@ class FormHelper extends Helper{
if (!isset($field['cols'])) { if (!isset($field['cols'])) {
$field['cols'] = 60; $field['cols'] = 60;
} }
$strFormFields = $strFormFields . $this->generateAreaDiv($field['tagName'], $field['prompt'],
$strFormFields= $field['required'], $field['errorMsg'], $field['cols'], $field['rows'], $field['htmlOptions']);
$strFormFields . $this->generateAreaDiv($field['tagName'], $field['prompt'],
$field['required'],
$field['errorMsg'], $field['cols'],
$field['rows'],
$field['htmlOptions']);
break; break;
case "fieldset": case "fieldset":
$strFieldsetFields = $this->generateFields($field['fields']); $strFieldsetFields = $this->generateFields($field['fields']);
$strFieldSet = sprintf(' <fieldset><legend>%s</legend><div class="notes"><h4>%s</h4><p class="last">%s</p></div>%s</fieldset>',
$strFieldSet =sprintf(' $field['legend'], $field['noteHeading'], $field['note'], $strFieldsetFields);
<fieldset><legend>%s</legend><div class="notes"><h4>%s</h4><p class="last">%s</p></div>%s</fieldset>', $field['legend'], $field['noteHeading'], $field['note'],
$strFieldsetFields);
$strFormFields = $strFormFields . $strFieldSet; $strFormFields = $strFormFields . $strFieldSet;
break; break;
case "hidden": case "hidden":
$strFormFields=$strFormFields . $this->Html->hiddenTag($field['tagName']); if(!isset($field['value'])){
$field['value'] = null;
}
$strFormFields = $strFormFields . $this->Html->hiddenTag($field['tagName'], $field['value']);
break; break;
case "date": case "date":
if (!isset($field['selected'])) { if (!isset($field['selected'])) {
$field['selected'] = null; $field['selected'] = null;
} }
$strFormFields = $strFormFields . $this->generateDate($field['tagName'], $field['prompt'], null,
$strFormFields=
$strFormFields . $this->generateDate($field['tagName'], $field['prompt'], null,
null, null, null, $field['selected']); null, null, null, $field['selected']);
break; break;
case "datetime": case "datetime":
if (!isset($field['selected'])) { if (!isset($field['selected'])) {
$field['selected'] = null; $field['selected'] = null;
} }
$strFormFields = $strFormFields . $this->generateDateTime($field['tagName'], $field['prompt'], '', '', '', '', $field['selected']);
$strFormFields=$strFormFields break;
. $this->generateDateTime($field['tagName'], $field['prompt'], '', '', '', '', default:
$field['selected']);
break; break;
default: break;
} }
} }
} }
return $strFormFields; return $strFormFields;
} }
} }

View file

@ -129,18 +129,7 @@ class HtmlHelper extends Helper {
* @return mixed Either string or boolean value, depends on AUTO_OUTPUT and $return. * @return mixed Either string or boolean value, depends on AUTO_OUTPUT and $return.
*/ */
function url($url = null, $return = false) { function url($url = null, $return = false) {
$base = $this->base; $base = strip_plugin($this->base, $this->plugin);
if ($this->plugin != null) {
$base = preg_replace('/' . $this->plugin . '/', '', $this->base);
$base = str_replace('//', '', $base);
$pos1 = strrpos($base, '/');
$char = strlen($base) - 1;
if ($pos1 == $char) {
$base = substr($base, 0, $char);
}
}
if (empty($url)) { if (empty($url)) {
return $this->here; return $this->here;
} elseif($url{0} == '/') { } elseif($url{0} == '/') {
@ -148,7 +137,8 @@ class HtmlHelper extends Helper {
} else { } else {
$output = $base . '/' . strtolower($this->params['controller']) . '/' . $url; $output = $base . '/' . strtolower($this->params['controller']) . '/' . $url;
} }
return $this->output(preg_replace('/&([^a])/', '&amp;\1', $output), $return);
return $this->output($output, $return);
} }
/** /**
* Creates an HTML link. * Creates an HTML link.
@ -212,6 +202,9 @@ class HtmlHelper extends Helper {
if (!isset($htmlAttributes['value'])) { if (!isset($htmlAttributes['value'])) {
$htmlAttributes['value'] = $this->tagValue($fieldName); $htmlAttributes['value'] = $this->tagValue($fieldName);
} }
if (!isset($htmlAttributes['id'])) {
$htmlAttributes['id'] = $this->model . Inflector::camelize($this->field);
}
if ($this->tagIsInvalid($this->model, $this->field)) { if ($this->tagIsInvalid($this->model, $this->field)) {
if (isset($htmlAttributes['class']) && trim($htmlAttributes['class']) != "") { if (isset($htmlAttributes['class']) && trim($htmlAttributes['class']) != "") {
@ -237,6 +230,9 @@ class HtmlHelper extends Helper {
$value = $htmlAttributes['value']; $value = $htmlAttributes['value'];
unset($htmlAttributes['value']); unset($htmlAttributes['value']);
} }
if (!isset($htmlAttributes['id'])) {
$htmlAttributes['id'] = $this->model . Inflector::camelize($this->field);
}
if ($this->tagIsInvalid($this->model, $this->field)) { if ($this->tagIsInvalid($this->model, $this->field)) {
if (isset($htmlAttributes['class']) && trim($htmlAttributes['class']) != "") { if (isset($htmlAttributes['class']) && trim($htmlAttributes['class']) != "") {
@ -272,6 +268,9 @@ class HtmlHelper extends Helper {
$htmlAttributes['checked'] = $value ? 'checked' : null; $htmlAttributes['checked'] = $value ? 'checked' : null;
$htmlAttributes['value'] = 1; $htmlAttributes['value'] = 1;
} }
if (!isset($htmlAttributes['id'])) {
$htmlAttributes['id'] = $this->model . Inflector::camelize($this->field);
}
$output = $this->hidden($fieldName, array('value' => $notCheckedValue), true); $output = $this->hidden($fieldName, array('value' => $notCheckedValue), true);
$output .= sprintf($this->tags['checkbox'], $this->model, $this->field, $this->_parseAttributes($htmlAttributes, null, '', ' ')); $output .= sprintf($this->tags['checkbox'], $this->model, $this->field, $this->_parseAttributes($htmlAttributes, null, '', ' '));
return $this->output($output, $return); return $this->output($output, $return);
@ -287,8 +286,12 @@ class HtmlHelper extends Helper {
*/ */
function css($path, $rel = 'stylesheet', $htmlAttributes = null, $return = false) { function css($path, $rel = 'stylesheet', $htmlAttributes = null, $return = false) {
$url = "{$this->webroot}" . (COMPRESS_CSS ? 'c' : '') . CSS_URL . $this->themeWeb . $path . ".css"; $url = "{$this->webroot}" . (COMPRESS_CSS ? 'c' : '') . CSS_URL . $this->themeWeb . $path . ".css";
if ($rel == 'import') {
return $this->output(sprintf($this->tags['style'], $this->parseHtmlOptions($htmlAttributes, null, '', ' '), '@import url(' . $url . ');'), $return);
} else {
return $this->output(sprintf($this->tags['css'], $rel, $url, $this->parseHtmlOptions($htmlAttributes, null, '', ' ')), $return); return $this->output(sprintf($this->tags['css'], $rel, $url, $this->parseHtmlOptions($htmlAttributes, null, '', ' ')), $return);
} }
}
/** /**
* Creates file input widget. * Creates file input widget.
* *
@ -300,6 +303,9 @@ class HtmlHelper extends Helper {
function file($fieldName, $htmlAttributes = null, $return = false) { function file($fieldName, $htmlAttributes = null, $return = false) {
if (strpos($fieldName, '/')) { if (strpos($fieldName, '/')) {
$this->setFormTag($fieldName); $this->setFormTag($fieldName);
if (!isset($htmlAttributes['id'])) {
$htmlAttributes['id'] = $this->model . Inflector::camelize($this->field);
}
return $this->output(sprintf($this->tags['file'], $this->model, $this->field, $this->_parseAttributes($htmlAttributes, null, '', ' ')), $return); return $this->output(sprintf($this->tags['file'], $this->model, $this->field, $this->_parseAttributes($htmlAttributes, null, '', ' ')), $return);
} }
return $this->output(sprintf($this->tags['file_no_model'], $fieldName, $this->_parseAttributes($htmlAttributes, null, '', ' ')), $return); return $this->output(sprintf($this->tags['file_no_model'], $fieldName, $this->_parseAttributes($htmlAttributes, null, '', ' ')), $return);
@ -340,6 +346,9 @@ class HtmlHelper extends Helper {
if (!isset($htmlAttributes['value'])) { if (!isset($htmlAttributes['value'])) {
$htmlAttributes['value'] = $this->tagValue($fieldName); $htmlAttributes['value'] = $this->tagValue($fieldName);
} }
if (!isset($htmlAttributes['id'])) {
$htmlAttributes['id'] = $this->model . Inflector::camelize($this->field);
}
return $this->output(sprintf($this->tags['hidden'], $this->model, $this->field, $this->_parseAttributes($htmlAttributes, null, ' ', ' ')), $return); return $this->output(sprintf($this->tags['hidden'], $this->model, $this->field, $this->_parseAttributes($htmlAttributes, null, ' ', ' ')), $return);
} }
/** /**
@ -400,9 +409,11 @@ class HtmlHelper extends Helper {
* @return mixed Either string or boolean value, depends on AUTO_OUTPUT and $return. * @return mixed Either string or boolean value, depends on AUTO_OUTPUT and $return.
*/ */
function radio($fieldName, $options, $inbetween = null, $htmlAttributes = array(), $return = false) { function radio($fieldName, $options, $inbetween = null, $htmlAttributes = array(), $return = false) {
$this->setFormTag($fieldName); $this->setFormTag($fieldName);
$value = isset($htmlAttributes['value']) ? $htmlAttributes['value'] : $this->tagValue($fieldName); $value = isset($htmlAttributes['value']) ? $htmlAttributes['value'] : $this->tagValue($fieldName);
$out = array(); $out = array();
foreach($options as $optValue => $optTitle) { foreach($options as $optValue => $optTitle) {
$optionsHere = array('value' => $optValue); $optionsHere = array('value' => $optValue);
$optValue == $value ? $optionsHere['checked'] = 'checked' : null; $optValue == $value ? $optionsHere['checked'] = 'checked' : null;
@ -805,6 +816,9 @@ class HtmlHelper extends Helper {
$selectAttr['class'] = 'form_error'; $selectAttr['class'] = 'form_error';
} }
} }
if (!isset($selectAttr['id'])) {
$selectAttr['id'] = $this->model . Inflector::camelize($this->field);
}
if (!is_array($optionElements)) { if (!is_array($optionElements)) {
return null; return null;
@ -815,11 +829,9 @@ class HtmlHelper extends Helper {
} }
if (isset($selectAttr) && array_key_exists("multiple", $selectAttr)) { if (isset($selectAttr) && array_key_exists("multiple", $selectAttr)) {
$select[] = sprintf($this->tags['selectmultiplestart'], $this->model, $this->field, $select[] = sprintf($this->tags['selectmultiplestart'], $this->model, $this->field, $this->parseHtmlOptions($selectAttr));
$this->parseHtmlOptions($selectAttr));
} else { } else {
$select[] = sprintf($this->tags['selectstart'], $this->model, $this->field, $select[] = sprintf($this->tags['selectstart'], $this->model, $this->field, $this->parseHtmlOptions($selectAttr));
$this->parseHtmlOptions($selectAttr));
} }
if ($showEmpty == true) { if ($showEmpty == true) {
@ -835,12 +847,10 @@ class HtmlHelper extends Helper {
$optionsHere['selected'] = 'selected'; $optionsHere['selected'] = 'selected';
} }
$select[] $select[] = sprintf($this->tags['selectoption'], $name, $this->parseHtmlOptions($optionsHere), $title);
=sprintf($this->tags['selectoption'], $name, $this->parseHtmlOptions($optionsHere), $title);
} }
$select[] = sprintf($this->tags['selectend']); $select[] = sprintf($this->tags['selectend']);
return $this->output(implode("\n", $select), $return); return $this->output(implode("\n", $select), $return);
} }
/** /**
@ -856,8 +866,7 @@ class HtmlHelper extends Helper {
*/ */
function submitTag() { function submitTag() {
$args = func_get_args(); $args = func_get_args();
return call_user_func_array(array(&$this, return call_user_func_array(array(&$this, "submit"), $args);
"submit"), $args);
} }
/************************************************************************* /*************************************************************************
* Moved methods * Moved methods
@ -1101,6 +1110,9 @@ class HtmlHelper extends Helper {
$hourValue = !isset($selected) ? date('H') : $selected; $hourValue = !isset($selected) ? date('H') : $selected;
} else { } else {
$hourValue = !isset($selected) ? date('g') : $selected; $hourValue = !isset($selected) ? date('g') : $selected;
if (intval($hourValue) == 0) {
$hourValue = 12;
}
} }
if ($format24Hours) { if ($format24Hours) {
@ -1179,6 +1191,10 @@ class HtmlHelper extends Helper {
} }
$meridian = 'am'; $meridian = 'am';
$selected = trim($selected);
if (strpos($selected, ' ') === false) {
$selected = '0000-00-00 ' . $selected;
}
$date = explode('-', $selected); $date = explode('-', $selected);
$days = explode(' ', $date[2]); $days = explode(' ', $date[2]);

View file

@ -36,19 +36,27 @@
*/ */
class JavascriptHelper extends Helper{ class JavascriptHelper extends Helper{
var $_cachedEvents = array(); var $_cachedEvents = array();
var $_cacheEvents = false; var $_cacheEvents = false;
var $_cacheToFile = false;
var $_cacheAll = false;
var $_rules = array();
/** /**
* Returns a JavaScript script tag. * Returns a JavaScript script tag.
* *
* @param string $script The JavaScript to be wrapped in SCRIPT tags. * @param string $script The JavaScript to be wrapped in SCRIPT tags.
* @param boolean $allowCache Allows the script to be cached if non-event caching is active
* @return string The full SCRIPT element, with the JavaScript inside it. * @return string The full SCRIPT element, with the JavaScript inside it.
*/ */
function codeBlock($script) { function codeBlock($script, $allowCache = true) {
if ($this->_cacheEvents && $this->_cacheAll && $allowCache) {
$this->_cachedEvents[] = $script;
} else {
return sprintf($this->tags['javascriptblock'], $script); return sprintf($this->tags['javascriptblock'], $script);
} }
}
/** /**
* Returns a JavaScript include tag (SCRIPT element) * Returns a JavaScript include tag (SCRIPT element)
* *
@ -56,12 +64,11 @@ class JavascriptHelper extends Helper{
* @return string * @return string
*/ */
function link($url) { function link($url) {
if (strpos($url, ".") === false) if (strpos($url, ".") === false) {
$url .= ".js"; $url .= ".js";
}
return sprintf($this->tags['javascriptlink'], $this->webroot . JS_URL . $this->themeWeb . $url); return sprintf($this->tags['javascriptlink'], $this->webroot . JS_URL . $this->themeWeb . $url);
} }
/** /**
* Returns a JavaScript include tag for an externally-hosted script * Returns a JavaScript include tag for an externally-hosted script
* *
@ -69,12 +76,11 @@ class JavascriptHelper extends Helper{
* @return string * @return string
*/ */
function linkOut($url) { function linkOut($url) {
if (strpos($url, ".") === false) if (strpos($url, ".") === false) {
$url .= ".js"; $url .= ".js";
}
return sprintf($this->tags['javascriptlink'], $url); return sprintf($this->tags['javascriptlink'], $url);
} }
/** /**
* Escape carriage returns and single and double quotes for JavaScript segments. * Escape carriage returns and single and double quotes for JavaScript segments.
* *
@ -82,18 +88,10 @@ class JavascriptHelper extends Helper{
* @return string escaped string * @return string escaped string
*/ */
function escapeScript($script) { function escapeScript($script) {
$script=str_replace(array("\r\n", $script = r(array("\r\n", "\n", "\r"), '\n', $script);
"\n", $script = r(array('"', "'"), array('\"', "\\'"), $script);
"\r"), '\n',
$script);
$script=str_replace(array('"',
"'"), array('\"',
"\\'"), $script);
return $script; return $script;
} }
/** /**
* Escape a string to be JavaScript friendly. * Escape a string to be JavaScript friendly.
* *
@ -108,13 +106,8 @@ class JavascriptHelper extends Helper{
* @return string Escaped string. * @return string Escaped string.
*/ */
function escapeString($string) { function escapeString($string) {
$escape=array("\r\n" => '\n', $escape = array("\r\n" => '\n', "\r" => '\n', "\n" => '\n', '"' => '\"', "'" => "\\'");
"\r" => '\n', return r(array_keys($escape), array_values($escape), $string);
"\n" => '\n',
'"' => '\"',
"'" => "\\'");
return str_replace(array_keys($escape), array_values($escape), $string);
} }
/** /**
* Attach an event to an element. Used with the Prototype library. * Attach an event to an element. Used with the Prototype library.
@ -125,42 +118,93 @@ class JavascriptHelper extends Helper{
* @param boolean $useCapture default true * @param boolean $useCapture default true
* @return boolean true on success * @return boolean true on success
*/ */
function event($object, $event, $observer, $useCapture = false) { function event($object, $event, $observer = null, $useCapture = false) {
if ($useCapture == true) { if ($useCapture == true) {
$useCapture = "true"; $useCapture = "true";
} else { } else {
$useCapture = "false"; $useCapture = "false";
} }
if ($object == 'window' || strpos($object, '$(') !== false || strpos($object, '"') !== false || strpos($object, '\'') !== false) {
$b = "Event.observe($object, '$event', function(event){ $observer }, $useCapture);"; $b = "Event.observe($object, '$event', function(event){ $observer }, $useCapture);";
} else {
$chars = array('#', ' ', ', ', '.', ':');
$found = false;
foreach ($chars as $char) {
if (strpos($object, $char) !== false) {
$found = true;
break;
}
}
if ($found) {
$this->_rules[$object] = $event;
} else {
$b = "Event.observe(\$('$object'), '$event', function(event){ $observer }, $useCapture);";
}
}
if (isset($b) && !empty($b)) {
if ($this->_cacheEvents === true) { if ($this->_cacheEvents === true) {
$this->_cachedEvents[] = $b; $this->_cachedEvents[] = $b;
return true; return;
} else { } else {
return $this->codeBlock($b); return $this->codeBlock($b);
} }
} }
}
/** /**
* Cache JavaScript events created with event() * Cache JavaScript events created with event()
* *
* @param boolean $file If true, code will be written to a file
* @param boolean $all If true, all code written with JavascriptHelper will be sent to a file
* @return null * @return null
*/ */
function cacheEvents() { function cacheEvents($file = false, $all = false) {
$this->_cacheEvents = true; $this->_cacheEvents = true;
$this->_cacheToFile = $file;
$this->_cacheAll = $all;
} }
/** /**
* Write cached JavaScript events * Write cached JavaScript events
* *
* @return string A single code block of all cached JavaScript events created with event() * @return string
*/ */
function writeEvents() { function writeEvents() {
$this->_cacheEvents=false;
return $this->codeBlock("\n" . implode("\n", $this->_cachedEvents) . "\n"); $rules = array();
if (!empty($this->_rules)) {
foreach ($this->_rules as $sel => $event) {
$rules[] = "\t'{$sel}': function(element, event) {\n\t\t{$event}\n\t}";
}
$this->_cacheEvents = true;
} }
if ($this->_cacheEvents) {
$this->_cacheEvents = false;
$events = $this->_cachedEvents;
$data = implode("\n", $events);
$this->_cachedEvents = array();
if (!empty($rules)) {
$data .= "\n\nvar SelectorRules = {\n" . implode(",\n\n", $rules) . "\n}\n";
$data .= "\nEventSelectors.start(SelectorRules);\n";
}
if (!empty($events) || !empty($rules)) {
if ($this->_cacheToFile) {
$filename = md5($data);
if (!file_exists(JS . $filename . '.js')) {
cache(r(WWW_ROOT, '', JS) . $filename . '.js', $data, '+999 days', 'public');
}
return $this->link($filename);
} else {
return $this->codeBlock("\n" . $data . "\n");
}
}
}
}
/** /**
* Includes the Prototype Javascript library (and anything else) inside a single script tag. * Includes the Prototype Javascript library (and anything else) inside a single script tag.
* *
@ -183,10 +227,8 @@ class JavascriptHelper extends Helper{
} else { } else {
$javascript = file_get_contents(JS . "$script.js") . "\n\n"; $javascript = file_get_contents(JS . "$script.js") . "\n\n";
} }
return $this->codeBlock("\n\n" . $javascript); return $this->codeBlock("\n\n" . $javascript);
} }
/** /**
* Generates a JavaScript object in JavaScript Object Notation (JSON) * Generates a JavaScript object in JavaScript Object Notation (JSON)
* from an array * from an array
@ -200,8 +242,7 @@ class JavascriptHelper extends Helper{
* @param string $q The type of quote to use * @param string $q The type of quote to use
* @return string A JSON code block * @return string A JSON code block
*/ */
function object($data = array(), $block = false, $prefix = '', $postfix = '', $stringKeys = array(), function object($data = array(), $block = false, $prefix = '', $postfix = '', $stringKeys = array(), $quoteKeys = true, $q = "\"") {
$quoteKeys = true, $q = "\"") {
if (is_object($data)) { if (is_object($data)) {
$data = get_object_vars($data); $data = get_object_vars($data);
} }
@ -228,12 +269,9 @@ class JavascriptHelper extends Helper{
if (is_array($val) || is_object($val)) { if (is_array($val) || is_object($val)) {
$val = $this->object($val, false, '', '', $stringKeys, $quoteKeys, $q); $val = $this->object($val, false, '', '', $stringKeys, $quoteKeys, $q);
} else { } else {
if ((!count($stringKeys) && !is_numeric($val) && !is_bool($val)) if ((!count($stringKeys) && !is_numeric($val) && !is_bool($val)) || ($quoteKeys && in_array($key, $stringKeys)) || (!$quoteKeys && !in_array($key, $stringKeys))) {
|| ($quoteKeys && in_array($key, $stringKeys))
|| (!$quoteKeys && !in_array($key, $stringKeys))) {
$val = $q . $val . $q; $val = $q . $val . $q;
} }
if (trim($val) == '') { if (trim($val) == '') {
$val = 'null'; $val = 'null';
} }
@ -251,7 +289,6 @@ class JavascriptHelper extends Helper{
} else { } else {
$rt = '[' . join(', ', $out) . ']'; $rt = '[' . join(', ', $out) . ']';
} }
$rt = $prefix . $rt . $postfix; $rt = $prefix . $rt . $postfix;
if ($block) { if ($block) {
@ -260,5 +297,14 @@ class JavascriptHelper extends Helper{
return $rt; return $rt;
} }
/**
* AfterRender callback. Writes any cached events to the view, or to a temp file.
*
* @return null
*/
function afterRender() {
echo $this->writeEvents();
} }
}
?> ?>

View file

@ -29,7 +29,7 @@
<html xmlns="http://www.w3.org/1999/xhtml"> <html xmlns="http://www.w3.org/1999/xhtml">
<head> <head>
<title>CakePHP : The PHP Rapid Development Framework :: <?php echo $title_for_layout?></title> <title>CakePHP : The PHP Rapid Development Framework :: <?php echo $title_for_layout?></title>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="<?php echo $html->url('/favicon.ico');?>" type="image/x-icon" />
<?php echo $html->charset('UTF-8')?> <?php echo $html->charset('UTF-8')?>
<?php echo $html->css('cake.basic', 'stylesheet', array("media"=>"all" ));?> <?php echo $html->css('cake.basic', 'stylesheet', array("media"=>"all" ));?>
<?php echo $html->css('cake.forms', 'stylesheet', array("media"=>"all" ));?> <?php echo $html->css('cake.forms', 'stylesheet', array("media"=>"all" ));?>

View file

@ -35,9 +35,8 @@
<p style="background:#DBA941;padding:4px;font-size: 16px;">Cake<?php echo $connected->isConnected() ? ' is able to' : ' is not able to';?> connect to the database.</p> <p style="background:#DBA941;padding:4px;font-size: 16px;">Cake<?php echo $connected->isConnected() ? ' is able to' : ' is not able to';?> connect to the database.</p>
<br /> <br />
<?php endif; ?> <?php endif; ?>
<h1>CakePHP</h1> <h2>CakePHP release information is on CakeForge</h2>
<a href="http://cakeforge.org/projects/cakephp">Read the release notes and get the latest version</a>
<p>If you plan to upgrade from an older version, you may also want to read the <a href="http://cakephp.org/pages/changelog">changelog</a></p>
<h2>Editing this Page</h2> <h2>Editing this Page</h2>
<p> <p>

View file

@ -389,8 +389,7 @@ class View extends Object{
$layout_fn = $this->_getLayoutFileName(); $layout_fn = $this->_getLayoutFileName();
if (DEBUG > 2 && $this->controller != null) { if (DEBUG > 2 && $this->controller != null) {
$debug = View::_render(LIBS . 'view' . DS . 'templates' . DS . 'elements' . DS $debug = View::_render(LIBS . 'view' . DS . 'templates' . DS . 'elements' . DS . 'dump.thtml', array('controller' => $this->controller), false);
. 'dump.thtml', array('controller' => $this->controller), false);
} else { } else {
$debug = ''; $debug = '';
} }
@ -401,32 +400,44 @@ class View extends Object{
$pageTitle = Inflector::humanize($this->viewPath); $pageTitle = Inflector::humanize($this->viewPath);
} }
$data_for_layout=array_merge($this->_viewVars, array('title_for_layout' => $pageTitle, $data_for_layout = array_merge(
$this->_viewVars,
array(
'title_for_layout' => $pageTitle,
'content_for_layout' => $content_for_layout, 'content_for_layout' => $content_for_layout,
'cakeDebug' => $debug)); 'cakeDebug' => $debug
)
);
if (is_file($layout_fn)) { if (is_file($layout_fn)) {
if (empty($this->loaded) && !empty($this->helpers)) {
$loadHelpers = true;
} else {
$loadHelpers = false;
$data_for_layout = array_merge($data_for_layout, $this->loaded); $data_for_layout = array_merge($data_for_layout, $this->loaded);
}
if (substr($layout_fn, -5) === 'thtml') { if (substr($layout_fn, -5) === 'thtml') {
$out = View::_render($layout_fn, $data_for_layout, false, true); $out = View::_render($layout_fn, $data_for_layout, $loadHelpers, true);
} else { } else {
$out = $this->_render($layout_fn, $data_for_layout, false); $out = $this->_render($layout_fn, $data_for_layout, $loadHelpers);
} }
if ($out === false) { if ($out === false) {
$out = $this->_render($layout_fn, $data_for_layout); $out = $this->_render($layout_fn, $data_for_layout);
trigger_error( trigger_error(sprintf(__("Error in layout %s, got: <blockquote>%s</blockquote>"), $layout_fn, $out), E_USER_ERROR);
sprintf(__("Error in layout %s, got: <blockquote>%s</blockquote>"), $layout_fn, $out),
E_USER_ERROR);
return false; return false;
} else { } else {
return $out; return $out;
} }
} else { } else {
return $this->cakeError('missingLayout', array(array('layout' => $this->layout, return $this->cakeError('missingLayout', array(
array(
'layout' => $this->layout,
'file' => $layout_fn, 'file' => $layout_fn,
'base' => $this->base))); 'base' => $this->base
)
));
} }
} }
@ -492,10 +503,8 @@ class View extends Object{
} }
} }
if ($viewFileName = fileExistsInPath(LIBS . 'view' . DS . 'templates' . DS . 'errors' . DS . $type if ($viewFileName = fileExistsInPath(LIBS . 'view' . DS . 'templates' . DS . 'errors' . DS . $type . $action . '.thtml')) {
. $action . '.thtml')) { } elseif($viewFileName = fileExistsInPath(LIBS . 'view' . DS . 'templates' . DS . $this->viewPath . DS . $type . $action . '.thtml')) {
} elseif($viewFileName = fileExistsInPath(LIBS . 'view' . DS . 'templates' . DS . $this->viewPath . DS
. $type . $action . '.thtml')) {
} else { } else {
$viewFileName = VIEWS . $this->viewPath . DS . $this->subDir . $type . $action . $this->ext; $viewFileName = VIEWS . $this->viewPath . DS . $this->subDir . $type . $action . $this->ext;
} }
@ -517,19 +526,15 @@ class View extends Object{
} }
if (isset($this->plugin) && !is_null($this->plugin)) { if (isset($this->plugin) && !is_null($this->plugin)) {
if (file_exists( if (file_exists(APP . 'plugins' . DS . $this->plugin . DS . 'views' . DS . 'layouts' . DS . $this->layout . $this->ext)) {
APP . 'plugins' . DS . $this->plugin . DS . 'views' . DS . 'layouts' . DS . $this->layout . $this->ext)) { $layoutFileName = APP . 'plugins' . DS . $this->plugin . DS . 'views' . DS . 'layouts' . DS . $this->layout . $this->ext;
$layoutFileName=
APP . 'plugins' . DS . $this->plugin . DS . 'views' . DS . 'layouts' . DS . $this->layout . $this->ext;
return $layoutFileName; return $layoutFileName;
} }
} }
if (file_exists(LAYOUTS . $this->subDir . $type . "{$this->layout}$this->ext")) { if (file_exists(LAYOUTS . $this->subDir . $type . "{$this->layout}$this->ext")) {
$layoutFileName = LAYOUTS . $this->subDir . $type . "{$this->layout}$this->ext"; $layoutFileName = LAYOUTS . $this->subDir . $type . "{$this->layout}$this->ext";
} elseif($layoutFileName } elseif($layoutFileName = fileExistsInPath(LIBS . 'view' . DS . 'templates' . DS . "layouts" . DS . $type . "{$this->layout}.thtml")) {
= fileExistsInPath(LIBS . 'view' . DS . 'templates' . DS . "layouts" . DS . $type . "{$this->layout}.thtml"))
{
} else { } else {
$layoutFileName = LAYOUTS . $type . "{$this->layout}$this->ext"; $layoutFileName = LAYOUTS . $type . "{$this->layout}$this->ext";
} }
@ -548,14 +553,12 @@ class View extends Object{
*/ */
function _render($___viewFn, $___dataForView, $loadHelpers = true, $cached = false) { function _render($___viewFn, $___dataForView, $loadHelpers = true, $cached = false) {
if ($this->helpers != false && $loadHelpers === true) { if ($this->helpers != false && $loadHelpers === true) {
$helperVars = array();
$loadedHelpers = array(); $loadedHelpers = array();
$loadedHelpers = $this->_loadHelpers($loadedHelpers, $this->helpers); $loadedHelpers = $this->_loadHelpers($loadedHelpers, $this->helpers);
foreach(array_keys($loadedHelpers) as $helper) { foreach(array_keys($loadedHelpers) as $helper) {
$replace = strtolower(substr($helper, 0, 1)); $replace = strtolower(substr($helper, 0, 1));
$camelBackedHelper = preg_replace('/\\w/', $replace, $helper, 1); $camelBackedHelper = preg_replace('/\\w/', $replace, $helper, 1);
$helperVars[] = $camelBackedHelper;
${$camelBackedHelper} =& $loadedHelpers[$helper]; ${$camelBackedHelper} =& $loadedHelpers[$helper];
@ -582,8 +585,12 @@ class View extends Object{
} }
if ($this->helpers != false && $loadHelpers === true) { if ($this->helpers != false && $loadHelpers === true) {
foreach ($helperVars as $helper) { foreach ($loadedHelpers as $helper) {
${$helper}->afterRender(); if (is_object($helper)) {
if (is_subclass_of($helper, 'Helper') || is_subclass_of($helper, 'helper')) {
$helper->afterRender();
}
}
} }
} }
@ -628,18 +635,8 @@ class View extends Object{
if (in_array($helper, array_keys($loaded)) !== true) { if (in_array($helper, array_keys($loaded)) !== true) {
if (!class_exists($helperCn)) { if (!class_exists($helperCn)) {
$helperFn = Inflector::underscore($helper) . '.php'; if (is_null($this->plugin) || !loadPluginHelper($this->plugin, $helper)) {
if (!loadHelper($helper)) {
if (file_exists(APP . 'plugins' . DS . $this->plugin . DS . 'views' . DS . 'helpers' . DS . $helperFn)) {
$helperFn = APP . 'plugins' . DS . $this->plugin . DS . 'views' . DS . 'helpers' . DS . $helperFn;
} else if(file_exists(HELPERS . $helperFn)) {
$helperFn = HELPERS . $helperFn;
} else if($helperFn = fileExistsInPath(LIBS . 'view' . DS . 'helpers' . DS . $helperFn)) {
}
if (is_file($helperFn)) {
require $helperFn;
} else {
return $this->cakeError('missingHelperFile', array(array( return $this->cakeError('missingHelperFile', array(array(
'helper' => $helper, 'helper' => $helper,
'file' => Inflector::underscore($helper) . '.php', 'file' => Inflector::underscore($helper) . '.php',
@ -647,11 +644,18 @@ class View extends Object{
))); )));
} }
} }
if (!class_exists($helperCn)) {
return $this->cakeError('missingHelperClass', array(array(
'helper' => $helper,
'file' => Inflector::underscore($helper) . '.php',
'base' => $this->base
)));
}
}
$replace = strtolower(substr($helper, 0, 1)); $replace = strtolower(substr($helper, 0, 1));
$camelBackedHelper = preg_replace('/\\w/', $replace, $helper, 1); $camelBackedHelper = preg_replace('/\\w/', $replace, $helper, 1);
if (class_exists($helperCn)) {
${$camelBackedHelper} =& new $helperCn; ${$camelBackedHelper} =& new $helperCn;
${$camelBackedHelper}->view =& $this; ${$camelBackedHelper}->view =& $this;
${$camelBackedHelper}->base = $this->base; ${$camelBackedHelper}->base = $this->base;
@ -673,13 +677,6 @@ class View extends Object{
if (isset(${$camelBackedHelper}->helpers) && is_array(${$camelBackedHelper}->helpers)) { if (isset(${$camelBackedHelper}->helpers) && is_array(${$camelBackedHelper}->helpers)) {
$loaded = &$this->_loadHelpers($loaded, ${$camelBackedHelper}->helpers); $loaded = &$this->_loadHelpers($loaded, ${$camelBackedHelper}->helpers);
} }
} else {
return $this->cakeError('missingHelperClass', array(array(
'helper' => $helper,
'file' => Inflector::underscore($helper) . '.php',
'base' => $this->base
)));
}
} }
} }
return $loaded; return $loaded;

View file

@ -27,8 +27,12 @@
* @lastmodified $Date$ * @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
define ('DS', DIRECTORY_SEPARATOR);
if (function_exists('ini_set')) {
ini_set('display_errors', '1'); ini_set('display_errors', '1');
ini_set('error_reporting', '7'); ini_set('error_reporting', '7');
}
$app = 'app'; $app = 'app';
$root = dirname(dirname(dirname(__FILE__))); $root = dirname(dirname(dirname(__FILE__)));
$core = null; $core = null;
@ -61,7 +65,12 @@
break; break;
} }
} }
define ('DS', DIRECTORY_SEPARATOR);
if (strlen($app) && $app[0] == DS) {
$cnt = substr_count($root, DS);
$app = str_repeat('..' . DS, $cnt) . $app;
}
define ('ROOT', $root.DS); define ('ROOT', $root.DS);
define ('APP_DIR', $app); define ('APP_DIR', $app);
define ('APP_PATH', $app.DS); define ('APP_PATH', $app.DS);
@ -71,6 +80,9 @@
if(function_exists('ini_set')) { if(function_exists('ini_set')) {
ini_set('include_path',ini_get('include_path').PATH_SEPARATOR.CAKE_CORE_INCLUDE_PATH.PATH_SEPARATOR.ROOT.DS.APP_DIR.DS); ini_set('include_path',ini_get('include_path').PATH_SEPARATOR.CAKE_CORE_INCLUDE_PATH.PATH_SEPARATOR.ROOT.DS.APP_DIR.DS);
} else {
define('APP_PATH', ROOT . DS . APP_DIR . DS);
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
} }
require_once (ROOT.'cake'.DS.'basics.php'); require_once (ROOT.'cake'.DS.'basics.php');
@ -219,12 +231,16 @@ class Bake {
} }
} }
$password = ''; $password = '';
$blankPassword = false;
while ($password == '') { while ($password == '' && $blankPassword == false) {
$password = $this->getInput('What is the database password?'); $password = $this->getInput('What is the database password?');
if ($password == '') { if ($password == '') {
$this->stdout('The password you supplied was empty. Please try again.'); $blank = $this->getInput('The password you supplied was empty. Use an empty password?', array('y', 'n'), 'n');
if($blank == 'y')
{
$blankPassword = true;
}
} }
} }
$database = ''; $database = '';
@ -272,7 +288,18 @@ class Bake {
}*/ }*/
$modelName = ''; $modelName = '';
$db =& ConnectionManager::getDataSource($dbConnection); $db =& ConnectionManager::getDataSource($dbConnection);
$usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
if ($usePrefix) {
$tables = array();
foreach ($db->listSources() as $table) {
if (! strncmp($table, $usePrefix, strlen($usePrefix))) {
$tables[] = substr($table, strlen($usePrefix));
}
}
} else {
$tables = $db->listSources(); $tables = $db->listSources();
}
$inflect = new Inflector(); $inflect = new Inflector();
$this->stdout('Possible models based on your current database:'); $this->stdout('Possible models based on your current database:');
@ -391,7 +418,7 @@ class Bake {
$this->stdout('Done.'); $this->stdout('Done.');
$this->hr(); $this->hr();
//if none found... //if none found...
if(count($hasOneClasses) < 1 && count($hasManyClasses) < 1 && count($hasAndBelongsToManyClasses) < 1 && count($belongsToClasses)) { if(count($hasOneClasses) < 1 && count($hasManyClasses) < 1 && count($hasAndBelongsToManyClasses) < 1 && count($belongsToClasses) < 1) {
$this->stdout('None found.'); $this->stdout('None found.');
} else { } else {
$this->stdout('Please confirm the following associations:'); $this->stdout('Please confirm the following associations:');
@ -502,7 +529,7 @@ class Bake {
$looksGood = $this->getInput('Look okay?', array('y','n'), 'y'); $looksGood = $this->getInput('Look okay?', array('y','n'), 'y');
if (strtolower($looksGood) == 'y' || strtolower($looksGood) == 'yes') { if (strtolower($looksGood) == 'y' || strtolower($looksGood) == 'yes') {
if ($inflect->camelize($inflect->singularize($modelTableName)) == $modelClassName) { if ($modelTableName == $inflect->underscore($inflect->pluralize($modelClassName))) {
// set it to null... // set it to null...
// putting $useTable in the model // putting $useTable in the model
// is unnecessary. // is unnecessary.
@ -842,16 +869,13 @@ class Bake {
} }
$tempModel = new $controllerModel(); $tempModel = new $controllerModel();
$actions .= "\n"; $actions .= "\n";
$actions .= "\tfunction index()\n"; $actions .= "\tfunction index() {\n";
$actions .= "\t{\n";
$actions .= "\t\t\$this->{$controllerModel}->recursive = 0;\n"; $actions .= "\t\t\$this->{$controllerModel}->recursive = 0;\n";
$actions .= "\t\t\$this->set('{$this->lowCtrl}', \$this->{$controllerModel}->findAll());\n"; $actions .= "\t\t\$this->set('{$this->lowCtrl}', \$this->{$controllerModel}->findAll());\n";
$actions .= "\t}\n"; $actions .= "\t}\n";
$actions .= "\n"; $actions .= "\n";
$actions .= "\tfunction add()\n"; $actions .= "\tfunction add() {\n";
$actions .= "\t{\n"; $actions .= "\t\tif(empty(\$this->data)) {\n";
$actions .= "\t\tif(empty(\$this->data))\n";
$actions .= "\t\t{\n";
foreach($tempModel->hasAndBelongsToMany as $association => $relation) { foreach($tempModel->hasAndBelongsToMany as $association => $relation) {
if(!empty($relation['className'])) { if(!empty($relation['className'])) {
@ -869,26 +893,17 @@ class Bake {
} }
} }
$actions .= "\t\t\t\$this->set('{$this->lowCtrl}', null);\n"; $actions .= "\t\t\t\$this->set('{$this->lowCtrl}', null);\n";
$actions .= "\t\t}\n"; $actions .= "\t\t} else {\n";
$actions .= "\t\telse\n";
$actions .= "\t\t{\n";
$actions .= "\t\t\t\$this->cleanUpFields();\n"; $actions .= "\t\t\t\$this->cleanUpFields();\n";
$actions .= "\t\t\tif(\$this->{$controllerModel}->save(\$this->data))\n"; $actions .= "\t\t\tif(\$this->{$controllerModel}->save(\$this->data)) {\n";
$actions .= "\t\t\t{\n"; $actions .= "\t\t\t\tif(is_object(\$this->Session)) {\n";
$actions .= "\t\t\t\tif(is_object(\$this->Session))\n";
$actions .= "\t\t\t\t{\n";
$actions .= "\t\t\t\t\t\$this->Session->setFlash('The ".Inflector::humanize($controllerModel)." has been saved');\n"; $actions .= "\t\t\t\t\t\$this->Session->setFlash('The ".Inflector::humanize($controllerModel)." has been saved');\n";
$actions .= "\t\t\t\t\t\$this->redirect(\$this->viewPath.'/index');\n"; $actions .= "\t\t\t\t\t\$this->redirect(\$this->viewPath.'/index');\n";
$actions .= "\t\t\t\t}\n"; $actions .= "\t\t\t\t} else {\n";
$actions .= "\t\t\t\telse\n";
$actions .= "\t\t\t\t{\n";
$actions .= "\t\t\t\t\t\$this->flash('{$controllerModel} saved.', \$this->viewPath.'/index');\n"; $actions .= "\t\t\t\t\t\$this->flash('{$controllerModel} saved.', \$this->viewPath.'/index');\n";
$actions .= "\t\t\t\t}\n"; $actions .= "\t\t\t\t}\n";
$actions .= "\t\t\t}\n"; $actions .= "\t\t\t} else {\n";
$actions .= "\t\t\telse\n"; $actions .= "\t\t\t\tif(is_object(\$this->Session)) {\n";
$actions .= "\t\t\t{\n";
$actions .= "\t\t\t\tif(is_object(\$this->Session))\n";
$actions .= "\t\t\t\t{\n";
$actions .= "\t\t\t\t\t\$this->Session->setFlash('Please correct errors below.');\n"; $actions .= "\t\t\t\t\t\$this->Session->setFlash('Please correct errors below.');\n";
$actions .= "\t\t\t\t}\n"; $actions .= "\t\t\t\t}\n";
$actions .= "\t\t\t\t\$data = \$this->data;\n"; $actions .= "\t\t\t\t\$data = \$this->data;\n";
@ -901,10 +916,8 @@ class Bake {
$lowerName = strtolower($association); $lowerName = strtolower($association);
$actions .= "\t\t\t\t\${$lowerName} = null;\n"; $actions .= "\t\t\t\t\${$lowerName} = null;\n";
$actions .= "\t\t\t\t\$this->set('{$lowerName}Array', \$this->{$controllerModel}->{$model}->generateList());\n"; $actions .= "\t\t\t\t\$this->set('{$lowerName}Array', \$this->{$controllerModel}->{$model}->generateList());\n";
$actions .= "\t\t\t\tif(isset(\$data['{$model}']['{$model}']))\n"; $actions .= "\t\t\t\tif(isset(\$data['{$model}']['{$model}'])) {\n";
$actions .= "\t\t\t\t{\n"; $actions .= "\t\t\t\t\tforeach(\$data['{$model}']['{$model}'] as \$var) {\n";
$actions .= "\t\t\t\t\tforeach(\$data['{$model}']['{$model}'] as \$var)\n";
$actions .= "\t\t\t\t\t{\n";
$actions .= "\t\t\t\t\t\t\${$lowerName}[\$var] = \$var;\n"; $actions .= "\t\t\t\t\t\t\${$lowerName}[\$var] = \$var;\n";
$actions .= "\t\t\t\t\t}\n"; $actions .= "\t\t\t\t\t}\n";
$actions .= "\t\t\t\t}\n"; $actions .= "\t\t\t\t}\n";
@ -922,10 +935,8 @@ class Bake {
$actions .= "\t\t}\n"; $actions .= "\t\t}\n";
$actions .= "\t}\n"; $actions .= "\t}\n";
$actions .= "\n"; $actions .= "\n";
$actions .= "\tfunction edit(\$id)\n"; $actions .= "\tfunction edit(\$id) {\n";
$actions .= "\t{\n"; $actions .= "\t\tif(empty(\$this->data)) {\n";
$actions .= "\t\tif(empty(\$this->data))\n";
$actions .= "\t\t{\n";
$actions .= "\t\t\t\$data = \$this->{$controllerModel}->read(null, \$id);\n"; $actions .= "\t\t\t\$data = \$this->{$controllerModel}->read(null, \$id);\n";
$actions .= "\t\t\t\$this->set('{$this->lowCtrl}', \$data );\n"; $actions .= "\t\t\t\$this->set('{$this->lowCtrl}', \$data );\n";
@ -936,8 +947,7 @@ class Bake {
$lowerName = strtolower($association); $lowerName = strtolower($association);
$actions .= "\t\t\t\${$lowerName} = null;\n"; $actions .= "\t\t\t\${$lowerName} = null;\n";
$actions .= "\t\t\t\$this->set('{$lowerName}Array', \$this->{$controllerModel}->{$model}->generateList());\n"; $actions .= "\t\t\t\$this->set('{$lowerName}Array', \$this->{$controllerModel}->{$model}->generateList());\n";
$actions .= "\t\t\tforeach(\$data['{$model}'] as \$var)\n"; $actions .= "\t\t\tforeach(\$data['{$model}'] as \$var) {\n";
$actions .= "\t\t\t{\n";
$actions .= "\t\t\t\t\${$lowerName}[\$var['{$associationModel->primaryKey}']] = \$var['{$associationModel->primaryKey}'];\n"; $actions .= "\t\t\t\t\${$lowerName}[\$var['{$associationModel->primaryKey}']] = \$var['{$associationModel->primaryKey}'];\n";
$actions .= "\t\t\t}\n"; $actions .= "\t\t\t}\n";
$actions .= "\t\t\t\$this->set('selected{$model}', \${$lowerName});\n"; $actions .= "\t\t\t\$this->set('selected{$model}', \${$lowerName});\n";
@ -950,26 +960,17 @@ class Bake {
$actions .= "\t\t\t\$this->set('{$lowerName}Array', \$this->{$controllerModel}->{$model}->generateList());\n"; $actions .= "\t\t\t\$this->set('{$lowerName}Array', \$this->{$controllerModel}->{$model}->generateList());\n";
} }
} }
$actions .= "\t\t}\n"; $actions .= "\t\t} else {\n";
$actions .= "\t\telse\n";
$actions .= "\t\t{\n";
$actions .= "\t\t\t\$this->cleanUpFields();\n"; $actions .= "\t\t\t\$this->cleanUpFields();\n";
$actions .= "\t\t\tif(\$this->{$controllerModel}->save(\$this->data))\n"; $actions .= "\t\t\tif(\$this->{$controllerModel}->save(\$this->data)) {\n";
$actions .= "\t\t\t{\n"; $actions .= "\t\t\t\tif(is_object(\$this->Session)) {\n";
$actions .= "\t\t\t\tif(is_object(\$this->Session))\n";
$actions .= "\t\t\t\t{\n";
$actions .= "\t\t\t\t\t\$this->Session->setFlash('The ".Inflector::humanize($controllerModel)." has been saved');\n"; $actions .= "\t\t\t\t\t\$this->Session->setFlash('The ".Inflector::humanize($controllerModel)." has been saved');\n";
$actions .= "\t\t\t\t\t\$this->redirect(\$this->viewPath.'/index');\n"; $actions .= "\t\t\t\t\t\$this->redirect(\$this->viewPath.'/index');\n";
$actions .= "\t\t\t\t}\n"; $actions .= "\t\t\t\t} else {\n";
$actions .= "\t\t\t\telse\n";
$actions .= "\t\t\t\t{\n";
$actions .= "\t\t\t\t\t\$this->flash('{$controllerModel} saved.', \$this->viewPath.'/index');\n"; $actions .= "\t\t\t\t\t\$this->flash('{$controllerModel} saved.', \$this->viewPath.'/index');\n";
$actions .= "\t\t\t\t}\n"; $actions .= "\t\t\t\t}\n";
$actions .= "\t\t\t}\n"; $actions .= "\t\t\t} else {\n";
$actions .= "\t\t\telse\n"; $actions .= "\t\t\t\tif(is_object(\$this->Session)) {\n";
$actions .= "\t\t\t{\n";
$actions .= "\t\t\t\tif(is_object(\$this->Session))\n";
$actions .= "\t\t\t\t{\n";
$actions .= "\t\t\t\t\t\$this->Session->setFlash('Please correct errors below.');\n"; $actions .= "\t\t\t\t\t\$this->Session->setFlash('Please correct errors below.');\n";
$actions .= "\t\t\t\t}\n"; $actions .= "\t\t\t\t}\n";
$actions .= "\t\t\t\t\$data = \$this->data;\n"; $actions .= "\t\t\t\t\$data = \$this->data;\n";
@ -982,10 +983,8 @@ class Bake {
$lowerName = strtolower($association); $lowerName = strtolower($association);
$actions .= "\t\t\t\t\${$lowerName} = null;\n"; $actions .= "\t\t\t\t\${$lowerName} = null;\n";
$actions .= "\t\t\t\t\$this->set('{$lowerName}Array', \$this->{$controllerModel}->{$model}->generateList());\n"; $actions .= "\t\t\t\t\$this->set('{$lowerName}Array', \$this->{$controllerModel}->{$model}->generateList());\n";
$actions .= "\t\t\t\tif(isset(\$data['{$model}']['{$model}']))\n"; $actions .= "\t\t\t\tif(isset(\$data['{$model}']['{$model}'])) {\n";
$actions .= "\t\t\t\t{\n"; $actions .= "\t\t\t\t\tforeach(\$data['{$model}']['{$model}'] as \$var) {\n";
$actions .= "\t\t\t\t\tforeach(\$data['{$model}']['{$model}'] as \$var)\n";
$actions .= "\t\t\t\t\t{\n";
$actions .= "\t\t\t\t\t\t\${$lowerName}[\$var] = \$var;\n"; $actions .= "\t\t\t\t\t\t\${$lowerName}[\$var] = \$var;\n";
$actions .= "\t\t\t\t\t}\n"; $actions .= "\t\t\t\t\t}\n";
$actions .= "\t\t\t\t}\n"; $actions .= "\t\t\t\t}\n";
@ -1003,13 +1002,11 @@ class Bake {
$actions .= "\t\t}\n"; $actions .= "\t\t}\n";
$actions .= "\t}\n"; $actions .= "\t}\n";
$actions .= "\n"; $actions .= "\n";
$actions .= "\tfunction view(\$id)\n"; $actions .= "\tfunction view(\$id) {\n";
$actions .= "\t{\n";
$actions .= "\t\t\$this->set('{$this->lowCtrl}', \$this->{$controllerModel}->read(null, \$id));\n"; $actions .= "\t\t\$this->set('{$this->lowCtrl}', \$this->{$controllerModel}->read(null, \$id));\n";
$actions .= "\t}\n"; $actions .= "\t}\n";
$actions .= "\n"; $actions .= "\n";
$actions .= "\tfunction delete(\$id)\n"; $actions .= "\tfunction delete(\$id) {\n";
$actions .= "\t{\n";
$actions .= "\t\t\$this->{$controllerModel}->del(\$id);\n"; $actions .= "\t\t\$this->{$controllerModel}->del(\$id);\n";
$actions .= "\t\t\$this->redirect('/{$this->lowCtrl}/index');\n"; $actions .= "\t\t\$this->redirect('/{$this->lowCtrl}/index');\n";
$actions .= "\t}\n"; $actions .= "\t}\n";
@ -1890,7 +1887,6 @@ class Bake {
$this->stdout(' -core [path...] Absolute path to Cake\'s cake Folder.'); $this->stdout(' -core [path...] Absolute path to Cake\'s cake Folder.');
$this->stdout(' -help Shows this help message.'); $this->stdout(' -help Shows this help message.');
$this->stdout(' -project [path...] Generates a new app folder in the path supplied.'); $this->stdout(' -project [path...] Generates a new app folder in the path supplied.');
$this->stdout(' Must be used with the -app command.');
$this->stdout(' -root [path...] Absolute path to Cake\'s \app\webroot Folder.'); $this->stdout(' -root [path...] Absolute path to Cake\'s \app\webroot Folder.');
$this->stdout(''); $this->stdout('');
} }
@ -1924,13 +1920,6 @@ class Bake {
$parentPath = explode(DS, $projectPath); $parentPath = explode(DS, $projectPath);
$count = count($parentPath); $count = count($parentPath);
$appName = $parentPath[$count - 1]; $appName = $parentPath[$count - 1];
unset($parentPath[$count - 1]);
$parentPath = implode(DS, $parentPath);
if(!is_writable($parentPath)) {
$projectPath = $this->getInput('The directory path is not writable. Please try again');
$this->project($projectPath);
}
$this->__buildDirLayout($projectPath, $appName); $this->__buildDirLayout($projectPath, $appName);
exit(); exit();
} }
@ -2019,7 +2008,9 @@ class Bake {
$messages=array(); $messages=array();
if (!is_dir($toDir)) { if (!is_dir($toDir)) {
mkdir($toDir, 0755); uses('folder');
$folder = new Folder();
$folder->mkdirr($toDir, 0755);
} }
if (!is_writable($toDir)) { if (!is_writable($toDir)) {
@ -2082,7 +2073,8 @@ class Bake {
* Enter description here... * Enter description here...
* *
*/ */
function welcome() { function welcome()
{
$this->stdout(''); $this->stdout('');
$this->stdout(' ___ __ _ _ ___ __ _ _ __ __ __ _ _ ___ '); $this->stdout(' ___ __ _ _ ___ __ _ _ __ __ __ _ _ ___ ');
$this->stdout('| |__| |_/ |__ |__] |__| |__] |__] |__| |_/ |__ '); $this->stdout('| |__| |_/ |__ |__] |__| |__] |__] |__| |_/ |__ ');

View file

@ -76,6 +76,13 @@
* *
*/ */
define('CAKE_SESSION_SAVE', 'php'); define('CAKE_SESSION_SAVE', 'php');
/**
* If using you own table name for storing sessions
* set the table name here.
* DO NOT INCLUDE PREFIX IF YOU HAVE SET ONE IN database.php
*
*/
define('CAKE_SESSION_TABLE', 'cake_sessions');
/** /**
* Set a random string of used in session. * Set a random string of used in session.
* *

View file

@ -2,7 +2,7 @@
<html xmlns="http://www.w3.org/1999/xhtml"> <html xmlns="http://www.w3.org/1999/xhtml">
<head> <head>
<title>CakePHP : <?php echo $title_for_layout;?></title> <title>CakePHP : <?php echo $title_for_layout;?></title>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="<?php echo $html->url('/favicon.ico')?>" type="image/x-icon" />
<?php echo $html->css('generic.basic');?> <?php echo $html->css('generic.basic');?>
<?php echo $html->css('generic.forms');?> <?php echo $html->css('generic.forms');?>
</head> </head>

View file

@ -68,6 +68,7 @@
if (preg_match('|\.\.|', $url) || !preg_match('|^ccss/(.+)$|i', $url, $regs)) { if (preg_match('|\.\.|', $url) || !preg_match('|^ccss/(.+)$|i', $url, $regs)) {
die('Wrong file name.'); die('Wrong file name.');
} }
$filename = 'css/' . $regs[1]; $filename = 'css/' . $regs[1];
$filepath = CSS . $regs[1]; $filepath = CSS . $regs[1];
$cachepath = CACHE . 'css' . DS . str_replace(array('/','\\'), '-', $regs[1]); $cachepath = CACHE . 'css' . DS . str_replace(array('/','\\'), '-', $regs[1]);

View file

@ -8,7 +8,7 @@ font-family:verdana,helvetica,arial,sans-serif;
font-size:12px; font-size:12px;
text-align:center; text-align:center;
color:#333; color:#333;
background:#fff; background:#003d4c;
line-height: 18px; line-height: 18px;
} }
@ -18,11 +18,11 @@ line-height: 18px;
a{ a{
color:#003d4c; color:#003d4c;
text-decoration:none; text-decoration:underline;
} }
a:hover{ a:hover{
color:#003d4c; color:#003d4c;
text-decoration:underline; text-decoration:none;
} }
a img{ a img{
@ -90,6 +90,8 @@ font-weight:normal;
#content{ #content{
padding: 10px 40px; padding: 10px 40px;
background-color: #fff;
color: #333;
} }
#footer{ #footer{
padding: 6px 10px; padding: 6px 10px;
@ -151,20 +153,29 @@ dd {
vertical-align:top; vertical-align:top;
} }
/* scaffold buttons */ /* notices and errors */
p.error, error_message {
color: #e32000;
font-size: 18px;
background-color: #fff;
margin: 8px 4px;
}
p.error em {
font-size: 18px;
color: #003d4c;
}
.notice { .notice {
color: #DB8101; color: #656565;
background-color: #ddd; font-size: 14px;
background-color: #f4f4f4;
padding: 4px;
display:block; display:block;
padding: 1em;
} }
.tip { .tip {
color: #DB8101; color: #e32000;
background-color: #ddd; background-color: #ddd;
display: block;
padding: 1em;
} }

View file

@ -129,12 +129,7 @@ form div label.labelCheckbox, form div label.labelRadio {
form div fieldset label.labelCheckbox, form div fieldset label.labelRadio { form div fieldset label.labelCheckbox, form div fieldset label.labelRadio {
margin: 0px 0px 5px 0px; margin: 0px 0px 5px 0px;
} }
p.error {
color: #DB8101;
background-color: #DBA941;
font-size: 14px;
padding: 1em;
}
form div input, form div select, form div textarea { form div input, form div select, form div textarea {
padding: 1px 3px; padding: 1px 3px;

View file

@ -76,7 +76,6 @@
} }
} }
require CORE_PATH . 'cake' . DS . 'bootstrap.php'; require CORE_PATH . 'cake' . DS . 'bootstrap.php';
if (isset($_GET['url']) && $_GET['url'] === 'favicon.ico') { if (isset($_GET['url']) && $_GET['url'] === 'favicon.ico') {
} else { } else {
$Dispatcher=new Dispatcher(); $Dispatcher=new Dispatcher();