Beispiel #1
0
 public function afterFind($results, $primary = false)
 {
     if (!empty($results)) {
         $braintreePlans = Braintree_Plan::all();
         foreach ($results as $resultKey => $result) {
             if (isset($result['BillingPlan']) && !empty($result['BillingPlan'])) {
                 foreach ($result['BillingPlan'] as $key => $plan) {
                     $_arr = array();
                     $_arr[0]['BillingPlan'] = $plan;
                     $_arr = Hash::extract($this->BillingPlan->decodeItems($_arr), "0.BillingPlan");
                     foreach ($_arr['remote_plans'] as $remotePlan) {
                         foreach ($braintreePlans as $braintreePlan) {
                             if ($remotePlan == $braintreePlan->id) {
                                 $_arr['BraintreePlan'][] = $braintreePlan;
                             }
                         }
                     }
                     $result['BillingPlan'][$key] = $_arr;
                 }
             }
             $results[$resultKey] = $result;
         }
     }
     return $results;
 }
Beispiel #2
0
 public function subsections($mark_id, $model_id, $type_id)
 {
     $aCatalog = Hash::combine($this->TechDocApi->getMarks(), '{n}.id', '{n}');
     $mark = $aCatalog[$mark_id];
     $this->set('mark', $mark);
     unset($aCatalog);
     $aModels = Hash::combine($this->TechDocApi->getModels($mark_id), '{n}.id', '{n}');
     $model = $aModels[$model_id];
     $this->set('model', $model);
     unset($aModels);
     $aSubModels = Hash::combine($this->TechDocApi->getModelSections($mark_id, $model_id), '{n}.id', '{n}');
     $submodel = $aSubModels[$type_id];
     $this->set('submodel', $aSubModels[$type_id]);
     unset($aSubModels);
     $aSubsections = $this->TechDocApi->getModelSubsections($mark_id, $model_id, $type_id);
     $this->set('aSubsections', $aSubsections);
     $title = $mark['title'] . ' ' . $model['title'] . ' ' . $submodel['type'] . ' ' . $model['date_issue'];
     $this->seo = array('title' => $title, 'keywords' => "Каталог запчастей для {$title}, запчасти для {$title}", 'descr' => "На нашем сайте вы можете приобрести лучшие запчасти {$title} в Белорусии. Низкие цены на запчасти, быстрая доставка по стране, диагностика, ремонт.");
     // Сохраняем осн.узлы для того, чтобы навесить картинки
     $this->loadModel('Subsection');
     $this->Subsection->saveMainSubsections($aSubsections);
     // получаем список узлов с картинками
     $ids = Hash::extract($aSubsections, '{n}.id');
     $conditions = array('Subsection.td_id' => $ids, 'Media.main' => 1);
     $order = 'Subsection.td_id';
     $subsections = $this->Subsection->find('all', compact('conditions', 'order'));
     $this->set('subsections', $subsections);
 }
 /**
  * beforeRender
  *
  * @param Controller $controller Controller
  * @return void
  * @throws NotFoundException
  */
 public function beforeRender(Controller $controller)
 {
     //RequestActionの場合、スキップする
     if (!empty($controller->request->params['requested']) || $controller->request->is('ajax')) {
         return;
     }
     //Pluginデータ取得
     $controller->Plugin = ClassRegistry::init('PluginManager.Plugin', true);
     $controller->PluginsRole = ClassRegistry::init('PluginManager.PluginsRole', true);
     $controlPanel = $controller->Plugin->create(array('key' => 'control_panel', 'name' => __d('control_panel', 'Control Panel Top'), 'default_action' => 'control_panel/index'));
     $this->plugins = $controller->PluginsRole->getPlugins(array(Plugin::PLUGIN_TYPE_FOR_SITE_MANAGER, Plugin::PLUGIN_TYPE_FOR_SYSTEM_MANGER), Current::read('User.role_key'), 'INNER');
     array_unshift($this->plugins, $controlPanel);
     //Layoutのセット
     $controller->layout = 'ControlPanel.default';
     //cancelUrlをセット
     $controller->set('cancelUrl', '/');
     $controller->set('isControlPanel', true);
     $controller->set('hasControlPanel', true);
     //ページHelperにセット
     $controller->set('pluginsMenu', $this->plugins);
     if (isset($this->settings['plugin'])) {
         $plugin = $this->settings['plugin'];
     } else {
         $plugin = $controller->params['plugin'];
     }
     $plugin = Hash::extract($this->plugins, '{n}.Plugin[key=' . $plugin . ']');
     if (isset($plugin[0]['name'])) {
         if (!isset($controller->viewVars['title'])) {
             $controller->set('title', $plugin[0]['name']);
         }
         $controller->set('pageTitle', $plugin[0]['name']);
     }
 }
 /**
  * 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;
 }
 /**
  * Attach promo Adjustment
  * @see PromoAdjustmentBehavior
  * @param $controller
  */
 protected function enablePromotions($controller)
 {
     if (in_array($controller->request->params['action'], $this->cartActions)) {
         if (isset($controller->ShoppingCartItem)) {
             App::import('Model', 'PromotionalProduct');
             App::import('Model', 'SystemSetting');
             /**
              * Get Promos
              */
             $this->promos = $this->loadPromos();
             // Load without cache
             $settings = ['promos' => [], 'className' => 'PromoItems'];
             foreach ($this->promos as $promo) {
                 /**
                  * Setup settings for Promo
                  */
                 $settings['promos'][] = ['id' => $promo['PromotionalProduct']['id'], 'qualifying_sku' => Hash::extract($promo, 'QualifyingProduct.{n}.sku'), 'reward_sku' => $promo['PromotionalProduct']['reward_sku'], 'reward_type' => $promo['PromotionalProduct']['promotional_product_type_id'], 'qty' => $promo['PromotionalProduct']['qty']];
             }
             /**
              * Load Promo
              */
             if (empty($controller->request->data['market_id'])) {
                 $settings['market_id'] = $controller->Session->read('market_id');
             } else {
                 $settings['market_id'] = $controller->request->data['market_id'];
             }
             $controller->ShoppingCartItem->Behaviors->load('PromoItems', $settings);
         }
     }
 }
