code
stringlengths 31
1.39M
| docstring
stringlengths 23
16.8k
| func_name
stringlengths 1
126
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
166
| url
stringlengths 50
220
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function truncate($table) {
return $this->execute('DELETE From ' . $this->fullTableName($table));
} | Deletes all the records in a table and resets the count of the auto-incrementing
primary key, where applicable.
@param mixed $table A string or model class representing the table to be truncated
@return boolean SQL TRUNCATE TABLE statement, false if not applicable.
@access public | truncate | php | Datawalke/Coordino | cake/libs/model/datasources/dbo/dbo_sqlite.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/datasources/dbo/dbo_sqlite.php | MIT |
function lastError() {
$error = sqlite_last_error($this->connection);
if ($error) {
return $error.': '.sqlite_error_string($error);
}
return null;
} | Returns a formatted error message from previous database operation.
@return string Error message | lastError | php | Datawalke/Coordino | cake/libs/model/datasources/dbo/dbo_sqlite.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/datasources/dbo/dbo_sqlite.php | MIT |
function lastAffected() {
if (!empty($this->_queryStats)) {
foreach (array('rows inserted', 'rows updated', 'rows deleted') as $key) {
if (array_key_exists($key, $this->_queryStats)) {
return $this->_queryStats[$key];
}
}
}
return false;
} | Returns number of affected rows in previous database operation. If no previous operation exists, this returns false.
@return integer Number of affected rows | lastAffected | php | Datawalke/Coordino | cake/libs/model/datasources/dbo/dbo_sqlite.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/datasources/dbo/dbo_sqlite.php | MIT |
function lastNumRows() {
if ($this->hasResult()) {
sqlite_num_rows($this->_result);
}
return false;
} | Returns number of rows in previous resultset. If no previous resultset exists,
this returns false.
@return integer Number of rows in resultset | lastNumRows | php | Datawalke/Coordino | cake/libs/model/datasources/dbo/dbo_sqlite.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/datasources/dbo/dbo_sqlite.php | MIT |
function lastInsertId() {
return sqlite_last_insert_rowid($this->connection);
} | Returns the ID generated from the previous INSERT operation.
@return int | lastInsertId | php | Datawalke/Coordino | cake/libs/model/datasources/dbo/dbo_sqlite.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/datasources/dbo/dbo_sqlite.php | MIT |
function column($real) {
if (is_array($real)) {
$col = $real['name'];
if (isset($real['limit'])) {
$col .= '('.$real['limit'].')';
}
return $col;
}
$col = strtolower(str_replace(')', '', $real));
$limit = null;
if (strpos($col, '(') !== false) {
list($col, $limit) = explode('(', $col);
}
if (in_array($col, array('text', 'integer', 'float', 'boolean', 'timestamp', 'date', 'datetime', 'time'))) {
return $col;
}
if (strpos($col, 'varchar') !== false) {
return 'string';
}
if (in_array($col, array('blob', 'clob'))) {
return 'binary';
}
if (strpos($col, 'numeric') !== false) {
return 'float';
}
return 'text';
} | Converts database-layer column types to basic types
@param string $real Real database-layer column type (i.e. "varchar(255)")
@return string Abstract column type (i.e. "string") | column | php | Datawalke/Coordino | cake/libs/model/datasources/dbo/dbo_sqlite.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/datasources/dbo/dbo_sqlite.php | MIT |
function fetchResult() {
if ($row = sqlite_fetch_array($this->results, SQLITE_ASSOC)) {
$resultRow = array();
$i = 0;
foreach ($row as $index => $field) {
if (strpos($index, '.')) {
list($table, $column) = explode('.', str_replace('"', '', $index));
$resultRow[$table][$column] = $row[$index];
} else {
$resultRow[0][str_replace('"', '', $index)] = $row[$index];
}
$i++;
}
return $resultRow;
} else {
return false;
}
} | Fetches the next row from the current result set
@return unknown | fetchResult | php | Datawalke/Coordino | cake/libs/model/datasources/dbo/dbo_sqlite.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/datasources/dbo/dbo_sqlite.php | MIT |
function buildColumn($column) {
$name = $type = null;
$column = array_merge(array('null' => true), $column);
extract($column);
if (empty($name) || empty($type)) {
trigger_error(__('Column name or type not defined in schema', true), E_USER_WARNING);
return null;
}
if (!isset($this->columns[$type])) {
trigger_error(sprintf(__('Column type %s does not exist', true), $type), E_USER_WARNING);
return null;
}
$real = $this->columns[$type];
$out = $this->name($name) . ' ' . $real['name'];
if (isset($column['key']) && $column['key'] == 'primary' && $type == 'integer') {
return $this->name($name) . ' ' . $this->columns['primary_key']['name'];
}
return parent::buildColumn($column);
} | Generate a database-native column schema string
@param array $column An array structured like the following: array('name'=>'value', 'type'=>'value'[, options]),
where options can be 'default', 'length', or 'key'.
@return string | buildColumn | php | Datawalke/Coordino | cake/libs/model/datasources/dbo/dbo_sqlite.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/datasources/dbo/dbo_sqlite.php | MIT |
function setEncoding($enc) {
if (!in_array($enc, array("UTF-8", "UTF-16", "UTF-16le", "UTF-16be"))) {
return false;
}
return $this->_execute("PRAGMA encoding = \"{$enc}\"") !== false;
} | Sets the database encoding
@param string $enc Database encoding | setEncoding | php | Datawalke/Coordino | cake/libs/model/datasources/dbo/dbo_sqlite.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/datasources/dbo/dbo_sqlite.php | MIT |
function getEncoding() {
return $this->fetchRow('PRAGMA encoding');
} | Gets the database encoding
@return string The database encoding | getEncoding | php | Datawalke/Coordino | cake/libs/model/datasources/dbo/dbo_sqlite.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/datasources/dbo/dbo_sqlite.php | MIT |
function buildIndex($indexes, $table = null) {
$join = array();
foreach ($indexes as $name => $value) {
if ($name == 'PRIMARY') {
continue;
}
$out = 'CREATE ';
if (!empty($value['unique'])) {
$out .= 'UNIQUE ';
}
if (is_array($value['column'])) {
$value['column'] = implode(', ', array_map(array(&$this, 'name'), $value['column']));
} else {
$value['column'] = $this->name($value['column']);
}
$out .= "INDEX {$name} ON {$table}({$value['column']});";
$join[] = $out;
}
return $join;
} | Removes redundant primary key indexes, as they are handled in the column def of the key.
@param array $indexes
@param string $table
@return string | buildIndex | php | Datawalke/Coordino | cake/libs/model/datasources/dbo/dbo_sqlite.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/datasources/dbo/dbo_sqlite.php | MIT |
function index(&$model) {
$index = array();
$table = $this->fullTableName($model);
if ($table) {
$indexes = $this->query('PRAGMA index_list(' . $table . ')');
$tableInfo = $this->query('PRAGMA table_info(' . $table . ')');
foreach ($indexes as $i => $info) {
$key = array_pop($info);
$keyInfo = $this->query('PRAGMA index_info("' . $key['name'] . '")');
foreach ($keyInfo as $keyCol) {
if (!isset($index[$key['name']])) {
$col = array();
if (preg_match('/autoindex/', $key['name'])) {
$key['name'] = 'PRIMARY';
}
$index[$key['name']]['column'] = $keyCol[0]['name'];
$index[$key['name']]['unique'] = intval($key['unique'] == 1);
} else {
if (!is_array($index[$key['name']]['column'])) {
$col[] = $index[$key['name']]['column'];
}
$col[] = $keyCol[0]['name'];
$index[$key['name']]['column'] = $col;
}
}
}
}
return $index;
} | Overrides DboSource::index to handle SQLite indexe introspection
Returns an array of the indexes in given table name.
@param string $model Name of model to inspect
@return array Fields in table. Keys are column and unique | index | php | Datawalke/Coordino | cake/libs/model/datasources/dbo/dbo_sqlite.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/datasources/dbo/dbo_sqlite.php | MIT |
function renderStatement($type, $data) {
switch (strtolower($type)) {
case 'schema':
extract($data);
foreach (array('columns', 'indexes') as $var) {
if (is_array(${$var})) {
${$var} = "\t" . implode(",\n\t", array_filter(${$var}));
}
}
return "CREATE TABLE {$table} (\n{$columns});\n{$indexes}";
break;
default:
return parent::renderStatement($type, $data);
break;
}
} | Overrides DboSource::renderStatement to handle schema generation with SQLite-style indexes
@param string $type
@param array $data
@return string | renderStatement | php | Datawalke/Coordino | cake/libs/model/datasources/dbo/dbo_sqlite.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/model/datasources/dbo/dbo_sqlite.php | MIT |
function loadConfig($name = 'tags') {
if (file_exists(CONFIGS . $name .'.php')) {
require(CONFIGS . $name .'.php');
if (isset($tags)) {
$this->tags = array_merge($this->tags, $tags);
}
}
return $this->tags;
} | Parses tag templates into $this->tags.
@param $name file name inside app/config to load.
@return array merged tags from config/$name.php
@access public | loadConfig | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function url($url = null, $full = false) {
return h(Router::url($url, $full));
} | Finds URL for specified action.
Returns a URL pointing at the provided parameters.
@param mixed $url Either a relative string url like `/products/view/23` or
an array of url parameters. Using an array for urls will allow you to leverage
the reverse routing features of CakePHP.
@param boolean $full If true, the full base URL will be prepended to the result
@return string Full translated URL with base path.
@access public
@link http://book.cakephp.org/view/1448/url | url | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function webroot($file) {
$asset = explode('?', $file);
$asset[1] = isset($asset[1]) ? '?' . $asset[1] : null;
$webPath = "{$this->webroot}" . $asset[0];
$file = $asset[0];
if (!empty($this->theme)) {
$file = trim($file, '/');
$theme = $this->theme . '/';
if (DS === '\\') {
$file = str_replace('/', '\\', $file);
}
if (file_exists(Configure::read('App.www_root') . 'theme' . DS . $this->theme . DS . $file)) {
$webPath = "{$this->webroot}theme/" . $theme . $asset[0];
} else {
$viewPaths = App::path('views');
foreach ($viewPaths as $viewPath) {
$path = $viewPath . 'themed'. DS . $this->theme . DS . 'webroot' . DS . $file;
if (file_exists($path)) {
$webPath = "{$this->webroot}theme/" . $theme . $asset[0];
break;
}
}
}
}
if (strpos($webPath, '//') !== false) {
return str_replace('//', '/', $webPath . $asset[1]);
}
return $webPath . $asset[1];
} | Checks if a file exists when theme is used, if no file is found default location is returned
@param string $file The file to create a webroot path to.
@return string Web accessible path to file.
@access public | webroot | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function assetTimestamp($path) {
$timestampEnabled = (
(Configure::read('Asset.timestamp') === true && Configure::read() > 0) ||
Configure::read('Asset.timestamp') === 'force'
);
if (strpos($path, '?') === false && $timestampEnabled) {
$filepath = preg_replace('/^' . preg_quote($this->webroot, '/') . '/', '', $path);
$webrootPath = WWW_ROOT . str_replace('/', DS, $filepath);
if (file_exists($webrootPath)) {
return $path . '?' . @filemtime($webrootPath);
}
$segments = explode('/', ltrim($filepath, '/'));
if ($segments[0] === 'theme') {
$theme = $segments[1];
unset($segments[0], $segments[1]);
$themePath = App::themePath($theme) . 'webroot' . DS . implode(DS, $segments);
return $path . '?' . @filemtime($themePath);
} else {
$plugin = $segments[0];
unset($segments[0]);
$pluginPath = App::pluginPath($plugin) . 'webroot' . DS . implode(DS, $segments);
return $path . '?' . @filemtime($pluginPath);
}
}
return $path;
} | Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in
Configure. If Asset.timestamp is true and debug > 0, or Asset.timestamp == 'force'
a timestamp will be added.
@param string $path The file path to timestamp, the path must be inside WWW_ROOT
@return string Path with a timestamp added, or not.
@access public | assetTimestamp | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function clean($output) {
$this->__reset();
if (empty($output)) {
return null;
}
if (is_array($output)) {
foreach ($output as $key => $value) {
$return[$key] = $this->clean($value);
}
return $return;
}
$this->__tainted = $output;
$this->__clean();
return $this->__cleaned;
} | Used to remove harmful tags from content. Removes a number of well known XSS attacks
from content. However, is not guaranteed to remove all possiblities. Escaping
content is the best way to prevent all possible attacks.
@param mixed $output Either an array of strings to clean or a single string to clean.
@return cleaned content for output
@access public | clean | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function __formatAttribute($key, $value, $escape = true) {
$attribute = '';
$attributeFormat = '%s="%s"';
$minimizedAttributes = array('compact', 'checked', 'declare', 'readonly', 'disabled',
'selected', 'defer', 'ismap', 'nohref', 'noshade', 'nowrap', 'multiple', 'noresize');
if (is_array($value)) {
$value = '';
}
if (in_array($key, $minimizedAttributes)) {
if ($value === 1 || $value === true || $value === 'true' || $value === '1' || $value == $key) {
$attribute = sprintf($attributeFormat, $key, $key);
}
} else {
$attribute = sprintf($attributeFormat, $key, ($escape ? h($value) : $value));
}
return $attribute;
} | 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.
@return string The composed attribute.
@access private | __formatAttribute | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function setEntity($entity, $setScope = false) {
$view =& ClassRegistry::getObject('view');
if ($setScope) {
$view->modelScope = false;
} elseif (!empty($view->entityPath) && $view->entityPath == $entity) {
return;
}
if ($entity === null) {
$view->model = null;
$view->association = null;
$view->modelId = null;
$view->modelScope = false;
$view->entityPath = null;
return;
}
$view->entityPath = $entity;
$model = $view->model;
$sameScope = $hasField = false;
$parts = array_values(Set::filter(explode('.', $entity), true));
if (empty($parts)) {
return;
}
$count = count($parts);
if ($count === 1) {
$sameScope = true;
} else {
if (is_numeric($parts[0])) {
$sameScope = true;
}
$reverse = array_reverse($parts);
$field = array_shift($reverse);
while(!empty($reverse)) {
$subject = array_shift($reverse);
if (is_numeric($subject)) {
continue;
}
if (ClassRegistry::isKeySet($subject)) {
$model = $subject;
break;
}
}
}
if (ClassRegistry::isKeySet($model)) {
$ModelObj =& ClassRegistry::getObject($model);
for ($i = 0; $i < $count; $i++) {
if (
is_a($ModelObj, 'Model') &&
($ModelObj->hasField($parts[$i]) ||
array_key_exists($parts[$i], $ModelObj->validate))
) {
$hasField = $i;
if ($hasField === 0 || ($hasField === 1 && is_numeric($parts[0]))) {
$sameScope = true;
}
break;
}
}
if ($sameScope === true && in_array($parts[0], array_keys($ModelObj->hasAndBelongsToMany))) {
$sameScope = false;
}
}
if (!$view->association && $parts[0] == $view->field && $view->field != $view->model) {
array_unshift($parts, $model);
$hasField = true;
}
$view->field = $view->modelId = $view->fieldSuffix = $view->association = null;
switch (count($parts)) {
case 1:
if ($view->modelScope === false) {
$view->model = $parts[0];
} else {
$view->field = $parts[0];
if ($sameScope === false) {
$view->association = $parts[0];
}
}
break;
case 2:
if ($view->modelScope === false) {
list($view->model, $view->field) = $parts;
} elseif ($sameScope === true && $hasField === 0) {
list($view->field, $view->fieldSuffix) = $parts;
} elseif ($sameScope === true && $hasField === 1) {
list($view->modelId, $view->field) = $parts;
} else {
list($view->association, $view->field) = $parts;
}
break;
case 3:
if ($sameScope === true && $hasField === 1) {
list($view->modelId, $view->field, $view->fieldSuffix) = $parts;
} elseif ($hasField === 2) {
list($view->association, $view->modelId, $view->field) = $parts;
} else {
list($view->association, $view->field, $view->fieldSuffix) = $parts;
}
break;
case 4:
if ($parts[0] === $view->model) {
list($view->model, $view->modelId, $view->field, $view->fieldSuffix) = $parts;
} else {
list($view->association, $view->modelId, $view->field, $view->fieldSuffix) = $parts;
}
break;
default:
$reverse = array_reverse($parts);
if ($hasField) {
$view->field = $field;
if (!is_numeric($reverse[1]) && $reverse[1] != $model) {
$view->field = $reverse[1];
$view->fieldSuffix = $field;
}
}
if (is_numeric($parts[0])) {
$view->modelId = $parts[0];
} elseif ($view->model == $parts[0] && is_numeric($parts[1])) {
$view->modelId = $parts[1];
}
$view->association = $model;
break;
}
if (!isset($view->model) || empty($view->model)) {
$view->model = $view->association;
$view->association = null;
} elseif ($view->model === $view->association) {
$view->association = null;
}
if ($setScope) {
$view->modelScope = true;
}
} | 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
@access public | setEntity | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function model() {
$view =& ClassRegistry::getObject('view');
if (!empty($view->association)) {
return $view->association;
} else {
return $view->model;
}
} | Gets the currently-used model of the rendering context.
@return string
@access public | model | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function modelID() {
$view =& ClassRegistry::getObject('view');
return $view->modelId;
} | Gets the ID of the currently-used model of the rendering context.
@return mixed
@access public | modelID | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function field() {
$view =& ClassRegistry::getObject('view');
return $view->field;
} | Gets the currently-used model field of the rendering context.
@return string
@access public | field | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function tagIsInvalid($model = null, $field = null, $modelID = null) {
$view =& ClassRegistry::getObject('view');
$errors = $this->validationErrors;
$entity = $view->entity();
if (!empty($entity)) {
return Set::extract(join('.', $entity), $errors);
}
} | Returns null if given FORM field has no errors. Otherwise it returns the constant set in
the array Model->validationErrors.
@param string $model Model name as a string
@param string $field Fieldname as a string
@param integer $modelID Unique index identifying this record within the form
@return mixed Null if no errors, string with error otherwhise. | tagIsInvalid | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function domId($options = null, $id = 'id') {
$view =& ClassRegistry::getObject('view');
if (is_array($options) && array_key_exists($id, $options) && $options[$id] === null) {
unset($options[$id]);
return $options;
} elseif (!is_array($options) && $options !== null) {
$this->setEntity($options);
return $this->domId();
}
$entity = $view->entity();
$model = array_shift($entity);
$dom = $model . join('', array_map(array('Inflector', 'camelize'), $entity));
if (is_array($options) && !array_key_exists($id, $options)) {
$options[$id] = $dom;
} elseif ($options === null) {
return $dom;
}
return $options;
} | Generates a DOM ID for the selected element, if one is not set.
Uses the current View::entity() settings to generate a CamelCased id attribute.
@param mixed $options Either an array of html attributes to add $id into, or a string
with a view entity path to get a domId for.
@param string $id The name of the 'id' attribute.
@return mixed If $options was an array, an array will be returned with $id set. If a string
was supplied, a string will be returned.
@todo Refactor this method to not have as many input/output options. | domId | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function _name($options = array(), $field = null, $key = 'name') {
$view =& ClassRegistry::getObject('view');
if ($options === null) {
$options = array();
} elseif (is_string($options)) {
$field = $options;
$options = 0;
}
if (!empty($field)) {
$this->setEntity($field);
}
if (is_array($options) && array_key_exists($key, $options)) {
return $options;
}
switch ($field) {
case '_method':
$name = $field;
break;
default:
$name = 'data[' . implode('][', $view->entity()) . ']';
break;
}
if (is_array($options)) {
$options[$key] = $name;
return $options;
} else {
return $name;
}
} | Gets the input field name for the current tag. Creates input name attributes
using CakePHP's data[Model][field] formatting.
@param mixed $options If an array, should be an array of attributes that $key needs to be added to.
If a string or null, will be used as the View entity.
@param string $field
@param string $key The name of the attribute to be set, defaults to 'name'
@return mixed If an array was given for $options, an array with $key set will be returned.
If a string was supplied a string will be returned.
@access protected
@todo Refactor this method to not have as many input/output options. | _name | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function value($options = array(), $field = null, $key = 'value') {
if ($options === null) {
$options = array();
} elseif (is_string($options)) {
$field = $options;
$options = 0;
}
if (is_array($options) && isset($options[$key])) {
return $options;
}
if (!empty($field)) {
$this->setEntity($field);
}
$view =& ClassRegistry::getObject('view');
$result = null;
$entity = $view->entity();
if (!empty($this->data) && !empty($entity)) {
$result = Set::extract(join('.', $entity), $this->data);
}
$habtmKey = $this->field();
if (empty($result) && isset($this->data[$habtmKey][$habtmKey]) && is_array($this->data[$habtmKey])) {
$result = $this->data[$habtmKey][$habtmKey];
} elseif (empty($result) && isset($this->data[$habtmKey]) && is_array($this->data[$habtmKey])) {
if (ClassRegistry::isKeySet($habtmKey)) {
$model =& ClassRegistry::getObject($habtmKey);
$result = $this->__selectedArray($this->data[$habtmKey], $model->primaryKey);
}
}
if (is_array($result)) {
if (array_key_exists($view->fieldSuffix, $result)) {
$result = $result[$view->fieldSuffix];
}
}
if (is_array($options)) {
if ($result === null && isset($options['default'])) {
$result = $options['default'];
}
unset($options['default']);
}
if (is_array($options)) {
$options[$key] = $result;
return $options;
} else {
return $result;
}
} | Gets the data for the current tag
@param mixed $options If an array, should be an array of attributes that $key needs to be added to.
If a string or null, will be used as the View entity.
@param string $field
@param string $key The name of the attribute to be set, defaults to 'value'
@return mixed If an array was given for $options, an array with $key set will be returned.
If a string was supplied a string will be returned.
@access public
@todo Refactor this method to not have as many input/output options. | value | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function _initInputField($field, $options = array()) {
if ($field !== null) {
$this->setEntity($field);
}
$options = (array)$options;
$options = $this->_name($options);
$options = $this->value($options);
$options = $this->domId($options);
if ($this->tagIsInvalid() !== null) {
$options = $this->addClass($options, 'form-error');
}
return $options;
} | Sets the defaults for an input tag. Will set the
name, value, and id attributes for an array of html attributes. Will also
add a 'form-error' class if the field contains validation errors.
@param string $field The field name to initialize.
@param array $options Array of options to use while initializing an input field.
@return array Array options for the form input.
@access protected | _initInputField | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function addClass($options = array(), $class = null, $key = 'class') {
if (isset($options[$key]) && trim($options[$key]) != '') {
$options[$key] .= ' ' . $class;
} else {
$options[$key] = $class;
}
return $options;
} | Adds the given class to the element options
@param array $options Array options/attributes to add a class to
@param string $class The classname being added.
@param string $key the key to use for class.
@return array Array of options with $key set.
@access public | addClass | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function output($str) {
return $str;
} | Returns a string generated by a helper method
This method can be overridden in subclasses to do generalized output post-processing
@param string $str String to be output.
@return string
@deprecated This method will be removed in future versions. | output | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function __selectedArray($data, $key = 'id') {
if (!is_array($data)) {
$model = $data;
if (!empty($this->data[$model][$model])) {
return $this->data[$model][$model];
}
if (!empty($this->data[$model])) {
$data = $this->data[$model];
}
}
$array = array();
if (!empty($data)) {
foreach ($data as $var) {
$array[$var[$key]] = $var[$key];
}
}
return $array;
} | Transforms a recordset from a hasAndBelongsToMany association to a list of selected
options for a multiple select element
@param mixed $data
@param string $key
@return array
@access private | __selectedArray | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function __reset() {
$this->__tainted = null;
$this->__cleaned = null;
} | Resets the vars used by Helper::clean() to null
@return void
@access private | __reset | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function __clean() {
if (get_magic_quotes_gpc()) {
$this->__cleaned = stripslashes($this->__tainted);
} else {
$this->__cleaned = $this->__tainted;
}
$this->__cleaned = str_replace(array("&", "<", ">"), array("&amp;", "&lt;", "&gt;"), $this->__cleaned);
$this->__cleaned = preg_replace('#(&\#*\w+)[\x00-\x20]+;#u', "$1;", $this->__cleaned);
$this->__cleaned = preg_replace('#(&\#x*)([0-9A-F]+);*#iu', "$1$2;", $this->__cleaned);
$this->__cleaned = html_entity_decode($this->__cleaned, ENT_COMPAT, "UTF-8");
$this->__cleaned = preg_replace('#(<[^>]+[\x00-\x20\"\'\/])(on|xmlns)[^>]*>#iUu', "$1>", $this->__cleaned);
$this->__cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*)[\\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iUu', '$1=$2nojavascript...', $this->__cleaned);
$this->__cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=([\'\"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iUu', '$1=$2novbscript...', $this->__cleaned);
$this->__cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=*([\'\"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#iUu','$1=$2nomozbinding...', $this->__cleaned);
$this->__cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=([\'\"]*)[\x00-\x20]*data[\x00-\x20]*:#Uu', '$1=$2nodata...', $this->__cleaned);
$this->__cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*expression[\x00-\x20]*\([^>]*>#iU', "$1>", $this->__cleaned);
$this->__cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*behaviour[\x00-\x20]*\([^>]*>#iU', "$1>", $this->__cleaned);
$this->__cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*>#iUu', "$1>", $this->__cleaned);
$this->__cleaned = preg_replace('#</*\w+:\w[^>]*>#i', "", $this->__cleaned);
do {
$oldstring = $this->__cleaned;
$this->__cleaned = preg_replace('#</*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>#i', "", $this->__cleaned);
} while ($oldstring != $this->__cleaned);
$this->__cleaned = str_replace(array("&", "<", ">"), array("&amp;", "&lt;", "&gt;"), $this->__cleaned);
} | Removes harmful content from output
@return void
@access private | __clean | php | Datawalke/Coordino | cake/libs/view/helper.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helper.php | MIT |
function render() {
$name = $download = $extension = $id = $modified = $path = $size = $cache = $mimeType = null;
extract($this->viewVars, EXTR_OVERWRITE);
if ($size) {
$id = $id . '_' . $size;
}
if (is_dir($path)) {
$path = $path . $id;
} else {
$path = APP . $path . $id;
}
if (!file_exists($path)) {
header('Content-Type: text/html');
$this->cakeError('error404');
}
if (is_null($name)) {
$name = $id;
}
if (is_array($mimeType)) {
$this->mimeType = array_merge($this->mimeType, $mimeType);
}
if (isset($extension) && isset($this->mimeType[strtolower($extension)]) && connection_status() == 0) {
$chunkSize = 8192;
$buffer = '';
$fileSize = @filesize($path);
$handle = fopen($path, 'rb');
if ($handle === false) {
return false;
}
if (!empty($modified)) {
$modified = gmdate('D, d M Y H:i:s', strtotime($modified, time())) . ' GMT';
} else {
$modified = gmdate('D, d M Y H:i:s') . ' GMT';
}
if ($download) {
$contentTypes = array('application/octet-stream');
$agent = env('HTTP_USER_AGENT');
if (preg_match('%Opera(/| )([0-9].[0-9]{1,2})%', $agent)) {
$contentTypes[0] = 'application/octetstream';
} else if (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $agent)) {
$contentTypes[0] = 'application/force-download';
array_merge($contentTypes, array(
'application/octet-stream',
'application/download'
));
}
foreach($contentTypes as $contentType) {
$this->_header('Content-Type: ' . $contentType);
}
$this->_header(array(
'Content-Disposition: attachment; filename="' . $name . '.' . $extension . '";',
'Expires: 0',
'Accept-Ranges: bytes',
'Cache-Control: private' => false,
'Pragma: private'));
$httpRange = env('HTTP_RANGE');
if (isset($httpRange)) {
list($toss, $range) = explode('=', $httpRange);
$size = $fileSize - 1;
$length = $fileSize - $range;
$this->_header(array(
'HTTP/1.1 206 Partial Content',
'Content-Length: ' . $length,
'Content-Range: bytes ' . $range . $size . '/' . $fileSize));
fseek($handle, $range);
} else {
$this->_header('Content-Length: ' . $fileSize);
}
} else {
$this->_header('Date: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
if ($cache) {
if (!is_numeric($cache)) {
$cache = strtotime($cache) - time();
}
$this->_header(array(
'Cache-Control: max-age=' . $cache,
'Expires: ' . gmdate('D, d M Y H:i:s', time() + $cache) . ' GMT',
'Pragma: cache'));
} else {
$this->_header(array(
'Cache-Control: must-revalidate, post-check=0, pre-check=0',
'Pragma: no-cache'));
}
$this->_header(array(
'Last-Modified: ' . $modified,
'Content-Type: ' . $this->mimeType[strtolower($extension)],
'Content-Length: ' . $fileSize));
}
$this->_output();
$this->_clearBuffer();
while (!feof($handle)) {
if (!$this->_isActive()) {
fclose($handle);
return false;
}
set_time_limit(0);
$buffer = fread($handle, $chunkSize);
echo $buffer;
$this->_flushBuffer();
}
fclose($handle);
return;
}
return false;
} | Display or download the given file
@return unknown | render | php | Datawalke/Coordino | cake/libs/view/media.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/media.php | MIT |
function _header($header, $boolean = true) {
if (is_array($header)) {
foreach ($header as $string => $boolean) {
if (is_numeric($string)) {
$this->_headers[] = array($boolean => true);
} else {
$this->_headers[] = array($string => $boolean);
}
}
return;
}
$this->_headers[] = array($header => $boolean);
return;
} | Method to set headers
@param mixed $header
@param boolean $boolean
@access protected | _header | php | Datawalke/Coordino | cake/libs/view/media.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/media.php | MIT |
function _output() {
foreach ($this->_headers as $key => $value) {
$header = key($value);
header($header, $value[$header]);
}
} | Method to output headers
@access protected | _output | php | Datawalke/Coordino | cake/libs/view/media.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/media.php | MIT |
function _isActive() {
return connection_status() == 0 && !connection_aborted();
} | Returns true if connection is still active
@return boolean
@access protected | _isActive | php | Datawalke/Coordino | cake/libs/view/media.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/media.php | MIT |
function _clearBuffer() {
return @ob_end_clean();
} | Clears the contents of the topmost output buffer and discards them
@return boolean
@access protected | _clearBuffer | php | Datawalke/Coordino | cake/libs/view/media.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/media.php | MIT |
function _flushBuffer() {
@flush();
@ob_flush();
} | Flushes the contents of the output buffer
@access protected | _flushBuffer | php | Datawalke/Coordino | cake/libs/view/media.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/media.php | MIT |
function __construct(&$controller, $register = true) {
parent::__construct($controller, $register);
$this->theme =& $controller->theme;
} | Constructor for ThemeView sets $this->theme.
@param Controller $controller Controller object to be rendered.
@param boolean $register Should the view be registered in the registry. | __construct | php | Datawalke/Coordino | cake/libs/view/theme.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/theme.php | MIT |
function _paths($plugin = null, $cached = true) {
$paths = parent::_paths($plugin, $cached);
$themePaths = array();
if (!empty($this->theme)) {
$count = count($paths);
for ($i = 0; $i < $count; $i++) {
if (strpos($paths[$i], DS . 'plugins' . DS) === false
&& strpos($paths[$i], DS . 'libs' . DS . 'view') === false) {
if ($plugin) {
$themePaths[] = $paths[$i] . 'themed'. DS . $this->theme . DS . 'plugins' . DS . $plugin . DS;
}
$themePaths[] = $paths[$i] . 'themed'. DS . $this->theme . DS;
}
}
$paths = array_merge($themePaths, $paths);
}
return $paths;
} | Return all possible paths to find view files in order
@param string $plugin The name of the plugin views are being found for.
@param boolean $cached Set to true to force dir scan.
@return array paths
@access protected
@todo Make theme path building respect $cached parameter. | _paths | php | Datawalke/Coordino | cake/libs/view/theme.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/theme.php | MIT |
function __construct(&$controller, $register = true) {
if (is_object($controller)) {
$count = count($this->__passedVars);
for ($j = 0; $j < $count; $j++) {
$var = $this->__passedVars[$j];
$this->{$var} = $controller->{$var};
}
}
parent::__construct();
if ($register) {
ClassRegistry::addObject('view', $this);
}
} | Constructor
@param Controller $controller A controller object to pull View::__passedArgs from.
@param boolean $register Should the View instance be registered in the ClassRegistry
@return View | __construct | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function element($name, $params = array(), $loadHelpers = false) {
$file = $plugin = $key = null;
if (isset($params['plugin'])) {
$plugin = $params['plugin'];
}
if (isset($this->plugin) && !$plugin) {
$plugin = $this->plugin;
}
if (isset($params['cache'])) {
$expires = '+1 day';
if (is_array($params['cache'])) {
$expires = $params['cache']['time'];
$key = Inflector::slug($params['cache']['key']);
} else {
$key = implode('_', array_keys($params));
if ($params['cache'] !== true) {
$expires = $params['cache'];
}
}
if ($expires) {
$cacheFile = 'element_' . $key . '_' . $plugin . Inflector::slug($name);
$cache = cache('views' . DS . $cacheFile, null, $expires);
if (is_string($cache)) {
return $cache;
}
}
}
$paths = $this->_paths($plugin);
$exts = $this->_getExtensions();
foreach ($exts as $ext) {
foreach ($paths as $path) {
if (file_exists($path . 'elements' . DS . $name . $ext)) {
$file = $path . 'elements' . DS . $name . $ext;
break;
}
}
if ($file) {
break;
}
}
if (is_file($file)) {
$vars = array_merge($this->viewVars, $params);
foreach ($this->loaded as $name => $helper) {
if (!isset($vars[$name])) {
$vars[$name] =& $this->loaded[$name];
}
}
$element = $this->_render($file, $vars, $loadHelpers);
if (isset($params['cache']) && isset($cacheFile) && isset($expires)) {
cache('views' . DS . $cacheFile, $element, $expires);
}
return $element;
}
$file = $paths[0] . 'elements' . DS . $name . $this->ext;
if (Configure::read() > 0) {
return "Not Found: " . $file;
}
} | 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 through use of the cache key.
### Special params
- `cache` - enable caching for this element accepts boolean or strtotime compatible string.
Can also be an array. If `cache` is an array,
`time` is used to specify duration of cache.
`key` can be used to create unique cache files.
- `plugin` - Load an element from a specific plugin.
@param string $name Name of template file in the/app/views/elements/ folder
@param array $params Array of data to be made available to the for rendered
view (i.e. the Element)
@return string Rendered Element
@access public | element | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function render($action = null, $layout = null, $file = null) {
if ($this->hasRendered) {
return true;
}
$out = null;
if ($file != null) {
$action = $file;
}
if ($action !== false && $viewFileName = $this->_getViewFileName($action)) {
$out = $this->_render($viewFileName, $this->viewVars);
}
if ($layout === null) {
$layout = $this->layout;
}
if ($out !== false) {
if ($layout && $this->autoLayout) {
$out = $this->renderLayout($out, $layout);
$isCached = (
isset($this->loaded['cache']) ||
Configure::read('Cache.check') === true
);
if ($isCached) {
$replace = array('<cake:nocache>', '</cake:nocache>');
$out = str_replace($replace, '', $out);
}
}
$this->hasRendered = true;
} else {
$out = $this->_render($viewFileName, $this->viewVars);
trigger_error(sprintf(__("Error in view %s, got: <blockquote>%s</blockquote>", true), $viewFileName, $out), E_USER_ERROR);
}
return $out;
} | Renders view for given action and layout. If $file is given, that is used
for a view filename (e.g. customFunkyView.ctp).
@param string $action Name of action to render for
@param string $layout Layout to use
@param string $file Custom filename for view
@return string Rendered Element
@access public | render | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function renderLayout($content_for_layout, $layout = null) {
$layoutFileName = $this->_getLayoutFileName($layout);
if (empty($layoutFileName)) {
return $this->output;
}
$dataForLayout = array_merge($this->viewVars, array(
'content_for_layout' => $content_for_layout,
'scripts_for_layout' => implode("\n\t", $this->__scripts),
));
if (!isset($dataForLayout['title_for_layout'])) {
$dataForLayout['title_for_layout'] = Inflector::humanize($this->viewPath);
}
if (empty($this->loaded) && !empty($this->helpers)) {
$loadHelpers = true;
} else {
$loadHelpers = false;
$dataForLayout = array_merge($dataForLayout, $this->loaded);
}
$this->_triggerHelpers('beforeLayout');
$this->output = $this->_render($layoutFileName, $dataForLayout, $loadHelpers, true);
if ($this->output === false) {
$this->output = $this->_render($layoutFileName, $dataForLayout);
trigger_error(sprintf(__("Error in layout %s, got: <blockquote>%s</blockquote>", true), $layoutFileName, $this->output), E_USER_ERROR);
return false;
}
$this->_triggerHelpers('afterLayout');
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.
@return mixed Rendered output, or false on error
@access public | renderLayout | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function _triggerHelpers($callback) {
if (empty($this->loaded)) {
return false;
}
$helpers = array_keys($this->loaded);
foreach ($helpers as $helperName) {
$helper =& $this->loaded[$helperName];
if (is_object($helper)) {
if (is_subclass_of($helper, 'Helper')) {
$helper->{$callback}();
}
}
}
} | Fire a callback on all loaded Helpers. All helpers must implement this method,
it is not checked before being called. You can add additional helper callbacks in AppHelper.
@param string $callback name of callback fire.
@access protected
@return void | _triggerHelpers | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function renderCache($filename, $timeStart) {
ob_start();
include ($filename);
if (Configure::read() > 0 && $this->layout != 'xml') {
echo "<!-- Cached Render Time: " . round(getMicrotime() - $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;
}
}
} | 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.
@access public | renderCache | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function getVars() {
return array_keys($this->viewVars);
} | Returns a list of variables available in the current View context
@return array Array of the set view variable names.
@access public | getVars | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function getVar($var) {
if (!isset($this->viewVars[$var])) {
return null;
} else {
return $this->viewVars[$var];
}
} | 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.
@access public | getVar | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function addScript($name, $content = null) {
if (empty($content)) {
if (!in_array($name, array_values($this->__scripts))) {
$this->__scripts[] = $name;
}
} else {
$this->__scripts[$name] = $content;
}
} | 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
@access public | addScript | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
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;
} | 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
@access public | uuid | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function entity() {
$assoc = ($this->association) ? $this->association : $this->model;
if (!empty($this->entityPath)) {
$path = explode('.', $this->entityPath);
$count = count($path);
if (
($count == 1 && !empty($this->association)) ||
($count == 1 && $this->model != $this->entityPath) ||
($count == 1 && empty($this->association) && !empty($this->field)) ||
($count == 2 && !empty($this->fieldSuffix)) ||
is_numeric($path[0]) && !empty($assoc)
) {
array_unshift($path, $assoc);
}
return Set::filter($path);
}
return array_values(Set::filter(
array($assoc, $this->modelId, $this->field, $this->fieldSuffix)
));
} | Returns the entity reference of the current context as an array of identity parts
@return array An array containing the identity elements of an entity
@access public | entity | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
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;
} | 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
@access public | set | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function error($code, $name, $message) {
header ("HTTP/1.1 {$code} {$name}");
print ($this->_render(
$this->_getLayoutFileName('error'),
array('code' => $code, 'name' => $name, 'message' => $message)
));
} | Displays an error page to the user. Uses layouts/error.ctp to render the page.
@param integer $code HTTP Error code (for instance: 404)
@param string $name Name of the error (for instance: Not Found)
@param string $message Error message as a web page
@access public | error | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function _render($___viewFn, $___dataForView, $loadHelpers = true, $cached = false) {
$loadedHelpers = array();
if ($this->helpers != false && $loadHelpers === true) {
$loadedHelpers = $this->_loadHelpers($loadedHelpers, $this->helpers);
$helpers = array_keys($loadedHelpers);
$helperNames = array_map(array('Inflector', 'variable'), $helpers);
for ($i = count($helpers) - 1; $i >= 0; $i--) {
$name = $helperNames[$i];
$helper =& $loadedHelpers[$helpers[$i]];
if (!isset($___dataForView[$name])) {
${$name} =& $helper;
}
$this->loaded[$helperNames[$i]] =& $helper;
$this->{$helpers[$i]} =& $helper;
}
$this->_triggerHelpers('beforeRender');
unset($name, $loadedHelpers, $helpers, $i, $helperNames, $helper);
}
extract($___dataForView, EXTR_SKIP);
ob_start();
if (Configure::read() > 0) {
include ($___viewFn);
} else {
@include ($___viewFn);
}
if ($loadHelpers === true) {
$this->_triggerHelpers('afterRender');
}
$out = ob_get_clean();
$caching = (
isset($this->loaded['cache']) &&
(($this->cacheAction != false)) && (Configure::read('Cache.check') === true)
);
if ($caching) {
if (is_a($this->loaded['cache'], 'CacheHelper')) {
$cache =& $this->loaded['cache'];
$cache->base = $this->base;
$cache->here = $this->here;
$cache->helpers = $this->helpers;
$cache->action = $this->action;
$cache->controllerName = $this->name;
$cache->layout = $this->layout;
$cache->cacheAction = $this->cacheAction;
$cache->viewVars = $this->viewVars;
$out = $cache->cache($___viewFn, $out, $cached);
}
}
return $out;
} | 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
@param boolean $loadHelpers Boolean to indicate that helpers should be loaded.
@param boolean $cached Whether or not to trigger the creation of a cache file.
@return string Rendered output
@access protected | _render | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function &_loadHelpers(&$loaded, $helpers, $parent = null) {
foreach ($helpers as $i => $helper) {
$options = array();
if (!is_int($i)) {
$options = $helper;
$helper = $i;
}
list($plugin, $helper) = pluginSplit($helper, true, $this->plugin);
$helperCn = $helper . 'Helper';
if (!isset($loaded[$helper])) {
if (!class_exists($helperCn)) {
$isLoaded = false;
if (!is_null($plugin)) {
$isLoaded = App::import('Helper', $plugin . $helper);
}
if (!$isLoaded) {
if (!App::import('Helper', $helper)) {
$this->cakeError('missingHelperFile', array(array(
'helper' => $helper,
'file' => Inflector::underscore($helper) . '.php',
'base' => $this->base
)));
return false;
}
}
if (!class_exists($helperCn)) {
$this->cakeError('missingHelperClass', array(array(
'helper' => $helper,
'file' => Inflector::underscore($helper) . '.php',
'base' => $this->base
)));
return false;
}
}
$loaded[$helper] =& new $helperCn($options);
$vars = array('base', 'webroot', 'here', 'params', 'action', 'data', 'theme', 'plugin');
$c = count($vars);
for ($j = 0; $j < $c; $j++) {
$loaded[$helper]->{$vars[$j]} = $this->{$vars[$j]};
}
if (!empty($this->validationErrors)) {
$loaded[$helper]->validationErrors = $this->validationErrors;
}
if (is_array($loaded[$helper]->helpers) && !empty($loaded[$helper]->helpers)) {
$loaded =& $this->_loadHelpers($loaded, $loaded[$helper]->helpers, $helper);
}
}
if (isset($loaded[$parent])) {
$loaded[$parent]->{$helper} =& $loaded[$helper];
}
}
return $loaded;
} | Loads helpers, with their dependencies.
@param array $loaded List of helpers that are already loaded.
@param array $helpers List of helpers to load.
@param string $parent holds name of helper, if loaded helper has helpers
@return array Array containing the loaded helpers.
@access protected | _loadHelpers | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function _getViewFileName($name = null) {
$subDir = null;
if (!is_null($this->subDir)) {
$subDir = $this->subDir . DS;
}
if ($name === null) {
$name = $this->action;
}
$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(Inflector::underscore($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;
}
}
}
return $this->_missingView($defaultPath . $name . $this->ext, 'missingView');
}
/**
* 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).
* @access 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(Inflector::underscore($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;
}
}
}
return $this->_missingView($paths[0] . $file . $this->ext, 'missingLayout');
}
/**
* Get the extensions that view files can use.
*
* @return array Array of extensions view files use.
* @access protected
*/
function _getExtensions() {
$exts = array($this->ext);
if ($this->ext !== '.ctp') {
array_push($exts, '.ctp');
}
return $exts;
}
/**
* Return a misssing view error message
*
* @param string $viewFileName the filename that should exist
* @return false
* @access protected
*/
function _missingView($file, $error = 'missingView') {
if ($error === 'missingView') {
$this->cakeError('missingView', array(
'className' => $this->name,
'action' => $this->action,
'file' => $file,
'base' => $this->base
));
return false;
} elseif ($error === 'missingLayout') {
$this->cakeError('missingLayout', array(
'layout' => $this->layout,
'file' => $file,
'base' => $this->base
));
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
* @access protected
*/
function _paths($plugin = null, $cached = true) {
if ($plugin === null && $cached === true && !empty($this->__paths)) {
return $this->__paths;
}
$paths = array();
$viewPaths = App::path('views');
$corePaths = array_flip(App::core('views'));
if (!empty($plugin)) {
$count = count($viewPaths);
for ($i = 0; $i < $count; $i++) {
if (!isset($corePaths[$viewPaths[$i]])) {
$paths[] = $viewPaths[$i] . 'plugins' . DS . $plugin . DS;
}
}
$paths[] = App::pluginPath($plugin) . 'views' . DS;
}
$this->__paths = array_merge($paths, $viewPaths);
return $this->__paths;
}
} | 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
@access protected | _getViewFileName | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function _getLayoutFileName($name = null) {
if ($name === null) {
$name = $this->layout;
}
$subDir = null;
if (!is_null($this->layoutPath)) {
$subDir = $this->layoutPath . DS;
}
$paths = $this->_paths(Inflector::underscore($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;
}
}
}
return $this->_missingView($paths[0] . $file . $this->ext, 'missingLayout');
} | 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).
@access protected | _getLayoutFileName | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function _getExtensions() {
$exts = array($this->ext);
if ($this->ext !== '.ctp') {
array_push($exts, '.ctp');
}
return $exts;
} | Get the extensions that view files can use.
@return array Array of extensions view files use.
@access protected | _getExtensions | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function _missingView($file, $error = 'missingView') {
if ($error === 'missingView') {
$this->cakeError('missingView', array(
'className' => $this->name,
'action' => $this->action,
'file' => $file,
'base' => $this->base
));
return false;
} elseif ($error === 'missingLayout') {
$this->cakeError('missingLayout', array(
'layout' => $this->layout,
'file' => $file,
'base' => $this->base
));
return false;
}
} | Return a misssing view error message
@param string $viewFileName the filename that should exist
@return false
@access protected | _missingView | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function _paths($plugin = null, $cached = true) {
if ($plugin === null && $cached === true && !empty($this->__paths)) {
return $this->__paths;
}
$paths = array();
$viewPaths = App::path('views');
$corePaths = array_flip(App::core('views'));
if (!empty($plugin)) {
$count = count($viewPaths);
for ($i = 0; $i < $count; $i++) {
if (!isset($corePaths[$viewPaths[$i]])) {
$paths[] = $viewPaths[$i] . 'plugins' . DS . $plugin . DS;
}
}
$paths[] = App::pluginPath($plugin) . 'views' . DS;
}
$this->__paths = array_merge($paths, $viewPaths);
return $this->__paths;
} | 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
@access protected | _paths | php | Datawalke/Coordino | cake/libs/view/view.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/view.php | MIT |
function link($title, $url = null, $options = array(), $confirm = null) {
if (!isset($url)) {
$url = $title;
}
if (!isset($options['url'])) {
$options['url'] = $url;
}
if (!empty($confirm)) {
$options['confirm'] = $confirm;
unset($confirm);
}
$htmlOptions = $this->__getHtmlOptions($options, array('url'));
$options += array('safe' => true);
unset($options['escape']);
if (empty($options['fallback']) || !isset($options['fallback'])) {
$options['fallback'] = $url;
}
$htmlDefaults = array('id' => 'link' . intval(mt_rand()), 'onclick' => '');
$htmlOptions = array_merge($htmlDefaults, $htmlOptions);
$htmlOptions['onclick'] .= ' event.returnValue = false; return false;';
$return = $this->Html->link($title, $url, $htmlOptions);
$callback = $this->remoteFunction($options);
$script = $this->Javascript->event("'{$htmlOptions['id']}'", "click", $callback);
if (is_string($script)) {
$return .= $script;
}
return $return;
} | Returns link to remote action
Returns a link to a remote action defined by <i>options[url]</i>
(using the url() format) that's called in the background using
XMLHttpRequest. The result of that request can then be inserted into a
DOM object whose id can be specified with <i>options[update]</i>.
Examples:
<code>
link("Delete this post",
array("update" => "posts", "url" => "delete/{$postid->id}"));
link(imageTag("refresh"),
array("update" => "emails", "url" => "list_emails" ));
</code>
By default, these remote requests are processed asynchronous during
which various callbacks can be triggered (for progress indicators and
the likes).
Example:
<code>
link (word,
array("url" => "undo", "n" => word_counter),
array("complete" => "undoRequestCompleted(request)"));
</code>
The callbacks that may be specified are:
- <i>loading</i>:: Called when the remote document is being
loaded with data by the browser.
- <i>loaded</i>:: Called when the browser has finished loading
the remote document.
- <i>interactive</i>:: Called when the user can interact with the
remote document, even though it has not
finished loading.
- <i>complete</i>:: Called when the XMLHttpRequest is complete.
If you for some reason or another need synchronous processing (that'll
block the browser while the request is happening), you can specify
<i>options[type] = synchronous</i>.
You can customize further browser side call logic by passing
in Javascript code snippets via some optional parameters. In
their order of use these are:
- <i>confirm</i>:: Adds confirmation dialog.
-<i>condition</i>:: Perform remote request conditionally
by this expression. Use this to
describe browser-side conditions when
request should not be initiated.
- <i>before</i>:: Called before request is initiated.
- <i>after</i>:: Called immediately after request was
initiated and before <i>loading</i>.
@param string $title Title of link
@param mixed $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
@param array $options Options for JavaScript function
@param string $confirm Confirmation message. Calls up a JavaScript confirm() message.
@return string HTML code for link to remote action
@link http://book.cakephp.org/view/1363/link | link | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function remoteFunction($options) {
if (isset($options['update'])) {
if (!is_array($options['update'])) {
$func = "new Ajax.Updater('{$options['update']}',";
} else {
$func = "new Ajax.Updater(document.createElement('div'),";
}
if (!isset($options['requestHeaders'])) {
$options['requestHeaders'] = array();
}
if (is_array($options['update'])) {
$options['update'] = implode(' ', $options['update']);
}
$options['requestHeaders']['X-Update'] = $options['update'];
} else {
$func = "new Ajax.Request(";
}
$url = isset($options['url']) ? $options['url'] : "";
if (empty($options['safe'])) {
$url = $this->url($url);
} else {
$url = Router::url($url);
}
$func .= "'" . $url . "'";
$func .= ", " . $this->__optionsForAjax($options) . ")";
if (isset($options['before'])) {
$func = "{$options['before']}; $func";
}
if (isset($options['after'])) {
$func = "$func; {$options['after']};";
}
if (isset($options['condition'])) {
$func = "if ({$options['condition']}) { $func; }";
}
if (isset($options['confirm'])) {
$func = "if (confirm('" . $this->Javascript->escapeString($options['confirm'])
. "')) { $func; } else { event.returnValue = false; return false; }";
}
return $func;
} | Creates JavaScript function for remote AJAX call
This function creates the javascript needed to make a remote call
it is primarily used as a helper for AjaxHelper::link.
@param array $options options for javascript
@return string html code for link to remote action
@see AjaxHelper::link() for docs on options parameter.
@link http://book.cakephp.org/view/1364/remoteFunction | remoteFunction | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function remoteTimer($options = null) {
$frequency = (isset($options['frequency'])) ? $options['frequency'] : 10;
$callback = $this->remoteFunction($options);
$code = "new PeriodicalExecuter(function(pe) {{$callback}}, $frequency)";
return $this->Javascript->codeBlock($code);
} | Periodically call remote url via AJAX.
Periodically calls the specified url (<i>options[url]</i>) every <i>options[frequency]</i>
seconds (default is 10). Usually used to update a specified div (<i>options[update]</i>) with
the results of the remote call. The options for specifying the target with url and defining
callbacks is the same as AjaxHelper::link().
@param array $options Callback options
@return string Javascript code
@see AjaxHelper::link()
@link http://book.cakephp.org/view/1365/remoteTimer | remoteTimer | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function observeField($field, $options = array()) {
if (!isset($options['with'])) {
$options['with'] = 'Form.Element.serialize(\'' . $field . '\')';
}
$observer = 'Observer';
if (!isset($options['frequency']) || intval($options['frequency']) == 0) {
$observer = 'EventObserver';
}
return $this->Javascript->codeBlock(
$this->_buildObserver('Form.Element.' . $observer, $field, $options)
);
} | Observe field and call ajax on change.
Observes the field with the DOM ID specified by <i>field</i> and makes
an Ajax when its contents have changed.
Required +options+ are:
- <i>frequency</i>:: The frequency (in seconds) at which changes to
this field will be detected.
- <i>url</i>:: @see url() -style options for the action to call
when the field has changed.
Additional options are:
- <i>update</i>:: Specifies the DOM ID of the element whose
innerHTML should be updated with the
XMLHttpRequest response text.
- <i>with</i>:: A Javascript expression specifying the
parameters for the XMLHttpRequest. This defaults
to Form.Element.serialize('$field'), which can be
accessed from params['form']['field_id'].
Additionally, you may specify any of the options documented in
@see linkToRemote().
@param string $field DOM ID of field to observe
@param array $options ajax options
@return string ajax script
@link http://book.cakephp.org/view/1368/observeField | observeField | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function observeForm($form, $options = array()) {
if (!isset($options['with'])) {
$options['with'] = 'Form.serialize(\'' . $form . '\')';
}
$observer = 'Observer';
if (!isset($options['frequency']) || intval($options['frequency']) == 0) {
$observer = 'EventObserver';
}
return $this->Javascript->codeBlock(
$this->_buildObserver('Form.' . $observer, $form, $options)
);
} | Observe entire form and call ajax on change.
Like @see observeField(), but operates on an entire form identified by the
DOM ID <b>form</b>. <b>options</b> are the same as <b>observeField</b>, except
the default value of the <i>with</i> option evaluates to the
serialized (request string) value of the form.
@param string $form DOM ID of form to observe
@param array $options ajax options
@return string ajax script
@link http://book.cakephp.org/view/1369/observeForm | observeForm | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function autoComplete($field, $url = "", $options = array()) {
$var = '';
if (isset($options['var'])) {
$var = 'var ' . $options['var'] . ' = ';
unset($options['var']);
}
if (!isset($options['id'])) {
$options['id'] = Inflector::camelize(str_replace(".", "_", $field));
}
$divOptions = array(
'id' => $options['id'] . "_autoComplete",
'class' => isset($options['class']) ? $options['class'] : 'auto_complete'
);
if (isset($options['div_id'])) {
$divOptions['id'] = $options['div_id'];
unset($options['div_id']);
}
$htmlOptions = $this->__getHtmlOptions($options);
$htmlOptions['autocomplete'] = "off";
foreach ($this->autoCompleteOptions as $opt) {
unset($htmlOptions[$opt]);
}
if (isset($options['tokens'])) {
if (is_array($options['tokens'])) {
$options['tokens'] = $this->Javascript->object($options['tokens']);
} else {
$options['tokens'] = '"' . $options['tokens'] . '"';
}
}
$options = $this->_optionsToString($options, array('paramName', 'indicator'));
$options = $this->_buildOptions($options, $this->autoCompleteOptions);
$text = $this->Form->text($field, $htmlOptions);
$div = $this->Html->div(null, '', $divOptions);
$script = "{$var}new Ajax.Autocompleter('{$htmlOptions['id']}', '{$divOptions['id']}', '";
$script .= $this->Html->url($url) . "', {$options});";
return "{$text}\n{$div}\n" . $this->Javascript->codeBlock($script);
} | Create a text field with Autocomplete.
Creates an autocomplete field with the given ID and options.
options['with'] defaults to "Form.Element.serialize('$field')",
but can be any valid javascript expression defining the additional fields.
@param string $field DOM ID of field to observe
@param string $url URL for the autocomplete action
@param array $options Ajax options
@return string Ajax script
@link http://book.cakephp.org/view/1370/autoComplete | autoComplete | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function div($id, $options = array()) {
if (env('HTTP_X_UPDATE') != null) {
$this->Javascript->enabled = false;
$divs = explode(' ', env('HTTP_X_UPDATE'));
if (in_array($id, $divs)) {
@ob_end_clean();
ob_start();
return '';
}
}
$attr = $this->_parseAttributes(array_merge($options, array('id' => $id)));
return sprintf($this->Html->tags['blockstart'], $attr);
} | Creates an Ajax-updateable DIV element
@param string $id options for javascript
@return string HTML code | div | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function divEnd($id) {
if (env('HTTP_X_UPDATE') != null) {
$divs = explode(' ', env('HTTP_X_UPDATE'));
if (in_array($id, $divs)) {
$this->__ajaxBuffer[$id] = ob_get_contents();
ob_end_clean();
ob_start();
return '';
}
}
return $this->Html->tags['blockend'];
} | Closes an Ajax-updateable DIV element
@param string $id The DOM ID of the element
@return string HTML code | divEnd | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function isAjax() {
return (isset($this->params['isAjax']) && $this->params['isAjax'] === true);
} | Detects Ajax requests
@return boolean True if the current request is a Prototype Ajax update call
@link http://book.cakephp.org/view/1371/isAjax | isAjax | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function drag($id, $options = array()) {
$var = '';
if (isset($options['var'])) {
$var = 'var ' . $options['var'] . ' = ';
unset($options['var']);
}
$options = $this->_buildOptions(
$this->_optionsToString($options, array('handle', 'constraint')), $this->dragOptions
);
return $this->Javascript->codeBlock("{$var}new Draggable('$id', " .$options . ");");
} | Creates a draggable element. For a reference on the options for this function,
check out http://github.com/madrobby/scriptaculous/wikis/draggable
@param unknown_type $id
@param array $options
@return unknown
@link http://book.cakephp.org/view/1372/drag-drop | drag | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function drop($id, $options = array()) {
$optionsString = array('overlap', 'hoverclass');
if (!isset($options['accept']) || !is_array($options['accept'])) {
$optionsString[] = 'accept';
} else if (isset($options['accept'])) {
$options['accept'] = $this->Javascript->object($options['accept']);
}
$options = $this->_buildOptions(
$this->_optionsToString($options, $optionsString), $this->dropOptions
);
return $this->Javascript->codeBlock("Droppables.add('{$id}', {$options});");
} | For a reference on the options for this function, check out
http://github.com/madrobby/scriptaculous/wikis/droppables
@param unknown_type $id
@param array $options
@return string
@link http://book.cakephp.org/view/1372/drag-drop | drop | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function dropRemote($id, $options = array(), $ajaxOptions = array()) {
$callback = $this->remoteFunction($ajaxOptions);
$options['onDrop'] = "function(element, droppable, event) {{$callback}}";
$optionsString = array('overlap', 'hoverclass');
if (!isset($options['accept']) || !is_array($options['accept'])) {
$optionsString[] = 'accept';
} else if (isset($options['accept'])) {
$options['accept'] = $this->Javascript->object($options['accept']);
}
$options = $this->_buildOptions(
$this->_optionsToString($options, $optionsString),
$this->dropOptions
);
return $this->Javascript->codeBlock("Droppables.add('{$id}', {$options});");
} | Make an element with the given $id droppable, and trigger an Ajax call when a draggable is
dropped on it.
For a reference on the options for this function, check out
http://wiki.script.aculo.us/scriptaculous/show/Droppables.add
@param string $id
@param array $options
@param array $ajaxOptions
@return string JavaScript block to create a droppable element | dropRemote | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function slider($id, $trackId, $options = array()) {
if (isset($options['var'])) {
$var = 'var ' . $options['var'] . ' = ';
unset($options['var']);
} else {
$var = 'var ' . $id . ' = ';
}
$options = $this->_optionsToString($options, array(
'axis', 'handleImage', 'handleDisabled'
));
$callbacks = array('change', 'slide');
foreach ($callbacks as $callback) {
if (isset($options[$callback])) {
$call = $options[$callback];
$options['on' . ucfirst($callback)] = "function(value) {{$call}}";
unset($options[$callback]);
}
}
if (isset($options['values']) && is_array($options['values'])) {
$options['values'] = $this->Javascript->object($options['values']);
}
$options = $this->_buildOptions($options, $this->sliderOptions);
$script = "{$var}new Control.Slider('$id', '$trackId', $options);";
return $this->Javascript->codeBlock($script);
} | Makes a slider control.
@param string $id DOM ID of slider handle
@param string $trackId DOM ID of slider track
@param array $options Array of options to control the slider
@link http://github.com/madrobby/scriptaculous/wikis/slider
@link http://book.cakephp.org/view/1373/slider | slider | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function editor($id, $url, $options = array()) {
$url = $this->url($url);
$options['ajaxOptions'] = $this->__optionsForAjax($options);
foreach ($this->ajaxOptions as $opt) {
if (isset($options[$opt])) {
unset($options[$opt]);
}
}
if (isset($options['callback'])) {
$options['callback'] = 'function(form, value) {' . $options['callback'] . '}';
}
$type = 'InPlaceEditor';
if (isset($options['collection']) && is_array($options['collection'])) {
$options['collection'] = $this->Javascript->object($options['collection']);
$type = 'InPlaceCollectionEditor';
}
$var = '';
if (isset($options['var'])) {
$var = 'var ' . $options['var'] . ' = ';
unset($options['var']);
}
$options = $this->_optionsToString($options, array(
'okText', 'cancelText', 'savingText', 'formId', 'externalControl', 'highlightcolor',
'highlightendcolor', 'savingClassName', 'formClassName', 'loadTextURL', 'loadingText',
'clickToEditText', 'okControl', 'cancelControl'
));
$options = $this->_buildOptions($options, $this->editorOptions);
$script = "{$var}new Ajax.{$type}('{$id}', '{$url}', {$options});";
return $this->Javascript->codeBlock($script);
} | Makes an Ajax In Place editor control.
@param string $id DOM ID of input element
@param string $url Postback URL of saved data
@param array $options Array of options to control the editor, including ajaxOptions (see link).
@link http://github.com/madrobby/scriptaculous/wikis/ajax-inplaceeditor
@link http://book.cakephp.org/view/1374/editor | editor | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function sortable($id, $options = array()) {
if (!empty($options['url'])) {
if (empty($options['with'])) {
$options['with'] = "Sortable.serialize('$id')";
}
$options['onUpdate'] = 'function(sortable) {' . $this->remoteFunction($options) . '}';
}
$block = true;
if (isset($options['block'])) {
$block = $options['block'];
unset($options['block']);
}
$strings = array(
'tag', 'constraint', 'only', 'handle', 'hoverclass', 'tree',
'treeTag', 'update', 'overlap'
);
$scrollIsObject = (
isset($options['scroll']) &&
$options['scroll'] != 'window' &&
strpos($options['scroll'], '$(') !== 0
);
if ($scrollIsObject) {
$strings[] = 'scroll';
}
$options = $this->_optionsToString($options, $strings);
$options = array_merge($options, $this->_buildCallbacks($options));
$options = $this->_buildOptions($options, $this->sortOptions);
$result = "Sortable.create('$id', $options);";
if (!$block) {
return $result;
}
return $this->Javascript->codeBlock($result);
} | Makes a list or group of floated objects sortable.
@param string $id DOM ID of parent
@param array $options Array of options to control sort.
@link http://github.com/madrobby/scriptaculous/wikis/sortable
@link http://book.cakephp.org/view/1375/sortable | sortable | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function __optionsForAjax($options) {
if (isset($options['indicator'])) {
if (isset($options['loading'])) {
$loading = $options['loading'];
if (!empty($loading) && substr(trim($loading), -1, 1) != ';') {
$options['loading'] .= '; ';
}
$options['loading'] .= "Element.show('{$options['indicator']}');";
} else {
$options['loading'] = "Element.show('{$options['indicator']}');";
}
if (isset($options['complete'])) {
$complete = $options['complete'];
if (!empty($complete) && substr(trim($complete), -1, 1) != ';') {
$options['complete'] .= '; ';
}
$options['complete'] .= "Element.hide('{$options['indicator']}');";
} else {
$options['complete'] = "Element.hide('{$options['indicator']}');";
}
unset($options['indicator']);
}
$jsOptions = array_merge(
array('asynchronous' => 'true', 'evalScripts' => 'true'),
$this->_buildCallbacks($options)
);
$options = $this->_optionsToString($options, array(
'contentType', 'encoding', 'fallback', 'method', 'postBody', 'update', 'url'
));
$jsOptions = array_merge($jsOptions, array_intersect_key($options, array_flip(array(
'contentType', 'encoding', 'method', 'postBody'
))));
foreach ($options as $key => $value) {
switch ($key) {
case 'type':
$jsOptions['asynchronous'] = ($value == 'synchronous') ? 'false' : 'true';
break;
case 'evalScripts':
$jsOptions['evalScripts'] = ($value) ? 'true' : 'false';
break;
case 'position':
$pos = Inflector::camelize($options['position']);
$jsOptions['insertion'] = "Insertion.{$pos}";
break;
case 'with':
$jsOptions['parameters'] = $options['with'];
break;
case 'form':
$jsOptions['parameters'] = 'Form.serialize(this)';
break;
case 'requestHeaders':
$keys = array();
foreach ($value as $key => $val) {
$keys[] = "'" . $key . "'";
$keys[] = "'" . $val . "'";
}
$jsOptions['requestHeaders'] = '[' . implode(', ', $keys) . ']';
break;
}
}
return $this->_buildOptions($jsOptions, $this->ajaxOptions);
} | Private helper function for Javascript.
@param array $options Set of options
@access private | __optionsForAjax | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function __getHtmlOptions($options, $extra = array()) {
foreach (array_merge($this->ajaxOptions, $this->callbacks, $extra) as $key) {
if (isset($options[$key])) {
unset($options[$key]);
}
}
return $options;
} | Private Method to return a string of html options
option data as a JavaScript options hash.
@param array $options Options in the shape of keys and values
@param array $extra Array of legal keys in this options context
@return array Array of html options
@access private | __getHtmlOptions | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function _buildOptions($options, $acceptable) {
if (is_array($options)) {
$out = array();
foreach ($options as $k => $v) {
if (in_array($k, $acceptable)) {
if ($v === true) {
$v = 'true';
} elseif ($v === false) {
$v = 'false';
}
$out[] = "$k:$v";
} elseif ($k === 'with' && in_array('parameters', $acceptable)) {
$out[] = "parameters:${v}";
}
}
$out = implode(', ', $out);
$out = '{' . $out . '}';
return $out;
} else {
return false;
}
} | Returns a string of JavaScript with the given option data as a JavaScript options hash.
@param array $options Options in the shape of keys and values
@param array $acceptable Array of legal keys in this options context
@return string String of Javascript array definition | _buildOptions | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function _buildObserver($klass, $name, $options = null) {
if (!isset($options['with']) && isset($options['update'])) {
$options['with'] = 'value';
}
$callback = $this->remoteFunction($options);
$hasFrequency = !(!isset($options['frequency']) || intval($options['frequency']) == 0);
$frequency = $hasFrequency ? $options['frequency'] . ', ' : '';
return "new $klass('$name', {$frequency}function(element, value) {{$callback}})";
} | Return JavaScript text for an observer...
@param string $klass Name of JavaScript class
@param string $name
@param array $options Ajax options
@return string Formatted JavaScript | _buildObserver | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function _buildCallbacks($options) {
$callbacks = array();
foreach ($this->callbacks as $callback) {
if (isset($options[$callback])) {
$name = 'on' . ucfirst($callback);
$code = $options[$callback];
switch ($name) {
case 'onComplete':
$callbacks[$name] = "function(request, json) {" . $code . "}";
break;
case 'onCreate':
$callbacks[$name] = "function(request, xhr) {" . $code . "}";
break;
case 'onException':
$callbacks[$name] = "function(request, exception) {" . $code . "}";
break;
default:
$callbacks[$name] = "function(request) {" . $code . "}";
break;
}
if (isset($options['bind'])) {
$bind = $options['bind'];
$hasBinding = (
(is_array($bind) && in_array($callback, $bind)) ||
(is_string($bind) && strpos($bind, $callback) !== false)
);
if ($hasBinding) {
$callbacks[$name] .= ".bind(this)";
}
}
}
}
return $callbacks;
} | Return Javascript text for callbacks.
@param array $options Option array where a callback is specified
@return array Options with their callbacks properly set
@access protected | _buildCallbacks | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function _optionsToString($options, $stringOpts = array()) {
foreach ($stringOpts as $option) {
$hasOption = (
isset($options[$option]) && !empty($options[$option]) &&
is_string($options[$option]) && $options[$option][0] != "'"
);
if ($hasOption) {
if ($options[$option] === true || $options[$option] === 'true') {
$options[$option] = 'true';
} elseif ($options[$option] === false || $options[$option] === 'false') {
$options[$option] = 'false';
} else {
$options[$option] = "'{$options[$option]}'";
}
}
}
return $options;
} | Returns a string of JavaScript with a string representation of given options array.
@param array $options Ajax options array
@param array $stringOpts Options as strings in an array
@access private
@return array | _optionsToString | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function afterRender() {
if (env('HTTP_X_UPDATE') != null && !empty($this->__ajaxBuffer)) {
@ob_end_clean();
$data = array();
$divs = explode(' ', env('HTTP_X_UPDATE'));
$keys = array_keys($this->__ajaxBuffer);
if (count($divs) == 1 && in_array($divs[0], $keys)) {
echo $this->__ajaxBuffer[$divs[0]];
} else {
foreach ($this->__ajaxBuffer as $key => $val) {
if (in_array($key, $divs)) {
$data[] = $key . ':"' . rawurlencode($val) . '"';
}
}
$out = 'var __ajaxUpdater__ = {' . implode(", \n", $data) . '};' . "\n";
$out .= 'for (n in __ajaxUpdater__) { if (typeof __ajaxUpdater__[n] == "string"';
$out .= ' && $(n)) Element.update($(n), unescape(decodeURIComponent(';
$out .= '__ajaxUpdater__[n]))); }';
echo $this->Javascript->codeBlock($out, false);
}
$scripts = $this->Javascript->getCache();
if (!empty($scripts)) {
echo $this->Javascript->codeBlock($scripts, false);
}
$this->_stop();
}
} | Executed after a view has rendered, used to include bufferred code
blocks.
@access public | afterRender | php | Datawalke/Coordino | cake/libs/view/helpers/ajax.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/ajax.php | MIT |
function cache($file, $out, $cache = false) {
$cacheTime = 0;
$useCallbacks = false;
if (is_array($this->cacheAction)) {
$keys = array_keys($this->cacheAction);
$index = null;
foreach ($keys as $action) {
if ($action == $this->params['action']) {
$index = $action;
break;
}
}
if (!isset($index) && $this->action == 'index') {
$index = 'index';
}
$options = $this->cacheAction;
if (isset($this->cacheAction[$index])) {
if (is_array($this->cacheAction[$index])) {
$options = array_merge(array('duration' => 0, 'callbacks' => false), $this->cacheAction[$index]);
} else {
$cacheTime = $this->cacheAction[$index];
}
}
if (isset($options['duration'])) {
$cacheTime = $options['duration'];
}
if (isset($options['callbacks'])) {
$useCallbacks = $options['callbacks'];
}
} else {
$cacheTime = $this->cacheAction;
}
if ($cacheTime != '' && $cacheTime > 0) {
$out = preg_replace_callback('/<cake\: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;
}
} | 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 | cache | php | Datawalke/Coordino | cake/libs/view/helpers/cache.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/cache.php | MIT |
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('/(<cake:nocache:\d{3}>(?<=<cake:nocache:\d{3}>)[\\s\\S]*?(?=<\/cake:nocache>)<\/cake:nocache>)/i', $cache, $outputResult, PREG_PATTERN_ORDER);
preg_match_all('/(?<=<cake:nocache>)([\\s\\S]*?)(?=<\/cake: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++;
}
}
} | Parse file searching for no cache tags
@param string $file The filename that needs to be parsed.
@param string $cache The cached content
@access private | __parseFile | php | Datawalke/Coordino | cake/libs/view/helpers/cache.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/cache.php | MIT |
function _replaceSection($matches) {
$this->_counter += 1;
return sprintf('<cake:nocache:%03d>', $this->_counter);
} | Munges the output from a view with cache tags, and numbers the sections.
This helps solve issues with empty/duplicate content.
@param string $content The content to munge.
@return string The content with cake:nocache tags replaced. | _replaceSection | php | Datawalke/Coordino | cake/libs/view/helpers/cache.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/cache.php | MIT |
function _stripTags($content) {
return preg_replace('#<\/?cake\:nocache(\:\d{3})?>#', '', $content);
} | 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. | _stripTags | php | Datawalke/Coordino | cake/libs/view/helpers/cache.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/cache.php | MIT |
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;
} | Parse the output and replace cache tags
@param string $cache Output to replace content in.
@return string with all replacements made to <cake:nocache><cake:nocache>
@access private | __parseOutput | php | Datawalke/Coordino | cake/libs/view/helpers/cache.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/cache.php | MIT |
function __writeFile($content, $timestamp, $useCallbacks = false) {
$now = time();
if (is_numeric($timestamp)) {
$cacheTime = $now + $timestamp;
} else {
$cacheTime = strtotime($timestamp, $now);
}
$path = $this->here;
if ($this->here == '/') {
$path = 'home';
}
$cache = strtolower(Inflector::slug($path));
if (empty($cache)) {
return;
}
$cache = $cache . '.php';
$file = '<!--cachetime:' . $cacheTime . '--><?php';
if (empty($this->plugin)) {
$file .= '
App::import(\'Controller\', \'' . $this->controllerName. '\');
';
} else {
$file .= '
App::import(\'Controller\', \'' . $this->plugin . '.' . $this->controllerName. '\');
';
}
$file .= '$controller =& new ' . $this->controllerName . 'Controller();
$controller->plugin = $this->plugin = \''.$this->plugin.'\';
$controller->helpers = $this->helpers = unserialize(\'' . serialize($this->helpers) . '\');
$controller->base = $this->base = \'' . $this->base . '\';
$controller->layout = $this->layout = \'' . $this->layout. '\';
$controller->webroot = $this->webroot = \'' . $this->webroot . '\';
$controller->here = $this->here = \'' . addslashes($this->here) . '\';
$controller->params = $this->params = unserialize(stripslashes(\'' . addslashes(serialize($this->params)) . '\'));
$controller->action = $this->action = unserialize(\'' . serialize($this->action) . '\');
$controller->data = $this->data = unserialize(stripslashes(\'' . addslashes(serialize($this->data)) . '\'));
$controller->viewVars = $this->viewVars = unserialize(base64_decode(\'' . base64_encode(serialize($this->viewVars)) . '\'));
$controller->theme = $this->theme = \'' . $this->theme . '\';
Router::setRequestInfo(array($this->params, array(\'base\' => $this->base, \'webroot\' => $this->webroot)));';
if ($useCallbacks == true) {
$file .= '
$controller->constructClasses();
$controller->Component->initialize($controller);
$controller->beforeFilter();
$controller->Component->startup($controller);
$this->params = $controller->params;';
}
$file .= '
$loadedHelpers = array();
$loadedHelpers = $this->_loadHelpers($loadedHelpers, $this->helpers);
foreach (array_keys($loadedHelpers) as $helper) {
$camelBackedHelper = Inflector::variable($helper);
${$camelBackedHelper} =& $loadedHelpers[$helper];
$this->loaded[$camelBackedHelper] =& ${$camelBackedHelper};
$this->{$helper} =& $loadedHelpers[$helper];
}
extract($this->viewVars, EXTR_SKIP);
?>';
$content = preg_replace("/(<\\?xml)/", "<?php echo '$1';?>",$content);
$file .= $content;
return cache('views' . DS . $cache, $file, $timestamp);
} | Write a cached version of the file
@param string $content view content to write to a cache file.
@param sting $timestamp Duration to set for cache file.
@return boolean success of caching view.
@access private | __writeFile | php | Datawalke/Coordino | cake/libs/view/helpers/cache.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/cache.php | MIT |
function &_introspectModel($model) {
$object = null;
if (is_string($model) && strpos($model, '.') !== false) {
$path = explode('.', $model);
$model = end($path);
}
if (ClassRegistry::isKeySet($model)) {
$object =& ClassRegistry::getObject($model);
}
if (!empty($object)) {
$fields = $object->schema();
foreach ($fields as $key => $value) {
unset($fields[$key]);
$fields[$key] = $value;
}
if (!empty($object->hasAndBelongsToMany)) {
foreach ($object->hasAndBelongsToMany as $alias => $assocData) {
$fields[$alias] = array('type' => 'multiple');
}
}
$validates = array();
if (!empty($object->validate)) {
foreach ($object->validate as $validateField => $validateProperties) {
if ($this->_isRequiredField($validateProperties)) {
$validates[] = $validateField;
}
}
}
$defaults = array('fields' => array(), 'key' => 'id', 'validates' => array());
$key = $object->primaryKey;
$this->fieldset[$model] = array_merge($defaults, compact('fields', 'key', 'validates'));
}
return $object;
} | Introspects model information and extracts information related
to validation, field length and field type. Appends information into
$this->fieldset.
@return Model Returns a model instance
@access protected | _introspectModel | php | Datawalke/Coordino | cake/libs/view/helpers/form.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/form.php | MIT |
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 if a field is required to be filled based on validation properties from the validating object
@return boolean true if field is required to be filled, false otherwise
@access protected | _isRequiredField | php | Datawalke/Coordino | cake/libs/view/helpers/form.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/form.php | MIT |
function secure($fields = array()) {
if (!isset($this->params['_Token']) || empty($this->params['_Token'])) {
return;
}
$locked = array();
foreach ($fields as $key => $value) {
if (!is_int($key)) {
$locked[$key] = $value;
unset($fields[$key]);
}
}
sort($fields, SORT_STRING);
ksort($locked, SORT_STRING);
$fields += $locked;
$fields = Security::hash(serialize($fields) . Configure::read('Security.salt'));
$locked = implode(array_keys($locked), '|');
$out = $this->hidden('_Token.fields', array(
'value' => urlencode($fields . ':' . $locked),
'id' => 'TokenFields' . mt_rand()
));
$out = sprintf($this->Html->tags['block'], ' style="display:none;"', $out);
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
@access public | secure | php | Datawalke/Coordino | cake/libs/view/helpers/form.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/form.php | MIT |
function __secure($field = null, $value = null) {
if (!$field) {
$view =& ClassRegistry::getObject('view');
$field = $view->entity();
} elseif (is_string($field)) {
$field = Set::filter(explode('.', $field), true);
}
if (!empty($this->params['_Token']['disabledFields'])) {
foreach ((array)$this->params['_Token']['disabledFields'] as $disabled) {
$disabled = explode('.', $disabled);
if (array_values(array_intersect($field, $disabled)) === $disabled) {
return;
}
}
}
$last = end($field);
if (is_numeric($last) || empty($last)) {
array_pop($field);
}
$field = implode('.', $field);
if (!in_array($field, $this->fields)) {
if ($value !== null) {
return $this->fields[$field] = $value;
}
$this->fields[] = $field;
}
} | Determine which fields of a form should be used for hash.
Populates $this->fields
@param mixed $field Reference to field to be secured
@param mixed $value Field value, if value should not be tampered with.
@return void
@access private | __secure | php | Datawalke/Coordino | cake/libs/view/helpers/form.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/form.php | MIT |
function isFieldError($field) {
$this->setEntity($field);
return (bool)$this->tagIsInvalid();
} | 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.
@access public
@link http://book.cakephp.org/view/1426/isFieldError | isFieldError | php | Datawalke/Coordino | cake/libs/view/helpers/form.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/form.php | MIT |
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 !== null) {
if (is_array($error)) {
list(,,$field) = explode('.', $field);
if (isset($error[$field])) {
$error = $error[$field];
} else {
return null;
}
}
if (is_array($text) && is_numeric($error) && $error > 0) {
$error--;
}
if (is_array($text)) {
$options = array_merge($options, array_intersect_key($text, $defaults));
if (isset($text['attributes']) && is_array($text['attributes'])) {
$options = array_merge($options, $text['attributes']);
}
$text = isset($text[$error]) ? $text[$error] : null;
unset($options[$error]);
}
if ($text !== null) {
$error = $text;
} elseif (is_numeric($error)) {
$error = sprintf(__('Error in field %s', true), Inflector::humanize($this->field()));
}
if ($options['escape']) {
$error = h($error);
unset($options['escape']);
}
if ($options['wrap']) {
$tag = is_string($options['wrap']) ? $options['wrap'] : 'div';
unset($options['wrap']);
return $this->Html->tag($tag, $error, $options);
} else {
return $error;
}
} else {
return null;
}
} | 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 or array of $options. If array, `attributes` key
will get used as html attributes 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.
@access public
@link http://book.cakephp.org/view/1423/error | error | php | Datawalke/Coordino | cake/libs/view/helpers/form.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/form.php | MIT |
function label($fieldName = null, $text = null, $options = array()) {
if (empty($fieldName)) {
$view = ClassRegistry::getObject('view');
$fieldName = implode('.', $view->entity());
}
if ($text === null) {
if (strpos($fieldName, '.') !== false) {
$text = array_pop(explode('.', $fieldName));
} else {
$text = $fieldName;
}
if (substr($text, -3) == '_id') {
$text = substr($text, 0, strlen($text) - 3);
}
$text = __(Inflector::humanize(Inflector::underscore($text)), true);
}
if (is_string($options)) {
$options = array('class' => $options);
}
if (isset($options['for'])) {
$labelFor = $options['for'];
unset($options['for']);
} else {
$labelFor = $this->domId($fieldName);
}
return sprintf(
$this->Html->tags['label'],
$labelFor,
$this->_parseAttributes($options), $text
);
} | 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/view/1427/label | label | php | Datawalke/Coordino | cake/libs/view/helpers/form.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/form.php | MIT |
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->fieldset[$model]['fields']);
}
if ($legend === true) {
$actionName = __('New %s', true);
$isEdit = (
strpos($this->action, 'update') !== false ||
strpos($this->action, 'edit') !== false
);
if ($isEdit) {
$actionName = __('Edit %s', true);
}
$modelName = Inflector::humanize(Inflector::underscore($model));
$legend = sprintf($actionName, __($modelName, true));
}
$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 sprintf(
$this->Html->tags['fieldset'],
$fieldsetClass,
sprintf($this->Html->tags['legend'], $legend) . $out
);
} elseif ($fieldset) {
return sprintf($this->Html->tags['fieldset'], $fieldsetClass, $out);
} else {
return $out;
}
} | 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.
@access public | inputs | php | Datawalke/Coordino | cake/libs/view/helpers/form.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/form.php | MIT |
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($this->fieldset[$modelKey])) {
$this->_introspectModel($modelKey);
}
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($this->fieldset[$modelKey]['fields'][$fieldKey])) {
$fieldDef = $this->fieldset[$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' => 'text'
);
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 (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')
) {
$view =& ClassRegistry::getObject('view');
$varName = Inflector::variable(
Inflector::pluralize(preg_replace('/_id$/', '', $fieldKey))
);
$varOptions = $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 (
isset($this->fieldset[$modelKey]) &&
in_array($fieldKey, $this->fieldset[$modelKey]['validates'])
) {
$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 'text':
case 'password':
case 'file':
$input = $this->{$type}($fieldName, $options);
break;
case 'select':
$options += array('options' => array());
$list = $options['options'];
unset($options['options']);
$input = $this->select($fieldName, $list, $selected, $options);
break;
case 'time':
$input = $this->dateTime($fieldName, null, $timeFormat, $selected, $options);
break;
case 'date':
$input = $this->dateTime($fieldName, $dateFormat, null, $selected, $options);
break;
case 'datetime':
$input = $this->dateTime($fieldName, $dateFormat, $timeFormat, $selected, $options);
break;
case 'textarea':
default:
$input = $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6'));
break;
}
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;
} | 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.
@access public
@link http://book.cakephp.org/view/1390/Automagic-Form-Elements | input | php | Datawalke/Coordino | cake/libs/view/helpers/form.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/form.php | MIT |
function _extractOption($name, $options, $default = null) {
if (array_key_exists($name, $options)) {
return $options[$name];
}
return $default;
} | 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 the contents of the option or default
@access protected | _extractOption | php | Datawalke/Coordino | cake/libs/view/helpers/form.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/form.php | MIT |
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);
} | Generate a label for an input() call.
@param array $options Options for the label element.
@return string Generated label element
@access protected | _inputLabel | php | Datawalke/Coordino | cake/libs/view/helpers/form.php | https://github.com/Datawalke/Coordino/blob/master/cake/libs/view/helpers/form.php | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.