Example #1
0
 /**
  * Connects to the database server
  * @param  string  $user     user name
  * @param  string  $passwd   password
  * @param  string  $host     host name
  * @param  string  $database database name
  * @param  array   $params   connection params
  * @return boolean true on success, false otherwise
  */
 public static function connect($user, $passwd, $host, $database, $params = array())
 {
     if (empty($params['dbc_name'])) {
         $params['dbc_name'] = 'main';
     }
     $params['table_prefix'] = $params['dbc_name'] == 'main' ? Registry::get('config.table_prefix') : $params['table_prefix'];
     if (empty(self::$_dbs[$params['dbc_name']])) {
         $_db_class = Registry::ifGet('config.database_backend', 'mysqli');
         $_db_class = '\\Tygh\\Backend\\Database\\' . ucfirst($_db_class);
         self::$_dbs[$params['dbc_name']] = array('db' => new $_db_class(), 'table_prefix' => $params['table_prefix']);
         $result = self::$_dbs[$params['dbc_name']]['db']->connect($user, $passwd, $host, $database);
         if (!$result) {
             self::$_dbs[$params['dbc_name']] = null;
         }
     } else {
         $result = true;
     }
     if ($result) {
         self::$_db =& self::$_dbs[$params['dbc_name']]['db'];
         self::$_table_prefix = self::$_dbs[$params['dbc_name']]['table_prefix'];
         if (empty($params['names'])) {
             $params['names'] = 'utf8';
         }
         if (empty($params['group_concat_max_len'])) {
             $params['group_concat_max_len'] = 3000;
             // 3Kb
         }
         self::$_db->initCommand(self::quote("SET NAMES ?s, sql_mode = ?s, SESSION group_concat_max_len = ?i", $params['names'], '', $params['group_concat_max_len']));
     }
     return $result;
 }
Example #2
0
function fn_rus_kupivkredit_pre_add_to_cart(&$product_data, &$cart, &$auth, &$update)
{
    if (Registry::ifGet('addons.rus_kupivkredit.status', 'D') == 'A' && Registry::get('runtime.action') == 'kvk_activate') {
        $payment_methods = fn_get_payment_methods($auth);
        foreach ($payment_methods as $p => $data) {
            if (!empty($data['processor']) && stristr($data['processor'], 'Kupivkredit')) {
                $cart['payment_id'] = $data['payment_id'];
            }
        }
    }
}
Example #3
0
 /**
  * @inheritDoc
  */
 public function register(Container $app)
 {
     // Session component
     $app['session'] = function ($app) {
         $session = new \Tygh\Web\Session($app);
         // Configure conditions of session start
         if (defined('NO_SESSION') && NO_SESSION) {
             $session->start_on_init = false;
             $session->start_on_read = false;
             $session->start_on_write = false;
             return $session;
         }
         // Configure session component
         $session->setSessionNamePrefix('sid_');
         $session->setSessionNameSuffix('_' . substr(md5(Registry::get('config.http_location')), 0, 5));
         $session->setName(ACCOUNT_TYPE);
         $session->setSessionIDSuffix('-' . AREA);
         $session->cache_limiter = 'nocache';
         $session->cookie_lifetime = SESSIONS_STORAGE_ALIVE_TIME;
         $session->cookie_path = Registry::ifGet('config.current_path', '/');
         $host = defined('HTTPS') ? 'https://' . Registry::get('config.https_host') : 'http://' . Registry::get('config.http_host');
         $host = parse_url($host, PHP_URL_HOST);
         if (strpos($host, '.') !== false) {
             // Check if host has www, www2, www4 prefix and remove it
             $host = preg_replace('/^www[0-9]*\\./i', '', $host);
             $host = strpos($host, '.') === 0 ? $host : '.' . $host;
         } else {
             // For local hosts set this to empty value
             $host = '';
         }
         if (!preg_match("/\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}/", $host, $matches)) {
             $cookie_domain = $host;
         } else {
             $cookie_domain = ini_get('session.cookie_domain');
         }
         $session->cookie_domain = $cookie_domain;
         $session->start_on_init = true;
         $session->start_on_read = true;
         $session->start_on_write = true;
         return $session;
     };
     // Session data storage driver class
     $app['session.storage.class'] = function ($app) {
         $storage_class = Registry::ifGet('config.session_backend', 'database');
         $storage_class = '\\Tygh\\Backend\\Session\\' . ucfirst($storage_class);
         return $storage_class;
     };
     // Session data storage driver instance
     $app['session.storage'] = function ($app) {
         return new $app['session.storage.class'](Registry::get('config'), array('ttl' => SESSION_ONLINE, 'ttl_storage' => SESSIONS_STORAGE_ALIVE_TIME, 'ttl_online' => SESSION_ONLINE));
     };
 }
Example #4
0
 /**
  * Prepare products list for get shippings
  *
  * @param  array $products Products list with products data
  * @param  array $location User location
  * @return array Product groups
  */
 public static function groupProductsList($products, $location)
 {
     $groups = array();
     foreach ($products as $key_product => $product) {
         if (fn_allowed_for('ULTIMATE')) {
             $company_id = Registry::ifGet('runtime.company_id', fn_get_default_company_id());
         } else {
             $company_id = $product['company_id'];
         }
         if (empty($groups[$company_id])) {
             $origination = self::_getOriginationData($company_id);
             $groups[$company_id] = array('name' => $origination['name'], 'company_id' => (int) $company_id, 'origination' => $origination, 'location' => $location);
         }
         $groups[$company_id]['products'][$key_product] = $product;
     }
     fn_set_hook('shippings_group_products_list', $products, $groups);
     foreach ($groups as $key_group => $group) {
         $groups[$key_group]['package_info'] = self::_getPackageInfo($group);
         $groups[$key_group]['package_info_full'] = self::_getPackageInfo($group, true);
         unset($groups[$key_group]['origination']);
         unset($groups[$key_group]['location']);
         $all_edp_free_shipping = true;
         $all_free_shipping = true;
         $free_shipping = true;
         $shipping_no_required = true;
         foreach ($group['products'] as $product) {
             if ($product['is_edp'] != 'Y' || $product['edp_shipping'] == 'Y') {
                 $all_edp_free_shipping = false;
                 // shipping is required when having non-EDP products with shipping
                 if (empty($product['shipping_no_required']) || $product['shipping_no_required'] != 'Y') {
                     $shipping_no_required = false;
                 }
                 if (empty($product['free_shipping']) || $product['free_shipping'] != 'Y') {
                     $free_shipping = false;
                 }
             }
             if (empty($product['free_shipping']) || $product['free_shipping'] != 'Y') {
                 $all_free_shipping = false;
             }
         }
         $groups[$key_group]['all_edp_free_shipping'] = $all_edp_free_shipping;
         $groups[$key_group]['all_free_shipping'] = $all_free_shipping;
         $groups[$key_group]['free_shipping'] = $free_shipping;
         $groups[$key_group]['shipping_no_required'] = $shipping_no_required;
     }
     return array_values($groups);
 }
Example #5
0
 /**
  * @inheritDoc
  */
 public function register(Container $app)
 {
     // Database component
     $app['db'] = function ($app) {
         $database = new Connection($app['db.driver']);
         $connected = $database->connect(Registry::get('config.db_user'), Registry::get('config.db_password'), Registry::get('config.db_host'), Registry::get('config.db_name'), array('table_prefix' => Registry::get('config.table_prefix')));
         if ($connected) {
             Registry::set('runtime.database.skip_errors', false);
         } else {
             throw new DatabaseException('Cannot connect to the database server');
         }
         return $database;
     };
     // Database driver instance
     $app['db.driver'] = function ($app) {
         return new $app['db.driver.class']();
     };
     $app['db.driver.class'] = function ($app) {
         $driver_class = Registry::ifGet('config.database_backend', 'mysqli');
         $driver_class = '\\Tygh\\Backend\\Database\\' . ucfirst($driver_class);
         return $driver_class;
     };
 }
