Exemple #1
0
 function _targetMode_NodeRef(&$eventOptions, $params)
 {
     if (array_key_exists('target', $params) && array_key_exists('field', $params)) {
         $localOpt = array('target', 'modelName');
         $defParams = array('target' => null, 'modelName' => false, 'field' => null);
         $opt = array_merge($defParams, $params);
         $this->Node = ClassRegistry::init('Node');
         $nOpt = array('fields' => array('foreign_key', 'model'));
         if (!empty($opt['modelName'])) {
             $nOpt['conditions']['Node.model'] = $opt['modelName'];
         }
         $nodes = $this->Node->getNodes($opt['target'], $nOpt);
         if ($opt['field'] == 'id') {
             return Set::extract('{n}.Node.foreign_key');
         } else {
             App::import('Lib', 'SetMulti');
             $nodes = SetMulti::group($nodes, 'Node.model', array('valPath' => 'Node.foreign_key'));
             $targets = array();
             foreach ($nodes as $model => $keys) {
                 $subOpt = array_diff_key($opt, array_flip($localOpt));
                 $subOpt['target'] = $keys;
                 $subOpt['modelName'] = $model;
                 $targets = array_merge($targets, $this->_targetMode_ForeignKey($eventOptions, $subOpt));
             }
             return $targets;
         }
     }
     return array();
 }
Exemple #2
0
 function applyOperation($op, $val, $parseString = false)
 {
     //debug($op);
     $_this =& Operations::getInstance();
     if ($parseString && is_string($op)) {
         $op = $_this->parseStringOperation($op);
     }
     $opOpt = $_this->getOperator($op);
     if ($opOpt) {
         App::import('Lib', 'SetMulti');
         //debug($opOpt);
         $params = SetMulti::extractHierarchicMulti($opOpt['named'], $op);
         //debug($params);
         $directParams = SetMulti::pregFilterKey('/^[0-9]+$/', $op);
         //debug($directParams);
         $params = $directParams + $params;
         array_unshift($params, $val);
         //debug($params);
         if (isset($opOpt['function']) && $opOpt['function'] === true) {
             $funct = array($_this, '_op_' . $opOpt['name']);
         } elseif (!empty($opOpt['function'])) {
             $funct = $opOpt['function'];
         }
         if (!empty($funct) && is_callable($funct)) {
             return call_user_func_array($funct, $params);
         }
     }
     return null;
 }
 function byCountry($options, $supplementItem, $order, $supplement_choice, $calcul)
 {
     $defOpt = array('keyPath' => array('order.ShopOrder.shipping_country', 'settings.defaultCountry'), 'subMethod' => null, 'modifProp' => 'total', 'list' => array());
     if (!count(array_intersect_key($options, $defOpt))) {
         $options = array('list' => $options);
     }
     $opt = array_merge($defOpt, $options);
     App::import('Lib', 'Shop.ShopConfig');
     $settings = ShopConfig::load();
     $dataSource = array('settings' => $settings, 'order' => $order, 'calcul' => $calcul);
     App::import('Lib', 'Shop.SetMulti');
     $country = SetMulti::extractHierarchic($opt['keyPath'], $dataSource);
     $val = null;
     if (array_key_exists($country, $opt['list'])) {
         $val = $opt['list'][$country];
     } else {
         App::import('Lib', 'O2form.Geography');
         $continent = Geography::getContinent($country);
         if (array_key_exists($continent, $opt['list'])) {
             $val = $opt['list'][$continent];
         } elseif (array_key_exists('default', $opt['list'])) {
             $val = $opt['list']['default'];
         }
     }
     if (!is_null($val)) {
         if (!empty($opt['subMethod'])) {
             return $this->calculFunct($opt['subMethod'], $val, $supplementItem, $order, $supplement_choice, $calcul);
         }
         $supplementItem[$opt['modifProp']] = $val;
     }
     return $supplementItem;
 }
Exemple #4
0
 function setFieldCache(&$model, $name, $opt = null)
 {
     if (is_null($opt)) {
         $opt = $name;
     } else {
         $opt['name'] = $name;
     }
     $reset = false;
     $localOpt = array('dry', 'association', 'usedField');
     App::import('Lib', 'SetMulti');
     if (!empty($opt['association'])) {
         if (!is_array($opt['association']) || SetMulti::isAssoc($opt['association'])) {
             $opt['association'] = array($opt['association']);
         }
         foreach ($opt['association'] as $assoc) {
             $fieldOpt = array_diff_key($opt, array_flip($localOpt));
             $fieldOpt['association'] = $assoc;
             if (isset($fieldOpt['association']) && !is_array($fieldOpt['association'])) {
                 $fieldOpt['association'] = array('name' => $fieldOpt['association']);
             }
             $fieldOpt = Set::merge($this->defFieldOpt, $fieldOpt);
             if (!empty($fieldOpt['name'])) {
                 if (isset($model->{$fieldOpt['association']['type']}[$fieldOpt['association']['name']])) {
                     $fieldOpt['association'] = Set::merge($model->{$fieldOpt['association']['type']}[$fieldOpt['association']['name']], $fieldOpt['association']);
                 }
                 if (empty($fieldOpt['association']['className'])) {
                     $fieldOpt['association']['className'] = $fieldOpt['association']['name'];
                 }
                 if (!empty($fieldOpt['association']['className'])) {
                     $className = $fieldOpt['association']['className'];
                     $fieldOpt['model'] = $model->name;
                     $invalidations = Cache::read($className, 'cacheBehavior');
                     //debug($fieldOpt);
                     if (empty($invalidations[$model->name][$fieldOpt['name']]) || count(array_diff_assoc($invalidations[$model->name][$fieldOpt['name']], $fieldOpt))) {
                         $reset = true;
                         $invalidations[$model->name][$fieldOpt['name']] = $fieldOpt;
                         Cache::write($className, $invalidations, 'cacheBehavior');
                     }
                 }
             }
         }
     }
     if (!empty($opt['usedField'])) {
         $invalidations = Cache::read($model->name, 'cacheBehavior');
         $invalidations['usedField'][$opt['name']] = (array) $opt['usedField'];
         Cache::write($model->name, $invalidations, 'cacheBehavior');
     }
     if (empty($opt['dry'])) {
         if ($reset) {
             $model->updateAll(array($fieldOpt['name'] => null), 1);
         }
         return true;
     } elseif ($reset) {
         return $fieldOpt['name'];
     }
     return false;
 }
 function editForm($prefix, $view)
 {
     $out = '';
     $out .= $view->Form->input('val', array('label' => __('Rebate', true)));
     App::import('Lib', 'Shop.SetMulti');
     $this->ShopPromotion = ClassRegistry::init('Shop.ShopPromotion');
     $operators = $this->ShopPromotion->operators;
     $out .= $view->Form->input('operator', array('options' => SetMulti::extractKeepKey('label', $operators)));
     return $out;
 }
 function mergeFindOpt($opt)
 {
     $options = func_get_args();
     array_shift($options);
     App::import('Lib', 'Newsletter.SetMulti');
     foreach ($options as $opt2) {
         $opt = SetMulti::merge2($opt, $opt2);
     }
     return $opt;
 }
