<?php


function pd_ot_get_option($key=''){
	
	if($key=='')
		return false;
	
	$data = get_option('pd_option_tree');
	
	if(!is_array($data))
		return false;
	
	if(empty($data))
		return false;
	
	if(array_key_exists($key, $data)){
		return $data[$key];
	}else{
		return false;
	}
	
}

function sbd_alexaRank($url) {
 $alexaData = simplexml_load_file("http://data.alexa.com/data?cli=10&url=".$url);
 $alexa['globalRank'] =  isset($alexaData->SD->POPULARITY) ? $alexaData->SD->POPULARITY->attributes()->TEXT : 0 ;
 $alexa['CountryRank'] =  isset($alexaData->SD->COUNTRY) ? $alexaData->SD->COUNTRY->attributes() : 0 ;
 return json_decode(json_encode($alexa), TRUE);
}

function qcsbd_get_id_by_shortcode($shortcode) {
	global $wpdb;
	$sql = 'SELECT ID
		FROM ' . $wpdb->posts . '
		WHERE
			post_type = "page"
			AND post_status="publish"
			AND post_content LIKE "%' . $shortcode . '%" limit 1';

	$id = $wpdb->get_var($sql);

	return $id;
}

/*
* This function return most voted link items of SLD
*/
function qcpd_get_most_popular_links_wi( $limit = null )
{
	
	
	$multipage = false;
	if(sbd_get_option_page('sbd_directory_page')==get_queried_object_id()){
		$multipage = true;
	}
	
	if( $limit == null )
	{
		$limit = 5;
	}

	$arrayOfElements = array();

	$enableUpvoting = pd_ot_get_option( 'pd_enable_widget_upvote' );

	$list_args = array(
		'post_type' => 'pd',
		'orderby' => 'date',
		'order' => 'desc',
		'posts_per_page' => -1,
	);

	$list_query = new WP_Query( $list_args );

	if( $list_query->have_posts() )
	{
		$count = 0;
		
		while ( $list_query->have_posts() ) 
		{
			$list_query->the_post();

			$lists = get_post_meta( get_the_ID(), 'qcpd_list_item01' );

			$title = get_the_title();
			$id = get_the_ID();
			
			$category = get_the_terms( $id, 'pd_cat' );   
			
			
			
			
			foreach( $lists as $list )
			{
				$img = "";
				$newtab = 0;
				$nofollow = 0;
				$votes = 0;

				if( isset($list['qcpd_item_img'])  && $list['qcpd_item_img'] != "" )
				{
					$img = wp_get_attachment_image_src($list['qcpd_item_img']);
				}

				if( isset($list['qcpd_item_nofollow']) && $list['qcpd_item_nofollow'] == 1 ) 
				{
					$nofollow = 1;
				}

				if( isset($list['qcpd_item_newtab']) && $list['qcpd_item_newtab'] == 1 ) 
				{
					$newtab = 1;
				}

				if( isset($list['qcpd_upvote_count']) && (int)$list['qcpd_upvote_count'] > 0 )
				{
			  	  $votes = (int)$list['qcpd_upvote_count'];
			    }

				$item['item_title'] = trim($list['qcpd_item_title']);
				$item['item_img'] = $img;
				$item['item_subtitle'] = trim($list['qcpd_item_subtitle']);
				$item['item_link'] = $list['qcpd_item_link'];
				$item['item_nofollow'] = $nofollow;
				$item['item_newtab'] = $newtab;
				$item['item_votes'] = $votes;
				$item['item_parent'] = $title;
				$item['item_parent_id'] = $id;
				$item['item_timelaps'] = $list['qcpd_timelaps'];
				
				$item['item_category'] = (!empty($category)?$category[0]->slug:'no_category');

				array_push($arrayOfElements, $item);

			}

			$count++;
		}

	}
	else
	{
		return __('No list elements was found.', 'qc-pd');
	}

	// Sort the multidimensional array
    usort($arrayOfElements, "sbd_custom_sort_by_votes");

    ob_start();

	//echo '<link rel="stylesheet" type="text/css" href="'.QCSBD_ASSETS_URL.'/css/directory-style.css" />';
    $count = 1;
    $listCount = 10111;
    $numberOfItems = count( $arrayOfElements );

    echo '<ul class="widget-pd-list">';
    
    foreach( $arrayOfElements as $item ){
		
		
		if($multipage==true && pd_ot_get_option('pd_widget_link_multipage')=='on'){
			$url = home_url().'/'.get_post_field( 'post_name', get_queried_object_id() ).'/'.$item['item_category'].'/'.str_replace('-',' ',strtolower($item['item_parent'])).'/'.urlencode(str_replace(' ','-',strtolower($item['item_title']))).'/'.$item['item_timelaps'];
		}else{
			$url = $item['item_link'];
		}
    	?>
		
		
    	<li id="item-<?php echo $item['item_parent_id'] ."-". $listCount; ?>">

			<a <?php echo (isset($item['item_nofollow']) && $item['item_nofollow'] == 1) ? 'rel="nofollow"' : ''; ?> <?php echo (isset($item['item_newtab']) && $item['item_newtab'] == 1) ? 'target="_blank"' : ''; ?> href="<?php echo $url; ?>">
	
				<?php if( !empty($item['item_img']) && $item['item_img'][0] != "" ) : ?>
				
					<img class="widget-avatar" src="<?php echo $item['item_img'][0]; ?>" alt="">

				<?php else : ?>

					<img class="widget-avatar" src="<?php echo QCSBD_IMG_URL; ?>/list-image-placeholder.png" alt="">

				<?php endif; ?>

				<?php echo $item['item_title']; ?>

				<?php if( $enableUpvoting == 'on' ) : ?>

				<div class="widget-vcount">
				
					<div class="upvote-section">
						
						<span data-post-id="<?php echo $item['item_parent_id']; ?>" data-item-title="<?php echo $item['item_title']; ?>" data-item-link="<?php echo $item['item_link']; ?>" class="sbd-upvote-btn upvote-on">
							<span class="opening-bracket">
								(
							</span>
							<i class="fa fa-thumbs-up"></i>
							<span class="upvote-count">
								<?php echo $item['item_votes']; ?>
							</span>
							<span class="closing-bracket">
								)
							</span>
						</span>	
						
					</div>

				</div>

				<?php endif; ?>

			</a>

		</li>
    	<?php

    	if( $numberOfItems > $limit )
    	{
    		if( $limit == $count )
    		{
    			break;
    		} //if $limit == $count

    	} //if $numberOfItems > $limit

    	$count++;
    	$listCount++;

    } // End Foreach

    echo '</ul>';

    $content = ob_get_clean();

    return $content;

} //End of get_most_popular_links

