<?php
/**
 * Plugin Name: Simple Business Directory - Pro
 * Plugin URI: https://www.quantumcloud.com/
 * Description: Simple Business is an advanced solution to all link page or partners page needs on your website. This innovative Link Directory PlugIn allows admin to create list of website links with website logo and a short description.
 * Version: 14.8.3
 * Author: QuantumCloud
 * Author URI: https://www.quantumcloud.com/
 * Requires at least: 4.6
 * Tested up to: 5.2
 * Text Domain: qc-pd
 * Domain Path: /lang/
 * License: GPL2
 */

defined('ABSPATH') or die("No direct script access!");

global $pd_plugin_version;

$pd_plugin_version = '14.7.9';

if( defined('ABSPATH') && !function_exists('wp_get_current_user') ){
    
	//include_once(ABSPATH . 'wp-includes/pluggable.php');
}

//Custom Constants
define('QCSBD_URL', plugin_dir_url(__FILE__));
define('QCSBD_IMG_URL', QCSBD_URL . "/assets/images");
define('QCSBD_ASSETS_URL', QCSBD_URL . "assets");
define('QCSBD_DIR_MOD', dirname(__FILE__)."/modules");
define('QCSBD_DIR_CAT', dirname(__FILE__)."/category_template");
define('QCSBD_DIR', dirname(__FILE__));

define('QCSBD_INC_DIR', QCSBD_DIR . "/inc");
define('OCSBD_TPL_DIR', QCSBD_DIR . "/templates");
define('OCSBD_UPLOAD_DIR', QCSBD_DIR . "/uploads");
define('OCSBD_TPL_URL', QCSBD_URL . "templates");
define('OCSBD_UPLOAD_URL', QCSBD_URL . "uploads");
//Helper function to extract domain
function qcpd_get_domain($url){

  $pieces = parse_url($url);
  $domain = isset($pieces['host']) ? $pieces['host'] : '';
  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
    return $regs['domain'];
  }
  return false;
}

//Include files and scripts
require_once( 'plugin-upgrader/plugin-upgrader.php' );
require_once( 'qcpd-helper-functions.php' );
add_filter( 'ot_theme_mode', '__return_false', 999 );
require_once( 'option-tree/ot-loader.php' );
require_once( 'qc-pd-setting-option.php' );
require_once( 'qc-pd-directory-post-type.php' );
require_once( 'qc-pd-directory-assets.php' );

require_once( 'qc-pd-directory-shortcodes.php' );
require_once( 'qc-pd-sorting-support.php' );

require_once( 'qc-pd-ajax-stuffs.php' );

require_once( 'qc-pd-ajax-bookmark.php' );

require_once( 'qcpd-widgets.php' );
require_once( 'qcpd-custom-hooks.php' );

require_once( 'qc-pd-directory-import.php' );
require_once( 'qcpd-shortcode-generator.php' );
require_once( 'qcpd-fa-modal.php' );
require_once( 'qcpd-all-category.php' );
require_once( 'qc-pd-directory-multipage.php' );
require_once( 'qc-pd-item-assign.php' );
require_once( 'qc-pd-help-license.php' );

require_once( QCSBD_DIR_MOD.'/registration/class.sbd_registration.php' );
require_once( QCSBD_DIR_MOD.'/login/class.sbd_login.php' );
require_once( QCSBD_DIR_MOD.'/dashboard/class.sbd_dashboard.php' );
require_once( QCSBD_DIR_MOD.'/dashboard/class.free_listing_restriction.php' );
require_once( QCSBD_DIR_MOD.'/captcha/simple-php-captcha.php' );
//Module for user approval
require_once( QCSBD_DIR_MOD.'/approval/pd-user-approve.php' );
//Package module integration

require_once( QCSBD_DIR_MOD.'/package/class.pd_package.php' );

require_once( QCSBD_DIR_MOD.'/package/class.pd_order_list.php' );
require_once( QCSBD_DIR_MOD.'/category/pd_category_image.php' );
require_once( QCSBD_DIR_MOD.'/claim_listing/class.sbd_claim_order_list.php' );

require_once( QCSBD_DIR_MOD.'/claim_listing/class.sbd_claim_listing_page.php' );
require_once( QCSBD_DIR_MOD.'/large_list/manage_large_list.php' );

register_activation_hook( __FILE__, 'qcld_pd_activate');

require_once( 'qc-support-promo-page/class-qc-support-promo-page.php' );

require_once( 'modules/addons/addons.php' );

//Remove Slug Edit Box
add_action('admin_head', 'qcpd_remove_post_slug_editing');



function qcpd_remove_post_slug_editing()
{
	$option = pd_ot_get_option('pd_global_font');
	//print_r($option);exit;
    global $post_type;

    if ($post_type == 'pd') {
        echo "<style>#edit-slug-box {display:none;} #qcpd_upvote_count, #qcpd_verified , #qcpd_entry_time, #qcpd_timelaps,#qcpd_paid, #qcpd_is_bookmarked { display: none; }</style>";
    }

}


//adding session
/*
add_action( 'template_redirect', function() {
	@session_start();
});
*/
//Check if outbound click tracking is ON
add_action('wp_head', 'qcpd_add_outbound_click_tracking_script');