Exemple #7
0
 function extractHierarchicMulti($pathsAssoc, $data = null, $options = array())
 {
     $defaultOptions = array('extractNull' => true);
     $options = array_merge($defaultOptions, $options);
     $res = array();
     foreach ($pathsAssoc as $name => $paths) {
         $val = SetMulti::extractHierarchic($paths, $data, $options);
         if (!is_null($val) || $options['extractNull']) {
             $res[$name] = $val;
         }
     }
     return $res;
 }
Exemple #8
0
 function getTargetHandlers($named = false)
 {
     App::import('Lib', 'ClassCollection');
     App::import('Lib', 'SetMulti');
     $class = ClassCollection::getClass('handler', 'Skills');
     $methods = get_class_methods($class);
     $targetHandlers = SetMulti::pregFilter('/^target\\w*$/', $methods);
     //debug($targetHandlers);
     if ($named) {
         $list = array();
         foreach ($targetHandlers as $handler) {
             $list[$handler] = Inflector::humanize(Inflector::underscore($handler));
         }
         $targetHandlers = $list;
     }
     return $targetHandlers;
 }
Exemple #9
0
 function beforeFind(&$model, $queryData)
 {
     $postprocess = $this->settings[$model->alias]['delete'] || $this->settings[$model->alias]['disable'];
     if ($this->checkLifetime($model) && (!empty($queryData['fields']) || !empty($queryData['limit']) || !$postprocess)) {
         $ef = $this->settings[$model->alias]['end_field'];
         $neededfields = array('id', $ef);
         if ($this->settings[$model->alias]['allways_postprocess']) {
             if (empty($queryData['fields'])) {
                 foreach ($neededfields as $needed) {
                     if (!count(array_intersect($queryData['fields'], array($needed, $model->alias . '.' . $needed)))) {
                         $queryData['fields'][] = $model->alias . '.' . $needed;
                         break;
                     }
                 }
             }
         } else {
             $postprocess = $postprocess && empty($queryData['limit']);
             if ($postprocess) {
                 foreach ($neededfields as $needed) {
                     if (!count(array_intersect((array) $queryData['fields'], array($needed, $model->alias . '.' . $needed)))) {
                         $postprocess = false;
                         break;
                     }
                 }
             }
             if (!$postprocess) {
                 // postprocess impossible or insecure
                 $time = $this->_getQueryTime(&$model);
                 $sf = $this->settings[$model->alias]['start_field'];
                 $timeout = $this->settings[$model->alias]['timeout'];
                 App::import('Lib', 'SetMulti');
                 if ($model->hasField($sf) && (empty($queryData['conditions']) || !count(SetMulti::pregFilterKey('/' . $sf . '/', $queryData['conditions'])))) {
                     $queryData['conditions'][] = array('or' => array($model->alias . '.' . $sf . ' IS NULL', $model->alias . '.' . $sf . ' <=' => $time));
                 }
                 if ($model->hasField($ef) && (empty($queryData['conditions']) || !count(SetMulti::pregFilterKey('/' . $ef . '/', $queryData['conditions'])))) {
                     $queryData['conditions'][] = array('or' => array($model->alias . '.' . $ef . ' IS NULL', $model->alias . '.' . $ef . ' >=' => $this->_modifTime($model, $time, -$timeout)));
                 }
             }
         }
     }
     return $queryData;
 }
Exemple #10
0
 function getOpt($name)
 {
     if (!empty($this->cache[$name])) {
         return $this->cache[$name];
     }
     $extract = array('typeId' => 'id', 'inheritParent' => 'inherit_parent', 'recursive_links' => 'recursive_links', 'globalLinks' => 'global_links', 'excludeModels' => 'exclude_models');
     $findOpt = array('conditions' => array(), 'recursive' => -1);
     if (is_numeric($name)) {
         $findOpt['conditions']['id'] = $name;
     } else {
         $findOpt['conditions']['name'] = $name;
     }
     $type = $this->find('first', $findOpt);
     App::import('Lib', 'SetMulti');
     $opt = SetMulti::extractHierarchicMulti($extract, $type[$this->alias], array('extractNull' => false));
     $this->cache[$type[$this->alias]['name']] = $opt;
     $this->cache[$type[$this->alias]['id']] = $opt;
     //debug($opt);
     return $opt;
 }
Exemple #11
0
 function addItems($items)
 {
     //debug($items);
     if (!empty($items)) {
         foreach ($items as $modelName => $model) {
             App::import('Lib', 'SetMulti');
             if (!Set::numeric(array_keys(SetMulti::excludeKeys($model, array('internal'))))) {
                 $model = array($model);
             }
             if (array_key_exists('internal', $model)) {
                 if (empty($this->items[$modelName]['internal'])) {
                     $this->items[$modelName]['internal'] = array();
                 }
                 $this->items[$modelName]['internal'] = array_merge($this->items[$modelName]['internal'], $model['internal']);
                 unset($model['internal']);
             }
             foreach ($model as $item) {
                 $this->items[$modelName][] = $item;
             }
         }
         $this->controller->Link->addLoadedItems($items);
     }
 }
 function testCond($cond, $data, $or = false, $empty = false)
 {
     $valid = true;
     $def = $empty;
     $modifKeys = array('and', 'or');
     App::import('Lib', 'Operations');
     foreach ($cond as $key => $cnd) {
         $op = false;
         $path = $key;
         if (is_numeric($path)) {
             $val = $data;
         } elseif (in_array($path, $modifKeys)) {
             $val = $data;
         } elseif (array_key_exists($path, $data)) {
             $val = $data[$path];
         } else {
             $op = Operations::parseStringOperation($path, array('mode' => 'left', 'type' => 'bool', 'sepPattern' => '\\h+'));
             if ($op) {
                 $path = $op['subject'];
             }
             $val = Set::Extract($path, $data);
         }
         if ($op) {
             $op['subject'] = $val;
             $op['val'] = $cnd;
             $valid = Operations::applyOperation($op);
         } elseif (is_null($cnd)) {
             $valid = is_null($val);
         } elseif (is_array($cnd)) {
             $or = $path == 'or';
             $valid = SetMulti::testCond($cnd, $val, $or);
         } elseif (!is_null($data)) {
             $valid = $val == $cnd;
         } else {
             $valid = false;
         }
         if ($valid == $or) {
             return $or;
         }
         $def = $valid;
     }
     return $def;
 }
 function alterEmailQuery($opt)
 {
     $Model = $this->EmailModel;
     $modelName = $Model->alias;
     if (!empty($opt)) {
         $NewsletterEmail = ClassRegistry::init('Newsletter.NewsletterEmail');
         App::import('Lib', 'Newsletter.SetMulti');
         $replace = array($NewsletterEmail->alias . '.email' => $this->realField('email'), $NewsletterEmail->alias => $modelName);
         $opt = SetMulti::replaceTree(array_keys($replace), array_values($replace), $opt);
     }
     $conditions = array();
     if (!empty($opt['active']) || !isset($opt['active']) && !$this->options['showInnactive']) {
         if ($opt['mode'] != 'count' && $this->options['checkUnsubscribe']) {
             $NewsletterEmail = ClassRegistry::init('Newsletter.NewsletterEmail');
             $opt['joins'][] = array('alias' => $NewsletterEmail->alias, 'table' => $NewsletterEmail->useTable, 'type' => 'LEFT', 'conditions' => array($this->realField('email') . ' = ' . $NewsletterEmail->alias . '.email'));
             $conditions[] = array('or' => array($NewsletterEmail->alias . '.active' => 1, $NewsletterEmail->alias . '.id IS NULL'));
         }
         if (!empty($this->options['fields']['active']) && $Model->hasField($this->options['fields']['active'])) {
             $conditions[$this->realField('active')] = 1;
         }
     }
     $conditions['NOT'][$this->realField('email')] = "";
     $conditions[] = $this->realField('email') . ' IS NOT NULL';
     if (!empty($this->options['conditions'])) {
         if (!array($this->options['conditions'])) {
             $this->options['conditions'] = array($this->options['conditions']);
         }
         $conditions = set::merge($conditions, $this->options['conditions']);
     }
     $opt['conditions'][] = $conditions;
     if ((empty($opt['mode']) || $opt['mode'] != 'count') && empty($opt['fields'])) {
         $opt['fields'] = $this->emailFields();
     }
     if (!empty($this->options['findOptions']) && is_array($this->options['findOptions'])) {
         $opt = set::merge($opt, $this->options['findOptions']);
     }
     return $opt;
 }
