/**
  * checkPage
  *
  * @param array $questionnaire questionnaire
  * @return array error message
  */
 public function checkPage($questionnaire)
 {
     $this->QuestionnairePage = ClassRegistry::init('Questionnaires.QuestionnairePage', true);
     // 少なくとも1ページは存在すること
     if (empty($questionnaire['QuestionnairePage'])) {
         $this->validationErrors['Questionnaire'][] = __d('questionnaires', 'please set at least one page.');
         return false;
     }
     $pageSeq = 0;
     foreach ($questionnaire['QuestionnairePage'] as $pageIndex => $page) {
         // それぞれのページのフィールド確認
         $this->QuestionnairePage->set($page);
         $this->QuestionnairePage->validates(array('fieldList' => array('questionnaire_id', 'page_title', 'page_sequence', 'route_number')));
         if ($this->QuestionnairePage->validationErrors) {
             $this->validationErrors['QuestionnairePage'][$pageIndex] = $this->QuestionnairePage->validationErrors;
         }
         // ページシーケンスが0始まりで連番になっているか
         if ($pageSeq != $page['page_sequence']) {
             $this->validationErrors['QuestionnairePage'][$pageIndex][] = __d('questionnaires', 'Invalid page sequence set. Please try again from the beginning.');
             return false;
         }
         // ページの中の質問についてチェック
         $this->checkQuestion($questionnaire, $page, $this->validationErrors['QuestionnairePage'][$pageIndex]);
         $pageSeq++;
     }
     $this->validationErrors = Hash::filter($this->validationErrors);
     if (!empty($this->validationErrors)) {
         return false;
     } else {
         return true;
     }
 }
 public function initialize(Controller $Controller)
 {
     parent::initialize($Controller);
     if (!self::_isSiftable($Controller)) {
         return;
     }
     if (empty($Controller->request->data['Sifter'])) {
         if (empty($Controller->request->params['named'])) {
             return true;
         }
         $Controller->request->params['named'] = Hash::expand($Controller->request->params['named']);
         return self::_sift($Controller);
     }
     $Model = $Controller->{$Controller->modelClass};
     $field = array_filter((array) $Model->sifterConfig('fields'));
     if (self::_isAjax($Controller)) {
         if (!array_key_exists($Controller->request->data['Sifter']['search_field'], $field) || empty($Controller->request->data['Sifter']['search_value'])) {
             return true;
         }
         return self::_setAutoComplete($Controller, array($Controller->request->data['Sifter']['search_field'] => $field[$Controller->request->data['Sifter']['search_field']]));
     } elseif ($Controller->request->is('post')) {
         unset($Controller->request->data['Sifter']);
         $url = array();
         foreach (Hash::filter($Controller->request->data) as $model => $fields) {
             foreach ($fields as $field => $data) {
                 $url[$model . '.' . $field] = $data;
             }
         }
         return $Controller->redirect(Hash::merge($url, array_diff_key($Controller->request->params, array('plugin' => null, 'controller' => null, 'action' => null, 'named' => null, 'pass' => null))));
     }
 }
 /**
  * Delete-insert circular notice choices
  *
  * @param array $data input data
  * @return bool
  * @throws InternalErrorException
  */
 public function replaceCircularNoticeChoices($data)
 {
     $contentId = $data['CircularNoticeContent']['id'];
     // 残す選択肢の条件を生成
     $deleteConditions = array('CircularNoticeChoice.circular_notice_content_id' => $contentId);
     $extractIds = Hash::filter(Hash::extract($data['CircularNoticeChoices'], '{n}.CircularNoticeChoice.id'));
     if (count($extractIds) > 0) {
         $deleteConditions['CircularNoticeChoice.id NOT'] = $extractIds;
     }
     // 選択肢を一旦削除
     if (!$this->deleteAll($deleteConditions, false)) {
         throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
     }
     // 1件ずつ保存
     foreach ($data['CircularNoticeChoices'] as $choice) {
         $choice['CircularNoticeChoice']['circular_notice_content_id'] = $contentId;
         if (!$this->validateCircularChoice($choice)) {
             return false;
         }
         if (!$this->save(null, false)) {
             throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
         }
     }
     return true;
 }
 private function prepareData()
 {
     $zeroToNull = function ($val) {
         return $val != 0 ? $val : null;
     };
     $this->request->data['Contatos'] = $this->Session->consume("inserir_ponto_focal.{$this->user['Acesso_Portal_Usuario']['id_usuarios']}");
     $this->request->data['Categorias']['Categorias'] = Hash::filter(array_map($zeroToNull, $this->request->data['Categorias']['Categorias']));
     return $this;
 }
