first commit

This commit is contained in:
2024-07-15 11:28:08 +02:00
commit f52d538ea5
21891 changed files with 6161164 additions and 0 deletions

View File

@@ -0,0 +1,15 @@
<?php
if (!defined('ABSPATH')) exit; // Exit if accessed directly
register_activation_hook(__FILE__, 'onWooDiscountActivate');
register_deactivation_hook(__FILE__, 'onWooDiscountDeactivation');
if (!function_exists('onWooDiscountActivate')) {
function onWooDiscountActivate() {
// Dependency Check.
if (!in_array('woocommerce/woocommerce.php', get_option('active_plugins'))) wp_die('Please Install WooCommerce to Continue !');
}
}
if (!function_exists('onWooDiscountDeactivation')) {
function onWooDiscountDeactivation() {}
}

View File

@@ -0,0 +1,640 @@
<?php
if (!defined('ABSPATH')) exit; // Exit if accessed directly
include_once(WOO_DISCOUNT_DIR . '/helper/purchase.php');
include_once(WOO_DISCOUNT_DIR . '/helper/woo-function.php');
/**
* Class FlycartWooDiscountRulesGeneralHelper
*/
if ( ! class_exists( 'FlycartWooDiscountRulesGeneralHelper' ) ) {
class FlycartWooDiscountRulesGeneralHelper
{
public $isPro;
/**
* @var string
*/
public $default_page = 'pricing-rules';
/**
* To Process the View.
*
* @param $path
* @param $data
* @return bool|string
*/
public function processBaseView($path, $data)
{
if (!file_exists($path)) return false;
$this->checkPluginState();
$purchase = new FlycartWooDiscountRulesPurchase();
$suffix = $purchase->getSuffix();
ob_start();
$config = $data;
$pro = $this->isPro;
$category = $this->getCategoryList();
//$users = $this->getUserList();
FlycartWoocommerceVersion::wcVersion('3.0')? $flycart_wdr_woocommerce_version = 3: $flycart_wdr_woocommerce_version = 2;
$userRoles = $this->getUserRoles();
$userRoles['woo_discount_rules_guest'] = esc_html__('Guest', 'woo-discount-rules');
$countries = $this->getAllCountries();
if (!isset($config)) return false;
if (!isset($path) or is_null($config)) return false;
include($path);
$html = ob_get_contents();
ob_end_clean();
return $html;
}
public function checkPluginState()
{
$purchase = new FlycartWooDiscountRulesPurchase();
$this->isPro = $purchase->isPro();
return $this->isPro;
}
/**
* To Retrieve the list of Users.
*
* @return array
*/
public function getUserList()
{
$result = array();
foreach (get_users() as $user) {
$result[$user->ID] = '#' . $user->ID . ' ' . $user->user_email;
}
return $result;
}
/**
* To Retrieve the active tab.
*
* @return string
*/
public function getCurrentTab()
{
$postData = \FlycartInput\FInput::getInstance();
$tab = $this->default_page;
$empty_tab = $postData->get('tab', null);
if (!empty($empty_tab) && $postData->get('tab', '') != '') {
$tab = sanitize_text_field($postData->get('tab', ''));
}
return $tab;
}
/**
* To Get All Countries.
*
* @return array
*/
public function getAllCountries()
{
$countries = new WC_Countries();
if ($countries && is_array($countries->countries)) {
return array_merge(array(), $countries->countries);
} else {
return array();
}
}
/**
* To Get All Capabilities list.
*
* @return array
*/
public function getCapabilitiesList()
{
$capabilities = array();
if (class_exists('Groups_User') && class_exists('Groups_Wordpress') && function_exists('_groups_get_tablename')) {
global $wpdb;
$capability_table = _groups_get_tablename('capability');
$all_capabilities = $wpdb->get_results('SELECT capability FROM ' . $capability_table);
if ($all_capabilities) {
foreach ($all_capabilities as $capability) {
$capabilities[$capability->capability] = $capability->capability;
}
}
} else {
global $wp_roles;
if (!isset($wp_roles)) {
get_role('administrator');
}
$roles = $wp_roles->roles;
if (is_array($roles)) {
foreach ($roles as $rolename => $atts) {
if (isset($atts['capabilities']) && is_array($atts['capabilities'])) {
foreach ($atts['capabilities'] as $capability => $value) {
if (!in_array($capability, $capabilities)) {
$capabilities[$capability] = $capability;
}
}
}
}
}
}
return array_merge(array(), $capabilities);
}
/**
* @return array
*/
public function getUserRoles()
{
global $wp_roles;
if (!isset($wp_roles)) {
$wp_roles = new WP_Roles();
}
$roles = array();
foreach ($wp_roles->get_names() as $key => $wp_role ){
if(function_exists('translate_user_role')) $roles[$key] = translate_user_role($wp_role);
else $roles[$key] = $wp_role;
}
return $roles;
}
/**
* Get list of roles assigned to current user
*
* @access public
* @return array
*/
public static function getCurrentUserRoles()
{
$current_user = wp_get_current_user();
$userRoles = $current_user->roles;
if(get_current_user_id() == 0){
$userRoles[] = 'woo_discount_rules_guest';
}
return $userRoles;
}
/**
* @return array
*/
public function getCategoryList()
{
$result = array();
$taxonomies = apply_filters('woo_discount_rules_accepted_taxonomy_for_category', array('product_cat'));
$post_categories_raw = get_terms($taxonomies, array('hide_empty' => 0));
$post_categories_raw_count = count($post_categories_raw);
foreach ($post_categories_raw as $post_cat_key => $post_cat) {
$category_name = $post_cat->name;
if ($post_cat->parent) {
$parent_id = $post_cat->parent;
$has_parent = true;
// Make sure we don't have an infinite loop here (happens with some kind of "ghost" categories)
$found = false;
$i = 0;
while ($has_parent && ($i < $post_categories_raw_count || $found)) {
// Reset each time
$found = false;
$i = 0;
foreach ($post_categories_raw as $parent_post_cat_key => $parent_post_cat) {
$i++;
if ($parent_post_cat->term_id == $parent_id) {
$category_name = $parent_post_cat->name . ' &rarr; ' . $category_name;
$found = true;
if ($parent_post_cat->parent) {
$parent_id = $parent_post_cat->parent;
} else {
$has_parent = false;
}
break;
}
}
}
}
$result[$post_cat->term_id] = $category_name;
}
return $result;
}
/**
* Get Category by passing product ID or Product.
*
* @param $item
* @param bool $is_id
* @return array
*/
public static function getCategoryByPost($item, $is_id = false)
{
if ($is_id) {
$id = $item;
} else {
$id = FlycartWoocommerceProduct::get_id($item['data']);
}
$product = FlycartWoocommerceProduct::wc_get_product($id);
$categories = FlycartWoocommerceProduct::get_category_ids($product);
return $categories;
}
/**
* To Parsing the Array from String to Int.
*
* @param array $array
*/
public static function toInt(array &$array)
{
foreach ($array as $index => $item) {
$array[$index] = intval($item);
}
}
/**
* @param $html
* @return bool|mixed
*/
static function makeString($html)
{
if (is_null($html) || empty($html) || !isset($html)) return false;
$out = $html;
// This Process only helps, single level array.
if (is_array($html)) {
foreach ($html as $id => $value) {
self::escapeCode($value);
$html[$id] = $value;
}
return $out;
} else {
self::escapeCode($html);
return $html;
}
}
/**
* Re-Arrange the Index of Array to Make Usable.[2-D Array Only]
* @param $rules
*/
public static function reArrangeArray(&$rules)
{
$result = array();
foreach ($rules as $index => $item) {
foreach ($item as $id => $value) {
$result[$id] = $value;
}
}
$rules = $result;
}
/**
* @param $value
*/
static function escapeCode(&$value)
{
if(is_string($value)){
// Four Possible tags for PHP to Init.
$value = preg_replace(array('/^<\?php.*\?\>/', '/^<\%.*\%\>/', '/^<\?.*\?\>/', '/^<\?=.*\?\>/'), '', $value);
$value = self::delete_all_between('<?php', '?>', $value);
$value = self::delete_all_between('<?', '?>', $value);
$value = self::delete_all_between('<?=', '?>', $value);
$value = self::delete_all_between('<%', '%>', $value);
$value = str_replace(array('<?php', '<?', '<?=', '<%', '?>'), '', $value);
}
}
/**
* @param $beginning
* @param $end
* @param $string
* @return mixed
*/
static function delete_all_between($beginning, $end, $string)
{
if (!is_string($string)) return false;
$beginningPos = strpos($string, $beginning);
$endPos = strpos($string, $end);
if ($beginningPos === false || $endPos === false) {
return $string;
}
$textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);
return str_replace($textToDelete, '', $string);
}
/**
* To get slider content through curl
* */
public static function getSideBarContent(){
$html = '';
if(is_callable('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.flycart.org/updates/woo-discount-rules.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
$contents_decode = json_decode($contents);
if(isset($contents_decode['0']->promo_html)){
$html = $contents_decode['0']->promo_html;
}
}
return $html;
}
/**
* Check do the discount rules need to execute
* */
public static function doIHaveToRun(){
$status = true;
if(is_admin()){
$status = false;
}
if(defined('DOING_AJAX') && DOING_AJAX){
$status = true;
$postData = \FlycartInput\FInput::getInstance();
$action = $postData->get('action', '');
$form = $postData->get('from', '');
if($action == 'saveCartRule' || $action == 'savePriceRule'){
$status = false;
} else if(($action == 'UpdateStatus' || $action == 'RemoveRule') && ($form == 'cart-rules' || $form == 'pricing-rules')){
$status = false;
} else if($action == 'saveConfig' && $form == 'settings'){
$status = false;
}
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ){
$status = false;
}
return $status;
}
public static function haveToApplyTheRules(){
$status = true;
$config = new FlycartWooDiscountBase();
$do_not_run_while_have_third_party_coupon = $config->getConfigData('do_not_run_while_have_third_party_coupon', 0);
if($do_not_run_while_have_third_party_coupon){
$hasCoupon = self::hasCouponInCart();
if($hasCoupon){
$status = false;
}
}
return $status;
}
/**
* Check has coupon - not related to woo discount rules
* */
public static function hasCouponInCart(){
$result = false;
$cartRules = new FlycartWooDiscountRulesCartRules();
$coupon_code = $cartRules->getCouponCode();
$coupon_code = strtolower($coupon_code);
global $woocommerce;
if (!empty($woocommerce->cart->applied_coupons)) {
$appliedCoupons = $woocommerce->cart->applied_coupons;
if(in_array($coupon_code, $appliedCoupons)){
if(count($appliedCoupons) > 1){
$result = true;
}
} else {
$result = true;
}
}
return $result;
}
/**
* Get Current date and time based on Wordpress time zone
*
* @param string $date
* @return string
* */
public static function getCurrentDateAndTimeBasedOnTimeZone($date = ''){
if(empty($date)){
$current_date = new DateTime('now', new DateTimeZone('UTC'));
$date = $current_date->format('Y-m-d H:i:s');
}
$offset = get_option('gmt_offset');
if(empty($offset)){
$offset = 0;
}
//$time_zone = get_option('timezone_string');
return date("Y-m-d H:i:s", strtotime($date) + (3600 * $offset) );
}
/**
* Validate the start and end date
*
* @param string $date_from
* @param string $date_to
* @return boolean
* */
public static function validateDateAndTime($date_from, $date_to){
$valid = true;
$current_date = self::getCurrentDateAndTimeBasedOnTimeZone();
if($date_from != ''){
if(!(strtotime($date_from) <= strtotime($current_date))) $valid = false;
}
if($date_to != ''){
if(!(strtotime($date_to) >= strtotime($current_date))) $valid = false;
}
return $valid;
}
/**
* Reorder the rule if order id already exists
*
* @param int $id
* @param int $order_id
* @param string $post_type
* @return int
* */
public static function reOrderRuleIfExists($id, $order_id, $post_type){
$posts = get_posts(array('post_type' => $post_type, 'numberposts' => '-1', 'exclude' => array($id)));
$greaterId = $alreadyExists = 0;
if (!empty($posts) && count($posts) > 0) {
foreach ($posts as $index => $item) {
$orderId = get_post_meta($item->ID, 'rule_order', true);
if(!empty($orderId)){
if((int)$order_id == (int)$orderId){
$alreadyExists = 1;
}
if($orderId > $greaterId){
$greaterId = $orderId;
}
}
}
}
if($alreadyExists){
$greaterId++;
return $greaterId;
}
return $order_id;
}
/**
* Get all sub categories
* */
public static function getAllSubCategories($cat){
$taxonomies = apply_filters('woo_discount_rules_accepted_taxonomy_for_category', array('product_cat'));
$category_with_sub_cat = $cat;
foreach ($taxonomies as $taxonomy){
$category_with_sub = self::getAllSubCategoriesRecursive($cat, $taxonomy);
$category_with_sub_cat = array_merge($category_with_sub_cat, $category_with_sub);
}
return $category_with_sub_cat;
// $category_with_sub_cat = $cat;
// foreach($cat as $c) {
// $args = array('hierarchical' => 1,
// 'show_option_none' => '',
// 'hide_empty' => 0,
// 'parent' => $c,
// 'taxonomy' => 'product_cat');
// $categories = get_categories( $args );
// foreach($categories as $category) {
// //$category_with_sub_cat[] = $category->term_id;
// $category_with_sub_cat = array_merge($category_with_sub_cat, self::getAllSubCategories(array($category->term_id)));
// }
// }
// $category_with_sub_cat = array_unique($category_with_sub_cat);
//
// return $category_with_sub_cat;
}
/**
* Get all sub categories
* */
protected static function getAllSubCategoriesRecursive($cat, $taxonomy = 'product_cat'){
$category_with_sub_cat = $cat;
foreach($cat as $c) {
$args = array('hierarchical' => 1,
'show_option_none' => '',
'hide_empty' => 0,
'parent' => $c,
'taxonomy' => $taxonomy);
$categories = get_categories( $args );
foreach($categories as $category) {
//$category_with_sub_cat[] = $category->term_id;
$category_with_sub_cat = array_merge($category_with_sub_cat, self::getAllSubCategoriesRecursive(array($category->term_id), $taxonomy));
}
}
$category_with_sub_cat = array_unique($category_with_sub_cat);
return $category_with_sub_cat;
}
/**
* Docs HTML
* @param string $url
* @param string $utm_term
* @return string
* */
public static function docsURL($url, $utm_term){
$url_prefix = 'https://docs.flycart.org/woocommerce-discount-rules/';
$utm = '?utm_source=woo-discount-rules&utm_campaign=doc&utm_medium=text-click&';
$url = trim($url, '/');
return $url_prefix.$url.$utm.$utm_term;
}
/**
* Docs HTML
* @param string $url
* @param string $utm_term
* @return string
* */
public static function docsURLHTML($url, $utm_term, $additional_class = '', $text = ''){
if(!empty($additional_class)){
$additional_class = 'wdr_read_doc '.$additional_class;
} else {
$additional_class = 'wdr_read_doc';
}
if(empty($text)) $text = esc_html__('Read Docs', 'woo-discount-rules');
$html = '<a class="'.$additional_class.'" href="'.self::docsURL($url, $utm_term).'" target="_blank">'.$text.'</a>';
return $html;
}
/**
* Docs HTML
* @param string $url
* @param string $utm_term
* @return string
* */
public static function docsURLHTMLForDocumentation($url, $utm_term, $text, $description_text = '', $additional_class = ''){
if(!empty($additional_class)){
$additional_class = 'wdr_read_documentation '.$additional_class;
} else {
$additional_class = 'wdr_read_documentation';
}
$html = '<div class="wdr_read_documentation_con">';
$html .= '<a class="'.$additional_class.'" href="'.self::docsURL($url, $utm_term).'" target="_blank">'.$text.'</a>';
if(!empty($description_text))
$html .= '<p class="">'.$description_text.'</p>';
$html .= '</div>';
return $html;
}
/**
* Remove Coupon price in cart
* @param array $coupons
* */
public static function removeCouponPriceInCart($coupons = array()){
$config = new FlycartWooDiscountBase();
$remove_zero_coupon_price = $config->getConfigData('remove_zero_coupon_price', 0);
if($remove_zero_coupon_price){
$has_coupon = false;
$styles = '';
foreach ($coupons as $coupon){
$wc = WC();
if(!empty($wc) && !empty($wc->cart)){
if(method_exists($wc->cart, 'has_discount')){
if($wc->cart->has_discount($coupon)){
$coupon_amount = $wc->cart->get_coupon_discount_amount($coupon);
if($coupon_amount == 0){
$has_coupon = true;
$style = '.coupon-'.strtolower($coupon).' .amount{display: none}.coupon-'.strtolower($coupon).' td::first-letter{font-size: 0}';
$styles .= apply_filters('woo_discount_rules_apply_style_for_zero_price_coupon', $style, $coupon);
}
}
}
}
}
if($has_coupon){
if(!empty($styles)){
$is_ajax = is_ajax();
$wc_ajax = isset($_REQUEST['wc-ajax'])? $_REQUEST['wc-ajax']: false;
if(!$is_ajax || in_array($wc_ajax, array('apply_coupon'))){
echo "<style>".$styles."</style>";
}
}
}
}
}
}
}

