/** * Get template data. * * @return array */ public function templateData() { $namespace = Configure::read('App.namespace'); if ($this->plugin) { $namespace = $this->_pluginNamespace($this->plugin); } $table = Inflector::tableize($this->args[0]); if (!empty($this->params['table'])) { $table = $this->params['table']; } $records = false; if ($this->param('data')) { $limit = (int) $this->param('limit'); $fields = $this->param('fields') ?: '*'; if ($fields !== '*') { $fields = explode(',', $fields); } $connection = ConnectionManager::get($this->connection); $query = $connection->newQuery()->from($table)->select($fields); if ($limit) { $query->limit($limit); } $records = $connection->execute($query)->fetchAll('assoc'); $records = $this->prettifyArray($records); } return ['className' => $this->BakeTemplate->viewVars['name'], 'namespace' => $namespace, 'records' => $records, 'table' => $table]; }
/** * Create bootstrap tabs. * * @param array $data * @param string $id * @return string * @SuppressWarnings(PHPMD.ShortVariable) */ public function tabs($id, array $data = []) { $i = 0; $output = []; foreach ($data as $key => $options) { $i++; $title = !is_array($options) ? $options : $key; $alias = Text::slug((string) Inflector::underscore($key), '-'); if (is_string($options)) { $options = []; } $_options = ['linkOptions' => ['data-toggle' => 'tab']]; if (isset($options['title'])) { $title = $options['title']; unset($options['title']); } $_options['linkOptions']['title'] = $title; if ($i == 1) { $_options = $this->addClass($_options, 'active'); } $options = Hash::merge($_options, $options); $linkOptions = $options['linkOptions']; unset($options['linkOptions']); $link = $this->Html->link($title, '#' . $alias, $linkOptions); $output[] = $this->Html->tag('li', $link, $options); } return $this->Html->tag('ul', implode('', $output), ['class' => 'nav nav-tabs', 'id' => $id]); }
/** * Create a controller for a given request/response * * @param \Cake\Network\Request $request The request to build a controller for. * @param \Cake\Network\Response $response The response to use. * @return \Cake\Controller\Controller */ public function create(Request $request, Response $response) { $pluginPath = $controller = null; $namespace = 'Controller'; if (isset($request->params['plugin'])) { $pluginPath = $request->params['plugin'] . '.'; } if (isset($request->params['controller'])) { $controller = $request->params['controller']; } if (isset($request->params['prefix'])) { if (strpos($request->params['prefix'], '/') === false) { $namespace .= '/' . Inflector::camelize($request->params['prefix']); } else { $prefixes = array_map('Cake\\Utility\\Inflector::camelize', explode('/', $request->params['prefix'])); $namespace .= '/' . implode('/', $prefixes); } } $firstChar = substr($controller, 0, 1); if (strpos($controller, '\\') !== false || strpos($controller, '.') !== false || $firstChar === strtolower($firstChar)) { return $this->missingController($request); } $className = false; if ($pluginPath . $controller) { $className = App::classname($pluginPath . $controller, $namespace, 'Controller'); } if (!$className) { return $this->missingController($request); } $reflection = new ReflectionClass($className); if ($reflection->isAbstract() || $reflection->isInterface()) { return $this->missingController($request); } return $reflection->newInstance($request, $response, $controller); }
/** * Builds asset file path based on the provided $url. * * @param string $url Asset URL * @return string|void Absolute path for asset file */ protected function _getAssetFile($url) { $parts = explode('/', $url); $pluginPart = []; $plugin = false; for ($i = 0; $i < 2; $i++) { if (!isset($parts[$i])) { break; } $pluginPart[] = Inflector::camelize($parts[$i]); $possiblePlugin = implode('/', $pluginPart); if ($possiblePlugin && Plugin::loaded($possiblePlugin)) { $plugin = $possiblePlugin; $parts = array_slice($parts, $i + 1); break; } } $isAssetRequest = isset($parts[0]) && $parts[0] === 'ASSETS'; if ($isAssetRequest && Configure::read('debug')) { $parts = array_slice($parts, 1); } else { $isAssetRequest = false; } if ($plugin && Plugin::loaded($plugin)) { return $this->_getPluginAsset($plugin, $parts, $isAssetRequest); } else { return $this->_getAppAsset($parts, $isAssetRequest); } }
/** * Inits PO file from POT file. * * @param string|null $language Language code to use. * @return int|null */ public function init($language = null) { if (!$language) { $language = $this->in('Please specify language code, e.g. `en`, `eng`, `en_US` etc.'); } if (strlen($language) < 2) { return $this->error('Invalid language code. Valid is `en`, `eng`, `en_US` etc.'); } $this->_paths = [APP]; if ($this->param('plugin')) { $plugin = Inflector::camelize($this->param('plugin')); $this->_paths = [Plugin::classPath($plugin)]; } $response = $this->in('What folder?', null, rtrim($this->_paths[0], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'Locale'); $sourceFolder = rtrim($response, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $targetFolder = $sourceFolder . $language . DIRECTORY_SEPARATOR; if (!is_dir($targetFolder)) { mkdir($targetFolder, 0775, true); } $count = 0; $iterator = new DirectoryIterator($sourceFolder); foreach ($iterator as $fileinfo) { if (!$fileinfo->isFile()) { continue; } $filename = $fileinfo->getFilename(); $newFilename = $fileinfo->getBasename('.pot'); $newFilename = $newFilename . '.po'; $this->createFile($targetFolder . $newFilename, file_get_contents($sourceFolder . $filename)); $count++; } $this->out('Generated ' . $count . ' PO files in ' . $targetFolder); }
/** * Generates a key string to use for the cache * * @param string|array|Entity $ref Array with 'model' and 'foreign_key', model object, or string value * @return string */ protected function _getNodeCacheKey($ref) { if (empty($ref)) { return ''; } elseif (is_string($ref)) { return Inflector::slug($ref, '_'); } elseif (is_object($ref) && $ref instanceof Entity) { return $ref->source() . '_' . $ref->id; } elseif (is_array($ref) && !(isset($ref['model']) && isset($ref['foreign_key']))) { $name = key($ref); list(, $alias) = pluginSplit($name); $bindTable = TableRegistry::get($name); $entityClass = $bindTable->entityClass(); if ($entityClass) { $entity = new $entityClass(); } if (empty($entity)) { throw new Exception\Exception(__d('cake_dev', "Entity class {0} not found in CachedDbAcl::_getNodeCacheKey() when trying to bind {1} object", [$type, $this->alias()])); } $tmpRef = null; if (method_exists($entity, 'bindNode')) { $tmpRef = $entity->bindNode($ref); } if (empty($tmpRef)) { $ref = ['model' => $alias, 'foreign_key' => $ref[$name][$bindTable->primaryKey()]]; } else { $ref = $tmpRef; } return $ref['model'] . '_' . $ref['foreign_key']; } elseif (is_array($ref)) { return $ref['model'] . '_' . $ref['foreign_key']; } return ''; }
/** * Returns a counter string for the paged result set * * ### Options * * - `model` The model to use, defaults to PaginatorHelper::defaultModel(); * - `format` The format string you want to use, defaults to 'pages' Which generates output like '1 of 5' * set to 'range' to generate output like '1 - 3 of 13'. Can also be set to a custom string, containing * the following placeholders `{{page}}`, `{{pages}}`, `{{current}}`, `{{count}}`, `{{model}}`, `{{start}}`, `{{end}}` and any * custom content you would like. * * @param string|array $options Options for the counter string. See #options for list of keys. * If string it will be used as format. * @return string Counter string. * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-a-page-counter */ public function counter($options = []) { if (is_string($options)) { $options = ['format' => $options]; } $default = ['model' => $this->defaultModel(), 'format' => 'pages']; $options = \Cake\Utility\Hash::merge($default, $options); $paging = $this->params($options['model']); if (!$paging['pageCount']) { $paging['pageCount'] = 1; } $start = 0; if ($paging['count'] >= 1) { $start = ($paging['page'] - 1) * $paging['perPage'] + 1; } $end = $start + $paging['perPage'] - 1; if ($paging['count'] < $end) { $end = $paging['count']; } switch ($options['format']) { case 'range': case 'pages': $template = 'counter' . ucfirst($options['format']); break; default: $template = 'counterCustom'; $this->templater()->add([$template => $options['format']]); } $map = array_map([$this->Number, 'format'], ['page' => $paging['page'], 'pages' => $paging['pageCount'], 'current' => $paging['current'], 'count' => $paging['count'], 'start' => $start, 'end' => $end]); $map += ['model' => strtolower(Inflector::humanize(Inflector::tableize($options['model'])))]; return $this->templater()->format($template, $map); }
public function edit($id = null) { $page = $this->Pages->get($id, ['contain' => []]); if ($this->request->is(['patch', 'post', 'put'])) { $page = $this->Pages->patchEntity($page, $this->request->data); //VARAIALBES $title = $this->request->data['title']; $templateName = $this->request->data['templatename']; // strToLower UTF8 $title = mb_strtolower($title, 'UTF-8'); $title = ucfirst($title); $templateName = mb_strtolower($templateName, 'UTF-8'); //SLUGIFY $slug = Inflector::slug(mb_strtolower($title, 'UTF-8'), '-'); $templateName = Inflector::slug(mb_strtolower($templateName, 'UTF-8'), '_'); //SAUVEGARDE DES MODIFICATIONS $page->title = $title; $page->slug = $slug; $page->templatename = $templateName; if ($this->Pages->save($page)) { $this->Flash->success(__('The page has been saved.')); return $this->redirect(['action' => 'index']); } else { $this->Flash->error(__('The page could not be saved. Please, try again.')); } } $this->set(compact('page')); $this->set('_serialize', ['page']); }
/** * Before render callback. * * @param \Cake\Event\Event $event The beforeRender event. * @return void */ public function beforeRender(Event $event) { parent::beforeRender($event); $params = $this->request->params; $page_id = Inflector::dasherize(implode('-', array_merge([$params['controller']], $params['pass']))); $this->set(compact('page_id')); }
/** * Class Constructor * * Merges defaults with * - Configure::read(Meta) * - Helper options * - viewVars _meta * in that order (the latter trumps) * * @param array $options */ public function __construct(View $View, $options = []) { parent::__construct($View, $options); $configureMeta = (array) Configure::read('Meta'); if (Configure::read('Meta.robots') && is_array(Configure::read('Meta.robots'))) { $configureMeta['robots'] = Hash::merge($this->meta['robots'], Configure::read('Meta.robots')); } $this->meta = $configureMeta + $this->meta; if (!empty($options['robots']) && is_array($options['robots'])) { $options['robots'] = Hash::merge($this->meta['robots'], $options['robots']); } $this->meta = $options + $this->meta; if (!empty($this->_View->viewVars['_meta'])) { $viewVarsMeta = (array) $this->_View->viewVars['_meta']; if (!empty($viewVarsMeta['robots']) && is_array($viewVarsMeta['robots'])) { $viewVarsMeta['robots'] = Hash::merge($this->meta['robots'], $viewVarsMeta['robots']); } $this->meta = $viewVarsMeta + $this->meta; } if ($this->meta['charset'] === null) { // By default include this $this->meta['charset'] = true; } if ($this->meta['icon'] === null) { // By default include this $this->meta['icon'] = true; } if ($this->meta['title'] === null) { $this->meta['title'] = __(Inflector::humanize(Inflector::underscore($this->request->params['controller']))) . ' - ' . __(Inflector::humanize(Inflector::underscore($this->request->params['action']))); } }
public function article_edit($id = null) { //LOAD CATEGORIES $this->loadModel('Categories'); $categories = $this->Categories->find('list'); $this->set(compact('categories')); $article = $this->Article->get($id); $this->set('title_for_layout', $article->title); $featured_image = $article->featured; if (empty($article)) { throw new NotFoundException('Could not find that article.'); } else { $this->set(compact('article')); } if ($this->request->is(['post', 'put'])) { $this->Article->patchEntity($article, $this->request->data); $article->slug = strtolower(Inflector::slug($article->title)); if (!empty($this->request->data['featured']['name'])) { $file = $this->request->data['featured']; move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img/articles/featured/' . $file['name']); $article->featured = $file['name']; } else { $article->featured = $featured_image; } if ($this->Article->save($article)) { $this->Flash->success(__('The article has been updated.')); return $this->redirect("" . Configure::read('BASE_URL') . "/admin/articles"); } $this->Flash->error(__('Unable to edit article.')); } }
/** * Renders new file input field with value. Applicable for edit action. * * @param Table $table Table * @param string $field Field * @param array $options Options * @param mixed $data Data * @return string HTML input field with data attribute. */ protected function _renderInputWithData($table, $field, $data, $options) { $files = []; $hiddenIds = ''; $fieldName = $this->_getFieldName($table, $field); $fileUploadsUtils = new FileUploadsUtils($table); $entities = $fileUploadsUtils->getFiles($table, $field, $data); if ($entities instanceof \Cake\ORM\ResultSet) { if (!$entities->count()) { return $this->_renderInputWithoutData($table, $field, $options); } } // @TODO: check if we return null anywhere, apart of ResultSet. // IF NOT: remove this block if (is_null($entities)) { return $this->_renderInputWithoutData($table, $field, $options); } foreach ($entities as $file) { $files[] = ['id' => $file->id, 'path' => $file->path]; $hiddenIds .= $this->cakeView->Form->hidden($this->_getFieldName($table, $field, $options) . '_ids][', ['class' => str_replace('.', '_', $fieldName . '_ids'), 'value' => $file->id]); } $label = $this->cakeView->Form->label($field); $uploadField = $this->cakeView->Form->file($fieldName . '[]', ['multiple' => true, 'data-document-id' => $data, 'data-upload-url' => sprintf("/api/%s/upload", Inflector::dasherize($table->table())), 'data-files' => json_encode($files)]); return sprintf(self::WRAPPER, $label, $uploadField, $hiddenIds); }
/** * Checks whether the response was cached and set the body accordingly. * * @param \Cake\Event\Event $event containing the request and response object * @return \Cake\Network\Response with cached content if found, null otherwise */ public function beforeDispatch(Event $event) { if (Configure::read('Cache.check') !== true) { return; } $path = $event->data['request']->here(); if ($path === '/') { $path = 'home'; } $prefix = Configure::read('Cache.viewPrefix'); if ($prefix) { $path = $prefix . '_' . $path; } $path = strtolower(Inflector::slug($path)); $filename = CACHE . 'views/' . $path . '.php'; if (!file_exists($filename)) { $filename = CACHE . 'views/' . $path . '_index.php'; } if (file_exists($filename)) { $controller = null; $view = new View($controller); $view->response = $event->data['response']; $result = $view->renderCache($filename, microtime(true)); if ($result !== false) { $event->stopPropagation(); $event->data['response']->body($result); return $event->data['response']; } } }
/** * Overrides the original method from phinx in order to return a tailored * Config object containing the connection details for the database. * * @param bool $forceRefresh * @return \Phinx\Config\Config */ public function getConfig($forceRefresh = false) { if ($this->configuration && $forceRefresh === false) { return $this->configuration; } $folder = 'Migrations'; if ($this->input->getOption('source')) { $folder = $this->input->getOption('source'); } $dir = ROOT . DS . 'config' . DS . $folder; $plugin = null; if ($this->input->getOption('plugin')) { $plugin = $this->input->getOption('plugin'); $dir = Plugin::path($plugin) . 'config' . DS . $folder; } if (!is_dir($dir)) { mkdir($dir, 0777, true); } $plugin = $plugin ? Inflector::underscore($plugin) . '_' : ''; $plugin = str_replace(['\\', '/', '.'], '_', $plugin); $connection = $this->getConnectionName($this->input); $connectionConfig = ConnectionManager::config($connection); $adapterName = $this->getAdapterName($connectionConfig['driver']); $config = ['paths' => ['migrations' => $dir], 'environments' => ['default_migration_table' => $plugin . 'phinxlog', 'default_database' => 'default', 'default' => ['adapter' => $adapterName, 'host' => isset($connectionConfig['host']) ? $connectionConfig['host'] : null, 'user' => isset($connectionConfig['username']) ? $connectionConfig['username'] : null, 'pass' => isset($connectionConfig['password']) ? $connectionConfig['password'] : null, 'port' => isset($connectionConfig['port']) ? $connectionConfig['port'] : null, 'name' => $connectionConfig['database'], 'charset' => isset($connectionConfig['encoding']) ? $connectionConfig['encoding'] : null, 'unix_socket' => isset($connectionConfig['unix_socket']) ? $connectionConfig['unix_socket'] : null]]]; if ($adapterName === 'mysql') { if (!empty($connectionConfig['ssl_key']) && !empty($connectionConfig['ssl_cert'])) { $config['environments']['default']['mysql_attr_ssl_key'] = $connectionConfig['ssl_key']; $config['environments']['default']['mysql_attr_ssl_cert'] = $connectionConfig['ssl_cert']; } if (!empty($connectionConfig['ssl_ca'])) { $config['environments']['default']['mysql_attr_ssl_ca'] = $connectionConfig['ssl_ca']; } } return $this->configuration = new Config($config); }
/** * Get the action path for a given request. Primarily used by authorize objects * that need to get information about the plugin, controller, and action being invoked. * * @param \Cake\Network\Request $request The request a path is needed for. * @param string $path Path * @return string The action path for the given request. */ public function action(Request $request, $path = '/:plugin/:controller/:action') { $plugin = empty($request['plugin']) ? null : Inflector::camelize($request['plugin']) . '/'; $path = str_replace(array(':controller', ':action', ':plugin/'), array(Inflector::camelize($request['controller']), $request['action'], $plugin), $this->_config['actionPath'] . $path); $path = str_replace('//', '/', $path); return trim($path, '/'); }
/** * Returns filtered associations for controllers models. HasMany association are filtered if * already existing in BelongsToMany * * @param Table $model The model to build associations for. * @return array associations */ public function filterAssociations(Table $model) { $belongsToManyJunctionsAliases = $this->belongsToManyJunctionAliases($model); $keys = ['BelongsTo', 'HasOne', 'HasMany', 'BelongsToMany']; $associations = []; foreach ($keys as $type) { foreach ($model->associations()->type($type) as $assoc) { $target = $assoc->target(); $assocName = $assoc->name(); $alias = $target->alias(); //filter existing HasMany if ($type === 'HasMany' && in_array($alias, $belongsToManyJunctionsAliases)) { continue; } $targetClass = get_class($target); list(, $className) = namespaceSplit($targetClass); $navLink = true; $modelClass = get_class($model); if ($modelClass !== 'Cake\\ORM\\Table' && $targetClass === $modelClass) { $navLink = false; } $className = preg_replace('/(.*)Table$/', '\\1', $className); if ($className === '') { $className = $alias; } try { $associations[$type][$assocName] = ['property' => $assoc->property(), 'variable' => Inflector::variable($assocName), 'primaryKey' => (array) $target->primaryKey(), 'displayField' => $target->displayField(), 'foreignKey' => $assoc->foreignKey(), 'alias' => $alias, 'controller' => $className, 'fields' => $target->schema()->columns(), 'navLink' => $navLink]; } catch (Exception $e) { // Do nothing it could be a bogus association name. } } } return $associations; }
/** * main * */ public function main() { $schemaPo = APP . 'Locale' . DS . 'schema.pot'; $conn = ConnectionManager::get('default'); $collection = $conn->schemaCollection(); $translations = new Translations(); $tables = $collection->listTables(); foreach ($tables as $table) { $translations->insert($table, Inflector::humanize(Inflector::underscore($table))); $translations->insert($table, Inflector::humanize(Inflector::underscore(Inflector::singularize($table)))); $columns = $collection->describe($table)->columns(); foreach ($columns as $column) { $c = $collection->describe($table)->column($column); $comment = $c['comment']; $t = new Translation($table . '.' . $column, Inflector::humanize(Inflector::underscore($column))); $translations[] = $t; $t->setTranslation($comment); $t = new Translation($table . '.' . $column, Inflector::humanize(Inflector::underscore(Inflector::singularize($table))) . ' ' . Inflector::humanize(Inflector::underscore($column))); $translations[] = $t; $t->setTranslation($comment); } } $poString = $translations->toPoString(); $caked = preg_replace('/msgctxt "([^"]+)"/i', '#: \\1', $poString); $this->createFile($schemaPo, $caked); }
/** * Get/Create an instance from the registry. * * When getting an instance, if it does not already exist, * a new instance will be created using the provide alias, and options. * * @param string $alias The name of the alias to get. * @param array $options Configuration options for the type constructor. * @return \Cake\ElasticSearch\Type */ public static function get($alias, array $options = []) { if (isset(static::$instances[$alias])) { if (!empty($options) && static::$options[$alias] !== $options) { throw new RuntimeException(sprintf('You cannot configure "%s", it already exists in the registry.', $alias)); } return static::$instances[$alias]; } static::$options[$alias] = $options; list(, $classAlias) = pluginSplit($alias); $options = $options + ['name' => Inflector::underscore($classAlias)]; if (empty($options['className'])) { $options['className'] = Inflector::camelize($alias); } $className = App::className($options['className'], 'Model/Type', 'Type'); if ($className) { $options['className'] = $className; } else { if (!isset($options['name']) && strpos($options['className'], '\\') === false) { list(, $name) = pluginSplit($options['className']); $options['name'] = Inflector::underscore($name); } $options['className'] = 'Cake\\ElasticSearch\\Type'; } if (empty($options['connection'])) { $connectionName = $options['className']::defaultConnectionName(); $options['connection'] = ConnectionManager::get($connectionName); } static::$instances[$alias] = new $options['className']($options); return static::$instances[$alias]; }
/** * Sets up the configuration for the model, and loads ACL models if they haven't been already * * @param Table $model Table instance being attached * @param array $config Configuration * @return void */ public function __construct(Table $model, array $config = []) { $this->_table = $model; if (isset($config[0])) { $config['type'] = $config[0]; unset($config[0]); } if (isset($config['type'])) { $config['type'] = strtolower($config['type']); } parent::__construct($model, $config); $types = $this->_typeMaps[$this->config()['type']]; if (!is_array($types)) { $types = [$types]; } foreach ($types as $type) { $alias = Inflector::pluralize($type); $className = App::className($alias . 'Table', 'Model/Table'); if ($className == false) { $className = App::className('Acl.' . $alias . 'Table', 'Model/Table'); } $config = []; if (!TableRegistry::exists($alias)) { $config = ['className' => $className]; } $model->hasMany($type, ['targetTable' => TableRegistry::get($alias, $config)]); } if (!method_exists($model->entityClass(), 'parentNode')) { trigger_error(__d('cake_dev', 'Callback {0} not defined in {1}', ['parentNode()', $model->entityClass()]), E_USER_WARNING); } }
/** * Get controller to use, either plugin controller or application controller * * @param \Cake\Network\Request $request Request object * @param \Cake\Network\Response $response Response for the controller. * @return mixed name of controller if not loaded, or object if loaded */ protected function _getController($request, $response) { $pluginPath = $controller = null; $namespace = 'Controller'; if (!empty($request->params['plugin'])) { $pluginPath = $request->params['plugin'] . '.'; } if ($pluginPath) { return parent::_getController($request, $response); } if (!empty($request->params['controller'])) { $controller = $request->params['controller']; } if (!empty($request->params['prefix'])) { $namespace .= '/' . Inflector::camelize($request->params['prefix']); } $className = false; if ($pluginPath . $controller) { $className = App::classname($pluginPath . $controller, $namespace, 'Controller'); } if (!$className) { return false; } $instance = PipingBag::get($className); if (method_exists($instance, 'viewBuilder')) { $instance->viewBuilder(); } else { $instance->viewPath = null; } $instance->name = $controller; $instance->setRequest($request); $instance->response = $response; return $instance; }
/** * Get list of plugins to process. Plugins without a webroot directory are skipped. * * @param string|null $name Name of plugin for which to symlink assets. * If null all plugins will be processed. * @return array List of plugins with meta data. */ protected function _list($name = null) { if ($name === null) { $pluginsList = Plugin::loaded(); } else { if (!Plugin::loaded($name)) { $this->err(sprintf('Plugin %s is not loaded.', $name)); return []; } $pluginsList = [$name]; } $plugins = []; foreach ($pluginsList as $plugin) { $path = Plugin::path($plugin) . 'webroot'; if (!is_dir($path)) { $this->out('', 1, Shell::VERBOSE); $this->out(sprintf('Skipping plugin %s. It does not have webroot folder.', $plugin), 2, Shell::VERBOSE); continue; } $link = Inflector::underscore($plugin); $dir = WWW_ROOT; $namespaced = false; if (strpos($link, '/') !== false) { $namespaced = true; $parts = explode('/', $link); $link = array_pop($parts); $dir = WWW_ROOT . implode(DIRECTORY_SEPARATOR, $parts) . DIRECTORY_SEPARATOR; } $plugins[$plugin] = ['srcPath' => Plugin::path($plugin) . 'webroot', 'destDir' => $dir, 'link' => $link, 'namespaced' => $namespaced]; } return $plugins; }
private function parse($json) { if (is_array($json)) { foreach ($json as $item) { $this->parse($item); } } else { $json = (array) $json; } foreach ($json as $tablename => $data) { if (!is_array($data)) { $this->parse($data); } else { $table = Inflector::tableize($tablename); $table = $table == 'armours' ? 'armour' : $table; // Hack for non-standard table names $table = TableRegistry::get($table); foreach ($data as $record) { $record = (array) $record; $new = $table->import($record); $result = ['table' => Inflector::humanize($tablename), 'record' => $new->import_name, 'status' => $new->import_action, 'errors' => $new->import_errors]; $this->results[] = $result; } } } }
public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary) { if (!array_key_exists('getRelated', $options) || !$options['getRelated']) { //Jen pokud se mají related stahovat return true; } $attachedTables = $this->_InRelatedIndexBehavior->getTablesWithBehaviorNames(); /** @var \Cake\ORM\Table $attachedTable */ foreach ($attachedTables as $tableName) { $modelName = Inflector::camelize($tableName); $query->contain(['Related' . $modelName => []]); } $query->formatResults(function ($results) { return $results->map(function ($row) { $temp = $row->toArray(); $related = []; foreach ($temp as $key => $item) { if (preg_match('/related-.*/', $key)) { foreach ($row->{$key} as $id => $similar) { $table_name = explode('-', $key); $row->{$key}[$id]->table_name = end($table_name); } $related = array_merge($related, $row->{$key}); unset($row->{$key}); } } $row->related = $related; return $row; }); }); return true; }
public function renderLayout($content, $layout = null) { try { $layout = $this->_getLayoutFileName($layout); } catch (MissingLayoutException $e) { $this->_renderLayoutAs = 'string'; } if (empty($layout)) { return $this->Blocks->get('content'); } if (empty($content)) { $content = $this->Blocks->get('content'); } else { $this->Blocks->set('content', $content); } $this->dispatchEvent('View.beforeLayout', [$layout]); $title = $this->Blocks->get('title'); if ($title === '') { $title = Inflector::humanize($this->viewPath); $this->Blocks->set('title', $title); } $this->_currentType = static::TYPE_LAYOUT; $this->Blocks->set('content', $this->_render($layout)); $this->dispatchEvent('View.afterLayout', [$layout]); return $this->Blocks->get('content'); }
/** * Displays a view * * @param mixed What page to display * @return void * @throws Cake\Error\NotFoundException When the view file could not be found * or Cake\View\Error\MissingViewException in debug mode. */ public function display() { $path = func_get_args(); $count = count($path); if (!$count) { return $this->redirect('/'); } $page = $subpage = $titleForLayout = null; if (!empty($path[0])) { $page = $path[0]; } if (!empty($path[1])) { $subpage = $path[1]; } if (!empty($path[$count - 1])) { $titleForLayout = Inflector::humanize($path[$count - 1]); } $this->set(array('page' => $page, 'subpage' => $subpage, 'title_for_layout' => $titleForLayout)); try { $this->render(implode('/', $path)); } catch (MissingViewException $e) { if (Configure::read('debug')) { throw $e; } throw new Error\NotFoundException(); } }
/** * Applies methods set from hooks to an object in __construct() * * @param string $configKey */ public static function applyHookMethods($configKey, &$object = null) { if (empty($object)) { $object = self; } if ($object instanceof Table) { $objectName = $object->alias(); } else { $objectName = $object->name; } if (php_sapi_name() !== 'cli') { $prefix = ($prefix = Router::getRequest()->param('prefix')) ? Inflector::camelize($prefix) . '.' : ''; $plugin = ($plugin = Router::getRequest()->param('plugin')) ? $plugin . '.' : ''; $objectName = $prefix . $plugin . $objectName; $hookMethods = Configure::read($configKey . '.' . $objectName); if (is_array(Configure::read($configKey . '.*'))) { $hookMethods = Hash::merge(Configure::read($configKey . '.*'), $hookMethods); } if (is_array($hookMethods)) { foreach ($hookMethods as $method => $values) { if (is_callable([$object, $method])) { foreach ($values as $name => $config) { $object->{$method}($name, $config); } } } } } }
/** * Social login link * * @param string $name * @param array $options * @return string */ public function socialLogin($name, $options = []) { if (empty($options['label'])) { $options['label'] = 'Sign in with'; } return $this->Html->link($this->Html->tag('i', '', ['class' => __d('Users', 'fa fa-{0}', strtolower($name))]) . __d('Users', '{0} {1}', Hash::get($options, 'label'), Inflector::camelize($name)), "/auth/{$name}", ['escape' => false, 'class' => __d('Users', 'btn btn-social btn-{0} ' . Hash::get($options, 'class') ?: '', strtolower($name))]); }
/** * Overrides the original method from phinx in order to return a tailored * Config object containing the connection details for the database. * * @return Phinx\Config\Config */ public function getConfig() { if ($this->configuration) { return $this->configuration; } $folder = 'Migrations'; if ($this->input->getOption('source')) { $folder = $this->input->getOption('source'); } $dir = ROOT . DS . 'config' . DS . $folder; $plugin = null; if ($this->input->getOption('plugin')) { $plugin = $this->input->getOption('plugin'); $dir = Plugin::path($plugin) . 'config' . DS . $folder; } if (!is_dir($dir)) { mkdir($dir, 0777, true); } $plugin = $plugin ? Inflector::underscore($plugin) . '_' : ''; $plugin = str_replace(array('\\', '/', '.'), '_', $plugin); $connection = 'default'; if ($this->input->getOption('connection')) { $connection = $this->input->getOption('connection'); } $config = ConnectionManager::config($connection); return $this->configuration = new Config(['paths' => ['migrations' => $dir], 'environments' => ['default_migration_table' => $plugin . 'phinxlog', 'default_database' => 'default', 'default' => ['adapter' => $this->getAdapterName($config['driver']), 'host' => isset($config['host']) ? $config['host'] : null, 'user' => isset($config['username']) ? $config['username'] : null, 'pass' => isset($config['password']) ? $config['password'] : null, 'port' => isset($config['port']) ? $config['port'] : null, 'name' => $config['database'], 'charset' => $config['encoding']]]]); }
/** * Index method * * @param string $filter Parameter to filter on * @param string $id Id of the model to filter * * @return \Cake\Network\Response|void */ public function index($filter = null, $id = null) { $findOptions = ['fields' => ['id', 'name', 'description', 'created', 'modified', 'sfw', 'status', 'user_id'], 'conditions' => ['Albums.status' => 1], 'contain' => ['Users' => ['fields' => ['id', 'username', 'realname']], 'Languages' => ['fields' => ['id', 'name', 'iso639_1']], 'Projects' => ['fields' => ['id', 'name', 'ProjectsAlbums.album_id']], 'Files' => ['fields' => ['id', 'name', 'filename', 'sfw', 'AlbumsFiles.album_id'], 'conditions' => ['status' => STATUS_PUBLISHED]]], 'order' => ['created' => 'desc'], 'sortWhitelist' => ['created', 'name', 'modified']]; // Sfw condition if (!$this->request->session()->read('seeNSFW')) { $findOptions['conditions']['sfw'] = true; } // Other conditions: if (!is_null($filter)) { switch ($filter) { case 'language': $findOptions['conditions']['Languages.id'] = $id; break; case 'license': $findOptions['conditions']['Licenses.id'] = $id; break; case 'user': $findOptions['conditions']['Users.id'] = $id; break; default: throw new \Cake\Network\Exception\NotFoundException(); } // Get additionnal infos infos $modelName = \Cake\Utility\Inflector::camelize(\Cake\Utility\Inflector::pluralize($filter)); $FilterModel = \Cake\ORM\TableRegistry::get($modelName); $filterData = $FilterModel->get($id); $this->set('filterData', $filterData); } $this->set('filter', $filter); $this->paginate = $findOptions; $this->set('albums', $this->paginate($this->Albums)); $this->set('_serialize', ['files']); }
/** * Return the webroot path to the image generated variant if this exist or to the controller if not. * * @param string $imagePath Path to the original image file from webroot if absolute, or relative to img/ * @param string|array $variantName Name of the variant configuration key or options array * @param array $options options * @return string */ public function variant($imagePath, $variantName, array $options = []) { if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) { list($plugin, $imagePath) = $this->_View->pluginSplit($imagePath, false); } $url = false; $imagePath = $imagePath[0] === '/' ? substr($imagePath, 1) : $imagePath; if (!isset($plugin)) { $originalFile = WWW_ROOT . $imagePath; $variantFile = dirname($originalFile) . DS . $variantName . DS . basename($originalFile); if (is_file($variantFile)) { $url = str_replace(DS, '/', str_replace(WWW_ROOT, '/', $variantFile)); } } else { $originalFile = WWW_ROOT . Inflector::underscore($plugin) . DS . $imagePath; $variantFile = dirname($originalFile) . DS . $variantName . DS . basename($originalFile); if (is_file($variantFile)) { $url = str_replace(DS, '/', str_replace(WWW_ROOT, '/', $variantFile)); } else { $originalFile = Plugin::path($plugin) . 'webroot' . DS . $imagePath; $variantFile = dirname($originalFile) . DS . $variantName . DS . basename($originalFile); if (is_file($variantFile)) { $url = str_replace(Plugin::path($plugin) . 'webroot' . DS, '/' . Inflector::underscore($plugin) . '/', $variantFile); $url = str_replace(DS, '/', $url); } } } if ($url === false) { $url = ['controller' => 'Presenter', 'action' => 'variant', 'plugin' => 'ImagePresenter', 'prefix' => false, '?' => ['image' => isset($plugin) ? "{$plugin}.{$imagePath}" : $imagePath, 'variant' => $variantName]]; } return Router::url($url); }