/**
  * Extract all required information from a CanteenOrder to send to the GatewayAccount Processor
  * @param CanteenOrder $CanteenOrder
  * @return Array:
  */
 public static function formatCanteenOrder($CanteenOrder)
 {
     $t = array();
     $customer = $CanteenOrder['BillingAddress'];
     #TRANSACTION
     $t['Transaction']['currency_id'] = Set::classicExtract($CanteenOrder, "CanteenOrder.currency_id");
     $t['Transaction']['amount'] = Set::classicExtract($CanteenOrder, "CanteenOrder.grand_total");
     $t['Transaction']['foreign_key'] = Set::classicExtract($CanteenOrder, "CanteenOrder.id");
     $t['Transaction']['model'] = "CanteenOrder";
     #CUSTOMER
     $t['Customer']['first_name'] = Set::classicExtract($customer, "first_name");
     $t['Customer']['last_name'] = Set::classicExtract($customer, "last_name");
     $t['Customer']['address'] = Set::classicExtract($customer, "street") . " " . Set::classicExtract($customer, "apt");
     $t['Customer']['postal'] = Set::classicExtract($customer, "postal_code");
     $t['Customer']['country'] = Set::classicExtract($customer, "country_code");
     $t['Customer']['email'] = Set::classicExtract($customer, "email");
     $t['Customer']['city'] = Set::classicExtract($customer, "city");
     $t['Customer']['state'] = Set::classicExtract($customer, "state");
     $t['Customer']['phone'] = Set::classicExtract($customer, "phone");
     $t['Customer']['user_id'] = Set::classicExtract($customer, "user_id");
     #CARD DATA
     $t['CardData']['number'] = Set::classicExtract($CanteenOrder, "CardData.number");
     $t['CardData']['exp_year'] = Set::classicExtract($CanteenOrder, "CardData.exp_year");
     $t['CardData']['exp_month'] = Set::classicExtract($CanteenOrder, "CardData.exp_month");
     $t['CardData']['code'] = Set::classicExtract($CanteenOrder, "CardData.code");
     return $t;
 }
 function admin_index()
 {
     $model = 'Telefone';
     $this->set('model', $model);
     //// Find de apoio à listagem. Filtro
     //// Relacionamento:
     ////	- Empresa
     //==============================================================
     $this->set('setores', $this->{$model}->Setor->find('list', array('fields' => array('id', 'setor'), 'conditions' => array('ativo' => 1))));
     //==============================================================
     //// FILTRO:
     //==============================================================
     if (!empty($this->request->data['filtro']['Setores'])) {
         $ids_empresas = '';
         foreach ($this->request->data['filtro']['Setores'] as $r) {
             $ids_empresas = $ids_empresas . $r . ',';
         }
         $sql_conteudo_id = "SELECT DISTINCT Telefone.id\n\t\t\t\t\t\t\t\tFROM tb_telefones as Telefone\n\t\t\t\t\t\t\t\tINNER JOIN tb_telefones_setores as TE ON (TE.telefone_id = Telefone.id)\n\t\t\t\t\t\t\t\tINNER JOIN tb_setores as Setor ON (TE.setor_id = Setor.id) \n\t\t\t\t\t\t\t\tWHERE Setor.id IN (" . substr_replace($ids_empresas, '', -1, 1) . ")";
         $conteudos = $this->{$model}->query($sql_conteudo_id);
         //////============>>>
         //Desmontar Array
         $conteudo_id = Set::classicExtract($conteudos, '{n}.Telefone.id');
         /////////////////
         $this->paginate['contain'] = array('Setor');
         $this->paginate['conditions'] = array('Telefone.id' => $conteudo_id);
     }
     //==============================================================
     $this->paginate['fields'] = array('id', 'telefones', 'ativo');
     $this->set('registros', $this->paginate($model));
 }
 /**
  * testGetPathToRole
  *
  * @return void
  */
 public function testGetPathToRole()
 {
     $expected = array(Role::SUPER, Role::ADMIN, Role::MOD, Role::USER);
     $result = $this->Role->getPathToRole(Role::USER);
     $actual = Set::classicExtract($result, '{n}.Role.name');
     $this->assertEquals($expected, $actual, 'path to user role should go super->admin->mod->user');
 }
