/** * Sets a configuration variable into this action * * If called with no arguments, all configuration values are * returned. * * $key is interpreted with dot notation, like the one used for * Configure::write() * * If $key is string and $value is not passed, it will return the * value associated with such key. * * If $key is an array and $value is empty, then $key will * be interpreted as key => value dictionary of settings and * it will be merged directly with $this->settings * * If $key is a string, the value will be inserted in the specified * slot as indicated using the dot notation * * @param mixed $key * @param mixed $value * @param boolean $merge * @return mixed|CrudAction */ public function config($key = null, $value = null, $merge = true) { if ($key === null && $value === null) { return $this->_settings; } if ($value === null) { if (is_array($key)) { if ($merge) { $this->_settings = Hash::merge($this->_settings, $key); } else { foreach (Hash::flatten($key) as $k => $v) { $this->_settings = Hash::insert($this->_settings, $k, $v); } } return $this; } return Hash::get($this->_settings, $key); } if (is_array($value)) { if ($merge) { $value = array_merge((array) Hash::get($this->_settings, $key), $value); } else { foreach ($value as $k => $v) { $this->_settings = Hash::insert($this->_settings, $k, $v); } } } $this->_settings = Hash::insert($this->_settings, $key, $value); return $this; }
/** * Save(公開)のテスト * * @param array $data 登録データ * @dataProvider dataProviderSave * @return array 登録後のデータ */ public function testSave($data) { $model = $this->_modelName; $method = $this->_methodName; $created = !isset($data[$this->{$model}->alias]['id']); //チェック用データ取得 if (!$created) { $before = $this->{$model}->find('first', array('recursive' => -1, 'conditions' => array('id' => $data[$this->{$model}->alias]['id']))); $saveData = Hash::remove($data, $this->{$model}->alias . '.id'); } else { $saveData = $data; $before[$this->{$model}->alias] = array(); } //テスト実行 $result = $this->{$model}->{$method}($saveData); $this->assertNotEmpty($result); $id = $this->{$model}->getLastInsertID(); //is_latestのチェック if (!$created) { $after = $this->{$model}->find('first', array('recursive' => -1, 'conditions' => array('id' => $data[$this->{$model}->alias]['id']))); $this->assertEquals($after, Hash::merge($before, array($this->{$model}->alias => array('is_latest' => false)))); } //更新のチェック $actual = $this->_getActual($id, $created); $expected = $this->_getExpected($id, $data, $before, $created); $this->assertEquals($expected, $actual); return $actual; }
/** * Return roles_rooms_users * * @param array $conditions Conditions by Model::find * @return array */ public function getRolesRoomsUsers($conditions = array()) { $this->Room = ClassRegistry::init('Rooms.Room'); $conditions = Hash::merge(array('Room.page_id_top NOT' => null), $conditions); $rolesRoomsUsers = $this->find('all', array('recursive' => -1, 'fields' => array($this->alias . '.*', $this->RolesRoom->alias . '.*', $this->Room->alias . '.*'), 'joins' => array(array('table' => $this->RolesRoom->table, 'alias' => $this->RolesRoom->alias, 'type' => 'INNER', 'conditions' => array($this->alias . '.roles_room_id' . ' = ' . $this->RolesRoom->alias . ' .id')), array('table' => $this->Room->table, 'alias' => $this->Room->alias, 'type' => 'INNER', 'conditions' => array($this->RolesRoom->alias . '.room_id' . ' = ' . $this->Room->alias . ' .id'))), 'conditions' => $conditions)); return $rolesRoomsUsers; }
/** * edit * * @return void */ public function edit() { if (!$this->initLink()) { return; } $this->Categories->initCategories(true); $this->Paginator->settings = array('Link' => array('order' => array('LinkOrder.weight' => 'asc'), 'conditions' => array('Link.block_id' => $this->viewVars['blockId'], 'Link.is_latest' => true), 'limit' => -1)); $links = $this->Paginator->paginate('Link'); $links = Hash::combine($links, '{n}.LinkOrder.weight', '{n}', '{n}.Category.id'); //POST処理 $data = array(); if ($this->request->isPost()) { //登録処理 $data = $this->data; $this->LinkOrder->saveLinkOrders($data); //validationError if ($this->NetCommons->handleValidationError($this->LinkOrder->validationErrors)) { //リダイレクト $this->redirect(NetCommonsUrl::backToPageUrl()); return; } } $data = Hash::merge(array('links' => $links), $data); $results = $this->camelizeKeyRecursive($data); $this->set($results); }
/** * Outputs room plugins * * @param string $roomId rooms.id * @param array $attributes The HTML attributes of the select element. * @return string Formatted CHECKBOX element * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs */ public function checkboxPluginsRoom($roomId, $attributes = array()) { $html = ''; //Modelの呼び出し $this->Plugin = ClassRegistry::init('PluginManager.Plugin'); $this->PluginsRoom = ClassRegistry::init('PluginManager.PluginsRoom'); //findのoptionsセット $findOptions = array('fields' => array($this->Plugin->alias . '.key', $this->Plugin->alias . '.name', $this->PluginsRoom->alias . '.room_id', $this->PluginsRoom->alias . '.plugin_key'), 'conditions' => array($this->Plugin->alias . '.type' => Plugin::PLUGIN_TYPE_FOR_FRAME, $this->Plugin->alias . '.language_id' => Configure::read('Config.languageId')), 'order' => array($this->Plugin->alias . '.weight' => 'asc')); //データ取得 if (isset($attributes['all']) && $attributes['all']) { $plugins = $this->Plugin->find('all', Hash::merge($findOptions, array('recursive' => -1, 'joins' => array(array('table' => $this->PluginsRoom->table, 'alias' => $this->PluginsRoom->alias, 'type' => 'LEFT', 'conditions' => array($this->Plugin->alias . '.key' . ' = ' . $this->PluginsRoom->alias . ' .plugin_key', $this->PluginsRoom->alias . '.room_id' => $roomId)))))); unset($attributes['all']); } else { $plugins = $this->PluginsRoom->find('all', Hash::merge($findOptions, array('recursive' => 0, 'conditions' => array($this->PluginsRoom->alias . '.room_id' => $roomId)))); } //チェックボックスの設定 $options = Hash::combine($plugins, '{n}.Plugin.key', '{n}.Plugin.name'); $this->_View->request->data['Plugin']['key'] = array_keys($options); foreach (array_keys($this->_View->request->data['Plugin']['key']) as $index) { $html .= $this->Form->hidden('Plugin.' . $index . '.key'); } $defaults = Hash::extract($plugins, '{n}.PluginsRoom[room_id=' . $roomId . ']'); $defaults = array_values(Hash::combine($defaults, '{n}.plugin_key', '{n}.plugin_key')); $this->_View->request->data['PluginsRoom']['plugin_key'] = $defaults; $html .= $this->Form->select('PluginsRoom.plugin_key', $options, Hash::merge($attributes, array('multiple' => 'checkbox'))); return $html; }
/** * beforeValidate is called before a model is validated, you can use this callback to * add behavior validation rules into a models validate array. Returning false * will allow you to make the validation fail. * * @param Model $model Model using this behavior * @param array $options Options passed from Model::save(). * @return mixed False or null will abort the operation. Any other result will continue. * @see Model::save() */ public function beforeValidate(Model $model, $options = array()) { $model->loadModels(array('CircularNoticeContent' => 'CircularNotices.CircularNoticeContent', 'CircularNoticeTargetUser' => 'CircularNotices.CircularNoticeTargetUser', 'User' => 'Users.User')); if (!$model->data['CircularNoticeContent']['is_room_target']) { // 回覧先ユーザのバリデーション処理 if (!isset($model->data['CircularNoticeTargetUser'])) { $model->data['CircularNoticeTargetUser'] = array(); } $model->CircularNoticeTargetUser->set($model->data['CircularNoticeTargetUser']); // ユーザ選択チェック $targetUsers = Hash::extract($model->data['CircularNoticeTargetUser'], '{n}.user_id'); if (!$model->CircularNoticeTargetUser->isUserSelected($targetUsers)) { $model->CircularNoticeTargetUser->validationErrors['user_id'] = sprintf(__d('circular_notices', 'Select user')); $model->validationErrors = Hash::merge($model->validationErrors, $model->CircularNoticeTargetUser->validationErrors); return false; } if (!$model->CircularNoticeTargetUser->validates()) { $model->validationErrors = Hash::merge($model->validationErrors, $model->CircularNoticeTargetUser->validationErrors); return false; } if (!$model->User->existsUser($targetUsers)) { $model->CircularNoticeTargetUser->validationErrors['user_id'][] = sprintf(__d('net_commons', 'Failed on validation errors. Please check the input data.')); $model->validationErrors = Hash::merge($model->validationErrors, $model->CircularNoticeTargetUser->validationErrors); return false; } } return true; }
/** * Constructor * * @param ComponentCollection $collection A ComponentCollection for this component * @param array $settings Array of settings. * @return RememberMeComponent */ public function __construct(ComponentCollection $collection, $settings = array()) { parent::__construct($collection, $settings); $this->_checkAndSetCookieLifeTime(); $this->settings = Hash::merge($this->_defaults, $settings); $this->configureCookie($this->settings['cookie']); }
/** * beforeFind can be used to cancel find operations, or modify the query that will be executed. * By returning null/false you can abort a find. By returning an array you can modify/replace the query * that is going to be run. * * @param Model $model Model using this behavior * @param array $query Data used to execute this query, i.e. conditions, order, etc. * @return bool|array False or null will abort the operation. You can return an array to replace the * $query that will be eventually run. */ public function beforeFind(Model $model, $query) { $model->Like = ClassRegistry::init('Likes.Like'); $model->LikesUser = ClassRegistry::init('Likes.LikesUser'); $conditions = $query['conditions']; if (is_array($query['conditions']) === false) { return $query; } $columns = array(); if (!isset($query['fields'])) { $columns = 'Like.*'; } else { $columns = $query['fields']; } $columns = Hash::merge((array) $columns, array_keys($conditions)); // Like条件あったらJOIN if (!preg_grep('/^Like\\./', $columns) && !preg_grep('/^LikesUser\\./', $columns)) { return $query; } if (!isset($query['fields'])) { $query['fields'] = '*'; } $query['joins'][] = array('table' => $model->Like->table, 'alias' => $model->Like->alias, 'type' => 'LEFT', 'conditions' => array('Like.plugin_key' => Inflector::underscore($model->plugin), $this->__model . '.' . $this->__field . ' = ' . 'Like.content_key')); $likesUserConditions = array('Like.id = LikesUser.like_id'); if (Current::read('User.id')) { $likesUserConditions['LikesUser.user_id'] = Current::read('User.id'); } else { $likesUserConditions['LikesUser.session_key'] = CakeSession::id(); } $query['joins'][] = array('table' => $model->LikesUser->table, 'alias' => $model->LikesUser->alias, 'type' => 'LEFT', 'conditions' => $likesUserConditions); return $query; }
/** * After find callback. Can be used to modify any results returned by find. * * @param Model $model Model using this behavior * @param mixed $results The results of the find operation * @param boolean $primary Whether this model is being queried directly (vs. being queried as an association) * * @return mixed An array value will replace the value of $results - any other value will be ignored. */ public function afterFind(Model $model, $results, $primary = false) { parent::afterFind($model, $results, $primary); if ($primary && array_key_exists($model->alias, $results[0])) { $arrObj = new ArrayObject($results); $iterator = $arrObj->getIterator(); while ($iterator->valid()) { $result = []; if (isset($iterator->current()[$model->alias]) && count($iterator->current()[$model->alias]) > 0) { $key = "{$model->alias}.{$this->settings[$model->alias]['key']}"; $value = "{$model->alias}.{$this->settings[$model->alias]['value']}"; $result = Hash::combine($iterator->current(), $key, $value); } if (!array_key_exists($this->settings[$model->alias]['key'], $iterator->current()[$model->alias]) && !array_key_exists($this->settings[$model->alias]['value'], $iterator->current()[$model->alias])) { $results[$iterator->key()][$model->alias] = Hash::merge($iterator->current()[$model->alias], $result); } else { $results[$iterator->key()][$model->alias] = $result; } $iterator->next(); } } elseif (array_key_exists($model->alias, $results)) { $key = "{n}.{$model->alias}.{$this->settings[$model->alias]['key']}"; $value = "{n}.{$model->alias}.{$this->settings[$model->alias]['value']}"; $output = Hash::combine($results, $key, $value); $results[$model->alias] = $output; } return $results; }
/** * Called during validation operations, before validation. Please note that custom * validation rules can be defined in $validate. * * @param array $options Options passed from Model::save(). * @return bool True if validate operation should continue, false to abort * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate * @see Model::save() * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function beforeValidate($options = array()) { // ウィザード画面中はstatusチェックをしないでほしいので // ここに来る前にWorkflowBehaviorでつけられたstatus-validateを削除しておく if (Hash::check($options, 'validate') == RegistrationsComponent::REGISTRATION_VALIDATE_TYPE) { $this->validate = Hash::remove($this->validate, 'status'); } $this->validate = Hash::merge($this->validate, array('block_id' => array('numeric' => array('rule' => array('numeric'), 'message' => __d('net_commons', 'Invalid request.'), 'on' => 'update')), 'title' => array('rule' => 'notBlank', 'message' => sprintf(__d('net_commons', 'Please input %s.'), __d('registrations', 'Title')), 'required' => true, 'allowEmpty' => false), 'answer_timing' => array('publicTypeCheck' => array('rule' => array('inList', array(RegistrationsComponent::USES_USE, RegistrationsComponent::USES_NOT_USE)), 'message' => __d('net_commons', 'Invalid request.')), 'requireOtherFields' => array('rule' => array('requireOtherFields', RegistrationsComponent::USES_USE, array('Registration.answer_start_period', 'Registration.answer_end_period'), 'OR'), 'message' => __d('registrations', 'if you set the period, please set time.'))), 'answer_start_period' => array('checkDateTime' => array('rule' => 'checkDateTime', 'message' => __d('registrations', 'Invalid datetime format.'))), 'answer_end_period' => array('checkDateTime' => array('rule' => 'checkDateTime', 'message' => __d('registrations', 'Invalid datetime format.')), 'checkDateComp' => array('rule' => array('checkDateComp', '>=', 'answer_start_period'), 'message' => __d('registrations', 'start period must be smaller than end period'))), 'is_key_pass_use' => array('boolean' => array('rule' => array('boolean'), 'message' => __d('net_commons', 'Invalid request.')), 'requireOtherFieldsKey' => array('rule' => array('requireOtherFields', RegistrationsComponent::USES_USE, array('AuthorizationKey.authorization_key'), 'AND'), 'message' => __d('registrations', 'if you set the use key phrase period, please set key phrase text.')), 'authentication' => array('rule' => array('requireOtherFields', RegistrationsComponent::USES_USE, array('Registration.is_image_authentication'), 'XOR'), 'message' => __d('registrations', 'Authentication key setting , image authentication , either only one can not be selected.'))), 'is_image_authentication' => array('boolean' => array('rule' => array('boolean'), 'message' => __d('net_commons', 'Invalid request.')), 'authentication' => array('rule' => array('requireOtherFields', RegistrationsComponent::USES_USE, array('Registration.is_key_pass_use'), 'XOR'), 'message' => __d('registrations', 'Authentication key setting , image authentication , either only one can not be selected.'))), 'is_answer_mail_send' => array('boolean' => array('rule' => array('boolean'), 'message' => __d('net_commons', 'Invalid request.'))), 'is_regist_user_send' => array('boolean' => array('rule' => array('boolean'), 'message' => __d('net_commons', 'Invalid request.'))), 'reply_to' => array('email' => array('rule' => array('email', false, null), 'message' => sprintf(__d('mails', '%s, please enter by e-mail format'), __d('mails', 'E-mail address to receive a reply')), 'allowEmpty' => true)))); parent::beforeValidate($options); // 最低でも1ページは存在しないとエラー if (!isset($this->data['RegistrationPage'][0])) { $this->validationErrors['pickup_error'] = __d('registrations', 'please set at least one page.'); } else { // ページデータが存在する場合 // 配下のページについてバリデート $validationErrors = array(); $maxPageIndex = count($this->data['RegistrationPage']); $options['maxPageIndex'] = $maxPageIndex; foreach ($this->data['RegistrationPage'] as $pageIndex => $page) { // それぞれのページのフィールド確認 $this->RegistrationPage->create(); $this->RegistrationPage->set($page); // ページシーケンス番号の正当性を確認するため、現在の配列インデックスを渡す $options['pageIndex'] = $pageIndex; if (!$this->RegistrationPage->validates($options)) { $validationErrors['RegistrationPage'][$pageIndex] = $this->RegistrationPage->validationErrors; } } $this->validationErrors += $validationErrors; } // 引き続き登録フォーム本体のバリデートを実施してもらうためtrueを返す return true; }
public function blocks($position_name, $options = array()) { $output = ''; if ($this->is_empty($position_name)) { return $output; } $options = Hash::merge(array('element_options' => array()), $options); $element_options = $options['element_options']; $default_element = 'Blocks.block'; $view = $this->_View; $view->Blocks->set('test', 'test 123'); $blocks = $view->viewVars['blocks_for_layout'][$position_name]; foreach ($blocks as $idx => $block) { $block['id'] = $idx; $element = $block['element']; $exists = $view->elementExists($element); $block_output = ''; if ($exists) { $block_output = $view->element($element, compact('block'), $element_options); } else { if (!empty($element)) { $this->log(sprintf('Missing element `%s`', $block['element']), LOG_WARNING); } $block_output = $view->element($default_element, compact('block'), array('ignoreMissing' => true) + $element_options); } $output .= $block_output; } return $output; }
/** * Generate tree menu * * @return void **/ public function nestedLinks($links, $options, $depth = 0) { $defaults = array('mainClass' => 'nav nav-pills', 'mainRole' => 'menulist', 'subClass' => 'dropdown-menu', 'subRole' => 'menu'); $options = Hash::merge($defaults, $options); $items = ''; foreach ($links as $link) { $hasChildren = !empty($link['children']); if (strstr($link['Link']['link'], 'controller:')) { $link['Link']['link'] = $this->Menus->linkStringToArray($link['Link']['link']); } $content = $this->Html->link($link['Link']['title'], $link['Link']['link'], array('class' => ($hasChildren ? ' dropdown-toggle' : '') . $link['Link']['class'] . '-link', 'data-toggle' => $hasChildren ? 'dropdown' : '', 'data-target' => '#', 'target' => $link['Link']['target'], 'rel' => $link['Link']['rel'], 'title' => empty($link['Link']['description']) ? $link['Link']['title'] : $link['Link']['description'])); if ($hasChildren) { $content .= $this->nestedLinks($link['children'], $options, $depth + 1); } $liClass = array($hasChildren ? 'dropdown' : 'no-children', $link['Link']['class']); if (!empty($this->_View->request->params['locale'])) { $currentUrl = substr($this->_View->request->url, strlen($this->_View->request->params['locale'] . '/')); } else { $currentUrl = $this->_View->request->url; } if (Router::url($link['Link']['link']) == Router::url('/' . $currentUrl)) { $liClass[] = 'active'; } $items .= $this->Html->tag('li', $content, array('class' => implode(' ', $liClass), 'id' => 'link-' . $link['Link']['id'])); } $attrs = array('class' => $depth == 0 ? $options['mainClass'] : $options['subClass'], 'role' => $depth == 0 ? $options['mainRole'] : $options['subRole']); return $this->Html->tag($options['tag'], $items, $attrs); }
/** * edit * * @param int $roomId rooms.id * @return void */ public function edit($roomId = null) { //登録処理の場合、URLよりPOSTパラメータでチェックする if ($this->request->isPost()) { $roomId = $this->data['Room']['id']; } //ルームデータチェック&セット if (!$this->RoomsUtility->validRoom($roomId, Configure::read('Config.languageId'))) { return; } //スペースデータチェック&セット if (!$this->SpacesUtility->validSpace($this->viewVars['room']['Room']['space_id'])) { return; } if ($this->request->isPost()) { //登録処理 $data = $this->data; //--不要パラメータ除去 unset($data['save']); $this->request->data = $data; } else { $results = $this->UserSearch->search(); $this->set('users', $results); $displayFields = Hash::merge(array('room_role_key'), $this->User->dispayFields($this->params['plugin'] . '/' . $this->params['controller'])); $this->set('displayFields', $displayFields); } }
public function payment() { $this->request->allowMethod('post'); if (!isset($this->request->data['amount']) || empty($this->request->data['amount'])) { $this->redirect($this->referer()); } $firstName = $lastName = ''; $name = explode(' ', $this->currUser['User']['full_name']); if (count($name) > 0) { $firstName = array_shift($name); $lastName = implode(' ', $name); } $customerData = array('firstName' => $firstName, 'lastName' => $lastName, 'email' => $this->currUser['User']['username'], 'phone' => $this->currUser['User']['phone']); try { $customer = Braintree_Customer::find('konstruktor-' . $this->currUser['User']['id']); $customer = Braintree_Customer::update('konstruktor-' . $this->currUser['User']['id'], $customerData); } catch (Exception $e) { $customer = Braintree_Customer::create(Hash::merge(array('id' => 'konstruktor-' . $this->currUser['User']['id']), $customerData)); } if ($customer->success) { $customer = $customer->customer; } else { throw new NotFoundException(__d('billing', 'Invalid billing group')); } $this->Session->write('Billing', array('amount' => $this->request->data['amount'])); $this->layout = 'profile_new'; $clientToken = Braintree_ClientToken::generate(); $this->set('clientToken', $clientToken); $this->set('customer', $customer); }
public function setup(Model $model, $config = array()) { $this->config = Hash::merge(self::$defaultConfig, (array) $config); if (!$model->schema($this->config['field'])) { throw new BadFunctionCallException(__d('optimistic_lock', 'Model %s doesn\'t have field %s.', $model->alias, $this->config['field'])); } }
/** * Called during validation operations, before validation. Please note that custom * validation rules can be defined in $validate. * * @param array $options Options passed from Model::save(). * @return bool True if validate operation should continue, false to abort * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @see Model::save() */ public function beforeValidate($options = array()) { $qIndex = $options['questionIndex']; // Questionモデルは繰り返し判定が行われる可能性高いのでvalidateルールは最初に初期化 // mergeはしません $this->validate = array('question_sequence' => array('numeric' => array('rule' => array('numeric'), 'message' => __d('net_commons', 'Invalid request.')), 'comparison' => array('rule' => array('comparison', '==', $qIndex), 'message' => __d('registrations', 'question sequence is illegal.'))), 'question_type' => array('inList' => array('rule' => array('inList', RegistrationsComponent::$typesList), 'message' => __d('net_commons', 'Invalid request.'))), 'question_value' => array('notBlank' => array('rule' => array('notBlank'), 'message' => __d('registrations', 'Please input question text.'))), 'is_require' => array('boolean' => array('rule' => array('boolean'), 'message' => __d('net_commons', 'Invalid request.'))), 'is_choice_random' => array('boolean' => array('rule' => array('boolean'), 'message' => __d('net_commons', 'Invalid request.'))), 'is_skip' => array('boolean' => array('rule' => array('boolean'), 'message' => __d('net_commons', 'Invalid request.'))), 'is_result_display' => array('inList' => array('rule' => array('inList', $this->_getResultDisplayList($this->data['RegistrationQuestion']['question_type'])), 'message' => __d('net_commons', 'Invalid request.'))), 'result_display_type' => array('inList' => array('rule' => array('inList', RegistrationsComponent::$resultDispTypesList), 'message' => __d('net_commons', 'Invalid request.'))), 'is_range' => array('boolean' => array('rule' => array('boolean'), 'message' => __d('net_commons', 'Invalid request.')))); // 範囲制限設定された項目の場合 if ($this->data['RegistrationQuestion']['is_range'] == true) { $this->validate = Hash::merge($this->validate, array('min' => array('notBlank' => array('rule' => array('notBlank'), 'message' => __d('registrations', 'Please enter both the maximum and minimum values.')), 'comparison' => array('rule' => array('comparison', '<', $this->data['RegistrationQuestion']['max']), 'message' => __d('registrations', 'Please enter smaller value than max.'))), 'max' => array('notBlank' => array('rule' => array('notBlank'), 'message' => __d('registrations', 'Please enter both the maximum and minimum values.')), 'comparison' => array('rule' => array('comparison', '>', $this->data['RegistrationQuestion']['min']), 'message' => __d('registrations', 'Please enter bigger value than min.'))))); } // validates時にはまだregistration_page_idの設定ができないのでチェックしないことにする // registration_page_idの設定は上位のRegistrationPageクラスで責任を持って行われるものとする parent::beforeValidate($options); $isSkip = $this->data['RegistrationQuestion']['is_skip']; // 付属の選択肢以下のvalidate if ($this->_checkChoiceExists() && isset($this->data['RegistrationChoice'])) { // この項目種別に必要な選択肢データがちゃんとあるなら選択肢をバリデート $validationErrors = array(); foreach ($this->data['RegistrationChoice'] as $cIndex => $choice) { // 項目データバリデータ $this->RegistrationChoice->create(); $this->RegistrationChoice->set($choice); $options['choiceIndex'] = $cIndex; $options['isSkip'] = $isSkip; if (!$this->RegistrationChoice->validates($options)) { $validationErrors['RegistrationChoice'][$cIndex] = $this->RegistrationChoice->validationErrors; } } $this->validationErrors += $validationErrors; } return true; }
/** * Convenience method to generate an API Url * * @param string|array $url * @param bool $full * @return string */ public function apiUrl($url = null, $full = false) { if (is_array($url)) { $url = Hash::merge(array('admin' => false, 'api' => Configure::read('Croogo.Api.path'), 'prefix' => 'v1.0', 'ext' => 'json'), $url); } return parent::url($url, $full); }
/** * 表示方法変更 * * @return CakeResponse */ public function edit() { // 取得 $videoFrameSetting = $this->VideoFrameSetting->getVideoFrameSetting($this->viewVars['frameKey'], $this->viewVars['roomId']); if ($this->request->isPost()) { // 更新時間を再セット unset($videoFrameSetting['VideoFrameSetting']['modified']); $data = Hash::merge($videoFrameSetting, $this->data, array('VideoFrameSetting' => array('frame_key' => $this->viewVars['frameKey'])), array('Frame' => array('id' => $this->viewVars['frameId']))); // 保存 if (!($videoFrameSetting = $this->VideoFrameSetting->saveVideoFrameSetting($data))) { // エラー処理 if (!$this->handleValidationError($this->VideoFrameSetting->validationErrors)) { $this->log($this->validationErrors, 'debug'); return; } // 正常処理 } else { // ajax以外は、リダイレクト if (!$this->request->is('ajax')) { // 一覧へ戻る $url = isset($this->viewVars['current']['page']) ? '/' . $this->viewVars['current']['page']['permalink'] : null; $this->redirect($url); } return; } } $results = array('videoFrameSetting' => $videoFrameSetting['VideoFrameSetting']); // キーをキャメル変換 $results = $this->camelizeKeyRecursive($results); $this->set($results); }
public function addToBasket(Model $Model, $id, array $options = array()) { $options = Hash::merge(array('basket' => $Model->ShoppingBasketItem->ShoppingBasket->currentBasketId(), 'amount' => 1, 'configuration' => array(), 'non_overridable' => array()), array_filter($options)); $configurationGroupIds = $Model->ItemConfigurationGroup->find('list', array('fields' => array('ConfigurationGroup.id'), 'conditions' => array('ItemConfigurationGroup.foreign_key' => $id, 'ItemConfigurationGroup.model' => $Model->name), 'contain' => array('ConfigurationGroup'))); $valueData = $Model->ShoppingBasketItem->ConfigurationValue->generateValueData($Model->ShoppingBasketItem->name, $configurationGroupIds, $options['configuration'], $options['non_overridable']); $stackable = $Model->field('stackable', array('id' => $id)); if ($stackable) { $shoppingBasketItemId = $Model->ShoppingBasketItem->field('id', array('ShoppingBasketItem.shopping_basket_id' => $options['basket'], 'ShoppingBasketItem.product_id' => $id)); if (!$shoppingBasketItemId) { $Model->ShoppingBasketItem->create(); $data = $Model->ShoppingBasketItem->saveAssociated(array('ShoppingBasketItem' => array('shopping_basket_id' => $options['basket'], 'product_id' => $id, 'amount' => $options['amount']), 'ConfigurationValue' => $valueData)); return $data; } $Model->ShoppingBasketItem->id = $shoppingBasketItemId; $amount = $Model->ShoppingBasketItem->field('amount'); return $Model->ShoppingBasketItem->saveField('amount', $amount + $options['amount']); } for ($number = 1; $number <= $options['amount']; $number++) { $Model->ShoppingBasketItem->create(); $data = $Model->ShoppingBasketItem->saveAssociated(array('ShoppingBasketItem' => array('shopping_basket_id' => $options['basket'], 'product_id' => $id, 'amount' => 1), 'ConfigurationValue' => $valueData)); if (!$data) { return false; } } return true; }
/** * Meta field: with key/value fields * * @param string $key (optional) key * @param string $value (optional) value * @param integer $id (optional) ID of Meta * @param array $options (optional) options * @return string */ public function field($key = '', $value = null, $id = null, $options = array()) { $inputClass = $this->Layout->cssClass('formInput'); $_options = array('key' => array('label' => __d('croogo', 'Key'), 'value' => $key), 'value' => array('label' => __d('croogo', 'Value'), 'value' => $value, 'type' => 'textarea', 'rows' => 2)); if ($inputClass) { $_options['key']['class'] = $_options['value']['class'] = $inputClass; } $options = Hash::merge($_options, $options); $uuid = String::uuid(); $fields = ''; if ($id != null) { $fields .= $this->Form->input('Meta.' . $uuid . '.id', array('type' => 'hidden', 'value' => $id)); $this->Form->unlockField('Meta.' . $uuid . '.id'); } $fields .= $this->Form->input('Meta.' . $uuid . '.key', $options['key']); $fields .= $this->Form->input('Meta.' . $uuid . '.value', $options['value']); $this->Form->unlockField('Meta.' . $uuid . '.key'); $this->Form->unlockField('Meta.' . $uuid . '.value'); $fields = $this->Html->tag('div', $fields, array('class' => 'fields')); $id = is_null($id) ? $uuid : $id; $deleteUrl = $this->settings['deleteUrl']; $deleteUrl[] = $id; $actions = $this->Html->link(__d('croogo', 'Remove'), $deleteUrl, array('class' => 'remove-meta', 'rel' => $id)); $actions = $this->Html->tag('div', $actions, array('class' => 'actions')); $output = $this->Html->tag('div', $actions . $fields, array('class' => 'meta')); return $output; }
/** * Looks upon $data and extract FeaturedImage tag or value * * By default, this method will return the generated <img> tag. Pass * array('tag' => false) in the $options array to get the value. * * If you have multiple versions of image, you can retrieve a specific image * by passing an integer value in the `maxWidth` key. * * Example: * * echo $this->AssetsImage->featured($node, array( * 'class' => 'gallery featured-image', * 'tag' => true, * 'maxWidth' => 500, * )); * * @param array $data Array of record containing `LinkedAssets` key * @param array $options Array of options */ public function featured($data, $options = array()) { if (empty($data['LinkedAssets']['FeaturedImage'])) { return null; } $options = Hash::merge(array('class' => 'featured-image', 'tag' => true), $options); $tag = $options['tag']; $image = $data['LinkedAssets']['FeaturedImage']; $path = $image['path']; if (isset($options['maxWidth'])) { $maxWidth = $options['maxWidth']; unset($options['maxWidth']); if ($image['width'] > $maxWidth && !empty($image['Versions'])) { $found = false; foreach ($image['Versions'] as $version) { $smallest = $version['path']; if ($version['width'] <= $maxWidth) { $path = $version['path']; $found = true; break; } } if (!$found && isset($smallest)) { $path = $smallest; } } } if ($tag) { return $this->Html->image($path, $options); } else { return $path; } }
/** * Output use like setting element * * @param string $likeFieldName This should be "Modelname.fieldname" for use_like field * @param string $unlikeFieldName This should be "Modelname.fieldname" for use_unlike field * @param array $attributes Array of attributes and HTML arguments. * @return string HTML tags */ public function setting($likeFieldName, $unlikeFieldName, $attributes = array()) { $output = ''; //属性の設定 $defaultAttributes = array('error' => false, 'div' => array('class' => 'form-inline'), 'label' => false, 'legend' => false); $likeAttributes = array('type' => 'checkbox', 'label' => '<span class="glyphicon glyphicon-thumbs-up"> </span> ' . __d('likes', 'Use like button')); if (isset($unlikeFieldName)) { $likeAttributes['ng-click'] = 'useLike()'; $like = Hash::get($this->_View->request->data, $likeFieldName); $unlikeAttributes = array('type' => 'checkbox', 'label' => '<span class="glyphicon glyphicon-thumbs-down"> </span> ' . __d('likes', 'Use unlike button'), 'ng-disabled' => !(int) $like); $unlikeAttributes = Hash::merge($defaultAttributes, $unlikeAttributes, $attributes); } $likeAttributes = Hash::merge($defaultAttributes, $likeAttributes, $attributes); //共通DIVの出力 if (isset($unlikeFieldName)) { $output .= '<div class="row form-group" ng-controller="LikeSettings" ' . 'ng-init="initialize(\'' . $this->domId($likeFieldName) . '\', \'' . $this->domId($unlikeFieldName) . '\')">'; } else { $output .= '<div class="row form-group">'; } //いいねの出力 $output .= '<div class="col-xs-12">'; $output .= $this->Form->input($likeFieldName, $likeAttributes); $output .= '</div>'; //わるいねの出力 if (isset($unlikeFieldName)) { $output .= '<div class="col-xs-11 col-xs-offset-1">'; $output .= $this->Form->input($unlikeFieldName, $unlikeAttributes); $output .= '</div>'; } $output .= '</div>'; return $output; }
protected function _request($path, $request = array()) { // preparing request $request = Hash::merge($this->_request, $request); $request['uri']['path'] .= $path; if (isset($request['uri']['query'])) { $request['uri']['query'] = array_merge(array('access_token' => $this->_config['token']), $request['uri']['query']); } else { $request['uri']['query'] = array('access_token' => $this->_config['token']); } // createding http socket object for later use $HttpSocket = new HttpSocket(array('ssl_verify_host' => false)); // issuing request $response = $HttpSocket->request($request); // olny valid response is going to be parsed if (substr($response->code, 0, 1) != 2) { if (Configure::read('debugApis')) { debug($request); debug($response->body); die; } return false; } // parsing response $results = $this->_parseResponse($response); if (isset($results['data'])) { return $results['data']; } return $results; }
public static function getUrl($name, array $args = null, array $options = null) { $url = null; if (isset(static::$url[$name])) { $url = static::$url[$name]; if (!is_null($options)) { $url = preg_replace('#\\{([a-z0-9_]+)\\}#e', 'isset($options["$1"]) ? $options["$1"] : null', $url); } if (!is_null($args)) { $parse_url = parse_url($url); if (!empty($parse_url['query'])) { $queries = explode('&', $parse_url['query']); $parse_url['query'] = array(); foreach ($queries as $query) { $name = $query; $value = null; if (strstr($query, '=')) { list($name, $value) = explode('=', $query, 2); } $parse_url['query'][$name] = $value; } } else { $parse_url['query'] = array(); } $url = $parse_url['scheme'] . '://' . $parse_url['host'] . $parse_url['path'] . '?' . http_build_query(Hash::merge($parse_url['query'], $args)); } } return $url; }
/** * Meta field: with key/value fields * * @param string $key (optional) key * @param string $value (optional) value * @param integer $id (optional) ID of Meta * @param array $options (optional) options * @return string */ public function field($key = '', $value = null, $id = null, $options = array()) { $_options = array('key' => array('label' => __d('croogo', 'Key'), 'value' => $key, 'class' => 'span12'), 'value' => array('label' => __d('croogo', 'Value'), 'value' => $value, 'class' => 'span12', 'type' => 'textarea', 'rows' => 2)); $options = Hash::merge($_options, $options); $uuid = String::uuid(); $fields = ''; if ($id != null) { $fields .= $this->Form->input('Meta.' . $uuid . '.id', array('type' => 'hidden', 'value' => $id)); $this->Form->unlockField('Meta.' . $uuid . '.id'); } $fields .= $this->Form->input('Meta.' . $uuid . '.key', $options['key']); $fields .= $this->Form->input('Meta.' . $uuid . '.value', $options['value']); $this->Form->unlockField('Meta.' . $uuid . '.key'); $this->Form->unlockField('Meta.' . $uuid . '.value'); $fields = $this->Html->tag('div', $fields, array('class' => 'fields')); $id = is_null($id) ? $uuid : $id; $deleteUrl = array_intersect_key($this->request->params, array('admin' => null, 'plugin' => null, 'controller' => null, 'named' => null)); $deleteUrl['action'] = 'delete_meta'; $deleteUrl[] = $id; $deleteUrl = $this->url($deleteUrl); $actions = $this->Html->link(__d('croogo', 'Remove'), $deleteUrl, array('class' => 'remove-meta', 'rel' => $id)); $actions = $this->Html->tag('div', $actions, array('class' => 'actions')); $output = $this->Html->tag('div', $actions . $fields, array('class' => 'meta')); return $output; }
protected function _request($path, $request = array()) { // preparing request $request = Hash::merge($this->_request, $request); $request['uri']['path'] .= $path; // Read cached GET results if ($request['method'] == 'GET') { $cacheKey = $this->_generateCacheKey(); $results = Cache::read($cacheKey); if ($results !== false) { return $results; } } // createding http socket object for later use $HttpSocket = new HttpSocket(); // issuing request $response = $HttpSocket->request($request); // olny valid response is going to be parsed if (substr($response->code, 0, 1) != 2) { if (Configure::read('debugApis')) { debug($request); debug($response->body); } return false; } // parsing response $results = $this->_parseResponse($response); // cache and return results if ($request['method'] == 'GET') { Cache::write($cacheKey, $results); } return $results; }
/** * Save link settings * * @param array $data received post data * @return bool True on success, false on failure * @throws InternalErrorException */ public function saveLinkSetting($data) { $this->loadModels(['LinkSetting' => 'Links.LinkSetting', 'BlockRolePermission' => 'Blocks.BlockRolePermission']); //トランザクションBegin $this->setDataSource('master'); $dataSource = $this->getDataSource(); $dataSource->begin(); try { if (!$this->validateLinkSetting($data)) { return false; } foreach ($data[$this->BlockRolePermission->alias] as $value) { if (!$this->BlockRolePermission->validateBlockRolePermissions($value)) { $this->validationErrors = Hash::merge($this->validationErrors, $this->BlockRolePermission->validationErrors); return false; } } if (!$this->save(null, false)) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } foreach ($data[$this->BlockRolePermission->alias] as $value) { if (!$this->BlockRolePermission->saveMany($value, ['validate' => false])) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } } //トランザクションCommit $dataSource->commit(); } catch (Exception $ex) { //トランザクションRollback $dataSource->rollback(); CakeLog::error($ex); throw $ex; } return true; }
/** * Outputs room roles radio * * @param string $fieldName Name attribute of the RADIO * @param array $attributes The HTML attributes of the select element. * @return string Formatted RADIO element * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs */ public function checkboxBlockRolePermission($fieldName, $attributes = array('inline' => true)) { list($model, $permission) = explode('.', $fieldName); $html = ''; if (!isset($this->_View->request->data[$model][$permission])) { return $html; } $html .= '<div class="form-inline">'; foreach ($this->_View->request->data[$model][$permission] as $roleKey => $role) { if (!$role['value'] && $role['fixed']) { continue; } $html .= '<span class="checkbox-separator"></span>'; $html .= '<div class="form-group">'; if (!$role['fixed']) { $html .= $this->Form->hidden($fieldName . '.' . $roleKey . '.id'); $html .= $this->Form->hidden($fieldName . '.' . $roleKey . '.roles_room_id'); $html .= $this->Form->hidden($fieldName . '.' . $roleKey . '.block_key'); $html .= $this->Form->hidden($fieldName . '.' . $roleKey . '.permission'); } $options = Hash::merge(array('div' => false, 'disabled' => (bool) $role['fixed']), $attributes); if (!$options['disabled']) { $options['ng-click'] = 'clickRole($event, \'' . $permission . '\', \'' . Inflector::variable($roleKey) . '\')'; } $html .= $this->Form->checkbox($fieldName . '.' . $roleKey . '.value', $options); $html .= $this->Form->label($fieldName . '.' . $roleKey . '.value', h($this->_View->viewVars['roles'][$roleKey]['name'])); $html .= '</div>'; } $html .= '</div>'; return $html; }
/** * Constructor * * @param ComponentCollection $collection The controller for this request. * @param string $settings An array of settings. This class does not use any settings. */ public function __construct(ComponentCollection $collection, $settings = array()) { $this->_Collection = $collection; $controller = $collection->getController(); $this->controller($controller); $this->settings = Hash::merge($this->settings, $settings); }
/** * Called before the Controller::beforeRender(), and before * the view class is loaded, and before Controller::render() * * @param Controller $controller Controller with components to beforeRender * @return void * @link http://book.cakephp.org/2.0/en/controllers/components.html#Component::beforeRender */ public function beforeRender(Controller $controller) { //RequestActionの場合、スキップする if (!empty($controller->request->params['requested'])) { return; } $this->controller = $controller; //RoomRolePermissionデータセット if (isset($this->settings['room_id'])) { $roomId = $this->settings['room_id']; } else { $roomId = null; } if (isset($this->settings['type'])) { $type = $this->settings['type']; } else { $type = null; } if (isset($this->settings['permissions'])) { $results = $this->NetCommonsRoomRole->getRoomRolePermissions($roomId, $this->settings['permissions'], $type); $defaultPermissions = Hash::remove($results['DefaultRolePermission'], '{s}.{s}.id'); $results['RoomRolePermission'] = Hash::merge($defaultPermissions, $results['RoomRolePermission']); $this->controller->request->data = Hash::merge($this->controller->request->data, $results); } }