Merge branch '1.3' into jshelper-integration

Conflicts:
	cake/tests/cases/libs/view/helpers/js.test.php
This commit is contained in:
mark_story 2009-07-06 23:43:57 -04:00
commit 9c51f720ed
151 changed files with 13288 additions and 3793 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
app/config
app/tmp
vendors

View file

@ -1,44 +1,46 @@
<?php
/* SVN FILE: $Id$ */
/**
* Short description for file.
* This file is loaded automatically by the app/webroot/index.php file after the core bootstrap.php
*
* Long description for file
* This is an application wide file to load any function that is not used within a class
* define. You can also use this to include or require any files in your application.
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.app.config
* @since CakePHP(tm) v 0.10.8.2117
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
/**
*
* This file is loaded automatically by the app/webroot/index.php file after the core bootstrap.php is loaded
* This is an application wide file to load any function that is not used within a class define.
* You can also use this to include or require any files in your application.
*
*/
/**
* The settings below can be used to set additional paths to models, views and controllers.
* This is related to Ticket #470 (https://trac.cakephp.org/ticket/470)
*
* $modelPaths = array('full path to models', 'second full path to models', 'etc...');
* $viewPaths = array('this path to views', 'second full path to views', 'etc...');
* $controllerPaths = array('this path to controllers', 'second full path to controllers', 'etc...');
* $modelPaths = array('/full/path/to/models/', '/next/full/path/to/models/');
* $viewPaths = array('/full/path/to/views/', '/next/full/path/to/views/');
* $controllerPaths = array(/full/path/to/controllers/', '/next/full/path/to/controllers/');
* $pluginPaths = array('/full/path/to/plugins/', '/next/full/path/to/plugins/');
* $behaviorPaths = array('/full/path/to/behaviors/', '/next/full/path/to/behaviors/');
* $componentPaths = array('/full/path/to/components/', '/next/full/path/to/components/');
* $helperPaths = array('/full/path/to/helpers/', '/next/full/path/to/helpers/');
* $vendorPaths = array('/full/path/to/vendors/', '/next/full/path/to/vendors/');
* $shellPaths = array('/full/path/to/shells/', '/next/full/path/to/shells/');
* $localePaths = array('/full/path/to/locale/', '/next/full/path/to/locale/';
*
*/
//EOF
?>
/**
* As of 1.3, additional rules for the inflector are added below
*
* Inflector::rule('singular', array('rules' => array(), irregular' => array(), 'uninflected' => array()));
* Inflector::rule('plural', array('rules' => array(), 'irregular' => array(), 'uninflected' => array()));
*
*/
?>

View file

@ -96,16 +96,30 @@
* To define a custom session handler, save it at /app/config/<name>.php.
* Set the value of 'Session.save' to <name> to utilize it in CakePHP.
*
* To use database sessions, execute the SQL file found at /app/config/sql/sessions.sql.
* To use database sessions, run the app/config/schema/sessions.php schema using
* the cake shell command: cake schema run create Sessions
*
*/
Configure::write('Session.save', 'php');
/**
* The model name to be used for the session model.
*
* 'Session.save' must be set to 'database' in order to utilize this constant.
*
* The model name set here should *not* be used elsewhere in your application.
*/
//Configure::write('Session.model', 'Session');
/**
* The name of the table used to store CakePHP database sessions.
*
* 'Session.save' must be set to 'database' in order to utilize this constant.
*
* The table name set here should *not* include any table prefix defined elsewhere.
*
* Please note that if you set a value for Session.model (above), any value set for
* Session.table will be ignored.
*
* [Note: Session.table is deprecated as of CakePHP 1.3]
*/
//Configure::write('Session.table', 'cake_sessions');
/**

View file

@ -1,5 +1,4 @@
<?php
/* SVN FILE: $Id$ */
/**
* This is core configuration file.
*
@ -7,22 +6,18 @@
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.app.config
* @since CakePHP(tm) v 0.2.9
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* In this file you set up your database connection details.

View file

@ -1,70 +0,0 @@
<?php
/* SVN FILE: $Id$ */
/**
* Custom Inflected Words.
*
* This file is used to hold words that are not matched in the normail Inflector::pluralize() and
* Inflector::singularize()
*
* PHP versions 4 and %
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @package cake
* @subpackage cake.app.config
* @since CakePHP(tm) v 1.0.0.2312
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
/**
* This is a key => value array of regex used to match words.
* If key matches then the value is returned.
*
* $pluralRules = array('/(s)tatus$/i' => '\1\2tatuses', '/^(ox)$/i' => '\1\2en', '/([m|l])ouse$/i' => '\1ice');
*/
$pluralRules = array();
/**
* This is a key only array of plural words that should not be inflected.
* Notice the last comma
*
* $uninflectedPlural = array('.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox');
*/
$uninflectedPlural = array();
/**
* This is a key => value array of plural irregular words.
* If key matches then the value is returned.
*
* $irregularPlural = array('atlas' => 'atlases', 'beef' => 'beefs', 'brother' => 'brothers')
*/
$irregularPlural = array();
/**
* This is a key => value array of regex used to match words.
* If key matches then the value is returned.
*
* $singularRules = array('/(s)tatuses$/i' => '\1\2tatus', '/(matr)ices$/i' =>'\1ix','/(vert|ind)ices$/i')
*/
$singularRules = array();
/**
* This is a key only array of singular words that should not be inflected.
* You should not have to change this value below if you do change it use same format
* as the $uninflectedPlural above.
*/
$uninflectedSingular = $uninflectedPlural;
/**
* This is a key => value array of singular irregular words.
* Most of the time this will be a reverse of the above $irregularPlural array
* You should not have to change this value below if you do change it use same format
*
* $irregularSingular = array('atlases' => 'atlas', 'beefs' => 'beef', 'brothers' => 'brother')
*/
$irregularSingular = array_flip($irregularPlural);
?>

View file

@ -1,27 +1,22 @@
<?php
/* SVN FILE: $Id$ */
/**
* Short description for file.
* Index
*
* Long description for file
* The Front Controller for handling every request
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.app.webroot
* @since CakePHP(tm) v 0.2.9
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
/**
@ -85,7 +80,7 @@
return;
} else {
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch($url);
$Dispatcher->dispatch();
}
if (Configure::read() > 0) {
echo "<!-- " . round(getMicrotime() - $TIME_START, 4) . "s -->";

View file

@ -1,9 +1,21 @@
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// +---------------------------------------------------------------------------------------------------+ //
// + $Id$
// + Last Modified: $Date$
// + Modified By: $LastChangedBy$
// +---------------------------------------------------------------------------------------------------+ //
///////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
// +--------------------------------------------------------------------------------------------+ // // CakePHP Version
//
// Holds a static string representing the current version of CakePHP
//
// CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
// Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
//
// Licensed under The MIT License
// Redistributions of files must retain the above copyright notice.
//
// @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
// @link http://cakephp.org
// @package cake
// @subpackage cake.cake.libs
// @since CakePHP(tm) v 0.2.9
// @license MIT License (http://www.opensource.org/licenses/mit-license.php)
// +--------------------------------------------------------------------------------------------+ //
////////////////////////////////////////////////////////////////////////////////////////////////////
1.2.2.8120
1.3.0.0

View file

@ -830,7 +830,7 @@ if (!function_exists('file_put_contents')) {
function array_intersect_key($arr1, $arr2) {
$res = array();
foreach ($arr1 as $key => $value) {
if (isset($arr2[$key])) {
if (array_key_exists($key, $arr2)) {
$res[$key] = $arr1[$key];
}
}

View file

@ -1,48 +1,35 @@
<?php
/* SVN FILE: $Id$ */
/**
* Basic Cake functionality.
*
* Core functions for including other source files, loading models and so forth.
* Handles loading of core files needed on every request
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.cake
* @since CakePHP(tm) v 0.2.9
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
if (!defined('PHP5')) {
define('PHP5', (PHP_VERSION >= 5));
}
/**
* Configuration, directory layout and standard libraries
*/
if (!isset($bootstrap)) {
require CORE_PATH . 'cake' . DS . 'basics.php';
$TIME_START = getMicrotime();
require CORE_PATH . 'cake' . DS . 'config' . DS . 'paths.php';
require LIBS . 'object.php';
require LIBS . 'inflector.php';
require LIBS . 'configure.php';
}
require LIBS . 'cache.php';
Configure::getInstance();
$url = null;
App::import('Core', array('Dispatcher'));
require CORE_PATH . 'cake' . DS . 'basics.php';
$TIME_START = getMicrotime();
require CORE_PATH . 'cake' . DS . 'config' . DS . 'paths.php';
require LIBS . 'object.php';
require LIBS . 'inflector.php';
require LIBS . 'configure.php';
require LIBS . 'set.php';
require LIBS . 'cache.php';
Configure::getInstance();
require CAKE . 'dispatcher.php';
?>

View file

@ -1,26 +1,23 @@
<?php
/* SVN FILE: $Id$ */
/**
* Core Configurations.
*
* Holds configurations used by CakePHP
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.app.config
* @since CakePHP(tm) v 1.1.11.4062
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
return $config['Cake.version'] = '1.3.0';
return $config['Cake.version'] = '1.3.0.0';
?>

View file

@ -198,7 +198,7 @@ class ShellDispatcher {
*/
function __buildPaths() {
$paths = array();
$pluginPaths = Configure::read('pluginPaths');
$pluginPaths = App::path('plugins');
if (!class_exists('Folder')) {
require LIBS . 'folder.php';
}
@ -214,7 +214,7 @@ class ShellDispatcher {
}
}
$vendorPaths = array_values(Configure::read('vendorPaths'));
$vendorPaths = array_values(App::path('vendors'));
foreach ($vendorPaths as $vendorPath) {
$path = rtrim($vendorPath, DS) . DS . 'shells' . DS;
if (file_exists($path)) {
@ -222,7 +222,7 @@ class ShellDispatcher {
}
}
$this->shellPaths = array_values(array_unique(array_merge($paths, Configure::read('shellPaths'))));
$this->shellPaths = array_values(array_unique(array_merge($paths, App::path('shells'))));
}
/**
* Initializes the environment and loads the Cake core.
@ -259,7 +259,7 @@ class ShellDispatcher {
Configure::getInstance(file_exists(CONFIGS . 'bootstrap.php'));
if (!file_exists(APP_PATH . 'config' . DS . 'core.php')) {
include_once CORE_PATH . 'cake' . DS . 'console' . DS . 'libs' . DS . 'templates' . DS . 'skel' . DS . 'config' . DS . 'core.php';
include_once CORE_PATH . 'cake' . DS . 'console' . DS . 'templates' . DS . 'skel' . DS . 'config' . DS . 'core.php';
Configure::buildPaths(array());
}
@ -548,7 +548,7 @@ class ShellDispatcher {
foreach ($this->shellPaths as $path) {
if (is_dir($path)) {
$shells = Configure::listObjects('file', $path);
$shells = App::objects('file', $path);
$path = str_replace(CAKE_CORE_INCLUDE_PATH . DS . 'cake' . DS, 'CORE' . DS, $path);
$path = str_replace(APP, 'APP' . DS, $path);
$path = str_replace(ROOT, 'ROOT', $path);

View file

@ -205,7 +205,7 @@ class AclShell extends Shell {
extract($this->__dataVars());
$data = array(
$class => array(
'id' => $this->args[1],
'id' => $this->args[1],
'parent_id' => $this->args[2]
)
);
@ -336,7 +336,12 @@ class AclShell extends Shell {
}
$last = $n[$class]['rght'];
$count = count($stack);
$this->out(str_repeat(' ', $count) . "[" . $n[$class]['id'] . "]" . $n[$class]['alias']."\n");
$indent = str_repeat(' ', $count);
if ($n[$class]['alias']) {
$this->out($indent . "[" . $n[$class]['id'] . "]" . $n[$class]['alias']."\n");
} else {
$this->out($indent . "[" . $n[$class]['id'] . "]" . $n[$class]['model'] . '.' . $n[$class]['foreign_key'] . "\n");
}
}
$this->hr();
}

View file

@ -82,7 +82,7 @@ class ApiShell extends Shell {
$class = Inflector::camelize($file);
}
$objects = Configure::listObjects('class', $path);
$objects = App::objects('class', $path);
if (in_array($class, $objects)) {
if (in_array($type, array('behavior', 'component', 'helper')) && $type !== $file) {
if (!preg_match('/' . Inflector::camelize($type) . '$/', $class)) {
@ -151,17 +151,17 @@ class ApiShell extends Shell {
$commands = array(
'path' => "\t<type>\n" .
"\t\tEither a full path or type of class (model, behavior, controller, component, view, helper).\n".
"\t\tAvailable values:\n\n".
"\t\tbehavior\tLook for class in CakePHP behavior path\n".
"\t\tcache\tLook for class in CakePHP cache path\n".
"\t\tcontroller\tLook for class in CakePHP controller path\n".
"\t\tcomponent\tLook for class in CakePHP component path\n".
"\t\thelper\tLook for class in CakePHP helper path\n".
"\t\tmodel\tLook for class in CakePHP model path\n".
"\t\tview\tLook for class in CakePHP view path\n",
"\t\tEither a full path or type of class (model, behavior, controller, component, view, helper).\n".
"\t\tAvailable values:\n\n".
"\t\tbehavior\tLook for class in CakePHP behavior path\n".
"\t\tcache\tLook for class in CakePHP cache path\n".
"\t\tcontroller\tLook for class in CakePHP controller path\n".
"\t\tcomponent\tLook for class in CakePHP component path\n".
"\t\thelper\tLook for class in CakePHP helper path\n".
"\t\tmodel\tLook for class in CakePHP model path\n".
"\t\tview\tLook for class in CakePHP view path\n",
'className' => "\t<className>\n" .
"\t\tA CakePHP core class name (e.g: Component, HtmlHelper).\n"
"\t\tA CakePHP core class name (e.g: Component, HtmlHelper).\n"
);
$this->out($head);
@ -196,16 +196,16 @@ class ApiShell extends Shell {
$contents = $File->read();
if (preg_match_all('%(/\\*\\*[\\s\\S]*?\\*/)(\\s+function\\s+\\w+)(\\(.+\\))%', $contents, $result, PREG_PATTERN_ORDER)) {
if (preg_match_all('%(/\\*\\*[\\s\\S]*?\\*/)(\\s+function\\s+\\w+)(\\(.*\\))%', $contents, $result, PREG_PATTERN_ORDER)) {
foreach ($result[2] as $key => $method) {
$method = str_replace('function ', '', trim($method));
if (strpos($method, '__') === false && $method[0] != '_') {
$parsed[$method] = array(
'comment' => r(array('/*', '*/', '*'), '', trim($result[1][$key])),
'method' => $method,
'parameters' => trim($result[3][$key]),
);
'comment' => r(array('/*', '*/', '*'), '', trim($result[1][$key])),
'method' => $method,
'parameters' => trim($result[3][$key])
);
}
}
}

View file