Example #6
0
function fn_get_sb_providers_meta_data($params)
{
    $addon_settings = Settings::instance()->getValues('social_buttons', 'ADDON');
    $providers_meta_data = array();
    if (fn_allowed_for('ULTIMATE')) {
        $company_id = Registry::ifGet('runtime.company_id', fn_get_default_company_id());
        $site_name = fn_get_company_name($company_id);
    }
    if ($params['object'] == 'products') {
        $product = Tygh::$app['view']->getTemplateVars('product');
        $providers_meta_data['all'] = array('title' => fn_sb_format_page_title(), 'url' => fn_url('products.view?product_id=' . $params['object_id']), 'image' => !empty($product['main_pair']['detailed']['http_image_path']) ? $product['main_pair']['detailed']['http_image_path'] : '', 'image:width' => !empty($product['main_pair']['detailed']['image_x']) ? $product['main_pair']['detailed']['image_x'] : '', 'image:height' => !empty($product['main_pair']['detailed']['image_y']) ? $product['main_pair']['detailed']['image_y'] : '', 'site_name' => !empty($site_name) ? $site_name : Registry::get('settings.Company.company_name'));
    } elseif ($params['object'] == 'pages') {
        $page = Tygh::$app['view']->getTemplateVars('page');
        $logos = fn_get_logos();
        if (fn_allowed_for('ULTIMATE')) {
            $logos = fn_get_logos($company_id);
        }
        $providers_meta_data['all'] = array('title' => $page['page'], 'url' => !empty($page['link']) ? $page['link'] : fn_url('pages.view?product_id=' . $params['object_id']), 'image' => !empty($logos['theme']['image']['http_image_path']) ? $logos['theme']['image']['http_image_path'] : '', 'image:width' => !empty($logos['theme']['image']['image_x']) ? $logos['theme']['image']['image_x'] : '', 'image:height' => !empty($logos['theme']['image']['image_y']) ? $logos['theme']['image']['image_y'] : '', 'site_name' => !empty($site_name) ? $site_name : Registry::get('settings.Company.company_name'));
    }
    if (!empty($addon_settings)) {
        foreach ($addon_settings as $provider_name => $provider_data) {
            $func_name = 'fn_' . $provider_name . '_prepare_meta_data';
            if (is_callable($func_name)) {
                $providers_meta_data[$provider_name] = call_user_func($func_name, $provider_data, $params);
            }
        }
    }
    return $providers_meta_data;
}
Example #7
0
function fn_log_event($type, $action, $data = array())
{
    $object_primary_keys = array('users' => 'user_id', 'orders' => 'order_id', 'products' => 'product_id', 'categories' => 'category_id');
    $update = false;
    $content = array();
    $actions = Registry::get('settings.Logging.log_type_' . $type);
    $cut_log = Registry::ifGet('log_cut', false);
    Registry::del('log_cut');
    $cut_data = Registry::ifGet('log_cut_data', false);
    Registry::del('log_cut_data');
    if (empty($actions) || $action && !empty($actions) && empty($actions[$action]) || !empty($cut_log)) {
        return false;
    }
    if (!empty($_SESSION['auth']['user_id'])) {
        $user_id = $_SESSION['auth']['user_id'];
    } else {
        $user_id = 0;
    }
    if ($type == 'users' && $action == 'logout' && !empty($data['user_id'])) {
        $user_id = $data['user_id'];
    }
    if ($user_id) {
        $udata = db_get_row("SELECT firstname, lastname, email FROM ?:users WHERE user_id = ?i", $user_id);
    }
    $event_type = 'N';
    // notice
    if (!empty($data['backtrace'])) {
        $_btrace = array();
        $func = '';
        foreach (array_reverse($data['backtrace']) as $v) {
            if (!empty($v['file'])) {
                $v['file'] = fn_get_rel_dir($v['file']);
            }
            if (empty($v['file'])) {
                $func = $v['function'];
                continue;
            } elseif (!empty($func)) {
                $v['function'] = $func;
                $func = '';
            }
            $_btrace[] = array('file' => !empty($v['file']) ? $v['file'] : '', 'line' => !empty($v['line']) ? $v['line'] : '', 'function' => $v['function']);
        }
        $data['backtrace'] = serialize($_btrace);
    } else {
        $data['backtrace'] = '';
    }
    if ($type == 'general') {
        if ($action == 'deprecated') {
            $content['deprecated_function'] = $data['function'];
        }
        $content['message'] = $data['message'];
    } elseif ($type == 'orders') {
        $order_status_descr = fn_get_simple_statuses(STATUSES_ORDER, true, true);
        $content = array('order' => '# ' . $data['order_id'], 'id' => $data['order_id']);
        if ($action == 'status') {
            $content['status'] = $order_status_descr[$data['status_from']] . ' -> ' . $order_status_descr[$data['status_to']];
        }
    } elseif ($type == 'products') {
        $product = db_get_field("SELECT product FROM ?:product_descriptions WHERE product_id = ?i AND lang_code = ?s", $data['product_id'], Registry::get('settings.Appearance.backend_default_language'));
        $content = array('product' => $product . ' (#' . $data['product_id'] . ')', 'id' => $data['product_id']);
        if ($action == 'low_stock') {
            // log stock - warning
            $event_type = 'W';
        }
    } elseif ($type == 'categories') {
        $category = db_get_field("SELECT category FROM ?:category_descriptions WHERE category_id = ?i AND lang_code = ?s", $data['category_id'], Registry::get('settings.Appearance.backend_default_language'));
        $content = array('category' => $category . ' (#' . $data['category_id'] . ')', 'id' => $data['category_id']);
    } elseif ($type == 'database') {
        if ($action == 'error') {
            $content = array('error' => $data['error']['message'], 'query' => $data['error']['query']);
            $event_type = 'E';
        }
    } elseif ($type == 'requests') {
        if (!empty($cut_data)) {
            $data['data'] = preg_replace("/\\<(" . implode('|', $cut_data) . ")\\>(.*?)\\<\\/(" . implode('|', $cut_data) . ")\\>/s", '<${1}>******</${1}>', $data['data']);
            $data['data'] = preg_replace("/%3C(" . implode('|', $cut_data) . ")%3E(.*?)%3C%2F(" . implode('|', $cut_data) . ")%3E/s", '%3C${1}%3E******%3C%2F${1}%3E', $data['data']);
            $data['data'] = preg_replace("/(" . implode('|', $cut_data) . ")=(.*?)(&)/s", '${1}=******${3}', $data['data']);
        }
        $content = array('url' => $data['url'], 'request' => fn_strlen($data['data']) < LOG_MAX_DATA_LENGTH && preg_match('//u', $data['data']) ? $data['data'] : '', 'response' => fn_strlen($data['response']) < LOG_MAX_DATA_LENGTH && preg_match('//u', $data['response']) ? $data['response'] : '');
    } elseif ($type == 'users') {
        if (!empty($data['time'])) {
            if (empty($_SESSION['log']['login_log_id'])) {
                return false;
            }
            $content = db_get_field('SELECT content FROM ?:logs WHERE log_id = ?i', $_SESSION['log']['login_log_id']);
            $content = unserialize($content);
            $minutes = ceil($data['time'] / 60);
            $hours = floor($minutes / 60);
            if ($hours) {
                $minutes -= $hours * 60;
            }
            if ($hours || $minutes) {
                $content['loggedin_time'] = ($hours ? $hours . ' |hours| ' : '') . ($minutes ? $minutes . ' |minutes|' : '');
            }
            if (!empty($data['timeout']) && $data['timeout']) {
                $content['timeout'] = true;
            }
            $update = $_SESSION['log']['login_log_id'];
        } else {
            if (!empty($data['user_id'])) {
                $info = db_get_row("SELECT firstname, lastname, email FROM ?:users WHERE user_id = ?i", $data['user_id']);
                $content = array('user' => $info['firstname'] . ($info['firstname'] && $info['lastname'] ? ' ' : '') . $info['lastname'] . ($info['firstname'] || $info['lastname'] ? '; ' : '') . $info['email'] . ' (#' . $data['user_id'] . ')');
                $content['id'] = $data['user_id'];
            } elseif (!empty($data['user'])) {
                $content = array('user' => $data['user']);
            }
            if (in_array($action, array('session', 'failed_login'))) {
                $ip = fn_get_ip();
                $content['ip_address'] = empty($data['ip']) ? $ip['host'] : $data['ip'];
            }
        }
        if ($action == 'failed_login') {
            // failed login - warning
            $event_type = 'W';
        }
    }
    fn_set_hook('save_log', $type, $action, $data, $user_id, $content, $event_type, $object_primary_keys);
    $content = serialize($content);
    if ($update) {
        db_query('UPDATE ?:logs SET content = ?s WHERE log_id = ?i', $content, $update);
    } else {
        if (Registry::get('runtime.company_id')) {
            $company_id = Registry::get('runtime.company_id');
        } elseif (!empty($object_primary_keys[$type]) && !empty($data[$object_primary_keys[$type]])) {
            $company_id = fn_get_company_id($type, $object_primary_keys[$type], $data[$object_primary_keys[$type]]);
        } else {
            $company_id = 0;
        }
        $row = array('user_id' => $user_id, 'timestamp' => TIME, 'type' => $type, 'action' => $action, 'event_type' => $event_type, 'content' => $content, 'backtrace' => $data['backtrace'], 'company_id' => $company_id);
        $log_id = db_query("INSERT INTO ?:logs ?e", $row);
        if ($type == 'users' && $action == 'session') {
            $_SESSION['log']['login_log_id'] = $log_id;
        }
    }
    return true;
}
Example #8
0
/**
 * Resizes image
 * @param string $src source image path
 * @param integer $new_width new image width
 * @param integer $new_height new image height
 * @param string $bg_color new image background color
 * @param array $custom_settings custom convertion settings
 * @return array - new image contents and format
 */
function fn_resize_image($src, $new_width = 0, $new_height = 0, $bg_color = '#ffffff', $custom_settings = array())
{
    static $notification_set = false;
    static $gd_settings = array();
    if (empty($gd_settings)) {
        $gd_settings = Settings::instance()->getValues('Thumbnails');
    }
    $settings = !empty($custom_settings) ? $custom_settings : $gd_settings;
    $class = '\\Tygh\\Backend\\Images\\' . ucfirst(Registry::ifGet('config.tweaks.image_resize_lib', 'gd'));
    if (file_exists($src) && (!empty($new_width) || !empty($new_height))) {
        $img_functions = $class::supportedFormats();
        list($width, $height, $mime_type) = fn_get_image_size($src);
        $ext = fn_get_image_extension($mime_type);
        if (empty($width) || empty($height) || empty($ext)) {
            return false;
        }
        if (empty($img_functions[$ext])) {
            if ($notification_set == false) {
                fn_set_notification('E', __('error'), __('error_image_format_not_supported', array('[format]' => $ext)));
                $notification_set = true;
            }
            return false;
        }
        if (empty($new_width) || empty($new_height)) {
            if ($width < $new_width) {
                $new_width = $width;
            }
            if ($height < $new_height) {
                $new_height = $height;
            }
        }
        $dst_width = $new_width;
        $dst_height = $new_height;
        $x = 0;
        $y = 0;
        if (empty($new_height)) {
            // if we passed width only, calculate height
            $dst_height = $new_height = $height / $width * $new_width;
        } elseif (empty($new_width)) {
            // if we passed height only, calculate width
            $dst_width = $new_width = $width / $height * $new_height;
        } else {
            // we passed width and height, we need to fit image in this sizes
            if ($new_width * $height / $width > $dst_height) {
                $new_width = $width * $dst_height / $height;
            }
            $new_height = $height / $width * $new_width;
            if ($new_height * $width / $height > $dst_width) {
                $new_height = $height * $dst_width / $width;
            }
            $new_width = $width / $height * $new_height;
            $x = intval(($dst_width - $new_width) / 2);
            $y = intval(($dst_height - $new_height) / 2);
        }
        $new_width = intval($new_width);
        $new_height = intval($new_height);
        if (!empty($bg_color) && !preg_match('/^#([0-9a-f]{3}){1,2}$/i', $bg_color)) {
            $bg_color = '#ffffff';
        }
        try {
            return $class::resize($src, array('ext' => $ext, 'new_width' => $new_width, 'new_height' => $new_height, 'dst_width' => $dst_width, 'dst_height' => $dst_height, 'width' => $width, 'height' => $height, 'bg_color' => $bg_color, 'convert_to' => $settings['convert_to'], 'jpeg_quality' => $settings['jpeg_quality'], 'x' => $x, 'y' => $y));
        } catch (Exception $e) {
            return array('', $ext);
        }
    }
    return false;
}
Example #9
0
/**
 * Add/update user
 *
 * @param int $user_id - user ID to update (empty for new user)
 * @param array $user_data - user data
 * @param array $auth - authentication information
 * @param bool $ship_to_another - flag indicates that shipping and billing fields are different
 * @param bool $notify_user - flag indicates that user should be notified
 * @return array with user ID and profile ID if success, false otherwise
 */