Exemple #14
0
 function updatePathing($id = null)
 {
     if (empty($id)) {
         $id = $this->id;
     }
     $this->Behaviors->attach('Containable');
     $data = $this->find('first', array('conditions' => array($this->alias . '.id' => $id), 'contain' => array('Tile' => array('Node'), 'StructureType', 'Node')));
     debug($data);
     $pathingData = $data['StructureType']['pathing'];
     //$pathingData = array('4x4'=>10);<
     $this->Event = ClassRegistry::init('Event');
     $this->Event->recursive = -1;
     $existing = $this->Event->find('all', array('conditions' => array('phase' => 1, 'context' => 'Pathing', 'owner_id' => $data['Node']['id'])));
     debug($existing);
     $toDelete = array();
     foreach ($existing as $event) {
         $ekey = $event['Event']['aco_id'] . ':' . $event['Event']['event_type_id'];
         if (empty($toDelete[$ekey])) {
             $toDelete[$ekey] = $event['Event'];
         } else {
             $toDelete[] = $event['Event'];
         }
     }
     //debug($toDelete);
     if (!empty($pathingData)) {
         foreach ($tmp = $pathingData as $key => $val) {
             if (strpos($key, 'x') !== false) {
                 list($w, $h) = explode('x', $key, 2);
                 for ($x = 0; $x < $w; $x++) {
                     for ($y = 0; $y < $h; $y++) {
                         $pathingData[$x . ';' . $y] = $val;
                     }
                 }
                 unset($pathingData[$key]);
             } elseif (strpos($key, ';') === false) {
                 unset($pathingData[$key]);
             }
         }
         $maxX = $maxY = 0;
         foreach ($pathingData as $key => $val) {
             list($x, $y) = explode(';', $key, 2);
             $maxX = max($maxX, $x);
             $maxY = max($maxY, $y);
         }
         if ($maxX > 0 || $maxY > 0) {
             $tiles = $this->Tile->getRect(array('w' => $maxX + 1, 'h' => $maxY + 1, 'centerTile' => $data['Tile'], 'aliased' => true));
         } else {
             $tiles = array('0;0' => $data['Tile']);
         }
         debug($tiles);
         $events = array();
         App::import('Lib', 'SetMulti');
         foreach ($pathingData as $key => $val) {
             if (isset($tiles[$key])) {
                 foreach ((array) $val as $t) {
                     $event = array('aro_id' => null, 'aco_id' => SetMulti::extractHierarchic(array('Node.id', 'Tile.Node.id'), $tiles[$key]), 'handler' => 'false', 'event_type_id' => $t, 'phase' => 1, 'active' => 1, 'context' => 'Pathing', 'owner_id' => $data['Node']['id']);
                     $exist = false;
                     $ekey = $event['aco_id'] . ':' . $event['event_type_id'];
                     if (!empty($toDelete[$ekey])) {
                         $exist = $toDelete[$ekey];
                         unset($toDelete[$ekey]);
                     }
                     if ($exist && count(array_diff_assoc($event, $exist)) > 0) {
                         $exist = false;
                     }
                     if (!$exist) {
                         $events[] = $event;
                     }
                 }
             }
         }
         //debug($toDelete);
         debug($events);
         foreach ($events as $event) {
             $this->Event->create();
             $this->Event->save($event);
         }
         foreach ($toDelete as $event) {
             $this->Event->delete($event['id']);
         }
         $pathing = array();
     }
 }
Exemple #15
0
 function updateSearchTable(&$Model, $id = null, $data = array(), $created = false)
 {
     if (empty($id)) {
         $id = $Model->id;
     }
     if (!empty($id)) {
         if (empty($data)) {
             $data = $Model->data;
         }
         if (empty($data)) {
             $data = $Model->read(null, $id);
         }
         if (!empty($data['SearchTable'])) {
             $search_data = $data['SearchTable'];
         }
         if (isset($data[$Model->alias]['active'])) {
             $search_data['active'] = $data[$Model->alias]['active'];
         } elseif (!$Model->hasField('active')) {
             $search_data['active'] = 1;
         }
         $plugin = $Model->searchOptions['plugin'];
         $model = $Model->alias;
         if (!$created) {
             $Model->SearchTable->recursive = -1;
             $cond = array('model' => $model, 'foreign_id' => $id);
             if (!is_null($plugin)) {
                 if (empty($plugin)) {
                     $cond['plugin'] = null;
                 } else {
                     $cond['plugin'] = $plugin;
                 }
             }
             $searchTable = $Model->SearchTable->find('first', array('conditions' => $cond));
             if ($searchTable) {
                 /****** UPDATE ******/
                 $search_data['id'] = $searchTable['SearchTable']['id'];
                 $plugin = $searchTable['SearchTable']['plugin'];
             } else {
                 $created = true;
             }
         }
         if ($created) {
             /****** ADD ******/
             if (is_null($plugin)) {
                 $parent_class = get_parent_class($model);
                 if ($parent_class != 'AppModel') {
                     if (preg_match("/^([\\w]+)AppModel\$/", $parent_class, $matches)) {
                         $plugin = $matches[1];
                     }
                 }
             }
             $search_data['foreign_id'] = $id;
             if (empty($plugin)) {
                 $search_data['plugin'] = null;
             } else {
                 $search_data['plugin'] = $plugin;
             }
             $search_data['model'] = $model;
             $data[$Model->alias]['id'] = $id;
         }
         $modelName = implode('.', array_filter(array($plugin, $model)));
         /****** Calculate title ******/
         $paths = (array) $Model->searchOptions['title'];
         App::import('Lib', 'Search.SetMulti');
         foreach ($Model->searchOptions['langs'] as $lang) {
             $l_paths = $this->_addBasePath($this->_addLangPath($paths, $lang), $model);
             $search_data['title_' . $lang] = SetMulti::extractHierarchic($l_paths, $data);
             $search_data['title_for_search_' . $lang] = $Model->SearchTable->cleanSearchData($search_data['title_' . $lang]);
         }
         /****** Calculate desc ******/
         $paths = (array) $Model->searchOptions['desc'];
         foreach ($Model->searchOptions['langs'] as $lang) {
             $l_paths = $this->_addBasePath($this->_addLangPath($paths, $lang), $model);
             $search_data['content_' . $lang] = SetMulti::extractHierarchic($l_paths, $data);
         }
         /****** Calculate content for search ******/
         $paths = (array) $Model->searchOptions['content'];
         foreach ($Model->searchOptions['langs'] as $lang) {
             $l_paths = $this->_addBasePath($this->_addLangPath($paths, $lang), $model);
             $search_data['content_for_search_' . $lang] = implode(' ', $Model->SearchTable->cleanSearchData(array_filter(SetMulti::extractMulti($l_paths, $data))));
         }
         /****** Calculate URL ******/
         $urlData = array('plugin' => Inflector::underscore($plugin), 'controller' => Inflector::tableize($model), 'id' => $id);
         foreach ($Model->searchOptions['langs'] as $lang) {
             $l_urlData = $urlData;
             $l_urlData['lang'] = $lang;
             $url = $Model->searchOptions['url'];
             if (is_array($url)) {
                 foreach ($url as $paramName => &$param) {
                     preg_match("/{([\\w]+)}/", $param, $matches);
                     if (!empty($matches)) {
                         $srch = $matches[0];
                         $dname = $matches[1];
                         $rep = '';
                         if (!empty($l_urlData[$dname])) {
                             $rep = $l_urlData[$dname];
                         }
                         $param = str_replace($srch, $rep, $param);
                     }
                     if (empty($param) && !in_array($paramName, $Model->searchOptions['urlKeepEmpty'])) {
                         unset($url[$paramName]);
                     }
                 }
             }
             if (method_exists($Model, 'search_url')) {
                 $res = $Model->search_url($url, $data, $lang);
                 if (is_array($res) || is_string($res)) {
                     $url = $res;
                 }
             }
             $base = Router::url('/');
             $search_data['link_' . $lang] = preg_replace('/^' . preg_quote($base, '/') . '/', '/', Router::url($url));
         }
         /****** Calculate type ******/
         foreach ($Model->searchOptions['langs'] as $lang) {
             if (empty($Model->searchOptions['type'])) {
                 $search_data['type_' . $lang] = $this->_translate($lang, $model);
             } elseif (is_array($Model->searchOptions['type'])) {
                 $search_data['type_' . $lang] = $Model->searchOptions['type'][$lang];
             } else {
                 $search_data['type_' . $lang] = $Model->searchOptions['type'];
             }
         }
         /****** SAVE ******/
         $Model->SearchTable->create();
         //debug($search_data);
         $Model->SearchTable->save($search_data);
     }
 }
Exemple #16
0
 function getInvalidationData($nodes)
 {
     $this->load();
     $opts = array('inheritParent' => false, 'mode' => 'all', 'fields' => array('id', 'model', 'foreign_key'), 'conditions' => array('model NOT' => null), 'order' => 'model');
     $NodeLink = ClassRegistry::init('NodeLink');
     $Invalidation = ClassRegistry::init('Invalidation');
     /*if(!empty($this->loadedItems)){
     			//reset($this->loadedItems);
     			//$minTime = current($this->loadedItems);
     			//debug($minTime);
     			$loadedCond = array();
     			foreach($this->loadedItems as $node_id => $time){
     				$loadedCond[] = array(
     					$Invalidation->alias.'.node_id'=>$node_id,
     					$Invalidation->alias.'.time >'=>$time
     				);
     			}
     			$opts = set::merge($opts,array(
     				'fields' => Array(
     					"GROUP_CONCAT(IFNULL (".$Invalidation->alias.".field,'all')) AS Fields"
     				),
     				'joins' => array('1000-invalidation'=>array(
     					'type'=>'left',
     					'table'=>$Invalidation->useTable,
     					'alias' =>$Invalidation->alias,
     					'conditions' => array(
     						$Invalidation->alias.'.node_id = AllNode.id',
     						array('or'=>$loadedCond)
     					)
     				)),
     				'conditions' => array(
     					array('or'=>array(
     							$Invalidation->alias.'.node_id IS NOT NULL',
     							'not'=>array('AllNode.id'=>array_keys($this->loadedItems))
     					))
     				)
     			));
     		}*/
     //debug($opts);
     $allNodes = $NodeLink->getLinked($nodes, 'invalidation', $opts);
     //debug($allNodes);
     if (!empty($allNodes)) {
         /////////// Get invalidations ///////////
         App::import('Lib', 'SetMulti');
         $allNodeId = $this->_getAllNodeIds($allNodes);
         $excludeCheck = array();
         $invalids = array();
         if (!$this->disableCache) {
             $excludeCheck = array_intersect_key($this->loadedItems, array_flip($allNodeId));
             $bydate = SetMulti::flip($excludeCheck);
             //debug($bydate);
             $findOpt = array('fields' => array($Invalidation->alias . '.id', $Invalidation->alias . '.node_id'));
             foreach ($bydate as $time => $nids) {
                 $findOpt['conditions']['or'][] = array($Invalidation->alias . '.node_id' => $nids, $Invalidation->alias . '.time >' => $time);
             }
             $invalids = $Invalidation->find('all', $findOpt);
             if (!empty($invalids)) {
                 $invalids = SetMulti::group($invalids, $Invalidation->alias . '.node_id');
             }
         }
         //debug($invalids);
         //debug($excludeCheck);
         /////////// remove unneeded ///////////
         $toGet = array();
         foreach ($allNodes as $node) {
             $nid = $node['Node']['id'];
             if ((!isset($excludeCheck[$nid]) || isset($invalids[$nid])) && !empty($node['Node']['model'])) {
                 $model = $node['Node']['model'];
                 if (empty($toGet[$model])) {
                     $toGet[$model] = array('ids' => array(), 'globalFields' => 'all', 'fields' => array());
                 }
                 $id = $node['Node']['foreign_key'];
                 $toGet[$model]['ids'][] = $id;
                 $toGet[$model]['fields'][$id] = 'all';
             }
         }
         //debug($toGet);
         $aro = array($this->controller->User->myNodeRef($this->controller->user['User']['id']));
         //debug($aro);
         $allItems = array();
         foreach ($toGet as $modelName => $opt) {
             $model = ClassRegistry::init($modelName);
             $model->create();
             $findOptions = array('conditions' => array($model->alias . '.id' => $opt['ids']));
             if ($opt['globalFields'] != 'all') {
                 $findOptions['restrict'] = $opt['globalFields'];
             }
             //debug($findOptions);
             $items = $model->triggerAction('linkRead', array($findOptions), $aro);
             if (!empty($items)) {
                 $allItems = array_merge($allItems, $items);
             }
         }
         //debug($allItems);
         return $allItems;
     }
     return null;
 }