Exemple #4
0
 /**
  * Get thread's messages
  *
  */
 public function getMessages($threadId = 0)
 {
     $messages = $this->find('all', array('conditions' => array('admin_thread_id' => $threadId), 'recursive' => -1, 'order' => array('created')));
     if (!$messages) {
         return array();
     }
     $today = date('Y-m-d');
     $dayOfWeekList = array(0 => '日', '月', '火', '水', '木', '金', '土');
     foreach ($messages as $key => $message) {
         // Prepare file attach message
         if (isset($message['AdminChat']['file']) && $message['AdminChat']['file']) {
             $messages[$key]['AdminChat']['file'] = Router::url(array('controller' => 'admin_messages', 'action' => 'file', $message['AdminChat']['id']));
         }
         $messages[$key]['AdminChat']['message_content'] = $message['AdminChat']['message'];
         unset($messages[$key]['AdminChat']['message']);
         // Prepare sent date
         if (isset($message['AdminChat']['created']) && $message['AdminChat']['created']) {
             $sentDate = date('Y-m-d', strtotime($message['AdminChat']['created']));
             $sentHour = date('H:i', strtotime($message['AdminChat']['created']));
             $sentDoW = $dayOfWeekList[date('w', strtotime($message['AdminChat']['created']))];
             $messages[$key]['AdminChat']['last_sent'] = $sentDate;
             if ($sentDate == $today) {
                 $messages[$key]['AdminChat']['display_date'] = '今日';
             } else {
                 $messages[$key]['AdminChat']['display_date'] = str_replace('-', '/', str_replace(date('Y') . '-', '', $sentDate)) . '(' . $sentDoW . ')';
             }
             $messages[$key]['AdminChat']['display_hour'] = $sentHour;
         }
     }
     return Set::classicExtract($messages, '{n}.AdminChat');
 }
 private function importElements()
 {
     App::import('Core', 'GummFolder');
     $Folder = new GummFolder(GUMM_LAYOUT_ELEMENTS);
     $elementFiles = $Folder->findRecursive('.*\\.php');
     $Folder->cd(GUMM_LAYOUT_ELEMENTS_SINGLE);
     $elementFiles = array_merge($elementFiles, $Folder->findRecursive('.*\\.php'));
     $availableElements = Set::flatten(Set::classicExtract(array_values(Configure::read('Data.BuilderElements')), '{n}.elements'));
     $elementsAvaialbleMap = array();
     foreach ($elementFiles as $layoutElementFullPath) {
         $basename = basename($layoutElementFullPath, '.php');
         if (in_array($basename, $availableElements)) {
             $elementsAvaialbleMap[$basename] = $layoutElementFullPath;
         }
     }
     foreach ($availableElements as $basename) {
         if (isset($elementsAvaialbleMap[$basename])) {
             require_once $elementsAvaialbleMap[$basename];
             $className = Inflector::camelize($basename) . 'LayoutElement';
             $settings = array();
             if ($this->post) {
                 $settings['postId'] = $this->post->ID;
             }
             $obj = new $className($settings);
             $this->elementsAvailable[Inflector::underscore($basename)] = $obj;
         }
     }
 }
 /**
  * index method
  *
  * @return void
  */
 public function index()
 {
     $this->loadModel('User');
     $this->loadModel('Wallet');
     $this->TransferWallet->recursive = 0;
     $id_auth = $this->Auth->user('id');
     $findWallet = $this->User->findWalletAuth($id_auth);
     $result_wallet_selected = Set::classicExtract($findWallet, '{n}.wallets.id');
     // search
     $sentWalletId = $this->request->query('sent_wallet_id');
     $recieveWalletId = $this->request->query('receive_wallet_id');
     $money = $this->request->query('transfer_money');
     $day = $this->request->query('day_start');
     $month = $this->request->query('month_start');
     $year = $this->request->query('year_start');
     $conditions = array('TransferWallet.sent_wallet_id is not null', 'TransferWallet.receive_wallet_id is not null');
     if (!empty($sentWalletId)) {
         $conditions['TransferWallet.sent_wallet_id'] = $sentWalletId;
     } else {
         $conditions['TransferWallet.sent_wallet_id'] = $result_wallet_selected;
     }
     if (!empty($recieveWalletId)) {
         $conditions['TransferWallet.receive_wallet_id'] = $recieveWalletId;
     } else {
         $conditions['TransferWallet.receive_wallet_id'] = $result_wallet_selected;
     }
     if (!empty($money)) {
         if ($money >= 500001) {
             $conditions[] = 'TransferWallet.transfer_money >' . $money;
         } else {
             $conditions[] = 'TransferWallet.transfer_money <=' . $money;
         }
     }
     if (!empty($day)) {
         $conditions['day(TransferWallet.created)'] = $day;
     } else {
         $conditions[] = 'day(TransferWallet.created) is not null';
     }
     if (!empty($month)) {
         $conditions['month(TransferWallet.created)'] = $month;
     }
     if (!empty($year)) {
         $conditions['YEAR(TransferWallet.created)'] = $year;
     }
     $countTransfer = count($this->TransferWallet->find('all', array('conditions' => $conditions)));
     // check if wallet count >= 2
     $countWallets = $this->Wallet->countWallets($id_auth);
     if ($countWallets[0][0]['count(*)'] < 2) {
         $this->Flash->error(__('you must have two wallets before add transfer!'));
         $this->redirect(array('controller' => 'wallets', 'action' => 'index'));
     }
     $this->paginate = array('conditions' => $conditions, 'limit' => 20);
     $sentWallets = $this->TransferWallet->getListWalletSent($result_wallet_selected);
     $receiveWallets = $this->TransferWallet->getListWalletReceive($result_wallet_selected);
     $this->set('transferWallets', $this->Paginator->paginate());
     $this->set('countTransfer', $countTransfer);
     $this->set(compact('sentWallets', 'receiveWallets'));
 }
 /**
  * @param string $path
  * @param bool $forUser
  * @return void
  */
 public function read($path = '', $forUser = true)
 {
     if (!$path) {
         return;
     }
     $path = $this->_getPath($path, $forUser);
     $__cookie = $this->_getGummCookie();
     return Set::classicExtract($__cookie, $path);
 }
 public function getLast($user_id, $limit = 20)
 {
     $results = $this->find('all', array('conditions' => array('Notification.user_id' => $user_id, "Notification.created >" => date('Y-m-d', strtotime("-1 weeks"))), 'limit' => $limit));
     $ids = Set::classicExtract($results, '{n}.Notification.id');
     $subjects = $this->Subject->findAllByNotificationId($ids);
     foreach ($results as $k => $result) {
         $s = Set::extract('/.[notification_id=' . $result['Notification']['id'] . ']', $subjects);
         foreach ($s as $t) {
             $results[$k][$t['model']] = $t[$t['model']];
         }
     }
     return $results;
 }
 /**
  * @param int $postId
  * @param string $metaId
  * @param bool $single
  * @return mixed
  */
 public function find($postId, $metaId, $single = true)
 {
     $metaId = $this->gummOptionId($metaId, true);
     $meta = false;
     if (strpos($metaId, '.') !== false) {
         $parts = explode('.', $metaId);
         $rootId = array_shift($parts);
         $rootMetaData = get_post_meta($postId, $rootId, $single);
         $metaXPath = implode('.', $parts);
         $meta = Set::classicExtract($rootMetaData, $metaXPath);
         if ($meta === null || $rootMetaData === '' && !$meta) {
             $meta = false;
         }
     } else {
         $meta = get_post_meta($postId, $metaId, $single);
         // if ($postId == 442 && $metaId == 'nova_postmeta') {
         //     debug(get_post_meta(442, 'nova_postmeta'), true);
         //     d($meta);
         // } else {
         //     debug($postId);
         //     debug($metaId);
         // }
     }
     // debug($metaId);
     $_post = get_post($postId);
     $friendlyId = $this->friendlyOptionId($metaId);
     $postTypes = array($_post->post_type);
     if (in_array($_post->post_type, $this->Post->getPostTypes())) {
         $postTypes[] = 'single';
     }
     if (!$meta && isset($this->_schema[$friendlyId])) {
         $meta = $this->_schema[$friendlyId];
     } elseif ($friendlyId == 'postmeta') {
         foreach ($postTypes as $postType) {
             if (isset($this->_schema[$postType]) && isset($this->_schema[$postType]['postmeta'])) {
                 if (!$meta) {
                     $meta = $this->_schema[$postType]['postmeta'];
                 } else {
                     $meta = array_merge($this->_schema[$postType]['postmeta'], (array) $meta);
                 }
                 if (is_array($meta)) {
                     $meta = Set::booleanize($meta);
                 }
             }
         }
     }
     if ($meta && !is_admin() && function_exists('qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage')) {
         $meta = qtrans_useCurrentLanguageIfNotFoundUseDefaultLanguage($meta);
     }
     return $meta;
 }
 /**
  * index method
  *
  * @return void
  */
 public function index()
 {
     $this->loadModel('User');
     $this->loadModel('Wallet');
     $this->Transaction->recursive = 0;
     $id_auth = $this->Auth->user('id');
     $findWallet = $this->User->findWalletAuth($id_auth);
     $result_wallet_id = Set::classicExtract($findWallet, '{n}.wallets.id');
     $categorieId = $this->request->query('categorie_id');
     $walletId = $this->request->query('wallet_id');
     $money = $this->request->query('money');
     $day = $this->request->query('day_start');
     $month = $this->request->query('month_start');
     $year = $this->request->query('year_start');
     $conditions = array('Wallet.id is not null', 'Categorie.id is not null');
     if (!empty($categorieId)) {
         $conditions['Transaction.categorie_id'] = $categorieId;
     }
     if (!empty($walletId)) {
         $conditions['Transaction.wallet_id'] = $walletId;
     } else {
         $conditions['Transaction.wallet_id'] = $result_wallet_id;
     }
     if (!empty($money)) {
         $conditions[] = 'Transaction.transaction_money <=' . $money;
     }
     if (!empty($day)) {
         $conditions['day(Transaction.day_transaction)'] = $day;
     }
     if (!empty($month)) {
         $conditions['month(Transaction.day_transaction)'] = $month;
     }
     if (!empty($year)) {
         $conditions['year(Transaction.day_transaction)'] = $year;
     }
     $this->paginate = array('conditions' => $conditions, 'limit' => 20);
     $countTransaction = count($this->Transaction->find('all', array('conditions' => $conditions)));
     $countWallets = $this->Wallet->countWallets($id_auth);
     if ($countWallets[0][0]['count(*)'] < 1) {
         $this->Flash->error(__('you must add wallet before add transaction!'));
         $this->redirect(array('controller' => 'wallets', 'action' => 'index'));
     }
     $categoriesIncome = $this->Transaction->getAllCategoriesIncome();
     $categoriesExpense = $this->Transaction->getAllCategoriesExpense();
     $categories = $this->Transaction->findListCategory();
     $wallets = $this->Transaction->findIdWalletAuth($result_wallet_id);
     $this->set('transactions', $this->Paginator->paginate());
     $this->set('countTransaction', $countTransaction);
     $this->set(compact('categoriesIncome', 'categoriesExpense', 'categories', 'wallets'));
 }
 public function afterFind($results, $primary = false)
 {
     if ($primary) {
         $ids = Set::classicExtract($results, '{n}.Notification.id');
         $subjects = $this->Subject->findAllByNotificationId($ids);
         foreach ($results as $k => $result) {
             $s = Set::extract('/.[notification_id=' . $result['Notification']['id'] . ']', $subjects);
             foreach ($s as $t) {
                 $results[$k][$t['model']] = $t[$t['model']];
             }
         }
     }
     return $results;
 }
 /**
  * CCL002 - history answer advisor
  *
  * @return void
  * @author huyenlt
  **/
 public function advisor_index()
 {
     $this->set('title_for_layout', '回答履歴一覧');
     $advisorProfile = $this->AdvisorProfile->find('first', array('contain' => array('Advisor' => array('username'), 'AdvisorInterview' => array('id', 'AdvisorStat'), 'AdvisorRatingStat' => array('id', 'avg_rating')), 'fields' => array('id', 'image_url', 'fullname', 'point', 'public_flag'), 'conditions' => array('AdvisorProfile.id' => $this->Auth->user('id'))));
     $conditions = array('DiscussionBid.delete_flag' => 0, 'OR' => array('DiscussionBid.complete_flag' => 1, 'DiscussionBid.order_flag' => array(3, 6)));
     $dateNow = date('Y-m-d');
     $this->Paginator->settings = array('fields' => array('DiscussionBid.rating', 'DiscussionBid.advisor_interview_id', 'DiscussionBid.complete_flag', 'DiscussionBid.discussion_id', 'DiscussionBid.advisor_bid_money', 'DiscussionBid.order_flag', 'AdvisorReview.id'), 'limit' => 20, 'contain' => array('Discussion' => array('fields' => 'title', 'delivery_date', 'complete_date', 'amount', 'business_field_id', 'id', 'complete_flag', 'user_id', 'BusinessField' => array('conditions' => 'Discussion.business_field_id = BusinessField.id', 'fields' => array('BusinessField.field_name', 'BusinessField.id')), 'UserProfile' => array('conditions' => 'Discussion.user_id = UserProfile.id', 'fields' => array('UserProfile.fullname', 'UserProfile.id', 'UserProfile.public_flag')))), 'joins' => array(array('table' => 'tb_advisor_interviews', 'alias' => 'AdvisorInterview', 'type' => 'INNER', 'conditions' => array('DiscussionBid.advisor_interview_id = AdvisorInterview.id', 'AdvisorInterview.delete_flag = 0', 'AdvisorInterview.advisor_id' => $this->Auth->user('id'))), array('table' => 'tb_advisor_reviews', 'alias' => 'AdvisorReview', 'type' => 'LEFT', 'conditions' => array('AdvisorReview.discussion_id = DiscussionBid.discussion_id', 'AdvisorReview.advisor_interview_id = DiscussionBid.advisor_interview_id', 'AdvisorReview.user_id = Discussion.user_id', 'AdvisorReview.review_direction_flag' => 1))), 'conditions' => $conditions);
     $discussionBids = $this->Paginator->paginate('DiscussionBid');
     $userProfileIds = Hash::extract($discussionBids, '{n}.Discussion.UserProfile.id');
     $userNames = $this->User->find('list', array('fields' => array('username'), 'conditions' => array('User.id' => $userProfileIds)));
     $discussionIds = Set::classicExtract($discussionBids, '{n}.Discussion.id');
     $countUnopenedAnwsers = $this->DiscussionAnswer->find('all', array('joins' => array(array('table' => 'tb_advisor_interviews', 'alias' => 'AdvisorInterview', 'type' => 'INNER', 'conditions' => array('DiscussionAnswer.advisor_interview_id = AdvisorInterview.id', 'AdvisorInterview.delete_flag = 0', 'AdvisorInterview.advisor_id' => $this->Auth->user('id')))), 'contain' => array('DiscussionBid.order_flag'), 'conditions' => array('DiscussionAnswer.discussion_id' => $discussionIds, 'DiscussionAnswer.opened_flag' => 0, 'DiscussionAnswer.direction_flag' => 0, 'DiscussionBid.order_flag' => 1), 'fields' => array('DiscussionAnswer.discussion_id', 'COUNT(DiscussionAnswer.id) AS count_unopened'), 'group' => array('DiscussionAnswer.discussion_id'), 'recursive' => -1));
     $countUnopenedAnwsers = Set::combine($countUnopenedAnwsers, '{n}.DiscussionAnswer.discussion_id', '{n}.0.count_unopened');
     $this->set(compact('discussionBids', 'advisorProfile', 'countUnopenedAnwsers', 'userNames'));
 }
 function admin_index()
 {
     $model = 'Mapa';
     $this->set('model', $model);
     $empresas = $this->Empresa->find('list', array('fields' => array('id', 'empresa'), 'conditions' => array('ativo' => 1)));
     $this->set('empresas', $empresas);
     $estado = $this->Estado->find('list', array('fields' => array('uf')));
     $cidade = $this->Cidade->find('list', array('fields' => array('nome')));
     $this->set(array('cidades' => $cidade, 'estados' => $estado));
     ///++++=====>>>> AREA DE BUSCA
     ///====================================================================
     ///====================================================================
     /// Variáveis alocadas:
     $array_conditions = array();
     ///====================================================================
     /// ==> Find dos registros da categoria selecionada
     if (!empty($this->request->data['filtro']['Empresas'])) {
         $ids_empresas = '';
         foreach ($this->request->data['filtro']['Empresas'] as $r) {
             $ids_empresas = $ids_empresas . $r . ',';
         }
         $sql_manifestacao_id = "SELECT DISTINCT Mapa.id\n\t\t\t\t\t\t\t\tFROM tb_manifestacao as Mapa\n\t\t\t\t\t\t\t\tINNER JOIN\n\t\t\t\t\t\t\t\ttb_manifestacao_empresa as ME ON (ME.manifestacao_id=Mapa.id)\n\t\t\t\t\t\t\t\tINNER JOIN\n\t\t\t\t\t\t\t\ttb_empresas as Empresa ON (ME.empresa_id=Empresa.id) WHERE Empresa.id IN (" . substr_replace($ids_empresas, '', -1, 1) . ")";
         $mapas = $this->{$model}->query($sql_manifestacao_id);
         //////============>>>
         //Desmontar Array
         $manifestacoes_ids = Set::classicExtract($mapas, '{n}.Mapa.id');
         /////////////////
         array_push($array_conditions, array('Mapa.id' => $manifestacoes_ids));
     }
     /// ==> Find dos campo de busca
     if (!empty($this->request->data['filtro']['busca'])) {
         array_push($array_conditions, array('OR' => array('Mapa.local like "%' . $this->request->data['filtro']['busca'] . '%" ', 'Mapa.ponto_partida like "%' . $this->request->data['filtro']['busca'] . '%" ', 'Mapa.ponto_termino like "%' . $this->request->data['filtro']['busca'] . '%" ', 'Mapa.horario like "%' . $this->request->data['filtro']['busca'] . '%" ', 'Mapa.total_manifestantes like "%' . $this->request->data['filtro']['busca'] . '%" ', 'Mapa.txt_impacto like "%' . $this->request->data['filtro']['busca'] . '%" ')));
     }
     /// ==> Find dos campo de busca
     if (!empty($this->request->data['filtro']['estado_id'])) {
         array_push($array_conditions, array('Mapa.estado_id' => $this->request->data['filtro']['estado_id'], 'Mapa.cidade_id' => $this->request->data['filtro']['cidade_id']));
     }
     /// Verifica se existe algo na busca
     if (!empty($array_conditions)) {
         //echo 'aqui';
         //print_r($array_conditions);
         $this->paginate['conditions'] = $array_conditions;
     }
     ///====================================================================
     ///====================================================================
     $this->set('manifestacoes', $this->paginate($model));
 }
 public function find($type = 'first', $params = array())
 {
     $ret = null;
     if (!CakeSession::check('TempItems')) {
         return false;
     }
     $ret = CakeSession::read('TempItems');
     if (isset($params['conditions'])) {
         if (isset($params['conditions']['id'])) {
             $id = $params['conditions']['id'];
             if ($id == 0) {
                 $ret = Set::classicExtract($ret, "{$id}");
             } else {
                 $ret = array(Set::classicExtract($ret, "{$id}"));
             }
         }
     }
     if (isset($params['order'])) {
         if ($params['order'] == 'DESC') {
             $ret = array_reverse($ret);
         }
     }
     if ($ret == null) {
         return false;
     }
     switch ($type) {
         case 'first':
             return $ret[0];
             break;
         case 'all':
             return $ret;
             break;
         case 'list':
             $ret2 = array();
             // debug($ret);
             foreach ($ret as $key => $val) {
                 $ret2[$key] = isset($val['tytul']) ? $val['tytul'] : '[Nowy wskaźnik]';
             }
             return $ret2;
             break;
         case 'count':
             return count($ret);
             break;
     }
     return false;
 }
 function admin_index($categoria_id = null)
 {
     $model = 'Conteudo';
     $this->set('model', $model);
     $this->set('categoria_id', $categoria_id);
     /// ==> Lista das Categorias existentes
     $categorias = $this->Categoria->find('list', array('fields' => array('id', 'categoria')));
     $setores = $this->Setor->find('list', array('fields' => array('id', 'setor'), 'conditions' => array('ativo' => 1)));
     $this->set(array('categorias' => $categorias, 'setores' => $setores));
     //print_r($this->request->data);
     ///++++=====>>>> AREA DE BUSCA
     ///====================================================================
     ///====================================================================
     /// Variáveis alocadas:
     $array_conditions = array();
     ///====================================================================
     /// ==> Find dos registros de empresas selecionada
     if (!empty($this->request->data['filtro']['Setores'])) {
         $ids_setores = '';
         foreach ($this->request->data['filtro']['Setores'] as $r) {
             $ids_setores = $ids_setores . $r . ',';
         }
         $sql_conteudo_id = "SELECT DISTINCT Conteudo.id\n\t\t\t\t\t\t\t\tFROM tb_conteudo as Conteudo\n\t\t\t\t\t\t\t\tINNER JOIN\n\t\t\t\t\t\t\t\ttb_conteudo_setores as CE ON (CE.conteudo_id=Conteudo.id)\n\t\t\t\t\t\t\t\tINNER JOIN\n\t\t\t\t\t\t\t\ttb_setores as Setor ON (CE.setor_id=Setor.id) WHERE Setor.id IN (" . substr_replace($ids_setores, '', -1, 1) . ")";
         $conteudos = $this->{$model}->query($sql_conteudo_id);
         //////============>>>
         //Desmontar Array
         $conteudo_id = Set::classicExtract($conteudos, '{n}.Conteudo.id');
         /////////////////
         array_push($array_conditions, array('Conteudo.id' => $conteudo_id));
     }
     /// ==> Find dos registros da categoria selecionada
     if (!empty($this->request->data['filtro']['categorias'])) {
         array_push($array_conditions, array('Conteudo.categoria_id' => $this->request->data['filtro']['categorias']));
     }
     /// ==> Find dos campo de busca
     if (!empty($this->request->data['filtro']['busca'])) {
         array_push($array_conditions, array('OR' => array('Conteudo.titulo like "%' . $this->request->data['filtro']['busca'] . '%" ', 'Conteudo.texto like "%' . $this->request->data['filtro']['busca'] . '%" ')));
     }
     /// Verifica se existe algo na busca
     if (!empty($array_conditions)) {
         $this->paginate['conditions'] = $array_conditions;
     }
     ///====================================================================
     ///====================================================================
     $this->set('conteudos', $this->paginate($model));
 }
 function search($search)
 {
     $tutorial_ids = array();
     $new_search = true;
     foreach ($this->allowedSearches as $key => $allowed) {
         $tutorial_id_results = array();
         if (array_key_exists($key, $search)) {
             if ($allowed['type'] == 'intArray') {
                 $association_ids = explode('|', $search[$key]);
                 $association_ids = array_filter($association_ids, 'is_numeric');
                 if (!empty($association_ids)) {
                     $associatedModel = $this->hasAndBelongsToMany[Inflector::camelize($key)];
                     $joinModel = $associatedModel['with'];
                     $foreign_key = $associatedModel['foreignKey'];
                     $association_foreign_key = $associatedModel['associationForeignKey'];
                     $search_results = $this->{$joinModel}->find('all', array('fields' => array($foreign_key), 'group' => $foreign_key . ' HAVING count(DISTINCT ' . $association_foreign_key . ') = ' . count($association_ids), 'conditions' => array($key . '_id IN (' . join(',', $association_ids) . ')')));
                     $tutorial_id_results = Set::classicExtract($search_results, "{n}.{$joinModel}.{$foreign_key}");
                 }
             } elseif ($allowed['type'] == 'text') {
                 $text = Sanitize::paranoid($search[$key], array(' '));
                 $individual_terms = explode(' ', $text);
                 $term_results = array();
                 $first_term = true;
                 foreach ($individual_terms as $term) {
                     $search_results = $this->find('all', array('fields' => array('id'), 'conditions' => array('or' => array('title LIKE ' => '% ' . $term . ' %', 'description LIKE ' => '% ' . $term . ' %'))));
                     $tag_search_results = $this->Tag->find('all', array('fields' => array('id', 'name'), 'conditions' => array('name LIKE' => '% ' . $term . ' %'), 'contain' => array('Tagged' => array('conditions' => array('model' => 'Tutorial')))));
                     $term_results = array_unique(array_merge(Set::extract("/Tutorial/id", $search_results), Set::extract("/Tagged/foreign_key", $tag_search_results)));
                     if ($first_term) {
                         $tutorial_id_results = $term_results;
                         $first_term = false;
                     } else {
                         $tutorial_id_results = array_intersect($tutorial_id_results, $term_results);
                     }
                 }
             }
             if ($new_search) {
                 $tutorial_ids = $tutorial_id_results;
                 $new_search = false;
             } else {
                 $tutorial_ids = array_intersect($tutorial_ids, $tutorial_id_results);
             }
         }
     }
     return $tutorial_ids;
 }