function fn_update_user($user_id, $user_data, &$auth, $ship_to_another, $notify_user)
{
    /**
     * Actions before updating user
     *
     * @param int   $user_id         User ID to update (empty for new user)
     * @param array $user_data       User data
     * @param array $auth            Authentication information
     * @param bool  $ship_to_another Flag indicates that shipping and billing fields are different
     * @param bool  $notify_user     Flag indicates that user should be notified
     */
    fn_set_hook('update_user_pre', $user_id, $user_data, $auth, $ship_to_another, $notify_user);
    array_walk($user_data, 'fn_trim_helper');
    $register_at_checkout = isset($user_data['register_at_checkout']) && $user_data['register_at_checkout'] == 'Y' ? true : false;
    if (fn_allowed_for('ULTIMATE')) {
        if (AREA == 'A' && !empty($user_data['user_type']) && $user_data['user_type'] == 'C' && (empty($user_data['company_id']) || Registry::get('runtime.company_id') && $user_data['company_id'] != Registry::get('runtime.company_id'))) {
            fn_set_notification('W', __('warning'), __('access_denied'));
            return false;
        }
    }
    if (!empty($user_id)) {
        $current_user_data = db_get_row("SELECT user_id, company_id, is_root, status, user_type, user_login, lang_code, password, salt, last_passwords FROM ?:users WHERE user_id = ?i", $user_id);
        if (empty($current_user_data)) {
            fn_set_notification('E', __('error'), __('object_not_found', array('[object]' => __('user'))), '', '404');
            return false;
        }
        if (!fn_check_editable_permissions($auth, $current_user_data)) {
            fn_set_notification('E', __('error'), __('access_denied'));
            return false;
        }
        if (!empty($user_data['profile_id']) && AREA != 'A') {
            $profile_ids = db_get_fields("SELECT profile_id FROM ?:user_profiles WHERE user_id = ?i", $user_id);
            if (!in_array($user_data['profile_id'], $profile_ids)) {
                fn_set_notification('W', __('warning'), __('access_denied'));
                return false;
            }
        }
        if (fn_allowed_for('ULTIMATE')) {
            if (AREA != 'A' || empty($user_data['company_id'])) {
                //we should set company_id for the frontdend, in the backend company_id received from form
                if ($current_user_data['user_type'] == 'A') {
                    if (!isset($user_data['company_id']) || AREA != 'A' || Registry::get('runtime.company_id')) {
                        // reset administrator's company if it was not set to root
                        $user_data['company_id'] = $current_user_data['company_id'];
                    }
                } elseif (Registry::get('settings.Stores.share_users') == 'Y') {
                    $user_data['company_id'] = $current_user_data['company_id'];
                } else {
                    $user_data['company_id'] = Registry::ifGet('runtime.company_id', 1);
                }
            }
        }
        if (fn_allowed_for('MULTIVENDOR')) {
            if (AREA != 'A') {
                //we should set company_id for the frontend
                $user_data['company_id'] = $current_user_data['company_id'];
            }
        }
        $action = 'update';
    } else {
        $current_user_data = array('status' => AREA != 'A' && Registry::get('settings.General.approve_user_profiles') == 'Y' ? 'D' : (!empty($user_data['status']) ? $user_data['status'] : 'A'), 'user_type' => 'C');
        if (fn_allowed_for('ULTIMATE')) {
            if (!empty($user_data['company_id']) || Registry::get('runtime.company_id') || AREA == 'A') {
                //company_id can be received when we create user account from the backend
                $company_id = !empty($user_data['company_id']) ? $user_data['company_id'] : Registry::get('runtime.company_id');
                if (empty($company_id)) {
                    $company_id = fn_check_user_type_admin_area($user_data['user_type']) ? $user_data['company_id'] : fn_get_default_company_id();
                }
                $user_data['company_id'] = $current_user_data['company_id'] = $company_id;
            } else {
                fn_set_notification('W', __('warning'), __('access_denied'));
                return false;
            }
        }
        $action = 'add';
        $user_data['lang_code'] = !empty($user_data['lang_code']) ? $user_data['lang_code'] : CART_LANGUAGE;
        $user_data['timestamp'] = TIME;
    }
    $original_password = '';
    $current_user_data['password'] = !empty($current_user_data['password']) ? $current_user_data['password'] : '';
    $current_user_data['salt'] = !empty($current_user_data['salt']) ? $current_user_data['salt'] : '';
    // Set the user type
    $user_data['user_type'] = fn_check_user_type($user_data, $current_user_data);
    if (Registry::get('runtime.company_id') && !fn_allowed_for('ULTIMATE') && (!fn_check_user_type_admin_area($user_data['user_type']) || isset($current_user_data['company_id']) && $current_user_data['company_id'] != Registry::get('runtime.company_id'))) {
        fn_set_notification('W', __('warning'), __('access_denied'));
        return false;
    }
    // Check if this user needs login/password
    if (fn_user_need_login($user_data['user_type'])) {
        // Check if user_login already exists
        // FIXME
        if (!isset($user_data['email'])) {
            $user_data['email'] = db_get_field("SELECT email FROM ?:users WHERE user_id = ?i", $user_id);
        }
        $is_exist = fn_is_user_exists($user_id, $user_data);
        if ($is_exist) {
            fn_set_notification('E', __('error'), __('error_user_exists'), '', 'user_exist');
            return false;
        }
        // Check the passwords
        if (!empty($user_data['password1']) || !empty($user_data['password2'])) {
            $original_password = trim($user_data['password1']);
            $user_data['password1'] = !empty($user_data['password1']) ? trim($user_data['password1']) : '';
            $user_data['password2'] = !empty($user_data['password2']) ? trim($user_data['password2']) : '';
        }
        // if the passwords are not set and this is not a forced password check
        // we will not update password, otherwise let's check password
        if (!empty($_SESSION['auth']['forced_password_change']) || !empty($user_data['password1']) || !empty($user_data['password2'])) {
            $valid_passwords = true;
            if ($user_data['password1'] != $user_data['password2']) {
                $valid_passwords = false;
                fn_set_notification('E', __('error'), __('error_passwords_dont_match'));
            }
            // PCI DSS Compliance
            if (fn_check_user_type_admin_area($user_data['user_type'])) {
                $msg = array();
                // Check password length
                $min_length = Registry::get('settings.Security.min_admin_password_length');
                if (strlen($user_data['password1']) < $min_length || strlen($user_data['password2']) < $min_length) {
                    $valid_passwords = false;
                    $msg[] = str_replace("[number]", $min_length, __('error_password_min_symbols'));
                }
                // Check password content
                if (Registry::get('settings.Security.admin_passwords_must_contain_mix') == 'Y') {
                    $tmp_result = preg_match('/\\d+/', $user_data['password1']) && preg_match('/\\D+/', $user_data['password1']) && preg_match('/\\d+/', $user_data['password2']) && preg_match('/\\D+/', $user_data['password2']);
                    if (!$tmp_result) {
                        $valid_passwords = false;
                        $msg[] = __('error_password_content');
                    }
                }
                if ($msg) {
                    fn_set_notification('E', __('error'), implode('<br />', $msg));
                }
                // Check last 4 passwords
                if (!empty($user_id)) {
                    $prev_passwords = !empty($current_user_data['last_passwords']) ? explode(',', $current_user_data['last_passwords']) : array();
                    if (!empty($_SESSION['auth']['forced_password_change'])) {
                        // if forced password change - new password can't be equal to current password.
                        $prev_passwords[] = $current_user_data['password'];
                    }
                    if (in_array(fn_generate_salted_password($user_data['password1'], $current_user_data['salt']), $prev_passwords)) {
                        $valid_passwords = false;
                        fn_set_notification('E', __('error'), __('error_password_was_used'));
                    } else {
                        if (count($prev_passwords) >= 5) {
                            array_shift($prev_passwords);
                        }
                        $user_data['last_passwords'] = implode(',', $prev_passwords);
                    }
                }
            }
            // PCI DSS Compliance
            if (!$valid_passwords) {
                return false;
            }
            $user_data['salt'] = fn_generate_salt();
            $user_data['password'] = fn_generate_salted_password($user_data['password1'], $user_data['salt']);
            if ($user_data['password'] != $current_user_data['password'] && !empty($user_id)) {
                // if user set current password - there is no necessity to update password_change_timestamp
                $user_data['password_change_timestamp'] = $_SESSION['auth']['password_change_timestamp'] = TIME;
            }
            unset($_SESSION['auth']['forced_password_change']);
            fn_delete_notification('password_expire');
        }
    }
    $user_data['status'] = AREA != 'A' || empty($user_data['status']) ? $current_user_data['status'] : $user_data['status'];
    // only administrator can change user status
    // Fill the firstname, lastname and phone from the billing address if the profile was created or updated through the admin area.
    if (AREA == 'A' || Registry::get('settings.Checkout.address_position') == 'billing_first') {
        $main_address_zone = BILLING_ADDRESS_PREFIX;
        $alt_address_zone = SHIPPING_ADDRESS_PREFIX;
    } else {
        $main_address_zone = SHIPPING_ADDRESS_PREFIX;
        $alt_address_zone = BILLING_ADDRESS_PREFIX;
    }
    $user_data = fn_fill_contact_info_from_address($user_data, $main_address_zone, $alt_address_zone);
    if (!fn_allowed_for('ULTIMATE')) {
        //for ult company_id was set before
        fn_set_company_id($user_data);
    }
    if (!empty($current_user_data['is_root']) && $current_user_data['is_root'] == 'Y') {
        $user_data['is_root'] = 'Y';
    } else {
        $user_data['is_root'] = 'N';
    }
    // check if it is a root admin
    $is_root_admin_exists = db_get_field("SELECT user_id FROM ?:users WHERE company_id = ?i AND is_root = 'Y' AND user_id != ?i", $user_data['company_id'], !empty($user_id) ? $user_id : 0);
    $user_data['is_root'] = empty($is_root_admin_exists) && $user_data['user_type'] !== 'C' ? 'Y' : 'N';
    unset($user_data['user_id']);
    if (!empty($user_id)) {
        db_query("UPDATE ?:users SET ?u WHERE user_id = ?i", $user_data, $user_id);
        fn_clean_usergroup_links($user_id, $current_user_data['user_type'], $user_data['user_type']);
        fn_log_event('users', 'update', array('user_id' => $user_id));
    } else {
        if (!isset($user_data['password_change_timestamp'])) {
            $user_data['password_change_timestamp'] = 1;
        }
        $user_id = db_query("INSERT INTO ?:users ?e", $user_data);
        fn_log_event('users', 'create', array('user_id' => $user_id));
    }
    $user_data['user_id'] = $user_id;
    // Set/delete insecure password notification
    if (AREA == 'A' && Registry::get('config.demo_mode') != true && !empty($user_data['password1'])) {
        if (!fn_compare_login_password($user_data, $user_data['password1'])) {
            fn_delete_notification('insecure_password');
        } else {
            $lang_var = 'warning_insecure_password_email';
            fn_set_notification('E', __('warning'), __($lang_var, array('[link]' => fn_url("profiles.update?user_id=" . $user_id))), 'K', 'insecure_password');
        }
    }
    if (empty($user_data['user_login'])) {
        // if we're using email as login or user type does not require login, fill login field
        db_query("UPDATE ?:users SET user_login = '******' WHERE user_id = ?i AND user_login = ''", $user_id, $user_id);
    }
    // Fill shipping info with billing if needed
    if (empty($ship_to_another)) {
        $profile_fields = fn_get_profile_fields($user_data['user_type']);
        $use_default = AREA == 'A' ? true : false;
        fn_fill_address($user_data, $profile_fields, $use_default);
    }
    $user_data['profile_id'] = fn_update_user_profile($user_id, $user_data, $action);
    $user_data = fn_get_user_info($user_id, true, $user_data['profile_id']);
    if ($register_at_checkout) {
        $user_data['register_at_checkout'] = 'Y';
    }
    $lang_code = AREA == 'A' && !empty($user_data['lang_code']) ? $user_data['lang_code'] : CART_LANGUAGE;
    if (!fn_allowed_for('ULTIMATE:FREE')) {
        $user_data['usergroups'] = db_get_hash_array("SELECT lnk.link_id, lnk.usergroup_id, lnk.status, a.type, b.usergroup" . " FROM ?:usergroup_links as lnk" . " INNER JOIN ?:usergroups as a ON a.usergroup_id = lnk.usergroup_id AND a.status != 'D'" . " LEFT JOIN ?:usergroup_descriptions as b ON b.usergroup_id = a.usergroup_id AND b.lang_code = ?s" . " WHERE a.status = 'A' AND lnk.user_id = ?i AND lnk.status != 'D' AND lnk.status != 'F'", 'usergroup_id', $lang_code, $user_id);
    }
    // Send notifications to customer
    if (!empty($notify_user)) {
        $from = 'company_users_department';
        if (fn_allowed_for('MULTIVENDOR')) {
            // Vendor administrator's notification
            // is sent from root users department
            if ($user_data['user_type'] == 'V') {
                $from = 'default_company_users_department';
            }
        }
        // Notify customer about profile activation (when update profile only)
        if ($action == 'update' && $current_user_data['status'] === 'D' && $user_data['status'] === 'A') {
            Mailer::sendMail(array('to' => $user_data['email'], 'from' => $from, 'data' => array('user_data' => $user_data), 'tpl' => 'profiles/profile_activated.tpl', 'company_id' => $user_data['company_id']), fn_check_user_type_admin_area($user_data['user_type']) ? 'A' : 'C', $lang_code);
        }
        // Notify customer about profile add/update
        $prefix = $action == 'add' ? 'create' : 'update';
        // Send password to user only if it was created by admin or vendor
        if (AREA != 'C' && $auth['user_id'] != $user_id) {
            $password = $original_password;
        } else {
            $password = null;
        }
        Mailer::sendMail(array('to' => $user_data['email'], 'from' => $from, 'data' => array('password' => $password, 'user_data' => $user_data), 'tpl' => 'profiles/' . $prefix . '_profile.tpl', 'company_id' => $user_data['company_id']), fn_check_user_type_admin_area($user_data['user_type']) ? 'A' : 'C', $lang_code);
    }
    if ($action == 'add') {
        if (AREA != 'A') {
            if (Registry::get('settings.General.approve_user_profiles') == 'Y') {
                fn_set_notification('W', __('important'), __('text_profile_should_be_approved'));
                // Notify administrator about new profile
                Mailer::sendMail(array('to' => 'company_users_department', 'from' => 'company_users_department', 'reply_to' => $user_data['email'], 'data' => array('user_data' => $user_data), 'tpl' => 'profiles/activate_profile.tpl', 'company_id' => $user_data['company_id']), 'A', Registry::get('settings.Appearance.backend_default_language'));
            } else {
                fn_set_notification('N', __('information'), __('text_profile_is_created'));
            }
        }
        if (!is_null($auth)) {
            if (!empty($auth['order_ids'])) {
                db_query("UPDATE ?:orders SET user_id = ?i WHERE order_id IN (?n)", $user_id, $auth['order_ids']);
            }
        }
    } else {
        if (AREA == 'C') {
            fn_set_notification('N', __('information'), __('text_profile_is_updated'));
        }
    }
    fn_set_hook('update_profile', $action, $user_data, $current_user_data);
    return array($user_id, !empty($user_data['profile_id']) ? $user_data['profile_id'] : false);
}
Example #10
0
 /**
  * Returns true if cache used for blocks
  *
  * @static
  * @return bool true if we may use cahce, false otherwise
  */
 public static function allowCache()
 {
     $use_cache = true;
     if (Registry::ifGet('config.tweaks.disable_block_cache', false) || Registry::get('runtime.customizaton_mode.design') || Registry::get('runtime.customizaton_mode.translation') || Development::isEnabled('compile_check')) {
         $use_cache = false;
     }
     return $use_cache;
 }
