sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function _findSymlinks($path) { die('Not yet implemented. (_findSymlinks)'); if (is_link($path)) { return true; } if (is_dir($path)) { foreach (scandir($path) as $name) { if ($name != '.' && $name != '..') { $p = $path.DIRECTORY_SEPARATOR.$name; if (is_link($p)) { return true; } if (is_dir($p) && $this->_findSymlinks($p)) { return true; } elseif (is_file($p)) { $this->archiveSize += filesize($p); } } } } else { $this->archiveSize += filesize($path); } return false; }
Recursive symlinks search @param string $path file/dir path @return bool @author Dmitry (dio) Levashov
entailment
public function addInputPrefix(MethodInvocation $invocation) { $helper = $invocation->getThis(); $args = $invocation->getArguments(); if (!empty($args[0]) && is_string($args[0]) && $helper instanceof FormHelper ) { $args[0] = $this->_fieldName($helper, $args[0]); } $this->setProperty($invocation, 'arguments', $args); return $invocation->proceed(); }
Adds prefix to every input element that may have a "name" attribute. @param \Go\Aop\Intercept\MethodInvocation $invocation Invocation @Around("execution(public Cake\View\Helper\FormHelper->label|input|checkbox|radio|textarea|hidden|file|select|multiCheckbox|day|year|month|hour|minute|meridian|dateTime|time|date(*))") @return bool Whether object invocation should proceed or not
entailment
protected function _fieldName(FormHelper $helper, $name) { $prefix = $helper->prefix(); if (!empty($prefix) && strpos($name, $prefix) !== 0) { $name = "{$prefix}{$name}"; } return $name; }
Add prefix to field name if a prefix was set using FormHelper::prefix(). @param \Cake\View\Helper\FormHelper $helper Field helper instance @param string $name Field name @return string Prefixed field name
entailment
public function index() { $this->loadModel('User.Acos'); $tree = $this->Acos ->find('threaded') ->order(['lft' => 'ASC']) ->all(); $this->title(__d('user', 'Permissions')); $this->set(compact('tree')); $this->Breadcrumb ->push('/admin/user/manage') ->push(__d('user', 'Permissions'), ['plugin' => 'User', 'controller' => 'permissions', 'action' => 'index']); }
Shows tree list of ACOS grouped by plugin. @return void
entailment
public function aco($acoId) { $this->loadModel('User.Acos'); $aco = $this->Acos->get($acoId, ['contain' => ['Roles']]); $path = $this->Acos->find('path', ['for' => $acoId])->extract('alias')->toArray(); if (!empty($this->request->data['roles'])) { $aco = $this->Acos->patchEntity($aco, $this->request->data); $save = $this->Acos->save($aco); if (!$this->request->isAjax()) { if ($save) { $this->Flash->success(__d('user', 'Permissions were successfully saved!')); } else { $this->Flash->danger(__d('user', 'Permissions could not be saved')); } } } $roles = $this->Acos->Roles ->find('list') ->where(['Roles.id <>' => ROLE_ID_ADMINISTRATOR]); $this->title(__d('user', 'Permissions')); $this->set(compact('aco', 'roles', 'path')); }
Shows the permissions table for the given ACO. @param int $acoId ACO's ID @return void
entailment
public function update() { $sync = !empty($this->request->query['sync']) ? true : false; if (AcoManager::buildAcos(null, $sync)) { $this->Flash->success(__d('user', 'Permissions tree was successfully updated!')); } else { $this->Flash->danger(__d('user', 'Some errors occur while updating permissions tree.')); } $this->title(__d('user', 'Update Permissions')); $this->redirect($this->referer()); }
Analyzes each plugin and adds any missing ACO path to the tree. It won't remove any invalid ACO unless 'sync' GET parameter is present in URL. @return void Redirects to previous page
entailment
public function export() { $this->loadModel('User.Acos'); $out = []; $permissions = $this->Acos->Permissions ->find() ->contain(['Acos', 'Roles']) ->all(); foreach ($permissions as $permission) { if (!isset($out[$permission->role->slug])) { $out[$permission->role->slug] = []; } $out[$permission->role->slug][] = implode( '/', $this->Acos ->find('path', ['for' => $permission->aco->id]) ->extract('alias') ->toArray() ); } $this->title(__d('user', 'Export Permissions')); $this->response->body(json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); $this->response->type('json'); $this->response->download('permissions_' . date('Y-m-d@H:i:s-\U\TC', time()) . '.json'); return $this->response; }
Exports all permissions as a JSON file. @return \Cake\Network\Response Forces JSON download
entailment
public function import() { if (!empty($this->request->data['json'])) { $this->loadModel('User.Acos'); $json = $this->request->data['json']; $dst = TMP . $json['name']; if (file_exists($dst)) { $file = new File($dst); $file->delete(); } if (!move_uploaded_file($json['tmp_name'], $dst)) { $this->Flash->danger(__d('user', 'File could not be uploaded, please check write permissions on /tmp directory.')); } else { $file = new File($dst); $info = json_decode($file->read(), true); $added = []; $error = false; if (is_array($info) && !empty($info)) { foreach ($info as $role => $paths) { if (!is_string($role)) { $error = true; $this->Flash->danger(__d('user', 'Given file seems to be corrupt.')); break; } $role = $this->Acos->Roles ->find() ->where(['slug' => $role]) ->limit(1) ->first(); if (!$role) { continue; } if (is_array($paths)) { foreach ($paths as $path) { $nodes = $this->Acos->node($path); if ($nodes) { $leaf = $nodes->first(); $exists = $this->Acos->Permissions ->exists([ 'aco_id' => $leaf->id, 'role_id' => $role->id ]); if (!$exists) { $newPermission = $this->Acos->Permissions->newEntity([ 'aco_id' => $leaf->id, 'role_id' => $role->id ]); if ($this->Acos->Permissions->save($newPermission)) { $added[] = "<strong>{$role->name}</strong>: {$path}"; } } } } } else { $error = true; $this->Flash->danger(__d('user', 'Given file seems to be corrupt.')); break; } } } else { $error = true; $this->Flash->danger(__d('user', 'Invalid file given.')); } if (!$error) { if (!empty($added)) { $imported = '<br />' . implode('<br />', $added); $this->Flash->success(__d('user', 'The following entries were imported: {0}', $imported)); } else { $this->Flash->success(__d('user', 'Success, but nothing was imported')); } } } } $this->title(__d('user', 'Import Permissions')); $this->redirect($this->referer()); }
Imports the given permissions given as a JSON file. @return void Redirects to previous page
entailment
public function defaultTemplates(MethodInvocation $invocation) { if (!static::cache('bootstrapTemplates')) { $helper = $invocation->getThis(); $helper->templates($this->_templates); static::cache('bootstrapTemplates', true); } }
Adds custom templates to PaginatorHelper::$_defaultConfig['templates']. @param \Go\Aop\Intercept\MethodInvocation $invocation Joinpoint @Before("execution(public Cake\View\Helper\PaginatorHelper->prev|numbers|next(*))") @return bool Whether object invocation should proceed or not
entailment
protected function _getRegion() { if (isset($this->_matchingData['BlockRegions'])) { return $this->_matchingData['BlockRegions']; } if (isset($this->_properties['region'])) { return $this->_properties['region']; } }
Tries to get block's region. This method is used when finding blocks matching a particular region. @return \Block\Model\Entity\BlockRegion
entailment
public static function formatter(Field $field) { $viewModeSettings = $field->viewModeSettings; $processing = $field->metadata->settings['text_processing']; $formatter = $viewModeSettings['formatter']; $content = static::process($field->value, $processing); switch ($formatter) { case 'plain': $content = static::filterText($content); break; case 'trimmed': $len = $viewModeSettings['trim_length']; $content = static::trimmer($content, $len); break; } return $content; }
Formats the given field. @param \Field\Model\Entity\Field $field The field being rendered @return string
entailment
public static function process($content, $processor) { switch ($processor) { case 'plain': $content = static::plainProcessor($content); break; case 'filtered': $content = static::filteredProcessor($content); break; case 'markdown': $content = static::markdownProcessor($content); break; } return $content; }
Process the given text to its corresponding format. @param string $content Content to process @param string $processor "plain", "filtered", "markdown" or "full" @return string
entailment
public static function plainProcessor($text) { $text = static::emailToLink($text); $text = static::urlToLink($text); $text = nl2br($text); return $text; }
Process text in plain mode. - No HTML tags allowed. - Web page addresses and e-mail addresses turn into links automatically. - Lines and paragraphs break automatically. @param string $text The text to process @return string
entailment
public static function filteredProcessor($text) { $text = static::emailToLink($text); $text = static::urlToLink($text); $text = strip_tags($text, '<a><em><strong><cite><blockquote><code><ul><ol><li><dl><dt><dd>'); return $text; }
Process text in filtered HTML mode. - Web page addresses turn into links automatically. - E-mail addresses turn into links automatically. - Allowed HTML tags: `<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>` - Lines and paragraphs break automatically. @param string $text The text to process @return string
entailment
public static function markdownProcessor($text) { $MarkdownParser = static::getMarkdownParser(); $text = $MarkdownParser->parse($text); $text = static::emailToLink($text); $text = str_replace('<p>h', '<p> h', $text); $text = static::urlToLink($text); return $text; }
Process text in markdown mode. - [Markdown](http://en.wikipedia.org/wiki/Markdown) text format allowed only. @param string $text The text to process @return string
entailment
public static function closeOpenTags($html) { preg_match_all("#<([a-z]+)( .*)?(?!/)>#iU", $html, $result); $openedTags = $result[1]; preg_match_all("#</([a-z]+)>#iU", $html, $result); $closedTags = $result[1]; $lenOpened = count($openedTags); if (count($closedTags) == $lenOpened) { return $html; } $openedTags = array_reverse($openedTags); for ($i = 0; $i < $lenOpened; $i++) { if (!in_array($openedTags[$i], $closedTags)) { $html .= '</' . $openedTags[$i] . '>'; } else { unset($closedTags[array_search($openedTags[$i], $closedTags)]); } } return $html; }
Attempts to close any unclosed HTML tag. @param string $html HTML content to fix @return string
entailment
public static function emailToLink($text) { preg_match_all("/([\\\a-z0-9_\-\.]+)@([a-z0-9-]{1,64})\.([a-z]{2,10})/iu", $text, $emails); foreach ($emails[0] as $email) { $email = trim($email); if ($email[0] == '\\') { $text = str_replace($email, mb_substr($email, 1), $text); } else { $text = str_replace($email, static::emailObfuscator($email), $text); } } return $text; }
Convert any email to a "mailto" link. Escape character is `\`. For example, "\[email protected]" won't be converted to link. @param string $text The text where to look for emails addresses @return string
entailment
public static function emailObfuscator($email) { $link = str_rot13('<a href="mailto:' . $email . '" rel="nofollow">' . $email . '</a>'); $out = '<script type="text/javascript">' . "\n"; $out .= ' document.write(\'' . $link . '\'.replace(/[a-zA-Z]/g, function(c) {' . "\n"; $out .= ' return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);' . "\n"; $out .= ' }));' . "\n"; $out .= '</script>' . "\n"; $out .= '<noscript>[' . __d('field', 'Turn on JavaScript to see the email address.') . ']</noscript>' . "\n"; return $out; }
Protects email address so bots can not read it. Replaces emails address with an encoded JS script, so there is no way bots can read an email address from the generated HTML source code. @param string $email The email to obfuscate @return string
entailment
public static function trimmer($text, $len = false, $ellipsis = ' ...') { if (!preg_match('/[0-9]+/i', $len)) { $parts = explode($len, $text); return static::closeOpenTags($parts[0]); } $len = $len === false || !is_numeric($len) || $len <= 0 ? 600 : $len; $text = static::filterText($text); $textLen = mb_strlen($text); if ($textLen > $len) { return mb_substr($text, 0, $len) . $ellipsis; } return $text; }
Safely trim a text. This method is HTML aware, it will not "destroy" any HTML tag. You can trim the text to a given number of characters, or you can give a string as second argument which will be used to cut the given text and return the first part. ## Examples: $text = ' Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce augue nulla, iaculis adipiscing risus sed, pharetra tempor risus. <!-- readmore --> Ut volutpat nisl enim, quic sit amet quam ut lacus condimentum volutpat in eu magna. Phasellus a dolor cursus, aliquam felis sit amet, feugiat orci. Donec vel consec.'; echo $this->trimmer($text, '<!-- readmore -->'); // outputs: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce augue nulla, iaculis adipiscing risus sed, pharetra tempor risus. echo $this->trimmer('Lorem ipsum dolor sit amet, consectetur adipiscing elit', 10); // out: "Lorem ipsu ..." @param string $text The text to trim @param string|int|false $len Either a string indicating where to cut the text, or a integer to trim text to that number of characters. If not given (false by default) text will be trimmed to 600 characters length. @param string $ellipsis Will be used as ending and appended to the trimmed string. Defaults to ` ...` @return string
entailment
public function update($name, $value, $autoload = null, $callbacks = true) { $option = $this ->find() ->where(['name' => $name]) ->first(); if (!$option) { return null; } if ($callbacks) { $option->set('value', $value); if ($autoload !== null) { $option->set('autoload', $autoload); } return $this->save($option, ['callbacks' => false]); } return $this->updateAll(['value' => $value], ['name' => $name]); }
Updates the given option. @param string $name Option name @param mixed $value Value to store for this option @param bool|null $autoload Set to true to load this option on bootstrap, null indicates it should not be modified. Defaults to null (do not change) @param bool $callbacks Whether to trigger callbacks (beforeSavem etc) or not. Defaults to true @return null|\Cake\ORM\Entity The option as an entity on success, null otherwise
entailment
public function render(Entity $entity) { if (!isset($this->_View->viewVars['__commentComponentLoaded__'])) { throw new InternalErrorException(__d('comment', 'Illegal usage of \Comment\View\Helper\CommentHelper.')); } $this->config('entity', $entity); $event = $this->trigger(['CommentHelper.beforeRender', $this->_View]); if ($event->isStopped()) { return $event->result; } $out = ''; if ($this->config('visibility') > 0) { $out .= $this->_View->element('Comment.render_comments_list'); if ($this->config('visibility') === 1) { $out .= $this->_View->element('Comment.render_comments_form'); } } $event = $this->trigger(['CommentHelper.afterRender', $this->_View], $out); if ($event->isStopped()) { return $event->result; } return $out; }
Renders a comments section for given entity. Entity's comments must be in the `comments` property. It is automatically filled when using `CommentableBehavior`. The following events will be triggered: - `CommentHelper.beforeRender`: Triggered before default rendering operation starts. By stopping this event, you can return the final value of the rendering operation. - `CommentHelper.afterRender`: Triggered after default rendering operation is completed. Listeners will receive the rendered output. By stopping this event, you can return the final value of the rendering operation. @param \Cake\ORM\Entity $entity Any valid entity @return string @throws \Cake\Network\Exception\InternalErrorException When comment component was not loaded
entailment
public function optionsForInput($input) { $options = [ 'author_name' => [ 'label' => ($this->config('anonymous_name_required') ? __d('comment', 'Name (required)') : __d('comment', 'Name')) ], 'author_email' => [ 'label' => ($this->config('anonymous_email_required') ? __d('comment', 'e-Mail (required)') : __d('comment', 'e-Mail')) ], 'author_web' => [ 'label' => ($this->config('anonymous_web_required') ? __d('comment', 'Website (required)') : __d('comment', 'Website')) ], 'subject' => [ 'label' => __d('comment', 'Subject (required)'), 'required', ], 'body' => [ 'type' => 'textarea', 'label' => __d('comment', 'Message (required)'), 'required', ], ]; if (isset($options[$input])) { if (in_array($input, ['author_name', 'author_email', 'author_web']) && $this->config($input . '_required') ) { $options[$input]['required'] = 'required'; } return $options[$input]; } return []; }
Shortcut for generate form-input's options. It take cares of adding an asterisk "*" to each required filed label, it also adds the "required" attribute. @param string $input Input name (author_name, author_email, author_web, subject or body) @return array
entailment
public function renderField(Event $event, $field, $options = []) { $viewMode = $this->viewMode(); if (isset($field->metadata->view_modes[$viewMode]) && !$field->metadata->view_modes[$viewMode]['hidden'] ) { $event->stopPropagation(); // We don't want other plugins to catch this $result = (string)$field->render($event->subject()); if (!$field->metadata->view_modes[$viewMode]['shortcodes']) { $result = $event->subject()->stripShortcodes($result); } return $result; } return ''; }
We catch all field rendering request (from CMS\View\View) here, then we dispatch to their corresponding FieldHandler. If the field object being rendered has been set to "hidden" for the current view mode it will not be rendered. @param \Cake\Event\Event $event The event that was triggered @param \Field\Model\Entity\Field $field Mock entity @param array $options Additional array of options @return string The rendered field
entailment
public function add($path, $roles = []) { $path = $this->_parseAco($path); if (!$path) { return false; } // path already exists $contents = $this->Acos->node($path); if (is_object($contents)) { $contents = $contents->extract('alias')->toArray(); } if (!empty($contents) && implode('/', $contents) === $path) { return true; } $parent = null; $current = null; $parts = explode('/', $path); $this->Acos->connection()->transactional(function () use ($parts, $current, &$parent, $path) { foreach ($parts as $alias) { $current[] = $alias; $content = $this->Acos->node(implode('/', $current)); if ($content) { $parent = $content->first(); } else { $acoEntity = $this->Acos->newEntity([ 'parent_id' => (isset($parent->id) ? $parent->id : null), 'plugin' => $this->_pluginName, 'alias' => $alias, 'alias_hash' => md5($alias), ]); $parent = $this->Acos->save($acoEntity); } } }); if ($parent) { // register roles if (!empty($roles)) { $this->loadModel('User.Permissions'); $roles = $this->Acos->Roles ->find() ->select(['id']) ->where(['Roles.slug IN' => $roles]) ->all(); foreach ($roles as $role) { $permissionEntity = $this->Permissions->newEntity([ 'aco_id' => $parent->id, // action 'role_id' => $role->id, ]); $this->Permissions->save($permissionEntity); } } return true; } return false; }
Grants permissions to all users within $roles over the given $aco. ### ACO path format: - `ControllerName/`: Maps to \<PluginName>\Controller\ControllerName::index() - `ControllerName`: Same. - `ControllerName/action_name`: Maps to \<PluginName>\Controller\ControllerName::action_name() - `Prefix/ControllerName/action_name`: Maps to \<PluginName>\Controller\Prefix\ControllerName::action_name() @param string $path ACO path as described above @param array $roles List of user roles to grant access to. If not given, $path cannot be used by anyone but "administrators" @return bool True on success
entailment
public function remove($path) { $contents = $this->Acos->node($path); if (!$contents) { return false; } $content = $contents->first(); $this->Acos->removeFromTree($content); $this->Acos->delete($content); return true; }
Removes the given ACO and its permissions. @param string $path ACO path e.g. `ControllerName/action_name` @return bool True on success, false if path was not found
entailment
public static function buildAcos($for = null, $sync = false) { if (function_exists('ini_set')) { ini_set('max_execution_time', 300); } elseif (function_exists('set_time_limit')) { set_time_limit(300); } if ($for === null) { $plugins = plugin()->toArray(); } else { try { $plugins = [plugin($for)]; } catch (\Exception $e) { return false; } } $added = []; foreach ($plugins as $plugin) { if (!Plugin::exists($plugin->name)) { continue; } $aco = new AcoManager($plugin->name); $controllerDir = normalizePath("{$plugin->path}/src/Controller/"); $folder = new Folder($controllerDir); $controllers = $folder->findRecursive('.*Controller\.php'); foreach ($controllers as $controller) { $controller = str_replace([$controllerDir, '.php'], '', $controller); $className = $plugin->name . '\\' . 'Controller\\' . str_replace(DS, '\\', $controller); $methods = static::_controllerMethods($className); if (!empty($methods)) { $path = explode('Controller\\', $className)[1]; $path = str_replace_last('Controller', '', $path); $path = str_replace('\\', '/', $path); foreach ($methods as $method) { if ($aco->add("{$path}/{$method}")) { $added[] = "{$plugin->name}/{$path}/{$method}"; } } } } } if ($sync && isset($aco)) { $aco->Acos->recover(); $existingPaths = static::paths($for); foreach ($existingPaths as $exists) { if (!in_array($exists, $added)) { $aco->remove($exists); } } $validLeafs = $aco->Acos ->find() ->select(['id']) ->where([ 'id NOT IN' => $aco->Acos->find() ->select(['parent_id']) ->where(['parent_id IS NOT' => null]) ]); $aco->Acos->Permissions->deleteAll([ 'aco_id NOT IN' => $validLeafs ]); } return true; }
This method should never be used unless you know what are you doing. Populates the "acos" DB with information of every installed plugin, or for the given plugin. It will automatically extracts plugin's controllers and actions for creating a tree structure as follow: - PluginName - Admin - PrivateController - index - some_action - ControllerName - index - another_action After tree is created you should be able to change permissions using User's permissions section in backend. @param string $for Optional, build ACOs for the given plugin, or all plugins if not given @param bool $sync Whether to sync the tree or not. When syncing all invalid ACO entries will be removed from the tree, also new ones will be added. When syn is set to false only new ACO entries will be added, any invalid entry will remain in the tree. Defaults to false @return bool True on success, false otherwise
entailment
public static function paths($for = null) { if ($for !== null) { try { $for = plugin($for)->name; } catch (\Exception $e) { return []; } } $cacheKey = "paths({$for})"; $paths = static::cache($cacheKey); if ($paths === null) { $paths = []; $aco = new AcoManager('__dummy__'); $aco->loadModel('User.Acos'); $leafs = $aco->Acos ->find('all') ->select(['id']) ->where([ 'Acos.id NOT IN' => $aco->Acos ->find() ->select(['parent_id']) ->where(['parent_id IS NOT' => null]) ]); foreach ($leafs as $leaf) { $path = $aco->Acos ->find('path', ['for' => $leaf->id]) ->extract('alias') ->toArray(); $path = implode('/', $path); if ($for === null || ($for !== null && str_starts_with($path, "{$for}/")) ) { $paths[] = $path; } } static::cache($cacheKey, $paths); } return $paths; }
Gets a list of existing ACO paths for the given plugin, or the entire list if no plugin is given. @param string $for Optional plugin name. e.g. `Taxonomy` @return array All registered ACO paths
entailment
protected static function _controllerMethods($className) { if (!class_exists($className)) { return []; } $methods = (array)get_this_class_methods($className); $actions = []; foreach ($methods as $methodName) { try { $method = new ReflectionMethod($className, $methodName); if ($method->isPublic()) { $actions[] = $methodName; } } catch (\ReflectionException $e) { // error } } return $actions; }
Extracts method names of the given controller class. @param string $className Fully qualified name @return array List of method names
entailment
protected function _parseAco($aco, $string = true) { $aco = preg_replace('/\/{2,}/', '/', trim($aco, '/')); $parts = explode('/', $aco); if (empty($parts)) { return false; } if (count($parts) === 1) { $controller = Inflector::camelize($parts[0]); return [ 'prefix' => '', 'controller' => $controller, 'action' => 'index', ]; } $prefixes = $this->_routerPrefixes(); $prefix = Inflector::camelize($parts[0]); if (!in_array($prefix, $prefixes)) { $prefix = ''; } else { array_shift($parts); } if (count($parts) == 2) { list($controller, $action) = $parts; } else { $controller = array_shift($parts); $action = 'index'; } $plugin = $this->_pluginName; $result = compact('plugin', 'prefix', 'controller', 'action'); if ($string) { $result = implode('/', array_values($result)); $result = str_replace('//', '/', $result); } return $result; }
Sanitizes the given ACO path. This methods can return an array with the following keys if `$string` option is set to false: - `plugin`: The name of the plugin being managed by this class. - `prefix`: ACO prefix, for example `Admin` for controller within /Controller/Admin/ it may be empty, if not prefix is found. - `controller`: Controller name. e.g.: `MySuperController` - `action`: Controller's action. e.g.: `mini_action`, `index` by default For example: `Admin/Users/` Returns: - plugin: YourPlugin - prefix: Admin - controller: Users - action: index Where "YourPlugin" is the plugin name passed to this class's constructor. @param string $aco An ACO path to parse @param bool $string Indicates if it should return a string format path (/Controller/action) @return bool|array|string An array as described above or false if an invalid $aco was given
entailment
protected function _routerPrefixes() { $cache = static::cache('_routerPrefixes'); if (!$cache) { $prefixes = []; foreach (Router::routes() as $route) { if (empty($route->defaults['prefix'])) { continue; } else { $prefix = Inflector::camelize($route->defaults['prefix']); if (!in_array($prefix, $prefixes)) { $prefixes[] = $prefix; } } } $cache = static::cache('_routerPrefixes', $prefixes); } return $cache; }
Gets a CamelizedList of all existing router prefixes. @return array
entailment
public function permissions() { if (is_array($this->_permissions)) { return $this->_permissions; } $out = []; $acosTable = TableRegistry::get('User.Acos'); $permissions = $acosTable ->Permissions ->find() ->where(['Acos.plugin' => $this->name]) ->contain(['Acos', 'Roles']) ->all(); foreach ($permissions as $permission) { if (!isset($out[$permission->role->slug])) { $out[$permission->role->slug] = []; } $out[$permission->role->slug][] = implode( '/', $acosTable ->find('path', ['for' => $permission->aco->id]) ->extract('alias') ->toArray() ); } $this->_permissions = $out; return $out; }
Gets plugin's permissions tree. ### Output example: ```php [ 'administrator' => [ 'Plugin/Controller/action', 'Plugin/Controller/action2', ... ], 'role-machine-name' => [ 'Plugin/Controller/anotherAction', 'Plugin/Controller/anotherAction2', ], ... ] ``` @return array Permissions index by role's machine-name
entailment
public function &info($key = null) { $plugin = $this->name(); if (empty($this->_info)) { $this->_info = (array)quickapps("plugins.{$plugin}"); } $parts = explode('.', $key); $getComposer = in_array('composer', $parts) || $key === null; $getSettings = in_array('settings', $parts) || $key === null; $getPermissions = in_array('permissions', $parts) || $key === null; if ($getComposer && !isset($this->_info['composer'])) { $this->_info['composer'] = $this->composer(); } if ($getSettings && !isset($this->_info['settings'])) { $this->_info['settings'] = (array)$this->settings(); } if ($getPermissions && !isset($this->_info['permissions'])) { $this->_info['permissions'] = (array)$this->permissions(); } if ($key === null) { return $this->_info; } return $this->_getKey($parts); }
Gets information for this plugin. When `$full` is set to true some additional keys will be repent in the resulting array: - `settings`: Plugin's settings info fetched from DB. - `composer`: Composer JSON information, converted to an array. - `permissions`: Permissions tree for this plugin, see `PluginPackage::permissions()` ### Example: Reading full information: ```php $plugin->info(); // returns an array as follow: [ 'name' => 'User, 'isTheme' => false, 'hasHelp' => true, 'hasSettings' => false, 'eventListeners' => [ ... ], 'status' => 1, 'path' => '/path/to/plugin', 'settings' => [ ... ], // only when $full = true 'composer' => [ ... ], // only when $full = true 'permissions' => [ ... ], // only when $full = true ] ``` Additionally the first argument, $key, can be used to get an specific value using a dot syntax path: ```php $plugin->info('isTheme'); $plugin->info('settings.some_key'); ``` If the given path is not found NULL will be returned @param string $key Optional path to read from the resulting array @return mixed Plugin information as an array if no key is given, or the requested value if a valid $key was provided, or NULL if $key path is not found
entailment
protected function &_getKey($key) { $default = null; $parts = is_string($key) ? explode('.', $key) : $key; switch (count($parts)) { case 1: if (isset($this->_info[$parts[0]])) { return $this->_info[$parts[0]]; } return $default; case 2: if (isset($this->_info[$parts[0]][$parts[1]])) { return $this->_info[$parts[0]][$parts[1]]; } return $default; case 3: if (isset($this->_info[$parts[0]][$parts[1]][$parts[2]])) { return $this->_info[$parts[0]][$parts[1]][$parts[2]]; } return $default; case 4: if (isset($this->_info[$parts[0]][$parts[1]][$parts[2]][$parts[3]])) { return $this->_info[$parts[0]][$parts[1]][$parts[2]][$parts[3]]; } return $default; default: $data = $this->_info; foreach ($parts as $key) { if (is_array($data) && isset($data[$key])) { $data = $data[$key]; } else { return $default; } } } return $data; }
Gets info value for the given key. @param string|array $key The path to read. String using a dot-syntax, or an array result of exploding by `.` symbol @return mixed
entailment
public function composer($full = false) { $composer = parent::composer($full); if ($this->isTheme && !isset($composer['extra']['admin'])) { $composer['extra']['admin'] = false; } if ($this->isTheme && !isset($composer['extra']['regions'])) { $composer['extra']['regions'] = []; } return $composer; }
{@inheritDoc}
entailment
public function settings($key = null) { $plugin = $this->name(); if ($cache = $this->config('settings')) { if ($key !== null) { $cache = isset($cache[$key]) ? $cache[$key] : null; } return $cache; } $pluginsTable = TableRegistry::get('System.Plugins'); $settings = []; $dbInfo = $pluginsTable->find() ->cache("{$plugin}_settings", 'plugins') ->select(['name', 'settings']) ->where(['name' => $plugin]) ->limit(1) ->first(); if ($dbInfo) { $settings = (array)$dbInfo->settings; } if (empty($settings)) { $settings = (array)$pluginsTable->trigger("Plugin.{$plugin}.settingsDefaults")->result; } $this->config('settings', $settings); if ($key !== null) { $settings = isset($settings[$key]) ? $settings[$key] : null; } return $settings; }
Gets settings from DB for this plugin. Or reads a single settings key value. @param string $key Which setting to read, the entire settings will be returned if no key is provided @return mixed Array of settings if $key was not provided, or the requested value for the given $key (null of key does not exists)
entailment
public function requiredBy() { if ($cache = $this->config('required_by')) { return collection($cache); } Plugin::dropCache(); $out = []; $plugins = Plugin::get()->filter(function ($v, $k) { return $v->name() !== $this->name(); }); foreach ($plugins as $plugin) { if ($dependencies = $plugin->dependencies($plugin->name)) { $packages = array_map(function ($item) { list(, $package) = packageSplit($item, true); return strtolower($package); }, array_keys($dependencies)); if (in_array(strtolower($this->name()), $packages)) { $out[] = $plugin; } } } $this->config('required_by', $out); return collection($out); }
Gets a collection list of plugin that depends on this plugin. @return \Cake\Collection\Collection List of plugins
entailment
public function version() { if (parent::version() !== null) { return parent::version(); } if (!Plugin::exists($this->name())) { $this->_version = ''; return $this->_version; } // from composer.json if (!empty($this->composer['version'])) { $this->_version = $this->composer['version']; return $this->_version; } // from version.txt $files = glob($this->path . '/*', GLOB_NOSORT); foreach ($files as $file) { $fileName = basename(strtolower($file)); if (preg_match('/version?(\.\w+)/i', $fileName)) { $versionFile = file($file); $version = trim(array_pop($versionFile)); $this->_version = $version; return $this->_version; } } // from installed.json $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 (isset($pkg['version']) && strtolower($pkg['name']) === strtolower($this->_packageName) ) { $this->_version = $pkg['version']; return $this->_version; } } } $this->_version = 'dev-master'; return $this->_version; }
{@inheritDoc} It will look for plugin's version in the following places: - Plugin's "composer.json" file. - Plugin's "VERSION.txt" file (or any file matching "/version?(\.\w+)/i"). - Composer's "installed.json" file. If not found `dev-master` is returned by default. If plugin is not registered on QuickAppsCMS (not installed) an empty string will be returned instead. @return string Plugin's version, for instance `1.2.x-dev`
entailment
public function authorize($user, Request $request) { if ($request->is('userAdmin')) { return true; } $user = user(); $path = $this->requestPath($request); $cacheKey = 'permissions_' . intval($user->id); $permissions = Cache::read($cacheKey, 'permissions'); if ($permissions === false) { $permissions = []; Cache::write($cacheKey, [], 'permissions'); } if (!isset($permissions[$path])) { $allowed = $user->isAllowed($path); $permissions[$path] = $allowed; Cache::write($cacheKey, $permissions, 'permissions'); } else { $allowed = $permissions[$path]; } return $allowed; }
Authorizes current logged in user, if user belongs to the "administrator" he/she is automatically authorized. @param array $user Active user data @param \Cake\Network\Request $request Request instance @return bool True if user is can access this request
entailment
public function requestPath(Request $request, $path = '/:plugin/:prefix/:controller/:action') { $plugin = empty($request['plugin']) ? null : Inflector::camelize($request['plugin']) . '/'; $prefix = empty($request->params['prefix']) ? '' : Inflector::camelize($request->params['prefix']) . '/'; $path = str_replace( [':controller', ':action', ':plugin/', ':prefix/'], [Inflector::camelize($request['controller']), $request['action'], $plugin, $prefix], $path ); $path = str_replace('//', '/', $path); return trim($path, '/'); }
Gets an ACO path for current request. @param \Cake\Network\Request $request Request instance @param string $path Pattern @return string
entailment
public function index() { $this->loadModel('Content.Contents'); $this->Contents->CreatedBy->fieldable(false); $this->Contents->ModifiedBy->fieldable(false); $contents = $this->Contents ->find('all', ['fieldable' => false]) ->contain(['ContentTypes', 'CreatedBy', 'ModifiedBy']); if (!empty($this->request->query['filter']) && $contents instanceof Query ) { $this->Contents->search($this->request->query['filter'], $contents); } $this->title(__d('content', 'Contents List')); $this->set('contents', $this->paginate($contents)); $this->Breadcrumb->push('/admin/content/manage'); }
Shows a list of all the contents. @return void
entailment
public function create() { $this->loadModel('Content.ContentTypes'); $types = $this->ContentTypes->find() ->select(['id', 'slug', 'name', 'description']) ->all(); $this->title(__d('content', 'Create New Content')); $this->set('types', $types); $this->Breadcrumb ->push('/admin/content/manage') ->push(__d('content', 'Create new content'), ''); }
Content-type selection screen. User must select which content type wish to create. @return void
entailment
public function add($typeSlug) { $this->loadModel('Content.ContentTypes'); $this->loadModel('Content.Contents'); $this->Contents->unbindComments(); $type = $this->ContentTypes->find() ->where(['slug' => $typeSlug]) ->limit(1) ->first(); if (!$type) { throw new ContentTypeNotFoundException(__d('content', 'The specified content type ({0}) does not exists.', $type)); } if (!$type->userAllowed('create')) { throw new ContentCreateException(__d('content', 'You are not allowed to create contents of this type ({0}).', $type->name)); } if ($this->request->data()) { $data = $this->request->data(); $data['content_type_slug'] = $type->slug; $data['content_type_id'] = $type->id; $content = $this->Contents->newEntity($data); if ($this->Contents->save($content)) { if (!$type->userAllowed('publish')) { $this->Flash->warning(__d('content', 'Content created, but awaiting moderation before publishing it.')); } else { $this->Flash->success(__d('content', 'Content created!.')); } $this->redirect(['plugin' => 'Content', 'controller' => 'manage', 'action' => 'edit', 'prefix' => 'admin', $content->id]); } else { $this->Flash->danger(__d('content', 'Something went wrong, please check your information.')); } } else { $content = $this->Contents->newEntity(['content_type_slug' => $type->slug]); $content->setDefaults($type); } $content->set('content_type', $type); $content = $this->Contents->attachFields($content); $languages = LocaleToolbox::languagesList(); $roles = $this->Contents->Roles->find('list'); $this->title(__d('content', 'Create New Content <small>({0})</small>', $type->slug)); $this->set(compact('content', 'type', 'languages', 'roles')); $this->Breadcrumb ->push('/admin/content/manage') ->push(__d('content', 'Create new content'), ['plugin' => 'Content', 'controller' => 'manage', 'action' => 'create']) ->push($type->name, ''); }
Shows the "new content" form. @param string $typeSlug Content type slug. e.g.: "article", "product-info" @return void @throws \Content\Error\ContentTypeNotFoundException When content type was not found @throws \Content\Error\ContentCreateException When current user is not allowed to create contents of this type
entailment
public function edit($id, $revisionId = false) { $this->loadModel('Content.Contents'); $this->Contents->unbindComments(); $content = false; if (intval($revisionId) > 0 && !$this->request->data()) { $this->loadModel('Content.ContentRevisions'); $revision = $this->ContentRevisions->find() ->where(['id' => $revisionId, 'content_id' => $id]) ->first(); if ($revision) { $content = $revision->data; if (!empty($content->_fields)) { // Merge previous data for each field, we just load the data (metadata keeps to the latests configured). $_fieldsRevision = $content->_fields; $content = $this->Contents->attachFields($content); $content->_fields = $content->_fields->map(function ($field, $key) use ($_fieldsRevision) { $fieldRevision = $_fieldsRevision[$field->name]; if ($fieldRevision) { $field->set('value', $fieldRevision->value); $field->set('extra', $fieldRevision->extra); } return $field; }); } } } else { $content = $this->Contents ->find() ->where(['Contents.id' => $id]) ->contain([ 'Roles', 'Translations', 'ContentRevisions', 'ContentTypes', 'TranslationOf', ]) ->first(); } if (!$content || empty($content->content_type)) { throw new ContentNotFoundException(__d('content', 'The requested page was not found.')); } if (!$content->content_type->userAllowed('edit')) { throw new ContentEditException(__d('content', 'You are not allowed to create contents of this type ({0}).', $content->content_type->name)); } if (!empty($this->request->data)) { if (empty($this->request->data['regenerate_slug'])) { $this->Contents->behaviors()->Sluggable->config(['on' => 'create']); } else { unset($this->request->data['regenerate_slug']); } $content->accessible([ 'id', 'content_type_id', 'content_type_slug', 'translation_for', 'created_by', ], false); $content = $this->Contents->patchEntity($content, $this->request->data()); if ($this->Contents->save($content, ['atomic' => true, 'associated' => ['Roles']])) { $this->Flash->success(__d('content', 'Content updated!')); $this->redirect("/admin/content/manage/edit/{$id}"); } else { $this->Flash->danger(__d('content', 'Something went wrong, please check your information.')); } } $languages = LocaleToolbox::languagesList(); $roles = $this->Contents->Roles->find('list'); $this->title(__d('content', 'Editing Content: {0} <small>({1})</small>', $content->title, $content->content_type_slug)); $this->set(compact('content', 'languages', 'roles')); $this->Breadcrumb ->push('/admin/content/manage/index') ->push(__d('content', 'Editing content'), '#'); }
Edit form for the given content. @param int $id Content's ID @param false|int $revisionId Fill form with content's revision information @return void @throws \Content\Error\ContentNotFoundException When content type, or when content content was not found @throws \Content\Error\ContentEditException When user is not allowed to edit contents of this type
entailment
public function translate($contentId) { $this->loadModel('Content.Contents'); $content = $this->Contents->get($contentId, ['contain' => 'ContentTypes']); if (!$content || empty($content->content_type)) { throw new ContentNotFoundException(__d('content', 'The requested page was not found.')); } if (!$content->content_type->userAllowed('translate')) { throw new ContentTranslateException(__d('content', 'You are not allowed to translate contents of this type ({0}).', $content->content_type->name)); } if (!$content->language || $content->translation_for) { $this->Flash->danger(__d('content', 'You cannot translate this content.')); $this->redirect(['plugin' => 'Content', 'controller' => 'manage', 'action' => 'index']); } $translations = $this->Contents ->find() ->where(['translation_for' => $content->id]) ->all(); $languages = LocaleToolbox::languagesList(); $illegal = array_merge([$content->language], $translations->extract('language')->toArray()); foreach ($languages as $code => $name) { if (in_array($code, $illegal)) { unset($languages[$code]); } } if (!empty($languages) && !empty($this->request->data['language']) && !empty($this->request->data['title']) && $this->request->data['language'] !== $content->language ) { $this->Contents->fieldable(false); // fix, wont trigger fields validation $newContent = $this->Contents->newEntity([ 'content_type_id' => $content->get('content_type_id'), 'content_type_slug' => $content->get('content_type_slug'), 'title' => $content->get('title'), 'status' => false, 'title' => $this->request->data['title'], 'translation_for' => $content->id, 'language' => $this->request->data['language'], ]); if ($this->Contents->save($newContent)) { $this->Flash->success(__d('content', 'Translation successfully created and was marked as unpublished. Complete the translation before publishing.')); $this->redirect(['plugin' => 'Content', 'controller' => 'manage', 'action' => 'edit', $newContent->id]); } else { $this->Flash->set(__d('content', 'Translation could not be created'), [ 'element' => 'System.installer_errors', 'params' => ['errors' => $newContent->errors()], ]); } } $this->title(__d('content', 'Translate Content')); $this->set(compact('content', 'translations', 'languages')); $this->Breadcrumb ->push('/admin/content/manage') ->push(__d('content', 'Translating content'), ''); }
Translate the given content to a different language. @param int $contentId Content's ID @return void @throws \Content\Error\ContentNotFoundException When content type, or when content content was not found @throws \Content\Error\ContentTranslateException When user is not allowed to translate contents of this type
entailment
public function delete($contentId) { $this->loadModel('Content.Contents'); $content = $this->Contents->get($contentId, ['contain' => ['ContentTypes']]); if (!$content || empty($content->content_type)) { throw new ContentNotFoundException(__d('content', 'The requested page was not found.')); } if (!$content->content_type->userAllowed('translate')) { throw new ContentDeleteException(__d('content', 'You are not allowed to delete contents of this type ({0}).', $content->content_type->name)); } if ($this->Contents->delete($content, ['atomic' => true])) { $this->Flash->success(__d('content', 'Content was successfully removed!')); } else { $this->Flash->danger(__d('content', 'Unable to remove this content, please try again.')); } $this->title(__d('content', 'Delete Content')); $this->redirect($this->referer()); }
Deletes the given content by ID. @param int $contentId Content's ID @return void
entailment
public function deleteRevision($contentId, $revisionId) { $this->loadModel('Content.ContentRevisions'); $revision = $this->ContentRevisions->find() ->where(['id' => $revisionId, 'content_id' => $contentId]) ->first(); if ($this->ContentRevisions->delete($revision, ['atomic' => true])) { $this->Flash->success(__d('content', 'Revision was successfully removed!')); } else { $this->Flash->danger(__d('content', 'Unable to remove this revision, please try again.')); } $this->title(__d('content', 'Editing Content Revision')); $this->redirect($this->referer()); }
Removes the given revision of the given content. @param int $contentId Content's ID @param int $revisionId Revision's ID @return void Redirects to previous page
entailment
public function isKeyValid() { // Check to see if the key is valid $response = $this->sendRequest('key=' . $this->wordPressAPIKey . '&blog=' . $this->blogURL, $this->akismetServer, '/' . $this->akismetVersion . '/verify-key'); return $response[1] == 'valid'; }
Makes a request to the Akismet service to see if the API key passed to the constructor is valid. Use this method if you suspect your API key is invalid. @return bool True is if the key is valid, false if not.
entailment
public function isCommentSpam() { $response = $this->sendRequest($this->getQueryString(), $this->wordPressAPIKey . '.rest.akismet.com', '/' . $this->akismetVersion . '/comment-check'); if ($response[1] == 'invalid' && !$this->isKeyValid()) { throw new exception('The Wordpress API key passed to the Akismet constructor is invalid. Please obtain a valid one from http://wordpress.com/api-keys/'); } return ($response[1] == 'true'); }
Tests for spam. Uses the web service provided by {@link http://www.akismet.com Akismet} to see whether or not the submitted comment is spam. Returns a boolean value. @return bool True if the comment is spam, false if not @throws Will throw an exception if the API key passed to the constructor is invalid.
entailment
public function submitSpam() { $this->sendRequest($this->getQueryString(), $this->wordPressAPIKey . '.' . $this->akismetServer, '/' . $this->akismetVersion . '/submit-spam'); }
Submit spam that is incorrectly tagged as ham. Using this function will make you a good citizen as it helps Akismet to learn from its mistakes. This will improve the service for everybody.
entailment
public function submitHam() { $this->sendRequest($this->getQueryString(), $this->wordPressAPIKey . '.' . $this->akismetServer, '/' . $this->akismetVersion . '/submit-ham'); }
Submit ham that is incorrectly tagged as spam. Using this function will make you a good citizen as it helps Akismet to learn from its mistakes. This will improve the service for everybody.
entailment
public function send() { $this->response = ''; $fs = fsockopen($this->host, $this->port, $this->errorNumber, $this->errorString, 3); if ($this->errorNumber != 0) { throw new Exception('Error connecting to host: ' . $this->host . ' Error number: ' . $this->errorNumber . ' Error message: ' . $this->errorString); } if ($fs !== false) { @fwrite($fs, $this->request); while (!feof($fs)) { $this->response .= fgets($fs, $this->responseLength); } fclose($fs); } }
Sends the data to the remote host. @throws An exception is thrown if a connection cannot be made to the remote host.
entailment
public function parse($criteria = '') { if (empty($criteria)) { $criteria = $this->_criteria; } $criteria = trim(urldecode($criteria)); $criteria = preg_replace('/(-?[\w]+)\:"([^\s"]+)/', '"${1}:${2}', $criteria); $criteria = str_replace(['-"', '+"'], ['"-', '"+'], $criteria); $parts = str_getcsv($criteria, ' '); $tokens = []; foreach ($parts as $i => $t) { $t = trim($t); if (empty($t) || in_array(strtolower($t), ['or', 'and'])) { continue; } $where = null; if (isset($parts[$i - 1]) && in_array(strtolower($parts[$i - 1]), ['or', 'and']) ) { $where = $parts[$i - 1]; } $tokens[] = new Token($t, $where); } return $tokens; }
{@inheritDoc}
entailment
public function add() { $this->loadModel('Content.ContentTypes'); $this->loadModel('User.Roles'); $type = $this->ContentTypes->newEntity(); if ($this->request->data()) { $type = $this->ContentTypes->patchEntity($type, $this->request->data()); $errors = $type->errors(); $success = empty($errors); if ($success) { $success = $this->ContentTypes->save($type); if ($success) { $this->Flash->success(__d('content', 'Content type created, now attach some fields.')); $this->redirect(['plugin' => 'Content', 'controller' => 'fields', 'type' => $type->slug]); } } if (!$success) { $this->Flash->danger(__d('content', 'Content type could not be created, check your information.')); } } $roles = $this->Roles->find('list'); $this->title(__d('content', 'Define New Content Type')); $this->set(compact('type', 'roles')); $this->set('languages', LocaleToolbox::languagesList()); $this->Breadcrumb ->push('/admin/content/manage') ->push(__d('content', 'Content Types'), '/admin/content/types') ->push(__d('content', 'Creating Content Type'), '#'); }
Create new content type. @return void
entailment
public function edit($slug) { $this->loadModel('Content.ContentTypes'); $this->loadModel('User.Roles'); $type = $this->ContentTypes ->find() ->where(['slug' => $slug]) ->first(); if (!$type) { throw new NotFoundException(__d('content', 'Content type was not found!')); } if ($this->request->data()) { $type->accessible(['id', 'slug'], false); $data = $this->request->data(); $type = $this->ContentTypes->patchEntity($type, $data); if ($this->ContentTypes->save($type, ['associated' => ['Roles']])) { $this->Flash->success(__d('content', 'Content type updated!')); $this->redirect(['plugin' => 'Content', 'controller' => 'types', 'action' => 'edit', $type->slug]); } else { $this->Flash->danger(__d('content', 'Content type could not be updated, check your information.')); } } else { // fix for auto-fill "defaults.*" by FormHelper $this->request->data = $type->toArray(); } $roles = $this->Roles->find('list'); $this->title(__d('content', 'Configure Content Type')); $this->set(compact('type', 'roles')); $this->set('languages', LocaleToolbox::languagesList()); $this->Breadcrumb ->push('/admin/content/manage') ->push(__d('content', 'Content Types'), '/admin/content/types') ->push(__d('content', 'Editing "{0}" Content Type', $type->name), ''); }
Edit content type settings. @param string $slug Content type's slug @return void @throws \Cake\Network\Exception\NotFoundException When content type was not found.
entailment
public function delete($slug) { $this->loadModel('Content.ContentTypes'); $type = $this->ContentTypes->find() ->where(['slug' => $slug]) ->first(); if (!$type) { throw new NotFoundException(__d('content', 'Content type was not found!')); } if ($this->ContentTypes->delete($type)) { $this->Flash->success(__d('content', 'Content was deleted!')); } else { $$this->Flash->danger(__d('content', 'Content type could not be deleted, please try again.')); } $this->title(__d('content', 'Delete Content Type')); $this->redirect($this->referer()); }
Remove content type. All existing contents will not be removed. @param string $slug Content type's slug @return void @throws \Cake\Network\Exception\NotFoundException When content type was not found.
entailment
public function blocks(Collection $blocks = null) { if ($blocks) { $this->_blocks = $blocks; $this->homogenize(); } elseif ($this->_blocks === null) { $this->_prepareBlocks(); } return $this->_blocks; }
Gets or sets the block collection of this region. When passing a collection of blocks as first argument, all blocks in the collection will be homogenized, see homogenize() for details. @param \Cake\Collection\Collection $blocks Blocks collection if you want to overwrite current collection, leave empty to return current collection @return \Cake\Collection\Collection @see \Block\View\Region::homogenize()
entailment
public function blockLimit($number = null) { $number = $number !== null ? intval($number) : $number; $this->_blockLimit = $number; return $this; }
Limits the number of blocks in this region. Null means unlimited number. @param null|int $number Defaults to null @return \Block\View\Region
entailment
public function merge(Region $region, $homogenize = true) { if ($region->name() !== $this->name()) { $blocks1 = $this->blocks(); $blocks2 = $region->blocks(); $combined = $blocks1->append($blocks2)->toArray(false); $this->blocks(collection($combined)); if ($homogenize) { $this->homogenize(); } } return $this; }
Merge blocks from another region. You can not merge regions with the same machine-name, new blocks are appended to this region. @param \Block\View\Region $region Region to merge with @param bool $homogenize Set to true to make sure all blocks in the collection are marked as they belongs to this region @return \Block\View\Region This region with $region's blocks appended
entailment
public function homogenize() { $this->_blocks = $this->blocks()->map(function ($block) { $block->region->set('region', $this->_machineName); return $block; }); return $this; }
Makes sure that every block in this region is actually marked as it belongs to this region. Used when merging blocks from another region. @return \Block\View\Region This region with homogenized blocks
entailment
public function render() { $html = ''; $i = 0; foreach ($this->blocks() as $block) { if ($this->_blockLimit !== null && $i === $this->_blockLimit) { break; } $html .= $block->render($this->_View); $i++; } return $html; }
Render all the blocks within this region. @return string
entailment
protected function _prepareBlocks() { $cacheKey = "{$this->_View->theme}_{$this->_machineName}"; $blocks = TableRegistry::get('Block.Blocks') ->find('all') ->cache($cacheKey, 'blocks') ->contain(['Roles', 'BlockRegions']) ->matching('BlockRegions', function ($q) { return $q->where([ 'BlockRegions.theme' => $this->_View->theme(), 'BlockRegions.region' => $this->_machineName, ]); }) ->where(['Blocks.status' => 1]) ->order(['BlockRegions.ordering' => 'ASC']); $blocks->sortBy(function ($block) { return $block->region->ordering; }, SORT_ASC); // remove blocks that cannot be rendered based on current request. $blocks = $blocks->filter(function ($block) { return $this->_filterBlock($block) && $block->renderable(); }); $this->blocks($blocks); }
Fetches all block entities that could be rendered within this region. @return void
entailment
protected function _filterBlock(Block $block) { $cacheKey = "allowed_{$block->id}"; $cache = static::cache($cacheKey); if ($cache !== null) { return $cache; } if (!empty($block->locale) && !in_array(I18n::locale(), (array)$block->locale) ) { return static::cache($cacheKey, false); } if (!$block->isAccessibleByUser()) { return static::cache($cacheKey, false); } $allowed = false; switch ($block->visibility) { case 'except': // Show on all pages except listed pages $allowed = !$this->_urlMatch($block->pages); break; case 'only': // Show only on listed pages $allowed = $this->_urlMatch($block->pages); break; case 'php': // Use custom PHP code to determine visibility $allowed = php_eval($block->pages, [ 'view' => &$this->_View, 'block' => &$block ]) === true; break; } if (!$allowed) { return static::cache($cacheKey, false); } return static::cache($cacheKey, true); }
Checks if the given block can be rendered. @param \Block\Model\Entity\Block $block Block entity @return bool True if can be rendered
entailment
protected function _urlMatch($patterns) { if (empty($patterns)) { return false; } $url = urldecode($this->_View->request->url); $path = str_starts_with($url, '/') ? str_replace_once('/', '', $url) : $url; if (option('url_locale_prefix')) { $patterns = explode("\n", $patterns); $locales = array_keys(quickapps('languages')); $localesPattern = '(' . implode('|', array_map('preg_quote', $locales)) . ')'; foreach ($patterns as &$p) { if (!preg_match("/^{$localesPattern}\//", $p)) { $p = I18n::locale() . '/' . $p; $p = str_replace('//', '/', $p); } } $patterns = implode("\n", $patterns); } // Convert path settings to a regular expression. // Therefore replace newlines with a logical or, /* with asterisks and "/" with the front page. $toReplace = [ '/(\r\n?|\n)/', // newlines '/\\\\\*/', // asterisks '/(^|\|)\/($|\|)/' // front '/' ]; $replacements = [ '|', '.*', '\1' . preg_quote($this->_View->Url->build('/'), '/') . '\2' ]; $patternsQuoted = preg_quote($patterns, '/'); $patterns = '/^(' . preg_replace($toReplace, $replacements, $patternsQuoted) . ')$/'; return (bool)preg_match($patterns, $path); }
Check if a current URL matches any pattern in a set of patterns. @param string $patterns String containing a set of patterns separated by \n, \r or \r\n @return bool TRUE if the path matches a pattern, FALSE otherwise
entailment
protected function _getAuthor() { $author = [ 'username' => __d('comment', 'anonymous'), 'name' => __d('comment', 'Anonymous'), 'web' => __d('comment', '(no website)'), 'email' => __d('comment', '(no email given)'), 'ip' => $this->get('author_ip'), ]; if (!empty($this->author_name)) { $author['name'] = $this->get('author_name'); } if (!empty($this->author_web)) { $author['web'] = $this->get('author_web'); } if (!empty($this->author_email)) { $author['email'] = $this->get('author_email'); } if ($this->has('user') || !empty($this->user_id)) { $user = $this->get('user'); if (!$user) { $user = TableRegistry::get('User.Users') ->find() ->where(['id' => $this->user_id]) ->first(); } if ($user && $user->id) { $author['name'] = $user->username; $author['email'] = $user->email; if (!empty($user->web)) { $author['web'] = $user->web; } } } if (empty($author['name'])) { $author['name'] = __d('comment', 'Anonymous'); } return new User($author); }
Returns comment's author as a mock user entity. With the properties below: - `username`: QuickAppsCMS's `username` (the one used for login) if comment's author was a logged in user. "anonymous" otherwise. - `name`: Real name of the author. `Anonymous` if not provided. - `web`: Author's website (if provided). - `email`: Author's email (if provided). @return \User\Model\Entity\User
entailment
public function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) { $v_result=1; // ----- Magic quotes trick $this->privDisableMagicQuotes(); // ----- Check the path if (($p_path == "") || ((substr($p_path, 0, 1) != "/") && (substr($p_path, 0, 3) != "../") && (substr($p_path, 1, 2)!=":/"))) { $p_path = "./".$p_path; } // ----- Reduce the path last (and duplicated) '/' if (($p_path != "./") && ($p_path != "/")) { // ----- Look for the path end '/' while (substr($p_path, -1) == "/") { $p_path = substr($p_path, 0, strlen($p_path)-1); } } // ----- Look for path to remove format (should end by /) if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) { $p_remove_path .= '/'; } $p_remove_path_size = strlen($p_remove_path); // ----- Open the zip file if (($v_result = $this->privOpenFd('rb')) != 1) { $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Read the central directory informations $v_central_dir = array(); if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Start at beginning of Central Dir $v_pos_entry = $v_central_dir['offset']; // ----- Read each entry $j_start = 0; for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { // ----- Read next Central dir entry @rewind($this->zip_fd); if (@fseek($this->zip_fd, $v_pos_entry)) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return return PclZip::errorCode(); } // ----- Read the file header $v_header = array(); if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Store the index $v_header['index'] = $i; // ----- Store the file position $v_pos_entry = ftell($this->zip_fd); // ----- Look for the specific extract rules $v_extract = false; // ----- Look for extract by name rule if ((isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { // ----- Look if the filename is in the list for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_extract); $j++) { // ----- Look for a directory if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") { // ----- Look if the directory is in the filename path if ((strlen($v_header['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { $v_extract = true; } } // ----- Look for a filename elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { $v_extract = true; } } } // ----- Look for extract by ereg rule // ereg() is deprecated with PHP 5.3 /* else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) { $v_extract = true; } } */ // ----- Look for extract by preg rule elseif ((isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { $v_extract = true; } } // ----- Look for extract by index rule elseif ((isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { // ----- Look if the index is in the list for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_extract); $j++) { if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { $v_extract = true; } if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { $j_start = $j+1; } if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { break; } } } // ----- Look for no rule, which means extract all the archive else { $v_extract = true; } // ----- Check compression method if (($v_extract) && (($v_header['compression'] != 8) && ($v_header['compression'] != 0))) { $v_header['status'] = 'unsupported_compression'; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { $this->privSwapBackMagicQuotes(); PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, "Filename '".$v_header['stored_filename']."' is " ."compressed by an unsupported compression " ."method (".$v_header['compression'].") "); return PclZip::errorCode(); } } // ----- Check encrypted files if (($v_extract) && (($v_header['flag'] & 1) == 1)) { $v_header['status'] = 'unsupported_encryption'; // ----- Look for PCLZIP_OPT_STOP_ON_ERROR if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { $this->privSwapBackMagicQuotes(); PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, "Unsupported encryption for " ." filename '".$v_header['stored_filename'] ."'"); return PclZip::errorCode(); } } // ----- Look for real extraction if (($v_extract) && ($v_header['status'] != 'ok')) { $v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++]); if ($v_result != 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } $v_extract = false; } // ----- Look for real extraction if ($v_extract) { // ----- Go to the file position @rewind($this->zip_fd); if (@fseek($this->zip_fd, $v_header['offset'])) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); // ----- Return return PclZip::errorCode(); } // ----- Look for extraction as string if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { $v_string = ''; // ----- Extracting the file $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options); if ($v_result1 < 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result1; } // ----- Get the only interesting attributes if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Set the file content $p_file_list[$v_nb_extracted]['content'] = $v_string; // ----- Next extracted file $v_nb_extracted++; // ----- Look for user callback abort if ($v_result1 == 2) { break; } } // ----- Look for extraction in standard output elseif ((isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { // ----- Extracting the file in standard output $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); if ($v_result1 < 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result1; } // ----- Get the only interesting attributes if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Look for user callback abort if ($v_result1 == 2) { break; } } // ----- Look for normal extraction else { // ----- Extracting the file $v_result1 = $this->privExtractFile($v_header, $p_path, $p_remove_path, $p_remove_all_path, $p_options); if ($v_result1 < 1) { $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result1; } // ----- Get the only interesting attributes if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); return $v_result; } // ----- Look for user callback abort if ($v_result1 == 2) { break; } } } } // ----- Close the zip file $this->privCloseFd(); $this->privSwapBackMagicQuotes(); // ----- Return return $v_result; }
--------------------------------------------------------------------------------
entailment
public function privReadEndCentralDir(&$p_central_dir) { $v_result=1; // ----- Go to the end of the zip file $v_size = filesize($this->zipname); @fseek($this->zip_fd, $v_size); if (@ftell($this->zip_fd) != $v_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); // ----- Return return PclZip::errorCode(); } // ----- First try : look if this is an archive with no commentaries (most of the time) // in this case the end of central dir is at 22 bytes of the file end $v_found = 0; if ($v_size > 26) { @fseek($this->zip_fd, $v_size-22); if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); // ----- Return return PclZip::errorCode(); } // ----- Read for bytes $v_binary_data = @fread($this->zip_fd, 4); $v_data = @unpack('Vid', $v_binary_data); // ----- Check signature if ($v_data['id'] == 0x06054b50) { $v_found = 1; } $v_pos = ftell($this->zip_fd); } // ----- Go back to the maximum possible size of the Central Dir End Record if (!$v_found) { $v_maximum_size = 65557; // 0xFFFF + 22; if ($v_maximum_size > $v_size) { $v_maximum_size = $v_size; } @fseek($this->zip_fd, $v_size-$v_maximum_size); if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); // ----- Return return PclZip::errorCode(); } // ----- Read byte per byte in order to find the signature $v_pos = ftell($this->zip_fd); $v_bytes = 0x00000000; while ($v_pos < $v_size) { // ----- Read a byte $v_byte = @fread($this->zip_fd, 1); // ----- Add the byte //$v_bytes = ($v_bytes << 8) | Ord($v_byte); // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number // Otherwise on systems where we have 64bit integers the check below for the magic number will fail. $v_bytes = (($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte); // ----- Compare the bytes if ($v_bytes == 0x504b0506) { $v_pos++; break; } $v_pos++; } // ----- Look if not found end of central dir if ($v_pos == $v_size) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); // ----- Return return PclZip::errorCode(); } } // ----- Read the first 18 bytes of the header $v_binary_data = fread($this->zip_fd, 18); // ----- Look for invalid block size if (strlen($v_binary_data) != 18) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); // ----- Return return PclZip::errorCode(); } // ----- Extract the values $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); // ----- Check the global size if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { // ----- Removed in release 2.2 see readme file // The check of the file size is a little too strict. // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. // While decrypted, zip has training 0 bytes if (0) { // ----- Error log PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'The central dir is not at the end of the archive.' .' Some trailing bytes exists after the archive.'); // ----- Return return PclZip::errorCode(); } } // ----- Get comment if ($v_data['comment_size'] != 0) { $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); } else { $p_central_dir['comment'] = ''; } $p_central_dir['entries'] = $v_data['entries']; $p_central_dir['disk_entries'] = $v_data['disk_entries']; $p_central_dir['offset'] = $v_data['offset']; $p_central_dir['size'] = $v_data['size']; $p_central_dir['disk'] = $v_data['disk']; $p_central_dir['disk_start'] = $v_data['disk_start']; // TBC //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { //} // ----- Return return $v_result; }
--------------------------------------------------------------------------------
entailment
public function validationDefault(Validator $validator) { return $validator ->add('theme', 'validTheme', [ 'rule' => function ($value, $context) { $exists = plugin() ->filter(function ($plugin) use ($value) { return $plugin->isTheme && $plugin->name === $value; }) ->first(); return !empty($exists); }, 'message' => __d('block', 'Invalid theme for region.'), ]); }
Default validation rules. @param \Cake\Validation\Validator $validator The validator object @return \Cake\Validation\Validator
entailment
public function afterSave(Event $event, BlockRegion $blockRegion, ArrayObject $options = null) { $this->clearCache(); }
Clears blocks cache after assignment changes. @param \Cake\Event\Event $event The event that was triggered @param \Block\Model\Entity\BlockRegion $blockRegion The block entity that was deleted @param \ArrayObject $options Additional options given as an array @return void
entailment
public function version() { if (parent::version() !== null) { return parent::version(); } $this->_version = ''; $lib = strtolower($this->_packageName); if ($lib === 'lib-icu') { $lib = 'intl'; } elseif (stripos($lib, 'ext-') === 0) { $lib = substr($lib, 4); } if ($lib === 'php') { $this->_version = PHP_VERSION; } elseif (function_exists('phpversion')) { $version = phpversion($lib); $this->_version = $version === false ? '' : $version; } elseif (function_exists('extension_loaded')) { $this->_version = extension_loaded($lib) ? '99999' : ''; } return $this->_version; }
{@inheritdoc} Gets library version using `phpversion()` function if possible, an empty string will be returned if no version could be found (library not installed). @return string Package's version, for instance `1.2.x-dev`
entailment
protected function _getLib() { require_once Plugin::classPath('Captcha') . 'Lib/ayah.php'; return new \AYAH([ 'publisher_key' => $this->config('publisherKey'), 'scoring_key' => $this->config('scoringKey'), 'web_service_host' => 'ws.areyouahuman.com', 'use_curl' => true, 'debug_mode' => Configure::read('debug'), ]); }
Gets an instance of AYAH library. @return object
entailment
public function afterSave(Event $event, Menu $menu, ArrayObject $options = null) { if ($menu->isNew()) { $block = TableRegistry::get('Block.Blocks')->newEntity([ 'title' => $menu->title . ' ' . __d('menu', '[menu: {0}]', $menu->id), 'handler' => 'Menu\Widget\MenuWidget', 'description' => (!empty($menu->description) ? $menu->description : __d('menu', 'Associated block for "{0}" menu.', $menu->title)), 'visibility' => 'except', 'pages' => null, 'locale' => null, 'status' => 0, 'settings' => ['menu_id' => $menu->id] ], ['validate' => false]); TableRegistry::get('Block.Blocks')->save($block); } $this->clearCache(); }
Triggered after menu was persisted in DB. It will also create menu's associated block if not exists. @param \Cake\Event\Event $event The event that was triggered @param \Menu\Model\Entity\Menu $menu The menu entity that was saved @param \ArrayObject $options Options given as an array @return void
entailment
public function afterDelete(Event $event, Menu $menu, ArrayObject $options = null) { $blocks = TableRegistry::get('Block.Blocks') ->find('all') ->select(['id', 'handler', 'settings']) ->where(['handler' => 'Menu\Widget\MenuWidget']); foreach ($blocks as $block) { if (!empty($menu->settings['menu_id']) && $menu->settings['menu_id'] == $menu->id) { TableRegistry::get('Block.Blocks')->delete($block); return; } } $this->clearCache(); }
Triggered after menu was removed from DB. This method will delete any associated block the removed menu could have. This operation may take a while if there are too many menus created. @param \Cake\Event\Event $event The event that was triggered @param \Menu\Model\Entity\Menu $menu The menu entity that was deleted @param \ArrayObject $options Options given as an array @return void
entailment
public function index() { $this->loadModel('System.Options'); $languages = LocaleToolbox::languagesList(); $arrayContext = [ 'schema' => [ 'site_title' => 'string', 'site_slogan' => 'string', 'site_description' => 'string', 'site_email' => 'string', 'site_contents_home' => 'integer', 'site_maintenance' => 'boolean', 'site_maintenance_ip' => 'string', 'site_maintenance_message' => 'string', 'default_language' => 'string', 'url_locale_prefix' => 'string', ], 'defaults' => [], 'errors' => [], ]; $variables = $this->Options ->find() ->where(['name IN' => array_keys($arrayContext['schema'])]) ->all(); foreach ($variables as $var) { $arrayContext['defaults'][$var->name] = $var->value; } if ($this->request->data()) { $validator = $this->_mockValidator(); $errors = $validator->errors($this->request->data()); if (empty($errors)) { foreach ($this->request->data() as $k => $v) { $this->Options->update($k, $v, null, false); } snapshot(); $this->Flash->success(__d('system', 'Configuration successfully saved!')); $this->redirect($this->referer()); } else { $arrayContext['errors'] = $errors; $this->Flash->danger(__d('system', 'Configuration could not be saved, please check your information.')); } } $pluginSettings = plugin() ->filter(function ($plugin) { return !$plugin->isTheme && $plugin->hasSettings; }); $this->title(__d('system', 'Site’ Configuration')); $this->set(compact('arrayContext', 'languages', 'variables', 'pluginSettings')); $this->Breadcrumb->push('/admin/system/configuration'); }
Main action. @return void
entailment
protected function _mockValidator() { $validator = new Validator(); return $validator ->requirePresence('site_title') ->add('site_title', 'length', [ 'rule' => ['minLength', 3], 'message' => __d('system', "Site's name must be at least 3 characters long."), ]) ->requirePresence('site_email') ->add('site_email', 'validEmail', [ 'rule' => 'email', 'message' => __d('system', 'Invalid e-Mail.'), ]); }
Created a mock validator object used when validating options @return \Cake\Validation\Validator
entailment
public function index() { $this->loadModel('Menu.MenuLinks'); $links = $this->MenuLinks ->find('threaded') ->where([ 'parent_id IN' => $this->MenuLinks ->find() ->select(['id']) ->where(['url' => '/admin/system/structure']) ]) ->all(); $this->title(__d('system', 'Site’s Structure')); $this->set('links', $links); $this->Breadcrumb->push('/admin/system/structure'); }
Index. @return void
entailment
public function render(View $view) { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->render($this, $view); } return ''; }
Renders this block/widget. @return string
entailment
public function settings(View $view) { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->settings($this, $view); } return ''; }
Renders block/widget's settings. @return string
entailment
public function validateSettings(array $settings, Validator $validator) { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->validateSettings($this, $settings, $validator); } }
Validates block/widget's settings. @return void
entailment
public function defaultSettings() { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->defaultSettings($this); } return []; }
Gets block/widget's default settings. @return array
entailment
public function beforeSave() { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->beforeSave($this); } }
Trigger block/widget's callback. @return bool|null
entailment
public function afterDelete() { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->afterDelete($this); } }
Trigger block/widget's callback. @return void
entailment
public function forgot() { if (!empty($this->request->data['username'])) { $this->loadModel('User.Users'); $user = $this->Users ->find() ->where(['Users.username' => $this->request->data['username']]) ->orWhere(['Users.email' => $this->request->data['username']]) ->first(); if ($user) { $emailSent = NotificationManager::passwordRequest($user)->send(); if ($emailSent) { $this->Flash->success(__d('user', 'Further instructions have been sent to your e-mail address.')); } else { $this->Flash->warning(__d('user', 'Instructions could not been sent to your e-mail address, please try again later.')); } } else { $this->Flash->danger(__d('user', 'Sorry, "{0}" is not recognized as a user name or an e-mail address.', $this->request->data['username'])); } } $this->title(__d('user', 'Password Recovery')); }
Starts the password recovery process. @return void
entailment
public function cancelRequest() { $user = user(); $this->loadModel('User.Users'); $user = $this->Users->get($user->id); $emailSent = NotificationManager::cancelRequest($user)->send(); if ($emailSent) { $this->Flash->success(__d('user', 'Further instructions have been sent to your e-mail address.')); } else { $this->Flash->warning(__d('user', 'Instructions could not been sent to your e-mail address, please try again later.')); } $this->title(__d('user', 'Account Cancellation')); $this->redirect($this->referer()); }
Here is where users can request to remove their accounts. Only non-administrator users can be canceled this way. User may request to cancel their accounts by using the form rendered by this action, an e-mail will be send with a especial link which will remove the account. @return void Redirects to previous page
entailment
public function cancel($userId, $code) { $this->loadModel('User.Users'); $user = $this->Users ->find() ->where(['id' => $userId]) ->contain(['Roles']) ->limit(1) ->first(); if (in_array(ROLE_ID_ADMINISTRATOR, $user->role_ids) && $this->Users->countAdministrators() === 1 ) { $this->Flash->warning(__d('user', 'You are the last administrator in the system, your account cannot be canceled.')); $this->redirect($this->referer()); } if ($user && $code == $user->cancel_code) { if ($this->Users->delete($user)) { NotificationManager::canceled($user)->send(); $this->Flash->success(__d('user', 'Account successfully canceled')); } else { $this->Flash->danger(__d('user', 'Account could not be canceled due to an internal error, please try again later.')); } } else { $this->Flash->warning(__d('user', 'Not user was found, invalid cancellation URL.')); } $this->title(__d('user', 'Account Cancellation')); $this->redirect($this->referer()); }
Here is where user's account is actually removed. @param int $userId The ID of the user whose account is being canceled @param string $code Cancellation code, code is a MD5 hash of user's encrypted password + site's salt @return void Redirects to previous page
entailment
public function register() { $this->loadModel('User.Users'); $this->Users->fieldable(false); $user = $this->Users->newEntity(); $registered = false; $languages = LocaleToolbox::languagesList(); if ($this->request->data()) { $user->set('status', 0); $user->accessible(['id', 'token', 'status', 'last_login', 'created', 'roles'], false); $user = $this->Users->patchEntity($user, $this->request->data); if ($this->Users->save($user)) { NotificationManager::welcome($user)->send(); $this->Flash->success(__d('user', 'Account successfully created, further instructions have been sent to your e-mail address.', ['key' => 'register'])); $registered = true; } else { $this->Flash->danger(__d('user', 'Account could not be created, please check your information.'), ['key' => 'register']); } } $this->title(__d('user', 'Registration')); $this->set(compact('registered', 'user', 'languages')); }
Registers a new user. @return void
entailment
public function activationEmail() { $this->loadModel('User.Users'); $sent = false; if (!empty($this->request->data['username'])) { $user = $this->Users ->find() ->where([ 'OR' => [ 'username' => $this->request->data['username'], 'email' => $this->request->data['username'], ], 'status' => 0 ]) ->limit(1) ->first(); if ($user) { NotificationManager::welcome($user)->send(); $this->Flash->success(__d('user', 'Instructions have been sent to your e-mail address.'), ['key' => 'activation_email']); $sent = true; } else { $this->Flash->danger(__d('user', 'No account was found matching the given username/email.'), ['key' => 'activation_email']); } } $this->title(__d('user', 'Activation Request')); $this->set(compact('sent')); }
Users can request to re-send activation instructions to their email address. @return void
entailment
public function activate($token = null) { $activated = false; if ($token === null) { $this->redirect('/'); } $this->loadModel('User.Users'); $user = $this->Users ->find() ->select(['id', 'name', 'token']) ->where(['status' => 0, 'token' => $token]) ->limit(1) ->first(); if ($user) { if ($this->Users->updateAll(['status' => 1], ['id' => $user->id])) { NotificationManager::activated($user)->send(); $activated = true; $this->Flash->success(__d('user', 'Account successfully activated.'), ['key' => 'activate']); } else { $this->Flash->danger(__d('user', 'Account could not be activated, please try again later.'), ['key' => 'activate']); } } else { $this->Flash->warning(__d('user', 'Account not found or is already active.'), ['key' => 'activate']); } $this->title(__d('user', 'Account Activation')); $this->set(compact('activated', 'token')); }
Activates a registered user. @param string $token A valid user token @return void
entailment
public function unauthorized() { $this->loadModel('User.Users'); if ($this->request->is('post')) { $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); return $this->redirect($this->Auth->redirectUrl()); } else { $this->Flash->danger(__d('user', 'Username or password is incorrect')); } } }
Renders the "unauthorized" screen, when an user attempts to access to a restricted area. @return \Cake\Network\Response|null
entailment
public function me() { $this->loadModel('User.Users'); $user = $this->Users->get(user()->id, ['conditions' => ['status' => 1]]); $languages = LocaleToolbox::languagesList(); if ($this->request->data()) { $user->accessible(['id', 'username', 'roles', 'status'], false); $user = $this->Users->patchEntity($user, $this->request->data); if ($this->Users->save($user)) { $this->Flash->success(__d('user', 'User information successfully updated!'), ['key' => 'user_profile']); $this->redirect($this->referer()); } else { $this->Flash->danger(__d('user', 'User information could not be saved, please check your information.'), ['key' => 'user_profile']); } } $this->title(__d('user', 'Account')); $this->set(compact('user', 'languages')); $this->viewMode('full'); }
Renders user's "my profile" form. Here is where user can change their information. @return void
entailment
public function profile($id = null) { $this->loadModel('User.Users'); $id = $id === null ? user()->id : $id; $conditions = []; if ($id != user()->id) { $conditions = ['status' => 1, 'public_profile' => true]; } $user = $this->Users->get(intval($id), ['conditions' => $conditions]); $this->title(__d('user', 'User’s Profile')); $this->viewMode('full'); $this->set(compact('user')); }
Shows profile information for the given user. @param int|null $id User's ID, or NULL for currently logged user @return void @throws \Cake\ORM\Exception\RecordNotFoundException When user not found, or users has marked profile as private
entailment
public function info() { list(, $handlerName) = namespaceSplit(get_class($this)); return [ 'type' => 'varchar', 'name' => (string)$handlerName, 'description' => (string)$handlerName, 'hidden' => false, 'maxInstances' => 0, 'searchable' => true, ]; }
Returns an array of information of this field. Valid options are: - `type` (string): Type of data this field stores, possible values are: datetime, decimal, int, text, varchar. - `name` (string): Human readable name of this field. ex. `Selectbox` Defaults to class name. - `description` (string): Something about what this field does or allows to do. Defaults to class name. - `hidden` (bool): If set to false users can not use this field via Field UI. Defaults to true, users can use it via Field UI. - `maxInstances` (int): Maximum number instances of this field a table can have. Set to 0 to indicates no limits. Defaults to 0. - `searchable` (bool): Whether this field can be searched using WHERE clauses. @return array
entailment
public function main() { if (!defined('QUICKAPPS_CORE')) { return parent::main(); } if (empty($this->params['xml'])) { $this->out(__d('cms', '<info>Current Paths:</info>'), 2); $this->out(__d('cms', '* QuickApps Core: {0}', [normalizePath(QUICKAPPS_CORE)])); $this->out(__d('cms', '* CakePHP Core: {0}', [normalizePath(CORE_PATH)])); $this->out(__d('cms', '* Site Path: {0}', [normalizePath(ROOT)])); $this->out(''); $this->out(__d('cms', '<info>Available Shells:</info>'), 2); } $shellList = $this->Command->getShellList(); if (empty($shellList)) { return; } if (empty($this->params['xml'])) { $this->_asText($shellList); } else { $this->_asXml($shellList); } }
Main function Prints out the list of shells. @return void
entailment
protected function _asText($shellList) { if (!defined('QUICKAPPS_CORE')) { return parent::_asText($shellList); } foreach ($shellList as $plugin => $commands) { sort($commands); if ($plugin == 'app') { $plugin = 'QUICKAPPS'; } elseif ($plugin == 'CORE') { $plugin = 'CAKEPHP'; } $this->out(__d('cms', '[<info>{0}</info>] {1}', $plugin, implode(', ', $commands))); } $this->out(); $this->out(__d('cms', 'To run an QuickAppsCMS or CakePHP command, type <info>"qs shell_name [args]"</info>')); $this->out(__d('cms', 'To run a Plugin command, type <info>"qs PluginName.shell_name [args]"</info>')); $this->out(__d('cms', 'To get help on a specific command, type <info>"qs shell_name --help"</info>'), 2); }
Output text. @param array $shellList The shell list. @return void
entailment
public function getOptionParser() { if (!defined('QUICKAPPS_CORE')) { return parent::getOptionParser(); } $parser = parent::getOptionParser(); $parser ->description(__d('cms', 'Get the list of available shells for this QuickAppsCMS installation.')) ->addOption('xml', [ 'help' => __d('cms', 'Get the listing as XML.'), 'boolean' => true, ]); return $parser; }
Gets the option parser instance and configures it. @return \Cake\Console\ConsoleOptionParser
entailment
protected function _welcome() { if (!defined('QUICKAPPS_CORE')) { return parent::_welcome(); } $this->out(); $this->out(__d('cms', '<info>Welcome to QuickApps CMS v{0} Console</info>', quickapps('version'))); $this->hr(); $this->out(__d('cms', 'Site Title: {0}', option('site_title'))); $this->hr(); $this->out(); }
Displays a header for the shell @return void
entailment
public function renderContent(Event $event, Content $content, $options = []) { $View = $event->subject(); $viewMode = $View->viewMode(); $try = [ "Content.render_content_{$content->content_type_slug}_{$viewMode}_{$content->slug}", "Content.render_content_{$content->content_type_slug}_{$content->slug}", "Content.render_content_{$viewMode}_{$content->slug}", "Content.render_content_{$content->slug}", "Content.render_content_{$content->content_type_slug}_{$viewMode}", "Content.render_content_{$content->content_type_slug}", "Content.render_content_{$viewMode}", 'Content.render_content', ]; foreach ($try as $element) { if ($View->elementExists($element)) { return $View->element($element, compact('content', 'options')); } } return ''; }
Renders a single Content Entity. You can define `specialized-renders` according to your needs as follow. This method looks for specialized renders in the order described below, if one is not found we look the next one, etc. ### Content's slug based [other-render]_[content-slug].ctp Where `[other-render]` is any of the ones described below, for instance when rendering an article which slug is `hello-world`: - render_content_[content-type]_[view-mode]_[hello-world].ctp - render_content_[content-type]_[hello-world].ctp - render_content_[view-mode]_[hello-world].ctp - render_content_[hello-world].ctp If none of these exists, then it will try to use one of renders described below. ### Render content based on content-type & view-mode render_content_[content-type]_[view-mode].ctp Renders the given content based on `content-type` + `view-mode` combination, for example: - render_content_article_full.ctp: Render for "article" contents in "full" view-mode. - render_content_article_search-result.ctp: Render for "article" contents in "search-result" view-mode. - render_content_basic-page_search-result.ctp: Render for "basic-page" contents in "search-result" view-mode. ### Render content based on content-type render_content_[content-type].ctp Similar as before, but just based on `content-type` (and any view-mode), for example: - render_content_article.ctp: Render for "article" contents. - render_content_basic-page.ctp: Render for "basic-page" contents ### Render content based on view-mode render_content_[view-mode].ctp Similar as before, but just based on `view-mode` (and any content-type), for example: - render_content_rss.ctp: Render any content (article, page, etc) in "rss" view-mode. - render_content_full.ctp: Render any content (article, page, etc) in "full" view-mode. NOTE: To avoid collisions between `view-mode` names and `content-type` names, you should alway use unique and descriptive names as possible when defining new content types. By default, Content plugin defines the following view- modes: `default`, `teaser`, `search-result`, `rss`, `full`. ### Default render_content.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_content.ctp`. --- NOTE: Please note the difference between "_" and "-" @param \Cake\Event\Event $event The event that was triggered @param \Content\Model\Entity\Content $content The content to render @param array $options Additional options as an array @return string HTML
entailment
public function initialize(array $config) { $this->belongsTo('ContentTypes', [ 'className' => 'Content.ContentTypes', 'propertyName' => 'content_type', 'fields' => ['slug', 'name', 'description'], 'conditions' => ['Contents.content_type_slug = ContentTypes.slug'] ]); $this->belongsTo('TranslationOf', [ 'className' => 'Content\Model\Table\ContentsTable', 'foreignKey' => 'translation_for', 'propertyName' => 'translation_of', 'fields' => ['slug', 'title', 'description'], ]); $this->belongsToMany('Roles', [ 'className' => 'User.Roles', 'propertyName' => 'roles', 'through' => 'Content.ContentsRoles', ]); $this->hasMany('ContentRevisions', [ 'className' => 'Content.ContentRevisions', 'dependent' => true, ]); $this->hasMany('Translations', [ 'className' => 'Content\Model\Table\ContentsTable', 'foreignKey' => 'translation_for', 'dependent' => true, ]); $this->addBehavior('Timestamp'); $this->addBehavior('Comment.Commentable'); $this->addBehavior('Sluggable'); $this->addBehavior('User.WhoDidIt', [ 'idCallable' => function () { return user()->get('id'); } ]); $this->addBehavior('Field.Fieldable', [ 'bundle' => function ($entity) { if ($entity->has('content_type_slug')) { return $entity->content_type_slug; } if ($entity->has('id')) { return $this ->get($entity->id, [ 'fields' => ['id', 'content_type_slug'], 'fieldable' => false, ]) ->content_type_slug; } return ''; } ]); $this->addBehavior('Search.Searchable', [ 'fields' => function ($content) { $words = ''; if ($content->has('title')) { $words .= " {$content->title}"; } if ($content->has('description')) { $words .= " {$content->description}"; } if (!$content->has('_fields')) { return $words; } foreach ($content->_fields as $virtualField) { $words .= " {$virtualField}"; } return $words; } ]); $this->addSearchOperator('promote', 'operatorPromote'); $this->addSearchOperator('author', 'operatorAuthor'); $this->addSearchOperator('limit', 'Search.Limit'); $this->addSearchOperator('modified', 'Search.Date', ['field' => 'modified']); $this->addSearchOperator('created', 'Search.Date', ['field' => 'created']); $this->addSearchOperator('type', 'Search.Generic', ['field' => 'content_type_slug', 'conjunction' => 'auto']); $this->addSearchOperator('term', 'operatorTerm'); $this->addSearchOperator('language', 'Search.Generic', ['field' => 'language', 'conjunction' => 'auto']); $this->addSearchOperator('order', 'Search.Order', ['fields' => ['slug', 'title', 'description', 'sticky', 'created', 'modified']]); }
Initialize a table instance. Called after the constructor. @param array $config Configuration options passed to the constructor @return void
entailment
public function beforeSave(Event $event, Entity $entity, ArrayObject $options = null) { $this->_saveRevision($entity); $this->_ensureStatus($entity); return true; }
This callback performs two action, saving revisions and checking publishing constraints. - Saves a revision version of each content being saved if it has changed. - Verifies the publishing status and forces to be "false" if use has no publishing permissions for this content type. @param \Cake\Event\Event $event The event that was triggered @param \Content\Model\Entity\Content $entity The entity being saved @param \ArrayObject $options Array of options @return bool True on success
entailment
protected function _saveRevision(Entity $entity) { if ($entity->isNew()) { return; } try { $prev = TableRegistry::get('Content.Contents')->get($entity->id); $hash = $this->_calculateHash($prev); $exists = $this->ContentRevisions->exists([ 'ContentRevisions.content_id' => $entity->id, 'ContentRevisions.hash' => $hash, ]); if (!$exists) { $revision = $this->ContentRevisions->newEntity([ 'content_id' => $prev->id, 'summary' => $entity->get('edit_summary'), 'data' => $prev, 'hash' => $hash, ]); if (!$this->ContentRevisions->hasBehavior('Timestamp')) { $this->ContentRevisions->addBehavior('Timestamp'); } $this->ContentRevisions->save($revision); } } catch (\Exception $ex) { // unable to create content's review } }
Tries to create a revision for the given content. @param \Cake\ORM\Entity $entity The content @return void
entailment
protected function _ensureStatus(Entity $entity) { if (!$entity->has('status')) { return; } if (!$entity->has('content_type') && ($entity->has('content_type_id') || $entity->has('content_type_slug')) ) { if ($entity->has('content_type_id')) { $type = $this->ContentTypes->get($entity->get('content_type_id')); } else { $type = $this->ContentTypes ->find() ->where(['content_type_slug' => $entity->get('content_type_id')]) ->limit(1) ->first(); } } else { $type = $entity->get('content_type'); } if ($type && !$type->userAllowed('publish')) { if ($entity->isNew()) { $entity->set('status', false); } else { $entity->unsetProperty('status'); } } }
Ensures that content content has the correct publishing status based in content type restrictions. If it's a new content it will set the correct status. However if it's an existing content and user has no publishing permissions this method will not change content's status, so it will remain published if it was already published by an administrator. @param \Cake\ORM\Entity $entity The content @return void
entailment