Example #1
0
 /**
  * Gets language variable by name
  *
  * @param string $var_name  Language variable name
  * @param string $lang_code 2-letter language code
  *
  * @return string Language variable value; in case the value is absent, language variable name with "_" prefix is returned
  */
 public static function getLangVar($var_name, $lang_code = CART_LANGUAGE)
 {
     Registry::registerCache('lang_cache', array('language_values', 'ult_language_values'), Registry::cacheLevel('dispatch'), true);
     if (empty($var_name)) {
         return '';
     }
     $values = Registry::get('lang_cache.' . $lang_code);
     if (empty($values)) {
         $values = array();
     }
     $var_name = strtolower($var_name);
     if (!isset($values[$var_name])) {
         $params = array();
         $left_join = array();
         $fields = array('lang.value' => true);
         $tables = array('?:language_values lang');
         $condition = array(db_quote('lang.lang_code = ?s', $lang_code), db_quote('lang.name = ?s', $var_name));
         fn_set_hook('get_lang_var', $fields, $tables, $left_join, $condition, $params);
         $joins = !empty($left_join) ? ' LEFT JOIN ' . implode(', ', $left_join) : '';
         $values[$var_name] = db_get_field('SELECT ' . implode(', ', array_keys($fields)) . ' FROM ' . implode(', ', $tables) . $joins . ' WHERE ' . implode(' AND ', $condition));
         if (!db_get_found_rows()) {
             unset($values[$var_name]);
         }
         Registry::set('lang_cache.' . $lang_code, $values);
     }
     if (!isset($values[$var_name])) {
         return '_' . $var_name;
     }
     if (Registry::get('runtime.customization_mode.live_editor')) {
         return '[lang name=' . $var_name . (preg_match('/\\[[\\w]+\\]/', $values[$var_name]) ? ' cm-pre-ajax' : '') . ']' . $values[$var_name] . '[/lang]';
     }
     return $values[$var_name];
 }
Example #2
0
 public static function init($reinit = false, $config = array())
 {
     self::$active_debug_mode = false;
     self::$allow_backtrace_sql = isset($_REQUEST['sql_backtrace']);
     self::$debugger_cookie = !empty($_COOKIE['debugger']) ? $_COOKIE['debugger'] : '';
     if ($reinit) {
         Registry::registerCache('debugger', SESSION_ALIVE_TIME, Registry::cacheLevel('time'), true);
         self::$actives = fn_get_storage_data('debugger_active');
         self::$actives = !empty(self::$actives) ? unserialize(self::$actives) : array();
         $active_in_registry = !empty(self::$actives[self::$debugger_cookie]) && time() - self::$actives[self::$debugger_cookie] < 0 ? true : false;
     }
     $debugger_token = !empty($config) ? $config['debugger_token'] : Registry::get('config.debugger_token');
     switch (true) {
         case defined('AJAX_REQUEST') && substr($_REQUEST['dispatch'], 0, 8) !== 'debugger':
             break;
         case defined('DEBUG_MODE') && DEBUG_MODE == true:
         case !$reinit && (!empty(self::$debugger_cookie) || isset($_REQUEST[$debugger_token])):
             self::$active_debug_mode = true;
             break;
         case !$reinit:
             break;
             // next if reinit
         // next if reinit
         case !empty(self::$debugger_cookie) && !empty($active_in_registry):
             self::$active_debug_mode = true;
             break;
         case isset($_REQUEST[$debugger_token]):
             $salt = '';
             if ($_SESSION['auth']['user_type'] == 'A' && $_SESSION['auth']['is_root'] == 'Y') {
                 $user_admin = db_get_row('SELECT email, password FROM ?:users WHERE user_id = ?i', $_SESSION['auth']['user_id']);
                 $salt = $user_admin['email'] . $user_admin['password'];
             }
             if ($debugger_token != self::DEFAULT_TOKEN || !empty($salt)) {
                 // for non-default token allow full access
                 self::$debugger_cookie = substr(md5(SESSION::getId() . $salt), 0, 8);
                 $active_in_registry = true;
                 self::$active_debug_mode = true;
             }
             if (AREA == 'C' && !empty($_REQUEST[$debugger_token])) {
                 if (!empty(self::$actives[$_REQUEST[$debugger_token]]) && time() - self::$actives[$_REQUEST[$debugger_token]] < 0) {
                     $active_in_registry = true;
                     self::$debugger_cookie = $_REQUEST[$debugger_token];
                     self::$active_debug_mode = true;
                 }
             }
             fn_set_cookie('debugger', self::$debugger_cookie, SESSION_ALIVE_TIME);
             break;
     }
     if ($reinit && self::$active_debug_mode && !empty(self::$debugger_cookie)) {
         self::$actives[self::$debugger_cookie] = time() + self::EXPIRE_DEBUGGER;
         fn_set_storage_data('debugger_active', serialize(self::$actives));
         $active_in_registry = true;
     }
     if ($reinit && !empty(self::$debugger_cookie) && empty($active_in_registry)) {
         fn_set_cookie('debugger', '', 0);
         unset(self::$actives[self::$debugger_cookie]);
         fn_set_storage_data('debugger_active', serialize(self::$actives));
     }
     return self::$active_debug_mode;
 }
Example #3
0
 public function get($name, $cache_level = NULL)
 {
     $data = $this->query('hGet', $this->mapTags($name), $cache_level);
     if (!empty($data)) {
         if (!empty($data) && ($cache_level != Registry::cacheLevel('time') || $cache_level == Registry::cacheLevel('time') && $data['expiry'] > TIME)) {
             return array($data['data']);
         } else {
             // clean up the cache
             $this->query('del', $this->mapTags($name));
         }
     }
     return false;
 }
Example #4
0
 public function get($name, $cache_level = NULL)
 {
     $fname = $this->_mapTags($name) . '/' . $cache_level;
     if (!empty($name) && is_readable($fname)) {
         $_cache_data = @unserialize(fn_get_contents($fname));
         if (!empty($_cache_data) && ($cache_level != Registry::cacheLevel('time') || $cache_level == Registry::cacheLevel('time') && $_cache_data['expiry'] > TIME)) {
             return array($_cache_data['data']);
         } else {
             // clean up the cache
             fn_rm($fname);
         }
     }
     return false;
 }
Example #5
0
 public function get($name, $cache_level = NULL)
 {
     $fname = $name . '.' . $cache_level;
     $expiry_condition = $cache_level == Registry::cacheLevel('time') ? db_quote(" AND expiry > ?i", TIME) : '';
     $res = $this->_dbFetch("SELECT data, expiry FROM cache WHERE name = '{$fname}' AND company_id = " . $this->_company_id . $expiry_condition);
     if (!empty($name) && !empty($res)) {
         $_cache_data = !empty($res['data']) ? @unserialize($res['data']) : false;
         if ($_cache_data !== false) {
             return array($_cache_data);
         }
         // clean up the cache
         $this->db->query("DELETE FROM cache WHERE name = '{$fname}' AND company_id = " . $this->_company_id);
     }
     return false;
 }
Example #6
0
 public function get($name, $cache_level = NULL)
 {
     $fname = $name . '.' . $cache_level;
     $expiry_condition = $cache_level == Registry::cacheLevel('time') ? db_quote(" AND expiry > ?i", TIME) : '';
     Db::$raw = true;
     $res = Db::getRow("SELECT data, expiry FROM ?:cache WHERE name = ?s AND company_id = ?i ?p", $fname, $this->_company_id, $expiry_condition);
     if (!empty($name) && !empty($res)) {
         $_cache_data = !empty($res['data']) ? @unserialize($res['data']) : false;
         if ($_cache_data !== false) {
             return array($_cache_data);
         }
         // clean up the cache
         Db::$raw = true;
         Db::query("DELETE FROM ?:cache WHERE name = ?s AND company_id = ?i", $fname, $this->_company_id);
     }
     return false;
 }
Example #7
0
 /**
  * Loads received language variables into language cache
  *
  * @param array  $var_names Language variable that to be loaded
  * @param string $lang_code 2-letter language code
  *
  * @return boolean True if any of received language variables were added into cache; false otherwise
  */
 public static function preloadLangVars($var_names, $lang_code = CART_LANGUAGE)
 {
     Registry::registerCache('lang_cache', array('language_values', 'ult_language_values'), Registry::cacheLevel('dispatch'), true);
     $values = Registry::get('lang_cache.' . $lang_code);
     if (empty($values)) {
         $values = array();
     }
     $var_names = array_diff($var_names, array_keys($values));
     if ($var_names) {
         foreach ($var_names as $index => $var_name) {
             $var_names[$index] = strtolower($var_name);
             if (isset($values[$var_name])) {
                 unset($var_names[$index]);
             }
         }
         if (empty($var_names)) {
             return true;
         }
         $fields = array('lang.name' => true, 'lang.value' => true);
         $tables = array('?:language_values lang');
         $left_join = array();
         $condition = array(db_quote('lang.lang_code = ?s', $lang_code), db_quote('lang.name IN (?a)', $var_names));
         $params = array();
         fn_set_hook('get_lang_var', $fields, $tables, $left_join, $condition, $params);
         $joins = !empty($left_join) ? ' LEFT JOIN ' . implode(', ', $left_join) : '';
         $new_values = db_get_hash_single_array('SELECT ' . implode(', ', array_keys($fields)) . ' FROM ' . implode(', ', $tables) . $joins . ' WHERE ' . implode(' AND ', $condition), array('name', 'value'));
         foreach ($var_names as $var_name) {
             if (!isset($new_values[$var_name])) {
                 $new_values[$var_name] = '_' . $var_name;
             }
         }
         $values = fn_array_merge($values, $new_values);
         Registry::set('lang_cache.' . $lang_code, $values);
         return true;
     }
     return false;
 }
Example #8
0
/**
 * Get all schema files (e.g. exim schemas, admin area menu)
 *
 * @param string $schema_dir schema name (subdirectory in /schema directory)
 * @param string $name file name/prefix
 * @param string $type schema type (php/xml)
 * @param bool $force_addon_init initialize disabled addons also
 * @return array schema definition (if exists)
 */
function fn_get_schema($schema_dir, $name, $type = 'php', $force_addon_init = false)
{
    Registry::registerCache(array('schemas', 'schema_' . $schema_dir . '_' . $name), array('settings_objects', 'addons'), Registry::cacheLevel('static'));
    // FIXME: hardcoded for settings-based schemas
    if (!Registry::isExist('schema_' . $schema_dir . '_' . $name)) {
        $files = array();
        $path_name = Registry::get('config.dir.schemas') . $schema_dir . '/' . $name;
        if (file_exists($path_name . '.' . $type)) {
            $files[] = $path_name . '.' . $type;
        }
        if (file_exists($path_name . '_' . fn_strtolower(PRODUCT_EDITION) . '.' . $type)) {
            $files[] = $path_name . '_' . fn_strtolower(PRODUCT_EDITION) . '.' . $type;
        }
        $addons = Registry::get('addons');
        if (!empty($addons)) {
            foreach ($addons as $k => $v) {
                if ($force_addon_init && $v['status'] == 'D' && file_exists(Registry::get('config.dir.addons') . $k . '/func.php')) {
                    // force addon initialization
                    include_once Registry::get('config.dir.addons') . $k . '/func.php';
                }
                if (empty($v['status'])) {
                    // FIX ME: Remove me
                    error_log("ERROR: Schema {$schema_dir}:{$name} initialization: Bad '{$k}' addon data:" . serialize($v) . " Addons Registry:" . serialize(Registry::get('addons')));
                }
                if (!empty($v['status']) && $v['status'] == 'A' || $force_addon_init) {
                    $path_name = Registry::get('config.dir.addons') . $k . '/schemas/' . $schema_dir . '/' . $name;
                    if (file_exists($path_name . '_' . fn_strtolower(PRODUCT_EDITION) . '.' . $type)) {
                        array_unshift($files, $path_name . '_' . fn_strtolower(PRODUCT_EDITION) . '.' . $type);
                    }
                    if (file_exists($path_name . '.' . $type)) {
                        array_unshift($files, $path_name . '.' . $type);
                    }
                    if (file_exists($path_name . '.post.' . $type)) {
                        $files[] = $path_name . '.post.' . $type;
                    }
                    if (file_exists($path_name . '_' . fn_strtolower(PRODUCT_EDITION) . '.post.' . $type)) {
                        $files[] = $path_name . '_' . fn_strtolower(PRODUCT_EDITION) . '.post.' . $type;
                    }
                }
            }
        }
        Registry::set('schema_' . $schema_dir . '_' . $name, $files);
    }
    $schema = '';
    $include_once = strpos($name, '.functions') !== false;
    foreach (Registry::get('schema_' . $schema_dir . '_' . $name) as $file) {
        if ($type == 'php') {
            $schema = $include_once ? include_once $file : (include $file);
        } else {
            $schema .= file_get_contents($file);
        }
    }
    return $schema;
}
Example #9
0
 /**
  * Checks if file exists
  *
  * @param  string  $file     file to check
  * @param  string  $in_cache indicates that file existance should be checked in cache only (useful for non-local storages)
  * @return boolean true if exists, false - otherwise
  */
 public function isExist($file, $in_cache = false)
 {
     $file = $this->prefix($file);
     $cache_name = 's3_' . $this->getOption('bucket');
     Registry::registerCache($cache_name, array(), Registry::cacheLevel('static'), true);
     $is_exist = Registry::get($cache_name . '.' . md5($file));
     if ($in_cache == false && $is_exist == false && ($is_exist = $this->s3()->if_object_exists($this->getOption('bucket'), $file))) {
         Registry::set($cache_name . '.' . md5($file), true);
     }
     return $is_exist;
 }