// Define the custom sort function
function sbd_custom_sort_by_votes($a, $b) {
    return $a['item_votes'] < $b['item_votes'];
}


/*
* This function return randomly picked link items of SLD
*/
function qcpd_get_random_links_wi( $limit = null )
{
	
	$multipage = false;
	if(sbd_get_option_page('sbd_directory_page')==get_queried_object_id()){
		$multipage = true;
	}
	
	if( $limit == null )
	{
		$limit = 5;
	}

	$enableUpvoting = pd_ot_get_option( 'pd_enable_widget_upvote' );

	$arrayOfElements = array();

	$list_args = array(
		'post_type' => 'pd',
		'orderby' => 'date',
		'order' => 'desc',
		'posts_per_page' => -1,
	);

	$list_query = new WP_Query( $list_args );

	if( $list_query->have_posts() )
	{
		$count = 0;
		
		while ( $list_query->have_posts() ) 
		{
			$list_query->the_post();

			$lists = get_post_meta( get_the_ID(), 'qcpd_list_item01' );

			$title = get_the_title();
			$id = get_the_ID();

			$category = get_the_terms( $id, 'pd_cat' );   
			foreach( $lists as $list )
			{
				$img = "";
				$newtab = 0;
				$nofollow = 0;
				$votes = 0;

				if( isset($list['qcpd_item_img'])  && $list['qcpd_item_img'] != "" )
				{
					$img = wp_get_attachment_image_src($list['qcpd_item_img']);
				}

				if( isset($list['qcpd_item_nofollow']) && $list['qcpd_item_nofollow'] == 1 ) 
				{
					$nofollow = 1;
				}

				if( isset($list['qcpd_item_newtab']) && $list['qcpd_item_newtab'] == 1 ) 
				{
					$newtab = 1;
				}

				if( isset($list['qcpd_upvote_count']) && (int)$list['qcpd_upvote_count'] > 0 )
				{
			  	  $votes = (int)$list['qcpd_upvote_count'];
			    }

				$item['item_title'] = trim($list['qcpd_item_title']);
				$item['item_img'] = $img;
				$item['item_subtitle'] = trim($list['qcpd_item_subtitle']);
				$item['item_link'] = $list['qcpd_item_link'];
				$item['item_nofollow'] = $nofollow;
				$item['item_newtab'] = $newtab;
				$item['item_votes'] = $votes;
				$item['item_parent'] = $title;
				$item['item_parent_id'] = $id;
				$item['item_timelaps'] = $list['qcpd_timelaps'];
				
				$item['item_category'] = (!empty($category)?$category[0]->slug:'no_category');

				array_push($arrayOfElements, $item);

			}

			$count++;
		}

	}
	else
	{
		return __('No list elements was found.', 'qc-pd');
	}

	// Sort the multidimensional array
    usort($arrayOfElements, "sbd_custom_sort_by_votes");

    shuffle( $arrayOfElements );

    ob_start();
	//echo '<link rel="stylesheet" type="text/css" href="'.QCSBD_ASSETS_URL.'/css/directory-style.css" />';
    $count = 1;
    $listCount = 20111;
    $numberOfItems = count( $arrayOfElements );

    echo '<ul class="widget-pd-list">';
    
    foreach( $arrayOfElements as $item ){
		
		if($multipage==true && pd_ot_get_option('pd_widget_link_multipage')=='on'){
			$url = home_url().'/'.get_post_field( 'post_name', get_queried_object_id() ).'/'.$item['item_category'].'/'.str_replace('-',' ',strtolower($item['item_parent'])).'/'.urlencode(str_replace(' ','-',strtolower($item['item_title']))).'/'.$item['item_timelaps'];
		}else{
			$url = $item['item_link'];
		}
		
    	?>
    	<li id="item-<?php echo $item['item_parent_id'] ."-". $listCount; ?>">
			<a <?php echo (isset($item['item_nofollow']) && $item['item_nofollow'] == 1) ? 'rel="nofollow"' : ''; ?> <?php echo (isset($item['item_newtab']) && $item['item_newtab'] == 1) ? 'target="_blank"' : ''; ?> href="<?php echo $url; ?>">

				<?php if( !empty($item['item_img']) && $item['item_img'][0] != "" ) : ?>
				
					<img class="widget-avatar" src="<?php echo $item['item_img'][0]; ?>" alt="">

				<?php else : ?>

					<img class="widget-avatar" src="<?php echo QCSBD_IMG_URL; ?>/list-image-placeholder.png" alt="">

				<?php endif; ?>

				<?php echo $item['item_title']; ?>

				<?php if( $enableUpvoting == 'on' ) : ?>

				<div class="widget-vcount">
				
					<div class="upvote-section">
						
						<span data-post-id="<?php echo $item['item_parent_id']; ?>" data-item-title="<?php echo $item['item_title']; ?>" data-item-link="<?php echo $item['item_link']; ?>" class="sbd-upvote-btn upvote-on">
							<span class="opening-bracket">
								(
							</span>
							<i class="fa fa-thumbs-up"></i>
							<span class="upvote-count">
								<?php echo $item['item_votes']; ?>
							</span>
							<span class="closing-bracket">
								)
							</span>
						</span>	
						
					</div>

				</div>

				<?php endif; ?>

			</a>
		</li>
    	<?php

    	if( $numberOfItems > $limit )
    	{
    		if( $limit == $count )
    		{
    			break;
    		} //if $limit == $count

    	} //if $numberOfItems > $limit

    	$count++;
    	$listCount++;

    } //End Foreach

    echo '</ul>';

    $content = ob_get_clean();

    return $content;

} //End of qcpd_get_random_links_wi


/*
* This function return the most recent link items of SLD
*/
function qcpd_get_latest_links_wi( $limit = null )
{
	
	$multipage = false;
	if(sbd_get_option_page('sbd_directory_page')==get_queried_object_id()){
		$multipage = true;
	}
	if( $limit == null )
	{
		$limit = 5;
	}

	$enableUpvoting = pd_ot_get_option( 'pd_enable_widget_upvote' );

	$arrayOfElements = array();

	$list_args = array(
		'post_type' => 'pd',
		'orderby' => 'date',
		'order' => 'desc',
		'posts_per_page' => -1,
	);

	$list_query = new WP_Query( $list_args );

	if( $list_query->have_posts() )
	{
		$count = 0;
		
		while ( $list_query->have_posts() ) 
		{
			$list_query->the_post();

			$lists = get_post_meta( get_the_ID(), 'qcpd_list_item01' );

			$title = get_the_title();
			$id = get_the_ID();

			$category = get_the_terms( $id, 'pd_cat' );   
			foreach( $lists as $list )
			{
				$img = "";
				$newtab = 0;
				$nofollow = 0;
				$votes = 0;

				if( isset($list['qcpd_item_img'])  && $list['qcpd_item_img'] != "" )
				{
					$img = wp_get_attachment_image_src($list['qcpd_item_img']);
				}

				if( isset($list['qcpd_item_nofollow']) && $list['qcpd_item_nofollow'] == 1 ) 
				{
					$nofollow = 1;
				}

				if( isset($list['qcpd_item_newtab']) && $list['qcpd_item_newtab'] == 1 ) 
				{
					$newtab = 1;
				}

				if( isset($list['qcpd_upvote_count']) && (int)$list['qcpd_upvote_count'] > 0 )
				{
			  	  $votes = (int)$list['qcpd_upvote_count'];
			    }

				$item['item_title'] = trim($list['qcpd_item_title']);
				$item['item_img'] = $img;
				$item['item_subtitle'] = trim($list['qcpd_item_subtitle']);
				$item['item_link'] = $list['qcpd_item_link'];
				$item['item_nofollow'] = $nofollow;
				$item['item_newtab'] = $newtab;
				$item['item_votes'] = $votes;
				$item['item_parent'] = $title;
				$item['item_parent_id'] = $id;

				$item['item_time'] = '1970-01-01 01:01:01';

				if( isset($list['qcpd_entry_time']) && $list['qcpd_entry_time'] != "" )
				{
					$item['item_time'] = $list['qcpd_entry_time'];
				}
				$item['item_timelaps'] = $list['qcpd_timelaps'];
				
				$item['item_category'] = (!empty($category)?$category[0]->slug:'no_category');

				array_push($arrayOfElements, $item);

			}

			$count++;
		}

	}
	else
	{
		return __('No list elements was found.', 'qc-pd');
	}

	// Sort the multidimensional array
    usort($arrayOfElements, "sbd_custom_sort_by_entry_time");

    ob_start();
	//echo '<link rel="stylesheet" type="text/css" href="'.QCSBD_ASSETS_URL.'/css/directory-style.css" />';
    $count = 1;
    $listCount = 30111;
    $numberOfItems = count( $arrayOfElements );

    echo '<ul class="widget-pd-list">';
    
    foreach( $arrayOfElements as $item ){
		
		if($multipage==true && pd_ot_get_option('pd_widget_link_multipage')=='on'){
			$url = home_url().'/'.get_post_field( 'post_name', get_queried_object_id() ).'/'.$item['item_category'].'/'.str_replace('-',' ',strtolower($item['item_parent'])).'/'.urlencode(str_replace(' ','-',strtolower($item['item_title']))).'/'.$item['item_timelaps'];
		}else{
			$url = $item['item_link'];
		}
		
    	?>
    	<li id="item-<?php echo $item['item_parent_id'] ."-". $listCount; ?>">
			<a <?php echo (isset($item['item_nofollow']) && $item['item_nofollow'] == 1) ? 'rel="nofollow"' : ''; ?> <?php echo (isset($item['item_newtab']) && $item['item_newtab'] == 1) ? 'target="_blank"' : ''; ?> href="<?php echo $url; ?>">

				<?php if( !empty($item['item_img']) && $item['item_img'][0] != "" ) : ?>
				
					<img class="widget-avatar" src="<?php echo $item['item_img'][0]; ?>" alt="">

				<?php else : ?>

					<img class="widget-avatar" src="<?php echo QCSBD_IMG_URL; ?>/list-image-placeholder.png" alt="">

				<?php endif; ?>

				<?php echo $item['item_title']; ?>

				<?php if( $enableUpvoting == 'on' ) : ?>

				<div class="widget-vcount">
				
					<div class="upvote-section">
						
						<span data-post-id="<?php echo $item['item_parent_id']; ?>" data-item-title="<?php echo $item['item_title']; ?>" data-item-link="<?php echo $item['item_link']; ?>" class="sbd-upvote-btn upvote-on">
							<span class="opening-bracket">
								(
							</span>
							<i class="fa fa-thumbs-up"></i>
							<span class="upvote-count">
								<?php echo $item['item_votes']; ?>
							</span>
							<span class="closing-bracket">
								)
							</span>
						</span>	
						
					</div>

				</div>

				<?php endif; ?>

			</a>
		</li>
    	<?php

    	if( $numberOfItems > $limit )
    	{
    		if( $limit == $count )
    		{
    			break;
    		} //if $limit == $count

    	} //if $numberOfItems > $limit

    	$count++;
    	$listCount++;

    } //End Foreach

    echo '</ul>';

    $content = ob_get_clean();

    return $content;

} //End of qcpd_get_latest_links_wi

