Пример #1
0
 public function returnSection($section, $locale = 'en_us')
 {
     $en_us = $this->returnEnSection($section);
     //get the us version of the section first
     if ($locale == 'en_us') {
         return $en_us;
     }
     //query up the languages
     if (Set::check(self::$sections, $section . "." . $locale)) {
         return self::$sections[$section][$locale];
     } else {
         $old_locale = $this->locale;
         $this->setLanguage($locale);
         $lang = $this->find("all", array("conditions" => array("Phrase.section" => $section)));
         $this->setLanguage($old_locale);
         foreach ($en_us as $k => $v) {
             $p = Set::extract("/Phrase[token=/" . $k . "/i]/value", $lang);
             if (count($p) > 0) {
                 $en_us[$k] = $p[0];
             }
         }
         //cache the data
         self::$sections[$section][$locale] = $en_us;
     }
     return self::$sections[$section][$locale];
 }
Пример #2
0
 function index()
 {
     $this->Phrase->recursive = 0;
     $phrases = $this->paginate('Phrase');
     $this->set('phrases', $phrases);
     //get the list of locales
     $this->loadModel("Locale");
     //$locales = $this->Locale->find("list",array("fields"=>array("Locale.locale","Locale.name"),"order"=>array("name"=>"ASC")));
     $locales = Lang::localeList();
     $this->set("locales", $locales);
     //set the incoming locale to the session
     if (!empty($this->request->data)) {
         if (Set::check($this->request->data, "Phrase.selectLocale")) {
             $this->Session->write("ControlPanel.translate_locale", $this->request->data['Phrase']['selectLocale']);
         }
     }
     //get the locale from the session
     if ($this->Session->check("ControlPanel.translate_locale")) {
         $translate_locale = $this->Session->read("ControlPanel.translate_locale");
     } else {
         $translate_locale = 'en_us';
         $this->request->data['Phrase']['selectLocale'] = 'en_us';
     }
     $this->request->data['Phrase']['selectLocale'] = $translate_locale;
     $this->Phrase->setLanguage($translate_locale);
     //get the trnaslated phrases
     $ids = Set::extract("/Phrase/id", $phrases);
     //pr($this->Session->read());
     $locale_phrases = $this->Phrase->find('all', array("conditions" => array("Phrase.id" => $ids)));
     $this->set("locale_phrases", $locale_phrases);
 }
Пример #3
0
 function specialValues($fieldName, $options = array())
 {
     $this->setEntity($fieldName);
     $specialValues = array('true' => true, 'false' => false, 'null' => null, 'undefined' => null);
     $spcFieldOpt = array('label' => __('Special value', true), 'options' => array_combine(array_keys($specialValues), array_keys($specialValues)), 'empty' => __('none', true));
     $hasSpecial = null;
     $value = $this->value($fieldName);
     $view =& ClassRegistry::getObject('view');
     $entity = $view->entity();
     foreach ($this->specialValues as $spc => $val) {
         if ($value === $val) {
             $hasSpecial = $spc;
         }
     }
     if (!$hasSpecial && !empty($entity) && (empty($this->data) || !Set::check($this->data, join('.', $entity)))) {
         $hasSpecial = 'undefined';
     }
     if ($hasSpecial) {
         $options['value'] = '';
         $spcFieldOpt['value'] = $hasSpecial;
     }
     if (empty($options['after'])) {
         $options['after'] = '';
     }
     $options['after'] .= $this->Form->input($fieldName . '_spc', $spcFieldOpt);
     return $this->Form->input($fieldName, $options);
 }
Пример #4
0
 function afterFind($results, $primary = false)
 {
     if ($primary == true) {
         if (Set::check($results, '0.0')) {
             $fieldName = key($results[0][0]);
             foreach ($results as $key => $value) {
                 $results[$key][$this->alias][$fieldName] = $value[0][$fieldName];
                 unset($results[$key][0]);
             }
         }
     }
     return $results;
 }
 /**
  * Return tags from database.
  *
  * @return array
  */
 function tagcloud(&$controller)
 {
     $term_id = Configure::read('Tagcloud.term');
     $query = "SELECT count(*) as tag_count, Term.title, Term.id, Term.slug\n            FROM nodes_terms as nt\n            JOIN terms as Term ON Term.id = nt.term_id\n            WHERE Term.vocabulary_id = {$term_id}\n            GROUP BY nt.term_id";
     $tags = ClassRegistry::init('Term')->query($query);
     if (Set::check($tags, '0.0')) {
         $fieldName = key($tags[0][0]);
         foreach ($tags as $key => $value) {
             $tags[$key]['Term'][$fieldName] = $value[0][$fieldName];
             unset($tags[$key][0]);
         }
     }
     return $tags;
 }