Exemple #17
0
 public function home()
 {
     $total = $this->User->query("SELECT SUM(amount) as total FROM expenses WHERE house_id='" . $this->Session->read("Auth.User.House") . "' AND user_id='" . $this->Session->read("Auth.User.id") . "' AND active=1");
     App::import('Model', 'Expense');
     $mExpense = new Expense();
     $expenses_id = $mExpense->query("SELECT expense_id FROM expenses_users WHERE user_id='" . $this->Session->read("Auth.User.id") . "'");
     $expenses_id = Set::classicExtract($expenses_id, '{n}.expenses_users.expense_id');
     $yourExpenses = $mExpense->find('all', array('conditions' => array('Expense.id' => $expenses_id, 'Expense.house_id' => $this->Session->read('Auth.User.House'), 'Expense.active' => 1)));
     $myTotal = 0.0;
     foreach ($yourExpenses as $expense) {
         $myTotal += $expense['Expense']['amount'] / count($expense['Perro']);
     }
     $totalP = $this->User->query("SELECT SUM(amount) as total FROM loans WHERE lender_id='" . $this->Session->read("Auth.User.id") . "' AND active=1");
     $total2P = $this->User->query("SELECT SUM(amount) as total FROM loans WHERE borrower_id='" . $this->Session->read("Auth.User.id") . "' AND active=1");
     $totalPaymentsP = $this->User->query("SELECT SUM(payments.amount) as total FROM payments, loans WHERE loans.id=payments.loan_id AND loans.lender_id='" . $this->Session->read("Auth.User.id") . "' AND loans.active=1 AND payments.active=1");
     $totalPayments2P = $this->User->query("SELECT SUM(payments.amount) as total FROM payments, loans WHERE loans.id=payments.loan_id AND loans.borrower_id='" . $this->Session->read("Auth.User.id") . "' AND loans.active=1 AND payments.active=1");
     $this->set(array('total' => $total[0][0]['total'], 'myTotal' => $myTotal, 'totalP' => $totalP['0']['0']['total'], 'total2P' => $total2P['0']['0']['total'], 'totalPaymentsP' => $totalPaymentsP['0']['0']['total'], 'totalPayments2P' => $totalPayments2P['0']['0']['total']));
 }
 function _getAvailGenreCourses($curuser)
 {
     if (empty($curuser['Genre']) && !empty($curuser['Contact']['Genre'])) {
         $curuser['Genre'] = $curuser['Contact']['Genre'];
     }
     if ($curuser['User']['group_id'] == 1) {
         $mygenres = $this->Genre->find('list', array('fields' => array('Genre.id')));
         $companycourses = $this->find('list', array('fields' => array('Course.id')));
     } else {
         $mygenres = Set::classicExtract($curuser['Genre'], "{n}.id");
         $companycourses = $this->find('list', array('fields' => array('Course.id'), 'conditions' => array('Course.company_id' => array($curuser['Contact']['company_id'], 0))));
     }
     $genres = $this->Genre->find('all', array('conditions' => array('Genre.id' => $mygenres), 'order' => 'Genre.display_order ASC', 'contain' => array('Course' => array('Depend'))));
     $completecourses = $this->TakenCourse->find('list', array('fields' => array('TakenCourse.course_id'), 'conditions' => array('TakenCourse.is_complete' => '1', 'TakenCourse.user_id' => $curuser['User']['id'])));
     // get company courses as well
     if (!empty($genres)) {
         foreach ($genres as $gid => $genre) {
             // loop through courses - make sure they match company courses
             foreach ($genre['Course'] as $cid => $course) {
                 if (!in_array($course['id'], $companycourses) || !$course['is_live']) {
                     unset($genres[$gid]['Course'][$cid]);
                 } else {
                     if (!empty($course['Depend'])) {
                         foreach ($course['Depend'] as $depend) {
                             if (!in_array($depend['id'], $completecourses)) {
                                 //Course should not show up because a dependent course has not been completed
                                 unset($genres[$gid]['Course'][$cid]);
                                 break;
                             }
                         }
                         if (!isset($genres[$gid]['Course'][$cid])) {
                             continue;
                         }
                         if (intval(strtotime($course['available'])) > time()) {
                             unset($genres[$gid]['Course'][$cid]);
                         }
                     }
                 }
             }
         }
     }
     return $genres;
 }