function sbd_custom_sort_by_entry_time($a, $b) {
    return strtotime( $a['item_time'] ) < strtotime( $b['item_time'] );
}

function sbd_featured_at_top($lists){
	
	$featured = array();
	foreach($lists as $k=>$v){
		if(isset($v['qcpd_featured']) and $v['qcpd_featured']==1){
			unset($lists[$k]);
			$featured[] = $v;
		}
	}
	return array_merge($featured,$lists);
}

function sbdRadiusSearch(){
?>
<div class="sbd_radius_search">

<?php 
if(pd_ot_get_option('sbd_lan_distant_search')!=''){
	$srcplaceholder = pd_ot_get_option('sbd_lan_distant_search');
}else{
	$srcplaceholder = __('Distance Search', 'qc-pd');
}
?>
	<label><?php echo $srcplaceholder; ?></label>
	<input type="text" name="location_name" placeholder="<?php echo (pd_ot_get_option('sbd_lan_city')!=''?pd_ot_get_option('sbd_lan_city'):__('City/Address/Zip code', 'qc-pd')); ?>" id="sbd_location_name" class="sbd_location_name" />
	<?php if(pd_ot_get_option('sbd_enable_current_location')=='on'): ?>
	<div class="sbd_current_location"><i class="fa fa-location-arrow"></i> <?php echo (pd_ot_get_option('sbd_lan_current_location')!=''?pd_ot_get_option('sbd_lan_current_location'):__('Current Location', 'qc-pd')); ?></div>
	<?php endif; ?>
	<input type="text" name="distance" placeholder="<?php echo (pd_ot_get_option('sbd_lan_distance_ex')!=''?pd_ot_get_option('sbd_lan_distance_ex'):__('Distance. Ex: 50', 'qc-pd')); ?>" class="sbd_distance" />
	<select class="sdb_distance_cal">
	<?php if(pd_ot_get_option('pd_distance_unit')=='km'): ?>
		<option value="km"><?php echo (pd_ot_get_option('sbd_lan_km')!=''?pd_ot_get_option('sbd_lan_km'):__('KM', 'qc-pd')); ?></option>
		<option value="miles"><?php echo (pd_ot_get_option('sbd_lan_miles')!=''?pd_ot_get_option('sbd_lan_miles'):__('Miles', 'qc-pd')); ?></option>
	<?php else:?>
		<option value="miles"><?php echo (pd_ot_get_option('sbd_lan_miles')!=''?pd_ot_get_option('sbd_lan_miles'):__('Miles', 'qc-pd')); ?></option>
		<option value="km"><?php echo (pd_ot_get_option('sbd_lan_km')!=''?pd_ot_get_option('sbd_lan_km'):__('KM', 'qc-pd')); ?></option>
	<?php endif; ?>
		
	</select>
	<button onclick="sbdradius_()" class="sbd_radius_find pd-add-btn"><?php echo (pd_ot_get_option('sbd_lan_find')!=''?pd_ot_get_option('sbd_lan_find'):__('Find', 'qc-pd')); ?></button>
	<button onclick="sbdclearradius_()" class="sbd_radius_clear pd-add-btn"><?php echo (pd_ot_get_option('sbd_lan_clear')!=''?pd_ot_get_option('sbd_lan_clear'):__('Clear', 'qc-pd')); ?></button>
</div>
<?php
}

function show_tag_filter_dropdown($args){
	if(!empty($args)){
		$listItems = get_posts( $args );
		$tags = array();
		foreach($listItems as $item){
			$configs = get_post_meta( $item->ID, 'qcpd_list_item01' );
			foreach($configs as $config){
				if(isset($config['qcpd_tags']) && $config['qcpd_tags']!=''){				
					foreach(explode(',',$config['qcpd_tags']) as $itm){
						if(!in_array($itm, $tags)){
							array_push($tags, $itm);
						}
					}				
				}
			}
		}
		sort($tags);
		?>
		<div class="sbd_tag_filter_dropdown">
			<span class="sbd_tag_filter_dropdown_label"><?php echo (pd_ot_get_option('sbd_lan_tags')!=''?pd_ot_get_option('sbd_lan_tags'):__('Tags', 'qc-pd')); ?> </span> 
			<select class="sbd_tag_filter_select">
				<option value=""><?php echo (pd_ot_get_option('sbd_lan_all')!=''?pd_ot_get_option('sbd_lan_all'):__('All', 'qc-pd')); ?></option>
				<?php foreach($tags as $tag): ?>
				<option value="<?php echo $tag; ?>"><?php echo $tag; ?></option>
				<?php endforeach; ?>
			</select>
		</div>
		<?php
	}
}

function show_tag_filter($category='', $shortcodeAtts=array()){
	
	$args = array(
		'numberposts' => -1,
		'post_type'   => 'pd',
	);
	
	if($category!=''){
		$taxArray = array(
			array(
				'taxonomy' => 'pd_cat',
				'field'    => 'slug',
				'terms'    => $category,
			),
		);

		$args = array_merge($args, array( 'tax_query' => $taxArray ));
	}
	
	if( $shortcodeAtts['mode'] == 'one' ){
		if( isset($shortcodeAtts['list_id']) && !empty($shortcodeAtts['list_id']) ){
			$args['post__in'] = array($shortcodeAtts['list_id']);
		}
	}
	
	$listItems = get_posts( $args );
	$tags = array();
	foreach($listItems as $item){
		$configs = get_post_meta( $item->ID, 'qcpd_list_item01' );
		foreach($configs as $config){
			if(isset($config['qcpd_tags']) && $config['qcpd_tags']!=''){				
				foreach(explode(',',$config['qcpd_tags']) as $itm){
					if(!in_array($itm, $tags)){
						array_push($tags, $itm);
					}
				}				
			}
		}
	}
	sort($tags);

	?>
	<div class="sbd-tag-filter-area <?php if( pd_ot_get_option('pd_enable_tag_filter_dropdown_mobile') == 'on' ){echo 'sbd-tag-filter-hide-mobile'; } ?>">
		<?php echo (pd_ot_get_option('sbd_lan_tags')!=''?pd_ot_get_option('sbd_lan_tags'):__('Tags', 'qc-pd')); ?> : 
		<a class="pd_tag_filter" data-tag=""><?php echo (pd_ot_get_option('sbd_lan_all')!=''?pd_ot_get_option('sbd_lan_all'):__('All', 'qc-pd')); ?></a>
		<?php foreach($tags as $tag): ?>
		<a class="pd_tag_filter" data-tag="<?php echo $tag; ?>"><?php echo $tag; ?></a>
		<?php endforeach; ?>
	
	</div>
	<?php
	if( pd_ot_get_option('pd_enable_tag_filter_dropdown_mobile') == 'on' ){
		echo '<div class="pd_tag_filter_dropdown_mobile">';
			show_tag_filter_dropdown($args);
		echo '</div>';
	}
	
}

