sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function parse($text) { # standardize line breaks $text = str_replace("\r\n", "\n", $text); $text = str_replace("\r", "\n", $text); # replace tabs with spaces $text = str_replace("\t", ' ', $text); # remove surrounding line breaks $text = trim($text, "\n"); # split text into lines $lines = explode("\n", $text); # iterate through lines to identify blocks $blocks = $this->findBlocks($lines); # iterate through blocks to build markup $markup = $this->compile($blocks); # trim line breaks $markup = trim($markup, "\n"); return $markup; }
#
entailment
public function settings(Block $block, View $view) { $languagesList = LocaleToolbox::languagesList(false, false); return $view->element('Locale.language_switcher_widget_settings', compact('block', 'languagesList')); }
{@inheritDoc}
entailment
public function vocabulary($id) { $this->loadModel('Taxonomy.Vocabularies'); $vocabulary = $this->Vocabularies->get($id); $terms = $this->Vocabularies->Terms ->find() ->where(['vocabulary_id' => $id]) ->order(['lft' => 'ASC']) ->all() ->map(function ($term) { $term->set('expanded', true); return $term; }) ->nest('id', 'parent_id'); if (!empty($this->request->data['tree_order'])) { $items = json_decode($this->request->data['tree_order']); if ($items) { unset($items[0]); $entities = []; foreach ($items as $key => $item) { $term = $this->Vocabularies->Terms->newEntity([ 'id' => $item->item_id, 'parent_id' => intval($item->parent_id), 'lft' => ($item->left - 1), 'rght' => ($item->right - 1), ], ['validate' => false]); $term->isNew(false); $term->dirty('id', false); $entities[] = $term; } $this->Vocabularies->Terms->unbindSluggable(); $this->Vocabularies->Terms->connection()->transactional(function () use ($entities) { foreach ($entities as $entity) { $this->Vocabularies->Terms->save($entity, ['atomic' => false]); } }); // don't trust "left" and "right" values coming from user's POST $this->Vocabularies->Terms->addBehavior('Tree', ['scope' => ['vocabulary_id' => $vocabulary->id]]); $this->Vocabularies->Terms->recover(); $this->Flash->success(__d('taxonomy', 'Vocabulary terms tree has been reordered')); } else { $this->Flash->danger(__d('taxonomy', 'Invalid information, check you have JavaScript enabled')); } $this->redirect($this->referer()); } $this->title(__d('taxonomy', 'Vocabulary’s Terms')); $this->set(compact('vocabulary', 'terms')); $this->Breadcrumb ->push('/admin/system/structure') ->push(__d('taxonomy', 'Taxonomy'), '/admin/taxonomy/manage') ->push(__d('taxonomy', 'Vocabularies'), ['plugin' => 'Taxonomy', 'controller' => 'vocabularies', 'action' => 'index']) ->push("\"{$vocabulary->name}\"", ['plugin' => 'Taxonomy', 'controller' => 'vocabularies', 'action' => 'edit', $vocabulary->id]) ->push(__d('taxonomy', 'Terms'), '#'); }
Shows a tree list of all terms within a vocabulary. @param int $id Vocabulary's ID for which render its terms @return void
entailment
public function add($vocabularyId) { $this->loadModel('Taxonomy.Vocabularies'); $vocabulary = $this->Vocabularies->get($vocabularyId); $term = $this->Vocabularies->Terms->newEntity(['vocabulary_id' => $vocabulary->id], ['validate' => false]); $this->Vocabularies->Terms->addBehavior('Tree', ['scope' => ['vocabulary_id' => $vocabulary->id]]); if ($this->request->data()) { $term = $this->Vocabularies->Terms->patchEntity($term, $this->request->data, [ 'fieldList' => [ 'parent_id', 'name', ] ]); if ($this->Vocabularies->Terms->save($term)) { $this->Flash->success(__d('taxonomy', 'Term has been created.')); if (!empty($this->request->data['action_vocabulary'])) { $this->redirect(['plugin' => 'Taxonomy', 'controller' => 'terms', 'action' => 'vocabulary', $vocabulary->id]); } elseif (!empty($this->request->data['action_add'])) { $this->redirect(['plugin' => 'Taxonomy', 'controller' => 'terms', 'action' => 'add', $vocabulary->id]); } } else { $this->Flash->danger(__d('taxonomy', 'Term could not be created, please check your information.')); } } $parentsTree = $this->Vocabularies->Terms ->find('treeList', ['spacer' => '--']) ->map(function ($link) { if (strpos($link, '-') !== false) { $link = str_replace_last('-', '- ', $link); } return $link; }); $this->title(__d('taxonomy', 'Create New Term')); $this->set(compact('vocabulary', 'term', 'parentsTree')); $this->Breadcrumb ->push('/admin/system/structure') ->push(__d('taxonomy', 'Taxonomy'), '/admin/taxonomy/manage') ->push(__d('taxonomy', 'Vocabularies'), ['plugin' => 'Taxonomy', 'controller' => 'vocabularies', 'action' => 'index']) ->push("\"{$vocabulary->name}\"", ['plugin' => 'Taxonomy', 'controller' => 'vocabularies', 'action' => 'edit', $vocabulary->id]) ->push(__d('taxonomy', 'Terms'), ['plugin' => 'Taxonomy', 'controller' => 'terms', 'action' => 'vocabulary', $vocabulary->id]) ->push(__d('taxonomy', 'Add new term'), '#'); }
Adds a new terms within the given vocabulary. @param int $vocabularyId Vocabulary's ID @return void
entailment
public function edit($id) { $this->loadModel('Taxonomy.Terms'); $term = $this->Terms->get($id, ['contain' => ['Vocabularies']]); $vocabulary = $term->vocabulary; if ($this->request->data()) { $term = $this->Terms->patchEntity($term, $this->request->data(), ['fieldList' => ['name']]); $errors = $term->errors(); if (empty($errors)) { $this->Terms->save($term, ['associated' => false]); $this->Flash->success(__d('taxonomy', 'Term has been updated')); $this->redirect($this->referer()); } else { $this->Flash->danger(__d('taxonomy', 'Term could not be updated, please check your information')); } } $this->title(__d('taxonomy', 'Editing Term')); $this->set('term', $term); $this->Breadcrumb ->push('/admin/system/structure') ->push(__d('taxonomy', 'Taxonomy'), '/admin/taxonomy/manage') ->push(__d('taxonomy', 'Vocabularies'), ['plugin' => 'Taxonomy', 'controller' => 'vocabularies', 'action' => 'index']) ->push("\"{$vocabulary->name}\"", ['plugin' => 'Taxonomy', 'controller' => 'vocabularies', 'action' => 'edit', $vocabulary->id]) ->push(__d('taxonomy', 'Terms'), ['plugin' => 'Taxonomy', 'controller' => 'terms', 'action' => 'vocabulary', $vocabulary->id]) ->push(__d('taxonomy', 'Editing term'), '#'); }
Edits the given vocabulary's term by ID. @param int $id Term's ID @return void
entailment
public function delete($id) { $this->loadModel('Taxonomy.Terms'); $term = $this->Terms->get($id); $this->Terms->addBehavior('Tree', ['scope' => ['vocabulary_id' => $term->vocabulary_id]]); $this->Terms->removeFromTree($term); if ($this->Terms->delete($term)) { $this->Flash->success(__d('taxonomy', 'Term successfully removed!')); } else { $this->Flash->danger(__d('taxonomy', 'Term could not be removed, please try again')); } $this->title(__d('taxonomy', 'Delete Term')); $this->redirect($this->referer()); }
Deletes the given term. @param int $id Term's ID @return void
entailment
public function input($fieldName, array $options = []) { if ($fieldName instanceof \Field\Model\Entity\Field) { if (!$this->_isRendering) { $this->_isRendering = true; $result = $fieldName->edit($this->_View); $this->_isRendering = false; return $result; } else { $options += ['value' => $fieldName->value, 'label' => $fieldName->label]; if ($fieldName->metadata->required) { $options['label'] .= ' *'; $options['required'] = 'required'; } $fieldName = $fieldName->get('name'); } } return parent::input($fieldName, $options); }
{@inheritDoc} Allows to render Field (EAV virtual columns) in edit mode; it triggers the event `Field.<handler>.Entity.edit`, it will try to append an `*` symbol to input label if Field has been marked as "required".
entailment
public function prefix($prefix = null) { if ($prefix !== null) { $this->_prefix = $prefix; } return $this->_prefix; }
Sets/Read input prefix. ### Example: ```php $this->Form->prefix('settings:'); echo $this->Form->input('site_name'); // outputs: <input type="text" name="settings:site_name" /> echo $this->Form->prefix(); // outputs: "settings:" $this->Form->prefix(''); echo $this->Form->prefix(); // outputs: <empty string> ``` @param string|null $prefix The prefix to be set, or leave empty to unset any previous prefix @return string Actual prefix always
entailment
public function render(Block $block, View $view) { $viewMode = $view->viewMode(); $blockRegion = isset($block->region->region) ? 'none' : $block->region->region; $cacheKey = "render_{$block->id}_{$blockRegion}_{$viewMode}"; $cache = static::cache($cacheKey); $element = 'Block.render_block'; if ($cache !== null) { $element = $cache; } else { $try = [ "Block.render_block_{$blockRegion}_{$viewMode}", "Block.render_block_{$blockRegion}", 'Block.render_block' ]; foreach ($try as $possible) { if ($view->elementExists($possible)) { $element = static::cache($cacheKey, $possible); break; } } } return $view->element($element, compact('block', 'options')); }
{@inheritDoc} This method will look for certain view elements when rendering each custom block, 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 block based on theme's region & view-mode render_block_[region-name]_[view-mode].ctp Renders the given block based on theme's **region-name and view-mode**, for example: - render_block_left-sidebar_full.ctp: Render for blocks in `left-sidebar` region when view-mode is `full` - render_block_left-sidebar_search-result.ctp: Render for blocks in `left-sidebar` region when view-mode is `search-result`. - render_block_footer_search-result.ctp: Render for blocks in `footer` region when view-mode is `search-result`. ### Render block based on theme's region render_block_[region-name].ctp Similar as before, but based on theme's **region-name** (and any view-mode), for example: - render_block_right-sidebar.ctp: Render for blocks in `right-sidebar` region. - render_block_left-sidebar.ctp: Render for blocks in `left-sidebar` region. ### Default render_block.ctp This is the global render, if none of the above renders 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
protected function _parseRange($value) { $range = parent::_parseRange($value); $lower = $this->_normalize($range['lower']); $upper = $this->_normalize($range['upper']); if (strtotime($lower) > strtotime($upper)) { list($lower, $upper) = [$upper, $lower]; } return [ 'lower' => $lower, 'upper' => $upper, ]; }
Parses and extracts lower and upper date values from the given range given as `lower..upper`. Dates must be in YEAR-MONTH-DATE format. e.g. `2014-12-30`. It automatically reorder dates if they are given in inversed order (upper..lower). @param string $value A date range given as `<dateLower>..<dateUpper>`. For instance. `2014-12-30..2015-12-30` @return array Associative array with two keys: `lower` and `upper`, returned dates are fully PHP compliant
entailment
protected function _normalize($date) { $date = preg_replace('/[^0-9\-]/', '', $date); $parts = explode('-', $date); $year = date('Y'); $month = 1; $day = 1; if (!empty($parts[0]) && 1 <= intval($parts[0]) && intval($parts[0]) <= 32767 ) { $year = intval($parts[0]); } if (!empty($parts[1]) && 1 <= intval($parts[1]) && intval($parts[1]) <= 12 ) { $month = intval($parts[1]); } if (!empty($parts[2]) && 1 <= intval($parts[2]) && intval($parts[2]) <= 31 ) { $day = intval($parts[2]); } return date('Y-m-d', strtotime("{$year}-{$month}-{$day}")); }
Normalizes the given date. @param string $date Date to normalize @return string Date formated as `Y-m-d`
entailment
public function info() { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->info(); } return []; }
Gets handler information. @return array
entailment
public function viewModeSettings(View $view, $viewMode) { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->viewModeSettings($this, $view, $viewMode); } return ''; }
Renders view-mode's settings form elements. @param \CMS\View\View $view View instance being used @param string $viewMode View-mode name for which render its settings @return void
entailment
public function defaultViewModeSettings($viewMode) { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->defaultViewModeSettings($this, $viewMode); } return []; }
Gets default settings for the given view-mode. @param string $viewMode Name of the view mode for which get its default settings values @return array
entailment
public function beforeAttach() { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->beforeAttach($this); } }
Triggers callback. @return bool|null
entailment
public function afterAttach() { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->afterAttach($this); } }
Triggers callback. @return void
entailment
public function beforeDetach() { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->beforeDetach($this); } }
Triggers callback. @return bool|null
entailment
public function afterDetach() { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->afterDetach($this); } }
Triggers callback. @return void
entailment
public function run() { $isPost = $_SERVER["REQUEST_METHOD"] == 'POST'; $src = $_SERVER["REQUEST_METHOD"] == 'POST' ? $_POST : $_GET; if ($isPost && !$src && $rawPostData = @file_get_contents('php://input')) { // for support IE XDomainRequest() $parts = explode('&', $rawPostData); foreach($parts as $part) { list($key, $value) = array_pad(explode('=', $part), 2, ''); $src[$key] = rawurldecode($value); } $_POST = $this->input_filter($src); $_REQUEST = $this->input_filter(array_merge_recursive($src, $_REQUEST)); } $cmd = isset($src['cmd']) ? $src['cmd'] : ''; $args = array(); if (!function_exists('json_encode')) { $error = $this->elFinder->error(elFinder::ERROR_CONF, elFinder::ERROR_CONF_NO_JSON); $this->output(array('error' => '{"error":["'.implode('","', $error).'"]}', 'raw' => true)); } if (!$this->elFinder->loaded()) { $this->output(array('error' => $this->elFinder->error(elFinder::ERROR_CONF, elFinder::ERROR_CONF_NO_VOL), 'debug' => $this->elFinder->mountErrors)); } // telepat_mode: on if (!$cmd && $isPost) { $this->output(array('error' => $this->elFinder->error(elFinder::ERROR_UPLOAD, elFinder::ERROR_UPLOAD_TOTAL_SIZE), 'header' => 'Content-Type: text/html')); } // telepat_mode: off if (!$this->elFinder->commandExists($cmd)) { $this->output(array('error' => $this->elFinder->error(elFinder::ERROR_UNKNOWN_CMD))); } // collect required arguments to exec command foreach ($this->elFinder->commandArgsList($cmd) as $name => $req) { $arg = $name == 'FILES' ? $_FILES : (isset($src[$name]) ? $src[$name] : ''); if (!is_array($arg)) { $arg = trim($arg); } if ($req && (!isset($arg) || $arg === '')) { $this->output(array('error' => $this->elFinder->error(elFinder::ERROR_INV_PARAMS, $cmd))); } $args[$name] = $arg; } $args['debug'] = isset($src['debug']) ? !!$src['debug'] : false; $this->output($this->elFinder->exec($cmd, $this->input_filter($args))); }
Execute elFinder command and output result @return void @author Dmitry (dio) Levashov
entailment
protected function output(array $data) { $header = isset($data['header']) ? $data['header'] : $this->header; unset($data['header']); if ($header) { if (is_array($header)) { foreach ($header as $h) { header($h); } } else { header($header); } } if (isset($data['pointer'])) { rewind($data['pointer']); fpassthru($data['pointer']); if (!empty($data['volume'])) { $data['volume']->close($data['pointer'], $data['info']['hash']); } exit(); } else { if (!empty($data['raw']) && !empty($data['error'])) { exit($data['error']); } else { exit(json_encode($data)); } } }
Output json @param array data to output @return void @author Dmitry (dio) Levashov
entailment
private function input_filter($args) { static $magic_quotes_gpc = NULL; if ($magic_quotes_gpc === NULL) $magic_quotes_gpc = (version_compare(PHP_VERSION, '5.4', '<') && get_magic_quotes_gpc()); if (is_array($args)) { return array_map(array(& $this, 'input_filter'), $args); } $res = str_replace("\0", '', $args); $magic_quotes_gpc && ($res = stripslashes($res)); return $res; }
Remove null & stripslashes applies on "magic_quotes_gpc" @param mixed $args @return mixed @author Naoki Sawada
entailment
public static function create($package) { static::_init(); foreach (static::$_detectors as $name => $callable) { $result = $callable($package); if ($result instanceof BasePackage) { return $result; } } return new GenericPackage($package, '', ''); }
Given a full package name, returns an instance of an object representing that package. If no matching package is found, `GenericPackage` will be used by default. @param string $package Full package name. e.g. `vendor-name/package-name` @return \CMS\Core\Package\BasePackage
entailment
protected static function _init() { if (static::$_initialized) { return; } static::$_detectors['plugin'] = function ($package) { return static::_getPlugin($package); }; static::$_detectors['library'] = function ($package) { return static::_getLibrary($package); }; static::$_detectors['thirdParty'] = function ($package) { return static::_getThirdParty($package); }; static::$_initialized = true; }
Initializes this class. @return void
entailment
protected static function _getPlugin($package) { list(, $plugin) = packageSplit($package, true); if (Plugin::exists($plugin)) { return new PluginPackage( quickapps("plugins.{$plugin}.name"), quickapps("plugins.{$plugin}.path") ); } return false; }
Tries to get a QuickAppsCMS plugin. @param string $package Full package name @return bool|\CMS\Core\Package\PluginPackage
entailment
protected static function _getThirdParty($package) { list($vendor, $packageName) = packageSplit($package); $packageJson = normalizePath(VENDOR_INCLUDE_PATH . "/{$vendor}/{$packageName}/composer.json"); if (is_readable($packageJson)) { $installedJson = normalizePath(VENDOR_INCLUDE_PATH . "composer/installed.json"); if (is_readable($installedJson)) { $json = (array)json_decode(file_get_contents($installedJson), true); foreach ($json as $pkg) { if (strtolower($pkg['name']) === strtolower($package)) { return new ThirdPartyPackage($package, dirname($packageJson), $pkg['version']); } } } } return false; }
Tries to get package that represents a third party library. - Package must exists on `VENDOR_PATH/vendor-name/package-name/`. - Its composer.json file must exists as well. - Package must be registered on Composer's "installed.json" file. @param string $package Full package name @return bool|\CMS\Core\Package\ThirdPartyPackage
entailment
public static function run($args, $extra = []) { static::$_out = ''; $argv = explode(' ', "dummy-shell.php {$args}"); $dispatcher = new WebShellDispatcher($argv); ob_start(); $response = $dispatcher->dispatch($extra); static::$_out = ob_get_clean(); return (int)($response === 0); }
Run the dispatcher. @param string $args Commands to run @param array $extra Extra parameters @return int Result of the shell process. 1 on success, 0 otherwise.
entailment
protected function _createShell($className, $shortName) { $instance = parent::_createShell($className, $shortName); $webIo = new ConsoleIo( new WebConsoleOutput(), new WebConsoleOutput(), new WebConsoleInput() ); $instance->io($webIo); return $instance; }
Create the given shell name, and set the plugin property. @param string $className The class name to instantiate @param string $shortName The plugin-prefixed shell name @return \Cake\Console\Shell A shell instance.
entailment
public function getOptionParser() { $parser = parent::getOptionParser(); $parser ->description('Database maintenance commands.') ->addSubcommand('export', [ 'help' => 'Export database to portable format.', 'parser' => $this->DatabaseExport->getOptionParser(), ]) ->addSubcommand('tables', [ 'help' => 'List all database tables.', ]) ->addSubcommand('connection', [ 'help' => 'Show connection settings.', ]); return $parser; }
Gets the option parser instance and configures it. @return \Cake\Console\ConsoleOptionParser
entailment
public function main() { $this->out('<info>Database Shell</info>'); $this->hr(); $this->out(__d('system', '[1] Export database')); $this->out(__d('system', '[2] List tables')); $this->out(__d('system', '[3] Show connection')); $this->out(__d('system', '[H]elp')); $this->out(__d('system', '[Q]uit')); $choice = (string)strtolower($this->in(__d('system', 'What would you like to do?'), ['1', '2', '3', 'H', 'Q'])); switch ($choice) { case '1': $this->dispatchShell('System.database export -m full'); break; case '2': $this->tables(); break; case '3': $this->connection(); break; case 'h': $this->out($this->OptionParser->help()); break; case 'q': return $this->_stop(); default: $this->out(__d('system', 'You have made an invalid selection. Please choose a command to execute by entering 1, 2, 3, H, or Q.')); } $this->hr(); $this->main(); }
Override main() for help message hook @return void
entailment
public function tables() { $db = ConnectionManager::get('default'); $db->connect(); $schemaCollection = $db->schemaCollection(); $tables = $schemaCollection->listTables(); foreach ($tables as $table) { $this->out(sprintf('- %s', $table)); } }
Displays a list of all table names in database. @return void
entailment
public function connection() { $db = ConnectionManager::get('default'); foreach ($db->config() as $key => $value) { if (is_array($value)) { continue; } $this->out(sprintf('- %s: %s', $key, $value)); } }
Display database connection information. @return void
entailment
public function load($options = []) { if (Configure::read('debug')) { return $this->_View->Html->script('Jquery.jquery-1.11.2.js', $options); } return $this->_View->Html->script('Jquery.jquery-1.11.2.min.js', $options); }
Loads jQuery's core library. ### Options - `block` Set to true to append output to view block "script" or provide custom block name. - `once` Whether or not the script should be checked for uniqueness. If true scripts will only be included once, use false to allow the same script to be included more than once per request. - `plugin` False value will prevent parsing path as a plugin. - `fullBase` If true the url will get a full address for the script file. @param array $options Array of options, and html attributes see above. @return mixed String of `<script />` tags or null if block is specified in options or if $once is true and the file has been included before.
entailment
public function ui() { $args = func_get_args(); $files = []; $options = []; $out = ''; foreach ($args as $file) { if (is_array($file)) { $options = $file; continue; } $file = 'Jquery.ui/' . strtolower($file); if (!str_ends_with($file, '.js')) { $file .= '.js'; } if ($file != 'Jquery.ui/core.js') { $files[] = $file; } } if (empty($files)) { $files[] = Configure::read('debug') ? 'Jquery.jquery-ui.js' : 'Jquery.jquery-ui.min.js'; } else { array_unshift($files, 'Jquery.ui/core.js'); } foreach ($files as $file) { $out .= (string)$this->_View->Html->script($file, $options); } if (empty($out)) { return null; } return $out; }
Loads the given jQuery UI components JS files. You can indicate the name of the JS files to include as follow: ```php $this->jQuery->ui('mouse', 'droppable', 'widget', ...); ``` You can provide an array of options for HtmlHelper::script() as follow: ```php $this->jQuery->ui('mouse', 'droppable', ['block' => 'true'], 'widget', ...); ``` If no component is given, all components (concatenated as a single JS file) will be loaded at once. @return mixed String of `<script />` tags or null if block is specified in options or if $once is true and the file has been included before
entailment
public function theme($themeName = null, array $options = []) { if (is_array($themeName)) { $options = $themeName; $themeName = null; } if ($themeName === null) { $default = Configure::read('jQueryUI.defaultTheme'); $themeName = $default ? $default : 'Jquery.ui-lightness'; } $out = ''; list($plugin, $theme) = pluginSplit($themeName); $plugin = !$plugin ? 'Jquery' : $plugin; $out .= (string)$this->_View->Html->css("{$plugin}.ui/{$theme}/theme.css", $options); if (Configure::read('debug')) { $out .= (string)$this->_View->Html->css("{$plugin}.ui/{$theme}/jquery-ui.css", $options); } else { $out .= (string)$this->_View->Html->css("{$plugin}.ui/{$theme}/jquery-ui.min.css", $options); } if (empty($out)) { return; } return $out; }
Loads all CSS and JS files for the given UI theme. ### Usage You can indicate UI themes provided by an specific plugin: ```php // Theme's assets should be located at `MyPlugin/webroot/css/ui/flick/` $this->jQuery->theme('MyPlugin.flick'); ``` If no plugin syntax is given, **Jquery** plugin will be used by default: ```php // Theme's assets are located at `Jquery/webroot/css/ui/flick/` $this->jQuery->theme('flick'); ``` If you want to use default theme ($themeName = null) and provide some options (second argument), you can do as follow: ```php $this->jQuery->theme(['block' => true]); ``` ### Theme auto-detect If no theme is given ($themeName = null) this method will try to: - Use global parameter `jQueryUI.defaultTheme`. - Use `Jquery.ui-lightness` otherwise. ### Default theme You can define the global parameter `jQueryUI.defaultTheme` in your site's `bootstrap.php` to indicate the theme to use by default. For instance: ```php Configure::write('jQueryUI.defaultTheme', 'MyPlugin.ui-darkness'); ``` The `MyPlugin.ui-darkness` theme will be used by default every time this method is used with no arguments: ```php $this->jQuery->theme(); ``` Theme's assets should be located at `MyPlugin/webroot/css/ui/ui-darkness/` ### Options - `block` Set to true to append output to view block "css" or provide custom block name. - `once` Whether or not the css file should be checked for uniqueness. If true css files will only be included once, use false to allow the same css to be included more than once per request. - `plugin` False value will prevent parsing path as a plugin. - `rel` Defaults to 'stylesheet'. If equal to 'import' the stylesheet will be imported. - `fullBase` If true the URL will get a full address for the css file. @param string|array|null $themeName Name of the theme to load, or array of options (will replace $options) to use default theme with options @param array $options Array of options and HTML arguments @return string CSS <link /> or <style /> tag, depending on the type of link.
entailment
public function scope(Query $query, $bundle = null) { $whereClause = $query->clause('where'); if (!$whereClause) { return $query; } $whereClause->traverse(function (&$expression) use ($bundle, $query) { if ($expression instanceof ExpressionInterface) { $expression = $this->_inspectExpression($expression, $bundle, $query); } }); return $query; }
{@inheritDoc} Look for virtual columns in query's WHERE clause. @param \Cake\ORM\Query $query The query to scope @param string|null $bundle Consider attributes only for a specific bundle @return \Cake\ORM\Query The modified query object
entailment
protected function _inspectExpression(ExpressionInterface $expression, $bundle, Query $query) { if ($expression instanceof Comparison) { $expression = $this->_inspectComparisonExpression($expression, $bundle, $query); } elseif ($expression instanceof UnaryExpression) { $expression = $this->_inspectUnaryExpression($expression, $bundle, $query); } return $expression; }
Analyzes the given WHERE expression, looks for virtual columns and alters the expressions according. @param \Cake\Database\ExpressionInterface $expression Expression to scope @param string $bundle Consider attributes only for a specific bundle @param \Cake\ORM\Query $query The query instance this expression comes from @return \Cake\Database\ExpressionInterface The altered expression (or not)
entailment
protected function _inspectComparisonExpression(Comparison $expression, $bundle, Query $query) { $field = $expression->getField(); $column = is_string($field) ? $this->_toolbox->columnName($field) : ''; if (empty($column) || in_array($column, (array)$this->_table->schema()->columns()) || // ignore real columns !in_array($column, $this->_toolbox->getAttributeNames()) || !$this->_toolbox->isSearchable($column) // ignore no searchable virtual columns ) { // nothing to alter return $expression; } $attr = $this->_toolbox->attributes($bundle)[$column]; $value = $expression->getValue(); $type = $this->_toolbox->getType($column); $conjunction = $expression->getOperator(); $conditions = [ 'EavValues.eav_attribute_id' => $attr['id'], "EavValues.value_{$type} {$conjunction}" => $value, ]; // subquery scope $subQuery = TableRegistry::get('Eav.EavValues') ->find() ->select('EavValues.entity_id') ->where($conditions) ->order(['EavValues.id' => 'DESC']); // some variables $pk = $this->_tablePrimaryKey(); $driverClass = $this->_toolbox->driver($query); switch ($driverClass) { case 'sqlite': $concat = implode(' || ', $pk); $field = "({$concat} || '')"; break; case 'sqlserver': $pk = array_map(function ($keyPart) { return "CAST({$keyPart} AS VARCHAR)"; }, $pk); $concat = implode(' + ', $pk); $field = "({$concat} + '')"; break; case 'mysql': case 'postgres': default: $concat = implode(', ', $pk); $field = "CONCAT({$concat}, '')"; break; } // compile query, faster than raw subquery in most cases $ids = $subQuery->all()->extract('entity_id')->toArray(); $ids = empty($ids) ? ['-1'] : $ids; $expression->setField($field); $expression->setValue($ids); $expression->setOperator('IN'); $class = new \ReflectionClass($expression); $property = $class->getProperty('_type'); $property->setAccessible(true); $property->setValue($expression, 'string'); $property = $class->getProperty('_isMultiple'); $property->setAccessible(true); $property->setValue($expression, true); return $expression; }
Analyzes the given comparison expression and alters it according. @param \Cake\Database\Expression\Comparison $expression Comparison expression @param string $bundle Consider attributes only for a specific bundle @param \Cake\ORM\Query $query The query instance this expression comes from @return \Cake\Database\Expression\Comparison Scoped expression (or not)
entailment
protected function _inspectUnaryExpression(UnaryExpression $expression, $bundle, Query $query) { $class = new \ReflectionClass($expression); $property = $class->getProperty('_value'); $property->setAccessible(true); $value = $property->getValue($expression); if ($value instanceof IdentifierExpression) { $field = $value->getIdentifier(); $column = is_string($field) ? $this->_toolbox->columnName($field) : ''; if (empty($column) || in_array($column, (array)$this->_table->schema()->columns()) || // ignore real columns !in_array($column, $this->_toolbox->getAttributeNames($bundle)) || !$this->_toolbox->isSearchable($column) // ignore no searchable virtual columns ) { // nothing to alter return $expression; } $pk = $this->_tablePrimaryKey(); $driverClass = $this->_toolbox->driver($query); switch ($driverClass) { case 'sqlite': $concat = implode(' || ', $pk); $field = "({$concat} || '')"; break; case 'mysql': case 'postgres': case 'sqlserver': default: $concat = implode(', ', $pk); $field = "CONCAT({$concat}, '')"; break; } $attr = $this->_toolbox->attributes($bundle)[$column]; $type = $this->_toolbox->getType($column); $subQuery = TableRegistry::get('Eav.EavValues') ->find() ->select("EavValues.value_{$type}") ->where([ 'EavValues.entity_id' => $field, 'EavValues.eav_attribute_id' => $attr['id'] ]) ->order(['EavValues.id' => 'DESC']) ->limit(1) ->sql(); $subQuery = str_replace([':c0', ':c1'], [$field, $attr['id']], $subQuery); $property->setValue($expression, "({$subQuery})"); } return $expression; }
Analyzes the given unary expression and alters it according. @param \Cake\Database\Expression\UnaryExpression $expression Unary expression @param string $bundle Consider attributes only for a specific bundle @param \Cake\ORM\Query $query The query instance this expression comes from @return \Cake\Database\Expression\UnaryExpression Scoped expression (or not)
entailment
protected function _tablePrimaryKey() { $alias = $this->_table->alias(); $pk = $this->_table->primaryKey(); if (!is_array($pk)) { $pk = [$pk]; } $pk = array_map(function ($key) use ($alias) { return "{$alias}.{$key}"; }, $pk); return $pk; }
Gets table's PK as an array. @return array
entailment
public function region($name, $options = [], $force = false) { if (empty($this->_regions[$name]) || $force) { $this->_regions[$name] = new Region($this, $name, $options); } return $this->_regions[$name]; }
Defines a new theme region to be rendered. ### Usage: Merge `left-sidebar` and `right-sidebar` regions together, the resulting region limits the number of blocks it can holds to `3`: ```php echo $this->region('left-sidebar') ->append($this->region('right-sidebar')) ->blockLimit(3); ``` ### Valid options are: - `fixMissing`: When creating a region that is not defined by the theme, it will try to fix it by adding it to theme's regions if this option is set to TRUE. Defaults to NULL which automatically enables when `debug` is enabled. This option will not work when using QuickAppsCMS's core themes. (NOTE: This option will alter theme's `composer.json` file). - `theme`: Name of the theme this regions belongs to. Defaults to auto- detect. @param string $name Theme's region machine-name. e.g. `left-sidebar` @param array $options Additional options for region being created @param bool $force Whether to skip reading from cache or not, defaults to false will get from cache if exists. @return \Block\View\Region Region object @see \Block\View\Region
entailment
public function render($view = null, $layout = null) { $html = ''; if (is_object($view)) { $className = get_class($view); $args = func_get_args(); array_shift($args); $args = array_merge([$view], (array)$args); // [entity, options] $event = new Event("Render.{$className}", $this, $args); EventManager::instance()->dispatch($event); $html = $event->result; } else { if (isset($this->jQuery)) { $this->jQuery->load(['block' => true]); } if (!$this->_hasRendered) { $this->_hasRendered = true; $this->_setTitle(); $this->_setDescription(); $html = parent::render($view, $layout); } } // parse shortcodes if not layout was applied if (!$layout || !$this->autoLayout()) { $this->shortcodes($html); } return $html; }
{@inheritDoc} Overrides Cake's view rendering method. Allows to "render" objects. **Example:** ```php // $content, instance of: Content\Model\Entity\Content $this->render($content); // $block, instance of: Block\Model\Entity\Block $this->render($block); // $field, instance of: Field\Model\Entity\Field $this->render($field); ``` When rendering objects the `Render.<ClassName>` event is automatically triggered. For example, when rendering a Content Entity the following event is triggered, and event handlers should provide a HTML representation of the given object, it basically works as the `__toString()` magic method: ```php $someContent = TableRegistry::get('Content.Contents')->get(1); $this->render($someContent); // triggers: Render.Content\Model\Entity\Content ``` It is not limited to Entity instances only, you can virtually define a `Render` for any class name. You can pass an unlimited number of arguments to your `Render` as follow: ```php $this->render($someObject, $arg1, $arg2, ...., $argn); ``` Your Render event-handler may look as below: ```php public function renderMyObject(Event $event, $theObject, $arg1, $arg2, ..., $argn); ```
entailment
public function renderLayout($content, $layout = null) { $html = parent::renderLayout($content, $layout); return $this->shortcodes($html); }
{@inheritDoc} Parses shortcodes.
entailment
protected function _getElementFileName($name, $pluginCheck = true) { list($plugin, $element) = $this->pluginSplit($name, $pluginCheck); if ($plugin && ($element === 'settings' || strpos($element, 'Help/help') !== false) ) { return Plugin::classPath($plugin) . "Template/Element/{$element}{$this->_ext}"; } return parent::_getElementFileName($name, $pluginCheck); }
{@inheritDoc} Workaround patch that allows plugins and themes provide their own independent "settings.ctp" files so themes won't "override" plugin element (as themes are actually plugins and may have their own "settings.ctp"). The same goes for "help.ctp" template files. So themes and plugins can provide help information.
entailment
protected function _paths($plugin = null, $cached = true) { // TODO: remove this? as ROOT/template is already added to app's paths $paths = parent::_paths($plugin, $cached); $base = ROOT . '/templates/'; $subDirectory = $this->request->isAdmin() ? 'Back/' : 'Front/'; foreach (['Common/', $subDirectory] as $dir) { array_unshift($paths, "{$base}{$dir}"); if ($plugin !== null) { array_unshift($paths, "{$base}{$dir}Plugin/{$plugin}/"); } } return $paths; }
{@inheritDoc} Allow users to overwrite ANY template by placing it at site's **ROOT/templates/Front** and **ROOT/templates/Back** directories. These directory has the highest priority when looking for template files. So in other words, this directories behaves as some sort of "primary themes". Each directory represents a "Frontend" and "Backend" respectively. For common templates -shared across front & back- the **ROOT/templates/Common** directory can be used instead.
entailment
protected function _getLayoutFileName($name = null) { try { $filename = parent::_getLayoutFileName($name); } catch (\Exception $e) { $filename = parent::_getLayoutFileName('default'); } return $filename; }
{@inheritDoc} Adds fallback functionality, if layout is not found it uses QuickAppsCMS's `default.ctp` as it will always exists.
entailment
protected function _evaluate($viewFile, $dataForView) { $this->__viewFile = $viewFile; extract($dataForView); ob_start(); include $this->__viewFile; unset($this->__viewFile); return ob_get_clean(); }
{@inheritDoc}
entailment
protected function _setTitle() { if (empty($this->viewVars['title_for_layout'])) { $title = option('site_title'); $this->assign('title', $title); $this->set('title_for_layout', $title); } else { $this->assign('title', $this->viewVars['title_for_layout']); } }
Sets title for layout. It sets `title_for_layout` view variable, if no previous title was set on controller. Site's title will be used if not found. @return void
entailment
protected function _setDescription() { if (empty($this->viewVars['description_for_layout'])) { $description = option('site_description'); $this->assign('description', $description); $this->set('description_for_layout', $description); $this->append('meta', $this->Html->meta('description', $description)); } else { $this->assign('description', $this->viewVars['description_for_layout']); } }
Sets meta-description for layout. It sets `description_for_layout` view-variable, and appends meta-description tag to `meta` block. Site's description will be used if not found. @return void
entailment
public function beforeFilter(Event $event) { $this->_controller->set('__commentComponentLoaded__', true); $this->_controller->set('_commentFormContext', $this->config('arrayContext')); }
Called before the controller's beforeFilter method. @param Event $event The event that was triggered @return void
entailment
public function config($key = null, $value = null, $merge = true) { if ($key !== null && in_array($key, array_keys($this->_defaultConfig['settings']))) { $key = "settings.{$key}"; } if (!$this->_configInitialized) { $this->_config = $this->_defaultConfig; $this->_configInitialized = true; } if (is_array($key) || func_num_args() >= 2) { $this->_configWrite($key, $value, $merge); return $this; } return $this->_configRead($key); }
Reads/writes settings for this component or for CommentHelper class. @param string|array|null $key The key to get/set, or a complete array of configs. @param mixed|null $value The value to set. @param bool $merge Whether to merge or overwrite existing config, defaults to true. @return mixed Config value being read, or the object itself on write operations. @throws \Cake\Core\Exception\Exception When trying to set a key that is invalid.
entailment
public function post(EntityInterface $entity) { $pk = (string)TableRegistry::get($entity->source())->primaryKey(); if (empty($this->_controller->request->data['comment']) || $this->config('settings.visibility') !== 1 || !$entity->has($pk) ) { return false; } $this->_controller->loadModel('Comment.Comments'); $data = $this->_getRequestData($entity); $this->_controller->Comments->validator('commentValidation', $this->_createValidator()); $comment = $this->_controller->Comments->newEntity($data, ['validate' => 'commentValidation']); $errors = $comment->errors(); $errors = !empty($errors); if (!$errors) { $persist = true; $saved = true; $this->_controller->Comments->addBehavior('Tree', [ 'scope' => [ 'entity_id' => $data['entity_id'], 'table_alias' => $data['table_alias'], ] ]); if ($this->config('settings.use_akismet')) { $newStatus = $this->_akismetStatus($data); $comment->set('status', $newStatus); if ($newStatus == 'spam' && $this->config('settings.akismet_action') != 'mark' ) { $persist = false; } } if ($persist) { $saved = $this->_controller->Comments->save($comment); } if ($saved) { $this->_afterSave($comment); return true; // all OK } else { $errors = true; } } if ($errors) { $this->_setErrors($comment); $errorMessage = $this->config('errorMessage'); if (is_callable($errorMessage)) { $errorMessage = $errorMessage($comment, $this->_controller); } $this->_controller->Flash->danger($errorMessage, ['key' => 'commentsForm']); } return false; }
Adds a new comment for the given entity. @param \Cake\Datasource\EntityInterface $entity The entity where to attach new comment @return bool True on success, false otherwise
entailment
protected function _akismetStatus($data) { require_once Plugin::classPath('Comment') . 'Lib/Akismet.php'; try { $akismet = new \Akismet(Router::url('/'), $this->config('settings.akismet_key')); if (!empty($data['author_name'])) { $akismet->setCommentAuthor($data['author_name']); } if (!empty($data['author_email'])) { $akismet->setCommentAuthorEmail($data['author_email']); } if (!empty($data['author_web'])) { $akismet->setCommentAuthorURL($data['author_web']); } if (!empty($data['body'])) { $akismet->setCommentContent($data['body']); } if ($akismet->isCommentSpam()) { return 'spam'; } } catch (\Exception $ex) { return 'pending'; } return $data['status']; }
Calculates comment's status using akismet. @param array $data Comment's data to be validated by Akismet @return string Filtered comment's status
entailment
protected function _afterSave(EntityInterface $comment) { $successMessage = $this->config('successMessage'); if (is_callable($successMessage)) { $successMessage = $successMessage($comment, $this->_controller); } $this->_controller->Flash->success($successMessage, ['key' => 'commentsForm']); if ($this->config('redirectOnSuccess')) { $redirectTo = $this->config('redirectOnSuccess') === true ? $this->_controller->referer() : $this->config('redirectOnSuccess'); $this->_controller->redirect($redirectTo); } }
Logic triggered after comment was successfully saved. @param \Cake\Datasource\EntityInterface $comment Comment that was just saved @return void
entailment
protected function _getRequestData(EntityInterface $entity) { $pk = (string)TableRegistry::get($entity->source())->primaryKey(); $data = $this->_controller->request->data('comment'); $return = [ 'parent_id' => null, 'subject' => '', 'body' => '', 'status' => 'pending', 'author_name' => null, 'author_email' => null, 'author_web' => null, 'author_ip' => $this->_controller->request->clientIp(), 'table_alias' => $this->_getTableAlias($entity), 'entity_id' => $entity->get($pk), ]; if (!empty($this->_controller->request->data['comment'])) { $data = $this->_controller->request->data['comment']; } if ($this->_controller->request->is('userLoggedIn')) { $return['user_id'] = user()->id; $return['author_name'] = null; $return['author_email'] = null; $return['author_web'] = null; } else { $return['author_name'] = !empty($data['author_name']) ? h($data['author_name']) : null; $return['author_email'] = !empty($data['author_email']) ? h($data['author_email']) : null; $return['author_web'] = !empty($data['author_web']) ? h($data['author_web']) : null; } if (!empty($data['subject'])) { $return['subject'] = h($data['subject']); } if (!empty($data['parent_id'])) { // this is validated at Model side $return['parent_id'] = $data['parent_id']; } if (!empty($data['body'])) { $return['body'] = TextToolbox::process($data['body'], $this->config('settings.text_processing')); } if ($this->config('settings.auto_approve') || $this->_controller->request->is('userAdmin') ) { $return['status'] = 'approved'; } return $return; }
Extract data from request and prepares for inserting a new comment for the given entity. @param \Cake\Datasource\EntityInterface $entity Entity used to guess table name @return array
entailment
protected function _getTableAlias(EntityInterface $entity) { $alias = $entity->source(); if (mb_strpos($alias, '.') !== false) { $parts = explode('.', $alias); $alias = array_pop($parts); } return strtolower($alias); }
Get table alias for the given entity. @param \Cake\Datasource\EntityInterface $entity The entity @return string Table alias
entailment
protected function _setErrors(Comment $comment) { $arrayContext = $this->config('arrayContext'); foreach ((array)$comment->errors() as $field => $msg) { $arrayContext['errors']['comment'][$field] = $msg; } $this->config('arrayContext', $arrayContext); $this->_controller->set('_commentFormContext', $this->config('arrayContext')); }
Prepares error messages for FormHelper. @param \Comment\Model\Entity\Comment $comment The invalidated comment entity to extract error messages @return void
entailment
protected function _loadSettings() { $settings = plugin('Comment')->settings(); foreach ($settings as $k => $v) { $this->config("settings.{$k}", $v); } }
Fetch settings from data base and merges with this component's configuration. @return array
entailment
protected function _createValidator() { $config = $this->config(); if ($config['validator'] instanceof Validator) { return $config['validator']; } $this->_controller->loadModel('Comment.Comments'); if ($this->_controller->request->is('userLoggedIn')) { // logged user posting $validator = $this->_controller->Comments->validationDefault(new Validator()); $validator ->requirePresence('user_id') ->notEmpty('user_id', __d('comment', 'Invalid user.')) ->add('user_id', 'checkUserId', [ 'rule' => function ($value, $context) { if (!empty($value)) { $valid = TableRegistry::get('User.Users')->find() ->where(['Users.id' => $value, 'Users.status' => 1]) ->count() === 1; return $valid; } return false; }, 'message' => __d('comment', 'Invalid user, please try again.'), 'provider' => 'table', ]); } elseif ($this->config('settings.allow_anonymous')) { // anonymous user posting $validator = $this->_controller->Comments->validator('anonymous'); } else { // other case $validator = new Validator(); } if ($this->config('settings.use_captcha')) { $validator ->add('body', 'humanCheck', [ 'rule' => function ($value, $context) { return CaptchaManager::adapter()->validate($this->_controller->request); }, 'message' => __d('comment', 'We were not able to verify you as human. Please try again.'), 'provider' => 'table', ]); } return $validator; }
Creates a validation object on the fly. @return \Cake\Validation\Validator
entailment
protected function _getViewModeSettings() { $viewMode = $this->viewMode(); $settings = []; if (!empty($this->metadata->view_modes[$viewMode])) { $settings = $this->metadata->view_modes[$viewMode]; } return $settings; }
Gets field's View Mode's settings for the in-use View Mode. @return array
entailment
public function getOptionParser() { $parser = parent::getOptionParser(); $parser ->description(__d('installer', 'Theme maintenance commands.')) ->addSubcommand('install', [ 'help' => __d('installer', 'Install a new theme.'), 'parser' => $this->PluginInstall->getOptionParser(), ]) ->addSubcommand('uninstall', [ 'help' => __d('installer', 'Uninstalls an existing theme.'), 'parser' => $this->PluginUninstall->getOptionParser(), ]) ->addSubcommand('change', [ 'help' => __d('installer', 'Change theme in use.'), 'parser' => $this->ThemeActivation->getOptionParser(), ]); return $parser; }
Gets the option parser instance and configures it. @return \Cake\Console\ConsoleOptionParser
entailment
public function main() { $this->out(__d('installer', '<info>Themes Shell</info>')); $this->hr(); $this->out(__d('installer', '[1] Install new theme')); $this->out(__d('installer', '[2] Remove an existing theme')); $this->out(__d('installer', '[3] Change site theme')); $this->out(__d('installer', '[H]elp')); $this->out(__d('installer', '[Q]uit')); $choice = (string)strtolower($this->in(__d('installer', 'What would you like to do?'), ['1', '2', '3', 'H', 'Q'])); switch ($choice) { case '1': $this->_install(); break; case '2': $this->_uninstall(); break; case '3': $this->_change(); break; case 'h': $this->out($this->OptionParser->help()); break; case 'q': return $this->_stop(); default: $this->out(__d('installer', 'You have made an invalid selection. Please choose a command to execute by entering 1, 2, 3, H, or Q.')); } $this->hr(); $this->main(); }
Override main() for help message hook @return void
entailment
protected function _install() { $message = __d('installer', "Please provide a theme source, it can be either an URL or a filesystem path to a ZIP/directory within your server?\n[Q]uit"); while (true) { $source = $this->in($message); if (strtoupper($source) === 'Q') { $this->err(__d('installer', 'Installation aborted')); break; } else { $this->out(__d('installer', 'Starting installation...'), 0); $task = $this->dispatchShell("Installer.plugins install -s \"{$source}\" --theme -a"); if ($task === 0) { $this->_io->overwrite(__d('installer', 'Starting installation... successfully installed!'), 2); $this->out(); break; } else { $this->_io->overwrite(__d('installer', 'Starting installation... failed!'), 2); $this->out(); } } } $this->out(); }
Installs a new theme. @return void
entailment
protected function _uninstall() { $allThemes = plugin() ->filter(function ($plugin) { return $plugin->isTheme; }) ->toArray(); $index = 1; $this->out(); foreach ($allThemes as $plugin) { $allThemes[$index] = $plugin; $this->out(__d('installer', '[{0, number}] {1}', [$index, $plugin->humanName])); $index++; } $this->out(); $message = __d('installer', "Which theme would you like to uninstall?\n[Q]uit"); while (true) { $in = trim($this->in($message)); if (strtoupper($in) === 'Q') { $this->err(__d('installer', 'Operation aborted')); break; } elseif (intval($in) < 1 || !isset($allThemes[intval($in)])) { $this->err(__d('installer', 'Invalid option')); } else { $plugin = plugin($allThemes[$in]->name()); $this->hr(); $this->out(__d('installer', '<info>The following theme will be uninstalled</info>')); $this->hr(); $this->out(__d('installer', 'Name: {0}', $plugin->name)); $this->out(__d('installer', 'Description: {0}', $plugin->composer['description'])); $this->out(__d('installer', 'Path: {0}', $plugin->path)); $this->hr(); $this->out(); $confirm = $this->in(__d('installer', 'Please type in "{0}" to uninstall', $allThemes[$in]->name)); if ($confirm === $allThemes[$in]->name) { $task = $this->dispatchShell("Installer.plugins uninstall -p {$allThemes[$in]->name}"); if ($task === 0) { $this->out(__d('installer', 'Plugin uninstalled!')); Plugin::dropCache(); } else { $this->err(__d('installer', 'Plugin could not be uninstalled.'), 2); $this->out(); } } else { $this->err(__d('installer', 'Confirmation failure, operation aborted!')); } break; } } $this->out(); }
Removes an existing theme. @return void
entailment
protected function _change() { $disabledThemes = plugin() ->filter(function ($theme) { return $theme->isTheme && !in_array($theme->name, [option('front_theme'), option('back_theme')]); }) ->toArray(); if (!count($disabledThemes)) { $this->err(__d('installer', '<info>There are no disabled themes!</info>')); $this->out(); return; } $index = 1; $this->out(); foreach ($disabledThemes as $theme) { $disabledThemes[$index] = $theme; $this->out( __d('installer', '[{0, number, integer}] {1} [{2}]', [ $index, $theme->humanName, ($theme->isAdmin ? __d('installer', 'backend') : __d('installer', 'frontend')), ]) ); $index++; } $this->out(); $message = __d('installer', "Which theme 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($disabledThemes[intval($in)])) { $this->err(__d('installer', 'Invalid option')); } else { $task = $this->dispatchShell("Installer.themes change -t {$disabledThemes[$in]->name}"); if ($task === 0) { $this->out(__d('installer', 'Theme changed!')); Plugin::dropCache(); } else { $this->err(__d('installer', 'Theme could not be changed.'), 2); $this->out(); } break; } } $this->out(); }
Switch site's theme. @return void
entailment
public function index(EntityInterface $entity) { $set = $this->_table->SearchDatasets->find() ->where([ 'entity_id' => $this->_entityId($entity), 'table_alias' => $this->config('tableAlias'), ]) ->limit(1) ->first(); if (!$set) { $set = $this->_table->SearchDatasets->newEntity([ 'entity_id' => $this->_entityId($entity), 'table_alias' => $this->config('tableAlias'), 'words' => '', ]); } // We add starting and trailing space to allow LIKE %something-to-match% $extractor = $this->config('wordsExtractor'); $set = $this->_table->SearchDatasets->patchEntity($set, [ 'words' => ' ' . $extractor($entity) . ' ' ]); return (bool)$this->_table->SearchDatasets->save($set); }
{@inheritDoc}
entailment
public function delete(EntityInterface $entity) { $this->_table->SearchDatasets->deleteAll([ 'entity_id' => $this->_entityId($entity), 'table_alias' => $this->config('tableAlias'), ]); return true; }
{@inheritDoc}
entailment
public function get(EntityInterface $entity) { return $this->_table->SearchDatasets->find() ->where([ 'entity_id' => $this->_entityId($entity), 'table_alias' => $this->config('tableAlias'), ]) ->limit(1) ->first(); }
{@inheritDoc}
entailment
public function search($criteria, Query $query, array $options = []) { $tokens = $this->tokenizer($criteria); $options += [ 'missingOperators' => 'event', 'tokenDecorator' => function ($t) { return $t; }, ]; if (!empty($tokens)) { $query->innerJoinWith('SearchDatasets'); $decorator = $options['tokenDecorator']; $operators = $this->_table->behaviors() ->get('Searchable') ->config('operators'); foreach ($tokens as $token) { $token = $decorator($token); $method = '_scopeWords'; if (!($token instanceof TokenInterface)) { continue; } if ($token->isOperator()) { $method = '_scopeOperator'; $operatorName = mb_strtolower($token->operatorName()); if (!isset($operators[$operatorName])) { switch ($options['missingOperators']) { case 'ignore': $method = null; break; case 'words': $method = '_scopeWords'; break; case 'event': default: // `event` is how missing operator are handled by default by // Searchable Behavior, so no specific action is required. break; } } } if ($method) { $query = $this->$method($query, $token); } } } return $query; }
{@inheritDoc} It looks for search-criteria and applies them over the query object. For example, given the criteria below: "this phrase" -"and not this one" Alters the query object as follow: ```php $query->where([ 'indexed_words LIKE' => '%this phrase%', 'indexed_words NOT LIKE' => '%and not this one%' ]); ``` The `AND` & `OR` keywords are allowed to create complex conditions. For example: "this phrase" OR -"and not this one" AND "this" Will produce something like: ```php $query ->where(['indexed_words LIKE' => '%this phrase%']) ->orWhere(['indexed_words NOT LIKE' => '%and not this one%']); ->andWhere(['indexed_words LIKE' => '%this%']); ``` ### Options - `missingOperators`: Controls what to do when an undefined operator is found. Possible values are: - `event` (default): Triggers an event so other parts of the system can react to any missing operator. - `ignore`: Ignore any undefined operator. - `words`: Converts operator information into a set of literal words. - `tokenDecorator`: Callable function which is applied to every token before it gets applied. Retuning anything that is not a `TokenInterface` will skip that token from being used.
entailment
protected function _scopeOperator(Query $query, TokenInterface $token) { return $this->_table->applySearchOperator($query, $token); }
Scopes the given query using the given operator token. @param \Cake\ORM\Query $query The query to scope @param \Search\Token $token Token describing an operator. e.g `-op_name:op_value` @return \Cake\ORM\Query Scoped query
entailment
protected function _scopeWords(Query $query, TokenInterface $token) { if ($this->_isFullTextEnabled()) { return $this->_scopeWordsInFulltext($query, $token); } $like = 'LIKE'; if ($token->negated()) { $like = 'NOT LIKE'; } // * Matches any one or more characters. // ! Matches any single character. $value = str_replace(['*', '!'], ['%', '_'], $token->value()); if ($token->where() === 'or') { $query->orWhere(["SearchDatasets.words {$like}" => "%{$value}%"]); } elseif ($token->where() === 'and') { $query->andWhere(["SearchDatasets.words {$like}" => "%{$value}%"]); } else { $query->where(["SearchDatasets.words {$like}" => "%{$value}%"]); } return $query; }
Scopes the given query using the given words token. @param \Cake\ORM\Query $query The query to scope @param \Search\TokenInterface $token Token describing a words sequence. e.g `this is a phrase` @return \Cake\ORM\Query Scoped query
entailment
protected function _scopeWordsInFulltext(Query $query, TokenInterface $token) { $value = str_replace(['*', '!'], ['*', '*'], $token->value()); $value = mb_strpos($value, '+') === 0 ? mb_substr($value, 1) : $value; if (empty($value) || in_array($value, $this->_stopWords())) { return $query; } $not = $token->negated() ? 'NOT' : ''; $value = str_replace(["'", '@'], ['"', ' '], $value); $conditions = ["{$not} MATCH(SearchDatasets.words) AGAINST('{$value}' IN BOOLEAN MODE) > 0"]; if ($token->where() === 'or') { $query->orWhere($conditions); } elseif ($token->where() === 'and') { $query->andWhere($conditions); } else { $query->where($conditions); } return $query; }
Similar to "_scopeWords" but using MySQL's fulltext indexes. @param \Cake\ORM\Query $query The query to scope @param \Search\TokenInterface $token Token describing a words sequence. e.g `this is a phrase` @return \Cake\ORM\Query Scoped query
entailment
protected function _isFullTextEnabled() { if (!$this->config('fulltext')) { return false; } static $enabled = null; if ($enabled !== null) { return $enabled; } list(, $driverClass) = namespaceSplit(strtolower(get_class($this->_table->connection()->driver()))); if ($driverClass != 'mysql') { $enabled = false; return false; } $schema = $this->_table->SearchDatasets->schema(); foreach ($schema->indexes() as $index) { $info = $schema->index($index); if (in_array('words', $info['columns']) && strtolower($info['type']) == 'fulltext' ) { $enabled = true; return true; } } $enabled = false; return false; }
Whether FullText index is available or not and should be used. @return bool True if enabled and should be used, false otherwise
entailment
protected function _stopWords() { $conn = $this->_table->find()->connection(); $cacheKey = $conn->configName() . '_generic_engine_stopwords_list'; if ($cache = Cache::read($cacheKey, '_cake_model_')) { return (array)$cache; } $words = []; $sql = $conn ->execute('SELECT * FROM INFORMATION_SCHEMA.INNODB_FT_DEFAULT_STOPWORD') ->fetchAll('assoc'); foreach ((array)$sql as $row) { if (!empty($row['value'])) { $words[] = $row['value']; } } Cache::write($cacheKey, $words, '_cake_model_'); return $words; }
Gets a list of storage engine's stopwords. That is words that is considered common or Trivial enough that it is omitted from the search index and ignored in search queries @return array List of words
entailment
public function extractEntityWords(EntityInterface $entity) { $text = ''; $entityArray = $entity->toArray(); $entityArray = Hash::flatten($entityArray); foreach ($entityArray as $key => $value) { if (is_string($value) || is_numeric($value)) { $text .= " {$value}"; } } $text = str_replace(["\n", "\r"], '', trim((string)$text)); // remove new lines $text = strip_tags($text); // remove HTML tags, but keep their content $strict = $this->config('strict'); if (!empty($strict)) { // only: space, digits (0-9), letters (any language), ".", ",", "-", "_", "/", "\" $pattern = is_string($strict) ? $strict : '[^\p{L}\p{N}\s\@\.\,\-\_\/\\0-9]'; $text = preg_replace('/' . $pattern . '/ui', ' ', $text); } $text = trim(preg_replace('/\s{2,}/i', ' ', $text)); // remove double spaces $text = mb_strtolower($text); // all to lowercase $text = $this->_filterText($text); // filter $text = iconv('UTF-8', 'UTF-8//IGNORE', mb_convert_encoding($text, 'UTF-8')); // remove any invalid character return trim($text); }
Extracts a list of words to by indexed for given entity. NOTE: Words can be repeated, this allows to search phrases. @param \Cake\Datasource\EntityInterface $entity The entity for which generate the list of words @return string Space-separated list of words. e.g. `cat dog this that`
entailment
protected function _filterText($text) { // return true means `yes, it's banned` if (is_callable($this->config('bannedWords'))) { $isBanned = function ($word) { $callable = $this->config('bannedWords'); return $callable($word); }; } else { $isBanned = function ($word) { return in_array($word, (array)$this->config('bannedWords')) || empty($word); }; } $words = explode(' ', $text); foreach ($words as $i => $w) { if ($isBanned($w)) { unset($words[$i]); } } return implode(' ', $words); }
Removes any invalid word from the given text. @param string $text The text to filter @return string Filtered text
entailment
public static function formatField(Field $field) { $timestamp = $field->value ? $field->value->getTimestamp() : 0; return DateToolbox::formatDate($field->view_mode_settings['format'], $timestamp); }
Formats the given DateField accordingly to current view-mode. @param \Field\Model\Entity\Field $field The field to be formatted @return string Formated date. e.g. `2036-01-01`
entailment
public static function createFromFormat($format, $date) { if (preg_match_all("/'([^']+)'/", $format, $matches)) { foreach ($matches[1] as $literal) { $date = str_replace($literal, '', $date); } $date = preg_replace('/\s{2,}/', ' ', $date); // remove double spaces } $date = trim($date); $format = DateToolbox::normalizeFormat($format); return date_create_from_format($format, $date); }
Converts the given $date to a valid PHP's DateTime object using a jQuery's date/time $format. @param string $format A jQuery's date/time format. e.g. `'today is:' yy-mm-dd` @param string $date A date formatted using $format. e.g. `today is: 2015-01-30` @return \DateTime|false Date object on success, false on error
entailment
public static function formatDate($format, $timestamp) { static $datesPatterns = null; static $timesPatterns = null; if ($datesPatterns === null || $timesPatterns === null) { $datesPatterns = "/\b(" . implode('|', array_keys(static::$_map['date'])) . ")\b(?![^']*'(?:(?:[^']*'){2})*[^']*$)/i"; $timesPatterns = "/\b(" . implode('|', array_keys(static::$_map['time'])) . ")\b(?![^']*'(?:(?:[^']*'){2})*[^']*$)/i"; } // normalize formats $result = preg_replace_callback($datesPatterns, function ($matches) use ($timestamp) { return date(static::$_map['date'][$matches[1]], $timestamp); }, trim($format)); $result = preg_replace_callback($timesPatterns, function ($matches) use ($timestamp) { return date(static::$_map['time'][$matches[1]], $timestamp); }, $result); return str_replace('\'', '', $result); }
Formats then given UNIX timestamp using the given jQuery format. @param string $format jQuery format. e.g. `'today is:' yy-mm-dd` @param int $timestamp Date as UNIX timestamp @return string Formated date. e.g. `today is: 2018-09-09`
entailment
public static function normalizeFormat($format) { static $datesPatterns = null; static $timesPatterns = null; if ($datesPatterns === null || $timesPatterns === null) { $datesPatterns = '/(' . implode('|', array_keys(static::$_map['date'])) . ')/'; $timesPatterns = '/(' . implode('|', array_keys(static::$_map['time'])) . ')/'; } $format = trim($format); $format = preg_replace("/'([^']+)'/", '', $format); // remove quotes $format = preg_replace('/\s{2,}/', ' ', $format); // remove double spaces $format = trim($format); list($dateFormat, $timeFormat) = explode(' ', "{$format} "); // normalize formats $dateFormat = preg_replace_callback($datesPatterns, function ($matches) { return static::$_map['date'][$matches[1]]; }, $dateFormat); $timeFormat = preg_replace_callback($timesPatterns, function ($matches) { return static::$_map['time'][$matches[1]]; }, $timeFormat); $format = trim($dateFormat . ' ' . $timeFormat); return $format; }
Converts jQuery's date/time format to PHP's. @param string $format Date format coming from jQuery's datepicker widget. e.g. yy-mm-dd hh:mm @return string A valid date/time format to use with PHP
entailment
public static function validateDateFormat($format) { $format = str_replace(array_keys(static::$_map['date']), '', $format); // remove placeholders $format = preg_replace("/'(.*)'/", '', $format); // remove literals $format = preg_replace('/[^a-z]/i', '', $format); $format = trim($format); return empty($format); }
Validates a date format for jQuery's datepicker widget. @param string $format Format to validate. e.g. yy:mm:ddQ (invalid) @return bool
entailment
public static function validateTimeFormat($format) { $format = str_replace(array_keys(static::$_map['time']), '', $format); // remove placeholders $format = preg_replace("/'(.*)'/", '', $format); // remove literals $format = preg_replace('/[^a-z]/i', '', $format); $format = trim($format); return empty($format); }
Validates a time format for jQuery's datepicker widget. @param string $format Format to validate. e.g. hh:mm:ssA (invalid) @return bool
entailment
public static function getPHPFormat(EntityInterface $field) { $settings = $field->metadata->settings; $format = empty($settings['format']) ? 'yy-mm-dd' : $settings['format']; if ($settings['timepicker']) { $format .= ' '; if (empty($settings['time_format'])) { $format .= 'H:mm'; $format .= empty($settings['time_seconds']) ?: ':ss'; } else { $format .= $settings['time_format']; } } return static::normalizeFormat($format); }
Given a DateField instance, gets its PHP's date-format. @param \Cake\Datasource\EntityInterface $field DateField instance @return string PHP date-format for later use with date() function
entailment
public function getOptionParser() { $parser = parent::getOptionParser(); $parser ->description(__d('eav', 'Select target table')) ->addOption('use', [ 'short' => 'u', 'help' => __d('eav', 'The table alias name. e.g. "User.Users".'), ]) ->addOption('bundle', [ 'short' => 'b', 'help' => __d('eav', 'Indicates the column belongs to a bundle name within the table.'), 'default' => null, ]); return $parser; }
Gets the option parser instance and configures it. @return \Cake\Console\ConsoleOptionParser
entailment
public function main() { $options = (array)$this->params; $options['bundle'] = empty($options['bundle']) ? null : $options['bundle']; if (empty($options['use'])) { $this->err(__d('eav', 'You must indicate a table alias name using the "--use" option. Example: "Articles.Users"')); return false; } try { $table = TableRegistry::get($options['use']); } catch (\Exception $ex) { $table = false; } if (!$table) { $this->err(__d('eav', 'The specified table does not exists.')); return false; } elseif (!$table->behaviors()->has('Eav')) { $this->err(__d('eav', 'The specified table is not using EAV behavior.')); return false; } $columns = $table->listColumns($options['bundle']); ksort($columns, SORT_LOCALE_STRING); $rows = [ [ __d('eav', 'Column Name'), __d('eav', 'Data Type'), __d('eav', 'Bundle'), __d('eav', 'Searchable'), ] ]; foreach ($columns as $name => $info) { $rows[] = [ $name, $info['type'], (!empty($info['bundle']) ? $info['bundle'] : '---'), (!empty($info['searchable']) ? 'no' : 'yes'), ]; } $this->out(); $this->out(__d('eav', 'EAV information for table "{0}":', $options['use'])); $this->out(); $this->helper('table')->output($rows); return true; }
Adds or drops the specified column. @return bool
entailment
public function getOptionParser() { $parser = parent::getOptionParser(); $parser ->description(__d('installer', 'Uninstall an existing plugin.')) ->addOption('plugin', [ 'short' => 'p', 'help' => __d('installer', 'Name of the plugin to uninstall.'), ]) ->addOption('no-callbacks', [ 'short' => 'c', 'help' => __d('installer', 'Plugin events will not be trigged.'), 'boolean' => true, 'default' => false, ]); return $parser; }
Gets the option parser instance and configures it. @return \Cake\Console\ConsoleOptionParser
entailment
public function main() { $connection = ConnectionManager::get('default'); $result = $connection->transactional(function ($conn) { try { $result = $this->_runTransactional(); } catch (\Exception $ex) { $this->err(__d('installer', 'Something went wrong. Details: {0}', $ex->getMessage())); $result = false; } return $result; }); // ensure snapshot snapshot(); return $result; }
Task main method. @return bool
entailment
protected function _runTransactional() { // to avoid any possible issue snapshot(); if (!is_writable(TMP)) { $this->err(__d('installer', 'Enable write permissions in /tmp directory before uninstall any plugin or theme.')); return false; } if (!$this->params['plugin']) { $this->err(__d('installer', 'No plugin/theme was given to remove.')); return false; } $this->loadModel('System.Plugins'); try { $plugin = plugin($this->params['plugin']); $pluginEntity = $this->Plugins ->find() ->where(['name' => $this->params['plugin']]) ->limit(1) ->first(); } catch (\Exception $ex) { $plugin = $pluginEntity = false; } if (!$plugin || !$pluginEntity) { $this->err(__d('installer', 'Plugin "{0}" was not found.', $this->params['plugin'])); return false; } $this->_plugin = $plugin; $type = $plugin->isTheme ? 'theme' : 'plugin'; if ($plugin->isTheme && in_array($plugin->name, [option('front_theme'), option('back_theme')])) { $this->err(__d('installer', '{0} "{1}" is currently being used and cannot be removed.', ($type == 'plugin' ? __d('installer', 'The plugin') : __d('installer', 'The theme')), $plugin->humanName)); return false; } $requiredBy = Plugin::checkReverseDependency($this->params['plugin']); if (!empty($requiredBy)) { $names = []; foreach ($requiredBy as $p) { $names[] = $p->name(); } $this->err(__d('installer', '{0} "{1}" cannot be removed as it is required by: {2}', ($type == 'plugin' ? __d('installer', 'The plugin') : __d('installer', 'The theme')), $plugin->humanName, implode(', ', $names))); return false; } if (!$this->_canBeDeleted($plugin->path)) { return false; } if (!$this->params['no-callbacks']) { try { $event = $this->trigger("Plugin.{$plugin->name}.beforeUninstall"); if ($event->isStopped() || $event->result === false) { $this->err(__d('installer', 'Task was explicitly rejected by {0}.', ($type == 'plugin' ? __d('installer', 'the plugin') : __d('installer', 'the theme')))); return false; } } catch (\Exception $e) { $this->err(__d('installer', 'Internal error, {0} did not respond to "beforeUninstall" callback correctly.', ($type == 'plugin' ? __d('installer', 'the plugin') : __d('installer', 'the theme')))); return false; } } if (!$this->Plugins->delete($pluginEntity)) { $this->err(__d('installer', '{0} "{1}" could not be unregistered from DB.', ($type == 'plugin' ? __d('installer', 'The plugin') : __d('installer', 'The theme')), $plugin->humanName)); return false; } $this->_removeOptions(); $this->_clearAcoPaths(); $folder = new Folder($plugin->path); $folder->delete(); snapshot(); if (!$this->params['no-callbacks']) { try { $this->trigger("Plugin.{$plugin->name}.afterUninstall"); } catch (\Exception $e) { $this->err(__d('installer', '{0} did not respond to "afterUninstall" callback.', ($type == 'plugin' ? __d('installer', 'The plugin') : __d('installer', 'The theme')))); } } Plugin::unload($plugin->name); Plugin::dropCache(); return true; }
Runs uninstallation logic inside a safe transactional thread. This prevent DB inconsistencies on uninstall failure. @return bool True on success, false otherwise
entailment
protected function _removeOptions() { $options = []; if (!empty($this->_plugin->composer['extra']['options'])) { $this->loadModel('System.Options'); $options = $this->_plugin->composer['extra']['options']; } foreach ($options as $option) { if (!empty($option['name'])) { $this->Options->deleteAll(['name' => $option['name']]); } } }
Removes from "options" table any entry registered by the plugin. @return void
entailment
protected function _clearAcoPaths() { $this->loadModel('User.Acos'); $nodes = $this->Acos ->find() ->where(['plugin' => $this->params['plugin']]) ->order(['lft' => 'ASC']) ->all(); foreach ($nodes as $node) { $this->Acos->removeFromTree($node); $this->Acos->delete($node); } AcoManager::buildAcos(null, true); // clear anything else }
Removes all ACOs created by the plugin being uninstall. @return void
entailment
protected function _canBeDeleted($path) { $type = $this->_plugin->isTheme ? 'theme' : 'plugin'; if (!file_exists($path) || !is_dir($path)) { $this->err(__d('installer', "{0} directory was not found: {1}", ($type == 'plugin' ? __d('installer', "Plugin's") : __d('installer', "Theme's")), $path)); return false; } $folder = new Folder($path); $folderContent = $folder->tree(); $notWritable = []; foreach ($folderContent as $foldersOrFiles) { foreach ($foldersOrFiles as $element) { if (!is_writable($element)) { $notWritable[] = $element; } } } if (!empty($notWritable)) { $this->err(__d('installer', "{0} files or directories cannot be removed from your server, please check write permissions of:", ($type == 'plugin' ? __d('installer', "Some plugin's") : __d('installer', "Some theme's")))); foreach ($notWritable as $path) { $this->err(__d('installer', ' - {0}', [$path])); } return false; } return true; }
Recursively checks if the given directory (and its content) can be deleted. This method automatically registers an error message if validation fails. @param string $path Directory to check @return bool
entailment
public function validationDefault(Validator $validator) { $validator ->add('subject', [ 'notBlank' => [ 'rule' => 'notBlank', 'message' => __d('comment', 'You need to provide a comment subject.'), ], 'length' => [ 'rule' => ['minLength', 5], 'message' => 'Comment subject need to be at least 5 characters long', ] ]) ->add('body', [ 'notBlank' => [ 'rule' => 'notBlank', 'message' => __d('comment', 'Your comment message cannot be empty') ], 'length' => [ 'rule' => ['minLength', 5], 'message' => 'Comment message need to be at least 5 characters long', ] ]) ->allowEmpty('user_id') ->allowEmpty('parent_id') ->add('parent_id', 'checkParentId', [ 'rule' => function ($value, $context) { if (!empty($value)) { // make sure it's a valid parent: exists and belongs to the // the same bundle (table) $conditions = [ 'id' => $value, 'entity_id' => $context['data']['entity_id'], 'table_alias' => $context['data']['table_alias'], ]; return TableRegistry::get('Comment.Comments')->find() ->where($conditions) ->count() > 0; } else { $context['data']['parent_id'] = null; } return true; }, 'message' => __d('comment', 'Invalid parent comment!.'), 'provider' => 'table', ]); return $validator; }
Basic validation set of rules. @param \Cake\Validation\Validator $validator The validator object @return \Cake\Validation\Validator
entailment
public function validationAnonymous(Validator $validator) { $settings = Plugin::get('Comment')->settings; $validator = $this->validationDefault($validator); if ($settings['allow_anonymous']) { if ($settings['anonymous_name']) { $validator ->requirePresence('author_name') ->add('author_name', 'nameLength', [ 'rule' => ['minLength', 3], 'message' => __d('comment', 'Your name need to be at least 3 characters long.'), ]); if ($settings['anonymous_name_required']) { $validator->notEmpty('author_name', __d('comment', 'You must provide your name.')); } else { $validator->allowEmpty('author_name'); } } if ($settings['anonymous_email']) { $validator ->requirePresence('author_email') ->add('author_email', 'validEmail', [ 'rule' => 'email', 'message' => __d('comment', 'e-Mail must be valid.'), ]); if ($settings['anonymous_email_required']) { $validator->notEmpty('author_email', __d('comment', 'You must provide an email.')); } else { $validator->allowEmpty('anonymous_email'); } } if ($settings['anonymous_web']) { $validator ->requirePresence('author_web') ->add('author_web', 'validURL', [ 'rule' => 'url', 'message' => __d('comment', 'Website must be a valid URL.'), ]); if ($settings['anonymous_web_required']) { $validator->notEmpty('author_web', __d('comment', 'You must provide a website URL.')); } else { $validator->allowEmpty('author_web'); } } } return $validator; }
Validation rules when editing a comment in backend. @param \Cake\Validation\Validator $validator The validator object @return \Cake\Validation\Validator
entailment
public function name($name = null) { if ($name !== null) { $this->config('name', $name); } return $this->config('name'); }
Gets or set Adapter's name. @param string|null $name The name to set, or null to get current name. @return string Adapter name, e.g. `reCAPTCHA`
entailment
public function unauthenticated(Request $request, Response $response) { if ($this->_cookieLogin($request)) { return true; } if ($this->_tokenLogin($request)) { return true; } }
Handle unauthenticated access attempt. In implementation valid return values can be: - Null - No action taken, AuthComponent should return appropriate response. - Cake\Network\Response - A response object, which will cause AuthComponent to simply return that response. @param \Cake\Network\Request $request A request object @param \Cake\Network\Response $response A response object @return bool|null
entailment
protected function _cookieLogin(Request $request) { $controller = $this->_registry->getController(); if (empty($controller->Cookie)) { $controller->loadComponent('Cookie'); } $cookie = $controller->Cookie->read('User.Cookie'); if ($cookie) { $cookie = json_decode($cookie, true); if (isset($cookie['user']) && isset($cookie['hash']) && $cookie['hash'] == Security::hash($cookie['user'], 'sha1', true) ) { $cookie['user'] = json_decode($cookie['user'], true); $user = $this->_findUser($cookie['user']['username']); if (!empty($user) && is_array($user)) { if (isset($user['password'])) { unset($user['password']); } $controller->Auth->setUser($user); return true; } } } $cacheKey = 'permissions_anonymous'; $permissions = Cache::read($cacheKey, 'permissions'); $action = $this->action($request); if ($permissions === false) { $permissions = $this->_rolePermissions(ROLE_ID_ANONYMOUS); Cache::write($cacheKey, $permissions, 'permissions'); } if (isset($permissions[$action])) { return true; } return false; }
Tries to login user if he/she has a cookie. @param \Cake\Network\Request $request A request object @return bool True if user was logged in using cookie, false otherwise
entailment
protected function _tokenLogin(Request $request) { if (!empty($request->query['token'])) { $token = $request->query['token']; $Users = TableRegistry::get('User.Users'); $exists = $Users ->find() ->select(['id', 'username']) ->where(['token' => $token, 'token_expiration <=' => time()]) ->limit(1) ->first(); if ($exists) { $user = $this->_findUser($exists->username); if (is_array($user)) { $controller = $this->_registry->getController(); if (isset($user['password'])) { unset($user['password']); } $controller->Auth->setUser($user); $exists->updateToken(); return true; } } } return false; }
Tries to login user using token. Token must be passed as a GET parameter named `token`, tokens looks as follow: // <md5-hash> (length = 32) 5df9f63916ebf8528697b629022993e8 Tokens are consumables, the same token cannot be used twice to log in. @param \Cake\Network\Request $request A request object @return bool True if user was logged in using token, false otherwise
entailment
protected function _rolePermissions($roleId) { $Acos = TableRegistry::get('User.Acos'); $Permissions = TableRegistry::get('User.Permissions'); $out = []; $acoIds = $Permissions ->find() ->select(['aco_id']) ->where(['role_id' => $roleId]) ->all() ->extract('aco_id') ->toArray(); foreach ($acoIds as $acoId) { $path = $Acos->find('path', ['for' => $acoId]); if (!$path) { continue; } $path = implode('/', $path->extract('alias')->toArray()); if ($path) { $out[$path] = true; } } return $out; }
Gets all permissions available for the given role. Example Output: ```php [ 'User/Admin/Gateway/login' => true, 'User/Admin/Gateway/logout' => true, ... ] ``` Resulting array is always `key` => **true**, as role have access to every ACO in the array "true" is the only possible value. @param int $roleId Role's ID @return array Array of ACO paths which role has permissions to
entailment
public function beforeRender(\Cake\Event\Event $event) { $this->_beforeRender($event); $this->Breadcrumb ->push('/admin/user/manage') ->push(__d('user', 'Virtual Fields'), '#'); }
Before every action of this controller. We sets appropriate breadcrumbs based on current action being requested. @param \Cake\Event\Event $event The event that was triggered @return void
entailment
protected function init() { // Normalize directory separator for windows if (DIRECTORY_SEPARATOR !== '/') { foreach(array('path', 'tmbPath', 'quarantine') as $key) { if ($this->options[$key]) { $this->options[$key] = str_replace('/', DIRECTORY_SEPARATOR, $this->options[$key]); } } } return true; }
Prepare driver before mount volume. Return true if volume is ready. @return bool
entailment
protected function _abspath($path) { return $path == DIRECTORY_SEPARATOR ? $this->root : $this->root.DIRECTORY_SEPARATOR.$path; }
Convert path related to root dir into real path @param string $path file path @return string @author Dmitry (dio) Levashov
entailment