Advertisement
Guest User

class-wpneo-frontend-hook

a guest
Jun 25th, 2018
429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 21.13 KB | None | 0 0
  1. <?php
  2. if ( ! defined( 'ABSPATH' ) ) {
  3.     exit; // Exit if accessed directly
  4. }
  5.  
  6. if (! class_exists('WPNEO_Frontend_Hook')) {
  7.  
  8.     class WPNEO_Frontend_Hook {
  9.  
  10.         protected static $_instance;
  11.         public static function instance() {
  12.             if ( is_null( self::$_instance ) ) {
  13.                 self::$_instance = new self();
  14.             }
  15.             return self::$_instance;
  16.         }
  17.  
  18.         public function __construct() {
  19.             add_action('woocommerce_after_shop_loop_item',      array($this, 'after_item_title_data')); // Woocommerce Backed User
  20.             add_filter( 'woocommerce_product_tabs',             array($this, 'product_backed_user_tab') );
  21.             add_filter( 'woocommerce_is_sold_individually',     array($this, 'wpneo_wc_remove_crowdfunding_quantity_fields'), 10, 2 ); //Remove quantity and force item 1 cart per checkout if product is crowdfunding
  22.             if ( 'true' == get_option('hide_cf_campaign_from_shop_page')){
  23.                 add_action('woocommerce_product_query',         array($this, 'limit_show_cf_campaign_in_shop')); //Filter product query
  24.             }
  25.         }
  26.  
  27.         /**
  28.          * @return string
  29.          *
  30.          *
  31.          */
  32.         public function after_item_title_data(){
  33.             global $woocommerce,$post,$wpdb;
  34.             $product = wc_get_product($post->ID);
  35.  
  36.             if($product->get_type() != 'crowdfunding'){
  37.                 return '';
  38.             }
  39.  
  40.             $funding_goal   = $this->totalGoalByCampaign($post->ID);
  41.             $wpneo_country  = get_post_meta( $post->ID, 'wpneo_country', true);
  42.             $total_sales    = get_post_meta( $post->ID, 'total_sales', true );
  43.             $enddate        = get_post_meta( $post->ID, '_nf_duration_end', true );
  44.  
  45.             //Get Country name from WooCommerce
  46.             $countries_obj  = new WC_Countries();
  47.             $countries      = $countries_obj->__get('countries');
  48.  
  49.             $country_name = '';
  50.             if ($wpneo_country){
  51.                 $country_name = $countries[$wpneo_country];
  52.             }
  53.  
  54.             $raised = 0;
  55.             $total_raised = $this->totalFundRaisedByCampaign();
  56.             if ($total_raised){
  57.                 $raised = $total_raised;
  58.             }
  59.  
  60.             //Get order sales value by product
  61.             $sales_value_by_product = 0;
  62.  
  63.             $days_remaining = apply_filters('date_expired_msg', __('Date expired', 'wp-crowdfunding'));
  64.             if ($this->dateRemaining()){
  65.                 $days_remaining = apply_filters('date_remaining_msg', __($this->dateRemaining().' days remaining', 'wp-crowdfunding'));
  66.             }
  67.  
  68.             $html = '';
  69.             $html .= '<div class="crowdfunding_wrapper">';
  70.  
  71.             if ($country_name) {
  72.                 $html .= '<div class="wpneo_location">';
  73.                 $html .= '<p class="wpneo_thumb_text">'. __('Location: ', 'wp-crowdfunding') . $country_name.'</p>';
  74.                 $html .= '</div>';
  75.             }
  76.  
  77.             if ($funding_goal) {
  78.                 $html .= '<div class="funding_goal">';
  79.                 $html .= '<p class="wpneo_thumb_text">'.__('Funding Goal: ', 'wp-crowdfunding') . '<span class="price amount">'.wc_price($funding_goal).'</span>'. '</p>';
  80.                 $html .= '</div>';
  81.             }
  82.  
  83.             if ($total_sales) {
  84.                 $html .= '<div class="total_raised">';
  85.                 $html .= '<p class="wpneo_thumb_text">'.__('Raised: ', 'wp-crowdfunding') . '<span class="price amount">' . wc_price( $raised).'</span>'. '</p>';
  86.                 $html .= '</div>';
  87.             }
  88.  
  89.             if ($total_sales && $funding_goal) {
  90.                 $percent = $this->getFundRaisedPercent();
  91.                 $html .= '<div class="percent_funded">';
  92.                 $html .= '<p class="wpneo_thumb_text">'.__('Funded percent: ', 'wp-crowdfunding') . '<span class="price amount">' . $percent.' %</span>'. '</p>';
  93.                 $html .= '</div>';
  94.             }
  95.  
  96.             if ($total_sales) {
  97.                 $html .= '<div class="days_remaining">';
  98.                 $html .= '<p class="wpneo_thumb_text">'.$days_remaining. '</p>';
  99.                 $html .= '</div>';
  100.             }
  101.  
  102.             $html .= '</div>';
  103.             echo apply_filters('woocommerce_product_cf_meta_data',$html);
  104.         }
  105.  
  106.         public function dateRemaining($post_id = 0){
  107.  
  108.             global $post;
  109.             if ($post_id == 0) $post_id = $post->ID;
  110.             $enddate = get_post_meta( $post_id, '_nf_duration_end', true );
  111.  
  112.             if ((strtotime($enddate) + 86399) > time()) {
  113.                 $diff = strtotime($enddate) - time();
  114.                 $temp = $diff / 86400; // 60 sec/min*60 min/hr*24 hr/day=86400 sec/day
  115.                 $days = floor($temp);
  116.                 return $days >= 1 ? $days : 1; //Return min one days, though if remain only 1 min
  117.             }
  118.             return 0;
  119.         }
  120.  
  121.         public function is_reach_target_goal(){
  122.             global $post;
  123.             $funding_goal = get_post_meta($post->ID, '_nf_funding_goal' , true);
  124.             $raised = $this->totalFundRaisedByCampaign();
  125.             if ( $raised >= $funding_goal ){
  126.                 return true;
  127.             }else{
  128.                 return false;
  129.             }
  130.         }
  131.  
  132.         public function campaignValid(){
  133.             global $post;
  134.  
  135.             $_nf_duration_start = get_post_meta($post->ID, '_nf_duration_start', true);
  136.  
  137.             if ($_nf_duration_start){
  138.                 if (strtotime($_nf_duration_start) > time()){
  139.                     return false;
  140.                 }
  141.             }
  142.  
  143.             $campaign_end_method = get_post_meta($post->ID, 'wpneo_campaign_end_method' , true);
  144.  
  145.             switch ($campaign_end_method){
  146.  
  147.                 case 'target_goal':
  148.                     if ($this->is_reach_target_goal()){
  149.                         return false;
  150.                     }else{
  151.                         return true;
  152.                     }
  153.                     break;
  154.  
  155.                 case 'target_date':
  156.                     if ($this->dateRemaining()){
  157.                         return true;
  158.                     }else{
  159.                         return false;
  160.                     }
  161.                     break;
  162.  
  163.                 case 'target_goal_and_date':
  164.                     if ( ! $this->is_reach_target_goal()) {
  165.                         return true;
  166.                     }
  167.                     if ( $this->dateRemaining()) {
  168.                         return true;
  169.                     }
  170.                     return false;
  171.                     break;
  172.  
  173.                 case 'never_end':
  174.                     return true;
  175.                     break;
  176.  
  177.                 default :
  178.                     return false;
  179.             }
  180.         }
  181.  
  182.         /**
  183.          * @param $campaign_id
  184.          * @return mixed
  185.          *
  186.          * Get Total funded amount by a campaign
  187.          */
  188.  
  189.         public function totalFundRaisedByCampaign($campaign_id = 0){
  190.  
  191.             global $wpdb, $post;
  192.  
  193.             if ($campaign_id == 0){
  194.                 $campaign_id = $post->ID;
  195.             }
  196.  
  197.             $query ="SELECT
  198.                        SUM(ltoim.meta_value) as total_sales_amount
  199.                    FROM
  200.                        {$wpdb->prefix}woocommerce_order_itemmeta woim
  201.                     LEFT JOIN
  202.                        {$wpdb->prefix}woocommerce_order_items oi ON woim.order_item_id = oi.order_item_id
  203.                     LEFT JOIN
  204.                        {$wpdb->prefix}posts wpposts ON order_id = wpposts.ID
  205.                     LEFT JOIN
  206.                        {$wpdb->prefix}woocommerce_order_itemmeta ltoim ON ltoim.order_item_id = oi.order_item_id AND ltoim.meta_key = '_line_total'
  207.                     WHERE
  208.                        woim.meta_key = '_product_id' AND woim.meta_value = %d AND wpposts.post_status = 'wc-completed';";
  209.  
  210.             $wp_sql = $wpdb->get_row($wpdb->prepare( $query, $campaign_id ));
  211.  
  212.             return $wp_sql->total_sales_amount;
  213.         }
  214.  
  215.         /**
  216.          * @param $campaign_id
  217.          * @return mixed
  218.          *
  219.          * Get total campaign goal
  220.          */
  221.         public function totalGoalByCampaign($campaign_id){
  222.             return $funding_goal = get_post_meta( $campaign_id, '_nf_funding_goal', true );
  223.         }
  224.  
  225.         /**
  226.          * @param $campaign_id
  227.          * @return int|string
  228.          *
  229.          * Return total percent funded for a campaign
  230.          */
  231.         public function getFundRaisedPercent($campaign_id = 0) {
  232.  
  233.             global $post;
  234.             $percent = 0;
  235.             if ($campaign_id == 0){
  236.                 $campaign_id = $post->ID;
  237.             }
  238.             $total = $this->totalFundRaisedByCampaign($campaign_id);
  239.             $goal = $this->totalGoalByCampaign($campaign_id);
  240.             if ($total > 0 && $goal > 0  ) {
  241.                 $percent = number_format($total / $goal * 100, 2, '.', '');
  242.             }
  243.             return $percent;
  244.         }
  245.  
  246.         public function getFundRaisedPercentFormat(){
  247.             return $this->getFundRaisedPercent().'%';
  248.         }
  249.  
  250.         public function wpneo_wc_remove_crowdfunding_quantity_fields( $return, $product ) {
  251.             if ($product->get_type() == 'crowdfunding'){
  252.                 return true;
  253.             }
  254.         }
  255.  
  256.         /**
  257.          * @param $tabs
  258.          * @return string
  259.          *
  260.          * Return Reward Tab Data
  261.          */
  262.         public function product_backed_user_tab( $tabs ) {
  263.  
  264.             global $post;
  265.             $product = wc_get_product($post->ID);
  266.             if($product->get_type() =='crowdfunding'){
  267.                 // Adds the new tab
  268.                 $tabs['backed_user'] = array(
  269.                     'title'     => __( 'Backed User', 'neo-croudfunding' ),
  270.                     'priority'  => 51,
  271.                     'callback'  => array($this, 'product_backed_user_tab_content')
  272.                 );
  273.             }
  274.             return $tabs;
  275.         }
  276.  
  277.         public function product_backed_user_tab_content( $post_id ){
  278.  
  279.             global $post, $wpdb;
  280.             $html       = '';
  281.             $prefix     = $wpdb->prefix;
  282.             $product_id = $post->ID;
  283.             $data_array = $this->ordersIDlistPerCampaign();
  284.  
  285.             $args = array(
  286.                 'post_type'     => 'shop_order',
  287.                 'post_status'   => array('wc-completed','wc-on-hold'),
  288.                 'post__in'      => $data_array
  289.             );
  290.             $the_query = new WP_Query( $args );
  291.  
  292.             if ( $the_query->have_posts() ) :
  293.  
  294.                 $html .= '  <table class="shop_table backed_user_table">
  295.  
  296.                    <thead>
  297.                        <tr>
  298.                            <th>'.__('ID', 'wp-crowdfunding').'</th>
  299.                            <th>'.__('Name', 'wp-crowdfunding').'</th>
  300.                            <th>'.__('Email', 'wp-crowdfunding').'</th>
  301.                            <th>'.__('Amount', 'wp-crowdfunding').'</th>
  302.                        </tr>
  303.                    </thead>';
  304.                 ?>
  305.  
  306.  
  307.                 <?php
  308.                 while ( $the_query->have_posts() ) : $the_query->the_post();
  309.  
  310.                     $html .= '<tr>';
  311.  
  312.                     $html .= '<td>'.get_the_ID().'</td>';
  313.  
  314.                     $html .= '<td>'. get_post_meta( get_the_ID() , "_billing_first_name",true ).' '.get_post_meta( get_the_ID() , "_billing_last_name",true ).'</td>';
  315.  
  316.                     $html .= '<td>'. get_post_meta( get_the_ID() , "_billing_email",true ).'</td>';
  317.                     $post_id = get_the_ID();
  318.  
  319.                     $price = $wpdb->get_results("SELECT order_meta.meta_value FROM `{$prefix}woocommerce_order_itemmeta` AS order_meta, `{$prefix}woocommerce_order_items` AS order_item WHERE order_meta.order_item_id IN (SELECT order_item.order_item_id FROM `{$prefix}woocommerce_order_items` as order_item WHERE order_item.order_id = {$post_id}) AND order_meta.order_item_id IN (SELECT meta.order_item_id FROM `{$prefix}woocommerce_order_itemmeta` AS meta WHERE meta.meta_key='_product_id' AND meta.meta_value={$product_id} ) AND order_meta.meta_key='_line_total' GROUP BY order_meta.meta_id");
  320.  
  321.                     $price = json_decode( json_encode($price), true );
  322.  
  323.                     if(isset($price[0]['meta_value'])){
  324.                         $html .= '<td>'. wc_price($price[0]['meta_value']).'</td>';
  325.                     }
  326.                     $html .= '</tr>';
  327.  
  328.                 endwhile;
  329.                 wp_reset_postdata();
  330.  
  331.                 $html .= '</table>';
  332.                 ?>
  333.  
  334.  
  335.  
  336.                 <?php
  337.             else :
  338.                 $html .= __( 'Sorry, no posts matched your criteria.','wp-crowdfunding' );
  339.             endif;
  340.  
  341.             echo $html;
  342.         }
  343.  
  344.         public function ordersIDlistPerCampaign(){
  345.  
  346.             global $wpdb, $post;
  347.             $prefix = $wpdb->prefix;
  348.             $post_id = $post->ID;
  349.  
  350.             $query ="SELECT
  351.                        order_id
  352.                    FROM
  353.                        {$wpdb->prefix}woocommerce_order_itemmeta woim
  354.                     LEFT JOIN
  355.                        {$wpdb->prefix}woocommerce_order_items oi ON woim.order_item_id = oi.order_item_id
  356.                     WHERE
  357.                        meta_key = '_product_id' AND meta_value = %d
  358.                     GROUP BY
  359.                        order_id ORDER BY order_id DESC ;";
  360.             $order_ids = $wpdb->get_col( $wpdb->prepare( $query, $post_id ) );
  361.  
  362.             return $order_ids;
  363.         }
  364.  
  365.         public function totalBackers(){
  366.             $wpneo_orders = $this->getCustomersByProductQuery();
  367.             if ($wpneo_orders){
  368.                 return $wpneo_orders->post_count;
  369.             }else{
  370.                 return 0;
  371.             }
  372.         }
  373.  
  374.         public function getCustomersByProductQuery(){
  375.             $order_ids = $this->ordersIDlistPerCampaign();
  376.             if( $order_ids ) {
  377.                 $args = array(
  378.                     'post_type'         =>'shop_order',
  379.                     'post__in'          => $order_ids,
  380.                     'posts_per_page'    =>  999,
  381.                     'order'             => 'ASC',
  382.                     'post_status'       => 'wc-completed',
  383.                 );
  384.                 $wpneo_orders = new WP_Query( $args );
  385.                 return $wpneo_orders;
  386.             }
  387.             return false;
  388.         }
  389.  
  390.         function getCustomersByProduct(){
  391.             $order_ids = $this->ordersIDlistPerCampaign();
  392.             return $order_ids;
  393.         }
  394.  
  395.         public function wpneo_campaign_update_status(){
  396.  
  397.             global $post;
  398.             $saved_campaign_update = get_post_meta($post->ID, 'wpneo_campaign_updates', true);
  399.             $saved_campaign_update_a = json_decode($saved_campaign_update, true);
  400.  
  401.             $html = '';
  402.             $html .="<div class='campaign_update_wrapper'>";
  403.  
  404.             $html .= '<h3>';
  405.             $html .= apply_filters( 'wpneo_campaign_update_title', __( $post->post_title.'\'s Update','wp-crowdfunding' ) );
  406.             $html .= '</h3>';
  407.  
  408.             if (is_array($saved_campaign_update_a)) {
  409.                 if ( count($saved_campaign_update_a) > 0 ) {
  410.                     $html .= '<table class="table table-border">';
  411.                     $html .= '<tr>';
  412.                     foreach ($saved_campaign_update_a[0] as $k => $v) {
  413.                         $html .= '<th>';
  414.                         $html .= ucfirst($k);
  415.                         $html .= '</th>';
  416.                     }
  417.                     $html .= '</tr>';
  418.  
  419.                     foreach ($saved_campaign_update_a as $key => $value) {
  420.                         $html .= '<tr>';
  421.                         foreach ($value as $k => $v) {
  422.                             $html .= '<td>';
  423.                             $html .= $v;
  424.                             $html .= '</td>';
  425.                         }
  426.                         $html .= '</tr>';
  427.                     }
  428.                     $html .= '</table>';
  429.                 }
  430.             }
  431.             $html .= "</div>";
  432.  
  433.             echo $html;
  434.         }
  435.  
  436.         function limit_show_cf_campaign_in_shop($wp_query){
  437.             $tax_query = array(
  438.                 array(
  439.                     'taxonomy' => 'product_type',
  440.                     'field'    => 'slug',
  441.                     'terms' => array(
  442.                         'crowdfunding'
  443.                     ),
  444.                     'operator' => 'NOT IN'
  445.                 )
  446.             );
  447.             $wp_query->set( 'tax_query', $tax_query );
  448.             return $wp_query;
  449.         }
  450.  
  451.         function limit_word_text($text, $limit) {
  452.             if(!function_exists('mb_str_word_count')){
  453.                 function mb_str_word_count($string, $format = 0, $charlist = '[]') {
  454.                     mb_internal_encoding( 'UTF-8');
  455.                     mb_regex_encoding( 'UTF-8');
  456.                     $words = mb_split('[^\x{0600}-\x{06FF}]', $string);
  457.                     switch ($format) {
  458.                         case 0:
  459.                             return count($words);
  460.                             break;
  461.                         case 1:
  462.                         case 2:
  463.                             return $words;
  464.                             break;
  465.                         default:
  466.                             return $words;
  467.                             break;
  468.                     }
  469.                 }
  470.             }
  471.             if (mb_str_word_count($text, 0) > $limit) {
  472.                 $words  = mb_str_word_count($text, 2);
  473.                 $pos    = array_keys($words);
  474.                 $text   = mb_substr($text, 0, $pos[$limit]) . '...';
  475.             }
  476.             return $text;
  477.         }
  478.  
  479.  
  480.         public function is_campaign_started($post_id = 0){
  481.             global $post;
  482.  
  483.             if ( ! $post_id){
  484.                 $post_id = $post->ID;
  485.             }
  486.  
  487.             $_nf_duration_start = get_post_meta($post_id, '_nf_duration_start', true);
  488.  
  489.             if ($_nf_duration_start){
  490.                 if (strtotime($_nf_duration_start) > time()){
  491.                     return false;
  492.                 }
  493.             }
  494.  
  495.             return true;
  496.         }
  497.  
  498.  
  499.         public function campaign_start_countdown($post_id = 0){
  500.             global $post;
  501.  
  502.             if ( ! $post_id){
  503.                 $post_id = $post->ID;
  504.             }
  505.             $_nf_duration_start = get_post_meta($post->ID, '_nf_duration_start', true);
  506.  
  507.             ?>
  508.             <p class="wpcf-start-campaign-countdown"> <?php _e('Campaign will be started within') ?> </p>
  509.             <div id="wpcf-campaign-countdown"></div>
  510.  
  511.             <?php
  512.                 $daycount   = get_post_meta( get_the_ID(), '_nf_duration_start', true );
  513.                 $dateval    = date("Y/m/d", strtotime($daycount));
  514.             ?>
  515.  
  516.             <script type="text/javascript">
  517.                 // Set the date we're counting down to
  518.                 var wpcfCountDownDate = new Date("<?php echo $dateval; ?>").getTime();
  519.                 // Update the count down every 1 second
  520.                 var wpcfIntervalE = setInterval(function() {
  521.                     // Get towpcfDays date and time
  522.                     var now = new Date().getTime();
  523.  
  524.                     // Find the wpcfDistance between now an the count down date
  525.                     var wpcfDistance = wpcfCountDownDate - now;
  526.  
  527.                     // Time calculations for wpcfDays, wpcfHours, wpcfMinutes and wpcfSeconds
  528.                     var wpcfDays = Math.floor(wpcfDistance / (1000 * 60 * 60 * 24));
  529.                     var wpcfHours = Math.floor((wpcfDistance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  530.                     var wpcfMinutes = Math.floor((wpcfDistance % (1000 * 60 * 60)) / (1000 * 60));
  531.                     var wpcfSeconds = Math.floor((wpcfDistance % (1000 * 60)) / 1000);
  532.  
  533.                     // Display the result in the element with id="wpcf-campaign-countdown"
  534.                     document.getElementById("wpcf-campaign-countdown").innerHTML =
  535.                     '<span>'+ wpcfDays +'</span>' + "d " +
  536.                         "<span>" + wpcfHours +
  537.                         "h </span> <span> " + wpcfMinutes + "m </span> <span> " + wpcfSeconds + "s </span> ";
  538.  
  539.                     // If the count down is finished, write some text
  540.                     if (wpcfDistance < 0) {
  541.                         // clearInterval(wpcfIntervalE);
  542.                         // document.getElementById("wpcf-campaign-countdown").innerHTML = "";
  543.                     }
  544.  
  545.                 }, 1000);
  546.             </script>
  547.  
  548.             <?php
  549.         }
  550.  
  551.         public function days_until_launch($post_id = 0){
  552.             global $post;
  553.  
  554.             if ( ! $post_id){
  555.                 $post_id = $post->ID;
  556.             }
  557.             $_nf_duration_start = get_post_meta($post->ID, '_nf_duration_start', true);
  558.  
  559.             if ((strtotime($_nf_duration_start) ) > time()) {
  560.                 $diff = strtotime($_nf_duration_start) - time();
  561.                 $temp = $diff / 86400; // 60 sec/min*60 min/hr*24 hr/day=86400 sec/day
  562.                 $days = floor($temp);
  563.                 return $days >= 1 ? $days : 1; //Return min one days, though if remain only 1 min
  564.             }
  565.  
  566.             return 0;
  567.         }
  568.  
  569.     }
  570. }
  571.  
  572. //Run this class now
  573. WPNEO_Frontend_Hook::instance();
  574. function WPNEOCF(){
  575.     return WPNEO_Frontend_Hook::instance();
  576. }
  577. $GLOBALS['WPNEOCF'] = WPNEOCF();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement