fgc-google-experiments.php 13.2 KB
<?php

/**
 * Plugin Name: Fgc Google Experiments
 * Plugin URI: http://fgc.vn
 * Description: Fgc Google Experiments
 * Author: Phuong An.
 * Author URI: http://fgc.vn
 * Version: 1.0
 *
 * Copyright 2016 Prospress, Inc.  (email : freedoms@prospress.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package		WooCommerce
 * @author		Phuong An
 * @since		1.0
 */
add_filter('woocommerce_general_settings', 'add_experiments_ID_setting');

function add_experiments_ID_setting($settings) {
    $updated_settings = array();
    foreach ($settings as $section) {
// at the bottom of the General Options section
        if (isset($section['id']) && 'general_options' == $section['id'] &&
                isset($section['type']) && 'sectionend' == $section['type']) {
            $updated_settings[] = array(
                'name' => 'Experiment ID',
                'desc_tip' => 'Experiment ID',
                'id' => 'woocommerce_google_experiment_id',
                'type' => 'text',
                'css' => 'min-width:300px;',
                'std' => '05JR-AqkRqWBOVdeQicVGA', // WC < 2.0
                'default' => '05JR-AqkRqWBOVdeQicVGA', // WC >= 2.0
                'desc' => 'Sample ID: 05JR-AqkRqWBOVdeQicVGA',
            );
        }
        $updated_settings[] = $section;
    }
    return $updated_settings;
}

require( 'Experiment.php' );

class Fgc_Google_Experiments {

    public static function getTableName() {
        return "fgc_google_experiment";
    }

    public static function getVarKeyType() {
        return array(0 => 'A', 1 => 'B', 2 => 'C');
    }

    public static function getTypeVarKey() {
        return array('A' => 0, 'B' => 1, 'C' => 2, 'D' => -1);
    }

    public static function getTypeSku() {
        return array('A' => 'REIZEA', 'B' => 'REIZEB', 'C' => 'REIZEC', 'D' => 'REIZE1');
    }

    public static function getSkuType() {
        return array('REIZEA' => 'A', 'REIZEB' => 'B', 'REIZEC' => 'C', 'REIZE1' => 'D');
    }

    public static function getTypeCategory() {
        return array('A' => 'Single Purchase A', 'B' => 'Single Purchase B', 'C' => 'Single Purchase C', 'D' => 'Single Purchase');
    }

    public static function getCategoryType() {
        return array('Single Purchase A' => 'A', 'Single Purchase B' => 'B', 'Single Purchase C' => 'C', 'Single Purchase' => 'D');
    }