Exemple #5
0
 /**
  * display method
  *
  * @param $page
  * @param $subpage
  * @return void
  */
 public function display($page = null, $subpage = null)
 {
     if (empty($page)) {
         $path = func_get_args();
         $count = count($path);
         if (!$count) {
             $this->redirect('/');
         }
         $page = $subpage = $title_for_layout = null;
         if (!empty($path[0])) {
             $page = $path[0];
         }
         if (!empty($path[1])) {
             $subpage = $path[1];
         }
         if (!empty($path[$count - 1])) {
             $title_for_layout = Inflector::humanize($path[$count - 1]);
         }
     } else {
         $path = Hash::filter(array($page, $subpage));
     }
     switch ($page) {
         case 'home':
             $content = $this->Page->find('first', array('conditions' => array('Page.id' => 4)));
             $this->set(compact('content'));
             // Fetch projects
             //				$projects = $this->Project->find('all');
             //				$this->set(compact('projects'));
             break;
         case 'bio':
             $this->page_data['page_title'][] = __('Biographie');
             $content = $this->Page->find('first', array('conditions' => array('Page.id' => 1)));
             $this->set(compact('content'));
             break;
         case 'about':
             $this->page_data['page_title'][] = __('À propos');
             $content = $this->Page->find('first', array('conditions' => array('Page.id' => 3)));
             $this->set(compact('content'));
             break;
         case 'contact':
             $this->page_data['page_title'][] = __('Contact');
             $content = $this->Page->find('first', array('conditions' => array('Page.id' => 2)));
             $this->set(compact('content'));
             break;
     }
     $this->path = $path;
     $this->set(compact('page', 'subpage', 'title_for_layout'));
     $this->render(implode('/', $path));
 }
 /**
  * Sets this helper's model and field properties to the dot-separated value-pair in $entity.
  *
  * @param string $entity A field name, like "ModelName.fieldName" or "ModelName.ID.fieldName"
  * @param boolean $setScope Sets the view scope to the model specified in $tagValue
  * @return void
  */
 public function setEntity($entity, $setScope = false)
 {
     if ($entity === null) {
         $this->_modelScope = false;
     }
     if ($setScope === true) {
         $this->_modelScope = $entity;
     }
     $parts = array_values(Hash::filter(explode('.', $entity)));
     if (empty($parts)) {
         return;
     }
     if ($parts[0] != '_Token') {
         $entity = $this->_modelScope . '.' . $entity;
     }
     $this->_association = null;
     $this->_entityPath = $entity;
 }
 public function cadastrar()
 {
     $this->Acesso_Portal_Perfil->recursive = -1;
     $controllers = $this->Acesso_Portal_Tela->geraListagemController();
     $this->set(compact('controllers'));
     if ($this->request->is(array('post', 'put'))) {
         $zeroToNull = function ($val) {
             return $val != 0 ? $val : null;
         };
         $this->request->data['Telas']['Telas'] = Hash::filter(array_map($zeroToNull, $this->request->data['Telas']['Telas']));
         unset($this->request->data['Base']);
         $this->Acesso_Portal_Perfil->create();
         $data = $this->request->data;
         $this->request->data = "";
         if ($this->Acesso_Portal_Perfil->save($data)) {
             $this->Session->setFlash($this->useLogger('Perfil Cadastrado com Sucesso'));
             return $this->redirect('/perfis/index');
         }
         $errors = $this->Acesso_Portal_Perfil->validationErrors;
         $this->Session->setFlash($this->useLogger($errors));
     }
 }
 public static function getPath($url)
 {
     $parse = parse_url($url);
     $url = $parse['path'];
     $pathSegments = explode('.', $url);
     $ext = array_pop($pathSegments);
     $url = implode('.', $pathSegments);
     $parts = explode('/', $url);
     $parts = Hash::filter($parts);
     $route = Router::parse($url . '/lang:' . Configure::read('Config.language'));
     // Thème
     if (isset($route['controller']) && $route['controller'] === 'theme') {
         $parts = array_merge(array('View', 'Themed', $route['action'], 'webroot'), $route['pass']);
     } elseif (isset($route['plugin']) && $route['plugin'] != '') {
         foreach ($parts as $k => $v) {
             if ($v == $route['plugin']) {
                 unset($parts[$k]);
                 break;
             }
             unset($parts[$k]);
         }
     }
     $endPath = implode(DS, $parts);
     if (isset($route['controller']) && $route['controller'] === 'theme') {
         $basePath = APP;
     } else {
         if (isset($route['plugin']) && $route['plugin'] != '') {
             $basePath = CakePlugin::path(Inflector::camelize($route['plugin'])) . WEBROOT_DIR . DS;
         } else {
             $basePath = APP . WEBROOT_DIR . DS;
         }
     }
     // Remove APP_DIR path
     $basePath = str_replace(APP, '', $basePath);
     return $basePath . $endPath . '.' . $ext;
 }
Exemple #9
0
 /**
  * testFilter method
  *
  * @return void
  */
 public function testFilter()
 {
     $result = Hash::filter(array('0', false, true, 0, array('one thing', 'I can tell you', 'is you got to be', false)));
     $expected = array('0', 2 => true, 3 => 0, 4 => array('one thing', 'I can tell you', 'is you got to be'));
     $this->assertSame($expected, $result);
     $result = Hash::filter(array(1, array(false)));
     $expected = array(1);
     $this->assertEquals($expected, $result);
     $result = Hash::filter(array(1, array(false, false)));
     $expected = array(1);
     $this->assertEquals($expected, $result);
     $result = Hash::filter(array(1, array('empty', false)));
     $expected = array(1, array('empty'));
     $this->assertEquals($expected, $result);
     $result = Hash::filter(array(1, array('2', false, array(3, null))));
     $expected = array(1, array('2', 2 => array(3)));
     $this->assertEquals($expected, $result);
     $this->assertSame(array(), Hash::filter(array()));
 }
