woocommerce-override.php 15.1 KB
<?php
/**
 * Plugin Name: Fgc WooCommerce Subscriptions Override
 * Plugin URI: http://fgc.vn
 * Description: Override path template.
 * Author: Hoang Bien.
 * 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 Subscriptions
 * @author		Hoang Bien
 * @since		1.0
 */
//do_action( 'woocommerce_before_template_part', $template_name, $template_path, $located, $args );
add_filter('wc_get_template', 'fgc_woocommerce_before_template_part', 99, 5);

function fgc_woocommerce_before_template_part($located, $template_name, $args, $template_path, $default_path) {
    $pathTheme = get_stylesheet_directory();
    $lenght = strpos($located, '/woocommerce-subscriptions/');
    if ($lenght) {
        $substring = substr($located, $lenght);
        $newLocated = $pathTheme . $substring;
        if (file_exists($newLocated)) {
            $located = $newLocated;
        }
    }
    return $located;
}

add_filter('woocommerce_credit_card_form_fields', 'fgcCreditCardForm', 10, 2);

function fgcCreditCardForm($cc_fields, $payment_id) {
    $months = '<select data-placeholder="" name="' . ( $args['fields_have_names'] ? $payment_id . '-card-expiry' : '' ) . '" id="' . esc_attr($payment_id) . '-card-expiry-month" class="month_select wc-credit-card-form-card-expiry" ><option></option>';
    for ($m = 1; $m <= 12; $m++) {
        $months .= '  <option value="' . $m . '">' . $m . '</option>';
    }
    $months .= '</select>';
    $current_year = date("Y");
    $years = '<select data-placeholder="" name="' . ( $args['fields_have_names'] ? $payment_id . '-card-expiry' : '' ) . '" id="' . esc_attr($payment_id) . '-card-expiry-year" class="year_select wc-credit-card-form-card-expiry" ><option></option>';
    for ($y = $current_year; $y <= ($current_year + 10); $y++) {
        $years .= '  <option value="' . $y . '">' . $y . '</option>';
    }
    $years .= '</select>';
    $cc_fields = array(
        'card-number-field' => '<p class="form-row form-row-wide">
				<label for="' . esc_attr($payment_id) . '-card-number">' . __('Card Number', 'woocommerce') . ' <span class="required">*</span></label>
				<input id="' . esc_attr($payment_id) . '-card-number" class="input-text wc-credit-card-form-card-number" type="text" maxlength="20" autocomplete="off" placeholder="Card Number" name="' . ( $args['fields_have_names'] ? $payment_id . '-card-number' : '' ) . '" />
			</p>
                        <div class="clearfix"></div>
                        <div class="despayment font14 robotoitalic">The digits on the front of the card</div>
                        ',
        'card-expiry-field' => '
            <input id="' . esc_attr($payment_id) . '-card-expiry" class="input-text wc-credit-card-form-card-expiry tvcard_expriry" type="text" autocomplete="off" placeholder="' . esc_attr__('MM / YY', 'woocommerce') . '" name="' . ( $args['fields_have_names'] ? $payment_id . '-card-expiry' : '' ) . '" />
            <p class="form-row form-row-first">
				<label for="' . esc_attr($payment_id) . '-card-expiry">' . __('Expiry (MM/YY)', 'woocommerce') . ' <span class="required">*</span></label>
				' . $months . '
			</p>
                        <p class="form-row form-row-last">
				<label for="' . esc_attr($payment_id) . '-card-expiry">' . __('Expiry (MM/YY)', 'woocommerce') . ' <span class="required">*</span></label>
				' . $years . '
			</p>
                        <div class="clearfix"></div>
                        <div class="despayment font14 robotoitalic">Expiration date - month and year</div>',
        'card-cvc-field' => '<p class="form-row form-row-first">
				<label for="' . esc_attr($payment_id) . '-card-cvc">' . __('Card Code', 'woocommerce') . ' <span class="required">*</span></label>
				<input id="' . esc_attr($payment_id) . '-card-cvc" class="input-text wc-credit-card-form-card-cvc" type="text" autocomplete="off" placeholder="' . esc_attr__('CCV', 'woocommerce') . '" name="' . ( $args['fields_have_names'] ? $payment_id . '-card-cvc' : '' ) . '" />
			</p>
                        <p class="form-row form-row-last">
                            <span class="icon_csv">&nbsp;</span>
                        </p>
                        <div class="clearfix"></div>
                        <div class="despayment font14 robotoitalic">It’s the last 3 digits on the back (or the 4 on the front for AMEX)</div>
                        <div class="clear"></div>'
    );
    return $cc_fields;
}

/**
 * Add the field to the checkout
 */
//add_action( 'woocommerce_before_order_notes', 'fgcCustomCheckoutField' );
//
//function fgcCustomCheckoutField( $checkout ) {
//    $checked = $checkout->get_value( 'authorise' ) ? $checkout->get_value( 'authorise' ) : 1;
//    woocommerce_form_field( 'authorise', array(
//        'type'          => 'checkbox',
////        'class'         => array('input-checkbox'),
//        'label'         => __('Authorise to leave package'),
//        ), $checked);
//
//}