Пример #6
0
 /**
  * view method
  *
  * @throws NotFoundException
  * @param string $id
  * @return void
  */
 public function view($id = null)
 {
     if (!$this->Group->exists($id)) {
         throw new NotFoundException(__('Usuário Inválido!'));
     }
     $options = array('conditions' => array('Group.' . $this->Group->primaryKey => $id));
     $this->set('group', $this->Group->find('first', $options));
     //Obtenção do aroId do grupo selecionado.
     $aro = $this->Acl->Aro->find('first', array('conditions' => array('Aro.model' => 'Group', 'Aro.foreign_key' => $id)));
     $aroId = $aro['Aro']['id'];
     //Obtendo os membros do grupo selecionado (Pode ser usuarios e grupos).
     $members = $this->Acl->Aro->query('SELECT * FROM aros AS Aro
                                                    INNER JOIN users AS User ON Aro.foreign_key = User.id
                                                    WHERE Aro.parent_id = ' . $aroId);
     $this->set('members', $members);
     //debug($members);
     //lista de usuários.
     $this->loadModel('User');
     $users = $this->User->find('list');
     $this->set(compact('users'));
     //Obtendo as permissões do grupo.
     $this->loadModel('Page');
     $pages = $this->Page->find('all', array('conditions' => array('Page.enable' => 1), 'order' => 'Page.name'));
     //debug($pages);
     $lista = array();
     $aros_aco_id = NULL;
     $aco_parent_id = NULL;
     foreach ($pages as $page) {
         //Check permissão
         $check_permission = $this->Acl->check(array('Group' => array('id' => $id)), array('Page' => array('id' => $page['Page']['id'])));
         //.....
         $direct_permission = $this->Acl->Aco->Permission->find('first', array('conditions' => array('Aco.model' => 'Page', 'Aco.foreign_key' => $page['Page']['id'], 'Aro.model' => 'Group', 'Aro.foreign_key' => $id)));
         //debug($direct_permission);
         if (Set::check($direct_permission, 'Permission')) {
             $aco_parent_id = $direct_permission['Aco']['parent_id'];
             $aros_aco_id = $direct_permission['Permission']['id'];
             $direct_permission = true;
         }
         $page_acos = $this->Acl->Aco->find('first', array('conditions' => array('Aco.model' => 'Page', 'Aco.foreign_key' => $page['Page']['id']), 'fields' => 'Aco.parent_id'));
         $aco_parent_id = $page_acos['Aco']['parent_id'];
         //debug($aco_parent_id);
         $lista[] = array('aco_parent_id' => $aco_parent_id, 'aros_aco_id' => $aros_aco_id, 'page_id' => $page['Page']['id'], 'pageName' => $page['Page']['name'], 'check_permission' => $check_permission, 'direct_permission' => $direct_permission);
         $aros_aco_id = NULL;
         $aco_parent_id = NULL;
     }
     $this->set('permissions', $lista);
     //debug($lista);
     //debug($this->Acl->Aco->find('all'));
 }
 /**
  * Connects to the database. Options are specified in the $config instance variable.
  *
  * @return boolean Connected.
  * @throws MissingConnectionException
  */
 public function connect()
 {
     if ($this->connected !== true) {
         if (Set::check($this->config, 'login')) {
             $this->config = Set::insert($this->config, 'request.uri.user', Set::get($this->config, 'login'));
         }
         if (Set::check($this->config, 'password')) {
             $this->config = Set::insert($this->config, 'request.uri.pass', Set::get($this->config, 'password'));
         }
         try {
             $this->Socket = new HttpSocket($this->config);
             $this->connected = true;
         } catch (SocketException $e) {
             throw new MissingConnectionException(array('class' => $e->getMessage()));
         }
     }
     return $this->connected;
 }
Пример #8
0
 /**
  * view method
  *
  * @throws NotFoundException
  * @param string $id
  * @return void
  */
 public function view($id = null)
 {
     if (!$this->User->exists($id)) {
         throw new NotFoundException(__('Usuário Inválido!'));
     }
     $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
     $this->set('user', $this->User->find('first', $options));
     //Obtendo os grupos que este usuário pertence.
     $belongs = $this->Acl->Aro->query("SELECT Aro.id, Aro.parent_id, parent.image_path, parent.name\n                                                       FROM aros AS Aro\n                                                       INNER JOIN ( SELECT aros.id, all_groups.image_path, all_groups.name \n                                                                    FROM aros \n                                                                    INNER JOIN ( SELECT groups.id, groups.image_path, groups.name FROM groups ) AS all_groups \n                                                                    ON aros.foreign_key = all_groups.id ) AS parent \n                                                       ON Aro.parent_id = parent.id                                                  \n                                                       WHERE Aro.model = 'User' AND Aro.foreign_key = " . $id);
     $this->set('belongs', $belongs);
     //debug($belongs);
     //lista de grupos.
     $this->loadModel('Group');
     $groups = $this->Group->find('list');
     $this->set(compact('groups'));
     //Obtendo as permissões do usuário.
     $this->loadModel('Page');
     $pages = $this->Page->find('all', array('conditions' => array('Page.enable' => 1), 'order' => 'Page.name'));
     //debug($pages);
     $lista = array();
     $aros_aco_id = NULL;
     $aco_parent_id = NULL;
     foreach ($pages as $page) {
         //Check permissão
         $check_permission = $this->Acl->check(array('User' => array('id' => $id)), array('Page' => array('id' => $page['Page']['id'])));
         //permissões diretas
         $direct_permission = $this->Acl->Aco->Permission->find('first', array('conditions' => array('Aco.model' => 'Page', 'Aco.foreign_key' => $page['Page']['id'], 'Aro.model' => 'User', 'Aro.foreign_key' => $id)));
         //debug($direct_permission);
         if (Set::check($direct_permission, 'Permission')) {
             $aco_parent_id = $direct_permission['Aco']['parent_id'];
             $aros_aco_id = $direct_permission['Permission']['id'];
             $direct_permission = true;
         }
         $page_acos = $this->Acl->Aco->find('first', array('conditions' => array('Aco.model' => 'Page', 'Aco.foreign_key' => $page['Page']['id']), 'fields' => 'Aco.parent_id'));
         $aco_parent_id = $page_acos['Aco']['parent_id'];
         //debug($aco_parent_id);
         $lista[] = array('aco_parent_id' => $aco_parent_id, 'aros_aco_id' => $aros_aco_id, 'page_id' => $page['Page']['id'], 'pageName' => $page['Page']['name'], 'check_permission' => $check_permission, 'direct_permission' => $direct_permission);
         $aros_aco_id = NULL;
         $aco_parent_id = NULL;
     }
     $this->set('permissions', $lista);
     //debug($lista);
     //debug($this->Acl->Aco->Permission->find('all'));
 }
Пример #9
0
 /**
  * Add a menu item
  *
  * @param string $path dot separated path in the array.
  * @param array $options menu options array
  * @return void
  */
 public static function add($path, $options)
 {
     $pathE = explode('.', $path);
     $pathE = array_splice($pathE, 0, count($pathE) - 2);
     $parent = join('.', $pathE);
     if (!empty($parent) && !Set::check(self::$_items, $parent)) {
         $title = Inflector::humanize(end($pathE));
         $o = array('title' => $title);
         self::_setupOptions($o);
         self::add($parent, $o);
     }
     self::_setupOptions($options);
     $current = Set::extract($path, self::$_items);
     if (!empty($current)) {
         self::_replace(self::$_items, $path, $options);
     } else {
         self::$_items = Set::insert(self::$_items, $path, $options);
     }
 }
Пример #10
0
 function getMinimalData(&$model, $fields, $data = null, $findOptions = array(), $priorityRes = true)
 {
     if (is_null($data)) {
         $data = $model->data;
     }
     //debug($data);
     //////// get fields and contain ////////
     $contain = array();
     $findFields = array();
     foreach ($fields as &$field) {
         if (substr($field, 0, strlen($model->alias) + 1) == $model->alias . '.') {
             $findFields[] = $field;
             $field = $model->alias . '.' . $field;
         } elseif (($pos = strrpos($field, '.')) == false) {
             $findFields[] = $model->alias . '.' . $field;
         } else {
             $path = substr($field, 0, $pos);
             $depth = count(explode('.', $path));
             $f = substr($field, $pos + 1);
             if ($depth > 1) {
                 $contain = Set::insert($contain, $path . '.fields', array('id', $f));
             } else {
                 $contain = Set::insert($contain, $path, array());
                 if (!in_array($path . '.id', $findFields)) {
                     $findFields[] = $path . '.id';
                 }
                 $findFields[] = $field;
             }
         }
     }
     if (!in_array($model->alias . '.id', $findFields)) {
         $findFields[] = $model->alias . '.id';
     }
     //////// normalize Data ////////
     list($data, $oldFormat) = $model->unifiedResult($data, null, null, true);
     App::import('Lib', 'SetMulti');
     $data = SetMulti::group($data, $model->alias . '.id', array('singleArray' => false));
     //debug($data);
     //////// get ids ////////
     $ids = array();
     foreach ($data as $entry) {
         foreach ($fields as $field) {
             if (!Set::check($entry, $field)) {
                 $ids[] = $entry[$model->alias]['id'];
                 continue 2;
             }
         }
     }
     //////// query ////////
     $findOpt = array('fields' => $findFields, 'conditions' => array($model->alias . '.id' => $ids), 'contain' => $contain);
     $findOpt = array_merge($findOpt, $findOptions);
     //debug($findOpt);
     $completion = $model->find('all', $findOpt);
     //debug($completion);
     //////// merge data ////////
     foreach ($completion as $c) {
         $id = $c[$model->alias]['id'];
         if ($priorityRes) {
             $data[$id] = Set::merge($data[$id], $c);
         } else {
             $data[$id] = Set::merge($c, $data[$id]);
         }
     }
     $data = array_values($data);
     $data = $this->unifiedResult($model, $data, null, $oldFormat);
     //debug($data);
     return $data;
 }
 function get_more_params($excepts = array())
 {
     $datas = $_GET;
     $excepts = am($this->excepts, array('page'));
     //On va parcourir les exemptions
     foreach ($excepts as $except) {
         if (Set::check($_GET, $except)) {
             $datas = Set::remove($datas, $except);
             $exceptPath = explode('.', $except);
             if (count(Set::classicExtract($datas, $exceptPath[0])) == 0) {
                 $datas = Set::remove($datas, $exceptPath[0]);
             }
         }
     }
     $moreParams = '';
     if (count($datas) > 0) {
         $moreParams = $this->_recursive_params($datas);
     }
     return $moreParams;
 }
Пример #12
0
 /**
  * Cette fonction est en charge de contrôler la valeur d'un champ est valide
  *
  * @param 	varchar	$valueToCheck 	Valeur du champ à contrôler
  * @param 	varchar	$validationRule Règle de validation
  * @param 	array 	$insertErrorIn 	Indique le chemin pour l'insertion de l'erreur
  * @param 	array 	$errors 		Erreurs
  * @return 	array 	Tableau d'erreurs
  * @access	protected
  * @author	koéZionCMS
  * @version 0.1 - 20/03/2015
  */
 protected function _is_valid_value($valueToCheck, $validationRule, $insertErrorIn, $errors)
 {
     include CONFIGS . DS . 'messages.php';
     //Inclusion des éventuels messages d'erreurs
     $isValid = $this->Validation->check($valueToCheck, $validationRule['rule']);
     //Lancement de la règle
     $allowEmpty = $validationRule['allowEmpty'] && empty($valueToCheck);
     //Génération du booléen allowEmpty
     //On injecte le message en cas d'erreur
     if (!$isValid && !$allowEmpty) {
         if (Set::check($Errorsmessages, $validationRule['message'])) {
             $errors[$insertErrorIn] = Set::classicExtract($Errorsmessages, $validationRule['message']);
         } else {
             $errors[$insertErrorIn] = $validationRule['message'];
         }
     }
     return $errors;
 }
Пример #13
0
 function testWritingWithFunkyKeys()
 {
     $set = new Set();
     $set->insert('Session Test', "test");
     $this->assertEqual($set->extract('Session Test'), 'test');
     $set->remove('Session Test');
     $this->assertFalse($set->check('Session Test'));
     $this->assertTrue($set->insert('Session Test.Test Case', "test"));
     $this->assertTrue($set->check('Session Test.Test Case'));
 }
 public function dma_codes()
 {
     $this->loadStuff();
     $month = false;
     $year = false;
     $domain_id = false;
     $sql_filter = '';
     if (Set::check($this->request->data, "Filters.report_month.month")) {
         $month = $this->request->data['Filters']['report_month']['month'];
     } else {
         $month = $this->request->data['Filters']['report_month']['month'] = date("m");
     }
     //get the year
     if (Set::check($this->request->data, "Filters.report_year.year")) {
         $year = $this->request->data['Filters']['report_year']['year'];
     } else {
         $year = $this->request->data['Filters']['report_year']['year'] = date("Y");
     }
     //get the domain id
     if (Set::check($this->request->data, "Filters.dim_domain_id")) {
         $domain_id = $this->request->data['Filters']['dim_domain_id'];
     }
     //make the pv report
     $report = $this->FactPageView->query("SELECT COUNT(*) AS `total`,DimDmaCode.dma_code,DimDmaCode.dma_location\n\t\t\tFROM fact_page_views AS `FactPageView` \n\t\t\tINNER JOIN dim_dates AS `DimDate` ON (DimDate.id = FactPageView.dim_date_id)\n\t\t\tINNER JOIN dim_domains AS `DimDomain` ON (DimDomain.id = FactPageView.dim_domain_id)\n\t\t\tINNER JOIN dim_dma_codes AS `DimDmaCode` ON (DimDmaCode.id = FactPageView.dim_dma_code_id)\n\t\t\tWHERE DimDate.report_month = '{$month}' AND DimDate.report_year = '{$year}' {$sql_filter}\n\t\t\tGROUP BY DimDmaCode.dma_code\n\t\t\tORDER BY total DESC");
     $uniques = $this->FactPageView->query("SELECT COUNT(*) AS `total`,dma_code\n\t\t\tFROM (\n\t\t\t\tSELECT DISTINCT(session),DimDmaCode.dma_code AS `dma_code`\n\t\t\t\tFROM fact_page_views AS `FactPageView`\n\t\t\t\tINNER JOIN dim_dates AS `DimDate` ON (DimDate.id = FactPageView.dim_date_id)\n\t\t\t\tINNER JOIN dim_domains AS `DimDomain` ON (DimDomain.id = FactPageView.dim_domain_id)\n\t\t\t\tINNER JOIN dim_dma_codes AS `DimDmaCode` ON (DimDmaCode.id = FactPageView.dim_dma_code_id)\n\t\t\t\tWHERE DimDate.report_month = '{$month}' AND DimDate.report_year = '{$year}' {$sql_filter}\n\t\t\t) AS Traffic\n\t\t\tGROUP BY dma_code");
     $berra = $this->FactPageView->query("SELECT SUM(uniques) AS `total`,dma_code\n\t\t\tFROM (\n\t\t\t\tSELECT COUNT(*) AS `uniques`,dma_code,report_hour,report_day\n\t\t\t\tFROM (\n\t\t\t\t\tSELECT DISTINCT(session),DimDmaCode.dma_code AS `dma_code`,DimDate.report_day AS `report_day`,DimDate.report_hour AS `report_hour`\n\t\t\t\t\tFROM fact_page_views AS `FactPageView`\n\t\t\t\t\tINNER JOIN dim_dates AS `DimDate` ON (DimDate.id = FactPageView.dim_date_id)\n\t\t\t\t\tINNER JOIN dim_domains AS `DimDomain` ON (DimDomain.id = FactPageView.dim_domain_id)\n\t\t\t\t\tINNER JOIN dim_dma_codes AS `DimDmaCode` ON (DimDmaCode.id = FactPageView.dim_dma_code_id)\n\t\t\t\t\tWHERE DimDate.report_month = '{$month}' AND DimDate.report_year = '{$year}' {$sql_filter}\n\t\t\t\t) AS Traffic\n\t\t\t\tGROUP BY dma_code,report_day,report_hour\n\t\t\t) AS Traffic\n\t\t\tGROUP BY dma_code");
     $unq = array();
     $b_unq = array();
     foreach ($uniques as $v) {
         $unq[$v['Traffic']['dma_code']] = $v[0]['total'];
     }
     foreach ($berra as $v) {
         $b_unq[$v['Traffic']['dma_code']] = $v[0]['total'];
     }
     //fill in the report
     foreach ($report as $k => $v) {
         $report[$k][0]['uniques'] = $unq[$v['DimDmaCode']['dma_code']];
         $report[$k][0]['berra'] = $b_unq[$v['DimDmaCode']['dma_code']];
     }
     //get some select lists
     $domainList = $this->DimDomain->selectList();
     $this->set(compact("report", "domainList"));
 }
Пример #15
0
 function _multiParseAttributes($data, $keys, $default = array())
 {
     $def = array('exclude' => null, 'insertBefore' => ' ', 'insertAfter' => null, 'isolate' => false);
     $def = array_merge($def, $default);
     if ($def['isolate']) {
         $attrs = array();
     } else {
         $attrs = $data;
     }
     foreach (Set::normalize($keys) as $key => $opt) {
         $opt = array_merge($def, (array) $opt);
         if (Set::check($data, $key)) {
             $parsed = false;
             $unparsed = Set::extract($key, $data);
             if ($unparsed !== false) {
                 $parsed = $this->_parseAttributes($unparsed, $opt['exclude'], $opt['insertBefore'], $opt['insertAfter']);
             }
             $attrs = Set::insert($attrs, $key, $parsed);
         }
     }
     return $attrs;
 }
Пример #16
0
 /**
  * Se ejecuta despues del beforeFilter del controller pero antes de la acción
  * @param Controller $controller Referencia
  */
 function startup(&$controller)
 {
     # se carga el modelo que se encarga de obtener el contenido de las claves
     $this->__loadModel();
     # se ejecuta el metodo controller del behavior Translate en todos los modelos cargados
     foreach ($controller->uses as $model) {
         $parts = pluginSplit($model);
         $model = $parts[1];
         if (isset($controller->{$model}->Behaviors)) {
             if ($controller->{$model}->Behaviors->enabled("Translate")) {
                 $controller->{$model}->controller($controller);
             }
         }
     }
     $auth = $this->Session->read($this->Auth->sessionKey);
     if (Set::check($auth, "I18n.L10n.allow")) {
         $this->allow = Set::classicExtract($auth, "I18n.L10n.allow");
     } else {
         $this->allow = $this->Acl->check($this->Auth->user(), 'i18n/l10n/admin_edit') && !isset($_GET['L10n']);
         $this->Session->write($this->Auth->sessionKey . ".I18n.L10n.allow", $this->allow);
     }
     Configure::write("I18n.L10n.allow", $this->allow);
     Configure::write("I18n.L10n.active", $this->Session->check($this->sessionName) && $this->allow);
 }
 /**
  * edit method
  *
  * @throws NotFoundException
  * @param string $id
  * @return void
  */
 public function edit($id = null)
 {
     if (!$this->User->exists($id)) {
         throw new NotFoundException(__('Usuário Inválido!'));
     }
     if ($this->request->is(array('post', 'put'))) {
         //Criptografia da senha.
         if ($this->request->data['User']['new_password']) {
             $this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['new_password']);
         }
         //Editar imagem de perfil se for selecionado algum arquivo.
         $file = $this->request->data['User']['uploadfile'];
         if (!empty($file['tmp_name'])) {
             //Salva o arquivo de upload.
             $file_path = 'files' . DS . 'uploads' . DS . 'users' . DS . $id;
             $allowed = array('jpg', 'jpeg', 'png');
             $file_path_abs = $this->Upload->upload($file, $file_path, $allowed);
             if (!$file_path_abs) {
                 $this->Session->setFlash(__('Tipo de arquivo não suportado, tente novamete!'), 'alert_error');
                 return $this->redirect(array('action' => 'edit', $id));
             }
             //Apaga o arquivo de imagem atual.
             $pathToDelete = substr($this->request->data['User']['image_path'], (strlen($this->request->data['User']['image_path']) - 1) * -1);
             $file = new File($pathToDelete, false, 0777);
             $file->delete();
             $this->request->data['User']['id'] = $id;
             $this->request->data['User']['image_path'] = DS . $file_path_abs;
         }
         //Salva os dados de usuário.
         if ($this->User->save($this->request->data)) {
             $this->Session->setFlash(__('Alterações salvas com sucesso!'), 'alert_success');
             if ($id === $this->Session->read('Auth.User.id')) {
                 return $this->redirect(array('controller' => 'users', 'action' => 'logout'));
             } else {
                 return $this->redirect(array('action' => 'edit', $id));
             }
         } else {
             $this->Session->setFlash(__('As alterações não puderam ser salvas, tente novamete!'), 'alert_error');
         }
     } else {
         $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
         $this->request->data = $this->User->find('first', $options);
     }
     //Status list select
     $userStatuses = $this->User->UserStatus->find('list');
     $this->set(compact('userStatuses'));
     //Obtendo os grupos que este usuário pertence.
     $belongs = $this->Acl->Aro->query("SELECT Aro.id, Aro.parent_id, parent.image_path, parent.name\n                                                   FROM aros AS Aro\n                                                   INNER JOIN ( SELECT aros.id, all_groups.image_path, all_groups.name \n                                                                FROM aros \n                                                                INNER JOIN ( SELECT groups.id, groups.image_path, groups.name FROM groups ) AS all_groups \n                                                                ON aros.foreign_key = all_groups.id ) AS parent \n                                                   ON Aro.parent_id = parent.id                                                  \n                                                   WHERE Aro.model = 'User' AND Aro.foreign_key = " . $id);
     $this->set('belongs', $belongs);
     //debug($belongs);
     //lista de grupos.
     $this->loadModel('Group');
     $groups = $this->Group->find('list');
     $this->set(compact('groups'));
     //Obtendo as permissões do usuário.
     $this->loadModel('Page');
     $pages = $this->Page->find('all', array('conditions' => array('Page.enable' => 1), 'order' => 'Page.name'));
     //debug($pages);
     $lista = array();
     $aros_aco_id = NULL;
     $aco_parent_id = NULL;
     foreach ($pages as $page) {
         //Check permissão
         $check_permission = $this->Acl->check(array('User' => array('id' => $id)), array('Page' => array('id' => $page['Page']['id'])));
         //permissões diretas
         $direct_permission = $this->Acl->Aco->Permission->find('first', array('conditions' => array('Aco.model' => 'Page', 'Aco.foreign_key' => $page['Page']['id'], 'Aro.model' => 'User', 'Aro.foreign_key' => $id)));
         //debug($direct_permission);
         if (Set::check($direct_permission, 'Permission')) {
             $aco_parent_id = $direct_permission['Aco']['parent_id'];
             $aros_aco_id = $direct_permission['Permission']['id'];
             $direct_permission = true;
         }
         $page_acos = $this->Acl->Aco->find('first', array('conditions' => array('Aco.model' => 'Page', 'Aco.foreign_key' => $page['Page']['id']), 'fields' => 'Aco.parent_id'));
         $aco_parent_id = $page_acos['Aco']['parent_id'];
         //debug($aco_parent_id);
         $lista[] = array('aco_parent_id' => $aco_parent_id, 'aros_aco_id' => $aros_aco_id, 'page_id' => $page['Page']['id'], 'pageName' => $page['Page']['name'], 'check_permission' => $check_permission, 'direct_permission' => $direct_permission);
         $aros_aco_id = NULL;
         $aco_parent_id = NULL;
     }
     $this->set('permissions', $lista);
     //debug($lista);
     //debug($this->Acl->Aco->Permission->find('all'));
 }
 /**
  * edit method
  *
  * @throws NotFoundException
  * @param string $id
  * @return void
  */
 public function edit($id = null)
 {
     if (!$this->Group->exists($id)) {
         throw new NotFoundException(__('Grupo Inválido!'));
     }
     if ($this->request->is(array('post', 'put'))) {
         //Editar imagem de perfil se for selecionado algum arquivo.
         $file = $this->request->data['Group']['uploadfile'];
         if (!empty($file['tmp_name'])) {
             //Salva o arquivo de upload.
             $file_path = 'files' . DS . 'uploads' . DS . 'groups' . DS . $id;
             $allowed = array('jpg', 'jpeg', 'png');
             $file_path_abs = $this->Upload->upload($file, $file_path, $allowed);
             if (!$file_path_abs) {
                 $this->Session->setFlash(__('Tipo de arquivo não suportado, tente novamete!'), 'alert_error');
                 return $this->redirect(array('action' => 'edit', $id));
             }
             //Apaga o arquivo de imagem atual.
             $pathToDelete = substr($this->request->data['Group']['image_path'], (strlen($this->request->data['Group']['image_path']) - 1) * -1);
             $file = new File($pathToDelete, false, 0777);
             $file->delete();
             $this->request->data['Group']['id'] = $id;
             $this->request->data['Group']['image_path'] = DS . $file_path_abs;
         }
         //Salva os dados do grupo.
         if ($this->Group->save($this->request->data)) {
             $this->Session->setFlash(__('Alterações salvas com sucesso!'), 'alert_success');
             return $this->redirect(array('action' => 'edit', $id));
         } else {
             $this->Session->setFlash(__('As alterações não puderam ser salvas, tente novamete!'), 'alert_error');
         }
     } else {
         $options = array('conditions' => array('Group.' . $this->Group->primaryKey => $id));
         $this->request->data = $this->Group->find('first', $options);
     }
     //Obtenção do aroId do grupo selecionado.
     $aro = $this->Acl->Aro->find('first', array('conditions' => array('Aro.model' => 'Group', 'Aro.foreign_key' => $id)));
     $aroId = $aro['Aro']['id'];
     //Obtendo os membros do grupo selecionado (Pode ser usuarios e grupos).
     $members = $this->Acl->Aro->query('SELECT * FROM aros AS Aro
                                                INNER JOIN users AS User ON Aro.foreign_key = User.id
                                                WHERE Aro.parent_id = ' . $aroId);
     $this->set('members', $members);
     //debug($members);
     //lista de usuários.
     $this->loadModel('User');
     $users = $this->User->find('list');
     $this->set(compact('users'));
     //Obtendo as permissões do grupo.
     $this->loadModel('Page');
     $pages = $this->Page->find('all', array('conditions' => array('Page.enable' => 1), 'order' => 'Page.name'));
     //debug($pages);
     $lista = array();
     $aros_aco_id = NULL;
     $aco_parent_id = NULL;
     foreach ($pages as $page) {
         //Check permissão
         $check_permission = $this->Acl->check(array('Group' => array('id' => $id)), array('Page' => array('id' => $page['Page']['id'])));
         //.....
         $direct_permission = $this->Acl->Aco->Permission->find('first', array('conditions' => array('Aco.model' => 'Page', 'Aco.foreign_key' => $page['Page']['id'], 'Aro.model' => 'Group', 'Aro.foreign_key' => $id)));
         //debug($direct_permission);
         if (Set::check($direct_permission, 'Permission')) {
             $aco_parent_id = $direct_permission['Aco']['parent_id'];
             $aros_aco_id = $direct_permission['Permission']['id'];
             $direct_permission = true;
         }
         $page_acos = $this->Acl->Aco->find('first', array('conditions' => array('Aco.model' => 'Page', 'Aco.foreign_key' => $page['Page']['id']), 'fields' => 'Aco.parent_id'));
         $aco_parent_id = $page_acos['Aco']['parent_id'];
         //debug($aco_parent_id);
         $lista[] = array('aco_parent_id' => $aco_parent_id, 'aros_aco_id' => $aros_aco_id, 'page_id' => $page['Page']['id'], 'pageName' => $page['Page']['name'], 'check_permission' => $check_permission, 'direct_permission' => $direct_permission);
         $aros_aco_id = NULL;
         $aco_parent_id = NULL;
     }
     $this->set('permissions', $lista);
     //debug($lista);
     //debug($this->Acl->Aco->find('all'));
 }
Пример #19
0
 /**
  * Cette fonction permet la récupération de la valeur par défaut du champ input
  *
  * @param 	varchar $name 				Nom du champ
  * @param 	mixed	$defaultValue 		Valeur par défaut
  * @param 	boolean	$forceDefaultValue 	Indique s'il faut forcer ou non la valeur par défaut de l'input
  * @return 	mixed Valeur du champ input
  * @access	private
  * @author	koéZionCMS
  * @version 0.1 - 25/01/2012 by FI
  * @version 0.2 - 31/03/2014 by FI - Modification de la récupération de la valeur par défaut
  * @version 0.3 - 09/06/2015 by FI - Rajout de $forceDefaultValue
  */
 function _get_input_value($name, $defaultValue, $forceDefaultValue)
 {
     $currentValue = '';
     if (Set::check($this->view->controller->request->data, $name)) {
         $currentValue = Set::classicExtract($this->view->controller->request->data, $name);
     }
     if (($currentValue == '' || $forceDefaultValue) && isset($defaultValue)) {
         return $defaultValue;
     } else {
         return $currentValue;
     }
 }
Пример #20
0
 /**
  * testStrictKeyCheck method
  * 
  * @access public
  * @return void
  */
 function testStrictKeyCheck()
 {
     $set = new Set(array('a' => 'hi'));
     $this->assertFalse($set->check('a.b'));
 }
Пример #21
0
 /**
  * Cette fonction permet d'effectuer le rempmlace des données contenues dans un text
  * Dans $content si on trouve un texte du style [Customer.name] et que l'index est présent dans $replacement alors le texte sera remplacé par sa veleur dans le tableau 
  * @param 	varchar $content 		Texte dans lequel il faut chercher
  * @param 	array 	$replacement	Données de remplacement
  * @return 	varchar	Contenu modifié
  * @access 	public
  * @author 	koéZionCMS
  * @version 0.1 - 06/03/2014 by FI
  * @version 0.2 - 04/04/2014 by FI - Modification de la récupération de la valeur à remplacer
  */
 public function replace_content($content, $replacement)
 {
     preg_match_all("/\\[(.+?)\\]/", $content, $result);
     //$result contient
     // - dans le premier index (0) les chaines trouvés dans le texte avec les crochets
     // - dans le second (1) les chaines trouvés dans le texte sans les crochets
     if (!empty($result[1])) {
         foreach ($result[1] as $key => $path) {
             if (Set::check($replacement, $path)) {
                 $value = Set::classicExtract($replacement, $path);
                 $content = str_replace($result[0][$key], $value, $content);
             }
         }
     }
     return $content;
 }
Пример #22
0
 function linkReadFindOptions(&$model, $findOptions = null, $containMode = false)
 {
     //////////// Normalize options ////////////
     if (is_null($findOptions)) {
         if (!$containMode && !empty($model->id)) {
             $findOptions = array('conditions' => array($model->alias . '.id' => $model->id));
         } else {
             $findOptions = array();
         }
     } else {
         $findOptions = (array) $findOptions;
         if (Set::numeric(array_keys($findOptions))) {
             if (Set::numeric($findOptions)) {
                 $findOptions = array('conditions' => array($model->alias . '.id' => $findOptions));
             } else {
                 $findOptions = array('fields' => $findOptions);
             }
         } else {
             $toArray = array('fields', 'conditions', 'contain');
             foreach ($toArray as $val) {
                 if (!empty($findOptions[$val]) && !is_array($findOptions[$val])) {
                     $findOptions[$val] = array($findOptions[$val]);
                 }
             }
         }
     }
     $def = $this->settings[$model->alias]['find'];
     $def['tagName'] = $model->tagName();
     $findOptions = Set::merge($def, $findOptions);
     if (!empty($findOptions['restrict'])) {
         $findOptions['fields'] = array_diff($findOptions['fields'], (array) $findOptions['restrict']);
     }
     if (empty($findOptions['fields'])) {
         return false;
     }
     if (!empty($findOptions['contain'])) {
         $findOptions['contain'] = Set::normalize($findOptions['contain']);
     }
     $defaultInternal = Configure::read('xmlLink.defaultInternal');
     if (!empty($defaultInternal)) {
         if (empty($findOptions['internal'])) {
             $findOptions['internal'] = array();
         }
         $findOptions['internal'] = Set::merge((array) $defaultInternal, (array) $findOptions['internal']);
     }
     //////////// Set mapping between bd and xml ////////////
     $fields = array();
     $mapping = array();
     foreach (Set::normalize($findOptions['fields']) as $key => $val) {
         if (empty($val)) {
             $fields[] = $key;
         } elseif (strpos($val, '.') !== false) {
             $parts = explode('.', $val);
             $last = array_pop($parts);
             $cmodel = $model;
             $defUpTo = 0;
             if (!empty($findOptions['contain'])) {
                 while ($defUpTo + 1 < count($parts) && Set::check($findOptions['contain'], implode('.', array_slice($parts, 0, $defUpTo + 1)))) {
                     $defUpTo++;
                     //debug(implode('.',array_slice($parts,0,$defUpTo+1)));
                 }
             }
             $fieldPath = 'contain.' . implode('.', $parts) . '.fields';
             $addFields = array();
             if (Set::check($findOptions, $fieldPath)) {
                 $addFields = Set::extract($fieldPath, $findOptions);
             }
             $addFields[] = $last;
             if ($defUpTo > 0) {
                 $internalPath = 'internal.' . implode('.', array_slice($parts, 0, $defUpTo));
                 $findOptions = Set::insert($findOptions, $internalPath, $parts[$defUpTo]);
             } else {
                 $findOptions = Set::insert($findOptions, 'internal.' . $fieldPath, $addFields);
             }
             $findOptions = Set::insert($findOptions, 'contain.' . implode('.', $parts) . '.fields', $addFields);
             $mapping[$key] = $val;
         } else {
             $fields[] = $val;
             $findOptions['internal'][] = $val;
             $mapping[$key] = $val;
         }
     }
     $findOptions['mapping'] = $mapping;
     //////////// Setup for output Definition field ////////////
     $outputDefineOpt = $this->settings[$model->alias]['outputDefine'];
     if ($outputDefineOpt && !empty($outputDefineOpt['field']) && $model->hasField($outputDefineOpt['field'])) {
         if (empty($outputDefineOpt['include'])) {
             $needed = array_keys($model->schema());
         } else {
             $needed = $outputDefineOpt['include'];
         }
         $needed += array($outputDefineOpt['field']);
         if (!empty($outputDefineOpt['exclude'])) {
             $needed = array_diff($needed, $outputDefineOpt['exclude']);
         }
         $needed = array_diff($needed, $fields);
         $needed = array_diff($needed, $findOptions['internal']);
         $findOptions['internal'] = array_merge($findOptions['internal'], $needed);
     }
     //////////// Set contains ////////////
     $fields += array('id');
     if (!empty($findOptions['internal'])) {
         $ifields = $findOptions['internal'];
         unset($ifields['contain']);
         $fields = array_merge($fields, $ifields);
     }
     if (!empty($findOptions['internal']['contain'])) {
         $findOptions['internal']['contain'] = Set::normalize($findOptions['internal']['contain']);
         foreach ($findOptions['internal']['contain'] as $modelName => $opt) {
             if (!empty($model->{$modelName}) && (empty($findOptions['contain']) || empty($findOptions['contain'][$modelName]) && !in_array($modelName, $findOptions['contain']))) {
                 $findOptions['contain'][$modelName] = $opt;
             }
         }
     }
     $findOptions['fields'] = $fields;
     if (!empty($findOptions['contain'])) {
         $contain = $findOptions['contain'];
         $finalContain = array();
         foreach ((array) $findOptions['contain'] as $modelName => $opt) {
             if (is_numeric($modelName)) {
                 $modelName = $opt;
                 $opt = null;
             }
             if (isset($model->{$modelName})) {
                 $cModel = $model->{$modelName};
             } else {
                 $cModel = ClassRegistry::init($modelName);
             }
             if ($cModel->Behaviors->attached('XmlLinked')) {
                 $subOpt = $cModel->linkReadFindOptions($opt, true);
                 if (!empty($subOpt)) {
                     $findOptions['sublinked'][$cModel->alias] = $subOpt;
                     /*if(!empty($subOpt['internal'])){
                     			$findOptions['internal'][$cModel->alias] = $subOpt['internal'];
                     			unset($subOpt['internal']);
                     		}*/
                     $subOpt = array_diff_key($subOpt, array_flip($this->internalFindOpt));
                     if (!empty($subOpt['contain'])) {
                         $subOpt = array_merge($subOpt, $subOpt['contain']);
                         unset($subOpt['contain']);
                     }
                 }
             } else {
                 $subOpt = (array) $opt;
                 if (empty($subOpt['fields'])) {
                     $subOpt['fields'] = array_keys($cModel->schema());
                 }
                 $findOptions['internal']['contain'][$modelName] = $subOpt;
             }
             if (!empty($subOpt)) {
                 if (!in_array('id', $subOpt['fields']) && !in_array($modelName . '.id', $subOpt['fields'])) {
                     $subOpt['fields'][] = $modelName . '.id';
                 }
                 $finalContain[$modelName] = $subOpt;
             }
         }
         $findOptions['contain'] = $finalContain;
     }
     //debug($findOptions);
     return $findOptions;
 }
Пример #23
0
 public function testUser()
 {
     $user = array('NinjaAuthComponentMockUser' => array('username' => 'test user1', 'Group' => array('name' => 'test group1'), 'Profile' => array('nickname' => 'test nick')));
     $this->NinjaAuth->Session->write('Auth', $user);
     $this->assertNull($this->NinjaAuth->user('undefined'));
     $this->assertEqual('test user1', $this->NinjaAuth->user('username'));
     $this->assertEqual('test group1', $this->NinjaAuth->user('Group.name'));
     $result = $this->NinjaAuth->user();
     $this->assertTrue(Set::check($result, 'NinjaAuthComponentMockUser.Profile.nickname'));
     $this->assertTrue(Set::check($result, 'NinjaAuthComponentMockUser.username'));
 }
 /**
  * Makes $mirror_name identical to $model_name
  *
  * @access private
  * @param string  $model_name  The name of the primary model
  * @param string  $mirror_name The name of the mirror model
  * @param boolean $truncate    (optional) Empty $mirror_name before (clean dump... no longer smart ;))
  * @return boolean Result of smart mirror
  */
 private function _smartMirror($model_name, $mirror_name, $truncate = false)
 {
     //if($mirror_name != 'CjcNetDataField'){ return true; }
     if (empty($this->_smartMirrors[$model_name][$mirror_name]['mirrorModel'])) {
         $this->_smartMirrors[$model_name][$mirror_name]['mirrorModel'] =& ClassRegistry::init($mirror_name);
     }
     $mirror_model = $this->_smartMirrors[$model_name][$mirror_name]['mirrorModel'];
     $model = $this->_smartMirrors[$model_name][$mirror_name]['model'];
     if (empty($mirror_model) or empty($model)) {
         $this->_log('Either the main model or the mirrored model failed to load', 0);
     }
     $errors = false;
     $find_options = $this->_smartMirrors[$model_name][$mirror_name]['findOptions'];
     if (!isset($find_options['contain'])) {
         $find_options['contain'] = false;
     }
     $primary_results = $model->find('all', $find_options);
     $primary_results = Set::combine($primary_results, '{n}.' . $model_name . '.' . $model->primaryKey, '{n}');
     if ($truncate) {
         $tresult = $mirror_model->query('TRUNCATE TABLE ' . $mirror_model->tablePrefix . $mirror_model->table);
         $mirror_results = array();
         if (!$tresult) {
             $this->_log('Failed to truncate table (model: ' . $mirror_name . '): ' . $mirror_model->tablePrefix . $mirror_model->table, 3);
         }
     } else {
         $mirror_results = $mirror_model->find('all', array('contain' => false));
         $mirror_results = Set::combine($mirror_results, '{n}.' . $mirror_name . '.' . $mirror_model->primaryKey, '{n}');
     }
     $primary_result_ids = array();
     $transaction = array();
     $mismatch_warning = false;
     $modified_field = $this->_smartMirrors[$model_name][$mirror_name]['modified_field'];
     $field_map = $this->_smartMirrors[$model_name][$mirror_name]['fieldMap'];
     foreach ($primary_results as $pr) {
         $result = $pr[$model->alias];
         $result_id = $result[$model->primaryKey];
         $primary_result_ids[] = $result_id;
         $do_update = true;
         if (!$truncate) {
             $do_update = false;
             $primary_result = $primary_results[$result_id];
             if (empty($mirror_results[$result_id])) {
                 $do_update = true;
                 $mirror_result = array();
             } else {
                 $mirror_result = $mirror_results[$result_id];
             }
             if (!$do_update) {
                 if (isset($field_map[$model_name . '.' . $modified_field])) {
                     $result_primary = Set::classicExtract($primary_result, $model_name . '.' . $modified_field);
                     $result_mirror = Set::classicExtract($mirror_result, $mirror_name . '.' . $modified_field);
                     if (!empty($result_primary) and Set::check($mirror_result, $mirror_name . '.' . $modified_field) === true) {
                         if (strtotime($result_primary) > strtotime($result_mirror)) {
                             $do_update = true;
                         }
                     } elseif (!$mismatch_warning and Set::check($mirror_result, $mirror_name . '.' . $modified_field) === false) {
                         $mismatch_warning = true;
                         $this->_log("The field '{$model_name}.{$modified_field}' is mismatched between {$model_name} and {$mirror_name}", 2);
                     }
                 } else {
                     foreach ($field_map as $primary_key => $mirror_key) {
                         if ($do_update) {
                             continue;
                         }
                         $result_primary = Set::classicExtract($primary_result, $primary_key);
                         $result_mirror = Set::classicExtract($mirror_result, $mirror_key);
                         $set_check = Set::check($mirror_result, $mirror_key);
                         if ($result_primary !== $result_mirror and $set_check === true) {
                             $do_update = true;
                         } elseif (!$mismatch_warning and $set_check === false) {
                             $mismatch_warning = true;
                             $this->_log("The field '{$primary_key}' is mismatched between {$model_name} and {$mirror_name}", 2);
                         }
                     }
                 }
             }
         }
         if ($do_update) {
             $build_data = $this->_buildDataPackage($model_name, $mirror_name, $pr);
             $transaction[] = $build_data[$mirror_name];
         }
     }
     if (!empty($transaction)) {
         if (!$mirror_model->saveAll($transaction, array('atomic' => $this->_smartMirrors[$model_name][$mirror_name]['atomic']))) {
             $errors = true;
             $this->_log('Failed to save updated/new record during a SmartMirror task', 3);
         }
     }
     // delete old ones
     if (!$mirror_model->deleteAll(array($mirror_name . '.' . $model->primaryKey . ' NOT' => $primary_result_ids), false)) {
         $errors = true;
         $this->_log('Failed to delete unused records during a SmartMirror task', 3);
     }
     if (!$errors) {
         $this->_stats[$model_name][$mirror_name]['last_smart_mirror'] = time();
     }
     return !$errors;
 }
Пример #25
0
 /**
  * Removes any ignored associations, as defined in the model settings, from
  * the $this->contain array.
  *
  * @access public
  *
  * @param object $Model Model object
  *
  * @return boolean
  */
 private function __removeIgnored($Model)
 {
     if (!$this->settings[$Model->alias]['ignore']) {
         return true;
     }
     $ignore = array_unique($this->settings[$Model->alias]['ignore']);
     foreach ($ignore as $path) {
         if (Set::check($this->contain, $path)) {
             $this->contain = Set::remove($this->contain, $path);
         }
     }
     return true;
 }
Пример #26
0
 public function testCheckDoubleSave()
 {
     $this->Model->Behaviors->attach('Ninja.CommonValidation', array('waitDoubleCheck' => 10));
     $this->Model->validate = array('created' => array('checkDoubleSave' => array('rule' => array('checkDoubleSave', 'common_validation_behavior_belonged_id', 'common_validation_behavior_user_id'))));
     $data = array('common_validation_behavior_belonged_id' => 4, 'common_validation_behavior_user_id' => 4);
     $this->assertTrue(!!$this->Model->save($this->Model->create($data)));
     $this->assertFalse($this->Model->save($this->Model->create($data)));
     $this->assertTrue(Set::check($this->Model->validationErrors, 'created'));
     $this->Model->validate = array('created' => array('checkDoubleSave' => array('rule' => array('checkDoubleSave'))));
     $this->assertFalse($this->Model->save($this->Model->create($data)));
     $this->assertTrue(Set::check($this->Model->validationErrors, 'created'));
     $this->Model->validate['created']['checkDoubleSave']['rule'][] = 5;
     $this->assertFalse($this->Model->save($this->Model->create($data)));
     $this->assertTrue(Set::check($this->Model->validationErrors, 'created'));
 }
Пример #27
0
 /**
  * testStrictKeyCheck method
  *
  * @return void
  */
 public function testStrictKeyCheck()
 {
     $set = array('a' => 'hi');
     $this->assertFalse(Set::check($set, 'a.b'));
 }
 /**
  * itemsFound method
  *
  */
 public function itemsFound($townhouses = null, $towers = null, $loc1 = null, $loc2 = null, $services = null, $checks = null, $checked1 = null, $checked2 = null, $checked3 = null)
 {
     $this->autoRender = false;
     $conditions = array();
     if ($townhouses !== 'null' && $townhouses !== null) {
         $townhouses = split(',', $townhouses);
         $conditions[] = array('Tower.townhouse_id' => $townhouses);
     }
     if ($towers !== 'null' && $towers !== null) {
         $towers = split(',', $towers);
         $conditions[] = array('Item.tower_id' => $towers);
     }
     if ($loc1 !== 'null' && $loc1 !== null) {
         $loc1 = split(',', $loc1);
         $conditions[] = array('Item.Location1_id' => $loc1);
     }
     if ($loc2 !== 'null' && $loc2 !== null) {
         $loc2 = split(',', $loc2);
         $conditions[] = array('Item.Location2_id' => $loc2);
     }
     //            if($loc3 !== 'null' && $loc3 !== null){
     //                $loc3 = split(',', $loc3);
     //                $conditions[] = array('Item.Location3_id' => $loc3);
     //            }
     if ($services !== 'null' && $services !== null) {
         $services = split(',', $services);
         $conditions[] = array('Item.Service_id' => $services);
     }
     if ($checks !== 'null' && $checks !== null) {
         $checks = split(',', $checks);
         $conditions[] = array('Item.Check_id' => $checks);
     }
     $conditionsChecks = array();
     if ($checked1 !== 'null' && $checked1 !== null || $checked2 !== 'null' && $checked2 !== null || $checked3 !== 'null' && $checked3 !== null) {
         if ($checked1 !== 'null' && $checked1 !== null) {
             $conditionsChecks[] = $checked1;
         }
         if ($checked2 !== 'null' && $checked2 !== null) {
             $conditionsChecks[] = $checked2;
         }
         if ($checked3 !== 'null' && $checked3 !== null) {
             $conditionsChecks[] = $checked3;
         }
         $conditions[] = array('Item.lastChecked' => $conditionsChecks);
     }
     //debug($conditions);
     //debug($this->request);
     //Total de Itens
     $totalItems = $this->Item->find('count', array('conditions' => $conditions));
     //lista de Itens
     //OBS.  o containable só funciona se colocado (public $actsAs = array('Containable'); em appModel.
     $items = $this->Item->find('all', array('recursive' => -2, 'contain' => array('Tower.Townhouse', 'Location1', 'Location2', 'Location3', 'Service', 'Check', 'Photo' => array('limit' => 1)), 'conditions' => $conditions, 'offset' => $this->request->query['start'], 'limit' => $this->request->query['length']));
     //debug($items);
     $result = array();
     foreach ($items as $item) {
         $EnterpriseTownhouse = "<div class='text-semibold'<h6>" . $item['Tower']['Townhouse']['name'] . "</h6></div><div class='text-muted'>" . $item['Tower']['name'] . "</div>";
         //Verificar o tipo medido.
         if ($item['Item']['lastChecked'] === '1') {
             $checked = '<i class="icon-thumbs-up3 text-success"></i>';
         } else {
             if ($item['Item']['lastChecked'] === '2') {
                 $checked = '<i class="icon-thumbs-down3 text-danger"></i>';
             } else {
                 $checked = '';
             }
         }
         $actions = "<ul class='icons-list'>";
         $actions = $actions . (Set::check($item, 'Photo.0') ? "<li><a data-toggle='modal' data-target='#modal_photo' onclick='getPhoto(" . $item['Item']['id'] . ")'><i class='icon-camera'></i></a><li>" : "");
         $actions = $actions . ($item['Item']['lastNote'] ? "<li><a data-toggle='modal' data-target='#modal_note' onclick='getNote(" . $item['Item']['id'] . ")'><i class='icon-comments'></i></a><li>" : "");
         $actions = $actions . "</ul>";
         $result[] = array($EnterpriseTownhouse, $item['Location1']['name'], $item['Location2']['name'], $item['Service']['name'], $item['Check']['name'], $checked, $actions);
     }
     $result = array('draw' => $this->request->query['draw'] + 1, 'recordsTotal' => $totalItems, 'recordsFiltered' => $totalItems, 'data' => $result);
     //debug($result);
     echo json_encode($result);
 }