Exemple #10
0
 /**
  * Filter handler for Pluck methods - strips out empty values, or anything
  * passed in via $filterCallback
  *
  * See Hash::filter() for more information
  *
  * @param array $data
  * @param mixed $filterCallback
  *     - false  will not run Hash::filter()
  *                removes noting, untouched
  *     - true   will run Hash::filter($data, array('Pluck', '_filterExcludeZero'))
  *                to remove all empties including 0
  *     - null   will run Hash::filter($data)
  *                to remove all empties except 0
  *     - {else} will run Hash::filter($data, $filterCallback)
  *                to remove whatever you tell it to remove
  *                $filterCallback should be: array($className, $methodName)
  * @return array $data
  */
 public static function filter($data, $filterCallback = null)
 {
     if ($filterCallback === false) {
         // not filtering
         return $data;
     }
     if ($filterCallback === true) {
         // custom callback
         // remove all empties AND 0
         return Hash::filter($data, array('Pluck', '_filterExcludeZero'));
     }
     if (empty($filterCallback)) {
         // default Hash::filter()
         // removes all empties EXCEPT 0
         return Hash::filter($data);
     }
     // custom callback
     return Hash::filter($data, $filterCallback);
 }
 /**
  * Parse the `contain` option of the query recursively
  *
  * @param Model $parent Parent model of the contained model
  * @param string $alias Alias of the contained model
  * @param array $contain Reformatted `contain` option for the deep associations
  * @param array|null $context Context
  * @return array
  * @throws InvalidArgumentException
  */
 private function parseContain(Model $parent, $alias, array $contain, $context = null)
 {
     // @codingStandardsIgnoreLine
     if ($context === null) {
         $context = array('root' => $parent->alias, 'aliasPath' => $parent->alias, 'propertyPath' => '', 'forceExternal' => false);
     }
     $aliasPath = $context['aliasPath'] . '.' . $alias;
     $propertyPath = ($context['propertyPath'] ? $context['propertyPath'] . '.' : '') . $alias;
     $types = $parent->getAssociated();
     if (!isset($types[$alias])) {
         throw new InvalidArgumentException(sprintf('Model "%s" is not associated with model "%s"', $parent->alias, $alias), E_USER_WARNING);
     }
     $parentAlias = $parent->alias;
     $target = $parent->{$alias};
     $type = $types[$alias];
     $relation = $parent->{$type}[$alias];
     $options = $contain['options'] + array_intersect_key(Hash::filter($relation), $this->containOptions);
     $has = stripos($type, 'has') !== false;
     $many = stripos($type, 'many') !== false;
     $belong = stripos($type, 'belong') !== false;
     if ($has && $belong) {
         $parentKey = $parent->primaryKey;
         $targetKey = $target->primaryKey;
         $habtmAlias = $relation['with'];
         $habtm = $parent->{$habtmAlias};
         $habtmParentKey = $relation['foreignKey'];
         $habtmTargetKey = $relation['associationForeignKey'];
     } elseif ($has) {
         $parentKey = $parent->primaryKey;
         $targetKey = $relation['foreignKey'];
     } else {
         $parentKey = $relation['foreignKey'];
         $targetKey = $target->primaryKey;
     }
     if (!empty($relation['external'])) {
         $external = true;
     }
     if (!empty($relation['finderQuery'])) {
         $finderQuery = $relation['finderQuery'];
     }
     $meta = compact('alias', 'parent', 'target', 'parentAlias', 'parentKey', 'targetKey', 'aliasPath', 'propertyPath', 'options', 'has', 'many', 'belong', 'external', 'finderQuery', 'habtm', 'habtmAlias', 'habtmParentKey', 'habtmTargetKey');
     if ($this->isExternal($context, $meta)) {
         $meta['external'] = true;
         $context['root'] = $aliasPath;
         $context['propertyPath'] = $alias;
         $path = $context['aliasPath'];
     } else {
         $meta['external'] = false;
         if ($context['root'] !== $context['aliasPath']) {
             $meta['eager'] = true;
         }
         $context['propertyPath'] = $propertyPath;
         $path = $context['root'];
     }
     $this->metas[$path][] = $meta;
     $context['aliasPath'] = $aliasPath;
     $context['forceExternal'] = !empty($finderQuery);
     foreach ($contain['contain'] as $key => $val) {
         $this->parseContain($target, $key, $val, $context);
     }
     return $this->metas;
 }
Exemple #12
0
 /**
  * testFilter method
  *
  * @return void
  */
 public function testFilter()
 {
     $result = Hash::filter(array('0', FALSE, TRUE, 0, array('one thing', 'I can tell you', 'is you got to be', FALSE)));
     $expected = array('0', 2 => TRUE, 3 => 0, 4 => array('one thing', 'I can tell you', 'is you got to be'));
     $this->assertSame($expected, $result);
     $result = Hash::filter(array(1, array(FALSE)));
     $expected = array(1);
     $this->assertEquals($expected, $result);
     $result = Hash::filter(array(1, array(FALSE, FALSE)));
     $expected = array(1);
     $this->assertEquals($expected, $result);
     $result = Hash::filter(array(1, array('empty', FALSE)));
     $expected = array(1, array('empty'));
     $this->assertEquals($expected, $result);
     $result = Hash::filter(array(1, array('2', FALSE, array(3, NULL))));
     $expected = array(1, array('2', 2 => array(3)));
     $this->assertEquals($expected, $result);
     $this->assertSame(array(), Hash::filter(array()));
 }
Exemple #13
0
 public function addLibs($libs, $type = 'css', $prepend = false)
 {
     if (!is_array($libs)) {
         $libs = explode(',', $libs);
         $libs = array_map('trim', $libs);
         $libs = Hash::filter($libs);
     }
     if (empty($libs)) {
         return;
     }
     foreach ($libs as $key => $value) {
         if (is_numeric($value)) {
             $lib = $key;
             $priority = $value;
         } else {
             $lib = $value;
             $priority = 1001;
         }
         if ($this->libExists($lib, $type)) {
             continue;
         }
         while (isset($this->libs[$type]['files'][$priority])) {
             $priority++;
         }
         $this->libs[$type]['files'][$priority] = $lib;
     }
     ksort($this->libs[$type]['files'], SORT_NUMERIC);
 }
Exemple #14
0
 /**
  * Sets this helper's model and field properties to the dot-separated value-pair in $entity.
  *
  * @param string $entity A field name, like "ModelName.fieldName" or "ModelName.ID.fieldName"
  * @param boolean $setScope Sets the view scope to the model specified in $tagValue
  * @return void
  */
 public function setEntity($entity, $setScope = false)
 {
     if ($entity === null) {
         $this->_modelScope = false;
     }
     if ($setScope === true) {
         $this->_modelScope = $entity;
     }
     $parts = array_values(Hash::filter(explode('.', $entity)));
     if (empty($parts)) {
         return;
     }
     $count = count($parts);
     $lastPart = isset($parts[$count - 1]) ? $parts[$count - 1] : null;
     // Either 'body' or 'date.month' type inputs.
     if ($count === 1 && $this->_modelScope && !$setScope || $count === 2 && in_array($lastPart, $this->_fieldSuffixes) && $this->_modelScope && $parts[0] !== $this->_modelScope) {
         $entity = $this->_modelScope . '.' . $entity;
     }
     // 0.name, 0.created.month style inputs. Excludes inputs with the modelScope in them.
     if ($count >= 2 && is_numeric($parts[0]) && !is_numeric($parts[1]) && $this->_modelScope && strpos($entity, $this->_modelScope) === false) {
         $entity = $this->_modelScope . '.' . $entity;
     }
     $this->_association = null;
     $isHabtm = isset($this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type']) && $this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type'] === 'multiple';
     // habtm models are special
     if ($count === 1 && $isHabtm) {
         $this->_association = $parts[0];
         $entity = $parts[0] . '.' . $parts[0];
     } else {
         // check for associated model.
         $reversed = array_reverse($parts);
         foreach ($reversed as $i => $part) {
             if ($i > 0 && preg_match('/^[A-Z]/', $part)) {
                 $this->_association = $part;
                 break;
             }
         }
     }
     $this->_entityPath = $entity;
 }