Beispiel #6
0
 public function render($form, $values, $offset = 0)
 {
     $html = '';
     $_values = array();
     if ($values) {
         $_values = array_combine(Hash::extract($values, '{n}.PMFormValue.field_id'), Hash::extract($values, '{n}.PMFormValue.value'));
     }
     $_ids = array();
     if ($values) {
         $_ids = array_combine(Hash::extract($values, '{n}.PMFormValue.field_id'), Hash::extract($values, '{n}.PMFormValue.id'));
     }
     foreach ($form as $i => $row) {
         $field = $row['FormField'];
         $value = Hash::get($_values, $field['id']);
         /*
         if ($field['id'] == 6) {
         	fdebug($field);
         	fdebug(array_merge(
         		$this->_options($i, 'value'), $this->_inputOptions($field), array('value' => $value)
         	));
         }
         */
         $html .= $this->_renderInput($field, $value, $i + $offset);
         if (isset($_values[$field['id']])) {
             $html .= $this->PHForm->hidden('PMFormValue.id', array_merge($this->_options($i + $offset, 'id'), array('value' => Hash::get($_ids, $field['id']))));
         }
         $html .= $this->PHForm->hidden('PMFormValue.field_id', array_merge($this->_options($i + $offset, 'field_id'), array('value' => $field['id'])));
     }
     return $html;
 }
