function add_video($product_id)
{
    global $new_video;
    assert('!empty($product_id) /* ' . __FUNCTION__ . ' */');
    $new_video['product_id'] = $product_id;
    $new_video_id = cw_array2insert('product_video', $new_video, false, array('product_id', 'pos', 'title', 'descr', 'code'));
    if ($new_video_id) {
        cw_add_top_message('Video added');
    }
    return $new_video_id;
}
function cw_payment_process_void($order)
{
    global $config;
    $doc_id = $order['doc_id'];
    $result = cw_call('cw_payment_do_void', array($order));
    if (!is_error($result)) {
        cw_call('cw_doc_place_extras_data', array($doc_id, array('capture_status' => 'V')));
        cw_call('cw_doc_change_status', array($doc_id, 'D'));
        cw_add_top_message('Payment voided, order status is changed to Declined');
    }
    return $result;
}
function cw_error_check(&$array_to_check, $rules, $attributes_type = '')
{
    $result = cw_get_return();
    // get array of errors returned by core cw_error_check()
    if ($attributes_type != 'P' || is_null($result)) {
        return $result;
    }
    // hook for products only
    if (!cw_is_catalog_product($array_to_check)) {
        return $result;
    }
    // do not check other product types
    if (empty($array_to_check['attributes']['original_url'])) {
        cw_add_top_message(cw_get_langvar_by_name('err_field_catalog_products', '', false, true), 'W');
    }
    return $result;
}
function cw_ps_bundle_process($action, $category, $category_src, $filter, $products_number, $discount, $disctype)
{
    global $tables;
    $fields[] = 'offer_id';
    $from_tbls['o'] = 'ps_offers';
    $where[] = 'pid>0';
    if ($filter['auto']) {
        $where['auto'] = "auto=1";
    }
    if ($filter['manual']) {
        $where['auto'] = "auto=0";
    }
    if ($filter['auto'] && $filter['manual']) {
        unset($where['auto']);
    }
    if ($category != 0) {
        cw_load('category');
        $subcats = cw_call('cw_category_get_subcategory_ids', array($category));
        $from_tbls['pc'] = 'products_categories';
        $where[] = 'product_id=pid';
        $where[] = 'category_id IN ("' . join('","', $subcats) . '")';
    }
    $sql = cw_db_generate_query($fields, $from_tbls, $query_joins = '', $where);
    $offers = cw_query_column($sql);
    foreach ($offers as $offer_id) {
        switch ($action) {
            case "drop":
                cw_call('cw_ps_offer_delete', array($offer_id));
                break;
            case "enable":
            case "disable":
                db_query("UPDATE {$tables['ps_offers']} SET active=" . ($action == 'enable' ? '1' : '0') . " WHERE offer_id='{$offer_id}'");
        }
    }
    $msg = count($offers) . ' offer(s) were processed';
    cw_add_top_message($msg);
}
        $arch_log_name = $var_dirs['logs_archive'] . '/' . $arch_log_file_name;
        $archive_where_string_qry = $where_string_qry;
        $arch_select_qry = "\"select ld.* from {$tables['logged_data']} as ld {$archive_where_string_qry}\"";
        $mysql_db = $app_config_file['sql']['db'];
        $mysql_user = $app_config_file['sql']['user'];
        $mysql_password = $app_config_file['sql']['password'];
        $mysql_host = $app_config_file['sql']['host'];
        $shell_comm = "echo {$arch_select_qry} | mysql --host={$mysql_host} --user={$mysql_user} --password={$mysql_password} {$mysql_db} > {$arch_log_name}";
        shell_exec($shell_comm);
        if (file_exists($arch_log_name)) {
            cw_add_top_message("Current log saved to archive: <a style='color:white' href='{$var_dirs_web['logs_archive']}/{$arch_log_file_name}'>{$arch_log_name}");
            if ($drop_archived == "1") {
                db_query("delete from ld using {$tables['logged_data']} as ld {$archive_where_string_qry}");
            }
        } else {
            cw_add_top_message('Cannot save log to file: ' . $arch_log_name, 'E');
        }
    }
    cw_header_location('index.php?target=logging');
}
$total_items = cw_query_first_cell("select count(*) from {$tables['logged_data']} as ld {$where_string_qry}");
$navigation = cw_core_get_navigation($target, $total_items, $page);
$navigation['script'] = 'index.php?target=' . $target;
$smarty->assign('navigation', $navigation);
$smarty->assign('page', $page);
$limit_qry = " LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}";
$logged_data = cw_query($s = "select ld.*, IF(ld.customer_id>0,1,0) as is_logged from {$tables['logged_data']} as ld {$where_string_qry} {$orderby_qry} {$limit_qry}");
$session_ids = array();
foreach ($logged_data as $ld_k => $ld_v) {
    $session_ids[$ld_v['cwsid']] = 1;
    $logged_data[$ld_k]['GET_POST'] = unserialize($ld_v['GET_POST']);
    if (!empty($review_id)) {
        $review_data = cw_query_first("SELECT * FROM {$tables['products_reviews']} WHERE review_id='{$review_id}'");
        foreach ($rating as $attr_id => $vote) {
            // update vote value
            $exists = cw_query_first_cell("SELECT vote_id FROM {$tables['products_votes']} WHERE review_id = '{$review_id}' AND attribute_id ='{$attr_id}'");
            if ($exists) {
                cw_array2update('products_votes', array('vote_value' => $vote), "review_id = '{$review_id}' AND attribute_id ='{$attr_id}'");
            } else {
                cw_array2insert('products_votes', array('remote_ip' => $review_data['remote_ip'], 'vote_value' => $vote, 'product_id' => $review_data['product_id'], 'customer_id' => $review_data['customer_id'], 'review_id' => $review_id, 'attribute_id' => $attr_id));
            }
            cw_review_recalculate_avg_rating($review_data['product_id'], $attr_id);
        }
        cw_review_recalculate_avg_rating($review_data['product_id']);
        cw_add_top_message(cw_get_langvar_by_name('txt_thank_you_for_review'));
    } else {
        cw_add_top_message(cw_get_langvar_by_name('err_filling_form'), 'E');
    }
    cw_header_location("index.php?target=global_reviews");
}
$items_per_page_targets[$target] = 10;
$total_items = cw_call('cw_review_get_global_review', array());
$navigation = cw_core_get_navigation($target, $total_items, $page);
$global_reviews = cw_call('cw_review_get_global_review', array('', '', " ORDER BY {$tables['products_reviews']}.ctime DESC ", "LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}", FALSE));
$items_per_page_targets[$target] = PHP_INT_MAX;
$navigation['script'] = 'index.php?target=' . $target;
$smarty->assign('navigation', $navigation);
if (!empty($global_reviews)) {
    $rating_cond = "type='global_rating'";
    list($attributes, $nav) = cw_func_call('cw_attributes_search', array('data' => array('active' => 1, 'is_show' => 1, 'sort_field' => 'orderby')), array('where' => array($rating_cond)));
    if (!empty($attributes)) {
        foreach ($global_reviews as $rev_k => $rev_v) {
                                cw_array2update('cms', $data, "contentsection_id = '" . $contentsection_id . "'");
                            }
                            cw_array2update('cms_alt_languages', $data, "contentsection_id = '" . $contentsection_id . "' AND code = '" . $current_language . "'");
                        }
                        // no break here because 'html' type needs image processing as well
                    // no break here because 'html' type needs image processing as well
                    case 'image':
                        if (!empty($contentsection_id) && !empty($file_upload_data) && is_array($file_upload_data)) {
                            $is_image_uploaded_and_saved = false;
                            if (cw_image_check_posted($file_upload_data['cms_images'])) {
                                if (cw_image_save($file_upload_data['cms_images'], array('id' => $contentsection_id, 'code' => $current_language))) {
                                    $is_image_uploaded_and_saved = true;
                                }
                            }
                            if (!$is_image_uploaded_and_saved) {
                                cw_add_top_message(cw_get_langvar_by_name('msg_ab_err_banner_image_not_uploaded_or_saved'), 'E');
                                cw_header_location('index.php?target=cms&mode=add');
                            }
                        }
                        break;
                }
                cw_event('on_cms_update', array($contentsection_id, $content_section));
                $presaved_content_section = array();
                cw_header_location('index.php?target=cms&mode=update&contentsection_id=' . $contentsection_id);
            }
            break;
    }
    cw_header_location('index.php?target=cms&mode=add');
}
$categories = cw_ab_get_cms_categories($contentsection_id);
$products = cw_ab_get_cms_products($contentsection_id);
        //init categories history - do not do this here, somewhere else: in order place func
        //        cw_call('cw_doc_save_history_categories', array(array()));
    }
    if (!empty($search_data['users'][$usertype]['orders']['attributes'])) {
        //init attributes history - do not do this here, somewhere else: in order place func
        //        cw_call('cw_doc_save_history_attributes', array(array()));
    }
    if ($action == 'save_search' && !empty($save_search_name)) {
        if ($save_search_restore) {
            cw_array2update('saved_search', array('name' => addslashes($save_search_name), 'type' => 'C', 'sql_query' => $sql_query4search, 'params' => serialize($search_data['users'][$usertype])), "ss_id = '{$save_search_restore}'");
            $save_search_id = $save_search_restore;
            $current_loaded_search_id = $save_search_restore;
        } else {
            $save_search_id = cw_array2insert('saved_search', array('name' => addslashes($save_search_name), 'type' => 'C', 'sql_query' => $sql_query4search, 'params' => serialize($search_data['users'][$usertype])));
        }
        cw_add_top_message("Saved search '{$save_search_name}'", 'I');
    }
    cw_header_location("index.php?target={$target}&mode=search#result");
}
if (empty($search_data['users'][$usertype])) {
    $search_data['users'][$usertype] = array('basic_search' => array('by_username' => 1, 'by_firstname' => 1, 'by_lastname' => 1, 'by_email' => 1, 'by_customer_id' => 1, 'by_company' => 1), 'search_sections' => array('basic_search' => 1), 'address' => array('type' => 1));
}
if (empty($search_data['users'][$usertype]['sort_field'])) {
    $search_data['users'][$usertype]['sort_field'] = "username";
    $search_data['users'][$usertype]['sort_direction'] = 0;
}
if (!empty($sort) && in_array($sort, array("username", "name", "email", "usertype", "last_login", 'phone', 'zipcode'))) {
    $search_data['users'][$usertype]['sort_field'] = $sort;
    $search_data['users'][$usertype]['sort_direction'] = abs(intval(isset($sort_direction) ? $sort_direction : $search_data['users'][$usertype]['sort_direction']) - 1);
}
if (!empty($page) && $search_data['users'][$usertype]['page'] != intval($page)) {
                }
                db_query("UPDATE {$tables['giftcerts']} SET status='{$val}' WHERE gc_id='{$gc_id}'");
            }
        }
        $top_message['content'] = cw_get_langvar_by_name("msg_adm_gcs_upd");
        cw_header_location("index.php?target=giftcerts");
    }
}
if ($action == "delete") {
    // Delete gift certificate
    if (!empty($gc_ids)) {
        $gcids = array_keys($gc_ids);
        // GC can be deleted if it's doc_id == 0 or is not exist
        db_query("DELETE gc \n        FROM {$tables['giftcerts']} gc\n        LEFT JOIN {$tables['docs']} d ON gc.doc_id=d.doc_id\n        WHERE gc.gc_id IN ('" . implode("' ,'", $gcids) . "')\n            AND (gc.doc_id=0 OR d.doc_id IS NULL)");
    }
    cw_add_top_message(cw_get_langvar_by_name("msg_adm_gcs_del"));
    cw_header_location("index.php?target=giftcerts");
}
if (in_array($mode, array('add_gc', 'modify_gc'))) {
    if (empty($country)) {
        $country = $config['General']['default_country'];
    }
    $smarty->assign('countries', cw_map_get_countries());
    $smarty->assign('states', cw_map_get_states($country));
    $smarty->assign('gc_templates', cw_gift_get_templates($app_dir . $app_skin_dir));
    $gc_readonly = "";
    if (!empty($gc_id)) {
        $giftcert = cw_query_first("SELECT * FROM {$tables['giftcerts']} where gc_id='" . $gc_id . "'");
        if ($giftcert['send_via'] != "E") {
            $giftcert['recipient_statename'] = cw_get_state($giftcert['recipient_state'], $giftcert['recipient_country']);
            $giftcert['recipient_countryname'] = cw_get_country($giftcert['recipient_country']);
    }
    if (defined('IS_AJAX') && constant('IS_AJAX') && $spambot_ajax_check == 'Y') {
        $antibot_validation_val[$antibot_page]['used'] = 'N';
        $smarty->assign('antibot_err', $antibot_err ? 'Y' : 'N');
        cw_ajax_add_block(array('id' => 'spambot_ajax_check_res', 'template' => 'addons/image_verification/spambot_ajax_check.tpl'));
    }
}
$send_to_friend_info =& cw_session_register("send_to_friend_info");
if ($action == 'send') {
    if ($email && $from && $name && !$antibot_err) {
        cw_load('mail');
        $smarty->assign("product", $product_info);
        $smarty->assign("name", $name);
        $smarty->assign("message", $from);
        cw_call('cw_send_mail', array($config['Company']['support_department'], $email, "mail/wishlist/send2friend_subj.tpl", "mail/wishlist/send2friend.tpl"));
        cw_add_top_message(cw_get_langvar_by_name('txt_send2friend_send'));
        $send_to_friend_info['fill_err'] = $send_to_friend_info['antibot_err'] = false;
    } else {
        $top_message['content'] = cw_get_langvar_by_name("err_filling_form");
        if ($antibot_err) {
            $top_message['content'] .= "<br />" . cw_get_langvar_by_name("msg_err_antibot");
        }
        $top_message['type'] = "E";
        $send_to_friend_info['name'] = $name;
        $send_to_friend_info['email'] = $email;
        $send_to_friend_info['from'] = $from;
        $send_to_friend_info['antibot_err'] = $antibot_err;
        $send_to_friend_info['fill_err'] = true;
    }
    cw_header_location(cw_call('cw_core_get_html_page_url', array(array('var' => 'product', 'product_id' => $product_id))));
}
if (empty($cart)) {
    return;
}
if (!empty($cart['info']['coupon']) && cw_discount_coupons_is_valid($cart['info']['coupon'], $cart['products']) > 0) {
    $cart['info']['coupon'] = '';
}
if ($action == 'add_coupon') {
    $my_coupon = cw_discount_coupons_is_valid($coupon, $cart['products']);
    if ($my_coupon == 2) {
        $message['content'] = cw_get_langvar_by_name("err_bad_coupon_warehouse_msg");
    } elseif ($my_coupon == 5) {
        $message['content'] = cw_get_langvar_by_name("txt_coupon_already_used_by_customer");
    } elseif ($my_coupon == 3) {
        $message['content'] = cw_get_langvar_by_name("txt_overstepping_coupon_order_total");
    } elseif ($my_coupon == 4) {
        $message['content'] = cw_get_langvar_by_name("txt_cart_not_contain_coupon_products");
    } elseif ($my_coupon == 1) {
        $message['content'] = cw_get_langvar_by_name("err_bad_coupon_code_msg");
    } elseif ($my_coupon == 0) {
        $cart['info']['coupon'] = $coupon;
    }
    if ($my_coupon > 0) {
        $cart['info']['coupon'] = '';
        $message['type'] = 'E';
    }
    cw_add_top_message($message['content'], $message['type']);
    $action = 'update';
} elseif ($action == 'unset_coupons') {
    $cart['info']['coupon'] = '';
    $action = 'update';
}
if ($action == 'product_filter') {
    $posted_data['facet'] = $posted_data['facet'];
    cw_array2update('attributes', $posted_data, "attribute_id='{$attribute_id}'");
    cw_header_location('index.php?target=' . $target . '&mode=att&attribute_id=' . $attribute_id);
}
if ($action == 'update_att' && is_array($posted_data)) {
    foreach ($posted_data as $attribute_id => $data) {
        cw_array2update('attributes', $data, "attribute_id='{$attribute_id}'");
    }
    cw_header_location('index.php?target=' . $target . '&mode=att');
}
if ($action == 'delete_att' && is_array($to_delete)) {
    foreach ($to_delete as $attribute_id => $tmp) {
        cw_call('cw_attributes_delete', array($attribute_id));
    }
    cw_add_top_message('Attribute has been deleted');
    cw_header_location('index.php?target=' . $target . '&mode=att');
}
if ($action == 'update_class' && is_array($posted_data)) {
    foreach ($posted_data as $attribute_class_id => $data) {
        cw_array2update('attributes_classes', $data, "attribute_class_id='{$attribute_class_id}'");
    }
    if ($is_default) {
        cw_func_call('cw_attributes_set_default_class', array('attribute_class_id' => $is_default));
    }
    cw_header_location('index.php?target=' . $target);
}
if ($action == 'modify_class') {
    $rules = array('name' => '');
    $fillerror = cw_error_check($posted_data, $rules);
    if (!$fillerror) {
            cw_call('cw_send_mail', array($email, $config['news']['newsletter_email'], "mail/newsletter_admin_subj.tpl", "mail/newsletter_admin.tpl", $config['default_admin_language']));
        }
        $current_language = $saved_lng;
        cw_header_location("index.php?target=news&mode=subscribed&email=" . urlencode(stripslashes($email)));
    }
}
if ($mode == 'unsubscribe') {
    $subscribe_lng = $current_language;
    $listid_cond = "";
    if (!empty($listid)) {
        $listid_cond = " AND list_id='{$listid}'";
        $subscribe_lng = cw_query_first_cell("SELECT lngcode FROM {$tables['newslists']} WHERE list_id='{$listid}'");
    }
    $c = cw_query_first_cell("SELECT COUNT(*) FROM {$tables['newslist_subscription']} WHERE email='{$email}'" . $listid_cond);
    if ($c < 1) {
        cw_add_top_message('Email is not subscribed to newslist', 'W');
        cw_header_location("index.php?target=news");
    }
    db_query("DELETE FROM {$tables['newslist_subscription']} WHERE email='{$email}'" . $listid_cond);
    $saved_lng = $current_language;
    #
    # Send mail notification to customer
    #
    $smarty->assign("email", $email);
    if ($config['news']['eml_newsletter_unsubscr'] == 'Y') {
        $current_language = $subscribe_lng;
        cw_call('cw_send_mail', array($config["news"]["newsletter_email"], $email, "mail/newsletter_unsubscribe_subj.tpl", "mail/newsletter_unsubscribe.tpl"));
    }
    #
    # Send mail notification to admin
    #
} elseif (empty($tables[$token_data['table']])) {
    $error = error("Token error. Table \"{$token_data['table']}\" is not defined");
} else {
    $errors = cw_call('cw_can_edit_on_place', array($token_data), array());
}
if (!empty($token_data['pk'])) {
    $pk_fields = cw_query("SHOW KEYS FROM {$tables[$token_data['table']]} WHERE Key_name = 'PRIMARY'");
    if (count($pk_fields) > 1) {
        $error = error('Token error. Primary key is specified, but table has multicolumn primary key. Use "where" instead');
    }
    if (count($pk_fields) == 0) {
        $error = error('Token error. Primary key is specified, but table has no primary key. Use "where" instead');
    }
}
if (is_error()) {
    cw_add_top_message(get_error_message(), 'E');
    return $error;
}
$where = array();
if (!empty($token_data['pk'])) {
    $where[] = $pk_fields[0]['Column_name'] . ' = ' . $token_data['pk'];
}
if (!empty($token_data['where'])) {
    $where[] = $token_data['where'];
}
$cw_tokens[$request_prepared['token']]['old_value'] = cw_query_first_cell($q = "SELECT {$token_data['field']} FROM {$tables[$token_data['table']]} WHERE " . join(' AND ', $where));
cw_array2update($token_data['table'], array($token_data['field'] => $request_prepared['value']), join(' AND ', $where));
cw_add_top_message("Data has been saved successfully");
if ($token_data['handler']) {
    cw_call($token_data['handler'], array($token_data, $request_prepared['value']));
}
    // Create a new review
    $review_id = cw_array2insert('products_reviews', array('remote_ip' => $user_ip, 'email' => $review_author, 'main_title' => $review_main_title, 'message' => $review_message, 'product_id' => $product_id, 'customer_id' => $_customer_id, 'status' => $config['estore_products_review']['status_created_reviews'], 'ctime' => time()));
    // Create votes
    if ($config['estore_products_review']['customer_voting'] == 'Y' && !empty($rating)) {
        foreach ($rating as $attribute_id => $vote) {
            cw_array2insert('products_votes', array('remote_ip' => $user_ip, 'vote_value' => $vote, 'product_id' => $product_id, 'customer_id' => $_customer_id, 'attribute_id' => $attribute_id, 'review_id' => $review_id));
            cw_review_recalculate_avg_rating($product_id, $attribute_id);
        }
        cw_review_recalculate_avg_rating($product_id, 0);
    }
    // Update attribute 'has_review'
    // has_review has dropdown type with single option "Yes" to avoid
    // useless option "No" in product filter when we use "yes_no" type
    $attribute_value_id = cw_query_first_cell("SELECT ad.attribute_value_id\n\t\tFROM {$tables['attributes_default']} ad\n\t\tINNER JOIN {$tables['attributes']} a ON a.attribute_id = ad.attribute_id\n\t\tWHERE a.field = 'has_review' AND a.addon = 'estore_products_review'");
    cw_func_call('cw_attributes_save_attribute', array('item_id' => $product_id, 'item_type' => 'P', 'attributes' => array('has_review' => $attribute_value_id)));
    cw_add_top_message(cw_get_langvar_by_name('txt_thank_you_for_review'));
    cw_header_location($return_url);
}
$vote_result = cw_query_first("\n    SELECT COUNT(v.remote_ip) AS total, AVG(v.vote_value) AS rating\n    FROM {$tables['products_votes']} v\n    LEFT JOIN {$tables['products_reviews']} r ON r.review_id = v.review_id\n    WHERE v.product_id='{$product_id}' AND IF(v.review_id = 0, 1, r.status) = 1 \n");
if ($vote_result['total'] == 0) {
    $vote_result['rating'] = 0;
}
$vote_result['rating'] = price_format($vote_result['rating']);
$smarty->assign('vote_result', $vote_result);
$attribute_votes = cw_review_get_attribute_votes($where, $product_id);
$smarty->assign('attribute_votes', $attribute_votes);
$product_rates = cw_review_get_product_rates($product_id);
$smarty->assign('product_rates', $product_rates);
// Get reviews from DB
$fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
$from_tbls['r'] = 'products_reviews';
$max_upl_size = ($pms = ini_get('post_max_size') > ($umfs = ini_get('upload_max_filesize'))) ? $umfs : $pms;
$smarty->assign('max_upl_size', $max_upl_size);
cw_load('import_export_csv', 'product', 'category');
$import =& cw_session_register('import');
$err = "";
if ($action == 'upload' && isset($_FILES) && !empty($_FILES) && isset($_FILES['csvfile'])) {
    $tmp = $_FILES['csvfile']['tmp_name'];
    $fn = $_FILES['csvfile']['name'];
    $mtype = strtolower($_FILES['csvfile']['type']);
    if (isset($_FILES['csvfile']['error'])) {
        $error = $_FILES['csvfile']['error'];
    }
    if (isset($error) && $error != 0) {
        cw_add_top_message(cw_get_langvar_by_name('lbl_upld_err') . " " . $error, 'E');
    } elseif ($mtype != 'text/csv') {
        cw_add_top_message(cw_get_langvar_by_name('lbl_err_file_is_not_csv'), 'E');
    } else {
        $path = csv_path;
        if (!is_dir($path)) {
            mkdir($path);
        }
        $path .= '/uploaded';
        if (!is_dir($path)) {
            mkdir($path);
        }
        copy($tmp, "{$path}/{$fn}");
    }
    cw_header_location("index.php?target={$target}&mode={$mode}");
}
if ($action == 'delete' && isset($filenames) && is_array($filenames)) {
    foreach ($filenames as $v) {
         $clean_urls_by_options = explode('###', $clean_urls);
         $attribute_value_ids_by_options = explode('###', $attribute_value_ids);
         foreach ($clean_urls_by_options as $o_idx => $cu_v) {
             cw_array2insert("clean_urls_custom_facet_urls_options", array('url_id' => $custom_facet_url_id, 'attribute_value_ids' => $attribute_value_ids_by_options[$o_idx], 'clean_urls' => $cu_v));
         }
         $top_message = array('content' => cw_get_langvar_by_name("txt_custom_facet_url_added"), 'type' => 'I');
     }
     if (!empty($custom_facet_url_id) && !empty($file_upload_data) && is_array($file_upload_data)) {
         $is_image_uploaded_and_saved = false;
         if (cw_image_check_posted($file_upload_data['facet_categories_images'])) {
             if (cw_image_save($file_upload_data['facet_categories_images'], array('id' => $custom_facet_url_id))) {
                 $is_image_uploaded_and_saved = true;
             }
         }
         if (!$is_image_uploaded_and_saved) {
             cw_add_top_message('Image cannot be saved', 'E');
         }
     }
 } else {
     $replace = $result['type'] == 1 ? 'Custom clean url' : 'Clean urls combination';
     $content = str_replace('{{paramname}}', $replace, cw_get_langvar_by_name("lbl_error_param_unique", null, false, true));
     $custom_facet_url_name = cw_clean_url_get_custom_facet_url_name($result['id']);
     $replaced = "<a href='index.php?target=custom_facet_urls&mode=details&custom_facet_url_id=" . $result['id'] . "'>" . $custom_facet_url_name . "</a>";
     $content = str_replace('{{entrylink}}', $replaced, $content);
     $top_message = array('content' => $content, 'type' => 'E');
 }
 $custom_facet_url_data['attribute_value_ids'] = $attribute_value_ids;
 $custom_facet_url_data['custom_facet_url'] = $custom_facet_url;
 $custom_facet_url_data['description'] = $description;
 $custom_facet_url_data['title'] = $title;
 $param = !empty($custom_facet_url_id) ? 'details&custom_facet_url_id=' . $custom_facet_url_id : 'add';
        $address = cw_user_get_address($user, $address_id);
    }
    $smarty->assign('address', $address);
    $smarty->assign('address_id', $address_id);
    //    $smarty->assign('is_main', $is_main);
    $smarty->assign('name_prefix', 'update_fields[address][' . (in_array($address_type, array('main', 'current'), true) ? $address_type : $address_id) . ']');
    cw_add_ajax_block(array('id' => in_array($address_type, array('main', 'current'), true) ? $address_type . '_address' : 'address', 'action' => 'update', 'template' => 'main/users/sections/address_modify.tpl'), $address_type . '_address');
}
if ($action == 'set_main' || $action == 'set_current') {
    $field = $action == 'set_main' ? 'main' : 'current';
    Customer\Address\setAddressType($user, $field, $address_id);
    cw_user_check_addresses($user);
    // For correct shipping cost calculate after address changing
    cw_load('user');
    $user_address =& cw_session_register('user_address');
    $user_address = array();
    global $userinfo;
    $userinfo['current_address'] = cw_user_get_address_by_type('current');
    cw_add_top_message('Address has been updated');
}
$smarty->assign('address_type', $address_type);
$smarty->assign('user', $user);
if (defined('IS_AJAX')) {
    if ($user) {
        $addresses = cw_user_get_addresses(intval($user));
    }
    $smarty->assign('addresses', $addresses);
    cw_add_ajax_block(array('id' => 'address_book', 'action' => 'replace', 'template' => 'main/users/address_book.tpl'), 'address_book');
} else {
    cw_header_location("index.php?target={$target}&user={$user}");
}
        /* Ping Google to update sitemaps
           http://www.google.com/support/webmasters/bin/answer.py?answer=183669
           */
        cw_flush('Sending update request: ' . 'www.google.com' . '/webmasters/tools/ping' . '?sitemap=' . urlencode($http_location . '/' . $_filename));
        cw_flush("\n");
        if (!defined('IS_CRON')) {
            echo '<br />';
        }
        cw_load('http');
        list($header, $body) = cw_http_get_request('www.google.com', '/webmasters/tools/ping', 'sitemap=' . urlencode($http_location . '/' . $_filename));
        $msg = "\nGoogle response:\n" . $body;
        if (!defined('IS_CRON')) {
            $msg = '<br /><br />' . $msg;
        }
        echo $msg;
        cw_add_top_message($msg);
    }
    $success_msg = "Sitemap XML <a href='{$http_location}/{$_filename}'>file</a> updated";
    cw_call('cw_system_messages_add', array('sitemap_xml', $success_msg, SYSTEM_MESSAGE_COMMON, SYSTEM_MESSAGE_INFO));
} else {
    $msg = cw_get_langvar_by_name('msg_err_file_permission_denied', null, false, true);
    echo $msg;
    echo "<br />File: {$_filename}<br />";
    cw_add_top_message($msg, 'E');
    $warn_msg = "Sitemap XML. <acronym title='{$_filename}'>" . cw_get_langvar_by_name('msg_err_file_permission_denied') . '</acronym>';
    cw_call('cw_system_messages_add', array('sitemap_xml', $warn_msg, SYSTEM_MESSAGE_COMMON, SYSTEM_MESSAGE_WARNING));
    cw_call('cw_system_messages_show', array('sitemap_xml'));
}
if (!defined('IS_CRON')) {
    cw_flush("\n <a href='index.php?target=sitemap_xml'>Continue</a>");
}
             $new_tmp_path = $var_dirs['flex_import_test'];
             if (!file_exists($new_tmp_path)) {
                 mkdir($new_tmp_path);
             }
             $new_tmp_fname = $new_tmp_path . '/' . basename($prefilled_data['import_file']['tmp_name']);
             copy($prefilled_data['import_file']['tmp_name'], $new_tmp_fname);
             $prefilled_data['import_file']['tmp_name'] = $new_tmp_fname;
         }
     } elseif ($action == 'import_file') {
         $parsed_file = cw_call('cw_flexible_import_parse_file', array($fi_profile, false));
         if ($parsed_file && !$parsed_file['err']) {
             cw_add_top_message(cw_get_langvar_by_name('lbl_import_success'), 'I');
         }
     }
     if ($parsed_file['err']) {
         cw_add_top_message($parsed_file['err'], 'E');
     }
     cw_header_location("index.php?target={$target}&mode={$mode}&action=check" . $url_id);
 } elseif ($action == 'check') {
 } elseif ($action == 'save_profile') {
     unset($fi_profile['test_file_demo_content']);
     $fi_profile['test_import_file'] = $prefilled_data['import_file'];
     $result = cw_call('cw_flexible_import_save_profile', array($fi_profile, $fi_profile['type']));
     if ($result) {
         cw_header_location("index.php?target=import&mode=flexible_import_profile&step=mapping&profile_id=" . (!empty($fi_profile['id']) ? $fi_profile['id'] : $result));
     }
 } elseif ($action == 'delete_profile') {
     if ($profile_ids) {
         cw_call('cw_flexible_import_delete_profile', array('profile_ids' => $profile_ids));
     }
     cw_header_location("index.php?target=import&mode=flexible_import");
$identifiers =& cw_session_register('identifiers', array());
if (!empty($_GET['operate_as_user']) && !empty($identifiers['A'])) {
    // operate as user
    $tmp_user = cw_query_first("SELECT usertype, email \n    FROM {$tables['customers']} \n    WHERE customer_id='{$operate_as_user}'");
    if ($tmp_user['usertype'] == 'C') {
        $identifiers['C'] = array('customer_id' => $operate_as_user);
        $customer_id = $operate_as_user;
        cw_load('cart');
        $cart =& cw_session_register('cart', array());
        $cart = cw_user_get_stored_cart($customer_id);
        $userinfo = cw_user_get_info($customer_id);
        $products = cw_call('cw_products_in_cart', array($cart, $userinfo));
        $cart = cw_func_call('cw_cart_calc', array('cart' => $cart, 'products' => $products, 'userinfo' => $userinfo));
        cw_add_top_message('You operate as user ' . $tmp_user['email'], 'W');
    } else {
        cw_add_top_message('You cannot operate as this user', 'E');
    }
    cw_header_location('index.php');
}
$smarty->assign_by_ref('identifiers', $identifiers);
if (defined('AREA_TYPE') && !empty($identifiers[AREA_TYPE])) {
    $customer_id = $identifiers[AREA_TYPE]['customer_id'];
} else {
    $customer_id = 0;
}
cw_include('include/check_userdata.php');
if ($current_area == 'A') {
    $merchant_password =& cw_session_register("merchant_password");
}
$is_merchant_password = '';
$is_anonymous = 0;
    }
    if ($register['password'] != $register['password2']) {
        $fill_error['password'] = true;
        $error_text .= '<br/>' . cw_get_langvar_by_name('lbl_password_confirmation_wrong');
    }
    if (count($fill_error)) {
        $prefilled_info = $register;
        $top_message = array('content' => $error_text, 'type' => 'E');
    } else {
        $register['usertype'] = $usertype;
        $register['membership_id'] = $partner_membership;
        $register['status'] = 'N';
        // Suspended by default until approval
        $customer_id = cw_user_create_profile($register);
        if ($action == 'register_seller') {
            cw_add_top_message(cw_get_langvar_by_name('lbl_b2b_account_suspended', array('email' => $register['email']), false, true), 'W');
        }
        cw_user_send_modification_mail($customer_id, true);
        $identifiers =& cw_session_register('identifiers', array());
        $identifiers[$usertype] = array('customer_id' => $customer_id);
        $prefilled_info = array();
    }
    cw_header_location("index.php?target={$target}&usertype={$usertype}");
}
if ($action == 'login_seller') {
    global $action, $current_area;
    $action = 'login';
    $current_area = seller_area_letter;
    cw_include('include/login.php');
    cw_header_location("index.php?target={$target}");
}
        }
        cw_user_update($new_profile, $user, $customer_id);
        // Sign in confirmation letter sending have to be apparently blocked if an user is fake
        if (!isset($is_anonymous) || $is_anonymous != 1) {
            cw_user_send_modification_mail($user, $is_new_profile);
        }
        cw_event('on_profile_modify', array($user, $new_profile));
        if ($mode == 'add' && $is_anonymous) {
            $top_message_text = 'Please proceed to shipping and payment';
        } else {
            $top_message_text = $mode == 'add' ? cw_get_langvar_by_name('msg_user_has_been_added_' . (empty($usertype) ? 'C' : $usertype)) : cw_get_langvar_by_name('msg_profile_upd');
        }
        cw_add_top_message($top_message_text, 'I');
    } else {
        $filled_profile = $update_fields;
        cw_add_top_message(cw_check_user_get_error($fill_error), 'E');
    }
    if (AREA_TYPE == 'A') {
        if (empty($fill_error)) {
            $mode = 'modify';
        }
        cw_header_location("index.php?target={$target}&mode={$mode}&user={$user}&js_tab={$js_tab}");
    } elseif (defined('IS_AJAX')) {
        $customer_id = $user;
        cw_func_call('cw_checkout_login', array());
    } else {
        cw_header_location("index.php?target={$target}" . ($mode ? "&mode={$mode}" : '') . "&js_tab={$js_tab}");
    }
}
if ($action == "delete" && @$confirmed == "Y" && !empty($user)) {
    // TODO: move delete function to another controller
    cw_add_top_message(cw_get_langvar_by_name('msg_product_deleted_from_cart'));
    cw_header_location('index.php?target=' . $target);
}
if (in_array($action, array('update', 'ajax_update', 'checkout'))) {
    if (!empty($productindexes)) {
        $warehouse_selection = array();
        cw_event('on_cart_productindexes_update', array(&$cart, $productindexes));
        $min_amount_warns = cw_call('cw_update_quantity_in_cart', array(&$cart, $productindexes, $warehouse_selection));
        if (!empty($min_amount_warns) && !empty($cart['products'])) {
            $min_amount_ids = array();
            foreach ($cart['products'] as $k => $v) {
                if (!isset($min_amount_warns[$v['cartid']]) || !isset($productindexes[$k]) || isset($min_amount_ids[$v['product_id']])) {
                    continue;
                }
                $product_name = cw_query_first_cell("SELECT IF({$tables['products_lng']}.product IS NULL OR {$tables['products_lng']}.product = '', {$tables['products']}.product, {$tables['products_lng']}.product) as product FROM {$tables['products']} LEFT JOIN {$tables['products_lng']} ON {$tables['products']}.product_id = {$tables['products_lng']}.product_id AND {$tables['products_lng']}.code = '{$current_language}' WHERE {$tables['products']}.product_id = '{$v['product_id']}'");
                cw_add_top_message(cw_get_langvar_by_name('lbl_cannot_buy_less_X', array('quantity' => $min_amount_warns[$v['cartid']], 'product' => $product_name)), 'W');
                $min_amount_ids[$v['product_id']] = true;
            }
        }
    }
    if (!empty($shipping_id)) {
        $cart['info']['shipping_id'] = $shipping_id;
    }
    if (!empty($payment_id)) {
        $cart['info']['payment_id'] = $payment_id;
    }
    if (!empty($shipping_arr)) {
        $cart['info']['shipping_arr'] = $shipping_arr;
    }
    if (!empty($carrier_arr)) {
        $cart['info']['carrier_arr'] = $carrier_arr;
namespace cw\addon_skeleton;

// use $target, $mode and $action params to define subject and action to call
// e.g. $target_$mode_$action or $target_$mode or $target_$action
$action_function = join('_', array_filter(array($target, $mode, $action)));
// Default action
if (empty($action_function) || !function_exists('cw\\' . addon_name . '\\' . $action_function)) {
    $action_function = 'view';
}
// Call action
$action_result = cw_call('cw\\' . addon_name . '\\' . $action_function);
// Action can return instance of Error via error() function
// see docs/core.error.txt
if (is_error($action_result)) {
    cw_add_top_message($action_result->getMessage(), 'E');
}
return $action_result;
/* ================================================================================== */
/* Actions */
function addon_main_target_view()
{
    global $request_prepared;
    if ($request_prepared['id']) {
        return error('Invalid instance ID');
        // return Error instance
    }
    /*
     * Do actions with object here
     */
    return $object;
         $code_data['email_admin'] = 0;
     }
     if (!isset($code_data['inventory_decreasing'])) {
         $code_data['inventory_decreasing'] = 0;
     }
     cw_array2update('order_statuses', $code_data, "code = '{$status_code}'");
 }
 if (!empty($added_data['code'])) {
     $added_data['code'] = trim($added_data['code']);
     $added_data['name'] = trim($added_data['name']);
     $new_os = $added_data;
     if (cw_query_first_cell("select count(*) from {$tables['order_statuses']} where code='{$added_data['code']}'")) {
         cw_add_top_message('Order Status code is already used, please enter different one', 'E');
         $item_hash = '#new_os_code';
     } elseif (empty($added_data['name'])) {
         cw_add_top_message('Cannot add new order status with empty name, please correct', 'E');
         $item_hash = '#new_os_code';
     } else {
         if (!intval($added_data['orderby'])) {
             $added_data['orderby'] = 1 + intval(cw_query_first_cell("select max(orderby) from {$tables['order_statuses']}"));
         }
         if (!isset($added_data['email_customer'])) {
             $added_data['email_customer'] = 0;
         }
         if (!isset($added_data['email_admin'])) {
             $added_data['email_admin'] = 0;
         }
         if (!isset($added_data['inventory_decreasing'])) {
             $added_data['inventory_decreasing'] = 0;
         }
         cw_array2insert('order_statuses', $added_data);
                     $tmp_fields[] = "(" . $col_data['custom_sql'] . ")";
                     $field_names[] = $_dname;
                 }
             }
             $load_data_tables_qry[] = "CREATE TABLE `{$table_name}` ({$table_key_name} int(11) NOT NULL AUTO_INCREMENT, " . implode(", ", $add_field_qry) . ", PRIMARY KEY `{$table_key_name}` (`{$table_key_name}`))ENGINE=MyISAM;";
             $load_data_tables_qry[] = "INSERT INTO `{$table_name}` (" . implode(", ", $field_names) . ") SELECT " . implode(", ", $tmp_fields) . " FROM {$parsed_file['tmp_table']}";
         }
         $load_data_tables_qry[] = "DROP TABLE IF EXISTS {$parsed_file['tmp_table']}";
         foreach ($load_data_tables_qry as $lqry) {
             cw_csvxc_logged_query($lqry);
         }
         cw_include('addons/flexible_import/include/tmp_tables_load.php');
         if ($parsed_file['err']) {
             cw_add_top_message($parsed_file['err'], 'E');
         } else {
             cw_add_top_message(cw_get_langvar_by_name('lbl_import_success'), 'I');
         }
     }
     cw_header_location("index.php?target={$target}&mode={$mode}");
 }
 $search_prefilled['files'] = cw_flexible_import_files_dir();
 $search_prefilled['sort_field'] = $sort && $sort != "" ? $sort : "id";
 $search_prefilled['sort_direction'] = $sort_direction && $sort_direction != 0 ? 0 : 1;
 $search_prefilled['items_per_page'] = $items_per_page ? $items_per_page : 20;
 $search_prefilled['page'] = $page ? $page : 1;
 $profiles = cw_call('cw_flexible_import_get_profiles', array('params' => $search_prefilled));
 $total_profiles = cw_query_first_cell("SELECT COUNT(*) from {$tables['flexible_import_profiles']}");
 $navigation = cw_core_get_navigation($target, $total_profiles, $page, $items_per_page);
 $navigation['script'] = "index.php?target=import&mode=flexible_import";
 $navigation['objects_per_page'] = $search_prefilled['items_per_page'];
 $smarty->assign('navigation', $navigation);
    }
    ini_set('zlib.output_compression', 0);
    ini_set('implicit_flush', 1);
    extract($request_prepared);
    $warn = "You have to agree explicitly that all previous data will be erased.<br>If you do agree with that, please check\n\t\"I agree, that all previous data will be erased...\" box at the bottom of this page to continue";
    if (!isset($agree) || !$agree) {
        $conn = false;
        $err = $warn;
    } else {
        $conn = cw_xcart_get_conn($path, $err, $xcart_conf);
    }
    if ($conn === false) {
        $smarty->assign('main', 'import_xcart');
        $smarty->assign('err_msg', $err);
        $smarty->assign('path', $path);
    } else {
        $t = "bcse_quotes";
        $f = 'email';
        //$smarty->assign('err_msg', "<textarea>".print_r(cw_common_tables_names($conn),true)."</textarea>");
        //cw_common_tables_diff ($conn);
        //  print_r(cw_vers_diff_attr($conn)); exit;
        cw_import_users($xcart_conf);
        import_products($xcart_conf);
        //exit;
        //header ('Location: /admin/index.php?target=categories');
        //	      echo "<script>\nwindow.location.href='/admin/index.php?target=categories'\n</script>";
        cw_add_top_message('Ok');
        cw_header_location('index.php?target=import&mode=xcart');
    }
}
$smarty->assign('main', 'import_xcart');
 $instagram_uname = $instagram_login_info['data']->user->username;
 $instagram_user_name = $instagram_login_info['data']->user->full_name;
 if (empty($instagram_user_name)) {
     $instagram_user_name = $instagram_uname;
 }
 $instagram_email = "instagram-" . $instagram_user_id . "-tmp-email";
 $instagram_profile_image_url = $instagram_login_info['data']->user->profile_picture;
 //        $instagram_personMarkup         = "$instagram_email<div><img src='$instagram_profile_image_url?sz=50'></div>";
 //================================================================
 cw_load('user');
 $user_data = cw_query_first("SELECT {$tables['customers']}.*\n                                    FROM {$tables['customers']} \n                                    WHERE oauth_uid='" . $instagram_user_id . "' AND oauth_type='I'  \n                                    AND usertype='" . $current_area . "'");
 if (!empty($user_data)) {
     // login user
     if ($user_data['status'] != 'Y') {
         //error message disabled login
         cw_add_top_message(cw_get_langvar_by_name('err_account_temporary_disabled'), 'E');
         cw_header_location($instagram_redirect_url);
     }
 } else {
     //add new customer to database
     $register = array();
     $register['email'] = $instagram_email;
     $register['usertype'] = $current_area;
     $partner_membership =& cw_session_register('partner_membership');
     $register['membership_id'] = $partner_membership;
     $customer_id = cw_user_create_profile($register);
     cw_array2update('customers', array('oauth_uid' => $instagram_user_id, 'oauth_type' => 'I'), "customer_id='{$customer_id}'");
     $user_name = explode(" ", $instagram_user_name);
     $address = array('main' => 1, 'firstname' => $user_name[0], 'lastname' => $user_name[1]);
     $userinfo = array('addresses' => $address);
     cw_user_update($userinfo, $customer_id, $customer_id);
<?php

if ($request_prepared['mode'] == 'update') {
    cw_top_menu_update($request_prepared['update_data']);
    cw_add_top_message('Menu was succesfully updated');
    cw_header_location('index.php?target=top_menu');
}
$item_list = top_menu_process(cw_top_menu_make_sql_query());
$smarty->assign('top_menu', $item_list);
$smarty->assign('main', 'top_menu');