/** * 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']; } } }
/** * 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 ''; }
/** * * * FUNCTIONS PRIVATE * */ private function _save($entity) { if ($this->request->is(['patch', 'post', 'put'])) { $entity = $this->Contentbuilders->patchEntity($entity, $this->request->data); // On ajoute les traductions $I18ns = TableRegistry::get('I18ns'); $langs = $I18ns->find('list', ['keyField' => 'id', 'valueField' => 'locale'])->toArray(); // On merge nos translations if (isset($entity->translations)) { $entity->_translations = array_merge($entity->_translations, $entity->translations); unset($entity->translations); } foreach ($entity->_translations as $lang => $data) { if (in_array($lang, $langs)) { if ($entity->type_id !== Type::TYPE_HOMEPAGE && empty($data['slug']) && !empty($data['title'])) { $data['slug'] = strtolower(Inflector::slug($data['title'])); // @ TODO : Il faudra penser a vérifier que le slug n'existe pas, sinon on rajoute -x } $entity->translation($lang)->set($data, ['guard' => false]); } } if ($this->Contentbuilders->save($entity)) { $this->set('response', [true, __("Object saved with success !"), Router::url(['controller' => 'Contentbuilders', 'action' => 'edit', $entity->id, '_ext' => 'html'])]); $this->set('_serialize', 'response'); } else { $this->set('response', [false, __("Error occured while saving object !"), $entity->errors()]); $this->set('_serialize', 'response'); } } $types = Contentbuilder::getPrettyType(); $parents = $this->Contentbuilders->find('treeList', ['keyPath' => 'id', 'valuePath' => 'label', 'spacer' => ' --- ']); $this->set(compact('entity', 'types', 'parents')); }
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']); }
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.')); } }
/** * Generate an ID suitable for use in an ID attribute. * * @param string $value The value to convert into an ID. * @return string The generated id. */ protected function _domId($value) { $domId = mb_strtolower(Inflector::slug($value, '-')); if (!empty($this->_idPrefix)) { $domId = $this->_idPrefix . '-' . $domId; } return $domId; }
protected function _setSlug($value) { debug($this); if (empty($value)) { return Inflector::slug($this->name); } return $value; }
/** * Generate slug. * * @param string $string Input string. * @param string $replacement Replacement string. * @return string Sluggified string. */ public function slug($string, $replacement = '-') { $string = Inflector::slug($string, $replacement); if ($this->config['lowercase']) { return strtolower($string); } return $string; }
/** * Initialize the Cache Engine * * Called automatically by the cache frontend * * @param array $config array of setting for the engine * @return bool True if the engine has been successfully initialized, false if not */ public function init(array $config = []) { if (!isset($config['prefix'])) { $config['prefix'] = Inflector::slug(APP_DIR) . '_'; } parent::init($config); return function_exists('apc_dec'); }
protected function _setSlug($slug) { if ($slug !== '') { $slug = Inflector::slug($slug); return $slug; } return $this->get('slug'); }
/** * Get classes for main wrapper. * * @return string */ public function getClasses() { $plugin = preg_replace('/[^A-Z0-9_\\.-]/i', '', $this->request->param('plugin')); $plugin = Inflector::underscore($plugin); $controller = mb_strtolower($this->request->param('controller')); $action = mb_strtolower($this->request->param('action')); return implode(' ', ['plg-' . Inflector::slug($plugin, '-'), 'cont-' . $controller, 'action-' . $action]); }
public function slug(Entity $entity) { $config = $this->config(); if (!($value = $entity->get($config['slug']))) { $value = $entity->get($config['field']); } $entity->set($config['slug'], Inflector::slug($value, $config['replacement'])); }
public function beforeSave(Event $event, Entity $entity) { $config = $this->config(); $value = $entity->get($config['field']); $id = isset($entity->id) ? $entity->id : 0; $slug = $this->createSLug(strtolower(Inflector::slug($value, $config['replacement'])), 0, $id); $entity->set($config['slug'], $slug); }
/** * Creates a set of files from the initial data and returns them as key/value * pairs, where the path on disk maps to name which each file should have. * The file name will be sluggified (using Inflector::slug()) and lowercased. * * Example: * * ``` * [ * '/tmp/path/to/file/on/disk' => 'file.pdf', * '/tmp/path/to/file/on/disk-2' => 'file-preview.png', * ] * ``` * * @return array key/value pairs of temp files mapping to their names */ public function transform() { $filename = pathinfo($this->data['name'], PATHINFO_FILENAME); $filename = Inflector::slug($filename, '-'); $ext = pathinfo($this->data['name'], PATHINFO_EXTENSION); if (!empty($ext)) { $filename = $filename . '.' . $ext; } return [$this->data['tmp_name'] => strtolower($filename)]; }
public function tab() { $tab = array_shift($this->_tabs); $class = 'tab ' . strtolower(Inflector::slug($tab)); if (!$this->_isActivated) { $this->_isActivated = true; $class .= ' active'; } return $class; }
/** * Helper method for slugerizing keys in a URL array. * * @param array $url An array of URL keys. * * @return array */ protected function _slugerize($url) { if (isset($url['slug']) && !empty($url['slug'])) { $url['slug'] = strtolower(Inflector::slug($url['slug'])); } if (!empty($url['controller'])) { $url['controller'] = Inflector::underscore($url['controller']); } if (!empty($url['plugin'])) { $url['plugin'] = Inflector::underscore($url['plugin']); } return $url; }
/** * Turns a string (and optionally a dynamic, data-injected string) into a slugged value * @param $pattern string a simple string (e.g. 'slug me') or Text::insert-friendly string (e.g. ':id-:name') * @param $data mixed an Array or Entity of data to Text::insert inject into $pattern * @param $replacement string the character to replace non-slug-friendly characters with (default '-') * @return string the slugged string */ public static function generate($pattern, $data = [], $replacement = '-') { # if given an Entity object, covert it to a hydrated array $data = $data instanceof \Cake\ORM\Entity ? json_decode(json_encode($data->jsonSerialize()), true) : $data; # build the slug $value = Text::insert($pattern, $data); # inject data into pattern (if applicable) $value = Inflector::slug($value, $replacement); # slug it $value = strtolower($value); # convert to lowercase return $value; }
/** * Custom rule to verify that the slug of the field is unique in the db * * @param string $element * @param obj $context object passed on validator calls * @return boolean true if rule is valid */ public function uniqueSlug($element = null, $context = null) { if (isset($context['newRecord']) && $context['newRecord']) { if ($this->findBySlug(Inflector::slug($element, '-'))->first()) { return false; } } else { if (!empty($this->findBySlug(Inflector::slug($element, '-'))->first())) { if ($this->findBySlug(Inflector::slug($element, '-'))->first()->extract(['id'])['id'] !== $context['data']['id']) { return false; } } } return true; }
/** * @param string $address * @param array $params * @return \Geocoder\Model\AddressCollection */ public function geocode($address, array $params = []) { $file = Inflector::slug($address) . '.txt'; $testFiles = ROOT . DS . 'tests' . DS . 'test_files' . DS . 'Geocoder' . DS; $testFile = $testFiles . $file; if (!file_exists($testFile)) { if (getenv('CI')) { throw new Exception('Should not happen on CI.'); } $addresses = parent::geocode($address, $params); file_put_contents($testFile, serialize($addresses)); } $addresses = file_get_contents($testFile); $addresses = unserialize($addresses); return $addresses; }
/** * Add method * * @return void Redirects on successful add, renders view otherwise. */ public function add() { $category = $this->Categories->newEntity(); if ($this->request->is('post')) { $category = $this->Categories->patchEntity($category, $this->request->data); $category->slug = \Cake\Utility\Inflector::slug($category->name); if ($this->Categories->save($category)) { $this->Flash->success(__('The category has been saved.')); return $this->redirect(['action' => 'index']); } else { $this->Flash->error(__('The category could not be saved. Please, try again.')); } } $this->set(compact('category')); $this->set('_serialize', ['category']); }
/** * @param string $url * @param mixed $data * @param string $requestType * @return mixed * @author Gustav Wellner Bou <*****@*****.**> */ protected function _post($url, $data, $requestType = 'POST') { $slug = Text::insert($url, $this->settings, ['before' => '{', 'after' => '}']); $slug = str_replace(static::BASE_URL, '', $slug); $slug = strtolower($requestType) . '_' . Inflector::slug($slug) . '_' . md5($data); $file = Plugin::path('Transifex') . 'tests/test_files/json/' . $slug . '.json'; if (!$this->settings['debug'] && file_exists($file)) { $content = file_get_contents($file); return json_decode($content, true); } $result = parent::_post($url, $data, $requestType); if ($this->settings['debug']) { $file = Plugin::path('Transifex') . 'tests/test_files/json/' . $slug . '.json'; file_put_contents($file, json_encode($result, JSON_OPTIONS)); } return $result; }
/** * Upload a file to the server * @param upload - file to upload * @param owner - contains model name and id associated with the file * @return array - uploaded file information or null for failure */ public function upload($upload, $owner = null) { // Filesize verification if ($upload['size'] == 0) { return null; } if ($upload['size'] > $this->maxFileSize) { return null; } $path = $this->storagePath; // Owner separated storage if ($this->storeOwner == true && $owner) { // Directory should be lower case $ownerTable = strtolower($owner->source()); // Owner specific directory must be unique (uuid) $ownerDirectory = Inflector::singularize($ownerTable) . $owner->id; $path .= DS . $ownerTable . DS . $ownerDirectory; } // If types do not match, default subdir is 'document' $subdir = 'document'; $types = ['image', 'audio', 'video']; // Check for filetype foreach ($types as $type) { if (strstr($upload['type'], $type)) { $subdir = $type; } } // Append the subdirectory (filtype directory) $path .= DS . $subdir; // Make directory if there is none $directory = new Folder(); if (!$directory->create(WWW_ROOT . DS . $path)) { return null; } // Find file in tmp $file = new File($upload['tmp_name']); // File's name must be unique, making the path unique as well $name = time() . '_' . Inflector::slug($upload['name']); $path .= DS . $name; // Copy from tmp to perm (create) if ($file->copy($path)) { return ['original_name' => $upload['name'], 'name' => $name, 'path' => $path, 'type' => $upload['type'], 'size' => $upload['size']]; } else { return null; } }
public function slug(Entity $entity) { $config = $this->config(); $value = $entity->get($config['field']); $baseSlug = Inflector::slug(strtolower($value), $config['replacement']); //Append "-1", "-2", etc. if slug already exists $counter = 0; do { $slug = $baseSlug; if ($counter > 0) { $slug .= $config['replacement'] . $counter; } $counter++; $existing = $this->_table->find('slug', ['slug' => $slug])->first(); } while (!empty($existing)); $entity->set($config['slug'], $slug); }
/** * beforeSave callback * * - create a slug based on the name of the page * * @param Event $event * @param Page $entity * @param ArrayObject $options */ public function beforeSave(Event $event, Page $entity, ArrayObject $options) { $entity->slug = strtolower(Inflector::slug($entity->name)); if (!$entity->isNew() && !$this->contentHasChanged($entity)) { // If we edit a page and the page content has not changed, // then we unset the "current" property to not create the // same content entry in the contents table. $entity->unsetProperty('current'); } // If the site wide meta robots attribute is identical with the pages meta robot attribute // then set it to null to inherit the site wide one. if ($entity->meta_robots_index === (bool) Configure::read('Settings.Cms.SEO.meta-robots-index')) { $entity->meta_robots_index = null; } if ($entity->meta_robots_follow === (bool) Configure::read('Settings.Cms.SEO.meta-robots-follow')) { $entity->meta_robots_follow = null; } }
/** * @param string $url * @param bool $mustExist * @return string */ public function getFile($url, $mustExist = true) { if ($url === '/') { $url = 'home'; } $path = $url; $prefix = Configure::read('Cache.prefix'); if ($prefix) { $path = $prefix . '_' . $path; } $path = Inflector::slug($path); $folder = CACHE . 'views' . DS; $file = $folder . $path . '.html'; if ($mustExist && !file_exists($file)) { return null; } return $file; }
public function uploadIt($field, $object) { $dados = $this->request->data[$field]; $filename = time() . '-' . strtolower(Inflector::slug($dados['name'])); $ext = pathinfo($dados['name'], PATHINFO_EXTENSION); $filename = $filename . "." . $ext; $uploadPath = WWW_ROOT . 'uploads' . DS . $filename; if (!empty($dados)) { if ($dados['error'] == 0) { if (move_uploaded_file($dados['tmp_name'], $uploadPath)) { return $filename; } } else { return $object->{$field}; } } return false; }
/** * Add method * * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise. */ public function add() { $post = $this->Posts->newEntity(); if ($this->request->is('post')) { $post = $this->Posts->patchEntity($post, $this->request->data); $post->slug = Inflector::slug($post->name); if ($this->Posts->save($post)) { $this->Flash->success(__('The post has been saved.')); return $this->redirect(['action' => 'index']); } else { $this->Flash->error(__('The post could not be saved. Please, try again.')); } } $categories = $this->Posts->Categories->find('list', ['limit' => 200]); $users = $this->Posts->Users->find('list', ['limit' => 200]); $this->set(compact('post', 'categories', 'users')); $this->set('_serialize', ['post']); }
/** * Uses the Geocode class to query * * @param string $address * @return \Geocoder\Model\Address|null * @throws \Exception */ protected function _execute($address) { $this->_Geocoder = new Geocoder($this->_config); $file = Inflector::slug($address) . '.txt'; $testFiles = ROOT . DS . 'tests' . DS . 'test_files' . DS . 'Behavior' . DS; $testFile = $testFiles . $file; if (!file_exists($testFile)) { if (getenv('CI')) { throw new Exception('Should not happen on CI: ' . $testFile); } $address = parent::_execute($address); file_put_contents($testFile, serialize($address)); return $address; } $address = file_get_contents($testFile); $address = unserialize($address); return $address; }
public function page_edit($id = null) { $page = $this->Page->get($id); $this->set('title_for_layout', $page->title); if (empty($page)) { throw new NotFoundException('Could not find that page.'); } else { $this->set(compact('page')); } if ($this->request->is(['post', 'put'])) { $this->Page->patchEntity($page, $this->request->data); $page->slug = strtolower(Inflector::slug($page->title)); if ($this->Page->save($page)) { $this->Flash->success(__('The page has been updated.')); return $this->redirect("" . Configure::read('BASE_URL') . "/admin/pages"); } $this->Flash->error(__('Unable to edit page.')); } }
public function add() { if ($this->request->session()->read("Auth.User.role") != 'Admin') { $this->Flash->error("Action non autorisée"); return $this->redirect(["controller" => "articles"]); } $article = $this->Articles->newEntity(); if ($this->request->is('post')) { $this->request->data["slug"] = strtolower(Inflector::slug($this->request->data["name"])); $article = $this->Articles->patchEntity($article, $this->request->data); if ($this->Articles->save($article)) { $this->Flash->success('Article ajouté'); return $this->redirect(['controller' => 'articles', 'action' => 'view', $article->id, $article->slug]); } else { $this->Flash->error("Une erreur est survenu"); } } $categories = $this->Articles->Categories->find("list"); $this->set("article", $article); $this->set("categories", $categories); }