Beispiel #7
0
 public function index($parent_id = '')
 {
     // Process filter
     if ($user_id = $this->request->query('user_id')) {
         $this->paginate['conditions']['user_id'] = $user_id;
     }
     $status = $this->request->query('status');
     if ($status != '') {
         $this->paginate['conditions']['status'] = $status;
     }
     $id = $this->request->query('id');
     if ($id) {
         if (strpos($id, ',') !== false) {
             $id = explode(',', $id);
         }
         $this->paginate['conditions']['id'] = $id;
     }
     $rowset = parent::index();
     $ids = Hash::extract($rowset, '{n}.Order.id');
     $orders = $this->Order->getOrder($ids);
     $ids = Hash::extract($rowset, '{n}.Order.user_id');
     $users = Hash::combine($this->User->findAllById($ids), '{n}.User.id', '{n}.User');
     $aUserOptions = $this->User->find('list', array('fields' => array('id', 'username')));
     $this->set(compact('orders', 'users', 'aUserOptions'));
 }
 /**
  * http://developers.facebook.com/docs/reference/api/page/#lifeevents
  **/
 public function milestones($pageId, $options = array())
 {
     $request = array();
     $limit = 15;
     if ($options) {
         $request['uri']['query'] = $options;
     }
     if (isset($options['limit'])) {
         $limit = $options['limit'];
     }
     $trace = debug_backtrace();
     $data = $this->_request(sprintf('/%s/%s', $pageId, $trace[0]['function']), $request);
     $results = array();
     $count = 0;
     foreach ($data['data'] as $k => $val) {
         $results['data'][$k] = $val;
         $photos = $this->milestonePhotos($val['id']);
         $results['data'][$k]['photos'] = Hash::extract($photos['data'], '{n}.source');
         $count++;
         if ($count == $limit) {
             break;
         }
     }
     return $results;
 }
 /**
  * Filter Audits by user id of model
  * @param $conditions
  */
 private function userFilters(&$conditions)
 {
     $model = $this->request->query['model'];
     $user_id = $this->request->query['user_id'];
     $entity_ids = null;
     if (!empty($user_id) && !empty($model)) {
         switch ($model) {
             case 'UserOauth2':
                 $entity_ids = $this->UserOauth2->find('all', ['fields' => 'id', 'conditions' => ['user_id' => $user_id]]);
                 break;
             case 'Email':
                 $entity_ids = $this->Email->find('all', ['fields' => 'id', 'conditions' => ['user_id' => $user_id]]);
                 break;
             case 'Address':
                 $entity_ids = $this->Address->find('all', ['fields' => 'id', 'conditions' => ['user_id' => $user_id]]);
                 break;
             default:
                 break;
         }
         if (!empty($entity_ids)) {
             $entity_ids = Hash::extract($entity_ids, "{n}.{$model}.id");
             $conditions["Audit.entity_id"] = $entity_ids;
         }
     }
 }
 /**
  * edit
  *
  * @param string $roleKey user_roles.key
  * @return void
  */
 public function edit($roleKey = null)
 {
     if ($this->request->isPut()) {
         //不要パラメータ除去
         $data = $this->data;
         unset($data['save']);
         //登録処理
         if ($this->UserRoleSetting->saveUserRoleSetting($data)) {
             //正常の場合
             $this->redirect('/user_roles/user_roles/index/');
             return;
         }
         $this->NetCommons->handleValidationError($this->UserRoleSetting->validationErrors);
         $this->request->data = $data;
     } else {
         $this->request->data = $this->UserRoleSetting->find('first', array('recursive' => -1, 'conditions' => array('role_key' => $roleKey)));
         $this->request->data['UserRoleSetting']['is_usable_room_manager'] = (bool) $this->PluginsRole->find('count', array('recursive' => -1, 'conditions' => array('role_key' => $roleKey, 'plugin_key' => 'rooms')));
     }
     //既存データ取得
     $userRole = $this->UserRole->find('first', array('recursive' => -1, 'conditions' => array('type' => UserRole::ROLE_TYPE_USER, 'key' => $roleKey, 'language_id' => Configure::read('Config.languageId'))));
     $this->request->data = Hash::merge($userRole, $this->request->data);
     if ($plugin = Hash::extract($this->ControlPanelLayout->plugins, '{n}.Plugin[key=rooms]')) {
         $this->set('roomsPluginName', $plugin[0]['name']);
     } else {
         $this->set('roomsPluginName', __d('user_roles', 'Room manager'));
     }
     $this->set('roleKey', $roleKey);
     $this->set('subtitle', $this->request->data['UserRole']['name']);
 }
 /**
  * Profile command
  * 
  * @param string $command
  * @return array
  */
 public function profileCommand($command)
 {
     $tasks = $this->Task->find('all', array('conditions' => array('command' => $command, 'status' => array(TaskType::STOPPED, TaskType::FINISHED), 'runtime >' => 0), 'fields' => array('runtime', 'id', 'started', 'stopped', 'created', 'waittime'), 'limit' => Configure::read('Task.profilerLimit'), 'order' => array('id' => 'DESC')));
     if (!$tasks) {
         return null;
     }
     $statistics = array_map(function ($item) {
         $endDate = new DateTime($item['stopped']);
         $startDate = new DateTime($item['started']);
         $createdDate = new DateTime($item['created']);
         $item['runtimeHuman'] = $startDate->diff($endDate)->format(Configure::read('Task.dateDiffFormat'));
         $item['waittimeHuman'] = $createdDate->diff($startDate)->format(Configure::read('Task.dateDiffFormat'));
         $item['startedTimestamp'] = $startDate->getTimestamp();
         $item['runtime'] = (int) $item['runtime'];
         $item['waittime'] = (int) $item['waittime'];
         return $item;
     }, Hash::extract($tasks, '{n}.{s}'));
     $runtimes = Hash::extract($statistics, '{n}.runtime');
     $runtimeAverage = (int) round($runtimes ? array_sum($runtimes) / count($runtimes) : 0);
     $runtimeMax = $runtimes ? max($runtimes) : 0;
     $runtimeMin = $runtimes ? min($runtimes) : 0;
     $waittimes = Hash::extract($statistics, '{n}.waittime');
     $waittimeAverage = (int) round($waittimes ? array_sum($waittimes) / count($waittimes) : 0);
     $waittimeMax = $waittimes ? max($waittimes) : 0;
     $waittimeMin = $waittimes ? min($waittimes) : 0;
     $countByStatus = array();
     foreach (TaskType::getTypes() as $statusCode) {
         $countByStatus[$statusCode] = $this->Task->find('count', array('conditions' => array('command' => $command, 'status' => $statusCode)));
     }
     $errored = $this->Task->find('count', array('conditions' => array('command' => $command, 'errored' => true)));
     return array('command' => $command, 'countByStatus' => $countByStatus, 'errored' => $errored, 'statistics' => $statistics, 'runtimeAverage' => $runtimeAverage, 'runtimeAverageHuman' => $this->_secondsToHuman($runtimeAverage), 'runtimeMax' => $runtimeMax, 'runtimeMaxHuman' => $this->_secondsToHuman($runtimeMax), 'runtimeMin' => $runtimeMin, 'runtimeMinHuman' => $this->_secondsToHuman($runtimeMin), 'waittimeAverage' => $waittimeAverage, 'waittimeAverageHuman' => $this->_secondsToHuman($waittimeAverage), 'waittimeMax' => $waittimeMax, 'waittimeMaxHuman' => $this->_secondsToHuman($waittimeMax), 'waittimeMin' => $waittimeMin, 'waittimeMinHuman' => $this->_secondsToHuman($waittimeMin));
 }
 public function testAfterFind()
 {
     $result = $this->User->find('first');
     $this->assertTrue(!array_key_exists('password', $result[$this->User->alias]));
     $result = $this->User->find('all');
     $this->assertEmpty(Hash::extract($result, '{n}.' . $this->User->alias . '.password'));
 }
 public function block()
 {
     try {
         $order_id = $this->request->data('order_id');
         if (!$order_id) {
             throw new Exception(__('Incorrect request'));
         }
         $products = $this->request->data('products');
         if ($products && !is_array($products)) {
             throw new Exception(__('Incorrect request'));
         }
         $blocked = $this->request->data('blocked');
         if ($products) {
             foreach ($products as $product_id) {
                 $this->OrderProduct->updateAll(compact('blocked'), compact('order_id', 'product_id'));
             }
         }
         $products = $this->OrderProduct->getByTypes($order_id, false);
         $distributed = $this->OrderProduct->getByTypes($order_id, true);
         $aID = Hash::extract($distributed, '{n}.{n}.OrderProduct.user_id');
         $users = $this->User->getUsers($aID);
         $this->setResponse(compact('products', 'distributed', 'users'));
     } catch (Exception $e) {
         $this->setError($e->getMessage());
     }
 }
 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;
 }
 /**
  * mirror action
  *
  * @param null $slug
  *
  * @throws NotFoundException
  * @return void
  */
 function mirror($slug = null)
 {
     $this->PluginsState->recursive = -1;
     $cloning_count = $this->PluginsState->find('count', array('conditions' => array('PluginsState.ip_address' => $this->request->clientIp(false))));
     if ($cloning_count >= Configure::read('App.max_cloning_per_ip')) {
         $this->Session->setFlash(__('You have reached the maximum of %s plugins queued for cloning currently, please try again later.', Configure::read('App.max_cloning_per_ip')), 'alert-warning', array('close' => true));
         $this->redirect($this->referer());
     }
     $plugin = $this->Plugin->find('first', array('contain' => array('PluginsState' => array('State')), 'conditions' => array('slug' => $slug)));
     // Some basic sanity checks...
     if (!$plugin) {
         throw new NotFoundException(__('Invalid plugin'));
     }
     if (in_array('cloned', Hash::extract($plugin, 'PluginsState.{n}.State.name'))) {
         $this->Session->setFlash(__('This plugin has already been cloned.'), 'alert-error', array('close' => true));
         $this->redirect($this->referer());
     }
     if (in_array('cloning', Hash::extract($plugin, 'PluginsState.{n}.State.name'))) {
         $this->Session->setFlash(__('This plugin is already in the cloning queue.'), 'alert-error', array('close' => true));
         $this->redirect($this->referer());
     }
     if ($this->PluginsState->findOrCreate($plugin['Plugin']['id'], 'cloning', $this->request->clientIp(false))) {
         $this->Session->setFlash(__('Plugin has been added to the queue to be cloned.'), 'alert-success', array('close' => true));
         $this->redirect($this->referer());
     }
     $this->Session->setFlash(__('There was a problem adding the plugin to the cloning queue.'), 'alert-error', array('close' => true));
     $this->redirect($this->referer());
 }
 public function edit($id = 0, $parent_id = '')
 {
     parent::edit($id, $parent_id);
     // find all groups of params by category of product
     $product = $this->Product->findById($this->parent_id);
     $cat_id = $product['Product']['parent_id'];
     $conditions = array('parent_id' => $cat_id, 'featured' => 1);
     $order = 'sorting';
     $aParamGroups = $this->ParamGroup->find('all', compact('conditions', 'order'));
     $aParamGroups = Hash::combine($aParamGroups, '{n}.ParamGroup.id', '{n}');
     $this->set('aFormGroups', $aParamGroups);
     // find all params by groups
     $conditions = array('object_type' => 'PMFormField', 'parent_id' => array_keys($aParamGroups));
     $order = 'sorting';
     $aParams = $this->PMFormField->find('all', compact('conditions', 'order'));
     if ($aParams) {
         $ids = Hash::extract($aParams, '{n}.PMFormField.id');
         $aParams = Hash::combine($aParams, '{n}.PMFormField.id', '{n}', '{n}.PMFormField.parent_id');
     }
     $this->set('aForms', $aParams);
     // get all values of params
     $aValues = array();
     if ($this->request->is(array('put', 'post'))) {
         $aValues = $this->request->data('PMFormValue');
     } elseif ($id) {
         $aValues = $this->PMFormValue->getValues('ProductPackParam', $id);
     }
     $this->set('aValues', $aValues);
 }