Exemple #19
0
 public function formatDateFields($results, $dates, $format = "%d/%m/%Y")
 {
     if (!empty($dates)) {
         $setResult = function ($val, $key) use(&$results, $format) {
             $innerKey = explode("/", $key);
             $results[$innerKey[0]][$innerKey[1]][$innerKey[2]] = CakeTime::format($val, $format);
         };
         $extracted = Set::extract($results, "/{$this->alias}");
         $dateExtracted = Set::classicExtract($extracted, '{\\w+}.{\\w+}.{' . implode("|", $dates) . '}');
         $applied = Set::apply("/", $dateExtracted, function ($val) {
             return count(Set::filter($val)) > 0 ? $val : null;
         });
         if ($applied) {
             $flatten = Set::flatten($applied, "/");
             array_walk($flatten, $setResult);
         }
     }
     return $results;
 }
 /**
  * Front Incentive search page without login
  *
  * @return void
  * @access public
  */
 public function citybypostal()
 {
     if (!empty($this->request->query['q'])) {
         $enteredPostal = $this->request->query['q'];
         $cities = array('id' => '', 'postal' => $enteredPostal, 'city' => '', 'state' => '');
         $this->loadModel('City');
         //$this->City->virtualFields = array('name' => 'CONCAT(City.city, ", ", City.state)');
         $response = array('flage' => false);
         $cities = $this->City->find('all', array('order' => 'City.postal ASC', 'fields' => array('City.id', 'City.city', 'City.state', 'City.state_id', 'City.postal'), "conditions" => array("City.postal like" => substr($enteredPostal, 0, 5) . "%")));
         if ($cities) {
             $citiesList = Set::classicExtract($cities, '{n}.City');
         }
         if ($this->request->query['callback'] == 'RaiseForMe_CallBackSearch') {
             $citiesList[] = array('id' => 'custom', 'name' => 'Search for ' . $enteredPostal, 'keywords' => $enteredPostal, 'postal' => $enteredPostal, 'city' => '', 'state' => '', 'state_id' => '');
         } else {
             $citiesList[] = array('id' => 'custom', 'name' => 'Use My entry ' . $enteredPostal, 'postal' => $enteredPostal, 'city' => '', 'state' => '', 'state_id' => '');
         }
     }
     echo json_encode($citiesList, true);
     exit;
 }
 /**
  * Fetch products, meant to be called via js
  * Creates simple id, title, stock 
  *
  * @param int $page Page number
  * @param int $limit How many records. Max is 250.
  *
  * @return void
  **/
 function get($page = 1, $limit = 20)
 {
     $products = $this->Shopify->product->get(0, 0, array('page' => $page, 'limit' => $limit));
     $output = array('Results' => array());
     foreach ($products as $product) {
         //Get the stock level - if there's an [variant][0], then there's more than one
         if (isset($product['variants']['variant'][0])) {
             //Extract it
             $stockLevels = Set::classicExtract($product['variants']['variant'], '{n}.inventory-quantity');
             $stock = array_sum($stockLevels);
         } else {
             $stock = $product['variants']['variant']['inventory-quantity'];
         }
         $p = array('id' => $product['id'], 'title' => $product['title'], 'stock' => $stock);
         $output['Results'][] = $p;
     }
     $output['Total'] = count($output['Results']);
     $output['Page'] = $page;
     $output['Limit'] = $limit;
     $this->set('output', $output);
 }
 /**
  * index method
  *
  * @return void
  */
 public function index()
 {
     $this->loadModel('User');
     $this->loadModel('Wallet');
     $this->loadModel('Transaction');
     $this->loadModel('Category');
     $id_auth = $this->Auth->user('id');
     $findAllCategories = $this->Transaction->findAllCategory();
     $result_categorie_id = Set::classicExtract($findAllCategories, '{n}.Categorie.id');
     $findWallet = $this->User->findWalletAuth($id_auth);
     $result_wallet_id = Set::classicExtract($findWallet, '{n}.wallets.id');
     $year = $this->request->query('year_start');
     $wallets = $this->Transaction->findIdWalletAuth($result_wallet_id);
     if (!empty($wallets)) {
         $categories = $this->Transaction->findIdCategory($result_categorie_id);
         $this->set(compact('categories', 'wallets', 'transactions'));
         $this->set('showLayoutContent', true);
         $groupByCategories = $this->Transaction->getMoneyGroupByCategories($result_wallet_id, $result_categorie_id);
         $transactions = $this->Transaction->findAllTransactionsAuth($result_wallet_id);
         $outputMonthTransactions = array();
         $i = 0;
         if (!empty($transactions)) {
             foreach ($transactions as $key => $transaction) {
                 if (!isset($outputMonthTransactions[$i])) {
                     if (!empty($year)) {
                         $outputMonthTransactions[$i] = date($year . '-m', strtotime($transaction['Transaction']['day_transaction']));
                     } else {
                         $outputMonthTransactions[$i] = date('Y-m', strtotime($transaction['Transaction']['day_transaction']));
                     }
                 }
                 $i++;
             }
             $months = array_unique($outputMonthTransactions);
             rsort($months);
             $this->set('months', $months);
             $this->set('pieData', $this->Transaction->getReportFollowType($result_wallet_id));
             $this->set('pieDataCategories', $this->Transaction->getReportFollowCategories($result_wallet_id));
         }
     }
 }
 public function printable($type, $hash = false)
 {
     $this->layout = "canteen_printer";
     if ($hash) {
         $this->loadModel("CanteenOrder");
         $o = $this->CanteenOrder->find("first", array("contain" => array(), "conditions" => array("CanteenOrder.hash" => $hash)));
         $order = $this->CanteenOrder->returnAdminOrder(Set::classicExtract($o, "CanteenOrder.id"));
         if (isset($order['CanteenOrder']['id'])) {
             $this->set(compact("order"));
         } else {
             throw new NotFoundException();
         }
     } else {
         throw new NotFoundException();
     }
     switch ($type) {
         case "receipt":
         default:
             $ele = "order-receipt";
             break;
     }
     $this->render("/elements/canteen_printing/{$ele}");
 }