function qcpd_add_outbound_click_tracking_script()
{

  if(!function_exists('wp_get_current_user')) {
    include(ABSPATH . "wp-includes/pluggable.php");
  }
  if(is_user_logged_in()){
    $current_user = wp_get_current_user();
    if(in_array('administrator',$current_user->roles)){
      return;
    }
  }

    $outbound_conf = pd_ot_get_option( 'pd_enable_click_tracking' );

    if ( isset($outbound_conf) && $outbound_conf == 'on' ) {

        ?>
        <script>

function _gaLt(event) {

        /* If GA is blocked or not loaded, or not main|middle|touch click then don't track */
        if (!ga.hasOwnProperty("loaded") || ga.loaded != true || (event.which != 1 && event.which != 2)) {
            return;
        }

        var el = event.srcElement || event.target;

        /* Loop up the DOM tree through parent elements if clicked element is not a link (eg: an image inside a link) */
        while (el && (typeof el.tagName == 'undefined' || el.tagName.toLowerCase() != 'a' || !el.href)) {
            el = el.parentNode;
        }

        /* if a link with valid href has been clicked */
        if (el && el.href) {

            var link = el.href;

            /* Only if it is an external link */
            if (link.indexOf(location.host) == -1 && !link.match(/^javascript\:/i)) {

                /* Is actual target set and not _(self|parent|top)? */
                var target = (el.target && !el.target.match(/^_(self|parent|top)$/i)) ? el.target : false;

                /* Assume a target if Ctrl|shift|meta-click */
                if (event.ctrlKey || event.shiftKey || event.metaKey || event.which == 2) {
                    target = "_blank";
                }

                var hbrun = false; // tracker has not yet run

                /* HitCallback to open link in same window after tracker */
                var hitBack = function() {
                    /* run once only */
                    if (hbrun) return;
                    hbrun = true;
                    window.location.href = link;
                };

                if (target) { /* If target opens a new window then just track */
                    ga(
                        "send", "event", "Outgoing Links", link,
                        document.location.pathname + document.location.search
                    );
                } else { /* Prevent standard click, track then open */
                    event.preventDefault ? event.preventDefault() : event.returnValue = !1;
                    /* send event with callback */
                    ga(
                        "send", "event", "Outgoing Links", link,
                        document.location.pathname + document.location.search, {
                            "hitCallback": hitBack
                        }
                    );

                    /* Run hitCallback again if GA takes longer than 1 second */
                    setTimeout(hitBack, 1000);
                }
            }
        }
    }

    var _w = window;
    /* Use "click" if touchscreen device, else "mousedown" */
    var _gaLtEvt = ("ontouchstart" in _w) ? "click" : "mousedown";
    /* Attach the event to all clicks in the document after page has loaded */
    _w.addEventListener ? _w.addEventListener("load", function() {document.body.addEventListener(_gaLtEvt, _gaLt, !1)}, !1)
        : _w.attachEvent && _w.attachEvent("onload", function() {document.body.attachEvent("on" + _gaLtEvt, _gaLt)});
        </script>
        <?php

    }
}

/**
 * Submenu filter function. Tested with Wordpress 4.1.1
 * Sort and order submenu positions to match your custom order.
 *
 * @author Hendrik Schuster <contact@deviantdev.com>
 */
function qcpd_order_index_catalog_menu_page( $menu_ord )
{

  global $submenu;

  // Enable the next line to see a specific menu and it's order positions
  //echo '<pre>'; print_r( $submenu['edit.php?post_type=pd'] ); echo '</pre>'; exit();

  // Sort the menu according to your preferences
  //Original order was 5,11,12,13,14,15

  //print_r($submenu);exit;
  
  
  $arr = array();
  if( current_user_can( 'edit_posts' ) ):
    if(isset($submenu['edit.php?post_type=pd'][5]))
        $arr[] = $submenu['edit.php?post_type=pd'][5];
    if(isset($submenu['edit.php?post_type=pd'][10]))
        $arr[] = $submenu['edit.php?post_type=pd'][10];
    if(isset($submenu['edit.php?post_type=pd'][15]))
        $arr[] = $submenu['edit.php?post_type=pd'][15];
    if(isset($submenu['edit.php?post_type=pd'][16]))
        $arr[] = $submenu['edit.php?post_type=pd'][16];
    if(isset($submenu['edit.php?post_type=pd'][17]))
        $arr[] = $submenu['edit.php?post_type=pd'][17];
    if(isset($submenu['edit.php?post_type=pd'][18]))
        $arr[] = $submenu['edit.php?post_type=pd'][18];
    if(isset($submenu['edit.php?post_type=pd'][20]))
        $arr[] = $submenu['edit.php?post_type=pd'][20];
    if(isset($submenu['edit.php?post_type=pd'][21]))
        $arr[] = $submenu['edit.php?post_type=pd'][21];
    if(isset($submenu['edit.php?post_type=pd'][23]))
        $arr[] = $submenu['edit.php?post_type=pd'][23];
    if(isset($submenu['edit.php?post_type=pd'][22]))
        $arr[] = $submenu['edit.php?post_type=pd'][22];
        // $arr[] = $submenu['edit.php?post_type=pd'][24];
    if(isset($submenu['edit.php?post_type=pd'][25]))
        $arr[] = $submenu['edit.php?post_type=pd'][25];
    if(isset($submenu['edit.php?post_type=pd'][26]))
        $arr[] = $submenu['edit.php?post_type=pd'][26];
    if(isset($submenu['edit.php?post_type=pd'][27]))
        $arr[] = $submenu['edit.php?post_type=pd'][27];
    if(isset($submenu['edit.php?post_type=pd'][251]))
        $arr[] = $submenu['edit.php?post_type=pd'][251];
    if(isset($submenu['edit.php?post_type=pd'][19]))
        $arr[] = $submenu['edit.php?post_type=pd'][19];
  //$arr[] = $submenu['edit.php?post_type=pd'][250];
  endif;  

  $submenu['edit.php?post_type=pd'] = $arr;

  return $submenu;

}


