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 echo '<?xml version="1.0" encoding="' . Configure::read('App.encoding') . '"?>'; ?> <?php echo $content_for_layout; ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Layouts/xml/default.ctp
PHP
gpl3
125
<?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.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/View/Layouts/flash.ctp
PHP
gpl3
1,264
<?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.View.Layouts * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ $cakeDescription = __d('cake_dev', 'CakePHP: the rapid development php framework'); ?> <!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 $cakeDescription ?>: <?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($cakeDescription, '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'=> $cakeDescription, '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/View/Layouts/default.ctp
PHP
gpl3
1,690
<?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.View.Layouts.Emails.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/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 Cake.View.Layouts.Emails.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/View/Layouts/Emails/text/default.ctp
PHP
gpl3
723
<?php if (!isset($channel)) { $channel = array(); } if (!isset($channel['title'])) { $channel['title'] = $title_for_layout; } echo $this->Rss->document( $this->Rss->channel( array(), $channel, $content_for_layout ) ); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Layouts/rss/default.ctp
PHP
gpl3
228
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ $pluginDot = empty($plugin) ? null : $plugin . '.'; ?> <h2><?php echo __d('cake_dev', 'Missing Helper'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', '%s could not be found.', '<em>' . $pluginDot . $class . '</em>'); ?> </p> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Create the class %s below in file: %s', '<em>' . $class . '</em>', (empty($plugin) ? APP_DIR . DS : CakePlugin::path($plugin)) . 'View' . DS . 'Helper' . DS . $class . '.php'); ?> </p> <pre> &lt;?php class <?php echo $class; ?> extends AppHelper { } </pre> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'missing_helper.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/missing_helper.ctp
PHP
gpl3
1,560
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h2><?php echo $name; ?></h2> <p class="error"> <strong><?php echo __d('cake', 'Error'); ?>: </strong> <?php echo __d('cake', 'An Internal Error Has Occurred.'); ?> </p> <?php if (Configure::read('debug') > 0 ): echo $this->element('exception_stack_trace'); endif; ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/error500.ctp
PHP
gpl3
877
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h2><?php echo __d('cake_dev', 'Database Error'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo h($error->getMessage()); ?> </p> <?php if (!empty($error->queryString)) : ?> <p class="notice"> <strong><?php echo __d('cake_dev', 'SQL Query'); ?>: </strong> <?php echo $error->queryString; ?> </p> <?php endif; ?> <?php if (!empty($error->params)) : ?> <strong><?php echo __d('cake_dev', 'SQL Query Params'); ?>: </strong> <?php echo Debugger::dump($error->params); ?> <?php endif; ?> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'pdo_error.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/pdo_error.ctp
PHP
gpl3
1,444
<?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.View.Errors * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h2><?php echo __d('cake_dev', 'Missing Datasource Configuration'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'The datasource configuration %1$s was not found in database.php.', '<em>' . $config . '</em>'); ?> </p> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'missing_datasource_config.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/missing_datasource_config.ctp
PHP
gpl3
1,194
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h2><?php echo __d('cake_dev', 'Missing Database Table'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Database table %1$s for model %2$s was not found.', '<em>' . $table . '</em>', '<em>' . $class . '</em>'); ?> </p> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'missing_table.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/missing_table.ctp
PHP
gpl3
1,192
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h2><?php echo __d('cake_dev', 'Missing Layout'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'The layout file %s can not be found or does not exist.', '<em>' . $file . '</em>'); ?> </p> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Confirm you have created the file: %s', '<em>' . $file . '</em>'); ?> </p> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'missing_layout.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/missing_layout.ctp
PHP
gpl3
1,343
<?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.View.Errors * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h2><?php echo __d('cake_dev', 'Missing Plugin'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'The application is trying to load a file from the %s plugin', '<em>' . $plugin . '</em>'); ?> </p> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Make sure your plugin %s is in the ' . APP_DIR . DS . 'Plugin directory and was loaded', $plugin); ?> </p> <pre> &lt;?php CakePlugin::load('<?php echo $plugin?>'); </pre> <p class="notice"> <strong><?php echo __d('cake_dev', 'Loading all plugins'); ?>: </strong> <?php echo __d('cake_dev', 'If you wish to load all plugins at once, use the following line in your ' . APP_DIR . DS . 'Config' . DS . 'bootstrap.php file'); ?> </p> <pre> CakePlugin::loadAll(); </pre> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'missing_plugin.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/missing_plugin.ctp
PHP
gpl3
1,735
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ $pluginDot = empty($plugin) ? null : $plugin . '.'; ?> <h2><?php echo __d('cake_dev', 'Missing Controller'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', '%s could not be found.', '<em>' . $pluginDot . $class . '</em>'); ?> </p> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Create the class %s below in file: %s', '<em>' . $class . '</em>', (empty($plugin) ? APP_DIR . DS : CakePlugin::path($plugin)) . 'Controller' . DS . $class . '.php'); ?> </p> <pre> &lt;?php class <?php echo $class; ?> extends AppController { } </pre> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'missing_controller.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/missing_controller.ctp
PHP
gpl3
1,562
<?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.View.Errors * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ $pluginDot = empty($plugin) ? null : $plugin . '.'; ?> <h2><?php echo __d('cake_dev', 'Missing Datasource'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Datasource class %s could not be found.', '<em>' . $pluginDot . $class . '</em>'); ?> </p> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'missing_datasource.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/missing_datasource.ctp
PHP
gpl3
1,212
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h2><?php echo __d('cake_dev', 'Missing Database Connection'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', '%s requires a database connection', $class); ?> </p> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Confirm you have created the file : %s.', APP_DIR . DS . 'Config' . DS . 'database.php'); ?> </p> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s.', APP_DIR . DS . 'View' . DS . 'Errors' . DS . basename(__FILE__)); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/missing_connection.ctp
PHP
gpl3
1,339
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h2><?php echo __d('cake_dev', 'Private Method in %s', $controller); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', '%s%s cannot be accessed directly.', '<em>' . $controller . '::</em>', '<em>' . $action . '()</em>'); ?> </p> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'private_action.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/private_action.ctp
PHP
gpl3
1,197
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h2><?php echo $name; ?></h2> <p class="error"> <strong><?php echo __d('cake', 'Error'); ?>: </strong> <?php printf( __d('cake', 'The requested address %s was not found on this server.'), "<strong>'{$url}'</strong>" ); ?> </p> <?php if (Configure::read('debug') > 0 ): echo $this->element('exception_stack_trace'); endif; ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/error400.ctp
PHP
gpl3
939
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h2><?php echo __d('cake_dev', 'Missing View'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'The view for %1$s%2$s was not found.', '<em>' . Inflector::camelize($this->request->controller) . 'Controller::</em>', '<em>' . $this->request->action . '()</em>'); ?> </p> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Confirm you have created the file: %s', $file); ?> </p> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'missing_view.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/missing_view.ctp
PHP
gpl3
1,401
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h2><?php echo __d('cake_dev', 'Scaffold Error'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Method _scaffoldError in was not found in the controller'); ?> </p> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'scaffold_error.ctp'); ?> </p> <pre> &lt;?php function _scaffoldError() {<br /> } </pre> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/scaffold_error.ctp
PHP
gpl3
1,197
<?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.View.Errors * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ $pluginDot = empty($plugin) ? null : $plugin . '.'; ?> <h2><?php echo __d('cake_dev', 'Missing Behavior'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', '%s could not be found.', '<em>' . $pluginDot . $class . '</em>'); ?> </p> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Create the class %s below in file: %s', '<em>' . $class . '</em>', (empty($plugin) ? APP_DIR . DS : CakePlugin::path($plugin)) . 'Model' . DS . 'Behavior' . DS . $class . '.php'); ?> </p> <pre> &lt;?php class <?php echo $class; ?> extends ModelBehavior { } </pre> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'missing_behavior.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/missing_behavior.ctp
PHP
gpl3
1,563
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ $pluginDot = empty($plugin) ? null : $plugin . '.'; ?> <h2><?php echo __d('cake_dev', 'Missing Component'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', '%s could not be found.', '<em>' . $pluginDot . $class . '</em>'); ?> </p> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Create the class %s below in file: %s', '<em>' . $class . '</em>', (empty($plugin) ? APP_DIR . DS : CakePlugin::path($plugin)) . 'Controller' . DS . 'Component' . DS . $class . '.php'); ?> </p> <pre> &lt;?php class <?php echo $class; ?> extends Component { } </pre> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'missing_component.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/missing_component.ctp
PHP
gpl3
1,575
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h2><?php echo __d('cake_dev', 'Missing Database Connection'); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Scaffold requires a database connection'); ?> </p> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Confirm you have created the file: %s', APP_DIR . DS . 'Config' . DS . 'database.php'); ?> </p> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'missing_database.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/missing_database.ctp
PHP
gpl3
1,338
<?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.View.Errors * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h2><?php echo __d('cake_dev', 'Missing Method in %s', $controller); ?></h2> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'The action %1$s is not defined in controller %2$s', '<em>' . $action . '</em>', '<em>' . $controller . '</em>'); ?> </p> <p class="error"> <strong><?php echo __d('cake_dev', 'Error'); ?>: </strong> <?php echo __d('cake_dev', 'Create %1$s%2$s in file: %3$s.', '<em>' . $controller . '::</em>', '<em>' . $action . '()</em>', APP_DIR . DS . 'Controller' . DS . $controller . '.php'); ?> </p> <pre> &lt;?php class <?php echo $controller;?> extends AppController { <strong> public function <?php echo $action;?>() { } </strong> } </pre> <p class="notice"> <strong><?php echo __d('cake_dev', 'Notice'); ?>: </strong> <?php echo __d('cake_dev', 'If you want to customize this error message, create %s', APP_DIR . DS . 'View' . DS . 'Errors' . DS . 'missing_action.ctp'); ?> </p> <?php echo $this->element('exception_stack_trace'); ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Errors/missing_action.ctp
PHP
gpl3
1,625
<?php /** * Methods for displaying presentation data in the view. * * 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.View * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Included libraries. */ App::uses('HelperCollection', 'View'); App::uses('AppHelper', 'View/Helper'); App::uses('Router', 'Routing'); /** * View, the V in the MVC triad. View interacts with Helpers and view variables passed * in from the controller to render the results of the controller action. Often this is HTML, * but can also take the form of JSON, XML, PDF's or streaming files. * * CakePHP uses a two-step-view pattern. This means that the view content is rendered first, * and then inserted into the selected layout. A special `$content_for_layout` variable is available * in the layout, and it contains the rendered view. This also means you can pass data from the view to the * layout using `$this->set()` * * @package Cake.View * @property CacheHelper $Cache * @property FormHelper $Form * @property HtmlHelper $Html * @property JsHelper $Js * @property NumberHelper $Number * @property PaginatorHelper $Paginator * @property RssHelper $Rss * @property SessionHelper $Session * @property TextHelper $Text * @property TimeHelper $Time */ class View extends Object { /** * Helpers collection * * @var HelperCollection */ public $Helpers; /** * Name of the plugin. * * @link http://manual.cakephp.org/chapter/plugins * @var string */ public $plugin = null; /** * Name of the controller. * * @var string Name of controller */ public $name = null; /** * Current passed params * * @var mixed */ public $passedArgs = array(); /** * An array of names of built-in helpers to include. * * @var mixed A single name as a string or a list of names as an array. */ public $helpers = array('Html'); /** * Path to View. * * @var string Path to View */ public $viewPath = null; /** * Variables for the view * * @var array */ public $viewVars = array(); /** * Name of view to use with this View. * * @var string */ public $view = null; /** * Name of layout to use with this View. * * @var string */ public $layout = 'default'; /** * Path to Layout. * * @var string Path to Layout */ public $layoutPath = null; /** * Turns on or off Cake's conventional mode of applying layout files. On by default. * Setting to off means that layouts will not be automatically applied to rendered views. * * @var boolean */ public $autoLayout = true; /** * File extension. Defaults to Cake's template ".ctp". * * @var string */ public $ext = '.ctp'; /** * Sub-directory for this view file. This is often used for extension based routing. * for example with an `xml` extension, $subDir would be `xml/` * * @var string */ public $subDir = null; /** * Theme name. If you are using themes, you should remember to use ThemeView as well. * * @var string */ public $theme = null; /** * Used to define methods a controller that will be cached. * * @see Controller::$cacheAction * @var mixed */ public $cacheAction = false; /** * holds current errors for the model validation * * @var array */ public $validationErrors = array(); /** * True when the view has been rendered. * * @var boolean */ public $hasRendered = false; /** * List of generated DOM UUIDs * * @var array */ public $uuids = array(); /** * Holds View output. * * @var string */ public $output = false; /** * An instance of a CakeRequest object that contains information about the current request. * This object contains all the information about a request and several methods for reading * additional information about the request. * * @var CakeRequest */ public $request; /** * The Cache configuration View will use to store cached elements. Changing this will change * the default configuration elements are stored under. You can also choose a cache config * per element. * * @var string * @see View::element() */ public $elementCache = 'default'; /** * List of variables to collect from the associated controller * * @var array */ protected $_passedVars = array( 'viewVars', 'autoLayout', 'ext', 'helpers', 'view', 'layout', 'name', 'layoutPath', 'viewPath', 'request', 'plugin', 'passedArgs', 'cacheAction' ); /** * Scripts (and/or other <head /> tags) for the layout * * @var array */ protected $_scripts = array(); /** * Holds an array of paths. * * @var array */ protected $_paths = array(); /** * boolean to indicate that helpers have been loaded. * * @var boolean */ protected $_helpersLoaded = false; /** * Constructor * * @param Controller $controller A controller object to pull View::__passedArgs from. */ public function __construct($controller) { if (is_object($controller)) { $count = count($this->_passedVars); for ($j = 0; $j < $count; $j++) { $var = $this->_passedVars[$j]; $this->{$var} = $controller->{$var}; } } $this->Helpers = new HelperCollection($this); parent::__construct(); } /** * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string. * * This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send * data to be used in the element. Elements can be cached improving performance by using the `cache` option. * * @param string $name Name of template file in the/app/View/Elements/ folder * @param array $data Array of data to be made available to the rendered view (i.e. the Element) * @param array $options Array of options. Possible keys are: * - `cache` - Can either be `true`, to enable caching using the config in View::$elementCache. Or an array * If an array, the following keys can be used: * - `config` - Used to store the cached element in a custom cache configuration. * - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_` * - `plugin` - Load an element from a specific plugin. * - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element. * Defaults to false. * @return string Rendered Element */ public function element($name, $data = array(), $options = array()) { $file = $plugin = $key = null; $callbacks = false; if (isset($options['plugin'])) { $plugin = Inflector::camelize($options['plugin']); } if (isset($this->plugin) && !$plugin) { $plugin = $this->plugin; } if (isset($options['callbacks'])) { $callbacks = $options['callbacks']; } if (isset($options['cache'])) { $underscored = null; if ($plugin) { $underscored = Inflector::underscore($plugin); } $keys = array_merge(array($underscored, $name), array_keys($options), array_keys($data)); $caching = array( 'config' => $this->elementCache, 'key' => implode('_', $keys) ); if (is_array($options['cache'])) { $defaults = array( 'config' => $this->elementCache, 'key' => $caching['key'] ); $caching = array_merge($defaults, $options['cache']); } $key = 'element_' . $caching['key']; $contents = Cache::read($key, $caching['config']); if ($contents !== false) { return $contents; } } $file = $this->_getElementFilename($name, $plugin); if ($file) { if (!$this->_helpersLoaded) { $this->loadHelpers(); } if ($callbacks) { $this->Helpers->trigger('beforeRender', array($file)); } $element = $this->_render($file, array_merge($this->viewVars, $data)); if ($callbacks) { $this->Helpers->trigger('afterRender', array($file, $element)); } if (isset($options['cache'])) { Cache::write($key, $element, $caching['config']); } return $element; } $file = 'Elements' . DS . $name . $this->ext; if (Configure::read('debug') > 0) { return "Element Not Found: " . $file; } } /** * Renders view for given view file and layout. * * Render triggers helper callbacks, which are fired before and after the view are rendered, * as well as before and after the layout. The helper callbacks are called * * - `beforeRender` * - `afterRender` * - `beforeLayout` * - `afterLayout` * * If View::$autoRender is false and no `$layout` is provided, the view will be returned bare. * * @param string $view Name of view file to use * @param string $layout Layout to use. * @return string Rendered Element * @throws CakeException if there is an error in the view. */ public function render($view = null, $layout = null) { if ($this->hasRendered) { return true; } if (!$this->_helpersLoaded) { $this->loadHelpers(); } $this->output = null; if ($view !== false && $viewFileName = $this->_getViewFileName($view)) { $this->Helpers->trigger('beforeRender', array($viewFileName)); $this->output = $this->_render($viewFileName); $this->Helpers->trigger('afterRender', array($viewFileName)); } if ($layout === null) { $layout = $this->layout; } if ($this->output === false) { throw new CakeException(__d('cake_dev', "Error in view %s, got no content.", $viewFileName)); } if ($layout && $this->autoLayout) { $this->output = $this->renderLayout($this->output, $layout); } $this->hasRendered = true; return $this->output; } /** * Renders a layout. Returns output from _render(). Returns false on error. * Several variables are created for use in layout. * * - `title_for_layout` - A backwards compatible place holder, you should set this value if you want more control. * - `content_for_layout` - contains rendered view file * - `scripts_for_layout` - contains scripts added to header * * @param string $content_for_layout Content to render in a view, wrapped by the surrounding layout. * @param string $layout Layout name * @return mixed Rendered output, or false on error * @throws CakeException if there is an error in the view. */ public function renderLayout($content_for_layout, $layout = null) { $layoutFileName = $this->_getLayoutFileName($layout); if (empty($layoutFileName)) { return $this->output; } if (!$this->_helpersLoaded) { $this->loadHelpers(); } $this->Helpers->trigger('beforeLayout', array($layoutFileName)); $this->viewVars = array_merge($this->viewVars, array( 'content_for_layout' => $content_for_layout, 'scripts_for_layout' => implode("\n\t", $this->_scripts), )); if (!isset($this->viewVars['title_for_layout'])) { $this->viewVars['title_for_layout'] = Inflector::humanize($this->viewPath); } $this->output = $this->_render($layoutFileName); if ($this->output === false) { throw new CakeException(__d('cake_dev', "Error in layout %s, got no content.", $layoutFileName)); } $this->Helpers->trigger('afterLayout', array($layoutFileName)); return $this->output; } /** * Render cached view. Works in concert with CacheHelper and Dispatcher to * render cached view files. * * @param string $filename the cache file to include * @param string $timeStart the page render start time * @return boolean Success of rendering the cached file. */ public function renderCache($filename, $timeStart) { ob_start(); include ($filename); if (Configure::read('debug') > 0 && $this->layout != 'xml') { echo "<!-- Cached Render Time: " . round(microtime(true) - $timeStart, 4) . "s -->"; } $out = ob_get_clean(); if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) { if (time() >= $match['1']) { @unlink($filename); unset ($out); return false; } else { if ($this->layout === 'xml') { header('Content-type: text/xml'); } $commentLength = strlen('<!--cachetime:' . $match['1'] . '-->'); echo substr($out, $commentLength); return true; } } } /** * Returns a list of variables available in the current View context * * @return array Array of the set view variable names. */ public function getVars() { return array_keys($this->viewVars); } /** * Returns the contents of the given View variable(s) * * @param string $var The view var you want the contents of. * @return mixed The content of the named var if its set, otherwise null. */ public function getVar($var) { if (!isset($this->viewVars[$var])) { return null; } else { return $this->viewVars[$var]; } } /** * Adds a script block or other element to be inserted in $scripts_for_layout in * the `<head />` of a document layout * * @param string $name Either the key name for the script, or the script content. Name can be used to * update/replace a script element. * @param string $content The content of the script being added, optional. * @return void */ public function addScript($name, $content = null) { if (empty($content)) { if (!in_array($name, array_values($this->_scripts))) { $this->_scripts[] = $name; } } else { $this->_scripts[$name] = $content; } } /** * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL. * * @param string $object Type of object, i.e. 'form' or 'link' * @param string $url The object's target URL * @return string */ public function uuid($object, $url) { $c = 1; $url = Router::url($url); $hash = $object . substr(md5($object . $url), 0, 10); while (in_array($hash, $this->uuids)) { $hash = $object . substr(md5($object . $url . $c), 0, 10); $c++; } $this->uuids[] = $hash; return $hash; } /** * Allows a template or element to set a variable that will be available in * a layout or other element. Analagous to Controller::set(). * * @param mixed $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) { $data = 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->viewVars = $data + $this->viewVars; } /** * Magic accessor for helpers. Provides access to attributes that were deprecated. * * @param string $name Name of the attribute to get. * @return mixed */ public function __get($name) { if (isset($this->Helpers->{$name})) { return $this->Helpers->{$name}; } switch ($name) { case 'base': case 'here': case 'webroot': case 'data': return $this->request->{$name}; case 'action': return isset($this->request->params['action']) ? $this->request->params['action'] : ''; case 'params': return $this->request; } return null; } /** * Interact with the HelperCollection to load all the helpers. * * @return void */ public function loadHelpers() { $helpers = HelperCollection::normalizeObjectArray($this->helpers); foreach ($helpers as $name => $properties) { list($plugin, $class) = pluginSplit($properties['class']); $this->{$class} = $this->Helpers->load($properties['class'], $properties['settings']); } $this->_helpersLoaded = true; } /** * Renders and returns output for given view filename with its * array of data. * * @param string $___viewFn Filename of the view * @param array $___dataForView Data to include in rendered view. If empty the current View::$viewVars will be used. * @return string Rendered output */ protected function _render($___viewFn, $___dataForView = array()) { if (empty($___dataForView)) { $___dataForView = $this->viewVars; } extract($___dataForView, EXTR_SKIP); ob_start(); include $___viewFn; return ob_get_clean(); } /** * Loads a helper. Delegates to the `HelperCollection::load()` to load the helper * * @param string $helperName Name of the helper to load. * @param array $settings Settings for the helper * @return Helper a constructed helper object. * @see HelperCollection::load() */ public function loadHelper($helperName, $settings = array()) { return $this->Helpers->load($helperName, $settings); } /** * Returns filename of given action's template file (.ctp) as a string. * CamelCased action names will be under_scored! This means that you can have * LongActionNames that refer to long_action_names.ctp views. * * @param string $name Controller action to find template filename for * @return string Template filename * @throws MissingViewException when a view file could not be found. */ protected function _getViewFileName($name = null) { $subDir = null; if (!is_null($this->subDir)) { $subDir = $this->subDir . DS; } if ($name === null) { $name = $this->view; } $name = str_replace('/', DS, $name); if (strpos($name, DS) === false && $name[0] !== '.') { $name = $this->viewPath . DS . $subDir . Inflector::underscore($name); } elseif (strpos($name, DS) !== false) { if ($name[0] === DS || $name[1] === ':') { if (is_file($name)) { return $name; } $name = trim($name, DS); } else if ($name[0] === '.') { $name = substr($name, 3); } else { $name = $this->viewPath . DS . $subDir . $name; } } $paths = $this->_paths($this->plugin); $exts = $this->_getExtensions(); foreach ($exts as $ext) { foreach ($paths as $path) { if (file_exists($path . $name . $ext)) { return $path . $name . $ext; } } } $defaultPath = $paths[0]; if ($this->plugin) { $pluginPaths = App::path('plugins'); foreach ($paths as $path) { if (strpos($path, $pluginPaths[0]) === 0) { $defaultPath = $path; break; } } } throw new MissingViewException(array('file' => $defaultPath . $name . $this->ext)); } /** * Returns layout filename for this template as a string. * * @param string $name The name of the layout to find. * @return string Filename for layout file (.ctp). * @throws MissingLayoutException when a layout cannot be located */ protected function _getLayoutFileName($name = null) { if ($name === null) { $name = $this->layout; } $subDir = null; if (!is_null($this->layoutPath)) { $subDir = $this->layoutPath . DS; } $paths = $this->_paths($this->plugin); $file = 'Layouts' . DS . $subDir . $name; $exts = $this->_getExtensions(); foreach ($exts as $ext) { foreach ($paths as $path) { if (file_exists($path . $file . $ext)) { return $path . $file . $ext; } } } throw new MissingLayoutException(array('file' => $paths[0] . $file . $this->ext)); } /** * Get the extensions that view files can use. * * @return array Array of extensions view files use. */ protected function _getExtensions() { $exts = array($this->ext); if ($this->ext !== '.ctp') { array_push($exts, '.ctp'); } return $exts; } /** * Finds an element filename, returns false on failure. * * @param string $name The name of the element to find. * @param string $plugin The plugin name the element is in. * @return mixed Either a string to the element filename or false when one can't be found. */ protected function _getElementFileName($name, $plugin = null) { $paths = $this->_paths($plugin); $exts = $this->_getExtensions(); foreach ($exts as $ext) { foreach ($paths as $path) { if (file_exists($path . 'Elements' . DS . $name . $ext)) { return $path . 'Elements' . DS . $name . $ext; } } } return false; } /** * Return all possible paths to find view files in order * * @param string $plugin Optional plugin name to scan for view files. * @param boolean $cached Set to true to force a refresh of view paths. * @return array paths */ protected function _paths($plugin = null, $cached = true) { if ($plugin === null && $cached === true && !empty($this->_paths)) { return $this->_paths; } $paths = array(); $viewPaths = App::path('View'); $corePaths = array_flip(App::core('View')); if (!empty($plugin)) { $count = count($viewPaths); for ($i = 0; $i < $count; $i++) { if (!isset($corePaths[$viewPaths[$i]])) { $paths[] = $viewPaths[$i] . 'Plugin' . DS . $plugin . DS; } } $paths = array_merge($paths, App::path('View', $plugin)); } $this->_paths = array_unique(array_merge($paths, $viewPaths, array_keys($corePaths))); return $this->_paths; } }
0001-bee
trunk/cakephp2/lib/Cake/View/View.php
PHP
gpl3
20,804
<?php /** * Prints a stack trace for an exception * * 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.View.Elements * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h4>Stack Trace</h4> <pre> <?php echo $error->getTraceAsString(); ?> </pre>
0001-bee
trunk/cakephp2/lib/Cake/View/Elements/exception_stack_trace.ctp
PHP
gpl3
717
<?php /** * SQL Dump element. Dumps out SQL log information * * 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.View.Elements * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ if (!class_exists('ConnectionManager') || Configure::read('debug') < 2) { return false; } $noLogs = !isset($logs); if ($noLogs): $sources = ConnectionManager::sourceList(); $logs = array(); foreach ($sources as $source): $db = ConnectionManager::getDataSource($source); if (!method_exists($db, 'getLog')): continue; endif; $logs[$source] = $db->getLog(); endforeach; endif; if ($noLogs || isset($_forced_from_dbo_)): foreach ($logs as $source => $logInfo): $text = $logInfo['count'] > 1 ? 'queries' : 'query'; printf( '<table class="cake-sql-log" id="cakeSqlLog_%s" summary="Cake SQL Log" cellspacing="0" border = "0">', preg_replace('/[^A-Za-z0-9_]/', '_', uniqid(time(), true)) ); printf('<caption>(%s) %s %s took %s ms</caption>', $source, $logInfo['count'], $text, $logInfo['time']); ?> <thead> <tr><th>Nr</th><th>Query</th><th>Error</th><th>Affected</th><th>Num. rows</th><th>Took (ms)</th></tr> </thead> <tbody> <?php foreach ($logInfo['log'] as $k => $i) : $i += array('error' => ''); echo "<tr><td>" . ($k + 1) . "</td><td>" . h($i['query']) . "</td><td>{$i['error']}</td><td style = \"text-align: right\">{$i['affected']}</td><td style = \"text-align: right\">{$i['numRows']}</td><td style = \"text-align: right\">{$i['took']}</td></tr>\n"; endforeach; ?> </tbody></table> <?php endforeach; else: echo '<p>Encountered unexpected $logs cannot generate SQL log</p>'; endif; ?>
0001-bee
trunk/cakephp2/lib/Cake/View/Elements/sql_dump.ctp
PHP
gpl3
2,090
<?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 Cake.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 Cake.View.Helper */ class AppHelper extends Helper { }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/AppHelper.php
PHP
gpl3
1,039
<?php /** * Session Helper provides access to the Session in the Views. * * 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.View.Helper * @since CakePHP(tm) v 1.1.7.3328 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AppHelper', 'View/Helper'); App::uses('CakeSession', 'Model/Datasource'); /** * Session Helper. * * Session reading from the view. * * @package Cake.View.Helper * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html */ class SessionHelper extends AppHelper { /** * Used to read a session values set in a controller for a key or return values for all keys. * * In your view: `$this->Session->read('Controller.sessKey');` * Calling the method without a param will return all session vars * * @param string $name the name of the session key you want to read * @return mixed values from the session vars * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html#displaying-notifcations-or-flash-messages */ public function read($name = null) { return CakeSession::read($name); } /** * Used to check is a session key has been set * * In your view: `$this->Session->check('Controller.sessKey');` * * @param string $name * @return boolean * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html#displaying-notifcations-or-flash-messages */ public function check($name) { return CakeSession::check($name); } /** * Returns last error encountered in a session * * In your view: `$this->Session->error();` * * @return string last error * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html#displaying-notifcations-or-flash-messages */ public function error() { return CakeSession::error(); } /** * Used to render the message set in Controller::Session::setFlash() * * In your view: $this->Session->flash('somekey'); * Will default to flash if no param is passed * * You can pass additional information into the flash message generation. This allows you * to consolidate all the parameters for a given type of flash message into the view. * * {{{ * echo $this->Session->flash('flash', array('params' => array('class' => 'new-flash'))); * }}} * * The above would generate a flash message with a custom class name. Using $attrs['params'] you * can pass additional data into the element rendering that will be made available as local variables * when the element is rendered: * * {{{ * echo $this->Session->flash('flash', array('params' => array('name' => $user['User']['name']))); * }}} * * This would pass the current user's name into the flash message, so you could create peronsonalized * messages without the controller needing access to that data. * * Lastly you can choose the element that is rendered when creating the flash message. Using * custom elements allows you to fully customize how flash messages are generated. * * {{{ * echo $this->Session->flash('flash', array('element' => 'my_custom_element')); * }}} * * @param string $key The [Message.]key you are rendering in the view. * @param array $attrs Additional attributes to use for the creation of this flash message. * Supports the 'params', and 'element' keys that are used in the helper. * @return string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html#displaying-notifcations-or-flash-messages * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html#SessionHelper::flash */ public function flash($key = 'flash', $attrs = array()) { $out = false; if (CakeSession::check('Message.' . $key)) { $flash = CakeSession::read('Message.' . $key); $message = $flash['message']; unset($flash['message']); if (!empty($attrs)) { $flash = array_merge($flash, $attrs); } if ($flash['element'] == 'default') { $class = 'message'; if (!empty($flash['params']['class'])) { $class = $flash['params']['class']; } $out = '<div id="' . $key . 'Message" class="' . $class . '">' . $message . '</div>'; } elseif ($flash['element'] == '' || $flash['element'] == null) { $out = $message; } else { $tmpVars = $flash['params']; $tmpVars['message'] = $message; $out = $this->_View->element($flash['element'], $tmpVars); } CakeSession::delete('Message.' . $key); } return $out; } /** * Used to check is a session is valid in a view * * @return boolean */ public function valid() { return CakeSession::valid(); } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/SessionHelper.php
PHP
gpl3
4,930
<?php /** * Text Helper * * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links... * * 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.View.Helper * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Included libraries. * */ App::uses('AppHelper', 'View/Helper'); App::uses('HtmlHelper', 'Helper'); App::uses('Multibyte', 'I18n'); /** * Text helper library. * * Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links... * * @package Cake.View.Helper * @property HtmlHelper $Html * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html */ class TextHelper extends AppHelper { /** * helpers * * @var array */ public $helpers = array('Html'); /** * Highlights a given phrase in a text. You can specify any expression in highlighter that * may include the \1 expression to include the $phrase found. * * ### Options: * * - `format` The piece of html with that the phrase will be highlighted * - `html` If true, will ignore any HTML tags, ensuring that only the correct text is highlighted * * @param string $text Text to search the phrase in * @param string $phrase The phrase that will be searched * @param array $options An array of html attributes and options. * @return string The highlighted text * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::highlight */ public function highlight($text, $phrase, $options = array()) { if (empty($phrase)) { return $text; } $default = array( 'format' => '<span class="highlight">\1</span>', 'html' => false ); $options = array_merge($default, $options); extract($options); if (is_array($phrase)) { $replace = array(); $with = array(); foreach ($phrase as $key => $segment) { $segment = "($segment)"; if ($html) { $segment = "(?![^<]+>)$segment(?![^<]+>)"; } $with[] = (is_array($format)) ? $format[$key] : $format; $replace[] = "|$segment|iu"; } return preg_replace($replace, $with, $text); } else { $phrase = "($phrase)"; if ($html) { $phrase = "(?![^<]+>)$phrase(?![^<]+>)"; } return preg_replace("|$phrase|iu", $format, $text); } } /** * Strips given text of all links (<a href=....) * * @param string $text Text * @return string The text without links * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::stripLinks */ public function stripLinks($text) { return preg_replace('|<a\s+[^>]+>|im', '', preg_replace('|<\/a>|im', '', $text)); } /** * Adds links (<a href=....) to a given text, by finding text that begins with * strings like http:// and ftp://. * * @param string $text Text to add links to * @param array $htmlOptions Array of HTML options. * @return string The text with links * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLinkUrls */ public function autoLinkUrls($text, $htmlOptions = array()) { $this->_linkOptions = $htmlOptions; $text = preg_replace_callback( '#(?<!href="|src="|">)((?:https?|ftp|nntp)://[^\s<>()]+)#i', array(&$this, '_linkBareUrl'), $text ); return preg_replace_callback( '#(?<!href="|">)(?<!http://|https://|ftp://|nntp://)(www\.[^\n\%\ <]+[^<\n\%\,\.\ <])(?<!\))#i', array(&$this, '_linkUrls'), $text ); } /** * Links urls that include http:// * * @param array $matches * @return string * @see TextHelper::autoLinkUrls() */ protected function _linkBareUrl($matches) { return $this->Html->link($matches[0], $matches[0], $this->_linkOptions); } /** * Links urls missing http:// * * @param array $matches * @return string * @see TextHelper::autoLinkUrls() */ protected function _linkUrls($matches) { return $this->Html->link($matches[0], 'http://' . $matches[0], $this->_linkOptions); } /** * Links email addresses * * @param array $matches * @return string * @see TextHelper::autoLinkUrls() */ protected function _linkEmails($matches) { return $this->Html->link($matches[0], 'mailto:' . $matches[0], $this->_linkOptions); } /** * Adds email links (<a href="mailto:....) to a given text. * * @param string $text Text * @param array $options Array of HTML options. * @return string The text with links * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLinkEmails */ public function autoLinkEmails($text, $options = array()) { $this->_linkOptions = $options; $atom = '[a-z0-9!#$%&\'*+\/=?^_`{|}~-]'; return preg_replace_callback( '/(' . $atom . '+(?:\.' . $atom . '+)*@[a-z0-9-]+(?:\.[a-z0-9-]+)+)/i', array(&$this, '_linkEmails'), $text ); } /** * Convert all links and email adresses to HTML links. * * @param string $text Text * @param array $options Array of HTML options. * @return string The text with links * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::autoLink */ public function autoLink($text, $options = array()) { return $this->autoLinkEmails($this->autoLinkUrls($text, $options), $options); } /** * Truncates text. * * Cuts a string to the length of $length and replaces the last characters * with the ending if the text is longer than length. * * ### Options: * * - `ending` Will be used as Ending and appended to the trimmed string * - `exact` If false, $text will not be cut mid-word * - `html` If true, HTML tags would be handled correctly * * @param string $text String to truncate. * @param integer $length Length of returned string, including ellipsis. * @param array $options An array of html attributes and options. * @return string Trimmed string. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::truncate */ public function truncate($text, $length = 100, $options = array()) { $default = array( 'ending' => '...', 'exact' => true, 'html' => false ); $options = array_merge($default, $options); extract($options); if (!function_exists('mb_strlen')) { class_exists('Multibyte'); } if ($html) { if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) { return $text; } $totalLength = mb_strlen(strip_tags($ending)); $openTags = array(); $truncate = ''; preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER); foreach ($tags as $tag) { if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) { if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) { array_unshift($openTags, $tag[2]); } else if (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) { $pos = array_search($closeTag[1], $openTags); if ($pos !== false) { array_splice($openTags, $pos, 1); } } } $truncate .= $tag[1]; $contentLength = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3])); if ($contentLength + $totalLength > $length) { $left = $length - $totalLength; $entitiesLength = 0; if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE)) { foreach ($entities[0] as $entity) { if ($entity[1] + 1 - $entitiesLength <= $left) { $left--; $entitiesLength += mb_strlen($entity[0]); } else { break; } } } $truncate .= mb_substr($tag[3], 0 , $left + $entitiesLength); break; } else { $truncate .= $tag[3]; $totalLength += $contentLength; } if ($totalLength >= $length) { break; } } } else { if (mb_strlen($text) <= $length) { return $text; } else { $truncate = mb_substr($text, 0, $length - mb_strlen($ending)); } } if (!$exact) { $spacepos = mb_strrpos($truncate, ' '); if (isset($spacepos)) { if ($html) { $bits = mb_substr($truncate, $spacepos); preg_match_all('/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER); if (!empty($droppedTags)) { foreach ($droppedTags as $closingTag) { if (!in_array($closingTag[1], $openTags)) { array_unshift($openTags, $closingTag[1]); } } } } $truncate = mb_substr($truncate, 0, $spacepos); } } $truncate .= $ending; if ($html) { foreach ($openTags as $tag) { $truncate .= '</'.$tag.'>'; } } return $truncate; } /** * Extracts an excerpt from the text surrounding the phrase with a number of characters on each side * determined by radius. * * @param string $text String to search the phrase in * @param string $phrase Phrase that will be searched for * @param integer $radius The amount of characters that will be returned on each side of the founded phrase * @param string $ending Ending that will be appended * @return string Modified string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::excerpt */ public function excerpt($text, $phrase, $radius = 100, $ending = '...') { if (empty($text) or empty($phrase)) { return $this->truncate($text, $radius * 2, array('ending' => $ending)); } $phraseLen = mb_strlen($phrase); if ($radius < $phraseLen) { $radius = $phraseLen; } $pos = mb_strpos(mb_strtolower($text), mb_strtolower($phrase)); $startPos = 0; if ($pos > $radius) { $startPos = $pos - $radius; } $textLen = mb_strlen($text); $endPos = $pos + $phraseLen + $radius; if ($endPos >= $textLen) { $endPos = $textLen; } $excerpt = mb_substr($text, $startPos, $endPos - $startPos); if ($startPos != 0) { $excerpt = substr_replace($excerpt, $ending, 0, $phraseLen); } if ($endPos != $textLen) { $excerpt = substr_replace($excerpt, $ending, -$phraseLen); } return $excerpt; } /** * Creates a comma separated list where the last two items are joined with 'and', forming natural English * * @param array $list The list to be joined * @param string $and The word used to join the last and second last items together with. Defaults to 'and' * @param string $separator The separator used to join all othe other items together. Defaults to ', ' * @return string The glued together string. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/text.html#TextHelper::toList */ public function toList($list, $and = 'and', $separator = ', ') { if (count($list) > 1) { return implode($separator, array_slice($list, null, -1)) . ' ' . $and . ' ' . array_pop($list); } else { return array_pop($list); } } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/TextHelper.php
PHP
gpl3
11,061
<?php /** * Pagination Helper class file. * * Generates pagination links * * 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.View.Helper * @since CakePHP(tm) v 1.2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AppHelper', 'View/Helper'); /** * Pagination Helper class for easy generation of pagination links. * * PaginationHelper encloses all methods needed when working with pagination. * * @package Cake.View.Helper * @property HtmlHelper $Html * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html */ class PaginatorHelper extends AppHelper { /** * Helper dependencies * * @var array */ public $helpers = array('Html'); /** * The class used for 'Ajax' pagination links. Defaults to JsHelper. You should make sure * that JsHelper is defined as a helper before PaginatorHelper, if you want to customize the JsHelper. * * @var string */ protected $_ajaxHelperClass = 'Js'; /** * Holds the default options for pagination links * * The values that may be specified are: * * - `format` Format of the counter. Supported formats are 'range' and 'pages' * and custom (default). In the default mode the supplied string is parsed and constants are replaced * by their actual values. * placeholders: %page%, %pages%, %current%, %count%, %start%, %end% . * - `separator` The separator of the actual page and number of pages (default: ' of '). * - `url` Url of the action. See Router::url() * - `url['sort']` the key that the recordset is sorted. * - `url['direction']` Direction of the sorting (default: 'asc'). * - `url['page']` Page number to use in links. * - `model` The name of the model. * - `escape` Defines if the title field for the link should be escaped (default: true). * - `update` DOM id of the element updated with the results of the AJAX call. * If this key isn't specified Paginator will use plain HTML links. * - `paging['paramType']` The type of parameters to use when creating links. Valid options are * 'querystring' and 'named'. See PaginatorComponent::$settings for more information. * - `convertKeys` - A list of keys in url arrays that should be converted to querysting params * if paramType == 'querystring'. * * @var array */ public $options = array( 'convertKeys' => array('page', 'limit', 'sort', 'direction') ); /** * Constructor for the helper. Sets up the helper that is used for creating 'AJAX' links. * * Use `public $helpers = array('Paginator' => array('ajax' => 'CustomHelper'));` to set a custom Helper * or choose a non JsHelper Helper. If you want to use a specific library with JsHelper declare JsHelper and its * adapter before including PaginatorHelper in your helpers array. * * The chosen custom helper must implement a `link()` method. * * @param View $View the view object the helper is attached to. * @param array $settings Array of settings. * @throws CakeException When the AjaxProvider helper does not implement a link method. */ public function __construct(View $View, $settings = array()) { $ajaxProvider = isset($settings['ajax']) ? $settings['ajax'] : 'Js'; $this->helpers[] = $ajaxProvider; $this->_ajaxHelperClass = $ajaxProvider; App::uses($ajaxProvider . 'Helper', 'View/Helper'); $classname = $ajaxProvider . 'Helper'; if (!method_exists($classname, 'link')) { throw new CakeException(sprintf( __d('cake_dev', '%s does not implement a link() method, it is incompatible with PaginatorHelper'), $classname )); } parent::__construct($View, $settings); } /** * Before render callback. Overridden to merge passed args with url options. * * @param string $viewFile * @return void */ public function beforeRender($viewFile) { $this->options['url'] = array_merge($this->request->params['pass'], $this->request->params['named']); parent::beforeRender($viewFile); } /** * Gets the current paging parameters from the resultset for the given model * * @param string $model Optional model name. Uses the default if none is specified. * @return array The array of paging parameters for the paginated resultset. */ public function params($model = null) { if (empty($model)) { $model = $this->defaultModel(); } if (!isset($this->request->params['paging']) || empty($this->request->params['paging'][$model])) { return null; } return $this->request->params['paging'][$model]; } /** * Sets default options for all pagination links * * @param mixed $options Default options for pagination links. If a string is supplied - it * is used as the DOM id element to update. See PaginatorHelper::$options for list of keys. * @return void */ public function options($options = array()) { if (is_string($options)) { $options = array('update' => $options); } if (!empty($options['paging'])) { if (!isset($this->request->params['paging'])) { $this->request->params['paging'] = array(); } $this->request->params['paging'] = array_merge($this->request->params['paging'], $options['paging']); unset($options['paging']); } $model = $this->defaultModel(); if (!empty($options[$model])) { if (!isset($this->request->params['paging'][$model])) { $this->request->params['paging'][$model] = array(); } $this->request->params['paging'][$model] = array_merge( $this->request->params['paging'][$model], $options[$model] ); unset($options[$model]); } if (!empty($options['convertKeys'])) { $options['convertKeys'] = array_merge($this->options['convertKeys'], $options['convertKeys']); } $this->options = array_filter(array_merge($this->options, $options)); } /** * Gets the current page of the recordset for the given model * * @param string $model Optional model name. Uses the default if none is specified. * @return string The current page number of the recordset. */ public function current($model = null) { $params = $this->params($model); if (isset($params['page'])) { return $params['page']; } return 1; } /** * Gets the current key by which the recordset is sorted * * @param string $model Optional model name. Uses the default if none is specified. * @param mixed $options Options for pagination links. See #options for list of keys. * @return string The name of the key by which the recordset is being sorted, or * null if the results are not currently sorted. */ public function sortKey($model = null, $options = array()) { if (empty($options)) { $params = $this->params($model); $options = $params['options']; } if (isset($options['sort']) && !empty($options['sort'])) { return $options['sort']; } elseif (isset($options['order']) && is_array($options['order'])) { return key($options['order']); } elseif (isset($options['order']) && is_string($options['order'])) { return $options['order']; } return null; } /** * Gets the current direction the recordset is sorted * * @param string $model Optional model name. Uses the default if none is specified. * @param mixed $options Options for pagination links. See #options for list of keys. * @return string The direction by which the recordset is being sorted, or * null if the results are not currently sorted. */ public function sortDir($model = null, $options = array()) { $dir = null; if (empty($options)) { $params = $this->params($model); $options = $params['options']; } if (isset($options['direction'])) { $dir = strtolower($options['direction']); } elseif (isset($options['order']) && is_array($options['order'])) { $dir = strtolower(current($options['order'])); } if ($dir == 'desc') { return 'desc'; } return 'asc'; } /** * Generates a "previous" link for a set of paged records * * ### Options: * * - `tag` The tag wrapping tag you want to use, defaults to 'span' * - `escape` Whether you want the contents html entity encoded, defaults to true * - `model` The model to use, defaults to PaginatorHelper::defaultModel() * * @param string $title Title for the link. Defaults to '<< Previous'. * @param array $options Options for pagination link. See #options for list of keys. * @param string $disabledTitle Title when the link is disabled. * @param array $disabledOptions Options for the disabled pagination link. See #options for list of keys. * @return string A "previous" link or $disabledTitle text if the link is disabled. */ public function prev($title = '<< Previous', $options = array(), $disabledTitle = null, $disabledOptions = array()) { $defaults = array( 'rel' => 'prev' ); $options = array_merge($defaults, (array)$options); return $this->_pagingLink('Prev', $title, $options, $disabledTitle, $disabledOptions); } /** * Generates a "next" link for a set of paged records * * ### Options: * * - `tag` The tag wrapping tag you want to use, defaults to 'span' * - `escape` Whether you want the contents html entity encoded, defaults to true * - `model` The model to use, defaults to PaginatorHelper::defaultModel() * * @param string $title Title for the link. Defaults to 'Next >>'. * @param mixed $options Options for pagination link. See above for list of keys. * @param string $disabledTitle Title when the link is disabled. * @param mixed $disabledOptions Options for the disabled pagination link. See above for list of keys. * @return string A "next" link or or $disabledTitle text if the link is disabled. */ public function next($title = 'Next >>', $options = array(), $disabledTitle = null, $disabledOptions = array()) { $defaults = array( 'rel' => 'next' ); $options = array_merge($defaults, (array)$options); return $this->_pagingLink('Next', $title, $options, $disabledTitle, $disabledOptions); } /** * Generates a sorting link. Sets named parameters for the sort and direction. Handles * direction switching automatically. * * ### Options: * * - `escape` Whether you want the contents html entity encoded, defaults to true * - `model` The model to use, defaults to PaginatorHelper::defaultModel() * - `direction` The default directon to use when this link isn't active. * * @param string $key The name of the key that the recordset should be sorted. * @param string $title Title for the link. If $title is null $key will be used * for the title and will be generated by inflection. * @param array $options Options for sorting link. See above for list of keys. * @return string A link sorting default by 'asc'. If the resultset is sorted 'asc' by the specified * key the returned link will sort by 'desc'. */ public function sort($key, $title = null, $options = array()) { $options = array_merge(array('url' => array(), 'model' => null), $options); $url = $options['url']; unset($options['url']); if (empty($title)) { $title = $key; $title = __(Inflector::humanize(preg_replace('/_id$/', '', $title))); } $dir = isset($options['direction']) ? $options['direction'] : 'asc'; unset($options['direction']); $sortKey = $this->sortKey($options['model']); $defaultModel = $this->defaultModel(); $isSorted = ( $sortKey === $key || $sortKey === $defaultModel . '.' . $key || $key === $defaultModel . '.' . $sortKey ); if ($isSorted) { $dir = $this->sortDir($options['model']) === 'asc' ? 'desc' : 'asc'; $class = $dir === 'asc' ? 'desc' : 'asc'; if (!empty($options['class'])) { $options['class'] .= ' ' . $class; } else { $options['class'] = $class; } } if (is_array($title) && array_key_exists($dir, $title)) { $title = $title[$dir]; } $url = array_merge(array('sort' => $key, 'direction' => $dir), $url, array('order' => null)); return $this->link($title, $url, $options); } /** * Generates a plain or Ajax link with pagination parameters * * ### Options * * - `update` The Id of the DOM element you wish to update. Creates Ajax enabled links * with the AjaxHelper. * - `escape` Whether you want the contents html entity encoded, defaults to true * - `model` The model to use, defaults to PaginatorHelper::defaultModel() * * @param string $title Title for the link. * @param mixed $url Url for the action. See Router::url() * @param array $options Options for the link. See #options for list of keys. * @return string A link with pagination parameters. */ public function link($title, $url = array(), $options = array()) { $options = array_merge(array('model' => null, 'escape' => true), $options); $model = $options['model']; unset($options['model']); if (!empty($this->options)) { $options = array_merge($this->options, $options); } if (isset($options['url'])) { $url = array_merge((array)$options['url'], (array)$url); unset($options['url']); } unset($options['convertKeys']); $url = $this->url($url, true, $model); $obj = isset($options['update']) ? $this->_ajaxHelperClass : 'Html'; return $this->{$obj}->link($title, $url, $options); } /** * Merges passed URL options with current pagination state to generate a pagination URL. * * @param array $options Pagination/URL options array * @param boolean $asArray Return the url as an array, or a URI string * @param string $model Which model to paginate on * @return mixed By default, returns a full pagination URL string for use in non-standard contexts (i.e. JavaScript) */ public function url($options = array(), $asArray = false, $model = null) { $paging = $this->params($model); $url = array_merge(array_filter($paging['options']), $options); if (isset($url['order'])) { $sort = $direction = null; if (is_array($url['order'])) { list($sort, $direction) = array($this->sortKey($model, $url), current($url['order'])); } unset($url['order']); $url = array_merge($url, compact('sort', 'direction')); } $url = $this->_convertUrlKeys($url, $paging['paramType']); if ($asArray) { return $url; } return parent::url($url); } /** * Converts the keys being used into the format set by options.paramType * * @param array $url Array of url params to convert * @param string $type * @return array converted url params. */ protected function _convertUrlKeys($url, $type) { if ($type == 'named') { return $url; } if (!isset($url['?'])) { $url['?'] = array(); } foreach ($this->options['convertKeys'] as $key) { if (isset($url[$key])) { $url['?'][$key] = $url[$key]; unset($url[$key]); } } return $url; } /** * Protected method for generating prev/next links * * @param string $which * @param string $title * @param array $options * @param string $disabledTitle * @param array $disabledOptions * @return string */ protected function _pagingLink($which, $title = null, $options = array(), $disabledTitle = null, $disabledOptions = array()) { $check = 'has' . $which; $_defaults = array( 'url' => array(), 'step' => 1, 'escape' => true, 'model' => null, 'tag' => 'span', 'class' => strtolower($which) ); $options = array_merge($_defaults, (array)$options); $paging = $this->params($options['model']); if (empty($disabledOptions)) { $disabledOptions = $options; } if (!$this->{$check}($options['model']) && (!empty($disabledTitle) || !empty($disabledOptions))) { if (!empty($disabledTitle) && $disabledTitle !== true) { $title = $disabledTitle; } $options = array_merge($_defaults, (array)$disabledOptions); } elseif (!$this->{$check}($options['model'])) { return null; } foreach (array_keys($_defaults) as $key) { ${$key} = $options[$key]; unset($options[$key]); } $url = array_merge(array('page' => $paging['page'] + ($which == 'Prev' ? $step * -1 : $step)), $url); if ($this->{$check}($model)) { return $this->Html->tag($tag, $this->link($title, $url, array_merge($options, compact('escape'))), compact('class')); } else { unset($options['rel']); return $this->Html->tag($tag, $title, array_merge($options, compact('escape', 'class'))); } } /** * Returns true if the given result set is not at the first page * * @param string $model Optional model name. Uses the default if none is specified. * @return boolean True if the result set is not at the first page. */ public function hasPrev($model = null) { return $this->_hasPage($model, 'prev'); } /** * Returns true if the given result set is not at the last page * * @param string $model Optional model name. Uses the default if none is specified. * @return boolean True if the result set is not at the last page. */ public function hasNext($model = null) { return $this->_hasPage($model, 'next'); } /** * Returns true if the given result set has the page number given by $page * * @param string $model Optional model name. Uses the default if none is specified. * @param integer $page The page number - if not set defaults to 1. * @return boolean True if the given result set has the specified page number. */ public function hasPage($model = null, $page = 1) { if (is_numeric($model)) { $page = $model; $model = null; } $paging = $this->params($model); return $page <= $paging['pageCount']; } /** * Does $model have $page in its range? * * @param string $model Model name to get parameters for. * @param integer $page Page number you are checking. * @return boolean Whether model has $page */ protected function _hasPage($model, $page) { $params = $this->params($model); if (!empty($params)) { if ($params["{$page}Page"] == true) { return true; } } return false; } /** * Gets the default model of the paged sets * * @return string Model name or null if the pagination isn't initialized. */ public function defaultModel() { if ($this->_defaultModel != null) { return $this->_defaultModel; } if (empty($this->request->params['paging'])) { return null; } list($this->_defaultModel) = array_keys($this->request->params['paging']); return $this->_defaultModel; } /** * Returns a counter string for the paged result set * * ### Options * * - `model` The model to use, defaults to PaginatorHelper::defaultModel(); * - `format` The format string you want to use, defaults to 'pages' Which generates output like '1 of 5' * set to 'range' to generate output like '1 - 3 of 13'. Can also be set to a custom string, containing * the following placeholders `{:page}`, `{:pages}`, `{:current}`, `{:count}`, `{:model}`, `{:start}`, `{:end}` and any * custom content you would like. * - `separator` The separator string to use, default to ' of ' * * The `%page%` style placeholders also work, but are deprecated and will be removed in a future version. * @param mixed $options Options for the counter string. See #options for list of keys. * @return string Counter string. * @deprecated The %page% style placeholders are deprecated. */ public function counter($options = array()) { if (is_string($options)) { $options = array('format' => $options); } $options = array_merge( array( 'model' => $this->defaultModel(), 'format' => 'pages', 'separator' => __(' of ') ), $options); $paging = $this->params($options['model']); if ($paging['pageCount'] == 0) { $paging['pageCount'] = 1; } $start = 0; if ($paging['count'] >= 1) { $start = (($paging['page'] - 1) * $paging['limit']) + 1; } $end = $start + $paging['limit'] - 1; if ($paging['count'] < $end) { $end = $paging['count']; } switch ($options['format']) { case 'range': if (!is_array($options['separator'])) { $options['separator'] = array(' - ', $options['separator']); } $out = $start . $options['separator'][0] . $end . $options['separator'][1]; $out .= $paging['count']; break; case 'pages': $out = $paging['page'] . $options['separator'] . $paging['pageCount']; break; default: $map = array( '%page%' => $paging['page'], '%pages%' => $paging['pageCount'], '%current%' => $paging['current'], '%count%' => $paging['count'], '%start%' => $start, '%end%' => $end, '%model%' => strtolower(Inflector::humanize(Inflector::tableize($options['model']))) ); $out = str_replace(array_keys($map), array_values($map), $options['format']); $newKeys = array( '{:page}', '{:pages}', '{:current}', '{:count}', '{:start}', '{:end}', '{:model}' ); $out = str_replace($newKeys, array_values($map), $out); break; } return $out; } /** * Returns a set of numbers for the paged result set * uses a modulus to decide how many numbers to show on each side of the current page (default: 8). * * `$this->Paginator->numbers(array('first' => 2, 'last' => 2));` * * Using the first and last options you can create links to the beginning and end of the page set. * * ### Options * * - `before` Content to be inserted before the numbers * - `after` Content to be inserted after the numbers * - `model` Model to create numbers for, defaults to PaginatorHelper::defaultModel() * - `modulus` how many numbers to include on either side of the current page, defaults to 8. * - `separator` Separator content defaults to ' | ' * - `tag` The tag to wrap links in, defaults to 'span' * - `first` Whether you want first links generated, set to an integer to define the number of 'first' * links to generate. * - `last` Whether you want last links generated, set to an integer to define the number of 'last' * links to generate. * - `ellipsis` Ellipsis content, defaults to '...' * * @param mixed $options Options for the numbers, (before, after, model, modulus, separator) * @return string numbers string. */ public function numbers($options = array()) { if ($options === true) { $options = array( 'before' => ' | ', 'after' => ' | ', 'first' => 'first', 'last' => 'last' ); } $defaults = array( 'tag' => 'span', 'before' => null, 'after' => null, 'model' => $this->defaultModel(), 'class' => null, 'modulus' => '8', 'separator' => ' | ', 'first' => null, 'last' => null, 'ellipsis' => '...', ); $options += $defaults; $params = (array)$this->params($options['model']) + array('page'=> 1); unset($options['model']); if ($params['pageCount'] <= 1) { return false; } extract($options); unset($options['tag'], $options['before'], $options['after'], $options['model'], $options['modulus'], $options['separator'], $options['first'], $options['last'], $options['ellipsis'], $options['class'] ); $out = ''; if ($modulus && $params['pageCount'] > $modulus) { $half = intval($modulus / 2); $end = $params['page'] + $half; if ($end > $params['pageCount']) { $end = $params['pageCount']; } $start = $params['page'] - ($modulus - ($end - $params['page'])); if ($start <= 1) { $start = 1; $end = $params['page'] + ($modulus - $params['page']) + 1; } if ($first && $start > 1) { $offset = ($start <= (int)$first) ? $start - 1 : $first; if ($offset < $start - 1) { $out .= $this->first($offset, compact('tag', 'separator', 'ellipsis', 'class')); } else { $out .= $this->first($offset, compact('tag', 'separator', 'class') + array('after' => $separator)); } } $out .= $before; for ($i = $start; $i < $params['page']; $i++) { $out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options), compact('class')) . $separator; } $currentClass = 'current'; if ($class) { $currentClass .= ' ' . $class; } $out .= $this->Html->tag($tag, $params['page'], array('class' => $currentClass)); if ($i != $params['pageCount']) { $out .= $separator; } $start = $params['page'] + 1; for ($i = $start; $i < $end; $i++) { $out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options), compact('class')) . $separator; } if ($end != $params['page']) { $out .= $this->Html->tag($tag, $this->link($i, array('page' => $end), $options), compact('class')); } $out .= $after; if ($last && $end < $params['pageCount']) { $offset = ($params['pageCount'] < $end + (int)$last) ? $params['pageCount'] - $end : $last; if ($offset <= $last && $params['pageCount'] - $end > $offset) { $out .= $this->last($offset, compact('tag', 'separator', 'ellipsis', 'class')); } else { $out .= $this->last($offset, compact('tag', 'separator', 'class') + array('before' => $separator)); } } } else { $out .= $before; for ($i = 1; $i <= $params['pageCount']; $i++) { if ($i == $params['page']) { $currentClass = 'current'; if ($class) { $currentClass .= ' ' . $class; } $out .= $this->Html->tag($tag, $i, array('class' => $currentClass)); } else { $out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options), compact('class')); } if ($i != $params['pageCount']) { $out .= $separator; } } $out .= $after; } return $out; } /** * Returns a first or set of numbers for the first pages. * * `echo $this->Paginator->first('< first');` * * Creates a single link for the first page. Will output nothing if you are on the first page. * * `echo $this->Paginator->first(3);` * * Will create links for the first 3 pages, once you get to the third or greater page. Prior to that * nothing will be output. * * ### Options: * * - `tag` The tag wrapping tag you want to use, defaults to 'span' * - `after` Content to insert after the link/tag * - `model` The model to use defaults to PaginatorHelper::defaultModel() * - `separator` Content between the generated links, defaults to ' | ' * - `ellipsis` Content for ellipsis, defaults to '...' * * @param mixed $first if string use as label for the link. If numeric, the number of page links * you want at the beginning of the range. * @param mixed $options An array of options. * @return string numbers string. */ public function first($first = '<< first', $options = array()) { $options = array_merge( array( 'tag' => 'span', 'after' => null, 'model' => $this->defaultModel(), 'separator' => ' | ', 'ellipsis' => '...', 'class' => null ), (array)$options); $params = array_merge(array('page' => 1), (array)$this->params($options['model'])); unset($options['model']); if ($params['pageCount'] <= 1) { return false; } extract($options); unset($options['tag'], $options['after'], $options['model'], $options['separator'], $options['ellipsis'], $options['class']); $out = ''; if (is_int($first) && $params['page'] >= $first) { if ($after === null) { $after = $ellipsis; } for ($i = 1; $i <= $first; $i++) { $out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options), compact('class')); if ($i != $first) { $out .= $separator; } } $out .= $after; } elseif ($params['page'] > 1 && is_string($first)) { $options += array('rel' => 'first'); $out = $this->Html->tag($tag, $this->link($first, array('page' => 1), $options), compact('class')) . $after; } return $out; } /** * Returns a last or set of numbers for the last pages. * * `echo $this->Paginator->last('last >');` * * Creates a single link for the last page. Will output nothing if you are on the last page. * * `echo $this->Paginator->last(3);` * * Will create links for the last 3 pages. Once you enter the page range, no output will be created. * * ### Options: * * - `tag` The tag wrapping tag you want to use, defaults to 'span' * - `before` Content to insert before the link/tag * - `model` The model to use defaults to PaginatorHelper::defaultModel() * - `separator` Content between the generated links, defaults to ' | ' * - `ellipsis` Content for ellipsis, defaults to '...' * * @param mixed $last if string use as label for the link, if numeric print page numbers * @param mixed $options Array of options * @return string numbers string. */ public function last($last = 'last >>', $options = array()) { $options = array_merge( array( 'tag' => 'span', 'before'=> null, 'model' => $this->defaultModel(), 'separator' => ' | ', 'ellipsis' => '...', 'class' => null ), (array)$options); $params = array_merge(array('page'=> 1), (array)$this->params($options['model'])); unset($options['model']); if ($params['pageCount'] <= 1) { return false; } extract($options); unset($options['tag'], $options['before'], $options['model'], $options['separator'], $options['ellipsis'], $options['class']); $out = ''; $lower = $params['pageCount'] - $last + 1; if (is_int($last) && $params['page'] <= $lower) { if ($before === null) { $before = $ellipsis; } for ($i = $lower; $i <= $params['pageCount']; $i++) { $out .= $this->Html->tag($tag, $this->link($i, array('page' => $i), $options), compact('class')); if ($i != $params['pageCount']) { $out .= $separator; } } $out = $before . $out; } elseif ($params['page'] < $params['pageCount'] && is_string($last)) { $options += array('rel' => 'last'); $out = $before . $this->Html->tag( $tag, $this->link($last, array('page' => $params['pageCount']), $options), compact('class') ); } return $out; } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/PaginatorHelper.php
PHP
gpl3
29,659
<?php /** * Time Helper class 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.View.Helper * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AppHelper', 'View/Helper'); /** * Time Helper class for easy use of time data. * * Manipulation of time data. * * @package Cake.View.Helper * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html */ class TimeHelper extends AppHelper { /** * The format to use when formatting a time using `TimeHelper::nice()` * * The format should use the locale strings as defined in the PHP docs under * `strftime` (http://php.net/manual/en/function.strftime.php) * * @var string * @see TimeHelper::format() */ public $niceFormat = '%a, %b %eS %Y, %H:%M'; /** * Constructor * * @param View $View the view object the helper is attached to. * @param array $settings Settings array Settings array */ public function __construct(View $View, $settings = array()) { if (isset($settings['niceFormat'])) { $this->niceFormat = $settings['niceFormat']; } parent::__construct($View, $settings); } /** * Converts a string representing the format for the function strftime and returns a * windows safe and i18n aware format. * * @param string $format Format with specifiers for strftime function. * Accepts the special specifier %S which mimics th modifier S for date() * @param string $time UNIX timestamp * @return string windows safe and date() function compatible format for strftime */ public function convertSpecifiers($format, $time = null) { if (!$time) { $time = time(); } $this->__time = $time; return preg_replace_callback('/\%(\w+)/', array($this, '_translateSpecifier'), $format); } /** * Auxiliary function to translate a matched specifier element from a regular expresion into * a windows safe and i18n aware specifier * * @param array $specifier match from regular expression * @return string converted element */ protected function _translateSpecifier($specifier) { switch ($specifier[1]) { case 'a': $abday = __dc('cake', 'abday', 5); if (is_array($abday)) { return $abday[date('w', $this->__time)]; } break; case 'A': $day = __dc('cake', 'day', 5); if (is_array($day)) { return $day[date('w', $this->__time)]; } break; case 'c': $format = __dc('cake', 'd_t_fmt', 5); if ($format != 'd_t_fmt') { return $this->convertSpecifiers($format, $this->__time); } break; case 'C': return sprintf("%02d", date('Y', $this->__time) / 100); case 'D': return '%m/%d/%y'; case 'e': if (DS === '/') { return '%e'; } $day = date('j', $this->__time); if ($day < 10) { $day = ' ' . $day; } return $day; case 'eS' : return date('jS', $this->__time); case 'b': case 'h': $months = __dc('cake', 'abmon', 5); if (is_array($months)) { return $months[date('n', $this->__time) -1]; } return '%b'; case 'B': $months = __dc('cake', 'mon', 5); if (is_array($months)) { return $months[date('n', $this->__time) -1]; } break; case 'n': return "\n"; case 'p': case 'P': $default = array('am' => 0, 'pm' => 1); $meridiem = $default[date('a',$this->__time)]; $format = __dc('cake', 'am_pm', 5); if (is_array($format)) { $meridiem = $format[$meridiem]; return ($specifier[1] == 'P') ? strtolower($meridiem) : strtoupper($meridiem); } break; case 'r': $complete = __dc('cake', 't_fmt_ampm', 5); if ($complete != 't_fmt_ampm') { return str_replace('%p',$this->_translateSpecifier(array('%p', 'p')),$complete); } break; case 'R': return date('H:i', $this->__time); case 't': return "\t"; case 'T': return '%H:%M:%S'; case 'u': return ($weekDay = date('w', $this->__time)) ? $weekDay : 7; case 'x': $format = __dc('cake', 'd_fmt', 5); if ($format != 'd_fmt') { return $this->convertSpecifiers($format, $this->__time); } break; case 'X': $format = __dc('cake', 't_fmt', 5); if ($format != 't_fmt') { return $this->convertSpecifiers($format, $this->__time); } break; } return $specifier[0]; } /** * Converts given time (in server's time zone) to user's local time, given his/her offset from GMT. * * @param string $serverTime UNIX timestamp * @param integer $userOffset User's offset from GMT (in hours) * @return string UNIX timestamp */ public function convert($serverTime, $userOffset) { $serverOffset = $this->serverOffset(); $gmtTime = $serverTime - $serverOffset; $userTime = $gmtTime + $userOffset * (60*60); return $userTime; } /** * Returns server's offset from GMT in seconds. * * @return integer Offset */ public function serverOffset() { return date('Z', time()); } /** * Returns a UNIX timestamp, given either a UNIX timestamp or a valid strtotime() date string. * * @param string $dateString Datetime string * @param integer $userOffset User's offset from GMT (in hours) * @return string Parsed timestamp * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function fromString($dateString, $userOffset = null) { if (empty($dateString)) { return false; } if (is_integer($dateString) || is_numeric($dateString)) { $date = intval($dateString); } else { $date = strtotime($dateString); } if ($userOffset !== null) { return $this->convert($date, $userOffset); } if ($date === -1) { return false; } return $date; } /** * Returns a nicely formatted date string for given Datetime string. * * See http://php.net/manual/en/function.strftime.php for information on formatting * using locale strings. * * @param string $dateString Datetime string or Unix timestamp * @param integer $userOffset User's offset from GMT (in hours) * @param string $format The format to use. If null, `TimeHelper::$niceFormat` is used * @return string Formatted date string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function nice($dateString = null, $userOffset = null, $format = null) { if ($dateString != null) { $date = $this->fromString($dateString, $userOffset); } else { $date = time(); } if (!$format) { $format = $this->niceFormat; } $format = $this->convertSpecifiers($format, $date); return strftime($format, $date); } /** * Returns a formatted descriptive date string for given datetime string. * * If the given date is today, the returned string could be "Today, 16:54". * If the given date was yesterday, the returned string could be "Yesterday, 16:54". * If $dateString's year is the current year, the returned string does not * include mention of the year. * * @param string $dateString Datetime string or Unix timestamp * @param integer $userOffset User's offset from GMT (in hours) * @return string Described, relative date string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function niceShort($dateString = null, $userOffset = null) { $date = $dateString ? $this->fromString($dateString, $userOffset) : time(); $y = $this->isThisYear($date) ? '' : ' %Y'; if ($this->isToday($dateString, $userOffset)) { $ret = __('Today, %s', strftime("%H:%M", $date)); } elseif ($this->wasYesterday($dateString, $userOffset)) { $ret = __('Yesterday, %s', strftime("%H:%M", $date)); } else { $format = $this->convertSpecifiers("%b %eS{$y}, %H:%M", $date); $ret = strftime($format, $date); } return $ret; } /** * Returns a partial SQL string to search for all records between two dates. * * @param string $begin Datetime string or Unix timestamp * @param string $end Datetime string or Unix timestamp * @param string $fieldName Name of database field to compare with * @param integer $userOffset User's offset from GMT (in hours) * @return string Partial SQL string. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function daysAsSql($begin, $end, $fieldName, $userOffset = null) { $begin = $this->fromString($begin, $userOffset); $end = $this->fromString($end, $userOffset); $begin = date('Y-m-d', $begin) . ' 00:00:00'; $end = date('Y-m-d', $end) . ' 23:59:59'; return "($fieldName >= '$begin') AND ($fieldName <= '$end')"; } /** * Returns a partial SQL string to search for all records between two times * occurring on the same day. * * @param string $dateString Datetime string or Unix timestamp * @param string $fieldName Name of database field to compare with * @param integer $userOffset User's offset from GMT (in hours) * @return string Partial SQL string. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function dayAsSql($dateString, $fieldName, $userOffset = null) { $date = $this->fromString($dateString, $userOffset); return $this->daysAsSql($dateString, $dateString, $fieldName); } /** * Returns true if given datetime string is today. * * @param string $dateString Datetime string or Unix timestamp * @param integer $userOffset User's offset from GMT (in hours) * @return boolean True if datetime string is today */ public function isToday($dateString, $userOffset = null) { $date = $this->fromString($dateString, $userOffset); return date('Y-m-d', $date) == date('Y-m-d', time()); } /** * Returns true if given datetime string is within this week. * * @param string $dateString * @param integer $userOffset User's offset from GMT (in hours) * @return boolean True if datetime string is within current week * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function isThisWeek($dateString, $userOffset = null) { $date = $this->fromString($dateString, $userOffset); return date('W o', $date) == date('W o', time()); } /** * Returns true if given datetime string is within this month * @param string $dateString * @param integer $userOffset User's offset from GMT (in hours) * @return boolean True if datetime string is within current month * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function isThisMonth($dateString, $userOffset = null) { $date = $this->fromString($dateString); return date('m Y',$date) == date('m Y', time()); } /** * Returns true if given datetime string is within current year. * * @param string $dateString Datetime string or Unix timestamp * @param integer $userOffset User's offset from GMT (in hours) * @return boolean True if datetime string is within current year * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function isThisYear($dateString, $userOffset = null) { $date = $this->fromString($dateString, $userOffset); return date('Y', $date) == date('Y', time()); } /** * Returns true if given datetime string was yesterday. * * @param string $dateString Datetime string or Unix timestamp * @param integer $userOffset User's offset from GMT (in hours) * @return boolean True if datetime string was yesterday * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time * */ public function wasYesterday($dateString, $userOffset = null) { $date = $this->fromString($dateString, $userOffset); return date('Y-m-d', $date) == date('Y-m-d', strtotime('yesterday')); } /** * Returns true if given datetime string is tomorrow. * * @param string $dateString Datetime string or Unix timestamp * @param integer $userOffset User's offset from GMT (in hours) * @return boolean True if datetime string was yesterday * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function isTomorrow($dateString, $userOffset = null) { $date = $this->fromString($dateString, $userOffset); return date('Y-m-d', $date) == date('Y-m-d', strtotime('tomorrow')); } /** * Returns the quarter * * @param string $dateString * @param boolean $range if true returns a range in Y-m-d format * @return boolean True if datetime string is within current week * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function toQuarter($dateString, $range = false) { $time = $this->fromString($dateString); $date = ceil(date('m', $time) / 3); if ($range === true) { $range = 'Y-m-d'; } if ($range !== false) { $year = date('Y', $time); switch ($date) { case 1: $date = array($year.'-01-01', $year.'-03-31'); break; case 2: $date = array($year.'-04-01', $year.'-06-30'); break; case 3: $date = array($year.'-07-01', $year.'-09-30'); break; case 4: $date = array($year.'-10-01', $year.'-12-31'); break; } } return $date; } /** * Returns a UNIX timestamp from a textual datetime description. Wrapper for PHP function strtotime(). * * @param string $dateString Datetime string to be represented as a Unix timestamp * @param integer $userOffset User's offset from GMT (in hours) * @return integer Unix timestamp * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function toUnix($dateString, $userOffset = null) { return $this->fromString($dateString, $userOffset); } /** * Returns a date formatted for Atom RSS feeds. * * @param string $dateString Datetime string or Unix timestamp * @param integer $userOffset User's offset from GMT (in hours) * @return string Formatted date string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function toAtom($dateString, $userOffset = null) { $date = $this->fromString($dateString, $userOffset); return date('Y-m-d\TH:i:s\Z', $date); } /** * Formats date for RSS feeds * * @param string $dateString Datetime string or Unix timestamp * @param integer $userOffset User's offset from GMT (in hours) * @return string Formatted date string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function toRSS($dateString, $userOffset = null) { $date = $this->fromString($dateString, $userOffset); if(!is_null($userOffset)) { if($userOffset == 0) { $timezone = '+0000'; } else { $hours = (int) floor(abs($userOffset)); $minutes = (int) (fmod(abs($userOffset), $hours) * 60); $timezone = ($userOffset < 0 ? '-' : '+') . str_pad($hours, 2, '0', STR_PAD_LEFT) . str_pad($minutes, 2, '0', STR_PAD_LEFT); } return date('D, d M Y H:i:s', $date) . ' ' . $timezone; } return date("r", $date); } /** * Returns either a relative date or a formatted date depending * on the difference between the current time and given datetime. * $datetime should be in a <i>strtotime</i> - parsable format, like MySQL's datetime datatype. * * ### Options: * * - `format` => a fall back format if the relative time is longer than the duration specified by end * - `end` => The end of relative time telling * - `userOffset` => Users offset from GMT (in hours) * * Relative dates look something like this: * 3 weeks, 4 days ago * 15 seconds ago * * Default date formatting is d/m/yy e.g: on 18/2/09 * * The returned string includes 'ago' or 'on' and assumes you'll properly add a word * like 'Posted ' before the function output. * * @param string $dateTime Datetime string or Unix timestamp * @param array $options Default format if timestamp is used in $dateString * @return string Relative time string. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function timeAgoInWords($dateTime, $options = array()) { $userOffset = null; if (is_array($options) && isset($options['userOffset'])) { $userOffset = $options['userOffset']; } $now = time(); if (!is_null($userOffset)) { $now = $this->convert(time(), $userOffset); } $inSeconds = $this->fromString($dateTime, $userOffset); $backwards = ($inSeconds > $now); $format = 'j/n/y'; $end = '+1 month'; if (is_array($options)) { if (isset($options['format'])) { $format = $options['format']; unset($options['format']); } if (isset($options['end'])) { $end = $options['end']; unset($options['end']); } } else { $format = $options; } if ($backwards) { $futureTime = $inSeconds; $pastTime = $now; } else { $futureTime = $now; $pastTime = $inSeconds; } $diff = $futureTime - $pastTime; // If more than a week, then take into account the length of months if ($diff >= 604800) { $current = array(); $date = array(); list($future['H'], $future['i'], $future['s'], $future['d'], $future['m'], $future['Y']) = explode('/', date('H/i/s/d/m/Y', $futureTime)); list($past['H'], $past['i'], $past['s'], $past['d'], $past['m'], $past['Y']) = explode('/', date('H/i/s/d/m/Y', $pastTime)); $years = $months = $weeks = $days = $hours = $minutes = $seconds = 0; if ($future['Y'] == $past['Y'] && $future['m'] == $past['m']) { $months = 0; $years = 0; } else { if ($future['Y'] == $past['Y']) { $months = $future['m'] - $past['m']; } else { $years = $future['Y'] - $past['Y']; $months = $future['m'] + ((12 * $years) - $past['m']); if ($months >= 12) { $years = floor($months / 12); $months = $months - ($years * 12); } if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] == 1) { $years --; } } } if ($future['d'] >= $past['d']) { $days = $future['d'] - $past['d']; } else { $daysInPastMonth = date('t', $pastTime); $daysInFutureMonth = date('t', mktime(0, 0, 0, $future['m'] - 1, 1, $future['Y'])); if (!$backwards) { $days = ($daysInPastMonth - $past['d']) + $future['d']; } else { $days = ($daysInFutureMonth - $past['d']) + $future['d']; } if ($future['m'] != $past['m']) { $months --; } } if ($months == 0 && $years >= 1 && $diff < ($years * 31536000)) { $months = 11; $years --; } if ($months >= 12) { $years = $years + 1; $months = $months - 12; } if ($days >= 7) { $weeks = floor($days / 7); $days = $days - ($weeks * 7); } } else { $years = $months = $weeks = 0; $days = floor($diff / 86400); $diff = $diff - ($days * 86400); $hours = floor($diff / 3600); $diff = $diff - ($hours * 3600); $minutes = floor($diff / 60); $diff = $diff - ($minutes * 60); $seconds = $diff; } $relativeDate = ''; $diff = $futureTime - $pastTime; if ($diff > abs($now - $this->fromString($end))) { $relativeDate = __('on %s', date($format, $inSeconds)); } else { if ($years > 0) { // years and months and days $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d year', '%d years', $years, $years); $relativeDate .= $months > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d month', '%d months', $months, $months) : ''; $relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d week', '%d weeks', $weeks, $weeks) : ''; $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days) : ''; } elseif (abs($months) > 0) { // months, weeks and days $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d month', '%d months', $months, $months); $relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d week', '%d weeks', $weeks, $weeks) : ''; $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days) : ''; } elseif (abs($weeks) > 0) { // weeks and days $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d week', '%d weeks', $weeks, $weeks); $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days) : ''; } elseif (abs($days) > 0) { // days and hours $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days); $relativeDate .= $hours > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d hour', '%d hours', $hours, $hours) : ''; } elseif (abs($hours) > 0) { // hours and minutes $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d hour', '%d hours', $hours, $hours); $relativeDate .= $minutes > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d minute', '%d minutes', $minutes, $minutes) : ''; } elseif (abs($minutes) > 0) { // minutes only $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d minute', '%d minutes', $minutes, $minutes); } else { // seconds only $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d second', '%d seconds', $seconds, $seconds); } if (!$backwards) { $relativeDate = __('%s ago', $relativeDate); } } return $relativeDate; } /** * Returns true if specified datetime was within the interval specified, else false. * * @param mixed $timeInterval the numeric value with space then time type. * Example of valid types: 6 hours, 2 days, 1 minute. * @param mixed $dateString the datestring or unix timestamp to compare * @param integer $userOffset User's offset from GMT (in hours) * @return boolean * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time */ public function wasWithinLast($timeInterval, $dateString, $userOffset = null) { $tmp = str_replace(' ', '', $timeInterval); if (is_numeric($tmp)) { $timeInterval = $tmp . ' ' . __('days'); } $date = $this->fromString($dateString, $userOffset); $interval = $this->fromString('-'.$timeInterval); if ($date >= $interval && $date <= time()) { return true; } return false; } /** * Returns gmt, given either a UNIX timestamp or a valid strtotime() date string. * * @param string $string Datetime string * @return string Formatted date string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting */ public function gmt($string = null) { if ($string != null) { $string = $this->fromString($string); } else { $string = time(); } $string = $this->fromString($string); $hour = intval(date("G", $string)); $minute = intval(date("i", $string)); $second = intval(date("s", $string)); $month = intval(date("n", $string)); $day = intval(date("j", $string)); $year = intval(date("Y", $string)); return gmmktime($hour, $minute, $second, $month, $day, $year); } /** * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string. * This function also accepts a time string and a format string as first and second parameters. * In that case this function behaves as a wrapper for TimeHelper::i18nFormat() * * @param string $format date format string (or a DateTime string) * @param string $date Datetime string (or a date format string) * @param boolean $invalid flag to ignore results of fromString == false * @param integer $userOffset User's offset from GMT (in hours) * @return string Formatted date string */ public function format($format, $date = null, $invalid = false, $userOffset = null) { $time = $this->fromString($date, $userOffset); $_time = $this->fromString($format, $userOffset); if (is_numeric($_time) && $time === false) { $format = $date; return $this->i18nFormat($_time, $format, $invalid, $userOffset); } if ($time === false && $invalid !== false) { return $invalid; } return date($format, $time); } /** * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string. * It take in account the default date format for the current language if a LC_TIME file is used. * * @param string $date Datetime string * @param string $format strftime format string. * @param boolean $invalid flag to ignore results of fromString == false * @param integer $userOffset User's offset from GMT (in hours) * @return string Formatted and translated date string */ public function i18nFormat($date, $format = null, $invalid = false, $userOffset = null) { $date = $this->fromString($date, $userOffset); if ($date === false && $invalid !== false) { return $invalid; } if (empty($format)) { $format = '%x'; } $format = $this->convertSpecifiers($format, $date); return strftime($format, $date); } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/TimeHelper.php
PHP
gpl3
24,928
<?php /** * JsEngineBaseClass * * PHP 5 * * CakePHP : 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.View.Helper * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AppHelper', 'View/Helper'); /** * JsEngineBaseClass * * Abstract Base Class for All JsEngines to extend. Provides generic methods. * * @package Cake.View.Helper */ abstract class JsBaseEngineHelper extends AppHelper { /** * The js snippet for the current selection. * * @var string */ public $selection; /** * Collection of option maps. Option maps allow other helpers to use generic names for engine * callbacks and options. Allowing uniform code access for all engine types. Their use is optional * for end user use though. * * @var array */ protected $_optionMap = array(); /** * An array of lowercase method names in the Engine that are buffered unless otherwise disabled. * This allows specific 'end point' methods to be automatically buffered by the JsHelper. * * @var array */ public $bufferedMethods = array('event', 'sortable', 'drag', 'drop', 'slider'); /** * Contains a list of callback names -> default arguments. * * @var array */ protected $_callbackArguments = array(); /** * Constructor. * * @param View $View * @param array $settings */ public function __construct($View, $settings = array()) { parent::__construct($View, $settings); } /** * Create an `alert()` message in Javascript * * @param string $message Message you want to alter. * @return string completed alert() */ public function alert($message) { return 'alert("' . $this->escape($message) . '");'; } /** * Redirects to a URL. Creates a window.location modification snippet * that can be used to trigger 'redirects' from Javascript. * * @param mixed $url * @param array $options * @return string completed redirect in javascript */ public function redirect($url = null) { return 'window.location = "' . Router::url($url) . '";'; } /** * Create a `confirm()` message * * @param string $message Message you want confirmed. * @return string completed confirm() */ public function confirm($message) { return 'confirm("' . $this->escape($message) . '");'; } /** * Generate a confirm snippet that returns false from the current * function scope. * * @param string $message Message to use in the confirm dialog. * @return string completed confirm with return script */ public function confirmReturn($message) { $out = 'var _confirm = ' . $this->confirm($message); $out .= "if (!_confirm) {\n\treturn false;\n}"; return $out; } /** * Create a `prompt()` Javascript function * * @param string $message Message you want to prompt. * @param string $default Default message * @return string completed prompt() */ public function prompt($message, $default = '') { return 'prompt("' . $this->escape($message) . '", "' . $this->escape($default) . '");'; } /** * Generates a JavaScript object in JavaScript Object Notation (JSON) * from an array. Will use native JSON encode method if available, and $useNative == true * * ### Options: * * - `prefix` - String prepended to the returned data. * - `postfix` - String appended to the returned data. * * @param array $data Data to be converted. * @param array $options Set of options, see above. * @return string A JSON code block */ public function object($data = array(), $options = array()) { $defaultOptions = array( 'prefix' => '', 'postfix' => '', ); $options = array_merge($defaultOptions, $options); return $options['prefix'] . json_encode($data) . $options['postfix']; } /** * Converts a PHP-native variable of any type to a JSON-equivalent representation * * @param mixed $val A PHP variable to be converted to JSON * @param boolean $quoteString If false, leaves string values unquoted * @return string a JavaScript-safe/JSON representation of $val */ public function value($val, $quoteString = true) { switch (true) { case (is_array($val) || is_object($val)): $val = $this->object($val); break; case ($val === null): $val = 'null'; break; case (is_bool($val)): $val = ($val === true) ? 'true' : 'false'; break; case (is_int($val)): $val = $val; break; case (is_float($val)): $val = sprintf("%.11f", $val); break; default: $val = $this->escape($val); if ($quoteString) { $val = '"' . $val . '"'; } break; } return $val; } /** * Escape a string to be JSON friendly. * * List of escaped elements: * * - "\r" => '\n' * - "\n" => '\n' * - '"' => '\"' * * @param string $string String that needs to get escaped. * @return string Escaped string. */ public function escape($string) { return $this->_utf8ToHex($string); } /** * Encode a string into JSON. Converts and escapes necessary characters. * * @param string $string The string that needs to be utf8->hex encoded * @return void */ protected function _utf8ToHex($string) { $length = strlen($string); $return = ''; for ($i = 0; $i < $length; ++$i) { $ord = ord($string{$i}); switch (true) { case $ord == 0x08: $return .= '\b'; break; case $ord == 0x09: $return .= '\t'; break; case $ord == 0x0A: $return .= '\n'; break; case $ord == 0x0C: $return .= '\f'; break; case $ord == 0x0D: $return .= '\r'; break; case $ord == 0x22: case $ord == 0x2F: case $ord == 0x5C: $return .= '\\' . $string{$i}; break; case (($ord >= 0x20) && ($ord <= 0x7F)): $return .= $string{$i}; break; case (($ord & 0xE0) == 0xC0): if ($i + 1 >= $length) { $i += 1; $return .= '?'; break; } $charbits = $string{$i} . $string{$i + 1}; $char = Multibyte::utf8($charbits); $return .= sprintf('\u%04s', dechex($char[0])); $i += 1; break; case (($ord & 0xF0) == 0xE0): if ($i + 2 >= $length) { $i += 2; $return .= '?'; break; } $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2}; $char = Multibyte::utf8($charbits); $return .= sprintf('\u%04s', dechex($char[0])); $i += 2; break; case (($ord & 0xF8) == 0xF0): if ($i + 3 >= $length) { $i += 3; $return .= '?'; break; } $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3}; $char = Multibyte::utf8($charbits); $return .= sprintf('\u%04s', dechex($char[0])); $i += 3; break; case (($ord & 0xFC) == 0xF8): if ($i + 4 >= $length) { $i += 4; $return .= '?'; break; } $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4}; $char = Multibyte::utf8($charbits); $return .= sprintf('\u%04s', dechex($char[0])); $i += 4; break; case (($ord & 0xFE) == 0xFC): if ($i + 5 >= $length) { $i += 5; $return .= '?'; break; } $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4} . $string{$i + 5}; $char = Multibyte::utf8($charbits); $return .= sprintf('\u%04s', dechex($char[0])); $i += 5; break; } } return $return; } /** * Create javascript selector for a CSS rule * * @param string $selector The selector that is targeted * @return JsBaseEngineHelper instance of $this. Allows chained methods. */ abstract public function get($selector); /** * Add an event to the script cache. Operates on the currently selected elements. * * ### Options * * - `wrap` - Whether you want the callback wrapped in an anonymous function. (defaults to true) * - `stop` - Whether you want the event to stopped. (defaults to true) * * @param string $type Type of event to bind to the current dom id * @param string $callback The Javascript function you wish to trigger or the function literal * @param array $options Options for the event. * @return string completed event handler */ abstract public function event($type, $callback, $options = array()); /** * Create a domReady event. This is a special event in many libraries * * @param string $functionBody The code to run on domReady * @return string completed domReady method */ abstract public function domReady($functionBody); /** * Create an iteration over the current selection result. * * @param string $callback The function body you wish to apply during the iteration. * @return string completed iteration */ abstract public function each($callback); /** * Trigger an Effect. * * ### Supported Effects * * The following effects are supported by all core JsEngines * * - `show` - reveal an element. * - `hide` - hide an element. * - `fadeIn` - Fade in an element. * - `fadeOut` - Fade out an element. * - `slideIn` - Slide an element in. * - `slideOut` - Slide an element out. * * ### Options * * - `speed` - Speed at which the animation should occur. Accepted values are 'slow', 'fast'. Not all effects use * the speed option. * * @param string $name The name of the effect to trigger. * @param array $options Array of options for the effect. * @return string completed string with effect. */ abstract public function effect($name, $options = array()); /** * Make an XHR request * * ### Event Options * * - `complete` - Callback to fire on complete. * - `success` - Callback to fire on success. * - `before` - Callback to fire on request initialization. * - `error` - Callback to fire on request failure. * * ### Options * * - `method` - The method to make the request with defaults to GET in more libraries * - `async` - Whether or not you want an asynchronous request. * - `data` - Additional data to send. * - `update` - Dom id to update with the content of the request. * - `type` - Data type for response. 'json' and 'html' are supported. Default is html for most libraries. * - `evalScripts` - Whether or not <script> tags should be eval'ed. * - `dataExpression` - Should the `data` key be treated as a callback. Useful for supplying `$options['data']` as * another Javascript expression. * * @param mixed $url Array or String URL to target with the request. * @param array $options Array of options. See above for cross library supported options * @return string XHR request. */ abstract public function request($url, $options = array()); /** * Create a draggable element. Works on the currently selected element. * Additional options may be supported by the library implementation. * * ### Options * * - `handle` - selector to the handle element. * - `snapGrid` - The pixel grid that movement snaps to, an array(x, y) * - `container` - The element that acts as a bounding box for the draggable element. * * ### Event Options * * - `start` - Event fired when the drag starts * - `drag` - Event fired on every step of the drag * - `stop` - Event fired when dragging stops (mouse release) * * @param array $options Options array see above. * @return string Completed drag script */ abstract public function drag($options = array()); /** * Create a droppable element. Allows for draggable elements to be dropped on it. * Additional options may be supported by the library implementation. * * ### Options * * - `accept` - Selector for elements this droppable will accept. * - `hoverclass` - Class to add to droppable when a draggable is over. * * ### Event Options * * - `drop` - Event fired when an element is dropped into the drop zone. * - `hover` - Event fired when a drag enters a drop zone. * - `leave` - Event fired when a drag is removed from a drop zone without being dropped. * * @param array $options Array of options for the drop. See above. * @return string Completed drop script */ abstract public function drop($options = array()); /** * Create a sortable element. * Additional options may be supported by the library implementation. * * ### Options * * - `containment` - Container for move action * - `handle` - Selector to handle element. Only this element will start sort action. * - `revert` - Whether or not to use an effect to move sortable into final position. * - `opacity` - Opacity of the placeholder * - `distance` - Distance a sortable must be dragged before sorting starts. * * ### Event Options * * - `start` - Event fired when sorting starts * - `sort` - Event fired during sorting * - `complete` - Event fired when sorting completes. * * @param array $options Array of options for the sortable. See above. * @return string Completed sortable script. */ abstract public function sortable($options = array()); /** * Create a slider UI widget. Comprised of a track and knob. * Additional options may be supported by the library implementation. * * ### Options * * - `handle` - The id of the element used in sliding. * - `direction` - The direction of the slider either 'vertical' or 'horizontal' * - `min` - The min value for the slider. * - `max` - The max value for the slider. * - `step` - The number of steps or ticks the slider will have. * - `value` - The initial offset of the slider. * * ### Events * * - `change` - Fired when the slider's value is updated * - `complete` - Fired when the user stops sliding the handle * * @param array $options Array of options for the slider. See above. * @return string Completed slider script */ abstract public function slider($options = array()); /** * Serialize the form attached to $selector. * Pass `true` for $isForm if the current selection is a form element. * Converts the form or the form element attached to the current selection into a string/json object * (depending on the library implementation) for use with XHR operations. * * ### Options * * - `isForm` - is the current selection a form, or an input? (defaults to false) * - `inline` - is the rendered statement going to be used inside another JS statement? (defaults to false) * * @param array $options options for serialization generation. * @return string completed form serialization script */ abstract public function serializeForm($options = array()); /** * Parse an options assoc array into an Javascript object literal. * Similar to object() but treats any non-integer value as a string, * does not include `{ }` * * @param array $options Options to be converted * @param array $safeKeys Keys that should not be escaped. * @return string Parsed JSON options without enclosing { }. */ protected function _parseOptions($options, $safeKeys = array()) { $out = array(); $safeKeys = array_flip($safeKeys); foreach ($options as $key => $value) { if (!is_int($value) && !isset($safeKeys[$key])) { $value = $this->value($value); } $out[] = $key . ':' . $value; } sort($out); return join(', ', $out); } /** * Maps Abstract options to engine specific option names. * If attributes are missing from the map, they are not changed. * * @param string $method Name of method whose options are being worked with. * @param array $options Array of options to map. * @return array Array of mapped options. */ protected function _mapOptions($method, $options) { if (!isset($this->_optionMap[$method])) { return $options; } foreach ($this->_optionMap[$method] as $abstract => $concrete) { if (isset($options[$abstract])) { $options[$concrete] = $options[$abstract]; unset($options[$abstract]); } } return $options; } /** * Prepare callbacks and wrap them with function ([args]) { } as defined in * _callbackArgs array. * * @param string $method Name of the method you are preparing callbacks for. * @param array $options Array of options being parsed * @param string $callbacks Additional Keys that contain callbacks * @return array Array of options with callbacks added. */ protected function _prepareCallbacks($method, $options, $callbacks = array()) { $wrapCallbacks = true; if (isset($options['wrapCallbacks'])) { $wrapCallbacks = $options['wrapCallbacks']; } unset($options['wrapCallbacks']); if (!$wrapCallbacks) { return $options; } $callbackOptions = array(); if (isset($this->_callbackArguments[$method])) { $callbackOptions = $this->_callbackArguments[$method]; } $callbacks = array_unique(array_merge(array_keys($callbackOptions), (array)$callbacks)); foreach ($callbacks as $callback) { if (empty($options[$callback])) { continue; } $args = null; if (!empty($callbackOptions[$callback])) { $args = $callbackOptions[$callback]; } $options[$callback] = 'function (' . $args . ') {' . $options[$callback] . '}'; } return $options; } /** * Conveinence wrapper method for all common option processing steps. * Runs _mapOptions, _prepareCallbacks, and _parseOptions in order. * * @param string $method Name of method processing options for. * @param array $options Array of options to process. * @return string Parsed options string. */ protected function _processOptions($method, $options) { $options = $this->_mapOptions($method, $options); $options = $this->_prepareCallbacks($method, $options); $options = $this->_parseOptions($options, array_keys($this->_callbackArguments[$method])); return $options; } /** * Convert an array of data into a query string * * @param array $parameters Array of parameters to convert to a query string * @return string Querystring fragment */ protected function _toQuerystring($parameters) { $out = ''; $keys = array_keys($parameters); $count = count($parameters); for ($i = 0; $i < $count; $i++) { $out .= $keys[$i] . '=' . $parameters[$keys[$i]]; if ($i < $count - 1) { $out .= '&'; } } return $out; } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/JsBaseEngineHelper.php
PHP
gpl3
18,167
<?php /** * MooTools Engine Helper for JsHelper * * Provides MooTools specific Javascript for JsHelper. * Assumes that you have the following MooTools packages * * - Remote, Remote.HTML, Remote.JSON * - Fx, Fx.Tween, Fx.Morph * - Selectors, DomReady, * - Drag, Drag.Move * * 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.View.Helper * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('JsBaseEngineHelper', 'View/Helper'); class MootoolsEngineHelper extends JsBaseEngineHelper { /** * Option mappings for MooTools * * @var array */ protected $_optionMap = array( 'request' => array( 'complete' => 'onComplete', 'success' => 'onSuccess', 'before' => 'onRequest', 'error' => 'onFailure' ), 'sortable' => array( 'distance' => 'snap', 'containment' => 'constrain', 'sort' => 'onSort', 'complete' => 'onComplete', 'start' => 'onStart', ), 'drag' => array( 'snapGrid' => 'snap', 'start' => 'onStart', 'drag' => 'onDrag', 'stop' => 'onComplete', ), 'drop' => array( 'drop' => 'onDrop', 'hover' => 'onEnter', 'leave' => 'onLeave', ), 'slider' => array( 'complete' => 'onComplete', 'change' => 'onChange', 'direction' => 'mode', 'step' => 'steps' ) ); /** * Contains a list of callback names -> default arguments. * * @var array */ protected $_callbackArguments = array( 'slider' => array( 'onTick' => 'position', 'onChange' => 'step', 'onComplete' => 'event' ), 'request' => array( 'onRequest' => '', 'onComplete' => '', 'onCancel' => '', 'onSuccess' => 'responseText, responseXML', 'onFailure' => 'xhr', 'onException' => 'headerName, value', ), 'drag' => array( 'onBeforeStart' => 'element', 'onStart' => 'element', 'onSnap' => 'element', 'onDrag' => 'element, event', 'onComplete' => 'element, event', 'onCancel' => 'element', ), 'drop' => array( 'onBeforeStart' => 'element', 'onStart' => 'element', 'onSnap' => 'element', 'onDrag' => 'element, event', 'onComplete' => 'element, event', 'onCancel' => 'element', 'onDrop' => 'element, droppable, event', 'onLeave' => 'element, droppable', 'onEnter' => 'element, droppable', ), 'sortable' => array( 'onStart' => 'element, clone', 'onSort' => 'element, clone', 'onComplete' => 'element', ) ); /** * Create javascript selector for a CSS rule * * @param string $selector The selector that is targeted * @return MootoolsEngineHelper instance of $this. Allows chained methods. */ public function get($selector) { $this->_multipleSelection = false; if ($selector == 'window' || $selector == 'document') { $this->selection = "$(" . $selector .")"; return $this; } if (preg_match('/^#[^\s.]+$/', $selector)) { $this->selection = '$("' . substr($selector, 1) . '")'; return $this; } $this->_multipleSelection = true; $this->selection = '$$("' . $selector . '")'; return $this; } /** * Add an event to the script cache. Operates on the currently selected elements. * * ### Options * * - 'wrap' - Whether you want the callback wrapped in an anonymous function. (defaults true) * - 'stop' - Whether you want the event to stopped. (defaults true) * * @param string $type Type of event to bind to the current dom id * @param string $callback The Javascript function you wish to trigger or the function literal * @param array $options Options for the event. * @return string completed event handler */ public function event($type, $callback, $options = array()) { $defaults = array('wrap' => true, 'stop' => true); $options = array_merge($defaults, $options); $function = 'function (event) {%s}'; if ($options['wrap'] && $options['stop']) { $callback = "event.stop();\n" . $callback; } if ($options['wrap']) { $callback = sprintf($function, $callback); } $out = $this->selection . ".addEvent(\"{$type}\", $callback);"; return $out; } /** * Create a domReady event. This is a special event in many libraries * * @param string $functionBody The code to run on domReady * @return string completed domReady method */ public function domReady($functionBody) { $this->selection = 'window'; return $this->event('domready', $functionBody, array('stop' => false)); } /** * Create an iteration over the current selection result. * * @param string $callback The function body you wish to apply during the iteration. * @return string completed iteration */ public function each($callback) { return $this->selection . '.each(function (item, index) {' . $callback . '});'; } /** * Trigger an Effect. * * @param string $name The name of the effect to trigger. * @param array $options Array of options for the effect. * @return string completed string with effect. * @see JsBaseEngineHelper::effect() */ public function effect($name, $options = array()) { $speed = null; if (isset($options['speed']) && in_array($options['speed'], array('fast', 'slow'))) { if ($options['speed'] == 'fast') { $speed = '"short"'; } elseif ($options['speed'] == 'slow') { $speed = '"long"'; } } $effect = ''; switch ($name) { case 'hide': $effect = 'setStyle("display", "none")'; break; case 'show': $effect = 'setStyle("display", "")'; break; case 'fadeIn': case 'fadeOut': case 'slideIn': case 'slideOut': list($effectName, $direction) = preg_split('/([A-Z][a-z]+)/', $name, -1, PREG_SPLIT_DELIM_CAPTURE); $direction = strtolower($direction); if ($speed) { $effect .= "set(\"$effectName\", {duration:$speed})."; } $effect .= "$effectName(\"$direction\")"; break; } return $this->selection . '.' . $effect . ';'; } /** * Create an new Request. * * Requires `Request`. If you wish to use 'update' key you must have ```Request.HTML``` * if you wish to do Json requests you will need ```JSON``` and ```Request.JSON```. * * @param mixed $url * @param array $options * @return string The completed ajax call. */ public function request($url, $options = array()) { $url = $this->url($url); $options = $this->_mapOptions('request', $options); $type = $data = null; if (isset($options['type']) || isset($options['update'])) { if (isset($options['type']) && strtolower($options['type']) == 'json') { $type = '.JSON'; } if (isset($options['update'])) { $options['update'] = str_replace('#', '', $options['update']); $type = '.HTML'; } unset($options['type']); } if (!empty($options['data'])) { $data = $options['data']; unset($options['data']); } $options['url'] = $url; $options = $this->_prepareCallbacks('request', $options); if (!empty($options['dataExpression'])) { $callbacks[] = 'data'; unset($options['dataExpression']); } elseif (!empty($data)) { $data = $this->object($data); } $options = $this->_parseOptions($options, array_keys($this->_callbackArguments['request'])); return "var jsRequest = new Request$type({{$options}}).send($data);"; } /** * Create a sortable element. * * Requires the `Sortables` plugin from MootoolsMore * * @param array $options Array of options for the sortable. * @return string Completed sortable script. * @see JsBaseEngineHelper::sortable() for options list. */ public function sortable($options = array()) { $options = $this->_processOptions('sortable', $options); return 'var jsSortable = new Sortables(' . $this->selection . ', {' . $options . '});'; } /** * Create a Draggable element. * * Requires the `Drag` plugin from MootoolsMore * * @param array $options Array of options for the draggable. * @return string Completed draggable script. * @see JsHelper::drag() for options list. */ public function drag($options = array()) { $options = $this->_processOptions('drag', $options); return $this->selection . '.makeDraggable({' . $options . '});'; } /** * Create a Droppable element. * * Requires the `Drag` and `Drag.Move` plugins from MootoolsMore * * Droppables in Mootools function differently from other libraries. Droppables * are implemented as an extension of Drag. So in addtion to making a get() selection for * the droppable element. You must also provide a selector rule to the draggable element. Furthermore, * Mootools droppables inherit all options from Drag. * * @param array $options Array of options for the droppable. * @return string Completed droppable script. * @see JsBaseEngineHelper::drop() for options list. */ public function drop($options = array()) { if (empty($options['drag'])) { trigger_error( __d('cake_dev', 'MootoolsEngine::drop() requires a "drag" option to properly function'), E_USER_WARNING ); return false; } $options['droppables'] = $this->selection; $this->get($options['drag']); unset($options['drag']); $options = $this->_mapOptions('drag', $this->_mapOptions('drop', $options)); $options = $this->_prepareCallbacks('drop', $options); $safe = array_merge(array_keys($this->_callbackArguments['drop']), array('droppables')); $optionString = $this->_parseOptions($options, $safe); $out = $this->selection . '.makeDraggable({' . $optionString . '});'; $this->selection = $options['droppables']; return $out; } /** * Create a slider control * * Requires `Slider` from MootoolsMore * * @param array $options Array of options for the slider. * @return string Completed slider script. * @see JsBaseEngineHelper::slider() for options list. */ public function slider($options = array()) { $slider = $this->selection; $this->get($options['handle']); unset($options['handle']); if (isset($options['min']) && isset($options['max'])) { $options['range'] = array($options['min'], $options['max']); unset($options['min'], $options['max']); } $optionString = $this->_processOptions('slider', $options); if (!empty($optionString)) { $optionString = ', {' . $optionString . '}'; } $out = 'var jsSlider = new Slider(' . $slider . ', ' . $this->selection . $optionString . ');'; $this->selection = $slider; return $out; } /** * Serialize the form attached to $selector. * * @param array $options Array of options. * @return string Completed serializeForm() snippet * @see JsBaseEngineHelper::serializeForm() */ public function serializeForm($options = array()) { $options = array_merge(array('isForm' => false, 'inline' => false), $options); $selection = $this->selection; if (!$options['isForm']) { $selection = '$(' . $this->selection . '.form)'; } $method = '.toQueryString()'; if (!$options['inline']) { $method .= ';'; } return $selection . $method; } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/MootoolsEngineHelper.php
PHP
gpl3
11,142
<?php /** * Number Helper. * * Methods to make numbers more readable. * * 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.View.Helper * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AppHelper', 'View/Helper'); /** * Number helper library. * * Methods to make numbers more readable. * * @package Cake.View.Helper * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html */ class NumberHelper extends AppHelper { /** * Currencies supported by the helper. You can add additional currency formats * with NumberHelper::addFormat * * @var array */ protected $_currencies = array( 'USD' => array( 'wholeSymbol' => '$', 'wholePosition' => 'before', 'fractionSymbol' => 'c', 'fractionPosition' => 'after', 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()', 'escape' => true ), 'GBP' => array( 'wholeSymbol'=>'&#163;', 'wholePosition' => 'before', 'fractionSymbol' => 'p', 'fractionPosition' => 'after', 'zero' => 0, 'places' => 2, 'thousands' => ',', 'decimals' => '.', 'negative' => '()','escape' => false ), 'EUR' => array( 'wholeSymbol'=>'&#8364;', 'wholePosition' => 'before', 'fractionSymbol' => false, 'fractionPosition' => 'after', 'zero' => 0, 'places' => 2, 'thousands' => '.', 'decimals' => ',', 'negative' => '()', 'escape' => false ) ); /** * Default options for currency formats * * @var array */ protected $_currencyDefaults = array( 'wholeSymbol'=>'', 'wholePosition' => 'before', 'fractionSymbol' => '', 'fractionPosition' => 'after', 'zero' => '0', 'places' => 2, 'thousands' => ',', 'decimals' => '.','negative' => '()', 'escape' => true ); /** * Formats a number with a level of precision. * * @param float $number A floating point number. * @param integer $precision The precision of the returned number. * @return float Formatted float. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::precision */ public function precision($number, $precision = 3) { return sprintf("%01.{$precision}f", $number); } /** * Returns a formatted-for-humans file size. * * @param integer $size Size in bytes * @return string Human readable size * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize */ public function toReadableSize($size) { switch (true) { case $size < 1024: return __dn('cake', '%d Byte', '%d Bytes', $size, $size); case round($size / 1024) < 1024: return __('%d KB', $this->precision($size / 1024, 0)); case round($size / 1024 / 1024, 2) < 1024: return __('%.2f MB', $this->precision($size / 1024 / 1024, 2)); case round($size / 1024 / 1024 / 1024, 2) < 1024: return __('%.2f GB', $this->precision($size / 1024 / 1024 / 1024, 2)); default: return __('%.2f TB', $this->precision($size / 1024 / 1024 / 1024 / 1024, 2)); } } /** * Formats a number into a percentage string. * * @param float $number A floating point number * @param integer $precision The precision of the returned number * @return string Percentage string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toPercentage */ public function toPercentage($number, $precision = 2) { return $this->precision($number, $precision) . '%'; } /** * Formats a number into a currency format. * * @param float $number A floating point number * @param integer $options if int then places, if string then before, if (,.-) then use it * or array with places and before keys * @return string formatted number * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::format */ public function format($number, $options = false) { $places = 0; if (is_int($options)) { $places = $options; } $separators = array(',', '.', '-', ':'); $before = $after = null; if (is_string($options) && !in_array($options, $separators)) { $before = $options; } $thousands = ','; if (!is_array($options) && in_array($options, $separators)) { $thousands = $options; } $decimals = '.'; if (!is_array($options) && in_array($options, $separators)) { $decimals = $options; } $escape = true; if (is_array($options)) { $options = array_merge(array('before'=>'$', 'places' => 2, 'thousands' => ',', 'decimals' => '.'), $options); extract($options); } $out = $before . number_format($number, $places, $decimals, $thousands) . $after; if ($escape) { return h($out); } return $out; } /** * Formats a number into a currency format. * * ### Options * * - `before` - The currency symbol to place before whole numbers ie. '$' * - `after` - The currency symbol to place after decimal numbers ie. 'c'. Set to boolean false to * use no decimal symbol. eg. 0.35 => $0.35. * - `zero` - The text to use for zero values, can be a string or a number. ie. 0, 'Free!' * - `places` - Number of decimal places to use. ie. 2 * - `thousands` - Thousands separator ie. ',' * - `decimals` - Decimal separator symbol ie. '.' * - `negative` - Symbol for negative numbers. If equal to '()', the number will be wrapped with ( and ) * - `escape` - Should the output be htmlentity escaped? Defaults to true * * @param float $number * @param string $currency Shortcut to default options. Valid values are 'USD', 'EUR', 'GBP', otherwise * set at least 'before' and 'after' options. * @param array $options * @return string Number formatted as a currency. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::currency */ public function currency($number, $currency = 'USD', $options = array()) { $default = $this->_currencyDefaults; if (isset($this->_currencies[$currency])) { $default = $this->_currencies[$currency]; } elseif (is_string($currency)) { $options['before'] = $currency; } $options = array_merge($default, $options); if (isset($options['before']) && $options['before'] !== '') { $options['wholeSymbol'] = $options['before']; } if (isset($options['after']) && !$options['after'] !== '') { $options['fractionSymbol'] = $options['after']; } $result = $options['before'] = $options['after'] = null; $symbolKey = 'whole'; if ($number == 0 ) { if ($options['zero'] !== 0 ) { return $options['zero']; } } elseif ($number < 1 && $number > -1 ) { if ($options['fractionSymbol'] !== false) { $multiply = intval('1' . str_pad('', $options['places'], '0')); $number = $number * $multiply; $options['places'] = null; $symbolKey = 'fraction'; } } $position = $options[$symbolKey.'Position'] != 'after' ? 'before' : 'after'; $options[$position] = $options[$symbolKey.'Symbol']; $abs = abs($number); $result = $this->format($abs, $options); if ($number < 0 ) { if ($options['negative'] == '()') { $result = '(' . $result .')'; } else { $result = $options['negative'] . $result; } } return $result; } /** * Add a currency format to the Number helper. Makes reusing * currency formats easier. * * {{{ $number->addFormat('NOK', array('before' => 'Kr. ')); }}} * * You can now use `NOK` as a shortform when formatting currency amounts. * * {{{ $number->currency($value, 'NOK'); }}} * * Added formats are merged with the following defaults. * * {{{ * array( * 'before' => '$', 'after' => 'c', 'zero' => 0, 'places' => 2, 'thousands' => ',', * 'decimals' => '.', 'negative' => '()', 'escape' => true * ) * }}} * * @param string $formatName The format name to be used in the future. * @param array $options The array of options for this format. * @return void * @see NumberHelper::currency() */ public function addFormat($formatName, $options) { $this->_currencies[$formatName] = $options + $this->_currencyDefaults; } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/NumberHelper.php
PHP
gpl3
8,334
<?php /** * CacheHelper helps create full page view caching. * * 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.View.Helper * @since CakePHP(tm) v 1.0.0.2277 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AppHelper', 'View/Helper'); /** * CacheHelper helps create full page view caching. * * When using CacheHelper you don't call any of its methods, they are all automatically * called by View, and use the $cacheAction settings set in the controller. * * @package Cake.View.Helper * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html */ class CacheHelper extends AppHelper { /** * Array of strings replaced in cached views. * The strings are found between `<!--nocache--><!--/nocache-->` in views * * @var array */ protected $_replace = array(); /** * Array of string that are replace with there var replace above. * The strings are any content inside `<!--nocache--><!--/nocache-->` and includes the tags in views * * @var array */ protected $_match = array(); /** * Counter used for counting nocache section tags. * * @var integer */ protected $_counter = 0; /** * Parses the view file and stores content for cache file building. * * @param string $viewFile * @return void */ public function afterRender($viewFile) { $caching = (($this->_View->cacheAction != false)) && (Configure::read('Cache.check') === true); if ($caching) { $this->_View->output = $this->cache($viewFile, $this->_View->output, false); } } /** * Parses the layout file and stores content for cache file building. * * @param string $layoutFile * @return void */ public function afterLayout($layoutFile) { $caching = (($this->_View->cacheAction != false)) && (Configure::read('Cache.check') === true); if ($caching) { $this->_View->output = $this->cache($layoutFile, $this->_View->output, true); } $this->_View->output = preg_replace('/<!--\/?nocache-->/', '', $this->_View->output); } /** * Main method used to cache a view * * @param string $file File to cache * @param string $out output to cache * @param boolean $cache Whether or not a cache file should be written. * @return string view ouput */ public function cache($file, $out, $cache = false) { $cacheTime = 0; $useCallbacks = false; $cacheAction = $this->_View->cacheAction; if (is_array($cacheAction)) { $keys = array_keys($cacheAction); $index = null; foreach ($keys as $action) { if ($action == $this->request->params['action']) { $index = $action; break; } } if (!isset($index) && $this->request->params['action'] == 'index') { $index = 'index'; } $options = $cacheAction; if (isset($cacheAction[$index])) { if (is_array($cacheAction[$index])) { $options = array_merge(array('duration' => 0, 'callbacks' => false), $cacheAction[$index]); } else { $cacheTime = $cacheAction[$index]; } } if (isset($options['duration'])) { $cacheTime = $options['duration']; } if (isset($options['callbacks'])) { $useCallbacks = $options['callbacks']; } } else { $cacheTime = $cacheAction; } if ($cacheTime != '' && $cacheTime > 0) { $out = preg_replace_callback('/<!--nocache-->/', array($this, '_replaceSection'), $out); $this->_parseFile($file, $out); if ($cache === true) { $cached = $this->_parseOutput($out); $this->_writeFile($cached, $cacheTime, $useCallbacks); $out = $this->_stripTags($out); } return $out; } else { return $out; } } /** * Parse file searching for no cache tags * * @param string $file The filename that needs to be parsed. * @param string $cache The cached content * @return void */ protected function _parseFile($file, $cache) { if (is_file($file)) { $file = file_get_contents($file); } elseif ($file = fileExistsInPath($file)) { $file = file_get_contents($file); } preg_match_all('/(<!--nocache:\d{3}-->(?<=<!--nocache:\d{3}-->)[\\s\\S]*?(?=<!--\/nocache-->)<!--\/nocache-->)/i', $cache, $outputResult, PREG_PATTERN_ORDER); preg_match_all('/(?<=<!--nocache-->)([\\s\\S]*?)(?=<!--\/nocache-->)/i', $file, $fileResult, PREG_PATTERN_ORDER); $fileResult = $fileResult[0]; $outputResult = $outputResult[0]; if (!empty($this->_replace)) { foreach ($outputResult as $i => $element) { $index = array_search($element, $this->_match); if ($index !== false) { unset($outputResult[$i]); } } $outputResult = array_values($outputResult); } if (!empty($fileResult)) { $i = 0; foreach ($fileResult as $cacheBlock) { if (isset($outputResult[$i])) { $this->_replace[] = $cacheBlock; $this->_match[] = $outputResult[$i]; } $i++; } } } /** * Munges the output from a view with cache tags, and numbers the sections. * This helps solve issues with empty/duplicate content. * * @return string The content with cake:nocache tags replaced. */ protected function _replaceSection() { $this->_counter += 1; return sprintf('<!--nocache:%03d-->', $this->_counter); } /** * Strip cake:nocache tags from a string. Since View::render() * only removes un-numbered nocache tags, remove all the numbered ones. * This is the complement to _replaceSection. * * @param string $content String to remove tags from. * @return string String with tags removed. */ protected function _stripTags($content) { return preg_replace('#<!--/?nocache(\:\d{3})?-->#', '', $content); } /** * Parse the output and replace cache tags * * @param string $cache Output to replace content in. * @return string with all replacements made to <!--nocache--><!--nocache--> */ protected function _parseOutput($cache) { $count = 0; if (!empty($this->_match)) { foreach ($this->_match as $found) { $original = $cache; $length = strlen($found); $position = 0; for ($i = 1; $i <= 1; $i++) { $position = strpos($cache, $found, $position); if ($position !== false) { $cache = substr($original, 0, $position); $cache .= $this->_replace[$count]; $cache .= substr($original, $position + $length); } else { break; } } $count++; } return $cache; } return $cache; } /** * Write a cached version of the file * * @param string $content view content to write to a cache file. * @param string $timestamp Duration to set for cache file. * @param boolean $useCallbacks * @return boolean success of caching view. */ protected function _writeFile($content, $timestamp, $useCallbacks = false) { $now = time(); if (is_numeric($timestamp)) { $cacheTime = $now + $timestamp; } else { $cacheTime = strtotime($timestamp, $now); } $path = $this->request->here(); if ($path == '/') { $path = 'home'; } $cache = strtolower(Inflector::slug($path)); if (empty($cache)) { return; } $cache = $cache . '.php'; $file = '<!--cachetime:' . $cacheTime . '--><?php'; if (empty($this->_View->plugin)) { $file .= ' App::import(\'Controller\', \'' . $this->_View->name. '\'); '; } else { $file .= ' App::import(\'Controller\', \'' . $this->_View->plugin . '.' . $this->_View->name. '\'); '; } $file .= '$controller = new ' . $this->_View->name . 'Controller(); $controller->plugin = $this->plugin = \'' . $this->_View->plugin . '\'; $controller->helpers = $this->helpers = unserialize(\'' . serialize($this->_View->helpers) . '\'); $controller->layout = $this->layout = \'' . $this->_View->layout. '\'; $controller->request = $this->request = unserialize(\'' . str_replace("'", "\\'", serialize($this->request)) . '\'); $controller->theme = $this->theme = \'' . $this->_View->theme . '\'; $controller->viewVars = $this->viewVars = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->viewVars)) . '\')); Router::setRequestInfo($controller->request);'; if ($useCallbacks == true) { $file .= ' $controller->constructClasses(); $controller->startupProcess();'; } $file .= ' $this->loadHelpers(); extract($this->viewVars, EXTR_SKIP); ?>'; $content = preg_replace("/(<\\?xml)/", "<?php echo '$1';?>",$content); $file .= $content; return cache('views' . DS . $cache, $file, $timestamp); } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/CacheHelper.php
PHP
gpl3
8,705
<?php /** * Prototype Engine Helper for JsHelper * * Provides Prototype specific Javascript for JsHelper. Requires at least * Prototype 1.6 * * 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.View.Helper * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('JsBaseEngineHelper', 'View/Helper'); class PrototypeEngineHelper extends JsBaseEngineHelper { /** * Is the current selection a multiple selection? or is it just a single element. * * @var boolean */ protected $_multiple = false; /** * Option mappings for Prototype * * @var array */ protected $_optionMap = array( 'request' => array( 'async' => 'asynchronous', 'data' => 'parameters', 'before' => 'onCreate', 'success' => 'onSuccess', 'complete' => 'onComplete', 'error' => 'onFailure' ), 'sortable' => array( 'sort' => 'onChange', 'complete' => 'onUpdate', ), 'drag' => array( 'snapGrid' => 'snap', 'container' => 'constraint', 'stop' => 'onEnd', 'start' => 'onStart', 'drag' => 'onDrag', ), 'drop' => array( 'hover' => 'onHover', 'drop' => 'onDrop', 'hoverClass' => 'hoverclass', ), 'slider' => array( 'direction' => 'axis', 'change' => 'onSlide', 'complete' => 'onChange', 'value' => 'sliderValue', ) ); /** * Contains a list of callback names -> default arguments. * * @var array */ protected $_callbackArguments = array( 'slider' => array( 'onSlide' => 'value', 'onChange' => 'value', ), 'drag' => array( 'onStart' => 'event', 'onDrag' => 'event', 'change' => 'draggable', 'onEnd' => 'event', ), 'drop' => array( 'onHover' => 'draggable, droppable, event', 'onDrop' => 'draggable, droppable, event', ), 'request' => array( 'onCreate' => 'transport', 'onComplete' => 'transport', 'onFailure' => 'response, jsonHeader', 'onRequest' => 'transport', 'onSuccess' => 'response, jsonHeader' ), 'sortable' => array( 'onStart' => 'element', 'onChange' => 'element', 'onUpdate' => 'element', ), ); /** * Create javascript selector for a CSS rule * * @param string $selector The selector that is targeted * @return PrototypeEngineHelper instance of $this. Allows chained methods. */ public function get($selector) { $this->_multiple = false; if ($selector == 'window' || $selector == 'document') { $this->selection = "$(" . $selector .")"; return $this; } if (preg_match('/^#[^\s.]+$/', $selector)) { $this->selection = '$("' . substr($selector, 1) . '")'; return $this; } $this->_multiple = true; $this->selection = '$$("' . $selector . '")'; return $this; } /** * Add an event to the script cache. Operates on the currently selected elements. * * ### Options * * - `wrap` - Whether you want the callback wrapped in an anonymous function. (defaults true) * - `stop` - Whether you want the event to stopped. (defaults true) * * @param string $type Type of event to bind to the current 946 id * @param string $callback The Javascript function you wish to trigger or the function literal * @param array $options Options for the event. * @return string completed event handler */ public function event($type, $callback, $options = array()) { $defaults = array('wrap' => true, 'stop' => true); $options = array_merge($defaults, $options); $function = 'function (event) {%s}'; if ($options['wrap'] && $options['stop']) { $callback = "event.stop();\n" . $callback; } if ($options['wrap']) { $callback = sprintf($function, $callback); } $out = $this->selection . ".observe(\"{$type}\", $callback);"; return $out; } /** * Create a domReady event. This is a special event in many libraries * * @param string $functionBody The code to run on domReady * @return string completed domReady method */ public function domReady($functionBody) { $this->selection = 'document'; return $this->event('dom:loaded', $functionBody, array('stop' => false)); } /** * Create an iteration over the current selection result. * * @param string $callback The function body you wish to apply during the iteration. * @return string completed iteration */ public function each($callback) { return $this->selection . '.each(function (item, index) {' . $callback . '});'; } /** * Trigger an Effect. * * ### Note: Effects require Scriptaculous to be loaded. * * @param string $name The name of the effect to trigger. * @param array $options Array of options for the effect. * @return string completed string with effect. * @see JsBaseEngineHelper::effect() */ public function effect($name, $options = array()) { $effect = ''; $optionString = null; if (isset($options['speed'])) { if ($options['speed'] == 'fast') { $options['duration'] = 0.5; } elseif ($options['speed'] == 'slow') { $options['duration'] = 2; } else { $options['duration'] = 1; } unset($options['speed']); } if (!empty($options)) { $optionString = ', {' . $this->_parseOptions($options) . '}'; } switch ($name) { case 'hide': case 'show': $effect = $this->selection . '.' . $name . '();'; break; case 'slideIn': case 'slideOut': $name = ($name == 'slideIn') ? 'slideDown' : 'slideUp'; $effect = 'Effect.' . $name . '(' . $this->selection . $optionString . ');'; break; case 'fadeIn': case 'fadeOut': $name = ($name == 'fadeIn') ? 'appear' : 'fade'; $effect = $this->selection . '.' . $name .'(' . substr($optionString, 2) . ');'; break; } return $effect; } /** * Create an Ajax or Ajax.Updater call. * * @param mixed $url * @param array $options * @return string The completed ajax call. */ public function request($url, $options = array()) { $url = '"'. $this->url($url) . '"'; $options = $this->_mapOptions('request', $options); $type = '.Request'; $data = null; if (isset($options['type']) && strtolower($options['type']) == 'json') { unset($options['type']); } if (isset($options['update'])) { $url = '"' . str_replace('#', '', $options['update']) . '", ' . $url; $type = '.Updater'; unset($options['update'], $options['type']); } $safe = array_keys($this->_callbackArguments['request']); $options = $this->_prepareCallbacks('request', $options, $safe); if (!empty($options['dataExpression'])) { $safe[] = 'parameters'; unset($options['dataExpression']); } $options = $this->_parseOptions($options, $safe); if (!empty($options)) { $options = ', {' . $options . '}'; } return "var jsRequest = new Ajax$type($url$options);"; } /** * Create a sortable element. * * #### Note: Requires scriptaculous to be loaded. * * The scriptaculous implementation of sortables does not suppot the 'start' * and 'distance' options. * * @param array $options Array of options for the sortable. * @return string Completed sortable script. * @see JsBaseEngineHelper::sortable() for options list. */ public function sortable($options = array()) { $options = $this->_processOptions('sortable', $options); if (!empty($options)) { $options = ', {' . $options . '}'; } return 'var jsSortable = Sortable.create(' . $this->selection . $options . ');'; } /** * Create a Draggable element. * * #### Note: Requires scriptaculous to be loaded. * * @param array $options Array of options for the draggable. * @return string Completed draggable script. * @see JsBaseEngineHelper::draggable() for options list. */ public function drag($options = array()) { $options = $this->_processOptions('drag', $options); if (!empty($options)) { $options = ', {' . $options . '}'; } if ($this->_multiple) { return $this->each('new Draggable(item' . $options . ');'); } return 'var jsDrag = new Draggable(' . $this->selection . $options . ');'; } /** * Create a Droppable element. * * #### Note: Requires scriptaculous to be loaded. * * @param array $options Array of options for the droppable. * @return string Completed droppable script. * @see JsBaseEngineHelper::droppable() for options list. */ public function drop($options = array()) { $options = $this->_processOptions('drop', $options); if (!empty($options)) { $options = ', {' . $options . '}'; } return 'Droppables.add(' . $this->selection . $options . ');'; } /** * Creates a slider control widget. * * ### Note: Requires scriptaculous to be loaded. * * @param array $options Array of options for the slider. * @return string Completed slider script. * @see JsBaseEngineHelper::slider() for options list. */ public function slider($options = array()) { $slider = $this->selection; $this->get($options['handle']); unset($options['handle']); if (isset($options['min']) && isset($options['max'])) { $options['range'] = sprintf('$R(%s,%s)', $options['min'], $options['max']); unset($options['min'], $options['max']); } $options = $this->_mapOptions('slider', $options); $options = $this->_prepareCallbacks('slider', $options); $optionString = $this->_parseOptions( $options, array_merge(array_keys($this->_callbackArguments['slider']), array('range')) ); if (!empty($optionString)) { $optionString = ', {' . $optionString . '}'; } $out = 'var jsSlider = new Control.Slider(' . $this->selection . ', ' . $slider . $optionString . ');'; $this->selection = $slider; return $out; } /** * Serialize the form attached to $selector. * * @param array $options Array of options. * @return string Completed serializeForm() snippet * @see JsBaseEngineHelper::serializeForm() */ public function serializeForm($options = array()) { $options = array_merge(array('isForm' => false, 'inline' => false), $options); $selection = $this->selection; if (!$options['isForm']) { $selection = '$(' . $this->selection . '.form)'; } $method = '.serialize()'; if (!$options['inline']) { $method .= ';'; } return $selection . $method; } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/PrototypeEngineHelper.php
PHP
gpl3
10,385
<?php /** * Html Helper class file. * * Simplifies the construction of HTML elements. * * 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.View.Helper * @since CakePHP(tm) v 0.9.1 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AppHelper', 'View/Helper'); /** * Html Helper class for easy use of HTML widgets. * * HtmlHelper encloses all methods needed while working with HTML pages. * * @package Cake.View.Helper * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html */ class HtmlHelper extends AppHelper { /** * html tags used by this helper. * * @var array */ protected $_tags = array( 'meta' => '<meta%s/>', 'metalink' => '<link href="%s"%s/>', 'link' => '<a href="%s"%s>%s</a>', 'mailto' => '<a href="mailto:%s" %s>%s</a>', 'form' => '<form action="%s"%s>', 'formend' => '</form>', 'input' => '<input name="%s"%s/>', 'textarea' => '<textarea name="%s"%s>%s</textarea>', 'hidden' => '<input type="hidden" name="%s"%s/>', 'checkbox' => '<input type="checkbox" name="%s" %s/>', 'checkboxmultiple' => '<input type="checkbox" name="%s[]"%s />', 'radio' => '<input type="radio" name="%s" id="%s" %s />%s', 'selectstart' => '<select name="%s"%s>', 'selectmultiplestart' => '<select name="%s[]"%s>', 'selectempty' => '<option value=""%s>&nbsp;</option>', 'selectoption' => '<option value="%s"%s>%s</option>', 'selectend' => '</select>', 'optiongroup' => '<optgroup label="%s"%s>', 'optiongroupend' => '</optgroup>', 'checkboxmultiplestart' => '', 'checkboxmultipleend' => '', 'password' => '<input type="password" name="%s" %s/>', 'file' => '<input type="file" name="%s" %s/>', 'file_no_model' => '<input type="file" name="%s" %s/>', 'submit' => '<input %s/>', 'submitimage' => '<input type="image" src="%s" %s/>', 'button' => '<button type="%s"%s>%s</button>', 'image' => '<img src="%s" %s/>', 'tableheader' => '<th%s>%s</th>', 'tableheaderrow' => '<tr%s>%s</tr>', 'tablecell' => '<td%s>%s</td>', 'tablerow' => '<tr%s>%s</tr>', 'block' => '<div%s>%s</div>', 'blockstart' => '<div%s>', 'blockend' => '</div>', 'tag' => '<%s%s>%s</%s>', 'tagstart' => '<%s%s>', 'tagend' => '</%s>', 'para' => '<p%s>%s</p>', 'parastart' => '<p%s>', 'label' => '<label for="%s"%s>%s</label>', 'fieldset' => '<fieldset%s>%s</fieldset>', 'fieldsetstart' => '<fieldset><legend>%s</legend>', 'fieldsetend' => '</fieldset>', 'legend' => '<legend>%s</legend>', 'css' => '<link rel="%s" type="text/css" href="%s" %s/>', 'style' => '<style type="text/css"%s>%s</style>', 'charset' => '<meta http-equiv="Content-Type" content="text/html; charset=%s" />', 'ul' => '<ul%s>%s</ul>', 'ol' => '<ol%s>%s</ol>', 'li' => '<li%s>%s</li>', 'error' => '<div%s>%s</div>', 'javascriptblock' => '<script type="text/javascript"%s>%s</script>', 'javascriptstart' => '<script type="text/javascript">', 'javascriptlink' => '<script type="text/javascript" src="%s"%s></script>', 'javascriptend' => '</script>' ); /** * Minimized attributes * * @var array */ protected $_minimizedAttributes = array( 'compact', 'checked', 'declare', 'readonly', 'disabled', 'selected', 'defer', 'ismap', 'nohref', 'noshade', 'nowrap', 'multiple', 'noresize' ); /** * Format to attribute * * @var string */ protected $_attributeFormat = '%s="%s"'; /** * Format to attribute * * @var string */ protected $_minimizedAttributeFormat = '%s="%s"'; /** * Breadcrumbs. * * @var array */ protected $_crumbs = array(); /** * Names of script files that have been included once * * @var array */ protected $_includedScripts = array(); /** * Options for the currently opened script block buffer if any. * * @var array */ protected $_scriptBlockOptions = array(); /** * Document type definitions * * @var array */ protected $_docTypes = array( 'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">', 'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">', 'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">', 'html5' => '<!DOCTYPE html>', 'xhtml-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', 'xhtml-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">', 'xhtml-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">', 'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">' ); /** * Constructor * * ### Settings * * - `configFile` A file containing an array of tags you wish to redefine. * * ### Customizing tag sets * * Using the `configFile` option you can redefine the tag HtmlHelper will use. * The file named should be compatible with HtmlHelper::loadConfig(). * * @param View $View The View this helper is being attached to. * @param array $settings Configuration settings for the helper. */ public function __construct(View $View, $settings = array()) { parent::__construct($View, $settings); if (!empty($settings['configFile'])) { $this->loadConfig($settings['configFile']); } } /** * Adds a link to the breadcrumbs array. * * @param string $name Text for link * @param string $link URL for link (if empty it won't be a link) * @param mixed $options Link attributes e.g. array('id'=>'selected') * @return void * @see HtmlHelper::link() for details on $options that can be used. */ public function addCrumb($name, $link = null, $options = null) { $this->_crumbs[] = array($name, $link, $options); } /** * Returns a doctype string. * * Possible doctypes: * * - html4-strict: HTML4 Strict. * - html4-trans: HTML4 Transitional. * - html4-frame: HTML4 Frameset. * - html5: HTML5. * - xhtml-strict: XHTML1 Strict. * - xhtml-trans: XHTML1 Transitional. * - xhtml-frame: XHTML1 Frameset. * - xhtml11: XHTML1.1. * * @param string $type Doctype to use. * @return string Doctype string * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::docType */ public function docType($type = 'xhtml-strict') { if (isset($this->_docTypes[$type])) { return $this->_docTypes[$type]; } return null; } /** * Creates a link to an external resource and handles basic meta tags * * ### Options * * - `inline` Whether or not the link element should be output inline, or in scripts_for_layout. * * @param string $type The title of the external resource * @param mixed $url The address of the external resource or string for content attribute * @param array $options Other attributes for the generated tag. If the type attribute is html, * rss, atom, or icon, the mime-type is returned. * @return string A completed `<link />` element. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::meta */ public function meta($type, $url = null, $options = array()) { $inline = isset($options['inline']) ? $options['inline'] : true; unset($options['inline']); if (!is_array($type)) { $types = array( 'rss' => array('type' => 'application/rss+xml', 'rel' => 'alternate', 'title' => $type, 'link' => $url), 'atom' => array('type' => 'application/atom+xml', 'title' => $type, 'link' => $url), 'icon' => array('type' => 'image/x-icon', 'rel' => 'icon', 'link' => $url), 'keywords' => array('name' => 'keywords', 'content' => $url), 'description' => array('name' => 'description', 'content' => $url), ); if ($type === 'icon' && $url === null) { $types['icon']['link'] = $this->webroot('favicon.ico'); } if (isset($types[$type])) { $type = $types[$type]; } elseif (!isset($options['type']) && $url !== null) { if (is_array($url) && isset($url['ext'])) { $type = $types[$url['ext']]; } else { $type = $types['rss']; } } elseif (isset($options['type']) && isset($types[$options['type']])) { $type = $types[$options['type']]; unset($options['type']); } else { $type = array(); } } elseif ($url !== null) { $inline = $url; } $options = array_merge($type, $options); $out = null; if (isset($options['link'])) { if (isset($options['rel']) && $options['rel'] === 'icon') { $out = sprintf($this->_tags['metalink'], $options['link'], $this->_parseAttributes($options, array('link'), ' ', ' ')); $options['rel'] = 'shortcut icon'; } else { $options['link'] = $this->url($options['link'], true); } $out .= sprintf($this->_tags['metalink'], $options['link'], $this->_parseAttributes($options, array('link'), ' ', ' ')); } else { $out = sprintf($this->_tags['meta'], $this->_parseAttributes($options, array('type'), ' ', ' ')); } if ($inline) { return $out; } else { $this->_View->addScript($out); } } /** * Returns a charset META-tag. * * @param string $charset The character set to be used in the meta tag. If empty, * The App.encoding value will be used. Example: "utf-8". * @return string A meta tag containing the specified character set. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::charset */ public function charset($charset = null) { if (empty($charset)) { $charset = strtolower(Configure::read('App.encoding')); } return sprintf($this->_tags['charset'], (!empty($charset) ? $charset : 'utf-8')); } /** * Creates an HTML link. * * If $url starts with "http://" this is treated as an external link. Else, * it is treated as a path to controller/action and parsed with the * HtmlHelper::url() method. * * If the $url is empty, $title is used instead. * * ### Options * * - `escape` Set to false to disable escaping of title and attributes. * - `confirm` JavaScript confirmation message. * * @param string $title The content to be wrapped by <a> tags. * @param mixed $url Cake-relative URL or array of URL parameters, or external URL (starts with http://) * @param array $options Array of HTML attributes. * @param string $confirmMessage JavaScript confirmation message. * @return string An `<a />` element. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::link */ public function link($title, $url = null, $options = array(), $confirmMessage = false) { $escapeTitle = true; if ($url !== null) { $url = $this->url($url); } else { $url = $this->url($title); $title = $url; $escapeTitle = false; } if (isset($options['escape'])) { $escapeTitle = $options['escape']; } if ($escapeTitle === true) { $title = h($title); } elseif (is_string($escapeTitle)) { $title = htmlentities($title, ENT_QUOTES, $escapeTitle); } if (!empty($options['confirm'])) { $confirmMessage = $options['confirm']; unset($options['confirm']); } if ($confirmMessage) { $confirmMessage = str_replace("'", "\'", $confirmMessage); $confirmMessage = str_replace('"', '\"', $confirmMessage); $options['onclick'] = "return confirm('{$confirmMessage}');"; } elseif (isset($options['default']) && $options['default'] == false) { if (isset($options['onclick'])) { $options['onclick'] .= ' event.returnValue = false; return false;'; } else { $options['onclick'] = 'event.returnValue = false; return false;'; } unset($options['default']); } return sprintf($this->_tags['link'], $url, $this->_parseAttributes($options), $title); } /** * Creates a link element for CSS stylesheets. * * ### Usage * * Include one CSS file: * * `echo $this->Html->css('styles.css');` * * Include multiple CSS files: * * `echo $this->Html->css(array('one.css', 'two.css'));` * * Add the stylesheet to the `$scripts_for_layout` layout var: * * `$this->Html->css('styles.css', null, array('inline' => false));` * * ### Options * * - `inline` If set to false, the generated tag appears in the head tag of the layout. Defaults to true * * @param mixed $path The name of a CSS style sheet or an array containing names of * CSS stylesheets. If `$path` is prefixed with '/', the path will be relative to the webroot * of your application. Otherwise, the path will be relative to your CSS path, usually webroot/css. * @param string $rel Rel attribute. Defaults to "stylesheet". If equal to 'import' the stylesheet will be imported. * @param array $options Array of HTML attributes. * @return string CSS <link /> or <style /> tag, depending on the type of link. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::css */ public function css($path, $rel = null, $options = array()) { $options += array('inline' => true); if (is_array($path)) { $out = ''; foreach ($path as $i) { $out .= "\n\t" . $this->css($i, $rel, $options); } if ($options['inline']) { return $out . "\n"; } return; } if (strpos($path, '://') !== false) { $url = $path; } else { if ($path[0] !== '/') { $path = CSS_URL . $path; } if (strpos($path, '?') === false) { if (substr($path, -4) !== '.css') { $path .= '.css'; } } $url = $this->assetTimestamp($this->webroot($path)); if (Configure::read('Asset.filter.css')) { $pos = strpos($url, CSS_URL); if ($pos !== false) { $url = substr($url, 0, $pos) . 'ccss/' . substr($url, $pos + strlen(CSS_URL)); } } } if ($rel == 'import') { $out = sprintf($this->_tags['style'], $this->_parseAttributes($options, array('inline'), '', ' '), '@import url(' . $url . ');'); } else { if ($rel == null) { $rel = 'stylesheet'; } $out = sprintf($this->_tags['css'], $rel, $url, $this->_parseAttributes($options, array('inline'), '', ' ')); } if ($options['inline']) { return $out; } else { $this->_View->addScript($out); } } /** * Returns one or many `<script>` tags depending on the number of scripts given. * * If the filename is prefixed with "/", the path will be relative to the base path of your * application. Otherwise, the path will be relative to your JavaScript path, usually webroot/js. * * * ### Usage * * Include one script file: * * `echo $this->Html->script('styles.js');` * * Include multiple script files: * * `echo $this->Html->script(array('one.js', 'two.js'));` * * Add the script file to the `$scripts_for_layout` layout var: * * `$this->Html->script('styles.js', null, array('inline' => false));` * * ### Options * * - `inline` - Whether script should be output inline or into scripts_for_layout. * - `once` - Whether or not the script should be checked for uniqueness. If true scripts will only be * included once, use false to allow the same script to be included more than once per request. * * @param mixed $url String or array of javascript files to include * @param mixed $options Array of options, and html attributes see above. If boolean sets $options['inline'] = value * @return mixed String of `<script />` tags or null if $inline is false or if $once is true and the file has been * included before. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::script */ public function script($url, $options = array()) { if (is_bool($options)) { list($inline, $options) = array($options, array()); $options['inline'] = $inline; } $options = array_merge(array('inline' => true, 'once' => true), $options); if (is_array($url)) { $out = ''; foreach ($url as $i) { $out .= "\n\t" . $this->script($i, $options); } if ($options['inline']) { return $out . "\n"; } return null; } if ($options['once'] && isset($this->_includedScripts[$url])) { return null; } $this->_includedScripts[$url] = true; if (strpos($url, '://') === false) { if ($url[0] !== '/') { $url = JS_URL . $url; } if (strpos($url, '?') === false && substr($url, -3) !== '.js') { $url .= '.js'; } $url = $this->assetTimestamp($this->webroot($url)); if (Configure::read('Asset.filter.js')) { $url = str_replace(JS_URL, 'cjs/', $url); } } $attributes = $this->_parseAttributes($options, array('inline', 'once'), ' '); $out = sprintf($this->_tags['javascriptlink'], $url, $attributes); if ($options['inline']) { return $out; } else { $this->_View->addScript($out); } } /** * Wrap $script in a script tag. * * ### Options * * - `safe` (boolean) Whether or not the $script should be wrapped in <![CDATA[ ]]> * - `inline` (boolean) Whether or not the $script should be added to $scripts_for_layout or output inline * * @param string $script The script to wrap * @param array $options The options to use. * @return mixed string or null depending on the value of `$options['inline']` * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptBlock */ public function scriptBlock($script, $options = array()) { $options += array('safe' => true, 'inline' => true); if ($options['safe']) { $script = "\n" . '//<![CDATA[' . "\n" . $script . "\n" . '//]]>' . "\n"; } $inline = $options['inline']; unset($options['inline'], $options['safe']); $attributes = $this->_parseAttributes($options, ' ', ' '); if ($inline) { return sprintf($this->_tags['javascriptblock'], $attributes, $script); } else { $this->_View->addScript(sprintf($this->_tags['javascriptblock'], $attributes, $script)); return null; } } /** * Begin a script block that captures output until HtmlHelper::scriptEnd() * is called. This capturing block will capture all output between the methods * and create a scriptBlock from it. * * ### Options * * - `safe` Whether the code block should contain a CDATA * - `inline` Should the generated script tag be output inline or in `$scripts_for_layout` * * @param array $options Options for the code block. * @return void * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptStart */ public function scriptStart($options = array()) { $options += array('safe' => true, 'inline' => true); $this->_scriptBlockOptions = $options; ob_start(); return null; } /** * End a Buffered section of Javascript capturing. * Generates a script tag inline or in `$scripts_for_layout` depending on the settings * used when the scriptBlock was started * * @return mixed depending on the settings of scriptStart() either a script tag or null * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptEnd */ public function scriptEnd() { $buffer = ob_get_clean(); $options = $this->_scriptBlockOptions; $this->_scriptBlockOptions = array(); return $this->scriptBlock($buffer, $options); } /** * Builds CSS style data from an array of CSS properties * * ### Usage: * * {{{ * echo $html->style(array('margin' => '10px', 'padding' => '10px'), true); * * // creates * 'margin:10px;padding:10px;' * }}} * * @param array $data Style data array, keys will be used as property names, values as property values. * @param boolean $oneline Whether or not the style block should be displayed on one line. * @return string CSS styling data * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::style */ public function style($data, $oneline = true) { if (!is_array($data)) { return $data; } $out = array(); foreach ($data as $key=> $value) { $out[] = $key.':'.$value.';'; } if ($oneline) { return join(' ', $out); } return implode("\n", $out); } /** * Returns the breadcrumb trail as a sequence of &raquo;-separated links. * * @param string $separator Text to separate crumbs. * @param string $startText This will be the first crumb, if false it defaults to first crumb in array * @return string Composed bread crumbs */ public function getCrumbs($separator = '&raquo;', $startText = false) { if (!empty($this->_crumbs)) { $out = array(); if ($startText) { $out[] = $this->link($startText, '/'); } foreach ($this->_crumbs as $crumb) { if (!empty($crumb[1])) { $out[] = $this->link($crumb[0], $crumb[1], $crumb[2]); } else { $out[] = $crumb[0]; } } return join($separator, $out); } else { return null; } } /** * Returns breadcrumbs as a (x)html list * * This method uses HtmlHelper::tag() to generate list and its elements. Works * similiary to HtmlHelper::getCrumbs(), so it uses options which every * crumb was added with. * * @param array $options Array of html attributes to apply to the generated list elements. * @return string breadcrumbs html list */ public function getCrumbList($options = array()) { if (!empty($this->_crumbs)) { $result = ''; $crumbCount = count($this->_crumbs); $ulOptions = $options; foreach ($this->_crumbs as $which => $crumb) { $options = array(); if (empty($crumb[1])) { $elementContent = $crumb[0]; } else { $elementContent = $this->link($crumb[0], $crumb[1], $crumb[2]); } if ($which == 0) { $options['class'] = 'first'; } elseif ($which == $crumbCount - 1) { $options['class'] = 'last'; } $result .= $this->tag('li', $elementContent, $options); } return $this->tag('ul', $result, $ulOptions); } else { return null; } } /** * Creates a formatted IMG element. If `$options['url']` is provided, an image link will be * generated with the link pointed at `$options['url']`. This method will set an empty * alt attribute if one is not supplied. * * ### Usage * * Create a regular image: * * `echo $html->image('cake_icon.png', array('alt' => 'CakePHP'));` * * Create an image link: * * `echo $html->image('cake_icon.png', array('alt' => 'CakePHP', 'url' => 'http://cakephp.org'));` * * @param string $path Path to the image file, relative to the app/webroot/img/ directory. * @param array $options Array of HTML attributes. * @return string completed img tag * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::image */ public function image($path, $options = array()) { if (is_array($path)) { $path = $this->url($path); } elseif (strpos($path, '://') === false) { if ($path[0] !== '/') { $path = IMAGES_URL . $path; } $path = $this->assetTimestamp($this->webroot($path)); } if (!isset($options['alt'])) { $options['alt'] = ''; } $url = false; if (!empty($options['url'])) { $url = $options['url']; unset($options['url']); } $image = sprintf($this->_tags['image'], $path, $this->_parseAttributes($options, null, '', ' ')); if ($url) { return sprintf($this->_tags['link'], $this->url($url), null, $image); } return $image; } /** * Returns a row of formatted and named TABLE headers. * * @param array $names Array of tablenames. * @param array $trOptions HTML options for TR elements. * @param array $thOptions HTML options for TH elements. * @return string Completed table headers * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::tableHeaders */ public function tableHeaders($names, $trOptions = null, $thOptions = null) { $out = array(); foreach ($names as $arg) { $out[] = sprintf($this->_tags['tableheader'], $this->_parseAttributes($thOptions), $arg); } return sprintf($this->_tags['tablerow'], $this->_parseAttributes($trOptions), join(' ', $out)); } /** * Returns a formatted string of table rows (TR's with TD's in them). * * @param array $data Array of table data * @param array $oddTrOptions HTML options for odd TR elements if true useCount is used * @param array $evenTrOptions HTML options for even TR elements * @param boolean $useCount adds class "column-$i" * @param boolean $continueOddEven If false, will use a non-static $count variable, * so that the odd/even count is reset to zero just for that call. * @return string Formatted HTML * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::tableCells */ public function tableCells($data, $oddTrOptions = null, $evenTrOptions = null, $useCount = false, $continueOddEven = true) { if (empty($data[0]) || !is_array($data[0])) { $data = array($data); } if ($oddTrOptions === true) { $useCount = true; $oddTrOptions = null; } if ($evenTrOptions === false) { $continueOddEven = false; $evenTrOptions = null; } if ($continueOddEven) { static $count = 0; } else { $count = 0; } foreach ($data as $line) { $count++; $cellsOut = array(); $i = 0; foreach ($line as $cell) { $cellOptions = array(); if (is_array($cell)) { $cellOptions = $cell[1]; $cell = $cell[0]; } elseif ($useCount) { $cellOptions['class'] = 'column-' . ++$i; } $cellsOut[] = sprintf($this->_tags['tablecell'], $this->_parseAttributes($cellOptions), $cell); } $options = $this->_parseAttributes($count % 2 ? $oddTrOptions : $evenTrOptions); $out[] = sprintf($this->_tags['tablerow'], $options, implode(' ', $cellsOut)); } return implode("\n", $out); } /** * Returns a formatted block tag, i.e DIV, SPAN, P. * * ### Options * * - `escape` Whether or not the contents should be html_entity escaped. * * @param string $name Tag name. * @param string $text String content that will appear inside the div element. * If null, only a start tag will be printed * @param array $options Additional HTML attributes of the DIV tag, see above. * @return string The formatted tag element * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::tag */ public function tag($name, $text = null, $options = array()) { if (is_array($options) && isset($options['escape']) && $options['escape']) { $text = h($text); unset($options['escape']); } if (!is_array($options)) { $options = array('class' => $options); } if ($text === null) { $tag = 'tagstart'; } else { $tag = 'tag'; } return sprintf($this->_tags[$tag], $name, $this->_parseAttributes($options, null, ' ', ''), $text, $name); } /** * Returns a formatted existent block of $tags * * @param string $tag Tag name * @return string Formatted block */ public function useTag($tag) { if (!isset($this->_tags[$tag])) { return ''; } $args = func_get_args(); array_shift($args); foreach ($args as &$arg) { if (is_array($arg)) { $arg = $this->_parseAttributes($arg, null, ' ', ''); } } return vsprintf($this->_tags[$tag], $args); } /** * Returns a formatted DIV tag for HTML FORMs. * * ### Options * * - `escape` Whether or not the contents should be html_entity escaped. * * @param string $class CSS class name of the div element. * @param string $text String content that will appear inside the div element. * If null, only a start tag will be printed * @param array $options Additional HTML attributes of the DIV tag * @return string The formatted DIV element * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::div */ public function div($class = null, $text = null, $options = array()) { if (!empty($class)) { $options['class'] = $class; } return $this->tag('div', $text, $options); } /** * Returns a formatted P tag. * * ### Options * * - `escape` Whether or not the contents should be html_entity escaped. * * @param string $class CSS class name of the p element. * @param string $text String content that will appear inside the p element. * @param array $options Additional HTML attributes of the P tag * @return string The formatted P element * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::para */ public function para($class, $text, $options = array()) { if (isset($options['escape'])) { $text = h($text); } if ($class != null && !empty($class)) { $options['class'] = $class; } if ($text === null) { $tag = 'parastart'; } else { $tag = 'para'; } return sprintf($this->_tags[$tag], $this->_parseAttributes($options, null, ' ', ''), $text); } /** * Build a nested list (UL/OL) out of an associative array. * * @param array $list Set of elements to list * @param array $options Additional HTML attributes of the list (ol/ul) tag or if ul/ol use that as tag * @param array $itemOptions Additional HTML attributes of the list item (LI) tag * @param string $tag Type of list tag to use (ol/ul) * @return string The nested list */ public function nestedList($list, $options = array(), $itemOptions = array(), $tag = 'ul') { if (is_string($options)) { $tag = $options; $options = array(); } $items = $this->_nestedListItem($list, $options, $itemOptions, $tag); return sprintf($this->_tags[$tag], $this->_parseAttributes($options, null, ' ', ''), $items); } /** * Internal function to build a nested list (UL/OL) out of an associative array. * * @param array $items Set of elements to list * @param array $options Additional HTML attributes of the list (ol/ul) tag * @param array $itemOptions Additional HTML attributes of the list item (LI) tag * @param string $tag Type of list tag to use (ol/ul) * @return string The nested list element * @see HtmlHelper::nestedList() */ protected function _nestedListItem($items, $options, $itemOptions, $tag) { $out = ''; $index = 1; foreach ($items as $key => $item) { if (is_array($item)) { $item = $key . $this->nestedList($item, $options, $itemOptions, $tag); } if (isset($itemOptions['even']) && $index % 2 == 0) { $itemOptions['class'] = $itemOptions['even']; } else if (isset($itemOptions['odd']) && $index % 2 != 0) { $itemOptions['class'] = $itemOptions['odd']; } $out .= sprintf($this->_tags['li'], $this->_parseAttributes($itemOptions, array('even', 'odd'), ' ', ''), $item); $index++; } return $out; } /** * Load Html tag configuration. * * Loads a file from APP/Config that contains tag data. By default the file is expected * to be compatible with PhpReader: * * `$this->Html->loadConfig('tags.php');` * * tags.php could look like: * * {{{ * $tags = array( * 'meta' => '<meta %s>' * ); * }}} * * If you wish to store tag definitions in another format you can give an array * containing the file name, and reader class name: * * `$this->Html->loadConfig(array('tags.ini', 'ini'));` * * Its expected that the `tags` index will exist from any configuration file that is read. * You can also specify the path to read the configuration file from, if APP/Config is not * where the file is. * * `$this->Html->loadConfig('tags.php', APP . 'Lib' . DS);` * * Configuration files can define the following sections: * * - `tags` The tags to replace. * - `minimizedAttributes` The attributes that are represented like `disabled="disabled"` * - `docTypes` Additional doctypes to use. * - `attributeFormat` Format for long attributes e.g. `'%s="%s"'` * - `minimizedAttributeFormat` Format for minimized attributes e.g. `'%s="%s"'` * * @param mixed $configFile String with the config file (load using PhpReader) or an array with file and reader name * @param string $path Path with config file * @return mixed False to error or loaded configs * @throws ConfigureException */ public function loadConfig($configFile, $path = null) { if (!$path) { $path = APP . 'Config' . DS; } $file = null; $reader = 'php'; if (!is_array($configFile)) { $file = $configFile; } elseif (isset($configFile[0])) { $file = $configFile[0]; if (isset($configFile[1])) { $reader = $configFile[1]; } } else { throw new ConfigureException(__d('cake_dev', 'Cannot load the configuration file. Wrong "configFile" configuration.')); } $readerClass = Inflector::camelize($reader) . 'Reader'; App::uses($readerClass, 'Configure'); if (!class_exists($readerClass)) { throw new ConfigureException(__d('cake_dev', 'Cannot load the configuration file. Unknown reader.')); } $readerObj = new $readerClass($path); $configs = $readerObj->read($file); if (isset($configs['tags']) && is_array($configs['tags'])) { $this->_tags = array_merge($this->_tags, $configs['tags']); } if (isset($configs['minimizedAttributes']) && is_array($configs['minimizedAttributes'])) { $this->_minimizedAttributes = array_merge($this->_minimizedAttributes, $configs['minimizedAttributes']); } if (isset($configs['docTypes']) && is_array($configs['docTypes'])) { $this->_docTypes = array_merge($this->_docTypes, $configs['docTypes']); } if (isset($configs['attributeFormat'])) { $this->_attributeFormat = $configs['attributeFormat']; } if (isset($configs['minimizedAttributeFormat'])) { $this->_minimizedAttributeFormat = $configs['minimizedAttributeFormat']; } return $configs; } /** * Returns a space-delimited string with items of the $options array. If a * key of $options array happens to be one of: * * - 'compact' * - 'checked' * - 'declare' * - 'readonly' * - 'disabled' * - 'selected' * - 'defer' * - 'ismap' * - 'nohref' * - 'noshade' * - 'nowrap' * - 'multiple' * - 'noresize' * * And its value is one of: * * - '1' (string) * - 1 (integer) * - true (boolean) * - 'true' (string) * * Then the value will be reset to be identical with key's name. * If the value is not one of these 3, the parameter is not output. * * 'escape' is a special option in that it controls the conversion of * attributes to their html-entity encoded equivalents. Set to false to disable html-encoding. * * If value for any option key is set to `null` or `false`, that option will be excluded from output. * * @param array $options Array of options. * @param array $exclude Array of options to be excluded, the options here will not be part of the return. * @param string $insertBefore String to be inserted before options. * @param string $insertAfter String to be inserted after options. * @return string Composed attributes. */ protected function _parseAttributes($options, $exclude = null, $insertBefore = ' ', $insertAfter = null) { if (is_array($options)) { $options = array_merge(array('escape' => true), $options); if (!is_array($exclude)) { $exclude = array(); } $filtered = array_diff_key($options, array_merge(array_flip($exclude), array('escape' => true))); $escape = $options['escape']; $attributes = array(); foreach ($filtered as $key => $value) { if ($value !== false && $value !== null) { $attributes[] = $this->_formatAttribute($key, $value, $escape); } } $out = implode(' ', $attributes); } else { $out = $options; } return $out ? $insertBefore . $out . $insertAfter : ''; } /** * Formats an individual attribute, and returns the string value of the composed attribute. * Works with minimized attributes that have the same value as their name such as 'disabled' and 'checked' * * @param string $key The name of the attribute to create * @param string $value The value of the attribute to create. * @param boolean $escape Define if the value must be escaped * @return string The composed attribute. */ protected function _formatAttribute($key, $value, $escape = true) { $attribute = ''; if (is_array($value)) { $value = ''; } if (is_numeric($key)) { $attribute = sprintf($this->_minimizedAttributeFormat, $value, $value); } elseif (in_array($key, $this->_minimizedAttributes)) { if ($value === 1 || $value === true || $value === 'true' || $value === '1' || $value == $key) { $attribute = sprintf($this->_minimizedAttributeFormat, $key, $key); } } else { $attribute = sprintf($this->_attributeFormat, $key, ($escape ? h($value) : $value)); } return $attribute; } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/HtmlHelper.php
PHP
gpl3
36,373
<?php /** * RSS Helper class file. * * Simplifies the output of RSS feeds. * * 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.View.Helper * @since CakePHP(tm) v 1.2 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AppHelper', 'View/Helper'); App::uses('Xml', 'Utility'); /** * RSS Helper class for easy output RSS structures. * * @package Cake.View.Helper * @property TimeHelper $Time * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/rss.html */ class RssHelper extends AppHelper { /** * Helpers used by RSS Helper * * @var array */ public $helpers = array('Time'); /** * Base URL * * @var string */ public $base = null; /** * URL to current action. * * @var string */ public $here = null; /** * Parameter array. * * @var array */ public $params = array(); /** * Current action. * * @var string */ public $action = null; /** * POSTed model data * * @var array */ public $data = null; /** * Name of the current model * * @var string */ public $model = null; /** * Name of the current field * * @var string */ public $field = null; /** * Default spec version of generated RSS * * @var string */ public $version = '2.0'; /** * Returns an RSS document wrapped in `<rss />` tags * * @param array $attrib `<rss />` tag attributes * @param string $content * @return string An RSS document */ public function document($attrib = array(), $content = null) { if ($content === null) { $content = $attrib; $attrib = array(); } if (!isset($attrib['version']) || empty($attrib['version'])) { $attrib['version'] = $this->version; } return $this->elem('rss', $attrib, $content); } /** * Returns an RSS `<channel />` element * * @param array $attrib `<channel />` tag attributes * @param mixed $elements Named array elements which are converted to tags * @param mixed $content Content (`<item />`'s belonging to this channel * @return string An RSS `<channel />` */ public function channel($attrib = array(), $elements = array(), $content = null) { if (!isset($elements['title']) && !empty($this->_View->pageTitle)) { $elements['title'] = $this->_View->pageTitle; } if (!isset($elements['link'])) { $elements['link'] = '/'; } if (!isset($elements['description'])) { $elements['description'] = ''; } $elements['link'] = $this->url($elements['link'], true); $elems = ''; foreach ($elements as $elem => $data) { $attributes = array(); if (is_array($data)) { if (strtolower($elem) == 'cloud') { $attributes = $data; $data = array(); } elseif (isset($data['attrib']) && is_array($data['attrib'])) { $attributes = $data['attrib']; unset($data['attrib']); } else { $innerElements = ''; foreach ($data as $subElement => $value) { $innerElements .= $this->elem($subElement, array(), $value); } $data = $innerElements; } } $elems .= $this->elem($elem, $attributes, $data); } return $this->elem('channel', $attrib, $elems . $content, !($content === null)); } /** * Transforms an array of data using an optional callback, and maps it to a set * of `<item />` tags * * @param array $items The list of items to be mapped * @param mixed $callback A string function name, or array containing an object * and a string method name * @return string A set of RSS `<item />` elements */ public function items($items, $callback = null) { if ($callback != null) { $items = array_map($callback, $items); } $out = ''; $c = count($items); for ($i = 0; $i < $c; $i++) { $out .= $this->item(array(), $items[$i]); } return $out; } /** * Converts an array into an `<item />` element and its contents * * @param array $att The attributes of the `<item />` element * @param array $elements The list of elements contained in this `<item />` * @return string An RSS `<item />` element */ public function item($att = array(), $elements = array()) { $content = null; if (isset($elements['link']) && !isset($elements['guid'])) { $elements['guid'] = $elements['link']; } foreach ($elements as $key => $val) { $attrib = array(); $escape = true; if (is_array($val) && isset($val['convertEntities'])) { $escape = $val['convertEntities']; unset($val['convertEntities']); } switch ($key) { case 'pubDate' : $val = $this->time($val); break; case 'category' : if (is_array($val) && !empty($val[0])) { foreach ($val as $category) { $attrib = array(); if (isset($category['domain'])) { $attrib['domain'] = $category['domain']; unset($category['domain']); } $categories[] = $this->elem($key, $attrib, $category); } $elements[$key] = implode('', $categories); continue 2; } else if (is_array($val) && isset($val['domain'])) { $attrib['domain'] = $val['domain']; } break; case 'link': case 'guid': case 'comments': if (is_array($val) && isset($val['url'])) { $attrib = $val; unset($attrib['url']); $val = $val['url']; } $val = $this->url($val, true); break; case 'source': if (is_array($val) && isset($val['url'])) { $attrib['url'] = $this->url($val['url'], true); $val = $val['title']; } elseif (is_array($val)) { $attrib['url'] = $this->url($val[0], true); $val = $val[1]; } break; case 'enclosure': if (is_string($val['url']) && is_file(WWW_ROOT . $val['url']) && file_exists(WWW_ROOT . $val['url'])) { if (!isset($val['length']) && strpos($val['url'], '://') === false) { $val['length'] = sprintf("%u", filesize(WWW_ROOT . $val['url'])); } if (!isset($val['type']) && function_exists('mime_content_type')) { $val['type'] = mime_content_type(WWW_ROOT . $val['url']); } } $val['url'] = $this->url($val['url'], true); $attrib = $val; $val = null; break; } if (!is_null($val) && $escape) { $val = h($val); } $elements[$key] = $this->elem($key, $attrib, $val); } if (!empty($elements)) { $content = implode('', $elements); } return $this->elem('item', (array)$att, $content, !($content === null)); } /** * Converts a time in any format to an RSS time * * @param mixed $time * @return string An RSS-formatted timestamp * @see TimeHelper::toRSS */ public function time($time) { return $this->Time->toRSS($time); } /** * Generates an XML element * * @param string $name The name of the XML element * @param array $attrib The attributes of the XML element * @param mixed $content XML element content * @param boolean $endTag Whether the end tag of the element should be printed * @return string XML */ public function elem($name, $attrib = array(), $content = null, $endTag = true) { $namespace = null; if (isset($attrib['namespace'])) { $namespace = $attrib['namespace']; unset($attrib['namespace']); } $cdata = false; if (is_array($content) && isset($content['cdata'])) { $cdata = true; unset($content['cdata']); } if (is_array($content) && array_key_exists('value', $content)) { $content = $content['value']; } $children = array(); if (is_array($content)) { $children = $content; $content = null; } $xml = '<' . $name; if (!empty($namespace)) { $xml .= ' xmlns:"' . $namespace . '"'; } $bareName = $name; if (strpos($name, ':') !== false) { list($prefix, $bareName) = explode(':', $name, 2); switch ($prefix) { case 'atom': $xml .= ' xmlns:atom="http://www.w3.org/2005/Atom"'; break; } } if ($cdata && !empty($content)) { $content = '<![CDATA[' . $content . ']]>'; } $xml .= '>' . $content . '</' . $name. '>'; $elem = Xml::build($xml, array('return' => 'domdocument')); $nodes = $elem->getElementsByTagName($bareName); foreach ($attrib as $key => $value) { $nodes->item(0)->setAttribute($key, $value); } foreach ($children as $k => $child) { $child = $elem->createElement($name, $child); $nodes->item(0)->appendChild($child); } $xml = $elem->saveXml(); $xml = trim(substr($xml, strpos($xml, '?>') + 2)); return $xml; } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/RssHelper.php
PHP
gpl3
8,660
<?php /** * jQuery Engine Helper for JsHelper * * Provides jQuery specific Javascript for JsHelper. * * Implements the JsHelper interface for jQuery. All $options arrays * support all options found in the JsHelper, as well as those in the jQuery * documentation. * * 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.View.Helper * @since CakePHP(tm) v 1.3 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AppHelper', 'View/Helper'); App::uses('JsBaseEngineHelper', 'View/Helper'); class JqueryEngineHelper extends JsBaseEngineHelper { /** * Option mappings for jQuery * * @var array */ protected $_optionMap = array( 'request' => array( 'type' => 'dataType', 'before' => 'beforeSend', 'method' => 'type', ), 'sortable' => array( 'complete' => 'stop', ), 'drag' => array( 'snapGrid' => 'grid', 'container' => 'containment', ), 'drop' => array( 'leave' => 'out', 'hover' => 'over' ), 'slider' => array( 'complete' => 'stop', 'direction' => 'orientation' ) ); /** * Callback arguments lists * * @var string */ protected $_callbackArguments = array( 'slider' => array( 'start' => 'event, ui', 'slide' => 'event, ui', 'change' => 'event, ui', 'stop' => 'event, ui' ), 'sortable' => array( 'start' => 'event, ui', 'sort' => 'event, ui', 'change' => 'event, ui', 'beforeStop' => 'event, ui', 'stop' => 'event, ui', 'update' => 'event, ui', 'receive' => 'event, ui', 'remove' => 'event, ui', 'over' => 'event, ui', 'out' => 'event, ui', 'activate' => 'event, ui', 'deactivate' => 'event, ui' ), 'drag' => array( 'start' => 'event, ui', 'drag' => 'event, ui', 'stop' => 'event, ui', ), 'drop' => array( 'activate' => 'event, ui', 'deactivate' => 'event, ui', 'over' => 'event, ui', 'out' => 'event, ui', 'drop' => 'event, ui' ), 'request' => array( 'beforeSend' => 'XMLHttpRequest', 'error' => 'XMLHttpRequest, textStatus, errorThrown', 'success' => 'data, textStatus', 'complete' => 'XMLHttpRequest, textStatus', 'xhr' => '' ) ); /** * The variable name of the jQuery Object, useful * when jQuery is put into noConflict() mode. * * @var string */ public $jQueryObject = '$'; /** * Helper function to wrap repetitive simple method templating. * * @param string $method The method name being generated. * @param string $template The method template * @param array $options Array of options for method * @param array $extraSafeKeys Extra safe keys * @return string Composed method string */ protected function _methodTemplate($method, $template, $options, $extraSafeKeys = array()) { $options = $this->_mapOptions($method, $options); $options = $this->_prepareCallbacks($method, $options); $callbacks = array_keys($this->_callbackArguments[$method]); if (!empty($extraSafeKeys)) { $callbacks = array_merge($callbacks, $extraSafeKeys); } $options = $this->_parseOptions($options, $callbacks); return sprintf($template, $this->selection, $options); } /** * Create javascript selector for a CSS rule * * @param string $selector The selector that is targeted * @return JqueryEngineHelper instance of $this. Allows chained methods. */ public function get($selector) { if ($selector == 'window' || $selector == 'document') { $this->selection = $this->jQueryObject . '(' . $selector .')'; } else { $this->selection = $this->jQueryObject . '("' . $selector . '")'; } return $this; } /** * Add an event to the script cache. Operates on the currently selected elements. * * ### Options * * - 'wrap' - Whether you want the callback wrapped in an anonymous function. (defaults true) * - 'stop' - Whether you want the event to stopped. (defaults true) * * @param string $type Type of event to bind to the current dom id * @param string $callback The Javascript function you wish to trigger or the function literal * @param array $options Options for the event. * @return string completed event handler */ public function event($type, $callback, $options = array()) { $defaults = array('wrap' => true, 'stop' => true); $options = array_merge($defaults, $options); $function = 'function (event) {%s}'; if ($options['wrap'] && $options['stop']) { $callback .= "\nreturn false;"; } if ($options['wrap']) { $callback = sprintf($function, $callback); } return sprintf('%s.bind("%s", %s);', $this->selection, $type, $callback); } /** * Create a domReady event. For jQuery. This method does not * bind a 'traditional event' as `$(document).bind('ready', fn)` * Works in an entirely different fashion than `$(document).ready()` * The first will not run the function when eval()'d as part of a response * The second will. Because of the way that ajax pagination is done * `$().ready()` is used. * * @param string $functionBody The code to run on domReady * @return string completed domReady method */ public function domReady($functionBody) { return $this->jQueryObject . '(document).ready(function () {' . $functionBody . '});'; } /** * Create an iteration over the current selection result. * * @param string $callback The function body you wish to apply during the iteration. * @return string completed iteration */ public function each($callback) { return $this->selection . '.each(function () {' . $callback . '});'; } /** * Trigger an Effect. * * @param string $name The name of the effect to trigger. * @param array $options Array of options for the effect. * @return string completed string with effect. * @see JsBaseEngineHelper::effect() */ public function effect($name, $options = array()) { $speed = null; if (isset($options['speed']) && in_array($options['speed'], array('fast', 'slow'))) { $speed = $this->value($options['speed']); } $effect = ''; switch ($name) { case 'slideIn': case 'slideOut': $name = ($name == 'slideIn') ? 'slideDown' : 'slideUp'; case 'hide': case 'show': case 'fadeIn': case 'fadeOut': case 'slideDown': case 'slideUp': $effect = ".$name($speed);"; break; } return $this->selection . $effect; } /** * Create an $.ajax() call. * * If the 'update' key is set, success callback will be overridden. * * @param mixed $url * @param array $options See JsHelper::request() for options. * @return string The completed ajax call. * @see JsBaseEngineHelper::request() for options list. */ public function request($url, $options = array()) { $url = $this->url($url); $options = $this->_mapOptions('request', $options); if (isset($options['data']) && is_array($options['data'])) { $options['data'] = $this->_toQuerystring($options['data']); } $options['url'] = $url; if (isset($options['update'])) { $wrapCallbacks = isset($options['wrapCallbacks']) ? $options['wrapCallbacks'] : true; $success = ''; if(isset($options['success']) AND !empty($options['success'])) { $success .= $options['success']; } $success .= $this->jQueryObject . '("' . $options['update'] . '").html(data);'; if (!$wrapCallbacks) { $success = 'function (data, textStatus) {' . $success . '}'; } $options['dataType'] = 'html'; $options['success'] = $success; unset($options['update']); } $callbacks = array('success', 'error', 'beforeSend', 'complete'); if (!empty($options['dataExpression'])) { $callbacks[] = 'data'; unset($options['dataExpression']); } $options = $this->_prepareCallbacks('request', $options); $options = $this->_parseOptions($options, $callbacks); return $this->jQueryObject . '.ajax({' . $options .'});'; } /** * Create a sortable element. * * Requires both Ui.Core and Ui.Sortables to be loaded. * * @param array $options Array of options for the sortable. * @return string Completed sortable script. * @see JsBaseEngineHelper::sortable() for options list. */ public function sortable($options = array()) { $template = '%s.sortable({%s});'; return $this->_methodTemplate('sortable', $template, $options); } /** * Create a Draggable element * * Requires both Ui.Core and Ui.Draggable to be loaded. * * @param array $options Array of options for the draggable element. * @return string Completed Draggable script. * @see JsBaseEngineHelper::drag() for options list. */ public function drag($options = array()) { $template = '%s.draggable({%s});'; return $this->_methodTemplate('drag', $template, $options); } /** * Create a Droppable element * * Requires both Ui.Core and Ui.Droppable to be loaded. * * @param array $options Array of options for the droppable element. * @return string Completed Droppable script. * @see JsBaseEngineHelper::drop() for options list. */ public function drop($options = array()) { $template = '%s.droppable({%s});'; return $this->_methodTemplate('drop', $template, $options); } /** * Create a Slider element * * Requires both Ui.Core and Ui.Slider to be loaded. * * @param array $options Array of options for the droppable element. * @return string Completed Slider script. * @see JsBaseEngineHelper::slider() for options list. */ public function slider($options = array()) { $callbacks = array('start', 'change', 'slide', 'stop'); $template = '%s.slider({%s});'; return $this->_methodTemplate('slider', $template, $options, $callbacks); } /** * Serialize a form attached to $selector. If the current selection is not an input or * form, errors will be created in the Javascript. * * @param array $options Options for the serialization * @return string completed form serialization script. * @see JsBaseEngineHelper::serializeForm() for option list. */ public function serializeForm($options = array()) { $options = array_merge(array('isForm' => false, 'inline' => false), $options); $selector = $this->selection; if (!$options['isForm']) { $selector = $this->selection . '.closest("form")'; } $method = '.serialize()'; if (!$options['inline']) { $method .= ';'; } return $selector . $method; } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/JqueryEngineHelper.php
PHP
gpl3
10,510
<?php /** * Automatic generation of HTML FORMs from given data. * * Used for scaffolding. * * 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.View.Helper * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AppHelper', 'View/Helper'); /** * Form helper library. * * Automatic generation of HTML FORMs from given data. * * @package Cake.View.Helper * @property HtmlHelper $Html * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html */ class FormHelper extends AppHelper { /** * Other helpers used by FormHelper * * @var array */ public $helpers = array('Html'); /** * Options used by DateTime fields * * @var array */ protected $_options = array( 'day' => array(), 'minute' => array(), 'hour' => array(), 'month' => array(), 'year' => array(), 'meridian' => array() ); /** * List of fields created, used with secure forms. * * @var array */ public $fields = array(); /** * Constant used internally to skip the securing process, * and neither add the field to the hash or to the unlocked fields. * * @var string */ const SECURE_SKIP = 'skip'; /** * Defines the type of form being created. Set by FormHelper::create(). * * @var string */ public $requestType = null; /** * The default model being used for the current form. * * @var string */ public $defaultModel = null; /** * Persistent default options used by input(). Set by FormHelper::create(). * * @var array */ protected $_inputDefaults = array(); /** * An array of fieldnames that have been excluded from * the Token hash used by SecurityComponent's validatePost method * * @see FormHelper::_secure() * @see SecurityComponent::validatePost() * @var array */ protected $_unlockedFields = array(); /** * Holds the model references already loaded by this helper * product of trying to inspect them out of field names * * @var array */ protected $_models = array(); /** * Holds all the validation errors for models loaded and inspected * it can also be set manually to be able to display custom error messages * in the any of the input fields generated by this helper * * @var array */ public $validationErrors = array(); /** * Copies the validationErrors variable from the View object into this instance * * @param View $View The View this helper is being attached to. * @param array $settings Configuration settings for the helper. */ public function __construct(View $View, $settings = array()) { parent::__construct($View, $settings); $this->validationErrors =& $View->validationErrors; } /** * Guess the location for a model based on its name and tries to create a new instance * or get an already created instance of the model * * @param string $model * @return Model model instance */ protected function _getModel($model) { $object = null; if (!$model || $model === 'Model') { return $object; } if (array_key_exists($model, $this->_models)) { return $this->_models[$model]; } if (ClassRegistry::isKeySet($model)) { $object = ClassRegistry::getObject($model); } elseif (isset($this->request->params['models'][$model])) { $plugin = $this->request->params['models'][$model]['plugin']; $plugin .= ($plugin) ? '.' : null; $object = ClassRegistry::init(array( 'class' => $plugin . $this->request->params['models'][$model]['className'], 'alias' => $model )); } else { $object = ClassRegistry::init($model, true); } $this->_models[$model] = $object; if (!$object) {; return null; } $this->fieldset[$model] = array('fields' => null, 'key' => $object->primaryKey, 'validates' => null); return $object; } /** * Inspects the model properties to extract information from them. * Currently it can extract information from the the fields, the primary key and required fields * * The $key parameter accepts the following list of values: * * - key: Returns the name of the primary key for the model * - fields: Returns the model schema * - validates: returns the list of fields that are required * - errors: returns the list of validation errors * * If the $field parameter is passed if will return the information for that sole field. * * `$this->_introspectModel('Post', 'fields', 'title');` will return the schema information for title column * * @param string $model name of the model to extract information from * @param string $key name of the special information key to obtain (key, fields, validates, errors) * @param string $field name of the model field to get information from * @return mixed information extracted for the special key and field in a model */ protected function _introspectModel($model, $key, $field = null) { $object = $this->_getModel($model); if (!$object) { return; } if ($key === 'key') { return $this->fieldset[$model]['key'] = $object->primaryKey; } if ($key === 'fields') { if (!isset($this->fieldset[$model]['fields'])) { $fields = $this->fieldset[$model]['fields'] = $object->schema(); } if (empty($field)) { foreach ($object->hasAndBelongsToMany as $alias => $assocData) { $this->fieldset[$object->alias]['fields'][$alias] = array('type' => 'multiple'); } return $this->fieldset[$model]['fields']; } elseif (isset($this->fieldset[$model]['fields'][$field])) { return $this->fieldset[$model]['fields'][$field]; } else { return isset($object->hasAndBelongsToMany[$field]) ? array('type' => 'multiple') : null; } } if ($key === 'errors' && !isset($this->validationErrors[$model])) { $this->validationErrors[$model] =& $object->validationErrors; return $this->validationErrors[$model]; } elseif ($key === 'errors' && isset($this->validationErrors[$model])) { return $this->validationErrors[$model]; } if ($key === 'validates' && !isset($this->fieldset[$model]['validates'])) { $validates = array(); if (!empty($object->validate)) { foreach ($object->validate as $validateField => $validateProperties) { if ($this->_isRequiredField($validateProperties)) { $validates[$validateField] = true; } } } $this->fieldset[$model]['validates'] = $validates; } if ($key === 'validates') { if (empty($field)) { return $this->fieldset[$model]['validates']; } else { return isset($this->fieldset[$model]['validates'][$field]) ? $this->fieldset[$model]['validates'] : null; } } } /** * Returns if a field is required to be filled based on validation properties from the validating object * * @param array $validateProperties * @return boolean true if field is required to be filled, false otherwise */ protected function _isRequiredField($validateProperties) { $required = false; if (is_array($validateProperties)) { $dims = Set::countDim($validateProperties); if ($dims == 1 || ($dims == 2 && isset($validateProperties['rule']))) { $validateProperties = array($validateProperties); } foreach ($validateProperties as $rule => $validateProp) { if (isset($validateProp['allowEmpty']) && $validateProp['allowEmpty'] === true) { return false; } $rule = isset($validateProp['rule']) ? $validateProp['rule'] : false; $required = $rule || empty($validateProp); if ($required) { break; } } } return $required; } /** * Returns false if given form field described by the current entity has no errors. * Otherwise it returns the validation message * * @return mixed Either false when there or no errors, or the error * string. The error string could be ''. */ public function tagIsInvalid() { $entity = $this->entity(); $model = array_shift($entity); $errors = array(); if (!empty($entity) && isset($this->validationErrors[$model])) { $errors = $this->validationErrors[$model]; } if (!empty($entity) && empty($errors)) { $errors = $this->_introspectModel($model, 'errors'); } if (empty($errors)) { return false; } $error = Set::classicExtract($errors, join('.', $entity)); return $error === null ? false : $error; } /** * Returns an HTML FORM element. * * ### Options: * * - `type` Form method defaults to POST * - `action` The controller action the form submits to, (optional). * - `url` The url the form submits to. Can be a string or a url array. If you use 'url' * you should leave 'action' undefined. * - `default` Allows for the creation of Ajax forms. Set this to false to prevent the default event handler. * Will create an onsubmit attribute if it doesn't not exist. If it does, default action suppression * will be appended. * - `onsubmit` Used in conjunction with 'default' to create ajax forms. * - `inputDefaults` set the default $options for FormHelper::input(). Any options that would * be set when using FormHelper::input() can be set here. Options set with `inputDefaults` * can be overridden when calling input() * - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')` * * @param string $model The model object which the form is being defined for * @param array $options An array of html attributes and options. * @return string An formatted opening FORM tag. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-create */ public function create($model = null, $options = array()) { $created = $id = false; $append = ''; if (is_array($model) && empty($options)) { $options = $model; $model = null; } if (empty($model) && $model !== false && !empty($this->request->params['models'])) { $model = key($this->request->params['models']); $this->defaultModel = $model; } elseif (empty($model) && empty($this->request->params['models'])) { $model = false; } $key = null; if ($model !== false) { $object = $this->_getModel($model); $key = $this->_introspectModel($model, 'key'); $this->setEntity($model, true); } if ($model !== false && $key) { $recordExists = ( isset($this->request->data[$model]) && !empty($this->request->data[$model][$key]) && !is_array($this->request->data[$model][$key]) ); if ($recordExists) { $created = true; $id = $this->request->data[$model][$key]; } } $options = array_merge(array( 'type' => ($created && empty($options['action'])) ? 'put' : 'post', 'action' => null, 'url' => null, 'default' => true, 'encoding' => strtolower(Configure::read('App.encoding')), 'inputDefaults' => array()), $options); $this->_inputDefaults = $options['inputDefaults']; unset($options['inputDefaults']); if (!isset($options['id'])) { $domId = isset($options['action']) ? $options['action'] : $this->request['action']; $options['id'] = $this->domId($domId . 'Form'); } if ($options['action'] === null && $options['url'] === null) { $options['action'] = $this->request->here(false); } elseif (empty($options['url']) || is_array($options['url'])) { if (empty($options['url']['controller'])) { if (!empty($model) && $model != $this->defaultModel) { $options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model)); } elseif (!empty($this->request->params['controller'])) { $options['url']['controller'] = Inflector::underscore($this->request->params['controller']); } } if (empty($options['action'])) { $options['action'] = $this->request->params['action']; } $plugin = null; if ($this->plugin) { $plugin = Inflector::underscore($this->plugin); } $actionDefaults = array( 'plugin' => $plugin, 'controller' => $this->_View->viewPath, 'action' => $options['action'], ); $options['action'] = array_merge($actionDefaults, (array)$options['url']); if (empty($options['action'][0]) && !empty($id)) { $options['action'][0] = $id; } } elseif (is_string($options['url'])) { $options['action'] = $options['url']; } unset($options['url']); switch (strtolower($options['type'])) { case 'get': $htmlAttributes['method'] = 'get'; break; case 'file': $htmlAttributes['enctype'] = 'multipart/form-data'; $options['type'] = ($created) ? 'put' : 'post'; case 'post': case 'put': case 'delete': $append .= $this->hidden('_method', array( 'name' => '_method', 'value' => strtoupper($options['type']), 'id' => null, 'secure' => self::SECURE_SKIP )); default: $htmlAttributes['method'] = 'post'; break; } $this->requestType = strtolower($options['type']); $action = $this->url($options['action']); unset($options['type'], $options['action']); if ($options['default'] == false) { if (!isset($options['onsubmit'])) { $options['onsubmit'] = ''; } $htmlAttributes['onsubmit'] = $options['onsubmit'] . 'event.returnValue = false; return false;'; } unset($options['default']); if (!empty($options['encoding'])) { $htmlAttributes['accept-charset'] = $options['encoding']; unset($options['encoding']); } $htmlAttributes = array_merge($options, $htmlAttributes); $this->fields = array(); $append .= $this->_csrfField(); if (!empty($append)) { $append = $this->Html->useTag('block', ' style="display:none;"', $append); } if ($model !== false) { $this->setEntity($model, true); } return $this->Html->useTag('form', $action, $htmlAttributes) . $append; } /** * Return a CSRF input if the _Token is present. * Used to secure forms in conjunction with SecurityComponent * * @return string */ protected function _csrfField() { if (empty($this->request->params['_Token'])) { return ''; } if (!empty($this->request['_Token']['unlockedFields'])) { foreach ((array)$this->request['_Token']['unlockedFields'] as $unlocked) { $this->_unlockedFields[] = $unlocked; } } return $this->hidden('_Token.key', array( 'value' => $this->request->params['_Token']['key'], 'id' => 'Token' . mt_rand(), 'secure' => self::SECURE_SKIP )); } /** * Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden * input fields where appropriate. * * If $options is set a form submit button will be created. Options can be either a string or an array. * * {{{ * array usage: * * array('label' => 'save'); value="save" * array('label' => 'save', 'name' => 'Whatever'); value="save" name="Whatever" * array('name' => 'Whatever'); value="Submit" name="Whatever" * array('label' => 'save', 'name' => 'Whatever', 'div' => 'good') <div class="good"> value="save" name="Whatever" * array('label' => 'save', 'name' => 'Whatever', 'div' => array('class' => 'good')); <div class="good"> value="save" name="Whatever" * }}} * * @param mixed $options as a string will use $options as the value of button, * @return string a closing FORM tag optional submit button. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#closing-the-form */ public function end($options = null) { $out = null; $submit = null; if ($options !== null) { $submitOptions = array(); if (is_string($options)) { $submit = $options; } else { if (isset($options['label'])) { $submit = $options['label']; unset($options['label']); } $submitOptions = $options; } $out .= $this->submit($submit, $submitOptions); } if (isset($this->request['_Token']) && !empty($this->request['_Token'])) { $out .= $this->secure($this->fields); $this->fields = array(); } $this->setEntity(null); $out .= $this->Html->useTag('formend'); $this->_View->modelScope = false; return $out; } /** * Generates a hidden field with a security hash based on the fields used in the form. * * @param array $fields The list of fields to use when generating the hash * @return string A hidden input field with a security hash */ public function secure($fields = array()) { if (!isset($this->request['_Token']) || empty($this->request['_Token'])) { return; } $locked = array(); $unlockedFields = $this->_unlockedFields; foreach ($fields as $key => $value) { if (!is_int($key)) { $locked[$key] = $value; unset($fields[$key]); } } sort($unlockedFields, SORT_STRING); sort($fields, SORT_STRING); ksort($locked, SORT_STRING); $fields += $locked; $locked = implode(array_keys($locked), '|'); $unlocked = implode($unlockedFields, '|'); $fields = Security::hash(serialize($fields) . $unlocked . Configure::read('Security.salt')); $out = $this->hidden('_Token.fields', array( 'value' => urlencode($fields . ':' . $locked), 'id' => 'TokenFields' . mt_rand() )); $out .= $this->hidden('_Token.unlocked', array( 'value' => urlencode($unlocked), 'id' => 'TokenUnlocked' . mt_rand() )); return $this->Html->useTag('block', ' style="display:none;"', $out); } /** * Add to or get the list of fields that are currently unlocked. * Unlocked fields are not included in the field hash used by SecurityComponent * unlocking a field once its been added to the list of secured fields will remove * it from the list of fields. * * @param string $name The dot separated name for the field. * @return mixed Either null, or the list of fields. */ public function unlockField($name = null) { if ($name === null) { return $this->_unlockedFields; } if (!in_array($name, $this->_unlockedFields)) { $this->_unlockedFields[] = $name; } $index = array_search($name, $this->fields); if ($index !== false) { unset($this->fields[$index]); } unset($this->fields[$name]); } /** * Determine which fields of a form should be used for hash. * Populates $this->fields * * @param boolean $lock Whether this field should be part of the validation * or excluded as part of the unlockedFields. * @param mixed $field Reference to field to be secured * @param mixed $value Field value, if value should not be tampered with. * @return void */ protected function _secure($lock, $field = null, $value = null) { if (!$field) { $field = $this->entity(); } elseif (is_string($field)) { $field = Set::filter(explode('.', $field), true); } foreach ($this->_unlockedFields as $unlockField) { $unlockParts = explode('.', $unlockField); if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) { return; } } $last = end($field); if (is_numeric($last) || empty($last)) { array_pop($field); } $field = implode('.', $field); if ($lock) { if (!in_array($field, $this->fields)) { if ($value !== null) { return $this->fields[$field] = $value; } $this->fields[] = $field; } } else { $this->unlockField($field); } } /** * Returns true if there is an error for the given field, otherwise false * * @param string $field This should be "Modelname.fieldname" * @return boolean If there are errors this method returns true, else false. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::isFieldError */ public function isFieldError($field) { $this->setEntity($field); return (bool)$this->tagIsInvalid(); } /** * Returns a formatted error message for given FORM field, NULL if no errors. * * ### Options: * * - `escape` bool Whether or not to html escape the contents of the error. * - `wrap` mixed Whether or not the error message should be wrapped in a div. If a * string, will be used as the HTML tag to use. * - `class` string The classname for the error message * * @param string $field A field name, like "Modelname.fieldname" * @param mixed $text Error message as string or array of messages. * If array contains `attributes` key it will be used as options for error container * @param array $options Rendering options for <div /> wrapper tag * @return string If there are errors this method returns an error message, otherwise null. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::error */ public function error($field, $text = null, $options = array()) { $defaults = array('wrap' => true, 'class' => 'error-message', 'escape' => true); $options = array_merge($defaults, $options); $this->setEntity($field); $error = $this->tagIsInvalid(); if ($error === false) { return null; } if (is_array($text)) { if (isset($text['attributes']) && is_array($text['attributes'])) { $options = array_merge($options, $text['attributes']); unset($text['attributes']); } $tmp = array(); foreach ($error as &$e) { if (isset($text[$e])) { $tmp []= $text[$e]; } else { $tmp []= $e; } } $text = $tmp; } if ($text !== null) { $error = $text; } if (is_array($error)) { foreach ($error as &$e) { if (is_numeric($e)) { $e = __('Error in field %s', Inflector::humanize($this->field())); } } } if ($options['escape']) { $error = h($error); unset($options['escape']); } if (is_array($error)) { if (count($error) > 1) { $listParams = array(); if (isset($options['listOptions'])) { if (is_string($options['listOptions'])) { $listParams []= $options['listOptions']; } else { if (isset($options['listOptions']['itemOptions'])) { $listParams []= $options['listOptions']['itemOptions']; unset($options['listOptions']['itemOptions']); } else { $listParams []= array(); } if (isset($options['listOptions']['tag'])) { $listParams []= $options['listOptions']['tag']; unset($options['listOptions']['tag']); } array_unshift($listParams, $options['listOptions']); } unset($options['listOptions']); } array_unshift($listParams, $error); $error = call_user_func_array(array($this->Html, 'nestedList'), $listParams); } else { $error = array_pop($error); } } if ($options['wrap']) { $tag = is_string($options['wrap']) ? $options['wrap'] : 'div'; unset($options['wrap']); return $this->Html->tag($tag, $error, $options); } else { return $error; } } /** * Returns a formatted LABEL element for HTML FORMs. Will automatically generate * a for attribute if one is not provided. * * @param string $fieldName This should be "Modelname.fieldname" * @param string $text Text that will appear in the label field. * @param mixed $options An array of HTML attributes, or a string, to be used as a class name. * @return string The formatted LABEL element * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::label */ public function label($fieldName = null, $text = null, $options = array()) { if (empty($fieldName)) { $fieldName = implode('.', $this->entity()); } if ($text === null) { if (strpos($fieldName, '.') !== false) { $fieldElements = explode('.', $fieldName); $text = array_pop($fieldElements); } else { $text = $fieldName; } if (substr($text, -3) == '_id') { $text = substr($text, 0, strlen($text) - 3); } $text = __(Inflector::humanize(Inflector::underscore($text))); } if (is_string($options)) { $options = array('class' => $options); } if (isset($options['for'])) { $labelFor = $options['for']; unset($options['for']); } else { $labelFor = $this->domId($fieldName); } return $this->Html->useTag('label', $labelFor, $options, $text); } /** * Generate a set of inputs for `$fields`. If $fields is null the current model * will be used. * * In addition to controller fields output, `$fields` can be used to control legend * and fieldset rendering with the `fieldset` and `legend` keys. * `$form->inputs(array('legend' => 'My legend'));` Would generate an input set with * a custom legend. You can customize individual inputs through `$fields` as well. * * {{{ * $form->inputs(array( * 'name' => array('label' => 'custom label') * )); * }}} * * In addition to fields control, inputs() allows you to use a few additional options. * * - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as * the classname for the fieldset element. * - `legend` Set to false to disable the legend for the generated input set. Or supply a string * to customize the legend text. * * @param mixed $fields An array of fields to generate inputs for, or null. * @param array $blacklist a simple array of fields to not create inputs for. * @return string Completed form inputs. */ public function inputs($fields = null, $blacklist = null) { $fieldset = $legend = true; $model = $this->model(); if (is_array($fields)) { if (array_key_exists('legend', $fields)) { $legend = $fields['legend']; unset($fields['legend']); } if (isset($fields['fieldset'])) { $fieldset = $fields['fieldset']; unset($fields['fieldset']); } } elseif ($fields !== null) { $fieldset = $legend = $fields; if (!is_bool($fieldset)) { $fieldset = true; } $fields = array(); } if (empty($fields)) { $fields = array_keys($this->_introspectModel($model, 'fields')); } if ($legend === true) { $actionName = __('New %s'); $isEdit = ( strpos($this->request->params['action'], 'update') !== false || strpos($this->request->params['action'], 'edit') !== false ); if ($isEdit) { $actionName = __('Edit %s'); } $modelName = Inflector::humanize(Inflector::underscore($model)); $legend = sprintf($actionName, __($modelName)); } $out = null; foreach ($fields as $name => $options) { if (is_numeric($name) && !is_array($options)) { $name = $options; $options = array(); } $entity = explode('.', $name); $blacklisted = ( is_array($blacklist) && (in_array($name, $blacklist) || in_array(end($entity), $blacklist)) ); if ($blacklisted) { continue; } $out .= $this->input($name, $options); } if (is_string($fieldset)) { $fieldsetClass = sprintf(' class="%s"', $fieldset); } else { $fieldsetClass = ''; } if ($fieldset && $legend) { return $this->Html->useTag('fieldset', $fieldsetClass, $this->Html->useTag('legend', $legend) . $out); } elseif ($fieldset) { return $this->Html->useTag('fieldset', $fieldsetClass, $out); } else { return $out; } } /** * Generates a form input element complete with label and wrapper div * * ### Options * * See each field type method for more information. Any options that are part of * $attributes or $options for the different **type** methods can be included in `$options` for input().i * Additionally, any unknown keys that are not in the list below, or part of the selected type's options * will be treated as a regular html attribute for the generated input. * * - `type` - Force the type of widget you want. e.g. `type => 'select'` * - `label` - Either a string label, or an array of options for the label. See FormHelper::label() * - `div` - Either `false` to disable the div, or an array of options for the div. * See HtmlHelper::div() for more options. * - `options` - for widgets that take options e.g. radio, select * - `error` - control the error message that is produced * - `empty` - String or boolean to enable empty select box options. * - `before` - Content to place before the label + input. * - `after` - Content to place after the label + input. * - `between` - Content to place between the label + input. * - `format` - format template for element order. Any element that is not in the array, will not be in the output. * - Default input format order: array('before', 'label', 'between', 'input', 'after', 'error') * - Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error') * - Hidden input will not be formatted * - Radio buttons cannot have the order of input and label elements controlled with these settings. * * @param string $fieldName This should be "Modelname.fieldname" * @param array $options Each type of input takes different options. * @return string Completed form widget. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elements */ public function input($fieldName, $options = array()) { $this->setEntity($fieldName); $options = array_merge( array('before' => null, 'between' => null, 'after' => null, 'format' => null), $this->_inputDefaults, $options ); $modelKey = $this->model(); $fieldKey = $this->field(); if (!isset($options['type'])) { $magicType = true; $options['type'] = 'text'; if (isset($options['options'])) { $options['type'] = 'select'; } elseif (in_array($fieldKey, array('psword', 'passwd', 'password'))) { $options['type'] = 'password'; } elseif (isset($options['checked'])) { $options['type'] = 'checkbox'; } elseif ($fieldDef = $this->_introspectModel($modelKey, 'fields', $fieldKey)) { $type = $fieldDef['type']; $primaryKey = $this->fieldset[$modelKey]['key']; } if (isset($type)) { $map = array( 'string' => 'text', 'datetime' => 'datetime', 'boolean' => 'checkbox', 'timestamp' => 'datetime', 'text' => 'textarea', 'time' => 'time', 'date' => 'date', 'float' => 'number', 'integer' => 'number' ); if (isset($this->map[$type])) { $options['type'] = $this->map[$type]; } elseif (isset($map[$type])) { $options['type'] = $map[$type]; } if ($fieldKey == $primaryKey) { $options['type'] = 'hidden'; } if ( $options['type'] === 'number' && $type === 'float' && !isset($options['step']) ) { $options['step'] = 'any'; } } if (preg_match('/_id$/', $fieldKey) && $options['type'] !== 'hidden') { $options['type'] = 'select'; } if ($modelKey === $fieldKey) { $options['type'] = 'select'; if (!isset($options['multiple'])) { $options['multiple'] = 'multiple'; } } } $types = array('checkbox', 'radio', 'select'); if ( (!isset($options['options']) && in_array($options['type'], $types)) || (isset($magicType) && $options['type'] == 'text') ) { $varName = Inflector::variable( Inflector::pluralize(preg_replace('/_id$/', '', $fieldKey)) ); $varOptions = $this->_View->getVar($varName); if (is_array($varOptions)) { if ($options['type'] !== 'radio') { $options['type'] = 'select'; } $options['options'] = $varOptions; } } $autoLength = (!array_key_exists('maxlength', $options) && isset($fieldDef['length'])); if ($autoLength && $options['type'] == 'text') { $options['maxlength'] = $fieldDef['length']; } if ($autoLength && $fieldDef['type'] == 'float') { $options['maxlength'] = array_sum(explode(',', $fieldDef['length']))+1; } $divOptions = array(); $div = $this->_extractOption('div', $options, true); unset($options['div']); if (!empty($div)) { $divOptions['class'] = 'input'; $divOptions = $this->addClass($divOptions, $options['type']); if (is_string($div)) { $divOptions['class'] = $div; } elseif (is_array($div)) { $divOptions = array_merge($divOptions, $div); } if ($this->_introspectModel($modelKey, 'validates', $fieldKey)) { $divOptions = $this->addClass($divOptions, 'required'); } if (!isset($divOptions['tag'])) { $divOptions['tag'] = 'div'; } } $label = null; if (isset($options['label']) && $options['type'] !== 'radio') { $label = $options['label']; unset($options['label']); } if ($options['type'] === 'radio') { $label = false; if (isset($options['options'])) { $radioOptions = (array)$options['options']; unset($options['options']); } } if ($label !== false) { $label = $this->_inputLabel($fieldName, $label, $options); } $error = $this->_extractOption('error', $options, null); unset($options['error']); $selected = $this->_extractOption('selected', $options, null); unset($options['selected']); if (isset($options['rows']) || isset($options['cols'])) { $options['type'] = 'textarea'; } if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') { $options += array('empty' => false); } if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') { $dateFormat = $this->_extractOption('dateFormat', $options, 'MDY'); $timeFormat = $this->_extractOption('timeFormat', $options, 12); unset($options['dateFormat'], $options['timeFormat']); } $type = $options['type']; $out = array_merge( array('before' => null, 'label' => null, 'between' => null, 'input' => null, 'after' => null, 'error' => null), array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after']) ); $format = null; if (is_array($options['format']) && in_array('input', $options['format'])) { $format = $options['format']; } unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']); switch ($type) { case 'hidden': $input = $this->hidden($fieldName, $options); $format = array('input'); unset($divOptions); break; case 'checkbox': $input = $this->checkbox($fieldName, $options); $format = $format ? $format : array('before', 'input', 'between', 'label', 'after', 'error'); break; case 'radio': $input = $this->radio($fieldName, $radioOptions, $options); break; case 'file': $input = $this->file($fieldName, $options); break; case 'select': $options += array('options' => array(), 'value' => $selected); $list = $options['options']; unset($options['options']); $input = $this->select($fieldName, $list, $options); break; case 'time': $options['value'] = $selected; $input = $this->dateTime($fieldName, null, $timeFormat, $options); break; case 'date': $options['value'] = $selected; $input = $this->dateTime($fieldName, $dateFormat, null, $options); break; case 'datetime': $options['value'] = $selected; $input = $this->dateTime($fieldName, $dateFormat, $timeFormat, $options); break; case 'textarea': $input = $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6')); break; case 'url': $input = $this->text($fieldName, array('type' => 'url') + $options); break; default: $input = $this->{$type}($fieldName, $options); } if ($type != 'hidden' && $error !== false) { $errMsg = $this->error($fieldName, $error); if ($errMsg) { $divOptions = $this->addClass($divOptions, 'error'); $out['error'] = $errMsg; } } $out['input'] = $input; $format = $format ? $format : array('before', 'label', 'between', 'input', 'after', 'error'); $output = ''; foreach ($format as $element) { $output .= $out[$element]; unset($out[$element]); } if (!empty($divOptions['tag'])) { $tag = $divOptions['tag']; unset($divOptions['tag']); $output = $this->Html->tag($tag, $output, $divOptions); } return $output; } /** * Extracts a single option from an options array. * * @param string $name The name of the option to pull out. * @param array $options The array of options you want to extract. * @param mixed $default The default option value * @return mixed the contents of the option or default */ protected function _extractOption($name, $options, $default = null) { if (array_key_exists($name, $options)) { return $options[$name]; } return $default; } /** * Generate a label for an input() call. * * @param string $fieldName * @param string $label * @param array $options Options for the label element. * @return string Generated label element */ protected function _inputLabel($fieldName, $label, $options) { $labelAttributes = $this->domId(array(), 'for'); if ($options['type'] === 'date' || $options['type'] === 'datetime') { if (isset($options['dateFormat']) && $options['dateFormat'] === 'NONE') { $labelAttributes['for'] .= 'Hour'; $idKey = 'hour'; } else { $labelAttributes['for'] .= 'Month'; $idKey = 'month'; } if (isset($options['id']) && isset($options['id'][$idKey])) { $labelAttributes['for'] = $options['id'][$idKey]; } } elseif ($options['type'] === 'time') { $labelAttributes['for'] .= 'Hour'; if (isset($options['id']) && isset($options['id']['hour'])) { $labelAttributes['for'] = $options['id']['hour']; } } if (is_array($label)) { $labelText = null; if (isset($label['text'])) { $labelText = $label['text']; unset($label['text']); } $labelAttributes = array_merge($labelAttributes, $label); } else { $labelText = $label; } if (isset($options['id']) && is_string($options['id'])) { $labelAttributes = array_merge($labelAttributes, array('for' => $options['id'])); } return $this->label($fieldName, $labelText, $labelAttributes); } /** * Creates a checkbox input widget. * * ### Options: * * - `value` - the value of the checkbox * - `checked` - boolean indicate that this checkbox is checked. * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include * a hidden input with a value of ''. * - `disabled` - create a disabled input. * - `default` - Set the default value for the checkbox. This allows you to start checkboxes * as checked, without having to check the POST data. A matching POST data value, will overwrite * the default value. * * @param string $fieldName Name of a field, like this "Modelname.fieldname" * @param array $options Array of HTML attributes. * @return string An HTML text input element. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs */ public function checkbox($fieldName, $options = array()) { $valueOptions = array(); if(isset($options['default'])){ $valueOptions['default'] = $options['default']; unset($options['default']); } $options = $this->_initInputField($fieldName, $options) + array('hiddenField' => true); $value = current($this->value($valueOptions)); $output = ""; if (empty($options['value'])) { $options['value'] = 1; } if ( (!isset($options['checked']) && !empty($value) && $value == $options['value']) || !empty($options['checked']) ) { $options['checked'] = 'checked'; } if ($options['hiddenField']) { $hiddenOptions = array( 'id' => $options['id'] . '_', 'name' => $options['name'], 'value' => '0', 'secure' => false ); if (isset($options['disabled']) && $options['disabled'] == true) { $hiddenOptions['disabled'] = 'disabled'; } $output = $this->hidden($fieldName, $hiddenOptions); } unset($options['hiddenField']); return $output . $this->Html->useTag('checkbox', $options['name'], array_diff_key($options, array('name' => ''))); } /** * Creates a set of radio widgets. Will create a legend and fieldset * by default. Use $options to control this * * ### Attributes: * * - `separator` - define the string in between the radio buttons * - `legend` - control whether or not the widget set has a fieldset & legend * - `value` - indicate a value that is should be checked * - `label` - boolean to indicate whether or not labels for widgets show be displayed * - `hiddenField` - boolean to indicate if you want the results of radio() to include * a hidden input with a value of ''. This is useful for creating radio sets that non-continuous * * @param string $fieldName Name of a field, like this "Modelname.fieldname" * @param array $options Radio button options array. * @param array $attributes Array of HTML attributes, and special attributes above. * @return string Completed radio widget set. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs */ public function radio($fieldName, $options = array(), $attributes = array()) { $attributes = $this->_initInputField($fieldName, $attributes); $legend = false; $disabled = array(); if (isset($attributes['legend'])) { $legend = $attributes['legend']; unset($attributes['legend']); } elseif (count($options) > 1) { $legend = __(Inflector::humanize($this->field())); } $label = true; if (isset($attributes['label'])) { $label = $attributes['label']; unset($attributes['label']); } $inbetween = null; if (isset($attributes['separator'])) { $inbetween = $attributes['separator']; unset($attributes['separator']); } if (isset($attributes['value'])) { $value = $attributes['value']; } else { $value = $this->value($fieldName); } if (isset($attributes['disabled'])) { $disabled = $attributes['disabled']; } $out = array(); $hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true; unset($attributes['hiddenField']); foreach ($options as $optValue => $optTitle) { $optionsHere = array('value' => $optValue); if (isset($value) && $optValue == $value) { $optionsHere['checked'] = 'checked'; } if (!empty($disabled) && in_array($optValue, $disabled)) { $optionsHere['disabled'] = true; } $tagName = Inflector::camelize( $attributes['id'] . '_' . Inflector::slug($optValue) ); if ($label) { $optTitle = $this->Html->useTag('label', $tagName, '', $optTitle); } $allOptions = array_merge($attributes, $optionsHere); $out[] = $this->Html->useTag('radio', $attributes['name'], $tagName, array_diff_key($allOptions, array('name' => '', 'type' => '', 'id' => '')), $optTitle ); } $hidden = null; if ($hiddenField) { if (!isset($value) || $value === '') { $hidden = $this->hidden($fieldName, array( 'id' => $attributes['id'] . '_', 'value' => '', 'name' => $attributes['name'] )); } } $out = $hidden . implode($inbetween, $out); if ($legend) { $out = $this->Html->useTag('fieldset', '', $this->Html->useTag('legend', $legend) . $out); } return $out; } /** * Missing method handler - implements various simple input types. Is used to create inputs * of various types. e.g. `$this->Form->text();` will create `<input type="text" />` while * `$this->Form->range();` will create `<input type="range" />` * * ### Usage * * `$this->Form->search('User.query', array('value' => 'test'));` * * Will make an input like: * * `<input type="search" id="UserQuery" name="data[User][query]" value="test" />` * * The first argument to an input type should always be the fieldname, in `Model.field` format. * The second argument should always be an array of attributes for the input. * * @param string $method Method name / input type to make. * @param array $params Parameters for the method call * @return string Formatted input method. * @throws CakeException When there are no params for the method call. */ public function __call($method, $params) { $options = array(); if (empty($params)) { throw new CakeException(__d('cake_dev', 'Missing field name for FormHelper::%s', $method)); } if (isset($params[1])) { $options = $params[1]; } if (!isset($options['type'])) { $options['type'] = $method; } $options = $this->_initInputField($params[0], $options); return $this->Html->useTag('input', $options['name'], array_diff_key($options, array('name' => ''))); } /** * Creates a textarea widget. * * ### Options: * * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true. * * @param string $fieldName Name of a field, in the form "Modelname.fieldname" * @param array $options Array of HTML attributes, and special options above. * @return string A generated HTML text input element * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::textarea */ public function textarea($fieldName, $options = array()) { $options = $this->_initInputField($fieldName, $options); $value = null; if (array_key_exists('value', $options)) { $value = $options['value']; if (!array_key_exists('escape', $options) || $options['escape'] !== false) { $value = h($value); } unset($options['value']); } return $this->Html->useTag('textarea', $options['name'], array_diff_key($options, array('type' => '', 'name' => '')), $value); } /** * Creates a hidden input field. * * @param string $fieldName Name of a field, in the form of "Modelname.fieldname" * @param array $options Array of HTML attributes. * @return string A generated hidden input * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hidden */ public function hidden($fieldName, $options = array()) { $secure = true; if (isset($options['secure'])) { $secure = $options['secure']; unset($options['secure']); } $options = $this->_initInputField($fieldName, array_merge( $options, array('secure' => self::SECURE_SKIP) )); if ($secure && $secure !== self::SECURE_SKIP) { $this->_secure(true, null, '' . $options['value']); } return $this->Html->useTag('hidden', $options['name'], array_diff_key($options, array('name' => ''))); } /** * Creates file input widget. * * @param string $fieldName Name of a field, in the form "Modelname.fieldname" * @param array $options Array of HTML attributes. * @return string A generated file input. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::file */ public function file($fieldName, $options = array()) { $options += array('secure' => true); $secure = $options['secure']; $options['secure'] = self::SECURE_SKIP; $options = $this->_initInputField($fieldName, $options); $field = $this->entity(); foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) { $this->_secure($secure, array_merge($field, array($suffix))); } return $this->Html->useTag('file', $options['name'], array_diff_key($options, array('name' => ''))); } /** * Creates a `<button>` tag. The type attribute defaults to `type="submit"` * You can change it to a different value by using `$options['type']`. * * ### Options: * * - `escape` - HTML entity encode the $title of the button. Defaults to false. * * @param string $title The button's caption. Not automatically HTML encoded * @param array $options Array of options and HTML attributes. * @return string A HTML button tag. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::button */ public function button($title, $options = array()) { $options += array('type' => 'submit', 'escape' => false, 'secure' => false); if ($options['escape']) { $title = h($title); } if (isset($options['name'])) { $this->_secure($options['secure'], $options['name']); } return $this->Html->useTag('button', $options['type'], array_diff_key($options, array('type' => '')), $title); } /** * Create a `<button>` tag with a surrounding `<form>` that submits via POST. * * This method creates a `<form>` element. So do not use this method in some opened form. * Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms. * * ### Options: * * - `data` - Array with key/value to pass in input hidden * - Other options is the same of button method. * * @param string $title The button's caption. Not automatically HTML encoded * @param mixed $url URL as string or array * @param array $options Array of options and HTML attributes. * @return string A HTML button tag. */ public function postButton($title, $url, $options = array()) { $out = $this->create(false, array('id' => false, 'url' => $url, 'style' => 'display:none;')); if (isset($options['data']) && is_array($options['data'])) { foreach ($options['data'] as $key => $value) { $out .= $this->hidden($key, array('value' => $value, 'id' => false)); } unset($options['data']); } $out .= $this->button($title, $options); $out .= $this->end(); return $out; } /** * Creates an HTML link, but access the url using method POST. * Requires javascript to be enabled in browser. * * This method creates a `<form>` element. So do not use this method inside an existing form. * Instead you should add a submit button using FormHelper::submit() * * ### Options: * * - `data` - Array with key/value to pass in input hidden * - `confirm` - Can be used instead of $confirmMessage. * - Other options is the same of HtmlHelper::link() method. * - The option `onclick` will be replaced. * * @param string $title The content to be wrapped by <a> tags. * @param mixed $url Cake-relative URL or array of URL parameters, or external URL (starts with http://) * @param array $options Array of HTML attributes. * @param string $confirmMessage JavaScript confirmation message. * @return string An `<a />` element. */ public function postLink($title, $url = null, $options = array(), $confirmMessage = false) { if (!empty($options['confirm'])) { $confirmMessage = $options['confirm']; unset($options['confirm']); } $formName = uniqid('post_'); $formUrl = $this->url($url); $out = $this->Html->useTag('form', $formUrl, array('name' => $formName, 'id' => $formName, 'style' => 'display:none;', 'method' => 'post')); $out .= $this->Html->useTag('hidden', '_method', ' value="POST"'); $out .= $this->_csrfField(); $fields = array(); if (isset($options['data']) && is_array($options['data'])) { foreach ($options['data'] as $key => $value) { $fields[$key] = $value; $out .= $this->hidden($key, array('value' => $value, 'id' => false)); } unset($options['data']); } $out .= $this->secure($fields); $out .= $this->Html->useTag('formend'); $url = '#'; $onClick = 'document.' . $formName . '.submit();'; if ($confirmMessage) { $confirmMessage = str_replace(array("'", '"'), array("\'", '\"'), $confirmMessage); $options['onclick'] = "if (confirm('{$confirmMessage}')) { {$onClick} }"; } else { $options['onclick'] = $onClick; } $options['onclick'] .= ' event.returnValue = false; return false;'; $out .= $this->Html->link($title, $url, $options); return $out; } /** * Creates a submit button element. This method will generate `<input />` elements that * can be used to submit, and reset forms by using $options. image submits can be created by supplying an * image path for $caption. * * ### Options * * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to * FormHelper::input(). * - `before` - Content to include before the input. * - `after` - Content to include after the input. * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit' * - Other attributes will be assigned to the input element. * * ### Options * * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to * FormHelper::input(). * - Other attributes will be assigned to the input element. * * @param string $caption The label appearing on the button OR if string contains :// or the * extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension * exists, AND the first character is /, image is relative to webroot, * OR if the first character is not /, image is relative to webroot/img. * @param array $options Array of options. See above. * @return string A HTML submit button * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::submit */ public function submit($caption = null, $options = array()) { if (!is_string($caption) && empty($caption)) { $caption = __('Submit'); } $out = null; $div = true; if (isset($options['div'])) { $div = $options['div']; unset($options['div']); } $options += array('type' => 'submit', 'before' => null, 'after' => null, 'secure' => false); $divOptions = array('tag' => 'div'); if ($div === true) { $divOptions['class'] = 'submit'; } elseif ($div === false) { unset($divOptions); } elseif (is_string($div)) { $divOptions['class'] = $div; } elseif (is_array($div)) { $divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div); } if (isset($options['name'])) { $this->_secure($options['secure'], $options['name']); } unset($options['secure']); $before = $options['before']; $after = $options['after']; unset($options['before'], $options['after']); $isUrl = strpos($caption, '://') !== false; $isImage = preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption); if ($isUrl || $isImage) { $unlockFields = array('x', 'y'); if (isset($options['name'])) { $unlockFields = array( $options['name'] . '_x', $options['name'] . '_y' ); } foreach ($unlockFields as $ignore) { $this->unlockField($ignore); } } if ($isUrl) { unset($options['type']); $tag = $this->Html->useTag('submitimage', $caption, $options); } elseif ($isImage) { unset($options['type']); if ($caption{0} !== '/') { $url = $this->webroot(IMAGES_URL . $caption); } else { $url = $this->webroot(trim($caption, '/')); } $tag = $this->Html->useTag('submitimage', $url, $options); } else { $options['value'] = $caption; $tag = $this->Html->useTag('submit', $options); } $out = $before . $tag . $after; if (isset($divOptions)) { $tag = $divOptions['tag']; unset($divOptions['tag']); $out = $this->Html->tag($tag, $out, $divOptions); } return $out; } /** * Returns a formatted SELECT element. * * ### Attributes: * * - `showParents` - If included in the array and set to true, an additional option element * will be added for the parent of each option group. You can set an option with the same name * and it's key will be used for the value of the option. * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be * created instead. * - `empty` - If true, the empty select option is shown. If a string, * that string is displayed as the empty element. * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true. * - `value` The selected value of the input. * - `class` - When using multiple = checkbox the classname to apply to the divs. Defaults to 'checkbox'. * * ### Using options * * A simple array will create normal options: * * {{{ * $options = array(1 => 'one', 2 => 'two); * $this->Form->select('Model.field', $options)); * }}} * * While a nested options array will create optgroups with options inside them. * {{{ * $options = array( * 1 => 'bill', * 'fred' => array( * 2 => 'fred', * 3 => 'fred jr.' * ) * ); * $this->Form->select('Model.field', $options); * }}} * * In the above `2 => 'fred'` will not generate an option element. You should enable the `showParents` * attribute to show the fred option. * * @param string $fieldName Name attribute of the SELECT * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the * SELECT element * @param array $attributes The HTML attributes of the select element. * @return string Formatted SELECT element * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs */ public function select($fieldName, $options = array(), $attributes = array()) { $select = array(); $style = null; $tag = null; $attributes += array( 'class' => null, 'escape' => true, 'secure' => true, 'empty' => '', 'showParents' => false, 'hiddenField' => true ); $escapeOptions = $this->_extractOption('escape', $attributes); $secure = $this->_extractOption('secure', $attributes); $showEmpty = $this->_extractOption('empty', $attributes); $showParents = $this->_extractOption('showParents', $attributes); $hiddenField = $this->_extractOption('hiddenField', $attributes); unset($attributes['escape'], $attributes['secure'], $attributes['empty'], $attributes['showParents'], $attributes['hiddenField']); $id = $this->_extractOption('id', $attributes); $attributes = $this->_initInputField($fieldName, array_merge( (array)$attributes, array('secure' => self::SECURE_SKIP) )); if (is_string($options) && isset($this->_options[$options])) { $options = $this->_generateOptions($options); } elseif (!is_array($options)) { $options = array(); } if (isset($attributes['type'])) { unset($attributes['type']); } if (!isset($selected)) { $selected = $attributes['value']; } if (!empty($attributes['multiple'])) { $style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null; $template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart'; $tag = $template; if ($hiddenField) { $hiddenAttributes = array( 'value' => '', 'id' => $attributes['id'] . ($style ? '' : '_'), 'secure' => false, 'name' => $attributes['name'] ); $select[] = $this->hidden(null, $hiddenAttributes); } } else { $tag = 'selectstart'; } if (!empty($tag) || isset($template)) { if (!isset($secure) || $secure == true) { $this->_secure(true); } $select[] = $this->Html->useTag($tag, $attributes['name'], array_diff_key($attributes, array('name' => '', 'value' => ''))); } $emptyMulti = ( $showEmpty !== null && $showEmpty !== false && !( empty($showEmpty) && (isset($attributes) && array_key_exists('multiple', $attributes)) ) ); if ($emptyMulti) { $showEmpty = ($showEmpty === true) ? '' : $showEmpty; $options = array_reverse($options, true); $options[''] = $showEmpty; $options = array_reverse($options, true); } if (!$id) { $attributes['id'] = Inflector::camelize($attributes['id']); } $select = array_merge($select, $this->_selectOptions( array_reverse($options, true), array(), $showParents, array( 'escape' => $escapeOptions, 'style' => $style, 'name' => $attributes['name'], 'value' => $attributes['value'], 'class' => $attributes['class'], 'id' => $attributes['id'] ) )); $template = ($style == 'checkbox') ? 'checkboxmultipleend' : 'selectend'; $select[] = $this->Html->useTag($template); return implode("\n", $select); } /** * Returns a SELECT element for days. * * ### Attributes: * * - `empty` - If true, the empty select option is shown. If a string, * that string is displayed as the empty element. * - `value` The selected value of the input. * * @param string $fieldName Prefix name for the SELECT element * @param array $attributes HTML attributes for the select element * @return string A generated day select box. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::day */ public function day($fieldName = null, $attributes = array()) { $attributes += array('empty' => true, 'value' => null); $attributes = $this->_dateTimeSelected('day', $fieldName, $attributes); if (strlen($attributes['value']) > 2) { $attributes['value'] = date('d', strtotime($attributes['value'])); } elseif ($attributes['value'] === false) { $attributes['value'] = null; } return $this->select($fieldName . ".day", $this->_generateOptions('day'), $attributes); } /** * Returns a SELECT element for years * * ### Attributes: * * - `empty` - If true, the empty select option is shown. If a string, * that string is displayed as the empty element. * - `orderYear` - Ordering of year values in select options. * Possible values 'asc', 'desc'. Default 'desc' * - `value` The selected value of the input. * * @param string $fieldName Prefix name for the SELECT element * @param integer $minYear First year in sequence * @param integer $maxYear Last year in sequence * @param array $attributes Attribute array for the select elements. * @return string Completed year select input * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::year */ public function year($fieldName, $minYear = null, $maxYear = null, $attributes = array()) { $attributes += array('empty' => true, 'value' => null); if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) { if (is_array($value)) { extract($value); $attributes['value'] = $year; } else { if (empty($value)) { if (!$attributes['empty'] && !$maxYear) { $attributes['value'] = 'now'; } elseif (!$attributes['empty'] && $maxYear && !$attributes['value']) { $attributes['value'] = $maxYear; } } else { $attributes['value'] = $value; } } } if (strlen($attributes['value']) > 4 || $attributes['value'] === 'now') { $attributes['value'] = date('Y', strtotime($attributes['value'])); } elseif ($attributes['value'] === false) { $attributes['value'] = null; } $yearOptions = array('min' => $minYear, 'max' => $maxYear, 'order' => 'desc'); if (isset($attributes['orderYear'])) { $yearOptions['order'] = $attributes['orderYear']; unset($attributes['orderYear']); } return $this->select( $fieldName . '.year', $this->_generateOptions('year', $yearOptions), $attributes ); } /** * Returns a SELECT element for months. * * ### Attributes: * * - `monthNames` - If false, 2 digit numbers will be used instead of text. * If a array, the given array will be used. * - `empty` - If true, the empty select option is shown. If a string, * that string is displayed as the empty element. * - `value` The selected value of the input. * * @param string $fieldName Prefix name for the SELECT element * @param array $attributes Attributes for the select element * @return string A generated month select dropdown. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::month */ public function month($fieldName, $attributes = array()) { $attributes += array('empty' => true, 'value' => null); $attributes = $this->_dateTimeSelected('month', $fieldName, $attributes); if (strlen($attributes['value']) > 2) { $attributes['value'] = date('m', strtotime($attributes['value'])); } elseif ($attributes['value'] === false) { $attributes['value'] = null; } $defaults = array('monthNames' => true); $attributes = array_merge($defaults, (array) $attributes); $monthNames = $attributes['monthNames']; unset($attributes['monthNames']); return $this->select( $fieldName . ".month", $this->_generateOptions('month', array('monthNames' => $monthNames)), $attributes ); } /** * Returns a SELECT element for hours. * * ### Attributes: * * - `empty` - If true, the empty select option is shown. If a string, * that string is displayed as the empty element. * - `value` The selected value of the input. * * @param string $fieldName Prefix name for the SELECT element * @param boolean $format24Hours True for 24 hours format * @param array $attributes List of HTML attributes * @return string Completed hour select input * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hour */ public function hour($fieldName, $format24Hours = false, $attributes = array()) { $attributes += array('empty' => true, 'value' => null); $attributes = $this->_dateTimeSelected('hour', $fieldName, $attributes); if (strlen($attributes['value']) > 2) { if ($format24Hours) { $attributes['value'] = date('H', strtotime($attributes['value'])); } else { $attributes['value'] = date('g', strtotime($attributes['value'])); } } elseif ($attributes['value'] === false) { $attributes['value'] = null; } return $this->select( $fieldName . ".hour", $this->_generateOptions($format24Hours ? 'hour24' : 'hour'), $attributes ); } /** * Returns a SELECT element for minutes. * * ### Attributes: * * - `empty` - If true, the empty select option is shown. If a string, * that string is displayed as the empty element. * - `value` The selected value of the input. * * @param string $fieldName Prefix name for the SELECT element * @param string $attributes Array of Attributes * @return string Completed minute select input. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::minute */ public function minute($fieldName, $attributes = array()) { $attributes += array('empty' => true, 'value' => null); $attributes = $this->_dateTimeSelected('min', $fieldName, $attributes); if (strlen($attributes['value']) > 2) { $attributes['value'] = date('i', strtotime($attributes['value'])); } elseif ($attributes['value'] === false) { $attributes['value'] = null; } $minuteOptions = array(); if (isset($attributes['interval'])) { $minuteOptions['interval'] = $attributes['interval']; unset($attributes['interval']); } return $this->select( $fieldName . ".min", $this->_generateOptions('minute', $minuteOptions), $attributes ); } /** * Selects values for dateTime selects. * * @param string $select Name of element field. ex. 'day' * @param string $fieldName Name of fieldName being generated ex. Model.created * @param array $attributes Array of attributes, must contain 'empty' key. * @return array Attributes array with currently selected value. */ protected function _dateTimeSelected($select, $fieldName, $attributes) { if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) { if (is_array($value) && isset($value[$select])) { $attributes['value'] = $value[$select]; } else { if (empty($value)) { if (!$attributes['empty']) { $attributes['value'] = 'now'; } } else { $attributes['value'] = $value; } } } return $attributes; } /** * Returns a SELECT element for AM or PM. * * ### Attributes: * * - `empty` - If true, the empty select option is shown. If a string, * that string is displayed as the empty element. * - `value` The selected value of the input. * * @param string $fieldName Prefix name for the SELECT element * @param string $attributes Array of Attributes * @return string Completed meridian select input * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::meridian */ public function meridian($fieldName, $attributes = array()) { $attributes += array('empty' => true, 'value' => null); if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) { if (is_array($value)) { extract($value); $attributes['value'] = $meridian; } else { if (empty($value)) { if (!$attributes['empty']) { $attributes['value'] = date('a'); } } else { $attributes['value'] = date('a', strtotime($value)); } } } if ($attributes['value'] === false) { $attributes['value'] = null; } return $this->select( $fieldName . ".meridian", $this->_generateOptions('meridian'), $attributes ); } /** * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time. * * ### Attributes: * * - `monthNames` If false, 2 digit numbers will be used instead of text. * If a array, the given array will be used. * - `minYear` The lowest year to use in the year select * - `maxYear` The maximum year to use in the year select * - `interval` The interval for the minutes select. Defaults to 1 * - `separator` The contents of the string between select elements. Defaults to '-' * - `empty` - If true, the empty select option is shown. If a string, * that string is displayed as the empty element. * - `value` | `default` The default value to be used by the input. A value in `$this->data` * matching the field name will override this value. If no default is provided `time()` will be used. * * @param string $fieldName Prefix name for the SELECT element * @param string $dateFormat DMY, MDY, YMD. * @param string $timeFormat 12, 24. * @param string $attributes array of Attributes * @return string Generated set of select boxes for the date and time formats chosen. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::dateTime */ public function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $attributes = array()) { $attributes += array('empty' => true, 'value' => null); $year = $month = $day = $hour = $min = $meridian = null; if (empty($attributes['value'])) { $attributes = $this->value($attributes, $fieldName); } if ($attributes['value'] === null && $attributes['empty'] != true) { $attributes['value'] = time(); } if (!empty($attributes['value'])) { if (is_array($attributes['value'])) { extract($attributes['value']); } else { if (is_numeric($attributes['value'])) { $attributes['value'] = strftime('%Y-%m-%d %H:%M:%S', $attributes['value']); } $meridian = 'am'; $pos = strpos($attributes['value'], '-'); if ($pos !== false) { $date = explode('-', $attributes['value']); $days = explode(' ', $date[2]); $day = $days[0]; $month = $date[1]; $year = $date[0]; } else { $days[1] = $attributes['value']; } if (!empty($timeFormat)) { $time = explode(':', $days[1]); if (($time[0] > 12) && $timeFormat == '12') { $time[0] = $time[0] - 12; $meridian = 'pm'; } elseif ($time[0] == '12' && $timeFormat == '12') { $meridian = 'pm'; } elseif ($time[0] == '00' && $timeFormat == '12') { $time[0] = 12; } elseif ($time[0] >= 12) { $meridian = 'pm'; } if ($time[0] == 0 && $timeFormat == '12') { $time[0] = 12; } $hour = $min = null; if (isset($time[1])) { $hour = $time[0]; $min = $time[1]; } } } } $elements = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian'); $defaults = array( 'minYear' => null, 'maxYear' => null, 'separator' => '-', 'interval' => 1, 'monthNames' => true ); $attributes = array_merge($defaults, (array) $attributes); if (isset($attributes['minuteInterval'])) { $attributes['interval'] = $attributes['minuteInterval']; unset($attributes['minuteInterval']); } $minYear = $attributes['minYear']; $maxYear = $attributes['maxYear']; $separator = $attributes['separator']; $interval = $attributes['interval']; $monthNames = $attributes['monthNames']; $attributes = array_diff_key($attributes, $defaults); if (isset($attributes['id'])) { if (is_string($attributes['id'])) { // build out an array version foreach ($elements as $element) { $selectAttrName = 'select' . $element . 'Attr'; ${$selectAttrName} = $attributes; ${$selectAttrName}['id'] = $attributes['id'] . $element; } } elseif (is_array($attributes['id'])) { // check for missing ones and build selectAttr for each element $attributes['id'] += array( 'month' => '', 'year' => '', 'day' => '', 'hour' => '', 'minute' => '', 'meridian' => '' ); foreach ($elements as $element) { $selectAttrName = 'select' . $element . 'Attr'; ${$selectAttrName} = $attributes; ${$selectAttrName}['id'] = $attributes['id'][strtolower($element)]; } } } else { // build the selectAttrName with empty id's to pass foreach ($elements as $element) { $selectAttrName = 'select' . $element . 'Attr'; ${$selectAttrName} = $attributes; } } $selects = array(); foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) { switch ($char) { case 'Y': $selectYearAttr['value'] = $year; $selects[] = $this->year( $fieldName, $minYear, $maxYear, $selectYearAttr ); break; case 'M': $selectMonthAttr['value'] = $month; $selectMonthAttr['monthNames'] = $monthNames; $selects[] = $this->month($fieldName, $selectMonthAttr); break; case 'D': $selectDayAttr['value'] = $day; $selects[] = $this->day($fieldName, $selectDayAttr); break; } } $opt = implode($separator, $selects); if (!empty($interval) && $interval > 1 && !empty($min)) { $min = round($min * (1 / $interval)) * $interval; } $selectMinuteAttr['interval'] = $interval; switch ($timeFormat) { case '24': $selectHourAttr['value'] = $hour; $selectMinuteAttr['value'] = $min; $opt .= $this->hour($fieldName, true, $selectHourAttr) . ':' . $this->minute($fieldName, $selectMinuteAttr); break; case '12': $selectHourAttr['value'] = $hour; $selectMinuteAttr['value'] = $min; $selectMeridianAttr['value'] = $meridian; $opt .= $this->hour($fieldName, false, $selectHourAttr) . ':' . $this->minute($fieldName, $selectMinuteAttr) . ' ' . $this->meridian($fieldName, $selectMeridianAttr); break; default: $opt .= ''; break; } return $opt; } /** * Add support for special HABTM syntax. * * Sets this helper's model and field properties to the dot-separated value-pair in $entity. * * @param mixed $entity A field name, like "ModelName.fieldName" or "ModelName.ID.fieldName" * @param boolean $setScope Sets the view scope to the model specified in $tagValue * @return void */ public function setEntity($entity, $setScope = false) { parent::setEntity($entity, $setScope); $parts = explode('.', $entity); $field = $this->_introspectModel($this->_modelScope, 'fields', $parts[0]); if (!empty($field) && $field['type'] === 'multiple') { $this->_entityPath = $parts[0] . '.' . $parts[0]; } } /** * Gets the input field name for the current tag * * @param array $options * @param string $field * @param string $key * @return array */ protected function _name($options = array(), $field = null, $key = 'name') { if ($this->requestType == 'get') { if ($options === null) { $options = array(); } elseif (is_string($options)) { $field = $options; $options = 0; } if (!empty($field)) { $this->setEntity($field); } if (is_array($options) && isset($options[$key])) { return $options; } $entity = $this->entity(); $model = $this->model(); $name = $model === $entity[0] && isset($entity[1]) ? $entity[1] : $entity[0]; $last = $entity[count($entity) - 1]; if (in_array($last, $this->_fieldSuffixes)) { $name .= '[' . $last . ']'; } if (is_array($options)) { $options[$key] = $name; return $options; } else { return $name; } } return parent::_name($options, $field, $key); } /** * Returns an array of formatted OPTION/OPTGROUP elements * * @param array $elements * @param array $parents * @param boolean $showParents * @param array $attributes * @return array */ protected function _selectOptions($elements = array(), $parents = array(), $showParents = null, $attributes = array()) { $select = array(); $attributes = array_merge( array('escape' => true, 'style' => null, 'value' => null, 'class' => null), $attributes ); $selectedIsEmpty = ($attributes['value'] === '' || $attributes['value'] === null); $selectedIsArray = is_array($attributes['value']); foreach ($elements as $name => $title) { $htmlOptions = array(); if (is_array($title) && (!isset($title['name']) || !isset($title['value']))) { if (!empty($name)) { if ($attributes['style'] === 'checkbox') { $select[] = $this->Html->useTag('fieldsetend'); } else { $select[] = $this->Html->useTag('optiongroupend'); } $parents[] = $name; } $select = array_merge($select, $this->_selectOptions( $title, $parents, $showParents, $attributes )); if (!empty($name)) { $name = $attributes['escape'] ? h($name) : $name; if ($attributes['style'] === 'checkbox') { $select[] = $this->Html->useTag('fieldsetstart', $name); } else { $select[] = $this->Html->useTag('optiongroup', $name, ''); } } $name = null; } elseif (is_array($title)) { $htmlOptions = $title; $name = $title['value']; $title = $title['name']; unset($htmlOptions['name'], $htmlOptions['value']); } if ($name !== null) { if ( (!$selectedIsArray && !$selectedIsEmpty && (string)$attributes['value'] == (string)$name) || ($selectedIsArray && in_array($name, $attributes['value'])) ) { if ($attributes['style'] === 'checkbox') { $htmlOptions['checked'] = true; } else { $htmlOptions['selected'] = 'selected'; } } if ($showParents || (!in_array($title, $parents))) { $title = ($attributes['escape']) ? h($title) : $title; if ($attributes['style'] === 'checkbox') { $htmlOptions['value'] = $name; $tagName = $attributes['id'] . Inflector::camelize(Inflector::slug($name)); $htmlOptions['id'] = $tagName; $label = array('for' => $tagName); if (isset($htmlOptions['checked']) && $htmlOptions['checked'] === true) { $label['class'] = 'selected'; } $name = $attributes['name']; if (empty($attributes['class'])) { $attributes['class'] = 'checkbox'; } elseif ($attributes['class'] === 'form-error') { $attributes['class'] = 'checkbox ' . $attributes['class']; } $label = $this->label(null, $title, $label); $item = $this->Html->useTag('checkboxmultiple', $name, $htmlOptions); $select[] = $this->Html->div($attributes['class'], $item . $label); } else { $select[] = $this->Html->useTag('selectoption', $name, $htmlOptions, $title); } } } } return array_reverse($select, true); } /** * Generates option lists for common <select /> menus * * @param string $name * @param array $options * @return array */ protected function _generateOptions($name, $options = array()) { if (!empty($this->options[$name])) { return $this->options[$name]; } $data = array(); switch ($name) { case 'minute': if (isset($options['interval'])) { $interval = $options['interval']; } else { $interval = 1; } $i = 0; while ($i < 60) { $data[sprintf('%02d', $i)] = sprintf('%02d', $i); $i += $interval; } break; case 'hour': for ($i = 1; $i <= 12; $i++) { $data[sprintf('%02d', $i)] = $i; } break; case 'hour24': for ($i = 0; $i <= 23; $i++) { $data[sprintf('%02d', $i)] = $i; } break; case 'meridian': $data = array('am' => 'am', 'pm' => 'pm'); break; case 'day': $min = 1; $max = 31; if (isset($options['min'])) { $min = $options['min']; } if (isset($options['max'])) { $max = $options['max']; } for ($i = $min; $i <= $max; $i++) { $data[sprintf('%02d', $i)] = $i; } break; case 'month': if ($options['monthNames'] === true) { $data['01'] = __('January'); $data['02'] = __('February'); $data['03'] = __('March'); $data['04'] = __('April'); $data['05'] = __('May'); $data['06'] = __('June'); $data['07'] = __('July'); $data['08'] = __('August'); $data['09'] = __('September'); $data['10'] = __('October'); $data['11'] = __('November'); $data['12'] = __('December'); } else if (is_array($options['monthNames'])) { $data = $options['monthNames']; } else { for ($m = 1; $m <= 12; $m++) { $data[sprintf("%02s", $m)] = strftime("%m", mktime(1, 1, 1, $m, 1, 1999)); } } break; case 'year': $current = intval(date('Y')); if (!isset($options['min'])) { $min = $current - 20; } else { $min = $options['min']; } if (!isset($options['max'])) { $max = $current + 20; } else { $max = $options['max']; } if ($min > $max) { list($min, $max) = array($max, $min); } for ($i = $min; $i <= $max; $i++) { $data[$i] = $i; } if ($options['order'] != 'asc') { $data = array_reverse($data, true); } break; } $this->_options[$name] = $data; return $this->_options[$name]; } /** * Sets field defaults and adds field to form security input hash * * ### Options * * - `secure` - boolean whether or not the field should be added to the security fields. * * @param string $field Name of the field to initialize options for. * @param array $options Array of options to append options into. * @return array Array of options for the input. */ protected function _initInputField($field, $options = array()) { if (isset($options['secure'])) { $secure = $options['secure']; unset($options['secure']); } else { $secure = (isset($this->request['_Token']) && !empty($this->request['_Token'])); } $result = parent::_initInputField($field, $options); if ($secure === self::SECURE_SKIP) { return $result; } $fieldName = null; if (!empty($options['name'])) { preg_match_all('/\[(.*?)\]/', $options['name'], $matches); if (isset($matches[1])) { $fieldName = $matches[1]; } } $this->_secure($secure, $fieldName); return $result; } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/FormHelper.php
PHP
gpl3
81,393
<?php /** * Javascript Generator class file. * * PHP 5 * * CakePHP : 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.View.Helper * @since CakePHP(tm) v 1.2 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AppHelper', 'View/Helper'); App::uses('JsBaseEngineHelper', 'View/Helper'); App::uses('Multibyte', 'I18n'); /** * Javascript Generator helper class for easy use of JavaScript. * * JsHelper provides an abstract interface for authoring JavaScript with a * given client-side library. * * @package Cake.View.Helper * @property HtmlHelper $Html * @property FormHelper $Form */ class JsHelper extends AppHelper { /** * Whether or not you want scripts to be buffered or output. * * @var boolean */ public $bufferScripts = true; /** * Helper dependencies * * @var array */ public $helpers = array('Html', 'Form'); /** * Variables to pass to Javascript. * * @var array * @see JsHelper::set() */ protected $_jsVars = array(); /** * Scripts that are queued for output * * @var array * @see JsHelper::buffer() */ protected $_bufferedScripts = array(); /** * Current Javascript Engine that is being used * * @var string */ protected $_engineName; /** * The javascript variable created by set() variables. * * @var string */ public $setVariable = 'app'; /** * Constructor - determines engine helper * * @param View $View the view object the helper is attached to. * @param array $settings Settings array contains name of engine helper. */ public function __construct(View $View, $settings = array()) { $className = 'Jquery'; if (is_array($settings) && isset($settings[0])) { $className = $settings[0]; } elseif (is_string($settings)) { $className = $settings; } $engineName = $className; list($plugin, $className) = pluginSplit($className); $this->_engineName = $className . 'Engine'; $engineClass = $engineName . 'Engine'; $this->helpers[] = $engineClass; parent::__construct($View, $settings); } /** * call__ Allows for dispatching of methods to the Engine Helper. * methods in the Engines bufferedMethods list will be automatically buffered. * You can control buffering with the buffer param as well. By setting the last parameter to * any engine method to a boolean you can force or disable buffering. * * e.g. `$js->get('#foo')->effect('fadeIn', array('speed' => 'slow'), true);` * * Will force buffering for the effect method. If the method takes an options array you may also add * a 'buffer' param to the options array and control buffering there as well. * * e.g. `$js->get('#foo')->event('click', $functionContents, array('buffer' => true));` * * The buffer parameter will not be passed onto the EngineHelper. * * @param string $method Method to be called * @param array $params Parameters for the method being called. * @return mixed Depends on the return of the dispatched method, or it could be an instance of the EngineHelper */ public function __call($method, $params) { if ($this->{$this->_engineName} && method_exists($this->{$this->_engineName}, $method)) { $buffer = false; $engineHelper = $this->{$this->_engineName}; if (in_array(strtolower($method), $engineHelper->bufferedMethods)) { $buffer = true; } if (count($params) > 0) { $lastParam = $params[count($params) - 1]; $hasBufferParam = (is_bool($lastParam) || is_array($lastParam) && isset($lastParam['buffer'])); if ($hasBufferParam && is_bool($lastParam)) { $buffer = $lastParam; unset($params[count($params) - 1]); } elseif ($hasBufferParam && is_array($lastParam)) { $buffer = $lastParam['buffer']; unset($params['buffer']); } } $out = call_user_func_array(array(&$engineHelper, $method), $params); if ($this->bufferScripts && $buffer && is_string($out)) { $this->buffer($out); return null; } if (is_object($out) && is_a($out, 'JsBaseEngineHelper')) { return $this; } return $out; } if (method_exists($this, $method . '_')) { return call_user_func(array(&$this, $method . '_'), $params); } trigger_error(__d('cake_dev', 'JsHelper:: Missing Method %s is undefined', $method), E_USER_WARNING); } /** * Overwrite inherited Helper::value() * See JsBaseEngineHelper::value() for more information on this method. * * @param mixed $val A PHP variable to be converted to JSON * @param boolean $quoteString If false, leaves string values unquoted * @return string a JavaScript-safe/JSON representation of $val **/ public function value($val, $quoteString = true) { return $this->{$this->_engineName}->value($val, $quoteString); } /** * Writes all Javascript generated so far to a code block or * caches them to a file and returns a linked script. If no scripts have been * buffered this method will return null. If the request is an XHR(ajax) request * onDomReady will be set to false. As the dom is already 'ready'. * * ### Options * * - `inline` - Set to true to have scripts output as a script block inline * if `cache` is also true, a script link tag will be generated. (default true) * - `cache` - Set to true to have scripts cached to a file and linked in (default false) * - `clear` - Set to false to prevent script cache from being cleared (default true) * - `onDomReady` - wrap cached scripts in domready event (default true) * - `safe` - if an inline block is generated should it be wrapped in <![CDATA[ ... ]]> (default true) * * @param array $options options for the code block * @return mixed Completed javascript tag if there are scripts, if there are no buffered * scripts null will be returned. */ public function writeBuffer($options = array()) { $domReady = $this->request->is('ajax'); $defaults = array( 'onDomReady' => $domReady, 'inline' => true, 'cache' => false, 'clear' => true, 'safe' => true ); $options = array_merge($defaults, $options); $script = implode("\n", $this->getBuffer($options['clear'])); if (empty($script)) { return null; } if ($options['onDomReady']) { $script = $this->{$this->_engineName}->domReady($script); } $opts = $options; unset($opts['onDomReady'], $opts['cache'], $opts['clear']); if (!$options['cache'] && $options['inline']) { return $this->Html->scriptBlock($script, $opts); } if ($options['cache'] && $options['inline']) { $filename = md5($script); if (!file_exists(JS . $filename . '.js')) { cache(str_replace(WWW_ROOT, '', JS) . $filename . '.js', $script, '+999 days', 'public'); } return $this->Html->script($filename); } $this->Html->scriptBlock($script, $opts); return null; } /** * Write a script to the buffered scripts. * * @param string $script Script string to add to the buffer. * @param boolean $top If true the script will be added to the top of the * buffered scripts array. If false the bottom. * @return void */ public function buffer($script, $top = false) { if ($top) { array_unshift($this->_bufferedScripts, $script); } else { $this->_bufferedScripts[] = $script; } } /** * Get all the buffered scripts * * @param boolean $clear Whether or not to clear the script caches (default true) * @return array Array of scripts added to the request. */ public function getBuffer($clear = true) { $this->_createVars(); $scripts = $this->_bufferedScripts; if ($clear) { $this->_bufferedScripts = array(); $this->_jsVars = array(); } return $scripts; } /** * Generates the object string for variables passed to javascript. * * @return string Generated JSON object of all set vars */ protected function _createVars() { if (!empty($this->_jsVars)) { $setVar = (strpos($this->setVariable, '.')) ? $this->setVariable : 'window.' . $this->setVariable; $this->buffer($setVar . ' = ' . $this->object($this->_jsVars) . ';', true); } } /** * Generate an 'Ajax' link. Uses the selected JS engine to create a link * element that is enhanced with Javascript. Options can include * both those for HtmlHelper::link() and JsBaseEngine::request(), JsBaseEngine::event(); * * ### Options * * - `confirm` - Generate a confirm() dialog before sending the event. * - `id` - use a custom id. * - `htmlAttributes` - additional non-standard htmlAttributes. Standard attributes are class, id, * rel, title, escape, onblur and onfocus. * - `buffer` - Disable the buffering and return a script tag in addition to the link. * * @param string $title Title for the link. * @param mixed $url Mixed either a string URL or an cake url array. * @param array $options Options for both the HTML element and Js::request() * @return string Completed link. If buffering is disabled a script tag will be returned as well. */ public function link($title, $url = null, $options = array()) { if (!isset($options['id'])) { $options['id'] = 'link-' . intval(mt_rand()); } list($options, $htmlOptions) = $this->_getHtmlOptions($options); $out = $this->Html->link($title, $url, $htmlOptions); $this->get('#' . $htmlOptions['id']); $requestString = $event = ''; if (isset($options['confirm'])) { $requestString = $this->confirmReturn($options['confirm']); unset($options['confirm']); } $buffer = isset($options['buffer']) ? $options['buffer'] : null; $safe = isset($options['safe']) ? $options['safe'] : true; unset($options['buffer'], $options['safe']); $requestString .= $this->request($url, $options); if (!empty($requestString)) { $event = $this->event('click', $requestString, $options + array('buffer' => $buffer)); } if (isset($buffer) && !$buffer) { $opts = array('safe' => $safe); $out .= $this->Html->scriptBlock($event, $opts); } return $out; } /** * Pass variables into Javascript. Allows you to set variables that will be * output when the buffer is fetched with `JsHelper::getBuffer()` or `JsHelper::writeBuffer()` * The Javascript variable used to output set variables can be controlled with `JsHelper::$setVariable` * * @param mixed $one Either an array of variables to set, or the name of the variable to set. * @param mixed $two If $one is a string, $two is the value for that key. * @return void */ public function set($one, $two = null) { $data = 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->_jsVars = array_merge($this->_jsVars, $data); } /** * Uses the selected JS engine to create a submit input * element that is enhanced with Javascript. Options can include * both those for FormHelper::submit() and JsBaseEngine::request(), JsBaseEngine::event(); * * Forms submitting with this method, cannot send files. Files do not transfer over XmlHttpRequest * and require an iframe or flash. * * ### Options * * - `url` The url you wish the XHR request to submit to. * - `confirm` A string to use for a confirm() message prior to submitting the request. * - `method` The method you wish the form to send by, defaults to POST * - `buffer` Whether or not you wish the script code to be buffered, defaults to true. * - Also see options for JsHelper::request() and JsHelper::event() * * @param string $caption The display text of the submit button. * @param array $options Array of options to use. See the options for the above mentioned methods. * @return string Completed submit button. */ public function submit($caption = null, $options = array()) { if (!isset($options['id'])) { $options['id'] = 'submit-' . intval(mt_rand()); } $formOptions = array('div'); list($options, $htmlOptions) = $this->_getHtmlOptions($options, $formOptions); $out = $this->Form->submit($caption, $htmlOptions); $this->get('#' . $htmlOptions['id']); $options['data'] = $this->serializeForm(array('isForm' => false, 'inline' => true)); $requestString = $url = ''; if (isset($options['confirm'])) { $requestString = $this->confirmReturn($options['confirm']); unset($options['confirm']); } if (isset($options['url'])) { $url = $options['url']; unset($options['url']); } if (!isset($options['method'])) { $options['method'] = 'post'; } $options['dataExpression'] = true; $buffer = isset($options['buffer']) ? $options['buffer'] : null; $safe = isset($options['safe']) ? $options['safe'] : true; unset($options['buffer'], $options['safe']); $requestString .= $this->request($url, $options); if (!empty($requestString)) { $event = $this->event('click', $requestString, $options + array('buffer' => $buffer)); } if (isset($buffer) && !$buffer) { $opts = array('safe' => $safe); $out .= $this->Html->scriptBlock($event, $opts); } return $out; } /** * Parse a set of Options and extract the Html options. * Extracted Html Options are removed from the $options param. * * @param array $options Options to filter. * @param array $additional Array of additional keys to extract and include in the return options array. * @return array Array of js options and Htmloptions */ protected function _getHtmlOptions($options, $additional = array()) { $htmlKeys = array_merge( array('class', 'id', 'escape', 'onblur', 'onfocus', 'rel', 'title', 'style'), $additional ); $htmlOptions = array(); foreach ($htmlKeys as $key) { if (isset($options[$key])) { $htmlOptions[$key] = $options[$key]; } unset($options[$key]); } if (isset($options['htmlAttributes'])) { $htmlOptions = array_merge($htmlOptions, $options['htmlAttributes']); unset($options['htmlAttributes']); } return array($options, $htmlOptions); } }
0001-bee
trunk/cakephp2/lib/Cake/View/Helper/JsHelper.php
PHP
gpl3
14,095
<?php /** * Methods to display or download any type of 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.View * @since CakePHP(tm) v 1.2.0.5714 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('View', 'View'); App::uses('CakeRequest', 'Network'); /** * Media View provides a custom view implementation for sending files to visitors. Its great * for making the response of a controller action be a file that is saved somewhere on the filesystem. * * An example use comes from the CakePHP internals. MediaView is used to serve plugin and theme assets, * as they are not normally accessible from an application's webroot. Unlike other views, MediaView * uses several viewVars that have special meaning: * * - `id` The filename on the server's filesystem, including extension. * - `name` The filename that will be sent to the user, specified without the extension. * - `download` Set to true to set a `Content-Disposition` header. This is ideal for file downloads. * - `extension` The extension of the file being served. This is used to set the mimetype * - `path` The absolute path, including the trailing / on the server's filesystem to `id`. * - `mimeType` The mime type of the file if CakeResponse doesn't know about it. * * ### Usage * * {{{ * class ExampleController extends AppController { * public function download () { * $this->viewClass = 'Media'; * $params = array( * 'id' => 'example.zip', * 'name' => 'example', * 'download' => true, * 'extension' => 'zip', * 'path' => APP . 'files' . DS * ); * $this->set($params); * } * } * }}} * * @package Cake.View */ class MediaView extends View { /** * Indicates whether response gzip compression was enabled for this class * * @var boolean */ protected $_compressionEnabled = false; /** * Reference to the Response object responsible for sending the headers * * @var CakeResponse */ public $response = null; /** * Constructor * * @param Controller $controller The controller with viewVars */ public function __construct($controller = null) { parent::__construct($controller); if (is_object($controller) && isset($controller->response)) { $this->response = $controller->response; } else { $this->response = new CakeResponse; } } /** * Display or download the given file * * @param string $view Not used * @param string $layout Not used * @return mixed * @throws NotFoundException */ public function render($view = null, $layout = null) { $name = $download = $extension = $id = $modified = $path = $cache = $mimeType = $compress = null; extract($this->viewVars, EXTR_OVERWRITE); if (is_dir($path)) { $path = $path . $id; } else { $path = APP . $path . $id; } if (!is_file($path)) { if (Configure::read('debug')) { throw new NotFoundException(sprintf('The requested file %s was not found', $path)); } throw new NotFoundException('The requested file was not found'); } if (is_array($mimeType)) { $this->response->type($mimeType); } if (isset($extension) && $this->_isActive()) { $extension = strtolower($extension); $chunkSize = 8192; $buffer = ''; $fileSize = @filesize($path); $handle = fopen($path, 'rb'); if ($handle === false) { return false; } if (!empty($modified) && !is_numeric($modified)) { $modified = strtotime($modified, time()); } else { $modified = time(); } if ($this->response->type($extension) === false) { $download = true; } if ($cache) { $this->response->cache($modified, $cache); } else { $this->response->header(array( 'Date' => gmdate('D, d M Y H:i:s', time()) . ' GMT', 'Expires' => '0', 'Cache-Control' => 'private, must-revalidate, post-check=0, pre-check=0', 'Pragma' => 'no-cache' )); } if ($download) { $agent = env('HTTP_USER_AGENT'); if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent)) { $contentType = 'application/octetstream'; } else if (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) { $contentType = 'application/force-download'; } if (!empty($contentType)) { $this->response->type($contentType); } if (is_null($name)) { $name = $id; } $this->response->download($name); $this->response->header(array('Accept-Ranges' => 'bytes')); $httpRange = env('HTTP_RANGE'); if (isset($httpRange)) { list($toss, $range) = explode('=', $httpRange); $size = $fileSize - 1; $length = $fileSize - $range; $this->response->header(array( 'Content-Length' => $length, 'Content-Range' => 'bytes ' . $range . $size . '/' . $fileSize )); $this->response->statusCode(206); fseek($handle, $range); } else { $this->response->header('Content-Length', $fileSize); } } else { $this->response->header(array( 'Content-Length' => $fileSize )); } $this->_clearBuffer(); if ($compress) { $this->_compressionEnabled = $this->response->compress(); } $this->response->send(); return $this->_sendFile($handle); } return false; } /** * Reads out a file handle, and echos the content to the client. * * @param resource $handle A file handle or stream * @return void */ protected function _sendFile($handle) { $chunkSize = 8192; $buffer = ''; while (!feof($handle)) { if (!$this->_isActive()) { fclose($handle); return false; } set_time_limit(0); $buffer = fread($handle, $chunkSize); echo $buffer; if (!$this->_compressionEnabled) { $this->_flushBuffer(); } } fclose($handle); } /** * Returns true if connection is still active * * @return boolean */ protected function _isActive() { return connection_status() == 0 && !connection_aborted(); } /** * Clears the contents of the topmost output buffer and discards them * * @return boolean */ protected function _clearBuffer() { return @ob_end_clean(); } /** * Flushes the contents of the output buffer * * @return void */ protected function _flushBuffer() { @flush(); @ob_flush(); } }
0001-bee
trunk/cakephp2/lib/Cake/View/MediaView.php
PHP
gpl3
6,565
<?php /** * Library of array functions for 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 Cake.Utility * @since CakePHP(tm) v 1.2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('String', 'Utility'); /** * Class used for manipulation of arrays. * * @package Cake.Utility */ class Set { /** * This function can be thought of as a hybrid between PHP's array_merge and array_merge_recursive. The difference * to the two is that if an array key contains another array then the function behaves recursive (unlike array_merge) * but does not do if for keys containing strings (unlike array_merge_recursive). * See the unit test for more information. * * Note: This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays. * * @param array $arr1 Array to be merged * @param array $arr2 Array to merge with * @return array Merged array */ public static function merge($arr1, $arr2 = null) { $args = func_get_args(); $r = (array)current($args); while (($arg = next($args)) !== false) { foreach ((array)$arg as $key => $val) { if (!empty($r[$key]) && is_array($r[$key]) && is_array($val)) { $r[$key] = Set::merge($r[$key], $val); } elseif (is_int($key)) { $r[] = $val; } else { $r[$key] = $val; } } } return $r; } /** * Filters empty elements out of a route array, excluding '0'. * * @param array $var Either an array to filter, or value when in callback * @return mixed Either filtered array, or true/false when in callback */ public static function filter(array $var) { foreach ($var as $k => $v) { if (is_array($v)) { $var[$k] = Set::filter($v); } } return array_filter($var, array('Set', '_filter')); } /** * Set::filter callback function * * @param array $var Array to filter. * @return boolean */ protected static function _filter($var) { if ($var === 0 || $var === '0' || !empty($var)) { return true; } return false; } /** * Pushes the differences in $array2 onto the end of $array * * @param mixed $array Original array * @param mixed $array2 Differences to push * @return array Combined array */ public static function pushDiff($array, $array2) { if (empty($array) && !empty($array2)) { return $array2; } if (!empty($array) && !empty($array2)) { foreach ($array2 as $key => $value) { if (!array_key_exists($key, $array)) { $array[$key] = $value; } else { if (is_array($value)) { $array[$key] = Set::pushDiff($array[$key], $array2[$key]); } } } } return $array; } /** * Maps the contents of the Set object to an object hierarchy. * Maintains numeric keys as arrays of objects * * @param string $class A class name of the type of object to map to * @param string $tmp A temporary class name used as $class if $class is an array * @return object Hierarchical object */ public static function map($class = 'stdClass', $tmp = 'stdClass') { if (is_array($class)) { $val = $class; $class = $tmp; } if (empty($val)) { return null; } return Set::_map($val, $class); } /** * Maps the given value as an object. If $value is an object, * it returns $value. Otherwise it maps $value as an object of * type $class, and if primary assign _name_ $key on first array. * If $value is not empty, it will be used to set properties of * returned object (recursively). If $key is numeric will maintain array * structure * * @param array $array Array to map * @param string $class Class name * @param boolean $primary whether to assign first array key as the _name_ * @return mixed Mapped object */ protected static function _map(&$array, $class, $primary = false) { if ($class === true) { $out = new stdClass; } else { $out = new $class; } if (is_array($array)) { $keys = array_keys($array); foreach ($array as $key => $value) { if ($keys[0] === $key && $class !== true) { $primary = true; } if (is_numeric($key)) { if (is_object($out)) { $out = get_object_vars($out); } $out[$key] = Set::_map($value, $class); if (is_object($out[$key])) { if ($primary !== true && is_array($value) && Set::countDim($value, true) === 2) { if (!isset($out[$key]->_name_)) { $out[$key]->_name_ = $primary; } } } } elseif (is_array($value)) { if ($primary === true) { if (!isset($out->_name_)) { $out->_name_ = $key; } $primary = false; foreach ($value as $key2 => $value2) { $out->{$key2} = Set::_map($value2, true); } } else { if (!is_numeric($key)) { $out->{$key} = Set::_map($value, true, $key); if (is_object($out->{$key}) && !is_numeric($key)) { if (!isset($out->{$key}->_name_)) { $out->{$key}->_name_ = $key; } } } else { $out->{$key} = Set::_map($value, true); } } } else { $out->{$key} = $value; } } } else { $out = $array; } return $out; } /** * Checks to see if all the values in the array are numeric * * @param array $array The array to check. If null, the value of the current Set object * @return boolean true if values are numeric, false otherwise */ public static function numeric($array = null) { if (empty($array)) { return null; } if ($array === range(0, count($array) - 1)) { return true; } $numeric = true; $keys = array_keys($array); $count = count($keys); for ($i = 0; $i < $count; $i++) { if (!is_numeric($array[$keys[$i]])) { $numeric = false; break; } } return $numeric; } /** * Return a value from an array list if the key exists. * * If a comma separated $list is passed arrays are numeric with the key of the first being 0 * $list = 'no, yes' would translate to $list = array(0 => 'no', 1 => 'yes'); * * If an array is used, keys can be strings example: array('no' => 0, 'yes' => 1); * * $list defaults to 0 = no 1 = yes if param is not passed * * @param mixed $select Key in $list to return * @param mixed $list can be an array or a comma-separated list. * @return string the value of the array key or null if no match */ public static function enum($select, $list = null) { if (empty($list)) { $list = array('no', 'yes'); } $return = null; $list = Set::normalize($list, false); if (array_key_exists($select, $list)) { $return = $list[$select]; } return $return; } /** * Returns a series of values extracted from an array, formatted in a format string. * * @param array $data Source array from which to extract the data * @param string $format Format string into which values will be inserted, see sprintf() * @param array $keys An array containing one or more Set::extract()-style key paths * @return array An array of strings extracted from $keys and formatted with $format */ public static function format($data, $format, $keys) { $extracted = array(); $count = count($keys); if (!$count) { return; } for ($i = 0; $i < $count; $i++) { $extracted[] = Set::extract($data, $keys[$i]); } $out = array(); $data = $extracted; $count = count($data[0]); if (preg_match_all('/\{([0-9]+)\}/msi', $format, $keys2) && isset($keys2[1])) { $keys = $keys2[1]; $format = preg_split('/\{([0-9]+)\}/msi', $format); $count2 = count($format); for ($j = 0; $j < $count; $j++) { $formatted = ''; for ($i = 0; $i <= $count2; $i++) { if (isset($format[$i])) { $formatted .= $format[$i]; } if (isset($keys[$i]) && isset($data[$keys[$i]][$j])) { $formatted .= $data[$keys[$i]][$j]; } } $out[] = $formatted; } } else { $count2 = count($data); for ($j = 0; $j < $count; $j++) { $args = array(); for ($i = 0; $i < $count2; $i++) { if (array_key_exists($j, $data[$i])) { $args[] = $data[$i][$j]; } } $out[] = vsprintf($format, $args); } } return $out; } /** * Implements partial support for XPath 2.0. If $path is an array or $data is empty it the call * is delegated to Set::classicExtract. * * #### Currently implemented selectors: * * - /User/id (similar to the classic {n}.User.id) * - /User[2]/name (selects the name of the second User) * - /User[id>2] (selects all Users with an id > 2) * - /User[id>2][<5] (selects all Users with an id > 2 but < 5) * - /Post/Comment[author_name=john]/../name (Selects the name of all Posts that have at least one Comment written by john) * - /Posts[name] (Selects all Posts that have a 'name' key) * - /Comment/.[1] (Selects the contents of the first comment) * - /Comment/.[:last] (Selects the last comment) * - /Comment/.[:first] (Selects the first comment) * - /Comment[text=/cakephp/i] (Selects the all comments that have a text matching the regex /cakephp/i) * - /Comment/@* (Selects the all key names of all comments) * * #### Other limitations: * * - Only absolute paths starting with a single '/' are supported right now * * **Warning**: Even so it has plenty of unit tests the XPath support has not gone through a lot of * real-world testing. Please report Bugs as you find them. Suggestions for additional features to * implement are also very welcome! * * @param string $path An absolute XPath 2.0 path * @param array $data An array of data to extract from * @param array $options Currently only supports 'flatten' which can be disabled for higher XPath-ness * @return array An array of matched items */ public static function extract($path, $data = null, $options = array()) { if (is_string($data)) { $tmp = $data; $data = $path; $path = $tmp; } if (strpos($path, '/') === false) { return Set::classicExtract($data, $path); } if (empty($data)) { return array(); } if ($path === '/') { return $data; } $contexts = $data; $options = array_merge(array('flatten' => true), $options); if (!isset($contexts[0])) { $current = current($data); if ((is_array($current) && count($data) < 1) || !is_array($current) || !Set::numeric(array_keys($data))) { $contexts = array($data); } } $tokens = array_slice(preg_split('/(?<!=|\\\\)\/(?![a-z-\s]*\])/', $path), 1); do { $token = array_shift($tokens); $conditions = false; if (preg_match_all('/\[([^=]+=\/[^\/]+\/|[^\]]+)\]/', $token, $m)) { $conditions = $m[1]; $token = substr($token, 0, strpos($token, '[')); } $matches = array(); foreach ($contexts as $key => $context) { if (!isset($context['trace'])) { $context = array('trace' => array(null), 'item' => $context, 'key' => $key); } if ($token === '..') { if (count($context['trace']) == 1) { $context['trace'][] = $context['key']; } $parent = implode('/', $context['trace']) . '/.'; $context['item'] = Set::extract($parent, $data); $context['key'] = array_pop($context['trace']); if (isset($context['trace'][1]) && $context['trace'][1] > 0) { $context['item'] = $context['item'][0]; } elseif (!empty($context['item'][$key])) { $context['item'] = $context['item'][$key]; } else { $context['item'] = array_shift($context['item']); } $matches[] = $context; continue; } if ($token === '@*' && is_array($context['item'])) { $matches[] = array( 'trace' => array_merge($context['trace'], (array)$key), 'key' => $key, 'item' => array_keys($context['item']), ); } elseif (is_array($context['item']) && array_key_exists($token, $context['item']) && !(strval($key) === strval($token) && count($tokens) == 1 && $tokens[0] === '.')) { $items = $context['item'][$token]; if (!is_array($items)) { $items = array($items); } elseif (!isset($items[0])) { $current = current($items); $currentKey = key($items); if (!is_array($current) || (is_array($current) && count($items) <= 1 && !is_numeric($currentKey))) { $items = array($items); } } foreach ($items as $key => $item) { $ctext = array($context['key']); if (!is_numeric($key)) { $ctext[] = $token; $tok = array_shift($tokens); if (isset($items[$tok])) { $ctext[] = $tok; $item = $items[$tok]; $matches[] = array( 'trace' => array_merge($context['trace'], $ctext), 'key' => $tok, 'item' => $item, ); break; } elseif ($tok !== null) { array_unshift($tokens, $tok); } } else { $key = $token; } $matches[] = array( 'trace' => array_merge($context['trace'], $ctext), 'key' => $key, 'item' => $item, ); } } elseif ($key === $token || (ctype_digit($token) && $key == $token) || $token === '.') { $context['trace'][] = $key; $matches[] = array( 'trace' => $context['trace'], 'key' => $key, 'item' => $context['item'], ); } } if ($conditions) { foreach ($conditions as $condition) { $filtered = array(); $length = count($matches); foreach ($matches as $i => $match) { if (Set::matches(array($condition), $match['item'], $i + 1, $length)) { $filtered[$i] = $match; } } $matches = $filtered; } } $contexts = $matches; if (empty($tokens)) { break; } } while(1); $r = array(); foreach ($matches as $match) { if ((!$options['flatten'] || is_array($match['item'])) && !is_int($match['key'])) { $r[] = array($match['key'] => $match['item']); } else { $r[] = $match['item']; } } return $r; } /** * This function can be used to see if a single item or a given xpath match certain conditions. * * @param mixed $conditions An array of condition strings or an XPath expression * @param array $data An array of data to execute the match on * @param integer $i Optional: The 'nth'-number of the item being matched. * @param integer $length * @return boolean */ public static function matches($conditions, $data = array(), $i = null, $length = null) { if (empty($conditions)) { return true; } if (is_string($conditions)) { return !!Set::extract($conditions, $data); } foreach ($conditions as $condition) { if ($condition === ':last') { if ($i != $length) { return false; } continue; } elseif ($condition === ':first') { if ($i != 1) { return false; } continue; } if (!preg_match('/(.+?)([><!]?[=]|[><])(.*)/', $condition, $match)) { if (ctype_digit($condition)) { if ($i != $condition) { return false; } } elseif (preg_match_all('/(?:^[0-9]+|(?<=,)[0-9]+)/', $condition, $matches)) { return in_array($i, $matches[0]); } elseif (!array_key_exists($condition, $data)) { return false; } continue; } list(,$key,$op,$expected) = $match; if (!isset($data[$key])) { return false; } $val = $data[$key]; if ($op === '=' && $expected && $expected{0} === '/') { return preg_match($expected, $val); } if ($op === '=' && $val != $expected) { return false; } if ($op === '!=' && $val == $expected) { return false; } if ($op === '>' && $val <= $expected) { return false; } if ($op === '<' && $val >= $expected) { return false; } if ($op === '<=' && $val > $expected) { return false; } if ($op === '>=' && $val < $expected) { return false; } } return true; } /** * Gets a value from an array or object that is contained in a given path using an array path syntax, i.e.: * "{n}.Person.{[a-z]+}" - Where "{n}" represents a numeric key, "Person" represents a string literal, * and "{[a-z]+}" (i.e. any string literal enclosed in brackets besides {n} and {s}) is interpreted as * a regular expression. * * @param array $data Array from where to extract * @param mixed $path As an array, or as a dot-separated string. * @return array Extracted data */ public static function classicExtract($data, $path = null) { if (empty($path)) { return $data; } if (is_object($data)) { if (!($data instanceof ArrayAccess || $data instanceof Traversable)) { $data = get_object_vars($data); } } if (empty($data)) { return null; } if (is_string($path) && strpos($path, '{') !== false) { $path = String::tokenize($path, '.', '{', '}'); } elseif (is_string($path)) { $path = explode('.', $path); } $tmp = array(); if (empty($path)) { return null; } foreach ($path as $i => $key) { if (is_numeric($key) && intval($key) > 0 || $key === '0') { if (isset($data[intval($key)])) { $data = $data[intval($key)]; } else { return null; } } elseif ($key === '{n}') { foreach ($data as $j => $val) { if (is_int($j)) { $tmpPath = array_slice($path, $i + 1); if (empty($tmpPath)) { $tmp[] = $val; } else { $tmp[] = Set::classicExtract($val, $tmpPath); } } } return $tmp; } elseif ($key === '{s}') { foreach ($data as $j => $val) { if (is_string($j)) { $tmpPath = array_slice($path, $i + 1); if (empty($tmpPath)) { $tmp[] = $val; } else { $tmp[] = Set::classicExtract($val, $tmpPath); } } } return $tmp; } elseif (false !== strpos($key,'{') && false !== strpos($key,'}')) { $pattern = substr($key, 1, -1); foreach ($data as $j => $val) { if (preg_match('/^'.$pattern.'/s', $j) !== 0) { $tmpPath = array_slice($path, $i + 1); if (empty($tmpPath)) { $tmp[$j] = $val; } else { $tmp[$j] = Set::classicExtract($val, $tmpPath); } } } return $tmp; } else { if (isset($data[$key])) { $data = $data[$key]; } else { return null; } } } return $data; } /** * Inserts $data into an array as defined by $path. * * @param mixed $list Where to insert into * @param mixed $path A dot-separated string. * @param array $data Data to insert * @return array */ public static function insert($list, $path, $data = null) { if (!is_array($path)) { $path = explode('.', $path); } $_list =& $list; $count = count($path); foreach ($path as $i => $key) { if (is_numeric($key) && intval($key) > 0 || $key === '0') { $key = intval($key); } if ($i === $count - 1) { $_list[$key] = $data; } else { if (!isset($_list[$key])) { $_list[$key] = array(); } $_list =& $_list[$key]; } } return $list; } /** * Removes an element from a Set or array as defined by $path. * * @param mixed $list From where to remove * @param mixed $path A dot-separated string. * @return array Array with $path removed from its value */ public static function remove($list, $path = null) { if (empty($path)) { return $list; } if (!is_array($path)) { $path = explode('.', $path); } $_list =& $list; foreach ($path as $i => $key) { if (is_numeric($key) && intval($key) > 0 || $key === '0') { $key = intval($key); } if ($i === count($path) - 1) { unset($_list[$key]); } else { if (!isset($_list[$key])) { return $list; } $_list =& $_list[$key]; } } return $list; } /** * Checks if a particular path is set in an array * * @param mixed $data Data to check on * @param mixed $path A dot-separated string. * @return boolean true if path is found, false otherwise */ public static function check($data, $path = null) { if (empty($path)) { return $data; } if (!is_array($path)) { $path = explode('.', $path); } foreach ($path as $i => $key) { if (is_numeric($key) && intval($key) > 0 || $key === '0') { $key = intval($key); } if ($i === count($path) - 1) { return (is_array($data) && array_key_exists($key, $data)); } if (!is_array($data) || !array_key_exists($key, $data)) { return false; } $data =& $data[$key]; } return true; } /** * Computes the difference between a Set and an array, two Sets, or two arrays * * @param mixed $val1 First value * @param mixed $val2 Second value * @return array Returns the key => value pairs that are not common in $val1 and $val2 * The expression for this function is ($val1 - $val2) + ($val2 - ($val1 - $val2)) */ public static function diff($val1, $val2 = null) { if (empty($val1)) { return (array)$val2; } if (empty($val2)) { return (array)$val1; } $intersection = array_intersect_key($val1, $val2); while (($key = key($intersection)) !== null) { if ($val1[$key] == $val2[$key]) { unset($val1[$key]); unset($val2[$key]); } next($intersection); } return $val1 + $val2; } /** * Determines if one Set or array contains the exact keys and values of another. * * @param array $val1 First value * @param array $val2 Second value * @return boolean true if $val1 contains $val2, false otherwise */ public static function contains($val1, $val2 = null) { if (empty($val1) || empty($val2)) { return false; } foreach ($val2 as $key => $val) { if (is_numeric($key)) { Set::contains($val, $val1); } else { if (!isset($val1[$key]) || $val1[$key] != $val) { return false; } } } return true; } /** * Counts the dimensions of an array. If $all is set to false (which is the default) it will * only consider the dimension of the first element in the array. * * @param array $array Array to count dimensions on * @param boolean $all Set to true to count the dimension considering all elements in array * @param integer $count Start the dimension count at this number * @return integer The number of dimensions in $array */ public static function countDim($array = null, $all = false, $count = 0) { if ($all) { $depth = array($count); if (is_array($array) && reset($array) !== false) { foreach ($array as $value) { $depth[] = Set::countDim($value, true, $count + 1); } } $return = max($depth); } else { if (is_array(reset($array))) { $return = Set::countDim(reset($array)) + 1; } else { $return = 1; } } return $return; } /** * Normalizes a string or array list. * * @param mixed $list List to normalize * @param boolean $assoc If true, $list will be converted to an associative array * @param string $sep If $list is a string, it will be split into an array with $sep * @param boolean $trim If true, separated strings will be trimmed * @return array */ public static function normalize($list, $assoc = true, $sep = ',', $trim = true) { if (is_string($list)) { $list = explode($sep, $list); if ($trim) { foreach ($list as $key => $value) { $list[$key] = trim($value); } } if ($assoc) { return Set::normalize($list); } } elseif (is_array($list)) { $keys = array_keys($list); $count = count($keys); $numeric = true; if (!$assoc) { for ($i = 0; $i < $count; $i++) { if (!is_int($keys[$i])) { $numeric = false; break; } } } if (!$numeric || $assoc) { $newList = array(); for ($i = 0; $i < $count; $i++) { if (is_int($keys[$i])) { $newList[$list[$keys[$i]]] = null; } else { $newList[$keys[$i]] = $list[$keys[$i]]; } } $list = $newList; } } return $list; } /** * Creates an associative array using a $path1 as the path to build its keys, and optionally * $path2 as path to get the values. If $path2 is not specified, all values will be initialized * to null (useful for Set::merge). You can optionally group the values by what is obtained when * following the path specified in $groupPath. * * @param mixed $data Array or object from where to extract keys and values * @param mixed $path1 As an array, or as a dot-separated string. * @param mixed $path2 As an array, or as a dot-separated string. * @param string $groupPath As an array, or as a dot-separated string. * @return array Combined array */ public static function combine($data, $path1 = null, $path2 = null, $groupPath = null) { if (empty($data)) { return array(); } if (is_object($data)) { if (!($data instanceof ArrayAccess || $data instanceof Traversable)) { $data = get_object_vars($data); } } if (is_array($path1)) { $format = array_shift($path1); $keys = Set::format($data, $format, $path1); } else { $keys = Set::extract($data, $path1); } if (empty($keys)) { return array(); } if (!empty($path2) && is_array($path2)) { $format = array_shift($path2); $vals = Set::format($data, $format, $path2); } elseif (!empty($path2)) { $vals = Set::extract($data, $path2); } else { $count = count($keys); for ($i = 0; $i < $count; $i++) { $vals[$i] = null; } } if ($groupPath != null) { $group = Set::extract($data, $groupPath); if (!empty($group)) { $c = count($keys); for ($i = 0; $i < $c; $i++) { if (!isset($group[$i])) { $group[$i] = 0; } if (!isset($out[$group[$i]])) { $out[$group[$i]] = array(); } $out[$group[$i]][$keys[$i]] = $vals[$i]; } return $out; } } if (empty($vals)) { return array(); } return array_combine($keys, $vals); } /** * Converts an object into an array. * @param object $object Object to reverse * @return array Array representation of given object */ public static function reverse($object) { $out = array(); if ($object instanceof SimpleXMLElement) { return Xml::toArray($object); } else if (is_object($object)) { $keys = get_object_vars($object); if (isset($keys['_name_'])) { $identity = $keys['_name_']; unset($keys['_name_']); } $new = array(); foreach ($keys as $key => $value) { if (is_array($value)) { $new[$key] = (array)Set::reverse($value); } else { if (isset($value->_name_)) { $new = array_merge($new, Set::reverse($value)); } else { $new[$key] = Set::reverse($value); } } } if (isset($identity)) { $out[$identity] = $new; } else { $out = $new; } } elseif (is_array($object)) { foreach ($object as $key => $value) { $out[$key] = Set::reverse($value); } } else { $out = $object; } return $out; } /** * Collapses a multi-dimensional array into a single dimension, using a delimited array path for * each array element's key, i.e. array(array('Foo' => array('Bar' => 'Far'))) becomes * array('0.Foo.Bar' => 'Far'). * * @param array $data Array to flatten * @param string $separator String used to separate array key elements in a path, defaults to '.' * @return array */ public static function flatten($data, $separator = '.') { $result = array(); $path = null; if (is_array($separator)) { extract($separator, EXTR_OVERWRITE); } if (!is_null($path)) { $path .= $separator; } foreach ($data as $key => $val) { if (is_array($val)) { $result += (array)Set::flatten($val, array( 'separator' => $separator, 'path' => $path . $key )); } else { $result[$path . $key] = $val; } } return $result; } /** * Flattens an array for sorting * * @param array $results * @param string $key * @return array */ protected static function _flatten($results, $key = null) { $stack = array(); foreach ($results as $k => $r) { $id = $k; if (!is_null($key)) { $id = $key; } if (is_array($r) && !empty($r)) { $stack = array_merge($stack, Set::_flatten($r, $id)); } else { $stack[] = array('id' => $id, 'value' => $r); } } return $stack; } /** * Sorts an array by any value, determined by a Set-compatible path * * @param array $data An array of data to sort * @param string $path A Set-compatible path to the array value * @param string $dir Direction of sorting - either ascending (ASC), or descending (DESC) * @return array Sorted array of data */ public static function sort($data, $path, $dir) { $originalKeys = array_keys($data); if (is_numeric(implode('', $originalKeys))) { $data = array_values($data); } $result = Set::_flatten(Set::extract($data, $path)); list($keys, $values) = array(Set::extract($result, '{n}.id'), Set::extract($result, '{n}.value')); $dir = strtolower($dir); if ($dir === 'asc') { $dir = SORT_ASC; } elseif ($dir === 'desc') { $dir = SORT_DESC; } array_multisort($values, $dir, $keys, $dir); $sorted = array(); $keys = array_unique($keys); foreach ($keys as $k) { $sorted[] = $data[$k]; } return $sorted; } /** * Allows the application of a callback method to elements of an * array extracted by a Set::extract() compatible path. * * @param mixed $path Set-compatible path to the array value * @param array $data An array of data to extract from & then process with the $callback. * @param mixed $callback Callback method to be applied to extracted data. * See http://ca2.php.net/manual/en/language.pseudo-types.php#language.types.callback for examples * of callback formats. * @param array $options Options are: * - type : can be pass, map, or reduce. Map will handoff the given callback * to array_map, reduce will handoff to array_reduce, and pass will * use call_user_func_array(). * @return mixed Result of the callback when applied to extracted data */ public static function apply($path, $data, $callback, $options = array()) { $defaults = array('type' => 'pass'); $options = array_merge($defaults, $options); $extracted = Set::extract($path, $data); if ($options['type'] === 'map') { return array_map($callback, $extracted); } elseif ($options['type'] === 'reduce') { return array_reduce($extracted, $callback); } elseif ($options['type'] === 'pass') { return call_user_func_array($callback, array($extracted)); } return null; } }
0001-bee
trunk/cakephp2/lib/Cake/Utility/Set.php
PHP
gpl3
30,367
<?php /** * Validation Class. Used for validation of model data * * PHP Version 5.x * * 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.Utility * @since CakePHP(tm) v 1.2.0.3830 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Multibyte', 'I18n'); // Load multibyte if the extension is missing. if (!function_exists('mb_strlen')) { class_exists('Multibyte'); } /** * Offers different validation methods. * * @package Cake.Utility * @since CakePHP v 1.2.0.3830 */ class Validation { /** * Some complex patterns needed in multiple places * * @var array */ protected static $_pattern = array( 'hostname' => '(?:[a-z0-9][-a-z0-9]*\.)*(?:[a-z0-9][-a-z0-9]{0,62})\.(?:(?:[a-z]{2}\.)?[a-z]{2,4}|museum|travel)' ); /** * Holds an array of errors messages set in this class. * These are used for debugging purposes * * @var array */ public static $errors = array(); /** * Checks that a string contains something other than whitespace * * Returns true if string contains something other than whitespace * * $check can be passed as an array: * array('check' => 'valueToCheck'); * * @param mixed $check Value to check * @return boolean Success */ public static function notEmpty($check) { if (is_array($check)) { extract(self::_defaults($check)); } if (empty($check) && $check != '0') { return false; } return self::_check($check, '/[^\s]+/m'); } /** * Checks that a string contains only integer or letters * * Returns true if string contains only integer or letters * * $check can be passed as an array: * array('check' => 'valueToCheck'); * * @param mixed $check Value to check * @return boolean Success */ public static function alphaNumeric($check) { if (is_array($check)) { extract(self::_defaults($check)); } if (empty($check) && $check != '0') { return false; } return self::_check($check, '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/mu'); } /** * Checks that a string length is within s specified range. * Spaces are included in the character count. * Returns true is string matches value min, max, or between min and max, * * @param string $check Value to check for length * @param integer $min Minimum value in range (inclusive) * @param integer $max Maximum value in range (inclusive) * @return boolean Success */ public static function between($check, $min, $max) { $length = mb_strlen($check); return ($length >= $min && $length <= $max); } /** * Returns true if field is left blank -OR- only whitespace characters are present in it's value * Whitespace characters include Space, Tab, Carriage Return, Newline * * $check can be passed as an array: * array('check' => 'valueToCheck'); * * @param mixed $check Value to check * @return boolean Success */ public static function blank($check) { if (is_array($check)) { extract(self::_defaults($check)); } return !self::_check($check, '/[^\\s]/'); } /** * Validation of credit card numbers. * Returns true if $check is in the proper credit card format. * * @param mixed $check credit card number to validate * @param mixed $type 'all' may be passed as a sting, defaults to fast which checks format of most major credit cards * if an array is used only the values of the array are checked. * Example: array('amex', 'bankcard', 'maestro') * @param boolean $deep set to true this will check the Luhn algorithm of the credit card. * @param string $regex A custom regex can also be passed, this will be used instead of the defined regex values * @return boolean Success * @see Validation::luhn() */ public static function cc($check, $type = 'fast', $deep = false, $regex = null) { if (is_array($check)) { extract(self::_defaults($check)); } $check = str_replace(array('-', ' '), '', $check); if (mb_strlen($check) < 13) { return false; } if (!is_null($regex)) { if (self::_check($check, $regex)) { return self::luhn($check, $deep); } } $cards = array( 'all' => array( 'amex' => '/^3[4|7]\\d{13}$/', 'bankcard' => '/^56(10\\d\\d|022[1-5])\\d{10}$/', 'diners' => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/', 'disc' => '/^(?:6011|650\\d)\\d{12}$/', 'electron' => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/', 'enroute' => '/^2(?:014|149)\\d{11}$/', 'jcb' => '/^(3\\d{4}|2100|1800)\\d{11}$/', 'maestro' => '/^(?:5020|6\\d{3})\\d{12}$/', 'mc' => '/^5[1-5]\\d{14}$/', 'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/', 'switch' => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4][0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/', 'visa' => '/^4\\d{12}(\\d{3})?$/', 'voyager' => '/^8699[0-9]{11}$/'), 'fast' => '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/'); if (is_array($type)) { foreach ($type as $value) { $regex = $cards['all'][strtolower($value)]; if (self::_check($check, $regex)) { return self::luhn($check, $deep); } } } elseif ($type == 'all') { foreach ($cards['all'] as $value) { $regex = $value; if (self::_check($check, $regex)) { return self::luhn($check, $deep); } } } else { $regex = $cards['fast']; if (self::_check($check, $regex)) { return self::luhn($check, $deep); } } return false; } /** * Used to compare 2 numeric values. * * @param mixed $check1 if string is passed for a string must also be passed for $check2 * used as an array it must be passed as array('check1' => value, 'operator' => 'value', 'check2' -> value) * @param string $operator Can be either a word or operand * is greater >, is less <, greater or equal >= * less or equal <=, is less <, equal to ==, not equal != * @param integer $check2 only needed if $check1 is a string * @return boolean Success */ public static function comparison($check1, $operator = null, $check2 = null) { if (is_array($check1)) { extract($check1, EXTR_OVERWRITE); } $operator = str_replace(array(' ', "\t", "\n", "\r", "\0", "\x0B"), '', strtolower($operator)); switch ($operator) { case 'isgreater': case '>': if ($check1 > $check2) { return true; } break; case 'isless': case '<': if ($check1 < $check2) { return true; } break; case 'greaterorequal': case '>=': if ($check1 >= $check2) { return true; } break; case 'lessorequal': case '<=': if ($check1 <= $check2) { return true; } break; case 'equalto': case '==': if ($check1 == $check2) { return true; } break; case 'notequal': case '!=': if ($check1 != $check2) { return true; } break; default: self::$errors[] = __d('cake_dev', 'You must define the $operator parameter for Validation::comparison()'); break; } return false; } /** * Used when a custom regular expression is needed. * * @param mixed $check When used as a string, $regex must also be a valid regular expression. * As and array: array('check' => value, 'regex' => 'valid regular expression') * @param string $regex If $check is passed as a string, $regex must also be set to valid regular expression * @return boolean Success */ public static function custom($check, $regex = null) { if (is_array($check)) { extract(self::_defaults($check)); } if ($regex === null) { self::$errors[] = __d('cake_dev', 'You must define a regular expression for Validation::custom()'); return false; } return self::_check($check, $regex); } /** * Date validation, determines if the string passed is a valid date. * keys that expect full month, day and year will validate leap years * * @param string $check a valid date string * @param mixed $format Use a string or an array of the keys below. Arrays should be passed as array('dmy', 'mdy', etc) * Keys: dmy 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash * mdy 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash * ymd 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash * dMy 27 December 2006 or 27 Dec 2006 * Mdy December 27, 2006 or Dec 27, 2006 comma is optional * My December 2006 or Dec 2006 * my 12/2006 separators can be a space, period, dash, forward slash * @param string $regex If a custom regular expression is used this is the only validation that will occur. * @return boolean Success */ public static function date($check, $format = 'ymd', $regex = null) { if (!is_null($regex)) { return self::_check($check, $regex); } $regex['dmy'] = '%^(?:(?:31(\\/|-|\\.|\\x20)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.|\\x20)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.|\\x20)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.|\\x20)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%'; $regex['mdy'] = '%^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.|\\x20)31)\\1|(?:(?:0?[13-9]|1[0-2])(\\/|-|\\.|\\x20)(?:29|30)\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:0?2(\\/|-|\\.|\\x20)29\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\\/|-|\\.|\\x20)(?:0?[1-9]|1\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%'; $regex['ymd'] = '%^(?:(?:(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(\\/|-|\\.|\\x20)(?:0?2\\1(?:29)))|(?:(?:(?:1[6-9]|[2-9]\\d)?\\d{2})(\\/|-|\\.|\\x20)(?:(?:(?:0?[13578]|1[02])\\2(?:31))|(?:(?:0?[1,3-9]|1[0-2])\\2(29|30))|(?:(?:0?[1-9])|(?:1[0-2]))\\2(?:0?[1-9]|1\\d|2[0-8]))))$%'; $regex['dMy'] = '/^((31(?!\\ (Feb(ruary)?|Apr(il)?|June?|(Sep(?=\\b|t)t?|Nov)(ember)?)))|((30|29)(?!\\ Feb(ruary)?))|(29(?=\\ Feb(ruary)?\\ (((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\\d|2[0-8])\\ (Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)\\ ((1[6-9]|[2-9]\\d)\\d{2})$/'; $regex['Mdy'] = '/^(?:(((Jan(uary)?|Ma(r(ch)?|y)|Jul(y)?|Aug(ust)?|Oct(ober)?|Dec(ember)?)\\ 31)|((Jan(uary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep)(tember)?|(Nov|Dec)(ember)?)\\ (0?[1-9]|([12]\\d)|30))|(Feb(ruary)?\\ (0?[1-9]|1\\d|2[0-8]|(29(?=,?\\ ((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))))\\,?\\ ((1[6-9]|[2-9]\\d)\\d{2}))$/'; $regex['My'] = '%^(Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)[ /]((1[6-9]|[2-9]\\d)\\d{2})$%'; $regex['my'] = '%^(((0[123456789]|10|11|12)([- /.])(([1][9][0-9][0-9])|([2][0-9][0-9][0-9]))))$%'; $format = (is_array($format)) ? array_values($format) : array($format); foreach ($format as $key) { $regex = $regex[$key]; if (self::_check($check, $regex) === true) { return true; } } return false; } /** * Validates a datetime value * All values matching the "date" core validation rule, and the "time" one will be valid * * @param array $check Value to check * @param mixed $dateFormat Format of the date part * Use a string or an array of the keys below. Arrays should be passed as array('dmy', 'mdy', etc) * ## Keys: * * - dmy 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash * - mdy 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash * - ymd 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash * - dMy 27 December 2006 or 27 Dec 2006 * - Mdy December 27, 2006 or Dec 27, 2006 comma is optional * - My December 2006 or Dec 2006 * - my 12/2006 separators can be a space, period, dash, forward slash * @param string $regex Regex for the date part. If a custom regular expression is used this is the only validation that will occur. * @return boolean True if the value is valid, false otherwise * @see Validation::date * @see Validation::time */ public function datetime($check, $dateFormat = 'ymd', $regex = null) { $valid = false; $parts = explode(' ', $check); if (!empty($parts) && count($parts) > 1) { $time = array_pop($parts); $date = implode(' ', $parts); $valid = self::date($date, $dateFormat, $regex) && self::time($time); } return $valid; } /** * Time validation, determines if the string passed is a valid time. * Validates time as 24hr (HH:MM) or am/pm ([H]H:MM[a|p]m) * Does not allow/validate seconds. * * @param string $check a valid time string * @return boolean Success */ public static function time($check) { return self::_check($check, '%^((0?[1-9]|1[012])(:[0-5]\d){0,2} ?([AP]M|[ap]m))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$%'); } /** * Boolean validation, determines if value passed is a boolean integer or true/false. * * @param string $check a valid boolean * @return boolean Success */ public static function boolean($check) { $booleanList = array(0, 1, '0', '1', true, false); return in_array($check, $booleanList, true); } /** * Checks that a value is a valid decimal. If $places is null, the $check is allowed to be a scientific float * If no decimal point is found a false will be returned. Both the sign and exponent are optional. * * @param integer $check The value the test for decimal * @param integer $places if set $check value must have exactly $places after the decimal point * @param string $regex If a custom regular expression is used this is the only validation that will occur. * @return boolean Success */ public static function decimal($check, $places = null, $regex = null) { if (is_null($regex)) { if (is_null($places)) { $regex = '/^[-+]?[0-9]*\\.{1}[0-9]+(?:[eE][-+]?[0-9]+)?$/'; } else { $regex = '/^[-+]?[0-9]*\\.{1}[0-9]{'.$places.'}$/'; } } return self::_check($check, $regex); } /** * Validates for an email address. * * Only uses getmxrr() checking for deep validation if PHP 5.3.0+ is used, or * any PHP version on a non-windows distribution * * @param string $check Value to check * @param boolean $deep Perform a deeper validation (if true), by also checking availability of host * @param string $regex Regex to use (if none it will use built in regex) * @return boolean Success */ public static function email($check, $deep = false, $regex = null) { if (is_array($check)) { extract(self::_defaults($check)); } if (is_null($regex)) { $regex = '/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@' . self::$_pattern['hostname'] . '$/i'; } $return = self::_check($check, $regex); if ($deep === false || $deep === null) { return $return; } if ($return === true && preg_match('/@(' . self::$_pattern['hostname'] . ')$/i', $check, $regs)) { if (function_exists('getmxrr') && getmxrr($regs[1], $mxhosts)) { return true; } if (function_exists('checkdnsrr') && checkdnsrr($regs[1], 'MX')) { return true; } return is_array(gethostbynamel($regs[1])); } return false; } /** * Check that value is exactly $comparedTo. * * @param mixed $check Value to check * @param mixed $comparedTo Value to compare * @return boolean Success */ public static function equalTo($check, $comparedTo) { return ($check === $comparedTo); } /** * Check that value has a valid file extension. * * @param mixed $check Value to check * @param array $extensions file extenstions to allow * @return boolean Success */ public static function extension($check, $extensions = array('gif', 'jpeg', 'png', 'jpg')) { if (is_array($check)) { return self::extension(array_shift($check), $extensions); } $pathSegments = explode('.', $check); $extension = strtolower(array_pop($pathSegments)); foreach ($extensions as $value) { if ($extension == strtolower($value)) { return true; } } return false; } /** * Validation of an IP address. * * @param string $check The string to test. * @param string $type The IP Protocol version to validate against * @return boolean Success */ public static function ip($check, $type = 'both') { $type = strtolower($type); $flags = array(); if ($type === 'ipv4' || $type === 'both') { $flags[] = FILTER_FLAG_IPV4; } if ($type === 'ipv6' || $type === 'both') { $flags[] = FILTER_FLAG_IPV6; } return (boolean)filter_var($check, FILTER_VALIDATE_IP, array('flags' => $flags)); } /** * Checks whether the length of a string is greater or equal to a minimal length. * * @param string $check The string to test * @param integer $min The minimal string length * @return boolean Success */ public static function minLength($check, $min) { return mb_strlen($check) >= $min; } /** * Checks whether the length of a string is smaller or equal to a maximal length.. * * @param string $check The string to test * @param integer $max The maximal string length * @return boolean Success */ public static function maxLength($check, $max) { return mb_strlen($check) <= $max; } /** * Checks that a value is a monetary amount. * * @param string $check Value to check * @param string $symbolPosition Where symbol is located (left/right) * @return boolean Success */ public static function money($check, $symbolPosition = 'left') { $money = '(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?(?:\1\d{3})*|(?:\d+))((?!\1)[,.]\d{2})?'; if ($symbolPosition == 'right') { $regex = '/^' . $money . '(?<!\x{00a2})\p{Sc}?$/u'; } else { $regex = '/^(?!\x{00a2})\p{Sc}?' . $money . '$/u'; } return self::_check($check, $regex); } /** * Validate a multiple select. * * Valid Options * * - in => provide a list of choices that selections must be made from * - max => maximun number of non-zero choices that can be made * - min => minimum number of non-zero choices that can be made * * @param mixed $check Value to check * @param mixed $options Options for the check. * @return boolean Success */ public static function multiple($check, $options = array()) { $defaults = array('in' => null, 'max' => null, 'min' => null); $options = array_merge($defaults, $options); $check = array_filter((array)$check); if (empty($check)) { return false; } if ($options['max'] && count($check) > $options['max']) { return false; } if ($options['min'] && count($check) < $options['min']) { return false; } if ($options['in'] && is_array($options['in'])) { foreach ($check as $val) { if (!in_array($val, $options['in'])) { return false; } } } return true; } /** * Checks if a value is numeric. * * @param string $check Value to check * @return boolean Succcess */ public static function numeric($check) { return is_numeric($check); } /** * Check that a value is a valid phone number. * * @param mixed $check Value to check (string or array) * @param string $regex Regular expression to use * @param string $country Country code (defaults to 'all') * @return boolean Success */ public static function phone($check, $regex = null, $country = 'all') { if (is_array($check)) { extract(self::_defaults($check)); } if (is_null($regex)) { switch ($country) { case 'us': case 'all': case 'can': // includes all NANPA members. see http://en.wikipedia.org/wiki/North_American_Numbering_Plan#List_of_NANPA_countries_and_territories $regex = '/^(?:\+?1)?[-. ]?\\(?[2-9][0-8][0-9]\\)?[-. ]?[2-9][0-9]{2}[-. ]?[0-9]{4}$/'; break; } } if (empty($regex)) { return self::_pass('phone', $check, $country); } return self::_check($check, $regex); } /** * Checks that a given value is a valid postal code. * * @param mixed $check Value to check * @param string $regex Regular expression to use * @param string $country Country to use for formatting * @return boolean Success */ public static function postal($check, $regex = null, $country = 'us') { if (is_array($check)) { extract(self::_defaults($check)); } if (is_null($regex)) { switch ($country) { case 'uk': $regex = '/\\A\\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\\b\\z/i'; break; case 'ca': $regex = '/\\A\\b[ABCEGHJKLMNPRSTVXY][0-9][A-Z] [0-9][A-Z][0-9]\\b\\z/i'; break; case 'it': case 'de': $regex = '/^[0-9]{5}$/i'; break; case 'be': $regex = '/^[1-9]{1}[0-9]{3}$/i'; break; case 'us': $regex = '/\\A\\b[0-9]{5}(?:-[0-9]{4})?\\b\\z/i'; break; } } if (empty($regex)) { return self::_pass('postal', $check, $country); } return self::_check($check, $regex); } /** * Validate that a number is in specified range. * if $lower and $upper are not set, will return true if * $check is a legal finite on this platform * * @param string $check Value to check * @param integer $lower Lower limit * @param integer $upper Upper limit * @return boolean Success */ public static function range($check, $lower = null, $upper = null) { if (!is_numeric($check)) { return false; } if (isset($lower) && isset($upper)) { return ($check > $lower && $check < $upper); } return is_finite($check); } /** * Checks that a value is a valid Social Security Number. * * @param mixed $check Value to check * @param string $regex Regular expression to use * @param string $country Country * @return boolean Success */ public static function ssn($check, $regex = null, $country = null) { if (is_array($check)) { extract(self::_defaults($check)); } if (is_null($regex)) { switch ($country) { case 'dk': $regex = '/\\A\\b[0-9]{6}-[0-9]{4}\\b\\z/i'; break; case 'nl': $regex = '/\\A\\b[0-9]{9}\\b\\z/i'; break; case 'us': $regex = '/\\A\\b[0-9]{3}-[0-9]{2}-[0-9]{4}\\b\\z/i'; break; } } if (empty($regex)) { return self::_pass('ssn', $check, $country); } return self::_check($check, $regex); } /** * Checks that a value is a valid URL according to http://www.w3.org/Addressing/URL/url-spec.txt * * The regex checks for the following component parts: * * - a valid, optional, scheme * - a valid ip address OR * a valid domain name as defined by section 2.3.1 of http://www.ietf.org/rfc/rfc1035.txt * with an optional port number * - an optional valid path * - an optional query string (get parameters) * - an optional fragment (anchor tag) * * @param string $check Value to check * @param boolean $strict Require URL to be prefixed by a valid scheme (one of http(s)/ftp(s)/file/news/gopher) * @return boolean Success */ public static function url($check, $strict = false) { self::_populateIp(); $validChars = '([' . preg_quote('!"$&\'()*+,-.@_:;=~[]') . '\/0-9a-z\p{L}\p{N}]|(%[0-9a-f]{2}))'; $regex = '/^(?:(?:https?|ftps?|file|news|gopher):\/\/)' . (!empty($strict) ? '' : '?') . '(?:' . self::$_pattern['IPv4'] . '|\[' . self::$_pattern['IPv6'] . '\]|' . self::$_pattern['hostname'] . ')(?::[1-9][0-9]{0,4})?' . '(?:\/?|\/' . $validChars . '*)?' . '(?:\?' . $validChars . '*)?' . '(?:#' . $validChars . '*)?$/iu'; return self::_check($check, $regex); } /** * Checks if a value is in a given list. * * @param string $check Value to check * @param array $list List to check against * @return boolean Succcess */ public static function inList($check, $list) { return in_array($check, $list); } /** * Runs an user-defined validation. * * @param mixed $check value that will be validated in user-defined methods. * @param object $object class that holds validation method * @param string $method class method name for validation to run * @param array $args arguments to send to method * @return mixed user-defined class class method returns */ public static function userDefined($check, $object, $method, $args = null) { return call_user_func_array(array($object, $method), array($check, $args)); } /** * Checks that a value is a valid uuid - http://tools.ietf.org/html/rfc4122 * * @param string $check Value to check * @return boolean Success */ public static function uuid($check) { $regex = '/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i'; return self::_check($check, $regex); } /** * Attempts to pass unhandled Validation locales to a class starting with $classPrefix * and ending with Validation. For example $classPrefix = 'nl', the class would be * `NlValidation`. * * @param string $method The method to call on the other class. * @param mixed $check The value to check or an array of parameters for the method to be called. * @param string $classPrefix The prefix for the class to do the validation. * @return mixed Return of Passed method, false on failure */ protected static function _pass($method, $check, $classPrefix) { $className = ucwords($classPrefix) . 'Validation'; if (!class_exists($className)) { trigger_error(__d('cake_dev', 'Could not find %s class, unable to complete validation.', $className), E_USER_WARNING); return false; } if (!method_exists($className, $method)) { trigger_error(__d('cake_dev', 'Method %s does not exist on %s unable to complete validation.', $method, $className), E_USER_WARNING); return false; } $check = (array)$check; return call_user_func_array(array($className, $method), $check); } /** * Runs a regular expression match. * * @param mixed $check Value to check against the $regex expression * @param string $regex Regular expression * @return boolean Success of match */ protected static function _check($check, $regex) { if (preg_match($regex, $check)) { self::$errors[] = false; return true; } else { self::$errors[] = true; return false; } } /** * Get the values to use when value sent to validation method is * an array. * * @param array $params Parameters sent to validation method * @return void */ protected static function _defaults($params) { self::_reset(); $defaults = array( 'check' => null, 'regex' => null, 'country' => null, 'deep' => false, 'type' => null ); $params = array_merge($defaults, $params); if ($params['country'] !== null) { $params['country'] = mb_strtolower($params['country']); } return $params; } /** * Luhn algorithm * * @param string|array $check * @param boolean $deep * @return boolean Success * @see http://en.wikipedia.org/wiki/Luhn_algorithm */ public static function luhn($check, $deep = false) { if (is_array($check)) { extract(self::_defaults($check)); } if ($deep !== true) { return true; } if ($check == 0) { return false; } $sum = 0; $length = strlen($check); for ($position = 1 - ($length % 2); $position < $length; $position += 2) { $sum += $check[$position]; } for ($position = ($length % 2); $position < $length; $position += 2) { $number = $check[$position] * 2; $sum += ($number < 10) ? $number : $number - 9; } return ($sum % 10 == 0); } /** * Lazily populate the IP address patterns used for validations * * @return void */ protected static function _populateIp() { if (!isset(self::$_pattern['IPv6'])) { $pattern = '((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}'; $pattern .= '(:|((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})'; $pattern .= '|(:[0-9A-Fa-f]{1,4})))|(([0-9A-Fa-f]{1,4}:){5}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})'; $pattern .= '(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)'; $pattern .= '{4}(:[0-9A-Fa-f]{1,4}){0,1}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))'; $pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}'; $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|'; $pattern .= '((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}'; $pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))'; $pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4})'; $pattern .= '{0,4}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)'; $pattern .= '|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]'; $pattern .= '\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4})'; $pattern .= '{1,2})))|(((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))(%.+)?'; self::$_pattern['IPv6'] = $pattern; } if (!isset(self::$_pattern['IPv4'])) { $pattern = '(?:(?:25[0-5]|2[0-4][0-9]|(?:(?:1[0-9])?|[1-9]?)[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|(?:(?:1[0-9])?|[1-9]?)[0-9])'; self::$_pattern['IPv4'] = $pattern; } } /** * Reset internal variables for another validation run. * * @return void */ protected static function _reset() { self::$errors = array(); } }
0001-bee
trunk/cakephp2/lib/Cake/Utility/Validation.php
PHP
gpl3
29,609
<?php /** * String handling methods. * * 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.Utility * @since CakePHP(tm) v 1.2.0.5551 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * String handling methods. * * * @package Cake.Utility */ class String { /** * Generate a random UUID * * @see http://www.ietf.org/rfc/rfc4122.txt * @return RFC 4122 UUID */ public static function uuid() { $node = env('SERVER_ADDR'); if (strpos($node, ':') !== false) { if (substr_count($node, '::')) { $node = str_replace( '::', str_repeat(':0000', 8 - substr_count($node, ':')) . ':', $node ); } $node = explode(':', $node) ; $ipv6 = '' ; foreach ($node as $id) { $ipv6 .= str_pad(base_convert($id, 16, 2), 16, 0, STR_PAD_LEFT); } $node = base_convert($ipv6, 2, 10); if (strlen($node) < 38) { $node = null; } else { $node = crc32($node); } } elseif (empty($node)) { $host = env('HOSTNAME'); if (empty($host)) { $host = env('HOST'); } if (!empty($host)) { $ip = gethostbyname($host); if ($ip === $host) { $node = crc32($host); } else { $node = ip2long($ip); } } } elseif ($node !== '127.0.0.1') { $node = ip2long($node); } else { $node = null; } if (empty($node)) { $node = crc32(Configure::read('Security.salt')); } if (function_exists('zend_thread_id')) { $pid = zend_thread_id(); } else { $pid = getmypid(); } if (!$pid || $pid > 65535) { $pid = mt_rand(0, 0xfff) | 0x4000; } list($timeMid, $timeLow) = explode(' ', microtime()); $uuid = sprintf( "%08x-%04x-%04x-%02x%02x-%04x%08x", (int)$timeLow, (int)substr($timeMid, 2) & 0xffff, mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3f) | 0x80, mt_rand(0, 0xff), $pid, $node ); return $uuid; } /** * Tokenizes a string using $separator, ignoring any instance of $separator that appears between * $leftBound and $rightBound * * @param string $data The data to tokenize * @param string $separator The token to split the data on. * @param string $leftBound The left boundary to ignore separators in. * @param string $rightBound The right boundary to ignore separators in. * @return array Array of tokens in $data. */ public static function tokenize($data, $separator = ',', $leftBound = '(', $rightBound = ')') { if (empty($data) || is_array($data)) { return $data; } $depth = 0; $offset = 0; $buffer = ''; $results = array(); $length = strlen($data); $open = false; while ($offset <= $length) { $tmpOffset = -1; $offsets = array( strpos($data, $separator, $offset), strpos($data, $leftBound, $offset), strpos($data, $rightBound, $offset) ); for ($i = 0; $i < 3; $i++) { if ($offsets[$i] !== false && ($offsets[$i] < $tmpOffset || $tmpOffset == -1)) { $tmpOffset = $offsets[$i]; } } if ($tmpOffset !== -1) { $buffer .= substr($data, $offset, ($tmpOffset - $offset)); if ($data{$tmpOffset} == $separator && $depth == 0) { $results[] = $buffer; $buffer = ''; } else { $buffer .= $data{$tmpOffset}; } if ($leftBound != $rightBound) { if ($data{$tmpOffset} == $leftBound) { $depth++; } if ($data{$tmpOffset} == $rightBound) { $depth--; } } else { if ($data{$tmpOffset} == $leftBound) { if (!$open) { $depth++; $open = true; } else { $depth--; $open = false; } } } $offset = ++$tmpOffset; } else { $results[] = $buffer . substr($data, $offset); $offset = $length + 1; } } if (empty($results) && !empty($buffer)) { $results[] = $buffer; } if (!empty($results)) { $data = array_map('trim', $results); } else { $data = array(); } return $data; } /** * Replaces variable placeholders inside a $str with any given $data. Each key in the $data array * corresponds to a variable placeholder name in $str. * Example: `String::insert(':name is :age years old.', array('name' => 'Bob', '65'));` * Returns: Bob is 65 years old. * * Available $options are: * * - before: The character or string in front of the name of the variable placeholder (Defaults to `:`) * - after: The character or string after the name of the variable placeholder (Defaults to null) * - escape: The character or string used to escape the before character / string (Defaults to `\`) * - format: A regex to use for matching variable placeholders. Default is: `/(?<!\\)\:%s/` * (Overwrites before, after, breaks escape / clean) * - clean: A boolean or array with instructions for String::cleanInsert * * @param string $str A string containing variable placeholders * @param string $data A key => val array where each key stands for a placeholder variable name * to be replaced with val * @param string $options An array of options, see description above * @return string */ public static function insert($str, $data, $options = array()) { $defaults = array( 'before' => ':', 'after' => null, 'escape' => '\\', 'format' => null, 'clean' => false ); $options += $defaults; $format = $options['format']; $data = (array)$data; if (empty($data)) { return ($options['clean']) ? String::cleanInsert($str, $options) : $str; } if (!isset($format)) { $format = sprintf( '/(?<!%s)%s%%s%s/', preg_quote($options['escape'], '/'), str_replace('%', '%%', preg_quote($options['before'], '/')), str_replace('%', '%%', preg_quote($options['after'], '/')) ); } if (strpos($str, '?') !== false && is_numeric(key($data))) { $offset = 0; while (($pos = strpos($str, '?', $offset)) !== false) { $val = array_shift($data); $offset = $pos + strlen($val); $str = substr_replace($str, $val, $pos, 1); } return ($options['clean']) ? String::cleanInsert($str, $options) : $str; } else { asort($data); $hashKeys = array(); foreach ($data as $key => $value) { $hashKeys[] = crc32($key); } $tempData = array_combine(array_keys($data), array_values($hashKeys)); krsort($tempData); foreach ($tempData as $key => $hashVal) { $key = sprintf($format, preg_quote($key, '/')); $str = preg_replace($key, $hashVal, $str); } $dataReplacements = array_combine($hashKeys, array_values($data)); foreach ($dataReplacements as $tmpHash => $tmpValue) { $tmpValue = (is_array($tmpValue)) ? '' : $tmpValue; $str = str_replace($tmpHash, $tmpValue, $str); } } if (!isset($options['format']) && isset($options['before'])) { $str = str_replace($options['escape'].$options['before'], $options['before'], $str); } return ($options['clean']) ? String::cleanInsert($str, $options) : $str; } /** * Cleans up a String::insert() formated string with given $options depending on the 'clean' key in * $options. The default method used is text but html is also available. The goal of this function * is to replace all whitespace and uneeded markup around placeholders that did not get replaced * by String::insert(). * * @param string $str * @param string $options * @return string * @see String::insert() */ public static function cleanInsert($str, $options) { $clean = $options['clean']; if (!$clean) { return $str; } if ($clean === true) { $clean = array('method' => 'text'); } if (!is_array($clean)) { $clean = array('method' => $options['clean']); } switch ($clean['method']) { case 'html': $clean = array_merge(array( 'word' => '[\w,.]+', 'andText' => true, 'replacement' => '', ), $clean); $kleenex = sprintf( '/[\s]*[a-z]+=(")(%s%s%s[\s]*)+\\1/i', preg_quote($options['before'], '/'), $clean['word'], preg_quote($options['after'], '/') ); $str = preg_replace($kleenex, $clean['replacement'], $str); if ($clean['andText']) { $options['clean'] = array('method' => 'text'); $str = String::cleanInsert($str, $options); } break; case 'text': $clean = array_merge(array( 'word' => '[\w,.]+', 'gap' => '[\s]*(?:(?:and|or)[\s]*)?', 'replacement' => '', ), $clean); $kleenex = sprintf( '/(%s%s%s%s|%s%s%s%s)/', preg_quote($options['before'], '/'), $clean['word'], preg_quote($options['after'], '/'), $clean['gap'], $clean['gap'], preg_quote($options['before'], '/'), $clean['word'], preg_quote($options['after'], '/') ); $str = preg_replace($kleenex, $clean['replacement'], $str); break; } return $str; } /** * Wraps text to a specific width, can optionally wrap at word breaks. * * ### Options * * - `width` The width to wrap to. Defaults to 72 * - `wordWrap` Only wrap on words breaks (spaces) Defaults to true. * - `indent` String to indent with. Defaults to null. * - `indentAt` 0 based index to start indenting at. Defaults to 0. * * @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 Formatted text. */ public static function wrap($text, $options = array()) { if (is_numeric($options)) { $options = array('width' => $options); } $options += array('width' => 72, 'wordWrap' => true, 'indent' => null, 'indentAt' => 0); if ($options['wordWrap']) { $wrapped = wordwrap($text, $options['width'], "\n"); } else { $wrapped = trim(chunk_split($text, $options['width'] - 1, "\n")); } if (!empty($options['indent'])) { $chunks = explode("\n", $wrapped); for ($i = $options['indentAt'], $len = count($chunks); $i < $len; $i++) { $chunks[$i] = $options['indent'] . $chunks[$i]; } $wrapped = implode("\n", $chunks); } return $wrapped; } }
0001-bee
trunk/cakephp2/lib/Cake/Utility/String.php
PHP
gpl3
10,174
<?php /** * Convenience class for handling directories. * * 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.Utility * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Folder structure browser, lists folders and files. * Provides an Object interface for Common directory related tasks. * * @package Cake.Utility */ class Folder { /** * Path to Folder. * * @var string */ public $path = null; /** * Sortedness. Whether or not list results * should be sorted by name. * * @var boolean */ public $sort = false; /** * Mode to be used on create. Does nothing on windows platforms. * * @var integer */ public $mode = 0755; /** * Holds messages from last method. * * @var array */ protected $_messages = array(); /** * Holds errors from last method. * * @var array */ protected $_errors = array(); /** * Holds array of complete directory paths. * * @var array */ protected $_directories; /** * Holds array of complete file paths. * * @var array */ protected $_files; /** * Constructor. * * @param string $path Path to folder * @param boolean $create Create folder if not found * @param mixed $mode Mode (CHMOD) to apply to created folder, false to ignore */ public function __construct($path = false, $create = false, $mode = false) { if (empty($path)) { $path = TMP; } if ($mode) { $this->mode = $mode; } if (!file_exists($path) && $create === true) { $this->create($path, $this->mode); } if (!Folder::isAbsolute($path)) { $path = realpath($path); } if (!empty($path)) { $this->cd($path); } } /** * Return current path. * * @return string Current path */ public function pwd() { return $this->path; } /** * Change directory to $path. * * @param string $path Path to the directory to change to * @return string The new path. Returns false on failure */ public function cd($path) { $path = $this->realpath($path); if (is_dir($path)) { return $this->path = $path; } return false; } /** * Returns an array of the contents of the current directory. * The returned array holds two arrays: One of directories and one of files. * * @param boolean $sort Whether you want the results sorted, set this and the sort property * to false to get unsorted results. * @param mixed $exceptions Either an array or boolean true will not grab dot files * @param boolean $fullPath True returns the full path * @return mixed Contents of current directory as an array, an empty array on failure */ public function read($sort = true, $exceptions = false, $fullPath = false) { $dirs = $files = array(); if (!$this->pwd()) { return array($dirs, $files); } if (is_array($exceptions)) { $exceptions = array_flip($exceptions); } $skipHidden = isset($exceptions['.']) || $exceptions === true; try { $iterator = new DirectoryIterator($this->path); } catch (UnexpectedValueException $e) { return array($dirs, $files); } foreach ($iterator as $item) { if ($item->isDot()) { continue; } $name = $item->getFileName(); if ($skipHidden && $name[0] === '.' || isset($exceptions[$name])) { continue; } if ($fullPath) { $name = $item->getPathName(); } if ($item->isDir()) { $dirs[] = $name; } else { $files[] = $name; } } if ($sort || $this->sort) { sort($dirs); sort($files); } return array($dirs, $files); } /** * Returns an array of all matching files in current directory. * * @param string $regexpPattern Preg_match pattern (Defaults to: .*) * @param boolean $sort Whether results should be sorted. * @return array Files that match given pattern */ public function find($regexpPattern = '.*', $sort = false) { list($dirs, $files) = $this->read($sort); return array_values(preg_grep('/^' . $regexpPattern . '$/i', $files)); ; } /** * Returns an array of all matching files in and below current directory. * * @param string $pattern Preg_match pattern (Defaults to: .*) * @param boolean $sort Whether results should be sorted. * @return array Files matching $pattern */ public function findRecursive($pattern = '.*', $sort = false) { if (!$this->pwd()) { return array(); } $startsOn = $this->path; $out = $this->_findRecursive($pattern, $sort); $this->cd($startsOn); return $out; } /** * Private helper function for findRecursive. * * @param string $pattern Pattern to match against * @param boolean $sort Whether results should be sorted. * @return array Files matching pattern */ protected function _findRecursive($pattern, $sort = false) { list($dirs, $files) = $this->read($sort); $found = array(); foreach ($files as $file) { if (preg_match('/^' . $pattern . '$/i', $file)) { $found[] = Folder::addPathElement($this->path, $file); } } $start = $this->path; foreach ($dirs as $dir) { $this->cd(Folder::addPathElement($start, $dir)); $found = array_merge($found, $this->findRecursive($pattern, $sort)); } return $found; } /** * Returns true if given $path is a Windows path. * * @param string $path Path to check * @return boolean true if windows path, false otherwise */ public static function isWindowsPath($path) { return (preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) == '\\\\'); } /** * Returns true if given $path is an absolute path. * * @param string $path Path to check * @return boolean true if path is absolute. */ public static function isAbsolute($path) { return !empty($path) && ($path[0] === '/' || preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) == '\\\\'); } /** * Returns a correct set of slashes for given $path. (\\ for Windows paths and / for other paths.) * * @param string $path Path to check * @return string Set of slashes ("\\" or "/") */ public static function normalizePath($path) { return Folder::correctSlashFor($path); } /** * Returns a correct set of slashes for given $path. (\\ for Windows paths and / for other paths.) * * @param string $path Path to check * @return string Set of slashes ("\\" or "/") */ public static function correctSlashFor($path) { return (Folder::isWindowsPath($path)) ? '\\' : '/'; } /** * Returns $path with added terminating slash (corrected for Windows or other OS). * * @param string $path Path to check * @return string Path with ending slash */ public static function slashTerm($path) { if (Folder::isSlashTerm($path)) { return $path; } return $path . Folder::correctSlashFor($path); } /** * Returns $path with $element added, with correct slash in-between. * * @param string $path Path * @param string $element Element to and at end of path * @return string Combined path */ public static function addPathElement($path, $element) { return rtrim($path, DS) . DS . $element; } /** * Returns true if the File is in a given CakePath. * * @param string $path The path to check. * @return boolean */ public function inCakePath($path = '') { $dir = substr(Folder::slashTerm(ROOT), 0, -1); $newdir = $dir . $path; return $this->inPath($newdir); } /** * Returns true if the File is in given path. * * @param string $path The path to check that the current pwd() resides with in. * @param boolean $reverse * @return boolean */ public function inPath($path = '', $reverse = false) { $dir = Folder::slashTerm($path); $current = Folder::slashTerm($this->pwd()); if (!$reverse) { $return = preg_match('/^(.*)' . preg_quote($dir, '/') . '(.*)/', $current); } else { $return = preg_match('/^(.*)' . preg_quote($current, '/') . '(.*)/', $dir); } return (bool)$return; } /** * Change the mode on a directory structure recursively. This includes changing the mode on files as well. * * @param string $path The path to chmod * @param integer $mode octal value 0755 * @param boolean $recursive chmod recursively, set to false to only change the current directory. * @param array $exceptions array of files, directories to skip * @return boolean Returns TRUE on success, FALSE on failure */ public function chmod($path, $mode = false, $recursive = true, $exceptions = array()) { if (!$mode) { $mode = $this->mode; } if ($recursive === false && is_dir($path)) { if (@chmod($path, intval($mode, 8))) { $this->_messages[] = __d('cake_dev', '%s changed to %s', $path, $mode); return true; } $this->_errors[] = __d('cake_dev', '%s NOT changed to %s', $path, $mode); return false; } if (is_dir($path)) { $paths = $this->tree($path); foreach ($paths as $type) { foreach ($type as $key => $fullpath) { $check = explode(DS, $fullpath); $count = count($check); if (in_array($check[$count - 1], $exceptions)) { continue; } if (@chmod($fullpath, intval($mode, 8))) { $this->_messages[] = __d('cake_dev', '%s changed to %s', $fullpath, $mode); } else { $this->_errors[] = __d('cake_dev', '%s NOT changed to %s', $fullpath, $mode); } } } if (empty($this->_errors)) { return true; } } return false; } /** * Returns an array of nested directories and files in each directory * * @param string $path the directory path to build the tree from * @param mixed $exceptions Array of files to exclude, defaults to excluding hidden files. * @param string $type either file or dir. null returns both files and directories * @return mixed array of nested directories and files in each directory */ public function tree($path = null, $exceptions = true, $type = null) { if ($path == null) { $path = $this->path; } $files = array(); $directories = array($path); $skipHidden = false; if ($exceptions === false) { $skipHidden = true; } if (is_array($exceptions)) { $exceptions = array_flip($exceptions); } try { $directory = new RecursiveDirectoryIterator($path); $iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST); } catch (UnexpectedValueException $e) { if ($type === null) { return array(array(), array()); } return array(); } foreach ($iterator as $item) { $name = $item->getFileName(); if ($skipHidden && $name[0] === '.' || isset($exceptions[$name])) { continue; } if ($item->isFile()) { $files[] = $item->getPathName(); } else if ($item->isDir() && !in_array($name, array('.', '..'))) { $directories[] = $item->getPathName(); } } if ($type === null) { return array($directories, $files); } if ($type === 'dir') { return $directories; } return $files; } /** * Private method to list directories and files in each directory * * @param string $path The Path to read. * @param mixed $exceptions Array of files to exclude from the read that will be performed. * @return void */ protected function _tree($path, $exceptions) { $this->path = $path; list($dirs, $files) = $this->read(false, $exceptions, true); $this->_directories = array_merge($this->_directories, $dirs); $this->_files = array_merge($this->_files, $files); } /** * Create a directory structure recursively. Can be used to create * deep path structures like `/foo/bar/baz/shoe/horn` * * @param string $pathname The directory structure to create * @param integer $mode octal value 0755 * @return boolean Returns TRUE on success, FALSE on failure */ public function create($pathname, $mode = false) { if (is_dir($pathname) || empty($pathname)) { return true; } if (!$mode) { $mode = $this->mode; } if (is_file($pathname)) { $this->_errors[] = __d('cake_dev', '%s is a file', $pathname); return false; } $pathname = rtrim($pathname, DS); $nextPathname = substr($pathname, 0, strrpos($pathname, DS)); if ($this->create($nextPathname, $mode)) { if (!file_exists($pathname)) { $old = umask(0); if (mkdir($pathname, $mode)) { umask($old); $this->_messages[] = __d('cake_dev', '%s created', $pathname); return true; } else { umask($old); $this->_errors[] = __d('cake_dev', '%s NOT created', $pathname); return false; } } } return false; } /** * Returns the size in bytes of this Folder and its contents. * * @return integer size in bytes of current folder */ public function dirsize() { $size = 0; $directory = Folder::slashTerm($this->path); $stack = array($directory); $count = count($stack); for ($i = 0, $j = $count; $i < $j; ++$i) { if (is_file($stack[$i])) { $size += filesize($stack[$i]); } elseif (is_dir($stack[$i])) { $dir = dir($stack[$i]); if ($dir) { while (false !== ($entry = $dir->read())) { if ($entry === '.' || $entry === '..') { continue; } $add = $stack[$i] . $entry; if (is_dir($stack[$i] . $entry)) { $add = Folder::slashTerm($add); } $stack[] = $add; } $dir->close(); } } $j = count($stack); } return $size; } /** * Recursively Remove directories if the system allows. * * @param string $path Path of directory to delete * @return boolean Success */ public function delete($path = null) { if (!$path) { $path = $this->pwd(); } if (!$path) { return null; } $path = Folder::slashTerm($path); if (is_dir($path) === true) { $normalFiles = glob($path . '*'); $hiddenFiles = glob($path . '\.?*'); $normalFiles = $normalFiles ? $normalFiles : array(); $hiddenFiles = $hiddenFiles ? $hiddenFiles : array(); $files = array_merge($normalFiles, $hiddenFiles); if (is_array($files)) { foreach ($files as $file) { if (preg_match('/(\.|\.\.)$/', $file)) { continue; } if (is_file($file) === true) { if (@unlink($file)) { $this->_messages[] = __d('cake_dev', '%s removed', $file); } else { $this->_errors[] = __d('cake_dev', '%s NOT removed', $file); } } elseif (is_dir($file) === true && $this->delete($file) === false) { return false; } } } $path = substr($path, 0, strlen($path) - 1); if (rmdir($path) === false) { $this->_errors[] = __d('cake_dev', '%s NOT removed', $path); return false; } else { $this->_messages[] = __d('cake_dev', '%s removed', $path); } } return true; } /** * Recursive directory copy. * * ### Options * * - `to` The directory to copy to. * - `from` The directory to copy from, this will cause a cd() to occur, changing the results of pwd(). * - `mode` The mode to copy the files/directories with. * - `skip` Files/directories to skip. * * @param mixed $options Either an array of options (see above) or a string of the destination directory. * @return boolean Success */ public function copy($options = array()) { if (!$this->pwd()) { return false; } $to = null; if (is_string($options)) { $to = $options; $options = array(); } $options = array_merge(array('to' => $to, 'from' => $this->path, 'mode' => $this->mode, 'skip' => array()), $options); $fromDir = $options['from']; $toDir = $options['to']; $mode = $options['mode']; if (!$this->cd($fromDir)) { $this->_errors[] = __d('cake_dev', '%s not found', $fromDir); return false; } if (!is_dir($toDir)) { $this->create($toDir, $mode); } if (!is_writable($toDir)) { $this->_errors[] = __d('cake_dev', '%s not writable', $toDir); return false; } $exceptions = array_merge(array('.', '..', '.svn'), $options['skip']); if ($handle = @opendir($fromDir)) { while (false !== ($item = readdir($handle))) { if (!in_array($item, $exceptions)) { $from = Folder::addPathElement($fromDir, $item); $to = Folder::addPathElement($toDir, $item); if (is_file($from)) { if (copy($from, $to)) { chmod($to, intval($mode, 8)); touch($to, filemtime($from)); $this->_messages[] = __d('cake_dev', '%s copied to %s', $from, $to); } else { $this->_errors[] = __d('cake_dev', '%s NOT copied to %s', $from, $to); } } if (is_dir($from) && !file_exists($to)) { $old = umask(0); if (mkdir($to, $mode)) { umask($old); $old = umask(0); chmod($to, $mode); umask($old); $this->_messages[] = __d('cake_dev', '%s created', $to); $options = array_merge($options, array('to'=> $to, 'from'=> $from)); $this->copy($options); } else { $this->_errors[] = __d('cake_dev', '%s not created', $to); } } } } closedir($handle); } else { return false; } if (!empty($this->_errors)) { return false; } return true; } /** * Recursive directory move. * * ### Options * * - `to` The directory to copy to. * - `from` The directory to copy from, this will cause a cd() to occur, changing the results of pwd(). * - `chmod` The mode to copy the files/directories with. * - `skip` Files/directories to skip. * * @param array $options (to, from, chmod, skip) * @return boolean Success */ public function move($options) { $to = null; if (is_string($options)) { $to = $options; $options = (array)$options; } $options = array_merge( array('to' => $to, 'from' => $this->path, 'mode' => $this->mode, 'skip' => array()), $options ); if ($this->copy($options)) { if ($this->delete($options['from'])) { return (bool)$this->cd($options['to']); } } return false; } /** * get messages from latest method * * @return array */ public function messages() { return $this->_messages; } /** * get error from latest method * * @return array */ public function errors() { return $this->_errors; } /** * Get the real path (taking ".." and such into account) * * @param string $path Path to resolve * @return string The resolved path */ public function realpath($path) { $path = str_replace('/', DS, trim($path)); if (strpos($path, '..') === false) { if (!Folder::isAbsolute($path)) { $path = Folder::addPathElement($this->path, $path); } return $path; } $parts = explode(DS, $path); $newparts = array(); $newpath = ''; if ($path[0] === DS) { $newpath = DS; } while (($part = array_shift($parts)) !== NULL) { if ($part === '.' || $part === '') { continue; } if ($part === '..') { if (!empty($newparts)) { array_pop($newparts); continue; } else { return false; } } $newparts[] = $part; } $newpath .= implode(DS, $newparts); return Folder::slashTerm($newpath); } /** * Returns true if given $path ends in a slash (i.e. is slash-terminated). * * @param string $path Path to check * @return boolean true if path ends with slash, false otherwise */ public static function isSlashTerm($path) { $lastChar = $path[strlen($path) - 1]; return $lastChar === '/' || $lastChar === '\\'; } }
0001-bee
trunk/cakephp2/lib/Cake/Utility/Folder.php
PHP
gpl3
19,272
<?php App::import('Model', 'ConnectionManager'); /** * Washes strings from unwanted noise. * * Helpful methods to make unsafe strings usable. * * 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.Utility * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Data Sanitization. * * Removal of alpahnumeric characters, SQL-safe slash-added strings, HTML-friendly strings, * and all of the above on arrays. * * @package Cake.Utility */ class Sanitize { /** * Removes any non-alphanumeric characters. * * @param string $string String to sanitize * @param array $allowed An array of additional characters that are not to be removed. * @return string Sanitized string */ public static function paranoid($string, $allowed = array()) { $allow = null; if (!empty($allowed)) { foreach ($allowed as $value) { $allow .= "\\$value"; } } if (is_array($string)) { $cleaned = array(); foreach ($string as $key => $clean) { $cleaned[$key] = preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $clean); } } else { $cleaned = preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $string); } return $cleaned; } /** * Makes a string SQL-safe. * * @param string $string String to sanitize * @param string $connection Database connection being used * @return string SQL safe string */ public static function escape($string, $connection = 'default') { $db = ConnectionManager::getDataSource($connection); if (is_numeric($string) || $string === null || is_bool($string)) { return $string; } $string = substr($db->value($string), 1); $string = substr($string, 0, -1); return $string; } /** * Returns given string safe for display as HTML. Renders entities. * * strip_tags() does not validating HTML syntax or structure, so it might strip whole passages * with broken HTML. * * ### Options: * * - remove (boolean) if true strips all HTML tags before encoding * - charset (string) the charset used to encode the string * - quotes (int) see http://php.net/manual/en/function.htmlentities.php * - double (boolean) doube encode html entities * * @param string $string String from where to strip tags * @param array $options Array of options to use. * @return string Sanitized string */ public static function html($string, $options = array()) { static $defaultCharset = false; if ($defaultCharset === false) { $defaultCharset = Configure::read('App.encoding'); if ($defaultCharset === null) { $defaultCharset = 'UTF-8'; } } $default = array( 'remove' => false, 'charset' => $defaultCharset, 'quotes' => ENT_QUOTES, 'double' => true ); $options = array_merge($default, $options); if ($options['remove']) { $string = strip_tags($string); } return htmlentities($string, $options['quotes'], $options['charset'], $options['double']); } /** * Strips extra whitespace from output * * @param string $str String to sanitize * @return string whitespace sanitized string */ public static function stripWhitespace($str) { $r = preg_replace('/[\n\r\t]+/', '', $str); return preg_replace('/\s{2,}/u', ' ', $r); } /** * Strips image tags from output * * @param string $str String to sanitize * @return string Sting with images stripped. */ public static function stripImages($str) { $str = preg_replace('/(<a[^>]*>)(<img[^>]+alt=")([^"]*)("[^>]*>)(<\/a>)/i', '$1$3$5<br />', $str); $str = preg_replace('/(<img[^>]+alt=")([^"]*)("[^>]*>)/i', '$2<br />', $str); $str = preg_replace('/<img[^>]*>/i', '', $str); return $str; } /** * Strips scripts and stylesheets from output * * @param string $str String to sanitize * @return string String with <script>, <style>, <link>, <img> elements removed. */ public static function stripScripts($str) { return preg_replace('/(<link[^>]+rel="[^"]*stylesheet"[^>]*>|<img[^>]*>|style="[^"]*")|<script[^>]*>.*?<\/script>|<style[^>]*>.*?<\/style>|<!--.*?-->/is', '', $str); } /** * Strips extra whitespace, images, scripts and stylesheets from output * * @param string $str String to sanitize * @return string sanitized string */ public static function stripAll($str) { $str = Sanitize::stripWhitespace($str); $str = Sanitize::stripImages($str); $str = Sanitize::stripScripts($str); return $str; } /** * Strips the specified tags from output. First parameter is string from * where to remove tags. All subsequent parameters are tags. * * Ex.`$clean = Sanitize::stripTags($dirty, 'b', 'p', 'div');` * * Will remove all `<b>`, `<p>`, and `<div>` tags from the $dirty string. * * @param string $str,... String to sanitize * @return string sanitized String */ public static function stripTags($str) { $params = func_get_args(); for ($i = 1, $count = count($params); $i < $count; $i++) { $str = preg_replace('/<' . $params[$i] . '\b[^>]*>/i', '', $str); $str = preg_replace('/<\/' . $params[$i] . '[^>]*>/i', '', $str); } return $str; } /** * Sanitizes given array or value for safe input. Use the options to specify * the connection to use, and what filters should be applied (with a boolean * value). Valid filters: * * - odd_spaces - removes any non space whitespace characters * - encode - Encode any html entities. Encode must be true for the `remove_html` to work. * - dollar - Escape `$` with `\$` * - carriage - Remove `\r` * - unicode - * - escape - Should the string be SQL escaped. * - backslash - * - remove_html - Strip HTML with strip_tags. `encode` must be true for this option to work. * * @param mixed $data Data to sanitize * @param mixed $options If string, DB connection being used, otherwise set of options * @return mixed Sanitized data */ public static function clean($data, $options = array()) { if (empty($data)) { return $data; } if (is_string($options)) { $options = array('connection' => $options); } else if (!is_array($options)) { $options = array(); } $options = array_merge(array( 'connection' => 'default', 'odd_spaces' => true, 'remove_html' => false, 'encode' => true, 'dollar' => true, 'carriage' => true, 'unicode' => true, 'escape' => true, 'backslash' => true ), $options); if (is_array($data)) { foreach ($data as $key => $val) { $data[$key] = Sanitize::clean($val, $options); } return $data; } else { if ($options['odd_spaces']) { $data = str_replace(chr(0xCA), '', $data); } if ($options['encode']) { $data = Sanitize::html($data, array('remove' => $options['remove_html'])); } if ($options['dollar']) { $data = str_replace("\\\$", "$", $data); } if ($options['carriage']) { $data = str_replace("\r", "", $data); } if ($options['unicode']) { $data = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $data); } if ($options['escape']) { $data = Sanitize::escape($data, $options['connection']); } if ($options['backslash']) { $data = preg_replace("/\\\(?!&amp;#|\?#)/", "\\", $data); } return $data; } } }
0001-bee
trunk/cakephp2/lib/Cake/Utility/Sanitize.php
PHP
gpl3
7,489
<?php /** * Framework debugging and PHP error-handling class * * Provides enhanced logging, stack traces, and rendering debug views * * 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.Utility * @since CakePHP(tm) v 1.2.4560 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Included libraries. * */ App::uses('CakeLog', 'Log'); App::uses('String', 'Utility'); /** * Provide custom logging and error handling. * * Debugger overrides PHP's default error handling to provide stack traces and enhanced logging * * @package Cake.Utility * @link http://book.cakephp.org/2.0/en/development/debugging.html#debugger-class */ class Debugger { /** * A list of errors generated by the application. * * @var array */ public $errors = array(); /** * The current output format. * * @var string */ protected $_outputFormat = 'js'; /** * Templates used when generating trace or error strings. Can be global or indexed by the format * value used in $_outputFormat. * * @var string */ protected $_templates = array( 'log' => array( 'trace' => '{:reference} - {:path}, line {:line}', 'error' => "{:error} ({:code}): {:description} in [{:file}, line {:line}]" ), 'js' => array( 'error' => '', 'info' => '', 'trace' => '<pre class="stack-trace">{:trace}</pre>', 'code' => '', 'context' => '', 'links' => array() ), 'html' => array( 'trace' => '<pre class="cake-error trace"><b>Trace</b> <p>{:trace}</p></pre>', 'context' => '<pre class="cake-error context"><b>Context</b> <p>{:context}</p></pre>' ), 'txt' => array( 'error' => "{:error}: {:code} :: {:description} on line {:line} of {:path}\n{:info}", 'code' => '', 'info' => '' ), 'base' => array( 'traceLine' => '{:reference} - {:path}, line {:line}', 'trace' => "Trace:\n{:trace}\n", 'context' => "Context:\n{:context}\n", ), 'log' => array(), ); /** * Holds current output data when outputFormat is false. * * @var string */ protected $_data = array(); /** * Constructor. * */ public function __construct() { $docRef = ini_get('docref_root'); if (empty($docRef) && function_exists('ini_set')) { ini_set('docref_root', 'http://php.net/'); } if (!defined('E_RECOVERABLE_ERROR')) { define('E_RECOVERABLE_ERROR', 4096); } $e = '<pre class="cake-error">'; $e .= '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-trace\')'; $e .= '.style.display = (document.getElementById(\'{:id}-trace\').style.display == '; $e .= '\'none\' ? \'\' : \'none\');"><b>{:error}</b> ({:code})</a>: {:description} '; $e .= '[<b>{:path}</b>, line <b>{:line}</b>]'; $e .= '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">'; $e .= '{:links}{:info}</div>'; $e .= '</pre>'; $this->_templates['js']['error'] = $e; $t = '<div id="{:id}-trace" class="cake-stack-trace" style="display: none;">'; $t .= '{:context}{:code}{:trace}</div>'; $this->_templates['js']['info'] = $t; $links = array(); $link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-code\')'; $link .= '.style.display = (document.getElementById(\'{:id}-code\').style.display == '; $link .= '\'none\' ? \'\' : \'none\')">Code</a>'; $links['code'] = $link; $link = '<a href="javascript:void(0);" onclick="document.getElementById(\'{:id}-context\')'; $link .= '.style.display = (document.getElementById(\'{:id}-context\').style.display == '; $link .= '\'none\' ? \'\' : \'none\')">Context</a>'; $links['context'] = $link; $this->_templates['js']['links'] = $links; $this->_templates['js']['context'] = '<pre id="{:id}-context" class="cake-context" '; $this->_templates['js']['context'] .= 'style="display: none;">{:context}</pre>'; $this->_templates['js']['code'] = '<pre id="{:id}-code" class="cake-code-dump" '; $this->_templates['js']['code'] .= 'style="display: none;">{:code}</pre>'; $e = '<pre class="cake-error"><b>{:error}</b> ({:code}) : {:description} '; $e .= '[<b>{:path}</b>, line <b>{:line}]</b></pre>'; $this->_templates['html']['error'] = $e; $this->_templates['html']['context'] = '<pre class="cake-context"><b>Context</b> '; $this->_templates['html']['context'] .= '<p>{:context}</p></pre>'; } /** * Returns a reference to the Debugger singleton object instance. * * @param string $class * @return object */ public static function &getInstance($class = null) { static $instance = array(); if (!empty($class)) { if (!$instance || strtolower($class) != strtolower(get_class($instance[0]))) { $instance[0] = new $class(); } } if (!$instance) { $instance[0] = new Debugger(); } return $instance[0]; } /** * Recursively formats and outputs the contents of the supplied variable. * * * @param mixed $var the variable to dump * @return void * @see Debugger::exportVar() * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::dump */ public static function dump($var) { pr(self::exportVar($var)); } /** * Creates an entry in the log file. The log entry will contain a stack trace from where it was called. * as well as export the variable using exportVar. By default the log is written to the debug log. * * @param mixed $var Variable or content to log * @param integer $level type of log to use. Defaults to LOG_DEBUG * @return void * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::log */ public static function log($var, $level = LOG_DEBUG) { $source = self::trace(array('start' => 1)) . "\n"; CakeLog::write($level, "\n" . $source . self::exportVar($var)); } /** * Overrides PHP's default error handling. * * @param integer $code Code of error * @param string $description Error description * @param string $file File on which error occurred * @param integer $line Line that triggered the error * @param array $context Context * @return boolean true if error was handled * @deprecated This function is supersceeded by Debugger::outputError() */ public static function showError($code, $description, $file = null, $line = null, $context = null) { $_this = Debugger::getInstance(); if (empty($file)) { $file = '[internal]'; } if (empty($line)) { $line = '??'; } $path = self::trimPath($file); $info = compact('code', 'description', 'file', 'line'); if (!in_array($info, $_this->errors)) { $_this->errors[] = $info; } else { return; } switch ($code) { case E_PARSE: case E_ERROR: case E_CORE_ERROR: case E_COMPILE_ERROR: case E_USER_ERROR: $error = 'Fatal Error'; $level = LOG_ERROR; break; case E_WARNING: case E_USER_WARNING: case E_COMPILE_WARNING: case E_RECOVERABLE_ERROR: $error = 'Warning'; $level = LOG_WARNING; break; case E_NOTICE: case E_USER_NOTICE: $error = 'Notice'; $level = LOG_NOTICE; break; default: return; break; } $data = compact( 'level', 'error', 'code', 'description', 'file', 'path', 'line', 'context' ); echo $_this->outputError($data); if ($error == 'Fatal Error') { exit(); } return true; } /** * Outputs a stack trace based on the supplied options. * * ### Options * * - `depth` - The number of stack frames to return. Defaults to 999 * - `format` - The format you want the return. Defaults to the currently selected format. If * format is 'array' or 'points' the return will be an array. * - `args` - Should arguments for functions be shown? If true, the arguments for each method call * will be displayed. * - `start` - The stack frame to start generating a trace from. Defaults to 0 * * @param array $options Format for outputting stack trace * @return mixed Formatted stack trace * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::trace */ public static function trace($options = array()) { $_this = Debugger::getInstance(); $defaults = array( 'depth' => 999, 'format' => $_this->_outputFormat, 'args' => false, 'start' => 0, 'scope' => null, 'exclude' => null ); $options += $defaults; $backtrace = debug_backtrace(); $count = count($backtrace); $back = array(); $_trace = array( 'line' => '??', 'file' => '[internal]', 'class' => null, 'function' => '[main]' ); for ($i = $options['start']; $i < $count && $i < $options['depth']; $i++) { $trace = array_merge(array('file' => '[internal]', 'line' => '??'), $backtrace[$i]); if (isset($backtrace[$i + 1])) { $next = array_merge($_trace, $backtrace[$i + 1]); $reference = $next['function']; if (!empty($next['class'])) { $reference = $next['class'] . '::' . $reference . '('; if ($options['args'] && isset($next['args'])) { $args = array(); foreach ($next['args'] as $arg) { $args[] = Debugger::exportVar($arg); } $reference .= join(', ', $args); } $reference .= ')'; } } else { $reference = '[main]'; } if (in_array($reference, array('call_user_func_array', 'trigger_error'))) { continue; } if ($options['format'] == 'points' && $trace['file'] != '[internal]') { $back[] = array('file' => $trace['file'], 'line' => $trace['line']); } elseif ($options['format'] == 'array') { $back[] = $trace; } else { if (isset($_this->_templates[$options['format']]['traceLine'])) { $tpl = $_this->_templates[$options['format']]['traceLine']; } else { $tpl = $_this->_templates['base']['traceLine']; } $trace['path'] = self::trimPath($trace['file']); $trace['reference'] = $reference; unset($trace['object'], $trace['args']); $back[] = String::insert($tpl, $trace, array('before' => '{:', 'after' => '}')); } } if ($options['format'] == 'array' || $options['format'] == 'points') { return $back; } return implode("\n", $back); } /** * Shortens file paths by replacing the application base path with 'APP', and the CakePHP core * path with 'CORE'. * * @param string $path Path to shorten * @return string Normalized path */ public static function trimPath($path) { if (!defined('CAKE_CORE_INCLUDE_PATH') || !defined('APP')) { return $path; } if (strpos($path, APP) === 0) { return str_replace(APP, 'APP' . DS, $path); } elseif (strpos($path, CAKE_CORE_INCLUDE_PATH) === 0) { return str_replace(CAKE_CORE_INCLUDE_PATH, 'CORE', $path); } elseif (strpos($path, ROOT) === 0) { return str_replace(ROOT, 'ROOT', $path); } if (strpos($path, CAKE) === 0) { return str_replace($corePath, 'CORE' . DS, $path); } return $path; } /** * Grabs an excerpt from a file and highlights a given line of code. * * Usage: * * `Debugger::excerpt('/path/to/file', 100, 4);` * * The above would return an array of 8 items. The 4th item would be the provided line, * and would be wrapped in `<span class="code-highlight"></span>`. All of the lines * are processed with highlight_string() as well, so they have basic PHP syntax highlighting * applied. * * @param string $file Absolute path to a PHP file * @param integer $line Line number to highlight * @param integer $context Number of lines of context to extract above and below $line * @return array Set of lines highlighted * @see http://php.net/highlight_string * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::excerpt */ public static function excerpt($file, $line, $context = 2) { $lines = array(); if (!file_exists($file)) { return array(); } $data = @explode("\n", file_get_contents($file)); if (empty($data) || !isset($data[$line])) { return; } for ($i = $line - ($context + 1); $i < $line + $context; $i++) { if (!isset($data[$i])) { continue; } $string = str_replace(array("\r\n", "\n"), "", highlight_string($data[$i], true)); if ($i == $line) { $lines[] = '<span class="code-highlight">' . $string . '</span>'; } else { $lines[] = $string; } } return $lines; } /** * Converts a variable to a string for debug output. * * *Note:* The following keys will have their contents replaced with * `*****`: * * - password * - login * - host * - database * - port * - prefix * - schema * * This is done to protect database credentials, which could be accidentally * shown in an error message if CakePHP is deployed in development mode. * * @param string $var Variable to convert * @param integer $recursion * @return string Variable as a formatted string * @link http://book.cakephp.org/2.0/en/development/debugging.html#Debugger::exportVar */ public static function exportVar($var, $recursion = 0) { switch (strtolower(gettype($var))) { case 'boolean': return ($var) ? 'true' : 'false'; break; case 'integer': case 'double': return $var; break; case 'string': if (trim($var) == "") { return '""'; } return '"' . h($var) . '"'; break; case 'object': return get_class($var) . "\n" . self::_object($var); case 'array': $var = array_merge($var, array_intersect_key(array( 'password' => '*****', 'login' => '*****', 'host' => '*****', 'database' => '*****', 'port' => '*****', 'prefix' => '*****', 'schema' => '*****' ), $var)); $out = "array("; $vars = array(); foreach ($var as $key => $val) { if ($recursion >= 0) { if (is_numeric($key)) { $vars[] = "\n\t" . self::exportVar($val, $recursion - 1); } else { $vars[] = "\n\t" . self::exportVar($key, $recursion - 1) . ' => ' . self::exportVar($val, $recursion - 1); } } } $n = null; if (!empty($vars)) { $n = "\n"; } return $out . implode(",", $vars) . "{$n})"; break; case 'resource': return strtolower(gettype($var)); break; case 'null': return 'null'; break; } } /** * Handles object to string conversion. * * @param string $var Object to convert * @return string * @see Debugger::exportVar() */ protected static function _object($var) { $out = array(); if (is_object($var)) { $className = get_class($var); $objectVars = get_object_vars($var); foreach ($objectVars as $key => $value) { if (is_object($value)) { $value = get_class($value) . ' object'; } elseif (is_array($value)) { $value = 'array'; } elseif ($value === null) { $value = 'NULL'; } elseif (in_array(gettype($value), array('boolean', 'integer', 'double', 'string', 'array', 'resource'))) { $value = Debugger::exportVar($value); } $out[] = "$className::$$key = " . $value; } } return implode("\n", $out); } /** * Get/Set the output format for Debugger error rendering. * * @param string $format The format you want errors to be output as. * Leave null to get the current format. * @return mixed Returns null when setting. Returns the current format when getting. * @throws CakeException when choosing a format that doesn't exist. */ public static function outputAs($format = null) { $self = Debugger::getInstance(); if ($format === null) { return $self->_outputFormat; } if ($format !== false && !isset($self->_templates[$format])) { throw new CakeException(__d('cake_dev', 'Invalid Debugger output format.')); } $self->_outputFormat = $format; } /** * Add an output format or update a format in Debugger. * * `Debugger::addFormat('custom', $data);` * * Where $data is an array of strings that use String::insert() variable * replacement. The template vars should be in a `{:id}` style. * An error formatter can have the following keys: * * - 'error' - Used for the container for the error message. Gets the following template * variables: `id`, `error`, `code`, `description`, `path`, `line`, `links`, `info` * - 'info' - A combination of `code`, `context` and `trace`. Will be set with * the contents of the other template keys. * - 'trace' - The container for a stack trace. Gets the following template * variables: `trace` * - 'context' - The container element for the context variables. * Gets the following templates: `id`, `context` * - 'links' - An array of HTML links that are used for creating links to other resources. * Typically this is used to create javascript links to open other sections. * Link keys, are: `code`, `context`, `help`. See the js output format for an * example. * - 'traceLine' - Used for creating lines in the stacktrace. Gets the following * template variables: `reference`, `path`, `line` * * Alternatively if you want to use a custom callback to do all the formatting, you can use * the callback key, and provide a callable: * * `Debugger::addFormat('custom', array('callback' => array($foo, 'outputError'));` * * The callback can expect two parameters. The first is an array of all * the error data. The second contains the formatted strings generated using * the other template strings. Keys like `info`, `links`, `code`, `context` and `trace` * will be present depending on the other templates in the format type. * * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for * straight HTML output, or 'txt' for unformatted text. * @param array $strings Template strings, or a callback to be used for the output format. * @return The resulting format string set. */ public static function addFormat($format, array $strings) { $self = Debugger::getInstance(); if (isset($self->_templates[$format])) { if (isset($strings['links'])) { $self->_templates[$format]['links'] = array_merge( $self->_templates[$format]['links'], $strings['links'] ); unset($strings['links']); } $self->_templates[$format] = array_merge($self->_templates[$format], $strings); } else { $self->_templates[$format] = $strings; } return $self->_templates[$format]; } /** * Switches output format, updates format strings. * Can be used to switch the active output format: * * @param string $format Format to use, including 'js' for JavaScript-enhanced HTML, 'html' for * straight HTML output, or 'txt' for unformatted text. * @param array $strings Template strings to be used for the output format. * @return string * @deprecated Use Debugger::outputAs() and Debugger::addFormat(). Will be removed * in 3.0 */ public function output($format = null, $strings = array()) { $_this = Debugger::getInstance(); $data = null; if (is_null($format)) { return Debugger::outputAs(); } if (!empty($strings)) { return Debugger::addFormat($format, $strings); } if ($format === true && !empty($_this->_data)) { $data = $_this->_data; $_this->_data = array(); $format = false; } Debugger::outputAs($format); return $data; } /** * Takes a processed array of data from an error and displays it in the chosen format. * * @param string $data * @return void */ public function outputError($data) { $defaults = array( 'level' => 0, 'error' => 0, 'code' => 0, 'description' => '', 'file' => '', 'line' => 0, 'context' => array(), 'start' => 2, ); $data += $defaults; $files = $this->trace(array('start' => $data['start'], 'format' => 'points')); $code = $this->excerpt($files[0]['file'], $files[0]['line'] - 1, 1); $trace = $this->trace(array('start' => $data['start'], 'depth' => '20')); $insertOpts = array('before' => '{:', 'after' => '}'); $context = array(); $links = array(); $info = ''; foreach ((array)$data['context'] as $var => $value) { $context[] = "\${$var}\t=\t" . $this->exportVar($value, 1); } switch ($this->_outputFormat) { case false: $this->_data[] = compact('context', 'trace') + $data; return; case 'log': $this->log(compact('context', 'trace') + $data); return; } $data['trace'] = $trace; $data['id'] = 'cakeErr' . uniqid(); $tpl = array_merge($this->_templates['base'], $this->_templates[$this->_outputFormat]); $insert = array('context' => join("\n", $context)) + $data; $detect = array('context'); if (isset($tpl['links'])) { foreach ($tpl['links'] as $key => $val) { if (in_array($key, $detect) && empty($insert[$key])) { continue; } $links[$key] = String::insert($val, $insert, $insertOpts); } } foreach (array('code', 'context', 'trace') as $key) { if (empty($$key) || !isset($tpl[$key])) { continue; } if (is_array($$key)) { $$key = join("\n", $$key); } $info .= String::insert($tpl[$key], compact($key) + $insert, $insertOpts); } $links = join(' ', $links); unset($data['context']); if (isset($tpl['callback']) && is_callable($tpl['callback'])) { return call_user_func($tpl['callback'], $data, compact('links', 'info')); } echo String::insert($tpl['error'], compact('links', 'info') + $data, $insertOpts); } /** * Verifies that the application's salt and cipher seed value has been changed from the default value. * * @return void */ public static function checkSecurityKeys() { if (Configure::read('Security.salt') == 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi') { trigger_error(__d('cake_dev', 'Please change the value of \'Security.salt\' in app/Config/core.php to a salt value specific to your application'), E_USER_NOTICE); } if (Configure::read('Security.cipherSeed') === '76859309657453542496749683645') { trigger_error(__d('cake_dev', 'Please change the value of \'Security.cipherSeed\' in app/Config/core.php to a numeric (digits only) seed value specific to your application'), E_USER_NOTICE); } } }
0001-bee
trunk/cakephp2/lib/Cake/Utility/Debugger.php
PHP
gpl3
22,094
<?php /** * Pluralize and singularize English words. * * Used by Cake's naming conventions throughout the framework. * * 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.Utility * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Pluralize and singularize English words. * * Inflector pluralizes and singularizes English nouns. * Used by Cake's naming conventions throughout the framework. * * @package Cake.Utility * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html */ class Inflector { /** * Plural inflector rules * * @var array */ protected static $_plural = array( 'rules' => array( '/(s)tatus$/i' => '\1\2tatuses', '/(quiz)$/i' => '\1zes', '/^(ox)$/i' => '\1\2en', '/([m|l])ouse$/i' => '\1ice', '/(matr|vert|ind)(ix|ex)$/i' => '\1ices', '/(x|ch|ss|sh)$/i' => '\1es', '/([^aeiouy]|qu)y$/i' => '\1ies', '/(hive)$/i' => '\1s', '/(?:([^f])fe|([lr])f)$/i' => '\1\2ves', '/sis$/i' => 'ses', '/([ti])um$/i' => '\1a', '/(p)erson$/i' => '\1eople', '/(m)an$/i' => '\1en', '/(c)hild$/i' => '\1hildren', '/(buffal|tomat)o$/i' => '\1\2oes', '/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|vir)us$/i' => '\1i', '/us$/i' => 'uses', '/(alias)$/i' => '\1es', '/(ax|cris|test)is$/i' => '\1es', '/s$/' => 's', '/^$/' => '', '/$/' => 's', ), 'uninflected' => array( '.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*sheep', 'people' ), 'irregular' => array( 'atlas' => 'atlases', 'beef' => 'beefs', 'brother' => 'brothers', 'cafe' => 'cafes', 'child' => 'children', 'corpus' => 'corpuses', 'cow' => 'cows', 'ganglion' => 'ganglions', 'genie' => 'genies', 'genus' => 'genera', 'graffito' => 'graffiti', 'hoof' => 'hoofs', 'loaf' => 'loaves', 'man' => 'men', 'money' => 'monies', 'mongoose' => 'mongooses', 'move' => 'moves', 'mythos' => 'mythoi', 'niche' => 'niches', 'numen' => 'numina', 'occiput' => 'occiputs', 'octopus' => 'octopuses', 'opus' => 'opuses', 'ox' => 'oxen', 'penis' => 'penises', 'person' => 'people', 'sex' => 'sexes', 'soliloquy' => 'soliloquies', 'testis' => 'testes', 'trilby' => 'trilbys', 'turf' => 'turfs' ) ); /** * Singular inflector rules * * @var array */ protected static $_singular = array( 'rules' => array( '/(s)tatuses$/i' => '\1\2tatus', '/^(.*)(menu)s$/i' => '\1\2', '/(quiz)zes$/i' => '\\1', '/(matr)ices$/i' => '\1ix', '/(vert|ind)ices$/i' => '\1ex', '/^(ox)en/i' => '\1', '/(alias)(es)*$/i' => '\1', '/(alumn|bacill|cact|foc|fung|nucle|radi|stimul|syllab|termin|viri?)i$/i' => '\1us', '/([ftw]ax)es/i' => '\1', '/(cris|ax|test)es$/i' => '\1is', '/(shoe|slave)s$/i' => '\1', '/(o)es$/i' => '\1', '/ouses$/' => 'ouse', '/([^a])uses$/' => '\1us', '/([m|l])ice$/i' => '\1ouse', '/(x|ch|ss|sh)es$/i' => '\1', '/(m)ovies$/i' => '\1\2ovie', '/(s)eries$/i' => '\1\2eries', '/([^aeiouy]|qu)ies$/i' => '\1y', '/([lr])ves$/i' => '\1f', '/(tive)s$/i' => '\1', '/(hive)s$/i' => '\1', '/(drive)s$/i' => '\1', '/([^fo])ves$/i' => '\1fe', '/(^analy)ses$/i' => '\1sis', '/(analy|ba|diagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => '\1\2sis', '/([ti])a$/i' => '\1um', '/(p)eople$/i' => '\1\2erson', '/(m)en$/i' => '\1an', '/(c)hildren$/i' => '\1\2hild', '/(n)ews$/i' => '\1\2ews', '/eaus$/' => 'eau', '/^(.*us)$/' => '\\1', '/s$/i' => '' ), 'uninflected' => array( '.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox', '.*sheep', '.*ss' ), 'irregular' => array( 'waves' => 'wave', 'curves' => 'curve' ) ); /** * Words that should not be inflected * * @var array */ protected static $_uninflected = array( 'Amoyese', 'bison', 'Borghese', 'bream', 'breeches', 'britches', 'buffalo', 'cantus', 'carp', 'chassis', 'clippers', 'cod', 'coitus', 'Congoese', 'contretemps', 'corps', 'debris', 'diabetes', 'djinn', 'eland', 'elk', 'equipment', 'Faroese', 'flounder', 'Foochowese', 'gallows', 'Genevese', 'Genoese', 'Gilbertese', 'graffiti', 'headquarters', 'herpes', 'hijinks', 'Hottentotese', 'information', 'innings', 'jackanapes', 'Kiplingese', 'Kongoese', 'Lucchese', 'mackerel', 'Maltese', 'media', 'mews', 'moose', 'mumps', 'Nankingese', 'news', 'nexus', 'Niasese', 'Pekingese', 'Piedmontese', 'pincers', 'Pistoiese', 'pliers', 'Portuguese', 'proceedings', 'rabies', 'rice', 'rhinoceros', 'salmon', 'Sarawakese', 'scissors', 'sea[- ]bass', 'series', 'Shavese', 'shears', 'siemens', 'species', 'swine', 'testes', 'trousers', 'trout','tuna', 'Vermontese', 'Wenchowese', 'whiting', 'wildebeest', 'Yengeese' ); /** * Default map of accented and special characters to ASCII characters * * @var array */ protected static $_transliteration = array( '/ä|æ|ǽ/' => 'ae', '/ö|œ/' => 'oe', '/ü/' => 'ue', '/Ä/' => 'Ae', '/Ü/' => 'Ue', '/Ö/' => 'Oe', '/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A', '/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a', '/Ç|Ć|Ĉ|Ċ|Č/' => 'C', '/ç|ć|ĉ|ċ|č/' => 'c', '/Ð|Ď|Đ/' => 'D', '/ð|ď|đ/' => 'd', '/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě/' => 'E', '/è|é|ê|ë|ē|ĕ|ė|ę|ě/' => 'e', '/Ĝ|Ğ|Ġ|Ģ/' => 'G', '/ĝ|ğ|ġ|ģ/' => 'g', '/Ĥ|Ħ/' => 'H', '/ĥ|ħ/' => 'h', '/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ/' => 'I', '/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı/' => 'i', '/Ĵ/' => 'J', '/ĵ/' => 'j', '/Ķ/' => 'K', '/ķ/' => 'k', '/Ĺ|Ļ|Ľ|Ŀ|Ł/' => 'L', '/ĺ|ļ|ľ|ŀ|ł/' => 'l', '/Ñ|Ń|Ņ|Ň/' => 'N', '/ñ|ń|ņ|ň|ʼn/' => 'n', '/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ/' => 'O', '/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º/' => 'o', '/Ŕ|Ŗ|Ř/' => 'R', '/ŕ|ŗ|ř/' => 'r', '/Ś|Ŝ|Ş|Š/' => 'S', '/ś|ŝ|ş|š|ſ/' => 's', '/Ţ|Ť|Ŧ/' => 'T', '/ţ|ť|ŧ/' => 't', '/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ/' => 'U', '/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ/' => 'u', '/Ý|Ÿ|Ŷ/' => 'Y', '/ý|ÿ|ŷ/' => 'y', '/Ŵ/' => 'W', '/ŵ/' => 'w', '/Ź|Ż|Ž/' => 'Z', '/ź|ż|ž/' => 'z', '/Æ|Ǽ/' => 'AE', '/ß/'=> 'ss', '/IJ/' => 'IJ', '/ij/' => 'ij', '/Œ/' => 'OE', '/ƒ/' => 'f' ); /** * Method cache array. * * @var array */ protected static $_cache = array(); /** * The initial state of Inflector so reset() works. * * @var array */ protected static $_initialState = array(); /** * Cache inflected values, and return if already available * * @param string $type Inflection type * @param string $key Original value * @param string $value Inflected value * @return string Inflected value, from cache */ protected static function _cache($type, $key, $value = false) { $key = '_' . $key; $type = '_' . $type; if ($value !== false) { self::$_cache[$type][$key] = $value; return $value; } if (!isset(self::$_cache[$type][$key])) { return false; } return self::$_cache[$type][$key]; } /** * Clears Inflectors inflected value caches. And resets the inflection * rules to the initial values. * * @return void */ public static function reset() { if (empty(self::$_initialState)) { self::$_initialState = get_class_vars('Inflector'); return; } foreach (self::$_initialState as $key => $val) { if ($key != '_initialState') { self::${$key} = $val; } } } /** * Adds custom inflection $rules, of either 'plural', 'singular' or 'transliteration' $type. * * ### Usage: * * {{{ * Inflector::rules('plural', array('/^(inflect)or$/i' => '\1ables')); * Inflector::rules('plural', array( * 'rules' => array('/^(inflect)ors$/i' => '\1ables'), * 'uninflected' => array('dontinflectme'), * 'irregular' => array('red' => 'redlings') * )); * Inflector::rules('transliteration', array('/å/' => 'aa')); * }}} * * @param string $type The type of inflection, either 'plural', 'singular' or 'transliteration' * @param array $rules Array of rules to be added. * @param boolean $reset If true, will unset default inflections for all * new rules that are being defined in $rules. * @return void */ public static function rules($type, $rules, $reset = false) { $var = '_' . $type; switch ($type) { case 'transliteration': if ($reset) { self::$_transliteration = $rules; } else { self::$_transliteration = $rules + self::$_transliteration; } break; default: foreach ($rules as $rule => $pattern) { if (is_array($pattern)) { if ($reset) { self::${$var}[$rule] = $pattern; } else { if ($rule === 'uninflected') { self::${$var}[$rule] = array_merge($pattern, self::${$var}[$rule]); } else { self::${$var}[$rule] = $pattern + self::${$var}[$rule]; } } unset($rules[$rule], self::${$var}['cache' . ucfirst($rule)]); if (isset(self::${$var}['merged'][$rule])) { unset(self::${$var}['merged'][$rule]); } if ($type === 'plural') { self::$_cache['pluralize'] = self::$_cache['tableize'] = array(); } elseif ($type === 'singular') { self::$_cache['singularize'] = array(); } } } self::${$var}['rules'] = $rules + self::${$var}['rules']; break; } } /** * Return $word in plural form. * * @param string $word Word in singular * @return string Word in plural * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::pluralize */ public static function pluralize($word) { if (isset(self::$_cache['pluralize'][$word])) { return self::$_cache['pluralize'][$word]; } if (!isset(self::$_plural['merged']['irregular'])) { self::$_plural['merged']['irregular'] = self::$_plural['irregular']; } if (!isset(self::$_plural['merged']['uninflected'])) { self::$_plural['merged']['uninflected'] = array_merge(self::$_plural['uninflected'], self::$_uninflected); } if (!isset(self::$_plural['cacheUninflected']) || !isset(self::$_plural['cacheIrregular'])) { self::$_plural['cacheUninflected'] = '(?:' . implode('|', self::$_plural['merged']['uninflected']) . ')'; self::$_plural['cacheIrregular'] = '(?:' . implode('|', array_keys(self::$_plural['merged']['irregular'])) . ')'; } if (preg_match('/(.*)\\b(' . self::$_plural['cacheIrregular'] . ')$/i', $word, $regs)) { self::$_cache['pluralize'][$word] = $regs[1] . substr($word, 0, 1) . substr(self::$_plural['merged']['irregular'][strtolower($regs[2])], 1); return self::$_cache['pluralize'][$word]; } if (preg_match('/^(' . self::$_plural['cacheUninflected'] . ')$/i', $word, $regs)) { self::$_cache['pluralize'][$word] = $word; return $word; } foreach (self::$_plural['rules'] as $rule => $replacement) { if (preg_match($rule, $word)) { self::$_cache['pluralize'][$word] = preg_replace($rule, $replacement, $word); return self::$_cache['pluralize'][$word]; } } } /** * Return $word in singular form. * * @param string $word Word in plural * @return string Word in singular * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::singularize */ public static function singularize($word) { if (isset(self::$_cache['singularize'][$word])) { return self::$_cache['singularize'][$word]; } if (!isset(self::$_singular['merged']['uninflected'])) { self::$_singular['merged']['uninflected'] = array_merge( self::$_singular['uninflected'], self::$_uninflected ); } if (!isset(self::$_singular['merged']['irregular'])) { self::$_singular['merged']['irregular'] = array_merge( self::$_singular['irregular'], array_flip(self::$_plural['irregular']) ); } if (!isset(self::$_singular['cacheUninflected']) || !isset(self::$_singular['cacheIrregular'])) { self::$_singular['cacheUninflected'] = '(?:' . join( '|', self::$_singular['merged']['uninflected']) . ')'; self::$_singular['cacheIrregular'] = '(?:' . join( '|', array_keys(self::$_singular['merged']['irregular'])) . ')'; } if (preg_match('/(.*)\\b(' . self::$_singular['cacheIrregular'] . ')$/i', $word, $regs)) { self::$_cache['singularize'][$word] = $regs[1] . substr($word, 0, 1) . substr(self::$_singular['merged']['irregular'][strtolower($regs[2])], 1); return self::$_cache['singularize'][$word]; } if (preg_match('/^(' . self::$_singular['cacheUninflected'] . ')$/i', $word, $regs)) { self::$_cache['singularize'][$word] = $word; return $word; } foreach (self::$_singular['rules'] as $rule => $replacement) { if (preg_match($rule, $word)) { self::$_cache['singularize'][$word] = preg_replace($rule, $replacement, $word); return self::$_cache['singularize'][$word]; } } self::$_cache['singularize'][$word] = $word; return $word; } /** * Returns the given lower_case_and_underscored_word as a CamelCased word. * * @param string $lowerCaseAndUnderscoredWord Word to camelize * @return string Camelized word. LikeThis. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::camelize */ public static function camelize($lowerCaseAndUnderscoredWord) { if (!($result = self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord))) { $result = str_replace(' ', '', Inflector::humanize($lowerCaseAndUnderscoredWord)); self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord, $result); } return $result; } /** * Returns the given camelCasedWord as an underscored_word. * * @param string $camelCasedWord Camel-cased word to be "underscorized" * @return string Underscore-syntaxed version of the $camelCasedWord * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::underscore */ public static function underscore($camelCasedWord) { if (!($result = self::_cache(__FUNCTION__, $camelCasedWord))) { $result = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $camelCasedWord)); self::_cache(__FUNCTION__, $camelCasedWord, $result); } return $result; } /** * Returns the given underscored_word_group as a Human Readable Word Group. * (Underscores are replaced by spaces and capitalized following words.) * * @param string $lowerCaseAndUnderscoredWord String to be made more readable * @return string Human-readable string * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::humanize */ public static function humanize($lowerCaseAndUnderscoredWord) { if (!($result = self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord))) { $result = ucwords(str_replace('_', ' ', $lowerCaseAndUnderscoredWord)); self::_cache(__FUNCTION__, $lowerCaseAndUnderscoredWord, $result); } return $result; } /** * Returns corresponding table name for given model $className. ("people" for the model class "Person"). * * @param string $className Name of class to get database table name for * @return string Name of the database table for given class * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::tableize */ public static function tableize($className) { if (!($result = self::_cache(__FUNCTION__, $className))) { $result = Inflector::pluralize(Inflector::underscore($className)); self::_cache(__FUNCTION__, $className, $result); } return $result; } /** * Returns Cake model class name ("Person" for the database table "people".) for given database table. * * @param string $tableName Name of database table to get class name for * @return string Class name * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::classify */ public static function classify($tableName) { if (!($result = self::_cache(__FUNCTION__, $tableName))) { $result = Inflector::camelize(Inflector::singularize($tableName)); self::_cache(__FUNCTION__, $tableName, $result); } return $result; } /** * Returns camelBacked version of an underscored string. * * @param string $string * @return string in variable form * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::variable */ public static function variable($string) { if (!($result = self::_cache(__FUNCTION__, $string))) { $string2 = Inflector::camelize(Inflector::underscore($string)); $replace = strtolower(substr($string2, 0, 1)); $result = preg_replace('/\\w/', $replace, $string2, 1); self::_cache(__FUNCTION__, $string, $result); } return $result; } /** * Returns a string with all spaces converted to underscores (by default), accented * characters converted to non-accented characters, and non word characters removed. * * @param string $string the string you want to slug * @param string $replacement will replace keys in map * @return string * @link http://book.cakephp.org/2.0/en/core-utility-libraries/inflector.html#Inflector::slug */ public static function slug($string, $replacement = '_') { $quotedReplacement = preg_quote($replacement, '/'); $merge = array( '/[^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ', '/\\s+/' => $replacement, sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '', ); $map = self::$_transliteration + $merge; return preg_replace(array_keys($map), array_values($map), $string); } } // Store the initial state Inflector::reset();
0001-bee
trunk/cakephp2/lib/Cake/Utility/Inflector.php
PHP
gpl3
17,814
<?php /** * Class collections. * * A repository for class objects, each registered with a key. * * 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.Utility * @since CakePHP(tm) v 0.9.2 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Class Collections. * * A repository for class objects, each registered with a key. * If you try to add an object with the same key twice, nothing will come of it. * If you need a second instance of an object, give it another key. * * @package Cake.Utility */ class ClassRegistry { /** * Names of classes with their objects. * * @var array */ protected $_objects = array(); /** * Names of class names mapped to the object in the registry. * * @var array */ protected $_map = array(); /** * Default constructor parameter settings, indexed by type * * @var array */ protected $_config = array(); /** * Return a singleton instance of the ClassRegistry. * * @return ClassRegistry instance */ public static function &getInstance() { static $instance = array(); if (!$instance) { $instance[0] = new ClassRegistry(); } return $instance[0]; } /** * Loads a class, registers the object in the registry and returns instance of the object. ClassRegistry::init() * is used as a factory for models, and handle correct injecting of settings, that assist in testing. * * Examples * Simple Use: Get a Post model instance ```ClassRegistry::init('Post');``` * * Expanded: ```array('class' => 'ClassName', 'alias' => 'AliasNameStoredInTheRegistry', 'type' => 'Model');``` * * Model Classes can accept optional ```array('id' => $id, 'table' => $table, 'ds' => $ds, 'alias' => $alias);``` * * When $class is a numeric keyed array, multiple class instances will be stored in the registry, * no instance of the object will be returned * {{{ * array( * array('class' => 'ClassName', 'alias' => 'AliasNameStoredInTheRegistry'), * array('class' => 'ClassName', 'alias' => 'AliasNameStoredInTheRegistry'), * array('class' => 'ClassName', 'alias' => 'AliasNameStoredInTheRegistry') * ); * }}} * @param mixed $class as a string or a single key => value array instance will be created, * stored in the registry and returned. * @param boolean $strict if set to true it will return false if the class was not found instead * of trying to create an AppModel * @return object instance of ClassName */ public static function init($class, $strict = false) { $_this = ClassRegistry::getInstance(); $false = false; $true = true; if (is_array($class)) { $objects = $class; if (!isset($class[0])) { $objects = array($class); } } else { $objects = array(array('class' => $class)); } $defaults = isset($_this->_config['Model']) ? $_this->_config['Model'] : array(); $count = count($objects); foreach ($objects as $key => $settings) { if (is_array($settings)) { $pluginPath = null; $settings = array_merge($defaults, $settings); $class = $settings['class']; list($plugin, $class) = pluginSplit($class); if ($plugin) { $pluginPath = $plugin . '.'; } if (empty($settings['alias'])) { $settings['alias'] = $class; } $alias = $settings['alias']; if ($model = $_this->_duplicate($alias, $class)) { $_this->map($alias, $class); return $model; } App::uses('Model', 'Model'); App::uses('AppModel', 'Model'); App::uses($plugin . 'AppModel', $pluginPath . 'Model'); App::uses($class, $pluginPath . 'Model'); if (class_exists($class)) { ${$class} = new $class($settings); if ($strict) { ${$class} = (${$class} instanceof Model) ? ${$class} : null; } } if (!isset(${$class})) { if ($strict) { return false; } elseif ($plugin && class_exists($plugin . 'AppModel')) { $appModel = $plugin . 'AppModel'; } else { $appModel = 'AppModel'; } if (!empty($appModel)) { $settings['name'] = $class; ${$class} = new $appModel($settings); } if (!isset(${$class})) { trigger_error(__d('cake_dev', '(ClassRegistry::init() could not create instance of %1$s class %2$s ', $class, $type), E_USER_WARNING); return $false; } } $_this->map($alias, $class); } elseif (is_numeric($settings)) { trigger_error(__d('cake_dev', '(ClassRegistry::init() Attempted to create instance of a class with a numeric name'), E_USER_WARNING); return $false; } } if ($count > 1) { return $true; } return ${$class}; } /** * Add $object to the registry, associating it with the name $key. * * @param string $key Key for the object in registry * @param mixed $object Object to store * @return boolean True if the object was written, false if $key already exists */ public static function addObject($key, $object) { $_this = ClassRegistry::getInstance(); $key = Inflector::underscore($key); if (!isset($_this->_objects[$key])) { $_this->_objects[$key] = $object; return true; } return false; } /** * Remove object which corresponds to given key. * * @param string $key Key of object to remove from registry * @return void */ public static function removeObject($key) { $_this = ClassRegistry::getInstance(); $key = Inflector::underscore($key); if (isset($_this->_objects[$key])) { unset($_this->_objects[$key]); } } /** * Returns true if given key is present in the ClassRegistry. * * @param string $key Key to look for * @return boolean true if key exists in registry, false otherwise */ public static function isKeySet($key) { $_this = ClassRegistry::getInstance(); $key = Inflector::underscore($key); if (isset($_this->_objects[$key])) { return true; } elseif (isset($_this->_map[$key])) { return true; } return false; } /** * Get all keys from the registry. * * @return array Set of keys stored in registry */ public static function keys() { $_this = ClassRegistry::getInstance(); return array_keys($_this->_objects); } /** * Return object which corresponds to given key. * * @param string $key Key of object to look for * @return mixed Object stored in registry or boolean false if the object does not exist. */ public static function &getObject($key) { $_this = ClassRegistry::getInstance(); $key = Inflector::underscore($key); $return = false; if (isset($_this->_objects[$key])) { $return = $_this->_objects[$key]; } else { $key = $_this->_getMap($key); if (isset($_this->_objects[$key])) { $return = $_this->_objects[$key]; } } return $return; } /** * Sets the default constructor parameter for an object type * * @param string $type Type of object. If this parameter is omitted, defaults to "Model" * @param array $param The parameter that will be passed to object constructors when objects * of $type are created * @return mixed Void if $param is being set. Otherwise, if only $type is passed, returns * the previously-set value of $param, or null if not set. */ public static function config($type, $param = array()) { $_this = ClassRegistry::getInstance(); if (empty($param) && is_array($type)) { $param = $type; $type = 'Model'; } elseif (is_null($param)) { unset($_this->_config[$type]); } elseif (empty($param) && is_string($type)) { return isset($_this->_config[$type]) ? $_this->_config[$type] : null; } $_this->_config[$type] = $param; } /** * Checks to see if $alias is a duplicate $class Object * * @param string $alias * @param string $class * @return boolean */ protected function &_duplicate($alias, $class) { $duplicate = false; if ($this->isKeySet($alias)) { $model = $this->getObject($alias); if (is_object($model) && (is_a($model, $class) || $model->alias === $class)) { $duplicate = $model; } unset($model); } return $duplicate; } /** * Add a key name pair to the registry to map name to class in the registry. * * @param string $key Key to include in map * @param string $name Key that is being mapped * @return void */ public static function map($key, $name) { $_this = ClassRegistry::getInstance(); $key = Inflector::underscore($key); $name = Inflector::underscore($name); if (!isset($_this->_map[$key])) { $_this->_map[$key] = $name; } } /** * Get all keys from the map in the registry. * * @return array Keys of registry's map */ public static function mapKeys() { $_this = ClassRegistry::getInstance(); return array_keys($_this->_map); } /** * Return the name of a class in the registry. * * @param string $key Key to find in map * @return string Mapped value */ protected function _getMap($key) { if (isset($this->_map[$key])) { return $this->_map[$key]; } } /** * Flushes all objects from the ClassRegistry. * * @return void */ public static function flush() { $_this = ClassRegistry::getInstance(); $_this->_objects = array(); $_this->_map = array(); } }
0001-bee
trunk/cakephp2/lib/Cake/Utility/ClassRegistry.php
PHP
gpl3
9,425
<?php /** * Convenience class for reading, writing and appending to 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 * @package Cake.Utility * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Included libraries. * */ App::uses('Folder', 'Utility'); /** * Convenience class for reading, writing and appending to files. * * @package Cake.Utility */ class File { /** * Folder object of the File * * @var Folder */ public $Folder = null; /** * Filename * * @var string */ public $name = null; /** * File info * * @var string */ public $info = array(); /** * Holds the file handler resource if the file is opened * * @var resource */ public $handle = null; /** * Enable locking for file reading and writing * * @var boolean */ public $lock = null; /** * Path property * * Current file's absolute path * * @var mixed null */ public $path = null; /** * Constructor * * @param string $path Path to file * @param boolean $create Create file if it does not exist (if true) * @param integer $mode Mode to apply to the folder holding the file */ public function __construct($path, $create = false, $mode = 0755) { $this->Folder = new Folder(dirname($path), $create, $mode); if (!is_dir($path)) { $this->name = basename($path); } $this->pwd(); $create && !$this->exists() && $this->safe($path) && $this->create(); } /** * Closes the current file if it is opened * */ public function __destruct() { $this->close(); } /** * Creates the File. * * @return boolean Success */ public function create() { $dir = $this->Folder->pwd(); if (is_dir($dir) && is_writable($dir) && !$this->exists()) { $old = umask(0); if (touch($this->path)) { umask($old); return true; } } return false; } /** * Opens the current file with a given $mode * * @param string $mode A valid 'fopen' mode string (r|w|a ...) * @param boolean $force If true then the file will be re-opened even if its already opened, otherwise it won't * @return boolean True on success, false on failure */ public function open($mode = 'r', $force = false) { if (!$force && is_resource($this->handle)) { return true; } clearstatcache(); if ($this->exists() === false) { if ($this->create() === false) { return false; } } $this->handle = fopen($this->path, $mode); if (is_resource($this->handle)) { return true; } return false; } /** * Return the contents of this File as a string. * * @param string $bytes where to start * @param string $mode A `fread` compatible mode. * @param boolean $force If true then the file will be re-opened even if its already opened, otherwise it won't * @return mixed string on success, false on failure */ public function read($bytes = false, $mode = 'rb', $force = false) { if ($bytes === false && $this->lock === null) { return file_get_contents($this->path); } if ($this->open($mode, $force) === false) { return false; } if ($this->lock !== null && flock($this->handle, LOCK_SH) === false) { return false; } if (is_int($bytes)) { return fread($this->handle, $bytes); } $data = ''; while (!feof($this->handle)) { $data .= fgets($this->handle, 4096); } if ($this->lock !== null) { flock($this->handle, LOCK_UN); } if ($bytes === false) { $this->close(); } return trim($data); } /** * Sets or gets the offset for the currently opened file. * * @param mixed $offset The $offset in bytes to seek. If set to false then the current offset is returned. * @param integer $seek PHP Constant SEEK_SET | SEEK_CUR | SEEK_END determining what the $offset is relative to * @return mixed True on success, false on failure (set mode), false on failure or integer offset on success (get mode) */ public function offset($offset = false, $seek = SEEK_SET) { if ($offset === false) { if (is_resource($this->handle)) { return ftell($this->handle); } } elseif ($this->open() === true) { return fseek($this->handle, $offset, $seek) === 0; } return false; } /** * Prepares a ascii string for writing. Converts line endings to the * correct terminator for the current platform. If windows "\r\n" will be used * all other platforms will use "\n" * * @param string $data Data to prepare for writing. * @param boolean $forceWindows * @return string The with converted line endings. */ public static function prepare($data, $forceWindows = false) { $lineBreak = "\n"; if (DIRECTORY_SEPARATOR == '\\' || $forceWindows === true) { $lineBreak = "\r\n"; } return strtr($data, array("\r\n" => $lineBreak, "\n" => $lineBreak, "\r" => $lineBreak)); } /** * Write given data to this File. * * @param string $data Data to write to this File. * @param string $mode Mode of writing. {@link http://php.net/fwrite See fwrite()}. * @param string $force force the file to open * @return boolean Success */ public function write($data, $mode = 'w', $force = false) { $success = false; if ($this->open($mode, $force) === true) { if ($this->lock !== null) { if (flock($this->handle, LOCK_EX) === false) { return false; } } if (fwrite($this->handle, $data) !== false) { $success = true; } if ($this->lock !== null) { flock($this->handle, LOCK_UN); } } return $success; } /** * Append given data string to this File. * * @param string $data Data to write * @param string $force force the file to open * @return boolean Success */ public function append($data, $force = false) { return $this->write($data, 'a', $force); } /** * Closes the current file if it is opened. * * @return boolean True if closing was successful or file was already closed, otherwise false */ public function close() { if (!is_resource($this->handle)) { return true; } return fclose($this->handle); } /** * Deletes the File. * * @return boolean Success */ public function delete() { clearstatcache(); if (is_resource($this->handle)) { fclose($this->handle); $this->handle = null; } if ($this->exists()) { return unlink($this->path); } return false; } /** * Returns the File info. * * @return string The File extension */ public function info() { if ($this->info == null) { $this->info = pathinfo($this->path); } if (!isset($this->info['filename'])) { $this->info['filename'] = $this->name(); } return $this->info; } /** * Returns the File extension. * * @return string The File extension */ public function ext() { if ($this->info == null) { $this->info(); } if (isset($this->info['extension'])) { return $this->info['extension']; } return false; } /** * Returns the File name without extension. * * @return string The File name without extension. */ public function name() { if ($this->info == null) { $this->info(); } if (isset($this->info['extension'])) { return basename($this->name, '.'.$this->info['extension']); } elseif ($this->name) { return $this->name; } return false; } /** * makes filename safe for saving * * @param string $name The name of the file to make safe if different from $this->name * @param string $ext The name of the extension to make safe if different from $this->ext * @return string $ext the extension of the file */ public function safe($name = null, $ext = null) { if (!$name) { $name = $this->name; } if (!$ext) { $ext = $this->ext(); } return preg_replace( "/(?:[^\w\.-]+)/", "_", basename($name, $ext)); } /** * Get md5 Checksum of file with previous check of Filesize * * @param mixed $maxsize in MB or true to force * @return string md5 Checksum {@link http://php.net/md5_file See md5_file()} */ public function md5($maxsize = 5) { if ($maxsize === true) { return md5_file($this->path); } $size = $this->size(); if ($size && $size < ($maxsize * 1024) * 1024) { return md5_file($this->path); } return false; } /** * Returns the full path of the File. * * @return string Full path to file */ public function pwd() { if (is_null($this->path)) { $this->path = $this->Folder->slashTerm($this->Folder->pwd()) . $this->name; } return $this->path; } /** * Returns true if the File exists. * * @return boolean true if it exists, false otherwise */ public function exists() { return (file_exists($this->path) && is_file($this->path)); } /** * Returns the "chmod" (permissions) of the File. * * @return string Permissions for the file */ public function perms() { if ($this->exists()) { return substr(sprintf('%o', fileperms($this->path)), -4); } return false; } /** * Returns the Filesize * * @return integer size of the file in bytes, or false in case of an error */ public function size() { if ($this->exists()) { return filesize($this->path); } return false; } /** * Returns true if the File is writable. * * @return boolean true if its writable, false otherwise */ public function writable() { return is_writable($this->path); } /** * Returns true if the File is executable. * * @return boolean true if its executable, false otherwise */ public function executable() { return is_executable($this->path); } /** * Returns true if the File is readable. * * @return boolean true if file is readable, false otherwise */ public function readable() { return is_readable($this->path); } /** * Returns the File's owner. * * @return integer the Fileowner */ public function owner() { if ($this->exists()) { return fileowner($this->path); } return false; } /** * Returns the File's group. * * @return integer the Filegroup */ public function group() { if ($this->exists()) { return filegroup($this->path); } return false; } /** * Returns last access time. * * @return integer timestamp Timestamp of last access time */ public function lastAccess() { if ($this->exists()) { return fileatime($this->path); } return false; } /** * Returns last modified time. * * @return integer timestamp Timestamp of last modification */ public function lastChange() { if ($this->exists()) { return filemtime($this->path); } return false; } /** * Returns the current folder. * * @return Folder Current folder */ public function &Folder() { return $this->Folder; } /** * Copy the File to $dest * * @param string $dest destination for the copy * @param boolean $overwrite Overwrite $dest if exists * @return boolean Succes */ public function copy($dest, $overwrite = true) { if (!$this->exists() || is_file($dest) && !$overwrite) { return false; } return copy($this->path, $dest); } }
0001-bee
trunk/cakephp2/lib/Cake/Utility/File.php
PHP
gpl3
11,142
<?php /** * Core Security * * 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.Utility * @since CakePHP(tm) v .0.10.0.1233 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('String', 'Utility'); /** * Security Library contains utility methods related to security * * @package Cake.Utility */ class Security { /** * Default hash method * * @var string */ public static $hashType = null; /** * Get allowed minutes of inactivity based on security level. * * @return integer Allowed inactivity in minutes */ public static function inactiveMins() { switch (Configure::read('Security.level')) { case 'high': return 10; break; case 'medium': return 100; break; case 'low': default: return 300; break; } } /** * Generate authorization hash. * * @return string Hash */ public static function generateAuthKey() { return Security::hash(String::uuid()); } /** * Validate authorization hash. * * @param string $authKey Authorization hash * @return boolean Success * @todo Complete implementation */ public static function validateAuthKey($authKey) { return true; } /** * Create a hash from string using given method. * Fallback on next available method. * * @param string $string String to hash * @param string $type Method to use (sha1/sha256/md5) * @param boolean $salt If true, automatically appends the application's salt * value to $string (Security.salt) * @return string Hash */ public static function hash($string, $type = null, $salt = false) { if ($salt) { if (is_string($salt)) { $string = $salt . $string; } else { $string = Configure::read('Security.salt') . $string; } } if (empty($type)) { $type = self::$hashType; } $type = strtolower($type); if ($type == 'sha1' || $type == null) { if (function_exists('sha1')) { $return = sha1($string); return $return; } $type = 'sha256'; } if ($type == 'sha256' && function_exists('mhash')) { return bin2hex(mhash(MHASH_SHA256, $string)); } if (function_exists('hash')) { return hash($type, $string); } return md5($string); } /** * Sets the default hash method for the Security object. This affects all objects using * Security::hash(). * * @param string $hash Method to use (sha1/sha256/md5) * @return void * @see Security::hash() */ public static function setHash($hash) { self::$hashType = $hash; } /** * Encrypts/Decrypts a text using the given key. * * @param string $text Encrypted string to decrypt, normal string to encrypt * @param string $key Key to use * @return string Encrypted/Decrypted string */ public static function cipher($text, $key) { if (empty($key)) { trigger_error(__d('cake_dev', 'You cannot use an empty key for Security::cipher()'), E_USER_WARNING); return ''; } srand(Configure::read('Security.cipherSeed')); $out = ''; $keyLength = strlen($key); for ($i = 0, $textLength = strlen($text); $i < $textLength; $i++) { $j = ord(substr($key, $i % $keyLength, 1)); while ($j--) { rand(0, 255); } $mask = rand(0, 255); $out .= chr(ord(substr($text, $i, 1)) ^ $mask); } srand(); return $out; } }
0001-bee
trunk/cakephp2/lib/Cake/Utility/Security.php
PHP
gpl3
3,646
<?php /** * XML handling for Cake. * * The methods in these classes enable the datasources that use XML to work. * * 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.Utility * @since CakePHP v .0.10.3.1400 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ class Xml { /** * Initialize SimpleXMLElement or DOMDocument from a given XML string, file path, URL or array. * * ### Usage: * * Building XML from a string: * * `$xml = Xml::build('<example>text</example>');` * * Building XML from string (output DOMDocument): * * `$xml = Xml::build('<example>text</example>', array('return' => 'domdocument'));` * * Building XML from a file path: * * `$xml = Xml::build('/path/to/an/xml/file.xml');` * * Building from a remote URL: * * `$xml = Xml::build('http://example.com/example.xml');` * * Building from an array: * * {{{ * $value = array( * 'tags' => array( * 'tag' => array( * array( * 'id' => '1', * 'name' => 'defect' * ), * array( * 'id' => '2', * 'name' => 'enhancement' * ) * ) * ) * ); * $xml = Xml::build($value); * }}} * * When building XML from an array ensure that there is only one top level element. * * ### Options * * - `return` Can be 'simplexml' to return object of SimpleXMLElement or 'domdocument' to return DOMDocument. * - If using array as input, you can pass `options` from Xml::fromArray. * * @param mixed $input XML string, a path to a file, an URL or an array * @param array $options The options to use * @return SimpleXMLElement|DOMDocument SimpleXMLElement or DOMDocument * @throws XmlException */ public static function build($input, $options = array()) { if (!is_array($options)) { $options = array('return' => (string)$options); } $defaults = array( 'return' => 'simplexml' ); $options = array_merge($defaults, $options); if (is_array($input) || is_object($input)) { return self::fromArray((array)$input, $options); } elseif (strpos($input, '<') !== false) { if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') { return new SimpleXMLElement($input, LIBXML_NOCDATA); } $dom = new DOMDocument(); $dom->loadXML($input); return $dom; } elseif (file_exists($input) || strpos($input, 'http://') === 0 || strpos($input, 'https://') === 0) { if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') { return new SimpleXMLElement($input, LIBXML_NOCDATA, true); } $dom = new DOMDocument(); $dom->load($input); return $dom; } elseif (!is_string($input)) { throw new XmlException(__d('cake_dev', 'Invalid input.')); } throw new XmlException(__d('cake_dev', 'XML cannot be read.')); } /** * Transform an array into a SimpleXMLElement * * ### Options * * - `format` If create childs ('tags') or attributes ('attribute'). * - `version` Version of XML document. Default is 1.0. * - `encoding` Encoding of XML document. If null remove from XML header. Default is the some of application. * - `return` If return object of SimpleXMLElement ('simplexml') or DOMDocument ('domdocument'). Default is SimpleXMLElement. * * Using the following data: * * {{{ * $value = array( * 'root' => array( * 'tag' => array( * 'id' => 1, * 'value' => 'defect', * '@' => 'description' * ) * ) * ); * }}} * * Calling `Xml::fromArray($value, 'tags');` Will generate: * * `<root><tag><id>1</id><value>defect</value>description</tag></root>` * * And calling `Xml::fromArray($value, 'attribute');` Will generate: * * `<root><tag id="1" value="defect">description</tag></root>` * * @param array $input Array with data * @param array $options The options to use * @return SimpleXMLElement|DOMDocument SimpleXMLElement or DOMDocument * @throws XmlException */ public static function fromArray($input, $options = array()) { if (!is_array($input) || count($input) !== 1) { throw new XmlException(__d('cake_dev', 'Invalid input.')); } $key = key($input); if (is_integer($key)) { throw new XmlException(__d('cake_dev', 'The key of input must be alphanumeric')); } if (!is_array($options)) { $options = array('format' => (string)$options); } $defaults = array( 'format' => 'tags', 'version' => '1.0', 'encoding' => Configure::read('App.encoding'), 'return' => 'simplexml' ); $options = array_merge($defaults, $options); $dom = new DOMDocument($options['version'], $options['encoding']); self::_fromArray($dom, $dom, $input, $options['format']); $options['return'] = strtolower($options['return']); if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') { return new SimpleXMLElement($dom->saveXML()); } return $dom; } /** * Recursive method to create childs from array * * @param DOMDocument $dom Handler to DOMDocument * @param DOMElement $node Handler to DOMElement (child) * @param array $data Array of data to append to the $node. * @param string $format Either 'attribute' or 'tags'. This determines where nested keys go. * @return void * @throws XmlException */ protected static function _fromArray($dom, $node, &$data, $format) { if (empty($data) || !is_array($data)) { return; } foreach ($data as $key => $value) { if (is_string($key)) { if (!is_array($value)) { if (is_bool($value)) { $value = (int)$value; } elseif ($value === null) { $value = ''; } $isNamespace = strpos($key, 'xmlns:'); if ($isNamespace !== false) { $node->setAttributeNS('http://www.w3.org/2000/xmlns/', $key, $value); continue; } if ($key[0] !== '@' && $format === 'tags') { $child = $dom->createElement($key, $value); $node->appendChild($child); } else { if ($key[0] === '@') { $key = substr($key, 1); } $attribute = $dom->createAttribute($key); $attribute->appendChild($dom->createTextNode($value)); $node->appendChild($attribute); } } else { if ($key[0] === '@') { throw new XmlException(__d('cake_dev', 'Invalid array')); } if (array_keys($value) === range(0, count($value) - 1)) { // List foreach ($value as $item) { $data = compact('dom', 'node', 'key', 'format'); $data['value'] = $item; self::_createChild($data); } } else { // Struct self::_createChild(compact('dom', 'node', 'key', 'value', 'format')); } } } else { throw new XmlException(__d('cake_dev', 'Invalid array')); } } } /** * Helper to _fromArray(). It will create childs of arrays * * @param array $data Array with informations to create childs * @return void */ protected static function _createChild($data) { extract($data); $childNS = $childValue = null; if (is_array($value)) { if (isset($value['@'])) { $childValue = (string)$value['@']; unset($value['@']); } if (isset($value['xmlns:'])) { $childNS = $value['xmlns:']; unset($value['xmlns:']); } } elseif (!empty($value) || $value === 0) { $childValue = (string)$value; } if ($childValue) { $child = $dom->createElement($key, $childValue); } else { $child = $dom->createElement($key); } if ($childNS) { $child->setAttribute('xmlns', $childNS); } self::_fromArray($dom, $child, $value, $format); $node->appendChild($child); } /** * Returns this XML structure as a array. * * @param SimpleXMLElement|DOMDocument|DOMNode $obj SimpleXMLElement, DOMDocument or DOMNode instance * @return array Array representation of the XML structure. * @throws XmlException */ public static function toArray($obj) { if ($obj instanceof DOMNode) { $obj = simplexml_import_dom($obj); } if (!($obj instanceof SimpleXMLElement)) { throw new XmlException(__d('cake_dev', 'The input is not instance of SimpleXMLElement, DOMDocument or DOMNode.')); } $result = array(); $namespaces = array_merge(array('' => ''), $obj->getNamespaces(true)); self::_toArray($obj, $result, '', array_keys($namespaces)); return $result; } /** * Recursive method to toArray * * @param SimpleXMLElement $xml SimpleXMLElement object * @param array $parentData Parent array with data * @param string $ns Namespace of current child * @param array $namespaces List of namespaces in XML * @return void */ protected static function _toArray($xml, &$parentData, $ns, $namespaces) { $data = array(); foreach ($namespaces as $namespace) { foreach ($xml->attributes($namespace, true) as $key => $value) { if (!empty($namespace)) { $key = $namespace . ':' . $key; } $data['@' . $key] = (string)$value; } foreach ($xml->children($namespace, true) as $child) { self::_toArray($child, $data, $namespace, $namespaces); } } $asString = trim((string)$xml); if (empty($data)) { $data = $asString; } elseif (!empty($asString)) { $data['@'] = $asString; } if (!empty($ns)) { $ns .= ':'; } $name = $ns . $xml->getName(); if (isset($parentData[$name])) { if (!is_array($parentData[$name]) || !isset($parentData[$name][0])) { $parentData[$name] = array($parentData[$name]); } $parentData[$name][] = $data; } else { $parentData[$name] = $data; } } }
0001-bee
trunk/cakephp2/lib/Cake/Utility/Xml.php
PHP
gpl3
9,772
<?php /** * 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) */ /** * Deals with Collections of objects. Keeping registries of those objects, * loading and constructing new objects and triggering callbacks. Each subclass needs * to implement its own load() functionality. * * All core subclasses of ObjectCollection by convention loaded objects are stored * in `$this->_loaded`. Enabled objects are stored in `$this->_enabled`. In addition * the all support an `enabled` option that controls the enabled/disabled state of the object * when loaded. * * @package Cake.Utility * @since CakePHP(tm) v 2.0 */ abstract class ObjectCollection { /** * List of the currently-enabled objects * * @var array */ protected $_enabled = array(); /** * A hash of loaded objects, indexed by name * * @var array */ protected $_loaded = array(); /** * Loads a new object onto the collection. Can throw a variety of exceptions * * Implementations of this class support a `$options['callbacks']` flag which enables/disables * a loaded object. * * @param string $name Name of object to load. * @param array $options Array of configuration options for the object to be constructed. * @return object the constructed object */ abstract public function load($name, $options = array()); /** * Trigger a callback method on every object in the collection. * Used to trigger methods on objects in the collection. Will fire the methods in the * order they were attached. * * ### Options * * - `breakOn` Set to the value or values you want the callback propagation to stop on. * Can either be a scalar value, or an array of values to break on. Defaults to `false`. * * - `break` Set to true to enabled breaking. When a trigger is broken, the last returned value * will be returned. If used in combination with `collectReturn` the collected results will be returned. * Defaults to `false`. * * - `collectReturn` Set to true to collect the return of each object into an array. * This array of return values will be returned from the trigger() call. Defaults to `false`. * * - `triggerDisabled` Will trigger the callback on all objects in the collection even the non-enabled * objects. Defaults to false. * * - `modParams` Allows each object the callback gets called on to modify the parameters to the next object. * Setting modParams to an integer value will allow you to modify the parameter with that index. * Any non-null value will modify the parameter index indicated. * Defaults to false. * * * @param string $callback Method to fire on all the objects. Its assumed all the objects implement * the method you are calling. * @param array $params Array of parameters for the triggered callback. * @param array $options Array of options. * @return mixed Either the last result or all results if collectReturn is on. * @throws CakeException when modParams is used with an index that does not exist. */ public function trigger($callback, $params = array(), $options = array()) { if (empty($this->_enabled)) { return true; } $options = array_merge( array( 'break' => false, 'breakOn' => false, 'collectReturn' => false, 'triggerDisabled' => false, 'modParams' => false ), $options ); $collected = array(); $list = $this->_enabled; if ($options['triggerDisabled'] === true) { $list = array_keys($this->_loaded); } if ($options['modParams'] !== false && !isset($params[$options['modParams']])) { throw new CakeException(__d('cake_dev', 'Cannot use modParams with indexes that do not exist.')); } foreach ($list as $name) { $result = call_user_func_array(array($this->_loaded[$name], $callback), $params); if ($options['collectReturn'] === true) { $collected[] = $result; } if ( $options['break'] && ($result === $options['breakOn'] || (is_array($options['breakOn']) && in_array($result, $options['breakOn'], true))) ) { return $result; } elseif ($options['modParams'] !== false && is_array($result)) { $params[$options['modParams']] = $result; } } if ($options['modParams'] !== false) { return $params[$options['modParams']]; } return $options['collectReturn'] ? $collected : $result; } /** * Provide public read access to the loaded objects * * @param string $name Name of property to read * @return mixed */ public function __get($name) { if (isset($this->_loaded[$name])) { return $this->_loaded[$name]; } return null; } /** * Provide isset access to _loaded * * @param string $name Name of object being checked. * @return boolean */ public function __isset($name) { return isset($this->_loaded[$name]); } /** * Enables callbacks on an object or array of objects * * @param mixed $name CamelCased name of the object(s) to enable (string or array) * @return void */ public function enable($name) { foreach ((array)$name as $object) { if (isset($this->_loaded[$object]) && array_search($object, $this->_enabled) === false) { $this->_enabled[] = $object; } } } /** * Disables callbacks on a object or array of objects. Public object methods are still * callable as normal. * * @param mixed $name CamelCased name of the objects(s) to disable (string or array) * @return void */ public function disable($name) { foreach ((array)$name as $object) { $index = array_search($object, $this->_enabled); unset($this->_enabled[$index]); } $this->_enabled = array_values($this->_enabled); } /** * Gets the list of currently-enabled objects, or, the current status of a single objects * * @param string $name Optional. The name of the object to check the status of. If omitted, * returns an array of currently-enabled object * @return mixed If $name is specified, returns the boolean status of the corresponding object. * Otherwise, returns an array of all enabled objects. */ public function enabled($name = null) { if (!empty($name)) { return in_array($name, $this->_enabled); } return $this->_enabled; } /** * Gets the list of attached behaviors, or, whether the given behavior is attached * * @param string $name Optional. The name of the behavior to check the status of. If omitted, * returns an array of currently-attached behaviors * @return mixed If $name is specified, returns the boolean status of the corresponding behavior. * Otherwise, returns an array of all attached behaviors. */ public function attached($name = null) { if (!empty($name)) { return isset($this->_loaded[$name]); } return array_keys($this->_loaded); } /** * Name of the object to remove from the collection * * @param string $name Name of the object to delete. * @return void */ public function unload($name) { list($plugin, $name) = pluginSplit($name); unset($this->_loaded[$name]); $this->_enabled = array_values(array_diff($this->_enabled, (array)$name)); } /** * Adds or overwrites an instantiated object to the collection * * @param string $name Name of the object * @param Object $object The object to use * @return array Loaded objects */ public function set($name = null, $object = null) { if (!empty($name) && !empty($object)) { list($plugin, $name) = pluginSplit($name); $this->_loaded[$name] = $object; } return $this->_loaded; } /** * Normalizes an object array, creates an array that makes lazy loading * easier * * @param array $objects Array of child objects to normalize. * @return array Array of normalized objects. */ public static function normalizeObjectArray($objects) { $normal = array(); foreach ($objects as $i => $objectName) { $options = array(); if (!is_int($i)) { $options = (array)$objectName; $objectName = $i; } list($plugin, $name) = pluginSplit($objectName); $normal[$name] = array('class' => $objectName, 'settings' => $options); } return $normal; } }
0001-bee
trunk/cakephp2/lib/Cake/Utility/ObjectCollection.php
PHP
gpl3
8,379
<?php /** * Error Handling Controller * * Controller used by ErrorHandler to render error views. * * 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.Controller * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ class CakeErrorController extends AppController { /** * Controller name * * @var string */ public $name = 'CakeError'; /** * Uses Property * * @var array */ public $uses = array(); /** * __construct * * @param CakeRequest $request * @param CakeResponse $response */ public function __construct($request = null, $response = null) { parent::__construct($request, $response); $this->constructClasses(); $this->Components->trigger('initialize', array(&$this)); $this->_set(array('cacheAction' => false, 'viewPath' => 'Errors')); } /** * Escapes the viewVars. * * @return void */ public function beforeRender() { parent::beforeRender(); foreach ($this->viewVars as $key => $value) { if (!is_object($value)){ $this->viewVars[$key] = h($value); } } } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/CakeErrorController.php
PHP
gpl3
1,481
<?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 Cake.Controller * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('AppController', 'Controller'); /** * Static content controller * * Override this controller by placing a copy in controllers directory of an application * * @package Cake.Controller * @link http://book.cakephp.org/2.0/en/controllers/pages-controller.html */ class PagesController extends AppController { /** * Controller name * * @var string */ public $name = 'Pages'; /** * Default helper * * @var array */ public $helpers = array('Html', 'Session'); /** * This controller does not use a model * * @var array */ public $uses = array(); /** * Displays a view * * @param mixed What page to display * @return void */ 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/Controller/PagesController.php
PHP
gpl3
1,831
<?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 Cake.Controller * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Controller', 'Controller'); /** * This is a placeholder class. * Create the same file in app/Controller/AppController.php * * Add your application-wide methods in the class below, your controllers * will inherit them. * * @package Cake.Controller * @link http://book.cakephp.org/view/957/The-App-Controller */ class AppController extends Controller { }
0001-bee
trunk/cakephp2/lib/Cake/Controller/AppController.php
PHP
gpl3
1,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 Cake.Controller * @since CakePHP(tm) v 1.2 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('ComponentCollection', 'Controller'); /** * Base class for an individual Component. Components provide resuable bits of * controller logic that can be composed into a controller. Components also * provide request life-cycle callbacks for injecting logic at specific points. * * ## Life cycle callbacks * * Components can provide several callbacks that are fired at various stages of the request * cycle. The available callbacks are: * * - `initialize()` - Fired before the controller's beforeFilter method. * - `startup()` - Fired after the controller's beforeFilter method. * - `beforeRender()` - Fired before the view + layout are rendered. * - `shutdown()` - Fired after the action is complete and the view has been rendered * but before Controller::afterFilter(). * - `beforeRedirect()` - Fired before a redirect() is done. * * @package Cake.Controller * @link http://book.cakephp.org/view/993/Components * @see Controller::$components */ class Component extends Object { /** * Component collection class used to lazy load components. * * @var ComponentCollection */ protected $_Collection; /** * Settings for this Component * * @var array */ public $settings = array(); /** * Other Components this component uses. * * @var array */ public $components = array(); /** * A component lookup table used to lazy load component objects. * * @var array */ protected $_componentMap = array(); /** * Constructor * * @param ComponentCollection $collection A ComponentCollection this component can use to lazy load its components * @param array $settings Array of configuration settings. */ public function __construct(ComponentCollection $collection, $settings = array()) { $this->_Collection = $collection; $this->settings = $settings; $this->_set($settings); if (!empty($this->components)) { $this->_componentMap = ComponentCollection::normalizeObjectArray($this->components); } } /** * Magic method for lazy loading $components. * * @param string $name Name of component to get. * @return mixed A Component object or null. */ public function __get($name) { if (isset($this->_componentMap[$name]) && !isset($this->{$name})) { $settings = array_merge((array)$this->_componentMap[$name]['settings'], array('enabled' => false)); $this->{$name} = $this->_Collection->load($this->_componentMap[$name]['class'], $settings); } if (isset($this->{$name})) { return $this->{$name}; } } /** * Called before the Controller::beforeFilter(). * * @param Controller $controller Controller with components to initialize * @return void * @link http://book.cakephp.org/2.0/en/controllers/components.html#Component::initialize */ public function initialize($controller) { } /** * Called after the Controller::beforeFilter() and before the controller action * * @param Controller $controller Controller with components to startup * @return void * @link http://book.cakephp.org/2.0/en/controllers/components.html#Component::startup */ public function startup($controller) { } /** * Called after the Controller::beforeRender(), after the view class is loaded, and before the * Controller::render() * * @param Controller $controller Controller with components to beforeRender * @return void * @link http://book.cakephp.org/2.0/en/controllers/components.html#Component::beforeRender */ public function beforeRender($controller) { } /** * Called after Controller::render() and before the output is printed to the browser. * * @param Controller $controller Controller with components to shutdown * @return void * @link @link http://book.cakephp.org/2.0/en/controllers/components.html#Component::shutdown */ public function shutdown($controller) { } /** * Called before Controller::redirect(). Allows you to replace the url that will * be redirected to with a new url. The return of this method can either be an array or a string. * * If the return is an array and contains a 'url' key. You may also supply the following: * * - `status` The status code for the redirect * - `exit` Whether or not the redirect should exit. * * If your response is a string or an array that does not contain a 'url' key it will * be used as the new url to redirect to. * * @param Controller $controller Controller with components to beforeRedirect * @param string|array $url Either the string or url array that is being redirected to. * @param integer $status The status code of the redirect * @param boolean $exit Will the script exit. * @return array|null Either an array or null. * @link @link http://book.cakephp.org/2.0/en/controllers/components.html#Component::beforeRedirect */ public function beforeRedirect($controller, $url, $status = null, $exit = true) {} }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component.php
PHP
gpl3
5,391
<?php /** * Scaffold. * * Automatic forms and actions generation for rapid web application development. * * 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.Controller * @since Cake v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Scaffold', 'View'); /** * Scaffolding is a set of automatic actions for starting web development work faster. * * Scaffold inspects your database tables, and making educated guesses, sets up a * number of pages for each of your Models. These pages have data forms that work, * and afford the web developer an early look at the data, and the possibility to over-ride * scaffolded actions with custom-made ones. * * @package Cake.Controller */ class Scaffold { /** * Controller object * * @var Controller */ public $controller = null; /** * Name of the controller to scaffold * * @var string */ public $name = null; /** * Name of current model this view context is attached to * * @var string */ public $model = null; /** * Path to View. * * @var string */ public $viewPath; /** * Name of layout to use with this View. * * @var string */ public $layout = 'default'; /** * Request object * * @var CakeRequest */ public $request; /** * Valid session. * * @var boolean */ protected $_validSession = null; /** * List of variables to collect from the associated controller * * @var array */ protected $_passedVars = array( 'layout', 'name', 'viewPath', 'request' ); /** * Title HTML element for current scaffolded view * * @var string */ public $scaffoldTitle = null; /** * Construct and set up given controller with given parameters. * * @param Controller $controller Controller to scaffold * @param CakeRequest $request Request parameters. * @throws MissingModelException */ public function __construct(Controller $controller, CakeRequest $request) { $this->controller = $controller; $count = count($this->_passedVars); for ($j = 0; $j < $count; $j++) { $var = $this->_passedVars[$j]; $this->{$var} = $controller->{$var}; } $this->redirect = array('action' => 'index'); $this->modelClass = $controller->modelClass; $this->modelKey = $controller->modelKey; if (!is_object($this->controller->{$this->modelClass})) { throw new MissingModelException($this->modelClass); } $this->ScaffoldModel = $this->controller->{$this->modelClass}; $this->scaffoldTitle = Inflector::humanize(Inflector::underscore($this->viewPath)); $this->scaffoldActions = $controller->scaffold; $title_for_layout = __d('cake_dev', 'Scaffold :: ') . Inflector::humanize($request->action) . ' :: ' . $this->scaffoldTitle; $modelClass = $this->controller->modelClass; $primaryKey = $this->ScaffoldModel->primaryKey; $displayField = $this->ScaffoldModel->displayField; $singularVar = Inflector::variable($modelClass); $pluralVar = Inflector::variable($this->controller->name); $singularHumanName = Inflector::humanize(Inflector::underscore($modelClass)); $pluralHumanName = Inflector::humanize(Inflector::underscore($this->controller->name)); $scaffoldFields = array_keys($this->ScaffoldModel->schema()); $associations = $this->_associations(); $this->controller->set(compact( 'title_for_layout', 'modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar', 'singularHumanName', 'pluralHumanName', 'scaffoldFields', 'associations' )); if ($this->controller->viewClass) { $this->controller->viewClass = 'Scaffold'; } $this->_validSession = ( isset($this->controller->Session) && $this->controller->Session->valid() != false ); $this->_scaffold($request); } /** * Renders a view action of scaffolded model. * * @param CakeRequest $request Request Object for scaffolding * @return mixed A rendered view of a row from Models database table * @throws NotFoundException */ protected function _scaffoldView(CakeRequest $request) { if ($this->controller->beforeScaffold('view')) { if (isset($request->params['pass'][0])) { $this->ScaffoldModel->id = $request->params['pass'][0]; } if (!$this->ScaffoldModel->exists()) { throw new NotFoundException(__d('cake_dev', 'Invalid %s', Inflector::humanize($this->modelKey))); } $this->ScaffoldModel->recursive = 1; $this->controller->request->data = $this->ScaffoldModel->read(); $this->controller->set( Inflector::variable($this->controller->modelClass), $this->request->data ); $this->controller->render($this->request['action'], $this->layout); } elseif ($this->controller->scaffoldError('view') === false) { return $this->_scaffoldError(); } } /** * Renders index action of scaffolded model. * * @param array $params Parameters for scaffolding * @return mixed A rendered view listing rows from Models database table */ protected function _scaffoldIndex($params) { if ($this->controller->beforeScaffold('index')) { $this->ScaffoldModel->recursive = 0; $this->controller->set( Inflector::variable($this->controller->name), $this->controller->paginate() ); $this->controller->render($this->request['action'], $this->layout); } elseif ($this->controller->scaffoldError('index') === false) { return $this->_scaffoldError(); } } /** * Renders an add or edit action for scaffolded model. * * @param string $action Action (add or edit) * @return mixed A rendered view with a form to edit or add a record in the Models database table */ protected function _scaffoldForm($action = 'edit') { $this->controller->viewVars['scaffoldFields'] = array_merge( $this->controller->viewVars['scaffoldFields'], array_keys($this->ScaffoldModel->hasAndBelongsToMany) ); $this->controller->render($action, $this->layout); } /** * Saves or updates the scaffolded model. * * @param CakeRequest $request Request Object for scaffolding * @param string $action add or edt * @return mixed Success on save/update, add/edit form if data is empty or error if save or update fails * @throws NotFoundException */ protected function _scaffoldSave(CakeRequest $request, $action = 'edit') { $formAction = 'edit'; $success = __d('cake_dev', 'updated'); if ($action === 'add') { $formAction = 'add'; $success = __d('cake_dev', 'saved'); } if ($this->controller->beforeScaffold($action)) { if ($action == 'edit') { if (isset($request->params['pass'][0])) { $this->ScaffoldModel->id = $request['pass'][0]; } if (!$this->ScaffoldModel->exists()) { throw new NotFoundException(__d('cake_dev', 'Invalid %s', Inflector::humanize($this->modelKey))); } } if (!empty($request->data)) { if ($action == 'create') { $this->ScaffoldModel->create(); } if ($this->ScaffoldModel->save($request->data)) { if ($this->controller->afterScaffoldSave($action)) { $message = __d('cake_dev', 'The %1$s has been %2$s', Inflector::humanize($this->modelKey), $success ); return $this->_sendMessage($message); } else { return $this->controller->afterScaffoldSaveError($action); } } else { if ($this->_validSession) { $this->controller->Session->setFlash(__d('cake_dev', 'Please correct errors below.')); } } } if (empty($request->data)) { if ($this->ScaffoldModel->id) { $this->controller->data = $request->data = $this->ScaffoldModel->read(); } else { $this->controller->data = $request->data = $this->ScaffoldModel->create(); } } foreach ($this->ScaffoldModel->belongsTo as $assocName => $assocData) { $varName = Inflector::variable(Inflector::pluralize( preg_replace('/(?:_id)$/', '', $assocData['foreignKey']) )); $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list')); } foreach ($this->ScaffoldModel->hasAndBelongsToMany as $assocName => $assocData) { $varName = Inflector::variable(Inflector::pluralize($assocName)); $this->controller->set($varName, $this->ScaffoldModel->{$assocName}->find('list')); } return $this->_scaffoldForm($formAction); } elseif ($this->controller->scaffoldError($action) === false) { return $this->_scaffoldError(); } } /** * Performs a delete on given scaffolded Model. * * @param CakeRequest $request Request for scaffolding * @return mixed Success on delete, error if delete fails * @throws MethodNotAllowedException, NotFoundException */ protected function _scaffoldDelete(CakeRequest $request) { if ($this->controller->beforeScaffold('delete')) { if (!$request->is('post')) { throw new MethodNotAllowedException(); } $id = false; if (isset($request->params['pass'][0])) { $id = $request->params['pass'][0]; } $this->ScaffoldModel->id = $id; if (!$this->ScaffoldModel->exists()) { throw new NotFoundException(__d('cake_dev', 'Invalid %s', Inflector::humanize($this->modelClass))); } if ($this->ScaffoldModel->delete()) { $message = __d('cake_dev', 'The %1$s with id: %2$d has been deleted.', Inflector::humanize($this->modelClass), $id); return $this->_sendMessage($message); } else { $message = __d('cake_dev', 'There was an error deleting the %1$s with id: %2$d', Inflector::humanize($this->modelClass), $id ); return $this->_sendMessage($message); } } elseif ($this->controller->scaffoldError('delete') === false) { return $this->_scaffoldError(); } } /** * Sends a message to the user. Either uses Sessions or flash messages depending * on the availability of a session * * @param string $message Message to display * @return void */ protected function _sendMessage($message) { if ($this->_validSession) { $this->controller->Session->setFlash($message); $this->controller->redirect($this->redirect); } else { $this->controller->flash($message, $this->redirect); } } /** * Show a scaffold error * * @return mixed A rendered view showing the error */ protected function _scaffoldError() { return $this->controller->render('error', $this->layout); } /** * When methods are now present in a controller * scaffoldView is used to call default Scaffold methods if: * `public $scaffold;` is placed in the controller's class definition. * * @param CakeRequest $request Request object for scaffolding * @return mixed A rendered view of scaffold action, or showing the error * @throws MissingActionException, MissingDatabaseException */ protected function _scaffold(CakeRequest $request) { $db = ConnectionManager::getDataSource($this->ScaffoldModel->useDbConfig); $prefixes = Configure::read('Routing.prefixes'); $scaffoldPrefix = $this->scaffoldActions; if (isset($db)) { if (empty($this->scaffoldActions)) { $this->scaffoldActions = array( 'index', 'list', 'view', 'add', 'create', 'edit', 'update', 'delete' ); } elseif (!empty($prefixes) && in_array($scaffoldPrefix, $prefixes)) { $this->scaffoldActions = array( $scaffoldPrefix . '_index', $scaffoldPrefix . '_list', $scaffoldPrefix . '_view', $scaffoldPrefix . '_add', $scaffoldPrefix . '_create', $scaffoldPrefix . '_edit', $scaffoldPrefix . '_update', $scaffoldPrefix . '_delete' ); } if (in_array($request->params['action'], $this->scaffoldActions)) { if (!empty($prefixes)) { $request->params['action'] = str_replace($scaffoldPrefix . '_', '', $request->params['action']); } switch ($request->params['action']) { case 'index': case 'list': $this->_scaffoldIndex($request); break; case 'view': $this->_scaffoldView($request); break; case 'add': case 'create': $this->_scaffoldSave($request, 'add'); break; case 'edit': case 'update': $this->_scaffoldSave($request, 'edit'); break; case 'delete': $this->_scaffoldDelete($request); break; } } else { throw new MissingActionException(array( 'controller' => $this->controller->name, 'action' => $request->action )); } } else { throw new MissingDatabaseException(array('connection' => $this->ScaffoldModel->useDbConfig)); } } /** * Returns associations for controllers models. * * @return array Associations for model */ protected function _associations() { $keys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'); $associations = array(); foreach ($keys as $key => $type) { foreach ($this->ScaffoldModel->{$type} as $assocKey => $assocData) { $associations[$type][$assocKey]['primaryKey'] = $this->ScaffoldModel->{$assocKey}->primaryKey; $associations[$type][$assocKey]['displayField'] = $this->ScaffoldModel->{$assocKey}->displayField; $associations[$type][$assocKey]['foreignKey'] = $assocData['foreignKey']; $associations[$type][$assocKey]['controller'] = Inflector::pluralize(Inflector::underscore($assocData['className'])); if ($type == 'hasAndBelongsToMany') { $associations[$type][$assocKey]['with'] = $assocData['with']; } } } return $associations; } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Scaffold.php
PHP
gpl3
13,556
<?php /** * Authentication component * * Manages user logins and permissions. * * 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.Controller.Component * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Component', 'Controller'); App::uses('Router', 'Routing'); App::uses('Security', 'Utility'); App::uses('Debugger', 'Utility'); App::uses('CakeSession', 'Model/Datasource'); App::uses('BaseAuthorize', 'Controller/Component/Auth'); App::uses('BaseAuthenticate', 'Controller/Component/Auth'); /** * Authentication control component class * * Binds access control with user authentication and session management. * * @package Cake.Controller.Component * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html */ class AuthComponent extends Component { const ALL = 'all'; /** * Other components utilized by AuthComponent * * @var array */ public $components = array('Session', 'RequestHandler'); /** * An array of authentication objects to use for authenticating users. You can configure * multiple adapters and they will be checked sequentially when users are identified. * * {{{ * $this->Auth->authenticate = array( * 'Form' => array( * 'userModel' => 'Users.User' * ) * ); * }}} * * Using the class name without 'Authenticate' as the key, you can pass in an array of settings for each * authentication object. Additionally you can define settings that should be set to all authentications objects * using the 'all' key: * * {{{ * $this->Auth->authenticate = array( * 'all' => array( * 'userModel' => 'Users.User', * 'scope' => array('User.active' => 1) * ), * 'Form', * 'Basic' * ); * }}} * * You can also use AuthComponent::ALL instead of the string 'all'. * * @var array * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html */ public $authenticate = array('Form'); /** * Objects that will be used for authentication checks. * * @var array */ protected $_authenticateObjects = array(); /** * An array of authorization objects to use for authorizing users. You can configure * multiple adapters and they will be checked sequentially when authorization checks are done. * * {{{ * $this->Auth->authorize = array( * 'Crud' => array( * 'actionPath' => 'controllers/' * ) * ); * }}} * * Using the class name without 'Authorize' as the key, you can pass in an array of settings for each * authorization object. Additionally you can define settings that should be set to all authorization objects * using the 'all' key: * * {{{ * $this->Auth->authorize = array( * 'all' => array( * 'actionPath' => 'controllers/' * ), * 'Crud', * 'CustomAuth' * ); * }}} * * You can also use AuthComponent::ALL instead of the string 'all' * * @var mixed * @link http://book.cakephp.org/view/1275/authorize */ public $authorize = false; /** * Objects that will be used for authorization checks. * * @var array */ protected $_authorizeObjects = array(); /** * The name of an optional view element to render when an Ajax request is made * with an invalid or expired session * * @var string */ public $ajaxLogin = null; /** * Settings to use when Auth needs to do a flash message with SessionComponent::setFlash(). * Available keys are: * * - `element` - The element to use, defaults to 'default'. * - `key` - The key to use, defaults to 'auth' * - `params` - The array of additional params to use, defaults to array() * * @var array */ public $flash = array( 'element' => 'default', 'key' => 'auth', 'params' => array() ); /** * The session key name where the record of the current user is stored. If * unspecified, it will be "Auth.User". * * @var string */ public static $sessionKey = 'Auth.User'; /** * A URL (defined as a string or array) to the controller action that handles * logins. Defaults to `/users/login` * * @var mixed */ public $loginAction = array( 'controller' => 'users', 'action' => 'login', 'plugin' => null ); /** * Normally, if a user is redirected to the $loginAction page, the location they * were redirected from will be stored in the session so that they can be * redirected back after a successful login. If this session value is not * set, the user will be redirected to the page specified in $loginRedirect. * * @var mixed * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent::$loginRedirect */ public $loginRedirect = null; /** * The default action to redirect to after the user is logged out. While AuthComponent does * not handle post-logout redirection, a redirect URL will be returned from AuthComponent::logout(). * Defaults to AuthComponent::$loginAction. * * @var mixed * @see AuthComponent::$loginAction * @see AuthComponent::logout() */ public $logoutRedirect = null; /** * Error to display when user attempts to access an object or action to which they do not have * acccess. * * @var string * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent::$authError */ public $authError = null; /** * Controller actions for which user validation is not required. * * @var array * @see AuthComponent::allow() */ public $allowedActions = array(); /** * Request object * * @var CakeRequest */ public $request; /** * Response object * * @var CakeResponse */ public $response; /** * Method list for bound controller * * @var array */ protected $_methods = array(); /** * Initializes AuthComponent for use in the controller * * @param Controller $controller A reference to the instantiating controller object * @return void */ public function initialize($controller) { $this->request = $controller->request; $this->response = $controller->response; $this->_methods = $controller->methods; if (Configure::read('debug') > 0) { Debugger::checkSecurityKeys(); } } /** * Main execution method. Handles redirecting of invalid users, and processing * of login form data. * * @param Controller $controller A reference to the instantiating controller object * @return boolean */ public function startup($controller) { if ($controller->name == 'CakeError') { return true; } $methods = array_flip($controller->methods); $action = $controller->request->params['action']; $isMissingAction = ( $controller->scaffold === false && !isset($methods[$action]) ); if ($isMissingAction) { return true; } if (!$this->_setDefaults()) { return false; } $request = $controller->request; $url = ''; if (isset($request->url)) { $url = $request->url; } $url = Router::normalize($url); $loginAction = Router::normalize($this->loginAction); $allowedActions = $this->allowedActions; $isAllowed = ( $this->allowedActions == array('*') || in_array($action, $allowedActions) ); if ($loginAction != $url && $isAllowed) { return true; } if ($loginAction == $url) { if (empty($request->data)) { if (!$this->Session->check('Auth.redirect') && !$this->loginRedirect && env('HTTP_REFERER')) { $this->Session->write('Auth.redirect', $controller->referer(null, true)); } } return true; } else { if (!$this->_getUser()) { if (!$request->is('ajax')) { $this->flash($this->authError); $this->Session->write('Auth.redirect', Router::reverse($request)); $controller->redirect($loginAction); return false; } elseif (!empty($this->ajaxLogin)) { $controller->viewPath = 'Elements'; echo $controller->render($this->ajaxLogin, $this->RequestHandler->ajaxLayout); $this->_stop(); return false; } else { $controller->redirect(null, 403); } } } if (empty($this->authorize) || $this->isAuthorized($this->user())) { return true; } $this->flash($this->authError); $controller->redirect($controller->referer('/'), null, true); return false; } /** * Attempts to introspect the correct values for object properties including * $userModel and $sessionKey. * * @return boolean */ protected function _setDefaults() { $defaults = array( 'logoutRedirect' => $this->loginAction, 'authError' => __d('cake_dev', 'You are not authorized to access that location.') ); foreach ($defaults as $key => $value) { if (empty($this->{$key})) { $this->{$key} = $value; } } return true; } /** * Uses the configured Authorization adapters to check whether or not a user is authorized. * Each adapter will be checked in sequence, if any of them return true, then the user will * be authorized for the request. * * @param mixed $user The user to check the authorization of. If empty the user in the session will be used. * @param CakeRequest $request The request to authenticate for. If empty, the current request will be used. * @return boolean True if $user is authorized, otherwise false */ public function isAuthorized($user = null, $request = null) { if (empty($user) && !$this->user()) { return false; } elseif (empty($user)) { $user = $this->user(); } if (empty($request)) { $request = $this->request; } if (empty($this->_authorizeObjects)) { $this->constructAuthorize(); } foreach ($this->_authorizeObjects as $authorizer) { if ($authorizer->authorize($user, $request) === true) { return true; } } return false; } /** * Loads the authorization objects configured. * * @return mixed Either null when authorize is empty, or the loaded authorization objects. * @throws CakeException */ public function constructAuthorize() { if (empty($this->authorize)) { return; } $this->_authorizeObjects = array(); $config = Set::normalize($this->authorize); $global = array(); if (isset($config[AuthComponent::ALL])) { $global = $config[AuthComponent::ALL]; unset($config[AuthComponent::ALL]); } foreach ($config as $class => $settings) { list($plugin, $class) = pluginSplit($class, true); $className = $class . 'Authorize'; App::uses($className, $plugin . 'Controller/Component/Auth'); if (!class_exists($className)) { throw new CakeException(__d('cake_dev', 'Authorization adapter "%s" was not found.', $class)); } if (!method_exists($className, 'authorize')) { throw new CakeException(__d('cake_dev', 'Authorization objects must implement an authorize method.')); } $settings = array_merge($global, (array)$settings); $this->_authorizeObjects[] = new $className($this->_Collection, $settings); } return $this->_authorizeObjects; } /** * Takes a list of actions in the current controller for which authentication is not required, or * no parameters to allow all actions. * * You can use allow with either an array, or var args. * * `$this->Auth->allow(array('edit', 'add'));` or * `$this->Auth->allow('edit', 'add');` * * allow() also supports '*' as a wildcard to mean all actions. * * `$this->Auth->allow('*');` * * @param mixed $action,... Controller action name or array of actions * @return void * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-public */ public function allow($action = null) { $args = func_get_args(); if (empty($args) || $args == array('*')) { $this->allowedActions = $this->_methods; } else { if (isset($args[0]) && is_array($args[0])) { $args = $args[0]; } $this->allowedActions = array_merge($this->allowedActions, $args); } } /** * Removes items from the list of allowed/no authentication required actions. * * You can use deny with either an array, or var args. * * `$this->Auth->deny(array('edit', 'add'));` or * `$this->Auth->deny('edit', 'add');` * * @param mixed $action,... Controller action name or array of actions * @return void * @see AuthComponent::allow() * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-require-authorization */ public function deny($action = null) { $args = func_get_args(); if (isset($args[0]) && is_array($args[0])) { $args = $args[0]; } foreach ($args as $arg) { $i = array_search($arg, $this->allowedActions); if (is_int($i)) { unset($this->allowedActions[$i]); } } $this->allowedActions = array_values($this->allowedActions); } /** * Maps action names to CRUD operations. Used for controller-based authentication. Make sure * to configure the authorize property before calling this method. As it delegates $map to all the * attached authorize objects. * * @param array $map Actions to map * @return void * @see BaseAuthorize::mapActions() * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#mapping-actions-when-using-crudauthorize */ public function mapActions($map = array()) { if (empty($this->_authorizeObjects)) { $this->constructAuthorize(); } foreach ($this->_authorizeObjects as $auth) { $auth->mapActions($map); } } /** * Log a user in. If a $user is provided that data will be stored as the logged in user. If `$user` is empty or not * specified, the request will be used to identify a user. If the identification was successful, * the user record is written to the session key specified in AuthComponent::$sessionKey. Logging in * will also change the session id in order to help mitigate session replays. * * @param mixed $user Either an array of user data, or null to identify a user using the current request. * @return boolean True on login success, false on failure * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in */ public function login($user = null) { $this->_setDefaults(); if (empty($user)) { $user = $this->identify($this->request, $this->response); } if ($user) { $this->Session->renew(); $this->Session->write(self::$sessionKey, $user); } return $this->loggedIn(); } /** * Logs a user out, and returns the login action to redirect to. * Triggers the logout() method of all the authenticate objects, so they can perform * custom logout logic. AuthComponent will remove the session data, so * there is no need to do that in an authentication object. Logging out * will also renew the session id. This helps mitigate issues with session replays. * * @return string AuthComponent::$logoutRedirect * @see AuthComponent::$logoutRedirect * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out */ public function logout() { $this->_setDefaults(); if (empty($this->_authenticateObjects)) { $this->constructAuthenticate(); } $user = $this->user(); foreach ($this->_authenticateObjects as $auth) { $auth->logout($user); } $this->Session->delete(self::$sessionKey); $this->Session->delete('Auth.redirect'); $this->Session->renew(); return Router::normalize($this->logoutRedirect); } /** * Get the current user from the session. * * @param string $key field to retrive. Leave null to get entire User record * @return mixed User record. or null if no user is logged in. * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user */ public static function user($key = null) { if (!CakeSession::check(self::$sessionKey)) { return null; } if ($key == null) { return CakeSession::read(self::$sessionKey); } $user = CakeSession::read(self::$sessionKey); if (isset($user[$key])) { return $user[$key]; } return null; } /** * Similar to AuthComponent::user() except if the session user cannot be found, connected authentication * objects will have their getUser() methods called. This lets stateless authentication methods function correctly. * * @return boolean true if a user can be found, false if one cannot. */ protected function _getUser() { $user = $this->user(); if ($user) { return true; } if (empty($this->_authenticateObjects)) { $this->constructAuthenticate(); } foreach ($this->_authenticateObjects as $auth) { $result = $auth->getUser($this->request); if (!empty($result) && is_array($result)) { return true; } } return false; } /** * If no parameter is passed, gets the authentication redirect URL. Pass a url in to * set the destination a user should be redirected to upon logging in. Will fallback to * AuthComponent::$loginRedirect if there is no stored redirect value. * * @param mixed $url Optional URL to write as the login redirect URL. * @return string Redirect URL */ public function redirect($url = null) { if (!is_null($url)) { $redir = $url; $this->Session->write('Auth.redirect', $redir); } elseif ($this->Session->check('Auth.redirect')) { $redir = $this->Session->read('Auth.redirect'); $this->Session->delete('Auth.redirect'); if (Router::normalize($redir) == Router::normalize($this->loginAction)) { $redir = $this->loginRedirect; } } else { $redir = $this->loginRedirect; } return Router::normalize($redir); } /** * Use the configured authentication adapters, and attempt to identify the user * by credentials contained in $request. * * @param CakeRequest $request The request that contains authentication data. * @param CakeResponse $response The response * @return array User record data, or false, if the user could not be identified. */ public function identify(CakeRequest $request, CakeResponse $response) { if (empty($this->_authenticateObjects)) { $this->constructAuthenticate(); } foreach ($this->_authenticateObjects as $auth) { $result = $auth->authenticate($request, $response); if (!empty($result) && is_array($result)) { return $result; } } return false; } /** * loads the configured authentication objects. * * @return mixed either null on empty authenticate value, or an array of loaded objects. * @throws CakeException */ public function constructAuthenticate() { if (empty($this->authenticate)) { return; } $this->_authenticateObjects = array(); $config = Set::normalize($this->authenticate); $global = array(); if (isset($config[AuthComponent::ALL])) { $global = $config[AuthComponent::ALL]; unset($config[AuthComponent::ALL]); } foreach ($config as $class => $settings) { list($plugin, $class) = pluginSplit($class, true); $className = $class . 'Authenticate'; App::uses($className, $plugin . 'Controller/Component/Auth'); if (!class_exists($className)) { throw new CakeException(__d('cake_dev', 'Authentication adapter "%s" was not found.', $class)); } if (!method_exists($className, 'authenticate')) { throw new CakeException(__d('cake_dev', 'Authentication objects must implement an authenticate method.')); } $settings = array_merge($global, (array)$settings); $this->_authenticateObjects[] = new $className($this->_Collection, $settings); } return $this->_authenticateObjects; } /** * Hash a password with the application's salt value (as defined with Configure::write('Security.salt'); * * This method is intended as a convenience wrapper for Security::hash(). If you want to use * a hashing/encryption system not supported by that method, do not use this method. * * @param string $password Password to hash * @return string Hashed password * @link http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#hashing-passwords */ public static function password($password) { return Security::hash($password, null, true); } /** * Component shutdown. If user is logged in, wipe out redirect. * * @param Controller $controller Instantiating controller * @return void */ public function shutdown($controller) { if ($this->loggedIn()) { $this->Session->delete('Auth.redirect'); } } /** * Check whether or not the current user has data in the session, and is considered logged in. * * @return boolean true if the user is logged in, false otherwise */ public function loggedIn() { return $this->user() != array(); } /** * Set a flash message. Uses the Session component, and values from AuthComponent::$flash. * * @param string $message The message to set. * @return void */ public function flash($message) { $this->Session->setFlash($message, $this->flash['element'], $this->flash['params'], $this->flash['key']); } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/AuthComponent.php
PHP
gpl3
20,909
<?php /** * Access Control List factory class. * * Permissions system. * * 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.Controller.Component * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Component', 'Controller'); /** * Access Control List factory class. * * Uses a strategy pattern to allow custom ACL implementations to be used with the same component interface. * You can define by changing `Configure::write('Acl.classname', 'DbAcl');` in your core.php. Concrete ACL * implementations should extend `AclBase` and implement the methods it defines. * * @package Cake.Controller.Component * @link http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html */ class AclComponent extends Component { /** * Instance of an ACL class * * @var AclInterface */ protected $_Instance = null; /** * Aro object. * * @var string */ public $Aro; /** * Aco object * * @var string */ public $Aco; /** * Constructor. Will return an instance of the correct ACL class as defined in `Configure::read('Acl.classname')` * * @param ComponentCollection $collection * @param array $settings * @throws CakeException when Acl.classname could not be loaded. */ public function __construct(ComponentCollection $collection, $settings = array()) { parent::__construct($collection, $settings); $name = Inflector::camelize(strtolower(Configure::read('Acl.classname'))); if (!class_exists($name)) { if (App::import('Component', $name)) { list($plugin, $name) = pluginSplit($name); $name .= 'Component'; } else { throw new CakeException(__d('cake_dev', 'Could not find %s.', $name)); } } $this->adapter($name); } /** * Sets or gets the Adapter object currently in the AclComponent. * * `$this->Acl->adapter();` will get the current adapter class while * `$this->Acl->adapter($obj);` will set the adapter class * * Will call the initialize method on the adapter if setting a new one. * * @param mixed $adapter Instance of AclBase or a string name of the class to use. (optional) * @return mixed either null, or instance of AclBase * @throws CakeException when the given class is not an AclBase */ public function adapter($adapter = null) { if ($adapter) { if (is_string($adapter)) { $adapter = new $adapter(); } if (!$adapter instanceof AclInterface) { throw new CakeException(__d('cake_dev', 'AclComponent adapters must implement AclInterface')); } $this->_Instance = $adapter; $this->_Instance->initialize($this); return; } return $this->_Instance; } /** * Pass-thru function for ACL check instance. Check methods * are used to check whether or not an ARO can access an ACO * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success */ public function check($aro, $aco, $action = "*") { return $this->_Instance->check($aro, $aco, $action); } /** * Pass-thru function for ACL allow instance. Allow methods * are used to grant an ARO access to an ACO. * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success */ public function allow($aro, $aco, $action = "*") { return $this->_Instance->allow($aro, $aco, $action); } /** * Pass-thru function for ACL deny instance. Deny methods * are used to remove permission from an ARO to access an ACO. * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success */ public function deny($aro, $aco, $action = "*") { return $this->_Instance->deny($aro, $aco, $action); } /** * Pass-thru function for ACL inherit instance. Inherit methods * modify the permission for an ARO to be that of its parent object. * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success */ public function inherit($aro, $aco, $action = "*") { return $this->_Instance->inherit($aro, $aco, $action); } /** * Pass-thru function for ACL grant instance. An alias for AclComponent::allow() * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success * @deprecated */ public function grant($aro, $aco, $action = "*") { trigger_error(__d('cake_dev', 'AclComponent::grant() is deprecated, use allow() instead'), E_USER_WARNING); return $this->_Instance->allow($aro, $aco, $action); } /** * Pass-thru function for ACL grant instance. An alias for AclComponent::deny() * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success * @deprecated */ public function revoke($aro, $aco, $action = "*") { trigger_error(__d('cake_dev', 'AclComponent::revoke() is deprecated, use deny() instead'), E_USER_WARNING); return $this->_Instance->deny($aro, $aco, $action); } } /** * Access Control List interface. * Implementing classes are used by AclComponent to perform ACL checks in Cake. * * @package Cake.Controller.Component */ interface AclInterface { /** * Empty method to be overridden in subclasses * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) */ public function check($aro, $aco, $action = "*"); /** * Allow methods are used to grant an ARO access to an ACO. * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success */ public function allow($aro, $aco, $action = "*"); /** * Deny methods are used to remove permission from an ARO to access an ACO. * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success */ public function deny($aro, $aco, $action = "*"); /** * Inherit methods modify the permission for an ARO to be that of its parent object. * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success */ public function inherit($aro, $aco, $action = "*"); /** * Initialization method for the Acl implementation * * @param AclComponent $component */ public function initialize($component); } /** * DbAcl implements an ACL control system in the database. ARO's and ACO's are * structured into trees and a linking table is used to define permissions. You * can install the schema for DbAcl with the Schema Shell. * * `$aco` and `$aro` parameters can be slash delimited paths to tree nodes. * * eg. `controllers/Users/edit` * * Would point to a tree structure like * * {{{ * controllers * Users * edit * }}} * * @package Cake.Controller.Component */ class DbAcl extends Object implements AclInterface { /** * Constructor * */ public function __construct() { parent::__construct(); App::uses('AclNode', 'Model'); $this->Aro = ClassRegistry::init(array('class' => 'Aro', 'alias' => 'Aro')); $this->Aco = ClassRegistry::init(array('class' => 'Aco', 'alias' => 'Aco')); } /** * Initializes the containing component and sets the Aro/Aco objects to it. * * @param AclComponent $component * @return void */ public function initialize($component) { $component->Aro = $this->Aro; $component->Aco = $this->Aco; } /** * Checks if the given $aro has access to action $action in $aco * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success (true if ARO has access to action in ACO, false otherwise) * @link http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html#checking-permissions-the-acl-component */ public function check($aro, $aco, $action = "*") { if ($aro == null || $aco == null) { return false; } $permKeys = $this->_getAcoKeys($this->Aro->Permission->schema()); $aroPath = $this->Aro->node($aro); $acoPath = $this->Aco->node($aco); if (empty($aroPath) || empty($acoPath)) { trigger_error(__d('cake_dev', "DbAcl::check() - Failed ARO/ACO node lookup in permissions check. Node references:\nAro: ") . print_r($aro, true) . "\nAco: " . print_r($aco, true), E_USER_WARNING); return false; } if ($acoPath == null || $acoPath == array()) { trigger_error(__d('cake_dev', "DbAcl::check() - Failed ACO node lookup in permissions check. Node references:\nAro: ") . print_r($aro, true) . "\nAco: " . print_r($aco, true), E_USER_WARNING); return false; } if ($action != '*' && !in_array('_' . $action, $permKeys)) { trigger_error(__d('cake_dev', "ACO permissions key %s does not exist in DbAcl::check()", $action), E_USER_NOTICE); return false; } $inherited = array(); $acoIDs = Set::extract($acoPath, '{n}.' . $this->Aco->alias . '.id'); $count = count($aroPath); for ($i = 0 ; $i < $count; $i++) { $permAlias = $this->Aro->Permission->alias; $perms = $this->Aro->Permission->find('all', array( 'conditions' => array( "{$permAlias}.aro_id" => $aroPath[$i][$this->Aro->alias]['id'], "{$permAlias}.aco_id" => $acoIDs ), 'order' => array($this->Aco->alias . '.lft' => 'desc'), 'recursive' => 0 )); if (empty($perms)) { continue; } else { $perms = Set::extract($perms, '{n}.' . $this->Aro->Permission->alias); foreach ($perms as $perm) { if ($action == '*') { foreach ($permKeys as $key) { if (!empty($perm)) { if ($perm[$key] == -1) { return false; } elseif ($perm[$key] == 1) { $inherited[$key] = 1; } } } if (count($inherited) === count($permKeys)) { return true; } } else { switch ($perm['_' . $action]) { case -1: return false; case 0: continue; break; case 1: return true; break; } } } } } return false; } /** * Allow $aro to have access to action $actions in $aco * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $actions Action (defaults to *) * @param integer $value Value to indicate access type (1 to give access, -1 to deny, 0 to inherit) * @return boolean Success * @link http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html#assigning-permissions */ public function allow($aro, $aco, $actions = "*", $value = 1) { $perms = $this->getAclLink($aro, $aco); $permKeys = $this->_getAcoKeys($this->Aro->Permission->schema()); $save = array(); if ($perms == false) { trigger_error(__d('cake_dev', 'DbAcl::allow() - Invalid node'), E_USER_WARNING); return false; } if (isset($perms[0])) { $save = $perms[0][$this->Aro->Permission->alias]; } if ($actions == "*") { $permKeys = $this->_getAcoKeys($this->Aro->Permission->schema()); $save = array_combine($permKeys, array_pad(array(), count($permKeys), $value)); } else { if (!is_array($actions)) { $actions = array('_' . $actions); } if (is_array($actions)) { foreach ($actions as $action) { if ($action{0} != '_') { $action = '_' . $action; } if (in_array($action, $permKeys)) { $save[$action] = $value; } } } } list($save['aro_id'], $save['aco_id']) = array($perms['aro'], $perms['aco']); if ($perms['link'] != null && !empty($perms['link'])) { $save['id'] = $perms['link'][0][$this->Aro->Permission->alias]['id']; } else { unset($save['id']); $this->Aro->Permission->id = null; } return ($this->Aro->Permission->save($save) !== false); } /** * Deny access for $aro to action $action in $aco * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success * @link http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html#assigning-permissions */ public function deny($aro, $aco, $action = "*") { return $this->allow($aro, $aco, $action, -1); } /** * Let access for $aro to action $action in $aco be inherited * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success */ public function inherit($aro, $aco, $action = "*") { return $this->allow($aro, $aco, $action, 0); } /** * Allow $aro to have access to action $actions in $aco * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success * @see allow() */ public function grant($aro, $aco, $action = "*") { return $this->allow($aro, $aco, $action); } /** * Deny access for $aro to action $action in $aco * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success * @see deny() */ public function revoke($aro, $aco, $action = "*") { return $this->deny($aro, $aco, $action); } /** * Get an array of access-control links between the given Aro and Aco * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @return array Indexed array with: 'aro', 'aco' and 'link' */ public function getAclLink($aro, $aco) { $obj = array(); $obj['Aro'] = $this->Aro->node($aro); $obj['Aco'] = $this->Aco->node($aco); if (empty($obj['Aro']) || empty($obj['Aco'])) { return false; } return array( 'aro' => Set::extract($obj, 'Aro.0.'.$this->Aro->alias.'.id'), 'aco' => Set::extract($obj, 'Aco.0.'.$this->Aco->alias.'.id'), 'link' => $this->Aro->Permission->find('all', array('conditions' => array( $this->Aro->Permission->alias . '.aro_id' => Set::extract($obj, 'Aro.0.'.$this->Aro->alias.'.id'), $this->Aro->Permission->alias . '.aco_id' => Set::extract($obj, 'Aco.0.'.$this->Aco->alias.'.id') ))) ); } /** * Get the keys used in an ACO * * @param array $keys Permission model info * @return array ACO keys */ protected function _getAcoKeys($keys) { $newKeys = array(); $keys = array_keys($keys); foreach ($keys as $key) { if (!in_array($key, array('id', 'aro_id', 'aco_id'))) { $newKeys[] = $key; } } return $newKeys; } } /** * IniAcl implements an access control system using an INI file. An example * of the ini file used can be found in /config/acl.ini.php. * * @package Cake.Controller.Component */ class IniAcl extends Object implements AclInterface { /** * Array with configuration, parsed from ini file * * @var array */ public $config = null; /** * The Set::classicExtract() path to the user/aro identifier in the * acl.ini file. This path will be used to extract the string * representation of a user used in the ini file. * * @var string */ public $userPath = 'User.username'; /** * Initialize method * * @param AclBase $component * @return void */ public function initialize($component) { } /** * No op method, allow cannot be done with IniAcl * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success */ public function allow($aro, $aco, $action = "*") { } /** * No op method, deny cannot be done with IniAcl * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success */ public function deny($aro, $aco, $action = "*") { } /** * No op method, inherit cannot be done with IniAcl * * @param string $aro ARO The requesting object identifier. * @param string $aco ACO The controlled object identifier. * @param string $action Action (defaults to *) * @return boolean Success */ public function inherit($aro, $aco, $action = "*") { } /** * Main ACL check function. Checks to see if the ARO (access request object) has access to the * ACO (access control object).Looks at the acl.ini.php file for permissions * (see instructions in /config/acl.ini.php). * * @param string $aro ARO * @param string $aco ACO * @param string $aco_action Action * @return boolean Success */ public function check($aro, $aco, $aco_action = null) { if ($this->config == null) { $this->config = $this->readConfigFile(APP . 'Config' . DS . 'acl.ini.php'); } $aclConfig = $this->config; if (is_array($aro)) { $aro = Set::classicExtract($aro, $this->userPath); } if (isset($aclConfig[$aro]['deny'])) { $userDenies = $this->arrayTrim(explode(",", $aclConfig[$aro]['deny'])); if (array_search($aco, $userDenies)) { return false; } } if (isset($aclConfig[$aro]['allow'])) { $userAllows = $this->arrayTrim(explode(",", $aclConfig[$aro]['allow'])); if (array_search($aco, $userAllows)) { return true; } } if (isset($aclConfig[$aro]['groups'])) { $userGroups = $this->arrayTrim(explode(",", $aclConfig[$aro]['groups'])); foreach ($userGroups as $group) { if (array_key_exists($group, $aclConfig)) { if (isset($aclConfig[$group]['deny'])) { $groupDenies = $this->arrayTrim(explode(",", $aclConfig[$group]['deny'])); if (array_search($aco, $groupDenies)) { return false; } } if (isset($aclConfig[$group]['allow'])) { $groupAllows = $this->arrayTrim(explode(",", $aclConfig[$group]['allow'])); if (array_search($aco, $groupAllows)) { return true; } } } } } return false; } /** * Parses an INI file and returns an array that reflects the INI file's section structure. Double-quote friendly. * * @param string $filename File * @return array INI section structure */ public function readConfigFile($filename) { App::uses('IniReader', 'Configure'); $iniFile = new IniReader(dirname($filename) . DS); return $iniFile->read(basename($filename)); } /** * Removes trailing spaces on all array elements (to prepare for searching) * * @param array $array Array to trim * @return array Trimmed array */ public function arrayTrim($array) { foreach ($array as $key => $value) { $array[$key] = trim($value); } array_unshift($array, ""); return $array; } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/AclComponent.php
PHP
gpl3
19,825
<?php /** * Paginator Component * * 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.Controller.Component * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * This component is used to handle automatic model data pagination. The primary way to use this * component is to call the paginate() method. There is a convience wrapper on Controller as well. * * ### Configuring pagination * * You configure pagination using the PaginatorComponent::$settings. This allows you to configure * the default pagination behavior in general or for a specific model. General settings are used when there * are no specific model configuration, or the model you are paginating does not have specific settings. * * {{{ * $this->Paginator->settings = array( * 'limit' => 20, * 'maxLimit' => 100 * ); * }}} * * The above settings will be used to paginate any model. You can configure model specific settings by * keying the settings with the model name. * * {{{ * $this->Paginator->settings = array( * 'Post' => array( * 'limit' => 20, * 'maxLimit' => 100 * ), * 'Comment' => array( ... ) * ); * }}} * * This would allow you to have different pagination settings for `Comment` and `Post` models. * * @package Cake.Controller.Component * @link http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html */ class PaginatorComponent extends Component { /** * Pagination settings. These settings control pagination at a general level. * You can also define sub arrays for pagination settings for specific models. * * - `maxLimit` The maximum limit users can choose to view. Defaults to 100 * - `limit` The initial number of items per page. Defaults to 20. * - `page` The starting page, defaults to 1. * - `paramType` What type of parameters you want pagination to use? * - `named` Use named parameters / routed parameters. * - `querystring` Use query string parameters. * * @var array */ public $settings = array( 'page' => 1, 'limit' => 20, 'maxLimit' => 100, 'paramType' => 'named' ); /** * A list of parameters users are allowed to set using request parameters. Modifying * this list will allow users to have more influence over pagination, * be careful with what you permit. * * @var array */ public $whitelist = array( 'limit', 'sort', 'page', 'direction' ); /** * Constructor * * @param ComponentCollection $collection A ComponentCollection this component can use to lazy load its components * @param array $settings Array of configuration settings. */ public function __construct(ComponentCollection $collection, $settings = array()) { $settings = array_merge($this->settings, (array)$settings); $this->Controller = $collection->getController(); parent::__construct($collection, $settings); } /** * Handles automatic pagination of model records. * * @param mixed $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel') * @param mixed $scope Additional find conditions to use while paginating * @param array $whitelist List of allowed fields for ordering. This allows you to prevent ordering * on non-indexed, or undesirable columns. * @return array Model query results * @throws MissingModelException */ public function paginate($object = null, $scope = array(), $whitelist = array()) { if (is_array($object)) { $whitelist = $scope; $scope = $object; $object = null; } $object = $this->_getObject($object); if (!is_object($object)) { throw new MissingModelException($object); } $options = $this->mergeOptions($object->alias); $options = $this->validateSort($object, $options, $whitelist); $options = $this->checkLimit($options); $conditions = $fields = $order = $limit = $page = $recursive = null; if (!isset($options['conditions'])) { $options['conditions'] = array(); } $type = 'all'; if (isset($options[0])) { $type = $options[0]; unset($options[0]); } extract($options); if (is_array($scope) && !empty($scope)) { $conditions = array_merge($conditions, $scope); } elseif (is_string($scope)) { $conditions = array($conditions, $scope); } if ($recursive === null) { $recursive = $object->recursive; } $extra = array_diff_key($options, compact( 'conditions', 'fields', 'order', 'limit', 'page', 'recursive' )); if ($type !== 'all') { $extra['type'] = $type; } if (intval($page) < 1) { $page = 1; } $page = $options['page'] = (int)$page; if ($object->hasMethod('paginate')) { $results = $object->paginate( $conditions, $fields, $order, $limit, $page, $recursive, $extra ); } else { $parameters = compact('conditions', 'fields', 'order', 'limit', 'page'); if ($recursive != $object->recursive) { $parameters['recursive'] = $recursive; } $results = $object->find($type, array_merge($parameters, $extra)); } $defaults = $this->getDefaults($object->alias); unset($defaults[0]); if ($object->hasMethod('paginateCount')) { $count = $object->paginateCount($conditions, $recursive, $extra); } else { $parameters = compact('conditions'); if ($recursive != $object->recursive) { $parameters['recursive'] = $recursive; } $count = $object->find('count', array_merge($parameters, $extra)); } $pageCount = intval(ceil($count / $limit)); $paging = array( 'page' => $page, 'current' => count($results), 'count' => $count, 'prevPage' => ($page > 1), 'nextPage' => ($count > ($page * $limit)), 'pageCount' => $pageCount, 'order' => $order, 'limit' => $limit, 'options' => Set::diff($options, $defaults), 'paramType' => $options['paramType'] ); if (!isset($this->Controller->request['paging'])) { $this->Controller->request['paging'] = array(); } $this->Controller->request['paging'] = array_merge( (array)$this->Controller->request['paging'], array($object->alias => $paging) ); if ( !in_array('Paginator', $this->Controller->helpers) && !array_key_exists('Paginator', $this->Controller->helpers) ) { $this->Controller->helpers[] = 'Paginator'; } return $results; } /** * Get the object pagination will occur on. * * @param mixed $object The object you are looking for. * @return mixed The model object to paginate on. */ protected function _getObject($object) { if (is_string($object)) { $assoc = null; if (strpos($object, '.') !== false) { list($object, $assoc) = pluginSplit($object); } if ($assoc && isset($this->Controller->{$object}->{$assoc})) { $object = $this->Controller->{$object}->{$assoc}; } elseif ( $assoc && isset($this->Controller->{$this->Controller->modelClass}) && isset($this->Controller->{$this->Controller->modelClass}->{$assoc} )) { $object = $this->Controller->{$this->Controller->modelClass}->{$assoc}; } elseif (isset($this->Controller->{$object})) { $object = $this->Controller->{$object}; } elseif ( isset($this->Controller->{$this->Controller->modelClass}) && isset($this->Controller->{$this->Controller->modelClass}->{$object} )) { $object = $this->Controller->{$this->Controller->modelClass}->{$object}; } } elseif (empty($object) || $object === null) { if (isset($this->Controller->{$this->Controller->modelClass})) { $object = $this->Controller->{$this->Controller->modelClass}; } else { $className = null; $name = $this->Controller->uses[0]; if (strpos($this->Controller->uses[0], '.') !== false) { list($name, $className) = explode('.', $this->Controller->uses[0]); } if ($className) { $object = $this->Controller->{$className}; } else { $object = $this->Controller->{$name}; } } } return $object; } /** * Merges the various options that Pagination uses. * Pulls settings together from the following places: * * - General pagination settings * - Model specific settings. * - Request parameters * * The result of this method is the aggregate of all the option sets combined together. You can change * PaginatorComponent::$whitelist to modify which options/values can be set using request parameters. * * @param string $alias Model alias being paginated, if the general settings has a key with this value * that key's settings will be used for pagination instead of the general ones. * @return array Array of merged options. */ public function mergeOptions($alias) { $defaults = $this->getDefaults($alias); switch ($defaults['paramType']) { case 'named': $request = $this->Controller->request->params['named']; break; case 'querystring': $request = $this->Controller->request->query; break; } $request = array_intersect_key($request, array_flip($this->whitelist)); return array_merge($defaults, $request); } /** * Get the default settings for a $model. If there are no settings for a specific model, the general settings * will be used. * * @param string $alias Model name to get default settings for. * @return array An array of pagination defaults for a model, or the general settings. */ public function getDefaults($alias) { if (isset($this->settings[$alias])) { $defaults = $this->settings[$alias]; } else { $defaults = $this->settings; } return array_merge( array('page' => 1, 'limit' => 20, 'maxLimit' => 100, 'paramType' => 'named'), $defaults ); } /** * Validate that the desired sorting can be performed on the $object. Only fields or * virtualFields can be sorted on. The direction param will also be sanitized. Lastly * sort + direction keys will be converted into the model friendly order key. * * You can use the whitelist parameter to control which columns/fields are available for sorting. * This helps prevent users from ordering large result sets on un-indexed values. * * @param Model $object The model being paginated. * @param array $options The pagination options being used for this request. * @param array $whitelist The list of columns that can be used for sorting. If empty all keys are allowed. * @return array An array of options with sort + direction removed and replaced with order if possible. */ public function validateSort($object, $options, $whitelist = array()) { if (isset($options['sort'])) { $direction = null; if (isset($options['direction'])) { $direction = strtolower($options['direction']); } if ($direction != 'asc' && $direction != 'desc') { $direction = 'asc'; } $options['order'] = array($options['sort'] => $direction); } if (!empty($whitelist)) { $field = key($options['order']); if (!in_array($field, $whitelist)) { $options['order'] = null; } } if (!empty($options['order']) && is_array($options['order'])) { $order = array(); foreach ($options['order'] as $key => $value) { $field = $key; $alias = $object->alias; if (strpos($key, '.') !== false) { list($alias, $field) = explode('.', $key); } if ($object->hasField($field)) { $order[$alias . '.' . $field] = $value; } elseif ($object->hasField($key, true)) { $order[$field] = $value; } elseif (isset($object->{$alias}) && $object->{$alias}->hasField($field)) { $order[$alias . '.' . $field] = $value; } } $options['order'] = $order; } return $options; } /** * Check the limit parameter and ensure its within the maxLimit bounds. * * @param array $options An array of options with a limit key to be checked. * @return array An array of options for pagination */ public function checkLimit($options) { $options['limit'] = (int) $options['limit']; if (empty($options['limit']) || $options['limit'] < 1) { $options['limit'] = 1; } $options['limit'] = min((int)$options['limit'], $options['maxLimit']); return $options; } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/PaginatorComponent.php
PHP
gpl3
12,283
<?php /** * SessionComponent. Provides access to Sessions from the Controller layer * * 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.Controller.Component * @since CakePHP(tm) v 0.10.0.1232 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Component', 'Controller'); App::uses('CakeSession', 'Model/Datasource'); /** * Session Component. * * Session handling from the controller. * * @package Cake.Controller.Component * @link http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html * @link http://book.cakephp.org/2.0/en/development/sessions.html */ class SessionComponent extends Component { /** * Get / Set the userAgent * * @param string $userAgent Set the userAgent * @return void */ public function userAgent($userAgent = null) { return CakeSession::userAgent($userAgent); } /** * Used to write a value to a session key. * * In your controller: $this->Session->write('Controller.sessKey', 'session value'); * * @param string $name The name of the key your are setting in the session. * This should be in a Controller.key format for better organizing * @param string $value The value you want to store in a session. * @return boolean Success * @link http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html#SessionComponent::write */ public function write($name, $value = null) { return CakeSession::write($name, $value); } /** * Used to read a session values for a key or return values for all keys. * * In your controller: $this->Session->read('Controller.sessKey'); * Calling the method without a param will return all session vars * * @param string $name the name of the session key you want to read * @return mixed value from the session vars * @link http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html#SessionComponent::read */ public function read($name = null) { return CakeSession::read($name); } /** * Wrapper for SessionComponent::del(); * * In your controller: $this->Session->delete('Controller.sessKey'); * * @param string $name the name of the session key you want to delete * @return boolean true is session variable is set and can be deleted, false is variable was not set. * @link http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html#SessionComponent::delete */ public function delete($name) { return CakeSession::delete($name); } /** * Used to check if a session variable is set * * In your controller: $this->Session->check('Controller.sessKey'); * * @param string $name the name of the session key you want to check * @return boolean true is session variable is set, false if not * @link http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html#SessionComponent::check */ public function check($name) { return CakeSession::check($name); } /** * Used to determine the last error in a session. * * In your controller: $this->Session->error(); * * @return string Last session error */ public function error() { return CakeSession::error(); } /** * Used to set a session variable that can be used to output messages in the view. * * In your controller: $this->Session->setFlash('This has been saved'); * * Additional params below can be passed to customize the output, or the Message.[key]. * You can also set additional parameters when rendering flash messages. See SessionHelper::flash() * for more information on how to do that. * * @param string $message Message to be flashed * @param string $element Element to wrap flash message in. * @param array $params Parameters to be sent to layout as view variables * @param string $key Message key, default is 'flash' * @return void * @link http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html#creating-notification-messages */ public function setFlash($message, $element = 'default', $params = array(), $key = 'flash') { CakeSession::write('Message.' . $key, compact('message', 'element', 'params')); } /** * Used to renew a session id * * In your controller: $this->Session->renew(); * * @return void */ public function renew() { return CakeSession::renew(); } /** * Used to check for a valid session. * * In your controller: $this->Session->valid(); * * @return boolean true is session is valid, false is session is invalid */ public function valid() { return CakeSession::valid(); } /** * Used to destroy sessions * * In your controller: $this->Session->destroy(); * * @return void * @link http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html#SessionComponent::destroy */ public function destroy() { return CakeSession::destroy(); } /** * Returns Session id * * If $id is passed in a beforeFilter, the Session will be started * with the specified id * * @param string $id * @return string */ public function id($id = null) { return CakeSession::id($id); } /** * Returns a bool, whether or not the session has been started. * * @return boolean */ public function started() { return CakeSession::started(); } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/SessionComponent.php
PHP
gpl3
5,534
<?php /** * Email Component * * 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.Controller.Component * @since CakePHP(tm) v 1.2.0.3467 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Component', 'Controller'); App::uses('Multibyte', 'I18n'); App::uses('CakeEmail', 'Network/Email'); /** * EmailComponent * * This component is used for handling Internet Message Format based * based on the standard outlined in http://www.rfc-editor.org/rfc/rfc2822.txt * * @package Cake.Controller.Component * @link http://book.cakephp.org/2.0/en/core-libraries/components/email.html * @link http://book.cakephp.org/2.0/en/core-utility-libraries/email.html * @deprecated Use Network/CakeEmail */ class EmailComponent extends Component { /** * Recipient of the email * * @var string */ public $to = null; /** * The mail which the email is sent from * * @var string */ public $from = null; /** * The email the recipient will reply to * * @var string */ public $replyTo = null; /** * The read receipt email * * @var string */ public $readReceipt = null; /** * The mail that will be used in case of any errors like * - Remote mailserver down * - Remote user has exceeded his quota * - Unknown user * * @var string */ public $return = null; /** * 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 */ public $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 */ public $bcc = array(); /** * The date to put in the Date: header. This should be a date * conformant with the RFC2822 standard. Leave null, to have * today's date generated. * * @var string */ public $date = null; /** * The subject of the email * * @var string */ public $subject = null; /** * Associative array of a user defined headers * Keys will be prefixed 'X-' as per RFC2822 Section 4.7.5 * * @var array */ public $headers = array(); /** * List of additional headers * * These will NOT be used if you are using safemode and mail() * * @var string */ public $additionalParams = null; /** * Layout for the View * * @var string */ public $layout = 'default'; /** * Template for the view * * @var string */ public $template = null; /** * Line feed character(s) to be used when sending using mail() function * By default PHP_EOL is used. * RFC2822 requires it to be CRLF but some Unix * mail transfer agents replace LF by CRLF automatically * (which leads to doubling CR if CRLF is used). * * @var string */ public $lineFeed = PHP_EOL; /** * What format should the email be sent in * * Supported formats: * - text * - html * - both * * @var string */ public $sendAs = 'text'; /** * What method should the email be sent by * * Supported methods: * - mail * - smtp * - debug * * @var string */ public $delivery = 'mail'; /** * charset the email is sent in * * @var string */ public $charset = 'utf-8'; /** * List of files that should be attached to the email. * * Can be both absolute and relative paths * * @var array */ public $attachments = array(); /** * What mailer should EmailComponent identify itself as * * @var string */ public $xMailer = 'CakePHP Email Component'; /** * The list of paths to search if an attachment isnt absolute * * @var array */ public $filePaths = array(); /** * List of options to use for smtp mail method * * Options is: * - port * - host * - timeout * - username * - password * - client * * @var array */ public $smtpOptions = array(); /** * Contains the rendered plain text message if one was sent. * * @var string */ public $textMessage = null; /** * Contains the rendered HTML message if one was sent. * * @var string */ public $htmlMessage = null; /** * Whether to generate a Message-ID header for the * e-mail. True to generate a Message-ID, False to let * it be handled by sendmail (or similar) or a string * to completely override the Message-ID. * * If you are sending Email from a shell, be sure to set this value. As you * could encounter delivery issues if you do not. * * @var mixed */ public $messageId = true; /** * Controller reference * * @var Controller */ protected $_controller = null; /** * Constructor * * @param ComponentCollection $collection A ComponentCollection this component can use to lazy load its components * @param array $settings Array of configuration settings. */ public function __construct(ComponentCollection $collection, $settings = array()) { $this->_controller = $collection->getController(); parent::__construct($collection, $settings); } /** * Initialize component * * @param Controller $controller Instantiating controller * @return void */ public function initialize($controller) { if (Configure::read('App.encoding') !== null) { $this->charset = Configure::read('App.encoding'); } } /** * Send an email using the specified content, template and layout * * @param mixed $content Either an array of text lines, or a string with contents * If you are rendering a template this variable will be sent to the templates as `$content` * @param string $template Template to use when sending email * @param string $layout Layout to use to enclose email body * @return boolean Success */ public function send($content = null, $template = null, $layout = null) { $lib = new CakeEmail(); $lib->charset = $this->charset; $lib->from($this->_formatAddresses((array)$this->from)); if (!empty($this->to)) { $lib->to($this->_formatAddresses((array)$this->to)); } if (!empty($this->cc)) { $lib->cc($this->_formatAddresses((array)$this->cc)); } if (!empty($this->bcc)) { $lib->bcc($this->_formatAddresses((array)$this->bcc)); } if (!empty($this->replyTo)) { $lib->replyTo($this->_formatAddresses((array)$this->replyTo)); } if (!empty($this->return)) { $lib->returnPath($this->_formatAddresses((array)$this->return)); } if (!empty($readReceipt)) { $lib->readReceipt($this->_formatAddresses((array)$this->readReceipt)); } $lib->subject($this->subject)->messageID($this->messageId); $lib->helpers($this->_controller->helpers); $headers = array('X-Mailer' => $this->xMailer); foreach ($this->headers as $key => $value) { $headers['X-' . $key] = $value; } if ($this->date != false) { $headers['Date'] = $this->date; } $lib->setHeaders($headers); if ($template) { $this->template = $template; } if ($layout) { $this->layout = $layout; } $lib->template($this->template, $this->layout)->viewVars($this->_controller->viewVars)->emailFormat($this->sendAs); if (!empty($this->attachments)) { $lib->attachments($this->_formatAttachFiles()); } $lib->transport(ucfirst($this->delivery)); if ($this->delivery === 'mail') { $lib->config(array('eol' => $this->lineFeed, 'additionalParameters' => $this->additionalParams)); } elseif ($this->delivery === 'smtp') { $lib->config($this->smtpOptions); } else { $lib->config(array()); } $sent = $lib->send($content); $this->htmlMessage = $lib->message(CakeEmail::MESSAGE_HTML); if (empty($this->htmlMessage)) { $this->htmlMessage = null; } $this->textMessage = $lib->message(CakeEmail::MESSAGE_TEXT); if (empty($this->textMessage)) { $this->textMessage = null; } $this->_header = array(); $this->_message = array(); return $sent; } /** * Reset all EmailComponent internal variables to be able to send out a new email. * * @return void */ public function reset() { $this->template = null; $this->to = array(); $this->from = null; $this->replyTo = null; $this->return = null; $this->cc = array(); $this->bcc = array(); $this->subject = null; $this->additionalParams = null; $this->date = null; $this->attachments = array(); $this->htmlMessage = null; $this->textMessage = null; $this->messageId = true; } /** * Format the attach array * * @return array */ protected function _formatAttachFiles() { $files = array(); foreach ($this->attachments as $filename => $attachment) { $file = $this->_findFiles($attachment); if (!empty($file)) { if (is_int($filename)) { $filename = basename($file); } $files[$filename] = $file; } } return $files; } /** * Find the specified attachment in the list of file paths * * @param string $attachment Attachment file name to find * @return string Path to located file */ protected function _findFiles($attachment) { if (file_exists($attachment)) { return $attachment; } foreach ($this->filePaths as $path) { if (file_exists($path . DS . $attachment)) { $file = $path . DS . $attachment; return $file; } } return null; } /** * Encode the specified string using the current charset * * @param string $subject String to encode * @return string Encoded string */ protected function _encode($subject) { $subject = $this->_strip($subject); $nl = "\r\n"; if ($this->delivery == 'mail') { $nl = ''; } $internalEncoding = function_exists('mb_internal_encoding'); if ($internalEncoding) { $restore = mb_internal_encoding(); mb_internal_encoding($this->charset); } $return = mb_encode_mimeheader($subject, $this->charset, 'B', $nl); if ($internalEncoding) { mb_internal_encoding($restore); } return $return; } /** * Format addresses to be an array with email as key and alias as value * * @param array $addresses * @return array */ protected function _formatAddresses($addresses) { $formatted = array(); foreach ($addresses as $address) { if (preg_match('/((.*))?\s?<(.+)>/', $address, $matches) && !empty($matches[2])) { $formatted[$this->_strip($matches[3])] = $this->_encode($matches[2]); } else { $address = $this->_strip($address); $formatted[$address] = $address; } } return $formatted; } /** * Remove certain elements (such as bcc:, to:, %0a) from given value. * Helps prevent header injection / mainipulation on user content. * * @param string $value Value to strip * @param boolean $message Set to true to indicate main message content * @return string Stripped value */ protected function _strip($value, $message = false) { $search = '%0a|%0d|Content-(?:Type|Transfer-Encoding)\:'; $search .= '|charset\=|mime-version\:|multipart/mixed|(?:[^a-z]to|b?cc)\:.*'; if ($message !== true) { $search .= '|\r|\n'; } $search = '#(?:' . $search . ')#i'; while (preg_match($search, $value)) { $value = preg_replace($search, '', $value); } return $value; } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/EmailComponent.php
PHP
gpl3
11,185
<?php /** * Security Component * * 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.Controller.Component * @since CakePHP(tm) v 0.10.8.2156 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Component', 'Controller'); App::uses('String', 'Utility'); App::uses('Security', 'Utility'); /** * SecurityComponent * * @package Cake.Controller.Component * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html */ class SecurityComponent extends Component { /** * The controller method that will be called if this request is black-hole'd * * @var string */ public $blackHoleCallback = null; /** * List of controller actions for which a POST request is required * * @var array * @see SecurityComponent::requirePost() */ public $requirePost = array(); /** * List of controller actions for which a GET request is required * * @var array * @see SecurityComponent::requireGet() */ public $requireGet = array(); /** * List of controller actions for which a PUT request is required * * @var array * @see SecurityComponent::requirePut() */ public $requirePut = array(); /** * List of controller actions for which a DELETE request is required * * @var array * @see SecurityComponent::requireDelete() */ public $requireDelete = array(); /** * List of actions that require an SSL-secured connection * * @var array * @see SecurityComponent::requireSecure() */ public $requireSecure = array(); /** * List of actions that require a valid authentication key * * @var array * @see SecurityComponent::requireAuth() */ public $requireAuth = array(); /** * Controllers from which actions of the current controller are allowed to receive * requests. * * @var array * @see SecurityComponent::requireAuth() */ public $allowedControllers = array(); /** * Actions from which actions of the current controller are allowed to receive * requests. * * @var array * @see SecurityComponent::requireAuth() */ public $allowedActions = array(); /** * Deprecated property, superseded by unlockedFields. * * @var array * @deprecated * @see SecurityComponent::$unlockedFields */ public $disabledFields = array(); /** * Form fields to exclude from POST validation. Fields can be unlocked * either in the Component, or with FormHelper::unlockField(). * Fields that have been unlocked are not required to be part of the POST * and hidden unlocked fields do not have their values checked. * * @var array */ public $unlockedFields = array(); /** * Whether to validate POST data. Set to false to disable for data coming from 3rd party * services, etc. * * @var boolean */ public $validatePost = true; /** * Whether to use CSRF protected forms. Set to false to disable CSRF protection on forms. * * @var boolean * @see http://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) * @see SecurityComponent::$csrfExpires */ public $csrfCheck = true; /** * The duration from when a CSRF token is created that it will expire on. * Each form/page request will generate a new token that can only be submitted once unless * it expires. Can be any value compatible with strtotime() * * @var string */ public $csrfExpires = '+30 minutes'; /** * Controls whether or not CSRF tokens are use and burn. Set to false to not generate * new tokens on each request. One token will be reused until it expires. This reduces * the chances of users getting invalid requests because of token consumption. * It has the side effect of making CSRF less secure, as tokens are reusable. * * @var boolean */ public $csrfUseOnce = true; /** * Other components used by the Security component * * @var array */ public $components = array('Session'); /** * Holds the current action of the controller * * @var string */ protected $_action = null; /** * Request object * * @var CakeRequest */ public $request; /** * Component startup. All security checking happens here. * * @param Controller $controller Instantiating controller * @return void */ public function startup($controller) { $this->request = $controller->request; $this->_action = $this->request->params['action']; $this->_methodsRequired($controller); $this->_secureRequired($controller); $this->_authRequired($controller); $isPost = ($this->request->is('post') || $this->request->is('put')); $isNotRequestAction = ( !isset($controller->request->params['requested']) || $controller->request->params['requested'] != 1 ); if ($isPost && $isNotRequestAction && $this->validatePost) { if ($this->_validatePost($controller) === false) { return $this->blackHole($controller, 'auth'); } } if ($isPost && $isNotRequestAction && $this->csrfCheck) { if ($this->_validateCsrf($controller) === false) { return $this->blackHole($controller, 'csrf'); } } $this->_generateToken($controller); } /** * Sets the actions that require a POST request, or empty for all actions * * @return void * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requirePost */ public function requirePost() { $args = func_get_args(); $this->_requireMethod('Post', $args); } /** * Sets the actions that require a GET request, or empty for all actions * * @return void */ public function requireGet() { $args = func_get_args(); $this->_requireMethod('Get', $args); } /** * Sets the actions that require a PUT request, or empty for all actions * * @return void */ public function requirePut() { $args = func_get_args(); $this->_requireMethod('Put', $args); } /** * Sets the actions that require a DELETE request, or empty for all actions * * @return void */ public function requireDelete() { $args = func_get_args(); $this->_requireMethod('Delete', $args); } /** * Sets the actions that require a request that is SSL-secured, or empty for all actions * * @return void * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requireSecure */ public function requireSecure() { $args = func_get_args(); $this->_requireMethod('Secure', $args); } /** * Sets the actions that require an authenticated request, or empty for all actions * * @return void * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#SecurityComponent::requireAuth */ public function requireAuth() { $args = func_get_args(); $this->_requireMethod('Auth', $args); } /** * Black-hole an invalid request with a 404 error or custom callback. If SecurityComponent::$blackHoleCallback * is specified, it will use this callback by executing the method indicated in $error * * @param Controller $controller Instantiating controller * @param string $error Error method * @return mixed If specified, controller blackHoleCallback's response, or no return otherwise * @see SecurityComponent::$blackHoleCallback * @link http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#handling-blackhole-callbacks */ public function blackHole($controller, $error = '') { if ($this->blackHoleCallback == null) { $code = 404; if ($error == 'login') { $code = 401; $controller->header($this->loginRequest()); } return $controller->redirect(null, $code, true); } else { return $this->_callback($controller, $this->blackHoleCallback, array($error)); } } /** * Sets the actions that require a $method HTTP request, or empty for all actions * * @param string $method The HTTP method to assign controller actions to * @param array $actions Controller actions to set the required HTTP method to. * @return void */ protected function _requireMethod($method, $actions = array()) { if (isset($actions[0]) && is_array($actions[0])) { $actions = $actions[0]; } $this->{'require' . $method} = (empty($actions)) ? array('*'): $actions; } /** * Check if HTTP methods are required * * @param Controller $controller Instantiating controller * @return boolean true if $method is required */ protected function _methodsRequired($controller) { foreach (array('Post', 'Get', 'Put', 'Delete') as $method) { $property = 'require' . $method; if (is_array($this->$property) && !empty($this->$property)) { $require = $this->$property; if (in_array($this->_action, $require) || $this->$property == array('*')) { if (!$this->request->is($method)) { if (!$this->blackHole($controller, $method)) { return null; } } } } } return true; } /** * Check if access requires secure connection * * @param Controller $controller Instantiating controller * @return boolean true if secure connection required */ protected function _secureRequired($controller) { if (is_array($this->requireSecure) && !empty($this->requireSecure)) { $requireSecure = $this->requireSecure; if (in_array($this->_action, $requireSecure) || $this->requireSecure == array('*')) { if (!$this->request->is('ssl')) { if (!$this->blackHole($controller, 'secure')) { return null; } } } } return true; } /** * Check if authentication is required * * @param Controller $controller Instantiating controller * @return boolean true if authentication required */ protected function _authRequired($controller) { if (is_array($this->requireAuth) && !empty($this->requireAuth) && !empty($this->request->data)) { $requireAuth = $this->requireAuth; if (in_array($this->request->params['action'], $requireAuth) || $this->requireAuth == array('*')) { if (!isset($controller->request->data['_Token'] )) { if (!$this->blackHole($controller, 'auth')) { return null; } } if ($this->Session->check('_Token')) { $tData = $this->Session->read('_Token'); if (!empty($tData['allowedControllers']) && !in_array($this->request->params['controller'], $tData['allowedControllers']) || !empty($tData['allowedActions']) && !in_array($this->request->params['action'], $tData['allowedActions'])) { if (!$this->blackHole($controller, 'auth')) { return null; } } } else { if (!$this->blackHole($controller, 'auth')) { return null; } } } } return true; } /** * Validate submitted form * * @param Controller $controller Instantiating controller * @return boolean true if submitted form is valid */ protected function _validatePost($controller) { if (empty($controller->request->data)) { return true; } $data = $controller->request->data; if (!isset($data['_Token']) || !isset($data['_Token']['fields']) || !isset($data['_Token']['unlocked'])) { return false; } $locked = ''; $check = $controller->request->data; $token = urldecode($check['_Token']['fields']); $unlocked = urldecode($check['_Token']['unlocked']); if (strpos($token, ':')) { list($token, $locked) = explode(':', $token, 2); } unset($check['_Token']); $locked = explode('|', $locked); $unlocked = explode('|', $unlocked); $lockedFields = array(); $fields = Set::flatten($check); $fieldList = array_keys($fields); $multi = array(); foreach ($fieldList as $i => $key) { if (preg_match('/\.\d+$/', $key)) { $multi[$i] = preg_replace('/\.\d+$/', '', $key); unset($fieldList[$i]); } } if (!empty($multi)) { $fieldList += array_unique($multi); } $unlockedFields = array_unique( array_merge((array)$this->disabledFields, (array)$this->unlockedFields, $unlocked) ); foreach ($fieldList as $i => $key) { $isDisabled = false; $isLocked = (is_array($locked) && in_array($key, $locked)); if (!empty($unlockedFields)) { foreach ($unlockedFields as $off) { $off = explode('.', $off); $field = array_values(array_intersect(explode('.', $key), $off)); $isUnlocked = ($field === $off); if ($isUnlocked) { break; } } } if ($isUnlocked || $isLocked) { unset($fieldList[$i]); if ($isLocked) { $lockedFields[$key] = $fields[$key]; } } } sort($unlocked, SORT_STRING); sort($fieldList, SORT_STRING); ksort($lockedFields, SORT_STRING); $fieldList += $lockedFields; $unlocked = implode('|', $unlocked); $check = Security::hash(serialize($fieldList) . $unlocked . Configure::read('Security.salt')); return ($token === $check); } /** * Add authentication key for new form posts * * @param Controller $controller Instantiating controller * @return boolean Success */ protected function _generateToken($controller) { if (isset($controller->request->params['requested']) && $controller->request->params['requested'] === 1) { if ($this->Session->check('_Token')) { $tokenData = $this->Session->read('_Token'); $controller->request->params['_Token'] = $tokenData; } return false; } $authKey = Security::generateAuthKey(); $token = array( 'key' => $authKey, 'allowedControllers' => $this->allowedControllers, 'allowedActions' => $this->allowedActions, 'unlockedFields' => array_merge($this->disabledFields, $this->unlockedFields), 'csrfTokens' => array() ); $tokenData = array(); if ($this->Session->check('_Token')) { $tokenData = $this->Session->read('_Token'); if (!empty($tokenData['csrfTokens']) && is_array($tokenData['csrfTokens'])) { $token['csrfTokens'] = $this->_expireTokens($tokenData['csrfTokens']); } } if ($this->csrfCheck && ($this->csrfUseOnce || empty($token['csrfTokens'])) ) { $token['csrfTokens'][$authKey] = strtotime($this->csrfExpires); } if ($this->csrfCheck && $this->csrfUseOnce == false) { $csrfTokens = array_keys($token['csrfTokens']); $token['key'] = $csrfTokens[0]; } $this->Session->write('_Token', $token); $controller->request->params['_Token'] = array( 'key' => $token['key'], 'unlockedFields' => $token['unlockedFields'] ); return true; } /** * Validate that the controller has a CSRF token in the POST data * and that the token is legit/not expired. If the token is valid * it will be removed from the list of valid tokens. * * @param Controller $controller A controller to check * @return boolean Valid csrf token. */ protected function _validateCsrf($controller) { $token = $this->Session->read('_Token'); $requestToken = $controller->request->data('_Token.key'); if (isset($token['csrfTokens'][$requestToken]) && $token['csrfTokens'][$requestToken] >= time()) { if ($this->csrfUseOnce) { $this->Session->delete('_Token.csrfTokens.' . $requestToken); } return true; } return false; } /** * Expire CSRF nonces and remove them from the valid tokens. * Uses a simple timeout to expire the tokens. * * @param array $tokens An array of nonce => expires. * @return array An array of nonce => expires. */ protected function _expireTokens($tokens) { $now = time(); foreach ($tokens as $nonce => $expires) { if ($expires < $now) { unset($tokens[$nonce]); } } return $tokens; } /** * Calls a controller callback method * * @param Controller $controller Controller to run callback on * @param string $method Method to execute * @param array $params Parameters to send to method * @return mixed Controller callback method's response */ protected function _callback($controller, $method, $params = array()) { if (is_callable(array($controller, $method))) { return call_user_func_array(array(&$controller, $method), empty($params) ? null : $params); } else { return null; } } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/SecurityComponent.php
PHP
gpl3
16,005
<?php /** * Cookie Component * * 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.Controller.Component * @since CakePHP(tm) v 1.2.0.4213 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Component', 'Controller'); App::uses('Security', 'Utility'); /** * Cookie Component. * * Cookie handling for the controller. * * @package Cake.Controller.Component * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html * */ class CookieComponent extends Component { /** * The name of the cookie. * * Overridden with the controller beforeFilter(); * $this->Cookie->name = 'CookieName'; * * @var string */ public $name = 'CakeCookie'; /** * The time a cookie will remain valid. * * Can be either integer Unix timestamp or a date string. * * Overridden with the controller beforeFilter(); * $this->Cookie->time = '5 Days'; * * @var mixed */ public $time = null; /** * Cookie path. * * Overridden with the controller beforeFilter(); * $this->Cookie->path = '/'; * * The path on the server in which the cookie will be available on. * If public $cookiePath is set to '/foo/', the cookie will only be available * within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. * The default value is the entire domain. * * @var string */ public $path = '/'; /** * Domain path. * * The domain that the cookie is available. * * Overridden with the controller beforeFilter(); * $this->Cookie->domain = '.example.com'; * * To make the cookie available on all subdomains of example.com. * Set $this->Cookie->domain = '.example.com'; in your controller beforeFilter * * @var string */ public $domain = ''; /** * Secure HTTPS only cookie. * * Overridden with the controller beforeFilter(); * $this->Cookie->secure = true; * * Indicates that the cookie should only be transmitted over a secure HTTPS connection. * When set to true, the cookie will only be set if a secure connection exists. * * @var boolean */ public $secure = false; /** * Encryption key. * * Overridden with the controller beforeFilter(); * $this->Cookie->key = 'SomeRandomString'; * * @var string */ public $key = null; /** * HTTP only cookie * * Set to true to make HTTP only cookies. Cookies that are HTTP only * are not accessible in Javascript. * * @var boolean */ public $httpOnly = false; /** * Values stored in the cookie. * * Accessed in the controller using $this->Cookie->read('Name.key'); * * @see CookieComponent::read(); * @var string */ protected $_values = array(); /** * Type of encryption to use. * * Currently only one method is available * Defaults to Security::cipher(); * * @var string * @todo add additional encryption methods */ protected $_type = 'cipher'; /** * Used to reset cookie time if $expire is passed to CookieComponent::write() * * @var string */ protected $_reset = null; /** * Expire time of the cookie * * This is controlled by CookieComponent::time; * * @var string */ protected $_expires = 0; /** * Constructor * * @param ComponentCollection $collection A ComponentCollection for this component * @param array $settings Array of settings. */ public function __construct(ComponentCollection $collection, $settings = array()) { $this->key = Configure::read('Security.salt'); parent::__construct($collection, $settings); if (isset($this->time)) { $this->_expire($this->time); } } /** * Start CookieComponent for use in the controller * * @param Controller $controller * @return void */ public function startup($controller) { $this->_expire($this->time); if (isset($_COOKIE[$this->name])) { $this->_values = $this->_decrypt($_COOKIE[$this->name]); } } /** * Write a value to the $_COOKIE[$key]; * * Optional [Name.], required key, optional $value, optional $encrypt, optional $expires * $this->Cookie->write('[Name.]key, $value); * * By default all values are encrypted. * You must pass $encrypt false to store values in clear test * * You must use this method before any output is sent to the browser. * Failure to do so will result in header already sent errors. * * @param mixed $key Key for the value * @param mixed $value Value * @param boolean $encrypt Set to true to encrypt value, false otherwise * @param string $expires Can be either Unix timestamp, or date string * @return void */ public function write($key, $value = null, $encrypt = true, $expires = null) { if (is_null($encrypt)) { $encrypt = true; } $this->_encrypted = $encrypt; $this->_expire($expires); if (!is_array($key)) { $key = array($key => $value); } foreach ($key as $name => $value) { if (strpos($name, '.') === false) { $this->_values[$name] = $value; $this->_write("[$name]", $value); } else { $names = explode('.', $name, 2); if (!isset($this->_values[$names[0]])) { $this->_values[$names[0]] = array(); } $this->_values[$names[0]] = Set::insert($this->_values[$names[0]], $names[1], $value); $this->_write('[' . implode('][', $names) . ']', $value); } } $this->_encrypted = true; } /** * Read the value of the $_COOKIE[$key]; * * Optional [Name.], required key * $this->Cookie->read(Name.key); * * @param mixed $key Key of the value to be obtained. If none specified, obtain map key => values * @return string or null, value for specified key */ public function read($key = null) { if (empty($this->_values) && isset($_COOKIE[$this->name])) { $this->_values = $this->_decrypt($_COOKIE[$this->name]); } if (is_null($key)) { return $this->_values; } if (strpos($key, '.') !== false) { $names = explode('.', $key, 2); $key = $names[0]; } if (!isset($this->_values[$key])) { return null; } if (!empty($names[1])) { return Set::extract($this->_values[$key], $names[1]); } return $this->_values[$key]; } /** * Delete a cookie value * * Optional [Name.], required key * $this->Cookie->read('Name.key); * * You must use this method before any output is sent to the browser. * Failure to do so will result in header already sent errors. * * @param string $key Key of the value to be deleted * @return void */ public function delete($key) { if (empty($this->_values)) { $this->read(); } if (strpos($key, '.') === false) { if (isset($this->_values[$key]) && is_array($this->_values[$key])) { foreach ($this->_values[$key] as $idx => $val) { $this->_delete("[$key][$idx]"); } } $this->_delete("[$key]"); unset($this->_values[$key]); return; } $names = explode('.', $key, 2); if (isset($this->_values[$names[0]])) { $this->_values[$names[0]] = Set::remove($this->_values[$names[0]], $names[1]); } $this->_delete('[' . implode('][', $names) . ']'); } /** * Destroy current cookie * * You must use this method before any output is sent to the browser. * Failure to do so will result in header already sent errors. * * @return void */ public function destroy() { if (isset($_COOKIE[$this->name])) { $this->_values = $this->_decrypt($_COOKIE[$this->name]); } foreach ($this->_values as $name => $value) { if (is_array($value)) { foreach ($value as $key => $val) { unset($this->_values[$name][$key]); $this->_delete("[$name][$key]"); } } unset($this->_values[$name]); $this->_delete("[$name]"); } } /** * Will allow overriding default encryption method. * * @param string $type Encryption method * @return void * @todo NOT IMPLEMENTED */ public function type($type = 'cipher') { $this->_type = 'cipher'; } /** * Set the expire time for a session variable. * * Creates a new expire time for a session variable. * $expire can be either integer Unix timestamp or a date string. * * Used by write() * CookieComponent::write(string, string, boolean, 8400); * CookieComponent::write(string, string, boolean, '5 Days'); * * @param mixed $expires Can be either Unix timestamp, or date string * @return integer Unix timestamp */ protected function _expire($expires = null) { $now = time(); if (is_null($expires)) { return $this->_expires; } $this->_reset = $this->_expires; if ($expires == 0) { return $this->_expires = 0; } if (is_integer($expires) || is_numeric($expires)) { return $this->_expires = $now + intval($expires); } return $this->_expires = strtotime($expires, $now); } /** * Set cookie * * @param string $name Name for cookie * @param string $value Value for cookie * @return void */ protected function _write($name, $value) { $this->_setcookie( $this->name . $name, $this->_encrypt($value), $this->_expires, $this->path, $this->domain, $this->secure, $this->httpOnly ); if (!is_null($this->_reset)) { $this->_expires = $this->_reset; $this->_reset = null; } } /** * Sets a cookie expire time to remove cookie value * * @param string $name Name of cookie * @return void */ protected function _delete($name) { $this->_setcookie( $this->name . $name, '', time() - 42000, $this->path, $this->domain, $this->secure, $this->httpOnly ); } /** * Object wrapper for setcookie() so it can be mocked in unit tests. * * @todo Re-factor setting cookies into CakeResponse. Cookies are part * of the HTTP response, and should be handled there. * * @param string $name Name of the cookie * @param string $value Value of the cookie * @param integer $expire Time the cookie expires in * @param string $path Path the cookie applies to * @param string $domain Domain the cookie is for. * @param boolean $secure Is the cookie https? * @param boolean $httpOnly Is the cookie available in the client? * @return void */ protected function _setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly = false) { setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly); } /** * Encrypts $value using public $type method in Security class * * @param string $value Value to encrypt * @return string encrypted string * @return string Encoded values */ protected function _encrypt($value) { if (is_array($value)) { $value = $this->_implode($value); } if ($this->_encrypted === true) { $type = $this->_type; $value = "Q2FrZQ==." .base64_encode(Security::$type($value, $this->key)); } return $value; } /** * Decrypts $value using public $type method in Security class * * @param array $values Values to decrypt * @return string decrypted string */ protected function _decrypt($values) { $decrypted = array(); $type = $this->_type; foreach ((array)$values as $name => $value) { if (is_array($value)) { foreach ($value as $key => $val) { $pos = strpos($val, 'Q2FrZQ==.'); $decrypted[$name][$key] = $this->_explode($val); if ($pos !== false) { $val = substr($val, 8); $decrypted[$name][$key] = $this->_explode(Security::$type(base64_decode($val), $this->key)); } } } else { $pos = strpos($value, 'Q2FrZQ==.'); $decrypted[$name] = $this->_explode($value); if ($pos !== false) { $value = substr($value, 8); $decrypted[$name] = $this->_explode(Security::$type(base64_decode($value), $this->key)); } } } return $decrypted; } /** * Implode method to keep keys are multidimensional arrays * * @param array $array Map of key and values * @return string A json encoded string. */ protected function _implode(array $array) { return json_encode($array); } /** * Explode method to return array from string set in CookieComponent::_implode() * Maintains reading backwards compatibility with 1.x CookieComponent::_implode(). * * @param string $string A string containing JSON encoded data, or a bare string. * @return array Map of key and values */ protected function _explode($string) { if ($string[0] === '{' || $string[0] === '[') { $ret = json_decode($string, true); return ($ret != null) ? $ret : $string; } $array = array(); foreach (explode(',', $string) as $pair) { $key = explode('|', $pair); if (!isset($key[1])) { return $key[0]; } $array[$key[0]] = $key[1]; } return $array; } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/CookieComponent.php
PHP
gpl3
12,630
<?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 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Security', 'Utility'); /** * Base Authentication class with common methods and properties. * * @package Cake.Controller.Component.Auth */ abstract class BaseAuthenticate { /** * Settings for this object. * * - `fields` The fields to use to identify a user by. * - `userModel` The model name of the User, defaults to User. * - `scope` Additional conditions to use when looking up and authenticating users, * i.e. `array('User.is_active' => 1).` * * @var array */ public $settings = array( 'fields' => array( 'username' => 'username', 'password' => 'password' ), 'userModel' => 'User', 'scope' => array() ); /** * A Component collection, used to get more components. * * @var ComponentCollection */ protected $_Collection; /** * Constructor * * @param ComponentCollection $collection The Component collection used on this request. * @param array $settings Array of settings to use. */ public function __construct(ComponentCollection $collection, $settings) { $this->_Collection = $collection; $this->settings = Set::merge($this->settings, $settings); } /** * Find a user record using the standard options. * * @param string $username The username/identifier. * @param string $password The unhashed password. * @return Mixed Either false on failure, or an array of user data. */ protected function _findUser($username, $password) { $userModel = $this->settings['userModel']; list($plugin, $model) = pluginSplit($userModel); $fields = $this->settings['fields']; $conditions = array( $model . '.' . $fields['username'] => $username, $model . '.' . $fields['password'] => $this->_password($password), ); if (!empty($this->settings['scope'])) { $conditions = array_merge($conditions, $this->settings['scope']); } $result = ClassRegistry::init($userModel)->find('first', array( 'conditions' => $conditions, 'recursive' => 0 )); if (empty($result) || empty($result[$model])) { return false; } unset($result[$model][$fields['password']]); return $result[$model]; } /** * Hash the plain text password so that it matches the hashed/encrytped password * in the datasource. * * @param string $password The plain text password. * @return string The hashed form of the password. */ protected function _password($password) { return Security::hash($password, null, true); } /** * Authenticate a user based on the request information. * * @param CakeRequest $request Request to get authentication information from. * @param CakeResponse $response A response object that can have headers added. * @return mixed Either false on failure, or an array of user data on success. */ abstract public function authenticate(CakeRequest $request, CakeResponse $response); /** * Allows you to hook into AuthComponent::logout(), * and implement specialized logout behaviour. * * All attached authentication objects will have this method * called when a user logs out. * * @param array $user The user about to be logged out. * @return void */ public function logout($user) { } /** * Get a user based on information in the request. Primarily used by stateless authentication * systems like basic and digest auth. * * @param CakeRequest $request Request object. * @return mixed Either false or an array of user information */ public function getUser($request) { return false; } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/Auth/BaseAuthenticate.php
PHP
gpl3
3,931
<?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 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('BaseAuthenticate', 'Controller/Component/Auth'); /** * An authentication adapter for AuthComponent. Provides the ability to authenticate using POST * data. Can be used by configuring AuthComponent to use it via the AuthComponent::$authenticate setting. * * {{{ * $this->Auth->authenticate = array( * 'Form' => array( * 'scope' => array('User.active' => 1) * ) * ) * }}} * * When configuring FormAuthenticate you can pass in settings to which fields, model and additional conditions * are used. See FormAuthenticate::$settings for more information. * * @package Cake.Controller.Component.Auth * @since 2.0 * @see AuthComponent::$authenticate */ class FormAuthenticate extends BaseAuthenticate { /** * Authenticates the identity contained in a request. Will use the `settings.userModel`, and `settings.fields` * to find POST data that is used to find a matching record in the `settings.userModel`. Will return false if * there is no post data, either username or password is missing, of if the scope conditions have not been met. * * @param CakeRequest $request The request that contains login information. * @param CakeResponse $response Unused response object. * @return mixed. False on login failure. An array of User data on success. */ public function authenticate(CakeRequest $request, CakeResponse $response) { $userModel = $this->settings['userModel']; list($plugin, $model) = pluginSplit($userModel); $fields = $this->settings['fields']; if (empty($request->data[$model])) { return false; } if ( empty($request->data[$model][$fields['username']]) || empty($request->data[$model][$fields['password']]) ) { return false; } return $this->_findUser( $request->data[$model][$fields['username']], $request->data[$model][$fields['password']] ); } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/Auth/FormAuthenticate.php
PHP
gpl3
2,368
<?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 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('BaseAuthorize', 'Controller/Component/Auth'); /** * An authorization adapter for AuthComponent. Provides the ability to authorize using the AclComponent, * If AclComponent is not already loaded it will be loaded using the Controller's ComponentCollection. * * @package Cake.Controller.Component.Auth * @since 2.0 * @see AuthComponent::$authenticate * @see AclComponent::check() */ class ActionsAuthorize extends BaseAuthorize { /** * Authorize a user using the AclComponent. * * @param array $user The user to authorize * @param CakeRequest $request The request needing authorization. * @return boolean */ public function authorize($user, CakeRequest $request) { $Acl = $this->_Collection->load('Acl'); $user = array($this->settings['userModel'] => $user); return $Acl->check($user, $this->action($request)); } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/Auth/ActionsAuthorize.php
PHP
gpl3
1,377
<?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 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('BaseAuthorize', 'Controller/Component/Auth'); App::uses('Router', 'Routing'); /** * An authorization adapter for AuthComponent. Provides the ability to authorize using CRUD mappings. * CRUD mappings allow you to translate controller actions into *C*reate *R*ead *U*pdate *D*elete actions. * This is then checked in the AclComponent as specific permissions. * * For example, taking `/posts/index` as the current request. The default mapping for `index`, is a `read` permission * check. The Acl check would then be for the `posts` controller with the `read` permission. This allows you * to create permission systems that focus more on what is being done to resources, rather than the specific actions * being visited. * * @package Cake.Controller.Component.Auth * @since 2.0 * @see AuthComponent::$authenticate * @see AclComponent::check() */ class CrudAuthorize extends BaseAuthorize { /** * Sets up additional actionMap values that match the configured `Routing.prefixes`. * * @param ComponentCollection $collection The component collection from the controller. * @param string $settings An array of settings. This class does not use any settings. */ public function __construct(ComponentCollection $collection, $settings = array()) { parent::__construct($collection, $settings); $this->_setPrefixMappings(); } /** * sets the crud mappings for prefix routes. * * @return void */ protected function _setPrefixMappings() { $crud = array('create', 'read', 'update', 'delete'); $map = array_combine($crud, $crud); $prefixes = Router::prefixes(); if (!empty($prefixes)) { foreach ($prefixes as $prefix) { $map = array_merge($map, array( $prefix . '_index' => 'read', $prefix . '_add' => 'create', $prefix . '_edit' => 'update', $prefix . '_view' => 'read', $prefix . '_remove' => 'delete', $prefix . '_create' => 'create', $prefix . '_read' => 'read', $prefix . '_update' => 'update', $prefix . '_delete' => 'delete' )); } } $this->mapActions($map); } /** * Authorize a user using the mapped actions and the AclComponent. * * @param array $user The user to authorize * @param CakeRequest $request The request needing authorization. * @return boolean */ public function authorize($user, CakeRequest $request) { if (!isset($this->settings['actionMap'][$request->params['action']])) { trigger_error(__d('cake_dev', 'CrudAuthorize::authorize() - Attempted access of un-mapped action "%1$s" in controller "%2$s"', $request->action, $request->controller ), E_USER_WARNING ); return false; } $user = array($this->settings['userModel'] => $user); $Acl = $this->_Collection->load('Acl'); return $Acl->check( $user, $this->action($request, ':controller'), $this->settings['actionMap'][$request->params['action']] ); } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/Auth/CrudAuthorize.php
PHP
gpl3
3,414
<?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 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('BaseAuthenticate', 'Controller/Component/Auth'); /** * Basic Authentication adapter for AuthComponent. * * Provides Basic HTTP authentication support for AuthComponent. Basic Auth will authenticate users * against the configured userModel and verify the username and passwords match. Clients using Basic Authentication * must support cookies. Since AuthComponent identifies users based on Session contents, clients using Basic * Auth must support cookies. * * ### Using Basic auth * * In your controller's components array, add auth + the required settings. * {{{ * public $components = array( * 'Auth' => array( * 'authenticate' => array('Basic') * ) * ); * }}} * * In your login function just call `$this->Auth->login()` without any checks for POST data. This * will send the authentication headers, and trigger the login dialog in the browser/client. * * @package Cake.Controller.Component.Auth * @since 2.0 */ class BasicAuthenticate extends BaseAuthenticate { /** * Settings for this object. * * - `fields` The fields to use to identify a user by. * - `userModel` The model name of the User, defaults to User. * - `scope` Additional conditions to use when looking up and authenticating users, * i.e. `array('User.is_active' => 1).` * - `realm` The realm authentication is for. Defaults the server name. * * @var array */ public $settings = array( 'fields' => array( 'username' => 'username', 'password' => 'password' ), 'userModel' => 'User', 'scope' => array(), 'realm' => '', ); /** * Constructor, completes configuration for basic authentication. * * @param ComponentCollection $collection The Component collection used on this request. * @param array $settings An array of settings. */ public function __construct(ComponentCollection $collection, $settings) { parent::__construct($collection, $settings); if (empty($this->settings['realm'])) { $this->settings['realm'] = env('SERVER_NAME'); } } /** * Authenticate a user using basic HTTP auth. Will use the configured User model and attempt a * login using basic HTTP auth. * * @param CakeRequest $request The request to authenticate with. * @param CakeResponse $response The response to add headers to. * @return mixed Either false on failure, or an array of user data on success. */ public function authenticate(CakeRequest $request, CakeResponse $response) { $result = $this->getUser($request); if (empty($result)) { $response->header($this->loginHeaders()); $response->statusCode(401); $response->send(); return false; } return $result; } /** * Get a user based on information in the request. Used by cookie-less auth for stateless clients. * * @param CakeRequest $request Request object. * @return mixed Either false or an array of user information */ public function getUser($request) { $username = env('PHP_AUTH_USER'); $pass = env('PHP_AUTH_PW'); if (empty($username) || empty($pass)) { return false; } return $this->_findUser($username, $pass); } /** * Generate the login headers * * @return string Headers for logging in. */ public function loginHeaders() { return sprintf('WWW-Authenticate: Basic realm="%s"', $this->settings['realm']); } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/Auth/BasicAuthenticate.php
PHP
gpl3
3,795
<?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 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Abstract base authorization adapter for AuthComponent. * * @package Cake.Controller.Component.Auth * @since 2.0 * @see AuthComponent::$authenticate */ abstract class BaseAuthorize { /** * Controller for the request. * * @var Controller */ protected $_Controller = null; /** * Component collection instance for getting more components. * * @var ComponentCollection */ protected $_Collection; /** * Settings for authorize objects. * * - `actionPath` - The path to ACO nodes that contains the nodes for controllers. Used as a prefix * when calling $this->action(); * - `actionMap` - Action -> crud mappings. Used by authorization objects that want to map actions to CRUD roles. * - `userModel` - Model name that ARO records can be found under. Defaults to 'User'. * * @var array */ public $settings = array( 'actionPath' => null, 'actionMap' => array( 'index' => 'read', 'add' => 'create', 'edit' => 'update', 'view' => 'read', 'delete' => 'delete', 'remove' => 'delete' ), 'userModel' => 'User' ); /** * Constructor * * @param ComponentCollection $collection The controller for this request. * @param string $settings An array of settings. This class does not use any settings. */ public function __construct(ComponentCollection $collection, $settings = array()) { $this->_Collection = $collection; $controller = $collection->getController(); $this->controller($controller); $this->settings = Set::merge($this->settings, $settings); } /** * Checks user authorization. * * @param array $user Active user data * @param CakeRequest $request * @return boolean */ abstract public function authorize($user, CakeRequest $request); /** * Accessor to the controller object. * * @param mixed $controller null to get, a controller to set. * @return mixed * @throws CakeException */ public function controller($controller = null) { if ($controller) { if (!$controller instanceof Controller) { throw new CakeException(__d('cake_dev', '$controller needs to be an instance of Controller')); } $this->_Controller = $controller; return true; } return $this->_Controller; } /** * Get the action path for a given request. Primarily used by authorize objects * that need to get information about the plugin, controller, and action being invoked. * * @param CakeRequest $request The request a path is needed for. * @param string $path * @return string the action path for the given request. */ public function action($request, $path = '/:plugin/:controller/:action') { $plugin = empty($request['plugin']) ? null : Inflector::camelize($request['plugin']) . '/'; return str_replace( array(':controller', ':action', ':plugin/'), array(Inflector::camelize($request['controller']), $request['action'], $plugin), $this->settings['actionPath'] . $path ); } /** * Maps crud actions to actual action names. Used to modify or get the current mapped actions. * * Create additional mappings for a standard CRUD operation: * * {{{ * $this->Auth->mapActions(array('create' => array('add', 'register')); * }}} * * Create mappings for custom CRUD operations: * * {{{ * $this->Auth->mapActions(array('my_action' => 'admin')); * }}} * * You can use the custom CRUD operations to create additional generic permissions * that behave like CRUD operations. Doing this will require additional columns on the * permissions lookup. When using with DbAcl, you'll have to add additional _admin type columns * to the `aros_acos` table. * * @param mixed $map Either an array of mappings, or undefined to get current values. * @return mixed Either the current mappings or null when setting. * @see AuthComponent::mapActions() */ public function mapActions($map = array()) { if (empty($map)) { return $this->settings['actionMap']; } $crud = array('create', 'read', 'update', 'delete'); foreach ($map as $action => $type) { if (in_array($action, $crud) && is_array($type)) { foreach ($type as $typedAction) { $this->settings['actionMap'][$typedAction] = $action; } } else { $this->settings['actionMap'][$action] = $type; } } } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/Auth/BaseAuthorize.php
PHP
gpl3
4,719
<?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 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('BaseAuthenticate', 'Controller/Component/Auth'); /** * Digest Authentication adapter for AuthComponent. * * Provides Digest HTTP authentication support for AuthComponent. Unlike most AuthComponent adapters, * DigestAuthenticate requires a special password hash that conforms to RFC2617. You can create this * password using `DigestAuthenticate::password()`. If you wish to use digest authentication alongside other * authentication methods, its recommended that you store the digest authentication separately. * * Clients using Digest Authentication must support cookies. Since AuthComponent identifies users based * on Session contents, clients without support for cookies will not function properly. * * ### Using Digest auth * * In your controller's components array, add auth + the required settings. * {{{ * public $components = array( * 'Auth' => array( * 'authenticate' => array('Digest') * ) * ); * }}} * * In your login function just call `$this->Auth->login()` without any checks for POST data. This * will send the authentication headers, and trigger the login dialog in the browser/client. * * ### Generating passwords compatible with Digest authentication. * * Due to the Digest authentication specification, digest auth requires a special password value. You * can generate this password using `DigestAuthenticate::password()` * * `$digestPass = DigestAuthenticate::password($username, env('SERVER_NAME'), $password);` * * Its recommended that you store this digest auth only password separate from password hashes used for other * login methods. For example `User.digest_pass` could be used for a digest password, while `User.password` would * store the password hash for use with other methods like Basic or Form. * * @package Cake.Controller.Component.Auth * @since 2.0 */ class DigestAuthenticate extends BaseAuthenticate { /** * Settings for this object. * * - `fields` The fields to use to identify a user by. * - `userModel` The model name of the User, defaults to User. * - `scope` Additional conditions to use when looking up and authenticating users, * i.e. `array('User.is_active' => 1).` * - `realm` The realm authentication is for, Defaults to the servername. * - `nonce` A nonce used for authentication. Defaults to `uniqid()`. * - `qop` Defaults to auth, no other values are supported at this time. * - `opaque` A string that must be returned unchanged by clients. Defaults to `md5($settings['realm'])` * * @var array */ public $settings = array( 'fields' => array( 'username' => 'username', 'password' => 'password' ), 'userModel' => 'User', 'scope' => array(), 'realm' => '', 'qop' => 'auth', 'nonce' => '', 'opaque' => '' ); /** * Constructor, completes configuration for digest authentication. * * @param ComponentCollection $collection The Component collection used on this request. * @param array $settings An array of settings. */ public function __construct(ComponentCollection $collection, $settings) { parent::__construct($collection, $settings); if (empty($this->settings['realm'])) { $this->settings['realm'] = env('SERVER_NAME'); } if (empty($this->settings['nonce'])) { $this->settings['nonce'] = uniqid(''); } if (empty($this->settings['opaque'])) { $this->settings['opaque'] = md5($this->settings['realm']); } } /** * Authenticate a user using Digest HTTP auth. Will use the configured User model and attempt a * login using Digest HTTP auth. * * @param CakeRequest $request The request to authenticate with. * @param CakeResponse $response The response to add headers to. * @return mixed Either false on failure, or an array of user data on success. */ public function authenticate(CakeRequest $request, CakeResponse $response) { $user = $this->getUser($request); if (empty($user)) { $response->header($this->loginHeaders()); $response->statusCode(401); $response->send(); return false; } return $user; } /** * Get a user based on information in the request. Used by cookie-less auth for stateless clients. * * @param CakeRequest $request Request object. * @return mixed Either false or an array of user information */ public function getUser($request) { $digest = $this->_getDigest(); if (empty($digest)) { return false; } $user = $this->_findUser($digest['username'], null); if (empty($user)) { return false; } $password = $user[$this->settings['fields']['password']]; unset($user[$this->settings['fields']['password']]); if ($digest['response'] === $this->generateResponseHash($digest, $password)) { return $user; } return false; } /** * Find a user record using the standard options. * * @param string $username The username/identifier. * @param string $password Unused password, digest doesn't require passwords. * @return Mixed Either false on failure, or an array of user data. */ protected function _findUser($username, $password) { $userModel = $this->settings['userModel']; list($plugin, $model) = pluginSplit($userModel); $fields = $this->settings['fields']; $conditions = array( $model . '.' . $fields['username'] => $username, ); if (!empty($this->settings['scope'])) { $conditions = array_merge($conditions, $this->settings['scope']); } $result = ClassRegistry::init($userModel)->find('first', array( 'conditions' => $conditions, 'recursive' => 0 )); if (empty($result) || empty($result[$model])) { return false; } return $result[$model]; } /** * Gets the digest headers from the request/environment. * * @return array Array of digest information. */ protected function _getDigest() { $digest = env('PHP_AUTH_DIGEST'); if (empty($digest) && function_exists('apache_request_headers')) { $headers = apache_request_headers(); if (!empty($headers['Authorization']) && substr($headers['Authorization'], 0, 7) == 'Digest ') { $digest = substr($headers['Authorization'], 7); } } if (empty($digest)) { return false; } return $this->parseAuthData($digest); } /** * Parse the digest authentication headers and split them up. * * @param string $digest The raw digest authentication headers. * @return array An array of digest authentication headers */ public function parseAuthData($digest) { if (substr($digest, 0, 7) == 'Digest ') { $digest = substr($digest, 7); } $keys = $match = array(); $req = array('nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1); preg_match_all('/(\w+)=([\'"]?)([a-zA-Z0-9@=.\/_-]+)\2/', $digest, $match, PREG_SET_ORDER); foreach ($match as $i) { $keys[$i[1]] = $i[3]; unset($req[$i[1]]); } if (empty($req)) { return $keys; } return null; } /** * Generate the response hash for a given digest array. * * @param array $digest Digest information containing data from DigestAuthenticate::parseAuthData(). * @param string $password The digest hash password generated with DigestAuthenticate::password() * @return string Response hash */ public function generateResponseHash($digest, $password) { return md5( $password . ':' . $digest['nonce'] . ':' . $digest['nc'] . ':' . $digest['cnonce'] . ':' . $digest['qop'] . ':' . md5(env('REQUEST_METHOD') . ':' . $digest['uri']) ); } /** * Creates an auth digest password hash to store * * @param string $username The username to use in the digest hash. * @param string $password The unhashed password to make a digest hash for. * @param string $realm The realm the password is for. * @return string the hashed password that can later be used with Digest authentication. */ public static function password($username, $password, $realm) { return md5($username . ':' . $realm . ':' . $password); } /** * Generate the login headers * * @return string Headers for logging in. */ public function loginHeaders() { $options = array( 'realm' => $this->settings['realm'], 'qop' => $this->settings['qop'], 'nonce' => $this->settings['nonce'], 'opaque' => $this->settings['opaque'] ); $opts = array(); foreach ($options as $k => $v) { $opts[] = sprintf('%s="%s"', $k, $v); } return 'WWW-Authenticate: Digest ' . implode(',', $opts); } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/Auth/DigestAuthenticate.php
PHP
gpl3
8,814
<?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 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('BaseAuthorize', 'Controller/Component/Auth'); /** * An authorization adapter for AuthComponent. Provides the ability to authorize using a controller callback. * Your controller's isAuthorized() method should return a boolean to indicate whether or not the user is authorized. * * {{{ * public function isAuthorized($user) { * if (!empty($this->request->params['admin'])) { * return $user['role'] == 'admin'; * } * return !empty($user); * } * }}} * * the above is simple implementation that would only authorize users of the 'admin' role to access * admin routing. * * @package Cake.Controller.Component.Auth * @since 2.0 * @see AuthComponent::$authenticate */ class ControllerAuthorize extends BaseAuthorize { /** * Get/set the controller this authorize object will be working with. Also checks that isAuthorized is implemented. * * @param mixed $controller null to get, a controller to set. * @return mixed * @throws CakeException */ public function controller($controller = null) { if ($controller) { if (!method_exists($controller, 'isAuthorized')) { throw new CakeException(__d('cake_dev', '$controller does not implement an isAuthorized() method.')); } } return parent::controller($controller); } /** * Checks user authorization using a controller callback. * * @param array $user Active user data * @param CakeRequest $request * @return boolean */ public function authorize($user, CakeRequest $request) { return (bool) $this->_Controller->isAuthorized($user); } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/Auth/ControllerAuthorize.php
PHP
gpl3
2,072
<?php /** * Request object for handling alternative HTTP requests * * Alternative HTTP requests can come from wireless units like mobile phones, palmtop computers, * and the like. These units have no use for Ajax requests, and this Component can tell how Cake * should respond to the different needs of a handheld computer and a desktop machine. * * 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.Controller.Component * @since CakePHP(tm) v 0.10.4.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Xml', 'Utility'); /** * Request object for handling HTTP requests * * @package Cake.Controller.Component * @link http://book.cakephp.org/2.0/en/core-libraries/components/request-handling.html * */ class RequestHandlerComponent extends Component { /** * The layout that will be switched to for Ajax requests * * @var string * @see RequestHandler::setAjax() */ public $ajaxLayout = 'ajax'; /** * Determines whether or not callbacks will be fired on this component * * @var boolean */ public $enabled = true; /** * Holds the reference to Controller::$request * * @var CakeRequest */ public $request; /** * Holds the reference to Controller::$response * * @var CakeResponse */ public $response; /** * Contains the file extension parsed out by the Router * * @var string * @see Router::parseExtensions() */ public $ext = null; /** * The template to use when rendering the given content type. * * @var string */ protected $_renderType = null; /** * A mapping between extensions and deserializers for request bodies of that type. * By default only JSON and XML are mapped, use RequestHandlerComponent::addInputType() * * @var array */ protected $_inputTypeMap = array( 'json' => array('json_decode', true) ); /** * Constructor. Parses the accepted content types accepted by the client using HTTP_ACCEPT * * @param ComponentCollection $collection ComponentCollection object. * @param array $settings Array of settings. */ public function __construct(ComponentCollection $collection, $settings = array()) { $this->addInputType('xml', array(array($this, 'convertXml'))); parent::__construct($collection, $settings); } /** * Checks to see if a file extension has been parsed by the Router, or if the * HTTP_ACCEPT_TYPE has matches only one content type with the supported extensions. * If there is only one matching type between the supported content types & extensions, * and the requested mime-types, RequestHandler::$ext is set to that value. * * @param Controller $controller A reference to the controller * @param array $settings Array of settings to _set(). * @return void * @see Router::parseExtensions() */ public function initialize($controller, $settings = array()) { $this->request = $controller->request; $this->response = $controller->response; if (isset($this->request->params['ext'])) { $this->ext = $this->request->params['ext']; } if (empty($this->ext) || $this->ext == 'html') { $this->_setExtension(); } $this->params = $controller->params; $this->_set($settings); } /** * Set the extension based on the accept headers. * Compares the accepted types and configured extensions. * If there is one common type, that is assigned as the ext/content type * for the response. * * If html is one of the preferred types, no content type will be set, this * is to avoid issues with browsers that prefer html and several other content types. * * @return void */ protected function _setExtension() { $accept = $this->request->parseAccept(); if (empty($accept)) { return; } $extensions = Router::extensions(); $preferred = array_shift($accept); $preferredTypes = $this->mapType($preferred); $similarTypes = array_intersect($extensions, $preferredTypes); if (count($similarTypes) === 1 && !in_array('html', $preferredTypes)) { $this->ext = $similarTypes[0]; } } /** * The startup method of the RequestHandler enables several automatic behaviors * related to the detection of certain properties of the HTTP request, including: * * - Disabling layout rendering for Ajax requests (based on the HTTP_X_REQUESTED_WITH header) * - If Router::parseExtensions() is enabled, the layout and template type are * switched based on the parsed extension or Accept-Type header. For example, if `controller/action.xml` * is requested, the view path becomes `app/View/Controller/xml/action.ctp`. Also if * `controller/action` is requested with `Accept-Type: application/xml` in the headers * the view path will become `app/View/Controller/xml/action.ctp`. * - If a helper with the same name as the extension exists, it is added to the controller. * - If the extension is of a type that RequestHandler understands, it will set that * Content-type in the response header. * - If the XML data is POSTed, the data is parsed into an XML object, which is assigned * to the $data property of the controller, which can then be saved to a model object. * * @param Controller $controller A reference to the controller * @return void */ public function startup($controller) { $controller->request->params['isAjax'] = $this->request->is('ajax'); $isRecognized = ( !in_array($this->ext, array('html', 'htm')) && $this->response->getMimeType($this->ext) ); if (!empty($this->ext) && $isRecognized) { $this->renderAs($controller, $this->ext); } elseif ($this->request->is('ajax')) { $this->renderAs($controller, 'ajax'); } elseif (empty($this->ext) || in_array($this->ext, array('html', 'htm'))) { $this->respondAs('html', array('charset' => Configure::read('App.encoding'))); } foreach ($this->_inputTypeMap as $type => $handler) { if ($this->requestedWith($type)) { $input = call_user_func_array(array($controller->request, 'input'), $handler); $controller->request->data = $input; } } } /** * Helper method to parse xml input data, due to lack of anonymous functions * this lives here. * * @param string $xml * @return array Xml array data */ public function convertXml($xml) { try { $xml = Xml::build($xml); if (isset($xml->data)) { return Xml::toArray($xml->data); } return Xml::toArray($xml); } catch (XmlException $e) { return array(); } } /** * Handles (fakes) redirects for Ajax requests using requestAction() * * @param Controller $controller A reference to the controller * @param string|array $url A string or array containing the redirect location * @param mixed $status HTTP Status for redirect * @param boolean $exit * @return void */ public function beforeRedirect($controller, $url, $status = null, $exit = true) { if (!$this->request->is('ajax')) { return; } foreach ($_POST as $key => $val) { unset($_POST[$key]); } if (is_array($url)) { $url = Router::url($url + array('base' => false)); } if (!empty($status)) { $statusCode = $this->response->httpCodes($status); $code = key($statusCode); $this->response->statusCode($code); } $this->response->body($this->requestAction($url, array('return', 'bare' => false))); $this->response->send(); $this->_stop(); } /** * Returns true if the current HTTP request is Ajax, false otherwise * * @return boolean True if call is Ajax * @deprecated use `$this->request->is('ajax')` instead. */ public function isAjax() { return $this->request->is('ajax'); } /** * Returns true if the current HTTP request is coming from a Flash-based client * * @return boolean True if call is from Flash * @deprecated use `$this->request->is('flash')` instead. */ public function isFlash() { return $this->request->is('flash'); } /** * Returns true if the current request is over HTTPS, false otherwise. * * @return boolean True if call is over HTTPS * @deprecated use `$this->request->is('ssl')` instead. */ public function isSSL() { return $this->request->is('ssl'); } /** * Returns true if the current call accepts an XML response, false otherwise * * @return boolean True if client accepts an XML response */ public function isXml() { return $this->prefers('xml'); } /** * Returns true if the current call accepts an RSS response, false otherwise * * @return boolean True if client accepts an RSS response */ public function isRss() { return $this->prefers('rss'); } /** * Returns true if the current call accepts an Atom response, false otherwise * * @return boolean True if client accepts an RSS response */ public function isAtom() { return $this->prefers('atom'); } /** * Returns true if user agent string matches a mobile web browser, or if the * client accepts WAP content. * * @return boolean True if user agent is a mobile web browser */ public function isMobile() { return $this->request->is('mobile') || $this->accepts('wap'); } /** * Returns true if the client accepts WAP content * * @return boolean */ public function isWap() { return $this->prefers('wap'); } /** * Returns true if the current call a POST request * * @return boolean True if call is a POST * @deprecated Use $this->request->is('post'); from your controller. */ public function isPost() { return $this->request->is('post'); } /** * Returns true if the current call a PUT request * * @return boolean True if call is a PUT * @deprecated Use $this->request->is('put'); from your controller. */ public function isPut() { return $this->request->is('put'); } /** * Returns true if the current call a GET request * * @return boolean True if call is a GET * @deprecated Use $this->request->is('get'); from your controller. */ public function isGet() { return $this->request->is('get'); } /** * Returns true if the current call a DELETE request * * @return boolean True if call is a DELETE * @deprecated Use $this->request->is('delete'); from your controller. */ public function isDelete() { return $this->request->is('delete'); } /** * Gets Prototype version if call is Ajax, otherwise empty string. * The Prototype library sets a special "Prototype version" HTTP header. * * @return string Prototype version of component making Ajax call */ public function getAjaxVersion() { if (env('HTTP_X_PROTOTYPE_VERSION') != null) { return env('HTTP_X_PROTOTYPE_VERSION'); } return false; } /** * Adds/sets the Content-type(s) for the given name. This method allows * content-types to be mapped to friendly aliases (or extensions), which allows * RequestHandler to automatically respond to requests of that type in the * startup method. * * @param string $name The name of the Content-type, i.e. "html", "xml", "css" * @param mixed $type The Content-type or array of Content-types assigned to the name, * i.e. "text/html", or "application/xml" * @return void * @deprecated use `$this->response->type()` instead. */ public function setContent($name, $type = null) { $this->response->type(array($name => $type)); } /** * Gets the server name from which this request was referred * * @return string Server address * @deprecated use $this->request->referer() from your controller instead */ public function getReferer() { return $this->request->referer(false); } /** * Gets remote client IP * * @param boolean $safe * @return string Client IP address * @deprecated use $this->request->clientIp() from your, controller instead. */ public function getClientIP($safe = true) { return $this->request->clientIp($safe); } /** * Determines which content types the client accepts. Acceptance is based on * the file extension parsed by the Router (if present), and by the HTTP_ACCEPT * header. Unlike CakeRequest::accepts() this method deals entirely with mapped content types. * * Usage: * * `$this->RequestHandler->accepts(array('xml', 'html', 'json'));` * * Returns true if the client accepts any of the supplied types. * * `$this->RequestHandler->accepts('xml');` * * Returns true if the client accepts xml. * * @param mixed $type Can be null (or no parameter), a string type name, or an * array of types * @return mixed If null or no parameter is passed, returns an array of content * types the client accepts. If a string is passed, returns true * if the client accepts it. If an array is passed, returns true * if the client accepts one or more elements in the array. * @see RequestHandlerComponent::setContent() */ public function accepts($type = null) { $accepted = $this->request->accepts(); if ($type == null) { return $this->mapType($accepted); } elseif (is_array($type)) { foreach ($type as $t) { $t = $this->mapAlias($t); if (in_array($t, $accepted)) { return true; } } return false; } elseif (is_string($type)) { $type = $this->mapAlias($type); return in_array($type, $accepted); } return false; } /** * Determines the content type of the data the client has sent (i.e. in a POST request) * * @param mixed $type Can be null (or no parameter), a string type name, or an array of types * @return mixed If a single type is supplied a boolean will be returned. If no type is provided * The mapped value of CONTENT_TYPE will be returned. If an array is supplied the first type * in the request content type will be returned. */ public function requestedWith($type = null) { if (!$this->request->is('post') && !$this->request->is('put')) { return null; } list($contentType) = explode(';', env('CONTENT_TYPE')); if ($type == null) { return $this->mapType($contentType); } elseif (is_array($type)) { foreach ($type as $t) { if ($this->requestedWith($t)) { return $t; } } return false; } elseif (is_string($type)) { return ($type == $this->mapType($contentType)); } } /** * Determines which content-types the client prefers. If no parameters are given, * the single content-type that the client most likely prefers is returned. If $type is * an array, the first item in the array that the client accepts is returned. * Preference is determined primarily by the file extension parsed by the Router * if provided, and secondarily by the list of content-types provided in * HTTP_ACCEPT. * * @param mixed $type An optional array of 'friendly' content-type names, i.e. * 'html', 'xml', 'js', etc. * @return mixed If $type is null or not provided, the first content-type in the * list, based on preference, is returned. If a single type is provided * a boolean will be returnend if that type is preferred. * If an array of types are provided then the first preferred type is returned. * If no type is provided the first preferred type is returned. * @see RequestHandlerComponent::setContent() */ public function prefers($type = null) { $acceptRaw = $this->request->parseAccept(); if (empty($acceptRaw)) { return $this->ext; } $accepts = array_shift($acceptRaw); $accepts = $this->mapType($accepts); if ($type == null) { if (empty($this->ext) && !empty($accepts)) { return $accepts[0]; } return $this->ext; } $types = (array)$type; if (count($types) === 1) { if (!empty($this->ext)) { return in_array($this->ext, $types); } return in_array($types[0], $accepts); } $intersect = array_values(array_intersect($accepts, $types)); if (empty($intersect)) { return false; } return $intersect[0]; } /** * Sets the layout and template paths for the content type defined by $type. * * ### Usage: * * Render the response as an 'ajax' response. * * `$this->RequestHandler->renderAs($this, 'ajax');` * * Render the response as an xml file and force the result as a file download. * * `$this->RequestHandler->renderAs($this, 'xml', array('attachment' => 'myfile.xml');` * * @param Controller $controller A reference to a controller object * @param string $type Type of response to send (e.g: 'ajax') * @param array $options Array of options to use * @return void * @see RequestHandlerComponent::setContent() * @see RequestHandlerComponent::respondAs() */ public function renderAs($controller, $type, $options = array()) { $defaults = array('charset' => 'UTF-8'); if (Configure::read('App.encoding') !== null) { $defaults['charset'] = Configure::read('App.encoding'); } $options = array_merge($defaults, $options); if ($type == 'ajax') { $controller->layout = $this->ajaxLayout; return $this->respondAs('html', $options); } $controller->ext = '.ctp'; if (empty($this->_renderType)) { $controller->viewPath .= DS . $type; } else { $remove = preg_replace("/([\/\\\\]{$this->_renderType})$/", DS . $type, $controller->viewPath); $controller->viewPath = $remove; } $this->_renderType = $type; $controller->layoutPath = $type; if ($this->response->getMimeType($type)) { $this->respondAs($type, $options); } $helper = ucfirst($type); $isAdded = ( in_array($helper, $controller->helpers) || array_key_exists($helper, $controller->helpers) ); if (!$isAdded) { App::uses('AppHelper', 'View/Helper'); App::uses($helper . 'Helper', 'View/Helper'); if (class_exists($helper . 'Helper')) { $controller->helpers[] = $helper; } } } /** * Sets the response header based on type map index name. This wraps several methods * available on CakeResponse. It also allows you to use Content-Type aliases. * * @param mixed $type Friendly type name, i.e. 'html' or 'xml', or a full content-type, * like 'application/x-shockwave'. * @param array $options If $type is a friendly type name that is associated with * more than one type of content, $index is used to select which content-type to use. * @return boolean Returns false if the friendly type name given in $type does * not exist in the type map, or if the Content-type header has * already been set by this method. * @see RequestHandlerComponent::setContent() */ public function respondAs($type, $options = array()) { $defaults = array('index' => null, 'charset' => null, 'attachment' => false); $options = $options + $defaults; if (strpos($type, '/') === false) { $cType = $this->response->getMimeType($type); if ($cType === false) { return false; } if (is_array($cType) && isset($cType[$options['index']])) { $cType = $cType[$options['index']]; } if (is_array($cType)) { if ($this->prefers($cType)) { $cType = $this->prefers($cType); } else { $cType = $cType[0]; } } } else { $cType = $type; } if ($cType != null) { if (empty($this->request->params['requested'])) { $this->response->type($cType); } if (!empty($options['charset'])) { $this->response->charset($options['charset']); } if (!empty($options['attachment'])) { $this->response->download($options['attachment']); } return true; } return false; } /** * Returns the current response type (Content-type header), or null if not alias exists * * @return mixed A string content type alias, or raw content type if no alias map exists, * otherwise null */ public function responseType() { return $this->mapType($this->response->type()); } /** * Maps a content-type back to an alias * * @param mixed $cType Either a string content type to map, or an array of types. * @return mixed Aliases for the types provided. * @deprecated Use $this->response->mapType() in your controller instead. */ public function mapType($cType) { return $this->response->mapType($cType); } /** * Maps a content type alias back to its mime-type(s) * * @param mixed $alias String alias to convert back into a content type. Or an array of aliases to map. * @return mixed Null on an undefined alias. String value of the mapped alias type. If an * alias maps to more than one content type, the first one will be returned. */ public function mapAlias($alias) { if (is_array($alias)) { return array_map(array($this, 'mapAlias'), $alias); } $type = $this->response->getMimeType($alias); if ($type) { if (is_array($type)) { return $type[0]; } return $type; } return null; } /** * Add a new mapped input type. Mapped input types are automatically * converted by RequestHandlerComponent during the startup() callback. * * @param string $type The type alias being converted, ie. json * @param array $handler The handler array for the type. The first index should * be the handling callback, all other arguments should be additional parameters * for the handler. * @return void * @throws CakeException */ public function addInputType($type, $handler) { if (!is_array($handler) || !isset($handler[0]) || !is_callable($handler[0])) { throw new CakeException(__d('cake_dev', 'You must give a handler callback.')); } $this->_inputTypeMap[$type] = $handler; } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Component/RequestHandlerComponent.php
PHP
gpl3
21,268
<?php /** * Base controller 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.Controller * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Include files */ App::uses('CakeResponse', 'Network'); App::uses('ClassRegistry', 'Utility'); App::uses('ComponentCollection', 'Controller'); App::uses('View', 'View'); /** * Application controller class for organization of business logic. * Provides basic functionality, such as rendering views inside layouts, * automatic model availability, redirection, callbacks, and more. * * Controllers should provide a number of 'action' methods. These are public methods on the controller * that are not prefixed with a '_' and not part of Controller. Each action serves as an endpoint for * performing a specific action on a resource or collection of resources. For example adding or editing a new * object, or listing a set of objects. * * You can access request parameters, using `$this->request`. The request object contains all the POST, GET and FILES * that were part of the request. * * After performing the required actions, controllers are responsible for creating a response. This usually * takes the form of a generated View, or possibly a redirection to another controller action. In either case * `$this->response` allows you to manipulate all aspects of the response. * * Controllers are created by Dispatcher based on request parameters and routing. By default controllers and actions * use conventional names. For example `/posts/index` maps to `PostsController::index()`. You can re-map urls * using Router::connect(). * * @package Cake.Controller * @property AclComponent $Acl * @property AuthComponent $Auth * @property CookieComponent $Cookie * @property EmailComponent $Email * @property PaginatorComponent $Paginator * @property RequestHandlerComponent $RequestHandler * @property SecurityComponent $Security * @property SessionComponent $Session * @link http://book.cakephp.org/2.0/en/controllers.html */ class Controller extends Object { /** * The name of this controller. Controller names are plural, named after the model they manipulate. * * @var string * @link http://book.cakephp.org/2.0/en/controllers.html#controller-attributes */ public $name = null; /** * An array containing the class names of models this controller uses. * * Example: `public $uses = array('Product', 'Post', 'Comment');` * * Can be set to array() to use no models. Can be set to false to * use no models and prevent the merging of $uses with AppController * * @var mixed A single name as a string or a list of names as an array. * @link http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses */ public $uses = false; /** * An array containing the names of helpers this controller uses. The array elements should * not contain the "Helper" part of the classname. * * Example: `public $helpers = array('Html', 'Javascript', 'Time', 'Ajax');` * * @var mixed A single name as a string or a list of names as an array. * @link http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses */ public $helpers = array('Session', 'Html', 'Form'); /** * An instance of a CakeRequest object that contains information about the current request. * This object contains all the information about a request and several methods for reading * additional information about the request. * * @var CakeRequest */ public $request; /** * An instance of a CakeResponse object that contains information about the impending response * * @var CakeResponse */ public $response; /** * The classname to use for creating the response object. * * @var string */ protected $_responseClass = 'CakeResponse'; /** * The name of the views subfolder containing views for this controller. * * @var string */ public $viewPath = null; /** * The name of the layouts subfolder containing layouts for this controller. * * @var string */ public $layoutPath = null; /** * Contains variables to be handed to the view. * * @var array */ public $viewVars = array(); /** * The name of the view file to render. The name specified * is the filename in /app/View/<SubFolder> without the .ctp extension. * * @var string */ public $view = null; /** * The name of the layout file to render the view inside of. The name specified * is the filename of the layout in /app/View/Layouts without the .ctp * extension. * * @var string */ public $layout = 'default'; /** * Set to true to automatically render the view * after action logic. * * @var boolean */ public $autoRender = true; /** * Set to true to automatically render the layout around views. * * @var boolean */ public $autoLayout = true; /** * Instance of ComponentCollection used to handle callbacks. * * @var string */ public $Components = null; /** * Array containing the names of components this controller uses. Component names * should not contain the "Component" portion of the classname. * * Example: `public $components = array('Session', 'RequestHandler', 'Acl');` * * @var array * @link http://book.cakephp.org/view/961/components-helpers-and-uses */ public $components = array('Session'); /** * The name of the View class this controller sends output to. * * @var string */ public $viewClass = 'View'; /** * Instance of the View created during rendering. Won't be set until after Controller::render() is called. * * @var View */ public $View; /** * File extension for view templates. Defaults to Cake's conventional ".ctp". * * @var string */ public $ext = '.ctp'; /** * Automatically set to the name of a plugin. * * @var string */ public $plugin = null; /** * Used to define methods a controller that will be cached. To cache a * single action, the value is set to an array containing keys that match * action names and values that denote cache expiration times (in seconds). * * Example: * * {{{ * public $cacheAction = array( * 'view/23/' => 21600, * 'recalled/' => 86400 * ); * }}} * * $cacheAction can also be set to a strtotime() compatible string. This * marks all the actions in the controller for view caching. * * @var mixed * @link http://book.cakephp.org/view/1380/Caching-in-the-Controller */ public $cacheAction = false; /** * Holds all params passed and named. * * @var mixed */ public $passedArgs = array(); /** * Triggers Scaffolding * * @var mixed * @link http://book.cakephp.org/view/1103/Scaffolding */ public $scaffold = false; /** * Holds current methods of the controller. This is a list of all the methods reachable * via url. Modifying this array, will allow you to change which methods can be reached. * * @var array */ public $methods = array(); /** * This controller's primary model class name, the Inflector::classify()'ed version of * the controller's $name property. * * Example: For a controller named 'Comments', the modelClass would be 'Comment' * * @var string */ public $modelClass = null; /** * This controller's model key name, an underscored version of the controller's $modelClass property. * * Example: For a controller named 'ArticleComments', the modelKey would be 'article_comment' * * @var string */ public $modelKey = null; /** * Holds any validation errors produced by the last call of the validateErrors() method/ * * @var array Validation errors, or false if none */ public $validationErrors = null; /** * The class name of the parent class you wish to merge with. * Typically this is AppController, but you may wish to merge vars with a different * parent class. * * @var string */ protected $_mergeParent = 'AppController'; /** * Constructor. * * @param CakeRequest $request Request object for this controller. Can be null for testing, * but expect that features that use the request parameters will not work. * @param CakeResponse $response Response object for this controller. */ public function __construct($request = null, $response = null) { if ($this->name === null) { $this->name = substr(get_class($this), 0, strlen(get_class($this)) -10); } if ($this->viewPath == null) { $this->viewPath = $this->name; } $this->modelClass = Inflector::singularize($this->name); $this->modelKey = Inflector::underscore($this->modelClass); $this->Components = new ComponentCollection(); $childMethods = get_class_methods($this); $parentMethods = get_class_methods('Controller'); $this->methods = array_diff($childMethods, $parentMethods); if ($request instanceof CakeRequest) { $this->setRequest($request); } if ($response instanceof CakeResponse) { $this->response = $response; } parent::__construct(); } /** * Provides backwards compatibility to avoid problems with empty and isset to alias properties. * Lazy loads models using the loadModel() method if declared in $uses * * @param string $name * @return void */ public function __isset($name) { switch ($name) { case 'base': case 'here': case 'webroot': case 'data': case 'action': case 'params': return true; } if (is_array($this->uses)) { foreach ($this->uses as $modelClass) { list($plugin, $class) = pluginSplit($modelClass, true); if ($name === $class) { if (!$plugin) { $plugin = $this->plugin ? $this->plugin . '.' : null; } return $this->loadModel($modelClass); } } } if ($name === $this->modelClass) { list($plugin, $class) = pluginSplit($name, true); if (!$plugin) { $plugin = $this->plugin ? $this->plugin . '.' : null; } return $this->loadModel($plugin . $this->modelClass); } return false; } /** * Provides backwards compatibility access to the request object properties. * Also provides the params alias. * * @param string $name * @return void */ public function __get($name) { switch ($name) { case 'base': case 'here': case 'webroot': case 'data': return $this->request->{$name}; case 'action': return isset($this->request->params['action']) ? $this->request->params['action'] : ''; case 'params': return $this->request; case 'paginate': return $this->Components->load('Paginator')->settings; } if (isset($this->{$name})) { return $this->{$name}; } return null; } /** * Provides backwards compatibility access for setting values to the request object. * * @param string $name * @param mixed $value * @return void */ public function __set($name, $value) { switch ($name) { case 'base': case 'here': case 'webroot': case 'data': return $this->request->{$name} = $value; case 'action': return $this->request->params['action'] = $value; case 'params': return $this->request->params = $value; case 'paginate': return $this->Components->load('Paginator')->settings = $value; } return $this->{$name} = $value; } /** * Sets the request objects and configures a number of controller properties * based on the contents of the request. The properties that get set are * * - $this->request - To the $request parameter * - $this->plugin - To the $request->params['plugin'] * - $this->view - To the $request->params['action'] * - $this->autoLayout - To the false if $request->params['bare']; is set. * - $this->autoRender - To false if $request->params['return'] == 1 * - $this->passedArgs - The the combined results of params['named'] and params['pass] * * @param CakeRequest $request * @return void */ public function setRequest(CakeRequest $request) { $this->request = $request; $this->plugin = isset($request->params['plugin']) ? Inflector::camelize($request->params['plugin']) : null; $this->view = isset($request->params['action']) ? $request->params['action'] : null; if (isset($request->params['pass']) && isset($request->params['named'])) { $this->passedArgs = array_merge($request->params['pass'], $request->params['named']); } if (array_key_exists('return', $request->params) && $request->params['return'] == 1) { $this->autoRender = false; } if (!empty($request->params['bare'])) { $this->autoLayout = false; } } /** * Dispatches the controller action. Checks that the action * exists and isn't private. * * @param CakeRequest $request * @return mixed The resulting response. * @throws PrivateActionException, MissingActionException */ public function invokeAction(CakeRequest $request) { try { $method = new ReflectionMethod($this, $request->params['action']); if ($this->_isPrivateAction($method, $request)) { throw new PrivateActionException(array( 'controller' => $this->name . "Controller", 'action' => $request->params['action'] )); } return $method->invokeArgs($this, $request->params['pass']); } catch (ReflectionException $e) { if ($this->scaffold !== false) { return $this->_getScaffold($request); } throw new MissingActionException(array( 'controller' => $this->name . "Controller", 'action' => $request->params['action'] )); } } /** * Check if the request's action is marked as private, with an underscore, * or if the request is attempting to directly accessing a prefixed action. * * @param ReflectionMethod $method The method to be invoked. * @param CakeRequest $request The request to check. * @return boolean */ protected function _isPrivateAction(ReflectionMethod $method, CakeRequest $request) { $privateAction = ( $method->name[0] === '_' || !$method->isPublic() || !in_array($method->name, $this->methods) ); $prefixes = Router::prefixes(); if (!$privateAction && !empty($prefixes)) { if (empty($request->params['prefix']) && strpos($request->params['action'], '_') > 0) { list($prefix) = explode('_', $request->params['action']); $privateAction = in_array($prefix, $prefixes); } } return $privateAction; } /** * Returns a scaffold object to use for dynamically scaffolded controllers. * * @param CakeRequest $request * @return Scaffold */ protected function _getScaffold(CakeRequest $request) { return new Scaffold($this, $request); } /** * Merge components, helpers, and uses vars from Controller::$_mergeParent and PluginAppController. * * @return void */ protected function _mergeControllerVars() { $pluginController = $pluginDot = null; if (!empty($this->plugin)) { $pluginController = $this->plugin . 'AppController'; if (!is_subclass_of($this, $pluginController)) { $pluginController = null; } $pluginDot = $this->plugin . '.'; } if (is_subclass_of($this, $this->_mergeParent) || !empty($pluginController)) { $appVars = get_class_vars($this->_mergeParent); $uses = $appVars['uses']; $merge = array('components', 'helpers'); if ($uses == $this->uses && !empty($this->uses)) { if (!in_array($pluginDot . $this->modelClass, $this->uses)) { array_unshift($this->uses, $pluginDot . $this->modelClass); } elseif ($this->uses[0] !== $pluginDot . $this->modelClass) { $this->uses = array_flip($this->uses); unset($this->uses[$pluginDot . $this->modelClass]); $this->uses = array_flip($this->uses); array_unshift($this->uses, $pluginDot . $this->modelClass); } } elseif ( ($this->uses !== null || $this->uses !== false) && is_array($this->uses) && !empty($appVars['uses']) ) { $this->uses = array_merge($this->uses, array_diff($appVars['uses'], $this->uses)); } $this->_mergeVars($merge, $this->_mergeParent, true); } if ($pluginController && $this->plugin != null) { $merge = array('components', 'helpers'); $appVars = get_class_vars($pluginController); if ( ($this->uses !== null || $this->uses !== false) && is_array($this->uses) && !empty($appVars['uses']) ) { $this->uses = array_merge($this->uses, array_diff($appVars['uses'], $this->uses)); } $this->_mergeVars($merge, $pluginController); } } /** * Loads Model classes based on the uses property * see Controller::loadModel(); for more info. * Loads Components and prepares them for initialization. * * @return mixed true if models found and instance created. * @see Controller::loadModel() * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::constructClasses * @throws MissingModelException */ public function constructClasses() { $this->_mergeControllerVars(); $this->Components->init($this); if ($this->uses) { $this->uses = (array) $this->uses; list(, $this->modelClass) = pluginSplit(current($this->uses)); } return true; } /** * Perform the startup process for this controller. * Fire the Components and Controller callbacks in the correct order. * * - Initializes components, which fires their `initialize` callback * - Calls the controller `beforeFilter`. * - triggers Component `startup` methods. * * @return void */ public function startupProcess() { $this->Components->trigger('initialize', array(&$this)); $this->beforeFilter(); $this->Components->trigger('startup', array(&$this)); } /** * Perform the various shutdown processes for this controller. * Fire the Components and Controller callbacks in the correct order. * * - triggers the component `shutdown` callback. * - calls the Controller's `afterFilter` method. * * @return void */ public function shutdownProcess() { $this->Components->trigger('shutdown', array(&$this)); $this->afterFilter(); } /** * 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. * @deprecated Use CakeResponse::httpCodes(); */ public function httpCodes($code = null) { return $this->response->httpCodes($code); } /** * Loads and instantiates models required by this controller. * If the model is non existent, it will throw a missing database table error, as Cake generates * dynamic models for the time being. * * @param string $modelClass Name of model class to load * @param mixed $id Initial ID the instanced model class should have * @return mixed true when single model found and instance created, error returned if model not found. * @throws MissingModelException if the model class cannot be found. */ public function loadModel($modelClass = null, $id = null) { if ($modelClass === null) { $modelClass = $this->modelClass; } $this->uses = ($this->uses) ? $this->uses : array(); if (!in_array($modelClass, $this->uses)) { $this->uses[] = $modelClass; } list($plugin, $modelClass) = pluginSplit($modelClass, true); $this->{$modelClass} = ClassRegistry::init(array( 'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id )); if (!$this->{$modelClass}) { throw new MissingModelException($modelClass); } return true; } /** * Redirects to given $url, after turning off $this->autoRender. * Script execution is halted after the redirect. * * @param mixed $url A string or array-based URL pointing to another location within the app, * or an absolute URL * @param integer $status Optional HTTP status code (eg: 404) * @param boolean $exit If true, exit() will be called after the redirect * @return mixed void if $exit = false. Terminates script if $exit = true * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::redirect */ public function redirect($url, $status = null, $exit = true) { $this->autoRender = false; if (is_array($status)) { extract($status, EXTR_OVERWRITE); } $response = $this->Components->trigger( 'beforeRedirect', array(&$this, $url, $status, $exit), array('break' => true, 'breakOn' => false, 'collectReturn' => true) ); if ($response === false) { return; } extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE); $response = $this->beforeRedirect($url, $status, $exit); if ($response === false) { return; } extract($this->_parseBeforeRedirect($response, $url, $status, $exit), EXTR_OVERWRITE); if (function_exists('session_write_close')) { session_write_close(); } if (!empty($status) && is_string($status)) { $codes = array_flip($this->response->httpCodes()); if (isset($codes[$status])) { $status = $codes[$status]; } } if ($url !== null) { $this->response->header('Location', Router::url($url, true)); } if (!empty($status) && ($status >= 300 && $status < 400)) { $this->response->statusCode($status); } if ($exit) { $this->response->send(); $this->_stop(); } } /** * Parse beforeRedirect Response * * @param mixed $response Response from beforeRedirect callback * @param mixed $url The same value of beforeRedirect * @param integer $status The same value of beforeRedirect * @param boolean $exit The same value of beforeRedirect * @return array Array with keys url, status and exit */ protected function _parseBeforeRedirect($response, $url, $status, $exit) { if (is_array($response)) { foreach ($response as $resp) { if (is_array($resp) && isset($resp['url'])) { extract($resp, EXTR_OVERWRITE); } elseif ($resp !== null) { $url = $resp; } } } return compact('url', 'status', 'exit'); } /** * Convenience and object wrapper method for CakeResponse::header(). * * @param string $status The header message that is being set. * @return void * @deprecated Use CakeResponse::header() */ public function header($status) { $this->response->header($status); } /** * Saves a variable for use inside a view template. * * @param mixed $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 * @link http://book.cakephp.org/2.0/en/controllers.html#interacting-with-views */ 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); } $this->viewVars = $data + $this->viewVars; } /** * Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect() * * Examples: * * {{{ * setAction('another_action'); * setAction('action_with_parameters', $parameter1); * }}} * * @param string $action The new action to be 'redirected' to * @param mixed Any other parameters passed to this method will be passed as * parameters to the new action. * @return mixed Returns the return value of the called action */ public function setAction($action) { $this->request->action = $action; $args = func_get_args(); unset($args[0]); return call_user_func_array(array(&$this, $action), $args); } /** * Returns number of errors in a submitted FORM. * * @return integer Number of errors */ public function validate() { $args = func_get_args(); $errors = call_user_func_array(array(&$this, 'validateErrors'), $args); if ($errors === false) { return 0; } return count($errors); } /** * Validates models passed by parameters. Example: * * `$errors = $this->validateErrors($this->Article, $this->User);` * * @param mixed A list of models as a variable argument * @return array Validation errors, or false if none */ public function validateErrors() { $objects = func_get_args(); if (empty($objects)) { return false; } $errors = array(); foreach ($objects as $object) { if (isset($this->{$object->alias})) { $object = $this->{$object->alias}; } $object->set($object->data); $errors = array_merge($errors, $object->invalidFields()); } return $this->validationErrors = (!empty($errors) ? $errors : false); } /** * Instantiates the correct view class, hands it its data, and uses it to render the view output. * * @param string $view View to use for rendering * @param string $layout Layout to use * @return CakeResponse A response object containing the rendered view. * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::render */ public function render($view = null, $layout = null) { $this->beforeRender(); $this->Components->trigger('beforeRender', array(&$this)); $viewClass = $this->viewClass; if ($this->viewClass != 'View') { list($plugin, $viewClass) = pluginSplit($viewClass, true); $viewClass = $viewClass . 'View'; App::uses($viewClass, $plugin . 'View'); } $View = new $viewClass($this); if (!empty($this->uses)) { foreach ($this->uses as $model) { list($plugin, $className) = pluginSplit($model); $this->request->params['models'][$className] = compact('plugin', 'className'); } } if (!empty($this->modelClass) && ($this->uses === false || $this->uses === array())) { $this->request->params['models'][$this->modelClass] = array('plugin' => $this->plugin, 'className' => $this->modelClass); } $models = ClassRegistry::keys(); foreach ($models as $currentModel) { $currentObject = ClassRegistry::getObject($currentModel); if (is_a($currentObject, 'Model')) { $className = get_class($currentObject); list($plugin) = pluginSplit(App::location($className)); $this->request->params['models'][$currentObject->alias] = compact('plugin', 'className'); $View->validationErrors[$currentObject->alias] =& $currentObject->validationErrors; } } $this->autoRender = false; $this->View = $View; $this->response->body($View->render($view, $layout)); return $this->response; } /** * Returns the referring URL for this request. * * @param string $default Default URL to use if HTTP_REFERER cannot be read from headers * @param boolean $local If true, restrict referring URLs to local server * @return string Referring URL * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::referer */ public function referer($default = null, $local = false) { if ($this->request) { $referer = $this->request->referer($local); if ($referer == '/' && $default != null) { return Router::url($default, true); } return $referer; } return '/'; } /** * Forces the user's browser not to cache the results of the current request. * * @return void * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::disableCache * @deprecated Use CakeResponse::disableCache() */ public function disableCache() { $this->response->disableCache(); } /** * Shows a message to the user for $pause seconds, then redirects to $url. * Uses flash.ctp as the default layout for the message. * Does not work if the current debug level is higher than 0. * * @param string $message Message to display to the user * @param mixed $url Relative string or array-based URL to redirect to after the time expires * @param integer $pause Time to show the message * @param string $layout Layout you want to use, defaults to 'flash' * @return void Renders flash layout * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::flash */ public function flash($message, $url, $pause = 1, $layout = 'flash') { $this->autoRender = false; $this->set('url', Router::url($url)); $this->set('message', $message); $this->set('pause', $pause); $this->set('page_title', $message); $this->render(false, $layout); } /** * Converts POST'ed form data to a model conditions array, suitable for use in a Model::find() call. * * @param array $data POST'ed data organized by model and field * @param mixed $op A string containing an SQL comparison operator, or an array matching operators * to fields * @param string $bool SQL boolean operator: AND, OR, XOR, etc. * @param boolean $exclusive If true, and $op is an array, fields not included in $op will not be * included in the returned conditions * @return array An array of model conditions * @deprecated */ public function postConditions($data = array(), $op = null, $bool = 'AND', $exclusive = false) { if (!is_array($data) || empty($data)) { if (!empty($this->request->data)) { $data = $this->request->data; } else { return null; } } $cond = array(); if ($op === null) { $op = ''; } $arrayOp = is_array($op); foreach ($data as $model => $fields) { foreach ($fields as $field => $value) { $key = $model.'.'.$field; $fieldOp = $op; if ($arrayOp) { if (array_key_exists($key, $op)) { $fieldOp = $op[$key]; } elseif (array_key_exists($field, $op)) { $fieldOp = $op[$field]; } else { $fieldOp = false; } } if ($exclusive && $fieldOp === false) { continue; } $fieldOp = strtoupper(trim($fieldOp)); if ($fieldOp === 'LIKE') { $key = $key.' LIKE'; $value = '%'.$value.'%'; } elseif ($fieldOp && $fieldOp != '=') { $key = $key.' '.$fieldOp; } $cond[$key] = $value; } } if ($bool != null && strtoupper($bool) != 'AND') { $cond = array($bool => $cond); } return $cond; } /** * Handles automatic pagination of model records. * * @param mixed $object Model to paginate (e.g: model instance, or 'Model', or 'Model.InnerModel') * @param mixed $scope Conditions to use while paginating * @param array $whitelist List of allowed options for paging * @return array Model query results * @link http://book.cakephp.org/2.0/en/controllers.html#Controller::paginate * @deprecated Use PaginatorComponent instead */ public function paginate($object = null, $scope = array(), $whitelist = array()) { return $this->Components->load('Paginator', $this->paginate)->paginate($object, $scope, $whitelist); } /** * Called before the controller action. You can use this method to configure and customize components * or perform logic that needs to happen before each controller action. * * @return void * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks */ public function beforeFilter() { } /** * Called after the controller action is run, but before the view is rendered. You can use this method * to perform logic or set view variables that are required on every request. * * @return void * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks */ public function beforeRender() { } /** * The beforeRedirect method is invoked when the controller's redirect method is called but before any * further action. If this method returns false the controller will not continue on to redirect the request. * The $url, $status and $exit variables have same meaning as for the controller's method. You can also * return a string which will be interpreted as the url to redirect to or return associative array with * key 'url' and optionally 'status' and 'exit'. * * @param mixed $url A string or array-based URL pointing to another location within the app, * or an absolute URL * @param integer $status Optional HTTP status code (eg: 404) * @param boolean $exit If true, exit() will be called after the redirect * @return boolean * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks */ public function beforeRedirect($url, $status = null, $exit = true) { return true; } /** * Called after the controller action is run and rendered. * * @return void * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks */ public function afterFilter() { } /** * This method should be overridden in child classes. * * @param string $method name of method called example index, edit, etc. * @return boolean Success * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks */ public function beforeScaffold($method) { return true; } /** * Alias to beforeScaffold() * * @param string $method * @return boolean * @see Controller::beforeScaffold() * @deprecated */ protected function _beforeScaffold($method) { return $this->beforeScaffold($method); } /** * This method should be overridden in child classes. * * @param string $method name of method called either edit or update. * @return boolean Success * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks */ public function afterScaffoldSave($method) { return true; } /** * Alias to afterScaffoldSave() * * @param string $method * @return boolean * @see Controller::afterScaffoldSave() * @deprecated */ protected function _afterScaffoldSave($method) { return $this->afterScaffoldSave($method); } /** * This method should be overridden in child classes. * * @param string $method name of method called either edit or update. * @return boolean Success * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks */ public function afterScaffoldSaveError($method) { return true; } /** * Alias to afterScaffoldSaveError() * * @param string $method * @return boolean * @see Controller::afterScaffoldSaveError() * @deprecated */ protected function _afterScaffoldSaveError($method) { return $this->afterScaffoldSaveError($method); } /** * This method should be overridden in child classes. * If not it will render a scaffold error. * Method MUST return true in child classes * * @param string $method name of method called example index, edit, etc. * @return boolean Success * @link http://book.cakephp.org/2.0/en/controllers.html#callbacks */ public function scaffoldError($method) { return false; } /** * Alias to scaffoldError() * * @param string $method * @return boolean * @see Controller::scaffoldError() * @deprecated */ protected function _scaffoldError($method) { return $this->scaffoldError($method); } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/Controller.php
PHP
gpl3
34,789
<?php /** * Components collection is used as a registry for loaded components and handles loading * and constructing component 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 * @package Cake.Controller * @since CakePHP(tm) v 2.0 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('ObjectCollection', 'Utility'); App::uses('Component', 'Controller'); class ComponentCollection extends ObjectCollection { /** * The controller that this collection was initialized with. * * @var Controller */ protected $_Controller = null; /** * Initializes all the Components for a controller. * Attaches a reference of each component to the Controller. * * @param Controller $Controller Controller to initialize components for. * @return void */ public function init(Controller $Controller) { if (empty($Controller->components)) { return; } $this->_Controller = $Controller; $components = ComponentCollection::normalizeObjectArray($Controller->components); foreach ($components as $name => $properties) { $Controller->{$name} = $this->load($properties['class'], $properties['settings']); } } /** * Get the controller associated with the collection. * * @return Controller. */ public function getController() { return $this->_Controller; } /** * Loads/constructs a component. Will return the instance in the registry if it already exists. * You can use `$settings['enabled'] = false` to disable callbacks on a component when loading it. * Callbacks default to on. Disabled component methods work as normal, only callbacks are disabled. * * You can alias your component as an existing component by setting the 'className' key, i.e., * {{{ * public $components = array( * 'Email' => array( * 'className' => 'AliasedEmail' * ); * ); * }}} * All calls to the `Email` component would use `AliasedEmail` instead. * * @param string $component Component name to load * @param array $settings Settings for the component. * @return Component A component object, Either the existing loaded component or a new one. * @throws MissingComponentException when the component could not be found */ public function load($component, $settings = array()) { if (is_array($settings) && isset($settings['className'])) { $alias = $component; $component = $settings['className']; } list($plugin, $name) = pluginSplit($component, true); if (!isset($alias)) { $alias = $name; } if (isset($this->_loaded[$alias])) { return $this->_loaded[$alias]; } $componentClass = $name . 'Component'; App::uses($componentClass, $plugin . 'Controller/Component'); if (!class_exists($componentClass)) { throw new MissingComponentException(array( 'class' => $componentClass )); } $this->_loaded[$alias] = new $componentClass($this, $settings); $enable = isset($settings['enabled']) ? $settings['enabled'] : true; if ($enable === true) { $this->_enabled[] = $alias; } return $this->_loaded[$alias]; } }
0001-bee
trunk/cakephp2/lib/Cake/Controller/ComponentCollection.php
PHP
gpl3
3,418
test_plugin test_plugin_theme default layout
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Themed/TestTheme/Plugin/TestPlugin/Layouts/plugin_default.ctp
PHP
gpl3
44
test plugin index theme view
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Themed/TestTheme/Plugin/TestPlugin/Tests/index.ctp
PHP
gpl3
28
root theme js file
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Themed/TestTheme/webroot/js/theme.js
JavaScript
gpl3
18
nested theme js file
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Themed/TestTheme/webroot/js/one/theme_one.js
JavaScript
gpl3
20
theme webroot css file
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Themed/TestTheme/webroot/css/theme_webroot.css
CSS
gpl3
22
this is the test asset css file
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Themed/TestTheme/webroot/css/test_asset.css
CSS
gpl3
31
posts index themed view
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Themed/TestTheme/Posts/index.ctp
PHP
gpl3
23
I'm a themed scaffold file.
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Themed/TestTheme/Posts/scaffold.index.ctp
PHP
gpl3
27
posts themed themed file. <!--nocache--> <?php echo $this->element('test_element'); ?> <!--/nocache-->
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Themed/TestTheme/Posts/themed.ctp
PHP
gpl3
103
default test_theme layout <?php echo $content_for_layout ?>
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Themed/TestTheme/Layouts/default.ctp
PHP
gpl3
60
Hi, I'm the test element.
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Themed/TestTheme/Elements/test_element.ctp
PHP
gpl3
25
<?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.libs.view.templates.pages * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <h1>Content</h1> <!--nocache--> <p>D. In View File</p> <?php $this->log('4. in view file') ?> <!--/nocache-->
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Posts/sequencial_nocache.ctp
PHP
gpl3
732
--view start-- <!--nocache--> <?php echo $batman ?> <!--/nocache--> this view has 3 nocache blocks <!--nocache--> <?php echo $spiderman; ?> <!--/nocache--> <!--nocache--> <?php echo 'some string'; ?> <!--/nocache--> --view end--
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Posts/multiple_nocache.ctp
PHP
gpl3
234
posts index
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Posts/index.ctp
PHP
gpl3
11
<?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.libs.view.templates.pages * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ ?> <p> <!--nocache--> <span class="notice"> <?php echo __d('cake', 'Your tmp directory is '); if (is_writable(TMP)): echo __d('cake', 'writable.'); else: echo __d('cake', 'NOT writable.'); endif; ?> </span> <!--/nocache--> </p> <p> <span class="notice"> <?php echo __d('cake', 'Your cache is '); if (Cache::isInitialized('default')): echo __d('cake', 'set up and initialized properly.'); $settings = Cache::settings(); echo '<p>' . $settings['engine']; echo __d('cake', ' is being used to cache, to change this edit config/core.php '); echo '</p>'; echo 'Settings: <ul>'; foreach ($settings as $name => $value): echo '<li>' . $name . ': ' . $value . '</li>'; endforeach; echo '</ul>'; else: echo __d('cake', 'NOT working.'); echo '<br />'; if (is_writable(TMP)): echo __d('cake', 'Edit: config/core.php to insure you have the newset version of this file and the variable $cakeCache set properly'); endif; endif; ?> </span> </p> <p> <span class="notice"> <?php echo __d('cake', 'Your database configuration file is '); $filePresent = null; if (file_exists(APP . 'Config'.'database.php')): echo __d('cake', 'present.'); $filePresent = true; else: echo __d('cake', 'NOT present.'); echo '<br/>'; echo __d('cake', 'Rename config/database.php.default to config/database.php'); endif; ?> </span> </p> <?php if (!empty($filePresent)): if (!class_exists('ConnectionManager')) { require CAKE . 'model' . DS . 'connection_manager.php'; } $connected = ConnectionManager::getDataSource('default'); ?> <p> <span class="notice"> <?php echo __d('cake', 'Cake'); if ($connected->isConnected()): __d('cake', ' is able to '); else: __d('cake', ' is NOT able to '); endif; __d('cake', 'connect to the database.'); ?> </span> </p> <?php endif; ?> <h2><?php echo __d('cake', 'Release Notes for CakePHP %s.', Configure::version()); ?></h2> <a href="https://trac.cakephp.org/wiki/notes/1.2.x.x"><?php echo __d('cake', 'Read the release notes and get the latest version'); ?> </a> <h2><?php echo __d('cake', 'Editing this Page'); ?></h2> <p> <?php echo __d('cake', 'To change the content of this page, create: /app/View/Pages/home.ctp.'); ?><br /> <?php echo __d('cake', 'To change its layout, create: /app/View/Layouts/default.ctp.'); ?><br /> <a href="http://manual.cakephp.org/"><?php echo __d('cake', 'See the views section of the manual for more info.'); ?> </a><br /> <?php echo __d('cake', 'You can also add some CSS styles for your pages at: app/webroot/css/.'); ?> </p> <h2><?php echo __d('cake', 'Getting Started'); ?></h2> <p> <a href="http://manual.cakephp.org/appendix/blog_tutorial"><?php echo __d('cake', 'The 15 min Blog Tutorial'); ?></a><br /> <a href="http://www-128.ibm.com/developerworks/edu/os-dw-os-php-cake1.html"><?php echo __d('cake', 'Cook up Web sites fast with CakePHP'); ?></a><br /> <a href="http://www-128.ibm.com/developerworks/edu/os-dw-os-php-wiki1.html"><?php echo __d('cake', 'Create an interactive production wiki using PHP'); ?></a> </p> <h2><?php echo __d('cake', 'More about Cake'); ?></h2> <p> <?php echo __d('cake', 'CakePHP is a rapid development framework for PHP which uses commonly known design patterns like Active Record, Association Data Mapping, Front Controller and MVC.'); ?> </p> <p> <?php echo __d('cake', 'Our primary goal is to provide a structured framework that enables PHP users at all levels to rapidly develop robust web applications, without any loss to flexibility.'); ?> </p> <ul> <li><a href="http://cakefoundation.org/"><?php echo __d('cake', 'Cake Software Foundation'); ?> </a> <ul><li><?php echo __d('cake', 'Promoting development related to CakePHP'); ?></li></ul></li> <li><a href="http://bakery.cakephp.org"><?php echo __d('cake', 'The Bakery'); ?> </a> <ul><li><?php echo __d('cake', 'Everything CakePHP'); ?></li></ul></li> <li><a href="http://astore.amazon.com/cakesoftwaref-20/"><?php echo __d('cake', 'Book Store'); ?> </a> <ul><li><?php echo __d('cake', 'Recommended Software Books'); ?></li></ul></li> <li><a href="http://www.cafepress.com/cakefoundation"><?php echo __d('cake', 'CakeSchwag'); ?> </a> <ul><li><?php echo __d('cake', 'Get your own CakePHP gear - Doughnate to Cake'); ?></li></ul></li> <li><a href="http://www.cakephp.org"><?php echo __d('cake', 'CakePHP'); ?> </a> <ul><li><?php echo __d('cake', 'The Rapid Development Framework'); ?></li></ul></li> <li><a href="http://manual.cakephp.org"><?php echo __d('cake', 'CakePHP Manual'); ?> </a> <ul><li><?php echo __d('cake', 'Your Rapid Development Cookbook'); ?></li></ul></li> <li><a href="http://api.cakephp.org"><?php echo __d('cake', 'CakePHP API'); ?> </a> <ul><li><?php echo __d('cake', 'Docblock Your Best Friend'); ?></li></ul></li> <li><a href="http://www.cakeforge.org"><?php echo __d('cake', 'CakeForge'); ?> </a> <ul><li><?php echo __d('cake', 'Open Development for CakePHP'); ?></li></ul></li> <li><a href="https://trac.cakephp.org/"><?php echo __d('cake', 'CakePHP Trac'); ?> </a> <ul><li><?php echo __d('cake', 'For the Development of CakePHP (Tickets, SVN browser, Roadmap, Changelogs)'); ?></li></ul></li> <li><a href="http://groups-beta.google.com/group/cake-php"><?php echo __d('cake', 'CakePHP Google Group'); ?> </a> <ul><li><?php echo __d('cake', 'Community mailing list'); ?></li></ul></li> <li><a href="irc://irc.freenode.net/cakephp">irc.freenode.net #cakephp</a> <ul><li><?php echo __d('cake', 'Live chat about CakePHP'); ?></li></ul></li> </ul>
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Posts/test_nocache_tags.ctp
PHP
gpl3
6,214
View Content <!--nocache--><?php $y = 1; ?><!--/nocache-->
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Posts/cache_empty_sections.ctp
PHP
gpl3
60
<!--nocache--> <?php echo $foo; ?> <!--/nocache--> <!--nocache--> <?php echo $bar; ?> <!--/nocache--> <?php echo $this->element('nocache/sub1'); ?>
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Posts/nocache_multiple_element.ctp
PHP
gpl3
151
<div class="users form"> <!--nocache--> <?php echo $this->Form->create('User');?> <fieldset> <legend><?php echo __('Add User');?></legend> <?php echo $this->Form->input('username'); echo $this->Form->input('email'); echo $this->Form->input('password'); ?> </fieldset> <?php echo $this->Form->end('Submit');?> <!--/nocache--> </div>
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Posts/cache_form.ctp
PHP
gpl3
354
test_app posts add/edit scaffold view
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Posts/scaffold.form.ctp
PHP
gpl3
37
<?php echo $html; echo $this->Html->link('Test link', '#'); ?>
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Posts/helper_overwrite.ctp
PHP
gpl3
63
<?php $count = 10; $messages = array('count' => 10); // Plural echo __n('You have %d new message.', 'You have %d new messages.', $count); echo __n('You deleted %d message.', 'You deleted %d messages.', $messages['count']); // Domain Plural echo __dn('domain', 'You have %d new message (domain).', 'You have %d new messages (domain).', '10'); echo __dn('domain', 'You deleted %d message (domain).', 'You deleted %d messages (domain).', $messages['count']); // Duplicated Message echo __('Editing this Page'); // Multiline __('Hot features!' . "\n - No Configuration:" . ' Set-up the database and let the magic begin' . "\n - Extremely Simple:" . ' Just look at the name...It\'s Cake' . "\n - Active, Friendly Community:" . ' Join us #cakephp on IRC. We\'d love to help you get started');
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Pages/extract.ctp
PHP
gpl3
800
<?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.libs.view.templates.pages * @since CakePHP(tm) v 0.10.0.1076 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ App::uses('Debugger', 'Utility'); ?> <h2><?php echo __d('cake_dev', 'Release Notes for CakePHP %s.', Configure::version()); ?></h2> <a href="http://cakephp.org/changelogs/1.3.6"><?php echo __d('cake_dev', 'Read the changelog'); ?> </a> <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 config/database.php.default to 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">'; __('PCRE has not been compiled with Unicode support.'); echo '<br/>'; __('Recompile PCRE with Unicode support by adding <code>--enable-unicode-properties</code> when configuring'); echo '</span></p>'; } ?> <h3><?php echo __d('cake_dev', 'Editing this Page'); ?></h3> <p> <?php echo __d('cake_dev', 'To change the content of this page, create: APP/views/pages/home.ctp.<br /> To change its layout, create: APP/views/layouts/default.ctp.<br /> You can also add some CSS styles for your pages at: APP/webroot/css.'); ?> </p> <h3><?php echo __d('cake_dev', 'Getting Started'); ?></h3> <p> <?php echo $this->Html->link( sprintf('<strong>%s</strong> %s', __d('cake_dev', 'New'), __d('cake_dev', 'CakePHP 1.3 Docs')), 'http://book.cakephp.org/view/875/x1-3-Collection', array('target' => '_blank', 'escape' => false) ); ?> </p> <p> <?php echo $this->Html->link( __d('cake_dev', 'The 15 min Blog Tutorial'), 'http://book.cakephp.org/view/1528/Blog', array('target' => '_blank', 'escape' => false) ); ?> </p> <h3><?php echo __d('cake_dev', 'More about Cake'); ?></h3> <p> <?php echo __d('cake_dev', 'CakePHP is a rapid development framework for PHP which uses commonly known design patterns like Active Record, Association Data Mapping, Front Controller and MVC.'); ?> </p> <p> <?php echo __d('cake_dev', 'Our primary goal is to provide a structured framework that enables PHP users at all levels to rapidly develop robust web applications, without any loss to flexibility.'); ?> </p> <ul> <li><a href="http://cakefoundation.org/"><?php echo __d('cake_dev', 'Cake Software Foundation'); ?> </a> <ul><li><?php echo __d('cake_dev', 'Promoting development related to CakePHP'); ?></li></ul></li> <li><a href="http://www.cakephp.org"><?php echo __d('cake_dev', 'CakePHP'); ?> </a> <ul><li><?php echo __d('cake_dev', 'The Rapid Development Framework'); ?></li></ul></li> <li><a href="http://book.cakephp.org"><?php echo __d('cake_dev', 'CakePHP Documentation'); ?> </a> <ul><li><?php echo __d('cake_dev', 'Your Rapid Development Cookbook'); ?></li></ul></li> <li><a href="http://api.cakephp.org"><?php echo __d('cake_dev', 'CakePHP API'); ?> </a> <ul><li><?php echo __d('cake_dev', 'Quick Reference'); ?></li></ul></li> <li><a href="http://bakery.cakephp.org"><?php echo __d('cake_dev', 'The Bakery'); ?> </a> <ul><li><?php echo __d('cake_dev', 'Everything CakePHP'); ?></li></ul></li> <li><a href="http://live.cakephp.org"><?php echo __d('cake_dev', 'The Show'); ?> </a> <ul><li><?php echo __d('cake_dev', 'The Show is a live and archived internet radio broadcast CakePHP-related topics and answer questions live via IRC, Skype, and telephone.'); ?></li></ul></li> <li><a href="http://groups.google.com/group/cake-php"><?php echo __d('cake_dev', 'CakePHP Google Group'); ?> </a> <ul><li><?php echo __d('cake_dev', 'Community mailing list'); ?></li></ul></li> <li><a href="irc://irc.freenode.net/cakephp">irc.freenode.net #cakephp</a> <ul><li><?php echo __d('cake_dev', 'Live chat about CakePHP'); ?></li></ul></li> <li><a href="http://github.com/cakephp/"><?php echo __d('cake_dev', 'CakePHP Code'); ?> </a> <ul><li><?php echo __d('cake_dev', 'For the Development of CakePHP Git repository, Downloads'); ?></li></ul></li> <li><a href="http://cakephp.lighthouseapp.com/"><?php echo __d('cake_dev', 'CakePHP Lighthouse'); ?> </a> <ul><li><?php echo __d('cake_dev', 'CakePHP Tickets, Wiki pages, Roadmap'); ?></li></ul></li> <li><a href="http://www.cakeforge.org"><?php echo __d('cake_dev', 'CakeForge'); ?> </a> <ul><li><?php echo __d('cake_dev', 'Open Development for CakePHP'); ?></li></ul></li> <li><a href="http://astore.amazon.com/cakesoftwaref-20/"><?php echo __d('cake_dev', 'Book Store'); ?> </a> <ul><li><?php echo __d('cake_dev', 'Recommended Software Books'); ?></li></ul></li> <li><a href="http://www.cafepress.com/cakefoundation"><?php echo __d('cake_dev', 'CakePHP gear'); ?> </a> <ul><li><?php echo __d('cake_dev', 'Get your own CakePHP gear - Doughnate to Cake'); ?></li></ul></li> </ul>
0001-bee
trunk/cakephp2/lib/Cake/Test/test_app/View/Pages/home.ctp
PHP
gpl3
6,863