Exemple #24
0
 function generateRelated($data)
 {
     #pr($data);
     $terms = null;
     if (isset($data['Term']['Term'])) {
         $terms = Set::classicExtract($data['Term']['Term'], "{n}.id");
     } else {
         if (isset($data['Term']) && !empty($data['Term']) && is_array($data['Term'])) {
             $terms = Set::classicExtract($data['Term'], "{n}.id");
         }
     }
     if (empty($terms)) {
         $terms = 0;
     } else {
         $terms = sprintf("count(DISTINCT IF( `Term`.`term_id` IN (%s), `Term`.`term_id`, NULL )) * 1", implode($terms, ","));
     }
     # Se obtienen todas las palabras con mas de 4 caracters del articulo
     $data['Article']['contenido'] = isset($data['Article']['contenido']) ? $data['Article']['contenido'] : $data['Article']['contenido_es_mx'];
     preg_match_all('/[a-zA-Z]{4,}/', strip_tags($data['Article']['contenido']), $words);
     $data['Article']['titulo'] = isset($data['Article']['titulo']) ? $data['Article']['titulo'] : $data['Article']['titulo_es_mx'];
     $matchTitulo = "(MATCH (Article.titulo) AGAINST ('" . $data['Article']['titulo'] . "')) * 1";
     $matchContenido = sprintf("(MATCH (Article.contenido) AGAINST ('%s')) * 1", implode($words[0], " "));
     if (!isset($data['Article']['id'])) {
         $data['Article']['id'] = $this->id;
     }
     # se obtienen todos los articulos
     $related = $this->find("all", array('fields' => array('Article.id', "ROUND(0 + {$matchTitulo} + {$matchContenido} + {$terms},2) AS score"), 'joins' => array(array('type' => 'left', 'table' => 'articles_terms', 'alias' => 'Term', 'conditions' => array('Term.article_id = Article.id'))), 'conditions' => array('Article.status' => 1, 'Article.id <>' => $data['Article']['id']), 'group' => 'Article.id HAVING score >= 50.0', 'order' => array('score DESC'), 'limit' => 10));
     if (!empty($related)) {
         $query = "REPLACE INTO article_relationships (article_id,related_id,score) VALUES ";
         foreach ($related as $r) {
             $query .= "({$data['Article']['id']},{$r['Article']['id']},{$r[0]['score']}),";
         }
         $query = substr($query, 0, -1);
         #pr($query);
         $this->query($query);
     }
 }
 public function afterFind($results, $primary = false)
 {
     array_walk($results, function ($val, $key) use(&$results) {
         if (!isset($results[$key][$this->alias])) {
             return;
         }
         $dtRecebimento = new DateTime($val['AcionamentoCampo_Aberta']['dt_rec_ticket'] . ' ' . $val['AcionamentoCampo_Aberta']['hr_rec_ticket']);
         $dtVencimento = $this->calculaPrazoSLA($val, $dtRecebimento);
         if (!$dtVencimento) {
             return;
         }
         $diffDias = -$dtVencimento->diff(new DateTime('now'), false)->format('%R%a');
         $results[$key][$this->alias]['dt_vencimento'] = $dtVencimento->format('Y-m-d H:i:s');
         $prazos = array_values(Set::classicExtract($results, '{\\w+}.{\\w+}.{' . implode("|", ['aviso1', 'aviso2', 'aviso3']) . '}')[$key]['AcionamentoCampo_Produto']);
         $prazos_classes = ['success', 'warning', 'danger'];
         foreach ($prazos as $innerKey => $prazo) {
             if ($prazo >= $diffDias) {
                 $results[$key][$this->alias]['classe_linha'] = $prazos_classes[$innerKey];
                 $results[$key][$this->alias]['prazo_restante'] = $diffDias;
             }
         }
     });
     return $this->formatDateFields($results, $this->datesToLoad, "%a - %d/%m/%Y");
 }
 /**
  * Render the body of the email.
  *
  * @param string $content Content to render
  * @return array Email body ready to be sent
  */
 protected function _render($content)
 {
     $content = implode("\n", $content);
     $rendered = $this->_renderTemplates($content);
     $msg = array();
     $contentIds = array_filter((array) Set::classicExtract($this->_attachments, '{s}.contentId'));
     $hasInlineAttachments = count($contentIds) > 0;
     $hasAttachments = !empty($this->_attachments);
     $hasMultipleTypes = count($rendered) > 1;
     $boundary = $relBoundary = $textBoundary = $this->_boundary;
     if ($hasInlineAttachments) {
         $msg[] = '--' . $boundary;
         $msg[] = 'Content-Type: multipart/related; boundary="rel-' . $boundary . '"';
         $msg[] = '';
         $relBoundary = $textBoundary = 'rel-' . $boundary;
     }
     if ($hasMultipleTypes) {
         $msg[] = '--' . $relBoundary;
         $msg[] = 'Content-Type: multipart/alternative; boundary="alt-' . $boundary . '"';
         $msg[] = '';
         $textBoundary = 'alt-' . $boundary;
     }
     if (isset($rendered['text'])) {
         if ($textBoundary !== $boundary || $hasAttachments) {
             $msg[] = '--' . $textBoundary;
             $msg[] = 'Content-Type: text/plain; charset=' . $this->charset;
             $msg[] = 'Content-Transfer-Encoding: ' . $this->_getContentTransferEncoding();
             $msg[] = '';
         }
         $this->_textMessage = $rendered['text'];
         $content = explode("\n", $this->_textMessage);
         $msg = array_merge($msg, $content);
         $msg[] = '';
     }
     if (isset($rendered['html'])) {
         if ($textBoundary !== $boundary || $hasAttachments) {
             $msg[] = '--' . $textBoundary;
             $msg[] = 'Content-Type: text/html; charset=' . $this->charset;
             $msg[] = 'Content-Transfer-Encoding: ' . $this->_getContentTransferEncoding();
             $msg[] = '';
         }
         $this->_htmlMessage = $rendered['html'];
         $content = explode("\n", $this->_htmlMessage);
         $msg = array_merge($msg, $content);
         $msg[] = '';
     }
     if ($hasMultipleTypes) {
         $msg[] = '--' . $textBoundary . '--';
         $msg[] = '';
     }
     if ($hasInlineAttachments) {
         $attachments = $this->_attachInlineFiles($relBoundary);
         $msg = array_merge($msg, $attachments);
         $msg[] = '';
         $msg[] = '--' . $relBoundary . '--';
         $msg[] = '';
     }
     if ($hasAttachments) {
         $attachments = $this->_attachFiles($boundary);
         $msg = array_merge($msg, $attachments);
     }
     if ($hasAttachments || $hasMultipleTypes) {
         $msg[] = '';
         $msg[] = '--' . $boundary . '--';
         $msg[] = '';
     }
     return $msg;
 }