Example #10
0
/**
 * Gets cached SEO name
 * @param string $name cached object (name or path)
 * @param string $object_type object type
 * @param mixed $object_id object_id/dispatch
 * @param integer $company_id company ID
 * @param string $lang_code language code
 * @param string $area current working area
 * @return string cached name
 */
function fn_seo_get_cache_name($name, $object_type, $object_id, $company_id, $lang_code, $area = AREA)
{
    static $init_cache = false;
    if ($area != 'C') {
        return null;
    }
    $cache_name = $object_type == 's' ? 'seo_cache_static' : 'seo_cache';
    if ($object_type == 's' && !$init_cache) {
        Registry::registerCache($cache_name, array('seo_names'), Registry::cacheLevel('static') . $lang_code, true);
    }
    $key = $lang_code . '_' . $object_id . '_' . $object_type . '_' . $company_id;
    return Registry::get($cache_name . '.' . $key . '.' . $name);
}
 /**
  * Registers block cache
  * @param string $cache_name   Cache name
  * @param array  $block_scheme Block scheme data
  */
 private static function _registerBlockCache($cache_name, $block_scheme)
 {
     if (isset($block_scheme['cache'])) {
         $additional_level = '';
         $default_handlers = fn_get_schema('block_manager', 'block_cache_properties');
         if (isset($block_scheme['cache']['update_handlers']) && is_array($block_scheme['cache']['update_handlers'])) {
             $handlers = $block_scheme['cache']['update_handlers'];
         } else {
             $handlers = array();
         }
         $cookie_data = fn_get_session_data();
         $cookie_data['all'] = $cookie_data;
         $additional_level .= self::_generateAdditionalCacheLevel($block_scheme['cache'], 'request_handlers', $_REQUEST);
         $additional_level .= self::_generateAdditionalCacheLevel($block_scheme['cache'], 'session_handlers', $_SESSION);
         $additional_level .= self::_generateAdditionalCacheLevel($block_scheme['cache'], 'cookie_handlers', $cookie_data);
         $additional_level .= self::_generateAdditionalCacheLevel($block_scheme['cache'], 'auth_handlers', $_SESSION['auth']);
         $additional_level .= '|path=' . Registry::get('config.current_path');
         $additional_level .= Embedded::isEnabled() ? '|embedded' : '';
         $additional_level = !empty($additional_level) ? md5($additional_level) : '';
         $handlers = array_merge($handlers, $default_handlers['update_handlers']);
         $cache_level = isset($block_scheme['cache']['cache_level']) ? $block_scheme['cache']['cache_level'] : Registry::cacheLevel('html_blocks');
         Registry::registerCache($cache_name, $handlers, $cache_level . '__' . $additional_level);
     }
 }
Example #12
0
/**
 * Gets product filters with ranges
 *
 * @param array $params Products filter search params
 * @return array Products and filters data
 *               array $filters - Product filters data
 *               array $view_all - All ranges filters
 */