    public static function init() {
        $user_id = get_current_user_id();

        if (isset($_COOKIE['GoogleExperimentCookie'])) {
            if ($user_id > 0) { // Khach hang da login
                if ($user_data = self::get_google_experiment_data_by_user_id($user_id)) { // khach hang da duoc cap nhat vao db
                    if ($_COOKIE['GoogleExperimentType'] == $user_data[0]->type) { // ko co su khac biet giua cookie va db
                    } else {
                        setcookie('GoogleExperimentType', $user_data[0]->type, time() + (10 * 365 * 24 * 60 * 60), '/');
                        setcookie('GoogleExperimentVarKey', $user_data[0]->var_key, time() + (10 * 365 * 24 * 60 * 60), '/');
                        $_SESSION['GoogleExperiment'] = array(
                            'cookie' => $_COOKIE['GoogleExperimentCookie'],
                            'user_id' => $user_id,
                            'var_key' => $user_data[0]->var_key,
                            'type' => $user_data[0]->type
                        );
                    }
                } else {// khach hang nay chua duoc cap nhat vao db, can cap nhat vao db
                    $type = self::get_type_of_user($user_id);
                    if ($type != NULL) {
                        $var_key = self::getTypeVarKey()[$type];
                    } else {
                        $type = $_SESSION['GoogleExperiment']['type'];
                        $var_key = $_SESSION['GoogleExperiment']['var_key'];
                    }
                    $reInsert = self::insert_new_user_to_google_experiment($_COOKIE['GoogleExperimentCookie'], $var_key, $type, $user_id);
//                    var_dump($reInsert);
//                    setcookie('GoogleExperimentType', $type, time() + (10 * 365 * 24 * 60 * 60), '/');
//                    setcookie('GoogleExperimentVarKey', $var_key, time() + (10 * 365 * 24 * 60 * 60), '/');
                    $_SESSION['GoogleExperiment'] = array(
                        'cookie' => $_COOKIE['GoogleExperimentCookie'],
                        'user_id' => $user_id,
                        'var_key' => $var_key,
                        'type' => $type
                    );
                }
            }
        } else { // chua co cookie, can su dung session va tao cookie
            if ($user_id > 0) { // Khach hang da login truoc khi tao plugin
                $type = self::get_type_of_user($user_id);
                $var_key = self::getTypeVarKey()[$type];
            } else { // Khach hang chua he login
                $var_key = self::get_variation_by_google_experiment();
                $type = self::getVarKeyType()[$var_key];
            }
            $google_experiment_code = self::generate_key_for_google_experiment(16);
            $_SESSION['GoogleExperiment'] = array(
                'cookie' => $google_experiment_code,
                'user_id' => $user_id,
                'var_key' => $var_key,
                'type' => $type
            );
            setcookie('GoogleExperimentCookie', $google_experiment_code, time() + (10 * 365 * 24 * 60 * 60), '/');
            setcookie('GoogleExperimentType', $type, time() + (10 * 365 * 24 * 60 * 60), '/');
            setcookie('GoogleExperimentVarKey', $var_key, time() + (10 * 365 * 24 * 60 * 60), '/');
        }
//        self::add_products_to_session();
    }

    public static function get_google_experiment_value($key) {
        if (isset($_COOKIE['GoogleExperimentCookie'])) {
            switch ($key):
                case 'cookie':
                    return $_COOKIE['GoogleExperimentCookie'];
                case 'type':
                    return $_COOKIE['GoogleExperimentType'];
                case 'var_key':
                    return $_COOKIE['GoogleExperimentVarKey'];
                default:
                    return '';
            endswitch;
        } else {
            switch ($key):
                case 'cookie':
                    return $_SESSION['GoogleExperiment']['cookie'];
                case 'type':
                    return $_SESSION['GoogleExperiment']['type'];
                case 'var_key':
                    return $_SESSION['GoogleExperiment']['var_key'];
                default:
                    return '';
            endswitch;
        }
    }

    public static function get_google_experiment_data_by_user_id($user_id = false) {
        if ($user_id && $user_id != '') {
            global $wpdb;
            $query = "SELECT * FROM " . $wpdb->prefix . self::getTableName() . " WHERE user_id = '" . $user_id . "'";
            $results = $wpdb->get_results($query);
            if (empty($results) || $results == NULL) { // The customer isn't created
                return false;
            } else { // The customer is created.
                return $results;
            }
        }
    }

    public static function insert_new_user_to_google_experiment($cookie = '', $var_key = -1, $type = '', $user_id = 0) {
        if ($cookie != '' && $var_key != -1 && $type != '' && $user_id != 0) {
            global $wpdb;
            $query = "INSERT INTO " . $wpdb->prefix . self::getTableName() . " (`cookie`, `var_key`, `user_id`,`type`) VALUES ('$cookie', '$var_key', '$user_id' , '$type');";
            return $wpdb->query($query);
        }
        return false;
    }

    public static function get_variation_by_google_experiment() {
//        return -1;

        $google_experiment_id = get_option('woocommerce_google_experiment_id');
        $experiment = new \UnitedPrototype\GoogleAnalytics\Experiment($google_experiment_id);
        return $variationKey = $experiment->chooseVariation();
    }