/**
 * Save the order meta with field value
 */
add_action('woocommerce_checkout_update_order_meta', 'fgc_checkout_field_update_order_meta');

function fgc_checkout_field_update_order_meta($order_id) {
    if (!empty($_POST['authorise'])) {
        update_post_meta($order_id, 'authorise', sanitize_text_field($_POST['authorise']));
    }
}

/**
 * Display field value on the order edit page
 */
add_action('woocommerce_admin_order_data_after_shipping_address', 'fgc_checkout_field_display_admin_order_meta', 10, 1);

function fgc_checkout_field_display_admin_order_meta($order) {
    $customer_comment = $order->customer_message;
    if (get_post_meta($order->id, 'authorise', true) == 1) {
        echo '<p><strong>' . __('Authorise to leave package') . '.</strong> ';
        if ($customer_comment != '') {
            echo $customer_comment;
        }
        echo '</p>';
    }
}

//
//function fgc_set_re_active_subscription($order_id, $user_id, $subscription_key) {
//    if ($subscription_key == '') {
//        return FALSE;
//    }
//    $set_re_active_time = (int) get_post_meta($order_id, '_set_on_re_active')[0];
//    if (fgc_check_time_to_run_cron($set_re_active_time)) {
//        if(WC_Subscriptions_Manager::activate_subscription($user_id, $subscription_key)){
//        delete_post_meta($order_id, '_set_on_re_active', $set_re_active_time);//
//        }
//    }
//}
//
//function fgc_check_time_to_run_cron($time_to_cal) {
//    if ($time_to_cal == 0) {
//        return FALSE;
//    }
//    $time_cron_run = current_time('timestamp', true);
//    $time_cron_run = 1463101261;
//    $time_to_check = $time_to_cal - $time_cron_run;
//    if ($time_to_check < 0) {
//        return FALSE;
//    }
//    if (($time_to_check / (60 * 60 * 24)) < 1) {
//        return TRUE;
//    }
//    return FALSE;
//}
//
//function fgcRunCronjob() {
//    if (isset($_GET['action'])) {
//        if ($_GET['action'] == 'take-month-off') {
//            $users = get_users_of_blog();
//            foreach ($users as $user) {
//                $user_id = $user->ID;
//                $subscriptions = WC_Subscriptions_Manager::get_users_subscriptions($user_id);
//                $this_subscription = '';
//                $subscription_key = '';
//                foreach ($subscriptions as $subscription) {
//                    if ($subscription['status'] == 'on-hold') {
//                        $subscription_key = WC_Subscriptions_Manager::get_subscription_key($subscription['order_id'], $subscription['product_id']);
//                        fgc_set_re_active_subscription($subscription['order_id'], $user_id, $subscription_key);
////                    break;
//                    }
//                }
//            }
//        }
//    }
//}
//
//add_action('plugins_loaded', 'fgcRunCronjob', 200);
//
//function fgc_check_cart_checkout() {
//    if (strpos($_SERVER["REQUEST_URI"], 'my-account') !== false) {
//        if (count(WC()->cart->cart_contents) == 0) {
//            wp_safe_redirect('checkout');
//        }
//    }
//}
//add_action('wp_loaded', 'fgc_check_cart_checkout', 9);


function fgc_cancelled_subscription() {
    if (isset($_GET['cancelled_subscription']) && isset($_GET['subscription_id']) && isset($_GET['_wpnonce'])) {
        global $wpdb;
        $user_id = get_current_user_id();
        $subscription = wcs_get_subscription($_GET['subscription_id']);
        $new_status = 'cancelled';

        if (WCS_User_Change_Status_Handler::validate_request($user_id, $subscription, $new_status, $_GET['_wpnonce'])) {
            WC_Subscriptions_Manager::cancel_subscriptions_for_order($subscription->order->id);
            $query_sql = " SELECT * FROM $wpdb->posts WHERE post_parent = " . $subscription->order->id . " ORDER BY post_date DESC ";
            $query_result = $wpdb->get_results($query_sql, OBJECT);
            wp_update_post(array(
                'ID' => $query_result[0]->ID,
                'post_status' => 'wc-cancelled'
            ));
            update_post_meta($query_result[0]->ID, '_schedule_end', date('Y-m-d h:i:s', time()));
            @WC_Subscriptions_Email::send_cancelled_email($subscription);
            wp_safe_redirect($subscription->get_view_order_url());
            exit();
        }
    }
}

add_action('wp_loaded', 'fgc_cancelled_subscription', 99);