Exemple #15
0
 /**
  * A special fallback method that handles URL arrays that cannot match
  * any defined routes.
  *
  * @param array $url A URL that didn't match any routes
  * @return string A generated URL for the array
  * @see Router::url()
  */
 protected static function _handleNoRoute($url)
 {
     $named = $args = array();
     $skip = array_merge(array('bare', 'action', 'controller', 'plugin', 'prefix'), self::$_prefixes);
     $keys = array_values(array_diff(array_keys($url), $skip));
     $count = count($keys);
     // Remove this once parsed URL parameters can be inserted into 'pass'
     for ($i = 0; $i < $count; $i++) {
         $key = $keys[$i];
         if (is_numeric($keys[$i])) {
             $args[] = $url[$key];
         } else {
             $named[$key] = $url[$key];
         }
     }
     list($args, $named) = array(Hash::filter($args), Hash::filter($named));
     foreach (self::$_prefixes as $prefix) {
         $prefixed = $prefix . '_';
         if (!empty($url[$prefix]) && strpos($url['action'], $prefixed) === 0) {
             $url['action'] = substr($url['action'], strlen($prefixed) * -1);
             break;
         }
     }
     if (empty($named) && empty($args) && (!isset($url['action']) || $url['action'] === 'index')) {
         $url['action'] = null;
     }
     $urlOut = array_filter(array($url['controller'], $url['action']));
     if (isset($url['plugin'])) {
         array_unshift($urlOut, $url['plugin']);
     }
     foreach (self::$_prefixes as $prefix) {
         if (isset($url[$prefix])) {
             array_unshift($urlOut, $prefix);
             break;
         }
     }
     $output = implode('/', $urlOut);
     if (!empty($args)) {
         $output .= '/' . implode('/', array_map('rawurlencode', $args));
     }
     if (!empty($named)) {
         foreach ($named as $name => $value) {
             if (is_array($value)) {
                 $flattend = Hash::flatten($value, '%5D%5B');
                 foreach ($flattend as $namedKey => $namedValue) {
                     $output .= '/' . $name . "%5B{$namedKey}%5D" . self::$_namedConfig['separator'] . rawurlencode($namedValue);
                 }
             } else {
                 $output .= '/' . $name . self::$_namedConfig['separator'] . rawurlencode($value);
             }
         }
     }
     return $output;
 }