Exemple #27
0
 /**
  * test classicExtract with keys that exceed 32bit max int.
  *
  * @return void
  */
 public function testClassicExtractMaxInt()
 {
     $data = array('Data' => array('13376924712' => 'abc'));
     $this->assertEquals('abc', Set::classicExtract($data, 'Data.13376924712'));
 }
 /**
  * Writes value to given session variable name.
  *
  * @param mixed $name Name of variable
  * @param string $value Value to write
  * @return boolean True if the write was successful, false if the write failed
  * @access public
  */
 public function write($name, $value)
 {
     if (empty($name)) {
         return false;
     }
     if (in_array($name, $this->watchKeys)) {
         trigger_error(sprintf(__('Writing session key {%s}: %s', true), $name, Debugger::exportVar($value)), E_USER_NOTICE);
     }
     $this->__overwrite($_SESSION, Set::insert($_SESSION, $name, $value));
     return Set::classicExtract($_SESSION, $name) === $value;
 }
 /**
  * Provides a read/write accessor for `$this->data`.  Allows you
  * to use a syntax similar to `CakeSession` for reading post data.
  *
  * ## Reading values.
  *
  * `$request->data('Post.title');`
  *
  * When reading values you will get `null` for keys/values that do not exist.
  *
  * ## Writing values
  *
  * `$request->data('Post.title', 'New post!');`
  *
  * You can write to any value, even paths/keys that do not exist, and the arrays
  * will be created for you.
  *
  * @param string $name,... Dot separated name of the value to read/write
  * @return mixed Either the value being read, or this so you can chain consecutive writes.
  */
 public function data($name)
 {
     $args = func_get_args();
     if (count($args) == 2) {
         $this->data = Set::insert($this->data, $name, $args[1]);
         return $this;
     }
     return Set::classicExtract($this->data, $name);
 }
 protected function _existingResponse()
 {
     $response_id = $this->Session->read('response');
     $response = $response_id ? $this->Response->find('first', array('conditions' => array('Response.id' => $response_id), 'contain' => array('ResponseStatement' => array('fields' => array('id', 'weighting', 'response_id', 'statement_id'), 'order' => 'ResponseStatement.id ASC', 'Category' => array('fields' => array('id', 'name'))), 'Condition' => array('fields' => array('id')), 'User' => array('fields' => array('id', 'email')), 'NetworkMember' => array('fields' => array('id', 'name', 'frequency', 'network_category_id', 'diagram_x', 'diagram_y', 'other'), 'NetworkCategory' => array('fields' => array('id', 'name', 'parent_id')))))) : false;
     // Process ResponseStatements so that they are indexed by Statement ID (VITAL FOR VIEW FUNCTIONALITY)
     if ($response && !empty($response['ResponseStatement'])) {
         $response['ResponseStatement'] = Set::combine($response['ResponseStatement'], '{n}.statement_id', '{n}');
         // Switch category key to IDs only (FormHelper fails otherwise)
         foreach ($response['ResponseStatement'] as &$responseStatement) {
             if (!empty($responseStatement['Category'])) {
                 $responseStatement['Category'] = Set::classicExtract($responseStatement['Category'], '{n}.id');
             }
         }
     }
     // Done
     return $response;
 }