code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
<?php
/**
* CakeTestSuiteDispatcher controls dispatching TestSuite web based requests.
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.TestSuite
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
define('CORE_TEST_CASES', CAKE . 'Test' . DS . 'Case');
define('APP_TEST_CASES', TESTS . 'Case');
App::uses('CakeTestSuiteCommand', 'TestSuite');
/**
* CakeTestSuiteDispatcher handles web requests to the test suite and runs the correct action.
*
* @package Cake.TestSuite
*/
class CakeTestSuiteDispatcher {
/**
* 'Request' parameters
*
* @var array
*/
public $params = array(
'codeCoverage' => false,
'case' => null,
'core' => false,
'app' => false,
'plugin' => null,
'output' => 'html',
'show' => 'groups',
'show_passes' => false,
'filter' => false,
'fixture' => null
);
/**
* Baseurl for the request
*
* @var string
*/
protected $_baseUrl;
/**
* Base dir of the request. Used for accessing assets.
*
* @var string
*/
protected $_baseDir;
/**
* boolean to set auto parsing of params.
*
* @var boolean
*/
protected $_paramsParsed = false;
/**
* reporter instance used for the request
*
* @var CakeBaseReporter
*/
protected static $_Reporter = null;
/**
* constructor
*
* @return void
*/
function __construct() {
$this->_baseUrl = $_SERVER['PHP_SELF'];
$dir = rtrim(dirname($this->_baseUrl), '\\');
$this->_baseDir = ($dir === '/') ? $dir : $dir . '/';
}
/**
* Runs the actions required by the URL parameters.
*
* @return void
*/
public function dispatch() {
$this->_checkPHPUnit();
$this->_parseParams();
if ($this->params['case']) {
$value = $this->_runTestCase();
} else {
$value = $this->_testCaseList();
}
$output = ob_get_clean();
echo $output;
return $value;
}
/**
* Static method to initialize the test runner, keeps global space clean
*
* @return void
*/
public static function run() {
$dispatcher = new CakeTestSuiteDispatcher();
$dispatcher->dispatch();
}
/**
* Checks that PHPUnit is installed. Will exit if it doesn't
*
* @return void
*/
protected function _checkPHPUnit() {
$found = $this->loadTestFramework();
if (!$found) {
$baseDir = $this->_baseDir;
include CAKE . 'TestSuite' . DS . 'templates' . DS . 'phpunit.php';
exit();
}
}
/**
* Checks for the existence of the test framework files
*
* @return boolean true if found, false otherwise
*/
public function loadTestFramework() {
$found = $path = null;
if (@include 'PHPUnit' . DS . 'Autoload.php') {
$found = true;
}
if (!$found) {
foreach (App::path('vendors') as $vendor) {
if (is_dir($vendor . 'PHPUnit')) {
$path = $vendor;
}
}
if ($path && ini_set('include_path', $path . PATH_SEPARATOR . ini_get('include_path'))) {
$found = include 'PHPUnit' . DS . 'Autoload.php';
}
}
if ($found) {
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
}
return $found;
}
/**
* Checks for the xdebug extension required to do code coverage. Displays an error
* if xdebug isn't installed.
*
* @return void
*/
function _checkXdebug() {
if (!extension_loaded('xdebug')) {
$baseDir = $this->_baseDir;
include CAKE . 'TestSuite' . DS . 'templates' . DS . 'xdebug.php';
exit();
}
}
/**
* Generates a page containing the a list of test cases that could be run.
*
* @return void
*/
function _testCaseList() {
$command = new CakeTestSuiteCommand('', $this->params);
$Reporter = $command->handleReporter($this->params['output']);
$Reporter->paintDocumentStart();
$Reporter->paintTestMenu();
$Reporter->testCaseList();
$Reporter->paintDocumentEnd();
}
/**
* Sets the params, calling this will bypass the auto parameter parsing.
*
* @param array $params Array of parameters for the dispatcher
* @return void
*/
public function setParams($params) {
$this->params = $params;
$this->_paramsParsed = true;
}
/**
* Parse url params into a 'request'
*
* @return void
*/
function _parseParams() {
if (!$this->_paramsParsed) {
if (!isset($_SERVER['SERVER_NAME'])) {
$_SERVER['SERVER_NAME'] = '';
}
foreach ($this->params as $key => $value) {
if (isset($_GET[$key])) {
$this->params[$key] = $_GET[$key];
}
}
if (isset($_GET['code_coverage'])) {
$this->params['codeCoverage'] = true;
$this->_checkXdebug();
}
}
if (empty($this->params['plugin']) && empty($this->params['app'])) {
$this->params['core'] = true;
}
$this->params['baseUrl'] = $this->_baseUrl;
$this->params['baseDir'] = $this->_baseDir;
}
/**
* Runs a test case file.
*
* @return void
*/
function _runTestCase() {
$commandArgs = array(
'case' => $this->params['case'],
'core' =>$this->params['core'],
'app' => $this->params['app'],
'plugin' => $this->params['plugin'],
'codeCoverage' => $this->params['codeCoverage'],
'showPasses' => !empty($this->params['show_passes']),
'baseUrl' => $this->_baseUrl,
'baseDir' => $this->_baseDir,
);
$options = array(
'--filter', $this->params['filter'],
'--output', $this->params['output'],
'--fixture', $this->params['fixture']
);
restore_error_handler();
try {
$command = new CakeTestSuiteCommand('CakeTestLoader', $commandArgs);
$result = $command->run($options);
} catch (MissingConnectionException $exception) {
ob_end_clean();
$baseDir = $this->_baseDir;
include CAKE . 'TestSuite' . DS . 'templates' . DS . 'missing_connection.php';
exit();
}
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/CakeTestSuiteDispatcher.php | PHP | gpl3 | 5,981 |
<?php
/**
* ControllerTestCase file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package Cake.TestSuite
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
App::uses('Dispatcher', 'Routing');
App::uses('CakeTestCase', 'TestSuite');
App::uses('Router', 'Routing');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
App::uses('Helper', 'View');
/**
* ControllerTestDispatcher class
*
* @package Cake.TestSuite
*/
class ControllerTestDispatcher extends Dispatcher {
/**
* The controller to use in the dispatch process
*
* @var Controller
*/
public $testController = null;
/**
* Use custom routes during tests
*
* @var boolean
*/
public $loadRoutes = true;
/**
* Returns the test controller
*
* @return Controller
*/
function _getController($request, $response) {
if ($this->testController === null) {
$this->testController = parent::_getController($request, $response);
}
$this->testController->helpers = array_merge(array('InterceptContent'), $this->testController->helpers);
$this->testController->setRequest($request);
$this->testController->response = $this->response;
return $this->testController;
}
/**
* Loads routes and resets if the test case dictates it should
*
* @return void
*/
protected function _loadRoutes() {
parent::_loadRoutes();
if (!$this->loadRoutes) {
Router::reload();
}
}
}
/**
* InterceptContentHelper class
*
* @package Cake.TestSuite
*/
class InterceptContentHelper extends Helper {
/**
* Intercepts and stores the contents of the view before the layout is rendered
*
* @param string $viewFile The view file
*/
public function afterRender($viewFile) {
$this->_View->_viewNoLayout = $this->_View->output;
$this->_View->Helpers->unload('InterceptContent');
}
}
/**
* ControllerTestCase class
*
* @package Cake.TestSuite
*/
abstract class ControllerTestCase extends CakeTestCase {
/**
* The controller to test in testAction
*
* @var Controller
*/
public $controller = null;
/**
* Automatically mock controllers that aren't mocked
*
* @var boolean
*/
public $autoMock = false;
/**
* Use custom routes during tests
*
* @var boolean
*/
public $loadRoutes = true;
/**
* The resulting view vars of the last testAction call
*
* @var array
*/
public $vars = null;
/**
* The resulting rendered view of the last testAction call
*
* @var string
*/
public $view = null;
/**
* The resulting rendered layout+view of the last testAction call
*
* @var string
*/
public $contents = null;
/**
* The returned result of the dispatch (requestAction), if any
*
* @var string
*/
public $result = null;
/**
* The headers that would have been sent by the action
*
* @var string
*/
public $headers = null;
/**
* Used to enable calling ControllerTestCase::testAction() without the testing
* framework thinking that it's a test case
*
* @param string $name The name of the function
* @param array $arguments Array of arguments
* @return Function
*/
public function __call($name, $arguments) {
if ($name == 'testAction') {
return call_user_func_array(array($this, '_testAction'), $arguments);
}
}
/**
* Tests a controller action.
*
* ### Options:
*
* - `data` POST or GET data to pass. Depends on the method.
* - `method` POST or GET. Defaults to POST.
* - `return` Specify the return type you want. Choose from:
* - `vars` Get the set view variables.
* - `view` Get the rendered view, without a layout.
* - `contents` Get the rendered view including the layout.
* - `result` Get the return value of the controller action. Useful
* for testing requestAction methods.
*
* @param string $url The url to test
* @param array $options See options
*/
protected function _testAction($url = '', $options = array()) {
$this->vars = $this->result = $this->view = $this->contents = $this->headers = null;
$options = array_merge(array(
'data' => array(),
'method' => 'POST',
'return' => 'result'
), $options);
$_SERVER['REQUEST_METHOD'] = strtoupper($options['method']);
if (strtoupper($options['method']) == 'GET') {
$_GET = $options['data'];
$_POST = array();
} else {
$_POST = $options['data'];
$_GET = array();
}
$request = new CakeRequest($url);
$Dispatch = new ControllerTestDispatcher();
foreach (Router::$routes as $route) {
if ($route instanceof RedirectRoute) {
$route->response = $this->getMock('CakeResponse', array('send'));
}
}
$Dispatch->loadRoutes = $this->loadRoutes;
$request = $Dispatch->parseParams($request);
if (!isset($request->params['controller'])) {
$this->headers = Router::currentRoute()->response->header();
return;
}
if ($this->controller !== null && Inflector::camelize($request->params['controller']) !== $this->controller->name) {
$this->controller = null;
}
$plugin = empty($request->params['plugin']) ? '' : Inflector::camelize($request->params['plugin']) . '.';
if ($this->controller === null && $this->autoMock) {
$this->generate(Inflector::camelize($plugin . $request->params['controller']));
}
$params = array();
if ($options['return'] == 'result') {
$params['return'] = 1;
$params['bare'] = 1;
$params['requested'] = 1;
}
$Dispatch->testController = $this->controller;
$Dispatch->response = $this->getMock('CakeResponse', array('send'));
$this->result = $Dispatch->dispatch($request, $Dispatch->response, $params);
$this->controller = $Dispatch->testController;
if ($options['return'] != 'result') {
if (isset($this->controller->View)) {
$this->vars = $this->controller->View->viewVars;
$this->view = $this->controller->View->_viewNoLayout;
}
$this->contents = $this->controller->response->body();
}
$this->headers = $Dispatch->response->header();
return $this->{$options['return']};
}
/**
* Generates a mocked controller and mocks any classes passed to `$mocks`. By
* default, `_stop()` is stubbed as is sending the response headers, so to not
* interfere with testing.
*
* ### Mocks:
*
* - `methods` Methods to mock on the controller. `_stop()` is mocked by default
* - `models` Models to mock. Models are added to the ClassRegistry so they any
* time they are instatiated the mock will be created. Pass as key value pairs
* with the value being specific methods on the model to mock. If `true` or
* no value is passed, the entire model will be mocked.
* - `components` Components to mock. Components are only mocked on this controller
* and not within each other (i.e., components on components)
*
* @param string $controller Controller name
* @param array $mocks List of classes and methods to mock
* @return Controller Mocked controller
*/
public function generate($controller, $mocks = array()) {
list($plugin, $controller) = pluginSplit($controller);
if ($plugin) {
App::uses($plugin . 'AppController', $plugin . '.Controller');
$plugin .= '.';
}
App::uses($controller . 'Controller', $plugin . 'Controller');
if (!class_exists($controller.'Controller')) {
throw new MissingControllerException(array(
'class' => $controller . 'Controller',
'plugin' => substr($plugin, 0, -1)
));
}
ClassRegistry::flush();
$mocks = array_merge_recursive(array(
'methods' => array('_stop'),
'models' => array(),
'components' => array()
), (array)$mocks);
list($plugin, $name) = pluginSplit($controller);
$_controller = $this->getMock($name.'Controller', $mocks['methods'], array(), '', false);
$_controller->name = $name;
$request = $this->getMock('CakeRequest');
$response = $this->getMock('CakeResponse', array('_sendHeader'));
$_controller->__construct($request, $response);
$config = ClassRegistry::config('Model');
foreach ($mocks['models'] as $model => $methods) {
if (is_string($methods)) {
$model = $methods;
$methods = true;
}
if ($methods === true) {
$methods = array();
}
ClassRegistry::init($model);
list($plugin, $name) = pluginSplit($model);
$config = array_merge((array)$config, array('name' => $model));
$_model = $this->getMock($name, $methods, array($config));
ClassRegistry::removeObject($name);
ClassRegistry::addObject($name, $_model);
}
foreach ($mocks['components'] as $component => $methods) {
if (is_string($methods)) {
$component = $methods;
$methods = true;
}
if ($methods === true) {
$methods = array();
}
list($plugin, $name) = pluginSplit($component, true);
$componentClass = $name . 'Component';
App::uses($componentClass, $plugin . 'Controller/Component');
if (!class_exists($componentClass)) {
throw new MissingComponentException(array(
'class' => $componentClass
));
}
$_component = $this->getMock($componentClass, $methods, array(), '', false);
$_controller->Components->set($name, $_component);
}
$_controller->constructClasses();
$this->controller = $_controller;
return $this->controller;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/ControllerTestCase.php | PHP | gpl3 | 9,586 |
<?php
/**
* Missing Connection error page
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package Cake.TestSuite.templates
* @since CakePHP(tm) v 1.2.0.4433
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<?php include dirname(__FILE__) . DS . 'header.php'; ?>
<div id="content">
<h2>Missing Test Database Connection</h2>
<h3><?php echo $exception->getMessage(); ?></h3>
<pre><?php echo $exception->getTraceAsString(); ?></pre>
</div>
<?php include dirname(__FILE__) . DS . 'footer.php'; ?>
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/templates/missing_connection.php | PHP | gpl3 | 954 |
<?php
/**
* Xdebug error page
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package Cake.TestSuite.templates
* @since CakePHP(tm) v 1.2.0.4433
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<?php include dirname(__FILE__) . DS . 'header.php'; ?>
<div id="content">
<h2>Xdebug is not installed</h2>
<p>You must install Xdebug to use the CakePHP(tm) Code Coverage Analyzation.</p>
<p><a href="http://www.xdebug.org/docs/install" target="_blank">Learn How To Install Xdebug</a></p>
</div>
<?php include dirname(__FILE__) . DS . 'footer.php'; ?> | 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/templates/xdebug.php | PHP | gpl3 | 1,007 |
<?php
/**
* Short description for file.
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package Cake.TestSuite.templates
* @since CakePHP(tm) v 1.2.0.4433
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<div class="test-menu">
<ul>
<li>
<span style="font-size: 18px">App</span>
<ul>
<li><a href='<?php echo $cases;?>&app=true'>Tests</a></li>
</ul>
</li>
<?php
if (!empty($plugins)):
?>
<li style="padding-top: 10px">
<span style="font-size: 18px">Plugins</span>
<?php foreach($plugins as $plugin): ?>
<ul>
<li style="padding-top: 10px">
<span style="font-size: 18px"><?php echo $plugin;?></span>
<ul>
<li><a href='<?php echo $cases;?>&plugin=<?php echo $plugin; ?>'>Tests</a></li>
</ul>
</li>
</ul>
<?php endforeach; ?>
</li>
<?php endif;?>
<li style="padding-top: 10px">
<span style="font-size: 18px">Core</span>
<ul>
<li><a href='<?php echo $cases;?>'>Tests</a></li>
</ul>
</li>
</ul>
</div>
<div class="test-results"> | 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/templates/menu.php | PHP | gpl3 | 1,453 |
<?php
/**
* Missing PHPUnit
* error page.
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package Cake.TestSuite.templates
* @since CakePHP(tm) v 1.2.0.4433
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<?php include dirname(__FILE__) . DS . 'header.php'; ?>
<div id="content">
<h2>PHPUnit is not installed!</h2>
<p>You must install PHPUnit to use the CakePHP(tm) Test Suite.</p>
<p>PHPUnit can either be installed with pear, using the pear installer. Or the 'PHPUnit' directory from the distribution can be placed in one of your vendors directories.</p>
<ul>
<li><?php echo CAKE; ?>vendors </li>
<li><?php echo APP_DIR . DS; ?>vendors</li>
</ul>
<p>To install with the PEAR installer run the following commands:</p>
<ul>
<li>pear channel-discover pear.phpunit.de</li>
<li>pear channel-discover components.ez.no</li>
<li>pear channel-discover pear.symfony-project.com</li>
<li>pear install phpunit/PHPUnit</li>
</ul>
<p>For full instructions on how to <a href="http://www.phpunit.de/manual/current/en/installation.html">install PHPUnit, see the PHPUnit installation guide</a>.</p>
<p><a href="http://github.com/sebastianbergmann/phpunit" target="_blank">Download PHPUnit</a></p>
</div>
<?php include dirname(__FILE__) . DS . 'footer.php'; ?> | 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/templates/phpunit.php | PHP | gpl3 | 1,726 |
<?php
/**
* Short description for file.
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package Cake.TestSuite.templates
* @since CakePHP(tm) v 1.2.0.4433
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?> </div>
</div>
<div id="footer">
<p>
<!--PLEASE USE ONE OF THE POWERED BY CAKEPHP LOGO-->
<a href="http://www.cakephp.org/" target="_blank">
<img src="<?php echo $baseDir; ?>img/cake.power.gif" alt="CakePHP(tm) :: Rapid Development Framework" /></a>
</p>
</div>
<?php
App::uses('View', 'View');
$null = null;
$View = new View($null, false);
echo $View->element('sql_dump');
?>
</div>
</body>
</html> | 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/templates/footer.php | PHP | gpl3 | 1,104 |
<?php
/**
* Short description for file.
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package Cake.TestSuite.templates
* @since CakePHP(tm) v 1.2.0.4433
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CakePHP Test Suite 2.0</title>
<style type="text/css">
body h2 {color: #777;}
h3 {font-size: 170%; padding-top: 1em}
a {font-size: 120%}
li {line-height: 140%}
.test-menu {float:left; margin-right: 24px;}
.test-results {float:left; width: 67%;}
ul.tests {margin: 0; font-size:12px;}
ul.tests li {
list-style: none;
margin: 14px 0;
padding-left: 20px;
}
ul.tests li span {
font-size:14px;
text-transform: uppercase;
font-weight: bold;
}
ul.tests li.pass span, ul.tests li.skipped span { display:inline;}
ul.tests li.fail span { color: red; }
ul.tests li.pass span { color: green; }
ul.tests li.skipped span { color: navy; }
ul.tests li.error span { color : #d15d00; }
ul.tests li.pass,
ul.tests li.error,
ul.tests li.skipped,
ul.tests li.fail {
background: #fff2f2 url(<?php echo $baseDir; ?>img/test-fail-icon.png) 5px 5px no-repeat;
border-top: 1px dotted red;
border-bottom: 1px dotted red;
padding:5px 10px 2px 25px;
}
ul.tests li.pass {
background-color: #f2fff2;
background-image: url(<?php echo $baseDir; ?>img/test-pass-icon.png);
border-color:green;
}
ul.tests li.skipped {
background-color: #edf1ff;
background-image: url(<?php echo $baseDir; ?>img/test-skip-icon.png);
border-color:navy;
}
ul.tests li.error {
background-color: #ffffe5;
background-image: url(<?php echo $baseDir; ?>img/test-error-icon.png);
border-color: #DF6300;
}
ul.tests li div { margin: 5px 0 8px 0; }
ul.tests li div.msg { font-weight: bold; }
table caption { color:#fff; }
div.code-coverage-results div.code-line {
padding-left:5px;
display:block;
margin-left:10px;
}
.coverage-toggle {
float:right;
margin-top:10px;
font-size:12px;
}
.coverage-container {
margin-top:1em;
}
div.code-coverage-results div.uncovered span.content { background:#ecc; }
div.code-coverage-results div.covered span.content { background:#cec; }
div.code-coverage-results div.ignored span.content { color:#aaa; }
div.code-coverage-results div:hover {
background:#e8e8e8;
cursor: pointer;
}
div.code-coverage-results div.covered:hover span.content { background:#b4edb4;}
div.code-coverage-results div.uncovered:hover span.content { background:#edb4b4;}
div.code-coverage-results span.line-num {
color:#666;
display:block;
float:left;
width:20px;
text-align:right;
margin-right:5px;
}
div.code-coverage-results span.line-num strong { color:#666; }
div.code-coverage-results div.start {
border:1px solid #aaa;
border-width:1px 1px 0px 1px;
margin-top:30px;
padding-top:5px;
}
div.code-coverage-results div.end {
border:1px solid #aaa;
border-width:0px 1px 1px 1px;
margin-bottom:30px;
padding-bottom:5px;
}
div.code-coverage-results div.realstart { margin-top:0px; }
div.code-coverage-results p.note {
color:#bbb;
padding:5px;
margin:5px 0 10px;
font-size:10px;
}
div.code-coverage-results span.result-bad { color: #a00; }
div.code-coverage-results span.result-ok { color: #fa0; }
div.code-coverage-results span.result-good { color: #0a0; }
</style>
<link rel="stylesheet" type="text/css" href="<?php echo $baseDir; ?>css/cake.generic.css" />
</head>
<body>
<div id="container">
<div id="header">
<h1>CakePHP: the rapid development php framework</h1>
</div>
<div id="content">
<h2>CakePHP Test Suite 2.0</h2>
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/templates/header.php | PHP | gpl3 | 4,463 |
<?php
/**
* CakeTextReporter contains reporting features used for plain text based output
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('CakeBaseReporter', 'TestSuite/Reporter');
App::uses('TextCoverageReport', 'TestSuite/Coverage');
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
/**
* CakeTextReporter contains reporting features used for plain text based output
*
* @package Cake.TestSuite.Reporter
*/
class CakeTextReporter extends CakeBaseReporter {
/**
* Sets the text/plain header if the test is not a CLI test.
*
* @return void
*/
public function paintDocumentStart() {
if (!headers_sent()) {
header('Content-type: text/plain');
}
}
/**
* Paints a pass
*
* @return void
*/
public function paintPass() {
echo '.';
}
/**
* Paints a failing test.
*
* @param $message PHPUnit_Framework_AssertionFailedError $message Failure object displayed in
* the context of the other tests.
* @return void
*/
public function paintFail($message) {
$context = $message->getTrace();
$realContext = $context[3];
$context = $context[2];
printf(
"FAIL on line %s\n%s in\n%s %s()\n\n",
$context['line'], $message->toString(), $context['file'], $realContext['function']
);
}
/**
* Paints the end of the test with a summary of
* the passes and failures.
*
* @param PHPUnit_Framework_TestResult $result Result object
* @return void
*/
public function paintFooter($result) {
if ($result->failureCount() + $result->errorCount() == 0) {
echo "\nOK\n";
} else {
echo "FAILURES!!!\n";
}
echo "Test cases run: " . $result->count() .
"/" . ($result->count() - $result->skippedCount()) .
', Passes: ' . $this->numAssertions .
', Failures: ' . $result->failureCount() .
', Exceptions: ' . $result->errorCount() . "\n";
echo 'Time: ' . $result->time() . " seconds\n";
echo 'Peak memory: ' . number_format(memory_get_peak_usage()) . " bytes\n";
if (isset($this->params['codeCoverage']) && $this->params['codeCoverage']) {
$coverage = $result->getCodeCoverage()->getSummary();
echo $this->paintCoverage($coverage);
}
}
/**
* Paints the title only.
*
* @param string $test_name Name class of test.
* @return void
*/
public function paintHeader() {
$this->paintDocumentStart();
flush();
}
/**
* Paints a PHP exception.
*
* @param Exception $exception Exception to describe.
* @return void
*/
public function paintException($exception) {
$message = 'Unexpected exception of type [' . get_class($exception) .
'] with message ['. $exception->getMessage() .
'] in ['. $exception->getFile() .
' line ' . $exception->getLine() . ']';
echo $message . "\n\n";
}
/**
* Prints the message for skipping tests.
*
* @param string $message Text of skip condition.
* @return void
*/
public function paintSkip($message) {
printf("Skip: %s\n", $message->getMessage());
}
/**
* Paints formatted text such as dumped variables.
*
* @param string $message Text to show.
* @return void
*/
public function paintFormattedMessage($message) {
echo "$message\n";
flush();
}
/**
* Generate a test case list in plain text.
* Creates as series of url's for tests that can be run.
* One case per line.
*
* @return void
*/
public function testCaseList() {
$testCases = parent::testCaseList();
$app = $this->params['app'];
$plugin = $this->params['plugin'];
$buffer = "Core Test Cases:\n";
$urlExtra = '';
if ($app) {
$buffer = "App Test Cases:\n";
$urlExtra = '&app=true';
} elseif ($plugin) {
$buffer = Inflector::humanize($plugin) . " Test Cases:\n";
$urlExtra = '&plugin=' . $plugin;
}
if (1 > count($testCases)) {
$buffer .= "EMPTY";
echo $buffer;
}
foreach ($testCases as $testCaseFile => $testCase) {
$buffer .= $_SERVER['SERVER_NAME'] . $this->baseUrl() ."?case=" . $testCase . "&output=text"."\n";
}
$buffer .= "\n";
echo $buffer;
}
/**
* Generates a Text summary of the coverage data.
*
* @param array $coverage Array of coverage data.
* @return string
*/
public function paintCoverage($coverage) {
$reporter = new TextCoverageReport($coverage, $this);
echo $reporter->report();
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/Reporter/CakeTextReporter.php | PHP | gpl3 | 4,728 |
<?php
/**
* CakeBaseReporter contains common functionality to all cake test suite reporters.
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
require_once 'PHPUnit/TextUI/ResultPrinter.php';
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
/**
* CakeBaseReporter contains common reporting features used in the CakePHP Test suite
*
* @package Cake.TestSuite.Reporter
*/
class CakeBaseReporter extends PHPUnit_TextUI_ResultPrinter {
protected $_headerSent = false;
/**
* Array of request parameters. Usually parsed GET params.
*
* @var array
*/
public $params = array();
/**
* Character set for the output of test reporting.
*
* @var string
*/
protected $_characterSet;
/**
* The number of assertions done for a test suite
*/
protected $numAssertions = 0;
/**
* Does nothing yet. The first output will
* be sent on the first test start.
*
* ### Params
*
* - show_passes - Should passes be shown
* - plugin - Plugin test being run?
* - app - App test being run.
* - case - The case being run
* - codeCoverage - Whether the case/group being run is being code covered.
*
* @param string $charset The character set to output with. Defaults to UTF-8
* @param array $params Array of request parameters the reporter should use. See above.
*/
function __construct($charset = 'utf-8', $params = array()) {
if (!$charset) {
$charset = 'utf-8';
}
$this->_characterSet = $charset;
$this->params = $params;
}
/**
* Retrieves a list of test cases from the active Manager class,
* displaying it in the correct format for the reporter subclass
*
* @return mixed
*/
public function testCaseList() {
$testList = CakeTestLoader::generateTestList($this->params);
return $testList;
}
/**
* Paints the start of the response from the test suite.
* Used to paint things like head elements in an html page.
*
* @return void
*/
public function paintDocumentStart() {
}
/**
* Paints the end of the response from the test suite.
* Used to paint things like </body> in an html page.
*
* @return void
*/
public function paintDocumentEnd() {
}
/**
* Paint a list of test sets, core, app, and plugin test sets
* available.
*
* @return void
*/
public function paintTestMenu() {
}
/**
* Get the baseUrl if one is available.
*
* @return string The base url for the request.
*/
public function baseUrl() {
if (!empty($_SERVER['PHP_SELF'])) {
return $_SERVER['PHP_SELF'];
}
return '';
}
public function printResult(PHPUnit_Framework_TestResult $result) {
$this->paintFooter($result);
}
public function paintResult(PHPUnit_Framework_TestResult $result) {
$this->paintFooter($result);
}
/**
* An error occurred.
*
* @param PHPUnit_Framework_Test $test
* @param Exception $e
* @param float $time
*/
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) {
$this->paintException($e, $test);
}
/**
* A failure occurred.
*
* @param PHPUnit_Framework_Test $test
* @param PHPUnit_Framework_AssertionFailedError $e
* @param float $time
*/
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) {
$this->paintFail($e, $test);
}
/**
* Incomplete test.
*
* @param PHPUnit_Framework_Test $test
* @param Exception $e
* @param float $time
*/
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) {
$this->paintSkip($e, $test);
}
/**
* Skipped test.
*
* @param PHPUnit_Framework_Test $test
* @param Exception $e
* @param float $time
*/
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) {
$this->paintSkip($e, $test);
}
/**
* A test suite started.
*
* @param PHPUnit_Framework_TestSuite $suite
*/
public function startTestSuite(PHPUnit_Framework_TestSuite $suite) {
if (!$this->_headerSent) {
echo $this->paintHeader();
}
echo __d('cake_dev', 'Running %s', $suite->getName()) . "\n";
}
/**
* A test suite ended.
*
* @param PHPUnit_Framework_TestSuite $suite
*/
public function endTestSuite(PHPUnit_Framework_TestSuite $suite) {
}
/**
* A test started.
*
* @param PHPUnit_Framework_Test $test
*/
public function startTest(PHPUnit_Framework_Test $test) {
}
/**
* A test ended.
*
* @param PHPUnit_Framework_Test $test
* @param float $time
*/
public function endTest(PHPUnit_Framework_Test $test, $time) {
$this->numAssertions += $test->getNumAssertions();
$this->paintPass($test, $time);
}
} | 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/Reporter/CakeBaseReporter.php | PHP | gpl3 | 5,033 |
<?php
/**
* CakeHtmlReporter
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2.0.4433
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('CakeBaseReporter', 'TestSuite/Reporter');
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
/**
* CakeHtmlReporter Reports Results of TestSuites and Test Cases
* in an HTML format / context.
*
* @package Cake.TestSuite.Reporter
*/
class CakeHtmlReporter extends CakeBaseReporter {
/**
* Paints the top of the web page setting the
* title to the name of the starting test.
*
* @return void
*/
public function paintHeader() {
$this->_headerSent = true;
$this->sendNoCacheHeaders();
$this->paintDocumentStart();
$this->paintTestMenu();
echo "<ul class='tests'>\n";
}
/**
* Paints the document start content contained in header.php
*
* @return void
*/
public function paintDocumentStart() {
ob_start();
$baseDir = $this->params['baseDir'];
include CAKE . 'TestSuite' . DS . 'templates' . DS . 'header.php';
}
/**
* Paints the menu on the left side of the test suite interface.
* Contains all of the various plugin, core, and app buttons.
*
* @return void
*/
public function paintTestMenu() {
$cases = $this->baseUrl() . '?show=cases';
$plugins = App::objects('plugin', null, false);
sort($plugins);
include CAKE . 'TestSuite' . DS . 'templates' . DS . 'menu.php';
}
/**
* Retrieves and paints the list of tests cases in an HTML format.
*
* @return void
*/
public function testCaseList() {
$testCases = parent::testCaseList();
$app = $this->params['app'];
$plugin = $this->params['plugin'];
$buffer = "<h3>Core Test Cases:</h3>\n<ul>";
$urlExtra = null;
if ($app) {
$buffer = "<h3>App Test Cases:</h3>\n<ul>";
$urlExtra = '&app=true';
} elseif ($plugin) {
$buffer = "<h3>" . Inflector::humanize($plugin) . " Test Cases:</h3>\n<ul>";
$urlExtra = '&plugin=' . $plugin;
}
if (1 > count($testCases)) {
$buffer .= "<strong>EMPTY</strong>";
}
foreach ($testCases as $testCaseFile => $testCase) {
$title = explode(DS, str_replace('.test.php', '', $testCase));
$title[count($title) - 1] = Inflector::camelize($title[count($title) - 1]);
$title = implode(' / ', $title);
$buffer .= "<li><a href='" . $this->baseUrl() . "?case=" . urlencode($testCase) . $urlExtra ."'>" . $title . "</a></li>\n";
}
$buffer .= "</ul>\n";
echo $buffer;
}
/**
* Send the headers necessary to ensure the page is
* reloaded on every request. Otherwise you could be
* scratching your head over out of date test data.
*
* @return void
*/
public function sendNoCacheHeaders() {
if (!headers_sent()) {
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
}
}
/**
* Paints the end of the test with a summary of
* the passes and failures.
*
* @param PHPUnit_Framework_TestResult $result Result object
* @return void
*/
public function paintFooter($result) {
ob_end_flush();
$colour = ($result->failureCount() + $result->errorCount() > 0 ? "red" : "green");
echo "</ul>\n";
echo "<div style=\"";
echo "padding: 8px; margin: 1em 0; background-color: $colour; color: white;";
echo "\">";
echo ($result->count() - $result->skippedCount()) . "/" . $result->count();
echo " test methods complete:\n";
echo "<strong>" . count($result->passed()) . "</strong> passes, ";
echo "<strong>" . $result->failureCount() . "</strong> fails, ";
echo "<strong>" . $this->numAssertions . "</strong> assertions and ";
echo "<strong>" . $result->errorCount() . "</strong> exceptions.";
echo "</div>\n";
echo '<div style="padding:0 0 5px;">';
echo '<p><strong>Time:</strong> ' . $result->time() . ' seconds</p>';
echo '<p><strong>Peak memory:</strong> ' . number_format(memory_get_peak_usage()) . ' bytes</p>';
echo $this->_paintLinks();
echo '</div>';
if (isset($this->params['codeCoverage']) && $this->params['codeCoverage']) {
$coverage = $result->getCodeCoverage()->getSummary();
echo $this->paintCoverage($coverage);
}
$this->paintDocumentEnd();
}
/**
* Paints a code coverage report.
*
* @return void
*/
public function paintCoverage(array $coverage) {
App::uses('HtmlCoverageReport', 'TestSuite/Coverage');
$reporter = new HtmlCoverageReport($coverage, $this);
echo $reporter->report();
}
/**
* Renders the links that for accessing things in the test suite.
*
* @return void
*/
protected function _paintLinks() {
$show = $query = array();
if (!empty($this->params['case'])) {
$show['show'] = 'cases';
}
if (!empty($this->params['app'])) {
$show['app'] = $query['app'] = 'true';
}
if (!empty($this->params['plugin'])) {
$show['plugin'] = $query['plugin'] = $this->params['plugin'];
}
if (!empty($this->params['case'])) {
$query['case'] = $this->params['case'];
}
$show = $this->_queryString($show);
$query = $this->_queryString($query);
echo "<p><a href='" . $this->baseUrl() . $show . "'>Run more tests</a> | <a href='" . $this->baseUrl() . $query . "&show_passes=1'>Show Passes</a> | \n";
echo " <a href='" . $this->baseUrl() . $query . "&code_coverage=true'>Analyze Code Coverage</a></p>\n";
}
/**
* Convert an array of parameters into a query string url
*
* @param array $url Url hash to be converted
* @return string Converted url query string
*/
protected function _queryString($url) {
$out = '?';
$params = array();
foreach ($url as $key => $value) {
$params[] = "$key=$value";
}
$out .= implode('&', $params);
return $out;
}
/**
* Paints the end of the document html.
*
* @return void
*/
public function paintDocumentEnd() {
$baseDir = $this->params['baseDir'];
include CAKE . 'TestSuite' . DS . 'templates' . DS . 'footer.php';
if (ob_get_length()) {
ob_end_flush();
}
}
/**
* Paints the test failure with a breadcrumbs
* trail of the nesting test suites below the
* top level test.
*
* @param PHPUnit_Framework_AssertionFailedError $message Failure object displayed in
* the context of the other tests.
* @return void
*/
public function paintFail($message, $test) {
$trace = $this->_getStackTrace($message);
$testName = get_class($test) . '(' . $test->getName() . ')';
echo "<li class='fail'>\n";
echo "<span>Failed</span>";
echo "<div class='msg'><pre>" . $this->_htmlEntities($message->toString()) . "</pre></div>\n";
echo "<div class='msg'>" . __d('cake_dev', 'Test case: %s', $testName) . "</div>\n";
echo "<div class='msg'>" . __d('cake_dev', 'Stack trace:') . '<br />' . $trace . "</div>\n";
echo "</li>\n";
}
/**
* Paints the test pass with a breadcrumbs
* trail of the nesting test suites below the
* top level test.
*
* @param PHPUnit_Framework_Test test method that just passed
* @param float $time time spent to run the test method
* @return void
*/
public function paintPass(PHPUnit_Framework_Test $test, $time = null) {
if (isset($this->params['showPasses']) && $this->params['showPasses']) {
echo "<li class='pass'>\n";
echo "<span>Passed</span> ";
echo "<br />" . $this->_htmlEntities($test->getName()) . " ($time seconds)\n";
echo "</li>\n";
}
}
/**
* Paints a PHP exception.
*
* @param Exception $exception Exception to display.
* @return void
*/
public function paintException($message, $test) {
$trace = $this->_getStackTrace($message);
$testName = get_class($test) . '(' . $test->getName() . ')';
echo "<li class='fail'>\n";
echo "<span>" . get_class($message) . "</span>";
echo "<div class='msg'>" . $this->_htmlEntities($message->getMessage()) . "</div>\n";
echo "<div class='msg'>" . __d('cake_dev', 'Test case: %s', $testName) . "</div>\n";
echo "<div class='msg'>" . __d('cake_dev', 'Stack trace:') . '<br />' . $trace . "</div>\n";
echo "</li>\n";
}
/**
* Prints the message for skipping tests.
*
* @param string $message Text of skip condition.
* @param PHPUnit_Framework_TestCase $test the test method skipped
* @return void
*/
public function paintSkip($message, $test) {
echo "<li class='skipped'>\n";
echo "<span>Skipped</span> ";
echo $test->getName() . ': ' . $this->_htmlEntities($message->getMessage());
echo "</li>\n";
}
/**
* Paints formatted text such as dumped variables.
*
* @param string $message Text to show.
* @return void
*/
public function paintFormattedMessage($message) {
echo '<pre>' . $this->_htmlEntities($message) . '</pre>';
}
/**
* Character set adjusted entity conversion.
*
* @param string $message Plain text or Unicode message.
* @return string Browser readable message.
*/
protected function _htmlEntities($message) {
return htmlentities($message, ENT_COMPAT, $this->_characterSet);
}
/**
* Gets a formatted stack trace.
*
* @param Exception $e Exception to get a stack trace for.
* @return string Generated stack trace.
*/
protected function _getStackTrace(Exception $e) {
$trace = $e->getTrace();
$out = array();
foreach ($trace as $frame) {
if (isset($frame['file']) && isset($frame['line'])) {
$out[] = $frame['file'] . ' : ' . $frame['line'];
} elseif (isset($frame['class']) && isset($frame['function'])) {
$out[] = $frame['class'] . '::' . $frame['function'];
} else {
$out[] = '[internal]';
}
}
return implode('<br />', $out);
}
/**
* A test suite started.
*
* @param PHPUnit_Framework_TestSuite $suite
*/
public function startTestSuite(PHPUnit_Framework_TestSuite $suite) {
if (!$this->_headerSent) {
echo $this->paintHeader();
}
echo '<h2>' . __d('cake_dev', 'Running %s', $suite->getName()) . '</h2>';
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/Reporter/CakeHtmlReporter.php | PHP | gpl3 | 10,272 |
<?php
/**
* TestLoader for CakePHP Test suite.
*
* Turns partial paths used on the testsuite console and web UI into full file paths.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @package Cake.TestSuite
*/
class CakeTestLoader extends PHPUnit_Runner_StandardTestSuiteLoader {
/**
* Load a file and find the first test case / suite in that file.
*
* @param string $filePath
* @param string $params
* @return ReflectionClass
*/
public function load($filePath, $params = '') {
$file = $this->_resolveTestFile($filePath, $params);
return parent::load('', $file);
}
/**
* Convert path fragments used by Cake's test runner to absolute paths that can be fed to PHPUnit.
*
* @return void
*/
protected function _resolveTestFile($filePath, $params) {
$basePath = $this->_basePath($params) . DS . $filePath;
$ending = 'Test.php';
return (strpos($basePath, $ending) === (strlen($basePath) - strlen($ending))) ? $basePath : $basePath . $ending;
}
/**
* Generates the base path to a set of tests based on the parameters.
*
* @param array $params
* @return string The base path.
*/
protected static function _basePath($params) {
$result = null;
if (!empty($params['core'])) {
$result = CORE_TEST_CASES;
} elseif (!empty($params['app'])) {
$result = APP_TEST_CASES;
} else if (!empty($params['plugin'])) {
if (!CakePlugin::loaded($params['plugin'])) {
try {
CakePlugin::load($params['plugin']);
$result = CakePlugin::path($params['plugin']) . 'Test' . DS . 'Case';
} catch (MissingPluginException $e) {}
} else {
$result = CakePlugin::path($params['plugin']) . 'Test' . DS . 'Case';
}
}
return $result;
}
/**
* Get the list of files for the test listing.
*
* @return void
*/
public static function generateTestList($params) {
$directory = self::_basePath($params);
$fileList = self::_getRecursiveFileList($directory);
$testCases = array();
foreach ($fileList as $testCaseFile) {
$case = str_replace($directory . DS, '', $testCaseFile);
$case = str_replace('Test.php', '', $case);
$testCases[$testCaseFile] = $case;
}
sort($testCases);
return $testCases;
}
/**
* Gets a recursive list of files from a given directory and matches then against
* a given fileTestFunction, like isTestCaseFile()
*
* @param string $directory The directory to scan for files.
* @param mixed $fileTestFunction
*/
protected static function _getRecursiveFileList($directory = '.') {
$fileList = array();
if (!is_dir($directory)) {
return $fileList;
}
$files = new RegexIterator(
new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)),
'/.*Test.php$/'
);
foreach ($files as $file) {
$fileList[] = $file->getPathname();
}
return $fileList;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/CakeTestLoader.php | PHP | gpl3 | 3,281 |
<?php
/**
* TestRunner for CakePHP Test suite.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
require_once 'PHPUnit/TextUI/TestRunner.php';
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
/**
* A custom test runner for Cake's use of PHPUnit.
*
* @package Cake.TestSuite
*/
class CakeTestRunner extends PHPUnit_TextUI_TestRunner {
/**
* Lets us pass in some options needed for cake's webrunner.
*
* @return void
*/
public function __construct($loader, $params) {
parent::__construct($loader);
$this->_params = $params;
}
/**
* Actually run a suite of tests. Cake initializes fixtures here using the chosen fixture manager
*
* @param PHPUnit_Framework_Test $suite
* @param array $arguments
* @return void
*/
public function doRun(PHPUnit_Framework_Test $suite, array $arguments = array()) {
if (isset($arguments['printer'])) {
self::$versionStringPrinted = true;
}
$fixture = $this->_getFixtureManager($arguments);
foreach ($suite->getIterator() as $test) {
if ($test instanceof CakeTestCase) {
$fixture->fixturize($test);
$test->fixtureManager = $fixture;
}
}
$return = parent::doRun($suite, $arguments);
$fixture->shutdown();
return $return;
}
/**
* Create the test result and splice on our code coverage reports.
*
* @return PHPUnit_Framework_TestResult
*/
protected function createTestResult() {
$result = new PHPUnit_Framework_TestResult;
if (isset($this->_params['codeCoverage'])) {
$result->collectCodeCoverageInformation(true);
}
return $result;
}
/**
* Get the fixture manager class specified or use the default one.
*
* @return instance of a fixture manager.
*/
protected function _getFixtureManager($arguments) {
if (isset($arguments['fixtureManager'])) {
App::uses($arguments['fixtureManager'], 'TestSuite');
if (class_exists($arguments['fixtureManager'])) {
return new $arguments['fixtureManager'];
}
throw new RuntimeException(__d('cake_dev', 'Could not find fixture manager %s.', $arguments['fixtureManager']));
}
App::uses('AppFixtureManager', 'TestSuite');
if (class_exists('AppFixtureManager')) {
return new AppFixtureManager();
}
return new CakeFixtureManager();
}
} | 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/CakeTestRunner.php | PHP | gpl3 | 2,748 |
<?php
/**
* Short description for file.
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package Cake.TestSuite.Fixture
* @since CakePHP(tm) v 1.2.0.4667
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
App::uses('CakeSchema', 'Model');
/**
* Short description for class.
*
* @package Cake.TestSuite.Fixture
*/
class CakeTestFixture {
/**
* Name of the object
*
* @var string
*/
public $name = null;
/**
* Cake's DBO driver (e.g: DboMysql).
*
*/
public $db = null;
/**
* Full Table Name
*
*/
public $table = null;
/**
* Instantiate the fixture.
*
*/
public function __construct() {
if ($this->name === null) {
if (preg_match('/^(.*)Fixture$/', get_class($this), $matches)) {
$this->name = $matches[1];
} else {
$this->name = get_class($this);
}
}
$this->Schema = new CakeSchema(array('name' => 'TestSuite', 'connection' => 'test'));
$this->init();
}
/**
* Initialize the fixture.
*
*/
public function init() {
if (isset($this->import) && (is_string($this->import) || is_array($this->import))) {
$import = array_merge(
array('connection' => 'default', 'records' => false),
is_array($this->import) ? $this->import : array('model' => $this->import)
);
if (isset($import['model'])) {
list($plugin, $modelClass) = pluginSplit($import['model'], true);
App::uses($modelClass, $plugin . 'Model');
if (!class_exists($modelClass)) {
throw new MissingModelException(array('class' => $modelClass));
}
$model = new $modelClass(null, null, $import['connection']);
$db = $model->getDataSource();
if (empty($model->tablePrefix)) {
$model->tablePrefix = $db->config['prefix'];
}
$this->fields = $model->schema(true);
$this->fields[$model->primaryKey]['key'] = 'primary';
$this->table = $db->fullTableName($model, false);
ClassRegistry::config(array('ds' => 'test'));
ClassRegistry::flush();
} elseif (isset($import['table'])) {
$model = new Model(null, $import['table'], $import['connection']);
$db = ConnectionManager::getDataSource($import['connection']);
$db->cacheSources = false;
$model->useDbConfig = $import['connection'];
$model->name = Inflector::camelize(Inflector::singularize($import['table']));
$model->table = $import['table'];
$model->tablePrefix = $db->config['prefix'];
$this->fields = $model->schema(true);
ClassRegistry::flush();
}
if (!empty($db->config['prefix']) && strpos($this->table, $db->config['prefix']) === 0) {
$this->table = str_replace($db->config['prefix'], '', $this->table);
}
if (isset($import['records']) && $import['records'] !== false && isset($model) && isset($db)) {
$this->records = array();
$query = array(
'fields' => $db->fields($model, null, array_keys($this->fields)),
'table' => $db->fullTableName($model),
'alias' => $model->alias,
'conditions' => array(),
'order' => null,
'limit' => null,
'group' => null
);
$records = $db->fetchAll($db->buildStatement($query, $model), false, $model->alias);
if ($records !== false && !empty($records)) {
$this->records = Set::extract($records, '{n}.' . $model->alias);
}
}
}
if (!isset($this->table)) {
$this->table = Inflector::underscore(Inflector::pluralize($this->name));
}
if (!isset($this->primaryKey) && isset($this->fields['id'])) {
$this->primaryKey = 'id';
}
}
/**
* Run before all tests execute, should return SQL statement to create table for this fixture could be executed successfully.
*
* @param object $db An instance of the database object used to create the fixture table
* @return boolean True on success, false on failure
*/
public function create($db) {
if (!isset($this->fields) || empty($this->fields)) {
return false;
}
if (empty($this->fields['tableParameters']['engine'])) {
$canUseMemory = true;
foreach($this->fields as $field => $args) {
if (is_string($args)) {
$type = $args;
} elseif (!empty($args['type'])) {
$type = $args['type'];
} else {
continue;
}
if (in_array($type, array('blob', 'text', 'binary'))) {
$canUseMemory = false;
break;
}
}
if ($canUseMemory) {
$this->fields['tableParameters']['engine'] = 'MEMORY';
}
}
$this->Schema->build(array($this->table => $this->fields));
try {
$db->execute($db->createSchema($this->Schema), array('log' => false));
} catch (Exception $e) {
return false;
}
return true;
}
/**
* Run after all tests executed, should return SQL statement to drop table for this fixture.
*
* @param object $db An instance of the database object used to create the fixture table
* @return boolean True on success, false on failure
*/
public function drop($db) {
if (empty($this->fields)) {
return false;
}
$this->Schema->build(array($this->table => $this->fields));
try {
$db->execute($db->dropSchema($this->Schema), array('log' => false));
} catch (Exception $e) {
return false;
}
return true;
}
/**
* Run before each tests is executed, should return a set of SQL statements to insert records for the table
* of this fixture could be executed successfully.
*
* @param object $db An instance of the database into which the records will be inserted
* @return boolean on success or if there are no records to insert, or false on failure
*/
public function insert($db) {
if (!isset($this->_insert)) {
$values = array();
if (isset($this->records) && !empty($this->records)) {
$fields = array();
foreach($this->records as $record) {
$fields = array_merge($fields, array_keys(array_intersect_key($record, $this->fields)));
}
$fields = array_unique($fields);
$default = array_fill_keys($fields, null);
foreach ($this->records as $record) {
$fields = array_keys($record);
$values[] = array_values(array_merge($default, $record));
}
return $db->insertMulti($this->table, $fields, $values);
}
return true;
}
}
/**
* Truncates the current fixture. Can be overwritten by classes extending CakeFixture to trigger other events before / after
* truncate.
*
* @param object $db A reference to a db instance
* @return boolean
*/
public function truncate($db) {
$fullDebug = $db->fullDebug;
$db->fullDebug = false;
$return = $db->truncate($this->table);
$db->fullDebug = $fullDebug;
return $return;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/Fixture/CakeTestFixture.php | PHP | gpl3 | 6,970 |
<?php
/**
* Short description for file.
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package Cake.TestSuite.Fixture
* @since CakePHP(tm) v 1.2.0.4667
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Model', 'Model');
/**
* Short description for class.
*
* @package Cake.TestSuite.Fixture
*/
class CakeTestModel extends Model {
public $useDbConfig = 'test';
public $cacheSources = false;
}
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/Fixture/CakeTestModel.php | PHP | gpl3 | 873 |
<?php
/**
* A factory class to manage the life cycle of test fixtures
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.TestSuite.Fixture
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
App::uses('ConnectionManager', 'Model');
App::uses('ClassRegistry', 'Utility');
class CakeFixtureManager {
/**
* Was this class already initialized?
*
* @var boolean
*/
protected $_initialized = false;
/**
* Default datasource to use
*
* @var DataSource
*/
protected $_db = null;
/**
* Holds the fixture classes that where instantiated
*
* @var array
*/
protected $_loaded = array();
/**
* Holds the fixture classes that where ins tantiated indexed by class name
*
* @var array
*/
protected $_fixtureMap = array();
/**
* Inspects the test to look for unloaded fixtures and loads them
*
* @param CakeTestCase $test the test case to inspect
* @return void
*/
public function fixturize($test) {
if (empty($test->fixtures) || !empty($this->_processed[get_class($test)])) {
$test->db = $this->_db;
return;
}
$this->_initDb();
$test->db = $this->_db;
if (!is_array($test->fixtures)) {
$test->fixtures = array_map('trim', explode(',', $test->fixtures));
}
if (isset($test->fixtures)) {
$this->_loadFixtures($test->fixtures);
}
$this->_processed[get_class($test)] = true;
}
/**
* Initializes this class with a DataSource object to use as default for all fixtures
*
* @return void
*/
protected function _initDb() {
if ($this->_initialized) {
return;
}
$db = ConnectionManager::getDataSource('test');
$db->cacheSources = false;
$this->_db = $db;
ClassRegistry::config(array('ds' => 'test'));
$this->_initialized = true;
}
/**
* Looks for fixture files and instantiates the classes accordingly
*
* @param array $fixtures the fixture names to load using the notation {type}.{name}
* @return void
*/
protected function _loadFixtures($fixtures) {
foreach ($fixtures as $index => $fixture) {
$fixtureFile = null;
$fixtureIndex = $fixture;
if (isset($this->_loaded[$fixture])) {
continue;
}
if (strpos($fixture, 'core.') === 0) {
$fixture = substr($fixture, strlen('core.'));
$fixturePaths[] = CAKE . 'Test' . DS . 'Fixture';
} elseif (strpos($fixture, 'app.') === 0) {
$fixture = substr($fixture, strlen('app.'));
$fixturePaths = array(
TESTS . 'Fixture'
);
} elseif (strpos($fixture, 'plugin.') === 0) {
$parts = explode('.', $fixture, 3);
$pluginName = $parts[1];
$fixture = $parts[2];
$fixturePaths = array(
CakePlugin::path(Inflector::camelize($pluginName)) . 'Test' . DS . 'Fixture',
TESTS . 'Fixture'
);
} else {
$fixturePaths = array(
TESTS . 'Fixture',
CAKE . 'Test' . DS . 'Fixture'
);
}
foreach ($fixturePaths as $path) {
$className = Inflector::camelize($fixture);
if (is_readable($path . DS . $className . 'Fixture.php')) {
$fixtureFile = $path . DS . $className . 'Fixture.php';
require_once($fixtureFile);
$fixtureClass = $className . 'Fixture';
$this->_loaded[$fixtureIndex] = new $fixtureClass($this->_db);
$this->_fixtureMap[$fixtureClass] = $this->_loaded[$fixtureIndex];
break;
}
}
}
}
/**
* Runs the drop and create commands on the fixtures if necessary.
*
* @param CakeTestFixture $fixture the fixture object to create
* @param DataSource $db the datasource instance to use
* @param boolean $drop whether drop the fixture if it is already created or not
* @return void
*/
protected function _setupTable($fixture, $db = null, $drop = true) {
if (!$db) {
$db = $this->_db;
}
if (!empty($fixture->created) && $fixture->created == $db->configKeyName) {
return;
}
$sources = $db->listSources();
$table = $db->config['prefix'] . $fixture->table;
if ($drop && in_array($table, $sources)) {
$fixture->drop($db);
$fixture->create($db);
$fixture->created = $db->configKeyName;
} elseif (!in_array($table, $sources)) {
$fixture->create($db);
$fixture->created = $db->configKeyName;
}
}
/**
* Crates the fixtures tables and inserts data on them
*
* @param CakeTestCase $test the test to inspect for fixture loading
* @return void
*/
public function load(CakeTestCase $test) {
if (empty($test->fixtures)) {
return;
}
$fixtures = $test->fixtures;
if (empty($fixtures) || $test->autoFixtures == false) {
return;
}
$test->db->begin();
foreach ($fixtures as $f) {
if (!empty($this->_loaded[$f])) {
$fixture = $this->_loaded[$f];
$this->_setupTable($fixture, $test->db, $test->dropTables);
$fixture->insert($test->db);
}
}
$test->db->commit();
}
/**
* Trucantes the fixtures tables
*
* @param CakeTestCase $test the test to inspect for fixture unloading
* @return void
*/
public function unload(CakeTestCase $test) {
$fixtures = !empty($test->fixtures) ? $test->fixtures : array();
foreach (array_reverse($fixtures) as $f) {
if (isset($this->_loaded[$f])) {
$fixture = $this->_loaded[$f];
if (!empty($fixture->created)) {
$fixture->truncate($test->db);
}
}
}
}
/**
* Trucantes the fixtures tables
*
* @param CakeTestCase $test the test to inspect for fixture unloading
* @return void
* @throws UnexpectedValueException if $name is not a previously loaded class
*/
public function loadSingle($name, $db = null) {
$name .= 'Fixture';
if (isset($this->_fixtureMap[$name])) {
if (!$db) {
$db = $this->_db;
}
$fixture = $this->_fixtureMap[$name];
$this->_setupTable($fixture, $db);
$fixture->truncate($db);
$fixture->insert($db);
} else {
throw new UnexpectedValueException(__d('cake_dev', 'Referenced fixture class %s not found', $name));
}
}
/**
* Drop all fixture tables loaded by this class
*
* @return void
*/
public function shutDown() {
foreach ($this->_loaded as $fixture) {
if (!empty($fixture->created)) {
$fixture->drop($this->_db);
}
}
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/Fixture/CakeFixtureManager.php | PHP | gpl3 | 6,536 |
<?php
/**
* Generates code coverage reports in HTML from data obtained from PHPUnit
*
* PHP5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.TestSuite.Coverage
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
App::uses('BaseCoverageReport', 'TestSuite/Coverage');
class HtmlCoverageReport extends BaseCoverageReport {
/**
* Generates report html to display.
*
* @return string compiled html report.
*/
public function report() {
$pathFilter = $this->getPathFilter();
$coverageData = $this->filterCoverageDataByPath($pathFilter);
if (empty($coverageData)) {
return '<h3>No files to generate coverage for</h3>';
}
$output = $this->coverageScript();
$output .= <<<HTML
<h3>Code coverage results
<a href="#" onclick="coverage_toggle_all()" class="coverage-toggle">Toggle all files</a>
</h3>
HTML;
foreach ($coverageData as $file => $coverageData) {
$fileData = file($file);
$output .= $this->generateDiff($file, $fileData, $coverageData);
}
return $output;
}
/**
* Generates an HTML diff for $file based on $coverageData.
*
* @param string $filename Name of the file having coverage generated
* @param array $fileLines File data as an array. See file() for how to get one of these.
* @param array $coverageData Array of coverage data to use to generate HTML diffs with
* @return string HTML diff.
*/
public function generateDiff($filename, $fileLines, $coverageData) {
$output = '';
$diff = array();
list($covered, $total) = $this->_calculateCoveredLines($fileLines, $coverageData);
//shift line numbers forward one;
array_unshift($fileLines, ' ');
unset($fileLines[0]);
foreach ($fileLines as $lineno => $line) {
$class = 'ignored';
$coveringTests = array();
if (isset($coverageData[$lineno]) && is_array($coverageData[$lineno])) {
$coveringTests = array();
foreach ($coverageData[$lineno] as $test) {
$testReflection = new ReflectionClass(current(explode('::', $test['id'])));
$this->_testNames[] = $this->_guessSubjectName($testReflection);
$coveringTests[] = $test['id'];
}
$class = 'covered';
} elseif (isset($coverageData[$lineno]) && $coverageData[$lineno] === -1) {
$class = 'uncovered';
} elseif (isset($coverageData[$lineno]) && $coverageData[$lineno] === -2) {
$class .= ' dead';
}
$diff[] = $this->_paintLine($line, $lineno, $class, $coveringTests);
}
$percentCovered = 100;
if ($total > 0) {
$percentCovered = round(100 * $covered / $total, 2);
}
$output .= $this->coverageHeader($filename, $percentCovered);
$output .= implode("", $diff);
$output .= $this->coverageFooter();
return $output;
}
/**
* Guess the classname the test was for based on the test case filename.
*
* @param ReflectionClass $testReflection.
* @return string Possible test subject name.
*/
protected function _guessSubjectName($testReflection) {
$basename = basename($testReflection->getFilename());
if (strpos($basename, '.test') !== false) {
list($subject, ) = explode('.', $basename, 2);
return $subject;
}
$subject = str_replace('Test.php', '', $basename);
return $subject;
}
/**
* Renders the html for a single line in the html diff.
*
* @return void
*/
protected function _paintLine($line, $linenumber, $class, $coveringTests) {
$coveredBy = '';
if (!empty($coveringTests)) {
$coveredBy = "Covered by:\n";
foreach ($coveringTests as $test) {
$coveredBy .= $test . "\n";
}
}
return sprintf(
'<div class="code-line %s" title="%s"><span class="line-num">%s</span><span class="content">%s</span></div>',
$class,
$coveredBy,
$linenumber,
htmlspecialchars($line)
);
}
/**
* generate some javascript for the coverage report.
*
* @return void
*/
public function coverageScript() {
return <<<HTML
<script type="text/javascript">
function coverage_show_hide(selector) {
var element = document.getElementById(selector);
element.style.display = (element.style.display == 'none') ? '' : 'none';
}
function coverage_toggle_all () {
var divs = document.querySelectorAll('div.coverage-container');
var i = divs.length;
while (i--) {
if (divs[i] && divs[i].className.indexOf('primary') == -1) {
divs[i].style.display = (divs[i].style.display == 'none') ? '' : 'none';
}
}
}
</script>
HTML;
}
/**
* Generate an HTML snippet for coverage headers
*
* @return void
*/
public function coverageHeader($filename, $percent) {
$filename = basename($filename);
list($file, $ext) = explode('.', $filename);
$display = in_array($file, $this->_testNames) ? 'block' : 'none';
$primary = $display == 'block' ? 'primary' : '';
return <<<HTML
<div class="coverage-container $primary" style="display:$display;">
<h4>
<a href="#coverage-$filename" onclick="coverage_show_hide('coverage-$filename');">
$filename Code coverage: $percent%
</a>
</h4>
<div class="code-coverage-results" id="coverage-$filename" style="display:none;">
<pre>
HTML;
}
/**
* Generate an HTML snippet for coverage footers
*
* @return void
*/
public function coverageFooter() {
return "</pre></div></div>";
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/Coverage/HtmlCoverageReport.php | PHP | gpl3 | 5,692 |
<?php
/**
* Generates code coverage reports in Simple plain text from data obtained from PHPUnit
*
* PHP5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.TestSuite.Coverage
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('BaseCoverageReport', 'TestSuite/Coverage');
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
class TextCoverageReport extends BaseCoverageReport {
/**
* Generates report text to display.
*
* @return string compiled plain text report.
*/
public function report() {
$pathFilter = $this->getPathFilter();
$coverageData = $this->filterCoverageDataByPath($pathFilter);
if (empty($coverageData)) {
return 'No files to generate coverage for';
}
$output = "\nCoverage Report:\n\n";
foreach ($coverageData as $file => $coverageData) {
$fileData = file($file);
$output .= $this->generateDiff($file, $fileData, $coverageData);
}
return $output;
}
/**
* Generates a 'diff' report for a file.
* Since diffs are too big for plain text reports a simple file => % covered is done.
*
* @param string $filename Name of the file having coverage generated
* @param array $fileLines File data as an array. See file() for how to get one of these.
* @param array $coverageData Array of coverage data to use to generate HTML diffs with
* @return string
*/
public function generateDiff($filename, $fileLines, $coverageData) {
list($covered, $total) = $this->_calculateCoveredLines($fileLines, $coverageData);
$percentCovered = round(100 * $covered / $total, 2);
return "$filename : $percentCovered%\n";
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/Coverage/TextCoverageReport.php | PHP | gpl3 | 2,066 |
<?php
/**
* Abstract class for common CoverageReport methods.
* Provides several template methods for custom output.
*
* PHP5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.TestSuite.Coverage
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
abstract class BaseCoverageReport {
/**
* coverage data
*
* @var string
*/
protected $_rawCoverage;
/**
* is the test an app test
*
* @var string
*/
public $appTest = false;
/**
* is the test a plugin test
*
* @var string
*/
public $pluginTest = false;
/**
* Array of test case file names. Used to do basename() matching with
* files that have coverage to decide which results to show on page load.
*
* @var array
*/
protected $_testNames = array();
/**
* Constructor
*
* @param array $coverage Array of coverage data from PHPUnit_Test_Result
* @param CakeBaseReporter $reporter A reporter to use for the coverage report.
* @return void
*/
public function __construct($coverage, CakeBaseReporter $reporter) {
$this->_rawCoverage = $coverage;
$this->setParams($reporter);
}
/**
* Pulls params out of the reporter.
*
* @param CakeBaseReporter $reporter Reporter to suck params out of.
* @return void
*/
protected function setParams(CakeBaseReporter $reporter) {
if ($reporter->params['app']) {
$this->appTest = true;
}
if ($reporter->params['plugin']) {
$this->pluginTest = Inflector::camelize($reporter->params['plugin']);
}
}
/**
* Set the coverage data array
*
* @param array $coverage Coverage data to use.
* @return void
*/
public function setCoverage($coverage) {
$this->_rawCoverage = $coverage;
}
/**
* Gets the base path that the files we are interested in live in.
*
* @return void
*/
public function getPathFilter() {
$path = ROOT . DS;
if ($this->appTest) {
$path .= APP_DIR . DS;
} elseif ($this->pluginTest) {
$path = App::pluginPath($this->pluginTest);
} else {
$path = CAKE;
}
return $path;
}
/**
* Filters the coverage data by path. Files not in the provided path will be removed.
*
* @param string $path Path to filter files by.
* @return array Array of coverage data for files that match the given path.
*/
public function filterCoverageDataByPath($path) {
$files = array();
foreach ($this->_rawCoverage as $fileName => $fileCoverage) {
if (strpos($fileName, $path) !== 0) {
continue;
}
$files[$fileName] = $fileCoverage;
}
return $files;
}
/**
* Calculates how many lines are covered and what the total number of executable lines is
*
* @param array $fileLines
* @param array $coverageData
* @return array. Array of covered, total lines.
*/
protected function _calculateCoveredLines($fileLines, $coverageData) {
$covered = $total = 0;
//shift line numbers forward one
array_unshift($fileLines, ' ');
unset($fileLines[0]);
foreach ($fileLines as $lineno => $line) {
if (!isset($coverageData[$lineno])) {
continue;
}
if (is_array($coverageData[$lineno])) {
$covered++;
$total++;
} else if ($coverageData[$lineno] === -1) {
$total++;
}
}
return array($covered, $total);
}
/**
* Generates report to display.
*
* @return string compiled html report.
*/
abstract public function report();
/**
* Generates an coverage 'diff' for $file based on $coverageData.
*
* @param string $filename Name of the file having coverage generated
* @param array $fileLines File data as an array. See file() for how to get one of these.
* @param array $coverageData Array of coverage data to use to generate HTML diffs with
* @return string prepared report for a single file.
*/
abstract public function generateDiff($filename, $fileLines, $coverageData);
}
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/Coverage/BaseCoverageReport.php | PHP | gpl3 | 4,245 |
<?php
/**
* A class to contain test cases and run them with shered fixtures
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.TestSuite
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
App::uses('Folder', 'Utility');
class CakeTestSuite extends PHPUnit_Framework_TestSuite {
/**
* Adds all the files in a directory to the test suite. Does not recurse through directories.
*
* @param string $directory The directory to add tests from.
* @return void
*/
public function addTestDirectory($directory = '.') {
$folder = new Folder($directory);
list($dirs, $files) = $folder->read(true, true, true);
foreach ($files as $file) {
$this->addTestFile($file);
}
}
/**
* Recursively adds all the files in a directory to the test suite.
*
* @param string $directory The directory subtree to add tests from.
* @return void
*/
public function addTestDirectoryRecursive($directory = '.') {
$folder = new Folder($directory);
$files = $folder->tree(null, false, 'files');
foreach ($files as $file) {
$this->addTestFile($file);
}
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/CakeTestSuite.php | PHP | gpl3 | 1,614 |
<?php
/**
* TestRunner for CakePHP Test suite.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.TestSuite
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
require_once 'PHPUnit/TextUI/Command.php';
App::uses('CakeTestRunner', 'TestSuite');
App::uses('CakeTestLoader', 'TestSuite');
App::uses('CakeTestSuite', 'TestSuite');
App::uses('CakeTestCase', 'TestSuite');
App::uses('ControllerTestCase', 'TestSuite');
App::uses('CakeTestModel', 'TestSuite/Fixture');
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
/**
* Class to customize loading of test suites from CLI
*
* @package Cake.TestSuite
*/
class CakeTestSuiteCommand extends PHPUnit_TextUI_Command {
/**
* Construct method
*
* @param array $params list of options to be used for this run
*/
public function __construct($loader, $params = array()) {
if ($loader && !class_exists($loader)) {
throw new MissingTestLoaderException(array('class' => $loader));
}
$this->arguments['loader'] = $loader;
$this->arguments['test'] = $params['case'];
$this->arguments['testFile'] = $params;
$this->_params = $params;
$this->longOptions['fixture='] = 'handleFixture';
$this->longOptions['output='] = 'handleReporter';
}
/**
* Ugly hack to get around PHPUnit having a hard coded classname for the Runner. :(
*
* @param array $argv
* @param boolean $exit
*/
public function run(array $argv, $exit = true) {
$this->handleArguments($argv);
$runner = $this->getRunner($this->arguments['loader']);
if (is_object($this->arguments['test']) &&
$this->arguments['test'] instanceof PHPUnit_Framework_Test) {
$suite = $this->arguments['test'];
} else {
$suite = $runner->getTest(
$this->arguments['test'],
$this->arguments['testFile'],
$this->arguments['syntaxCheck']
);
}
if (count($suite) == 0) {
$skeleton = new PHPUnit_Util_Skeleton_Test(
$suite->getName(),
$this->arguments['testFile']
);
$result = $skeleton->generate(true);
if (!$result['incomplete']) {
eval(str_replace(array('<?php', '?>'), '', $result['code']));
$suite = new PHPUnit_Framework_TestSuite(
$this->arguments['test'] . 'Test'
);
}
}
if ($this->arguments['listGroups']) {
PHPUnit_TextUI_TestRunner::printVersionString();
print "Available test group(s):\n";
$groups = $suite->getGroups();
sort($groups);
foreach ($groups as $group) {
print " - $group\n";
}
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
}
unset($this->arguments['test']);
unset($this->arguments['testFile']);
try {
$result = $runner->doRun($suite, $this->arguments);
}
catch (PHPUnit_Framework_Exception $e) {
print $e->getMessage() . "\n";
}
if ($exit) {
if (isset($result) && $result->wasSuccessful()) {
exit(PHPUnit_TextUI_TestRunner::SUCCESS_EXIT);
}
else if (!isset($result) || $result->errorCount() > 0) {
exit(PHPUnit_TextUI_TestRunner::EXCEPTION_EXIT);
}
else {
exit(PHPUnit_TextUI_TestRunner::FAILURE_EXIT);
}
}
}
/**
* Create a runner for the command.
*
* @param $loader The loader to be used for the test run.
* @return CakeTestRunner
*/
public function getRunner($loader) {
return new CakeTestRunner($loader, $this->_params);
}
/**
* Handler for customizing the FixtureManager class/
*
* @param string $class Name of the class that will be the fixture manager
* @return void
*/
public function handleFixture($class) {
$this->arguments['fixtureManager'] = $class;
}
/**
* Handles output flag used to change printing on webrunner.
*
* @return void
*/
public function handleReporter($reporter) {
$object = null;
$type = strtolower($reporter);
$reporter = ucwords($reporter);
$coreClass = 'Cake' . $reporter . 'Reporter';
App::uses($coreClass, 'TestSuite/Reporter');
$appClass = $reporter . 'Reporter';
App::uses($appClass, 'TestSuite/Reporter');
if (!class_exists($appClass)) {
$object = new $coreClass(null, $this->_params);
} else {
$object = new $appClass(null, $this->_params);
}
return $this->arguments['printer'] = $object;
}
} | 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/CakeTestSuiteCommand.php | PHP | gpl3 | 4,621 |
<?php
/**
* CakeTestCase file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package Cake.TestSuite
* @since CakePHP(tm) v 1.2.0.4667
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
PHP_CodeCoverage_Filter::getInstance()->addFileToBlacklist(__FILE__, 'DEFAULT');
App::uses('CakeFixtureManager', 'TestSuite/Fixture');
App::uses('CakeTestFixture', 'TestSuite/Fixture');
/**
* CakeTestCase class
*
* @package Cake.TestSuite
*/
abstract class CakeTestCase extends PHPUnit_Framework_TestCase {
/**
* The class responsible for managing the creation, loading and removing of fixtures
*
* @var CakeFixtureManager
*/
public $fixtureManager = null;
/**
* By default, all fixtures attached to this class will be truncated and reloaded after each test.
* Set this to false to handle manually
*
* @var array
*/
public $autoFixtures = true;
/**
* Set this to false to avoid tables to be dropped if they already exist
*
* @var boolean
*/
public $dropTables = true;
/**
* Configure values to restore at end of test.
*
* @var array
*/
protected $_configure = array();
/**
* Path settings to restore at the end of the test.
*
* @var array
*/
protected $_pathRestore = array();
/**
* Runs the test case and collects the results in a TestResult object.
* If no TestResult object is passed a new one will be created.
* This method is run for each test method in this class
*
* @param PHPUnit_Framework_TestResult $result
* @return PHPUnit_Framework_TestResult
* @throws InvalidArgumentException
*/
public function run(PHPUnit_Framework_TestResult $result = NULL) {
if (!empty($this->fixtureManager)) {
$this->fixtureManager->load($this);
}
$result = parent::run($result);
if (!empty($this->fixtureManager)) {
$this->fixtureManager->unload($this);
}
return $result;
}
/**
* Called when a test case method is about to start (to be overriden when needed.)
*
* @param string $method Test method about to get executed.
* @return void
*/
public function startTest($method) {
}
/**
* Called when a test case method has been executed (to be overriden when needed.)
*
* @param string $method Test method about that was executed.
* @return void
*/
public function endTest($method) {
}
/**
* Overrides SimpleTestCase::skipIf to provide a boolean return value
*
* @param boolean $shouldSkip
* @param string $message
* @return boolean
*/
public function skipIf($shouldSkip, $message = '') {
if ($shouldSkip) {
$this->markTestSkipped($message);
}
return $shouldSkip;
}
/**
* Setup the test case, backup the static object values so they can be restored.
* Specifically backs up the contents of Configure and paths in App if they have
* not already been backed up.
*
* @return void
*/
public function setUp() {
parent::setUp();
if (empty($this->_configure)) {
$this->_configure = Configure::read();
}
if (empty($this->_pathRestore)) {
$this->_pathRestore = App::paths();
}
if (class_exists('Router', false)) {
Router::reload();
}
}
/**
* teardown any static object changes and restore them.
*
* @return void
*/
public function tearDown() {
parent::tearDown();
App::build($this->_pathRestore, App::RESET);
if (class_exists('ClassRegistry', false)) {
ClassRegistry::flush();
}
Configure::write($this->_configure);
}
/**
* Announces the start of a test.
*
* @param string $method Test method just started.
* @return void
*/
protected function assertPreConditions() {
parent::assertPreConditions();
$this->startTest($this->getName());
}
/**
* Announces the end of a test.
*
* @param string $method Test method just finished.
* @return void
*/
protected function assertPostConditions() {
parent::assertPostConditions();
$this->endTest($this->getName());
}
/**
* Chooses which fixtures to load for a given test
*
* @param string $fixture Each parameter is a model name that corresponds to a
* fixture, i.e. 'Post', 'Author', etc.
* @return void
* @see CakeTestCase::$autoFixtures
*/
public function loadFixtures() {
if (empty($this->fixtureManager)) {
throw new Exception(__d('cake_dev', 'No fixture manager to load the test fixture'));
}
$args = func_get_args();
foreach ($args as $class) {
$this->fixtureManager->loadSingle($class);
}
}
/**
* Takes an array $expected and generates a regex from it to match the provided $string.
* Samples for $expected:
*
* Checks for an input tag with a name attribute (contains any non-empty value) and an id
* attribute that contains 'my-input':
* array('input' => array('name', 'id' => 'my-input'))
*
* Checks for two p elements with some text in them:
* array(
* array('p' => true),
* 'textA',
* '/p',
* array('p' => true),
* 'textB',
* '/p'
* )
*
* You can also specify a pattern expression as part of the attribute values, or the tag
* being defined, if you prepend the value with preg: and enclose it with slashes, like so:
* array(
* array('input' => array('name', 'id' => 'preg:/FieldName\d+/')),
* 'preg:/My\s+field/'
* )
*
* Important: This function is very forgiving about whitespace and also accepts any
* permutation of attribute order. It will also allow whitespaces between specified tags.
*
* @param string $string An HTML/XHTML/XML string
* @param array $expected An array, see above
* @param string $message SimpleTest failure output string
* @return boolean
*/
public function assertTags($string, $expected, $fullDebug = false) {
$regex = array();
$normalized = array();
foreach ((array) $expected as $key => $val) {
if (!is_numeric($key)) {
$normalized[] = array($key => $val);
} else {
$normalized[] = $val;
}
}
$i = 0;
foreach ($normalized as $tags) {
if (!is_array($tags)) {
$tags = (string)$tags;
}
$i++;
if (is_string($tags) && $tags{0} == '<') {
$tags = array(substr($tags, 1) => array());
} elseif (is_string($tags)) {
$tagsTrimmed = preg_replace('/\s+/m', '', $tags);
if (preg_match('/^\*?\//', $tags, $match) && $tagsTrimmed !== '//') {
$prefix = array(null, null);
if ($match[0] == '*/') {
$prefix = array('Anything, ', '.*?');
}
$regex[] = array(
sprintf('%sClose %s tag', $prefix[0], substr($tags, strlen($match[0]))),
sprintf('%s<[\s]*\/[\s]*%s[\s]*>[\n\r]*', $prefix[1], substr($tags, strlen($match[0]))),
$i,
);
continue;
}
if (!empty($tags) && preg_match('/^preg\:\/(.+)\/$/i', $tags, $matches)) {
$tags = $matches[1];
$type = 'Regex matches';
} else {
$tags = preg_quote($tags, '/');
$type = 'Text equals';
}
$regex[] = array(
sprintf('%s "%s"', $type, $tags),
$tags,
$i,
);
continue;
}
foreach ($tags as $tag => $attributes) {
$regex[] = array(
sprintf('Open %s tag', $tag),
sprintf('[\s]*<%s', preg_quote($tag, '/')),
$i,
);
if ($attributes === true) {
$attributes = array();
}
$attrs = array();
$explanations = array();
$i = 1;
foreach ($attributes as $attr => $val) {
if (is_numeric($attr) && preg_match('/^preg\:\/(.+)\/$/i', $val, $matches)) {
$attrs[] = $matches[1];
$explanations[] = sprintf('Regex "%s" matches', $matches[1]);
continue;
} else {
$quotes = '["\']';
if (is_numeric($attr)) {
$attr = $val;
$val = '.+?';
$explanations[] = sprintf('Attribute "%s" present', $attr);
} elseif (!empty($val) && preg_match('/^preg\:\/(.+)\/$/i', $val, $matches)) {
$quotes = '["\']?';
$val = $matches[1];
$explanations[] = sprintf('Attribute "%s" matches "%s"', $attr, $val);
} else {
$explanations[] = sprintf('Attribute "%s" == "%s"', $attr, $val);
$val = preg_quote($val, '/');
}
$attrs[] = '[\s]+' . preg_quote($attr, '/') . '=' . $quotes . $val . $quotes;
}
$i++;
}
if ($attrs) {
$permutations = $this->_array_permute($attrs);
$permutationTokens = array();
foreach ($permutations as $permutation) {
$permutationTokens[] = implode('', $permutation);
}
$regex[] = array(
sprintf('%s', implode(', ', $explanations)),
$permutationTokens,
$i,
);
}
$regex[] = array(
sprintf('End %s tag', $tag),
'[\s]*\/?[\s]*>[\n\r]*',
$i,
);
}
}
foreach ($regex as $i => $assertation) {
list($description, $expressions, $itemNum) = $assertation;
$matches = false;
foreach ((array)$expressions as $expression) {
if (preg_match(sprintf('/^%s/s', $expression), $string, $match)) {
$matches = true;
$string = substr($string, strlen($match[0]));
break;
}
}
if (!$matches) {
$this->assertTrue(false, sprintf('Item #%d / regex #%d failed: %s', $itemNum, $i, $description));
if ($fullDebug) {
debug($string, true);
debug($regex, true);
}
return false;
}
}
$this->assertTrue(true, '%s');
return true;
}
/**
* Generates all permutation of an array $items and returns them in a new array.
*
* @param array $items An array of items
* @return array
*/
protected function _array_permute($items, $perms = array()) {
static $permuted;
if (empty($perms)) {
$permuted = array();
}
if (empty($items)) {
$permuted[] = $perms;
} else {
$numItems = count($items) - 1;
for ($i = $numItems; $i >= 0; --$i) {
$newItems = $items;
$newPerms = $perms;
list($tmp) = array_splice($newItems, $i, 1);
array_unshift($newPerms, $tmp);
$this->_array_permute($newItems, $newPerms);
}
return $permuted;
}
}
/**
* Compatibility wrapper function for assertEquals
*
* @param mixed $result
* @param mixed $expected
* @param string $message the text to display if the assertion is not correct
* @return void
*/
protected function assertEqual($result, $expected, $message = '') {
return $this->assertEquals($expected, $result, $message);
}
/**
* Compatibility wrapper function for assertNotEquals
*
* @param mixed $result
* @param mixed $expected
* @param string $message the text to display if the assertion is not correct
* @return void
*/
protected function assertNotEqual($result, $expected, $message = '') {
return $this->assertNotEquals($expected, $result, $message);
}
/**
* Compatibility wrapper function for assertRegexp
*
* @param mixed $pattern a regular expression
* @param string $string the text to be matched
* @param string $message the text to display if the assertion is not correct
* @return void
*/
protected function assertPattern($pattern, $string, $message = '') {
return $this->assertRegExp($pattern, $string, $message);
}
/**
* Compatibility wrapper function for assertEquals
*
* @param mixed $actual
* @param mixed $expected
* @param string $message the text to display if the assertion is not correct
* @return void
*/
protected function assertIdentical($actual, $expected, $message = '') {
return $this->assertSame($expected, $actual, $message);
}
/**
* Compatibility wrapper function for assertNotEquals
*
* @param mixed $actual
* @param mixed $expected
* @param string $message the text to display if the assertion is not correct
* @return void
*/
protected function assertNotIdentical($actual, $expected, $message = '') {
return $this->assertNotSame($expected, $actual, $message);
}
/**
* Compatibility wrapper function for assertNotRegExp
*
* @param mixed $pattern a regular expression
* @param string $string the text to be matched
* @param string $message the text to display if the assertion is not correct
* @return void
*/
protected function assertNoPattern($pattern, $string, $message = '') {
return $this->assertNotRegExp($pattern, $string, $message);
}
protected function assertNoErrors() {
}
/**
* Compatibility wrapper function for setExpectedException
*
* @param mixed $expected the name of the Exception or error
* @param string $message the text to display if the assertion is not correct
* @return void
*/
protected function expectError($expected = false, $message = '') {
if (!$expected) {
$expected = 'Exception';
}
$this->setExpectedException($expected, $message);
}
/**
* Compatibility wrapper function for setExpectedException
*
* @param mixed $expected the name of the Exception
* @param string $message the text to display if the assertion is not correct
* @return void
*/
protected function expectException($name = 'Exception', $message = '') {
$this->setExpectedException($name, $message);
}
/**
* Compatibility wrapper function for assertSame
*
* @param mixed $first
* @param mixed $second
* @param string $message the text to display if the assertion is not correct
* @return void
*/
protected function assertReference(&$first, &$second, $message = '') {
return $this->assertSame($first, $second, $message);
}
/**
* Compatibility wrapper for assertIsA
*
* @param string $object
* @param string $type
* @param string $message
* @return void
*/
protected function assertIsA($object, $type, $message = '') {
return $this->assertInstanceOf($type, $object, $message);
}
/**
* Compatibility function to test if value is between an acceptable range
*
* @param mixed $result
* @param mixed $expected
* @param mixed $margin the rage of acceptation
* @param string $message the text to display if the assertion is not correct
* @return void
*/
protected function assertWithinMargin($result, $expected, $margin, $message = '') {
$upper = $result + $margin;
$lower = $result - $margin;
$this->assertTrue((($expected <= $upper) && ($expected >= $lower)), $message);
}
/**
* Compatibility function for skipping.
*
* @param boolean $condition Condition to trigger skipping
* @param string $message Message for skip
* @return boolean
*/
protected function skipUnless($condition, $message = '') {
if (!$condition) {
$this->markTestSkipped($message);
}
return $condition;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/TestSuite/CakeTestCase.php | PHP | gpl3 | 14,491 |
<?php
/**
* Cake Socket connection class.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Network
* @since CakePHP(tm) v 1.2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Validation', 'Utility');
/**
* Cake network socket connection class.
*
* Core base class for network communication.
*
* @package Cake.Network
*/
class CakeSocket {
/**
* Object description
*
* @var string
*/
public $description = 'Remote DataSource Network Socket Interface';
/**
* Base configuration settings for the socket connection
*
* @var array
*/
protected $_baseConfig = array(
'persistent' => false,
'host' => 'localhost',
'protocol' => 'tcp',
'port' => 80,
'timeout' => 30
);
/**
* Configuration settings for the socket connection
*
* @var array
*/
public $config = array();
/**
* Reference to socket connection resource
*
* @var resource
*/
public $connection = null;
/**
* This boolean contains the current state of the CakeSocket class
*
* @var boolean
*/
public $connected = false;
/**
* This variable contains an array with the last error number (num) and string (str)
*
* @var array
*/
public $lastError = array();
/**
* Constructor.
*
* @param array $config Socket configuration, which will be merged with the base configuration
* @see CakeSocket::$_baseConfig
*/
public function __construct($config = array()) {
$this->config = array_merge($this->_baseConfig, $config);
if (!is_numeric($this->config['protocol'])) {
$this->config['protocol'] = getprotobyname($this->config['protocol']);
}
}
/**
* Connect the socket to the given host and port.
*
* @return boolean Success
* @throws SocketException
*/
public function connect() {
if ($this->connection != null) {
$this->disconnect();
}
$scheme = null;
if (isset($this->config['request']) && $this->config['request']['uri']['scheme'] == 'https') {
$scheme = 'ssl://';
}
if ($this->config['persistent'] == true) {
$this->connection = @pfsockopen($scheme.$this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
} else {
$this->connection = @fsockopen($scheme.$this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
}
if (!empty($errNum) || !empty($errStr)) {
$this->setLastError($errNum, $errStr);
throw new SocketException($errStr, $errNum);
}
$this->connected = is_resource($this->connection);
if ($this->connected) {
stream_set_timeout($this->connection, $this->config['timeout']);
}
return $this->connected;
}
/**
* Get the host name of the current connection.
*
* @return string Host name
*/
public function host() {
if (Validation::ip($this->config['host'])) {
return gethostbyaddr($this->config['host']);
}
return gethostbyaddr($this->address());
}
/**
* Get the IP address of the current connection.
*
* @return string IP address
*/
public function address() {
if (Validation::ip($this->config['host'])) {
return $this->config['host'];
}
return gethostbyname($this->config['host']);
}
/**
* Get all IP addresses associated with the current connection.
*
* @return array IP addresses
*/
public function addresses() {
if (Validation::ip($this->config['host'])) {
return array($this->config['host']);
}
return gethostbynamel($this->config['host']);
}
/**
* Get the last error as a string.
*
* @return string Last error
*/
public function lastError() {
if (!empty($this->lastError)) {
return $this->lastError['num'] . ': ' . $this->lastError['str'];
}
return null;
}
/**
* Set the last error.
*
* @param integer $errNum Error code
* @param string $errStr Error string
* @return void
*/
public function setLastError($errNum, $errStr) {
$this->lastError = array('num' => $errNum, 'str' => $errStr);
}
/**
* Write data to the socket.
*
* @param string $data The data to write to the socket
* @return boolean Success
*/
public function write($data) {
if (!$this->connected) {
if (!$this->connect()) {
return false;
}
}
$totalBytes = strlen($data);
for ($written = 0, $rv = 0; $written < $totalBytes; $written += $rv) {
$rv = fwrite($this->connection, substr($data, $written));
if ($rv === false || $rv === 0) {
return $written;
}
}
return $written;
}
/**
* Read data from the socket. Returns false if no data is available or no connection could be
* established.
*
* @param integer $length Optional buffer length to read; defaults to 1024
* @return mixed Socket data
*/
public function read($length = 1024) {
if (!$this->connected) {
if (!$this->connect()) {
return false;
}
}
if (!feof($this->connection)) {
$buffer = fread($this->connection, $length);
$info = stream_get_meta_data($this->connection);
if ($info['timed_out']) {
$this->setLastError(E_WARNING, __d('cake_dev', 'Connection timed out'));
return false;
}
return $buffer;
}
return false;
}
/**
* Disconnect the socket from the current connection.
*
* @return boolean Success
*/
public function disconnect() {
if (!is_resource($this->connection)) {
$this->connected = false;
return true;
}
$this->connected = !fclose($this->connection);
if (!$this->connected) {
$this->connection = null;
}
return !$this->connected;
}
/**
* Destructor, used to disconnect from current connection.
*
*/
public function __destruct() {
$this->disconnect();
}
/**
* Resets the state of this Socket instance to it's initial state (before Object::__construct got executed)
*
* @param array $state Array with key and values to reset
* @return boolean True on success
*/
public function reset($state = null) {
if (empty($state)) {
static $initalState = array();
if (empty($initalState)) {
$initalState = get_class_vars(__CLASS__);
}
$state = $initalState;
}
foreach ($state as $property => $value) {
$this->{$property} = $value;
}
return true;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Network/CakeSocket.php | PHP | gpl3 | 6,445 |
<?php
/**
* CakeRequest
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Set', 'Utility');
/**
* A class that helps wrap Request information and particulars about a single request.
* Provides methods commonly used to introspect on the request headers and request body.
*
* Has both an Array and Object interface. You can access framework parameters using indexes:
*
* `$request['controller']` or `$request->controller`.
*
* @package Cake.Network
*/
class CakeRequest implements ArrayAccess {
/**
* Array of parameters parsed from the url.
*
* @var array
*/
public $params = array();
/**
* Array of POST data. Will contain form data as well as uploaded files.
* Inputs prefixed with 'data' will have the data prefix removed. If there is
* overlap between an input prefixed with data and one without, the 'data' prefixed
* value will take precedence.
*
* @var array
*/
public $data = array();
/**
* Array of querystring arguments
*
* @var array
*/
public $query = array();
/**
* The url string used for the request.
*
* @var string
*/
public $url;
/**
* Base url path.
*
* @var string
*/
public $base = false;
/**
* webroot path segment for the request.
*
* @var string
*/
public $webroot = '/';
/**
* The full address to the current request
*
* @var string
*/
public $here = null;
/**
* The built in detectors used with `is()` can be modified with `addDetector()`.
*
* There are several ways to specify a detector, see CakeRequest::addDetector() for the
* various formats and ways to define detectors.
*
* @var array
*/
protected $_detectors = array(
'get' => array('env' => 'REQUEST_METHOD', 'value' => 'GET'),
'post' => array('env' => 'REQUEST_METHOD', 'value' => 'POST'),
'put' => array('env' => 'REQUEST_METHOD', 'value' => 'PUT'),
'delete' => array('env' => 'REQUEST_METHOD', 'value' => 'DELETE'),
'head' => array('env' => 'REQUEST_METHOD', 'value' => 'HEAD'),
'options' => array('env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'),
'ssl' => array('env' => 'HTTPS', 'value' => 1),
'ajax' => array('env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'),
'flash' => array('env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'),
'mobile' => array('env' => 'HTTP_USER_AGENT', 'options' => array(
'Android', 'AvantGo', 'BlackBerry', 'DoCoMo', 'Fennec', 'iPod', 'iPhone',
'J2ME', 'MIDP', 'NetFront', 'Nokia', 'Opera Mini', 'PalmOS', 'PalmSource',
'portalmmm', 'Plucker', 'ReqwirelessWeb', 'SonyEricsson', 'Symbian', 'UP\\.Browser',
'webOS', 'Windows CE', 'Xiino'
))
);
/**
* Copy of php://input. Since this stream can only be read once in most SAPI's
* keep a copy of it so users don't need to know about that detail.
*
* @var string
*/
protected $_input = '';
/**
* Constructor
*
* @param string $url Trimmed url string to use. Should not contain the application base path.
* @param boolean $parseEnvironment Set to false to not auto parse the environment. ie. GET, POST and FILES.
*/
public function __construct($url = null, $parseEnvironment = true) {
$this->_base();
if (empty($url)) {
$url = $this->_url();
}
if ($url[0] == '/') {
$url = substr($url, 1);
}
$this->url = $url;
if ($parseEnvironment) {
$this->_processPost();
$this->_processGet();
$this->_processFiles();
}
$this->here = $this->base . '/' . $this->url;
}
/**
* process the post data and set what is there into the object.
* processed data is available at $this->data
*
* @return void
*/
protected function _processPost() {
$this->data = $_POST;
if (ini_get('magic_quotes_gpc') === '1') {
$this->data = stripslashes_deep($this->data);
}
if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
$this->data['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
}
if (isset($this->data['_method'])) {
if (!empty($_SERVER)) {
$_SERVER['REQUEST_METHOD'] = $this->data['_method'];
} else {
$_ENV['REQUEST_METHOD'] = $this->data['_method'];
}
unset($this->data['_method']);
}
if (isset($this->data['data'])) {
$data = $this->data['data'];
unset($this->data['data']);
$this->data = Set::merge($this->data, $data);
}
}
/**
* Process the GET parameters and move things into the object.
*
* @return void
*/
protected function _processGet() {
if (ini_get('magic_quotes_gpc') === '1') {
$query = stripslashes_deep($_GET);
} else {
$query = $_GET;
}
unset($query['/' . $this->url]);
if (strpos($this->url, '?') !== false) {
list(, $querystr) = explode('?', $this->url);
parse_str($querystr, $queryArgs);
$query += $queryArgs;
}
if (isset($this->params['url'])) {
$query = array_merge($this->params['url'], $query);
}
$this->query = $query;
}
/**
* Get the request uri. Looks in PATH_INFO first, as this is the exact value we need prepared
* by PHP. Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order.
* Each of these server variables have the base path, and query strings stripped off
*
* @return string URI The CakePHP request path that is being accessed.
*/
protected function _url() {
if (!empty($_SERVER['PATH_INFO'])) {
return $_SERVER['PATH_INFO'];
} elseif (isset($_SERVER['REQUEST_URI'])) {
$uri = $_SERVER['REQUEST_URI'];
} elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['SCRIPT_NAME'])) {
$uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
} elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
$uri = $_SERVER['HTTP_X_REWRITE_URL'];
} elseif ($var = env('argv')) {
$uri = $var[0];
}
$base = $this->base;
if (strlen($base) > 0 && strpos($uri, $base) === 0) {
$uri = substr($uri, strlen($base));
}
if (strpos($uri, '?') !== false) {
$uri = parse_url($uri, PHP_URL_PATH);
}
if (empty($uri) || $uri == '/' || $uri == '//') {
return '/';
}
return $uri;
}
/**
* Returns a base URL and sets the proper webroot
*
* @return string Base URL
*/
protected function _base() {
$dir = $webroot = null;
$config = Configure::read('App');
extract($config);
if (!isset($base)) {
$base = $this->base;
}
if ($base !== false) {
$this->webroot = $base . '/';
return $this->base = $base;
}
if (!$baseUrl) {
$base = dirname(env('SCRIPT_NAME'));
if ($webroot === 'webroot' && $webroot === basename($base)) {
$base = dirname($base);
}
if ($dir === 'app' && $dir === basename($base)) {
$base = dirname($base);
}
if ($base === DS || $base === '.') {
$base = '';
}
$this->webroot = $base .'/';
return $this->base = $base;
}
$file = '/' . basename($baseUrl);
$base = dirname($baseUrl);
if ($base === DS || $base === '.') {
$base = '';
}
$this->webroot = $base . '/';
$docRoot = env('DOCUMENT_ROOT');
$docRootContainsWebroot = strpos($docRoot, $dir . '/' . $webroot);
if (!empty($base) || !$docRootContainsWebroot) {
if (strpos($this->webroot, $dir) === false) {
$this->webroot .= $dir . '/' ;
}
if (strpos($this->webroot, $webroot) === false) {
$this->webroot .= $webroot . '/';
}
}
return $this->base = $base . $file;
}
/**
* Process $_FILES and move things into the object.
*
* @return void
*/
protected function _processFiles() {
if (isset($_FILES) && is_array($_FILES)) {
foreach ($_FILES as $name => $data) {
if ($name != 'data') {
$this->params['form'][$name] = $data;
}
}
}
if (isset($_FILES['data'])) {
foreach ($_FILES['data'] as $key => $data) {
foreach ($data as $model => $fields) {
if (is_array($fields)) {
foreach ($fields as $field => $value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$this->data[$model][$field][$k][$key] = $v;
}
} else {
$this->data[$model][$field][$key] = $value;
}
}
} else {
$this->data[$model][$key] = $fields;
}
}
}
}
}
/**
* Get the IP the client is using, or says they are using.
*
* @param boolean $safe Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP
* header. Setting $safe = false will will also look at HTTP_X_FORWARDED_FOR
* @return string The client IP.
*/
public function clientIp($safe = true) {
if (!$safe && env('HTTP_X_FORWARDED_FOR') != null) {
$ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
} else {
if (env('HTTP_CLIENT_IP') != null) {
$ipaddr = env('HTTP_CLIENT_IP');
} else {
$ipaddr = env('REMOTE_ADDR');
}
}
if (env('HTTP_CLIENTADDRESS') != null) {
$tmpipaddr = env('HTTP_CLIENTADDRESS');
if (!empty($tmpipaddr)) {
$ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
}
}
return trim($ipaddr);
}
/**
* Returns the referer that referred this request.
*
* @param boolean $local Attempt to return a local address. Local addresses do not contain hostnames.
* @return string The referring address for this request.
*/
public function referer($local = false) {
$ref = env('HTTP_REFERER');
$forwarded = env('HTTP_X_FORWARDED_HOST');
if ($forwarded) {
$ref = $forwarded;
}
$base = '';
if (defined('FULL_BASE_URL')) {
$base = FULL_BASE_URL . $this->webroot;
}
if (!empty($ref) && !empty($base)) {
if ($local && strpos($ref, $base) === 0) {
$ref = substr($ref, strlen($base));
if ($ref[0] != '/') {
$ref = '/' . $ref;
}
return $ref;
} elseif (!$local) {
return $ref;
}
}
return '/';
}
/**
* Missing method handler, handles wrapping older style isAjax() type methods
*
* @param string $name The method called
* @param array $params Array of parameters for the method call
* @return mixed
* @throws CakeException when an invalid method is called.
*/
public function __call($name, $params) {
if (strpos($name, 'is') === 0) {
$type = strtolower(substr($name, 2));
return $this->is($type);
}
throw new CakeException(__d('cake_dev', 'Method %s does not exist', $name));
}
/**
* Magic get method allows access to parsed routing parameters directly on the object.
*
* Allows access to `$this->params['controller']` via `$this->controller`
*
* @param string $name The property being accessed.
* @return mixed Either the value of the parameter or null.
*/
public function __get($name) {
if (isset($this->params[$name])) {
return $this->params[$name];
}
return null;
}
/**
* Check whether or not a Request is a certain type. Uses the built in detection rules
* as well as additional rules defined with CakeRequest::addDetector(). Any detector can be called
* as `is($type)` or `is$Type()`.
*
* @param string $type The type of request you want to check.
* @return boolean Whether or not the request is the type you are checking.
*/
public function is($type) {
$type = strtolower($type);
if (!isset($this->_detectors[$type])) {
return false;
}
$detect = $this->_detectors[$type];
if (isset($detect['env'])) {
if (isset($detect['value'])) {
return env($detect['env']) == $detect['value'];
}
if (isset($detect['pattern'])) {
return (bool)preg_match($detect['pattern'], env($detect['env']));
}
if (isset($detect['options'])) {
$pattern = '/' . implode('|', $detect['options']) . '/i';
return (bool)preg_match($pattern, env($detect['env']));
}
}
if (isset($detect['callback']) && is_callable($detect['callback'])) {
return call_user_func($detect['callback'], $this);
}
return false;
}
/**
* Add a new detector to the list of detectors that a request can use.
* There are several different formats and types of detectors that can be set.
*
* ### Environment value comparison
*
* An environment value comparison, compares a value fetched from `env()` to a known value
* the environment value is equality checked against the provided value.
*
* e.g `addDetector('post', array('env' => 'REQUEST_METHOD', 'value' => 'POST'))`
*
* ### Pattern value comparison
*
* Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
*
* e.g `addDetector('iphone', array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i'));`
*
* ### Option based comparison
*
* Option based comparisons use a list of options to create a regular expression. Subsequent calls
* to add an already defined options detector will merge the options.
*
* e.g `addDetector('mobile', array('env' => 'HTTP_USER_AGENT', 'options' => array('Fennec')));`
*
* ### Callback detectors
*
* Callback detectors allow you to provide a 'callback' type to handle the check. The callback will
* recieve the request object as its only parameter.
*
* e.g `addDetector('custom', array('callback' => array('SomeClass', 'somemethod')));`
*
* @param string $name The name of the detector.
* @param array $options The options for the detector definition. See above.
* @return void
*/
public function addDetector($name, $options) {
if (isset($this->_detectors[$name]) && isset($options['options'])) {
$options = Set::merge($this->_detectors[$name], $options);
}
$this->_detectors[$name] = $options;
}
/**
* Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
* This modifies the parameters available through `$request->params`.
*
* @param array $params Array of parameters to merge in
* @return The current object, you can chain this method.
*/
public function addParams($params) {
$this->params = array_merge($this->params, (array)$params);
return $this;
}
/**
* Add paths to the requests' paths vars. This will overwrite any existing paths.
* Provides an easy way to modify, here, webroot and base.
*
* @param array $paths Array of paths to merge in
* @return CakeRequest the current object, you can chain this method.
*/
public function addPaths($paths) {
foreach (array('webroot', 'here', 'base') as $element) {
if (isset($paths[$element])) {
$this->{$element} = $paths[$element];
}
}
return $this;
}
/**
* Get the value of the current requests url. Will include named parameters and querystring arguments.
*
* @param boolean $base Include the base path, set to false to trim the base path off.
* @return string the current request url including query string args.
*/
public function here($base = true) {
$url = $this->here;
if (!empty($this->query)) {
$url .= '?' . http_build_query($this->query);
}
if (!$base) {
$url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
}
return $url;
}
/**
* Read an HTTP header from the Request information.
*
* @param string $name Name of the header you want.
* @return mixed Either false on no header being set or the value of the header.
*/
public static function header($name) {
$name = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
if (!empty($_SERVER[$name])) {
return $_SERVER[$name];
}
return false;
}
/**
* Get the HTTP method used for this request.
* There are a few ways to specify a method.
*
* - If your client supports it you can use native HTTP methods.
* - You can set the HTTP-X-Method-Override header.
* - You can submit an input with the name `_method`
*
* Any of these 3 approaches can be used to set the HTTP method used
* by CakePHP internally, and will effect the result of this method.
*
* @return string The name of the HTTP method used.
*/
public function method() {
return env('REQUEST_METHOD');
}
/**
* Get the host that the request was handled on.
*
* @return void
*/
public function host() {
return env('HTTP_HOST');
}
/**
* Get the domain name and include $tldLength segments of the tld.
*
* @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
* While `example.co.uk` contains 2.
* @return string Domain name without subdomains.
*/
public function domain($tldLength = 1) {
$segments = explode('.', $this->host());
$domain = array_slice($segments, -1 * ($tldLength + 1));
return implode('.', $domain);
}
/**
* Get the subdomains for a host.
*
* @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
* While `example.co.uk` contains 2.
* @return array of subdomains.
*/
public function subdomains($tldLength = 1) {
$segments = explode('.', $this->host());
return array_slice($segments, 0, -1 * ($tldLength + 1));
}
/**
* Find out which content types the client accepts or check if they accept a
* particular type of content.
*
* #### Get all types:
*
* `$this->request->accepts();`
*
* #### Check for a single type:
*
* `$this->request->accepts('json');`
*
* This method will order the returned content types by the preference values indicated
* by the client.
*
* @param string $type The content type to check for. Leave null to get all types a client accepts.
* @return mixed Either an array of all the types the client accepts or a boolean if they accept the
* provided type.
*/
public function accepts($type = null) {
$raw = $this->parseAccept();
$accept = array();
foreach ($raw as $value => $types) {
$accept = array_merge($accept, $types);
}
if ($type === null) {
return $accept;
}
return in_array($type, $accept);
}
/**
* Parse the HTTP_ACCEPT header and return a sorted array with content types
* as the keys, and pref values as the values.
*
* Generally you want to use CakeRequest::accept() to get a simple list
* of the accepted content types.
*
* @return array An array of prefValue => array(content/types)
*/
public function parseAccept() {
$accept = array();
$header = explode(',', $this->header('accept'));
foreach (array_filter($header) as $value) {
$prefPos = strpos($value, ';');
if ($prefPos !== false) {
$prefValue = substr($value, strpos($value, '=') + 1);
$value = trim(substr($value, 0, $prefPos));
} else {
$prefValue = '1.0';
$value = trim($value);
}
if (!isset($accept[$prefValue])) {
$accept[$prefValue] = array();
}
if ($prefValue) {
$accept[$prefValue][] = $value;
}
}
krsort($accept);
return $accept;
}
/**
* Get the languages accepted by the client, or check if a specific language is accepted.
*
* Get the list of accepted languages:
*
* {{{ CakeRequest::acceptLanguage(); }}}
*
* Check if a specific language is accepted:
*
* {{{ CakeRequest::acceptLanguage('es-es'); }}}
*
* @param string $language The language to test.
* @return If a $language is provided, a boolean. Otherwise the array of accepted languages.
*/
public static function acceptLanguage($language = null) {
$accepts = preg_split('/[;,]/', self::header('Accept-Language'));
foreach ($accepts as &$accept) {
$accept = strtolower($accept);
if (strpos($accept, '_') !== false) {
$accept = str_replace('_', '-', $accept);
}
}
if ($language === null) {
return $accepts;
}
return in_array($language, $accepts);
}
/**
* Provides a read/write accessor for `$this->data`. Allows you
* to use a syntax similar to `CakeSession` for reading post data.
*
* ## Reading values.
*
* `$request->data('Post.title');`
*
* When reading values you will get `null` for keys/values that do not exist.
*
* ## Writing values
*
* `$request->data('Post.title', 'New post!');`
*
* You can write to any value, even paths/keys that do not exist, and the arrays
* will be created for you.
*
* @param string $name,... Dot separated name of the value to read/write
* @return mixed Either the value being read, or this so you can chain consecutive writes.
*/
public function data($name) {
$args = func_get_args();
if (count($args) == 2) {
$this->data = Set::insert($this->data, $name, $args[1]);
return $this;
}
return Set::classicExtract($this->data, $name);
}
/**
* Read data from `php://input`. Useful when interacting with XML or JSON
* request body content.
*
* Getting input with a decoding function:
*
* `$this->request->input('json_decode');`
*
* Getting input using a decoding function, and additional params:
*
* `$this->request->input('Xml::build', array('return' => 'DOMDocument'));`
*
* Any additional parameters are applied to the callback in the order they are given.
*
* @param string $callback A decoding callback that will convert the string data to another
* representation. Leave empty to access the raw input data. You can also
* supply additional parameters for the decoding callback using var args, see above.
* @return The decoded/processed request data.
*/
public function input($callback = null) {
$input = $this->_readInput();
$args = func_get_args();
if (!empty($args)) {
$callback = array_shift($args);
array_unshift($args, $input);
return call_user_func_array($callback, $args);
}
return $input;
}
/**
* Read data from php://input, mocked in tests.
*
* @return string contents of php://input
*/
protected function _readInput() {
if (empty($this->_input)) {
$fh = fopen('php://input', 'r');
$content = stream_get_contents($fh);
fclose($fh);
$this->_input = $content;
}
return $this->_input;
}
/**
* Array access read implementation
*
* @param string $name Name of the key being accessed.
* @return mixed
*/
public function offsetGet($name) {
if (isset($this->params[$name])) {
return $this->params[$name];
}
if ($name == 'url') {
return $this->query;
}
if ($name == 'data') {
return $this->data;
}
return null;
}
/**
* Array access write implementation
*
* @param string $name Name of the key being written
* @param mixed $value The value being written.
* @return void
*/
public function offsetSet($name, $value) {
$this->params[$name] = $value;
}
/**
* Array access isset() implementation
*
* @param string $name thing to check.
* @return boolean
*/
public function offsetExists($name) {
return isset($this->params[$name]);
}
/**
* Array access unset() implementation
*
* @param string $name Name to unset.
* @return void
*/
public function offsetUnset($name) {
unset($this->params[$name]);
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Network/CakeRequest.php | PHP | gpl3 | 22,689 |
<?php
/**
* HTTP Socket connection class.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Network.Http
* @since CakePHP(tm) v 1.2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('CakeSocket', 'Network');
App::uses('Router', 'Routing');
/**
* Cake network socket connection class.
*
* Core base class for HTTP network communication. HttpSocket can be used as an
* Object Oriented replacement for cURL in many places.
*
* @package Cake.Network.Http
*/
class HttpSocket extends CakeSocket {
/**
* 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
*/
public $quirksMode = false;
/**
* Contain information about the last request (read only)
*
* @var array
*/
public $request = array(
'method' => 'GET',
'uri' => array(
'scheme' => 'http',
'host' => null,
'port' => 80,
'user' => null,
'pass' => null,
'path' => null,
'query' => null,
'fragment' => null
),
'version' => '1.1',
'body' => '',
'line' => null,
'header' => array(
'Connection' => 'close',
'User-Agent' => 'CakePHP'
),
'raw' => null,
'cookies' => array()
);
/**
* Contain information about the last response (read only)
*
* @var array
*/
public $response = null;
/**
* Response classname
*
* @var string
*/
public $responseClass = 'HttpResponse';
/**
* Configuration settings for the HttpSocket and the requests
*
* @var array
*/
public $config = array(
'persistent' => false,
'host' => 'localhost',
'protocol' => 'tcp',
'port' => 80,
'timeout' => 30,
'request' => array(
'uri' => array(
'scheme' => 'http',
'host' => 'localhost',
'port' => 80
),
'cookies' => array()
)
);
/**
* Authentication settings
*
* @var array
*/
protected $_auth = array();
/**
* Proxy settings
*
* @var array
*/
protected $_proxy = array();
/**
* Resource to receive the content of request
*
* @var mixed
*/
protected $_contentResource = null;
/**
* Build an HTTP Socket using the specified configuration.
*
* You can use a url string to set the url and use default configurations for
* all other options:
*
* `$http = new HttpSocket('http://cakephp.org/');`
*
* Or use an array to configure multiple options:
*
* {{{
* $http = new HttpSocket(array(
* 'host' => 'cakephp.org',
* 'timeout' => 20
* ));
* }}}
*
* See HttpSocket::$config for options that can be used.
*
* @param mixed $config Configuration information, either a string url or an array of options.
*/
public function __construct($config = array()) {
if (is_string($config)) {
$this->_configUri($config);
} elseif (is_array($config)) {
if (isset($config['request']['uri']) && is_string($config['request']['uri'])) {
$this->_configUri($config['request']['uri']);
unset($config['request']['uri']);
}
$this->config = Set::merge($this->config, $config);
}
parent::__construct($this->config);
}
/**
* Set authentication settings
*
* @param string $method Authentication method (ie. Basic, Digest). If empty, disable authentication
* @param mixed $user Username for authentication. Can be an array with settings to authentication class
* @param string $pass Password for authentication
* @return void
*/
public function configAuth($method, $user = null, $pass = null) {
if (empty($method)) {
$this->_auth = array();
return;
}
if (is_array($user)) {
$this->_auth = array($method => $user);
return;
}
$this->_auth = array($method => compact('user', 'pass'));
}
/**
* Set proxy settings
*
* @param mixed $host Proxy host. Can be an array with settings to authentication class
* @param integer $port Port. Default 3128.
* @param string $method Proxy method (ie, Basic, Digest). If empty, disable proxy authentication
* @param string $user Username if your proxy need authentication
* @param string $pass Password to proxy authentication
* @return void
*/
public function configProxy($host, $port = 3128, $method = null, $user = null, $pass = null) {
if (empty($host)) {
$this->_proxy = array();
return;
}
if (is_array($host)) {
$this->_proxy = $host + array('host' => null);
return;
}
$this->_proxy = compact('host', 'port', 'method', 'user', 'pass');
}
/**
* Set the resource to receive the request content. This resource must support fwrite.
*
* @param mixed $resource Resource or false to disable the resource use
* @return void
* @throws SocketException
*/
public function setContentResource($resource) {
if ($resource === false) {
$this->_contentResource = null;
return;
}
if (!is_resource($resource)) {
throw new SocketException(__d('cake_dev', 'Invalid resource.'));
}
$this->_contentResource = $resource;
}
/**
* Issue the specified request. HttpSocket::get() and HttpSocket::post() wrap this
* method and provide a more granular interface.
*
* @param mixed $request Either an URI string, or an array defining host/uri
* @return mixed false on error, HttpResponse on success
* @throws SocketException
*/
public function request($request = array()) {
$this->reset(false);
if (is_string($request)) {
$request = array('uri' => $request);
} elseif (!is_array($request)) {
return false;
}
if (!isset($request['uri'])) {
$request['uri'] = null;
}
$uri = $this->_parseUri($request['uri']);
if (!isset($uri['host'])) {
$host = $this->config['host'];
}
if (isset($request['host'])) {
$host = $request['host'];
unset($request['host']);
}
$request['uri'] = $this->url($request['uri']);
$request['uri'] = $this->_parseUri($request['uri'], true);
$this->request = Set::merge($this->request, array_diff_key($this->config['request'], array('cookies' => true)), $request);
$this->_configUri($this->request['uri']);
$Host = $this->request['uri']['host'];
if (!empty($this->config['request']['cookies'][$Host])) {
if (!isset($this->request['cookies'])) {
$this->request['cookies'] = array();
}
if (!isset($request['cookies'])) {
$request['cookies'] = array();
}
$this->request['cookies'] = array_merge($this->request['cookies'], $this->config['request']['cookies'][$Host], $request['cookies']);
}
if (isset($host)) {
$this->config['host'] = $host;
}
$this->_setProxy();
$this->request['proxy'] = $this->_proxy;
$cookies = null;
if (is_array($this->request['header'])) {
if (!empty($this->request['cookies'])) {
$cookies = $this->buildCookies($this->request['cookies']);
}
$schema = '';
$port = 0;
if (isset($this->request['uri']['schema'])) {
$schema = $this->request['uri']['schema'];
}
if (isset($this->request['uri']['port'])) {
$port = $this->request['uri']['port'];
}
if (
($schema === 'http' && $port != 80) ||
($schema === 'https' && $port != 443) ||
($port != 80 && $port != 443)
) {
$Host .= ':' . $port;
}
$this->request['header'] = array_merge(compact('Host'), $this->request['header']);
}
if (isset($this->request['uri']['user'], $this->request['uri']['pass'])) {
$this->configAuth('Basic', $this->request['uri']['user'], $this->request['uri']['pass']);
}
$this->_setAuth();
$this->request['auth'] = $this->_auth;
if (is_array($this->request['body'])) {
$this->request['body'] = $this->_httpSerialize($this->request['body']);
}
if (!empty($this->request['body']) && !isset($this->request['header']['Content-Type'])) {
$this->request['header']['Content-Type'] = 'application/x-www-form-urlencoded';
}
if (!empty($this->request['body']) && !isset($this->request['header']['Content-Length'])) {
$this->request['header']['Content-Length'] = strlen($this->request['body']);
}
$connectionType = null;
if (isset($this->request['header']['Connection'])) {
$connectionType = $this->request['header']['Connection'];
}
$this->request['header'] = $this->_buildHeader($this->request['header']) . $cookies;
if (empty($this->request['line'])) {
$this->request['line'] = $this->_buildRequestLine($this->request);
}
if ($this->quirksMode === false && $this->request['line'] === false) {
return false;
}
$this->request['raw'] = '';
if ($this->request['line'] !== false) {
$this->request['raw'] = $this->request['line'];
}
if ($this->request['header'] !== false) {
$this->request['raw'] .= $this->request['header'];
}
$this->request['raw'] .= "\r\n";
$this->request['raw'] .= $this->request['body'];
$this->write($this->request['raw']);
$response = null;
$inHeader = true;
while ($data = $this->read()) {
if ($this->_contentResource) {
if ($inHeader) {
$response .= $data;
$pos = strpos($response, "\r\n\r\n");
if ($pos !== false) {
$pos += 4;
$data = substr($response, $pos);
fwrite($this->_contentResource, $data);
$response = substr($response, 0, $pos);
$inHeader = false;
}
} else {
fwrite($this->_contentResource, $data);
fflush($this->_contentResource);
}
} else {
$response .= $data;
}
}
if ($connectionType === 'close') {
$this->disconnect();
}
list($plugin, $responseClass) = pluginSplit($this->responseClass, true);
App::uses($this->responseClass, $plugin . 'Network/Http');
if (!class_exists($responseClass)) {
throw new SocketException(__d('cake_dev', 'Class %s not found.', $this->responseClass));
}
$responseClass = $this->responseClass;
$this->response = new $responseClass($response);
if (!empty($this->response->cookies)) {
if (!isset($this->config['request']['cookies'][$Host])) {
$this->config['request']['cookies'][$Host] = array();
}
$this->config['request']['cookies'][$Host] = array_merge($this->config['request']['cookies'][$Host], $this->response->cookies);
}
return $this->response;
}
/**
* Issues a GET request to the specified URI, query, and request.
*
* Using a string uri and an array of query string parameters:
*
* `$response = $http->get('http://google.com/search', array('q' => 'cakephp', 'client' => 'safari'));`
*
* Would do a GET request to `http://google.com/search?q=cakephp&client=safari`
*
* You could express the same thing using a uri array and query string parameters:
*
* {{{
* $response = $http->get(
* array('host' => 'google.com', 'path' => '/search'),
* array('q' => 'cakephp', 'client' => 'safari')
* );
* }}}
*
* @param mixed $uri URI to request. Either a string uri, or a uri array, see HttpSocket::_parseUri()
* @param array $query Querystring parameters to append to URI
* @param array $request An indexed array with indexes such as 'method' or uri
* @return mixed Result of request, either false on failure or the response to the request.
*/
public function get($uri = null, $query = array(), $request = array()) {
if (!empty($query)) {
$uri = $this->_parseUri($uri, $this->config['request']['uri']);
if (isset($uri['query'])) {
$uri['query'] = array_merge($uri['query'], $query);
} else {
$uri['query'] = $query;
}
$uri = $this->_buildUri($uri);
}
$request = Set::merge(array('method' => 'GET', 'uri' => $uri), $request);
return $this->request($request);
}
/**
* Issues a POST request to the specified URI, query, and request.
*
* `post()` can be used to post simple data arrays to a url:
*
* {{{
* $response = $http->post('http://example.com', array(
* 'username' => 'batman',
* 'password' => 'bruce_w4yne'
* ));
* }}}
*
* @param mixed $uri URI to request. See HttpSocket::_parseUri()
* @param array $data Array of POST data keys and values.
* @param array $request An indexed array with indexes such as 'method' or uri
* @return mixed Result of request, either false on failure or the response to the request.
*/
public function post($uri = null, $data = array(), $request = array()) {
$request = Set::merge(array('method' => 'POST', 'uri' => $uri, 'body' => $data), $request);
return $this->request($request);
}
/**
* Issues a PUT request to the specified URI, query, and request.
*
* @param mixed $uri URI to request, See HttpSocket::_parseUri()
* @param array $data Array of PUT data keys and values.
* @param array $request An indexed array with indexes such as 'method' or uri
* @return mixed Result of request
*/
public function put($uri = null, $data = array(), $request = array()) {
$request = Set::merge(array('method' => 'PUT', 'uri' => $uri, 'body' => $data), $request);
return $this->request($request);
}
/**
* Issues a DELETE request to the specified URI, query, and request.
*
* @param mixed $uri URI to request (see {@link _parseUri()})
* @param array $data Query to append to URI
* @param array $request An indexed array with indexes such as 'method' or uri
* @return mixed Result of request
*/
public function delete($uri = null, $data = array(), $request = array()) {
$request = Set::merge(array('method' => 'DELETE', 'uri' => $uri, 'body' => $data), $request);
return $this->request($request);
}
/**
* Normalizes urls into a $uriTemplate. If no template is provided
* a default one will be used. Will generate the url using the
* current config information.
*
* ### Usage:
*
* After configuring part of the request parameters, you can use url() to generate
* urls.
*
* {{{
* $http->configUri('http://www.cakephp.org');
* $url = $http->url('/search?q=bar');
* }}}
*
* Would return `http://www.cakephp.org/search?q=bar`
*
* url() can also be used with custom templates:
*
* `$url = $http->url('http://www.cakephp/search?q=socket', '/%path?%query');`
*
* Would return `/search?q=socket`.
*
* @param mixed $url Either a string or array of url options to create a url with.
* @param string $uriTemplate A template string to use for url formatting.
* @return mixed Either false on failure or a string containing the composed url.
*/
public function url($url = null, $uriTemplate = null) {
if (is_null($url)) {
$url = '/';
}
if (is_string($url)) {
if ($url{0} == '/') {
$url = $this->config['request']['uri']['host'] . ':' . $this->config['request']['uri']['port'] . $url;
}
if (!preg_match('/^.+:\/\/|\*|^\//', $url)) {
$url = $this->config['request']['uri']['scheme'] . '://' . $url;
}
} elseif (!is_array($url) && !empty($url)) {
return false;
}
$base = array_merge($this->config['request']['uri'], array('scheme' => array('http', 'https'), 'port' => array(80, 443)));
$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);
}
/**
* Set authentication in request
*
* @return void
* @throws SocketException
*/
protected function _setAuth() {
if (empty($this->_auth)) {
return;
}
$method = key($this->_auth);
list($plugin, $authClass) = pluginSplit($method, true);
$authClass = Inflector::camelize($authClass) . 'Authentication';
App::uses($authClass, $plugin . 'Network/Http');
if (!class_exists($authClass)) {
throw new SocketException(__d('cake_dev', 'Unknown authentication method.'));
}
if (!method_exists($authClass, 'authentication')) {
throw new SocketException(sprintf(__d('cake_dev', 'The %s do not support authentication.'), $authClass));
}
call_user_func_array("$authClass::authentication", array($this, &$this->_auth[$method]));
}
/**
* Set the proxy configuration and authentication
*
* @return void
* @throws SocketException
*/
protected function _setProxy() {
if (empty($this->_proxy) || !isset($this->_proxy['host'], $this->_proxy['port'])) {
return;
}
$this->config['host'] = $this->_proxy['host'];
$this->config['port'] = $this->_proxy['port'];
if (empty($this->_proxy['method']) || !isset($this->_proxy['user'], $this->_proxy['pass'])) {
return;
}
list($plugin, $authClass) = pluginSplit($this->_proxy['method'], true);
$authClass = Inflector::camelize($authClass) . 'Authentication';
App::uses($authClass, $plugin. 'Network/Http');
if (!class_exists($authClass)) {
throw new SocketException(__d('cake_dev', 'Unknown authentication method for proxy.'));
}
if (!method_exists($authClass, 'proxyAuthentication')) {
throw new SocketException(sprintf(__d('cake_dev', 'The %s do not support proxy authentication.'), $authClass));
}
call_user_func_array("$authClass::proxyAuthentication", array($this, &$this->_proxy));
}
/**
* Parses and sets the specified URI into current request configuration.
*
* @param mixed $uri URI, See HttpSocket::_parseUri()
* @return boolean If uri has merged in config
*/
protected function _configUri($uri = null) {
if (empty($uri)) {
return false;
}
if (is_array($uri)) {
$uri = $this->_parseUri($uri);
} else {
$uri = $this->_parseUri($uri, true);
}
if (!isset($uri['host'])) {
return false;
}
$config = array(
'request' => array(
'uri' => array_intersect_key($uri, $this->config['request']['uri'])
)
);
$this->config = Set::merge($this->config, $config);
$this->config = Set::merge($this->config, array_intersect_key($this->config['request']['uri'], $this->config));
return true;
}
/**
* Takes a $uri array and turns it into a fully qualified URL string
*
* @param mixed $uri Either A $uri array, or a request string. Will use $this->config if left empty.
* @param string $uriTemplate The Uri template/format to use.
* @return mixed A fully qualified URL formated according to $uriTemplate, or false on failure
*/
protected 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);
if (!is_array($uri) || empty($uri)) {
return false;
}
$uri['path'] = preg_replace('/^\//', null, $uri['path']);
$uri['query'] = $this->_httpSerialize($uri['query']);
$stripIfEmpty = array(
'query' => '?%query',
'fragment' => '#%fragment',
'user' => '%user:%pass@',
'host' => '%host:%port/'
);
foreach ($stripIfEmpty as $key => $strip) {
if (empty($uri[$key])) {
$uriTemplate = str_replace($strip, null, $uriTemplate);
}
}
$defaultPorts = array('http' => 80, 'https' => 443);
if (array_key_exists($uri['scheme'], $defaultPorts) && $defaultPorts[$uri['scheme']] == $uri['port']) {
$uriTemplate = str_replace(':%port', null, $uriTemplate);
}
foreach ($uri as $property => $value) {
$uriTemplate = str_replace('%' . $property, $value, $uriTemplate);
}
if ($uriTemplate === '/*') {
$uriTemplate = '*';
}
return $uriTemplate;
}
/**
* Parses the given URI and breaks it down into pieces as an indexed array with elements
* such as 'scheme', 'port', 'query'.
*
* @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
*/
protected function _parseUri($uri = null, $base = array()) {
$uriBase = array(
'scheme' => array('http', 'https'),
'host' => null,
'port' => array(80, 443),
'user' => null,
'pass' => null,
'path' => '/',
'query' => null,
'fragment' => null
);
if (is_string($uri)) {
$uri = parse_url($uri);
}
if (!is_array($uri) || empty($uri)) {
return false;
}
if ($base === true) {
$base = $uriBase;
}
if (isset($base['port'], $base['scheme']) && is_array($base['port']) && is_array($base['scheme'])) {
if (isset($uri['scheme']) && !isset($uri['port'])) {
$base['port'] = $base['port'][array_search($uri['scheme'], $base['scheme'])];
} elseif (isset($uri['port']) && !isset($uri['scheme'])) {
$base['scheme'] = $base['scheme'][array_search($uri['port'], $base['port'])];
}
}
if (is_array($base) && !empty($base)) {
$uri = array_merge($base, $uri);
}
if (isset($uri['scheme']) && is_array($uri['scheme'])) {
$uri['scheme'] = array_shift($uri['scheme']);
}
if (isset($uri['port']) && is_array($uri['port'])) {
$uri['port'] = array_shift($uri['port']);
}
if (array_key_exists('query', $uri)) {
$uri['query'] = $this->_parseQuery($uri['query']);
}
if (!array_intersect_key($uriBase, $uri)) {
return false;
}
return $uri;
}
/**
* This function can be thought of as a reverse to PHP5's http_build_query(). It takes a given query string and turns it into an array and
* supports nesting by using the php bracket syntax. So this menas you can parse queries like:
*
* - ?key[subKey]=value
* - ?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()
*
* @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.
*/
protected function _parseQuery($query) {
if (is_array($query)) {
return $query;
}
$parsedQuery = array();
if (is_string($query) && !empty($query)) {
$query = preg_replace('/^\?/', '', $query);
$items = explode('&', $query);
foreach ($items as $item) {
if (strpos($item, '=') !== false) {
list($key, $value) = explode('=', $item, 2);
} else {
$key = $item;
$value = null;
}
$key = urldecode($key);
$value = urldecode($value);
if (preg_match_all('/\[([^\[\]]*)\]/iUs', $key, $matches)) {
$subKeys = $matches[1];
$rootKey = substr($key, 0, strpos($key, '['));
if (!empty($rootKey)) {
array_unshift($subKeys, $rootKey);
}
$queryNode =& $parsedQuery;
foreach ($subKeys as $subKey) {
if (!is_array($queryNode)) {
$queryNode = array();
}
if ($subKey === '') {
$queryNode[] = array();
end($queryNode);
$subKey = key($queryNode);
}
$queryNode =& $queryNode[$subKey];
}
$queryNode = $value;
} else {
$parsedQuery[$key] = $value;
}
}
}
return $parsedQuery;
}
/**
* Builds a request line according to HTTP/1.1 specs. Activate quirks mode to work outside specs.
*
* @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
* @throws SocketException
*/
protected 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)))) {
throw new SocketException(__d('cake_dev', 'HttpSocket::_buildRequestLine - Passed an invalid request line string. Activate quirks mode to do this.'));
}
return $request;
} elseif (!is_array($request)) {
return false;
} elseif (!array_key_exists('uri', $request)) {
return false;
}
$request['uri'] = $this->_parseUri($request['uri']);
$request = array_merge(array('method' => 'GET'), $request);
if (!empty($this->_proxy['host'])) {
$request['uri'] = $this->_buildUri($request['uri'], '%scheme://%host:%port/%path?%query');
} else {
$request['uri'] = $this->_buildUri($request['uri'], '/%path?%query');
}
if (!$this->quirksMode && $request['uri'] === '*' && !in_array($request['method'], $asteriskMethods)) {
throw new SocketException(__d('cake_dev', 'HttpSocket::_buildRequestLine - The "*" asterisk character is only allowed for the following methods: %s. Activate quirks mode to work outside of HTTP/1.1 specs.', implode(',', $asteriskMethods)));
}
return $request['method'] . ' ' . $request['uri'] . ' ' . $versionToken . "\r\n";
}
/**
* Serializes an array for transport.
*
* @param array $data Data to serialize
* @return string Serialized variable
*/
protected function _httpSerialize($data = array()) {
if (is_string($data)) {
return $data;
}
if (empty($data) || !is_array($data)) {
return false;
}
return substr(Router::queryString($data), 1);
}
/**
* Builds the header.
*
* @param array $header Header to build
* @param string $mode
* @return string Header built from array
*/
protected function _buildHeader($header, $mode = 'standard') {
if (is_string($header)) {
return $header;
} elseif (!is_array($header)) {
return false;
}
$fieldsInHeader = array();
foreach ($header as $key => $value) {
$lowKey = strtolower($key);
if (array_key_exists($lowKey, $fieldsInHeader)) {
$header[$fieldsInHeader[$lowKey]] = $value;
unset($header[$key]);
} else {
$fieldsInHeader[$lowKey] = $key;
}
}
$returnHeader = '';
foreach ($header as $field => $contents) {
if (is_array($contents) && $mode == 'standard') {
$contents = implode(',', $contents);
}
foreach ((array)$contents as $content) {
$contents = preg_replace("/\r\n(?![\t ])/", "\r\n ", $content);
$field = $this->_escapeToken($field);
$returnHeader .= $field . ': ' . $contents . "\r\n";
}
}
return $returnHeader;
}
/**
* Builds cookie headers for a request.
*
* @param array $cookies Array of cookies to send with the request.
* @return string Cookie header string to be sent with the request.
* @todo Refactor token escape mechanism to be configurable
*/
public function buildCookies($cookies) {
$header = array();
foreach ($cookies as $name => $cookie) {
$header[] = $name . '=' . $this->_escapeToken($cookie['value'], array(';'));
}
return $this->_buildHeader(array('Cookie' => implode('; ', $header)), 'pragmatic');
}
/**
* Escapes a given $token according to RFC 2616 (HTTP 1.1 specs)
*
* @param string $token Token to escape
* @param array $chars
* @return string Escaped token
* @todo Test $chars parameter
*/
protected function _escapeToken($token, $chars = null) {
$regex = '/([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])/';
$token = preg_replace($regex, '"\\1"', $token);
return $token;
}
/**
* Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
*
* @param boolean $hex true to get them as HEX values, false otherwise
* @param array $chars
* @return array Escape chars
* @todo Test $chars parameter
*/
protected function _tokenEscapeChars($hex = true, $chars = null) {
if (!empty($chars)) {
$escape = $chars;
} else {
$escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
for ($i = 0; $i <= 31; $i++) {
$escape[] = chr($i);
}
$escape[] = chr(127);
}
if ($hex == false) {
return $escape;
}
foreach ($escape as $key => $char) {
$escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
}
return $escape;
}
/**
* Resets the state of this HttpSocket instance to it's initial state (before Object::__construct got executed) or does
* the same thing partially for the request and the response property only.
*
* @param boolean $full If set to false only HttpSocket::response and HttpSocket::request are reseted
* @return boolean True on success
*/
public function reset($full = true) {
static $initalState = array();
if (empty($initalState)) {
$initalState = get_class_vars(__CLASS__);
}
if (!$full) {
$this->request = $initalState['request'];
$this->response = $initalState['response'];
return true;
}
parent::reset($initalState);
return true;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Network/Http/HttpSocket.php | PHP | gpl3 | 28,283 |
<?php
/**
* HTTP Response from HttpSocket.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Network.Http
* @since CakePHP(tm) v 2.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* HTTP Response
*
* @package Cake.Network.Http
*/
class HttpResponse implements ArrayAccess {
/**
* Body content
*
* @var string
*/
public $body = '';
/**
* Headers
*
* @var array
*/
public $headers = array();
/**
* Cookies
*
* @var array
*/
public $cookies = array();
/**
* HTTP version
*
* @var string
*/
public $httpVersion = 'HTTP/1.1';
/**
* Response code
*
* @var integer
*/
public $code = 0;
/**
* Reason phrase
*
* @var string
*/
public $reasonPhrase = '';
/**
* Pure raw content
*
* @var string
*/
public $raw = '';
/**
* Contructor
*
* @param string $message
*/
public function __construct($message = null) {
if ($message !== null) {
$this->parseResponse($message);
}
}
/**
* Body content
*
* @return string
*/
public function body() {
return (string)$this->body;
}
/**
* Get header in case insensitive
*
* @param string $name Header name
* @param array $headers
* @return mixed String if header exists or null
*/
public function getHeader($name, $headers = null) {
if (!is_array($headers)) {
$headers =& $this->headers;
}
if (isset($headers[$name])) {
return $headers[$name];
}
foreach ($headers as $key => $value) {
if (strcasecmp($key, $name) == 0) {
return $value;
}
}
return null;
}
/**
* If return is 200 (OK)
*
* @return boolean
*/
public function isOk() {
return $this->code == 200;
}
/**
* Parses the given message and breaks it down in parts.
*
* @param string $message Message to parse
* @return void
* @throws SocketException
*/
public function parseResponse($message) {
if (!is_string($message)) {
throw new SocketException(__d('cake_dev', 'Invalid response.'));
}
if (!preg_match("/^(.+\r\n)(.*)(?<=\r\n)\r\n/Us", $message, $match)) {
throw new SocketException(__d('cake_dev', 'Invalid HTTP response.'));
}
list(, $statusLine, $header) = $match;
$this->raw = $message;
$this->body = (string)substr($message, strlen($match[0]));
if (preg_match("/(.+) ([0-9]{3}) (.+)\r\n/DU", $statusLine, $match)) {
$this->httpVersion = $match[1];
$this->code = $match[2];
$this->reasonPhrase = $match[3];
}
$this->headers = $this->_parseHeader($header);
$transferEncoding = $this->getHeader('Transfer-Encoding');
$decoded = $this->_decodeBody($this->body, $transferEncoding);
$this->body = $decoded['body'];
if (!empty($decoded['header'])) {
$this->headers = $this->_parseHeader($this->_buildHeader($this->headers) . $this->_buildHeader($decoded['header']));
}
if (!empty($this->headers)) {
$this->cookies = $this->parseCookies($this->headers);
}
}
/**
* Generic function to decode a $body with a given $encoding. Returns either an array with the keys
* 'body' and 'header' or false on failure.
*
* @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 of response headers and body or false.
*/
protected function _decodeBody($body, $encoding = 'chunked') {
if (!is_string($body)) {
return false;
}
if (empty($encoding)) {
return array('body' => $body, 'header' => false);
}
$decodeMethod = '_decode' . Inflector::camelize(str_replace('-', '_', $encoding)) . 'Body';
if (!is_callable(array(&$this, $decodeMethod))) {
return array('body' => $body, 'header' => false);
}
return $this->{$decodeMethod}($body);
}
/**
* Decodes a chunked message $body and returns either an array with the keys 'body' and 'header' or false as
* a result.
*
* @param string $body A string continaing the chunked body to decode.
* @return mixed Array of response headers and body or false.
* @throws SocketException
*/
protected function _decodeChunkedBody($body) {
if (!is_string($body)) {
return false;
}
$decodedBody = null;
$chunkLength = null;
while ($chunkLength !== 0) {
if (!preg_match("/^([0-9a-f]+) *(?:;(.+)=(.+))?\r\n/iU", $body, $match)) {
throw new SocketException(__d('cake_dev', 'HttpSocket::_decodeChunkedBody - Could not parse malformed chunk.'));
}
$chunkSize = 0;
$hexLength = 0;
$chunkExtensionName = '';
$chunkExtensionValue = '';
if (isset($match[0])) {
$chunkSize = $match[0];
}
if (isset($match[1])) {
$hexLength = $match[1];
}
if (isset($match[2])) {
$chunkExtensionName = $match[2];
}
if (isset($match[3])) {
$chunkExtensionValue = $match[3];
}
$body = substr($body, strlen($chunkSize));
$chunkLength = hexdec($hexLength);
$chunk = substr($body, 0, $chunkLength);
if (!empty($chunkExtensionName)) {
/**
* @todo See if there are popular chunk extensions we should implement
*/
}
$decodedBody .= $chunk;
if ($chunkLength !== 0) {
$body = substr($body, $chunkLength + strlen("\r\n"));
}
}
$entityHeader = false;
if (!empty($body)) {
$entityHeader = $this->_parseHeader($body);
}
return array('body' => $decodedBody, 'header' => $entityHeader);
}
/**
* Parses an array based header.
*
* @param array $header Header as an indexed array (field => value)
* @return array Parsed header
*/
protected function _parseHeader($header) {
if (is_array($header)) {
return $header;
} elseif (!is_string($header)) {
return false;
}
preg_match_all("/(.+):(.+)(?:(?<![\t ])\r\n|\$)/Uis", $header, $matches, PREG_SET_ORDER);
$header = array();
foreach ($matches as $match) {
list(, $field, $value) = $match;
$value = trim($value);
$value = preg_replace("/[\t ]\r\n/", "\r\n", $value);
$field = $this->_unescapeToken($field);
if (!isset($header[$field])) {
$header[$field] = $value;
} else {
$header[$field] = array_merge((array)$header[$field], (array)$value);
}
}
return $header;
}
/**
* Parses cookies in response headers.
*
* @param array $header Header array containing one ore more 'Set-Cookie' headers.
* @return mixed Either false on no cookies, or an array of cookies recieved.
* @todo Make this 100% RFC 2965 confirm
*/
public function parseCookies($header) {
$cookieHeader = $this->getHeader('Set-Cookie', $header);
if (!$cookieHeader) {
return false;
}
$cookies = array();
foreach ((array)$cookieHeader as $cookie) {
if (strpos($cookie, '";"') !== false) {
$cookie = str_replace('";"', "{__cookie_replace__}", $cookie);
$parts = str_replace("{__cookie_replace__}", '";"', explode(';', $cookie));
} else {
$parts = preg_split('/\;[ \t]*/', $cookie);
}
list($name, $value) = explode('=', array_shift($parts), 2);
$cookies[$name] = compact('value');
foreach ($parts as $part) {
if (strpos($part, '=') !== false) {
list($key, $value) = explode('=', $part);
} else {
$key = $part;
$value = true;
}
$key = strtolower($key);
if (!isset($cookies[$name][$key])) {
$cookies[$name][$key] = $value;
}
}
}
return $cookies;
}
/**
* Unescapes a given $token according to RFC 2616 (HTTP 1.1 specs)
*
* @param string $token Token to unescape
* @param array $chars
* @return string Unescaped token
* @todo Test $chars parameter
*/
protected function _unescapeToken($token, $chars = null) {
$regex = '/"([' . implode('', $this->_tokenEscapeChars(true, $chars)) . '])"/';
$token = preg_replace($regex, '\\1', $token);
return $token;
}
/**
* Gets escape chars according to RFC 2616 (HTTP 1.1 specs).
*
* @param boolean $hex true to get them as HEX values, false otherwise
* @param array $chars
* @return array Escape chars
* @todo Test $chars parameter
*/
protected function _tokenEscapeChars($hex = true, $chars = null) {
if (!empty($chars)) {
$escape = $chars;
} else {
$escape = array('"', "(", ")", "<", ">", "@", ",", ";", ":", "\\", "/", "[", "]", "?", "=", "{", "}", " ");
for ($i = 0; $i <= 31; $i++) {
$escape[] = chr($i);
}
$escape[] = chr(127);
}
if ($hex == false) {
return $escape;
}
foreach ($escape as $key => $char) {
$escape[$key] = '\\x' . str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
}
return $escape;
}
/**
* ArrayAccess - Offset Exists
*
* @param mixed $offset
* @return boolean
*/
public function offsetExists($offset) {
return in_array($offset, array('raw', 'status', 'header', 'body', 'cookies'));
}
/**
* ArrayAccess - Offset Get
*
* @param mixed $offset
* @return mixed
*/
public function offsetGet($offset) {
switch ($offset) {
case 'raw':
$firstLineLength = strpos($this->raw, "\r\n") + 2;
if ($this->raw[$firstLineLength] === "\r") {
$header = null;
} else {
$header = substr($this->raw, $firstLineLength, strpos($this->raw, "\r\n\r\n") - $firstLineLength) . "\r\n";
}
return array(
'status-line' => $this->httpVersion . ' ' . $this->code . ' ' . $this->reasonPhrase . "\r\n",
'header' => $header,
'body' => $this->body,
'response' => $this->raw
);
case 'status':
return array(
'http-version' => $this->httpVersion,
'code' => $this->code,
'reason-phrase' => $this->reasonPhrase
);
case 'header':
return $this->headers;
case 'body':
return $this->body;
case 'cookies':
return $this->cookies;
}
return null;
}
/**
* ArrayAccess - 0ffset Set
*
* @param mixed $offset
* @param mixed $value
* @return void
*/
public function offsetSet($offset, $value) {
return;
}
/**
* ArrayAccess - Offset Unset
*
* @param mixed $offset
* @return void
*/
public function offsetUnset($offset) {
return;
}
/**
* Instance as string
*
* @return string
*/
public function __toString() {
return $this->body();
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Network/Http/HttpResponse.php | PHP | gpl3 | 10,352 |
<?php
/**
* Basic authentication
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Network.Http
* @since CakePHP(tm) v 2.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Basic authentication
*
* @package Cake.Network.Http
*/
class BasicAuthentication {
/**
* Authentication
*
* @param HttpSocket $http
* @param array $authInfo
* @return void
* @see http://www.ietf.org/rfc/rfc2617.txt
*/
public static function authentication(HttpSocket $http, &$authInfo) {
if (isset($authInfo['user'], $authInfo['pass'])) {
$http->request['header']['Authorization'] = self::_generateHeader($authInfo['user'], $authInfo['pass']);
}
}
/**
* Proxy Authentication
*
* @param HttpSocket $http
* @param array $proxyInfo
* @return void
* @see http://www.ietf.org/rfc/rfc2617.txt
*/
public static function proxyAuthentication(HttpSocket $http, &$proxyInfo) {
if (isset($proxyInfo['user'], $proxyInfo['pass'])) {
$http->request['header']['Proxy-Authorization'] = self::_generateHeader($proxyInfo['user'], $proxyInfo['pass']);
}
}
/**
* Generate basic [proxy] authentication header
*
* @param string $user
* @param string $pass
* @return string
*/
protected static function _generateHeader($user, $pass) {
return 'Basic ' . base64_encode($user . ':' . $pass);
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Network/Http/BasicAuthentication.php | PHP | gpl3 | 1,754 |
<?php
/**
* Digest authentication
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Network.Http
* @since CakePHP(tm) v 2.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Digest authentication
*
* @package Cake.Network.Http
*/
class DigestAuthentication {
/**
* Authentication
*
* @param HttpSocket $http
* @param array $authInfo
* @return void
* @link http://www.ietf.org/rfc/rfc2617.txt
*/
public static function authentication(HttpSocket $http, &$authInfo) {
if (isset($authInfo['user'], $authInfo['pass'])) {
if (!isset($authInfo['realm']) && !self::_getServerInformation($http, $authInfo)) {
return;
}
$http->request['header']['Authorization'] = self::_generateHeader($http, $authInfo);
}
}
/**
* Retrive information about the authetication
*
* @param HttpSocket $http
* @param array $authInfo
* @return boolean
*/
protected static function _getServerInformation(HttpSocket $http, &$authInfo) {
$originalRequest = $http->request;
$http->configAuth(false);
$http->request($http->request);
$http->request = $originalRequest;
$http->configAuth('Digest', $authInfo);
if (empty($http->response['header']['WWW-Authenticate'])) {
return false;
}
preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $http->response['header']['WWW-Authenticate'], $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$authInfo[$match[1]] = $match[2];
}
if (!empty($authInfo['qop']) && empty($authInfo['nc'])) {
$authInfo['nc'] = 1;
}
return true;
}
/**
* Generate the header Authorization
*
* @param HttpSocket $http
* @param array $authInfo
* @return string
*/
protected static function _generateHeader(HttpSocket $http, &$authInfo) {
$a1 = md5($authInfo['user'] . ':' . $authInfo['realm'] . ':' . $authInfo['pass']);
$a2 = md5($http->request['method'] . ':' . $http->request['uri']['path']);
if (empty($authInfo['qop'])) {
$response = md5($a1 . ':' . $authInfo['nonce'] . ':' . $a2);
} else {
$authInfo['cnonce'] = uniqid();
$nc = sprintf('%08x', $authInfo['nc']++);
$response = md5($a1 . ':' . $authInfo['nonce'] . ':' . $nc . ':' . $authInfo['cnonce'] . ':auth:' . $a2);
}
$authHeader = 'Digest ';
$authHeader .= 'username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $authInfo['user']) . '", ';
$authHeader .= 'realm="' . $authInfo['realm'] . '", ';
$authHeader .= 'nonce="' . $authInfo['nonce'] . '", ';
$authHeader .= 'uri="' . $http->request['uri']['path'] . '", ';
$authHeader .= 'response="' . $response . '"';
if (!empty($authInfo['opaque'])) {
$authHeader .= ', opaque="' . $authInfo['opaque'] . '"';
}
if (!empty($authInfo['qop'])) {
$authHeader .= ', qop="auth", nc=' . $nc . ', cnonce="' . $authInfo['cnonce'] . '"';
}
return $authHeader;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Network/Http/DigestAuthentication.php | PHP | gpl3 | 3,259 |
<?php
/**
* CakeResponse
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Network
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* CakeResponse is responsible for managing the response text, status and headers of a HTTP response.
*
* By default controllers will use this class to render their response. If you are going to use
* a custom response class it should subclass this object in order to ensure compatibility.
*
* @package Cake.Network
*/
class CakeResponse {
/**
* Holds HTTP response statuses
*
* @var array
*/
protected $_statusCodes = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out'
);
/**
* Holds known mime type mappings
*
* @var array
*/
protected $_mimeTypes = array(
'ai' => 'application/postscript',
'bcpio' => 'application/x-bcpio',
'bin' => 'application/octet-stream',
'ccad' => 'application/clariscad',
'cdf' => 'application/x-netcdf',
'class' => 'application/octet-stream',
'cpio' => 'application/x-cpio',
'cpt' => 'application/mac-compactpro',
'csh' => 'application/x-csh',
'csv' => array('text/csv', 'application/vnd.ms-excel', 'text/plain'),
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dms' => 'application/octet-stream',
'doc' => 'application/msword',
'drw' => 'application/drafting',
'dvi' => 'application/x-dvi',
'dwg' => 'application/acad',
'dxf' => 'application/dxf',
'dxr' => 'application/x-director',
'eot' => 'application/vnd.ms-fontobject',
'eps' => 'application/postscript',
'exe' => 'application/octet-stream',
'ez' => 'application/andrew-inset',
'flv' => 'video/x-flv',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'bz2' => 'application/x-bzip',
'7z' => 'application/x-7z-compressed',
'hdf' => 'application/x-hdf',
'hqx' => 'application/mac-binhex40',
'ico' => 'image/vnd.microsoft.icon',
'ips' => 'application/x-ipscript',
'ipx' => 'application/x-ipix',
'js' => 'text/javascript',
'latex' => 'application/x-latex',
'lha' => 'application/octet-stream',
'lsp' => 'application/x-lisp',
'lzh' => 'application/octet-stream',
'man' => 'application/x-troff-man',
'me' => 'application/x-troff-me',
'mif' => 'application/vnd.mif',
'ms' => 'application/x-troff-ms',
'nc' => 'application/x-netcdf',
'oda' => 'application/oda',
'otf' => 'font/otf',
'pdf' => 'application/pdf',
'pgn' => 'application/x-chess-pgn',
'pot' => 'application/mspowerpoint',
'pps' => 'application/mspowerpoint',
'ppt' => 'application/mspowerpoint',
'ppz' => 'application/mspowerpoint',
'pre' => 'application/x-freelance',
'prt' => 'application/pro_eng',
'ps' => 'application/postscript',
'roff' => 'application/x-troff',
'scm' => 'application/x-lotusscreencam',
'set' => 'application/set',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'sit' => 'application/x-stuffit',
'skd' => 'application/x-koan',
'skm' => 'application/x-koan',
'skp' => 'application/x-koan',
'skt' => 'application/x-koan',
'smi' => 'application/smil',
'smil' => 'application/smil',
'sol' => 'application/solids',
'spl' => 'application/x-futuresplash',
'src' => 'application/x-wais-source',
'step' => 'application/STEP',
'stl' => 'application/SLA',
'stp' => 'application/STEP',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
'swf' => 'application/x-shockwave-flash',
't' => 'application/x-troff',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'texi' => 'application/x-texinfo',
'texinfo' => 'application/x-texinfo',
'tr' => 'application/x-troff',
'tsp' => 'application/dsptype',
'ttf' => 'font/ttf',
'unv' => 'application/i-deas',
'ustar' => 'application/x-ustar',
'vcd' => 'application/x-cdlink',
'vda' => 'application/vda',
'xlc' => 'application/vnd.ms-excel',
'xll' => 'application/vnd.ms-excel',
'xlm' => 'application/vnd.ms-excel',
'xls' => 'application/vnd.ms-excel',
'xlw' => 'application/vnd.ms-excel',
'zip' => 'application/zip',
'aif' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'au' => 'audio/basic',
'kar' => 'audio/midi',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'mpga' => 'audio/mpeg',
'ra' => 'audio/x-realaudio',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'snd' => 'audio/basic',
'tsi' => 'audio/TSP-audio',
'wav' => 'audio/x-wav',
'asc' => 'text/plain',
'c' => 'text/plain',
'cc' => 'text/plain',
'css' => 'text/css',
'etx' => 'text/x-setext',
'f' => 'text/plain',
'f90' => 'text/plain',
'h' => 'text/plain',
'hh' => 'text/plain',
'html' => array('text/html', '*/*'),
'htm' => array('text/html', '*/*'),
'm' => 'text/plain',
'rtf' => 'text/rtf',
'rtx' => 'text/richtext',
'sgm' => 'text/sgml',
'sgml' => 'text/sgml',
'tsv' => 'text/tab-separated-values',
'tpl' => 'text/template',
'txt' => 'text/plain',
'text' => 'text/plain',
'xml' => array('application/xml', 'text/xml'),
'avi' => 'video/x-msvideo',
'fli' => 'video/x-fli',
'mov' => 'video/quicktime',
'movie' => 'video/x-sgi-movie',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'qt' => 'video/quicktime',
'viv' => 'video/vnd.vivo',
'vivo' => 'video/vnd.vivo',
'gif' => 'image/gif',
'ief' => 'image/ief',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'pbm' => 'image/x-portable-bitmap',
'pgm' => 'image/x-portable-graymap',
'png' => 'image/png',
'pnm' => 'image/x-portable-anymap',
'ppm' => 'image/x-portable-pixmap',
'ras' => 'image/cmu-raster',
'rgb' => 'image/x-rgb',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'xbm' => 'image/x-xbitmap',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'ice' => 'x-conference/x-cooltalk',
'iges' => 'model/iges',
'igs' => 'model/iges',
'mesh' => 'model/mesh',
'msh' => 'model/mesh',
'silo' => 'model/mesh',
'vrml' => 'model/vrml',
'wrl' => 'model/vrml',
'mime' => 'www/mime',
'pdb' => 'chemical/x-pdb',
'xyz' => 'chemical/x-pdb',
'javascript' => 'text/javascript',
'json' => 'application/json',
'form' => 'application/x-www-form-urlencoded',
'file' => 'multipart/form-data',
'xhtml' => array('application/xhtml+xml', 'application/xhtml', 'text/xhtml'),
'xhtml-mobile' => 'application/vnd.wap.xhtml+xml',
'rss' => 'application/rss+xml',
'atom' => 'application/atom+xml',
'amf' => 'application/x-amf',
'wap' => array('text/vnd.wap.wml', 'text/vnd.wap.wmlscript', 'image/vnd.wap.wbmp'),
'wml' => 'text/vnd.wap.wml',
'wmlscript' => 'text/vnd.wap.wmlscript',
'wbmp' => 'image/vnd.wap.wbmp',
);
/**
* Protocol header to send to the client
*
* @var string
*/
protected $_protocol = 'HTTP/1.1';
/**
* Status code to send to the client
*
* @var integer
*/
protected $_status = 200;
/**
* Content type to send. This can be an 'extension' that will be transformed using the $_mimetypes array
* or a complete mime-type
*
* @var integer
*/
protected $_contentType = 'text/html';
/**
* Buffer list of headers
*
* @var array
*/
protected $_headers = array();
/**
* Buffer string for response message
*
* @var string
*/
protected $_body = null;
/**
* The charset the response body is encoded with
*
* @var string
*/
protected $_charset = 'UTF-8';
/**
* Class constructor
*
* @param array $options list of parameters to setup the response. Possible values are:
* - body: the rensonse text that should be sent to the client
* - status: the HTTP status code to respond with
* - type: a complete mime-type string or an extension mapepd in this class
* - charset: the charset for the response body
*/
public function __construct(array $options = array()) {
if (isset($options['body'])) {
$this->body($options['body']);
}
if (isset($options['status'])) {
$this->statusCode($options['status']);
}
if (isset($options['type'])) {
$this->type($options['type']);
}
if (isset($options['charset'])) {
$this->charset($options['charset']);
}
}
/**
* Sends the complete response to the client including headers and message body.
* Will echo out the content in the response body.
*
* @return void
*/
public function send() {
if (isset($this->_headers['Location']) && $this->_status === 200) {
$this->statusCode(302);
}
$codeMessage = $this->_statusCodes[$this->_status];
$this->_sendHeader("{$this->_protocol} {$this->_status} {$codeMessage}");
$this->_sendHeader('Content-Type', "{$this->_contentType}; charset={$this->_charset}");
foreach ($this->_headers as $header => $value) {
$this->_sendHeader($header, $value);
}
$this->_sendContent($this->_body);
}
/**
* Sends a header to the client.
*
* @param string $name the header name
* @param string $value the header value
* @return void
*/
protected function _sendHeader($name, $value = null) {
if (!headers_sent()) {
if (is_null($value)) {
header($name);
} else {
header("{$name}: {$value}");
}
}
}
/**
* Sends a content string to the client.
*
* @param string $content string to send as response body
* @return void
*/
protected function _sendContent($content) {
echo $content;
}
/**
* Buffers a header string to be sent
* Returns the complete list of buffered headers
*
* ### Single header
* e.g `header('Location', 'http://example.com');`
*
* ### Multiple headers
* e.g `header(array('Location' => 'http://example.com', 'X-Extra' => 'My header'));`
*
* ### String header
* e.g `header('WWW-Authenticate: Negotiate');`
*
* ### Array of string headers
* e.g `header(array('WWW-Authenticate: Negotiate', 'Content-type: application/pdf'));`
*
* Multiple calls for setting the same header name will have the same effect as setting the header once
* with the last value sent for it
* e.g `header('WWW-Authenticate: Negotiate'); header('WWW-Authenticate: Not-Negotiate');`
* will have the same effect as only doing `header('WWW-Authenticate: Not-Negotiate');`
*
* @param mixed $header. An array of header strings or a single header string
* - an assotiative array of "header name" => "header value" is also accepted
* - an array of string headers is also accepted
* @param mixed $value. The header value.
* @return array list of headers to be sent
*/
public function header($header = null, $value = null) {
if (is_null($header)) {
return $this->_headers;
}
if (is_array($header)) {
foreach ($header as $h => $v) {
if (is_numeric($h)) {
$this->header($v);
continue;
}
$this->_headers[$h] = trim($v);
}
return $this->_headers;
}
if (!is_null($value)) {
$this->_headers[$header] = $value;
return $this->_headers;
}
list($header, $value) = explode(':', $header, 2);
$this->_headers[$header] = trim($value);
return $this->_headers;
}
/**
* Buffers the response message to be sent
* if $content is null the current buffer is returned
*
* @param string $content the string message to be sent
* @return string current message buffer if $content param is passed as null
*/
public function body($content = null) {
if (is_null($content)) {
return $this->_body;
}
return $this->_body = $content;
}
/**
* Sets the HTTP status code to be sent
* if $code is null the current code is returned
*
* @param integer $code
* @return integer current status code
* @throws CakeException When an unknown status code is reached.
*/
public function statusCode($code = null) {
if (is_null($code)) {
return $this->_status;
}
if (!isset($this->_statusCodes[$code])) {
throw new CakeException(__d('cake_dev', 'Unknown status code'));
}
return $this->_status = $code;
}
/**
* Queries & sets valid HTTP response codes & messages.
*
* @param mixed $code If $code is an integer, then the corresponding code/message is
* returned if it exists, null if it does not exist. If $code is an array,
* then the 'code' and 'message' keys of each nested array are added to the default
* HTTP codes. Example:
*
* httpCodes(404); // returns array(404 => 'Not Found')
*
* httpCodes(array(
* 701 => 'Unicorn Moved',
* 800 => 'Unexpected Minotaur'
* )); // sets these new values, and returns true
*
* @return mixed associative array of the HTTP codes as keys, and the message
* strings as values, or null of the given $code does not exist.
*/
public function httpCodes($code = null) {
if (empty($code)) {
return $this->_statusCodes;
}
if (is_array($code)) {
$this->_statusCodes = $code + $this->_statusCodes;
return true;
}
if (!isset($this->_statusCodes[$code])) {
return null;
}
return array($code => $this->_statusCodes[$code]);
}
/**
* Sets the response content type. It can be either a file extension
* which will be mapped internally to a mime-type or a string representing a mime-type
* if $contentType is null the current content type is returned
* if $contentType is an associative array, it will be stored as a content type definition
*
* ### Setting the content type
*
* e.g `type('jpg');`
*
* ### Returning the current content type
*
* e.g `type();`
*
* ### Storing a content type definition
*
* e.g `type(array('keynote' => 'application/keynote'));`
*
* ### Replacing a content type definition
*
* e.g `type(array('jpg' => 'text/plain'));`
*
* @param string $contentType
* @return mixed current content type or false if supplied an invalid content type
*/
public function type($contentType = null) {
if (is_null($contentType)) {
return $this->_contentType;
}
if (is_array($contentType)) {
$type = key($contentType);
$defitition = current($contentType);
$this->_mimeTypes[$type] = $defitition;
return $this->_contentType;
}
if (isset($this->_mimeTypes[$contentType])) {
$contentType = $this->_mimeTypes[$contentType];
$contentType = is_array($contentType) ? current($contentType) : $contentType;
}
if (strpos($contentType, '/') === false) {
return false;
}
return $this->_contentType = $contentType;
}
/**
* Returns the mime type definition for an alias
*
* e.g `getMimeType('pdf'); // returns 'application/pdf'`
*
* @param string $alias the content type alias to map
* @return mixed string mapped mime type or false if $alias is not mapped
*/
public function getMimeType($alias) {
if (isset($this->_mimeTypes[$alias])) {
return $this->_mimeTypes[$alias];
}
return false;
}
/**
* Maps a content-type back to an alias
*
* e.g `mapType('application/pdf'); // returns 'pdf'`
*
* @param mixed $ctype Either a string content type to map, or an array of types.
* @return mixed Aliases for the types provided.
*/
public function mapType($ctype) {
if (is_array($ctype)) {
return array_map(array($this, 'mapType'), $ctype);
}
foreach ($this->_mimeTypes as $alias => $types) {
if (is_array($types) && in_array($ctype, $types)) {
return $alias;
} elseif (is_string($types) && $types == $ctype) {
return $alias;
}
}
return null;
}
/**
* Sets the response charset
* if $charset is null the current charset is returned
*
* @param string $charset
* @return string current charset
*/
public function charset($charset = null) {
if (is_null($charset)) {
return $this->_charset;
}
return $this->_charset = $charset;
}
/**
* Sets the correct headers to instruct the client to not cache the response
*
* @return void
*/
public function disableCache() {
$this->header(array(
'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
'Last-Modified' => gmdate("D, d M Y H:i:s") . " GMT",
'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
'Pragma' => 'no-cache'
));
}
/**
* Sets the correct headers to instruct the client to cache the response.
*
* @param string $since a valid time since the response text has not been modified
* @param string $time a valid time for cache expiry
* @return void
*/
public function cache($since, $time = '+1 day') {
if (!is_integer($time)) {
$time = strtotime($time);
}
$this->header(array(
'Date' => gmdate("D, j M Y G:i:s ", time()) . 'GMT',
'Last-Modified' => gmdate("D, j M Y G:i:s ", $since) . 'GMT',
'Expires' => gmdate("D, j M Y H:i:s", $time) . " GMT",
'Cache-Control' => 'public, max-age=' . ($time - time()),
'Pragma' => 'cache'
));
}
/**
* Sets the correct output buffering handler to send a compressed response. Responses will
* be compressed with zlib, if the extension is available.
*
* @return boolean false if client does not accept compressed responses or no handler is available, true otherwise
*/
public function compress() {
$compressionEnabled = ini_get("zlib.output_compression") !== '1' &&
extension_loaded("zlib") &&
(strpos(env('HTTP_ACCEPT_ENCODING'), 'gzip') !== false);
return $compressionEnabled && ob_start('ob_gzhandler');
}
/**
* Sets the correct headers to instruct the browser to dowload the response as a file.
*
* @param string $filename the name of the file as the browser will download the response
* @return void
*/
public function download($filename) {
$this->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
}
/**
* String conversion. Fetches the response body as a string.
* Does *not* send headers.
*
* @return string
*/
public function __toString() {
return (string)$this->_body;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Network/CakeResponse.php | PHP | gpl3 | 19,192 |
<?php
/**
* Abstract send email
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Network.Email
* @since CakePHP(tm) v 2.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Abstract class
*
* @package Cake.Network.Email
*/
abstract class AbstractTransport {
/**
* Configurations
*
* @var array
*/
protected $_config = array();
/**
* Send mail
*
* @params CakeEmail $email
* @return array
*/
abstract public function send(CakeEmail $email);
/**
* Set the config
*
* @param array $config
* @return array Returns configs
*/
public function config($config = null) {
if (is_array($config)) {
$this->_config = $config;
}
return $this->_config;
}
/**
* Help to convert headers in string
*
* @param array $headers Headers in format key => value
* @param string $eol
* @return string
*/
protected function _headersToString($headers, $eol = "\r\n") {
$out = '';
foreach ($headers as $key => $value) {
if ($value === false || $value === null || $value === '') {
continue;
}
$out .= $key . ': ' . $value . $eol;
}
if (!empty($out)) {
$out = substr($out, 0, -1 * strlen($eol));
}
return $out;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Network/Email/AbstractTransport.php | PHP | gpl3 | 1,618 |
<?php
/**
* Send mail using SMTP protocol
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Network.Email
* @since CakePHP(tm) v 2.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('CakeSocket', 'Network');
/**
* SendEmail class
*
* @package Cake.Network.Email
*/
class SmtpTransport extends AbstractTransport {
/**
* Socket to SMTP server
*
* @var CakeSocket
*/
protected $_socket;
/**
* CakeEmail
*
* @var CakeEmail
*/
protected $_cakeEmail;
/**
* Content of email to return
*
* @var string
*/
protected $_content;
/**
* Send mail
*
* @param CakeEmail $email CakeEmail
* @return array
* @throws SocketException
*/
public function send(CakeEmail $email) {
$this->_cakeEmail = $email;
$this->_connect();
$this->_auth();
$this->_sendRcpt();
$this->_sendData();
$this->_disconnect();
return $this->_content;
}
/**
* Set the configuration
*
* @param array $config
* @return void
*/
public function config($config = array()) {
$default = array(
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => null,
'password' => null,
'client' => null
);
$this->_config = $config + $default;
}
/**
* Connect to SMTP Server
*
* @return void
* @throws SocketException
*/
protected function _connect() {
$this->_generateSocket();
if (!$this->_socket->connect()) {
throw new SocketException(__d('cake_dev', 'Unable to connect to SMTP server.'));
}
$this->_smtpSend(null, '220');
if (isset($this->_config['client'])) {
$host = $this->_config['client'];
} elseif ($httpHost = env('HTTP_HOST')) {
list($host) = explode(':', $httpHost);
} else {
$host = 'localhost';
}
try {
$this->_smtpSend("EHLO {$host}", '250');
} catch (SocketException $e) {
try {
$this->_smtpSend("HELO {$host}", '250');
} catch (SocketException $e2) {
throw new SocketException(__d('cake_dev', 'SMTP server did not accept the connection.'));
}
}
}
/**
* Send authentication
*
* @return void
* @throws SocketException
*/
protected function _auth() {
if (isset($this->_config['username']) && isset($this->_config['password'])) {
$authRequired = $this->_smtpSend('AUTH LOGIN', '334|503');
if ($authRequired == '334') {
if (!$this->_smtpSend(base64_encode($this->_config['username']), '334')) {
throw new SocketException(__d('cake_dev', 'SMTP server did not accept the username.'));
}
if (!$this->_smtpSend(base64_encode($this->_config['password']), '235')) {
throw new SocketException(__d('cake_dev', 'SMTP server did not accept the password.'));
}
} elseif ($authRequired != '503') {
throw new SocketException(__d('cake_dev', 'SMTP does not require authentication.'));
}
}
}
/**
* Send emails
*
* @return void
* @throws SocketException
*/
protected function _sendRcpt() {
$from = $this->_cakeEmail->from();
$this->_smtpSend('MAIL FROM:<' . key($from) . '>');
$to = $this->_cakeEmail->to();
$cc = $this->_cakeEmail->cc();
$bcc = $this->_cakeEmail->bcc();
$emails = array_merge(array_keys($to), array_keys($cc), array_keys($bcc));
foreach ($emails as $email) {
$this->_smtpSend('RCPT TO:<' . $email . '>');
}
}
/**
* Send Data
*
* @return void
* @throws SocketException
*/
protected function _sendData() {
$this->_smtpSend('DATA', '354');
$headers = $this->_cakeEmail->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc', 'subject'));
$headers = $this->_headersToString($headers);
$message = implode("\r\n", $this->_cakeEmail->message());
$this->_smtpSend($headers . "\r\n\r\n" . $message . "\r\n\r\n\r\n.");
$this->_content = array('headers' => $headers, 'message' => $message);
}
/**
* Disconnect
*
* @return void
* @throws SocketException
*/
protected function _disconnect() {
$this->_smtpSend('QUIT', false);
$this->_socket->disconnect();
}
/**
* Helper method to generate socket
*
* @return void
* @throws SocketException
*/
protected function _generateSocket() {
$this->_socket = new CakeSocket($this->_config);
}
/**
* Protected method for sending data to SMTP connection
*
* @param string $data data to be sent to SMTP server
* @param mixed $checkCode code to check for in server response, false to skip
* @return void
* @throws SocketException
*/
protected function _smtpSend($data, $checkCode = '250') {
if (!is_null($data)) {
$this->_socket->write($data . "\r\n");
}
while ($checkCode !== false) {
$response = '';
$startTime = time();
while (substr($response, -2) !== "\r\n" && ((time() - $startTime) < $this->_config['timeout'])) {
$response .= $this->_socket->read();
}
if (substr($response, -2) !== "\r\n") {
throw new SocketException(__d('cake_dev', 'SMTP timeout.'));
}
$response = end(explode("\r\n", rtrim($response, "\r\n")));
if (preg_match('/^(' . $checkCode . ')(.)/', $response, $code)) {
if ($code[2] === '-') {
continue;
}
return $code[1];
}
throw new SocketException(__d('cake_dev', 'SMTP Error: %s', $response));
}
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Network/Email/SmtpTransport.php | PHP | gpl3 | 5,563 |
<?php
/**
* Emulates the email sending process for testing purposes
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Network.Email
* @since CakePHP(tm) v 2.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Debug Transport class, useful for emulate the email sending process and inspect the resulted
* email message before actually send it during development
*
* @package Cake.Network.Email
*/
class DebugTransport extends AbstractTransport {
/**
* Send mail
*
* @param CakeEmail $email CakeEmail
* @return array
*/
public function send(CakeEmail $email) {
$headers = $email->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc', 'subject'));
$headers = $this->_headersToString($headers);
$message = implode("\r\n", (array)$email->message());
return array('headers' => $headers, 'message' => $message);
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Network/Email/DebugTransport.php | PHP | gpl3 | 1,333 |
<?php
/**
* Cake E-Mail
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Network.Email
* @since CakePHP(tm) v 2.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Validation', 'Utility');
App::uses('Multibyte', 'I18n');
App::uses('AbstractTransport', 'Network/Email');
App::uses('String', 'Utility');
App::uses('View', 'View');
App::import('I18n', 'Multibyte');
/**
* Cake e-mail class.
*
* This class is used for handling Internet Message Format based
* based on the standard outlined in http://www.rfc-editor.org/rfc/rfc2822.txt
*
* @package Cake.Network.Email
*/
class CakeEmail {
/**
* Default X-Mailer
*
* @constant EMAIL_CLIENT
*/
const EMAIL_CLIENT = 'CakePHP Email';
/**
* Line length - no should more - RFC 2822 - 2.1.1
*
* @constant LINE_LENGTH_SHOULD
*/
const LINE_LENGTH_SHOULD = 78;
/**
* Line length - no must more - RFC 2822 - 2.1.1
*
* @constant LINE_LENGTH_MUST
*/
const LINE_LENGTH_MUST = 998;
/**
* Type of message - HTML
*
* @constant MESSAGE_HTML
*/
const MESSAGE_HTML = 'html';
/**
* Type of message - TEXT
*
* @constant MESSAGE_TEXT
*/
const MESSAGE_TEXT = 'text';
/**
* Recipient of the email
*
* @var array
*/
protected $_to = array();
/**
* The mail which the email is sent from
*
* @var array
*/
protected $_from = array();
/**
* The sender email
*
* @var array();
*/
protected $_sender = array();
/**
* The email the recipient will reply to
*
* @var array
*/
protected $_replyTo = array();
/**
* The read receipt email
*
* @var array
*/
protected $_readReceipt = array();
/**
* The mail that will be used in case of any errors like
* - Remote mailserver down
* - Remote user has exceeded his quota
* - Unknown user
*
* @var array
*/
protected $_returnPath = array();
/**
* Carbon Copy
*
* List of email's that should receive a copy of the email.
* The Recipient WILL be able to see this list
*
* @var array
*/
protected $_cc = array();
/**
* Blind Carbon Copy
*
* List of email's that should receive a copy of the email.
* The Recipient WILL NOT be able to see this list
*
* @var array
*/
protected $_bcc = array();
/**
* Message ID
*
* @var mixed True to generate, False to ignore, String with value
*/
protected $_messageId = true;
/**
* The subject of the email
*
* @var string
*/
protected $_subject = '';
/**
* Associative array of a user defined headers
* Keys will be prefixed 'X-' as per RFC2822 Section 4.7.5
*
* @var array
*/
protected $_headers = array();
/**
* Layout for the View
*
* @var string
*/
protected $_layout = 'default';
/**
* Template for the view
*
* @var string
*/
protected $_template = '';
/**
* View for render
*
* @var string
*/
protected $_viewRender = 'View';
/**
* Vars to sent to render
*
* @var array
*/
protected $_viewVars = array();
/**
* Helpers to be used in the render
*
* @var array
*/
protected $_helpers = array('Html');
/**
* Text message
*
* @var string
*/
protected $_textMessage = '';
/**
* Html message
*
* @var string
*/
protected $_htmlMessage = '';
/**
* Final message to send
*
* @var array
*/
protected $_message = array();
/**
* Available formats to be sent.
*
* @var array
*/
protected $_emailFormatAvailable = array('text', 'html', 'both');
/**
* What format should the email be sent in
*
* @var string
*/
protected $_emailFormat = 'text';
/**
* What method should the email be sent
*
* @var string
*/
protected $_transportName = 'Mail';
/**
* Instance of transport class
*
* @var AbstractTransport
*/
protected $_transportClass = null;
/**
* Charset the email body is sent in
*
*
* @var string
*/
public $charset = 'utf-8';
/**
* Charset the email header is sent in
* If null, the $charset property will be used as default
* @var string
*/
public $headerCharset = null;
/**
* The application wide charset, used to encode headers and body
* @var string
*/
public $_appCharset = null;
/**
* List of files that should be attached to the email.
*
* Only absolute paths
*
* @var array
*/
protected $_attachments = array();
/**
* If set, boundary to use for multipart mime messages
*
* @var string
*/
protected $_boundary = null;
/**
* Configuration to transport
*
* @var mixed
*/
protected $_config = array();
/**
* Constructor
* @param mixed $config Array of configs, or string to load configs from email.php
*
*/
public function __construct($config = null) {
$this->_appCharset = Configure::read('App.encoding');
if ($this->_appCharset !== null) {
$this->charset = $this->_appCharset;
}
if ($config) {
$this->config($config);
}
if (empty($this->headerCharset)) {
$this->headerCharset = $this->charset;
}
}
/**
* From
*
* @param mixed $email
* @param string $name
* @return mixed
* @throws SocketException
*/
public function from($email = null, $name = null) {
if ($email === null) {
return $this->_from;
}
return $this->_setEmailSingle('_from', $email, $name, __d('cake_dev', 'From requires only 1 email address.'));
}
/**
* Sender
*
* @param mixed $email
* @param string $name
* @return mixed
* @throws SocketException
*/
public function sender($email = null, $name = null) {
if ($email === null) {
return $this->_sender;
}
return $this->_setEmailSingle('_sender', $email, $name, __d('cake_dev', 'Sender requires only 1 email address.'));
}
/**
* Reply-To
*
* @param mixed $email
* @param string $name
* @return mixed
* @throws SocketException
*/
public function replyTo($email = null, $name = null) {
if ($email === null) {
return $this->_replyTo;
}
return $this->_setEmailSingle('_replyTo', $email, $name, __d('cake_dev', 'Reply-To requires only 1 email address.'));
}
/**
* Read Receipt (Disposition-Notification-To header)
*
* @param mixed $email
* @param string $name
* @return mixed
* @throws SocketException
*/
public function readReceipt($email = null, $name = null) {
if ($email === null) {
return $this->_readReceipt;
}
return $this->_setEmailSingle('_readReceipt', $email, $name, __d('cake_dev', 'Disposition-Notification-To requires only 1 email address.'));
}
/**
* Return Path
*
* @param mixed $email
* @param string $name
* @return mixed
* @throws SocketException
*/
public function returnPath($email = null, $name = null) {
if ($email === null) {
return $this->_returnPath;
}
return $this->_setEmailSingle('_returnPath', $email, $name, __d('cake_dev', 'Return-Path requires only 1 email address.'));
}
/**
* To
*
* @param mixed $email Null to get, String with email, Array with email as key, name as value or email as value (without name)
* @param string $name
* @return mixed
*/
public function to($email = null, $name = null) {
if ($email === null) {
return $this->_to;
}
return $this->_setEmail('_to', $email, $name);
}
/**
* Add To
*
* @param mixed $email String with email, Array with email as key, name as value or email as value (without name)
* @param string $name
* @return CakeEmail $this
*/
public function addTo($email, $name = null) {
return $this->_addEmail('_to', $email, $name);
}
/**
* Cc
*
* @param mixed $email String with email, Array with email as key, name as value or email as value (without name)
* @param string $name
* @return mixed
*/
public function cc($email = null, $name = null) {
if ($email === null) {
return $this->_cc;
}
return $this->_setEmail('_cc', $email, $name);
}
/**
* Add Cc
*
* @param mixed $email String with email, Array with email as key, name as value or email as value (without name)
* @param string $name
* @return CakeEmail $this
*/
public function addCc($email, $name = null) {
return $this->_addEmail('_cc', $email, $name);
}
/**
* Bcc
*
* @param mixed $email String with email, Array with email as key, name as value or email as value (without name)
* @param string $name
* @return mixed
*/
public function bcc($email = null, $name = null) {
if ($email === null) {
return $this->_bcc;
}
return $this->_setEmail('_bcc', $email, $name);
}
/**
* Add Bcc
*
* @param mixed $email String with email, Array with email as key, name as value or email as value (without name)
* @param string $name
* @return CakeEmail $this
*/
public function addBcc($email, $name = null) {
return $this->_addEmail('_bcc', $email, $name);
}
/**
* Set email
*
* @param string $varName
* @param mixed $email
* @param mixed $name
* @return CakeEmail $this
* @throws SocketException
*/
protected function _setEmail($varName, $email, $name) {
if (!is_array($email)) {
if (!Validation::email($email)) {
throw new SocketException(__d('cake_dev', 'Invalid email: "%s"', $email));
}
if ($name === null) {
$name = $email;
}
$this->{$varName} = array($email => $name);
return $this;
}
$list = array();
foreach ($email as $key => $value) {
if (is_int($key)) {
$key = $value;
}
if (!Validation::email($key)) {
throw new SocketException(__d('cake_dev', 'Invalid email: "%s"', $key));
}
$list[$key] = $value;
}
$this->{$varName} = $list;
return $this;
}
/**
* Set only 1 email
*
* @param string $varName
* @param mixed $email
* @param string $name
* @param string $throwMessage
* @return CakeEmail $this
* @throws SocketException
*/
protected function _setEmailSingle($varName, $email, $name, $throwMessage) {
$current = $this->{$varName};
$this->_setEmail($varName, $email, $name);
if (count($this->{$varName}) !== 1) {
$this->{$varName} = $current;
throw new SocketException($throwMessage);
}
return $this;
}
/**
* Add email
*
* @param string $varName
* @param mixed $email
* @param mixed $name
* @return CakeEmail $this
* @throws SocketException
*/
protected function _addEmail($varName, $email, $name) {
if (!is_array($email)) {
if (!Validation::email($email)) {
throw new SocketException(__d('cake_dev', 'Invalid email: "%s"', $email));
}
if ($name === null) {
$name = $email;
}
$this->{$varName}[$email] = $name;
return $this;
}
$list = array();
foreach ($email as $key => $value) {
if (is_int($key)) {
$key = $value;
}
if (!Validation::email($key)) {
throw new SocketException(__d('cake_dev', 'Invalid email: "%s"', $key));
}
$list[$key] = $value;
}
$this->{$varName} = array_merge($this->{$varName}, $list);
return $this;
}
/**
* Set Subject
*
* @param string $subject
* @return mixed
*/
public function subject($subject = null) {
if ($subject === null) {
return $this->_subject;
}
$this->_subject = $this->_encode((string)$subject);
return $this;
}
/**
* Sets headers for the message
*
* @param array $headers Associative array containing headers to be set.
* @return CakeEmail $this
* @throws SocketException
*/
public function setHeaders($headers) {
if (!is_array($headers)) {
throw new SocketException(__d('cake_dev', '$headers should be an array.'));
}
$this->_headers = $headers;
return $this;
}
/**
* Add header for the message
*
* @param array $headers
* @return object $this
* @throws SocketException
*/
public function addHeaders($headers) {
if (!is_array($headers)) {
throw new SocketException(__d('cake_dev', '$headers should be an array.'));
}
$this->_headers = array_merge($this->_headers, $headers);
return $this;
}
/**
* Get list of headers
*
* ### Includes:
*
* - `from`
* - `replyTo`
* - `readReceipt`
* - `returnPath`
* - `to`
* - `cc`
* - `bcc`
* - `subject`
*
* @param array $include
* @return array
*/
public function getHeaders($include = array()) {
if ($include == array_values($include)) {
$include = array_fill_keys($include, true);
}
$defaults = array_fill_keys(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc', 'subject'), false);
$include += $defaults;
$headers = array();
$relation = array(
'from' => 'From',
'replyTo' => 'Reply-To',
'readReceipt' => 'Disposition-Notification-To',
'returnPath' => 'Return-Path'
);
foreach ($relation as $var => $header) {
if ($include[$var]) {
$var = '_' . $var;
$headers[$header] = current($this->_formatAddress($this->{$var}));
}
}
if ($include['sender']) {
if (key($this->_sender) === key($this->_from)) {
$headers['Sender'] = '';
} else {
$headers['Sender'] = current($this->_formatAddress($this->_sender));
}
}
foreach (array('to', 'cc', 'bcc') as $var) {
if ($include[$var]) {
$classVar = '_' . $var;
$headers[ucfirst($var)] = implode(', ', $this->_formatAddress($this->{$classVar}));
}
}
$headers += $this->_headers;
if (!isset($headers['X-Mailer'])) {
$headers['X-Mailer'] = self::EMAIL_CLIENT;
}
if (!isset($headers['Date'])) {
$headers['Date'] = date(DATE_RFC2822);
}
if ($this->_messageId !== false) {
if ($this->_messageId === true) {
$headers['Message-ID'] = '<' . str_replace('-', '', String::UUID()) . '@' . env('HTTP_HOST') . '>';
} else {
$headers['Message-ID'] = $this->_messageId;
}
}
if ($include['subject']) {
$headers['Subject'] = $this->_subject;
}
$headers['MIME-Version'] = '1.0';
if (!empty($this->_attachments)) {
$headers['Content-Type'] = 'multipart/mixed; boundary="' . $this->_boundary . '"';
} elseif ($this->_emailFormat === 'text') {
$headers['Content-Type'] = 'text/plain; charset=' . $this->charset;
} elseif ($this->_emailFormat === 'html') {
$headers['Content-Type'] = 'text/html; charset=' . $this->charset;
} elseif ($this->_emailFormat === 'both') {
$headers['Content-Type'] = 'multipart/alternative; boundary="alt-' . $this->_boundary . '"';
}
$headers['Content-Transfer-Encoding'] = '7bit';
return $headers;
}
/**
* Format addresses
*
* @param array $address
* @return array
*/
protected function _formatAddress($address) {
$return = array();
foreach ($address as $email => $alias) {
if ($email === $alias) {
$return[] = $email;
} else {
$return[] = sprintf('%s <%s>', $this->_encode($alias), $email);
}
}
return $return;
}
/**
* Template and layout
*
* @param mixed $template Template name or null to not use
* @param mixed $layout Layout name or null to not use
* @return mixed
*/
public function template($template = false, $layout = false) {
if ($template === false) {
return array(
'template' => $this->_template,
'layout' => $this->_layout
);
}
$this->_template = $template;
if ($layout !== false) {
$this->_layout = $layout;
}
return $this;
}
/**
* View class for render
*
* @param string $viewClass
* @return mixed
*/
public function viewRender($viewClass = null) {
if ($viewClass === null) {
return $this->_viewRender;
}
$this->_viewRender = $viewClass;
return $this;
}
/**
* Variables to be set on render
*
* @param array $viewVars
* @return mixed
*/
public function viewVars($viewVars = null) {
if ($viewVars === null) {
return $this->_viewVars;
}
$this->_viewVars = array_merge($this->_viewVars, (array)$viewVars);
return $this;
}
/**
* Helpers to be used in render
*
* @param array $helpers
* @return mixed
*/
public function helpers($helpers = null) {
if ($helpers === null) {
return $this->_helpers;
}
$this->_helpers = (array)$helpers;
return $this;
}
/**
* Email format
*
* @param string $format
* @return mixed
* @throws SocketException
*/
public function emailFormat($format = null) {
if ($format === null) {
return $this->_emailFormat;
}
if (!in_array($format, $this->_emailFormatAvailable)) {
throw new SocketException(__d('cake_dev', 'Format not available.'));
}
$this->_emailFormat = $format;
return $this;
}
/**
* Transport name
*
* @param string $name
* @return mixed
*/
public function transport($name = null) {
if ($name === null) {
return $this->_transportName;
}
$this->_transportName = (string)$name;
$this->_transportClass = null;
return $this;
}
/**
* Return the transport class
*
* @return CakeEmail
* @throws SocketException
*/
public function transportClass() {
if ($this->_transportClass) {
return $this->_transportClass;
}
list($plugin, $transportClassname) = pluginSplit($this->_transportName, true);
$transportClassname .= 'Transport';
App::uses($transportClassname, $plugin . 'Network/Email');
if (!class_exists($transportClassname)) {
throw new SocketException(__d('cake_dev', 'Class "%s" not found.', $transportClassname));
} elseif (!method_exists($transportClassname, 'send')) {
throw new SocketException(__d('cake_dev', 'The "%s" do not have send method.', $transportClassname));
}
return $this->_transportClass = new $transportClassname();
}
/**
* Message-ID
*
* @param mixed $message True to generate a new Message-ID, False to ignore (not send in email), String to set as Message-ID
* @return mixed
* @throws SocketException
*/
public function messageId($message = null) {
if ($message === null) {
return $this->_messageId;
}
if (is_bool($message)) {
$this->_messageId = $message;
} else {
if (!preg_match('/^\<.+@.+\>$/', $message)) {
throw new SocketException(__d('cake_dev', 'Invalid format to Message-ID. The text should be something like "<uuid@server.com>"'));
}
$this->_messageId = $message;
}
return $this;
}
/**
* Attachments
*
* @param mixed $attachments String with the filename or array with filenames
* @return mixed
* @throws SocketException
*/
public function attachments($attachments = null) {
if ($attachments === null) {
return $this->_attachments;
}
$attach = array();
foreach ((array)$attachments as $name => $fileInfo) {
if (!is_array($fileInfo)) {
$fileInfo = array('file' => $fileInfo);
}
if (!isset($fileInfo['file'])) {
throw new SocketException(__d('cake_dev', 'File not specified.'));
}
$fileInfo['file'] = realpath($fileInfo['file']);
if ($fileInfo['file'] === false || !file_exists($fileInfo['file'])) {
throw new SocketException(__d('cake_dev', 'File not found: "%s"', $fileInfo['file']));
}
if (is_int($name)) {
$name = basename($fileInfo['file']);
}
if (!isset($fileInfo['mimetype'])) {
$fileInfo['mimetype'] = 'application/octet-stream';
}
$attach[$name] = $fileInfo;
}
$this->_attachments = $attach;
return $this;
}
/**
* Add attachments
*
* @param mixed $attachments String with the filename or array with filenames
* @return CakeEmail $this
* @throws SocketException
*/
public function addAttachments($attachments) {
$current = $this->_attachments;
$this->attachments($attachments);
$this->_attachments = array_merge($current, $this->_attachments);
return $this;
}
/**
* Get generated message (used by transport classes)
*
* @param mixed $type Use MESSAGE_* constants or null to return the full message as array
* @return mixed String if have type, array if type is null
*/
public function message($type = null) {
switch ($type) {
case self::MESSAGE_HTML:
return $this->_htmlMessage;
case self::MESSAGE_TEXT:
return $this->_textMessage;
}
return $this->_message;
}
/**
* Configuration to use when send email
*
* @param mixed $config String with configuration name (from email.php), array with config or null to return current config
* @return mixed
*/
public function config($config = null) {
if ($config === null) {
return $this->_config;
}
if (!is_array($config)) {
$config = (string)$config;
}
$this->_applyConfig($config);
return $this;
}
/**
* Send an email using the specified content, template and layout
*
* @return array
* @throws SocketException
*/
public function send($content = null) {
if (empty($this->_from)) {
throw new SocketException(__d('cake_dev', 'From is not specified.'));
}
if (empty($this->_to) && empty($this->_cc) && empty($this->_bcc)) {
throw new SocketException(__d('cake_dev', 'You need specify one destination on to, cc or bcc.'));
}
if (is_array($content)) {
$content = implode("\n", $content) . "\n";
}
$this->_textMessage = $this->_htmlMessage = '';
if ($content !== null) {
if ($this->_emailFormat === 'text') {
$this->_textMessage = $content;
} elseif ($this->_emailFormat === 'html') {
$this->_htmlMessage = $content;
} elseif ($this->_emailFormat === 'both') {
$this->_textMessage = $this->_htmlMessage = $content;
}
}
$this->_createBoundary();
$message = $this->_wrap($content);
if (empty($this->_template)) {
$message = $this->_formatMessage($message);
} else {
$message = $this->_render($message);
}
$message[] = '';
$this->_message = $message;
if (!empty($this->_attachments)) {
$this->_attachFiles();
$this->_message[] = '';
$this->_message[] = '--' . $this->_boundary . '--';
$this->_message[] = '';
}
$contents = $this->transportClass()->send($this);
if (!empty($this->_config['log'])) {
$level = LOG_DEBUG;
if ($this->_config['log'] !== true) {
$level = $this->_config['log'];
}
CakeLog::write($level, PHP_EOL . $contents['headers'] . PHP_EOL . $contents['message']);
}
return $contents;
}
/**
* Static method to fast create an instance of CakeEmail
*
* @param mixed $to Address to send (see CakeEmail::to()). If null, will try to use 'to' from transport config
* @param mixed $subject String of subject or null to use 'subject' from transport config
* @param mixed $message String with message or array with variables to be used in render
* @param mixed $transportConfig String to use config from EmailConfig or array with configs
* @param boolean $send Send the email or just return the instance pre-configured
* @return CakeEmail Instance of CakeEmail
* @throws SocketException
*/
public static function deliver($to = null, $subject = null, $message = null, $transportConfig = 'fast', $send = true) {
$class = __CLASS__;
$instance = new $class($transportConfig);
if ($to !== null) {
$instance->to($to);
}
if ($subject !== null) {
$instance->subject($subject);
}
if (is_array($message)) {
$instance->viewVars($message);
$message = null;
} elseif ($message === null && array_key_exists('message', $config = $instance->config())) {
$message = $config['message'];
}
if ($send === true) {
$instance->send($message);
}
return $instance;
}
/**
* Apply the config to an instance
*
* @param CakeEmail $obj CakeEmail
* @param array $config
* @return void
*/
protected function _applyConfig($config) {
if (is_string($config)) {
if (!class_exists('EmailConfig') && !config('email')) {
throw new ConfigureException(__d('cake_dev', '%s not found.', APP . 'Config' . DS . 'email.php'));
}
$configs = new EmailConfig();
if (!isset($configs->{$config})) {
throw new ConfigureException(__d('cake_dev', 'Unknown email configuration "%s".', $config));
}
$config = $configs->{$config};
}
$this->_config += $config;
if (!empty($config['charset'])) {
$this->charset = $config['charset'];
}
if (!empty($config['headerCharset'])) {
$this->headerCharset = $config['headerCharset'];
}
if (empty($this->headerCharset)) {
$this->headerCharset = $this->charset;
}
$simpleMethods = array(
'from', 'sender', 'to', 'replyTo', 'readReceipt', 'returnPath', 'cc', 'bcc',
'messageId', 'subject', 'viewRender', 'viewVars', 'attachments',
'transport', 'emailFormat'
);
foreach ($simpleMethods as $method) {
if (isset($config[$method])) {
$this->$method($config[$method]);
unset($config[$method]);
}
}
if (isset($config['headers'])) {
$this->setHeaders($config['headers']);
unset($config['headers']);
}
if (array_key_exists('template', $config)) {
$layout = false;
if (array_key_exists('layout', $config)) {
$layout = $config['layout'];
unset($config['layout']);
}
$this->template($config['template'], $layout);
unset($config['template']);
}
$this->transportClass()->config($config);
}
/**
* Reset all EmailComponent internal variables to be able to send out a new email.
*
* @return CakeEmail $this
*/
public function reset() {
$this->_to = array();
$this->_from = array();
$this->_sender = array();
$this->_replyTo = array();
$this->_readReceipt = array();
$this->_returnPath = array();
$this->_cc = array();
$this->_bcc = array();
$this->_messageId = true;
$this->_subject = '';
$this->_headers = array();
$this->_layout = 'default';
$this->_template = '';
$this->_viewRender = 'View';
$this->_viewVars = array();
$this->_helpers = array('Html');
$this->_textMessage = '';
$this->_htmlMessage = '';
$this->_message = '';
$this->_emailFormat = 'text';
$this->_transportName = 'Mail';
$this->_transportClass = null;
$this->_attachments = array();
$this->_config = array();
return $this;
}
/**
* Encode the specified string using the current charset
*
* @param string $text String to encode
* @return string Encoded string
*/
protected function _encode($text) {
$internalEncoding = function_exists('mb_internal_encoding');
if ($internalEncoding) {
$restore = mb_internal_encoding();
mb_internal_encoding($this->_appCharset);
}
$text = $this->_encodeString($text, $this->headerCharset);
$return = mb_encode_mimeheader($text, $this->headerCharset, 'B');
if ($internalEncoding) {
mb_internal_encoding($restore);
}
return $return;
}
/**
* Translates a string for one charset to another if the App.encoding value
* differs and the mb_convert_encoding function exists
*
* @param string $text The text to be converted
* @param string $charset the target encoding
* @return string
*/
protected function _encodeString($text, $charset) {
if ($this->_appCharset === $charset || !function_exists('mb_convert_encoding')) {
return $text;
}
return mb_convert_encoding($text, $charset, $this->_appCharset);
}
/**
* Wrap the message to follow the RFC 2822 - 2.1.1
*
* @param string $message Message to wrap
* @return array Wrapped message
*/
protected function _wrap($message) {
$message = str_replace(array("\r\n", "\r"), "\n", $message);
$lines = explode("\n", $message);
$formatted = array();
foreach ($lines as $line) {
if (empty($line)) {
$formatted[] = '';
continue;
}
if ($line[0] === '.') {
$line = '.' . $line;
}
if (!preg_match('/\<[a-z]/i', $line)) {
$formatted = array_merge($formatted, explode("\n", wordwrap($line, self::LINE_LENGTH_SHOULD, "\n")));
continue;
}
$tagOpen = false;
$tmpLine = $tag = '';
$tmpLineLength = 0;
for ($i = 0, $count = strlen($line); $i < $count; $i++) {
$char = $line[$i];
if ($tagOpen) {
$tag .= $char;
if ($char === '>') {
$tagLength = strlen($tag);
if ($tagLength + $tmpLineLength < self::LINE_LENGTH_SHOULD) {
$tmpLine .= $tag;
$tmpLineLength += $tagLength;
} else {
if ($tmpLineLength > 0) {
$formatted[] = trim($tmpLine);
$tmpLine = '';
$tmpLineLength = 0;
}
if ($tagLength > self::LINE_LENGTH_SHOULD) {
$formatted[] = $tag;
} else {
$tmpLine = $tag;
$tmpLineLength = $tagLength;
}
}
$tag = '';
$tagOpen = false;
}
continue;
}
if ($char === '<') {
$tagOpen = true;
$tag = '<';
continue;
}
if ($char === ' ' && $tmpLineLength >= self::LINE_LENGTH_SHOULD) {
$formatted[] = $tmpLine;
$tmpLineLength = 0;
continue;
}
$tmpLine .= $char;
$tmpLineLength++;
if ($tmpLineLength === self::LINE_LENGTH_SHOULD) {
$nextChar = $line[$i + 1];
if ($nextChar === ' ' || $nextChar === '<') {
$formatted[] = trim($tmpLine);
$tmpLine = '';
$tmpLineLength = 0;
if ($nextChar === ' ') {
$i++;
}
} else {
$lastSpace = strrpos($tmpLine, ' ');
if ($lastSpace === false) {
continue;
}
$formatted[] = trim(substr($tmpLine, 0, $lastSpace));
$tmpLine = substr($tmpLine, $lastSpace + 1);
$tmpLineLength = strlen($tmpLine);
}
}
}
if (!empty($tmpLine)) {
$formatted[] = $tmpLine;
}
}
$formatted[] = '';
return $formatted;
}
/**
* Create unique boundary identifier
*
* @return void
*/
protected function _createBoundary() {
if (!empty($this->_attachments) || $this->_emailFormat === 'both') {
$this->_boundary = md5(uniqid(time()));
}
}
/**
* Attach files by adding file contents inside boundaries.
*
* @return void
*/
protected function _attachFiles() {
foreach ($this->_attachments as $filename => $fileInfo) {
$handle = fopen($fileInfo['file'], 'rb');
$data = fread($handle, filesize($fileInfo['file']));
$data = chunk_split(base64_encode($data)) ;
fclose($handle);
$this->_message[] = '--' . $this->_boundary;
$this->_message[] = 'Content-Type: ' . $fileInfo['mimetype'];
$this->_message[] = 'Content-Transfer-Encoding: base64';
if (empty($fileInfo['contentId'])) {
$this->_message[] = 'Content-Disposition: attachment; filename="' . $filename . '"';
} else {
$this->_message[] = 'Content-ID: <' . $fileInfo['contentId'] . '>';
$this->_message[] = 'Content-Disposition: inline; filename="' . $filename . '"';
}
$this->_message[] = '';
$this->_message[] = $data;
$this->_message[] = '';
}
}
/**
* Format the message by seeing if it has attachments.
*
* @param array $message Message to format
* @return array
*/
protected function _formatMessage($message) {
if (!empty($this->_attachments)) {
$prefix = array('--' . $this->_boundary);
if ($this->_emailFormat === 'text') {
$prefix[] = 'Content-Type: text/plain; charset=' . $this->charset;
} elseif ($this->_emailFormat === 'html') {
$prefix[] = 'Content-Type: text/html; charset=' . $this->charset;
} elseif ($this->_emailFormat === 'both') {
$prefix[] = 'Content-Type: multipart/alternative; boundary="alt-' . $this->_boundary . '"';
}
$prefix[] = 'Content-Transfer-Encoding: 7bit';
$prefix[] = '';
$message = array_merge($prefix, $message);
}
return $message;
}
/**
* Render the contents using the current layout and template.
*
* @param string $content Content to render
* @return array Email ready to be sent
*/
protected function _render($content) {
$viewClass = $this->_viewRender;
if ($viewClass !== 'View') {
list($plugin, $viewClass) = pluginSplit($viewClass, true);
$viewClass .= 'View';
App::uses($viewClass, $plugin . 'View');
}
$View = new $viewClass(null);
$View->viewVars = $this->_viewVars;
$View->helpers = $this->_helpers;
$msg = array();
list($templatePlugin, $template) = pluginSplit($this->_template);
list($layoutPlugin, $layout) = pluginSplit($this->_layout);
if ($templatePlugin) {
$View->plugin = $templatePlugin;
} elseif ($layoutPlugin) {
$View->plugin = $layoutPlugin;
}
$content = implode("\n", $content);
if ($this->_emailFormat === 'both') {
$originalContent = $content;
if (!empty($this->_attachments)) {
$msg[] = '--' . $this->_boundary;
$msg[] = 'Content-Type: multipart/alternative; boundary="alt-' . $this->_boundary . '"';
$msg[] = '';
}
$msg[] = '--alt-' . $this->_boundary;
$msg[] = 'Content-Type: text/plain; charset=' . $this->charset;
$msg[] = 'Content-Transfer-Encoding: 7bit';
$msg[] = '';
$View->viewPath = $View->layoutPath = 'Emails' . DS . 'text';
$View->viewVars['content'] = $originalContent;
$this->_textMessage = str_replace(array("\r\n", "\r"), "\n", $View->render($template, $layout));
$content = explode("\n", $this->_textMessage);
$msg = array_merge($msg, $content);
$msg[] = '';
$msg[] = '--alt-' . $this->_boundary;
$msg[] = 'Content-Type: text/html; charset=' . $this->charset;
$msg[] = 'Content-Transfer-Encoding: 7bit';
$msg[] = '';
$View->viewPath = $View->layoutPath = 'Emails' . DS . 'html';
$View->viewVars['content'] = $originalContent;
$View->hasRendered = false;
$this->_htmlMessage = str_replace(array("\r\n", "\r"), "\n", $View->render($template, $layout));
$content = explode("\n", $this->_htmlMessage);
$msg = array_merge($msg, $content);
$msg[] = '';
$msg[] = '--alt-' . $this->_boundary . '--';
$msg[] = '';
return $msg;
}
if (!empty($this->_attachments)) {
if ($this->_emailFormat === 'html') {
$msg[] = '';
$msg[] = '--' . $this->_boundary;
$msg[] = 'Content-Type: text/html; charset=' . $this->charset;
$msg[] = 'Content-Transfer-Encoding: 7bit';
$msg[] = '';
} else {
$msg[] = '--' . $this->_boundary;
$msg[] = 'Content-Type: text/plain; charset=' . $this->charset;
$msg[] = 'Content-Transfer-Encoding: 7bit';
$msg[] = '';
}
}
$View->viewPath = $View->layoutPath = 'Emails' . DS . $this->_emailFormat;
$View->viewVars['content'] = $content;
$rendered = $this->_encodeString($View->render($template, $layout), $this->charset);
$content = explode("\n", $rendered);
if ($this->_emailFormat === 'html') {
$this->_htmlMessage = $rendered;
} else {
$this->_textMessage = $rendered;
}
return array_merge($msg, $content);
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Network/Email/CakeEmail.php | PHP | gpl3 | 33,823 |
<?php
/**
* Send mail using mail() function
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Network.Email
* @since CakePHP(tm) v 2.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Mail class
*
* @package Cake.Network.Email
*/
class MailTransport extends AbstractTransport {
/**
* Send mail
*
* @param CakeEmail $email CakeEmail
* @return array
*/
public function send(CakeEmail $email) {
$eol = PHP_EOL;
if (isset($this->_config['eol'])) {
$eol = $this->_config['eol'];
}
$headers = $email->getHeaders(array('from', 'sender', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc'));
$to = $headers['To'];
unset($headers['To']);
$headers = $this->_headersToString($headers, $eol);
$message = implode($eol, $email->message());
if (ini_get('safe_mode') || !isset($this->_config['additionalParameters'])) {
if (!@mail($to, $email->subject(), $message, $headers)) {
throw new SocketException(__d('cake_dev', 'Could not send email.'));
}
} elseif (!@mail($to, $email->subject(), $message, $headers, $this->_config['additionalParameters'])) {
throw new SocketException(__d('cake_dev', 'Could not send email.'));
}
return array('headers' => $headers, 'message' => $message);
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Network/Email/MailTransport.php | PHP | gpl3 | 1,695 |
<?php
/**
* ConsoleInputOption file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* An object to represent a single option used in the command line.
* ConsoleOptionParser creates these when you use addOption()
*
* @see ConsoleOptionParser::addOption()
* @package Cake.Console
*/
class ConsoleInputOption {
/**
* Name of the option
*
* @var string
*/
protected $_name;
/**
* Short (1 character) alias for the option.
*
* @var string
*/
protected $_short;
/**
* Help text for the option.
*
* @var string
*/
protected $_help;
/**
* Is the option a boolean option. Boolean options do not consume a parameter.
*
* @var boolean
*/
protected $_boolean;
/**
* Default value for the option
*
* @var mixed
*/
protected $_default;
/**
* An array of choices for the option.
*
* @var array
*/
protected $_choices;
/**
* Make a new Input Option
*
* @param mixed $name The long name of the option, or an array with all the properties.
* @param string $short The short alias for this option
* @param string $help The help text for this option
* @param boolean $boolean Whether this option is a boolean option. Boolean options don't consume extra tokens
* @param string $default The default value for this option.
* @param array $choices Valid choices for this option.
* @throws ConsoleException
*/
public function __construct($name, $short = null, $help = '', $boolean = false, $default = '', $choices = array()) {
if (is_array($name) && isset($name['name'])) {
foreach ($name as $key => $value) {
$this->{'_' . $key} = $value;
}
} else {
$this->_name = $name;
$this->_short = $short;
$this->_help = $help;
$this->_boolean = $boolean;
$this->_default = $default;
$this->_choices = $choices;
}
if (strlen($this->_short) > 1) {
throw new ConsoleException(
__d('cake_console', 'Short options must be one letter.')
);
}
}
/**
* Get the value of the name attribute.
*
* @return string Value of this->_name.
*/
public function name() {
return $this->_name;
}
/**
* Get the value of the short attribute.
*
* @return string Value of this->_short.
*/
public function short() {
return $this->_short;
}
/**
* Generate the help for this this option.
*
* @param integer $width The width to make the name of the option.
* @return string
*/
public function help($width = 0) {
$default = $short = '';
if (!empty($this->_default) && $this->_default !== true) {
$default = __d('cake_console', ' <comment>(default: %s)</comment>', $this->_default);
}
if (!empty($this->_choices)) {
$default .= __d('cake_console', ' <comment>(choices: %s)</comment>', implode('|', $this->_choices));
}
if (!empty($this->_short)) {
$short = ', -' . $this->_short;
}
$name = sprintf('--%s%s', $this->_name, $short);
if (strlen($name) < $width) {
$name = str_pad($name, $width, ' ');
}
return sprintf('%s%s%s', $name, $this->_help, $default);
}
/**
* Get the usage value for this option
*
* @return string
*/
public function usage() {
$name = empty($this->_short) ? '--' . $this->_name : '-' . $this->_short;
$default = '';
if (!empty($this->_default) && $this->_default !== true) {
$default = ' ' . $this->_default;
}
if (!empty($this->_choices)) {
$default = ' ' . implode('|', $this->_choices);
}
return sprintf('[%s%s]', $name, $default);
}
/**
* Get the default value for this option
*
* @return mixed
*/
public function defaultValue() {
return $this->_default;
}
/**
* Check if this option is a boolean option
*
* @return boolean
*/
public function isBoolean() {
return (bool) $this->_boolean;
}
/**
* Check that a value is a valid choice for this option.
*
* @param string $value
* @return boolean
* @throws ConsoleException
*/
public function validChoice($value) {
if (empty($this->_choices)) {
return true;
}
if (!in_array($value, $this->_choices)) {
throw new ConsoleException(
__d('cake_console', '"%s" is not a valid value for --%s. Please use one of "%s"',
$value, $this->_name, implode(', ', $this->_choices)
));
}
return true;
}
/**
* Append the option's xml into the parent.
*
* @param SimpleXmlElement $parent The parent element.
* @return SimpleXmlElement The parent with this option appended.
*/
public function xml(SimpleXmlElement $parent) {
$option = $parent->addChild('option');
$option->addAttribute('name', '--' . $this->_name);
$short = '';
if (strlen($this->_short)) {
$short = $this->_short;
}
$option->addAttribute('short', '-' . $short);
$option->addAttribute('boolean', $this->_boolean);
$option->addChild('default', $this->_default);
$choices = $option->addChild('choices');
foreach ($this->_choices as $valid) {
$choices->addChild('choice', $valid);
}
return $parent;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/ConsoleInputOption.php | PHP | gpl3 | 5,349 |
<?php
/**
* ConsoleInputSubcommand file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* An object to represent a single subcommand used in the command line.
* Created when you call ConsoleOptionParser::addSubcommand()
*
* @see ConsoleOptionParser::addSubcommand()
* @package Cake.Console
*/
class ConsoleInputSubcommand {
/**
* Name of the subcommand
*
* @var string
*/
protected $_name;
/**
* Help string for the subcommand
*
* @var string
*/
protected $_help;
/**
* The ConsoleOptionParser for this subcommand.
*
* @var ConsoleOptionParser
*/
protected $_parser;
/**
* Make a new Subcommand
*
* @param mixed $name The long name of the subcommand, or an array with all the properties.
* @param string $help The help text for this option
* @param mixed $parser A parser for this subcommand. Either a ConsoleOptionParser, or an array that can be
* used with ConsoleOptionParser::buildFromArray()
*/
public function __construct($name, $help = '', $parser = null) {
if (is_array($name) && isset($name['name'])) {
foreach ($name as $key => $value) {
$this->{'_' . $key} = $value;
}
} else {
$this->_name = $name;
$this->_help = $help;
$this->_parser = $parser;
}
if (is_array($this->_parser)) {
$this->_parser['command'] = $this->_name;
$this->_parser = ConsoleOptionParser::buildFromArray($this->_parser);
}
}
/**
* Get the value of the name attribute.
*
* @return string Value of this->_name.
*/
public function name() {
return $this->_name;
}
/**
* Generate the help for this this subcommand.
*
* @param integer $width The width to make the name of the subcommand.
* @return string
*/
public function help($width = 0) {
$name = $this->_name;
if (strlen($name) < $width) {
$name = str_pad($name, $width, ' ');
}
return $name . $this->_help;
}
/**
* Get the usage value for this option
*
* @return mixed Either false or a ConsoleOptionParser
*/
public function parser() {
if ($this->_parser instanceof ConsoleOptionParser) {
return $this->_parser;
}
return false;
}
/**
* Append this subcommand to the Parent element
*
* @param SimpleXmlElement $parent The parent element.
* @return SimpleXmlElement The parent with this subcommand appended.
*/
public function xml(SimpleXmlElement $parent) {
$command = $parent->addChild('command');
$command->addAttribute('name', $this->_name);
$command->addAttribute('help', $this->_help);
return $parent;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/ConsoleInputSubcommand.php | PHP | gpl3 | 2,990 |
<?php
/**
* Acl Shell provides Acl access in the CLI environment
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2.0.5012
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('ComponentCollection', 'Controller');
App::uses('AclComponent', 'Controller/Component');
App::uses('DbAcl', 'Model');
/**
* Shell for ACL management. This console is known to have issues with zend.ze1_compatibility_mode
* being enabled. Be sure to turn it off when using this shell.
*
* @package Cake.Console.Command
*/
class AclShell extends Shell {
/**
* Contains instance of AclComponent
*
* @var AclComponent
*/
public $Acl;
/**
* Contains arguments parsed from the command line.
*
* @var array
*/
public $args;
/**
* Contains database source to use
*
* @var string
*/
public $connection = 'default';
/**
* Contains tasks to load and instantiate
*
* @var array
*/
public $tasks = array('DbConfig');
/**
* Override startup of the Shell
*
* @return void
*/
public function startup() {
parent::startup();
if (isset($this->params['connection'])) {
$this->connection = $this->params['connection'];
}
if (!in_array(Configure::read('Acl.classname'), array('DbAcl', 'DB_ACL'))) {
$out = "--------------------------------------------------\n";
$out .= __d('cake_console', 'Error: Your current Cake configuration is set to an ACL implementation other than DB.') . "\n";
$out .= __d('cake_console', 'Please change your core config to reflect your decision to use DbAcl before attempting to use this script') . "\n";
$out .= "--------------------------------------------------\n";
$out .= __d('cake_console', 'Current ACL Classname: %s', Configure::read('Acl.classname')) . "\n";
$out .= "--------------------------------------------------\n";
$this->err($out);
$this->_stop();
}
if ($this->command) {
if (!config('database')) {
$this->out(__d('cake_console', 'Your database configuration was not found. Take a moment to create one.'), true);
$this->args = null;
return $this->DbConfig->execute();
}
require_once (APP . 'Config' . DS . 'database.php');
if (!in_array($this->command, array('initdb'))) {
$collection = new ComponentCollection();
$this->Acl = new AclComponent($collection);
$controller = null;
$this->Acl->startup($controller);
}
}
}
/**
* Override main() for help message hook
*
* @return void
*/
public function main() {
$this->out($this->OptionParser->help());
}
/**
* Creates an ARO/ACO node
*
* @return void
*/
public function create() {
extract($this->_dataVars());
$class = ucfirst($this->args[0]);
$parent = $this->parseIdentifier($this->args[1]);
if (!empty($parent) && $parent != '/' && $parent != 'root') {
$parent = $this->_getNodeId($class, $parent);
} else {
$parent = null;
}
$data = $this->parseIdentifier($this->args[2]);
if (is_string($data) && $data != '/') {
$data = array('alias' => $data);
} elseif (is_string($data)) {
$this->error(__d('cake_console', '/ can not be used as an alias!') . __d('cake_console', " / is the root, please supply a sub alias"));
}
$data['parent_id'] = $parent;
$this->Acl->{$class}->create();
if ($this->Acl->{$class}->save($data)) {
$this->out(__d('cake_console', "<success>New %s</success> '%s' created.", $class, $this->args[2]), 2);
} else {
$this->err(__d('cake_console', "There was a problem creating a new %s '%s'.", $class, $this->args[2]));
}
}
/**
* Delete an ARO/ACO node.
*
* @return void
*/
public function delete() {
extract($this->_dataVars());
$identifier = $this->parseIdentifier($this->args[1]);
$nodeId = $this->_getNodeId($class, $identifier);
if (!$this->Acl->{$class}->delete($nodeId)) {
$this->error(__d('cake_console', 'Node Not Deleted') . __d('cake_console', 'There was an error deleting the %s. Check that the node exists.', $class) . "\n");
}
$this->out(__d('cake_console', '<success>%s deleted.</success>', $class), 2);
}
/**
* Set parent for an ARO/ACO node.
*
* @return void
*/
public function setParent() {
extract($this->_dataVars());
$target = $this->parseIdentifier($this->args[1]);
$parent = $this->parseIdentifier($this->args[2]);
$data = array(
$class => array(
'id' => $this->_getNodeId($class, $target),
'parent_id' => $this->_getNodeId($class, $parent)
)
);
$this->Acl->{$class}->create();
if (!$this->Acl->{$class}->save($data)) {
$this->out(__d('cake_console', 'Error in setting new parent. Please make sure the parent node exists, and is not a descendant of the node specified.'), true);
} else {
$this->out(__d('cake_console', 'Node parent set to %s', $this->args[2]) . "\n", true);
}
}
/**
* Get path to specified ARO/ACO node.
*
* @return void
*/
public function getPath() {
extract($this->_dataVars());
$identifier = $this->parseIdentifier($this->args[1]);
$id = $this->_getNodeId($class, $identifier);
$nodes = $this->Acl->{$class}->getPath($id);
if (empty($nodes)) {
$this->error(
__d('cake_console', "Supplied Node '%s' not found", $this->args[1]),
__d('cake_console', 'No tree returned.')
);
}
$this->out(__d('cake_console', 'Path:'));
$this->hr();
for ($i = 0; $i < count($nodes); $i++) {
$this->_outputNode($class, $nodes[$i], $i);
}
}
/**
* Outputs a single node, Either using the alias or Model.key
*
* @param string $class Class name that is being used.
* @param array $node Array of node information.
* @param integer $indent indent level.
* @return void
*/
protected function _outputNode($class, $node, $indent) {
$indent = str_repeat(' ', $indent);
$data = $node[$class];
if ($data['alias']) {
$this->out($indent . "[" . $data['id'] . "] " . $data['alias']);
} else {
$this->out($indent . "[" . $data['id'] . "] " . $data['model'] . '.' . $data['foreign_key']);
}
}
/**
* Check permission for a given ARO to a given ACO.
*
* @return void
*/
public function check() {
extract($this->_getParams());
if ($this->Acl->check($aro, $aco, $action)) {
$this->out(__d('cake_console', '%s is <success>allowed</success>.', $aroName), true);
} else {
$this->out(__d('cake_console', '%s is <error>not allowed</error>.', $aroName), true);
}
}
/**
* Grant permission for a given ARO to a given ACO.
*
* @return void
*/
public function grant() {
extract($this->_getParams());
if ($this->Acl->allow($aro, $aco, $action)) {
$this->out(__d('cake_console', 'Permission <success>granted</success>.'), true);
} else {
$this->out(__d('cake_console', 'Permission was <error>not granted</error>.'), true);
}
}
/**
* Deny access for an ARO to an ACO.
*
* @return void
*/
public function deny() {
extract($this->_getParams());
if ($this->Acl->deny($aro, $aco, $action)) {
$this->out(__d('cake_console', 'Permission denied.'), true);
} else {
$this->out(__d('cake_console', 'Permission was not denied.'), true);
}
}
/**
* Set an ARO to inherit permission to an ACO.
*
* @return void
*/
public function inherit() {
extract($this->_getParams());
if ($this->Acl->inherit($aro, $aco, $action)) {
$this->out(__d('cake_console', 'Permission inherited.'), true);
} else {
$this->out(__d('cake_console', 'Permission was not inherited.'), true);
}
}
/**
* Show a specific ARO/ACO node.
*
* @return void
*/
public function view() {
extract($this->_dataVars());
if (isset($this->args[1])) {
$identity = $this->parseIdentifier($this->args[1]);
$topNode = $this->Acl->{$class}->find('first', array(
'conditions' => array($class . '.id' => $this->_getNodeId($class, $identity))
));
$nodes = $this->Acl->{$class}->find('all', array(
'conditions' => array(
$class . '.lft >=' => $topNode[$class]['lft'],
$class . '.lft <=' => $topNode[$class]['rght']
),
'order' => $class . '.lft ASC'
));
} else {
$nodes = $this->Acl->{$class}->find('all', array('order' => $class . '.lft ASC'));
}
if (empty($nodes)) {
if (isset($this->args[1])) {
$this->error(__d('cake_console', '%s not found', $this->args[1]), __d('cake_console', 'No tree returned.'));
} elseif (isset($this->args[0])) {
$this->error(__d('cake_console', '%s not found', $this->args[0]), __d('cake_console', 'No tree returned.'));
}
}
$this->out($class . ' tree:');
$this->hr();
$stack = array();
$last = null;
foreach ($nodes as $n) {
$stack[] = $n;
if (!empty($last)) {
$end = end($stack);
if ($end[$class]['rght'] > $last) {
foreach ($stack as $k => $v) {
$end = end($stack);
if ($v[$class]['rght'] < $end[$class]['rght']) {
unset($stack[$k]);
}
}
}
}
$last = $n[$class]['rght'];
$count = count($stack);
$this->_outputNode($class, $n, $count);
}
$this->hr();
}
/**
* Initialize ACL database.
*
* @return mixed
*/
public function initdb() {
return $this->dispatchShell('schema create DbAcl');
}
/**
* Get the option parser.
*
* @return void
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
$type = array(
'choices' => array('aro', 'aco'),
'required' => true,
'help' => __d('cake_console', 'Type of node to create.')
);
$parser->description(__d('cake_console', 'A console tool for managing the DbAcl'))
->addSubcommand('create', array(
'help' => __d('cake_console', 'Create a new ACL node'),
'parser' => array(
'description' => __d('cake_console', 'Creates a new ACL object <node> under the parent'),
'arguments' => array(
'type' => $type,
'parent' => array(
'help' => __d('cake_console', 'The node selector for the parent.'),
'required' => true
),
'alias' => array(
'help' => __d('cake_console', 'The alias to use for the newly created node.'),
'required' => true
)
)
)
))->addSubcommand('delete', array(
'help' => __d('cake_console', 'Deletes the ACL object with the given <node> reference'),
'parser' => array(
'description' => __d('cake_console', 'Delete an ACL node.'),
'arguments' => array(
'type' => $type,
'node' => array(
'help' => __d('cake_console', 'The node identifier to delete.'),
'required' => true,
)
)
)
))->addSubcommand('setparent', array(
'help' => __d('cake_console', 'Moves the ACL node under a new parent.'),
'parser' => array(
'description' => __d('cake_console', 'Moves the ACL object specified by <node> beneath <parent>'),
'arguments' => array(
'type' => $type,
'node' => array(
'help' => __d('cake_console', 'The node to move'),
'required' => true,
),
'parent' => array(
'help' => __d('cake_console', 'The new parent for <node>.'),
'required' => true
)
)
)
))->addSubcommand('getpath', array(
'help' => __d('cake_console', 'Print out the path to an ACL node.'),
'parser' => array(
'description' => array(
__d('cake_console', "Returns the path to the ACL object specified by <node>."),
__d('cake_console', "This command is useful in determining the inheritance of permissions for a certain object in the tree.")
),
'arguments' => array(
'type' => $type,
'node' => array(
'help' => __d('cake_console', 'The node to get the path of'),
'required' => true,
)
)
)
))->addSubcommand('check', array(
'help' => __d('cake_console', 'Check the permissions between an ACO and ARO.'),
'parser' => array(
'description' => array(
__d('cake_console', 'Use this command to check ACL permissions.')
),
'arguments' => array(
'aro' => array('help' => __d('cake_console', 'ARO to check.'), 'required' => true),
'aco' => array('help' => __d('cake_console', 'ACO to check.'), 'required' => true),
'action' => array('help' => __d('cake_console', 'Action to check'), 'default' => 'all')
)
)
))->addSubcommand('grant', array(
'help' => __d('cake_console', 'Grant an ARO permissions to an ACO.'),
'parser' => array(
'description' => array(
__d('cake_console', 'Use this command to grant ACL permissions. Once executed, the ARO specified (and its children, if any) will have ALLOW access to the specified ACO action (and the ACO\'s children, if any).')
),
'arguments' => array(
'aro' => array('help' => __d('cake_console', 'ARO to grant permission to.'), 'required' => true),
'aco' => array('help' => __d('cake_console', 'ACO to grant access to.'), 'required' => true),
'action' => array('help' => __d('cake_console', 'Action to grant'), 'default' => 'all')
)
)
))->addSubcommand('deny', array(
'help' => __d('cake_console', 'Deny an ARO permissions to an ACO.'),
'parser' => array(
'description' => array(
__d('cake_console', 'Use this command to deny ACL permissions. Once executed, the ARO specified (and its children, if any) will have DENY access to the specified ACO action (and the ACO\'s children, if any).')
),
'arguments' => array(
'aro' => array('help' => __d('cake_console', 'ARO to deny.'), 'required' => true),
'aco' => array('help' => __d('cake_console', 'ACO to deny.'), 'required' => true),
'action' => array('help' => __d('cake_console', 'Action to deny'), 'default' => 'all')
)
)
))->addSubcommand('inherit', array(
'help' => __d('cake_console', 'Inherit an ARO\'s parent permissions.'),
'parser' => array(
'description' => array(
__d('cake_console', "Use this command to force a child ARO object to inherit its permissions settings from its parent.")
),
'arguments' => array(
'aro' => array('help' => __d('cake_console', 'ARO to have permissions inherit.'), 'required' => true),
'aco' => array('help' => __d('cake_console', 'ACO to inherit permissions on.'), 'required' => true),
'action' => array('help' => __d('cake_console', 'Action to inherit'), 'default' => 'all')
)
)
))->addSubcommand('view', array(
'help' => __d('cake_console', 'View a tree or a single node\'s subtree.'),
'parser' => array(
'description' => array(
__d('cake_console', "The view command will return the ARO or ACO tree."),
__d('cake_console', "The optional node parameter allows you to return"),
__d('cake_console', "only a portion of the requested tree.")
),
'arguments' => array(
'type' => $type,
'node' => array('help' => __d('cake_console', 'The optional node to view the subtree of.'))
)
)
))->addSubcommand('initdb', array(
'help' => __d('cake_console', 'Initialize the DbAcl tables. Uses this command : cake schema run create DbAcl')
))->epilog(
array(
'Node and parent arguments can be in one of the following formats:',
'',
' - <model>.<id> - The node will be bound to a specific record of the given model.',
'',
' - <alias> - The node will be given a string alias (or path, in the case of <parent>)',
" i.e. 'John'. When used with <parent>, this takes the form of an alias path,",
" i.e. <group>/<subgroup>/<parent>.",
'',
"To add a node at the root level, enter 'root' or '/' as the <parent> parameter."
)
);
return $parser;
}
/**
* Checks that given node exists
*
* @return boolean Success
*/
public function nodeExists() {
if (!isset($this->args[0]) || !isset($this->args[1])) {
return false;
}
extract($this->_dataVars($this->args[0]));
$key = is_numeric($this->args[1]) ? $secondary_id : 'alias';
$conditions = array($class . '.' . $key => $this->args[1]);
$possibility = $this->Acl->{$class}->find('all', compact('conditions'));
if (empty($possibility)) {
$this->error(__d('cake_console', '%s not found', $this->args[1]), __d('cake_console', 'No tree returned.'));
}
return $possibility;
}
/**
* Parse an identifier into Model.foreignKey or an alias.
* Takes an identifier determines its type and returns the result as used by other methods.
*
* @param string $identifier Identifier to parse
* @return mixed a string for aliases, and an array for model.foreignKey
*/
public function parseIdentifier($identifier) {
if (preg_match('/^([\w]+)\.(.*)$/', $identifier, $matches)) {
return array(
'model' => $matches[1],
'foreign_key' => $matches[2],
);
}
return $identifier;
}
/**
* Get the node for a given identifier. $identifier can either be a string alias
* or an array of properties to use in AcoNode::node()
*
* @param string $class Class type you want (Aro/Aco)
* @param mixed $identifier A mixed identifier for finding the node.
* @return integer Integer of NodeId. Will trigger an error if nothing is found.
*/
protected function _getNodeId($class, $identifier) {
$node = $this->Acl->{$class}->node($identifier);
if (empty($node)) {
if (is_array($identifier)) {
$identifier = var_export($identifier, true);
}
$this->error(__d('cake_console', 'Could not find node using reference "%s"', $identifier));
}
return Set::extract($node, "0.{$class}.id");
}
/**
* get params for standard Acl methods
*
* @return array aro, aco, action
*/
protected function _getParams() {
$aro = is_numeric($this->args[0]) ? intval($this->args[0]) : $this->args[0];
$aco = is_numeric($this->args[1]) ? intval($this->args[1]) : $this->args[1];
$aroName = $aro;
$acoName = $aco;
if (is_string($aro)) {
$aro = $this->parseIdentifier($aro);
}
if (is_string($aco)) {
$aco = $this->parseIdentifier($aco);
}
$action = null;
if (isset($this->args[2])) {
$action = $this->args[2];
if ($action == '' || $action == 'all') {
$action = '*';
}
}
return compact('aro', 'aco', 'action', 'aroName', 'acoName');
}
/**
* Build data parameters based on node type
*
* @param string $type Node type (ARO/ACO)
* @return array Variables
*/
protected function _dataVars($type = null) {
if ($type == null) {
$type = $this->args[0];
}
$vars = array();
$class = ucwords($type);
$vars['secondary_id'] = (strtolower($class) == 'aro') ? 'foreign_key' : 'object_id';
$vars['data_name'] = $type;
$vars['table_name'] = $type . 's';
$vars['class'] = $class;
return $vars;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/AclShell.php | PHP | gpl3 | 18,816 |
<?php
/**
* Test Suite Shell
*
* This Shell allows the running of test suites via the cake command line
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @since CakePHP(tm) v 1.2.0.4433
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Shell', 'Console');
App::uses('CakeTestSuiteDispatcher', 'TestSuite');
App::uses('CakeTestSuiteCommand', 'TestSuite');
App::uses('CakeTestLoader', 'TestSuite');
/**
* Provides a CakePHP wrapper around PHPUnit.
* Adds in CakePHP's fixtures and gives access to plugin, app and core test cases
*
* @package Cake.Console.Command
*/
class TestsuiteShell extends Shell {
/**
* Dispatcher object for the run.
*
* @var CakeTestDispatcher
*/
protected $_dispatcher = null;
/**
* get the option parser for the test suite.
*
* @return void
*/
public function getOptionParser() {
$parser = new ConsoleOptionParser($this->name);
$parser->description(array(
__d('cake_console', 'The CakePHP Testsuite allows you to run test cases from the command line'),
__d('cake_console', 'If run with no command line arguments, a list of available core test cases will be shown')
))->addArgument('category', array(
'help' => __d('cake_console', 'app, core or name of a plugin.'),
'required' => true
))->addArgument('file', array(
'help' => __d('cake_console', 'file name with folder prefix and without the test.php suffix.'),
'required' => false,
))->addOption('log-junit', array(
'help' => __d('cake_console', '<file> Log test execution in JUnit XML format to file.'),
'default' => false
))->addOption('log-json', array(
'help' => __d('cake_console', '<file> Log test execution in TAP format to file.'),
'default' => false
))->addOption('log-tap', array(
'help' => __d('cake_console', '<file> Log test execution in TAP format to file.'),
'default' => false
))->addOption('log-dbus', array(
'help' => __d('cake_console', 'Log test execution to DBUS.'),
'default' => false
))->addOption('coverage-html', array(
'help' => __d('cake_console', '<dir> Generate code coverage report in HTML format.'),
'default' => false
))->addOption('coverage-clover', array(
'help' => __d('cake_console', '<file> Write code coverage data in Clover XML format.'),
'default' => false
))->addOption('testdox-html', array(
'help' => __d('cake_console', '<file> Write agile documentation in HTML format to file.'),
'default' => false
))->addOption('testdox-text', array(
'help' => __d('cake_console', '<file> Write agile documentation in Text format to file.'),
'default' => false
))->addOption('filter', array(
'help' => __d('cake_console', '<pattern> Filter which tests to run.'),
'default' => false
))->addOption('group', array(
'help' => __d('cake_console', '<name> Only runs tests from the specified group(s).'),
'default' => false
))->addOption('exclude-group', array(
'help' => __d('cake_console', '<name> Exclude tests from the specified group(s).'),
'default' => false
))->addOption('list-groups', array(
'help' => __d('cake_console', 'List available test groups.'),
'boolean' => true
))->addOption('loader', array(
'help' => __d('cake_console', 'TestSuiteLoader implementation to use.'),
'default' => false
))->addOption('repeat', array(
'help' => __d('cake_console', '<times> Runs the test(s) repeatedly.'),
'default' => false
))->addOption('tap', array(
'help' => __d('cake_console', 'Report test execution progress in TAP format.'),
'boolean' => true
))->addOption('testdox', array(
'help' => __d('cake_console', 'Report test execution progress in TestDox format.'),
'default' => false,
'boolean' => true
))->addOption('no-colors', array(
'help' => __d('cake_console', 'Do not use colors in output.'),
'boolean' => true
))->addOption('stderr', array(
'help' => __d('cake_console', 'Write to STDERR instead of STDOUT.'),
'boolean' => true
))->addOption('stop-on-error', array(
'help' => __d('cake_console', 'Stop execution upon first error or failure.'),
'boolean' => true
))->addOption('stop-on-failure', array(
'help' => __d('cake_console', 'Stop execution upon first failure.'),
'boolean' => true
))->addOption('stop-on-skipped ', array(
'help' => __d('cake_console', 'Stop execution upon first skipped test.'),
'boolean' => true
))->addOption('stop-on-incomplete', array(
'help' => __d('cake_console', 'Stop execution upon first incomplete test.'),
'boolean' => true
))->addOption('strict', array(
'help' => __d('cake_console', 'Mark a test as incomplete if no assertions are made.'),
'boolean' => true
))->addOption('wait', array(
'help' => __d('cake_console', 'Waits for a keystroke after each test.'),
'boolean' => true
))->addOption('process-isolation', array(
'help' => __d('cake_console', 'Run each test in a separate PHP process.'),
'boolean' => true
))->addOption('no-globals-backup', array(
'help' => __d('cake_console', 'Do not backup and restore $GLOBALS for each test.'),
'boolean' => true
))->addOption('static-backup ', array(
'help' => __d('cake_console', 'Backup and restore static attributes for each test.'),
'boolean' => true
))->addOption('syntax-check', array(
'help' => __d('cake_console', 'Try to check source files for syntax errors.'),
'boolean' => true
))->addOption('bootstrap', array(
'help' => __d('cake_console', '<file> A "bootstrap" PHP file that is run before the tests.'),
'default' => false
))->addOption('configuration', array(
'help' => __d('cake_console', '<file> Read configuration from XML file.'),
'default' => false
))->addOption('no-configuration', array(
'help' => __d('cake_console', 'Ignore default configuration file (phpunit.xml).'),
'boolean' => true
))->addOption('include-path', array(
'help' => __d('cake_console', '<path(s)> Prepend PHP include_path with given path(s).'),
'default' => false
))->addOption('directive', array(
'help' => __d('cake_console', 'key[=value] Sets a php.ini value.'),
'default' => false
))->addOption('fixture', array(
'help' => __d('cake_console', 'Choose a custom fixture manager.'),
))->addOption('debug', array(
'help' => __d('cake_console', 'More verbose output.'),
));
return $parser;
}
/**
* Initialization method installs PHPUnit and loads all plugins
*
* @return void
* @throws Exception
*/
public function initialize() {
$this->_dispatcher = new CakeTestSuiteDispatcher();
$sucess = $this->_dispatcher->loadTestFramework();
if (!$sucess) {
throw new Exception(__d('cake_dev', 'Please install PHPUnit framework <info>(http://www.phpunit.de)</info>'));
}
}
/**
* Parse the CLI options into an array CakeTestDispatcher can use.
*
* @return array Array of params for CakeTestDispatcher
*/
protected function _parseArgs() {
if (empty($this->args)) {
return;
}
$params = array(
'core' => false,
'app' => false,
'plugin' => null,
'output' => 'text',
);
$category = $this->args[0];
if ($category == 'core') {
$params['core'] = true;
} elseif ($category == 'app') {
$params['app'] = true;
} elseif ($category != 'core') {
$params['plugin'] = $category;
}
if (isset($this->args[1])) {
$params['case'] = $this->args[1];
}
return $params;
}
/**
* Converts the options passed to the shell as options for the PHPUnit cli runner
*
* @return array Array of params for CakeTestDispatcher
*/
protected function _runnerOptions() {
$options = array();
$params = $this->params;
unset($params['help']);
if (!empty($params['no-colors'])) {
unset($params['no-colors'], $params['colors']);
} else {
$params['colors'] = true;
}
foreach ($params as $param => $value) {
if ($value === false) {
continue;
}
$options[] = '--' . $param;
if (is_string($value)) {
$options[] = $value;
}
}
return $options;
}
/**
* Main entry point to this shell
*
* @return void
*/
public function main() {
$this->out(__d('cake_console', 'CakePHP Test Shell'));
$this->hr();
$args = $this->_parseArgs();
if (empty($args['case'])) {
return $this->available();
}
$this->_run($args, $this->_runnerOptions());
}
/**
* Runs the test case from $runnerArgs
*
* @param array $runnerArgs list of arguments as obtained from _parseArgs()
* @param array $options list of options as constructed by _runnerOptions()
* @return void
*/
protected function _run($runnerArgs, $options = array()) {
restore_error_handler();
restore_error_handler();
$testCli = new CakeTestSuiteCommand('CakeTestLoader', $runnerArgs);
$testCli->run($options);
}
/**
* Shows a list of available test cases and gives the option to run one of them
*
* @return void
*/
public function available() {
$params = $this->_parseArgs();
$testCases = CakeTestLoader::generateTestList($params);
$app = $params['app'];
$plugin = $params['plugin'];
$title = "Core Test Cases:";
$category = 'core';
if ($app) {
$title = "App Test Cases:";
$category = 'app';
} elseif ($plugin) {
$title = Inflector::humanize($plugin) . " Test Cases:";
$category = $plugin;
}
if (empty($testCases)) {
$this->out(__d('cake_console', "No test cases available \n\n"));
return $this->out($this->OptionParser->help());
}
$this->out($title);
$i = 1;
$cases = array();
foreach ($testCases as $testCaseFile => $testCase) {
$case = str_replace('Test.php', '', $testCase);
$this->out("[$i] $case");
$cases[$i] = $case;
$i++;
}
while ($choice = $this->in(__d('cake_console', 'What test case would you like to run?'), null, 'q')) {
if (is_numeric($choice) && isset($cases[$choice])) {
$this->args[0] = $category;
$this->args[1] = $cases[$choice];
$this->_run($this->_parseArgs(), $this->_runnerOptions());
break;
}
if (is_string($choice) && in_array($choice, $cases)) {
$this->args[0] = $category;
$this->args[1] = $choice;
$this->_run($this->_parseArgs(), $this->_runnerOptions());
break;
}
if ($choice == 'q') {
break;
}
}
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/TestsuiteShell.php | PHP | gpl3 | 10,589 |
<?php
/**
* Upgrade Shell
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Console.Command
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Folder', 'Utility');
/**
* A shell class to help developers upgrade applications to CakePHP 2.0
*
* @package Cake.Console.Command
*/
class UpgradeShell extends Shell {
/**
* Files
*
* @var array
*/
protected $_files = array();
/**
* Paths
*
* @var array
*/
protected $_paths = array();
/**
* Map
*
* @var array
*/
protected $_map = array(
'Controller' => 'Controller',
'Component' => 'Controller/Component',
'Model' => 'Model',
'Behavior' => 'Model/Behavior',
'Datasource' => 'Model/Datasource',
'Dbo' => 'Model/Datasource/Database',
'View' => 'View',
'Helper' => 'View/Helper',
'Shell' => 'Console/Command',
'Task' => 'Console/Command/Task',
'Case' => 'Test/Case',
'Fixture' => 'Test/Fixture',
'Error' => 'Lib/Error',
);
/**
* Shell startup, prints info message about dry run.
*
* @return void
*/
public function startup() {
parent::startup();
if ($this->params['dry-run']) {
$this->out(__d('cake_console', '<warning>Dry-run mode enabled!</warning>'), 1, Shell::QUIET);
}
if ($this->params['git'] && !is_dir('.git')) {
$this->out(__d('cake_console', '<warning>No git repository detected!</warning>'), 1, Shell::QUIET);
}
}
/**
* Run all upgrade steps one at a time
*
* @return void
*/
public function all() {
foreach($this->OptionParser->subcommands() as $command) {
$name = $command->name();
if ($name === 'all') {
continue;
}
$this->out(__d('cake_console', 'Running %s', $name));
$this->$name();
}
}
/**
* Update tests.
*
* - Update tests class names to FooTest rather than FooTestCase.
*
* @return void
*/
public function tests() {
$this->_paths = array(APP . 'tests' . DS);
if (!empty($this->params['plugin'])) {
$this->_paths = App::pluginPath($this->params['plugin']) . 'tests' . DS;
}
$patterns = array(
array(
'*TestCase extends CakeTestCase to *Test extends CakeTestCase',
'/([a-zA-Z]*Test)Case extends CakeTestCase/',
'\1 extends CakeTestCase'
),
);
$this->_filesRegexpUpdate($patterns);
}
/**
* Move files and folders to their new homes
*
* Moves folders containing files which cannot necessarily be auto-detected (libs and templates)
* and then looks for all php files except vendors, and moves them to where Cake 2.0 expects
* to find them.
*
* @return void
*/
public function locations() {
$cwd = getcwd();
if (!empty($this->params['plugin'])) {
chdir(App::pluginPath($this->params['plugin']));
}
if (is_dir('plugins')) {
$Folder = new Folder('plugins');
list($plugins) = $Folder->read();
foreach($plugins as $plugin) {
chdir($cwd . DS . 'plugins' . DS . $plugin);
$this->locations();
}
$this->_files = array();
chdir($cwd);
}
$this->_moveViewFiles();
$moves = array(
'libs' => 'Lib',
'tests' => 'Test',
'Test' . DS . 'cases' => 'Test' . DS . 'Case',
'Test' . DS . 'fixtures' => 'Test' . DS . 'Fixture',
'vendors' . DS . 'shells' . DS . 'templates' => 'Console' . DS . 'Templates',
);
foreach($moves as $old => $new) {
if (is_dir($old)) {
$this->out(__d('cake_console', 'Moving %s to %s', $old, $new));
if (!$this->params['dry-run']) {
if ($this->params['git']) {
exec('git mv -f ' . escapeshellarg($old) . ' ' . escapeshellarg($new));
} else {
$Folder = new Folder($old);
$Folder->move($new);
}
}
}
}
$sourceDirs = array(
'.' => array('recursive' => false),
'Console',
'Controller',
'controllers',
'Lib' => array('checkFolder' => false),
'Model',
'models',
'Test' => array('regex' => '@class (\S*Test) extends CakeTestCase@'),
'tests',
'View',
'views',
'vendors/shells',
);
$defaultOptions = array(
'recursive' => true,
'checkFolder' => true,
'regex' => '@class (\S*) .*{@i'
);
foreach($sourceDirs as $dir => $options) {
if (is_numeric($dir)) {
$dir = $options;
$options = array();
}
$options = array_merge($defaultOptions, $options);
$this->_movePhpFiles($dir, $options);
}
}
/**
* Update helpers.
*
* - Converts helpers usage to new format.
*
* @return void
*/
public function helpers() {
$this->_paths = array_diff(App::path('views'), App::core('views'));
if (!empty($this->params['plugin'])) {
$this->_paths = array(App::pluginPath($this->params['plugin']) . 'views' . DS);
}
$patterns = array();
$helpers = App::objects('helper');
$plugins = App::objects('plugin');
$pluginHelpers = array();
foreach ($plugins as $plugin) {
$pluginHelpers = array_merge(
$pluginHelpers,
App::objects('helper', App::pluginPath($plugin) . DS . 'views' . DS . 'helpers' . DS, false)
);
}
$helpers = array_merge($pluginHelpers, $helpers);
foreach ($helpers as $helper) {
$oldHelper = strtolower(substr($helper, 0, 1)).substr($helper, 1);
$patterns[] = array(
"\${$oldHelper} to \$this->{$helper}",
"/\\\${$oldHelper}->/",
"\\\$this->{$helper}->"
);
}
$this->_filesRegexpUpdate($patterns);
}
/**
* Update i18n.
*
* - Removes extra true param.
* - Add the echo to __*() calls that didn't need them before.
*
* @return void
*/
public function i18n() {
$this->_paths = array(
APP
);
if (!empty($this->params['plugin'])) {
$this->_paths = array(App::pluginPath($this->params['plugin']));
}
$patterns = array(
array(
'<?php __*(*) to <?php echo __*(*)',
'/<\?php\s*(__[a-z]*\(.*?\))/',
'<?php echo \1'
),
array(
'<?php __*(*, true) to <?php echo __*()',
'/<\?php\s*(__[a-z]*\(.*?)(,\s*true)(\))/',
'<?php echo \1\3'
),
array('__*(*, true) to __*(*)', '/(__[a-z]*\(.*?)(,\s*true)(\))/', '\1\3')
);
$this->_filesRegexpUpdate($patterns);
}
/**
* Upgrade the removed basics functions.
*
* - a(*) -> array(*)
* - e(*) -> echo *
* - ife(*, *, *) -> !empty(*) ? * : *
* - a(*) -> array(*)
* - r(*, *, *) -> str_replace(*, *, *)
* - up(*) -> strtoupper(*)
* - low(*, *, *) -> strtolower(*)
* - getMicrotime() -> microtime(true)
*
* @return void
*/
public function basics() {
$this->_paths = array(
APP
);
if (!empty($this->params['plugin'])) {
$this->_paths = array(App::pluginPath($this->params['plugin']));
}
$patterns = array(
array(
'a(*) -> array(*)',
'/\ba\((.*)\)/',
'array(\1)'
),
array(
'e(*) -> echo *',
'/\be\((.*)\)/',
'echo \1'
),
array(
'ife(*, *, *) -> !empty(*) ? * : *',
'/ife\((.*), (.*), (.*)\)/',
'!empty(\1) ? \2 : \3'
),
array(
'r(*, *, *) -> str_replace(*, *, *)',
'/\br\(/',
'str_replace('
),
array(
'up(*) -> strtoupper(*)',
'/\bup\(/',
'strtoupper('
),
array(
'low(*) -> strtolower(*)',
'/\blow\(/',
'strtolower('
),
array(
'getMicrotime() -> microtime(true)',
'/getMicrotime\(\)/',
'microtime(true)'
),
);
$this->_filesRegexpUpdate($patterns);
}
/**
* Update the properties moved to CakeRequest.
*
* @return void
*/
public function request() {
$views = array_diff(App::path('views'), App::core('views'));
$controllers = array_diff(App::path('controllers'), App::core('controllers'), array(APP));
$components = array_diff(App::path('components'), App::core('components'));
$this->_paths = array_merge($views, $controllers, $components);
if (!empty($this->params['plugin'])) {
$pluginPath = App::pluginPath($this->params['plugin']);
$this->_paths = array(
$pluginPath . 'controllers' . DS,
$pluginPath . 'controllers' . DS . 'components' .DS,
$pluginPath . 'views' . DS,
);
}
$patterns = array(
array(
'$this->data -> $this->request->data',
'/(\$this->data\b(?!\())/',
'$this->request->data'
),
array(
'$this->params -> $this->request->params',
'/(\$this->params\b(?!\())/',
'$this->request->params'
),
array(
'$this->webroot -> $this->request->webroot',
'/(\$this->webroot\b(?!\())/',
'$this->request->webroot'
),
array(
'$this->base -> $this->request->base',
'/(\$this->base\b(?!\())/',
'$this->request->base'
),
array(
'$this->here -> $this->request->here',
'/(\$this->here\b(?!\())/',
'$this->request->here'
),
array(
'$this->action -> $this->request->action',
'/(\$this->action\b(?!\())/',
'$this->request->action'
),
);
$this->_filesRegexpUpdate($patterns);
}
/**
* Update Configure::read() calls with no params.
*
* @return void
*/
public function configure() {
$this->_paths = array(
APP
);
if (!empty($this->params['plugin'])) {
$this->_paths = array(App::pluginPath($this->params['plugin']));
}
$patterns = array(
array(
"Configure::read() -> Configure::read('debug')",
'/Configure::read\(\)/',
'Configure::read(\'debug\')'
),
);
$this->_filesRegexpUpdate($patterns);
}
/**
* constants
*
* @return void
*/
public function constants() {
$this->_paths = array(
APP
);
if (!empty($this->params['plugin'])) {
$this->_paths = array(App::pluginPath($this->params['plugin']));
}
$patterns = array(
array(
"LIBS -> CAKE",
'/\bLIBS\b/',
'CAKE'
),
array(
"CONFIGS -> APP . 'Config' . DS",
'/\bCONFIGS\b/',
'APP . \'Config\' . DS'
),
array(
"CONTROLLERS -> APP . 'Controller' . DS",
'/\bCONTROLLERS\b/',
'APP . \'Controller\' . DS'
),
array(
"COMPONENTS -> APP . 'Controller' . DS . 'Component' . DS",
'/\bCOMPONENTS\b/',
'APP . \'Controller\' . DS . \'Component\''
),
array(
"MODELS -> APP . 'Model' . DS",
'/\bMODELS\b/',
'APP . \'Model\' . DS'
),
array(
"BEHAVIORS -> APP . 'Model' . DS . 'Behavior' . DS",
'/\bBEHAVIORS\b/',
'APP . \'Model\' . DS . \'Behavior\' . DS'
),
array(
"VIEWS -> APP . 'View' . DS",
'/\bVIEWS\b/',
'APP . \'View\' . DS'
),
array(
"HELPERS -> APP . 'View' . DS . 'Helper' . DS",
'/\bHELPERS\b/',
'APP . \'View\' . DS . \'Helper\' . DS'
),
array(
"LAYOUTS -> APP . 'View' . DS . 'Layouts' . DS",
'/\bLAYOUTS\b/',
'APP . \'View\' . DS . \'Layouts\' . DS'
),
array(
"ELEMENTS -> APP . 'View' . DS . 'Elements' . DS",
'/\bELEMENTS\b/',
'APP . \'View\' . DS . \'Elements\' . DS'
),
array(
"CONSOLE_LIBS -> CAKE . 'Console' . DS",
'/\bCONSOLE_LIBS\b/',
'CAKE . \'Console\' . DS'
),
array(
"CAKE_TESTS_LIB -> CAKE . 'TestSuite' . DS",
'/\bCAKE_TESTS_LIB\b/',
'CAKE . \'TestSuite\' . DS'
),
array(
"CAKE_TESTS -> CAKE . 'Test' . DS",
'/\bCAKE_TESTS\b/',
'CAKE . \'Test\' . DS'
)
);
$this->_filesRegexpUpdate($patterns);
}
/**
* Update components.
*
* - Make components that extend Object to extend Component.
*
* @return void
*/
public function components() {
$this->_paths = App::Path('Controller/Component');
if (!empty($this->params['plugin'])) {
$this->_paths = App::Path('Controller/Component', $this->params['plugin']);
}
$patterns = array(
array(
'*Component extends Object to *Component extends Component',
'/([a-zA-Z]*Component extends) Object/',
'\1 Component'
),
);
$this->_filesRegexpUpdate($patterns);
}
/**
* Move application views files to where they now should be
*
* Find all view files in the folder and determine where cake expects the file to be
*
* @return void
*/
protected function _moveViewFiles() {
if (!is_dir('views')) {
return;
}
$dirs = scandir('views');
foreach ($dirs as $old) {
if (!is_dir('views' . DS . $old) || $old === '.' || $old === '..') {
continue;
}
$new = 'View' . DS . Inflector::camelize($old);
$old = 'views' . DS . $old;
$this->out(__d('cake_console', 'Moving %s to %s', $old, $new));
if (!$this->params['dry-run']) {
if ($this->params['git']) {
exec('git mv -f ' . escapeshellarg($old) . ' ' . escapeshellarg($new));
} else {
$Folder = new Folder($old);
$Folder->move($new);
}
}
}
}
/**
* Move application php files to where they now should be
*
* Find all php files in the folder (honoring recursive) and determine where cake expects the file to be
* If the file is not exactly where cake expects it - move it.
*
* @param mixed $path
* @param mixed $options array(recursive, checkFolder)
* @return void
*/
protected function _movePhpFiles($path, $options) {
if (!is_dir($path)) {
return;
}
$paths = $this->_paths;
$this->_paths = array($path);
$this->_files = array();
if ($options['recursive']) {
$this->_findFiles('php');
} else {
$this->_files = scandir($path);
foreach($this->_files as $i => $file) {
if (strlen($file) < 5 || substr($file, -4) !== '.php') {
unset($this->_files[$i]);
}
}
}
$cwd = getcwd();
foreach ($this->_files as &$file) {
$file = $cwd . DS . $file;
$contents = file_get_contents($file);
preg_match($options['regex'], $contents, $match);
if (!$match) {
continue;
}
$class = $match[1];
if (substr($class, 0, 3) === 'Dbo') {
$type = 'Dbo';
} else {
preg_match('@([A-Z][^A-Z]*)$@', $class, $match);
if ($match) {
$type = $match[1];
} else {
$type = 'unknown';
}
}
preg_match('@^.*[\\\/]plugins[\\\/](.*?)[\\\/]@', $file, $match);
$base = $cwd . DS;
$plugin = false;
if ($match) {
$base = $match[0];
$plugin = $match[1];
}
if ($options['checkFolder'] && !empty($this->_map[$type])) {
$folder = str_replace('/', DS, $this->_map[$type]);
$new = $base . $folder . DS . $class . '.php';
} else {
$new = dirname($file) . DS . $class . '.php';
}
if ($file === $new) {
continue;
}
$dir = dirname($new);
if (!is_dir($dir)) {
new Folder($dir, true);
}
$this->out(__d('cake_console', 'Moving %s to %s', $file, $new), 1, Shell::VERBOSE);
if (!$this->params['dry-run']) {
if ($this->params['git']) {
exec('git mv -f ' . escapeshellarg($file) . ' ' . escapeshellarg($new));
} else {
rename($file, $new);
}
}
}
$this->_paths = $paths;
}
/**
* Updates files based on regular expressions.
*
* @param array $patterns Array of search and replacement patterns.
* @return void
*/
protected function _filesRegexpUpdate($patterns) {
$this->_findFiles($this->params['ext']);
foreach ($this->_files as $file) {
$this->out(__d('cake_console', 'Updating %s...', $file), 1, Shell::VERBOSE);
$this->_updateFile($file, $patterns);
}
}
/**
* Searches the paths and finds files based on extension.
*
* @param string $extensions
* @return void
*/
protected function _findFiles($extensions = '') {
foreach ($this->_paths as $path) {
if (!is_dir($path)) {
continue;
}
$this->_files = array();
$Iterator = new RegexIterator(
new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)),
'/^.+\.(' . $extensions . ')$/i',
RegexIterator::MATCH
);
foreach ($Iterator as $file) {
if ($file->isFile()) {
$this->_files[] = $file->getPathname();
}
}
}
}
/**
* Update a single file.
*
* @param string $file The file to update
* @param array $patterns The replacement patterns to run.
* @return void
*/
protected function _updateFile($file, $patterns) {
$contents = file_get_contents($file);
foreach ($patterns as $pattern) {
$this->out(__d('cake_console', ' * Updating %s', $pattern[0]), 1, Shell::VERBOSE);
$contents = preg_replace($pattern[1], $pattern[2], $contents);
}
$this->out(__d('cake_console', 'Done updating %s', $file), 1);
if (!$this->params['dry-run']) {
file_put_contents($file, $contents);
}
}
/**
* get the option parser
*
* @return ConsoleOptionParser
*/
public function getOptionParser() {
$subcommandParser = array(
'options' => array(
'plugin' => array(
'short' => 'p',
'help' => __d('cake_console', 'The plugin to update. Only the specified plugin will be updated.')
),
'ext' => array(
'short' => 'e',
'help' => __d('cake_console', 'The extension(s) to search. A pipe delimited list, or a preg_match compatible subpattern'),
'default' => 'php|ctp|thtml|inc|tpl'
),
'git' => array(
'short' => 'g',
'help' => __d('cake_console', 'Use git command for moving files around.'),
'boolean' => true
),
'dry-run'=> array(
'short' => 'd',
'help' => __d('cake_console', 'Dry run the update, no files will actually be modified.'),
'boolean' => true
)
)
);
return parent::getOptionParser()
->description(__d('cake_console', "A shell to help automate upgrading from CakePHP 1.3 to 2.0. \n" .
"Be sure to have a backup of your application before running these commands."))
->addSubcommand('all', array(
'help' => __d('cake_console', 'Run all upgrade commands.'),
'parser' => $subcommandParser
))
->addSubcommand('tests', array(
'help' => __d('cake_console', 'Update tests class names to FooTest rather than FooTestCase.'),
'parser' => $subcommandParser
))
->addSubcommand('locations', array(
'help' => __d('cake_console', 'Move files and folders to their new homes.'),
'parser' => $subcommandParser
))
->addSubcommand('i18n', array(
'help' => __d('cake_console', 'Update the i18n translation method calls.'),
'parser' => $subcommandParser
))
->addSubcommand('helpers', array(
'help' => __d('cake_console', 'Update calls to helpers.'),
'parser' => $subcommandParser
))
->addSubcommand('basics', array(
'help' => __d('cake_console', 'Update removed basics functions to PHP native functions.'),
'parser' => $subcommandParser
))
->addSubcommand('request', array(
'help' => __d('cake_console', 'Update removed request access, and replace with $this->request.'),
'parser' => $subcommandParser
))
->addSubcommand('configure', array(
'help' => __d('cake_console', "Update Configure::read() to Configure::read('debug')"),
'parser' => $subcommandParser
))
->addSubcommand('constants', array(
'help' => __d('cake_console', "Replace Obsolete constants"),
'parser' => $subcommandParser
))
->addSubcommand('components', array(
'help' => __d('cake_console', 'Update components to extend Component class.'),
'parser' => $subcommandParser
));
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/UpgradeShell.php | PHP | gpl3 | 18,981 |
<?php
/**
* Internationalization Management Shell
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2.0.5669
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Shell for I18N management.
*
* @package Cake.Console.Command
*/
class I18nShell extends Shell {
/**
* Contains database source to use
*
* @var string
*/
public $dataSource = 'default';
/**
* Contains tasks to load and instantiate
*
* @var array
*/
public $tasks = array('DbConfig', 'Extract');
/**
* Override startup of the Shell
*
* @return mixed
*/
public function startup() {
$this->_welcome();
if (isset($this->params['datasource'])) {
$this->dataSource = $this->params['datasource'];
}
if ($this->command && !in_array($this->command, array('help'))) {
if (!config('database')) {
$this->out(__d('cake_console', 'Your database configuration was not found. Take a moment to create one.'), true);
return $this->DbConfig->execute();
}
}
}
/**
* Override main() for help message hook
*
* @return void
*/
public function main() {
$this->out(__d('cake_console', '<info>I18n Shell</info>'));
$this->hr();
$this->out(__d('cake_console', '[E]xtract POT file from sources'));
$this->out(__d('cake_console', '[I]nitialize i18n database table'));
$this->out(__d('cake_console', '[H]elp'));
$this->out(__d('cake_console', '[Q]uit'));
$choice = strtolower($this->in(__d('cake_console', 'What would you like to do?'), array('E', 'I', 'H', 'Q')));
switch ($choice) {
case 'e':
$this->Extract->execute();
break;
case 'i':
$this->initdb();
break;
case 'h':
$this->out($this->OptionParser->help());
break;
case 'q':
exit(0);
break;
default:
$this->out(__d('cake_console', 'You have made an invalid selection. Please choose a command to execute by entering E, I, H, or Q.'));
}
$this->hr();
$this->main();
}
/**
* Initialize I18N database.
*
* @return void
*/
public function initdb() {
$this->dispatchShell('schema create i18n');
}
/**
* Get and configure the Option parser
*
* @return ConsoleOptionParser
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
return $parser->description(
__d('cake_console', 'I18n Shell initializes i18n database table for your application and generates .pot files(s) with translations.')
)->addSubcommand('initdb', array(
'help' => __d('cake_console', 'Initialize the i18n table.')
))->addSubcommand('extract', array(
'help' => __d('cake_console', 'Extract the po translations from your application'),
'parser' => $this->Extract->getOptionParser()
));
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/I18nShell.php | PHP | gpl3 | 3,090 |
<?php
/**
* CakePHP Console Shell
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2.0.5012
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Provides a very basic 'interactive' console for CakePHP apps.
*
* @package Cake.Console.Command
*/
class ConsoleShell extends Shell {
/**
* Available binding types
*
* @var array
*/
public $associations = array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany');
/**
* Chars that describe invalid commands
*
* @var array
*/
public $badCommandChars = array('$', ';');
/**
* Available models
*
* @var array
*/
public $models = array();
/**
* Override initialize of the Shell
*
* @return void
*/
public function initialize() {
App::uses('Dispatcher', 'Routing');
$this->Dispatcher = new Dispatcher();
$this->models = App::objects('Model');
foreach ($this->models as $model) {
$class = $model;
$this->models[$model] = $class;
App::uses($class, 'Model');
$this->{$class} = new $class();
}
$this->out(__d('cake_console', 'Model classes:'));
$this->hr();
foreach ($this->models as $model) {
$this->out(" - {$model}");
}
$this->_loadRoutes();
}
/**
* Prints the help message
*
* @return void
*/
public function help() {
$out = 'Console help:';
$out .= '-------------';
$out .= 'The interactive console is a tool for testing parts of your app before you';
$out .= 'write code.';
$out .= "\n";
$out .= 'Model testing:';
$out .= 'To test model results, use the name of your model without a leading $';
$out .= 'e.g. Foo->find("all")';
$out .= "\n";
$out .= 'To dynamically set associations, you can do the following:';
$out .= "\tModelA bind <association> ModelB";
$out .= "where the supported assocations are hasOne, hasMany, belongsTo, hasAndBelongsToMany";
$out .= "\n";
$out .= 'To dynamically remove associations, you can do the following:';
$out .= "\t ModelA unbind <association> ModelB";
$out .= "where the supported associations are the same as above";
$out .= "\n";
$out .= "To save a new field in a model, you can do the following:";
$out .= "\tModelA->save(array('foo' => 'bar', 'baz' => 0))";
$out .= "where you are passing a hash of data to be saved in the format";
$out .= "of field => value pairs";
$out .= "\n";
$out .= "To get column information for a model, use the following:";
$out .= "\tModelA columns";
$out .= "which returns a list of columns and their type";
$out .= "\n";
$out .= "\n";
$out .= 'Route testing:';
$out .= "\n";
$out .= 'To test URLs against your app\'s route configuration, type:';
$out .= "\n";
$out .= "\tRoute <url>";
$out .= "\n";
$out .= "where url is the path to your your action plus any query parameters,";
$out .= "minus the application's base path. For example:";
$out .= "\n";
$out .= "\tRoute /posts/view/1";
$out .= "\n";
$out .= "will return something like the following:";
$out .= "\n";
$out .= "\tarray (";
$out .= "\t [...]";
$out .= "\t 'controller' => 'posts',";
$out .= "\t 'action' => 'view',";
$out .= "\t [...]";
$out .= "\t)";
$out .= "\n";
$out .= 'Alternatively, you can use simple array syntax to test reverse';
$out .= 'To reload your routes config (Config/routes.php), do the following:';
$out .= "\n";
$out .= "\tRoutes reload";
$out .= "\n";
$out .= 'To show all connected routes, do the following:';
$out .= "\tRoutes show";
$this->out($out);
}
/**
* Override main() to handle action
*
* @param string $command
* @return void
*/
public function main($command = null) {
while (true) {
if (empty($command)) {
$command = trim($this->in(''));
}
switch ($command) {
case 'help':
$this->help();
break;
case 'quit':
case 'exit':
return true;
break;
case 'models':
$this->out(__d('cake_console', 'Model classes:'));
$this->hr();
foreach ($this->models as $model) {
$this->out(" - {$model}");
}
break;
case (preg_match("/^(\w+) bind (\w+) (\w+)/", $command, $tmp) == true):
foreach ($tmp as $data) {
$data = strip_tags($data);
$data = str_replace($this->badCommandChars, "", $data);
}
$modelA = $tmp[1];
$association = $tmp[2];
$modelB = $tmp[3];
if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations)) {
$this->{$modelA}->bindModel(array($association => array($modelB => array('className' => $modelB))), false);
$this->out(__d('cake_console', "Created %s association between %s and %s",
$association, $modelA, $modelB));
} else {
$this->out(__d('cake_console', "Please verify you are using valid models and association types"));
}
break;
case (preg_match("/^(\w+) unbind (\w+) (\w+)/", $command, $tmp) == true):
foreach ($tmp as $data) {
$data = strip_tags($data);
$data = str_replace($this->badCommandChars, "", $data);
}
$modelA = $tmp[1];
$association = $tmp[2];
$modelB = $tmp[3];
// Verify that there is actually an association to unbind
$currentAssociations = $this->{$modelA}->getAssociated();
$validCurrentAssociation = false;
foreach ($currentAssociations as $model => $currentAssociation) {
if ($model == $modelB && $association == $currentAssociation) {
$validCurrentAssociation = true;
}
}
if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations) && $validCurrentAssociation) {
$this->{$modelA}->unbindModel(array($association => array($modelB)));
$this->out(__d('cake_console', "Removed %s association between %s and %s",
$association, $modelA, $modelB));
} else {
$this->out(__d('cake_console', "Please verify you are using valid models, valid current association, and valid association types"));
}
break;
case (strpos($command, "->find") > 0):
// Remove any bad info
$command = strip_tags($command);
$command = str_replace($this->badCommandChars, "", $command);
// Do we have a valid model?
list($modelToCheck, $tmp) = explode('->', $command);
if ($this->_isValidModel($modelToCheck)) {
$findCommand = "\$data = \$this->$command;";
@eval($findCommand);
if (is_array($data)) {
foreach ($data as $idx => $results) {
if (is_numeric($idx)) { // findAll() output
foreach ($results as $modelName => $result) {
$this->out("$modelName");
foreach ($result as $field => $value) {
if (is_array($value)) {
foreach ($value as $field2 => $value2) {
$this->out("\t$field2: $value2");
}
$this->out();
} else {
$this->out("\t$field: $value");
}
}
}
} else { // find() output
$this->out($idx);
foreach ($results as $field => $value) {
if (is_array($value)) {
foreach ($value as $field2 => $value2) {
$this->out("\t$field2: $value2");
}
$this->out();
} else {
$this->out("\t$field: $value");
}
}
}
}
} else {
$this->out();
$this->out(__d('cake_console', "No result set found"));
}
} else {
$this->out(__d('cake_console', "%s is not a valid model", $modelToCheck));
}
break;
case (strpos($command, '->save') > 0):
// Validate the model we're trying to save here
$command = strip_tags($command);
$command = str_replace($this->badCommandChars, "", $command);
list($modelToSave, $tmp) = explode("->", $command);
if ($this->_isValidModel($modelToSave)) {
// Extract the array of data we are trying to build
list($foo, $data) = explode("->save", $command);
$data = preg_replace('/^\(*(array)?\(*(.+?)\)*$/i', '\\2', $data);
$saveCommand = "\$this->{$modelToSave}->save(array('{$modelToSave}' => array({$data})));";
@eval($saveCommand);
$this->out(__d('cake_console', 'Saved record for %s', $modelToSave));
}
break;
case (preg_match("/^(\w+) columns/", $command, $tmp) == true):
$modelToCheck = strip_tags(str_replace($this->badCommandChars, "", $tmp[1]));
if ($this->_isValidModel($modelToCheck)) {
// Get the column info for this model
$fieldsCommand = "\$data = \$this->{$modelToCheck}->getColumnTypes();";
@eval($fieldsCommand);
if (is_array($data)) {
foreach ($data as $field => $type) {
$this->out("\t{$field}: {$type}");
}
}
} else {
$this->out(__d('cake_console', "Please verify that you selected a valid model"));
}
break;
case (preg_match("/^routes\s+reload/i", $command, $tmp) == true):
$router = Router::getInstance();
if (!$this->_loadRoutes()) {
$this->out(__d('cake_console', "There was an error loading the routes config. Please check that the file exists and is free of parse errors."));
break;
}
$this->out(__d('cake_console', "Routes configuration reloaded, %d routes connected", count($router->routes)));
break;
case (preg_match("/^routes\s+show/i", $command, $tmp) == true):
$router = Router::getInstance();
$this->out(implode("\n", Set::extract($router->routes, '{n}.0')));
break;
case (preg_match("/^route\s+(\(.*\))$/i", $command, $tmp) == true):
if ($url = eval('return array' . $tmp[1] . ';')) {
$this->out(Router::url($url));
}
break;
case (preg_match("/^route\s+(.*)/i", $command, $tmp) == true):
$this->out(var_export(Router::parse($tmp[1]), true));
break;
default:
$this->out(__d('cake_console', "Invalid command"));
$this->out();
break;
}
$command = '';
}
}
/**
* Tells if the specified model is included in the list of available models
*
* @param string $modelToCheck
* @return boolean true if is an available model, false otherwise
*/
protected function _isValidModel($modelToCheck) {
return in_array($modelToCheck, $this->models);
}
/**
* Reloads the routes configuration from app/Config/routes.php, and compiles
* all routes found
*
* @return boolean True if config reload was a success, otherwise false
*/
protected function _loadRoutes() {
Router::reload();
extract(Router::getNamedExpressions());
if (!@include(APP . 'Config' . DS . 'routes.php')) {
return false;
}
CakePlugin::routes();
Router::parse('/');
foreach (array_keys(Router::getNamedExpressions()) as $var) {
unset(${$var});
}
foreach (Router::$routes as $route) {
$route->compile();
}
return true;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/ConsoleShell.php | PHP | gpl3 | 11,205 |
<?php
/**
* Command-line code generation utility to automate programmer chores.
*
* Bake is CakePHP's code generation script, which can help you kickstart
* application development by writing fully functional skeleton controllers,
* models, and views. Going further, Bake can also write Unit Tests for you.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2.0.5012
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Model', 'Model');
/**
* Bake is a command-line code generation utility for automating programmer chores.
*
* @package Cake.Console.Command
* @link http://book.cakephp.org/2.0/en/console-and-shells/code-generation-with-bake.html
*/
class BakeShell extends Shell {
/**
* Contains tasks to load and instantiate
*
* @var array
*/
public $tasks = array('Project', 'DbConfig', 'Model', 'Controller', 'View', 'Plugin', 'Fixture', 'Test');
/**
* The connection being used.
*
* @var string
*/
public $connection = 'default';
/**
* Assign $this->connection to the active task if a connection param is set.
*
* @return void
*/
public function startup() {
parent::startup();
Configure::write('debug', 2);
Configure::write('Cache.disable', 1);
$task = Inflector::classify($this->command);
if (isset($this->{$task}) && !in_array($task, array('Project', 'DbConfig'))) {
if (isset($this->params['connection'])) {
$this->{$task}->connection = $this->params['connection'];
}
}
}
/**
* Override main() to handle action
*
* @return mixed
*/
public function main() {
if (!is_dir($this->DbConfig->path)) {
$path = $this->Project->execute();
if (!empty($path)) {
$this->DbConfig->path = $path . 'Config' . DS;
} else {
return false;
}
}
if (!config('database')) {
$this->out(__d('cake_console', 'Your database configuration was not found. Take a moment to create one.'));
$this->args = null;
return $this->DbConfig->execute();
}
$this->out(__d('cake_console', 'Interactive Bake Shell'));
$this->hr();
$this->out(__d('cake_console', '[D]atabase Configuration'));
$this->out(__d('cake_console', '[M]odel'));
$this->out(__d('cake_console', '[V]iew'));
$this->out(__d('cake_console', '[C]ontroller'));
$this->out(__d('cake_console', '[P]roject'));
$this->out(__d('cake_console', '[F]ixture'));
$this->out(__d('cake_console', '[T]est case'));
$this->out(__d('cake_console', '[Q]uit'));
$classToBake = strtoupper($this->in(__d('cake_console', 'What would you like to Bake?'), array('D', 'M', 'V', 'C', 'P', 'F', 'T', 'Q')));
switch ($classToBake) {
case 'D':
$this->DbConfig->execute();
break;
case 'M':
$this->Model->execute();
break;
case 'V':
$this->View->execute();
break;
case 'C':
$this->Controller->execute();
break;
case 'P':
$this->Project->execute();
break;
case 'F':
$this->Fixture->execute();
break;
case 'T':
$this->Test->execute();
break;
case 'Q':
exit(0);
break;
default:
$this->out(__d('cake_console', 'You have made an invalid selection. Please choose a type of class to Bake by entering D, M, V, F, T, or C.'));
}
$this->hr();
$this->main();
}
/**
* Quickly bake the MVC
*
* @return void
*/
public function all() {
$this->out('Bake All');
$this->hr();
if (!isset($this->params['connection']) && empty($this->connection)) {
$this->connection = $this->DbConfig->getConfig();
}
if (empty($this->args)) {
$this->Model->interactive = true;
$name = $this->Model->getName($this->connection);
}
foreach (array('Model', 'Controller', 'View') as $task) {
$this->{$task}->connection = $this->connection;
$this->{$task}->interactive = false;
}
if (!empty($this->args[0])) {
$name = $this->args[0];
}
$modelExists = false;
$model = $this->_modelName($name);
App::uses('AppModel', 'Model');
App::uses($model, 'Model');
if (class_exists($model)) {
$object = new $model();
$modelExists = true;
} else {
$object = new Model(array('name' => $name, 'ds' => $this->connection));
}
$modelBaked = $this->Model->bake($object, false);
if ($modelBaked && $modelExists === false) {
if ($this->_checkUnitTest()) {
$this->Model->bakeFixture($model);
$this->Model->bakeTest($model);
}
$modelExists = true;
}
if ($modelExists === true) {
$controller = $this->_controllerName($name);
if ($this->Controller->bake($controller, $this->Controller->bakeActions($controller))) {
if ($this->_checkUnitTest()) {
$this->Controller->bakeTest($controller);
}
}
App::uses($controller . 'Controller', 'Controller');
if (class_exists($controller . 'Controller')) {
$this->View->args = array($controller);
$this->View->execute();
}
$this->out('', 1, Shell::QUIET);
$this->out(__d('cake_console', '<success>Bake All complete</success>'), 1, Shell::QUIET);
array_shift($this->args);
} else {
$this->error(__d('cake_console', 'Bake All could not continue without a valid model'));
}
return $this->_stop();
}
/**
* get the option parser.
*
* @return void
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
return $parser->description(__d('cake_console',
'The Bake script generates controllers, views and models for your application.'
. ' If run with no command line arguments, Bake guides the user through the class creation process.'
. ' You can customize the generation process by telling Bake where different parts of your application are using command line arguments.'
))->addSubcommand('all', array(
'help' => __d('cake_console', 'Bake a complete MVC. optional <name> of a Model'),
))->addSubcommand('project', array(
'help' => __d('cake_console', 'Bake a new app folder in the path supplied or in current directory if no path is specified'),
'parser' => $this->Project->getOptionParser()
))->addSubcommand('plugin', array(
'help' => __d('cake_console', 'Bake a new plugin folder in the path supplied or in current directory if no path is specified.'),
'parser' => $this->Plugin->getOptionParser()
))->addSubcommand('db_config', array(
'help' => __d('cake_console', 'Bake a database.php file in config directory.'),
'parser' => $this->DbConfig->getOptionParser()
))->addSubcommand('model', array(
'help' => __d('cake_console', 'Bake a model.'),
'parser' => $this->Model->getOptionParser()
))->addSubcommand('view', array(
'help' => __d('cake_console', 'Bake views for controllers.'),
'parser' => $this->View->getOptionParser()
))->addSubcommand('controller', array(
'help' => __d('cake_console', 'Bake a controller.'),
'parser' => $this->Controller->getOptionParser()
))->addSubcommand('fixture', array(
'help' => __d('cake_console', 'Bake a fixture.'),
'parser' => $this->Fixture->getOptionParser()
))->addSubcommand('test', array(
'help' => __d('cake_console', 'Bake a unit test.'),
'parser' => $this->Test->getOptionParser()
))->addOption('connection', array(
'help' => __d('cake_console', 'Database connection to use in conjunction with `bake all`.'),
'short' => 'c',
'default' => 'default'
));
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/BakeShell.php | PHP | gpl3 | 7,650 |
<?php
/**
* Command list Shell
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Console.Command
* @since CakePHP v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Inflector', 'Utility');
/**
* Shows a list of commands available from the console.
*
* @package Cake.Console.Command
*/
class CommandListShell extends Shell {
/**
* startup
*
* @return void
*/
public function startup() {
if (empty($this->params['xml'])) {
parent::startup();
}
}
/**
* Main function Prints out the list of shells.
*
* @return void
*/
public function main() {
if (empty($this->params['xml'])) {
$this->out(__d('cake_console', "<info>Current Paths:</info>"), 2);
$this->out(" -app: ". APP_DIR);
$this->out(" -working: " . rtrim(APP, DS));
$this->out(" -root: " . rtrim(ROOT, DS));
$this->out(" -core: " . rtrim(CORE_PATH, DS));
$this->out("");
$this->out(__d('cake_console', "<info>Changing Paths:</info>"), 2);
$this->out(__d('cake_console', "Your working path should be the same as your application path to change your path use the '-app' param."));
$this->out(__d('cake_console', "Example: -app relative/path/to/myapp or -app /absolute/path/to/myapp"), 2);
$this->out(__d('cake_console', "<info>Available Shells:</info>"), 2);
}
$shellList = $this->_getShellList();
if ($shellList) {
ksort($shellList);
if (empty($this->params['xml'])) {
if (!empty($this->params['sort'])) {
$this->_asSorted($shellList);
} else {
$this->_asText($shellList);
}
} else {
$this->_asXml($shellList);
}
}
}
/**
* Gets the shell command listing.
*
* @return array
*/
protected function _getShellList() {
$shellList = array();
$shells = App::objects('file', App::core('Console/Command'));
$shellList = $this->_appendShells('CORE', $shells, $shellList);
$appShells = App::objects('Console/Command', null, false);
$shellList = $this->_appendShells('app', $appShells, $shellList);
$plugins = CakePlugin::loaded();
foreach ($plugins as $plugin) {
$pluginShells = App::objects($plugin . '.Console/Command');
$shellList = $this->_appendShells($plugin, $pluginShells, $shellList);
}
return $shellList;
}
/**
* Scan the provided paths for shells, and append them into $shellList
*
* @param string $type
* @param array $shells
* @param array $shellList
* @return array
*/
protected function _appendShells($type, $shells, $shellList) {
foreach ($shells as $shell) {
$shell = Inflector::underscore(str_replace('Shell', '', $shell));
$shellList[$shell][$type] = $type;
}
return $shellList;
}
/**
* Output text.
*
* @param array $shellList
* @return void
*/
protected function _asText($shellList) {
if (DS === '/') {
$width = exec('tput cols') - 2;
}
if (empty($width)) {
$width = 80;
}
$columns = max(1, floor($width / 30));
$rows = ceil(count($shellList) / $columns);
foreach ($shellList as $shell => $types) {
sort($types);
$shellList[$shell] = str_pad($shell . ' [' . implode ($types, ', ') . ']', $width / $columns);
}
$out = array_chunk($shellList, $rows);
for ($i = 0; $i < $rows; $i++) {
$row = '';
for ($j = 0; $j < $columns; $j++) {
if (!isset($out[$j][$i])) {
continue;
}
$row .= $out[$j][$i];
}
$this->out(" " . $row);
}
$this->out();
$this->out(__d('cake_console', "To run a command, type <info>cake shell_name [args]</info>"));
$this->out(__d('cake_console', "To get help on a specific command, type <info>cake shell_name --help</info>"), 2);
}
/**
* Generates the shell list sorted by where the shells are found.
*
* @param array $shellList
* @return void
*/
protected function _asSorted($shellList) {
$grouped = array();
foreach ($shellList as $shell => $types) {
foreach ($types as $type) {
$type = Inflector::camelize($type);
if (empty($grouped[$type])) {
$grouped[$type] = array();
}
$grouped[$type][] = $shell;
}
}
if (!empty($grouped['App'])) {
sort($grouped['App'], SORT_STRING);
$this->out('[ App ]');
$this->out(' ' . implode(', ', $grouped['App']), 2);
unset($grouped['App']);
}
foreach ($grouped as $section => $shells) {
if ($section == 'CORE') {
continue;
}
sort($shells, SORT_STRING);
$this->out('[ ' . $section . ' ]');
$this->out(' ' . implode(', ', $shells), 2);
}
if (!empty($grouped['CORE'])) {
sort($grouped['CORE'], SORT_STRING);
$this->out('[ Core ]');
$this->out(' ' . implode(', ', $grouped['CORE']), 2);
}
$this->out();
}
/**
* Output as XML
*
* @param array $shellList
* @return void
*/
protected function _asXml($shellList) {
$plugins = CakePlugin::loaded();
$shells = new SimpleXmlElement('<shells></shells>');
foreach ($shellList as $name => $location) {
$source = current($location);
$callable = $name;
if (in_array($source, $plugins)) {
$callable = Inflector::camelize($source) . '.' . $name;
}
$shell = $shells->addChild('shell');
$shell->addAttribute('name', $name);
$shell->addAttribute('call_as', $callable);
$shell->addAttribute('provider', $source);
$shell->addAttribute('help', $callable . ' -h');
}
$this->stdout->outputAs(ConsoleOutput::RAW);
$this->out($shells->saveXml());
}
/**
* get the option parser
*
* @return void
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
return $parser->description(__d('cake_console', 'Get the list of available shells for this CakePHP application.'))
->addOption('xml', array(
'help' => __d('cake_console', 'Get the listing as XML.'),
'boolean' => true
))->addOption('sort', array(
'help' => __d('cake_console', 'Sorts the commands by where they are located.'),
'boolean' => true
));
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/CommandListShell.php | PHP | gpl3 | 6,244 |
<?php
/**
* API shell to get CakePHP core method signatures.
*
* Implementation of a Cake Shell to show CakePHP core method signatures.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2.0.5012
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('File', 'Utility');
/**
* API shell to show method signatures of CakePHP core classes.
*
* @package Cake.Console.Command
*/
class ApiShell extends Shell {
/**
* Map between short name for paths and real paths.
*
* @var array
*/
public $paths = array();
/**
* Override initialize of the Shell
*
* @return void
*/
public function initialize() {
$this->paths = array_merge($this->paths, array(
'behavior' => CAKE . 'Model' . DS . 'Behavior' . DS,
'cache' => CAKE . 'Cache' . DS,
'controller' => CAKE . 'Controller' . DS,
'component' => CAKE . 'Controller' . DS . 'Component' . DS,
'helper' => CAKE . 'View' . DS . 'Helper' . DS,
'model' => CAKE . 'Model' . DS,
'view' => CAKE . 'View' . DS,
'core' => CAKE
));
}
/**
* Override main() to handle action
*
* @return void
*/
public function main() {
if (empty($this->args)) {
return $this->out($this->OptionParser->help());
}
$type = strtolower($this->args[0]);
if (isset($this->paths[$type])) {
$path = $this->paths[$type];
} else {
$path = $this->paths['core'];
}
if (count($this->args) == 1) {
$file = $type;
$class = Inflector::camelize($type);
} elseif (count($this->args) > 1) {
$file = Inflector::underscore($this->args[1]);
$class = Inflector::camelize($this->args[1]);
}
$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)) {
$class .= Inflector::camelize($type);
}
}
} else {
$this->error(__d('cake_console', '%s not found', $class));
}
$parsed = $this->_parseClass($path . $class .'.php', $class);
if (!empty($parsed)) {
if (isset($this->params['method'])) {
if (!isset($parsed[$this->params['method']])) {
$this->err(__d('cake_console', '%s::%s() could not be found', $class, $this->params['method']));
$this->_stop();
}
$method = $parsed[$this->params['method']];
$this->out($class .'::'.$method['method'] . $method['parameters']);
$this->hr();
$this->out($method['comment'], true);
} else {
$this->out(ucwords($class));
$this->hr();
$i = 0;
foreach ($parsed as $method) {
$list[] = ++$i . ". " . $method['method'] . $method['parameters'];
}
$this->out($list);
$methods = array_keys($parsed);
while ($number = strtolower($this->in(__d('cake_console', 'Select a number to see the more information about a specific method. q to quit. l to list.'), null, 'q'))) {
if ($number === 'q') {
$this->out(__d('cake_console', 'Done'));
return $this->_stop();
}
if ($number === 'l') {
$this->out($list);
}
if (isset($methods[--$number])) {
$method = $parsed[$methods[$number]];
$this->hr();
$this->out($class .'::'.$method['method'] . $method['parameters']);
$this->hr();
$this->out($method['comment'], true);
}
}
}
}
}
/**
* Get and configure the optionparser.
*
* @return ConsoleOptionParser
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
$parser->addArgument('type', array(
'help' => __d('cake_console', 'Either a full path or type of class (model, behavior, controller, component, view, helper)')
))->addArgument('className', array(
'help' => __d('cake_console', 'A CakePHP core class name (e.g: Component, HtmlHelper).')
))->addOption('method', array(
'short' => 'm',
'help' => __d('cake_console', 'The specific method you want help on.')
))->description(__d('cake_console', 'Lookup doc block comments for classes in CakePHP.'));
return $parser;
}
/**
* Show help for this shell.
*
* @return void
*/
public function help() {
$head = "Usage: cake api [<type>] <className> [-m <method>]\n";
$head .= "-----------------------------------------------\n";
$head .= "Parameters:\n\n";
$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",
'className' => "\t<className>\n" .
"\t\tA CakePHP core class name (e.g: Component, HtmlHelper).\n"
);
$this->out($head);
if (!isset($this->args[1])) {
foreach ($commands as $cmd) {
$this->out("{$cmd}\n\n");
}
} elseif (isset($commands[strtolower($this->args[1])])) {
$this->out($commands[strtolower($this->args[1])] . "\n\n");
} else {
$this->out(__d('cake_console', 'Command %s not found', $this->args[1]));
}
}
/**
* Parse a given class (located on given file) and get public methods and their
* signatures.
*
* @param string $path File path
* @param string $class Class name
* @return array Methods and signatures indexed by method name
*/
protected function _parseClass($path, $class) {
$parsed = array();
if (!class_exists($class)) {
if (!include_once($path)) {
$this->err(__d('cake_console', '%s could not be found', $path));
}
}
$reflection = new ReflectionClass($class);
foreach ($reflection->getMethods() as $method) {
if (!$method->isPublic() || strpos($method->getName(), '_') === 0) {
continue;
}
if ($method->getDeclaringClass()->getName() != $class) {
continue;
}
$args = array();
foreach ($method->getParameters() as $param) {
$paramString = '$' . $param->getName();
if ($param->isDefaultValueAvailable()) {
$paramString .= ' = ' . str_replace("\n", '', var_export($param->getDefaultValue(), true));
}
$args[] = $paramString;
}
$parsed[$method->getName()] = array(
'comment' => str_replace(array('/*', '*/', '*'), '', $method->getDocComment()),
'method' => $method->getName(),
'parameters' => '(' . implode(', ', $args) . ')'
);
}
ksort($parsed);
return $parsed;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/ApiShell.php | PHP | gpl3 | 7,020 |
<?php
/**
* Command-line database management utility to automate programmer chores.
*
* Schema is CakePHP's database management utility. This helps you maintain versions of
* of your database.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2.0.5550
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('File', 'Utility');
App::uses('Folder', 'Utility');
App::uses('CakeSchema', 'Model');
/**
* Schema is a command-line database management utility for automating programmer chores.
*
* @package Cake.Console.Command
* @link http://book.cakephp.org/2.0/en/console-and-shells/schema-management-and-migrations.html
*/
class SchemaShell extends Shell {
/**
* Schema class being used.
*
* @var CakeSchema
*/
public $Schema;
/**
* is this a dry run?
*
* @var boolean
*/
protected $_dry = null;
/**
* Override initialize
*
* @return string
*/
public function initialize() {
$this->_welcome();
$this->out('Cake Schema Shell');
$this->hr();
}
/**
* Override startup
*
* @return void
*/
public function startup() {
$name = $path = $connection = $plugin = null;
if (!empty($this->params['name'])) {
$name = $this->params['name'];
} elseif (!empty($this->args[0])) {
$name = $this->params['name'] = $this->args[0];
}
if (strpos($name, '.')) {
list($this->params['plugin'], $splitName) = pluginSplit($name);
$name = $this->params['name'] = $splitName;
}
if ($name) {
$this->params['file'] = Inflector::underscore($name);
}
if (empty($this->params['file'])) {
$this->params['file'] = 'schema.php';
}
if (strpos($this->params['file'], '.php') === false) {
$this->params['file'] .= '.php';
}
$file = $this->params['file'];
if (!empty($this->params['path'])) {
$path = $this->params['path'];
}
if (!empty($this->params['connection'])) {
$connection = $this->params['connection'];
}
if (!empty($this->params['plugin'])) {
$plugin = $this->params['plugin'];
if (empty($name)) {
$name = $plugin;
}
}
$this->Schema = new CakeSchema(compact('name', 'path', 'file', 'connection', 'plugin'));
}
/**
* Read and output contents of schema object
* path to read as second arg
*
* @return void
*/
public function view() {
$File = new File($this->Schema->path . DS . $this->params['file']);
if ($File->exists()) {
$this->out($File->read());
$this->_stop();
} else {
$file = $this->Schema->path . DS . $this->params['file'];
$this->err(__d('cake_console', 'Schema file (%s) could not be found.', $file));
$this->_stop();
}
}
/**
* Read database and Write schema object
* accepts a connection as first arg or path to save as second arg
*
* @return void
*/
public function generate() {
$this->out(__d('cake_console', 'Generating Schema...'));
$options = array();
if ($this->params['force']) {
$options = array('models' => false);
}
$snapshot = false;
if (isset($this->args[0]) && $this->args[0] === 'snapshot') {
$snapshot = true;
}
if (!$snapshot && file_exists($this->Schema->path . DS . $this->params['file'])) {
$snapshot = true;
$prompt = __d('cake_console', "Schema file exists.\n [O]verwrite\n [S]napshot\n [Q]uit\nWould you like to do?");
$result = strtolower($this->in($prompt, array('o', 's', 'q'), 's'));
if ($result === 'q') {
return $this->_stop();
}
if ($result === 'o') {
$snapshot = false;
}
}
$cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', true);
$content = $this->Schema->read($options);
$content['file'] = $this->params['file'];
Configure::write('Cache.disable', $cacheDisable);
if ($snapshot === true) {
$Folder = new Folder($this->Schema->path);
$result = $Folder->read();
$numToUse = false;
if (isset($this->params['snapshot'])) {
$numToUse = $this->params['snapshot'];
}
$count = 0;
if (!empty($result[1])) {
foreach ($result[1] as $file) {
if (preg_match('/schema(?:[_\d]*)?\.php$/', $file)) {
$count++;
}
}
}
if ($numToUse !== false) {
if ($numToUse > $count) {
$count = $numToUse;
}
}
$fileName = rtrim($this->params['file'], '.php');
$content['file'] = $fileName . '_' . $count . '.php';
}
if ($this->Schema->write($content)) {
$this->out(__d('cake_console', 'Schema file: %s generated', $content['file']));
$this->_stop();
} else {
$this->err(__d('cake_console', 'Schema file: %s generated'));
$this->_stop();
}
}
/**
* Dump Schema object to sql file
* Use the `write` param to enable and control SQL file output location.
* Simply using -write will write the sql file to the same dir as the schema file.
* If -write contains a full path name the file will be saved there. If -write only
* contains no DS, that will be used as the file name, in the same dir as the schema file.
*
* @return string
*/
public function dump() {
$write = false;
$Schema = $this->Schema->load();
if (!$Schema) {
$this->err(__d('cake_console', 'Schema could not be loaded'));
$this->_stop();
}
if (!empty($this->params['write'])) {
if ($this->params['write'] == 1) {
$write = Inflector::underscore($this->Schema->name);
} else {
$write = $this->params['write'];
}
}
$db = ConnectionManager::getDataSource($this->Schema->connection);
$contents = "#" . $Schema->name . " sql generated on: " . date('Y-m-d H:i:s') . " : " . time() . "\n\n";
$contents .= $db->dropSchema($Schema) . "\n\n". $db->createSchema($Schema);
if ($write) {
if (strpos($write, '.sql') === false) {
$write .= '.sql';
}
if (strpos($write, DS) !== false) {
$File = new File($write, true);
} else {
$File = new File($this->Schema->path . DS . $write, true);
}
if ($File->write($contents)) {
$this->out(__d('cake_console', 'SQL dump file created in %s', $File->pwd()));
$this->_stop();
} else {
$this->err(__d('cake_console', 'SQL dump could not be created'));
$this->_stop();
}
}
$this->out($contents);
return $contents;
}
/**
* Run database create commands. Alias for run create.
*
* @return void
*/
public function create() {
list($Schema, $table) = $this->_loadSchema();
$this->_create($Schema, $table);
}
/**
* Run database create commands. Alias for run create.
*
* @return void
*/
public function update() {
list($Schema, $table) = $this->_loadSchema();
$this->_update($Schema, $table);
}
/**
* Prepares the Schema objects for database operations.
*
* @return void
*/
protected function _loadSchema() {
$name = $plugin = null;
if (!empty($this->params['name'])) {
$name = $this->params['name'];
}
if (!empty($this->params['plugin'])) {
$plugin = $this->params['plugin'];
}
if (!empty($this->params['dry'])) {
$this->_dry = true;
$this->out(__d('cake_console', 'Performing a dry run.'));
}
$options = array('name' => $name, 'plugin' => $plugin);
if (!empty($this->params['snapshot'])) {
$fileName = rtrim($this->Schema->file, '.php');
$options['file'] = $fileName . '_' . $this->params['snapshot'] . '.php';
}
$Schema = $this->Schema->load($options);
if (!$Schema) {
$this->err(__d('cake_console', '%s could not be loaded', $this->Schema->path . DS . $this->Schema->file));
$this->_stop();
}
$table = null;
if (isset($this->args[1])) {
$table = $this->args[1];
}
return array(&$Schema, $table);
}
/**
* Create database from Schema object
* Should be called via the run method
*
* @param CakeSchema $Schema
* @param string $table
* @return void
*/
protected function _create($Schema, $table = null) {
$db = ConnectionManager::getDataSource($this->Schema->connection);
$drop = $create = array();
if (!$table) {
foreach ($Schema->tables as $table => $fields) {
$drop[$table] = $db->dropSchema($Schema, $table);
$create[$table] = $db->createSchema($Schema, $table);
}
} elseif (isset($Schema->tables[$table])) {
$drop[$table] = $db->dropSchema($Schema, $table);
$create[$table] = $db->createSchema($Schema, $table);
}
if (empty($drop) || empty($create)) {
$this->out(__d('cake_console', 'Schema is up to date.'));
$this->_stop();
}
$this->out("\n" . __d('cake_console', 'The following table(s) will be dropped.'));
$this->out(array_keys($drop));
if ('y' == $this->in(__d('cake_console', 'Are you sure you want to drop the table(s)?'), array('y', 'n'), 'n')) {
$this->out(__d('cake_console', 'Dropping table(s).'));
$this->_run($drop, 'drop', $Schema);
}
$this->out("\n" . __d('cake_console', 'The following table(s) will be created.'));
$this->out(array_keys($create));
if ('y' == $this->in(__d('cake_console', 'Are you sure you want to create the table(s)?'), array('y', 'n'), 'y')) {
$this->out(__d('cake_console', 'Creating table(s).'));
$this->_run($create, 'create', $Schema);
}
$this->out(__d('cake_console', 'End create.'));
}
/**
* Update database with Schema object
* Should be called via the run method
*
* @param CakeSchema $Schema
* @param string $table
* @return void
*/
protected function _update(&$Schema, $table = null) {
$db = ConnectionManager::getDataSource($this->Schema->connection);
$this->out(__d('cake_console', 'Comparing Database to Schema...'));
$options = array();
if (isset($this->params['force'])) {
$options['models'] = false;
}
$Old = $this->Schema->read($options);
$compare = $this->Schema->compare($Old, $Schema);
$contents = array();
if (empty($table)) {
foreach ($compare as $table => $changes) {
$contents[$table] = $db->alterSchema(array($table => $changes), $table);
}
} elseif (isset($compare[$table])) {
$contents[$table] = $db->alterSchema(array($table => $compare[$table]), $table);
}
if (empty($contents)) {
$this->out(__d('cake_console', 'Schema is up to date.'));
$this->_stop();
}
$this->out("\n" . __d('cake_console', 'The following statements will run.'));
$this->out(array_map('trim', $contents));
if ('y' == $this->in(__d('cake_console', 'Are you sure you want to alter the tables?'), array('y', 'n'), 'n')) {
$this->out();
$this->out(__d('cake_console', 'Updating Database...'));
$this->_run($contents, 'update', $Schema);
}
$this->out(__d('cake_console', 'End update.'));
}
/**
* Runs sql from _create() or _update()
*
* @param array $contents
* @param string $event
* @param CakeSchema $Schema
* @return void
*/
protected function _run($contents, $event, &$Schema) {
if (empty($contents)) {
$this->err(__d('cake_console', 'Sql could not be run'));
return;
}
Configure::write('debug', 2);
$db = ConnectionManager::getDataSource($this->Schema->connection);
foreach ($contents as $table => $sql) {
if (empty($sql)) {
$this->out(__d('cake_console', '%s is up to date.', $table));
} else {
if ($this->_dry === true) {
$this->out(__d('cake_console', 'Dry run for %s :', $table));
$this->out($sql);
} else {
if (!$Schema->before(array($event => $table))) {
return false;
}
$error = null;
try {
$db->execute($sql);
} catch (PDOException $e) {
$error = $table . ': ' . $e->getMessage();
}
$Schema->after(array($event => $table, 'errors' => $error));
if (!empty($error)) {
$this->err($error);
} else {
$this->out(__d('cake_console', '%s updated.', $table));
}
}
}
}
}
/**
* get the option parser
*
* @return void
*/
public function getOptionParser() {
$plugin = array(
'help' => __d('cake_console', 'The plugin to use.'),
);
$connection = array(
'help' => __d('cake_console', 'Set the db config to use.'),
'default' => 'default'
);
$path = array(
'help' => __d('cake_console', 'Path to read and write schema.php'),
'default' => APP . 'Config' . DS . 'Schema'
);
$file = array(
'help' => __d('cake_console', 'File name to read and write.'),
'default' => 'schema.php'
);
$name = array(
'help' => __d('cake_console', 'Classname to use. If its Plugin.class, both name and plugin options will be set.')
);
$snapshot = array(
'short' => 's',
'help' => __d('cake_console', 'Snapshot number to use/make.')
);
$dry = array(
'help' => __d('cake_console', 'Perform a dry run on create and update commands. Queries will be output instead of run.'),
'boolean' => true
);
$force = array(
'short' => 'f',
'help' => __d('cake_console', 'Force "generate" to create a new schema'),
'boolean' => true
);
$write = array(
'help' => __d('cake_console', 'Write the dumped SQL to a file.')
);
$parser = parent::getOptionParser();
$parser->description(
__d('cake_console', 'The Schema Shell generates a schema object from the database and updates the database from the schema.')
)->addSubcommand('view', array(
'help' => __d('cake_console', 'Read and output the contents of a schema file'),
'parser' => array(
'options' => compact('plugin', 'path', 'file', 'name', 'connection'),
'arguments' => compact('name')
)
))->addSubcommand('generate', array(
'help' => __d('cake_console', 'Reads from --connection and writes to --path. Generate snapshots with -s'),
'parser' => array(
'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'snapshot', 'force'),
'arguments' => array(
'snapshot' => array('help' => __d('cake_console', 'Generate a snapshot.'))
)
)
))->addSubcommand('dump', array(
'help' => __d('cake_console', 'Dump database SQL based on a schema file to stdout.'),
'parser' => array(
'options' => compact('plugin', 'path', 'file', 'name', 'connection'),
'arguments' => compact('name')
)
))->addSubcommand('create', array(
'help' => __d('cake_console', 'Drop and create tables based on the schema file.'),
'parser' => array(
'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot'),
'args' => array(
'name' => array(
'help' => __d('cake_console', 'Name of schema to use.')
),
'table' => array(
'help' => __d('cake_console', 'Only create the specified table.')
)
)
)
))->addSubcommand('update', array(
'help' => __d('cake_console', 'Alter the tables based on the schema file.'),
'parser' => array(
'options' => compact('plugin', 'path', 'file', 'name', 'connection', 'dry', 'snapshot'),
'args' => array(
'name' => array(
'help' => __d('cake_console', 'Name of schema to use.')
),
'table' => array(
'help' => __d('cake_console', 'Only create the specified table.')
)
)
)
));
return $parser;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/SchemaShell.php | PHP | gpl3 | 15,156 |
<?php
/**
* The DbConfig Task handles creating and updating the database.php
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Task class for creating and updating the database configuration file.
*
* @package Cake.Console.Command.Task
*/
class DbConfigTask extends Shell {
/**
* path to CONFIG directory
*
* @var string
*/
public $path = null;
/**
* Default configuration settings to use
*
* @var array
*/
protected $_defaultConfig = array(
'name' => 'default',
'datasource'=> 'Database/Mysql',
'persistent'=> 'false',
'host'=> 'localhost',
'login'=> 'root',
'password'=> 'password',
'database'=> 'project_name',
'schema'=> null,
'prefix'=> null,
'encoding' => null,
'port' => null
);
/**
* String name of the database config class name.
* Used for testing.
*
* @var string
*/
public $databaseClassName = 'DATABASE_CONFIG';
/**
* initialization callback
*
* @return void
*/
public function initialize() {
$this->path = APP . 'Config' . DS;
}
/**
* Execution method always used for tasks
*
* @return void
*/
public function execute() {
if (empty($this->args)) {
$this->_interactive();
$this->_stop();
}
}
/**
* Interactive interface
*
* @return void
*/
protected function _interactive() {
$this->hr();
$this->out('Database Configuration:');
$this->hr();
$done = false;
$dbConfigs = array();
while ($done == false) {
$name = '';
while ($name == '') {
$name = $this->in(__d('cake_console', "Name:"), null, 'default');
if (preg_match('/[^a-z0-9_]/i', $name)) {
$name = '';
$this->out(__d('cake_console', 'The name may only contain unaccented latin characters, numbers or underscores'));
} else if (preg_match('/^[^a-z_]/i', $name)) {
$name = '';
$this->out(__d('cake_console', 'The name must start with an unaccented latin character or an underscore'));
}
}
$driver = $this->in(__d('cake_console', 'Driver:'), array('Mysql', 'Postgres', 'Sqlite', 'Sqlserver'), 'Mysql');
$persistent = $this->in(__d('cake_console', 'Persistent Connection?'), array('y', 'n'), 'n');
if (strtolower($persistent) == 'n') {
$persistent = 'false';
} else {
$persistent = 'true';
}
$host = '';
while ($host == '') {
$host = $this->in(__d('cake_console', 'Database Host:'), null, 'localhost');
}
$port = '';
while ($port == '') {
$port = $this->in(__d('cake_console', 'Port?'), null, 'n');
}
if (strtolower($port) == 'n') {
$port = null;
}
$login = '';
while ($login == '') {
$login = $this->in(__d('cake_console', 'User:'), null, 'root');
}
$password = '';
$blankPassword = false;
while ($password == '' && $blankPassword == false) {
$password = $this->in(__d('cake_console', 'Password:'));
if ($password == '') {
$blank = $this->in(__d('cake_console', 'The password you supplied was empty. Use an empty password?'), array('y', 'n'), 'n');
if ($blank == 'y') {
$blankPassword = true;
}
}
}
$database = '';
while ($database == '') {
$database = $this->in(__d('cake_console', 'Database Name:'), null, 'cake');
}
$prefix = '';
while ($prefix == '') {
$prefix = $this->in(__d('cake_console', 'Table Prefix?'), null, 'n');
}
if (strtolower($prefix) == 'n') {
$prefix = null;
}
$encoding = '';
while ($encoding == '') {
$encoding = $this->in(__d('cake_console', 'Table encoding?'), null, 'n');
}
if (strtolower($encoding) == 'n') {
$encoding = null;
}
$schema = '';
if ($driver == 'postgres') {
while ($schema == '') {
$schema = $this->in(__d('cake_console', 'Table schema?'), null, 'n');
}
}
if (strtolower($schema) == 'n') {
$schema = null;
}
$config = compact('name', 'driver', 'persistent', 'host', 'login', 'password', 'database', 'prefix', 'encoding', 'port', 'schema');
while ($this->_verify($config) == false) {
$this->_interactive();
}
$dbConfigs[] = $config;
$doneYet = $this->in(__d('cake_console', 'Do you wish to add another database configuration?'), null, 'n');
if (strtolower($doneYet == 'n')) {
$done = true;
}
}
$this->bake($dbConfigs);
config('database');
return true;
}
/**
* Output verification message and bake if it looks good
*
* @param array $config
* @return boolean True if user says it looks good, false otherwise
*/
protected function _verify($config) {
$config = array_merge($this->_defaultConfig, $config);
extract($config);
$this->out();
$this->hr();
$this->out(__d('cake_console', 'The following database configuration will be created:'));
$this->hr();
$this->out(__d('cake_console', "Name: %s", $name));
$this->out(__d('cake_console', "Driver: %s", $driver));
$this->out(__d('cake_console', "Persistent: %s", $persistent));
$this->out(__d('cake_console', "Host: %s", $host));
if ($port) {
$this->out(__d('cake_console', "Port: %s", $port));
}
$this->out(__d('cake_console', "User: %s", $login));
$this->out(__d('cake_console', "Pass: %s", str_repeat('*', strlen($password))));
$this->out(__d('cake_console', "Database: %s", $database));
if ($prefix) {
$this->out(__d('cake_console', "Table prefix: %s", $prefix));
}
if ($schema) {
$this->out(__d('cake_console', "Schema: %s", $schema));
}
if ($encoding) {
$this->out(__d('cake_console', "Encoding: %s", $encoding));
}
$this->hr();
$looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y', 'n'), 'y');
if (strtolower($looksGood) == 'y') {
return $config;
}
return false;
}
/**
* Assembles and writes database.php
*
* @param array $configs Configuration settings to use
* @return boolean Success
*/
public function bake($configs) {
if (!is_dir($this->path)) {
$this->err(__d('cake_console', '%s not found', $this->path));
return false;
}
$filename = $this->path . 'database.php';
$oldConfigs = array();
if (file_exists($filename)) {
config('database');
$db = new $this->databaseClassName;
$temp = get_class_vars(get_class($db));
foreach ($temp as $configName => $info) {
$info = array_merge($this->_defaultConfig, $info);
if (!isset($info['schema'])) {
$info['schema'] = null;
}
if (!isset($info['encoding'])) {
$info['encoding'] = null;
}
if (!isset($info['port'])) {
$info['port'] = null;
}
if ($info['persistent'] === false) {
$info['persistent'] = 'false';
} else {
$info['persistent'] = ($info['persistent'] == true) ? 'true' : 'false';
}
$oldConfigs[] = array(
'name' => $configName,
'driver' => $info['driver'],
'persistent' => $info['persistent'],
'host' => $info['host'],
'port' => $info['port'],
'login' => $info['login'],
'password' => $info['password'],
'database' => $info['database'],
'prefix' => $info['prefix'],
'schema' => $info['schema'],
'encoding' => $info['encoding']
);
}
}
foreach ($oldConfigs as $key => $oldConfig) {
foreach ($configs as $key1 => $config) {
if ($oldConfig['name'] == $config['name']) {
unset($oldConfigs[$key]);
}
}
}
$configs = array_merge($oldConfigs, $configs);
$out = "<?php\n";
$out .= "class DATABASE_CONFIG {\n\n";
foreach ($configs as $config) {
$config = array_merge($this->_defaultConfig, $config);
extract($config);
$out .= "\tpublic \${$name} = array(\n";
$out .= "\t\t'datasource' => 'Database/{$driver}',\n";
$out .= "\t\t'persistent' => {$persistent},\n";
$out .= "\t\t'host' => '{$host}',\n";
if ($port) {
$out .= "\t\t'port' => {$port},\n";
}
$out .= "\t\t'login' => '{$login}',\n";
$out .= "\t\t'password' => '{$password}',\n";
$out .= "\t\t'database' => '{$database}',\n";
if ($schema) {
$out .= "\t\t'schema' => '{$schema}',\n";
}
if ($prefix) {
$out .= "\t\t'prefix' => '{$prefix}',\n";
}
if ($encoding) {
$out .= "\t\t'encoding' => '{$encoding}'\n";
}
$out .= "\t);\n";
}
$out .= "}\n";
$filename = $this->path . 'database.php';
return $this->createFile($filename, $out);
}
/**
* Get a user specified Connection name
*
* @return void
*/
public function getConfig() {
App::uses('ConnectionManager', 'Model');
$configs = ConnectionManager::enumConnectionObjects();
$useDbConfig = key($configs);
if (!is_array($configs) || empty($configs)) {
return $this->execute();
}
$connections = array_keys($configs);
if (count($connections) > 1) {
$useDbConfig = $this->in(__d('cake_console', 'Use Database Config') .':', $connections, $useDbConfig);
}
return $useDbConfig;
}
/**
* get the option parser
*
* @return ConsoleOptionParser
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
return $parser->description(
__d('cake_console', 'Bake new database configuration settings.')
);
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/Task/DbConfigTask.php | PHP | gpl3 | 9,528 |
<?php
/**
* The FixtureTask handles creating and updating fixture files.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('BakeTask', 'Console/Command/Task');
App::uses('Model', 'Model');
/**
* Task class for creating and updating fixtures files.
*
* @package Cake.Console.Command.Task
*/
class FixtureTask extends BakeTask {
/**
* Tasks to be loaded by this Task
*
* @var array
*/
public $tasks = array('DbConfig', 'Model', 'Template');
/**
* path to fixtures directory
*
* @var string
*/
public $path = null;
/**
* Schema instance
*
* @var CakeSchema
*/
protected $_Schema = null;
/**
* Override initialize
*
* @param ConsoleOutput $stdout A ConsoleOutput object for stdout.
* @param ConsoleOutput $stderr A ConsoleOutput object for stderr.
* @param ConsoleInput $stdin A ConsoleInput object for stdin.
*/
public function __construct($stdout = null, $stderr = null, $stdin = null) {
parent::__construct($stdout, $stderr, $stdin);
$this->path = APP . 'Test' . DS . 'Fixture' . DS;
}
/**
* get the option parser.
*
* @return void
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
return $parser->description(
__d('cake_console', 'Generate fixtures for use with the test suite. You can use `bake fixture all` to bake all fixtures.')
)->addArgument('name', array(
'help' => __d('cake_console', 'Name of the fixture to bake. Can use Plugin.name to bake plugin fixtures.')
))->addOption('count', array(
'help' => __d('cake_console', 'When using generated data, the number of records to include in the fixture(s).'),
'short' => 'n',
'default' => 10
))->addOption('connection', array(
'help' => __d('cake_console', 'Which database configuration to use for baking.'),
'short' => 'c',
'default' => 'default'
))->addOption('plugin', array(
'help' => __d('cake_console', 'CamelCased name of the plugin to bake fixtures for.'),
'short' => 'p',
))->addOption('records', array(
'help' => __d('cake_console', 'Used with --count and <name>/all commands to pull [n] records from the live tables, where [n] is either --count or the default of 10'),
'short' => 'r',
'boolean' => true
))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));;
}
/**
* Execution method always used for tasks
* Handles dispatching to interactive, named, or all processeses.
*
* @return void
*/
public function execute() {
parent::execute();
if (empty($this->args)) {
$this->_interactive();
}
if (isset($this->args[0])) {
$this->interactive = false;
if (!isset($this->connection)) {
$this->connection = 'default';
}
if (strtolower($this->args[0]) == 'all') {
return $this->all();
}
$model = $this->_modelName($this->args[0]);
$this->bake($model);
}
}
/**
* Bake All the Fixtures at once. Will only bake fixtures for models that exist.
*
* @return void
*/
public function all() {
$this->interactive = false;
$this->Model->interactive = false;
$tables = $this->Model->listAll($this->connection, false);
foreach ($tables as $table) {
$model = $this->_modelName($table);
$this->bake($model);
}
}
/**
* Interactive baking function
*
* @return void
*/
protected function _interactive() {
$this->DbConfig->interactive = $this->Model->interactive = $this->interactive = true;
$this->hr();
$this->out(__d('cake_console', "Bake Fixture\nPath: %s", $this->path));
$this->hr();
if (!isset($this->connection)) {
$this->connection = $this->DbConfig->getConfig();
}
$modelName = $this->Model->getName($this->connection);
$useTable = $this->Model->getTable($modelName, $this->connection);
$importOptions = $this->importOptions($modelName);
$this->bake($modelName, $useTable, $importOptions);
}
/**
* Interacts with the User to setup an array of import options. For a fixture.
*
* @param string $modelName Name of model you are dealing with.
* @return array Array of import options.
*/
public function importOptions($modelName) {
$options = array();
$doSchema = $this->in(__d('cake_console', 'Would you like to import schema for this fixture?'), array('y', 'n'), 'n');
if ($doSchema == 'y') {
$options['schema'] = $modelName;
}
$doRecords = $this->in(__d('cake_console', 'Would you like to use record importing for this fixture?'), array('y', 'n'), 'n');
if ($doRecords == 'y') {
$options['records'] = true;
}
if ($doRecords == 'n') {
$prompt = __d('cake_console', "Would you like to build this fixture with data from %s's table?", $modelName);
$fromTable = $this->in($prompt, array('y', 'n'), 'n');
if (strtolower($fromTable) == 'y') {
$options['fromTable'] = true;
}
}
return $options;
}
/**
* Assembles and writes a Fixture file
*
* @param string $model Name of model to bake.
* @param string $useTable Name of table to use.
* @param array $importOptions Options for public $import
* @return string Baked fixture content
*/
public function bake($model, $useTable = false, $importOptions = array()) {
App::uses('CakeSchema', 'Model');
$table = $schema = $records = $import = $modelImport = null;
$importBits = array();
if (!$useTable) {
$useTable = Inflector::tableize($model);
} elseif ($useTable != Inflector::tableize($model)) {
$table = $useTable;
}
if (!empty($importOptions)) {
if (isset($importOptions['schema'])) {
$modelImport = true;
$importBits[] = "'model' => '{$importOptions['schema']}'";
}
if (isset($importOptions['records'])) {
$importBits[] = "'records' => true";
}
if ($this->connection != 'default') {
$importBits[] .= "'connection' => '{$this->connection}'";
}
if (!empty($importBits)) {
$import = sprintf("array(%s)", implode(', ', $importBits));
}
}
$this->_Schema = new CakeSchema();
$data = $this->_Schema->read(array('models' => false, 'connection' => $this->connection));
if (!isset($data['tables'][$useTable])) {
$this->err('Could not find your selected table ' . $useTable);
return false;
}
$tableInfo = $data['tables'][$useTable];
if (is_null($modelImport)) {
$schema = $this->_generateSchema($tableInfo);
}
if (!isset($importOptions['records']) && !isset($importOptions['fromTable'])) {
$recordCount = 1;
if (isset($this->params['count'])) {
$recordCount = $this->params['count'];
}
$records = $this->_makeRecordString($this->_generateRecords($tableInfo, $recordCount));
}
if (isset($this->params['records']) || isset($importOptions['fromTable'])) {
$records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
}
$out = $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import', 'fields'));
return $out;
}
/**
* Generate the fixture file, and write to disk
*
* @param string $model name of the model being generated
* @param string $otherVars Contents of the fixture file.
* @return string Content saved into fixture file.
*/
public function generateFixtureFile($model, $otherVars) {
$defaults = array('table' => null, 'schema' => null, 'records' => null, 'import' => null, 'fields' => null);
$vars = array_merge($defaults, $otherVars);
$path = $this->getPath();
$filename = Inflector::camelize($model) . 'Fixture.php';
$this->Template->set('model', $model);
$this->Template->set($vars);
$content = $this->Template->generate('classes', 'fixture');
$this->out("\n" . __d('cake_console', 'Baking test fixture for %s...', $model), 1, Shell::QUIET);
$this->createFile($path . $filename, $content);
return $content;
}
/**
* Get the path to the fixtures.
*
* @return string Path for the fixtures
*/
public function getPath() {
$path = $this->path;
if (isset($this->plugin)) {
$path = $this->_pluginPath($this->plugin) . 'Test' . DS . 'Fixture' . DS;
}
return $path;
}
/**
* Generates a string representation of a schema.
*
* @param array $tableInfo Table schema array
* @return string fields definitions
*/
protected function _generateSchema($tableInfo) {
$schema = $this->_Schema->generateTable('f', $tableInfo);
return substr($schema, 10, -2);
}
/**
* Generate String representation of Records
*
* @param array $tableInfo Table schema array
* @param integer $recordCount
* @return array Array of records to use in the fixture.
*/
protected function _generateRecords($tableInfo, $recordCount = 1) {
$records = array();
for ($i = 0; $i < $recordCount; $i++) {
$record = array();
foreach ($tableInfo as $field => $fieldInfo) {
if (empty($fieldInfo['type'])) {
continue;
}
switch ($fieldInfo['type']) {
case 'integer':
case 'float':
$insert = $i + 1;
break;
case 'string':
case 'binary':
$isPrimaryUuid = (
isset($fieldInfo['key']) && strtolower($fieldInfo['key']) == 'primary' &&
isset($fieldInfo['length']) && $fieldInfo['length'] == 36
);
if ($isPrimaryUuid) {
$insert = String::uuid();
} else {
$insert = "Lorem ipsum dolor sit amet";
if (!empty($fieldInfo['length'])) {
$insert = substr($insert, 0, (int)$fieldInfo['length'] - 2);
}
}
break;
case 'timestamp':
$insert = time();
break;
case 'datetime':
$insert = date('Y-m-d H:i:s');
break;
case 'date':
$insert = date('Y-m-d');
break;
case 'time':
$insert = date('H:i:s');
break;
case 'boolean':
$insert = 1;
break;
case 'text':
$insert = "Lorem ipsum dolor sit amet, aliquet feugiat.";
$insert .= " Convallis morbi fringilla gravida,";
$insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
$insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
$insert .= " vestibulum massa neque ut et, id hendrerit sit,";
$insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
$insert .= " duis vestibulum nunc mattis convallis.";
break;
}
$record[$field] = $insert;
}
$records[] = $record;
}
return $records;
}
/**
* Convert a $records array into a a string.
*
* @param array $records Array of records to be converted to string
* @return string A string value of the $records array.
*/
protected function _makeRecordString($records) {
$out = "array(\n";
foreach ($records as $record) {
$values = array();
foreach ($record as $field => $value) {
$val = var_export($value, true);
$values[] = "\t\t\t'$field' => $val";
}
$out .= "\t\tarray(\n";
$out .= implode(",\n", $values);
$out .= "\n\t\t),\n";
}
$out .= "\t)";
return $out;
}
/**
* Interact with the user to get a custom SQL condition and use that to extract data
* to build a fixture.
*
* @param string $modelName name of the model to take records from.
* @param string $useTable Name of table to use.
* @return array Array of records.
*/
protected function _getRecordsFromTable($modelName, $useTable = null) {
if ($this->interactive) {
$condition = null;
$prompt = __d('cake_console', "Please provide a SQL fragment to use as conditions\nExample: WHERE 1=1");
while (!$condition) {
$condition = $this->in($prompt, null, 'WHERE 1=1');
}
$prompt = __d('cake_console', "How many records do you want to import?");
$recordCount = $this->in($prompt, null, 10);
} else {
$condition = 'WHERE 1=1';
$recordCount = (isset($this->params['count']) ? $this->params['count'] : 10);
}
$modelObject = new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
$records = $modelObject->find('all', array(
'conditions' => $condition,
'recursive' => -1,
'limit' => $recordCount
));
$db = $modelObject->getDatasource();
$schema = $modelObject->schema(true);
$out = array();
foreach ($records as $record) {
$row = array();
foreach ($record[$modelObject->alias] as $field => $value) {
if ($schema[$field]['type'] === 'boolean') {
$value = (int)(bool)$value;
}
$row[$field] = $value;
}
$out[] = $row;
}
return $out;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/Task/FixtureTask.php | PHP | gpl3 | 12,680 |
<?php
/**
* The Project Task handles creating the base application
*
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('File', 'Utility');
App::uses('Folder', 'Utility');
App::uses('String', 'Utility');
App::uses('Security', 'Utility');
/**
* Task class for creating new project apps and plugins
*
* @package Cake.Console.Command.Task
*/
class ProjectTask extends Shell {
/**
* configs path (used in testing).
*
* @var string
*/
public $configPath = null;
/**
* Checks that given project path does not already exist, and
* finds the app directory in it. Then it calls bake() with that information.
*
* @return mixed
*/
public function execute() {
$project = null;
if (isset($this->args[0])) {
$project = $this->args[0];
}
while (!$project) {
$prompt = __d('cake_console', "What is the path to the project you want to bake?");
$project = $this->in($prompt, null, APP . 'myapp');
}
if ($project && !Folder::isAbsolute($project) && isset($_SERVER['PWD'])) {
$project = $_SERVER['PWD'] . DS . $project;
}
$response = false;
while ($response == false && is_dir($project) === true && file_exists($project . 'Config' . 'core.php')) {
$prompt = __d('cake_console', '<warning>A project already exists in this location:</warning> %s Overwrite?', $project);
$response = $this->in($prompt, array('y','n'), 'n');
if (strtolower($response) === 'n') {
$response = $project = false;
}
}
$success = true;
if ($this->bake($project)) {
$path = Folder::slashTerm($project);
if ($this->createHome($path)) {
$this->out(__d('cake_console', ' * Welcome page created'));
} else {
$this->err(__d('cake_console', 'The Welcome page was <error>NOT</error> created'));
$success = false;
}
if ($this->securitySalt($path) === true) {
$this->out(__d('cake_console', ' * Random hash key created for \'Security.salt\''));
} else {
$this->err(__d('cake_console', 'Unable to generate random hash for \'Security.salt\', you should change it in %s', APP . 'Config' . DS . 'core.php'));
$success = false;
}
if ($this->securityCipherSeed($path) === true) {
$this->out(__d('cake_console', ' * Random seed created for \'Security.cipherSeed\''));
} else {
$this->err(__d('cake_console', 'Unable to generate random seed for \'Security.cipherSeed\', you should change it in %s', APP . 'Config' . DS . 'core.php'));
$success = false;
}
if ($this->consolePath($path) === true) {
$this->out(__d('cake_console', ' * app/Console/cake.php path set.'));
} else {
$this->err(__d('cake_console', 'Unable to set console path for app/Console.'));
$success = false;
}
$hardCode = false;
if ($this->cakeOnIncludePath()) {
$this->out(__d('cake_console', '<info>CakePHP is on your `include_path`. CAKE_CORE_INCLUDE_PATH will be set, but commented out.</info>'));
} else {
$this->out(__d('cake_console', '<warning>CakePHP is not on your `include_path`, CAKE_CORE_INCLUDE_PATH will be hard coded.</warning>'));
$this->out(__d('cake_console', 'You can fix this by adding CakePHP to your `include_path`.'));
$hardCode = true;
}
$success = $this->corePath($path, $hardCode) === true;
if ($success) {
$this->out(__d('cake_console', ' * CAKE_CORE_INCLUDE_PATH set to %s in webroot/index.php', CAKE_CORE_INCLUDE_PATH));
$this->out(__d('cake_console', ' * CAKE_CORE_INCLUDE_PATH set to %s in webroot/test.php', CAKE_CORE_INCLUDE_PATH));
} else {
$this->err(__d('cake_console', 'Unable to set CAKE_CORE_INCLUDE_PATH, you should change it in %s', $path . 'webroot' .DS .'index.php'));
$success = false;
}
if ($success && $hardCode) {
$this->out(__d('cake_console', ' * <warning>Remember to check these values after moving to production server</warning>'));
}
$Folder = new Folder($path);
if (!$Folder->chmod($path . 'tmp', 0777)) {
$this->err(__d('cake_console', 'Could not set permissions on %s', $path . DS .'tmp'));
$this->out(__d('cake_console', 'chmod -R 0777 %s', $path . DS .'tmp'));
$success = false;
}
if ($success) {
$this->out(__d('cake_console', '<success>Project baked successfully!</success>'));
} else {
$this->out(__d('cake_console', 'Project baked but with <warning>some issues.</warning>.'));
}
return $path;
}
}
/**
* Checks PHP's include_path for CakePHP.
*
* @return boolean Indicates whether or not CakePHP exists on include_path
*/
public function cakeOnIncludePath() {
$paths = explode(PATH_SEPARATOR, ini_get('include_path'));
foreach ($paths as $path) {
if (file_exists($path . DS . 'Cake' . DS . 'bootstrap.php')) {
return true;
}
}
return false;
}
/**
* Looks for a skeleton template of a Cake application,
* and if not found asks the user for a path. When there is a path
* this method will make a deep copy of the skeleton to the project directory.
* A default home page will be added, and the tmp file storage will be chmod'ed to 0777.
*
* @param string $path Project path
* @param string $skel Path to copy from
* @param string $skip array of directories to skip when copying
* @return mixed
*/
public function bake($path, $skel = null, $skip = array('empty')) {
if (!$skel && !empty($this->params['skel'])) {
$skel = $this->params['skel'];
}
while (!$skel) {
$skel = $this->in(
__d('cake_console', "What is the path to the directory layout you wish to copy?"),
null,
CAKE . 'Console' . DS . 'Templates' . DS . 'skel'
);
if (!$skel) {
$this->err(__d('cake_console', 'The directory path you supplied was empty. Please try again.'));
} else {
while (is_dir($skel) === false) {
$skel = $this->in(
__d('cake_console', 'Directory path does not exist please choose another:'),
null,
CAKE . 'Console' . DS . 'Templates' . DS . 'skel'
);
}
}
}
$app = basename($path);
$this->out(__d('cake_console', '<info>Skel Directory</info>: ') . $skel);
$this->out(__d('cake_console', '<info>Will be copied to</info>: ') . $path);
$this->hr();
$looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y', 'n', 'q'), 'y');
switch (strtolower($looksGood)) {
case 'y':
$Folder = new Folder($skel);
if (!empty($this->params['empty'])) {
$skip = array();
}
if ($Folder->copy(array('to' => $path, 'skip' => $skip))) {
$this->hr();
$this->out(__d('cake_console', '<success>Created:</success> %s in %s', $app, $path));
$this->hr();
} else {
$this->err(__d('cake_console', "<error>Could not create</error> '%s' properly.", $app));
return false;
}
foreach ($Folder->messages() as $message) {
$this->out(String::wrap(' * ' . $message), 1, Shell::VERBOSE);
}
return true;
case 'n':
unset($this->args[0]);
$this->execute();
return false;
case 'q':
$this->out(__d('cake_console', '<error>Bake Aborted.</error>'));
return false;
}
}
/**
* Writes a file with a default home page to the project.
*
* @param string $dir Path to project
* @return boolean Success
*/
public function createHome($dir) {
$app = basename($dir);
$path = $dir . 'View' . DS . 'Pages' . DS;
$source = CAKE . 'Console' . DS . 'Templates' . DS .'default' . DS . 'views' . DS . 'home.ctp';
include($source);
return $this->createFile($path.'home.ctp', $output);
}
/**
* Generates the correct path to the CakePHP libs that are generating the project
* and points app/console/cake.php to the right place
*
* @param string $path Project path.
* @return boolean success
*/
public function consolePath($path) {
$File = new File($path . 'Console' . DS . 'cake.php');
$contents = $File->read();
if (preg_match('/(__CAKE_PATH__)/', $contents, $match)) {
$root = strpos(CAKE_CORE_INCLUDE_PATH, '/') === 0 ? " \$ds . '" : "'";
$replacement = $root . str_replace(DS, "' . \$ds . '", trim(CAKE_CORE_INCLUDE_PATH, DS)) . "'";
$result = str_replace($match[0], $replacement, $contents);
if ($File->write($result)) {
return true;
}
return false;
}
return false;
}
/**
* Generates and writes 'Security.salt'
*
* @param string $path Project path
* @return boolean Success
*/
public function securitySalt($path) {
$File = new File($path . 'Config' . DS . 'core.php');
$contents = $File->read();
if (preg_match('/([\s]*Configure::write\(\'Security.salt\',[\s\'A-z0-9]*\);)/', $contents, $match)) {
$string = Security::generateAuthKey();
$result = str_replace($match[0], "\t" . 'Configure::write(\'Security.salt\', \''.$string.'\');', $contents);
if ($File->write($result)) {
return true;
}
return false;
}
return false;
}
/**
* Generates and writes 'Security.cipherSeed'
*
* @param string $path Project path
* @return boolean Success
*/
public function securityCipherSeed($path) {
$File = new File($path . 'Config' . DS . 'core.php');
$contents = $File->read();
if (preg_match('/([\s]*Configure::write\(\'Security.cipherSeed\',[\s\'A-z0-9]*\);)/', $contents, $match)) {
if (!class_exists('Security')) {
require CAKE . 'Utility' . DS . 'security.php';
}
$string = substr(bin2hex(Security::generateAuthKey()), 0, 30);
$result = str_replace($match[0], "\t" . 'Configure::write(\'Security.cipherSeed\', \''.$string.'\');', $contents);
if ($File->write($result)) {
return true;
}
return false;
}
return false;
}
/**
* Generates and writes CAKE_CORE_INCLUDE_PATH
*
* @param string $path Project path
* @param boolean $hardCode Wether or not define calls should be hardcoded.
* @return boolean Success
*/
public function corePath($path, $hardCode = true) {
if (dirname($path) !== CAKE_CORE_INCLUDE_PATH) {
$filename = $path . 'webroot' . DS . 'index.php';
if (!$this->_replaceCorePath($filename, $hardCode)) {
return false;
}
$filename = $path . 'webroot' . DS . 'test.php';
if (!$this->_replaceCorePath($filename, $hardCode)) {
return false;
}
return true;
}
}
/**
* Replaces the __CAKE_PATH__ placeholder in the template files.
*
* @param string $filename The filename to operate on.
* @param boolean $hardCode Whether or not the define should be uncommented.
* @return boolean Success
*/
protected function _replaceCorePath($filename, $hardCode) {
$contents = file_get_contents($filename);
$root = strpos(CAKE_CORE_INCLUDE_PATH, '/') === 0 ? " DS . '" : "'";
$corePath = $root . str_replace(DS, "' . DS . '", trim(CAKE_CORE_INCLUDE_PATH, DS)) . "'";
$result = str_replace('__CAKE_PATH__', $corePath, $contents, $count);
if ($hardCode) {
$result = str_replace('//define(\'CAKE_CORE', 'define(\'CAKE_CORE', $result);
}
if (!file_put_contents($filename, $result)) {
return false;
}
if ($count == 0) {
return false;
}
return true;
}
/**
* Enables Configure::read('Routing.prefixes') in /app/Config/core.php
*
* @param string $name Name to use as admin routing
* @return boolean Success
*/
public function cakeAdmin($name) {
$path = (empty($this->configPath)) ? APP . 'Config' . DS : $this->configPath;
$File = new File($path . 'core.php');
$contents = $File->read();
if (preg_match('%(\s*[/]*Configure::write\(\'Routing.prefixes\',[\s\'a-z,\)\(]*\);)%', $contents, $match)) {
$result = str_replace($match[0], "\n" . 'Configure::write(\'Routing.prefixes\', array(\''.$name.'\'));', $contents);
if ($File->write($result)) {
Configure::write('Routing.prefixes', array($name));
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* Checks for Configure::read('Routing.prefixes') and forces user to input it if not enabled
*
* @return string Admin route to use
*/
public function getPrefix() {
$admin = '';
$prefixes = Configure::read('Routing.prefixes');
if (!empty($prefixes)) {
if (count($prefixes) == 1) {
return $prefixes[0] . '_';
}
if ($this->interactive) {
$this->out();
$this->out(__d('cake_console', 'You have more than one routing prefix configured'));
}
$options = array();
foreach ($prefixes as $i => $prefix) {
$options[] = $i + 1;
if ($this->interactive) {
$this->out($i + 1 . '. ' . $prefix);
}
}
$selection = $this->in(__d('cake_console', 'Please choose a prefix to bake with.'), $options, 1);
return $prefixes[$selection - 1] . '_';
}
if ($this->interactive) {
$this->hr();
$this->out(__d('cake_console', 'You need to enable Configure::write(\'Routing.prefixes\',array(\'admin\')) in /app/Config/core.php to use prefix routing.'));
$this->out(__d('cake_console', 'What would you like the prefix route to be?'));
$this->out(__d('cake_console', 'Example: www.example.com/admin/controller'));
while ($admin == '') {
$admin = $this->in(__d('cake_console', 'Enter a routing prefix:'), null, 'admin');
}
if ($this->cakeAdmin($admin) !== true) {
$this->out(__d('cake_console', '<error>Unable to write to</error> /app/Config/core.php.'));
$this->out(__d('cake_console', 'You need to enable Configure::write(\'Routing.prefixes\',array(\'admin\')) in /app/Config/core.php to use prefix routing.'));
$this->_stop();
}
return $admin . '_';
}
return '';
}
/**
* get the option parser.
*
* @return ConsoleOptionParser
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
return $parser->description(
__d('cake_console', 'Generate a new CakePHP project skeleton.')
)->addArgument('name', array(
'help' => __d('cake_console', 'Application directory to make, if it starts with "/" the path is absolute.')
))->addOption('empty', array(
'help' => __d('cake_console', 'Create empty files in each of the directories. Good if you are using git')
))->addOption('skel', array(
'default' => current(App::core('Console')) . 'Templates' . DS . 'skel',
'help' => __d('cake_console', 'The directory layout to use for the new application skeleton. Defaults to cake/Console/Templates/skel of CakePHP used to create the project.')
));
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/Task/ProjectTask.php | PHP | gpl3 | 14,607 |
<?php
/**
* Template Task can generate templated output Used in other Tasks
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Folder', 'Utility');
/**
* Template Task can generate templated output Used in other Tasks.
* Acts like a simplified View class.
*
* @package Cake.Console.Command.Task
*/
class TemplateTask extends Shell {
/**
* variables to add to template scope
*
* @var array
*/
public $templateVars = array();
/**
* Paths to look for templates on.
* Contains a list of $theme => $path
*
* @var array
*/
public $templatePaths = array();
/**
* Initialize callback. Setup paths for the template task.
*
* @return void
*/
public function initialize() {
$this->templatePaths = $this->_findThemes();
}
/**
* Find the paths to all the installed shell themes in the app.
*
* Bake themes are directories not named `skel` inside a `Console/Templates` path.
*
* @return array Array of bake themes that are installed.
*/
protected function _findThemes() {
$paths = App::path('Console');
$core = current(App::core('Console'));
$separator = DS === '/' ? '/' : '\\\\';
$core = preg_replace('#shells' . $separator . '$#', '', $core);
$Folder = new Folder($core . 'Templates' . DS . 'default');
$contents = $Folder->read();
$themeFolders = $contents[0];
$plugins = App::objects('plugin');
foreach ($plugins as $plugin) {
$paths[] = $this->_pluginPath($plugin) . 'Console' . DS;
}
$paths[] = $core;
// TEMPORARY TODO remove when all paths are DS terminated
foreach ($paths as $i => $path) {
$paths[$i] = rtrim($path, DS) . DS;
}
$themes = array();
foreach ($paths as $path) {
$Folder = new Folder($path . 'Templates', false);
$contents = $Folder->read();
$subDirs = $contents[0];
foreach ($subDirs as $dir) {
if (empty($dir) || preg_match('@^skel$|_skel$@', $dir)) {
continue;
}
$Folder = new Folder($path . 'Templates' . DS . $dir);
$contents = $Folder->read();
$subDirs = $contents[0];
if (array_intersect($contents[0], $themeFolders)) {
$templateDir = $path . 'Templates' . DS . $dir . DS;
$themes[$dir] = $templateDir;
}
}
}
return $themes;
}
/**
* Set variable values to the template scope
*
* @param string|array $one A string or an array of data.
* @param mixed $two Value in case $one is a string (which then works as the key).
* Unused if $one is an associative array, otherwise serves as the values to $one's keys.
* @return void
*/
public function set($one, $two = null) {
if (is_array($one)) {
if (is_array($two)) {
$data = array_combine($one, $two);
} else {
$data = $one;
}
} else {
$data = array($one => $two);
}
if ($data == null) {
return false;
}
$this->templateVars = $data + $this->templateVars;
}
/**
* Runs the template
*
* @param string $directory directory / type of thing you want
* @param string $filename template name
* @param array $vars Additional vars to set to template scope.
* @return string contents of generated code template
*/
public function generate($directory, $filename, $vars = null) {
if ($vars !== null) {
$this->set($vars);
}
if (empty($this->templatePaths)) {
$this->initialize();
}
$themePath = $this->getThemePath();
$templateFile = $this->_findTemplate($themePath, $directory, $filename);
if ($templateFile) {
extract($this->templateVars);
ob_start();
ob_implicit_flush(0);
include($templateFile);
$content = ob_get_clean();
return $content;
}
return '';
}
/**
* Find the theme name for the current operation.
* If there is only one theme in $templatePaths it will be used.
* If there is a -theme param in the cli args, it will be used.
* If there is more than one installed theme user interaction will happen
*
* @return string returns the path to the selected theme.
*/
public function getThemePath() {
if (count($this->templatePaths) == 1) {
$paths = array_values($this->templatePaths);
return $paths[0];
}
if (!empty($this->params['theme']) && isset($this->templatePaths[$this->params['theme']])) {
return $this->templatePaths[$this->params['theme']];
}
$this->hr();
$this->out(__d('cake_console', 'You have more than one set of templates installed.'));
$this->out(__d('cake_console', 'Please choose the template set you wish to use:'));
$this->hr();
$i = 1;
$indexedPaths = array();
foreach ($this->templatePaths as $key => $path) {
$this->out($i . '. ' . $key);
$indexedPaths[$i] = $path;
$i++;
}
$index = $this->in(__d('cake_console', 'Which bake theme would you like to use?'), range(1, $i - 1), 1);
$themeNames = array_keys($this->templatePaths);
$this->params['theme'] = $themeNames[$index - 1];
return $indexedPaths[$index];
}
/**
* Find a template inside a directory inside a path.
* Will scan all other theme dirs if the template is not found in the first directory.
*
* @param string $path The initial path to look for the file on. If it is not found fallbacks will be used.
* @param string $directory Subdirectory to look for ie. 'views', 'objects'
* @param string $filename lower_case_underscored filename you want.
* @return string filename will exit program if template is not found.
*/
protected function _findTemplate($path, $directory, $filename) {
$themeFile = $path . $directory . DS . $filename . '.ctp';
if (file_exists($themeFile)) {
return $themeFile;
}
foreach ($this->templatePaths as $path) {
$templatePath = $path . $directory . DS . $filename . '.ctp';
if (file_exists($templatePath)) {
return $templatePath;
}
}
$this->err(__d('cake_console', 'Could not find template for %s', $filename));
return false;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/Task/TemplateTask.php | PHP | gpl3 | 6,250 |
<?php
/**
* The Plugin Task handles creating an empty plugin, ready to be used
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('File', 'Utility');
App::uses('Folder', 'Utility');
/**
* Task class for creating a plugin
*
* @package Cake.Console.Command.Task
*/
class PluginTask extends Shell {
/**
* path to plugins directory
*
* @var array
*/
public $path = null;
/**
* initialize
*
* @return void
*/
public function initialize() {
$this->path = current(App::path('plugins'));
}
/**
* Execution method always used for tasks
*
* @return void
*/
public function execute() {
if (isset($this->args[0])) {
$plugin = Inflector::camelize($this->args[0]);
$pluginPath = $this->_pluginPath($plugin);
if (is_dir($pluginPath)) {
$this->out(__d('cake_console', 'Plugin: %s', $plugin));
$this->out(__d('cake_console', 'Path: %s', $pluginPath));
} else {
$this->_interactive($plugin);
}
} else {
return $this->_interactive();
}
}
/**
* Interactive interface
*
* @param string $plugin
* @return void
*/
protected function _interactive($plugin = null) {
while ($plugin === null) {
$plugin = $this->in(__d('cake_console', 'Enter the name of the plugin in CamelCase format'));
}
if (!$this->bake($plugin)) {
$this->error(__d('cake_console', "An error occured trying to bake: %s in %s", $plugin, $this->path . $plugin));
}
}
/**
* Bake the plugin, create directories and files
*
* @param string $plugin Name of the plugin in CamelCased format
* @return boolean
*/
public function bake($plugin) {
$pathOptions = App::path('plugins');
if (count($pathOptions) > 1) {
$this->findPath($pathOptions);
}
$this->hr();
$this->out(__d('cake_console', "<info>Plugin Name:</info> %s", $plugin));
$this->out(__d('cake_console', "<info>Plugin Directory:</info> %s", $this->path . $plugin));
$this->hr();
$looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y', 'n', 'q'), 'y');
if (strtolower($looksGood) == 'y') {
$Folder = new Folder($this->path . $plugin);
$directories = array(
'Config' . DS . 'Schema',
'Model' . DS . 'Behavior',
'Model' . DS . 'Datasource',
'Console' . DS . 'Command' . DS . 'Task',
'Controller' . DS . 'Component',
'Lib',
'View' . DS . 'Helper',
'Test' . DS . 'Case' . DS . 'Controller' . DS . 'Component',
'Test' . DS . 'Case' . DS . 'View' . DS . 'Helper',
'Test' . DS . 'Case' . DS . 'Model' . DS . 'Behavior',
'Test' . DS . 'Fixture',
'Vendor',
'webroot'
);
foreach ($directories as $directory) {
$dirPath = $this->path . $plugin . DS . $directory;
$Folder->create($dirPath);
$File = new File($dirPath . DS . 'empty', true);
}
foreach ($Folder->messages() as $message) {
$this->out($message, 1, Shell::VERBOSE);
}
$errors = $Folder->errors();
if (!empty($errors)) {
return false;
}
$controllerFileName = $plugin . 'AppController.php';
$out = "<?php\n\n";
$out .= "class {$plugin}AppController extends AppController {\n\n";
$out .= "}\n\n";
$this->createFile($this->path . $plugin. DS . 'Controller' . DS . $controllerFileName, $out);
$modelFileName = $plugin . 'AppModel.php';
$out = "<?php\n\n";
$out .= "class {$plugin}AppModel extends AppModel {\n\n";
$out .= "}\n\n";
$this->createFile($this->path . $plugin . DS . 'Model' . DS . $modelFileName, $out);
$this->hr();
$this->out(__d('cake_console', '<success>Created:</success> %s in %s', $plugin, $this->path . $plugin), 2);
}
return true;
}
/**
* find and change $this->path to the user selection
*
* @param array $pathOptions
* @return string plugin path
*/
public function findPath($pathOptions) {
$valid = false;
foreach ($pathOptions as $i =>$path) {
if(!is_dir($path)) {
array_splice($pathOptions, $i, 1);
}
}
$max = count($pathOptions);
while (!$valid) {
foreach ($pathOptions as $i => $option) {
$this->out($i + 1 .'. ' . $option);
}
$prompt = __d('cake_console', 'Choose a plugin path from the paths above.');
$choice = $this->in($prompt);
if (intval($choice) > 0 && intval($choice) <= $max) {
$valid = true;
}
}
$this->path = $pathOptions[$choice - 1];
}
/**
* get the option parser for the plugin task
*
* @return void
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
return $parser->description(__d('cake_console',
'Create the directory structure, AppModel and AppController classes for a new plugin. ' .
'Can create plugins in any of your bootstrapped plugin paths.'
))->addArgument('name', array(
'help' => __d('cake_console', 'CamelCased name of the plugin to create.')
));
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/Task/PluginTask.php | PHP | gpl3 | 5,252 |
<?php
/**
* The ModelTask handles creating and updating models files.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('BakeTask', 'Console/Command/Task');
App::uses('ConnectionManager', 'Model');
App::uses('Model', 'Model');
App::uses('Validation', 'Utility');
/**
* Task class for creating and updating model files.
*
* @package Cake.Console.Command.Task
*/
class ModelTask extends BakeTask {
/**
* path to Model directory
*
* @var string
*/
public $path = null;
/**
* tasks
*
* @var array
*/
public $tasks = array('DbConfig', 'Fixture', 'Test', 'Template');
/**
* Tables to skip when running all()
*
* @var array
*/
public $skipTables = array('i18n');
/**
* Holds tables found on connection.
*
* @var array
*/
protected $_tables = array();
/**
* Holds validation method map.
*
* @var array
*/
protected $_validations = array();
/**
* Override initialize
*
* @return void
*/
public function initialize() {
$this->path = current(App::path('Model'));
}
/**
* Execution method always used for tasks
*
* @return void
*/
public function execute() {
parent::execute();
if (empty($this->args)) {
$this->_interactive();
}
if (!empty($this->args[0])) {
$this->interactive = false;
if (!isset($this->connection)) {
$this->connection = 'default';
}
if (strtolower($this->args[0]) == 'all') {
return $this->all();
}
$model = $this->_modelName($this->args[0]);
$object = $this->_getModelObject($model);
if ($this->bake($object, false)) {
if ($this->_checkUnitTest()) {
$this->bakeFixture($model);
$this->bakeTest($model);
}
}
}
}
/**
* Bake all models at once.
*
* @return void
*/
public function all() {
$this->listAll($this->connection, false);
$unitTestExists = $this->_checkUnitTest();
foreach ($this->_tables as $table) {
if (in_array($table, $this->skipTables)) {
continue;
}
$modelClass = Inflector::classify($table);
$this->out(__d('cake_console', 'Baking %s', $modelClass));
$object = $this->_getModelObject($modelClass);
if ($this->bake($object, false) && $unitTestExists) {
$this->bakeFixture($modelClass);
$this->bakeTest($modelClass);
}
}
}
/**
* Get a model object for a class name.
*
* @param string $className Name of class you want model to be.
* @param string $table Table name
* @return Model Model instance
*/
protected function &_getModelObject($className, $table = null) {
if (!$table) {
$table = Inflector::tableize($className);
}
$object = new Model(array('name' => $className, 'table' => $table, 'ds' => $this->connection));
return $object;
}
/**
* Generate a key value list of options and a prompt.
*
* @param array $options Array of options to use for the selections. indexes must start at 0
* @param string $prompt Prompt to use for options list.
* @param integer $default The default option for the given prompt.
* @return integer result of user choice.
*/
public function inOptions($options, $prompt = null, $default = null) {
$valid = false;
$max = count($options);
while (!$valid) {
foreach ($options as $i => $option) {
$this->out($i + 1 .'. ' . $option);
}
if (empty($prompt)) {
$prompt = __d('cake_console', 'Make a selection from the choices above');
}
$choice = $this->in($prompt, null, $default);
if (intval($choice) > 0 && intval($choice) <= $max) {
$valid = true;
}
}
return $choice - 1;
}
/**
* Handles interactive baking
*
* @return boolean
*/
protected function _interactive() {
$this->hr();
$this->out(__d('cake_console', "Bake Model\nPath: %s", $this->path));
$this->hr();
$this->interactive = true;
$primaryKey = 'id';
$validate = $associations = array();
if (empty($this->connection)) {
$this->connection = $this->DbConfig->getConfig();
}
$currentModelName = $this->getName();
$useTable = $this->getTable($currentModelName);
$db = ConnectionManager::getDataSource($this->connection);
$fullTableName = $db->fullTableName($useTable);
if (in_array($useTable, $this->_tables)) {
$tempModel = new Model(array('name' => $currentModelName, 'table' => $useTable, 'ds' => $this->connection));
$fields = $tempModel->schema(true);
if (!array_key_exists('id', $fields)) {
$primaryKey = $this->findPrimaryKey($fields);
}
} else {
$this->err(__d('cake_console', 'Table %s does not exist, cannot bake a model without a table.', $useTable));
$this->_stop();
return false;
}
$displayField = $tempModel->hasField(array('name', 'title'));
if (!$displayField) {
$displayField = $this->findDisplayField($tempModel->schema());
}
$prompt = __d('cake_console', "Would you like to supply validation criteria \nfor the fields in your model?");
$wannaDoValidation = $this->in($prompt, array('y','n'), 'y');
if (array_search($useTable, $this->_tables) !== false && strtolower($wannaDoValidation) == 'y') {
$validate = $this->doValidation($tempModel);
}
$prompt = __d('cake_console', "Would you like to define model associations\n(hasMany, hasOne, belongsTo, etc.)?");
$wannaDoAssoc = $this->in($prompt, array('y','n'), 'y');
if (strtolower($wannaDoAssoc) == 'y') {
$associations = $this->doAssociations($tempModel);
}
$this->out();
$this->hr();
$this->out(__d('cake_console', 'The following Model will be created:'));
$this->hr();
$this->out(__d('cake_console', "Name: %s", $currentModelName));
if ($this->connection !== 'default') {
$this->out(__d('cake_console', "DB Config: %s", $this->connection));
}
if ($fullTableName !== Inflector::tableize($currentModelName)) {
$this->out(__d('cake_console', 'DB Table: %s', $fullTableName));
}
if ($primaryKey != 'id') {
$this->out(__d('cake_console', 'Primary Key: %s', $primaryKey));
}
if (!empty($validate)) {
$this->out(__d('cake_console', 'Validation: %s', print_r($validate, true)));
}
if (!empty($associations)) {
$this->out(__d('cake_console', 'Associations:'));
$assocKeys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
foreach ($assocKeys as $assocKey) {
$this->_printAssociation($currentModelName, $assocKey, $associations);
}
}
$this->hr();
$looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y','n'), 'y');
if (strtolower($looksGood) == 'y') {
$vars = compact('associations', 'validate', 'primaryKey', 'useTable', 'displayField');
$vars['useDbConfig'] = $this->connection;
if ($this->bake($currentModelName, $vars)) {
if ($this->_checkUnitTest()) {
$this->bakeFixture($currentModelName, $useTable);
$this->bakeTest($currentModelName, $useTable, $associations);
}
}
} else {
return false;
}
}
/**
* Print out all the associations of a particular type
*
* @param string $modelName Name of the model relations belong to.
* @param string $type Name of association you want to see. i.e. 'belongsTo'
* @param string $associations Collection of associations.
* @return void
*/
protected function _printAssociation($modelName, $type, $associations) {
if (!empty($associations[$type])) {
for ($i = 0; $i < count($associations[$type]); $i++) {
$out = "\t" . $modelName . ' ' . $type . ' ' . $associations[$type][$i]['alias'];
$this->out($out);
}
}
}
/**
* Finds a primary Key in a list of fields.
*
* @param array $fields Array of fields that might have a primary key.
* @return string Name of field that is a primary key.
*/
public function findPrimaryKey($fields) {
foreach ($fields as $name => $field) {
if (isset($field['key']) && $field['key'] == 'primary') {
break;
}
}
return $this->in(__d('cake_console', 'What is the primaryKey?'), null, $name);
}
/**
* interact with the user to find the displayField value for a model.
*
* @param array $fields Array of fields to look for and choose as a displayField
* @return mixed Name of field to use for displayField or false if the user declines to choose
*/
public function findDisplayField($fields) {
$fieldNames = array_keys($fields);
$prompt = __d('cake_console', "A displayField could not be automatically detected\nwould you like to choose one?");
$continue = $this->in($prompt, array('y', 'n'));
if (strtolower($continue) == 'n') {
return false;
}
$prompt = __d('cake_console', 'Choose a field from the options above:');
$choice = $this->inOptions($fieldNames, $prompt);
return $fieldNames[$choice];
}
/**
* Handles Generation and user interaction for creating validation.
*
* @param Model $model Model to have validations generated for.
* @return array $validate Array of user selected validations.
*/
public function doValidation($model) {
if (!is_object($model)) {
return false;
}
$fields = $model->schema();
if (empty($fields)) {
return false;
}
$validate = array();
$this->initValidations();
foreach ($fields as $fieldName => $field) {
$validation = $this->fieldValidation($fieldName, $field, $model->primaryKey);
if (!empty($validation)) {
$validate[$fieldName] = $validation;
}
}
return $validate;
}
/**
* Populate the _validations array
*
* @return void
*/
public function initValidations() {
$options = $choices = array();
if (class_exists('Validation')) {
$options = get_class_methods('Validation');
}
sort($options);
$default = 1;
foreach ($options as $key => $option) {
if ($option{0} != '_') {
$choices[$default] = strtolower($option);
$default++;
}
}
$choices[$default] = 'none'; // Needed since index starts at 1
$this->_validations = $choices;
return $choices;
}
/**
* Does individual field validation handling.
*
* @param string $fieldName Name of field to be validated.
* @param array $metaData metadata for field
* @param string $primaryKey
* @return array Array of validation for the field.
*/
public function fieldValidation($fieldName, $metaData, $primaryKey = 'id') {
$defaultChoice = count($this->_validations);
$validate = $alreadyChosen = array();
$anotherValidator = 'y';
while ($anotherValidator == 'y') {
if ($this->interactive) {
$this->out();
$this->out(__d('cake_console', 'Field: %s', $fieldName));
$this->out(__d('cake_console', 'Type: %s', $metaData['type']));
$this->hr();
$this->out(__d('cake_console', 'Please select one of the following validation options:'));
$this->hr();
}
$prompt = '';
for ($i = 1; $i < $defaultChoice; $i++) {
$prompt .= $i . ' - ' . $this->_validations[$i] . "\n";
}
$prompt .= __d('cake_console', "%s - Do not do any validation on this field.\n", $defaultChoice);
$prompt .= __d('cake_console', "... or enter in a valid regex validation string.\n");
$methods = array_flip($this->_validations);
$guess = $defaultChoice;
if ($metaData['null'] != 1 && !in_array($fieldName, array($primaryKey, 'created', 'modified', 'updated'))) {
if ($fieldName == 'email') {
$guess = $methods['email'];
} elseif ($metaData['type'] == 'string' && $metaData['length'] == 36) {
$guess = $methods['uuid'];
} elseif ($metaData['type'] == 'string') {
$guess = $methods['notempty'];
} elseif ($metaData['type'] == 'integer') {
$guess = $methods['numeric'];
} elseif ($metaData['type'] == 'boolean') {
$guess = $methods['boolean'];
} elseif ($metaData['type'] == 'date') {
$guess = $methods['date'];
} elseif ($metaData['type'] == 'time') {
$guess = $methods['time'];
} elseif ($metaData['type'] == 'inet') {
$guess = $methods['ip'];
}
}
if ($this->interactive === true) {
$choice = $this->in($prompt, null, $guess);
if (in_array($choice, $alreadyChosen)) {
$this->out(__d('cake_console', "You have already chosen that validation rule,\nplease choose again"));
continue;
}
if (!isset($this->_validations[$choice]) && is_numeric($choice)) {
$this->out(__d('cake_console', 'Please make a valid selection.'));
continue;
}
$alreadyChosen[] = $choice;
} else {
$choice = $guess;
}
if (isset($this->_validations[$choice])) {
$validatorName = $this->_validations[$choice];
} else {
$validatorName = Inflector::slug($choice);
}
if ($choice != $defaultChoice) {
if (is_numeric($choice) && isset($this->_validations[$choice])) {
$validate[$validatorName] = $this->_validations[$choice];
} else {
$validate[$validatorName] = $choice;
}
}
if ($this->interactive == true && $choice != $defaultChoice) {
$anotherValidator = $this->in(__d('cake_console', 'Would you like to add another validation rule?'), array('y', 'n'), 'n');
} else {
$anotherValidator = 'n';
}
}
return $validate;
}
/**
* Handles associations
*
* @param Model $model
* @return array $assocaitons
*/
public function doAssociations($model) {
if (!is_object($model)) {
return false;
}
if ($this->interactive === true) {
$this->out(__d('cake_console', 'One moment while the associations are detected.'));
}
$fields = $model->schema(true);
if (empty($fields)) {
return false;
}
if (empty($this->_tables)) {
$this->_tables = $this->getAllTables();
}
$associations = array(
'belongsTo' => array(), 'hasMany' => array(), 'hasOne'=> array(), 'hasAndBelongsToMany' => array()
);
$associations = $this->findBelongsTo($model, $associations);
$associations = $this->findHasOneAndMany($model, $associations);
$associations = $this->findHasAndBelongsToMany($model, $associations);
if ($this->interactive !== true) {
unset($associations['hasOne']);
}
if ($this->interactive === true) {
$this->hr();
if (empty($associations)) {
$this->out(__d('cake_console', 'None found.'));
} else {
$this->out(__d('cake_console', 'Please confirm the following associations:'));
$this->hr();
$associations = $this->confirmAssociations($model, $associations);
}
$associations = $this->doMoreAssociations($model, $associations);
}
return $associations;
}
/**
* Find belongsTo relations and add them to the associations list.
*
* @param Model $model Model instance of model being generated.
* @param array $associations Array of inprogress associations
* @return array $associations with belongsTo added in.
*/
public function findBelongsTo($model, $associations) {
$fields = $model->schema(true);
foreach ($fields as $fieldName => $field) {
$offset = strpos($fieldName, '_id');
if ($fieldName != $model->primaryKey && $fieldName != 'parent_id' && $offset !== false) {
$tmpModelName = $this->_modelNameFromKey($fieldName);
$associations['belongsTo'][] = array(
'alias' => $tmpModelName,
'className' => $tmpModelName,
'foreignKey' => $fieldName,
);
} elseif ($fieldName == 'parent_id') {
$associations['belongsTo'][] = array(
'alias' => 'Parent' . $model->name,
'className' => $model->name,
'foreignKey' => $fieldName,
);
}
}
return $associations;
}
/**
* Find the hasOne and HasMany relations and add them to associations list
*
* @param Model $model Model instance being generated
* @param array $associations Array of inprogress associations
* @return array $associations with hasOne and hasMany added in.
*/
public function findHasOneAndMany($model, $associations) {
$foreignKey = $this->_modelKey($model->name);
foreach ($this->_tables as $otherTable) {
$tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
$modelFieldsTemp = $tempOtherModel->schema(true);
$pattern = '/_' . preg_quote($model->table, '/') . '|' . preg_quote($model->table, '/') . '_/';
$possibleJoinTable = preg_match($pattern , $otherTable);
if ($possibleJoinTable == true) {
continue;
}
foreach ($modelFieldsTemp as $fieldName => $field) {
$assoc = false;
if ($fieldName != $model->primaryKey && $fieldName == $foreignKey) {
$assoc = array(
'alias' => $tempOtherModel->name,
'className' => $tempOtherModel->name,
'foreignKey' => $fieldName
);
} elseif ($otherTable == $model->table && $fieldName == 'parent_id') {
$assoc = array(
'alias' => 'Child' . $model->name,
'className' => $model->name,
'foreignKey' => $fieldName
);
}
if ($assoc) {
$associations['hasOne'][] = $assoc;
$associations['hasMany'][] = $assoc;
}
}
}
return $associations;
}
/**
* Find the hasAndBelongsToMany relations and add them to associations list
*
* @param Model $model Model instance being generated
* @param array $associations Array of in-progress associations
* @return array $associations with hasAndBelongsToMany added in.
*/
public function findHasAndBelongsToMany($model, $associations) {
$foreignKey = $this->_modelKey($model->name);
foreach ($this->_tables as $otherTable) {
$tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
$modelFieldsTemp = $tempOtherModel->schema(true);
$offset = strpos($otherTable, $model->table . '_');
$otherOffset = strpos($otherTable, '_' . $model->table);
if ($offset !== false) {
$offset = strlen($model->table . '_');
$habtmName = $this->_modelName(substr($otherTable, $offset));
$associations['hasAndBelongsToMany'][] = array(
'alias' => $habtmName,
'className' => $habtmName,
'foreignKey' => $foreignKey,
'associationForeignKey' => $this->_modelKey($habtmName),
'joinTable' => $otherTable
);
} elseif ($otherOffset !== false) {
$habtmName = $this->_modelName(substr($otherTable, 0, $otherOffset));
$associations['hasAndBelongsToMany'][] = array(
'alias' => $habtmName,
'className' => $habtmName,
'foreignKey' => $foreignKey,
'associationForeignKey' => $this->_modelKey($habtmName),
'joinTable' => $otherTable
);
}
}
return $associations;
}
/**
* Interact with the user and confirm associations.
*
* @param array $model Temporary Model instance.
* @param array $associations Array of associations to be confirmed.
* @return array Array of confirmed associations
*/
public function confirmAssociations($model, $associations) {
foreach ($associations as $type => $settings) {
if (!empty($associations[$type])) {
foreach ($associations[$type] as $i => $assoc) {
$prompt = "{$model->name} {$type} {$assoc['alias']}?";
$response = $this->in($prompt, array('y','n'), 'y');
if ('n' == strtolower($response)) {
unset($associations[$type][$i]);
} elseif ($type == 'hasMany') {
unset($associations['hasOne'][$i]);
}
}
$associations[$type] = array_merge($associations[$type]);
}
}
return $associations;
}
/**
* Interact with the user and generate additional non-conventional associations
*
* @param Model $model Temporary model instance
* @param array $associations Array of associations.
* @return array Array of associations.
*/
public function doMoreAssociations($model, $associations) {
$prompt = __d('cake_console', 'Would you like to define some additional model associations?');
$wannaDoMoreAssoc = $this->in($prompt, array('y','n'), 'n');
$possibleKeys = $this->_generatePossibleKeys();
while (strtolower($wannaDoMoreAssoc) == 'y') {
$assocs = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
$this->out(__d('cake_console', 'What is the association type?'));
$assocType = intval($this->inOptions($assocs, __d('cake_console', 'Enter a number')));
$this->out(__d('cake_console', "For the following options be very careful to match your setup exactly.\nAny spelling mistakes will cause errors."));
$this->hr();
$alias = $this->in(__d('cake_console', 'What is the alias for this association?'));
$className = $this->in(__d('cake_console', 'What className will %s use?', $alias), null, $alias );
if ($assocType == 0) {
$showKeys = $possibleKeys[$model->table];
$suggestedForeignKey = $this->_modelKey($alias);
} else {
$otherTable = Inflector::tableize($className);
if (in_array($otherTable, $this->_tables)) {
if ($assocType < 3) {
$showKeys = $possibleKeys[$otherTable];
} else {
$showKeys = null;
}
} else {
$otherTable = $this->in(__d('cake_console', 'What is the table for this model?'));
$showKeys = $possibleKeys[$otherTable];
}
$suggestedForeignKey = $this->_modelKey($model->name);
}
if (!empty($showKeys)) {
$this->out(__d('cake_console', 'A helpful List of possible keys'));
$foreignKey = $this->inOptions($showKeys, __d('cake_console', 'What is the foreignKey?'));
$foreignKey = $showKeys[intval($foreignKey)];
}
if (!isset($foreignKey)) {
$foreignKey = $this->in(__d('cake_console', 'What is the foreignKey? Specify your own.'), null, $suggestedForeignKey);
}
if ($assocType == 3) {
$associationForeignKey = $this->in(__d('cake_console', 'What is the associationForeignKey?'), null, $this->_modelKey($model->name));
$joinTable = $this->in(__d('cake_console', 'What is the joinTable?'));
}
$associations[$assocs[$assocType]] = array_values((array)$associations[$assocs[$assocType]]);
$count = count($associations[$assocs[$assocType]]);
$i = ($count > 0) ? $count : 0;
$associations[$assocs[$assocType]][$i]['alias'] = $alias;
$associations[$assocs[$assocType]][$i]['className'] = $className;
$associations[$assocs[$assocType]][$i]['foreignKey'] = $foreignKey;
if ($assocType == 3) {
$associations[$assocs[$assocType]][$i]['associationForeignKey'] = $associationForeignKey;
$associations[$assocs[$assocType]][$i]['joinTable'] = $joinTable;
}
$wannaDoMoreAssoc = $this->in(__d('cake_console', 'Define another association?'), array('y','n'), 'y');
}
return $associations;
}
/**
* Finds all possible keys to use on custom associations.
*
* @return array array of tables and possible keys
*/
protected function _generatePossibleKeys() {
$possible = array();
foreach ($this->_tables as $otherTable) {
$tempOtherModel = new Model(array('table' => $otherTable, 'ds' => $this->connection));
$modelFieldsTemp = $tempOtherModel->schema(true);
foreach ($modelFieldsTemp as $fieldName => $field) {
if ($field['type'] == 'integer' || $field['type'] == 'string') {
$possible[$otherTable][] = $fieldName;
}
}
}
return $possible;
}
/**
* Assembles and writes a Model file.
*
* @param mixed $name Model name or object
* @param mixed $data if array and $name is not an object assume bake data, otherwise boolean.
* @return string
*/
public function bake($name, $data = array()) {
if (is_object($name)) {
if ($data == false) {
$data = $associations = array();
$data['associations'] = $this->doAssociations($name, $associations);
$data['validate'] = $this->doValidation($name);
}
$data['primaryKey'] = $name->primaryKey;
$data['useTable'] = $name->table;
$data['useDbConfig'] = $name->useDbConfig;
$data['name'] = $name = $name->name;
} else {
$data['name'] = $name;
}
$defaults = array('associations' => array(), 'validate' => array(), 'primaryKey' => 'id',
'useTable' => null, 'useDbConfig' => 'default', 'displayField' => null);
$data = array_merge($defaults, $data);
$this->Template->set($data);
$this->Template->set(array(
'plugin' => $this->plugin,
'pluginPath' => empty($this->plugin) ? '' : $this->plugin . '.'
));
$out = $this->Template->generate('classes', 'model');
$path = $this->getPath();
$filename = $path . $name . '.php';
$this->out("\n" . __d('cake_console', 'Baking model class for %s...', $name), 1, Shell::QUIET);
$this->createFile($filename, $out);
ClassRegistry::flush();
return $out;
}
/**
* Assembles and writes a unit test file
*
* @param string $className Model class name
* @return string
*/
public function bakeTest($className) {
$this->Test->interactive = $this->interactive;
$this->Test->plugin = $this->plugin;
$this->Test->connection = $this->connection;
return $this->Test->bake('Model', $className);
}
/**
* outputs the a list of possible models or controllers from database
*
* @param string $useDbConfig Database configuration name
* @return array
*/
public function listAll($useDbConfig = null) {
$this->_tables = $this->getAllTables($useDbConfig);
if ($this->interactive === true) {
$this->out(__d('cake_console', 'Possible Models based on your current database:'));
$this->_modelNames = array();
$count = count($this->_tables);
for ($i = 0; $i < $count; $i++) {
$this->_modelNames[] = $this->_modelName($this->_tables[$i]);
$this->out($i + 1 . ". " . $this->_modelNames[$i]);
}
}
return $this->_tables;
}
/**
* Interact with the user to determine the table name of a particular model
*
* @param string $modelName Name of the model you want a table for.
* @param string $useDbConfig Name of the database config you want to get tables from.
* @return string Table name
*/
public function getTable($modelName, $useDbConfig = null) {
if (!isset($useDbConfig)) {
$useDbConfig = $this->connection;
}
$db = ConnectionManager::getDataSource($useDbConfig);
$useTable = Inflector::tableize($modelName);
$fullTableName = $db->fullTableName($useTable, false);
$tableIsGood = false;
if (array_search($useTable, $this->_tables) === false) {
$this->out();
$this->out(__d('cake_console', "Given your model named '%s',\nCake would expect a database table named '%s'", $modelName, $fullTableName));
$tableIsGood = $this->in(__d('cake_console', 'Do you want to use this table?'), array('y','n'), 'y');
}
if (strtolower($tableIsGood) == 'n') {
$useTable = $this->in(__d('cake_console', 'What is the name of the table?'));
}
return $useTable;
}
/**
* Get an Array of all the tables in the supplied connection
* will halt the script if no tables are found.
*
* @param string $useDbConfig Connection name to scan.
* @return array Array of tables in the database.
*/
public function getAllTables($useDbConfig = null) {
if (!isset($useDbConfig)) {
$useDbConfig = $this->connection;
}
$tables = array();
$db = ConnectionManager::getDataSource($useDbConfig);
$db->cacheSources = false;
$usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
if ($usePrefix) {
foreach ($db->listSources() as $table) {
if (!strncmp($table, $usePrefix, strlen($usePrefix))) {
$tables[] = substr($table, strlen($usePrefix));
}
}
} else {
$tables = $db->listSources();
}
if (empty($tables)) {
$this->err(__d('cake_console', 'Your database does not have any tables.'));
$this->_stop();
}
return $tables;
}
/**
* Forces the user to specify the model he wants to bake, and returns the selected model name.
*
* @param string $useDbConfig Database config name
* @return string the model name
*/
public function getName($useDbConfig = null) {
$this->listAll($useDbConfig);
$enteredModel = '';
while ($enteredModel == '') {
$enteredModel = $this->in(__d('cake_console', "Enter a number from the list above,\ntype in the name of another model, or 'q' to exit"), null, 'q');
if ($enteredModel === 'q') {
$this->out(__d('cake_console', 'Exit'));
$this->_stop();
}
if ($enteredModel == '' || intval($enteredModel) > count($this->_modelNames)) {
$this->err(__d('cake_console', "The model name you supplied was empty,\nor the number you selected was not an option. Please try again."));
$enteredModel = '';
}
}
if (intval($enteredModel) > 0 && intval($enteredModel) <= count($this->_modelNames)) {
$currentModelName = $this->_modelNames[intval($enteredModel) - 1];
} else {
$currentModelName = $enteredModel;
}
return $currentModelName;
}
/**
* get the option parser.
*
* @return void
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
return $parser->description(
__d('cake_console', 'Bake models.')
)->addArgument('name', array(
'help' => __d('cake_console', 'Name of the model to bake. Can use Plugin.name to bake plugin models.')
))->addSubcommand('all', array(
'help' => __d('cake_console', 'Bake all model files with associations and validation.')
))->addOption('plugin', array(
'short' => 'p',
'help' => __d('cake_console', 'Plugin to bake the model into.')
))->addOption('connection', array(
'short' => 'c',
'help' => __d('cake_console', 'The connection the model table is on.')
))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
}
/**
* Interact with FixtureTask to automatically bake fixtures when baking models.
*
* @param string $className Name of class to bake fixture for
* @param string $useTable Optional table name for fixture to use.
* @return void
* @see FixtureTask::bake
*/
public function bakeFixture($className, $useTable = null) {
$this->Fixture->interactive = $this->interactive;
$this->Fixture->connection = $this->connection;
$this->Fixture->plugin = $this->plugin;
$this->Fixture->bake($className, $useTable);
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/Task/ModelTask.php | PHP | gpl3 | 29,740 |
<?php
/**
* The ControllerTask handles creating and updating controller files.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('BakeTask', 'Console/Command/Task');
App::uses('AppModel', 'Model');
/**
* Task class for creating and updating controller files.
*
* @package Cake.Console.Command.Task
*/
class ControllerTask extends BakeTask {
/**
* Tasks to be loaded by this Task
*
* @var array
*/
public $tasks = array('Model', 'Test', 'Template', 'DbConfig', 'Project');
/**
* path to Controller directory
*
* @var array
*/
public $path = null;
/**
* Override initialize
*
* @return void
*/
public function initialize() {
$this->path = current(App::path('Controller'));
}
/**
* Execution method always used for tasks
*
* @return void
*/
public function execute() {
parent::execute();
if (empty($this->args)) {
return $this->_interactive();
}
if (isset($this->args[0])) {
if (!isset($this->connection)) {
$this->connection = 'default';
}
if (strtolower($this->args[0]) == 'all') {
return $this->all();
}
$controller = $this->_controllerName($this->args[0]);
$actions = '';
if (!empty($this->params['public'])) {
$this->out(__d('cake_console', 'Baking basic crud methods for ') . $controller);
$actions .= $this->bakeActions($controller);
}
if (!empty($this->params['admin'])) {
$admin = $this->Project->getPrefix();
if ($admin) {
$this->out(__d('cake_console', 'Adding %s methods', $admin));
$actions .= "\n" . $this->bakeActions($controller, $admin);
}
}
if (empty($actions)) {
$actions = 'scaffold';
}
if ($this->bake($controller, $actions)) {
if ($this->_checkUnitTest()) {
$this->bakeTest($controller);
}
}
}
}
/**
* Bake All the controllers at once. Will only bake controllers for models that exist.
*
* @return void
*/
public function all() {
$this->interactive = false;
$this->listAll($this->connection, false);
ClassRegistry::config('Model', array('ds' => $this->connection));
$unitTestExists = $this->_checkUnitTest();
foreach ($this->__tables as $table) {
$model = $this->_modelName($table);
$controller = $this->_controllerName($model);
App::uses($model, 'Model');
if (class_exists($model)) {
$actions = $this->bakeActions($controller);
if ($this->bake($controller, $actions) && $unitTestExists) {
$this->bakeTest($controller);
}
}
}
}
/**
* Interactive
*
* @return void
*/
protected function _interactive() {
$this->interactive = true;
$this->hr();
$this->out(__d('cake_console', "Bake Controller\nPath: %s", $this->path));
$this->hr();
if (empty($this->connection)) {
$this->connection = $this->DbConfig->getConfig();
}
$controllerName = $this->getName();
$this->hr();
$this->out(__d('cake_console', 'Baking %sController', $controllerName));
$this->hr();
$helpers = $components = array();
$actions = '';
$wannaUseSession = 'y';
$wannaBakeAdminCrud = 'n';
$useDynamicScaffold = 'n';
$wannaBakeCrud = 'y';
$question[] = __d('cake_console', "Would you like to build your controller interactively?");
if (file_exists($this->path . $controllerName .'Controller.php')) {
$question[] = __d('cake_console', "Warning: Choosing no will overwrite the %sController.", $controllerName);
}
$doItInteractive = $this->in(implode("\n", $question), array('y','n'), 'y');
if (strtolower($doItInteractive) == 'y') {
$this->interactive = true;
$useDynamicScaffold = $this->in(
__d('cake_console', "Would you like to use dynamic scaffolding?"), array('y','n'), 'n'
);
if (strtolower($useDynamicScaffold) == 'y') {
$wannaBakeCrud = 'n';
$actions = 'scaffold';
} else {
list($wannaBakeCrud, $wannaBakeAdminCrud) = $this->_askAboutMethods();
$helpers = $this->doHelpers();
$components = $this->doComponents();
$wannaUseSession = $this->in(
__d('cake_console', "Would you like to use Session flash messages?"), array('y','n'), 'y'
);
}
} else {
list($wannaBakeCrud, $wannaBakeAdminCrud) = $this->_askAboutMethods();
}
if (strtolower($wannaBakeCrud) == 'y') {
$actions = $this->bakeActions($controllerName, null, strtolower($wannaUseSession) == 'y');
}
if (strtolower($wannaBakeAdminCrud) == 'y') {
$admin = $this->Project->getPrefix();
$actions .= $this->bakeActions($controllerName, $admin, strtolower($wannaUseSession) == 'y');
}
$baked = false;
if ($this->interactive === true) {
$this->confirmController($controllerName, $useDynamicScaffold, $helpers, $components);
$looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y','n'), 'y');
if (strtolower($looksGood) == 'y') {
$baked = $this->bake($controllerName, $actions, $helpers, $components);
if ($baked && $this->_checkUnitTest()) {
$this->bakeTest($controllerName);
}
}
} else {
$baked = $this->bake($controllerName, $actions, $helpers, $components);
if ($baked && $this->_checkUnitTest()) {
$this->bakeTest($controllerName);
}
}
return $baked;
}
/**
* Confirm a to be baked controller with the user
*
* @param string $controllerName
* @param string $useDynamicScaffold
* @param array $helpers
* @param array $components
* @return void
*/
public function confirmController($controllerName, $useDynamicScaffold, $helpers, $components) {
$this->out();
$this->hr();
$this->out(__d('cake_console', 'The following controller will be created:'));
$this->hr();
$this->out(__d('cake_console', "Controller Name:\n\t%s", $controllerName));
if (strtolower($useDynamicScaffold) == 'y') {
$this->out("var \$scaffold;");
}
$properties = array(
'helpers' => __d('cake_console', 'Helpers:'),
'components' => __d('cake_console', 'Components:'),
);
foreach ($properties as $var => $title) {
if (count($$var)) {
$output = '';
$length = count($$var);
foreach ($$var as $i => $propElement) {
if ($i != $length -1) {
$output .= ucfirst($propElement) . ', ';
} else {
$output .= ucfirst($propElement);
}
}
$this->out($title . "\n\t" . $output);
}
}
$this->hr();
}
/**
* Interact with the user and ask about which methods (admin or regular they want to bake)
*
* @return array Array containing (bakeRegular, bakeAdmin) answers
*/
protected function _askAboutMethods() {
$wannaBakeCrud = $this->in(
__d('cake_console', "Would you like to create some basic class methods \n(index(), add(), view(), edit())?"),
array('y','n'), 'n'
);
$wannaBakeAdminCrud = $this->in(
__d('cake_console', "Would you like to create the basic class methods for admin routing?"),
array('y','n'), 'n'
);
return array($wannaBakeCrud, $wannaBakeAdminCrud);
}
/**
* Bake scaffold actions
*
* @param string $controllerName Controller name
* @param string $admin Admin route to use
* @param boolean $wannaUseSession Set to true to use sessions, false otherwise
* @return string Baked actions
*/
public function bakeActions($controllerName, $admin = null, $wannaUseSession = true) {
$currentModelName = $modelImport = $this->_modelName($controllerName);
$plugin = $this->plugin;
if ($plugin) {
$plugin .= '.';
}
App::uses($modelImport, $plugin . 'Model');
if (!class_exists($modelImport)) {
$this->err(__d('cake_console', 'You must have a model for this class to build basic methods. Please try again.'));
$this->_stop();
}
$modelObj = ClassRegistry::init($currentModelName);
$controllerPath = $this->_controllerPath($controllerName);
$pluralName = $this->_pluralName($currentModelName);
$singularName = Inflector::variable($currentModelName);
$singularHumanName = $this->_singularHumanName($controllerName);
$pluralHumanName = $this->_pluralName($controllerName);
$displayField = $modelObj->displayField;
$primaryKey = $modelObj->primaryKey;
$this->Template->set(compact(
'plugin', 'admin', 'controllerPath', 'pluralName', 'singularName',
'singularHumanName', 'pluralHumanName', 'modelObj', 'wannaUseSession', 'currentModelName',
'displayField', 'primaryKey'
));
$actions = $this->Template->generate('actions', 'controller_actions');
return $actions;
}
/**
* Assembles and writes a Controller file
*
* @param string $controllerName Controller name already pluralized and correctly cased.
* @param string $actions Actions to add, or set the whole controller to use $scaffold (set $actions to 'scaffold')
* @param array $helpers Helpers to use in controller
* @param array $components Components to use in controller
* @return string Baked controller
*/
public function bake($controllerName, $actions = '', $helpers = null, $components = null) {
$this->out("\n" . __d('cake_console', 'Baking controller class for %s...', $controllerName), 1, Shell::QUIET);
$isScaffold = ($actions === 'scaffold') ? true : false;
$this->Template->set(array(
'plugin' => $this->plugin,
'pluginPath' => empty($this->plugin) ? '' : $this->plugin . '.'
));
$this->Template->set(compact('controllerName', 'actions', 'helpers', 'components', 'isScaffold'));
$contents = $this->Template->generate('classes', 'controller');
$path = $this->getPath();
$filename = $path . $controllerName . 'Controller.php';
if ($this->createFile($filename, $contents)) {
return $contents;
}
return false;
}
/**
* Assembles and writes a unit test file
*
* @param string $className Controller class name
* @return string Baked test
*/
public function bakeTest($className) {
$this->Test->plugin = $this->plugin;
$this->Test->connection = $this->connection;
$this->Test->interactive = $this->interactive;
return $this->Test->bake('Controller', $className);
}
/**
* Interact with the user and get a list of additional helpers
*
* @return array Helpers that the user wants to use.
*/
public function doHelpers() {
return $this->_doPropertyChoices(
__d('cake_console', "Would you like this controller to use other helpers\nbesides HtmlHelper and FormHelper?"),
__d('cake_console', "Please provide a comma separated list of the other\nhelper names you'd like to use.\nExample: 'Ajax, Javascript, Time'")
);
}
/**
* Interact with the user and get a list of additional components
*
* @return array Components the user wants to use.
*/
public function doComponents() {
return $this->_doPropertyChoices(
__d('cake_console', "Would you like this controller to use any components?"),
__d('cake_console', "Please provide a comma separated list of the component names you'd like to use.\nExample: 'Acl, Security, RequestHandler'")
);
}
/**
* Common code for property choice handling.
*
* @param string $prompt A yes/no question to precede the list
* @param string $example A question for a comma separated list, with examples.
* @return array Array of values for property.
*/
protected function _doPropertyChoices($prompt, $example) {
$proceed = $this->in($prompt, array('y','n'), 'n');
$property = array();
if (strtolower($proceed) == 'y') {
$propertyList = $this->in($example);
$propertyListTrimmed = str_replace(' ', '', $propertyList);
$property = explode(',', $propertyListTrimmed);
}
return array_filter($property);
}
/**
* Outputs and gets the list of possible controllers from database
*
* @param string $useDbConfig Database configuration name
* @return array Set of controllers
*/
public function listAll($useDbConfig = null) {
if (is_null($useDbConfig)) {
$useDbConfig = $this->connection;
}
$this->__tables = $this->Model->getAllTables($useDbConfig);
if ($this->interactive == true) {
$this->out(__d('cake_console', 'Possible Controllers based on your current database:'));
$this->_controllerNames = array();
$count = count($this->__tables);
for ($i = 0; $i < $count; $i++) {
$this->_controllerNames[] = $this->_controllerName($this->_modelName($this->__tables[$i]));
$this->out($i + 1 . ". " . $this->_controllerNames[$i]);
}
return $this->_controllerNames;
}
return $this->__tables;
}
/**
* Forces the user to specify the controller he wants to bake, and returns the selected controller name.
*
* @param string $useDbConfig Connection name to get a controller name for.
* @return string Controller name
*/
public function getName($useDbConfig = null) {
$controllers = $this->listAll($useDbConfig);
$enteredController = '';
while ($enteredController == '') {
$enteredController = $this->in(__d('cake_console', "Enter a number from the list above,\ntype in the name of another controller, or 'q' to exit"), null, 'q');
if ($enteredController === 'q') {
$this->out(__d('cake_console', 'Exit'));
return $this->_stop();
}
if ($enteredController == '' || intval($enteredController) > count($controllers)) {
$this->err(__d('cake_console', "The Controller name you supplied was empty,\nor the number you selected was not an option. Please try again."));
$enteredController = '';
}
}
if (intval($enteredController) > 0 && intval($enteredController) <= count($controllers) ) {
$controllerName = $controllers[intval($enteredController) - 1];
} else {
$controllerName = Inflector::camelize($enteredController);
}
return $controllerName;
}
/**
* get the option parser.
*
* @return void
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
return $parser->description(
__d('cake_console', 'Bake a controller for a model. Using options you can bake public, admin or both.')
)->addArgument('name', array(
'help' => __d('cake_console', 'Name of the controller to bake. Can use Plugin.name to bake controllers into plugins.')
))->addOption('public', array(
'help' => __d('cake_console', 'Bake a controller with basic crud actions (index, view, add, edit, delete).'),
'boolean' => true
))->addOption('admin', array(
'help' => __d('cake_console', 'Bake a controller with crud actions for one of the Routing.prefixes.'),
'boolean' => true
))->addOption('plugin', array(
'short' => 'p',
'help' => __d('cake_console', 'Plugin to bake the controller into.')
))->addOption('connection', array(
'short' => 'c',
'help' => __d('cake_console', 'The connection the controller\'s model is on.')
))->addSubcommand('all', array(
'help' => __d('cake_console', 'Bake all controllers with CRUD methods.')
))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
}
/**
* Displays help contents
*
* @return void
*/
public function help() {
$this->hr();
$this->out("Usage: cake bake controller <arg1> <arg2>...");
$this->hr();
$this->out('Arguments:');
$this->out();
$this->out("<name>");
$this->out("\tName of the controller to bake. Can use Plugin.name");
$this->out("\tas a shortcut for plugin baking.");
$this->out();
$this->out('Params:');
$this->out();
$this->out('-connection <config>');
$this->out("\tset db config <config>. uses 'default' if none is specified");
$this->out();
$this->out('Commands:');
$this->out();
$this->out("controller <name>");
$this->out("\tbakes controller with var \$scaffold");
$this->out();
$this->out("controller <name> public");
$this->out("\tbakes controller with basic crud actions");
$this->out("\t(index, view, add, edit, delete)");
$this->out();
$this->out("controller <name> admin");
$this->out("\tbakes a controller with basic crud actions for one of the");
$this->out("\tConfigure::read('Routing.prefixes') methods.");
$this->out();
$this->out("controller <name> public admin");
$this->out("\tbakes a controller with basic crud actions for one");
$this->out("\tConfigure::read('Routing.prefixes') and non admin methods.");
$this->out("\t(index, view, add, edit, delete,");
$this->out("\tadmin_index, admin_view, admin_edit, admin_add, admin_delete)");
$this->out();
$this->out("controller all");
$this->out("\tbakes all controllers with CRUD methods.");
$this->out();
$this->_stop();
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/Task/ControllerTask.php | PHP | gpl3 | 16,600 |
<?php
/**
* The View Tasks handles creating and updating view files.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Controller', 'Controller');
App::uses('BakeTask', 'Console/Command/Task');
/**
* Task class for creating and updating view files.
*
* @package Cake.Console.Command.Task
*/
class ViewTask extends BakeTask {
/**
* Tasks to be loaded by this Task
*
* @var array
*/
public $tasks = array('Project', 'Controller', 'DbConfig', 'Template');
/**
* path to View directory
*
* @var array
*/
public $path = null;
/**
* Name of the controller being used
*
* @var string
*/
public $controllerName = null;
/**
* The template file to use
*
* @var string
*/
public $template = null;
/**
* Actions to use for scaffolding
*
* @var array
*/
public $scaffoldActions = array('index', 'view', 'add', 'edit');
/**
* An array of action names that don't require templates. These
* actions will not emit errors when doing bakeActions()
*
* @var array
*/
public $noTemplateActions = array('delete');
/**
* Override initialize
*
* @return void
*/
public function initialize() {
$this->path = current(App::path('View'));
}
/**
* Execution method always used for tasks
*
* @return mixed
*/
public function execute() {
parent::execute();
if (empty($this->args)) {
$this->_interactive();
}
if (empty($this->args[0])) {
return;
}
if (!isset($this->connection)) {
$this->connection = 'default';
}
$action = null;
$this->controllerName = $this->_controllerName($this->args[0]);
$this->Project->interactive = false;
if (strtolower($this->args[0]) == 'all') {
return $this->all();
}
if (isset($this->args[1])) {
$this->template = $this->args[1];
}
if (isset($this->args[2])) {
$action = $this->args[2];
}
if (!$action) {
$action = $this->template;
}
if ($action) {
return $this->bake($action, true);
}
$vars = $this->_loadController();
$methods = $this->_methodsToBake();
foreach ($methods as $method) {
$content = $this->getContent($method, $vars);
if ($content) {
$this->bake($method, $content);
}
}
}
/**
* Get a list of actions that can / should have views baked for them.
*
* @return array Array of action names that should be baked
*/
protected function _methodsToBake() {
$methods = array_diff(
array_map('strtolower', get_class_methods($this->controllerName . 'Controller')),
array_map('strtolower', get_class_methods('AppController'))
);
$scaffoldActions = false;
if (empty($methods)) {
$scaffoldActions = true;
$methods = $this->scaffoldActions;
}
$adminRoute = $this->Project->getPrefix();
foreach ($methods as $i => $method) {
if ($adminRoute && isset($this->params['admin'])) {
if ($scaffoldActions) {
$methods[$i] = $adminRoute . $method;
continue;
} elseif (strpos($method, $adminRoute) === false) {
unset($methods[$i]);
}
}
if ($method[0] === '_' || $method == strtolower($this->controllerName . 'Controller')) {
unset($methods[$i]);
}
}
return $methods;
}
/**
* Bake All views for All controllers.
*
* @return void
*/
public function all() {
$this->Controller->interactive = false;
$tables = $this->Controller->listAll($this->connection, false);
$actions = null;
if (isset($this->args[1])) {
$actions = array($this->args[1]);
}
$this->interactive = false;
foreach ($tables as $table) {
$model = $this->_modelName($table);
$this->controllerName = $this->_controllerName($model);
App::uses($model, 'Model');
if (class_exists($model)) {
$vars = $this->_loadController();
if (!$actions) {
$actions = $this->_methodsToBake();
}
$this->bakeActions($actions, $vars);
$actions = null;
}
}
}
/**
* Handles interactive baking
*
* @return void
*/
protected function _interactive() {
$this->hr();
$this->out(sprintf("Bake View\nPath: %s", $this->path));
$this->hr();
$this->DbConfig->interactive = $this->Controller->interactive = $this->interactive = true;
if (empty($this->connection)) {
$this->connection = $this->DbConfig->getConfig();
}
$this->Controller->connection = $this->connection;
$this->controllerName = $this->Controller->getName();
$prompt = __d('cake_console', "Would you like bake to build your views interactively?\nWarning: Choosing no will overwrite %s views if it exist.", $this->controllerName);
$interactive = $this->in($prompt, array('y', 'n'), 'n');
if (strtolower($interactive) == 'n') {
$this->interactive = false;
}
$prompt = __d('cake_console', "Would you like to create some CRUD views\n(index, add, view, edit) for this controller?\nNOTE: Before doing so, you'll need to create your controller\nand model classes (including associated models).");
$wannaDoScaffold = $this->in($prompt, array('y','n'), 'y');
$wannaDoAdmin = $this->in(__d('cake_console', "Would you like to create the views for admin routing?"), array('y','n'), 'n');
if (strtolower($wannaDoScaffold) == 'y' || strtolower($wannaDoAdmin) == 'y') {
$vars = $this->_loadController();
if (strtolower($wannaDoScaffold) == 'y') {
$actions = $this->scaffoldActions;
$this->bakeActions($actions, $vars);
}
if (strtolower($wannaDoAdmin) == 'y') {
$admin = $this->Project->getPrefix();
$regularActions = $this->scaffoldActions;
$adminActions = array();
foreach ($regularActions as $action) {
$adminActions[] = $admin . $action;
}
$this->bakeActions($adminActions, $vars);
}
$this->hr();
$this->out();
$this->out(__d('cake_console', "View Scaffolding Complete.\n"));
} else {
$this->customAction();
}
}
/**
* Loads Controller and sets variables for the template
* Available template variables
* 'modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
* 'singularHumanName', 'pluralHumanName', 'fields', 'foreignKeys',
* 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
*
* @return array Returns an variables to be made available to a view template
*/
protected function _loadController() {
if (!$this->controllerName) {
$this->err(__d('cake_console', 'Controller not found'));
}
$plugin = null;
if ($this->plugin) {
$plugin = $this->plugin . '.';
}
$controllerClassName = $this->controllerName . 'Controller';
App::uses($controllerClassName, $plugin . 'Controller');
if (!class_exists($controllerClassName)) {
$file = $controllerClassName . '.php';
$this->err(__d('cake_console', "The file '%s' could not be found.\nIn order to bake a view, you'll need to first create the controller.", $file));
$this->_stop();
}
$controllerObj = new $controllerClassName();
$controllerObj->plugin = $this->plugin;
$controllerObj->constructClasses();
$modelClass = $controllerObj->modelClass;
$modelObj = $controllerObj->{$controllerObj->modelClass};
if ($modelObj) {
$primaryKey = $modelObj->primaryKey;
$displayField = $modelObj->displayField;
$singularVar = Inflector::variable($modelClass);
$singularHumanName = $this->_singularHumanName($this->controllerName);
$schema = $modelObj->schema(true);
$fields = array_keys($schema);
$associations = $this->_associations($modelObj);
} else {
$primaryKey = $displayField = null;
$singularVar = Inflector::variable(Inflector::singularize($this->controllerName));
$singularHumanName = $this->_singularHumanName($this->controllerName);
$fields = $schema = $associations = array();
}
$pluralVar = Inflector::variable($this->controllerName);
$pluralHumanName = $this->_pluralHumanName($this->controllerName);
return compact('modelClass', 'schema', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
'singularHumanName', 'pluralHumanName', 'fields','associations');
}
/**
* Bake a view file for each of the supplied actions
*
* @param array $actions Array of actions to make files for.
* @param array $vars
* @return void
*/
public function bakeActions($actions, $vars) {
foreach ($actions as $action) {
$content = $this->getContent($action, $vars);
$this->bake($action, $content);
}
}
/**
* handle creation of baking a custom action view file
*
* @return void
*/
public function customAction() {
$action = '';
while ($action == '') {
$action = $this->in(__d('cake_console', 'Action Name? (use lowercase_underscored function name)'));
if ($action == '') {
$this->out(__d('cake_console', 'The action name you supplied was empty. Please try again.'));
}
}
$this->out();
$this->hr();
$this->out(__d('cake_console', 'The following view will be created:'));
$this->hr();
$this->out(__d('cake_console', 'Controller Name: %s', $this->controllerName));
$this->out(__d('cake_console', 'Action Name: %s', $action));
$this->out(__d('cake_console', 'Path: %s', $this->params['app'] . DS . 'View' . DS . $this->controllerName . DS . Inflector::underscore($action) . ".ctp"));
$this->hr();
$looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y','n'), 'y');
if (strtolower($looksGood) == 'y') {
$this->bake($action, ' ');
$this->_stop();
} else {
$this->out(__d('cake_console', 'Bake Aborted.'));
}
}
/**
* Assembles and writes bakes the view file.
*
* @param string $action Action to bake
* @param string $content Content to write
* @return boolean Success
*/
public function bake($action, $content = '') {
if ($content === true) {
$content = $this->getContent($action);
}
if (empty($content)) {
return false;
}
$this->out("\n" . __d('cake_console', 'Baking `%s` view file...', $action), 1, Shell::QUIET);
$path = $this->getPath();
$filename = $path . $this->controllerName . DS . Inflector::underscore($action) . '.ctp';
return $this->createFile($filename, $content);
}
/**
* Builds content from template and variables
*
* @param string $action name to generate content to
* @param array $vars passed for use in templates
* @return string content from template
*/
public function getContent($action, $vars = null) {
if (!$vars) {
$vars = $this->_loadController();
}
$this->Template->set('action', $action);
$this->Template->set('plugin', $this->plugin);
$this->Template->set($vars);
$template = $this->getTemplate($action);
if ($template) {
return $this->Template->generate('views', $template);
}
return false;
}
/**
* Gets the template name based on the action name
*
* @param string $action name
* @return string template name
*/
public function getTemplate($action) {
if ($action != $this->template && in_array($action, $this->noTemplateActions)) {
return false;
}
if (!empty($this->template) && $action != $this->template) {
return $this->template;
}
$template = $action;
$prefixes = Configure::read('Routing.prefixes');
foreach ((array)$prefixes as $prefix) {
if (strpos($template, $prefix) !== false) {
$template = str_replace($prefix . '_', '', $template);
}
}
if (in_array($template, array('add', 'edit'))) {
$template = 'form';
} elseif (preg_match('@(_add|_edit)$@', $template)) {
$template = str_replace(array('_add', '_edit'), '_form', $template);
}
return $template;
}
/**
* get the option parser for this task
*
* @return ConsoleOptionParser
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
return $parser->description(
__d('cake_console', 'Bake views for a controller, using built-in or custom templates.')
)->addArgument('controller', array(
'help' => __d('cake_console', 'Name of the controller views to bake. Can be Plugin.name as a shortcut for plugin baking.')
))->addArgument('action', array(
'help' => __d('cake_console', "Will bake a single action's file. core templates are (index, add, edit, view)")
))->addArgument('alias', array(
'help' => __d('cake_console', 'Will bake the template in <action> but create the filename after <alias>.')
))->addOption('plugin', array(
'short' => 'p',
'help' => __d('cake_console', 'Plugin to bake the view into.')
))->addOption('admin', array(
'help' => __d('cake_console', 'Set to only bake views for a prefix in Routing.prefixes'),
'boolean' => true
))->addOption('connection', array(
'short' => 'c',
'help' => __d('cake_console', 'The connection the connected model is on.')
))->addSubcommand('all', array(
'help' => __d('cake_console', 'Bake all CRUD action views for all controllers. Requires models and controllers to exist.')
))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
}
/**
* Returns associations for controllers models.
*
* @param Model $model
* @return array $associations
*/
protected function _associations($model) {
$keys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
$associations = array();
foreach ($keys as $key => $type) {
foreach ($model->{$type} as $assocKey => $assocData) {
list($plugin, $modelClass) = pluginSplit($assocData['className']);
$associations[$type][$assocKey]['primaryKey'] = $model->{$assocKey}->primaryKey;
$associations[$type][$assocKey]['displayField'] = $model->{$assocKey}->displayField;
$associations[$type][$assocKey]['foreignKey'] = $assocData['foreignKey'];
$associations[$type][$assocKey]['controller'] = Inflector::pluralize(Inflector::underscore($modelClass));
$associations[$type][$assocKey]['fields'] = array_keys($model->{$assocKey}->schema(true));
}
}
return $associations;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/Task/ViewTask.php | PHP | gpl3 | 14,096 |
<?php
/**
* Language string extractor
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2.0.5012
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('File', 'Utility');
App::uses('Folder', 'Utility');
/**
* Language string extractor
*
* @package Cake.Console.Command.Task
*/
class ExtractTask extends Shell {
/**
* Paths to use when looking for strings
*
* @var string
*/
protected $_paths = array();
/**
* Files from where to extract
*
* @var array
*/
protected $_files = array();
/**
* Merge all domains string into the default.pot file
*
* @var boolean
*/
protected $_merge = false;
/**
* Current file being processed
*
* @var string
*/
protected $_file = null;
/**
* Contains all content waiting to be write
*
* @var string
*/
protected $_storage = array();
/**
* Extracted tokens
*
* @var array
*/
protected $_tokens = array();
/**
* Extracted strings
*
* @var array
*/
protected $_strings = array();
/**
* Destination path
*
* @var string
*/
protected $_output = null;
/**
* An array of directories to exclude.
*
* @var array
*/
protected $_exclude = array();
/**
* Holds whether this call should extract model validation messages
*
* @var boolean
*/
protected $_extractValidation = true;
/**
* Holds the validation string domain to use for validation messages when extracting
*
* @var boolean
*/
protected $_validationDomain = 'default';
/**
* Execution method always used for tasks
*
* @return void
*/
public function execute() {
if (!empty($this->params['exclude'])) {
$this->_exclude = explode(',', $this->params['exclude']);
}
if (isset($this->params['files']) && !is_array($this->params['files'])) {
$this->_files = explode(',', $this->params['files']);
}
if (isset($this->params['paths'])) {
$this->_paths = explode(',', $this->params['paths']);
} else if (isset($this->params['plugin'])) {
$plugin = Inflector::camelize($this->params['plugin']);
if (!CakePlugin::loaded($plugin)) {
CakePlugin::load($plugin);
}
$this->_paths = array(CakePlugin::path($plugin));
$this->params['plugin'] = $plugin;
} else {
$defaultPath = APP;
$message = __d('cake_console', "What is the path you would like to extract?\n[Q]uit [D]one");
while (true) {
$response = $this->in($message, null, $defaultPath);
if (strtoupper($response) === 'Q') {
$this->out(__d('cake_console', 'Extract Aborted'));
$this->_stop();
} elseif (strtoupper($response) === 'D') {
$this->out();
break;
} elseif (is_dir($response)) {
$this->_paths[] = $response;
$defaultPath = 'D';
} else {
$this->err(__d('cake_console', 'The directory path you supplied was not found. Please try again.'));
}
$this->out();
}
}
if (!empty($this->params['exclude-plugins']) && $this->_isExtractingApp()) {
$this->_exclude = array_merge($this->_exclude, App::path('plugins'));
}
if (!empty($this->params['ignore-model-validation']) || (!$this->_isExtractingApp() && empty($plugin))) {
$this->_extractValidation = false;
}
if (!empty($this->params['validation-domain'])) {
$this->_validationDomain = $this->params['validation-domain'];
}
if (isset($this->params['output'])) {
$this->_output = $this->params['output'];
} else if (isset($this->params['plugin'])) {
$this->_output = $this->_paths[0] . DS . 'Locale';
} else {
$message = __d('cake_console', "What is the path you would like to output?\n[Q]uit", $this->_paths[0] . DS . 'Locale');
while (true) {
$response = $this->in($message, null, $this->_paths[0] . DS . 'Locale');
if (strtoupper($response) === 'Q') {
$this->out(__d('cake_console', 'Extract Aborted'));
$this->_stop();
} elseif (is_dir($response)) {
$this->_output = $response . DS;
break;
} else {
$this->err(__d('cake_console', 'The directory path you supplied was not found. Please try again.'));
}
$this->out();
}
}
if (isset($this->params['merge'])) {
$this->_merge = !(strtolower($this->params['merge']) === 'no');
} else {
$this->out();
$response = $this->in(__d('cake_console', 'Would you like to merge all domains strings into the default.pot file?'), array('y', 'n'), 'n');
$this->_merge = strtolower($response) === 'y';
}
if (empty($this->_files)) {
$this->_searchFiles();
}
$this->_extract();
}
/**
* Extract text
*
* @return void
*/
protected function _extract() {
$this->out();
$this->out();
$this->out(__d('cake_console', 'Extracting...'));
$this->hr();
$this->out(__d('cake_console', 'Paths:'));
foreach ($this->_paths as $path) {
$this->out(' ' . $path);
}
$this->out(__d('cake_console', 'Output Directory: ') . $this->_output);
$this->hr();
$this->_extractTokens();
$this->_extractValidationMessages();
$this->_buildFiles();
$this->_writeFiles();
$this->_paths = $this->_files = $this->_storage = array();
$this->_strings = $this->_tokens = array();
$this->_extractValidation = true;
$this->out();
$this->out(__d('cake_console', 'Done.'));
}
/**
* Get & configure the option parser
*
* @return void
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
return $parser->description(__d('cake_console', 'CakePHP Language String Extraction:'))
->addOption('app', array('help' => __d('cake_console', 'Directory where your application is located.')))
->addOption('paths', array('help' => __d('cake_console', 'Comma separated list of paths.')))
->addOption('merge', array(
'help' => __d('cake_console', 'Merge all domain strings into the default.po file.'),
'choices' => array('yes', 'no')
))
->addOption('output', array('help' => __d('cake_console', 'Full path to output directory.')))
->addOption('files', array('help' => __d('cake_console', 'Comma separated list of files.')))
->addOption('exclude-plugins', array(
'boolean' => true,
'default' => true,
'help' => __d('cake_console', 'Ignores all files in plugins if this command is run inside from the same app directory.')
))
->addOption('plugin', array(
'help' => __d('cake_console', 'Extracts tokens only from the plugin specified and puts the result in the plugin\'s Locale directory.')
))
->addOption('ignore-model-validation', array(
'boolean' => true,
'default' => false,
'help' => __d('cake_console', 'Ignores validation messages in the $validate property. If this flag is not set and the command is run from the same app directory, all messages in model validation rules will be extracted as tokens.')
))
->addOption('validation-domain', array(
'help' => __d('cake_console', 'If set to a value, the localization domain to be used for model validation messages.')
))
->addOption('exclude', array(
'help' => __d('cake_console', 'Comma separated list of directories to exclude. Any path containing a path segment with the provided values will be skipped. E.g. test,vendors')
));
}
/**
* Extract tokens out of all files to be processed
*
* @return void
*/
protected function _extractTokens() {
foreach ($this->_files as $file) {
$this->_file = $file;
$this->out(__d('cake_console', 'Processing %s...', $file));
$code = file_get_contents($file);
$allTokens = token_get_all($code);
$this->_tokens = array();
foreach ($allTokens as $token) {
if (!is_array($token) || ($token[0] != T_WHITESPACE && $token[0] != T_INLINE_HTML)) {
$this->_tokens[] = $token;
}
}
unset($allTokens);
$this->_parse('__', array('singular'));
$this->_parse('__n', array('singular', 'plural'));
$this->_parse('__d', array('domain', 'singular'));
$this->_parse('__c', array('singular'));
$this->_parse('__dc', array('domain', 'singular'));
$this->_parse('__dn', array('domain', 'singular', 'plural'));
$this->_parse('__dcn', array('domain', 'singular', 'plural'));
}
}
/**
* Parse tokens
*
* @param string $functionName Function name that indicates translatable string (e.g: '__')
* @param array $map Array containing what variables it will find (e.g: domain, singular, plural)
* @return void
*/
protected function _parse($functionName, $map) {
$count = 0;
$tokenCount = count($this->_tokens);
while (($tokenCount - $count) > 1) {
list($countToken, $firstParenthesis) = array($this->_tokens[$count], $this->_tokens[$count + 1]);
if (!is_array($countToken)) {
$count++;
continue;
}
list($type, $string, $line) = $countToken;
if (($type == T_STRING) && ($string == $functionName) && ($firstParenthesis == '(')) {
$position = $count;
$depth = 0;
while ($depth == 0) {
if ($this->_tokens[$position] == '(') {
$depth++;
} elseif ($this->_tokens[$position] == ')') {
$depth--;
}
$position++;
}
$mapCount = count($map);
$strings = $this->_getStrings($position, $mapCount);
if ($mapCount == count($strings)) {
extract(array_combine($map, $strings));
$domain = isset($domain) ? $domain : 'default';
$string = isset($plural) ? $singular . "\0" . $plural : $singular;
$this->_strings[$domain][$string][$this->_file][] = $line;
} else {
$this->_markerError($this->_file, $line, $functionName, $count);
}
}
$count++;
}
}
/**
* Looks for models in the application and extracts the validation messages
* to be added to the translation map
*
* @return void
*/
protected function _extractValidationMessages() {
if (!$this->_extractValidation) {
return;
}
App::uses('AppModel', 'Model');
$plugin = null;
if (!empty($this->params['plugin'])) {
App::uses($this->params['plugin'] . 'AppModel', $this->params['plugin'] . '.Model');
$plugin = $this->params['plugin'] . '.';
}
$models = App::objects($plugin . 'Model', null, false);
foreach ($models as $model) {
App::uses($model, $plugin . 'Model');
$reflection = new ReflectionClass($model);
$properties = $reflection->getDefaultProperties();
$validate = $properties['validate'];
if (empty($validate)) {
continue;
}
$file = $reflection->getFileName();
$domain = $this->_validationDomain;
if (!empty($properties['validationDomain'])) {
$domain = $properties['validationDomain'];
}
foreach ($validate as $field => $rules) {
$this->_processValidationRules($field, $rules, $file, $domain);
}
}
}
/**
* Process a validation rule for a field and looks for a message to be added
* to the translation map
*
* @param string $field the name of the field that is being processed
* @param array $rules the set of validation rules for the field
* @param string $file the file name where this validation rule was found
* @param string $domain default domain to bind the validations to
* @return void
*/
protected function _processValidationRules($field, $rules, $file, $domain) {
if (is_array($rules)) {
$dims = Set::countDim($rules);
if ($dims == 1 || ($dims == 2 && isset($rules['message']))) {
$rules = array($rules);
}
foreach ($rules as $rule => $validateProp) {
$message = null;
if (isset($validateProp['message'])) {
if (is_array($validateProp['message'])) {
$message = $validateProp['message'][0];
} else {
$message = $validateProp['message'];
}
} elseif (is_string($rule)) {
$message = $rule;
}
if ($message) {
$this->_strings[$domain][$message][$file][] = 'validation for field ' . $field;
}
}
}
}
/**
* Build the translate template file contents out of obtained strings
*
* @return void
*/
protected function _buildFiles() {
foreach ($this->_strings as $domain => $strings) {
foreach ($strings as $string => $files) {
$occurrences = array();
foreach ($files as $file => $lines) {
$occurrences[] = $file . ':' . implode(';', $lines);
}
$occurrences = implode("\n#: ", $occurrences);
$header = '#: ' . str_replace($this->_paths, '', $occurrences) . "\n";
if (strpos($string, "\0") === false) {
$sentence = "msgid \"{$string}\"\n";
$sentence .= "msgstr \"\"\n\n";
} else {
list($singular, $plural) = explode("\0", $string);
$sentence = "msgid \"{$singular}\"\n";
$sentence .= "msgid_plural \"{$plural}\"\n";
$sentence .= "msgstr[0] \"\"\n";
$sentence .= "msgstr[1] \"\"\n\n";
}
$this->_store($domain, $header, $sentence);
if ($domain != 'default' && $this->_merge) {
$this->_store('default', $header, $sentence);
}
}
}
}
/**
* Prepare a file to be stored
*
* @param string $domain
* @param string $header
* @param string $sentence
* @return void
*/
protected function _store($domain, $header, $sentence) {
if (!isset($this->_storage[$domain])) {
$this->_storage[$domain] = array();
}
if (!isset($this->_storage[$domain][$sentence])) {
$this->_storage[$domain][$sentence] = $header;
} else {
$this->_storage[$domain][$sentence] .= $header;
}
}
/**
* Write the files that need to be stored
*
* @return void
*/
protected function _writeFiles() {
$overwriteAll = false;
foreach ($this->_storage as $domain => $sentences) {
$output = $this->_writeHeader();
foreach ($sentences as $sentence => $header) {
$output .= $header . $sentence;
}
$filename = $domain . '.pot';
$File = new File($this->_output . $filename);
$response = '';
while ($overwriteAll === false && $File->exists() && strtoupper($response) !== 'Y') {
$this->out();
$response = $this->in(__d('cake_console', 'Error: %s already exists in this location. Overwrite? [Y]es, [N]o, [A]ll', $filename), array('y', 'n', 'a'), 'y');
if (strtoupper($response) === 'N') {
$response = '';
while ($response == '') {
$response = $this->in(__d('cake_console', "What would you like to name this file?"), null, 'new_' . $filename);
$File = new File($this->_output . $response);
$filename = $response;
}
} elseif (strtoupper($response) === 'A') {
$overwriteAll = true;
}
}
$File->write($output);
$File->close();
}
}
/**
* Build the translation template header
*
* @return string Translation template header
*/
protected function _writeHeader() {
$output = "# LANGUAGE translation of CakePHP Application\n";
$output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
$output .= "#\n";
$output .= "#, fuzzy\n";
$output .= "msgid \"\"\n";
$output .= "msgstr \"\"\n";
$output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
$output .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
$output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
$output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
$output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
$output .= "\"MIME-Version: 1.0\\n\"\n";
$output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
$output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
$output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";
return $output;
}
/**
* Get the strings from the position forward
*
* @param integer $position Actual position on tokens array
* @param integer $target Number of strings to extract
* @return array Strings extracted
*/
protected function _getStrings(&$position, $target) {
$strings = array();
while (count($strings) < $target && ($this->_tokens[$position] == ',' || $this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING)) {
if ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING && $this->_tokens[$position+1] == '.') {
$string = '';
while ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING || $this->_tokens[$position] == '.') {
if ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
$string .= $this->_formatString($this->_tokens[$position][1]);
}
$position++;
}
$strings[] = $string;
} else if ($this->_tokens[$position][0] == T_CONSTANT_ENCAPSED_STRING) {
$strings[] = $this->_formatString($this->_tokens[$position][1]);
}
$position++;
}
return $strings;
}
/**
* Format a string to be added as a translatable string
*
* @param string $string String to format
* @return string Formatted string
*/
protected function _formatString($string) {
$quote = substr($string, 0, 1);
$string = substr($string, 1, -1);
if ($quote == '"') {
$string = stripcslashes($string);
} else {
$string = strtr($string, array("\\'" => "'", "\\\\" => "\\"));
}
$string = str_replace("\r\n", "\n", $string);
return addcslashes($string, "\0..\37\\\"");
}
/**
* Indicate an invalid marker on a processed file
*
* @param string $file File where invalid marker resides
* @param integer $line Line number
* @param string $marker Marker found
* @param integer $count Count
* @return void
*/
protected function _markerError($file, $line, $marker, $count) {
$this->out(__d('cake_console', "Invalid marker content in %s:%s\n* %s(", $file, $line, $marker), true);
$count += 2;
$tokenCount = count($this->_tokens);
$parenthesis = 1;
while ((($tokenCount - $count) > 0) && $parenthesis) {
if (is_array($this->_tokens[$count])) {
$this->out($this->_tokens[$count][1], false);
} else {
$this->out($this->_tokens[$count], false);
if ($this->_tokens[$count] == '(') {
$parenthesis++;
}
if ($this->_tokens[$count] == ')') {
$parenthesis--;
}
}
$count++;
}
$this->out("\n", true);
}
/**
* Search files that may contain translatable strings
*
* @return void
*/
protected function _searchFiles() {
$pattern = false;
if (!empty($this->_exclude)) {
$exclude = array();
foreach ($this->_exclude as $e) {
if ($e[0] !== DS) {
$e = DS . $e;
}
$exclude[] = preg_quote($e, '/');
}
$pattern = '/' . implode('|', $exclude) . '/';
}
foreach ($this->_paths as $path) {
$Folder = new Folder($path);
$files = $Folder->findRecursive('.*\.(php|ctp|thtml|inc|tpl)', true);
if (!empty($pattern)) {
foreach ($files as $i => $file) {
if (preg_match($pattern, $file)) {
unset($files[$i]);
}
}
$files = array_values($files);
}
$this->_files = array_merge($this->_files, $files);
}
}
/**
* Returns whether this execution is meant to extract string only from directories in folder represented by the
* APP constant, i.e. this task is extracting strings from same application.
*
* @return boolean
*/
protected function _isExtractingApp() {
return $this->_paths === array(APP);
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/Task/ExtractTask.php | PHP | gpl3 | 19,033 |
<?php
/**
* Base class for Bake Tasks.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Shell', 'Console');
/**
* Base class for Bake Tasks.
*
* @package Cake.Console.Command.Task
*/
class BakeTask extends Shell {
/**
* Name of plugin
*
* @var string
*/
public $plugin = null;
/**
* The db connection being used for baking
*
* @var string
*/
public $connection = null;
/**
* Flag for interactive mode
*
* @var boolean
*/
public $interactive = false;
/**
* Disable caching and enable debug for baking.
* This forces the most current database schema to be used.
*
* @return void
*/
function startup() {
Configure::write('debug', 2);
Configure::write('Cache.disable', 1);
parent::startup();
}
/**
* Gets the path for output. Checks the plugin property
* and returns the correct path.
*
* @return string Path to output.
*/
public function getPath() {
$path = $this->path;
if (isset($this->plugin)) {
$path = $this->_pluginPath($this->plugin) . $this->name . DS;
}
return $path;
}
/**
* Base execute method parses some parameters and sets some properties on the bake tasks.
* call when overriding execute()
*
* @return void
*/
public function execute() {
foreach($this->args as $i => $arg) {
if (strpos($arg, '.')) {
list($this->params['plugin'], $this->args[$i]) = pluginSplit($arg);
break;
}
}
if (isset($this->params['plugin'])) {
$this->plugin = $this->params['plugin'];
}
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/Task/BakeTask.php | PHP | gpl3 | 1,958 |
<?php
/**
* The TestTask handles creating and updating test files.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('BakeTask', 'Console/Command/Task');
App::uses('ClassRegistry', 'Utility');
/**
* Task class for creating and updating test files.
*
* @package Cake.Console.Command.Task
*/
class TestTask extends BakeTask {
/**
* path to TESTS directory
*
* @var string
*/
public $path = TESTS;
/**
* Tasks used.
*
* @var array
*/
public $tasks = array('Template');
/**
* class types that methods can be generated for
*
* @var array
*/
public $classTypes = array(
'Model' => 'Model',
'Controller' => 'Controller',
'Component' => 'Controller/Component',
'Behavior' => 'Model/Behavior',
'Helper' => 'View/Helper'
);
/**
* Internal list of fixtures that have been added so far.
*
* @var array
*/
protected $_fixtures = array();
/**
* Execution method always used for tasks
*
* @return void
*/
public function execute() {
parent::execute();
if (empty($this->args)) {
$this->_interactive();
}
if (count($this->args) == 1) {
$this->_interactive($this->args[0]);
}
if (count($this->args) > 1) {
$type = Inflector::underscore($this->args[0]);
if ($this->bake($type, $this->args[1])) {
$this->out('<success>Done</success>');
}
}
}
/**
* Handles interactive baking
*
* @param string $type
* @return string|boolean
*/
protected function _interactive($type = null) {
$this->interactive = true;
$this->hr();
$this->out(__d('cake_console', 'Bake Tests'));
$this->out(__d('cake_console', 'Path: %s', $this->path));
$this->hr();
if ($type) {
$type = Inflector::camelize($type);
if (!isset($this->classTypes[$type])) {
$this->error(__d('cake_console', 'Incorrect type provided. Please choose one of %s', implode(', ', array_keys($this->classTypes))));
}
} else {
$type = $this->getObjectType();
}
$className = $this->getClassName($type);
return $this->bake($type, $className);
}
/**
* Completes final steps for generating data to create test case.
*
* @param string $type Type of object to bake test case for ie. Model, Controller
* @param string $className the 'cake name' for the class ie. Posts for the PostsController
* @return string|boolean
*/
public function bake($type, $className) {
$plugin = null;
if ($this->plugin) {
$plugin = $this->plugin . '.';
}
$realType = $this->mapType($type, $plugin);
$fullClassName = $this->getRealClassName($type, $className);
if ($this->typeCanDetectFixtures($type) && $this->isLoadableClass($realType, $fullClassName)) {
$this->out(__d('cake_console', 'Bake is detecting possible fixtures...'));
$testSubject = $this->buildTestSubject($type, $className);
$this->generateFixtureList($testSubject);
} elseif ($this->interactive) {
$this->getUserFixtures();
}
App::uses($fullClassName, $realType);
$methods = array();
if (class_exists($fullClassName)) {
$methods = $this->getTestableMethods($fullClassName);
}
$mock = $this->hasMockClass($type, $fullClassName);
$construction = $this->generateConstructor($type, $fullClassName);
$this->out("\n" . __d('cake_console', 'Baking test case for %s %s ...', $className, $type), 1, Shell::QUIET);
$this->Template->set('fixtures', $this->_fixtures);
$this->Template->set('plugin', $plugin);
$this->Template->set(compact(
'className', 'methods', 'type', 'fullClassName', 'mock',
'construction', 'realType'
));
$out = $this->Template->generate('classes', 'test');
$filename = $this->testCaseFileName($type, $className);
$made = $this->createFile($filename, $out);
if ($made) {
return $out;
}
return false;
}
/**
* Interact with the user and get their chosen type. Can exit the script.
*
* @return string Users chosen type.
*/
public function getObjectType() {
$this->hr();
$this->out(__d('cake_console', 'Select an object type:'));
$this->hr();
$keys = array();
$i = 0;
foreach ($this->classTypes as $option => $package) {
$this->out(++$i . '. ' . $option);
$keys[] = $i;
}
$keys[] = 'q';
$selection = $this->in(__d('cake_console', 'Enter the type of object to bake a test for or (q)uit'), $keys, 'q');
if ($selection == 'q') {
return $this->_stop();
}
$types = array_keys($this->classTypes);
return $types[$selection - 1];
}
/**
* Get the user chosen Class name for the chosen type
*
* @param string $objectType Type of object to list classes for i.e. Model, Controller.
* @return string Class name the user chose.
*/
public function getClassName($objectType) {
$type = ucfirst(strtolower($objectType));
$typeLength = strlen($type);
$type = $this->classTypes[$type];
if ($this->plugin) {
$plugin = $this->plugin . '.';
$options = App::objects($plugin . $type);
} else {
$options = App::objects($type);
}
$this->out(__d('cake_console', 'Choose a %s class', $objectType));
$keys = array();
foreach ($options as $key => $option) {
$this->out(++$key . '. ' . $option);
$keys[] = $key;
}
$selection = $this->in(__d('cake_console', 'Choose an existing class, or enter the name of a class that does not exist'));
if (isset($options[$selection - 1])) {
$selection = $options[$selection - 1];
}
if ($type !== 'Model') {
$selection = substr($selection, 0, $typeLength * - 1);
}
return $selection;
}
/**
* Checks whether the chosen type can find its own fixtures.
* Currently only model, and controller are supported
*
* @param string $type The Type of object you are generating tests for eg. controller
* @return boolean
*/
public function typeCanDetectFixtures($type) {
$type = strtolower($type);
return in_array($type, array('controller', 'model'));
}
/**
* Check if a class with the given package is loaded or can be loaded.
*
* @param string $package The package of object you are generating tests for eg. controller
* @param string $class the Classname of the class the test is being generated for.
* @return boolean
*/
public function isLoadableClass($package, $class) {
App::uses($class, $package);
return class_exists($class);
}
/**
* Construct an instance of the class to be tested.
* So that fixtures can be detected
*
* @param string $type The Type of object you are generating tests for eg. controller
* @param string $class the Classname of the class the test is being generated for.
* @return object And instance of the class that is going to be tested.
*/
public function &buildTestSubject($type, $class) {
ClassRegistry::flush();
App::import($type, $class);
$class = $this->getRealClassName($type, $class);
if (strtolower($type) == 'model') {
$instance = ClassRegistry::init($class);
} else {
$instance = new $class();
}
return $instance;
}
/**
* Gets the real class name from the cake short form. If the class name is already
* suffixed with the type, the type will not be duplicated.
*
* @param string $type The Type of object you are generating tests for eg. controller
* @param string $class the Classname of the class the test is being generated for.
* @return string Real classname
*/
public function getRealClassName($type, $class) {
if (strtolower($type) == 'model' || empty($this->classTypes[$type])) {
return $class;
}
if (strlen($class) - strpos($class, $type) == strlen($type)) {
return $class;
}
return $class . $type;
}
/**
* Map the types that TestTask uses to concrete types that App::uses can use.
*
* @param string $type The type of thing having a test generated.
* @param string $plugin The plugin name.
* @return string
*/
public function mapType($type, $plugin) {
$type = ucfirst($type);
if (empty($this->classTypes[$type])) {
throw new CakeException(__d('cake_dev', 'Invalid object type.'));
}
$real = $this->classTypes[$type];
if ($plugin) {
$real = trim($plugin, '.') . '.' . $real;
}
return $real;
}
/**
* Get methods declared in the class given.
* No parent methods will be returned
*
* @param string $className Name of class to look at.
* @return array Array of method names.
*/
public function getTestableMethods($className) {
$classMethods = get_class_methods($className);
$parentMethods = get_class_methods(get_parent_class($className));
$thisMethods = array_diff($classMethods, $parentMethods);
$out = array();
foreach ($thisMethods as $method) {
if (substr($method, 0, 1) != '_' && $method != strtolower($className)) {
$out[] = $method;
}
}
return $out;
}
/**
* Generate the list of fixtures that will be required to run this test based on
* loaded models.
*
* @param object $subject The object you want to generate fixtures for.
* @return array Array of fixtures to be included in the test.
*/
public function generateFixtureList($subject) {
$this->_fixtures = array();
if (is_a($subject, 'Model')) {
$this->_processModel($subject);
} elseif (is_a($subject, 'Controller')) {
$this->_processController($subject);
}
return array_values($this->_fixtures);
}
/**
* Process a model recursively and pull out all the
* model names converting them to fixture names.
*
* @param Model $subject A Model class to scan for associations and pull fixtures off of.
* @return void
*/
protected function _processModel($subject) {
$this->_addFixture($subject->name);
$associated = $subject->getAssociated();
foreach ($associated as $alias => $type) {
$className = $subject->{$alias}->name;
if (!isset($this->_fixtures[$className])) {
$this->_processModel($subject->{$alias});
}
if ($type == 'hasAndBelongsToMany') {
$joinModel = Inflector::classify($subject->hasAndBelongsToMany[$alias]['joinTable']);
if (!isset($this->_fixtures[$joinModel])) {
$this->_processModel($subject->{$joinModel});
}
}
}
}
/**
* Process all the models attached to a controller
* and generate a fixture list.
*
* @param Controller $subject A controller to pull model names off of.
* @return void
*/
protected function _processController($subject) {
$subject->constructClasses();
$models = array(Inflector::classify($subject->name));
if (!empty($subject->uses)) {
$models = $subject->uses;
}
foreach ($models as $model) {
$this->_processModel($subject->{$model});
}
}
/**
* Add classname to the fixture list.
* Sets the app. or plugin.plugin_name. prefix.
*
* @param string $name Name of the Model class that a fixture might be required for.
* @return void
*/
protected function _addFixture($name) {
$parent = get_parent_class($name);
$prefix = 'app.';
if (strtolower($parent) != 'appmodel' && strtolower(substr($parent, -8)) == 'appmodel') {
$pluginName = substr($parent, 0, strlen($parent) -8);
$prefix = 'plugin.' . Inflector::underscore($pluginName) . '.';
}
$fixture = $prefix . Inflector::underscore($name);
$this->_fixtures[$name] = $fixture;
}
/**
* Interact with the user to get additional fixtures they want to use.
*
* @return array Array of fixtures the user wants to add.
*/
public function getUserFixtures() {
$proceed = $this->in(__d('cake_console', 'Bake could not detect fixtures, would you like to add some?'), array('y','n'), 'n');
$fixtures = array();
if (strtolower($proceed) == 'y') {
$fixtureList = $this->in(__d('cake_console', "Please provide a comma separated list of the fixtures names you'd like to use.\nExample: 'app.comment, app.post, plugin.forums.post'"));
$fixtureListTrimmed = str_replace(' ', '', $fixtureList);
$fixtures = explode(',', $fixtureListTrimmed);
}
$this->_fixtures = array_merge($this->_fixtures, $fixtures);
return $fixtures;
}
/**
* Is a mock class required for this type of test?
* Controllers require a mock class.
*
* @param string $type The type of object tests are being generated for eg. controller.
* @return boolean
*/
public function hasMockClass($type) {
$type = strtolower($type);
return $type == 'controller';
}
/**
* Generate a constructor code snippet for the type and classname
*
* @param string $type The Type of object you are generating tests for eg. controller
* @param string $fullClassName The Classname of the class the test is being generated for.
* @return string Constructor snippet for the thing you are building.
*/
public function generateConstructor($type, $fullClassName) {
$type = strtolower($type);
if ($type == 'model') {
return "ClassRegistry::init('$fullClassName');\n";
}
if ($type == 'controller') {
$className = substr($fullClassName, 0, strlen($fullClassName) - 10);
return "new Test$fullClassName();\n\t\t\$this->{$className}->constructClasses();\n";
}
return "new $fullClassName();\n";
}
/**
* Make the filename for the test case. resolve the suffixes for controllers
* and get the plugin path if needed.
*
* @param string $type The Type of object you are generating tests for eg. controller
* @param string $className the Classname of the class the test is being generated for.
* @return string filename the test should be created on.
*/
public function testCaseFileName($type, $className) {
$path = $this->getPath() . 'Case' . DS;
if (isset($this->classTypes[$type])) {
$path .= $this->classTypes[$type] . DS;
}
$className = $this->getRealClassName($type, $className);
return str_replace('/', DS, $path) . Inflector::camelize($className) . 'Test.php';
}
/**
* get the option parser.
*
* @return void
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
return $parser->description(__d('cake_console', 'Bake test case skeletons for classes.'))
->addArgument('type', array(
'help' => __d('cake_console', 'Type of class to bake, can be any of the following: controller, model, helper, component or behavior.'),
'choices' => array('controller', 'model', 'helper', 'component', 'behavior')
))->addArgument('name', array(
'help' => __d('cake_console', 'An existing class to bake tests for.')
))->addOption('plugin', array(
'short' => 'p',
'help' => __d('cake_console', 'CamelCased name of the plugin to bake tests for.')
))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Command/Task/TestTask.php | PHP | gpl3 | 14,757 |
<?php
/**
* Task collection is used as a registry for loaded tasks and handles loading
* and constructing task class objects.
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('ObjectCollection', 'Utility');
/**
* Collection object for Tasks. Provides features
* for lazily loading tasks, and firing callbacks on loaded tasks.
*
* @package Cake.Console
*/
class TaskCollection extends ObjectCollection {
/**
* Shell to use to set params to tasks.
*
* @var Shell
*/
protected $_Shell;
/**
* The directory inside each shell path that contains tasks.
*
* @var string
*/
public $taskPathPrefix = 'tasks/';
/**
* Constructor
*
* @param Shell $Shell
*/
public function __construct(Shell $Shell) {
$this->_Shell = $Shell;
}
/**
* Loads/constructs a task. Will return the instance in the collection
* if it already exists.
*
* @param string $task Task name to load
* @param array $settings Settings for the task.
* @return Task A task object, Either the existing loaded task or a new one.
* @throws MissingTaskException when the task could not be found
*/
public function load($task, $settings = array()) {
list($plugin, $name) = pluginSplit($task, true);
if (isset($this->_loaded[$name])) {
return $this->_loaded[$name];
}
$taskClass = $name . 'Task';
App::uses($taskClass, $plugin . 'Console/Command/Task');
if (!class_exists($taskClass)) {
if (!class_exists($taskClass)) {
throw new MissingTaskException(array(
'class' => $taskClass
));
}
}
$this->_loaded[$name] = new $taskClass(
$this->_Shell->stdout, $this->_Shell->stderr, $this->_Shell->stdin
);
$enable = isset($settings['enabled']) ? $settings['enabled'] : true;
if ($enable === true) {
$this->_enabled[] = $name;
}
return $this->_loaded[$name];
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/TaskCollection.php | PHP | gpl3 | 2,305 |
<?php
/**
* ConsoleOutput file.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Object wrapper for outputting information from a shell application.
* Can be connected to any stream resource that can be used with fopen()
*
* Can generate colorized output on consoles that support it. There are a few
* built in styles
*
* - `error` Error messages.
* - `warning` Warning messages.
* - `info` Informational messages.
* - `comment` Additional text.
* - `question` Magenta text used for user prompts
*
* By defining styles with addStyle() you can create custom console styles.
*
* ### Using styles in output
*
* You can format console output using tags with the name of the style to apply. From inside a shell object
*
* `$this->out('<warning>Overwrite:</warning> foo.php was overwritten.');`
*
* This would create orange 'Overwrite:' text, while the rest of the text would remain the normal color.
* See ConsoleOutput::styles() to learn more about defining your own styles. Nested styles are not supported
* at this time.
*
* @package Cake.Console
*/
class ConsoleOutput {
/**
* Raw output constant - no modification of output text.
*/
const RAW = 0;
/**
* Plain output - tags will be stripped.
*/
const PLAIN = 1;
/**
* Color output - Convert known tags in to ANSI color escape codes.
*/
const COLOR = 2;
/**
* Constant for a newline.
*/
const LF = PHP_EOL;
/**
* File handle for output.
*
* @var resource
*/
protected $_output;
/**
* The current output type. Manipulated with ConsoleOutput::outputAs();
*
* @var integer.
*/
protected $_outputAs = self::COLOR;
/**
* text colors used in colored output.
*
* @var array
*/
protected static $_foregroundColors = array(
'black' => 30,
'red' => 31,
'green' => 32,
'yellow' => 33,
'blue' => 34,
'magenta' => 35,
'cyan' => 36,
'white' => 37
);
/**
* background colors used in colored output.
*
* @var array
*/
protected static $_backgroundColors = array(
'black' => 40,
'red' => 41,
'green' => 42,
'yellow' => 43,
'blue' => 44,
'magenta' => 45,
'cyan' => 46,
'white' => 47
);
/**
* formatting options for colored output
*
* @var string
*/
protected static $_options = array(
'bold' => 1,
'underline' => 4,
'blink' => 5,
'reverse' => 7,
);
/**
* Styles that are available as tags in console output.
* You can modify these styles with ConsoleOutput::styles()
*
* @var array
*/
protected static $_styles = array(
'error' => array('text' => 'red', 'underline' => true),
'warning' => array('text' => 'yellow'),
'info' => array('text' => 'cyan'),
'success' => array('text' => 'green'),
'comment' => array('text' => 'blue'),
'question' => array('text' => "magenta"),
);
/**
* Construct the output object.
*
* Checks for a pretty console environment. Ansicon allows pretty consoles
* on windows, and is supported.
*
* @param string $stream The identifier of the stream to write output to.
*/
public function __construct($stream = 'php://stdout') {
$this->_output = fopen($stream, 'w');
if (DS == '\\' && !(bool)env('ANSICON')) {
$this->_outputAs = self::PLAIN;
}
}
/**
* Outputs a single or multiple messages to stdout. If no parameters
* are passed, outputs just a newline.
*
* @param mixed $message A string or a an array of strings to output
* @param integer $newlines Number of newlines to append
* @return integer Returns the number of bytes returned from writing to stdout.
*/
public function write($message, $newlines = 1) {
if (is_array($message)) {
$message = implode(self::LF, $message);
}
return $this->_write($this->styleText($message . str_repeat(self::LF, $newlines)));
}
/**
* Apply styling to text.
*
* @param string $text Text with styling tags.
* @return string String with color codes added.
*/
public function styleText($text) {
if ($this->_outputAs == self::RAW) {
return $text;
}
if ($this->_outputAs == self::PLAIN) {
return strip_tags($text);
}
return preg_replace_callback(
'/<(?<tag>[a-z0-9-_]+)>(?<text>.*?)<\/(\1)>/ims', array($this, '_replaceTags'), $text
);
}
/**
* Replace tags with color codes.
*
* @param array $matches.
* @return string
*/
protected function _replaceTags($matches) {
$style = $this->styles($matches['tag']);
if (empty($style)) {
return '<' . $matches['tag'] . '>' . $matches['text'] . '</' . $matches['tag'] . '>';
}
$styleInfo = array();
if (!empty($style['text']) && isset(self::$_foregroundColors[$style['text']])) {
$styleInfo[] = self::$_foregroundColors[$style['text']];
}
if (!empty($style['background']) && isset(self::$_backgroundColors[$style['background']])) {
$styleInfo[] = self::$_backgroundColors[$style['background']];
}
unset($style['text'], $style['background']);
foreach ($style as $option => $value) {
if ($value) {
$styleInfo[] = self::$_options[$option];
}
}
return "\033[" . implode($styleInfo, ';') . 'm' . $matches['text'] . "\033[0m";
}
/**
* Writes a message to the output stream.
*
* @param string $message Message to write.
* @return boolean success
*/
protected function _write($message) {
return fwrite($this->_output, $message);
}
/**
* Get the current styles offered, or append new ones in.
*
* ### Get a style definition
*
* `$this->output->styles('error');`
*
* ### Get all the style definitions
*
* `$this->output->styles();`
*
* ### Create or modify an existing style
*
* `$this->output->styles('annoy', array('text' => 'purple', 'background' => 'yellow', 'blink' => true));`
*
* ### Remove a style
*
* `$this->output->styles('annoy', false);`
*
* @param string $style The style to get or create.
* @param mixed $definition The array definition of the style to change or create a style
* or false to remove a style.
* @return mixed If you are getting styles, the style or null will be returned. If you are creating/modifying
* styles true will be returned.
*/
public function styles($style = null, $definition = null) {
if ($style === null && $definition === null) {
return self::$_styles;
}
if (is_string($style) && $definition === null) {
return isset(self::$_styles[$style]) ? self::$_styles[$style] : null;
}
if ($definition === false) {
unset(self::$_styles[$style]);
return true;
}
self::$_styles[$style] = $definition;
return true;
}
/**
* Get/Set the output type to use. The output type how formatting tags are treated.
*
* @param integer $type The output type to use. Should be one of the class constants.
* @return mixed Either null or the value if getting.
*/
public function outputAs($type = null) {
if ($type === null) {
return $this->_outputAs;
}
$this->_outputAs = $type;
}
/**
* clean up and close handles
*
*/
public function __destruct() {
fclose($this->_output);
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/ConsoleOutput.php | PHP | gpl3 | 7,372 |
<?php
/**
* ShellDispatcher file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Shell dispatcher handles dispatching cli commands.
*
* @package Cake.Console
*/
class ShellDispatcher {
/**
* Contains command switches parsed from the command line.
*
* @var array
*/
public $params = array();
/**
* Contains arguments parsed from the command line.
*
* @var array
*/
public $args = array();
/**
* Constructor
*
* The execution of the script is stopped after dispatching the request with
* a status code of either 0 or 1 according to the result of the dispatch.
*
* @param array $args the argv from PHP
* @param boolean $bootstrap Should the environment be bootstrapped.
*/
public function __construct($args = array(), $bootstrap = true) {
set_time_limit(0);
if ($bootstrap) {
$this->_initConstants();
}
$this->parseParams($args);
if ($bootstrap) {
$this->_initEnvironment();
}
}
/**
* Run the dispatcher
*
* @param array $argv The argv from PHP
* @return void
*/
public static function run($argv) {
$dispatcher = new ShellDispatcher($argv);
$dispatcher->_stop($dispatcher->dispatch() === false ? 1 : 0);
}
/**
* Defines core configuration.
*
* @return void
*/
protected function _initConstants() {
if (function_exists('ini_set')) {
ini_set('html_errors', false);
ini_set('implicit_flush', true);
ini_set('max_execution_time', 0);
}
if (!defined('CAKE_CORE_INCLUDE_PATH')) {
define('DS', DIRECTORY_SEPARATOR);
define('CAKE_CORE_INCLUDE_PATH', dirname(dirname(dirname(__FILE__))));
define('CAKEPHP_SHELL', true);
if (!defined('CORE_PATH')) {
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
}
}
}
/**
* Defines current working environment.
*
* @return void
* @throws CakeException
*/
protected function _initEnvironment() {
if (!$this->_bootstrap()) {
$message = "Unable to load CakePHP core.\nMake sure " . DS . 'lib' . DS . 'Cake exists in ' . CAKE_CORE_INCLUDE_PATH;
throw new CakeException($message);
}
if (!isset($this->args[0]) || !isset($this->params['working'])) {
$message = "This file has been loaded incorrectly and cannot continue.\n" .
"Please make sure that " . DS . 'lib' . DS . 'Cake' . DS . "Console is in your system path,\n" .
"and check the cookbook for the correct usage of this command.\n" .
"(http://book.cakephp.org/)";
throw new CakeException($message);
}
$this->shiftArgs();
}
/**
* Initializes the environment and loads the Cake core.
*
* @return boolean Success.
*/
protected function _bootstrap() {
define('ROOT', $this->params['root']);
define('APP_DIR', $this->params['app']);
define('APP', $this->params['working'] . DS);
define('WWW_ROOT', APP . $this->params['webroot'] . DS);
if (!is_dir(ROOT . DS . APP_DIR . DS . 'tmp')) {
define('TMP', CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'Console' . DS . 'Templates' . DS . 'skel' . DS . 'tmp' . DS);
}
$boot = file_exists(ROOT . DS . APP_DIR . DS . 'Config' . DS . 'bootstrap.php');
require CORE_PATH . 'Cake' . DS . 'bootstrap.php';
if (!file_exists(APP . 'Config' . DS . 'core.php')) {
include_once CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'Console' . DS . 'Templates' . DS . 'skel' . DS . 'Config' . DS . 'core.php';
App::build();
}
require_once CAKE . 'Console' . DS . 'ConsoleErrorHandler.php';
$ErrorHandler = new ConsoleErrorHandler();
set_exception_handler(array($ErrorHandler, 'handleException'));
set_error_handler(array($ErrorHandler, 'handleError'), Configure::read('Error.level'));
if (!defined('FULL_BASE_URL')) {
define('FULL_BASE_URL', 'http://localhost');
}
return true;
}
/**
* Dispatches a CLI request
*
* @return boolean
* @throws MissingShellMethodException
*/
public function dispatch() {
$shell = $this->shiftArgs();
if (!$shell) {
$this->help();
return false;
}
if (in_array($shell, array('help', '--help', '-h'))) {
$this->help();
return true;
}
$Shell = $this->_getShell($shell);
$command = null;
if (isset($this->args[0])) {
$command = $this->args[0];
}
if ($Shell instanceof Shell) {
$Shell->initialize();
$Shell->loadTasks();
return $Shell->runCommand($command, $this->args);
}
$methods = array_diff(get_class_methods($Shell), get_class_methods('Shell'));
$added = in_array($command, $methods);
$private = $command[0] == '_' && method_exists($Shell, $command);
if (!$private) {
if ($added) {
$this->shiftArgs();
$Shell->startup();
return $Shell->{$command}();
}
if (method_exists($Shell, 'main')) {
$Shell->startup();
return $Shell->main();
}
}
throw new MissingShellMethodException(array('shell' => $shell, 'method' => $arg));
}
/**
* Get shell to use, either plugin shell or application shell
*
* All paths in the loaded shell paths are searched.
*
* @param string $shell Optionally the name of a plugin
* @return mixed An object
* @throws MissingShellException when errors are encountered.
*/
protected function _getShell($shell) {
list($plugin, $shell) = pluginSplit($shell, true);
$class = Inflector::camelize($shell) . 'Shell';
App::uses('Shell', 'Console');
App::uses('AppShell', 'Console');
App::uses($class, $plugin . 'Console/Command');
if (!class_exists($class)) {
throw new MissingShellException(array(
'class' => $class
));
}
$Shell = new $class();
return $Shell;
}
/**
* Parses command line options and extracts the directory paths from $params
*
* @param array $args Parameters to parse
* @return void
*/
public function parseParams($args) {
$this->_parsePaths($args);
$defaults = array(
'app' => 'app',
'root' => dirname(dirname(dirname(dirname(__FILE__)))),
'working' => null,
'webroot' => 'webroot'
);
$params = array_merge($defaults, array_intersect_key($this->params, $defaults));
$isWin = false;
foreach ($defaults as $default => $value) {
if (strpos($params[$default], '\\') !== false) {
$isWin = true;
break;
}
}
$params = str_replace('\\', '/', $params);
if (isset($params['working'])) {
$params['working'] = trim($params['working']);
}
if (!empty($params['working']) && (!isset($this->args[0]) || isset($this->args[0]) && $this->args[0]{0} !== '.')) {
if (empty($this->params['app']) && $params['working'] != $params['root']) {
$params['root'] = dirname($params['working']);
$params['app'] = basename($params['working']);
} else {
$params['root'] = $params['working'];
}
}
if ($params['app'][0] == '/' || preg_match('/([a-z])(:)/i', $params['app'], $matches)) {
$params['root'] = dirname($params['app']);
} elseif (strpos($params['app'], '/')) {
$params['root'] .= '/' . dirname($params['app']);
}
$params['app'] = basename($params['app']);
$params['working'] = rtrim($params['root'], '/');
if (!$isWin || !preg_match('/^[A-Z]:$/i', $params['app'])) {
$params['working'] .= '/' . $params['app'];
}
if (!empty($matches[0]) || !empty($isWin)) {
$params = str_replace('/', '\\', $params);
}
$this->params = array_merge($this->params, $params);
}
/**
* Parses out the paths from from the argv
*
* @param array $args
* @return void
*/
protected function _parsePaths($args) {
$parsed = array();
$keys = array('-working', '--working', '-app', '--app', '-root', '--root');
foreach ($keys as $key) {
$index = array_search($key, $args);
if ($index !== false) {
$keyname = str_replace('-', '', $key);
$valueIndex = $index + 1;
$parsed[$keyname] = $args[$valueIndex];
array_splice($args, $index, 2);
}
}
$this->args = $args;
$this->params = $parsed;
}
/**
* Removes first argument and shifts other arguments up
*
* @return mixed Null if there are no arguments otherwise the shifted argument
*/
public function shiftArgs() {
return array_shift($this->args);
}
/**
* Shows console help. Performs an internal dispatch to the CommandList Shell
*
* @return void
*/
public function help() {
$this->args = array_merge(array('command_list'), $this->args);
$this->dispatch();
}
/**
* Stop execution of the current script
*
* @param integer|string $status see http://php.net/exit for values
* @return void
*/
protected function _stop($status = 0) {
exit($status);
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/ShellDispatcher.php | PHP | gpl3 | 8,839 |
#!/usr/bin/php -q
<?php
/**
* Command-line code generation utility to automate programmer chores.
*
* Shell dispatcher class
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Console
* @since CakePHP(tm) v 1.2.0.5012
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ShellDispatcher.php');
return ShellDispatcher::run($argv);
| 0001-bee | trunk/cakephp2/lib/Cake/Console/cake.php | PHP | gpl3 | 804 |
#!/bin/bash
################################################################################
#
# Bake is a shell script for running CakePHP bake script
# PHP 5
#
# CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
# Copyright 2005-2011, Cake Software Foundation, Inc.
#
# Licensed under The MIT License
# Redistributions of files must retain the above copyright notice.
#
# @copyright Copyright 2005-2011, Cake Software Foundation, Inc.
# @link http://cakephp.org CakePHP(tm) Project
# @package cake.console
# @since CakePHP(tm) v 1.2.0.5012
# @license MIT License (http://www.opensource.org/licenses/mit-license.php)
#
################################################################################
LIB=$(cd -P -- "$(dirname -- "$0")" && pwd -P) && LIB=$LIB/$(basename -- "$0")
while [ -h "$LIB" ]; do
DIR=$(dirname -- "$LIB")
SYM=$(readlink "$LIB")
LIB=$(cd "$DIR" && cd $(dirname -- "$SYM") && pwd)/$(basename -- "$SYM")
done
LIB=$(dirname -- "$LIB")/
APP=`pwd`
exec php -q "$LIB"cake.php -working "$APP" "$@"
exit;
| 0001-bee | trunk/cakephp2/lib/Cake/Console/.svn/text-base/cake.svn-base | Shell | gpl3 | 1,062 |
#!/usr/bin/php -q
<?php
/**
* Command-line code generation utility to automate programmer chores.
*
* Shell dispatcher class
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Console
* @since CakePHP(tm) v 1.2.0.5012
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ShellDispatcher.php');
return ShellDispatcher::run($argv);
| 0001-bee | trunk/cakephp2/lib/Cake/Console/.svn/text-base/cake.php.svn-base | PHP | gpl3 | 804 |
<?php
/**
* Base class for Shells
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 1.2.0.5012
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('TaskCollection', 'Console');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('ConsoleInputSubcommand', 'Console');
App::uses('ConsoleOptionParser', 'Console');
App::uses('File', 'Utility');
/**
* Base class for command-line utilities for automating programmer chores.
*
* @package Cake.Console
*/
class Shell extends Object {
/**
* Output constants for making verbose and quiet shells.
*/
const VERBOSE = 2;
const NORMAL = 1;
const QUIET = 0;
/**
* An instance of ConsoleOptionParser that has been configured for this class.
*
* @var ConsoleOptionParser
*/
public $OptionParser;
/**
* If true, the script will ask for permission to perform actions.
*
* @var boolean
*/
public $interactive = true;
/**
* Contains command switches parsed from the command line.
*
* @var array
*/
public $params = array();
/**
* The command (method/task) that is being run.
*
* @var string
*/
public $command;
/**
* Contains arguments parsed from the command line.
*
* @var array
*/
public $args = array();
/**
* The name of the shell in camelized.
*
* @var string
*/
public $name = null;
/**
* Contains tasks to load and instantiate
*
* @var array
*/
public $tasks = array();
/**
* Contains the loaded tasks
*
* @var array
*/
public $taskNames = array();
/**
* Contains models to load and instantiate
*
* @var array
*/
public $uses = array();
/**
* Task Collection for the command, used to create Tasks.
*
* @var TaskCollection
*/
public $Tasks;
/**
* Normalized map of tasks.
*
* @var string
*/
protected $_taskMap = array();
/**
* stdout object.
*
* @var ConsoleOutput
*/
public $stdout;
/**
* stderr object.
*
* @var ConsoleOutput
*/
public $stderr;
/**
* stdin object
*
* @var ConsoleInput
*/
public $stdin;
/**
* Constructs this Shell instance.
*
* @param ConsoleOutput $stdout A ConsoleOutput object for stdout.
* @param ConsoleOutput $stderr A ConsoleOutput object for stderr.
* @param ConsoleInput $stdin A ConsoleInput object for stdin.
*/
public function __construct($stdout = null, $stderr = null, $stdin = null) {
if ($this->name == null) {
$this->name = Inflector::camelize(str_replace(array('Shell', 'Task'), '', get_class($this)));
}
$this->Tasks = new TaskCollection($this);
$this->stdout = $stdout;
$this->stderr = $stderr;
$this->stdin = $stdin;
if ($this->stdout == null) {
$this->stdout = new ConsoleOutput('php://stdout');
}
if ($this->stderr == null) {
$this->stderr = new ConsoleOutput('php://stderr');
}
if ($this->stdin == null) {
$this->stdin = new ConsoleInput('php://stdin');
}
$parent = get_parent_class($this);
if ($this->tasks !== null && $this->tasks !== false) {
$this->_mergeVars(array('tasks'), $parent, true);
}
if ($this->uses !== null && $this->uses !== false) {
$this->_mergeVars(array('uses'), $parent, false);
}
}
/**
* Initializes the Shell
* acts as constructor for subclasses
* allows configuration of tasks prior to shell execution
*
* @return void
*/
public function initialize() {
$this->_loadModels();
}
/**
* Starts up the Shell and displays the welcome message.
* Allows for checking and configuring prior to command or main execution
*
* Override this method if you want to remove the welcome information,
* or otherwise modify the pre-command flow.
*
* @return void
*/
public function startup() {
$this->_welcome();
}
/**
* Displays a header for the shell
*
* @return void
*/
protected function _welcome() {
$this->out();
$this->out(__d('cake_console', '<info>Welcome to CakePHP %s Console</info>', 'v' . Configure::version()));
$this->hr();
$this->out(__d('cake_console', 'App : %s', APP_DIR));
$this->out(__d('cake_console', 'Path: %s', APP));
$this->hr();
}
/**
* If $uses = true
* Loads AppModel file and constructs AppModel class
* makes $this->AppModel available to subclasses
* If public $uses is an array of models will load those models
*
* @return boolean
*/
protected function _loadModels() {
if ($this->uses === null || $this->uses === false) {
return;
}
App::uses('ClassRegistry', 'Utility');
if ($this->uses !== true && !empty($this->uses)) {
$uses = is_array($this->uses) ? $this->uses : array($this->uses);
$modelClassName = $uses[0];
if (strpos($uses[0], '.') !== false) {
list($plugin, $modelClassName) = explode('.', $uses[0]);
}
$this->modelClass = $modelClassName;
foreach ($uses as $modelClass) {
list($plugin, $modelClass) = pluginSplit($modelClass, true);
$this->{$modelClass} = ClassRegistry::init($plugin . $modelClass);
}
return true;
}
return false;
}
/**
* Loads tasks defined in public $tasks
*
* @return boolean
*/
public function loadTasks() {
if ($this->tasks === true || empty($this->tasks) || empty($this->Tasks)) {
return true;
}
$this->_taskMap = TaskCollection::normalizeObjectArray((array)$this->tasks);
foreach ($this->_taskMap as $task => $properties) {
$this->taskNames[] = $task;
}
return true;
}
/**
* Check to see if this shell has a task with the provided name.
*
* @param string $task The task name to check.
* @return boolean Success
*/
public function hasTask($task) {
return isset($this->_taskMap[Inflector::camelize($task)]);
}
/**
* Check to see if this shell has a callable method by the given name.
*
* @param string $name The method name to check.
* @return boolean
*/
public function hasMethod($name) {
if (empty($this->_reflection)) {
$this->_reflection = new ReflectionClass($this);
}
try {
$method = $this->_reflection->getMethod($name);
if (!$method->isPublic() || substr($name, 0, 1) === '_') {
return false;
}
if ($method->getDeclaringClass() != $this->_reflection) {
return false;
}
return true;
} catch (ReflectionException $e) {
return false;
}
}
/**
* Dispatch a command to another Shell. Similar to Object::requestAction()
* but intended for running shells from other shells.
*
* ### Usage:
*
* With a string command:
*
* `return $this->dispatchShell('schema create DbAcl');`
*
* Avoid using this form if you have string arguments, with spaces in them.
* The dispatched will be invoked incorrectly. Only use this form for simple
* command dispatching.
*
* With an array command:
*
* `return $this->dispatchShell('schema', 'create', 'i18n', '--dry');`
*
* @return mixed The return of the other shell.
*/
public function dispatchShell() {
$args = func_get_args();
if (is_string($args[0]) && count($args) == 1) {
$args = explode(' ', $args[0]);
}
$Dispatcher = new ShellDispatcher($args, false);
return $Dispatcher->dispatch();
}
/**
* Runs the Shell with the provided argv.
*
* Delegates calls to Tasks and resolves methods inside the class. Commands are looked
* up with the following order:
*
* - Method on the shell.
* - Matching task name.
* - `main()` method.
*
* If a shell implements a `main()` method, all missing method calls will be sent to
* `main()` with the original method name in the argv.
*
* @param string $command The command name to run on this shell. If this argument is empty,
* and the shell has a `main()` method, that will be called instead.
* @param array $argv Array of arguments to run the shell with. This array should be missing the shell name.
* @return void
*/
public function runCommand($command, $argv) {
$isTask = $this->hasTask($command);
$isMethod = $this->hasMethod($command);
$isMain = $this->hasMethod('main');
if ($isTask || $isMethod && $command !== 'execute') {
array_shift($argv);
}
try {
$this->OptionParser = $this->getOptionParser();
list($this->params, $this->args) = $this->OptionParser->parse($argv, $command);
} catch (ConsoleException $e) {
$this->out($this->OptionParser->help($command));
return false;
}
$this->command = $command;
if (!empty($this->params['help'])) {
return $this->_displayHelp($command);
}
if (($isTask || $isMethod || $isMain) && $command !== 'execute' ) {
$this->startup();
}
if ($isTask) {
$command = Inflector::camelize($command);
return $this->{$command}->runCommand('execute', $argv);
}
if ($isMethod) {
return $this->{$command}();
}
if ($isMain) {
return $this->main();
}
$this->out($this->OptionParser->help($command));
return false;
}
/**
* Display the help in the correct format
*
* @param string $command
* @return void
*/
protected function _displayHelp($command) {
$format = 'text';
if (!empty($this->args[0]) && $this->args[0] == 'xml') {
$format = 'xml';
$this->stdout->outputAs(ConsoleOutput::RAW);
} else {
$this->_welcome();
}
return $this->out($this->OptionParser->help($command, $format));
}
/**
* Gets the option parser instance and configures it.
* By overriding this method you can configure the ConsoleOptionParser before returning it.
*
* @return ConsoleOptionParser
*/
public function getOptionParser() {
$parser = new ConsoleOptionParser($this->name);
return $parser;
}
/**
* Overload get for lazy building of tasks
*
* @param string $name
* @return Shell Object of Task
*/
public function __get($name) {
if (empty($this->{$name}) && in_array($name, $this->taskNames)) {
$properties = $this->_taskMap[$name];
$this->{$name} = $this->Tasks->load($properties['class'], $properties['settings']);
$this->{$name}->args =& $this->args;
$this->{$name}->params =& $this->params;
$this->{$name}->initialize();
$this->{$name}->loadTasks();
}
return $this->{$name};
}
/**
* Prompts the user for input, and returns it.
*
* @param string $prompt Prompt text.
* @param mixed $options Array or string of options.
* @param string $default Default input value.
* @return mixed Either the default value, or the user-provided input.
*/
public function in($prompt, $options = null, $default = null) {
if (!$this->interactive) {
return $default;
}
$in = $this->_getInput($prompt, $options, $default);
if ($options && is_string($options)) {
if (strpos($options, ',')) {
$options = explode(',', $options);
} elseif (strpos($options, '/')) {
$options = explode('/', $options);
} else {
$options = array($options);
}
}
if (is_array($options)) {
while ($in === '' || ($in !== '' && (!in_array(strtolower($in), $options) && !in_array(strtoupper($in), $options)) && !in_array($in, $options))) {
$in = $this->_getInput($prompt, $options, $default);
}
}
return $in;
}
/**
* Prompts the user for input, and returns it.
*
* @param string $prompt Prompt text.
* @param mixed $options Array or string of options.
* @param string $default Default input value.
* @return Either the default value, or the user-provided input.
*/
protected function _getInput($prompt, $options, $default) {
if (!is_array($options)) {
$printOptions = '';
} else {
$printOptions = '(' . implode('/', $options) . ')';
}
if ($default === null) {
$this->stdout->write('<question>' . $prompt . '</question>' . " $printOptions \n" . '> ', 0);
} else {
$this->stdout->write('<question>' . $prompt . '</question>' . " $printOptions \n" . "[$default] > ", 0);
}
$result = $this->stdin->read();
if ($result === false) {
$this->_stop(1);
}
$result = trim($result);
if ($default !== null && ($result === '' || $result === null)) {
return $default;
}
return $result;
}
/**
* Wrap a block of text.
* Allows you to set the width, and indenting on a block of text.
*
* ### Options
*
* - `width` The width to wrap to. Defaults to 72
* - `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
* - `indent` Indent the text with the string provided. Defaults to null.
*
* @param string $text Text the text to format.
* @param mixed $options Array of options to use, or an integer to wrap the text to.
* @return string Wrapped / indented text
* @see String::wrap()
*/
public function wrapText($text, $options = array()) {
return String::wrap($text, $options);
}
/**
* Outputs a single or multiple messages to stdout. If no parameters
* are passed outputs just a newline.
*
* ### Output levels
*
* There are 3 built-in output level. Shell::QUIET, Shell::NORMAL, Shell::VERBOSE.
* The verbose and quiet output levels, map to the `verbose` and `quiet` output switches
* present in most shells. Using Shell::QUIET for a message means it will always display.
* While using Shell::VERBOSE means it will only display when verbose output is toggled.
*
* @param mixed $message A string or a an array of strings to output
* @param integer $newlines Number of newlines to append
* @param integer $level The message's output level, see above.
* @return integer|boolean Returns the number of bytes returned from writing to stdout.
*/
public function out($message = null, $newlines = 1, $level = Shell::NORMAL) {
$currentLevel = Shell::NORMAL;
if (!empty($this->params['verbose'])) {
$currentLevel = Shell::VERBOSE;
}
if (!empty($this->params['quiet'])) {
$currentLevel = Shell::QUIET;
}
if ($level <= $currentLevel) {
return $this->stdout->write($message, $newlines);
}
return true;
}
/**
* Outputs a single or multiple error messages to stderr. If no parameters
* are passed outputs just a newline.
*
* @param mixed $message A string or a an array of strings to output
* @param integer $newlines Number of newlines to append
* @return void
*/
public function err($message = null, $newlines = 1) {
$this->stderr->write($message, $newlines);
}
/**
* Returns a single or multiple linefeeds sequences.
*
* @param integer $multiplier Number of times the linefeed sequence should be repeated
* @return string
*/
public function nl($multiplier = 1) {
return str_repeat(ConsoleOutput::LF, $multiplier);
}
/**
* Outputs a series of minus characters to the standard output, acts as a visual separator.
*
* @param integer $newlines Number of newlines to pre- and append
* @param integer $width Width of the line, defaults to 63
* @return void
*/
public function hr($newlines = 0, $width = 63) {
$this->out(null, $newlines);
$this->out(str_repeat('-', $width));
$this->out(null, $newlines);
}
/**
* Displays a formatted error message
* and exits the application with status code 1
*
* @param string $title Title of the error
* @param string $message An optional error message
* @return void
*/
public function error($title, $message = null) {
$this->err(__d('cake_console', '<error>Error:</error> %s', $title));
if (!empty($message)) {
$this->err($message);
}
$this->_stop(1);
}
/**
* Clear the console
*
* @return void
*/
public function clear() {
if (empty($this->params['noclear'])) {
if (DS === '/') {
passthru('clear');
} else {
passthru('cls');
}
}
}
/**
* Creates a file at given path
*
* @param string $path Where to put the file.
* @param string $contents Content to put in the file.
* @return boolean Success
*/
public function createFile($path, $contents) {
$path = str_replace(DS . DS, DS, $path);
$this->out();
if (is_file($path) && $this->interactive === true) {
$this->out(__d('cake_console', '<warning>File `%s` exists</warning>', $path));
$key = $this->in(__d('cake_console', 'Do you want to overwrite?'), array('y', 'n', 'q'), 'n');
if (strtolower($key) == 'q') {
$this->out(__d('cake_console', '<error>Quitting</error>.'), 2);
$this->_stop();
} elseif (strtolower($key) != 'y') {
$this->out(__d('cake_console', 'Skip `%s`', $path), 2);
return false;
}
} else {
$this->out(__d('cake_console', 'Creating file %s', $path));
}
$File = new File($path, true);
if ($File->exists()) {
$data = $File->prepare($contents);
$File->write($data);
$this->out(__d('cake_console', '<success>Wrote</success> `%s`', $path));
return true;
} else {
$this->err(__d('cake_console', '<error>Could not write to `%s`</error>.', $path), 2);
return false;
}
}
/**
* Action to create a Unit Test
*
* @return boolean Success
*/
protected function _checkUnitTest() {
if (App::import('Vendor', 'phpunit', array('file' => 'PHPUnit' . DS . 'Autoload.php'))) {
return true;
}
if (@include 'PHPUnit' . DS . 'Autoload.php') {
return true;
}
$prompt = __d('cake_console', 'PHPUnit is not installed. Do you want to bake unit test files anyway?');
$unitTest = $this->in($prompt, array('y','n'), 'y');
$result = strtolower($unitTest) == 'y' || strtolower($unitTest) == 'yes';
if ($result) {
$this->out();
$this->out(__d('cake_console', 'You can download PHPUnit from %s', 'http://phpunit.de'));
}
return $result;
}
/**
* Makes absolute file path easier to read
*
* @param string $file Absolute file path
* @return string short path
*/
public function shortPath($file) {
$shortPath = str_replace(ROOT, null, $file);
$shortPath = str_replace('..' . DS, '', $shortPath);
return str_replace(DS . DS, DS, $shortPath);
}
/**
* Creates the proper controller path for the specified controller class name
*
* @param string $name Controller class name
* @return string Path to controller
*/
protected function _controllerPath($name) {
return Inflector::underscore($name);
}
/**
* Creates the proper controller plural name for the specified controller class name
*
* @param string $name Controller class name
* @return string Controller plural name
*/
protected function _controllerName($name) {
return Inflector::pluralize(Inflector::camelize($name));
}
/**
* Creates the proper controller camelized name (singularized) for the specified name
*
* @param string $name Name
* @return string Camelized and singularized controller name
*/
protected function _modelName($name) {
return Inflector::camelize(Inflector::singularize($name));
}
/**
* Creates the proper underscored model key for associations
*
* @param string $name Model class name
* @return string Singular model key
*/
protected function _modelKey($name) {
return Inflector::underscore($name) . '_id';
}
/**
* Creates the proper model name from a foreign key
*
* @param string $key Foreign key
* @return string Model name
*/
protected function _modelNameFromKey($key) {
return Inflector::camelize(str_replace('_id', '', $key));
}
/**
* creates the singular name for use in views.
*
* @param string $name
* @return string $name
*/
protected function _singularName($name) {
return Inflector::variable(Inflector::singularize($name));
}
/**
* Creates the plural name for views
*
* @param string $name Name to use
* @return string Plural name for views
*/
protected function _pluralName($name) {
return Inflector::variable(Inflector::pluralize($name));
}
/**
* Creates the singular human name used in views
*
* @param string $name Controller name
* @return string Singular human name
*/
protected function _singularHumanName($name) {
return Inflector::humanize(Inflector::underscore(Inflector::singularize($name)));
}
/**
* Creates the plural human name used in views
*
* @param string $name Controller name
* @return string Plural human name
*/
protected function _pluralHumanName($name) {
return Inflector::humanize(Inflector::underscore($name));
}
/**
* Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
*
* @param string $pluginName Name of the plugin you want ie. DebugKit
* @return string $path path to the correct plugin.
*/
protected function _pluginPath($pluginName) {
if (CakePlugin::loaded($pluginName)) {
return CakePlugin::path($pluginName);
}
return current(App::path('plugins')) . $pluginName . DS;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Shell.php | PHP | gpl3 | 20,403 |
<?php
/**
* HelpFormatter
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('String', 'Utility');
/**
* HelpFormatter formats help for console shells. Can format to either
* text or XML formats. Uses ConsoleOptionParser methods to generate help.
*
* Generally not directly used. Using $parser->help($command, 'xml'); is usually
* how you would access help. Or via the `--help=xml` option on the command line.
*
* Xml output is useful for integration with other tools like IDE's or other build tools.
*
* @package Cake.Console
* @since CakePHP(tm) v 2.0
*/
class HelpFormatter {
/**
* The maximum number of arguments shown when generating usage.
*
* @var integer
*/
protected $_maxArgs = 6;
/**
* The maximum number of options shown when generating usage.
*
* @var integer
*/
protected $_maxOptions = 6;
/**
* Build the help formatter for a an OptionParser
*
* @param ConsoleOptionParser $parser The option parser help is being generated for.
*/
public function __construct(ConsoleOptionParser $parser) {
$this->_parser = $parser;
}
/**
* Get the help as formatted text suitable for output on the command line.
*
* @param integer $width The width of the help output.
* @return string
*/
public function text($width = 72) {
$parser = $this->_parser;
$out = array();
$description = $parser->description();
if (!empty($description)) {
$out[] = String::wrap($description, $width);
$out[] = '';
}
$out[] = __d('cake_console', '<info>Usage:</info>');
$out[] = $this->_generateUsage();
$out[] = '';
$subcommands = $parser->subcommands();
if (!empty($subcommands)) {
$out[] = __d('cake_console', '<info>Subcommands:</info>');
$out[] = '';
$max = $this->_getMaxLength($subcommands) + 2;
foreach ($subcommands as $command) {
$out[] = String::wrap($command->help($max), array(
'width' => $width,
'indent' => str_repeat(' ', $max),
'indentAt' => 1
));
}
$out[] = '';
$out[] = __d('cake_console', 'To see help on a subcommand use <info>`cake %s [subcommand] --help`</info>', $parser->command());
$out[] = '';
}
$options = $parser->options();
if (!empty($options)) {
$max = $this->_getMaxLength($options) + 8;
$out[] = __d('cake_console', '<info>Options:</info>');
$out[] = '';
foreach ($options as $option) {
$out[] = String::wrap($option->help($max), array(
'width' => $width,
'indent' => str_repeat(' ', $max),
'indentAt' => 1
));
}
$out[] = '';
}
$arguments = $parser->arguments();
if (!empty($arguments)) {
$max = $this->_getMaxLength($arguments) + 2;
$out[] = __d('cake_console', '<info>Arguments:</info>');
$out[] = '';
foreach ($arguments as $argument) {
$out[] = String::wrap($argument->help($max), array(
'width' => $width,
'indent' => str_repeat(' ', $max),
'indentAt' => 1
));
}
$out[] = '';
}
$epilog = $parser->epilog();
if (!empty($epilog)) {
$out[] = String::wrap($epilog, $width);
$out[] = '';
}
return implode("\n", $out);
}
/**
* Generate the usage for a shell based on its arguments and options.
* Usage strings favor short options over the long ones. and optional args will
* be indicated with []
*
* @return string
*/
protected function _generateUsage() {
$usage = array('cake ' . $this->_parser->command());
$subcommands = $this->_parser->subcommands();
if (!empty($subcommands)) {
$usage[] = '[subcommand]';
}
$options = array();
foreach ($this->_parser->options() as $option) {
$options[] = $option->usage();
}
if (count($options) > $this->_maxOptions){
$options = array('[options]');
}
$usage = array_merge($usage, $options);
$args = array();
foreach ($this->_parser->arguments() as $argument) {
$args[] = $argument->usage();
}
if (count($args) > $this->_maxArgs) {
$args = array('[arguments]');
}
$usage = array_merge($usage, $args);
return implode(' ', $usage);
}
/**
* Iterate over a collection and find the longest named thing.
*
* @param array $collection
* @return integer
*/
protected function _getMaxLength($collection) {
$max = 0;
foreach ($collection as $item) {
$max = (strlen($item->name()) > $max) ? strlen($item->name()) : $max;
}
return $max;
}
/**
* Get the help as an xml string.
*
* @param boolean $string Return the SimpleXml object or a string. Defaults to true.
* @return mixed. See $string
*/
public function xml($string = true) {
$parser = $this->_parser;
$xml = new SimpleXmlElement('<shell></shell>');
$xml->addChild('command', $parser->command());
$xml->addChild('description', $parser->description());
$xml->addChild('epilog', $parser->epilog());
$subcommands = $xml->addChild('subcommands');
foreach ($parser->subcommands() as $command) {
$command->xml($subcommands);
}
$options = $xml->addChild('options');
foreach ($parser->options() as $option) {
$option->xml($options);
}
$arguments = $xml->addChild('arguments');
foreach ($parser->arguments() as $argument) {
$argument->xml($arguments);
}
return $string ? $xml->asXml() : $xml;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/HelpFormatter.php | PHP | gpl3 | 5,612 |
<?php
/**
* ConsoleInput file.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Console
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Object wrapper for interacting with stdin
*
* @package Cake.Console
*/
class ConsoleInput {
/**
* Input value.
*
* @var resource
*/
protected $_input;
/**
* Constructor
*
* @param string $handle The location of the stream to use as input.
*/
public function __construct($handle = 'php://stdin') {
$this->_input = fopen($handle, 'r');
}
/**
* Read a value from the stream
*
* @return mixed The value of the stream
*/
public function read() {
return fgets($this->_input);
}
} | 0001-bee | trunk/cakephp2/lib/Cake/Console/ConsoleInput.php | PHP | gpl3 | 1,125 |
<?php
/**
* ConsoleArgumentOption file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* An object to represent a single argument used in the command line.
* ConsoleOptionParser creates these when you use addArgument()
*
* @see ConsoleOptionParser::addArgument()
* @package Cake.Console
*/
class ConsoleInputArgument {
/**
* Name of the argument.
*
* @var string
*/
protected $_name;
/**
* Help string
*
* @var string
*/
protected $_help;
/**
* Is this option required?
*
* @var boolean
*/
protected $_required;
/**
* An array of valid choices for this argument.
*
* @var array
*/
protected $_choices;
/**
* Make a new Input Argument
*
* @param mixed $name The long name of the option, or an array with all the properties.
* @param string $help The help text for this option
* @param boolean $required Whether this argument is required. Missing required args will trigger exceptions
* @param array $choices Valid choices for this option.
*/
public function __construct($name, $help = '', $required = false, $choices = array()) {
if (is_array($name) && isset($name['name'])) {
foreach ($name as $key => $value) {
$this->{'_' . $key} = $value;
}
} else {
$this->_name = $name;
$this->_help = $help;
$this->_required = $required;
$this->_choices = $choices;
}
}
/**
* Get the value of the name attribute.
*
* @return string Value of this->_name.
*/
public function name() {
return $this->_name;
}
/**
* Generate the help for this argument.
*
* @param integer $width The width to make the name of the option.
* @return string
*/
public function help($width = 0) {
$name = $this->_name;
if (strlen($name) < $width) {
$name = str_pad($name, $width, ' ');
}
$optional = '';
if (!$this->isRequired()) {
$optional = __d('cake_console', ' <comment>(optional)</comment>');
}
if (!empty($this->_choices)) {
$optional .= __d('cake_console', ' <comment>(choices: %s)</comment>', implode('|', $this->_choices));
}
return sprintf('%s%s%s', $name, $this->_help, $optional);
}
/**
* Get the usage value for this argument
*
* @return string
*/
public function usage() {
$name = $this->_name;
if (!empty($this->_choices)) {
$name = implode('|', $this->_choices);
}
$name = '<' . $name . '>';
if (!$this->isRequired()) {
$name = '[' . $name . ']';
}
return $name;
}
/**
* Check if this argument is a required argument
*
* @return boolean
*/
public function isRequired() {
return (bool) $this->_required;
}
/**
* Check that $value is a valid choice for this argument.
*
* @param string $value
* @return boolean
* @throws ConsoleException
*/
public function validChoice($value) {
if (empty($this->_choices)) {
return true;
}
if (!in_array($value, $this->_choices)) {
throw new ConsoleException(
__d('cake_console', '"%s" is not a valid value for %s. Please use one of "%s"',
$value, $this->_name, implode(', ', $this->_choices)
));
}
return true;
}
/**
* Append this arguments XML representation to the passed in SimpleXml object.
*
* @param SimpleXmlElement $parent The parent element.
* @return SimpleXmlElement The parent with this argument appended.
*/
public function xml(SimpleXmlElement $parent) {
$option = $parent->addChild('argument');
$option->addAttribute('name', $this->_name);
$option->addAttribute('help', $this->_help);
$option->addAttribute('required', $this->isRequired());
$choices = $option->addChild('choices');
foreach ($this->_choices as $valid) {
$choices->addChild('choice', $valid);
}
return $parent;
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/ConsoleInputArgument.php | PHP | gpl3 | 4,131 |
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.View.Emails.html
* @since CakePHP(tm) v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<?php
$content = explode("\n", $content);
foreach ($content as $line):
echo '<p> ' . $line . '</p>';
endforeach;
?> | 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/View/Emails/html/default.ctp | PHP | gpl3 | 727 |
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.View.Emails.text
* @since CakePHP(tm) v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<?php echo $content; ?> | 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/View/Emails/text/default.ctp | PHP | gpl3 | 633 |
<?php echo $scripts_for_layout; ?>
<script type="text/javascript"><?php echo $content_for_layout; ?></script> | 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/View/Layouts/js/default.ctp | PHP | gpl3 | 109 |
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.View.Layouts
* @since CakePHP(tm) v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<?php echo $content_for_layout; ?> | 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/View/Layouts/ajax.ctp | PHP | gpl3 | 640 |
<?php echo $xml->header(); ?>
<?php echo $content_for_layout; ?> | 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/View/Layouts/xml/default.ctp | PHP | gpl3 | 64 |
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.View.Layouts
* @since CakePHP(tm) v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php echo $this->Html->charset(); ?>
<title><?php echo $page_title; ?></title>
<?php if (Configure::read('debug') == 0) { ?>
<meta http-equiv="Refresh" content="<?php echo $pause?>;url=<?php echo $url?>"/>
<?php } ?>
<style><!--
P { text-align:center; font:bold 1.1em sans-serif }
A { color:#444; text-decoration:none }
A:HOVER { text-decoration: underline; color:#44E }
--></style>
</head>
<body>
<p><a href="<?php echo $url?>"><?php echo $message?></a></p>
</body>
</html> | 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/View/Layouts/flash.ctp | PHP | gpl3 | 1,255 |
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.View.Layouts
* @since CakePHP(tm) v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php echo $this->Html->charset(); ?>
<title>
<?php echo __('CakePHP: the rapid development php framework:'); ?>
<?php echo $title_for_layout; ?>
</title>
<?php
echo $this->Html->meta('icon');
echo $this->Html->css('cake.generic');
echo $scripts_for_layout;
?>
</head>
<body>
<div id="container">
<div id="header">
<h1><?php echo $this->Html->link(__('CakePHP: the rapid development php framework'), 'http://cakephp.org'); ?></h1>
</div>
<div id="content">
<?php echo $this->Session->flash(); ?>
<?php echo $content_for_layout; ?>
</div>
<div id="footer">
<?php echo $this->Html->link(
$this->Html->image('cake.power.gif', array('alt'=> __('CakePHP: the rapid development php framework'), 'border' => '0')),
'http://www.cakephp.org/',
array('target' => '_blank', 'escape' => false)
);
?>
</div>
</div>
<?php echo $this->element('sql_dump'); ?>
</body>
</html> | 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/View/Layouts/default.ctp | PHP | gpl3 | 1,707 |
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.View.Layouts.Email.html
* @since CakePHP(tm) v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title><?php echo $title_for_layout;?></title>
</head>
<body>
<?php echo $content_for_layout;?>
<p>This email was sent using the <a href="http://cakephp.org">CakePHP Framework</a></p>
</body>
</html> | 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/View/Layouts/Emails/html/default.ctp | PHP | gpl3 | 887 |
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.View.Layouts.Email.text
* @since CakePHP(tm) v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<?php echo $content_for_layout;?>
This email was sent using the CakePHP Framework, http://cakephp.org.
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/View/Layouts/Emails/text/default.ctp | PHP | gpl3 | 722 |
<?php
echo $rss->header();
if (!isset($channel)) {
$channel = array();
}
if (!isset($channel['title'])) {
$channel['title'] = $title_for_layout;
}
echo $rss->document(
$rss->channel(
array(), $channel, $content_for_layout
)
);
?> | 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/View/Layouts/rss/default.ctp | PHP | gpl3 | 238 |
<?php
/**
* Application level View Helper
*
* This file is application-wide helper file. You can put all
* application-wide helper-related methods here.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.View.Helper
* @since CakePHP(tm) v 0.2.9
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Helper', 'View');
/**
* This is a placeholder class.
* Create the same file in app/View/Helper/AppHelper.php
*
* Add your application-wide methods in the class below, your helpers
* will inherit them.
*
* @package app.View.Helper
*/
class AppHelper extends Helper {
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/View/Helper/AppHelper.php | PHP | gpl3 | 1,037 |
<?php
/**
* Index
*
* The Front Controller for handling every request
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.webroot
* @since CakePHP(tm) v 0.2.9
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Use the DS to separate the directories in other defines
*/
if (!defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
}
/**
* These defines should only be edited if you have cake installed in
* a directory layout other than the way it is distributed.
* When using custom settings be sure to use the DS and do not add a trailing DS.
*/
/**
* The full path to the directory which holds "app", WITHOUT a trailing DS.
*
*/
if (!defined('ROOT')) {
define('ROOT', dirname(dirname(dirname(__FILE__))));
}
/**
* The actual directory name for the "app".
*
*/
if (!defined('APP_DIR')) {
define('APP_DIR', basename(dirname(dirname(__FILE__))));
}
/**
* The absolute path to the "cake" directory, WITHOUT a trailing DS.
*
* Un-comment this line to specify a fixed path to CakePHP.
* This should point at the directory containg `Cake`.
*
* For ease of development CakePHP uses PHP's include_path. If you
* cannot modify your include_path set this value.
*
* Leaving this constant undefined will result in it being defined in Cake/bootstrap.php
*/
//define('CAKE_CORE_INCLUDE_PATH', __CAKE_PATH__);
/**
* Editing below this line should NOT be necessary.
* Change at your own risk.
*
*/
if (!defined('WEBROOT_DIR')) {
define('WEBROOT_DIR', basename(dirname(__FILE__)));
}
if (!defined('WWW_ROOT')) {
define('WWW_ROOT', dirname(__FILE__) . DS);
}
if (!defined('CAKE_CORE_INCLUDE_PATH')) {
if (function_exists('ini_set')) {
ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR . ini_get('include_path'));
}
if (!include('Cake' . DS . 'bootstrap.php')) {
$failed = true;
}
} else {
if (!include(CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) {
$failed = true;
}
}
if (!empty($failed)) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
}
if (isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] == '/favicon.ico') {
return;
}
App::uses('Dispatcher', 'Routing');
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch(new CakeRequest(), new CakeResponse(array('charset' => Configure::read('App.encoding'))));
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/webroot/index.php | PHP | gpl3 | 2,968 |
<?php
/**
* Web Access Frontend for TestSuite
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing
* @package app.webroot
* @since CakePHP(tm) v 1.2.0.4433
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
set_time_limit(0);
ini_set('display_errors', 1);
/**
* Use the DS to separate the directories in other defines
*/
if (!defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
}
/**
* These defines should only be edited if you have cake installed in
* a directory layout other than the way it is distributed.
* When using custom settings be sure to use the DS and do not add a trailing DS.
*/
/**
* The full path to the directory which holds "app", WITHOUT a trailing DS.
*
*/
if (!defined('ROOT')) {
define('ROOT', dirname(dirname(dirname(__FILE__))));
}
/**
* The actual directory name for the "app".
*
*/
if (!defined('APP_DIR')) {
define('APP_DIR', basename(dirname(dirname(__FILE__))));
}
/**
* The absolute path to the "Cake" directory, WITHOUT a trailing DS.
*
* For ease of development CakePHP uses PHP's include_path. If you
* need to cannot modify your include_path, you can set this path.
*
* Leaving this constant undefined will result in it being defined in Cake/bootstrap.php
*/
//define('CAKE_CORE_INCLUDE_PATH', __CAKE_PATH__);
/**
* Editing below this line should not be necessary.
* Change at your own risk.
*
*/
if (!defined('WEBROOT_DIR')) {
define('WEBROOT_DIR', basename(dirname(__FILE__)));
}
if (!defined('WWW_ROOT')) {
define('WWW_ROOT', dirname(__FILE__) . DS);
}
if (!defined('CAKE_CORE_INCLUDE_PATH')) {
if (!include('Cake' . DS . 'bootstrap.php')) {
$failed = true;
}
} else {
if (!include(CAKE_CORE_INCLUDE_PATH . DS . 'Cake' . DS . 'bootstrap.php')) {
$failed = true;
}
}
if (!empty($failed)) {
trigger_error("CakePHP core could not be found. Check the value of CAKE_CORE_INCLUDE_PATH in APP/webroot/index.php. It should point to the directory containing your " . DS . "cake core directory and your " . DS . "vendors root directory.", E_USER_ERROR);
}
if (Configure::read('debug') < 1) {
die(__d('cake_dev', 'Debug setting does not allow access to this url.'));
}
require_once CAKE . 'TestSuite' . DS . 'CakeTestSuiteDispatcher.php';
CakeTestSuiteDispatcher::run();
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/webroot/test.php | PHP | gpl3 | 2,685 |
/**
*
* Generic CSS for CakePHP
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.webroot.css
* @since CakePHP(tm)
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
* {
margin:0;
padding:0;
}
/** General Style Info **/
body {
background: #003d4c;
color: #fff;
font-family:'lucida grande',verdana,helvetica,arial,sans-serif;
font-size:90%;
margin: 0;
}
a {
color: #003d4c;
text-decoration: underline;
font-weight: bold;
}
a:hover {
color: #367889;
text-decoration:none;
}
a img {
border:none;
}
h1, h2, h3, h4 {
font-weight: normal;
margin-bottom:0.5em;
}
h1 {
background:#fff;
color: #003d4c;
font-size: 100%;
}
h2 {
background:#fff;
color: #e32;
font-family:'Gill Sans','lucida grande', helvetica, arial, sans-serif;
font-size: 190%;
}
h3 {
color: #2c6877;
font-family:'Gill Sans','lucida grande', helvetica, arial, sans-serif;
font-size: 165%;
}
h4 {
color: #993;
font-weight: normal;
}
ul, li {
margin: 0 12px;
}
p {
margin: 0 0 1em 0;
}
/** Layout **/
#container {
text-align: left;
}
#header{
padding: 10px 20px;
}
#header h1 {
line-height:20px;
background: #003d4c url('../img/cake.icon.png') no-repeat left;
color: #fff;
padding: 0px 30px;
}
#header h1 a {
color: #fff;
background: #003d4c;
font-weight: normal;
text-decoration: none;
}
#header h1 a:hover {
color: #fff;
background: #003d4c;
text-decoration: underline;
}
#content{
background: #fff;
clear: both;
color: #333;
padding: 10px 20px 40px 20px;
overflow: auto;
}
#footer {
clear: both;
padding: 6px 10px;
text-align: right;
}
/** containers **/
div.form,
div.index,
div.view {
float:right;
width:76%;
border-left:1px solid #666;
padding:10px 2%;
}
div.actions {
float:left;
width:16%;
padding:10px 1.5%;
}
div.actions h3 {
padding-top:0;
color:#777;
}
/** Tables **/
table {
border-right:0;
clear: both;
color: #333;
margin-bottom: 10px;
width: 100%;
}
th {
border:0;
border-bottom:2px solid #555;
text-align: left;
padding:4px;
}
th a {
display: block;
padding: 2px 4px;
text-decoration: none;
}
th a.asc:after {
content: ' ⇣';
}
th a.desc:after {
content: ' ⇡';
}
table tr td {
padding: 6px;
text-align: left;
vertical-align: top;
border-bottom:1px solid #ddd;
}
table tr:nth-child(even) {
background: #f9f9f9;
}
td.actions {
text-align: center;
white-space: nowrap;
}
table td.actions a {
margin: 0px 6px;
padding:2px 5px;
}
/* SQL log */
.cake-sql-log {
background: #fff;
}
.cake-sql-log td {
padding: 4px 8px;
text-align: left;
font-family: Monaco, Consolas, "Courier New", monospaced;
}
.cake-sql-log caption {
color:#fff;
}
/** Paging **/
.paging {
background:#fff;
color: #ccc;
margin-top: 1em;
clear:both;
}
.paging .current,
.paging .disabled,
.paging a {
text-decoration: none;
padding: 5px 8px;
display: inline-block
}
.paging > span {
display: inline-block;
border: 1px solid #ccc;
border-left: 0;
}
.paging > span:hover {
background: #efefef;
}
.paging .prev {
border-left: 1px solid #ccc;
-moz-border-radius: 4px 0 0 4px;
-webkit-border-radius: 4px 0 0 4px;
border-radius: 4px 0 0 4px;
}
.paging .next {
-moz-border-radius: 0 4px 4px 0;
-webkit-border-radius: 0 4px 4px 0;
border-radius: 0 4px 4px 0;
}
.paging .disabled {
color: #ddd;
}
.paging .disabled:hover {
background: transparent;
}
.paging .current {
background: #efefef;
color: #c73e14;
}
/** Scaffold View **/
dl {
line-height: 2em;
margin: 0em 0em;
width: 60%;
}
dl dd:nth-child(4n+2),
dl dt:nth-child(4n+1) {
background: #f4f4f4;
}
dt {
font-weight: bold;
padding-left: 4px;
vertical-align: top;
width: 10em;
}
dd {
margin-left: 10em;
margin-top: -2em;
vertical-align: top;
}
/** Forms **/
form {
clear: both;
margin-right: 20px;
padding: 0;
width: 95%;
}
fieldset {
border: none;
margin-bottom: 1em;
padding: 16px 10px;
}
fieldset legend {
color: #e32;
font-size: 160%;
font-weight: bold;
}
fieldset fieldset {
margin-top: 0;
padding: 10px 0 0;
}
fieldset fieldset legend {
font-size: 120%;
font-weight: normal;
}
fieldset fieldset div {
clear: left;
margin: 0 20px;
}
form div {
clear: both;
margin-bottom: 1em;
padding: .5em;
vertical-align: text-top;
}
form .input {
color: #444;
}
form .required {
font-weight: bold;
}
form .required label:after {
color: #e32;
content: '*';
display:inline;
}
form div.submit {
border: 0;
clear: both;
margin-top: 10px;
}
label {
display: block;
font-size: 110%;
margin-bottom:3px;
}
input, textarea {
clear: both;
font-size: 140%;
font-family: "frutiger linotype", "lucida grande", "verdana", sans-serif;
padding: 1%;
width:98%;
}
select {
clear: both;
font-size: 120%;
vertical-align: text-bottom;
}
select[multiple=multiple] {
width: 100%;
}
option {
font-size: 120%;
padding: 0 3px;
}
input[type=checkbox] {
clear: left;
float: left;
margin: 0px 6px 7px 2px;
width: auto;
}
div.checkbox label {
display: inline;
}
input[type=radio] {
float:left;
width:auto;
margin: 6px 0;
padding: 0;
line-height: 26px;
}
.radio label {
margin: 0 0 6px 20px;
line-height: 26px;
}
input[type=submit] {
display: inline;
font-size: 110%;
width: auto;
}
form .submit input[type=submit] {
background:#62af56;
background-image: -webkit-gradient(linear, left top, left bottom, from(#76BF6B), to(#3B8230));
background-image: -webkit-linear-gradient(top, #76BF6B, #3B8230);
background-image: -moz-linear-gradient(top, #76BF6B, #3B8230);
border-color: #2d6324;
color: #fff;
text-shadow: rgba(0, 0, 0, 0.5) 0px -1px 0px;
padding: 8px 10px;
}
form .submit input[type=submit]:hover {
background: #5BA150;
}
/* Form errors */
form .error {
background: #FFDACC;
-moz-order-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
font-weight: normal;
}
form .error-message {
-moz-border-radius: none;
-webkit-border-radius: none;
border-radius: none;
border: none;
background: none;
margin: 0;
padding-left: 4px;
padding-right: 0;
}
form .error,
form .error-message {
color: #9E2424;
-webkit-box-shadow: none;
-moz-box-shadow: none;
-ms-box-shadow: none;
-o-box-shadow: none;
box-shadow: none;
text-shadow: none;
}
/** Notices and Errors **/
.message {
clear: both;
color: #fff;
font-size: 140%;
font-weight: bold;
margin: 0 0 1em 0;
padding: 5px;
}
.success,
.message,
.cake-error,
.cake-debug,
.notice,
p.error,
.error-message {
background: #ffcc00;
background-repeat: repeat-x;
background-image: -moz-linear-gradient(top, #ffcc00, #E6B800);
background-image: -ms-linear-gradient(top, #ffcc00, #E6B800);
background-image: -webkit-gradient(linear, left top, left bottom, from(#ffcc00), to(#E6B800));
background-image: -webkit-linear-gradient(top, #ffcc00, #E6B800);
background-image: -o-linear-gradient(top, #ffcc00, #E6B800);
background-image: linear-gradient(top, #ffcc00, #E6B800);
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
border: 1px solid rgba(0, 0, 0, 0.2);
margin-bottom: 18px;
padding: 7px 14px;
color: #404040;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25);
-moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25);
}
.success,
.message,
.cake-error,
p.error,
.error-message {
clear: both;
color: #fff;
background: #c43c35;
border: 1px solid rgba(0, 0, 0, 0.5);
background-repeat: repeat-x;
background-image: -moz-linear-gradient(top, #ee5f5b, #c43c35);
background-image: -ms-linear-gradient(top, #ee5f5b, #c43c35);
background-image: -webkit-gradient(linear, left top, left bottom, from(#ee5f5b), to(#c43c35));
background-image: -webkit-linear-gradient(top, #ee5f5b, #c43c35);
background-image: -o-linear-gradient(top, #ee5f5b, #c43c35);
background-image: linear-gradient(top, #ee5f5b, #c43c35);
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.3);
}
.success {
clear: both;
color: #fff;
border: 1px solid rgba(0, 0, 0, 0.5);
background: #3B8230;
background-repeat: repeat-x;
background-image: -webkit-gradient(linear, left top, left bottom, from(#76BF6B), to(#3B8230));
background-image: -webkit-linear-gradient(top, #76BF6B, #3B8230);
background-image: -moz-linear-gradient(top, #76BF6B, #3B8230);
background-image: -ms-linear-gradient(top, #76BF6B, #3B8230);
background-image: -o-linear-gradient(top, #76BF6B, #3B8230);
background-image: linear-gradient(top, #76BF6B, #3B8230);
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.3);
}
p.error {
font-family: Monaco, Consolas, Courier, monospace;
font-size: 120%;
padding: 0.8em;
margin: 1em 0;
}
p.error em {
font-weight: normal;
line-height: 140%;
}
.notice {
color: #000;
display: block;
font-size: 120%;
padding: 0.8em;
margin: 1em 0;
}
.success {
color: #fff;
}
/** Actions **/
.actions ul {
margin: 0;
padding: 0;
}
.actions li {
margin:0 0 0.5em 0;
list-style-type: none;
white-space: nowrap;
padding: 0;
}
.actions ul li a {
font-weight: normal;
display: block;
clear: both;
}
/* Buttons and button links */
input[type=submit],
.actions ul li a,
.actions a {
font-weight:normal;
padding: 4px 8px;
background: #dcdcdc;
background-image: -webkit-gradient(linear, left top, left bottom, from(#fefefe), to(#dcdcdc));
background-image: -webkit-linear-gradient(top, #fefefe, #dcdcdc);
background-image: -moz-linear-gradient(top, #fefefe, #dcdcdc);
background-image: -ms-linear-gradient(top, #fefefe, #dcdcdc);
background-image: -o-linear-gradient(top, #fefefe, #dcdcdc);
background-image: linear-gradient(top, #fefefe, #dcdcdc);
color:#333;
border:1px solid #bbb;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
text-decoration: none;
text-shadow: #fff 0px 1px 0px;
min-width: 0;
-moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3), 0px 1px 1px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3), 0px 1px 1px rgba(0, 0, 0, 0.2);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3), 0px 1px 1px rgba(0, 0, 0, 0.2);
-webkit-user-select: none;
user-select: none;
}
.actions ul li a:hover,
.actions a:hover {
background: #ededed;
border-color: #acacac;
text-decoration: none;
}
input[type=submit]:active,
.actions ul li a:active,
.actions a:active {
background: #eee;
background-image: -webkit-gradient(linear, left top, left bottom, from(#dfdfdf), to(#eee));
background-image: -webkit-linear-gradient(top, #dfdfdf, #eee);
background-image: -moz-linear-gradient(top, #dfdfdf, #eee);
background-image: -ms-linear-gradient(top, #dfdfdf, #eee);
background-image: -o-linear-gradient(top, #dfdfdf, #eee);
background-image: linear-gradient(top, #dfdfdf, #eee);
text-shadow: #eee 0px 1px 0px;
-moz-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.3);
-webkit-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.3);
box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.3);
border-color: #aaa;
text-decoration: none;
}
/** Related **/
.related {
clear: both;
display: block;
}
/** Debugging **/
pre {
color: #000;
background: #f0f0f0;
padding: 15px;
-moz-box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
-webkit-box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
}
.cake-debug-output {
padding: 0;
position: relative;
}
.cake-debug-output > span {
position: absolute;
top: 5px;
right: 5px;
background: rgba(255, 255, 255, 0.3);
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
padding: 5px 6px;
color: #000;
display: block;
float: left;
-moz-box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.25), 0 1px 0 rgba(255, 255, 255, 0.5);
-webkit-box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.25), 0 1px 0 rgba(255, 255, 255, 0.5);
box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.25), 0 1px 0 rgba(255, 255, 255, 0.5);
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);
}
.cake-debug,
.cake-error {
font-size: 16px;
line-height: 20px;
clear: both;
}
.cake-error > a {
text-shadow: none;
}
.cake-error {
white-space: normal;
}
.cake-stack-trace {
background: rgba(255, 255, 255, 0.7);
color: #333;
margin: 10px 0 5px 0;
padding: 10px 10px 0 10px;
font-size: 120%;
line-height: 140%;
overflow: auto;
position: relative;
-moz-border-radius: 4px;
-wekbkit-border-radius: 4px;
border-radius: 4px;
}
.cake-stack-trace a {
text-shadow: none;
background: rgba(255, 255, 255, 0.7);
padding: 5px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
margin: 0px 4px 10px 2px;
font-family: sans-serif;
font-size: 14px;
line-height: 14px;
display: inline-block;
text-decoration: none;
-moz-box-shadow: inset 0px 1px 0 rgba(0, 0, 0, 0.3);
-webkit-box-shadow: inset 0px 1px 0 rgba(0, 0, 0, 0.3);
box-shadow: inset 0px 1px 0 rgba(0, 0, 0, 0.3);
}
.cake-code-dump pre {
position: relative;
overflow: auto;
}
.cake-context {
margin-bottom: 10px;
}
.cake-stack-trace pre {
color: #000;
background-color: #F0F0F0;
margin: 0px 0 10px 0;
padding: 1em;
overflow: auto;
text-shadow: none;
}
/* excerpt */
.cake-code-dump pre,
.cake-code-dump pre code {
clear: both;
font-size: 12px;
line-height: 15px;
margin: 4px 2px;
padding: 4px;
overflow: auto;
}
.cake-code-dump .code-highlight {
display: block;
background-color: rgba(255, 255, 0, 0.5);
}
.code-coverage-results div.code-line {
padding-left:5px;
display:block;
margin-left:10px;
}
.code-coverage-results div.uncovered span.content {
background:#ecc;
}
.code-coverage-results div.covered span.content {
background:#cec;
}
.code-coverage-results div.ignored span.content {
color:#aaa;
}
.code-coverage-results span.line-num {
color:#666;
display:block;
float:left;
width:20px;
text-align:right;
margin-right:5px;
}
.code-coverage-results span.line-num strong {
color:#666;
}
.code-coverage-results div.start {
border:1px solid #aaa;
border-width:1px 1px 0px 1px;
margin-top:30px;
padding-top:5px;
}
.code-coverage-results div.end {
border:1px solid #aaa;
border-width:0px 1px 1px 1px;
margin-bottom:30px;
padding-bottom:5px;
}
.code-coverage-results div.realstart {
margin-top:0px;
}
.code-coverage-results p.note {
color:#bbb;
padding:5px;
margin:5px 0 10px;
font-size:10px;
}
.code-coverage-results span.result-bad {
color: #a00;
}
.code-coverage-results span.result-ok {
color: #fa0;
}
.code-coverage-results span.result-good {
color: #0a0;
}
/** Elements **/
#url-rewriting-warning {
display:none;
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/webroot/css/cake.generic.css | CSS | gpl3 | 14,775 |
<?php
/**
* Static content controller.
*
* This file will render views from views/pages/
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.Controller
* @since CakePHP(tm) v 0.2.9
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Static content controller
*
* Override this controller by placing a copy in controllers directory of an application
*
* @package app.Controller
*/
class PagesController extends AppController {
/**
* Controller name
*
* @var string
*/
public $name = 'Pages';
/**
* Default helper
*
* @var array
*/
public $helpers = array('Html');
/**
* This controller does not use a model
*
* @var array
*/
public $uses = array();
/**
* Displays a view
*
* @param mixed What page to display
*/
public function display() {
$path = func_get_args();
$count = count($path);
if (!$count) {
$this->redirect('/');
}
$page = $subpage = $title_for_layout = null;
if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
if (!empty($path[$count - 1])) {
$title_for_layout = Inflector::humanize($path[$count - 1]);
}
$this->set(compact('page', 'subpage', 'title_for_layout'));
$this->render(implode('/', $path));
}
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Controller/PagesController.php | PHP | gpl3 | 1,685 |
<?php
/**
* Application level Controller
*
* This file is application-wide controller file. You can put all
* application-wide controller-related methods here.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.Controller
* @since CakePHP(tm) v 0.2.9
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Controller', 'Controller');
/**
* Application Controller
*
* Add your application-wide methods in the class below, your controllers
* will inherit them.
*
* @package app.Controller
*/
class AppController extends Controller {
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Controller/AppController.php | PHP | gpl3 | 1,002 |
<?php
/**
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app
* @since CakePHP(tm) v 0.10.0.1076
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
require 'webroot' . DIRECTORY_SEPARATOR . 'index.php';
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/index.php | PHP | gpl3 | 642 |
#!/usr/bin/php -q
<?php
/**
* Command-line code generation utility to automate programmer chores.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.Console
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
$ds = DIRECTORY_SEPARATOR;
$dispatcher = 'Cake' . $ds . 'Console' . $ds . 'ShellDispatcher.php';
$found = false;
$paths = explode(PATH_SEPARATOR, ini_get('include_path'));
foreach ($paths as $path) {
if (file_exists($path . $ds . $dispatcher)) {
$found = $path;
}
}
if (!$found && function_exists('ini_set')) {
$root = dirname(dirname(dirname(__FILE__)));
ini_set('include_path', __CAKE_PATH__ . PATH_SEPARATOR . ini_get('include_path'));
}
if (!include($dispatcher)) {
trigger_error('Could not locate CakePHP core files.', E_USER_ERROR);
}
unset($paths, $path, $found, $dispatcher, $root, $ds);
return ShellDispatcher::run($argv);
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Console/cake.php | PHP | gpl3 | 1,294 |
#!/bin/bash
################################################################################
#
# Bake is a shell script for running CakePHP bake script
# PHP 5
#
# CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
# Copyright 2005-2011, Cake Software Foundation, Inc.
#
# Licensed under The MIT License
# Redistributions of files must retain the above copyright notice.
#
# @copyright Copyright 2005-2011, Cake Software Foundation, Inc.
# @link http://cakephp.org CakePHP(tm) Project
# @package app.Console
# @since CakePHP(tm) v 2.0
# @license MIT License (http://www.opensource.org/licenses/mit-license.php)
#
################################################################################
LIB=$(cd -P -- "$(dirname -- "$0")" && pwd -P) && LIB=$LIB/$(basename -- "$0")
while [ -h "$LIB" ]; do
DIR=$(dirname -- "$LIB")
SYM=$(readlink "$LIB")
LIB=$(cd "$DIR" && cd $(dirname -- "$SYM") && pwd)/$(basename -- "$SYM")
done
LIB=$(dirname -- "$LIB")/
APP=`pwd`
exec php -q "$LIB"cake.php -working "$APP" "$@"
exit; | 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Console/.svn/text-base/cake.svn-base | Shell | gpl3 | 1,050 |
#!/usr/bin/php -q
<?php
/**
* Command-line code generation utility to automate programmer chores.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.Console
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
$ds = DIRECTORY_SEPARATOR;
$dispatcher = 'Cake' . $ds . 'Console' . $ds . 'ShellDispatcher.php';
$found = false;
$paths = explode(PATH_SEPARATOR, ini_get('include_path'));
foreach ($paths as $path) {
if (file_exists($path . $ds . $dispatcher)) {
$found = $path;
}
}
if (!$found && function_exists('ini_set')) {
$root = dirname(dirname(dirname(__FILE__)));
ini_set('include_path', __CAKE_PATH__ . PATH_SEPARATOR . ini_get('include_path'));
}
if (!include($dispatcher)) {
trigger_error('Could not locate CakePHP core files.', E_USER_ERROR);
}
unset($paths, $path, $found, $dispatcher, $root, $ds);
return ShellDispatcher::run($argv);
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Console/.svn/text-base/cake.php.svn-base | PHP | gpl3 | 1,294 |
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: Bake is a shell script for running CakePHP bake script
:: PHP 5
::
:: CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
:: Copyright 2005-2011, Cake Software Foundation, Inc.
::
:: Licensed under The MIT License
:: Redistributions of files must retain the above copyright notice.
::
:: @copyright Copyright 2005-2011, Cake Software Foundation, Inc.
:: @link http://cakephp.org CakePHP(tm) Project
:: @package app.Console
:: @since CakePHP(tm) v 2.0
:: @license MIT License (http://www.opensource.org/licenses/mit-license.php)
::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: In order for this script to work as intended, the cake\console\ folder must be in your PATH
@echo.
@echo off
SET app=%0
SET lib=%~dp0
php -q "%lib%cake.php" -working "%CD% " %*
echo.
exit /B %ERRORLEVEL%
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Console/cake.bat | Batchfile | gpl3 | 963 |
#!/bin/bash
################################################################################
#
# Bake is a shell script for running CakePHP bake script
# PHP 5
#
# CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
# Copyright 2005-2011, Cake Software Foundation, Inc.
#
# Licensed under The MIT License
# Redistributions of files must retain the above copyright notice.
#
# @copyright Copyright 2005-2011, Cake Software Foundation, Inc.
# @link http://cakephp.org CakePHP(tm) Project
# @package app.Console
# @since CakePHP(tm) v 2.0
# @license MIT License (http://www.opensource.org/licenses/mit-license.php)
#
################################################################################
LIB=$(cd -P -- "$(dirname -- "$0")" && pwd -P) && LIB=$LIB/$(basename -- "$0")
while [ -h "$LIB" ]; do
DIR=$(dirname -- "$LIB")
SYM=$(readlink "$LIB")
LIB=$(cd "$DIR" && cd $(dirname -- "$SYM") && pwd)/$(basename -- "$SYM")
done
LIB=$(dirname -- "$LIB")/
APP=`pwd`
exec php -q "$LIB"cake.php -working "$APP" "$@"
exit; | 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Console/cake | Shell | gpl3 | 1,050 |
<?php
/**
* Routes configuration
*
* In this file, you set up routes to your controllers and their actions.
* Routes are very important mechanism that allows you to freely connect
* different urls to chosen controllers and their actions (functions).
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.Config
* @since CakePHP(tm) v 0.2.9
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Here, we are connecting '/' (base path) to controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, /app/View/Pages/home.ctp)...
*/
Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
/**
* ...and connect the rest of 'Pages' controller's urls.
*/
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
/**
* Load all plugin routes. See the CakePlugin documentation on
* how to customize the loading of plugin routes.
*/
CakePlugin::routes();
/**
* Load the CakePHP default routes. Remove this if you do not want to use
* the built-in default routes.
*/
require CAKE . 'Config' . DS . 'routes.php';
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Config/routes.php | PHP | gpl3 | 1,591 |
;<?php exit() ?>
;/**
; * ACL Configuration
; *
; *
; * PHP 5
; *
; * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
; * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
; *
; * Licensed under The MIT License
; * Redistributions of files must retain the above copyright notice.
; *
; * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
; * @link http://cakephp.org CakePHP(tm) Project
; * @package app.Config
; * @since CakePHP(tm) v 0.10.0.1076
; * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
; */
; acl.ini.php - Cake ACL Configuration
; ---------------------------------------------------------------------
; Use this file to specify user permissions.
; aco = access control object (something in your application)
; aro = access request object (something requesting access)
;
; User records are added as follows:
;
; [uid]
; groups = group1, group2, group3
; allow = aco1, aco2, aco3
; deny = aco4, aco5, aco6
;
; Group records are added in a similar manner:
;
; [gid]
; allow = aco1, aco2, aco3
; deny = aco4, aco5, aco6
;
; The allow, deny, and groups sections are all optional.
; NOTE: groups names *cannot* ever be the same as usernames!
;
; ACL permissions are checked in the following order:
; 1. Check for user denies (and DENY if specified)
; 2. Check for user allows (and ALLOW if specified)
; 3. Gather user's groups
; 4. Check group denies (and DENY if specified)
; 5. Check group allows (and ALLOW if specified)
; 6. If no aro, aco, or group information is found, DENY
;
; ---------------------------------------------------------------------
;-------------------------------------
;Users
;-------------------------------------
[username-goes-here]
groups = group1, group2
deny = aco1, aco2
allow = aco3, aco4
;-------------------------------------
;Groups
;-------------------------------------
[groupname-goes-here]
deny = aco5, aco6
allow = aco7, aco8
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Config/acl.ini.php | PHP | gpl3 | 2,028 |
<?php
/**
* This is core configuration file.
*
* Use it to configure core behavior of Cake.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.Config
* @since CakePHP(tm) v 0.2.9
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* CakePHP Debug Level:
*
* Production Mode:
* 0: No error messages, errors, or warnings shown. Flash messages redirect.
*
* Development Mode:
* 1: Errors and warnings shown, model caches refreshed, flash messages halted.
* 2: As in 1, but also with full debug messages and SQL output.
*
* In production mode, flash messages redirect after a time interval.
* In development mode, you need to click the flash message to continue.
*/
Configure::write('debug', 2);
/**
* Configure the Error handler used to handle errors for your application. By default
* ErrorHandler::handleError() is used. It will display errors using Debugger, when debug > 0
* and log errors with CakeLog when debug = 0.
*
* Options:
*
* - `handler` - callback - The callback to handle errors. You can set this to any callback type,
* including anonymous functions.
* - `level` - int - The level of errors you are interested in capturing.
* - `trace` - boolean - Include stack traces for errors in log files.
*
* @see ErrorHandler for more information on error handling and configuration.
*/
Configure::write('Error', array(
'handler' => 'ErrorHandler::handleError',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true
));
/**
* Configure the Exception handler used for uncaught exceptions. By default,
* ErrorHandler::handleException() is used. It will display a HTML page for the exception, and
* while debug > 0, framework errors like Missing Controller will be displayed. When debug = 0,
* framework errors will be coerced into generic HTTP errors.
*
* Options:
*
* - `handler` - callback - The callback to handle exceptions. You can set this to any callback type,
* including anonymous functions.
* - `renderer` - string - The class responsible for rendering uncaught exceptions. If you choose a custom class you
* should place the file for that class in app/Error. This class needs to implement a render method.
* - `log` - boolean - Should Exceptions be logged?
*
* @see ErrorHandler for more information on exception handling and configuration.
*/
Configure::write('Exception', array(
'handler' => 'ErrorHandler::handleException',
'renderer' => 'ExceptionRenderer',
'log' => true
));
/**
* Application wide charset encoding
*/
Configure::write('App.encoding', 'UTF-8');
/**
* To configure CakePHP *not* to use mod_rewrite and to
* use CakePHP pretty URLs, remove these .htaccess
* files:
*
* /.htaccess
* /app/.htaccess
* /app/webroot/.htaccess
*
* And uncomment the App.baseUrl below:
*/
//Configure::write('App.baseUrl', env('SCRIPT_NAME'));
/**
* Uncomment the define below to use CakePHP prefix routes.
*
* The value of the define determines the names of the routes
* and their associated controller actions:
*
* Set to an array of prefixes you want to use in your application. Use for
* admin or other prefixed routes.
*
* Routing.prefixes = array('admin', 'manager');
*
* Enables:
* `admin_index()` and `/admin/controller/index`
* `manager_index()` and `/manager/controller/index`
*
*/
//Configure::write('Routing.prefixes', array('admin'));
/**
* Turn off all caching application-wide.
*
*/
//Configure::write('Cache.disable', true);
/**
* Enable cache checking.
*
* If set to true, for view caching you must still use the controller
* public $cacheAction inside your controllers to define caching settings.
* You can either set it controller-wide by setting public $cacheAction = true,
* or in each action using $this->cacheAction = true.
*
*/
//Configure::write('Cache.check', true);
/**
* Defines the default error type when using the log() function. Used for
* differentiating error logging and debugging. Currently PHP supports LOG_DEBUG.
*/
define('LOG_ERROR', 2);
/**
* Session configuration.
*
* Contains an array of settings to use for session configuration. The defaults key is
* used to define a default preset to use for sessions, any settings declared here will override
* the settings of the default config.
*
* ## Options
*
* - `Session.cookie` - The name of the cookie to use. Defaults to 'CAKEPHP'
* - `Session.timeout` - The number of minutes you want sessions to live for. This timeout is handled by CakePHP
* - `Session.cookieTimeout` - The number of minutes you want session cookies to live for.
* - `Session.checkAgent` - Do you want the user agent to be checked when starting sessions? You might want to set the
* value to false, when dealing with older versions of IE, Chrome Frame or certain web-browsing devices and AJAX
* - `Session.defaults` - The default configuration set to use as a basis for your session.
* There are four builtins: php, cake, cache, database.
* - `Session.handler` - Can be used to enable a custom session handler. Expects an array of of callables,
* that can be used with `session_save_handler`. Using this option will automatically add `session.save_handler`
* to the ini array.
* - `Session.autoRegenerate` - Enabling this setting, turns on automatic renewal of sessions, and
* sessionids that change frequently. See CakeSession::$requestCountdown.
* - `Session.ini` - An associative array of additional ini values to set.
*
* The built in defaults are:
*
* - 'php' - Uses settings defined in your php.ini.
* - 'cake' - Saves session files in CakePHP's /tmp directory.
* - 'database' - Uses CakePHP's database sessions.
* - 'cache' - Use the Cache class to save sessions.
*
* To define a custom session handler, save it at /app/Model/Datasource/Session/<name>.php.
* Make sure the class implements `CakeSessionHandlerInterface` and set Session.handler to <name>
*
* To use database sessions, run the app/Config/Schema/sessions.php schema using
* the cake shell command: cake schema create Sessions
*
*/
Configure::write('Session', array(
'defaults' => 'php'
));
/**
* The level of CakePHP security.
*/
Configure::write('Security.level', 'medium');
/**
* A random string used in security hashing methods.
*/
Configure::write('Security.salt', 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi');
/**
* A random numeric string (digits only) used to encrypt/decrypt strings.
*/
Configure::write('Security.cipherSeed', '76859309657453542496749683645');
/**
* Apply timestamps with the last modified time to static assets (js, css, images).
* Will append a querystring parameter containing the time the file was modified. This is
* useful for invalidating browser caches.
*
* Set to `true` to apply timestamps when debug > 0. Set to 'force' to always enable
* timestamping regardless of debug value.
*/
//Configure::write('Asset.timestamp', true);
/**
* Compress CSS output by removing comments, whitespace, repeating tags, etc.
* This requires a/var/cache directory to be writable by the web server for caching.
* and /vendors/csspp/csspp.php
*
* To use, prefix the CSS link URL with '/ccss/' instead of '/css/' or use HtmlHelper::css().
*/
//Configure::write('Asset.filter.css', 'css.php');
/**
* Plug in your own custom JavaScript compressor by dropping a script in your webroot to handle the
* output, and setting the config below to the name of the script.
*
* To use, prefix your JavaScript link URLs with '/cjs/' instead of '/js/' or use JavaScriptHelper::link().
*/
//Configure::write('Asset.filter.js', 'custom_javascript_output_filter.php');
/**
* The classname and database used in CakePHP's
* access control lists.
*/
Configure::write('Acl.classname', 'DbAcl');
Configure::write('Acl.database', 'default');
/**
* If you are on PHP 5.3 uncomment this line and correct your server timezone
* to fix the date & time related errors.
*/
//date_default_timezone_set('UTC');
/**
*
* Cache Engine Configuration
* Default settings provided below
*
* File storage engine.
*
* Cache::config('default', array(
* 'engine' => 'File', //[required]
* 'duration'=> 3600, //[optional]
* 'probability'=> 100, //[optional]
* 'path' => CACHE, //[optional] use system tmp directory - remember to use absolute path
* 'prefix' => 'cake_', //[optional] prefix every cache file with this string
* 'lock' => false, //[optional] use file locking
* 'serialize' => true, [optional]
* ));
*
* APC (http://pecl.php.net/package/APC)
*
* Cache::config('default', array(
* 'engine' => 'Apc', //[required]
* 'duration'=> 3600, //[optional]
* 'probability'=> 100, //[optional]
* 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
* ));
*
* Xcache (http://xcache.lighttpd.net/)
*
* Cache::config('default', array(
* 'engine' => 'Xcache', //[required]
* 'duration'=> 3600, //[optional]
* 'probability'=> 100, //[optional]
* 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
* 'user' => 'user', //user from xcache.admin.user settings
* 'password' => 'password', //plaintext password (xcache.admin.pass)
* ));
*
* Memcache (http://www.danga.com/memcached/)
*
* Cache::config('default', array(
* 'engine' => 'Memcache', //[required]
* 'duration'=> 3600, //[optional]
* 'probability'=> 100, //[optional]
* 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
* 'servers' => array(
* '127.0.0.1:11211' // localhost, default port 11211
* ), //[optional]
* 'persistent' => true, // [optional] set this to false for non-persistent connections
* 'compress' => false, // [optional] compress data in Memcache (slower, but uses less memory)
* ));
*
* Wincache (http://php.net/wincache)
*
* Cache::config('default', array(
* 'engine' => 'Wincache', //[required]
* 'duration'=> 3600, //[optional]
* 'probability'=> 100, //[optional]
* 'prefix' => Inflector::slug(APP_DIR) . '_', //[optional] prefix every cache file with this string
* ));
*/
/**
* Pick the caching engine to use. If APC is enabled use it.
* If running via cli - apc is disabled by default. ensure it's available and enabled in this case
*
*/
$engine = 'File';
if (extension_loaded('apc') && (php_sapi_name() !== 'cli' || ini_get('apc.enable_cli'))) {
$engine = 'Apc';
}
// In development mode, caches should expire quickly.
$duration = '+999 days';
if (Configure::read('debug') >= 1) {
$duration = '+10 seconds';
}
/**
* Configure the cache used for general framework caching. Path information,
* object listings, and translation cache files are stored with this configuration.
*/
Cache::config('_cake_core_', array(
'engine' => $engine,
'prefix' => 'cake_core_',
'path' => CACHE . 'persistent' . DS,
'serialize' => ($engine === 'File'),
'duration' => $duration
));
/**
* Configure the cache for model and datasource caches. This cache configuration
* is used to store schema descriptions, and table listings in connections.
*/
Cache::config('_cake_model_', array(
'engine' => $engine,
'prefix' => 'cake_model_',
'path' => CACHE . 'models' . DS,
'serialize' => ($engine === 'File'),
'duration' => $duration
));
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Config/core.php | PHP | gpl3 | 11,757 |
<?php
/**
* This file is loaded automatically by the app/webroot/index.php file after core.php
*
* This file should load/create any application wide configuration settings, such as
* Caching, Logging, loading additional configuration files.
*
* You should also use this file to include any files that provide global functions/constants
* that your application uses.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.Config
* @since CakePHP(tm) v 0.10.8.2117
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
// Setup a 'default' cache configuration for use in the application.
Cache::config('default', array('engine' => 'File'));
/**
* The settings below can be used to set additional paths to models, views and controllers.
*
* App::build(array(
* 'Plugin' => array('/full/path/to/plugins/', '/next/full/path/to/plugins/'),
* 'Model' => array('/full/path/to/models/', '/next/full/path/to/models/'),
* 'View' => array('/full/path/to/views/', '/next/full/path/to/views/'),
* 'Controller' => array('/full/path/to/controllers/', '/next/full/path/to/controllers/'),
* 'Model/Datasource' => array('/full/path/to/datasources/', '/next/full/path/to/datasources/'),
* 'Model/Behavior' => array('/full/path/to/behaviors/', '/next/full/path/to/behaviors/'),
* 'Controller/Component' => array('/full/path/to/components/', '/next/full/path/to/components/'),
* 'View/Helper' => array('/full/path/to/helpers/', '/next/full/path/to/helpers/'),
* 'Vendor' => array('/full/path/to/vendors/', '/next/full/path/to/vendors/'),
* 'Console/Command' => array('/full/path/to/shells/', '/next/full/path/to/shells/'),
* 'locales' => array('/full/path/to/locale/', '/next/full/path/to/locale/')
* ));
*
*/
/**
* Custom Inflector rules, can be set to correctly pluralize or singularize table, model, controller names or whatever other
* string is passed to the inflection functions
*
* Inflector::rules('singular', array('rules' => array(), 'irregular' => array(), 'uninflected' => array()));
* Inflector::rules('plural', array('rules' => array(), 'irregular' => array(), 'uninflected' => array()));
*
*/
/**
* Plugins need to be loaded manually, you can either load them one by one or all of them in a single call
* Uncomment one of the lines below, as you need. make sure you read the documentation on CakePlugin to use more
* advanced ways of loading plugins
*
* CakePlugin::loadAll(); // Loads all plugins at once
* CakePlugin::load('DebugKit'); //Loads a single plugin named DebugKit
*
*/
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Config/bootstrap.php | PHP | gpl3 | 3,000 |
<?php
/*DbAcl schema generated on: 2007-11-24 15:11:13 : 1195945453*/
/**
* This is Acl Schema file
*
* Use it to configure database for ACL
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.Config.Schema
* @since CakePHP(tm) v 0.2.9
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/*
*
* Using the Schema command line utility
* cake schema run create DbAcl
*
*/
class DbAclSchema extends CakeSchema {
public $name = 'DbAcl';
public function before($event = array()) {
return true;
}
public function after($event = array()) {
}
public $acos = array(
'id' => array('type'=>'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'),
'parent_id' => array('type'=>'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'model' => array('type'=>'string', 'null' => true),
'foreign_key' => array('type'=>'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'alias' => array('type'=>'string', 'null' => true),
'lft' => array('type'=>'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'rght' => array('type'=>'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1))
);
public $aros = array(
'id' => array('type'=>'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'),
'parent_id' => array('type'=>'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'model' => array('type'=>'string', 'null' => true),
'foreign_key' => array('type'=>'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'alias' => array('type'=>'string', 'null' => true),
'lft' => array('type'=>'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'rght' => array('type'=>'integer', 'null' => true, 'default' => NULL, 'length' => 10),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1))
);
public $aros_acos = array(
'id' => array('type'=>'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'),
'aro_id' => array('type'=>'integer', 'null' => false, 'length' => 10, 'key' => 'index'),
'aco_id' => array('type'=>'integer', 'null' => false, 'length' => 10),
'_create' => array('type'=>'string', 'null' => false, 'default' => '0', 'length' => 2),
'_read' => array('type'=>'string', 'null' => false, 'default' => '0', 'length' => 2),
'_update' => array('type'=>'string', 'null' => false, 'default' => '0', 'length' => 2),
'_delete' => array('type'=>'string', 'null' => false, 'default' => '0', 'length' => 2),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1), 'ARO_ACO_KEY' => array('column' => array('aro_id', 'aco_id'), 'unique' => 1))
);
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Config/Schema/db_acl.php | PHP | gpl3 | 3,210 |
<?php
/*i18n schema generated on: 2007-11-25 07:11:25 : 1196004805*/
/**
* This is i18n Schema file
*
* Use it to configure database for i18n
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.Config.Schema
* @since CakePHP(tm) v 0.2.9
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/*
*
* Using the Schema command line utility
* cake schema run create i18n
*
*/
class i18nSchema extends CakeSchema {
public $name = 'i18n';
public function before($event = array()) {
return true;
}
public function after($event = array()) {
}
public $i18n = array(
'id' => array('type'=>'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'),
'locale' => array('type'=>'string', 'null' => false, 'length' => 6, 'key' => 'index'),
'model' => array('type'=>'string', 'null' => false, 'key' => 'index'),
'foreign_key' => array('type'=>'integer', 'null' => false, 'length' => 10, 'key' => 'index'),
'field' => array('type'=>'string', 'null' => false, 'key' => 'index'),
'content' => array('type'=>'text', 'null' => true, 'default' => NULL),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1), 'locale' => array('column' => 'locale', 'unique' => 0), 'model' => array('column' => 'model', 'unique' => 0), 'row_id' => array('column' => 'foreign_key', 'unique' => 0), 'field' => array('column' => 'field', 'unique' => 0))
);
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Config/Schema/i18n.php | PHP | gpl3 | 1,843 |
<?php
/*Sessions schema generated on: 2007-11-25 07:11:54 : 1196004714*/
/**
* This is Sessions Schema file
*
* Use it to configure database for Sessions
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.Config.Schema
* @since CakePHP(tm) v 0.2.9
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/*
*
* Using the Schema command line utility
* cake schema run create Sessions
*
*/
class SessionsSchema extends CakeSchema {
public $name = 'Sessions';
public function before($event = array()) {
return true;
}
public function after($event = array()) {
}
public $cake_sessions = array(
'id' => array('type'=>'string', 'null' => false, 'key' => 'primary'),
'data' => array('type'=>'text', 'null' => true, 'default' => NULL),
'expires' => array('type'=>'integer', 'null' => true, 'default' => NULL),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1))
);
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Config/Schema/sessions.php | PHP | gpl3 | 1,354 |
<?php
/**
* Application model for Cake.
*
* This file is application-wide model file. You can put all
* application-wide model-related methods here.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package app.Model
* @since CakePHP(tm) v 0.2.9
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Model', 'Model');
/**
* Application model for Cake.
*
* Add your application-wide methods in the class below, your models
* will inherit them.
*
* @package app.Model
*/
class AppModel extends Model {
}
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/skel/Model/AppModel.php | PHP | gpl3 | 961 |
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Console.Templates.default.views
* @since CakePHP(tm) v 1.2.0.5234
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<div class="<?php echo $pluralVar;?> index">
<h2><?php echo "<?php echo __('{$pluralHumanName}');?>";?></h2>
<table cellpadding="0" cellspacing="0">
<tr>
<?php foreach ($fields as $field):?>
<th><?php echo "<?php echo \$this->Paginator->sort('{$field}');?>";?></th>
<?php endforeach;?>
<th class="actions"><?php echo "<?php echo __('Actions');?>";?></th>
</tr>
<?php
echo "<?php
\$i = 0;
foreach (\${$pluralVar} as \${$singularVar}): ?>\n";
echo "\t<tr>\n";
foreach ($fields as $field) {
$isKey = false;
if (!empty($associations['belongsTo'])) {
foreach ($associations['belongsTo'] as $alias => $details) {
if ($field === $details['foreignKey']) {
$isKey = true;
echo "\t\t<td>\n\t\t\t<?php echo \$this->Html->link(\${$singularVar}['{$alias}']['{$details['displayField']}'], array('controller' => '{$details['controller']}', 'action' => 'view', \${$singularVar}['{$alias}']['{$details['primaryKey']}'])); ?>\n\t\t</td>\n";
break;
}
}
}
if ($isKey !== true) {
echo "\t\t<td><?php echo h(\${$singularVar}['{$modelClass}']['{$field}']); ?> </td>\n";
}
}
echo "\t\t<td class=\"actions\">\n";
echo "\t\t\t<?php echo \$this->Html->link(__('View'), array('action' => 'view', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?>\n";
echo "\t\t\t<?php echo \$this->Html->link(__('Edit'), array('action' => 'edit', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?>\n";
echo "\t\t\t<?php echo \$this->Form->postLink(__('Delete'), array('action' => 'delete', \${$singularVar}['{$modelClass}']['{$primaryKey}']), null, __('Are you sure you want to delete # %s?', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?>\n";
echo "\t\t</td>\n";
echo "\t</tr>\n";
echo "<?php endforeach; ?>\n";
?>
</table>
<p>
<?php echo "<?php
echo \$this->Paginator->counter(array(
'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}')
));
?>";?>
</p>
<div class="paging">
<?php
echo "<?php\n";
echo "\t\techo \$this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));\n";
echo "\t\techo \$this->Paginator->numbers(array('separator' => ''));\n";
echo "\t\techo \$this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));\n";
echo "\t?>\n";
?>
</div>
</div>
<div class="actions">
<h3><?php echo "<?php echo __('Actions'); ?>"; ?></h3>
<ul>
<li><?php echo "<?php echo \$this->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><?php echo \$this->Html->link(__('List " . Inflector::humanize($details['controller']) . "'), array('controller' => '{$details['controller']}', 'action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$this->Html->link(__('New " . Inflector::humanize(Inflector::underscore($alias)) . "'), array('controller' => '{$details['controller']}', 'action' => 'add')); ?> </li>\n";
$done[] = $details['controller'];
}
}
}
?>
</ul>
</div>
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/default/views/index.ctp | PHP | gpl3 | 3,923 |
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Console.Templates.default.views
* @since CakePHP(tm) v 1.2.0.5234
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<div class="<?php echo $pluralVar;?> view">
<h2><?php echo "<?php echo __('{$singularHumanName}');?>";?></h2>
<dl>
<?php
foreach ($fields as $field) {
$isKey = false;
if (!empty($associations['belongsTo'])) {
foreach ($associations['belongsTo'] as $alias => $details) {
if ($field === $details['foreignKey']) {
$isKey = true;
echo "\t\t<dt><?php echo __('" . Inflector::humanize(Inflector::underscore($alias)) . "'); ?></dt>\n";
echo "\t\t<dd>\n\t\t\t<?php echo \$this->Html->link(\${$singularVar}['{$alias}']['{$details['displayField']}'], array('controller' => '{$details['controller']}', 'action' => 'view', \${$singularVar}['{$alias}']['{$details['primaryKey']}'])); ?>\n\t\t\t \n\t\t</dd>\n";
break;
}
}
}
if ($isKey !== true) {
echo "\t\t<dt><?php echo __('" . Inflector::humanize($field) . "'); ?></dt>\n";
echo "\t\t<dd>\n\t\t\t<?php echo h(\${$singularVar}['{$modelClass}']['{$field}']); ?>\n\t\t\t \n\t\t</dd>\n";
}
}
?>
</dl>
</div>
<div class="actions">
<h3><?php echo "<?php echo __('Actions'); ?>"; ?></h3>
<ul>
<?php
echo "\t\t<li><?php echo \$this->Html->link(__('Edit " . $singularHumanName ."'), array('action' => 'edit', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?> </li>\n";
echo "\t\t<li><?php echo \$this->Form->postLink(__('Delete " . $singularHumanName . "'), array('action' => 'delete', \${$singularVar}['{$modelClass}']['{$primaryKey}']), null, __('Are you sure you want to delete # %s?', \${$singularVar}['{$modelClass}']['{$primaryKey}'])); ?> </li>\n";
echo "\t\t<li><?php echo \$this->Html->link(__('List " . $pluralHumanName . "'), array('action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$this->Html->link(__('New " . $singularHumanName . "'), array('action' => 'add')); ?> </li>\n";
$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 \$this->Html->link(__('List " . Inflector::humanize($details['controller']) . "'), array('controller' => '{$details['controller']}', 'action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$this->Html->link(__('New " . Inflector::humanize(Inflector::underscore($alias)) . "'), array('controller' => '{$details['controller']}', 'action' => 'add')); ?> </li>\n";
$done[] = $details['controller'];
}
}
}
?>
</ul>
</div>
<?php
if (!empty($associations['hasOne'])) :
foreach ($associations['hasOne'] as $alias => $details): ?>
<div class="related">
<h3><?php echo "<?php echo __('Related " . Inflector::humanize($details['controller']) . "');?>";?></h3>
<?php echo "<?php if (!empty(\${$singularVar}['{$alias}'])):?>\n";?>
<dl>
<?php
foreach ($details['fields'] as $field) {
echo "\t\t<dt><?php echo __('" . Inflector::humanize($field) . "');?></dt>\n";
echo "\t\t<dd>\n\t<?php echo \${$singularVar}['{$alias}']['{$field}'];?>\n </dd>\n";
}
?>
</dl>
<?php echo "<?php endif; ?>\n";?>
<div class="actions">
<ul>
<li><?php echo "<?php echo \$this->Html->link(__('Edit " . Inflector::humanize(Inflector::underscore($alias)) . "'), array('controller' => '{$details['controller']}', 'action' => 'edit', \${$singularVar}['{$alias}']['{$details['primaryKey']}'])); ?></li>\n";?>
</ul>
</div>
</div>
<?php
endforeach;
endif;
if (empty($associations['hasMany'])) {
$associations['hasMany'] = array();
}
if (empty($associations['hasAndBelongsToMany'])) {
$associations['hasAndBelongsToMany'] = array();
}
$relations = array_merge($associations['hasMany'], $associations['hasAndBelongsToMany']);
$i = 0;
foreach ($relations as $alias => $details):
$otherSingularVar = Inflector::variable($alias);
$otherPluralHumanName = Inflector::humanize($details['controller']);
?>
<div class="related">
<h3><?php echo "<?php echo __('Related " . $otherPluralHumanName . "');?>";?></h3>
<?php echo "<?php if (!empty(\${$singularVar}['{$alias}'])):?>\n";?>
<table cellpadding = "0" cellspacing = "0">
<tr>
<?php
foreach ($details['fields'] as $field) {
echo "\t\t<th><?php echo __('" . Inflector::humanize($field) . "'); ?></th>\n";
}
?>
<th class="actions"><?php echo "<?php echo __('Actions');?>";?></th>
</tr>
<?php
echo "\t<?php
\$i = 0;
foreach (\${$singularVar}['{$alias}'] as \${$otherSingularVar}): ?>\n";
echo "\t\t<tr>\n";
foreach ($details['fields'] as $field) {
echo "\t\t\t<td><?php echo \${$otherSingularVar}['{$field}'];?></td>\n";
}
echo "\t\t\t<td class=\"actions\">\n";
echo "\t\t\t\t<?php echo \$this->Html->link(__('View'), array('controller' => '{$details['controller']}', 'action' => 'view', \${$otherSingularVar}['{$details['primaryKey']}'])); ?>\n";
echo "\t\t\t\t<?php echo \$this->Html->link(__('Edit'), array('controller' => '{$details['controller']}', 'action' => 'edit', \${$otherSingularVar}['{$details['primaryKey']}'])); ?>\n";
echo "\t\t\t\t<?php echo \$this->Form->postLink(__('Delete'), array('controller' => '{$details['controller']}', 'action' => 'delete', \${$otherSingularVar}['{$details['primaryKey']}']), null, __('Are you sure you want to delete # %s?', \${$otherSingularVar}['{$details['primaryKey']}'])); ?>\n";
echo "\t\t\t</td>\n";
echo "\t\t</tr>\n";
echo "\t<?php endforeach; ?>\n";
?>
</table>
<?php echo "<?php endif; ?>\n\n";?>
<div class="actions">
<ul>
<li><?php echo "<?php echo \$this->Html->link(__('New " . Inflector::humanize(Inflector::underscore($alias)) . "'), array('controller' => '{$details['controller']}', 'action' => 'add'));?>";?> </li>
</ul>
</div>
</div>
<?php endforeach;?>
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/default/views/view.ctp | PHP | gpl3 | 6,297 |
<?php
/**
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Console.Templates.default.views
* @since CakePHP(tm) v 1.2.0.5234
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
?>
<div class="<?php echo $pluralVar;?> form">
<?php echo "<?php echo \$this->Form->create('{$modelClass}');?>\n";?>
<fieldset>
<legend><?php printf("<?php echo __('%s %s'); ?>", Inflector::humanize($action), $singularHumanName); ?></legend>
<?php
echo "\t<?php\n";
foreach ($fields as $field) {
if (strpos($action, 'add') !== false && $field == $primaryKey) {
continue;
} elseif (!in_array($field, array('created', 'modified', 'updated'))) {
echo "\t\techo \$this->Form->input('{$field}');\n";
}
}
if (!empty($associations['hasAndBelongsToMany'])) {
foreach ($associations['hasAndBelongsToMany'] as $assocName => $assocData) {
echo "\t\techo \$this->Form->input('{$assocName}');\n";
}
}
echo "\t?>\n";
?>
</fieldset>
<?php
echo "<?php echo \$this->Form->end(__('Submit'));?>\n";
?>
</div>
<div class="actions">
<h3><?php echo "<?php echo __('Actions'); ?>"; ?></h3>
<ul>
<?php if (strpos($action, 'add') === false): ?>
<li><?php echo "<?php echo \$this->Form->postLink(__('Delete'), array('action' => 'delete', \$this->Form->value('{$modelClass}.{$primaryKey}')), null, __('Are you sure you want to delete # %s?', \$this->Form->value('{$modelClass}.{$primaryKey}'))); ?>";?></li>
<?php endif;?>
<li><?php echo "<?php echo \$this->Html->link(__('List " . $pluralHumanName . "'), array('action' => 'index'));?>";?></li>
<?php
$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 \$this->Html->link(__('List " . Inflector::humanize($details['controller']) . "'), array('controller' => '{$details['controller']}', 'action' => 'index')); ?> </li>\n";
echo "\t\t<li><?php echo \$this->Html->link(__('New " . Inflector::humanize(Inflector::underscore($alias)) . "'), array('controller' => '{$details['controller']}', 'action' => 'add')); ?> </li>\n";
$done[] = $details['controller'];
}
}
}
?>
</ul>
</div>
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/default/views/form.ctp | PHP | gpl3 | 2,672 |
<?php
$output = "
<iframe src=\"http://cakephp.org/bake-banner\" width=\"830\" height=\"160\" style=\"overflow:hidden; border:none;\">
<p>For updates and important announcements, visit http://cakefest.org</p>
</iframe>\n";
$output .= "<h2>Sweet, \"" . Inflector::humanize($app) . "\" got Baked by CakePHP!</h2>\n";
$output .="
<?php
App::uses('Debugger', 'Utility');
if (Configure::read('debug') > 0):
Debugger::checkSecurityKeys();
endif;
?>
<p>
<?php
if (version_compare(PHP_VERSION, '5.2.6', '>=')):
echo '<span class=\"notice success\">';
echo __d('cake_dev', 'Your version of PHP is 5.2.6 or higher.');
echo '</span>';
else:
echo '<span class=\"notice\">';
echo __d('cake_dev', 'Your version of PHP is too low. You need PHP 5.2.6 or higher to use CakePHP.');
echo '</span>';
endif;
?>
</p>
<p>
<?php
if (is_writable(TMP)):
echo '<span class=\"notice success\">';
echo __d('cake_dev', 'Your tmp directory is writable.');
echo '</span>';
else:
echo '<span class=\"notice\">';
echo __d('cake_dev', 'Your tmp directory is NOT writable.');
echo '</span>';
endif;
?>
</p>
<p>
<?php
\$settings = Cache::settings();
if (!empty(\$settings)):
echo '<span class=\"notice success\">';
echo __d('cake_dev', 'The %s is being used for caching. To change the config edit APP/Config/core.php ', '<em>'. \$settings['engine'] . 'Engine</em>');
echo '</span>';
else:
echo '<span class=\"notice\">';
echo __d('cake_dev', 'Your cache is NOT working. Please check the settings in APP/Config/core.php');
echo '</span>';
endif;
?>
</p>
<p>
<?php
\$filePresent = null;
if (file_exists(APP . 'Config' . DS . 'database.php')):
echo '<span class=\"notice success\">';
echo __d('cake_dev', 'Your database configuration file is present.');
\$filePresent = true;
echo '</span>';
else:
echo '<span class=\"notice\">';
echo __d('cake_dev', 'Your database configuration file is NOT present.');
echo '<br/>';
echo __d('cake_dev', 'Rename APP/Config/database.php.default to APP/Config/database.php');
echo '</span>';
endif;
?>
</p>
<?php
if (isset(\$filePresent)):
App::uses('ConnectionManager', 'Model');
try {
\$connected = ConnectionManager::getDataSource('default');
} catch (Exception \$e) {
\$connected = false;
}
?>
<p>
<?php
if (\$connected && \$connected->isConnected()):
echo '<span class=\"notice success\">';
echo __d('cake_dev', 'Cake is able to connect to the database.');
echo '</span>';
else:
echo '<span class=\"notice\">';
echo __d('cake_dev', 'Cake is NOT able to connect to the database.');
echo '</span>';
endif;
?>
</p>
<?php endif;?>
<?php
App::uses('Validation', 'Utility');
if (!Validation::alphaNumeric('cakephp')) {
echo '<p><span class=\"notice\">';
__d('cake_dev', 'PCRE has not been compiled with Unicode support.');
echo '<br/>';
__d('cake_dev', 'Recompile PCRE with Unicode support by adding <code>--enable-unicode-properties</code> when configuring');
echo '</span></p>';
}
?>\n";
$output .= "<h3><?php echo __d('cake_dev', 'Editing this Page'); ?></h3>\n";
$output .= "<p>\n";
$output .= "<?php\n";
$output .= "\techo __d('cake_dev', 'To change the content of this page, edit: %s\n";
$output .= "\t\tTo change its layout, edit: %s\n";
$output .= "\t\tYou can also add some CSS styles for your pages at: %s',\n";
$output .= "\t\tAPP . 'View' . DS . 'Pages' . DS . 'home.ctp.<br />', APP . 'View' . DS . 'Layouts' . DS . 'default.ctp.<br />', APP . 'webroot' . DS . 'css');\n";
$output .= "?>\n";
$output .= "</p>\n";
?>
| 0001-bee | trunk/cakephp2/lib/Cake/Console/Templates/default/views/home.ctp | PHP | gpl3 | 3,554 |