Exemple #16
0
 /**
  * ルーム配信で送らないユーザID ゲット
  *
  * @param string $sendTime メール送信日時
  * @param array $notSendRoomUserIds ルーム配信で送らないユーザID
  * @return string ルーム配信で送らないユーザID
  */
 private function __getNotSendRoomUserIds($sendTime, $notSendRoomUserIds)
 {
     // 未来日送信は2通(承認完了とルーム配信)送るため、送らないユーザIDをセットしない
     $now = NetCommonsTime::getNowDatetime();
     if ($sendTime > $now) {
         return null;
     }
     // 重複登録を排除
     $notSendRoomUserIds = array_unique($notSendRoomUserIds);
     // 空要素を排除
     $notSendRoomUserIds = Hash::filter($notSendRoomUserIds);
     $notSendRoomUserIds = implode('|', $notSendRoomUserIds);
     return $notSendRoomUserIds;
 }
 /**
  * Queries associations.  Used to fetch results on recursive models.
  *
  * @param Model $model Primary Model object
  * @param Model $linkModel Linked model that
  * @param string $type Association type, one of the model association types ie. hasMany
  * @param string $association
  * @param array $assocData
  * @param array $queryData
  * @param boolean $external Whether or not the association query is on an external datasource.
  * @param array $resultSet Existing results
  * @param integer $recursive Number of levels of association
  * @param array $stack
  * @return mixed
  * @throws CakeException when results cannot be created.
  */
 public function queryAssociation(Model $model, &$linkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet, $recursive, $stack)
 {
     if (isset($stack['_joined'])) {
         $joined = $stack['_joined'];
         unset($stack['_joined']);
     }
     if ($query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external, $resultSet)) {
         if (!is_array($resultSet)) {
             throw new CakeException(__d('cake_dev', 'Error in Model %s', get_class($model)));
         }
         if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) {
             $ins = $fetch = array();
             foreach ($resultSet as &$result) {
                 if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) {
                     $ins[] = $in;
                 }
             }
             if (!empty($ins)) {
                 $ins = array_unique($ins);
                 $fetch = $this->fetchAssociated($model, $query, $ins);
             }
             if (!empty($fetch) && is_array($fetch)) {
                 if ($recursive > 0) {
                     foreach ($linkModel->associations() as $type1) {
                         foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
                             $deepModel = $linkModel->{$assoc1};
                             $tmpStack = $stack;
                             $tmpStack[] = $assoc1;
                             if ($linkModel->useDbConfig === $deepModel->useDbConfig) {
                                 $db = $this;
                             } else {
                                 $db = ConnectionManager::getDataSource($deepModel->useDbConfig);
                             }
                             $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
                         }
                     }
                 }
             }
             if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
                 $this->_filterResults($fetch, $model);
             }
             return $this->_mergeHasMany($resultSet, $fetch, $association, $model, $linkModel);
         } elseif ($type === 'hasAndBelongsToMany') {
             $ins = $fetch = array();
             foreach ($resultSet as &$result) {
                 if ($in = $this->insertQueryData('{$__cakeID__$}', $result, $association, $assocData, $model, $linkModel, $stack)) {
                     $ins[] = $in;
                 }
             }
             if (!empty($ins)) {
                 $ins = array_unique($ins);
                 if (count($ins) > 1) {
                     $query = str_replace('{$__cakeID__$}', '(' . implode(', ', $ins) . ')', $query);
                     $query = str_replace('= (', 'IN (', $query);
                 } else {
                     $query = str_replace('{$__cakeID__$}', $ins[0], $query);
                 }
                 $query = str_replace(' WHERE 1 = 1', '', $query);
             }
             $foreignKey = $model->hasAndBelongsToMany[$association]['foreignKey'];
             $joinKeys = array($foreignKey, $model->hasAndBelongsToMany[$association]['associationForeignKey']);
             list($with, $habtmFields) = $model->joinModel($model->hasAndBelongsToMany[$association]['with'], $joinKeys);
             $habtmFieldsCount = count($habtmFields);
             $q = $this->insertQueryData($query, null, $association, $assocData, $model, $linkModel, $stack);
             if ($q !== false) {
                 $fetch = $this->fetchAll($q, $model->cacheQueries);
             } else {
                 $fetch = null;
             }
         }
         $modelAlias = $model->alias;
         $modelPK = $model->primaryKey;
         foreach ($resultSet as &$row) {
             if ($type !== 'hasAndBelongsToMany') {
                 $q = $this->insertQueryData($query, $row, $association, $assocData, $model, $linkModel, $stack);
                 $fetch = null;
                 if ($q !== false) {
                     $joinedData = array();
                     if (($type === 'belongsTo' || $type === 'hasOne') && isset($row[$linkModel->alias], $joined[$model->alias]) && in_array($linkModel->alias, $joined[$model->alias])) {
                         $joinedData = Hash::filter($row[$linkModel->alias]);
                         if (!empty($joinedData)) {
                             $fetch[0] = array($linkModel->alias => $row[$linkModel->alias]);
                         }
                     } else {
                         $fetch = $this->fetchAll($q, $model->cacheQueries);
                     }
                 }
             }
             $selfJoin = $linkModel->name === $model->name;
             if (!empty($fetch) && is_array($fetch)) {
                 if ($recursive > 0) {
                     foreach ($linkModel->associations() as $type1) {
                         foreach ($linkModel->{$type1} as $assoc1 => $assocData1) {
                             $deepModel = $linkModel->{$assoc1};
                             if ($type1 === 'belongsTo' || $deepModel->alias === $modelAlias && $type === 'belongsTo' || $deepModel->alias !== $modelAlias) {
                                 $tmpStack = $stack;
                                 $tmpStack[] = $assoc1;
                                 if ($linkModel->useDbConfig == $deepModel->useDbConfig) {
                                     $db = $this;
                                 } else {
                                     $db = ConnectionManager::getDataSource($deepModel->useDbConfig);
                                 }
                                 $db->queryAssociation($linkModel, $deepModel, $type1, $assoc1, $assocData1, $queryData, true, $fetch, $recursive - 1, $tmpStack);
                             }
                         }
                     }
                 }
                 if ($type === 'hasAndBelongsToMany') {
                     $merge = array();
                     foreach ($fetch as $data) {
                         if (isset($data[$with]) && $data[$with][$foreignKey] === $row[$modelAlias][$modelPK]) {
                             if ($habtmFieldsCount <= 2) {
                                 unset($data[$with]);
                             }
                             $merge[] = $data;
                         }
                     }
                     if (empty($merge) && !isset($row[$association])) {
                         $row[$association] = $merge;
                     } else {
                         $this->_mergeAssociation($row, $merge, $association, $type);
                     }
                 } else {
                     $this->_mergeAssociation($row, $fetch, $association, $type, $selfJoin);
                 }
                 if (isset($row[$association])) {
                     $row[$association] = $linkModel->afterFind($row[$association], false);
                 }
             } else {
                 $tempArray[0][$association] = false;
                 $this->_mergeAssociation($row, $tempArray, $association, $type, $selfJoin);
             }
         }
     }
 }
 /**
  * saveAnswer
  * save the answer data
  *
  * @param array $data Postされた登録データ
  * @param array $registration registration data
  * @param array $summary answer summary data
  * @throws InternalErrorException
  * @return bool
  */
 public function saveAnswer($data, $registration, $summary)
 {
     //トランザクションBegin
     $this->begin();
     try {
         $summaryId = $summary['RegistrationAnswerSummary']['id'];
         // 繰り返しValidationを行うときは、こうやってエラーメッセージを蓄積するところ作らねばならない
         // 仕方ないCakeでModelObjectを使う限りは
         $validationErrors = array();
         foreach ($data['RegistrationAnswer'] as $answer) {
             $targetQuestionKey = $answer[0]['registration_question_key'];
             $targetQuestion = Hash::extract($registration['RegistrationPage'], '{n}.RegistrationQuestion.{n}[key=' . $targetQuestionKey . ']');
             if (!$targetQuestion) {
                 throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
             }
             // データ保存
             // Matrixタイプの場合はanswerが配列になっているがsaveでかまわない
             // saveMany中で1回しかValidateしなくてよい関数のためのフラグ
             $this->oneTimeValidateFlag = false;
             // Validate、Saveで使用するオプションデータ
             $options = array('registration_answer_summary_id' => $summaryId, 'question' => $targetQuestion[0], 'allAnswers' => $data['RegistrationAnswer']);
             if (!$this->saveMany($answer, $options)) {
                 $validationErrors[$targetQuestionKey] = $this->__errorMessageUnique($targetQuestion[0], Hash::filter($this->validationErrors));
             }
         }
         if (!empty($validationErrors)) {
             $this->validationErrors = Hash::filter($validationErrors);
             $this->rollback();
             return false;
         }
         $this->commit();
     } catch (Exception $ex) {
         $this->rollback();
         CakeLog::error($ex);
         throw $ex;
     }
     return true;
 }
 /**
  * TODO: move to Lib
  * returns type
  * - username: everything till @ (xyz@abc.de => xyz)
  * - hostname: whole domain (xyz@abc.de => abc.de)
  * - tld: top level domain only (xyz@abc.de => de)
  * - domain: if available (xyz@e.abc.de => abc)
  * - subdomain: if available (xyz@e.abc.de => e)
  * @param string $email: well formatted email! (containing one @ and one .)
  * @param string $type (TODO: defaults to return all elements)
  * @return string or false on failure
  */
 public function extractEmailInfo($email, $type = null)
 {
     //$checkpos = strrpos($email, '@');
     $nameParts = Hash::filter(explode('@', $email));
     if (count($nameParts) !== 2) {
         return false;
     }
     if ($type === 'username') {
         return $nameParts[0];
     }
     if ($type === 'hostname') {
         return $nameParts[1];
     }
     $checkpos = strrpos($nameParts[1], '.');
     $tld = trim(mb_substr($nameParts[1], $checkpos + 1));
     if ($type === 'tld') {
         return $tld;
     }
     $server = trim(mb_substr($nameParts[1], 0, $checkpos));
     //TODO; include 3rd-Level-Label
     $domain = '';
     $subdomain = '';
     $checkpos = strrpos($server, '.');
     if ($checkpos !== false) {
         $subdomain = trim(mb_substr($server, 0, $checkpos));
         $domain = trim(mb_substr($server, $checkpos + 1));
     }
     if ($type === 'domain') {
         return $domain;
     }
     if ($type === 'subdomain') {
         return $subdomain;
     }
     //$hostParts = explode();
     //$check = trim(mb_substr($email, $checkpos));
     return '';
 }