// add the filter to wordpress
add_filter( 'custom_menu_order', 'qcpd_order_index_catalog_menu_page' );

	/*
	* Register Activation hook
	*/
	 function qcld_pd_activate(){

    /* Free version replace code.
     */
    $free = array( 'phone-directory/qc-op-directory-main.php' );
    $all_plugins = get_plugins();
    foreach( $all_plugins as $plugin => $plugin_details ){
        if( in_array( $plugin, $free ) ){
            if( is_plugin_active( $plugin ) ){
                if( deactivate_plugins( array( $plugin ) ) ){
                    delete_plugins( array( $plugin ) );
                }
            } else {
                delete_plugins( array( $plugin ) );
            }
        }
    }
    /**
     * Free version replace code End.
     */
		global $wpdb;
		if(!get_option('sbd_generate_info')){
			update_option('sbd_generate_info', 1);
			update_option('sbd_subtitle', 1);
			update_option('sbd_long_description', 1);
			update_option('sbd_phone', 1);
			update_option('sbd_short_address', 1);
			update_option('sbd_full_address', 1);
			update_option('sbd_latitude', 1);
			update_option('sbd_longitude', 1);
			update_option('sbd_linkedin', 1);
			update_option('sbd_twitter', 1);
			update_option('sbd_email', 1);
			update_option('sbd_business_hour', 1);
			update_option('sbd_yelp', 1);
			update_option('sbd_facebook', 1);
			update_option('sbd_tags', 1);
			update_option('sbd_image', 1);
			update_option('sbd_no_follow', 1);
			update_option('sbd_custom1', 1);
			update_option('sbd_custom2', 1);
			update_option('sbd_custom3', 1);
			update_option('sbd_custom4', 1);
			update_option('sbd_custom5', 1);
		}
		
		
		$collate = '';

		if ( $wpdb->has_cap( 'collation' ) ) {

			if ( ! empty( $wpdb->charset ) ) {

				$collate .= "DEFAULT CHARACTER SET $wpdb->charset";
			}
			if ( ! empty( $wpdb->collate ) ) {

				$collate .= " COLLATE $wpdb->collate";

			}
		}

		$table             = $wpdb->prefix.'pd_user_entry';
		$table1             = $wpdb->prefix.'pd_package';
		$table2             = $wpdb->prefix.'pd_package_purchased';
		$table3             = $wpdb->prefix.'sbd_claim_configuration';
		$table4             = $wpdb->prefix.'sbd_claim_purchase';

		$sql_sliders_Table = "
		CREATE TABLE IF NOT EXISTS `$table` (
		  `id` int(11) NOT NULL AUTO_INCREMENT,
		  `item_title` varchar(150) NOT NULL,
		  `item_link` varchar(150) NOT NULL,
		  `item_phone` varchar(150) NOT NULL,
		  `item_subtitle` text NOT NULL,
		  `location` text NOT NULL,
		  `full_address` text NOT NULL,
		  `email` varchar(150) NOT NULL,
		  `twitter` varchar(250) NOT NULL,
		  `linkedin` varchar(250) NOT NULL,
		  `facebook` varchar(250) NOT NULL,
		  `yelp` varchar(250) NOT NULL,
		  `business_hour` varchar(250) NOT NULL,
		  `category` varchar(50) NOT NULL,
		  `pd_list` varchar(100) NOT NULL,
		  `latitude` varchar(100) NOT NULL,
		  `longitude` varchar(100) NOT NULL,
		  `nofollow` varchar(10) NOT NULL,
		  `opennewtab` varchar(10) NOT NULL,
		  `approval` int(11) NOT NULL,
		  `package_id` int(11) NOT NULL,
		  `time` datetime NOT NULL,
		  `image_url` text NOT NULL,
		  `user_id` varchar(50) NOT NULL,
		  `custom` text NOT NULL,
		  PRIMARY KEY (`id`)
		)  $collate AUTO_INCREMENT=1 ";


     $sql_sld_package = "
      CREATE TABLE IF NOT EXISTS `$table1` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `title` varchar(200) NOT NULL,
      `description` text NOT NULL,
      `date` datetime NOT NULL,
      `duration` varchar(10) NOT NULL,
      `Amount` float NOT NULL,
      `currency` varchar(10) NOT NULL,
      `item` varchar(10) NOT NULL,
      `paypal` varchar(100) NOT NULL,
      `sandbox` int(11) NOT NULL,
	  `recurring` int(11) NOT NULL,
      `enable` int(11) NOT NULL,
      PRIMARY KEY (`id`)
    ) $collate AUTO_INCREMENT=1";

     $sql_sld_package_purchased = "
      CREATE TABLE IF NOT EXISTS `$table2` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `date` datetime NOT NULL,
      `renew_date` datetime NOT NULL,
      `expire_date` datetime NOT NULL,
      `package_id` int(11) NOT NULL,
      `user_id` int(11) NOT NULL,
      `paid_amount` float NOT NULL,
      `transaction_id` varchar(150) NOT NULL,
      `payer_name` varchar(100) NOT NULL,
      `payer_email` varchar(100) NOT NULL,
	  `recurring` int(11) NOT NULL,
      `status` varchar(50) NOT NULL,
      PRIMARY KEY (`id`)
    ) $collate AUTO_INCREMENT=1";

	$sql_sld_claim_configuration = "
      CREATE TABLE IF NOT EXISTS `$table3` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `date` datetime NOT NULL,
      `Amount` float NOT NULL,
      `currency` varchar(10) NOT NULL,
      `enable` int(11) NOT NULL,
      PRIMARY KEY (`id`)
    ) $collate AUTO_INCREMENT=1";

	$sql_sld_claim_purchased = "
      CREATE TABLE IF NOT EXISTS `$table4` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `date` datetime NOT NULL,
      `user_id` int(11) NOT NULL,
      `listid` int(11) NOT NULL,
	   `item` varchar(255) NOT NULL,
      `paid_amount` float NOT NULL,
      `transaction_id` varchar(150) NOT NULL,
      `payer_name` varchar(100) NOT NULL,
      `payer_email` varchar(100) NOT NULL,
      `status` varchar(50) NOT NULL,
      PRIMARY KEY (`id`)
    ) $collate AUTO_INCREMENT=1";

		 require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
		 dbDelta( $sql_sliders_Table );
		 dbDelta( $sql_sld_package );
		 dbDelta( $sql_sld_package_purchased );
		 dbDelta( $sql_sld_claim_configuration );
		 dbDelta( $sql_sld_claim_purchased );

		 if(!function_exists('qc_sld_isset_table_column')) {
			 function qc_sld_isset_table_column($table_name, $column_name)
			 {
				 global $wpdb;
				 $columns = $wpdb->get_results("SHOW COLUMNS FROM  " . $table_name, ARRAY_A);
				 foreach ($columns as $column) {
					 if ($column['Field'] == $column_name) {
						 return true;
					 }
				 }
			 }
		 }


		 if ( ! @qc_sld_isset_table_column( $table, 'package_id' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table` ADD `package_id` int(11) NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 if ( ! @qc_sld_isset_table_column( $table, 'description' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table` ADD `description` text NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 
		 if ( ! @qc_sld_isset_table_column( $table, 'qcpd_field_1' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table` ADD `qcpd_field_1` text NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 if ( ! @qc_sld_isset_table_column( $table, 'qcpd_field_2' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table` ADD `qcpd_field_2` text NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 if ( ! @qc_sld_isset_table_column( $table, 'qcpd_field_3' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table` ADD `qcpd_field_3` text NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 if ( ! @qc_sld_isset_table_column( $table, 'qcpd_field_4' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table` ADD `qcpd_field_4` text NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 if ( ! @qc_sld_isset_table_column( $table, 'qcpd_field_5' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table` ADD `qcpd_field_5` text NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 if ( ! @qc_sld_isset_table_column( $table, 'tags' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table` ADD `tags` text NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 if ( ! @qc_sld_isset_table_column( $table, 'verified' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table` ADD `verified` text NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }

		 if ( ! @qc_sld_isset_table_column( $table1, 'sandbox' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table1` ADD `sandbox` int(11) NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 if ( ! @qc_sld_isset_table_column( $table1, 'enable' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table1` ADD `enable` int(11) NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 if ( ! @qc_sld_isset_table_column( $table1, 'recurring' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table1` ADD `recurring` int(11) NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 if ( ! @qc_sld_isset_table_column( $table1, 'item' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table1` ADD `item` int(11) NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }

		 if ( ! @qc_sld_isset_table_column( $table2, 'renew' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table2` ADD `renew` datetime NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 if ( ! @qc_sld_isset_table_column( $table2, 'expire_date' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table2` ADD `expire_date` datetime NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 if ( ! @qc_sld_isset_table_column( $table2, 'recurring' ) ) {

			 $sql_slides_Table_update_1 = "ALTER TABLE `$table2` ADD `recurring` int(11) NOT NULL;";
			 @$wpdb->query( $sql_slides_Table_update_1 );
		 }
		 
		 $table_post             = $wpdb->prefix.'posts';
		 $table_postmeta             = $wpdb->prefix.'postmeta';
		 $table_taxonomy             = $wpdb->prefix.'term_taxonomy';
		 $rows     = $wpdb->get_results( "SELECT * FROM $table_post WHERE 1 and `post_type`='pnd'" );
		 
		 foreach($rows as $row){
			$wpdb->update(
				$table_post,
				array(
					'post_type'  => 'pd',
				),
				array( 'ID' => $row->ID),
				array(
					'%s',
				),
				array( '%d')
			);
		 }
		 
		$rows     = $wpdb->get_results( "SELECT * FROM $table_postmeta WHERE 1 and `meta_key`='qcpnd_list_item01'" );
		foreach($rows as $row){

			 $meta_key=qc_meta_format($row->meta_value);
			 $wpdb->update(
				$table_postmeta,
				array(
					'meta_key'  => 'qcpd_list_item01',
					'meta_value'=> $meta_key
				),
				array( 'meta_id' => $row->meta_id),
				array(
					'%s',
					'%s'
				),
				array('%d')
			);

		}
		 
		$wpdb->update(
			$table_taxonomy,
			array(
				'taxonomy'  => 'pd_cat',
			),
			array( 'taxonomy' => 'pnd_cat'),
			array(
				'%s',
			),
			array( '%s')
		); 

}

//Remove top admin bar for slduser only

//add_action('init', 'pd_remove_admin_bar_slduser');

function pd_remove_admin_bar_slduser(){
	if(!function_exists('wp_get_current_user')) {
		include(ABSPATH . "wp-includes/pluggable.php");
	}
	if(is_user_logged_in()){
		$current_user = wp_get_current_user();
		if(in_array('pduser',$current_user->roles)){
			add_filter('show_admin_bar', '__return_false');
		}
	}
}




add_action( 'init', 'qcld_pd_wpdocs_load_textdomain' );

//Plugin loaded
add_action( 'plugins_loaded', 'qcpd_qcpdsbd_help_link_submenu' );
function qcpd_qcpdsbd_help_link_submenu(){

    $getoption1 = get_option('pd_option_tree');


	global $wpdb;
	$table             = $wpdb->prefix.'pd_package';
	$pkg = $wpdb->get_row("select * from $table");
  if( isset($pkg->paypal) ){
  	if(@$pkg->paypal!=''){
  		if($getoption1['sbd_paypal_email']==''){
  			$getoption1['sbd_paypal_email'] = $pkg->paypal;
  			update_option( 'pd_option_tree', $getoption1, 'yes' );
  		}

  	}
  }

}

/**
 * Load plugin textdomain.
 */
function qcld_pd_wpdocs_load_textdomain() {
    load_plugin_textdomain( 'qc-pd', false, dirname( plugin_basename( __FILE__ ) ) . '/lang' );
}

/*Menu Order*/
add_action( 'admin_init', 'qcpd_posts_order_wpse' );

function qcpd_posts_order_wpse()
{
    add_post_type_support( 'pd', 'page-attributes' );
}

//Plugin loaded




function sbd_change_role_name() {
    global $wp_roles;

    if ( ! isset( $wp_roles ) )
        $wp_roles = new WP_Roles();

    //You can list all currently available roles like this...
    //$roles = $wp_roles->get_names();
    //print_r($roles);

    //You can replace "administrator" with any other role "editor", "author", "contributor" or "subscriber"...
    $wp_roles->roles['pduser']['name'] = 'SBD User';
    $wp_roles->role_names['pduser'] = 'SBD User';    


}
add_action('init', 'sbd_change_role_name');


//add_action('pre_get_posts','pd_users_own_attachments');
function pd_users_own_attachments( $wp_query_obj ) {

    global $current_user, $pagenow;

    $is_attachment_request = ($wp_query_obj->get('post_type')=='attachment');

    if( !$is_attachment_request )
        return;

	if(in_array('pduser',$current_user->roles) or in_array('subscriber',$current_user->roles))
		$wp_query_obj->set('author', $current_user->ID );

    return;
}

add_action('init', 'sbd_init_fnc');
function sbd_init_fnc(){
  add_filter('widget_text', 'do_shortcode');
	$prev = get_option('option_tree');
	if(!empty($prev)){
		if(!get_option('sbd_option_restore')){
			if(get_option('pd_option_tree')){
				update_option('pd_option_tree', $prev);
				add_option( 'sbd_option_restore', 'yes', '', 'yes' );
			}else{
				add_option( 'pd_option_tree', $prev, '', 'yes' );
				add_option( 'sbd_option_restore', 'yes', '', 'yes' );
			}
		}
	}
}



// To show the column header
function pd_cat_column_header( $columns ){
  $columns['header_name'] = 'ID'; 
	$new = array("image"=>"Image");

  array_splice($columns, 1, 0, $new);
 
  return $columns;
}

add_filter( "manage_edit-pd_cat_columns", 'pd_cat_column_header', 1);
add_filter( "manage_edit-pd_cat_sortable_columns", 'pd_cat_column_header' );

// To show the column value
function pd_cat_column_content( $value, $column_name, $tax_id ){
	if($column_name=='0'){
		$image_id = get_term_meta( $tax_id, 'category-image-id', true );
		if($image_id){
			return wp_get_attachment_image ( $image_id, 'thumbnail' );
		}
	}else{
		return $tax_id ;
	}
   
}
add_action( "manage_pd_cat_custom_column", 'pd_cat_column_content', 1, 3);

/*
add_action('save_post','save_post_callback');
function save_post_callback($post_id){
    global $post; 
    if ($post->post_type != 'pd'){
        return;
    }
    $items = get_post_meta($post->ID, 'qcpd_list_item01');
	//print_r($items);exit;
	
}*/

add_action( 'added_post_meta', 'sbd_sync_on_product_save', 10, 4 );

function sbd_sync_on_product_save( $meta_id, $post_id, $meta_key, $meta_value ) {
	global $wpdb;
    if ( $meta_key == 'qcpd_list_item01' ) { // we've been editing the post
		if(isset($meta_value['qcpd_other_list']) && $meta_value['qcpd_other_list']!=''){
			
			$listids = explode(',',$meta_value['qcpd_other_list']);
			$meta_value['qcpd_other_list'] = '';

			@$wpdb->delete(
                "{$wpdb->prefix}postmeta",
	            array( 'meta_id' => $meta_id ),
	            array( '%d' )
            );
			
			add_post_meta( $post_id, 'qcpd_list_item01', $meta_value );
			
			foreach($listids as $listid){
				if($post_id != $listid)
					@add_post_meta( $listid, 'qcpd_list_item01', $meta_value );
			}
			
		}
    }
}

add_action( 'added_post_meta', 'sbd_collect_image_from_web', 10, 4 );
function sbd_collect_image_from_web( $meta_id, $post_id, $meta_key, $meta_value ){
	global $wpdb;
	if ( $meta_key == 'qcpd_list_item01' ) {
		
		if(isset($meta_value['qcpd_item_img']) && $meta_value['qcpd_item_img']==''){
			
			if(isset($meta_value['qcpd_item_link']) && $meta_value['qcpd_item_link']!=''){
				
				if(isset($meta_value['qcpd_image_from_link']) && $meta_value['qcpd_image_from_link']=='1'){
					
					//Main functionality
					
					
						
						$image = sld_get_web_page("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=".$meta_value['qcpd_item_link']."&screenshot=true");
						$image = json_decode($image, true);
						$image = $image['screenshot']['data'];
						$upload_dir       = wp_upload_dir();
						$upload_path      = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
						$image = str_replace(array('_', '-'), array('/', '+'), $image);
						$imgBase64 = str_replace('data:image/jpeg;base64,', '', $image);
						$imgBase64 = str_replace(' ', '+', $imgBase64);
						$decoded = base64_decode($imgBase64);
						$filename         = 'sbdwebsite.jpg';
						$hashed_filename  = md5( $filename . microtime() ) . '_' . $filename;
						$image_upload     = file_put_contents( $upload_path . $hashed_filename, $decoded );
						if( !function_exists( 'wp_handle_sideload' ) ) {
						  require_once( ABSPATH . 'wp-admin/includes/file.php' );
						}
						if( !function_exists( 'wp_get_current_user' ) ) {
						  require_once( ABSPATH . 'wp-includes/pluggable.php' );
						}
						$file             = array();
						$file['error']    = '';
						$file['tmp_name'] = $upload_path . $hashed_filename;
						$file['name']     = $hashed_filename;
						$file['type']     = 'image/jpeg';
						$file['size']     = filesize( $upload_path . $hashed_filename );
						$file_return      = wp_handle_sideload( $file, array( 'test_form' => false ) );
						$filename = $file_return['file'];
						$attachment = array(
						 'post_mime_type' => $file_return['type'],
						 'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
						 'post_content' => '',
						 'post_status' => 'inherit',
						 'guid' => $upload_dir['url'] . '/' . basename($filename)
						 );
						$attach_id = wp_insert_attachment( $attachment, $filename, $post_id );
						require_once(ABSPATH . 'wp-admin/includes/image.php');
						$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
						wp_update_attachment_metadata( $attach_id, $attach_data );					
						$meta_value['qcpd_item_img'] = $attach_id;
						
						@$wpdb->delete(
							"{$wpdb->prefix}postmeta",
							array( 'meta_id' => $meta_id ),
							array( '%d' )
						);
						add_post_meta( $post_id, 'qcpd_list_item01', $meta_value );
						
					

				}
				
			}
			
		}
		
	}
}

add_action( 'admin_menu' , 'qcpdsbd_help_link_submenu', 20 );
function qcpdsbd_help_link_submenu(){
	global $submenu;
	
	$link_text = "Help";
	$submenu["edit.php?post_type=pd"][250] = array( $link_text, 'activate_plugins' , admin_url('edit.php?post_type=pd&page=pd-options-page#section_help') );
	ksort($submenu["edit.php?post_type=pd"]);
	
	return ($submenu);
}

add_action( 'add_meta_boxes', 'qcpdsbd_meta_box_video' );
function qcpdsbd_meta_box_video()
{					                  // --- Parameters: ---
    add_meta_box( 'qc-sbd-meta-box-id', // ID attribute of metabox
                  'Shortcode Generator for SBD',       // Title of metabox visible to user
                  'qcpdsbd_meta_box_callback', // Function that prints box in wp-admin
                  'page',              // Show box for posts, pages, custom, etc.
                  'side',            // Where on the page to show the box
                  'high' );            // Priority of box in display order
}

function qcpdsbd_meta_box_callback( $post )
{
    ?>
    <p>
        <label for="sh_meta_box_bg_effect"><p>Click the button below to generate shortcode</p></label>
		<input type="button" id="sbd_shortcode_generator_meta" class="button button-primary button-large" value="Generate Shortcode" />
    </p>
    
    <?php
}

/*
apply_filters('sbd_script_loader_tag', $tag, $handle, $src);
function sbd_add_async_attribute($tag, $handle) {
    if ( 'qcopd-google-map-script' !== $handle )
        return $tag;
    return str_replace( ' src', ' async="async" src', $tag );
}

function sbd_add_def_attribute($tag, $handle) {
    if ( 'qcopd-google-map-script' !== $handle )
        return $tag;
    return str_replace( ' src', ' defer="defer" src', $tag );
}
add_filter('sbd_script_loader_tag', 'sbd_add_async_attribute', 10, 2);
add_filter('sbd_script_loader_tag', 'sbd_add_def_attribute', 10, 2);
*/

//wp cron functionality

add_action( 'wp', 'sbd_prefix_setup_schedule' );
/**
 * On an early action hook, check if the hook is scheduled - if not, schedule it.
 */
function sbd_prefix_setup_schedule() {
    if ( ! wp_next_scheduled( 'sbd_prefix_daily_event' ) ) {
        wp_schedule_event( time(), 'daily', 'sbd_prefix_daily_event');
    }
}

add_action( 'sbd_prefix_daily_event', 'sbd_prefix_daily_event_fnc' );

/**
 * On the scheduled action hook, run a function.
 */
function sbd_prefix_daily_event_fnc() {
    // check every user and see if their account is expiring, if yes, send your email.
	
	global $wpdb;

	$package_purchased_table = $wpdb->prefix.'pd_package_purchased';
	$package_table = $wpdb->prefix.'pd_package';
	
	if(pd_ot_get_option('pd_enable_email_notification_package_expire')!='on'){
		return;
	}
	
	$userpkgs = $wpdb->get_results("select * from $package_purchased_table WHERE 1 and `expire_date` < CURDATE()");
	if(!empty($userpkgs)){
		
		foreach($userpkgs as $package){
			
			if(get_option('sbd_is_email_sent_'.$package->id)!='yes'){
				
				sbd_send_package_expire_notification($package);
				
				add_option( 'sbd_is_email_sent_'.$package->id, 'yes', '', 'yes' );
			}
			
		}
		
	}

}

add_filter('post_row_actions','qc_sbd_action_row', 10, 2);

function qc_sbd_action_row($actions, $post){
    //check for your post type
    if ($post->post_type =="pd"){
       $actions['large_list_edit'] = '<a href="'.admin_url( 'edit.php?post_type=pd&page=pd-manage-large-list&listid=' . $post->ID ).'" rel="bookmark" aria-label="View &#8220;PRACTITIONER&#8221;">Edit Large List</a>';
	   return $actions;
    }
    return $actions;
}

add_action( 'edit_form_top', 'qc_sbd_edit_form_after_title' );

function qc_sbd_edit_form_after_title($post) {

	if($post->post_type=='pd'){
		echo '<p>If you face any issues saving your List, try the alternative way to manage Longer Lists from <a href="'.admin_url( 'edit.php?post_type=pd&page=pd-manage-large-list&listid=' . $post->ID ).'">here</a>.</p>';
	}

}


if( function_exists('register_block_type') ){
	function qcpd__sbd_gutenberg_block() {
        if(is_admin()){
    	    require_once plugin_dir_path( __FILE__ ).'/gutenberg/sbd-block/plugin.php';
        }
	}
	add_action( 'init', 'qcpd__sbd_gutenberg_block' );
}
//free to pro upgrade
function qc_meta_format($data){
	$data = unserialize($data);
	$data['qcpd_item_title'] = $data['qcpnd_item_title'];
	unset($data['qcpnd_item_title']);
	$data['qcpd_item_link'] = $data['qcpnd_item_link'];
	unset($data['qcpnd_item_link']);
	$data['qcpd_item_phone'] = $data['qcpnd_item_phone'];
	unset($data['qcpnd_item_phone']);
	
	$data['qcpd_item_img'] = $data['qcpnd_item_img'];
	unset($data['qcpnd_item_img']);
	
	$data['qcpd_item_subtitle'] = $data['qcpnd_item_description'];
	unset($data['qcpnd_item_description']);
	
	$data['qcpd_item_location'] = $data['qcpnd_item_subtitle'];
	unset($data['qcpnd_item_subtitle']);
	
	return serialize($data);
	
}
// Remove view from custom post type.
add_filter( 'post_row_actions', 'qcpd_sbd_remove_row_actions', 10, 1 );
function qcpd_sbd_remove_row_actions( $actions )
{
	if( get_post_type() === 'pd' ){
	 unset( $actions['view'] );
	}
	 
	return $actions;
}
// Remove view from taxonomies
add_filter( 'pd_cat_row_actions', 'qcpd_sbd_category_remove_row_actions', 10, 1 );
function qcpd_sbd_category_remove_row_actions($actions){
	unset($actions['view']);
	return $actions;
}

add_action('wp_head', 'sbd_add_css_to_head');
function sbd_add_css_to_head(){
  $sbd_style = '<style>
              .mfp-hide {
                  display: none !important;
              }
            </style>';
  echo $sbd_style;
}

add_action('wp_footer', 'sbd_email_form_footer');
function sbd_email_form_footer(){
	/*if (session_status() == PHP_SESSION_NONE) {
		session_start();
	}*/
  //wp_enqueue_style( 'qcopd-magpopup-css', QCSBD_ASSETS_URL . '/css/magnific-popup.css');
  $pd_disallow_send_listing_email = pd_ot_get_option('pd_disallow_send_listing_email');

	if(isset($_SESSION['sbd_captcha'])){
		unset($_SESSION['sbd_captcha']);
	}

    global $post;
    if( is_a( $post, 'WP_Post' ) && (has_shortcode( $post->post_content, 'qcpd-directory-multipage') || has_shortcode( $post->post_content, 'sbd_single_item') || has_shortcode( $post->post_content, 'qcpd-directory') || has_shortcode( $post->post_content, 'sbd-multipage-category') || has_shortcode( $post->post_content, 'pd-tab') ) ) {

    	$_SESSION['sbd_captcha'] = pd_simple_php_captcha();
    }


  if( pd_ot_get_option( 'pd_enable_recaptcha')=='on' ){
    wp_enqueue_script('qcld_pd_google_recaptcha', 'https://www.google.com/recaptcha/api.js', array('jquery'), '1.0.0', true);
  }
?>
	<div id="sbd_email_form" class="white-popup mfp-hide">
		<div class="sbd_business_container">
			<div class="sbd_email_container">
        <?php if( $pd_disallow_send_listing_email == 'on' && !is_user_logged_in() ){}else{ ?>
				  <h2><?php echo (pd_ot_get_option('sbd_lan_email_listing_owner')!=''?pd_ot_get_option('sbd_lan_email_listing_owner'):esc_html__('Contact to Listing Owner','qc-pd')); ?></h2>
        <?php } ?>
			  <form id="sbd_email_form_id" action="">
        <?php if( $pd_disallow_send_listing_email == 'on' && !is_user_logged_in() ){ ?>
          <p>
            <?php
              $url = qc_sbd_login_page()->pdcustom_login_get_translated_option_page('sbd_login_url');
              $login_url = apply_filters('sbd_email_login_url', $url);
              if(pd_ot_get_option('sbd_lan_login_to_email_listing_owner')!=''){
                echo pd_ot_get_option('sbd_lan_login_to_email_listing_owner');
              }else{
                esc_html_e('You need to login to contact with the Listing Owner. ', 'qc-pd');
              }

              if(pd_ot_get_option('sbd_lan_click_to_login')!=''){
                echo "<a href='".esc_url($login_url)."'>".pd_ot_get_option('sbd_lan_click_to_login')."</a>";
                //echo sprintf(__('<a href="%s">Click Here to log in</a>.','qc-pd'),$url);
              }else{
                      echo sprintf(__('<a href="%s">Click Here to log in</a>.','qc-pd'),$login_url);
              }
            ?>
          </p>
        <?php }else{ ?>
  				<label for="fname"><?php echo pd_ot_get_option('sbd_lan_name')!='' ? pd_ot_get_option('sbd_lan_name') : __('Name *', 'qc-pd'); ?></label>
  				<input type="text" id="sbd_email_name" name="sbd_email_name" placeholder="" required>

  				<label for="lname"><?php echo pd_ot_get_option('sbd_lan_email')!='' ? pd_ot_get_option('sbd_lan_email') : __('Email *', 'qc-pd'); ?></label>
  				<input type="email" id="sbd_email_email" name="sbd_email_email" placeholder="" required>


  				<label for="subject"><?php echo pd_ot_get_option('sbd_lan_subject')!='' ? pd_ot_get_option('sbd_lan_subject') : __('Subject *', 'qc-pd'); ?></label>
  				<input type="text" id="sbd_email_subject" name="sbd_email_subject" placeholder="" required>
  				
  				<label for="subject"><?php echo pd_ot_get_option('sbd_lan_message')!='' ? pd_ot_get_option('sbd_lan_message') : __('Message *', 'qc-pd'); ?></label>

    			<textarea id="sbd_email_message" name="sbd_email_message" placeholder="" style="height:200px" required></textarea>
    			<input type="hidden" id="sbd_email_to" name="sbd_email_to" value="" />
          <input type="hidden" id="sbd_email_title" name="sbd_email_title" value="" />
          <input type="hidden" id="sbd_email_subtitle" name="sbd_email_subtitle" value="" />
  				
  				<?php if( pd_ot_get_option( 'pd_enable_recaptcha') !='on' ){ ?>
    				<img src="<?php echo (isset($_SESSION['sbd_captcha']['image_src']) ? $_SESSION['sbd_captcha']['image_src'] : ''); ?>" alt="Captcha Code" id="pd_captcha_image" />
    				<img style="width: 24px;cursor:pointer;" id="captcha_reload1" src="<?php echo QCSBD_IMG_URL.'/captcha_reload.png'; ?>" />
    				
    				<br>
    				<label for="subject"><?php echo pd_ot_get_option('sbd_lan_code')!='' ? pd_ot_get_option('sbd_lan_code') : __('Code *', 'qc-pd'); ?></label>
    				<input class="cleanlogin-field-username" placeholder="" type="text" name="ccode" id="pdcode" value="" required>				             
    				<input class="cleanlogin-field-username" placeholder="" type="hidden" id="pdccode" value="<?php echo (isset($_SESSION['sbd_captcha']['sbd_code']) ? $_SESSION['sbd_captcha']['sbd_code'] : ''); ?>">	
          <?php } ?>	
          <?php
            if( pd_ot_get_option( 'pd_enable_recaptcha')=='on' ){

                echo '<div class="cleanlogin-field sbd-ajaxmail-recaptcha"><div class="g-recaptcha" data-sitekey="'.pd_ot_get_option( 'pd_recaptcha_site_key').'"></div></div>';
              }
          ?>		             
  				
  				<input type="submit" id="sbd_email_submit" value="<?php echo pd_ot_get_option('sbd_lan_submit')!='' ? pd_ot_get_option('sbd_lan_submit') : __('Submit', 'qc-pd'); ?>">
  				<span id="sbd_email_loading" style="display:none;"><img src="<?php echo QCSBD_ASSETS_URL; ?>/css/ajax-loader.gif" /></span>
  				<span id="sbd_email_status"></span>
        <?php } ?>
			  </form>
			</div>
		</div>
	</div>
<?php
}



function qcpd_admin_importexport_enqueue() 
{

    wp_enqueue_script( 'pd-import-script', QCSBD_ASSETS_URL . '/admin/js/pd-admin-js.js' );
    wp_enqueue_style( 'pd-import-style', QCSBD_ASSETS_URL . '/admin/css/pd-admin-css.css' );
  
}

add_action( 'admin_enqueue_scripts', 'qcpd_admin_importexport_enqueue' );

//plugin activate redirect codecanyon
function qc_sbd_activation_redirect( $plugin ) {
    if( $plugin == plugin_basename( __FILE__ ) ) {
        exit( wp_redirect( admin_url('edit.php?post_type=pd&page=qcld_sbd_help_license') ) );
    }
}
add_action( 'activated_plugin', 'qc_sbd_activation_redirect' );


function sbd_ot_google_fonts_api_key( $key ) {
  $key = pd_ot_get_option('pd_google_font_api');
  if( !isset($key) || empty($key) ){
    $key = 'AIzaSyCWhl0a3K4X0hi2Srdwm_hb4YQtTtVgNXU';
  }
  return $key;
}
add_filter( 'ot_google_fonts_api_key', 'sbd_ot_google_fonts_api_key' );

function qcpd_init(){
  if( is_admin() ){ 
      global $pagenow;
      
      if (
        ('post.php' === $pagenow && (isset($_GET['post']) && 'pd' != get_post_type( $_GET['post'] )) ) ||
        ( 'post-new.php' === $pagenow && (isset($_GET['post_type']) && 'pd' != $_GET['post_type']) )
      ){
        // Remove scripts for metaboxes to post-new.php & post.php.
        remove_action( 'admin_print_scripts-post-new.php', 'ot_admin_scripts', 11 );
        remove_action( 'admin_print_scripts-post.php', 'ot_admin_scripts', 11 );

        // Remove styles for metaboxes to post-new.php & post.php.
        remove_action( 'admin_print_styles-post-new.php', 'ot_admin_styles', 11 );
        remove_action( 'admin_print_styles-post.php', 'ot_admin_styles', 11 );
      }
  }
}
add_action('init', 'qcpd_init');

function sbd_remove_admin_menu_items() {
    if( !current_user_can( 'edit_posts' ) ):
        remove_menu_page( 'edit.php?post_type=pd' );
    endif;
}
add_action( 'admin_menu', 'sbd_remove_admin_menu_items' );


add_action( 'admin_notices', 'qcpd_wp_pro_shortcode_notice',100 );

 function qcpd_wp_pro_shortcode_notice(){

    global $pagenow, $typenow;

    if ( isset($typenow) && $typenow == 'pd'  ) {

           ?>
                <div id="message" class="notice notice-info is-dismissible">
                    <p>
                        <?php
                        printf(
                            __('%s Simple Business Directory %s works the best when you create multiple Lists and show them all in a page. Use the following shortcode to display All lists on any page:  %s %s %s  Use the %s shortcode generator %s to select style and other options.', 'dna88-wp-notice'),
                            '<strong>',
                            '</strong>',
                            '<code>',
                            '[qcpd-directory mode="all" style="simple" map="show"]',
                            '</code>',
                            '<strong>',
                            '</strong>',
                        );
                        ?>
                    </p>
                </div>
        <?php 
        
    }

}