sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function configure($id)
{
$instance = $this->_getOrThrow($id, ['locked' => false]);
$arrayContext = [
'schema' => [],
'defaults' => [],
'errors' => [],
];
if ($this->request->data()) {
$instance->accessible('*', true);
$instance->accessible(['id', 'eav_attribute', 'handler', 'ordering'], false);
foreach ($this->request->data as $k => $v) {
if (str_starts_with($k, '_')) {
$instance->set(str_replace_once('_', '', $k), $v);
unset($this->request->data[$k]);
}
}
$validator = $this->FieldInstances->validator('settings');
$instance->validateSettings($this->request->data(), $validator);
$errors = $validator->errors($this->request->data(), false);
if (empty($errors)) {
$instance->set('settings', $this->request->data());
$save = $this->FieldInstances->save($instance);
if ($save) {
$this->Flash->success(__d('field', 'Field information was saved.'));
$this->redirect($this->referer());
} else {
$this->Flash->danger(__d('field', 'Your information could not be saved.'));
}
} else {
$this->Flash->danger(__d('field', 'Field settings could not be saved.'));
foreach ($errors as $field => $message) {
$arrayContext['errors'][$field] = $message;
}
}
} else {
$arrayContext['defaults'] = (array)$instance->settings;
$this->request->data = $arrayContext['defaults'];
}
$this->title(__d('field', 'Configure Field'));
$this->set(compact('arrayContext', 'instance'));
}
|
Handles a single field instance configuration parameters.
In FormHelper, all fields prefixed with `_` will be considered as columns
values of the instance being edited. Any other input element will be
considered as part of the `settings` column.
For example: `_label`, `_required` and `description` maps to `label`,
`required` and `description`. And `some_input`, `another_input` maps to
`settings.some_input`, `settings.another_input`
@param int $id The field instance ID to manage
@return void
@throws \Cake\ORM\Exception\RecordNotFoundException When no field instance
was found
|
entailment
|
public function attach()
{
$this->loadModel('Field.FieldInstances');
if ($this->request->data()) {
$handler = $this->request->data('handler');
$info = fieldsInfo($handler);
$type = !empty($info['type']) ? $info['type'] : null;
$data = $this->request->data();
$data['eav_attribute'] = array_merge([
'table_alias' => $this->_tableAlias,
'bundle' => $this->_getBundle(),
'type' => $type,
], (array)$this->request->data('eav_attribute'));
$fieldInstance = $this->FieldInstances->newEntity($data, ['associated' => ['EavAttribute']]);
$this->_validateSlug($fieldInstance);
$instanceErrors = $fieldInstance->errors();
$attributeErrors = $fieldInstance->get('eav_attribute')->errors();
$success = empty($instanceErrors) && empty($attributeErrors);
if ($success) {
$success = $this->FieldInstances->save($fieldInstance, ['associated' => ['EavAttribute']]);
if ($success) {
$this->Flash->success(__d('field', 'Field attached!'));
$this->redirect($this->referer());
}
}
if (!$success) {
$this->Flash->danger(__d('field', 'Field could not be attached'));
}
} else {
$fieldInstance = $this->FieldInstances->newEntity();
}
$fieldsInfoCollection = fieldsInfo();
$fieldsList = $fieldsInfoCollection->combine('handler', 'name')->toArray(); // for form select
$fieldsInfo = $fieldsInfoCollection->toArray(); // for help-blocks
$this->title(__d('field', 'Attach New Field'));
$this->set('fieldsList', $fieldsList);
$this->set('fieldsInfo', $fieldsInfo);
$this->set('fieldInstance', $fieldInstance);
}
|
Attach action.
Attaches a new Field to the table being managed.
@return void
|
entailment
|
public function detach($id)
{
$instance = $this->_getOrThrow($id, ['locked' => false]);
$this->loadModel('Field.FieldInstances');
if ($this->FieldInstances->delete($instance)) {
$this->Flash->success(__d('field', 'Field detached successfully!'));
} else {
$this->Flash->danger(__d('field', 'Field could not be detached'));
}
$this->title(__d('field', 'Detach Field'));
$this->redirect($this->referer());
}
|
Detach action.
Detaches a Field from table being managed.
@param int $id ID of the instance to detach
@return void
|
entailment
|
public function viewModeList($viewMode)
{
$this->_validateViewMode($viewMode);
$this->loadModel('Field.FieldInstances');
$instances = $this->_getInstances();
if (count($instances) === 0) {
$this->Flash->warning(__d('field', 'There are no field attached yet.'));
} else {
$instances = $instances->sortBy(function ($fieldInstance) use ($viewMode) {
if (isset($fieldInstance->view_modes[$viewMode]['ordering'])) {
return $fieldInstance->view_modes[$viewMode]['ordering'];
}
return 0;
}, SORT_ASC);
}
$this->title(__d('field', 'View Modes'));
$this->set('instances', $instances);
$this->set('viewMode', $viewMode);
$this->set('viewModeInfo', $this->viewModes($viewMode));
}
|
View modes.
Shows the list of fields for corresponding view mode.
@param string $viewMode View mode slug. e.g. `rss` or `default`
@return void
@throws \Cake\Network\Exception\NotFoundException When given view mode
does not exists
|
entailment
|
public function viewModeEdit($viewMode, $id)
{
$this->_validateViewMode($viewMode);
$instance = $this->_getOrThrow($id);
$arrayContext = [
'schema' => [
'label_visibility' => ['type' => 'string'],
'shortcodes' => ['type' => 'boolean'],
'hidden' => ['type' => 'boolean'],
],
'defaults' => [
'label_visibility' => 'hidden',
'shortcodes' => false,
'hidden' => false,
],
'errors' => []
];
$viewModeInfo = $this->viewModes($viewMode);
if ($this->request->data()) {
$validator = $this->FieldInstances->validator('viewMode');
$instance->validateViewModeSettings($this->request->data(), $validator, $viewMode);
$errors = $validator->errors($this->request->data(), false);
if (empty($errors)) {
$instance->accessible('*', true);
$viewModes = $instance->get('view_modes');
$viewModes[$viewMode] = array_merge($viewModes[$viewMode], $this->request->data());
$instance->set('view_modes', $viewModes);
if ($this->FieldInstances->save($instance)) {
$this->Flash->success(__d('field', 'Field information was saved.'));
$this->redirect($this->referer());
} else {
$this->Flash->danger(__d('field', 'Your information could not be saved.'));
}
} else {
$this->Flash->danger(__d('field', 'View mode settings could not be saved.'));
foreach ($errors as $field => $message) {
$arrayContext['errors'][$field] = $message;
}
}
} else {
$arrayContext['defaults'] = (array)$instance->view_modes[$viewMode];
$this->request->data = $arrayContext['defaults'];
}
$this->title(__d('field', 'Configure View Mode'));
$instance->accessible('settings', true);
$this->set(compact('arrayContext', 'viewMode', 'viewModeInfo', 'instance'));
}
|
Handles field instance rendering settings for a particular view mode.
@param string $viewMode View mode slug
@param int $id The field instance ID to manage
@return void
@throws \Cake\ORM\Exception\RecordNotFoundException When no field
instance was found
@throws \Cake\Network\Exception\NotFoundException When given view
mode does not exists
|
entailment
|
public function viewModeMove($viewMode, $id, $direction)
{
$this->_validateViewMode($viewMode);
$instance = $this->_getOrThrow($id);
$unordered = [];
$position = false;
$k = 0;
$list = $this->_getInstances()
->sortBy(function ($fieldInstance) use ($viewMode) {
if (isset($fieldInstance->view_modes[$viewMode]['ordering'])) {
return $fieldInstance->view_modes[$viewMode]['ordering'];
}
return 0;
}, SORT_ASC);
foreach ($list as $field) {
if ($field->id === $instance->id) {
$position = $k;
}
$unordered[] = $field;
$k++;
}
if ($position !== false) {
$ordered = array_move($unordered, $position, $direction);
$before = md5(serialize($unordered));
$after = md5(serialize($ordered));
if ($before != $after) {
foreach ($ordered as $k => $field) {
$viewModes = $field->view_modes;
$viewModes[$viewMode]['ordering'] = $k;
$field->set('view_modes', $viewModes);
$this->FieldInstances->save($field);
}
}
}
$this->title(__d('field', 'Change Field Order'));
$this->redirect($this->referer());
}
|
Moves a field up or down within a view mode.
The ordering indicates the position they are displayed when entities are
rendered in a specific view mode.
@param string $viewMode View mode slug
@param int $id Field instance id
@param string $direction Direction, 'up' or 'down'
@return void Redirects to previous page
@throws \Cake\ORM\Exception\RecordNotFoundException When no field
instance was found
@throws \Cake\Network\Exception\NotFoundException When given view mode
does not exists
|
entailment
|
public function move($id, $direction)
{
$instance = $this->_getOrThrow($id);
$unordered = [];
$direction = !in_array($direction, ['up', 'down']) ? 'up' : $direction;
$position = false;
$list = $this->_getInstances();
foreach ($list as $k => $field) {
if ($field->id === $instance->id) {
$position = $k;
}
$unordered[] = $field;
}
if ($position !== false) {
$ordered = array_move($unordered, $position, $direction);
$before = md5(serialize($unordered));
$after = md5(serialize($ordered));
if ($before != $after) {
foreach ($ordered as $k => $field) {
$field->set('ordering', $k);
$this->FieldInstances->save($field);
}
}
}
$this->title(__d('field', 'Reorder Field'));
$this->redirect($this->referer());
}
|
Moves a field up or down.
The ordering indicates the position they are displayed on entity's
editing form.
@param int $id Field instance id
@param string $direction Direction, 'up' or 'down'
@return void Redirects to previous page
|
entailment
|
protected function _getInstances()
{
$conditions = ['EavAttribute.table_alias' => $this->_tableAlias];
if (!empty($this->_bundle)) {
$conditions['EavAttribute.bundle'] = $this->_bundle;
}
$this->loadModel('Field.FieldInstances');
return $this->FieldInstances
->find()
->contain(['EavAttribute'])
->where($conditions)
->order(['FieldInstances.ordering' => 'ASC'])
->all();
}
|
Returns all field instances attached to the table being managed.
@return \Cake\Datasource\ResultSetInterface
|
entailment
|
protected function _validateSlug($instance)
{
$slug = $instance->get('eav_attribute')->get('name');
$columns = $this->_table->schema()->columns();
if (in_array($slug, $columns)) {
$instance->get('eav_attribute')->errors('name', __d('field', 'The name "{0}" cannot be used as it collides with table column names.', $slug));
}
}
|
Checks that the given instance's slug do not collide with table's real column
names.
If collision occurs, an error message will be registered on the given entity.
@param \Field\Model\Entity\FieldInstance $instance Instance to validate
@return void
|
entailment
|
protected function _getOrThrow($id, $conditions = [])
{
$this->loadModel('Field.FieldInstances');
$conditions = array_merge(['id' => $id], $conditions);
$instance = $this->FieldInstances
->find()
->where($conditions)
->limit(1)
->first();
if (!$instance) {
throw new RecordNotFoundException(__d('field', 'The requested field does not exists.'));
}
return $instance;
}
|
Gets the given field instance by ID or throw if not exists.
@param int $id Field instance ID
@param array $conditions Additional conditions for the WHERE query
@return \Field\Model\Entity\FieldInstance The instance
@throws \Cake\ORM\Exception\RecordNotFoundException When instance
was not found
|
entailment
|
public function upload()
{
if (!isset($this->_package['tmp_name']) || !is_readable($this->_package['tmp_name'])) {
$this->_error(__d('installer', 'Invalid package.'));
return false;
} elseif (!isset($this->_package['name']) || !str_ends_with(strtolower($this->_package['name']), '.zip')) {
$this->_error(__d('installer', 'Invalid package format, it is not a ZIP package.'));
return false;
} else {
$dst = normalizePath(TMP . $this->_package['name']);
if (is_readable($dst)) {
$file = new File($dst);
$file->delete();
}
if (move_uploaded_file($this->_package['tmp_name'], $dst)) {
$this->_dst = $dst;
return true;
}
}
$this->_error(__d('installer', 'Package could not be uploaded, please check write permissions on /tmp directory.'));
return false;
}
|
Uploads a ZIP package to the server.
@return bool True on success
|
entailment
|
protected function _runTransactional()
{
// to avoid any possible issue
snapshot();
if (!$this->_init()) {
return $this->_reset();
}
if (!$this->params['no-callbacks']) {
// "before" events occurs even before plugins is moved to its destination
$this->_attachListeners($this->_plugin['name'], "{$this->_workingDir}/");
try {
$event = $this->trigger("Plugin.{$this->_plugin['name']}.beforeInstall");
if ($event->isStopped() || $event->result === false) {
$this->err(__d('installer', 'Task was explicitly rejected by {0}.', ($this->_plugin['type'] == 'plugin' ? __d('installer', 'the plugin') : __d('installer', 'the theme'))));
return $this->_reset();
}
} catch (\Exception $ex) {
$this->err(__d('installer', 'Internal error, {0} did not respond to "beforeInstall" callback correctly.', ($this->_plugin['type'] == 'plugin' ? __d('installer', 'plugin') : __d('installer', 'theme'))));
return $this->_reset();
}
}
$this->loadModel('System.Plugins');
$entity = $this->Plugins->newEntity([
'name' => $this->_plugin['name'],
'package' => $this->_plugin['packageName'],
'settings' => [],
'status' => 0,
'ordering' => 0,
], ['validate' => false]);
// do not move this lines
if (!$this->_copyPackage()) {
return $this->_reset();
}
if (!$this->_addOptions()) {
$this->_rollbackCopyPackage();
return $this->_reset();
}
if (!$this->Plugins->save($entity)) {
$this->_rollbackCopyPackage();
return $this->_reset();
}
// hold these values as _finish() erases them
$pluginName = $this->_plugin['name'];
$pluginType = $this->_plugin['type'];
$this->_finish(); // plugin namespace is available at this point
if ($this->params['activate']) {
$this->dispatchShell("Installer.plugins toggle -p {$pluginName} -s enable");
}
if (!$this->params['no-callbacks']) {
try {
$event = $this->trigger("Plugin.{$pluginName}.afterInstall");
} catch (\Exception $ex) {
$this->err(__d('installer', '{0} was installed but some errors occur.', ($pluginType == 'plugin' ? __d('installer', 'The plugin') : __d('installer', 'The theme'))));
}
}
return true;
}
|
Runs installation logic inside a safe transactional thread. This prevent
DB inconsistencies on install failure.
@return bool True on success, false otherwise
|
entailment
|
protected function _rollbackCopyPackage()
{
if (!empty($this->_plugin['name'])) {
$destinationPath = normalizePath(ROOT . "/plugins/{$this->_plugin['name']}/");
if (is_dir($destinationPath) && is_writable($destinationPath)) {
$dst = new Folder($destinationPath);
$dst->delete();
}
}
}
|
Deletes the directory that was copied to its final destination.
@return void
|
entailment
|
protected function _addOptions()
{
if (!empty($this->_plugin['composer']['extra']['options'])) {
$this->loadModel('System.Options');
foreach ($this->_plugin['composer']['extra']['options'] as $index => $option) {
if (empty($option['name'])) {
$this->err(__d('installer', 'Unable to register {0} option, invalid option #{1}.', ($this->_plugin['type'] == 'plugin' ? __d('installer', 'plugin') : __d('installer', 'theme')), $index));
return false;
}
$entity = $this->Options->newEntity([
'name' => $option['name'],
'value' => !empty($option['value']) ? $option['value'] : null,
'autoload' => isset($option['autoload']) ? (bool)$option['autoload'] : false,
]);
$errors = $entity->errors();
if (empty($errors)) {
if (!$this->Options->save($entity)) {
$this->err(__d('installer', 'Unable to register option "{0}".', [$option['name']]));
return false;
}
$this->_addedOptions[] = $option['name'];
} else {
$this->err(__d('installer', 'Some errors were found while trying to register {0} options values, see below:', ($this->_plugin['type'] == 'plugin' ? __d('installer', 'plugin') : __d('installer', 'theme'))));
foreach ($errors as $error) {
$this->err(__d('installer', ' - {0}', [$error]));
}
return false;
}
}
}
return true;
}
|
Register on "options" table any declared option is plugin's "composer.json".
@return bool True on success, false otherwise
|
entailment
|
protected function _reset()
{
if ($this->_sourceType !== self::TYPE_DIR && $this->_workingDir) {
$source = new Folder($this->_workingDir);
$source->delete();
}
$this->_addedOptions = [];
$this->_workingDir = null;
$this->_sourceType = null;
$this->_plugin = [
'name' => '',
'packageName' => '',
'type' => '',
'composer' => [],
];
Plugin::dropCache();
$this->_detachListeners();
return false;
}
|
Discards the install operation. Restores this class's status
to its initial state.
### Usage:
```php
return $this->_reset();
```
@return bool False always
|
entailment
|
protected function _finish()
{
global $classLoader; // composer's class loader instance
snapshot();
Plugin::dropCache();
// trick: makes plugin visible to AcoManager
$classLoader->addPsr4($this->_plugin['name'] . "\\", normalizePath(ROOT . "/plugins/{$this->_plugin['name']}/src"), true);
AcoManager::buildAcos($this->_plugin['name']);
$this->_reset();
}
|
After installation is completed.
@return void
|
entailment
|
protected function _copyPackage($clearDestination = false)
{
$source = new Folder($this->_workingDir);
$destinationPath = normalizePath(ROOT . "/plugins/{$this->_plugin['name']}/");
// allow to install from destination folder
if ($this->_workingDir === $destinationPath) {
return true;
}
if (!$clearDestination && is_readable($destinationPath)) {
$this->err(__d('installer', 'Destination directory already exists, please delete manually this directory: {0}', $destinationPath));
return false;
} elseif ($clearDestination && is_readable($destinationPath)) {
$destination = new Folder($destinationPath);
if (!$destination->delete()) {
$this->err(__d('installer', 'Destination directory could not be cleared, please check write permissions: {0}', $destinationPath));
return false;
}
}
if ($source->copy(['to' => $destinationPath])) {
return true;
}
$this->err(__d('installer', 'Error when moving package content.'));
return false;
}
|
Copies the extracted package to its final destination.
@param bool $clearDestination Set to true to delete the destination directory
if already exists. Defaults to false; an error will occur if destination
already exists. Useful for upgrade tasks
@return bool True on success
|
entailment
|
protected function _init()
{
$this->params['source'] = str_replace('"', '', $this->params['source']);
if (function_exists('ini_set')) {
ini_set('max_execution_time', 300);
} elseif (function_exists('set_time_limit')) {
set_time_limit(300);
}
if (is_readable($this->params['source']) && is_dir($this->params['source'])) {
$this->_sourceType = self::TYPE_DIR;
return $this->_getFromDirectory();
} elseif (is_readable($this->params['source']) && !is_dir($this->params['source'])) {
$this->_sourceType = self::TYPE_ZIP;
return $this->_getFromFile();
} elseif (Validation::url($this->params['source'])) {
$this->_sourceType = self::TYPE_URL;
return $this->_getFromUrl();
}
$this->err(__d('installer', 'Unable to resolve the given source ({0}).', [$this->params['source']]));
return false;
}
|
Prepares this task and the package to be installed.
@return bool True on success
|
entailment
|
protected function _getFromFile()
{
$file = new File($this->params['source']);
if ($this->_unzip($file->pwd())) {
return $this->_validateContent();
}
$this->err(__d('installer', 'Unable to extract the package.'));
return false;
}
|
Prepares install from ZIP file.
@return bool True on success
|
entailment
|
protected function _getFromUrl()
{
try {
$http = new Client(['redirect' => 3]); // follow up to 3 redirections
$response = $http->get($this->params['source'], [], [
'headers' => [
'X-Requested-With' => 'XMLHttpRequest'
]
]);
} catch (\Exception $ex) {
$response = false;
$this->err(__d('installer', 'Could not download the package. Details: {0}', $ex->getMessage()));
return false;
}
if ($response && $response->isOk()) {
$this->params['source'] = TMP . substr(md5($this->params['source']), 24) . '.zip';
$file = new File($this->params['source']);
$responseBody = $response->body();
if (is_readable($file->pwd())) {
$file->delete();
}
if (!empty($responseBody) &&
$file->create() &&
$file->write($responseBody, 'w+', true)
) {
$file->close();
return $this->_getFromFile();
$this->err(__d('installer', 'Unable to extract the package.'));
return false;
}
$this->err(__d('installer', 'Unable to download the file, check write permission on "{0}" directory.', [TMP]));
return false;
}
$this->err(__d('installer', 'Could not download the package, no .ZIP file was found at the given URL.'));
return false;
}
|
Prepares install from remote URL.
@return bool True on success
|
entailment
|
protected function _unzip($file)
{
include_once Plugin::classPath('Installer') . 'Lib/pclzip.lib.php';
$File = new File($file);
$to = normalizePath($File->folder()->pwd() . '/' . $File->name() . '_unzip/');
if (is_readable($to)) {
$folder = new Folder($to);
$folder->delete();
} else {
$folder = new Folder($to, true);
}
$PclZip = new \PclZip($file);
$PclZip->delete(PCLZIP_OPT_BY_EREG, '/__MACOSX/');
$PclZip->delete(PCLZIP_OPT_BY_EREG, '/\.DS_Store$/');
if ($PclZip->extract(PCLZIP_OPT_PATH, $to)) {
list($directories, $files) = $folder->read(false, false, true);
if (count($directories) === 1 && empty($files)) {
$container = new Folder($directories[0]);
$container->move(['to' => $to]);
}
$this->_workingDir = $to;
return true;
}
$this->err(__d('installer', 'Unzip error: {0}', [$PclZip->errorInfo(true)]));
return false;
}
|
Extracts the current ZIP package.
@param string $file Full path to the ZIP package
@return bool True on success
|
entailment
|
protected function _validateContent()
{
if (!$this->_workingDir) {
return false;
}
$errors = [];
if (!is_readable("{$this->_workingDir}src") || !is_dir("{$this->_workingDir}src")) {
$errors[] = __d('installer', 'Invalid package, missing "src" directory.');
}
if (!is_readable("{$this->_workingDir}composer.json")) {
$errors[] = __d('installer', 'Invalid package, missing "composer.json" file.');
} else {
$jsonErrors = Plugin::validateJson("{$this->_workingDir}composer.json", true);
if (!empty($jsonErrors)) {
$errors[] = __d('installer', 'Invalid "composer.json".');
$errors = array_merge($errors, (array)$jsonErrors);
} else {
$json = (new File("{$this->_workingDir}composer.json"))->read();
$json = json_decode($json, true);
list(, $pluginName) = packageSplit($json['name'], true);
if ($this->params['theme'] && !str_ends_with($pluginName, 'Theme')) {
$this->err(__d('installer', 'The given package is not a valid theme.'));
return false;
} elseif (!$this->params['theme'] && str_ends_with($pluginName, 'Theme')) {
$this->err(__d('installer', 'The given package is not a valid plugin.'));
return false;
}
$this->_plugin = [
'name' => $pluginName,
'packageName' => $json['name'],
'type' => str_ends_with($pluginName, 'Theme') ? 'theme' : 'plugin',
'composer' => $json,
];
if (Plugin::exists($this->_plugin['name'])) {
$exists = plugin($this->_plugin['name']);
if ($exists->status) {
$errors[] = __d('installer', '{0} "{1}" is already installed.', [($this->_plugin['type'] == 'plugin' ? __d('installer', 'The plugin') : __d('installer', 'The theme')), $this->_plugin['name']]);
} else {
$errors[] = __d('installer', '{0} "{1}" is already installed but disabled, maybe you want try to enable it?.', [($this->_plugin['type'] == 'plugin' ? __d('installer', 'The plugin') : __d('installer', 'The theme')), $this->_plugin['name']]);
}
}
if ($this->_plugin['type'] == 'theme' &&
!is_readable("{$this->_workingDir}webroot/screenshot.png")
) {
$errors[] = __d('installer', 'Missing "screenshot.png" file.');
}
if (isset($json['require'])) {
$checker = new RuleChecker($json['require']);
if (!$checker->check()) {
$errors[] = __d('installer', '{0} "{1}" depends on other packages, plugins or libraries that were not found: {2}', [($this->_plugin['type'] == 'plugin' ? __d('installer', 'The plugin') : __d('installer', 'The theme')), $this->_plugin['name'], $checker->fail(true)]);
}
}
}
}
if (!file_exists(ROOT . '/plugins') ||
!is_dir(ROOT . '/plugins') ||
!is_writable(ROOT . '/plugins')
) {
$errors[] = __d('installer', 'Write permissions required for directory: {0}.', [ROOT . '/plugins/']);
}
foreach ($errors as $message) {
$this->err($message);
}
return empty($errors);
}
|
Validates the content of working directory.
@return bool True on success
|
entailment
|
protected function _attachListeners($plugin, $path)
{
$path = normalizePath("{$path}/");
$eventsPath = normalizePath("{$path}/src/Event/");
if (is_readable($eventsPath) && is_dir($eventsPath)) {
$EventManager = EventManager::instance();
$eventsFolder = new Folder($eventsPath);
Plugin::load($plugin, [
'autoload' => true,
'bootstrap' => false,
'routes' => false,
'path' => $path,
'classBase' => 'src',
'ignoreMissing' => true,
]);
foreach ($eventsFolder->read(false, false, true)[1] as $classPath) {
$className = preg_replace('/\.php$/i', '', basename($classPath));
$fullClassName = implode('\\', [$plugin, 'Event', $className]);
if (class_exists($fullClassName)) {
$handler = new $fullClassName;
$this->_listeners[] = $handler;
$EventManager->on($handler);
}
}
}
}
|
Loads and registers plugin's namespace and loads its event listeners classes.
This is used to allow plugins being installed to respond to events before
they are integrated to the system. Events such as `beforeInstall`,
`afterInstall`, etc.
@param string $plugin Name of the plugin for which attach listeners
@param string $path Path to plugin's root directory (which contains "src")
@throws \Cake\Error\FatalErrorException On illegal usage of this method
|
entailment
|
protected function _detachListeners()
{
$EventManager = EventManager::instance();
foreach ($this->_listeners as $listener) {
$EventManager->detach($listener);
}
}
|
Unloads all registered listeners that were attached using the
"_attachListeners()" method.
@return void
|
entailment
|
protected function _enable()
{
$disabledPlugins = plugin()
->filter(function ($plugin) {
return !$plugin->status && !$plugin->isTheme;
})
->toArray();
if (!count($disabledPlugins)) {
$this->err(__d('installer', '<info>There are no disabled plugins!</info>'));
$this->out();
return;
}
$index = 1;
$this->out();
foreach ($disabledPlugins as $plugin) {
$disabledPlugins[$index] = $plugin;
$this->out(__d('installer', '[{0, number, integer}] {1}', [$index, $plugin->humanName]));
$index++;
}
$this->out();
$message = __d('installer', "Which plugin would you like to activate?\n[Q]uit");
while (true) {
$in = $this->in($message);
if (strtoupper($in) === 'Q') {
$this->err(__d('installer', 'Operation aborted'));
break;
} elseif (intval($in) < 1 || !isset($disabledPlugins[intval($in)])) {
$this->err(__d('installer', 'Invalid option'));
} else {
$task = $this->dispatchShell("Installer.plugins toggle -p {$disabledPlugins[$in]->name} -s enable");
if ($task === 0) {
$this->out(__d('installer', 'Plugin enabled!'));
Plugin::dropCache();
} else {
$this->err(__d('installer', 'Plugin could not be enabled.'), 2);
$this->out();
}
break;
}
}
$this->out();
}
|
Activates a plugin.
@return void
|
entailment
|
public function eventManager(EventManager $eventManager = null)
{
if ($eventManager !== null) {
$this->_eventManager = $eventManager;
}
return $this->_eventManager;
}
|
Gets or sets event manager instance associated to this dispatcher.
@param \Cake\Event\EventManager|null $eventManager The instance to set
@return \Cake\Event\EventManager
|
entailment
|
public static function instance($name = 'default')
{
if (!isset(static::$_instances[$name])) {
static::$_instances[$name] = new EventDispatcher();
}
return static::$_instances[$name];
}
|
Gets an instance of this class.
@param string $name Name of the Event Dispatcher instance to get, if does not
exists a new instance will be created and registered
@return \CMS\Event\EventDispatcher
|
entailment
|
public function trigger($eventName)
{
$data = func_get_args();
array_shift($data);
$event = $this->_prepareEvent($eventName, $data);
$this->_log($event->name());
$this->_eventManager->dispatch($event);
return $event;
}
|
Trigger the given event name.
### Usage:
```php
EventDispatcher::instance()->trigger('GetTime', $arg0, $arg1, ..., $argn);
```
Your Event Listener must implement:
```php
public function implementedEvents()
{
return ['GetTime' => 'handlerForGetTime'];
}
public function handlerForGetTime(Event $event, $arg0, $arg1, ..., $argn)
{
// logic
}
```
You can provide a subject to use by passing an array as first arguments where
the first element is the event name and the second one is the subject:
```php
EventDispatcher::instance()
->trigger(['GetTime', new MySubject()], $arg0, $arg1, ..., $argn);
```
If no subject is given an instance of "EventDispatcher" class will be used by
default.
@param array|string $eventName The event name to trigger
@return \Cake\Event\Event The event object that was triggered
|
entailment
|
public function triggerArray($eventName, array $data = [])
{
$event = $this->_prepareEvent($eventName, $data);
$this->_log($event->name());
$this->_eventManager->dispatch($event);
return $event;
}
|
Similar to "trigger()" but this method expects that data is given as an
associative array instead of function arguments.
### Usage:
```php
EventDispatcher::instance()->triggerArray('myEvent', [$data1, $data2]);
```
Which is equivalent to:
```php
EventDispatcher::instance()->trigger('myEvent', $data1, $data2);
```
@param array|string $eventName The event name to trigger
@param array $data Information to be passed to event listener
@return \Cake\Event\Event The event object that was triggered
|
entailment
|
public function triggered($eventName = null, $sort = true)
{
if ($eventName === null) {
if ($sort) {
arsort($this->_log, SORT_NATURAL);
}
return $this->_log;
}
if (isset($this->_log[$eventName])) {
return $this->_log[$eventName];
}
return 0;
}
|
Retrieves the number of times an event was triggered, or the complete
list of events that were triggered.
@param string|null $eventName The name of the event, if null returns the entire
list of event that were fired
@param bool $sort If first argument is null set this to true to sort the list.
Defaults to true
@return int|array
|
entailment
|
protected function _prepareEvent($eventName, array $data = [])
{
if (is_array($eventName)) {
list($eventName, $subject) = $eventName;
} else {
$subject = new EventDispatcher();
}
return new Event($eventName, $subject, $data);
}
|
Prepares the event object to be triggered.
@param array|string $eventName The event name to trigger
@param array $data Data to be passed to event listener method
@return \Cake\Event\Event
|
entailment
|
protected function _log($eventName)
{
if (isset($this->_log[$eventName])) {
$this->_log[$eventName]++;
} else {
$this->_log[$eventName] = 1;
}
}
|
Logs the given event.
@param string $eventName The event name to log
@return void
|
entailment
|
public function subject($subject = null)
{
if ($subject !== null) {
$this->_subject = $subject;
return $this;
}
return $this->_subject;
}
|
Gets or sets message's subject.
@param string $subject Subject
@return $this|string When new value is set, $this is returned for allowing
method chaining. When getting value a string will be returned
|
entailment
|
public function body($body = null)
{
if ($body !== null) {
$this->_body = $body;
return $this;
}
return $this->_body;
}
|
Gets or sets message's body.
@param string $body Body
@return $this|string When new value is set, $this is returned for allowing
method chaining. When getting value a string will be returned
|
entailment
|
public function send()
{
if (!$this->_user->has('email') || !$this->_user->has('name')) {
throw new BadMethodCallException(__d('user', 'Missing "name" or "email" property when trying to send the email.'));
}
if ($this->config('updateToken') === true) {
$this->loadModel('User.Users');
$this->_user->updateToken();
}
$subject = $this->_parseVariables((string)$this->subject());
$body = $this->_parseVariables((string)$this->body());
if (empty($subject) || empty($body)) {
return false;
}
$sender = new Email($this->config('emailConfig'));
$sent = false;
try {
$sent = $sender
->to($this->_user->get('email'), $this->_user->get('name'))
->subject($subject)
->send($body);
} catch (\Exception $e) {
return false;
}
return $sent;
}
|
Sends email message to user.
@return bool True on success, false otherwise
@throws \BadMethodCallException When "name" or "email" properties are missing
for the provided User entity
|
entailment
|
protected function _parseVariables($text)
{
$user = $this->_user;
return str_replace([
'{{user:name}}',
'{{user:username}}',
'{{user:email}}',
'{{user:activation-url}}',
'{{user:one-time-login-url}}',
'{{user:cancel-url}}',
'{{site:name}}',
'{{site:url}}',
'{{site:description}}',
'{{site:slogan}}',
'{{site:login-url}}',
], [
$user->get('name'),
$user->get('username'),
$user->get('email'),
Router::url(['plugin' => 'User', 'controller' => 'gateway', 'action' => 'activate', 'prefix' => false, $user->get('token')], true),
Router::url(['plugin' => 'User', 'controller' => 'gateway', 'action' => 'me', 'prefix' => false, 'token' => $user->get('token')], true),
Router::url(['plugin' => 'User', 'controller' => 'gateway', 'action' => 'cancel', 'prefix' => false, $user->id, $user->get('cancelCode')], true),
option('site_title'),
Router::url('/', true),
option('site_description'),
option('site_slogan'),
Router::url(['plugin' => 'User', 'controller' => 'gateway', 'action' => 'login', 'prefix' => false], true),
], $text);
}
|
Looks for variables tags in the given message and replaces with their
corresponding values. For example, "{{site:name}} will be replaced with
user's real name.
Message classes can overwrite this method and add their own logic for parsing
variables.
@param string $text Message where to look for tags.
@return string
|
entailment
|
public function upload($name)
{
$instance = $this->_getInstance($name);
require_once Plugin::classPath('Field') . 'Lib/class.upload.php';
$uploader = new \upload($this->request->data['Filedata']);
if (!empty($instance->settings['extensions'])) {
$exts = explode(',', $instance->settings['extensions']);
$exts = array_map('trim', $exts);
$exts = array_map('strtolower', $exts);
if (!in_array(strtolower($uploader->file_src_name_ext), $exts)) {
$this->_error(__d('field', 'Invalid file extension.'), 501);
}
}
$response = '';
$uploader->file_overwrite = false;
$folder = normalizePath(WWW_ROOT . "/files/{$instance->settings['upload_folder']}/");
$url = normalizePath("/files/{$instance->settings['upload_folder']}/", '/');
$uploader->process($folder);
if ($uploader->processed) {
$response = json_encode([
'file_url' => Router::url($url . $uploader->file_dst_name, true),
'file_size' => FileToolbox::bytesToSize($uploader->file_src_size),
'file_name' => $uploader->file_dst_name,
'mime_icon' => FileToolbox::fileIcon($uploader->file_src_mime),
]);
} else {
$this->_error(__d('field', 'File upload error, details: {0}', $uploader->error), 502);
}
$this->viewBuilder()->layout('ajax');
$this->title(__d('field', 'Upload File'));
$this->set(compact('response'));
}
|
Uploads a new file for the given FileField instance.
@param string $name EAV attribute name
@throws \Cake\Network\Exception\NotFoundException When invalid slug is given,
or when upload process could not be completed
|
entailment
|
public function delete($name)
{
$this->loadModel('Field.FieldInstances');
$instance = $this->_getInstance($name);
if ($instance && !empty($this->request->query['file'])) {
$file = normalizePath(WWW_ROOT . "/files/{$instance->settings['upload_folder']}/{$this->request->query['file']}", DS);
$file = new File($file);
$file->delete();
}
$response = '';
$this->viewBuilder()->layout('ajax');
$this->title(__d('field', 'Delete File'));
$this->set(compact('response'));
}
|
Deletes a file for the given FileField instance.
File name must be passes as `file` GET parameter.
@param string $name EAV attribute name
@return void
@throws \Cake\Network\Exception\NotFoundException When invalid attribute name
is given
|
entailment
|
protected function _getInstance($name)
{
$this->loadModel('Field.FieldInstances');
$instance = $this->FieldInstances
->find()
->contain(['EavAttribute'])
->where(['EavAttribute.name' => $name])
->first();
if (!$instance) {
$this->_error(__d('field', 'Invalid field instance.'), 504);
}
return $instance;
}
|
Get field instance information.
@param string $name EAV attribute name
@return \Field\Model\Entity\FieldInstance
@throws \Cake\Network\Exception\NotFoundException When invalid attribute name
is given
|
entailment
|
protected function _error($message, $code)
{
header("HTTP/1.0 {$code} {$message}");
echo $message;
TableRegistry::get('Field.FieldInstances')->connection()->disconnect();
exit(0);
}
|
Sends a JSON message error.
@param string $message The message
@param int $code A unique code identifier for this message
@return void Stops scripts execution
|
entailment
|
public function isAction($action)
{
try {
$method = new ReflectionMethod($this, $action);
} catch (\ReflectionException $e) {
return false;
}
if (!$method->isPublic()) {
return false;
}
if ($method->getDeclaringClass()->name === 'Cake\Controller\Controller' ||
$method->getDeclaringClass()->name === 'CMS\Controller\Controller'
) {
return false;
}
return true;
}
|
Method to check that an action is accessible from a URL.
Override this method to change which controller methods can be reached.
The default implementation disallows access to all methods defined on
Cake\Controller\Controller or CMS\Controller\Controller, and allows all
public methods on all subclasses of this class.
@param string $action The action to check.
@return bool Whether or not the method is accessible from a URL.
|
entailment
|
public function prepareTheme()
{
$this->viewBuilder()->layout('default');
if (!empty($this->request->params['prefix']) &&
strtolower($this->request->params['prefix']) === 'admin'
) {
$this->viewBuilder()->theme(option('back_theme'));
} else {
$this->viewBuilder()->theme(option('front_theme'));
}
if ($this->request->isAjax()) {
$this->viewBuilder()->layout('ajax');
}
if ($this->request->isHome()) {
$this->viewBuilder()->layout('home');
}
if ($this->request->isDashboard()) {
$this->viewBuilder()->layout('dashboard');
}
}
|
Sets the theme to use.
@return void
|
entailment
|
public function checkMaintenanceMode()
{
if (option('site_maintenance') &&
!$this->request->isUserAdmin() &&
!in_array(strtolower("{$this->request->plugin}:{$this->request->controller}:{$this->request->action}"), ['user:gateway:login', 'user:gateway:logout'])
) {
$allowedIps = (array)array_filter(array_map('trim', explode(',', option('site_maintenance_ip'))));
if (!in_array(env('REMOTE_ADDR'), $allowedIps)) {
throw new SiteUnderMaintenanceException(option('site_maintenance_message'));
}
}
}
|
Checks if maintenance is enabled, and renders the corresponding maintenance
message.
Login & logout sections of the site still working even on maintenance mode,
administrators can access the whole site as well.
@return void
@throws CMS\Error\SiteUnderMaintenanceException When site is under
maintenance mode
|
entailment
|
public function render($items, $config = [])
{
if ($this->_rendering) {
throw new FatalErrorException(__d('menu', 'Loop detected, MenuHelper already rendering.'));
}
$items = $this->_prepareItems($items);
if (empty($items)) {
return '';
}
list($config, $attrs) = $this->_prepareOptions($config);
$this->_rendering = true;
$this->countItems($items);
$this->config($config);
if ($this->config('breadcrumbGuessing')) {
$this->Link->config(['breadcrumbGuessing' => $this->config('breadcrumbGuessing')]);
}
$out = '';
if (intval($this->config('split')) > 1) {
$out .= $this->_renderPart($items, $config, $attrs);
} else {
$out .= $this->formatTemplate('root', [
'attrs' => $this->templater()->formatAttributes($attrs),
'content' => $this->_render($items)
]);
}
if ($this->config('beautify')) {
include_once Plugin::classPath('Menu') . 'Lib/htmLawed.php';
$tidy = is_bool($this->config('beautify')) ? '1t0n' : $this->config('beautify');
$out = htmLawed($out, compact('tidy'));
}
$this->_clear();
return $out;
}
|
Renders a nested menu.
This methods renders a HTML menu using a `threaded` result set:
```php
// In controller:
$this->set('links', $this->Links->find('threaded'));
// In view:
echo $this->Menu->render('links');
```
### Options:
You can pass an associative array `key => value`. Any `key` not in
`$_defaultConfig` will be treated as an additional attribute for the top
level UL (root). If `key` is in `$_defaultConfig` it will temporally
overwrite default configuration parameters, it will be restored to its
default values after rendering completes:
- `formatter`: Callable method used when formating each item.
- `activeClass`: CSS class to use when an item is active (its URL matches current URL).
- `firstItemClass`: CSS class for the first item.
- `lastItemClass`: CSS class for the last item.
- `hasChildrenClass`: CSS class to use when an item has children.
- `split`: Split menu into multiple root menus (multiple UL's)
- `templates`: The templates you want to use for this menu. Any templates
will be merged on top of the already loaded templates. This option can
either be a filename in App/config that contains the templates you want
to load, or an array of templates to use.
You can also pass a callable function as second argument which will be
used as formatter:
```php
echo $this->Menu->render($links, function ($link, $info) {
// render $item here
});
```
Formatters receives two arguments, the item being rendered as first argument
and information abut the item (has children, depth, etc) as second.
You can pass the ID or slug of a menu as fist argument to render that menu's
links:
```php
echo $this->Menu->render('management');
// OR
echo $this->Menu->render(1);
```
@param int|string|array|\Cake\Collection\Collection $items Nested items
to render, given as a query result set or as an array list. Or an integer as
menu ID in DB to render, or a string as menu Slug in DB to render.
@param callable|array $config An array of HTML attributes and options as
described above or a callable function to use as `formatter`
@return string HTML
@throws \Cake\Error\FatalErrorException When loop invocation is detected,
that is, when "render()" method is invoked within a callable method when
rendering menus.
|
entailment
|
public function formatter($item, array $info, array $options = [])
{
if (!empty($options['templates'])) {
$templatesBefore = $this->templates();
$this->templates((array)$options['templates']);
unset($options['templates']);
}
$attrs = $this->_prepareItemAttrs($item, $info, $options);
$return = $this->formatTemplate('child', [
'attrs' => $this->templater()->formatAttributes($attrs['child']),
'content' => $this->formatTemplate('link', [
'url' => $this->Link->url($item->url),
'attrs' => $this->templater()->formatAttributes($attrs['link']),
'content' => $item->title,
]),
'children' => $info['children'],
]);
if (isset($templatesBefore)) {
$this->templates($templatesBefore);
}
return $return;
}
|
Default callable method (see formatter option).
### Valid options are:
- `templates`: Array of templates indexed as `templateName` => `templatePattern`.
Temporally overwrites templates when rendering this item, after item is rendered
templates are restored to previous values.
- `childAttrs`: Array of attributes for `child` template.
- `class`: Array list of multiple CSS classes or a single string (will be merged
with auto-generated CSS; "active", "has-children", etc).
- `linkAttrs`: Array of attributes for the `link` template.
- `class`: Same as childAttrs.
### Information argument
The second argument `$info` holds a series of useful values when rendering
each item of the menu. This values are stored as `key` => `value` array.
- `index` (integer): Position of current item.
- `total` (integer): Total number of items in the menu being rendered.
- `depth` (integer): Item depth within the tree structure.
- `hasChildren` (boolean): true|false
- `children` (string): HTML content of rendered children for this item.
Empty if has no children.
@param \Cake\ORM\Entity $item The item to render
@param array $info Array of useful information such as described above
@param array $options Additional options
@return string
|
entailment
|
public function countItems($items)
{
if ($this->_count) {
return $this->_count;
}
$this->_count($items);
return $this->_count;
}
|
Counts items in menu.
@param \Cake\ORM\Query $items Items to count
@return int
|
entailment
|
protected function _prepareOptions($options = [])
{
$attrs = [];
if (is_callable($options)) {
$this->config('formatter', $options);
$options = [];
} else {
if (!empty($options['templates']) && is_array($options['templates'])) {
$this->templates($options['templates']);
unset($options['templates']);
}
foreach ($options as $key => $value) {
if (isset($this->_defaultConfig[$key])) {
$this->config($key, $value);
} else {
$attrs[$key] = $value;
}
}
}
return [
$options,
$attrs,
];
}
|
Prepares options given to "render()" method.
### Usage:
```php
list($options, $attrs) = $this->_prepareOptions($options);
```
@param array|callable $options Options given to `render()`
@return array Array with two keys: `0 => $options` sanitized and filtered
options array, and `1 => $attrs` list of attributes for top level UL element
|
entailment
|
protected function _prepareItemAttrs($item, array $info, array $options)
{
$options = Hash::merge($options, [
'childAttrs' => ['class' => []],
'linkAttrs' => ['class' => []],
]);
$childAttrs = $options['childAttrs'];
$linkAttrs = $options['linkAttrs'];
if (is_string($childAttrs['class'])) {
$childAttrs['class'] = [$childAttrs['class']];
}
if (is_string($linkAttrs['class'])) {
$linkAttrs['class'] = [$linkAttrs['class']];
}
if ($info['index'] === 1) {
$childAttrs['class'][] = $this->config('firstClass');
}
if ($info['index'] === $info['total']) {
$childAttrs['class'][] = $this->config('lastClass');
}
if ($info['hasChildren']) {
$childAttrs['class'][] = $this->config('hasChildrenClass');
if ($this->config('dropdown')) {
$childAttrs['class'][] = 'dropdown';
$linkAttrs['data-toggle'] = 'dropdown';
}
}
if (!empty($item->description)) {
$linkAttrs['title'] = $item->description;
}
if (!empty($item->target)) {
$linkAttrs['target'] = $item->target;
}
if ($info['active']) {
$childAttrs['class'][] = $this->config('activeClass');
$linkAttrs['class'][] = $this->config('activeClass');
}
$id = $this->_calculateItemId($item);
if (!empty($id)) {
$childAttrs['class'][] = "menu-link-{$id}";
}
$childAttrs['class'] = array_unique($childAttrs['class']);
$linkAttrs['class'] = array_unique($linkAttrs['class']);
return [
'link' => $linkAttrs,
'child' => $childAttrs,
];
}
|
Prepares item's attributes for rendering.
@param \Cake\Datasource\EntityInterface $item The item being rendered
@param array $info Item's rendering info
@param array $options Item's rendering options
@return array Associative array with two keys, `link` and `child`
@see \Menu\View\Helper\MenuHelper::formatter()
|
entailment
|
protected function _calculateItemId(EntityInterface $item)
{
if ($item->has('id')) {
return $item->id;
}
if (is_array($item->url)) {
return Inflector::slug(strtolower(implode(' ', array_values($item->url))));
}
return Inflector::slug(strtolower($item->url));
}
|
Calculates an item's ID
@param \Cake\Datasource\EntityInterface $item The item
@return string The ID, it may be an empty
|
entailment
|
protected function _prepareItems($items)
{
if (is_integer($items)) {
$id = $items;
$cacheKey = "render({$id})";
$items = static::cache($cacheKey);
if ($items === null) {
$items = TableRegistry::get('Menu.MenuLinks')
->find('threaded')
->where(['menu_id' => $id])
->all();
static::cache($cacheKey, $items);
}
} elseif (is_string($items)) {
$slug = $items;
$cacheKey = "render({$slug})";
$items = static::cache($cacheKey);
if ($items === null) {
$items = [];
$menu = TableRegistry::get('Menu.Menus')
->find()
->select(['id'])
->where(['slug' => $slug])
->first();
if ($menu instanceof EntityInterface) {
$items = TableRegistry::get('Menu.MenuLinks')
->find('threaded')
->where(['menu_id' => $menu->id])
->all();
}
static::cache($cacheKey, $items);
}
}
return $items;
}
|
Prepares the items (links) to be rendered as part of a menu.
@param mixed $items As described on `render()`
@return mixed Collection of links to be rendered
|
entailment
|
protected function _renderPart($items, $options, $attrs)
{
if (is_object($items) && method_exists($items, 'toArray')) {
$arrayItems = $items->toArray();
} else {
$arrayItems = (array)$items;
}
$chunkOut = '';
$size = round(count($arrayItems) / intval($this->config('split')));
$chunk = array_chunk($arrayItems, $size);
$i = 1;
foreach ($chunk as $menu) {
$chunkOut .= $this->formatTemplate('parent', [
'attrs' => $this->templater()->formatAttributes(['class' => "menu-part part-{$i}"]),
'content' => $this->_render($menu, $this->config('formatter'))
]);
$i++;
}
return $this->formatTemplate('div', [
'attrs' => $this->templater()->formatAttributes($attrs),
'content' => $chunkOut,
]);
}
|
Starts rendering process of a menu's parts (when using the "split" option).
@param mixed $items Menu links
@param array $options Options for the rendering process
@param array $attrs Menu's attributes
@return string
|
entailment
|
protected function _render($items, $depth = 0)
{
$content = '';
$formatter = $this->config('formatter');
foreach ($items as $item) {
$children = '';
if (is_array($item)) {
$item = new Entity($item);
}
if ($item->has('children') && !empty($item->children) && $item->expanded) {
$children = $this->formatTemplate('parent', [
'attrs' => $this->templater()->formatAttributes([
'class' => ($this->config('dropdown') ? 'dropdown-menu multi-level' : ''),
'role' => 'menu'
]),
'content' => $this->_render($item->children, $depth + 1)
]);
}
$this->_index++;
$info = [
'index' => $this->_index,
'total' => $this->_count,
'active' => $this->Link->isActive($item),
'depth' => $depth,
'hasChildren' => !empty($children),
'children' => $children,
];
$content .= $formatter($item, $info);
}
return $content;
}
|
Internal method to recursively generate the menu.
@param \Cake\ORM\Query $items Items to render
@param int $depth Current iteration depth
@return string HTML
|
entailment
|
protected function _count($items)
{
foreach ($items as $item) {
$this->_count++;
$item = is_array($item) ? new Entity($item) : $item;
if ($item->has('children') && !empty($item->children) && $item->expanded) {
$this->_count($item->children);
}
}
}
|
Internal method for counting items in menu.
This method will ignore children if parent has been marked as `do no expand`.
@param \Cake\ORM\Query $items Items to count
@return int
|
entailment
|
protected function _clear()
{
$this->_index = 0;
$this->_count = 0;
$this->_rendering = false;
$this->config($this->_defaultConfig);
$this->Link->config(['breadcrumbGuessing' => $this->_defaultConfig['breadcrumbGuessing']]);
$this->resetTemplates();
}
|
Clears all temporary variables used when rendering a menu, so they do not
interfere when rendering other menus.
@return void
|
entailment
|
public function renderComment(Event $event, $comment, $options = [])
{
$View = $event->subject();
$html = $View->element('Comment.render_comment', compact('comment', 'options'));
return $html;
}
|
Renders a single Comment.
@param Event $event The event that was triggered
@param \Comment\Model\Entity\Comment $comment The comment entity to render
@param array $options Additional options given as an array
@return string HTML
|
entailment
|
public function settingsDefaults(Event $event)
{
return [
'visibility' => 0,
'auto_approve' => false,
'allow_anonymous' => false,
'anonymous_name' => false,
'anonymous_name_required' => true,
'anonymous_email' => false,
'anonymous_email_required' => true,
'anonymous_web' => false,
'anonymous_web_required' => true,
'text_processing' => 'plain',
'use_ayah' => false,
'ayah_publisher_key' => '',
'ayah_scoring_key' => '',
'use_akismet' => false,
'akismet_key' => '',
'akismet_action' => 'mark',
];
}
|
Defaults settings for Comment's settings form.
@param Event $event The event that was triggered
@return array
|
entailment
|
public function version()
{
if (parent::version() !== null) {
return parent::version();
}
$packages = $this->_packages();
$this->_version = isset($packages[$this->_packageName]) ? $packages[$this->_packageName] : '';
return $this->_version;
}
|
{@inheritDoc}
Gets package's version from composer's "installed.json". By default CakePHP
and QuickAppCMS package versions are handled by their internal version
getters:
- \Cake\Core\Configure\version() for CakePHP
- quickapps('version') for QuickAppsCMS
@return string Package's version, for instance `1.2.x-dev`
|
entailment
|
protected function _packages()
{
$installed = static::cache('_composerPackages');
if (is_array($installed)) {
return $installed;
}
$jsonPath = VENDOR_INCLUDE_PATH . 'composer/installed.json';
$installed = [];
if (is_readable($jsonPath)) {
$json = (array)json_decode(file_get_contents($jsonPath), true);
foreach ($json as $pkg) {
$installed[$pkg['name']] = [
'name' => $pkg['name'],
'version' => $pkg['version'],
'version_normalized' => $pkg['version_normalized'],
];
}
}
return static::cache('_composerPackages', $installed);
}
|
Gets a list of all packages installed using composer.
@return array
|
entailment
|
protected function configure() {
// set thumbnails path
$path = $this->options['tmbPath'];
if ($path) {
if (!file_exists($path)) {
if (@mkdir($path)) {
chmod($path, $this->options['tmbPathMode']);
} else {
$path = '';
}
}
if (is_dir($path) && is_readable($path)) {
$this->tmbPath = $path;
$this->tmbPathWritable = is_writable($path);
}
}
// set image manipulation library
$type = preg_match('/^(imagick|gd|auto)$/i', $this->options['imgLib'])
? strtolower($this->options['imgLib'])
: 'auto';
if (($type == 'imagick' || $type == 'auto') && extension_loaded('imagick')) {
$this->imgLib = 'imagick';
} else {
$this->imgLib = function_exists('gd_info') ? 'gd' : '';
}
}
|
Configure after successfull mount.
By default set thumbnails path and image manipulation library.
@return void
@author Dmitry (dio) Levashov
|
entailment
|
public function debug() {
return array(
'id' => $this->id(),
'name' => strtolower(substr(get_class($this), strlen('elfinderdriver'))),
'mimeDetect' => $this->mimeDetect,
'imgLib' => $this->imgLib
);
}
|
Return debug info for client
@return array
@author Dmitry (dio) Levashov
|
entailment
|
public function mount(array $opts) {
if (!isset($opts['path']) || $opts['path'] === '') {
return $this->setError('Path undefined.');;
}
$this->options = array_merge($this->options, $opts);
$this->id = $this->driverId.(!empty($this->options['id']) ? $this->options['id'] : elFinder::$volumesCnt++).'_';
$this->root = $this->normpathCE($this->options['path']);
$this->separator = isset($this->options['separator']) ? $this->options['separator'] : DIRECTORY_SEPARATOR;
// set server encoding
if (!empty($this->options['encoding']) && strtoupper($this->options['encoding']) !== 'UTF-8') {
$this->encoding = $this->options['encoding'];
} else {
$this->encoding = null;
}
$argInit = ($_SERVER['REQUEST_METHOD'] === 'POST')? !empty($_POST['init']) : !empty($_GET['init']);
// session cache
if ($argInit || ! isset($_SESSION[elFinder::$sessionCacheKey][$this->id])) {
$_SESSION[elFinder::$sessionCacheKey][$this->id] = array();
}
$this->sessionCache = &$_SESSION[elFinder::$sessionCacheKey][$this->id];
// default file attribute
$this->defaults = array(
'read' => isset($this->options['defaults']['read']) ? !!$this->options['defaults']['read'] : true,
'write' => isset($this->options['defaults']['write']) ? !!$this->options['defaults']['write'] : true,
'locked' => isset($this->options['defaults']['locked']) ? !!$this->options['defaults']['locked'] : false,
'hidden' => isset($this->options['defaults']['hidden']) ? !!$this->options['defaults']['hidden'] : false
);
// root attributes
$this->attributes[] = array(
'pattern' => '~^'.preg_quote(DIRECTORY_SEPARATOR).'$~',
'locked' => true,
'hidden' => false
);
// set files attributes
if (!empty($this->options['attributes']) && is_array($this->options['attributes'])) {
foreach ($this->options['attributes'] as $a) {
// attributes must contain pattern and at least one rule
if (!empty($a['pattern']) || count($a) > 1) {
$this->attributes[] = $a;
}
}
}
if (!empty($this->options['accessControl']) && is_callable($this->options['accessControl'])) {
$this->access = $this->options['accessControl'];
}
$this->today = mktime(0,0,0, date('m'), date('d'), date('Y'));
$this->yesterday = $this->today-86400;
// debug($this->attributes);
if (!$this->init()) {
return false;
}
// check some options is arrays
$this->uploadAllow = isset($this->options['uploadAllow']) && is_array($this->options['uploadAllow'])
? $this->options['uploadAllow']
: array();
$this->uploadDeny = isset($this->options['uploadDeny']) && is_array($this->options['uploadDeny'])
? $this->options['uploadDeny']
: array();
if (is_string($this->options['uploadOrder'])) { // telephat_mode on, compatibility with 1.x
$parts = explode(',', isset($this->options['uploadOrder']) ? $this->options['uploadOrder'] : 'deny,allow');
$this->uploadOrder = array(trim($parts[0]), trim($parts[1]));
} else { // telephat_mode off
$this->uploadOrder = $this->options['uploadOrder'];
}
if (!empty($this->options['uploadMaxSize'])) {
$size = ''.$this->options['uploadMaxSize'];
$unit = strtolower(substr($size, strlen($size) - 1));
$n = 1;
switch ($unit) {
case 'k':
$n = 1024;
break;
case 'm':
$n = 1048576;
break;
case 'g':
$n = 1073741824;
}
$this->uploadMaxSize = intval($size)*$n;
}
$this->disabled = isset($this->options['disabled']) && is_array($this->options['disabled'])
? $this->options['disabled']
: array();
$this->cryptLib = $this->options['cryptLib'];
$this->mimeDetect = $this->options['mimeDetect'];
// find available mimetype detect method
$type = strtolower($this->options['mimeDetect']);
$type = preg_match('/^(finfo|mime_content_type|internal|auto)$/i', $type) ? $type : 'auto';
$regexp = '/text\/x\-(php|c\+\+)/';
if (($type == 'finfo' || $type == 'auto')
&& class_exists('finfo')) {
$tmpFileInfo = @explode(';', @finfo_file(finfo_open(FILEINFO_MIME), __FILE__));
} else {
$tmpFileInfo = false;
}
if ($tmpFileInfo && preg_match($regexp, array_shift($tmpFileInfo))) {
$type = 'finfo';
$this->finfo = finfo_open(FILEINFO_MIME);
} elseif (($type == 'mime_content_type' || $type == 'auto')
&& function_exists('mime_content_type')
&& preg_match($regexp, array_shift(explode(';', mime_content_type(__FILE__))))) {
$type = 'mime_content_type';
} else {
$type = 'internal';
}
$this->mimeDetect = $type;
// load mimes from external file for mimeDetect == 'internal'
// based on Alexey Sukhotin idea and patch: http://elrte.org/redmine/issues/163
// file must be in file directory or in parent one
if ($this->mimeDetect == 'internal' && !self::$mimetypesLoaded) {
self::$mimetypesLoaded = true;
$this->mimeDetect = 'internal';
$file = false;
if (!empty($this->options['mimefile']) && file_exists($this->options['mimefile'])) {
$file = $this->options['mimefile'];
} elseif (file_exists(dirname(__FILE__).DIRECTORY_SEPARATOR.'mime.types')) {
$file = dirname(__FILE__).DIRECTORY_SEPARATOR.'mime.types';
} elseif (file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'mime.types')) {
$file = dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'mime.types';
}
if ($file && file_exists($file)) {
$mimecf = file($file);
foreach ($mimecf as $line_num => $line) {
if (!preg_match('/^\s*#/', $line)) {
$mime = preg_split('/\s+/', $line, -1, PREG_SPLIT_NO_EMPTY);
for ($i = 1, $size = count($mime); $i < $size ; $i++) {
if (!isset(self::$mimetypes[$mime[$i]])) {
self::$mimetypes[$mime[$i]] = $mime[0];
}
}
}
}
}
}
$this->rootName = empty($this->options['alias']) ? $this->basenameCE($this->root) : $this->options['alias'];
// This get's triggered if $this->root == '/' and alias is empty.
// Maybe modify _basename instead?
if ($this->rootName === '') $this->rootName = $this->separator;
$root = $this->stat($this->root);
if (!$root) {
return $this->setError('Root folder does not exists.');
}
if (!$root['read'] && !$root['write']) {
return $this->setError('Root folder has not read and write permissions.');
}
// debug($root);
if ($root['read']) {
// check startPath - path to open by default instead of root
if ($this->options['startPath']) {
$start = $this->stat($this->options['startPath']);
if (!empty($start)
&& $start['mime'] == 'directory'
&& $start['read']
&& empty($start['hidden'])
&& $this->inpathCE($this->options['startPath'], $this->root)) {
$this->startPath = $this->options['startPath'];
if (substr($this->startPath, -1, 1) == $this->options['separator']) {
$this->startPath = substr($this->startPath, 0, -1);
}
}
}
} else {
$this->options['URL'] = '';
$this->options['tmbURL'] = '';
$this->options['tmbPath'] = '';
// read only volume
array_unshift($this->attributes, array(
'pattern' => '/.*/',
'read' => false
));
}
$this->treeDeep = $this->options['treeDeep'] > 0 ? (int)$this->options['treeDeep'] : 1;
$this->tmbSize = $this->options['tmbSize'] > 0 ? (int)$this->options['tmbSize'] : 48;
$this->URL = $this->options['URL'];
if ($this->URL && preg_match("|[^/?&=]$|", $this->URL)) {
$this->URL .= '/';
}
$this->tmbURL = !empty($this->options['tmbURL']) ? $this->options['tmbURL'] : '';
if ($this->tmbURL && preg_match("|[^/?&=]$|", $this->tmbURL)) {
$this->tmbURL .= '/';
}
$this->nameValidator = !empty($this->options['acceptedName']) && (is_string($this->options['acceptedName']) || is_callable($this->options['acceptedName']))
? $this->options['acceptedName']
: '';
$this->_checkArchivers();
// manual control archive types to create
if (!empty($this->options['archiveMimes']) && is_array($this->options['archiveMimes'])) {
foreach ($this->archivers['create'] as $mime => $v) {
if (!in_array($mime, $this->options['archiveMimes'])) {
unset($this->archivers['create'][$mime]);
}
}
}
// manualy add archivers
if (!empty($this->options['archivers']['create']) && is_array($this->options['archivers']['create'])) {
foreach ($this->options['archivers']['create'] as $mime => $conf) {
if (strpos($mime, 'application/') === 0
&& !empty($conf['cmd'])
&& isset($conf['argc'])
&& !empty($conf['ext'])
&& !isset($this->archivers['create'][$mime])) {
$this->archivers['create'][$mime] = $conf;
}
}
}
if (!empty($this->options['archivers']['extract']) && is_array($this->options['archivers']['extract'])) {
foreach ($this->options['archivers']['extract'] as $mime => $conf) {
if (strpos($mime, 'application/') === 0
&& !empty($conf['cmd'])
&& isset($conf['argc'])
&& !empty($conf['ext'])
&& !isset($this->archivers['extract'][$mime])) {
$this->archivers['extract'][$mime] = $conf;
}
}
}
$this->configure();
// echo $this->uploadMaxSize;
// echo $this->options['uploadMaxSize'];
return $this->mounted = true;
}
|
"Mount" volume.
Return true if volume available for read or write,
false - otherwise
@return bool
@author Dmitry (dio) Levashov
@author Alexey Sukhotin
|
entailment
|
public function options($hash) {
return array(
'path' => $this->path($this->decode($hash)),
'url' => $this->URL,
'tmbUrl' => $this->tmbURL,
'disabled' => $this->disabled,
'separator' => $this->separator,
'copyOverwrite' => intval($this->options['copyOverwrite']),
'uploadMaxSize' => intval($this->uploadMaxSize),
'archivers' => array(
// 'create' => array_keys($this->archivers['create']),
// 'extract' => array_keys($this->archivers['extract']),
'create' => isset($this->archivers['create']) && is_array($this->archivers['create']) ? array_keys($this->archivers['create']) : array(),
'extract' => isset($this->archivers['extract']) && is_array($this->archivers['extract']) ? array_keys($this->archivers['extract']) : array()
)
);
}
|
Return volume options required by client:
@return array
@author Dmitry (dio) Levashov
|
entailment
|
public function getOptionsPlugin($name = '') {
if ($name) {
return isset($this->options['plugin'][$name])? $this->options['plugin'][$name] : array();
} else {
return $this->options['plugin'];
}
}
|
Get plugin values of this options
@param string $name Plugin name
@return NULL|array Plugin values
@author Naoki Sawada
|
entailment
|
public function mimeAccepted($mime, $mimes = array(), $empty = true) {
$mimes = !empty($mimes) ? $mimes : $this->onlyMimes;
if (empty($mimes)) {
return $empty;
}
return $mime == 'directory'
|| in_array('all', $mimes)
|| in_array('All', $mimes)
|| in_array($mime, $mimes)
|| in_array(substr($mime, 0, strpos($mime, '/')), $mimes);
}
|
Return true if mime is required mimes list
@param string $mime mime type to check
@param array $mimes allowed mime types list or not set to use client mimes list
@param bool|null $empty what to return on empty list
@return bool|null
@author Dmitry (dio) Levashov
@author Troex Nevelin
|
entailment
|
public function path($hash) {
return $this->convEncOut($this->_path($this->convEncIn($this->decode($hash))));
}
|
Return file path related to root with convert encoging
@param string $hash file hash
@return string
@author Dmitry (dio) Levashov
|
entailment
|
public function realpath($hash) {
$path = $this->decode($hash);
return $this->stat($path) ? $path : false;
}
|
Return file real path if file exists
@param string $hash file hash
@return string
@author Dmitry (dio) Levashov
|
entailment
|
public function closest($hash, $attr, $val) {
return ($path = $this->closestByAttr($this->decode($hash), $attr, $val)) ? $this->encode($path) : false;
}
|
Return file/dir hash or first founded child hash with required attr == $val
@param string $hash file hash
@param string $attr attribute name
@param bool $val attribute value
@return string|false
@author Dmitry (dio) Levashov
|
entailment
|
public function file($hash) {
$path = $this->decode($hash);
return ($file = $this->stat($path)) ? $file : $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
}
|
Return file info or false on error
@param string $hash file hash
@param bool $realpath add realpath field to file info
@return array|false
@author Dmitry (dio) Levashov
|
entailment
|
public function dir($hash, $resolveLink=false) {
if (($dir = $this->file($hash)) == false) {
return $this->setError(elFinder::ERROR_DIR_NOT_FOUND);
}
if ($resolveLink && !empty($dir['thash'])) {
$dir = $this->file($dir['thash']);
}
return $dir && $dir['mime'] == 'directory' && empty($dir['hidden'])
? $dir
: $this->setError(elFinder::ERROR_NOT_DIR);
}
|
Return folder info
@param string $hash folder hash
@param bool $hidden return hidden file info
@return array|false
@author Dmitry (dio) Levashov
|
entailment
|
public function scandir($hash) {
if (($dir = $this->dir($hash)) == false) {
return false;
}
return $dir['read']
? $this->getScandir($this->decode($hash))
: $this->setError(elFinder::ERROR_PERM_DENIED);
}
|
Return directory content or false on error
@param string $hash file hash
@return array|false
@author Dmitry (dio) Levashov
|
entailment
|
public function ls($hash) {
if (($dir = $this->dir($hash)) == false || !$dir['read']) {
return false;
}
$list = array();
$path = $this->decode($hash);
foreach ($this->getScandir($path) as $stat) {
if (empty($stat['hidden']) && $this->mimeAccepted($stat['mime'])) {
$list[] = $stat['name'];
}
}
return $list;
}
|
Return dir files names list
@param string $hash file hash
@return array
@author Dmitry (dio) Levashov
|
entailment
|
public function parents($hash, $lineal = false) {
if (($current = $this->dir($hash)) == false) {
return false;
}
$path = $this->decode($hash);
$tree = array();
while ($path && $path != $this->root) {
$path = $this->dirnameCE($path);
$stat = $this->stat($path);
if (!empty($stat['hidden']) || !$stat['read']) {
return false;
}
array_unshift($tree, $stat);
if (!$lineal) {
foreach ($this->gettree($path, 0) as $dir) {
if (!in_array($dir, $tree)) {
$tree[] = $dir;
}
}
}
}
return $tree ? $tree : array($current);
}
|
Return part of dirs tree from required dir up to root dir
@param string $hash directory hash
@param bool|null $lineal only lineal parents
@return array
@author Dmitry (dio) Levashov
|
entailment
|
public function tmb($hash) {
$path = $this->decode($hash);
$stat = $this->stat($path);
if (isset($stat['tmb'])) {
return $stat['tmb'] == "1" ? $this->createTmb($path, $stat) : $stat['tmb'];
}
return false;
}
|
Create thumbnail for required file and return its name of false on failed
@return string|false
@author Dmitry (dio) Levashov
|
entailment
|
public function open($hash) {
if (($file = $this->file($hash)) == false
|| $file['mime'] == 'directory') {
return false;
}
return $this->fopenCE($this->decode($hash), 'rb');
}
|
Open file for reading and return file pointer
@param string file hash
@return Resource
@author Dmitry (dio) Levashov
|
entailment
|
public function mkdir($dsthash, $name) {
if ($this->commandDisabled('mkdir')) {
return $this->setError(elFinder::ERROR_PERM_DENIED);
}
if (!$this->nameAccepted($name)) {
return $this->setError(elFinder::ERROR_INVALID_NAME);
}
if (($dir = $this->dir($dsthash)) == false) {
return $this->setError(elFinder::ERROR_TRGDIR_NOT_FOUND, '#'.$dsthash);
}
$path = $this->decode($dsthash);
if (!$dir['write'] || !$this->allowCreate($path, $name, true)) {
return $this->setError(elFinder::ERROR_PERM_DENIED);
}
$dst = $this->joinPathCE($path, $name);
$stat = $this->stat($dst);
if (!empty($stat)) {
return $this->setError(elFinder::ERROR_EXISTS, $name);
}
$this->clearcache();
return ($path = $this->convEncOut($this->_mkdir($this->convEncIn($path), $this->convEncIn($name)))) ? $this->stat($path) : false;
}
|
Create directory and return dir info
@param string $dsthash destination directory hash
@param string $name directory name
@return array|false
@author Dmitry (dio) Levashov
|
entailment
|
public function mkfile($dst, $name) {
if ($this->commandDisabled('mkfile')) {
return $this->setError(elFinder::ERROR_PERM_DENIED);
}
if (!$this->nameAccepted($name)) {
return $this->setError(elFinder::ERROR_INVALID_NAME);
}
if (($dir = $this->dir($dst)) == false) {
return $this->setError(elFinder::ERROR_TRGDIR_NOT_FOUND, '#'.$dst);
}
$path = $this->decode($dst);
if (!$dir['write'] || !$this->allowCreate($path, $name, false)) {
return $this->setError(elFinder::ERROR_PERM_DENIED);
}
if ($this->stat($this->joinPathCE($path, $name))) {
return $this->setError(elFinder::ERROR_EXISTS, $name);
}
$this->clearcache();
return ($path = $this->convEncOut($this->_mkfile($this->convEncIn($path), $this->convEncIn($name)))) ? $this->stat($path) : false;
}
|
Create empty file and return its info
@param string $dst destination directory
@param string $name file name
@return array|false
@author Dmitry (dio) Levashov
|
entailment
|
public function rename($hash, $name) {
if ($this->commandDisabled('rename')) {
return $this->setError(elFinder::ERROR_PERM_DENIED);
}
if (!$this->nameAccepted($name)) {
return $this->setError(elFinder::ERROR_INVALID_NAME, $name);
}
if (!($file = $this->file($hash))) {
return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
}
if ($name == $file['name']) {
return $file;
}
if (!empty($file['locked'])) {
return $this->setError(elFinder::ERROR_LOCKED, $file['name']);
}
$path = $this->decode($hash);
$dir = $this->dirnameCE($path);
$stat = $this->stat($this->joinPathCE($dir, $name));
if ($stat) {
return $this->setError(elFinder::ERROR_EXISTS, $name);
}
if (!$this->allowCreate($dir, $name, ($file['mime'] === 'directory'))) {
return $this->setError(elFinder::ERROR_PERM_DENIED);
}
$this->rmTmb($file); // remove old name tmbs, we cannot do this after dir move
if ($path = $this->convEncOut($this->_move($this->convEncIn($path), $this->convEncIn($dir), $this->convEncIn($name)))) {
$this->clearcache();
return $this->stat($path);
}
return false;
}
|
Rename file and return file info
@param string $hash file hash
@param string $name new file name
@return array|false
@author Dmitry (dio) Levashov
|
entailment
|
public function duplicate($hash, $suffix='copy') {
if ($this->commandDisabled('duplicate')) {
return $this->setError(elFinder::ERROR_COPY, '#'.$hash, elFinder::ERROR_PERM_DENIED);
}
if (($file = $this->file($hash)) == false) {
return $this->setError(elFinder::ERROR_COPY, elFinder::ERROR_FILE_NOT_FOUND);
}
$path = $this->decode($hash);
$dir = $this->dirnameCE($path);
$name = $this->uniqueName($dir, $this->basenameCE($path), ' '.$suffix.' ');
if (!$this->allowCreate($dir, $name, ($file['mime'] === 'directory'))) {
return $this->setError(elFinder::ERROR_PERM_DENIED);
}
return ($path = $this->copy($path, $dir, $name)) == false
? false
: $this->stat($path);
}
|
Create file copy with suffix "copy number" and return its info
@param string $hash file hash
@param string $suffix suffix to add to file name
@return array|false
@author Dmitry (dio) Levashov
|
entailment
|
public function paste($volume, $src, $dst, $rmSrc = false) {
$err = $rmSrc ? elFinder::ERROR_MOVE : elFinder::ERROR_COPY;
if ($this->commandDisabled('paste')) {
return $this->setError($err, '#'.$src, elFinder::ERROR_PERM_DENIED);
}
if (($file = $volume->file($src, $rmSrc)) == false) {
return $this->setError($err, '#'.$src, elFinder::ERROR_FILE_NOT_FOUND);
}
$name = $file['name'];
$errpath = $volume->path($src);
if (($dir = $this->dir($dst)) == false) {
return $this->setError($err, $errpath, elFinder::ERROR_TRGDIR_NOT_FOUND, '#'.$dst);
}
if (!$dir['write'] || !$file['read']) {
return $this->setError($err, $errpath, elFinder::ERROR_PERM_DENIED);
}
$destination = $this->decode($dst);
if (($test = $volume->closest($src, $rmSrc ? 'locked' : 'read', $rmSrc))) {
return $rmSrc
? $this->setError($err, $errpath, elFinder::ERROR_LOCKED, $volume->path($test))
: $this->setError($err, $errpath, elFinder::ERROR_PERM_DENIED);
}
$test = $this->joinPathCE($destination, $name);
$stat = $this->stat($test);
$this->clearcache();
if ($stat) {
if ($this->options['copyOverwrite']) {
// do not replace file with dir or dir with file
if (!$this->isSameType($file['mime'], $stat['mime'])) {
return $this->setError(elFinder::ERROR_NOT_REPLACE, $this->path($test));
}
// existed file is not writable
if (!$stat['write']) {
return $this->setError($err, $errpath, elFinder::ERROR_PERM_DENIED);
}
// existed file locked or has locked child
if (($locked = $this->closestByAttr($test, 'locked', true))) {
return $this->setError(elFinder::ERROR_LOCKED, $this->path($locked));
}
// target is entity file of alias
if ($volume == $this && ($test == @$file['target'] || $test == $this->decode($src))) {
return $this->setError(elFinder::ERROR_REPLACE, $errpath);
}
// remove existed file
if (!$this->remove($test)) {
return $this->setError(elFinder::ERROR_REPLACE, $this->path($test));
}
} else {
$name = $this->uniqueName($destination, $name, ' ', false);
}
}
// copy/move inside current volume
if ($volume == $this) {
$source = $this->decode($src);
// do not copy into itself
if ($this->inpathCE($destination, $source)) {
return $this->setError(elFinder::ERROR_COPY_INTO_ITSELF, $errpath);
}
$method = $rmSrc ? 'move' : 'copy';
return ($path = $this->$method($source, $destination, $name)) ? $this->stat($path) : false;
}
// copy/move from another volume
if (!$this->options['copyTo'] || !$volume->copyFromAllowed()) {
return $this->setError(elFinder::ERROR_COPY, $errpath, elFinder::ERROR_PERM_DENIED);
}
if (($path = $this->copyFrom($volume, $src, $destination, $name)) == false) {
return false;
}
if ($rmSrc) {
if ($volume->rm($src)) {
$this->removed[] = $file;
} else {
return $this->setError(elFinder::ERROR_MOVE, $errpath, elFinder::ERROR_RM_SRC);
}
}
return $this->stat($path);
}
|
Paste files
@param Object $volume source volume
@param string $source file hash
@param string $dst destination dir hash
@param bool $rmSrc remove source after copy?
@return array|false
@author Dmitry (dio) Levashov
|
entailment
|
public function getContents($hash) {
$file = $this->file($hash);
if (!$file) {
return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
}
if ($file['mime'] == 'directory') {
return $this->setError(elFinder::ERROR_NOT_FILE);
}
if (!$file['read']) {
return $this->setError(elFinder::ERROR_PERM_DENIED);
}
return $this->convEncOut($this->_getContents($this->convEncIn($this->decode($hash))));
}
|
Return file contents
@param string $hash file hash
@return string|false
@author Dmitry (dio) Levashov
|
entailment
|
public function resize($hash, $width, $height, $x, $y, $mode = 'resize', $bg = '', $degree = 0) {
if ($this->commandDisabled('resize')) {
return $this->setError(elFinder::ERROR_PERM_DENIED);
}
if (($file = $this->file($hash)) == false) {
return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
}
if (!$file['write'] || !$file['read']) {
return $this->setError(elFinder::ERROR_PERM_DENIED);
}
$path = $this->decode($hash);
if (!$this->canResize($path, $file)) {
return $this->setError(elFinder::ERROR_UNSUPPORT_TYPE);
}
$work_path = $this->getWorkFile($this->encoding? $this->convEncIn($path, true) : $path);
if (!$work_path || !is_writable($work_path)) {
if ($work_path && $path !== $work_path && is_file($work_path)) {
@unlink($work_path);
}
return false;
}
switch($mode) {
case 'propresize':
$result = $this->imgResize($work_path, $width, $height, true, true);
break;
case 'crop':
$result = $this->imgCrop($work_path, $width, $height, $x, $y);
break;
case 'fitsquare':
$result = $this->imgSquareFit($work_path, $width, $height, 'center', 'middle', ($bg ? $bg : $this->options['tmbBgColor']));
break;
case 'rotate':
$result = $this->imgRotate($work_path, $degree, ($bg ? $bg : $this->options['tmbBgColor']));
break;
default:
$result = $this->imgResize($work_path, $width, $height, false, true);
break;
}
$ret = false;
if ($result) {
$stat = $this->stat($path);
clearstatcache();
$fstat = stat($work_path);
$stat['size'] = $fstat['size'];
$stat['ts'] = $fstat['mtime'];
if ($imgsize = @getimagesize($work_path)) {
$stat['width'] = $imgsize[0];
$stat['height'] = $imgsize[1];
$stat['mime'] = $imgsize['mime'];
}
if ($path !== $work_path) {
if ($fp = @fopen($work_path, 'rb')) {
$ret = $this->saveCE($fp, $this->dirnameCE($path), $this->basenameCE($path), $stat);
@fclose($fp);
}
} else {
$ret = true;
}
if ($ret) {
$this->rmTmb($file);
$this->clearcache();
$ret = $this->stat($path);
$ret['width'] = $stat['width'];
$ret['height'] = $stat['height'];
}
}
if ($path !== $work_path) {
is_file($work_path) && @unlink($work_path);
}
return $ret;
}
|
Resize image
@param string $hash image file
@param int $width new width
@param int $height new height
@param int $x X start poistion for crop
@param int $y Y start poistion for crop
@param string $mode action how to mainpulate image
@return array|false
@author Dmitry (dio) Levashov
@author Alexey Sukhotin
@author nao-pon
@author Troex Nevelin
|
entailment
|
public function rm($hash) {
return $this->commandDisabled('rm')
? $this->setError(elFinder::ERROR_PERM_DENIED)
: $this->remove($this->decode($hash));
}
|
Remove file/dir
@param string $hash file hash
@return bool
@author Dmitry (dio) Levashov
|
entailment
|
public function search($q, $mimes) {
return $this->commandDisabled('search')
? array()
: $this->doSearch($this->root, $q, $mimes);
}
|
Search files
@param string $q search string
@param array $mimes
@return array
@author Dmitry (dio) Levashov
|
entailment
|
public function dimensions($hash) {
if (($file = $this->file($hash)) == false) {
return false;
}
return $this->convEncOut($this->_dimensions($this->convEncIn($this->decode($hash)), $file['mime']));
}
|
Return image dimensions
@param string $hash file hash
@return array
@author Dmitry (dio) Levashov
|
entailment
|
public function getContentUrl($hash, $options = array()) {
if (($file = $this->file($hash)) == false || !$file['url'] || $file['url'] == 1) {
return false;
}
return $file['url'];
}
|
Return content URL (for netmout volume driver)
If file.url == 1 requests from JavaScript client with XHR
@param string $hash file hash
@param array $options options array
@return boolean|string
@author Naoki Sawada
|
entailment
|
public function getTempPath() {
if (@ $this->tmpPath) {
return $this->tmpPath;
} else if (@ $this->tmp) {
return $this->tmp;
} else if (function_exists('sys_get_temp_dir')) {
return sys_get_temp_dir();
} else if (@ $this->tmbPath) {
return $this->tmbPath;
} else {
return null;
}
}
|
Return temp path
@return string
@author Naoki Sawada
|
entailment
|
public function getUploadTaget($baseTargetHash, $path, & $result) {
$base = $this->decode($baseTargetHash);
$targetHash = $baseTargetHash;
$path = ltrim($path, '/');
$dirs = explode('/', $path);
array_pop($dirs);
foreach($dirs as $dir) {
$targetPath = $this->joinPathCE($base, $dir);
if (! $_realpath = $this->realpath($this->encode($targetPath))) {
if ($stat = $this->mkdir($targetHash, $dir)) {
$result['added'][] = $stat;
$targetHash = $stat['hash'];
$base = $this->decode($targetHash);
} else {
return false;
}
} else {
$targetHash = $this->encode($_realpath);
if ($this->dir($targetHash)) {
$base = $this->decode($targetHash);
} else {
return false;
}
}
}
return $targetHash;
}
|
(Make &) Get upload taget dirctory hash
@param string $baseTargetHash
@param string $path
@param array $result
@return boolean|string
@author Naoki Sawada
|
entailment
|
protected function setError($error) {
$this->error = array();
foreach (func_get_args() as $err) {
if (is_array($err)) {
$this->error = array_merge($this->error, $err);
} else {
$this->error[] = $err;
}
}
// $this->error = is_array($error) ? $error : func_get_args();
return false;
}
|
Save error message
@param array error
@return false
@author Dmitry(dio) Levashov
|
entailment
|
protected function dirnameCE($path) {
return (!$this->encoding)? $this->_dirname($path) : $this->convEncOut($this->_dirname($this->convEncIn($path)));
}
|
Return parent directory path (with convert encording)
@param string $path file path
@return string
@author Naoki Sawada
|
entailment
|
protected function basenameCE($path) {
return (!$this->encoding)? $this->_basename($path) : $this->convEncOut($this->_basename($this->convEncIn($path)));
}
|
Return file name (with convert encording)
@param string $path file path
@return string
@author Naoki Sawada
|
entailment
|
protected function joinPathCE($dir, $name) {
return (!$this->encoding)? $this->_joinPath($dir, $name) : $this->convEncOut($this->_joinPath($this->convEncIn($dir), $this->convEncIn($name)));
}
|
Join dir name and file name and return full path. (with convert encording)
Some drivers (db) use int as path - so we give to concat path to driver itself
@param string $dir dir path
@param string $name file name
@return string
@author Naoki Sawada
|
entailment
|
protected function normpathCE($path) {
return (!$this->encoding)? $this->_normpath($path) : $this->convEncOut($this->_normpath($this->convEncIn($path)));
}
|
Return normalized path (with convert encording)
@param string $path file path
@return string
@author Naoki Sawada
|
entailment
|
protected function relpathCE($path) {
return (!$this->encoding)? $this->_relpath($path) : $this->convEncOut($this->_relpath($this->convEncIn($path)));
}
|
Return file path related to root dir (with convert encording)
@param string $path file path
@return string
@author Naoki Sawada
|
entailment
|
protected function abspathCE($path) {
return (!$this->encoding)? $this->_abspath($path): $this->convEncOut($this->_abspath($this->convEncIn($path)));
}
|
Convert path related to root dir into real path (with convert encording)
@param string $path rel file path
@return string
@author Naoki Sawada
|
entailment
|
protected function inpathCE($path, $parent) {
return (!$this->encoding)? $this->_inpath($path, $parent) : $this->convEncOut($this->_inpath($this->convEncIn($path), $this->convEncIn($parent)));
}
|
Return true if $path is children of $parent (with convert encording)
@param string $path path to check
@param string $parent parent path
@return bool
@author Naoki Sawada
|
entailment
|
protected function fopenCE($path, $mode='rb') {
return (!$this->encoding)? $this->_fopen($path, $mode) : $this->convEncOut($this->_fopen($this->convEncIn($path), $mode));
}
|
Open file and return file pointer (with convert encording)
@param string $path file path
@param bool $write open file for writing
@return resource|false
@author Naoki Sawada
|
entailment
|
protected function fcloseCE($fp, $path='') {
return (!$this->encoding)? $this->_fclose($fp, $path) : $this->convEncOut($this->_fclose($fp, $this->convEncIn($path)));
}
|
Close opened file (with convert encording)
@param resource $fp file pointer
@param string $path file path
@return bool
@author Naoki Sawada
|
entailment
|
protected function saveCE($fp, $dir, $name, $stat) {
return (!$this->encoding)? $this->_save($fp, $dir, $name, $stat) : $this->convEncOut($this->_save($fp, $this->convEncIn($dir), $this->convEncIn($name), $this->convEncIn($stat)));
}
|
Create new file and write into it from file pointer. (with convert encording)
Return new file path or false on error.
@param resource $fp file pointer
@param string $dir target dir path
@param string $name file name
@param array $stat file stat (required by some virtual fs)
@return bool|string
@author Naoki Sawada
|
entailment
|
protected function subdirsCE($path) {
return (!$this->encoding)? $this->_subdirs($path) : $this->convEncOut($this->_subdirs($this->convEncIn($path)));
}
|
Return true if path is dir and has at least one childs directory (with convert encording)
@param string $path dir path
@return bool
@author Naoki Sawada
|
entailment
|
protected function scandirCE($path) {
return (!$this->encoding)? $this->_scandir($path) : $this->convEncOut($this->_scandir($this->convEncIn($path)));
}
|
Return files list in directory (with convert encording)
@param string $path dir path
@return array
@author Naoki Sawada
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.