function save_info_before_checkout() {
    if (isset($_GET['save_info_before_checkout']) && isset($_GET['delivery_instructions']) && isset($_GET['card_number'])) {
        global $wpdb;
        $user_id = get_current_user_id();
//        $subscription = wcs_get_subscription($_GET['subscription_id']);
//        $new_status = 'cancelled';
//
//        if (WCS_User_Change_Status_Handler::validate_request($user_id, $subscription, $new_status, $_GET['_wpnonce'])) {
//            WC_Subscriptions_Manager::cancel_subscriptions_for_order($subscription->order->id);
//            $query_sql = " SELECT * FROM $wpdb->posts WHERE post_parent = " . $subscription->order->id . " ORDER BY post_date DESC ";
//            $query_result = $wpdb->get_results($query_sql, OBJECT);
//            wp_update_post(array(
//                'ID' => $query_result[0]->ID,
//                'post_status' => 'wc-cancelled'
//            ));
//            update_post_meta($query_result[0]->ID, '_schedule_end', date('Y-m-d h:i:s', time()));
//
//            wp_safe_redirect($subscription->get_view_order_url());
//            exit();
//        }
    }
}

add_action('wp_loaded', 'save_info_before_checkout', 99);

function clear_cart_after_logout() {
    if (strpos($request_uri, '/checkout') !== false) {
        if (function_exists('WC')) {
            WC()->cart->empty_cart();
        }

        $array_cookies = array('stripe-card-number', 'stripe-card-cvc', 'order_comments', 'billing_first_name', 'billing_last_name', 'billing_address_1', 'billing_address_2', 'billing_city', 'billing_postcode', 'billing_email', 'billing_phone', 'shipping_first_name', 'shipping_last_name', 'shipping_address_1', 'shipping_address_2', 'shipping_city', 'shipping_postcode', 'stripe-card-expiry-month', 'billing_first_name', 'stripe-card-expiry-year', 'stripe-card-expiry-month', 'stripe-card-expiry-year');
        foreach ($array_cookies as $value) {
            setcookie($value, '', 1, '/checkout');
        }
    }
}

add_action('wp_logout', 'clear_cart_after_logout');

add_action('wp_loaded', 'load_shipping_address');

function load_shipping_address() {
    if (isset($_REQUEST['load_address_form']) && $_REQUEST['load_address_form'] == 'shipping_address') {
        $load_address = 'shipping';
        $page_title = ( $load_address === 'billing' ) ? __('Billing Address', 'woocommerce') : __('Shipping Address', 'woocommerce');
        $current_user = wp_get_current_user();
        $load_address = sanitize_key($load_address);

        $address = WC()->countries->get_address_fields(get_user_meta(get_current_user_id(), $load_address . '_country', true), $load_address . '_');

// Enqueue scripts
        wp_enqueue_script('wc-country-select');
        wp_enqueue_script('wc-address-i18n');

// Prepare values
        foreach ($address as $key => $field) {

            $value = get_user_meta(get_current_user_id(), $key, true);

            if (!$value) {
                switch ($key) {
                    case 'billing_email' :
                    case 'shipping_email' :
                        $value = $current_user->user_email;
                        break;
                    case 'billing_country' :
                    case 'shipping_country' :
                        $value = WC()->countries->get_base_country();
                        break;
                    case 'billing_state' :
                    case 'shipping_state' :
//                        $value = WC()->countries->get_base_state();
                        break;
                }
            }

            $address[$key]['value'] = apply_filters('woocommerce_my_account_edit_address_field_value', $value, $key, $load_address);
        }
        ?>
        <form method="post" class="form_shippiing_address nomargin" action="/?fgcSaveAddress&type=shipping">

            <h3 class="hide"><?php echo apply_filters('woocommerce_my_account_edit_address_title', $page_title); ?></h3>

            <?php do_action("woocommerce_before_edit_address_form_{$load_address}"); ?>

            <?php
            if ($address['shipping_state']['value'] == '') {
                $address['shipping_city']['class'][0] = 'form-row-first';
            }
            foreach ($address as $key => $field) :
                woocommerce_form_field($key, $field, !empty($_POST[$key]) ? wc_clean($_POST[$key]) : $field['value'] );
            endforeach;
            ?>

            <?php do_action("woocommerce_after_edit_address_form_{$load_address}"); ?>

            <p>
                <button type="submit" class="button" name="save_address" ><?php esc_attr_e('Save Address', 'woocommerce'); ?> <i class="hide ajax-loader small animate-spin"></i></button>
                    <?php wp_nonce_field('woocommerce-edit_address'); ?>
                <input type="hidden" name="action" value="edit_address" />
            </p>

        </form>
        <?php
        exit();
    }
}

add_action('wp_loaded', 'fgc_redirect_view_subcription_to_myaccount');

function fgc_redirect_view_subcription_to_myaccount() {
    $uri = explode('/', $_SERVER["REQUEST_URI"]);
    if ($uri[1] == 'my-account' && $uri[2] == 'view-subscription') {
        $subscription_id = $uri[3];
        global $wpdb;
        $subscription = wcs_get_subscription($subscription_id);
        if ($subscription->post->post_status != 'wc-cancelled') {
            wp_redirect(home_url() . '/my-account');
            exit();
        }
    }
}