Beispiel #17
0
 /**
  * Clone model's data.
  *
  * @param Model $Model
  * @param array $options
  * @return [type]
  */
 public function duplicate(Model $Model, $data, $config = array())
 {
     $config = array_merge($this->settings[$Model->alias], $config);
     if (empty($Model->id) && empty($data[$Model->alias][$Model->primaryKey])) {
         throw new Exception(__d('common', "Missing primary key for duplicatable '%s' data", $Model->name));
     }
     $id = $Model->id ? $Model->id : $data[$Model->alias][$Model->primaryKey];
     $conditions = array($Model->primaryKey => $id) + (array) $this->settings[$Model->alias]['scope'];
     if (!empty($this->settings[$Model->alias]['scope']) && !$Model->find('count', compact('conditions'))) {
         return false;
     }
     $duplicateData = array($config['duplicatedKey'] => $id, $config['duplicatedModel'] => (!empty($Model->plugin) ? $Model->plugin . '.' : '') . $Model->name);
     $DuplicateModel = ClassRegistry::init($config['model']);
     $DuplicateModel->create();
     $duplicateRecord = $DuplicateModel->find('first', array('conditions' => $duplicateData, 'recursive' => -1));
     if (!empty($duplicateRecord)) {
         $DuplicateModel->id = $duplicateRecord[$DuplicateModel->alias][$DuplicateModel->primaryKey];
     }
     foreach ((array) $config['mapFields'] as $field => $path) {
         $value = Hash::extract($data, $path);
         $duplicateData[$field] = array_pop($value);
         if (!empty($duplicateRecord[$DuplicateModel->alias][$field]) && $duplicateRecord[$DuplicateModel->alias][$field] === $duplicateData[$field]) {
             unset($duplicateData[$field]);
         }
     }
     if ((empty($duplicateRecord) || 1 < count($duplicateData)) && (!empty($DuplicateModel->id) || $DuplicateModel->create($duplicateData)) && !$DuplicateModel->save()) {
         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;
 }
Beispiel #19
0
 public static function getWidgetData($uniqueId)
 {
     $optionName = Configure::read('template') . '.widgets';
     $sidebarsWidgets = unserialize(Configure::read($optionName));
     $getAllData = Hash::extract($sidebarsWidgets, '{s}.' . $uniqueId);
     return array_slice($getAllData[0], 0, count($getAllData[0]) - 3);
 }
 /**
  * Process presenter related table and ids into
  * presenter ids.
  *
  * @param $data
  * @return array|null
  */
 private function processOrders($data)
 {
     $order_ids = [];
     foreach ($data as $table => $ids) {
         switch ($table) {
             case 'orders':
                 $this->addIds($order_ids, $ids);
                 break;
             case 'order_customers':
                 $orders = $this->Order->find('all', ['fields' => ['Order.id'], 'joins' => [['table' => 'order_customers', 'alias' => 'oc', 'type' => 'INNER', 'conditions' => ['oc.order_id = Order.id']]], 'conditions' => ['oc.id' => $ids]]);
                 $oids = Hash::extract($orders, '{n}.Order.id');
                 $this->addIds($order_ids, $oids);
                 break;
             case 'order_items':
                 $orders = $this->Order->find('all', ['fields' => ['Order.id'], 'joins' => [['table' => 'order_customers', 'alias' => 'oc', 'type' => 'INNER', 'conditions' => ['oc.order_id = Order.id']], ['table' => 'order_items', 'alias' => 'oi', 'type' => 'INNER', 'conditions' => ['oi.order_customer_id = oc.id']]], 'conditions' => ['oi.id' => $ids]]);
                 $oids = Hash::extract($orders, '{n}.Order.id');
                 $this->addIds($order_ids, $oids);
                 break;
             case 'order_shipments':
                 $orders = $this->Order->find('all', ['fields' => ['Order.id'], 'joins' => [['table' => 'order_shipments', 'alias' => 'os', 'type' => 'INNER', 'conditions' => ['os.order_id = Order.id']]], 'conditions' => ['os.id' => $ids]]);
                 $oids = Hash::extract($orders, '{n}.Order.id');
                 $this->addIds($order_ids, $oids);
         }
     }
     return $order_ids;
 }
Beispiel #21
0
 /**
  * Deletes the last Progression row for the specified Task and updates the Task's progress
  * column with the resulting total Progression sum.
  *
  * @param int $taskId
  * @return bool|number
  */
 public function deleteLast($taskId)
 {
     // Get the last Progression
     $data = $this->find('first', array('conditions' => array('Progression.task_id' => $taskId), 'order' => array('Progression.created DESC'), 'limit' => 1, 'recursive' => -1));
     if ($data) {
         $dataSource = $this->getDataSource();
         // Begin the transaction
         $dataSource->begin();
         // Flag to indicate a commit
         $commit = true;
         // Revert the Task progress
         if (!$this->Task->updateAll(array('Task.progress' => "Task.progress - {$data['Progression']['delta']}"), array('Task.id' => $taskId))) {
             $commit = false;
         }
         // Delete the Progression
         $this->id = $data['Progression']['id'];
         if (!$this->delete()) {
             $commit = false;
         }
         // Update associated Achievement statuses
         $task = $this->Task->find('first', array('conditions' => array('Task.id' => $taskId), 'fields' => array('Task.id'), 'contain' => array('Goal' => array('fields' => array('Goal.id', 'Goal.achievement_id')))));
         // Update each Achievement's status
         if (!$task || !$this->Task->Goal->Achievement->setComplete(Hash::extract($task, 'Goal.{n}[achievement_id>0].achievement_id'))) {
             $commit = false;
         }
         // End the transaction
         if ($commit) {
             $dataSource->commit();
             return array('task_id' => $taskId, 'progression_total' => $this->Task->getProgressions($taskId));
         } else {
             $dataSource->rollback();
         }
     }
     return false;
 }
 public function read_index()
 {
     $querystring_params = $this->request->query;
     $search_term = !empty($querystring_params['q']) ? $querystring_params['q'] : false;
     $collections = array();
     $collectionItems = array();
     $collectionItemFields = array();
     $users = array();
     $limit = 5;
     $collection_id = !empty($querystring_params['collection_id']) ? $querystring_params['collection_id'] : null;
     $user_id = !empty($querystring_params['user_id']) ? $querystring_params['user_id'] : null;
     if ($search_term) {
         // TODO: multiple paginations (one for each group searched -> paging simulated in view; 'show more' leads to page with more results for particular type of search
         $collections = $this->Collections->readSearch($search_term, $limit);
         $collectionItems = $this->CollectionItems->readSearch($search_term, $collection_id, $limit);
         if (!empty($collectionItems)) {
             $itemCollections = $this->Collections->readList(array_unique(Hash::extract($collectionItems, '{n}.CollectionItem.collection_id')), true);
             $itemCollections = Hash::combine($itemCollections, '{n}.Collection.id', '{n}');
             foreach ($collectionItems as &$item) {
                 $item = array_merge($item, $itemCollections[$item['CollectionItem']['collection_id']]);
             }
         }
         $collectionItemFields = $this->CollectionItemFields->readSearch($search_term, $collection_id, $limit);
         $users = $this->Users->readSearch($search_term, $limit);
         $availabilityLegend = $this->CollectionItems->readAvailabilityLegend();
         $this->set('q', $search_term);
         $this->set('collections', $collections);
         $this->set('collectionItems', $collectionItems);
         $this->set('collectionItemFields', $collectionItemFields);
         $this->set('users', $users);
         $this->set('availabilityLegend', $availabilityLegend);
     }
 }
 /**
  * Take a comma seperated list of id's and save them in the matching order
  *
  * @param Controller $controller
  */
 public function startup(Controller $controller)
 {
     parent::startup($controller);
     $postedRanks = Hash::extract($controller->request->data, '{s}.updated-ranks');
     if ($controller->request->is('post') && !empty($postedRanks)) {
         $ranks = explode(',', $postedRanks[0]);
         $i = 0;
         foreach ($ranks as $order => $rowId) {
             $data[$i][$this->settings['model']][$this->settings['field']] = $rowId;
             $data[$i][$this->settings['model']][$this->settings['sortField']] = $order + 1;
             // As arrays count from 0, but our ranks count from 1
             $i++;
         }
         $element = 'default';
         if ($this->settings['useNiceAdmin']) {
             $element = 'NiceAdmin.alert-box';
         }
         $controller->loadModel($this->settings['model']);
         if ($controller->{$this->settings['model']}->saveAll($data, array('validate' => false))) {
             $controller->Session->setFlash($this->settings['model'] . ' order updated', $element, array('class' => 'alert-success'));
             $controller->redirect($controller->referer());
         } else {
             $controller->Session->setFlash($this->settings['model'] . ' order could not be updated, please try again', $element, array('class' => 'alert-error'));
         }
     }
 }
 /**
  * Called after the Controller::beforeFilter() and before the controller action
  *
  * @param Controller $controller Controller with components to startup
  * @return void
  * @link http://book.cakephp.org/2.0/en/controllers/components.html#Component::startup
  */
 public function startup(Controller $controller)
 {
     //RequestActionの場合、スキップする
     if (!empty($controller->request->params['requested'])) {
         return;
     }
     $this->controller = $controller;
     //Modelの呼び出し
     $this->Plugin = ClassRegistry::init('PluginManager.Plugin');
     //Pluginデータ取得
     $this->plugins = $this->Plugin->getPlugins(Plugin::PLUGIN_TYPE_FOR_CONTROL_PANEL, $this->controller->viewVars['languageId']);
     //Layoutのセット
     $this->controller->layout = 'ControlPanel.default';
     //cancelUrlをセット
     $this->controller->set('cancelUrl', '/');
     $this->controller->set('isControlPanel', true);
     $this->controller->set('hasControlPanel', true);
     //ページHelperにセット
     $this->controller->set('pluginsMenu', $this->plugins);
     if (isset($this->settings['plugin'])) {
         $plugin = $this->settings['plugin'];
     } else {
         $plugin = $this->controller->params['plugin'];
     }
     $plugin = Hash::extract($this->plugins, '{n}.Plugin[key=' . $plugin . ']');
     if (isset($plugin[0]['name']) && !isset($this->controller->viewVars['title'])) {
         $this->controller->set('title', $plugin[0]['name']);
     }
 }
Beispiel #25
0
 /**
  * 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;
 }
 /**
  * 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;
 }
 /**
  * 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;
 }
Beispiel #28
0
 public function admin_add($id = null)
 {
     $this->loadModel('Revista.Edition');
     $edicao_id = null;
     if (isset($this->request->params['named']['edicao'])) {
         $result = $this->Edition->findById($this->request->params['named']['edicao']);
         if ($result) {
             $edicao_id = $result['Edition']['id'];
         }
     }
     if ($this->request->is('post') || $this->request->is('put')) {
         if (empty($this->request->data['Artigo']['weight'])) {
             $result = $this->Artigo->find('all', array('conditions' => array('Artigo.edicao_id' => $edicao_id), 'order' => 'Artigo.weight DESC', 'limit' => 1));
             if (!empty($result)) {
                 $weight = Hash::extract($result, '{n}.Artigo.weight');
                 $this->request->data['Artigo']['weight'] = $weight[0] + 1;
             }
         }
         if (isset($this->request->data['Artigo']['arquivo']['tmp_name']) && $this->request->data['Artigo']['arquivo']['tmp_name']) {
             if ($this->_upload($this->request->data['Artigo'])) {
                 $this->request->data['Artigo']['arquivo'] = $this->request->data['Artigo']['arquivo']['name'];
             }
         } else {
             unset($this->request->data['Artigo']['arquivo']);
         }
         if ($this->Artigo->save($this->request->data)) {
             $this->Session->setFlash('Artigo cadastrado com sucesso', 'default', array('class' => 'success'));
             $this->redirect(array('action' => 'admin_index', 'edicao' => $edicao_id));
         }
     }
     if ($this->request->is('get')) {
         $this->request->data = $this->Artigo->read(null, $id);
     }
     $this->set('edicao_id', $edicao_id);
 }
Beispiel #29
0
 /**
  * Выдает список статей по подписке пользователя 
  *  
  * @param int $userId 
  * @return array
  */
 public function getUserSubcsribedArticles($userId)
 {
     $this->loadModel('Api.ApiArticleEvent');
     $subscriptionListGroup = $this->Subscription->find('list', array('fields' => array('Subscription.object_id'), 'conditions' => array('Subscription.subscriber_id' => $userId, 'Subscription.type' => $this->getGroupType())));
     $subscriptionListUser = $this->Subscription->find('list', array('fields' => array('Subscription.object_id'), 'conditions' => array('Subscription.subscriber_id' => $userId, 'Subscription.type' => $this->getUserType())));
     if (!$subscriptionListGroup and !$subscriptionListUser) {
         return array();
     }
     $this->loadModel('Article');
     $this->Article->bindModel(array('belongsTo' => array('ArticleCategory' => array('className' => 'ArticleCategory', 'foreignKey' => 'cat_id'))));
     $orCondtions = array();
     if ($subscriptionListUser) {
         $orCondtions[] = array('Article.group_id' => NULL, 'Article.owner_id' => $subscriptionListUser);
     }
     if ($subscriptionListGroup) {
         $orCondtions[] = array('Article.group_id' => $subscriptionListGroup);
     }
     $fields = array('Article.id', 'Article.title', 'Article.cat_id', 'Article.created', 'ArticleCategory.title', 'ArticleMedia.*');
     $conditions = array('Article.published' => 1, 'OR' => $orCondtions);
     $order = array('Article.created DESC');
     $limit = 25;
     $articles = $this->Article->find('all', compact('conditions', 'fields', 'order', 'limit'));
     $articleIds = Hash::extract($articles, '{n}.Article.id');
     $this->commentsCount = $this->ApiArticleEvent->getCommentsCount($articleIds);
     $result = $this->formatUserSubcsribedArticles($articles);
     return $result;
 }
 /**
  * Returns an array of workderIds of blocked user for mobileWorks
  */
 public function getBlockedUserWorkerIds()
 {
     if (!$this->User) {
         $this->loadModel('User');
     }
     // get a array of all banned users
     return Hash::extract($this->User->findAllByBanned(1), '{n}.User.workerid');
 }