sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function _triggerOperator(Query $query, TokenInterface $token)
{
$eventName = 'Search.' . (string)Inflector::variable('operator_' . $token->name());
$event = new Event($eventName, $this->_table, compact('query', 'token'));
return EventManager::instance()->dispatch($event)->result;
}
|
Triggers an event for handling undefined operators. Event listeners may
capture this event and provide operator handling logic, such listeners should
alter the provided Query object and then return it back.
The triggered event follows the pattern:
```
Search.operator<CamelCaseOperatorName>
```
For example, `Search.operatorAuthorName` will be triggered for
handling an operator named either `author-name` or `author_name`.
@param \Cake\ORM\Query $query The query that is expected to be scoped
@param \Search\TokenInterface $token Token describing an operator. e.g `-op_name:op_value`
@return mixed Scoped query object expected or null if event was not captured by any listener
|
entailment
|
protected function _operatorCallable($name)
{
$operator = $this->config("operators.{$name}");
if ($operator) {
$handler = $operator['handler'];
if (is_callable($handler)) {
return function ($query, $token) use ($handler) {
return $handler($query, $token);
};
} elseif ($handler instanceof BaseOperator) {
return function ($query, $token) use ($handler) {
return $handler->scope($query, $token);
};
} elseif (is_string($handler) && method_exists($this->_table, $handler)) {
return function ($query, $token) use ($handler) {
return $this->_table->$handler($query, $token);
};
} elseif (is_string($handler) && is_subclass_of($handler, '\Search\Operator\BaseOperator')) {
return function ($query, $token) use ($operator) {
$instance = new $operator['handler']($this->_table, $operator['options']);
return $instance->scope($query, $token);
};
}
}
return false;
}
|
Gets the callable method for a given operator method.
@param string $name Name of the method to get
@return bool|callable False if no callback was found for the given operator
name. Or the callable if found.
|
entailment
|
public function index()
{
$themes = plugin()
->filter(function ($plugin) {
return $plugin->isTheme;
});
$frontThemes = $themes
->filter(function ($theme) {
return !isset($theme->composer['extra']['admin']) || !$theme->composer['extra']['admin'];
})
->sortBy(function ($theme) {
if ($theme->name() === option('front_theme')) {
return 0;
}
return 1;
}, SORT_ASC);
$backThemes = $themes
->filter(function ($theme) {
return isset($theme->composer['extra']['admin']) && $theme->composer['extra']['admin'];
})
->sortBy(function ($theme) {
if ($theme->name() === option('back_theme')) {
return 0;
}
return 1;
}, SORT_ASC);
$frontCount = count($frontThemes->toArray());
$backCount = count($backThemes->toArray());
$this->title(__d('system', 'Themes'));
$this->_awaitingPlugins('theme');
$this->set(compact('frontCount', 'backCount', 'frontThemes', 'backThemes'));
$this->Breadcrumb->push('/admin/system/themes');
}
|
Main action.
@return void
|
entailment
|
public function install()
{
if ($this->request->data()) {
$task = false;
$uploadError = false;
if (isset($this->request->data['download'])) {
$task = (bool)WebShellDispatcher::run("Installer.plugins install -s \"{$this->request->data['url']}\" --theme -a");
} elseif (isset($this->request->data['file_system'])) {
$task = (bool)WebShellDispatcher::run("Installer.plugins install -s \"{$this->request->data['path']}\" --theme -a");
} else {
$uploader = new PackageUploader($this->request->data['file']);
if ($uploader->upload()) {
$task = (bool)WebShellDispatcher::run('Installer.plugins install -s "' . $uploader->dst() . '" --theme -a');
} else {
$uploadError = true;
$this->Flash->set(__d('system', 'Plugins installed but some errors occur'), [
'element' => 'System.installer_errors',
'params' => ['errors' => $uploader->errors(), 'type' => 'warning'],
]);
}
}
if ($task) {
$this->Flash->success(__d('system', 'Theme successfully installed!'));
$this->redirect($this->referer());
} elseif (!$task && !$uploadError) {
$this->Flash->set(__d('system', 'Theme could not be installed'), [
'element' => 'System.installer_errors',
'params' => ['errors' => WebShellDispatcher::output()],
]);
}
}
$this->title(__d('system', 'Install Theme'));
$this->Breadcrumb
->push('/admin/system/themes')
->push(__d('system', 'Install new theme'), '#');
}
|
Install a new theme.
@return void
|
entailment
|
public function uninstall($themeName)
{
$theme = plugin($themeName); // throws
if (!in_array($themeName, [option('front_theme'), option('back_theme')])) {
if (!$theme->requiredBy()->isEmpty()) {
$this->Flash->danger(__d('system', 'You cannot remove this theme!'));
} else {
$task = (bool)WebShellDispatcher::run("Installer.plugins uninstall -p {$theme->name}");
if ($task) {
$this->Flash->success(__d('system', 'Theme successfully removed!'));
} else {
$this->Flash->set(__d('system', 'Theme could not be removed'), [
'element' => 'System.installer_errors',
'params' => ['errors' => WebShellDispatcher::output()],
]);
}
}
} else {
$this->Flash->danger(__d('system', 'This theme cannot be removed as it is currently being used.'));
}
$this->title(__d('system', 'Uninstall Theme'));
$this->redirect($this->referer());
}
|
Removes the given theme.
@param string $themeName Theme's name
@return void
|
entailment
|
public function details($themeName)
{
$theme = plugin($themeName); // throws
$this->title(__d('system', 'Theme Information'));
$this->set(compact('theme'));
$this->Breadcrumb
->push('/admin/system/themes')
->push($theme->humanName, '#')
->push(__d('system', 'Details'), '#');
}
|
Detailed theme's information.
@param string $themeName Theme's name
@return void
|
entailment
|
public function screenshot($themeName)
{
$theme = plugin($themeName); // throws
$this->response->file("{$theme->path}/webroot/screenshot.png");
return $this->response;
}
|
Renders theme's "screenshot.png"
@param string $themeName Theme's name
@return \Cake\Network\Response
|
entailment
|
public function settings($themeName)
{
$info = plugin($themeName);
$this->loadModel('System.Plugins');
$theme = $this->Plugins->get($themeName, ['flatten' => true]);
if (!$info->hasSettings || !$info->isTheme) {
throw new NotFoundException(__d('system', 'The requested page was not found.'));
}
if ($this->request->data()) {
$theme = $this->Plugins->patchEntity($theme, $this->request->data(), ['entity' => $theme]);
if (!$theme->errors()) {
if ($this->Plugins->save($theme)) {
$this->Flash->success(__d('system', 'Theme settings saved!'));
$this->redirect($this->referer());
}
} else {
$this->Flash->danger(__d('system', 'Theme settings could not be saved.'));
}
}
$this->title(__d('system', 'Theme’s Settings'));
$this->set(compact('info', 'theme'));
$this->Breadcrumb
->push('/admin/system/themes')
->push(__d('system', 'Settings for {0} theme', $info->name), '#');
}
|
Handles theme's specifics settings.
When saving theme's information `PluginsTable` will trigger the
following events:
- `Plugin.<PluginName>.beforeValidate`
- `Plugin.<PluginName>.afterValidate`
- `Plugin.<PluginName>.beforeSave`
- `Plugin.<PluginName>.afterSave`
Check `PluginsTable` documentation for more details.
Additionally theme may define default values for each input, to do this they
must catch the event:
- `Plugin.<PluginName>.settingsDefaults`
They must return an associative array of default values for each input in the
form.
Validation rules can be applied to settings, theme must simply catch the
event:
- `Plugin.<PluginName>.settingsValidate`
@param string $themeName Theme's name
@return void
@throws \Cake\Network\Exception\NotFoundException When plugin do not exists
|
entailment
|
public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
{
$status = array_key_exists('fieldable', $options) ? $options['fieldable'] : $this->config('status');
if (!$status) {
return;
}
if (array_key_exists('eav', $options)) {
unset($options['eav']);
}
return parent::beforeFind($event, $query, $options, $primary);
}
|
Modifies the query object in order to merge custom fields records into each
entity under the `_fields` property.
You can enable or disable this behavior for a single `find()` or `get()`
operation by setting `fieldable` or `eav` to false in the options array for
find method. e.g.:
```php
$contents = $this->Contents->find('all', ['fieldable' => false]);
$content = $this->Contents->get($id, ['fieldable' => false]);
```
It also looks for custom fields in WHERE clause. This will search entities in
all bundles this table may have, if you need to restrict the search to an
specific bundle you must use the `bundle` key in find()'s options:
```php
$this->Contents
->find('all', ['bundle' => 'articles'])
->where(['article-title' => 'My first article!']);
```
The `bundle` option has no effects if no custom fields are given in the
WHERE clause.
@param \Cake\Event\Event $event The beforeFind event that was triggered
@param \Cake\ORM\Query $query The original query to modify
@param \ArrayObject $options Additional options given as an array
@param bool $primary Whether this find is a primary query or not
@return void
|
entailment
|
protected function _hydrateEntities(CollectionInterface $entities, array $args)
{
return $entities->map(function ($entity) use ($args) {
if ($entity instanceof EntityInterface) {
$entity = $this->_prepareCachedColumns($entity);
$entity = $this->_attachEntityFields($entity, $args);
if ($entity === null) {
return self::NULL_ENTITY;
}
}
return $entity;
})
->filter(function ($entity) {
return $entity !== self::NULL_ENTITY;
});
}
|
{@inheritDoc}
|
entailment
|
protected function _attachEntityFields(EntityInterface $entity, array $args)
{
$entity = $this->attachEntityFields($entity);
foreach ($entity->get('_fields') as $field) {
$result = $field->beforeFind((array)$args['options'], $args['primary']);
if ($result === null) {
return null; // remove entity from collection
}
}
return $entity;
}
|
Attaches entity's field under the `_fields` property, this method is invoked
by `beforeFind()` when iterating results sets.
@param \Cake\Datasource\EntityInterface $entity The entity being altered
@param array $args Arguments given to the originating `beforeFind()`
|
entailment
|
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)
{
if (!$this->config('status')) {
return true;
}
if (!$options['atomic']) {
throw new FatalErrorException(__d('field', 'Entities in fieldable tables can only be saved using transaction. Set [atomic = true]'));
}
if (!$this->_validation($entity)) {
return false;
}
$this->_cache['createValues'] = [];
foreach ($this->_attributesForEntity($entity) as $attr) {
if (!$this->_toolbox->propertyExists($entity, $attr->get('name'))) {
continue;
}
$field = $this->_prepareMockField($entity, $attr);
$result = $field->beforeSave($this->_fetchPost($field));
if ($result === false) {
$this->attachEntityFields($entity);
return false;
}
$data = [
'eav_attribute_id' => $field->get('metadata')->get('attribute_id'),
'entity_id' => $this->_toolbox->getEntityId($entity),
"value_{$field->metadata['type']}" => $field->get('value'),
'extra' => $field->get('extra'),
];
if ($field->get('metadata')->get('value_id')) {
$valueEntity = TableRegistry::get('Eav.EavValues')->get($field->get('metadata')->get('value_id'));
$valueEntity = TableRegistry::get('Eav.EavValues')->patchEntity($valueEntity, $data, ['validate' => false]);
} else {
$valueEntity = TableRegistry::get('Eav.EavValues')->newEntity($data, ['validate' => false]);
}
if ($entity->isNew() || $valueEntity->isNew()) {
$this->_cache['createValues'][] = $valueEntity;
} elseif (!TableRegistry::get('Eav.EavValues')->save($valueEntity)) {
$this->attachEntityFields($entity);
$event->stopPropagation();
return false;
}
}
$this->attachEntityFields($entity);
return true;
}
|
Before an entity is saved.
Here is where we dispatch each custom field's `$_POST` information to its
corresponding Field Handler, so they can operate over their values.
Fields Handler's `beforeSave()` method is automatically invoked for each
attached field for the entity being processed, your field handler should look
as follow:
```php
use Field\Handler;
class TextField extends Handler
{
public function beforeSave(Field $field, $post)
{
// alter $field, and do nifty things with $post
// return FALSE; will halt the operation
}
}
```
Field Handlers should **alter** `$field->value` and `$field->extra` according
to its needs using the provided **$post** argument.
**NOTE:** Returning boolean FALSE will halt the whole Entity's save operation.
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\Datasource\EntityInterface $entity The entity being saved
@param \ArrayObject $options Additional options given as an array
@throws \Cake\Error\FatalErrorException When using this behavior in non-atomic mode
@return bool True if save operation should continue
|
entailment
|
public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options)
{
if (!$this->config('status')) {
return true;
}
// as we don't know entity's ID on beforeSave, we must delay values storage;
// all this occurs inside a transaction so we are safe
if (!empty($this->_cache['createValues'])) {
foreach ($this->_cache['createValues'] as $valueEntity) {
$valueEntity->set('entity_id', $this->_toolbox->getEntityId($entity));
$valueEntity->unsetProperty('id');
TableRegistry::get('Eav.EavValues')->save($valueEntity);
}
$this->_cache['createValues'] = [];
}
foreach ($this->_attributesForEntity($entity) as $attr) {
$field = $this->_prepareMockField($entity, $attr);
$field->afterSave();
}
if ($this->config('cacheMap')) {
$this->updateEavCache($entity);
}
return true;
}
|
After an entity is saved.
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\Datasource\EntityInterface $entity The entity that was saved
@param \ArrayObject $options Additional options given as an array
@return bool True always
|
entailment
|
public function beforeDelete(Event $event, EntityInterface $entity, ArrayObject $options)
{
if (!$this->config('status')) {
return true;
}
if (!$options['atomic']) {
throw new FatalErrorException(__d('field', 'Entities in fieldable tables can only be deleted using transaction. Set [atomic = true]'));
}
foreach ($this->_attributesForEntity($entity) as $attr) {
$field = $this->_prepareMockField($entity, $attr);
$result = $field->beforeDelete();
if ($result === false) {
$event->stopPropagation();
return false;
}
// holds in cache field mocks, so we can catch them on afterDelete
$this->_cache['afterDelete'][] = $field;
}
return true;
}
|
Deletes an entity from a fieldable table.
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\Datasource\EntityInterface $entity The entity being deleted
@param \ArrayObject $options Additional options given as an array
@return bool
@throws \Cake\Error\FatalErrorException When using this behavior in non-atomic mode
|
entailment
|
public function afterDelete(Event $event, EntityInterface $entity, ArrayObject $options)
{
if (!$this->config('status')) {
return;
}
if (!$options['atomic']) {
throw new FatalErrorException(__d('field', 'Entities in fieldable tables can only be deleted using transactions. Set [atomic = true]'));
}
if (!empty($this->_cache['afterDelete'])) {
foreach ((array)$this->_cache['afterDelete'] as $field) {
$field->afterDelete();
}
$this->_cache['afterDelete'] = [];
}
parent::afterDelete($event, $entity, $options);
}
|
After an entity was removed from database.
**NOTE:** This method automatically removes all field values from
`eav_values` database table for each entity.
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\Datasource\EntityInterface $entity The entity that was deleted
@param \ArrayObject $options Additional options given as an array
@throws \Cake\Error\FatalErrorException When using this behavior in non-atomic mode
@return void
|
entailment
|
public function attachEntityFields(EntityInterface $entity)
{
$_fields = [];
foreach ($this->_attributesForEntity($entity) as $attr) {
$field = $this->_prepareMockField($entity, $attr);
if ($entity->has($field->get('name'))) {
$this->_fetchPost($field);
}
$field->fieldAttached();
$_fields[] = $field;
}
$entity->set('_fields', new FieldCollection($_fields));
return $entity;
}
|
The method which actually fetches custom fields.
Fetches all Entity's fields under the `_fields` property.
@param \Cake\Datasource\EntityInterface $entity The entity where to fetch fields
@return \Cake\Datasource\EntityInterface
|
entailment
|
protected function _validation(EntityInterface $entity)
{
$validator = new Validator();
$hasErrors = false;
foreach ($this->_attributesForEntity($entity) as $attr) {
$field = $this->_prepareMockField($entity, $attr);
$result = $field->validate($validator);
if ($result === false) {
$this->attachEntityFields($entity);
return false;
}
$errors = $validator->errors($entity->toArray(), $entity->isNew());
$entity->errors($errors);
if (!empty($errors)) {
$hasErrors = true;
if ($entity->has('_fields')) {
$entityErrors = $entity->errors();
foreach ($entity->get('_fields') as $field) {
$postData = $entity->get($field->name);
if (!empty($entityErrors[$field->name])) {
$field->set('value', $postData);
$field->metadata->set('errors', (array)$entityErrors[$field->name]);
}
}
}
}
}
return !$hasErrors;
}
|
Triggers before/after validate events.
@param \Cake\Datasource\EntityInterface $entity The entity being validated
@return bool True if save operation should continue, false otherwise
|
entailment
|
protected function _fetchPost(Field $field)
{
$post = $field
->get('metadata')
->get('entity')
->get($field->get('name'));
// auto-magic
if (is_array($post)) {
$field->set('extra', $post);
$field->set('value', null);
} else {
$field->set('extra', null);
$field->set('value', $post);
}
return $post;
}
|
Alters the given $field and fetches incoming POST data, both "value" and
"extra" property will be automatically filled for the given $field entity.
@param \Field\Model\Entity\Field $field The field entity for which fetch POST information
@return mixed Raw POST information
|
entailment
|
protected function _attributesForEntity(EntityInterface $entity)
{
$bundle = $this->_resolveBundle($entity);
$attrs = $this->_toolbox->attributes($bundle);
$attrByIds = []; // attrs indexed by id
$attrByNames = []; // attrs indexed by name
foreach ($attrs as $name => $attr) {
$attrByNames[$name] = $attr;
$attrByIds[$attr->get('id')] = $attr;
$attr->set(':value', null);
}
if (!empty($attrByIds)) {
$instances = $this->Attributes->Instance
->find()
->where(['eav_attribute_id IN' => array_keys($attrByIds)])
->all();
foreach ($instances as $instance) {
if (!empty($attrByIds[$instance->get('eav_attribute_id')])) {
$attr = $attrByIds[$instance->get('eav_attribute_id')];
if (!$attr->has('instance')) {
$attr->set('instance', $instance);
}
}
}
}
$values = $this->_fetchValues($entity, array_keys($attrByNames));
foreach ($values as $value) {
if (!empty($attrByNames[$value->get('eav_attribute')->get('name')])) {
$attrByNames[$value->get('eav_attribute')->get('name')]->set(':value', $value);
}
}
return $this->_toolbox->attributes($bundle);
}
|
Gets all attributes that should be attached to the given entity, this entity
will be used as context to calculate the proper bundle.
@param \Cake\Datasource\EntityInterface $entity Entity context
@return array
|
entailment
|
protected function _fetchValues(EntityInterface $entity, array $attrNames = [])
{
$bundle = $this->_resolveBundle($entity);
$conditions = [
'EavAttribute.table_alias' => $this->_table->table(),
'EavValues.entity_id' => $entity->get((string)$this->_table->primaryKey()),
];
if ($bundle) {
$conditions['EavAttribute.bundle'] = $bundle;
}
if (!empty($attrNames)) {
$conditions['EavAttribute.name IN'] = $attrNames;
}
$storedValues = TableRegistry::get('Eav.EavValues')
->find()
->contain(['EavAttribute'])
->where($conditions)
->all();
return $storedValues;
}
|
Retrieves stored values for all virtual properties by name. This gets all
values at once.
This method is used to reduce the number of SQl queries, so we get all
values at once in a single Select instead of creating a select for every
field attached to the given entity.
@param \Cake\Datasource\EntityInterface $entity The entity for which get related values
@param array $attrNames List of attribute names for which get their values
@return \Cake\Datasource\ResultSetInterface
|
entailment
|
protected function _prepareMockField(EntityInterface $entity, EntityInterface $attribute)
{
$type = $this->_toolbox->mapType($attribute->get('type'));
if (!$attribute->has(':value')) {
$bundle = $this->_resolveBundle($entity);
$conditions = [
'EavAttribute.table_alias' => $this->_table->table(),
'EavAttribute.name' => $attribute->get('name'),
'EavValues.entity_id' => $entity->get((string)$this->_table->primaryKey()),
];
if ($bundle) {
$conditions['EavAttribute.bundle'] = $bundle;
}
$storedValue = TableRegistry::get('Eav.EavValues')
->find()
->contain(['EavAttribute'])
->select(['id', "value_{$type}", 'extra'])
->where($conditions)
->limit(1)
->first();
} else {
$storedValue = $attribute->get(':value');
}
$mockField = new Field([
'name' => $attribute->get('name'),
'label' => $attribute->get('instance')->get('label'),
'value' => null,
'extra' => null,
'metadata' => new Entity([
'value_id' => null,
'instance_id' => $attribute->get('instance')->get('id'),
'attribute_id' => $attribute->get('id'),
'entity_id' => $this->_toolbox->getEntityId($entity),
'table_alias' => $attribute->get('table_alias'),
'type' => $type,
'bundle' => $attribute->get('bundle'),
'handler' => $attribute->get('instance')->get('handler'),
'required' => $attribute->get('instance')->required,
'description' => $attribute->get('instance')->description,
'settings' => $attribute->get('instance')->settings,
'view_modes' => $attribute->get('instance')->view_modes,
'entity' => $entity,
'errors' => [],
]),
]);
if ($storedValue) {
$mockField->set('value', $this->_toolbox->marshal($storedValue->get("value_{$type}"), $type));
$mockField->set('extra', $storedValue->get('extra'));
$mockField->metadata->set('value_id', $storedValue->id);
}
$mockField->isNew($entity->isNew());
return $mockField;
}
|
Creates a new Virtual "Field" to be attached to the given entity.
This mock Field represents a new property (table column) of the entity.
@param \Cake\Datasource\EntityInterface $entity The entity where the
generated virtual field will be attached
@param \Cake\Datasource\EntityInterface $attribute The attribute where to get
the information when creating the mock field.
@return \Field\Model\Entity\Field
|
entailment
|
protected function _resolveBundle(EntityInterface $entity)
{
$bundle = $this->config('bundle');
if (is_callable($bundle)) {
$callable = $this->config('bundle');
$bundle = $callable($entity);
}
return (string)$bundle;
}
|
Resolves `bundle` name using $entity as context.
@param \Cake\Datasource\EntityInterface $entity Entity to use as context when resolving bundle
@return string Bundle name as string value, it may be an empty string if no bundle should be applied
|
entailment
|
public function render(Block $block, View $view)
{
$menuId = intval($block->settings['menu_id']);
$menu = TableRegistry::get('Menu.Menus')
->find()
->cache("info_{$menuId}", 'menus')
->where(['Menus.id' => $menuId])
->first();
if (!$menu) {
return '';
}
$links = TableRegistry::get('Menu.MenuLinks')
->find('threaded')
->cache("links_{$menuId}", 'menus')
->where(['menu_id' => $menuId])
->order(['lft' => 'ASC']);
$menu->set('links', $links);
$viewMode = $view->viewMode();
$blockRegion = isset($block->region->region) ? $block->region->region : 'none';
$cacheKey = "render_{$blockRegion}_{$viewMode}";
$cache = static::cache($cacheKey);
$element = 'Menu.render_menu';
if ($cache !== null) {
$element = $cache;
} else {
$try = [
"Menu.render_menu_{$blockRegion}_{$viewMode}",
"Menu.render_menu_{$blockRegion}",
'Menu.render_menu'
];
foreach ($try as $possible) {
if ($view->elementExists($possible)) {
$element = static::cache($cacheKey, $possible);
break;
}
}
}
return $view->element($element, compact('menu'));
}
|
{@inheritDoc}
Renders menu's associated block.
This method will look for certain view elements when rendering each menu, if
one of this elements is not present it'll look the next one, and so on. These
view elements should be defined by Themes by placing them in
`<MyTheme>/Template/Element`.
### Render menu based on theme's region & view-mode
render_menu_[region-name]_[view-mode].ctp
Renders the given block based on theme's `region-name` and `view-mode`, for
example:
- `render_menu_left-sidebar_full.ctp`: Render for menus in `left-sidebar`
region when view-mode is `full`.
- `render_menu_left-sidebar_search-result.ctp`: Render for menus in
`left-sidebar` region when view-mode is `search-result`
- `render_menu_footer_search-result.ctp`: Render for menus in `footer` region
when view-mode is `search-result`.
### Render menu based on theme's region
render_menu_[region-name].ctp
Similar as before, but based only on theme's `region` (and any view-mode), for
example:
- `render_menu_right-sidebar.ctp`: Render for menus in `right-sidebar`
region.
- `render_menu_left-sidebar.ctp`: Render for menus in `left-sidebar`
region.
### Default
render_block.ctp
This is the default render, if none of the above is found we try to use this
last. Themes can overwrite this view element by creating a new one
at `ExampleTheme/Template/Element/render_block.ctp`.
---
NOTE: Please note the difference between "_" and "-"
|
entailment
|
public function edit(Field $field, View $view)
{
$terms = [];
if ($field->metadata->settings['vocabulary']) {
$TermsTable = TableRegistry::get('Taxonomy.Terms');
$TermsTable->removeBehavior('Tree');
$TermsTable->addBehavior('Tree', [
'scope' => [
'vocabulary_id' => $field->metadata->settings['vocabulary']
]
]);
$terms = $TermsTable->find('treeList', ['spacer' => ' ']);
}
return $view->element('Taxonomy.taxonomy_field_edit', compact('field', 'terms'));
}
|
{@inheritDoc}
|
entailment
|
public function validate(Field $field, Validator $validator)
{
if ($field->metadata->required) {
$validator->notEmpty($field->name, __d('taxonomy', 'Field required.'), true);
} else {
$validator->allowEmpty($field->name, true);
}
if (intval($field->metadata->settings['max_values']) > 0) {
if (!empty($field->metadata->settings['error_message'])) {
$limitErrorMessage = $field->metadata->settings['error_message'];
} else {
$limitErrorMessage = __d('taxonomy', 'You can select {0,number} values as maximum.', $field->metadata->settings['max_values']);
}
$validator
->add($field->name, 'validateLimit', [
'rule' => function ($value, $context) use ($field) {
if (!is_array($value)) {
$value = explode(',', (string)$value);
}
return count($value) <= $field->metadata->settings['max_values'];
},
'message' => $limitErrorMessage,
]);
}
return true;
}
|
{@inheritDoc}
|
entailment
|
public function beforeSave(Field $field, $post)
{
if (!$field->metadata->settings['vocabulary']) {
return true;
}
$TermsTable = TableRegistry::get('Taxonomy.Terms');
if ($field->metadata->settings['type'] === 'autocomplete') {
$termIds = explode(',', (string)$post);
$TermsTable->removeBehavior('Tree');
$TermsTable->addBehavior('Tree', [
'scope' => [
'vocabulary_id' => $field->metadata->settings['vocabulary']
]
]);
// any non-integer value represents a new term to be registered
foreach ($termIds as $i => $idOrName) {
if (!intval($idOrName)) {
$alreadyExists = $TermsTable->find()
->where(['name' => $idOrName])
->first();
if ($alreadyExists) {
$termIds[$i] = $alreadyExists->id;
} else {
$termEntity = $TermsTable->newEntity([
'name' => $idOrName,
'vocabulary_id' => $field->metadata->settings['vocabulary'],
]);
if ($TermsTable->save($termEntity)) {
$termIds[$i] = $termEntity->id;
} else {
unset($termIds[$i]);
}
}
}
}
$field->set('extra', array_unique($termIds));
} else {
// single value given (radio)
if (!is_array($post)) {
$post = [$post];
}
$field->set('extra', array_unique($post));
}
$ids = empty($field->extra) ? [-1] : $field->extra;
$termsNames = $TermsTable
->find()
->select(['name'])
->where(['id IN' => $ids])
->all()
->extract('name')
->toArray();
$field->set('value', implode(' ', $termsNames));
return true;
}
|
{@inheritDoc}
|
entailment
|
public function afterSave(Field $field)
{
$entity = $field->get('metadata')->get('entity');
$table = TableRegistry::get($entity->source());
$pk = $table->primaryKey();
if ($entity->has($pk)) {
$tableAlias = Inflector::underscore($table->alias());
$extra = !is_array($field->extra) ? [$field->extra] : $field->extra;
TableRegistry::get('Taxonomy.EntitiesTerms')->deleteAll([
'entity_id' => $entity->get($pk),
'table_alias' => $tableAlias,
'field_instance_id' => $field->metadata->instance_id,
]);
foreach ($extra as $termId) {
Cache::delete("t{$termId}", 'terms_count');
$link = TableRegistry::get('Taxonomy.EntitiesTerms')
->newEntity([
'entity_id' => $entity->get($pk),
'term_id' => $termId,
'table_alias' => $tableAlias,
'field_instance_id' => $field->metadata->instance_id,
]);
TableRegistry::get('Taxonomy.EntitiesTerms')->save($link);
}
}
}
|
{@inheritDoc}
|
entailment
|
public function settings(FieldInstance $instance, View $view)
{
$vocabularies = TableRegistry::get('Taxonomy.Vocabularies')->find('list');
return $view->element('Taxonomy.taxonomy_field_settings_form', compact('instance', 'vocabularies'));
}
|
{@inheritDoc}
|
entailment
|
protected function _dirname($path) {
$newpath = preg_replace("/\/$/", "", $path);
$dn = substr($path, 0, strrpos($newpath, '/')) ;
if (substr($dn, 0, 1) != '/') {
$dn = "/$dn";
}
return $dn;
}
|
Return parent directory path
@param string $path file path
@return string
@author Dmitry (dio) Levashov
|
entailment
|
protected function _normpath($path) {
$tmp = preg_replace("/^\//", "", $path);
$tmp = preg_replace("/\/\//", "/", $tmp);
$tmp = preg_replace("/\/$/", "", $tmp);
return $tmp;
}
|
Return normalized path, this works the same as os.path.normpath() in Python
@param string $path path
@return string
@author Troex Nevelin
|
entailment
|
protected function _relpath($path) {
$newpath = $path;
if (substr($path, 0, 1) != '/') {
$newpath = "/$newpath";
}
$newpath = preg_replace("/\/$/", "", $newpath);
$ret = ($newpath == $this->root) ? '' : substr($newpath, strlen($this->root)+1);
return $ret;
}
|
Return file path related to root dir
@param string $path file path
@return string
@author Dmitry (dio) Levashov
|
entailment
|
protected function metaobj2array($metadata) {
$arr = array();
if (is_array($metadata)) {
foreach ($metadata as $meta) {
$arr[$meta->Name] = $meta->Value;
}
} else {
$arr[$metadata->Name] = $metadata->Value;
}
return $arr;
}
|
Converting array of objects with name and value properties to
array[key] = value
@param array $metadata source array
@return array
@author Alexey Sukhotin
|
entailment
|
protected function _stat($path) {
$stat = array(
'size' => 0,
'ts' => time(),
'read' => true,
'write' => true,
'locked' => false,
'hidden' => false,
'mime' => 'directory',
);
if ($this->root == $path) {
return $stat;
}
$np = $this->_normpath($path);
try {
$obj = $this->s3->GetObject(array('Bucket' => $this->options['bucket'], 'Key' => $np , 'GetMetadata' => true, 'InlineData' => false, 'GetData' => false));
} catch (Exception $e) {
}
if (!isset($obj) || ($obj->GetObjectResponse->Status->Code != 200)) {
$np .= '/';
try {
$obj = $this->s3->GetObject(array('Bucket' => $this->options['bucket'], 'Key' => $np , 'GetMetadata' => true, 'InlineData' => false, 'GetData' => false));
} catch (Exception $e) {
}
}
if (!(isset($obj) && $obj->GetObjectResponse->Status->Code == 200)) {
return array();
}
$mime = '';
$metadata = $this->metaobj2array($obj->GetObjectResponse->Metadata);
$mime = $metadata['Content-Type'];
if (!empty($mime)) {
$stat['mime'] = ($mime == 'binary/octet-stream') ? 'directory' : $mime;
}
if (isset($obj->GetObjectResponse->LastModified)) {
$stat['ts'] = strtotime($obj->GetObjectResponse->LastModified);
}
try {
$files = $this->s3->ListBucket(array('Bucket' => $this->options['bucket'], 'Prefix' => $np, 'Delimiter' => '/'))->ListBucketResponse->Contents;
} catch (Exception $e) {
}
if (!is_array($files)) {
$files = array($files);
}
foreach ($files as $file) {
if ($file->Key == $np) {
$stat['size'] = $file->Size;
}
}
return $stat;
}
|
Return stat for given path.
Stat contains following fields:
- (int) size file size in b. required
- (int) ts file modification time in unix time. required
- (string) mime mimetype. required for folders, others - optionally
- (bool) read read permissions. required
- (bool) write write permissions. required
- (bool) locked is object locked. optionally
- (bool) hidden is object hidden. optionally
- (string) alias for symlinks - link target path relative to root path. optionally
- (string) target for symlinks - link target path. optionally
If file does not exists - returns empty array or false.
@param string $path file path
@return array|false
@author Dmitry (dio) Levashov,
@author Alexey Sukhotin
|
entailment
|
protected function _subdirs($path) {
$stat = $this->_stat($path);
if ($stat['mime'] == 'directory') {
$files = $this->_scandir($path);
foreach ($files as $file) {
$fstat = $this->_stat($file);
if ($fstat['mime'] == 'directory') {
return true;
}
}
}
return false;
}
|
Return true if path is dir and has at least one childs directory
@param string $path dir path
@return bool
@author Alexey Sukhotin
|
entailment
|
protected function _scandir($path) {
$s3path = preg_replace("/^\//", "", $path) . '/';
$files = $this->s3->ListBucket(array('Bucket' => $this->options['bucket'], 'delimiter' => '/', 'Prefix' => $s3path))->ListBucketResponse->Contents;
$finalfiles = array();
foreach ($files as $file) {
if (preg_match("|^" . $s3path . "[^/]*/?$|", $file->Key)) {
$fname = preg_replace("/\/$/", "", $file->Key);
$fname = $file->Key;
if ($fname != preg_replace("/\/$/", "", $s3path)) {
}
$finalfiles[] = $fname;
}
}
sort($finalfiles);
return $finalfiles;
}
|
Return files list in directory
@param string $path dir path
@return array
@author Dmitry (dio) Levashov,
@author Alexey Sukhotin
|
entailment
|
protected function _fopen($path, $mode="rb") {
$tn = $this->getTempFile($path);
$fp = $this->tmbPath
? @fopen($tn, 'w+')
: @tmpfile();
if ($fp) {
try {
$obj = $this->s3->GetObject(array('Bucket' => $this->options['bucket'], 'Key' => $this->_normpath($path) , 'GetMetadata' => true, 'InlineData' => true, 'GetData' => true));
} catch (Exception $e) {
}
$mime = '';
$metadata = $this->metaobj2array($obj->GetObjectResponse->Metadata);
fwrite($fp, $obj->GetObjectResponse->Data);
rewind($fp);
return $fp;
}
return false;
}
|
Open file and return file pointer
@param string $path file path
@param bool $write open file for writing
@return resource|false
@author Dmitry (dio) Levashov,
@author Alexey Sukhotin
|
entailment
|
protected function _mkdir($path, $name) {
$newkey = $this->_normpath($path);
$newkey = preg_replace("/\/$/", "", $newkey);
$newkey = "$newkey/$name/";
try {
$obj = $this->s3->PutObjectInline(array('Bucket' => $this->options['bucket'], 'Key' => $newkey , 'ContentLength' => 0, 'Data' => ''));
} catch (Exception $e) {
}
if (isset($obj)) {
return "$path/$name";
}
return false;
}
|
Create dir and return created dir path or false on failed
@param string $path parent dir path
@param string $name new directory name
@return string|bool
@author Dmitry (dio) Levashov,
@author Alexey Sukhotin
|
entailment
|
protected function _unlink($path) {
$newkey = $this->_normpath($path);
$newkey = preg_replace("/\/$/", "", $newkey);
try {
$obj = $this->s3->DeleteObject(array('Bucket' => $this->options['bucket'], 'Key' => $newkey));
} catch (Exception $e) {
}
/*$fp = fopen('/tmp/eltest.txt','a+');
fwrite($fp, 'key='.$newkey);*/
if (is_object($obj)) {
//fwrite($fp, 'obj='.var_export($obj,true));
if (isset($obj->DeleteObjectResponse->Code)) {
$rc = $obj->DeleteObjectResponse->Code;
if (substr($rc, 0, 1) == '2') {
return true;
}
}
}
//fclose($fp);
return false;
}
|
Remove file
@param string $path file path
@return bool
@author Dmitry (dio) Levashov
|
entailment
|
protected function sign($operation) {
$params = array(
'AWSAccessKeyId' => $this->accesskey,
'Timestamp' => gmdate('Y-m-d\TH:i:s.000\Z'),
);
$sign_str = 'AmazonS3' . $operation . $params['Timestamp'];
$params['Signature'] = base64_encode(hash_hmac('sha1', $sign_str, $this->secretkey, TRUE));
return $params;
}
|
Generating signature and timestamp for specified S3 operation
@param string $operation S3 operation name
@return array
@author Alexey Sukhotin
|
entailment
|
public function authenticate(Request $request, Response $response)
{
$result = parent::authenticate($request, $response);
if (!$result) {
// fail? try using "username" as "email"
$this->_config['fields']['username'] = 'email';
if (!empty($request->data['username'])) {
$request->data['email'] = $request->data['username'];
}
$result = parent::authenticate($request, $response);
}
if ($result && !empty($request->data['remember'])) {
$controller = $this->_registry->getController();
if (empty($controller->Cookie)) {
$controller->loadComponent('Cookie');
}
// user information array
$user = json_encode($result);
// used to check that user's info array is authentic
$hash = Security::hash($user, 'sha1', true);
$controller->Cookie->write('User.Cookie', json_encode(compact('user', 'hash')));
}
return $result;
}
|
{@inheritDoc}
|
entailment
|
public function logout(Event $event, array $user)
{
$controller = $this->_registry->getController();
if (empty($controller->Cookie)) {
$controller->loadComponent('Cookie');
}
$controller->Cookie->delete('User.Cookie');
}
|
Removes "remember me" cookie.
@param array $event User information given as an array
@return void
|
entailment
|
public function shortcodeRandom(Event $event, array $atts, $content, $tag)
{
if (strpos($content, ',') === false) {
return '';
}
$elements = explode(',', trim($content));
$elements = array_map('trim', $elements);
$c = count($elements);
if ($c == 2 && is_numeric($elements[0]) && is_numeric($elements[1])) {
return rand($elements[0], $elements[1]);
}
return $elements[array_rand($elements)];
}
|
Implements the "random" shortcode.
{random}1,2,3{/random}
@param \Cake\Event\Event $event The event that was fired
@param array $atts An associative array of attributes, or an empty string if
no attributes are given
@param string $content The enclosed content (if the shortcode is used in its
enclosing form)
@param string $tag The shortcode tag
@return string
|
entailment
|
public function shortcodeTranslate(Event $event, array $atts, $content, $tag)
{
if (!empty($atts['domain'])) {
return __d($atts['domain'], $content);
} else {
return __($content);
}
}
|
Implements the "t" shortcode.
{t}Text for translate{/t}
@param \Cake\Event\Event $event The event that was fired
@param array $atts An associative array of attributes, or an empty string if
no attributes are given
@param string $content The enclosed content (if the shortcode is used in its
enclosing form)
@param string $tag The shortcode tag
@return string
|
entailment
|
public function shortcodeUrl(Event $event, array $atts, $content, $tag)
{
try {
$url = Router::url($content, true);
} catch (\Exception $e) {
$url = '';
}
return $url;
}
|
Implements the "url" shortcode.
{url}/some/url/on/my/site{/url}
@param \Cake\Event\Event $event The event that was fired
@param array $atts An associative array of attributes, or an empty string if
no attributes are given
@param string $content The enclosed content (if the shortcode is used in its
enclosing form)
@param string $tag The shortcode tag
@return string
|
entailment
|
public function shortcodeDate(Event $event, array $atts, $content, $tag)
{
if (!empty($atts['format']) && !empty($content)) {
if (is_numeric($content)) {
return date($atts['format'], $content);
} else {
return date($atts['format'], strtotime($content));
}
}
return '';
}
|
Implements the "date" shortcode.
{date format=d-m-Y}2014-05-06{/date}
@param \Cake\Event\Event $event The event that was fired
@param array $atts An associative array of attributes, or an empty string if
no attributes are given
@param string $content The enclosed content (if the shortcode is used in its
enclosing form)
@param string $tag The shortcode tag
@return string
|
entailment
|
public function shortcodeLocale(Event $event, array $atts, $content, $tag)
{
$option = array_keys((array)$atts);
$locale = I18n::locale();
$languages = quickapps('languages');
$out = '';
if (!isset($languages[$locale])) {
return $out;
}
if (empty($option)) {
$option = 'code';
} else {
$option = $option[0];
}
if ($info = $languages[$locale]) {
switch ($option) {
case 'code':
$out = $info['code'];
break;
case 'name':
$out = $info['name'];
break;
case 'direction':
$out = $info['direction'];
break;
}
}
return $out;
}
|
Implements the "locale" shortcode.
{locale code /}
{locale name /}
{locale direction /}
@param \Cake\Event\Event $event The event that was fired
@param array $atts An associative array of attributes, or an empty string if
no attributes are given
@param string $content The enclosed content (if the shortcode is used in its
enclosing form)
@param string $tag The shortcode tag
@return string
|
entailment
|
protected function _getTitle()
{
if ($this->_getIsPlugin()) {
try {
return plugin($this->alias)->humanName;
} catch (\Exception $e) {
return $this->alias;
}
}
return $this->alias;
}
|
For usage as part of MenuHelper.
@return string
|
entailment
|
protected function _awaitingPlugins($type = 'plugin')
{
$type = !in_array($type, ['plugin', 'theme']) ? 'plugin' : $type;
$ignoreThemes = $type === 'plugin';
$plugins = Plugin::scan($ignoreThemes);
foreach ($plugins as $name => $path) {
if (Plugin::exists($name) ||
($type == 'theme' && !str_ends_with($name, 'Theme'))
) {
unset($plugins[$name]);
}
}
if (!empty($plugins)) {
$this->Flash->set(__d('system', '{0} are awaiting for installation', ($type == 'plugin' ? __d('system', 'Some plugins') : __d('system', 'Some themes'))), [
'element' => 'System.stashed_plugins',
'params' => compact('plugins'),
]);
}
}
|
Look for plugin/themes awaiting for installation and sets a flash message
with instructions about how to proceed.
@param string $type Possible values `plugin` (default) or `theme`, defaults
to "plugin"
@return void
|
entailment
|
public static function adapter($name = null, array $config = [])
{
$class = null;
if ($name === null) {
$default = (string)plugin('Captcha')->settings('default_adapter');
if (!empty($default)) {
return static::adapter($default, $config);
}
$class = end(static::$_adapters);
} elseif (isset(static::$_adapters[$name])) {
$class = static::$_adapters[$name];
}
if (empty($config)) {
$config = (array)plugin('Captcha')->settings($name);
}
if (is_string($class) && class_exists($class)) {
$class = new $class($config);
$created = true;
}
if ($class instanceof BaseAdapter) {
if (!isset($created)) {
$class->config($config);
}
return $class;
}
throw new AdapterNotFoundException(__d('captcha', 'The captcha adapter "{0}" was not found.'), $name);
}
|
Gets an instance of the given adapter name (or default adapter if not given).
@param string|null $name Name of the adapter, or null to use default adapter
selected in Captcha plugin's setting page. The latest registered adapter
will be used if no default adapter has been selected yet
@param array $config Options to be passed to Adapter's `config()` method, if
not given it will try to get such parameters from Captcha plugin's settings
@return \Captcha\Adapter\BaseAdapter
@throws \Captcha\Error\AdapterNotFoundException When no adapter was found
|
entailment
|
public function beforeDispatch(Event $event)
{
parent::beforeDispatch($event);
$request = Router::getRequest();
if (empty($request)) {
throw new InternalErrorException(__d('cms', 'No request object could be found.'));
}
$locales = array_keys(quickapps('languages'));
$localesPattern = '(' . implode('|', array_map('preg_quote', $locales)) . ')';
$rawUrl = str_replace_once($request->base, '', env('REQUEST_URI'));
$normalizedURL = str_replace('//', '/', "/{$rawUrl}");
if (!empty($request->query['locale']) && in_array($request->query['locale'], $locales)) {
$request->session()->write('locale', $request->query['locale']);
I18n::locale($request->session()->read('locale'));
} elseif (option('url_locale_prefix') && preg_match("/\/{$localesPattern}\//", $normalizedURL, $matches)) {
I18n::locale($matches[1]);
} elseif ($request->session()->check('locale') && in_array($request->session()->read('locale'), $locales)) {
I18n::locale($request->session()->read('locale'));
} elseif ($request->is('userLoggedIn') && in_array(user()->locale, $locales)) {
I18n::locale(user()->locale);
} elseif (in_array(option('default_language'), $locales)) {
I18n::locale(option('default_language'));
} else {
I18n::locale(CORE_LOCALE);
}
if (option('url_locale_prefix') &&
!$request->is('home') &&
!preg_match("/\/{$localesPattern}\//", $normalizedURL)
) {
$url = Router::url('/' . I18n::locale() . $normalizedURL, true);
http_response_code(303);
header("Location: {$url}");
die;
}
}
|
Prepares the default language to use by the script.
### Detection Methods
This method applies the following detection methods when looking for
language to use:
- GET parameter: If `locale` GET parameter is present in current request, and
if it's a valid language code, then will be used as current language and
also will be persisted on `locale` session for further use.
- URL: If current URL is prefixed with a valid language code and
`url_locale_prefix` option is enabled, URL's language code will be used.
- Locale session: If `locale` session exists it will be used.
- User session: If user is logged in and has selected a valid preferred
language it will be used.
- Default: Site's language will be used otherwise.
### Locale Prefix
If `url_locale_prefix` option is enabled, and current request's URL is not
language prefixed, user will be redirected to a locale-prefixed version of
the requested URL (using the language code selected as explained above).
For example:
/article/demo-article.html
Might redirects to:
/en_US/article/demo-article.html
@param \Cake\Event\Event $event containing the request, response and
additional parameters
@return void
@throws \Cake\Network\Exception\InternalErrorException When no valid request
object could be found
|
entailment
|
public function send()
{
$this
->subject(plugin('User')->settings['message_blocked_subject'])
->body(plugin('User')->settings['message_blocked_body']);
if (plugin('User')->settings['message_blocked']) {
return parent::send();
}
return true;
}
|
{@inheritDoc}
|
entailment
|
protected function _getType()
{
$name = __d('content', '(unknown)');
if ($this->has('content_type') && $this->get('content_type')->has('name')) {
$name = $this->get('content_type')->get('name');
}
return $name;
}
|
Gets content type.
As Content Types are not dependent of Contents (deleting a content_type won't
remove all contents of that type). Some times we found contents without
`content_type`, in that cases, if no content_type is found `--unknow--` will
be returned.
@return string
|
entailment
|
protected function _getUrl()
{
$url = Router::getRequest()->base;
if (option('url_locale_prefix')) {
$url .= '/' . I18n::locale();
}
$url .= "/{$this->content_type_slug}/{$this->slug}";
return Router::normalize($url) . CONTENT_EXTENSION;
}
|
Gets content's details page URL.
Content's details URL's follows the syntax below:
http://example.com/{content-type-slug}/{content-slug}{CONTENT_EXTENSION}
Example:
http://example.com/blog-article/my-first-article.html
@return string
|
entailment
|
protected function _getAuthor()
{
if ($this->created_by instanceof User) {
return $this->created_by;
}
return new User([
'username' => __d('content', 'unknown'),
'name' => __d('content', 'Unknown'),
'web' => __d('content', '(no website)'),
'email' => __d('content', 'Unknown'),
]);
}
|
Gets content's author as an User entity.
@return \User\Model\Entity\User
|
entailment
|
public function parent()
{
if (!$this->has('slug')) {
throw new FatalErrorException(__d('content', "Missing property 'slug', make sure to include it using Query::select()."));
}
return TableRegistry::get('Content.Contents')
->find()
->select(['id', 'slug', 'content_type_slug', 'language'])
->where([
'id' => $this->translation_for,
'status' => 1,
])
->first();
}
|
Gets the parent content for which this content is a translation of.
@return mixed The parent content if exists, null otherwise
|
entailment
|
public function translation($locale = null)
{
if (!$this->has('id') || !$this->has('content_type_slug')) {
throw new FatalErrorException(__d('content', "Missing properties 'id' or 'content_type_slug', make sure to include them using Query::select()."));
}
if ($locale === null) {
$locale = I18n::locale();
}
return TableRegistry::get('Content.Contents')
->find()
->select(['id', 'slug', 'content_type_slug', 'language'])
->where([
'translation_for' => $this->id,
'language' => $locale,
'status' => 1,
])
->first();
}
|
Find if this content has a translation to the given locale code.
@param string|null $locale Locale code for which look for translations,
if not given current language code will be used
@return mixed Translation entity if exists, null otherwise
@throws Cake\Error\FatalErrorException When if any of the required
properties is not present in this entity
|
entailment
|
public function setDefaults($type = false)
{
if (!$type) {
if (!$this->has('content_type_slug') && !$this->has('id')) {
throw new FatalErrorException(__d('content', 'Unable to get Content-Type information.'));
}
if (!$this->has('content_type_slug')) {
$contentTypeSlug = TableRegistry::get('Content.Contents')->find()
->select(['content_type_slug'])
->where(['id' => $this->get('id')])
->first();
$contentTypeSlug = $contentTypeSlug->content_type_slug;
} else {
$contentTypeSlug = $this->get('content_type_slug');
}
$type = TableRegistry::get('Content.ContentTypes')->find()
->where(['slug' => $contentTypeSlug])
->first();
}
if (!($type instanceof ContentType) || !$type->has('defaults')) {
throw new FatalErrorException(__d('content', "Content::setDefaults() was unable to get Content Type defaults values."));
}
$this->set('language', $type->defaults['language']);
$this->set('comment_status', $type->defaults['comment_status']);
$this->set('status', $type->defaults['status']);
$this->set('promote', $type->defaults['promote']);
$this->set('sticky', $type->defaults['sticky']);
}
|
Set defaults content settings based on parent content type.
You can provide a ContentType entity to fetch defaults values. By default if
none is provided it automatically fetches the information from the
corresponding Content Type.
@param bool|\Content\Model\Entity\ContentType $type False for auto fetch or a
ContentType entity to extract information from
@return void
@throws Cake\Error\FatalErrorException When content type was not found for
this content content.
|
entailment
|
public function operatorTerm(Event $event, $query, $token)
{
$slugs = explode(',', $token->value());
$slugs = array_slice($slugs, 0, 10);
if (!empty($slugs)) {
$IN = $token->negated() ? 'NOT IN' : 'IN';
$table = $event->subject();
$pk = $table->primaryKey();
$tableAlias = $table->alias();
$termsIds = TableRegistry::get('Taxonomy.Terms')
->find()
->select(['id'])
->where(['Terms.slug IN' => $slugs])
->all()
->extract('id')
->toArray();
$termsIds = empty($termsIds) ? [0] : $termsIds;
$subQuery = TableRegistry::get('Taxonomy.EntitiesTerms')
->find()
->select(['entity_id'])
->where(['term_id IN' => $termsIds, 'table_alias' => $tableAlias]);
if ($token->where() === 'or') {
$query->orWhere(["{$tableAlias}.{$pk} {$IN}" => $subQuery]);
} elseif ($token->where() === 'and') {
$query->andWhere(["{$tableAlias}.{$pk} {$IN}" => $subQuery]);
} else {
$query->where(["{$tableAlias}.{$pk} {$IN}" => $subQuery]);
}
}
return $query;
}
|
Handles the "term:" search operator. Which filters all entities matching
a given collection of terms.
term:cat,dog,bird,...,term-slug
You can provide up to 10 terms as maximum.
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\ORM\Query $query The query being scoped
@param \Search\Token $token Operator token
@return \Cake\ORM\Query Scoped query
|
entailment
|
public function bind($cmd, $handler) {
$allCmds = array_keys($this->commands);
$cmds = array();
foreach(explode(' ', $cmd) as $_cmd) {
if ($_cmd !== '') {
if ($all = strpos($_cmd, '*') !== false) {
list(, $sub) = array_pad(explode('.', $_cmd), 2, '');
if ($sub) {
$sub = str_replace('\'', '\\\'', $sub);
$addSub = create_function('$cmd', 'return $cmd . \'.\' . trim(\'' . $sub . '\');');
$cmds = array_merge($cmds, array_map($addSub, $allCmds));
} else {
$cmds = array_merge($cmds, $allCmds);
}
} else {
$cmds[] = $_cmd;
}
}
}
$cmds = array_unique($cmds);
foreach ($cmds as $cmd) {
if (!isset($this->listeners[$cmd])) {
$this->listeners[$cmd] = array();
}
if (is_callable($handler)) {
$this->listeners[$cmd][] = $handler;
}
}
return $this;
}
|
Add handler to elFinder command
@param string command name
@param string|array callback name or array(object, method)
@return elFinder
@author Dmitry (dio) Levashov
|
entailment
|
public function unbind($cmd, $handler) {
if (!empty($this->listeners[$cmd])) {
foreach ($this->listeners[$cmd] as $i => $h) {
if ($h === $handler) {
unset($this->listeners[$cmd][$i]);
return $this;
}
}
}
return $this;
}
|
Remove event (command exec) handler
@param string command name
@param string|array callback name or array(object, method)
@return elFinder
@author Dmitry (dio) Levashov
|
entailment
|
public function commandExists($cmd) {
return $this->loaded && isset($this->commands[$cmd]) && method_exists($this, $cmd);
}
|
Return true if command exists
@param string command name
@return bool
@author Dmitry (dio) Levashov
|
entailment
|
public function realpath($hash) {
if (($volume = $this->volume($hash)) == false) {
return false;
}
return $volume->realpath($hash);
}
|
Return file real path
@param string $hash file hash
@return string
@author Dmitry (dio) Levashov
|
entailment
|
protected function getNetVolumes() {
return isset($_SESSION[$this->netVolumesSessionKey]) && is_array($_SESSION[$this->netVolumesSessionKey]) ? $_SESSION[$this->netVolumesSessionKey] : array();
}
|
Return network volumes config.
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function getPluginInstance($name, $opts = array()) {
$key = strtolower($name);
if (! isset($this->plugins[$key])) {
$p_file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $name . DIRECTORY_SEPARATOR . 'plugin.php';
if (is_file($p_file)) {
require_once $p_file;
$class = 'elFinderPlugin' . $name;
$this->plugins[$key] = new $class($opts);
} else {
$this->plugins[$key] = false;
}
}
return $this->plugins[$key];
}
|
Get plugin instance & set to $this->plugins
@param string $name Plugin name (dirctory name)
@param array $opts Plugin options (optional)
@return object | bool Plugin object instance Or false
@author Naoki Sawada
|
entailment
|
public function error() {
$errors = array();
foreach (func_get_args() as $msg) {
if (is_array($msg)) {
$errors = array_merge($errors, $msg);
} else {
$errors[] = $msg;
}
}
return count($errors) ? $errors : array(self::ERROR_UNKNOWN);
}
|
Normalize error messages
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function ls($args) {
$target = $args['target'];
if (($volume = $this->volume($target)) == false
|| ($list = $volume->ls($target)) === false) {
return array('error' => $this->error(self::ERROR_OPEN, '#'.$target));
}
return array('list' => $list);
}
|
Return dir files names list
@param array command arguments
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function tree($args) {
$target = $args['target'];
if (($volume = $this->volume($target)) == false
|| ($tree = $volume->tree($target)) == false) {
return array('error' => $this->error(self::ERROR_OPEN, '#'.$target));
}
return array('tree' => $tree);
}
|
Return subdirs for required directory
@param array command arguments
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function tmb($args) {
$result = array('images' => array());
$targets = $args['targets'];
foreach ($targets as $target) {
if (($volume = $this->volume($target)) != false
&& (($tmb = $volume->tmb($target)) != false)) {
$result['images'][$target] = $tmb;
}
}
return $result;
}
|
Return new created thumbnails list
@param array command arguments
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function file($args) {
$target = $args['target'];
$download = !empty($args['download']);
$h403 = 'HTTP/1.x 403 Access Denied';
$h404 = 'HTTP/1.x 404 Not Found';
if (($volume = $this->volume($target)) == false) {
return array('error' => 'File not found', 'header' => $h404, 'raw' => true);
}
if (($file = $volume->file($target)) == false) {
return array('error' => 'File not found', 'header' => $h404, 'raw' => true);
}
if (!$file['read']) {
return array('error' => 'Access denied', 'header' => $h403, 'raw' => true);
}
if (($fp = $volume->open($target)) == false) {
return array('error' => 'File not found', 'header' => $h404, 'raw' => true);
}
if ($download) {
$disp = 'attachment';
$mime = 'application/force-download';
} else {
$disp = preg_match('/^(image|text)/i', $file['mime']) || $file['mime'] == 'application/x-shockwave-flash'
? 'inline'
: 'attachment';
$mime = $file['mime'];
}
$filenameEncoded = rawurlencode($file['name']);
if (strpos($filenameEncoded, '%') === false) { // ASCII only
$filename = 'filename="'.$file['name'].'"';
} else {
$ua = $_SERVER["HTTP_USER_AGENT"];
if (preg_match('/MSIE [4-8]/', $ua)) { // IE < 9 do not support RFC 6266 (RFC 2231/RFC 5987)
$filename = 'filename="'.$filenameEncoded.'"';
} elseif (strpos($ua, 'Chrome') === false && strpos($ua, 'Safari') !== false) { // Safari
$filename = 'filename="'.str_replace('"', '', $file['name']).'"';
} else { // RFC 6266 (RFC 2231/RFC 5987)
$filename = 'filename*=UTF-8\'\''.$filenameEncoded;
}
}
$result = array(
'volume' => $volume,
'pointer' => $fp,
'info' => $file,
'header' => array(
'Content-Type: '.$mime,
'Content-Disposition: '.$disp.'; '.$filename,
'Content-Location: '.$file['name'],
'Content-Transfer-Encoding: binary',
'Content-Length: '.$file['size'],
'Connection: close'
)
);
return $result;
}
|
Required to output file in browser when volume URL is not set
Return array contains opened file pointer, root itself and required headers
@param array command arguments
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function size($args) {
$size = 0;
foreach ($args['targets'] as $target) {
if (($volume = $this->volume($target)) == false
|| ($file = $volume->file($target)) == false
|| !$file['read']) {
return array('error' => $this->error(self::ERROR_OPEN, '#'.$target));
}
$size += $volume->size($target);
}
return array('size' => $size);
}
|
Count total files size
@param array command arguments
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function mkdir($args) {
$target = $args['target'];
$name = $args['name'];
if (($volume = $this->volume($target)) == false) {
return array('error' => $this->error(self::ERROR_MKDIR, $name, self::ERROR_TRGDIR_NOT_FOUND, '#'.$target));
}
return ($dir = $volume->mkdir($target, $name)) == false
? array('error' => $this->error(self::ERROR_MKDIR, $name, $volume->error()))
: array('added' => array($dir));
}
|
Create directory
@param array command arguments
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function mkfile($args) {
$target = $args['target'];
$name = $args['name'];
if (($volume = $this->volume($target)) == false) {
return array('error' => $this->error(self::ERROR_MKFILE, $name, self::ERROR_TRGDIR_NOT_FOUND, '#'.$target));
}
return ($file = $volume->mkfile($target, $args['name'])) == false
? array('error' => $this->error(self::ERROR_MKFILE, $name, $volume->error()))
: array('added' => array($file));
}
|
Create empty file
@param array command arguments
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function rename($args) {
$target = $args['target'];
$name = $args['name'];
if (($volume = $this->volume($target)) == false
|| ($rm = $volume->file($target)) == false) {
return array('error' => $this->error(self::ERROR_RENAME, '#'.$target, self::ERROR_FILE_NOT_FOUND));
}
$rm['realpath'] = $volume->realpath($target);
return ($file = $volume->rename($target, $name)) == false
? array('error' => $this->error(self::ERROR_RENAME, $rm['name'], $volume->error()))
: array('added' => array($file), 'removed' => array($rm));
}
|
Rename file
@param array $args
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function duplicate($args) {
$targets = is_array($args['targets']) ? $args['targets'] : array();
$result = array('added' => array());
$suffix = empty($args['suffix']) ? 'copy' : $args['suffix'];
foreach ($targets as $target) {
if (($volume = $this->volume($target)) == false
|| ($src = $volume->file($target)) == false) {
$result['warning'] = $this->error(self::ERROR_COPY, '#'.$target, self::ERROR_FILE_NOT_FOUND);
break;
}
if (($file = $volume->duplicate($target, $suffix)) == false) {
$result['warning'] = $this->error($volume->error());
break;
}
$result['added'][] = $file;
}
return $result;
}
|
Duplicate file - create copy with "copy %d" suffix
@param array $args command arguments
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function rm($args) {
$targets = is_array($args['targets']) ? $args['targets'] : array();
$result = array('removed' => array());
foreach ($targets as $target) {
if (($volume = $this->volume($target)) == false) {
$result['warning'] = $this->error(self::ERROR_RM, '#'.$target, self::ERROR_FILE_NOT_FOUND);
return $result;
}
if (!$volume->rm($target)) {
$result['warning'] = $this->error($volume->error());
return $result;
}
}
return $result;
}
|
Remove dirs/files
@param array command arguments
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function parse_data_scheme( $str, $extTable ) {
$data = $name = '';
if ($fp = fopen('data://'.substr($str, 5), 'rb')) {
if ($data = stream_get_contents($fp)) {
$meta = stream_get_meta_data($fp);
$ext = isset($extTable[$meta['mediatype']])? '.' . $extTable[$meta['mediatype']] : '';
$name = substr(md5($data), 0, 8) . $ext;
}
fclose($fp);
}
return array($data, $name);
}
|
Parse Data URI scheme
@param string $str
@param array $extTable
@return array
@author Naoki Sawada
|
entailment
|
protected function detectFileExtension($path) {
static $type, $finfo, $extTable;
if (!$type) {
$keys = array_keys($this->volumes);
$volume = $this->volumes[$keys[0]];
$extTable = array_flip(array_unique($volume->getMimeTable()));
if (class_exists('finfo')) {
$tmpFileInfo = @explode(';', @finfo_file(finfo_open(FILEINFO_MIME), __FILE__));
} else {
$tmpFileInfo = false;
}
$regexp = '/text\/x\-(php|c\+\+)/';
if ($tmpFileInfo && preg_match($regexp, array_shift($tmpFileInfo))) {
$type = 'finfo';
$finfo = finfo_open(FILEINFO_MIME);
} elseif (function_exists('mime_content_type')
&& preg_match($regexp, array_shift(explode(';', mime_content_type(__FILE__))))) {
$type = 'mime_content_type';
} elseif (function_exists('getimagesize')) {
$type = 'getimagesize';
} else {
$type = 'none';
}
}
$mime = '';
if ($type === 'finfo') {
$mime = @finfo_file($finfo, $path);
} elseif ($type === 'mime_content_type') {
$mime = mime_content_type($path);
} elseif ($type === 'getimagesize') {
if ($img = @getimagesize($path)) {
$mime = $img['mime'];
}
}
if ($mime) {
$mime = explode(';', $mime);
$mime = trim($mime[0]);
if (in_array($mime, array('application/x-empty', 'inode/x-empty'))) {
// finfo return this mime for empty files
$mime = 'text/plain';
} elseif ($mime == 'application/x-zip') {
// http://elrte.org/redmine/issues/163
$mime = 'application/zip';
}
}
return ($mime && isset($extTable[$mime]))? ('.' . $extTable[$mime]) : '';
}
|
Detect file type extension by local path
@param string $path Local path
@return string file type extension with dot
@author Naoki Sawada
|
entailment
|
private function checkChunkedFile($tmpname, $chunk, $cid, $tempDir) {
if (preg_match('/^(.+)(\.\d+_(\d+))\.part$/s', $chunk, $m)) {
$encname = md5($cid . '_' . $m[1]);
$part = $tempDir . '/ELF' . $encname . $m[2];
if (is_null($tmpname)) {
// chunked file upload fail
foreach(glob($tempDir . '/ELF' . $encname . '*') as $cf) {
@unlink($cf);
}
return;
}
if (move_uploaded_file($tmpname, $part)) {
@chmod($part, 0600);
$total = $m[3];
$parts = array();
for ($i = 0; $i <= $total; $i++) {
$name = $tempDir . '/ELF' . $encname . '.' . $i . '_' . $total;
if (is_readable($name)) {
$parts[] = $name;
} else {
$parts = null;
break;
}
}
if ($parts) {
$check = $tempDir . '/ELF' . $encname;
if (!is_file($check)) {
touch($check);
if ($resfile = tempnam($tempDir, 'ELF')) {
$target = fopen($resfile, 'wb');
foreach($parts as $f) {
$fp = fopen($f, 'rb');
while (!feof($fp)) {
fwrite($target, fread($fp, 8192));
}
fclose($fp);
unlink($f);
}
fclose($target);
unlink($check);
return array($resfile, $m[1]);
}
unlink($check);
}
}
}
}
return array('', '');
}
|
Check chunked upload files
@param string $tmpname uploaded temporary file path
@param string $chunk uploaded chunk file name
@param string $cid uploaded chunked file id
@param string $tempDir temporary dirctroy path
@return array (string JoinedTemporaryFilePath, string FileName) or (empty, empty)
@author Naoki Sawada
|
entailment
|
private function getTempDir($volumeTempPath = null) {
$testDirs = array();
if (function_exists('sys_get_temp_dir')) {
$testDirs[] = sys_get_temp_dir();
}
if ($volumeTempPath) {
$testDirs[] = rtrim(realpath($volumeTempPath), DIRECTORY_SEPARATOR);
}
$tempDir = '';
$test = DIRECTORY_SEPARATOR . microtime(true);
foreach($testDirs as $testDir) {
if (!$testDir) continue;
$testFile = $testDir.$test;
if (touch($testFile)) {
unlink($testFile);
$tempDir = $testDir;
$gc = time() - 3600;
foreach(glob($tempDir . '/ELF*') as $cf) {
if (filemtime($cf) < $gc) {
@unlink($cf);
}
}
break;
}
}
return $tempDir;
}
|
Get temporary dirctroy path
@param string $volumeTempPath
@return string
@author Naoki Sawada
|
entailment
|
protected function upload($args) {
$target = $args['target'];
$volume = $this->volume($target);
$files = isset($args['FILES']['upload']) && is_array($args['FILES']['upload']) ? $args['FILES']['upload'] : array();
$result = array('added' => array(), 'header' => empty($args['html']) ? false : 'Content-Type: text/html; charset=utf-8');
$paths = $args['upload_path']? $args['upload_path'] : array();
$chunk = $args['chunk']? $args['chunk'] : '';
$cid = $args['cid']? (int)$args['cid'] : '';
if (!$volume) {
return array('error' => $this->error(self::ERROR_UPLOAD, self::ERROR_TRGDIR_NOT_FOUND, '#'.$target), 'header' => $header);
}
// regist Shutdown function
$GLOBALS['elFinderTempFiles'] = array();
// if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
// $shutdownfunc = function(){ // <- Parse error on PHP < 5.3 ;-(
// foreach(array_keys($GLOBALS['elFinderTempFiles']) as $f){
// @unlink($f);
// }
// };
// } else {
$shutdownfunc = create_function('', '
foreach(array_keys($GLOBALS[\'elFinderTempFiles\']) as $f){
@unlink($f);
}
');
// }
register_shutdown_function($shutdownfunc);
// file extentions table by MIME
$extTable = array_flip(array_unique($volume->getMimeTable()));
if (empty($files)) {
if (isset($args['upload']) && is_array($args['upload']) && ($tempDir = $this->getTempDir($volume->getTempPath()))) {
$names = array();
foreach($args['upload'] as $i => $url) {
// check chunked file upload commit
if ($args['chunk']) {
if ($url === 'chunkfail' && $args['mimes'] === 'chunkfail') {
$this->checkChunkedFile(null, $chunk, $cid, $tempDir);
if (preg_match('/^(.+)(\.\d+_(\d+))\.part$/s', $chunk, $m)) {
$result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $m[1], self::ERROR_UPLOAD_TRANSFER);
}
return $result;
} else {
$tmpfname = $tempDir . '/' . $args['chunk'];
$files['tmp_name'][$i] = $tmpfname;
$files['name'][$i] = $url;
$files['error'][$i] = 0;
$GLOBALS['elFinderTempFiles'][$tmpfname] = true;
break;
}
}
$tmpfname = $tempDir . DIRECTORY_SEPARATOR . 'ELF_FATCH_' . md5($url.microtime(true));
// check is data:
if (substr($url, 0, 5) === 'data:') {
list($data, $args['name'][$i]) = $this->parse_data_scheme($url, $extTable);
} else {
$fp = fopen($tmpfname, 'wb');
$data = $this->get_remote_contents($url, 30, 5, 'Mozilla/5.0', $fp);
}
if ($data) {
$_name = isset($args['name'][$i])? $args['name'][$i] : preg_replace('~^.*?([^/#?]+)(?:\?.*)?(?:#.*)?$~', '$1', rawurldecode($url));
if ($_name) {
$_ext = '';
if (preg_match('/(\.[a-z0-9]{1,7})$/', $_name, $_match)) {
$_ext = $_match[1];
}
if ((is_resource($data) && fclose($data)) || file_put_contents($tmpfname, $data)) {
$GLOBALS['elFinderTempFiles'][$tmpfname] = true;
$_name = preg_replace('/[\/\\?*:|"<>]/', '_', $_name);
list($_a, $_b) = array_pad(explode('.', $_name, 2), 2, '');
if ($_b === '') {
if ($_ext) {
rename($tmpfname, $tmpfname . $_ext);
$tmpfname = $tmpfname . $_ext;
}
$_b = $this->detectFileExtension($tmpfname);
$_name = $_a.$_b;
} else {
$_b = '.'.$_b;
}
if (isset($names[$_name])) {
$_name = $_a.'_'.$names[$_name]++.$_b;
} else {
$names[$_name] = 1;
}
$files['tmp_name'][$i] = $tmpfname;
$files['name'][$i] = $_name;
$files['error'][$i] = 0;
} else {
@ unlink($tmpfname);
}
}
}
}
}
if (empty($files)) {
return array('error' => $this->error(self::ERROR_UPLOAD, self::ERROR_UPLOAD_NO_FILES), 'header' => $header);
}
}
foreach ($files['name'] as $i => $name) {
if (($error = $files['error'][$i]) > 0) {
$result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $name, $error == UPLOAD_ERR_INI_SIZE || $error == UPLOAD_ERR_FORM_SIZE ? self::ERROR_UPLOAD_FILE_SIZE : self::ERROR_UPLOAD_TRANSFER);
$this->uploadDebug = 'Upload error code: '.$error;
break;
}
$tmpname = $files['tmp_name'][$i];
$path = ($paths && !empty($paths[$i]))? $paths[$i] : '';
if ($name === 'blob') {
if ($chunk) {
if ($tempDir = $this->getTempDir($volume->getTempPath())) {
list($tmpname, $name) = $this->checkChunkedFile($tmpname, $chunk, $cid, $tempDir);
if ($name) {
$result['_chunkmerged'] = basename($tmpname);
$result['_name'] = $name;
}
} else {
$result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $chunk, self::ERROR_UPLOAD_TRANSFER);
$this->uploadDebug = 'Upload error: unable open tmp file';
}
return $result;
} else {
// for form clipboard with Google Chrome
$type = $files['type'][$i];
$ext = isset($extTable[$type])? '.' . $extTable[$type] : '';
$name = substr(md5(basename($tmpname)), 0, 8) . $ext;
}
}
// do hook function 'upload.presave'
if (! empty($this->listeners['upload.presave'])) {
foreach($this->listeners['upload.presave'] as $handler) {
call_user_func_array($handler, array(&$path, &$name, $tmpname, $this, $volume));
}
}
if (($fp = fopen($tmpname, 'rb')) == false) {
$result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $name, self::ERROR_UPLOAD_TRANSFER);
$this->uploadDebug = 'Upload error: unable open tmp file';
if (! is_uploaded_file($tmpname)) {
if (@ unlink($tmpname)) unset($GLOBALS['elFinderTempFiles'][$tmpfname]);
continue;
}
break;
}
if ($path) {
$_target = $volume->getUploadTaget($target, $path, $result);
} else {
$_target = $target;
}
if (! $_target || ($file = $volume->upload($fp, $_target, $name, $tmpname)) === false) {
$result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $name, $volume->error());
fclose($fp);
if (! is_uploaded_file($tmpname)) {
if (@ unlink($tmpname)) unset($GLOBALS['elFinderTempFiles'][$tmpname]);;
continue;
}
break;
}
is_resource($fp) && fclose($fp);
if (! is_uploaded_file($tmpname) && @ unlink($tmpname)) unset($GLOBALS['elFinderTempFiles'][$tmpname]);
$result['added'][] = $file;
}
if ($GLOBALS['elFinderTempFiles']) {
foreach(array_keys($GLOBALS['elFinderTempFiles']) as $_temp) {
@ unlink($_temp);
}
}
$result['removed'] = $volume->removed();
return $result;
}
|
Save uploaded files
@param array
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function paste($args) {
$dst = $args['dst'];
$targets = is_array($args['targets']) ? $args['targets'] : array();
$cut = !empty($args['cut']);
$error = $cut ? self::ERROR_MOVE : self::ERROR_COPY;
$result = array('added' => array(), 'removed' => array());
if (($dstVolume = $this->volume($dst)) == false) {
return array('error' => $this->error($error, '#'.$targets[0], self::ERROR_TRGDIR_NOT_FOUND, '#'.$dst));
}
foreach ($targets as $target) {
if (($srcVolume = $this->volume($target)) == false) {
$result['warning'] = $this->error($error, '#'.$target, self::ERROR_FILE_NOT_FOUND);
break;
}
if (($file = $dstVolume->paste($srcVolume, $target, $dst, $cut)) == false) {
$result['warning'] = $this->error($dstVolume->error());
break;
}
$result['added'][] = $file;
}
return $result;
}
|
Copy/move files into new destination
@param array command arguments
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function get($args) {
$target = $args['target'];
$volume = $this->volume($target);
if (!$volume || ($file = $volume->file($target)) == false) {
return array('error' => $this->error(self::ERROR_OPEN, '#'.$target, self::ERROR_FILE_NOT_FOUND));
}
if (($content = $volume->getContents($target)) === false) {
return array('error' => $this->error(self::ERROR_OPEN, $volume->path($target), $volume->error()));
}
if ($args['conv'] && function_exists('mb_detect_encoding') && function_exists('mb_convert_encoding')) {
$mime = isset($file['mime'])? $file['mime'] : '';
if ($mime && strtolower(substr($mime, 0, 4)) === 'text') {
if ($enc = mb_detect_encoding ( $content , mb_detect_order(), true)) {
if (strtolower($enc) !== 'utf-8') {
$content = mb_convert_encoding($content, 'UTF-8', $enc);
}
}
}
}
$json = json_encode($content);
if ($json === false || strlen($json) < strlen($content)) {
if ($args['conv']) {
return array('error' => $this->error(self::ERROR_CONV_UTF8,self::ERROR_NOT_UTF8_CONTENT, $volume->path($target)));
} else {
return array('doconv' => true);
}
}
return array('content' => $content);
}
|
Return file content
@param array $args command arguments
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function put($args) {
$target = $args['target'];
if (($volume = $this->volume($target)) == false
|| ($file = $volume->file($target)) == false) {
return array('error' => $this->error(self::ERROR_SAVE, '#'.$target, self::ERROR_FILE_NOT_FOUND));
}
if (($file = $volume->putContents($target, $args['content'])) == false) {
return array('error' => $this->error(self::ERROR_SAVE, $volume->path($target), $volume->error()));
}
return array('changed' => array($file));
}
|
Save content into text file
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function extract($args) {
$target = $args['target'];
$mimes = !empty($args['mimes']) && is_array($args['mimes']) ? $args['mimes'] : array();
$error = array(self::ERROR_EXTRACT, '#'.$target);
if (($volume = $this->volume($target)) == false
|| ($file = $volume->file($target)) == false) {
return array('error' => $this->error(self::ERROR_EXTRACT, '#'.$target, self::ERROR_FILE_NOT_FOUND));
}
return ($file = $volume->extract($target))
? array('added' => array($file))
: array('error' => $this->error(self::ERROR_EXTRACT, $volume->path($target), $volume->error()));
}
|
Extract files from archive
@param array $args command arguments
@return array
@author Dmitry (dio) Levashov,
@author Alexey Sukhotin
|
entailment
|
protected function archive($args) {
$type = $args['type'];
$targets = isset($args['targets']) && is_array($args['targets']) ? $args['targets'] : array();
if (($volume = $this->volume($targets[0])) == false) {
return $this->error(self::ERROR_ARCHIVE, self::ERROR_TRGDIR_NOT_FOUND);
}
return ($file = $volume->archive($targets, $args['type']))
? array('added' => array($file))
: array('error' => $this->error(self::ERROR_ARCHIVE, $volume->error()));
}
|
Create archive
@param array $args command arguments
@return array
@author Dmitry (dio) Levashov,
@author Alexey Sukhotin
|
entailment
|
protected function search($args) {
$q = trim($args['q']);
$mimes = !empty($args['mimes']) && is_array($args['mimes']) ? $args['mimes'] : array();
$result = array();
foreach ($this->volumes as $volume) {
$result = array_merge($result, $volume->search($q, $mimes));
}
return array('files' => $result);
}
|
Search files
@param array $args command arguments
@return array
@author Dmitry Levashov
|
entailment
|
protected function info($args) {
$files = array();
foreach ($args['targets'] as $hash) {
if (($volume = $this->volume($hash)) != false
&& ($info = $volume->file($hash)) != false) {
$files[] = $info;
}
}
return array('files' => $files);
}
|
Return file info (used by client "places" ui)
@param array $args command arguments
@return array
@author Dmitry Levashov
|
entailment
|
protected function dim($args) {
$target = $args['target'];
if (($volume = $this->volume($target)) != false) {
$dim = $volume->dimensions($target);
return $dim ? array('dim' => $dim) : array();
}
return array();
}
|
Return image dimmensions
@param array $args command arguments
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function resize($args) {
$target = $args['target'];
$width = $args['width'];
$height = $args['height'];
$x = (int)$args['x'];
$y = (int)$args['y'];
$mode = $args['mode'];
$bg = null;
$degree = (int)$args['degree'];
if (($volume = $this->volume($target)) == false
|| ($file = $volume->file($target)) == false) {
return array('error' => $this->error(self::ERROR_RESIZE, '#'.$target, self::ERROR_FILE_NOT_FOUND));
}
return ($file = $volume->resize($target, $width, $height, $x, $y, $mode, $bg, $degree))
? array('changed' => array($file))
: array('error' => $this->error(self::ERROR_RESIZE, $volume->path($target), $volume->error()));
}
|
Resize image
@param array command arguments
@return array
@author Dmitry (dio) Levashov
@author Alexey Sukhotin
|
entailment
|
protected function url($args) {
$target = $args['target'];
$options = isset($args['options'])? $args['options'] : array();
if (($volume = $this->volume($target)) != false) {
$url = $volume->getContentUrl($target, $options);
return $url ? array('url' => $url) : array();
}
return array();
}
|
Return content URL
@param array $args command arguments
@return array
@author Naoki Sawada
|
entailment
|
protected function callback($args) {
$checkReg = '/[^a-zA-Z0-9;._-]/';
$node = (isset($args['node']) && !preg_match($checkReg, $args['node']))? $args['node'] : '';
$json = (isset($args['json']) && @json_decode($args['json']))? $args['json'] : '{}';
$bind = (isset($args['bind']) && !preg_match($checkReg, $args['bind']))? $args['bind'] : '';
$done = (!empty($args['done']));
while( ob_get_level() ) {
if (! ob_end_clean()) {
break;
}
}
if ($done || ! $this->callbackWindowURL) {
$script = '';
if ($node) {
$script .= '
var w = window.opener || weindow.parent || window
var elf = w.document.getElementById(\''.$node.'\').elfinder;
if (elf) {
var data = '.$json.';
data.warning && elf.error(data.warning);
data.removed && data.removed.length && elf.remove(data);
data.added && data.added.length && elf.add(data);
data.changed && data.changed.length && elf.change(data);';
if ($bind) {
$script .= '
elf.trigger(\''.$bind.'\', data);';
}
$script .= '
data.sync && elf.sync();
}';
}
$script .= 'window.close();';
$out = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><script>'.$script.'</script></head><body><a href="#" onlick="window.close();return false;">Close this window</a></body></html>';
header('Content-Type: text/html; charset=utf-8');
header('Content-Length: '.strlen($out));
header('Cache-Control: private');
header('Pragma: no-cache');
echo $out;
} else {
$url = $this->callbackWindowURL;
$url .= ((strpos($url, '?') === false)? '?' : '&')
. '&node=' . rawurlencode($node)
. (($json !== '{}')? ('&json=' . rawurlencode($json)) : '')
. ($bind? ('&bind=' . rawurlencode($bind)) : '')
. '&done=1';
header('Location: ' . $url);
}
exit();
}
|
Output callback result with JavaScript that control elFinder
or HTTP redirect to callbackWindowURL
@param array command arguments
@author Naoki Sawada
|
entailment
|
protected function volume($hash) {
foreach ($this->volumes as $id => $v) {
if (strpos(''.$hash, $id) === 0) {
return $this->volumes[$id];
}
}
return false;
}
|
Return root - file's owner
@param string file hash
@return elFinderStorageDriver
@author Dmitry (dio) Levashov
|
entailment
|
protected function filter($files) {
foreach ($files as $i => $file) {
if (!empty($file['hidden']) || !$this->default->mimeAccepted($file['mime'])) {
unset($files[$i]);
}
}
return array_merge($files, array());
}
|
Remove from files list hidden files and files with required mime types
@param array $files files info
@return array
@author Dmitry (dio) Levashov
|
entailment
|
public static function uses($slug)
{
if (empty(static::$_modes[$slug])) {
throw new InternalErrorException(__d('cms', 'Illegal usage of ViewModeRegistry::uses(), view mode "{0}" was not found.', $slug));
}
static::$_current = $slug;
}
|
Marks as "in use" the given view mode.
The given view mode must be registered first using `add()`. If you
try to switch to an unexisting (unregistered) view mode this method will
throw and exception.
@param string $slug View mode machine name to switch to
@return void
@throws \Cake\Network\Exception\InternalErrorException When switching to an
unregistered view mode
|
entailment
|
public static function add($slug, $name = null, $description = null)
{
if (is_array($slug) && $name === null && $description === null) {
foreach ($slug as $s => $more) {
if (!empty($more['name']) && !empty($more['description'])) {
static::$_modes[$s] = [
'name' => $more['name'],
'description' => $more['description'],
];
}
}
} elseif (is_string($slug)) {
static::$_modes[$slug] = [
'name' => $name,
'description' => $description,
];
}
}
|
Registers a new view mode. Or overwrite if already exists.
You can register more than one view mode at once by passing an array as first
argument and ignore the others two:
```php
ViewModeRegistry::add([
'slug_1' => [
'name' => 'View Mode 1',
'description' => 'Lorem ipsum',
],
'slug_2' => [
'name' => 'View Mode 2',
'description' => 'Dolor sit amet',
],
]);
```
Or you can register a single view mode by passing its "slug", "name"
and "description" as three separated arguments:
```php
ViewModeRegistry::add('slug-1', 'View Mode 1', 'Lorem ipsum');
ViewModeRegistry::add('slug-2', 'View Mode 2', 'Dolor sit amet');
```
@param string|array $slug Slug name of your view mode. e.g.: `my-view mode`,
or an array of view modes to register indexed by slug name
@param string|null $name Human readable name. e.g.: `My View Mode`
@param string|null $description A brief description about for what is this view mode
@return void
|
entailment
|
public static function remove($slug = null)
{
if ($slug === null) {
static::$_current = null;
static::$_modes = [];
} else {
if (isset(static::$_modes[$slug])) {
unset(static::$_modes[$slug]);
}
}
}
|
Unregisters the given view-mode, or all of them if first parameter is null.
@param string|null $slug View mode's slug
@return void
|
entailment
|
public static function current($full = false)
{
if (empty(static::$_current)) {
return '';
} elseif ($full === false) {
return static::$_current;
}
return static::$_modes[static::$_current];
}
|
Gets the in use view-mode information.
You can get either, slug only or full information as an array.
@param bool $full Set to true to get full information as an array,
or set to false (by default) to get slug name only
@return array|string
|
entailment
|
public static function modes($mode = false)
{
if (is_string($mode)) {
if (!isset(static::$_modes[$mode])) {
throw new InternalErrorException(__d('cms', 'Illegal usage of ViewModeRegistry::modes(), view mode "{0}" was not found.', $mode));
}
return static::$_modes[$mode];
} elseif (!$mode) {
return array_keys(static::$_modes);
}
return static::$_modes;
}
|
Gets the full list of all registered view modes, or for a single view mode
if $viewMode is set to a string value.
You can get either a full list of every registered view mode, or a plain list
of slugs of every registered view mode. Or you can get all information for a
particular view mode by passing its slug as first argument.
## Usage:
### Get a list of View Modes slugs:
```php
ViewModeRegistry::modes();
// output: ['teaser', 'full', ...]
```
### Get a full list of every View Mode:
```php
ViewModeRegistry::modes(true);
// output: [
// 'teaser' => [
// 'name' => 'Human readable for teaser mode',
// 'description' => 'Brief description for teaser view-mode'
// ],
// 'full' => [
// 'name' => 'Human readable for full mode',
// 'description' => 'Brief description for full view-mode'
// ],
// ...
// ]
```
### Get full information for a particular View Mode:
```php
ViewModeRegistry::modes('teaser');
// output: [
// 'name' => 'Human readable for teaser mode',
// 'description' => 'Brief description for teaser view-mode'
// ]
```
@param bool|string $mode Set to true to get full list. Or false (by default) to
get only the slug of all registered view modes. Or set to a string value to
get information for that view mode only.
@return array
@throws \Cake\Network\Exception\InternalErrorException When you try to get
information for a particular View Mode that does not exists
|
entailment
|
public function beforeSave(Event $event, Aco $aco)
{
if ($aco->isNew()) {
$aco->set('alias_hash', md5($aco->alias));
}
}
|
We create a hash of "alias" property so we can perform
case sensitive SQL comparisons.
@param \Cake\Event\Event $event The event that was triggered
@param \User\Model\Entity\Aco $aco ACO entity being saved
@return void
|
entailment
|
public function node($ref)
{
$type = $this->alias();
$table = $this->table();
$path = [];
if (is_array($ref)) {
$path = implode('/', array_values(array_filter($ref)));
$path = explode('/', $path);
} elseif (is_string($ref)) {
$path = explode('/', $ref);
}
if (empty($path)) {
return false;
}
$start = $path[0];
unset($path[0]);
$queryData = [
'conditions' => [
"{$type}.lft" . ' <= ' . "{$type}0.lft",
"{$type}.rght" . ' >= ' . "{$type}0.rght",
],
'fields' => ['id', 'parent_id', 'alias'],
'join' => [[
'table' => $table,
'alias' => "{$type}0",
'type' => 'INNER',
'conditions' => [
"{$type}0.alias_hash" => md5($start),
"{$type}0.plugin = {$type}.plugin",
]
]],
'order' => "{$type}.lft" . ' DESC'
];
foreach ($path as $i => $alias) {
$j = $i - 1;
$queryData['join'][] = [
'table' => $table,
'alias' => "{$type}{$i}",
'type' => 'INNER',
'conditions' => [
"{$type}{$i}.lft" . ' > ' . "{$type}{$j}.lft",
"{$type}{$i}.rght" . ' < ' . "{$type}{$j}.rght",
"{$type}{$i}.alias_hash" => md5($alias),
"{$type}{$i}.plugin = {$type}{$i}.plugin",
"{$type}{$j}.id" . ' = ' . "{$type}{$i}.parent_id"
]
];
$queryData['conditions'] = [
'OR' => [
"{$type}.lft" . ' <= ' . "{$type}0.lft" . ' AND ' . "{$type}.rght" . ' >= ' . "{$type}0.rght",
"{$type}.lft" . ' <= ' . "{$type}{$i}.lft" . ' AND ' . "{$type}.rght" . ' >= ' . "{$type}{$i}.rght"
]
];
}
$query = $this->find('all', $queryData);
$result = $query->toArray();
$path = array_values($path);
if (!isset($result[0]) ||
(!empty($path) && $result[0]->alias !== $path[count($path) - 1]) ||
(empty($path) && $result[0]->alias !== $start)
) {
return false;
}
return $query;
}
|
Retrieves the ACO contents for the given ACO path.
### ACO path format:
As a string describing a path:
PluginName/ControllerName/actionName
Or an associative array which values describes a path, for instance:
```php
[
'plugin' => YourPlugin,
'prefix' => Admin,
'controller' => Users,
'action' => index,
]
```
The above array is equivalent to: `PluginName/Admin/Users/index`
@param string|array $ref ACO path as described above
@return \Cake\ORM\Query|bool False if not found or query result if found
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.