@ -58,7 +58,7 @@ class ConsoleShell extends Shell {
function initialize() {
require_once CAKE . 'dispatcher.php';
$this->Dispatcher = new Dispatcher();
$this->models = Configure::listObjects('model');
$this->models = App::objects('model');
App::import('Model', $this->models);
foreach ($this->models as $model) {

View file

@ -26,7 +26,7 @@
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
App::import('File');
App::import('Model', 'Schema');
App::import('Model', 'CakeSchema');
/**
* Schema is a command-line database management utility for automating programmer chores.
*

View file

@ -243,8 +243,11 @@ class ControllerTask extends Shell {
* @access private
*/
function bakeActions($controllerName, $admin = null, $wannaUseSession = true) {
$currentModelName = $this->_modelName($controllerName);
if (!App::import('Model', $currentModelName)) {
$currentModelName = $modelImport = $this->_modelName($controllerName);
if ($this->plugin) {
$modelImport = $this->plugin . '.' . $modelImport;
}
if (!App::import('Model', $modelImport)) {
$this->err(__('You must have a model for this class to build scaffold methods. Please try again.', true));
exit;
}
@ -375,7 +378,7 @@ class ControllerTask extends Shell {
$actions .= "\t\t\t\$this->flash(__('Invalid {$singularHumanName}', true), array('action'=>'index'));\n";
}
$actions .= "\t\t}\n";
$actions .= "\t\tif (\$this->{$currentModelName}->del(\$id)) {\n";
$actions .= "\t\tif (\$this->{$currentModelName}->delete(\$id)) {\n";
if ($wannaUseSession) {
$actions .= "\t\t\t\$this->Session->setFlash(__('{$singularHumanName} deleted', true));\n";
$actions .= "\t\t\t\$this->redirect(array('action'=>'index'));\n";
@ -465,11 +468,11 @@ class ControllerTask extends Shell {
$out .= "\tvar \$autoRender = false;\n}\n\n";
$out .= "class {$className}ControllerTest extends CakeTestCase {\n";
$out .= "\tvar \${$className} = null;\n\n";
$out .= "\tfunction setUp() {\n\t\t\$this->{$className} = new Test{$className}();";
$out .= "\tfunction startTest() {\n\t\t\$this->{$className} = new Test{$className}();";
$out .= "\n\t\t\$this->{$className}->constructClasses();\n\t}\n\n";
$out .= "\tfunction test{$className}ControllerInstance() {\n";
$out .= "\t\t\$this->assertTrue(is_a(\$this->{$className}, '{$className}Controller'));\n\t}\n\n";
$out .= "\tfunction tearDown() {\n\t\tunset(\$this->{$className});\n\t}\n}\n";
$out .= "\tfunction endTest() {\n\t\tunset(\$this->{$className});\n\t}\n}\n";
$path = CONTROLLER_TESTS;
if (isset($this->plugin)) {

View file

@ -281,7 +281,7 @@ class DbConfigTask extends Shell {
if ($info['persistent'] === false) {
$info['persistent'] = 'false';
} else {
$info['persistent'] = 'false';
$info['persistent'] = ($info['persistent'] == true) ? 'true' : 'false';
}
$oldConfigs[] = array(

View file

@ -832,7 +832,7 @@ class ModelTask extends Shell {
*/
function fixture($model, $useTable = null) {
if (!class_exists('CakeSchema')) {
App::import('Model', 'Schema');
App::import('Model', 'CakeSchema');
}
$out = "\nclass {$model}Fixture extends CakeTestFixture {\n";
$out .= "\tvar \$name = '$model';\n";

View file

@ -85,7 +85,7 @@
return;
} else {
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch($url);
$Dispatcher->dispatch();
}
if (Configure::read() > 0) {
echo "<!-- " . round(getMicrotime() - $TIME_START, 4) . "s -->";

View file

@ -50,16 +50,16 @@
<div class="actions">
<ul>
<?php if ($action != 'add'):?>
<li><?php echo "<?php echo \$html->link(__('Delete', true), array('action'=>'delete', \$form->value('{$modelClass}.{$primaryKey}')), null, sprintf(__('Are you sure you want to delete # %s?', true), \$form->value('{$modelClass}.{$primaryKey}'))); ?>";?></li>
<li><?php echo "<?php echo \$html->link(__('Delete', true), array('action' => 'delete', \$form->value('{$modelClass}.{$primaryKey}')), null, sprintf(__('Are you sure you want to delete # %s?', true), \$form->value('{$modelClass}.{$primaryKey}'))); ?>";?></li>
<?php endif;?>
<li><?php echo "<?php echo \$html->link(__('List {$pluralHumanName}', true), array('action'=>'index'));?>";?></li>
<li><?php echo "<?php echo \$html->link(__('List {$pluralHumanName}', true), array('action' => 'index'));?>";?></li>
<?php
$done = array();
foreach ($associations as $type => $data) {
foreach ($data as $alias => $details) {
if ($details['controller'] != $this->name && !in_array($details['controller'], $done)) {
echo "\t\t<li><?php echo \$html->link(__('List ".Inflector::humanize($details['controller'])."', true), array('controller'=> '{$details['controller']}', 'action'=>'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller'=> '{$details['controller']}', 'action'=>'add')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('List ".Inflector::humanize($details['controller'])."', true), array('controller' => '{$details['controller']}', 'action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller' => '{$details['controller']}', 'action' => 'add')); ?> </li>\n";
$done[] = $details['controller'];
}
}

View file

@ -54,7 +54,7 @@ foreach (\${$pluralVar} as \${$singularVar}):
foreach ($associations['belongsTo'] as $alias => $details) {
if ($field === $details['foreignKey']) {
$isKey = true;
echo "\t\t<td>\n\t\t\t<?php echo \$html->link(\${$singularVar}['{$alias}']['{$details['displayField']}'], array('controller'=> '{$details['controller']}', 'action'=>'view', \${$singularVar}['{$alias}']['{$details['primaryKey']}'])); ?>\n\t\t</td>\n";
echo "\t\t<td>\n\t\t\t<?php echo \$html->link(\${$singularVar}['{$alias}']['{$details['displayField']}'], array('controller' => '{$details['controller']}', 'action' => 'view', \${$singularVar}['{$alias}']['{$details['primaryKey']}'])); ?>\n\t\t</td>\n";
break;
}
}
@ -65,9 +65,9 @@ foreach (\${$pluralVar} as \${$singularVar}):
}
echo "\t\t<td class=\"actions\">\n";
echo "\t\t\t<?php echo \$html->link(__('View', true), array('action'=>'view', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?>\n";
echo "\t\t\t<?php echo \$html->link(__('Edit', true), array('action'=>'edit', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?>\n";
echo "\t\t\t<?php echo \$html->link(__('Delete', true), array('action'=>'delete', \${$singularVar}['{$modelClass}']['{$primaryKey}']), null, sprintf(__('Are you sure you want to delete # %s?', true), \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?>\n";
echo "\t\t\t<?php echo \$html->link(__('View', true), array('action' => 'view', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?>\n";
echo "\t\t\t<?php echo \$html->link(__('Edit', true), array('action' => 'edit', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?>\n";
echo "\t\t\t<?php echo \$html->link(__('Delete', true), array('action' => 'delete', \${$singularVar}['{$modelClass}']['{$primaryKey}']), null, sprintf(__('Are you sure you want to delete # %s?', true), \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?>\n";
echo "\t\t</td>\n";
echo "\t</tr>\n";
@ -78,18 +78,18 @@ echo "<?php endforeach; ?>\n";
<div class="paging">
<?php echo "\t<?php echo \$paginator->prev('<< '.__('previous', true), array(), null, array('class'=>'disabled'));?>\n";?>
| <?php echo "\t<?php echo \$paginator->numbers();?>\n"?>
<?php echo "\t<?php echo \$paginator->next(__('next', true).' >>', array(), null, array('class'=>'disabled'));?>\n";?>
<?php echo "\t<?php echo \$paginator->next(__('next', true).' >>', array(), null, array('class' => 'disabled'));?>\n";?>
</div>
<div class="actions">
<ul>
<li><?php echo "<?php echo \$html->link(__('New {$singularHumanName}', true), array('action'=>'add')); ?>";?></li>
<li><?php echo "<?php echo \$html->link(__('New {$singularHumanName}', true), array('action' => 'add')); ?>";?></li>
<?php
$done = array();
foreach ($associations as $type => $data) {
foreach ($data as $alias => $details) {
if ($details['controller'] != $this->name && !in_array($details['controller'], $done)) {
echo "\t\t<li><?php echo \$html->link(__('List ".Inflector::humanize($details['controller'])."', true), array('controller'=> '{$details['controller']}', 'action'=>'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller'=> '{$details['controller']}', 'action'=>'add')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('List ".Inflector::humanize($details['controller'])."', true), array('controller' => '{$details['controller']}', 'action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller' => '{$details['controller']}', 'action' => 'add')); ?> </li>\n";
$done[] = $details['controller'];
}
}

View file

@ -33,7 +33,7 @@ foreach ($fields as $field) {
if ($field === $details['foreignKey']) {
$isKey = true;
echo "\t\t<dt<?php if (\$i % 2 == 0) echo \$class;?>><?php __('".Inflector::humanize(Inflector::underscore($alias))."'); ?></dt>\n";
echo "\t\t<dd<?php if (\$i++ % 2 == 0) echo \$class;?>>\n\t\t\t<?php echo \$html->link(\${$singularVar}['{$alias}']['{$details['displayField']}'], array('controller'=> '{$details['controller']}', 'action'=>'view', \${$singularVar}['{$alias}']['{$details['primaryKey']}'])); ?>\n\t\t\t&nbsp;\n\t\t</dd>\n";
echo "\t\t<dd<?php if (\$i++ % 2 == 0) echo \$class;?>>\n\t\t\t<?php echo \$html->link(\${$singularVar}['{$alias}']['{$details['displayField']}'], array('controller' => '{$details['controller']}', 'action' => 'view', \${$singularVar}['{$alias}']['{$details['primaryKey']}'])); ?>\n\t\t\t&nbsp;\n\t\t</dd>\n";
break;
}
}
@ -49,17 +49,17 @@ foreach ($fields as $field) {
<div class="actions">
<ul>
<?php
echo "\t\t<li><?php echo \$html->link(__('Edit {$singularHumanName}', true), array('action'=>'edit', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('Delete {$singularHumanName}', true), array('action'=>'delete', \${$singularVar}['{$modelClass}']['{$primaryKey}']), null, sprintf(__('Are you sure you want to delete # %s?', true), \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('List {$pluralHumanName}', true), array('action'=>'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New {$singularHumanName}', true), array('action'=>'add')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('Edit {$singularHumanName}', true), array('action' => 'edit', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('Delete {$singularHumanName}', true), array('action' => 'delete', \${$singularVar}['{$modelClass}']['{$primaryKey}']), null, sprintf(__('Are you sure you want to delete # %s?', true), \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('List {$pluralHumanName}', true), array('action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New {$singularHumanName}', true), array('action' => 'add')); ?> </li>\n";
$done = array();
foreach ($associations as $type => $data) {
foreach ($data as $alias => $details) {
if ($details['controller'] != $this->name && !in_array($details['controller'], $done)) {
echo "\t\t<li><?php echo \$html->link(__('List ".Inflector::humanize($details['controller'])."', true), array('controller'=> '{$details['controller']}', 'action'=>'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller'=> '{$details['controller']}', 'action'=>'add')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('List ".Inflector::humanize($details['controller'])."', true), array('controller' => '{$details['controller']}', 'action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$html->link(__('New ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller' => '{$details['controller']}', 'action' => 'add')); ?> </li>\n";
$done[] = $details['controller'];
}
}
@ -84,7 +84,7 @@ if (!empty($associations['hasOne'])) :
<?php echo "<?php endif; ?>\n";?>
<div class="actions">
<ul>
<li><?php echo "<?php echo \$html->link(__('Edit ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller'=> '{$details['controller']}', 'action'=>'edit', \${$singularVar}['{$alias}']['{$details['primaryKey']}'])); ?></li>\n";?>
<li><?php echo "<?php echo \$html->link(__('Edit ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller' => '{$details['controller']}', 'action' => 'edit', \${$singularVar}['{$alias}']['{$details['primaryKey']}'])); ?></li>\n";?>
</ul>
</div>
</div>
@ -131,9 +131,9 @@ echo "\t<?php
}
echo "\t\t\t<td class=\"actions\">\n";
echo "\t\t\t\t<?php echo \$html->link(__('View', true), array('controller'=> '{$details['controller']}', 'action'=>'view', \${$otherSingularVar}['{$details['primaryKey']}'])); ?>\n";
echo "\t\t\t\t<?php echo \$html->link(__('Edit', true), array('controller'=> '{$details['controller']}', 'action'=>'edit', \${$otherSingularVar}['{$details['primaryKey']}'])); ?>\n";
echo "\t\t\t\t<?php echo \$html->link(__('Delete', true), array('controller'=> '{$details['controller']}', 'action'=>'delete', \${$otherSingularVar}['{$details['primaryKey']}']), null, sprintf(__('Are you sure you want to delete # %s?', true), \${$otherSingularVar}['{$details['primaryKey']}'])); ?>\n";
echo "\t\t\t\t<?php echo \$html->link(__('View', true), array('controller' => '{$details['controller']}', 'action' => 'view', \${$otherSingularVar}['{$details['primaryKey']}'])); ?>\n";
echo "\t\t\t\t<?php echo \$html->link(__('Edit', true), array('controller' => '{$details['controller']}', 'action' => 'edit', \${$otherSingularVar}['{$details['primaryKey']}'])); ?>\n";
echo "\t\t\t\t<?php echo \$html->link(__('Delete', true), array('controller' => '{$details['controller']}', 'action' => 'delete', \${$otherSingularVar}['{$details['primaryKey']}']), null, sprintf(__('Are you sure you want to delete # %s?', true), \${$otherSingularVar}['{$details['primaryKey']}'])); ?>\n";
echo "\t\t\t</td>\n";
echo "\t\t</tr>\n";
@ -143,7 +143,7 @@ echo "\t<?php endforeach; ?>\n";
<?php echo "<?php endif; ?>\n\n";?>
<div class="actions">
<ul>
<li><?php echo "<?php echo \$html->link(__('New ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller'=> '{$details['controller']}', 'action'=>'add'));?>";?> </li>
<li><?php echo "<?php echo \$html->link(__('New ".Inflector::humanize(Inflector::underscore($alias))."', true), array('controller' => '{$details['controller']}', 'action' => 'add'));?>";?> </li>
</ul>
</div>
</div>

View file

@ -93,7 +93,7 @@ class TestSuiteShell extends Shell {
require_once CAKE . 'tests' . DS . 'lib' . DS . 'test_manager.php';
require_once CAKE . 'tests' . DS . 'lib' . DS . 'cli_reporter.php';
$plugins = Configure::listObjects('plugin');
$plugins = App::objects('plugin');
foreach ($plugins as $p) {
$this->plugins[] = Inflector::underscore($p);
}
@ -156,30 +156,30 @@ class TestSuiteShell extends Shell {
function help() {
$this->out('Usage: ');
$this->out("\tcake testsuite category test_type file");
$this->out("\t\t - category - \"app\", \"core\" or name of a plugin");
$this->out("\t\t - test_type - \"case\", \"group\" or \"all\"");
$this->out("\t\t - test_file - file name with folder prefix and without the (test|group).php suffix");
$this->out("\t\t- category - \"app\", \"core\" or name of a plugin");
$this->out("\t\t- test_type - \"case\", \"group\" or \"all\"");
$this->out("\t\t- test_file - file name with folder prefix and without the (test|group).php suffix");
$this->out('');
$this->out('Examples: ');
$this->out("\t\t cake testsuite app all");
$this->out("\t\t cake testsuite core all");
$this->out("\t\tcake testsuite app all");
$this->out("\t\tcake testsuite core all");
$this->out('');
$this->out("\t\t cake testsuite app case behaviors/debuggable");
$this->out("\t\t cake testsuite app case models/my_model");
$this->out("\t\t cake testsuite app case controllers/my_controller");
$this->out("\t\tcake testsuite app case behaviors/debuggable");
$this->out("\t\tcake testsuite app case models/my_model");
$this->out("\t\tcake testsuite app case controllers/my_controller");
$this->out('');
$this->out("\t\t cake testsuite core case file");
$this->out("\t\t cake testsuite core case router");
$this->out("\t\t cake testsuite core case set");
$this->out("\t\tcake testsuite core case file");
$this->out("\t\tcake testsuite core case router");
$this->out("\t\tcake testsuite core case set");
$this->out('');
$this->out("\t\t cake testsuite app group mygroup");
$this->out("\t\t cake testsuite core group acl");
$this->out("\t\t cake testsuite core group socket");
$this->out("\t\tcake testsuite app group mygroup");
$this->out("\t\tcake testsuite core group acl");
$this->out("\t\tcake testsuite core group socket");
$this->out('');
$this->out("\t\t cake testsuite bugs case models/bug // for the plugin 'bugs' and its test case 'bug'");
$this->out("\t\t cake testsuite bugs group bug // for the plugin bugs and its test group 'bug'");
$this->out("\t\t cake testsuite bugs_me case models/bug // for the plugin 'bugs_me' and its test case 'bug'");
$this->out("\t\t cake testsuite bugs_me group bug // for the plugin bugs_me and its test group 'bug'");
$this->out("\t\tcake testsuite bugs case models/bug");
$this->out("\t\t // for the plugin 'bugs' and its test case 'models/bug'");
$this->out("\t\tcake testsuite bugs group bug");
$this->out("\t\t // for the plugin bugs and its test group 'bug'");
$this->out('');
$this->out('Code Coverage Analysis: ');
$this->out("\n\nAppend 'cov' to any of the above in order to enable code coverage analysis");
@ -312,11 +312,19 @@ class TestSuiteShell extends Shell {
);
if (array_key_exists($category, $paths)) {
$folder = $paths[$category];
$folder = $paths[$category] . 'tests';
} else {
$folder = APP.'plugins'.DS.Inflector::underscore($category).DS;
$scoredCategory = Inflector::underscore($category);
$folder = APP . 'plugins' . DS . $scoredCategory . DS;
$pluginPaths = App::path('plugins');
foreach ($pluginPaths as $path) {
if (file_exists($path . $scoredCategory . DS . 'tests')) {
$folder = $path . $scoredCategory . DS . 'tests';
break;
}
}
}
return $folder.'tests';
return $folder;
}
/**
* Sets some get vars needed for TestManager

View file

@ -344,7 +344,8 @@ class Dispatcher extends Object {
return $this->base = $base;
}
if (!$baseUrl) {
$base = dirname(env('PHP_SELF'));
$replace = array('<', '>', '*', '\'', '"');
$base = str_replace($replace, '', dirname(env('PHP_SELF')));
if ($webroot === 'webroot' && $webroot === basename($base)) {
$base = dirname($base);
@ -619,13 +620,13 @@ class Dispatcher extends Object {
if ($pos > 0) {
$plugin = substr($url, 0, $pos - 1);
$url = str_replace($plugin . '/', '', $url);
$pluginPaths = Configure::read('pluginPaths');
$pluginPaths = App::path('plugins');
$count = count($pluginPaths);
for ($i = 0; $i < $count; $i++) {
$paths[] = $pluginPaths[$i] . $plugin . DS . 'vendors' . DS;
}
}
$paths = array_merge($paths, Configure::read('vendorPaths'));
$paths = array_merge($paths, App::path('vendors'));
foreach ($paths as $path) {
if (is_file($path . $url) && file_exists($path . $url)) {

View file

@ -168,7 +168,6 @@ class FileEngine extends CacheEngine {
if ($cachetime !== false && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) {
$this->__File->close();
$this->__File->delete();
return false;
}
$data = $this->__File->read(true);

View file

@ -27,16 +27,7 @@
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
/**
* Database name for cake sessions.
*
*/
if (!class_exists('Set')) {
require LIBS . 'set.php';
}
if (!class_exists('Security')) {
require LIBS . 'security.php';
}
/**
* Session class for Cake.
*
@ -125,34 +116,52 @@ class CakeSession extends Object {
* @access public
*/
function __construct($base = null, $start = true) {
if (Configure::read('Session.save') === 'database' && !class_exists('ConnectionManager')) {
App::import('Core', 'ConnectionManager');
}
App::import('Core', 'Security');
$this->time = time();
if (Configure::read('Session.checkAgent') === true || Configure::read('Session.checkAgent') === null) {
if (env('HTTP_USER_AGENT') != null) {
$this->_userAgent = md5(env('HTTP_USER_AGENT') . Configure::read('Security.salt'));
}
}
$this->time = time();
if (Configure::read('Session.save') === 'database') {
$modelName = Configure::read('Session.model');
$database = Configure::read('Session.database');
$table = Configure::read('Session.table');
if ($start === true) {
$this->host = env('HTTP_HOST');
if (empty($base) || strpos($base, '?') === 0 || strpos($base, 'index.php') === 0) {
$this->path = '/';
} else {
$this->path = $base;
if (empty($database)) {
$database = 'default';
}
if (empty($modelName)) {
ClassRegistry::init(array(
'class' => Inflector::classify($table),
'alias' => 'Session'
));
} else {
ClassRegistry::init(array(
'class' => $modelName,
'alias' => 'Session'
));
}
}
if ($start === true) {
if (!empty($base)) {
$this->path = $base;
if (strpos($base, 'index.php') !== false) {
$this->path = str_replace('index.php', '', $base);
}
if (strpos($base, '?') !== false) {
$this->path = str_replace('?', '', $base);
}
}
$this->host = env('HTTP_HOST');
if (strpos($this->host, ':') !== false) {
$this->host = substr($this->host, 0, strpos($this->host, ':'));
}
if (!class_exists('Security')) {
App::import('Core', 'Security');
}
$this->sessionTime = $this->time + (Security::inactiveMins() * Configure::read('Session.timeout'));
$this->security = Configure::read('Security.level');
}
@ -510,7 +519,7 @@ class CakeSession extends Object {
array('Cache', 'read'),
array('Cache', 'write'),
array('Cache', 'delete'),
array('CakeSession', '__gc'));
array('Cache', 'gc'));
break;
default:
if (empty($_SESSION)) {
@ -685,81 +694,64 @@ class CakeSession extends Object {
/**
* Method used to read from a database session.
*
* @param mixed $key The key of the value to read
* @param mixed $id The key of the value to read
* @return mixed The value of the key or false if it does not exist
* @access private
*/
function __read($key) {
$db =& ConnectionManager::getDataSource(Configure::read('Session.database'));
$table = $db->fullTableName(Configure::read('Session.table'), false);
$row = $db->query("SELECT " . $db->name($table.'.data') . " FROM " . $db->name($table) . " WHERE " . $db->name($table.'.id') . " = " . $db->value($key), false);
function __read($id) {
$model =& ClassRegistry::getObject('Session');
if ($row && !isset($row[0][$table]) && isset($row[0][0])) {
$table = 0;
}
$row = $model->find('first', array(
'conditions' => array($model->primaryKey => $id)
));
if ($row && $row[0][$table]['data']) {
return $row[0][$table]['data'];
} else {
if (empty($row[$model->alias]['data'])) {
return false;
}
return $row[$model->alias]['data'];
}
/**
* Helper function called on write for database sessions.
*
* @param mixed $key The name of the var
* @param mixed $value The value of the var
* @return boolean Success
* @param integer $id ID that uniquely identifies session in database
* @param mixed $data The value of the the data to be saved.
* @return boolean True for successful write, false otherwise.
* @access private
*/
function __write($key, $value) {
$db =& ConnectionManager::getDataSource(Configure::read('Session.database'));
$table = $db->fullTableName(Configure::read('Session.table'));
function __write($id, $data) {
switch (Configure::read('Security.level')) {
case 'high':
$factor = 10;
break;
case 'medium':
$factor = 100;
break;
case 'low':
$factor = 300;
break;
case 'high':
default:
$factor = 10;
break;
}
$expires = time() + Configure::read('Session.timeout') * $factor;
$row = $db->query("SELECT COUNT(id) AS count FROM " . $db->name($table) . " WHERE "
. $db->name('id') . " = "
. $db->value($key), false);
if ($row[0][0]['count'] > 0) {
$db->execute("UPDATE " . $db->name($table) . " SET " . $db->name('data') . " = "
. $db->value($value) . ", " . $db->name('expires') . " = "
. $db->value($expires) . " WHERE " . $db->name('id') . " = "
. $db->value($key));
} else {
$db->execute("INSERT INTO " . $db->name($table) . " (" . $db->name('data') . ","
. $db->name('expires') . "," . $db->name('id')
. ") VALUES (" . $db->value($value) . ", " . $db->value($expires) . ", "
. $db->value($key) . ")");
}
return true;
$expires = time() + Configure::read('Session.timeout') * $factor;
$model =& ClassRegistry::getObject('Session');
$return = $model->save(compact('id', 'data', 'expires'));
return $return;
}
/**
* Method called on the destruction of a database session.
*
* @param integer $key Key that uniquely identifies session in database
* @return boolean Success
* @param integer $id ID that uniquely identifies session in database
* @return boolean True for successful delete, false otherwise.
* @access private
*/
function __destroy($key) {
$db =& ConnectionManager::getDataSource(Configure::read('Session.database'));
$table = $db->fullTableName(Configure::read('Session.table'));
$db->execute("DELETE FROM " . $db->name($table) . " WHERE " . $db->name($table.'.id') . " = " . $db->value($key));
return true;
function __destroy($id) {
$model =& ClassRegistry::getObject('Session');
$return = $model->delete($id);
return $return;
}
/**
* Helper function called on gc for database sessions.
@ -769,10 +761,14 @@ class CakeSession extends Object {
* @access private
*/
function __gc($expires = null) {
$db =& ConnectionManager::getDataSource(Configure::read('Session.database'));
$table = $db->fullTableName(Configure::read('Session.table'));
$db->execute("DELETE FROM " . $db->name($table) . " WHERE " . $db->name($table.'.expires') . " < ". $db->value(time()));
return true;
$model =& ClassRegistry::getObject('Session');
if (!$expires) {
$expires = time();
}
$return = $model->deleteAll(array($model->alias . ".expires <" => $expires), false, false);
return $return;
}
}
?>

View file

@ -32,76 +32,6 @@
* @link http://book.cakephp.org/view/42/The-Configuration-Class
*/
class Configure extends Object {
/**
* List of additional path(s) where model files reside.
*
* @var array
* @access public
*/
var $modelPaths = array();
/**
* List of additional path(s) where behavior files reside.
*
* @var array
* @access public
*/
var $behaviorPaths = array();
/**
* List of additional path(s) where controller files reside.
*
* @var array
* @access public
*/
var $controllerPaths = array();
/**
* List of additional path(s) where component files reside.
*
* @var array
* @access public
*/
var $componentPaths = array();
/**
* List of additional path(s) where view files reside.
*
* @var array
* @access public
*/
var $viewPaths = array();
/**
* List of additional path(s) where helper files reside.
*
* @var array
* @access public
*/
var $helperPaths = array();
/**
* List of additional path(s) where plugins reside.
*
* @var array
* @access public
*/
var $pluginPaths = array();
/**
* List of additional path(s) where vendor packages reside.
*
* @var array
* @access public
*/
var $vendorPaths = array();
/**
* List of additional path(s) where locale files reside.
*
* @var array
* @access public
*/
var $localePaths = array();
/**
* List of additional path(s) where console shell files reside.
*
* @var array
* @access public
*/
var $shellPaths = array();
/**
* Current debug level.
*
@ -117,13 +47,6 @@ class Configure extends Object {
* @access private
*/
var $__cache = false;
/**
* Holds and key => value array of objects' types.
*
* @var array
* @access private
*/
var $__objects = array();
/**
* Returns a singleton instance of the Configure class.
*
@ -138,111 +61,6 @@ class Configure extends Object {
}
return $instance[0];
}
/**
* Returns an index of objects of the given type, with the physical path to each object.
*
* @param string $type Type of object, i.e. 'model', 'controller', 'helper', or 'plugin'
* @param mixed $path Optional
* @return Configure instance
* @access public
*/
function listObjects($type, $path = null, $cache = true) {
$objects = array();
$extension = false;
$name = $type;
if ($type === 'file' && !$path) {
return false;
} elseif ($type === 'file') {
$extension = true;
$name = $type . str_replace(DS, '', $path);
}
$_this =& Configure::getInstance();
if (empty($_this->__objects) && $cache === true) {
$_this->__objects = Cache::read('object_map', '_cake_core_');
}
if (empty($_this->__objects) || !isset($_this->__objects[$type]) || $cache !== true) {
$types = array(
'model' => array('suffix' => '.php', 'base' => 'AppModel', 'core' => false),
'behavior' => array('suffix' => '.php', 'base' => 'ModelBehavior'),
'controller' => array('suffix' => '_controller.php', 'base' => 'AppController'),
'component' => array('suffix' => '.php', 'base' => null),
'view' => array('suffix' => '.php', 'base' => null),
'helper' => array('suffix' => '.php', 'base' => 'AppHelper'),
'plugin' => array('suffix' => '', 'base' => null),
'vendor' => array('suffix' => '', 'base' => null),
'class' => array('suffix' => '.php', 'base' => null),
'file' => array('suffix' => '.php', 'base' => null)
);
if (!isset($types[$type])) {
return false;
}
$objects = array();
if (empty($path)) {
$path = $_this->{$type . 'Paths'};
if (isset($types[$type]['core']) && $types[$type]['core'] === false) {
array_pop($path);
}
}
$items = array();
foreach ((array)$path as $dir) {
if ($type === 'file' || $type === 'class' || strpos($dir, $type) !== false) {
$items = $_this->__list($dir, $types[$type]['suffix'], $extension);
$objects = array_merge($items, array_diff($objects, $items));
}
}
if ($type !== 'file') {
foreach ($objects as $key => $value) {
$objects[$key] = Inflector::camelize($value);
}
}
if ($cache === true && !empty($objects)) {
$_this->__objects[$name] = $objects;
$_this->__cache = true;
} else {
return $objects;
}
}
return $_this->__objects[$name];
}
/**
* Returns an array of filenames of PHP files in the given directory.
*
* @param string $path Path to scan for files
* @param string $suffix if false, return only directories. if string, match and return files
* @return array List of directories or files in directory
*/
function __list($path, $suffix = false, $extension = false) {
if (!class_exists('Folder')) {
require LIBS . 'folder.php';
}
$items = array();
$Folder =& new Folder($path);
$contents = $Folder->read(false, true);
if (is_array($contents)) {
if (!$suffix) {
return $contents[0];
} else {
foreach ($contents[1] as $item) {
if (substr($item, - strlen($suffix)) === $suffix) {
if ($extension) {
$items[] = $item;
} else {
$items[] = substr($item, 0, strlen($item) - strlen($suffix));
}
}
}
}
}
return $items;
}
/**
* Used to store a dynamic variable in the Configure instance.
*
@ -254,7 +72,7 @@ class Configure extends Object {
* 'key1' => 'value of the Configure::One[key1]',
* 'key2' => 'value of the Configure::One[key2]'
* );
*
*
* Configure::write(array(
* 'One.key1' => 'value of the Configure::One[key1]',
* 'One.key2' => 'value of the Configure::One[key2]'
@ -403,7 +221,7 @@ class Configure extends Object {
include(CACHE . 'persistent' . DS . $fileName . '.php');
$found = true;
} else {
foreach (Configure::corePaths('cake') as $key => $path) {
foreach (App::core('cake') as $key => $path) {
if (file_exists($path . DS . 'config' . DS . $fileName . '.php')) {
include($path . DS . 'config' . DS . $fileName . '.php');
$found = true;
@ -479,57 +297,6 @@ class Configure extends Object {
}
Configure::__writeConfig($content, $name, $write);
}
/**
* Returns a key/value list of all paths where core libs are found.
* Passing $type only returns the values for a given value of $key.
*
* @param string $type valid values are: 'model', 'behavior', 'controller', 'component',
* 'view', 'helper', 'datasource', 'libs', and 'cake'
* @return array numeric keyed array of core lib paths
* @access public
*/
function corePaths($type = null) {
$paths = Cache::read('core_paths', '_cake_core_');
if (!$paths) {
$paths = array();
$openBasedir = ini_get('open_basedir');
if ($openBasedir) {
$all = explode(PATH_SEPARATOR, $openBasedir);
$all = array_flip(array_flip((array_merge(array(CAKE_CORE_INCLUDE_PATH), $all))));
} else {
$all = explode(PATH_SEPARATOR, ini_get('include_path'));
$all = array_flip(array_flip((array_merge(array(CAKE_CORE_INCLUDE_PATH), $all))));
}
foreach ($all as $path) {
if ($path !== DS) {
$path = rtrim($path, DS);
}
if (empty($path) || $path === '.') {
continue;
}
$cake = $path . DS . 'cake' . DS;
$libs = $cake . 'libs' . DS;
if (is_dir($libs)) {
$paths['libs'][] = $libs;
$paths['model'][] = $libs . 'model' . DS;
$paths['behavior'][] = $libs . 'model' . DS . 'behaviors' . DS;
$paths['controller'][] = $libs . 'controller' . DS;
$paths['component'][] = $libs . 'controller' . DS . 'components' . DS;
$paths['view'][] = $libs . 'view' . DS;
$paths['helper'][] = $libs . 'view' . DS . 'helpers' . DS;
$paths['cake'][] = $cake;
$paths['vendor'][] = $path . DS . 'vendors' . DS;
$paths['shell'][] = $cake . 'console' . DS . 'libs' . DS;
break;
}
}
Cache::write('core_paths', array_filter($paths), '_cake_core_');
}
if ($type && isset($paths[$type])) {
return $paths[$type];
}
return $paths;
}
/**
* Creates a cached version of a configuration file.
* Appends values passed from Configure::store() to the cached file
@ -582,56 +349,25 @@ class Configure extends Object {
return $name;
}
/**
* Build path references. Merges the supplied $paths
* with the base paths and the default core paths.
*
* @param array $paths paths defines in config/bootstrap.php
* @return void
* @access public
* @deprecated
* @see App::objects()
*/
function listObjects($type, $path = null, $cache = true) {
return App::objects($type, $path, $cache);
}
/**
* @deprecated
* @see App::core()
*/
function corePaths($type = null) {
return App::core($type);
}
/**
* @deprecated
* @see App::build()
*/
function buildPaths($paths) {
$_this =& Configure::getInstance();
$core = $_this->corePaths();
$basePaths = array(
'model' => array(MODELS),
'behavior' => array(BEHAVIORS),
'controller' => array(CONTROLLERS),
'component' => array(COMPONENTS),
'view' => array(VIEWS),
'helper' => array(HELPERS),
'plugin' => array(APP . 'plugins' . DS),
'vendor' => array(APP . 'vendors' . DS, VENDORS),
'locale' => array(APP . 'locale' . DS),
'shell' => array(),
'datasource' => array(MODELS . 'datasources')
);
foreach ($basePaths as $type => $default) {
$pathsVar = $type . 'Paths';
$merge = array();
if (isset($core[$type])) {
$merge = $core[$type];
}
if ($type === 'model' || $type === 'controller' || $type === 'helper') {
$merge = array_merge(array(APP), $merge);
}
if (!is_array($default)) {
$default = array($default);
}
$_this->{$pathsVar} = $default;
if (isset($paths[$pathsVar]) && !empty($paths[$pathsVar])) {
$path = array_flip(array_flip((array_merge(
$_this->{$pathsVar}, (array)$paths[$pathsVar], $merge
))));
$_this->{$pathsVar} = array_values($path);
} else {
$path = array_flip(array_flip((array_merge($_this->{$pathsVar}, $merge))));
$_this->{$pathsVar} = array_values($path);
}
}
return App::build($paths);
}
/**
* Loads app/config/bootstrap.php.
@ -692,9 +428,9 @@ class Configure extends Object {
}
Cache::config('default');
}
Configure::buildPaths(compact(
'modelPaths', 'viewPaths', 'controllerPaths', 'helperPaths', 'componentPaths',
'behaviorPaths', 'pluginPaths', 'vendorPaths', 'localePaths', 'shellPaths'
App::build(compact(
'models', 'views', 'controllers', 'helpers', 'components',
'behaviors', 'plugins', 'vendors', 'locales', 'shells'
));
}
}
@ -718,6 +454,96 @@ class Configure extends Object {
* @subpackage cake.cake.libs
*/
class App extends Object {
/**
* List of object types and their properties
*
* @var array
* @access public
*/
var $types = array(
'class' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'file' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'model' => array('suffix' => '.php', 'extends' => 'AppModel', 'core' => false),
'behavior' => array('suffix' => '.php', 'extends' => 'ModelBehavior', 'core' => true),
'controller' => array('suffix' => '_controller.php', 'extends' => 'AppController', 'core' => true),
'component' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'view' => array('suffix' => '.php', 'extends' => null, 'core' => true),
'helper' => array('suffix' => '.php', 'extends' => 'AppHelper', 'core' => true),
'vendor' => array('suffix' => '', 'extends' => null, 'core' => true),
'shell' => array('suffix' => '.php', 'extends' => 'Shell', 'core' => true),
'plugin' => array('suffix' => '', 'extends' => null, 'core' => true)
);
/**
* List of additional path(s) where model files reside.
*
* @var array
* @access public
*/
var $models = array();
/**
* List of additional path(s) where behavior files reside.
*
* @var array
* @access public
*/
var $behaviors = array();
/**
* List of additional path(s) where controller files reside.
*
* @var array
* @access public
*/
var $controllers = array();
/**
* List of additional path(s) where component files reside.
*
* @var array
* @access public
*/
var $components = array();
/**
* List of additional path(s) where view files reside.
*
* @var array
* @access public
*/
var $views = array();
/**
* List of additional path(s) where helper files reside.
*
* @var array
* @access public
*/
var $helpers = array();
/**
* List of additional path(s) where plugins reside.
*
* @var array
* @access public
*/
var $plugins = array();
/**
* List of additional path(s) where vendor packages reside.
*
* @var array
* @access public
*/
var $vendors = array();
/**
* List of additional path(s) where locale files reside.
*
* @var array
* @access public
*/
var $locales = array();
/**
* List of additional path(s) where console shell files reside.
*
* @var array
* @access public
*/
var $shells = array();
/**
* Paths to search for files.
*
@ -760,6 +586,201 @@ class App extends Object {
* @access private
*/
var $__loaded = array();
/**
* Holds and key => value array of object types.
*
* @var array
* @access private
*/
var $__objects = array();
/**
* Used to read information stored path
*
* Usage
* App::path('models'); will return all paths for models
*
* @param string $type type of path
* @return string array
* @access public
*/
function path($type) {
$_this =& App::getInstance();
if (!isset($_this->{$type})) {
return array();
}
return $_this->{$type};
}
/**
* Build path references. Merges the supplied $paths
* with the base paths and the default core paths.
*
* @param array $paths paths defines in config/bootstrap.php
* @param boolean $reset true will set paths, false merges paths [default] false
* @return void
* @access public
*/
function build($paths = array(), $reset = false) {
$_this =& App::getInstance();
$defaults = array(
'models' => array(MODELS),
'behaviors' => array(BEHAVIORS),
'datasources' => array(MODELS . 'datasources'),
'controllers' => array(CONTROLLERS),
'components' => array(COMPONENTS),
'views' => array(VIEWS),
'helpers' => array(HELPERS),
'locales' => array(APP . 'locale' . DS),
'shells' => array(APP . 'vendors' . DS . 'shells', VENDORS . 'shells'),
'vendors' => array(APP . 'vendors' . DS, VENDORS),
'plugins' => array(APP . 'plugins' . DS),
);
if ($reset == true) {
foreach ($paths as $type => $new) {
$_this->{$type} = (array)$new;
}
return $paths;
}
$core = $_this->core();
$app = array('models' => true, 'controllers' => true, 'helpers' => true);
foreach ($defaults as $type => $default) {
$merge = array();
if (isset($app[$type])) {
$merge = array(APP);
}
if (isset($core[$type])) {
$merge = array_merge($merge, (array)$core[$type]);
}
$_this->{$type} = $default;
if (!empty($paths[$type])) {
$path = array_flip(array_flip((array_merge(
$_this->{$type}, (array)$paths[$type], $merge
))));
$_this->{$type} = array_values($path);
} else {
$path = array_flip(array_flip((array_merge($_this->{$type}, $merge))));
$_this->{$type} = array_values($path);
}
}
}
/**
* Returns a key/value list of all paths where core libs are found.
* Passing $type only returns the values for a given value of $key.
*
* @param string $type valid values are: 'model', 'behavior', 'controller', 'component',
* 'view', 'helper', 'datasource', 'libs', and 'cake'
* @return array numeric keyed array of core lib paths
* @access public
*/
function core($type = null) {
$paths = Cache::read('core_paths', '_cake_core_');
if (!$paths) {
$paths = array();
$openBasedir = ini_get('open_basedir');
if ($openBasedir) {
$all = explode(PATH_SEPARATOR, $openBasedir);
$all = array_flip(array_flip((array_merge(array(CAKE_CORE_INCLUDE_PATH), $all))));
} else {
$all = explode(PATH_SEPARATOR, ini_get('include_path'));
$all = array_flip(array_flip((array_merge(array(CAKE_CORE_INCLUDE_PATH), $all))));
}
foreach ($all as $path) {
if ($path !== DS) {
$path = rtrim($path, DS);
}
if (empty($path) || $path === '.') {
continue;
}
$cake = $path . DS . 'cake' . DS;
$libs = $cake . 'libs' . DS;
if (is_dir($libs)) {
$paths['cake'][] = $cake;
$paths['libs'][] = $libs;
$paths['models'][] = $libs . 'model' . DS;
$paths['behaviors'][] = $libs . 'model' . DS . 'behaviors' . DS;
$paths['controllers'][] = $libs . 'controller' . DS;
$paths['components'][] = $libs . 'controller' . DS . 'components' . DS;
$paths['views'][] = $libs . 'view' . DS;
$paths['helpers'][] = $libs . 'view' . DS . 'helpers' . DS;
$paths['vendors'][] = $path . DS . 'vendors' . DS;
$paths['shells'][] = $cake . 'console' . DS . 'libs' . DS;
break;
}
}
Cache::write('core_paths', array_filter($paths), '_cake_core_');
}
if ($type && isset($paths[$type])) {
return $paths[$type];
}
return $paths;
}
/**
* Returns an index of objects of the given type, with the physical path to each object.
*
* @param string $type Type of object, i.e. 'model', 'controller', 'helper', or 'plugin'
* @param mixed $path Optional
* @return Configure instance
* @access public
*/
function objects($type, $path = null, $cache = true) {
$objects = array();
$extension = false;
$name = $type;
if ($type === 'file' && !$path) {
return false;
} elseif ($type === 'file') {
$extension = true;
$name = $type . str_replace(DS, '', $path);
}
$_this =& App::getInstance();
if (empty($_this->__objects) && $cache === true) {
$_this->__objects = Cache::read('object_map', '_cake_core_');
}
if (empty($_this->__objects) || !isset($_this->__objects[$type]) || $cache !== true) {
$types = $_this->types;
if (!isset($types[$type])) {
return false;
}
$objects = array();
if (empty($path)) {
$path = $_this->{"{$type}s"};
if (isset($types[$type]['core']) && $types[$type]['core'] === false) {
array_pop($path);
}
}
$items = array();
foreach ((array)$path as $dir) {
if ($type === 'file' || $type === 'class' || strpos($dir, $type) !== false) {
$items = $_this->__list($dir, $types[$type]['suffix'], $extension);
$objects = array_merge($items, array_diff($objects, $items));
}
}
if ($type !== 'file') {
foreach ($objects as $key => $value) {
$objects[$key] = Inflector::camelize($value);
}
}
if ($cache === true && !empty($objects)) {
$_this->__objects[$name] = $objects;
$_this->__cache = true;
} else {
return $objects;
}
}
return $_this->__objects[$name];
}
/**
* Finds classes based on $name or specific file(s) to search.
*
@ -779,6 +800,7 @@ class App extends Object {
* @access public
*/
function import($type = null, $name = null, $parent = true, $search = array(), $file = null, $return = false) {
$_this =& App::getInstance();
$plugin = $directory = null;
if (is_array($type)) {
@ -827,12 +849,13 @@ class App extends Object {
if ($name != null && strpos($name, '.') !== false) {
list($plugin, $name) = explode('.', $name);
$plugin = Inflector::camelize($plugin);
}
$_this =& App::getInstance();
$_this->return = $return;
if (isset($ext)) {
$file = Inflector::underscore($name) . ".$ext";
$file = Inflector::underscore($name) . ".{$ext}";
}
$ext = $_this->__settings($type, $plugin, $parent);
@ -868,7 +891,6 @@ class App extends Object {
foreach ($paths as $key => $value) {
$_this->search[$key] = $value . $ext['path'];
}
$plugin = Inflector::camelize($plugin);
}
}
@ -904,7 +926,7 @@ class App extends Object {
static $instance = array();
if (!$instance) {
$instance[0] =& new App();
$instance[0]->__map = Cache::read('file_map', '_cake_core_');
$instance[0]->__map = (array)Cache::read('file_map', '_cake_core_');
}
return $instance[0];
}
@ -985,12 +1007,11 @@ class App extends Object {
* @param string $file full path to file
* @param string $name unique name for this map
* @param string $type type object being mapped
* @param string $plugin if object is from a plugin, the name of the plugin
* @param string $plugin camelized if object is from a plugin, the name of the plugin
* @access private
*/
function __map($file, $name, $type, $plugin) {
if ($plugin) {
$plugin = Inflector::camelize($plugin);
$this->__map['Plugin'][$plugin][$type][$name] = $file;
} else {
$this->__map[$type][$name] = $file;
@ -1001,14 +1022,12 @@ class App extends Object {
*
* @param string $name unique name
* @param string $type type object
* @param string $plugin if object is from a plugin, the name of the plugin
* @param string $plugin camelized if object is from a plugin, the name of the plugin
* @return mixed, file path if found, false otherwise
* @access private
*/
function __mapped($name, $type, $plugin) {
if ($plugin) {
$plugin = Inflector::camelize($plugin);
if (isset($this->__map['Plugin'][$plugin][$type]) && isset($this->__map['Plugin'][$plugin][$type][$name])) {
return $this->__map['Plugin'][$plugin][$type][$name];
}
@ -1037,7 +1056,7 @@ class App extends Object {
* Returns a prefix or suffix needed for loading files.
*
* @param string $type type of object
* @param string $plugin name of plugin
* @param string $plugin camelized name of plugin
* @param boolean $parent false will not attempt to load parent
* @return array
* @access private
@ -1048,8 +1067,7 @@ class App extends Object {
}
if ($plugin) {
$plugin = Inflector::underscore($plugin);
$name = Inflector::camelize($plugin);
$pluginPath = Inflector::underscore($plugin);
}
$path = null;
$load = strtolower($type);
@ -1057,42 +1075,42 @@ class App extends Object {
switch ($load) {
case 'model':
if (!class_exists('Model')) {
App::import('Core', 'Model', false, Configure::corePaths('model'));
App::import('Core', 'Model', false, App::core('models'));
}
if (!class_exists('AppModel')) {
App::import($type, 'AppModel', false, Configure::read('modelPaths'));
App::import($type, 'AppModel', false, App::path('models'));
}
if ($plugin) {
if (!class_exists($name . 'AppModel')) {
App::import($type, $plugin . '.' . $name . 'AppModel', false, array(), $plugin . DS . $plugin . '_app_model.php');
if (!class_exists($plugin . 'AppModel')) {
App::import($type, $plugin . '.' . $plugin . 'AppModel', false, array(), $pluginPath . DS . $pluginPath . '_app_model.php');
}
$path = $plugin . DS . 'models' . DS;
$path = $pluginPath . DS . 'models' . DS;
}
return array('class' => null, 'suffix' => null, 'path' => $path);
break;
case 'behavior':
if ($plugin) {
$path = $plugin . DS . 'models' . DS . 'behaviors' . DS;
$path = $pluginPath . DS . 'models' . DS . 'behaviors' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
case 'controller':
App::import($type, 'AppController', false);
if ($plugin) {
App::import($type, $plugin . '.' . $name . 'AppController', false, array(), $plugin . DS . $plugin . '_app_controller.php');
$path = $plugin . DS . 'controllers' . DS;
App::import($type, $plugin . '.' . $plugin . 'AppController', false, array(), $pluginPath . DS . $pluginPath . '_app_controller.php');
$path = $pluginPath . DS . 'controllers' . DS;
}
return array('class' => $type, 'suffix' => $type, 'path' => $path);
break;
case 'component':
if ($plugin) {
$path = $plugin . DS . 'controllers' . DS . 'components' . DS;
$path = $pluginPath . DS . 'controllers' . DS . 'components' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
case 'view':
if ($plugin) {
$path = $plugin . DS . 'views' . DS;
$path = $pluginPath . DS . 'views' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
@ -1101,13 +1119,13 @@ class App extends Object {
App::import($type, 'AppHelper', false);
}
if ($plugin) {
$path = $plugin . DS . 'views' . DS . 'helpers' . DS;
$path = $pluginPath . DS . 'views' . DS . 'helpers' . DS;
}
return array('class' => $type, 'suffix' => null, 'path' => $path);
break;
case 'vendor':
if ($plugin) {
$path = $plugin . DS . 'vendors' . DS;
$path = $pluginPath . DS . 'vendors' . DS;
}
return array('class' => null, 'suffix' => null, 'path' => $path);
break;
@ -1128,7 +1146,7 @@ class App extends Object {
$type = strtolower($type);
if ($type === 'core') {
$path = Configure::corePaths();
$path = App::core();
$paths = array();
foreach ($path as $key => $value) {
@ -1139,8 +1157,7 @@ class App extends Object {
}
return $paths;
}
if ($paths = Configure::read($type . 'Paths')) {
if ($paths = App::path($type .'s')) {
return $paths;
}
@ -1162,18 +1179,49 @@ class App extends Object {
*
* @param string $name name of object
* @param string $type type of object
* @param string $plugin name of plugin
* @param string $plugin camelized name of plugin
* @return void
* @access private
*/
function __remove($name, $type, $plugin) {
if ($plugin) {
$plugin = Inflector::camelize($plugin);
unset($this->__map['Plugin'][$plugin][$type][$name]);
} else {
unset($this->__map[$type][$name]);
}
}
/**
* Returns an array of filenames of PHP files in the given directory.
*
* @param string $path Path to scan for files
* @param string $suffix if false, return only directories. if string, match and return files
* @return array List of directories or files in directory
*/
function __list($path, $suffix = false, $extension = false) {
if (!class_exists('Folder')) {
require LIBS . 'folder.php';
}
$items = array();
$Folder =& new Folder($path);
$contents = $Folder->read(false, true);
if (is_array($contents)) {
if (!$suffix) {
return $contents[0];
} else {
foreach ($contents[1] as $item) {
if (substr($item, - strlen($suffix)) === $suffix) {
if ($extension) {
$items[] = $item;
} else {
$items[] = substr($item, 0, strlen($item) - strlen($suffix));
}
}
}
}
}
return $items;
}
/**
* Object destructor.
*
@ -1184,7 +1232,7 @@ class App extends Object {
*/
function __destruct() {
if ($this->__cache) {
$core = Configure::corePaths('cake');
$core = App::core('cake');
unset($this->__paths[rtrim($core[0], DS)]);
Cache::write('dir_map', array_filter($this->__paths), '_cake_core_');
Cache::write('file_map', array_filter($this->__map), '_cake_core_');

View file

@ -263,6 +263,9 @@ class AuthComponent extends Object {
*/
function startup(&$controller) {
$methods = array_flip($controller->methods);
$action = strtolower($controller->params['action']);
$allowedActions = array_map('strtolower', $this->allowedActions);
$isErrorOrTests = (
strtolower($controller->name) == 'cakeerror' ||
(strtolower($controller->name) == 'tests' && Configure::read() > 0)
@ -273,7 +276,7 @@ class AuthComponent extends Object {
$isMissingAction = (
$controller->scaffold === false &&
!isset($methods[strtolower($controller->params['action'])])
!isset($methods[$action])
);
if ($isMissingAction) {
@ -295,7 +298,7 @@ class AuthComponent extends Object {
$isAllowed = (
$this->allowedActions == array('*') ||
in_array($controller->params['action'], $this->allowedActions)
in_array($action, $allowedActions)
);
if ($loginAction != $url && $isAllowed) {
@ -337,6 +340,11 @@ class AuthComponent extends Object {
if (!$this->user()) {
if (!$this->RequestHandler->isAjax()) {
$this->Session->setFlash($this->authError, 'default', array(), 'auth');
if (!empty($controller->params['url']) && count($controller->params['url']) >= 2) {
$query = $controller->params['url'];
unset($query['url'], $query['ext']);
$url .= Router::queryString($query, array());
}
$this->Session->write('Auth.redirect', $url);
$controller->redirect($loginAction);
return false;

View file

@ -345,6 +345,7 @@ class EmailComponent extends Object{
$this->bcc = array();
$this->subject = null;
$this->additionalParams = null;
$this->smtpError = null;
$this->__header = array();
$this->__boundary = null;
$this->__message = array();
@ -631,7 +632,9 @@ class EmailComponent extends Object{
* @access private
*/
function __strip($value, $message = false) {
$search = '%0a|%0d|Content-(?:Type|Transfer-Encoding)\:|charset\=|mime-version\:|multipart/mixed|(?:to|b?cc)\:.*';
$search = '%0a|%0d|Content-(?:Type|Transfer-Encoding)\:';
$search .= '|charset\=|mime-version\:|multipart/mixed|(?:[^a-z]to|b?cc)\:.*';
if ($message !== true) {
$search .= '|\r|\n';
}
@ -662,7 +665,7 @@ class EmailComponent extends Object{
* @access private
*/
function __smtp() {
App::import('Core', array('Socket'));
App::import('Core', array('CakeSocket'));
$this->__smtpConnection =& new CakeSocket(array_merge(array('protocol'=>'smtp'), $this->smtpOptions));
@ -673,7 +676,13 @@ class EmailComponent extends Object{
return false;
}
if (!$this->__smtpSend('HELO cake', '250')) {
if (isset($this->smtpOptions['client'])) {
$host = $this->smtpOptions['client'];
} else {
$host = env('HTTP_HOST');
}
if (!$this->__smtpSend("HELO {$host}", '250')) {
return false;
}

View file

@ -524,6 +524,7 @@ class RequestHandlerComponent extends Object {
return $this->ext;
}
$types = $type;
if (is_string($type)) {
$types = array($type);
}
@ -550,7 +551,11 @@ class RequestHandlerComponent extends Object {
return $accepts[0];
}
$accepts = array_intersect($this->__acceptTypes, $accepts);
$acceptedTypes = array();
foreach ($this->__acceptTypes as $type) {
$acceptedTypes[] = $this->mapType($type);
}
$accepts = array_intersect($acceptedTypes, $accepts);
return $accepts[0];
}
/**

View file

@ -25,7 +25,7 @@
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
if (!class_exists('cakesession')) {
require LIBS . 'session.php';
require LIBS . 'cake_session.php';
}
/**
* Session Component.

View file

@ -1,26 +1,21 @@
<?php
/* SVN FILE: $Id$ */
/**
* Base controller class.
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.cake.libs.controller
* @since CakePHP(tm) v 0.2.9
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Include files
@ -55,7 +50,7 @@ class Controller extends Object {
*/
var $here = null;
/**
* The webroot of the application. Helpful if your application is placed in a folder under the current domain name.
* The webroot of the application.
*
* @var string
* @access public
@ -292,7 +287,7 @@ class Controller extends Object {
*/
var $methods = array();
/**
* This controller's primary model class name, the Inflector::classify()'ed version of
* This controller's primary model class name, the Inflector::classify()'ed version of
* the controller's $name property.
*
* Example: For a controller named 'Comments', the modelClass would be 'Comment'
@ -325,7 +320,8 @@ class Controller extends Object {
if ($this->name === null) {
$r = null;
if (!preg_match('/(.*)Controller/i', get_class($this), $r)) {
die (__("Controller::__construct() : Can not get or parse my own class name, exiting."));
__("Controller::__construct() : Can not get or parse my own class name, exiting.");
$this->_stop();
}
$this->name = $r[1];
}
@ -393,9 +389,13 @@ class Controller extends Object {
if ($var === 'components') {
$normal = Set::normalize($this->{$var});
$app = Set::normalize($appVars[$var]);
$this->{$var} = Set::merge($normal, $app);
if ($app !== $normal) {
$this->{$var} = Set::merge($app, $normal);
}
} else {
$this->{$var} = Set::merge($this->{$var}, array_diff($appVars[$var], $this->{$var}));
$this->{$var} = Set::merge(
$this->{$var}, array_diff($appVars[$var], $this->{$var})
);
}
}
}
@ -415,9 +415,13 @@ class Controller extends Object {
if ($var === 'components') {
$normal = Set::normalize($this->{$var});
$app = Set::normalize($appVars[$var]);
$this->{$var} = Set::merge($normal, array_diff_assoc($app, $normal));
if ($app !== $normal) {
$this->{$var} = Set::merge($app, $normal);
}
} else {
$this->{$var} = Set::merge($this->{$var}, array_diff($appVars[$var], $this->{$var}));
$this->{$var} = Set::merge(
$this->{$var}, array_diff($appVars[$var], $this->{$var})
);
}
}
}
@ -462,7 +466,7 @@ class Controller extends Object {
}
/**
* Loads and instantiates models required by this controller.
* If Controller::persistModel; is true, controller will create cached model instances on first request,
* If Controller::persistModel; is true, controller will cache model instances on first request,
* additional request will used cached models.
* If the model is non existent, it will throw a missing database table error, as Cake generates
* dynamic models for the time being.
@ -498,13 +502,19 @@ class Controller extends Object {
$this->modelNames[] = $modelClass;
if (!PHP5) {
$this->{$modelClass} =& ClassRegistry::init(array('class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id));
$this->{$modelClass} =& ClassRegistry::init(array(
'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
));
} else {
$this->{$modelClass} = ClassRegistry::init(array('class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id));
$this->{$modelClass} = ClassRegistry::init(array(
'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
));
}
if (!$this->{$modelClass}) {
return $this->cakeError('missingModel', array(array('className' => $modelClass, 'webroot' => '', 'base' => $this->base)));
return $this->cakeError('missingModel', array(array(
'className' => $modelClass, 'webroot' => '', 'base' => $this->base
)));
}
if ($this->persistModel === true) {
@ -522,7 +532,8 @@ class Controller extends Object {
* Redirects to given $url, after turning off $this->autoRender.
* Script execution is halted after the redirect.
*
* @param mixed $url A string or array-based URL pointing to another location within the app, or an absolute URL
* @param mixed $url A string or array-based URL pointing to another location within the app,
* or an absolute URL
* @param integer $status Optional HTTP status code (eg: 404)
* @param boolean $exit If true, exit() will be called after the redirect
* @return mixed void if $exit = false. Terminates script if $exit = true
@ -689,14 +700,17 @@ class Controller extends Object {
return call_user_func_array(array(&$this, $action), $args);
}
/**
* Controller callback to tie into Auth component. Only called when AuthComponent::authorize is set to 'controller'.
* Controller callback to tie into Auth component.
* Only called when AuthComponent::authorize is set to 'controller'.
*
* @return bool true if authorized, false otherwise
* @access public
* @link http://book.cakephp.org/view/396/authorize
*/
function isAuthorized() {
trigger_error(sprintf(__('%s::isAuthorized() is not defined.', true), $this->name), E_USER_WARNING);
trigger_error(sprintf(
__('%s::isAuthorized() is not defined.', true), $this->name
), E_USER_WARNING);
return false;
}
/**
@ -776,8 +790,13 @@ class Controller extends Object {
if (isset($this->$currentModel) && is_a($this->$currentModel, 'Model')) {
$models[] = Inflector::underscore($currentModel);
}
if (isset($this->$currentModel) && is_a($this->$currentModel, 'Model') && !empty($this->$currentModel->validationErrors)) {
$View->validationErrors[Inflector::camelize($currentModel)] =& $this->$currentModel->validationErrors;
$isValidModel = (
isset($this->$currentModel) && is_a($this->$currentModel, 'Model') &&
!empty($this->$currentModel->validationErrors)
);
if ($isValidModel) {
$View->validationErrors[Inflector::camelize($currentModel)] =&
$this->$currentModel->validationErrors;
}
}
$models = array_diff(ClassRegistry::keys(), $models);
@ -785,7 +804,8 @@ class Controller extends Object {
if (ClassRegistry::isKeySet($currentModel)) {
$currentObject =& ClassRegistry::getObject($currentModel);
if (is_a($currentObject, 'Model') && !empty($currentObject->validationErrors)) {
$View->validationErrors[Inflector::camelize($currentModel)] =& $currentObject->validationErrors;
$View->validationErrors[Inflector::camelize($currentModel)] =&
$currentObject->validationErrors;
}
}
}
@ -821,7 +841,8 @@ class Controller extends Object {
}
if ($default != null) {
return $default;
$url = Router::url($default, true);
return $url;
}
return '/';
}
@ -863,9 +884,11 @@ class Controller extends Object {
* Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call.
*
* @param array $data POST'ed data organized by model and field
* @param mixed $op A string containing an SQL comparison operator, or an array matching operators to fields
* @param mixed $op A string containing an SQL comparison operator, or an array matching operators
* to fields
* @param string $bool SQL boolean operator: AND, OR, XOR, etc.
* @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be included in the returned conditions
* @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be
* included in the returned conditions
* @return array An array of model conditions
* @access public
* @link http://book.cakephp.org/view/432/postConditions
@ -940,11 +963,16 @@ class Controller extends Object {
if ($assoc && isset($this->{$object}->{$assoc})) {
$object = $this->{$object}->{$assoc};
} elseif ($assoc && isset($this->{$this->modelClass}) && isset($this->{$this->modelClass}->{$assoc})) {
} elseif (
$assoc && isset($this->{$this->modelClass}) &&
isset($this->{$this->modelClass}->{$assoc}
)) {
$object = $this->{$this->modelClass}->{$assoc};
} elseif (isset($this->{$object})) {
$object = $this->{$object};
} elseif (isset($this->{$this->modelClass}) && isset($this->{$this->modelClass}->{$object})) {
} elseif (
isset($this->{$this->modelClass}) && isset($this->{$this->modelClass}->{$object}
)) {
$object = $this->{$this->modelClass}->{$object};
}
} elseif (empty($object) || $object === null) {
@ -965,7 +993,11 @@ class Controller extends Object {
}
if (!is_object($object)) {
trigger_error(sprintf(__('Controller::paginate() - can\'t find model %1$s in controller %2$sController', true), $object, $this->name), E_USER_WARNING);
trigger_error(sprintf(
__('Controller::paginate() - can\'t find model %1$s in controller %2$sController',
true
), $object, $this->name
), E_USER_WARNING);
return array();
}
$options = array_merge($this->params, $this->params['url'], $this->passedArgs);
@ -1026,6 +1058,14 @@ class Controller extends Object {
if (!isset($defaults['conditions'])) {
$defaults['conditions'] = array();
}
$type = 'all';
if (isset($defaults[0])) {
$type = $defaults[0];
unset($defaults[0]);
}
extract($options = array_merge(array('page' => 1, 'limit' => 20), $defaults, $options));
if (is_array($scope) && !empty($scope)) {
@ -1036,12 +1076,7 @@ class Controller extends Object {
if ($recursive === null) {
$recursive = $object->recursive;
}
$type = 'all';
if (isset($defaults[0])) {
$type = $defaults[0];
unset($defaults[0]);
}
$extra = array_diff_key($defaults, compact(
'conditions', 'fields', 'order', 'limit', 'page', 'recursive'
));
@ -1068,7 +1103,9 @@ class Controller extends Object {
$page = $options['page'] = (integer)$page;
if (method_exists($object, 'paginate')) {
$results = $object->paginate($conditions, $fields, $order, $limit, $page, $recursive, $extra);
$results = $object->paginate(
$conditions, $fields, $order, $limit, $page, $recursive, $extra
);
} else {
$parameters = compact('conditions', 'fields', 'order', 'limit', 'page');
if ($recursive != $object->recursive) {
@ -1164,4 +1201,4 @@ class Controller extends Object {
return false;
}
}
?>
?>

View file

@ -1,5 +1,4 @@
<?php
/* SVN FILE: $Id$ */
/**
* Scaffold.
*
@ -7,25 +6,21 @@
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.cake.libs.controller
* @since Cake v 0.10.0.1076
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Scaffolding is a set of automatic views, forms and controllers for starting web development work faster.
* Scaffolding is a set of automatic actions for starting web development work faster.
*
* Scaffold inspects your database tables, and making educated guesses, sets up a
* number of pages for each of your Models. These pages have data forms that work,
@ -113,13 +108,23 @@ class Scaffold extends Object {
* @access public
*/
var $plugin = null;
/**
* valid session.
*
* @var boolean
* @access public
*/
var $_validSession = null;
/**
* List of variables to collect from the associated controller
*
* @var array
* @access private
*/
var $__passedVars = array('action', 'base', 'webroot', 'layout', 'name', 'viewPath', 'ext', 'params', 'data', 'plugin', 'cacheAction');
var $__passedVars = array(
'action', 'base', 'webroot', 'layout', 'name',
'viewPath', 'ext', 'params', 'data', 'plugin', 'cacheAction'
);
/**
* Title HTML element for current scaffolded view
*
@ -148,31 +153,38 @@ class Scaffold extends Object {
$this->modelKey = $controller->modelKey;
if (!is_object($this->controller->{$this->modelClass})) {
return $this->cakeError('missingModel', array(array('className' => $this->modelClass, 'webroot' => '', 'base' => $controller->base)));
return $this->cakeError('missingModel', array(array(
'className' => $this->modelClass, 'webroot' => '', 'base' => $controller->base
)));
}
$this->ScaffoldModel =& $this->controller->{$this->modelClass};
$this->scaffoldTitle = Inflector::humanize($this->viewPath);
$this->scaffoldActions = $controller->scaffold;
$this->controller->pageTitle = __('Scaffold :: ', true) . Inflector::humanize($this->action) . ' :: ' . $this->scaffoldTitle;
$this->controller->pageTitle = __('Scaffold :: ', true)
. Inflector::humanize($this->action) . ' :: ' . $this->scaffoldTitle;
$modelClass = $this->controller->modelClass;
$primaryKey = $this->ScaffoldModel->primaryKey;
$displayField = $this->ScaffoldModel->displayField;
$singularVar = Inflector::variable($modelClass);
$pluralVar = Inflector::variable($this->controller->name);
$singularHumanName = Inflector::humanize($modelClass);
$pluralHumanName = Inflector::humanize($this->controller->name);
$singularHumanName = Inflector::humanize(Inflector::underscore($modelClass));
$pluralHumanName = Inflector::humanize(Inflector::underscore($this->controller->name));
$scaffoldFields = array_keys($this->ScaffoldModel->schema());
$associations = $this->__associations();
$this->controller->set(compact('modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
'singularHumanName', 'pluralHumanName', 'scaffoldFields', 'associations'));
$this->controller->set(compact(
'modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
'singularHumanName', 'pluralHumanName', 'scaffoldFields', 'associations'
));
if ($this->controller->view && $this->controller->view !== 'Theme') {
$this->controller->view = 'scaffold';
}
$this->__scaffold($params);
$this->_validSession = (
isset($this->controller->Session) && $this->controller->Session->valid() != false
);
}
/**
* Outputs the content of a scaffold method passing it through the Controller::afterFilter()
@ -196,16 +208,23 @@ class Scaffold extends Object {
if (isset($params['pass'][0])) {
$this->ScaffoldModel->id = $params['pass'][0];
} elseif (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
$this->controller->Session->setFlash(sprintf(__("No id set for %s::view()", true), Inflector::humanize($this->modelKey)));
} elseif ($this->_validSession) {
$this->controller->Session->setFlash(sprintf(
__("No id set for %s::view()", true),
Inflector::humanize($this->modelKey
)));
$this->controller->redirect($this->redirect);
} else {
return $this->controller->flash(sprintf(__("No id set for %s::view()", true), Inflector::humanize($this->modelKey)),
'/' . Inflector::underscore($this->controller->viewPath));
return $this->controller->flash(sprintf(
__("No id set for %s::view()", true), Inflector::humanize($this->modelKey)),
'/' . Inflector::underscore($this->controller->viewPath
));
}
$this->ScaffoldModel->recursive = 1;
$this->controller->data = $this->ScaffoldModel->read();
$this->controller->set(Inflector::variable($this->controller->modelClass), $this->controller->data);
$this->controller->set(
Inflector::variable($this->controller->modelClass), $this->controller->data
);
$this->controller->render($this->action, $this->layout);
$this->_output();
} elseif ($this->controller->_scaffoldError('view') === false) {
@ -222,7 +241,9 @@ class Scaffold extends Object {
function __scaffoldIndex($params) {
if ($this->controller->_beforeScaffold('index')) {
$this->ScaffoldModel->recursive = 0;
$this->controller->set(Inflector::variable($this->controller->name), $this->controller->paginate());
$this->controller->set(
Inflector::variable($this->controller->name), $this->controller->paginate()
);
$this->controller->render($this->action, $this->layout);
$this->_output();
} elseif ($this->controller->_scaffoldError('index') === false) {
@ -263,11 +284,17 @@ class Scaffold extends Object {
}
if (!$this->ScaffoldModel->exists()) {
if (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
$this->controller->Session->setFlash(sprintf(__("Invalid id for %s::edit()", true), Inflector::humanize($this->modelKey)));
if ($this->_validSession) {
$this->controller->Session->setFlash(sprintf(
__("Invalid id for %s::edit()", true),
Inflector::humanize($this->modelKey)
));
$this->controller->redirect($this->redirect);
} else {
return $this->controller->flash(sprintf(__("Invalid id for %s::edit()", true), Inflector::humanize($this->modelKey)), $this->redirect);
return $this->controller->flash(sprintf(
__("Invalid id for %s::edit()", true),
Inflector::humanize($this->modelKey)
), $this->redirect);
}
}
}
@ -279,18 +306,26 @@ class Scaffold extends Object {
if ($this->ScaffoldModel->save($this->controller->data)) {
if ($this->controller->_afterScaffoldSave($action)) {
if (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
$this->controller->Session->setFlash(sprintf(__('The %1$s has been %2$s', true), Inflector::humanize($this->modelClass), $success));
if ($this->_validSession) {
$this->controller->Session->setFlash(sprintf(
__('The %1$s has been %2$s', true),
Inflector::humanize($this->modelClass), $success
));
$this->controller->redirect($this->redirect);
} else {
return $this->controller->flash(sprintf(__('The %1$s has been %2$s', true), Inflector::humanize($this->modelClass), $success), $this->redirect);
return $this->controller->flash(sprintf(
__('The %1$s has been %2$s', true),
Inflector::humanize($this->modelClass), $success
), $this->redirect);
}
} else {
return $this->controller->_afterScaffoldSaveError($action);
}
} else {
if (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
$this->controller->Session->setFlash(__('Please correct errors below.', true));
if ($this->_validSession) {
$this->controller->Session->setFlash(
__('Please correct errors below.', true
));
}
}
}
@ -304,7 +339,9 @@ class Scaffold extends Object {
}
foreach ($this->ScaffoldModel->belongsTo as $assocName => $assocData) {
$varName = Inflector::variable(Inflector::pluralize(preg_replace('/(?:_id)$/', '', $assocData['foreignKey'])));
$varName = Inflector::variable(Inflector::pluralize(
preg_replace('/(?:_id)$/', '', $assocData['foreignKey'])
));
$this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list'));
}
foreach ($this->ScaffoldModel->hasAndBelongsToMany as $assocName => $assocData) {
@ -328,27 +365,42 @@ class Scaffold extends Object {
if ($this->controller->_beforeScaffold('delete')) {
if (isset($params['pass'][0])) {
$id = $params['pass'][0];
} elseif (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
$this->controller->Session->setFlash(sprintf(__("No id set for %s::delete()", true), Inflector::humanize($this->modelKey)));
} elseif ($this->_validSession) {
$this->controller->Session->setFlash(sprintf(
__("No id set for %s::delete()", true), Inflector::humanize($this->modelKey)
));
$this->controller->redirect($this->redirect);
} else {
return $this->controller->flash(sprintf(__("No id set for %s::delete()", true), Inflector::humanize($this->modelKey)),
'/' . Inflector::underscore($this->controller->viewPath));
return $this->controller->flash(sprintf(
__("No id set for %s::delete()", true), Inflector::humanize($this->modelKey)
), '/' . Inflector::underscore($this->controller->viewPath));
}
if ($this->ScaffoldModel->del($id)) {
if (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
$this->controller->Session->setFlash(sprintf(__('The %1$s with id: %2$d has been deleted.', true), Inflector::humanize($this->modelClass), $id));
if ($this->ScaffoldModel->delete($id)) {
if ($this->_validSession) {
$this->controller->Session->setFlash(sprintf(
__('The %1$s with id: %2$d has been deleted.', true),
Inflector::humanize($this->modelClass), $id
));
$this->controller->redirect($this->redirect);
} else {
return $this->controller->flash(sprintf(__('The %1$s with id: %2$d has been deleted.', true), Inflector::humanize($this->modelClass), $id), '/' . $this->viewPath);
return $this->controller->flash(sprintf(
__('The %1$s with id: %2$d has been deleted.', true),
Inflector::humanize($this->modelClass), $id
), '/' . $this->viewPath);
}
} else {
if (isset($this->controller->Session) && $this->controller->Session->valid() != false) {
$this->controller->Session->setFlash(sprintf(__('There was an error deleting the %1$s with id: %2$d', true), Inflector::humanize($this->modelClass), $id));
if ($this->_validSession) {
$this->controller->Session->setFlash(sprintf(
__('There was an error deleting the %1$s with id: %2$d', true),
Inflector::humanize($this->modelClass), $id
));
$this->controller->redirect($this->redirect);
} else {
return $this->controller->flash(sprintf(__('There was an error deleting the %1$s with id: %2$d', true), Inflector::humanize($this->modelClass), $id), '/' . $this->viewPath);
return $this->controller->flash(sprintf(
__('There was an error deleting the %1$s with id: %2$d', true),
Inflector::humanize($this->modelClass), $id
), '/' . $this->viewPath);
}
}
} elseif ($this->controller->_scaffoldError('delete') === false) {
@ -383,9 +435,14 @@ class Scaffold extends Object {
if (isset($db)) {
if (empty($this->scaffoldActions)) {
$this->scaffoldActions = array('index', 'list', 'view', 'add', 'create', 'edit', 'update', 'delete');
$this->scaffoldActions = array(
'index', 'list', 'view', 'add', 'create', 'edit', 'update', 'delete'
);
} elseif (!empty($admin) && $this->scaffoldActions === $admin) {
$this->scaffoldActions = array($admin .'_index', $admin .'_list', $admin .'_view', $admin .'_add', $admin .'_create', $admin .'_edit', $admin .'_update', $admin .'_delete');
$this->scaffoldActions = array(
$admin .'_index', $admin .'_list', $admin .'_view', $admin .'_add',
$admin .'_create', $admin .'_edit', $admin .'_update', $admin .'_delete'
);
}
if (in_array($params['action'], $this->scaffoldActions)) {
@ -419,13 +476,17 @@ class Scaffold extends Object {
break;
}
} else {
return $this->cakeError('missingAction', array(array('className' => $this->controller->name . "Controller",
'base' => $this->controller->base,
'action' => $this->action,
'webroot' => $this->controller->webroot)));
return $this->cakeError('missingAction', array(array(
'className' => $this->controller->name . "Controller",
'base' => $this->controller->base,
'action' => $this->action,
'webroot' => $this->controller->webroot
)));
}
} else {
return $this->cakeError('missingDatabase', array(array('webroot' => $this->controller->webroot)));
return $this->cakeError('missingDatabase', array(array(
'webroot' => $this->controller->webroot
)));
}
}
/**
@ -440,10 +501,17 @@ class Scaffold extends Object {
foreach ($keys as $key => $type) {
foreach ($this->ScaffoldModel->{$type} as $assocKey => $assocData) {
$associations[$type][$assocKey]['primaryKey'] = $this->ScaffoldModel->{$assocKey}->primaryKey;
$associations[$type][$assocKey]['displayField'] = $this->ScaffoldModel->{$assocKey}->displayField;
$associations[$type][$assocKey]['foreignKey'] = $assocData['foreignKey'];
$associations[$type][$assocKey]['controller'] = Inflector::pluralize(Inflector::underscore($assocData['className']));
$associations[$type][$assocKey]['primaryKey'] =
$this->ScaffoldModel->{$assocKey}->primaryKey;
$associations[$type][$assocKey]['displayField'] =
$this->ScaffoldModel->{$assocKey}->displayField;
$associations[$type][$assocKey]['foreignKey'] =
$assocData['foreignKey'];
$associations[$type][$assocKey]['controller'] =
Inflector::pluralize(Inflector::underscore($assocData['className']));
}
}
return $associations;

View file

@ -1,5 +1,4 @@
<?php
/* SVN FILE: $Id$ */
/**
* Framework debugging and PHP error-handling class
*
@ -7,33 +6,34 @@
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 1.2.4560
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Included libraries.
*
*/
if (!class_exists('Object')) {
uses('object');
}
if (!class_exists('CakeLog')) {
uses('cake_log');
}
if (!class_exists('Object')) {
require_once LIBS . 'object.php';
}
if (!class_exists('CakeLog')) {
require_once LIBS . 'cake_log.php';
}
if (!class_exists('String')) {
require_once LIBS . 'string.php';
}
/**
* Provide custom logging and error handling.
*
@ -44,6 +44,7 @@
* @link http://book.cakephp.org/view/460/Using-the-Debugger-Class
*/
class Debugger extends Object {
/**
* A list of errors generated by the application.
*
@ -51,6 +52,7 @@ class Debugger extends Object {
* @access public
*/
var $errors = array();
/**
* Contains the base URL for error code documentation.
*
@ -58,6 +60,7 @@ class Debugger extends Object {
* @access public
*/
var $helpPath = null;
/**
* The current output format.
*
@ -65,26 +68,110 @@ class Debugger extends Object {
* @access protected
*/
var $_outputFormat = 'js';
/**
* Templates used when generating trace or error strings. Can be global or indexed by the format
* value used in $_outputFormat.
*
* @var string
* @access protected
*/
var $_templates = array(
'log' => array(
'trace' => '{:reference} - {:path}, line {:line}',
'error' => "{:error} ({:code}): {:description} in [{:file}, line {:line}]"
),
'js' => array(
'error' => '',
'info' => '',
'trace' => '<pre class="stack-trace">{:trace}</pre>',
'code' => '',
'context' => '',
'links' => array()
),
'html' => array(
'trace' => '<pre class="cake-debug trace"><b>Trace</b> <p>{:trace}</p></pre>',
'context' => '<pre class="cake-debug context"><b>Context</b> <p>{:context}</p></pre>'
),
'txt' => array(
'error' => "{:error}: {:code} :: {:description} on line {:line} of {:path}\n{:info}",
'context' => "Context:\n{:context}\n",
'trace' => "Trace:\n{:trace}\n",
'code' => '',
'info' => ''
),
'base' => array(
'traceLine' => '{:reference} - {:path}, line {:line}'
)
);
/**
* Holds current output data when outputFormat is false.
*
* @var string
* @access private
*/
var $__data = array();
var $_data = array();
/**
* Constructor.
*
*/
function __construct() {
$docRef = ini_get('docref_root');
if (empty($docRef)) {
ini_set('docref_root', 'http://php.net/');
}
if (!defined('E_RECOVERABLE_ERROR')) {
define('E_RECOVERABLE_ERROR', 4096);
}
if (!defined('E_DEPRECATED')) {
define('E_DEPRECATED', 8192);
}
$e = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-trace\')';
$e .= '.style.display = (document.getElementById(\'{:id}-trace\').style.display == ';
$e .= '\'none\' ? \'\' : \'none\');"><b>{:error}</b> ({:code})</a>: {:description} ';
$e .= '[<b>{:path}</b>, line <b>{:line}</b>]';
$e .= '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">';
$e .= '{:links}{:info}</div>';
$this->_templates['js']['error'] = $e;
$t = '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">';
$t .= '{:context}{:code}{:trace}</div>';
$this->_templates['js']['info'] = $t;
$links = array();
$link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-code\')';
$link .= '.style.display = (document.getElementById(\'{:id}-code\').style.display == ';
$link .= '\'none\' ? \'\' : \'none\')">Code</a>';
$links['code'] = $link;
$link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-context\')';
$link .= '.style.display = (document.getElementById(\'{:id}-context\').style.display == ';
$link .= '\'none\' ? \'\' : \'none\')">Context</a>';
$links['context'] = $link;
$links['help'] = '<a href="{:helpPath}{:code}" target="_blank">Help</a>';
$this->_templates['js']['links'] = $links;
$this->_templates['js']['context'] = '<pre id="{:id}-context" class="cake-context" ';
$this->_templates['js']['context'] .= 'style="display: none;">{:context}</pre>';
$this->_templates['js']['code'] = '<div id="{:id}-code" class="cake-code-dump" ';
$this->_templates['js']['code'] .= 'style="display: none;"><pre>{:code}</pre></div>';
$e = '<pre class="cake-debug"><b>{:error}</b> ({:code}) : {:description} ';
$e .= '[<b>{:path}</b>, line <b>{:line}]</b></pre>';
$this->_templates['html']['error'] = $e;
$this->_templates['html']['context'] = '<pre class="cake-debug context"><b>Context</b> ';
$this->_templates['html']['context'] .= '<p>{:context}</p></pre>';
}
/**
* Returns a reference to the Debugger singleton object instance.
*
@ -113,6 +200,7 @@ class Debugger extends Object {
}
return $instance[0];
}
/**
* Formats and outputs the contents of the supplied variable.
*
@ -127,6 +215,7 @@ class Debugger extends Object {
$_this = Debugger::getInstance();
pr($_this->exportVar($var));
}
/**
* Creates a detailed stack trace log at the time of invocation, much like dump()
* but to debug.log.
@ -144,7 +233,8 @@ class Debugger extends Object {
if (is_object($trace[0]['object']) && isset($trace[0]['object']->_reporter->_test_stack)) {
$stack = $trace[0]['object']->_reporter->_test_stack;
$source = "[". $stack[0].", ". $stack[2] ."::" . $stack[3] ."()]\n";
$source = sprintf('[%1$s, %3$s::%2$s()]' . "\n",
array_shift($stack), array_pop($stack), array_pop($stack));
}
CakeLog::write($level, $source . $_this->exportVar($var));
@ -174,7 +264,7 @@ class Debugger extends Object {
if (empty($line)) {
$line = '??';
}
$file = $_this->trimPath($file);
$path = $_this->trimPath($file);
$info = compact('code', 'description', 'file', 'line');
if (!in_array($info, $_this->errors)) {
@ -213,15 +303,20 @@ class Debugger extends Object {
$helpCode = null;
if (!empty($_this->helpPath) && preg_match('/.*\[([0-9]+)\]$/', $description, $codes)) {
if (isset($codes[1])) {
$helpCode = $codes[1];
$helpID = $codes[1];
$description = trim(preg_replace('/\[[0-9]+\]$/', '', $description));
}
}
echo $_this->_output($level, $error, $code, $helpCode, $description, $file, $line, $context);
$data = compact(
'level', 'error', 'code', 'helpID', 'description', 'file', 'path', 'line', 'context'
);
echo $_this->_output($data);
if (Configure::read('log')) {
CakeLog::write($level, "{$error} ({$code}): {$description} in [{$file}, line {$line}]");
$tpl = $_this->_templates['log']['error'];
$options = array('before' => '{:', 'after' => '}');
CakeLog::write($level, String::insert($tpl, $data, $options));
}
if ($error == 'Fatal Error') {
@ -229,6 +324,7 @@ class Debugger extends Object {
}
return true;
}
/**
* Outputs a stack trace based on the supplied options.
*
@ -239,65 +335,66 @@ class Debugger extends Object {
* @link http://book.cakephp.org/view/460/Using-the-Debugger-Class
*/
function trace($options = array()) {
$options = array_merge(array(
'depth' => 999,
'format' => '',
'args' => false,
'start' => 0,
'scope' => null,
'exclude' => null
),
$options
$_this = Debugger::getInstance();
$defaults = array(
'depth' => 999,
'format' => $_this->_outputFormat,
'args' => false,
'start' => 0,
'scope' => null,
'exclude' => null
);
$options += $defaults;
$backtrace = debug_backtrace();
$back = array();
$count = count($backtrace);
$back = array();
$_trace = array(
'line' => '??',
'file' => '[internal]',
'class' => null,
'function' => '[main]'
);
for ($i = $options['start']; $i < $count && $i < $options['depth']; $i++) {
$trace = array_merge(
array(
'file' => '[internal]',
'line' => '??'
),
$backtrace[$i]
);
$trace = array_merge(array('file' => '[internal]', 'line' => '??'), $backtrace[$i]);
if (isset($backtrace[$i + 1])) {
$next = array_merge(
array(
'line' => '??',
'file' => '[internal]',
'class' => null,
'function' => '[main]'
),
$backtrace[$i + 1]
);
$function = $next['function'];
$next = array_merge($_trace, $backtrace[$i + 1]);
$reference = $next['function'];
if (!empty($next['class'])) {
$function = $next['class'] . '::' . $function . '(';
$reference = $next['class'] . '::' . $reference . '(';
if ($options['args'] && isset($next['args'])) {
$args = array();
foreach ($next['args'] as $arg) {
$args[] = Debugger::exportVar($arg);
}
$function .= join(', ', $args);
$reference .= join(', ', $args);
}
$function .= ')';
$reference .= ')';
}
} else {
$function = '[main]';
$reference = '[main]';
}
if (in_array($function, array('call_user_func_array', 'trigger_error'))) {
if (in_array($reference, array('call_user_func_array', 'trigger_error'))) {
continue;
}
if ($options['format'] == 'points' && $trace['file'] != '[internal]') {
$back[] = array('file' => $trace['file'], 'line' => $trace['line']);
} elseif (empty($options['format'])) {
$back[] = $function . ' - ' . Debugger::trimPath($trace['file']) . ', line ' . $trace['line'];
} else {
} elseif ($options['format'] == 'array') {
$back[] = $trace;
} else {
if (isset($_this->_templates[$options['format']]['traceLine'])) {
$tpl = $_this->_templates[$options['format']]['traceLine'];
} else {
$tpl = $_this->_templates['base']['traceLine'];
}
$trace['path'] = Debugger::trimPath($trace['file']);
$trace['reference'] = $reference;
unset($trace['object'], $trace['args']);
$back[] = String::insert($tpl, $trace, array('before' => '{:', 'after' => '}'));
}
}
@ -306,6 +403,7 @@ class Debugger extends Object {
}
return join("\n", $back);
}
/**
* Shortens file paths by replacing the application base path with 'APP', and the CakePHP core
* path with 'CORE'.
@ -335,6 +433,7 @@ class Debugger extends Object {
}
return $path;
}
/**
* Grabs an excerpt from a file and highlights a given line of code
*
@ -369,6 +468,7 @@ class Debugger extends Object {
}
return $lines;
}
/**
* Converts a variable to a string for debug output.
*
@ -423,6 +523,7 @@ class Debugger extends Object {
break;
}
}
/**
* Handles object to string conversion.
*
@ -453,98 +554,122 @@ class Debugger extends Object {
}
return join("\n", $out);
}
/**
* Handles object conversion to debug string.
* Switches output format, updates format strings
*
* @param string $var Object to convert
* @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for
* straight HTML output, or 'text' for unformatted text.
* @access protected
*/
function output($format = 'js') {
function output($format = null, $strings = array()) {
$_this = Debugger::getInstance();
$data = null;
if ($format === true && !empty($_this->__data)) {
$data = $_this->__data;
$_this->__data = array();
if (is_null($format)) {
return $_this->_outputFormat;
}
if (!empty($strings)) {
if (isset($_this->_templates[$format])) {
if (isset($strings['links'])) {
$_this->_templates[$format]['links'] = array_merge(
$_this->_templates[$format]['links'],
$strings['links']
);
unset($strings['links']);
}
$_this->_templates[$format] = array_merge($_this->_templates[$format], $strings);
} else {
$_this->_templates[$format] = $strings;
}
return $_this->_templates[$format];
}
if ($format === true && !empty($_this->_data)) {
$data = $_this->_data;
$_this->_data = array();
$format = false;
}
$_this->_outputFormat = $format;
return $data;
}
/**
* Handles object conversion to debug string.
* Renders error messages
*
* @param string $var Object to convert
* @param array $data Data about the current error
* @access private
*/
function _output($level, $error, $code, $helpCode, $description, $file, $line, $kontext) {
$files = $this->trace(array('start' => 2, 'format' => 'points'));
$listing = $this->excerpt($files[0]['file'], $files[0]['line'] - 1, 1);
$trace = $this->trace(array('start' => 2, 'depth' => '20'));
$context = array();
function _output($data = array()) {
$defaults = array(
'level' => 0,
'error' => 0,
'code' => 0,
'helpID' => null,
'description' => '',
'file' => '',
'line' => 0,
'context' => array()
);
$data += $defaults;
foreach ((array)$kontext as $var => $value) {
$files = $this->trace(array('start' => 2, 'format' => 'points'));
$code = $this->excerpt($files[0]['file'], $files[0]['line'] - 1, 1);
$trace = $this->trace(array('start' => 2, 'depth' => '20'));
$insertOpts = array('before' => '{:', 'after' => '}');
$context = array();
$links = array();
$info = '';
foreach ((array)$data['context'] as $var => $value) {
$context[] = "\${$var}\t=\t" . $this->exportVar($value, 1);
}
switch ($this->_outputFormat) {
default:
case 'js':
$link = "document.getElementById(\"CakeStackTrace" . count($this->errors) . "\").style.display = (document.getElementById(\"CakeStackTrace" . count($this->errors) . "\").style.display == \"none\" ? \"\" : \"none\")";
$out = "<a href='javascript:void(0);' onclick='{$link}'><b>{$error}</b> ({$code})</a>: {$description} [<b>{$file}</b>, line <b>{$line}</b>]";
if (Configure::read() > 0) {
debug($out, false, false);
echo '<div id="CakeStackTrace' . count($this->errors) . '" class="cake-stack-trace" style="display: none;">';
$link = "document.getElementById(\"CakeErrorCode" . count($this->errors) . "\").style.display = (document.getElementById(\"CakeErrorCode" . count($this->errors) . "\").style.display == \"none\" ? \"\" : \"none\")";
echo "<a href='javascript:void(0);' onclick='{$link}'>Code</a>";
if (!empty($context)) {
$link = "document.getElementById(\"CakeErrorContext" . count($this->errors) . "\").style.display = (document.getElementById(\"CakeErrorContext" . count($this->errors) . "\").style.display == \"none\" ? \"\" : \"none\")";
echo " | <a href='javascript:void(0);' onclick='{$link}'>Context</a>";
if (!empty($helpCode)) {
echo " | <a href='{$this->helpPath}{$helpCode}' target='_blank'>Help</a>";
}
echo "<pre id=\"CakeErrorContext" . count($this->errors) . "\" class=\"cake-context\" style=\"display: none;\">";
echo implode("\n", $context);
echo "</pre>";
}
if (!empty($listing)) {
echo "<div id=\"CakeErrorCode" . count($this->errors) . "\" class=\"cake-code-dump\" style=\"display: none;\">";
pr(implode("\n", $listing) . "\n", false);
echo '</div>';
}
pr($trace, false);
echo '</div>';
}
break;
case 'html':
echo "<pre class=\"cake-debug\"><b>{$error}</b> ({$code}) : {$description} [<b>{$file}</b>, line <b>{$line}]</b></pre>";
if (!empty($context)) {
echo "Context:\n" .implode("\n", $context) . "\n";
}
echo "<pre class=\"cake-debug context\"><b>Context</b> <p>" . implode("\n", $context) . "</p></pre>";
echo "<pre class=\"cake-debug trace\"><b>Trace</b> <p>" . $trace. "</p></pre>";
break;
case 'text':
case 'txt':
echo "{$error}: {$code} :: {$description} on line {$line} of {$file}\n";
if (!empty($context)) {
echo "Context:\n" .implode("\n", $context) . "\n";
}
echo "Trace:\n" . $trace;
break;
case 'log':
$this->log(compact('error', 'code', 'description', 'line', 'file', 'context', 'trace'));
break;
case false:
$this->__data[] = compact('error', 'code', 'description', 'line', 'file', 'context', 'trace');
break;
$this->_data[] = compact('context', 'trace') + $data;
return;
case 'log':
$this->log(compact('context', 'trace') + $data);
return;
}
if (empty($this->_outputFormat) || !isset($this->_templates[$this->_outputFormat])) {
$this->_outputFormat = 'js';
}
$data['id'] = 'cakeErr' . count($this->errors);
$tpl = array_merge($this->_templates['base'], $this->_templates[$this->_outputFormat]);
$insert = array('context' => join("\n", $context), 'helpPath' => $this->helpPath) + $data;
$detect = array('help' => 'helpID', 'context' => 'context');
if (isset($tpl['links'])) {
foreach ($tpl['links'] as $key => $val) {
if (isset($detect[$key]) && empty($insert[$detect[$key]])) {
continue;
}
$links[$key] = String::insert($val, $insert, $insertOpts);
}
}
foreach (array('code', 'context', 'trace') as $key) {
if (empty($$key) || !isset($tpl[$key])) {
continue;
}
if (is_array($$key)) {
$$key = join("\n", $$key);
}
$info .= String::insert($tpl[$key], compact($key) + $insert, $insertOpts);
}
$links = join(' | ', $links);
unset($data['context']);
echo String::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts);
}
/**
* Verifies that the application's salt value has been changed from the default value.
*
@ -556,9 +681,10 @@ class Debugger extends Object {
trigger_error(__('Please change the value of \'Security.salt\' in app/config/core.php to a salt value specific to your application', true), E_USER_NOTICE);
}
}
/**
* Invokes the given debugger object as the current error handler, taking over control from the previous handler
* in a stack-like hierarchy.
* Invokes the given debugger object as the current error handler, taking over control from the
* previous handler in a stack-like hierarchy.
*
* @param object $debugger A reference to the Debugger object
* @access public
@ -573,4 +699,5 @@ class Debugger extends Object {
if (!defined('DISABLE_DEFAULT_ERROR_HANDLING')) {
Debugger::invoke(Debugger::getInstance());
}
?>

View file

@ -366,12 +366,13 @@ class File extends Object {
function md5($maxsize = 5) {
if ($maxsize === true) {
return md5_file($this->path);
} else {
$size = $this->size();
if ($size && $size < ($maxsize * 1024) * 1024) {
return md5_file($this->path);
}
}
$size = $this->size();
if ($size && $size < ($maxsize * 1024) * 1024) {
return md5_file($this->path);
}
return false;
}
/**

View file

@ -22,7 +22,7 @@
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
App::import('Core', array('Socket', 'Set', 'Router'));
App::import('Core', array('CakeSocket', 'Set', 'Router'));
/**
* Cake network socket connection class.
*
@ -40,7 +40,8 @@ class HttpSocket extends CakeSocket {
*/
var $description = 'HTTP-based DataSource Interface';
/**
* When one activates the $quirksMode by setting it to true, all checks meant to enforce RFC 2616 (HTTP/1.1 specs)
* When one activates the $quirksMode by setting it to true, all checks meant to
* enforce RFC 2616 (HTTP/1.1 specs).
* will be disabled and additional measures to deal with non-standard responses will be enabled.
*
* @var boolean
@ -143,10 +144,10 @@ class HttpSocket extends CakeSocket {
*/
function __construct($config = array()) {
if (is_string($config)) {
$this->configUri($config);
$this->_configUri($config);
} elseif (is_array($config)) {
if (isset($config['request']['uri']) && is_string($config['request']['uri'])) {
$this->configUri($config['request']['uri']);
$this->_configUri($config['request']['uri']);
unset($config['request']['uri']);
}
$this->config = Set::merge($this->config, $config);
@ -172,7 +173,7 @@ class HttpSocket extends CakeSocket {
if (!isset($request['uri'])) {
$request['uri'] = null;
}
$uri = $this->parseUri($request['uri']);
$uri = $this->_parseUri($request['uri']);
if (!isset($uri['host'])) {
$host = $this->config['host'];
@ -183,10 +184,10 @@ class HttpSocket extends CakeSocket {
}
$request['uri'] = $this->url($request['uri']);
$request['uri'] = $this->parseUri($request['uri'], true);
$request['uri'] = $this->_parseUri($request['uri'], true);
$this->request = Set::merge($this->request, $this->config['request'], $request);
$this->configUri($this->request['uri']);
$this->_configUri($this->request['uri']);
if (isset($host)) {
$this->config['host'] = $host;
@ -194,7 +195,7 @@ class HttpSocket extends CakeSocket {
$cookies = null;
if (is_array($this->request['header'])) {
$this->request['header'] = $this->parseHeader($this->request['header']);
$this->request['header'] = $this->_parseHeader($this->request['header']);
if (!empty($this->request['cookies'])) {
$cookies = $this->buildCookies($this->request['cookies']);
}
@ -209,7 +210,7 @@ class HttpSocket extends CakeSocket {
}
if (is_array($this->request['body'])) {
$this->request['body'] = $this->httpSerialize($this->request['body']);
$this->request['body'] = $this->_httpSerialize($this->request['body']);
}
if (!empty($this->request['body']) && !isset($this->request['header']['Content-Type'])) {
@ -221,10 +222,10 @@ class HttpSocket extends CakeSocket {
}
$connectionType = @$this->request['header']['Connection'];
$this->request['header'] = $this->buildHeader($this->request['header']).$cookies;
$this->request['header'] = $this->_buildHeader($this->request['header']).$cookies;
if (empty($this->request['line'])) {
$this->request['line'] = $this->buildRequestLine($this->request);
$this->request['line'] = $this->_buildRequestLine($this->request);
}
if ($this->quirksMode === false && $this->request['line'] === false) {
@ -252,7 +253,7 @@ class HttpSocket extends CakeSocket {
$this->disconnect();
}
$this->response = $this->parseResponse($response);
$this->response = $this->_parseResponse($response);
if (!empty($this->response['cookies'])) {
$this->config['request']['cookies'] = array_merge($this->config['request']['cookies'], $this->response['cookies']);
}
@ -262,7 +263,7 @@ class HttpSocket extends CakeSocket {
/**
* Issues a GET request to the specified URI, query, and request.
*
* @param mixed $uri URI to request (see {@link parseUri()})
* @param mixed $uri URI to request (see {@link _parseUri()})
* @param array $query Query to append to URI
* @param array $request An indexed array with indexes such as 'method' or uri
* @return mixed Result of request
@ -270,13 +271,13 @@ class HttpSocket extends CakeSocket {
*/
function get($uri = null, $query = array(), $request = array()) {
if (!empty($query)) {
$uri =$this->parseUri($uri);
$uri =$this->_parseUri($uri);
if (isset($uri['query'])) {
$uri['query'] = array_merge($uri['query'], $query);
} else {
$uri['query'] = $query;
}
$uri = $this->buildUri($uri);
$uri = $this->_buildUri($uri);
}
$request = Set::merge(array('method' => 'GET', 'uri' => $uri), $request);
@ -286,7 +287,7 @@ class HttpSocket extends CakeSocket {
/**
* Issues a POST request to the specified URI, query, and request.
*
* @param mixed $uri URI to request (see {@link parseUri()})
* @param mixed $uri URI to request (see {@link _parseUri()})
* @param array $query Query to append to URI
* @param array $request An indexed array with indexes such as 'method' or uri
* @return mixed Result of request
@ -299,7 +300,7 @@ class HttpSocket extends CakeSocket {
/**
* Issues a PUT request to the specified URI, query, and request.
*
* @param mixed $uri URI to request (see {@link parseUri()})
* @param mixed $uri URI to request (see {@link _parseUri()})
* @param array $query Query to append to URI
* @param array $request An indexed array with indexes such as 'method' or uri
* @return mixed Result of request
@ -312,7 +313,7 @@ class HttpSocket extends CakeSocket {
/**
* Issues a DELETE request to the specified URI, query, and request.
*
* @param mixed $uri URI to request (see {@link parseUri()})
* @param mixed $uri URI to request (see {@link _parseUri()})
* @param array $query Query to append to URI
* @param array $request An indexed array with indexes such as 'method' or uri
* @return mixed Result of request
@ -346,16 +347,16 @@ class HttpSocket extends CakeSocket {
}
$base = array_merge($this->config['request']['uri'], array('scheme' => array('http', 'https'), 'port' => array(80, 443)));
$url = $this->parseUri($url, $base);
$url = $this->_parseUri($url, $base);
if (empty($url)) {
$url = $this->config['request']['uri'];
}
if (!empty($uriTemplate)) {
return $this->buildUri($url, $uriTemplate);
return $this->_buildUri($url, $uriTemplate);
}
return $this->buildUri($url);
return $this->_buildUri($url);
}
/**
* Parses the given message and breaks it down in parts.
@ -364,7 +365,7 @@ class HttpSocket extends CakeSocket {
* @return array Parsed message (with indexed elements such as raw, status, header, body)
* @access protected
*/
function parseResponse($message) {
function _parseResponse($message) {
if (is_array($message)) {
return $message;
} elseif (!is_string($message)) {
@ -394,12 +395,12 @@ class HttpSocket extends CakeSocket {
$response['status']['reason-phrase'] = $match[3];
}
$response['header'] = $this->parseHeader($response['raw']['header']);
$decoded = $this->decodeBody($response['raw']['body'], @$response['header']['Transfer-Encoding']);
$response['header'] = $this->_parseHeader($response['raw']['header']);
$decoded = $this->_decodeBody($response['raw']['body'], @$response['header']['Transfer-Encoding']);
$response['body'] = $decoded['body'];
if (!empty($decoded['header'])) {
$response['header'] = $this->parseHeader($this->buildHeader($response['header']).$this->buildHeader($decoded['header']));
$response['header'] = $this->_parseHeader($this->_buildHeader($response['header']).$this->_buildHeader($decoded['header']));
}
if (!empty($response['header'])) {
@ -423,7 +424,7 @@ class HttpSocket extends CakeSocket {
* @return mixed Array or false
* @access protected
*/
function decodeBody($body, $encoding = 'chunked') {
function _decodeBody($body, $encoding = 'chunked') {
if (!is_string($body)) {
return false;
}
@ -434,7 +435,7 @@ class HttpSocket extends CakeSocket {
if (!is_callable(array(&$this, $decodeMethod))) {
if (!$this->quirksMode) {
trigger_error(sprintf(__('HttpSocket::decodeBody - Unknown encoding: %s. Activate quirks mode to surpress error.', true), h($encoding)), E_USER_WARNING);
trigger_error(sprintf(__('HttpSocket::_decodeBody - Unknown encoding: %s. Activate quirks mode to surpress error.', true), h($encoding)), E_USER_WARNING);
}
return array('body' => $body, 'header' => false);
}
@ -448,7 +449,7 @@ class HttpSocket extends CakeSocket {
* @return mixed Array or false
* @access protected
*/
function decodeChunkedBody($body) {
function _decodeChunkedBody($body) {
if (!is_string($body)) {
return false;
}
@ -459,7 +460,7 @@ class HttpSocket extends CakeSocket {
while ($chunkLength !== 0) {
if (!preg_match("/^([0-9a-f]+) *(?:;(.+)=(.+))?\r\n/iU", $body, $match)) {
if (!$this->quirksMode) {
trigger_error(__('HttpSocket::decodeChunkedBody - Could not parse malformed chunk. Activate quirks mode to do this.', true), E_USER_WARNING);
trigger_error(__('HttpSocket::_decodeChunkedBody - Could not parse malformed chunk. Activate quirks mode to do this.', true), E_USER_WARNING);
return false;
}
break;
@ -498,26 +499,26 @@ class HttpSocket extends CakeSocket {
$entityHeader = false;
if (!empty($body)) {
$entityHeader = $this->parseHeader($body);
$entityHeader = $this->_parseHeader($body);
}
return array('body' => $decodedBody, 'header' => $entityHeader);
}
/**
* Parses and sets the specified URI into current request configuration.
*
* @param mixed $uri URI (see {@link parseUri()})
* @param mixed $uri URI (see {@link _parseUri()})
* @return array Current configuration settings
* @access protected
*/
function configUri($uri = null) {
function _configUri($uri = null) {
if (empty($uri)) {
return false;
}
if (is_array($uri)) {
$uri = $this->parseUri($uri);
$uri = $this->_parseUri($uri);
} else {
$uri = $this->parseUri($uri, true);
$uri = $this->_parseUri($uri, true);
}
if (!isset($uri['host'])) {
@ -542,18 +543,18 @@ class HttpSocket extends CakeSocket {
* @return string A fully qualified URL formated according to $uriTemplate
* @access protected
*/
function buildUri($uri = array(), $uriTemplate = '%scheme://%user:%pass@%host:%port/%path?%query#%fragment') {
function _buildUri($uri = array(), $uriTemplate = '%scheme://%user:%pass@%host:%port/%path?%query#%fragment') {
if (is_string($uri)) {
$uri = array('host' => $uri);
}
$uri = $this->parseUri($uri, true);
$uri = $this->_parseUri($uri, true);
if (!is_array($uri) || empty($uri)) {
return false;
}
$uri['path'] = preg_replace('/^\//', null, $uri['path']);
$uri['query'] = $this->httpSerialize($uri['query']);
$uri['query'] = $this->_httpSerialize($uri['query']);
$stripIfEmpty = array(
'query' => '?%query',
'fragment' => '#%fragment',
@ -589,7 +590,7 @@ class HttpSocket extends CakeSocket {
* @return array Parsed URI
* @access protected
*/
function parseUri($uri = null, $base = array()) {
function _parseUri($uri = null, $base = array()) {
$uriBase = array(
'scheme' => array('http', 'https'),
'host' => null,
@ -631,7 +632,7 @@ class HttpSocket extends CakeSocket {
}
if (array_key_exists('query', $uri)) {
$uri['query'] = $this->parseQuery($uri['query']);
$uri['query'] = $this->_parseQuery($uri['query']);
}
if (!array_intersect_key($uriBase, $uri)) {
@ -647,13 +648,13 @@ class HttpSocket extends CakeSocket {
* - ?key[]=value1&key[]=value2
*
* A leading '?' mark in $query is optional and does not effect the outcome of this function. For the complete capabilities of this implementation
* take a look at HttpSocketTest::testParseQuery()
* take a look at HttpSocketTest::testparseQuery()
*
* @param mixed $query A query string to parse into an array or an array to return directly "as is"
* @return array The $query parsed into a possibly multi-level array. If an empty $query is given, an empty array is returned.
* @access protected
*/
function parseQuery($query) {
function _parseQuery($query) {
if (is_array($query)) {
return $query;
}
@ -710,13 +711,13 @@ class HttpSocket extends CakeSocket {
* @return string Request line
* @access protected
*/
function buildRequestLine($request = array(), $versionToken = 'HTTP/1.1') {
function _buildRequestLine($request = array(), $versionToken = 'HTTP/1.1') {
$asteriskMethods = array('OPTIONS');
if (is_string($request)) {
$isValid = preg_match("/(.+) (.+) (.+)\r\n/U", $request, $match);
if (!$this->quirksMode && (!$isValid || ($match[2] == '*' && !in_array($match[3], $asteriskMethods)))) {
trigger_error(__('HttpSocket::buildRequestLine - Passed an invalid request line string. Activate quirks mode to do this.', true), E_USER_WARNING);
trigger_error(__('HttpSocket::_buildRequestLine - Passed an invalid request line string. Activate quirks mode to do this.', true), E_USER_WARNING);
return false;
}
return $request;
@ -726,12 +727,12 @@ class HttpSocket extends CakeSocket {
return false;
}
$request['uri'] = $this->parseUri($request['uri']);
$request['uri'] = $this->_parseUri($request['uri']);
$request = array_merge(array('method' => 'GET'), $request);
$request['uri'] = $this->buildUri($request['uri'], '/%path?%query');
$request['uri'] = $this->_buildUri($request['uri'], '/%path?%query');
if (!$this->quirksMode && $request['uri'] === '*' && !in_array($request['method'], $asteriskMethods)) {
trigger_error(sprintf(__('HttpSocket::buildRequestLine - The "*" asterisk character is only allowed for the following methods: %s. Activate quirks mode to work outside of HTTP/1.1 specs.', true), join(',', $asteriskMethods)), E_USER_WARNING);
trigger_error(sprintf(__('HttpSocket::_buildRequestLine - The "*" asterisk character is only allowed for the following methods: %s. Activate quirks mode to work outside of HTTP/1.1 specs.', true), join(',', $asteriskMethods)), E_USER_WARNING);
return false;
}
return $request['method'].' '.$request['uri'].' '.$versionToken.$this->lineBreak;
@ -743,7 +744,7 @@ class HttpSocket extends CakeSocket {
* @return string Serialized variable
* @access protected
*/
function httpSerialize($data = array()) {
function _httpSerialize($data = array()) {
if (is_string($data)) {
return $data;
}
@ -759,7 +760,7 @@ class HttpSocket extends CakeSocket {
* @return string Header built from array
* @access protected
*/
function buildHeader($header, $mode = 'standard') {
function _buildHeader($header, $mode = 'standard') {
if (is_string($header)) {
return $header;
} elseif (!is_array($header)) {
@ -773,7 +774,7 @@ class HttpSocket extends CakeSocket {
}
foreach ((array)$contents as $content) {
$contents = preg_replace("/\r\n(?![\t ])/", "\r\n ", $content);
$field = $this->escapeToken($field);
$field = $this->_escapeToken($field);
$returnHeader .= $field.': '.$contents.$this->lineBreak;
}
@ -788,7 +789,7 @@ class HttpSocket extends CakeSocket {
* @return array Parsed header
* @access protected
*/
function parseHeader($header) {
function _parseHeader($header) {
if (is_array($header)) {
foreach ($header as $field => $value) {
unset($header[$field]);
@ -814,7 +815,7 @@ class HttpSocket extends CakeSocket {
$value = trim($value);
$value = preg_replace("/[\t ]\r\n/", "\r\n", $value);
$field = $this->unescapeToken($field);
$field = $this->_unescapeToken($field);
$field = strtolower($field);
preg_match_all('/(?:^|(?<=-))[a-z]/U', $field, $offsets, PREG_OFFSET_CAPTURE);
@ -846,7 +847,7 @@ class HttpSocket extends CakeSocket {
$cookies = array();
foreach ((array)$header['Set-Cookie'] as $cookie) {
$parts = preg_split('/(?<![^;]");[ \t]*/', $cookie);
list($name, $value) = explode('=', array_shift($parts));
list($name, $value) = explode('=', array_shift($parts), 2);
$cookies[$name] = compact('value');
foreach ($parts as $part) {
if (strpos($part, '=') !== false) {
@ -875,29 +876,11 @@ class HttpSocket extends CakeSocket {
function buildCookies($cookies) {
$header = array();
foreach ($cookies as $name => $cookie) {
$header[] = $name.'='.$this->escapeToken($cookie['value'], array(';'));
$header[] = $name.'='.$this->_escapeToken($cookie['value'], array(';'));
}
$header = $this->buildHeader(array('Cookie' => $header), 'pragmatic');
$header = $this->_buildHeader(array('Cookie' => $header), 'pragmatic');
return $header;
}
/**
* undocumented function
*
* @return void
* @access public
*/
function saveCookies() {
}
/**
* undocumented function
*
* @return void
* @access public
*/
function loadCookies() {
}
/**
* Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs)
*
@ -906,8 +889,8 @@ class HttpSocket extends CakeSocket {
* @access protected
* @todo Test $chars parameter
*/
function unescapeToken($token, $chars = null) {
$regex = '/"(['.join('', $this->__tokenEscapeChars(true, $chars)).'])"/';
function _unescapeToken($token, $chars = null) {
$regex = '/"(['.join('', $this->_tokenEscapeChars(true, $chars)).'])"/';
$token = preg_replace($regex, '\\1', $token);
return $token;
}
@ -919,8 +902,8 @@ class HttpSocket extends CakeSocket {
* @access protected
* @todo Test $chars parameter
*/
function escapeToken($token, $chars = null) {
$regex = '/(['.join('', $this->__tokenEscapeChars(true, $chars)).'])/';
function _escapeToken($token, $chars = null) {
$regex = '/(['.join('', $this->_tokenEscapeChars(true, $chars)).'])/';
$token = preg_replace($regex, '"\\1"', $token);
return $token;
}
@ -929,10 +912,10 @@ class HttpSocket extends CakeSocket {
*
* @param boolean $hex true to get them as HEX values, false otherwise
* @return array Escape chars
* @access private
* @access protected
* @todo Test $chars parameter
*/
function __tokenEscapeChars($hex = true, $chars = null) {
function _tokenEscapeChars($hex = true, $chars = null) {
if (!empty($chars)) {
$escape = $chars;
} else {

View file

@ -251,11 +251,11 @@ class I18n extends Object {
$this->__noLocale = true;
$core = true;
$merge = array();
$searchPaths = Configure::read('localePaths');
$plugins = Configure::listObjects('plugin');
$searchPaths = App::path('locales');
$plugins = App::objects('plugin');
if (!empty($plugins)) {
$pluginPaths = Configure::read('pluginPaths');
$pluginPaths = App::path('plugins');
foreach ($plugins as $plugin) {
$plugin = Inflector::underscore($plugin);

View file

@ -1,5 +1,4 @@
<?php
/* SVN FILE: $Id$ */
/**
* Pluralize and singularize English words.
*
@ -7,148 +6,46 @@
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 0.2.9
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Included libraries.
*
*/
if (!class_exists('Object')) {
uses('object');
}
if (!class_exists('Set')) {
require LIBS . 'set.php';
require_once(LIBS . 'object.php');
}
/**
* Pluralize and singularize English words.
*
* Inflector pluralizes and singularizes English nouns.
* Used by Cake's naming conventions throughout the framework.
* Test with $i = new Inflector(); $i->test();
*
* @package cake
* @subpackage cake.cake.libs
* @link http://book.cakephp.org/view/491/Inflector
*/
class Inflector extends Object {
/**
* Pluralized words.
*
* @var array
* @access private
**/
var $pluralized = array();
/**
* List of pluralization rules in the form of pattern => replacement.
*
* @var array
* @access public
* @link http://book.cakephp.org/view/47/Custom-Inflections
**/
var $pluralRules = array();
/**
* Singularized words.
*
* @var array
* @access private
**/
var $singularized = array();
/**
* List of singularization rules in the form of pattern => replacement.
*
* @var array
* @access public
* @link http://book.cakephp.org/view/47/Custom-Inflections
**/
var $singularRules = array();
/**
* Plural rules from inflections.php
*
* @var array
* @access private
**/
var $__pluralRules = array();
/**
* Un-inflected plural rules from inflections.php
*
* @var array
* @access private
**/
var $__uninflectedPlural = array();
/**
* Irregular plural rules from inflections.php
*
* @var array
* @access private
**/
var $__irregularPlural = array();
/**
* Singular rules from inflections.php
*
* @var array
* @access private
**/
var $__singularRules = array();
/**
* Un-inflectd singular rules from inflections.php
*
* @var array
* @access private
**/
var $__uninflectedSingular = array();
/**
* Irregular singular rules from inflections.php
*
* @var array
* @access private
**/
var $__irregularSingular = array();
/**
* Gets a reference to the Inflector object instance
*
* @return object
* @access public
*/
function &getInstance() {
static $instance = array();
if (!$instance) {
$instance[0] =& new Inflector();
if (file_exists(CONFIGS.'inflections.php')) {
include(CONFIGS.'inflections.php');
$instance[0]->__pluralRules = $pluralRules;
$instance[0]->__uninflectedPlural = $uninflectedPlural;
$instance[0]->__irregularPlural = $irregularPlural;
$instance[0]->__singularRules = $singularRules;
$instance[0]->__uninflectedSingular = $uninflectedPlural;
$instance[0]->__irregularSingular = array_flip($irregularPlural);
}
}
return $instance[0];
}
/**
* Initializes plural inflection rules.
* Plural inflector rules
*
* @return void
* @access private
*/
function __initPluralRules() {
$corePluralRules = array(
* @var array
* @access protected
**/
var $_plural = array(
'rules' => array(
'/(s)tatus$/i' => '\1\2tatuses',
'/(quiz)$/i' => '\1zes',
'/^(ox)$/i' => '\1\2en',
@ -170,21 +67,12 @@ class Inflector extends Object {
'/(ax|cris|test)is$/i' => '\1es',
'/s$/' => 's',
'/^$/' => '',
'/$/' => 's');
$coreUninflectedPlural = array(
'.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*sheep', 'Amoyese',
'bison', 'Borghese', 'bream', 'breeches', 'britches', 'buffalo', 'cantus', 'carp', 'chassis', 'clippers',
'cod', 'coitus', 'Congoese', 'contretemps', 'corps', 'debris', 'diabetes', 'djinn', 'eland', 'elk',
'equipment', 'Faroese', 'flounder', 'Foochowese', 'gallows', 'Genevese', 'Genoese', 'Gilbertese', 'graffiti',
'headquarters', 'herpes', 'hijinks', 'Hottentotese', 'information', 'innings', 'jackanapes', 'Kiplingese',
'Kongoese', 'Lucchese', 'mackerel', 'Maltese', 'media', 'mews', 'moose', 'mumps', 'Nankingese', 'news',
'nexus', 'Niasese', 'Pekingese', 'People', 'Piedmontese', 'pincers', 'Pistoiese', 'pliers', 'Portuguese', 'proceedings',
'rabies', 'rice', 'rhinoceros', 'salmon', 'Sarawakese', 'scissors', 'sea[- ]bass', 'series', 'Shavese', 'shears',
'siemens', 'species', 'swine', 'testes', 'trousers', 'trout', 'tuna', 'Vermontese', 'Wenchowese',
'whiting', 'wildebeest', 'Yengeese');
$coreIrregularPlural = array(
'/$/' => 's',
),
'uninflected' => array(
'.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*sheep', 'people'
),
'irregular' => array(
'atlas' => 'atlases',
'beef' => 'beefs',
'brother' => 'brothers',
@ -202,6 +90,7 @@ class Inflector extends Object {
'mongoose' => 'mongooses',
'move' => 'moves',
'mythos' => 'mythoi',
'niche' => 'niches',
'numen' => 'numina',
'occiput' => 'occiputs',
'octopus' => 'octopuses',
@ -213,67 +102,18 @@ class Inflector extends Object {
'soliloquy' => 'soliloquies',
'testis' => 'testes',
'trilby' => 'trilbys',
'turf' => 'turfs');
'turf' => 'turfs'
)
);
$pluralRules = Set::pushDiff($this->__pluralRules, $corePluralRules);
$uninflected = Set::pushDiff($this->__uninflectedPlural, $coreUninflectedPlural);
$irregular = Set::pushDiff($this->__irregularPlural, $coreIrregularPlural);
$this->pluralRules = array('pluralRules' => $pluralRules, 'uninflected' => $uninflected, 'irregular' => $irregular);
$this->pluralized = array();
}
/**
* Return $word in plural form.
* Singular inflector rules
*
* @param string $word Word in singular
* @return string Word in plural
* @access public
* @static
* @link http://book.cakephp.org/view/572/Class-methods
*/
function pluralize($word) {
$_this =& Inflector::getInstance();
if (!isset($_this->pluralRules) || empty($_this->pluralRules)) {
$_this->__initPluralRules();
}
if (isset($_this->pluralized[$word])) {
return $_this->pluralized[$word];
}
extract($_this->pluralRules);
if (!isset($regexUninflected) || !isset($regexIrregular)) {
$regexUninflected = __enclose(join( '|', $uninflected));
$regexIrregular = __enclose(join( '|', array_keys($irregular)));
$_this->pluralRules['regexUninflected'] = $regexUninflected;
$_this->pluralRules['regexIrregular'] = $regexIrregular;
}
if (preg_match('/(.*)\\b(' . $regexIrregular . ')$/i', $word, $regs)) {
$_this->pluralized[$word] = $regs[1] . substr($word, 0, 1) . substr($irregular[strtolower($regs[2])], 1);
return $_this->pluralized[$word];
}
if (preg_match('/^(' . $regexUninflected . ')$/i', $word, $regs)) {
$_this->pluralized[$word] = $word;
return $word;
}
foreach ($pluralRules as $rule => $replacement) {
if (preg_match($rule, $word)) {
$_this->pluralized[$word] = preg_replace($rule, $replacement, $word);
return $_this->pluralized[$word];
}
}
}
/**
* Initializes singular inflection rules.
*
* @return void
* @var array
* @access protected
*/
function __initSingularRules() {
$coreSingularRules = array(
**/
var $_singular = array(
'rules' => array(
'/(s)tatuses$/i' => '\1\2tatus',
'/^(.*)(menu)s$/i' => '\1\2',
'/(quiz)zes$/i' => '\\1',
@ -306,58 +146,142 @@ class Inflector extends Object {
'/(c)hildren$/i' => '\1\2hild',
'/(n)ews$/i' => '\1\2ews',
'/^(.*us)$/' => '\\1',
'/s$/i' => '');
'/s$/i' => ''
),
'uninflected' => array(
'.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*sheep', '.*ss'
),
'irregular' => array()
);
$coreUninflectedSingular = array(
'.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*sheep', '.*ss', 'Amoyese',
'bison', 'Borghese', 'bream', 'breeches', 'britches', 'buffalo', 'cantus', 'carp', 'chassis', 'clippers',
'cod', 'coitus', 'Congoese', 'contretemps', 'corps', 'debris', 'diabetes', 'djinn', 'eland', 'elk',
'equipment', 'Faroese', 'flounder', 'Foochowese', 'gallows', 'Genevese', 'Genoese', 'Gilbertese', 'graffiti',
'headquarters', 'herpes', 'hijinks', 'Hottentotese', 'information', 'innings', 'jackanapes', 'Kiplingese',
'Kongoese', 'Lucchese', 'mackerel', 'Maltese', 'media', 'mews', 'moose', 'mumps', 'Nankingese', 'news',
'nexus', 'Niasese', 'Pekingese', 'Piedmontese', 'pincers', 'Pistoiese', 'pliers', 'Portuguese', 'proceedings',
'rabies', 'rice', 'rhinoceros', 'salmon', 'Sarawakese', 'scissors', 'sea[- ]bass', 'series', 'Shavese', 'shears',
'siemens', 'species', 'swine', 'testes', 'trousers', 'trout', 'tuna', 'Vermontese', 'Wenchowese',
'whiting', 'wildebeest', 'Yengeese');
/**
* Words that should not be inflected
*
* @var array
* @access protected
**/
var $_uninflected = array(
'Amoyese', 'bison', 'Borghese', 'bream', 'breeches', 'britches', 'buffalo', 'cantus',
'carp', 'chassis', 'clippers', 'cod', 'coitus', 'Congoese', 'contretemps', 'corps',
'debris', 'diabetes', 'djinn', 'eland', 'elk', 'equipment', 'Faroese', 'flounder',
'Foochowese', 'gallows', 'Genevese', 'Genoese', 'Gilbertese', 'graffiti',
'headquarters', 'herpes', 'hijinks', 'Hottentotese', 'information', 'innings',
'jackanapes', 'Kiplingese', 'Kongoese', 'Lucchese', 'mackerel', 'Maltese', 'media',
'mews', 'moose', 'mumps', 'Nankingese', 'news', 'nexus', 'Niasese',
'Pekingese', 'Piedmontese', 'pincers', 'Pistoiese', 'pliers', 'Portuguese',
'proceedings', 'rabies', 'rice', 'rhinoceros', 'salmon', 'Sarawakese', 'scissors',
'sea[- ]bass', 'series', 'Shavese', 'shears', 'siemens', 'species', 'swine', 'testes',
'trousers', 'trout','tuna', 'Vermontese', 'Wenchowese', 'whiting', 'wildebeest',
'Yengeese'
);
$coreIrregularSingular = array(
'atlases' => 'atlas',
'beefs' => 'beef',
'brothers' => 'brother',
'children' => 'child',
'corpuses' => 'corpus',
'cows' => 'cow',
'ganglions' => 'ganglion',
'genies' => 'genie',
'genera' => 'genus',
'graffiti' => 'graffito',
'hoofs' => 'hoof',
'loaves' => 'loaf',
'men' => 'man',
'monies' => 'money',
'mongooses' => 'mongoose',
'moves' => 'move',
'mythoi' => 'mythos',
'numina' => 'numen',
'occiputs' => 'occiput',
'octopuses' => 'octopus',
'opuses' => 'opus',
'oxen' => 'ox',
'penises' => 'penis',
'people' => 'person',
'sexes' => 'sex',
'soliloquies' => 'soliloquy',
'testes' => 'testis',
'trilbys' => 'trilby',
'turfs' => 'turf');
/**
* Cached array identity map of pluralized words.
*
* @var array
* @access protected
**/
var $_pluralized = array();
$singularRules = Set::pushDiff($this->__singularRules, $coreSingularRules);
$uninflected = Set::pushDiff($this->__uninflectedSingular, $coreUninflectedSingular);
$irregular = Set::pushDiff($this->__irregularSingular, $coreIrregularSingular);
/**
* Cached array identity map of singularized words.
*
* @var array
* @access protected
**/
var $_singularized = array();
$this->singularRules = array('singularRules' => $singularRules, 'uninflected' => $uninflected, 'irregular' => $irregular);
$this->singularized = array();
/**
* Gets a reference to the Inflector object instance
*
* @return object
* @access public
*/
function &getInstance() {
static $instance = array();
if (!$instance) {
$instance[0] =& new Inflector();
}
return $instance[0];
}
/**
* Adds custom inflection $rules, of either 'plural' or 'singular' $type.
*
* @param string $type The type of inflection, either 'singular' or 'plural'
* @param array $rules Array of rules to be added. Example usage:
* Inflector::rules('plural', array('/^(inflect)or$/i' => '\1ables'));
* Inflector::rules('plural', array(
* 'rules' => array('/^(inflect)ors$/i' => '\1ables'),
* 'uninflected' => array('dontinflectme'),
* 'irregular' => array('red' => 'redlings')
* ));
* @access public
* @return void
* @static
*/
function rules($type, $rules = array()) {
$_this =& Inflector::getInstance();
$type = '_'.$type;
foreach ($rules as $rule => $pattern) {
if (is_array($pattern)) {
$_this->{$type}[$rule] = array_merge($pattern, $_this->{$type}[$rule]);
unset($rules[$rule], $_this->{$type}['cache' . ucfirst($rule)], $_this->{$type}['merged'][$rule]);
}
}
$_this->{$type}['rules'] = array_merge($rules, $_this->{$type}['rules']);
}
/**
* Return $word in plural form.
*
* @param string $word Word in singular
* @return string Word in plural
* @access public
* @static
* @link http://book.cakephp.org/view/572/Class-methods
*/
function pluralize($word) {
$_this =& Inflector::getInstance();
if (isset($_this->_pluralized[$word])) {
return $_this->_pluralized[$word];
}
if (!isset($_this->_plural['merged']['irregular'])) {
$_this->_plural['merged']['irregular'] = $_this->_plural['irregular'];
}
if (!isset($_this->plural['merged']['uninflected'])) {
$_this->_plural['merged']['uninflected'] = array_merge($_this->_plural['uninflected'], $_this->_uninflected);
}
if (!isset($_this->_plural['cacheUninflected']) || !isset($_this->_plural['cacheIrregular'])) {
$_this->_plural['cacheUninflected'] = '(?:' . join( '|', $_this->_plural['merged']['uninflected']) . ')';
$_this->_plural['cacheIrregular'] = '(?:' . join( '|', array_keys($_this->_plural['merged']['irregular'])) . ')';
}
if (preg_match('/(.*)\\b(' . $_this->_plural['cacheIrregular'] . ')$/i', $word, $regs)) {
$_this->_pluralized[$word] = $regs[1] . substr($word, 0, 1) . substr($_this->_plural['merged']['irregular'][strtolower($regs[2])], 1);
return $_this->_pluralized[$word];
}
if (preg_match('/^(' . $_this->_plural['cacheUninflected'] . ')$/i', $word, $regs)) {
$_this->_pluralized[$word] = $word;
return $word;
}
foreach ($_this->_plural['rules'] as $rule => $replacement) {
if (preg_match($rule, $word)) {
$_this->_pluralized[$word] = preg_replace($rule, $replacement, $word);
return $_this->_pluralized[$word];
}
}
}
/**
* Return $word in singular form.
*
@ -369,41 +293,44 @@ class Inflector extends Object {
*/
function singularize($word) {
$_this =& Inflector::getInstance();
if (!isset($_this->singularRules) || empty($_this->singularRules)) {
$_this->__initSingularRules();
if (isset($_this->_singularized[$word])) {
return $_this->_singularized[$word];
}
if (isset($_this->singularized[$word])) {
return $_this->singularized[$word];
}
extract($_this->singularRules);
if (!isset($regexUninflected) || !isset($regexIrregular)) {
$regexUninflected = __enclose(join( '|', $uninflected));
$regexIrregular = __enclose(join( '|', array_keys($irregular)));
$_this->singularRules['regexUninflected'] = $regexUninflected;
$_this->singularRules['regexIrregular'] = $regexIrregular;
if (!isset($_this->_singular['merged']['uninflected'])) {
$_this->_singular['merged']['uninflected'] = array_merge($_this->_singular['uninflected'], $_this->_uninflected);
}
if (preg_match('/(.*)\\b(' . $regexIrregular . ')$/i', $word, $regs)) {
$_this->singularized[$word] = $regs[1] . substr($word, 0, 1) . substr($irregular[strtolower($regs[2])], 1);
return $_this->singularized[$word];
if (!isset($_this->_singular['merged']['irregular'])) {
$_this->_singular['merged']['irregular'] = array_merge($_this->_singular['irregular'], array_flip($_this->_plural['irregular']));
}
if (preg_match('/^(' . $regexUninflected . ')$/i', $word, $regs)) {
$_this->singularized[$word] = $word;
if (!isset($_this->_singular['cacheUninflected']) || !isset($_this->_singular['cacheIrregular'])) {
$_this->_singular['cacheUninflected'] = '(?:' . join( '|', $_this->_singular['merged']['uninflected']) . ')';
$_this->_singular['cacheIrregular'] = '(?:' . join( '|', array_keys($_this->_singular['merged']['irregular'])) . ')';
}
if (preg_match('/(.*)\\b(' . $_this->_singular['cacheIrregular'] . ')$/i', $word, $regs)) {
$_this->_singularized[$word] = $regs[1] . substr($word, 0, 1) . substr($_this->_singular['merged']['irregular'][strtolower($regs[2])], 1);
return $_this->_singularized[$word];
}
if (preg_match('/^(' . $_this->_singular['cacheUninflected'] . ')$/i', $word, $regs)) {
$_this->_singularized[$word] = $word;
return $word;
}
foreach ($singularRules as $rule => $replacement) {
foreach ($_this->_singular['rules'] as $rule => $replacement) {
if (preg_match($rule, $word)) {
$_this->singularized[$word] = preg_replace($rule, $replacement, $word);
return $_this->singularized[$word];
$_this->_singularized[$word] = preg_replace($rule, $replacement, $word);
return $_this->_singularized[$word];
}
}
$_this->singularized[$word] = $word;
$_this->_singularized[$word] = $word;
return $word;
}
/**
* Returns the given lower_case_and_underscored_word as a CamelCased word.
*
@ -416,6 +343,7 @@ class Inflector extends Object {
function camelize($lowerCaseAndUnderscoredWord) {
return str_replace(" ", "", ucwords(str_replace("_", " ", $lowerCaseAndUnderscoredWord)));
}
/**
* Returns the given camelCasedWord as an underscored_word.
*
@ -428,6 +356,7 @@ class Inflector extends Object {
function underscore($camelCasedWord) {
return strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $camelCasedWord));
}
/**
* Returns the given underscored_word_group as a Human Readable Word Group.
* (Underscores are replaced by spaces and capitalized following words.)
@ -441,6 +370,7 @@ class Inflector extends Object {
function humanize($lowerCaseAndUnderscoredWord) {
return ucwords(str_replace("_", " ", $lowerCaseAndUnderscoredWord));
}
/**
* Returns corresponding table name for given model $className. ("people" for the model class "Person").
*
@ -453,6 +383,7 @@ class Inflector extends Object {
function tableize($className) {
return Inflector::pluralize(Inflector::underscore($className));
}
/**
* Returns Cake model class name ("Person" for the database table "people".) for given database table.
*
@ -465,6 +396,7 @@ class Inflector extends Object {
function classify($tableName) {
return Inflector::camelize(Inflector::singularize($tableName));
}
/**
* Returns camelBacked version of an underscored string.
*
@ -479,22 +411,28 @@ class Inflector extends Object {
$replace = strtolower(substr($string, 0, 1));
return preg_replace('/\\w/', $replace, $string, 1);
}
/**
* Returns a string with all spaces converted to underscores (by default), accented
* characters converted to non-accented characters, and non word characters removed.
*
* @param string $string
* @param string $replacement
* @param string $string the string you want to slug
* @param string $replacement will replace keys in map
* @param array $map extra elements to map to the replacement
* @return string
* @access public
* @static
* @link http://book.cakephp.org/view/572/Class-methods
*/
function slug($string, $replacement = '_') {
if (!class_exists('String')) {
require LIBS . 'string.php';
function slug($string, $replacement = '_', $map = array()) {
if (is_array($replacement)) {
$map = $replacement;
$replacement = '_';
}
$map = array(
$quotedReplacement = preg_quote($replacement, '/');
$default = array(
'/à|á|å|â/' => 'a',
'/è|é|ê|ẽ|ë/' => 'e',
'/ì|í|î/' => 'i',
@ -511,18 +449,10 @@ class Inflector extends Object {
'/ß/' => 'ss',
'/[^\w\s]/' => ' ',
'/\\s+/' => $replacement,
String::insert('/^[:replacement]+|[:replacement]+$/', array('replacement' => preg_quote($replacement, '/'))) => '',
sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '',
);
$map = array_merge($default, $map);
return preg_replace(array_keys($map), array_values($map), $string);
}
}
/**
* Enclose a string for preg matching.
*
* @param string $string String to enclose
* @return string Enclosed string
*/
function __enclose($string) {
return '(?:' . $string . ')';
}
?>

View file

@ -877,9 +877,10 @@ class TreeBehavior extends ModelBehavior {
$scope['NOT'][$Model->alias . '.' . $Model->primaryKey] = $Model->id;
}
}
$name = $Model->alias . '.' . $right;
list($edge) = array_values($Model->find('first', array(
'conditions' => $scope,
'fields' => $db->calculate($Model, 'max', array($right)),
'fields' => $db->calculate($Model, 'max', array($name, $right)),
'recursive' => $recursive
)));
return (empty($edge[$right])) ? 0 : $edge[$right];
@ -895,9 +896,10 @@ class TreeBehavior extends ModelBehavior {
*/
function __getMin($Model, $scope, $left, $recursive = -1) {
$db =& ConnectionManager::getDataSource($Model->useDbConfig);
$name = $Model->alias . '.' . $left;
list($edge) = array_values($Model->find('first', array(
'conditions' => $scope,
'fields' => $db->calculate($Model, 'min', array($left)),
'fields' => $db->calculate($Model, 'min', array($name, $left)),
'recursive' => $recursive
)));
return (empty($edge[$left])) ? 0 : $edge[$left];

View file

@ -198,7 +198,7 @@ class CakeSchema extends Object {
}
if (!is_array($models) && $models !== false) {
$models = Configure::listObjects('model');
$models = App::objects('model');
}
if (is_array($models)) {

View file

@ -241,13 +241,14 @@ class DataSource extends Object {
if ($this->cacheSources === false) {
return null;
}
if (isset($this->__descriptions[$model->tablePrefix . $model->table])) {
return $this->__descriptions[$model->tablePrefix . $model->table];
$table = $this->fullTableName($model, false);
if (isset($this->__descriptions[$table])) {
return $this->__descriptions[$table];
}
$cache = $this->__cacheDescription($model->tablePrefix . $model->table);
$cache = $this->__cacheDescription($table);
if ($cache !== null) {
$this->__descriptions[$model->tablePrefix . $model->table] =& $cache;
$this->__descriptions[$table] =& $cache;
return $cache;
}
return null;

View file

@ -221,7 +221,7 @@ class DboMssql extends DboSource {
'null' => (strtoupper($column[0]['Null']) == 'YES'),
'default' => preg_replace("/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/", "$1", $column[0]['Default']),
'length' => intval($column[0]['Length']),
'key' => ($column[0]['Key'] == '1')
'key' => ($column[0]['Key'] == '1') ? 'primary' : false
);
if ($fields[$field]['default'] === 'null') {
$fields[$field]['default'] = null;
@ -341,17 +341,18 @@ class DboMssql extends DboSource {
if (!empty($values)) {
$fields = array_combine($fields, $values);
}
$primaryKey = $this->_getPrimaryKey($model);
if (array_key_exists($model->primaryKey, $fields)) {
if (empty($fields[$model->primaryKey])) {
unset($fields[$model->primaryKey]);
if (array_key_exists($primaryKey, $fields)) {
if (empty($fields[$primaryKey])) {
unset($fields[$primaryKey]);
} else {
$this->_execute("SET IDENTITY_INSERT " . $this->fullTableName($model) . " ON");
$this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' ON');
}
}
$result = parent::create($model, array_keys($fields), array_values($fields));
if (array_key_exists($model->primaryKey, $fields) && !empty($fields[$model->primaryKey])) {
$this->_execute("SET IDENTITY_INSERT " . $this->fullTableName($model) . " OFF");
if (array_key_exists($primaryKey, $fields) && !empty($fields[$primaryKey])) {
$this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($model) . ' OFF');
}
return $result;
}
@ -383,7 +384,7 @@ class DboMssql extends DboSource {
$error = mssql_get_last_message($this->connection);
if ($error) {
if (!preg_match('/contexto de la base de datos a|contesto di database|changed database/i', $error)) {
if (!preg_match('/contexto de la base de datos a|contesto di database|changed database|datenbankkontext/i', $error)) {
return $error;
}
}
@ -631,6 +632,29 @@ class DboMssql extends DboSource {
return false;
}
}
/**
* Inserts multiple values into a table
*
* @param string $table
* @param string $fields
* @param array $values
* @access protected
*/
function insertMulti($table, $fields, $values) {
$primaryKey = $this->_getPrimaryKey($table);
$hasPrimaryKey = $primaryKey != null && (
(is_array($fields) && in_array($primaryKey, $fields)
|| (is_string($fields) && strpos($fields, $this->startQuote . $primaryKey . $this->endQuote) !== false))
);
if ($hasPrimaryKey) {
$this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($table) . ' ON');
}
parent::insertMulti($table, $fields, $values);
if ($hasPrimaryKey) {
$this->_execute('SET IDENTITY_INSERT ' . $this->fullTableName($table) . ' OFF');
}
}
/**
* Generate a database-native column schema string
*
@ -680,5 +704,27 @@ class DboMssql extends DboSource {
}
return $join;
}
/**
* Makes sure it will return the primary key
*
* @param mixed $model
* @access protected
* @return string
*/
function _getPrimaryKey($model) {
if (is_object($model)) {
$schema = $model->schema();
} else {
$schema = $this->describe($model);
}
foreach ($schema as $field => $props) {
if (isset($props['key']) && $props['key'] == 'primary') {
return $field;
}
}
return null;
}
}
?>

View file

@ -232,20 +232,6 @@ class DboMysqli extends DboMysqlBase {
return $data;
}
/**
* Begin a transaction
*
* @param unknown_type $model
* @return boolean True on success, false on fail
* (i.e. if the database/model does not support transactions).
*/
function begin(&$model) {
if (parent::begin($model) && $this->execute('START TRANSACTION')) {
$this->_transactionStarted = true;
return true;
}
return false;
}
/**
* Returns a formatted error message from previous database operation.
*

View file

@ -454,6 +454,7 @@ class DboOracle extends DboSource {
while($r = $this->fetchRow()) {
$sources[] = strtolower($r[0]['name']);
}
parent::listSources($sources);
return $sources;
}
/**
@ -834,8 +835,7 @@ class DboOracle extends DboSource {
switch($column) {
case 'date':
$date = new DateTime($data);
$data = $date->format('Y-m-d H:i:s');
$data = date('Y-m-d H:i:s', strtotime($data));
$data = "TO_DATE('$data', 'YYYY-MM-DD HH24:MI:SS')";
break;
case 'integer' :

View file

@ -275,6 +275,9 @@ class DboPostgres extends DboSource {
case 'inet':
case 'float':
case 'integer':
case 'date':
case 'datetime':
case 'timestamp':
if ($data === '') {
return $read ? 'NULL' : 'DEFAULT';
}

View file

@ -88,7 +88,7 @@ class DboSqlite extends DboSource {
'primary_key' => array('name' => 'integer primary key'),
'string' => array('name' => 'varchar', 'limit' => '255'),
'text' => array('name' => 'text'),
'integer' => array('name' => 'integer', 'limit' => null, 'formatter' => 'intval'),
'integer' => array('name' => 'integer', 'limit' => 11, 'formatter' => 'intval'),
'float' => array('name' => 'float', 'formatter' => 'floatval'),
'datetime' => array('name' => 'datetime', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
'timestamp' => array('name' => 'timestamp', 'format' => 'Y-m-d H:i:s', 'formatter' => 'date'),
@ -190,18 +190,19 @@ class DboSqlite extends DboSource {
foreach ($result as $column) {
$fields[$column[0]['name']] = array(
'type' => $this->column($column[0]['type']),
'null' => !$column[0]['notnull'],
'default' => $column[0]['dflt_value'],
'length' => $this->length($column[0]['type'])
'type' => $this->column($column[0]['type']),
'null' => !$column[0]['notnull'],
'default' => $column[0]['dflt_value'],
'length' => $this->length($column[0]['type'])
);
if ($column[0]['pk'] == 1) {
$colLength = $this->length($column[0]['type']);
$fields[$column[0]['name']] = array(
'type' => $fields[$column[0]['name']]['type'],
'null' => false,
'default' => $column[0]['dflt_value'],
'key' => $this->index['PRI'],
'length' => 11
'type' => $fields[$column[0]['name']]['type'],
'null' => false,
'default' => $column[0]['dflt_value'],
'key' => $this->index['PRI'],
'length'=> ($colLength != null) ? $colLength : 11
);
}
}
@ -449,34 +450,34 @@ class DboSqlite extends DboSource {
}
$real = $this->columns[$type];
if (isset($column['key']) && $column['key'] == 'primary') {
$out = $this->name($name) . ' ' . $this->columns['primary_key']['name'];
} else {
$out = $this->name($name) . ' ' . $real['name'];
if (isset($real['limit']) || isset($real['length']) || isset($column['limit']) || isset($column['length'])) {
if (isset($column['length'])) {
$length = $column['length'];
} elseif (isset($column['limit'])) {
$length = $column['limit'];
} elseif (isset($real['length'])) {
$length = $real['length'];
} else {
$length = $real['limit'];
}
$out .= '(' . $length . ')';
}
if (isset($column['key']) && $column['key'] == 'primary') {
$out .= ' NOT NULL';
} elseif (isset($column['default']) && isset($column['null']) && $column['null'] == false) {
$out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
} elseif (isset($column['default'])) {
$out .= ' DEFAULT ' . $this->value($column['default'], $type);
} elseif (isset($column['null']) && $column['null'] == true) {
$out .= ' DEFAULT NULL';
} elseif (isset($column['null']) && $column['null'] == false) {
$out .= ' NOT NULL';
$out = $this->name($name) . ' ' . $real['name'];
if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
return $this->name($name) . ' ' . $this->columns['primary_key']['name'];
}
if (isset($real['limit']) || isset($real['length']) || isset($column['limit']) || isset($column['length'])) {
if (isset($column['length'])) {
$length = $column['length'];
} elseif (isset($column['limit'])) {
$length = $column['limit'];
} elseif (isset($real['length'])) {
$length = $real['length'];
} else {
$length = $real['limit'];
}
$out .= '(' . $length . ')';
}
if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
$out .= ' ' . $this->columns['primary_key']['name'];
} elseif (isset($column['key']) && $column['key'] == 'primary') {
$out .= ' NOT NULL';
} elseif (isset($column['default']) && isset($column['null']) && $column['null'] == false) {
$out .= ' DEFAULT ' . $this->value($column['default'], $type) . ' NOT NULL';
} elseif (isset($column['default'])) {
$out .= ' DEFAULT ' . $this->value($column['default'], $type);
} elseif (isset($column['null']) && $column['null'] == true) {
$out .= ' DEFAULT NULL';
} elseif (isset($column['null']) && $column['null'] == false) {
$out .= ' NOT NULL';
}
return $out;
}

View file

@ -627,16 +627,22 @@ class DboSource extends DataSource {
$queryData['fields'] = $this->fields($model);
}
foreach ($model->__associations as $type) {
foreach ($model->{$type} as $assoc => $assocData) {
if ($model->recursive > -1) {
$linkModel =& $model->{$assoc};
$external = isset($assocData['external']);
$_associations = $model->__associations;
if ($model->useDbConfig == $linkModel->useDbConfig) {
if (true === $this->generateAssociationQuery($model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null)) {
$linkedModels[] = $type . '/' . $assoc;
}
if ($model->recursive == -1) {
$_associations = array();
} else if ($model->recursive == 0) {
unset($_associations[2], $_associations[3]);
}
foreach ($_associations as $type) {
foreach ($model->{$type} as $assoc => $assocData) {
$linkModel =& $model->{$assoc};
$external = isset($assocData['external']);
if ($model->useDbConfig == $linkModel->useDbConfig) {
if (true === $this->generateAssociationQuery($model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null)) {
$linkedModels[$type . '/' . $assoc] = true;
}
}
}
@ -653,12 +659,12 @@ class DboSource extends DataSource {
$filtered = $this->__filterResults($resultSet, $model);
if ($model->recursive > 0) {
foreach ($model->__associations as $type) {
if ($model->recursive > -1) {
foreach ($_associations as $type) {
foreach ($model->{$type} as $assoc => $assocData) {
$linkModel =& $model->{$assoc};
if (!in_array($type . '/' . $assoc, $linkedModels)) {
if (empty($linkedModels[$type . '/' . $assoc])) {
if ($model->useDbConfig == $linkModel->useDbConfig) {
$db =& $this;
} else {
@ -852,11 +858,8 @@ class DboSource extends DataSource {
foreach ($fetch as $j => $data) {
if (
(isset($data[$with]) && $data[$with][$foreignKey] === $row[$model->alias][$model->primaryKey]) &&
(!in_array($data[$with][$joinKeys[1]], $uniqueIds))
(isset($data[$with]) && $data[$with][$foreignKey] === $row[$model->alias][$model->primaryKey])
) {
$uniqueIds[] = $data[$with][$joinKeys[1]];
if ($habtmFieldsCount <= 2) {
unset($data[$with]);
}

View file

@ -1,5 +1,4 @@
<?php
/* SVN FILE: $Id$ */
/**
* Object-relational mapper.
*
@ -7,27 +6,25 @@
*
* PHP versions 5
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.cake.libs.model
* @since CakePHP(tm) v 0.10.0.0
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Included libs
*/
App::import('Core', array('ClassRegistry', 'Overloadable', 'Validation', 'Behavior', 'ConnectionManager', 'Set', 'String'));
App::import('Core', array(
'ClassRegistry', 'Overloadable', 'Validation', 'ModelBehavior', 'ConnectionManager', 'Set', 'String'
));
/**
* Object-relational mapper.
*
@ -372,6 +369,10 @@ class Model extends Overloadable {
} elseif ($table) {
$this->useTable = $table;
}
if ($ds !== null) {
$this->useDbConfig = $ds;
}
if (is_subclass_of($this, 'AppModel')) {
$appVars = get_class_vars('AppModel');
@ -815,13 +816,18 @@ class Model extends Overloadable {
* @access public
*/
function deconstruct($field, $data) {
if (!is_array($data)) {
return $data;
}
$copy = $data;
$type = $this->getColumnType($field);
$db =& ConnectionManager::getDataSource($this->useDbConfig);
if (in_array($type, array('datetime', 'timestamp', 'date', 'time'))) {
$useNewDate = (isset($data['year']) || isset($data['month']) || isset($data['day']) || isset($data['hour']) || isset($data['minute']));
$dateFields = array('Y' => 'year', 'm' => 'month', 'd' => 'day', 'H' => 'hour', 'i' => 'min', 's' => 'sec');
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$format = $db->columns[$type]['format'];
$date = array();
@ -1010,7 +1016,10 @@ class Model extends Overloadable {
}
if ($id !== null && $id !== false) {
$this->data = $this->find(array($this->alias . '.' . $this->primaryKey => $id), $fields);
$this->data = $this->find('first', array(
'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
'fields' => $fields
));
return $this->data;
} else {
return false;
@ -1210,7 +1219,7 @@ class Model extends Overloadable {
foreach ($this->_schema as $field => $properties) {
if ($this->primaryKey === $field) {
$fInfo = $this->_schema[$field];
$isUUID = ($fInfo['length'] === 36 &&
$isUUID = ($fInfo['length'] == 36 &&
($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')
);
if (empty($this->data[$this->alias][$this->primaryKey]) && $isUUID) {
@ -1279,7 +1288,7 @@ class Model extends Overloadable {
));
$isUUID = !empty($this->{$join}->primaryKey) && (
$this->{$join}->_schema[$this->{$join}->primaryKey]['length'] === 36 && (
$this->{$join}->_schema[$this->{$join}->primaryKey]['length'] == 36 && (
$this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'string' ||
$this->{$join}->_schema[$this->{$join}->primaryKey]['type'] === 'binary'
)
@ -1374,16 +1383,15 @@ class Model extends Overloadable {
$conditions = ($recursive == 1) ? (array)$assoc['counterScope'] : array();
if (isset($keys['old'][$foreignKey])) {
if ($keys['old'][$foreignKey] == $keys[$foreignKey]) {
continue;
}
$conditions[$fkQuoted] = $keys['old'][$foreignKey];
$count = intval($this->find('count', compact('conditions', 'recursive')));
if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
$conditions[$fkQuoted] = $keys['old'][$foreignKey];
$count = intval($this->find('count', compact('conditions', 'recursive')));
$this->{$parent}->updateAll(
array($assoc['counterCache'] => $count),
array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
);
$this->{$parent}->updateAll(
array($assoc['counterCache'] => $count),
array($this->{$parent}->escapeField() => $keys['old'][$foreignKey])
);
}
}
$conditions[$fkQuoted] = $keys[$foreignKey];
@ -1420,7 +1428,7 @@ class Model extends Overloadable {
return array();
}
$old = $this->find('first', array(
'conditions' => array('id' => $this->id),
'conditions' => array($this->primaryKey => $this->id),
'fields' => array_values($included),
'recursive' => -1
));
@ -1464,7 +1472,7 @@ class Model extends Overloadable {
if (Set::numeric(array_keys($data))) {
while ($validates) {
foreach ($data as $key => $record) {
if (!$currentValidates = $this->__save($this, $record, $options)) {
if (!$currentValidates = $this->__save($record, $options)) {
$validationErrors[$key] = $this->validationErrors;
}
@ -1517,7 +1525,7 @@ class Model extends Overloadable {
if (isset($associations[$association])) {
switch ($associations[$association]) {
case 'belongsTo':
if ($this->__save($this->{$association}, $values, $options)) {
if ($this->{$association}->__save($values, $options)) {
$data[$this->alias][$this->belongsTo[$association]['foreignKey']] = $this->{$association}->id;
} else {
$validationErrors[$association] = $this->{$association}->validationErrors;
@ -1530,7 +1538,7 @@ class Model extends Overloadable {
}
}
}
if (!$this->__save($this, $data, $options)) {
if (!$this->__save($data, $options)) {
$validationErrors[$this->alias] = $this->validationErrors;
$validates = false;
}
@ -1548,7 +1556,7 @@ class Model extends Overloadable {
switch ($type) {
case 'hasOne':
$values[$this->{$type}[$association]['foreignKey']] = $this->id;
if (!$this->__save($this->{$association}, $values, $options)) {
if (!$this->{$association}->__save($values, $options)) {
$validationErrors[$association] = $this->{$association}->validationErrors;
$validates = false;
}
@ -1621,12 +1629,12 @@ class Model extends Overloadable {
* @access private
* @see Model::saveAll()
*/
function __save(&$model, $data, $options) {
function __save($data, $options) {
if ($options['validate'] === 'first' || $options['validate'] === 'only') {
if (!($model->create($data) && $model->validates($options))) {
if (!($this->create($data) && $this->validates($options))) {
return false;
}
} elseif (!($model->create(null) !== null && $model->save($data, $options))) {
} elseif (!($this->create(null) !== null && $this->save($data, $options))) {
return false;
}
return true;
@ -1646,17 +1654,11 @@ class Model extends Overloadable {
return $db->update($this, $fields, null, $conditions);
}
/**
* Alias for del().
*
* @param mixed $id ID of record to delete
* @param boolean $cascade Set to true to delete records that depend on this record
* @return boolean True on success
* @access public
* @see Model::del()
* @deprecated
* @link http://book.cakephp.org/view/691/remove
*/
function remove($id = null, $cascade = true) {
return $this->del($id, $cascade);
return $this->delete($id, $cascade);
}
/**
* Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.
@ -1667,7 +1669,7 @@ class Model extends Overloadable {
* @access public
* @link http://book.cakephp.org/view/690/del
*/
function del($id = null, $cascade = true) {
function delete($id = null, $cascade = true) {
if (!empty($id)) {
$this->id = $id;
}
@ -1675,7 +1677,10 @@ class Model extends Overloadable {
if ($this->exists() && $this->beforeDelete($cascade)) {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
if (!$this->Behaviors->trigger($this, 'beforeDelete', array($cascade), array('break' => true, 'breakOn' => false))) {
$filters = $this->Behaviors->trigger($this, 'beforeDelete', array($cascade), array(
'break' => true, 'breakOn' => false
));
if (!$filters) {
return false;
}
$this->_deleteDependent($id, $cascade);
@ -1701,16 +1706,10 @@ class Model extends Overloadable {
return false;
}
/**
* Alias for del().
*
* @param mixed $id ID of record to delete
* @param boolean $cascade Set to true to delete records that depend on this record
* @return boolean True on success
* @access public
* @see Model::del()
* @deprecated
*/
function delete($id = null, $cascade = true) {
return $this->del($id, $cascade);
function del($id = null, $cascade = true) {
return $this->delete($id, $cascade);
}
/**
* Cascades model deletes through associated hasMany and hasOne child records.
@ -1738,7 +1737,9 @@ class Model extends Overloadable {
if (isset($data['exclusive']) && $data['exclusive']) {
$model->deleteAll($conditions);
} else {
$records = $model->find('all', array('conditions' => $conditions, 'fields' => $model->primaryKey));
$records = $model->find('all', array(
'conditions' => $conditions, 'fields' => $model->primaryKey
));
if (!empty($records)) {
foreach ($records as $record) {
@ -1763,14 +1764,18 @@ class Model extends Overloadable {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
foreach ($this->hasAndBelongsToMany as $assoc => $data) {
$with = $data['with'];
$records = $this->{$data['with']}->find('all', array(
'conditions' => array_merge(array($this->{$data['with']}->escapeField($data['foreignKey']) => $id)),
'fields' => $this->{$data['with']}->primaryKey,
'conditions' => array_merge(array(
$this->{$with}->escapeField($data['foreignKey']) => $id
)),
'fields' => $this->{$with}->primaryKey,
'recursive' => -1
));
if (!empty($records)) {
foreach ($records as $record) {
$this->{$data['with']}->delete($record[$this->{$data['with']}->alias][$this->{$data['with']}->primaryKey]);
$id = $record[$this->{$with}->alias][$this->{$with}->primaryKey];
$this->{$with}->delete($id);
}
}
}
@ -1795,12 +1800,15 @@ class Model extends Overloadable {
return $db->delete($this, $conditions);
} else {
$ids = Set::extract(
$this->find('all', array_merge(array('fields' => "{$this->alias}.{$this->primaryKey}", 'recursive' => 0), compact('conditions'))),
$this->find('all', array_merge(array(
'fields' => "{$this->alias}.{$this->primaryKey}",
'recursive' => 0), compact('conditions'))
),
"{n}.{$this->alias}.{$this->primaryKey}"
);
if (empty($ids)) {
return false;
return true;
}
if ($callbacks) {
@ -1822,6 +1830,7 @@ class Model extends Overloadable {
}
}
}
/**
* Collects foreign keys from associations.
*
@ -1838,6 +1847,7 @@ class Model extends Overloadable {
}
return $result;
}
/**
* Returns true if a record with the currently set ID exists.
*
@ -1853,7 +1863,7 @@ class Model extends Overloadable {
if ($this->getID() === false || $this->useTable === false) {
return false;
}
if ($this->__exists !== null && $reset !== true) {
if (!empty($this->__exists) && $reset !== true) {
return $this->__exists;
}
$conditions = array($this->alias . '.' . $this->primaryKey => $this->getID());
@ -1864,6 +1874,7 @@ class Model extends Overloadable {
}
return $this->__exists = ($this->find('count', $query) > 0);
}
/**
* Returns true if a record that meets given conditions exists.
*
@ -1874,6 +1885,7 @@ class Model extends Overloadable {
function hasAny($conditions = null) {
return ($this->find('count', array('conditions' => $conditions, 'recursive' => -1)) != false);
}
/**
* Returns a result set array.
*
@ -1895,8 +1907,10 @@ class Model extends Overloadable {
* - If three fields are specified, they are used (in order) for key, value and group.
* - Otherwise, first and second fields are used for key and value.
*
* @param array $conditions SQL conditions array, or type of find operation (all / first / count / neighbors / list / threaded)
* @param mixed $fields Either a single string of a field name, or an array of field names, or options for matching
* @param array $conditions SQL conditions array, or type of find operation (all / first / count /
* neighbors / list / threaded)
* @param mixed $fields Either a single string of a field name, or an array of field names, or
* options for matching
* @param string $order SQL ORDER BY conditions (e.g. "price DESC" or "name ASC")
* @param integer $recursive The number of levels deep to fetch associated records
* @return array Array of records
@ -1974,6 +1988,7 @@ class Model extends Overloadable {
}
}
}
/**
* Handles the before/after filter logic for find('first') operations. Only called by Model::find().
*
@ -1998,6 +2013,7 @@ class Model extends Overloadable {
return $results[0];
}
}
/**
* Handles the before/after filter logic for find('count') operations. Only called by Model::find().
*
@ -2029,6 +2045,7 @@ class Model extends Overloadable {
return false;
}
}
/**
* Handles the before/after filter logic for find('list') operations. Only called by Model::find().
*
@ -2087,6 +2104,7 @@ class Model extends Overloadable {
return Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
}
}
/**
* Detects the previous field's value, then uses logic to find the 'wrapping'
* rows and return them.
@ -2145,6 +2163,7 @@ class Model extends Overloadable {
return $return;
}
}
/**
* In the event of ambiguous results returned (multiple top level results, with different parent_ids)
* top level results with different parent_ids to the first result will be dropped
@ -2191,6 +2210,7 @@ class Model extends Overloadable {
return $return;
}
}
/**
* Passes query results through model and behavior afterFilter() methods.
*
@ -2206,6 +2226,7 @@ class Model extends Overloadable {
}
return $this->afterFind($results, $primary);
}
/**
* Called only when bindTo<ModelName>() is used.
* This resets the association arrays for the model back
@ -2234,6 +2255,7 @@ class Model extends Overloadable {
$this->__backAssociation = array();
return true;
}
/**
* Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
*
@ -2276,6 +2298,7 @@ class Model extends Overloadable {
}
return ($this->find('count', array('conditions' => $fields, 'recursive' => -1)) == 0);
}
/**
* Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
*
@ -2289,6 +2312,7 @@ class Model extends Overloadable {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
return call_user_func_array(array(&$db, 'query'), $params);
}
/**
* Returns true if all fields pass validation.
*
@ -2304,6 +2328,7 @@ class Model extends Overloadable {
}
return $errors;
}
/**
* Returns an array of fields that have failed validation.
*
@ -2454,6 +2479,7 @@ class Model extends Overloadable {
$this->validate = $_validate;
return $this->validationErrors;
}
/**
* Marks a field as invalid, optionally setting the name of validation
* rule (in case of multiple validation for field) that was broken.
@ -2469,6 +2495,7 @@ class Model extends Overloadable {
}
$this->validationErrors[$field] = $value;
}
/**
* Returns true if given field name is a foreign key in this model.
*
@ -2485,6 +2512,7 @@ class Model extends Overloadable {
}
return in_array($field, $foreignKeys);
}
/**
* Returns the display field for this model.
*
@ -2495,6 +2523,7 @@ class Model extends Overloadable {
function getDisplayField() {
return $this->displayField;
}
/**
* Escapes the field name and prepends the model name. Escaping is done according to the current database driver's rules.
*
@ -2516,6 +2545,7 @@ class Model extends Overloadable {
}
return $db->name($alias . '.' . $field);
}
/**
* Returns the current record's ID
*
@ -2548,6 +2578,7 @@ class Model extends Overloadable {
return false;
}
/**
* Returns the ID of the last record this model inserted.
*
@ -2557,6 +2588,7 @@ class Model extends Overloadable {
function getLastInsertID() {
return $this->getInsertID();
}
/**
* Returns the ID of the last record this model inserted.
*
@ -2566,6 +2598,7 @@ class Model extends Overloadable {
function getInsertID() {
return $this->__insertID;
}
/**
* Sets the ID of the last record this model inserted
*
@ -2659,7 +2692,12 @@ class Model extends Overloadable {
}
return array_keys($this->{$type});
} else {
$assoc = array_merge($this->hasOne, $this->hasMany, $this->belongsTo, $this->hasAndBelongsToMany);
$assoc = array_merge(
$this->hasOne,
$this->hasMany,
$this->belongsTo,
$this->hasAndBelongsToMany
);
if (array_key_exists($type, $assoc)) {
foreach ($this->__associations as $a) {
if (isset($this->{$a}[$type])) {
@ -2673,7 +2711,8 @@ class Model extends Overloadable {
}
}
/**
* Gets the name and fields to be used by a join model. This allows specifying join fields in the association definition.
* Gets the name and fields to be used by a join model. This allows specifying join fields
* in the association definition.
*
* @param object $model The model to be joined
* @param mixed $with The 'with' key of the model association
@ -2687,16 +2726,19 @@ class Model extends Overloadable {
} elseif (is_array($assoc)) {
$with = key($assoc);
return array($with, array_unique(array_merge($assoc[$with], $keys)));
} else {
trigger_error(sprintf(__('Invalid join model settings in %s', true), $model->alias), E_USER_WARNING);
}
trigger_error(
sprintf(__('Invalid join model settings in %s', true), $model->alias),
E_USER_WARNING
);
}
/**
* Called before each find operation. Return false if you want to halt the find
* call, otherwise return the (modified) query data.
*
* @param array $queryData Data used to execute this query, i.e. conditions, order, etc.
* @return mixed true if the operation should continue, false if it should abort; or, modified $queryData to continue with new $queryData
* @return mixed true if the operation should continue, false if it should abort; or, modified
* $queryData to continue with new $queryData
* @access public
* @link http://book.cakephp.org/view/680/beforeFind
*/
@ -2737,7 +2779,7 @@ class Model extends Overloadable {
function afterSave($created) {
}
/**
* Called after every deletion operation.
* Called before every deletion operation.
*
* @param boolean $cascade If true records that depend on this record will also be deleted
* @return boolean True if the operation should continue, false if it should abort
@ -2823,43 +2865,6 @@ class Model extends Overloadable {
*/
function __wakeup() {
}
/**
* @deprecated
* @see Model::find('all')
*/
function findAll($conditions = null, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) {
//trigger_error(__('(Model::findAll) Deprecated, use Model::find("all")', true), E_USER_WARNING);
return $this->find('all', compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'));
}
/**
* @deprecated
* @see Model::find('count')
*/
function findCount($conditions = null, $recursive = 0) {
//trigger_error(__('(Model::findCount) Deprecated, use Model::find("count")', true), E_USER_WARNING);
return $this->find('count', compact('conditions', 'recursive'));
}
/**
* @deprecated
* @see Model::find('threaded')
*/
function findAllThreaded($conditions = null, $fields = null, $order = null) {
//trigger_error(__('(Model::findAllThreaded) Deprecated, use Model::find("threaded")', true), E_USER_WARNING);
return $this->find('threaded', compact('conditions', 'fields', 'order'));
}
/**
* @deprecated
* @see Model::find('neighbors')
*/
function findNeighbours($conditions = null, $field, $value) {
//trigger_error(__('(Model::findNeighbours) Deprecated, use Model::find("neighbors")', true), E_USER_WARNING);
$query = compact('conditions', 'field', 'value');
$query['fields'] = $field;
if (is_array($field)) {
$query['field'] = $field[0];
}
return $this->find('neighbors', $query);
}
}
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
Overloadable::overload('Model');

View file

@ -593,7 +593,7 @@ class Router extends Object {
$params = array('prefix' => $this->__admin, $this->__admin => true);
}
if ($plugins = Configure::listObjects('plugin')) {
if ($plugins = App::objects('plugin')) {
foreach ($plugins as $key => $value) {
$plugins[$key] = Inflector::underscore($value);
}

View file

@ -918,7 +918,7 @@ class Set extends Object {
* to null (useful for Set::merge). You can optionally group the values by what is obtained when
* following the path specified in $groupPath.
*
* @param array $data Array from where to extract keys and values
* @param mixed $data Array or object from where to extract keys and values
* @param mixed $path1 As an array, or as a dot-separated string.
* @param mixed $path2 As an array, or as a dot-separated string.
* @param string $groupPath As an array, or as a dot-separated string.

View file

@ -1,27 +1,22 @@
<?php
/* SVN FILE: $Id$ */
/**
* String handling methods.
*
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.cake.libs
* @since CakePHP(tm) v 1.2.0.5551
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* String handling methods.
@ -59,7 +54,9 @@ class String extends Object {
if (strpos($node, ':') !== false) {
if (substr_count($node, '::')) {
$node = str_replace('::', str_repeat(':0000', 8 - substr_count($node, ':')) . ':', $node);
$node = str_replace(
'::', str_repeat(':0000', 8 - substr_count($node, ':')) . ':', $node
);
}
$node = explode(':', $node) ;
$ipv6 = '' ;
@ -111,14 +108,16 @@ class String extends Object {
}
list($timeMid, $timeLow) = explode(' ', microtime());
$uuid = sprintf("%08x-%04x-%04x-%02x%02x-%04x%08x", (int)$timeLow, (int)substr($timeMid, 2) & 0xffff,
mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3f) | 0x80, mt_rand(0, 0xff), $pid, $node);
$uuid = sprintf(
"%08x-%04x-%04x-%02x%02x-%04x%08x", (int)$timeLow, (int)substr($timeMid, 2) & 0xffff,
mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3f) | 0x80, mt_rand(0, 0xff), $pid, $node
);
return $uuid;
}
/**
* Tokenizes a string using $separator, ignoring any instance of $separator that appears between $leftBound
* and $rightBound
* Tokenizes a string using $separator, ignoring any instance of $separator that appears between
* $leftBound and $rightBound
*
* @param string $data The data to tokenize
* @param string $separator The token to split the data on
@ -140,7 +139,11 @@ class String extends Object {
while ($offset <= $length) {
$tmpOffset = -1;
$offsets = array(strpos($data, $separator, $offset), strpos($data, $leftBound, $offset), strpos($data, $rightBound, $offset));
$offsets = array(
strpos($data, $separator, $offset),
strpos($data, $leftBound, $offset),
strpos($data, $rightBound, $offset)
);
for ($i = 0; $i < 3; $i++) {
if ($offsets[$i] !== false && ($offsets[$i] < $tmpOffset || $tmpOffset == -1)) {
$tmpOffset = $offsets[$i];
@ -190,21 +193,22 @@ class String extends Object {
return $data;
}
/**
* Replaces variable placeholders inside a $str with any given $data. Each key in the $data array corresponds to a variable
* placeholder name in $str. Example:
*
* Sample: String::insert('My name is :name and I am :age years old.', array('name' => 'Bob', '65'));
* Returns: My name is Bob and I am 65 years old.
* Replaces variable placeholders inside a $str with any given $data. Each key in the $data array
* corresponds to a variable placeholder name in $str.
* Example: String::insert(':name is :age years old.', array('name' => 'Bob', '65'));
* Returns: Bob is 65 years old.
*
* Available $options are:
* before: The character or string in front of the name of the variable placeholder (Defaults to ':')
* after: The character or string after the name of the variable placeholder (Defaults to null)
* escape: The character or string used to escape the before character / string (Defaults to '\')
* format: A regex to use for matching variable placeholders. Default is: '/(?<!\\)\:%s/' (Overwrites before, after, breaks escape / clean)
* format: A regex to use for matching variable placeholders. Default is: '/(?<!\\)\:%s/'
* (Overwrites before, after, breaks escape / clean)
* clean: A boolean or array with instructions for String::cleanInsert
*
* @param string $str A string containing variable placeholders
* @param string $data A key => val array where each key stands for a placeholder variable name to be replaced with val
* @param string $data A key => val array where each key stands for a placeholder variable name
* to be replaced with val
* @param string $options An array of options, see description above
* @return string
* @access public
@ -237,6 +241,8 @@ class String extends Object {
$str = substr_replace($str, $val, $pos, 1);
}
} else {
asort($data);
$hashKeys = array_map('md5', array_keys($data));
$tempData = array_combine(array_keys($data), array_values($hashKeys));
foreach ($tempData as $key => $hashVal) {
@ -245,6 +251,9 @@ class String extends Object {
}
$dataReplacements = array_combine($hashKeys, array_values($data));
foreach ($dataReplacements as $tmpHash => $data) {
if (is_array($data)) {
$data = '';
}
$str = str_replace($tmpHash, $data, $str);
}
}
@ -258,15 +267,17 @@ class String extends Object {
return String::cleanInsert($str, $options);
}
/**
* Cleans up a Set::insert formated string with given $options depending on the 'clean' key in $options. The default method used is
* text but html is also available. The goal of this function is to replace all whitespace and uneeded markup around placeholders
* that did not get replaced by Set::insert.
* Cleans up a Set::insert formated string with given $options depending on the 'clean' key in
* $options. The default method used is text but html is also available. The goal of this function
* is to replace all whitespace and uneeded markup around placeholders that did not get replaced
* by Set::insert.
*
* @param string $str
* @param string $options
* @return string
* @access public
* @static
* @see Set::insert()
*/
function cleanInsert($str, $options) {
$clean = $options['clean'];

View file

@ -798,6 +798,7 @@ class Validation extends Object {
* an optional fragment (anchor tag)
*
* @param string $check Value to check
* @param boolean $strict Require URL to be prefixed by a valid scheme (one of http(s)/ftp(s)/file/news/gopher)
* @return boolean Success
* @access public
*/
@ -925,4 +926,4 @@ class Validation extends Object {
$this->errors = array();
}
}
?>
?>

View file

@ -591,7 +591,7 @@ class Helper extends Overloadable {
if (is_array($result)) {
$view =& ClassRegistry::getObject('view');
if (isset($result[$view->fieldSuffix])) {
if (array_key_exists($view->fieldSuffix, $result)) {
$result = $result[$view->fieldSuffix];
}
}

View file

@ -81,7 +81,8 @@ class AjaxHelper extends AppHelper {
*/
var $dragOptions = array(
'handle', 'revert', 'snap', 'zindex', 'constraint', 'change', 'ghosting',
'starteffect', 'reverteffect', 'endeffect'
'starteffect', 'reverteffect', 'endeffect', 'scroll', 'scrollSensitivity',
'onStart', 'onDrag', 'onEnd'
);
/**
* Options for droppable.

View file

@ -264,7 +264,8 @@ class CacheHelper extends AppHelper {
$controller->params = $this->params = unserialize(stripslashes(\'' . addslashes(serialize($this->params)) . '\'));
$controller->action = $this->action = unserialize(\'' . serialize($this->action) . '\');
$controller->data = $this->data = unserialize(stripslashes(\'' . addslashes(serialize($this->data)) . '\'));
$controller->themeWeb = $this->themeWeb = \'' . $this->themeWeb . '\';';
$controller->themeWeb = $this->themeWeb = \'' . $this->themeWeb . '\';
Router::setRequestInfo(array($this->params, array(\'base\' => $this->base, \'webroot\' => $this->webroot)));';
if ($useCallbacks == true) {
$file .= '
@ -275,7 +276,6 @@ class CacheHelper extends AppHelper {
}
$file .= '
Router::setRequestInfo(array($this->params, array(\'base\' => $this->base, \'webroot\' => $this->webroot)));
$loadedHelpers = array();
$loadedHelpers = $this->_loadHelpers($loadedHelpers, $this->helpers);
foreach (array_keys($loadedHelpers) as $helper) {

View file

@ -563,7 +563,8 @@ class FormHelper extends AppHelper {
/**
* Generates a form input element complete with label and wrapper div
*
* Options - See each field type method for more information.
* Options - See each field type method for more information. Any options that are part of
* $attributes or $options for the different type methods can be included in $options for input().
*
* - 'type' - Force the type of widget you want. e.g. ```type => 'select'```
* - 'label' - control the label
@ -852,11 +853,14 @@ class FormHelper extends AppHelper {
} elseif (!empty($value) && $value === $options['value']) {
$options['checked'] = 'checked';
}
$output = $this->hidden($fieldName, array(
$hiddenOptions = array(
'id' => $options['id'] . '_', 'name' => $options['name'],
'value' => '0', 'secure' => false
));
);
if (isset($options['disabled']) && $options['disabled'] == true) {
$hiddenOptions['disabled'] = 'disabled';
}
$output = $this->hidden($fieldName, $hiddenOptions);
return $this->output($output . sprintf(
$this->Html->tags['checkbox'],
@ -935,7 +939,7 @@ class FormHelper extends AppHelper {
if (!isset($value) || $value === '') {
$hidden = $this->hidden($fieldName, array(
'id' => $attributes['id'] . '_', 'value' => ''
'id' => $attributes['id'] . '_', 'value' => '', 'name' => $attributes['name']
));
}
$out = $hidden . join($inbetween, $out);

View file

@ -325,8 +325,10 @@ class HtmlHelper extends AppHelper {
/**
* Creates a link element for CSS stylesheets.
*
* @param mixed $path The name of a CSS style sheet in /app/webroot/css, or an array containing names of CSS stylesheets in that directory.
* @param string $rel Rel attribute. Defaults to "stylesheet".
* @param mixed $path The name of a CSS style sheet or an array containing names of
* CSS stylesheets. If `$path` is prefixed with '/', the path will be relative to the webroot
* of your application. Otherwise, the path will be relative to your CSS path, usually webroot/css.
* @param string $rel Rel attribute. Defaults to "stylesheet". If equal to 'import' the stylesheet will be imported.
* @param array $htmlAttributes Array of HTML attributes.
* @param boolean $inline If set to false, the generated tag appears in the head tag of the layout.
* @return string CSS <link /> or <style /> tag, depending on the type of link.

View file

@ -319,8 +319,104 @@ class JavascriptHelper extends AppHelper {
* @return string Escaped string.
*/
function escapeString($string) {
$escape = array("\r\n" => '\n', "\r" => '\n', "\n" => '\n', '"' => '\"', "'" => "\\'");
return str_replace(array_keys($escape), array_values($escape), $string);
App::import('Core', 'Multibyte');
$escape = array("\r\n" => "\n", "\r" => "\n");
$string = str_replace(array_keys($escape), array_values($escape), $string);
return $this->_utf8ToHex($string);
}
/**
* Encode a string into JSON. Converts and escapes necessary characters.
*
* @return void
**/
function _utf8ToHex($string) {
$length = strlen($string);
$return = '';
for ($i = 0; $i < $length; ++$i) {
$ord = ord($string{$i});
switch (true) {
case $ord == 0x08:
$return .= '\b';
break;
case $ord == 0x09:
$return .= '\t';
break;
case $ord == 0x0A:
$return .= '\n';
break;
case $ord == 0x0C:
$return .= '\f';
break;
case $ord == 0x0D:
$return .= '\r';
break;
case $ord == 0x22:
case $ord == 0x2F:
case $ord == 0x5C:
case $ord == 0x27:
$return .= '\\' . $string{$i};
break;
case (($ord >= 0x20) && ($ord <= 0x7F)):
$return .= $string{$i};
break;
case (($ord & 0xE0) == 0xC0):
if ($i + 1 >= $length) {
$i += 1;
$return .= '?';
break;
}
$charbits = $string{$i} . $string{$i + 1};
$char = Multibyte::utf8($charbits);
$return .= sprintf('\u%04s', dechex($char[0]));
$i += 1;
break;
case (($ord & 0xF0) == 0xE0):
if ($i + 2 >= $length) {
$i += 2;
$return .= '?';
break;
}
$charbits = $string{$i} . $string{$i + 1} . $string{$i + 2};
$char = Multibyte::utf8($charbits);
$return .= sprintf('\u%04s', dechex($char[0]));
$i += 2;
break;
case (($ord & 0xF8) == 0xF0):
if ($i + 3 >= $length) {
$i += 3;
$return .= '?';
break;
}
$charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3};
$char = Multibyte::utf8($charbits);
$return .= sprintf('\u%04s', dechex($char[0]));
$i += 3;
break;
case (($ord & 0xFC) == 0xF8):
if ($i + 4 >= $length) {
$i += 4;
$return .= '?';
break;
}
$charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4};
$char = Multibyte::utf8($charbits);
$return .= sprintf('\u%04s', dechex($char[0]));
$i += 4;
break;
case (($ord & 0xFE) == 0xFC):
if ($i + 5 >= $length) {
$i += 5;
$return .= '?';
break;
}
$charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4} . $string{$i + 5};
$char = Multibyte::utf8($charbits);
$return .= sprintf('\u%04s', dechex($char[0]));
$i += 5;
break;
}
}
return $return;
}
/**
* Attach an event to an element. Used with the Prototype library.

View file

@ -1,26 +1,21 @@
<?php
/* SVN FILE: $Id$ */
/**
* Pagination Helper class file.
*
* Generates pagination links
*
* CakePHP(tm) : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.cake.libs.view.helpers
* @since CakePHP(tm) v 1.2.0
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Pagination Helper class for easy generation of pagination links.
@ -105,7 +100,9 @@ class PaginatorHelper extends AppHelper {
if (!isset($this->params['paging'][$model])) {
$this->params['paging'][$model] = array();
}
$this->params['paging'][$model] = array_merge($this->params['paging'][$model], $options[$model]);
$this->params['paging'][$model] = array_merge(
$this->params['paging'][$model], $options[$model]
);
unset($options[$model]);
}
$this->options = array_filter(array_merge($this->options, $options));
@ -140,7 +137,9 @@ class PaginatorHelper extends AppHelper {
if (isset($options['sort']) && !empty($options['sort'])) {
if (preg_match('/(?:\w+\.)?(\w+)/', $options['sort'], $result) && isset($result[1])) {
return $result[1];
if ($result[0] == $this->defaultModel()) {
return $result[1];
}
}
return $options['sort'];
} elseif (isset($options['order']) && is_array($options['order'])) {
@ -149,6 +148,7 @@ class PaginatorHelper extends AppHelper {
if (preg_match('/(?:\w+\.)?(\w+)/', $options['order'], $result) && isset($result[1])) {
return $result[1];
}
return $options['order'];
}
return null;
}
@ -222,8 +222,10 @@ class PaginatorHelper extends AppHelper {
$title = __(Inflector::humanize(preg_replace('/_id$/', '', $title)), true);
}
$dir = 'asc';
$sortKey = $this->sortKey($options['model']);
$isSorted = ($sortKey === $key);
if ($this->sortKey($options['model']) == $key && $this->sortDir($options['model']) == 'asc') {
if ($isSorted && $this->sortDir($options['model']) === 'asc') {
$dir = 'desc';
}
if (is_array($title) && array_key_exists($dir, $title)) {
@ -270,7 +272,9 @@ class PaginatorHelper extends AppHelper {
*/
function url($options = array(), $asArray = false, $model = null) {
$paging = $this->params($model);
$url = array_merge(array_filter(Set::diff(array_merge($paging['defaults'], $paging['options']), $paging['defaults'])), $options);
$url = array_merge(array_filter(Set::diff(array_merge(
$paging['defaults'], $paging['options']), $paging['defaults'])), $options
);
if (isset($url['order'])) {
$sort = $direction = null;
@ -416,7 +420,8 @@ class PaginatorHelper extends AppHelper {
if (!is_array($options['separator'])) {
$options['separator'] = array(' - ', $options['separator']);
}
$out = $start . $options['separator'][0] . $end . $options['separator'][1] . $paging['count'];
$out = $start . $options['separator'][0] . $end . $options['separator'][1];
$out .= $paging['count'];
break;
case 'pages':
$out = $paging['page'] . $options['separator'] . $paging['pageCount'];
@ -497,7 +502,8 @@ class PaginatorHelper extends AppHelper {
$out .= $before;
for ($i = $start; $i < $params['page']; $i++) {
$out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options)) . $separator;
$out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options))
. $separator;
}
$out .= $this->Html->tag($tag, $params['page'], array('class' => 'current'));
@ -507,7 +513,8 @@ class PaginatorHelper extends AppHelper {
$start = $params['page'] + 1;
for ($i = $start; $i < $end; $i++) {
$out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options)). $separator;
$out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options))
. $separator;
}
if ($end != $params['page']) {
@ -583,7 +590,8 @@ class PaginatorHelper extends AppHelper {
}
$out .= $after;
} elseif ($params['page'] > 1) {
$out = $this->Html->tag($tag, $this->link($first, array('page' => 1), $options)) . $after;
$out = $this->Html->tag($tag, $this->link($first, array('page' => 1), $options))
. $after;
}
return $out;
}
@ -629,7 +637,9 @@ class PaginatorHelper extends AppHelper {
}
$out = $before . $out;
} elseif ($params['page'] < $params['pageCount']) {
$out = $before . $this->Html->tag($tag, $this->link($last, array('page' => $params['pageCount']), $options));
$out = $before . $this->Html->tag(
$tag, $this->link($last, array('page' => $params['pageCount']), $options
));
}
return $out;
}

View file

@ -25,23 +25,23 @@
<div class="<?php echo $pluralVar;?> form">
<?php
echo $form->create();
echo $form->inputs(null, array('created', 'modified', 'updated'));
echo $form->inputs($scaffoldFields, array('created', 'modified', 'updated'));
echo $form->end(__('Submit', true));
?>
</div>
<div class="actions">
<ul>
<?php if ($this->action != 'add'):?>
<li><?php echo $html->link(__('Delete', true), array('action'=>'delete', $form->value($modelClass.'.'.$primaryKey)), null, __('Are you sure you want to delete', true).' #' . $form->value($modelClass.'.'.$primaryKey)); ?></li>
<li><?php echo $html->link(__('Delete', true), array('action' => 'delete', $form->value($modelClass.'.'.$primaryKey)), null, __('Are you sure you want to delete', true).' #' . $form->value($modelClass.'.'.$primaryKey)); ?></li>
<?php endif;?>
<li><?php echo $html->link(__('List', true).' '.$pluralHumanName, array('action'=>'index'));?></li>
<li><?php echo $html->link(__('List', true).' '.$pluralHumanName, array('action' => 'index'));?></li>
<?php
$done = array();
foreach ($associations as $_type => $_data) {
foreach ($_data as $_alias => $_details) {
if ($_details['controller'] != $this->name && !in_array($_details['controller'], $done)) {
echo "\t\t<li>".$html->link(sprintf(__('List %s', true), Inflector::humanize($_details['controller'])), array('controller'=> $_details['controller'], 'action'=>'index'))."</li>\n";
echo "\t\t<li>".$html->link(sprintf(__('New %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller'=> $_details['controller'], 'action'=>'add'))."</li>\n";
echo "\t\t<li>".$html->link(sprintf(__('List %s', true), Inflector::humanize($_details['controller'])), array('controller' => $_details['controller'], 'action' =>'index'))."</li>\n";
echo "\t\t<li>".$html->link(sprintf(__('New %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller' => $_details['controller'], 'action' =>'add'))."</li>\n";
$done[] = $_details['controller'];
}
}

View file

@ -51,7 +51,7 @@ echo "\n";
foreach ($associations['belongsTo'] as $_alias => $_details) {
if ($_field === $_details['foreignKey']) {
$isKey = true;
echo "\t\t<td>\n\t\t\t" . $html->link(${$singularVar}[$_alias][$_details['displayField']], array('controller'=> $_details['controller'], 'action'=>'view', ${$singularVar}[$_alias][$_details['primaryKey']])) . "\n\t\t</td>\n";
echo "\t\t<td>\n\t\t\t" . $html->link(${$singularVar}[$_alias][$_details['displayField']], array('controller' => $_details['controller'], 'action' => 'view', ${$singularVar}[$_alias][$_details['primaryKey']])) . "\n\t\t</td>\n";
break;
}
}
@ -62,9 +62,9 @@ echo "\n";
}
echo "\t\t<td class=\"actions\">\n";
echo "\t\t\t" . $html->link(__('View', true), array('action'=>'view', ${$singularVar}[$modelClass][$primaryKey])) . "\n";
echo "\t\t\t" . $html->link(__('Edit', true), array('action'=>'edit', ${$singularVar}[$modelClass][$primaryKey])) . "\n";
echo "\t\t\t" . $html->link(__('Delete', true), array('action'=>'delete', ${$singularVar}[$modelClass][$primaryKey]), null, __('Are you sure you want to delete', true).' #' . ${$singularVar}[$modelClass][$primaryKey]) . "\n";
echo "\t\t\t" . $html->link(__('View', true), array('action' => 'view', ${$singularVar}[$modelClass][$primaryKey])) . "\n";
echo "\t\t\t" . $html->link(__('Edit', true), array('action' => 'edit', ${$singularVar}[$modelClass][$primaryKey])) . "\n";
echo "\t\t\t" . $html->link(__('Delete', true), array('action' => 'delete', ${$singularVar}[$modelClass][$primaryKey]), null, __('Are you sure you want to delete', true).' #' . ${$singularVar}[$modelClass][$primaryKey]) . "\n";
echo "\t\t</td>\n";
echo "\t</tr>\n";
@ -74,20 +74,20 @@ echo "\n";
</table>
</div>
<div class="paging">
<?php echo "\t" . $paginator->prev('<< ' . __('previous', true), array(), null, array('class'=>'disabled')) . "\n";?>
<?php echo "\t" . $paginator->prev('<< ' . __('previous', true), array(), null, array('class' => 'disabled')) . "\n";?>
| <?php echo $paginator->numbers() . "\n"?>
<?php echo "\t ". $paginator->next(__('next', true) .' >>', array(), null, array('class'=>'disabled')) . "\n";?>
<?php echo "\t ". $paginator->next(__('next', true) .' >>', array(), null, array('class' => 'disabled')) . "\n";?>
</div>
<div class="actions">
<ul>
<li><?php echo $html->link('New '.$singularHumanName, array('action'=>'add')); ?></li>
<li><?php echo $html->link('New '.$singularHumanName, array('action' => 'add')); ?></li>
<?php
$done = array();
foreach ($associations as $_type => $_data) {
foreach ($_data as $_alias => $_details) {
if ($_details['controller'] != $this->name && !in_array($_details['controller'], $done)) {
echo "\t\t<li>".$html->link(sprintf(__('List %s', true), Inflector::humanize($_details['controller'])), array('controller'=> $_details['controller'], 'action'=>'index'))."</li>\n";
echo "\t\t<li>".$html->link(sprintf(__('New %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller'=> $_details['controller'], 'action'=>'add'))."</li>\n";
echo "\t\t<li>".$html->link(sprintf(__('List %s', true), Inflector::humanize($_details['controller'])), array('controller' => $_details['controller'], 'action' => 'index'))."</li>\n";
echo "\t\t<li>".$html->link(sprintf(__('New %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller' => $_details['controller'], 'action' => 'add'))."</li>\n";
$done[] = $_details['controller'];
}
}

View file

@ -38,7 +38,7 @@ foreach ($scaffoldFields as $_field) {
if ($_field === $_details['foreignKey']) {
$isKey = true;
echo "\t\t<dt{$class}>".Inflector::humanize($_alias)."</dt>\n";
echo "\t\t<dd{$class}>\n\t\t\t" . $html->link(${$singularVar}[$_alias][$_details['displayField']], array('controller'=> $_details['controller'], 'action'=>'view', ${$singularVar}[$_alias][$_details['primaryKey']])) . "\n\t\t&nbsp;</dd>\n";
echo "\t\t<dd{$class}>\n\t\t\t" . $html->link(${$singularVar}[$_alias][$_details['displayField']], array('controller' => $_details['controller'], 'action' => 'view', ${$singularVar}[$_alias][$_details['primaryKey']])) . "\n\t\t&nbsp;</dd>\n";
break;
}
}
@ -54,17 +54,17 @@ foreach ($scaffoldFields as $_field) {
<div class="actions">
<ul>
<?php
echo "\t\t<li>" .$html->link(sprintf(__('Edit %s', true), $singularHumanName), array('action'=>'edit', ${$singularVar}[$modelClass][$primaryKey])). " </li>\n";
echo "\t\t<li>" .$html->link(sprintf(__('Delete %s', true), $singularHumanName), array('action'=>'delete', ${$singularVar}[$modelClass][$primaryKey]), null, __('Are you sure you want to delete', true).' #' . ${$singularVar}[$modelClass][$primaryKey] . '?'). " </li>\n";
echo "\t\t<li>" .$html->link(sprintf(__('List %s', true), $pluralHumanName), array('action'=>'index')). " </li>\n";
echo "\t\t<li>" .$html->link(sprintf(__('New %s', true), $singularHumanName), array('action'=>'add')). " </li>\n";
echo "\t\t<li>" .$html->link(sprintf(__('Edit %s', true), $singularHumanName), array('action' => 'edit', ${$singularVar}[$modelClass][$primaryKey])). " </li>\n";
echo "\t\t<li>" .$html->link(sprintf(__('Delete %s', true), $singularHumanName), array('action' => 'delete', ${$singularVar}[$modelClass][$primaryKey]), null, __('Are you sure you want to delete', true).' #' . ${$singularVar}[$modelClass][$primaryKey] . '?'). " </li>\n";
echo "\t\t<li>" .$html->link(sprintf(__('List %s', true), $pluralHumanName), array('action' => 'index')). " </li>\n";
echo "\t\t<li>" .$html->link(sprintf(__('New %s', true), $singularHumanName), array('action' => 'add')). " </li>\n";
$done = array();
foreach ($associations as $_type => $_data) {
foreach ($_data as $_alias => $_details) {
if ($_details['controller'] != $this->name && !in_array($_details['controller'], $done)) {
echo "\t\t<li>".$html->link(sprintf(__('List %s', true), Inflector::humanize($_details['controller'])), array('controller'=> $_details['controller'], 'action'=>'index'))."</li>\n";
echo "\t\t<li>".$html->link(sprintf(__('New %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller'=> $_details['controller'], 'action'=>'add'))."</li>\n";
echo "\t\t<li>".$html->link(sprintf(__('List %s', true), Inflector::humanize($_details['controller'])), array('controller' => $_details['controller'], 'action' => 'index'))."</li>\n";
echo "\t\t<li>".$html->link(sprintf(__('New %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller' => $_details['controller'], 'action' => 'add'))."</li>\n";
$done[] = $_details['controller'];
}
}
@ -95,7 +95,7 @@ foreach ($associations['hasOne'] as $_alias => $_details): ?>
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $html->link(sprintf(__('Edit %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller'=> $_details['controller'], 'action'=>'edit', ${$singularVar}[$_alias][$_details['primaryKey']]))."</li>\n";?>
<li><?php echo $html->link(sprintf(__('Edit %s', true), Inflector::humanize(Inflector::underscore($_alias))), array('controller' => $_details['controller'], 'action' => 'edit', ${$singularVar}[$_alias][$_details['primaryKey']]))."</li>\n";?>
</ul>
</div>
</div>
@ -141,9 +141,9 @@ $otherSingularVar = Inflector::variable($_alias);
}
echo "\t\t\t<td class=\"actions\">\n";
echo "\t\t\t\t" . $html->link(__('View', true), array('controller'=> $_details['controller'], 'action'=>'view', ${$otherSingularVar}[$_details['primaryKey']])). "\n";
echo "\t\t\t\t" . $html->link(__('Edit', true), array('controller'=> $_details['controller'], 'action'=>'edit', ${$otherSingularVar}[$_details['primaryKey']])). "\n";
echo "\t\t\t\t" . $html->link(__('Delete', true), array('controller'=> $_details['controller'], 'action'=>'delete', ${$otherSingularVar}[$_details['primaryKey']]), null, __('Are you sure you want to delete', true).' #' . ${$otherSingularVar}[$_details['primaryKey']] . '?'). "\n";
echo "\t\t\t\t" . $html->link(__('View', true), array('controller' => $_details['controller'], 'action' => 'view', ${$otherSingularVar}[$_details['primaryKey']])). "\n";
echo "\t\t\t\t" . $html->link(__('Edit', true), array('controller' => $_details['controller'], 'action' => 'edit', ${$otherSingularVar}[$_details['primaryKey']])). "\n";
echo "\t\t\t\t" . $html->link(__('Delete', true), array('controller' => $_details['controller'], 'action' => 'delete', ${$otherSingularVar}[$_details['primaryKey']]), null, __('Are you sure you want to delete', true).' #' . ${$otherSingularVar}[$_details['primaryKey']] . '?'). "\n";
echo "\t\t\t</td>\n";
echo "\t\t</tr>\n";
endforeach;
@ -152,7 +152,7 @@ $otherSingularVar = Inflector::variable($_alias);
<?php endif; ?>
<div class="actions">
<ul>
<li><?php echo $html->link(sprintf(__("New %s", true), Inflector::humanize(Inflector::underscore($_alias))), array('controller'=> $_details['controller'], 'action'=>'add'));?> </li>
<li><?php echo $html->link(sprintf(__("New %s", true), Inflector::humanize(Inflector::underscore($_alias))), array('controller' => $_details['controller'], 'action' => 'add'));?> </li>
</ul>
</div>
</div>

View file

@ -800,7 +800,7 @@ class View extends Object {
}
}
$paths = $this->_paths($this->plugin);
$paths = $this->_paths(Inflector::underscore($this->plugin));
foreach ($paths as $path) {
if (file_exists($path . $name . $this->ext)) {
@ -814,7 +814,7 @@ class View extends Object {
$defaultPath = $paths[0];
if ($this->plugin) {
$pluginPaths = Configure::read('pluginPaths');
$pluginPaths = App::path('plugins');
foreach ($paths as $path) {
if (strpos($path, $pluginPaths[0]) === 0) {
$defaultPath = $path;
@ -840,7 +840,7 @@ class View extends Object {
if (!is_null($this->layoutPath)) {
$subDir = $this->layoutPath . DS;
}
$paths = $this->_paths($this->plugin);
$paths = $this->_paths(Inflector::underscore($this->plugin));
$file = 'layouts' . DS . $subDir . $name;
$exts = array($this->ext, '.ctp', '.thtml');
@ -890,14 +890,14 @@ class View extends Object {
return $this->__paths;
}
$paths = array();
$viewPaths = Configure::read('viewPaths');
$viewPaths = App::path('views');
if ($plugin !== null) {
$count = count($viewPaths);
for ($i = 0; $i < $count; $i++) {
$paths[] = $viewPaths[$i] . 'plugins' . DS . $plugin . DS;
}
$pluginPaths = Configure::read('pluginPaths');
$pluginPaths = App::path('plugins');
$count = count($pluginPaths);
for ($i = 0; $i < $count; $i++) {

View file

@ -607,6 +607,9 @@ class XmlNode extends Object {
if (is_array($this->attributes) && count($this->attributes) > 0) {
foreach ($this->attributes as $key => $val) {
if (is_bool($val) && $val === false) {
$val = 0;
}
$d .= ' ' . $key . '="' . htmlspecialchars($val, ENT_QUOTES, Configure::read('App.encoding')) . '"';
}
}
@ -682,6 +685,19 @@ class XmlNode extends Object {
$out[$child->name] = $value;
}
continue;
} elseif (count($child->children) === 0 && $child->value == '') {
$value = $child->attributes;
if (isset($out[$child->name]) || isset($multi[$key])) {
if (!isset($multi[$key])) {
$multi[$key] = array($out[$child->name]);
unset($out[$child->name]);
}
$multi[$key][] = $value;
} else {
$out[$key] = $value;
}
continue;
} else {
$value = $child->toArray($camelize);
}
@ -823,13 +839,19 @@ class Xml extends XmlNode {
$this->{$key} = $options[$key];
}
$this->__tags = $options['tags'];
parent::__construct($options['root']);
parent::__construct('#document');
if ($options['root'] !== '#document') {
$Root = $this->createNode($options['root']);
} else {
$Root =& $this;
}
if (!empty($input)) {
if (is_string($input)) {
$this->load($input);
$Root->load($input);
} elseif (is_array($input) || is_object($input)) {
$this->append($input, $options);
$Root->append($input, $options);
}
}
// if (Configure::read('App.encoding') !== null) {
@ -874,10 +896,11 @@ class Xml extends XmlNode {
*/
function parse() {
$this->__initParser();
$this->__rawData = trim($this->__rawData);
$this->__header = trim(str_replace(
a('<' . '?', '?' . '>'),
a('', ''),
substr(trim($this->__rawData), 0, strpos($this->__rawData, "\n"))
substr($this->__rawData, 0, strpos($this->__rawData, '?' . '>'))
));
xml_parse_into_struct($this->__parser, $this->__rawData, $vals);

View file

@ -40,7 +40,20 @@ class BasicsTest extends CakeTestCase {
* @return void
*/
function setUp() {
Configure::write('localePaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'locale'));
App::build(array(
'locales' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'locale')
));
$this->_language = Configure::read('Config.language');
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
App::build();
Configure::write('Config.language', $this->_language);
}
/**
* testHttpBase method
@ -119,7 +132,7 @@ class BasicsTest extends CakeTestCase {
* @return void
*/
function testUses() {
$this->skipIf(class_exists('Security') || class_exists('Sanitize'), 'Security and/or Sanitize class already loaded');
$this->skipIf(class_exists('Security') || class_exists('Sanitize'), '%s Security and/or Sanitize class already loaded');
$this->assertFalse(class_exists('Security'));
$this->assertFalse(class_exists('Sanitize'));

View file

@ -123,17 +123,15 @@ class ShellDispatcherTest extends UnitTestCase {
* @return void
*/
function setUp() {
if (!isset($this->pluginPaths)) {
$this->pluginPaths = Configure::read('pluginPaths');
$this->shellPaths = Configure::read('shellPaths');
}
Configure::write('pluginPaths', array(
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS
));
Configure::write('shellPaths', array(
CORE_PATH ? CONSOLE_LIBS : ROOT . DS . CONSOLE_LIBS,
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors' . DS . 'shells' . DS
));
App::build(array(
'plugins' => array(
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS
),
'shells' => array(
CORE_PATH ? CONSOLE_LIBS : ROOT . DS . CONSOLE_LIBS,
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors' . DS . 'shells' . DS
)
), true);
}
/**
* tearDown method
@ -142,8 +140,7 @@ class ShellDispatcherTest extends UnitTestCase {
* @return void
*/
function tearDown() {
Configure::write('pluginPaths', $this->pluginPaths);
Configure::write('shellPaths', $this->shellPaths);
App::build();
}
/**
* testParseParams method
@ -408,6 +405,7 @@ class ShellDispatcherTest extends UnitTestCase {
$Dispatcher =& new TestShellDispatcher();
$result = $Dispatcher->shellPaths;
$expected = array(
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS . 'test_plugin' . DS . 'vendors' . DS . 'shells' . DS,
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS . 'test_plugin_two' . DS . 'vendors' . DS . 'shells' . DS,

View file

@ -0,0 +1,128 @@
<?php
/* SVN FILE: $Id$ */
/**
* AclShell Test file
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2006-2008, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2006-2008, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.2.0.7726
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
App::import('Core', 'Shell');
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
if (!class_exists('AclShell')) {
require CAKE . 'console' . DS . 'libs' . DS . 'acl.php';
}
Mock::generatePartial(
'ShellDispatcher', 'TestAclShellMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'AclShell', 'MockAclShell',
array('in', 'out', 'hr', 'createFile')
);
/**
* AclShellTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class AclShellTest extends CakeTestCase {
var $fixtures = array('core.aco', 'core.aro', 'core.aros_aco');
/**
* configure Configure for testcase
*
* @return void
**/
function startCase() {
$this->_aclDb = Configure::read('Acl.database');
$this->_aclClass = Configure::read('Acl.classname');
Configure::write('Acl.database', 'test_suite');
Configure::write('Acl.classname', 'DbAcl');
}
/**
* restore Environment settings
*
* @return void
**/
function endCase() {
Configure::write('Acl.database', $this->_aclDb);
Configure::write('Acl.classname', $this->_aclClass);
}
/**
* setUp method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestAclShellMockShellDispatcher();
$this->Task =& new MockAclShell($this->Dispatcher);
$this->Task->Dispatch = new $this->Dispatcher;
$this->Task->params['datasource'] = 'test_suite';
}
/**
* tearDown method
*
* @return void
* @access public
*/
function endTest() {
ClassRegistry::flush();
}
/**
* test that model.foreign_key output works when looking at acl rows
*
* @return void
**/
function testViewWithModelForeignKeyOutput() {
$this->Task->command = 'view';
$this->Task->startup();
$data = array(
'parent_id' => null,
'model' => 'MyModel',
'foreign_key' => 2,
);
$this->Task->Acl->Aro->create($data);
$this->Task->Acl->Aro->save();
$this->Task->args[0] = 'aro';
$this->Task->expectAt(0, 'out', array('Aro tree:'));
$this->Task->expectAt(1, 'out', array(new PatternExpectation('/\[1\]ROOT/')));
$this->Task->expectAt(3, 'out', array(new PatternExpectation('/\[3\]Gandalf/')));
$this->Task->expectAt(5, 'out', array(new PatternExpectation('/\[5\]MyModel.2/')));
$this->Task->view();
}
}
?>

View file

@ -0,0 +1,118 @@
<?php
/* SVN FILE: $Id$ */
/**
* TestTaskTest file
*
* Test Case for test generation shell task
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://www.cakephp.org)
* Copyright 2006-2008, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2006-2008, Cake Software Foundation, Inc.
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.2.0.7726
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
App::import('Core', 'Shell');
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
if (!class_exists('ApiShell')) {
require CAKE . 'console' . DS . 'libs' . DS . 'api.php';
}
Mock::generatePartial(
'ShellDispatcher', 'ApiShellMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'ApiShell', 'MockApiShell',
array('in', 'out', 'createFile', 'hr', '_stop')
);
/**
* TestTaskTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TestTaskTest extends CakeTestCase {
/**
* setUp method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new ApiShellMockShellDispatcher();
$this->Shell =& new MockApiShell($this->Dispatcher);
$this->Shell->Dispatch = new $this->Dispatcher;
}
/**
* tearDown method
*
* @return void
* @access public
*/
function endTest() {
ClassRegistry::flush();
}
/**
* Test that method names are detected properly including those with no arguments.
*
* @access public
* @return void
*/
function testMethodNameDetection () {
$this->Shell->setReturnValueAt(0, 'in', 'q');
$this->Shell->expectAt(0, 'out', array('Controller'));
$expected = array(
array(
'1. afterFilter()',
'2. beforeFilter()',
'3. beforeRender()',
'4. constructClasses()',
'5. disableCache()',
'6. flash($message, $url, $pause = 1)',
'7. header($status)',
'8. isAuthorized()',
'9. loadModel($modelClass = null, $id = null)',
'10. paginate($object = null, $scope = array(), $whitelist = array())',
'11. postConditions($data = array(), $op = null, $bool = \'AND\', $exclusive = false)',
'12. redirect($url, $status = null, $exit = true)',
'13. referer($default = null, $local = false)',
'14. render($action = null, $layout = null, $file = null)',
'15. set($one, $two = null)',
'16. setAction($action)',
'17. validate()',
'18. validateErrors()'
)A
);
$this->Shell->expectAt(1, 'out', $expected);
$this->Shell->args = array('controller');
$this->Shell->paths['controller'] = CAKE_CORE_INCLUDE_PATH . DS . LIBS . 'controller' . DS;
$this->Shell->main();
}
}
?>

View file

@ -78,7 +78,10 @@ class ShellTest extends CakeTestCase {
* @var array
* @access public
*/
var $fixtures = array('core.post', 'core.comment');
var $fixtures = array(
'core.post', 'core.comment', 'core.article', 'core.user',
'core.tag', 'core.articles_tag', 'core.attachment'
);
/**
* setUp method
*
@ -116,13 +119,11 @@ class ShellTest extends CakeTestCase {
* @access public
*/
function testInitialize() {
$_back = array(
'modelPaths' => Configure::read('modelPaths'),
'pluginPaths' => Configure::read('pluginPaths'),
'viewPaths' => Configure::read('viewPaths'),
);
Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS));
Configure::write('modelPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models' . DS));
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'models' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models' . DS)
), true);
$this->Shell->uses = array('TestPlugin.TestPluginPost');
$this->Shell->initialize();
@ -141,8 +142,7 @@ class ShellTest extends CakeTestCase {
$this->assertTrue(isset($this->Shell->AppModel));
$this->assertIsA($this->Shell->AppModel, 'AppModel');
Configure::write('pluginPaths', $_back['pluginPaths']);
Configure::write('modelPaths', $_back['modelPaths']);
App::build();
}
/**
* testOut method

View file

@ -24,8 +24,13 @@
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
require_once CAKE.'dispatcher.php';
App::import('Core', 'AppController');
require_once CAKE . 'dispatcher.php';
if (!class_exists('AppController')) {
require_once LIBS . 'controller' . DS . 'app_controller.php';
} elseif (!defined('APP_CONTROLLER_EXISTS')){
define('APP_CONTROLLER_EXISTS', true);
}
/**
* TestDispatcher class
*
@ -488,14 +493,25 @@ class DispatcherTest extends CakeTestCase {
* @access public
* @return void
*/
function setUp() {
function startTest() {
$this->_get = $_GET;
$_GET = array();
$this->_post = $_POST;
$this->_files = $_FILES;
$this->_server = $_SERVER;
$this->_app = Configure::read('App');
Configure::write('App.base', false);
Configure::write('App.baseUrl', false);
Configure::write('App.dir', 'app');
Configure::write('App.webroot', 'webroot');
$this->_cache = Configure::read('Cache');
Configure::write('Cache.disable', true);
$this->_debug = Configure::read('debug');
App::build(App::core());
}
/**
* tearDown method
@ -503,8 +519,15 @@ class DispatcherTest extends CakeTestCase {
* @access public
* @return void
*/
function tearDown() {
function endTest() {
$_GET = $this->_get;
$_POST = $this->_post;
$_FILES = $this->_files;
$_SERVER = $this->_server;
App::build();
Configure::write('App', $this->_app);
Configure::write('Cache', $this->_cache);
Configure::write('debug', $this->_debug);
}
/**
* testParseParamsWithoutZerosAndEmptyPost method
@ -626,8 +649,6 @@ class DispatcherTest extends CakeTestCase {
$this->assertTrue(isset($result['url']['sleep']));
$this->assertTrue(isset($result['url']['coffee']));
$this->assertEqual($result['url']['coffee'], 'life');
$_GET = $this->_get;
}
/**
* testFileUploadArrayStructure method
@ -854,8 +875,6 @@ class DispatcherTest extends CakeTestCase {
)
);
$this->assertEqual($result['data'], $expected);
$_FILES = array();
}
/**
* testGetUrl method
@ -935,7 +954,7 @@ class DispatcherTest extends CakeTestCase {
$expectedWebroot = '/';
$this->assertEqual($expectedWebroot, $Dispatcher->webroot);
$Dispatcher->base = false;;
$Dispatcher->base = false;
$_SERVER['DOCUMENT_ROOT'] = '/some/apps/where';
$_SERVER['SCRIPT_FILENAME'] = '/some/apps/where/app/webroot/index.php';
$_SERVER['PHP_SELF'] = '/some/apps/where/app/webroot/index.php';
@ -948,7 +967,7 @@ class DispatcherTest extends CakeTestCase {
Configure::write('App.dir', 'auth');
$Dispatcher->base = false;;
$Dispatcher->base = false;
$_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches';
$_SERVER['SCRIPT_FILENAME'] = '/cake/repo/branches/demos/auth/webroot/index.php';
$_SERVER['PHP_SELF'] = '/demos/auth/webroot/index.php';
@ -961,7 +980,7 @@ class DispatcherTest extends CakeTestCase {
Configure::write('App.dir', 'code');
$Dispatcher->base = false;;
$Dispatcher->base = false;
$_SERVER['DOCUMENT_ROOT'] = '/Library/WebServer/Documents';
$_SERVER['SCRIPT_FILENAME'] = '/Library/WebServer/Documents/clients/PewterReport/code/webroot/index.php';
$_SERVER['PHP_SELF'] = '/clients/PewterReport/code/webroot/index.php';
@ -1596,8 +1615,9 @@ class DispatcherTest extends CakeTestCase {
**/
function testTestPluginDispatch() {
$Dispatcher =& new TestDispatcher();
$_back = Configure::read('pluginPaths');
Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS));
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$url = '/test_plugin/tests/index';
$result = $Dispatcher->dispatch($url, array('return' => 1));
$this->assertTrue(class_exists('TestsController'));
@ -1605,7 +1625,7 @@ class DispatcherTest extends CakeTestCase {
$this->assertTrue(class_exists('OtherComponentComponent'));
$this->assertTrue(class_exists('PluginsComponentComponent'));
Configure::write('pluginPaths', $_back);
App::build();
}
/**
* testChangingParamsFromBeforeFilter method
@ -1614,6 +1634,7 @@ class DispatcherTest extends CakeTestCase {
* @return void
*/
function testChangingParamsFromBeforeFilter() {
$_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php';
$Dispatcher =& new TestDispatcher();
$url = 'some_posts/index/param:value/param2:value2';
$controller = $Dispatcher->dispatch($url, array('return' => 1));
@ -1650,8 +1671,10 @@ class DispatcherTest extends CakeTestCase {
$Configure = Configure::getInstance();
$Configure->__objects = null;
Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS));
Configure::write('vendorPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors'. DS));
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'vendors' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors'. DS)
));
$Dispatcher =& new TestDispatcher();
@ -1706,7 +1729,9 @@ class DispatcherTest extends CakeTestCase {
Router::reload();
Router::connect('/', array('controller' => 'test_cached_pages', 'action' => 'index'));
Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS));
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS),
), true);
$dispatcher =& new Dispatcher();
$dispatcher->base = false;
@ -1875,6 +1900,23 @@ class DispatcherTest extends CakeTestCase {
unset($_POST['_method']);
}
/**
* Tests that invalid characters cannot be injected into the application base path.
*
* @return void
*/
function testBasePathInjection() {
$self = $_SERVER['PHP_SELF'];
$_SERVER['PHP_SELF'] = urldecode(
"/index.php/%22%3E%3Ch1%20onclick=%22alert('xss');%22%3Eheya%3C/h1%3E"
);
$dispatcher =& new Dispatcher();
$result = $dispatcher->baseUrl();
$expected = '/index.php/h1 onclick=alert(xss);heya';
$this->assertEqual($result, $expected);
}
/**
* testEnvironmentDetection method
*

View file

@ -41,20 +41,24 @@ class CacheTest extends CakeTestCase {
* @return void
*/
function setUp() {
if (!isset($this->config)) {
$this->config = Cache::config('default');
}
$this->_cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
Cache::config('default', array('engine'=> 'File', 'path' => CACHE));
$this->_defaultCacheConfig = Cache::config('default');
Cache::config('default', array('engine' => 'File', 'path' => TMP . 'tests'));
Cache::engine('File', array('path' => TMP . 'tests'));
}
/**
* end method
* tearDown method
*
* @access public
* @return void
*/
function end() {
Cache::config('default', $this->config['settings']);
function tearDown() {
Configure::write('Cache.disable', $this->_cacheDisable);
Cache::config('default', $this->_defaultCacheConfig['settings']);
Cache::engine('File');
}
/**
* testConfig method
@ -74,11 +78,17 @@ class CacheTest extends CakeTestCase {
* @return void
*/
function testConfigChange() {
$_cacheConfigSessions = Cache::config('sessions');
$_cacheConfigTests = Cache::config('tests');
$result = Cache::config('sessions', array('engine'=> 'File', 'path' => TMP . 'sessions'));
$this->assertEqual($result['settings'], Cache::settings('File'));
$result = Cache::config('tests', array('engine'=> 'File', 'path' => TMP . 'tests'));
$this->assertEqual($result['settings'], Cache::settings('File'));
Cache::config('sessions', $_cacheConfigSessions['settings']);
Cache::config('tests', $_cacheConfigTests['settings']);
}
/**
* testWritingWithConfig method
@ -87,7 +97,8 @@ class CacheTest extends CakeTestCase {
* @return void
*/
function testWritingWithConfig() {
Cache::config('sessions');
$_cacheConfigSessions = Cache::config('sessions');
Cache::write('test_somthing', 'this is the test data', 'tests');
$expected = array(
@ -101,6 +112,8 @@ class CacheTest extends CakeTestCase {
'isWindows' => DIRECTORY_SEPARATOR == '\\'
);
$this->assertEqual($expected, Cache::settings('File'));
Cache::config('sessions', $_cacheConfigSessions['settings']);
}
/**
* testInitSettings method
@ -110,6 +123,7 @@ class CacheTest extends CakeTestCase {
*/
function testInitSettings() {
Cache::engine('File', array('path' => TMP . 'tests'));
$settings = Cache::settings();
$expecting = array(
'engine' => 'File',
@ -122,6 +136,8 @@ class CacheTest extends CakeTestCase {
'isWindows' => DIRECTORY_SEPARATOR == '\\'
);
$this->assertEqual($settings, $expecting);
Cache::engine('File');
}
/**
* testWriteEmptyValues method
@ -130,8 +146,6 @@ class CacheTest extends CakeTestCase {
* @return void
*/
function testWriteEmptyValues() {
return;
Cache::engine('File', array('path' => TMP . 'tests'));
Cache::write('App.falseTest', false);
$this->assertIdentical(Cache::read('App.falseTest'), false);
@ -147,6 +161,49 @@ class CacheTest extends CakeTestCase {
Cache::write('App.zeroTest2', '0');
$this->assertIdentical(Cache::read('App.zeroTest2'), '0');
}
/**
* testCacheDisable method
*
* Check that the "Cache.disable" configuration and a change to it
* (even after a cache config has been setup) is taken into account.
*
* @link https://trac.cakephp.org/ticket/6236
* @access public
* @return void
*/
function testCacheDisable() {
Configure::write('Cache.disable', false);
Cache::config('test_cache_disable_1', array('engine'=> 'File', 'path' => TMP . 'tests'));
$this->assertTrue(Cache::write('key_1', 'hello'));
$this->assertIdentical(Cache::read('key_1'), 'hello');
Configure::write('Cache.disable', true);
$this->assertFalse(Cache::write('key_2', 'hello'));
$this->assertFalse(Cache::read('key_2'));
Configure::write('Cache.disable', false);
$this->assertTrue(Cache::write('key_3', 'hello'));
$this->assertIdentical(Cache::read('key_3'), 'hello');
Configure::write('Cache.disable', true);
Cache::config('test_cache_disable_2', array('engine'=> 'File', 'path' => TMP . 'tests'));
$this->assertFalse(Cache::write('key_4', 'hello'));
$this->assertFalse(Cache::read('key_4'));
Configure::write('Cache.disable', false);
$this->assertTrue(Cache::write('key_5', 'hello'));
$this->assertIdentical(Cache::read('key_5'), 'hello');
Configure::write('Cache.disable', true);
$this->assertFalse(Cache::write('key_6', 'hello'));
$this->assertFalse(Cache::read('key_6'));
}
/**
* testSet method
*
@ -154,7 +211,7 @@ class CacheTest extends CakeTestCase {
* @return void
*/
function testSet() {
$write = false;
$_cacheSet = Cache::set();
Cache::set(array('duration' => '+1 year'));
$data = Cache::read('test_cache');
@ -162,17 +219,17 @@ class CacheTest extends CakeTestCase {
$data = 'this is just a simple test of the cache system';
$write = Cache::write('test_cache', $data);
$this->assertTrue($write);
Cache::set(array('duration' => '+1 year'));
$data = Cache::read('test_cache');
$this->assertEqual($data, 'this is just a simple test of the cache system');
Cache::delete('test_cache');
$global = Cache::settings();
Cache::set($_cacheSet);
}
}
?>

View file

@ -45,7 +45,7 @@ class ApcEngineTest extends UnitTestCase {
if (Cache::engine('Apc')) {
$skip = false;
}
$this->skipif($skip, 'Apc is not installed or configured properly');
$this->skipIf($skip, '%s Apc is not installed or configured properly');
}
/**
* setUp method
@ -54,7 +54,9 @@ class ApcEngineTest extends UnitTestCase {
* @return void
*/
function setUp() {
Cache::config('apc', array('engine'=>'Apc', 'prefix' => 'cake_'));
$this->_cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
Cache::config('apc', array('engine' => 'Apc', 'prefix' => 'cake_'));
}
/**
* tearDown method
@ -63,6 +65,7 @@ class ApcEngineTest extends UnitTestCase {
* @return void
*/
function tearDown() {
Configure::write('Cache.disable', $this->_cacheDisable);
Cache::config('default');
}
/**

View file

@ -45,23 +45,26 @@ class FileEngineTest extends CakeTestCase {
*/
var $config = array();
/**
* start method
* startCase method
*
* @access public
* @return void
*/
function start() {
$this->config = Cache::config('default');
$settings = Cache::config('default', array('engine'=> 'File', 'path' => CACHE));
function startCase() {
$this->_cacheDisable = Configure::read('Cache.disable');
$this->_cacheConfig = Cache::config('default');
Configure::write('Cache.disable', false);
Cache::config('default', array('engine' => 'File', 'path' => CACHE));
}
/**
* end method
* endCase method
*
* @access public
* @return void
*/
function end() {
Cache::config('default', $this->config['settings']);
function endCase() {
Configure::write('Cache.disable', $this->_cacheDisable);
Cache::config('default', $this->_cacheConfig['settings']);
}
/**
* testCacheDirChange method

View file

@ -26,7 +26,8 @@
*/
if (!class_exists('Cache')) {
require LIBS . 'cache.php';
}/**
}
/**
* MemcacheEngineTest class
*
* @package cake
@ -50,7 +51,7 @@ class MemcacheEngineTest extends CakeTestCase {
if (Cache::engine('Memcache')) {
$skip = false;
}
$this->skipIf($skip, 'Memcache is not installed or configured properly');
$this->skipIf($skip, '%s Memcache is not installed or configured properly');
}
/**
* setUp method
@ -59,7 +60,9 @@ class MemcacheEngineTest extends CakeTestCase {
* @return void
*/
function setUp() {
Cache::config('memcache', array('engine'=>'Memcache', 'prefix' => 'cake_'));
$this->_cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
Cache::config('memcache', array('engine' => 'Memcache', 'prefix' => 'cake_'));
}
/**
* tearDown method
@ -68,6 +71,7 @@ class MemcacheEngineTest extends CakeTestCase {
* @return void
*/
function tearDown() {
Configure::write('Cache.disable', $this->_cacheDisable);
Cache::config('default');
}
/**
@ -107,7 +111,7 @@ class MemcacheEngineTest extends CakeTestCase {
}
}
if ($this->skipIf(!$available, 'Need memcache servers at ' . implode(', ', $servers) . ' to run this test')) {
if ($this->skipIf(!$available, '%s Need memcache servers at ' . implode(', ', $servers) . ' to run this test')) {
return;
}

View file

@ -45,7 +45,7 @@ class XcacheEngineTest extends UnitTestCase {
if ($result = Cache::engine('Xcache')) {
$skip = false;
}
$this->skipif($skip, 'Xcache is not installed or configured properly');
$this->skipIf($skip, '%s Xcache is not installed or configured properly');
}
/**
* setUp method
@ -54,7 +54,9 @@ class XcacheEngineTest extends UnitTestCase {
* @return void
*/
function setUp() {
Cache::config('xcache', array('engine'=>'Xcache', 'prefix' => 'cake_'));
$this->_cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
Cache::config('xcache', array('engine' => 'Xcache', 'prefix' => 'cake_'));
}
/**
* tearDown method
@ -63,6 +65,7 @@ class XcacheEngineTest extends UnitTestCase {
* @return void
*/
function tearDown() {
Configure::write('Cache.disable', $this->_cacheDisable);
Cache::config('default');
}
/**

View file

@ -25,7 +25,7 @@
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!class_exists('CakeSession')) {
App::import('Core', 'Session');
App::import('Core', 'CakeSession');
}
/**
* SessionTest class
@ -34,7 +34,34 @@ if (!class_exists('CakeSession')) {
* @subpackage cake.tests.cases.libs
*/
class SessionTest extends CakeTestCase {
/**
* Fixtures used in the SessionTest
*
* @var array
* @access public
*/
var $fixtures = array('core.session');
/**
* startCase method
*
* @access public
* @return void
*/
function startCase() {
// Make sure garbage colector will be called
$this->__gc_divisor = ini_get('session.gc_divisor');
ini_set('session.gc_divisor', '1');
}
/**
* endCase method
*
* @access public
* @return void
*/
function endCase() {
// Revert to the default setting
ini_set('session.gc_divisor', $this->__gc_divisor);
}
/**
* setUp method
*
@ -46,6 +73,32 @@ class SessionTest extends CakeTestCase {
$this->Session->start();
$this->Session->_checkValid();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
unset($_SESSION);
session_destroy();
}
/**
* testSessionPath
*
* @access public
* @return void
*/
function testSessionPath() {
$Session = new CakeSession('/index.php');
$this->assertEqual('/', $Session->path);
$Session = new CakeSession('/sub_dir/index.php');
$this->assertEqual('/sub_dir/', $Session->path);
$Session = new CakeSession('');
$this->assertEqual('/', $Session->path, 'Session path is empty, with "" as $base needs to be / %s');
}
/**
* testCheck method
*
@ -366,6 +419,9 @@ class SessionTest extends CakeTestCase {
$this->Session->write('SessionTestCase', 'This is a Test');
$this->assertEqual($this->Session->read('SessionTestCase'), 'This is a Test');
$this->Session->write('SessionTestCase', 'Some additional data');
$this->assertEqual($this->Session->read('SessionTestCase'), 'Some additional data');
$this->Session->destroy();
$this->assertFalse($this->Session->read('SessionTestCase'));
session_write_close();

View file

@ -24,14 +24,14 @@
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', 'Socket');
App::import('Core', 'CakeSocket');
/**
* SocketTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class SocketTest extends CakeTestCase {
class CakeSocketTest extends CakeTestCase {
/**
* setUp method
*

View file

@ -25,7 +25,12 @@
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
App::import('Core', 'CakeTestCase');
App::import('Core', 'AppController');
if (!class_exists('AppController')) {
require_once LIBS . 'controller' . DS . 'app_controller.php';
} elseif (!defined('APP_CONTROLLER_EXISTS')) {
define('APP_CONTROLLER_EXISTS', true);
}
Mock::generate('CakeHtmlReporter');
Mock::generate('CakeTestCase', 'CakeDispatcherMockTestCase');
@ -88,6 +93,15 @@ class CakeTestCaseTest extends CakeTestCase {
unset($this->Case);
unset($this->Reporter);
}
/**
* endTest
*
* @access public
* @return void
*/
function endTest() {
App::build();
}
/**
* testAssertGoodTags
*
@ -233,16 +247,12 @@ class CakeTestCaseTest extends CakeTestCase {
* @return void
**/
function testTestAction() {
$_back = array(
'controller' => Configure::read('controllerPaths'),
'view' => Configure::read('viewPaths'),
'model' => Configure::read('modelPaths'),
'plugin' => Configure::read('pluginPaths')
);
Configure::write('controllerPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'controllers' . DS));
Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS));
Configure::write('modelPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models' . DS));
Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS));
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'models' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models' . DS),
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS),
'controllers' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'controllers' . DS)
), true);
$result = $this->Case->testAction('/tests_apps/index', array('return' => 'view'));
$this->assertPattern('/This is the TestsAppsController index view/', $result);
@ -360,12 +370,6 @@ class CakeTestCaseTest extends CakeTestCase {
$db =& ConnectionManager::getDataSource('test_suite');
$db->config['prefix'] = $_backPrefix;
$fixture->drop($db);
Configure::write('modelPaths', $_back['model']);
Configure::write('controllerPaths', $_back['controller']);
Configure::write('viewPaths', $_back['view']);
Configure::write('pluginPaths', $_back['plugin']);
}
/**
* testSkipIf
@ -383,14 +387,12 @@ class CakeTestCaseTest extends CakeTestCase {
* @return void
*/
function testTestDispatcher() {
$_back = array(
'controller' => Configure::read('controllerPaths'),
'view' => Configure::read('viewPaths'),
'plugin' => Configure::read('pluginPaths')
);
Configure::write('controllerPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'controllers' . DS));
Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS));
Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS));
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'models' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models' . DS),
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS),
'controllers' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'controllers' . DS)
), true);
$Dispatcher =& new CakeTestDispatcher();
$Case =& new CakeDispatcherMockTestCase();
@ -402,10 +404,6 @@ class CakeTestCaseTest extends CakeTestCase {
$this->assertTrue(isset($Dispatcher->testCase));
$return = $Dispatcher->dispatch('/tests_apps/index', array('autoRender' => 0, 'return' => 1, 'requested' => 1));
Configure::write('controllerPaths', $_back['controller']);
Configure::write('viewPaths', $_back['view']);
Configure::write('pluginPaths', $_back['plugin']);
}
}
?>

View file

@ -51,8 +51,8 @@ class CakeTestFixtureTestFixture extends CakeTestFixture {
*/
var $fields = array(
'id' => array('type' => 'integer', 'key' => 'primary'),
'name' => array('type' => 'text', 'length' => '255'),
'created' => array('type' => 'datetime'),
'name' => array('type' => 'string', 'length' => '255'),
'created' => array('type' => 'datetime')
);
/**
* Records property

View file

@ -40,7 +40,7 @@ class CodeCoverageManagerTest extends CakeTestCase {
* @access public
*/
function skip() {
$this->skipif (!extension_loaded('xdebug'), 'XDebug not installed');
$this->skipIf(!extension_loaded('xdebug'), '%s XDebug not installed');
}
/**
* startTest Method
@ -116,6 +116,9 @@ class CodeCoverageManagerTest extends CakeTestCase {
$expected = $manager->__testObjectFileFromCaseFile('models/some_file.test.php', true);
$this->assertIdentical(APP.'models'.DS.'some_file.php', $expected);
$expected = $manager->__testObjectFileFromCaseFile('models/datasources/some_file.test.php', true);
$this->assertIdentical(APP.'models'.DS.'datasources'.DS.'some_file.php', $expected);
$expected = $manager->__testObjectFileFromCaseFile('controllers/some_file.test.php', true);
$this->assertIdentical(APP.'controllers'.DS.'some_file.php', $expected);

View file

@ -39,9 +39,20 @@ class ConfigureTest extends CakeTestCase {
* @return void
*/
function setUp() {
parent::setUp();
$this->_cacheDisable = Configure::read('Cache.disable');
$this->_debug = Configure::read('debug');
Configure::write('Cache.disable', true);
}
/**
* endTest
*
* @access public
* @return void
*/
function endTest() {
App::build();
}
/**
* tearDown method
*
@ -67,52 +78,8 @@ class ConfigureTest extends CakeTestCase {
if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'test.php')) {
unlink(TMP . 'cache' . DS . 'persistent' . DS . 'test.php');
}
Configure::write('debug', 2);
parent::tearDown();
}
/**
* testListObjects method
*
* @access public
* @return void
*/
function testListObjects() {
$result = Configure::listObjects('class', TEST_CAKE_CORE_INCLUDE_PATH . 'libs');
$this->assertTrue(in_array('Xml', $result));
$this->assertTrue(in_array('Cache', $result));
$this->assertTrue(in_array('HttpSocket', $result));
$result = Configure::listObjects('behavior');
$this->assertTrue(in_array('Tree', $result));
$result = Configure::listObjects('controller');
$this->assertTrue(in_array('Pages', $result));
$result = Configure::listObjects('component');
$this->assertTrue(in_array('Auth', $result));
$result = Configure::listObjects('view');
$this->assertTrue(in_array('Media', $result));
$result = Configure::listObjects('helper');
$this->assertTrue(in_array('Html', $result));
$result = Configure::listObjects('model');
$notExpected = array('AppModel', 'Behavior', 'ConnectionManager', 'DbAcl', 'Model', 'Schema');
foreach ($notExpected as $class) {
$this->assertFalse(in_array($class, $result));
}
$result = Configure::listObjects('file');
$this->assertFalse($result);
$result = Configure::listObjects('file', 'non_existing_configure');
$expected = array();
$this->assertEqual($result, $expected);
$result = Configure::listObjects('NonExistingType');
$this->assertFalse($result);
Configure::write('debug', $this->_debug);
Configure::write('Cache.disable', $this->_cacheDisable);
}
/**
* testRead method
@ -246,17 +213,6 @@ class ConfigureTest extends CakeTestCase {
$result = Configure::version();
$this->assertTrue(version_compare($result, '1.2', '>='));
}
/**
* testBuildPaths method
*
* @access public
* @return void
*/
function testBuildPaths() {
Configure::buildPaths(array());
$models = Configure::read('modelPaths');
$this->assertTrue(!empty($models));
}
}
/**
* AppImportTest class
@ -265,6 +221,125 @@ class ConfigureTest extends CakeTestCase {
* @subpackage cake.tests.cases.libs
*/
class AppImportTest extends UnitTestCase {
/**
* testBuild method
*
* @access public
* @return void
*/
function testBuild() {
$old = App::path('models');
$expected = array(
APP . 'models' . DS,
APP,
ROOT . DS . LIBS . 'model' . DS
);
$this->assertEqual($expected, $old);
App::build(array('models' => array('/path/to/models/')));
$new = App::path('models');
$expected = array(
APP . 'models' . DS,
'/path/to/models/',
APP,
ROOT . DS . LIBS . 'model' . DS
);
$this->assertEqual($expected, $new);
App::build(); //reset defaults
$defaults = App::path('models');
$this->assertEqual($old, $defaults);
}
/**
* testBuildWithReset method
*
* @access public
* @return void
*/
function testBuildWithReset() {
$old = App::path('models');
$expected = array(
APP . 'models' . DS,
APP,
ROOT . DS . LIBS . 'model' . DS
);
$this->assertEqual($expected, $old);
App::build(array('models' => array('/path/to/models/')), true);
$new = App::path('models');
$expected = array(
'/path/to/models/'
);
$this->assertEqual($expected, $new);
App::build(); //reset defaults
$defaults = App::path('models');
$this->assertEqual($old, $defaults);
}
/**
* testCore method
*
* @access public
* @return void
*/
function testCore() {
$model = App::core('models');
$this->assertEqual(array(ROOT . DS . LIBS . 'model' . DS), $model);
$view = App::core('views');
$this->assertEqual(array(ROOT . DS . LIBS . 'view' . DS), $view);
$controller = App::core('controllers');
$this->assertEqual(array(ROOT . DS . LIBS . 'controller' . DS), $controller);
}
/**
* testListObjects method
*
* @access public
* @return void
*/
function testListObjects() {
$result = App::objects('class', TEST_CAKE_CORE_INCLUDE_PATH . 'libs');
$this->assertTrue(in_array('Xml', $result));
$this->assertTrue(in_array('Cache', $result));
$this->assertTrue(in_array('HttpSocket', $result));
$result = App::objects('behavior');
$this->assertTrue(in_array('Tree', $result));
$result = App::objects('controller');
$this->assertTrue(in_array('Pages', $result));
$result = App::objects('component');
$this->assertTrue(in_array('Auth', $result));
$result = App::objects('view');
$this->assertTrue(in_array('Media', $result));
$result = App::objects('helper');
$this->assertTrue(in_array('Html', $result));
$result = App::objects('model');
$notExpected = array('AppModel', 'ModelBehavior', 'ConnectionManager', 'DbAcl', 'Model', 'CakeSchema');
foreach ($notExpected as $class) {
$this->assertFalse(in_array($class, $result));
}
$result = App::objects('file');
$this->assertFalse($result);
$result = App::objects('file', 'non_existing_configure');
$expected = array();
$this->assertEqual($result, $expected);
$result = App::objects('NonExistingType');
$this->assertFalse($result);
}
/**
* testClassLoading method
*
@ -339,8 +414,9 @@ class AppImportTest extends UnitTestCase {
$this->assertFalse($file);
}
$_back = Configure::read('pluginPaths');
Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS));
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$result = App::import('Controller', 'TestPlugin.Tests');
$this->assertTrue($result);
@ -351,7 +427,7 @@ class AppImportTest extends UnitTestCase {
$this->assertTrue($result);
$this->assertTrue(class_exists('OtherHelperHelper'));
Configure::write('pluginPaths', $_back);
App::build();
}
/**
* testFileLoading method
@ -438,11 +514,11 @@ class AppImportTest extends UnitTestCase {
* @return void
*/
function testMultipleLoading() {
$toLoad = array('I18n', 'Socket');
$toLoad = array('I18n', 'CakeSocket');
$classes = array_flip(get_declared_classes());
$this->assertFalse(isset($classes['i18n']));
$this->assertFalse(isset($classes['Socket']));
$this->assertFalse(isset($classes['CakeSocket']));
$load = App::import($toLoad);
$this->assertTrue($load);
@ -455,7 +531,7 @@ class AppImportTest extends UnitTestCase {
$this->assertTrue(isset($classes['i18n']));
}
$load = App::import(array('I18n', 'SomeNotFoundClass', 'Socket'));
$load = App::import(array('I18n', 'SomeNotFoundClass', 'CakeSocket'));
$this->assertFalse($load);
$load = App::import($toLoad);
@ -481,9 +557,11 @@ class AppImportTest extends UnitTestCase {
}
*/
function testLoadingVendor() {
Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS));
Configure::write('vendorPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors'. DS));
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'vendors' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors'. DS),
), true);
ob_start();
$result = App::import('Vendor', 'TestPlugin.TestPluginAsset', array('ext' => 'css'));
$text = ob_get_clean();

View file

@ -62,9 +62,8 @@ if (!class_exists('AppController')) {
* @access public
*/
var $components = array('Orange' => array('colour' => 'blood orange'));
}
} else if (!defined('APP_CONTROLLER_EXISTS')){
} elseif (!defined('APP_CONTROLLER_EXISTS')){
define('APP_CONTROLLER_EXISTS', true);
}
/**
@ -281,10 +280,21 @@ class ComponentTest extends CakeTestCase {
* @return void
*/
function setUp() {
Configure::write('pluginPaths', array(
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS
$this->_pluginPaths = App::path('plugins');
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
App::build();
ClassRegistry::flush();
}
/**
* testLoadComponents method
*
@ -395,7 +405,9 @@ class ComponentTest extends CakeTestCase {
* @return void
*/
function testComponentsWithParams() {
$this->skipIf(defined('APP_CONTROLLER_EXISTS'), 'Components with Params test will be skipped as it needs a non-existent AppController. As the an AppController class exists, this cannot be run.');
if ($this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController')) {
return;
}
$Controller =& new ComponentTestController();
$Controller->components = array('ParamTest' => array('test' => 'value', 'flag'), 'Apple');
@ -424,6 +436,21 @@ class ComponentTest extends CakeTestCase {
$this->assertEqual($Controller->Orange->settings, $expected);
$this->assertEqual($Controller->ParamTest->test, 'value');
}
/**
* Ensure that settings are not duplicated when passed into component initialize.
*
* @return void
**/
function testComponentParamsNoDuplication() {
$Controller =& new ComponentTestController();
$Controller->components = array('Orange' => array('setting' => array('itemx')));
$Controller->constructClasses();
$Controller->Component->initialize($Controller);
$expected = array('setting' => array('itemx'), 'colour' => 'blood orange');
$this->assertEqual($Controller->Orange->settings, $expected, 'Params duplication has occured %s');
}
/**
* Test mutually referencing components.
*
@ -475,11 +502,14 @@ class ComponentTest extends CakeTestCase {
));
}
/**
* test that SessionComponent doesn't get added if its already in the components array.
* Test that SessionComponent doesn't get added if its already in the components array.
*
* @return void
**/
* @access public
*/
function testDoubleLoadingOfSessionComponent() {
$this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController');
$Controller =& new ComponentTestController();
$Controller->uses = array();
$Controller->components = array('Session');

View file

@ -27,7 +27,7 @@
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
App::import(array('controller'.DS.'components'.DS.'acl', 'model'.DS.'db_acl'));
App::import(array('controller' .DS . 'components' . DS . 'acl', 'model' . DS . 'db_acl'));
/**
* AclNodeTwoTestBase class
*

View file

@ -25,10 +25,8 @@
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import(array('controller' . DS . 'components' . DS .'auth', 'controller' . DS . 'components' . DS .'acl'));
App::import(array('controller'.DS.'components'.DS.'acl', 'model'.DS.'db_acl'));
App::import(array('controller' . DS . 'components' . DS . 'acl', 'model' . DS . 'db_acl'));
App::import('Core', 'Xml');
Configure::write('Security.salt', 'JfIxfs2guVoUubWDYhG93b0qyJfIxfs2guwvniR2G0FgaC9mi');
/**
* TestAuthComponent class
*
@ -437,6 +435,13 @@ class AuthTest extends CakeTestCase {
* @return void
*/
function startTest() {
$this->_server = $_SERVER;
$this->_env = $_ENV;
$this->_securitySalt = Configure::read('Security.salt');
Configure::write('Security.salt', 'JfIxfs2guVoUubWDYhG93b0qyJfIxfs2guwvniR2G0FgaC9mi');
$this->_acl = Configure::read('Acl');
Configure::write('Acl.database', 'test_suite');
Configure::write('Acl.classname', 'DbAcl');
@ -444,17 +449,28 @@ class AuthTest extends CakeTestCase {
$this->Controller->Component->init($this->Controller);
ClassRegistry::addObject('view', new View($this->Controller));
$this->Controller->Session->del('Auth');
$this->Controller->Session->del('Message.auth');
Router::reload();
$this->initialized = true;
}
/**
* tearDown method
* endTest method
*
* @access public
* @return void
*/
function tearDown() {
function endTest() {
$_SERVER = $this->_server;
$_ENV = $this->_env;
Configure::write('Acl', $this->_acl);
Configure::write('Security.salt', $this->_securitySalt);
$this->Controller->Session->del('Auth');
$this->Controller->Session->del('Message.auth');
ClassRegistry::flush();
unset($this->Controller, $this->AuthUser);
}
/**
@ -578,7 +594,6 @@ class AuthTest extends CakeTestCase {
$this->assertFalse($result);
$this->assertTrue($this->Controller->Session->check('Message.auth'));
$this->Controller->params = Router::parse('auth_test/camelCase');
$result = $this->Controller->Auth->startup($this->Controller);
$this->assertFalse($result);
@ -713,6 +728,36 @@ class AuthTest extends CakeTestCase {
$this->Controller->params['action'] = 'Add';
$this->assertFalse($this->Controller->Auth->startup($this->Controller));
}
/**
* test that allow() and allowedActions work with camelCase method names.
*
* @return void
**/
function testAllowedActionsWithCamelCaseMethods() {
$url = '/auth_test/camelCase';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
$this->Controller->Auth->allow('*');
$result = $this->Controller->Auth->startup($this->Controller);
$this->assertTrue($result, 'startup() should return true, as action is allowed. %s');
$url = '/auth_test/camelCase';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
$this->Controller->Auth->allowedActions = array('delete', 'camelCase', 'add');
$result = $this->Controller->Auth->startup($this->Controller);
$this->assertTrue($result, 'startup() should return true, as action is allowed. %s');
$this->Controller->Auth->allowedActions = array('delete', 'add');
$result = $this->Controller->Auth->startup($this->Controller);
$this->assertFalse($result, 'startup() should return false, as action is not allowed. %s');
}
/**
* testLoginRedirect method
*
@ -824,10 +869,15 @@ class AuthTest extends CakeTestCase {
$this->assertEqual($expected, $this->Controller->Session->read('Auth.redirect'));
// QueryString parameters
$_back = $_GET;
$_GET = array(
'url' => '/posts/index/29',
'print' => 'true',
'refer' => 'menu'
);
$this->Controller->Session->del('Auth');
$url = '/posts/index/29?print=true&refer=menu';
$this->Controller->params = Router::parse($url);
$this->Controller->params['url']['url'] = Router::normalize($url);
$this->Controller->params = Dispatcher::parseParams($url);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
@ -835,6 +885,23 @@ class AuthTest extends CakeTestCase {
$expected = Router::normalize('posts/index/29?print=true&refer=menu');
$this->assertEqual($expected, $this->Controller->Session->read('Auth.redirect'));
$_GET = array(
'url' => '/posts/index/29',
'print' => 'true',
'refer' => 'menu',
'ext' => 'html'
);
$this->Controller->Session->del('Auth');
$url = '/posts/index/29?print=true&refer=menu';
$this->Controller->params = Dispatcher::parseParams($url);
$this->Controller->Auth->initialize($this->Controller);
$this->Controller->Auth->loginAction = array('controller' => 'AuthTest', 'action' => 'login');
$this->Controller->Auth->userModel = 'AuthUser';
$this->Controller->Auth->startup($this->Controller);
$expected = Router::normalize('posts/index/29?print=true&refer=menu');
$this->assertEqual($expected, $this->Controller->Session->read('Auth.redirect'));
$_GET = $_back;
//external authed action
$_SERVER['HTTP_REFERER'] = 'http://webmail.example.com/view/message';
$this->Controller->Session->del('Auth');
@ -1133,7 +1200,7 @@ class AuthTest extends CakeTestCase {
* @return void
*/
function testAjaxLogin() {
Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS));
App::build(array('views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)));
$_SERVER['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest";
if (!class_exists('dispatcher')) {

View file

@ -24,8 +24,96 @@
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
Configure::write('App.encoding', 'UTF-8');
App::import('Component', 'Email');
/**
* EmailTestComponent class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class EmailTestComponent extends EmailComponent {
/**
* smtpSend method override for testing
*
* @access public
* @return mixed
*/
function smtpSend($data, $code = '250') {
return parent::__smtpSend($data, $code);
}
/**
* Convenience setter method for testing.
*
* @access public
* @return void
*/
function setConnectionSocket(&$socket) {
$this->__smtpConnection = $socket;
}
/**
* Convenience getter method for testing.
*
* @access public
* @return mixed
*/
function getConnectionSocket() {
return $this->__smtpConnection;
}
/**
* Convenience setter for testing.
*
* @access public
* @return void
*/
function setHeaders($headers) {
$this->__header += $headers;
}
/**
* Convenience getter for testing.
*
* @access public
* @return array
*/
function getHeaders() {
return $this->__header;
}
/**
* Convenience setter for testing.
*
* @access public
* @return void
*/
function setBoundary() {
$this->__createBoundary();
}
/**
* Convenience getter for testing.
*
* @access public
* @return string
*/
function getBoundary() {
return $this->__boundary;
}
/**
* Convenience getter for testing.
*
* @access public
* @return string
*/
function getMessage() {
return $this->__message;
}
/**
* Convenience method for testing.
*
* @access public
* @return string
*/
function strip($content, $message = false) {
return parent::__strip($content, $message);
}
}
/**
* EmailTestController class
*
@ -53,7 +141,7 @@ class EmailTestController extends Controller {
* @var array
* @access public
*/
var $components = array('Email');
var $components = array('EmailTest');
/**
* pageTitle property
*
@ -90,16 +178,34 @@ class EmailComponentTest extends CakeTestCase {
* @return void
*/
function setUp() {
$this->_appEncoding = Configure::read('App.encoding');
Configure::write('App.encoding', 'UTF-8');
$this->Controller =& new EmailTestController();
restore_error_handler();
@$this->Controller->Component->init($this->Controller);
set_error_handler('simpleTestErrorHandler');
$this->Controller->Email->initialize($this->Controller, array());
$this->Controller->EmailTest->initialize($this->Controller, array());
ClassRegistry::addObject('view', new View($this->Controller));
Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS));
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
));
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
Configure::write('App.encoding', $this->_appEncoding);
App::build();
$this->Controller->Session->del('Message');
restore_error_handler();
ClassRegistry::flush();
}
/**
* testBadSmtpSend method
@ -108,9 +214,9 @@ class EmailComponentTest extends CakeTestCase {
* @return void
*/
function testBadSmtpSend() {
$this->Controller->Email->smtpOptions['host'] = 'blah';
$this->Controller->Email->delivery = 'smtp';
$this->assertFalse($this->Controller->Email->send('Should not work'));
$this->Controller->EmailTest->smtpOptions['host'] = 'blah';
$this->Controller->EmailTest->delivery = 'smtp';
$this->assertFalse($this->Controller->EmailTest->send('Should not work'));
}
/**
* testSmtpSend method
@ -119,21 +225,21 @@ class EmailComponentTest extends CakeTestCase {
* @return void
*/
function testSmtpSend() {
if (!$this->skipIf(!@fsockopen('localhost', 25), 'No SMTP server running on localhost')) {
if (!$this->skipIf(!@fsockopen('localhost', 25), '%s No SMTP server running on localhost')) {
return;
}
$this->Controller->Email->reset();
$this->Controller->Email->to = 'postmaster@localhost';
$this->Controller->Email->from = 'noreply@example.com';
$this->Controller->Email->subject = 'Cake SMTP test';
$this->Controller->Email->replyTo = 'noreply@example.com';
$this->Controller->Email->template = null;
$this->Controller->EmailTest->reset();
$this->Controller->EmailTest->to = 'postmaster@localhost';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake SMTP test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->Email->delivery = 'smtp';
$this->assertTrue($this->Controller->Email->send('This is the body of the message'));
$this->Controller->EmailTest->delivery = 'smtp';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->Controller->Email->_debug = true;
$this->Controller->Email->sendAs = 'text';
$this->Controller->EmailTest->_debug = true;
$this->Controller->EmailTest->sendAs = 'text';
$expect = <<<TEMPDOC
<pre>Host: localhost
Port: 25
@ -157,7 +263,7 @@ This is the body of the message
</pre>
TEMPDOC;
$this->assertTrue($this->Controller->Email->send('This is the body of the message'));
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
}
/**
@ -167,22 +273,24 @@ TEMPDOC;
* @return void
*/
function testAuthenticatedSmtpSend() {
$this->skipIf(!@fsockopen('localhost', 25), 'No SMTP server running on localhost');
$this->skipIf(!@fsockopen('localhost', 25), '%s No SMTP server running on localhost');
$this->Controller->Email->reset();
$this->Controller->Email->to = 'postmaster@localhost';
$this->Controller->Email->from = 'noreply@example.com';
$this->Controller->Email->subject = 'Cake SMTP test';
$this->Controller->Email->replyTo = 'noreply@example.com';
$this->Controller->Email->template = null;
$this->Controller->Email->smtpOptions['username'] = 'test';
$this->Controller->Email->smtpOptions['password'] = 'testing';
$this->Controller->EmailTest->reset();
$this->Controller->EmailTest->to = 'postmaster@localhost';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake SMTP test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->smtpOptions['username'] = 'test';
$this->Controller->EmailTest->smtpOptions['password'] = 'testing';
$this->Controller->Email->delivery = 'smtp';
$result = $this->Controller->Email->send('This is the body of the message');
$code = substr($this->Controller->Email->smtpError, 0, 3);
$this->skipIf(!$code, 'Authentication not enabled on server');
$this->assertTrue(!$result && $code == '535');
$this->Controller->EmailTest->delivery = 'smtp';
$result = $this->Controller->EmailTest->send('This is the body of the message');
$code = substr($this->Controller->EmailTest->smtpError, 0, 3);
$this->skipIf(!$code, '%s Authentication not enabled on server');
$this->assertFalse($result);
$this->assertEqual($code, '535');
}
/**
* testSendFormats method
@ -191,13 +299,13 @@ TEMPDOC;
* @return void
*/
function testSendFormats() {
$this->Controller->Email->reset();
$this->Controller->Email->to = 'postmaster@localhost';
$this->Controller->Email->from = 'noreply@example.com';
$this->Controller->Email->subject = 'Cake SMTP test';
$this->Controller->Email->replyTo = 'noreply@example.com';
$this->Controller->Email->template = null;
$this->Controller->Email->delivery = 'debug';
$this->Controller->EmailTest->reset();
$this->Controller->EmailTest->to = 'postmaster@localhost';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake SMTP test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'debug';
$message = <<<MSGBLOC
<pre>To: postmaster@localhost
@ -217,20 +325,20 @@ This is the body of the message
</pre>
MSGBLOC;
$this->Controller->Email->sendAs = 'text';
$this->Controller->EmailTest->sendAs = 'text';
$expect = str_replace('{CONTENTTYPE}', 'text/plain; charset=UTF-8', $message);
$this->assertTrue($this->Controller->Email->send('This is the body of the message'));
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
$this->Controller->Email->sendAs = 'html';
$this->Controller->EmailTest->sendAs = 'html';
$expect = str_replace('{CONTENTTYPE}', 'text/html; charset=UTF-8', $message);
$this->assertTrue($this->Controller->Email->send('This is the body of the message'));
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
// TODO: better test for format of message sent?
$this->Controller->Email->sendAs = 'both';
$this->Controller->EmailTest->sendAs = 'both';
$expect = str_replace('{CONTENTTYPE}', 'multipart/alternative; boundary="alt-"' . "\n", $message);
$this->assertTrue($this->Controller->Email->send('This is the body of the message'));
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
}
/**
@ -240,13 +348,13 @@ MSGBLOC;
* @return void
*/
function testTemplates() {
$this->Controller->Email->reset();
$this->Controller->Email->to = 'postmaster@localhost';
$this->Controller->Email->from = 'noreply@example.com';
$this->Controller->Email->subject = 'Cake SMTP test';
$this->Controller->Email->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->reset();
$this->Controller->EmailTest->to = 'postmaster@localhost';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake SMTP test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->Email->delivery = 'debug';
$this->Controller->EmailTest->delivery = 'debug';
$header = <<<HEADBLOC
To: postmaster@localhost
@ -265,8 +373,8 @@ Message:
HEADBLOC;
$this->Controller->Email->layout = 'default';
$this->Controller->Email->template = 'default';
$this->Controller->EmailTest->layout = 'default';
$this->Controller->EmailTest->template = 'default';
$text = <<<TEXTBLOC
@ -293,22 +401,22 @@ TEXTBLOC;
HTMLBLOC;
$this->Controller->Email->sendAs = 'text';
$this->Controller->EmailTest->sendAs = 'text';
$expect = '<pre>' . str_replace('{CONTENTTYPE}', 'text/plain; charset=UTF-8', $header) . $text . "\n" . '</pre>';
$this->assertTrue($this->Controller->Email->send('This is the body of the message'));
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
$this->Controller->Email->sendAs = 'html';
$this->Controller->EmailTest->sendAs = 'html';
$expect = '<pre>' . str_replace('{CONTENTTYPE}', 'text/html; charset=UTF-8', $header) . $html . "\n" . '</pre>';
$this->assertTrue($this->Controller->Email->send('This is the body of the message'));
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
$this->Controller->Email->sendAs = 'both';
$this->Controller->EmailTest->sendAs = 'both';
$expect = str_replace('{CONTENTTYPE}', 'multipart/alternative; boundary="alt-"' . "\n", $header);
$expect .= '--alt-' . "\n" . 'Content-Type: text/plain; charset=UTF-8' . "\n" . 'Content-Transfer-Encoding: 7bit' . "\n\n" . $text . "\n\n";
$expect .= '--alt-' . "\n" . 'Content-Type: text/html; charset=UTF-8' . "\n" . 'Content-Transfer-Encoding: 7bit' . "\n\n" . $html . "\n\n";
$expect = '<pre>' . $expect . '--alt---' . "\n\n" . '</pre>';
$this->assertTrue($this->Controller->Email->send('This is the body of the message'));
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
$html = <<<HTMLBLOC
@ -327,9 +435,9 @@ HTMLBLOC;
HTMLBLOC;
$this->Controller->Email->sendAs = 'html';
$this->Controller->EmailTest->sendAs = 'html';
$expect = '<pre>' . str_replace('{CONTENTTYPE}', 'text/html; charset=UTF-8', $header) . $html . "\n" . '</pre>';
$this->assertTrue($this->Controller->Email->send('This is the body of the message', 'default', 'thin'));
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message', 'default', 'thin'));
$this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
return;
@ -345,11 +453,34 @@ This email was sent using the CakePHP Framework, http://cakephp.org.
TEXTBLOC;
$this->Controller->Email->sendAs = 'text';
$this->Controller->EmailTest->sendAs = 'text';
$expect = '<pre>' . str_replace('{CONTENTTYPE}', 'text/plain; charset=UTF-8', $header) . $text . "\n" . '</pre>';
$this->assertTrue($this->Controller->Email->send('This is the body of the message', 'wide', 'default'));
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message', 'wide', 'default'));
$this->assertEqual($this->Controller->Session->read('Message.email.message'), $this->__osFix($expect));
}
/**
* testSmtpSendSocket method
*
* @access public
* @return void
*/
function testSmtpSendSocket() {
$this->skipIf(!@fsockopen('localhost', 25), '%s No SMTP server running on localhost');
$this->Controller->EmailTest->reset();
$socket =& new CakeSocket(array_merge(array('protocol'=>'smtp'), $this->Controller->EmailTest->smtpOptions));
$this->Controller->EmailTest->setConnectionSocket($socket);
$this->assertTrue($this->Controller->EmailTest->getConnectionSocket());
$response = $this->Controller->EmailTest->smtpSend('HELO', '250');
$this->assertPattern('/501 Syntax: HELO hostname/', $this->Controller->EmailTest->smtpError);
$this->Controller->EmailTest->smtpError = null;
$response = $this->Controller->EmailTest->smtpSend('HELO somehostname', '250');
$this->assertNoPattern('/501 Syntax: HELO hostname/', $this->Controller->EmailTest->smtpError);
}
/**
* testSendDebug method
*
@ -357,15 +488,15 @@ TEXTBLOC;
* @return void
*/
function testSendDebug() {
$this->Controller->Email->reset();
$this->Controller->Email->to = 'postmaster@localhost';
$this->Controller->Email->from = 'noreply@example.com';
$this->Controller->Email->subject = 'Cake SMTP test';
$this->Controller->Email->replyTo = 'noreply@example.com';
$this->Controller->Email->template = null;
$this->Controller->EmailTest->reset();
$this->Controller->EmailTest->to = 'postmaster@localhost';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake SMTP test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->Email->delivery = 'debug';
$this->assertTrue($this->Controller->Email->send('This is the body of the message'));
$this->Controller->EmailTest->delivery = 'debug';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
}
/**
* testContentStripping method
@ -377,9 +508,21 @@ TEXTBLOC;
$content = "Previous content\n--alt-\nContent-TypeContent-Type:: text/html; charsetcharset==utf-8\nContent-Transfer-Encoding: 7bit";
$content .= "\n\n<p>My own html content</p>";
$result = $this->Controller->Email->__strip($content, true);
$result = $this->Controller->EmailTest->strip($content, true);
$expected = "Previous content\n--alt-\n text/html; utf-8\n 7bit\n\n<p>My own html content</p>";
$this->assertEqual($result, $expected);
$content = '<p>Some HTML content with an <a href="mailto:test@example.com">email link</a>';
$result = $this->Controller->EmailTest->strip($content, true);
$expected = $content;
$this->assertEqual($result, $expected);
$content = '<p>Some HTML content with an ';
$content .= '<a href="mailto:test@example.com,test2@example.com">email link</a>';
$result = $this->Controller->EmailTest->strip($content, true);
$expected = $content;
$this->assertEqual($result, $expected);
}
/**
* testMultibyte method
@ -388,31 +531,68 @@ TEXTBLOC;
* @return void
*/
function testMultibyte() {
$this->Controller->Email->reset();
$this->Controller->Email->to = 'postmaster@localhost';
$this->Controller->Email->from = 'noreply@example.com';
$this->Controller->Email->subject = 'هذه رسالة بعنوان طويل مرسل للمستلم';
$this->Controller->Email->replyTo = 'noreply@example.com';
$this->Controller->Email->template = null;
$this->Controller->Email->delivery = 'debug';
$this->Controller->EmailTest->reset();
$this->Controller->EmailTest->to = 'postmaster@localhost';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'هذه رسالة بعنوان طويل مرسل للمستلم';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'debug';
$subject = '=?UTF-8?B?2YfYsNmHINix2LPYp9mE2Kkg2KjYudmG2YjYp9mGINi32YjZitmEINmF2LE=?=' . "\r\n" . ' =?UTF-8?B?2LPZhCDZhNmE2YXYs9iq2YTZhQ==?=';
$this->Controller->Email->sendAs = 'text';
$this->assertTrue($this->Controller->Email->send('This is the body of the message'));
$this->Controller->EmailTest->sendAs = 'text';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
preg_match('/Subject: (.*)Header:/s', $this->Controller->Session->read('Message.email.message'), $matches);
$this->assertEqual(trim($matches[1]), $subject);
$this->Controller->Email->sendAs = 'html';
$this->assertTrue($this->Controller->Email->send('This is the body of the message'));
$this->Controller->EmailTest->sendAs = 'html';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
preg_match('/Subject: (.*)Header:/s', $this->Controller->Session->read('Message.email.message'), $matches);
$this->assertEqual(trim($matches[1]), $subject);
$this->Controller->Email->sendAs = 'both';
$this->assertTrue($this->Controller->Email->send('This is the body of the message'));
$this->Controller->EmailTest->sendAs = 'both';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
preg_match('/Subject: (.*)Header:/s', $this->Controller->Session->read('Message.email.message'), $matches);
$this->assertEqual(trim($matches[1]), $subject);
}
/**
* testReset method
*
* @access public
* @return void
*/
function testReset() {
$this->Controller->EmailTest->template = 'test_template';
$this->Controller->EmailTest->to = 'test.recipient@example.com';
$this->Controller->EmailTest->from = 'test.sender@example.com';
$this->Controller->EmailTest->replyTo = 'test.replyto@example.com';
$this->Controller->EmailTest->return = 'test.return@example.com';
$this->Controller->EmailTest->cc = array('cc1@example.com', 'cc2@example.com');
$this->Controller->EmailTest->bcc = array('bcc1@example.com', 'bcc2@example.com');
$this->Controller->EmailTest->subject = 'Test subject';
$this->Controller->EmailTest->additionalParams = 'X-additional-header';
$this->Controller->EmailTest->delivery = 'smtp';
$this->Controller->EmailTest->smtpOptions['host'] = 'blah';
$this->assertFalse($this->Controller->EmailTest->send('Should not work'));
$this->Controller->EmailTest->reset();
$this->assertNull($this->Controller->EmailTest->template);
$this->assertNull($this->Controller->EmailTest->to);
$this->assertNull($this->Controller->EmailTest->from);
$this->assertNull($this->Controller->EmailTest->replyTo);
$this->assertNull($this->Controller->EmailTest->return);
$this->assertIdentical($this->Controller->EmailTest->cc, array());
$this->assertIdentical($this->Controller->EmailTest->bcc, array());
$this->assertNull($this->Controller->EmailTest->subject);
$this->assertNull($this->Controller->EmailTest->additionalParams);
$this->assertIdentical($this->Controller->EmailTest->getHeaders(), array());
$this->assertNull($this->Controller->EmailTest->getBoundary());
$this->assertIdentical($this->Controller->EmailTest->getMessage(), array());
$this->assertNull($this->Controller->EmailTest->smtpError);
}
/**
* osFix method
*

View file

@ -144,6 +144,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
if (!headers_sent()) {
header('Content-type: text/html'); //reset content type.
}
App::build();
}
/**
* testInitializeCallback method
@ -416,6 +417,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
$this->RequestHandler->ext = 'rss';
$this->assertEqual($this->RequestHandler->prefers(), 'rss');
$this->assertFalse($this->RequestHandler->prefers('xml'));
$this->assertEqual($this->RequestHandler->prefers(array('js', 'xml', 'xhtml')), 'xml');
$this->assertTrue($this->RequestHandler->accepts('xml'));
$_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
@ -484,9 +486,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
function testAjaxRedirectAsRequestAction() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->_init();
$_paths = Configure::read('viewPaths');
$testDir = array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS);
Configure::write('viewPaths', array_merge($testDir, $_paths));
App::build(array('views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)));
$this->Controller->RequestHandler = new NoStopRequestHandler($this);
$this->Controller->RequestHandler->expectOnce('_stop');
@ -498,7 +498,6 @@ class RequestHandlerComponentTest extends CakeTestCase {
$result = ob_get_clean();
$this->assertPattern('/posts index/', $result, 'RequestAction redirect failed.');
Configure::write('viewPaths', $_paths);
unset($_SERVER['HTTP_X_REQUESTED_WITH']);
}
/**

View file

@ -141,7 +141,6 @@ class SecurityComponentTest extends CakeTestCase {
$this->Controller->Component->init($this->Controller);
$this->Controller->Security =& $this->Controller->TestSecurity;
$this->Controller->Security->blackHoleCallback = 'fail';
$this->oldSalt = Configure::read('Security.salt');
Configure::write('Security.salt', 'foo!');
}
@ -152,10 +151,11 @@ class SecurityComponentTest extends CakeTestCase {
* @return void
*/
function tearDown() {
Configure::write('Security.salt', $this->oldSalt);
$this->Controller->Session->del('_Token');
unset($this->Controller->Security);
unset($this->Controller->Component);
unset($this->Controller);
Configure::write('Security.salt', $this->oldSalt);
}
/**
* testStartup method

View file

@ -81,6 +81,24 @@ class OrangeSessionTestController extends Controller {
* @subpackage cake.tests.cases.libs.controller.components
*/
class SessionComponentTest extends CakeTestCase {
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->_session = Configure::read('Session');
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
Configure::write('Session', $this->_session);
}
/**
* testSessionAutoStart method
*
@ -322,6 +340,8 @@ class SessionComponentTest extends CakeTestCase {
$Session->setFlash('This is a test message', 'non_existing_layout');
$this->assertEqual($Session->read('Message.myFlash'), array('message' => 'This is a test message', 'layout' => 'default', 'params' => array()));
$Session->del('Message');
}
/**
* testSessionId method

View file

@ -1,5 +1,4 @@
<?php
/* SVN FILE: $Id$ */
/**
* ControllerTest file
*
@ -7,22 +6,18 @@
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The Open Group Test Suite License
* Redistributions of files must retain the above copyright notice.
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.tests.cases.libs.controller
* @since CakePHP(tm) v 1.2.0.5436
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'Controller');
App::import('Component', 'Security');
@ -63,7 +58,7 @@ if (!class_exists('AppController')) {
*/
var $components = array('Cookie');
}
} else if (!defined('APP_CONTROLLER_EXISTS')) {
} elseif (!defined('APP_CONTROLLER_EXISTS')) {
define('APP_CONTROLLER_EXISTS', true);
}
/**
@ -373,6 +368,15 @@ class ControllerTest extends CakeTestCase {
* @access public
*/
var $fixtures = array('core.post', 'core.comment', 'core.name');
/**
* endTest
*
* @access public
* @return void
*/
function endTest() {
App::build();
}
/**
* testConstructClasses method
*
@ -399,10 +403,7 @@ class ControllerTest extends CakeTestCase {
unset($Controller);
$_back = array(
'pluginPaths' => Configure::read('pluginPaths'),
);
Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS));
App::build(array('plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)));
$Controller =& new Controller();
$Controller->uses = array('TestPlugin.TestPluginPost');
@ -412,7 +413,6 @@ class ControllerTest extends CakeTestCase {
$this->assertTrue(isset($Controller->TestPluginPost));
$this->assertTrue(is_a($Controller->TestPluginPost, 'TestPluginPost'));
Configure::write('pluginPaths', $_back['pluginPaths']);
unset($Controller);
}
/**
@ -604,6 +604,26 @@ class ControllerTest extends CakeTestCase {
);
$this->assertEqual($Controller->params['paging']['ControllerPost']['options'],$expected);
}
/**
* Test that special paginate types are called and that the type param doesn't leak out into defaults or options.
*
* @return void
**/
function testPaginateSpecialType() {
$Controller =& new Controller();
$Controller->uses = array('ControllerPost', 'ControllerComment');
$Controller->passedArgs[] = '1';
$Controller->params['url'] = array();
$Controller->constructClasses();
$Controller->paginate = array('ControllerPost' => array('popular', 'fields' => array('id', 'title')));
$result = $Controller->paginate('ControllerPost');
$this->assertEqual(Set::extract($result, '{n}.ControllerPost.id'), array(2, 3));
$this->assertEqual($Controller->ControllerPost->lastQuery['conditions'], array('ControllerPost.id > ' => '1'));
$this->assertFalse(isset($Controller->params['paging']['ControllerPost']['defaults'][0]));
$this->assertFalse(isset($Controller->params['paging']['ControllerPost']['options'][0]));
}
/**
* testDefaultPaginateParams method
*
@ -691,7 +711,7 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testRender() {
Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS, TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS));
App::build(array('views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)));
$Controller =& new Controller();
$Controller->viewPath = 'posts';
@ -867,7 +887,9 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testMergeVars() {
$this->skipIf(defined('APP_CONTROLLER_EXISTS'), 'MergeVars will be skipped as it needs a non-existent AppController. As the an AppController class exists, this cannot be run.');
if ($this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController')) {
return;
}
$TestController =& new TestController();
$TestController->constructClasses();
@ -918,6 +940,22 @@ class ControllerTest extends CakeTestCase {
$this->assertTrue(isset($TestController->ControllerPost));
$this->assertTrue(isset($TestController->ControllerComment));
}
/**
* test that options from child classes replace those in the parent classes.
*
* @access public
* @return void
**/
function testChildComponentOptionsSupercedeParents() {
if ($this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController')) {
return;
}
$TestController =& new TestController();
$expected = array('foo');
$TestController->components = array('Cookie' => $expected);
$TestController->constructClasses();
$this->assertEqual($TestController->components['Cookie'], $expected);
}
/**
* Ensure that __mergeVars is not being greedy and merging with
* AppController when you make an instance of Controller
@ -950,6 +988,16 @@ class ControllerTest extends CakeTestCase {
$expected = 'http://cakephp.org';
$this->assertIdentical($result, $expected);
$_SERVER['HTTP_REFERER'] = '';
$referer = array(
'controller' => 'pages',
'action' => 'display',
'home'
);
$result = $Controller->referer($referer, false);
$expected = 'http://' . env('HTTP_HOST') . '/pages/display/home';
$this->assertIdentical($result, $expected);
$_SERVER['HTTP_REFERER'] = '';
$result = $Controller->referer(null, false);
$expected = '/';

View file

@ -0,0 +1,222 @@
<?php
/* SVN FILE: $Id$ */
/**
* Controller Merge vars Test file
*
* Isolated from the Controller and Component test as to not pollute their AppController class
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
*
* Licensed under The Open Group Test Suite License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests
* @package cake
* @subpackage cake.tests.cases.libs.controller
* @since CakePHP(tm) v 1.2.3
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!class_exists('AppController')) {
/**
* Test case AppController requred
*
* @package cake.tests.cases.libs.controller
**/
class AppController extends Controller {
/**
* components
*
* @var array
**/
var $components = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => false));
/**
* helpers
*
* @var array
**/
var $helpers = array('MergeVar' => array('format' => 'html', 'terse'));
}
} elseif (!defined('APP_CONTROLLER_EXISTS')) {
define('APP_CONTROLLER_EXISTS', true);
}
/**
* MergeVar Component
*
* @package cake.tests.cases.libs.controller
**/
class MergeVarComponent extends Object {
}
/**
* Additional controller for testing
*
* @package cake.tests.cases.libs.controller
**/
class MergeVariablesController extends AppController {
/**
* name
*
* @var string
**/
var $name = 'MergeVariables';
/**
* uses
*
* @var arrays
**/
var $uses = array();
}
/**
* MergeVarPlugin App Controller
*
* @package cake.tests.cases.libs.controller
**/
class MergeVarPluginAppController extends AppController {
/**
* components
*
* @var array
**/
var $components = array('Auth' => array('setting' => 'val', 'otherVal'));
/**
* helpers
*
* @var array
**/
var $helpers = array('Javascript');
}
/**
* MergePostsController
*
* @package cake.tests.cases.libs.controller
**/
class MergePostsController extends MergeVarPluginAppController {
/**
* name
*
* @var string
**/
var $name = 'MergePosts';
/**
* uses
*
* @var array
**/
var $uses = array();
}
/**
* Test Case for Controller Merging of Vars.
*
* @package cake.tests.cases.libs.controller
**/
class ControllerMergeVarsTestCase extends CakeTestCase {
/**
* end test
*
* @return void
**/
function endTest() {
ClassRegistry::flush();
}
/**
* test that component settings are not duplicated when merging component settings
*
* @return void
**/
function testComponentParamMergingNoDuplication() {
$Controller =& new MergeVariablesController();
$Controller->constructClasses();
$expected = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => false));
$this->assertEqual($Controller->components, $expected, 'Duplication of settings occured. %s');
}
/**
* test component merges with redeclared components
*
* @return void
**/
function testComponentMergingWithRedeclarations() {
$Controller =& new MergeVariablesController();
$Controller->components['MergeVar'] = array('remote', 'redirect' => true);
$Controller->constructClasses();
$expected = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => true, 'remote'));
$this->assertEqual($Controller->components, $expected, 'Merging of settings is wrong. %s');
}
/**
* test merging of helpers array, ensure no duplication occurs
*
* @return void
**/
function testHelperSettingMergingNoDuplication() {
$Controller =& new MergeVariablesController();
$Controller->constructClasses();
$expected = array('MergeVar' => array('format' => 'html', 'terse'));
$this->assertEqual($Controller->helpers, $expected, 'Duplication of settings occured. %s');
}
/**
* test merging of vars with plugin
*
* @return void
**/
function testMergeVarsWithPlugin() {
$Controller =& new MergePostsController();
$Controller->components = array('Email' => array('ports' => 'open'));
$Controller->plugin = 'MergeVarPlugin';
$Controller->constructClasses();
$expected = array(
'MergeVar' => array('flag', 'otherFlag', 'redirect' => false),
'Auth' => array('setting' => 'val', 'otherVal'),
'Email' => array('ports' => 'open')
);
$this->assertEqual($Controller->components, $expected, 'Components are unexpected %s');
$expected = array(
'Javascript',
'MergeVar' => array('format' => 'html', 'terse')
);
$this->assertEqual($Controller->helpers, $expected, 'Helpers are unexpected %s');
$Controller =& new MergePostsController();
$Controller->components = array();
$Controller->plugin = 'MergeVarPlugin';
$Controller->constructClasses();
$expected = array(
'MergeVar' => array('flag', 'otherFlag', 'redirect' => false),
'Auth' => array('setting' => 'val', 'otherVal'),
);
$this->assertEqual($Controller->components, $expected, 'Components are unexpected %s');
}
/**
* Ensure that __mergeVars is not being greedy and merging with
* AppController when you make an instance of Controller
*
* @return void
**/
function testMergeVarsNotGreedy() {
$Controller =& new Controller();
$Controller->components = array();
$Controller->uses = array();
$Controller->constructClasses();
$this->assertTrue(isset($Controller->Session));
}
}

View file

@ -24,7 +24,12 @@
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', array('Controller', 'AppController', 'PagesController'));
if (!class_exists('AppController')) {
require_once LIBS . 'controller' . DS . 'app_controller.php';
} elseif (!defined('APP_CONTROLLER_EXISTS')) {
define('APP_CONTROLLER_EXISTS', true);
}
App::import('Core', array('Controller', 'PagesController'));
/**
* PagesControllerTest class
*
@ -32,6 +37,15 @@ App::import('Core', array('Controller', 'AppController', 'PagesController'));
* @subpackage cake.tests.cases.libs.controller
*/
class PagesControllerTest extends CakeTestCase {
/**
* endTest method
*
* @access public
* @return void
*/
function endTest() {
App::build();
}
/**
* testDisplay method
*
@ -39,7 +53,11 @@ class PagesControllerTest extends CakeTestCase {
* @return void
*/
function testDisplay() {
Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS, TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS));
if ($this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController')) {
return;
}
App::build(array('views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS, TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS)));
$Pages =& new PagesController();
$Pages->viewPath = 'posts';

View file

@ -47,6 +47,37 @@ class ScaffoldMockController extends Controller {
*/
var $scaffold;
}
/**
* ScaffoldMockControllerWithFields class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class ScaffoldMockControllerWithFields extends Controller {
/**
* name property
*
* @var string 'ScaffoldMock'
* @access public
*/
var $name = 'ScaffoldMock';
/**
* scaffold property
*
* @var mixed
* @access public
*/
var $scaffold;
/**
* function _beforeScaffold
*
* @param string method
*/
function _beforeScaffold($method) {
$this->set('scaffoldFields', array('title'));
return true;
}
}
/**
* TestScaffoldMock class
*
@ -332,11 +363,11 @@ class ScaffoldViewTest extends CakeTestCase {
new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertPattern('#<h2>ScaffoldMock</h2>#', $result);
$this->assertPattern('#<h2>Scaffold Mock</h2>#', $result);
$this->assertPattern('#<table cellpadding="0" cellspacing="0">#', $result);
//TODO: add testing for table generation
$this->assertPattern('#<a href="/scaffold_users/view/1">1</a>#', $result); //belongsTo links
$this->assertPattern('#<li><a href="/scaffold_mock/add/">New ScaffoldMock</a></li>#', $result);
$this->assertPattern('#<li><a href="/scaffold_mock/add/">New Scaffold Mock</a></li>#', $result);
$this->assertPattern('#<li><a href="/scaffold_users/">List Scaffold Users</a></li>#', $result);
$this->assertPattern('#<li><a href="/scaffold_comments/add/">New Comment</a></li>#', $result);
}
@ -371,12 +402,12 @@ class ScaffoldViewTest extends CakeTestCase {
new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertPattern('/<h2>View ScaffoldMock<\/h2>/', $result);
$this->assertPattern('/<h2>View Scaffold Mock<\/h2>/', $result);
$this->assertPattern('/<dl>/', $result);
//TODO: add specific tests for fields.
$this->assertPattern('/<a href="\/scaffold_users\/view\/1">1<\/a>/', $result); //belongsTo links
$this->assertPattern('/<li><a href="\/scaffold_mock\/edit\/1">Edit ScaffoldMock<\/a>\s<\/li>/', $result);
$this->assertPattern('/<li><a href="\/scaffold_mock\/delete\/1"[^>]*>Delete ScaffoldMock<\/a>\s*<\/li>/', $result);
$this->assertPattern('/<li><a href="\/scaffold_mock\/edit\/1">Edit Scaffold Mock<\/a>\s<\/li>/', $result);
$this->assertPattern('/<li><a href="\/scaffold_mock\/delete\/1"[^>]*>Delete Scaffold Mock<\/a>\s*<\/li>/', $result);
//check related table
$this->assertPattern('/<div class="related">\s*<h3>Related Scaffold Comments<\/h3>\s*<table cellpadding="0" cellspacing="0">/', $result);
$this->assertPattern('/<li><a href="\/scaffold_comments\/add\/">New Comment<\/a><\/li>/', $result);
@ -459,10 +490,10 @@ class ScaffoldViewTest extends CakeTestCase {
$Scaffold = new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertPattern('/<h2>ScaffoldMock<\/h2>/', $result);
$this->assertPattern('/<h2>Scaffold Mock<\/h2>/', $result);
$this->assertPattern('/<table cellpadding="0" cellspacing="0">/', $result);
//TODO: add testing for table generation
$this->assertPattern('/<li><a href="\/admin\/scaffold_mock\/add\/">New ScaffoldMock<\/a><\/li>/', $result);
$this->assertPattern('/<li><a href="\/admin\/scaffold_mock\/add\/">New Scaffold Mock<\/a><\/li>/', $result);
Configure::write('Routing.admin', $_backAdmin);
}
@ -580,5 +611,76 @@ class ScaffoldTest extends CakeTestCase {
$result = $Scaffold->getParams();
$this->assertEqual($result['action'], 'admin_edit');
}
/**
* test that the proper names and variable values are set by Scaffold
*
* @return void
**/
function testScaffoldVariableSetting() {
$this->Controller->action = 'admin_edit';
$this->Controller->here = '/admin/scaffold_mock/edit';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(),
'form' => array(),
'named' => array(),
'url' => array('url' =>'admin/scaffold_mock/edit'),
'controller' => 'scaffold_mock',
'action' => 'admin_edit',
'admin' => true,
);
//set router.
Router::setRequestInfo(array($params, array('base' => '/', 'here' => 'admin/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->constructClasses();
$Scaffold =& new TestScaffoldMock($this->Controller, $params);
$result = $this->Controller->viewVars;
$this->assertEqual($result['singularHumanName'], 'Scaffold Mock');
$this->assertEqual($result['pluralHumanName'], 'Scaffold Mock');
$this->assertEqual($result['modelClass'], 'ScaffoldMock');
$this->assertEqual($result['primaryKey'], 'id');
$this->assertEqual($result['displayField'], 'title');
$this->assertEqual($result['singularVar'], 'scaffoldMock');
$this->assertEqual($result['pluralVar'], 'scaffoldMock');
$this->assertEqual($result['scaffoldFields'], array('id', 'user_id', 'title', 'body', 'published', 'created', 'updated'));
}
/**
* test that the proper names and variable values are set by Scaffold
*
* @return void
**/
function testEditScaffoldWithScaffoldFields() {
$this->Controller = new ScaffoldMockControllerWithFields();
$this->Controller->action = 'edit';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' =>'scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'edit',
);
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertNoPattern('/textarea name="data\[ScaffoldMock\]\[body\]" cols="30" rows="6" id="ScaffoldMockBody"/', $result);
}
}
?>

View file

@ -7,22 +7,18 @@
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
* Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The Open Group Test Suite License
* Redistributions of files must retain the above copyright notice.
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org
* @package cake
* @subpackage cake.tests.cases.libs
* @since CakePHP(tm) v 1.2.0.5432
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'Debugger');
/**
@ -88,10 +84,18 @@ class DebuggerTest extends CakeTestCase {
* @return void
*/
function testExcerpt() {
$return = Debugger::excerpt(__FILE__, 2, 2);
$this->assertTrue(is_array($return));
$this->assertEqual(count($return), 4);
$this->assertPattern('#/*&nbsp;SVN&nbsp;FILE:&nbsp;\$Id:&nbsp;debugger.test.php#', $return[1]);
$result = Debugger::excerpt(__FILE__, __LINE__, 2);
$this->assertTrue(is_array($result));
$this->assertEqual(count($result), 5);
$this->assertPattern('/function(.+)testExcerpt/', $result[1]);
$result = Debugger::excerpt(__FILE__, 2, 2);
$this->assertTrue(is_array($result));
$this->assertEqual(count($result), 4);
$expected = '<code><span style="color: #000000"><span style="color: #0000BB">&lt;?php';
$expected .= '</span></span></code>';
$this->assertEqual($result[0], $expected);
$return = Debugger::excerpt('[internal]', 2, 2);
$this->assertTrue(empty($return));
@ -135,14 +139,60 @@ class DebuggerTest extends CakeTestCase {
ob_start();
Debugger::output('js');
$buzz .= '';
$result = ob_get_clean();
$this->assertPattern("/<a href\='javascript:void\(0\);' onclick\='/", $result);
$this->assertPattern('/<b>Notice<\/b>/', $result);
$this->assertPattern('/Undefined variable: buzz/', $result);
$this->assertPattern('/<a[^>]+>Code<\/a>/', $result);
$this->assertPattern('/<a[^>]+>Context<\/a>/', $result);
$result = explode('</a>', ob_get_clean());
$this->assertTags($result[0], array(
'a' => array(
'href' => "javascript:void(0);",
'onclick' => "document.getElementById('cakeErr4-trace').style.display = " .
"(document.getElementById('cakeErr4-trace').style.display == 'none'" .
" ? '' : 'none');"
),
'b' => array(), 'Notice', '/b', ' (8)'
));
$this->assertPattern('/Undefined variable: buzz/', $result[1]);
$this->assertPattern('/<a[^>]+>Code/', $result[1]);
$this->assertPattern('/<a[^>]+>Context/', $result[2]);
set_error_handler('simpleTestErrorHandler');
}
/**
* Tests that changes in output formats using Debugger::output() change the templates used.
*
* @return void
*/
function testChangeOutputFormats() {
Debugger::invoke(Debugger::getInstance());
Debugger::output('js', array(
'traceLine' => '{:reference} - <a href="txmt://open?url=file://{:file}' .
'&line={:line}">{:path}</a>, line {:line}'
));
$result = Debugger::trace();
$this->assertPattern('/' . preg_quote('txmt://open?url=file:///', '/') . '/', $result);
Debugger::output('xml', array(
'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' .
'{:description}</error>',
'context' => "<context>{:context}</context>",
'trace' => "<stack>{:trace}</stack>",
));
Debugger::output('xml');
ob_start();
$foo .= '';
$result = ob_get_clean();
set_error_handler('simpleTestErrorHandler');
$data = array(
'error' => array(),
'code' => array(), '8', '/code',
'file' => array(), 'preg:/[^<]+/', '/file',
'line' => array(), '' . (intval(__LINE__) + -8), '/line',
'Undefined variable: foo',
'/error'
);
$this->assertTags($result, $data, true);
}
/**
* testTrimPath method
*
@ -218,15 +268,14 @@ class DebuggerTest extends CakeTestCase {
Debugger::log('cool');
$result = file_get_contents(LOGS . 'debug.log');
$this->assertPattern('/DebuggerTest::testLog/', $result);
$this->assertPattern('/DebuggerTest\:\:testLog/', $result);
$this->assertPattern('/"cool"/', $result);
unlink(TMP . 'logs' . DS . 'debug.log');
Debugger::log(array('whatever', 'here'));
$result = file_get_contents(TMP . 'logs' . DS . 'debug.log');
$this->assertPattern('/DebuggerTest::testLog/', $result);
$this->assertPattern('/DebuggerTest\:\:testLog/', $result);
$this->assertPattern('/array/', $result);
$this->assertPattern('/"whatever",/', $result);
$this->assertPattern('/"here"/', $result);

View file

@ -95,48 +95,50 @@ class AuthBlueberryUser extends CakeTestModel {
var $useTable = false;
}
if (!class_exists('AppController')) {
/**
* AppController class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class AppController extends Controller {
/**
* components property
*
* @access public
* @return void
*/
var $components = array('Blueberry');
/**
* beforeRender method
*
* @access public
* @return void
*/
function beforeRender() {
echo $this->Blueberry->testName;
/**
* AppController class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class AppController extends Controller {
/**
* components property
*
* @access public
* @return void
*/
var $components = array('Blueberry');
/**
* beforeRender method
*
* @access public
* @return void
*/
function beforeRender() {
echo $this->Blueberry->testName;
}
/**
* header method
*
* @access public
* @return void
*/
function header($header) {
echo $header;
}
/**
* _stop method
*
* @access public
* @return void
*/
function _stop($status = 0) {
echo 'Stopped with status: ' . $status;
}
}
/**
* header method
*
* @access public
* @return void
*/
function header($header) {
echo $header;
}
/**
* _stop method
*
* @access public
* @return void
*/
function _stop($status = 0) {
echo 'Stopped with status: ' . $status;
}
}
} elseif (!defined('APP_CONTROLLER_EXISTS')){
define('APP_CONTROLLER_EXISTS', true);
}
App::import('Core', array('Error', 'Controller'));
/**
@ -224,7 +226,7 @@ class ErrorHandlerTest extends CakeTestCase {
* @return void
*/
function skip() {
$this->skipif ((PHP_SAPI == 'cli'), 'TestErrorHandlerTest cannot be run from console');
$this->skipIf(PHP_SAPI === 'cli', '%s Cannot be run from console');
}
/**
* testError method
@ -277,6 +279,8 @@ class ErrorHandlerTest extends CakeTestCase {
* @return void
*/
function testMissingController() {
$this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController');
ob_start();
$TestErrorHandler = new TestErrorHandler('missingController', array('className' => 'PostsController'));
$result = ob_get_clean();

View file

@ -95,7 +95,7 @@ class FileTest extends CakeTestCase {
$result = $this->File->Folder();
$this->assertIsA($result, 'Folder');
$this->skipIf(DIRECTORY_SEPARATOR === '\\', 'File permissions tests not supported on Windows');
$this->skipIf(DIRECTORY_SEPARATOR === '\\', '%s File permissions tests not supported on Windows');
$result = $this->File->perms();
$expecting = '0644';
$this->assertEqual($result, $expecting);

View file

@ -161,7 +161,7 @@ class FolderTest extends CakeTestCase {
* @access public
*/
function testChmod() {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Folder permissions tests not supported on Windows');
$this->skipIf(DIRECTORY_SEPARATOR === '\\', '%s Folder permissions tests not supported on Windows');
$path = TEST_CAKE_CORE_INCLUDE_PATH . 'console' . DS . 'libs' . DS . 'templates' . DS . 'skel';
$Folder =& new Folder($path);
@ -566,5 +566,141 @@ class FolderTest extends CakeTestCase {
);
$this->assertEqual($expected, $messages);
}
/**
* testCopy method
*
* Verify that directories and files are copied recursively
* even if the destination directory already exists.
* Subdirectories existing in both destination and source directory
* are skipped and not merged or overwritten.
*
* @return void
* @access public
* @link https://trac.cakephp.org/ticket/6259
*/
function testCopy() {
$path = TMP . 'folder_test';
$folder1 = $path . DS . 'folder1';
$folder2 = $folder1 . DS . 'folder2';
$folder3 = $path . DS . 'folder3';
$file1 = $folder1 . DS . 'file1.php';
$file2 = $folder2 . DS . 'file2.php';
new Folder($path, true);
new Folder($folder1, true);
new Folder($folder2, true);
new Folder($folder3, true);
touch($file1);
touch($file2);
$Folder =& new Folder($folder1);
$result = $Folder->copy($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
$this->assertTrue(file_exists($folder3 . DS . 'folder2' . DS . 'file2.php'));
$Folder =& new Folder($folder3);
$Folder->delete();
$Folder =& new Folder($folder1);
$result = $Folder->copy($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
$this->assertTrue(file_exists($folder3 . DS . 'folder2' . DS . 'file2.php'));
$Folder =& new Folder($folder3);
$Folder->delete();
new Folder($folder3, true);
new Folder($folder3 . DS . 'folder2', true);
file_put_contents($folder3 . DS . 'folder2' . DS . 'file2.php', 'untouched');
$Folder =& new Folder($folder1);
$result = $Folder->copy($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
$this->assertEqual(file_get_contents($folder3 . DS . 'folder2' . DS . 'file2.php'), 'untouched');
$Folder =& new Folder($path);
$Folder->delete();
}
/**
* testMove method
*
* Verify that directories and files are moved recursively
* even if the destination directory already exists.
* Subdirectories existing in both destination and source directory
* are skipped and not merged or overwritten.
*
* @return void
* @access public
* @link https://trac.cakephp.org/ticket/6259
*/
function testMove() {
$path = TMP . 'folder_test';
$folder1 = $path . DS . 'folder1';
$folder2 = $folder1 . DS . 'folder2';
$folder3 = $path . DS . 'folder3';
$file1 = $folder1 . DS . 'file1.php';
$file2 = $folder2 . DS . 'file2.php';
new Folder($path, true);
new Folder($folder1, true);
new Folder($folder2, true);
new Folder($folder3, true);
touch($file1);
touch($file2);
$Folder =& new Folder($folder1);
$result = $Folder->move($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
$this->assertTrue(is_dir($folder3 . DS . 'folder2'));
$this->assertTrue(file_exists($folder3 . DS . 'folder2' . DS . 'file2.php'));
$this->assertFalse(file_exists($file1));
$this->assertFalse(file_exists($folder2));
$this->assertFalse(file_exists($file2));
$Folder =& new Folder($folder3);
$Folder->delete();
new Folder($folder1, true);
new Folder($folder2, true);
touch($file1);
touch($file2);
$Folder =& new Folder($folder1);
$result = $Folder->move($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
$this->assertTrue(is_dir($folder3 . DS . 'folder2'));
$this->assertTrue(file_exists($folder3 . DS . 'folder2' . DS . 'file2.php'));
$this->assertFalse(file_exists($file1));
$this->assertFalse(file_exists($folder2));
$this->assertFalse(file_exists($file2));
$Folder =& new Folder($folder3);
$Folder->delete();
new Folder($folder1, true);
new Folder($folder2, true);
new Folder($folder3, true);
new Folder($folder3 . DS . 'folder2', true);
touch($file1);
touch($file2);
file_put_contents($folder3 . DS . 'folder2' . DS . 'file2.php', 'untouched');
$Folder =& new Folder($folder1);
$result = $Folder->move($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
$this->assertEqual(file_get_contents($folder3 . DS . 'folder2' . DS . 'file2.php'), 'untouched');
$this->assertFalse(file_exists($file1));
$this->assertFalse(file_exists($folder2));
$this->assertFalse(file_exists($file2));
$Folder =& new Folder($path);
$Folder->delete();
}
}
?>
?>

View file

@ -25,6 +25,132 @@
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', 'HttpSocket');
class TestHttpSocket extends HttpSocket {
/**
* Convenience method for testing protected method
*
* @param mixed $uri URI (see {@link _parseUri()})
* @return array Current configuration settings
*/
function configUri($uri = null) {
return parent::_configUri($uri);
}
/**
* Convenience method for testing protected method
*
* @param string $uri URI to parse
* @param mixed $base If true use default URI config, otherwise indexed array to set 'scheme', 'host', 'port', etc.
* @return array Parsed URI
*/
function parseUri($uri = null, $base = array()) {
return parent::_parseUri($uri, $base);
}
/**
* Convenience method for testing protected method
*
* @param array $uri A $uri array, or uses $this->config if left empty
* @param string $uriTemplate The Uri template/format to use
* @return string A fully qualified URL formated according to $uriTemplate
*/
function buildUri($uri = array(), $uriTemplate = '%scheme://%user:%pass@%host:%port/%path?%query#%fragment') {
return parent::_buildUri($uri, $uriTemplate);
}
/**
* Convenience method for testing protected method
*
* @param array $header Header to build
* @return string Header built from array
*/
function buildHeader($header, $mode = 'standard') {
return parent::_buildHeader($header, $mode);
}
/**
* Convenience method for testing protected method
*
* @param string $message Message to parse
* @return array Parsed message (with indexed elements such as raw, status, header, body)
*/
function parseResponse($message) {
return parent::_parseResponse($message);
}
/**
* Convenience method for testing protected method
*
* @param array $header Header as an indexed array (field => value)
* @return array Parsed header
*/
function parseHeader($header) {
return parent::_parseHeader($header);
}
/**
* Convenience method for testing protected method
*
* @param mixed $query A query string to parse into an array or an array to return directly "as is"
* @return array The $query parsed into a possibly multi-level array. If an empty $query is given, an empty array is returned.
*/
function parseQuery($query) {
return parent::_parseQuery($query);
}
/**
* Convenience method for testing protected method
*
* @param string $body A string continaing the body to decode
* @param mixed $encoding Can be false in case no encoding is being used, or a string representing the encoding
* @return mixed Array or false
*/
function decodeBody($body, $encoding = 'chunked') {
return parent::_decodeBody($body, $encoding);
}
/**
* Convenience method for testing protected method
*
* @param string $body A string continaing the chunked body to decode
* @return mixed Array or false
*/
function decodeChunkedBody($body) {
return parent::_decodeChunkedBody($body);
}
/**
* Convenience method for testing protected method
*
* @param array $request Needs to contain a 'uri' key. Should also contain a 'method' key, otherwise defaults to GET.
* @param string $versionToken The version token to use, defaults to HTTP/1.1
* @return string Request line
*/
function buildRequestLine($request = array(), $versionToken = 'HTTP/1.1') {
return parent::_buildRequestLine($request, $versionToken);
}
/**
* Convenience method for testing protected method
*
* @param boolean $hex true to get them as HEX values, false otherwise
* @return array Escape chars
*/
function tokenEscapeChars($hex = true, $chars = null) {
return parent::_tokenEscapeChars($hex, $chars);
}
/**
* Convenience method for testing protected method
*
* @param string $token Token to escape
* @return string Escaped token
*/
function EscapeToken($token, $chars = null) {
return parent::_escapeToken($token, $chars);
}
/**
* Convenience method for testing protected method
*
* @param string $token Token to unescape
* @return string Unescaped token
*/
function unescapeToken($token, $chars = null) {
return parent::_unescapeToken($token, $chars);
}
}
/**
* HttpSocketTest class
*
@ -53,13 +179,13 @@ class HttpSocketTest extends CakeTestCase {
* @return void
*/
function setUp() {
if (!class_exists('TestHttpSocket')) {
Mock::generatePartial('HttpSocket', 'TestHttpSocket', array('read', 'write', 'connect'));
Mock::generatePartial('HttpSocket', 'TestHttpSocketRequests', array('read', 'write', 'connect', 'request'));
if (!class_exists('MockHttpSocket')) {
Mock::generatePartial('TestHttpSocket', 'MockHttpSocket', array('read', 'write', 'connect'));
Mock::generatePartial('TestHttpSocket', 'MockHttpSocketRequests', array('read', 'write', 'connect', 'request'));
}
$this->Socket =& new TestHttpSocket();
$this->RequestSocket =& new TestHttpSocketRequests();
$this->Socket =& new MockHttpSocket();
$this->RequestSocket =& new MockHttpSocketRequests();
}
/**
* We use this function to clean up after the test case was executed
@ -373,12 +499,6 @@ class HttpSocketTest extends CakeTestCase {
$r = array('config' => $this->Socket->config, 'request' => $this->Socket->request);
$v = $this->assertIdentical($r, $expectation, '%s in test #'.$i.' ');
if (!$v) {
debug('Result:');
debug($r);
debug('Expected:');
debug($expectation);
}
$expectation['request']['raw'] = $raw;
}
@ -1156,7 +1276,8 @@ class HttpSocketTest extends CakeTestCase {
$header = array(
'Set-Cookie' => array(
'foo=bar',
'people=jim,jack,johnny";";Path=/accounts'
'people=jim,jack,johnny";";Path=/accounts',
'google=not=nice'
),
'Transfer-Encoding' => 'chunked',
'Date' => 'Sun, 18 Nov 2007 18:57:42 GMT',
@ -1168,7 +1289,10 @@ class HttpSocketTest extends CakeTestCase {
),
'people' => array(
'value' => 'jim,jack,johnny";"',
'path' => '/accounts'
'path' => '/accounts',
),
'google' => array(
'value' => 'not=nice',
)
);
$this->assertEqual($cookies, $expected);
@ -1179,7 +1303,7 @@ class HttpSocketTest extends CakeTestCase {
$this->assertEqual($cookies, $expected);
$header['Set-Cookie'] = 'foo=bar';
unset($expected['people'], $expected['cakephp']);
unset($expected['people'], $expected['cakephp'], $expected['google']);
$cookies = $this->Socket->parseCookies($header);
$this->assertEqual($cookies, $expected);
}
@ -1205,7 +1329,7 @@ class HttpSocketTest extends CakeTestCase {
$this->assertEqual($result, $expect);
}
/**
* Tests that HttpSocket::__tokenEscapeChars() returns the right characters.
* Tests that HttpSocket::_tokenEscapeChars() returns the right characters.
*
* @access public
* @return void
@ -1219,14 +1343,14 @@ class HttpSocketTest extends CakeTestCase {
'\x0e','\x0f','\x10','\x11','\x12','\x13','\x14','\x15','\x16','\x17','\x18','\x19','\x1a','\x1b','\x1c','\x1d',
'\x1e','\x1f','\x7f'
);
$r = $this->Socket->__tokenEscapeChars();
$r = $this->Socket->tokenEscapeChars();
$this->assertEqual($r, $expected);
foreach ($expected as $key => $char) {
$expected[$key] = chr(hexdec(substr($char, 2)));
}
$r = $this->Socket->__tokenEscapeChars(false);
$r = $this->Socket->tokenEscapeChars(false);
$this->assertEqual($r, $expected);
}
/**
@ -1240,7 +1364,7 @@ class HttpSocketTest extends CakeTestCase {
$this->assertIdentical($this->Socket->escapeToken('Foo'), 'Foo');
$escape = $this->Socket->__tokenEscapeChars(false);
$escape = $this->Socket->tokenEscapeChars(false);
foreach ($escape as $char) {
$token = 'My-special-'.$char.'-Token';
$escapedToken = $this->Socket->escapeToken($token);
@ -1265,7 +1389,7 @@ class HttpSocketTest extends CakeTestCase {
$this->assertIdentical($this->Socket->unescapeToken('Foo'), 'Foo');
$escape = $this->Socket->__tokenEscapeChars(false);
$escape = $this->Socket->tokenEscapeChars(false);
foreach ($escape as $char) {
$token = 'My-special-"'.$char.'"-Token';
$unescapedToken = $this->Socket->unescapeToken($token);

View file

@ -39,7 +39,19 @@ class I18nTest extends CakeTestCase {
* @return void
*/
function setUp() {
Configure::write('localePaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'locale'));
$this->_localePaths = App::path('locales');
App::build(array(
'locales' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'locale')
));
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
App::build();
}
/**
* testDefaultStrings method
@ -2343,8 +2355,9 @@ class I18nTest extends CakeTestCase {
* @return void
*/
function testPluginTranslation() {
$pluginPaths = Configure::read('pluginPaths');
Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins'));
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins')
));
Configure::write('Config.language', 'po');
$singular = $this->__domainSingular();
@ -2378,7 +2391,7 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 = 0 or > 1 (from plugin)', $plurals));
$this->assertTrue(in_array('25 = 0 or > 1 (from plugin)', $plurals));
Configure::write('pluginPaths', $pluginPaths);
App::build();
}
/**
* testPoMultipleLineTranslation method

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