/** * Before migration callback * * @param string $direction Direction of migration process (up or down) * @return bool Should process continue */ public function before($direction) { if ($direction === 'up') { $Model = ClassRegistry::init('SiteManager.SiteSetting'); $dataSource = $Model->getDataSource(); $searchType = SiteSetting::DATABASE_SEARCH_LIKE; $hasMroonga = false; if ($dataSource->config['datasource'] === 'Database/Mysql') { $result = $Model->query('SELECT * FROM information_schema.ENGINES'); $engines = Hash::extract($result, '{n}.ENGINES.ENGINE'); $mysql56 = (bool) version_compare($dataSource->getVersion(), '5.6', '>='); if ($mysql56) { $searchType = SiteSetting::DATABASE_SEARCH_MATCH_AGAIN; } elseif (in_array('Mroonga', $engines, true)) { //$searchType = 'match_against'; //$hasMroonga = true; } } if ($searchType === SiteSetting::DATABASE_SEARCH_LIKE) { //インデックスが使われないため、検索用のインデックス(FullText)は削除する $this->migration = Hash::remove($this->migration, 'up.create_table.topics.indexes.search'); } if (!$hasMroonga) { $this->migration = Hash::insert($this->migration, 'up.create_table.topics.tableParameters.engine', 'InnoDB'); $this->migration = Hash::remove($this->migration, 'up.create_table.topics.tableParameters.comment', null); } $record = array('language_id' => 0, 'key' => 'Search.type', 'value' => $searchType); $Model->create(); if (!$Model->save($record, false)) { return false; } } return true; }
public function beforeSave($options = []) { $id = Hash::get($this->data, $this->name . '.id'); $updateRules = []; $readFields = []; foreach (Hash::extract($this->data, $this->name) as $field => $value) { foreach ($this->rules as $key => $rule) { if ($rule[3] == false && array_search($this->name . '.' . $field, $rule[1]) !== FALSE) { $this->rules[$key][3] = true; $readFields = array_merge($readFields, $rule[1]); } } } if (!empty($readFields)) { $this->save(null, ['callbacks' => false]); $id = $this->id; $this->read(array_unique($readFields), $id); foreach ($this->rules as $rule) { if ($rule[3]) { $values = []; foreach ($rule[1] as $depend) { $value = Hash::get($this->data, $depend); $values[] = $value; } $this->data = Hash::insert($this->data, $rule[0], $rule[2]($values)); } } } return true; }
/** * Adds a new item to a menu * * @param string $menu The menu alias * @param string $key * @param string $label * @param array $options * @return void */ public function add($menu, $key, $label = null, $url = null, $options = array()) { if (is_array($key)) { foreach ($key as $k => $item) { if (is_string($k)) { $item['key'] = $k; } $item = array_merge(array('url' => null, 'options' => array()), $item); $this->add($menu, $item['key'], $item['label'], $item['url'], $item['options']); } return; } $path = array(); if (strpos($menu, '.') !== false) { $path = explode('.', $menu); $menu = $path[0]; } else { $path = array($menu); } if (!array_key_exists($menu, $this->_menus)) { $this->create($menu); } $subitems = array(); if (!empty($options['items'])) { $subitems = $options['items']; unset($options['items']); } $item = array('label' => $label, 'url' => $url, 'options' => $options); $hashPath = implode($path, '.items.') . '.items.' . $key; $this->_menus = Hash::insert($this->_menus, $hashPath, $item); if (!empty($subitems)) { $submenuKey = implode($path, '.') . '.' . $key; $this->add($submenuKey, $subitems); } }
public function beforeFilter() { $this->Maintenance->checkMaintenance(); $this->Cookie->name = APP_NAME; $this->Cookie->type('rijndael'); if (isset($this->request->params['prefix']) && $this->request->params['prefix'] == 'admin') { $this->layout = 'admin'; $this->Auth->authenticate = Hash::insert($this->Auth->authenticate, "{s}.scope", array('User.is_admin' => 1)); $this->Auth->loginAction = array('prefix' => 'admin', 'plugin' => '', 'controller' => 'user', 'action' => 'login'); $this->Auth->loginRedirect = array('prefix' => 'admin', 'plugin' => '', 'controller' => 'dashboard', 'action' => 'index'); $this->Auth->logoutRedirect = '/admin'; $this->Auth->flash = array('element' => 'alert', 'key' => 'auth', 'params' => array('plugin' => 'BoostCake', 'class' => 'alert-error')); $this->helpers['Html'] = array('className' => 'BoostCake.BoostCakeHtml'); $this->helpers['Form'] = array('className' => 'BoostCake.BoostCakeForm'); $this->helpers['Paginator'] = array('className' => 'BoostCake.BoostCakePaginator'); } $this->_checkAuth(); if (!$this->Auth->loggedIn() && !in_array($this->request->params['action'], array('register', 'login', 'fbAuth', 'fbAuthCheck', 'confirm', 'forgetPassword', 'passwordRequest', 'ipnPaypal'))) { $this->layout = 'unregistered'; $this->set('currUserID', $this->currUserID); $this->set('currUser', $this->currUser); } $this->Auth->authError = __('You must log in to access this page'); $this->Auth->allow(array('register', 'login', 'fbAuth', 'fbAuthCheck', 'fbAccessToken', 'confirm', 'forgetPassword', 'passwordRequest', 'ipnPaypal', 'error404', 'vacancies')); // $this->_checkAuth(); $this->_updateUser(); }
public function afterFind($results, $primary = false) { if ($primary) { $results = Hash::insert($results, "{n}.BraintreeSubscription", array()); $results = Hash::insert($results, "{n}.BraintreePlan", array()); $braintreeSubscriptions = Braintree_Subscription::search([Braintree_SubscriptionSearch::ids()->in(Hash::extract($results, "{n}.BillingSubscription.remote_subscription_id"))]); $braintreePlans = Braintree_Plan::all(); foreach ($results as $key => $result) { foreach ($braintreeSubscriptions as $braintreeSubscription) { if ($braintreeSubscription->id == $result['BillingSubscription']['remote_subscription_id']) { $result['BraintreeSubscription'] = $braintreeSubscription; break; } //$results = Hash::insert($results, "{n}.BillingSubscription[remote_subscription_id=".$braintreeSubscription->id."]", array('BraintreeSubscription' => $braintreeSubscription)); } foreach ($braintreePlans as $braintreePlan) { if ($braintreePlan->id == $result['BillingSubscription']['remote_plan_id']) { $result['BraintreePlan'] = $braintreePlan; break; } } $results[$key] = $result; } } return $results; }
public static function addSubMenu($parentSlug, $slug, $title, $url, $capability) { if (self::menuExists($parentSlug)) { if (!self::subMenuExists($parentSlug, $slug)) { self::$menus = Hash::insert(self::$menus, $parentSlug . '.sub_menus.' . $slug, array('title' => $title, 'url' => $url, 'capability' => $capability)); } } }
public function setState($key, $value, $defaultValue = null) { $current = isset($_SESSION[$this->sessionVariable]) ? $_SESSION[$this->sessionVariable] : array(); if ($value === $defaultValue) { $_SESSION[$this->sessionVariable] = Hash::remove($current, $key); } else { $_SESSION[$this->sessionVariable] = Hash::insert($current, $key, $value); } }
/** * Saves dashboard setting * * @return void */ public function admin_save() { $userId = $this->Auth->user('id'); if (!$userId) { throw new CakeException('You must be logged in'); } $data = Hash::insert($this->request->data['dashboard'], '{n}.user_id', $userId); $this->DashboardsDashboard->deleteAll(array('user_id' => $userId)); $this->DashboardsDashboard->saveMany($data); }
public static function write($config, $value = null) { if (!is_object(self::$singletoninstance)) { self::singleton(); } if (!is_array($config)) { $config = array($config => $value); } foreach ($config as $name => $value) { self::$confList = Hash::insert(self::$confList, $name, $value); } $_SESSION['cacheConfig'] = self::$confList; }
/** * タイトル(ブロックタイトル)の出力 * * #### サンプル * ``` * echo $this->NetCommonsHtml->blockTitle($bbs['name']) * ``` * ##### 出力結果 * ``` * <h1>新しい掲示板 20160513074815</h1> * ``` * * @param string $text タイトル * @param string $titleIcon タイトルアイコン * @param array $options HTML属性オプション * @return string `<h1>`タグ */ public function blockTitle($text = '', $titleIcon = null, $options = array()) { $output = ''; $escape = Hash::get($options, 'escape', true); if ($escape) { $text = h($text); } $options = Hash::insert($options, 'escape', false); if ($titleIcon) { $text = $this->NetCommonsHtml->titleIcon($titleIcon) . ' ' . $text; } $output .= $this->Html->tag('h1', $text, $options); return $output; }
/** * Expect FileModel->saveFile() on success * * @return void */ public function testSaveFile() { //データ生成 $data = array('File' => array('status' => 1, 'role_type' => 'file_test', 'path' => TMP . 'tests' . DS . 'files' . DS, 'slug' => 'file_test_1', 'extension' => 'gif', 'original_name' => 'file_test_1', 'mimetype' => 'image/gif', 'name' => 'logo.gif', 'alt' => 'logo.gif', 'size' => 5873), 'FilesPlugin' => array('plugin_key' => 'files'), 'FilesRoom' => array('room_id' => 1), 'FilesUser' => array('user_id' => 1)); $this->FileModel->saveFile($data); //期待値の生成 $fileId = 2; $expected = $data; $expected = Hash::insert($expected, '{s}.file_id', $fileId); $expected['File']['id'] = $expected['File']['file_id']; unset($expected['File']['file_id']); $result = $this->FileModel->findById($fileId); $result['FilesPlugin'] = $result['FilesPlugin'][0]; $result['FilesRoom'] = $result['FilesRoom'][0]; $result['FilesUser'] = $result['FilesUser'][0]; $this->_assertArray(null, $expected, $result); }
/** * @param $name * @param $value * @return bool */ public function write($name, $value) { if (empty($name)) { return false; } $write = $name; if (!is_array($name)) { $write = array($name => $value); } foreach ($write as $key => $val) { self::_overwrite($this->data, Hash::insert($this->data, $key, $val)); if (Hash::get($this->data, $key) !== $val) { return false; } } return true; }
/** * Expect RssReaderItem->updateRssReaderItems() validate error by RssReader * * @return void */ public function testValidateErrorByRssReader() { $rssReaderId = 1; //コンテンツの公開権限true $this->RssReader->Behaviors->attach('Publishable'); $this->RssReader->Behaviors->Publishable->setup($this->RssReader, ['contentPublishable' => true]); //データ生成 $rssReader = $this->RssReader->find('first', array('recursive' => -1, 'conditions' => array('id' => $rssReaderId))); $rssReader['RssReader']['url'] = ''; $url = APP . 'Plugin' . DS . 'RssReaders' . DS . 'Test' . DS . 'Fixture' . DS . 'rss_v1.xml'; $xmlData = $this->RssReaderItem->serializeXmlToArray($url); $xmlData = Hash::insert($xmlData, '{n}.rss_reader_id', $rssReaderId); $data = array('RssReader' => $rssReader['RssReader'], 'RssReaderItem' => $xmlData); //登録処理実行 $result = $this->RssReaderItem->updateRssReaderItems($data); //テスト実施(詳細なバリデーションのチェックは、RssReaderValidateErrorTestで行う) $this->assertFalse($result); }
/** * Save default UserAttributesRole * * @param Model $model Model using this behavior * @param array $data User role data * @return bool True on success * @throws InternalErrorException */ public function saveDefaultUserAttributesRole(Model $model, $data) { $model->loadModels(['UserAttributesRole' => 'UserRoles.UserAttributesRole']); //UserAttributesRoleデフォルトのデータ取得 $userAttributesRole = $model->UserAttributesRole->find('all', array('recursive' => -1, 'conditions' => array('role_key' => $data['UserRoleSetting']['origin_role_key']))); if (!$userAttributesRole) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } //UserAttributesRoleの登録処理 foreach (['id', 'created', 'created_user', 'modified', 'modified_user'] as $field) { $userAttributesRole = Hash::remove($userAttributesRole, '{n}.UserAttributesRole.' . $field); } $userAttributesRole = Hash::insert($userAttributesRole, '{n}.UserAttributesRole.role_key', $data['UserRoleSetting']['role_key']); if (!$model->UserAttributesRole->saveMany($userAttributesRole, array('validate' => false))) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } return true; }
/** * Camelize処理 * * @param array $orig 変換元データ * @return array 変換後データ */ public function camelizeKeyRecursive($orig) { $newResult = []; foreach ($orig as $key => $value) { if (Hash::get($value, 'TrackableCreator')) { $avatar = $this->DisplayUser->avatar($value, [], 'TrackableCreator.id'); $value = Hash::insert($value, 'TrackableCreator.avatar', $avatar); } if (Hash::get($value, 'TrackableUpdater')) { $avatar = $this->DisplayUser->avatar($value, [], 'TrackableUpdater.id'); $value = Hash::insert($value, 'TrackableUpdater.avatar', $avatar); } $newResult[$key] = $this->__camelizeKeyRecursive($value); $displayStatus = $this->__getStatusLabel($newResult[$key]); $newResult[$key]['topic']['displayStatus'] = $displayStatus; } return $newResult; }
/** * フォーム設定にあるメール文面等をメール設定へ反映する * * @param Model $model Model * @param array $saveRegistration Registraion データ * @return void * @throws InternalErrorException */ public function updateMailSetting(Model $model, $saveRegistration) { // 登録通知メール設定を取得 $mailSetting = $model->MailSetting->getMailSettingPlugin($saveRegistration[$model->alias]['language_id'], array(MailSettingFixedPhrase::DEFAULT_TYPE, MailSettingFixedPhrase::ANSWER_TYPE), $model->plugin); if (!Hash::check($mailSetting, 'MailSetting.id')) { // まだメール設定がないときは、登録フォームで登録通知メールONならメール設定も送信する設定にする。 //$mailSetting = $model->MailSetting->createMailSetting($model->alias); $mailSetting['MailSetting']['is_mail_send'] = $saveRegistration['Registration']['is_answer_mail_send']; } // 登録通知メール設定を変更 $pluginLowercase = strtolower(Inflector::singularize($model->plugin)); $mailSetting['MailSetting']['plugin_key'] = strtolower($model->plugin); $mailSetting['MailSetting']['block_key'] = Current::read('Block.key'); $mailSetting['MailSetting']['reply_to'] = $saveRegistration[$model->alias]['reply_to']; $mailSetting['MailSettingFixedPhrase']['answer']['mail_fixed_phrase_subject'] = $saveRegistration[$model->alias][$pluginLowercase . '_mail_subject']; $mailSetting['MailSettingFixedPhrase']['answer']['mail_fixed_phrase_body'] = $saveRegistration[$model->alias][$pluginLowercase . '_mail_body']; $mailSetting['MailSettingFixedPhrase']['answer']['plugin_key'] = strtolower($model->plugin); $mailSetting['MailSettingFixedPhrase']['answer']['block_key'] = Current::read('Block.key'); $mailSetting['MailSettingFixedPhrase']['contents']['plugin_key'] = strtolower($model->plugin); $mailSetting['MailSettingFixedPhrase']['contents']['block_key'] = Current::read('Block.key'); // 登録通知メール設定を保存 if ($model->MailSetting->save($mailSetting)) { $mailSetting = Hash::insert($mailSetting, 'MailSettingFixedPhrase.answer.mail_setting_id', $model->MailSetting->id); $mailSetting = Hash::insert($mailSetting, 'MailSettingFixedPhrase.contents.mail_setting_id', $model->MailSetting->id); $model->MailSettingFixedPhrase = ClassRegistry::init('Mails.MailSettingFixedPhrase'); $answerPhrase = $mailSetting['MailSettingFixedPhrase']['answer']; //$answerPhrase = array( // 'MailSettingFixedPhrase' => $answerPhrase //); //if (!$model->MailSettingFixedPhrase->save($answerPhrase, ['callbacks' => false])) { if (!$model->MailSettingFixedPhrase->save($answerPhrase)) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } $model->MailSettingFixedPhrase->create(); $contentsPhrase = $mailSetting['MailSettingFixedPhrase']['contents']; //$contentsPhrase = array( // 'MailSettingFixedPhrase' => $contentsPhrase //); //if (!$model->MailSettingFixedPhrase->save($contentsPhrase, ['callbacks' => false])) { if (!$model->MailSettingFixedPhrase->save($contentsPhrase)) { throw new InternalErrorException(__d('net_commons', 'Internal Server Error')); } } }
/** * Add a menu item * * @param string $path dot separated path in the array. * @param array $options menu options array * @return void */ public static function add($path, $options) { $pathE = explode('.', $path); $pathE = array_splice($pathE, 0, count($pathE) - 2); $parent = join('.', $pathE); if (!empty($parent) && !Hash::check(self::$_items, $parent)) { $title = Inflector::humanize(end($pathE)); $o = array('title' => $title); self::_setupOptions($o); self::add($parent, $o); } self::_setupOptions($options); $current = Hash::extract(self::$_items, $path); if (!empty($current)) { self::_replace(self::$_items, $path, $options); } else { self::$_items = Hash::insert(self::$_items, $path, $options); } }
/** * Filter results from a call, parsing out the records * * @param array $results * @return array Array of results * @author David Kullmann */ public function filterResults($results = array()) { if (!empty($this->currentModel)) { if ($this->currentModel->findQueryType === 'count') { return isset($results['count']) ? $results['count'] : $results; } } if (!empty($results['facets'])) { if (!isset($this->currentModel->_facets)) { $this->currentModel->_facets = array(); } foreach ($results['facets'] as $facet => $data) { $this->currentModel->_facets[$facet] = $data; } } if (!empty($results['hits'])) { foreach ($results['hits']['hits'] as &$result) { $tmp = isset($result['_source']) ? $result['_source'] : array(); if (!empty($result['fields'])) { foreach ($result['fields'] as $field => $value) { if (strpos($field, '.') && strpos($field, 'doc') !== 0) { $tmp = Hash::insert($tmp, $field, $value); } else { $tmp[0][$field] = $value; } } } if (empty($tmp[$this->currentModel->alias][$this->currentModel->primaryKey])) { $tmp[$this->currentModel->alias][$this->currentModel->primaryKey] = $result['_id']; } $result = $tmp; } return $results['hits']['hits']; } if (!empty($results['_id'])) { $model = $results['_source']; if (empty($model[$this->currentModel->alias][$this->currentModel->primaryKey])) { $model[$this->currentModel->alias][$this->currentModel->primaryKey] = $results['_id']; } return array($model); } return $results; }
/** * Safely access the values in $this->params. * * @param string $name The name of the parameter to get. * * @return mixed The value of the provided parameter. Will * return false if the parameter doesn't exist or is falsey. */ public function param($name) { $args = func_get_args(); if (count($args) === 2) { $this->params = Hash::insert($this->params, $name, $args[1]); return $this; } if (!isset($this->params[$name])) { return Hash::get($this->params, $name, FALSE); } return $this->params[$name]; }
/** * parses nested values out of keys. * * @param array $values Values to be exploded. * @return array Array of values exploded */ protected function _parseNestedValues($values) { foreach ($values as $key => $value) { if ($value === '1') { $value = true; } if ($value === '') { $value = false; } unset($values[$key]); if (strpos($key, '.') !== false) { $values = Hash::insert($values, $key, $value); } else { $values[$key] = $value; } } return $values; }
/** * view method * * @return void */ public function view() { if (!$this->__prepare()) { return; } //レイアウトの設定 if ($this->request->is('ajax')) { $this->viewClass = 'View'; $this->layout = 'NetCommons.modal'; } elseif (Current::isControlPanel()) { $this->ControlPanelLayout = $this->Components->load('ControlPanel.ControlPanelLayout'); } else { $this->PageLayout = $this->Components->load('Pages.PageLayout'); } if (!Hash::get($this->request->query, 'tab')) { $this->request->query = Hash::insert($this->request->query, 'tab', 'user-infomation'); } //自分自身の場合、ルーム・グループデータ取得する if (Hash::get($this->viewVars['user'], 'User.id') === Current::read('User.id')) { //ルームデータ取得 $this->Rooms->setReadableRooms(Hash::get($this->viewVars['user'], 'User.id')); // グループデータ取得・設定 $this->Groups->setGroupList($this); } else { if (Current::allowSystemPlugin('rooms')) { //ルームデータ取得 $this->Rooms->setReadableRooms(Hash::get($this->viewVars['user'], 'User.id')); } } }
/** * Used to store a dynamic variable in Configure. * * Usage: * {{{ * Configure::write('One.key1', 'value of the Configure::One[key1]'); * Configure::write(array('One.key1' => 'value of the Configure::One[key1]')); * Configure::write('One', array( * 'key1' => 'value of the Configure::One[key1]', * 'key2' => 'value of the Configure::One[key2]' * ); * * Configure::write(array( * 'One.key1' => 'value of the Configure::One[key1]', * 'One.key2' => 'value of the Configure::One[key2]' * )); * }}} * * @link http://book.cakephp.org/2.0/en/development/configuration.html#Configure::write * @param string|array $config The key to write, can be a dot notation value. * Alternatively can be an array containing key(s) and value(s). * @param mixed $value Value to set for var * @return boolean True if write was successful */ public static function write($config, $value = null) { if (!is_array($config)) { $config = array($config => $value); } foreach ($config as $name => $value) { self::$_values = Hash::insert(self::$_values, $name, $value); } if (isset($config['debug']) && function_exists('ini_set')) { if (self::$_values['debug']) { ini_set('display_errors', 1); } else { ini_set('display_errors', 0); } } return true; }
/** * 新規登録の入力チェック用のバリデーションルールをセット * * @return bool */ private function __setValidateRequest() { $default = $this->__getDefaultData(); $userAttributes = $this->getUserAttribures(); $this->User->userAttributeData = $userAttributes; foreach ($userAttributes as $id => $userAttribute) { $key = Hash::get($userAttribute, 'UserAttribute.key'); $dataTypeKey = $userAttribute['UserAttributeSetting']['data_type_key']; $editable = Hash::get($userAttribute, 'UserAttributesRole.self_editable'); if ($editable) { continue; } if (!isset($userAttribute['UserAttributeChoice'])) { continue; } $model = $this->__getModel($userAttribute); //eメールは、確認を含める if ($dataTypeKey === DataType::DATA_TYPE_EMAIL) { if ($userAttribute['UserAttributeSetting']['required']) { $this->{$model}->validate[$key . '_again']['notBlank'] = array('rule' => array('notBlank'), 'allowEmpty' => false, 'message' => sprintf(__d('net_commons', 'Please input %s.'), __d('net_commons', 'Re-enter')), 'required' => true); } $this->{$model}->validate[$key . '_again']['equalToField'] = array('rule' => array('equalToField', $key), 'message' => __d('net_commons', 'The input data does not match. Please try again.'), 'allowEmpty' => false, 'required' => true); } //self_editable=falseものに対して、選択肢の初期値セットして登録する if (isset($default[$model][$key])) { $this->{$model}->validate[$key]['equalTo'] = array('rule' => array('equalTo', $default[$model][$key]), 'message' => __d('net_commons', 'Invalid request.'), 'allowEmpty' => true, 'required' => false); $this->User->userAttributeData[$id] = Hash::insert($this->User->userAttributeData[$id], 'UserAttributesRole.self_editable', true); $this->User->userAttributeData[$id] = Hash::insert($this->User->userAttributeData[$id], 'UserAttributeSetting.only_administrator_editable', false); } } }
/** * testBehaviorSaveCallbacks method * * @return void */ public function testBehaviorSaveCallbacks() { $Sample = new Sample(); $record = array('Sample' => array('apple_id' => 6, 'name' => 'sample99')); $Sample->Behaviors->attach('Test', array('beforeSave' => 'on')); $Sample->create(); $this->assertSame(false, $Sample->save($record)); $Sample->Behaviors->attach('Test', array('beforeSave' => 'off')); $Sample->create(); $result = $Sample->save($record); $expected = $record; $expected['Sample']['id'] = $Sample->id; $this->assertSame($expected, $result); $Sample->Behaviors->attach('Test', array('beforeSave' => 'test')); $Sample->create(); $result = $Sample->save($record); $expected = $record; $expected['Sample']['id'] = $Sample->id; $this->assertSame($expected, $result); $Sample->Behaviors->attach('Test', array('beforeSave' => 'modify')); $expected = Hash::insert($record, 'Sample.name', 'sample99 modified before'); $Sample->create(); $result = $Sample->save($record); $expected['Sample']['id'] = $Sample->id; $this->assertSame($expected, $result); $Sample->Behaviors->disable('Test'); $this->assertSame($record, $Sample->save($record)); $Sample->Behaviors->attach('Test', array('beforeSave' => 'off', 'afterSave' => 'on')); $expected = Hash::merge($record, array('Sample' => array('aftersave' => 'modified after on create'))); $Sample->create(); $result = $Sample->save($record); $expected['Sample']['id'] = $Sample->id; $this->assertEquals($expected, $result); $Sample->Behaviors->attach('Test', array('beforeSave' => 'modify', 'afterSave' => 'modify')); $expected = Hash::merge($record, array('Sample' => array('name' => 'sample99 modified before modified after on create'))); $Sample->create(); $result = $Sample->save($record); $expected['Sample']['id'] = $Sample->id; $this->assertSame($expected, $result); $Sample->Behaviors->attach('Test', array('beforeSave' => 'off', 'afterSave' => 'test')); $Sample->create(); $expected = $record; unset($expected['Sample']['name']); $result = $Sample->save($record); $expected['Sample']['id'] = $Sample->id; $this->assertSame($expected, $result); $Sample->Behaviors->attach('Test', array('afterSave' => 'test2')); $Sample->create(); $expected = $record; $result = $Sample->save($record); $expected['Sample']['id'] = $Sample->id; $this->assertSame($expected, $result); $Sample->Behaviors->attach('Test', array('beforeFind' => 'off', 'afterFind' => 'off')); $Sample->recursive = -1; $record2 = $Sample->read(null, 1); $Sample->Behaviors->attach('Test', array('afterSave' => 'on')); $expected = Hash::merge($record2, array('Sample' => array('aftersave' => 'modified after'))); $Sample->create(); $this->assertSame($expected, $Sample->save($record2)); $Sample->Behaviors->attach('Test', array('afterSave' => 'modify')); $expected = Hash::merge($record2, array('Sample' => array('name' => 'sample1 modified after'))); $Sample->create(); $this->assertSame($expected, $Sample->save($record2)); }
/** * Writes value to given session variable name. * * @param string|array $name Name of variable * @param string $value Value to write * @return bool True if the write was successful, false if the write failed */ public static function write($name, $value = null) { if (empty($name) || !self::start()) { return false; } $write = $name; if (!is_array($name)) { $write = array($name => $value); } foreach ($write as $key => $val) { self::_overwrite($_SESSION, Hash::insert($_SESSION, $key, $val)); if (Hash::get($_SESSION, $key) !== $val) { return false; } } return true; }
/** * Write a value to the $_COOKIE[$key]; * * Optional [Name.], required key, optional $value, optional $encrypt, optional $expires * $this->Cookie->write('[Name.]key, $value); * * By default all values are encrypted. * You must pass $encrypt false to store values in clear test * * You must use this method before any output is sent to the browser. * Failure to do so will result in header already sent errors. * * @param string|array $key Key for the value * @param mixed $value Value * @param boolean $encrypt Set to true to encrypt value, false otherwise * @param integer|string $expires Can be either the number of seconds until a cookie * expires, or a strtotime compatible time offset. * @return void * @link http://book.cakephp.org/2.0/en/core-libraries/components/cookie.html#CookieComponent::write */ public function write($key, $value = null, $encrypt = true, $expires = null) { if (empty($this->_values[$this->name])) { $this->read(); } if (is_null($encrypt)) { $encrypt = true; } $this->_encrypted = $encrypt; $this->_expire($expires); if (!is_array($key)) { $key = array($key => $value); } foreach ($key as $name => $value) { if (strpos($name, '.') === false) { $this->_values[$this->name][$name] = $value; $this->_write("[{$name}]", $value); } else { $names = explode('.', $name, 2); if (!isset($this->_values[$this->name][$names[0]])) { $this->_values[$this->name][$names[0]] = array(); } $this->_values[$this->name][$names[0]] = Hash::insert($this->_values[$this->name][$names[0]], $names[1], $value); $this->_write('[' . implode('][', $names) . ']', $value); } } $this->_encrypted = true; }
/** * Inserts $data into an array as defined by $path. * * @param array $list Where to insert into * @param string $path A dot-separated string. * @param array $data Data to insert * @return array * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::insert */ public static function insert($list, $path, $data = null) { return Hash::insert($list, $path, $data); }
/** * Tests that HttpSocket::request (the heart of the HttpSocket) is working properly. * * @return void */ public function testRequest() { $this->Socket->reset(); $response = $this->Socket->request(true); $this->assertFalse($response); $context = array('ssl' => array('verify_peer' => true, 'allow_self_signed' => false, 'verify_depth' => 5, 'CN_match' => 'www.cakephp.org', 'cafile' => CAKE . 'Config' . DS . 'cacert.pem')); $tests = array(array('request' => 'http://www.cakephp.org/?foo=bar', 'expectation' => array('config' => array('persistent' => false, 'host' => 'www.cakephp.org', 'protocol' => 'tcp', 'port' => 80, 'timeout' => 30, 'context' => $context, 'request' => array('uri' => array('scheme' => 'http', 'host' => 'www.cakephp.org', 'port' => 80), 'redirect' => false, 'cookies' => array())), 'request' => array('method' => 'GET', 'uri' => array('scheme' => 'http', 'host' => 'www.cakephp.org', 'port' => 80, 'user' => null, 'pass' => null, 'path' => '/', 'query' => array('foo' => 'bar'), 'fragment' => null), 'version' => '1.1', 'body' => '', 'line' => "GET /?foo=bar HTTP/1.1\r\n", 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\n", 'raw' => "", 'redirect' => false, 'cookies' => array(), 'proxy' => array(), 'auth' => array()))), array('request' => array('uri' => array('host' => 'www.cakephp.org', 'query' => '?foo=bar'))), array('request' => 'www.cakephp.org/?foo=bar'), array('request' => array('host' => '192.168.0.1', 'uri' => 'http://www.cakephp.org/?foo=bar'), 'expectation' => array('request' => array('uri' => array('host' => 'www.cakephp.org')), 'config' => array('request' => array('uri' => array('host' => 'www.cakephp.org')), 'host' => '192.168.0.1'))), 'reset4' => array('request.uri.query' => array()), array('request' => array('header' => array('Foo@woo' => 'bar-value')), 'expectation' => array('request' => array('header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nFoo\"@\"woo: bar-value\r\n", 'line' => "GET / HTTP/1.1\r\n"))), array('request' => array('header' => array('Foo@woo' => 'bar-value', 'host' => 'foo.com'), 'uri' => 'http://www.cakephp.org/'), 'expectation' => array('request' => array('header' => "Host: foo.com\r\nConnection: close\r\nUser-Agent: CakePHP\r\nFoo\"@\"woo: bar-value\r\n"), 'config' => array('host' => 'www.cakephp.org'))), array('request' => array('header' => "Foo: bar\r\n"), 'expectation' => array('request' => array('header' => "Foo: bar\r\n"))), array('request' => array('header' => "Foo: bar\r\n", 'uri' => 'http://www.cakephp.org/search?q=http_socket#ignore-me'), 'expectation' => array('request' => array('uri' => array('path' => '/search', 'query' => array('q' => 'http_socket'), 'fragment' => 'ignore-me'), 'line' => "GET /search?q=http_socket HTTP/1.1\r\n"))), 'reset8' => array('request.uri.query' => array()), array('request' => array('method' => 'POST', 'uri' => 'http://www.cakephp.org/posts/add', 'body' => array('name' => 'HttpSocket-is-released', 'date' => 'today')), 'expectation' => array('request' => array('method' => 'POST', 'uri' => array('path' => '/posts/add', 'fragment' => null), 'body' => "name=HttpSocket-is-released&date=today", 'line' => "POST /posts/add HTTP/1.1\r\n", 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\n", 'raw' => "name=HttpSocket-is-released&date=today"))), array('request' => array('method' => 'POST', 'uri' => 'http://www.cakephp.org:8080/posts/add', 'body' => array('name' => 'HttpSocket-is-released', 'date' => 'today')), 'expectation' => array('config' => array('port' => 8080, 'request' => array('uri' => array('port' => 8080))), 'request' => array('uri' => array('port' => 8080), 'header' => "Host: www.cakephp.org:8080\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\n"))), array('request' => array('method' => 'POST', 'uri' => 'https://www.cakephp.org/posts/add', 'body' => array('name' => 'HttpSocket-is-released', 'date' => 'today')), 'expectation' => array('config' => array('port' => 443, 'request' => array('uri' => array('scheme' => 'https', 'port' => 443))), 'request' => array('uri' => array('scheme' => 'https', 'port' => 443), 'header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\n"))), array('request' => array('method' => 'POST', 'uri' => 'https://www.cakephp.org/posts/add', 'body' => array('name' => 'HttpSocket-is-released', 'date' => 'today'), 'cookies' => array('foo' => array('value' => 'bar'))), 'expectation' => array('request' => array('header' => "Host: www.cakephp.org\r\nConnection: close\r\nUser-Agent: CakePHP\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 38\r\nCookie: foo=bar\r\n", 'cookies' => array('foo' => array('value' => 'bar')))))); $expectation = array(); foreach ($tests as $i => $test) { if (strpos($i, 'reset') === 0) { foreach ($test as $path => $val) { $expectation = Hash::insert($expectation, $path, $val); } continue; } if (isset($test['expectation'])) { $expectation = Hash::merge($expectation, $test['expectation']); } $this->Socket->request($test['request']); $raw = $expectation['request']['raw']; $expectation['request']['raw'] = $expectation['request']['line'] . $expectation['request']['header'] . "\r\n" . $raw; $r = array('config' => $this->Socket->config, 'request' => $this->Socket->request); $this->assertEquals($r, $expectation, 'Failed test #' . $i . ' '); $expectation['request']['raw'] = $raw; } $this->Socket->reset(); $request = array('method' => 'POST', 'uri' => 'http://www.cakephp.org/posts/add', 'body' => array('name' => 'HttpSocket-is-released', 'date' => 'today')); $response = $this->Socket->request($request); $this->assertEquals("name=HttpSocket-is-released&date=today", $this->Socket->request['body']); }
/** * Provides a read/write accessor for `$this->data`. Allows you * to use a syntax similar to `CakeSession` for reading post data. * * ## Reading values. * * `$request->data('Post.title');` * * When reading values you will get `null` for keys/values that do not exist. * * ## Writing values * * `$request->data('Post.title', 'New post!');` * * You can write to any value, even paths/keys that do not exist, and the arrays * will be created for you. * * @param string $name,... Dot separated name of the value to read/write * @return mixed Either the value being read, or this so you can chain consecutive writes. */ public function data($name) { $args = func_get_args(); if (count($args) == 2) { $this->data = Hash::insert($this->data, $name, $args[1]); return $this; } return Hash::get($this->data, $name); }
/** * 管理者の承認確認 * * @return void **/ public function acceptance() { //ウィザードのリンク削除 $this->helpers['NetCommons.Wizard']['navibar'] = Hash::remove($this->helpers['NetCommons.Wizard']['navibar'], '{s}.url'); $this->helpers['NetCommons.Wizard']['navibar'] = Hash::insert($this->helpers['NetCommons.Wizard']['navibar'], self::WIZARD_COMPLETION . '.label', array('auth', 'Approval completion.')); $result = $this->AutoUserRegist->saveUserStatus($this->request->query, AutoUserRegist::CONFIRMATION_ADMIN_APPROVAL); if ($result) { $message = __d('auth', 'hank you for your registration.<br>' . 'We have sent you the registration key to your registered e-mail address.'); $this->set('message', $message); $this->set('options', array()); $this->set('redirectUrl', '/'); $user = $this->User->find('first', array('recursive' => -1, 'conditions' => array('id' => $this->request->query['id']))); $user = Hash::merge($user, $result); $this->AutoUserRegistMail->sendMail(AutoUserRegist::CONFIRMATION_USER_OWN, $user); } else { $this->view = 'acceptance'; return $this->__setValidationError(); } }