    public static function get_type_of_user($user_id) {
        global $wpdb;
        $select_get_orders = "SELECT * FROM `" . $wpdb->prefix . "postmeta` WHERE `meta_key` = '_customer_user' AND `meta_value` = " . $user_id;
        $results = $wpdb->get_results($select_get_orders);
        if (empty($results)) { // The customer doesn't have any order
            return false;
        } else { // The customer has order.
            return self::get_type_of_order($results[0]->post_id);
        }
    }

    public static function get_type_of_order($order_id) {
        $order = new WC_Order($order_id);
        $items = $order->get_items();

        foreach ($items as $key => $item) {
            $item_meta_array = $item['item_meta_array'];
            break;
        }
        foreach ($item_meta_array as $key => $value) {
            if ($value->key == '_variation_id') {
                $product_variation_id = $value->value;
                break;
            }
            if ($value->key == '_product_id') {
                $product_id = $value->value;
            }
        }
        if ($product_variation_id) {
            $product = new WC_Product($product_id);
            $sku = $product->get_sku();
            return self::getSkuType()[$sku];
        } else {
            $product = new WC_Product($product_id);
            $category = $product->get_categories();
            return self::getCategoryType()[$category];
        }
    }

    public static function generate_key_for_google_experiment($length) {
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    public static function get_products_for_slider($isSubscription) {
//        if (strpos($_SERVER["REQUEST_URI"], 'get-started')) {
//            echo $_SESSION['SubscriptionProductSlider'];
//        } else if (strpos($current_path, 'single-purchase')) {
//            echo $_SESSION['SingleProductsSlider'];
//        } else {
        $type = self::get_google_experiment_value('type');
        if ($isSubscription) {
            $sku = self::getTypeSku()[$type];
            echo self::get_subscription_product_for_slider($sku);
        } else {
            $category = self::getTypeCategory()[$type];
            echo self::get_single_products_for_slider($category);
        }
//        }
    }

    public static function add_products_to_session() {
        if (!isset($_SESSION['SubscriptionProductSlider']) || !isset($_SESSION['SingleProductsSlider'])) {
            $type = self::get_google_experiment_value('type');
            $sku = self::getTypeSku()[$type];
            $_SESSION['SubscriptionProductSlider'] = self::get_subscription_product_for_slider($sku);
            $category = self::getTypeCategory()[$type];
            $_SESSION['SingleProductsSlider'] = self::get_single_products_for_slider($category);
        }
    }

    public static function get_subscription_product_for_slider($sku) {
        return WC_Shortcodes::product_page(array('sku' => $sku));
    }

    public static function get_single_products_for_slider($category) {
        return WC_Shortcodes::product_category(array("category" => $category, "per_page" => "16", "orderby" => "price", "order" => "asc"));
    }

    public static function get_sku_for_get_started_page() {
        $type = self::get_google_experiment_value('type');
        return $sku = self::getTypeSku()[$type];
    }

    public static function get_var_key_for_get_started_page() {
        return self::get_google_experiment_value('var_key');
    }

    public static function get_cookie_for_get_started_page() {
        return self::get_google_experiment_value('cookie');
    }

}

function test_google_experiment() {
    if (isset($_REQUEST['testgoogleexperiment'])) {
//        Fgc_Google_Experiments::get_type_for_slider();
        echo WC_Shortcodes::product_page(array('sku' => 'REIZE1'));

        exit();
    }
}

add_action('init', 'test_google_experiment');
add_action('init', 'Fgc_Google_Experiments::init');

global $wpdb;
$google_experiment_db_version = '1.8';

$google_experiment_installed_ver = get_option("google_experiment_db_version");

if ($google_experiment_installed_ver != $google_experiment_db_version) {

    $table_name_new1 = $wpdb->prefix . 'fgc_google_experiment';

    $sql1 = "CREATE TABLE IF NOT EXISTS `$table_name_new1` (
  `id` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `cookie` VARCHAR(255)  NULL,
  `var_key` BIGINT(20) NULL,
  `user_id` BIGINT(20) NULL,
  `type` VARCHAR(255) NULL,
  PRIMARY KEY (`id`));";

    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta($sql1);

    update_option("google_experiment_db_version", $google_experiment_db_version);
}