Example #11
0
/**
 * Function checks should the given menu element be marked as active or not
 *
 * @param array $object_data Menu item
 * @param string $object_type Type of menu item (category or page data)
 * @return bool
 */
function fn_check_is_active_menu_item($object_data, $object_type)
{
    $id = null;
    if ($object_type == 'categories') {
        $active_ids = Registry::ifGet('runtime.active_category_ids', array());
        $id = $object_data['category_id'];
    } elseif ($object_type == 'pages') {
        $active_ids = Registry::ifGet('runtime.active_page_ids', array());
        $id = $object_data['page_id'];
    } else {
        return false;
    }
    return in_array($id, $active_ids);
}
Example #12
0
function fn_get_payment_templates($payment = array())
{
    $templates = array();
    $company_id = null;
    if (fn_allowed_for('ULTIMATE')) {
        if (!empty($payment['company_id'])) {
            $company_id = $payment['company_id'];
        } else {
            $company_id = Registry::ifGet('runtime.company_id', fn_get_default_company_id());
        }
    }
    $theme_path = fn_get_theme_path('[themes]/[theme]', 'C', $company_id);
    $_templates = fn_get_dir_contents($theme_path . '/templates/views/orders/components/payments/', false, true, '.tpl');
    foreach ($_templates as $template) {
        $templates[$template] = 'views/orders/components/payments/' . $template;
    }
    // Get addons templates as well
    $path = 'addons/[addon]/views/orders/components/payments/';
    $addons = Registry::get('addons');
    foreach ($addons as $addon_id => $addon) {
        $addon_path = str_replace('[addon]', $addon_id, $path);
        $addon_templates = fn_get_dir_contents($theme_path . '/templates/' . $addon_path, false, true, '.tpl');
        if (!empty($addon_templates)) {
            foreach ($addon_templates as $template) {
                $templates[$template] = $addon_path . $template;
            }
        }
    }
    return $templates;
}
Example #13
0
 if (empty($items_schema['func'])) {
     $c_elm = '';
 } else {
     $c_elm = $items_schema['func'];
     foreach ($c_elm as $k => $v) {
         if (strpos($v, '@') !== false) {
             $ind = str_replace('@', '', $v);
             if (!empty($auth[$ind]) || !empty($_REQUEST[$ind])) {
                 $c_elm[$k] = $ind == 'user_id' && empty($_REQUEST[$ind]) ? $auth[$ind] : $_REQUEST[$ind];
             }
         }
     }
 }
 $url = Registry::get('config.current_url');
 if (fn_allowed_for('ULTIMATE') && !Registry::get('runtime.simple_ultimate')) {
     $url = fn_link_attach($url, 'switch_company_id=' . Registry::ifGet('runtime.company_id', 'all'));
     $url = str_replace('&amp;', '&', $url);
     // FIXME: workaround for fn_link_attach return result
 }
 $last_item = array('func' => $c_elm, 'url' => $url, 'icon' => empty($items_schema['icon']) ? '' : $items_schema['icon'], 'text' => empty($items_schema['text']) ? '' : $items_schema['text']);
 $current_hash = fn_crc32(!empty($c_elm) ? implode('', $c_elm) : $items_schema['text']);
 // remove element if it already exists and add it to the end of history
 unset($last_edited_items[$current_hash]);
 $last_edited_items[$current_hash] = $last_item;
 if (count($last_edited_items) > $last_items_cnt) {
     foreach ($last_edited_items as $k => $v) {
         unset($last_edited_items[$k]);
         if (count($last_edited_items) == $last_items_cnt) {
             break;
         }
     }
Example #14
0
function fn_searchanise_get_products_before_select(&$params, &$join, &$condition, &$u_condition, &$inventory_condition, &$sortings, &$total, &$items_per_page, &$lang_code, &$having)
{
    // disable by core
    if (AREA == 'A' || fn_se_check_disabled() || !empty($params['having']) || !empty($params['disable_searchanise']) || empty($params['search_performed']) || !empty($params['block_data']) || empty($params['q']) && fn_se_get_simple_setting('use_navigation') !== 'Y' || fn_se_get_import_status(fn_se_get_company_id(), $lang_code) != 'done' || !empty($params['pid']) || !empty($params['b_id']) || !empty($params['item_ids']) || !empty($params['feature']) || !empty($params['downloadable']) || !empty($params['tracking']) || !empty($params['shipping_freight_from']) || !empty($params['shipping_freight_to']) || !empty($params['exclude_pid']) || !empty($params['get_query']) || !empty($params['only_short_fields']) || isset($params['supplier_id']) || isset($params['amount_to']) || isset($params['amount_from']) || isset($params['q']) && Registry::get('settings.General.search_objects') || isset($params['compact']) && $params['compact'] == 'Y' || !empty($_REQUEST['sort_by']) && !in_array($_REQUEST['sort_by'], fn_se_get_valid_sortings()) || !empty($params['force_get_by_ids']) && empty($params['pid']) && empty($params['product_id'])) {
        return;
    }
    // disable by addons
    if (!empty($params['rating']) || !empty($params['bestsellers']) || !empty($params['also_bought_for_product_id']) || !empty($params['for_required_product']) || !empty($params['ppcode']) && $params['ppcode'] == 'Y' || isset($params['tag']) && fn_string_not_empty($params['tag']) || Registry::ifGet('addons.age_verification.status', 'D') == 'A' || Registry::ifGet('addons.vendor_data_premoderation.status', 'D') == 'A' || !empty($params['picker_for']) && $params['picker_for'] == 'gift_certificates') {
        return;
    }
    list($restrict_by, $query_by, $union) = fn_se_prepare_request_params($params);
    //
    // Categories
    //
    if (!empty($params['cid'])) {
        $cids = is_array($params['cid']) ? $params['cid'] : array($params['cid']);
        $c_condition = '';
        if (AREA == 'C') {
            $_c_statuses = array('A', 'H');
            // Show enabled categories
            $cids = db_get_fields("SELECT a.category_id FROM ?:categories as a WHERE a.category_id IN (?n) AND a.status IN (?a)", $cids, $_c_statuses);
            $c_condition = db_quote('AND a.status IN (?a) AND (' . fn_find_array_in_set(Tygh::$app['session']['auth']['usergroup_ids'], 'a.usergroup_ids', true) . ')', $_c_statuses);
        }
        $sub_categories_ids = db_get_fields("SELECT a.category_id FROM ?:categories as a LEFT JOIN ?:categories as b ON b.category_id IN (?n) WHERE a.id_path LIKE CONCAT(b.id_path, '/%') ?p", $cids, $c_condition);
        $sub_categories_ids = fn_array_merge($cids, $sub_categories_ids, false);
        if (empty($sub_categories_ids)) {
            $params['force_get_by_ids'] = true;
            $params['pid'] = $params['product_id'] = 0;
            return;
        }
        if (!empty($params['subcats']) && $params['subcats'] == 'Y') {
            $restrict_by['category_id'] = join('|', $sub_categories_ids);
        } else {
            $restrict_by['category_id'] = join('|', $cids);
        }
    }
    //
    // Sortings
    //
    if (!empty($_REQUEST['search_performed']) && empty($_REQUEST['sort_by']) && SE_USE_RELEVANCE_AS_DEFAULT_SORTING == 'Y') {
        $params['sort_by'] = 'relevance';
        $params['sort_order'] = 'asc';
    }
    if (!empty($params['sort_by']) && !in_array($params['sort_by'], fn_se_get_valid_sortings())) {
        return;
    }
    if ($params['sort_by'] == 'product') {
        $sort_by = 'title';
    } elseif ($params['sort_by'] == 'relevance') {
        $params['sort_order'] = 'asc';
        $sort_by = 'relevance';
    } else {
        $sort_by = $params['sort_by'];
    }
    $sort_order = $params['sort_order'] == 'asc' ? 'asc' : 'desc';
    //
    // Items_per_page
    //
    $items_per_page = empty($params['items_per_page']) ? 10 : (int) $params['items_per_page'];
    if (!empty($params['limit'])) {
        $max_results = $params['limit'];
    } else {
        $max_results = $items_per_page;
    }
    $get_items = true;
    $get_facets = false;
    if (!fn_allowed_for('ULTIMATE:FREE') && AREA == 'C' && !empty($params['dispatch']) && in_array($params['dispatch'], fn_se_get_facet_valid_locations()) && fn_se_check_product_filter_block() == true) {
        $get_facets = true;
    }
    $request_params = array('sortBy' => $sort_by, 'sortOrder' => $sort_order, 'union' => $union, 'queryBy' => $query_by, 'restrictBy' => $restrict_by, 'items' => $get_items == true ? 'true' : 'false', 'facets' => $get_facets == true ? 'true' : 'false', 'maxResults' => $max_results, 'startIndex' => ($params['page'] - 1) * $items_per_page);
    if ($request_params['sortBy'] == 'null') {
        unset($request_params['sortBy']);
    }
    if (!empty($params['q']) && fn_strlen($params['q']) > 0) {
        $request_params['q'] = $params['q'];
        $request_params['suggestions'] = 'true';
        $request_params['query_correction'] = 'false';
        $request_params['suggestionsMaxResults'] = 1;
    } else {
        $request_params['q'] = '';
    }
    $result = fn_searchanise_send_search_request($request_params, $lang_code);
    if ($result == false) {
        //revert to standart sorting
        if ($params['sort_by'] == 'relevance') {
            $params['sort_by'] = '';
        }
        Registry::set('runtime.se_use_relevance_sorting', false);
        return;
    }
    if (!empty($result['suggestions']) && count($result['suggestions']) > 0) {
        $params['suggestion'] = reset($result['suggestions']);
    }
    if (!empty($result['items'])) {
        foreach ($result['items'] as $product) {
            $params['pid'][] = $product['product_id'];
        }
        if ($params['sort_by'] == 'relevance') {
            $sortings['relevance'] = "FIELD(products.product_id, '" . join("','", $params['pid']) . "')";
            $params['sort_order'] = 'asc';
        }
    } else {
        $products = array();
        $params['force_get_by_ids'] = true;
        $params['pid'] = $params['product_id'] = 0;
    }
    if (isset($result['facets'])) {
        Registry::set('searchanise.received_facets', $result['facets']);
    }
    $total = $result['totalItems'];
    $params['limit'] = $items_per_page;
    // need to set it manually for proper pagination
    // reset condition with text search && filtering params  - we are get all control under process of  text search and filtering
    $condition = '';
    $join = '';
    return;
}
Example #15
0
function fn_mailru_put_header($filename)
{
    $_SESSION['mailru_export_count'] = 0;
    $shop_name = Registry::get('addons.rus_tovary_mailru.shop_name');
    if (empty($shop_name)) {
        if (fn_allowed_for('ULTIMATE')) {
            $company_id = Registry::ifGet('runtime.company_id', fn_get_default_company_id());
            $shop_name = fn_get_company_name($company_id);
        } else {
            $shop_name = Registry::get('settings.Company.company_name');
        }
    }
    $shop_name = strip_tags($shop_name);
    $yml_header = array('<?xml version="1.0" encoding="' . Registry::get('addons.rus_tovary_mailru.export_encoding') . '"?>', '<torg_price date="' . date('Y-m-d G:i') . '">', '<shop>');
    $yml = array('shopname' => $shop_name, 'company' => Registry::get('settings.Company.company_name'), 'url' => Registry::get('config.http_location'));
    $currencies = Registry::get('currencies');
    if (CART_PRIMARY_CURRENCY != "RUB") {
        $rub_coefficient = !empty($currencies['RUB']) ? $currencies['RUB']['coefficient'] : 1;
        $primary_coefficient = $currencies[CART_PRIMARY_CURRENCY]['coefficient'];
        foreach ($currencies as $cur) {
            if (fn_mailru_check_currencies($cur['currency_code']) && $cur['status'] == 'A') {
                if ($cur['currency_code'] == "RUB") {
                    $coefficient = '1.0000';
                    $yml['currencies']['currency@id=' . $cur['currency_code'] . '@rate=' . $coefficient] = '';
                } else {
                    $coefficient = $cur['coefficient'] * $primary_coefficient / $rub_coefficient;
                    $yml['currencies']['currency@id=' . $cur['currency_code'] . '@rate=' . $coefficient] = '';
                }
            }
        }
    } else {
        foreach ($currencies as $cur) {
            if (fn_mailru_check_currencies($cur['currency_code']) && $cur['status'] == 'A') {
                $yml['currencies']['currency@id=' . $cur['currency_code'] . '@rate=' . $cur['coefficient']] = '';
            }
        }
    }
    $params = array('simple' => false, 'plain' => true);
    if (fn_allowed_for('ULTIMATE') && is_numeric($shop_name)) {
        $params['company_ids'] = $shop_name;
    }
    list($categories_tree, ) = fn_get_categories($params);
    foreach ($categories_tree as $cat) {
        if (isset($cat['category_id'])) {
            $yml['categories']['category@id=' . $cat['category_id'] . '@parentId=' . $cat['parent_id']] = htmlspecialchars($cat['category']);
        }
    }
    $yml_data = implode("\n", $yml_header) . "\n" . fn_mailru_array_to_yml($yml) . "<offers>\n";
    fn_mailru_write_yml($filename, 'w+', $yml_data);
}
Example #16
0
/**
 * Gets runtime company_id in any mode
 * 
 * @return int Company id | 0
 */
function fn_get_runtime_company_id()
{
    $company_id = Registry::ifGet('runtime.company_id', 0);
    if (!$company_id && Registry::get('runtime.simple_ultimate')) {
        $company_id = Registry::get('runtime.forced_company_id');
    }
    return $company_id;
}
Example #17
0
function fn_magiczoom_parse(&$contents, &$products, $block)
{
    $tool = fn_magiczoom_load();
    $tool->params->setProfile($block);
    //NOTE: Non-ASCII filenames are chunked if no locale is provided
    //$oldLocale = setlocale(LC_ALL, NULL);
    //setlocale(LC_ALL, 'en_US.UTF8');
    switch ($block) {
        case 'product':
            $productThumbImageType = $tool->params->getValue('quick-view') ? 'quick-view-thumb' : 'thumb';
            $isMainPairExists = true;
            if (isset($products[0]['main_pair']['detailed']['image_path'])) {
                $imagePath = $products[0]['main_pair']['detailed']['image_path'];
                $imageAlt = $products[0]['main_pair']['detailed']['alt'];
            } else {
                if (isset($products[0]['main_pair']['icon']['image_path'])) {
                    $imagePath = $products[0]['main_pair']['icon']['image_path'];
                    $imageAlt = $products[0]['main_pair']['icon']['alt'];
                } else {
                    if (!empty($products[0]['image_pairs'])) {
                        $isMainPairExists = false;
                        $mainImagePair = reset($products[0]['image_pairs']);
                        if (isset($mainImagePair['detailed']['image_path'])) {
                            $imagePath = $mainImagePair['detailed']['image_path'];
                            $imageAlt = $mainImagePair['detailed']['alt'];
                        } else {
                            $imagePath = $mainImagePair['icon']['image_path'];
                            $imageAlt = $mainImagePair['icon']['alt'];
                        }
                    } else {
                        break;
                    }
                }
            }
            $img = fn_magiczoom_create_thumb($imagePath, 'original', $products[0]['product_id']);
            if (!$img) {
                break;
            }
            //NOTE: possibly image does not exists
            $useMagic360 = false;
            if (function_exists('fn_magic360_load') && Registry::ifGet('addons.magic360.status', 'D') == 'A') {
                $magic360tool = fn_magic360_load();
                if ($magic360tool->params->checkValue('enable-effect', 'Yes', 'product')) {
                    $rezult = db_get_row('SELECT gallery FROM ?:addon_magic360_images WHERE id = ?i', $products[0]['product_id']);
                    if (isset($rezult['gallery']) && !empty($rezult['gallery'])) {
                        $magic360Images = explode(';', $rezult['gallery']);
                        if (count($magic360Images)) {
                            $useMagic360 = true;
                            //NOTE: disable transition effect to prevent the disappearance of the image when it is toggled
                            $tool->params->setValue('transitionEffect', 'No', 'product');
                        }
                    }
                }
            }
            $thumb = fn_magiczoom_create_thumb($imagePath, $productThumbImageType, $products[0]['product_id']);
            $title = !empty($imageAlt) ? $imageAlt : $products[0]['product'];
            $mainImageHTML = $tool->getMainTemplate(array('id' => $block . $products[0]['product_id'], 'group' => $block . $tool->params->getValue('block-id'), 'img' => $img, 'thumb' => $thumb, 'title' => $title)) . "<style type=\"text/css\">.MagicZoom { max-width: " . $tool->params->getValue('thumb-max-width') . "px; }</style>";
            $jcarousel = Registry::get('settings.Appearance.thumbnails_gallery') == 'Y';
            //NOTE: this important for JCarousel
            if ($jcarousel && $tool->params->checkValue('template', 'original')) {
                $width = $tool->params->checkValue('selector-max-width', array('0', '')) ? 'auto' : $tool->params->getValue('selector-max-width');
                $height = $tool->params->checkValue('selector-max-height', array('0', '')) ? 'auto' : $tool->params->getValue('selector-max-height');
            } else {
                $width = '';
                $height = '';
            }
            $mainImageSelectorHTML = $tool->getSelectorTemplate(array('id' => $block . $products[0]['product_id'], 'group' => $block . $tool->params->getValue('block-id'), 'img' => $img, 'medium' => $thumb, 'thumb' => fn_magiczoom_create_thumb($imagePath, 'selector', $products[0]['product_id']), 'title' => $title, 'width' => $width, 'height' => $height));
            $additionalImages = array();
            if (!empty($products[0]['image_pairs'])) {
                if ($isMainPairExists) {
                    $additionalImages[] = str_replace('<a ', '<a class="cm-gallery-item cm-thumbnails-mini thumbnails-item" ', $mainImageSelectorHTML);
                }
                foreach ($products[0]['image_pairs'] as $imagePair) {
                    if (isset($imagePair['detailed']['image_path'])) {
                        $imagePairPath = $imagePair['detailed']['image_path'];
                        $imageAlt = $imagePair['detailed']['alt'];
                        //if(!file_exists($imagePair['detailed']['absolute_path'])) {
                        //NOTICE: there is no guarantee that this picture exists
                        //NOTICE: there is no guarantee that this is a picture of this product (it may be a different picture, if the name is the same)
                        //$imageData = fn_image_to_display($imagePair, Registry::get('settings.Thumbnails.product_details_thumbnail_width'), Registry::get('settings.Thumbnails.product_details_thumbnail_height'));
                        //$imagePairPath = $imageData['image_path'];
                        //}
                    } else {
                        $imagePairPath = $imagePair['icon']['image_path'];
                        $imageAlt = $imagePair['icon']['alt'];
                    }
                    $img = fn_magiczoom_create_thumb($imagePairPath, 'original', $products[0]['product_id']);
                    if (!$img) {
                        continue;
                    }
                    //NOTE: possibly image does not exists
                    $a = $tool->getSelectorTemplate(array('id' => $block . $products[0]['product_id'], 'group' => $block . $tool->params->getValue('block-id'), 'img' => $img, 'medium' => fn_magiczoom_create_thumb($imagePairPath, $productThumbImageType, $products[0]['product_id']), 'thumb' => fn_magiczoom_create_thumb($imagePairPath, 'selector', $products[0]['product_id']), 'title' => !empty($imageAlt) ? $imageAlt : $products[0]['product'], 'width' => $width, 'height' => $height));
                    $additionalImages[] = str_replace('<a ', '<a class="cm-gallery-item cm-thumbnails-mini thumbnails-item" ', $a);
                }
            }
            if ($useMagic360) {
                $GLOBALS['magictoolbox']['cooperative_mode'] = 'magiczoom';
                $magic360tool->params->setValue('selector-max-width', $tool->params->getValue('selector-max-width'));
                $magic360tool->params->setValue('selector-max-height', $tool->params->getValue('selector-max-height'));
                $mainImageHTML = '<div style="position: relative;">' . '<div id="mainImageContainer' . $products[0]['product_id'] . '" style="position: absolute; left: -10000px;">' . '<div>' . $mainImageHTML . '</div>' . '</div>' . '<div id="magic360Container' . $products[0]['product_id'] . '"><!-- MAGIC360 --></div>' . '</div>';
                if (empty($additionalImages)) {
                    $additionalImages[] = str_replace('<a ', '<a class="cm-gallery-item cm-thumbnails-mini thumbnails-item" ', $mainImageSelectorHTML);
                }
                array_unshift($additionalImages, '<!-- MAGIC360SELECTOR -->');
            }
            require_once dirname(__FILE__) . MT_DS . 'classes' . MT_DS . 'magictoolbox.templatehelper.class.php';
            MagicToolboxTemplateHelperClass::setPath(dirname(__FILE__) . MT_DS . 'templates');
            MagicToolboxTemplateHelperClass::setOptions($tool->params);
            $html = MagicToolboxTemplateHelperClass::render(array('main' => $mainImageHTML, 'thumbs' => $additionalImages, 'pid' => $products[0]['product_id'], 'jcarousel' => $jcarousel, 'ul' => version_compare(PRODUCT_VERSION, '4.1', '<')));
            //NOTE: set width for a large number of selectors
            if ($tool->params->checkValue('magicscroll', 'No') && $tool->params->checkValue('template', array('top', 'bottom', 'original'))) {
                $html = preg_replace('#(<div\\b[^>]*?\\bclass="[^"]*?MagicToolboxContainer[^"]*+)("[^>]*+>)#i', '$1 maxWidth$2', $html);
            }
            $html .= '
<script type="text/javascript">
    magicToolboxProductId = ' . $products[0]['product_id'] . ';
</script>';
            $additionalThumbnailsPattern = '(<div\\b[^>]*?\\bclass="[^"]*?\\bcm-image-gallery-wrapper\\b[^"]*+"[^>]*+>[^<]*+)?' . '<(div|ul)\\b[^>]*?\\bclass="[^"]*?\\bproduct-thumbnails\\b[^"]*+"[^>]*+>' . '(' . '(?:' . '[^<]++' . '|' . '<(?!/?\\2\\b|!--)' . '|' . '<!--.*?-->' . '|' . '<\\2\\b[^>]*+>' . '(?3)' . '</\\2\\s*+>' . ')*+' . ')' . '</\\2\\s*+>' . '(?(1)[^<]*+</div\\s*+>)';
            $matches = array();
            preg_match('#' . $additionalThumbnailsPattern . '#is', $contents, $matches);
            /*
            $imagePattern =
                '<a [^>]*?id="det_img_link_[^"]*"[^>]*>[^<]*'.//class=cm-image-previewer, det_img_link_{$preview_id}_
                '(?:<img [^>]*?id="det_img_(?!variant_image)[^"]*"[^>]*>[^<]*'.//class=pict, det_img_{$preview_id}_
                '(?:<span [^>]*?class="view-larger-image"[^>]*>[^<]*</span>[^<]*)?'.
                '|<div [^>]*?class="no-image"[^>]*>.*?</div>[^<]*)'.
                '</a>[^<]*';
            */
            $imagePattern = '(?:' . '<img [^>]*?id="det_img_' . $products[0]['product_id'] . '[0-9][^"]*+"[^>]*+>' . '|' . '<div [^>]*?class="no-image"[^>]*+>.*?</div>' . '|' . '<span [^>]*?class="ty-no-image"[^>]*+>.*?</span>' . ')';
            $imagePattern = '(?:<a [^>]*?id="det_img_link_[^"]*+"[^>]*+>[^<]*+' . $imagePattern . '[^<]*+' . '(?:<span\\b[^>]*+>[^<]*+</span>[^<]*+)?' . '</a>|' . $imagePattern . ')[^<]*+';
            $replaced = 0;
            $contents = preg_replace('#(?:' . $imagePattern . ')+#is', str_replace('$', '\\$', $html), $contents, 1, $replaced);
            //NOTE: $limit = 1 to prevent the replacement of product in product tabs(product id == block id)
            if ($replaced && !empty($matches)) {
                //NOTE: cut selectors
                $contents = str_replace($matches[0], '', $contents);
            }
            break;
        case 'category':
        case 'search':
        case 'newest':
        case 'recent_products':
        case 'most_popular':
        case 'bestsellers':
        case 'rating':
        case 'on_sale':
        case 'manually':
            $useLink = $tool->params->checkValue('link-to-product-page', 'Yes');
            $showGallery = $tool->params->getValue('show-gallery');
            foreach ($products as $product) {
                $imagePairs = $product['image_pairs'];
                if (isset($product['main_pair']['detailed']['image_path'])) {
                    $imagePath = $product['main_pair']['detailed']['image_path'];
                    $imageAlt = $product['main_pair']['detailed']['alt'];
                    if (isset($product['main_pair']['icon']['image_path'])) {
                        $srcPattern = $product['main_pair']['icon']['image_path'];
                    } else {
                        $srcPattern = $imagePath;
                    }
                } else {
                    if (isset($product['main_pair']['icon']['image_path'])) {
                        $imagePath = $product['main_pair']['icon']['image_path'];
                        $imageAlt = $product['main_pair']['icon']['alt'];
                        $srcPattern = $imagePath;
                    } else {
                        if ($showGallery && !empty($imagePairs)) {
                            $imagePair = array_shift($imagePairs);
                            if (isset($imagePair['detailed']['image_path'])) {
                                $imagePath = $imagePair['detailed']['image_path'];
                                $imageAlt = $imagePair['detailed']['alt'];
                                if (isset($imagePair['icon']['image_path'])) {
                                    $srcPattern = $imagePair['icon']['image_path'];
                                } else {
                                    $srcPattern = $imagePath;
                                }
                            } else {
                                $imagePath = $imagePair['icon']['image_path'];
                                $imageAlt = $imagePair['icon']['alt'];
                                $srcPattern = $imagePath;
                            }
                        } else {
                            continue;
                        }
                    }
                }
                //NOTE: cut off timestamp from URL
                $srcPattern = preg_replace('#\\?t=\\d+$#i', '', $srcPattern);
                //NOTE: prepare regexp
                $srcPattern = '[^"]*?/' . preg_quote(basename($srcPattern)) . '(?:\\?t=\\d++)?';
                $img = fn_magiczoom_create_thumb($imagePath, 'original', $product['product_id']);
                if (!$img) {
                    continue;
                }
                //NOTE: possibly image does not exists
                if ($showGallery && !empty($product['image_pairs'])) {
                    //product_icon.tpl (with gallery)
                    /*
                    $galleryPattern =
                        '<div [^>]*?id="icons_[^"]*?'.$product['product_id'].'"[^>]*+>[^<]*+'.//cm-image-gallery `$block.block_id`000`$product.product_id`
                        '(?:'.
                        //new 4.1.x pattern
                        '(?:<div [^>]*?class="[^"]*?cm-gallery-item[^"]*+"[^>]*+>[^<]*+'.
                        '<a [^>]*+>[^<]*+'.
                        '<img [^>]*?id="det_img_[^"]*?'.$product['product_id'].'(?:_[^"]*+)?"[^>]*+>[^<]*+'.
                        '</a>[^<]*+'.
                        '</div>[^<]*+)+'.
                        '|'.
                        //old 4.0.x pattern
                        '<ul[^>]*+>[^<]*+'.
                        '(?:<li [^>]*?class="[^"]*?cm-gallery-item[^"]*+"[^>]*+>[^<]*+'.
                        '<a [^>]*+>[^<]*+'.
                        '<img [^>]*?id="det_img_[^"]*?'.$product['product_id'].'(?:_[^"]*+)?"[^>]*+>[^<]*+'.
                        '</a>[^<]*+'.
                        '</li>[^<]*+)+'.
                        '</ul>[^<]*+'.
                        '(?:<i [^>]*+></i>[^<]*+){2}?'.
                        ')'.
                        '</div>';
                    */
                    $galleryPattern = '<div\\b[^>]*?\\bid\\s*+=\\s*+"icons_[^"]*?' . $product['product_id'] . '"[^>]*+>' . '(' . '(?:' . '[^<]++' . '|' . '<(?!/?div\\b|!--)' . '|' . '<!--.*?-->' . '|' . '<div\\b[^>]*+>' . '(?1)' . '</div\\s*+>' . ')*+' . ')' . '</div\\s*+>';
                    $matches = array();
                    if (preg_match('#' . $galleryPattern . '#is', $contents, $matches)) {
                        $galleryHTML = $matches[0];
                        //product_icon.tpl
                        $galleryItemPattern = '<a\\b[^>]*+>[^<]*+' . '<img\\b[^>]*+>[^<]*+' . '</a>';
                        $index = 0;
                        $html = $tool->getMainTemplate(array('id' => $block . $product['product_id'] . "_{$index}", 'group' => $block . $tool->params->getValue('block-id') . "_{$product['product_id']}", 'img' => $img, 'thumb' => fn_magiczoom_create_thumb($imagePath, 'thumb', $product['product_id']), 'title' => $product['product'], 'link' => $useLink ? fn_url("products.view?product_id={$product['product_id']}") : ''));
                        $galleryHTML = preg_replace('#' . $galleryItemPattern . '#is', str_replace('$', '\\$', $html), $galleryHTML, 1);
                        foreach ($imagePairs as $imagePair) {
                            $index++;
                            if (isset($imagePair['detailed']['image_path'])) {
                                $imagePath = $imagePair['detailed']['image_path'];
                                $imageAlt = $imagePair['detailed']['alt'];
                            } else {
                                $imagePath = $imagePair['icon']['image_path'];
                                $imageAlt = $imagePair['icon']['alt'];
                            }
                            $img = fn_magiczoom_create_thumb($imagePath, 'original', $product['product_id']);
                            if (!$img) {
                                continue;
                            }
                            //NOTE: possibly image does not exists
                            $html = $tool->getMainTemplate(array('id' => $block . $product['product_id'] . "_{$index}", 'group' => $block . $tool->params->getValue('block-id') . "_{$product['product_id']}", 'img' => $img, 'thumb' => fn_magiczoom_create_thumb($imagePath, 'thumb', $product['product_id']), 'title' => $product['product'], 'link' => $useLink ? fn_url("products.view?product_id={$product['product_id']}") : ''));
                            $galleryHTML = preg_replace('#' . $galleryItemPattern . '#is', str_replace('$', '\\$', $html), $galleryHTML, 1);
                        }
                        $contents = str_replace($matches[0], $galleryHTML, $contents);
                    }
                } else {
                    $html = $tool->getMainTemplate(array('id' => $block . $product['product_id'], 'group' => $block . $tool->params->getValue('block-id'), 'img' => $img, 'thumb' => fn_magiczoom_create_thumb($imagePath, 'thumb', $product['product_id']), 'title' => $product['product'], 'link' => $useLink ? fn_url("products.view?product_id={$product['product_id']}") : ''));
                    //products_list.tpl
                    $productListPattern = '(?P<discount><span [^>]*?class="[^"]*?thumb-discount-label[^"]*+"[^>]*+>.*?</span>[^<]*+)?' . '(?P<input1><input [^>]*+>[^<]*+)' . '<img [^>]*?id="det_img_[^"]*?' . $product['product_id'] . '"[^>]*+>';
                    $productListPattern = '(<a [^>]*+>[^<]*+(?P<input2><input [^>]*+>)[^<]*+)?' . $productListPattern . '(?(1)[^<]*+</a>)';
                    //product_icon.tpl (without gallery)
                    $productIconPattern = '<a [^>]*+>[^<]*+' . '(?:<img [^>]*?id="det_img_[^"]*?' . $product['product_id'] . '"[^>]*+>|' . '<img [^>]*?src="' . $srcPattern . '"[^>]*+>)' . '[^<]*+</a>';
                    /*
                    //product_icon.tpl (with gallery)
                    $productIconPattern =
                        '<div [^>]*?id="icons_'.$product['product_id'].'"[^>]*>[^<]*'.//cm-image-gallery
                        '<ul>[^<]*'.
                        '(?:<li [^>]*?class="[^"]*?cm-gallery-item[^"]*"[^>]*>[^<]*'.
                        '<a [^>]*>[^<]*'.
                        '<img [^>]*?id="det_img_[^"]*?'.$product['product_id'].'(?:_[^"]*)?"[^>]*>[^<]*'.
                        '</a>[^<]*'.
                        '</li>[^<]*)+'.
                        '</ul>[^<]*'.
                        '(?:<i [^>]*></i>[^<]*){2}?'.
                        '</div>|'.$productIconPattern;
                    */
                    $matches = array();
                    $matchedData = '';
                    //inputs, span
                    if (preg_match('#' . $productListPattern . '|' . $productIconPattern . '#is', $contents, $matches)) {
                        $matchedData = (empty($matches['discount']) ? '' : $matches['discount']) . (empty($matches['input1']) ? '' : $matches['input1']) . (empty($matches['input2']) ? '' : $matches['input2']);
                        $contents = str_replace($matches[0], $matchedData . $html, $contents);
                    }
                }
            }
            if ($tool->params->getValue('products-scroller')) {
                $contents = str_replace('wrap: \'circular\'', 'wrap: \'both\'', $contents);
            }
            break;
    }
    //setlocale(LC_ALL, $oldLocale);
    $tool->params->resetProfile();
    return $contents;
}
Example #18
0
/**
 * Updates product option
 *
 * @param array $option_data option data array
 * @param int $option_id option ID (empty if we're adding the option)
 * @param string $lang_code language code to add/update option for
 * @return int ID of the added/updated option
 */
function fn_update_product_option($option_data, $option_id = 0, $lang_code = DESCR_SL)
{
    /**
     * Changes parameters before update option data
     *
     * @param array  $option_data Option data
     * @param int    $option_id   Option identifier
     * @param string $lang_code   Two-letter language code (e.g. 'en', 'ru', etc.)
     */
    fn_set_hook('update_product_option_pre', $option_data, $option_id, $lang_code);
    // Add option
    if (empty($option_id)) {
        if (empty($option_data['product_id'])) {
            $option_data['product_id'] = 0;
        }
        $option_data['option_id'] = $option_id = db_query('INSERT INTO ?:product_options ?e', $option_data);
        foreach (fn_get_translation_languages() as $option_data['lang_code'] => $_v) {
            db_query("INSERT INTO ?:product_options_descriptions ?e", $option_data);
        }
        $create = true;
        // Update option
    } else {
        // if option inventory changed from Y to N, we should clear option combinations
        if (!empty($option_data['product_id']) && !empty($option_data['inventory']) && $option_data['inventory'] == 'N') {
            $condition = fn_get_company_condition('?:product_options.company_id');
            $old_option_inventory = db_get_field("SELECT inventory FROM ?:product_options WHERE option_id = ?i {$condition}", $option_id);
            if ($old_option_inventory == 'Y') {
                $inventory_filled = db_get_field('SELECT COUNT(*) FROM ?:product_options_inventory WHERE product_id = ?i', $option_data['product_id']);
                if ($inventory_filled) {
                    fn_delete_product_option_combinations($option_data['product_id']);
                }
            }
        }
        if (fn_allowed_for('ULTIMATE') && !empty($option_data['product_id']) && fn_ult_is_shared_product($option_data['product_id']) == 'Y') {
            $product_company_id = db_get_field('SELECT company_id FROM ?:products WHERE product_id = ?i', $option_data['product_id']);
            $option_id = fn_ult_update_shared_product_option($option_data, $option_id, Registry::ifGet('runtime.company_id', $product_company_id), $lang_code);
            if (Registry::get('runtime.company_id') && Registry::get('runtime.company_id') != $product_company_id) {
                $deleted_variants = array();
                fn_set_hook('update_product_option_post', $option_data, $option_id, $deleted_variants, $lang_code);
                return $option_id;
            }
        }
        db_query("UPDATE ?:product_options SET ?u WHERE option_id = ?i", $option_data, $option_id);
        db_query("UPDATE ?:product_options_descriptions SET ?u WHERE option_id = ?i AND lang_code = ?s", $option_data, $option_id, $lang_code);
    }
    if (fn_allowed_for('ULTIMATE')) {
        // options of shared product under the shared store hasn't a company_id. No necessary for updating.
        if (!empty($option_data['company_id'])) {
            fn_ult_update_share_object($option_id, 'product_options', $option_data['company_id']);
        }
        if (!empty($option_data['product_id'])) {
            fn_ult_share_product_option($option_id, $option_data['product_id']);
        }
    }
    if (!empty($option_data['variants'])) {
        $var_ids = array();
        // Generate special variants structure for checkbox (2 variants, 1 hidden)
        if ($option_data['option_type'] == 'C') {
            $option_data['variants'] = array_slice($option_data['variants'], 0, 1);
            // only 1 variant should be here
            reset($option_data['variants']);
            $_k = key($option_data['variants']);
            $option_data['variants'][$_k]['position'] = 1;
            // checked variant
            $v_id = db_get_field("SELECT variant_id FROM ?:product_option_variants WHERE option_id = ?i AND position = 0", $option_id);
            $option_data['variants'][] = array('position' => 0, 'variant_id' => $v_id);
        }
        $variant_images = array();
        foreach ($option_data['variants'] as $k => $v) {
            if ((!isset($v['variant_name']) || $v['variant_name'] == '') && $option_data['option_type'] != 'C') {
                continue;
            }
            // Update product options variants
            if (isset($v['modifier'])) {
                $v['modifier'] = floatval($v['modifier']);
                if (floatval($v['modifier']) > 0) {
                    $v['modifier'] = '+' . $v['modifier'];
                }
            }
            if (isset($v['weight_modifier'])) {
                $v['weight_modifier'] = floatval($v['weight_modifier']);
                if (floatval($v['weight_modifier']) > 0) {
                    $v['weight_modifier'] = '+' . $v['weight_modifier'];
                }
            }
            //            if (isset($v['set_by_user'])) {
            //
            //            }
            $v['option_id'] = $option_id;
            if (empty($v['variant_id']) || !empty($v['variant_id']) && !db_get_field("SELECT variant_id FROM ?:product_option_variants WHERE variant_id = ?i", $v['variant_id'])) {
                $v['variant_id'] = db_query("INSERT INTO ?:product_option_variants ?e", $v);
                foreach (fn_get_translation_languages() as $v['lang_code'] => $_v) {
                    db_query("INSERT INTO ?:product_option_variants_descriptions ?e", $v);
                }
            } else {
                db_query("DELETE FROM ?:product_option_variants_disabled WHERE product_id=?i AND option_id =?i AND variant_id=?i", $option_data['extraProductId'], $option_id, $v['variant_id']);
                if ($v['status'] == 'Y') {
                    $vd = array('product_id' => $option_data['extraProductId'], 'option_id' => $option_id, 'variant_id' => $v['variant_id']);
                    db_query("INSERT INTO ?:product_option_variants_disabled ?e", $vd);
                    unset($v['status']);
                }
                db_query("UPDATE ?:product_option_variants SET ?u WHERE variant_id = ?i", $v, $v['variant_id']);
                db_query("UPDATE ?:product_option_variants_descriptions SET ?u WHERE variant_id = ?i AND lang_code = ?s", $v, $v['variant_id'], $lang_code);
            }
            $var_ids[] = $v['variant_id'];
            if ($option_data['option_type'] == 'C') {
                fn_delete_image_pairs($v['variant_id'], 'variant_image');
                // force deletion of variant image for "checkbox" option
            } else {
                $variant_images[$k] = $v['variant_id'];
            }
        }
        if ($option_data['option_type'] != 'C' && !empty($variant_images)) {
            fn_attach_image_pairs('variant_image', 'variant_image', 0, $lang_code, $variant_images);
        }
        // Delete obsolete variants
        $condition = !empty($var_ids) ? db_quote('AND variant_id NOT IN (?n)', $var_ids) : '';
        $deleted_variants = db_get_fields("SELECT variant_id FROM ?:product_option_variants WHERE option_id = ?i {$condition}", $option_id, $var_ids);
        if (!empty($deleted_variants)) {
            db_query("DELETE FROM ?:product_option_variants WHERE variant_id IN (?n)", $deleted_variants);
            db_query("DELETE FROM ?:product_option_variants_descriptions WHERE variant_id IN (?n)", $deleted_variants);
            foreach ($deleted_variants as $v_id) {
                fn_delete_image_pairs($v_id, 'variant_image');
            }
        }
    }
    if (!fn_allowed_for('ULTIMATE:FREE')) {
        // Rebuild exceptions
        if (!empty($create) && !empty($option_data['product_id'])) {
            fn_update_exceptions($option_data['product_id']);
        }
    }
    /**
     * Update product option (running after fn_update_product_option() function)
     *
     * @param array  $option_data      Array with option data
     * @param int    $option_id        Option identifier
     * @param array  $deleted_variants Array with deleted variants ids
     * @param string $lang_code        Language code to add/update option for
     */
    fn_set_hook('update_product_option_post', $option_data, $option_id, $deleted_variants, $lang_code);
    return $option_id;
}
Example #19
0
function fn_call_requests_get_phone()
{
    return Registry::ifGet('addons.call_requests.phone', Registry::get('settings.Company.company_phone'));
}
Example #20
0
function fn_create_return_gift_certificate($order_id, $amount)
{
    $min = Registry::get('addons.gift_certificates.min_amount') * 1;
    $max = Registry::get('addons.gift_certificates.max_amount') * 1;
    $order_info = fn_get_order_info($order_id);
    $templates = fn_get_gift_certificate_templates();
    $_data = array('send_via' => 'E', 'recipient' => "{$order_info['firstname']} {$order_info['lastname']}", 'sender' => Registry::get('settings.Company.company_name'), 'amount' => $amount, 'email' => $order_info['email'], 'address' => $order_info['s_address'], 'address_2' => $order_info['s_address_2'], 'city' => $order_info['s_city'], 'country' => $order_info['s_country'], 'state' => $order_info['s_state'], 'zipcode' => $order_info['s_zipcode'], 'phone' => $order_info['phone'], 'template' => key($templates));
    if (fn_allowed_for('ULTIMATE')) {
        $_data['company_id'] = Registry::ifGet('runtime.company_id', $order_info['company_id']);
    }
    do {
        $code = fn_generate_gift_certificate_code();
    } while (true == fn_check_gift_certificate_code($code));
    if ($amount < $min || $amount > $max) {
        fn_set_notification('E', __('error'), __('gift_cert_error_amount', array('[min]' => $min, '[max]' => $max)));
        $result = array();
    } else {
        $_data = fn_array_merge($_data, array('gift_cert_code' => $code, 'timestamp' => TIME));
        $gift_cert_id = db_query('INSERT INTO ?:gift_certificates ?e', $_data);
        $result = array($gift_cert_id => array('code' => $code, 'amount' => $amount));
    }
    return $result;
}
Example #21
0
function fn_facebook_prepare_meta_data($provider_data, $params)
{
    $addon_settings = Settings::instance()->getValues('social_buttons', 'ADDON');
    if (fn_allowed_for('ULTIMATE')) {
        $company_id = Registry::ifGet('runtime.company_id', fn_get_default_company_id());
        $site_name = fn_get_company_name($company_id);
    }
    if ($params['object'] == 'products') {
        $product = Registry::get('view')->getTemplateVars('product');
        $return = array('type' => !empty($product['facebook_product_type']) ? $product['facebook_product_type'] : '', 'title' => fn_sb_format_page_title(), 'url' => fn_url('products.view?product_id=' . $params['object_id']), 'image' => !empty($product['main_pair']['detailed']['http_image_path']) ? $product['main_pair']['detailed']['http_image_path'] : '', 'site_name' => !empty($site_name) ? $site_name : Registry::get('settings.Company.company_name'), 'app_id' => !empty($addon_settings['facebook']['facebook_app_id']) ? $addon_settings['facebook']['facebook_app_id'] : '');
    } elseif ($params['object'] == 'pages') {
        $page = Registry::get('view')->getTemplateVars('page');
        $logos = fn_get_logos();
        if (fn_allowed_for('ULTIMATE')) {
            $logos = fn_get_logos($company_id);
        }
        $return = array('type' => !empty($page['facebook_obj_type']) ? $page['facebook_obj_type'] : '', 'title' => $page['page'], 'url' => !empty($page['link']) ? $page['link'] : fn_url('pages.view?product_id=' . $params['object_id']), 'image' => $logos['theme']['image']['http_image_path'], 'site_name' => !empty($site_name) ? $site_name : Registry::get('settings.Company.company_name'), 'app_id' => !empty($addon_settings['facebook']['facebook_app_id']) ? $addon_settings['facebook']['facebook_app_id'] : '');
    }
    return $return;
}
Example #22
0
function fn_discussion_get_pages(&$params, &$join, &$conditions, &$fields, &$group_by, &$sortings)
{
    if (!empty($params['rating'])) {
        $fields[] = 'avg(?:discussion_rating.rating_value) AS rating';
        $join .= db_quote(" INNER JOIN ?:discussion ON ?:discussion.object_id = ?:pages.page_id AND ?:discussion.object_type = 'A'");
        if (fn_allowed_for('ULTIMATE') && Registry::ifGet('addons.discussion.page_share_discussion', 'N') == 'N' && Registry::get('runtime.company_id')) {
            $join .= " AND ?:discussion.company_id = " . Registry::get('runtime.company_id');
        }
        $join .= db_quote(" INNER JOIN ?:discussion_rating ON ?:discussion.thread_id=?:discussion_rating.thread_id");
        $join .= db_quote(" INNER JOIN ?:discussion_posts ON ?:discussion_posts.post_id=?:discussion_rating.post_id AND ?:discussion_posts.status = 'A'");
        $group_by = '?:discussion_rating.thread_id';
        $sortings['rating'] = 'rating';
        $params['sort_by'] = 'rating';
        $params['sort_order'] = 'desc';
    }
    return true;
}
/**
 * Gets part of SQL-query with codition for company_id field.
 *
 * @staticvar array $sharing_schema Local static cache for sharing schema
 * @param string $db_field Field name (usually table_name.company_id)
 * @param bool $add_and Include or not AND keyword berofe condition.
 * @param mixed $company_id Company ID for using in SQL condition.
 * @param bool $show_admin Include or not company_id == 0 in condition (used in the MultiVendor Edition)
 * @param bool $force_condition_for_area_c Used in the MultiVendor Edition. By default, SQL codition should be empty in the customer area. But in some cases,
 * this condition should be enabled in the customer area. If <i>$force_condition_for_area_c</i> is set, condtion will be formed for the customer area.
 * @return string Part of SQL query with company ID condition
 */
function fn_get_company_condition($db_field = 'company_id', $add_and = true, $company_id = '', $show_admin = false, $force_condition_for_area_c = false)
{
    if (fn_allowed_for('ULTIMATE')) {
        // Completely remove company condition for sharing objects
        static $sharing_schema;
        if (empty($sharing_schema) && Registry::get('addons_initiated') === true) {
            $sharing_schema = fn_get_schema('sharing', 'schema');
        }
        // Check if table was passed
        if (strpos($db_field, '.')) {
            list($table, $field) = explode('.', $db_field);
            $table = str_replace('?:', '', $table);
            // Check if the db_field table is in the schema
            if (isset($sharing_schema[$table])) {
                return '';
            }
        } else {
            return '';
        }
        if (Registry::get('runtime.company_id') && !$company_id) {
            $company_id = Registry::get('runtime.company_id');
        }
    }
    if ($company_id === '') {
        $company_id = Registry::ifGet('runtime.company_id', '');
    }
    $skip_cond = AREA == 'C' && !$force_condition_for_area_c && !fn_allowed_for('ULTIMATE');
    if (!$company_id || $skip_cond) {
        $cond = '';
    } else {
        $cond = $add_and ? ' AND' : '';
        // FIXME 2tl show admin
        if ($show_admin && $company_id) {
            $cond .= " {$db_field} IN (0, {$company_id})";
        } else {
            $cond .= " {$db_field} = {$company_id}";
        }
    }
    return $cond;
}
Example #24
0
/**
 * Get default supplier id
 *
 * @param int $company_id Supplier company_id
 * @return int Default supplier id
 */
function fn_get_default_supplier_id($company_id = 0)
{
    if (empty($company_id)) {
        $company_id = Registry::ifGet('runtime.company_id', fn_get_default_company_id());
    }
    return db_get_field("SELECT supplier_id FROM ?:suppliers WHERE status = 'A' AND company_id = ?i ORDER BY supplier_id LIMIT 1", $company_id);
}
Example #25
0
    die('Access denied');
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if ($mode == 'm_delete') {
        if (!empty($_REQUEST['delete_posts']) && is_array($_REQUEST['delete_posts'])) {
            foreach ($_REQUEST['delete_posts'] as $p_id => $v) {
                fn_discussion_delete_post($p_id);
            }
        }
    }
    if ($mode == 'delete') {
        if (!empty($_REQUEST['post_id'])) {
            fn_discussion_delete_post($_REQUEST['post_id']);
        }
    }
    return array(CONTROLLER_STATUS_OK);
}
if ($mode == 'update') {
    $discussion = array();
    if (!empty($_REQUEST['discussion_type'])) {
        $discussion = fn_get_discussion(0, $_REQUEST['discussion_type'], true, $_REQUEST);
    }
    if (!empty($discussion) && $discussion['type'] != 'D' && Registry::ifGet('addons.discussion.home_page_testimonials', 'N') != 'D') {
        if (fn_allowed_for('MULTIVENDOR') || fn_allowed_for('ULTIMATE') && Registry::get('runtime.company_id')) {
            Registry::set('navigation.tabs.discussion', array('title' => __('discussion_title_home_page'), 'js' => true));
        }
    } else {
        $discussion['is_empty'] = true;
    }
    Tygh::$app['view']->assign('discussion', $discussion);
}
Example #26
0
        $tabs['configure']['hidden'] = 'N';
    } else {
        $tabs['configure']['hidden'] = 'Y';
    }
    if (Registry::get('runtime.company_id') && Registry::get('runtime.company_id') != $shipping['company_id']) {
        unset($tabs['configure']);
        Tygh::$app['view']->assign('hide_for_vendor', true);
    }
    Registry::set('navigation.tabs', $tabs);
    Tygh::$app['view']->assign('services', $services);
    Tygh::$app['view']->assign('carriers', fn_get_carriers_from_services($services));
    Tygh::$app['view']->assign('taxes', fn_get_taxes());
    Tygh::$app['view']->assign('usergroups', fn_get_usergroups(array('type' => 'C', 'status' => array('A', 'H')), DESCR_SL));
    // Show all shipping methods
} elseif ($mode == 'manage') {
    $company_id = Registry::ifGet('runtime.company_id', null);
    Tygh::$app['view']->assign('shippings', fn_get_available_shippings($company_id));
    Tygh::$app['view']->assign('usergroups', fn_get_usergroups(array('type' => 'C', 'status' => array('A', 'H')), DESCR_SL));
}
function fn_delete_rate_values($delete_rate_data, $shipping_id, $destination_id)
{
    $rate_values = db_get_field("SELECT rate_value FROM ?:shipping_rates WHERE shipping_id = ?i AND destination_id = ?i", $shipping_id, $destination_id);
    if (!empty($rate_values)) {
        $rate_values = unserialize($rate_values);
    }
    foreach ((array) $rate_values as $rate_type => $rd) {
        foreach ((array) $rd as $amount => $data) {
            if (isset($delete_rate_data[$rate_type][$amount]) && $delete_rate_data[$rate_type][$amount] == 'Y') {
                unset($rate_values[$rate_type][$amount]);
            }
        }
Example #27
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);
}
* This  is  commercial  software,  only  users  who have purchased a valid *
* license  and  accept  to the terms of the  License Agreement can install *
* and use this program.                                                    *
*                                                                          *
****************************************************************************
* PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
* "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
****************************************************************************/
use Tygh\Registry;
if (!defined('BOOTSTRAP')) {
    die('Access denied');
}
if ($mode == 'update_mode') {
    if (!empty($_REQUEST['status']) && !empty($_REQUEST['type'])) {
        $return_url = !empty($_REQUEST['return_url']) ? $_REQUEST['return_url'] : '';
        if (fn_allowed_for('ULTIMATE') && Registry::ifGet('runtime.company_id', 0) == 0) {
            fn_set_notification('W', __('warning'), __('text_select_vendor'));
            return array(CONTROLLER_STATUS_REDIRECT, $return_url);
        }
        $c_mode = $_REQUEST['type'];
        $status = $_REQUEST['status'];
        $avail_modes = array_keys(fn_get_customization_modes());
        if (!in_array($c_mode, $avail_modes)) {
            return array(CONTROLLER_STATUS_NO_PAGE);
        }
        $changed_modes = array();
        if ($status == 'enable') {
            // disable all other modes
            $changed_modes = array_fill_keys($avail_modes, 'disable');
        }
        $changed_modes[$c_mode] = $status;
Example #29
0
****************************************************************************/
use Tygh\Registry;
use Tygh\Navigation\LastView;
if (!defined('BOOTSTRAP')) {
    die('Access denied');
}
if ($mode == 'manage') {
    $discussion_object_types = fn_get_discussion_objects();
    if (empty($_REQUEST['object_type'])) {
        reset($discussion_object_types);
        $_REQUEST['object_type'] = key($discussion_object_types);
        // FIXME: bad style
    }
    $_url = fn_query_remove(Registry::get('config.current_url'), 'object_type', 'page');
    foreach ($discussion_object_types as $obj_type => $obj) {
        if ($obj_type == 'E' && Registry::ifGet('addons.discussion.home_page_testimonials', 'D') == 'D') {
            continue;
        }
        $_name = $obj_type != 'E' ? __($obj) . ' ' . __('discussion_title_' . $obj) : __('discussion_title_' . $obj);
        // FIXME!!! Bad style
        Registry::set('navigation.tabs.' . $obj, array('title' => $_name, 'href' => $_url . '&object_type=' . $obj_type));
    }
    list($posts, $search) = fn_get_discussions($_REQUEST, Registry::get('settings.Appearance.admin_elements_per_page'));
    if (!empty($posts)) {
        foreach ($posts as $k => $v) {
            $posts[$k]['object_data'] = fn_get_discussion_object_data($v['object_id'], $v['object_type'], DESCR_SL);
        }
    }
    Tygh::$app['view']->assign('posts', $posts);
    Tygh::$app['view']->assign('search', $search);
    Tygh::$app['view']->assign('discussion_object_type', $_REQUEST['object_type']);
Example #30
0
function fn_set_cookie($var, $value, $expiry = 0)
{
    $expiry = empty($expiry) ? 0 : $expiry + TIME;
    $current_path = Registry::ifGet('config.current_path', '/');
    return setcookie($var, $value, $expiry, $current_path);
}