function sld_get_web_page( $url )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        CURLOPT_SSL_VERIFYPEER => false,     // Disabled SSL Cert checks
        CURLOPT_USERAGENT	=> 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'
    );
    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );
    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;
    return $content;
}

//filter by upvotes
function sbd_filter_by_upvote($lists){
	$upvotesarray = array();
	if(!empty($lists)){
		
		foreach($lists as $k=>$v){
			if($v['qcpd_upvote_count']>0){
				$upvotesarray[] = $v;
				unset($lists[$k]);
			}
		}
		
		
		if(!empty($upvotesarray)){
			usort($upvotesarray, "pd_custom_sort_by_tpl_upvotes");
		}
		$reindexed_array = array_values($lists);
		return array_merge($upvotesarray,$reindexed_array);
	}else{
		return array();
	}
}

function sbd_new_expired($id){
	//$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE post_id = ".get_the_ID()." AND meta_key = 'qcopd_list_item01' order by `meta_id` ASC");
	$metas = get_post_meta($id, 'qcpd_list_item01');
	$expire = pd_ot_get_option('sbd_new_expire_after');
	$expire_date = date('Y-m-d H:i:s',strtotime("-$expire days"));
	
	foreach($metas as $meta){

		
		if(isset($meta['qcpd_entry_time']) && strtotime($meta['qcpd_entry_time']) < strtotime($expire_date)){
			if(isset($meta['qcpd_new'])){
				unset($meta['qcpd_new']);
			}
		}
	}
	delete_post_meta($id, 'qcpd_list_item01');
	foreach($metas as $meta){
		add_post_meta( $id, 'qcpd_list_item01', $meta );
	}
	
	
}

// Package Expire Notification

function sbd_send_package_expire_notification($package){
	
	global $wpdb;

	$package_table = $wpdb->prefix.'pd_package';
	
	$user = get_user_by( 'ID', $package->user_id );
	$package_info = $wpdb->get_row("select * from $package_table where 1 and id = ".$package->id." ");
	
	$email_content = pd_ot_get_option('pd_package_expire_email');
	$email_content = str_replace(array('#user_name','#package_name','#expire_date','#create_date'),array($user->user_login, $package_info->title, date("d/m/Y", strtotime($package->expire_date)), date("d/m/Y", strtotime($package->date))),$email_content);

	$sbd_lan_email_package_expired = (pd_ot_get_option('sbd_lan_email_package_expired')!=''?pd_ot_get_option('sbd_lan_email_package_expired'):__('Your package has been expired!', 'qc-pd'));

	@wp_mail($user->user_email, sprintf(__('[%s] %s %s!'), get_option('blogname'), $sbd_lan_email_package_expired, get_option('blogname')), $email_content);
	
}

function sbd_is_linkedin($url){
	if(strpos($url, 'linkedin') !== false){
		return true;
	}else{
		return false;
	}
}

function sbd_remove_duplicate_master($post_id){
	
	if(pd_ot_get_option('pd_auto_remove_dup_item')=='on'){
		if($post_id!=''){
			$datas = get_post_meta($post_id, 'qcpd_list_item01');	
			
			$tempArr = array_unique(array_column($datas, 'qcpd_item_title'));		
			
			$new_datas = array_intersect_key($datas, $tempArr);		
			if(count($datas) != count($new_datas) and count($datas)>count($new_datas)){
				delete_post_meta($post_id, 'qcpd_list_item01');
				foreach($new_datas as $value){
					add_post_meta( $post_id, 'qcpd_list_item01', $value );
				}
			}
		}
	}
	
}
if ( ! function_exists( 'sbd_minify_html' ) ) {

    function sbd_minify_html( $html ) {

        if ( preg_match( '/(\s){2,}/s', $html ) === 1 ) {

            return preg_replace( '/(\s){2,}/s', '', $html );

        }

    }

}
function qc_sbd_custom_body($list){
	ob_start();
	
	if(pd_ot_get_option('sbd_field_1_enable')=='on' and isset($list['qcpd_field_1']) and $list['qcpd_field_1']!=''){
		if(pd_ot_get_option('sbd_field_1_type')=='text'){
			?>
			<span class='top-address sbd_custom_field' style='display:block;'><?php echo (pd_ot_get_option('sbd_field_1_label')!=''?'<b>'.pd_ot_get_option('sbd_field_1_label').':</b>&nbsp;':'') ?><?php echo $list['qcpd_field_1']; ?></span>
			<?php
		}
	}
	if(pd_ot_get_option('sbd_field_2_enable')=='on' and isset($list['qcpd_field_2']) and $list['qcpd_field_2']!=''){
		if(pd_ot_get_option('sbd_field_2_type')=='text'){
			?>
			<span class='top-address sbd_custom_field' style='display:block;'><?php echo (pd_ot_get_option('sbd_field_2_label')!=''?'<b>'.pd_ot_get_option('sbd_field_2_label').':</b>&nbsp;':'') ?><?php echo $list['qcpd_field_2']; ?></span>
			<?php
		}
	}
	if(pd_ot_get_option('sbd_field_3_enable')=='on' and isset($list['qcpd_field_3']) and $list['qcpd_field_3']!=''){
		if(pd_ot_get_option('sbd_field_3_type')=='text'){
			?>
			<span class='top-address sbd_custom_field' style='display:block;'><?php echo (pd_ot_get_option('sbd_field_3_label')!=''?'<b>'.pd_ot_get_option('sbd_field_3_label').':</b>&nbsp;':'') ?><?php echo $list['qcpd_field_3']; ?></span>
			<?php
		}
	}
	if(pd_ot_get_option('sbd_field_4_enable')=='on' and isset($list['qcpd_field_4']) and $list['qcpd_field_4']!=''){
		if(pd_ot_get_option('sbd_field_4_type')=='text'){
			?>
			<span class='top-address sbd_custom_field' style='display:block;'><?php echo (pd_ot_get_option('sbd_field_4_label')!=''?'<b>'.pd_ot_get_option('sbd_field_4_label').':</b>&nbsp;':'') ?><?php echo $list['qcpd_field_4']; ?></span>
			<?php
		}
	}
	if(pd_ot_get_option('sbd_field_5_enable')=='on' and isset($list['qcpd_field_5']) and $list['qcpd_field_5']!=''){
		if(pd_ot_get_option('sbd_field_5_type')=='text'){
			?>
			<span class='top-address sbd_custom_field' style='display:block;'><?php echo (pd_ot_get_option('sbd_field_5_label')!=''?'<b>'.pd_ot_get_option('sbd_field_5_label').':</b>&nbsp;':'') ?><?php echo $list['qcpd_field_5']; ?></span>
			<?php
		}
	}
	
	$content = ob_get_clean();
	
    return sbd_minify_html($content);
}