Exemple #17
0
 function beforeSave()
 {
     $named = isset($this->data[$this->name]);
     if ($named) {
         $data = $this->data[$this->name];
     } else {
         $data = $this->data;
     }
     if (isset($data['id'])) {
         $id = $data['id'];
     } else {
         $id = $this->id;
     }
     if (!empty($data['use_shipping'])) {
         if (!empty($data['shipping_address'])) {
             $shipping_data = $data;
         } elseif (!empty($id)) {
             $shipping_data = $this->read(null, $id);
             $shipping_data = $shipping_data[$this->name];
         }
         if (!empty($shipping_data)) {
             $prefix_from = "shipping_";
             $prefix_to = "billing_";
             foreach ($shipping_data as $key => $val) {
                 if (substr($key, 0, strlen($prefix_from)) == $prefix_from) {
                     $sufix = substr($key, strlen($prefix_from));
                     //if(empty($data[$prefix_to.$sufix])){
                     $data[$prefix_to . $sufix] = $shipping_data[$key];
                     //}
                 }
             }
         }
     }
     if (!empty($data['use_billing'])) {
         if (!empty($data['billing_address'])) {
             $billing_data = $data;
         } elseif (!empty($id)) {
             $billing_data = $this->read(null, $id);
             $billing_data = $billing_data[$this->name];
         }
         if (!empty($billing_data)) {
             $prefix_from = "billing_";
             $prefix_to = "shipping_";
             foreach ($billing_data as $key => $val) {
                 if (substr($key, 0, strlen($prefix_from)) == $prefix_from) {
                     $sufix = substr($key, strlen($prefix_from));
                     //if(empty($data[$prefix_to.$sufix])){
                     $data[$prefix_to . $sufix] = $billing_data[$key];
                     //}
                 }
             }
         }
     }
     App::import('Lib', 'Shop.SetMulti');
     $both_keys = SetMulti::pregFilterKey('/^both_/', $data);
     foreach ($both_keys as $key => $val) {
         $key = preg_replace('/^both_/', '', $key);
         if (empty($data["billing_" . $key])) {
             $data["billing_" . $key] = $val;
         }
         if (empty($data["shipping_" . $key])) {
             $data["shipping_" . $key] = $val;
         }
     }
     $fieldsToAlias = array('billing_country' => 'country', 'billing_region' => 'region', 'shipping_country' => 'country', 'shipping_region' => 'region');
     App::import('lib', 'Shop.Alias');
     $data = Alias::applyAliasMulti($data, $fieldsToAlias);
     if ($named) {
         $this->data = array($this->name => $data);
     } else {
         $this->data = $data;
     }
     return true;
 }
 function _parse_xls_cols($filePath)
 {
     if (file_exists($filePath)) {
         App::import('Vendor', 'Newsletter.php-ofc-library', array('file' => 'php-ofc-library/open-flash-chart.php'));
         App::import('Vendor', 'Newsletter.PHPExcel', array('file' => 'PHPExcel/IOFactory.php'));
         $objPHPExcel = PHPExcel_IOFactory::load($filePath);
         $objWorksheet = $objPHPExcel->getActiveSheet();
         $highestRow = $objWorksheet->getHighestRow();
         $highestColumn = $objWorksheet->getHighestColumn();
         $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
         /////////////// cols config ///////////////
         $langs = Configure::read('languages');
         $fieldsAlias = array('first_name' => array("first name", "firstname", "prenom"), 'last_name' => array("last name", "lastname", "nom", "nom de famille"), 'email' => array("email", "mail", "courriel"));
         $fieldsCharAlias = array("é" => "e", "è" => "e", "ê" => "e", "_" => " ", "-" => " ");
         $fieldGess = array('email' => '/^[\\w-]+@([\\w-]+\\.)+[\\w-]+$/', 'phone' => '/^\\(?[0-9]{3}\\)?[-\\s]?[0-9]{3}[-\\s]?[0-9]{4}$/', 'sex' => '/^(f|m)$/i', 'name' => '/^[a-z\\s-]+$/i');
         $fields = $this->NewsletterSendlist->NewsletterEmail->schema();
         unset($fields['id'], $fields['created'], $fields['modified'], $fields['sendlist_id']);
         $fields = array_merge(array('first_name' => array(), 'last_name' => array()), $fields);
         $defFieldsAlias = array();
         $fieldsList = array();
         foreach ($fields as $f => $opt) {
             $fieldsList[$f] = __(Inflector::humanize($f), true);
             $defFieldsAlias[$f] = array($f);
             $langTmp = Configure::read('Config.language');
             foreach ($langs as $l) {
                 Configure::write('Config.language', 'Config.language', $l);
                 if (!in_array(__($f, true), $defFieldsAlias[$f])) {
                     $defFieldsAlias[$f][] = __($f, true);
                 }
                 if (!in_array(__d('newsletter', $f, true), $defFieldsAlias[$f])) {
                     $defFieldsAlias[$f][] = __d('newsletter', $f, true);
                 }
             }
             Configure::write('Config.language', $langTmp);
         }
         unset($defFieldsAlias['active']);
         $fieldsAlias = array_merge($defFieldsAlias, $fieldsAlias);
         //debug($fieldsAlias);
         $fieldGess = array_intersect_key($fieldGess, $fieldsAlias);
         //debug($fieldGess);
         /////////////// Test first row ///////////////
         $first_row = array();
         for ($col = 0; $col <= $highestColumnIndex; ++$col) {
             $cell = $objWorksheet->getCellByColumnAndRow($col, 1)->getValue();
             $cell = mb_strtolower($cell);
             $cell = str_replace(array_keys($fieldsCharAlias), array_values($fieldsCharAlias), $cell);
             $first_row[$col] = $cell;
         }
         //debug($first_row);
         $cols_fields = array_flip($first_row);
         App::import('Lib', 'Newsletter.SetMulti');
         $cols_fields = SetMulti::extractHierarchicMulti($fieldsAlias, $cols_fields);
         $cols_fields = SetMulti::filterNot($cols_fields, 'is_null');
         $title_row = !empty($cols_fields);
         /////////////// Test data ///////////////
         $tmpGess = array_diff_key($fieldGess, $cols_fields);
         if (!empty($cols_fields['first_name'])) {
             unset($tmpGess['name']);
         }
         for ($i = 0; $i < 50 && !empty($tmpGess) && $i < $highestRow; $i++) {
             $row = $this->_get_xls_row($objWorksheet, $i + 1 + $title_row);
             //debug($row);
             foreach ($tmpGess as $f => $exp) {
                 foreach ($row as $col => $val) {
                     if (!in_array($col, $cols_fields)) {
                         if (preg_match($exp, $val)) {
                             unset($tmpGess[$f]);
                             $cols_fields[$f] = $col;
                             break;
                         }
                     }
                 }
             }
         }
         $cols_fields = array_flip($cols_fields);
         /////////////// teaser ///////////////
         $teaser = array();
         for ($i = 0; $i < 15 && $i < $highestRow; $i++) {
             $row = $this->_get_xls_row($objWorksheet, $i + 1);
             $teaser[] = $row;
         }
         //debug($cols_fields);
         return array('cols' => $cols_fields, 'fields' => $fieldsList, 'showFirst' => !$title_row, 'teaser' => $teaser);
     }
     return null;
 }
 function getFilter($options)
 {
     $defOpt = array('models' => array('CustomFilterCond' => array('field', 'val1', 'type'), 'CustomFilterGroup' => array('group' => 'title', 'group_key' => 'key'), 'CustomFilter'), 'override' => array(), 'default' => array());
     $opt = Set::merge($defOpt, $options);
     $data = $this->_optionsToFormatedData($opt, $defOpt);
     $override = $this->_optionsToFormatedData($opt['override'], $defOpt);
     $default = $this->_optionsToFormatedData($opt['default'], $defOpt);
     if (empty($data[$this->alias]['model'])) {
         return null;
     }
     App::import('Lib', 'CustomFilter.SetMulti');
     //debug($data);
     $key = empty($data['CustomFilter']['key']) ? null : $data['CustomFilter']['key'];
     if ($key) {
         $findOpt = array('conditions' => array('CustomFilter.key' => $key), 'recursive' => -1);
         $override = SetMulti::complexMerge($data, $override, 2);
     } else {
         $findOpt = array('conditions' => Set::flatten(array_diff_key($data, array_flip(array('CustomFilterCond')))), 'contain' => 'CustomFilterGroup');
         if (!empty($data['CustomFilterCond'])) {
             $findOpt['conditions']['CustomFilter.cond_count'] = count($data['CustomFilterCond']);
             foreach ($data['CustomFilterCond'] as $i => $cond) {
                 $a = 'CustomFilterCond' . $i;
                 $join = array('alias' => $a, 'table' => $this->CustomFilterCond->useTable, 'type' => 'INNER', 'conditions' => Set::flatten(array($a => $cond)));
                 $join['conditions'][] = 'CustomFilter.id = ' . $a . '.custom_filter_id';
                 $findOpt['joins'][] = $join;
             }
         }
         //debug($findOpt);
     }
     $existing = $this->find('first', $findOpt);
     if ($existing) {
         $filter = $existing;
     }
     if (empty($existing) || !empty($override)) {
         $filter = $default;
         if ($existing) {
             $filter = SetMulti::complexMerge($filter, $existing, 2);
         } else {
             $filter = SetMulti::complexMerge($filter, $data, 2);
         }
         $filter = SetMulti::complexMerge($filter, $override, 2);
         //debug($filter);
         $this->create();
         if ($this->save($filter)) {
             return $this->id;
         }
     } else {
         return $existing['CustomFilter']['id'];
     }
 }
Exemple #20
0
 function updateDataNow(&$model, $data, $time = null, $options = array())
 {
     App::import('Lib', 'SetMulti');
     if (empty($data)) {
         return $data;
     }
     if (is_array($time)) {
         $options = $time;
     } else {
         $options['time'] = $time;
     }
     $defOpt = array('time' => null, 'belongsTo' => array());
     $opt = array_merge($options, $defOpt);
     if (empty($opt['time'])) {
         $opt['time'] = mktime();
     }
     ////// Normalize Data //////
     //todo : add lateral relation normalisation
     $model->Behaviors->attach('Util');
     $oldFormat = array();
     //$data = $model->unifiedResult($data, null, array(), $oldFormat);
     list($data, $oldFormat) = $model->unifiedResult($data, null, null, true);
     //debug($oldFormat);
     ////// get relation key fields //////
     $relationKeyFields = array();
     $belongsTo = array_merge($model->belongsTo, $opt['belongsTo']);
     foreach ($model->belongsTo as $bkey => $belongs) {
         if (!empty($data[0][$bkey])) {
             $relationKeyFields[] = $belongs['foreignKey'];
         }
     }
     ////// get updated Data //////
     $plans = array();
     $fields = array_merge(array_keys($data[0][$model->alias]), $relationKeyFields);
     $changes = $this->getChanges($model, $data, $opt['time'], $fields, $plans);
     ////// get updated relations //////
     foreach ($model->belongsTo as $bkey => $belongs) {
         $toUpdate = array();
         foreach ($changes as $rkey => $row) {
             if (!empty($data[$rkey][$bkey]) && !empty($row[$model->alias][$belongs['foreignKey']])) {
                 $toUpdate[$rkey] = $row[$model->alias][$belongs['foreignKey']];
             }
         }
         $mapping = SetMulti::flip($toUpdate);
         if (!empty($toUpdate)) {
             $excludeFields = array('name', 'className', 'counterCache');
             $findOptions = array_diff_key($belongs, array_flip($excludeFields));
             $bModel = $model->{$bkey};
             $findOptions['conditions'][$bModel->alias . '.id'] = $toUpdate;
             $findOptions['recursive'] = -1;
             // in the futur we may want to detect contain option
             $newBinded = $bModel->find('all', $findOptions);
             //$newBinded = $bModel->dataToContainedRelations($new); //see comment on recursive
             foreach ($newBinded as $n) {
                 $nid = $n[$bkey][$bModel->primaryKey];
                 foreach ((array) $mapping[$nid] as $rkey) {
                     $changes[$rkey][$bkey] = $n[$bkey];
                 }
             }
         }
     }
     //debug($changes);
     $data = Set::merge($data, $changes);
     //todo : recursive relations update
     ////// Painless update //////
     if (strtotime($opt['time']) <= mktime()) {
         $this->_applyPlans($model, $plans, $opt['time']);
     }
     ////// Un-normalize Data //////
     $data = $model->unifiedResult($data, null, $oldFormat);
     return $data;
 }
Exemple #21
0
 function finalizeOrder($order)
 {
     $dataSource = $this->ShopOrder->getDataSource();
     $data = array();
     $data['id'] = $order['ShopOrder']['id'];
     $data['active'] = 1;
     $data['date'] = $dataSource->expression('NOW()');
     $data = array_merge($data, $this->ShopFunct->calculate($order));
     $order['ShopOrder'] = array_merge($order['ShopOrder'], $data);
     $extract = array('id' => 'id', 'final_price' => 'item_price', 'item_price' => 'item_alone_price');
     foreach ($data['OrderItem'] as $item) {
         $itemdata = SetMulti::extractHierarchicMulti($extract, $item);
         $itemdata = array_merge($item, $itemdata);
         $this->ShopOrder->ShopOrdersItem->save($itemdata);
         if (!empty($item['SubItem'])) {
             foreach ($item['SubItem'] as $subitem) {
                 $this->ShopOrder->ShopOrdersItem->ShopOrdersSubitem->save($subitem);
             }
         }
     }
     //debug($data);
     //debug($data['OrderItem']);
     //debug($data['ShopOrdersSubitem']);
     //return null;
     $data['status'] = 'ready';
     $this->ShopOrder->save($data);
     $this->statusUpdated($data['id'], $data['status']);
     $order['ShopOrder'] = array_merge($order['ShopOrder'], $data);
     return $order;
 }
 function codesExists($codes, $full = false, $availableCoupon = false)
 {
     if (empty($codes)) {
         return null;
     }
     $multi = is_array($codes);
     if (!$multi) {
         $codes = array($codes);
     }
     $res = array_combine($codes, array_fill(0, count($codes), false));
     $findOpt = array('conditions' => array('code' => $codes), 'recursive' => -1);
     if ($full) {
         App::import('Lib', 'Shop.SetMulti');
         $existingPromo = $this->find('all', $findOpt);
         if (!empty($existingPromo)) {
             $existingPromo = SetMulti::group($existingPromo, 'ShopPromotion.code', array('singleArray' => true));
         }
     } else {
         $findOpt['fields'] = array('id', 'code');
         $existingPromo = $this->find('list', $findOpt);
         if (!empty($existingPromo)) {
             $existingPromo = array_combine($existingPromo, array_fill(0, count($existingPromo), true));
         }
     }
     if (!empty($existingPromo)) {
         $res = array_merge($res, $existingPromo);
     }
     if (count(array_filter($res)) != count($res)) {
         $findOpt = array('fields' => array('id', 'code'), 'conditions' => array('code' => $codes));
         if ($availableCoupon) {
             $findOpt['conditions'][] = array('or' => array('ShopCoupon.status not' => array('used', 'reserved'), 'ShopCoupon.status' => null));
         }
         if ($full) {
             App::import('Lib', 'Shop.SetMulti');
             $findOpt['contain'] = array('ShopPromotion');
             $existingCoupon = $this->ShopCoupon->find('all', $findOpt);
             if (!empty($existingCoupon)) {
                 $existingCoupon = SetMulti::group($existingCoupon, 'ShopCoupon.code', array('singleArray' => false));
             }
         } else {
             $findOpt['fields'] = array('id', 'code');
             $findOpt['recursive'] = -1;
             $existingCoupon = $this->ShopCoupon->find('list', $findOpt);
             if (!empty($existingCoupon)) {
                 $existingCoupon = array_combine($existingCoupon, array_fill(0, count($existingCoupon), true));
             }
         }
         if (!empty($existingCoupon)) {
             $res = array_merge($res, $existingCoupon);
         }
     }
     if (!$multi && !empty($res)) {
         return $res[0];
     }
     return $res;
 }