Exemple #20
0
 /**
  * Common search method
  *
  * Handles processes common to all PRG forms
  *
  * - Handles validation of post data
  * - converting post data into named params
  * - Issuing redirect(), and connecting named parameters before redirect
  * - Setting named parameter form data to view
  *
  * @param string $modelName - Name of the model class being used for the prg form
  * @param array $options Optional parameters:
  *  - string formName - name of the form involved in the prg
  *  - string action - The action to redirect to. Defaults to the current action
  *  - mixed modelMethod - If not false a string that is the model method that will be used to process the data
  *  - array allowedParams - An array of additional top level route params that should be included in the params processed
  *  - array excludedParams - An array of named/query params that should be excluded from the redirect url
  *  - string paramType - 'named' if you want to used named params or 'querystring' is you want to use query string
  * @return void
  */
 public function commonProcess($modelName = null, array $options = array())
 {
     $defaults = array('excludedParams' => array('page'));
     $defaults = Hash::merge($defaults, $this->_defaults['commonProcess']);
     extract(Hash::merge($defaults, $options));
     $paramType = strtolower($paramType);
     if (empty($modelName)) {
         $modelName = $this->controller->modelClass;
     }
     if (empty($formName)) {
         $formName = $modelName;
     }
     if (empty($action)) {
         $action = $this->controller->action;
     }
     if (!empty($this->controller->request->data)) {
         $this->controller->{$modelName}->set($this->controller->request->data);
         $valid = true;
         if ($modelMethod !== false) {
             $valid = $this->controller->{$modelName}->{$modelMethod}();
         }
         if ($valid) {
             $params = $this->controller->request->params['named'];
             if ($keepPassed) {
                 $params = array_merge($this->controller->request->params['pass'], $params);
             }
             $searchParams = $this->controller->request->data[$modelName];
             $this->serializeParams($searchParams);
             if ($paramType === 'named') {
                 $params = array_merge($params, $searchParams);
                 $params = $this->exclude($params, $excludedParams);
                 if ($filterEmpty) {
                     $params = Hash::filter($params);
                 }
                 $params = $this->_filter($params);
                 $this->connectNamed($params, array());
             } else {
                 $searchParams = array_merge($this->controller->request->query, $searchParams);
                 $searchParams = $this->exclude($searchParams, $excludedParams);
                 if ($filterEmpty) {
                     $searchParams = Hash::filter($searchParams);
                 }
                 $searchParams = $this->_filter($searchParams);
                 $this->connectNamed($searchParams, array());
                 $params['?'] = $searchParams;
             }
             $params['action'] = $action;
             foreach ($allowedParams as $key) {
                 if (isset($this->controller->request->params[$key])) {
                     $params[$key] = $this->controller->request->params[$key];
                 }
             }
             $this->controller->redirect($params);
         } else {
             $this->controller->Session->setFlash(__d('search', 'Please correct the errors below.'));
         }
     } elseif ($paramType === 'named' && !empty($this->controller->passedArgs) || $paramType === 'querystring' && !empty($this->controller->request->query)) {
         $this->connectNamed($this->controller->passedArgs, array());
         $this->presetForm(array('model' => $formName, 'paramType' => $paramType));
     }
 }
Exemple #21
0
 private function _explodeClass($formClass)
 {
     if (!is_array($formClass)) {
         $formClass = explode(' ', $formClass);
     }
     $formClass = Hash::filter($formClass);
     $formClass = array_map('trim', $formClass);
     return $formClass;
 }