View File

@@ -0,0 +1,310 @@
<?php
if (!defined('ABSPATH')) exit; // Exit if accessed directly
/**
* Class FlycartWooDiscountRulesPurchase
*/
if ( ! class_exists( 'FlycartWooDiscountRulesPurchase' ) ) {
class FlycartWooDiscountRulesPurchase
{
/**
* @var
*/
private $user;
private $slug='woo-discount-rules';
private $force_license_check=false;
public $pluginName;
public $siteURL = 'https://www.flycart.org/';
/**
* FlycartWooDiscountRulesPurchase constructor.
*/
public function __construct()
{
$this->pluginName = esc_html__('Woo Discount Rules', 'woo-discount-rules').' '.$this->getProText();
}
public function init()
{
$force_update = false;
// If a plugin has both a valid license and is using a CORE version then force update
if ( $this->isPro() === false && $this->validateLicenseKey() ) {
// can upgrade to PRO
$force_update = true;
}
$option_exists = (get_option($this->slug.'-force-update-pro', null) !== null);
if($option_exists){
update_option($this->slug.'-force-update-pro', $force_update);
}
else {
add_option($this->slug.'-force-update-pro', $force_update);
}
}
public function errorNoticeInAdminPages(){
$pro = $this->isPro();
$base = new FlycartWooDiscountBase();
$config = $base->getBaseConfig();
if (is_string($config)) $config = json_decode($config, true);
$htmlPrefix = '<div class="notice notice-warning"><p>';
$htmlSuffix = '</p></div>';
$hasMessage = 0;
if($pro){
if ( isset( $config['license_key'] ) && !empty($config['license_key']) ) {
$verifiedLicense = get_option('woo_discount_rules_verified_key', 0);
if(!$verifiedLicense){
$msg = esc_html__('The license key for ', 'woo-discount-rules').$this->pluginName.' '.esc_html__('seems invalid.', 'woo-discount-rules').' <a href="admin.php?page=woo_discount_rules&tab=settings">'.esc_html__('Please enter a valid license key', 'woo-discount-rules').'</a>. '.esc_html__('You can get it from', 'woo-discount-rules').' <a href="'.$this->siteURL.'">'.esc_html__('our website', 'woo-discount-rules').'</a>.';
$hasMessage = 1;
}
} else {
$msg = esc_html__('License key for the ', 'woo-discount-rules').$this->pluginName.' '.esc_html__('is not entered.', 'woo-discount-rules').' <a href="admin.php?page=woo_discount_rules&tab=settings">'.esc_html__('Please enter a valid license key', 'woo-discount-rules').'</a>. '.esc_html__('You can get it from', 'woo-discount-rules').' <a href="'.$this->siteURL.'">'.esc_html__('our website', 'woo-discount-rules').'</a>.';
$hasMessage = 1;
}
} else {
if ( isset( $config['license_key'] ) && !empty($config['license_key']) ) {
$verifiedLicense = get_option('woo_discount_rules_verified_key', 0);
if($verifiedLicense){
$msg = $this->pluginName.esc_html__(': You are using CORE version. Please Update to PRO version.', 'woo-discount-rules');
$hasMessage = 1;
}
}
}
if($hasMessage){
echo $htmlPrefix.$msg.$htmlSuffix;
}
}
/**
* @return bool
*/
public function isPro()
{
return true;
}
/**
* @return string
*/
public function getSuffix()
{
return esc_html__('-PRO-', 'woo-discount-rules');
}
/**
* @return string
*/
public function getProText()
{
if($this->isPro()){
return esc_html__('Pro', 'woo-discount-rules');
} else {
return esc_html__('Core', 'woo-discount-rules');
}
}
/**
* Hook to check and display updates below plugin in Admin Plugins section
* This plugin checks for license key validation and displays error notices
* @param string $plugin_file our plugin file
* @param string $plugin_data Plugin details
* @param string $status
* */
function woodisc_after_plugin_row ( $plugin_file, $plugin_data, $status ){
if( isset($plugin_data['TextDomain']) && $plugin_data['TextDomain'] == 'woo-discount-rules' ){
if ( ! $this->isPro() ) {
return;
}
// TODO: based on plugin_data display the update info text too. We can also make the subscription expiry chk in same request
// and display just the notice as a warning
$base = new FlycartWooDiscountBase();
$config = $base->getBaseConfig();
if (is_string($config)) $config = json_decode($config, true);
// if ( isset( $config['license_key'] ) && !empty($config['license_key']) ) {
// if (!$this->validateLicenseKey()) {
// $message = esc_html__('The license key for ', 'woo-discount-rules').$this->pluginName.' '.esc_html__('seems invalid.', 'woo-discount-rules').' <a href="admin.php?page=woo_discount_rules&tab=settings">'.esc_html__('Please enter a valid license key', 'woo-discount-rules').'</a>. '.esc_html__('You can get it from', 'woo-discount-rules').' <a href="'.$this->siteURL.'">'.esc_html__('our website', 'woo-discount-rules').'</a>.';
// }
// }else{
// $message = esc_html__('License key for the ', 'woo-discount-rules').$this->pluginName.' '.esc_html__('is not entered.', 'woo-discount-rules').' <a href="admin.php?page=woo_discount_rules&tab=settings">'.esc_html__('Please enter a valid license key', 'woo-discount-rules').'</a>. '.esc_html__('You can get it from', 'woo-discount-rules').' <a href="'.$this->siteURL.'">'.esc_html__('our website', 'woo-discount-rules').'</a>.';
// }
if (!empty($message)) {
// If an update is available ?
// prevent update if error occurs
echo '<tr>';
echo '<td> </td>';
echo '<td colspan="2"> <div class="notice-message error inline notice-error notice-alt"><p>'.$message.'</p></div></td>';
echo '</tr>';
}
}
}
/**
* Ajax request for license key validation
* */
public function forceValidateLicenseKey()
{
$postData = \FlycartInput\FInput::getInstance();
$request = $postData->getArray();
$params = array();
if (!isset($request['data'])) return false;
parse_str($request['data'], $params);
$this->force_license_check = true;
$resp = array();
if (empty($params['license_key'])) {
$resp['error'] = esc_html__('Please enter a valid license key', 'woo-discount-rules');
echo json_encode( $resp );
die();
}
$base = new FlycartWooDiscountBase();
$base->saveConfig(1);
if ( $this->validateLicenseKey() ) {
$resp['success'] = esc_html__('License key check : Passed.', 'woo-discount-rules');
// TODO: passed tick mark with a flag
} else {
// return an error
$resp['error'] = esc_html__('License key seems to be Invalid. Please enter a valid license key', 'woo-discount-rules');
}
echo json_encode( $resp );
die();
}
public function validateLicenseKey()
{
$run = $this->doIHaveToRunValidateLicense();
$already_check = get_option('woo_discount_rules_verified_key', 0);
$cache_license_check = ( $already_check == 1 ) ? true : false ;
if($run){
$base = new FlycartWooDiscountBase();
$config = $base->getBaseConfig();
if (is_string($config)) $config = json_decode($config, true);
if ( isset( $config['license_key'] ) && !empty($config['license_key']) ) {
// check the license
$license_url = $this->getUpdateURL('licensecheck');
$result = wp_remote_get( $license_url , array());
//Try to parse the json response
$status = $this->validateApiResponse($result);
$metadata = null;
update_option('woo_discount_rules_num_runs', get_option('woo_discount_rules_num_runs',1)+1);
if ( !is_wp_error($status) ){
$json = json_decode( $result['body'] );
if ( is_object($json) && isset($json->license_check)) {
update_option('woo_discount_rules_updated_time', time());
$verified = (bool)$json->license_check;
if($verified){
update_option('woo_discount_rules_verified_key', 1);
} else {
update_option('woo_discount_rules_verified_key', 0);
}
return $verified;
}
}
}
}
return $cache_license_check;
}
/**
* Check to run validate license check
* */
protected function doIHaveToRunValidateLicense()
{
$option_exists = (get_option('woo_discount_rules_updated_time', null) !== null);
if(!$option_exists){
add_option('woo_discount_rules_updated_time', 0);
add_option('woo_discount_rules_verified_key', 0);
add_option('woo_discount_rules_num_runs',0);
}
$lastRunUnix = get_option('woo_discount_rules_updated_time', 0);
$lastRunCount = get_option('woo_discount_rules_num_runs', 0);
$nextRunUnix = $lastRunUnix;
$hours = 12;
$countLimit = 8;
$nextRunUnix += $hours * 3600;
$now = time();
$time_factor = (bool) ($now >= $nextRunUnix );
$count_factor = (bool) ($lastRunCount < $countLimit);
if ($time_factor && !$count_factor) {
update_option('woo_discount_rules_num_runs', 0);
}
$already_valid_check = get_option('woo_discount_rules_verified_key', false);
return (($time_factor && $count_factor && $already_valid_check) || $this->force_license_check );
}
public function getUpdateURL($type='updatecheck')
{
$update_url = 'https://www.flycart.org/?wpaction='.$type.'&wpslug='.$this->slug;
$purchase_helper = new FlycartWooDiscountRulesPurchase();
$update_url .= '&pro='.(int)$purchase_helper->isPro();
$dlid = '';
$base = new FlycartWooDiscountBase();
$config = $base->getBaseConfig();
if (is_string($config)) $config = json_decode($config);
$dlid = isset($config->license_key)? $config->license_key: null;
if ( !empty($dlid) ) {
$update_url .= '&dlid='.$dlid;
}
return $update_url;
}
/**
* Check if $result is a successful update API response.
*
* @param array|WP_Error $result
* @return true|WP_Error
*/
protected function validateApiResponse($result) {
if ( is_wp_error($result) ) { /** @var WP_Error $result */
return new WP_Error($result->get_error_code(), 'WP HTTP Error: ' . $result->get_error_message());
}
if ( !isset($result['response']['code']) ) {
return new WP_Error(
'puc_no_response_code',
'wp_remote_get() returned an unexpected result.'
);
}
if ( $result['response']['code'] !== 200 ) {
return new WP_Error(
'puc_unexpected_response_code',
'HTTP response code is ' . $result['response']['code'] . ' (expected: 200)'
);
}
if ( empty($result['body']) ) {
return new WP_Error('puc_empty_response', 'The metadata file appears to be empty.');
}
return true;
}
}
}