function qc_sbd_custom_icon($list){
	ob_start();
	if(pd_ot_get_option('sbd_field_1_enable')=='on' and isset($list['qcpd_field_1']) and $list['qcpd_field_1']!='' and pd_ot_get_option('sbd_field_1_type')!='text'){
		if(pd_ot_get_option('sbd_field_1_type')=='link'){
			?>
			<p><a target="_blank" href="<?php echo $list['qcpd_field_1']; ?>"><i class="fa <?php echo (pd_ot_get_option('sbd_field_1_icon')!=''?pd_ot_get_option('sbd_field_1_icon'):'fa-sun-o'); ?>"></i></a></p>
			<?php
		}elseif(pd_ot_get_option('sbd_field_1_type')=='phone'){
			?>
			<p><a target="_blank" href="tel:<?php echo $list['qcpd_field_1']; ?>"><i class="fa <?php echo (pd_ot_get_option('sbd_field_1_icon')!=''?pd_ot_get_option('sbd_field_1_icon'):'fa-sun-o'); ?>"></i></a></p>
			<?php
		}
	}
	if(pd_ot_get_option('sbd_field_2_enable')=='on' and isset($list['qcpd_field_2']) and $list['qcpd_field_2']!='' and pd_ot_get_option('sbd_field_2_type')!='text'){
		if(pd_ot_get_option('sbd_field_2_type')=='link'){
			?>
			<p><a target="_blank" href="<?php echo $list['qcpd_field_2']; ?>"><i class="fa <?php echo (pd_ot_get_option('sbd_field_2_icon')!=''?pd_ot_get_option('sbd_field_2_icon'):'fa-sun-o'); ?>"></i></a></p>
			<?php
		}elseif(pd_ot_get_option('sbd_field_2_type')=='phone'){
			?>
			<p><a target="_blank" href="tel:<?php echo $list['qcpd_field_2']; ?>"><i class="fa <?php echo (pd_ot_get_option('sbd_field_2_icon')!=''?pd_ot_get_option('sbd_field_2_icon'):'fa-sun-o'); ?>"></i></a></p>
			<?php
		}
	}
	if(pd_ot_get_option('sbd_field_3_enable')=='on' and isset($list['qcpd_field_3']) and $list['qcpd_field_3']!='' and pd_ot_get_option('sbd_field_3_type')!='text'){
		if(pd_ot_get_option('sbd_field_3_type')=='link'){
			?>
			<p><a target="_blank" href="<?php echo $list['qcpd_field_3']; ?>"><i class="fa <?php echo (pd_ot_get_option('sbd_field_3_icon')!=''?pd_ot_get_option('sbd_field_3_icon'):'fa-sun-o'); ?>"></i></a></p>
			<?php
		}elseif(pd_ot_get_option('sbd_field_3_type')=='phone'){
			?>
			<p><a target="_blank" href="tel:<?php echo $list['qcpd_field_3']; ?>"><i class="fa <?php echo (pd_ot_get_option('sbd_field_3_icon')!=''?pd_ot_get_option('sbd_field_3_icon'):'fa-sun-o'); ?>"></i></a></p>
			<?php
		}
	}
	if(pd_ot_get_option('sbd_field_4_enable')=='on' and isset($list['qcpd_field_4']) and $list['qcpd_field_4']!='' and pd_ot_get_option('sbd_field_4_type')!='text'){
		if(pd_ot_get_option('sbd_field_4_type')=='link'){
			?>
			<p><a target="_blank" href="<?php echo $list['qcpd_field_4']; ?>"><i class="fa <?php echo (pd_ot_get_option('sbd_field_4_icon')!=''?pd_ot_get_option('sbd_field_4_icon'):'fa-sun-o'); ?>"></i></a></p>
			<?php
		}elseif(pd_ot_get_option('sbd_field_4_type')=='phone'){
			?>
			<p><a target="_blank" href="<?php echo $list['qcpd_field_4']; ?>"><i class="fa <?php echo (pd_ot_get_option('sbd_field_4_icon')!=''?pd_ot_get_option('sbd_field_4_icon'):'fa-sun-o'); ?>"></i></a></p>
			<?php
		}
	}
	if(pd_ot_get_option('sbd_field_5_enable')=='on' and isset($list['qcpd_field_5']) and $list['qcpd_field_5']!='' and pd_ot_get_option('sbd_field_5_type')!='text'){
		if(pd_ot_get_option('sbd_field_5_type')=='link'){
			?>
			<p><a target="_blank" href="<?php echo $list['qcpd_field_5']; ?>"><i class="fa <?php echo (pd_ot_get_option('sbd_field_5_icon')!=''?pd_ot_get_option('sbd_field_5_icon'):'fa-sun-o'); ?>"></i></a></p>
			<?php
		}elseif(pd_ot_get_option('sbd_field_5_type')=='phone'){
			?>
			<p><a target="_blank" href="tel:<?php echo $list['qcpd_field_5']; ?>"><i class="fa <?php echo (pd_ot_get_option('sbd_field_5_icon')!=''?pd_ot_get_option('sbd_field_5_icon'):'fa-sun-o'); ?>"></i></a></p>
			<?php
		}
	}
	$content = ob_get_clean();
	
    return sbd_minify_html($content);
}