Exemple #22
0
 /**
  * Queries associations.
  *
  * Used to fetch results on recursive models.
  *
  * - 'hasMany' associations with no limit set:
  *    Fetch, filter and merge is done recursively for every level.
  *
  * - 'hasAndBelongsToMany' associations:
  *    Fetch and filter is done unaffected by the (recursive) level set.
  *
  * @param Model $Model Primary Model object.
  * @param Model $LinkModel Linked model object.
  * @param string $type Association type, one of the model association types ie. hasMany.
  * @param string $association Association name.
  * @param array $assocData Association data.
  * @param array &$queryData An array of queryData information containing keys similar to Model::find().
  * @param bool $external Whether or not the association query is on an external datasource.
  * @param array &$resultSet Existing results.
  * @param int $recursive Number of levels of association.
  * @param array $stack A list with joined models.
  * @return mixed
  * @throws CakeException when results cannot be created.
  */
 public function queryAssociation(Model $Model, Model $LinkModel, $type, $association, $assocData, &$queryData, $external, &$resultSet, $recursive, $stack)
 {
     if (isset($stack['_joined'])) {
         $joined = $stack['_joined'];
         unset($stack['_joined']);
     }
     $queryTemplate = $this->generateAssociationQuery($Model, $LinkModel, $type, $association, $assocData, $queryData, $external);
     if (empty($queryTemplate)) {
         return null;
     }
     if (!is_array($resultSet)) {
         throw new CakeException(__d('cake_dev', 'Error in Model %s', get_class($Model)));
     }
     if ($type === 'hasMany' && empty($assocData['limit']) && !empty($assocData['foreignKey'])) {
         // 'hasMany' associations with no limit set.
         $assocIds = array();
         foreach ($resultSet as $result) {
             $assocIds[] = $this->insertQueryData('{$__cakeID__$}', $result, $association, $Model, $stack);
         }
         $assocIds = array_filter($assocIds);
         // Fetch
         $assocResultSet = array();
         if (!empty($assocIds)) {
             $assocResultSet = $this->_fetchHasMany($Model, $queryTemplate, $assocIds);
         }
         // Recursively query associations
         if ($recursive > 0 && !empty($assocResultSet) && is_array($assocResultSet)) {
             foreach ($LinkModel->associations() as $type1) {
                 foreach ($LinkModel->{$type1} as $assoc1 => $assocData1) {
                     $DeepModel = $LinkModel->{$assoc1};
                     $tmpStack = $stack;
                     $tmpStack[] = $assoc1;
                     $db = $LinkModel->useDbConfig === $DeepModel->useDbConfig ? $this : $DeepModel->getDataSource();
                     $db->queryAssociation($LinkModel, $DeepModel, $type1, $assoc1, $assocData1, $queryData, true, $assocResultSet, $recursive - 1, $tmpStack);
                 }
             }
         }
         // Filter
         if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
             $this->_filterResultsInclusive($assocResultSet, $Model, array($association));
         }
         // Merge
         return $this->_mergeHasMany($resultSet, $assocResultSet, $association, $Model);
     } elseif ($type === 'hasAndBelongsToMany') {
         // 'hasAndBelongsToMany' associations.
         $assocIds = array();
         foreach ($resultSet as $result) {
             $assocIds[] = $this->insertQueryData('{$__cakeID__$}', $result, $association, $Model, $stack);
         }
         $assocIds = array_filter($assocIds);
         // Fetch
         $assocResultSet = array();
         if (!empty($assocIds)) {
             $assocResultSet = $this->_fetchHasAndBelongsToMany($Model, $queryTemplate, $assocIds, $association);
         }
         $habtmAssocData = $Model->hasAndBelongsToMany[$association];
         $foreignKey = $habtmAssocData['foreignKey'];
         $joinKeys = array($foreignKey, $habtmAssocData['associationForeignKey']);
         list($with, $habtmFields) = $Model->joinModel($habtmAssocData['with'], $joinKeys);
         $habtmFieldsCount = count($habtmFields);
         // Filter
         if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
             $this->_filterResultsInclusive($assocResultSet, $Model, array($association, $with));
         }
     }
     $modelAlias = $Model->alias;
     $primaryKey = $Model->primaryKey;
     $selfJoin = $Model->name === $LinkModel->name;
     foreach ($resultSet as &$row) {
         if ($type === 'hasOne' || $type === 'belongsTo' || $type === 'hasMany') {
             $assocResultSet = array();
             $prefetched = false;
             if (($type === 'hasOne' || $type === 'belongsTo') && isset($row[$LinkModel->alias], $joined[$Model->alias]) && in_array($LinkModel->alias, $joined[$Model->alias])) {
                 $joinedData = Hash::filter($row[$LinkModel->alias]);
                 if (!empty($joinedData)) {
                     $assocResultSet[0] = array($LinkModel->alias => $row[$LinkModel->alias]);
                 }
                 $prefetched = true;
             } else {
                 $query = $this->insertQueryData($queryTemplate, $row, $association, $Model, $stack);
                 if ($query !== false) {
                     $assocResultSet = $this->fetchAll($query, $Model->cacheQueries);
                 }
             }
         }
         if (!empty($assocResultSet) && is_array($assocResultSet)) {
             if ($recursive > 0) {
                 foreach ($LinkModel->associations() as $type1) {
                     foreach ($LinkModel->{$type1} as $assoc1 => $assocData1) {
                         $DeepModel = $LinkModel->{$assoc1};
                         if ($type1 === 'belongsTo' || $type === 'belongsTo' && $DeepModel->alias === $modelAlias || $DeepModel->alias !== $modelAlias) {
                             $tmpStack = $stack;
                             $tmpStack[] = $assoc1;
                             $db = $LinkModel->useDbConfig === $DeepModel->useDbConfig ? $this : $DeepModel->getDataSource();
                             $db->queryAssociation($LinkModel, $DeepModel, $type1, $assoc1, $assocData1, $queryData, true, $assocResultSet, $recursive - 1, $tmpStack);
                         }
                     }
                 }
             }
             if ($type === 'hasAndBelongsToMany') {
                 $merge = array();
                 foreach ($assocResultSet as $data) {
                     if (isset($data[$with]) && $data[$with][$foreignKey] === $row[$modelAlias][$primaryKey]) {
                         if ($habtmFieldsCount <= 2) {
                             unset($data[$with]);
                         }
                         $merge[] = $data;
                     }
                 }
                 if (empty($merge) && !isset($row[$association])) {
                     $row[$association] = $merge;
                 } else {
                     $this->_mergeAssociation($row, $merge, $association, $type);
                 }
             } else {
                 if (!$prefetched && $LinkModel->useConsistentAfterFind) {
                     if ($queryData['callbacks'] === true || $queryData['callbacks'] === 'after') {
                         $this->_filterResultsInclusive($assocResultSet, $Model, array($association));
                     }
                 }
                 $this->_mergeAssociation($row, $assocResultSet, $association, $type, $selfJoin);
             }
             if ($type !== 'hasAndBelongsToMany' && isset($row[$association]) && !$prefetched && !$LinkModel->useConsistentAfterFind) {
                 $row[$association] = $LinkModel->afterFind($row[$association], false);
             }
         } else {
             $tempArray[0][$association] = false;
             $this->_mergeAssociation($row, $tempArray, $association, $type, $selfJoin);
         }
     }
 }
