/**
 * Get shares of the orders distributed between admin and sellers in case the payments go directly to sellers.
 * Shares are returned in absolute amounts, not as percentage
 * 
 * @param array $cart
 * 
 * @return
 * array(
 *  [0] => <admin_share_amount>,
 *  [seller1_id] => <seller_share_amount>,
 *  [seller2_id] => <seller_share_amount>,
 * )
 */
function cw_seller_get_payment_shares($cart)
{
    global $config;
    $shares = array(0 => 0.0);
    foreach ($cart['orders'] as $order) {
        $seller = cw_call('cw_user_get_info', array($order['warehouse_customer_id'], 65535));
        $seller['custom_fields'] = cw_user_get_custom_fields($seller['customer_id'], 0, '', 'field');
        if (empty($seller) || $seller['usertype'] == 'A') {
            $seller['customer_id'] = 0;
        }
        if ($config['seller']['seller_enable_admin_commission_share'] == 'Y') {
            $admin_commision = $seller['custom_fields']['admin_commission_rate'] > 0 ? $seller['custom_fields']['admin_commission_rate'] : $config['seller']['seller_admin_commission_rate'];
        } else {
            $admin_commission = 0.0;
        }
        $shares[$seller['customer_id']] += $_seller_share = (1 - $admin_commision / 100) * $order['info']['total'];
        $shares[0] += $order['info']['total'] - $_seller_share;
    }
    cw_log_add('seller_shares', $shares);
    return $shares;
}
function cw_log_flag($flag_key, $label, $message, $add_backtrace = false, $stack_skip = 0)
{
    static $email_addresses = false;
    global $config;
    if ($email_addresses === false && isset($config['Logging']['email_addresses'])) {
        $email_addresses = array_unique(explode('[ ,]+', $config['Logging']['email_addresses']));
    }
    $do_log = empty($config);
    $addresses = false;
    $do_email = false;
    if (isset($config['Logging'][$flag_key])) {
        $value = $config['Logging'][$flag_key];
        $do_log = strpos($value, 'L') !== false;
        $do_email = strpos($value, 'E') !== false;
    }
    if ($do_email) {
        $addresses = $email_addresses;
    }
    if ($do_log || $do_email) {
        cw_log_add($label, $message, $add_backtrace, $stack_skip + 1, $addresses, $do_email && !$do_log);
    }
}
         }
     }
 }
 if ($server_filenames) {
     foreach ($server_filenames as $s_file) {
         $profile['file_name'] = fi_files_path . $s_file;
         $parsed_file = cw_call('cw_flexible_import_parse_file', array($profile, false));
         if ($parsed_file['err']) {
             break;
         }
     }
 } else {
     $profile['import_file'] = $_FILES['import_file'];
     $parsed_file = cw_call('cw_flexible_import_parse_file', array($profile, false));
 }
 cw_log_add("flexible_import", array("Import started", "parsed_file" => $parsed_file, "profile" => $profile, "mapping_data" => $mapping_data));
 $load_data_tables_qry = array();
 foreach ($mapping_data as $import_section_name => $tbl_map) {
     $table_name = "tmp_load_{$import_section_name}";
     $table_key_name = "id_" . strtolower($import_section_name);
     $load_data_tables_qry[] = "DROP TABLE IF EXISTS `{$table_name}`;";
     $add_field_qry = array();
     $field_names = array();
     $tmp_fields = array();
     foreach ($tbl_map as $col_id => $col_data) {
         $_dname = $col_id;
         //$col_data['imp_field'];
         if (!empty($csvxc_field_types[$_dname])) {
             $add_field_qry[] = "`{$_dname}` " . $csvxc_field_types[$_dname];
         } else {
             if (isset($csvxc_field_types["default_{$import_section_name}"])) {
function cw_array2update_esc($tab, $arr, $where = '')
{
    foreach ($arr as $k => $v) {
        if (preg_match("'\\''", $v)) {
            $arr[$k] = addslashes($v);
        }
    }
    print "u ";
    /*
    print("<br>");
    print_r(array($tab,$arr,$where)); 
    print("<br>\n");
    return;*/
    cw_log_add("import_xcart", array("update", $tab, $arr, $where));
    return cw_array2update($tab, $arr, $where);
}
        }
    }
    if ($config['google_base']['gb_file_format'] == 'xml') {
        cw_gb_write_xml($file, $data);
    } else {
        cw_gb_write_csv($file, $data);
    }
    fclose($file);
}
if (defined('GB_XML_OUT') && constant('GB_XML_OUT')) {
    //    header('Content-type: text/plain');
    header('Content-type: text/' . $config['google_base']['gb_file_format']);
    echo file_get_contents($_filename);
}
$result = count($data);
if ($success) {
    $top_message = array('content' => 'The products have been exported successfully', 'type' => 'I');
    if (!empty($warnings)) {
        cw_log_add('google_base', $warnings);
        $top_message = array('content' => implode('<br />', array_slice($warnings, 0, 10)) . '...', 'type' => 'W');
    }
    $success_msg = "Google Base <a href='{$http_location}/{$_filename}'>file</a> updated, records count: {$result}";
    cw_call('cw_system_messages_add', array('google_base', $success_msg, SYSTEM_MESSAGE_COMMON, SYSTEM_MESSAGE_INFO));
} else {
    $top_message = array('content' => cw_get_langvar_by_name('msg_err_file_permission_denied'), 'type' => 'E');
    $warn_msg = "Google Base. <acronym title='{$_filename}'>" . cw_get_langvar_by_name('msg_err_file_permission_denied') . '</acronym>';
    cw_call('cw_system_messages_add', array('google_base', $warn_msg, SYSTEM_MESSAGE_COMMON, SYSTEM_MESSAGE_WARNING));
    cw_call('cw_system_messages_show', array('google_base'));
}
unset($data, $xml, $items);
return $result;
        $_log .= "[REQUEST {$xml_id}]:\n\n" . $xml_data['xml_request'] . "\n\n";
        $request = $server . "?API=" . $data['api'] . "&XML=" . urlencode($xml_data['xml_request']);
        $_log .= "[SEND REQUEST TO URL]:\n\n" . $request . "\n\n";
        # Sending secure GET request to USPS (for first-type image)
        list($header, $return) = cw_https_request("GET", $request);
        $_log .= "[RESPONSE]:\n\n" . $header . "\n\n" . $return . "\n\n";
        # Parcing first USPS response
        $response = cw_usps_parce_result($return, $data['xml_head'], $xml_data['file_type']);
        if ($response['error'] && $response['error_code'] != $xml_data['ignore']) {
            $error[$method . " #" . $xml_id] = $response['data'];
        }
        if ($response['error']) {
            $_log .= "[ERROR]:\n\n" . $method . " " . $xml_id . " = " . $response['data'] . "\n\n";
        } else {
            # Saving labels or messages
            cw_usps_save_response($response, $method, $xml_id);
        }
    }
}
if (defined('USPS_DEBUG')) {
    cw_log_add('usps', $_log);
}
$status =& cw_session_register("status");
$error =& cw_session_register("error");
if (!empty($error)) {
    $status = "E";
    // Error
} else {
    $status = "S";
    // Success
}
Ejemplo n.º 7
0
function db_error_generic($query, $query_error, $msg)
{
    global $config;
    $email = false;
    if (@$config['Email']['admin_sqlerror_notify'] == "Y") {
        $email = array($config['Company']['site_administrator']);
    }
    if (DEBUG_MODE == 1 || DEBUG_MODE == 3) {
        echo '<div>INVALID SQL:' . htmlspecialchars($query_error) . "</div>\n";
        echo '<div>SQL QUERY FAILURE:' . htmlspecialchars($query) . "</div>\n";
        print_r(cw_get_backtrace());
        flush();
    }
    $do_log = DEBUG_MODE == 2 || DEBUG_MODE == 3;
    if ($email !== false || $do_log) {
        cw_log_add('SQL', $msg, true, 1, $email, !$do_log);
    }
}
Ejemplo n.º 8
0
<POZipCode></POZipCode>
<ImageType>{$image_type}</ImageType>
<LabelDate></LabelDate>
<CustomerRefNo></CustomerRefNo>
<AddressServiceRequested></AddressServiceRequested>
<SenderName></SenderName>
<SenderEMail></SenderEMail>
<RecipientName></RecipientName>
<RecipientEMail></RecipientEMail>
</{$xml_head}>
EOT;
    }
    $query_prepared = urlencode($query);
    list($header, $return) = cw_https_request("GET", $usps_server . "?API={$api}&XML=" . $query_prepared);
    if (defined('USPS_DEBUG')) {
        cw_log_add('usps', $query . "\n\n" . $header . "\n\n" . $return);
    }
    $response = array("result" => 'http_error');
    $res = cw_xml2hash($return);
    if ($res['Error']) {
        $response['result'] = 'error';
        $response['error'] = $res['Error']['Description'];
    } elseif ($res[$head . 'Response']) {
        $response['result'] = 'ok';
        if ($service_type == "GlobalAir" || $service_type == "GlobalExpress" || $service_type == "GlobalPriority") {
            $response['image'] = base64_decode(str_replace(array("\n"), array(""), $res[$head . 'Response']['LabelImage']));
        } elseif ($service_type == "ExpressMail") {
            $response['image'] = base64_decode(str_replace(array("\n"), array(""), $res[$head . 'Response']['EMLabel']));
        } else {
            $response['image'] = base64_decode(str_replace(array("\n"), array(""), $res[$head . 'Response']['DeliveryConfirmationLabel']));
        }
Ejemplo n.º 9
0
    foreach ($tasks as $task => $period) {
        if ($period == 'regular' || $executed == 0) {
            $log[$task] = cw_event($task, array($time, $last_run[$period]));
            if (empty($log[$task])) {
                $log[$task] = null;
            }
            unset($tasks[$task]);
        }
        if ($period != 'regular') {
            $executed++;
        }
    }
    $last_run['queue'] = $tasks;
    // Old fashion cron handlers are files in cron folder
    $targets = cw_func_call('cw_cron_get_targets', array('time' => $time_dump, 'hour' => $hour, 'minute' => $minute, 'manual_run' => $manual_run));
    foreach ($targets as $target) {
        $log['include:' . $target] = cw_include($area . '/' . $target . '.php');
    }
} else {
    $log[$manual_run] = cw_call($manual_run, array($time, $time));
    $log['include:' . $manual_run] = cw_include($area . '/' . $manual_run . '.php');
}
$last_run['flag'] = 0;
// Cron finished
db_query("REPLACE {$tables['config']} (name, config_category_id, value) values ('last_cron_run',1,'" . mysql_real_escape_string(serialize($last_run)) . "')");
cw_system_messages_delete('cron_not_finished');
$log['end'] = '#' . $counter . ': Cron ended at ' . date('H:i:s', time());
cw_log_add('cron', $log, false);
cw_call('cw_system_messages_delete', array('crontab_warning'));
exit(0);
// do not return back to display functions
} elseif (0 && !$is_verified) {
    $bill_output["code"] = 2;
    $bill_message = "Declined (invalid request)";
} elseif (in_array($payment_status, array('CREATED', 'INCOMPLETE', 'COMPLETED', 'PROCESSING', 'PENDING'))) {
    $bill_output["code"] = $payment_status == 'COMPLETED' ? 1 : 3;
    $bill_message = $payment_status == 'COMPLETED' ? 'Accepted' : 'Queued';
    $tx = explode('&', urldecode($txt));
    sort($tx);
    foreach ($tx as $ti => $tv) {
        if (!preg_match("/^transaction\\[\\d+\\]/", $tv)) {
            unset($tx[$ti]);
        }
    }
    $txinfo = "\n" . join("\n", $tx);
    # &memo=293%2C294%2110& .. &sender_email=us_buyer%40shabaev.com&
    cw_log_add('pp_adapt_email', array($_POST["memo"], $_POST["sender_email"]));
    $memo_parts = explode("!", $_POST["memo"]);
    if (is_array($memo_parts)) {
        $memo_doc_ids = $memo_parts[0];
        if (!empty($memo_doc_ids)) {
            $memo_doc_ids_arr = explode(",", $memo_doc_ids);
            foreach ($memo_doc_ids_arr as $memo_doc_id) {
                cw_array2insert('paypal_adaptive_doc_accounts', array('doc_id' => $memo_doc_id, 'email' => $_POST["sender_email"]), true);
            }
        }
    }
    /*
            if (!strcasecmp($payment_status, "Pending")) {
                $bill_message = "Queued";
                $bill_output["code"] = 3;
    
        }
    }
    list($message_header, $mail_message) = cw_parse_mail($msgs);
    $mail_from = $from;
    if ($config['Email']['use_base64_headers'] == "Y") {
        $mail_subject = cw_mail_quote($mail_subject, $charset);
    }
    $headers = "From: " . $mail_from . $lend . "X-Mailer: PHP/" . phpversion() . $lend . "MIME-Version: 1.0" . $lend . $message_header;
    if (trim($mail_from) != "") {
        $headers .= 'Reply-to: ' . $mail_from . $lend;
    }
    $mail_result = false;
    if ($config['Email']['use_smtp'] == "Y") {
        $mail_data = array('from' => $mail_from, 'send_to' => $to, 'subject' => $mail_subject, 'body' => $orig_mail_message, 'alt_body' => $plain_mail_message);
        $mail_result = cw_smtp_send_mail($mail_data, $config['Email']['smtp_debug_enabled'] == 'Y' ? 2 : 0);
        cw_log_add('phpmailer_sent', $mail_data);
    } else {
        if (preg_match('/([^ @,;<>]+@[^ @,;<>]+)/S', $from, $m)) {
            $mail_result = mail($to, $mail_subject, $mail_message, $headers, "-f" . $m[1]);
        } else {
            $mail_result = mail($to, $mail_subject, $mail_message, $headers);
        }
    }
    if ($mail_result) {
        cw_log_add('cron', "Email sent: {$to} - {$mail_subject}", false);
    } else {
        cw_log_add('email_errors', "Could not send email #{$mail['mail_id']}: {$to} - {$mail_subject}");
    }
    db_query("delete from {$tables['mail_spool']} where mail_id='{$mail['mail_id']}'");
    $end_time = cw_core_get_time();
}
Ejemplo n.º 12
0
 /**
  * Trigger a PEAR error
  *
  * To improve performances, the PEAR.php file is included dynamically.
  * The file is so included only when an error is triggered. So, in most
  * cases, the file isn't included and perfs are much better.
  *
  * @param string $msg error message
  * @param int $code error code
  * @access public
  */
 function raiseError($msg, $code)
 {
     //        include_once('PEAR.php');
     //        return PEAR::raiseError($msg, $code, $this->_pearErrorMode);
     cw_log_add('cache_lite', array('msg' => $msg, 'code' => $code, 'pearErrorMode' => $this->_pearErrorMode));
     return '';
 }
Ejemplo n.º 13
0
<?php

/**
 * Show or log bench result
 */
if (!empty($__bench) && (constant('BENCH_DISPLAY') || constant('BENCH_LOG'))) {
    $smarty->assign('bench_max_memory', memory_get_peak_usage(true));
    $smarty->assign_by_ref('bench', $__bench);
    if (constant('BENCH_LOG')) {
        for ($i = 1; $i < $__bench_counter; $i++) {
            $__bench_timelog[strval($__bench[$i]['start_time'] - $__start_mictotime)] = $i;
            $__bench_timelog[strval($__bench[$i]['end_time'] - $__start_mictotime)] = -1 * $i;
        }
        ksort($__bench_timelog, SORT_NUMERIC);
        $smarty->assign_by_ref('bench_timelog', $__bench_timelog);
    }
    if (constant('BENCH_DISPLAY')) {
        $smarty->display($app_dir . '/' . $app_skin_dir . '/debug/bench.tpl');
    }
    if (constant('BENCH_LOG')) {
        cw_log_add('bench_exec', $smarty->fetch($app_dir . '/' . $app_skin_dir . '/debug/bench2.tpl'));
    }
}
Ejemplo n.º 14
0
/**
 * cw_smtp_send_mail sends email via SMTP PHPmailer library
 *
 * @param
 * mail_data = array(
 * from - 'sent from' email address, optional, default value: $config['Email']['smtp_mail_from'] 
 * from_name - 'Sent from' person name, optional
 * send_to - recepient email address, required
 * send_to_name - recepient person name, optional
 * subject - email subject, required
 * body - email body, required
 * alt_body - alternative body, optional
 *
 * @return boolean
 */
function cw_smtp_send_mail($mail_data, $dbg_level = 0)
{
    global $config, $app_main_dir;
    include_once $app_main_dir . '/include/lib/PHPmailer/class.phpmailer.php';
    include_once $app_main_dir . '/include/lib/PHPmailer/class.smtp.php';
    $result = 0;
    $mail = new PHPMailer();
    $mail->isSMTP();
    //Enable SMTP debugging
    // 0 = off (for production use)
    // 1 = client messages
    // 2 = client and server messages
    $mail->SMTPDebug = $dbg_level;
    //Ask for HTML-friendly debug output
    if ($dbg_level) {
        $mail->Debugoutput = 'html';
    }
    //Set the hostname of the mail server
    $mail->Host = $config['Email']['smtp_server'];
    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
    $mail->Port = $config['Email']['smtp_port'];
    //Set the encryption system to use - ssl (deprecated) or tls
    if ($config['Email']['smtp_use_tlc_connect'] == "Y") {
        $mail->SMTPSecure = 'tls';
    }
    //Whether to use SMTP authentication
    $mail->SMTPAuth = true;
    //Username to use for SMTP authentication - use full email address for gmail
    $mail->Username = $config['Email']['smtp_username'];
    //Password to use for SMTP authentication
    $mail->Password = $config['Email']['smtp_password'];
    //Set who the message is to be sent from
    if ($config['Email']['smtp_mail_from_force'] != 'Y') {
        $mail_from = empty($mail_data['from']) ? $config['Email']['smtp_mail_from'] : $mail_data['from'];
    } else {
        $mail_from = $config['Email']['smtp_mail_from'];
    }
    $mail->setFrom($mail_from, $mail_data['from_name']);
    $mail->addAddress($mail_data['send_to'], $mail_data['send_to_name']);
    //Set the subject line
    $mail->Subject = $mail_data['subject'];
    //Read an HTML message body from an external file, convert referenced images to embedded,
    //convert HTML into a basic plain-text alternative body
    $mail->msgHTML($mail_data['body'], dirname(__FILE__));
    //Replace the plain text body with one created manually
    if (!empty($mail_data['alt_body'])) {
        $mail->AltBody = $mail_data['alt_body'];
    }
    //send the message, check for errors
    if (!$mail->send()) {
        cw_log_add("phpmailer", $mail->ErrorInfo);
    } else {
        $result = 1;
    }
    $mail->smtpClose();
    return $result;
}
Ejemplo n.º 15
0
function cw_product_stages_send_emails()
{
    global $tables, $smarty, $config;
    cw_load('doc');
    //select all active product stages settings
    $stages_settings = cw_query("select ps.title, ps.default_status, ps.default_period, ps.subject, ps.body, psp.* from {$tables['product_stages_product_settings']} psp inner join {$tables['product_stages_library']} ps on ps.stage_lib_id=psp.stage_lib_id where psp.active=1");
    foreach ($stages_settings as $stage_setting) {
        $stage_statuses = array();
        if (!empty($stage_setting['status']) && $stage_setting['status'] != -1) {
            $stage_statuses = unserialize($stage_setting['status']);
        } elseif ($stage_setting['status'] == -1 && !empty($stage_setting['default_status'])) {
            $stage_statuses = unserialize($stage_setting['default_status']);
        }
        if (empty($stage_statuses)) {
            continue;
        }
        if ($stage_setting['period'] != -1) {
            $stage_period = $stage_setting['period'];
        } else {
            $stage_period = $stage_setting['default_period'];
        }
        $smarty->assign('stage_message_subject', $stage_setting['subject']);
        $smarty->assign('stage_message_body', $stage_setting['body']);
        //find all ordered products which have been bought within stage period and which are linked to current stage_setting
        $date_past = cw_product_stages_date_in_past($stage_period);
        $ordered_items = cw_query($s = "select di.* from {$tables['docs_items']} di inner join {$tables['docs']} d on d.doc_id=di.doc_id and d.date >= '{$date_past}' where di.product_id = '{$stage_setting['product_id']}'");
        //print("$s <br/>\n");
        foreach ($ordered_items as $doc_item) {
            $doc_data = array();
            //get status change history
            $status_log = cw_query("select * from {$tables['docs_statuses_log']} where doc_id='{$doc_item['doc_id']}' and status in ('" . implode("','", $stage_statuses) . "')");
            foreach ($status_log as $st_log) {
                $days_passed = cw_product_stages_days_passed($st_log['date']);
                if ($days_passed >= $stage_period) {
                    $stage_is_processed = cw_query_first_cell("select count(*) from {$tables['product_stages_process_log']} where setting_id='{$stage_setting['setting_id']}' and doc_item_id='{$doc_item['item_id']}' and status='{$st_log['status']}'");
                    if (!$stage_is_processed) {
                        $smarty->assign('stage_status', $st_log['status']);
                        $smarty->assign('stage_status_date', $st_log['date']);
                        if (empty($doc_data)) {
                            $doc_data = cw_doc_get($doc_item['doc_id'], 8192);
                            $smarty->assign('info', $doc_data['info']);
                            $smarty->assign('products', $doc_data['products']);
                            $smarty->assign('order', $doc_data);
                            $smarty->assign('doc', $doc_data);
                            $smarty->assign('userinfo', $doc_data['userinfo']);
                            cw_log_add('stage_process', array($st_log, $stage_setting, $doc_data));
                        }
                        cw_call('cw_send_mail', array($config['Company']['orders_department'], $doc_data['userinfo']['email'], 'addons/product_stages/mail/stage_notification_subj.tpl', 'addons/product_stages/mail/stage_notification.tpl'));
                        cw_array2insert('product_stages_process_log', array('setting_id' => $stage_setting['setting_id'], 'doc_item_id' => $doc_item['item_id'], 'status' => $st_log['status'], 'date' => time()));
                    }
                }
            }
        }
    }
}
 function GetAccessToken(&$access_token)
 {
     if (!$this->session_started && !session_start()) {
         return $this->SetPHPError('it was not possible to start the PHP session', $php_error_message);
     }
     $this->session_started = true;
     $mslive_login_session =& cw_session_register('mslive_login_session', array());
     if (isset($mslive_login_session['OAUTH_ACCESS_TOKEN'][$this->access_token_url])) {
         $access_token = $mslive_login_session['OAUTH_ACCESS_TOKEN'][$this->access_token_url];
     } else {
         $access_token = array();
     }
     cw_log_add('mslive', array('get access_token' => $access_token));
     return true;
 }
 if ($success = $linkedin_login_client->Initialize()) {
     if ($success = $linkedin_login_client->Process()) {
         if (strlen($linkedin_login_client->authorization_error)) {
             $linkedin_login_client->error = $linkedin_login_client->authorization_error;
             $success = false;
         } elseif (strlen($linkedin_login_client->access_token)) {
             $success = $linkedin_login_client->CallAPI('https://api.linkedin.com/v1/people/~', 'GET', array('format' => 'json'), array('FailOnAccessError' => true), $user);
             /*
              * Use this if you just want to get the LinkedIn user email address
              */
             $success = $linkedin_login_client->CallAPI('https://api.linkedin.com/v1/people/~/email-address', 'GET', array('format' => 'json'), array('FailOnAccessError' => true), $linkedin_email);
         }
     }
     $success = $linkedin_login_client->Finalize($success);
 }
 cw_log_add('linkedin_login', array($linkedin_email, $user, $success));
 if ($success) {
     //For logged in user, get details from linkedin using access token
     $linkedin_user_id = md5($linkedin_email);
     //        $linkedin_uname                = $user->firstName . ' ' . $user->lastName;
     $linkedin_user_firstname = $user->firstName;
     $linkedin_user_lastname = $user->lastName;
     cw_load('user');
     $user_data = cw_query_first("SELECT {$tables['customers']}.*\n                                    FROM {$tables['customers']} \n                                    WHERE oauth_uid='" . $linkedin_user_id . "' AND oauth_type='L'  \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');
             if (!empty($linkedin_login_info['return_url'])) {
                 cw_header_location($linkedin_login_info['return_url']);
Ejemplo n.º 18
0
function cw_doc_place_order($params, $return = null)
{
    extract($params);
    global $cart, $discount_coupon, $smarty, $config, $addons, $salesman, $adv_campaign_id, $salesman_click_id;
    global $tables, $to_customer;
    global $wlid;
    global $app_main_dir, $REMOTE_ADDR, $PROXY_IP, $CLIENT_IP, $add_to_cart_time;
    $mintime = 10;
    cw_load('web');
    cw_lock('cw_doc_place_order');
    $doc_ids = array();
    foreach ($cart['orders'] as $cart_order_idx => $current_order) {
        # $extra - one serialized field in doc details
        # 	use $extra as storage of details which will not be used for orders search or aggregate
        # $extras - key=>value pairs in doc extras table
        # 	use $extras for scalar values which can be used in SQL queries
        $extra = cw_event('on_place_order_extra', array($current_order));
        $extra['additional_fields'] = $userinfo['additional_fields'];
        if (!empty($current_order['info']['shipping_no_offer'])) {
            $extra['shipping_no_offer'] = $current_order['info']['shipping_no_offer'];
        }
        $extras = cw_event('on_place_order_extras', array($current_order));
        //$extras['ip'] = $CLIENT_IP;
        //$extras['proxy_ip'] = $PROXY_IP;
        # kornev, each doc has got the same attributes as the other elements, like products
        # kornev, the attributes should be defined in the params by the pre function
        $doc_id = cw_doc_create_empty($order_type, array('warehouse_customer_id' => $current_order['warehouse_customer_id']), $params['prefix'], array(), $return['attributes']);
        $cart['orders'][$cart_order_idx]['created_doc_id'] = $doc_id;
        $extra['tax_info'] = array('display_taxed_order_totals' => $config['Taxes']['display_taxed_order_totals'], 'display_cart_products_tax_rates' => $config['Taxes']['display_cart_products_tax_rates'] == "Y", 'taxed_subtotal' => $current_order['display_subtotal'], 'taxed_discounted_subtotal' => $current_order['display_discounted_subtotal'], 'taxed_shipping' => $current_order['display_shipping_cost']);
        $giftcert_discount = $current_order['info']['giftcert_discount'];
        $applied_taxes = addslashes(serialize($current_order['info']['taxes']));
        $discount_coupon = $current_order['coupon'];
        if (!empty($current_order['coupon'])) {
            $current_order['coupon'] = cw_query_first_cell("SELECT coupon_type FROM {$tables['discount_coupons']} WHERE coupon='" . addslashes($current_order['coupon']) . "'") . "``" . $current_order['coupon'];
        }
        $current_order['userinfo'] = $userinfo;
        $current_order['new'] = true;
        // Flag can be used in cw_doc_update to differ just placed empty doc from update of existing doc
        $current_order['info']['shipping_id'] = $cart['info']['shipping_id'];
        $current_order['info']['payment_id'] = $cart['info']['payment_id'];
        $current_order['info']['payment_label'] = $cart['info']['payment_label'];
        $current_order['info']['quote_doc_id'] = isset($cart['info']['quote_doc_id']) ? $cart['info']['quote_doc_id'] : null;
        $current_order['info']['details'] = addslashes(cw_crypt_text($order_details));
        $current_order['info']['customer_notes'] = addslashes($customer_notes);
        if ($config['Appearance']['show_cart_summary'] == 'Y') {
            $current_order['info']['shipping_id'] = $cart['info']['shipping_arr'][$current_order['warehouse_customer_id']];
        }
        $current_order['info']['extra'] = $extra;
        $current_order['info']['extras'] = $_extras;
        $current_order['status'] = $order_status;
        $doc_info = cw_doc_get_basic_info($doc_id);
        $current_order['info']['doc_info_id'] = $doc_info['doc_info_id'];
        $current_order['info']['warehouse_customer_id'] = $current_order['warehouse_customer_id'];
        $current_order['userinfo']['main_address']['address_id'] = $doc_info['main_address_id'];
        $current_order['userinfo']['current_address']['address_id'] = $doc_info['current_address_id'];
        cw_log_add('doc_placed', array('doc_id' => $doc_id, 'current_order' => $current_order, 'cart' => $cart));
        cw_call('cw_doc_update', array($doc_id, $current_order));
        $doc_ids[] = $doc_id;
        $order = cw_call('cw_doc_get', array($doc_id));
        if ($discount_coupon) {
            // artem, TODO: no SQL
            $_per_user = cw_query_first_cell("SELECT per_user FROM {$tables['discount_coupons']} WHERE coupon='{$discount_coupon}' LIMIT 1");
            if ($_per_user == "Y") {
                $_need_to_update = cw_query_first_cell("SELECT COUNT(*) FROM {$tables['discount_coupons_login']} WHERE coupon='{$discount_coupon}' AND customer_id='" . intval($userinfo['customer_id']) . "' LIMIT 1");
                if ($_need_to_update > 0) {
                    db_query("UPDATE {$tables['discount_coupons_login']} SET times_used=times_used+1 WHERE coupon='{$discount_coupon}' AND customer_id='" . intval($userinfo['customer_id']) . "'");
                } else {
                    db_query("INSERT INTO {$tables['discount_coupons_login']} (coupon, customer_id, times_used) VALUES ('{$discount_coupon}', '" . intval($userinfo['customer_id']) . "', '1')");
                }
            } else {
                db_query("UPDATE {$tables['discount_coupons']} SET times_used=times_used+1 WHERE coupon='{$discount_coupon}'");
                db_query("UPDATE {$tables['discount_coupons']} SET status='U' WHERE coupon='{$discount_coupon}' AND times_used=times");
            }
            $discount_coupon = "";
        }
        # Mail template processing
        $admin_notify = $order_status == "Q" && $config['Email']['enable_order_notif'] == "Y" || $order_status == "I" && $config['Email']['enable_init_order_notif'] == "Y";
        $customer_notify = $order_status == "Q" || $order_status == "I" && $config['Email']['enable_init_order_notif_customer'] == "Y";
        $doc_data = $doc_data_customer = cw_call('cw_doc_get', array($doc_id));
        if ($customer_notify) {
            $to_customer = $userinfo['language'] ? $userinfo['language'] : $config['default_customer_language'];
            $doc_data_customer['products'] = cw_doc_translate_products($doc_data['products'], $to_customer);
            $smarty->assign('doc_data', $doc_data_customer);
            if ($doc_data['info']['layout_id']) {
                $layout = cw_web_get_layout_by_id($doc_data['info']['layout_id']);
            } else {
                $layout = cw_call('cw_web_get_layout', array('docs_' . $doc_data['type']), true);
            }
            $smarty->assign('layout_data', $layout);
            $smarty->assign('info', $doc_data['info']);
            $smarty->assign('products', $doc_data_customer['products']);
            $smarty->assign('order', $doc_data);
            $smarty->assign('doc', $doc_data);
            $smarty->assign('is_email_invoice', 'Y');
            cw_call('cw_send_mail', array($config['Company']['orders_department'], $userinfo['email'], 'mail/docs/customer_subj.tpl', 'mail/docs/customer.tpl', null, false, true));
            $smarty->assign('is_email_invoice', 'N');
        }
        if ($admin_notify) {
            # Notify orders department by email
            $smarty->assign('doc_data', $doc_data);
            $smarty->assign('usertype_layout', 'A');
            $smarty->assign('is_email_invoice', 'Y');
            cw_call('cw_send_mail', array($userinfo['email'], $config['Company']['orders_department'], 'mail/docs/admin_subj.tpl', 'mail/docs/admin.tpl', $config['default_admin_language'], true));
            $smarty->assign('is_email_invoice', 'N');
            $smarty->assign('usertype_layout', '');
            # Notify warehouse (or warehouses) by email
            if ($config['Email']['send_notifications_to_warehouse'] == "Y") {
                $pr_result = cw_query_first("SELECT email, language FROM {$tables['customers']} WHERE customer_id='{$current_order['warehouse_customer_id']}'");
                $prov_email = $pr_result['email'];
                if ($prov_email != $config['Company']['orders_department']) {
                    $to_customer = $pr_result['language'];
                    if (empty($to_customer)) {
                        $to_customer = $config['default_admin_language'];
                    }
                    $smarty->assign('is_email_invoice', 'Y');
                    cw_call('cw_send_mail', array($userinfo['email'], $prov_email, 'mail/docs/admin_subj.tpl', 'mail/docs/admin.tpl'));
                    $smarty->assign('is_email_invoice', 'N');
                }
            }
        }
        if ($addons['survey'] && AREA_TYPE == 'C') {
            cw_load('surveys');
            cw_check_surveys_events("OPL", $doc_data);
        }
        //cw_call('cw_doc_save_history_totals_by_customer', array(array(intval($userinfo['customer_id']))));
        cw_call('cw_doc_save_history_categories', array(array($doc_id)));
        cw_call('cw_doc_save_history_attributes', array(array($doc_id)));
    }
    # Send notifications to orders department and warehouses when product amount in stock is low
    foreach ($cart['products'] as $product) {
        if (!empty($product['distribution']) && $addons['egoods']) {
            continue;
        }
        # kornev, TOFIX
        if ($addons['product_options'] && $product['extra_data']['product_options']) {
            $avail_now = cw_get_options_amount($product['extra_data']['product_options'], $product['product_id']);
        } else {
            $avail_now = cw_query_first_cell("SELECT avail FROM {$tables['products_warehouses_amount']} WHERE product_id='" . $product['product_id'] . "' AND warehouse_customer_id ='" . $product['warehouse_customer_id'] . "'");
        }
        if ($product['low_avail_limit'] >= $avail_now && $config['Email']['eml_lowlimit_warning'] == 'Y') {
            # Mail template processing
            $product['avail'] = $avail_now;
            $smarty->assign('product', $product);
            cw_call('cw_send_mail', array($config['Company']['orders_department'], $config['Company']['orders_department'], 'mail/lowlimit/subj.tpl', 'mail/lowlimit/body.tpl'));
            $pr_result = cw_query_first("SELECT email, language FROM {$tables['customers']} WHERE customer_id='" . $product['warehouse_customer_id'] . "'");
        }
    }
    cw_unlock('cw_doc_place_order');
    return $doc_ids;
}
Ejemplo n.º 19
0
        exit;
    } elseif (strcasecmp($payment_status, "Refunded") == 0) {
        # Register Refund transaction
        if (!empty($parent_txn_id)) {
            $doc_ids = cw_payment_get_docs_by_transaction($parent_txn_id);
            foreach ($doc_ids as $doc_id) {
                cw_call('cw_doc_place_extras_data', array($doc_id, array('capture_status' => 'R', 'refund_txnid' => $txn_id)));
            }
        }
        if (constant('PP_STD_DBG')) {
            cw_log_add('paypal_std', array('callback Refunded', $doc_ids), false);
        }
        exit;
    } else {
        $bill_message = "Declined";
        $bill_output["code"] = 2;
    }
    $bill_output["billmes"] = "{$bill_message} Status: {$payment_status} (TransID #{$txn_id})";
    if (!empty($pending_reason)) {
        $bill_output["billmes"] .= " Reason: {$pending_reason}";
    }
    cw_call('cw_payment_put_data', array($skey, array('billmes' => $bill_output["billmes"])));
    if (constant('PP_STD_DBG')) {
        cw_log_add('paypal_std', array('callback end', $bill_output), false);
    }
    $return = cw_call('cw_payment_check_results', array($bill_output));
    if (constant('PP_STD_DBG')) {
        cw_log_add('paypal_std', array('callback stop', $return), false);
    }
    cw_call('cw_payment_stop', array($return));
}
function cw_survey_onsend_handler($row, $survey_id)
{
    cw_log_add("invitation", date("m/d/Y H:i:s") . " invitaion sent: " . $row['email']);
}
Ejemplo n.º 21
0
function cw_http_test_bouncer($force = false)
{
    global $config;
    global $var_dirs;
    static $module_active = null;
    if (!$force && !is_null($module_active)) {
        return $module_active;
    }
    $bouncers = array('libcurl', 'curl', 'openssl', 'ssleay', 'httpscli');
    if ($config['General']['httpsmod']) {
        array_unshift($bouncers, $config['General']['httpsmod']);
    }
    $result = false;
    foreach ($bouncers as $k => $bouncer) {
        $fn = "cw_http_test_{$bouncer}";
        if (function_exists($fn) && $fn()) {
            $result = $bouncer;
            break;
        }
    }
    $old_module = false;
    $data_file = $var_dirs['log'] . "/data.httpsmodule.php";
    if (file_exists($data_file)) {
        ob_start();
        readfile($data_file);
        $old_module = ob_get_contents();
        ob_end_clean();
        $old_module = substr($old_module, strlen(LOG_PHP_SIGNATURE));
    }
    if (!empty($old_module) && strcmp($old_module, $result)) {
        cw_log_add('ENV', "HTTPS module is changed to: {$result} (was: {$old_module})");
    }
    if ($old_module === false || strcmp($old_module, $result)) {
        $_tmp_fp = @fopen($data_file, "wb");
        if ($_tmp_fp !== false) {
            @fwrite($_tmp_fp, LOG_PHP_SIGNATURE . $result);
            @fclose($_tmp_fp);
        }
    }
    $module_active = $result;
    return $result;
}
Ejemplo n.º 22
0
function cw_order_messages_get_emails($time, $prev_time)
{
    global $tables, $config;
    global $take_messages_debug;
    /*
    $config['order_messages']['contact_email_access_info'] = '{pop.gmail.com:995/novalidate-cert/pop3/ssl}INBOX';
    */
    $mail = imap_open($config['order_messages']['contact_email_access_info'], $config['order_messages']['contact_email_address'], $config['order_messages']['contact_email_password']);
    /*cw_log_add("order_messages_get_emails",array('contact_email_access_info'=>$config['order_messages']['contact_email_access_info'],
      'contact_email_address'=>$config['order_messages']['contact_email_address'],
      'contact_email_password'=>'--hidden--'));*/
    if (!$mail) {
        //cw_log_add("order_messages_get_emails", array("imap last error: "=>imap_last_error()));
        if ($take_messages_debug == 'Y') {
            print_r(array("order_messages_get_emails", array("imap last error: " => imap_last_error())));
            print "<br>";
        }
    } else {
        if ($take_messages_debug == 'Y') {
            print_r(array("order_messages_get_emails", array("imap last error: " => imap_last_error(), "mail_obj" => $mail)));
            print "<br>";
        }
    }
    $last_mail_id = cw_query_first_cell("select max(mail_id) from {$tables['mail_rpool']}");
    if ($mail) {
        $headers = imap_headers($mail);
        if (!empty($headers)) {
            $curr_message_id = imap_num_msg($mail);
            while ($curr_message_id > 0) {
                $header = imap_header($mail, $curr_message_id);
                //do not save emails from anyone else but users
                $from = $header->from;
                foreach ($from as $id => $object) {
                    $emailfrom = $object->mailbox . "@" . $object->host;
                }
                $is_users_email = cw_query_first_cell("select count(*) from {$tables['customers']} where email='" . addslashes($emailfrom) . "'");
                if (!$is_users_email) {
                    $curr_message_id--;
                    continue;
                }
                // pull the plain text for message $n
                $st = imap_fetchstructure($mail, $curr_message_id);
                if (!empty($st->parts)) {
                    for ($i = 0, $j = count($st->parts); $i < $j; $i++) {
                        $part = $st->parts[$i];
                        if ($part->subtype == 'PLAIN') {
                            $body = imap_fetchbody($mail, $curr_message_id, $i + 1);
                        }
                    }
                } else {
                    $body = imap_body($mail, $curr_message_id);
                }
                $body = preg_replace('#(^\\w.+:\\n)?(^>.*(\\n|$))+#mi', "", $body);
                cw_array2insert('mail_rpool', array('header' => serialize($header), 'body' => addslashes($body), 'subject' => $header->subject, 'mail_from' => addslashes($emailfrom), 'mail_to' => $header->toaddress));
                cw_log_add('mail_rpool', array('header' => $header, 'subject' => $header->subject, 'mail_from' => $emailfrom, 'mail_to' => $header->toaddress, 'body' => $body));
                $curr_message_id--;
            }
        }
        imap_close($mail);
    }
    if ($last_mail_id) {
        $last_mail_id_condition = " where mail_id > '{$last_mail_id}' ";
    }
    if ($take_messages_debug != 'Y') {
        cw_order_messages_process_new_emails($last_mail_id_condition);
    }
    return;
}
Ejemplo n.º 23
0
function cw_dod_generate()
{
    global $tables, $config, $current_language;
    $generator = cw_query_first("select * from {$tables['dod_generators']} where active=1 and startdate<='" . time() . "' and enddate>'" . time() . "'  and dod_interval<>0 order by position asc, generator_id asc");
    if (!empty($generator)) {
        //check last generation date
        $last_gen_date = $generator['current_offer_date'];
        $hrs_since_last_generation = intval((time() - $last_gen_date) / 3600);
        $generate_again = false;
        if ($generator['dod_interval_type'] == 'D') {
            $generate_again = $hrs_since_last_generation >= $generator['dod_interval'] * 24;
            $offer_enddate = min($generator['enddate'], time() + $generator['dod_interval'] * 24 * 3600);
        } elseif ($generator['dod_interval_type'] == 'T') {
            $dod_period_hrs = intval(($generator['enddate'] - $generator['startdate']) / 3600);
            $hrs_interval = intval($dod_period_hrs / $generator['dod_interval']);
            $generate_again = $hrs_since_last_generation >= $hrs_interval;
            $offer_enddate = min($generator['enddate'], time() + $dod_period_hrs / $generator['dod_interval'] * 3600);
        }
        if ($generate_again || $_GET['force_generate']) {
            if (!empty($generator['used_pids'])) {
                $used_pids = explode(';', $generator['used_pids']);
            } else {
                $used_pids = array();
            }
            $dod_products = cw_query_column("select dbd.object_id from {$tables['dod_bonus_details']} dbd inner join {$tables['dod_bonuses']} db on db.generator_id=dbd.generator_id and db.bonus_id=dbd.bonus_id and db.type='" . DOD_DISCOUNT . "' where dbd.generator_id='{$generator['generator_id']}' and dbd.object_type='" . DOD_OBJ_TYPE_PRODS . "'");
            $dod_categories = cw_query_column("select dbd.object_id from {$tables['dod_bonus_details']} dbd inner join {$tables['dod_bonuses']} db on db.generator_id=dbd.generator_id and db.bonus_id=dbd.bonus_id and db.type='" . DOD_DISCOUNT . "' where dbd.generator_id='{$generator['generator_id']}' and dbd.object_type='" . DOD_OBJ_TYPE_CATS . "'");
            $dod_manufacturers = cw_query_column("select dbd.object_id from {$tables['dod_bonus_details']} dbd inner join {$tables['dod_bonuses']} db on db.generator_id=dbd.generator_id and db.bonus_id=dbd.bonus_id and db.type='" . DOD_DISCOUNT . "' where dbd.generator_id='{$generator['generator_id']}' and dbd.object_type='" . DOD_OBJ_TYPE_MANS . "'");
            $dod_attributes = cw_query("select dbd.*  from {$tables['dod_bonus_details']} dbd inner join {$tables['dod_bonuses']} db on db.generator_id=dbd.generator_id and db.bonus_id=dbd.bonus_id and db.type='" . DOD_DISCOUNT . "' where dbd.generator_id='{$generator['generator_id']}' and dbd.object_type='" . DOD_OBJ_TYPE_ATTR . "'");
            //select products by dod conditions
            $data = array();
            $dod_data_where_pids = '';
            if ($dod_products) {
                $dod_data_where_pids = "{$tables['products']}.product_id in ('" . implode("','", $dod_products) . "')";
            }
            if ($dod_categories) {
                $data['search_in_subcategories'] = 1;
                $data['category_ids'] = $dod_categories;
            }
            if ($dod_manufacturers) {
                $manufacturer_id_attribute = cw_query_first_cell("select attribute_id from {$tables['attributes']} where field='manufacturer_id' and addon='manufacturers'");
                if ($manufacturer_id_attribute) {
                    if (!isset($ret_params)) {
                        $ret_params = array();
                    }
                    if (!isset($ret_params['query_joins'])) {
                        $ret_params['query_joins'] = array();
                    }
                    $ret_params['query_joins']['atv_manufacturer'] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_manufacturer.item_id and atv_manufacturer.item_type='P' and atv_manufacturer.attribute_id = '{$manufacturer_id_attribute}' and atv_manufacturer.code in ('{$current_language}', '') and atv_manufacturer.value in ('" . implode("','", $dod_manufacturers) . "')", 'is_inner' => 1);
                }
            }
            if ($dod_attributes) {
                $param2_sql = array('eq' => '=', 'lt' => '<', 'le' => '<=', 'gt' => '>', 'ge' => '=>');
                foreach ($dod_attributes as $attr_data_k => $attr_data) {
                    $is_def_values = cw_query_first("select * from {$tables['attributes_default']} where attribute_value_id='{$attr_data['param1']}' and attribute_id='{$attr_data['object_id']}'");
                    //print_r($is_def_values);print("<br><br>");
                    $sql_operation = $param2_sql[$attr_data['param2']];
                    if (empty($sql_operation)) {
                        continue;
                    }
                    if (!isset($ret_params)) {
                        $ret_params = array();
                    }
                    if (!isset($ret_params['query_joins'])) {
                        $ret_params['query_joins'] = array();
                    }
                    if ($is_def_values) {
                        $ret_params['query_joins']['atv_dod_' . $attr_data_k] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_dod_{$attr_data_k}.item_id and atv_dod_{$attr_data_k}.item_type='P' and atv_dod_{$attr_data_k}.attribute_id = '{$attr_data['object_id']}' and atv_dod_{$attr_data_k}.code in ('{$current_language}', '')", 'is_inner' => 1);
                        $ret_params['query_joins']['atd_dod_' . $attr_data_k] = array('tblname' => 'attributes_default', 'on' => "atd_dod_{$attr_data_k}.attribute_value_id=atv_dod_{$attr_data_k}.value and atv_dod_{$attr_data_k}.attribute_id=atd_dod_{$attr_data_k}.attribute_id and atd_dod_{$attr_data_k}.value{$sql_operation}'" . addslashes($is_def_values['value']) . "'", 'is_inner' => 1);
                    } else {
                        $ret_params['query_joins']['atv_dod_' . $attr_data_k] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_dod_{$attr_data_k}.item_id and atv_dod_{$attr_data_k}.item_type='P' and atv_dod_{$attr_data_k}.attribute_id = '{$attr_data['object_id']}' and atv_dod_{$attr_data_k}.code in ('{$current_language}', '') and atv_dod_{$attr_data_k}.value{$sql_operation}'{$attr_data['param1']}'", 'is_inner' => 1);
                    }
                }
            }
            global $user_account, $current_area, $items_per_page_targets, $target;
            $items_per_page_targets[$target] = 1;
            $new_pid = 0;
            $safety_cnt = 1000;
            while (!$new_pid && $safety_cnt > 0) {
                if (!empty($data) || !empty($dod_data_where_pids)) {
                    $data['sort_field'] = 'rand';
                    $data['flat_search'] = 1;
                    $dod_data_where = array();
                    if (!empty($dod_data_where_pids)) {
                        $dod_data_where[] = $dod_data_where_pids;
                    }
                    if (!empty($used_pids)) {
                        $dod_data_where[] = "{$tables['products']}.product_id not in ('" . implode("','", $used_pids) . "')";
                    }
                    $data['where'] = implode(' and ', $dod_data_where);
                    list($products, $nav, $product_filter) = cw_func_call('cw_product_search', array('data' => $data, 'user_account' => $user_account, 'current_area' => $current_area, 'info_type' => 8, 'product_id_only' => 1), $ret_params);
                }
                $product = reset($products);
                //print_r(array('product'=>$product));print("<br><br>");
                $new_pid = $product['product_id'];
                if (!$new_pid) {
                    if ($generator['no_item_repeat']) {
                        break;
                    } else {
                        if (!empty($used_pids)) {
                            array_shift($used_pids);
                        } else {
                            break;
                        }
                    }
                }
                $safety_cnt--;
            }
            //die;
            if ($new_pid) {
                $used_pids[] = $new_pid;
            }
            $generator['used_pids'] = implode(';', $used_pids);
            $regenerate_offer = true;
            if ($regenerate_offer) {
                //regenerate offer
                if (!empty($generator['current_offer_id'])) {
                    $offer_ids = array($generator['current_offer_id']);
                    $offer_ids_query = implode("', '", $offer_ids);
                    db_query("DELETE FROM {$tables['ps_offers']} WHERE offer_id IN ('" . $offer_ids_query . "')");
                    db_query("DELETE FROM {$tables['ps_bonuses']} WHERE offer_id IN ('" . $offer_ids_query . "')");
                    db_query("DELETE FROM {$tables['ps_bonus_details']} WHERE offer_id IN ('" . $offer_ids_query . "')");
                    db_query("DELETE FROM {$tables['ps_conditions']} WHERE offer_id IN ('" . $offer_ids_query . "')");
                    db_query("DELETE FROM {$tables['ps_cond_details']} WHERE offer_id IN ('" . $offer_ids_query . "')");
                    db_query("DELETE FROM {$tables['attributes_values']} WHERE item_id IN ('" . $offer_ids_query . "') and item_type='PS'");
                    foreach ($offer_ids as $offer_id) {
                        cw_image_delete($offer_id, PS_IMG_TYPE);
                    }
                    cw_attributes_cleanup($offer_ids, PS_ATTR_ITEM_TYPE);
                    cw_cache_clean('shipping_rates');
                }
                if ($new_pid) {
                    cw_log_add('dod_generator', array('new DOD product selected' => $new_pid));
                    $new_offer_id = cw_array2insert('ps_offers', array('title' => 'Deal Of The Day', 'description' => $generator['description'], 'startdate' => time(), 'enddate' => $offer_enddate, 'active' => 1));
                }
                $current_offer_id = 0;
                if ($new_offer_id) {
                    $mdm_attribute_id = cw_query_first_cell("select attribute_id from {$tables['attributes']} where addon='multi_domains' and item_type='PS'");
                    if ($mdm_attribute_id) {
                        cw_array2insert('attributes_values', array('item_id' => $new_offer_id, 'attribute_id' => $mdm_attribute_id, 'value' => 0, 'code' => '', 'item_type' => 'PS'));
                    }
                    //copy bonus and bonus details
                    $dod_bonuses = cw_query("select * from {$tables['dod_bonuses']} where generator_id='{$generator['generator_id']}' and unused=0");
                    foreach ($dod_bonuses as $dod_bonus) {
                        $_dod_bonus = $dod_bonus;
                        unset($_dod_bonus['generator_id']);
                        $_dod_bonus['offer_id'] = $new_offer_id;
                        $new_bonus_id = cw_array2insert('ps_bonuses', $_dod_bonus);
                        if ($_dod_bonus['type'] == 'D' && $_dod_bonus['apply'] == 3) {
                            cw_array2insert('ps_bonus_details', array('bonus_id' => $new_bonus_id, 'offer_id' => $new_offer_id, 'object_id' => $new_pid, 'quantity' => 1, 'object_type' => DOD_OBJ_TYPE_PRODS));
                        } else {
                            $dod_bonus_details = cw_query("select * from {$tables['dod_bonus_details']} where generator_id='{$generator['generator_id']}' and bonus_id='{$dod_bonus['bonus_id']}'");
                            if (!empty($dod_bonus_details)) {
                                foreach ($dod_bonus_details as $dod_bonus_detail) {
                                    $_dod_bonus_detail = $dod_bonus_detail;
                                    unset($_dod_bonus_detail['generator_id']);
                                    $_dod_bonus_detail['offer_id'] = $new_offer_id;
                                    $_dod_bonus_detail['bonus_id'] = $new_bonus_id;
                                    cw_array2insert('ps_bonus_details', $_dod_bonus_detail);
                                }
                            }
                        }
                    }
                    $new_cond_id = cw_array2insert('ps_conditions', array('type' => 'P', 'total' => '0.00', 'offer_id' => $new_offer_id));
                    if ($new_cond_id) {
                        cw_array2insert('ps_cond_details', array('cond_id' => $new_cond_id, 'offer_id' => $new_offer_id, 'object_id' => $new_pid, 'quantity' => 1, 'object_type' => DOD_OBJ_TYPE_PRODS));
                    }
                    $current_offer_id = $new_offer_id;
                }
            }
            //update dod_generator fields
            cw_array2update('dod_generators', array('current_offer_id' => $current_offer_id, 'used_pids' => $generator['used_pids'], 'current_offer_date' => $current_offer_id ? time() : 0), "generator_id='{$generator['generator_id']}'");
            if ($current_offer_id && !empty($config['deal_of_day']['dod_news_template']) && $config['deal_of_day']['dod_newslist']) {
                $newslist = cw_query_first("select * from {$tables['newslists']} where list_id='" . $config['deal_of_day']['dod_newslist'] . "' and avail=1");
                if (!empty($newslist)) {
                    //create message
                    global $smarty;
                    $smarty->assign('promotion', $generator);
                    $smarty->assign('product_id', $new_pid);
                    $product_info = cw_func_call('cw_product_get', array('id' => $new_pid, 'user_account' => $user_account, 'info_type' => 65535));
                    $smarty->assign('product', $product_info);
                    $smarty->assign('news_message', $config['deal_of_day']['dod_news_template']);
                    $message = cw_display("addons/deal_of_day/admin/generate_news.tpl", $smarty, false, $newslist['lngcode']);
                    $smarty->assign('news_message', $config['deal_of_day']['dod_news_template_subject']);
                    $message_subject = cw_display("addons/deal_of_day/admin/generate_news.tpl", $smarty, false, $newslist['lngcode']);
                    //                    $message = $smarty->display('addons/deal_of_day/admin/generate_news.tpl');
                    print $message_subject . "<hr />" . $message;
                    if (!empty($message)) {
                        cw_array2insert('newsletter', array('subject' => $message_subject, 'body' => $message, 'created_date' => time(), 'send_date' => time(), 'updated_date' => time(), 'status' => 'N', 'list_id' => $config['deal_of_day']['dod_newslist'], 'show_as_news' => 1, 'allow_html' => 1));
                    }
                }
            }
        }
    }
    return $new_pid;
}
function cw_csvxc_transfer_import_images($src_table, $src_field, $key_field, $alt_field = '')
{
    global $src_images_path, $dst_images_path, $csvxc_images_translate_path, $cw_images_subdir;
    if (empty($csvxc_images_translate_path[$src_table . "_" . $src_field])) {
        return;
    }
    if (!empty($alt_field)) {
        $alt_field_qry = ", `{$alt_field}`";
    }
    $imgs_list = cw_query($qry = "SELECT `{$src_field}`, `{$key_field}`{$alt_field_qry} FROM `{$src_table}` WHERE `{$src_field}`!='' AND `{$key_field}`!=0");
    cw_log_add("flexible_import", $qry);
    $img_cw_type = $csvxc_images_translate_path[$src_table . "_" . $src_field]['dir'];
    cw_flush("<b>Importing new images {$img_cw_type}</b> found " . count($imgs_list) . " to copy <br>");
    cw_log_add("flexible_import", "<b>Importing new images {$img_cw_type}</b> found " . count($imgs_list) . " to copy <br>");
    $flush_step = intval(count($imgs_list) / 100);
    $flush_cnt = 0;
    if (empty($imgs_list)) {
        return;
    }
    if (!isset($csvxc_images_translate_path[$src_table . "_" . $src_field]['table'])) {
        $csvxc_images_translate_path[$src_table . "_" . $src_field]['table'] = 'cw_' . $img_cw_type;
    }
    cw_flush("Taking images from {$src_images_path} <br>");
    cw_log_add("flexible_import", "Taking images from {$src_images_path}");
    $img_exts = array(1 => 'gif', 2 => 'jpg', 3 => 'png');
    foreach ($imgs_list as $img_data) {
        if (strpos($img_data[$src_field], "http:") !== false) {
            $image_type = 2;
            foreach ($img_exts as $im_type => $im_ext) {
                if (strpos($img_data[$src_field], ".{$im_ext}") !== false) {
                    $image_type = $im_type;
                    break;
                }
            }
            $path_parts = parse_str($img_data[$src_field]);
            $image_ins_array = array('id' => $img_data[$key_field], 'image_path' => $img_data[$src_field], 'image_type' => $image_type, 'image_x' => 0, 'image_y' => 0, 'image_size' => 0, 'filename' => ltrim($path_parts['path'], '/'), 'date' => time(), 'alt' => isset($img_data[$alt_field]) ? $img_data[$alt_field] : '', 'avail' => 1, 'orderby' => 0, 'md5' => '');
            cw_flush("Inserted web file " . $img_data[$src_field] . " <br>");
            cw_log_add("flexible_import", "Inserted web file " . $img_data[$src_field]);
            cw_array2insert($csvxc_images_translate_path[$src_table . "_" . $src_field]['table'], $image_ins_array, 'true');
            $flush_cnt++;
            if ($flush_cnt >= $flush_step) {
                //cw_flush("+ ");
                $flush_cnt = 0;
            }
            continue;
            /*
                        cw_flush("Loading web file $img_data[$src_field]<br>");
                        //continue;
              
                        $web_file_content = file_get_contents($img_data[$src_field]);
                        if ($web_file_content) {
                            $temp_image_name = $src_images_path.'/'.md5($img_data[$src_field]);
                            @unlink($temp_image_name); 
                            if (file_put_contents($temp_image_name, $web_file_content)) {
                                $size_info = getimagesize($temp_image_name);
                                if (isset($img_exts[$size_info[2]])) {
                                    $new_temp_image_name = $temp_image_name.".".$img_exts[$size_info[2]];
                                    rename($temp_image_name, $new_temp_image_name);
                                    if (file_exists($new_temp_image_name)) {
                                        $img_data[$src_field] = md5($img_data[$src_field]).".".$img_exts[$size_info[2]]; 
                                    } 
                                }
                            }
                        }  
            */
        }
        $src_path = $src_images_path . '/' . ltrim($img_data[$src_field], '/');
        if (!file_exists($src_path)) {
            cw_flush("Cant find file {$src_path} <br>");
            cw_log_add("flexible_import", "Cant find file {$src_path}");
            //cw_flush("- ");
            continue;
        }
        $flush_cnt++;
        if ($flush_cnt >= $flush_step) {
            //cw_flush("+ ");
            $flush_cnt = 0;
        }
        $subdir_fname = $img_cw_type;
        $dest_filename = end(explode('/', $img_data[$src_field]));
        $dest_path = $dst_images_path . '/' . $subdir_fname . '/' . $dest_filename;
        $fname_c = 1;
        while (file_exists($dest_path) && $fname_c < 10 && strpos($src_path, "no_image.jpg") === false) {
            $path_parts = pathinfo($dest_path);
            $dest_filename = $path_parts['filename'] . '_' . $fname_c . '.' . $path_parts['extension'];
            $dest_path = $dst_images_path . '/' . $subdir_fname . '/' . $dest_filename;
            $fname_c++;
        }
        if (copy($src_path, $dest_path)) {
            list($image_x, $image_y, $image_type) = getimagesize($dest_path);
            $path_parts = pathinfo($dest_path);
            $image_ins_array = array('id' => $img_data[$key_field], 'image_path' => addslashes('.' . $cw_images_subdir . '/' . $subdir_fname . '/' . $dest_filename), 'image_type' => $image_type, 'image_x' => $image_x, 'image_y' => $image_y, 'image_size' => filesize($dest_path), 'filename' => addslashes($path_parts['basename']), 'date' => time(), 'alt' => isset($img_data[$alt_field]) ? $img_data[$alt_field] : '', 'avail' => 1, 'orderby' => 0, 'md5' => md5_file($dest_path));
            cw_flush("Inserted file {$dest_path} copied from {$src_path} <br>");
            cw_log_add("flexible_import", "Inserted file {$dest_path} copied from {$src_path}");
            cw_array2insert($csvxc_images_translate_path[$src_table . "_" . $src_field]['table'], $image_ins_array, 'true');
        } else {
            cw_flush("Cant copy image {$src_path} to {$dest_path}");
            cw_log_add("flexible_import", "Cant copy image {$src_path} to {$dest_path}");
        }
    }
    cw_flush("<b>Done</b><br>");
}