Exemple #23
0
 function save($data = null)
 {
     if (!empty($data)) {
         $nomalized = $data;
         if (isset($data['ShopCart'])) {
             $nomalized = $data['ShopCart'];
         }
         if (isset($data['ShopOrder'])) {
             $nomalized['order'] = $data['ShopOrder'];
             unset($nomalized['ShopOrder']);
         }
         if (!empty($nomalized['products'])) {
             foreach ($tmp = $nomalized['products'] as $no => $prod) {
                 if ($prod['nb'] <= 0) {
                     //unset($nomalized['products'][$no]);
                     array_splice($nomalized['products'], $no, 1);
                     $this->remove($no);
                 }
             }
         }
         App::import('Lib', 'Shop.SetMulti');
         $this->data = SetMulti::complexMerge($this->data, $nomalized, array('sequences' => false));
         $this->clearCache();
     }
     //debug($this->data);
     $this->Session->write('Shop.cart', $this->data);
     $this->_itemListData = null;
 }
 function shipping_billing($id = null)
 {
     if (!$id && isset($this->params['named']['id']) && is_numeric($this->params['named']['id'])) {
         $id = $this->params['named']['id'];
     }
     if (!empty($this->data)) {
         $id = $this->data['ShopOrder']['id'];
     }
     if (!$id) {
         $this->Session->setFlash(sprintf(__('Invalid %s', true), 'shop order'));
         $this->redirect(array('action' => 'index'));
     }
     $this->OrderFunct->tcheckAcl($id);
     $this->ShopOrder->checkActive = false;
     $this->ShopOrder->recursive = -1;
     $order = $this->ShopOrder->read(null, $id);
     debug($order);
     if (!empty($order['ShopOrder']['confirm'])) {
         $this->redirect(array('action' => 'add', $id));
     }
     if (!empty($this->data)) {
         //$this->dispatchComponentCallback('shipping_save');
         //$this->dispatchComponentCallback('billing_save');
         $data = $this->data['ShopOrder'];
         $pattern = '/(^id$)|(^use_shipping$)|(^use_billing$)|(^shipping_)|(^billing_)|(^both_)/';
         App::import('Lib', 'Shop.SetMulti');
         $data = SetMulti::pregFilterKey($pattern, $data);
         $this->ShopOrder->save($data);
         $remind = $data;
         unset($remind['id']);
         $this->Session->write('Shop.address', $remind);
         $this->redirect(array('action' => 'add', $id));
     } else {
         $remind = $this->Session->read('Shop.address');
         if (!empty($remind)) {
             $remind = array_diff_key($remind, array_filter($order['ShopOrder']));
             $order['ShopOrder'] = array_merge($order['ShopOrder'], $remind);
         }
         $this->data = $order;
     }
 }
Exemple #25
0
 function afterSave($created)
 {
     if (!empty($this->planningUpdate)) {
         if ($created) {
             App::import('Lib', 'SetMulti');
             //$this->log(var_export($this->planningUpdate, true),'debug');
             $this->planningUpdate = SetMulti::replaceTree('%pathId%', $this->id, $this->planningUpdate);
             //$this->log(var_export($this->planningUpdate, true),'debug');
             ///// Binding Listening /////
             /*if(empty($this->Event)){
             			$this->Event = ClassRegistry::init('Event');
             		}
             		$node_id = $this->Node->getNodeId($this->myNodeRef());
             		$data = array(
             			'aro_id' => null,
             			'aco_id' => $node_id,
             			'handler' => 'path',
             			'function' => 'bindListening',
             			'event_type_id' => 15,
             			'owner_id' => $node_id,
             			'phase' => 2,
             			'context' => 'path'.$this->id.'BindingListening',
             			'active' => 1,
             		);
             		//debug($data);
             		$this->Event->save($data);*/
         }
         $this->Character->savePlanningChanges($this->planningUpdate);
     }
     unset($this->planningUpdate);
 }
Exemple #26
0
 function getRelatedRef($product = null)
 {
     if (!is_array($product)) {
         $id = $product;
         if (!$id) {
             $id = $this->id;
         }
         $this->recursive = -1;
         $product = $this->find('first', array('field' => array('model', 'foreign_id'), 'conditions' => array($this->alias . '.id', $id)));
     }
     $extract_data = array('model' => array('model', $this->name . '.model', 'Options.model'), 'foreign_id' => array('foreign_id', $this->name . '.foreign_id', 'Options.foreign_id'), 'product_id' => array('id', $this->name . '.id', 'Options.id'));
     App::import('Lib', 'Shop.SetMulti');
     $res = SetMulti::extractHierarchicMulti($extract_data, $product);
     return $res;
 }
Exemple #27
0
 function reverseOrderItem($originalOpt, $calculResult)
 {
     if (empty($calculResult)) {
         return $calculResult;
     }
     $extract_data = array('Options.nb' => 'nb', 'Options.data' => 'data', 'DynamicField.price' => 'item_price', 'DynamicField.rebate' => 'item_rebate', 'DynamicField.original_price' => 'item_original_price');
     foreach ($calculResult['OrderItem'] as $pos => $item) {
         $newData = SetMulti::extractHierarchicMulti($extract_data, $item);
         $calculResult['items'][$pos] = Set::merge($originalOpt['items'][$pos], $newData);
     }
     return $calculResult;
 }
 function _boxSeparator($opt)
 {
     $defaultOpt = array('tr' => array('class' => array('nltr_sep')), 'td' => array(), 'content' => '&nbsp');
     if (!is_array($opt)) {
         $opt = array('content' => $opt);
     }
     App::import('Lib', 'Newsletter.SetMulti');
     $opt = SetMulti::merge2($defaultOpt, $opt);
     $result_html = '<tr' . $this->_parseAttributes($opt['tr']) . '>' . "\n";
     $result_html .= '	<td' . $this->_parseAttributes($opt['td']) . '>' . "\n";
     $result_html .= '		' . $opt['content'] . "\n";
     $result_html .= '	</td>' . "\n";
     $result_html .= '</tr>' . "\n";
     return $result_html;
 }