Exemple #23
0
 /**
  * display method
  *
  * @param $page
  * @param $subpage
  * @return void
  */
 public function display($page = null, $subpage = null)
 {
     if (empty($page)) {
         $path = func_get_args();
         $count = count($path);
         if (!$count) {
             $this->redirect('/');
         }
         $page = $subpage = $title_for_layout = null;
         if (!empty($path[0])) {
             $page = $path[0];
         }
         if (!empty($path[1])) {
             $subpage = $path[1];
         }
         if (!empty($path[$count - 1])) {
             $title_for_layout = Inflector::humanize($path[$count - 1]);
         }
     } else {
         $path = Hash::filter(array($page, $subpage));
     }
     switch ($page) {
         case 'home':
             $this->page_data['page_title'][] = __('Réalisations');
             // Fetch projects
             $projects = $this->Project->find('all');
             $this->set(compact('projects'));
             break;
         case 'bio':
             $this->page_data['page_title'][] = __('Biographie');
             $content = $this->Page->find('first', array('conditions' => array('Page.id' => 1)));
             $this->set(compact('content'));
             break;
         case 'about':
             $this->page_data['page_title'][] = __('À propos');
             $content = $this->Page->find('first', array('conditions' => array('Page.id' => 3)));
             $this->set(compact('content'));
             break;
         case 'contact':
             $this->page_data['page_title'][] = __('Contact');
             $content = $this->Page->find('first', array('conditions' => array('Page.id' => 2)));
             if ($this->request->is('post')) {
                 $data = $this->request->data['Email'];
                 // Send email
                 $message = "\n\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t<strong>Sujet :</strong> {$data['subject']}<br>\n\t\t\t\t\t\t\t<strong>Nom :</strong> {$data['name']}<br>\n\t\t\t\t\t\t\t<strong>Email :</strong> {$data['email']}\n\t\t\t\t\t\t</p>\n\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t{$data['message']}\n\t\t\t\t\t\t</p>\n\t\t\t\t\t";
                 $email = new CakeEmail('default');
                 $email->emailFormat('both');
                 $email->to(Configure::read('App.contact'), "Emile Artiste-Peintre");
                 $email->subject("Emile Artiste-Peintre - Contact");
                 if ($email->send($message)) {
                     $this->Session->setFlash(__('Message envoyé avec succès'), 'alert-success');
                 } else {
                     $this->Session->setFlash(__('Une erreur est survenue lors de l\'envoi du message'), 'alert-error');
                 }
             }
             $this->set(compact('content'));
             break;
     }
     $this->path = $path;
     $this->set(compact('page', 'subpage', 'title_for_layout'));
     $this->render(implode('/', $path));
 }
Exemple #24
0
 /**
  * Filters empty elements out of a route array, excluding '0'.
  *
  * @param array $var Either an array to filter, or value when in callback
  * @return mixed Either filtered array, or true/false when in callback
  * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::filter
  */
 public static function filter(array $var)
 {
     return Hash::filter($var);
 }
Exemple #25
0
 /**
  * Retrieve a list of allowed parent roles
  *
  * @paraam integer $roleId
  * @param integer $id Role id
  * @return array list of allowable parent roles in 'list' format
  */
 public function allowedParents(Model $model, $id = null)
 {
     if (!$model->Behaviors->enabled('Croogo.Aliasable')) {
         $model->Behaviors->load('Croogo.Aliasable');
     }
     if ($id == $model->byAlias('public')) {
         return array();
     }
     $adminRoleId = $model->byAlias('admin');
     $excludes = Hash::filter(array_values(array($adminRoleId, $id)));
     $options = array('conditions' => array('NOT' => array($model->alias . '.id' => $excludes)));
     return $model->find('list', $options);
 }
Exemple #26
0
/**
 * Determine which fields of a form should be used for hash.
 * Populates $this->fields
 *
 * @param boolean $lock Whether this field should be part of the validation
 *     or excluded as part of the unlockedFields.
 * @param string|array $field Reference to field to be secured. Should be dot separated to indicate nesting.
 * @param mixed $value Field value, if value should not be tampered with.
 * @return void
 */
	protected function _secure($lock, $field = null, $value = null) {
		if (!$field) {
			$field = $this->entity();
		} elseif (is_string($field)) {
			$field = Hash::filter(explode('.', $field));
		}

		foreach ($this->_unlockedFields as $unlockField) {
			$unlockParts = explode('.', $unlockField);
			if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) {
				return;
			}
		}

		$field = implode('.', $field);
		$field = preg_replace('/(\.\d+)+$/', '', $field);

		if ($lock) {
			if (!in_array($field, $this->fields)) {
				if ($value !== null) {
					return $this->fields[$field] = $value;
				}
				$this->fields[] = $field;
			}
		} else {
			$this->unlockField($field);
		}
	}
Exemple #27
0
 /**
  * Merge 2 arrays, but only merge in the $defaults which were "empty" in $data
  *
  * Hash::filter() - $data
  * Hash::merge() - $defaultsAndData + $filteredData
  *
  * @param array $defaults
  * @param array $data
  * @return array $data
  */
 public static function mergeIfEmpty($defaults, $data)
 {
     $defaultsAndData = Hash::merge($data, $defaults);
     $filteredData = Hash::filter($data);
     return Hash::merge($defaultsAndData, $filteredData);
 }