function sbd_icons_content($section, $url=''){
	
	switch ($section) {
		case "phone":
			echo (pd_ot_get_option('pd_phone_icon_text')!=''?pd_ot_get_option('pd_phone_icon_text'):'<i class="fa fa-phone"></i>');
			break;
		case "link":
			echo (pd_ot_get_option('pd_link_icon_text')!=''?pd_ot_get_option('pd_link_icon_text'):'<i class="fa fa-link"></i>');
			break;
		case "facebook":
			echo (pd_ot_get_option('pd_facebook_icon_text')!=''?pd_ot_get_option('pd_facebook_icon_text'):'<i class="fa fa-facebook"></i>');
			break;
		case "yelp":
			echo (pd_ot_get_option('pd_yelp_icon_text')!=''?pd_ot_get_option('pd_yelp_icon_text'):'<i class="fa fa-yelp"></i>');
			break;
		case "email":
			echo (pd_ot_get_option('pd_email_icon_text')!=''?pd_ot_get_option('pd_email_icon_text'):'<i class="fa fa-envelope"></i>');
			break;
		case "linkedin":
			if( sbd_is_linkedin($url) ){
				echo (pd_ot_get_option('pd_linkedin_icon_text')!=''?pd_ot_get_option('pd_linkedin_icon_text'):'<i class="fa fa-linkedin-square fa-linkedin"></i>');
			}else{
				echo (pd_ot_get_option('pd_linkedin_icon_text')!=''?pd_ot_get_option('pd_linkedin_icon_text'):'<i class="fa fa-instagram"></i>');
			}
			break;
		case "twitter":
			echo (pd_ot_get_option('pd_twitter_icon_text')!=''?pd_ot_get_option('pd_twitter_icon_text'):'<i class="fa fa-twitter-square"></i>');
			break;
		case "map":
			echo (pd_ot_get_option('pd_map_icon_text')!=''?pd_ot_get_option('pd_map_icon_text'):'<i class="fa fa-map"></i>');
			break;
		case "info":
			echo (pd_ot_get_option('pd_info_icon_text')!=''?pd_ot_get_option('pd_info_icon_text'):'<i class="fa fa-info-circle"></i>');
			break;
		
	}
}

function qc_sbd_get_list_items($listid){
	global $wpdb;
	$lists = array();
	if($listid!=''){
		$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE post_id = ".$listid." AND meta_key = 'qcpd_list_item01' order by `meta_id` ASC");
		
		if(!empty($results)){
			foreach($results as $result){
				$unserialize = unserialize($result->meta_value);
				
				if(!isset($unserialize['qcpd_unpublished']) or $unserialize['qcpd_unpublished']==0){					
					if(isset($unserialize['qcpd_ex_date']) && $unserialize['qcpd_ex_date']!='' && date('Y-m-d') > $unserialize['qcpd_ex_date']){
						//
					}else{
						$lists[] = $unserialize;
					}
				}
					
			}
		}
	}
	return $lists;
}


function sld_pagination_links( $sld_paged=1, $total_pagination_page=0, $post_id=0){
	if( $post_id > 0 &&  $total_pagination_page > 0 ){	
		$pagination_links = sld_paginate_links(array(
	        'current'=>max(1,$sld_paged),
	        'total'=>$total_pagination_page,
	        'type'=>'array', //default it will return anchor,
	        'mid_size'=> 1,
	        'list_id' => $post_id,
	        'end_size'=> 3,
	        'format' => '?sld_paged=%#%&sld_list_id='.$post_id,
	        'prev_text' => __( '&laquo;' ),
			'next_text' => __( '&raquo;' ),
	    ));

		echo "<div class='sld-page-numbers-container'>\n\t";
		// join( "</div>\n\t<div class='sld-page-numbers-item'>", $pagination_links );
		foreach ($pagination_links as $links) {
	    	echo ( "<div class='sld-page-numbers-item'>". $links."</div>\n\t" );
		}
	    echo "</div>\n";
	}
}