function fn_get_filters_products_count($params = array())
{
    /**
     * Change parameters for getting product filters count
     *
     * @param array $params Products filter search params
     */
    fn_set_hook('get_filters_products_count_pre', $params);
    $key = 'pfilters_' . md5(serialize($params));
    Registry::registerCache($key, array('products', 'product_features', 'product_filters', 'product_features_values', 'categories'), Registry::cacheLevel('user'));
    if (Registry::isExist($key) == false) {
        if (!empty($params['check_location'])) {
            // FIXME: this is bad style, should be refactored
            $valid_locations = array('index.index', 'products.search', 'categories.view', 'product_features.view');
            if (!in_array($params['dispatch'], $valid_locations)) {
                return array();
            }
            if ($params['dispatch'] == 'categories.view') {
                $params['simple_link'] = true;
                // this parameter means that extended filters on this page should be displayed as simple
                $params['filter_custom_advanced'] = true;
                // this parameter means that extended filtering should be stayed on the same page
            } else {
                if ($params['dispatch'] == 'product_features.view') {
                    $params['simple_link'] = true;
                    $params['features_hash'] = (!empty($params['features_hash']) ? $params['features_hash'] . '.' : '') . 'V' . $params['variant_id'];
                    //$params['exclude_feature_id'] = db_get_field("SELECT feature_id FROM ?:product_features_values WHERE variant_id = ?i", $params['variant_id']);
                }
                $params['get_for_home'] = 'Y';
            }
        }
        // hide filters block on the advanced search page
        if (!empty($params['skip_if_advanced']) && !empty($params['advanced_filter']) && $params['advanced_filter'] == 'Y') {
            return array();
        }
        // Base fields for the SELECT queries
        $values_fields = array('?:product_features_values.feature_id', 'COUNT(DISTINCT ?:products.product_id) as products', '?:product_features_values.variant_id as range_id', '?:product_feature_variant_descriptions.variant as range_name', '?:product_features.feature_type', '?:product_filters.filter_id');
        $ranges_fields = array('?:product_features_values.feature_id', 'COUNT(DISTINCT ?:products.product_id) as products', '?:product_filter_ranges.range_id', '?:product_filter_ranges_descriptions.range_name', '?:product_filter_ranges.filter_id', '?:product_features.feature_type');
        $condition = $where = $join = $filter_vq = $filter_rq = '';
        $advanced_variant_ids = $ranges_ids = $field_filters = $feature_ids = $field_ranges_ids = $field_ranges_counts = $field_range_values = $slider_vals = array();
        if (!empty($params['features_hash']) && empty($params['skip_advanced_variants'])) {
            list($av_ids, $ranges_ids, $_field_ranges_ids, $slider_vals, $field_ranges_ids) = fn_parse_features_hash($params['features_hash']);
            $advanced_variant_ids = db_get_hash_multi_array("SELECT feature_id, variant_id FROM ?:product_feature_variants WHERE variant_id IN (?n)", array('feature_id', 'variant_id'), $av_ids);
        }
        if (!empty($params['category_id'])) {
            if (Registry::get('settings.General.show_products_from_subcategories') == 'Y') {
                $id_path = db_get_field("SELECT id_path FROM ?:categories WHERE category_id = ?i", $params['category_id']);
                $category_ids = db_get_fields("SELECT category_id FROM ?:categories WHERE id_path LIKE ?l", $id_path . '/%');
            } else {
                $category_ids = array();
            }
            $category_ids[] = $params['category_id'];
            $condition .= db_quote(" AND (categories_path = '' OR FIND_IN_SET(?i, categories_path))", $params['category_id']);
            $where .= db_quote(" AND ?:products_categories.category_id IN (?n)", $category_ids);
        } elseif (empty($params['get_for_home']) && empty($params['get_custom'])) {
            $condition .= " AND categories_path = ''";
        }
        if (!empty($params['filter_id'])) {
            $condition .= db_quote(" AND ?:product_filters.filter_id = ?i", $params['filter_id']);
        }
        if (!empty($params['item_ids'])) {
            $condition .= db_quote(" AND ?:product_filters.filter_id IN (?a)", explode(',', $params['item_ids']));
        }
        if (!empty($params['get_for_home'])) {
            $condition .= db_quote(" AND ?:product_filters.show_on_home_page = ?s", $params['get_for_home']);
        }
        if (!empty($params['exclude_feature_id'])) {
            $condition .= db_quote(" AND ?:product_filters.feature_id NOT IN (?n)", $params['exclude_feature_id']);
        }
        if (fn_allowed_for('ULTIMATE')) {
            $condition .= fn_get_company_condition('?:product_filters.company_id');
        }
        $sf_fields = db_quote("?:product_filters.feature_id, ?:product_filters.filter_id, ?:product_filters.field_type, ?:product_filters.round_to, ?:product_filters.display, ?:product_filters.display_count, ?:product_filters.display_more_count, ?:product_filter_descriptions.filter, ?:product_features_descriptions.prefix, ?:product_features_descriptions.suffix");
        $sf_join = db_quote("LEFT JOIN ?:product_filter_descriptions ON ?:product_filter_descriptions.filter_id = ?:product_filters.filter_id AND ?:product_filter_descriptions.lang_code = ?s LEFT JOIN ?:product_features_descriptions ON ?:product_features_descriptions.feature_id = ?:product_filters.feature_id AND ?:product_features_descriptions.lang_code = ?s", CART_LANGUAGE, CART_LANGUAGE);
        $sf_sorting = db_quote("position, filter");
        /**
         * Change SQL parameters before select product filters
         *
         * @param array $sf_fields String of comma-separated SQL fields to be selected in an SQL-query
         * @param string $sf_join String with the complete JOIN information (JOIN type, tables and fields) for an SQL-query
         * @param string $condition String containing SQL-query condition possibly prepended with a logical operator (AND or OR)
         * @param string $sf_sorting String containing the SQL-query ORDER BY clause
         * @param array $params Products filter search params
         */
        fn_set_hook('get_filters_products_count_before_select_filters', $sf_fields, $sf_join, $condition, $sf_sorting, $params);
        $limit = '';
        if (fn_allowed_for('ULTIMATE:FREE')) {
            $limit = db_quote(' LIMIT ?i', FILTERS_LIMIT);
        }
        $filters = db_get_hash_array("SELECT {$sf_fields} FROM ?:product_filters {$sf_join} WHERE ?:product_filters.status = 'A' ?p ORDER BY {$sf_sorting} {$limit}", 'filter_id', $condition);
        $fields = fn_get_product_filter_fields();
        if (empty($filters) && empty($params['advanced_filter'])) {
            return array(array(), false);
        } else {
            foreach ($filters as $k => $v) {
                if (!empty($v['feature_id'])) {
                    // Feature filters
                    $feature_ids[] = $v['feature_id'];
                } else {
                    // Product field filters
                    if (!empty($fields[$v['field_type']])) {
                        $_field = $fields[$v['field_type']];
                        $field_filters[$v['filter_id']] = array_merge($v, $_field);
                        $filters[$k]['condition_type'] = $_field['condition_type'];
                        if (!empty($_field['slider'])) {
                            $filters[$k]['slider'] = $_field['slider'];
                        }
                    }
                }
            }
        }
        // Variants
        if (!empty($advanced_variant_ids)) {
            $join .= db_quote(" LEFT JOIN (SELECT product_id, GROUP_CONCAT(?:product_features_values.variant_id) AS advanced_variants FROM ?:product_features_values WHERE lang_code = ?s GROUP BY product_id) AS pfv_advanced ON pfv_advanced.product_id = ?:products.product_id", CART_LANGUAGE);
            $where_and_conditions = array();
            foreach ($advanced_variant_ids as $k => $variant_ids) {
                $where_or_conditions = array();
                foreach ($variant_ids as $variant_id => $v) {
                    $where_or_conditions[] = db_quote(" FIND_IN_SET('?i', advanced_variants)", $variant_id);
                }
                $where_and_conditions[] = '(' . implode(' OR ', $where_or_conditions) . ')';
            }
            $where .= ' AND ' . implode(' AND ', $where_and_conditions);
        }
        // Ranges
        if (!empty($ranges_ids)) {
            $filter_conditions = db_get_hash_multi_array("SELECT `from`, `to`, feature_id, filter_id, range_id FROM ?:product_filter_ranges WHERE range_id IN (?n)", array('filter_id', 'range_id'), $ranges_ids);
            $where_conditions = array();
            foreach ($filter_conditions as $fid => $range_conditions) {
                foreach ($range_conditions as $k => $condition) {
                    $k = $fid . "_" . $k;
                    $join .= db_quote(" LEFT JOIN ?:product_features_values as var_val_{$k} ON var_val_{$k}.product_id = ?:products.product_id AND var_val_{$k}.lang_code = ?s", CART_LANGUAGE);
                    $where_conditions[] = db_quote("(var_val_{$k}.value_int >= ?i AND var_val_{$k}.value_int <= ?i AND var_val_{$k}.value = '' AND var_val_{$k}.feature_id = ?i)", $condition['from'], $condition['to'], $condition['feature_id']);
                }
                $where .= db_quote(" AND (?p)", implode(" OR ", $where_conditions));
                $where_conditions = array();
            }
        }
        if (!empty($params['filter_id']) && empty($params['view_all'])) {
            $filter_vq .= db_quote(" AND ?:product_filters.filter_id = ?i", $params['filter_id']);
            $filter_rq .= db_quote(" AND ?:product_filter_ranges.filter_id = ?i", $params['filter_id']);
        }
        if (!empty($params['view_all'])) {
            $values_fields[] = "UPPER(SUBSTRING(?:product_feature_variant_descriptions.variant, 1, 1)) AS `index`";
        }
        $_join = $join;
        // Build condition for the standart fields
        if (!empty($field_ranges_ids)) {
            foreach ($field_ranges_ids as $field_type => $rids) {
                $structure = $fields[$field_type];
                if (empty($fields[$field_type])) {
                    continue;
                }
                if ($structure['table'] !== 'products' && strpos($join, 'JOIN ?:' . $structure['table']) === false) {
                    $join .= " LEFT JOIN ?:{$structure['table']} ON ?:{$structure['table']}.product_id = ?:products.product_id";
                }
                if ($structure['condition_type'] == 'D' && empty($structure['slider'])) {
                    foreach ($rids as $rid) {
                        $range_condition = db_get_row("SELECT `from`, `to` FROM ?:product_filter_ranges WHERE range_id = ?i", $rid);
                        if (!empty($range_condition)) {
                            $where .= db_quote(" AND ?:{$structure['table']}.{$structure['db_field']} >= ?i AND ?:{$structure['table']}.{$structure['db_field']} <= ?i", $range_condition['from'], $range_condition['to']);
                        }
                    }
                } elseif ($structure['condition_type'] == 'F') {
                    $where .= db_quote(" AND ?:{$structure['table']}.{$structure['db_field']} IN (?a)", $rids);
                } elseif ($structure['condition_type'] == 'C') {
                    if (count($rids) > 1) {
                        unset($field_ranges_ids[$field_type]);
                        foreach ($rids as $rid) {
                            $params['features_hash'] = fn_delete_range_from_url($params['features_hash'], array('range_id' => $rid), $field_type);
                        }
                    } else {
                        $where .= db_quote(" AND ?:{$structure['table']}.{$structure['db_field']} = ?s", $rids[0] == 1 ? 'Y' : 'N');
                    }
                }
                if (!empty($structure['join_params'])) {
                    foreach ($structure['join_params'] as $field => $param) {
                        $join .= db_quote(" AND ?:{$structure['table']}.{$field} = ?s ", $param);
                    }
                }
            }
        }
        // Product availability conditions
        $where .= ' AND (' . fn_find_array_in_set($_SESSION['auth']['usergroup_ids'], '?:categories.usergroup_ids', true) . ')';
        $where .= ' AND (' . fn_find_array_in_set($_SESSION['auth']['usergroup_ids'], '?:products.usergroup_ids', true) . ')';
        $where .= db_quote(" AND ?:categories.status IN (?a) AND ?:products.status IN (?a)", array('A', 'H'), array('A'));
        if (fn_allowed_for('ULTIMATE') && Registry::get('runtime.company_id')) {
            $categories_join_condition = db_quote(' AND ?:categories.company_id = ?i', Registry::get('runtime.company_id'));
        } else {
            $categories_join_condition = '';
        }
        $_j = " INNER JOIN ?:products_categories ON ?:products_categories.product_id = ?:products.product_id LEFT JOIN ?:categories ON ?:categories.category_id = ?:products_categories.category_id {$categories_join_condition}";
        if (fn_allowed_for('MULTIVENDOR') && AREA == 'C') {
            if (!empty($_REQUEST['company_id'])) {
                $where .= " AND (?:products.company_id = " . !empty($_REQUEST['company_id']) . ") ";
            }
            $where .= " AND (companies.status = 'A')";
            $_j .= " LEFT JOIN ?:companies as companies ON companies.company_id = ?:products.company_id";
        }
        $_join .= $_j;
        $join .= $_j;
        $inventory_join = '';
        if (Registry::get('settings.General.inventory_tracking') == 'Y' && Registry::get('settings.General.show_out_of_stock_products') == 'N' && AREA == 'C') {
            $inventory_join .= " LEFT JOIN ?:product_options_inventory as inventory ON inventory.product_id = ?:products.product_id";
            $where .= " AND IF(?:products.tracking = 'O', inventory.amount > 0, ?:products.amount > 0)";
        }
        $join .= $inventory_join;
        // Localization
        $where .= fn_get_localizations_condition('?:products.localization', true);
        $where .= fn_get_localizations_condition('?:categories.localization', true);
        $sliders_join = $sliders_where = '';
        /**
         * Change SQL parameters before select filter variants and products count
         *
         * @param array $values_fields Array of SQL fields to be selected in an SQL-query
         * @param string $join String with the complete JOIN information (JOIN type, tables and fields) for an SQL-query
         * @param string $sliders_join String with the additional complete JOIN information (JOIN type, tables and fields) for an SQL-query (for slider range filters)
         * @param array $feature_ids Array of feature IDs.
         * @param string $where String containing SQL-query condition possibly prepended with a logical operator (AND or OR)
         * @param string $sliders_where String containing additional SQL-query condition possibly prepended with a logical operator (AND or OR) (for slider range filters)
         * @param string $filter_vq String containing additional SQL-query condition for filter with variants possibly prepended with a logical operator (AND or OR) (for slider range filters)
         * @param string $filter_rq String containing additional SQL-query condition for filter with ranges possibly prepended with a logical operator (AND or OR) (for slider range filters)
         */
        fn_set_hook('get_filters_products_count_query_params', $values_fields, $join, $sliders_join, $feature_ids, $where, $sliders_where, $filter_vq, $filter_rq);
        //var_dump($field_filters);echo"<br/>____________________________<br/>";
        if (!empty($field_filters)) {
            // Field ranges
            foreach ($field_filters as $filter_id => $field) {
                $fields_join = $fields_where = '';
                // Dinamic ranges (price, amount etc)
                if ($field['condition_type'] == 'D') {
                    $_fields_join = " LEFT JOIN ?:{$field['table']} ON ?:{$field['table']}.{$field['db_field']} >= ?:product_filter_ranges.from AND ?:{$field['table']}.{$field['db_field']} <= ?:product_filter_ranges.to ";
                    if ($field['field_type'] != 'A') {
                        if (strpos($_join, 'JOIN ?:products ') === false) {
                            $fields_join .= " LEFT JOIN ?:products ON ?:products.product_id = ?:product_prices.product_id";
                        } elseif (strpos($fields_join . $_join, 'JOIN ?:product_prices ') === false) {
                            $fields_join .= db_quote(" LEFT JOIN ?:product_prices ON ?:product_prices.product_id = ?:products.product_id AND ?:product_prices.lower_limit = 1 AND ?:product_prices.usergroup_id IN (?n)", array_merge(array(USERGROUP_ALL), $_SESSION['auth']['usergroup_ids']));
                        }
                    }
                    if ($field['table'] == 'product_prices') {
                        $fields_join .= db_quote(" LEFT JOIN ?:product_prices as prices_2 ON ?:product_prices.product_id = prices_2.product_id AND ?:product_prices.price > prices_2.price AND prices_2.lower_limit = 1 AND prices_2.usergroup_id IN (?n)", array_merge(array(USERGROUP_ALL), $_SESSION['auth']['usergroup_ids']));
                        $fields_join .= db_quote(" LEFT JOIN ?:product_options_inventory_prices as prices_3 ON ?:product_prices.product_id = prices_3.product_id ");
                        $fields_where .= db_quote(" AND ?:product_prices.lower_limit = 1 AND ?:product_prices.usergroup_id IN (?n)", array_merge(array(USERGROUP_ALL), $_SESSION['auth']['usergroup_ids']));
                        $fields_where .= " AND prices_2.price IS NULL";
                    }
                    if (empty($field['slider'])) {
                        $fields_join = $_fields_join . $fields_join . $inventory_join;
                        $field_ranges_counts[$filter_id] = db_get_hash_array("SELECT COUNT(DISTINCT ?:{$field['table']}.product_id) as products, ?:product_filter_ranges.range_id, ?:product_filter_ranges_descriptions.range_name, ?:product_filter_ranges.filter_id FROM ?:product_filter_ranges LEFT JOIN ?:product_filter_ranges_descriptions ON ?:product_filter_ranges_descriptions.range_id = ?:product_filter_ranges.range_id AND ?:product_filter_ranges_descriptions.lang_code = ?s ?p WHERE ?:products.status IN ('A') AND ?:product_filter_ranges.filter_id = ?i ?p GROUP BY ?:product_filter_ranges.range_id HAVING products != 0 ORDER BY ?:product_filter_ranges.position, ?:product_filter_ranges_descriptions.range_name", 'range_id', CART_LANGUAGE, $fields_join . $_join, $filter_id, $where . $fields_where);
                    } else {
                        if ($field['field_type'] == 'A') {
                            $db_field = "IF(?:products.tracking = 'O', inventory.amount, ?:products.amount)";
                            $fields_join .= " LEFT JOIN ?:product_options_inventory as inventory ON inventory.product_id = ?:products.product_id";
                        } else {
                            $db_field = "?:{$field['table']}.{$field['db_field']}";
                            $fields_join .= $inventory_join;
                            if (fn_allowed_for('ULTIMATE') && $field['field_type'] == 'P' && Registry::get('runtime.company_id')) {
                                $db_field = "IF(prices_3.price IS NOT NULL, prices_3.price, IF(shared_prices.product_id IS NOT NULL, shared_prices.price, ?:product_prices.price))";
                                //$db_field = " IF(shared_prices.product_id IS NOT NULL, shared_prices.price, ?:product_prices.price)";
                                $fields_join .= db_quote(" LEFT JOIN ?:ult_product_prices AS shared_prices ON shared_prices.product_id = ?:products.product_id" . " AND shared_prices.lower_limit = 1" . " AND shared_prices.usergroup_id IN (?n)" . " AND shared_prices.company_id = ?i", array_merge(array(USERGROUP_ALL), $_SESSION['auth']['usergroup_ids']), Registry::get('runtime.company_id'));
                            }
                        }
                        $field_range_values[$filter_id] = db_get_row("SELECT MIN({$db_field}) min, MAX({$db_field}) max FROM ?:{$field['table']} ?p WHERE ?:products.status IN ('A') ?p", $fields_join . $_join, $where . $fields_where);
                        //var_dump($field_range_values);echo"<br/>________________________<br/>";
                        if (fn_is_empty($field_range_values[$filter_id])) {
                            unset($field_range_values[$filter_id]);
                        } else {
                            if ($field['field_type'] == 'P' && CART_SECONDARY_CURRENCY != CART_PRIMARY_CURRENCY) {
                                $coef = Registry::get('currencies.' . CART_SECONDARY_CURRENCY . '.coefficient');
                                $field_range_values[$filter_id]['min'] = floatval($field_range_values[$filter_id]['min']) / floatval($coef);
                                $field_range_values[$filter_id]['max'] = floatval($field_range_values[$filter_id]['max']) / floatval($coef);
                            }
                            $field_range_values[$filter_id]['min'] = floor($field_range_values[$filter_id]['min'] / $filters[$filter_id]['round_to']) * $filters[$filter_id]['round_to'];
                            $field_range_values[$filter_id]['max'] = ceil($field_range_values[$filter_id]['max'] / $filters[$filter_id]['round_to']) * $filters[$filter_id]['round_to'];
                            if ($field_range_values[$filter_id]['max'] - $field_range_values[$filter_id]['min'] <= $filters[$filter_id]['round_to']) {
                                $field_range_values[$filter_id]['max'] = $field_range_values[$filter_id]['min'] + $filters[$filter_id]['round_to'];
                            }
                            if (!empty($slider_vals[$field['field_type']])) {
                                $_slider_vals[$field['field_type']] = $slider_vals[$field['field_type']];
                                if ($field['field_type'] == 'P' && $slider_vals['P'][2] != CART_SECONDARY_CURRENCY) {
                                    $prev_coef = Registry::get('currencies.' . $slider_vals['P'][2] . '.coefficient');
                                    $cur_coef = Registry::get('currencies.' . CART_SECONDARY_CURRENCY . '.coefficient');
                                    $slider_vals['P'][0] = floor(floatval($slider_vals['P'][0]) * floatval($prev_coef) / floatval($cur_coef));
                                    $slider_vals['P'][1] = ceil(floatval($slider_vals['P'][1]) * floatval($prev_coef) / floatval($cur_coef));
                                }
                                $field_range_values[$filter_id]['left'] = $slider_vals[$field['field_type']][0];
                                $field_range_values[$filter_id]['right'] = $slider_vals[$field['field_type']][1];
                                if ($field_range_values[$filter_id]['left'] < $field_range_values[$filter_id]['min']) {
                                    $field_range_values[$filter_id]['left'] = $field_range_values[$filter_id]['min'];
                                }
                                if ($field_range_values[$filter_id]['left'] > $field_range_values[$filter_id]['max']) {
                                    $field_range_values[$filter_id]['left'] = $field_range_values[$filter_id]['max'];
                                }
                                if ($field_range_values[$filter_id]['right'] > $field_range_values[$filter_id]['max']) {
                                    $field_range_values[$filter_id]['right'] = $field_range_values[$filter_id]['max'];
                                }
                                if ($field_range_values[$filter_id]['right'] < $field_range_values[$filter_id]['min']) {
                                    $field_range_values[$filter_id]['right'] = $field_range_values[$filter_id]['min'];
                                }
                                if ($field_range_values[$filter_id]['right'] < $field_range_values[$filter_id]['left']) {
                                    $tmp = $field_range_values[$filter_id]['right'];
                                    $field_range_values[$filter_id]['right'] = $field_range_values[$filter_id]['left'];
                                    $field_range_values[$filter_id]['left'] = $tmp;
                                }
                                $field_range_values[$filter_id]['left'] = floor($field_range_values[$filter_id]['left'] / $filters[$filter_id]['round_to']) * $filters[$filter_id]['round_to'];
                                $field_range_values[$filter_id]['right'] = ceil($field_range_values[$filter_id]['right'] / $filters[$filter_id]['round_to']) * $filters[$filter_id]['round_to'];
                                /*if ($field_range_values[$filter_id]['right'] - $field_range_values[$filter_id]['left'] <= $filters[$filter_id]['round_to']) {
                                      $field_range_values[$filter_id]['right'] = $field_range_values[$filter_id]['left'] + $filters[$filter_id]['round_to'];
                                  }*/
                                if (!empty($field_range_values[$filter_id]['left']) || !empty($field_range_values[$filter_id]['right'])) {
                                    if ($field['field_type'] == 'P') {
                                        if (strpos($sliders_join, 'JOIN ?:product_prices ') === false) {
                                            if (strpos($join, 'JOIN ?:product_prices ') === false) {
                                                $sliders_join .= db_quote(" LEFT JOIN ?:product_prices ON ?:product_prices.product_id = ?:products.product_id AND ?:product_prices.lower_limit = 1 AND ?:product_prices.usergroup_id IN (?n)", array_merge(array(USERGROUP_ALL), $_SESSION['auth']['usergroup_ids']));
                                            }
                                            $vals = $_slider_vals['P'];
                                            $currency = !empty($vals[2]) ? $vals[2] : CART_PRIMARY_CURRENCY;
                                            if ($currency != CART_PRIMARY_CURRENCY) {
                                                $coef = Registry::get('currencies.' . $currency . '.coefficient');
                                                $decimals = Registry::get('currencies.' . CART_PRIMARY_CURRENCY . '.decimals');
                                                $vals[0] = round(floatval($vals[0]) * floatval($coef), $decimals);
                                                $vals[1] = round(floatval($vals[1]) * floatval($coef), $decimals);
                                            }
                                            $sliders_where .= db_quote(" AND ?:product_prices.price >= ?i AND ?:product_prices.price <= ?i", $vals[0], $vals[1]);
                                        }
                                    } elseif ($field['field_type'] == 'A') {
                                        if (strpos($sliders_join, 'JOIN ?:product_options_inventory ') === false) {
                                            if (strpos($join, 'JOIN ?:product_options_inventory ') === false) {
                                                $sliders_join .= " LEFT JOIN ?:product_options_inventory as inventory ON inventory.product_id = ?:products.product_id";
                                            }
                                            $sliders_where .= db_quote(" AND {$db_field} >= ?i AND {$db_field} <= ?i", $field_range_values[$filter_id]['left'], $field_range_values[$filter_id]['right']);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // Char values (free shipping etc)
                } elseif ($field['condition_type'] == 'C') {
                    $field_ranges_counts[$filter_id] = db_get_hash_array("SELECT COUNT(DISTINCT ?:{$field['table']}.product_id) as products, ?:{$field['table']}.{$field['db_field']} as range_name, ?s AS field_type FROM ?:{$field['table']} ?p WHERE ?:products.status = 'A' ?p GROUP BY ?:{$field['table']}.{$field['db_field']}", 'range_name', $field['field_type'], $join, $where);
                    if (!empty($field_ranges_counts[$filter_id])) {
                        foreach ($field_ranges_counts[$filter_id] as $range_key => $range) {
                            $field_ranges_counts[$filter_id][$range_key]['range_name'] = $field['variant_descriptions'][$range['range_name']];
                            $field_ranges_counts[$filter_id][$range_key]['range_id'] = $range['range_name'] == 'Y' ? 1 : 0;
                        }
                    }
                    // Fixed values (supplier etc)
                } elseif ($field['condition_type'] == 'F') {
                    $field_ranges_counts[$filter_id] = db_get_hash_array("SELECT COUNT(DISTINCT ?:{$field['table']}.product_id) as products, ?:{$field['foreign_table']}.{$field['range_name']} as range_name, UPPER(SUBSTRING(?:{$field['foreign_table']}.{$field['range_name']}, 1, 1)) AS `index`, ?:{$field['foreign_table']}.{$field['foreign_index']} as range_id, ?s AS field_type FROM ?:{$field['table']} LEFT JOIN ?:{$field['foreign_table']} ON ?:{$field['foreign_table']}.{$field['foreign_index']} = ?:{$field['table']}.{$field['db_field']} ?p WHERE ?:products.status IN ('A') ?p GROUP BY ?:{$field['table']}.{$field['db_field']} ORDER BY ?:{$field['foreign_table']}.{$field['range_name']} ", 'range_id', $field['field_type'], $join, $where);
                }
            }
        }
        $filter_company_condition = "";
        if (fn_allowed_for('ULTIMATE') && Registry::get('runtime.company_id')) {
            $filters_list = db_get_fields("SELECT ?:product_filters.filter_id FROM ?:product_filters");
            if (!empty($filters_list)) {
                $filter_company_condition = db_quote(" AND ?:product_filters.filter_id IN (?a)", $filters_list);
            }
        }
        if (!fn_allowed_for('ULTIMATE') || !empty($filters_list)) {
            $variants_counts = db_get_hash_multi_array("SELECT " . implode(', ', $values_fields) . " FROM ?:product_features_values LEFT JOIN ?:products ON ?:products.product_id = ?:product_features_values.product_id LEFT JOIN ?:product_filters ON ?:product_filters.feature_id = ?:product_features_values.feature_id AND ?:product_filters.status = 'A' LEFT JOIN ?:product_feature_variants ON ?:product_feature_variants.variant_id = ?:product_features_values.variant_id LEFT JOIN ?:product_feature_variant_descriptions ON ?:product_feature_variant_descriptions.variant_id = ?:product_feature_variants.variant_id AND ?:product_feature_variant_descriptions.lang_code = ?s LEFT JOIN ?:product_features ON ?:product_features.feature_id = ?:product_filters.feature_id ?p WHERE ?:product_features_values.feature_id IN (?n) AND ?:product_features_values.lang_code = ?s AND ?:product_features_values.variant_id ?p ?p AND ?:product_features.feature_type IN ('S', 'M', 'E') GROUP BY ?:product_features_values.variant_id, ?:product_filters.filter_id ORDER BY ?:product_feature_variants.position, ?:product_feature_variant_descriptions.variant", array('filter_id', 'range_id'), CART_LANGUAGE, $join . $sliders_join, $feature_ids, CART_LANGUAGE, $where . $sliders_where . $filter_company_condition, $filter_vq);
        } else {
            $variants_counts = array();
        }
        $ranges_counts = db_get_hash_multi_array("SELECT " . implode(', ', $ranges_fields) . " FROM ?:product_filter_ranges LEFT JOIN ?:product_features_values ON ?:product_features_values.feature_id = ?:product_filter_ranges.feature_id AND ?:product_features_values.value_int >= ?:product_filter_ranges.from AND ?:product_features_values.value_int <= ?:product_filter_ranges.to LEFT JOIN ?:products ON ?:products.product_id = ?:product_features_values.product_id LEFT JOIN ?:product_filter_ranges_descriptions ON ?:product_filter_ranges_descriptions.range_id = ?:product_filter_ranges.range_id AND ?:product_filter_ranges_descriptions.lang_code = ?s LEFT JOIN ?:product_features ON ?:product_features.feature_id = ?:product_filter_ranges.feature_id ?p WHERE ?:product_features_values.feature_id IN (?n) AND ?:product_features_values.lang_code = ?s ?p ?p GROUP BY ?:product_filter_ranges.range_id ORDER BY ?:product_filter_ranges.position, ?:product_filter_ranges_descriptions.range_name", array('filter_id', 'range_id'), CART_LANGUAGE, $join . $sliders_join, $feature_ids, CART_LANGUAGE, $where . $sliders_where, $filter_rq);
        $merged = fn_array_merge($variants_counts, $ranges_counts, $field_ranges_counts);
        $view_all = array();
        if (empty($merged) && empty($params['skip_other_variants']) && (!empty($av_ids) || !empty($ranges_ids) || !empty($_field_ranges_ids))) {
            fn_set_notification('W', __('text_nothing_found'), __('text_nothing_found_filter_message'));
            if (defined('AJAX_REQUEST')) {
                exit;
            } elseif (!empty($_SERVER['HTTP_REFERER'])) {
                fn_redirect($_SERVER['HTTP_REFERER']);
            } else {
                $_params = $params;
                $_params['skip_advanced_variants'] = true;
                $_params['only_selected'] = true;
                list($_f, $_view_all) = fn_get_filters_products_count($_params);
                foreach ($_f as $filter_id => $filter) {
                    if (!empty($field_range_values[$filter_id])) {
                        $_f[$filter_id]['range_values'] = $field_range_values[$filter_id];
                    }
                }
                return array($_f, $_view_all);
            }
        }
        foreach ($filters as $filter_id => $filter) {
            if (!empty($field_range_values[$filter_id]) || !empty($merged[$filter_id]) && empty($params['view_all']) || !empty($params['filter_id']) && $params['filter_id'] != $filter_id) {
                // Check if filter range was selected
                if (!empty($merged[$filter_id])) {
                    if (empty($filters[$filter_id]['feature_id'])) {
                        $intersect = array_intersect(array_keys($merged[$filter_id]), $field_ranges_ids);
                    } else {
                        $intersect = array_intersect(array_keys($merged[$filter_id]), $ranges_ids);
                    }
                }
                if (!empty($intersect)) {
                    foreach ($merged[$filter_id] as $k => $v) {
                        if (!in_array($v['range_id'], $intersect)) {
                            // Unset unselected ranges
                            unset($merged[$filter_id][$k]);
                        }
                    }
                }
                if (!empty($field_range_values[$filter_id])) {
                    $filters[$filter_id]['range_values'] = $field_range_values[$filter_id];
                }
                $filters[$filter_id]['ranges'] =& $merged[$filter_id];
                // Add feature type to the filter
                if (!empty($merged[$filter_id])) {
                    $_first = reset($merged[$filter_id]);
                    if (!empty($_first['feature_type'])) {
                        $filters[$filter_id]['feature_type'] = $_first['feature_type'];
                    }
                }
                if (!empty($params['simple_link']) && $filters[$filter_id]['feature_type'] == 'E') {
                    $filters[$filter_id]['simple_link'] = true;
                }
                if (empty($params['advanced_filter']) && empty($params['skip_other_variants']) && !empty($filters[$filter_id]['ranges'])) {
                    $selected = array();
                    $features_hash = !empty($params['features_hash']) ? $params['features_hash'] : '';
                    foreach ($filters[$filter_id]['ranges'] as $_k => $r) {
                        if (fn_check_selected_filter($r['range_id'], !empty($r['feature_type']) ? $r['feature_type'] : '', $params, $filters[$filter_id]['field_type'])) {
                            // selected variant
                            $selected[$_k] = $r;
                            $selected[$_k]['selected'] = true;
                            unset($filters[$filter_id]['ranges'][$_k]);
                            $features_hash = fn_delete_range_from_url($features_hash, $r, $filters[$filter_id]['field_type']);
                        }
                    }
                    if (!empty($selected)) {
                        $selected_range_ids = array_keys($selected);
                        // Get other variants
                        $_params = $params;
                        //$_params['filter_id'] = $filter_id;
                        $_params['features_hash'] = $features_hash;
                        $_params['skip_other_variants'] = true;
                        unset($_params['variant_id'], $_params['check_location']);
                        list($_f) = fn_get_filters_products_count($_params);
                        if (!empty($_f[$filter_id])) {
                            $_f = $_f[$filter_id];
                            if (!empty($_f['ranges'])) {
                                // delete current range
                                foreach ($_f['ranges'] as $_rid => $_rv) {
                                    if (in_array($_rid, $selected_range_ids)) {
                                        unset($_f['ranges'][$_rid]);
                                    }
                                }
                                $filters[$filter_id]['ranges'] = $_f['ranges'];
                                $filters[$filter_id]['more_cut'] = !empty($_f['more_cut']) ? $_f['more_cut'] : false;
                            }
                        }
                        $filters[$filter_id]['selected_ranges'] = $selected;
                    }
                    if (!empty($params['only_selected'])) {
                        //unset($filters[$filter_id]['ranges']);
                        foreach ($filters[$filter_id]['ranges'] as $k => $v) {
                            $filters[$filter_id]['ranges'][$k]['disabled'] = true;
                        }
                    } else {
                        $_params = $params;
                        $_params['filter_id'] = $filter_id;
                        $_params['features_hash'] = '';
                        $_params['get_custom'] = true;
                        $_params['skip_other_variants'] = true;
                        unset($_params['variant_id'], $_params['check_location']);
                        list($_f) = fn_get_filters_products_count($_params);
                        if (!empty($_f[$filter_id])) {
                            $_f = $_f[$filter_id];
                            if (!empty($_f['ranges'])) {
                                foreach ($_f['ranges'] as $_rid => $_rv) {
                                    if (!isset($filters[$filter_id]['ranges'][$_rid]) && !isset($filters[$filter_id]['selected_ranges'][$_rid])) {
                                        $filters[$filter_id]['ranges'][$_rid] = $_rv;
                                        $filters[$filter_id]['ranges'][$_rid]['disabled'] = true;
                                        if (fn_check_selected_filter($_rv['range_id'], !empty($_rv['feature_type']) ? $_rv['feature_type'] : '', $params, !empty($_f[$filter_id]) ? $_f[$filter_id]['field_type'] : $_f['field_type'])) {
                                            $filters[$filter_id]['ranges'][$_rid]['checked'] = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // Calculate number of ranges and compare with displaying count
                    if (empty($params['get_all'])) {
                        if (!empty($filters[$filter_id]['ranges'])) {
                            $count = count($filters[$filter_id]['ranges']);
                        } else {
                            $count = 1;
                        }
                        if ($count > $filters[$filter_id]['display_more_count']) {
                            $filters[$filter_id]['more_ranges'] = array_slice($filters[$filter_id]['ranges'], 0, $filters[$filter_id]['display_more_count'], true);
                            $count = $filters[$filter_id]['display_more_count'];
                            $filters[$filter_id]['more_cut'] = true;
                        } else {
                            $filters[$filter_id]['more_ranges'] = $filters[$filter_id]['ranges'];
                        }
                        $filters[$filter_id]['ranges'] = array_slice($filters[$filter_id]['more_ranges'], 0, $filters[$filter_id]['display_count'], true);
                        $filters[$filter_id]['more_ranges'] = array_slice($filters[$filter_id]['more_ranges'], $filters[$filter_id]['display_count'], $count, true);
                    }
                } else {
                    if (!empty($params['variant_id']) && !empty($filters[$filter_id]['ranges'][$params['variant_id']])) {
                        $filters[$filter_id]['ranges'][$params['variant_id']]['selected'] = true;
                        // mark selected variant
                    }
                }
                continue;
                // If its "view all" page, return all ranges
            } elseif (!empty($params['filter_id']) && $params['filter_id'] == $filter_id && !empty($merged[$filter_id])) {
                if (empty($params['return_view_all'])) {
                    $filters[$filter_id]['ranges'] =& $merged[$filter_id];
                    $selected = array();
                    $features_hash = !empty($params['features_hash']) ? $params['features_hash'] : '';
                    foreach ($filters[$filter_id]['ranges'] as $_k => $r) {
                        if (fn_check_selected_filter($r['range_id'], !empty($r['feature_type']) ? $r['feature_type'] : '', $params, $filters[$filter_id]['field_type'])) {
                            $selected[$_k] = $r;
                            $selected[$_k]['selected'] = true;
                            unset($filters[$filter_id]['ranges'][$_k]);
                            $features_hash = fn_delete_range_from_url($features_hash, $r, $filters[$filter_id]['field_type']);
                            continue;
                        }
                    }
                    if (!empty($selected)) {
                        $selected_range_ids = array_keys($selected);
                        // Get other variants
                        $_params = $params;
                        $_params['filter_id'] = $filter_id;
                        $_params['features_hash'] = $features_hash;
                        $_params['skip_other_variants'] = true;
                        $_params['return_view_all'] = true;
                        unset($_params['variant_id'], $_params['check_location']);
                        list($_f, $view_all) = fn_get_filters_products_count($_params);
                    }
                }
                if (empty($view_all)) {
                    foreach ($merged[$filter_id] as $range) {
                        if (!empty($range['index']) || strlen($range['index']) > 0) {
                            // feature
                            $view_all[$range['index']][] = $range;
                        } else {
                            // custom range
                            $view_all[$filters[$range['filter_id']]['filter']][] = $range;
                        }
                    }
                    ksort($view_all);
                }
            }
            // Unset filter if it's empty
            unset($filters[$filter_id]);
        }
        if (!empty($params['advanced_filter'])) {
            $_params = array('feature_types' => array('C', 'T'), 'plain' => true, 'category_ids' => array(empty($params['category_id']) ? 0 : $params['category_id']));
            list($features) = fn_get_product_features($_params);
            if (!empty($features)) {
                $filters = array_merge($filters, $features);
            }
        }
        /**
         * Change product filters data
         *
         * @param array $filters  Product filters data
         * @param array $view_all All ranges filters
         * @param array $params Products filter search params
         */
        fn_set_hook('get_filters_products_count_before_select', $filters, $view_all, $params);
        Registry::set($key, array($filters, $view_all));
    } else {
        list($filters, $view_all) = Registry::get($key);
    }
    return array($filters, $view_all);
}
Example #13
0
 /**
  * Puts static SEO name to cache
  * @param string $key cache key
  * @param string $lang_code language code
  * @param string $area current working area
  * @return mixed cached data
  */
 private static function getStatic($key, $lang_code, $area = AREA)
 {
     if ($area != 'C') {
         return null;
     }
     if (!self::$init_cache) {
         Registry::registerCache('seo_cache_static', array('seo_names'), Registry::cacheLevel('static') . $lang_code, true);
     }
     return Registry::get('seo_cache_static.' . $key);
 }
Example #14
0
 private static function getStatic($key)
 {
     if (!self::$init_cache) {
         Registry::registerCache('yandex_delivery_cache_static', YD_CACHE_STATIC, Registry::cacheLevel('time'));
     }
     return Registry::get('yandex_delivery_cache_static.' . $key);
 }
Example #15
0
 public function set($name, $data, $condition, $cache_level = null)
 {
     if (!empty($data)) {
         apcu_store($this->_mapTags($name) . '/' . $cache_level, $data, $cache_level == Registry::cacheLevel('time') ? TIME + $condition : $this->global_ttl);
     }
 }
Example #16
0
function fn_searchanise_get_filters_products_count($params)
{
    if (AREA == 'A' || fn_se_check_disabled() || !empty($params['disable_searchanise']) || empty($params['q']) && fn_se_get_simple_setting('use_navigation') !== 'Y' || fn_se_get_import_status(fn_se_get_company_id(), CART_LANGUAGE) != 'done' || Registry::ifGet('addons.age_verification.status', 'D') == 'A' || Registry::ifGet('addons.vendor_data_premoderation.status', 'D') == 'A') {
        return fn_get_filters_products_count($params);
    }
    $key = 'pfilters_se_' . md5(serialize($params));
    Registry::registerCache($key, array('products', 'product_features', 'product_filters', 'product_features_values', 'categories'), Registry::cacheLevel('user'));
    // Check exist cache.
    if (Registry::isExist($key) == true) {
        list($filters, $view_all) = Registry::get($key);
    } else {
        if (!fn_se_check_product_filter_block()) {
            return array();
        }
        if (!empty($params['check_location'])) {
            // FIXME: this is bad style, should be refactored
            $valid_locations = array('index.index', 'products.search', 'categories.view', 'product_features.view');
            if (!in_array($params['dispatch'], $valid_locations)) {
                return array();
            }
            if ($params['dispatch'] == 'categories.view') {
                $params['simple_link'] = true;
                // this parameter means that extended filters on this page should be displayed as simple
                $params['filter_custom_advanced'] = true;
                // this parameter means that extended filtering should be stayed on the same page
            } else {
                if ($params['dispatch'] == 'product_features.view') {
                    $params['simple_link'] = true;
                    $params['features_hash'] = (!empty($params['features_hash']) ? $params['features_hash'] . '.' : '') . 'V' . $params['variant_id'];
                    //$params['exclude_feature_id'] = db_get_field("SELECT feature_id FROM ?:product_features_values WHERE variant_id = ?i", $params['variant_id']);
                }
                $params['get_for_home'] = 'Y';
            }
        }
        // hide filters block on the advanced search page
        if (!empty($params['skip_if_advanced']) && !empty($params['advanced_filter']) && $params['advanced_filter'] == 'Y') {
            return array();
        }
        // End copied code.
        $get_custom = !empty($params['get_custom']);
        $received_facets = Registry::get('searchanise.received_facets');
        $r_filters = $view_all = $variants_ids = $feature_variants = $fields_ids = $slider_vals = $category_facets = array();
        $params['filters_category_id'] = empty($params['category_id']) ? 0 : $params['category_id'];
        if (is_null($received_facets) || $get_custom) {
            list($restrict_by, $query_by, $union) = fn_se_prepare_request_params($params);
            $request_params = array('items' => 'false', 'facets' => 'true', 'union' => $union, 'queryBy' => $query_by, 'restrictBy' => $restrict_by);
            $result = fn_searchanise_send_search_request($request_params);
            if (empty($result)) {
                return fn_get_filters_products_count($params);
            }
            $received_facets = $result['facets'];
        }
        if (empty($received_facets)) {
            // Nothing found
            return array();
        }
        if (!empty($params['features_hash'])) {
            list(, , $fields_ids, $slider_vals) = fn_parse_features_hash($params['features_hash']);
            //
            // Get without
            //
            list($restrict_by, $query_by, $union) = fn_se_prepare_request_params(array_merge($params, array('features_hash' => '')));
            $request_params = array('items' => 'false', 'facets' => 'true', 'union' => $union, 'queryBy' => $query_by, 'restrictBy' => $restrict_by);
            $result = fn_searchanise_send_search_request($request_params);
            if (empty($result)) {
                return fn_get_filters_products_count($params);
            } else {
                $category_facets = $result['facets'];
            }
        }
        $params_for_filters = array('get_variants' => true);
        if (!empty($params['item_ids'])) {
            $params_for_filters['filter_id'] = $params['item_ids'];
        }
        $params_for_filters = array_merge($params_for_filters, $params);
        list($filters, ) = fn_get_product_filters($params_for_filters);
        if (empty($filters)) {
            return array(array(), false);
        }
        $fields = fn_get_product_filter_fields();
        foreach ($filters as $filter_id => $filter) {
            $r_facet = $c_facet = array();
            foreach ($received_facets as $r) {
                $r_feature_id = str_replace('feature_', '', $r['attribute']);
                if (!empty($filter['feature_id']) && $r_feature_id == $filter['feature_id'] || !empty($filter['field_type']) && !empty($fields[$filter['field_type']]['db_field']) && $fields[$filter['field_type']]['db_field'] == $r_feature_id) {
                    $r_facet = $r;
                    break;
                }
            }
            if (empty($r_facet) && $get_custom == false) {
                unset($filters[$filter_id]);
                continue;
            }
            foreach ($category_facets as $c) {
                if ($c['attribute'] == $r_facet['attribute']) {
                    $c_facet = $c;
                    break;
                }
            }
            if ($filter['field_type'] == 'F') {
                $filters[$filter_id]['ranges'] = $filter['ranges'] = array('N' => array('range_id' => 0, 'range_name' => __('no'), 'products' => 0), 'Y' => array('range_id' => 1, 'range_name' => __('yes'), 'products' => 0));
            } elseif ($filter['field_type'] == 'S' && (count($r_facet['buckets']) == 1 && $r_facet['buckets'][0]['value'] == 0) == false) {
                //skip if only default vendor (id=0) range passed
                $_companies = array();
                $companies = db_get_hash_single_array("SELECT ?:companies.company_id, ?:companies.company FROM ?:companies  WHERE status = 'A' ORDER BY ?:companies.company", array('company_id', 'company'));
                foreach ($companies as $company_id => $company) {
                    $_companies[$company_id] = array('range_id' => $company_id, 'range_name' => $company, 'products' => 0);
                }
                $filters[$filter_id]['ranges'] = $filter['ranges'] = $_companies;
            }
            $ranges_count = 0;
            $tmp_ranges = array('selected' => array(), 'used' => array(), 'disabled' => array());
            $filter['ranges'] = isset($filter['ranges']) ? $filter['ranges'] : array();
            //
            // Speed up for many variants!
            //
            if (!empty($filter['feature_id']) && !in_array($filter['feature_type'], array('D', 'N', 'O'))) {
                $rr_ranges = array();
                foreach ($r_facet['buckets'] as $r) {
                    $rr_ranges[$r['value']] = $r;
                }
                $cc_ranges = array();
                if (!empty($c_facet)) {
                    foreach ($c_facet['buckets'] as $cc) {
                        $cc_ranges[$cc['value']] = $cc;
                    }
                }
            }
            foreach ($filter['ranges'] as $s_range_id => $s_range) {
                $r_range = array();
                if (!empty($filter['feature_id']) && !in_array($filter['feature_type'], array('D', 'N', 'O'))) {
                    // features with variants
                    $r_range = isset($rr_ranges[$s_range['variant_id']]) ? $rr_ranges[$s_range['variant_id']] : array();
                } elseif ($filter['field_type'] == 'F') {
                    // Free shipping
                    foreach ($r_facet['buckets'] as $r) {
                        if ($r['value'] == $s_range_id) {
                            $r_range = $r;
                            break;
                        }
                    }
                } elseif ($filter['field_type'] == 'S') {
                    // Vendors
                    foreach ($r_facet['buckets'] as $r) {
                        if ($r['value'] == $s_range_id) {
                            unset($r['selected']);
                            foreach ($fields_ids as $fr_id => $ff_type) {
                                if ($ff_type == 'S' && $fr_id == $r['value']) {
                                    $r['selected'] = true;
                                }
                            }
                            $r_range = $r;
                            break;
                        }
                    }
                } else {
                    // range
                    foreach ($r_facet['buckets'] as $r) {
                        if (abs($r['from'] - $s_range['from']) < 0.01 && abs($r['to'] - $s_range['to']) < 0.01) {
                            $r_range = $r;
                            break;
                        }
                    }
                }
                $range_id = isset($s_range['variant_id']) ? $s_range['variant_id'] : $s_range['range_id'];
                $new_range = array('feature_id' => $filter['feature_id'], 'range_id' => $range_id, 'range_name' => isset($s_range['variant']) ? $s_range['variant'] : $s_range['range_name'], 'feature_type' => $filter['feature_type'], 'filter_id' => $filter_id);
                if (!empty($r_range)) {
                    $new_range['products'] = $r_range['count'];
                }
                if (empty($r_range['selected']) && fn_check_selected_filter($new_range['range_id'], !empty($new_range['feature_type']) ? $new_range['feature_type'] : '', $params, $filter['field_type'])) {
                    $new_range['checked'] = true;
                }
                if (!empty($r_range['selected'])) {
                    $is_select_found = true;
                    $new_range['selected'] = true;
                    $tmp_ranges['selected'][$range_id] = $new_range;
                } elseif (!empty($r_range)) {
                    $tmp_ranges['used'][$range_id] = $new_range;
                } elseif (!empty($c_facet['buckets'])) {
                    $c_range = false;
                    if (!empty($filter['feature_id']) && !in_array($filter['feature_type'], array('D', 'N', 'O'))) {
                        // features with variants
                        $c_range = isset($cc_ranges[$s_range['variant_id']]) ? $cc_ranges[$s_range['variant_id']] : array();
                    } elseif ($filter['field_type'] == 'F') {
                        // Free shipping
                        foreach ($c_facet['buckets'] as $c) {
                            if ($c['value'] == $s_range_id) {
                                $c_range = $c;
                                break;
                            }
                        }
                    } elseif ($filter['field_type'] == 'S') {
                        // Suppliers
                        foreach ($c_facet['buckets'] as $c) {
                            if ($c['value'] == $s_range_id) {
                                $c_range = $c;
                                break;
                            }
                        }
                    } else {
                        // range
                        foreach ($c_facet['buckets'] as $c) {
                            if (abs($c['from'] - $s_range['from']) < 0.01 && abs($c['to'] - $s_range['to']) < 0.01) {
                                $c_range = $c;
                                break;
                            }
                        }
                    }
                    if (!empty($c_range)) {
                        $new_range['disabled'] = true;
                        $tmp_ranges['disabled'][$range_id] = $new_range;
                    }
                }
                $ranges_count++;
            }
            // \ by store filter ranges
            if (!empty($filters[$filter_id]['slider'])) {
                $is_select_found = true;
                $r_range = $r_facet['buckets'][0];
                $r = array('min' => $r_range['from'], 'max' => $r_range['to']);
                $field_type = $filters[$filter_id]['field_type'];
                if ($field_type == 'P' && CART_SECONDARY_CURRENCY != CART_PRIMARY_CURRENCY) {
                    $coef = Registry::get('currencies.' . CART_SECONDARY_CURRENCY . '.coefficient');
                    $r['min'] = floatval($r['min']) / floatval($coef);
                    $r['max'] = floatval($r['max']) / floatval($coef);
                }
                $r['min'] = floor($r['min'] / $filters[$filter_id]['round_to']) * $filters[$filter_id]['round_to'];
                $r['max'] = ceil($r['max'] / $filters[$filter_id]['round_to']) * $filters[$filter_id]['round_to'];
                if ($r['max'] - $r['min'] <= $filters[$filter_id]['round_to']) {
                    $r['max'] = $r['min'] + $filters[$filter_id]['round_to'];
                }
                if (!empty($slider_vals[$field_type])) {
                    if ($field_type == 'P' && $slider_vals['P'][2] != CART_SECONDARY_CURRENCY) {
                        $prev_coef = Registry::get('currencies.' . $slider_vals['P'][2] . '.coefficient');
                        $cur_coef = Registry::get('currencies.' . CART_SECONDARY_CURRENCY . '.coefficient');
                        $slider_vals['P'][0] = floor(floatval($slider_vals['P'][0]) * floatval($prev_coef) / floatval($cur_coef));
                        $slider_vals['P'][1] = ceil(floatval($slider_vals['P'][1]) * floatval($prev_coef) / floatval($cur_coef));
                    }
                    $r['left'] = $slider_vals[$field_type][0];
                    $r['right'] = $slider_vals[$field_type][1];
                    if ($r['left'] < $r['min']) {
                        $r['left'] = $r['min'];
                    }
                    if ($r['left'] > $r['max']) {
                        $r['left'] = $r['max'];
                    }
                    if ($r['right'] > $r['max']) {
                        $r['right'] = $r['max'];
                    }
                    if ($r['right'] < $r['min']) {
                        $r['right'] = $r['min'];
                    }
                    if ($r['right'] < $r['left']) {
                        $tmp = $r['right'];
                        $r['right'] = $r['left'];
                        $r['left'] = $tmp;
                    }
                    $r['left'] = floor($r['left'] / $filters[$filter_id]['round_to']) * $filters[$filter_id]['round_to'];
                    $r['right'] = ceil($r['right'] / $filters[$filter_id]['round_to']) * $filters[$filter_id]['round_to'];
                }
                $filters[$filter_id]['range_values'] = $r;
            } else {
                if (empty($tmp_ranges)) {
                    unset($filters[$filter_id]);
                } else {
                    if (!empty($tmp_ranges['selected'])) {
                        $filters[$filter_id]['selected_ranges'] = $tmp_ranges['selected'];
                    }
                    $filters[$filter_id]['ranges'] = $tmp_ranges['used'] + $tmp_ranges['disabled'];
                    // Calculate number of ranges and compare with displaying count
                    if (empty($params['get_all'])) {
                        if (!empty($filters[$filter_id]['ranges'])) {
                            $count = count($filters[$filter_id]['ranges']);
                        } else {
                            $count = 1;
                        }
                        if ($count > $filters[$filter_id]['display_more_count']) {
                            $filters[$filter_id]['more_ranges'] = array_slice($filters[$filter_id]['ranges'], 0, $filters[$filter_id]['display_more_count'], true);
                            $count = $filters[$filter_id]['display_more_count'];
                            $filters[$filter_id]['more_cut'] = true;
                        } else {
                            $filters[$filter_id]['more_ranges'] = $filters[$filter_id]['ranges'];
                        }
                        $filters[$filter_id]['ranges'] = array_slice($filters[$filter_id]['more_ranges'], 0, $filters[$filter_id]['display_count'], true);
                        $filters[$filter_id]['more_ranges'] = array_slice($filters[$filter_id]['more_ranges'], $filters[$filter_id]['display_count'], $count, true);
                    }
                    if (!empty($params['simple_link']) && $filters[$filter_id]['feature_type'] == 'E') {
                        $filters[$filter_id]['simple_link'] = true;
                    }
                }
            }
        }
        if (empty($is_select_found) && empty($params['skip_other_variants']) && !empty($params['features_hash'])) {
            fn_set_notification('W', __('text_nothing_found'), __('text_nothing_found_filter_message'));
            if (defined('AJAX_REQUEST')) {
                die;
            } elseif (!empty($_SERVER['HTTP_REFERER'])) {
                fn_redirect($_SERVER['HTTP_REFERER'], true);
            } else {
                $_params = $params;
                $_params['skip_advanced_variants'] = true;
                $_params['only_selected'] = true;
                if (!empty($params['features_hash']) && empty($params['skip_advanced_variants'])) {
                    list(, , , , $field_ranges_ids) = fn_parse_features_hash($params['features_hash']);
                }
                list($_f, $_view_all) = fn_get_filters_products_count($_params);
                foreach ($_f as $filter_id => $filter) {
                    if (!empty($field_range_values[$filter_id])) {
                        $_f[$filter_id]['range_values'] = $field_range_values[$filter_id];
                    }
                }
                return array($_f, $_view_all);
            }
        }
        // Adding to the cache.
        Registry::set($key, array($filters, $view_all));
    }
    return array($filters, $view_all);
}
Example #17
0
function smarty_block_hook($params, $content, &$smarty)
{
    static $overrides = array();
    $hook_content = '';
    $hook_name = 'thooks_' . $smarty->template_area;
    Registry::registerCache($hook_name, array('addons'), Registry::cacheLevel('static'));
    $hooks = Registry::ifGet($hook_name, array());
    if (!isset($hooks[$params['name']])) {
        list($dir, $name) = explode(':', $params['name']);
        $hooks_list = array('pre' => array(), 'post' => array(), 'override' => array());
        foreach (Registry::get('addons') as $addon => $data) {
            if ($data['status'] == 'D') {
                continue;
            }
            $files = array();
            foreach (Registry::get('addons') as $_addon => $_data) {
                if ($_data['status'] == 'D' || $_addon == $addon) {
                    continue;
                }
                $files[] = 'addons/' . $addon . '/addons/' . $_addon . '/hooks/' . $dir . '/' . $name;
            }
            $files[] = 'addons/' . $addon . '/hooks/' . $dir . '/' . $name;
            foreach ($files as $file) {
                if ($smarty->templateExists($file . '.pre.tpl')) {
                    $hooks_list['pre'][] = $file . '.pre.tpl';
                }
                if ($smarty->templateExists($file . '.post.tpl')) {
                    $hooks_list['post'][] = $file . '.post.tpl';
                }
                if ($smarty->templateExists($file . '.override.tpl')) {
                    $hooks_list['override'][] = $file . '.override.tpl';
                }
            }
        }
        if (fn_is_empty($hooks_list)) {
            $hooks[$params['name']] = array();
        } else {
            $hooks[$params['name']] = $hooks_list;
        }
        Registry::set($hook_name, $hooks);
    }
    if (is_null($content)) {
        // reset override for current hook
        $overrides[$params['name']] = false;
        // override hook should be call for opened tag to prevent pre/post hook execution
        if (!empty($hooks[$params['name']]['override'])) {
            $override_content = '';
            foreach ($hooks[$params['name']]['override'] as $tpl) {
                if ($tpl == $smarty->template_resource) {
                    continue;
                }
                $_hook_content = $smarty->fetch($tpl);
                if (trim($_hook_content)) {
                    $overrides[$params['name']] = true;
                    $hook_content = $_hook_content;
                }
            }
        }
        // prehook should be called for the opening {hook} tag to allow variables passed from hook to body
        if (empty($overrides[$params['name']])) {
            if (!empty($hooks[$params['name']]['pre'])) {
                foreach ($hooks[$params['name']]['pre'] as $tpl) {
                    $hook_content .= $smarty->fetch($tpl);
                }
            }
        }
    } else {
        // post hook should be called only if override hook was no executed
        if (empty($overrides[$params['name']])) {
            if (!empty($hooks[$params['name']]['post'])) {
                foreach ($hooks[$params['name']]['post'] as $tpl) {
                    $hook_content .= $smarty->fetch($tpl);
                }
            }
            $hook_content = $content . "\n" . $hook_content;
        }
    }
    fn_set_hook('smarty_block_hook_post', $params, $content, $overrides, $smarty, $hook_content);
    return $hook_content;
}
Example #18
0
 /**
  * Registers block cache
  *
  * @param string $cache_name   Cache name
  * @param array  $block_schema Block schema data
  * @param array  $block_data   Block data from DB
  *
  * @return bool Whether cache have been registered or not
  */
 public static function registerBlockCacheIfNeeded($cache_name, $block_schema, $block_data)
 {
     // @TODO: remove Registry calls and use RenderManager::$_location instead. This method should be non-static.
     $dispatch = Registry::get('runtime.controller') . '.' . Registry::get('runtime.mode');
     // Use parameters for current dispatch with fallback to common params
     if (!empty($block_schema['cache_overrides_by_dispatch'][$dispatch])) {
         $cache_params = $block_schema['cache_overrides_by_dispatch'][$dispatch];
     } elseif (!empty($block_schema['cache'])) {
         $cache_params = $block_schema['cache'];
     } else {
         return false;
     }
     $cookie_data = fn_get_session_data();
     $cookie_data['all'] = $cookie_data;
     $callable_handlers_variables = compact('block_schema', 'block_data');
     $disable_cache = false;
     // Check conditions that disable block caching
     if (!empty($cache_params['disable_cache_when'])) {
         $disable_cache |= self::findHandlerParamsAtData($cache_params['disable_cache_when'], 'request_handlers', $_REQUEST);
         $disable_cache |= self::findHandlerParamsAtData($cache_params['disable_cache_when'], 'session_handlers', $_SESSION);
         $disable_cache |= self::findHandlerParamsAtData($cache_params['disable_cache_when'], 'cookie_handlers', $cookie_data);
         $disable_cache |= self::findHandlerParamsAtData($cache_params['disable_cache_when'], 'auth_handlers', $_SESSION['auth']);
         // Disable cache if any of callable handlers returns true
         if (!empty($cache_params['disable_cache_when']['callable_handlers'])) {
             self::execCallableHandlers(function ($handler_name, $handler_result) use(&$disable_cache) {
                 $disable_cache |= $handler_result;
             }, (array) $cache_params['disable_cache_when']['callable_handlers'], $callable_handlers_variables);
         }
     }
     if ($disable_cache) {
         return false;
     }
     // Generate suffix to cache key using dependencies specified at schema
     $cache_key_suffix = '';
     $generate_additional_level = function ($param_name, $param_value) use(&$cache_key_suffix) {
         $cache_key_suffix .= '|' . $param_name . '=' . md5(serialize($param_value));
     };
     self::findHandlerParamsAtData($cache_params, 'request_handlers', $_REQUEST, $generate_additional_level);
     self::findHandlerParamsAtData($cache_params, 'session_handlers', $_SESSION, $generate_additional_level);
     self::findHandlerParamsAtData($cache_params, 'cookie_handlers', $cookie_data, $generate_additional_level);
     self::findHandlerParamsAtData($cache_params, 'auth_handlers', $_SESSION['auth'], $generate_additional_level);
     if (!empty($cache_params['callable_handlers'])) {
         self::execCallableHandlers($generate_additional_level, (array) $cache_params['callable_handlers'], $callable_handlers_variables);
     }
     $cache_key_suffix .= '|path=' . Registry::get('config.current_path');
     $cache_key_suffix .= Embedded::isEnabled() ? '|embedded' : '';
     $cache_key_suffix = empty($cache_key_suffix) ? '' : md5($cache_key_suffix);
     $default_update_handlers = fn_get_schema('block_manager', 'block_cache_properties');
     if (isset($cache_params['update_handlers']) && is_array($cache_params['update_handlers'])) {
         $handlers = array_merge($cache_params['update_handlers'], $default_update_handlers['update_handlers']);
     } else {
         $handlers = $default_update_handlers['update_handlers'];
     }
     $cache_level = isset($cache_params['cache_level']) ? $cache_params['cache_level'] : Registry::cacheLevel('html_blocks');
     Registry::registerCache($cache_name, $handlers, $cache_level . '__' . $cache_key_suffix);
     // Check conditions that trigger block cache regeneration
     $regenerate_cache = false;
     if (!empty($cache_params['regenerate_cache_when'])) {
         $regenerate_cache |= self::findHandlerParamsAtData($cache_params['regenerate_cache_when'], 'request_handlers', $_REQUEST);
         $regenerate_cache |= self::findHandlerParamsAtData($cache_params['regenerate_cache_when'], 'session_handlers', $_SESSION);
         $regenerate_cache |= self::findHandlerParamsAtData($cache_params['regenerate_cache_when'], 'cookie_handlers', $cookie_data);
         $regenerate_cache |= self::findHandlerParamsAtData($cache_params['regenerate_cache_when'], 'auth_handlers', $_SESSION['auth']);
         // Regenerate cache if any of callable handlers returns true
         if (!empty($cache_params['regenerate_cache_when']['callable_handlers'])) {
             self::execCallableHandlers(function ($handler_name, $handler_result) use(&$regenerate_cache) {
                 $regenerate_cache |= $handler_result;
             }, (array) $cache_params['regenerate_cache_when']['callable_handlers'], $callable_handlers_variables);
         }
     }
     if ($regenerate_cache) {
         Registry::del($cache_name);
     }
     return true;
 }
Example #19
0
function fn_watermarks_generate_thumbnail_post(&$relative_path, &$lazy)
{
    static $init_cache = false;
    $image_path_info = fn_pathinfo($relative_path);
    $image_name = $image_path_info['filename'];
    $key = 'wt_data_' . fn_crc32($image_name);
    $condition = array('images', 'images_links');
    if (fn_allowed_for('ULTIMATE')) {
        $condition[] = 'products';
        $condition[] = 'categories';
    }
    $cache_name = 'watermarks_cache_static';
    if (!$init_cache) {
        Registry::registerCache($cache_name, $condition, Registry::cacheLevel('static'), true);
        $init_cache = true;
    }
    $image_data = Registry::get($cache_name . '.' . $key);
    if (empty($image_data)) {
        $image_data = db_get_row("SELECT l.* FROM ?:images AS i, ?:images_links AS l WHERE (l.image_id = i.image_id OR detailed_id = i.image_id) AND image_path LIKE ?l", $image_name . '.%');
        if (empty($image_data)) {
            return true;
        }
        if (fn_allowed_for('ULTIMATE')) {
            $image_data['company_id'] = fn_wt_get_image_company_id($image_data);
        }
        Registry::set($cache_name . '.' . $key, $image_data);
    }
    $company_id = null;
    if (fn_allowed_for('ULTIMATE')) {
        $company_id = Registry::get('runtime.company_id');
        if ($company_id == null) {
            $company_id = $image_data['company_id'];
        }
    }
    if (!empty($image_data['object_type']) && fn_is_need_watermark($image_data['object_type'], $image_data['object_type'] == 'detailed', $company_id)) {
        $prefix = WATERMARKS_DIR_NAME;
        if (fn_allowed_for('ULTIMATE') && !Registry::get('runtime.company_id')) {
            $prefix = WATERMARKS_DIR_NAME . $company_id . '/';
        }
        if (!Storage::instance('images')->isExist($prefix . $relative_path)) {
            fn_watermark_create($relative_path, $prefix . $relative_path, false, $company_id);
        }
        $relative_path = $prefix . $relative_path;
    }
    return true;
}
Example #20
0
 /**
  * Gets scheme for some block type
  * @static
  * @param  string $block_type Block type. Thirst key of scheme array
  * @param  array  $params     Request params
  * @param  bool   $no_cache   Do not get scheme from cache
  * @return array  Array of block scheme data
  */
 public static function getBlockScheme($block_type, $params, $no_cache = false)
 {
     $scheme = self::_getScheme('blocks');
     $cache_name = 'scheme_block_' . $block_type;
     Registry::registerCache(array('scheme_block', $cache_name), array('addons'), Registry::cacheLevel('static'));
     if (Registry::isExist($cache_name) == true && $no_cache == false) {
         return Registry::get($cache_name);
     } else {
         if (isset($scheme[$block_type])) {
             // Get all data for this block type
             $_block_scheme = $scheme[$block_type];
             $_block_scheme['type'] = $block_type;
             // Update templates data
             $_block_scheme['templates'] = self::_prepareTemplates($_block_scheme);
             $_block_scheme['wrappers'] = self::_prepareWrappers($_block_scheme);
             $_block_scheme['content'] = self::prepareContent($_block_scheme, $params);
             $_block_scheme = self::_prepareSettings($_block_scheme);
             Registry::set($cache_name, $_block_scheme);
             return $_block_scheme;
         }
     }
     return array();
 }
Example #21
0
/**
 * Initialize all enabled addons
 *
 * @return array INIT_STATUS_OK
 */
function fn_init_addons()
{
    Registry::registerCache('addons', array('addons', 'settings_objects', 'settings_vendor_values', 'settings_descriptions', 'settings_sections', 'settings_variants'), Registry::cacheLevel('static'));
    if (Registry::isExist('addons') == false) {
        $init_addons = Registry::get('settings.init_addons');
        $allowed_addons = null;
        if ($init_addons == 'none') {
            $allowed_addons = array();
        } elseif ($init_addons == 'core') {
            $allowed_addons = Snapshot::getCoreAddons();
        }
        $_addons = db_get_hash_array("SELECT addon, priority, status, unmanaged FROM ?:addons WHERE 1 ORDER BY priority", 'addon');
        foreach ($_addons as $k => $v) {
            $_addons[$k] = Settings::instance()->getValues($v['addon'], Settings::ADDON_SECTION, false);
            if (fn_check_addon_snapshot($k)) {
                $_addons[$k]['status'] = $v['status'];
            } else {
                $_addons[$k]['status'] = 'D';
            }
            if ($allowed_addons !== null && !in_array($v['addon'], $allowed_addons)) {
                $_addons[$k]['status'] = 'D';
            }
            $_addons[$k]['priority'] = $v['priority'];
            $_addons[$k]['unmanaged'] = $v['unmanaged'];
        }
        // Some addons could be disabled for vendors.
        if (fn_allowed_for('MULTIVENDOR') && Registry::get('runtime.company_id')) {
            Registry::set('addons', $_addons);
            // So, we have to parse it one more time
            foreach ($_addons as $k => $v) {
                // and check permissions schema.
                // We couldn't make it in the previous cycle because the fn_get_scheme func works only with full list of addons.
                if (!fn_check_addon_permission($k)) {
                    unset($_addons[$k]);
                }
            }
        }
        Registry::set('addons', $_addons);
    }
    foreach ((array) Registry::get('addons') as $addon_name => $data) {
        if (empty($data['status'])) {
            // FIX ME: Remove me
            error_log("ERROR: Addons initialization: Bad '{$addon_name}' addon data:" . serialize($data) . " Addons Registry:" . serialize(Registry::get('addons')));
        }
        if (!empty($data['status']) && $data['status'] == 'A') {
            fn_load_addon($addon_name);
        }
    }
    Registry::set('addons_initiated', true, true);
    return array(INIT_STATUS_OK);
}
Example #22
0
/**
 * Get list of templates that should be overridden by addons
 *
 * @param  string $resource_name    Base template name
 * @param  Smarty $view             Templater object
 *
 * @return string Overridden template name
 */
function fn_addon_template_overrides($resource_name, &$view)
{
    static $init = array();
    $o_name = 'template_overrides_' . AREA;
    $template_dir = rtrim($view->getTemplateDir(0), '/') . '/';
    if (!isset($init[$o_name])) {
        Registry::registerCache($o_name, array('addons'), Registry::cacheLevel('static'));
        if (!Registry::isExist($o_name)) {
            $template_overrides = array();
            foreach (Registry::get('addons') as $a => $_settings) {
                $odir = $template_dir . 'addons/' . $a . '/overrides';
                if ($_settings['status'] == 'A' && is_dir($odir)) {
                    $tpls = fn_get_dir_contents($odir, false, true, '', '', true);
                    foreach ($tpls as $k => $t) {
                        $tpl_hash = md5($t);
                        if (empty($template_overrides[$tpl_hash])) {
                            $template_overrides[$tpl_hash] = $template_dir . 'addons/' . $a . '/overrides/' . $t;
                        }
                    }
                }
            }
            if (empty($template_overrides)) {
                $template_overrides['plug'] = true;
            }
            Registry::set($o_name, $template_overrides);
        }
        $init[$o_name] = true;
    }
    return Registry::ifGet($o_name . '.' . md5($resource_name), $resource_name);
}
Example #23
0
/**
 * Filters: gets available filters according to current products set
 *
 * @param array $params request params
 * @param string $lang_code language code
 * @return array available filters list
 */
function fn_get_filters_products_count($params = array(), $lang_code = CART_LANGUAGE)
{
    /**
     * Change parameters for getting product filters count
     *
     * @param array $params Products filter search params
     */
    fn_set_hook('get_filters_products_count_pre', $params);
    $cache_params = array('category_id', 'company_id', 'dispatch', 'search_performed', 'q', 'filter_id', 'item_ids', 'variant_id');
    $key = array();
    foreach ($cache_params as $prop) {
        if (isset($params[$prop])) {
            $key[] = $params[$prop];
        }
    }
    $key = 'pfilters_' . md5(implode('|', $key));
    Registry::registerCache(array('pfilters', $key), array('products', 'product_descriptions', 'product_features', 'product_filters', 'product_features_values', 'products_categories', 'categories', 'product_filter_descriptions', 'product_features_descriptions', 'product_feature_variant_descriptions', 'ult_objects_sharing'), Registry::cacheLevel('user'));
    $selected_filters = array();
    $available_variants = array();
    if (!Registry::isExist($key)) {
        if (!empty($params['check_location'])) {
            // FIXME: this is bad style, should be refactored
            $valid_locations = array('categories.view', 'product_features.view', 'companies.products', 'products.search');
            if (!in_array($params['dispatch'], $valid_locations)) {
                return array();
            }
        }
        $condition = $join = '';
        if (!empty($params['category_id'])) {
            if (Registry::get('settings.General.show_products_from_subcategories') == 'Y') {
                $id_path = db_get_field("SELECT id_path FROM ?:categories WHERE category_id = ?i", $params['category_id']);
                $category_ids = db_get_fields("SELECT category_id FROM ?:categories WHERE id_path LIKE ?l", $id_path . '/%');
            } else {
                $category_ids = array();
            }
            $category_ids[] = $params['category_id'];
            $condition .= db_quote(" AND (?:product_filters.categories_path = '' OR FIND_IN_SET(?i, ?:product_filters.categories_path))", $params['category_id']);
        }
        if (!empty($params['filter_id'])) {
            $condition .= db_quote(" AND ?:product_filters.filter_id = ?i", $params['filter_id']);
        }
        if (!empty($params['item_ids'])) {
            $condition .= db_quote(" AND ?:product_filters.filter_id IN (?a)", explode(',', $params['item_ids']));
        }
        if (!empty($params['variant_id'])) {
            $exclude_feature_id = db_get_field("SELECT feature_id FROM ?:product_features_values WHERE variant_id = ?i", $params['variant_id']);
            $condition .= db_quote(" AND ?:product_filters.feature_id NOT IN (?n)", $exclude_feature_id);
        }
        if (fn_allowed_for('ULTIMATE')) {
            $condition .= fn_get_company_condition('?:product_filters.company_id');
        }
        $sf_fields = db_quote("?:product_filters.feature_id, " . "?:product_filters.filter_id," . "?:product_filters.field_type," . "?:product_filters.round_to," . "?:product_filters.display," . "?:product_filters.display_count," . "?:product_filter_descriptions.filter," . "?:product_features.feature_type," . "?:product_features_descriptions.prefix," . "?:product_features_descriptions.suffix");
        $sf_join = db_quote(" LEFT JOIN ?:product_filter_descriptions ON ?:product_filter_descriptions.filter_id = ?:product_filters.filter_id AND ?:product_filter_descriptions.lang_code = ?s" . " LEFT JOIN ?:product_features ON ?:product_features.feature_id = ?:product_filters.feature_id" . " LEFT JOIN ?:product_features_descriptions ON ?:product_features_descriptions.feature_id = ?:product_filters.feature_id AND ?:product_features_descriptions.lang_code = ?s", $lang_code, $lang_code);
        $sf_sorting = db_quote("?:product_filters.position, ?:product_filter_descriptions.filter");
        /**
         * Change SQL parameters before select product filters
         *
         * @param array $sf_fields String of comma-separated SQL fields to be selected in an SQL-query
         * @param string $sf_join String with the complete JOIN information (JOIN type, tables and fields) for an SQL-query
         * @param string $condition String containing SQL-query condition possibly prepended with a logical operator (AND or OR)
         * @param string $sf_sorting String containing the SQL-query ORDER BY clause
         * @param array $params Products filter search params
         */
        fn_set_hook('get_filters_products_count_before_select_filters', $sf_fields, $sf_join, $condition, $sf_sorting, $params);
        $limit = '';
        if (fn_allowed_for('ULTIMATE:FREE')) {
            $limit = db_quote(' LIMIT ?i', FILTERS_LIMIT);
        }
        $filters = db_get_hash_array("SELECT {$sf_fields} FROM ?:product_filters ?p WHERE ?:product_filters.status = 'A' ?p ORDER BY {$sf_sorting} {$limit}", 'filter_id', $sf_join, $condition);
        if (empty($filters)) {
            return array(array());
        }
        list($variant_values, $range_values, $field_variant_values, $field_range_values) = fn_get_current_filters($params, $filters, array(), AREA, $lang_code);
        Registry::set($key, array($filters, $variant_values, $range_values, $field_variant_values, $field_range_values));
    } else {
        list($filters, $variant_values, $range_values, $field_variant_values, $field_range_values) = Registry::get($key);
    }
    $range_values = fn_filter_process_ranges($range_values, $filters, $selected_filters);
    $field_range_values = fn_filter_process_ranges($field_range_values, $filters, $selected_filters);
    $merged = fn_array_merge($variant_values, $range_values, $field_variant_values, $field_range_values);
    $available_variants = $merged;
    if (!empty($params['features_hash']) && empty($params['skip_advanced_variants'])) {
        $selected_filters = fn_parse_filters_hash($params['features_hash']);
        // Get available variants for current selection
        $_params = $params;
        $_params['split_filters'] = true;
        list($available_variants, $available_ranges, $available_field_values, $available_field_ranges) = fn_get_current_filters($_params, $filters, $selected_filters, AREA, $lang_code);
        list($variant_filter_ids) = fn_split_selected_feature_variants($filters, $selected_filters, false);
        if (sizeof($variant_filter_ids) == 1 && sizeof($selected_filters) == 1) {
            $filter_id = key($variant_filter_ids);
            $available_variants[$filter_id] = $variant_values[$filter_id];
        }
        $available_ranges = fn_filter_process_ranges($available_ranges, $filters, $selected_filters);
        $available_field_ranges = fn_filter_process_ranges($available_field_ranges, $filters, $selected_filters);
        $available_variants = fn_array_merge($available_variants, $available_ranges, $available_field_values, $available_field_ranges);
        $merged = fn_array_merge($merged, $available_variants);
    }
    foreach ($filters as $filter_id => $filter) {
        if (empty($merged[$filter_id]) || !empty($filter['feature_type']) && empty($available_variants[$filter_id])) {
            unset($filters[$filter_id]);
            continue;
        }
        $filters[$filter_id] = fn_array_merge($filters[$filter_id], $merged[$filter_id]);
        // Move selected variants to selected_variants key
        if (!empty($filters[$filter_id]['variants']) && !empty($selected_filters[$filter_id])) {
            foreach ($selected_filters[$filter_id] as $variant_id) {
                if (!empty($filters[$filter_id]['variants'][$variant_id])) {
                    $filters[$filter_id]['selected_variants'][$variant_id] = $filters[$filter_id]['variants'][$variant_id];
                    unset($filters[$filter_id]['variants'][$variant_id]);
                }
            }
        }
        // If we selected any variants in filter, disabled unavailable variants
        if (!empty($available_variants) && !empty($available_variants[$filter_id])) {
            foreach ($filters[$filter_id]['variants'] as $variant_id => $variant_data) {
                if (empty($available_variants[$filter_id]['variants'][$variant_id])) {
                    // disable variant and move it to the end of list
                    unset($filters[$filter_id]['variants'][$variant_id]);
                    $variant_data['disabled'] = true;
                    $filters[$filter_id]['variants'][$variant_id] = $variant_data;
                }
            }
        }
        // If range is selected, mark this filter
        if (!empty($filters[$filter_id]['slider']) && !empty($selected_filters[$filter_id])) {
            if (!empty($filters[$filter_id]['slider']['left']) || !empty($filters[$filter_id]['right'])) {
                $filters[$filter_id]['selected_range'] = true;
            }
        }
    }
    return array($filters);
}