function export()
{
    global $REQUEST_METHOD, $smarty, $config, $addons, $top_message, $customer_id, $tables;
    global $mode, $action, $amazon_config;
    $success = false;
    if ($REQUEST_METHOD != 'POST') {
        cw_header_location('index.php?target=' . addon_target);
    }
    if ($_POST['export_type'] == 'PaQ' && (empty($_POST['price']) && empty($_POST['quantity']))) {
        $top_message = array('content' => 'At least Price or Quantity must be exported.', 'type' => 'E');
        cw_header_location('index.php?target=' . addon_target);
        return false;
    }
    $_filename = 'files/amazon/' . date('Ymd') . '_' . date('His') . '_' . $_POST['export_type'] . '.csv';
    if (($filename = cw_allow_file($_filename, true)) && ($file = cw_fopen($_filename, 'w', true))) {
        $pids = cw_call('cw_objects_get_list_ids', array('P'));
        if (empty($pids)) {
            $pids = cw_query_column("SELECT product_id FROM {$tables['products']} WHERE status=1");
            // Very bad. Use API
        }
        if ($pids) {
            $amazon_config = cw_array_merge($amazon_config, $config['amazon'], $_POST);
            cw_config_update('amazon', $_POST);
            $warnings = array();
            $data = array();
            $header_put = false;
            foreach ($pids as $v) {
                $variants = array();
                $prod = cw_func_call('cw_product_get', array('id' => $v, 'info_type' => 8 | 64 | 128 | 256 | 512 | 2048));
                $attr = cw_query_hash("SELECT a.field, av.value\n                    FROM {$tables['attributes_values']} av, {$tables['attributes']} a\n                    WHERE av.item_id={$v} AND av.item_type='P' AND a.attribute_id=av.attribute_id", 'field', false, true);
                // very bad. Use API
                if ($prod['is_variants']) {
                    $variants = cw_call('cw_get_product_variants', array($v));
                } else {
                    $variants[0] = $prod;
                }
                foreach ($variants as $var) {
                    $var = cw_array_merge($var, $attr);
                    if ($_POST['export_type'] == 'PaQ') {
                        $data = array('sku' => $var['productcode'], 'price' => $_POST['price'] ? $var['price'] : '', 'quantity' => $_POST['quantity'] ? $var['avail'] : '', 'leadtime-to-ship' => $amazon_config['default_leadtime_to_ship']);
                    }
                    if ($_POST['export_type'] == 'InvLoad') {
                        $data = array('sku' => $var['productcode'], 'product-id' => empty($amazon_config['product_id_type']) ? '' : (string) $var[$amazon_config['product_id']], 'product-id-type' => $amazon_config['product_id_type'], 'price' => $var['price'], 'item-condition' => empty($var[$amazon_config['item_condition']]) ? $amazon_config['default_item_condition'] : $var[$amazon_config['item_condition']], 'quantity' => empty($amazon_config['fulfillment_center_id']) ? $var['avail'] : '', 'add-delete' => empty($_POST['add-delete']) ? 'a' : $_POST['add-delete'], 'will-ship-internationally' => empty($var[$amazon_config['ship_internationally']]) ? $amazon_config['default_ship_internationally'] : $var[$amazon_config['ship_internationally']], 'expedited-shipping' => empty($var[$amazon_config['expedited_shipping']]) ? $amazon_config['default_expedited_shipping'] : $var[$amazon_config['expedited_shipping']], 'standard-plus' => empty($var[$amazon_config['standard_plus']]) ? $amazon_config['default_standard_plus'] : $var[$amazon_config['standard_plus']], 'item-note' => $var[$amazon_config['item_note']], 'fulfillment-center-id' => $amazon_config['fulfillment_center_id'], 'product-tax-code' => $amazon_config['default_product_tax_code'], 'leadtime-to-ship' => $amazon_config['default_leadtime_to_ship']);
                    }
                    if (!$header_put) {
                        fputcsv($file, array_keys($data), "\t");
                        $header_put = true;
                    }
                    fputcsv($file, $data, "\t");
                }
            }
        }
        fclose($file);
        $top_message = array('content' => 'File <b>' . $_filename . '</b> successfully created');
    }
    cw_header_location('index.php?target=' . addon_target);
}
    cw_header_location("index.php?target=db_backup");
}
if ($REQUEST_METHOD == "POST" && $action == "restore" && ($userfile != "none" && $userfile != "" || $_POST['local_file'] && $file_exists)) {
    cw_log_flag('log_database', 'DATABASE', $log_prefix . 'Started');
    $source_file = "uploaded";
    if ($_POST['local_file']) {
        if ($fd = cw_fopen($sqldump_file, "r", true)) {
            $source_file = "local";
        }
    }
    if ($source_file == "uploaded") {
        $userfile = cw_move_uploaded_file("userfile");
    } else {
        $userfile = $sqldump_file;
    }
    $fp = cw_fopen($userfile, "rb", true);
    if ($fp === false) {
        $top_message['content'] = cw_get_langvar_by_name("msg_adm_err_sql_file_not_found");
        $top_message['type'] = "E";
        cw_log_flag('log_database', 'DATABASE', $log_prefix . cw_get_langvar_by_name("msg_adm_err_sql_file_not_found", false, false, true));
        cw_header_location("index.php?target=db_backup");
    }
    $command = "";
    echo cw_get_langvar_by_name("lbl_please_wait", false, false, true) . "<br />\n";
    $cmdcnt = 0;
    while (!feof($fp)) {
        $c = fgets($fp, 1500000);
        $c = chop($c);
        $c = ereg_replace("^[ \t]*(#|-- |---*).*", "", $c);
        $command .= $c;
        if (ereg(";\$", $command)) {
<?xml version="1.0" encoding="UTF-8"?>
   <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <sitemap>
      <loc>http://www.example.com/sitemap1.xml.gz</loc>
      <lastmod>2004-10-01T18:23:17+00:00</lastmod>
   </sitemap>
   <sitemap>
      <loc>http://www.example.com/sitemap2.xml.gz</loc>
      <lastmod>2005-01-01</lastmod>
   </sitemap>
   </sitemapindex>
*/
if ($success && is_array($index)) {
    cw_flush('Sitemap Index');
    $_filename = cw_sitemap_name('index', false);
    if (($filename = cw_allow_file($_filename, true)) && ($file = cw_fopen($_filename, 'w', true))) {
        $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<?xml-stylesheet type="text/xsl" href="' . $smarty->get_template_vars('SkinDir') . '/addons/sitemap_xml/style.xsl"?>' . "\n";
        $xml .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' . "\n";
        $xml .= '//<![CDATA[#Generated by sitemap_xml generator by CartWorks software, http://www.cartworks.com //]]>' . "\n";
        fwrite($file, $xml);
        foreach ($index as $sitemap) {
            $xml = '<sitemap><loc>' . $sitemap . '</loc><lastmod>' . $today . '</lastmod></sitemap>' . "\n";
            fwrite($file, $xml);
        }
        fwrite($file, '</sitemapindex>');
        fclose($file);
        if ($config['sitemap_xml']['sm_pack_result'] == 'Y') {
            @unlink($filename . '.gz');
            exec("gzip --suffix .gz {$filename}");
        }
$query = "SELECT * FROM {$tables['download_keys']} WHERE download_key = '{$id}'";
$res = cw_query_first($query);
# If there is corresponding key in database and not expired
if (count($res) > 0 and $res['expires'] > time()) {
    # check if there is valid distribution for this product
    $product_id = $res['product_id'];
    $result = cw_query_first("SELECT distribution, product, warehouse FROM {$tables['products']} WHERE product_id = '{$product_id}'");
    $distribution = $result['distribution'];
    $warehouse = $result['warehouse'];
    if (!is_url($distribution)) {
        if (!empty($warehouse)) {
            $warehouse_flag = cw_query_first_cell("SELECT {$tables['memberships']}.flag FROM {$tables['customers']}, {$tables['memberships']} WHERE {$tables['customers']}.customer_id='{$warehouse}' AND {$tables['customers']}.membership_id = {$tables['memberships']}.membership_id");
        }
        $distribution = $var_dirs['files'] . $distribution;
        $remote_file = false;
        $fd = cw_fopen($distribution, "rb");
    } else {
        $remote_file = true;
        $fd = fopen($distribution, "rb");
    }
    if ($fd) {
        $fname = basename($distribution);
        header("Content-type: application/force-download");
        header("Content-Disposition: attachment; filename=\"{$fname}\"");
        if (!$remote_file) {
            $size = filesize($distribution);
            header("Content-length: {$size}");
        }
        fpassthru($fd);
        fclose($fd);
    } else {
function export()
{
    global $REQUEST_METHOD, $smarty, $config, $addons, $top_message, $customer_id, $tables;
    global $mode, $action, $ebay_config;
    if ($REQUEST_METHOD != 'POST') {
        cw_header_location('index.php?target=' . addon_target);
    }
    $result = cw_ebay_check_fields($_POST);
    if (count($result)) {
        $top_message = array('content' => implode("<br />", $result), 'type' => 'E');
        cw_header_location('index.php?target=' . addon_target);
    }
    if (empty($_POST['file_name'])) {
        $_filename = addon_files_location_path . 'ebay_export_' . date('Ymd') . '_' . date('His') . '.csv';
    } else {
        $_filename = addon_files_location_path . $_POST['file_name'] . '.csv';
    }
    $_copy_filename = $_filename;
    if (($filename = cw_allow_file($_filename, true)) && ($file = cw_fopen($_filename, 'w', true))) {
        $pids = cw_call('cw_objects_get_list_ids', array('P'));
        if (empty($pids)) {
            $pids = cw_query_column("SELECT product_id FROM {$tables['products']} WHERE status=1");
            // Very bad. Use API
        }
        if ($pids) {
            $ebay_config = cw_array_merge($ebay_config, $config['ebay'], $_POST);
            cw_config_update('ebay', $_POST);
            $data = array();
            $header_put = false;
            $count_files = 0;
            foreach ($pids as $v) {
                $variants = array();
                $prod = cw_func_call('cw_product_get', array('id' => $v, 'info_type' => 8 | 64 | 128 | 256 | 512 | 2048));
                $attr = cw_query_hash("SELECT a.field, av.value\n\t                    FROM {$tables['attributes_values']} av, {$tables['attributes']} a\n\t                    WHERE av.item_id={$v} AND av.item_type='P' \n\t                    \tAND a.attribute_id=av.attribute_id", 'field', false, true);
                // very bad. Use API
                if ($prod['is_variants']) {
                    $variants = cw_call('cw_get_product_variants', array($v));
                } else {
                    $variants[0] = $prod;
                }
                foreach ($variants as $var) {
                    $var = cw_array_merge($var, $attr);
                    $ebay_category = cw_ebay_get_category_value($prod['category_id'], $ebay_config['ebay_category']);
                    if (!$ebay_category) {
                        fclose($file);
                        $top_message = array('content' => 'For <a href="index.php?target=categories&mode=edit&cat=' . $prod['category_id'] . '">Main category</a> for the product "' . $prod['product'] . '" option "Category" does not set.', 'type' => 'E');
                        cw_header_location('index.php?target=' . addon_target);
                    }
                    if (!$header_put) {
                        // Set smart headers
                        $data = array('Action' => $ebay_config['ebay_action'], 'ImmediatePayRequired=' . ($ebay_config['ebay_immediate_pay_required'] == 'Y' ? "1" : "0") => "", 'Category' => $ebay_category, 'ConditionID' => cw_ebay_get_condition_value($var, $ebay_config['ebay_condition_id']), 'Description' => substr(nl2br($var['descr']), 0, 500000), 'Duration=' . $ebay_config['ebay_duration'] => "", 'Format=' . $ebay_config['ebay_format'] => "", 'Location=' . $ebay_config['ebay_location'] => "", 'PayPalAccepted=' . ($ebay_config['ebay_paypal_accepted'] == 'Y' ? "1" : "0") => "", 'PayPalEmailAddress' => $ebay_config['ebay_paypal_accepted'] == 'Y' ? $ebay_config['ebay_paypal_email_address'] : "", 'Quantity' => $var['avail'], 'Title' => substr($var['product'], 0, 80), 'DispatchTimeMax=' . $ebay_config['ebay_dispatch_time_max'] => "", 'ReturnsAcceptedOption=' . $ebay_config['ebay_returns_accepted_option'] => "", 'StartPrice' => $var['price']);
                    } else {
                        $data = array('Action' => $ebay_config['ebay_action'], 'ImmediatePayRequired' => "", 'Category' => $ebay_category, 'ConditionID' => cw_ebay_get_condition_value($var, $ebay_config['ebay_condition_id']), 'Description' => substr(nl2br($var['descr']), 0, 500000), 'Duration' => "", 'Format' => "", 'Location' => "", 'PayPalAccepted' => "", 'PayPalEmailAddress' => $ebay_config['ebay_paypal_accepted'] == 'Y' ? $ebay_config['ebay_paypal_email_address'] : "", 'Quantity' => $var['avail'], 'Title' => substr($var['product'], 0, 80), 'DispatchTimeMax' => "", 'ReturnsAcceptedOption' => "", 'StartPrice' => $var['price']);
                    }
                    if (!$header_put) {
                        fputcsv($file, array_keys($data), ",");
                        $header_put = true;
                    }
                    fputcsv($file, $data, ",");
                    // A single file cannot exceed 15 MB
                    if (filesize($_filename) > 14680064) {
                        fclose($file);
                        $new_filename = str_replace(".csv", "_" . $count_files . ".csv", $_copy_filename);
                        rename($_filename, $new_filename);
                        $count_files++;
                        $_filename = str_replace(".csv", "_" . $count_files . ".csv", $_copy_filename);
                        $file = cw_fopen($_filename, 'w', true);
                        $header_put = false;
                    }
                }
            }
        }
        fclose($file);
        $top_message = array('content' => 'File <b>' . $_filename . '</b> successfully created');
    }
    cw_header_location('index.php?target=' . addon_target);
}
function cw_image_store_fs($image_data, $type)
{
    $dest_dir = cw_image_dir($type);
    if (isset($image_data['file_path'])) {
        $image_data['id'] = false;
        $image_data['image_id'] = false;
        $image_data['image'] = cw_file_get($image_data['file_path'], true);
    }
    $file_name = cw_image_gen_unique_filename($image_data['filename'], $type, $image_data['image_type'], $image_data['id'], $image_data['image_id']);
    if ($file_name === false) {
        return false;
    }
    $file = $dest_dir . '/' . $file_name;
    $fd = cw_fopen($file, "wb", true);
    if ($fd === false) {
        return false;
    }
    $image = fwrite($fd, $image_data['image']);
    fclose($fd);
    @chmod($file, 0666);
    if (!empty($image_data['is_copied'])) {
        unlink(cw_realpath($image_data['file_path']));
    }
    return $file;
}
         $import_file = $localfile;
         $is_import = true;
     } else {
         $top_message['content'] = cw_get_langvar_by_name("msg_err_file_wrong");
         $top_message['type'] = "E";
         $serverfile = $localfile;
         cw_header_location("index.php?target=languages");
     }
 } elseif ($source == "upload" && $import_file && $import_file != "none") {
     $import_file = cw_move_uploaded_file("import_file");
     $is_import = true;
 } else {
     $is_import = false;
 }
 if ($is_import) {
     if ($fp = cw_fopen($import_file, "r", true)) {
         $lngs = $avail_languages;
         while ($columns = fgetcsv($fp, 65536, $delimiter)) {
             if (sizeof($columns) >= 4) {
                 $res = cw_query_first("SELECT * FROM {$tables['languages']} WHERE name='{$columns['0']}' AND {$tables['languages']}.code = '{$new_language}' LIMIT 1");
                 if ($res) {
                     db_query("UPDATE {$tables['languages']} SET value='" . addslashes($columns[1]) . "', topic='" . addslashes($columns[3]) . "' WHERE name='{$columns['0']}' AND code='{$new_language}'");
                 } else {
                     db_query("INSERT INTO {$tables['languages']} (code, name, value, topic) VALUES ('{$new_language}','{$columns['0']}','" . addslashes($columns[1]) . "','" . addslashes($columns[3]) . "')");
                 }
             }
         }
         fclose($fp);
     }
 }
 cw_header_location("index.php?target=languages&language={$new_language}&topic={$topic}&page={$page}");
function cw_filesize($file)
{
    clearstatcache();
    # without can return zero for just uploaded, non-zero size and exists files (affected: PHP 4.4.0 CGI).
    if (!is_url($file)) {
        return @filesize($file);
    }
    $host = parse_url($file);
    if ($host['scheme'] != 'http') {
        return false;
    }
    if (empty($host['port'])) {
        $host['port'] = 80;
    }
    $fp = fsockopen($host['host'], $host['port'], $errno, $errstr, 30);
    if (!$fp) {
        return false;
    }
    fputs($fp, "HEAD {$host['path']}?{$host['query']} HTTP/1.0\r\n");
    fputs($fp, "Host: {$host['host']}:{$host['port']}\r\n");
    fputs($fp, "User-Agent: Mozilla/4.5 [en]\r\n");
    fputs($fp, "\r\n");
    $err = chop(fgets($fp, 4096));
    if (strpos($err, " 200 ") === false) {
        return false;
    }
    $header_passed = false;
    $len = false;
    while (!feof($fp)) {
        $line = fgets($fp, 4096);
        if ($line == "\n" || $line == "\r\n") {
            break;
        }
        $header_line = explode(": ", $line, 2);
        if (strtoupper($header_line[0]) == 'CONTENT-LENGTH') {
            $len = (int) trim($header_line[1]);
            break;
        }
    }
    fclose($fp);
    if ($len === false) {
        if ($fp = cw_fopen($file, 'rb')) {
            while (strlen($str = fread($fp, 8192)) > 0) {
                $len += strlen($str);
            }
            fclose($fp);
        }
    }
    return $len;
}