function sld_paginate_links( $args = '' ) {
    global $wp_query, $wp_rewrite;
 
    // Setting up default values based on the current URL.
    $pagenum_link = html_entity_decode( get_pagenum_link() );
    $url_parts    = explode( '?', $pagenum_link );
 
    // Get max pages and current page out of the current query, if available.
    $total   = isset( $wp_query->max_num_pages ) ? $wp_query->max_num_pages : 1;
    $current = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1;
    
    $sld_list_id = isset($_GET['sld_list_id']) && intval( $_GET['sld_list_id'] > 0 ) ? $_GET['sld_list_id'] : 0;

    // Append the format placeholder to the base URL.
    $pagenum_link = trailingslashit( $url_parts[0] ) . '%_%';
 
    // URL base depends on permalink settings.
    $format  = $wp_rewrite->using_index_permalinks() && ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : '';
    $format .= $wp_rewrite->using_permalinks() ? user_trailingslashit( $wp_rewrite->pagination_base . '/%#%', 'paged' ) : '?paged=%#%';
 
    $defaults = array(
        'base'               => $pagenum_link, // http://example.com/all_posts.php%_% : %_% is replaced by format (below)
        'format'             => $format, // ?page=%#% : %#% is replaced by the page number
        'total'              => $total,
        'current'            => $current,
        'aria_current'       => 'page',
        'show_all'           => false,
        'prev_next'          => true,
        'prev_text'          => __( '&laquo; Previous' ),
        'next_text'          => __( 'Next &raquo;' ),
        'end_size'           => 1,
        'mid_size'           => 2,
        'type'               => 'plain',
        'add_args'           => array(), // array of query args to add
        'add_fragment'       => '',
        'before_page_number' => '',
        'after_page_number'  => '',
    );
 
    $args = wp_parse_args( $args, $defaults );
 
    if ( ! is_array( $args['add_args'] ) ) {
        $args['add_args'] = array();
    }
 
    // Merge additional query vars found in the original URL into 'add_args' array.
    if ( isset( $url_parts[1] ) ) {
        // Find the format argument.
        $format       = explode( '?', str_replace( '%_%', $args['format'], $args['base'] ) );
        $format_query = isset( $format[1] ) ? $format[1] : '';
        wp_parse_str( $format_query, $format_args );
 
        // Find the query args of the requested URL.
        wp_parse_str( $url_parts[1], $url_query_args );
 
        // Remove the format argument from the array of query arguments, to avoid overwriting custom format.
        foreach ( $format_args as $format_arg => $format_arg_value ) {
            unset( $url_query_args[ $format_arg ] );
        }
 
        $args['add_args'] = array_merge( $args['add_args'], urlencode_deep( $url_query_args ) );
    }
 
    // Who knows what else people pass in $args
    $total = (int) $args['total'];
    if ( $total < 2 ) {
        return;
    }
    $current  = (int) $args['current'];
    $end_size = (int) $args['end_size']; // Out of bounds?  Make it the default.
    if ( $end_size < 1 ) {
        $end_size = 1;
    }
    $mid_size = (int) $args['mid_size'];
    if ( $mid_size < 0 ) {
        $mid_size = 2;
    }
 
    $add_args   = $args['add_args'];
    $r          = '';
    $page_links = array();
    $dots       = false;
 
    if ( $args['prev_next'] && $current && 1 < $current ) :
        $link = str_replace( '%_%', 2 == $current ? '' : $args['format'], $args['base'] );
        $link = str_replace( '%#%', $current - 1, $link );
        if ( $add_args ) {
            $link = add_query_arg( $add_args, $link );
        }
        $link .= $args['add_fragment'];
 
        $page_links[] = sprintf(
            '<a class="prev page-numbers" href="%s">%s</a>',
            /**
             * Filters the paginated links for the given archive pages.
             *
             * @since 3.0.0
             *
             * @param string $link The paginated link URL.
             */
            esc_url( apply_filters( 'paginate_links', $link ) ),
            $args['prev_text']
        );
    endif;

    for ( $n = 1; $n <= $total; $n++ ) :
        if ( $n == $current && $sld_list_id == $args['list_id'] ) :
            $page_links[] = sprintf(
                '<span aria-current="%s" class="page-numbers current">%s</span>',
                esc_attr( $args['aria_current'] ),
                $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number']
            );
 
            $dots = true;
        else :
            if ( $args['show_all'] || ( $n <= $end_size || ( $current && $n >= $current - $mid_size && $n <= $current + $mid_size ) || $n > $total - $end_size ) ) :
                $link = str_replace( '%_%', 1 == $n ? '' : $args['format'], $args['base'] );
                $link = str_replace( '%#%', $n, $link );
                if ( $add_args ) {
                    $link = add_query_arg( $add_args, $link );
                }
                $link .= $args['add_fragment'];
 
                $page_links[] = sprintf(
                    '<a class="page-numbers" href="%s">%s</a>',
                    /** This filter is documented in wp-includes/general-template.php */
                    esc_url( apply_filters( 'paginate_links', $link ) ),
                    $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number']
                );
 
                $dots = true;
            elseif ( $dots && ! $args['show_all'] ) :
                $page_links[] = '<span class="page-numbers dots">' . __( '&hellip;' ) . '</span>';
 
                $dots = false;
            endif;
        endif;
    endfor;
 
    if ( $args['prev_next'] && $current && $current < $total ) :
        $link = str_replace( '%_%', $args['format'], $args['base'] );
        $link = str_replace( '%#%', $current + 1, $link );
        if ( $add_args ) {
            $link = add_query_arg( $add_args, $link );
        }
        $link .= $args['add_fragment'];
 
        $page_links[] = sprintf(
            '<a class="next page-numbers" href="%s">%s</a>',
            /** This filter is documented in wp-includes/general-template.php */
            esc_url( apply_filters( 'paginate_links', $link ) ),
            $args['next_text']
        );
    endif;
 
    switch ( $args['type'] ) {
        case 'array':
            return $page_links;
 
        case 'list':
            $r .= "<ul class='page-numbers'>\n\t<li>";
            $r .= join( "</li>\n\t<li>", $page_links );
            $r .= "</li>\n</ul>\n";
            break;
 
        default:
            $r = join( "\n", $page_links );
            break;
    }
 
    return $r;
}

function sbd_display_claim_badge( $list ){
	if( pd_ot_get_option('pd_enable_claim_badge') == 'on' ){
		global $wpdb;
		$timelaps = $list['qcpd_timelaps'];
		$table = $wpdb->prefix.'pd_user_entry';
		$query = $wpdb->get_var( 
                    "SELECT COUNT(id) FROM $table WHERE item_link = '".$list['qcpd_item_link']."' AND custom = '$timelaps'"
                 );
		if( $query > 0 ){
			return true;
		}
	}
	return false;
}