Exemple #29
0
 function subitemInput($type, $prod = null, $options = array(), $no = null)
 {
     $view =& ClassRegistry::getObject('view');
     if (!is_array($type)) {
         App::import('Lib', 'Shop.ShopConfig');
         $types = empty($options['types']) ? ShopConfig::getSubProductTypes() : $options['types'];
         if (empty($types[$type])) {
             return null;
         }
         $type = $types[$type];
     }
     $localOpt = array('prefix', 'recursive', 'types', 'subProducts');
     $defOpt = array('prefix' => !is_null($no) && is_numeric($no) ? 'ShopCart.products.' . $no . '.SubItem.' : 'ShopCart.SubItem.', 'label' => $type['label'], 'class' => 'subItem', 'recursive' => true);
     $opt = array_merge($defOpt, $options);
     if (empty($opt['subProducts'])) {
         //debug($prod);
         if (!is_array($prod)) {
             $prod = null;
             $no = $prod;
         }
         $sources = array('prod.ShopProduct.ShopSubproduct.' . $type['name'], 'prod.ShopSubproduct.' . $type['name'], 'data.ShopProduct.ShopSubproduct.' . $type['name'], 'vars.' . Inflector::singularize($this->params['controller']) . '.ShopProduct.ShopSubproduct.' . $type['name']);
         App::import('Lib', 'Shop.SetMulti');
         $data = array('prod' => $prod, 'data' => $this->data, 'vars' => $view->viewVars, 'params' => $this->params);
         $subProducts = SetMulti::extractHierarchic($sources, $data);
     } elseif (!empty($opt['subProducts'][$type['name']])) {
         $subProducts = $opt['subProducts'][$type['name']];
     } else {
         return null;
     }
     $children = array();
     if (empty($subProducts)) {
         return null;
     }
     $name = $opt['prefix'] . $type['name'];
     if ($opt['recursive']) {
         foreach ($subProducts as $subProduct) {
             if (!empty($subProduct['children'])) {
                 $children[$subProduct['id']] = $this->O2form->conditionalBlock($this->subitemInputs($prod, array('types' => $type['children'], 'subProducts' => $subProduct['children'], 'prefix' => $opt['prefix'] . 'children.' . $subProduct['id'] . '.'), $no), $name, $subProduct['id']);
             }
         }
     }
     return $view->element('subproduct_select', array('plugin' => 'shop', 'type' => $type, 'subProducts' => $subProducts, 'name' => $name, 'options' => array_diff_key($opt, array_flip($localOpt)), 'children' => $children));
 }
Exemple #30
0
 function getIneritedFields(&$model, $data, $options = array())
 {
     $defOpt = array('fields' => null, 'fetchAssociations' => true);
     $opt = array_merge($defOpt, $options);
     //debug($opt);
     if (!empty($this->settings[$model->alias]['fields']) && is_array($data)) {
         App::import('Lib', 'SetMulti');
         if (isset($data[$model->alias])) {
             $myData =& $data[$model->alias];
         } else {
             $myData =& $data;
         }
         $originalData = $myData;
         $fieldsOpt = $this->_formatFieldsOpt($this->settings[$model->alias]['fields']);
         if (!empty($opt['fields'])) {
             $fieldsOpt = array_intersect_key($fieldsOpt, array_flip($opt['fields']));
         }
         $fieldsOpt = array_intersect_key($fieldsOpt, array_merge(array_filter($myData, 'is_null'), array_filter($myData, 'is_array')));
         if (!empty($fieldsOpt)) {
             $fieldsOpt = SetMulti::group($fieldsOpt, 'alias');
             //debug($fieldsOpt);
             foreach ($fieldsOpt as $alias => $iopt) {
                 $hdata = null;
                 //debug($model->{$alias}->name ."==".$model->name);
                 if (isset($model->{$alias}) && $model->{$alias}->name == $model->name && $model->Behaviors->attached('Tree')) {
                     //tree inerit
                     $d = $myData;
                     if (!isset($d['lft']) || !isset($d['rght'])) {
                         $d = $model->read(null, $myData['id']);
                     }
                     $model->recursive = -1;
                     $tmp = $this->settings[$model->alias]['fetch'];
                     $this->settings[$model->alias]['fetch'] = false;
                     $res = $model->find('all', array('fields' => array_merge(array('id'), array_keys($iopt)), 'conditions' => array('lft' > $d['lft'], 'rght' < $d['rght']), 'order' => 'lft DESC'));
                     //debug($res);
                     $this->settings[$model->alias]['fetch'] = $tmp;
                     $hdata = array();
                     foreach ($res as $item) {
                         $hdata = array_merge($hdata, array_filter($item[$model->alias]));
                     }
                     //debug($hdata);
                 } else {
                     if (isset($data[$alias])) {
                         $hdata = $data[$alias];
                     } elseif (isset($data[$model->alias][$alias])) {
                         $hdata = $data[$model->alias][$alias];
                     }
                     //debug($hdata);
                     if (isset($model->{$alias}) && $model->{$alias}->Behaviors->attached('Inheritor') && !empty($hdata)) {
                         $hdata = $model->{$alias}->getIneritedFields($hdata, array('fields' => array_keys($iopt), 'fetchAssociations' => false));
                     }
                 }
                 foreach ($iopt as $key => $val) {
                     if (!isset($hdata[$key])) {
                         $myData[$key] = null;
                     } elseif (is_array($myData[$key])) {
                         if (!empty($hdata[$key])) {
                             $myData[$key] = SetMulti::merge2($myData[$key], $hdata[$key]);
                         }
                     } else {
                         $myData[$key] = $hdata[$key];
                     }
                 }
                 if ($opt['fetchAssociations']) {
                     if (!empty($model->lastAssociations['belongsTo'])) {
                         $associationFields = SetMulti::extractKeepKey('foreignKey', $model->lastAssociations['belongsTo']);
                         $toFetch = array_intersect($associationFields, array_keys($iopt));
                         foreach ($toFetch as $aalias => $field) {
                             if ($originalData[$field] != $myData[$field]) {
                                 $findOpt = $model->lastAssociations['belongsTo'][$aalias];
                                 if (isset($model->{$aalias})) {
                                     $amodel = $model->{$aalias};
                                 } else {
                                     $amodel = ClassRegistry::init($findOpt['className']);
                                 }
                                 unset($findOpt['className'], $findOpt['foreignKey']);
                                 $findOpt['conditions'][$amodel->alias . '.' . $amodel->primaryKey] = $myData[$field];
                                 //debug($findOpt);
                                 $res = $amodel->find('first', $findOpt);
                                 $amodel->Behaviors->attach('Util');
                                 $res = $amodel->dataToContainedRelations($res);
                                 $data[$aalias] = $res;
                             }
                         }
                     }
                 }
             }
         }
     }
     return $data;
 }