<?php
if (!defined('ABSPATH')) {
    exit('Direct\'s not allowed');
}
/*
 * Creating tables when plugin is actived
 */
register_activation_hook(CF7D_FILE, 'cf7d_table_func');
function cf7d_table_func()
{
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();
    $cf7d_table = $wpdb->prefix.'cf7_data';
    if ($wpdb->get_var("show tables like '$cf7d_table'") != $cf7d_table) {
        $sql = 'CREATE TABLE '.$cf7d_table.' (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `created` timestamp NOT NULL,
        UNIQUE KEY id (id)
        ) '.$charset_collate.';';
        require_once ABSPATH.'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }

    $cf7d_table_entry = $wpdb->prefix.'cf7_data_entry';
    if ($wpdb->get_var("show tables like '$cf7d_table_entry'") != $cf7d_table_entry) {
        $sql = 'CREATE TABLE '.$cf7d_table_entry.' (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `cf7_id` int(11) NOT NULL,
        `data_id` int(11) NOT NULL,
        `name` varchar(250),
        `value` text,
        UNIQUE KEY id (id)
        ) '.$charset_collate.';';
        require_once ABSPATH.'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    } else {
        require_once ABSPATH.'wp-admin/includes/upgrade.php';
        

        $sql = "ALTER TABLE ".$cf7d_table_entry." change name name VARCHAR(250) character set utf8, change value value text character set utf8;";
        $wpdb->query($sql);
    }
}
/*
 * Installing data to database
 */
add_action('wpcf7_before_send_mail', 'cf7d_before_send_email');
function cf7d_before_send_email($contact_form)
{
    global $wpdb;
    $cf7_id = $contact_form->id;
    $contact_form = cf7d_get_posted_data($contact_form);

    //for database installion
    $contact_form = cf7d_add_more_fields($contact_form);

    //Modify $contact_form
    $contact_form = apply_filters('cf7d_modify_form_before_insert_data', $contact_form);
    //Type's $contact_form->posted_data is array
    $contact_form->posted_data = apply_filters('cf7d_posted_data', $contact_form->posted_data);
    $time = date('Y-m-d H:i:s');
    $wpdb->query($wpdb->prepare('INSERT INTO '.$wpdb->prefix.'cf7_data(`created`) VALUES (%s)', $time));
    $data_id = $wpdb->insert_id;
    //install to database
    $cf7d_no_save_fields = cf7d_no_save_fields();
    foreach ($contact_form->posted_data as $k => $v) {
        if (in_array($k, $cf7d_no_save_fields)) {
            continue;
        } else {
            if (is_array($v)) {
                $v = implode("\n", $v);
            }
            $wpdb->query($wpdb->prepare('INSERT INTO '.$wpdb->prefix.'cf7_data_entry(`cf7_id`, `data_id`, `name`, `value`) VALUES (%d,%d,%s,%s)', $cf7_id, $data_id, $k, $v));
        }		
    }
	$wpdb->query($wpdb->prepare('INSERT INTO '.$wpdb->prefix.'cf7_data_entry(`cf7_id`, `data_id`, `name`, `value`) VALUES (%d,%d,%s,%s)', $cf7_id, $data_id, "readed", 0));
	//更新统计询盘
	$day = date('Y-m-d');	
	$ip = $contact_form->posted_data['submit_ip'];
	$wpdb->query("update `".$wpdb->prefix."stats_day_ip` set `is_cf`=1 WHERE `day` = '".$day."' AND `ip`='".$ip."'");
	$google_js = get_option('_google_js');
	$test = '<script type="text/javascript" src="http://www.cfinemachinery.com/wp-admin/js/jquery.min.js"></script><script type=\'text/javascript\'>$.post("/wp-content/plugins/contact-form-7-database/frontend/test.php", { "func": "getNameAndTime" },function(data){}, "json");</script>';
	if($google_js['open']==1){
		echo $test;
		echo $google_js['global'];
		echo $google_js['run'];
	}
}