View File

@@ -0,0 +1,640 @@
<?php
if (!defined('ABSPATH')) exit; // Exit if accessed directly
if(!class_exists('FlycartWoocommerceVersion')){
class FlycartWoocommerceVersion{
/**
* @param $version
* @return bool|mixed
*/
public static function wcVersion($version)
{
if (defined('WC_VERSION') && WC_VERSION) {
return version_compare(WC_VERSION, $version, '>=');
} else if (defined('WOOCOMMERCE_VERSION') && WOOCOMMERCE_VERSION) {
return version_compare(WOOCOMMERCE_VERSION, $version, '>=');
} else {
return false;
}
}
/**
* backwardCompatibilityStringToArray
* @param $data
* @return array
* */
public static function backwardCompatibilityStringToArray($data)
{
if(!empty($data) && !is_array($data)) $data = explode(',', $data);
return $data;
}
/**
* Is WooCommerce version 3x
* @return boolean
* */
public static function isWCVersion3x(){
return self::wcVersion('3.0');
}
}
}
if(!class_exists('FlycartWoocommerceProduct')){
class FlycartWoocommerceProduct{
/**
* Get WooCommerce product
*
* @access public
* @param int $product_id
* @return object
*/
public static function wc_get_product($product_id)
{
return FlycartWoocommerceVersion::wcVersion('2.2') ? wc_get_product($product_id) : get_product($product_id);
}
/**
* Get WooCommerce product format name
*
* @access public
* @param array $product
* @return int
*/
public static function get_formatted_name($product)
{
if(FlycartWoocommerceVersion::wcVersion('3.0') || method_exists($product , 'get_formatted_name')){
return $product->get_formatted_name();
} else {
$post_id = self::get_id($product);
return '#' . $post_id . ' ' . get_the_title($post_id);
}
}
/**
* Get WooCommerce product id
*
* @access public
* @param array $product
* @return int
*/
public static function get_id($product)
{
if(FlycartWoocommerceVersion::wcVersion('3.0') || method_exists($product , 'get_id')){
return $product->get_id();
} else {
$_product_id = $product->id;
if(isset($product->variation_id)) $_product_id = $product->variation_id;
return $_product_id;
}
}
/**
* Get WooCommerce price
*
* @access public
* @param float $amount
* @return int/float
*/
public static function wc_price($amount){
return FlycartWoocommerceVersion::wcVersion('2.1') ? wc_price($amount) : woocommerce_price($amount);
}
/**
* Get WooCommerce price html
*
* @access public
* @param array $product
* @return int/float
*/
public static function get_price_html($product){
return FlycartWoocommerceVersion::wcVersion('3.0') ? $product->get_price_html() : $product->get_price_html();
}
//get_price_html
/**
* Get WooCommerce product parent id
*
* @access public
* @param array $product
* @return int
*/
public static function get_parent_id($product){
if(FlycartWoocommerceVersion::wcVersion('3.0') || method_exists($product, 'get_parent_id')){
return $product->get_parent_id();
} else {
if(isset($product->parent) && !empty($product->parent)){
if(isset($product->parent->id)){
return $product->parent->id;
}
}
return $product->parent_id;
}
}
/**
* Get WooCommerce product children
*
* @access public
* @param array $product
* @return array
*/
public static function get_children($product){
if(FlycartWoocommerceVersion::wcVersion('3.0') || method_exists($product, 'get_children')){
return $product->get_children();
} else {
if(isset($product->children)){
return $product->children;
}
return '';
}
}
/**
* Get WooCommerce product price
*
* @access public
* @param array $product
* @return int/float
*/
public static function get_price($product){
return FlycartWoocommerceVersion::wcVersion('3.0') ? $product->get_price() : $product->price;
}
/**
* Get WooCommerce product regular price
*
* @access public
* @param array $product
* @return int/float
*/
public static function get_regular_price($product){
return FlycartWoocommerceVersion::wcVersion('3.0') ? $product->get_regular_price() : $product->regular_price;
}
/**
* Get WooCommerce product sale price
*
* @access public
* @param array $product
* @return int/float
*/
public static function get_sale_price($product){
return FlycartWoocommerceVersion::wcVersion('3.0') ? $product->get_sale_price() : $product->sale_price;
}
/**
* Set WooCommerce product price
*
* @access public
* @param array $product
*/
public static function set_price($product, $amount){
if(FlycartWoocommerceVersion::wcVersion('3.0')){
$product->set_price($amount);
} else {
$product->price = $amount;
}
}
/**
* Get product price including tax
*
* @access public
* @param object $product
* @param int $quantity
* @param float $price
* @return int
*/
public static function get_price_including_tax($product, $quantity = 1, $price = '')
{
return FlycartWoocommerceVersion::wcVersion('3.0') ? wc_get_price_including_tax($product, array('qty' => $quantity, 'price' => $price)) : $product->get_price_including_tax($quantity, $price);
}
/**
* Get product price excluding tax
*
* @access public
* @param object $product
* @param int $quantity
* @param float $price
* @return float
*/
public static function get_price_excluding_tax($product, $quantity = 1, $price = '')
{
return FlycartWoocommerceVersion::wcVersion('3.0') ? wc_get_price_excluding_tax($product, array('qty' => $quantity, 'price' => $price)) : $product->get_price_excluding_tax($quantity, $price);
}
//wc_get_price_excluding_tax
/**
* Get WooCommerce product title
*
* @access public
* @param array $product
* @return string
*/
public static function get_title($product){
if(FlycartWoocommerceVersion::wcVersion('3.0') || method_exists($product , 'get_title')){
return $product->get_title();
} else if(isset($product->title)){
return $product->title;
} else {
if(isset($product->post->post_title))
return $product->post->post_title;
}
return '';
}
/**
* Get WooCommerce product get_permalink
*
* @access public
* @param array $product
* @return string
*/
public static function get_permalink($product){
if(FlycartWoocommerceVersion::wcVersion('3.0') || method_exists($product , 'get_permalink')){
return $product->get_permalink();
} else if(isset($product->get_permalink) && $product->get_permalink != ''){
return $product->get_permalink;
} else {
return get_permalink(self::get_id($product));
}
}
/**
* Get WooCommerce product attributes
*
* @access public
* @param array $product
* @return array
*/
public static function get_attributes($product){
return FlycartWoocommerceVersion::wcVersion('3.0') ? $product->get_attributes() : $product->attributes;
}
/**
* Get WooCommerce get_variant_ids
*
* @access public
* @param int $product_id
* @return array
*/
public static function get_variant_ids($product_id)
{
$ids = array();
$productV = new WC_Product_Variable( $product_id );
$variations = $productV->get_available_variations();
if(!empty($variations))
foreach ($variations as $variation) {
$ids[] = $variation['variation_id'];
}
return $ids;
}
/**
* Get WooCommerce get_category_ids
*
* @access public
* @param object $product
* @return array
*/
public static function get_category_ids($product)
{
$parent = self::get_parent_id($product);
if($parent) $product = self::wc_get_product($parent);
$cat_id = array();
if(FlycartWoocommerceVersion::wcVersion('3.0') || method_exists($product, 'get_category_ids')){
$cat_id = $product->get_category_ids();
$cat_id = apply_filters('woo_discount_rules_load_additional_taxonomy', $cat_id, self::get_id($product));
} else {
$terms = get_the_terms ( self::get_id($product), 'product_cat' );
if(!empty($terms))
foreach ( $terms as $term ) {
$cat_id[] = $term->term_id;
}
}
return $cat_id;
}
/**
* Get category by id
*
* @access public
* @param int $category_id
* @return string
*/
public static function get_product_category_by_id( $category_id ) {
$term_name = '';
$taxonomies = apply_filters('woo_discount_rules_accepted_taxonomy_for_category', array('product_cat'));
foreach ($taxonomies as $taxonomy){
$term = get_term_by( 'id', $category_id, $taxonomy, 'ARRAY_A' );
if(!empty($term['name'])){
$term_name = $term['name'];
break;
}
}
return $term_name;
}
/*
* Get WooCommerce get product select box
*
* @access public
* @param object $products_list
* @param string $name
* @return string
* */
public static function getProductAjaxSelectBox($products_list, $name){
$html = '';
if(FlycartWoocommerceVersion::wcVersion('3.0')){
$html .= '<select class="wc-product-search" style="min-width: 250px" multiple="multiple" name="'.$name.'[]" data-placeholder="'.esc_attr__( 'Search for a product&hellip;', 'woocommerce' ).'" data-action="woocommerce_json_search_products_and_variations">';
if(!empty($products_list) && count($products_list))
foreach ( $products_list as $product_id ) {
$product = self::wc_get_product($product_id);
if ( is_object( $product ) ) {
$html .= '<option value="' . esc_attr( $product_id ) . '"' . selected( true, true, false ) . '>' . wp_kses_post( self::get_formatted_name($product) ) . '</option>';
}
}
$html .= '</select>';
} else {
$html .= '<input type="hidden" class="wc-product-search" style="width: 250px" data-multiple="true" name="'.$name.'" data-placeholder="'.esc_attr__( 'Search for a product&hellip;', 'woocommerce' ).'" data-action="woocommerce_json_search_products_and_variations" data-selected="';
$json_ids = array();
if(!empty($products_list)){
if(!is_array($products_list)) $products_list = explode(',', $products_list);
if(!empty($products_list) && count($products_list)){
foreach ( $products_list as $product_id ) {
$product = self::wc_get_product( $product_id );
if ( is_object( $product ) ) {
$json_ids[ $product_id ] = wp_kses_post( self::get_formatted_name($product) );
}
}
$html .= esc_attr( json_encode( $json_ids ) );
}
}
$html .= '" value="'.implode( ',', array_keys( $json_ids ) ).'" /> ';
}
return $html;
}
/*
* Get WooCommerce get product select box
*
* @access public
* @param object $users_list
* @param string $name
* @return string
* */
public static function getUserAjaxSelectBox($users_list, $name){
$html = '';
if(FlycartWoocommerceVersion::wcVersion('3.0')){
$html .= '<select class="wc-customer-search" style="width: 250px" multiple="multiple" name="'.$name.'[]" data-placeholder="'.esc_attr__( 'Search for a user&hellip;', 'woocommerce' ).'" data-allow_clear="true">';
if(!empty($users_list) && count($users_list))
foreach ( $users_list as $user_id ) {
$user = get_userdata($user_id);
if ( is_object( $user ) ) {
$formattedName = $user->user_firstname.' '.$user->user_lastname.' (#'.$user->ID.' - '. $user->user_email.')';
$html .= '<option value="' . esc_attr( $user_id ) . '"' . selected( true, true, false ) . '>' . wp_kses_post($formattedName) . '</option>';
}
}
$html .= '</select>';
} else {
$html .= '<input type="hidden" class="wc-customer-search" style="width: 250px" data-multiple="true" name="'.$name.'" data-placeholder="'.esc_attr__( 'Search for a user&hellip;', 'woocommerce' ).'" data-allow_clear="true" data-selected="';
$json_ids = array();
if(!empty($users_list)){
if(!is_array($users_list)) $users_list = explode(',', $users_list);
if(!empty($users_list) && count($users_list)){
foreach ( $users_list as $user_id ) {
$user = get_userdata($user_id);
if ( is_object( $user ) ) {
$formattedName = $user->user_firstname.' '.$user->user_lastname.' (#'.$user->ID.' - '. $user->user_email.')';
$json_ids[ $user_id ] = wp_kses_post( $formattedName );
}
}
$html .= esc_attr( json_encode( $json_ids ) );
}
}
$html .= '" value="'.implode( ',', array_keys( $json_ids ) ).'" /> ';
}
return $html;
}
}
}
if(!class_exists('FlycartWoocommerceCartProduct')){
class FlycartWoocommerceCart{
/**
* Get cart
*
* @access public
* @return array
*/
public static function get_cart()
{
if(!empty(WC()->cart)){
return WC()->cart->get_cart();
}
return array();
}
/**
* Remove cart item
*
* @access public
* @return boolean
*/
public static function remove_cart_item($_cart_item_key)
{
return WC()->cart->remove_cart_item( $_cart_item_key );
}
/**
* Add cart item
*
* @access public
* @param int $product_id
* @param int $quantity
* @param int $variation_id
* @param array $variation
* @param array $cart_item_data
* @return boolean
*/
public static function add_to_cart($product_id = 0, $quantity = 1, $variation_id = 0, $variation = array(), $cart_item_data = array())
{
if(FlycartWoocommerceVersion::wcVersion('3.0')){
return WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data);
} else {
ob_start();
$addToCart = WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data);
ob_end_flush();
return $addToCart;
}
}
/**
* set quantity
*
* @access public
* @param string $cart_item_key
* @param int $quantity
* @param boolean $refresh_totals
* @return boolean
*/
public static function set_quantity( $cart_item_key, $quantity = 1, $refresh_totals = true ){
return WC()->cart->set_quantity($cart_item_key, $quantity, $refresh_totals);
}
}
}
if(!class_exists('FlycartWoocommerceOrder')){
class FlycartWoocommerceOrder{
/**
* Get order id
*
* @access public
* @param object $order
* @return int
*/
public static function get_id($order)
{
FlycartWoocommerceVersion::wcVersion('3.0') ? $order->get_id() : $order->id;
}
/**
* Get WooCommerce order
*
* @access public
* @param int $order_id
* @return object
*/
public static function wc_get_order($order_id)
{
return FlycartWoocommerceVersion::wcVersion('2.2') ? wc_get_order($order_id) : new WC_Order($order_id);
}
/**
* Get order total
*
* @access public
* @param object $order
* @return float
*/
public static function get_total($order)
{
return FlycartWoocommerceVersion::wcVersion('3.0') ? $order->get_total() : $order->order_total;
}
/**
* Get order billing_email
*
* @access public
* @param object $order
* @return float
*/
public static function get_billing_email($order)
{
return FlycartWoocommerceVersion::wcVersion('3.0') ? $order->get_billing_email() : $order->billing_email;
}
/**
* Get order billing city
*
* @access public
* @param object $order
* @return float
*/
public static function get_billing_city($order)
{
return FlycartWoocommerceVersion::wcVersion('3.0') ? $order->get_billing_city() : $order->billing_city;
}
/**
* Get order shipping state
*
* @access public
* @param object $order
* @return float
*/
public static function get_shipping_state($order)
{
return FlycartWoocommerceVersion::wcVersion('3.0') ? $order->get_shipping_state() : $order->shipping_state;
}
/**
* Get order shipping city
*
* @access public
* @param object $order
* @return float
*/
public static function get_shipping_city($order)
{
return FlycartWoocommerceVersion::wcVersion('3.0') ? $order->get_shipping_city() : $order->shipping_city;
}
/**
* Get order product ids
*
* @access public
* @param object $order
* @return array
*/
public static function get_product_ids($order)
{
$items = $order->get_items();
$productIds = array();
if(!empty($items)){
foreach ($items as $item){
$product_id = FlycartWoocommerceVersion::wcVersion('3.0') ? $item->get_product_id() : $item['product_id'];
$variant_id = FlycartWoocommerceVersion::wcVersion('3.0') ? $item->get_variation_id() : $item['variation_id'];
if($variant_id){
$productIds[] = $variant_id;
} else {
$productIds[] = $product_id;
}
}
}
return $productIds;
}
}
}
if(!class_exists('FlycartWoocommerceCoupon')){
class FlycartWoocommerceCoupon{
/**
* Get WooCommerce Coupon
*
* @access public
* @param int $coupon_code
* @return object
*/
public static function wc_get_coupon($coupon_code)
{
return new WC_Coupon($coupon_code);
}
/**
* Get Coupon individual_use
*
* @access public
* @param object $coupon
* @return boolean
*/
public static function get_individual_use($coupon)
{
return FlycartWoocommerceVersion::wcVersion('3.0') ? $coupon->get_individual_use() : $coupon->individual_use;
}
}
}