Merging fixes and enhancements into trunk

Revision: [2025]
A little more work on plugin to set some default routing.

Revision: [2024]
Changed DboSource::field() so the name() is not called for some field variables.

Revision: [2023]
Changes made in [2022] should only check if the $conditions is not empty.

Revision: [2022]
Changed DboSource::conditions() so it will add the "ticks" needed around the Model.field names.
The Model.field name conventions must be used for this to work.

Revision: [2021]
Adding fix for Ticket #405

Revision: [2020]
Added fix for Ticket #403

Revision: [2019]
Added patch from Ticket #404.
Fixing formatting of files.

Revision: [2018]
Fixing formatting of files 

Revision: [2017]
Fixed bad search and replace

Revision: [2016]
Fixing formatting of files 

Revision: [2015]
Replaced all 3 space indents with 4 space indents

Revision: [2014]
Updating variables to use the naming proper conventions

Revision: [2013]
Added patch from Ticket #406

Revision: [2012]
Adding fix for Ticket #407.
Fix variables that where not formatted per the coding conventions

Revision: [2011]
Adding patch from Ticket #401

git-svn-id: https://svn.cakephp.org/repo/trunk/cake@2026 3807eeeb-6ff5-0310-8944-8be069107fe0
This commit is contained in:
phpnut 2006-02-18 23:42:21 +00:00
parent 9a8d5c15fe
commit a75e08976f
74 changed files with 3207 additions and 3045 deletions

View file

@ -1,5 +1,5 @@
<IfModule mod_rewrite.c> <IfModule mod_rewrite.c>
RewriteEngine on RewriteEngine on
RewriteRule ^$ app/webroot/ [L] RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L] RewriteRule (.*) app/webroot/$1 [L]
</IfModule> </IfModule>

View file

@ -6,4 +6,4 @@
// +---------------------------------------------------------------------------------------------------+ // // +---------------------------------------------------------------------------------------------------+ //
/////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
0.10.8.2010 0.10.8.2026

View file

@ -1,5 +1,5 @@
<IfModule mod_rewrite.c> <IfModule mod_rewrite.c>
RewriteEngine on RewriteEngine on
RewriteRule ^$ webroot/ [L] RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L] RewriteRule (.*) webroot/$1 [L]
</IfModule> </IfModule>

View file

@ -54,14 +54,14 @@
*/ */
define('DEBUG', 1); define('DEBUG', 1);
/** /**
* Error constant. Used for differentiating error logging and debugging. * Error constant. Used for differentiating error logging and debugging.
* Currently PHP supports LOG_DEBUG * Currently PHP supports LOG_DEBUG
*/ */
define ('LOG_ERROR', 2); define ('LOG_ERROR', 2);
/** /**
* CakePHP includes 3 types of session saves * CakePHP includes 3 types of session saves
* database or file. Set this to your preffered method. * database or file. Set this to your preferred method.
* If you want to use your own save handeler place it in * If you want to use your own save handler place it in
* app/config/name.php DO NOT USE file or database as the name. * app/config/name.php DO NOT USE file or database as the name.
* and use just the name portion below. * and use just the name portion below.
* *
@ -117,7 +117,7 @@ define('WEBSERVICES', 'off');
/** /**
* Compress output CSS (removing comments, whitespace, repeating tags etc.) * Compress output CSS (removing comments, whitespace, repeating tags etc.)
* This requires a /var/cache directory to be writable by the web server (caching). * This requires a/var/cache directory to be writable by the web server (caching).
* To use, prefix the CSS link URL with '/ccss/' instead of '/css/' or use Controller::cssTag(). * To use, prefix the CSS link URL with '/ccss/' instead of '/css/' or use Controller::cssTag().
*/ */
define('COMPRESS_CSS', false); define('COMPRESS_CSS', false);
@ -141,6 +141,6 @@ define('MAX_MD5SIZE', (5*1024)*1024 );
* To use Access Control Lists with Cake... * To use Access Control Lists with Cake...
*/ */
define('ACL_CLASSNAME', 'DB_ACL'); define('ACL_CLASSNAME', 'DB_ACL');
define('ACL_FILENAME', 'dbacl'.DS.'db_acl'); define('ACL_FILENAME', 'dbacl'.DS.'db_acl');
?> ?>

View file

@ -48,8 +48,8 @@
* PostgreSQL set the connect to either pg_pconnect of pg_connect * PostgreSQL set the connect to either pg_pconnect of pg_connect
* SQLite set the connect to sqlite_popen sqlite_open * SQLite set the connect to sqlite_popen sqlite_open
* ADOdb set the connect to one of these * ADOdb set the connect to one of these
* (http://phplens.com/adodb/supported.databases.html) and * (http://phplens.com/adodb/supported.databases.html) and
* append it '|p' for persistent connection. (mssql|p for example, or just mssql for not persistent) * append it '|p' for persistent connection. (mssql|p for example, or just mssql for not persistent)
* *
* host => * host =>
* the host you connect to the database * the host you connect to the database
@ -59,21 +59,21 @@
*/ */
class DATABASE_CONFIG class DATABASE_CONFIG
{ {
var $default = array('driver' => 'mysql', var $default = array('driver' => 'mysql',
'connect' => 'mysql_pconnect', 'connect' => 'mysql_pconnect',
'host' => 'localhost', 'host' => 'localhost',
'login' => 'user', 'login' => 'user',
'password' => 'password', 'password' => 'password',
'database' => 'project_name', 'database' => 'project_name',
'prefix' => ''); 'prefix' => '');
var $test = array('driver' => 'mysql', var $test = array('driver' => 'mysql',
'connect' => 'mysql_pconnect', 'connect' => 'mysql_pconnect',
'host' => 'localhost', 'host' => 'localhost',
'login' => 'user', 'login' => 'user',
'password' => 'password', 'password' => 'password',
'database' => 'project_name-test', 'database' => 'project_name-test',
'prefix' => ''); 'prefix' => '');
} }
?> ?>

View file

@ -3,22 +3,22 @@
/** /**
* Short description for file. * Short description for file.
* *
* In this file, you set up routes to your controllers and their actions. * In this file, you set up routes to your controllers and their actions.
* Routes are very important mechanism that allows you to freely connect * Routes are very important mechanism that allows you to freely connect
* different urls to chosen controllers and their actions (functions). * different urls to chosen controllers and their actions (functions).
* *
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP : Rapid Development Framework <http://www.cakephp.org/> * CakePHP : Rapid Development Framework <http://www.cakephp.org/>
* Copyright (c) 2006, Cake Software Foundation, Inc. * Copyright (c) 2006, Cake Software Foundation, Inc.
* 1785 E. Sahara Avenue, Suite 490-204 * 1785 E. Sahara Avenue, Suite 490-204
* Las Vegas, Nevada 89104 * Las Vegas, Nevada 89104
* *
* Licensed under The MIT License * Licensed under The MIT License
* Redistributions of files must retain the above copyright notice. * Redistributions of files must retain the above copyright notice.
* *
* @filesource * @filesource
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc. * @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
* @package cake * @package cake
@ -31,8 +31,8 @@
*/ */
/** /**
* Here, we are connecting '/' (base path) to controller called 'Pages', * Here, we are connecting '/' (base path) to controller called 'Pages',
* its action called 'display', and we pass a param to select the view file * its action called 'display', and we pass a param to select the view file
* to use (in this case, /app/views/pages/home.thtml)... * to use (in this case, /app/views/pages/home.thtml)...
*/ */
$Route->connect ('/', array('controller'=>'pages', 'action'=>'display', 'home')); $Route->connect ('/', array('controller'=>'pages', 'action'=>'display', 'home'));

View file

@ -1,7 +1,7 @@
# @copyright Copyright (c) 2006, Cake Software Foundation, Inc. -- @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
# @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project -- @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
# @since CakePHP v 0.10.8.1997 -- @since CakePHP v 0.10.8.1997
# @version $Revision$ -- @version $Revision$
CREATE TABLE cake_sessions ( CREATE TABLE cake_sessions (
id varchar(255) NOT NULL default '', id varchar(255) NOT NULL default '',

View file

@ -3,20 +3,20 @@
/** /**
* Short description for file. * Short description for file.
* *
* Long description for file * Long description for file
* *
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP : Rapid Development Framework <http://www.cakephp.org/> * CakePHP : Rapid Development Framework <http://www.cakephp.org/>
* Copyright (c) 2006, Cake Software Foundation, Inc. * Copyright (c) 2006, Cake Software Foundation, Inc.
* 1785 E. Sahara Avenue, Suite 490-204 * 1785 E. Sahara Avenue, Suite 490-204
* Las Vegas, Nevada 89104 * Las Vegas, Nevada 89104
* *
* Licensed under The MIT License * Licensed under The MIT License
* Redistributions of files must retain the above copyright notice. * Redistributions of files must retain the above copyright notice.
* *
* @filesource * @filesource
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc. * @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
* @package cake * @package cake
@ -46,16 +46,16 @@ require(LIBS.'legacy.php');
*/ */
function make_clean_css ($path, $name) function make_clean_css ($path, $name)
{ {
require(VENDORS.'csspp'.DS.'csspp.php'); require(VENDORS.'csspp'.DS.'csspp.php');
$data = file_get_contents($path); $data = file_get_contents($path);
$csspp = new csspp(); $csspp = new csspp();
$output = $csspp->compress($data); $output = $csspp->compress($data);
$ratio = 100-(round(strlen($output)/strlen($data), 3)*100); $ratio = 100-(round(strlen($output)/strlen($data), 3)*100);
$output = " /* file: $name, ratio: $ratio% */ " . $output; $output = " /* file: $name, ratio: $ratio% */ " . $output;
return $output; return $output;
} }
/** /**
@ -67,50 +67,50 @@ function make_clean_css ($path, $name)
*/ */
function write_css_cache ($path, $content) function write_css_cache ($path, $content)
{ {
if (!is_dir(dirname($path))) if (!is_dir(dirname($path)))
mkdir(dirname($path)); mkdir(dirname($path));
$cache = new File($path); $cache = new File($path);
return $cache->write($content); return $cache->write($content);
} }
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]);
if (!file_exists($filepath)) if (!file_exists($filepath))
die('Wrong file name.'); die('Wrong file name.');
if (file_exists($cachepath)) if (file_exists($cachepath))
{ {
$templateModified = filemtime($filepath); $templateModified = filemtime($filepath);
$cacheModified = filemtime($cachepath); $cacheModified = filemtime($cachepath);
if ($templateModified > $cacheModified) if ($templateModified > $cacheModified)
{ {
$output = make_clean_css ($filepath, $filename); $output = make_clean_css ($filepath, $filename);
write_css_cache ($cachepath, $output); write_css_cache ($cachepath, $output);
} }
else else
{ {
$output = file_get_contents($cachepath); $output = file_get_contents($cachepath);
} }
} }
else else
{ {
$output = make_clean_css ($filepath, $filename); $output = make_clean_css ($filepath, $filename);
write_css_cache ($cachepath, $output); write_css_cache ($cachepath, $output);
} }
header("Date: ".date("D, j M Y G:i:s ", $templateModified).'GMT'); header("Date: ".date("D, j M Y G:i:s ", $templateModified).'GMT');
header("Content-Type: text/css"); header("Content-Type: text/css");
header("Expires: ".gmdate("D, j M Y H:i:s", time()+DAY)." GMT"); header("Expires: ".gmdate("D, j M Y H:i:s", time()+DAY)." GMT");
header("Cache-Control: cache"); // HTTP/1.1 header("Cache-Control: cache");// HTTP/1.1
header("Pragma: cache"); // HTTP/1.0 header("Pragma: cache");// HTTP/1.0
print $output; print $output;
?> ?>

View file

@ -37,13 +37,13 @@
if (!defined('ROOT')) if (!defined('ROOT'))
{ {
//define('ROOT', 'FULL PATH TO DIRECTORY WHERE APP DIRECTORY IS LOCATED DO NOT ADD A TRAILING DIRECTORY SEPARATOR'; //define('ROOT', 'FULL PATH TO DIRECTORY WHERE APP DIRECTORY IS LOCATED DO NOT ADD A TRAILING DIRECTORY SEPARATOR';
define('ROOT', dirname(dirname(dirname(__FILE__)))); define('ROOT', dirname(dirname(dirname(__FILE__))));
} }
if (!defined('APP_DIR')) if (!defined('APP_DIR'))
{ {
//define('APP_DIR', 'DIRECTORY NAME OF APPLICATION'; //define('APP_DIR', 'DIRECTORY NAME OF APPLICATION';
define ('APP_DIR', basename(dirname(dirname(__FILE__)))); define ('APP_DIR', basename(dirname(dirname(__FILE__))));
} }
@ -53,7 +53,7 @@ if (!defined('APP_DIR'))
*/ */
if (!defined('CAKE_CORE_INCLUDE_PATH')) if (!defined('CAKE_CORE_INCLUDE_PATH'))
{ {
//define ('CAKE_CORE_INCLUDE_PATH', FULL PATH TO DIRECTORY WHERE CAKE CORE IS INSTALLED DO NOT ADD A TRAILING DIRECTORY SEPARATOR'; //define ('CAKE_CORE_INCLUDE_PATH', FULL PATH TO DIRECTORY WHERE CAKE CORE IS INSTALLED DO NOT ADD A TRAILING DIRECTORY SEPARATOR';
define('CAKE_CORE_INCLUDE_PATH', ROOT); define('CAKE_CORE_INCLUDE_PATH', ROOT);
} }
@ -62,7 +62,7 @@ if (!defined('CAKE_CORE_INCLUDE_PATH'))
/////////////////////////////// ///////////////////////////////
if (!defined('DS')) if (!defined('DS'))
{ {
define('DS', DIRECTORY_SEPARATOR); define('DS', DIRECTORY_SEPARATOR);
} }
if (!defined('WEBROOT_DIR')) if (!defined('WEBROOT_DIR'))

View file

@ -3,21 +3,21 @@
/** /**
* Short description for file. * Short description for file.
* *
* This file includes js vendor-files from /vendor/ directory if they need to * This file includes js vendor-files from /vendor/ directory if they need to
* be accessible to the public. * be accessible to the public.
* *
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP : Rapid Development Framework <http://www.cakephp.org/> * CakePHP : Rapid Development Framework <http://www.cakephp.org/>
* Copyright (c) 2006, Cake Software Foundation, Inc. * Copyright (c) 2006, Cake Software Foundation, Inc.
* 1785 E. Sahara Avenue, Suite 490-204 * 1785 E. Sahara Avenue, Suite 490-204
* Las Vegas, Nevada 89104 * Las Vegas, Nevada 89104
* *
* Licensed under The MIT License * Licensed under The MIT License
* Redistributions of files must retain the above copyright notice. * Redistributions of files must retain the above copyright notice.
* *
* @filesource * @filesource
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc. * @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
* @package cake * @package cake
@ -34,7 +34,7 @@
*/ */
if(is_file('../../vendors/javascript/'.$_GET['file']) && (preg_match('/(.+)\\.js/', $_GET['file']))) if(is_file('../../vendors/javascript/'.$_GET['file']) && (preg_match('/(.+)\\.js/', $_GET['file'])))
{ {
readfile('../../vendors/javascript/'.$_GET['file']); readfile('../../vendors/javascript/'.$_GET['file']);
} }
?> ?>

View file

@ -33,7 +33,7 @@
*/ */
define('SECOND', 1); define('SECOND', 1);
define('MINUTE', 60 * SECOND); define('MINUTE', 60 * SECOND);
define('HOUR', 60 * MINUTE); define('HOUR', 60 * MINUTE);
define('DAY', 24 * HOUR); define('DAY', 24 * HOUR);
define('WEEK', 7 * DAY); define('WEEK', 7 * DAY);
define('MONTH', 30 * DAY); define('MONTH', 30 * DAY);
@ -165,7 +165,7 @@ function loadModel($name)
{ {
$name = Inflector::underscore($name); $name = Inflector::underscore($name);
// Make sure AppModel is loaded // Make sure AppModel is loaded
if(!class_exists('AppModel')) if(!class_exists('AppModel'))
{ {
if(file_exists(APP.'app_model.php')) if(file_exists(APP.'app_model.php'))
@ -289,23 +289,33 @@ function loadPluginController ($plugin, $controller)
} }
} }
if(empty($controller))
{
if(file_exists(APP.'plugins'.DS.$plugin.DS.'controllers'.DS.$plugin.'_controller.php'))
{
require(APP.'plugins'.DS.$plugin.DS.'controllers'.DS.$plugin.'_controller.php');
return true;
}
}
if(!class_exists($controller.'Controller')) if(!class_exists($controller.'Controller'))
{ {
$controller = Inflector::underscore($controller); $controller = Inflector::underscore($controller);
$file = APP.'plugins'.DS.$plugin.DS.'controllers'.DS.$controller.'_controller.php'; $file = APP.'plugins'.DS.$plugin.DS.'controllers'.DS.$controller.'_controller.php';
if(!file_exists($file)) if(file_exists($file))
{
return false;
}
else
{ {
require($file); require($file);
return true; return true;
} }
} elseif(file_exists(APP.'plugins'.DS.$plugin.DS.'controllers'.DS.$plugin.'_controller.php'))
else {
{ require(APP.'plugins'.DS.$plugin.DS.'controllers'.DS.$plugin.'_controller.php');
return true; return true;
}
else
{
return false;
}
} }
} }
@ -428,7 +438,7 @@ function debug($var = false, $showHtml = false)
} }
print "{$var}\n</pre>\n"; print "{$var}\n</pre>\n";
} }
} }
if (!function_exists('getMicrotime')) if (!function_exists('getMicrotime'))
@ -438,11 +448,11 @@ if (!function_exists('getMicrotime'))
* *
* @return integer * @return integer
*/ */
function getMicrotime() function getMicrotime()
{ {
list($usec, $sec) = explode(" ", microtime()); list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec); return ((float)$usec + (float)$sec);
} }
} }
if (!function_exists('sortByKey')) if (!function_exists('sortByKey'))
@ -450,7 +460,7 @@ if (!function_exists('sortByKey'))
/** /**
* Sorts given $array by key $sortby. * Sorts given $array by key $sortby.
* *
* @param array $array * @param array $array
* @param string $sortby * @param string $sortby
* @param string $order Sort order asc/desc (ascending or descending). * @param string $order Sort order asc/desc (ascending or descending).
* @param integer $type * @param integer $type
@ -506,11 +516,11 @@ if (!function_exists('array_combine'))
if ($c1 != $c2) if ($c1 != $c2)
{ {
return false; // different lenghts return false;// different lenghts
} }
if ($c1 <= 0) if ($c1 <= 0)
{ {
return false; // arrays are the same and both are empty return false;// arrays are the same and both are empty
} }
$output = array(); $output = array();
@ -645,8 +655,8 @@ function r($search, $replace, $subject)
* Print_r convenience function, which prints out <PRE> tags around * Print_r convenience function, which prints out <PRE> tags around
* the output of given array. Similar to debug(). * the output of given array. Similar to debug().
* *
* @see debug() * @see debug()
* @param array $var * @param array $var
*/ */
function pr($var) function pr($var)
{ {
@ -750,14 +760,14 @@ function env($key)
if (!function_exists('file_get_contents')) if (!function_exists('file_get_contents'))
{ {
/** /**
* Returns contents of a file as a string. * Returns contents of a file as a string.
* *
* @param string $fileName Name of the file. * @param string $fileName Name of the file.
* @param boolean $useIncludePath Wheter the function should use the * @param boolean $useIncludePath Wheter the function should use the
* include path or not. * include path or not.
* @return mixed Boolean false or contents of required file. * @return mixed Boolean false or contents of required file.
*/ */
function file_get_contents($fileName, $useIncludePath = false) function file_get_contents($fileName, $useIncludePath = false)
{ {
$res = fopen($fileName, 'rb', $useIncludePath); $res = fopen($fileName, 'rb', $useIncludePath);
@ -788,15 +798,15 @@ if (!function_exists('file_get_contents'))
if (!function_exists('file_put_contents')) if (!function_exists('file_put_contents'))
{ {
/** /**
* Writes data into file. * Writes data into file.
* *
* If file exists, it will be overwritten. If data is an array, it will be * If file exists, it will be overwritten. If data is an array, it will be
* join()ed with an empty string. * join()ed with an empty string.
* *
* @param string $fileName File name. * @param string $fileName File name.
* @param mixed $data String or array. * @param mixed $data String or array.
*/ */
function file_put_contents($fileName, $data) function file_put_contents($fileName, $data)
{ {
if (is_array($data)) if (is_array($data))
@ -843,12 +853,12 @@ function cache($path, $data = null, $expires = '+1 day', $target = 'cache')
if ($data == null) if ($data == null)
{ {
// Read data from file // Read data from file
if (file_exists($filename) && $filetime !== false) if (file_exists($filename) && $filetime !== false)
{ {
if ($filetime + $timediff < $now) if ($filetime + $timediff < $now)
{ {
// File has expired // File has expired
@unlink($filename); @unlink($filename);
} }
else else
@ -906,8 +916,8 @@ function countdim($array)
} }
/** /**
* Shortcut to Log::write. * Shortcut to Log::write.
*/ */
function LogError ($message) function LogError ($message)
{ {
if(!class_exists('CakeLog')) if(!class_exists('CakeLog'))

View file

@ -79,7 +79,7 @@ else
} }
else else
{ {
$url = $_GET['url']; $url = $_GET['url'];
} }
} }
@ -87,8 +87,8 @@ else
if (strpos($url, 'ccss/') === 0) if (strpos($url, 'ccss/') === 0)
{ {
include WWW_ROOT.DS.'css.php'; include WWW_ROOT.DS.'css.php';
die(); die();
} }

View file

@ -36,12 +36,12 @@
*/ */
if(!defined('ROOT')) if(!defined('ROOT'))
{ {
define ('ROOT', '../'); define ('ROOT', '../');
} }
if(!defined('WEBROOT_DIR')) if(!defined('WEBROOT_DIR'))
{ {
define ('WEBROOT_DIR', 'webroot'); define ('WEBROOT_DIR', 'webroot');
} }
/** /**

View file

@ -49,30 +49,30 @@ class Dispatcher extends Object
* Base URL * Base URL
* @var string * @var string
*/ */
var $base = false; var $base = false;
/** /**
* @var string * @var string
*/ */
var $admin = false; var $admin = false;
/** /**
* @var string * @var string
*/ */
var $webservices = null; var $webservices = null;
/** /**
* @var string * @var string
*/ */
var $plugin = null; var $plugin = null;
/** /**
* Constructor. * Constructor.
*/ */
function __construct() function __construct()
{ {
parent::__construct(); parent::__construct();
} }
/** /**
* Dispatches and invokes given URL, handing over control to the involved controllers, and then renders the results (if autoRender is set). * Dispatches and invokes given URL, handing over control to the involved controllers, and then renders the results (if autoRender is set).
@ -84,12 +84,12 @@ class Dispatcher extends Object
* @param string $url URL information to work on. * @param string $url URL information to work on.
* @return boolean Success * @return boolean Success
*/ */
function dispatch($url, $additionalParams=array()) function dispatch($url, $additionalParams=array())
{ {
$params = array_merge($this->parseParams($url), $additionalParams); $params = array_merge($this->parseParams($url), $additionalParams);
$missingController = false; $missingController = false;
$missingAction = false; $missingAction = false;
$missingView = false; $missingView = false;
$privateAction = false; $privateAction = false;
$this->base = $this->baseUrl(); $this->base = $this->baseUrl();
if (empty($params['controller'])) if (empty($params['controller']))
@ -125,11 +125,18 @@ class Dispatcher extends Object
else else
{ {
$ctrlClass = $pluginClass; $ctrlClass = $pluginClass;
$oldAction = $params['action'];
$params = $this->_restructureParams($params); $params = $this->_restructureParams($params);
$plugin = Inflector::underscore($ctrlName); $plugin = Inflector::underscore($ctrlName);
$this->plugin = $plugin.DS; $this->plugin = $plugin.DS;
loadPluginModels($plugin); loadPluginModels($plugin);
$this->base = $this->base.'/'.Inflector::underscore($ctrlName); $this->base = $this->base.'/'.Inflector::underscore($ctrlName);
if(empty($params['controller']) || !class_exists($pluginClass))
{
$params['controller'] = Inflector::underscore($ctrlName);
$ctrlClass = $ctrlName.'Controller';
$params['action'] = $oldAction;
}
} }
} }
} }
@ -157,7 +164,7 @@ class Dispatcher extends Object
if ($missingController) if ($missingController)
{ {
return $this->cakeError('missingController',array(array('className' => Inflector::camelize($params['controller']."Controller"), return $this->cakeError('missingController',array(array('className' => Inflector::camelize($params['controller']."Controller"),
'webroot' => $this->webroot))); 'webroot' => $this->webroot)));
} }
else else
{ {
@ -229,7 +236,7 @@ class Dispatcher extends Object
} }
return $this->_invoke($controller, $params); return $this->_invoke($controller, $params);
} }
/** /**
* Invokes given controller's render action if autoRender option is set. Otherwise the contents of the operation are returned as a string. * Invokes given controller's render action if autoRender option is set. Otherwise the contents of the operation are returned as a string.
@ -238,47 +245,47 @@ class Dispatcher extends Object
* @param array $params * @param array $params
* @return string * @return string
*/ */
function _invoke (&$controller, $params) function _invoke (&$controller, $params)
{ {
if (!empty($controller->beforeFilter)) if (!empty($controller->beforeFilter))
{ {
if(is_array($controller->beforeFilter)) if(is_array($controller->beforeFilter))
{ {
foreach($controller->beforeFilter as $filter) foreach($controller->beforeFilter as $filter)
{ {
if(is_callable(array($controller,$filter)) && $filter != 'beforeFilter') if(is_callable(array($controller,$filter)) && $filter != 'beforeFilter')
{ {
$controller->$filter(); $controller->$filter();
} }
} }
} }
else else
{ {
if(is_callable(array($controller, $controller->beforeFilter)) && $controller->beforeFilter != 'beforeFilter') if(is_callable(array($controller, $controller->beforeFilter)) && $controller->beforeFilter != 'beforeFilter')
{ {
$controller->{$controller->beforeFilter}(); $controller->{$controller->beforeFilter}();
} }
} }
} }
$controller->beforeFilter(); $controller->beforeFilter();
foreach($controller->components as $c) foreach($controller->components as $c)
{ {
if (isset($controller->{$c}) && is_object($controller->{$c}) && is_callable(array($controller->{$c}, 'startup'))) if (isset($controller->{$c}) && is_object($controller->{$c}) && is_callable(array($controller->{$c}, 'startup')))
{ {
$controller->{$c}->startup($controller); $controller->{$c}->startup($controller);
} }
} }
$output = call_user_func_array(array(&$controller, $params['action']), empty($params['pass'])? null: $params['pass']); $output = call_user_func_array(array(&$controller, $params['action']), empty($params['pass'])? null: $params['pass']);
if ($controller->autoRender) if ($controller->autoRender)
{ {
$output = $controller->render(); $output = $controller->render();
} }
$controller->output =& $output; $controller->output =& $output;
$controller->afterFilter(); $controller->afterFilter();
return $controller->output; return $controller->output;
} }
/** /**
* Returns array of GET and POST parameters. GET parameters are taken from given URL. * Returns array of GET and POST parameters. GET parameters are taken from given URL.
@ -286,52 +293,52 @@ class Dispatcher extends Object
* @param string $from_url URL to mine for parameter information. * @param string $from_url URL to mine for parameter information.
* @return array Parameters found in POST and GET. * @return array Parameters found in POST and GET.
*/ */
function parseParams($from_url) function parseParams($from_url)
{ {
// load routes config // load routes config
$Route = new Router(); $Route = new Router();
include CONFIGS.'routes.php'; include CONFIGS.'routes.php';
$params = $Route->parse ($from_url); $params = $Route->parse ($from_url);
if (ini_get('magic_quotes_gpc') == 1) if (ini_get('magic_quotes_gpc') == 1)
{ {
if(!empty($_POST)) if(!empty($_POST))
{ {
$params['form'] = stripslashes_deep($_POST); $params['form'] = stripslashes_deep($_POST);
} }
} }
else else
{ {
$params['form'] = $_POST; $params['form'] = $_POST;
} }
if (isset($params['form']['data'])) if (isset($params['form']['data']))
{ {
$params['data'] = $params['form']['data']; $params['data'] = $params['form']['data'];
} }
if (isset($_GET)) if (isset($_GET))
{ {
if (ini_get('magic_quotes_gpc') == 1) if (ini_get('magic_quotes_gpc') == 1)
{ {
$params['url'] = stripslashes_deep($_GET); $params['url'] = stripslashes_deep($_GET);
} }
else else
{ {
$params['url'] = $_GET; $params['url'] = $_GET;
} }
} }
foreach ($_FILES as $name => $data) foreach ($_FILES as $name => $data)
{ {
$params['form'][$name] = $data; $params['form'][$name] = $data;
} }
$params['bare'] = empty($params['ajax'])? (empty($params['bare'])? 0: 1): 1; $params['bare'] = empty($params['ajax'])? (empty($params['bare'])? 0: 1): 1;
$params['webservices'] = empty($params['webservices']) ? null : $params['webservices']; $params['webservices'] = empty($params['webservices']) ? null : $params['webservices'];
return $params; return $params;
} }
/** /**
* Returns a base URL. * Returns a base URL.
@ -340,18 +347,18 @@ class Dispatcher extends Object
*/ */
function baseUrl() function baseUrl()
{ {
$htaccess = null; $htaccess = null;
$base = $this->admin; $base = $this->admin;
$this->webroot = ''; $this->webroot = '';
if (defined('BASE_URL')) if (defined('BASE_URL'))
{ {
$base = BASE_URL.$this->admin; $base = BASE_URL.$this->admin;
} }
$docRoot = env('DOCUMENT_ROOT'); $docRoot = env('DOCUMENT_ROOT');
$scriptName = env('PHP_SELF'); $scriptName = env('PHP_SELF');
// If document root ends with 'webroot', it's probably correctly set // If document root ends with 'webroot', it's probably correctly set
$r = null; $r = null;
if (preg_match('/'.APP_DIR.'\\'.DS.WEBROOT_DIR.'/', $docRoot)) if (preg_match('/'.APP_DIR.'\\'.DS.WEBROOT_DIR.'/', $docRoot))
{ {
@ -399,21 +406,21 @@ class Dispatcher extends Object
} }
} }
return $base; return $base;
} }
function _restructureParams($params) function _restructureParams($params)
{ {
$params['controller'] = $params['action']; $params['controller'] = $params['action'];
if(isset($params['pass'][0])) if(isset($params['pass'][0]))
{ {
$params['action'] = $params['pass'][0]; $params['action'] = $params['pass'][0];
array_shift($params['pass']); array_shift($params['pass']);
} }
else else
{ {
$params['action'] = null; $params['action'] = null;
} }
return $params; return $params;
} }
} }
?> ?>

View file

@ -1,7 +1,7 @@
/////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// +---------------------------------------------------------------------------------------------------+ // // +---------------------------------------------------------------------------------------------------+//
// + $Id$ // + $Id$
// + Last Modified: $Date$ // + Last Modified: $Date$
// + Modified By: $LastChangedBy$ // + Modified By: $LastChangedBy$
// +---------------------------------------------------------------------------------------------------+ // // +---------------------------------------------------------------------------------------------------+//
/////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////

View file

@ -1,7 +1,7 @@
/////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// +---------------------------------------------------------------------------------------------------+ // // +---------------------------------------------------------------------------------------------------+//
// + $Id$ // + $Id$
// + Last Modified: $Date$ // + Last Modified: $Date$
// + Modified By: $LastChangedBy$ // + Modified By: $LastChangedBy$
// +---------------------------------------------------------------------------------------------------+ // // +---------------------------------------------------------------------------------------------------+//
/////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////

View file

@ -1,9 +1,9 @@
/////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// +---------------------------------------------------------------------------------------------------+ // // +---------------------------------------------------------------------------------------------------+//
// + $Id$ // + $Id$
// + Last Modified:$ // + Last Modified:$
// + Modified By:$ // + Modified By:$
// +---------------------------------------------------------------------------------------------------+ // // +---------------------------------------------------------------------------------------------------+//
/////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
You can find some help with problems you may have installing CakePHP here: You can find some help with problems you may have installing CakePHP here:

View file

@ -1,9 +1,9 @@
/////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// +---------------------------------------------------------------------------------------------------+ // // +---------------------------------------------------------------------------------------------------+//
// + $Id$ // + $Id$
// + Last Modified: $Date$ // + Last Modified: $Date$
// + Modified By: $LastChangedBy$ // + Modified By: $LastChangedBy$
// +---------------------------------------------------------------------------------------------------+ // // +---------------------------------------------------------------------------------------------------+//
/////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
This README will be updated This README will be updated

View file

@ -39,11 +39,11 @@ uses('object', 'inflector');
* @package cake * @package cake
* @subpackage cake.libs * @subpackage cake.libs
* @since CakePHP v CakePHP v 0.10.3.1612 * @since CakePHP v CakePHP v 0.10.3.1612
*/ */
class Bake extends Object class Bake extends Object
{ {
/** /**
* Standard input stream (php://stdin). * Standard input stream (php://stdin).
* *
* @var resource * @var resource
@ -51,7 +51,7 @@ class Bake extends Object
*/ */
var $stdin = null; var $stdin = null;
/** /**
* Standard output stream (php://stdout). * Standard output stream (php://stdout).
* *
* @var resource * @var resource
@ -59,7 +59,7 @@ class Bake extends Object
*/ */
var $stdout = null; var $stdout = null;
/** /**
* Standard error stream (php://stderr). * Standard error stream (php://stderr).
* *
* @var resource * @var resource
@ -67,7 +67,7 @@ class Bake extends Object
*/ */
var $stderr = null; var $stderr = null;
/** /**
* Counts actions taken. * Counts actions taken.
* *
* @var integer * @var integer
@ -75,7 +75,7 @@ class Bake extends Object
*/ */
var $actions = null; var $actions = null;
/** /**
* Decides whether to overwrite existing files without asking. * Decides whether to overwrite existing files without asking.
* *
* @var boolean * @var boolean
@ -83,7 +83,7 @@ class Bake extends Object
*/ */
var $dontAsk = false; var $dontAsk = false;
/** /**
* Returns code template for PHP file generator. * Returns code template for PHP file generator.
* *
* @param string $type * @param string $type
@ -94,24 +94,24 @@ class Bake extends Object
{ {
switch ($type) switch ($type)
{ {
case 'view': return "%s"; case 'view': return "%s";
case 'model': return "<?php\n\nclass %s extends AppModel\n{\n}\n\n?>"; case 'model': return "<?php\n\nclass %s extends AppModel\n{\n}\n\n?>";
case 'action': return "\n\tfunction %s () {\n\t\t\n\t}\n"; case 'action': return "\n\tfunction %s () {\n\t\t\n\t}\n";
case 'ctrl': return "<?php\n\nclass %s extends %s\n{\n%s\n}\n\n?>"; case 'ctrl': return "<?php\n\nclass %s extends %s\n{\n%s\n}\n\n?>";
case 'helper': return "<?php\n\nclass %s extends AppController\n{\n}\n\n?>"; case 'helper': return "<?php\n\nclass %s extends AppController\n{\n}\n\n?>";
case 'test': return '<?php case 'test': return '<?php
class %sTest extends TestCase class %sTest extends TestCase
{ {
var $abc; var $abc;
// called before the tests // called before the tests
function setUp() function setUp()
{ {
$this->abc = new %s (); $this->abc = new %s ();
} }
// called after the tests // called after the tests
function tearDown() function tearDown()
{ {
unset($this->abc); unset($this->abc);
@ -120,7 +120,7 @@ class %sTest extends TestCase
/* /*
function testFoo () function testFoo ()
{ {
$result = $this->abc->Foo(); $result = $this->abc->Foo();
$expected = \'\'; $expected = \'\';
$this->assertEquals($result, $expected); $this->assertEquals($result, $expected);
} }
@ -133,7 +133,7 @@ class %sTest extends TestCase
} }
} }
/** /**
* Baker's constructor method. Initialises bakery, and starts production. * Baker's constructor method. Initialises bakery, and starts production.
* *
* @param string $type * @param string $type
@ -152,7 +152,7 @@ class %sTest extends TestCase
$this->stdout = fopen('php://stdout', 'w'); $this->stdout = fopen('php://stdout', 'w');
$this->stderr = fopen('php://stderr', 'w'); $this->stderr = fopen('php://stderr', 'w');
// Output directory name // Output directory name
fwrite($this->stderr, "\n".substr(ROOT,0,strlen(ROOT)-1).":\n".str_repeat('-',strlen(ROOT)+1)."\n"); fwrite($this->stderr, "\n".substr(ROOT,0,strlen(ROOT)-1).":\n".str_repeat('-',strlen(ROOT)+1)."\n");
switch ($type) switch ($type)
@ -172,7 +172,7 @@ class %sTest extends TestCase
$add_actions = array(); $add_actions = array();
$controllerPlural = Inflector::pluralize($controller); $controllerPlural = Inflector::pluralize($controller);
if ($controllerPlural != $controller) if ($controllerPlural != $controller)
{ {
fwrite($this->stdout, "I use pluralized Controller names. You entered '$controller'. I can inflect it to '$controllerPlural'. Should I? If no, I will use '$controller'. [y/n/q] "); fwrite($this->stdout, "I use pluralized Controller names. You entered '$controller'. I can inflect it to '$controllerPlural'. Should I? If no, I will use '$controller'. [y/n/q] ");
@ -221,7 +221,7 @@ class %sTest extends TestCase
} }
} }
/** /**
* Creates new view in VIEWS/$controller/ directory. * Creates new view in VIEWS/$controller/ directory.
* *
* @param string $controller * @param string $controller
@ -245,7 +245,7 @@ class %sTest extends TestCase
$this->actions++; $this->actions++;
} }
/** /**
* Creates new controller with defined actions, controller's test and * Creates new controller with defined actions, controller's test and
* helper with helper's test. * helper with helper's test.
* *
@ -263,12 +263,12 @@ class %sTest extends TestCase
{ {
$this->makeController($name, $actions); $this->makeController($name, $actions);
$this->makeControllerTest($name); $this->makeControllerTest($name);
//$this->makeHelper($name); //$this->makeHelper($name);
//$this->makeHelperTest($name); //$this->makeHelperTest($name);
$this->actions++; $this->actions++;
} }
/** /**
* Creates new controller file with defined actions. * Creates new controller file with defined actions.
* *
* @param string $name * @param string $name
@ -284,14 +284,14 @@ class %sTest extends TestCase
*/ */
function makeController ($name, $actions) function makeController ($name, $actions)
{ {
$ctrl = $this->makeControllerName($name); $ctrl = $this->makeControllerName($name);
$helper = $this->makeHelperName($name); $helper = $this->makeHelperName($name);
//$body = sprintf($this->template('ctrl'), $ctrl, $helper, join('', $this->getActions($actions))); //$body = sprintf($this->template('ctrl'), $ctrl, $helper, join('', $this->getActions($actions)));
$body = sprintf($this->template('ctrl'), $ctrl, 'AppController', join('', $this->getActions($actions))); $body = sprintf($this->template('ctrl'), $ctrl, 'AppController', join('', $this->getActions($actions)));
return $this->createFile($this->makeControllerFn($name), $body); return $this->createFile($this->makeControllerFn($name), $body);
} }
/** /**
* Returns controller's name in CamelCase. * Returns controller's name in CamelCase.
* *
* @param string $name * @param string $name
@ -304,7 +304,7 @@ class %sTest extends TestCase
return Inflector::camelize($name).'Controller'; return Inflector::camelize($name).'Controller';
} }
/** /**
* Returns a name for controller's file, underscored. * Returns a name for controller's file, underscored.
* *
* @param string $name * @param string $name
@ -317,7 +317,7 @@ class %sTest extends TestCase
return CONTROLLERS.Inflector::underscore($name).'_controller.php'; return CONTROLLERS.Inflector::underscore($name).'_controller.php';
} }
/** /**
* Creates new test for a controller. * Creates new test for a controller.
* *
* @param string $name * @param string $name
@ -331,13 +331,13 @@ class %sTest extends TestCase
*/ */
function makeControllerTest ($name) function makeControllerTest ($name)
{ {
$fn = CONTROLLER_TESTS.Inflector::underscore($name).'_controller_test.php'; $fn = CONTROLLER_TESTS.Inflector::underscore($name).'_controller_test.php';
$body = $this->getTestBody($this->makeControllerName($name)); $body = $this->getTestBody($this->makeControllerName($name));
return true; //$this->createFile($fn, $body); // Disable creating tests till later return true;//$this->createFile($fn, $body);// Disable creating tests till later
} }
/** /**
* Creates new helper. * Creates new helper.
* *
* @param string $name * @param string $name
@ -355,7 +355,7 @@ class %sTest extends TestCase
return $this->createFile($this->makeHelperFn($name), $body); return $this->createFile($this->makeHelperFn($name), $body);
} }
/** /**
* Returns CamelCase name for a helper. * Returns CamelCase name for a helper.
* *
* @param string $name * @param string $name
@ -368,7 +368,7 @@ class %sTest extends TestCase
return Inflector::camelize($name).'Helper'; return Inflector::camelize($name).'Helper';
} }
/** /**
* Underscores file name for a helper. * Underscores file name for a helper.
* *
* @param string $name * @param string $name
@ -382,7 +382,7 @@ class %sTest extends TestCase
return HELPERS.Inflector::underscore($name).'_helper.php'; return HELPERS.Inflector::underscore($name).'_helper.php';
} }
/** /**
* Creates new test for a helper. * Creates new test for a helper.
* *
* @param string $name * @param string $name
@ -396,13 +396,13 @@ class %sTest extends TestCase
*/ */
function makeHelperTest ($name) function makeHelperTest ($name)
{ {
$fn = HELPER_TESTS.Inflector::underscore($name).'_helper_test.php'; $fn = HELPER_TESTS.Inflector::underscore($name).'_helper_test.php';
$body = $this->getTestBody($this->makeHelperName($name)); $body = $this->getTestBody($this->makeHelperName($name));
return $this->createFile($fn, $body); return $this->createFile($fn, $body);
} }
/** /**
* Returns an array of actions' templates. * Returns an array of actions' templates.
* *
* @param array $as * @param array $as
@ -420,7 +420,7 @@ class %sTest extends TestCase
return $out; return $out;
} }
/** /**
* Returns a test template for given class. * Returns a test template for given class.
* *
* @param string $class * @param string $class
@ -433,7 +433,7 @@ class %sTest extends TestCase
return sprintf($this->template('test'), $class, $class); return sprintf($this->template('test'), $class, $class);
} }
/** /**
* Creates new model. * Creates new model.
* *
* @param string $name * @param string $name
@ -470,12 +470,12 @@ class %sTest extends TestCase
} }
$this->createFile($this->getModelFn($name), sprintf($this->template('model'), $this->getModelName($name))); $this->createFile($this->getModelFn($name), sprintf($this->template('model'), $this->getModelName($name)));
//$this->makeModelTest ($name); //$this->makeModelTest ($name);
// TODO: Add model test back when I'm less lazy // TODO: Add model test back when I'm less lazy
$this->actions++; $this->actions++;
} }
/** /**
* Returns an underscored filename for a model. * Returns an underscored filename for a model.
* *
* @param string $name * @param string $name
@ -489,7 +489,7 @@ class %sTest extends TestCase
return MODELS.Inflector::underscore($name).'.php'; return MODELS.Inflector::underscore($name).'.php';
} }
/** /**
* Creates a test for a given model. * Creates a test for a given model.
* *
* @param string $name * @param string $name
@ -503,13 +503,13 @@ class %sTest extends TestCase
*/ */
function makeModelTest ($name) function makeModelTest ($name)
{ {
$fn = MODEL_TESTS.Inflector::underscore($name).'_test.php'; $fn = MODEL_TESTS.Inflector::underscore($name).'_test.php';
$body = $this->getTestBody($this->getModelName($name)); $body = $this->getTestBody($this->getModelName($name));
return $this->createFile($fn, $body); return $this->createFile($fn, $body);
} }
/** /**
* Returns CamelCased name of a model. * Returns CamelCased name of a model.
* *
* @param string $name * @param string $name
@ -522,7 +522,7 @@ class %sTest extends TestCase
return Inflector::camelize($name); return Inflector::camelize($name);
} }
/** /**
* Creates a file with given path and contents. * Creates a file with given path and contents.
* *
* @param string $path * @param string $path
@ -558,7 +558,7 @@ class %sTest extends TestCase
} }
else else
{ {
fwrite($this->stdout, "Skip {$shortPath}\n"); fwrite($this->stdout, "Skip {$shortPath}\n");
return false; return false;
} }
} }
@ -567,19 +567,19 @@ class %sTest extends TestCase
{ {
fwrite($f, $contents); fwrite($f, $contents);
fclose($f); fclose($f);
fwrite($this->stdout, "Wrote {$shortPath}\n"); fwrite($this->stdout, "Wrote {$shortPath}\n");
// debug ("Wrote {$path}"); // debug ("Wrote {$path}");
return true; return true;
} }
else else
{ {
fwrite($this->stderr, "Error! Couldn't open {$shortPath} for writing.\n"); fwrite($this->stderr, "Error! Couldn't open {$shortPath} for writing.\n");
// debug ("Error! Couldn't open {$path} for writing."); // debug ("Error! Couldn't open {$path} for writing.");
return false; return false;
} }
} }
/** /**
* Creates a directory with given path. * Creates a directory with given path.
* *
* @param string $path * @param string $path
@ -600,13 +600,13 @@ class %sTest extends TestCase
if (mkdir($path)) if (mkdir($path))
{ {
fwrite($this->stdout, "Created {$shortPath}\n"); fwrite($this->stdout, "Created {$shortPath}\n");
// debug ("Created {$path}"); // debug ("Created {$path}");
return true; return true;
} }
else else
{ {
fwrite($this->stderr, "Error! Couldn't create dir {$shortPath}\n"); fwrite($this->stderr, "Error! Couldn't create dir {$shortPath}\n");
// debug ("Error! Couldn't create dir {$path}"); // debug ("Error! Couldn't create dir {$path}");
return false; return false;
} }
} }

View file

@ -30,9 +30,9 @@
/** /**
* Included libraries. * Included libraries.
* *
*/ */
if(!class_exists('Model')) if(!class_exists('Model'))
{ {
uses(DS.'model'.DS.'model'); uses(DS.'model'.DS.'model');
@ -48,64 +48,64 @@ if(!class_exists('Model'))
*/ */
class Cache extends Model { class Cache extends Model {
/** /**
* Identifier. Either an MD5 string or NULL. * Identifier. Either an MD5 string or NULL.
* *
* @var string * @var string
*/ */
var $id = null; var $id = null;
/** /**
* Content container for cache data. * Content container for cache data.
* *
* @var unknown_type * @var unknown_type
*/ */
var $data = null; var $data = null;
/** /**
* Content to be cached. * Content to be cached.
* *
* @var unknown_type * @var unknown_type
*/ */
var $for_caching = null; var $for_caching = null;
/** /**
* Name of the database table used for caching. * Name of the database table used for caching.
* *
* @var string * @var string
*/ */
var $useTable = 'cache'; var $useTable = 'cache';
/** /**
* Constructor. Generates an md5'ed id for internal use. Calls the constructor on Model as well. * Constructor. Generates an md5'ed id for internal use. Calls the constructor on Model as well.
* *
* @param unknown_type $id * @param unknown_type $id
*/ */
function __construct ($id) function __construct ($id)
{ {
$this->id = (md5($id)); $this->id = (md5($id));
parent::__construct($this->id); parent::__construct($this->id);
} }
/** /**
* Returns this object's id after setting it. If called without parameters the current object's id is returned. * Returns this object's id after setting it. If called without parameters the current object's id is returned.
* *
* @param unknown_type $id * @param unknown_type $id
* @return unknown * @return unknown
*/ */
function id ($id=null) function id ($id=null)
{ {
if (!$id) return $this->id; if (!$id) return $this->id;
return ($this->id = $id); return ($this->id = $id);
} }
/** /**
* Store given content in cache database. * Store given content in cache database.
* *
* @param string $content Content to keep in cache. * @param string $content Content to keep in cache.
* @param int $keep_for Number of seconds to keep data in cache. * @param int $keep_for Number of seconds to keep data in cache.
* @return boolean Success * @return boolean Success
*/ */
function remember ($content, $keep_for=CACHE_PAGES_FOR) function remember ($content, $keep_for=CACHE_PAGES_FOR)
{ {
$data = addslashes($this->for_caching.$content); $data = addslashes($this->for_caching.$content);
@ -113,12 +113,12 @@ class Cache extends Model {
return $this->query("REPLACE {$this->useTable} (id,data,expire) VALUES ('{$this->id}', '{$data}', '{$expire}')"); return $this->query("REPLACE {$this->useTable} (id,data,expire) VALUES ('{$this->id}', '{$data}', '{$expire}')");
} }
/** /**
* Returns content from the Cache object itself, if the Cache object has a non-empty data property. * Returns content from the Cache object itself, if the Cache object has a non-empty data property.
* Else from the database cache. * Else from the database cache.
* *
* @return unknown * @return unknown
*/ */
function restore() function restore()
{ {
if (empty($this->data['data'])) if (empty($this->data['data']))
@ -127,31 +127,31 @@ class Cache extends Model {
return $this->data['data']; return $this->data['data'];
} }
/** /**
* Returns true if the cache data property has current (non-stale) content for given id. * Returns true if the cache data property has current (non-stale) content for given id.
* *
* @return boolean * @return boolean
*/ */
function has() function has()
{ {
return is_array($this->data = $this->find("id='{$this->id}' AND expire>NOW()")); return is_array($this->data = $this->find("id='{$this->id}' AND expire>NOW()"));
} }
/** /**
* Appends $string to the for_caching property of the Cache object. * Appends $string to the for_caching property of the Cache object.
* *
* @param string $string * @param string $string
*/ */
function append($string) function append($string)
{ {
$this->for_caching .= $string; $this->for_caching .= $string;
} }
/** /**
* Clears the cache database table. * Clears the cache database table.
* *
* @return unknown * @return unknown
*/ */
function clear() function clear()
{ {
return $this->query("DELETE FROM {$this->useTable}"); return $this->query("DELETE FROM {$this->useTable}");

View file

@ -29,9 +29,9 @@
*/ */
/** /**
* Included libraries. * Included libraries.
* *
*/ */
if(!class_exists('File')) if(!class_exists('File'))
{ {
uses('file'); uses('file');
@ -53,14 +53,14 @@ class CakeLog
* @param string $msg Message to log * @param string $msg Message to log
* @return boolean Success * @return boolean Success
*/ */
function write($type, $msg) function write($type, $msg)
{ {
$filename = LOGS.$type.'.log'; $filename = LOGS.$type.'.log';
$output = date('y-m-d H:i:s').' '.ucfirst($type).': '.$msg."\n"; $output = date('y-m-d H:i:s').' '.ucfirst($type).': '.$msg."\n";
$log = new File($filename); $log = new File($filename);
return $log->append($output); return $log->append($output);
} }
} }
?> ?>

View file

@ -48,22 +48,22 @@ class ClassRegistry
* @var array * @var array
* @access private * @access private
*/ */
var $_objects = array(); var $_objects = array();
/** /**
* Return a singleton instance of the ClassRegistry. * Return a singleton instance of the ClassRegistry.
* *
* @return ClassRegistry instance * @return ClassRegistry instance
*/ */
function &getInstance() function &getInstance()
{ {
static $instance = array(); static $instance = array();
if (!$instance) if (!$instance)
{ {
$instance[0] =& new ClassRegistry; $instance[0] =& new ClassRegistry;
} }
return $instance[0]; return $instance[0];
} }
/** /**
* Add $object to the registry, associating it with the name $key. * Add $object to the registry, associating it with the name $key.
@ -71,8 +71,8 @@ class ClassRegistry
* @param string $key * @param string $key
* @param mixed $object * @param mixed $object
*/ */
function addObject($key, &$object) function addObject($key, &$object)
{ {
$_this =& ClassRegistry::getInstance(); $_this =& ClassRegistry::getInstance();
$key = strtolower($key); $key = strtolower($key);
@ -80,7 +80,7 @@ class ClassRegistry
{ {
$_this->_objects[$key] =& $object; $_this->_objects[$key] =& $object;
} }
} }
/** /**
* Returns true if given key is present in the ClassRegistry. * Returns true if given key is present in the ClassRegistry.
@ -88,12 +88,12 @@ class ClassRegistry
* @param string $key Key to look for * @param string $key Key to look for
* @return boolean Success * @return boolean Success
*/ */
function isKeySet($key) function isKeySet($key)
{ {
$_this =& ClassRegistry::getInstance(); $_this =& ClassRegistry::getInstance();
$key = strtolower($key); $key = strtolower($key);
return array_key_exists($key, $_this->_objects); return array_key_exists($key, $_this->_objects);
} }
/** /**
* Return object which corresponds to given key. * Return object which corresponds to given key.
@ -101,11 +101,11 @@ class ClassRegistry
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
function &getObject($key) function &getObject($key)
{ {
$key = strtolower($key); $key = strtolower($key);
$_this =& ClassRegistry::getInstance(); $_this =& ClassRegistry::getInstance();
return $_this->_objects[$key]; return $_this->_objects[$key];
} }
} }
?> ?>

View file

@ -41,25 +41,25 @@
class AclComponent extends Object class AclComponent extends Object
{ {
var $_instance = null; var $_instance = null;
var $controller = true; var $controller = true;
/** /**
* Constructor. Will return an instance of the correct ACL class. * Constructor. Will return an instance of the correct ACL class.
* *
*/ */
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.
* *
* @return MyACL * @return MyACL
*/ */
function &getACL() function &getACL()
{ {
if($this->_instance == null) if($this->_instance == null)
{ {
uses('controller'.DS.'components'.DS.ACL_FILENAME); uses('controller'.DS.'components'.DS.ACL_FILENAME);
@ -67,26 +67,26 @@ class AclComponent extends Object
$this->_instance = new $classname; $this->_instance = new $classname;
} }
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.
* *
* @return boolean * @return boolean
*/ */
function check($aro, $aco, $action = "*") function check($aro, $aco, $action = "*")
{ {
return $this->_instance->check($aro, $aco, $action); return $this->_instance->check($aro, $aco, $action);
} }
/** /**
@ -94,50 +94,50 @@ class AclComponent extends Object
* *
* @return boolean * @return boolean
*/ */
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.
* *
* @return boolean * @return boolean
*/ */
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.
* *
* @return boolean * @return boolean
*/ */
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.
* *
* @return boolean * @return boolean
*/ */
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.
* *
* @return boolean * @return boolean
*/ */
function revoke($aro, $aco, $action = "*") function revoke($aro, $aco, $action = "*")
{ {
return $this->_instance->revoke($aro, $aco, $action); return $this->_instance->revoke($aro, $aco, $action);
} }
/** /**
@ -145,10 +145,10 @@ class AclComponent extends Object
* *
* @return Aro * @return Aro
*/ */
function getAro($id) function getAro($id)
{ {
return $this->_instance->getAro($id); return $this->_instance->getAro($id);
} }
/** /**
@ -156,10 +156,10 @@ class AclComponent extends Object
* *
* @return Aco * @return Aco
*/ */
function getAco($id) function getAco($id)
{ {
return $this->_instance->getAco($id); return $this->_instance->getAco($id);
} }
} }

View file

@ -45,16 +45,16 @@ class AclBase
* *
* @return AclBase * @return AclBase
*/ */
function AclBase() function AclBase()
{ {
//No instantiations or constructor calls (even statically) //No instantiations or constructor calls (even statically)
if (strcasecmp(get_class($this), "AclBase") == 0 || !is_subclass_of($this, "AclBase")) if (strcasecmp(get_class($this), "AclBase") == 0 || !is_subclass_of($this, "AclBase"))
{ {
trigger_error(__("[acl_base] The AclBase class constructor has been called, or the class was instantiated. This class must remain abstract. Please refer to the Cake docs for ACL configuration."), E_USER_ERROR); trigger_error(__("[acl_base] The AclBase class constructor has been called, or the class was instantiated. This class must remain abstract. Please refer to the Cake docs for ACL configuration."), E_USER_ERROR);
return NULL; return NULL;
} }
} }
/** /**
* Empty method to be overridden in subclasses * Empty method to be overridden in subclasses
@ -63,7 +63,7 @@ class AclBase
* @param unknown_type $aco * @param unknown_type $aco
* @param string $action * @param string $action
*/ */
function check($aro, $aco, $action = "*") {} function check($aro, $aco, $action = "*") {}
} }

View file

@ -49,10 +49,10 @@ class DB_ACL extends AclBase
* Enter description here... * Enter description here...
* *
*/ */
function __construct() function __construct()
{ {
} }
/** /**
* Enter description here... * Enter description here...
@ -62,8 +62,8 @@ class DB_ACL extends AclBase
* @param unknown_type $action * @param unknown_type $action
* @return unknown * @return unknown
*/ */
function check($aro, $aco, $action = "*") function check($aro, $aco, $action = "*")
{ {
$Perms = new ArosAco(); $Perms = new ArosAco();
$Aro = new Aro(); $Aro = new Aro();
@ -101,9 +101,9 @@ class DB_ACL extends AclBase
{ {
foreach($perms as $perm) foreach($perms as $perm)
{ {
if($action == '*') if($action == '*')
{ {
// ARO must be cleared for ALL ACO actions // ARO must be cleared for ALL ACO actions
foreach($permKeys as $key) foreach($permKeys as $key)
{ {
if(isset($perm['aros_acos'])) if(isset($perm['aros_acos']))
@ -115,9 +115,9 @@ class DB_ACL extends AclBase
} }
} }
return true; return true;
} }
else else
{ {
switch($perm['aros_acos']['_' . $action]) switch($perm['aros_acos']['_' . $action])
{ {
case -1: case -1:
@ -128,21 +128,21 @@ class DB_ACL extends AclBase
case 1: case 1:
return true; return true;
} }
} }
} }
} }
} }
return false; return false;
} }
/** /**
* Allow * Allow
* *
* @return boolean * @return boolean
*/ */
function allow($aro, $aco, $action = "*", $value = 1) function allow($aro, $aco, $action = "*", $value = 1)
{ {
$Perms = new ArosAco(); $Perms = new ArosAco();
$perms = $this->getAclLink($aro, $aco); $perms = $this->getAclLink($aro, $aco);
$permKeys = $this->_getAcoKeys($Perms->loadInfo()); $permKeys = $this->_getAcoKeys($Perms->loadInfo());
@ -151,7 +151,7 @@ class DB_ACL extends AclBase
if($perms == false) if($perms == false)
{ {
// One of the nodes does not exist // One of the nodes does not exist
return false; return false;
} }
@ -176,7 +176,7 @@ class DB_ACL extends AclBase
} }
else else
{ {
// Raise an error // Raise an error
return false; return false;
} }
} }
@ -188,7 +188,7 @@ class DB_ACL extends AclBase
{ {
$save['id'] = $perms['link'][0]['aros_acos']['id']; $save['id'] = $perms['link'][0]['aros_acos']['id'];
} }
//return $Perms->save(array('ArosAco' => $save)); //return $Perms->save(array('ArosAco' => $save));
if(isset($save['id'])) if(isset($save['id']))
{ {
@ -198,7 +198,7 @@ class DB_ACL extends AclBase
{ {
if($key != 'id') if($key != 'id')
{ {
$saveKeys[] = $key . ' = ' . $val; $saveKeys[] = $key . ' = ' . $val;
} }
} }
$q .= implode(', ', $saveKeys) . ' where id = ' . $save['id']; $q .= implode(', ', $saveKeys) . ' where id = ' . $save['id'];
@ -210,47 +210,47 @@ class DB_ACL extends AclBase
$Perms->db->query($q); $Perms->db->query($q);
return true; return true;
} }
/** /**
* Deny * Deny
* *
* @return boolean * @return boolean
*/ */
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
* *
* @return boolean * @return boolean
*/ */
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
* *
* @return boolean * @return boolean
*/ */
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
* *
* @return boolean * @return boolean
*/ */
function revoke($aro, $aco, $action = "*") function revoke($aro, $aco, $action = "*")
{ {
return $this->deny($aro, $aco, $action); return $this->deny($aro, $aco, $action);
} }
@ -260,17 +260,17 @@ class DB_ACL extends AclBase
* @param unknown_type $id * @param unknown_type $id
* @return unknown * @return unknown
*/ */
function getAro($id = null) function getAro($id = null)
{ {
if($id == null) if($id == null)
{ {
// Raise error // Raise error
} }
$aro = new Aro(); $aro = new Aro();
$tmp = $aro->find(is_string($aro) ? "aros.alias = '" . addslashes($aro) . "'" : "aros.user_id = {$aro}"); $tmp = $aro->find(is_string($aro) ? "aros.alias = '" . addslashes($aro) . "'" : "aros.user_id = {$aro}");
$aro->setId($tmp['aro']['id']); $aro->setId($tmp['aro']['id']);
return $aro; return $aro;
} }
/** /**
@ -279,17 +279,17 @@ class DB_ACL extends AclBase
* @param unknown_type $id * @param unknown_type $id
* @return unknown * @return unknown
*/ */
function getAco($id = null) function getAco($id = null)
{ {
if($id == null) if($id == null)
{ {
// Raise error // Raise error
} }
$aco = new Aco(); $aco = new Aco();
$tmp = $aco->find(is_string($aco) ? "acos.alias = '" . addslashes($aco) . "'" : "acos.user_id = {$aco}"); $tmp = $aco->find(is_string($aco) ? "acos.alias = '" . addslashes($aco) . "'" : "acos.user_id = {$aco}");
$aro->setId($tmp['aco']['id']); $aro->setId($tmp['aco']['id']);
return $aco; return $aco;
} }
/** /**
@ -299,12 +299,12 @@ class DB_ACL extends AclBase
* @param unknown_type $aco * @param unknown_type $aco
* @return unknown * @return unknown
*/ */
function getAclLink($aro, $aco) function getAclLink($aro, $aco)
{ {
$Aro = new Aro(); $Aro = new Aro();
$Aco = new Aco(); $Aco = new Aco();
$qAro = (is_string($aro) ? "alias = '" . addslashes($aro) . "'" : "user_id = {$aro}"); $qAro = (is_string($aro) ? "alias = '" . addslashes($aro) . "'" : "user_id = {$aro}");
$qAco = (is_string($aco) ? "alias = '" . addslashes($aco) . "'" : "object_id = {$aco}"); $qAco = (is_string($aco) ? "alias = '" . addslashes($aco) . "'" : "object_id = {$aco}");
$obj = array(); $obj = array();
@ -323,7 +323,7 @@ class DB_ACL extends AclBase
'aco' => $obj['Aco']['id'], 'aco' => $obj['Aco']['id'],
'link' => $Aro->findBySql("select * from aros_acos where aro_id = {$obj['Aro']['id']} and aco_id = {$obj['Aco']['id']}") 'link' => $Aro->findBySql("select * from aros_acos where aro_id = {$obj['Aro']['id']} and aco_id = {$obj['Aco']['id']}")
); );
} }
/** /**
* Enter description here... * Enter description here...
@ -331,8 +331,8 @@ class DB_ACL extends AclBase
* @param unknown_type $keys * @param unknown_type $keys
* @return unknown * @return unknown
*/ */
function _getAcoKeys($keys) function _getAcoKeys($keys)
{ {
$newKeys = array(); $newKeys = array();
$keys = $keys->value; $keys = $keys->value;
foreach($keys as $key) foreach($keys as $key)
@ -343,7 +343,7 @@ class DB_ACL extends AclBase
} }
} }
return $newKeys; return $newKeys;
} }
} }

View file

@ -46,11 +46,11 @@ class AclNode extends AppModel
* Enter description here... * Enter description here...
* *
*/ */
function __construct() function __construct()
{ {
$this->setSource(); $this->setSource();
parent::__construct(); parent::__construct();
} }
/** /**
* Enter description here... * Enter description here...
@ -60,8 +60,8 @@ class AclNode extends AppModel
* @param unknown_type $alias * @param unknown_type $alias
* @return unknown * @return unknown
*/ */
function create($link_id = 0, $parent_id = null, $alias = '') function create($link_id = 0, $parent_id = null, $alias = '')
{ {
parent::create(); parent::create();
if (strtolower(get_class($this)) == "aclnode") if (strtolower(get_class($this)) == "aclnode")
@ -78,7 +78,7 @@ class AclNode extends AppModel
if($parent[0]['MAX(rght)'] == null) if($parent[0]['MAX(rght)'] == null)
{ {
// The tree is empty // The tree is empty
$parent['lft'] = 0; $parent['lft'] = 0;
} }
} }
@ -96,14 +96,14 @@ class AclNode extends AppModel
$return = $this->save(array($class => array( $return = $this->save(array($class => array(
$secondary_id => $link_id, $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->setId($this->getLastInsertID()); $this->setId($this->getLastInsertID());
return $return; return $return;
} }
/** /**
@ -113,8 +113,8 @@ class AclNode extends AppModel
* @param unknown_type $id * @param unknown_type $id
* @return unknown * @return unknown
*/ */
function setParent($parent_id = null, $id = null) function setParent($parent_id = null, $id = null)
{ {
if (strtolower(get_class($this)) == "aclnode") if (strtolower(get_class($this)) == "aclnode")
{ {
trigger_error(__("[acl_base] The AclBase class constructor has been called, or the class was instantiated. This class must remain abstract. Please refer to the Cake docs for ACL configuration."), E_USER_ERROR); trigger_error(__("[acl_base] The AclBase class constructor has been called, or the class was instantiated. This class must remain abstract. Please refer to the Cake docs for ACL configuration."), E_USER_ERROR);
@ -134,12 +134,12 @@ class AclNode extends AppModel
$object = $this->find($this->_resolveID($id, $secondary_id)); $object = $this->find($this->_resolveID($id, $secondary_id));
if($object == null || count($object) == 0) if($object == null || count($object) == 0)
{ {
// Couldn't find object // Couldn't find object
return false; return false;
} }
$parent = $this->getParent(intval($object[$class][$secondary_id])); $parent = $this->getParent(intval($object[$class][$secondary_id]));
// Node is already at root, or new parent == old parent // Node is already at root, or new parent == old parent
if(($parent == null && $parent_id == null) || ($parent_id == $parent[$class][$secondary_id]) || ($parent_id == $parent[$class]['alias'])) if(($parent == null && $parent_id == null) || ($parent_id == $parent[$class][$secondary_id]) || ($parent_id == $parent[$class]['alias']))
{ {
return false; return false;
@ -147,7 +147,7 @@ class AclNode extends AppModel
if($parent_id != null && $parent[$class]['lft'] <= $object[$class]['lft'] && $parent[$class]['rght'] >= $object[$class]['rght']) if($parent_id != null && $parent[$class]['lft'] <= $object[$class]['lft'] && $parent[$class]['rght'] >= $object[$class]['rght'])
{ {
// Can't move object inside self or own child // Can't move object inside self or own child
return false; return false;
} }
$this->_syncTable($table_name, 0, $object[$class]['lft'], $object[$class]['lft']); $this->_syncTable($table_name, 0, $object[$class]['lft'], $object[$class]['lft']);
@ -173,7 +173,7 @@ class AclNode extends AppModel
$this->_syncTable($table_name, 2, $parent['lft'], $parent['lft']); $this->_syncTable($table_name, 2, $parent['lft'], $parent['lft']);
} }
} }
/** /**
@ -182,8 +182,8 @@ class AclNode extends AppModel
* @param unknown_type $id * @param unknown_type $id
* @return unknown * @return unknown
*/ */
function getParent($id) function getParent($id)
{ {
$path = $this->getPath($id); $path = $this->getPath($id);
if($path == null || count($path) < 2) if($path == null || count($path) < 2)
{ {
@ -193,7 +193,7 @@ class AclNode extends AppModel
{ {
return $path[count($path) - 2]; return $path[count($path) - 2];
} }
} }
/** /**
* Enter description here... * Enter description here...
@ -201,8 +201,8 @@ class AclNode extends AppModel
* @param unknown_type $id * @param unknown_type $id
* @return unknown * @return unknown
*/ */
function getPath($id) function getPath($id)
{ {
if (strtolower(get_class($this)) == "aclnode") if (strtolower(get_class($this)) == "aclnode")
{ {
trigger_error(__("[acl_base] The AclBase class constructor has been called, or the class was instantiated. This class must remain abstract. Please refer to the Cake docs for ACL configuration."), E_USER_ERROR); trigger_error(__("[acl_base] The AclBase class constructor has been called, or the class was instantiated. This class must remain abstract. Please refer to the Cake docs for ACL configuration."), E_USER_ERROR);
@ -216,7 +216,7 @@ class AclNode extends AppModel
return null; return null;
} }
return $this->findAll("{$data_name}.lft <= {$item[$class]['lft']} and {$data_name}.rght >= {$item[$class]['rght']}"); return $this->findAll("{$data_name}.lft <= {$item[$class]['lft']} and {$data_name}.rght >= {$item[$class]['rght']}");
} }
/** /**
* Enter description here... * Enter description here...
@ -224,8 +224,8 @@ class AclNode extends AppModel
* @param unknown_type $id * @param unknown_type $id
* @return unknown * @return unknown
*/ */
function getChildren($id) function getChildren($id)
{ {
if (strtolower(get_class($this)) == "aclnode") if (strtolower(get_class($this)) == "aclnode")
{ {
trigger_error(__("[acl_base] The AclBase class constructor has been called, or the class was instantiated. This class must remain abstract. Please refer to the Cake docs for ACL configuration."), E_USER_ERROR); trigger_error(__("[acl_base] The AclBase class constructor has been called, or the class was instantiated. This class must remain abstract. Please refer to the Cake docs for ACL configuration."), E_USER_ERROR);
@ -235,7 +235,7 @@ class AclNode extends AppModel
$item = $this->find($this->_resolveID($id, $secondary_id)); $item = $this->find($this->_resolveID($id, $secondary_id));
return $this->findAll("{$data_name}.lft > {$item[$class]['lft']} and {$data_name}.rght < {$item[$class]['rght']}"); return $this->findAll("{$data_name}.lft > {$item[$class]['lft']} and {$data_name}.rght < {$item[$class]['rght']}");
} }
/** /**
* Enter description here... * Enter description here...
@ -244,12 +244,12 @@ class AclNode extends AppModel
* @param unknown_type $fKey * @param unknown_type $fKey
* @return unknown * @return unknown
*/ */
function _resolveID($id, $fKey) function _resolveID($id, $fKey)
{ {
$key = (is_string($id) ? 'alias' : $fKey); $key = (is_string($id) ? 'alias' : $fKey);
$val = (is_string($id) ? '"' . addslashes($id) . '"' : $id); $val = (is_string($id) ? '"' . addslashes($id) . '"' : $id);
return "{$key} = {$val}"; return "{$key} = {$val}";
} }
/** /**
* Enter description here... * Enter description here...
@ -259,37 +259,37 @@ class AclNode extends AppModel
* @param unknown_type $lft * @param unknown_type $lft
* @param unknown_type $rght * @param unknown_type $rght
*/ */
function _syncTable($table, $dir, $lft, $rght) function _syncTable($table, $dir, $lft, $rght)
{ {
$shift = ($dir == 2 ? 1 : 2); $shift = ($dir == 2 ? 1 : 2);
$this->db->query("UPDATE $table SET rght = rght " . ($dir > 0 ? "+" : "-") . " {$shift} WHERE rght > " . $rght); $this->db->query("UPDATE $table SET rght = rght " . ($dir > 0 ? "+" : "-") . " {$shift} WHERE rght > " . $rght);
$this->db->query("UPDATE $table SET lft = lft " . ($dir > 0 ? "+" : "-") . " {$shift} WHERE lft > " . $lft); $this->db->query("UPDATE $table SET lft = lft " . ($dir > 0 ? "+" : "-") . " {$shift} WHERE lft > " . $lft);
} }
/** /**
* Enter description here... * Enter description here...
* *
* @return unknown * @return unknown
*/ */
function __dataVars() function __dataVars()
{ {
$vars = array(); $vars = array();
$class = Inflector::camelize(strtolower(get_class($this))); $class = Inflector::camelize(strtolower(get_class($this)));
$vars['secondary_id'] = (strtolower($class) == 'aro' ? 'user_id' : 'object_id'); $vars['secondary_id'] = (strtolower($class) == 'aro' ? 'user_id' : 'object_id');
$vars['data_name'] = $class; $vars['data_name'] = $class;
$vars['table_name'] = strtolower($class) . 's'; $vars['table_name'] = strtolower($class) . 's';
$vars['class'] = Inflector::camelize($class); $vars['class'] = Inflector::camelize($class);
return $vars; return $vars;
} }
/** /**
* Enter description here... * Enter description here...
* *
*/ */
function setSource() function setSource()
{ {
$this->table = low(get_class($this)) . "s"; $this->table = low(get_class($this)) . "s";
} }
} }
?> ?>

View file

@ -40,13 +40,13 @@
*/ */
class Aco extends AclNode class Aco extends AclNode
{ {
var $name = 'Aco'; var $name = 'Aco';
/** /**
* Enter description here... * Enter description here...
* *
* @var unknown_type * @var unknown_type
*/ */
var $hasMany = 'ArosAco'; var $hasMany = 'ArosAco';
} }

View file

@ -52,7 +52,7 @@ class AcoAction extends AppModel
* *
* @var unknown_type * @var unknown_type
*/ */
var $belongsTo = 'Aco'; var $belongsTo = 'Aco';
} }
?> ?>

View file

@ -47,19 +47,19 @@ class ArosAco extends AppModel
* *
* @var unknown_type * @var unknown_type
*/ */
var $name = 'ArosAco'; var $name = 'ArosAco';
/** /**
* Enter description here... * Enter description here...
* *
* @var unknown_type * @var unknown_type
*/ */
var $useTable = 'aros_acos'; var $useTable = 'aros_acos';
/** /**
* Enter description here... * Enter description here...
* *
* @var unknown_type * @var unknown_type
*/ */
var $belongsTo = 'Aro,Aco'; var $belongsTo = 'Aro,Aco';
} }
?> ?>

View file

@ -43,152 +43,152 @@ class INI_ACL extends AclBase
* The constructor must be overridden, as AclBase is abstract. * The constructor must be overridden, as AclBase is abstract.
* *
*/ */
function __construct() function __construct()
{ {
} }
/** /**
* Main ACL check function. Checks to see if the ARO (access request object) has access to the ACO (access control object). * Main ACL check function. Checks to see if the ARO (access request object) has access to the ACO (access control object).
* Looks at the acl.ini.php file for permissions (see instructions in /config/acl.ini.php). * Looks at the acl.ini.php file for permissions (see instructions in/config/acl.ini.php).
* *
* @param string $aro * @param string $aro
* @param string $aco * @param string $aco
* @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'); $aclConfig = $this->readConfigFile(CONFIGS . 'acl.ini.php');
//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']))
{ {
$userDenies = $this->arrayTrim(explode(",", $aclConfig[$aro]['deny'])); $userDenies = $this->arrayTrim(explode(",", $aclConfig[$aro]['deny']));
if (array_search($aco, $userDenies)) if (array_search($aco, $userDenies))
{ {
//echo "User Denied!"; //echo "User Denied!";
return false; return false;
} }
} }
//Second, if the user is specifically allowed, then ALLOW //Second, if the user is specifically allowed, then ALLOW
if(isset($aclConfig[$aro]['allow'])) if(isset($aclConfig[$aro]['allow']))
{ {
$userAllows = $this->arrayTrim(explode(",", $aclConfig[$aro]['allow'])); $userAllows = $this->arrayTrim(explode(",", $aclConfig[$aro]['allow']));
if (array_search($aco, $userAllows)) if (array_search($aco, $userAllows))
{ {
//echo "User Allowed!"; //echo "User Allowed!";
return true; return true;
} }
} }
//Check group permissions //Check group permissions
if (isset($aclConfig[$aro]['groups'])) if (isset($aclConfig[$aro]['groups']))
{ {
$userGroups = $this->arrayTrim(explode(",", $aclConfig[$aro]['groups'])); $userGroups = $this->arrayTrim(explode(",", $aclConfig[$aro]['groups']));
foreach ($userGroups as $group) foreach ($userGroups as $group)
{ {
//If such a group exists, //If such a group exists,
if(array_key_exists($group, $aclConfig)) if(array_key_exists($group, $aclConfig))
{ {
//If the group is specifically denied, then DENY //If the group is specifically denied, then DENY
if(isset($aclConfig[$group]['deny'])) if(isset($aclConfig[$group]['deny']))
{ {
$groupDenies = $this->arrayTrim(explode(",", $aclConfig[$group]['deny'])); $groupDenies = $this->arrayTrim(explode(",", $aclConfig[$group]['deny']));
if (array_search($aco, $groupDenies)) if (array_search($aco, $groupDenies))
{ {
//echo("Group Denied!"); //echo("Group Denied!");
return false; return false;
} }
} }
//If the group is specifically allowed, then ALLOW //If the group is specifically allowed, then ALLOW
if(isset($aclConfig[$group]['allow'])) if(isset($aclConfig[$group]['allow']))
{ {
$groupAllows = $this->arrayTrim(explode(",", $aclConfig[$group]['allow'])); $groupAllows = $this->arrayTrim(explode(",", $aclConfig[$group]['allow']));
if (array_search($aco, $groupAllows)) if (array_search($aco, $groupAllows))
{ {
//echo("Group Allowed!"); //echo("Group Allowed!");
return true; return true;
} }
} }
} }
} }
} }
//Default, DENY //Default, DENY
//echo("DEFAULT: DENY."); //echo("DEFAULT: DENY.");
return false; return false;
} }
/** /**
* Parses an INI file and returns an array that reflects the INI file's section structure. Double-quote friendly. * Parses an INI file and returns an array that reflects the INI file's section structure. Double-quote friendly.
* *
* @param string $fileName * @param string $fileName
* @return array * @return array
*/ */
function readConfigFile ($fileName) function readConfigFile ($fileName)
{ {
$fileLineArray = file($fileName); $fileLineArray = file($fileName);
foreach ($fileLineArray as $fileLine) foreach ($fileLineArray as $fileLine)
{ {
$dataLine = trim($fileLine); $dataLine = trim($fileLine);
$firstChar = substr($dataLine, 0, 1); $firstChar = substr($dataLine, 0, 1);
if ($firstChar != ';' && $dataLine != '') if ($firstChar != ';' && $dataLine != '')
{ {
if ($firstChar == '[' && substr($dataLine, -1, 1) == ']') if ($firstChar == '[' && substr($dataLine, -1, 1) == ']')
{ {
$sectionName = preg_replace('/[\[\]]/', '', $dataLine); $sectionName = preg_replace('/[\[\]]/', '', $dataLine);
} }
else else
{ {
$delimiter = strpos($dataLine, '='); $delimiter = strpos($dataLine, '=');
if ($delimiter > 0) if ($delimiter > 0)
{ {
$key = strtolower(trim(substr($dataLine, 0, $delimiter))); $key = strtolower(trim(substr($dataLine, 0, $delimiter)));
$value = trim(substr($dataLine, $delimiter + 1)); $value = trim(substr($dataLine, $delimiter + 1));
if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') if (substr($value, 0, 1) == '"' && substr($value, -1) == '"')
{ {
$value = substr($value, 1, -1); $value = substr($value, 1, -1);
} }
$iniSetting[$sectionName][$key] = stripcslashes($value); $iniSetting[$sectionName][$key] = stripcslashes($value);
} }
else else
{ {
if(!isset($sectionName)) if(!isset($sectionName))
{ {
$sectionName = ''; $sectionName = '';
} }
$iniSetting[$sectionName][strtolower(trim($dataLine))]=''; $iniSetting[$sectionName][strtolower(trim($dataLine))]='';
} }
} }
} }
else else
{ {
} }
} }
return $iniSetting; return $iniSetting;
} }
/** /**
* Removes trailing spaces on all array elements (to prepare for searching) * Removes trailing spaces on all array elements (to prepare for searching)
* *
* @param array $array * @param array $array
* @return array * @return array
*/ */
function arrayTrim($array) function arrayTrim($array)
{ {
foreach($array as $element) { foreach($array as $element) {
$element = trim($element); $element = trim($element);
} }
//Adding this element keeps array_search from returning 0: //Adding this element keeps array_search from returning 0:
//0 is the first key, which may be correct, but 0 is interpreted as false. //0 is the first key, which may be correct, but 0 is interpreted as false.
//Adding this element makes all the keys be positive integers. //Adding this element makes all the keys be positive integers.
array_unshift($array, ""); array_unshift($array, "");
return $array; return $array;
} }
} }

View file

@ -73,7 +73,7 @@ class RequestHandlerComponent extends Object
{ {
$controller->layout = $this->ajaxLayout; $controller->layout = $this->ajaxLayout;
// Add UTF-8 header for IE6 on XPsp2 bug // Add UTF-8 header for IE6 on XPsp2 bug
header('Content-Type: text/html; charset=UTF-8'); header('Content-Type: text/html; charset=UTF-8');
} }
} }

View file

@ -246,7 +246,7 @@ class Controller extends Object
elseif($this->uses === false) elseif($this->uses === false)
{ {
return $this->cakeError('missingModel',array(array('className' => $this->modelClass, return $this->cakeError('missingModel',array(array('className' => $this->modelClass,
'webroot' => ''))); 'webroot' => '')));
} }
if ($this->uses) if ($this->uses)
{ {
@ -264,7 +264,7 @@ class Controller extends Object
else else
{ {
return $this->cakeError('missingModel',array(array('className' => $modelClass, return $this->cakeError('missingModel',array(array('className' => $modelClass,
'webroot' => ''))); 'webroot' => '')));
} }
} }
} }
@ -518,7 +518,7 @@ class Controller extends Object
* @param string $url Relative URL to redirect to after the time expires * @param string $url Relative URL to redirect to after the time expires
* @param int $time Time to show the message * @param int $time Time to show the message
*/ */
function flash($message, $url, $pause=1) function flash($message, $url, $pause = 1)
{ {
$this->autoRender = false; $this->autoRender = false;
$this->autoLayout = false; $this->autoLayout = false;
@ -532,14 +532,11 @@ class Controller extends Object
{ {
$flash = VIEWS.'layouts'.DS.'flash.thtml'; $flash = VIEWS.'layouts'.DS.'flash.thtml';
} }
else if(file_exists(LIBS.'view'.DS.'templates'.DS."layouts".DS.'flash.thtml')) elseif($flash = fileExistsInPath(LIBS.'view'.DS.'templates'.DS."layouts".DS.'flash.thtml'))
{ {
$flash = LIBS.'view'.DS.'templates'.DS."layouts".DS.'flash.thtml';
} }
$this->render(null, false, $flash);
$this->render(null,false,$flash);
} }
/** /**
@ -563,7 +560,7 @@ class Controller extends Object
$this->set('message', $message); $this->set('message', $message);
$this->set('time', $time); $this->set('time', $time);
$this->render(null,false,VIEWS.'layouts'.DS.'flash.thtml'); $this->render(null, false, VIEWS.'layouts'.DS.'flash.thtml');
} }
/** /**

View file

@ -49,35 +49,35 @@ class PagesController extends AppController{
* *
* @var unknown_type * @var unknown_type
*/ */
var $helpers = array('Html'); var $helpers = array('Html');
/** /**
* This controller does not use a model * This controller does not use a model
* *
* @var $uses * @var $uses
*/ */
var $uses = null; var $uses = null;
/** /**
* Displays a view * Displays a view
* *
*/ */
function display() function display()
{ {
if (!func_num_args()) if (!func_num_args())
{ {
$this->redirect('/'); $this->redirect('/');
} }
$path = func_get_args(); $path = func_get_args();
if (!count($path)) if (!count($path))
{ {
$this->redirect('/'); $this->redirect('/');
} }
$this->set('page', $path[0]); $this->set('page', $path[0]);
$this->set('subpage', empty($path[1])? null: $path[1]); $this->set('subpage', empty($path[1])? null: $path[1]);
$this->set('title', ucfirst($path[count($path)-1])); $this->set('title', ucfirst($path[count($path)-1]));
$this->render(join('/', $path)); $this->render(join('/', $path));
} }
} }
?> ?>

View file

@ -329,7 +329,7 @@ class Scaffold extends Object {
} }
else else
{ {
return $this->controllerClass->flash('There was an error deleting the '.Inflector::humanize($this->modelKey).' with the id '. return $this->controllerClass->flash('There was an error deleting the '.Inflector::humanize($this->modelKey).' with the id '.
$id, '/'.Inflector::underscore($this->controllerClass->viewPath)); $id, '/'.Inflector::underscore($this->controllerClass->viewPath));
} }
} }
@ -360,52 +360,52 @@ class Scaffold extends Object {
if(isset($this->controllerClass->{$this->modelKey}->db)) if(isset($this->controllerClass->{$this->modelKey}->db))
{ {
if($params['action'] === 'index' || $params['action'] === 'list' || if($params['action'] === 'index' || $params['action'] === 'list' ||
$params['action'] === 'show' || $params['action'] === 'add' || $params['action'] === 'show' || $params['action'] === 'add' ||
$params['action'] === 'create' || $params['action'] === 'edit' || $params['action'] === 'create' || $params['action'] === 'edit' ||
$params['action'] === 'update' || $params['action'] === 'destroy') $params['action'] === 'update' || $params['action'] === 'destroy')
{ {
switch ($params['action']) switch ($params['action'])
{ {
case 'index': case 'index':
$this->_scaffoldIndex($params); $this->_scaffoldIndex($params);
break; break;
case 'show': case 'show':
$this->_scaffoldShow($params); $this->_scaffoldShow($params);
break; break;
case 'list': case 'list':
$this->_scaffoldList($params); $this->_scaffoldList($params);
break; break;
case 'add': case 'add':
$this->_scaffoldNew($params); $this->_scaffoldNew($params);
break; break;
case 'edit': case 'edit':
$this->_scaffoldEdit($params); $this->_scaffoldEdit($params);
break; break;
case 'create': case 'create':
$this->_scaffoldCreate($params); $this->_scaffoldCreate($params);
break; break;
case 'update': case 'update':
$this->_scaffoldUpdate($params); $this->_scaffoldUpdate($params);
break; break;
case 'destroy': case 'destroy':
$this->_scaffoldDestroy($params); $this->_scaffoldDestroy($params);
break; break;
} }
} }
else else
{ {
return $this->cakeError('missingAction', return $this->cakeError('missingAction',
array(array('className' => Inflector::camelize($params['controller']."Controller"), array(array('className' => Inflector::camelize($params['controller']."Controller"),
'action' => $params['action'], 'action' => $params['action'],
'webroot' => $this->controllerClass->webroot))); 'webroot' => $this->controllerClass->webroot)));
} }
} }
else else
{ {

View file

@ -55,14 +55,14 @@ class File extends Object
* *
* @var Folder * @var Folder
*/ */
var $folder = null; var $folder = null;
/** /**
* Filename * Filename
* *
* @var string * @var string
*/ */
var $name = null; var $name = null;
/** /**
* Constructor * Constructor
@ -71,8 +71,8 @@ class File extends Object
* @param boolean $create Create file if it does not exist * @param boolean $create Create file if it does not exist
* @return File * @return File
*/ */
function __construct ($path, $create = false) function __construct ($path, $create = false)
{ {
parent::__construct(); parent::__construct();
$this->folder = new Folder(dirname($path), $create); $this->folder = new Folder(dirname($path), $create);
@ -84,7 +84,7 @@ class File extends Object
{ {
if (!$this->create()) if (!$this->create())
{ {
return false; return false;
} }
} }
else else
@ -92,17 +92,17 @@ class File extends Object
return false; return false;
} }
} }
} }
/** /**
* Return the contents of this File as a string. * Return the contents of this File as a string.
* *
* @return string Contents * @return string Contents
*/ */
function read () function read ()
{ {
return file_get_contents($this->getFullPath()); return file_get_contents($this->getFullPath());
} }
/** /**
* Append given data string to this File. * Append given data string to this File.
@ -110,10 +110,10 @@ class File extends Object
* @param string $data Data to write * @param string $data Data to write
* @return boolean Success * @return boolean Success
*/ */
function append ($data) function append ($data)
{ {
return $this->write($data, 'a'); return $this->write($data, 'a');
} }
/** /**
* Write given data to this File. * Write given data to this File.
@ -122,8 +122,8 @@ class File extends Object
* @param string $mode Mode of writing. {@link http://php.net/fwrite See fwrite()}. * @param string $mode Mode of writing. {@link http://php.net/fwrite See fwrite()}.
* @return boolean Success * @return boolean Success
*/ */
function write ($data, $mode = 'w') function write ($data, $mode = 'w')
{ {
$file = $this->getFullPath(); $file = $this->getFullPath();
if (!($handle = fopen( $file , $mode))) if (!($handle = fopen( $file , $mode)))
{ {
@ -138,7 +138,7 @@ class File extends Object
return false; return false;
return true; return true;
} }
/** /**
* Get md5 Checksum of file with previous check of Filesize * Get md5 Checksum of file with previous check of Filesize
@ -146,8 +146,8 @@ class File extends Object
* @param string $force Data to write to this File. * @param string $force Data to write to this File.
* @return string md5 Checksum {@link http://php.net/md5_file See md5_file()} * @return string md5 Checksum {@link http://php.net/md5_file See md5_file()}
*/ */
function getMd5 ($force = false) function getMd5 ($force = false)
{ {
$md5 = ''; $md5 = '';
if ( $force == true || $this->getSize(false) < MAX_MD5SIZE ) if ( $force == true || $this->getSize(false) < MAX_MD5SIZE )
{ {
@ -155,7 +155,7 @@ class File extends Object
} }
return $md5; return $md5;
} }
/** /**
* Returns the Filesize, either in bytes or in human-readable format. * Returns the Filesize, either in bytes or in human-readable format.
@ -163,19 +163,19 @@ class File extends Object
* @param boolean $humanReadeble Data to write to this File. * @param boolean $humanReadeble Data to write to this File.
* @return string|int filesize as int or as a human-readable string * @return string|int filesize as int or as a human-readable string
*/ */
function getSize () function getSize ()
{ {
$size = filesize( $this->getFullPath() ); $size = filesize( $this->getFullPath() );
return $size; return $size;
} }
/** /**
* Returns the File extension. * Returns the File extension.
* *
* @return string The Fileextension * @return string The Fileextension
*/ */
function getExt () function getExt ()
{ {
$ext = ''; $ext = '';
$parts = explode('.', $this->getName() ); $parts = explode('.', $this->getName() );
@ -190,45 +190,45 @@ class File extends Object
} }
return $ext; return $ext;
} }
/** /**
* Returns the filename. * Returns the filename.
* *
* @return string The Filename * @return string The Filename
*/ */
function getName () function getName ()
{ {
return $this->name; return $this->name;
} }
/** /**
* Returns the File's owner. * Returns the File's owner.
* *
* @return int the Fileowner * @return int the Fileowner
*/ */
function getOwner () function getOwner ()
{ {
return fileowner( $this->getFullPath() ); return fileowner( $this->getFullPath() );
} }
/** /**
* Returns the File group. * Returns the File group.
* *
* @return int the Filegroup * @return int the Filegroup
*/ */
function getGroup () function getGroup ()
{ {
return filegroup( $this->getFullPath() ); return filegroup( $this->getFullPath() );
} }
/** /**
* Creates the File. * Creates the File.
* *
* @return boolean Success * @return boolean Success
*/ */
function create () function create ()
{ {
$dir = $this->folder->pwd(); $dir = $this->folder->pwd();
if ( file_exists( $dir ) && is_dir($dir) && is_writable($dir) && !$this->exists() ) if ( file_exists( $dir ) && is_dir($dir) && is_writable($dir) && !$this->exists() )
{ {
@ -247,107 +247,107 @@ class File extends Object
print ("[File] Could not create $this->getName()!"); print ("[File] Could not create $this->getName()!");
return false; return false;
} }
} }
/** /**
* Returns true if the File exists. * Returns true if the File exists.
* *
* @return boolean * @return boolean
*/ */
function exists () function exists ()
{ {
return file_exists( $this->getFullPath() ); return file_exists( $this->getFullPath() );
} }
/** /**
* Deletes the File. * Deletes the File.
* *
* @return boolean * @return boolean
*/ */
function delete () function delete ()
{ {
return unlink( $this->getFullPath() ); return unlink( $this->getFullPath() );
} }
/** /**
* Returns true if the File is writable. * Returns true if the File is writable.
* *
* @return boolean * @return boolean
*/ */
function writable () function writable ()
{ {
return is_writable( $this->getFullPath() ); return is_writable( $this->getFullPath() );
} }
/** /**
* Returns true if the File is executable. * Returns true if the File is executable.
* *
* @return boolean * @return boolean
*/ */
function executable () function executable ()
{ {
return is_executable( $this->getFullPath() ); return is_executable( $this->getFullPath() );
} }
/** /**
* Returns true if the File is readable. * Returns true if the File is readable.
* *
* @return boolean * @return boolean
*/ */
function readable () function readable ()
{ {
return is_readable( $this->getFullPath() ); return is_readable( $this->getFullPath() );
} }
/** /**
* Returns last access time. * Returns last access time.
* *
* @return int timestamp * @return int timestamp
*/ */
function lastAccess () function lastAccess ()
{ {
return fileatime( $this->getFullPath() ); return fileatime( $this->getFullPath() );
} }
/** /**
* Returns last modified time. * Returns last modified time.
* *
* @return int timestamp * @return int timestamp
*/ */
function lastChange () function lastChange ()
{ {
return filemtime( $this->getFullPath() ); return filemtime( $this->getFullPath() );
} }
/** /**
* Returns the current folder. * Returns the current folder.
* *
* @return Folder * @return Folder
*/ */
function getFolder () function getFolder ()
{ {
return $this->folder; return $this->folder;
} }
/** /**
* Returns the "chmod" (permissions) of the File. * Returns the "chmod" (permissions) of the File.
* *
* @return string * @return string
*/ */
function getChmod ( ) function getChmod ( )
{ {
return substr(sprintf('%o', fileperms($this->getFullPath())), -4); return substr(sprintf('%o', fileperms($this->getFullPath())), -4);
} }
/** /**
* Returns the full path of the File. * Returns the full path of the File.
* *
* @return string * @return string
*/ */
function getFullPath ( ) function getFullPath ( )
{ {
return Folder::slashTerm($this->folder->pwd()).$this->getName(); return Folder::slashTerm($this->folder->pwd()).$this->getName();
} }
} }
?> ?>

View file

@ -29,9 +29,9 @@
*/ */
/** /**
* Included libraries. * Included libraries.
* *
*/ */
if(!class_exists('Object')) if(!class_exists('Object'))
{ {
uses('object'); uses('object');
@ -49,40 +49,40 @@ if(!class_exists('Object'))
class Flay extends Object class Flay extends Object
{ {
/** /**
* Text to be parsed. * Text to be parsed.
* *
* @var string * @var string
*/ */
var $text = null; var $text = null;
/** /**
* Set this to allow HTML in the markup. * Set this to allow HTML in the markup.
* *
* @var boolean * @var boolean
*/ */
var $allow_html = false; var $allow_html = false;
/** /**
* Constructor. * Constructor.
* *
* @param string $text * @param string $text
*/ */
function __construct ($text=null) function __construct ($text=null)
{ {
$this->text = $text; $this->text = $text;
parent::__construct(); parent::__construct();
} }
/** /**
* Returns given text translated to HTML using the Flay syntax. * Returns given text translated to HTML using the Flay syntax.
* *
* @param string $text String to format * @param string $text String to format
* @param boolean $bare Set this to only do <p> transforms and > to &gt;, no typography additions. * @param boolean $bare Set this to only do <p> transforms and > to &gt;, no typography additions.
* @param boolean $allowHtml Set this to trim whitespace and disable all HTML * @param boolean $allowHtml Set this to trim whitespace and disable all HTML
* @return string Formatted text * @return string Formatted text
*/ */
function toHtml ($text=null, $bare=false, $allowHtml=false) function toHtml ($text=null, $bare=false, $allowHtml=false)
{ {
if (empty($text) && empty($this->text)) if (empty($text) && empty($this->text))
{ {
@ -91,7 +91,7 @@ class Flay extends Object
$text = $text? $text: $this->text; $text = $text? $text: $this->text;
// trim whitespace and disable all HTML // trim whitespace and disable all HTML
if ($allowHtml) if ($allowHtml)
{ {
$text = trim($text); $text = trim($text);
@ -103,17 +103,17 @@ class Flay extends Object
if (!$bare) if (!$bare)
{ {
// multi-paragraph functions // multi-paragraph functions
$text = preg_replace('#(?:[\n]{0,2})"""(.*)"""(?:[\n]{0,2})#s', "\n\n%BLOCKQUOTE%\n\n\\1\n\n%ENDBLOCKQUOTE%\n\n", $text); $text = preg_replace('#(?:[\n]{0,2})"""(.*)"""(?:[\n]{0,2})#s', "\n\n%BLOCKQUOTE%\n\n\\1\n\n%ENDBLOCKQUOTE%\n\n", $text);
$text = preg_replace('#(?:[\n]{0,2})===(.*)===(?:[\n]{0,2})#s', "\n\n%CENTER%\n\n\\1\n\n%ENDCENTER%\n\n", $text); $text = preg_replace('#(?:[\n]{0,2})===(.*)===(?:[\n]{0,2})#s', "\n\n%CENTER%\n\n\\1\n\n%ENDCENTER%\n\n", $text);
} }
// pre-parse newlines // pre-parse newlines
$text = preg_replace("#\r\n#", "\n", $text); $text = preg_replace("#\r\n#", "\n", $text);
$text = preg_replace("#[\n]{2,}#", "%PARAGRAPH%", $text); $text = preg_replace("#[\n]{2,}#", "%PARAGRAPH%", $text);
$text = preg_replace('#[\n]{1}#', "%LINEBREAK%", $text); $text = preg_replace('#[\n]{1}#', "%LINEBREAK%", $text);
// split into paragraphs and parse // split into paragraphs and parse
$out = ''; $out = '';
foreach (split('%PARAGRAPH%', $text) as $line) foreach (split('%PARAGRAPH%', $text) as $line)
{ {
@ -123,64 +123,64 @@ class Flay extends Object
if (!$bare) if (!$bare)
{ {
// pre-parse links // pre-parse links
$links = array(); $links = array();
$regs = null; $regs = null;
if (preg_match_all('#\[([^\[]{4,})\]#', $line, $regs)) if (preg_match_all('#\[([^\[]{4,})\]#', $line, $regs))
{ {
foreach ($regs[1] as $reg) foreach ($regs[1] as $reg)
{ {
$links[] = $reg; $links[] = $reg;
$line = str_replace("[{$reg}]",'%LINK'.(count($links)-1).'%', $line); $line = str_replace("[{$reg}]",'%LINK'.(count($links)-1).'%', $line);
} }
} }
// MAIN TEXT FUNCTIONS // MAIN TEXT FUNCTIONS
// bold // bold
$line = ereg_replace("\*([^\*]*)\*", "<strong>\\1</strong>", $line); $line = ereg_replace("\*([^\*]*)\*", "<strong>\\1</strong>", $line);
// italic // italic
$line = ereg_replace("_([^_]*)_", "<em>\\1</em>", $line); $line = ereg_replace("_([^_]*)_", "<em>\\1</em>", $line);
} }
// entities // entities
$line = str_replace(' - ', ' &ndash; ', $line); $line = str_replace(' - ', ' &ndash; ', $line);
$line = str_replace(' -- ', ' &mdash; ', $line); $line = str_replace(' -- ', ' &mdash; ', $line);
$line = str_replace('(C)', '&copy;', $line); $line = str_replace('(C)', '&copy;', $line);
$line = str_replace('(R)', '&reg;', $line); $line = str_replace('(R)', '&reg;', $line);
$line = str_replace('(TM)', '&trade;', $line); $line = str_replace('(TM)', '&trade;', $line);
// guess e-mails // guess e-mails
$emails = null; $emails = null;
if (preg_match_all("#([_A-Za-z0-9+-+]+(?:\.[_A-Za-z0-9+-]+)*@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*)#", $line, $emails)) if (preg_match_all("#([_A-Za-z0-9+-+]+(?:\.[_A-Za-z0-9+-]+)*@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*)#", $line, $emails))
{ {
foreach ($emails[1] as $email) foreach ($emails[1] as $email)
{ {
$line = str_replace($email, "<a href=\"mailto:{$email}\">{$email}</a>", $line); $line = str_replace($email, "<a href=\"mailto:{$email}\">{$email}</a>", $line);
} }
} }
if (!$bare) if (!$bare)
{ {
// guess links // guess links
$urls = null; $urls = null;
if (preg_match_all("#((?:http|https|ftp|nntp)://[^ ]+)#", $line, $urls)) if (preg_match_all("#((?:http|https|ftp|nntp)://[^ ]+)#", $line, $urls))
{ {
foreach ($urls[1] as $url) foreach ($urls[1] as $url)
{ {
$line = str_replace($url, "<a href=\"{$url}\">{$url}</a>", $line); $line = str_replace($url, "<a href=\"{$url}\">{$url}</a>", $line);
} }
} }
if (preg_match_all("#(www\.[^\n\%\ ]+[^\n\%\,\.\ ])#", $line, $urls)) if (preg_match_all("#(www\.[^\n\%\ ]+[^\n\%\,\.\ ])#", $line, $urls))
{ {
foreach ($urls[1] as $url) foreach ($urls[1] as $url)
{ {
$line = str_replace($url, "<a href=\"http://{$url}\">{$url}</a>", $line); $line = str_replace($url, "<a href=\"http://{$url}\">{$url}</a>", $line);
} }
} }
// re-parse links // re-parse links
if (count($links)) if (count($links))
{ {
for ($ii=0; $ii<count($links); $ii++) for ($ii=0; $ii<count($links); $ii++)
{ {
if (preg_match("#^(http|https|ftp|nntp)://#", $links[$ii])) if (preg_match("#^(http|https|ftp|nntp)://#", $links[$ii]))
@ -200,19 +200,19 @@ class Flay extends Object
{ {
if (isset($regs[2])) if (isset($regs[2]))
{ {
if (preg_match('#\.(jpg|jpeg|gif|png)$#', $regs[2])) if (preg_match('#\.(jpg|jpeg|gif|png)$#', $regs[2]))
{ {
$body = "<img src=\"{$prefix}{$regs[2]}\" alt=\"\" />"; $body = "<img src=\"{$prefix}{$regs[2]}\" alt=\"\" />";
} }
else else
{ {
$body = $regs[2]; $body = $regs[2];
} }
} }
else else
{ {
$body = $links[$ii]; $body = $links[$ii];
} }
$with = "<a href=\"{$prefix}{$regs[1]}\" target=\"_blank\">{$body}</a>"; $with = "<a href=\"{$prefix}{$regs[1]}\" target=\"_blank\">{$body}</a>";
@ -224,17 +224,17 @@ class Flay extends Object
$line = str_replace("%LINK{$ii}%", $with, $line); $line = str_replace("%LINK{$ii}%", $with, $line);
} }
} }
} }
// re-parse newlines // re-parse newlines
$out .= str_replace('%LINEBREAK%', "<br />\n", "<p>{$line}</p>\n"); $out .= str_replace('%LINEBREAK%', "<br />\n", "<p>{$line}</p>\n");
} }
} }
if (!$bare) if (!$bare)
{ {
// re-parse multilines // re-parse multilines
$out = str_replace('<p>%BLOCKQUOTE%</p>', "<blockquote>", $out); $out = str_replace('<p>%BLOCKQUOTE%</p>', "<blockquote>", $out);
$out = str_replace('<p>%ENDBLOCKQUOTE%</p>', "</blockquote>", $out); $out = str_replace('<p>%ENDBLOCKQUOTE%</p>', "</blockquote>", $out);
$out = str_replace('<p>%CENTER%</p>', "<center>", $out); $out = str_replace('<p>%CENTER%</p>', "<center>", $out);
@ -242,7 +242,7 @@ class Flay extends Object
} }
return $out; return $out;
} }
/** /**
* Return the words of the string as an array. * Return the words of the string as an array.
@ -250,10 +250,10 @@ class Flay extends Object
* @param string $string * @param string $string
* @return array Array of words * @return array Array of words
*/ */
function extractWords ($string) function extractWords ($string)
{ {
return preg_split('/[\s,\.:\/="!\(\)<>~\[\]]+/', $string); return preg_split('/[\s,\.:\/="!\(\)<>~\[\]]+/', $string);
} }
/** /**
* Return given string with words in array colorMarked, up to a number of times (defaults to 5). * Return given string with words in array colorMarked, up to a number of times (defaults to 5).
@ -264,8 +264,8 @@ class Flay extends Object
* @return string * @return string
* @see colorMark * @see colorMark
*/ */
function markedSnippets ($words, $string, $max_snippets=5) function markedSnippets ($words, $string, $max_snippets=5)
{ {
$string = strip_tags($string); $string = strip_tags($string);
@ -277,7 +277,7 @@ class Flay extends Object
{ {
foreach ($r as $result) foreach ($r as $result)
{ {
$rest = str_replace($result, '', $rest); $rest = str_replace($result, '', $rest);
} }
$snips = array_merge($snips, $r[0]); $snips = array_merge($snips, $r[0]);
} }
@ -285,13 +285,13 @@ class Flay extends Object
if (count($snips) > $max_snippets) if (count($snips) > $max_snippets)
{ {
$snips = array_slice($snips, 0, $max_snippets); $snips = array_slice($snips, 0, $max_snippets);
} }
$joined = join(' <b>...</b> ', $snips); $joined = join(' <b>...</b> ', $snips);
$snips = $joined? "<b>...</b> {$joined} <b>...</b>": substr($string, 0, 80) . '<b>...</b>'; $snips = $joined? "<b>...</b> {$joined} <b>...</b>": substr($string, 0, 80) . '<b>...</b>';
return Flay::colorMark($words, $snips); return Flay::colorMark($words, $snips);
} }
/** /**
* Returns string with EM elements with color classes added. * Returns string with EM elements with color classes added.
@ -300,8 +300,8 @@ class Flay extends Object
* @param string $string Text in which the words might be found * @param string $string Text in which the words might be found
* @return string * @return string
*/ */
function colorMark($words, $string) function colorMark($words, $string)
{ {
$colors = array('yl','gr','rd','bl','fu','cy'); $colors = array('yl','gr','rd','bl','fu','cy');
$nextColorIndex = 0; $nextColorIndex = 0;
@ -312,7 +312,7 @@ class Flay extends Object
} }
return $string; return $string;
} }
/** /**
* Returns given text with tags stripped out. * Returns given text with tags stripped out.
@ -320,10 +320,10 @@ class Flay extends Object
* @param string $text * @param string $text
* @return string * @return string
*/ */
function toClean ($text) function toClean ($text)
{ {
return strip_tags(html_entity_decode($text, ENT_QUOTES)); return strip_tags(html_entity_decode($text, ENT_QUOTES));
} }
/** /**
* Return parsed text with tags stripped out. * Return parsed text with tags stripped out.
@ -331,10 +331,10 @@ class Flay extends Object
* @param string $text * @param string $text
* @return string * @return string
*/ */
function toParsedAndClean ($text) function toParsedAndClean ($text)
{ {
return Flay::toClean(Flay::toHtml($text)); return Flay::toClean(Flay::toHtml($text));
} }
/** /**
* Return a fragment of a text, up to $length characters long, with an ellipsis after it. * Return a fragment of a text, up to $length characters long, with an ellipsis after it.
@ -344,8 +344,8 @@ class Flay extends Object
* @param string $ellipsis Sign to print after truncated text. * @param string $ellipsis Sign to print after truncated text.
* @return string * @return string
*/ */
function fragment ($text, $length, $ellipsis='...') function fragment ($text, $length, $ellipsis='...')
{ {
$soft = $length - 5; $soft = $length - 5;
$hard = $length + 5; $hard = $length + 5;
$rx = '/(.{' . $soft . ',' . $hard . '})[\s,\.:\/="!\(\)<>~\[\]]+.*/'; $rx = '/(.{' . $soft . ',' . $hard . '})[\s,\.:\/="!\(\)<>~\[\]]+.*/';
@ -360,7 +360,7 @@ class Flay extends Object
$out = $out . (strlen($out)<strlen($text)? $ellipsis: null); $out = $out . (strlen($out)<strlen($text)? $ellipsis: null);
return $out; return $out;
} }
} }
?> ?>

View file

@ -28,9 +28,9 @@
*/ */
/** /**
* Included libraries. * Included libraries.
* *
*/ */
if(!class_exists('Object')) if(!class_exists('Object'))
{ {
uses('object'); uses('object');
@ -47,27 +47,27 @@ if(!class_exists('Object'))
class Folder extends Object { class Folder extends Object {
/** /**
* Path to Folder. * Path to Folder.
* *
* @var string * @var string
*/ */
var $path = null; var $path = null;
/** /**
* Sortedness. * Sortedness.
* *
* @var boolean * @var boolean
*/ */
var $sort = false; var $sort = false;
/** /**
* Constructor. * Constructor.
* *
* @param string $path * @param string $path
* @param boolean $path * @param boolean $path
*/ */
function Folder ($path = false , $create = false, $mode = false) function Folder ($path = false , $create = false, $mode = false)
{ {
if (empty($path)) if (empty($path))
{ {
$path = getcwd(); $path = getcwd();
@ -78,45 +78,45 @@ class Folder extends Object {
$this->mkdirr($path, $mode); $this->mkdirr($path, $mode);
} }
$this->cd($path); $this->cd($path);
} }
/** /**
* Return current path. * Return current path.
* *
* @return string Current path * @return string Current path
*/ */
function pwd () function pwd ()
{ {
return $this->path; return $this->path;
} }
/** /**
* Change directory to $desired_path. * Change directory to $desired_path.
* *
* @param string $desired_path Path to the directory to change to * @param string $desired_path Path to the directory to change to
* @return string The new path. Returns false on failure * @return string The new path. Returns false on failure
*/ */
function cd ($desired_path) function cd ($desired_path)
{ {
$desired_path = realpath($desired_path); $desired_path = realpath($desired_path);
$new_path = Folder::isAbsolute($desired_path)? $new_path = Folder::isAbsolute($desired_path)?
$desired_path: $desired_path:
Folder::addPathElement($this->path, $desired_path); Folder::addPathElement($this->path, $desired_path);
return is_dir($new_path)? $this->path = $new_path: false; return is_dir($new_path)? $this->path = $new_path: false;
} }
/** /**
* Returns an array of the contents of the current directory, or false on failure. * Returns an array of the contents of the current directory, or false on failure.
* The returned array holds two arrays: one of dirs and one of files. * The returned array holds two arrays: one of dirs and one of files.
* *
* @param boolean $sort * @param boolean $sort
* @param boolean $noDotFiles * @param boolean $noDotFiles
* @return array * @return array
*/ */
function ls($sort=true , $noDotFiles = false) function ls($sort=true , $noDotFiles = false)
{ {
$dir = opendir($this->path); $dir = opendir($this->path);
if ($dir) if ($dir)
@ -126,14 +126,14 @@ class Folder extends Object {
{ {
if ( (!preg_match('#^\.+$#', $n) && $noDotFiles == false) || ( $noDotFiles == true && !preg_match('#^\.(.*)$#', $n) ) ) if ( (!preg_match('#^\.+$#', $n) && $noDotFiles == false) || ( $noDotFiles == true && !preg_match('#^\.(.*)$#', $n) ) )
{ {
if (is_dir($this->addPathElement($this->path, $n))) if (is_dir($this->addPathElement($this->path, $n)))
{ {
$dirs[] = $n; $dirs[] = $n;
} }
else else
{ {
$files[] = $n; $files[] = $n;
} }
} }
} }
@ -151,17 +151,17 @@ class Folder extends Object {
{ {
return false; return false;
} }
} }
/** /**
* Returns an array of all matching files in current directory. * Returns an array of all matching files in current directory.
* *
* @param string $pattern Preg_match pattern (Defaults to: .*) * @param string $pattern Preg_match pattern (Defaults to: .*)
* @return array * @return array
*/ */
function find ($regexp_pattern='.*') function find ($regexp_pattern='.*')
{ {
$data = $this->ls(); $data = $this->ls();
if (!is_array($data)) if (!is_array($data))
@ -181,32 +181,32 @@ class Folder extends Object {
} }
return $found; return $found;
} }
/** /**
* Returns an array of all matching files in and below current directory. * Returns an array of all matching files in and below current directory.
* *
* @param string $pattern Preg_match pattern (Defaults to: .*) * @param string $pattern Preg_match pattern (Defaults to: .*)
* @return array Files matching $pattern * @return array Files matching $pattern
*/ */
function findRecursive ($pattern='.*') function findRecursive ($pattern='.*')
{ {
$starts_on = $this->path; $starts_on = $this->path;
$out = $this->_findRecursive($pattern); $out = $this->_findRecursive($pattern);
$this->cd($starts_on); $this->cd($starts_on);
return $out; return $out;
} }
/** /**
* Private helper function for findRecursive. * Private helper function for findRecursive.
* *
* @param string $pattern * @param string $pattern
* @return array Files matching pattern * @return array Files matching pattern
* @access private * @access private
*/ */
function _findRecursive ($pattern) function _findRecursive ($pattern)
{ {
list($dirs, $files) = $this->ls(); list($dirs, $files) = $this->ls();
$found = array(); $found = array();
@ -226,102 +226,102 @@ class Folder extends Object {
} }
return $found; return $found;
} }
/** /**
* Returns true if given $path is a Windows path. * Returns true if given $path is a Windows path.
* *
* @param string $path Path to check * @param string $path Path to check
* @return boolean * @return boolean
* @static * @static
*/ */
function isWindowsPath ($path) function isWindowsPath ($path)
{ {
return preg_match('#^[A-Z]:\\\#i', $path)? true: false; return preg_match('#^[A-Z]:\\\#i', $path)? true: false;
} }
/** /**
* Returns true if given $path is an absolute path. * Returns true if given $path is an absolute path.
* *
* @param string $path Path to check * @param string $path Path to check
* @return boolean * @return boolean
* @static * @static
*/ */
function isAbsolute ($path) function isAbsolute ($path)
{ {
return preg_match('#^\/#', $path) || preg_match('#^[A-Z]:\\\#i', $path); return preg_match('#^\/#', $path) || preg_match('#^[A-Z]:\\\#i', $path);
} }
/** /**
* Returns true if given $path ends in a slash (i.e. is slash-terminated). * Returns true if given $path ends in a slash (i.e. is slash-terminated).
* *
* @param string $path Path to check * @param string $path Path to check
* @return boolean * @return boolean
* @static * @static
*/ */
function isSlashTerm ($path) function isSlashTerm ($path)
{ {
return preg_match('#[\\\/]$#', $path)? true: false; return preg_match('#[\\\/]$#', $path)? true: false;
} }
/** /**
* Returns a correct set of slashes for given $path. (\\ for Windows paths and / for other paths.) * Returns a correct set of slashes for given $path. (\\ for Windows paths and / for other paths.)
* *
* @param string $path Path to check * @param string $path Path to check
* @return string Set of slashes ("\\" or "/") * @return string Set of slashes ("\\" or "/")
* @static * @static
*/ */
function correctSlashFor ($path) function correctSlashFor ($path)
{ {
return Folder::isWindowsPath($path)? '\\': '/'; return Folder::isWindowsPath($path)? '\\': '/';
} }
/** /**
* Returns $path with added terminating slash (corrected for Windows or other OS). * Returns $path with added terminating slash (corrected for Windows or other OS).
* *
* @param string $path Path to check * @param string $path Path to check
* @return string * @return string
* @static * @static
*/ */
function slashTerm ($path) function slashTerm ($path)
{ {
return $path . (Folder::isSlashTerm($path)? null: Folder::correctSlashFor($path)); return $path . (Folder::isSlashTerm($path)? null: Folder::correctSlashFor($path));
} }
/** /**
* Returns $path with $element added, with correct slash in-between. * Returns $path with $element added, with correct slash in-between.
* *
* @param string $path * @param string $path
* @param string $element * @param string $element
* @return string * @return string
* @static * @static
*/ */
function addPathElement ($path, $element) function addPathElement ($path, $element)
{ {
return Folder::slashTerm($path).$element; return Folder::slashTerm($path).$element;
} }
/** /**
* Returns true if the File is in a given CakePath. * Returns true if the File is in a given CakePath.
* *
* @return boolean * @return boolean
*/ */
function inCakePath ( $path = '' ) function inCakePath ( $path = '' )
{ {
$dir = substr( Folder::slashTerm(ROOT) , 0 , -1 ); $dir = substr( Folder::slashTerm(ROOT) , 0 , -1 );
$newdir = Folder::slashTerm($dir.$path); $newdir = Folder::slashTerm($dir.$path);
return $this->inPath( $newdir ); return $this->inPath( $newdir );
} }
/** /**
* Returns true if the File is in given path. * Returns true if the File is in given path.
* *
* @return boolean * @return boolean
*/ */
function inPath ( $path = '' ) function inPath ( $path = '' )
{ {
$dir = substr( Folder::slashTerm($path) , 0 , -1 ); $dir = substr( Folder::slashTerm($path) , 0 , -1 );
$return = preg_match('/^'.preg_quote(Folder::slashTerm($dir),'/').'(.*)/' , Folder::slashTerm($this->pwd()) ); $return = preg_match('/^'.preg_quote(Folder::slashTerm($dir),'/').'(.*)/' , Folder::slashTerm($this->pwd()) );
@ -334,30 +334,30 @@ class Folder extends Object {
{ {
return false; return false;
} }
} }
/** /**
* Create a directory structure recursively. * Create a directory structure recursively.
* *
* @param string $pathname The directory structure to create * @param string $pathname The directory structure to create
* @return bool Returns TRUE on success, FALSE on failure * @return bool Returns TRUE on success, FALSE on failure
*/ */
function mkdirr($pathname, $mode = null) function mkdirr($pathname, $mode = null)
{ {
// Check if directory already exists // Check if directory already exists
if (is_dir($pathname) || empty($pathname)) if (is_dir($pathname) || empty($pathname))
{ {
return true; return true;
} }
// Ensure a file does not already exist with the same name // Ensure a file does not already exist with the same name
if (is_file($pathname)) if (is_file($pathname))
{ {
trigger_error('mkdirr() File exists', E_USER_WARNING); trigger_error('mkdirr() File exists', E_USER_WARNING);
return false; return false;
} }
// Crawl up the directory tree // Crawl up the directory tree
$next_pathname = substr($pathname, 0, strrpos($pathname, DIRECTORY_SEPARATOR)); $next_pathname = substr($pathname, 0, strrpos($pathname, DIRECTORY_SEPARATOR));
if ($this->mkdirr($next_pathname, $mode)) if ($this->mkdirr($next_pathname, $mode))
{ {
@ -369,67 +369,67 @@ class Folder extends Object {
} }
return false; return false;
} }
/** /**
* Returns the size in bytes of this Folder. * Returns the size in bytes of this Folder.
* *
* @param string $directory Path to directory * @param string $directory Path to directory
*/ */
function dirsize() function dirsize()
{ {
// Init // Init
$size = 0; $size = 0;
$directory = Folder::slashTerm($this->path); $directory = Folder::slashTerm($this->path);
// Creating the stack array // Creating the stack array
$stack = array($directory); $stack = array($directory);
// Iterate stack // Iterate stack
for ($i = 0, $j = count($stack); $i < $j; ++$i) for ($i = 0, $j = count($stack); $i < $j; ++$i)
{ {
// Add to total size // Add to total size
if (is_file($stack[$i])) if (is_file($stack[$i]))
{ {
$size += filesize($stack[$i]); $size += filesize($stack[$i]);
} }
// Add to stack // Add to stack
elseif (is_dir($stack[$i])) elseif (is_dir($stack[$i]))
{ {
// Read directory // Read directory
$dir = dir($stack[$i]); $dir = dir($stack[$i]);
while (false !== ($entry = $dir->read())) while (false !== ($entry = $dir->read()))
{ {
// No pointers // No pointers
if ($entry == '.' || $entry == '..') if ($entry == '.' || $entry == '..')
{ {
continue; continue;
} }
// Add to stack // Add to stack
$add = $stack[$i] . $entry; $add = $stack[$i] . $entry;
if (is_dir($stack[$i] . $entry)) if (is_dir($stack[$i] . $entry))
{ {
$add = Folder::slashTerm($add); $add = Folder::slashTerm($add);
} }
$stack[] = $add; $stack[] = $add;
} }
// Clean up // Clean up
$dir->close(); $dir->close();
} }
// Recount stack // Recount stack
$j = count($stack); $j = count($stack);
} }
return $size; return $size;
} }
} }
?> ?>

View file

@ -29,9 +29,9 @@
*/ */
/** /**
* Included libraries. * Included libraries.
* *
*/ */
if(!class_exists('Object')) if(!class_exists('Object'))
{ {
uses('object'); uses('object');
@ -51,13 +51,13 @@ class Inflector extends Object
{ {
/** /**
* Constructor. * Constructor.
* *
*/ */
function __construct () function __construct ()
{ {
parent::__construct(); parent::__construct();
} }
/** /**
* Return $word in plural form. * Return $word in plural form.
@ -69,22 +69,22 @@ class Inflector extends Object
{ {
$pluralRules = array('/(s)tatus$/i' => '\1\2tatuses', $pluralRules = array('/(s)tatus$/i' => '\1\2tatuses',
'/^(ox)$/i' => '\1\2en', # ox '/^(ox)$/i' => '\1\2en', # ox
'/([m|l])ouse$/i' => '\1ice', # mouse, louse '/([m|l])ouse$/i' => '\1ice', # mouse, louse
'/(matr|vert|ind)ix|ex$/i' => '\1ices', # matrix, vertex, index '/(matr|vert|ind)ix|ex$/i' => '\1ices', # matrix, vertex, index
'/(x|ch|ss|sh)$/i' => '\1es', # search, switch, fix, box, process, address '/(x|ch|ss|sh)$/i' => '\1es', # search, switch, fix, box, process, address
'/([^aeiouy]|qu)y$/i' => '\1ies', # query, ability, agency '/([^aeiouy]|qu)y$/i' => '\1ies', # query, ability, agency
'/(hive)$/i' => '\1s', # archive, hive '/(hive)$/i' => '\1s', # archive, hive
'/(?:([^f])fe|([lr])f)$/i' => '\1\2ves', # half, safe, wife '/(?:([^f])fe|([lr])f)$/i' => '\1\2ves', # half, safe, wife
'/sis$/i' => 'ses', # basis, diagnosis '/sis$/i' => 'ses', # basis, diagnosis
'/([ti])um$/i' => '\1a', # datum, medium '/([ti])um$/i' => '\1a', # datum, medium
'/(p)erson$/i' => '\1eople', # person, salesperson '/(p)erson$/i' => '\1eople', # person, salesperson
'/(m)an$/i' => '\1en', # man, woman, spokesman '/(m)an$/i' => '\1en', # man, woman, spokesman
'/(c)hild$/i' => '\1hildren', # child '/(c)hild$/i' => '\1hildren', # child
'/(buffal|tomat)o$/i' => '\1\2oes', # buffalo, tomato '/(buffal|tomat)o$/i' => '\1\2oes', # buffalo, tomato
'/(bu)s$/i' => '\1\2ses', # bus '/(bu)s$/i' => '\1\2ses', # bus
'/(alias)/i' => '\1es', # alias '/(alias)/i' => '\1es', # alias
'/(octop|vir)us$/i' => '\1i', # octopus, virus - virus has no defined plural (according to Latin/dictionary.com), but viri is better than viruses/viruss '/(octop|vir)us$/i' => '\1i', # octopus, virus - virus has no defined plural (according to Latin/dictionary.com), but viri is better than viruses/viruss
'/(ax|cri|test)is$/i' => '\1es', # axis, crisis '/(ax|cri|test)is$/i' => '\1es', # axis, crisis
'/s$/' => 's', # no change (compatibility) '/s$/' => 's', # no change (compatibility)
'/$/' => 's'); '/$/' => 's');
@ -100,34 +100,34 @@ class Inflector extends Object
'whiting', 'wildebeest', 'Yengeese',); 'whiting', 'wildebeest', 'Yengeese',);
$irregular = array('atlas' => 'atlases', $irregular = array('atlas' => 'atlases',
'beef' => 'beefs', 'beef' => 'beefs',
'brother' => 'brothers', 'brother' => 'brothers',
'child' => 'children', 'child' => 'children',
'corpus' => 'corpuses', 'corpus' => 'corpuses',
'cow' => 'cows', 'cow' => 'cows',
'ganglion' => 'ganglions', 'ganglion' => 'ganglions',
'genie' => 'genies', 'genie' => 'genies',
'genus' => 'genera', 'genus' => 'genera',
'graffito' => 'graffiti', 'graffito' => 'graffiti',
'hoof' => 'hoofs', 'hoof' => 'hoofs',
'loaf' => 'loaves', 'loaf' => 'loaves',
'man' => 'men', 'man' => 'men',
'money' => 'monies', 'money' => 'monies',
'mongoose' => 'mongooses', 'mongoose' => 'mongooses',
'move' => 'moves', 'move' => 'moves',
'mythos' => 'mythoi', 'mythos' => 'mythoi',
'numen' => 'numina', 'numen' => 'numina',
'occiput' => 'occiputs', 'occiput' => 'occiputs',
'octopus' => 'octopuses', 'octopus' => 'octopuses',
'opus' => 'opuses', 'opus' => 'opuses',
'ox' => 'oxen', 'ox' => 'oxen',
'penis' => 'penises', 'penis' => 'penises',
'person' => 'people', 'person' => 'people',
'sex' => 'sexes', 'sex' => 'sexes',
'soliloquy' => 'soliloquies', 'soliloquy' => 'soliloquies',
'testis' => 'testes', 'testis' => 'testes',
'trilby' => 'trilbys', 'trilby' => 'trilbys',
'turf' => 'turfs',); 'turf' => 'turfs',);
$regexUninflected = __enclose(join( '|', $uninflected)); $regexUninflected = __enclose(join( '|', $uninflected));
$regexIrregular = __enclose(join( '|', array_keys($irregular))); $regexIrregular = __enclose(join( '|', array_keys($irregular)));
@ -161,33 +161,33 @@ class Inflector extends Object
function singularize ($word) function singularize ($word)
{ {
$singularRules = array('/(s)tatuses$/i' => '\1\2tatus', $singularRules = array('/(s)tatuses$/i' => '\1\2tatus',
'/(matr)ices$/i' =>'\1ix', '/(matr)ices$/i' =>'\1ix',
'/(vert|ind)ices$/i' => '\1ex', '/(vert|ind)ices$/i' => '\1ex',
'/^(ox)en/i' => '\1', '/^(ox)en/i' => '\1',
'/(alias)es$/i' => '\1', '/(alias)es$/i' => '\1',
'/([octop|vir])i$/i' => '\1us', '/([octop|vir])i$/i' => '\1us',
'/(cris|ax|test)es$/i' => '\1is', '/(cris|ax|test)es$/i' => '\1is',
'/(shoe)s$/i' => '\1', '/(shoe)s$/i' => '\1',
'/(o)es$/i' => '\1', '/(o)es$/i' => '\1',
'/(bus)es$/i' => '\1', '/(bus)es$/i' => '\1',
'/([m|l])ice$/i' => '\1ouse', '/([m|l])ice$/i' => '\1ouse',
'/(x|ch|ss|sh)es$/i' => '\1', '/(x|ch|ss|sh)es$/i' => '\1',
'/(m)ovies$/i' => '\1\2ovie', '/(m)ovies$/i' => '\1\2ovie',
'/(s)eries$/i' => '\1\2eries', '/(s)eries$/i' => '\1\2eries',
'/([^aeiouy]|qu)ies$/i' => '\1y', '/([^aeiouy]|qu)ies$/i' => '\1y',
'/([lr])ves$/i' => '\1f', '/([lr])ves$/i' => '\1f',
'/(tive)s$/i' => '\1', '/(tive)s$/i' => '\1',
'/(hive)s$/i' => '\1', '/(hive)s$/i' => '\1',
'/(drive)s$/i' => '\1', '/(drive)s$/i' => '\1',
'/([^f])ves$/i' => '\1fe', '/([^f])ves$/i' => '\1fe',
'/(^analy)ses$/i' => '\1sis', '/(^analy)ses$/i' => '\1sis',
'/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis', '/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis',
'/([ti])a$/i' => '\1um', '/([ti])a$/i' => '\1um',
'/(p)eople$/i' => '\1\2erson', '/(p)eople$/i' => '\1\2erson',
'/(m)en$/i' => '\1an', '/(m)en$/i' => '\1an',
'/(c)hildren$/i' => '\1\2hild', '/(c)hildren$/i' => '\1\2hild',
'/(n)ews$/i' => '\1\2ews', '/(n)ews$/i' => '\1\2ews',
'/s$/i' => ''); '/s$/i' => '');
$uninflected = array('.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*rice', '.*sheep', 'Amoyese', $uninflected = array('.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*rice', '.*sheep', 'Amoyese',
'bison', 'Borghese', 'bream', 'breeches', 'britches', 'buffalo', 'cantus', 'carp', 'chassis', 'clippers', 'bison', 'Borghese', 'bream', 'breeches', 'britches', 'buffalo', 'cantus', 'carp', 'chassis', 'clippers',
@ -200,35 +200,35 @@ class Inflector extends Object
'siemens', 'species', 'swine', 'testes', 'trousers', 'trout', 'tuna', 'Vermontese', 'Wenchowese', 'siemens', 'species', 'swine', 'testes', 'trousers', 'trout', 'tuna', 'Vermontese', 'Wenchowese',
'whiting', 'wildebeest', 'Yengeese',); 'whiting', 'wildebeest', 'Yengeese',);
$irregular = array('atlas' => 'atlases', $irregular = array('atlas' => 'atlases',
'beefs' => 'beef', 'beefs' => 'beef',
'brothers' => 'brother', 'brothers' => 'brother',
'children' => 'child', 'children' => 'child',
'corpuses' => 'corpus', 'corpuses' => 'corpus',
'cows' => 'cow', 'cows' => 'cow',
'ganglions' => 'ganglion', 'ganglions' => 'ganglion',
'genies' => 'genie', 'genies' => 'genie',
'genera' => 'genus', 'genera' => 'genus',
'graffiti' => 'graffito', 'graffiti' => 'graffito',
'hoofs' => 'hoof', 'hoofs' => 'hoof',
'loaves' => 'loaf', 'loaves' => 'loaf',
'men' => 'man', 'men' => 'man',
'monies' => 'money', 'monies' => 'money',
'mongooses' => 'mongoose', 'mongooses' => 'mongoose',
'moves' => 'move', 'moves' => 'move',
'mythoi' => 'mythos', 'mythoi' => 'mythos',
'numina' => 'numen', 'numina' => 'numen',
'occiputs' => 'occiput', 'occiputs' => 'occiput',
'octopuses' => 'octopus', 'octopuses' => 'octopus',
'opuses' => 'opus', 'opuses' => 'opus',
'oxen' => 'ox', 'oxen' => 'ox',
'penises' => 'penis', 'penises' => 'penis',
'people' => 'person', 'people' => 'person',
'sexes' => 'sex', 'sexes' => 'sex',
'soliloquies' => 'soliloquy', 'soliloquies' => 'soliloquy',
'testes' => 'testis', 'testes' => 'testis',
'trilbys' => 'trilby', 'trilbys' => 'trilby',
'turfs' => 'turf',); 'turfs' => 'turf',);
$regexUninflected = __enclose(join( '|', $uninflected)); $regexUninflected = __enclose(join( '|', $uninflected));
$regexIrregular = __enclose(join( '|', array_keys($irregular))); $regexIrregular = __enclose(join( '|', array_keys($irregular)));
@ -254,60 +254,60 @@ class Inflector extends Object
} }
/** /**
* Returns given $lower_case_and_underscored_word as a camelCased word. * Returns given $lower_case_and_underscored_word as a camelCased word.
* *
* @param string $lower_case_and_underscored_word Word to camelize * @param string $lower_case_and_underscored_word Word to camelize
* @return string Camelized word. likeThis. * @return string Camelized word. likeThis.
*/ */
function camelize($lowerCaseAndUnderscoredWord) function camelize($lowerCaseAndUnderscoredWord)
{ {
return str_replace(" ","",ucwords(str_replace("_"," ",$lowerCaseAndUnderscoredWord))); return str_replace(" ","",ucwords(str_replace("_"," ",$lowerCaseAndUnderscoredWord)));
} }
/** /**
* Returns an underscore-syntaxed ($like_this_dear_reader) version of the $camel_cased_word. * Returns an underscore-syntaxed ($like_this_dear_reader) version of the $camel_cased_word.
* *
* @param string $camel_cased_word Camel-cased word to be "underscorized" * @param string $camel_cased_word Camel-cased word to be "underscorized"
* @return string Underscore-syntaxed version of the $camel_cased_word * @return string Underscore-syntaxed version of the $camel_cased_word
*/ */
function underscore($camelCasedWord) function underscore($camelCasedWord)
{ {
return strtolower (preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $camelCasedWord)); return strtolower (preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $camelCasedWord));
} }
/** /**
* Returns a human-readable string from $lower_case_and_underscored_word, * Returns a human-readable string from $lower_case_and_underscored_word,
* by replacing underscores with a space, and by upper-casing the initial characters. * by replacing underscores with a space, and by upper-casing the initial characters.
* *
* @param string $lower_case_and_underscored_word String to be made more readable * @param string $lower_case_and_underscored_word String to be made more readable
* @return string Human-readable string * @return string Human-readable string
*/ */
function humanize($lowerCaseAndUnderscoredWord) function humanize($lowerCaseAndUnderscoredWord)
{ {
return ucwords(str_replace("_"," ",$lowerCaseAndUnderscoredWord)); return ucwords(str_replace("_"," ",$lowerCaseAndUnderscoredWord));
} }
/** /**
* Returns corresponding table name for given $class_name. ("posts" for the model class "Post"). * Returns corresponding table name for given $class_name. ("posts" for the model class "Post").
* *
* @param string $class_name Name of class to get database table name for * @param string $class_name Name of class to get database table name for
* @return string Name of the database table for given class * @return string Name of the database table for given class
*/ */
function tableize($className) function tableize($className)
{ {
return Inflector::pluralize(Inflector::underscore($className)); return Inflector::pluralize(Inflector::underscore($className));
} }
/** /**
* Returns Cake model class name ("Post" for the database table "posts".) for given database table. * Returns Cake model class name ("Post" for the database table "posts".) for given database table.
* *
* @param string $tableName Name of database table to get class name for * @param string $tableName Name of database table to get class name for
* @return string * @return string
*/ */
function classify($tableName) function classify($tableName)
{ {
return Inflector::camelize(Inflector::singularize($tableName)); return Inflector::camelize(Inflector::singularize($tableName));
} }
} }
function __enclose($string) function __enclose($string)

View file

@ -48,7 +48,7 @@ if (!function_exists('file_get_contents'))
* Replace file_get_contents() * Replace file_get_contents()
* *
* @internal resource_context is not supported * @internal resource_context is not supported
* @since PHP 5 * @since PHP 5
* require PHP 4.0.0 (user_error) * require PHP 4.0.0 (user_error)
* *
* @param unknown_type $filename * @param unknown_type $filename

View file

@ -107,13 +107,13 @@ class ConnectionManager extends Object
if(isset($config['driver']) && $config['driver'] != null && $config['driver'] != '') if(isset($config['driver']) && $config['driver'] != null && $config['driver'] != '')
{ {
$filename = 'dbo_'.$config['driver']; $filename = 'dbo_'.$config['driver'];
$classname = Inflector::camelize(strtolower('DBO_'.$config['driver'])); $classname = Inflector::camelize(strtolower('DBO_'.$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'));
} }
$tail = 'dbo'.DS.$filename.'.php'; $tail = 'dbo'.DS.$filename.'.php';

View file

@ -47,7 +47,7 @@ class DataSource extends Object
* @var boolean * @var boolean
* @access public * @access public
*/ */
var $connected = false; var $connected = false;
/** /**
* Print debug info? * Print debug info?
@ -55,7 +55,7 @@ class DataSource extends Object
* @var boolean * @var boolean
* @access public * @access public
*/ */
var $debug = false; var $debug = false;
/** /**
* Print full query debug info? * Print full query debug info?
@ -63,7 +63,7 @@ class DataSource extends Object
* @var boolean * @var boolean
* @access public * @access public
*/ */
var $fullDebug = false; var $fullDebug = false;
/** /**
* Error description of last query * Error description of last query
@ -71,7 +71,7 @@ class DataSource extends Object
* @var unknown_type * @var unknown_type
* @access public * @access public
*/ */
var $error = null; var $error = null;
/** /**
* String to hold how many rows were affected by the last SQL operation. * String to hold how many rows were affected by the last SQL operation.
@ -79,7 +79,7 @@ class DataSource extends Object
* @var string * @var string
* @access public * @access public
*/ */
var $affected = null; var $affected = null;
/** /**
* Number of rows in current resultset * Number of rows in current resultset
@ -87,7 +87,7 @@ class DataSource extends Object
* @var int * @var int
* @access public * @access public
*/ */
var $numRows = null; var $numRows = null;
/** /**
* Time the last query took * Time the last query took
@ -95,7 +95,7 @@ class DataSource extends Object
* @var int * @var int
* @access public * @access public
*/ */
var $took = null; var $took = null;
/** /**
* Enter description here... * Enter description here...
@ -103,7 +103,7 @@ class DataSource extends Object
* @var array * @var array
* @access private * @access private
*/ */
var $_result = null; var $_result = null;
/** /**
* Queries count. * Queries count.
@ -111,7 +111,7 @@ class DataSource extends Object
* @var int * @var int
* @access private * @access private
*/ */
var $_queriesCnt = 0; var $_queriesCnt = 0;
/** /**
* Total duration of all queries. * Total duration of all queries.
@ -119,7 +119,7 @@ class DataSource extends Object
* @var unknown_type * @var unknown_type
* @access private * @access private
*/ */
var $_queriesTime = null; var $_queriesTime = null;
/** /**
* Log of queries executed by this DataSource * Log of queries executed by this DataSource
@ -127,7 +127,7 @@ class DataSource extends Object
* @var unknown_type * @var unknown_type
* @access private * @access private
*/ */
var $_queriesLog = array(); var $_queriesLog = array();
/** /**
* Maximum number of items in query log, to prevent query log taking over * Maximum number of items in query log, to prevent query log taking over
@ -137,7 +137,7 @@ class DataSource extends Object
* @var int Maximum number of queries in the queries log. * @var int Maximum number of queries in the queries log.
* @access private * @access private
*/ */
var $_queriesLogMax = 200; var $_queriesLogMax = 200;
/** /**
* The default configuration of a specific DataSource * The default configuration of a specific DataSource
@ -192,14 +192,14 @@ class DataSource extends Object
* Constructor. * Constructor.
* *
*/ */
function __construct () function __construct ()
{ {
parent::__construct(); parent::__construct();
if(func_num_args() > 0) if(func_num_args() > 0)
{ {
$this->setConfig(func_get_arg(0)); $this->setConfig(func_get_arg(0));
} }
} }
/** /**
* Returns true if the DataSource supports the given interface (method) * Returns true if the DataSource supports the given interface (method)
@ -207,13 +207,13 @@ class DataSource extends Object
* @param string $interface The name of the interface (method) * @param string $interface The name of the interface (method)
* @return boolean True on success * @return boolean True on success
*/ */
function isInterfaceSupported ($interface) function isInterfaceSupported ($interface)
{ {
$methods = get_class_methods(get_class($this)); $methods = get_class_methods(get_class($this));
$methods = strtolower(implode('|', $methods)); $methods = strtolower(implode('|', $methods));
$methods = explode('|', $methods); $methods = explode('|', $methods);
return in_array(strtolower($interface), $methods); return in_array(strtolower($interface), $methods);
} }
/** /**
* Sets the configuration for the DataSource * Sets the configuration for the DataSource
@ -221,17 +221,17 @@ class DataSource extends Object
* @param array $config The configuration array * @param array $config The configuration array
* @return void * @return void
*/ */
function setConfig ($config) function setConfig ($config)
{ {
if(is_array($this->_baseConfig)) if(is_array($this->_baseConfig))
{ {
$this->config = $this->_baseConfig; $this->config = $this->_baseConfig;
foreach($config as $key => $val) foreach($config as $key => $val)
{ {
$this->config[$key] = $val; $this->config[$key] = $val;
} }
} }
} }
/** /**
* Cache the DataSource description * Cache the DataSource description
@ -264,7 +264,7 @@ class DataSource extends Object
$new = cache('models'.DS.low(get_class($this)).'_'.$object, $cache, $expires); $new = cache('models'.DS.low(get_class($this)).'_'.$object, $cache, $expires);
if($new != null) if($new != null)
{ {
$new = unserialize($new); $new = unserialize($new);
} }
return $new; return $new;
} }
@ -412,14 +412,14 @@ class DataSource extends Object
*/ */
function insertQueryData($query, $data, $association, $assocData, &$model, &$linkModel, $index) function insertQueryData($query, $data, $association, $assocData, &$model, &$linkModel, $index)
{ {
$keys = array('{$__cake_id__$}', '{$__cake_foreignKey__$}'); $keys = array('{$__cakeID__$}', '{$__cakeForeignKey__$}');
foreach($keys as $key) foreach($keys as $key)
{ {
if (strpos($query, $key) !== false) if (strpos($query, $key) !== false)
{ {
switch($key) switch($key)
{ {
case '{$__cake_id__$}': case '{$__cakeID__$}':
$val = null; $val = null;
if (isset($data[$index][$model->name])) if (isset($data[$index][$model->name]))
{ {

View file

@ -51,24 +51,24 @@ class DboSource extends DataSource
* *
* @var unknown_type * @var unknown_type
*/ */
var $__bypass = false; var $__bypass = false;
/** /**
* Enter description here... * Enter description here...
* *
* @var array * @var array
*/ */
var $__assocJoins = null; var $__assocJoins = null;
/** /**
* Constructor * Constructor
* *
*/ */
function __construct($config = null) function __construct($config = null)
{ {
$this->debug = DEBUG > 0; $this->debug = DEBUG > 0;
$this->fullDebug = DEBUG > 1; $this->fullDebug = DEBUG > 1;
parent::__construct($config); parent::__construct($config);
return $this->connect(); return $this->connect();
} }
/** /**
* Prepares a value, or an array of values for database queries by quoting and escaping them. * Prepares a value, or an array of values for database queries by quoting and escaping them.
@ -76,8 +76,8 @@ class DboSource extends DataSource
* @param mixed $data A value or an array of values to prepare. * @param mixed $data A value or an array of values to prepare.
* @return mixed Prepared value or array of values. * @return mixed Prepared value or array of values.
*/ */
function value ($data, $column = null) function value ($data, $column = null)
{ {
if (is_array($data)) if (is_array($data))
{ {
$out = array(); $out = array();
@ -91,17 +91,17 @@ class DboSource extends DataSource
{ {
return null; return null;
} }
} }
/** /**
* Convenience method for DboSource::listSources(). * Convenience method for DboSource::listSources().
* *
* @return array * @return array
*/ */
function sources () function sources ()
{ {
return array_map('strtolower', $this->listSources()); return array_map('strtolower', $this->listSources());
} }
/** /**
* Executes given SQL statement. * Executes given SQL statement.
@ -109,11 +109,11 @@ class DboSource extends DataSource
* @param string $sql SQL statement * @param string $sql SQL statement
* @return unknown * @return unknown
*/ */
function rawQuery ($sql) function rawQuery ($sql)
{ {
$this->took = $this->error = $this->numRows = false; $this->took = $this->error = $this->numRows = false;
return $this->execute($sql); return $this->execute($sql);
} }
/** /**
* Queries the database with given SQL statement, and obtains some metadata about the result * Queries the database with given SQL statement, and obtains some metadata about the result
@ -123,8 +123,8 @@ class DboSource extends DataSource
* @param string $sql * @param string $sql
* @return unknown * @return unknown
*/ */
function execute($sql) function execute($sql)
{ {
$t = getMicrotime(); $t = getMicrotime();
$this->_result = $this->_execute($sql); $this->_result = $this->_execute($sql);
@ -142,7 +142,7 @@ class DboSource extends DataSource
{ {
return $this->_result; return $this->_result;
} }
} }
/** /**
* Returns a single row of results from the _last_ SQL query. * Returns a single row of results from the _last_ SQL query.
@ -150,8 +150,8 @@ class DboSource extends DataSource
* @param resource $res * @param resource $res
* @return array A single row of results * @return array A single row of results
*/ */
function fetchArray ($assoc=false) function fetchArray ($assoc=false)
{ {
if ($assoc === false) if ($assoc === false)
{ {
return $this->fetchRow(); return $this->fetchRow();
@ -160,7 +160,7 @@ class DboSource extends DataSource
{ {
return $this->fetchRow($assoc); return $this->fetchRow($assoc);
} }
} }
/** /**
* Returns a single row of results for a _given_ SQL query. * Returns a single row of results for a _given_ SQL query.
@ -168,14 +168,14 @@ class DboSource extends DataSource
* @param string $sql SQL statement * @param string $sql SQL statement
* @return array A single row of results * @return array A single row of results
*/ */
function one ($sql) function one ($sql)
{ {
if ($this->execute($sql)) if ($this->execute($sql))
{ {
return $this->fetchArray(); return $this->fetchArray();
} }
return false; return false;
} }
/** /**
* Returns an array of all result rows for a given SQL query. * Returns an array of all result rows for a given SQL query.
@ -184,8 +184,8 @@ class DboSource extends DataSource
* @param string $sql SQL statement * @param string $sql SQL statement
* @return array Array of resultset rows, or false if no rows matched * @return array Array of resultset rows, or false if no rows matched
*/ */
function fetchAll ($sql) function fetchAll ($sql)
{ {
if($this->execute($sql)) if($this->execute($sql))
{ {
$out = array(); $out = array();
@ -199,7 +199,7 @@ class DboSource extends DataSource
{ {
return false; return false;
} }
} }
/** /**
* Returns a single field of the first of query results for a given SQL query, or false if empty. * Returns a single field of the first of query results for a given SQL query, or false if empty.
@ -226,18 +226,18 @@ class DboSource extends DataSource
* *
* @return boolean True if the database is connected, else false * @return boolean True if the database is connected, else false
*/ */
function isConnected() function isConnected()
{ {
return $this->connected; return $this->connected;
} }
/** /**
* Outputs the contents of the queries log. * Outputs the contents of the queries log.
* *
* @param boolean $sorted * @param boolean $sorted
*/ */
function showLog($sorted=false) function showLog($sorted=false)
{ {
$log = $sorted? $log = $sorted?
sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC): sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC):
$this->_queriesLog; $this->_queriesLog;
@ -259,15 +259,15 @@ class DboSource extends DataSource
} }
print("</table>\n"); print("</table>\n");
} }
/** /**
* Log given SQL query. * Log given SQL query.
* *
* @param string $sql SQL statement * @param string $sql SQL statement
*/ */
function logQuery($sql) function logQuery($sql)
{ {
$this->_queriesCnt++; $this->_queriesCnt++;
$this->_queriesTime += $this->took; $this->_queriesTime += $this->took;
@ -286,10 +286,10 @@ class DboSource extends DataSource
if ($this->error) if ($this->error)
{ {
return false; // shouldn't we be logging errors somehow? return false;// shouldn't we be logging errors somehow?
// TODO: Add hook to error log // TODO: Add hook to error log
} }
} }
/** /**
* Output information about an SQL query. The SQL statement, number of rows in resultset, * Output information about an SQL query. The SQL statement, number of rows in resultset,
@ -299,22 +299,22 @@ class DboSource extends DataSource
*/ */
function showQuery($sql) function showQuery($sql)
{ {
$error = $this->error; $error = $this->error;
if (strlen($sql) > 200 && !$this->fullDebug) if (strlen($sql) > 200 && !$this->fullDebug)
{ {
$sql = substr($sql, 0, 200) .'[...]'; $sql = substr($sql, 0, 200) .'[...]';
} }
if ($this->debug || $error) if ($this->debug || $error)
{ {
print("<p style=\"text-align:left\"><b>Query:</b> {$sql} <small>[Aff:{$this->affected} Num:{$this->numRows} Took:{$this->took}ms]</small>"); print("<p style=\"text-align:left\"><b>Query:</b> {$sql} <small>[Aff:{$this->affected} Num:{$this->numRows} Took:{$this->took}ms]</small>");
if($error) if($error)
{ {
print("<br /><span style=\"color:Red;text-align:left\"><b>ERROR:</b> {$this->error}</span>"); print("<br /><span style=\"color:Red;text-align:left\"><b>ERROR:</b> {$this->error}</span>");
} }
print('</p>'); print('</p>');
} }
} }
/** /**
@ -403,7 +403,7 @@ class DboSource extends DataSource
} }
} }
// Build final query SQL // Build final query SQL
$query = $this->generateAssociationQuery($model, $null, null, null, null, $queryData, false, $null); $query = $this->generateAssociationQuery($model, $null, null, null, null, $queryData, false, $null);
$resultSet = $this->fetchAll($query); $resultSet = $this->fetchAll($query);
@ -421,7 +421,7 @@ class DboSource extends DataSource
// Fetch recursively on belongsTo and hasOne // Fetch recursively on belongsTo and hasOne
if ($model->recursive > 1) if ($model->recursive > 1)
{ {
//$this->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1); //$this->queryAssociation($model, $linkModel, $type, $assoc, $assocData, $array, true, $resultSet, $model->recursive - 1);
} }
} }
} }
@ -593,7 +593,7 @@ class DboSource extends DataSource
{ {
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);
} }
else else
{ {
@ -606,7 +606,7 @@ class DboSource extends DataSource
{ {
$joinFields = null; $joinFields = null;
} }
// Generates primary query // Generates primary query
$sql = 'SELECT ' . join(', ', $this->fields($model, $model->name, $queryData['fields'])) .$joinFields. ' FROM '; $sql = 'SELECT ' . join(', ', $this->fields($model, $model->name, $queryData['fields'])) .$joinFields. ' FROM ';
$sql .= $this->name($model->table).' AS '; $sql .= $this->name($model->table).' AS ';
$sql .= $this->name($model->name).' ' . join(' ', $queryData['joins']).' '; $sql .= $this->name($model->name).' ' . join(' ', $queryData['joins']).' ';
@ -639,7 +639,7 @@ class DboSource extends DataSource
$sql .= ' FROM '.$this->name($linkModel->table).' AS '.$alias; $sql .= ' FROM '.$this->name($linkModel->table).' AS '.$alias;
$conditions = $queryData['conditions']; $conditions = $queryData['conditions'];
$condition = $model->escapeField($assocData['foreignKey']); $condition = $model->escapeField($assocData['foreignKey']);
$condition .= '={$__cake_foreignKey__$}'; $condition .= '={$__cakeForeignKey__$}';
if (is_array($conditions)) if (is_array($conditions))
{ {
$conditions[] = $condition; $conditions[] = $condition;
@ -702,7 +702,7 @@ class DboSource extends DataSource
$conditions = $assocData['conditions']; $conditions = $assocData['conditions'];
$condition = $linkModel->escapeField($linkModel->primaryKey); $condition = $linkModel->escapeField($linkModel->primaryKey);
$condition .= '={$__cake_id__$}'; $condition .= '={$__cakeID__$}';
if (is_array($conditions)) if (is_array($conditions))
{ {
@ -775,12 +775,12 @@ class DboSource extends DataSource
if (is_array($conditions)) if (is_array($conditions))
{ {
$conditions[$alias.'.'.$assocData['foreignKey']] = '{$__cake_id__$}'; $conditions[$alias.'.'.$assocData['foreignKey']] = '{$__cakeID__$}';
} }
else else
{ {
$cond = $this->name($alias).'.'.$this->name($assocData['foreignKey']); $cond = $this->name($alias).'.'.$this->name($assocData['foreignKey']);
$cond .= '={$__cake_id__$}'; $cond .= '={$__cakeID__$}';
if (trim($conditions) != '') if (trim($conditions) != '')
{ {
@ -805,7 +805,7 @@ class DboSource extends DataSource
$sql = 'SELECT '.join(', ', $this->fields($linkModel, $alias, $assocData['fields'])); $sql = 'SELECT '.join(', ', $this->fields($linkModel, $alias, $assocData['fields']));
$sql .= ' FROM '.$this->name($linkModel->table).' AS '.$this->name($alias); $sql .= ' FROM '.$this->name($linkModel->table).' AS '.$this->name($alias);
$sql .= ' JOIN '.$joinTbl.' ON '.$joinTbl; $sql .= ' JOIN '.$joinTbl.' ON '.$joinTbl;
$sql .= '.'.$this->name($assocData['foreignKey']).'={$__cake_id__$}'; $sql .= '.'.$this->name($assocData['foreignKey']).'={$__cakeID__$}';
$sql .= ' AND '.$joinTbl.'.'.$this->name($assocData['associationForeignKey']); $sql .= ' AND '.$joinTbl.'.'.$this->name($assocData['associationForeignKey']);
$sql .= ' = '.$this->name($alias).'.'.$this->name($linkModel->primaryKey); $sql .= ' = '.$this->name($alias).'.'.$this->name($linkModel->primaryKey);
@ -971,7 +971,13 @@ class DboSource extends DataSource
} }
$count = count($fields); $count = count($fields);
if ($count >= 1 && $fields[0] != '*' && strpos($fields[0], 'COUNT(*)') === false) if ($count >= 1 && $fields[0] != '*'
&& strpos($fields[0], 'COUNT(') === false
&& strpos($fields[0], 'MAX(') === false
&& strpos($fields[0], 'MIN(') === false
&& strpos($fields[0], 'DISTINCT') === false
&& strpos($fields[0], 'SUM(') === false
&& strpos($fields[0], 'CONCAT(') === false)
{ {
for ($i = 0; $i < $count; $i++) for ($i = 0; $i < $count; $i++)
{ {
@ -1010,6 +1016,16 @@ class DboSource extends DataSource
{ {
$conditions = ' 1 = 1'; $conditions = ' 1 = 1';
} }
else
{
preg_match_all('/([a-zA-Z0-9_]{1,})\\.([a-zA-Z0-9_]{1,})/', $conditions, $result, PREG_PATTERN_ORDER);
$pregCount = count($result[0]);
for ($i = 0; $i < $pregCount; $i++)
{
$conditions = preg_replace('/'.$result[0][$i].'/', $this->name($result[0][$i]), $conditions);
}
}
return $rt.$conditions; return $rt.$conditions;
} }
elseif (is_array($conditions)) elseif (is_array($conditions))
@ -1032,7 +1048,7 @@ class DboSource extends DataSource
} }
else else
{ {
if (($value != '{$__cake_id__$}') && ($value != '{$__cake_foreignKey__$}')) if (($value != '{$__cakeID__$}') && ($value != '{$__cakeForeignKey__$}'))
{ {
$value = $this->value($value); $value = $this->value($value);
} }
@ -1118,12 +1134,12 @@ class DboSource extends DataSource
*/ */
function close () function close ()
{ {
if ($this->fullDebug) if ($this->fullDebug)
{ {
$this->showLog(); $this->showLog();
} }
$this->_conn = NULL; $this->_conn = NULL;
$this->connected = false; $this->connected = false;
} }
/** /**
@ -1147,10 +1163,10 @@ class DboSource extends DataSource
* @param string $sql SQL WHERE clause (condition only, not the "WHERE" part) * @param string $sql SQL WHERE clause (condition only, not the "WHERE" part)
* @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($table, $sql) function hasAny($table, $sql)
{ {
$out = $this->one("SELECT COUNT(*) AS count FROM {$table}".($sql? " WHERE {$sql}":"")); $out = $this->one("SELECT COUNT(*) AS count FROM {$table}".($sql? " WHERE {$sql}":""));
return is_array($out)? $out[0]['count']: false; return is_array($out)? $out[0]['count']: false;
} }
} }
?> ?>

View file

@ -50,7 +50,7 @@ class DboAdodb extends DboSource
* *
* @var unknown_type * @var unknown_type
*/ */
var $description = "ADOdb DBO Driver"; var $description = "ADOdb DBO Driver";
/** /**
@ -59,15 +59,15 @@ class DboAdodb extends DboSource
* @var ADOConnection The connection object. * @var ADOConnection The connection object.
* @access private * @access private
*/ */
var $_adodb = null; var $_adodb = null;
/** /**
* Connects to the database using options in the given configuration array. * Connects to the database using options in the given configuration array.
* *
* @param array $config Configuration array for connecting * @param array $config Configuration array for connecting
*/ */
function connect () function connect ()
{ {
$config = $this->config; $config = $this->config;
$persistent = strrpos($config['connect'], '|p'); $persistent = strrpos($config['connect'], '|p');
if($persistent === FALSE){ if($persistent === FALSE){
@ -86,19 +86,19 @@ class DboAdodb extends DboSource
if(!$this->connected) if(!$this->connected)
{ {
//die('Could not connect to DB.'); //die('Could not connect to DB.');
} }
} }
/** /**
* Disconnects from database. * Disconnects from database.
* *
* @return boolean True if the database could be disconnected, else false * @return boolean True if the database could be disconnected, else false
*/ */
function disconnect () function disconnect ()
{ {
return $this->_adodb->Close(); return $this->_adodb->Close();
} }
/** /**
* Executes given SQL statement. * Executes given SQL statement.
@ -106,20 +106,20 @@ class DboAdodb extends DboSource
* @param string $sql SQL statement * @param string $sql SQL statement
* @return resource Result resource identifier * @return resource Result resource identifier
*/ */
function execute ($sql) function execute ($sql)
{ {
return $this->_adodb->execute($sql); return $this->_adodb->execute($sql);
} }
/** /**
* Returns a row from given resultset as an array . * Returns a row from given resultset as an array .
* *
* @return array The fetched row as an array * @return array The fetched row as an array
*/ */
function fetchRow () function fetchRow ()
{ {
return $this->_result->FetchRow(); return $this->_result->FetchRow();
} }
/** /**
* Begin a transaction * Begin a transaction
@ -181,8 +181,8 @@ class DboAdodb extends DboSource
* *
* @return array Array of tablenames in the database * @return array Array of tablenames in the database
*/ */
function tablesList () function tablesList ()
{ {
$tables = $this->_adodb->MetaTables('TABLES'); $tables = $this->_adodb->MetaTables('TABLES');
if (!sizeof($tables) > 0) { if (!sizeof($tables) > 0) {
@ -190,7 +190,7 @@ class DboAdodb extends DboSource
exit; exit;
} }
return $tables; return $tables;
} }
/** /**
* Returns an array of the fields in given table name. * Returns an array of the fields in given table name.
@ -198,8 +198,8 @@ class DboAdodb extends DboSource
* @param string $tableName Name of database table to inspect * @param string $tableName Name of database table to inspect
* @return array Fields in table. Keys are name and type * @return array Fields in table. Keys are name and type
*/ */
function fields ($tableName) function fields ($tableName)
{ {
$data = $this->_adodb->MetaColumns($tableName); $data = $this->_adodb->MetaColumns($tableName);
$fields = false; $fields = false;
@ -207,7 +207,7 @@ class DboAdodb extends DboSource
$fields[] = array('name'=>$item->name, 'type'=>$item->type); $fields[] = array('name'=>$item->name, 'type'=>$item->type);
return $fields; return $fields;
} }
/** /**
* Returns a quoted and escaped string of $data for use in an SQL statement. * Returns a quoted and escaped string of $data for use in an SQL statement.
@ -217,40 +217,40 @@ class DboAdodb extends DboSource
* *
* @todo To be implemented. * @todo To be implemented.
*/ */
function prepareValue ($data) function prepareValue ($data)
{ {
return $this->_adodb->Quote($data); return $this->_adodb->Quote($data);
} }
/** /**
* Returns a formatted error message from previous database operation. * Returns a formatted error message from previous database operation.
* *
* @return string Error message * @return string Error message
*/ */
function lastError () function lastError ()
{ {
return $this->_adodb->ErrorMsg(); return $this->_adodb->ErrorMsg();
} }
/** /**
* Returns number of affected rows in previous database operation, or false if no previous operation exists. * Returns number of affected rows in previous database operation, or false if no previous operation exists.
* *
* @return int Number of affected rows * @return int Number of affected rows
*/ */
function lastAffected () function lastAffected ()
{ {
return $this->_adodb->Affected_Rows(); return $this->_adodb->Affected_Rows();
} }
/** /**
* Returns number of rows in previous resultset, or false if no previous resultset exists. * Returns number of rows in previous resultset, or false if no previous resultset exists.
* *
* @return int Number of rows in resultset * @return int Number of rows in resultset
*/ */
function lastNumRows () function lastNumRows ()
{ {
return $this->_result? $this->_result->RecordCount(): false; return $this->_result? $this->_result->RecordCount(): false;
} }
/** /**
* Returns the ID generated from the previous INSERT operation. * Returns the ID generated from the previous INSERT operation.
@ -259,10 +259,10 @@ class DboAdodb extends DboSource
* *
* @Returns the last autonumbering ID inserted. Returns false if function not supported. * @Returns the last autonumbering ID inserted. Returns false if function not supported.
*/ */
function lastInsertId () function lastInsertId ()
{ {
return $this->_adodb->Insert_ID(); return $this->_adodb->Insert_ID();
} }
/** /**
* Returns a LIMIT statement in the correct format for the particular database. * Returns a LIMIT statement in the correct format for the particular database.
@ -272,12 +272,12 @@ class DboAdodb extends DboSource
* @return string SQL limit/offset statement * @return string SQL limit/offset statement
* @todo Please change output string to whatever select your database accepts. adodb doesn't allow us to get the correct limit string out of it. * @todo Please change output string to whatever select your database accepts. adodb doesn't allow us to get the correct limit string out of it.
*/ */
function selectLimit ($limit, $offset=null) function selectLimit ($limit, $offset=null)
{ {
return " LIMIT {$limit}".($offset? "{$offset}": null); return " LIMIT {$limit}".($offset? "{$offset}": null);
// please change to whatever select your database accepts // please change to whatever select your database accepts
// adodb doesn't allow us to get the correct limit string out of it // adodb doesn't allow us to get the correct limit string out of it
} }
} }

View file

@ -44,22 +44,22 @@ uses('object');
* Example usage: * Example usage:
* *
* <code> * <code>
* require('dbo_mysql.php'); // or 'dbo_postgres.php' * require('dbo_mysql.php');// or 'dbo_postgres.php'
* *
* // create and connect the object *// create and connect the object
* $db = new DBO_MySQL(array( // or 'DBO_Postgres' * $db = new DBO_MySQL(array(// or 'DBO_Postgres'
* 'host'=>'localhost', * 'host'=>'localhost',
* 'login'=>'username', * 'login'=>'username',
* 'password'=>'password', * 'password'=>'password',
* 'database'=>'database')); * 'database'=>'database'));
* *
* // read the whole query result array (of rows) *// read the whole query result array (of rows)
* $all_rows = $db->fetchAll("SELECT a,b,c FROM table"); * $all_rows = $db->fetchAll("SELECT a,b,c FROM table");
* *
* // read the first row with debugging on *// read the first row with debugging on
* $first_row_only = $db->one("SELECT a,b,c FROM table WHERE a=1", TRUE); * $first_row_only = $db->one("SELECT a,b,c FROM table WHERE a=1", TRUE);
* *
* // emulate the usual way of reading query results *// emulate the usual way of reading query results
* if ($db->query("SELECT a,b,c FROM table")) * if ($db->query("SELECT a,b,c FROM table"))
* { * {
* while ($row = $db->fetchArray()) * while ($row = $db->fetchArray())
@ -68,7 +68,7 @@ uses('object');
* } * }
* } * }
* *
* // show a log of all queries, sorted by execution time *// show a log of all queries, sorted by execution time
* $db->showLog(TRUE); * $db->showLog(TRUE);
* </code> * </code>
* *
@ -85,7 +85,7 @@ class DBO extends Object
* @var boolean * @var boolean
* @access public * @access public
*/ */
var $connected=FALSE; var $connected=FALSE;
/** /**
* Connection configuration. * Connection configuration.
@ -93,7 +93,7 @@ class DBO extends Object
* @var array * @var array
* @access public * @access public
*/ */
var $config=FALSE; var $config=FALSE;
/** /**
* Enter description here... * Enter description here...
@ -101,7 +101,7 @@ class DBO extends Object
* @var boolean * @var boolean
* @access public * @access public
*/ */
var $debug=FALSE; var $debug=FALSE;
/** /**
* Enter description here... * Enter description here...
@ -109,7 +109,7 @@ class DBO extends Object
* @var boolean * @var boolean
* @access public * @access public
*/ */
var $fullDebug=FALSE; var $fullDebug=FALSE;
/** /**
* Enter description here... * Enter description here...
@ -117,7 +117,7 @@ class DBO extends Object
* @var unknown_type * @var unknown_type
* @access public * @access public
*/ */
var $error=NULL; var $error=NULL;
/** /**
* String to hold how many rows were affected by the last SQL operation. * String to hold how many rows were affected by the last SQL operation.
@ -125,7 +125,7 @@ class DBO extends Object
* @var unknown_type * @var unknown_type
* @access public * @access public
*/ */
var $affected=NULL; var $affected=NULL;
/** /**
* Number of rows in current resultset * Number of rows in current resultset
@ -133,7 +133,7 @@ class DBO extends Object
* @var int * @var int
* @access public * @access public
*/ */
var $numRows=NULL; var $numRows=NULL;
/** /**
* Time the last query took * Time the last query took
@ -141,7 +141,7 @@ class DBO extends Object
* @var unknown_type * @var unknown_type
* @access public * @access public
*/ */
var $took=NULL; var $took=NULL;
/** /**
* Enter description here... * Enter description here...
@ -149,7 +149,7 @@ class DBO extends Object
* @var unknown_type * @var unknown_type
* @access private * @access private
*/ */
var $_conn=NULL; var $_conn=NULL;
/** /**
* Enter description here... * Enter description here...
@ -157,7 +157,7 @@ class DBO extends Object
* @var unknown_type * @var unknown_type
* @access private * @access private
*/ */
var $_result=NULL; var $_result=NULL;
/** /**
* Queries count. * Queries count.
@ -165,7 +165,7 @@ class DBO extends Object
* @var unknown_type * @var unknown_type
* @access private * @access private
*/ */
var $_queriesCnt=0; var $_queriesCnt=0;
/** /**
* Total duration of all queries. * Total duration of all queries.
@ -173,7 +173,7 @@ class DBO extends Object
* @var unknown_type * @var unknown_type
* @access private * @access private
*/ */
var $_queriesTime=NULL; var $_queriesTime=NULL;
/** /**
* Enter description here... * Enter description here...
@ -181,7 +181,7 @@ class DBO extends Object
* @var unknown_type * @var unknown_type
* @access private * @access private
*/ */
var $_queriesLog=array(); var $_queriesLog=array();
/** /**
* Maximum number of items in query log, to prevent query log taking over * Maximum number of items in query log, to prevent query log taking over
@ -191,7 +191,7 @@ class DBO extends Object
* @var int Maximum number of queries in the queries log. * @var int Maximum number of queries in the queries log.
* @access private * @access private
*/ */
var $_queriesLogMax=200; var $_queriesLogMax=200;
/** /**
@ -200,22 +200,22 @@ class DBO extends Object
* @param array $config * @param array $config
* @return unknown * @return unknown
*/ */
function __construct($config=NULL) function __construct($config=NULL)
{ {
$this->debug = DEBUG > 0; $this->debug = DEBUG > 0;
$this->fullDebug = DEBUG > 1; $this->fullDebug = DEBUG > 1;
parent::__construct(); parent::__construct();
return $this->connect($config); return $this->connect($config);
} }
/** /**
* Destructor. Closes connection to the database. * Destructor. Closes connection to the database.
* *
*/ */
function __destructor() function __destructor()
{ {
$this->close(); $this->close();
} }
/** /**
* Returns a string with a USE [databasename] SQL statement. * Returns a string with a USE [databasename] SQL statement.
@ -223,22 +223,22 @@ class DBO extends Object
* @param string $db_name Name of database to use * @param string $db_name Name of database to use
* @return unknown Result of the query * @return unknown Result of the query
*/ */
function useDb($db_name) function useDb($db_name)
{ {
return $this->query("USE {$db_name}"); return $this->query("USE {$db_name}");
} }
/** /**
* Disconnects database, kills the connection and says the connection is closed, and if DEBUG is turned on, the log for this object is shown. * Disconnects database, kills the connection and says the connection is closed, and if DEBUG is turned on, the log for this object is shown.
* *
*/ */
function close () function close ()
{ {
if ($this->fullDebug) $this->showLog(); if ($this->fullDebug) $this->showLog();
$this->disconnect(); $this->disconnect();
$this->_conn = NULL; $this->_conn = NULL;
$this->connected = false; $this->connected = false;
} }
/** /**
* Prepares a value, or an array of values for database queries by quoting and escaping them. * Prepares a value, or an array of values for database queries by quoting and escaping them.
@ -246,8 +246,8 @@ class DBO extends Object
* @param mixed $data A value or an array of values to prepare. * @param mixed $data A value or an array of values to prepare.
* @return mixed Prepared value or array of values. * @return mixed Prepared value or array of values.
*/ */
function prepare ($data) function prepare ($data)
{ {
if (is_array($data)) if (is_array($data))
{ {
$out = null; $out = null;
@ -261,12 +261,12 @@ class DBO extends Object
{ {
return $this->prepareValue($data); return $this->prepareValue($data);
} }
} }
function sources () function sources ()
{ {
return array_map('strtolower', $this->listSources()); return array_map('strtolower', $this->listSources());
} }
/** /**
* Executes given SQL statement. * Executes given SQL statement.
@ -274,11 +274,11 @@ class DBO extends Object
* @param string $sql SQL statement * @param string $sql SQL statement
* @return unknown * @return unknown
*/ */
function rawQuery ($sql) function rawQuery ($sql)
{ {
$this->took = $this->error = $this->numRows = false; $this->took = $this->error = $this->numRows = false;
return $this->execute($sql); return $this->execute($sql);
} }
/** /**
* Queries the database with given SQL statement, and obtains some metadata about the result * Queries the database with given SQL statement, and obtains some metadata about the result
@ -288,8 +288,8 @@ class DBO extends Object
* @param string $sql * @param string $sql
* @return unknown * @return unknown
*/ */
function query($sql) function query($sql)
{ {
$t = getMicrotime(); $t = getMicrotime();
$this->_result = $this->execute($sql); $this->_result = $this->execute($sql);
$this->affected = $this->lastAffected(); $this->affected = $this->lastAffected();
@ -301,7 +301,7 @@ class DBO extends Object
$this->showQuery($sql); $this->showQuery($sql);
return $this->error? false: $this->_result; return $this->error? false: $this->_result;
} }
/** /**
* Returns a single row of results from the _last_ SQL query. * Returns a single row of results from the _last_ SQL query.
@ -309,8 +309,8 @@ class DBO extends Object
* @param resource $res * @param resource $res
* @return array A single row of results * @return array A single row of results
*/ */
function farr ($assoc=false) function farr ($assoc=false)
{ {
if ($assoc === false) if ($assoc === false)
{ {
return $this->fetchRow(); return $this->fetchRow();
@ -319,7 +319,7 @@ class DBO extends Object
{ {
return $this->fetchRow($assoc); return $this->fetchRow($assoc);
} }
} }
/** /**
* Returns a single row of results for a _given_ SQL query. * Returns a single row of results for a _given_ SQL query.
@ -327,10 +327,10 @@ class DBO extends Object
* @param string $sql SQL statement * @param string $sql SQL statement
* @return array A single row of results * @return array A single row of results
*/ */
function one ($sql) function one ($sql)
{ {
return $this->query($sql)? $this->fetchArray(): false; return $this->query($sql)? $this->fetchArray(): false;
} }
/** /**
* Returns an array of all result rows for a given SQL query. * Returns an array of all result rows for a given SQL query.
@ -339,8 +339,8 @@ class DBO extends Object
* @param string $sql SQL statement * @param string $sql SQL statement
* @return array Array of resultset rows, or false if no rows matched * @return array Array of resultset rows, or false if no rows matched
*/ */
function all ($sql) function all ($sql)
{ {
if($this->query($sql)) if($this->query($sql))
{ {
$out=array(); $out=array();
@ -354,7 +354,7 @@ class DBO extends Object
{ {
return false; return false;
} }
} }
/** /**
* Returns a single field of the first of query results for a given SQL query, or false if empty. * Returns a single field of the first of query results for a given SQL query, or false if empty.
@ -363,11 +363,11 @@ class DBO extends Object
* @param string $sql SQL query * @param string $sql SQL query
* @return unknown * @return unknown
*/ */
function field ($name, $sql) function field ($name, $sql)
{ {
$data = $this->one($sql); $data = $this->one($sql);
return empty($data[$name])? false: $data[$name]; return empty($data[$name])? false: $data[$name];
} }
/** /**
* Checks if the specified table contains any record matching specified SQL * Checks if the specified table contains any record matching specified SQL
@ -376,29 +376,29 @@ class DBO extends Object
* @param string $sql SQL WHERE clause (condition only, not the "WHERE" part) * @param string $sql SQL WHERE clause (condition only, not the "WHERE" part)
* @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($table, $sql) function hasAny($table, $sql)
{ {
$out = $this->one("SELECT COUNT(*) AS count FROM {$table}".($sql? " WHERE {$sql}":"")); $out = $this->one("SELECT COUNT(*) AS count FROM {$table}".($sql? " WHERE {$sql}":""));
return is_array($out)? $out[0]['count']: false; return is_array($out)? $out[0]['count']: false;
} }
/** /**
* Checks if it's connected to the database * Checks if it's connected to the database
* *
* @return boolean True if the database is connected, else false * @return boolean True if the database is connected, else false
*/ */
function isConnected() function isConnected()
{ {
return $this->connected; return $this->connected;
} }
/** /**
* Outputs the contents of the log. * Outputs the contents of the log.
* *
* @param boolean $sorted * @param boolean $sorted
*/ */
function showLog($sorted=false) function showLog($sorted=false)
{ {
$log = $sorted? $log = $sorted?
sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC): sortByKey($this->_queriesLog, 'took', 'desc', SORT_NUMERIC):
$this->_queriesLog; $this->_queriesLog;
@ -412,15 +412,15 @@ class DBO extends Object
} }
print("</table>\n"); print("</table>\n");
} }
/** /**
* Log given SQL query. * Log given SQL query.
* *
* @param string $sql SQL statement * @param string $sql SQL statement
*/ */
function logQuery($sql) function logQuery($sql)
{ {
$this->_queriesCnt++; $this->_queriesCnt++;
$this->_queriesTime += $this->took; $this->_queriesTime += $this->took;
@ -438,8 +438,8 @@ class DBO extends Object
} }
if ($this->error) if ($this->error)
return false; // shouldn't we be logging errors somehow? return false;// shouldn't we be logging errors somehow?
} }
/** /**
* Output information about an SQL query. The SQL statement, number of rows in resultset, * Output information about an SQL query. The SQL statement, number of rows in resultset,
@ -447,8 +447,8 @@ class DBO extends Object
* *
* @param string $sql * @param string $sql
*/ */
function showQuery($sql) function showQuery($sql)
{ {
$error = $this->error; $error = $this->error;
if (strlen($sql)>200 && !$this->fullDebug) if (strlen($sql)>200 && !$this->fullDebug)
@ -465,7 +465,7 @@ class DBO extends Object
} }
print('</p>'); print('</p>');
} }
} }
} }
?> ?>

View file

@ -44,99 +44,99 @@ class DBO_generic extends DBO
* Abstract method defined in subclasses. * Abstract method defined in subclasses.
* *
*/ */
function connect ($config) function connect ($config)
{ {
} }
/** /**
* Abstract method defined in subclasses. * Abstract method defined in subclasses.
* *
*/ */
function disconnect () function disconnect ()
{ {
} }
/** /**
* Abstract method defined in subclasses. * Abstract method defined in subclasses.
* *
*/ */
function execute ($sql) function execute ($sql)
{ {
} }
/**
* Abstract method defined in subclasses.
*
*
*/
function fetchRow ()
{
}
/** /**
* Abstract method defined in subclasses. * Abstract method defined in subclasses.
* *
* *
*/ */
function tablesList () function fetchRow ()
{ {
} }
/**
* Abstract method defined in subclasses.
*
*
*/
function tablesList ()
{
}
/** /**
* Abstract method defined in subclasses. * Abstract method defined in subclasses.
* *
*/ */
function fields ($tableName) function fields ($tableName)
{ {
} }
/** /**
* Abstract method defined in subclasses. * Abstract method defined in subclasses.
* *
*/ */
function prepareValue ($data) function prepareValue ($data)
{ {
} }
/** /**
* Abstract method defined in subclasses. * Abstract method defined in subclasses.
* *
*/ */
function lastError () function lastError ()
{ {
} }
/** /**
* Abstract method defined in subclasses. * Abstract method defined in subclasses.
* *
*/ */
function lastAffected () function lastAffected ()
{ {
} }
/** /**
* Abstract method defined in subclasses. * Abstract method defined in subclasses.
* *
*/ */
function lastNumRows () function lastNumRows ()
{ {
} }
/** /**
* Abstract method defined in subclasses. * Abstract method defined in subclasses.
* *
*/ */
function lastInsertId () function lastInsertId ()
{ {
} }
/** /**
* Abstract method defined in subclasses. * Abstract method defined in subclasses.
* *
*/ */
function selectLimit ($limit, $offset=null) function selectLimit ($limit, $offset=null)
{ {
} }
} }

View file

@ -58,11 +58,11 @@ class DboMysql extends DboSource
* @var unknown_type * @var unknown_type
*/ */
var $_baseConfig = array('persistent' => true, var $_baseConfig = array('persistent' => true,
'host' => 'localhost', 'host' => 'localhost',
'login' => 'root', 'login' => 'root',
'password' => '', 'password' => '',
'database' => 'cake', 'database' => 'cake',
'port' => 3306); 'port' => 3306);
/** /**
* Enter description here... * Enter description here...
@ -73,9 +73,9 @@ class DboMysql extends DboSource
'string' => array('name' => 'varchar', 'limit' => '255'), 'string' => array('name' => 'varchar', 'limit' => '255'),
'text' => array('name' => 'text'), 'text' => array('name' => 'text'),
'integer' => array('name' => 'int', 'limit' => '11'), 'integer' => array('name' => 'int', 'limit' => '11'),
'float' => array('name' => 'float'), 'float' => array('name' => 'float'),
'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d h:i:s'), 'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d h:i:s'),
'timestamp' => array('name' => 'datetime', 'format' => 'Y-m-d h:i:s'), 'timestamp' => array('name' => 'datetime', 'format' => 'Y-m-d h:i:s'),
'time' => array('name' => 'time', 'format' => 'h:i:s'), 'time' => array('name' => 'time', 'format' => 'h:i:s'),
'date' => array('name' => 'date', 'format' => 'Y-m-d'), 'date' => array('name' => 'date', 'format' => 'Y-m-d'),
'binary' => array('name' => 'blob'), 'binary' => array('name' => 'blob'),
@ -115,7 +115,7 @@ class DboMysql extends DboSource
} }
else else
{ {
//die('Could not connect to DB.'); //die('Could not connect to DB.');
} }
} }
@ -257,7 +257,12 @@ class DboMysql extends DboSource
{ {
return '*'; return '*';
} }
return '`'. ereg_replace('\.', '`.`', $data) .'`'; $pos = strpos($data, '`');
if ($pos === false)
{
$data = '`'. str_replace('.', '`.`', $data) .'`';
}
return $data;
} }
/** /**
@ -294,7 +299,7 @@ class DboMysql extends DboSource
$return = $data; $return = $data;
} }
return $return; return $return;
} }
/** /**
* Translates between PHP boolean values and MySQL (faked) boolean values * Translates between PHP boolean values and MySQL (faked) boolean values

View file

@ -29,8 +29,8 @@
*/ */
/** /**
* Create an include path required PEAR libraries. * Create an include path required PEAR libraries.
*/ */
uses('model'.DS.'dbo'.DS.'dbo'); uses('model'.DS.'dbo'.DS.'dbo');
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . PEAR); ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . PEAR);
vendor('Pear/DB'); vendor('Pear/DB');
@ -53,21 +53,21 @@ class DBO_Pear extends DBO
* @var DB The connection object. * @var DB The connection object.
* @access private * @access private
*/ */
var $_pear = null; var $_pear = null;
/** /**
* Connects to the database using options in the given configuration array. * Connects to the database using options in the given configuration array.
* *
* @param array $config Configuration array for connecting * @param array $config Configuration array for connecting
* @return boolean True if the database could be connected, else false * @return boolean True if the database could be connected, else false
*/ */
function connect ($config) function connect ($config)
{ {
$this->config = $config; $this->config = $config;
$dsn = $config['driver'].'://'.$config['login'].':'.$config['password'].'@'.$config['host'].'/'.$config['database']; $dsn = $config['driver'].'://'.$config['login'].':'.$config['password'].'@'.$config['host'].'/'.$config['database'];
$options = array( $options = array(
'debug' => DEBUG-1, 'debug' => DEBUG-1,
'portability' => DB_PORTABILITY_ALL, 'portability' => DB_PORTABILITY_ALL,
); );
@ -76,47 +76,47 @@ class DBO_Pear extends DBO
return !(PEAR::isError($this->_pear)); return !(PEAR::isError($this->_pear));
} }
/** /**
* Disconnects from database. * Disconnects from database.
* *
* @return boolean True if the database could be disconnected, else false * @return boolean True if the database could be disconnected, else false
*/ */
function disconnect () function disconnect ()
{ {
die('Please implement DBO::disconnect() first.'); die('Please implement DBO::disconnect() first.');
} }
/** /**
* Executes given SQL statement. * Executes given SQL statement.
* *
* @param string $sql SQL statement * @param string $sql SQL statement
* @return resource Result resource identifier * @return resource Result resource identifier
*/ */
function execute ($sql) function execute ($sql)
{ {
return $this->_pear->query($sql); return $this->_pear->query($sql);
} }
/** /**
* Returns a row from given resultset as an array . * Returns a row from given resultset as an array .
* *
* @return array The fetched row as an array * @return array The fetched row as an array
*/ */
function fetchRow () function fetchRow ()
{ {
return $this->_result->fetchRow(DB_FETCHMODE_ASSOC); return $this->_result->fetchRow(DB_FETCHMODE_ASSOC);
} }
/** /**
* Returns an array of tables in the database. If there are no tables, an error is raised and the application exits. * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
* :WARNING: :TODO: POSTGRESQL & MYSQL ONLY! PEAR::DB doesn't support universal table listing. * :WARNING: :TODO: POSTGRESQL & MYSQL ONLY! PEAR::DB doesn't support universal table listing.
* *
* @return array Array of tablenames in the database * @return array Array of tablenames in the database
*/ */
function tablesList () function tablesList ()
{ {
$driver = $this->config['driver']; $driver = $this->config['driver'];
$tables = array(); $tables = array();
@ -159,16 +159,16 @@ class DBO_Pear extends DBO
{ {
return $tables; return $tables;
} }
} }
/** /**
* Returns an array of the fields in given table name. * Returns an array of the fields in given table name.
* *
* @param string $tableName Name of database table to inspect * @param string $tableName Name of database table to inspect
* @return array Fields in table. Keys are name and type * @return array Fields in table. Keys are name and type
*/ */
function fields ($tableName) function fields ($tableName)
{ {
$data = $this->_pear->tableInfo($tableName); $data = $this->_pear->tableInfo($tableName);
$fields = false; $fields = false;
@ -176,47 +176,47 @@ class DBO_Pear extends DBO
$fields[] = array('name'=>$item['name'], 'type'=>$item['type']); $fields[] = array('name'=>$item['name'], 'type'=>$item['type']);
return $fields; return $fields;
} }
/** /**
* Returns a quoted and escaped string of $data for use in an SQL statement. * 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 $data String to be prepared for use in an SQL statement
* @return string Quoted and escaped * @return string Quoted and escaped
*/ */
function prepareValue ($data) function prepareValue ($data)
{ {
return $this->_pear->quoteSmart($data); return $this->_pear->quoteSmart($data);
} }
/** /**
* Returns a formatted error message from previous database operation. * Returns a formatted error message from previous database operation.
* *
* @return string Error message * @return string Error message
*/ */
function lastError () function lastError ()
{ {
return PEAR::isError($this->_result)? $this->_result->getMessage(): null; return PEAR::isError($this->_result)? $this->_result->getMessage(): null;
} }
/** /**
* Returns number of affected rows in previous database operation. If no previous operation exists, this returns false. * Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
* *
* @return int Number of affected rows * @return int Number of affected rows
*/ */
function lastAffected () function lastAffected ()
{ {
return $this->_pear->affectedRows(); return $this->_pear->affectedRows();
} }
/** /**
* Returns number of rows in previous resultset. If no previous resultset exists, * Returns number of rows in previous resultset. If no previous resultset exists,
* this returns false. * this returns false.
* *
* @return int Number of rows in resultset * @return int Number of rows in resultset
*/ */
function lastNumRows () function lastNumRows ()
{ {
if (method_exists($this->_result, 'numRows')) if (method_exists($this->_result, 'numRows'))
{ {
return $this->_result->numRows(); return $this->_result->numRows();
@ -225,18 +225,18 @@ class DBO_Pear extends DBO
{ {
return false; return false;
} }
} }
/** /**
* Returns the ID generated from the previous INSERT operation. * Returns the ID generated from the previous INSERT operation.
* *
* @param string $table Name of the database table * @param string $table Name of the database table
* @return int * @return int
*/ */
function lastInsertId ($table) function lastInsertId ($table)
{ {
return $this->field('id', "SELECT MAX(id) FROM {$table}"); return $this->field('id', "SELECT MAX(id) FROM {$table}");
} }
/** /**
* Returns a limit statement in the correct format for the particular database. * Returns a limit statement in the correct format for the particular database.
@ -245,10 +245,10 @@ class DBO_Pear extends DBO
* @param int $offset Offset from which to start results * @param int $offset Offset from which to start results
* @return string SQL limit/offset statement * @return string SQL limit/offset statement
*/ */
function selectLimit ($limit, $offset='0') function selectLimit ($limit, $offset='0')
{ {
return ' ' . $this->_pear->modifyLimitQuery('', $offset, $limit); return ' ' . $this->_pear->modifyLimitQuery('', $offset, $limit);
} }
} }

View file

@ -29,8 +29,8 @@
*/ */
/** /**
* Include DBO. * Include DBO.
*/ */
uses('model'.DS.'datasources'.DS.'dbo_source'); uses('model'.DS.'datasources'.DS.'dbo_source');
/** /**
@ -45,23 +45,23 @@ uses('model'.DS.'datasources'.DS.'dbo_source');
class DboPostgres extends DboSource class DboPostgres extends DboSource
{ {
var $description = "PostgreSQL DBO Driver"; var $description = "PostgreSQL DBO Driver";
var $_baseConfig = array('persistent' => true, var $_baseConfig = array('persistent' => true,
'host' => 'localhost', 'host' => 'localhost',
'login' => 'root', 'login' => 'root',
'password' => '', 'password' => '',
'database' => 'cake', 'database' => 'cake',
'port' => 3306); 'port' => 3306);
var $columns = array( var $columns = array(
'primary_key' => array('name' => 'serial primary key'), 'primary_key' => array('name' => 'serial primary key'),
'string' => array('name' => 'varchar', 'limit' => '255'), 'string' => array('name' => 'varchar', 'limit' => '255'),
'text' => array('name' => 'text'), 'text' => array('name' => 'text'),
'integer' => array('name' => 'integer'), 'integer' => array('name' => 'integer'),
'float' => array('name' => 'float'), 'float' => array('name' => 'float'),
'datetime' => array('name' => 'timestamp'), 'datetime' => array('name' => 'timestamp'),
'timestamp' => array('name' => 'timestamp'), 'timestamp' => array('name' => 'timestamp'),
'time' => array('name' => 'time'), 'time' => array('name' => 'time'),
'date' => array('name' => 'date'), 'date' => array('name' => 'date'),
'binary' => array('name' => 'bytea'), 'binary' => array('name' => 'bytea'),
@ -69,12 +69,12 @@ class DboPostgres extends DboSource
'number' => array('name' => 'numeric')); 'number' => array('name' => 'numeric'));
/** /**
* Connects to the database using options in the given configuration array. * Connects to the database using options in the given configuration array.
* *
* @return True if successfully connected. * @return True if successfully connected.
*/ */
function connect () function connect ()
{ {
$config = $this->config; $config = $this->config;
$connect = $config['connect']; $connect = $config['connect'];
@ -89,31 +89,31 @@ class DboPostgres extends DboSource
} }
return $this->connected; return $this->connected;
} }
/** /**
* Disconnects from database. * Disconnects from database.
* *
* @return boolean True if the database could be disconnected, else false * @return boolean True if the database could be disconnected, else false
*/ */
function disconnect () function disconnect ()
{ {
return pg_close($this->connection); return pg_close($this->connection);
} }
/** /**
* Executes given SQL statement. * Executes given SQL statement.
* *
* @param string $sql SQL statement * @param string $sql SQL statement
* @return resource Result resource identifier * @return resource Result resource identifier
*/ */
function _execute ($sql) function _execute ($sql)
{ {
return pg_query($this->connection, $sql); return pg_query($this->connection, $sql);
} }
function query () function query ()
{ {
$args = func_get_args(); $args = func_get_args();
if (count($args) == 1) if (count($args) == 1)
{ {
@ -131,26 +131,34 @@ class DboPostgres extends DboSource
$query = '"' . $args[2]->name . '"."' . $field . '" = ' . $this->value($args[1][0]); $query = '"' . $args[2]->name . '"."' . $field . '" = ' . $this->value($args[1][0]);
return $args[2]->findAll($query); return $args[2]->findAll($query);
} }
} }
/** /**
* Returns a row from given resultset as an array . * Returns a row from given resultset as an array .
* *
* @return array The fetched row as an array * @return array The fetched row as an array
*/ */
function fetchRow ($assoc = false) function fetchRow ($assoc = false)
{ {
$assoc = ($assoc === false) ? PGSQL_BOTH : PGSQL_ASSOC; if(is_resource($this->_result))
return pg_fetch_array($this->_result, null, $assoc); {
} $this->resultSet($this->_result);
$resultRow = $this->fetchResult();
return $resultRow;
}
else
{
return null;
}
}
/** /**
* Returns an array of tables in the database. If there are no tables, an error is raised and the application exits. * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
* *
* @return array Array of tablenames in the database * @return array Array of tablenames in the database
*/ */
function listSources () function listSources ()
{ {
$sql = "SELECT table_name as name FROM information_schema.tables WHERE table_schema = 'public';"; $sql = "SELECT table_name as name FROM information_schema.tables WHERE table_schema = 'public';";
$result = $this->query($sql); $result = $this->query($sql);
@ -164,33 +172,72 @@ class DboPostgres extends DboSource
$tables = array(); $tables = array();
foreach ($result as $item) foreach ($result as $item)
{ {
$tables[] = $item['name']; $tables[] = $item[0]['name'];
} }
return $tables; return $tables;
} }
} }
/** /**
* Returns an array of the fields in given table name. * Generates the fields list of an SQL query.
* *
* @param string $tableName Name of database table to inspect * @param Model $model
* @return array Fields in table. Keys are name and type * @param string $alias Alias tablename
*/ * @param mixed $fields
function fields ($tableName) * @return array
{ */
$sql = "SELECT c.relname, a.attname, t.typname FROM pg_class c, pg_attribute a, pg_type t WHERE c.relname = '{$tableName}' AND a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid"; function fields (&$model, $alias, $fields)
{
if (is_array($fields))
{
$fields = $fields;
}
else
{
if ($fields != null)
{
if (strpos($fields, ','))
{
$fields = explode(',', $fields);
}
else
{
$fields = array($fields);
}
$fields = array_map('trim', $fields);
}
else
{
foreach ($model->_tableInfo->value as $field)
{
$fields[]= $field[0]['name'];
}
$fields = false; }
foreach ($this->all($sql) as $field) { }
$fields[] = array(
'name' => $field['attname'],
'type' => $field['typname']);
}
return $fields; $count = count($fields);
} if ($count >= 1 && $fields[0] != '*' && strpos($fields[0], 'COUNT(*)') === false)
{
for ($i = 0; $i < $count; $i++)
{
$dot = strrpos($fields[$i], '.');
if ($dot === false)
{
$fields[$i] = $this->name($alias).'.'.$this->name($fields[$i]) . ' AS ' . $this->name($alias . '__' . $fields[$i]);
}
else
{
$build = explode('.',$fields[$i]);
$fields[$i] = $this->name($build[0]).'.'.$this->name($build[1]) . ' AS ' . $this->name($build[0] . '__' . $build[1]);
}
}
}
return $fields;
}
/** /**
* Returns an array of the fields in given table name. * Returns an array of the fields in given table name.
* *
* @param string $tableName Name of database table to inspect * @param string $tableName Name of database table to inspect
@ -206,92 +253,115 @@ class DboPostgres extends DboSource
$fields = false; $fields = false;
$fields = $this->query("SELECT column_name as name, data_type as type FROM information_schema.columns WHERE table_name =".$this->name($model->table)); $fields = $this->query("SELECT column_name as name, data_type as type FROM information_schema.columns WHERE table_name =".$this->value($model->table));
$this->__cacheDescription($model->table, $fields); $this->__cacheDescription($model->table, $fields);
return $fields; return $fields;
} }
/** /**
* Returns a quoted and escaped string of $data for use in an SQL statement. * 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 $data String to be prepared for use in an SQL statement
* @return string Quoted and escaped * @return string Quoted and escaped
*/ */
function name ($data) function name ($data)
{ {
return "'". $data."'"; if ($data == '*')
} {
return '*';
}
return '"'. ereg_replace('\.', '"."', $data) .'"';
}
/** /**
* Returns a quoted and escaped string of $data for use in an SQL statement. * 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 $data String to be prepared for use in an SQL statement
* @return string Quoted and escaped * @param string $column The column into which this data will be inserted
*/ * @return string Quoted and escaped
function value ($data) * @todo Add logic that formats/escapes data based on column type
{ */
return "'".pg_escape_string($data)."'"; function value ($data, $column = null)
} {
$parent = parent::value($data, $column);
if ($parent != null)
{
return $parent;
}
if ($data === null)
{
return 'NULL';
}
if (ini_get('magic_quotes_gpc') == 1)
{
$data = stripslashes($data);
}
$data = pg_escape_string($data);
$return = "'" . $data . "'";
return $return;
}
/** /**
* Returns a formatted error message from previous database operation. * Returns a formatted error message from previous database operation.
* *
* @return string Error message * @return string Error message
*/ */
function lastError () function lastError ()
{ {
$last_error = pg_last_error($this->connection); $last_error = pg_last_error($this->connection);
if ($last_error) if ($last_error)
{ {
return $last_error; return $last_error;
} }
return null; return null;
} }
/** /**
* Returns number of affected rows in previous database operation. If no previous operation exists, this returns false. * Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
* *
* @return int Number of affected rows * @return int Number of affected rows
*/ */
function lastAffected () function lastAffected ()
{ {
if ($this->_result) if ($this->_result)
{ {
return pg_affected_rows($this->_result); return pg_affected_rows($this->_result);
} }
return false; return false;
} }
/** /**
* Returns number of rows in previous resultset. If no previous resultset exists, * Returns number of rows in previous resultset. If no previous resultset exists,
* this returns false. * this returns false.
* *
* @return int Number of rows in resultset * @return int Number of rows in resultset
*/ */
function lastNumRows () function lastNumRows ()
{ {
if ($this->_result) if ($this->_result)
{ {
return pg_num_rows($this->_result); return pg_num_rows($this->_result);
} }
return false; return false;
} }
/** /**
* Returns the ID generated from the previous INSERT operation. * Returns the ID generated from the previous INSERT operation.
* *
* @param string $source Name of the database table * @param string $source Name of the database table
* @param string $field Name of the ID database field. Defaults to "id" * @param string $field Name of the ID database field. Defaults to "id"
* @return int * @return int
*/ */
function lastInsertId ($source, $field='id') function lastInsertId ($source, $field='id')
{ {
$sql = "SELECT CURRVAL('{$source}_{$field}_seq') AS max"; $sql = "SELECT CURRVAL('{$source}_{$field}_seq') AS max";
$res = $this->rawQuery($sql); $res = $this->rawQuery($sql);
$data = $this->fetchRow($res); $data = $this->fetchRow($res);
return $data['max']; return $data['max'];
} }
/** /**
* Returns a limit statement in the correct format for the particular database. * Returns a limit statement in the correct format for the particular database.
@ -300,16 +370,74 @@ class DboPostgres extends DboSource
* @param int $offset Offset from which to start results * @param int $offset Offset from which to start results
* @return string SQL limit/offset statement * @return string SQL limit/offset statement
*/ */
function limit ($limit, $offset = null) function limit ($limit, $offset = null)
{ {
$rt = ' LIMIT ' . $limit; if ($limit)
if ($offset) {
{ $rt = '';
$rt .= ' OFFSET ' . $offset; if (!strpos(low($limit), 'limit') || strpos(low($limit), 'limit') === 0)
} {
return $rt; $rt = ' LIMIT';
} }
if ($offset)
{
$rt .= ' ' . $offset. ',';
}
$rt .= ' ' . $limit;
return $rt;
}
return null;
}
function resultSet(&$results)
{
$this->results =& $results;
$this->map = array();
$num_fields = pg_num_fields($results);
$index = 0;
$j = 0;
while ($j < $num_fields)
{
$columnName = pg_field_name($results, $j);
if (strpos($columnName, '__'))
{
$parts = explode('__', $columnName);
$this->map[$index++] = array($parts[0], $parts[1]);
}
else
{
$this->map[$index++] = array(0, $columnName);
}
$j++;
}
}
/**
* Fetches the next row from the current result set
*
* @return unknown
*/
function fetchResult()
{
if ($row = pg_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;
}
}
} }
?> ?>

View file

@ -51,8 +51,8 @@ class DBO_SQLite extends DBO
* @param array $config Configuration array for connecting * @param array $config Configuration array for connecting
* @return mixed * @return mixed
*/ */
function connect($config) function connect($config)
{ {
if ($config) if ($config)
{ {
$this->config = $config; $this->config = $config;
@ -66,19 +66,19 @@ class DBO_SQLite extends DBO
} }
else else
{ {
//die('Could not connect to DB.'); //die('Could not connect to DB.');
} }
} }
/** /**
* Disconnects from database. * Disconnects from database.
* *
* @return boolean True if the database could be disconnected, else false * @return boolean True if the database could be disconnected, else false
*/ */
function disconnect() function disconnect()
{ {
return sqlite_close($this->_conn); return sqlite_close($this->_conn);
} }
/** /**
* Executes given SQL statement. * Executes given SQL statement.
@ -86,28 +86,28 @@ class DBO_SQLite extends DBO
* @param string $sql SQL statement * @param string $sql SQL statement
* @return resource Result resource identifier * @return resource Result resource identifier
*/ */
function execute($sql) function execute($sql)
{ {
return sqlite_query($this->_conn, $sql); return sqlite_query($this->_conn, $sql);
} }
/** /**
* Returns a row from given resultset as an array. * Returns a row from given resultset as an array.
* *
* @return array The fetched row as an array * @return array The fetched row as an array
*/ */
function fetchRow() function fetchRow()
{ {
return sqlite_fetch_array($this->_result); return sqlite_fetch_array($this->_result);
} }
/** /**
* Returns an array of tables in the database. If there are no tables, an error is raised and the application exits. * Returns an array of tables in the database. If there are no tables, an error is raised and the application exits.
* *
* @return array Array of tablenames in the database * @return array Array of tablenames in the database
*/ */
function tablesList() function tablesList()
{ {
$result = sqlite_query($this->_conn, "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;"); $result = sqlite_query($this->_conn, "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;");
if (!$result) if (!$result)
@ -124,7 +124,7 @@ class DBO_SQLite extends DBO
} }
return $tables; return $tables;
} }
} }
/** /**
* Returns an array of the fields in given table name. * Returns an array of the fields in given table name.
@ -132,8 +132,8 @@ class DBO_SQLite extends DBO
* @param string $tableName Name of database table to inspect * @param string $tableName Name of database table to inspect
* @return array Fields in table. Keys are name and type * @return array Fields in table. Keys are name and type
*/ */
function fields($tableName) function fields($tableName)
{ {
$fields = false; $fields = false;
$cols = sqlite_fetch_column_types($tableName, $this->_conn); $cols = sqlite_fetch_column_types($tableName, $this->_conn);
@ -143,7 +143,7 @@ class DBO_SQLite extends DBO
} }
return $fields; return $fields;
} }
/** /**
* Returns a quoted and escaped string of $data for use in an SQL statement. * Returns a quoted and escaped string of $data for use in an SQL statement.
@ -151,30 +151,30 @@ class DBO_SQLite extends DBO
* @param string $data String to be prepared for use in an SQL statement * @param string $data String to be prepared for use in an SQL statement
* @return string Quoted and escaped * @return string Quoted and escaped
*/ */
function prepareValue($data) function prepareValue($data)
{ {
return "'" . sqlite_escape_string($data) . "'"; return "'" . sqlite_escape_string($data) . "'";
} }
/** /**
* Returns a formatted error message from previous database operation. * Returns a formatted error message from previous database operation.
* *
* @return string Error message * @return string Error message
*/ */
function lastError() function lastError()
{ {
return sqlite_last_error($this->_conn)? sqlite_last_error($this->_conn).': '.sqlite_error_string(sqlite_last_error($this->_conn)): null; return sqlite_last_error($this->_conn)? sqlite_last_error($this->_conn).': '.sqlite_error_string(sqlite_last_error($this->_conn)): null;
} }
/** /**
* Returns number of affected rows in previous database operation. If no previous operation exists, this returns false. * Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
* *
* @return int Number of affected rows * @return int Number of affected rows
*/ */
function lastAffected() function lastAffected()
{ {
return $this->_result? sqlite_changes($this->_conn): false; return $this->_result? sqlite_changes($this->_conn): false;
} }
/** /**
* Returns number of rows in previous resultset. If no previous resultset exists, * Returns number of rows in previous resultset. If no previous resultset exists,
@ -182,20 +182,20 @@ class DBO_SQLite extends DBO
* *
* @return int Number of rows in resultset * @return int Number of rows in resultset
*/ */
function lastNumRows() function lastNumRows()
{ {
return $this->_result? sqlite_num_rows($this->_result): false; return $this->_result? sqlite_num_rows($this->_result): false;
} }
/** /**
* Returns the ID generated from the previous INSERT operation. * Returns the ID generated from the previous INSERT operation.
* *
* @return int * @return int
*/ */
function lastInsertId() function lastInsertId()
{ {
return sqlite_last_insert_rowid($this->_conn); return sqlite_last_insert_rowid($this->_conn);
} }
/** /**
* Returns a limit statement in the correct format for the particular database. * Returns a limit statement in the correct format for the particular database.
@ -204,9 +204,9 @@ class DBO_SQLite extends DBO
* @param int $offset Offset from which to start results * @param int $offset Offset from which to start results
* @return string SQL limit/offset statement * @return string SQL limit/offset statement
*/ */
function selectLimit($limit, $offset=null) function selectLimit($limit, $offset=null)
{ {
return " LIMIT {$limit}".($offset? ", {$offset}": null); return " LIMIT {$limit}".($offset? ", {$offset}": null);
} }
} }
?> ?>

View file

@ -57,7 +57,7 @@ class Model extends Object
* @var string * @var string
* @access public * @access public
*/ */
var $useDbConfig = 'default'; var $useDbConfig = 'default';
/** /**
* The DataSource connection object that this Model uses * The DataSource connection object that this Model uses
@ -65,7 +65,7 @@ class Model extends Object
* @var unknown_type * @var unknown_type
* @access public * @access public
*/ */
var $db = null; var $db = null;
/** /**
* Enter description here... Still used? * Enter description here... Still used?
@ -74,7 +74,7 @@ class Model extends Object
* @access public * @access public
* @todo Is this still used? -OJ 22 nov 2006 * @todo Is this still used? -OJ 22 nov 2006
*/ */
var $parent = false; var $parent = false;
/** /**
* Custom database table name. * Custom database table name.
@ -82,7 +82,7 @@ class Model extends Object
* @var string * @var string
* @access public * @access public
*/ */
var $useTable = null; var $useTable = null;
/** /**
* Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements. * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
@ -90,7 +90,7 @@ class Model extends Object
* @var string * @var string
* @access public * @access public
*/ */
var $displayField = null; var $displayField = null;
/** /**
*Value of the primary key ID of the record that this model is currently pointing to *Value of the primary key ID of the record that this model is currently pointing to
@ -98,7 +98,7 @@ class Model extends Object
* @var unknown_type * @var unknown_type
* @access public * @access public
*/ */
var $id = false; var $id = false;
/** /**
* Container for the data that this model gets from persistent storage (the database). * Container for the data that this model gets from persistent storage (the database).
@ -106,7 +106,7 @@ class Model extends Object
* @var array * @var array
* @access public * @access public
*/ */
var $data = array(); var $data = array();
/** /**
* Table name for this Model. * Table name for this Model.
@ -114,7 +114,7 @@ class Model extends Object
* @var string * @var string
* @access public * @access public
*/ */
var $table = false; var $table = false;
/** /**
* The name of the ID field for this Model. * The name of the ID field for this Model.
@ -122,7 +122,7 @@ class Model extends Object
* @var string * @var string
* @access public * @access public
*/ */
var $primaryKey = null; var $primaryKey = null;
/** /**
* Table metadata * Table metadata
@ -130,7 +130,7 @@ class Model extends Object
* @var array * @var array
* @access private * @access private
*/ */
var $_tableInfo = null; var $_tableInfo = null;
/** /**
* List of validation rules. Append entries for validation as ('field_name' => '/^perl_compat_regexp$/') * List of validation rules. Append entries for validation as ('field_name' => '/^perl_compat_regexp$/')
@ -138,118 +138,118 @@ class Model extends Object
* *
* @var array * @var array
*/ */
var $validate = array(); var $validate = array();
/** /**
* Errors in validation * Errors in validation
* @var array * @var array
*/ */
var $validationErrors = null; var $validationErrors = null;
/** /**
* Database table prefix for tables in model. * Database table prefix for tables in model.
* *
* @var string * @var string
*/ */
var $tablePrefix = null; var $tablePrefix = null;
/** /**
* Name of the model. * Name of the model.
* *
* @var string * @var string
*/ */
var $name = null; var $name = null;
/** /**
* Name of the current model. * Name of the current model.
* *
* @var string * @var string
*/ */
var $currentModel = null; var $currentModel = null;
/** /**
* List of table names included in the Model description. Used for associations. * List of table names included in the Model description. Used for associations.
* *
* @var array * @var array
*/ */
var $tableToModel = array(); var $tableToModel = array();
/** /**
* List of Model names by used tables. Used for associations. * List of Model names by used tables. Used for associations.
* *
* @var array * @var array
*/ */
var $modelToTable = array(); var $modelToTable = array();
/** /**
* List of Foreign Key names to used tables. Used for associations. * List of Foreign Key names to used tables. Used for associations.
* *
* @var array * @var array
*/ */
var $keyToTable = array(); var $keyToTable = array();
/** /**
* Alias table names for model, for use in SQL JOIN statements. * Alias table names for model, for use in SQL JOIN statements.
* *
* @var array * @var array
*/ */
var $alias = array(); var $alias = array();
/** /**
* Whether or not transactions for this model should be logged * Whether or not transactions for this model should be logged
* *
* @var boolean * @var boolean
*/ */
var $logTransactions = false; var $logTransactions = false;
/** /**
* Whether or not to enable transactions for this model (i.e. BEGIN/COMMIT/ROLLBACK) * Whether or not to enable transactions for this model (i.e. BEGIN/COMMIT/ROLLBACK)
* *
* @var boolean * @var boolean
*/ */
var $transactional = false; var $transactional = false;
/** /**
* belongsTo association * belongsTo association
* *
* @var array * @var array
*/ */
var $belongsTo = array(); var $belongsTo = array();
/** /**
* hasOne association * hasOne association
* *
* @var array * @var array
*/ */
var $hasOne = array(); var $hasOne = array();
/** /**
* hasMany association * hasMany association
* *
* @var array * @var array
*/ */
var $hasMany = array(); var $hasMany = array();
/** /**
* hasAndBelongsToMany association * hasAndBelongsToMany association
* *
* @var array * @var array
*/ */
var $hasAndBelongsToMany = array(); var $hasAndBelongsToMany = array();
/** /**
* Depth of recursive association * Depth of recursive association
* *
* @var int * @var int
*/ */
var $recursive = 1; var $recursive = 1;
/** /**
* Default association keys * Default association keys
* *
* @var array * @var array
*/ */
var $__associationKeys = array('belongsTo' => array('className', 'conditions', 'order', 'foreignKey', 'counterCache'), var $__associationKeys = array('belongsTo' => array('className', 'conditions', 'order', 'foreignKey', 'counterCache'),
'hasOne' => array('className', 'conditions', 'order', 'foreignKey', 'dependent'), 'hasOne' => array('className', 'conditions', 'order', 'foreignKey', 'dependent'),
'hasMany' => array('className', 'conditions', 'order', 'foreignKey', 'fields', 'dependent', 'exclusive', 'finder_query', 'counter_query'), 'hasMany' => array('className', 'conditions', 'order', 'foreignKey', 'fields', 'dependent', 'exclusive', 'finder_query', 'counter_query'),
'hasAndBelongsToMany' => array('className', 'joinTable', 'fields', 'foreignKey', 'associationForeignKey', 'conditions', 'order', 'uniq', 'finderQuery', 'deleteQuery', 'insertQuery') 'hasAndBelongsToMany' => array('className', 'joinTable', 'fields', 'foreignKey', 'associationForeignKey', 'conditions', 'order', 'uniq', 'finderQuery', 'deleteQuery', 'insertQuery')
@ -260,7 +260,7 @@ class Model extends Object
* *
* @var array * @var array
*/ */
var $__associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'); var $__associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
/** /**
* The last inserted ID of the data that this model created * The last inserted ID of the data that this model created
@ -268,7 +268,7 @@ class Model extends Object
* @var int * @var int
* @access private * @access private
*/ */
var $__insertID = null; var $__insertID = null;
/** /**
* The number of records returned by the last query * The number of records returned by the last query
@ -276,7 +276,7 @@ class Model extends Object
* @access private * @access private
* @var int * @var int
*/ */
var $__numRows = null; var $__numRows = null;
/** /**
* The number of records affected by the last query * The number of records affected by the last query
@ -284,7 +284,7 @@ class Model extends Object
* @access private * @access private
* @var int * @var int
*/ */
var $__affectedRows = null; var $__affectedRows = null;
/** /**
* Constructor. Binds the Model's database table to the object. * Constructor. Binds the Model's database table to the object.
@ -330,37 +330,37 @@ class Model extends Object
} }
} }
if (in_array('settableprefix', get_class_methods($this))) if (in_array('settableprefix', get_class_methods($this)))
{ {
$this->setTablePrefix(); $this->setTablePrefix();
} }
if ($this->tablePrefix) if ($this->tablePrefix)
{ {
$this->setSource($this->tablePrefix.$tableName); $this->setSource($this->tablePrefix.$tableName);
} }
else else
{ {
$this->setSource($tableName); $this->setSource($tableName);
} }
$this->__createLinks(); $this->__createLinks();
if ($this->displayField == null) if ($this->displayField == null)
{ {
if ($this->hasField('title')) if ($this->hasField('title'))
{ {
$this->displayField = 'title'; $this->displayField = 'title';
} }
if ($this->hasField('name')) if ($this->hasField('name'))
{ {
$this->displayField = 'name'; $this->displayField = 'name';
} }
if ($this->displayField == null) if ($this->displayField == null)
{ {
$this->displayField = $this->primaryKey; $this->displayField = $this->primaryKey;
} }
} }
} }
} }
@ -378,8 +378,8 @@ class Model extends Object
*/ */
function __call($method, $params, &$return) function __call($method, $params, &$return)
{ {
$return = $this->db->query($method, $params, $this); $return = $this->db->query($method, $params, $this);
return true; return true;
} }
/** /**
@ -389,7 +389,7 @@ class Model extends Object
*/ */
function __createLinks() function __createLinks()
{ {
// Convert all string-based associations to array based // Convert all string-based associations to array based
foreach($this->__associations as $type) foreach($this->__associations as $type)
{ {
if(!is_array($this->{$type})) if(!is_array($this->{$type}))
@ -514,23 +514,23 @@ class Model extends Object
{ {
if($this->db->isInterfaceSupported('listSources')) if($this->db->isInterfaceSupported('listSources'))
{ {
if (!in_array(strtolower($tableName), $this->db->listSources())) if (!in_array(strtolower($tableName), $this->db->listSources()))
{ {
return $this->cakeError('missingTable',array(array('className' => $this->name, return $this->cakeError('missingTable',array(array('className' => $this->name,
'table' => $tableName))); 'table' => $tableName)));
} }
else else
{ {
$this->table = $tableName; $this->table = $tableName;
$this->tableToModel[$this->table] = $this->name; $this->tableToModel[$this->table] = $this->name;
$this->loadInfo(); $this->loadInfo();
} }
} }
else else
{ {
$this->table = $tableName; $this->table = $tableName;
$this->tableToModel[$this->table] = $this->name; $this->tableToModel[$this->table] = $this->name;
$this->loadInfo(); $this->loadInfo();
} }
} }
@ -578,31 +578,31 @@ class Model extends Object
* *
* @return array Array of table metadata * @return array Array of table metadata
*/ */
function loadInfo () function loadInfo ()
{ {
if (!is_object($this->_tableInfo) && $this->db->isInterfaceSupported('describe')) if (!is_object($this->_tableInfo) && $this->db->isInterfaceSupported('describe'))
{ {
$this->_tableInfo = new NeatArray($this->db->describe($this)); $this->_tableInfo = new NeatArray($this->db->describe($this));
} }
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.
* *
* @return array * @return array
*/ */
function getColumnTypes () function getColumnTypes ()
{ {
$columns = $this->loadInfo(); $columns = $this->loadInfo();
$columns = $columns->value; $columns = $columns->value;
$cols = array(); $cols = array();
foreach($columns as $col) { foreach($columns as $col) {
$cols[$col['name']] = $col['type']; $cols[$col['name']] = $col['type'];
} }
return $cols; return $cols;
} }
/** /**
* Returns true if this Model has given field in its database table. * Returns true if this Model has given field in its database table.
@ -612,15 +612,15 @@ class Model extends Object
*/ */
function hasField ($name) function hasField ($name)
{ {
if (empty($this->_tableInfo)) if (empty($this->_tableInfo))
{ {
$this->loadInfo(); $this->loadInfo();
} }
if($this->_tableInfo != null) if($this->_tableInfo != null)
{ {
return $this->_tableInfo->findIn('name', $name); return $this->_tableInfo->findIn('name', $name);
} }
return null; return null;
} }
/** /**
@ -628,31 +628,31 @@ class Model extends Object
* *
* @return boolean True * @return boolean True
*/ */
function create () function create ()
{ {
$this->id = false; $this->id = false;
unset($this->data); unset($this->data);
$this->data = array(); $this->data = array();
return true; return true;
} }
/** /**
* Deprecated * Deprecated
* *
*/ */
function setId ($id) function setId ($id)
{ {
$this->id = $id; $this->id = $id;
} }
/** /**
* Deprecated. Use query() instead. * Deprecated. Use query() instead.
* *
*/ */
function findBySql ($sql) function findBySql ($sql)
{ {
return $this->query($sql); return $this->query($sql);
} }
/** /**
@ -964,10 +964,10 @@ class Model extends Object
{ {
if ($this->id && $this->db->delete($this)) if ($this->id && $this->db->delete($this))
{ {
//$this->__deleteJoins($id); //$this->__deleteJoins($id);
if ($cascade) if ($cascade)
{ {
//$this->__deleteMulti($id); //$this->__deleteMulti($id);
} }
$this->afterDelete(); $this->afterDelete();
$this->id = false; $this->id = false;
@ -1046,7 +1046,7 @@ class Model extends Object
/** /**
* 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
* the ones this model is directly associated to. * the ones this model is directly associated to.
* *
* @param array $conditions SQL conditions array * @param array $conditions SQL conditions array
@ -1113,25 +1113,25 @@ class Model extends Object
* @param string $data Query data * @param string $data Query data
* @return array * @return array
*/ */
function execute ($data) function execute ($data)
{ {
$data = $this->db->fetchAll($data); $data = $this->db->fetchAll($data);
foreach ($data as $key => $value) foreach ($data as $key => $value)
{ {
foreach ($this->tableToModel as $key1 => $value1) foreach ($this->tableToModel as $key1 => $value1)
{ {
if (isset($data[$key][$key1])) if (isset($data[$key][$key1]))
{ {
$newData[$key][$value1] = $data[$key][$key1]; $newData[$key][$value1] = $data[$key][$key1];
} }
} }
} }
if (!empty($newData)) if (!empty($newData))
{ {
return $newData; return $newData;
} }
return $data; return $data;
} }
/** /**
* Returns number of rows matching given SQL condition. * Returns number of rows matching given SQL condition.
@ -1141,15 +1141,15 @@ class Model extends Object
* @return int Number of matching rows * @return int Number of matching rows
* @see Model::findAll * @see Model::findAll
*/ */
function findCount ($conditions = null, $recursive = 0) function findCount ($conditions = null, $recursive = 0)
{ {
list($data) = $this->findAll($conditions, 'COUNT(*) AS count', null, null, 1, $recursive); list($data) = $this->findAll($conditions, 'COUNT(*) AS count', null, null, 1, $recursive);
if (isset($data[0]['count'])) if (isset($data[0]['count']))
{ {
return $data[0]['count']; return $data[0]['count'];
} }
return false; return false;
} }
/** /**
* Special findAll variation for tables joined to themselves. * Special findAll variation for tables joined to themselves.
@ -1161,10 +1161,10 @@ class Model extends Object
* @return array * @return array
* @todo Perhaps create a Component with this logic * @todo Perhaps create a Component with this logic
*/ */
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.
@ -1175,28 +1175,28 @@ class Model extends Object
* @access private * @access private
* @see findAllThreaded * @see findAllThreaded
*/ */
function __doThread ($data, $root) function __doThread ($data, $root)
{ {
$out = array(); $out = array();
$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)
{ {
$tmp = $data[$ii]; $tmp = $data[$ii];
if (isset($data[$ii][$this->name][$this->primaryKey])) if (isset($data[$ii][$this->name][$this->primaryKey]))
{ {
$tmp['children'] = $this->__doThread($data, $data[$ii][$this->name][$this->primaryKey]); $tmp['children'] = $this->__doThread($data, $data[$ii][$this->name][$this->primaryKey]);
} }
else else
{ {
$tmp['children'] = null; $tmp['children'] = null;
} }
$out[] = $tmp; $out[] = $tmp;
} }
} }
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,
@ -1233,11 +1233,11 @@ class Model extends Object
* @param string $sql SQL statement * @param string $sql SQL statement
* @return array Resultset * @return array Resultset
*/ */
function query () function query ()
{ {
$params = func_get_args(); $params = func_get_args();
return call_user_func_array(array(&$this->db, 'query'), $params); return call_user_func_array(array(&$this->db, 'query'), $params);
} }
/** /**
* Returns true if all fields pass validation, otherwise false. * Returns true if all fields pass validation, otherwise false.
@ -1245,15 +1245,15 @@ class Model extends Object
* @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 = null)
{ {
if ($data == null) if ($data == null)
{ {
$data = $this->data; $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.
@ -1261,8 +1261,8 @@ class Model extends Object
* @param array $data * @param array $data
* @return array Array of invalid fields * @return array Array of invalid fields
*/ */
function invalidFields ($data=null) function invalidFields ($data=null)
{ {
if (!isset($this->validate) || is_array($this->validationErrors)) if (!isset($this->validate) || is_array($this->validationErrors))
{ {
if (!isset($this->validate)) if (!isset($this->validate))
@ -1292,7 +1292,7 @@ class Model extends Object
{ {
foreach ($this->validate as $field_name => $validator) foreach ($this->validate as $field_name => $validator)
{ {
if (isset($data[$table][$field_name]) && !preg_match($validator, $data[$table][$field_name])) if (isset($data[$table][$field_name]) && !preg_match($validator, $data[$table][$field_name]))
{ {
$errors[$field_name] = 1; $errors[$field_name] = 1;
} }
@ -1300,7 +1300,7 @@ class Model extends Object
$this->validationErrors = $errors; $this->validationErrors = $errors;
return $errors; return $errors;
} }
} }
/** /**
* 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.
@ -1310,16 +1310,16 @@ class Model extends Object
*/ */
function isForeignKey($field) function isForeignKey($field)
{ {
$foreignKeys = array(); $foreignKeys = array();
if(count($this->belongsTo)) if(count($this->belongsTo))
{ {
foreach ($this->belongsTo as $assoc => $data) foreach ($this->belongsTo as $assoc => $data)
{ {
$foreignKeys[] = $data['foreignKey']; $foreignKeys[] = $data['foreignKey'];
} }
} }
return (bool)(in_array($field, $foreignKeys)); return (bool)(in_array($field, $foreignKeys));
} }
/** /**
@ -1425,7 +1425,7 @@ class Model extends Object
*/ */
function getNumRows () function getNumRows ()
{ {
//return $this->__numRows; //return $this->__numRows;
return $this->db->lastNumRows(); return $this->db->lastNumRows();
} }
@ -1436,7 +1436,7 @@ class Model extends Object
*/ */
function getAffectedRows () function getAffectedRows ()
{ {
//return $this->__affectedRows; //return $this->__affectedRows;
return $this->db->lastAffected(); return $this->db->lastAffected();
} }

View file

@ -57,7 +57,7 @@ class Model extends Object
* @var string * @var string
* @access public * @access public
*/ */
var $useDbConfig = 'default'; var $useDbConfig = 'default';
/** /**
* The DataSource connection object that this Model uses * The DataSource connection object that this Model uses
@ -65,7 +65,7 @@ class Model extends Object
* @var unknown_type * @var unknown_type
* @access public * @access public
*/ */
var $db = null; var $db = null;
/** /**
* Enter description here... Still used? * Enter description here... Still used?
@ -74,7 +74,7 @@ class Model extends Object
* @access public * @access public
* @todo Is this still used? -OJ 22 nov 2006 * @todo Is this still used? -OJ 22 nov 2006
*/ */
var $parent = false; var $parent = false;
/** /**
* Custom database table name. * Custom database table name.
@ -82,7 +82,7 @@ class Model extends Object
* @var string * @var string
* @access public * @access public
*/ */
var $useTable = null; var $useTable = null;
/** /**
* Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements. * Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.
@ -90,7 +90,7 @@ class Model extends Object
* @var string * @var string
* @access public * @access public
*/ */
var $displayField = null; var $displayField = null;
/** /**
*Value of the primary key ID of the record that this model is currently pointing to *Value of the primary key ID of the record that this model is currently pointing to
@ -98,7 +98,7 @@ class Model extends Object
* @var unknown_type * @var unknown_type
* @access public * @access public
*/ */
var $id = false; var $id = false;
/** /**
* Container for the data that this model gets from persistent storage (the database). * Container for the data that this model gets from persistent storage (the database).
@ -106,7 +106,7 @@ class Model extends Object
* @var array * @var array
* @access public * @access public
*/ */
var $data = array(); var $data = array();
/** /**
* Table name for this Model. * Table name for this Model.
@ -114,7 +114,7 @@ class Model extends Object
* @var string * @var string
* @access public * @access public
*/ */
var $table = false; var $table = false;
/** /**
* The name of the ID field for this Model. * The name of the ID field for this Model.
@ -122,7 +122,7 @@ class Model extends Object
* @var string * @var string
* @access public * @access public
*/ */
var $primaryKey = null; var $primaryKey = null;
/** /**
* Table metadata * Table metadata
@ -130,7 +130,7 @@ class Model extends Object
* @var array * @var array
* @access private * @access private
*/ */
var $_tableInfo = null; var $_tableInfo = null;
/** /**
* List of validation rules. Append entries for validation as ('field_name' => '/^perl_compat_regexp$/') * List of validation rules. Append entries for validation as ('field_name' => '/^perl_compat_regexp$/')
@ -138,118 +138,118 @@ class Model extends Object
* *
* @var array * @var array
*/ */
var $validate = array(); var $validate = array();
/** /**
* Errors in validation * Errors in validation
* @var array * @var array
*/ */
var $validationErrors = null; var $validationErrors = null;
/** /**
* Database table prefix for tables in model. * Database table prefix for tables in model.
* *
* @var string * @var string
*/ */
var $tablePrefix = null; var $tablePrefix = null;
/** /**
* Name of the model. * Name of the model.
* *
* @var string * @var string
*/ */
var $name = null; var $name = null;
/** /**
* Name of the current model. * Name of the current model.
* *
* @var string * @var string
*/ */
var $currentModel = null; var $currentModel = null;
/** /**
* List of table names included in the Model description. Used for associations. * List of table names included in the Model description. Used for associations.
* *
* @var array * @var array
*/ */
var $tableToModel = array(); var $tableToModel = array();
/** /**
* List of Model names by used tables. Used for associations. * List of Model names by used tables. Used for associations.
* *
* @var array * @var array
*/ */
var $modelToTable = array(); var $modelToTable = array();
/** /**
* List of Foreign Key names to used tables. Used for associations. * List of Foreign Key names to used tables. Used for associations.
* *
* @var array * @var array
*/ */
var $keyToTable = array(); var $keyToTable = array();
/** /**
* Alias table names for model, for use in SQL JOIN statements. * Alias table names for model, for use in SQL JOIN statements.
* *
* @var array * @var array
*/ */
var $alias = array(); var $alias = array();
/** /**
* Whether or not transactions for this model should be logged * Whether or not transactions for this model should be logged
* *
* @var boolean * @var boolean
*/ */
var $logTransactions = false; var $logTransactions = false;
/** /**
* Whether or not to enable transactions for this model (i.e. BEGIN/COMMIT/ROLLBACK) * Whether or not to enable transactions for this model (i.e. BEGIN/COMMIT/ROLLBACK)
* *
* @var boolean * @var boolean
*/ */
var $transactional = false; var $transactional = false;
/** /**
* belongsTo association * belongsTo association
* *
* @var array * @var array
*/ */
var $belongsTo = array(); var $belongsTo = array();
/** /**
* hasOne association * hasOne association
* *
* @var array * @var array
*/ */
var $hasOne = array(); var $hasOne = array();
/** /**
* hasMany association * hasMany association
* *
* @var array * @var array
*/ */
var $hasMany = array(); var $hasMany = array();
/** /**
* hasAndBelongsToMany association * hasAndBelongsToMany association
* *
* @var array * @var array
*/ */
var $hasAndBelongsToMany = array(); var $hasAndBelongsToMany = array();
/** /**
* Depth of recursive association * Depth of recursive association
* *
* @var int * @var int
*/ */
var $recursive = 1; var $recursive = 1;
/** /**
* Default association keys * Default association keys
* *
* @var array * @var array
*/ */
var $__associationKeys = array('belongsTo' => array('className', 'conditions', 'order', 'foreignKey', 'counterCache'), var $__associationKeys = array('belongsTo' => array('className', 'conditions', 'order', 'foreignKey', 'counterCache'),
'hasOne' => array('className', 'conditions', 'order', 'foreignKey', 'dependent'), 'hasOne' => array('className', 'conditions', 'order', 'foreignKey', 'dependent'),
'hasMany' => array('className', 'conditions', 'order', 'foreignKey', 'fields', 'dependent', 'exclusive', 'finder_query', 'counter_query'), 'hasMany' => array('className', 'conditions', 'order', 'foreignKey', 'fields', 'dependent', 'exclusive', 'finder_query', 'counter_query'),
'hasAndBelongsToMany' => array('className', 'joinTable', 'fields', 'foreignKey', 'associationForeignKey', 'conditions', 'order', 'uniq', 'finderQuery', 'deleteQuery', 'insertQuery') 'hasAndBelongsToMany' => array('className', 'joinTable', 'fields', 'foreignKey', 'associationForeignKey', 'conditions', 'order', 'uniq', 'finderQuery', 'deleteQuery', 'insertQuery')
@ -260,7 +260,7 @@ class Model extends Object
* *
* @var array * @var array
*/ */
var $__associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'); var $__associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
/** /**
* The last inserted ID of the data that this model created * The last inserted ID of the data that this model created
@ -268,7 +268,7 @@ class Model extends Object
* @var int * @var int
* @access private * @access private
*/ */
var $__insertID = null; var $__insertID = null;
/** /**
* The number of records returned by the last query * The number of records returned by the last query
@ -276,7 +276,7 @@ class Model extends Object
* @access private * @access private
* @var int * @var int
*/ */
var $__numRows = null; var $__numRows = null;
/** /**
* The number of records affected by the last query * The number of records affected by the last query
@ -284,7 +284,7 @@ class Model extends Object
* @access private * @access private
* @var int * @var int
*/ */
var $__affectedRows = null; var $__affectedRows = null;
/** /**
* Constructor. Binds the Model's database table to the object. * Constructor. Binds the Model's database table to the object.
@ -330,37 +330,37 @@ class Model extends Object
} }
} }
if (in_array('settableprefix', get_class_methods($this))) if (in_array('settableprefix', get_class_methods($this)))
{ {
$this->setTablePrefix(); $this->setTablePrefix();
} }
if ($this->tablePrefix) if ($this->tablePrefix)
{ {
$this->setSource($this->tablePrefix.$tableName); $this->setSource($this->tablePrefix.$tableName);
} }
else else
{ {
$this->setSource($tableName); $this->setSource($tableName);
} }
$this->__createLinks(); $this->__createLinks();
if ($this->displayField == null) if ($this->displayField == null)
{ {
if ($this->hasField('title')) if ($this->hasField('title'))
{ {
$this->displayField = 'title'; $this->displayField = 'title';
} }
if ($this->hasField('name')) if ($this->hasField('name'))
{ {
$this->displayField = 'name'; $this->displayField = 'name';
} }
if ($this->displayField == null) if ($this->displayField == null)
{ {
$this->displayField = $this->primaryKey; $this->displayField = $this->primaryKey;
} }
} }
} }
} }
@ -375,7 +375,7 @@ class Model extends Object
*/ */
function __call($method, $params) function __call($method, $params)
{ {
return $this->db->query($method, $params, $this); return $this->db->query($method, $params, $this);
} }
/** /**
@ -385,7 +385,7 @@ class Model extends Object
*/ */
function __createLinks() function __createLinks()
{ {
// Convert all string-based associations to array based // Convert all string-based associations to array based
foreach($this->__associations as $type) foreach($this->__associations as $type)
{ {
if(!is_array($this->{$type})) if(!is_array($this->{$type}))
@ -510,23 +510,23 @@ class Model extends Object
{ {
if($this->db->isInterfaceSupported('listSources')) if($this->db->isInterfaceSupported('listSources'))
{ {
if (!in_array(strtolower($tableName), $this->db->listSources())) if (!in_array(strtolower($tableName), $this->db->listSources()))
{ {
return $this->cakeError('missingTable',array(array('className' => $this->name, return $this->cakeError('missingTable',array(array('className' => $this->name,
'table' => $tableName))); 'table' => $tableName)));
} }
else else
{ {
$this->table = $tableName; $this->table = $tableName;
$this->tableToModel[$this->table] = $this->name; $this->tableToModel[$this->table] = $this->name;
$this->loadInfo(); $this->loadInfo();
} }
} }
else else
{ {
$this->table = $tableName; $this->table = $tableName;
$this->tableToModel[$this->table] = $this->name; $this->tableToModel[$this->table] = $this->name;
$this->loadInfo(); $this->loadInfo();
} }
} }
@ -574,31 +574,31 @@ class Model extends Object
* *
* @return array Array of table metadata * @return array Array of table metadata
*/ */
function loadInfo () function loadInfo ()
{ {
if (!is_object($this->_tableInfo) && $this->db->isInterfaceSupported('describe')) if (!is_object($this->_tableInfo) && $this->db->isInterfaceSupported('describe'))
{ {
$this->_tableInfo = new NeatArray($this->db->describe($this)); $this->_tableInfo = new NeatArray($this->db->describe($this));
} }
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.
* *
* @return array * @return array
*/ */
function getColumnTypes () function getColumnTypes ()
{ {
$columns = $this->loadInfo(); $columns = $this->loadInfo();
$columns = $columns->value; $columns = $columns->value;
$cols = array(); $cols = array();
foreach($columns as $col) { foreach($columns as $col) {
$cols[$col['name']] = $col['type']; $cols[$col['name']] = $col['type'];
} }
return $cols; return $cols;
} }
/** /**
* Returns true if this Model has given field in its database table. * Returns true if this Model has given field in its database table.
@ -608,15 +608,15 @@ class Model extends Object
*/ */
function hasField ($name) function hasField ($name)
{ {
if (empty($this->_tableInfo)) if (empty($this->_tableInfo))
{ {
$this->loadInfo(); $this->loadInfo();
} }
if($this->_tableInfo != null) if($this->_tableInfo != null)
{ {
return $this->_tableInfo->findIn('name', $name); return $this->_tableInfo->findIn('name', $name);
} }
return null; return null;
} }
/** /**
@ -624,31 +624,31 @@ class Model extends Object
* *
* @return boolean True * @return boolean True
*/ */
function create () function create ()
{ {
$this->id = false; $this->id = false;
unset($this->data); unset($this->data);
$this->data = array(); $this->data = array();
return true; return true;
} }
/** /**
* Deprecated * Deprecated
* *
*/ */
function setId ($id) function setId ($id)
{ {
$this->id = $id; $this->id = $id;
} }
/** /**
* Deprecated. Use query() instead. * Deprecated. Use query() instead.
* *
*/ */
function findBySql ($sql) function findBySql ($sql)
{ {
return $this->query($sql); return $this->query($sql);
} }
/** /**
@ -960,10 +960,10 @@ class Model extends Object
{ {
if ($this->id && $this->db->delete($this)) if ($this->id && $this->db->delete($this))
{ {
//$this->__deleteJoins($id); //$this->__deleteJoins($id);
if ($cascade) if ($cascade)
{ {
//$this->__deleteMulti($id); //$this->__deleteMulti($id);
} }
$this->afterDelete(); $this->afterDelete();
$this->id = false; $this->id = false;
@ -1042,7 +1042,7 @@ class Model extends Object
/** /**
* 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
* the ones this model is directly associated to. * the ones this model is directly associated to.
* *
* @param array $conditions SQL conditions array * @param array $conditions SQL conditions array
@ -1109,25 +1109,25 @@ class Model extends Object
* @param string $data Query data * @param string $data Query data
* @return array * @return array
*/ */
function execute ($data) function execute ($data)
{ {
$data = $this->db->fetchAll($data); $data = $this->db->fetchAll($data);
foreach ($data as $key => $value) foreach ($data as $key => $value)
{ {
foreach ($this->tableToModel as $key1 => $value1) foreach ($this->tableToModel as $key1 => $value1)
{ {
if (isset($data[$key][$key1])) if (isset($data[$key][$key1]))
{ {
$newData[$key][$value1] = $data[$key][$key1]; $newData[$key][$value1] = $data[$key][$key1];
} }
} }
} }
if (!empty($newData)) if (!empty($newData))
{ {
return $newData; return $newData;
} }
return $data; return $data;
} }
/** /**
* Returns number of rows matching given SQL condition. * Returns number of rows matching given SQL condition.
@ -1137,15 +1137,15 @@ class Model extends Object
* @return int Number of matching rows * @return int Number of matching rows
* @see Model::findAll * @see Model::findAll
*/ */
function findCount ($conditions = null, $recursive = 0) function findCount ($conditions = null, $recursive = 0)
{ {
list($data) = $this->findAll($conditions, 'COUNT(*) AS count', null, null, 1, $recursive); list($data) = $this->findAll($conditions, 'COUNT(*) AS count', null, null, 1, $recursive);
if (isset($data[0]['count'])) if (isset($data[0]['count']))
{ {
return $data[0]['count']; return $data[0]['count'];
} }
return false; return false;
} }
/** /**
* Special findAll variation for tables joined to themselves. * Special findAll variation for tables joined to themselves.
@ -1157,10 +1157,10 @@ class Model extends Object
* @return array * @return array
* @todo Perhaps create a Component with this logic * @todo Perhaps create a Component with this logic
*/ */
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.
@ -1171,28 +1171,28 @@ class Model extends Object
* @access private * @access private
* @see findAllThreaded * @see findAllThreaded
*/ */
function __doThread ($data, $root) function __doThread ($data, $root)
{ {
$out = array(); $out = array();
$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)
{ {
$tmp = $data[$ii]; $tmp = $data[$ii];
if (isset($data[$ii][$this->name][$this->primaryKey])) if (isset($data[$ii][$this->name][$this->primaryKey]))
{ {
$tmp['children'] = $this->__doThread($data, $data[$ii][$this->name][$this->primaryKey]); $tmp['children'] = $this->__doThread($data, $data[$ii][$this->name][$this->primaryKey]);
} }
else else
{ {
$tmp['children'] = null; $tmp['children'] = null;
} }
$out[] = $tmp; $out[] = $tmp;
} }
} }
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,
@ -1229,11 +1229,11 @@ class Model extends Object
* @param string $sql SQL statement * @param string $sql SQL statement
* @return array Resultset * @return array Resultset
*/ */
function query () function query ()
{ {
$params = func_get_args(); $params = func_get_args();
return call_user_func_array(array(&$this->db, 'query'), $params); return call_user_func_array(array(&$this->db, 'query'), $params);
} }
/** /**
* Returns true if all fields pass validation, otherwise false. * Returns true if all fields pass validation, otherwise false.
@ -1241,15 +1241,15 @@ class Model extends Object
* @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 = null)
{ {
if ($data == null) if ($data == null)
{ {
$data = $this->data; $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.
@ -1257,8 +1257,8 @@ class Model extends Object
* @param array $data * @param array $data
* @return array Array of invalid fields * @return array Array of invalid fields
*/ */
function invalidFields ($data=null) function invalidFields ($data=null)
{ {
if (!isset($this->validate) || is_array($this->validationErrors)) if (!isset($this->validate) || is_array($this->validationErrors))
{ {
if (!isset($this->validate)) if (!isset($this->validate))
@ -1288,7 +1288,7 @@ class Model extends Object
{ {
foreach ($this->validate as $field_name => $validator) foreach ($this->validate as $field_name => $validator)
{ {
if (isset($data[$table][$field_name]) && !preg_match($validator, $data[$table][$field_name])) if (isset($data[$table][$field_name]) && !preg_match($validator, $data[$table][$field_name]))
{ {
$errors[$field_name] = 1; $errors[$field_name] = 1;
} }
@ -1296,7 +1296,7 @@ class Model extends Object
$this->validationErrors = $errors; $this->validationErrors = $errors;
return $errors; return $errors;
} }
} }
/** /**
* 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.
@ -1306,16 +1306,16 @@ class Model extends Object
*/ */
function isForeignKey($field) function isForeignKey($field)
{ {
$foreignKeys = array(); $foreignKeys = array();
if(count($this->belongsTo)) if(count($this->belongsTo))
{ {
foreach ($this->belongsTo as $assoc => $data) foreach ($this->belongsTo as $assoc => $data)
{ {
$foreignKeys[] = $data['foreignKey']; $foreignKeys[] = $data['foreignKey'];
} }
} }
return (bool)(in_array($field, $foreignKeys)); return (bool)(in_array($field, $foreignKeys));
} }
/** /**
@ -1421,7 +1421,7 @@ class Model extends Object
*/ */
function getNumRows () function getNumRows ()
{ {
//return $this->__numRows; //return $this->__numRows;
return $this->db->lastNumRows(); return $this->db->lastNumRows();
} }
@ -1432,7 +1432,7 @@ class Model extends Object
*/ */
function getAffectedRows () function getAffectedRows ()
{ {
//return $this->__affectedRows; //return $this->__affectedRows;
return $this->db->lastAffected(); return $this->db->lastAffected();
} }

View file

@ -45,7 +45,7 @@ class NeatArray
* @var array * @var array
* @access public * @access public
*/ */
var $value; var $value;
/** /**
* Constructor. Defaults to an empty array. * Constructor. Defaults to an empty array.
@ -54,10 +54,10 @@ class NeatArray
* @access public * @access public
* @uses NeatArray::value * @uses NeatArray::value
*/ */
function NeatArray ($value=array()) function NeatArray ($value=array())
{ {
$this->value = $value; $this->value = $value;
} }
/** /**
* Finds and returns records with $fieldName equal to $value from this NeatArray. * Finds and returns records with $fieldName equal to $value from this NeatArray.
@ -68,8 +68,8 @@ class NeatArray
* @access public * @access public
* @uses NeatArray::value * @uses NeatArray::value
*/ */
function findIn ($fieldName, $value) function findIn ($fieldName, $value)
{ {
if (!is_array($this->value)) if (!is_array($this->value))
{ {
return false; return false;
@ -85,7 +85,7 @@ class NeatArray
} }
return $out; return $out;
} }
/** /**
* Checks if $this->value is an array, and removes all empty elements. * Checks if $this->value is an array, and removes all empty elements.
@ -93,8 +93,8 @@ class NeatArray
* @access public * @access public
* @uses NeatArray::value * @uses NeatArray::value
*/ */
function cleanup () function cleanup ()
{ {
$out = is_array($this->value)? array(): null; $out = is_array($this->value)? array(): null;
foreach ($this->value as $k=>$v) foreach ($this->value as $k=>$v)
{ {
@ -108,7 +108,7 @@ class NeatArray
} }
} }
$this->value = $out; $this->value = $out;
} }
/** /**
* Adds elements from given array to itself. * Adds elements from given array to itself.
@ -118,10 +118,10 @@ class NeatArray
* @access public * @access public
* @uses NeatArray::value * @uses NeatArray::value
*/ */
function add ($value) function add ($value)
{ {
return ($this->value = $this->plus($value))? true: false; return ($this->value = $this->plus($value))? true: false;
} }
/** /**
* Returns itself merged with given array. * Returns itself merged with given array.
@ -131,10 +131,10 @@ class NeatArray
* @access public * @access public
* @uses NeatArray::value * @uses NeatArray::value
*/ */
function plus ($value) function plus ($value)
{ {
return array_merge($this->value, (is_array($value)? $value: array($value))); return array_merge($this->value, (is_array($value)? $value: array($value)));
} }
/** /**
* Counts repeating strings and returns an array of totals. * Counts repeating strings and returns an array of totals.
@ -144,8 +144,8 @@ class NeatArray
* @access public * @access public
* @uses NeatArray::value * @uses NeatArray::value
*/ */
function totals ($sortedBy=1,$reverse=true) function totals ($sortedBy=1,$reverse=true)
{ {
$out = array(); $out = array();
foreach ($this->value as $val) foreach ($this->value as $val)
{ {
@ -163,7 +163,7 @@ class NeatArray
} }
return $out; return $out;
} }
/** /**
* Performs an array_filter() on the contents of this NeatArray. * Performs an array_filter() on the contents of this NeatArray.
@ -171,10 +171,10 @@ class NeatArray
* @param string $with Name of callback function to perform on each element of this NeatArray. * @param string $with Name of callback function to perform on each element of this NeatArray.
* @return array * @return array
*/ */
function filter ($with) function filter ($with)
{ {
return $this->value = array_filter($this->value, $with); return $this->value = array_filter($this->value, $with);
} }
/** /**
* Passes each of its values through a specified function or method. * Passes each of its values through a specified function or method.
@ -185,11 +185,11 @@ class NeatArray
* @access public * @access public
* @uses NeatArray::value * @uses NeatArray::value
*/ */
function walk ($with) function walk ($with)
{ {
array_walk($this->value, $with); array_walk($this->value, $with);
return $this->value; return $this->value;
} }
/** /**
* Apply $template to all elements of this NeatArray, and return the array itself. * Apply $template to all elements of this NeatArray, and return the array itself.
@ -197,15 +197,15 @@ class NeatArray
* @param string $template {@link http://php.net/sprintf sprintf()}-compatible string to be applied to all values of this NeatArray. * @param string $template {@link http://php.net/sprintf sprintf()}-compatible string to be applied to all values of this NeatArray.
* @return array * @return array
*/ */
function sprintf($template) function sprintf($template)
{ {
for ($ii=0; $ii<count($this->value); $ii++) for ($ii=0; $ii<count($this->value); $ii++)
{ {
$this->value[$ii] = sprintf($template, $this->value[$ii]); $this->value[$ii] = sprintf($template, $this->value[$ii]);
} }
return $this->value; return $this->value;
} }
/** /**
* Extracts a value from all array items. * Extracts a value from all array items.
@ -214,8 +214,8 @@ class NeatArray
* @access public * @access public
* @uses NeatArray::value * @uses NeatArray::value
*/ */
function extract ($name) function extract ($name)
{ {
$out = array(); $out = array();
foreach ($this->value as $val) foreach ($this->value as $val)
{ {
@ -223,27 +223,27 @@ class NeatArray
$out[] = $val[$name]; $out[] = $val[$name];
} }
return $out; return $out;
} }
/** /**
* Returns a list of unique elements. * Returns a list of unique elements.
* *
* @return array * @return array
*/ */
function unique () function unique ()
{ {
return array_unique($this->value); return array_unique($this->value);
} }
/** /**
* Removes duplicate elements from the value and returns it. * Removes duplicate elements from the value and returns it.
* *
* @return array * @return array
*/ */
function makeUnique () function makeUnique ()
{ {
return $this->value = array_unique($this->value); return $this->value = array_unique($this->value);
} }
/** /**
* Joins an array with myself using a key (like a join between database tables). * Joins an array with myself using a key (like a join between database tables).
@ -251,7 +251,7 @@ class NeatArray
* Example: * Example:
* *
* $alice = array('id'=>'1', 'name'=>'Alice'); * $alice = array('id'=>'1', 'name'=>'Alice');
* $bob = array('id'=>'2', 'name'=>'Bob'); * $bob = array('id'=>'2', 'name'=>'Bob');
* *
* $users = new NeatArray(array($alice, $bob)); * $users = new NeatArray(array($alice, $bob));
* *
@ -268,7 +268,7 @@ class NeatArray
* $users->value == array * $users->value == array
* ( * (
* array('id'=>'1', 'name'=>'Alice', 'born'=>'1980'), * array('id'=>'1', 'name'=>'Alice', 'born'=>'1980'),
* array('id'=>'2', 'name'=>'Bob', 'born'=>'1976') * array('id'=>'2', 'name'=>'Bob', 'born'=>'1976')
* ); * );
* *
* *
@ -277,8 +277,8 @@ class NeatArray
* @param string $onHis Key to use on him. * @param string $onHis Key to use on him.
* @return array * @return array
*/ */
function joinWith ($his, $onMine, $onHis=null) function joinWith ($his, $onMine, $onHis=null)
{ {
if (empty($onHis)) if (empty($onHis))
{ {
$onHis = $onMine; $onHis = $onMine;
@ -301,7 +301,7 @@ class NeatArray
} }
return $this->value = $out; return $this->value = $out;
} }
/** /**
* Enter description here... * Enter description here...
@ -313,8 +313,8 @@ class NeatArray
* @param string $childrenKey * @param string $childrenKey
* @return array * @return array
*/ */
function threaded ($root=null, $idKey='id', $parentIdKey='parent_id', $childrenKey='children') function threaded ($root=null, $idKey='id', $parentIdKey='parent_id', $childrenKey='children')
{ {
$out = array(); $out = array();
$sizeof = sizeof($this->value); $sizeof = sizeof($this->value);
for ($ii=0; $ii < $sizeof; $ii++) for ($ii=0; $ii < $sizeof; $ii++)
@ -330,7 +330,7 @@ class NeatArray
} }
return $out; return $out;
} }
/** /**
@ -341,8 +341,8 @@ class NeatArray
* @return array * @return array
* @link http://php.net/array_search#47116 * @link http://php.net/array_search#47116
*/ */
function multi_search($search_value, $the_array=null) function multi_search($search_value, $the_array=null)
{ {
if ( $the_array == null ) if ( $the_array == null )
{ {
$the_array = $this->value; $the_array = $this->value;
@ -355,14 +355,14 @@ class NeatArray
$result = $this->multi_search($search_value, $value); $result = $this->multi_search($search_value, $value);
if (is_array($result)) if (is_array($result))
{ {
$return = $result; $return = $result;
array_unshift($return, $key); array_unshift($return, $key);
return $return; return $return;
} }
elseif ($result == true) elseif ($result == true)
{ {
$return[] = $key; $return[] = $key;
return $return; return $return;
} }
} }
return false; return false;
@ -375,7 +375,7 @@ class NeatArray
} }
else return false; else return false;
} }
} }
} }

View file

@ -40,7 +40,7 @@
*/ */
class NeatString class NeatString
{ {
/** /**
* Returns an array with each of the non-empty characters in $string as an element. * Returns an array with each of the non-empty characters in $string as an element.
* *
* @param string $string * @param string $string
@ -51,7 +51,7 @@ class NeatString
return preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY); return preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY);
} }
/** /**
* Returns string with Cyrillic characters translated to Roman ones. * Returns string with Cyrillic characters translated to Roman ones.
* *
* @param string $string * @param string $string
@ -65,7 +65,7 @@ class NeatString
return str_replace($pl, $ro, $string); return str_replace($pl, $ro, $string);
} }
/** /**
* Returns string as lowercase with whitespace removed. * Returns string as lowercase with whitespace removed.
* *
* @param string $string * @param string $string
@ -77,7 +77,7 @@ class NeatString
return strtolower(str_replace($whitespace, '', $string)); return strtolower(str_replace($whitespace, '', $string));
} }
/** /**
* Returns a random password. * Returns a random password.
* *
* @param integer $length Length of generated password * @param integer $length Length of generated password

View file

@ -47,7 +47,7 @@ class Object
* *
* @var object * @var object
*/ */
var $_log = null; var $_log = null;
/** /**
* A hack to support __construct() on PHP 4 * A hack to support __construct() on PHP 4
@ -57,24 +57,24 @@ class Object
* *
* @return Object * @return Object
*/ */
function Object() function Object()
{ {
$args = func_get_args(); $args = func_get_args();
if (method_exists($this, '__destruct')) if (method_exists($this, '__destruct'))
{ {
register_shutdown_function(array(&$this, '__destruct')); register_shutdown_function(array(&$this, '__destruct'));
} }
call_user_func_array(array(&$this, '__construct'), $args); call_user_func_array(array(&$this, '__construct'), $args);
} }
/** /**
* Class constructor, overridden in descendant classes. * Class constructor, overridden in descendant classes.
*/ */
function __construct() function __construct()
{ {
} }
/** /**
* Object-to-string conversion. * Object-to-string conversion.
@ -82,10 +82,10 @@ class Object
* *
* @return string The name of this class * @return string The name of this class
*/ */
function toString() function toString()
{ {
return get_class($this); return get_class($this);
} }
/** /**
* Calls a controller's method from any location. * Calls a controller's method from any location.
@ -102,7 +102,7 @@ class Object
if(in_array('return', $extra)) if(in_array('return', $extra))
{ {
$extra['return'] = 0; $extra['return'] = 0;
$extra['bare'] = 1; $extra['bare'] = 1;
ob_start(); ob_start();
$out = $dispatcher->dispatch($url, $extra); $out = $dispatcher->dispatch($url, $extra);
$out = ob_get_clean(); $out = ob_get_clean();
@ -111,7 +111,7 @@ class Object
else else
{ {
$extra['return'] = 1; $extra['return'] = 1;
$extra['bare'] = 1; $extra['bare'] = 1;
return $dispatcher->dispatch($url, $extra); return $dispatcher->dispatch($url, $extra);
} }
} }
@ -127,12 +127,12 @@ class Object
* @param string $msg Log message * @param string $msg Log message
* @param int $type Error type constant. Defined in app/config/core.php. * @param int $type Error type constant. Defined in app/config/core.php.
*/ */
function log ($msg, $type=LOG_ERROR) function log ($msg, $type=LOG_ERROR)
{ {
if(!class_exists('CakeLog')) if(!class_exists('CakeLog'))
{ {
uses('cake_log'); uses('cake_log');
} }
if (is_null($this->_log)) if (is_null($this->_log))
{ {
$this->_log = new CakeLog(); $this->_log = new CakeLog();
@ -145,7 +145,7 @@ class Object
default: default:
return $this->_log->write('error', $msg); return $this->_log->write('error', $msg);
} }
} }
/** /**
* Enter description here... * Enter description here...
@ -154,14 +154,14 @@ class Object
* @param unknown_type $messages * @param unknown_type $messages
* @return unknown * @return unknown
*/ */
function cakeError($method, $messages) function cakeError($method, $messages)
{ {
if(!class_exists('ErrorHandler')) if(!class_exists('ErrorHandler'))
{ {
uses('error'); uses('error');
} }
return new ErrorHandler($method, $messages); return new ErrorHandler($method, $messages);
} }
} }
?> ?>

View file

@ -28,40 +28,40 @@
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
/** /**
* Included libraries. * Included libraries.
* *
*/ */
if(!class_exists('Object')) if(!class_exists('Object'))
{ {
uses('object'); uses('object');
} }
/** /**
* Parses the request URL into controller, action, and parameters. * Parses the request URL into controller, action, and parameters.
* *
* @package cake * @package cake
* @subpackage cake.cake.libs * @subpackage cake.cake.libs
* @since CakePHP v 0.2.9 * @since CakePHP v 0.2.9
* *
*/ */
class Router extends Object { class Router extends Object {
/** /**
* Array of routes * Array of routes
* *
* @var array * @var array
*/ */
var $routes = array(); var $routes = array();
/** /**
* TODO: Better description. Returns this object's routes array. Returns false if there are no routes available. * TODO: Better description. Returns this object's routes array. Returns false if there are no routes available.
* *
* @param string $route An empty string, or a route string "/" * @param string $route An empty string, or a route string "/"
* @param array $default NULL or an array describing the default route * @param array $default NULL or an array describing the default route
* @see routes * @see routes
* @return array Array of routes * @return array Array of routes
*/ */
function connect ($route, $default=null) function connect ($route, $default=null)
{ {
$parsed = $names = array (); $parsed = $names = array ();
$r = null; $r = null;
@ -103,19 +103,19 @@ class Router extends Object {
$this->routes[] = array($route, $regexp, $names, $default); $this->routes[] = array($route, $regexp, $names, $default);
} }
return $this->routes; return $this->routes;
} }
/** /**
* Parses given URL and returns an array of controllers, action and parameters * Parses given URL and returns an array of controllers, action and parameters
* taken from that URL. * taken from that URL.
* *
* @param string $url URL to be parsed * @param string $url URL to be parsed
* @return array * @return array
*/ */
function parse ($url) function parse ($url)
{ {
// An URL should start with a '/', mod_rewrite doesn't respect that, but no-mod_rewrite version does. // An URL should start with a '/', mod_rewrite doesn't respect that, but no-mod_rewrite version does.
// Here's the fix. // Here's the fix.
if ($url && ('/' != $url[0])) if ($url && ('/' != $url[0]))
{ {
$url = '/'.$url; $url = '/'.$url;
@ -167,20 +167,20 @@ class Router extends Object {
if (preg_match($regexp, $url, $r)) if (preg_match($regexp, $url, $r))
{ {
// $this->log($url.' matched '.$regexp, 'note'); // $this->log($url.' matched '.$regexp, 'note');
// remove the first element, which is the url // remove the first element, which is the url
array_shift($r); array_shift($r);
// hack, pre-fill the default route names // hack, pre-fill the default route names
foreach ($names as $name) foreach ($names as $name)
$out[$name] = null; $out[$name] = null;
$ii = 0; $ii = 0;
if (is_array($defaults)) if (is_array($defaults))
{ {
foreach ($defaults as $name=>$value) foreach ($defaults as $name=>$value)
{ {
if (preg_match('#[a-zA-Z_\-]#i', $name)) if (preg_match('#[a-zA-Z_\-]#i', $name))
{ {
$out[$name] = $value; $out[$name] = $value;
@ -189,31 +189,31 @@ class Router extends Object {
{ {
$out['pass'][] = $value; $out['pass'][] = $value;
} }
} }
} }
foreach ($r as $found) foreach ($r as $found)
{ {
// if $found is a named url element (i.e. ':action') // if $found is a named url element (i.e. ':action')
if (isset($names[$ii])) if (isset($names[$ii]))
{ {
$out[$names[$ii]] = $found; $out[$names[$ii]] = $found;
} }
// unnamed elements go in as 'pass' // unnamed elements go in as 'pass'
else else
{ {
$pass = new NeatArray(explode('/', $found)); $pass = new NeatArray(explode('/', $found));
$pass->cleanup(); $pass->cleanup();
$out['pass'] = $pass->value; $out['pass'] = $pass->value;
} }
$ii++; $ii++;
} }
break; break;
} }
} }
return $out; return $out;
} }
} }
?> ?>

View file

@ -62,10 +62,10 @@ class Sanitize
if(is_array($string)) if(is_array($string))
{ {
foreach ($string as $key => $clean) foreach ($string as $key => $clean)
{ {
$cleaned[$key] = preg_replace( "/[^{$allow}a-zA-Z0-9]/", "", $clean); $cleaned[$key] = preg_replace( "/[^{$allow}a-zA-Z0-9]/", "", $clean);
} }
} }
else else
{ {
@ -80,38 +80,38 @@ class Sanitize
* @param string $string * @param string $string
* @return string * @return string
*/ */
function sql($string) function sql($string)
{ {
if (!ini_get('magic_quotes_gpc')) if (!ini_get('magic_quotes_gpc'))
{ {
$string = addslashes($string); $string = addslashes($string);
} }
return $string; return $string;
} }
/** /**
* Returns given string safe for display as HTML. Renders entities and converts newlines to <br/>. * Returns given string safe for display as HTML. Renders entities and converts newlines to <br />.
* *
* @param string $string * @param string $string
* @param boolean $remove If true, the string is stripped of all HTML tags * @param boolean $remove If true, the string is stripped of all HTML tags
* @return string * @return string
*/ */
function html($string, $remove = false) function html($string, $remove = false)
{ {
if ($remove) if ($remove)
{ {
$string = strip_tags($string); $string = strip_tags($string);
} }
else else
{ {
$patterns = array("/\&/", "/%/", "/</", "/>/", '/"/', "/'/", "/\(/", "/\)/", "/\+/", "/-/", "/\n/"); $patterns = array("/\&/", "/%/", "/</", "/>/", '/"/', "/'/", "/\(/", "/\)/", "/\+/", "/-/", "/\n/");
$replacements = array("&amp;", "&#37;", "&lt;", "&gt;", "&quot;", "&#39;", "&#40;", "&#41;", "&#43;", "&#45;", "<br/>"); $replacements = array("&amp;", "&#37;", "&lt;", "&gt;", "&quot;", "&#39;", "&#40;", "&#41;", "&#43;", "&#45;", "<br />");
$string = preg_replace($patterns, $replacements, $string); $string = preg_replace($patterns, $replacements, $string);
} }
return $string; return $string;
} }
/** /**
* Recursively sanitizes given array of data for safe input. * Recursively sanitizes given array of data for safe input.
@ -119,10 +119,10 @@ class Sanitize
* @param mixed $toClean * @param mixed $toClean
* @return mixed * @return mixed
*/ */
function cleanArray(&$toClean) function cleanArray(&$toClean)
{ {
return $this->cleanArrayR($toClean); return $this->cleanArrayR($toClean);
} }
/** /**
* Private method used for recursion (see cleanArray()). * Private method used for recursion (see cleanArray()).
@ -131,19 +131,19 @@ class Sanitize
* @return array * @return array
* @see cleanArray * @see cleanArray
*/ */
function cleanArrayR(&$toClean) function cleanArrayR(&$toClean)
{ {
if (is_array($toClean)) if (is_array($toClean))
{ {
while(list($k, $v) = each($toClean)) while(list($k, $v) = each($toClean))
{ {
if ( is_array($toClean[$k]) ) if ( is_array($toClean[$k]) )
{ {
$this->cleanArray($toClean[$k]); $this->cleanArray($toClean[$k]);
} }
else else
{ {
$toClean[$k] = $this->cleanValue($v); $toClean[$k] = $this->cleanValue($v);
} }
} }
} }
@ -151,29 +151,29 @@ class Sanitize
{ {
return null; return null;
} }
} }
/** /**
* Do we really need to sanitize array keys? If so, we can use this code... * Do we really need to sanitize array keys? If so, we can use this code...
function cleanKey($key) function cleanKey($key)
{ {
if ($key == "") if ($key == "")
{ {
return ""; return "";
} }
//URL decode and convert chars to HTML entities //URL decode and convert chars to HTML entities
$key = htmlspecialchars(urldecode($key)); $key = htmlspecialchars(urldecode($key));
//Remove .. //Remove ..
$key = preg_replace( "/\.\./", "", $key ); $key = preg_replace( "/\.\./", "", $key );
//Remove __FILE__, etc. //Remove __FILE__, etc.
$key = preg_replace( "/\_\_(.+?)\_\_/", "", $key ); $key = preg_replace( "/\_\_(.+?)\_\_/", "", $key );
//Trim word chars, '.', '-', '_' //Trim word chars, '.', '-', '_'
$key = preg_replace( "/^([\w\.\-\_]+)$/", "$1", $key ); $key = preg_replace( "/^([\w\.\-\_]+)$/", "$1", $key );
return $key; return $key;
} }
*/ */
/** /**
@ -182,37 +182,37 @@ class Sanitize
* @param string $val * @param string $val
* @return string * @return string
*/ */
function cleanValue($val) function cleanValue($val)
{ {
if ($val == "") if ($val == "")
{ {
return ""; return "";
} }
//Replace odd spaces with safe ones //Replace odd spaces with safe ones
$val = str_replace(" ", " ", $val); $val = str_replace(" ", " ", $val);
$val = str_replace(chr(0xCA), "", $val); $val = str_replace(chr(0xCA), "", $val);
//Encode any HTML to entities (including \n --> <br/>) //Encode any HTML to entities (including \n --> <br />)
$val = $this->html($val); $val = $this->html($val);
//Double-check special chars and remove carriage returns //Double-check special chars and remove carriage returns
//For increased SQL security //For increased SQL security
$val = preg_replace( "/\\\$/" ,"$" ,$val); $val = preg_replace( "/\\\$/" ,"$" ,$val);
$val = preg_replace( "/\r/" ,"" ,$val); $val = preg_replace( "/\r/" ,"" ,$val);
$val = str_replace ( "!" ,"!" ,$val); $val = str_replace ( "!" ,"!" ,$val);
$val = str_replace ( "'" , "'" ,$val); $val = str_replace ( "'" , "'" ,$val);
//Allow unicode (?) //Allow unicode (?)
$val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val ); $val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val );
//Add slashes for SQL //Add slashes for SQL
$val = $this->sql($val); $val = $this->sql($val);
//Swap user-inputted backslashes (?) //Swap user-inputted backslashes (?)
$val = preg_replace( "/\\\(?!&amp;#|\?#)/", "\\", $val ); $val = preg_replace( "/\\\(?!&amp;#|\?#)/", "\\", $val );
return $val; return $val;
} }
} }
?> ?>

View file

@ -116,7 +116,7 @@ class Security extends Object
{ {
if (!defined('CIPHER_SEED')) if (!defined('CIPHER_SEED'))
{ {
//This is temporary will change later //This is temporary will change later
define('CIPHER_SEED', 'mKEZGy8AB8FErX4t'); define('CIPHER_SEED', 'mKEZGy8AB8FErX4t');
} }
srand(CIPHER_SEED); srand(CIPHER_SEED);

View file

@ -62,7 +62,7 @@ class CakeSession extends Object
* *
* @var string * @var string
*/ */
var $path = false; var $path = false;
/** /**
* Error number of last occurred error * Error number of last occurred error
* *
@ -87,7 +87,7 @@ class CakeSession extends Object
* *
* @var integer * @var integer
*/ */
var $time = false; var $time = false;
/** /**
* Time when this session becomes invalid. * Time when this session becomes invalid.
* *
@ -431,7 +431,7 @@ class CakeSession extends Object
if($this->readSessionVar("Config")) if($this->readSessionVar("Config"))
{ {
if($this->userAgent == $this->readSessionVar("Config.userAgent") if($this->userAgent == $this->readSessionVar("Config.userAgent")
&& $this->time <= $this->readSessionVar("Config.time")) && $this->time <= $this->readSessionVar("Config.time"))
{ {
$this->writeSessionVar("Config.time", $this->sessionTime); $this->writeSessionVar("Config.time", $this->sessionTime);
$this->valid = true; $this->valid = true;

View file

@ -29,23 +29,23 @@
*/ */
/** /**
* Not empty. * Not empty.
*/ */
define('VALID_NOT_EMPTY', '/.+/'); define('VALID_NOT_EMPTY', '/.+/');
/** /**
* Numbers [0-9] only. * Numbers [0-9] only.
*/ */
define('VALID_NUMBER', '/^[0-9]+$/'); define('VALID_NUMBER', '/^[0-9]+$/');
/** /**
* A valid email address. * A valid email address.
*/ */
define('VALID_EMAIL', '/\\A(?:^([a-z0-9][a-z0-9_\\-\\.\\+]*)@([a-z0-9][a-z0-9\\.\\-]{0,63}\\.(com|org|net|biz|info|name|net|pro|aero|coop|museum|[a-z]{2,4}))$)\\z/i'); define('VALID_EMAIL', '/\\A(?:^([a-z0-9][a-z0-9_\\-\\.\\+]*)@([a-z0-9][a-z0-9\\.\\-]{0,63}\\.(com|org|net|biz|info|name|net|pro|aero|coop|museum|[a-z]{2,4}))$)\\z/i');
/** /**
* A valid year (1000-2999). * A valid year (1000-2999).
*/ */
define('VALID_YEAR', '/^[12][0-9]{3}$/'); define('VALID_YEAR', '/^[12][0-9]{3}$/');
?> ?>

View file

@ -40,16 +40,16 @@
*/ */
class Helper extends Object class Helper extends Object
{ {
/************************************************************************* /*************************************************************************
* Public variables * Public variables
*************************************************************************/ *************************************************************************/
/**#@+ /**#@+
* @access public * @access public
*/ */
/** /**
* Holds tag templates. * Holds tag templates.
* *
* @access public * @access public
@ -57,17 +57,17 @@ class Helper extends Object
*/ */
var $tags = array(); var $tags = array();
/**#@-*/ /**#@-*/
/************************************************************************* /*************************************************************************
* Public methods * Public methods
*************************************************************************/ *************************************************************************/
/**#@+ /**#@+
* @access public * @access public
*/ */
/** /**
* Constructor. * Constructor.
* *
* Parses tag templates into $this->tags. * Parses tag templates into $this->tags.
@ -80,10 +80,10 @@ class Helper extends Object
function loadConfig() function loadConfig()
{ {
return $this->readConfigFile($config = fileExistsInPath(CAKE.'config'.DS.'tags.ini.php')); return $this->readConfigFile($config = fileExistsInPath(CAKE.'config'.DS.'tags.ini.php'));
} }
/** /**
* Decides whether to output or return a string. * Decides whether to output or return a string.
* *
* Based on AUTO_OUTPUT and $return's value, this method decides whether to * Based on AUTO_OUTPUT and $return's value, this method decides whether to
@ -92,7 +92,7 @@ class Helper extends Object
* @param string $str String to be output or returned. * @param string $str String to be output or returned.
* @param boolean $return Whether this method should return a value or * @param boolean $return Whether this method should return a value or
* output it. This overrides AUTO_OUTPUT. * output it. This overrides AUTO_OUTPUT.
* @return mixed Either string or boolean value, depends on AUTO_OUTPUT * @return mixed Either string or boolean value, depends on AUTO_OUTPUT
* and $return. * and $return.
*/ */
function output($str, $return = false) function output($str, $return = false)
@ -114,7 +114,7 @@ class Helper extends Object
} }
} }
/** /**
* Assigns values to tag templates. * Assigns values to tag templates.
* *
* Finds a tag template by $keyName, and replaces $values's keys with * Finds a tag template by $keyName, and replaces $values's keys with
@ -148,9 +148,9 @@ class Helper extends Object
{ {
if ($firstChar == '[' && substr($dataLine, -1, 1) == ']') if ($firstChar == '[' && substr($dataLine, -1, 1) == ']')
{ {
// [section block] we might use this later do not know for sure // [section block] we might use this later do not know for sure
// this could be used to add a key with the section block name // this could be used to add a key with the section block name
// but it adds another array level // but it adds another array level
} }
else else
{ {
@ -178,7 +178,7 @@ class Helper extends Object
return $iniSetting; return $iniSetting;
} }
/**#@-*/ /**#@-*/
} }
?> ?>

View file

@ -43,58 +43,58 @@ class AjaxHelper extends Helper
{ {
/** /**
* Included helpers. * Included helpers.
* *
* @var array * @var array
*/ */
var $helpers = array('Html', 'Javascript'); var $helpers = array('Html', 'Javascript');
/** /**
* Names of Javascript callback functions. * Names of Javascript callback functions.
* *
* @var array * @var array
*/ */
var $callbacks = array('uninitialized', 'loading', 'loaded', 'interactive', 'complete'); var $callbacks = array('uninitialized', 'loading', 'loaded', 'interactive', 'complete');
/** /**
* Names of AJAX options. * Names of AJAX options.
* *
* @var array * @var array
*/ */
var $ajaxOptions = array('type', 'confirm', 'condition', 'before', 'after', 'fallback', 'update', 'loading', 'loaded', 'interactive', 'complete', 'with', 'url', 'method', 'position', 'form', 'parameters', 'evalScripts', 'asynchronous', 'onComplete', 'onUninitialized', 'onLoading', 'onLoaded', 'onInteractive'); var $ajaxOptions = array('type', 'confirm', 'condition', 'before', 'after', 'fallback', 'update', 'loading', 'loaded', 'interactive', 'complete', 'with', 'url', 'method', 'position', 'form', 'parameters', 'evalScripts', 'asynchronous', 'onComplete', 'onUninitialized', 'onLoading', 'onLoaded', 'onInteractive');
/** /**
* Options for draggable. * Options for draggable.
* *
* @var array * @var array
*/ */
var $dragOptions = array('handle', 'revert', 'constraint', 'change'); var $dragOptions = array('handle', 'revert', 'constraint', 'change');
/** /**
* Options for droppable. * Options for droppable.
* *
* @var array * @var array
*/ */
var $dropOptions = array('accept', 'containment', 'overlap', 'greedy', 'hoverclass', 'onHover', 'onDrop'); var $dropOptions = array('accept', 'containment', 'overlap', 'greedy', 'hoverclass', 'onHover', 'onDrop');
/** /**
* Options for sortable. * Options for sortable.
* *
* @var array * @var array
*/ */
var $sortOptions = array('tag', 'only', 'overlap', 'constraint', 'containment', 'handle', 'hoverClass', 'ghosting', 'dropOnEmpty', 'onUpdate', 'onChange'); var $sortOptions = array('tag', 'only', 'overlap', 'constraint', 'containment', 'handle', 'hoverClass', 'ghosting', 'dropOnEmpty', 'onUpdate', 'onChange');
/** /**
* Options for slider. * Options for slider.
* *
* @var array * @var array
*/ */
var $sliderOptions = array('axis', 'increment', 'maximum', 'minimum', 'alignX', 'alignY', 'sliderValue', 'disabled', 'handleImage', 'handleDisabled', 'values', 'onSlide', 'onChange'); var $sliderOptions = array('axis', 'increment', 'maximum', 'minimum', 'alignX', 'alignY', 'sliderValue', 'disabled', 'handleImage', 'handleDisabled', 'values', 'onSlide', 'onChange');
/** /**
* Options for in-place editor. * Options for in-place editor.
* *
* @var array * @var array
*/ */
var $editorOptions = array('okText', 'cancelText', 'savingText', 'formId', 'externalControl', 'rows', 'cols', 'size', 'highlightcolor', 'highlightendcolor', 'savingClassName', 'formClassName', 'loadTextURL', 'loadingText', 'callback', 'ajaxOptions'); var $editorOptions = array('okText', 'cancelText', 'savingText', 'formId', 'externalControl', 'rows', 'cols', 'size', 'highlightcolor', 'highlightendcolor', 'savingClassName', 'formClassName', 'loadTextURL', 'loadingText', 'callback', 'ajaxOptions');
@ -122,20 +122,20 @@ class AjaxHelper extends Helper
* *
* Example: * Example:
* <code> * <code>
* link (word, * link (word,
* array("url" => "undo", "n" => word_counter), * array("url" => "undo", "n" => word_counter),
* array("complete" => "undoRequestCompleted(request)")); * array("complete" => "undoRequestCompleted(request)"));
* </code> * </code>
* *
* The callbacks that may be specified are: * The callbacks that may be specified are:
* *
* - <i>loading</i>:: Called when the remote document is being * - <i>loading</i>:: Called when the remote document is being
* loaded with data by the browser. * loaded with data by the browser.
* - <i>loaded</i>:: Called when the browser has finished loading * - <i>loaded</i>:: Called when the browser has finished loading
* the remote document. * the remote document.
* - <i>interactive</i>:: Called when the user can interact with the * - <i>interactive</i>:: Called when the user can interact with the
* remote document, even though it has not * remote document, even though it has not
* finished loading. * finished loading.
* - <i>complete</i>:: Called when the XMLHttpRequest is complete. * - <i>complete</i>:: Called when the XMLHttpRequest is complete.
* *
* If you for some reason or another need synchronous processing (that'll * If you for some reason or another need synchronous processing (that'll
@ -151,17 +151,17 @@ class AjaxHelper extends Helper
* by this expression. Use this to * by this expression. Use this to
* describe browser-side conditions when * describe browser-side conditions when
* request should not be initiated. * request should not be initiated.
* - <i>before</i>:: Called before request is initiated. * - <i>before</i>:: Called before request is initiated.
* - <i>after</i>:: Called immediately after request was * - <i>after</i>:: Called immediately after request was
* initiated and before <i>loading</i>. * initiated and before <i>loading</i>.
* *
* @param string $title Title of link * @param string $title Title of link
* @param string $href Href string "/products/view/12" * @param string $href Href string "/products/view/12"
* @param array $options Options for JavaScript function * @param array $options Options for JavaScript function
* @param string $confirm Confirmation message. Calls up a JavaScript confirm() message. * @param string $confirm Confirmation message. Calls up a JavaScript confirm() message.
* @param boolean $escapeTitle Escaping the title string to HTML entities * @param boolean $escapeTitle Escaping the title string to HTML entities
* *
* @return string HTML code for link to remote action * @return string HTML code for link to remote action
*/ */
function link($title, $href = null, $options = array(), $confirm = null, $escapeTitle = true) function link($title, $href = null, $options = array(), $confirm = null, $escapeTitle = true)
{ {
@ -200,7 +200,7 @@ class AjaxHelper extends Helper
function linkToRemote ($title, $options = array(), $html_options = array()) function linkToRemote ($title, $options = array(), $html_options = array())
{ {
//trigger_error('Deprecated function: use AjaxHelper::link', E_USER_WARNING); //trigger_error('Deprecated function: use AjaxHelper::link', E_USER_WARNING);
$href = '#'; $href = '#';
if (!empty($options['fallback']) && isset($options['fallback'])) if (!empty($options['fallback']) && isset($options['fallback']))
{ {
@ -217,16 +217,16 @@ class AjaxHelper extends Helper
} }
} }
/** /**
* Creates JavaScript function for remote AJAX call * Creates JavaScript function for remote AJAX call
* *
* This function creates the javascript needed to make a remote call * This function creates the javascript needed to make a remote call
* it is primarily used as a helper for linkToRemote. * it is primarily used as a helper for linkToRemote.
* *
* @see linkToRemote() for docs on options parameter. * @see linkToRemote() for docs on options parameter.
* *
* @param array $options options for javascript * @param array $options options for javascript
* @return string html code for link to remote action * @return string html code for link to remote action
*/ */
function remoteFunction ($options = null) function remoteFunction ($options = null)
{ {
$javascript_options = $this->__optionsForAjax($options); $javascript_options = $this->__optionsForAjax($options);
@ -255,15 +255,15 @@ class AjaxHelper extends Helper
} }
/** /**
* Periodically call remote url via AJAX. * Periodically call remote url via AJAX.
* *
* Periodically calls the specified url (<i>options[url]</i>) every <i>options[frequency]</i> seconds (default is 10). * Periodically calls the specified url (<i>options[url]</i>) every <i>options[frequency]</i> seconds (default is 10).
* Usually used to update a specified div (<i>options[update]</i>) with the results of the remote call. * Usually used to update a specified div (<i>options[update]</i>) with the results of the remote call.
* The options for specifying the target with url and defining callbacks is the same as linkToRemote. * The options for specifying the target with url and defining callbacks is the same as linkToRemote.
* *
* @param array $options Callback options * @param array $options Callback options
* @return string Javascript code * @return string Javascript code
*/ */
function remoteTimer ($options = null) function remoteTimer ($options = null)
{ {
$frequency = (isset($options['frequency']))? $options['frequency'] : 10; $frequency = (isset($options['frequency']))? $options['frequency'] : 10;
@ -272,18 +272,18 @@ class AjaxHelper extends Helper
} }
/** /**
* Returns form tag that will submit using Ajax. * Returns form tag that will submit using Ajax.
* *
* Returns a form tag that will submit using XMLHttpRequest in the background instead of the regular * Returns a form tag that will submit using XMLHttpRequest in the background instead of the regular
* reloading POST arrangement. Even though it's using Javascript to serialize the form elements, the form submission * reloading POST arrangement. Even though it's using Javascript to serialize the form elements, the form submission
* will work just like a regular submission as viewed by the receiving side (all elements available in params). * will work just like a regular submission as viewed by the receiving side (all elements available in params).
* The options for specifying the target with :url and defining callbacks is the same as link_to_remote. * The options for specifying the target with :url and defining callbacks is the same as link_to_remote.
* *
* @param array $params Form id * @param array $params Form id
* @param array $type How form data is posted: 'get' or 'post' * @param array $type How form data is posted: 'get' or 'post'
* @param array $options Callback/HTML options * @param array $options Callback/HTML options
* @return string JavaScript/HTML code * @return string JavaScript/HTML code
*/ */
function form($params = null, $type = 'post', $options = array()) function form($params = null, $type = 'post', $options = array())
{ {
if (is_array($params)) if (is_array($params))
@ -326,15 +326,15 @@ class AjaxHelper extends Helper
} }
/** /**
* Returns a button input tag that will submit using Ajax * Returns a button input tag that will submit using Ajax
* *
* Returns a button input tag that will submit form using XMLHttpRequest in the background instead of regular * Returns a button input tag that will submit form using XMLHttpRequest in the background instead of regular
* reloading POST arrangement. <i>options</i> argument is the same as in <i>form_remote_tag</i> * reloading POST arrangement. <i>options</i> argument is the same as in <i>form_remote_tag</i>
* *
* @param string $title Input button title * @param string $title Input button title
* @param array $options Callback options * @param array $options Callback options
* @return string Ajaxed input button * @return string Ajaxed input button
*/ */
function submit ($title = 'Submit', $options = array()) function submit ($title = 'Submit', $options = array())
{ {
$htmlOptions = $this->__getHtmlOptions($options); $htmlOptions = $this->__getHtmlOptions($options);
@ -360,33 +360,33 @@ class AjaxHelper extends Helper
} }
/** /**
* Observe field and call ajax on change. * Observe field and call ajax on change.
* *
* Observes the field with the DOM ID specified by <i>field_id</i> and makes * Observes the field with the DOM ID specified by <i>field_id</i> and makes
* an Ajax when its contents have changed. * an Ajax when its contents have changed.
* *
* Required +options+ are: * Required +options+ are:
* - <i>frequency</i>:: The frequency (in seconds) at which changes to * - <i>frequency</i>:: The frequency (in seconds) at which changes to
* this field will be detected. * this field will be detected.
* - <i>url</i>:: @see urlFor() -style options for the action to call * - <i>url</i>:: @see urlFor() -style options for the action to call
* when the field has changed. * when the field has changed.
* *
* Additional options are: * Additional options are:
* - <i>update</i>:: Specifies the DOM ID of the element whose * - <i>update</i>:: Specifies the DOM ID of the element whose
* innerHTML should be updated with the * innerHTML should be updated with the
* XMLHttpRequest response text. * XMLHttpRequest response text.
* - <i>with</i>:: A Javascript expression specifying the * - <i>with</i>:: A Javascript expression specifying the
* parameters for the XMLHttpRequest. This defaults * parameters for the XMLHttpRequest. This defaults
* to Form.Element.serialize('$field_id'), which can be * to Form.Element.serialize('$field_id'), which can be
* accessed from params['form']['field_id']. * accessed from params['form']['field_id'].
* *
* Additionally, you may specify any of the options documented in * Additionally, you may specify any of the options documented in
* @see linkToRemote(). * @see linkToRemote().
* *
* @param string $field_id DOM ID of field to observe * @param string $field_id DOM ID of field to observe
* @param array $options ajax options * @param array $options ajax options
* @return string ajax script * @return string ajax script
*/ */
function observeField ($field_id, $options = array()) function observeField ($field_id, $options = array())
{ {
if (!isset($options['with'])) if (!isset($options['with']))
@ -397,17 +397,17 @@ class AjaxHelper extends Helper
} }
/** /**
* Observe entire form and call ajax on change. * Observe entire form and call ajax on change.
* *
* Like @see observeField(), but operates on an entire form identified by the * Like @see observeField(), but operates on an entire form identified by the
* DOM ID <b>form_id</b>. <b>options</b> are the same as <b>observe_field</b>, except * DOM ID <b>form_id</b>. <b>options</b> are the same as <b>observe_field</b>, except
* the default value of the <i>with</i> option evaluates to the * the default value of the <i>with</i> option evaluates to the
* serialized (request string) value of the form. * serialized (request string) value of the form.
* *
* @param string $field_id DOM ID of field to observe * @param string $field_id DOM ID of field to observe
* @param array $options ajax options * @param array $options ajax options
* @return string ajax script * @return string ajax script
*/ */
function observeForm ($field_id, $options = array()) function observeForm ($field_id, $options = array())
{ {
if (!isset($options['with'])) if (!isset($options['with']))
@ -418,18 +418,18 @@ class AjaxHelper extends Helper
} }
/** /**
* Create a text field with Autocomplete. * Create a text field with Autocomplete.
* *
* Creates an autocomplete field with the given ID and options. * Creates an autocomplete field with the given ID and options.
* *
* options['with'] defaults to "Form.Element.serialize('$field_id')", * options['with'] defaults to "Form.Element.serialize('$field_id')",
* but can be any valid javascript expression defining the * but can be any valid javascript expression defining the
* *
* @param string $field_id DOM ID of field to observe * @param string $field_id DOM ID of field to observe
* @param string $url URL for the autocomplete action * @param string $url URL for the autocomplete action
* @param array $options Ajax options * @param array $options Ajax options
* @return string Ajax script * @return string Ajax script
*/ */
function autoComplete ($field, $url = "", $options = array()) function autoComplete ($field, $url = "", $options = array())
{ {
if (!isset($options['id'])) if (!isset($options['id']))
@ -468,10 +468,10 @@ class AjaxHelper extends Helper
} }
/** /**
* Private helper method to return an array of options for draggable. * Private helper method to return an array of options for draggable.
* *
* @param array $options * @param array $options
* @return array * @return array
*/ */
function _optionsForDraggable ($options) function _optionsForDraggable ($options)
{ {
@ -480,13 +480,13 @@ class AjaxHelper extends Helper
} }
/** /**
* For a reference on the options for this function, check out * For a reference on the options for this function, check out
* http://wiki.script.aculo.us/scriptaculous/show/Droppables.add * http://wiki.script.aculo.us/scriptaculous/show/Droppables.add
* *
* @param unknown_type $id * @param unknown_type $id
* @param array $options * @param array $options
* @return array * @return array
*/ */
function drop($id, $options = array()) function drop($id, $options = array())
{ {
$options = $this->_optionsForDroppable($options); $options = $this->_optionsForDroppable($options);
@ -520,13 +520,13 @@ class AjaxHelper extends Helper
} }
/** /**
* Makes a slider control. * Makes a slider control.
* *
* @param string $id DOM ID of slider handle * @param string $id DOM ID of slider handle
* @param string $track_id DOM ID of slider track * @param string $track_id DOM ID of slider track
* @param array $options Array of options to control the slider * @param array $options Array of options to control the slider
* @link http://wiki.script.aculo.us/scriptaculous/show/Slider * @link http://wiki.script.aculo.us/scriptaculous/show/Slider
*/ */
function slider($id, $track_id, $options = array()) function slider($id, $track_id, $options = array())
{ {
$options = $this->_optionsToString($options, array('axis','handleImage','handleDisabled')); $options = $this->_optionsToString($options, array('axis','handleImage','handleDisabled'));
@ -545,13 +545,13 @@ class AjaxHelper extends Helper
} }
/** /**
* Makes an Ajax In Place editor control. * Makes an Ajax In Place editor control.
* *
* @param string $id DOM ID of input element * @param string $id DOM ID of input element
* @param string $url Postback URL of saved data * @param string $url Postback URL of saved data
* @param array $options Array of options to control the editor, including ajaxOptions (see link). * @param array $options Array of options to control the editor, including ajaxOptions (see link).
* @link http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor * @link http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor
*/ */
function editor($id, $url, $options = array()) function editor($id, $url, $options = array())
{ {
$url = $this->Html->url($url); $url = $this->Html->url($url);
@ -574,12 +574,12 @@ class AjaxHelper extends Helper
} }
/** /**
* Makes a list or group of floated objects sortable. * Makes a list or group of floated objects sortable.
* *
* @param string $id DOM ID of parent * @param string $id DOM ID of parent
* @param array $options Array of options to control sort.http://wiki.script.aculo.us/scriptaculous/show/Sortable.create * @param array $options Array of options to control sort.http://wiki.script.aculo.us/scriptaculous/show/Sortable.create
* @link http://wiki.script.aculo.us/scriptaculous/show/Sortable.create * @link http://wiki.script.aculo.us/scriptaculous/show/Sortable.create
*/ */
function sortable($id, $options = array()) function sortable($id, $options = array())
{ {
if (!empty($options['url'])) if (!empty($options['url']))
@ -604,9 +604,9 @@ class AjaxHelper extends Helper
} }
/** /**
* Private helper function for Javascript. * Private helper function for Javascript.
* *
*/ */
function __optionsForAjax ($options = array()) function __optionsForAjax ($options = array())
{ {
$js_options = $this->_buildCallbacks($options); $js_options = $this->_buildCallbacks($options);
@ -690,12 +690,12 @@ class AjaxHelper extends Helper
} }
/** /**
* Return JavaScript text for an observer... * Return JavaScript text for an observer...
* *
* @param string $klass Name of JavaScript class * @param string $klass Name of JavaScript class
* @param string $name * @param string $name
* @param array $options Ajax options * @param array $options Ajax options
* @return string Formatted JavaScript * @return string Formatted JavaScript
*/ */
function _buildObserver ($klass, $name, $options=null) function _buildObserver ($klass, $name, $options=null)
{ {
@ -712,10 +712,10 @@ class AjaxHelper extends Helper
} }
/** /**
* Enter description here... Return JavaScript text for all callbacks... * Enter description here... Return JavaScript text for all callbacks...
* *
* @param array $options * @param array $options
* @return array * @return array
*/ */
function _buildCallbacks($options) function _buildCallbacks($options)
{ {
@ -744,10 +744,10 @@ class AjaxHelper extends Helper
{ {
foreach ($stringOpts as $option) foreach ($stringOpts as $option)
{ {
if(isset($options[$option]) && !$options[$option][0] != "'") if(isset($options[$option]) && !$options[$option][0] != "'")
{ {
$options[$option] = "'{$options[$option]}'"; $options[$option] = "'{$options[$option]}'";
} }
} }
return $options; return $options;
} }

View file

@ -63,7 +63,7 @@ class FormHelper extends Helper
{ {
var $helpers = array('Html'); var $helpers = array('Html');
/** /**
* Constructor which takes an instance of the HtmlHelper class. * Constructor which takes an instance of the HtmlHelper class.
* *
* @return void * @return void
@ -72,7 +72,7 @@ class FormHelper extends Helper
{ {
} }
/** /**
* 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.
* *
* @param string $field This should be "Modelname/fieldname" * @param string $field This should be "Modelname/fieldname"
@ -92,7 +92,7 @@ class FormHelper extends Helper
} }
} }
/** /**
* Returns a formatted LABEL element for HTML FORMs. * Returns a formatted LABEL element for HTML FORMs.
* *
* @param string $tagName This should be "Modelname/fieldname" * @param string $tagName This should be "Modelname/fieldname"
@ -104,10 +104,10 @@ class FormHelper extends Helper
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.
* *
* @param string $class CSS class name of the div element. * @param string $class CSS class name of the div element.
* @param string $text String content that will appear inside the div element. * @param string $text String content that will appear inside the div element.
* @return string The formatted DIV element * @return string The formatted DIV element
*/ */
@ -116,7 +116,7 @@ class FormHelper extends Helper
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.
* *
* @param string $class CSS class name of the p element. * @param string $class CSS class name of the p element.
@ -128,13 +128,13 @@ class FormHelper extends Helper
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.
* *
* @param string $tagName This should be "Modelname/fieldname" * @param string $tagName This should be "Modelname/fieldname"
* @param string $prompt Text that will appear in the label field. * @param string $prompt Text that will appear in the label field.
* @param bool $required True if this field is a required field. * @param bool $required True if this field is a required field.
* @param string $errorMsg Text that will appear if an error has occurred. * @param string $errorMsg Text that will appear if an error has occurred.
* @param int $size Size attribute for INPUT element * @param int $size Size attribute for INPUT element
* @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.
@ -152,11 +152,11 @@ class FormHelper extends Helper
if( $required ) if( $required )
$divClass = "required"; $divClass = "required";
$strError = ""; // initialize the error to empty. $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. // 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 );
} }
@ -166,7 +166,7 @@ class FormHelper extends Helper
} }
/** /**
* Returns a formatted CHECKBOX tag inside a DIV for HTML FORMs. * Returns a formatted CHECKBOX tag inside a DIV for HTML FORMs.
* *
* @param string $tagName This should be "Modelname/fieldname" * @param string $tagName This should be "Modelname/fieldname"
@ -188,11 +188,11 @@ class FormHelper extends Helper
if( $required ) if( $required )
$divClass = "required"; $divClass = "required";
$strError = ""; // initialize the error to empty. $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. // 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 );
} }
@ -202,13 +202,13 @@ class FormHelper extends Helper
} }
/** /**
* Returns a formatted date option element for HTML FORMs. * Returns a formatted date option element for HTML FORMs.
* *
* @param string $tagName This should be "Modelname/fieldname" * @param string $tagName This should be "Modelname/fieldname"
* @param string $prompt Text that will appear in the label field. * @param string $prompt Text that will appear in the label field.
* @param bool $required True if this field is a required field. * @param bool $required True if this field is a required field.
* @param string $errorMsg Text that will appear if an error has occurred. * @param string $errorMsg Text that will appear if an error has occurred.
* @param int $size Not used. * @param int $size Not used.
* @todo Remove the $size parameter from this method. * @todo Remove the $size parameter from this method.
* @param array $htmlOptions HTML options array * @param array $htmlOptions HTML options array
@ -225,11 +225,11 @@ class FormHelper extends Helper
if( $required ) if( $required )
$divClass = "required"; $divClass = "required";
$strError = ""; // initialize the error to empty. $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. // 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 );
} }
@ -240,7 +240,7 @@ class FormHelper extends Helper
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.
* *
* @param string $tagName This should be "Modelname/fieldname" * @param string $tagName This should be "Modelname/fieldname"
@ -264,11 +264,11 @@ class FormHelper extends Helper
if( $required ) if( $required )
$divClass = "required"; $divClass = "required";
$strError = ""; // initialize the error to empty. $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. // 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 );
} }
@ -279,7 +279,7 @@ class FormHelper extends Helper
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.
* *
* @param string $tagName This should be "Modelname/fieldname" * @param string $tagName This should be "Modelname/fieldname"
@ -305,11 +305,11 @@ class FormHelper extends Helper
if( $required ) if( $required )
$divClass = "required"; $divClass = "required";
$strError = ""; // initialize the error to empty. $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. // 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 );
} }
@ -319,7 +319,7 @@ class FormHelper extends Helper
} }
/** /**
* Returns a formatted SELECT tag for HTML FORMs. * Returns a formatted SELECT tag for HTML FORMs.
* *
* @param string $tagName This should be "Modelname/fieldname" * @param string $tagName This should be "Modelname/fieldname"
@ -343,11 +343,11 @@ class FormHelper extends Helper
if( $required ) if( $required )
$divClass = "required"; $divClass = "required";
$strError = ""; // initialize the error to empty. $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. // 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 );
} }
@ -357,7 +357,7 @@ class FormHelper extends Helper
} }
/** /**
* Returns a formatted submit widget for HTML FORMs. * Returns a formatted submit widget for HTML FORMs.
* *
* @param string $displayText Text that will appear on the widget * @param string $displayText Text that will appear on the widget
@ -369,7 +369,7 @@ class FormHelper extends Helper
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.
* *
* @param array $fields An array of form field definitions * @param array $fields An array of form field definitions

File diff suppressed because it is too large Load diff

View file

@ -43,7 +43,7 @@ class JavascriptHelper extends Helper
var $_cachedEvents = array(); var $_cachedEvents = array();
var $_cacheEvents = false; var $_cacheEvents = false;
/** /**
* 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.
@ -54,7 +54,7 @@ class JavascriptHelper extends Helper
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)
* *
* @param string $url URL to JavaScript file. * @param string $url URL to JavaScript file.
@ -66,7 +66,7 @@ class JavascriptHelper extends Helper
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
* *
* @param string $url URL to JavaScript file. * @param string $url URL to JavaScript file.
@ -79,11 +79,11 @@ class JavascriptHelper extends Helper
} }
/** /**
* Escape carriage returns and single and double quotes for JavaScript segments. * Escape carriage returns and single and double quotes for JavaScript segments.
* *
* @param string $script string that might have javascript elements * @param string $script string that might have javascript elements
* @return string escaped string * @return string escaped string
*/ */
function escapeScript ($script) function escapeScript ($script)
{ {
$script = str_replace(array("\r\n","\n","\r"),'\n', $script); $script = str_replace(array("\r\n","\n","\r"),'\n', $script);
@ -95,11 +95,11 @@ class JavascriptHelper extends Helper
* Escape a string to be JavaScript friendly. * Escape a string to be JavaScript friendly.
* *
* List of escaped ellements: * List of escaped ellements:
* + "\r\n" => '\n' * + "\r\n" => '\n'
* + "\r" => '\n' * + "\r" => '\n'
* + "\n" => '\n' * + "\n" => '\n'
* + '"' => '\"' * + '"' => '\"'
* + "'" => "\\'" * + "'" => "\\'"
* *
* @param string $script String that needs to get escaped. * @param string $script String that needs to get escaped.
* @return string Escaped string. * @return string Escaped string.
@ -108,8 +108,8 @@ class JavascriptHelper extends Helper
{ {
$escape = array( $escape = array(
"\r\n" => '\n', "\r\n" => '\n',
"\r" => '\n', "\r" => '\n',
"\n" => '\n', "\n" => '\n',
'"' => '\"', '"' => '\"',
"'" => "\\'" "'" => "\\'"
); );
@ -117,14 +117,14 @@ class JavascriptHelper extends Helper
return str_replace(array_keys($escape), array_values($escape), $string); 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.
* *
* @param string $object Object to be observed * @param string $object Object to be observed
* @param string $event event to observe * @param string $event event to observe
* @param string $observer function to call * @param string $observer function to call
* @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 = true) function event ($object, $event, $observer, $useCapture = true)
{ {
if($useCapture == true) if($useCapture == true)
@ -149,10 +149,10 @@ class JavascriptHelper extends Helper
/** /**
* Cache JavaScript events created with event() * Cache JavaScript events created with event()
* *
* @return null * @return null
*/ */
function cacheEvents () function cacheEvents ()
{ {
$this->_cacheEvents = true; $this->_cacheEvents = true;
@ -160,10 +160,10 @@ class JavascriptHelper extends Helper
/** /**
* Write cached JavaScript events * Write cached JavaScript events
* *
* @return string A single code block of all cached JavaScript events created with event() * @return string A single code block of all cached JavaScript events created with event()
*/ */
function writeEvents () function writeEvents ()
{ {
$this->_cacheEvents = false; $this->_cacheEvents = false;
@ -171,14 +171,14 @@ class JavascriptHelper extends Helper
} }
/** /**
* 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.
* *
* Note: The recommended approach is to copy the contents of * Note: The recommended approach is to copy the contents of
* javascripts into your application's * javascripts into your application's
* public/javascripts/ directory, and use @see javascriptIncludeTag() to * public/javascripts/ directory, and use @see javascriptIncludeTag() to
* create remote script links. * create remote script links.
* @return string script with all javascript in /javascripts folder * @return string script with all javascript in/javascripts folder
*/ */
function includeScript ($script = "") function includeScript ($script = "")
{ {
if($script == "") if($script == "")
@ -201,18 +201,18 @@ class JavascriptHelper extends Helper
} }
/** /**
* Generates a JavaScript object in JavaScript Object Notation (JSON) * Generates a JavaScript object in JavaScript Object Notation (JSON)
* from an array * from an array
* *
* @param array $data Data to be converted * @param array $data Data to be converted
* @param boolean $block Wraps return value in a <script /> block if true * @param boolean $block Wraps return value in a <script/> block if true
* @param string $prefix Prepends the string to the returned data * @param string $prefix Prepends the string to the returned data
* @param string $postfix Appends the string to the returned data * @param string $postfix Appends the string to the returned data
* @param array $stringKeys A list of array keys to be treated as a string * @param array $stringKeys A list of array keys to be treated as a string
* @param boolean $quoteKeys If false, treats $stringKey as a list of keys *not* to be quoted * @param boolean $quoteKeys If false, treats $stringKey as a list of keys *not* to be quoted
* @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(), $quoteKeys = true, $q = "'") function object ($data = array(), $block = false, $prefix = '', $postfix = '', $stringKeys = array(), $quoteKeys = true, $q = "'")
{ {
$out = array(); $out = array();

View file

@ -3,13 +3,13 @@
/** /**
* Number Helper. * Number Helper.
* *
* Methods to make numbers more readable. * Methods to make numbers more readable.
* *
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP : Rapid Development Framework <http://www.cakephp.org/> * CakePHP : Rapid Development Framework <http://www.cakephp.org/>
* Copyright (c) 2006, Cake Software Foundation, Inc. * Copyright (c) 2006, Cake Software Foundation, Inc.
* 1785 E. Sahara Avenue, Suite 490-204 * 1785 E. Sahara Avenue, Suite 490-204
* Las Vegas, Nevada 89104 * Las Vegas, Nevada 89104
* *
@ -41,25 +41,25 @@
*/ */
class NumberHelper extends Helper class NumberHelper extends Helper
{ {
/** /**
* Formats a number with a level of precision. * Formats a number with a level of precision.
* *
* @param float $number A floating point number. * @param float $number A floating point number.
* @param integer $precision The precision of the returned number. * @param integer $precision The precision of the returned number.
* @return float Enter description here... * @return float Enter description here...
* @static * @static
*/ */
function precision($number, $precision = 3) function precision($number, $precision = 3)
{ {
return sprintf("%01.{$precision}f", $number); return sprintf("%01.{$precision}f", $number);
} }
/** /**
* Returns a formatted-for-humans file size. * Returns a formatted-for-humans file size.
* *
* @param integer $length Size in bytes * @param integer $length Size in bytes
* @return string Human readable size * @return string Human readable size
* @static * @static
*/ */
function toReadableSize($size) function toReadableSize($size)
{ {
@ -74,13 +74,13 @@ class NumberHelper extends Helper
} }
} }
/** /**
* Formats a number into a percentage string. * Formats a number into a percentage string.
* *
* @param float $number A floating point number * @param float $number A floating point number
* @param integer $precision The precision of the returned number * @param integer $precision The precision of the returned number
* @return string Percentage string * @return string Percentage string
* @static * @static
*/ */
function toPercentage($number, $precision = 2) function toPercentage($number, $precision = 2)
{ {

View file

@ -53,7 +53,7 @@ if(!class_exists('Html'))
*/ */
class TextHelper extends Helper class TextHelper extends Helper
{ {
/** /**
* Highlights a given phrase in a text. * Highlights a given phrase in a text.
* *
* @param string $text Text to search the phrase in * @param string $text Text to search the phrase in
@ -86,7 +86,7 @@ class TextHelper extends Helper
} }
} }
/** /**
* Strips given text of all links (<a href=....) * Strips given text of all links (<a href=....)
* *
* @param string $text Text * @param string $text Text
@ -97,7 +97,7 @@ class TextHelper extends Helper
return preg_replace('|<a.*>(.*)<\/a>|im', '\1', $text); return preg_replace('|<a.*>(.*)<\/a>|im', '\1', $text);
} }
/** /**
* Adds links (<a href=....) to a given text, by finding text that begins with * Adds links (<a href=....) to a given text, by finding text that begins with
* strings like http:// and ftp://. * strings like http:// and ftp://.
* *
@ -132,7 +132,7 @@ class TextHelper extends Helper
); );
} }
/** /**
* Adds email links (<a href="mailto:....) to a given text. * Adds email links (<a href="mailto:....) to a given text.
* *
* @param string $text Text * @param string $text Text
@ -158,7 +158,7 @@ class TextHelper extends Helper
); );
} }
/** /**
* Convert all links and email adresses to HTML links. * Convert all links and email adresses to HTML links.
* *
* @param string $text Text * @param string $text Text
@ -170,13 +170,13 @@ class TextHelper extends Helper
return $this->autoLinkEmails($this->autoLinkUrls($text, $htmlOptions), $htmlOptions); return $this->autoLinkEmails($this->autoLinkUrls($text, $htmlOptions), $htmlOptions);
} }
/** /**
* Truncates text. * Truncates text.
* *
* Cuts a string to the length of $length and replaces the last characters * Cuts a string to the length of $length and replaces the last characters
* with the ending if the text is longer than length. * with the ending if the text is longer than length.
* *
* @param string $text String to truncate. * @param string $text String to truncate.
* @param integer $length Length of returned string, including ellipsis. * @param integer $length Length of returned string, including ellipsis.
* @param string $ending Ending to be appended to the trimmed string. * @param string $ending Ending to be appended to the trimmed string.
* @return string Trimmed string. * @return string Trimmed string.
@ -190,7 +190,7 @@ class TextHelper extends Helper
} }
/** /**
* Alias for truncate(). * Alias for truncate().
* *
* @see TextHelper::truncate() * @see TextHelper::truncate()
@ -201,7 +201,7 @@ class TextHelper extends Helper
return call_user_func_array(array(&$this, "truncate"), $args); return call_user_func_array(array(&$this, "truncate"), $args);
} }
/** /**
* Extracts an excerpt from the text surrounding the phrase with a number of characters on each side determined by radius. * Extracts an excerpt from the text surrounding the phrase with a number of characters on each side determined by radius.
* *
* @param string $text String to search the phrase in * @param string $text String to search the phrase in
@ -227,7 +227,7 @@ class TextHelper extends Helper
return $excerpt; return $excerpt;
} }
/** /**
* Text-to-html parser, similar to Textile or RedCloth, only with a little different syntax. * Text-to-html parser, similar to Textile or RedCloth, only with a little different syntax.
* *
* @param string $text String to "flay" * @param string $text String to "flay"

View file

@ -157,7 +157,7 @@ class TimeHelper extends Helper
$begin = $this->fromString($begin); $begin = $this->fromString($begin);
$end = $this->fromString($end); $end = $this->fromString($end);
$begin = date('Y-m-d', $begin).' 00:00:00'; $begin = date('Y-m-d', $begin).' 00:00:00';
$end = date('Y-m-d', $end). ' 23:59:59'; $end = date('Y-m-d', $end). ' 23:59:59';
$ret = "($field_name >= '$begin') AND ($field_name <= '$end')"; $ret = "($field_name >= '$begin') AND ($field_name <= '$end')";
@ -190,7 +190,7 @@ class TimeHelper extends Helper
* or output it. This overrides AUTO_OUTPUT. * or output it. This overrides AUTO_OUTPUT.
* @return boolean True if datetime string is within current year * @return boolean True if datetime string is within current year
*/ */
function isThisYear ($date_string, $return = false) function isThisYear ($date_string, $return = false)
{ {
$date = $this->fromString($date_string); $date = $this->fromString($date_string);
$ret = date('Y', $date) == date('Y', time()); $ret = date('Y', $date) == date('Y', time());
@ -206,7 +206,7 @@ class TimeHelper extends Helper
* or output it. This overrides AUTO_OUTPUT. * or output it. This overrides AUTO_OUTPUT.
* @return boolean True if datetime string was yesterday * @return boolean True if datetime string was yesterday
*/ */
function wasYesterday ($date_string, $return = false) function wasYesterday ($date_string, $return = false)
{ {
$date = $this->fromString($date_string); $date = $this->fromString($date_string);
$ret = date('Y-m-d', $date) == date('Y-m-d', strtotime('yesterday')); $ret = date('Y-m-d', $date) == date('Y-m-d', strtotime('yesterday'));
@ -222,7 +222,7 @@ class TimeHelper extends Helper
* or output it. This overrides AUTO_OUTPUT. * or output it. This overrides AUTO_OUTPUT.
* @return boolean True if datetime string was yesterday * @return boolean True if datetime string was yesterday
*/ */
function isTomorrow ($date_string, $return = false) function isTomorrow ($date_string, $return = false)
{ {
$date = $this->fromString($date_string); $date = $this->fromString($date_string);
$ret = date('Y-m-d', $date) == date('Y-m-d', strtotime('tomorrow')); $ret = date('Y-m-d', $date) == date('Y-m-d', strtotime('tomorrow'));
@ -253,7 +253,7 @@ class TimeHelper extends Helper
* or output it. This overrides AUTO_OUTPUT. * or output it. This overrides AUTO_OUTPUT.
* @return string Formatted date string * @return string Formatted date string
*/ */
function toAtom ($date_string, $return = false) function toAtom ($date_string, $return = false)
{ {
$date = $this->fromString($date_string); $date = $this->fromString($date_string);
$ret = date('Y-m-d\TH:i:s\Z', $date); $ret = date('Y-m-d\TH:i:s\Z', $date);
@ -325,7 +325,7 @@ class TimeHelper extends Helper
if ($months > 0) if ($months > 0)
{ {
// over a month old, just show date (mm/dd/yyyy format) // over a month old, just show date (mm/dd/yyyy format)
$relative_date = 'on '. date($format, $in_seconds); $relative_date = 'on '. date($format, $in_seconds);
$old = true; $old = true;
} }
@ -335,36 +335,36 @@ class TimeHelper extends Helper
$old = false; $old = false;
if ($weeks > 0) if ($weeks > 0)
{ {
// weeks and days // weeks and days
$relative_date .= ( $relative_date ? ', ' : '' ).$weeks.' week'.( $weeks > 1 ?'s' : '' ); $relative_date .= ( $relative_date ? ', ' : '' ).$weeks.' week'.( $weeks > 1 ?'s' : '' );
$relative_date .= $days > 0 ? ($relative_date?', ':'').$days.' day'.( $days > 1 ? 's' : '' ):''; $relative_date .= $days > 0 ? ($relative_date?', ':'').$days.' day'.( $days > 1 ? 's' : '' ):'';
} }
elseif ($days > 0) elseif ($days > 0)
{ {
// days and hours // days and hours
$relative_date .= ($relative_date ? ', ':'').$days.' day'.($days > 1 ? 's' : ''); $relative_date .= ($relative_date ? ', ':'').$days.' day'.($days > 1 ? 's' : '');
$relative_date .= $hours > 0 ? ($relative_date ? ', ' : '').$hours.' hour'.($hours > 1 ? 's' : '') : ''; $relative_date .= $hours > 0 ? ($relative_date ? ', ' : '').$hours.' hour'.($hours > 1 ? 's' : '') : '';
} }
elseif ($hours > 0) elseif ($hours > 0)
{ {
// hours and minutes // hours and minutes
$relative_date .= ($relative_date ? ', ' : '').$hours.' hour'.($hours > 1 ? 's' : ''); $relative_date .= ($relative_date ? ', ' : '').$hours.' hour'.($hours > 1 ? 's' : '');
$relative_date .= $minutes > 0 ? ($relative_date ? ', ' : '').$minutes.' minute'.($minutes > 1 ? 's' : '') : ''; $relative_date .= $minutes > 0 ? ($relative_date ? ', ' : '').$minutes.' minute'.($minutes > 1 ? 's' : '') : '';
} }
elseif ($minutes > 0) elseif ($minutes > 0)
{ {
// minutes only // minutes only
$relative_date .= ($relative_date ? ', ' : '').$minutes.' minute'.($minutes > 1 ? 's' : ''); $relative_date .= ($relative_date ? ', ' : '').$minutes.' minute'.($minutes > 1 ? 's' : '');
} }
else else
{ {
// seconds only // seconds only
$relative_date .= ($relative_date ? ', ' : '').$seconds.' second'.($seconds > 1 ? 's' : ''); $relative_date .= ($relative_date ? ', ' : '').$seconds.' second'.($seconds > 1 ? 's' : '');
} }
} }
$ret = $relative_date; $ret = $relative_date;
// show relative date and add proper verbiage // show relative date and add proper verbiage
if(!$backwards && !$old) if(!$backwards && !$old)
{ {
$ret .= ' ago'; $ret .= ' ago';
@ -402,14 +402,14 @@ class TimeHelper extends Helper
* Returns true if specified datetime was within the interval specified, else false. * Returns true if specified datetime was within the interval specified, else false.
* *
* @param mixed $timeInterval the numeric value with space then time * @param mixed $timeInterval the numeric value with space then time
* type. Example of valid types: 6 hours, 2 days, 1 minute. * type. Example of valid types: 6 hours, 2 days, 1 minute.
* @param mixed $date_string the datestring or unix timestamp to compare * @param mixed $date_string the datestring or unix timestamp to compare
* @param boolean $return Whether this method should return a value * @param boolean $return Whether this method should return a value
* or output it. This overrides AUTO_OUTPUT. * or output it. This overrides AUTO_OUTPUT.
* @return boolean * @return boolean
*/ */
function wasWithinLast($timeInterval, $date_string, $return = false) function wasWithinLast($timeInterval, $date_string, $return = false)
{ {
$date = $this->fromString($date_string); $date = $this->fromString($date_string);
$result = preg_split('/\\s/', $timeInterval); $result = preg_split('/\\s/', $timeInterval);
@ -483,7 +483,7 @@ class TimeHelper extends Helper
$ret = false; $ret = false;
} }
return $this->output($ret, $return); return $this->output($ret, $return);
} }
} }
?> ?>

View file

@ -57,8 +57,8 @@
<?php echo $html->image('cake.power.png', array('alt'=>'CakePHP : Rapid Development Framework', <?php echo $html->image('cake.power.png', array('alt'=>'CakePHP : Rapid Development Framework',
'height' => "15", 'height' => "15",
'width' => "80"))?> 'width' => "80"))?>
</a> </a>
</p> </p>
<p> <p>
<a href="http://validator.w3.org/check?uri=referer"> <a href="http://validator.w3.org/check?uri=referer">
<?php echo $html->image('w3c_xhtml10.png', array('alt' => 'Valid XHTML 1.0 Transitional', <?php echo $html->image('w3c_xhtml10.png', array('alt' => 'Valid XHTML 1.0 Transitional',

View file

@ -3,20 +3,20 @@
/** /**
* *
* *
* *
* *
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
* CakePHP : Rapid Development Framework <http://www.cakephp.org/> * CakePHP : Rapid Development Framework <http://www.cakephp.org/>
* Copyright (c) 2006, Cake Software Foundation, Inc. * Copyright (c) 2006, Cake Software Foundation, Inc.
* 1785 E. Sahara Avenue, Suite 490-204 * 1785 E. Sahara Avenue, Suite 490-204
* Las Vegas, Nevada 89104 * Las Vegas, Nevada 89104
* *
* Licensed under The MIT License * Licensed under The MIT License
* Redistributions of files must retain the above copyright notice. * Redistributions of files must retain the above copyright notice.
* *
* @filesource * @filesource
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc. * @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
* @package cake * @package cake
@ -28,13 +28,13 @@
* @license http://www.opensource.org/licenses/mit-license.php The MIT License * @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/ */
?> ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="pl" xml:lang="pl"> <html xmlns="http://www.w3.org/1999/xhtml">
<head> <head>
<title><?php echo $page_title?></title> <title><?php echo $page_title?></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<?php if(DEBUG == 0) { ?> <?php if(DEBUG == 0) { ?>
<meta http-equiv="Refresh" content="<?php echo $pause?>;url=<?php echo $url?>" /> <meta http-equiv="Refresh" content="<?php echo $pause?>;url=<?php echo $url?>"/>
<?php } ?> <?php } ?>
<style><!-- <style><!--
P { text-align:center; font:bold 1.1em sans-serif } P { text-align:center; font:bold 1.1em sans-serif }

View file

@ -58,7 +58,7 @@ foreach($fieldNames as $field => $value)
if(!empty($data[$objModel->tableToModel[$objModel->table]][$field]) && (isset($displayText))) if(!empty($data[$objModel->tableToModel[$objModel->table]][$field]) && (isset($displayText)))
{ {
echo "<dd>".$html->link($displayText, '/'.Inflector::underscore($value['controller']).'/show/' echo "<dd>".$html->link($displayText, '/'.Inflector::underscore($value['controller']).'/show/'
.$data[$objModel->tableToModel[$objModel->table]][$field] )."</dd>"; .$data[$objModel->tableToModel[$objModel->table]][$field] )."</dd>";
} }
else else
{ {
@ -181,7 +181,7 @@ foreach($relations as $association => $relation)
"/edit/{$row[$this->controller->{$modelName}->{$association}->primaryKey]}/")?> "/edit/{$row[$this->controller->{$modelName}->{$association}->primaryKey]}/")?>
<?php echo $html->link('Delete',"/".Inflector::underscore($controller). <?php echo $html->link('Delete',"/".Inflector::underscore($controller).
"/destroy/{$row[$this->controller->{$modelName}->{$association}->primaryKey]}/")?> "/destroy/{$row[$this->controller->{$modelName}->{$association}->primaryKey]}/")?>
</td> </td>
<?php <?php
} }
else else

View file

@ -28,8 +28,8 @@
*/ */
/** /**
* Included libraries. * Included libraries.
*/ */
uses(DS.'view'.DS.'helper'); uses(DS.'view'.DS.'helper');
/** /**
@ -49,14 +49,14 @@ class View extends Object
* @var string Name of controller * @var string Name of controller
* @access public * @access public
*/ */
var $name = null; var $name = null;
/** /**
* Stores the current URL (for links etc.) * Stores the current URL (for links etc.)
* *
* @var string Current URL * @var string Current URL
*/ */
var $here = null; var $here = null;
/** /**
* Not used. 2006-09 * Not used. 2006-09
@ -64,7 +64,7 @@ class View extends Object
* @var unknown_type * @var unknown_type
* @access public * @access public
*/ */
var $parent = null; var $parent = null;
/** /**
* Action to be performed. * Action to be performed.
@ -72,7 +72,7 @@ class View extends Object
* @var string Name of action * @var string Name of action
* @access public * @access public
*/ */
var $action = null; var $action = null;
/** /**
* An array of names of models the particular controller wants to use. * An array of names of models the particular controller wants to use.
@ -80,7 +80,7 @@ class View extends Object
* @var mixed A single name as a string or a list of names as an array. * @var mixed A single name as a string or a list of names as an array.
* @access protected * @access protected
*/ */
var $uses = false; var $uses = false;
/** /**
* An array of names of built-in helpers to include. * An array of names of built-in helpers to include.
@ -88,14 +88,14 @@ class View extends Object
* @var mixed A single name as a string or a list of names as an array. * @var mixed A single name as a string or a list of names as an array.
* @access protected * @access protected
*/ */
var $helpers = array('Html'); var $helpers = array('Html');
/** /**
* Path to View. * Path to View.
* *
* @var string Path to View * @var string Path to View
*/ */
var $viewPath; var $viewPath;
/** /**
* Variables for the view * Variables for the view
@ -103,7 +103,7 @@ class View extends Object
* @var array * @var array
* @access private * @access private
*/ */
var $_viewVars = array(); var $_viewVars = array();
/** /**
* Title HTML element of this View. * Title HTML element of this View.
@ -111,7 +111,7 @@ class View extends Object
* @var boolean * @var boolean
* @access private * @access private
*/ */
var $pageTitle = false; var $pageTitle = false;
/** /**
* An array of model objects. * An array of model objects.
@ -119,7 +119,7 @@ class View extends Object
* @var array Array of model objects. * @var array Array of model objects.
* @access public * @access public
*/ */
var $models = array(); var $models = array();
/** /**
* Path parts for creating links in views. * Path parts for creating links in views.
@ -127,7 +127,7 @@ class View extends Object
* @var string Base URL * @var string Base URL
* @access public * @access public
*/ */
var $base = null; var $base = null;
/** /**
* Name of layout to use with this View. * Name of layout to use with this View.
@ -135,7 +135,7 @@ class View extends Object
* @var string * @var string
* @access public * @access public
*/ */
var $layout = 'default'; var $layout = 'default';
/** /**
* Turns on or off Cake's conventional mode of rendering views. On by default. * Turns on or off Cake's conventional mode of rendering views. On by default.
@ -143,7 +143,7 @@ class View extends Object
* @var boolean * @var boolean
* @access public * @access public
*/ */
var $autoRender = true; var $autoRender = true;
/** /**
* Turns on or off Cake's conventional mode of finding layout files. On by default. * Turns on or off Cake's conventional mode of finding layout files. On by default.
@ -151,27 +151,27 @@ class View extends Object
* @var boolean * @var boolean
* @access public * @access public
*/ */
var $autoLayout = true; var $autoLayout = true;
/** /**
* Array of parameter data * Array of parameter data
* *
* @var array Parameter data * @var array Parameter data
*/ */
var $params; var $params;
/** /**
* True when the view has been rendered. * True when the view has been rendered.
* *
* @var boolean * @var boolean
*/ */
var $hasRendered = null; var $hasRendered = null;
/** /**
* Reference to the Controller for this view. * Reference to the Controller for this view.
* *
* @var Controller * @var Controller
*/ */
var $controller = null; var $controller = null;
/** /**
* Array of loaded view helpers. * Array of loaded view helpers.
@ -214,8 +214,8 @@ class View extends Object
* *
* @return View * @return View
*/ */
function __construct (&$controller) function __construct (&$controller)
{ {
$this->controller =& $controller; $this->controller =& $controller;
$this->_viewVars =& $this->controller->_viewVars; $this->_viewVars =& $this->controller->_viewVars;
$this->action =& $this->controller->action; $this->action =& $this->controller->action;
@ -237,7 +237,7 @@ class View extends Object
$this->webservices =& $this->controller->webservices; $this->webservices =& $this->controller->webservices;
$this->plugin =& $this->controller->plugin; $this->plugin =& $this->controller->plugin;
parent::__construct(); parent::__construct();
} }
/** /**
* Renders view for given action and layout. If $file is given, that is used * Renders view for given action and layout. If $file is given, that is used
@ -247,9 +247,9 @@ class View extends Object
* @param string $layout Layout to use * @param string $layout Layout to use
* @param string $file Custom filename for view * @param string $file Custom filename for view
*/ */
function render($action=null, $layout=null, $file=null) function render($action=null, $layout=null, $file=null)
{ {
if (isset($this->hasRendered) && $this->hasRendered) if (isset($this->hasRendered) && $this->hasRendered)
{ {
return true; return true;
} }
@ -288,7 +288,7 @@ class View extends Object
return array('action' => $action, 'layout' => $layout, 'viewFn' => $viewFileName); return array('action' => $action, 'layout' => $layout, 'viewFn' => $viewFileName);
} }
// check to see if the missing view is due to a custom missingAction // check to see if the missing view is due to a custom missingAction
if (strpos($action, 'missingAction') !== false) if (strpos($action, 'missingAction') !== false)
{ {
$errorAction = 'missingAction'; $errorAction = 'missingAction';
@ -298,7 +298,7 @@ class View extends Object
$errorAction = 'missingView'; $errorAction = 'missingView';
} }
// check for controller-level view handler // check for controller-level view handler
foreach(array($this->name, 'errors') as $viewDir) foreach(array($this->name, 'errors') as $viewDir)
{ {
$errorAction =Inflector::underscore($errorAction); $errorAction =Inflector::underscore($errorAction);
@ -318,7 +318,7 @@ class View extends Object
$missingViewExists = is_file($missingViewFileName); $missingViewExists = is_file($missingViewFileName);
if ($missingViewExists) if ($missingViewExists)
{ {
break; break;
} }
} }
@ -332,7 +332,7 @@ class View extends Object
$isFatal = isset($this->isFatal) ? $this->isFatal : false; $isFatal = isset($this->isFatal) ? $this->isFatal : false;
if (!$isFatal) if (!$isFatal)
{ {
$viewFileName = $missingViewFileName; $viewFileName = $missingViewFileName;
} }
} }
else else
@ -342,14 +342,14 @@ class View extends Object
if (!$missingViewExists || $isFatal) if (!$missingViewExists || $isFatal)
{ {
// app/view/errors/missing_view.thtml view is missing! // app/view/errors/missing_view.thtml view is missing!
if (DEBUG) if (DEBUG)
{ {
trigger_error(sprintf(__("No template file for view %s (expected %s), create it first'"), $action, $viewFileName), E_USER_ERROR); trigger_error(sprintf(__("No template file for view %s (expected %s), create it first'"), $action, $viewFileName), E_USER_ERROR);
} }
else else
{ {
$this->error('404', 'Not found', sprintf("The requested address %s was not found on this server.", '', "missing view \"{$action}\"")); $this->error('404', 'Not found', sprintf("The requested address %s was not found on this server.", '', "missing view \"{$action}\""));
} }
die(); die();
@ -370,7 +370,7 @@ class View extends Object
{ {
if ($this->layout && $this->autoLayout) if ($this->layout && $this->autoLayout)
{ {
$out = $this->renderLayout($out); $out = $this->renderLayout($out);
} }
print $out; print $out;
@ -384,7 +384,7 @@ class View extends Object
return true; return true;
} }
} }
/** /**
* Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string. * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
@ -394,12 +394,12 @@ class View extends Object
* Element. * Element.
* *
* @link http://wiki.cakephp.org/docs:view:renderelement * @link http://wiki.cakephp.org/docs:view:renderelement
* @param string $name Name of template file in the /app/views/elements/ folder * @param string $name Name of template file in the/app/views/elements/ folder
* @param array $params Array of data to be made available to the for rendered view (i.e. the Element) * @param array $params Array of data to be made available to the for rendered view (i.e. the Element)
* @return string Rendered output * @return string Rendered output
*/ */
function renderElement($name, $params=array()) function renderElement($name, $params=array())
{ {
$fn = ELEMENTS.$name.$this->ext; $fn = ELEMENTS.$name.$this->ext;
if(!is_null($this->plugin)) if(!is_null($this->plugin))
@ -419,7 +419,7 @@ class View extends Object
$params = array_merge_recursive($params, $this->loaded); $params = array_merge_recursive($params, $this->loaded);
return $this->_render($fn, array_merge($this->_viewVars, $params), true, false); return $this->_render($fn, array_merge($this->_viewVars, $params), true, false);
} }
/** /**
* Renders a layout. Returns output from _render(). Returns false on error. * Renders a layout. Returns output from _render(). Returns false on error.
@ -427,8 +427,8 @@ class View extends Object
* @param string $content_for_layout Content to render in a view, wrapped by the surrounding layout. * @param string $content_for_layout Content to render in a view, wrapped by the surrounding layout.
* @return mixed Rendered output, or false on error * @return mixed Rendered output, or false on error
*/ */
function renderLayout($content_for_layout) function renderLayout($content_for_layout)
{ {
$layout_fn = $this->_getLayoutFileName(); $layout_fn = $this->_getLayoutFileName();
if(DEBUG > 2) if(DEBUG > 2)
@ -474,17 +474,17 @@ class View extends Object
array(array('layout' => $this->layout, array(array('layout' => $this->layout,
'file' => $layout_fn))); 'file' => $layout_fn)));
} }
} }
/** /**
* Sets layout to be used when rendering. * Sets layout to be used when rendering.
* *
* @param string $layout Name of layout. * @param string $layout Name of layout.
*/ */
function setLayout($layout) function setLayout($layout)
{ {
$this->layout = $layout; $this->layout = $layout;
} }
/** /**
* Displays an error page to the user. Uses layouts/error.html to render the page. * Displays an error page to the user. Uses layouts/error.html to render the page.
@ -493,16 +493,16 @@ class View extends Object
* @param string $name Name of the error (for instance: Not Found) * @param string $name Name of the error (for instance: Not Found)
* @param string $message Error message as a web page * @param string $message Error message as a web page
*/ */
function error ($code, $name, $message) function error ($code, $name, $message)
{ {
header ("HTTP/1.0 {$code} {$name}"); header ("HTTP/1.0 {$code} {$name}");
print ($this->_render(VIEWS.'layouts/error.thtml', array('code'=>$code,'name'=>$name,'message'=>$message))); print ($this->_render(VIEWS.'layouts/error.thtml', array('code'=>$code,'name'=>$name,'message'=>$message)));
} }
/************************************************************************** /**************************************************************************
* Private methods. * Private methods.
*************************************************************************/ *************************************************************************/
/** /**
@ -512,44 +512,44 @@ class View extends Object
* @return string Template filename * @return string Template filename
* @access private * @access private
*/ */
function _getViewFileName($action) function _getViewFileName($action)
{ {
$action = Inflector::underscore($action); $action = Inflector::underscore($action);
if(!is_null($this->webservices)) if(!is_null($this->webservices))
{ {
$type = strtolower($this->webservices).DS; $type = strtolower($this->webservices).DS;
} }
else else
{ {
$type = null; $type = null;
} }
$viewFileName = VIEWS.$this->viewPath.DS.$this->subDir.$type.$action.$this->ext; $viewFileName = VIEWS.$this->viewPath.DS.$this->subDir.$type.$action.$this->ext;
if(file_exists(VIEWS.$this->viewPath.DS.$this->subDir.$type.$action.$this->ext)) if(file_exists(VIEWS.$this->viewPath.DS.$this->subDir.$type.$action.$this->ext))
{ {
$viewFileName = VIEWS.$this->viewPath.DS.$this->subDir.$type.$action.$this->ext; $viewFileName = VIEWS.$this->viewPath.DS.$this->subDir.$type.$action.$this->ext;
} }
elseif(file_exists(VIEWS.'errors'.DS.$this->subDir.$type.$action.$this->ext)) elseif(file_exists(VIEWS.'errors'.DS.$this->subDir.$type.$action.$this->ext))
{ {
$viewFileName = VIEWS.'errors'.DS.$this->subDir.$type.$action.$this->ext; $viewFileName = VIEWS.'errors'.DS.$this->subDir.$type.$action.$this->ext;
} }
elseif($viewFileName = fileExistsInPath(LIBS.'view'.DS.'templates'.DS.'errors'.DS.$type.$action.'.thtml')) elseif($viewFileName = fileExistsInPath(LIBS.'view'.DS.'templates'.DS.'errors'.DS.$type.$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'))
{ {
} }
$viewPath = explode(DS, $viewFileName); $viewPath = explode(DS, $viewFileName);
$i = array_search('..', $viewPath); $i = array_search('..', $viewPath);
unset($viewPath[$i-1]); unset($viewPath[$i-1]);
unset($viewPath[$i]); unset($viewPath[$i]);
$return = '/'.implode('/', $viewPath); $return = '/'.implode('/', $viewPath);
return $return; return $return;
} }
/** /**
* Returns layout filename for this template as a string. * Returns layout filename for this template as a string.
@ -561,7 +561,7 @@ class View extends Object
{ {
if(!is_null($this->webservices)) if(!is_null($this->webservices))
{ {
$type = strtolower($this->webservices).DS; $type = strtolower($this->webservices).DS;
} }
else else
{ {
@ -587,19 +587,19 @@ class View extends Object
{ {
} }
return $layoutFileName; return $layoutFileName;
} }
/** /**
* Renders and returns output for given view filename with its * Renders and returns output for given view filename with its
* array of data. * array of data.
* *
* @param string $___viewFn Filename of the view * @param string $___viewFn Filename of the view
* @param array $___data_for_view Data to include in rendered view * @param array $___dataForView Data to include in rendered view
* @param boolean $___play_safe If set to false, the include() of the $__viewFn is done without suppressing output of errors * @param boolean $___playSafe If set to false, the include() of the $__viewFn is done without suppressing output of errors
* @return string Rendered output * @return string Rendered output
* @access private * @access private
*/ */
function _render($___viewFn, $___data_for_view, $___play_safe = true, $loadHelpers = true) function _render($___viewFn, $___dataForView, $___playSafe = true, $loadHelpers = true)
{ {
if ($this->helpers != false && $loadHelpers === true) if ($this->helpers != false && $loadHelpers === true)
{ {
@ -624,35 +624,35 @@ class View extends Object
} }
} }
extract($___data_for_view, EXTR_SKIP); # load all view variables extract($___dataForView, EXTR_SKIP); # load all view variables
/** /**
* Local template variables. * Local template variables.
*/ */
$BASE = $this->base; $BASE = $this->base;
$params = &$this->params; $params = &$this->params;
$page_title = $this->pageTitle; $page_title = $this->pageTitle;
/** /**
* Start caching output (eval outputs directly so we need to cache). * Start caching output (eval outputs directly so we need to cache).
*/ */
ob_start(); ob_start();
/** /**
* Include the template. * Include the template.
*/ */
$___play_safe? @include($___viewFn): include($___viewFn); $___playSafe? @include($___viewFn): include($___viewFn);
$out = ob_get_clean(); $out = ob_get_clean();
return $out; return $out;
} }
/** /**
* Loads helpers, with their dependencies. * Loads helpers, with their dependencies.
* *
* @param array $loaded List of helpers that are already loaded. * @param array $loaded List of helpers that are already loaded.
* @param array $helpers List of helpers to load. * @param array $helpers List of helpers to load.
* @return array * @return array
*/ */
function &_loadHelpers(&$loaded, $helpers) function &_loadHelpers(&$loaded, $helpers)
{ {
@ -702,12 +702,12 @@ class View extends Object
if(class_exists($helperCn)) if(class_exists($helperCn))
{ {
${$camelBackedHelper} =& new $helperCn; ${$camelBackedHelper} =& new $helperCn;
${$camelBackedHelper}->base = $this->base; ${$camelBackedHelper}->base = $this->base;
${$camelBackedHelper}->webroot = $this->webroot; ${$camelBackedHelper}->webroot = $this->webroot;
${$camelBackedHelper}->here = $this->here; ${$camelBackedHelper}->here = $this->here;
${$camelBackedHelper}->params = $this->params; ${$camelBackedHelper}->params = $this->params;
${$camelBackedHelper}->action = $this->action; ${$camelBackedHelper}->action = $this->action;
${$camelBackedHelper}->data = $this->data; ${$camelBackedHelper}->data = $this->data;
${$camelBackedHelper}->themeWeb = $this->themeWeb; ${$camelBackedHelper}->themeWeb = $this->themeWeb;
${$camelBackedHelper}->tags = $tags; ${$camelBackedHelper}->tags = $tags;

View file

@ -80,65 +80,65 @@ $aclCLI = new AclCLI ($command, $args);
class AclCLI { class AclCLI {
/** /**
* Enter description here... * Enter description here...
* *
* @var unknown_type * @var unknown_type
*/ */
var $stdin; var $stdin;
/** /**
* Enter description here... * Enter description here...
* *
* @var unknown_type * @var unknown_type
*/ */
var $stdout; var $stdout;
/** /**
* Enter description here... * Enter description here...
* *
* @var unknown_type * @var unknown_type
*/ */
var $stderr; var $stderr;
/** /**
* Enter description here... * Enter description here...
* *
* @var unknown_type * @var unknown_type
*/ */
var $acl; var $acl;
/** /**
* Enter description here... * Enter description here...
* *
* @var unknown_type * @var unknown_type
*/ */
var $args; var $args;
/** /**
* Enter description here... * Enter description here...
* *
* @var unknown_type * @var unknown_type
*/ */
var $dataSource = 'default'; var $dataSource = 'default';
/** /**
* Enter description here... * Enter description here...
* *
* @param unknown_type $command * @param unknown_type $command
* @param unknown_type $args * @param unknown_type $args
* @return AclCLI * @return AclCLI
*/ */
function AclCLI($command, $args) function AclCLI($command, $args)
{ {
$this->__construct($command, $args); $this->__construct($command, $args);
} }
/** /**
* Enter description here... * Enter description here...
* *
* @param unknown_type $command * @param unknown_type $command
* @param unknown_type $args * @param unknown_type $args
*/ */
function __construct ($command, $args) function __construct ($command, $args)
{ {
$acl = new AclComponent(); $acl = new AclComponent();
$this->acl = $acl->getACL(); $this->acl = $acl->getACL();
@ -149,7 +149,7 @@ class AclCLI {
$this->stdout = fopen('php://stdout', 'w'); $this->stdout = fopen('php://stdout', 'w');
$this->stderr = fopen('php://stderr', 'w'); $this->stderr = fopen('php://stderr', 'w');
//Check to see if DB ACL is enabled //Check to see if DB ACL is enabled
if (ACL_CLASSNAME != 'DB_ACL') if (ACL_CLASSNAME != 'DB_ACL')
{ {
$out = "--------------------------------------------------\n"; $out = "--------------------------------------------------\n";
@ -201,14 +201,14 @@ class AclCLI {
fwrite($this->stderr, "Unknown ACL command '$command'.\nFor usage, try 'php acl.php help'.\n\n"); fwrite($this->stderr, "Unknown ACL command '$command'.\nFor usage, try 'php acl.php help'.\n\n");
} }
} }
/** /**
* Enter description here... * Enter description here...
* *
*/ */
function create() function create()
{ {
$this->checkArgNumber(4, 'create'); $this->checkArgNumber(4, 'create');
$this->checkNodeType(); $this->checkNodeType();
extract($this->__dataVars()); extract($this->__dataVars());
@ -222,30 +222,30 @@ class AclCLI {
} }
fwrite($this->stdout, "New $class '".$this->args[3]."' created.\n\n"); fwrite($this->stdout, "New $class '".$this->args[3]."' created.\n\n");
} }
/** /**
* Enter description here... * Enter description here...
* *
*/ */
function delete() function delete()
{ {
$this->checkArgNumber(2, 'delete'); $this->checkArgNumber(2, 'delete');
$this->checkNodeType(); $this->checkNodeType();
extract($this->__dataVars()); extract($this->__dataVars());
$node = &new $class; $node = &new $class;
//What about children? //What about children?
//$node->del($this->args[1]); //$node->del($this->args[1]);
//fwrite($this->stdout, "$class deleted.\n\n"); //fwrite($this->stdout, "$class deleted.\n\n");
} }
/** /**
* Enter description here... * Enter description here...
* *
*/ */
function setParent() function setParent()
{ {
$this->checkArgNumber(3, 'setParent'); $this->checkArgNumber(3, 'setParent');
$this->checkNodeType(); $this->checkNodeType();
extract($this->__dataVars()); extract($this->__dataVars());
@ -259,14 +259,14 @@ class AclCLI {
{ {
fwrite($this->stdout, "Node parent set to ".$this->args[2]."\n\n"); fwrite($this->stdout, "Node parent set to ".$this->args[2]."\n\n");
} }
} }
/** /**
* Enter description here... * Enter description here...
* *
*/ */
function getPath() function getPath()
{ {
$this->checkArgNumber(2, 'getPath'); $this->checkArgNumber(2, 'getPath');
$this->checkNodeType(); $this->checkNodeType();
extract($this->__dataVars()); extract($this->__dataVars());
@ -286,47 +286,47 @@ class AclCLI {
{ {
fwrite($this->stdout, str_repeat(' ', $i) . "[" . $nodes[$i][$class]['id'] . "]" . $nodes[$i][$class]['alias'] . "\n"); fwrite($this->stdout, str_repeat(' ', $i) . "[" . $nodes[$i][$class]['id'] . "]" . $nodes[$i][$class]['alias'] . "\n");
} }
} }
/** /**
* Enter description here... * Enter description here...
* *
*/ */
function grant() function grant()
{ {
$this->checkArgNumber(3, 'grant'); $this->checkArgNumber(3, 'grant');
//add existence checks for nodes involved //add existence checks for nodes involved
$this->acl->allow(intval($this->args[0]), intval($this->args[1]), $this->args[2]); $this->acl->allow(intval($this->args[0]), intval($this->args[1]), $this->args[2]);
fwrite($this->stdout, "Permission granted.\n"); fwrite($this->stdout, "Permission granted.\n");
} }
/** /**
* Enter description here... * Enter description here...
* *
*/ */
function deny() function deny()
{ {
$this->checkArgNumber(3, 'deny'); $this->checkArgNumber(3, 'deny');
//add existence checks for nodes involved //add existence checks for nodes involved
$this->acl->deny(intval($this->args[0]), intval($this->args[1]), $this->args[2]); $this->acl->deny(intval($this->args[0]), intval($this->args[1]), $this->args[2]);
fwrite($this->stdout, "Requested permission successfully denied.\n"); fwrite($this->stdout, "Requested permission successfully denied.\n");
} }
/** /**
* Enter description here... * Enter description here...
* *
*/ */
function inherit() {} function inherit() {}
/** /**
* Enter description here... * Enter description here...
* *
*/ */
function view() function view()
{ {
$this->checkArgNumber(1, 'view'); $this->checkArgNumber(1, 'view');
$this->checkNodeType(); $this->checkNodeType();
extract($this->__dataVars()); extract($this->__dataVars());
@ -345,14 +345,14 @@ class AclCLI {
{ {
while ($right[count($right)-1] < $nodes[$i][$class]['rght']) while ($right[count($right)-1] < $nodes[$i][$class]['rght'])
{ {
if ($right[count($right)-1]) if ($right[count($right)-1])
{ {
array_pop($right); array_pop($right);
} }
else else
{ {
break; break;
} }
} }
} }
@ -362,59 +362,59 @@ class AclCLI {
} }
fwrite($this->stdout, "------------------------------------------------\n"); fwrite($this->stdout, "------------------------------------------------\n");
} }
/** /**
* Enter description here... * Enter description here...
* *
*/ */
function initdb() function initdb()
{ {
fwrite($this->stdout, "Initializing Database...\n"); fwrite($this->stdout, "Initializing Database...\n");
fwrite($this->stdout, "Creating access control objects table (acos)...\n"); fwrite($this->stdout, "Creating access control objects table (acos)...\n");
$sql = " CREATE TABLE `acos` ( $sql = " CREATE TABLE `acos` (
`id` int(11) NOT NULL auto_increment, `id` int(11) NOT NULL auto_increment,
`object_id` int(11) default NULL, `object_id` int(11) default NULL,
`alias` varchar(255) NOT NULL default '', `alias` varchar(255) NOT NULL default '',
`lft` int(11) default NULL, `lft` int(11) default NULL,
`rght` int(11) default NULL, `rght` int(11) default NULL,
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
);"; );";
$this->db->query($sql); $this->db->query($sql);
fwrite($this->stdout, "Creating access request objects table (acos)...\n"); fwrite($this->stdout, "Creating access request objects table (acos)...\n");
$sql2 = "CREATE TABLE `aros` ( $sql2 = "CREATE TABLE `aros` (
`id` int(11) NOT NULL auto_increment, `id` int(11) NOT NULL auto_increment,
`user_id` int(11) default NULL, `user_id` int(11) default NULL,
`alias` varchar(255) NOT NULL default '', `alias` varchar(255) NOT NULL default '',
`lft` int(11) default NULL, `lft` int(11) default NULL,
`rght` int(11) default NULL, `rght` int(11) default NULL,
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
);"; );";
$this->db->query($sql2); $this->db->query($sql2);
fwrite($this->stdout, "Creating relationships table (aros_acos)...\n"); fwrite($this->stdout, "Creating relationships table (aros_acos)...\n");
$sql3 = "CREATE TABLE `aros_acos` ( $sql3 = "CREATE TABLE `aros_acos` (
`id` int(11) NOT NULL auto_increment, `id` int(11) NOT NULL auto_increment,
`aro_id` int(11) default NULL, `aro_id` int(11) default NULL,
`aco_id` int(11) default NULL, `aco_id` int(11) default NULL,
`_create` int(1) NOT NULL default '0', `_create` int(1) NOT NULL default '0',
`_read` int(1) NOT NULL default '0', `_read` int(1) NOT NULL default '0',
`_update` int(1) NOT NULL default '0', `_update` int(1) NOT NULL default '0',
`_delete` int(11) NOT NULL default '0', `_delete` int(11) NOT NULL default '0',
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
);"; );";
$this->db->query($sql3); $this->db->query($sql3);
fwrite($this->stdout, "\nDone.\n"); fwrite($this->stdout, "\nDone.\n");
} }
/** /**
* Enter description here... * Enter description here...
* *
*/ */
function help() function help()
{ {
$out = "Usage: php acl.php <command> <arg1> <arg2>...\n"; $out = "Usage: php acl.php <command> <arg1> <arg2>...\n";
$out .= "-----------------------------------------------\n"; $out .= "-----------------------------------------------\n";
$out .= "Commands:\n"; $out .= "Commands:\n";
@ -486,60 +486,60 @@ class AclCLI {
$out .= "\n"; $out .= "\n";
fwrite($this->stdout, $out); fwrite($this->stdout, $out);
} }
/** /**
* Enter description here... * Enter description here...
* *
* @param unknown_type $title * @param unknown_type $title
* @param unknown_type $msg * @param unknown_type $msg
*/ */
function displayError($title, $msg) function displayError($title, $msg)
{ {
$out = "\n"; $out = "\n";
$out .= "Error: $title\n"; $out .= "Error: $title\n";
$out .= "$msg\n"; $out .= "$msg\n";
$out .= "\n"; $out .= "\n";
fwrite($this->stdout, $out); fwrite($this->stdout, $out);
exit(); exit();
} }
/** /**
* Enter description here... * Enter description here...
* *
* @param unknown_type $expectedNum * @param unknown_type $expectedNum
* @param unknown_type $command * @param unknown_type $command
*/ */
function checkArgNumber($expectedNum, $command) function checkArgNumber($expectedNum, $command)
{ {
if (count($this->args) != $expectedNum) if (count($this->args) != $expectedNum)
{ {
$this->displayError('Wrong number of parameters: '.count($this->args), 'Please type \'php acl.php help\' for help on usage of the '.$command.' command.'); $this->displayError('Wrong number of parameters: '.count($this->args), 'Please type \'php acl.php help\' for help on usage of the '.$command.' command.');
} }
} }
/** /**
* Enter description here... * Enter description here...
* *
*/ */
function checkNodeType() function checkNodeType()
{ {
if ($this->args[0] != 'aco' && $this->args[0] != 'aro') if ($this->args[0] != 'aco' && $this->args[0] != 'aro')
{ {
$this->displayError("Missing/Unknown node type: '".$this->args[0]."'", 'Please specify which ACL object type you wish to create.'); $this->displayError("Missing/Unknown node type: '".$this->args[0]."'", 'Please specify which ACL object type you wish to create.');
} }
} }
/** /**
* Enter description here... * Enter description here...
* *
* @param unknown_type $type * @param unknown_type $type
* @param unknown_type $id * @param unknown_type $id
* @return unknown * @return unknown
*/ */
function nodeExists($type, $id) function nodeExists($type, $id)
{ {
//fwrite($this->stdout, "Check to see if $type with ID = $id exists...\n"); //fwrite($this->stdout, "Check to see if $type with ID = $id exists...\n");
extract($this->__dataVars($type)); extract($this->__dataVars($type));
$node = &new $class; $node = &new $class;
@ -553,16 +553,16 @@ class AclCLI {
{ {
return $possibility; return $possibility;
} }
} }
/** /**
* Enter description here... * Enter description here...
* *
* @param unknown_type $type * @param unknown_type $type
* @return unknown * @return unknown
*/ */
function __dataVars($type = null) function __dataVars($type = null)
{ {
if ($type == null) if ($type == null)
{ {
$type = $this->args[0]; $type = $this->args[0];
@ -572,9 +572,9 @@ class AclCLI {
$class = ucwords($type); $class = ucwords($type);
$vars['secondary_id'] = ($class == 'aro' ? 'user_id' : 'object_id'); $vars['secondary_id'] = ($class == 'aro' ? 'user_id' : 'object_id');
$vars['data_name'] = $type; $vars['data_name'] = $type;
$vars['table_name'] = $type . 's'; $vars['table_name'] = $type . 's';
$vars['class'] = $class; $vars['class'] = $class;
return $vars; return $vars;
} }
} }
?> ?>

View file

@ -30,8 +30,8 @@
*/ */
/** /**
* START-UP * START-UP
*/ */
define ('DS', DIRECTORY_SEPARATOR); define ('DS', DIRECTORY_SEPARATOR);
define ('ROOT', dirname(dirname(dirname(__FILE__))).DS); define ('ROOT', dirname(dirname(dirname(__FILE__))).DS);
define ('APP_DIR', 'app'); define ('APP_DIR', 'app');

View file

@ -6,7 +6,7 @@
* *
* This file collects requests if: * This file collects requests if:
* - no mod_rewrite is avilable or .htaccess files are not supported * - no mod_rewrite is avilable or .htaccess files are not supported
* - /public is not set as a web root. * -/public is not set as a web root.
* *
* PHP versions 4 and 5 * PHP versions 4 and 5
* *
@ -42,7 +42,7 @@ define ('ROOT', dirname(__FILE__).DS);
*/ */
if (!defined('CAKE_CORE_INCLUDE_PATH')) if (!defined('CAKE_CORE_INCLUDE_PATH'))
{ {
//define ('CAKE_CORE_INCLUDE_PATH', FULL PATH TO DIRECTORY WHERE CAKE CORE IS INSTALLED DO NOT ADD A TRAILING DIRECTORY SEPARATOR'; //define ('CAKE_CORE_INCLUDE_PATH', FULL PATH TO DIRECTORY WHERE CAKE CORE IS INSTALLED DO NOT ADD A TRAILING DIRECTORY SEPARATOR';
define('CAKE_CORE_INCLUDE_PATH', ROOT); define('CAKE_CORE_INCLUDE_PATH', ROOT);
} }