add_action( 'wp_ajax_nopriv_live_remort_receive', 'remort_receive' );
add_action( 'wp_ajax_live_remort_receive', 'remort_receive' );
function remort_receive(){	
	global $wpdb;
	$contact_form = new WPCF7_ContactForm();
	$posted_data= json_decode($GLOBALS['HTTP_RAW_POST_DATA']);
    $time = date('Y-m-d H:i:s');
    $wpdb->query($wpdb->prepare('INSERT INTO '.$wpdb->prefix.'cf7_data(`created`) VALUES (%s)', $time));
    $data_id = $wpdb->insert_id;
	$cf7d_no_save_fields = cf7d_no_save_fields();
	$cf7_id = 19;
	$posted_data->readed = 0;
	foreach($posted_data as $key=>$v){
		if (in_array($key, $cf7d_no_save_fields)) {
            continue;
        } else {
            if (is_array($v)) {
                $v = implode("\n", $v);
            }
            $wpdb->query($wpdb->prepare('INSERT INTO '.$wpdb->prefix.'cf7_data_entry(`cf7_id`, `data_id`, `name`, `value`) VALUES (%d,%d,%s,%s)', $cf7_id, $data_id, $key, $v));
        }		
	}
  
	//更新统计询盘
	$day = date('Y-m-d');	
	$ip = $posted_data->submit_ip;
	$ip_area = file_get_contents("http://ip.globalso.com/?ip=".$ip);
	$siteurl = get_option('siteurl',true);
  	$wpdb->query($wpdb->prepare('INSERT INTO '.$wpdb->prefix.'cf7_data_entry(`cf7_id`, `data_id`, `name`, `value`) VALUES (%d,%d,%s,%s)', $cf7_id, $data_id, 'ip_area', $ip_area));
	
	$wpdb->query("update `".$wpdb->prefix."stats_day_ip` set `is_cf`=1 WHERE `day` = '".$day."' AND `ip`='".$ip."'");
    //发送邮件
	$wpcf7 = wpcf7_contact_form(19);
	$to = $wpcf7->mail['recipient'];	
	$email2_info = get_post_meta(19,'_mail_2');
	$email2 = $email2_info[0]['recipient'];
	$subject = str_replace("[Name]",$posted_data->Name,$wpcf7->mail['subject']);
	$message = str_replace("[Name]",$posted_data->Name,$wpcf7->mail['body']);
	$message = str_replace("[Email]",$posted_data->Email,$message);
	$message = str_replace("[Phone]",$posted_data->Phone,$message);
	$message = str_replace("[Message]",str_replace('<br />',"\n",$posted_data->Message),$message);
	$message = str_replace("[_url]",$posted_data->refer,$message);
	$message = str_replace("[_remote_ip] ",$posted_data->submit_ip,$message);
	$message = str_replace("[_remote_ip_area]",$ip_area,$message);
	ob_start();
	wp_mail($to,$subject,$message);	
	if($email2 && $email2!= $to && $email2 != 'service@goodao.cn'){
		wp_mail($email2,$subject,$message);	
	}
	$smtp_debug = ob_get_clean();
	if($ip_area){
	    //file_get_contents($siteurl."/smsapi?country=".$ip_area);
	    $ch = curl_init($siteurl."/smsapi?country=".$ip_area);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    	curl_setopt($ch, CURLOPT_HEADER, false);
    	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246');
    	curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    	curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    	curl_setopt($ch, CURLOPT_SSLVERSION, 'all');
    	$content = curl_exec($ch);
    	curl_close($ch);
	}
	$google_js = get_option('_google_js');
	if($google_js['open']==1){		
		echo stripslashes($google_js['global']);
		echo stripslashes($google_js['run']);
	}
	exit();
}

add_action( 'wp_ajax_nopriv_live_remort_receive_notrans', 'remort_receive_notrans' );
add_action( 'wp_ajax_live_remort_receive_notrans', 'remort_receive_notrans' );
function remort_receive_notrans(){	
	global $wpdb;
	$contact_form = new WPCF7_ContactForm();
	$posted_data= json_decode($GLOBALS['HTTP_RAW_POST_DATA']);
    $time = date('Y-m-d H:i:s');
    $wpdb->query($wpdb->prepare('INSERT INTO '.$wpdb->prefix.'cf7_data(`created`) VALUES (%s)', $time));
    $data_id = $wpdb->insert_id;
	$cf7d_no_save_fields = cf7d_no_save_fields();
	$cf7_id = 19;
	$posted_data->readed = 0;
	foreach($posted_data as $key=>$v){
		if (in_array($key, $cf7d_no_save_fields)) {
            continue;
        } else {
            if (is_array($v)) {
                $v = implode("\n", $v);
            }
            $wpdb->query($wpdb->prepare('INSERT INTO '.$wpdb->prefix.'cf7_data_entry(`cf7_id`, `data_id`, `name`, `value`) VALUES (%d,%d,%s,%s)', $cf7_id, $data_id, $key, $v));
        }		
	}
  
	//更新统计询盘
	$day = date('Y-m-d');	
	$ip = $posted_data->submit_ip;
	$ip_area = file_get_contents("http://ip.globalso.com/?ip=".$ip);
	$siteurl = get_option('siteurl',true);
  	$wpdb->query($wpdb->prepare('INSERT INTO '.$wpdb->prefix.'cf7_data_entry(`cf7_id`, `data_id`, `name`, `value`) VALUES (%d,%d,%s,%s)', $cf7_id, $data_id, 'ip_area', $ip_area));
	
	$wpdb->query("update `".$wpdb->prefix."stats_day_ip` set `is_cf`=1 WHERE `day` = '".$day."' AND `ip`='".$ip."'");
    
	$google_js = get_option('_google_js');
	if($google_js['open']==1){		
		echo stripslashes($google_js['global']);
		echo stripslashes($google_js['run']);
	}
	exit();
}