<?php 
/* 
	Plugin Name: DigitalAccessPass LiveLinks
	Plugin URI: http://www.DigitalAccessPass.com
	Description: DigitalAccessPass is a Premium Membership Plugin for WordPress that can "Drip" WordPress Posts, Pages, Categories and Custom Post Types, has a built-in Shopping Cart, Email Autoresponders & Broadcasting, Affiliate Program, File Protection and lots more!
	Author: DigitalAccessPass.com
	Author URI: https://www.DigitalAccessPass.com
	Version: 5.7.1
/*
	For sites that have a sub-domain problem, do the following:
	
	1. Go to the folder where dap is supposed to be installed. Do a getpath in that folder. Get the path (let's call it NEWPATH)
	2. Add these two lines of code somewhere towards the middle, after any existing similar if(!defined...) statement, within wp-config.php
		if ( !defined('SITEROOT') )
			define('SITEROOT', '/home/content/html');
	3. Try to activate LiveLinks.
	4. If you get an error saying NEWPATH/dap/dap-config.php cannot be found, 
		then create dap-config.php manually by copying db settings from wp-config.php, 
		and upload to dap folder, and now try activating LiveLinks again.
	
	That's it!
*/

//require_once(ABSPATH.'wp-includes/pluggable.php');
$lldocroot = defined('SITEROOT') ? SITEROOT : $_SERVER['DOCUMENT_ROOT'];
if( isset($_SESSION["lldocroot"]) && ($_SESSION["lldocroot"] != "") ) {
  //logToFile("DAP-LiveLinks-session, docroot=".$_SESSION["lldocroot"]); 
  $lldocroot = $_SESSION["lldocroot"];
}

if(file_exists($lldocroot . "/dap/dap-config.php")) include_once ($lldocroot . "/dap/dap-config.php");

require_once ($lldocroot . "/dap/inc/classes/Dap_Base.class.php");
require_once ($lldocroot . "/dap/inc/classes/Dap_Session.class.php");
require_once("DAP-LoginLogout.php");
require_once("DAP-Product-Links.php");
require_once("DAP-ShortCodes-UserLinks.php");
require_once("DAP-ShortCodes-ComingSoon.php");
require_once("DAP-ShortCodes-UserProfile.php");
require_once("DAP-Upline.php");
require_once("DAP-Auto-Cancellation.php");
require_once("DAP-ShortCodes-Transactions.php");
require_once("DAP-User-Subscription.php");
require_once("DAPUpgradeButton.php");
require_once("DAP-ShortCodes-RefAffId.php");
require_once("DAP-1ClickBuy.php");
require_once("DAP-AutoConfigUpdate.php");
require_once("DAP-Protected-Content.php");

// add post meta
require_once("DAP-Post-Metabox.php"); 

require_once("DAP-ShortCodes-FormBuilder.php"); 

	
if(! is_admin()){  
	require_once("DAP-ShortCodes-Frontend.php"); 
	require_once("DAP-LessonComplete.php"); 
	require_once("DAP-AllCertificate.php"); 
	include_once("DAP-CourseProgressBar-Frontend.php"); 
}


/*****Add shortcode starts*********/
if ( !is_admin() ){
	add_shortcode('DAPMyContent', 'dap_mycontentshortcode');
	add_shortcode('DAPMyProfile', 'dap_myprofileshortcode');
	add_shortcode('DAPAffiliateInfo', 'dap_affiliate_detailsshortcode');
	add_shortcode('DAPLoginForm', 'dap_loginformshortcode');
	add_shortcode('DAPShowTransactions', 'dap_displaytransactionsshortcode');
	add_shortcode('DAPUMemberSubscriptions', 'dap_membersubscriptionshortcode');
	add_shortcode('DAP', 'dap_shortcodeNew');
	add_shortcode('DAPMemberInvoice', 'dap_displayInvoiceshortcode');
	add_shortcode('DAPMemberCancellation', 'dap_memberCancellationShortcode');
	add_shortcode('DAPMemberGroupUser', 'dap_memberGroupShortcode');
	add_shortcode('DAPCourseCertificate', 'dapCertificateShortcode');
	add_shortcode('DAPALLCertificates', 'dapallCertificateShortcode');
	
	$_SESSION['showPPP'] = 'yes';
	$_SESSION['pppposts_id'] = '';
}
add_filter('widget_text', 'do_shortcode');
add_shortcode('DAPLoginFormPermalink', 'dap_loginform_permalinkshortcode');


function add_tags_to_pages() {
register_taxonomy_for_object_type( 'post_tag', 'page' );
}
add_action( 'init', 'add_tags_to_pages');

/*******Add shortcode ends*******/

/*
require_once("DAP-ShortCodes.php");
require_once("DAP-ShortCodes-MemberPages.php"); 
require_once("DAP-ShortCodes-MyContent.php");
require_once("DAP-ShortCodes-MyProfile.php");
require_once("DAP-ShortCodes-AffiliateInfo.php");
require_once("DAP-ShortCodes-Invoice.php");
require_once("DAP-ShortCodes-Cancel.php");
require_once("DAP-ShortCodes-LoginForm.php");
require_once("DAP-Member-Subscriptions.php"); 
*/


global $current_user;

add_action('init', 'figureOutWPConfigPath');
function figureOutWPConfigPath() {
	$current_user = wp_get_current_user();
	if(!isset($_SESSION["wpconfigpath"]))
		$_SESSION["wpconfigpath"] = ABSPATH.'wp-config.php';
}

if( isset($_GET['msg']) && ($_GET['msg'] != "") ) {
	if( defined($_GET['msg']) ) {
		$_GET['msg'] = constant($_GET['msg']);
	} else {
		$_GET['msg'] = str_replace("_"," ",$_GET['msg']);
	}
	if(isset($_GET['email'])) $_GET['msg'] = $_GET['msg'] . " " . $_SESSION['email'];
}

global $reset_password;
$reset_password = "N";
//Auto-login DAP Admin (with min id) if WP Admin logs in
add_action( 'admin_init', 'dapAdminLogin' );

// open_ssl encryption update
function dapAdminLogin() {
	global $reset_password;
	global $current_user;
	logToFile("current_user->ID: " . $current_user->ID); 

	if( is_admin() && user_can($current_user->ID, 'administrator') ) {
		global $lldocroot;
		$configFileName = $lldocroot . "/dap/dap-config.php";
	
    	try{
			$saltExists = Dap_User::checkIfSaltExists();
			if(!$saltExists) {
				logToFile('DAP-WP-Livelinks.php:dapAdminLogin():Salt field doesnot exist so creating the field',LOG_DEBUG_DAP);
				Dap_User::addSaltFieldToDAPUsers();
			}
		}
		catch(Exception $e){
			logToFile('DAP-WP-Livelinks.php:dapAdminLogin():exception'.$e->getMessage(),LOG_DEBUG_DAP);
		}
		
			logToFile("DAP-WP-Livelinks.php:dapAdminLogin():HERE",LOG_DEBUG_DAP);
		if( (file_exists($configFileName)) && (!Dap_Session::isLoggedIn()) ) {
			include_once ($configFileName);
			Dap_Config::loadConfig(true);

			$use_openssl = 'N';
			/*if(defined('USE_MCRYPT') && USE_MCRYPT == 'Y')	 
			   $use_openssl = 'N';*/
			if(PHP_VERSION >= 7.2) 
			   $use_openssl = 'Y';
			   
			logToFile('DAP-WP-Livelinks.php:dapAdminLogin():use_openssl = '.$use_openssl,LOG_DEBUG_DAP);
			
			$userAdmin = Dap_User::loadAdminUserByMinIdPasswordEncryption();
			$email = $userAdmin->getEmail();
			$salt = $userAdmin->getSalt();
			
			if($salt != "")  
				$use_openssl = 'Y';
			if (Dap_Config::get("AUTOLOGIN_DAPWP_ADM") == "Y") {
				logToFile('dapAdminLogin():autologin is enabled',LOG_DEBUG_DAP); 

				if($use_openssl == "Y" ){
					logToFile('dapAdminLogin():openssl is Y ',LOG_DEBUG_DAP); 
					
					// user's current password is in mcrypt format
					// so we have to generate new password for the user so it can encrypted in openssl format and admin can be auto-logged-in

					if($salt == "" || $salt == NULL){
						logToFile("dapAdminLogin(): openssl = Y.., but salt is missing geneating password...", LOG_DEBUG_DAP); 
						try{
							$newPassword=Dap_User::GeneratePassword(10);
						}
						catch(Exception $e){
							logToFile("dapAdminLogin():Exception".$e->getMessage(), LOG_DEBUG_DAP); 
						}
						$salt = '';
						$encrypted = encryptPassword($newPassword,$email,$userid,$salt);	
					}
						
					$userAdmin = Dap_User::loadAdminUserByMinId();
					$email = $userAdmin->getEmail();
				
					$rawPassword = $userAdmin->getPassword();
					$encryptedPassword = encryptPassword($rawPassword,$email);
				  
					logToFile('dapAdminLogin():now going to validate',LOG_DEBUG_DAP); 
					if( validate($email, $rawPassword) ) {
						logToFile("WP Admin validated ok in DAP Admin in LiveLinks", LOG_DEBUG_DAP); 
						$rememberMe = "rememberMe";
						//Set cookie only if rememberMe is set. If not, no cookie is set
						//Set cookie for 2 weeks
						//logToFile("remembering...",LOG_DEBUG_DAP);
						$_SESSION["dapRememberMe"] = "dapRememberMe";
						$i = 14;
						setcookie("dapcookie_email",$email,time()+(3600*24*$i),"/");
						setcookie("dapcookie_password",$encryptedPassword,time()+(3600*24*$i),"/");
						pluginLogin($email);
					}
									
				}  //useopenssl  = Y
				else {
					//old mcrypt way or salt is not null  
					logToFile("dapAdminLogin(): openssl = N,going to validate", LOG_DEBUG_DAP); 
					$userAdmin = Dap_User::loadAdminUserByMinId();
					$email = $userAdmin->getEmail();
					$rawPassword = $userAdmin->getPassword();
					//$decryptedPassword = decryptPassword($rawPassword,$email);
					$encryptedPassword = encryptPassword($rawPassword,$email);
					
					//if(validate($email, $rawPassword) || validate($email, $decryptedPassword)) {
					if( validate($email, $rawPassword) ) {
						logToFile("WP Admin validated ok in DAP Admin in LiveLinks", LOG_DEBUG_DAP); 
						$rememberMe = "rememberMe";
						//Set cookie only if rememberMe is set. If not, no cookie is set
						//Set cookie for 2 weeks
						//logToFile("remembering...",LOG_DEBUG_DAP);
						$_SESSION["dapRememberMe"] = "dapRememberMe";
						$i = 14;
						setcookie("dapcookie_email",$email,time()+(3600*24*$i),"/");
						setcookie("dapcookie_password",$encryptedPassword,time()+(3600*24*$i),"/");
						pluginLogin($email);
					}
				}
				 
			} // autologin = Y
			else if ( ($salt == ""  || $salt == NULL) && ($use_openssl == "Y")) {
				logToFile("dapAdminLogin: autologin is disabled and also salt is missing, so will have to take user to reset password", LOG_DEBUG_DAP); 
			   //autologin is turned off. use openssl is Y but there's no salt. So we need to get users to reset their password. 
				$reset_password = "Y";
			 }

		}
	}
}



function dap_filter_posts($posts) {
		$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		$tagPostID = dap_url_to_postid($url);
		$_SESSION['showPPPMsg'] = $showPPPMsg = true;
		$errorIdSet = false;
		if(isset($posts[0]))
			$_SESSION['pppposts_id'] = $posts_id = $posts[0]->ID;		 
			
	/***Added for the thrive preview having issue, loads forever 
	 * So if thrive preview then bypass *****/	
	 /*	print_r($_REQUEST);	[tve] => true  */	 	 
	if(count($posts)<=0){return $posts;}		
	if(isset($_REQUEST['tve']) && $_REQUEST['tve'] == true){return $posts;}		
	/***ends here thrive condition*****/
	
	/***Added this line to fix the DIVI theme page not load issue in backend*****/ 
	if(isset($_REQUEST['et_fb']) && $_REQUEST['et_fb'] == 1){return $posts;}	
	
	/***Added this line to fix the elementor ,  page not load issue in backend*****/
	if(isset($_REQUEST['action']) && ($_REQUEST['action']  == "elementor" || isset($_REQUEST['elementor-preview']))){
		return $posts;
	} 
	$actions = array("elementor");
	if ( isset( $_GET['action'] ) && in_array( $_GET['action'], $actions ) || isset($_GET['elementor-preview']) ) {
		return $posts;
	}
	//end for the fix for elementor ,  page not load issue in backend
	
	global $current_user;
	
	
	//return if admin.
	//logToFile("------------------------- in dap_filter_posts"); 
	//if(is_admin()) return $posts;
	if(is_admin() && user_can($current_user->ID, 'administrator')) return $posts;
	
	if(is_feed()) {
		//logToFile("I'm a feed");
		$key = ( isset($_GET['key']) && ($_GET['key'] != "") ) ? stripslashes($_GET['key']) : "";
		if($key != "") {
			//Someone with a legit key trying to access the feed. So load user & determine access
			//logToFile("key: $key");
			$user = Dap_User::loadUserByActivationKey($key);
			if( isset($user) && ($user != null) ) {
				$session = Dap_Session::getSession();
				if( validateLogins($user->getEmail(), getIpOfUser()) ) {
					//logToFile("user is " . $user->getEmail());
					//$session->setUser($user);
					define('DAP_FEED_USER_ID',$user->getId());
				} else {
					return null;
				}
			}
		} //end if($key != "")
		/* else, if isfeed but no key, then just keep going and filter out everything */
	}
	
	$homeUrl = get_home_url();
	$homeArray = explode('/', $homeUrl);
	$blogPath = '';
	if(isset($homeArray[3])){
			$blogPath = $homeArray[3];
	}
	
	global $lldocroot;
	include_once ($lldocroot . "/dap/dap-config.php");
	dap_wp_sync();

	$sneak_peek = Dap_Config::get("SNEAK_PEEK");
	
	//If sneak-peek is on, is category and there's only 1 post in the array (like home page or archive page or category page)
	$size = count($posts);
	//logToFile("1) size: $size");
	
	if( is_category() && ($sneak_peek == "Y") && ($size = 1)  && !is_feed() ) return $posts;
	
	
	//if ( false ) {
	if ( is_category()  && ($sneak_peek == "N") ) {
		//logToFile("is category and sneak peek is N"); 
		//If error page URL is set, just redirect to that URL
		global $wp_query;
		$cat_obj = $wp_query->get_queried_object();
		//logToFile( $cat_obj->name . " has id ". $cat_obj->term_id );

		$cat_permalink = get_category_link($cat_obj->term_id);
		$cat_permalink = getResourceFromString($cat_permalink);
		//logToFile("cat_permalink: $cat_permalink"); 
		
		$resource = isURLAllowed($cat_permalink, $tagPostID, $blogPath);
		$showPPPMsg = $_SESSION['showPPPMsg'];
		$errId = $resource->getError_id();
		if(isset($errId)) {
			//logToFile("Protected category"); 
			//protected category
			$errorPageURL = Dap_Config::get("SITEWIDE_ERROR"); //initially point to global error page
			//logToFile("errorPageURL: " . $errorPageURL); 
			$productCount = Dap_Product::isPartOfHowManyDistinctProducts($cat_permalink);
			//logToFile("category permalink: productCount: $productCount");
			if( $productCount == 1 ) {
				//logToFile("productCount is 1"); 
				$product = Dap_Product::getProductDetailsByResource($cat_permalink);
				$productErrorPageURL = $product->getError_page_url();
				if ( ($productErrorPageURL != "") && ($productErrorPageURL != "/dap/product-error.php") )  {
					$errorPageURL = $productErrorPageURL; 
				}
			}			
			
			//logToFile("errorPageURL: $errorPageURL"); 
			if ( ($errorPageURL != "") && ($errorPageURL != "/dap/product-error.php") )  {
				//Redirect to product-specific error page
				//logToFile("Redirecting to product-specific error page " . $errorPageURL); 
				@header( "Location: " . $errorPageURL );
				exit;
			}
			$errorIdSet =true;
		} 
		
	}

	//If sneak-peek is on, and there's more than 1 post in the array (like home page or archive page or category page)
	$size = count($posts);
	//logToFile("2) size: $size");
	if( ($sneak_peek == "Y") && ($size > 1)  && !is_feed() ) return $posts;
	
	
	$permalink = null;
	$unsetAtleastOne = false;
	$session = Dap_Session::getSession();
	$user = $session->getUser();
	$errId = null;
	

	
	
	if(defined('FORNULL')) { $errId = 0; } else { $errId = null; }   
	if(defined('FORNULL')) { $permalink = 0; } else { $permalink = null; }   
	
	for ($i=0; $i < $size; $i++) {
		//logToFile("Going through individual posts"); 
		$postId = $posts[$i]->ID;
		$permalink = get_permalink($postId);
		$permalink = getResourceFromString($permalink);
		//logToFile("Permalink: $permalink",LOG_DEBUG_DAP); 
		$resource = isURLAllowed($permalink, $tagPostID, $blogPath);
		$showPPPMsg = $_SESSION['showPPPMsg'];
		$errId = $resource->getError_id();
		if(isset($user)){
			$userId = $user->getId();
		}
		
		if(isset($errId)) {
			$pppresult = checkIfUserHasAccessViaPPP($posts[$i]->ID, $userId);
			if($pppresult) {
				logToFile("User has access via PPP to this post $i : " . $posts[$i]->ID);
				unset($errId);
				continue;
			}
		}
		
		if(isset($errId)) {
			
			//something wrong with link, unset and continue
			if($sneak_peek == "N") {
				//logToFile("Removing post $i : " . $posts[$i]->ID); 
				unset($posts[$i]);
				$unsetAtleastOne = true;
			} else {
				//logToFile("There is an error and Sneak peek is Y");
				$beforeMore = strpos($posts[$i]->post_content, '<!--more-->');
				$content = substr($posts[$i]->post_content,0,$beforeMore);
				//logToFile("Content: " . $content); 
				$posts[$i]->post_content = trim($content);
			}
			$errorIdSet =true;
			continue;
			
		}
		
		if($user != NULL && isset($user)) {
			Dap_Resource::isResourceClickCountOK($user->getId(), $permalink);
		}		
		
		//Now, let's also check the categories to which this post belongs to, to see 
		//if in case maybe the post itself is not protected, but the category it belongs to is protected
		$categories = wp_get_post_categories($posts[$i]->ID);
      	foreach($categories as $cat_id) {
           $cat_permalink = get_category_link($cat_id);
           $cat_permalink = getResourceFromString($cat_permalink);
			$resource = isURLAllowed($cat_permalink, $tagPostID, $blogPath);	
			$showPPPMsg = $_SESSION['showPPPMsg'];
			$errId = $resource->getError_id();
			if(isset($errId)) {
				//remove post as there is error
				//logToFile("post itself not protected, but category is"); 
				if($sneak_peek == "N") {
					$postId = $posts[$i]->ID;
					unset($posts[$i]);
					$unsetAtleastOne = true;
				} else {
					//logToFile("Category: There is an error and Sneak peek is Y");
					$beforeMore = strpos($posts[$i]->post_content, '<!--more-->');
					$content = substr($posts[$i]->post_content,0,$beforeMore);
					//logToFile("Content: " . $content); 
					$posts[$i]->post_content = trim($content);
				}
				$errorIdSet =true;
				continue 2;
					
			}
			//if it is part of at least one category (isURLAllowed generates no error), 
			//then don't check other categories - simply exit the immediate loop
			//break;
      	}
      
	} //end for
	
	if(defined('FORNULL')) {
		 
		if($errorIdSet == true ){ 			 
			 $isseterror  = $errId; 			 
		}else{ 			 
			$isseterror  = 0 ;
		} 
	} else {		 
		$isseterror = isset($errId) ; 
	} 

 
	if( $isseterror && ($size == 1) ) {
 
	//if this is only one post/page and we have error code, then it means user may not have access to it
	
		//Only two things to possibly do: 1) Replace or 2) Redirect
		//Replace if sneak-peek is Y - Don't even look at any redirection
		//logToFile("Single Post/Page"); 
		if($sneak_peek == "Y") { //Sneak-Peek is yes, means need to call dap_sanitize_post
			//logToFile("---------------- 1) Sneak Peek is Y"); 
			//dap_sanitize_post($posts[0], $resource, $permalink );
			//dap_sanitize_post($post0 = $posts[0], $resource, $permalink );
			//$post0 = $posts[0];
			//$posts[0] = dap_sanitize_post($post0 = $posts[0], $resource, $permalink );
			$posts[0] = dap_sanitize_post($posts[0], $resource, $permalink );			
		} else if($sneak_peek == "N") {
			//logToFile("---------------- 1) Sneak Peek is N"); 
			//If error page is empty/default, then REPLACE
			//Else if error page is anything BUT empty/default, then REDIRECT
			$errorPageURL = Dap_Config::get("SITEWIDE_ERROR"); //initially point to global error page
			$productCount = Dap_Product::isPartOfHowManyDistinctProducts($permalink);
			//logToFile("productCount: $productCount");
			if( $productCount == 1 ) {
				$product = Dap_Product::getProductDetailsByResource($permalink);
				if( isset($product) && !is_null($product) ) {
					$errorPageURL = $product->getError_page_url();
				}
			}			
			
			//logToFile("errorPageURL: $errorPageURL"); 
			if ( ($errorPageURL == "") || ($errorPageURL == "/dap/product-error.php") )  {//Empty/default, so do REPLACE
				//logToFile("errorPageURL is blank"); 
				//dap_sanitize_post($posts[0], $resource, $permalink );
				//dap_sanitize_post($post0 = $posts[0], $resource, $permalink );
				//$post0 = $posts[0];
				$posts[0] = dap_sanitize_post($posts[0], $resource, $permalink );
			} else {
				//Redirect to product-specific error page
				//logToFile("Redirecting to error page: $errorPageURL");
				@header( "Location: " . $errorPageURL . "?request=" . urlencode($_SERVER['REQUEST_URI']));				
				if(defined('RETURNEXIT')) { return; exit; } else {exit;return;}   
			}
		}
	}
	
	//Make sure the array index is reset properly. 
	if (!is_feed()) {
		$posts = @array_merge($posts);
	}
	$size = count($posts);
	
	
	//logToFile("size: $size"); 
	
	if( ($size == 0) && $unsetAtleastOne ) {
		
		//logToFile("---------- About to createPost"); 
		//No posts were found
		global $wp;
		global $wp_query;
		
		$errorPageURL = Dap_Config::get("SITEWIDE_ERROR");
		
		if(defined('FORNULL')) { 
			if(is_null($errorPageURL) || ($errorPageURL == 0)) {
				$posts = 0;
				$posts[] = createPost();
			} else {
				@header( "Location: " . $errorPageURL . "?request=" . urlencode($_SERVER['REQUEST_URI']));			
				if(defined('RETURNEXIT')) { return; exit; } else {exit;return;}   	
			}
		}else{
			if(is_null($errorPageURL) || ($errorPageURL == "")) {
				$posts = NULL;
				$posts[] = createPost();
			} else {
				@header( "Location: " . $errorPageURL . "?request=" . urlencode($_SERVER['REQUEST_URI']));			
				if(defined('RETURNEXIT')) { return; exit; } else {exit;return;}   	
			}
		}
	}
	
	/** Added for thrive page starts***/
	if(defined('THRIVE_ENABLED')) {  
		$_SESSION['pppposts_id'] = $posts_id = $posts[0]->ID;		 
		$_SESSION['post'] = $posts;
		global $wpdb;
		$results = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}postmeta WHERE `post_id` = $posts_id AND `meta_key` LIKE '%tve_globals%'" ); 	 
		$permalink = get_permalink($posts_id);
		$permalink = getResourceFromString($permalink);
		//logToFile("THRIVE_ENABLED to permalink".$permalink);
		if(isset($results) && count($results) > 0){ 
			$product_Count = Dap_Product::isPartOfHowManyDistinctProducts($permalink);		
			//logToFile("THRIVE_ENABLED to product_Count".$product_Count);	 		
			if(isset($product_Count) && $product_Count >0 ) { 					
				if( isset($user) && ($user != null) ) {
					$uid = $user->getId();	
					$products = Dap_Product::getProductByResourceAndUserId($uid,$permalink);			 							 
				}		
				if(isset($products) &&  count($products) > 0){ 
				}else{
					$posts = NULL;
					$posts[0]['post_content'] = $posts[0]->post_content;
					$posts[] = createPost();	
				}	
			}	
		}	 
	}
	/** Added for thrive page ends here ***/
	
	//logToFile("-------------------------------- about to return from dap_filter_posts"); 

	if(isset($errId) && ( $errId == 'DAP006' || $errId == 'DAP001' || $errId == 'DAP002'  || $errId == 'DAP005' )){
		$showPPPMsg = true;
	}

	if($showPPPMsg == false){
		$_SESSION['showPPP'] = 'no';
	}

	return $posts;

} //end function

//New function since 4.3 to filter out menu links
function dap_filter_posts_menu($posts) {
	//return if admin.
	//logToFile("######################### in dap_filter_posts_menu"); 
	if(is_admin() && user_can($current_user->ID, 'administrator')) return $posts;
	
	$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	$url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
	$tagPostID = dap_url_to_postid($url);
	
	global $lldocroot;
	include_once ($lldocroot . "/dap/dap-config.php");
	$sneak_peek = Dap_Config::get("SNEAK_PEEK");
	$showProtectedLinksInMenu = Dap_Config::get("SHOW_PROT_MENULINKS");
	
	$homeUrl = get_home_url();
	$homeArray = explode('/', $homeUrl);
	$blogPath = '';
	if(isset($homeArray[3])){
			$blogPath = $homeArray[3];
	}
	// No filtering is done if Sneak Peek=Y or showProtectedLinksInMenu=N
	if(($showProtectedLinksInMenu == "Y") || ($sneak_peek == "Y")) {
		//logToFile("dap_filter_posts_menu: showProtectedLinksInMenu = Y or sneak peek = Y - so returning"); 
		return $posts;
	}	
	
	//If sneak-peek is on, is category and there's only 1 post in the array (like home page or archive page or category page)
	$size = count($posts);
	//logToFile("1) size: $size");
	
	if( is_category() && ($sneak_peek == "Y") && ($size = 1)  && !is_feed() ) return $posts;
	
	if ( is_category()  && ($sneak_peek == "N") ) {
		//If error page URL is set, just redirect to that URL
		global $wp_query;
		$cat_obj = $wp_query->get_queried_object();
		//logToFile( $cat_obj->name . " has id ". $cat_obj->term_id );

		$cat_permalink = get_category_link($cat_obj->term_id);
		$cat_permalink = getResourceFromString($cat_permalink);
		//logToFile("cat_permalink: $cat_permalink"); 
		 
		$resource = isURLAllowed($cat_permalink, $tagPostID, $blogPath);
		$errId = $resource->getError_id();
	}

	//If sneak-peek is on, and there's more than 1 post in the array (like home page or archive page or category page)
	$size = count($posts);
	//logToFile("2) size: $size");
	if( ($sneak_peek == "Y") && ($size > 1)  && !is_feed() ) return $posts;
	
	$permalink = null;
	$unsetAtleastOne = false;
	$session = Dap_Session::getSession();
	$user = $session->getUser();
	$errId = null;
	
	for ($i=0; $i < $size; $i++) {
		$postId = $posts[$i]->ID;
		$permalink = get_permalink($postId);
		$permalink = getResourceFromString($permalink);
		//logToFile("Permalink: $permalink",LOG_DEBUG_DAP); 
		$resource = isURLAllowed($permalink, $tagPostID, $blogPath);
		$errId = $resource->getError_id();
		
		if(isset($errId)) {
			//something wrong with link, unset and continue
			if($sneak_peek == "N") {
				//logToFile("Removing post $i : " . $posts[$i]->ID); 
				unset($posts[$i]);
				$unsetAtleastOne = true;
			}
			continue;
		}
		
		if($user != NULL && isset($user)) {
			Dap_Resource::isResourceClickCountOK($user->getId(), $permalink);
		}		
		
		//Now, let's also check the categories to which this post belongs to, to see 
		//if in case maybe the post itself is not protected, but the category it belongs to is protected
		$categories = wp_get_post_categories($posts[$i]->ID);
      	foreach($categories as $cat_id) {
           $cat_permalink = get_category_link($cat_id);
           $cat_permalink = getResourceFromString($cat_permalink);
			$resource = isURLAllowed($cat_permalink, $tagPostID, $blogPath);	
			$errId = $resource->getError_id();
			if(isset($errId)) {
				//remove post as there is error
				//logToFile("post itself not protected, but category is"); 
				if($sneak_peek == "N") {
					unset($posts[$i]);
					$unsetAtleastOne = true;
				}
				continue 2;
			} 
      	}
	} //end for
	
	
	//if this is only one post/page and we have error code, then it means user may not have access to it
	if( isset($errId) && ($size == 1) ) {
		//Only two things to possibly do: 1) Replace or 2) Redirect
		//Replace if sneak-peek is Y - Don't even look at any redirection
		//logToFile("Single Post/Page"); 
		if($sneak_peek == "Y") { //Sneak-Peek is yes, means need to call dap_sanitize_post
			//logToFile("---------------- 1) Sneak Peek is Y"); 
			//dap_sanitize_post($posts[0], $resource, $permalink );
			//dap_sanitize_post($post0 = $posts[0], $resource, $permalink );
			$post0 = $posts[0];
			$posts[0] = dap_sanitize_post($post0 = $posts[0], $resource, $permalink );
		} else if($sneak_peek == "N") {
			//do nothing
		}
	}
	
	//logToFile("########################### about to return from dap_filter_posts_menu"); 	
	//logToFile(""); 	
	return $posts;
	

} //end function


function createPost() {
	
	//logToFile("In create post"); 
	
	//If error page URL is set, just redirect to that URL
	global $wp_query;
	global $showPPP ;
	$cat_obj = $wp_query->get_queried_object();
	//logToFile( $cat_obj->name . " has id ". $cat_obj->term_id );

	$cat_permalink = get_category_link($cat_obj->term_id);
	$permalink = getResourceFromString($cat_permalink);
	//logToFile("cat_permalink: " . $cat_permalink); 
	
	$showPPP = 'no';
	
	$lldocroot = "";
	if( defined('SITEROOT') ) {
		$lldocroot = SITEROOT;
	} else {
		$lldocroot = $_SERVER['DOCUMENT_ROOT'];
	}
	include_once ($lldocroot . "/dap/dap-config.php");
	$output = "";
	$redirectURL = "";
	$salesPageURL = Dap_Config::get("SALES_PAGE_URL"); //global SPU
	$loggedInURL = Dap_Config::get("LOGGED_IN_URL");
	
	if($salesPageURL == "") $salesPageURL = "/";
	if($loggedInURL == "") $loggedInURL = "/";
	
	if ( isset($_GET['request']) && ($_GET['request'] != "") ) {
		//request is available in query string
		$redirectURL = $_GET['request'];
	} else {
		//No 'request' available. Check if this is the home page.
		//If not home page, then whatever is the URL being visited, is the redirectURL
		wp_reset_query();
		if (!is_home() && !is_front_page()) {
			$redirectURL = $_SERVER['REQUEST_URI'];
		}
	}
	
	
	if(Dap_Session::isLoggedIn()) {//LOGGED IN
		//logToFile("Logged in"); 
		$session = Dap_Session::getSession();
		$user = $session->getUser();		
		
		$errorHTMLPath = $lldocroot . "/dap/inc/error-loggedin.php";
		//Check for custom error page
		if( file_exists($lldocroot . "/dap/inc/customerror-loggedin.php") ) {
			$errorHTMLPath = $lldocroot . "/dap/inc/customerror-loggedin.php";
		}
		
		//$productCount = $user->hasAccessToHowManyDistinctProducts();
		$productCount = Dap_Product::isPartOfHowManyDistinctProducts($permalink);
		//logToFile("productCount: $productCount");
		if( $productCount == 1 ) {
			$product = Dap_Product::getProductDetailsByResource($permalink);
			if(!is_null($product) && isset($product)) {
				if ($product->getSales_page_url() != "") {
					$salesPageURL = $product->getSales_page_url();
				}
				if ($product->getLogged_in_url() != "") {
					$loggedInURL = $product->getLogged_in_url();
				}
			}
		}
		
		$output = replaceFillers($errorHTMLPath,"%%LOGIN_URL%%",Dap_Config::get("LOGIN_URL"));
		$output = str_replace("%%REQUEST%%",$redirectURL,$output);
		$output = str_replace("%%LOGGED_IN_URL%%",$loggedInURL,$output);
		$output = str_replace("%%SALES_PAGE_URL%%",$salesPageURL,$output);
		//logToFile("About to return");
	} 
	
	else {//NOT LOGGED IN
		//logToFile("NOT Logged in createPost"); 
		$errorHTMLPath = $lldocroot . "/dap/inc/error-notloggedin.php";
		//Check for custom error page
		if( file_exists($lldocroot . "/dap/inc/customerror-notloggedin.php") ) {
			$errorHTMLPath = $lldocroot . "/dap/inc/customerror-notloggedin.php";
		}
		
		$productCount = Dap_Product::isPartOfHowManyDistinctProducts($permalink);
		//logToFile("productCount: $productCount");
		if( intval($productCount) == 1 ) {
			$product = Dap_Product::getProductDetailsByResource($permalink);
			if ($product->getSales_page_url() != "") {
				$salesPageURL = $product->getSales_page_url();
			}
			if ($product->getLogged_in_url() != "") {
				$loggedInURL = $product->getLogged_in_url();
			}
		}
		
		$output = replaceFillers($errorHTMLPath,"%%LOGIN_URL%%",Dap_Config::get("LOGIN_URL"));
		$output = str_replace("%%REQUEST%%",$redirectURL,$output);
		$output = str_replace("%%LOGGED_IN_URL%%",$loggedInURL,$output);
		$output = str_replace("%%SALES_PAGE_URL%%",$salesPageURL,$output);
		$output = str_replace("%%LOGIN_FORM%%",dap_login("%%LOGIN_FORM%%",$redirectURL),$output);
		
		//logToFile("output: $output"); 
		
		//add_filter("comments_template", "dap_incl_nothing_file", 10);
		//add_action('init','less_filters',20);
	}
	
	//logToFile("creating temp post"); 
	//$output = mb_convert_encoding($output, "UTF-8", "auto");
	
	$post = new stdClass;
	$post->post_author = 1;
	$post->post_name = "error";
	$post->guid = get_bloginfo('wpurl');
	$post->post_title = "For Members Only";
	$post->post_content = $output;
	$post->ID = -1;
	//$post->post_status = 'static';
	$post->comment_status = 'closed';
	//$post->ping_status = $this->ping_status;
	$post->comment_count = 0;
	$post->post_date = current_time('mysql');
	$post->post_date_gmt = current_time('mysql', 1);
	return($post);		
}

function dap_sanitize_post(&$post, $resource, $permalink ) {
	//Only time this gets called is when a permalink (single post/page) is accessed
	//logToFile("in dap_sanitize_post"); 
	$lldocroot = "";
	if( defined('SITEROOT') ) {
		$lldocroot = SITEROOT;
	} else {
		$lldocroot = $_SERVER['DOCUMENT_ROOT'];
	}
	
	include_once ($lldocroot . "/dap/dap-config.php");
	$results = get_extended($post->post_content);
	
	//logToFile("Post author: " . $post->post_author); 
	$main = $results['main'];
	
	$sneak_peek = Dap_Config::get("SNEAK_PEEK");
	if($sneak_peek == "Y") {
		if ( $post->post_excerpt ) {
			$main = $post->post_excerpt;
		}
	}
	
	$output = "";
	$redirectURL = "";
	$salesPageURL = Dap_Config::get("SALES_PAGE_URL"); //global SPU
	$loggedInURL = Dap_Config::get("LOGGED_IN_URL");
	
	if($salesPageURL == "") $salesPageURL = "/";
	if($loggedInURL == "") $loggedInURL = "/";
	
	if ( isset($_GET['request']) && ($_GET['request'] != "") ) {
		//request is available in query string
		$redirectURL = $_GET['request'];
	} else {
		//No 'request' available. Check if this is the home page.
		//If not home page, then whatever is the URL being visited, is the redirectURL
		//logToFile("No request available, so redirect url is: " . $_SERVER['REQUEST_URI']); 
		wp_reset_query();
		if (!is_home() && !is_front_page()) {
			$redirectURL = $_SERVER['REQUEST_URI'];
		}
	}
	
	if(Dap_Session::isLoggedIn()) {//LOGGED IN
		//logToFile("Logged in"); 
		$session = Dap_Session::getSession();
		$user = $session->getUser();		
		
		$errorHTMLPath = $lldocroot . "/dap/inc/error-loggedin.php";
		//Check for custom error page
		if( file_exists($lldocroot . "/dap/inc/customerror-loggedin.php") ) {
			$errorHTMLPath = $lldocroot . "/dap/inc/customerror-loggedin.php";
		}
		//logToFile("errorHTMLPath: $errorHTMLPath"); 
		
		//$productCount = $user->hasAccessToHowManyDistinctProducts();
		$productCount = Dap_Product::isPartOfHowManyDistinctProducts($permalink);
		//logToFile("productCount: $productCount");
		if( $productCount == 1 ) {
			$product = Dap_Product::getProductDetailsByResource($permalink);
			//logToFile("Back from Dap_Product:getProductDetailsByResource"); 
			//logToFile("product name: " . $product->getName()); 
			
			if(isset($product)) {
				if ($product->getSales_page_url() != "") {
					$salesPageURL = $product->getSales_page_url();
				}
				if ($product->getLogged_in_url() != "") {
					$loggedInURL = $product->getLogged_in_url();
				}
			}
		}
		
		$output = replaceFillers($errorHTMLPath,"%%LOGIN_URL%%",Dap_Config::get("LOGIN_URL"));
		$output = str_replace("%%REQUEST%%",$redirectURL,$output);
		$output = str_replace("%%LOGGED_IN_URL%%",$loggedInURL,$output);
		$output = str_replace("%%SALES_PAGE_URL%%",$salesPageURL,$output);
		$output = str_replace("%%ERROR_MSG%%",$resource->getError(0),$output);
		//logToFile("About to return"); 
	} 
	
	else {//NOT LOGGED IN
		//logToFile("Not logged in");
		$errorHTMLPath = $lldocroot . "/dap/inc/error-notloggedin.php";
		//Check for custom error page
		if( file_exists($lldocroot . "/dap/inc/customerror-notloggedin.php") ) {
			$errorHTMLPath = $lldocroot . "/dap/inc/customerror-notloggedin.php";
		}
		
		$productCount = Dap_Product::isPartOfHowManyDistinctProducts($permalink);
		//logToFile("productCount: $productCount");
		if( intval($productCount) == 1 ) {
			$product = Dap_Product::getProductDetailsByResource($permalink);
			if ($product->getSales_page_url() != "") {
				$salesPageURL = $product->getSales_page_url();
			}
			if ($product->getLogged_in_url() != "") {
				$loggedInURL = $product->getLogged_in_url();
			}
		}
		
		$output = replaceFillers($errorHTMLPath,"%%LOGIN_URL%%",Dap_Config::get("LOGIN_URL"));
		$output = str_replace("%%REQUEST%%",$redirectURL,$output);
		$output = str_replace("%%LOGGED_IN_URL%%",$loggedInURL,$output);
		$output = str_replace("%%SALES_PAGE_URL%%",$salesPageURL,$output);
		$output = str_replace("%%LOGIN_FORM%%",dap_login("%%LOGIN_FORM%%",$redirectURL),$output);
	}
	
	//logToFile("output: $output"); 
	//$output = mb_convert_encoding($output, "UTF-8", "auto");
	$main .= $output;
	if(is_array($post)){  
		$post['post_content'] = $main; 
	}    
	else if (isset($post)) {
		$post->post_content = $main;
	}
	else {
		$post = new StdClass;
		$post->post_content = $main;
	}
	
	add_filter("comments_template", "dap_incl_nothing_file", 10);
	//logToFile("returning from dap_sanitize_post"); 
	return $post;
}

function dap_incl_nothing_file() {
	if( Dap_Config::get('SHOW_COMMENTS') == "Y" ) {
		return;
	}
	//If "" or "N", return blank file
	return dirname(__FILE__) . '/do-nothing.php';
	
}

function dap_livelinks_activate() {
	//This deliberately uses dap-settings.php (instead of dap-config.php)
	//because when LL is being activated, dap-config.php does not exist yet.
	
	//global $lldocroot;
	//include_once ($lldocroot . "/dap/dap-settings.php");	
	
	if( defined('SITEROOT') ) {
		include_once (SITEROOT . "/dap/dap-settings.php");	
	} else {
		include_once ($_SERVER['DOCUMENT_ROOT'] . "/dap/dap-settings.php");
	}	
	
	$site_url = get_option("siteurl");
	$admin_email = get_option("admin_email");
	$list = parse_url($site_url);
	$site_url = $list['scheme']."://".$list['host'];
	$dap_install_result = dap_install(DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, $site_url, "admin", $admin_email);
	$var = "<h3 style='color:#C00;font-size:16.9px'>" . $dap_install_result[1] . " (" . $dap_install_result[0] . ") </h3>";
	update_option('dap_install_result', $var);
	$output = ob_get_contents();
    ob_end_clean();
}


function dap_install($DB_NAME_DAP, $DB_USER_DAP, 
								$DB_PASSWORD_DAP, $DB_HOST_DAP, 
								$SITE_URL_DAP, 
								$ADMIN_FIRSTNAME_DAP, $ADMIN_EMAIL_DAP) {
	//logToFile(DAP_ROOT); 
	//lets do some checks, init setting etc
	
	$result = array();
	$ver = phpversion();
	
	if($ver < 5) {
		$result[0] = "100";
		$result[1] = "Sorry, you need a minimum of PHP version 5 in order to run DAP. Your current PHP version is: " . $ver . "<br/><br/> Installation failed. Please de-activate LiveLinks and re-activate it when you've resolved this issue.";
		return $result;
	} 
	
	if ( !class_exists('PDO') || !method_exists('PDO', 'query') || !class_exists('PDOStatement') || !class_exists('PDOException') || !in_array("mysql", PDO::getAvailableDrivers()) ) {
		$result[0] = "101";
		$result[1] = "Sorry, it appears that a required library (PDO) for connecting to a MySQL database has not been enabled. Pls ask your web host if your web site can have 'PHP PDO Enabled for MySQL'<br/><br/> Installation failed. Please de-activate LiveLinks and re-activate it when you've resolved this issue.";
		return $result;
	}
	
	//check if any of the required variables are not set/empty.
	if(empty($DB_NAME_DAP)) {
		$result[0] = "102";
		$result[1] = "Required field Database Name (DB_NAME_DAP) is missing. <br/> Installation failed. Please de-activate LiveLinks and re-activate it when you've fixed this issue.";
		return $result;	
	}
	
	$config_file = DAP_ROOT."dap-config.php";
	$config_template_file = ABSPATH."wp-content/plugins/DAP-WP-LiveLinks/includes/templates/config/dap-config-template.php";
	
	$install_ddl_file = DAP_ROOT."db/dap_ddl.php";
	$install_data_file = DAP_ROOT."db/dap_data.php";
	
	//if the dap-config is there, check if tables exist
	if(file_exists($config_file)) {
		//echo $config_file;
		//Check if tables exist too...
	//	echo "Config file exists. Checking to see if database tables exist...<br/>";
		include_once($config_file);
		//echo "Creating connection for checking...<br>";

		try { //First check if the info in the dap-config file are correct
			$dap_dbh = Dap_Connection::getConnection();
		} catch (PDOException $e) {
			$result[0] = "103";
			//$result[1] = $e->getMessage() . $DB_ERROR_INCORRECT;
			$result[1] = $e->getMessage();
			return $result;
		} catch (Exception $e) { 
			$result[0] = "104";
			$result[1] = $e->getMessage() . $DB_ERROR_INCORRECT;
			return $result;
		}
		
		//echo "Obtained Connection...<br>";
		//echo "Checking if tables exist...<br/>";
		
		try{	
			$sql = "select count(*) as count from dap_config";
			$stmt = $dap_dbh->prepare($sql);
			$stmt->execute();
			if ( $row = $stmt->fetch() ) {
				$result[0] = "105";
				$result[1] = "WARNING: You probably already have a working installation of DAP. So, if you are trying to do a FRESH install of DAP, then delete any existing DAP tables and re-try.<br/><br/>But if you just happened to de-activate & activate LiveLinks for some other reason, then don't worry - nothing has changed in your DAP installation. You may continue using DAP as usual.";
				return $result;
			}
		} catch (PDOException $e) {
			//Eat it because if there is a PDO Exception, it means that
			//the database has not been created, and installation should continue
		} catch (Exception $e) {
			//Eat it because if there is a PDO Exception, it means that
			//the database has not been created, and installation should continue
		}
	} else { //config file doesn't exist, so create it
		$configTemplateFileText = file_get_contents($config_template_file);
		$fd = fopen($config_file, "w");
		fwrite($fd, $configTemplateFileText);
		fclose($fd);
		
		$configFileText = file_get_contents($config_file);
		$configFileText = str_replace("%%DB_NAME_DAP%%", $DB_NAME_DAP, $configFileText);
		$configFileText = str_replace("%%DB_USER_DAP%%", $DB_USER_DAP, $configFileText);
		$configFileText = str_replace("%%DB_PASSWORD_DAP%%", $DB_PASSWORD_DAP, $configFileText);
		$configFileText = str_replace("%%DB_HOST_DAP%%", $DB_HOST_DAP, $configFileText);
		$configFileText = str_replace("%%SITE_URL_DAP%%", $SITE_URL_DAP, $configFileText);
		$fd = fopen($config_file, "w");
		fwrite($fd, $configFileText);
		fclose($fd);		
		
		//After creation let us make sure we did file write, if not exit
		if(!file_exists($config_file)) {
			$result[0] = "106";
			$result[1] = "Oops! Could not create the config file (dap-config.php). Please make the 'dap' folder writable by doing CHMOD 755 (and if that doesn't work, then try CHMOD 777.) <br/> Installation failed. Please de-activate LiveLinks and re-activate it when you've fixed the issue.";
			return $result;		
		}
	}
	
	//Everything looks good at this point - so start installation

	include_once($config_file);	 	

	try {
		//echo "Creating Database Tables....<br>";
		$sql_ddl = array();
		$sql_data = array();
		include_once($install_ddl_file);
		$sql_ddl = array_merge($sql_ddl, $sql_data);
		//echo "Creating connection.....<br>";
		$dap_dbh = Dap_Connection::getConnection();
		//echo "Obtained Connection...<br>";
		//echo "Executing SQL for DDL.....<br>";
		$i=1;
		foreach($sql_ddl as $sql) {
			try {
				$stmt = $dap_dbh->prepare($sql);
				$stmt->execute();
				//echo $sql . "<br/>";
				$stmt = null;
			} catch (PDOException $e) {
				$result[0] = "107";
				$result[1] = $e->getMessage();
				return $result;
			} catch (Exception $e) {
				$result[0] = "108";
				$result[1] = $e->getMessage();
				return $result;
			}
		}
		//echo "Completed creation of tables.....<br>";

		//$response = "";

		$sql_ddl = array();
		$sql_data = array();
		include_once($install_data_file);
		$sql_data = array_merge($sql_ddl, $sql_data);
		//echo "Inserting Data into the Database....<br>";

		//Insert Data
		foreach($sql_data as $sql) {
			try {
				$stmt = $dap_dbh->prepare($sql);
				$stmt->execute();
				//echo $sql . "<br/>";
				$stmt = null;
			} catch (PDOException $e) {
				$result[0] = "109";
				$result[1] = $e->getMessage();
				return $result;
			} catch (Exception $e) {
				$result[0] = "110";
				$result[1] = $e->getMessage();
				return $result;
			}
		}
		
		//echo "Completed inserting data.....<br/><br/><br/>";
		
		$response = "SUCCESS! DAP installation is now ALMOST Done...<br/><br/>
		
		Just One Last Thing...<br/><br/> 

Go to <a href=\"options-permalink.php\" target=\"_blank\">'Settings > Permalinks'</a> (opens in a new window) and choose <strong>ANY permalink structure other than 'Default'</strong> and EVEN if you already have a non-default setting selected, you <strong>MUST MUST MUST click on 'Save Changes'</strong> for the DAP installation to be complete.<br/><br/>

Once you've done that, DAP installation is then complete!<br/><br/>

!!!******** IMPORTANT ********!!!<br/>
A new DAP Admin account has been created for you.<br/><br/>

When you log in as WP Admin, you will now also be logged in automatically as DAP Admin.<br/><br/>

You may now log in to DAP Admin Control Panel right within your WordPress Admin Panel, by clicking on the link 'DigitalAccessPass' towards the bottom left.<br/><br/>

PLEASE NOTE:<br/>
When you login to DAP on *YOUR* site ( either by clicking on the new 'DigitalAccessPass' link towards the bottom left, or directly, outside of WordPress, at: ".SITE_URL_DAP . "/dap/ ) using the login info above, you will notice a \"license notification\" message.<br/><br/>

What you have to do is this...<br/><br/>

1) Login to OUR web site at http://digitalaccesspass.com/dap using the credentials we sent you when you first purchased DAP (if you do not know what it is, then just click on the forgot password link in the login page - http://www.digitalaccesspass.com/dap)
and after you login to this member's area on OUR site, click on the link that says 'Get License Key'.<br/><br/>

2) Copy that license key, come back to DAP admin panel on YOUR site right here, and follow the instructions there to update license key.<br/><br/>

That's it!<br/><br/>

";

		//Send email to admin with login info
		$subject = " Your DAP Admin Login Info";
		$bodyText = "SUCCESS! DAP has been successfully installed.\n\n
The following DAP Admin account has been created for you:\n
Please note that the 'DAP Admin' login is *COMPLETELY* separate from your 'WordPress Admin' login\n
So PLEASE store this important login information carefully...\n
			
------------------------				
Login: $ADMIN_EMAIL_DAP
Password: dap
------------------------				
		
You can manage DAP right from within your WordPress Admin Panel, by clicking on the new link 'DigitalAccessPass' (towards the bottom left in your WP Admin Panel.)\n\n
(Or you may also login to DAP (outside of WordPress), at: " . SITE_URL_DAP . "/dap/ )";

		if( $ADMIN_EMAIL_DAP !== ("admin@".$domain_name[0]) ) {
			sendAdminEmail($subject, $bodyText);
		}
		
		$result[0] = "111";
		$result[1] = $response;
		
		//Set cookie for 10 years for the new DAP-within-WP
		//$password = md5("dap");
		$password = Dap_User::GeneratePassword(10);
		setcookie("dapcookie_email",$ADMIN_EMAIL_DAP,time()+3600*24*3650,"/");
		setcookie("dapcookie_password",$password,time()+3600*24*3650,"/");		
		return $result;		
	} catch (PDOException $e) {
		$result[0] = "112";
		//$result[1] = $e->getMessage();
		$result[1] = $e->getMessage() . " - " . $config_file;
		return $result;
	} catch (Exception $e) {
		$result[0] = "113";
		$result[1] = $e->getMessage();
		return $result;
	}
	
}







if(get_option('dap_install_result')) {
	function dap_warning() {
		$var = get_option('dap_install_result');
		echo "
		<div id='dap-warning' class='updated'><p>".$var."</p></div>
		";
		delete_option('dap_install_result');

	}
	add_action('admin_notices', 'dap_warning');
}


function dap_mod_rewrite($rules) { 
	$rules = str_replace("</IfModule>\n","",$rules);
	$rules .= "\n\n#----- START DAP -----\n";
	$rules .= "RewriteCond %{REQUEST_FILENAME} -f \n";
	$rules .= "RewriteCond %{REQUEST_FILENAME} !-d \n";
	$rules .= "RewriteCond %{REQUEST_FILENAME} (.*)/wp-content/uploads/(.*) \n";
	$rules .= "RewriteCond %{REQUEST_FILENAME} !(.*)(\.php|\.css|\.js|\.jpg|\.gif|\.png|\.txt|\.ico|\.jpeg)$ \n";
	$rules .= "RewriteRule (.*) /dap/client/website/dapclient.php?dapref=%{REQUEST_URI}&plug=wp&%{QUERY_STRING}  [L] \n";
	$rules .= "#----- END DAP -----\n\n";
	$rules .= "</IfModule>\n";
	return $rules;
}


//This function replaces %%LOGIN_FORM%% tags with actual form code
function dap_login($data,$redirectURL="") {
	if (strpos($data,'%%LOGIN_FORM') === false) return $data;
	
	$lldocroot = "";
	if( defined('SITEROOT') ) {
		$lldocroot = SITEROOT;
	} else {
		$lldocroot = $_SERVER['DOCUMENT_ROOT'];
	}
	include_once ($lldocroot . "/dap/dap-config.php");	
	
	//logToFile("data: $data",LOG_DEBUG_DAP); 
	//$redirectURL = "";
	
	//if (strpos($data,'%%LOGIN_FORM%%')!== false) {//found the string - so specific to login page
	$session = Dap_Session::getSession();
	$signup_page = Dap_Config::get("SITE_URL_DAP");
	//logToFile("in here",LOG_DEBUG_DAP); 
	
	//$redirectURL = "";
	
	if ( isset($_GET['request']) && ($_GET['request'] != "") && ($redirectURL == "") ) {
		//request is available in query string
		//logToFile("There's a request URL: " . $_GET['request']); 
		$redirectURL = $_GET['request'];
	} 
	
	//else {
		//No 'request' available. Check if this is the home page.
		//If not home page, then whatever is the URL being visited, is the redirectURL
		//logToFile("here...."); 
		//wp_reset_query();
		//if (!is_home() && !is_front_page()) {
			//logToFile("not is_home"); 
			//$redirectURL = $_SERVER['REQUEST_URI'];
		//}
	//}
	
	//logToFile("redirectURL: $redirectURL"); 
	//logToFile("Current page where %%LOGIN_FORM%% is getting triggered from: " . $_SERVER['REQUEST_URI']); 
	//$httpURL = "http://" . str_replace("www.","",$_SERVER['HTTP_HOST']) . $_SERVER['REQUEST_URI'];
	
	//$loginURL = str_replace("www.","",Dap_Config::get("LOGIN_URL"));
	//logToFile("loginURL: " . $loginURL);
	//logToFile("httpURL: " . $httpURL);
	//logToFile("trim(httpURL): " . trim($httpURL,"/"));
	//logToFile("request_uri: " . $_SERVER['REQUEST_URI']);
	//logToFile("trim(request_uri): " . trim($_SERVER['REQUEST_URI'],"/"));
	
	/*
	if( 
		($loginURL == $httpURL) ||
		($loginURL == trim($httpURL,"/")) ||
		($loginURL == $_SERVER['REQUEST_URI']) ||
		(trim($loginURL,"/") == trim($_SERVER['REQUEST_URI'],"/"))
	) {
		//%%LOGIN_FORM%% is getting triggered on same page as true login page - so make sure post-login never comes back here
		//logToFile("In here"); 
		$redirectURL = "";
	}
	*/
	
	$product = Dap_Product::getProductDetailsByResource($redirectURL);
	if( isset($product) && !empty($product) && ($product->getSales_page_url() != "") ) {
		$signup_page =  $product->getSales_page_url();
	}
	
	if(!Dap_Session::isLoggedIn()) { //Not logged in
		//logToFile("not logged in livelinks",LOG_DEBUG_DAP);
		$output = "";
		
		$loginFormFilepath = WP_PLUGIN_DIR . "/DAP-WP-LiveLinks/DAP-WP-LoginForm.html";
		if( file_exists(WP_PLUGIN_DIR . "/DAP-WP-LiveLinks/customDAP-WP-LoginForm.html") ) {
			$loginFormFilepath = WP_PLUGIN_DIR . "/DAP-WP-LiveLinks/customDAP-WP-LoginForm.html";
		}
		
		$output .= replaceFillers($loginFormFilepath,"%%LOGIN_URL%%",Dap_Config::get("LOGIN_URL"));
		$output = str_replace("%%SIGNUP_PAGE%%",$signup_page,$output);
		$output = str_replace("%%LOGGED_IN_URL%%",Dap_Config::get("LOGGED_IN_URL"),$output);
		$output = str_replace("%%REQUEST%%",$redirectURL,$output);

		//Finally, replace just the %%LOGIN_FORM%% and leave the rest of the content alone
		$output = str_replace("%%LOGIN_FORM%%",$output,$data);
		//$output = mb_convert_encoding($output, "UTF-8", "auto");
		
		if( isset($_GET['msg']) ) {
			//$msg = mb_convert_encoding($msg, "UTF-8", "auto");
			$output = "<div class='confirmationMessage'>" . stripslashes($_GET['msg']) . "</div>" . $output;
		}
		
		//logToFile("output: $output",LOG_DEBUG_DAP);
		return $output;
	} //End Not Logged In
	
	else if(Dap_Session::isLoggedIn()) {
		//Check if there is a request uri
		//logToFile("loggedIn",LOG_DEBUG_DAP);
		$msg = "";
		$session = DAP_Session::getSession();
		$user = $session->getUser();		
		//ob_end_clean();
		$redirectURL = Dap_UsersProducts::getLoggedInURL();
		//@header("Location:".$redirectURL);
		
		$msg = "[" . MSG_ALREADY_LOGGEDIN_1 . " <a href='" . $redirectURL . "'>" . MSG_ALREADY_LOGGEDIN_2 . "</a>]<br/><br/>";
		
		if( $session->isAdmin() ) {
			$msg .= ">>> <a href='/dap/admin/'>You are logged in as DAP Admin. Proceed to DAP Admin Dashboard</a> <<< <br/><br/>";
		}
		
		$output = str_replace("%%LOGIN_FORM%%",$msg,$data);
		//$output = mb_convert_encoding($output, "UTF-8", "auto");

		if( isset($_GET['msg']) ) {
			//$msg = mb_convert_encoding($msg, "UTF-8", "auto");
			$output = "<div class='confirmationMessage'>" . stripslashes($_GET['msg']) . "</div><br/><br/>" . $output;
		}
		
		if( isset($_GET['request']) && ($_GET['request'] != "") ) {
			$permalink = $_GET['request'];
			//logToFile("permalink: " . $permalink); 
			
			$salesPageURL = Dap_Config::get("SALES_PAGE_URL"); //global SPU
			if($salesPageURL == "") $salesPageURL = "/";

			/**
				It means user already logged in, and was redirected back here 
				with a query string, because user not eligible to view that content
			*/
		
			//$msg = mb_convert_encoding($msg, "UTF-8", "auto");
			//$msg = "[You are already logged in as admin. <a href='" . $redirectURL . "'>Click here</a> to continue to DAP Admin Control Panel]";
		
			/** Append error-loggedin.php content to message */
			$errorHTMLPath = $lldocroot . "/dap/inc/error-loggedin.php";
			//Check for custom error page
			if( file_exists($lldocroot . "/dap/inc/customerror-loggedin.php") ) {
				$errorHTMLPath = $lldocroot . "/dap/inc/customerror-loggedin.php";
			}
			
			//$productCount = $user->hasAccessToHowManyDistinctProducts();
			//$permalink = str_replace( $_SERVER['REQUEST_QUERY'], '', $_SERVER['REQUEST_URI'] );
			//logToFile("permalink: " . $permalink); 
			//logToFile($_SERVER['REQUEST_QUERY']); 
			//logToFile($_SERVER['REQUEST_URI']); 
			$productCount = Dap_Product::isPartOfHowManyDistinctProducts($permalink);
			logToFile("productCount: $productCount");
			if( $productCount == 1 ) {
				$product = Dap_Product::getProductDetailsByResource($permalink);
				if(!is_null($product) && isset($product)) {
					if ($product->getSales_page_url() != "") {
						$salesPageURL = $product->getSales_page_url();
					}
					if ($product->getLogged_in_url() != "") {
						$loggedInURL = $product->getLogged_in_url();
					}
				}
			}
			$output2 = replaceFillers($errorHTMLPath,"%%LOGIN_URL%%",Dap_Config::get("LOGIN_URL"));
			$output2 = str_replace("%%SALES_PAGE_URL%%",$salesPageURL,$output2);
			//logToFile("About to return");
			
			$output = $output2 . "<br/><br/>" . $output;
		}
		
		

		return $output;  
		exit;
	}


	//} //End if (strpos($data,'%%LOGIN_FORM%%')!== false) 

	//simply return blog post content
	return $data;

} //end function
	
	
function dap_personalize($data) {
	if (strpos($data,'%%') === false) return $data;
	
	$lldocroot = "";
	if( defined('SITEROOT') ) {
		$lldocroot = SITEROOT;
	} else {
		$lldocroot = $_SERVER['DOCUMENT_ROOT'];
	}
	include_once ($lldocroot . "/dap/dap-config.php");	
	$errorHTML = mb_convert_encoding(MSG_PLS_LOGIN, "UTF-8", "auto") . " <a href=\"" . Dap_Config::get("LOGIN_URL") . "\">". mb_convert_encoding(MSG_CLICK_HERE_TO_LOGIN, "UTF-8", "auto") . "</a>";

	if (
			(
				(strpos($data,'%%AFFDETAILS%%')!== false) ||
				(strpos($data,'%%USERPROFILE%%')!== false) ||
				(strpos($data,'%%USERLINKS%%')!== false) ||
				(strpos($data,'%%FEEDLINK%%')!== false) ||
				(strpos($data,'%%ACTIVATION_KEY%%')!== false) ||
				(strpos($data,'%%AFF_LINK%%')!== false) || 
				(strpos($data,'%%SELFSERVICE%%')!== false) || 
				(strpos($data,'%%CREDITSTORE%%')!== false) || 
				(strpos($data,'%%PAYPALCONFIRM%%')!== false) || 
				(strpos($data,'%%CREDITHISTORY%%')!== false) ||
				(strpos($data,'%%USER_ID%%')!== false) ||
				(strpos($data,'%%USERNAME%%')!== false)
			)
			&&
			!Dap_Session::isLoggedIn()
		) 
	{
		
		$data = str_replace ("%%AFFDETAILS%%", $errorHTML, $data);
		$data = str_replace ("%%USERPROFILE%%", $errorHTML, $data);
		$data = str_replace ("%%USERLINKS%%", $errorHTML, $data);
		$data = str_replace ("%%FEEDLINK%%", $errorHTML, $data);
		$data = str_replace ("%%ACTIVATION_KEY%%", $errorHTML, $data);
		$data = str_replace ("%%AFF_LINK%%", $errorHTML, $data);
		$data = str_replace ("%%SELFSERVICE%%", $errorHTML, $data);
		$data = str_replace ("%%CREDITHISTORY%%", $errorHTML, $data);
		$data = str_replace ("%%USER_ID%%", $errorHTML, $data);
		$data = str_replace ("%%USERNAME%%", $errorHTML, $data);
		
		return $data;
	}
	
	$session = Dap_Session::getSession();
	$user = $session->getUser();
	
	if (strpos($data,'%%FEEDLINK%%')!== false) {//found the string - so replace with session data
		//if( isset($user) && ($user != null) && ($user->isPaidUser()) ) {
		if( isset($user) && ($user != null) ) {
			$activation_key = $user->getActivation_key();
			$feedlink = "?key=" . $activation_key;
			$data = str_replace ("%%FEEDLINK%%", $feedlink, $data);
		}
	}
	
	if (strpos($data,'%%ACTIVATION_KEY%%')!== false) {//found the string - so replace with session data
		if( isset($user) && ($user != null) ) {
			$activation_key = $user->getActivation_key();
			$data = str_replace ("%%ACTIVATION_KEY%%", $activation_key, $data);
		}
	}
	
	if (strpos($data,'%%FIRST_NAME%%')!== false) {//found the string - so replace with session data
		if(isset($user)) {
			$first_name = $user->getFirst_name();
			$data = str_replace ("%%FIRST_NAME%%", $first_name, $data);
		} else {
			$data = str_replace ("%%FIRST_NAME%%", "reader", $data);
		}
	}
	
	if (strpos($data,'%%LAST_NAME%%')!== false) {//found the string - so replace with session data
		if(isset($user)) {
			$last_name = $user->getLast_name();
			$data = str_replace ("%%LAST_NAME%%", $last_name, $data);
		} else {
			$data = str_replace ("%%LAST_NAME%%", "", $data);
		}
	}

	if (strpos($data,'%%AFFDETAILS%%')!== false) {//found the string - so replace with session data
		ob_start();
		eval("?>" . file_get_contents($lldocroot . "/dap/inc/content/affdetails.inc.php"));
		$output = ob_get_contents();
		ob_end_clean();
		$data = str_replace ("%%AFFDETAILS%%", $output, $data);
	}

	if (strpos($data,'%%USERPROFILE%%')!== false) {//found the string - so replace with session data
		$data = str_replace ("%%USERPROFILE%%", "[DAPUserProfile]", $data);
		do_shortcode(dap_clean_shortcode_content($data));
		/**
		ob_start();
		eval("?>" . file_get_contents($lldocroot . "/dap/inc/content/userprofile.inc.php"));
		$output = ob_get_contents();
		ob_end_clean();
		$data = str_replace ("%%USERPROFILE%%", $output, $data);
		*/
	}

	if (strpos($data,'%%USERLINKS%%')!== false) {//found the string - so replace with session data
		$data = str_replace ("%%USERLINKS%%", "[DAPUserLinks]", $data);
		do_shortcode(dap_clean_shortcode_content($data));
		
		/**
		ob_start();
		eval("?>" . file_get_contents($lldocroot . "/dap/inc/content/userlinks.inc.php"));
		$output = ob_get_contents();
		ob_end_clean();
		$data = str_replace ("%%USERLINKS%%", $output, $data);
		*/
	}

	if (strpos($data,'%%EMAIL%%')!== false) {//found the string - so replace with session data
		if(isset($user)) {
			$email = $user->getEmail();
			$data = str_replace ("%%EMAIL%%", $email, $data);
		} else {
			$data = str_replace ("%%EMAIL%%", "[No Email Id Found]", $data);
		}
	}
	
	if (strpos($data,'%%EMAIL_ID%%')!== false) {//found the string - so replace with session data
		if(isset($user)) {
			$email = $user->getEmail();
			$data = str_replace ("%%EMAIL_ID%%", $email, $data);
		} else {
			$data = str_replace ("%%EMAIL_ID%%", "[No Email Id Found]", $data);
		}
	}
	
	if (strpos($data,'%%USER_NAME%%')!== false) {//found the string - so replace with session data
		if(isset($user)) {
			$user_name = $user->getUser_name();
			$data = str_replace ("%%USER_NAME%%", $user_name, $data);
		} else {
			$data = str_replace ("%%USER_NAME%%", "[No Username Found]", $data);
		}
	}

	if (strpos($data,'%%MEMBER_HOME_PAGE%%')!== false) {//found the string - so replace with session data
		$data = str_replace ("%%MEMBER_HOME_PAGE%%", $_SESSION['dap_member_home_page'], $data);
	}
	
	if (strpos($data,'%%AFF_LINK%%')!== false) {//found the string
		if(isset($user)) {
			$userId = $user->getId();
			$affLink = trim(Dap_Config::get("SITE_URL_DAP"),"/") . "/dap/a/?a=" . $userId; //Aff id looks like this: http://digitalaccesspass.com/dap/a/?a=1
			$data = str_replace ("%%AFF_LINK%%", $affLink, $data);
		} else {
			$data = str_replace ("%%AFF_LINK%%", "[No Affiliate Info Found]", $data);
		}
	}
	
	if (strpos($data,'%%SELFSERVICE%%')!== false) {//found the string - so replace with session data
		ob_start();
		eval("?>" . file_get_contents($lldocroot . "/dap/inc/content/selfService.inc.php"));
		$output = ob_get_contents();
		ob_end_clean();
		$data = str_replace ("%%SELFSERVICE%%", $output, $data);
	}

	if (strpos($data,'%%CREDITHISTORY%%')!== false) {//found the string - so replace with session data
		ob_start();
		eval("?>" . file_get_contents($lldocroot . "/dap/inc/content/creditHistory.inc.php"));
		$output = ob_get_contents();
		ob_end_clean();
		$data = str_replace ("%%CREDITHISTORY%%", $output, $data);
	}	

	if (strpos($data,'%%CREDITSTORE%%')!== false) {//found the string - so replace with session data
		ob_start();
		eval("?>" . file_get_contents($lldocroot . "/dap/inc/content/creditStore.inc.php"));
		$output = ob_get_contents();
		ob_end_clean();
		$data = str_replace ("%%CREDITSTORE%%", $output, $data);
	}
	
	if (strpos($data,'%%PAYPALCONFIRM%%')!== false) {//found the string - so replace with session data
		ob_start();
		eval("?>" . file_get_contents($lldocroot . "/dap/PaypalCheckoutConfirm.php"));
		$output = ob_get_contents();
		ob_end_clean();
		$data = str_replace ("%%PAYPALCONFIRM%%", $output, $data);
		
	}
	
	
	if (strpos($data,'%%SALES_PAGE_URL%%') !== false) {//found the string - so replace with data
		//logToFile("SERVER['REQUEST_URI']: " . $_SERVER['REQUEST_URI']); 
		$msg = "";
		$req = rtrim($_SERVER['REQUEST_URI'],"/");
		$product = Dap_Product::getProductDetailsByResource($req);
		if(isset($product)) {
			//logToFile("Yup, product is set"); 
			$msg = $product->getSales_page_url();
		}
		$data = str_replace ("%%SALES_PAGE_URL%%", $msg, $data);
	}
	
	if (strpos($data,'%%DAPCART%%')!== false) {//found the string - so replace with session data
		if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
      		session_start();
    	}
		ob_start();
		eval("?>" . file_get_contents($lldocroot . "/dap/checkout.php"));
		$output = ob_get_contents();
		ob_end_clean();
		//logToFile("DAPCART:  output=" . $output);
		$data = str_replace ("%%DAPCART%%", $output, $data);
		
		//unset($_SESSION["err_text"]);
		return $data;
	}	
	
	if (strpos($data,'%%DAPCARTSUMMARY%%')!== false) {//found the string - so replace with session data
		if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
      		session_start();
    	}
		ob_start();
		eval("?>" . file_get_contents($lldocroot . "/dap/CheckoutConfirm.php"));
		$output = ob_get_contents();

		//logToFile("DAPCARTCONFIRM:  output=" . $output);
		$data = str_replace ("%%DAPCARTSUMMARY%%", $output, $data);
		
		//unset($_SESSION["err_text"]);
		return;	
	}	
	
	if (strpos($data,'%%USER_ID%%')!== false) {//found the string - so replace with session data
		if(isset($user)) {
			$userId = $user->getId();
			$data = str_replace ("%%USER_ID%%", $userId, $data);
		} else {
			$data = str_replace ("%%USER_ID%%", "[Not logged in]", $data);
		}
	}

	if (strpos($data,'%%PASSWORD%%')!== false) {//found the string - so replace with session data
		if(isset($user)) {
			$password = $user->getPassword();
			$data = str_replace ("%%PASSWORD%%", $password, $data);
		} else {
			$data = str_replace ("%%PASSWORD%%", "[Not logged in]", $data);
		}
	}
	
	
	if (strpos($data,'%%SITE_NAME%%')!== false) {//found the string - so replace with session data
		$data = str_replace ("%%SITE_NAME%%", Dap_Config::get("SITE_NAME"), $data);
	}	
	
	if (strpos($data,'%%DAPCUSTOMFIELD_')!== false) {//found the string - so replace with session data
		$data = dap_personalize_custom_fields($user, $data);
	}	
	
	return $data;
}


function dap_personalize_custom_fields($user, $data) {
	//hi, your tax id is %%custom_tax%% and your ssn is %%custom_ssn%%.
	$count = substr_count($data, "%%DAPCUSTOMFIELD_"); 
	//count = 2
	//logToFile("DAP-WP-LiveLinks.php: dap_personalize_custom_fields: occurences=" . $count);
	
	for($i=0; $i<$count;$i++) {
		$remaining_data = stristr($data,"%%DAPCUSTOMFIELD_");
		
		//$remaining_data = tax%% and your ssn is %%custom_ssn%%
		//logToFile("DAP-WP-LiveLinks.php: dap_personalize_custom_fields:: remaining_data=" . $remaining_data);
		
		if($remaining_data) {
			$new_data = substr($remaining_data,17);
			$pos = strpos($new_data, "%%");
			//$pos=3
			//logToFile("DAP-WP-LiveLinks.php: dap_personalize_custom_fields: pos=" . $pos);
					
			if ($pos !== false) {
				$custom_field_name = substr($new_data, 0, intval($pos));
				//custom_field_name = tax
				//logToFile("DAP-WP-LiveLinks.php: dap_personalize_custom_fields: custom_field_name=" . $custom_field_name);
				
				if(isset($user)) {
					$userId = $user->getId();
				  	$user_custom_value = Dap_UserCustomFields::loadUserCustomFieldsByCustomFieldName($custom_field_name, $userId);
				  	$value = "";
			  
				  	if ($user_custom_value) {
					  	foreach ($user_custom_value as $val) {
							//logToFile("DAP-WP-LiveLinks.php: dap_personalize_custom_fields: val=" . $val['custom_value']);
							$value = $val['custom_value'];
							$data = str_replace("%%DAPCUSTOMFIELD_" . $custom_field_name . "%%", $value, $data);
						} //foreach
					} else {
						//logToFile("DAP-WP-LiveLinks.php: dap_personalize_custom_fields: " . $custom_field_name);
						$data = str_replace("%%DAPCUSTOMFIELD_" . $custom_field_name . "%%", $value, $data);
					}
				} //if(isset($user))
				else {
					$data = str_replace("%%DAPCUSTOMFIELD_" . $custom_field_name . "%%", "[Not logged in]", $data);
				}
 			}
			else { break; }
		} //if
		else break;
	} // for
	
	return $data;
}

function dap_personalize_error($data) {
	if (strpos($data,'%%') === false) return $data;
	
	$lldocroot = "";
	if( defined('SITEROOT') ) {
		$lldocroot = SITEROOT;
	} else {
		$lldocroot = $_SERVER['DOCUMENT_ROOT'];
	}
	include_once ($lldocroot . "/dap/dap-config.php");	

	if (strpos($data,'%%MSG%%') !== false) {//found the string - so replace with data
		$msg = "Nothing to see here :-)";
		//if( isset($_GET['msg']) ) {
			//$msg = "<h3><div align='center'><font color='#CC0000'>" . stripslashes($_GET['msg']) . "</font></div></h3>";
		//}
		
		if(isset($_GET['request']) && isset($_GET['msg'])) {
			$msg = $_GET['msg'];
			$req = $_GET['request'];		
			$product = Dap_Product::getProductDetailsByResource($req);
			$_SESSION['request'] = $req;
			$pos = strpos($msg, "DAP006");
			if(!($pos === false)) {
				header("Location:".Dap_Config::get("LOGIN_URL")."?msg=$msg&request=$req");
			}
			
			if(isset($product)) {
				$msg = "This content is part of the product: <br/><br/>
				<a href=" . $product->getSales_page_url() . ">" . $product->getName() . "</a><br/>" . 
				$product->getDescription();
			}
		}
		
		$data = str_replace ("%%MSG%%", $msg, $data);
	}
	
	if (strpos($data,'%%SALES_PAGE_URL%%') !== false) {//found the string - so replace with data
		if( isset($_GET['request']) ) {
			$msg = "";
			Dap_Config::loadConfig(true);
			$req = $_GET['request'];		
			$product = Dap_Product::getProductDetailsByResource($req);
			$_SESSION['request'] = $req;
			if(isset($product)) {
				$msg = $product->getSales_page_url();
			}
		}
		$data = str_replace ("%%SALES_PAGE_URL%%", $msg, $data);
	}
	
	$data = mb_convert_encoding($data, "UTF-8", "auto");
	return $data;
}

/******Newly added to remove  post_type product******************/	  
function dap_remove_element($array,$value) {
	  return array_diff($array, (is_array($value) ? $value : array($value)));
}

function dap_permalink_dump($data) {
	global $wpdb;
	global $table_prefix;
	
	$lldocroot = "";
	if( defined('SITEROOT') ) {
		$lldocroot = SITEROOT;
	} else {
		$lldocroot = $_SERVER['DOCUMENT_ROOT'];
	}
	
	try {
	$fp = fopen($lldocroot . '/dap/dap_permalink_dump.php', 'w');
	fwrite($fp,  "----------------- POSTS -----------------\n");
	
	//$posts = get_posts('showposts=1000');
	$q = "SELECT ID FROM " . $table_prefix . "posts WHERE post_status='publish' AND post_type='post' ORDER BY post_date DESC";
	$posts = $wpdb->get_results($q);
	foreach( $posts as $post ) :
		fwrite($fp,  get_permalink($post->ID) . "\n");
	endforeach;
	
	//$pages = get_pages('');
	fwrite($fp,  "----------------- PAGES -----------------\n");
	$q = "SELECT ID FROM " . $table_prefix . "posts WHERE post_status='publish' AND post_type='page' ORDER BY post_date DESC";
	$pages = $wpdb->get_results($q);
	foreach( $pages as $page ) :
		fwrite($fp,  get_page_link($page->ID) . "\n");
	endforeach;
	
	$args = array(
		'public'   => true,
		'_builtin' => false
	);

	$output = 'names'; // names or objects, note names is the default
	$operator = 'and'; // 'and' or 'or'

	$post_types1 = get_post_types( $args, $output, $operator ); 
	
	/******Added because it is creating error when woo-commerce is there for post_type product and other custom post type******************/	  
	$post_types2 = dap_remove_element($post_types1,'product');
	$post_types3 = dap_remove_element($post_types2,'tcb_symbol');
	$post_types = dap_remove_element($post_types3,'tcb_lightbox');
	
	/*$post_types3 = dap_remove_element($post_types2,'sfwd-topic');
	$post_types4 = dap_remove_element($post_types3,'sfwd-lessons');
	$post_types6 = dap_remove_element($post_types5,'sfwd-courses');
	$post_types7 = dap_remove_element($post_types6,'sfwd-quiz');
	$post_types8 = dap_remove_element($post_types7,'sfwd-essays');
	$post_types9 = dap_remove_element($post_types8,'sfwd-assignment');
	$post_types11 = dap_remove_element($post_types10,'sfwd-certificates');
	$post_types = dap_remove_element($post_types11,'sfwd-transactions');*/


	fwrite($fp,  "----------- CUSTOM POST TYPES ----------\n");
	if(isset($post_types)){
		foreach ( $post_types  as $post_type ) {
	
		//logToFile("DAP-WP-LiveLinks.php: dap_permalink_dump: post_type=" . $post_type);	
		 
			$args = array( 'post_type' => $post_type, 'posts_per_page' => -1);
			$custom_posts = get_posts($args);
			foreach ( $custom_posts  as $post )
			{
				fwrite($fp,  get_permalink($post->ID) . "\n");	
			}  
		 
		}
	}
	
	fclose($fp);
	}
	catch (PDOException $e) {
			logToFile($e->getMessage(),LOG_DEBUG_DAP);
			throw $e;
	} catch (Exception $e) {
			logToFile($e->getMessage(),LOG_DEBUG_DAP);
			throw $e;
	}
  	return $data;
}


function dap_permalink_dump_menu_fix ($data) {
	global $wpdb;
	global $table_prefix;
	
	$lldocroot = "";
	if( defined('SITEROOT') ) {
		$lldocroot = SITEROOT;
	} else {
		$lldocroot = $_SERVER['DOCUMENT_ROOT'];
	}
	
	if(defined("DO_NOT_UPDATE_PERMALINK_ON_MENU_SAVE") && DO_NOT_UPDATE_PERMALINK_ON_MENU_SAVE == "Y"){
		return;
	}
	
	try {
	$fp = fopen($lldocroot . '/dap/dap_permalink_dump.php', 'w');
	fwrite($fp,  "----------------- POSTS -----------------\n");
	
	//$posts = get_posts('showposts=1000');
	$q = "SELECT ID FROM " . $table_prefix . "posts WHERE post_status='publish' AND post_type='post' ORDER BY post_date DESC";
	$posts = $wpdb->get_results($q);
	foreach( $posts as $post ) :
		fwrite($fp,  get_permalink($post->ID) . "\n");
	endforeach;
	
	//$pages = get_pages('');
	fwrite($fp,  "----------------- PAGES -----------------\n");
	$q = "SELECT ID FROM " . $table_prefix . "posts WHERE post_status='publish' AND post_type='page' ORDER BY post_date DESC";
	$pages = $wpdb->get_results($q);
	foreach( $pages as $page ) :
		fwrite($fp,  get_page_link($page->ID) . "\n");
	endforeach;
	
	$args = array(
		'public'   => true,
		'_builtin' => false
	);

	$output = 'names'; // names or objects, note names is the default
	$operator = 'and'; // 'and' or 'or'

	$post_types1 = get_post_types( $args, $output, $operator ); 
	
	/******Added because it is creating error when woo-commerce is there for post_type product and other custom post type******************/	  
	$post_types2 = dap_remove_element($post_types1,'product');
	$post_types3 = dap_remove_element($post_types2,'tcb_symbol');
	$post_types = dap_remove_element($post_types3,'tcb_lightbox');
	
	/*$post_types3 = dap_remove_element($post_types2,'sfwd-topic');
	$post_types4 = dap_remove_element($post_types3,'sfwd-lessons');
	$post_types6 = dap_remove_element($post_types5,'sfwd-courses');
	$post_types7 = dap_remove_element($post_types6,'sfwd-quiz');
	$post_types8 = dap_remove_element($post_types7,'sfwd-essays');
	$post_types9 = dap_remove_element($post_types8,'sfwd-assignment');
	$post_types11 = dap_remove_element($post_types10,'sfwd-certificates');
	$post_types = dap_remove_element($post_types11,'sfwd-transactions');*/


	fwrite($fp,  "----------- CUSTOM POST TYPES ----------\n");
	if(isset($post_types)){
		foreach ( $post_types  as $post_type ) {
	
		//logToFile("DAP-WP-LiveLinks.php: dap_permalink_dump: post_type=" . $post_type);	
		 
			$args = array( 'post_type' => $post_type, 'posts_per_page' => -1);
			$custom_posts = get_posts($args);
			foreach ( $custom_posts  as $post )
			{
				fwrite($fp,  get_permalink($post->ID) . "\n");	
			}  
		 
		}
	}
	
	fclose($fp);
	}
	catch (PDOException $e) {
			logToFile($e->getMessage(),LOG_DEBUG_DAP);
			throw $e;
	} catch (Exception $e) {
			logToFile($e->getMessage(),LOG_DEBUG_DAP);
			throw $e;
	}
  	return $data;
}


/*********For New Member pages**********/

function dap_add_pages() {

	add_menu_page('DigitalAccessPass', 'Digital Access Pass (DAP)', 'manage_options', 'dapHome', 'dap_wp_admin');
	add_submenu_page('dapHome', 'DAP Member Pages', 'DAP Member Pages' , 'administrator' , 'dap_member_pages' , 'dap_member_pages' );
	add_submenu_page('dapHome', 'Customize Settings', 'Customize Settings' , 'administrator' , 'dap_member_settings' , 'dap_member_settings' );
	add_submenu_page('dapHome', 'Pay-Per-Post Settings', 'Pay-Per-Post Settings' , 'administrator' , 'dap_pay_per_post_settings' , 'dap_pay_per_post_settings' );
	add_submenu_page('dapHome', 'Content Thumbnail', 'Content Thumbnail' , 'administrator' , 'dap_postmeta_settings' , 'dap_postmeta_settings' );
	add_submenu_page('dapHome', 'DAP Shortcode', 'DAP Shortcode' , 'administrator' , 'dap_shortcodes' , 'dap_shortcodes' );
	//add_submenu_page('dapHome', 'DAP Security Scan', 'DAP Security Scan' , 'administrator' , 'dap_security_scan' , 'dap_security_scan' );
	add_submenu_page('dapHome', 'DAP Member Pages Old', 'DAP Member Pages Old' , 'administrator' , 'dap_memberpages' , 'dap_memberpages' );
	
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_mycontent'  , 'dap_mycontent' );
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_myprofile'  , 'dap_myprofile' );
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_affiliateinfo'  , 'dap_affiliateinfo' );
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_invoice'  , 'dap_invoice' );	
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_member_invoice'  , 'dap_member_invoice' );	
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_member_cancellation'  , 'dap_member_cancellation' );	
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_create_member_pages'  , 'dap_create_member_pages' );
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_member_subaccount'  , 'dap_member_subaccount' );		
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_cancel'  , 'dap_cancel' );	
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_loginform'  , 'dap_loginform' );	
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_membersubscription'  , 'dap_membersubscription' );	
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_member_login'  , 'dap_member_login' );	
	
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_member_content'  , 'dap_member_content' );	
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_member_profile'  , 'dap_member_profile' );	
	add_submenu_page(null, '', ''  , 'administrator' , 'dap_member_affiliate'  , 'dap_member_affiliate' );	
	
}
 
//Include file for member login page 
include_once(plugin_dir_path(__FILE__)."DAP-Member-Pages-Function.php");
 
function dap_member_settings(){
	require_once("DAP-Member-Settings-Page.php");
} 
 
function dap_member_login(){
	require_once("DAP-Member-Login-Page.php");
} 
function dap_member_content(){
	require_once("DAP-Member-Content-Page.php");
} 
function dap_member_profile(){
	require_once("DAP-Member-Profile-Page.php");
} 

function dap_pay_per_post_settings(){	
	require_once("DAP-PayPerPost-Page.php");	
}
function dap_postmeta_settings(){	
	require_once("DAP-Postmeta-Settings.php");	
}

function dap_member_affiliate(){
	
	require_once("DAP-Member-Affiliate-Page.php");
	
}
 
function dap_member_pages(){
	require_once("DAP-Member-Pages.php");
}   
 
function dap_memberpages(){	
	 require_once("DAP-ShortCodes-MemberPages.php");
} 

function dap_mycontent(){
	require_once("DAP-ShortCodes-MyContent.php");
}

function dap_myprofile(){
	require_once("DAP-ShortCodes-MyProfile.php");
}

function dap_loginform(){
	require_once("DAP-ShortCodes-LoginForm.php");
}
function dap_affiliateinfo(){
	 require_once("DAP-ShortCodes-AffiliateInfo.php");
}

function dap_invoice(){
	require_once("DAP-ShortCodes-Invoice.php");
}

function dap_member_invoice(){
	require_once("DAP-ShortCodes-MembersInvoice.php");
}

function dap_member_cancellation(){
	require_once("DAP-ShortCodes-MembersCancellation.php");
}

function dap_member_subaccount(){
	require_once("DAP-ShortCodes-MembersSubaccount.php");
}

function dap_create_member_pages(){
	require_once("DAP-Create-Member-Pages.php");
}

function dap_cancel(){
	require_once("DAP-ShortCodes-CancelPause.php");
}
function dap_shortcodes(){
	require_once("DAP-ShortCodes.php");
}

function dap_security_scan(){
	require_once("DAP-SecurityScan.php");
}
 
if(is_admin()){ 
	add_action( "admin_enqueue_scripts", "dapCommonScripts" );
	
	
	add_action('admin_enqueue_scripts', 'members_uploader_enqueue');

}


 // Media uploader
function members_uploader_enqueue() {
	if($_GET['page']=='dap_member_login'){
		wp_enqueue_media();
		wp_register_script( 'media-lib-uploader-js', plugins_url( 'media-lib-uploader.js' , __FILE__ ), array('jquery') );
		wp_enqueue_script( 'media-lib-uploader-js' );
	}
}

function dapCommonScripts(){
	
	$include_common_jscss_on_page = array(
		"dap_memberpages",
		"dap_mycontent",						
		"dap_shortcodes",
		"dap_myprofile",
		"dap_affiliateinfo",
		"dap_invoice",
		"dap_cancel",
		"dap_loginform",
		"dap_security_scan",
		"dap_member_pages",
		"dap_member_settings",
		"dap_member_login",
		"dap_member_content",
		"dap_member_profile",
		"dap_member_affiliate",
		"dap_member_invoice",
		"dap_member_cancellation",
		"dap_create_member_pages",
		"dap_member_subaccount",
		"dap_pay_per_post_settings",
		"dap_postmeta_settings",
	);

	if(in_array($_GET["page"], $include_common_jscss_on_page)){
		wp_register_script('dap-jquery-js',  '//code.jquery.com/jquery-3.3.1.min.js');	
		wp_enqueue_script( 'dap-jquery-js' );			
		wp_register_script('dap-bootstrap-js',  '//stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js');	
		wp_enqueue_script( 'dap-bootstrap-js' );		
		wp_register_style( 'dap-bootstrap-css',   plugin_dir_url(__FILE__). 'includes/css/bootstrap.min.css', false, '1.0.0' );	
		wp_enqueue_style( 'dap-bootstrap-css' );		
		wp_register_style( 'font-awesome.min.css', '//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css', false, '1.0.0' );	
		wp_enqueue_style( 'font-awesome.min.css' );		
		wp_register_style( 'dap-memberpages-css', plugin_dir_url(__FILE__). 'includes/css/dap_memberpages.css', false, '1.0.0' );	
		wp_enqueue_style( 'dap-memberpages-css' );		
		
		$include_tinymce_js_on_page = array('dap_member_login', 'dap_member_content', 'dap_member_profile','dap_member_affiliate', 'dap_member_cancellation', 'dap_member_invoice', 'dap_create_member_pages', 'dap_member_subaccount','dap_member_settings' , 'dap_postmeta_settings');
		if(in_array($_GET['page'], $include_tinymce_js_on_page)){
			wp_enqueue_script("dap_member_tinymce-min-js", "//cdn.tinymce.com/4/tinymce.min.js?ver=4.9.4", array("jquery"));

		}
		
		$include_bootstrap_slider_js_css_on_page = array('dap_member_login', 'dap_member_content', 'dap_member_profile','dap_member_affiliate', 'dap_member_invoice' , 'dap_member_cancellation', 'dap_create_member_pages','dap_member_settings', 'dap_member_subaccount','dap_pay_per_post_settings');
		if(in_array($_GET['page'], $include_bootstrap_slider_js_css_on_page)){
			wp_enqueue_style( "dap_member_bootstrap_slider_min","//cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/10.0.2/css/bootstrap-slider.min.css", false, "10.0.2" );
			wp_enqueue_script( "dap_member_bootstrap_slider_min","//cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/10.0.2/bootstrap-slider.min.js", false, "10.0.2" );
			wp_enqueue_style("dap_member_bootstrap_colorpicker_min","//cdnjs.cloudflare.com/ajax/libs/bootstrap-colorpicker/2.5.2/css/bootstrap-colorpicker.min.css", false, "2.5.2" );
			wp_enqueue_script("dap_member_bootstrap_colorpicker_min-js","//cdnjs.cloudflare.com/ajax/libs/bootstrap-colorpicker/2.5.2/js/bootstrap-colorpicker.min.js", false, "2.5.2" );
			wp_enqueue_script("dap_member_sweetalert2-min-js", "//cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.16.0/sweetalert2.all.js", array('jquery'),null,true);
			wp_enqueue_style( "dap_member_sweetalert2-min-css","//cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.16.0/sweetalert2.css", false, "7.16.0");
			
		}		
		
	}

	 if($_GET['page']=='dap_memberpages'){ 	 				  
		wp_register_script('dap-memberpages-js', plugin_dir_url(__FILE__). 'includes/js/dap_memberpages.js');	
		wp_enqueue_script( 'dap-memberpages-js' );		 
		 
		 
	}else  if($_GET['page']=='dap_shortcodes'){ 
		wp_register_style( 'jquery-ui-css1', '//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css', false, '1.0.0' );	
		wp_enqueue_style( 'jquery-ui-css1' );	
		wp_register_script('dap-jquery1-js',  '//code.jquery.com/ui/1.11.4/jquery-ui.js');	
		wp_enqueue_script( 'dap-jquery1-js' );	
		wp_register_script('dap-tinymce-js',  '//cdn.tinymce.com/4/tinymce.min.js');	
		wp_enqueue_script( 'dap-tinymce-js' );	 
		wp_register_script('dap-shortcode-js', plugin_dir_url(__FILE__). 'includes/js/dap_shortcode.js?11');	
		wp_enqueue_script( 'dap-shortcode-js' );		
		wp_register_style( 'dap_shortcode.css', plugin_dir_url(__FILE__). 'includes/css/dap_shortcode.css', false, '1.0.0' );	
		wp_enqueue_style( 'dap_shortcode.css' );
		
	}else  if($_GET['page']=='dap_mycontent'){  

		wp_register_script('dap-bootstrap-colorpicker-js', plugin_dir_url(__FILE__). 'includes/js/bootstrap-colorpicker.js');
		wp_enqueue_script( 'dap-bootstrap-colorpicker-js' );
		wp_register_script('dap-bootstrap-slider-js', plugin_dir_url(__FILE__). 'includes/js/bootstrap-slider.js');
		wp_enqueue_script( 'dap-bootstrap-slider-js' );				
		wp_register_script('dap-memberpages-js', plugin_dir_url(__FILE__). 'includes/js/dap_memberpages.js');
		wp_enqueue_script( 'dap-memberpages-js' );
		wp_register_style( 'dap-bootstrap-colorpicker-css', plugin_dir_url(__FILE__). 'includes/css/bootstrap-colorpicker.min.css', false, '1.0.0' );
		wp_enqueue_style( 'dap-bootstrap-colorpicker-css' );
		wp_register_style( 'dap-bootstrap-slider-css', plugin_dir_url(__FILE__). 'includes/css/bootstrap-slider.css', false, '1.0.0' );
		wp_enqueue_style( 'dap-bootstrap-slider-css' );
		wp_register_style( 'dap-mycontent-css', plugin_dir_url(__FILE__). 'includes/css/dap-mycontent.css', false, '1.0.0' );
		wp_enqueue_style( 'dap-mycontent-css' );
		
	}else  if($_GET['page']=='dap_myprofile'){ 
		
		wp_register_script('dap-tinymce-js',  '//cdn.tinymce.com/4/tinymce.min.js');	
		wp_enqueue_script( 'dap-tinymce-js' );		
		wp_register_style( 'dap-mycontent-css', plugin_dir_url(__FILE__). 'includes/css/dap-mycontent.css', false, '1.0.0' );
		wp_enqueue_style( 'dap-mycontent-css' );
		
	}else  if($_GET['page']=='dap_cancel'){ 
		wp_register_script('dap-bootstrap-colorpicker-js', plugin_dir_url(__FILE__). 'includes/js/bootstrap-colorpicker.js');
		wp_enqueue_script( 'dap-bootstrap-colorpicker-js' );
		wp_register_script('dap-bootstrap-slider-js', plugin_dir_url(__FILE__). 'includes/js/bootstrap-slider.js');
		wp_enqueue_script( 'dap-bootstrap-slider-js' );		
		
		wp_register_script('dap-memberpages-js', plugin_dir_url(__FILE__). 'includes/js/dap_memberpages.js');
		wp_enqueue_script( 'dap-memberpages-js' );
		wp_register_style( 'dap-bootstrap-colorpicker-css', plugin_dir_url(__FILE__). 'includes/css/bootstrap-colorpicker.min.css', false, '1.0.0' );
		wp_enqueue_style( 'dap-bootstrap-colorpicker-css' );
		wp_register_style( 'dap-bootstrap-slider-css', plugin_dir_url(__FILE__). 'includes/css/bootstrap-slider.css', false, '1.0.0' );
		wp_enqueue_style( 'dap-bootstrap-slider-css' );
		
	}else  if($_GET['page']=='dap_loginform'){ 
		wp_register_script('dap-bootstrap-colorpickerjs', plugin_dir_url(__FILE__). 'includes/js/bootstrap-colorpicker.js');
		wp_enqueue_script( 'dap-bootstrap-colorpickerjs' );
		wp_register_style( 'dap-bootstrap-colorpicker-css', plugin_dir_url(__FILE__). 'includes/css/bootstrap-colorpicker.min.css', false, '1.0.0' );
		wp_enqueue_style( 'dap-bootstrap-colorpicker-css' );
		wp_register_script('dap-tinymce-js',  '//cdn.tinymce.com/4/tinymce.min.js');	
		wp_enqueue_script( 'dap-tinymce-js' ); 		
		wp_register_style( 'dap_shortcode.css', plugin_dir_url(__FILE__). 'includes/css/dap_shortcode.css', false, '1.0.0' );	
		wp_enqueue_style( 'dap_shortcode.css' );	
			
	}else  if($_GET['page']=='dap_security_scan'){ 
		
		wp_register_style( 'bootstrap.css',  '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', false, '1.0.0' );	
		wp_enqueue_style( 'bootstrap.css' );
		wp_register_style( 'dap-datatables.css',  '//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css', false, '1.0.0' );	
		wp_enqueue_style( 'dap-datatables.css' );
		wp_register_script('dap-dataTables-js',  '//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js');	
		wp_enqueue_script( 'dap-dataTables-js' ); 	
		wp_register_style( 'dap-sweetalert2.css',  '//cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.16.0/sweetalert2.css', false, '1.0.0' );	
		wp_enqueue_style( 'dap-sweetalert2.css' );
		wp_register_script('dap-sweetalert2-js',  '//cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.16.0/sweetalert2.all.js');	
		wp_enqueue_script( 'dap-sweetalert2-js' ); 	
		wp_register_script('dap_security_scan-js',  plugin_dir_url(__FILE__). 'includes/js/dap_security_scan.js');	
		wp_enqueue_script( 'dap_security_scan-js' ); 	
		wp_register_style( 'dap_security_scan.css', plugin_dir_url(__FILE__). 'includes/css/dap_security_scan.css', false, '1.0.0' );	
		wp_enqueue_style( 'dap_security_scan.css' );
	
	}else  if($_GET['page'] == 'dap_member_pages' || $_GET['page'] == 'dap_create_member_pages'){ 
		
		wp_enqueue_style( 'dap_member_pages_dataTables.css', '//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css', false, '1.0.0' );
		wp_enqueue_script('dap_member_pages-dataTables-js',  '//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js');	
		
		wp_enqueue_script('dap_member_pages_bootstrap-js',  '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js');	
		
		wp_enqueue_style( 'dap_member_pages_bootstrap.css', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', false, '1.0.0' );
		wp_enqueue_style( 'dap_member_pages_fonts_awesome_all.css', '//use.fontawesome.com/releases/v5.3.1/css/all.css', false, '1.0.0' );
		wp_enqueue_style( 'dap_member_pages_fonts_awesome.css', '//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css', false, '1.0.0' );
		wp_enqueue_style( 'dap_member_pages_fonts.css', '//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800&display=swap', false, '1.0.0' );
		
		wp_enqueue_style( 'dap_member_pages_common.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_pages_common.css?'.rand(10,1000), false, '1.0.0' );
		wp_enqueue_style( 'dap_member_pages.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_pages.css?'.rand(10,1000), false, '1.0.0' );
		wp_enqueue_script('dap_member_pages-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_pages.js?'.rand(10,1000));	
		wp_enqueue_script('dap_member_common-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_common.js?'.rand(10,1000));
		wp_enqueue_script('dap_swal-js',  '//unpkg.com/sweetalert/dist/sweetalert.min.js?'.rand(10,1000));
		
	}else  if($_GET['page'] == 'dap_member_login'){ 
		wp_enqueue_style('dap_member_google_font','//fonts.googleapis.com/css?family=Open+Sans%3A400%2C600%2C700&#038;display=swap', false, "2.5.2" );
		wp_enqueue_style( 'dap_member_bootstrap.css', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', false, '1.0.0' );
		wp_enqueue_style( 'dap_member_pages_common.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_pages_common.css?'.rand(10,1000), false, '1.0.0' );
		wp_enqueue_style( 'dap_member_login.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_login.css', false, '1.0.0' );
		wp_enqueue_script('dap_member_login-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_login.js?'.rand(10,1000));	
		wp_enqueue_script('dap_member_common-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_common.js?'.rand(10,1000));
		
	}else  if($_GET['page'] == 'dap_member_content'){ 
			wp_enqueue_style( 'dap_member_bootstrap.css', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', false, '1.0.0' );
			wp_enqueue_style('dap_member_toggle_min','//gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css', false, "2.5.2" );
			wp_enqueue_script('dap_member_toggle_min','//gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js', false, "2.5.2" );
			
			wp_enqueue_style( 'dap_member_pages_common.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_pages_common.css?'.rand(10,1000), false, '1.0.0' );		 
			wp_enqueue_style( 'dap_member_content.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_content.css?v='.rand(10,1000), false, '1.0.0' );		
			wp_enqueue_script('dap_member_common-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_common.js?'.rand(10,1000));
			wp_enqueue_script('dap_member_content ',  plugin_dir_url(__FILE__). 'includes/js/dap_member_content.js?'.rand(10,1000));
			
	}else  if($_GET['page'] == 'dap_member_profile'){ 
		    wp_enqueue_style('dap_member_google_font','//fonts.googleapis.com/css?family=Open+Sans%3A400%2C600%2C700&#038;display=swap', false, "2.5.2" );
			wp_enqueue_style( 'dap_member_bootstrap.css', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', false, '1.0.0' );
			wp_enqueue_style('dap_member_toggle_min','//gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css', false, "2.5.2" );
			wp_enqueue_script('dap_member_toggle_min','//gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js', false, "2.5.2" );
			
			wp_enqueue_style( 'dap_member_pages_common.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_pages_common.css?'.rand(10,1000), false, '1.0.0' );		 
			wp_enqueue_style( 'dap_member_profile.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_profile.css?'.rand(10,1000), false, '1.0.0' );		
			wp_enqueue_script('dap_member_common-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_common.js?'.rand(10,1000));
			wp_enqueue_script('dap_member_profile ',  plugin_dir_url(__FILE__). 'includes/js/dap_member_profile.js?'.rand(10,1000));	
		
		
	}else  if($_GET['page'] == 'dap_member_settings'){ 
		wp_enqueue_style( 'dap_member_bootstrap.css', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', false, '1.0.0' );
		wp_enqueue_style( 'dap_member_pages_common.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_pages_common.css?'.rand(10,1000), false, '1.0.0' );
		wp_enqueue_style( 'dap_member_settings.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_settings.css', false, '1.0.0' );
		wp_enqueue_script('dap_member_settings-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_settings.js?'.rand(10,1000));	
		wp_enqueue_script('dap_member_common-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_common.js?'.rand(10,1000));
		
	}else  if($_GET['page'] == 'dap_member_affiliate'){ 
		
		wp_enqueue_style('dap_member_google_font','//fonts.googleapis.com/css?family=Open+Sans%3A400%2C600%2C700&#038;display=swap', false, "2.5.2" );
		wp_enqueue_style('dap_member_toggle_min','//gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css', false, "2.5.2" );
		wp_enqueue_script('dap_member_toggle_min','//gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js', false, "2.5.2" );
			
		
		wp_enqueue_style( 'dap_member_bootstrap.css', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', false, '1.0.0' );
		wp_enqueue_style( 'dap_member_pages_common.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_pages_common.css?'.rand(10,1000), false, '1.0.0' );
		wp_enqueue_style( 'dap_member_affiliate.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_affiliate.css?'.rand(10,1000), false, '1.0.0' );
		
		wp_enqueue_script('dap_member_common-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_common.js?'.rand(10,100000));	
		wp_enqueue_script('dap_member_affiliate-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_affiliate.js?'.rand(10,1000));	
	}else  if($_GET['page'] == 'dap_member_invoice'){ 
		
		wp_enqueue_style('dap_member_toggle_min','//gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css', false, "2.5.2" );
		wp_enqueue_script('dap_member_toggle_min','//gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js', false, "2.5.2" );
			
		
		wp_enqueue_style( 'dap_member_bootstrap.css', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', false, '1.0.0' );
		wp_enqueue_style( 'dap_member_pages_common.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_pages_common.css?'.rand(10,1000), false, '1.0.0' );
		wp_enqueue_style( 'dap_member_invoice.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_invoice.css?'.rand(10,1000), false, '1.0.0' );
		
		wp_enqueue_script('dap_member_common-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_common.js?'.rand(10,1000));	
		wp_enqueue_script('dap_member_invoice-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_invoice.js?'.rand(10,1000));	
	}
	else  if($_GET['page'] == 'dap_member_cancellation'){ 
		
		wp_enqueue_style('dap_member_toggle_min','//gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css', false, "2.5.2" );
		wp_enqueue_script('dap_member_toggle_min','//gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js', false, "2.5.2" );
			
		
		wp_enqueue_style( 'dap_member_bootstrap.css', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', false, '1.0.0' );
		wp_enqueue_style( 'dap_member_pages_common.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_pages_common.css?'.rand(10,1000), false, '1.0.0' );
		wp_enqueue_style( 'dap_member_cancellation.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_cancellation.css?'.rand(10,1000), false, '1.0.0' );
		
		wp_enqueue_script('dap_member_common-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_common.js?'.rand(10,1000));	
		wp_enqueue_script('dap_member_cancellation-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_cancellation.js?'.rand(10,1000));	
		
		wp_register_script('dap-bootstrap-colorpickerjs', plugin_dir_url(__FILE__). 'includes/js/bootstrap-colorpicker.js');
		wp_enqueue_script( 'dap-bootstrap-colorpickerjs' );
		wp_register_style( 'dap-bootstrap-colorpicker-css', plugin_dir_url(__FILE__). 'includes/css/bootstrap-colorpicker.min.css', false, '1.0.0' );
		
	}else  if($_GET['page'] == 'dap_member_subaccount'){ 
		
		wp_enqueue_style('dap_member_toggle_min','//gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css', false, "2.5.2" );
		wp_enqueue_script('dap_member_toggle_min','//gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js', false, "2.5.2" );
			
		
		wp_enqueue_style( 'dap_member_bootstrap.css', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', false, '1.0.0' );
		wp_enqueue_style( 'dap_member_pages_common.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_pages_common.css?'.rand(10,1000), false, '1.0.0' );
		wp_enqueue_style( 'dap_member_subaccount.css', plugin_dir_url(__FILE__). 'includes/css/dap_member_subaccount.css?'.rand(10,1000), false, '1.0.0' );
		
		wp_enqueue_script('dap_member_common-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_common.js?'.rand(10,1000));	
		wp_enqueue_script('dap_member_subaccount-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_subaccount.js?'.rand(10,1000));	
		
		wp_register_script('dap-bootstrap-colorpickerjs', plugin_dir_url(__FILE__). 'includes/js/bootstrap-colorpicker.js');
		wp_enqueue_script( 'dap-bootstrap-colorpickerjs' );
		wp_register_style( 'dap-bootstrap-colorpicker-css', plugin_dir_url(__FILE__). 'includes/css/bootstrap-colorpicker.min.css', false, '1.0.0' );
		
	}else  if($_GET['page'] == 'dap_pay_per_post_settings'){
		
 
		wp_enqueue_script('dap_member_settings-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_settings.js');	
		wp_enqueue_script('dap_member_common-js',  plugin_dir_url(__FILE__). 'includes/js/dap_member_common.js?'.rand(10,1000));	
		 	
		wp_enqueue_style( 'dap_pay_per_post_settings_dataTables.css', '//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css', false, '1.0.0' );	
		wp_enqueue_script('dap_pay_per_post_settings-dataTables-js',  '//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js');		
		wp_enqueue_style( 'dap_pay_per_post_settings.css', plugin_dir_url(__FILE__). 'includes/css/dap_postmetabox_settings.css',  false, '1.0.0' );	
		wp_enqueue_script('dap_postmetabox_settings-js',  plugin_dir_url(__FILE__). 'includes/js/dap_postmetabox_settings.js?'.rand(10,1000));	
			
	}else  if($_GET['page'] == 'dap_postmeta_settings'){  
		wp_enqueue_script("dap_member_sweetalert2-min-js", "//cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.16.0/sweetalert2.all.js", array('jquery'),null,true);
		wp_enqueue_style( "dap_member_sweetalert2-min-css","//cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.16.0/sweetalert2.css", false, "7.16.0");			
	 	wp_enqueue_script('dap_pay_per_post_settings-dataTables-js',  '//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js');		
		wp_enqueue_style( 'dap_pay_per_post_settings.css', plugin_dir_url(__FILE__). 'includes/css/dap_postmetabox_settings.css',  false, '1.0.0' );	
		wp_enqueue_style( 'dap_postmeta_settings.css', plugin_dir_url(__FILE__). 'includes/css/dap_postmeta_settings.css',  false, '1.0.0' );	
		wp_enqueue_script('dap_postmetabox_settings-js',  plugin_dir_url(__FILE__). 'includes/js/dap_postmeta_settings.js?'.rand(10,1000));		
	} 
	
	
}
/*********For New Member pages**********/


// Top Level Menu Page (Configs)

function dap_wp_admin() {
	global $reset_password;
	$lldocroot = "";
	if( defined('SITEROOT') ) {
		$lldocroot = SITEROOT;
	} else {
		$lldocroot = $_SERVER['DOCUMENT_ROOT'];
	}
	include_once ($lldocroot . "/dap/dap-config.php");	
    
	$session = Dap_Session::getSession();
	if( !isset($session) || !Dap_Session::isLoggedIn() || !$session->isAdmin() ) {
		//session_destroy();
		//$msg = "Sorry, you are either not logged in - or not authorized to view this page.";
		
		if($reset_password == "Y"){
			echo '<iframe src = "/dap/admin/resetForm.php" width="100%" height="2550" frameborder="0" marginheight="0" marginwidth="0" scrolling="auto">
				<p>Your browser does not support iframes.</p>
				</iframe><style>#wpcontent {   padding-left: 0;}</style>';
		}else{
			echo '<iframe src = "'  . Dap_Config::get("LOGIN_URL") . '?request=/dap/admin/" width="100%" height="1550" frameborder="0" marginheight="0" marginwidth="0" scrolling="auto">
			<p>Your browser does not support iframes.</p>
			</iframe><style>#wpcontent {   padding-left: 0;}</style>';
		}

	} else if( Dap_Session::isLoggedIn() && $session->isAdmin() ) {
		echo '<iframe src ="/dap/admin/index.php" width="100%" height="2550" frameborder="0" marginheight="0" marginwidth="0" scrolling="auto">
			<p>Your browser does not support iframes.</p>
			</iframe><style>#wpcontent {   padding-left: 0;}</style>
			';
	}
}



function dap_wp_sync() {
	 logToFile("In dap_wp_sync");
	
	global $current_user;
	
	$lldocroot = "";
	if( defined('SITEROOT') ) {
		$lldocroot = SITEROOT;
	} else {
		$lldocroot = $_SERVER['DOCUMENT_ROOT'];
	}
	include_once ($lldocroot . "/dap/dap-config.php");
	
	//Do not sync WP admin or DAP admin
	$session = Dap_Session::getSession();
	if( is_admin() || user_can($current_user->ID, 'administrator') || (isset($session) && Dap_Session::isLoggedIn() && $session->isAdmin()) ) {
		return;
	}
	
	$blogName = get_bloginfo('name');
	$blogName = preg_replace("/[^A-Za-z0-9]/", "", $blogName );
	//logToFile("blog name: " . $blogName); 
	
	$matchFound = false;
	
	if( Dap_Config::get("DAP_WP_SYNC") == "N" ) {
		 logToFile("DAP_WP_SYNC = 'N'"); 
		return;
	}
	
	//If dap-wp-nosync is deliberately set (to anything), don't do any syncing and just return
	if( isset($_SESSION["dap-wp-nosync"]) && ($_SESSION["dap-wp-nosync"] != "") ) {
		//logToFile("dap-wp-nosync returning 1 : " . $_SESSION["dap-wp-nosync"]);
		if( isset($_SESSION[$blogName]) && ($_SESSION[$blogName] != "") ) { //already synced for this specific blog
			//logToFile("blogName: " . $_SESSION[$blogName]);
		//	logToFile("Already synced for this blog: Not syncing and returning"); 
			return; //No need to sync or create user in WP
		}
	}
	
	//logToFile("Going to sync now...");
	if(!Dap_Session::isLoggedIn()) { //Not logged in
		//logToFile("NOT Logged In, so returning");
		return;
	}
	
	require_once ( ABSPATH . WPINC . '/registration.php' );
	require_once( ABSPATH . 'wp-includes/class-phpass.php');

	if(Dap_Session::isLoggedIn()) {
		//If it gets here, it means new session, or user updated profile, and sync/create is required
	//	logToFile("Logged In");
		$session = DAP_Session::getSession();
		$user = $session->getUser();
		//logToFile("Id: " . $user->getId() . ", First name: " . $user->getFirst_name() . ", Last Name: " . $user->getLast_name() . ", User Name: " . $user->getUser_name()); 
		
		try {
			
			$username = "";
			
			/** 
				First, check if there's a $_SESSION["wpUsername"] in session. 
				If yes, previously synced user, and WP username is known
			*/
			$wpUsername = ( isset($_SESSION["wpUsername"]) && ($_SESSION["wpUsername"] != "") ) ? $_SESSION["wpUsername"] : "";
		//	logToFile("wpUsername: $wpUsername"); 
			if( ($wpUsername != "") && isset($_SESSION[$blogName]) ) {
				//Simply sync blindly from DAP to WP and get out
				$dapUsername = $user->getUser_name();
					
				$userarrayupd = array();
				$id = username_exists($wpUsername);
				$userarrayupd['ID'] = $id;
				$wpUser = get_userdata($id);
				
				if( (Dap_Config::get("WP_SYNC_IF_USERNAME") == "N") && isset($dapUsername) && ($dapUsername!="") ) {
					$userarrayupd['user_login'] = $dapUsername;
				} else {
					$userarrayupd['user_login'] = $wpUsername;
				}
				
				$userarrayupd['user_pass'] = $user->getPassword();                 
				$userarrayupd['user_email'] = $user->getEmail();
				$userarrayupd['first_name'] = $user->getFirst_name();
				$userarrayupd['last_name'] = $user->getLast_name();
				$userarrayupd['role'] = "";
				$userarrayupd['role'] = getDAPProductRole($user->getId());
				if($userarrayupd['role'] == ""){
					if ($user->isPaidUser()) {
						$userarrayupd['role'] = Dap_Config::get("WP_DEF_ROLE_PAID");
					} else {
						$userarrayupd['role'] = Dap_Config::get("WP_DEF_ROLE_FREE");
					}
				}
				$userarrayupd['role'] = ($userarrayupd['role'] == "") ? "subscriber" : $userarrayupd['role']; //default to subscriber for v<=3.9
			
				if($wpUser->display_name != "") {
					$userarrayupd['display_name'] = $wpUser->display_name;
				} else {
					$userarrayupd['display_name'] = $user->getFirst_name() . $user->getLast_name();
				}
				
				logToFile("Updating user role to: " . $userarrayupd['role'],LOG_DEBUG_DAP); 

				wp_update_user($userarrayupd);
				$_SESSION["dap-wp-nosync"] = "Y";
				$_SESSION[$blogName] = "Y";
				return;
			}
			
			/** 
				Before checking anything, see if DAP username/email match with WP username/email
				If yes, then it means matching user found. So don't even bother checking for anything else.
				Simply log in user using actual WP 'username' field
			*/
			//logToFile("Dap username: " . $user->getUser_name());
			//logToFile("Does it exist in WP: " . username_exists($user->getUser_name()));
			
			if(Dap_Config::get("WP_SYNC_IF_USERNAME") == "Y") {
				/*
					v>=4.0: Sync only if username exists.
					If DAP username is not set, don't sync
				*/
				//logToFile("WP_SYNC_IF_USERNAME is set to 'Y'"); 
				$username = $user->getUser_name();
				if( !isset($username) || ($username=="") ) {
					//Set sync to something. Setting to "Y" so it won't try to sync again for the rest of this session
					//Unless of course a) user updates profile, or b) logs out and logs back in
					//logToFile("Username is not set in DAP. So no sync. Returning");
					$_SESSION["dap-wp-nosync"] = "Y";
					$_SESSION[$blogName] = "Y";
					return;
				}
				
			}

			
			//Continuing.....
			
			/**
				If you get here, then it means WP_SYNC_IF_USERNAME == "N" (Which means sync regardless of DAP user name)
				OR
				It could also mean WP_SYNC_IF_USERNAME == "Y" but there IS a username in DAP
				(could happen if user updated user profile to enter new username in DAP)
			*/
			
			/**
			Check for these 3... if none match, then new user
			1.WP username = DAP username?			
			2.WP username = DAP Email?			
			3.WP username = DAP FirstLast?			
			*/
			
			//1.WP username = DAP username?			
			if( ($user->getUser_name() != "") && username_exists($user->getUser_name()) ) {
			//	logToFile("Case 1 match"); 
				//If DAP username found in WP, then also make sure emails and passwords match
				$id = username_exists($user->getUser_name());
				$userWP = get_userdata($id);
				//logToFile("Email in WP: " . $userWP->user_email); 
				//logToFile("Email in DAP: " . $user->getEmail()); 
				//logToFile("Password in WP: " . $userWP->user_pass); 
				//logToFile("Password (normal) in DAP: " . $user->getPassword()); 
				//logToFile("Password in DAP: " . wp_hash_password($user->getPassword())); 
				//$wpPass = new PasswordHash();
				
				$passwordsMatched = false;
				$wp_hasher = new PasswordHash(8, TRUE);
				if($wp_hasher->CheckPassword($user->getPassword(), $userWP->user_pass)) {
   					//logToFile("YES, Passwords Matched");
					$passwordsMatched = true;
				}
				
				//if( ($userWP->user_email === $user->getEmail()) && ($passwordsMatched) ) { 	
				
				if( ($userWP->user_email === $user->getEmail()) ) { 
					//Found correct user in both DAP & WP, so use actual 'username' to log in
					//logToFile("Matching username found: " . $user->getUser_name() . ", so not bothering with anything else"); 
					$username = $user->getUser_name();
					$matchFound = true;
				} else {
					//Username match found, but no match between DAP & WP emails. So username already taken by someone else
					//So do not sync, and return
					//logToFile("Matching username " . $user->getUser_name() . " found. But no match between DAP and WP emails or password. So someone in WP already has taken this username");
					$_SESSION["dap-wp-nosync"] = "Y";
					$_SESSION[$blogName] = "Y";
					return;
				}
			} 
			
			
			//2.WP username = DAP Email?
			if( !$matchFound && ($id = username_exists($user->getEmail())) ) {
			//	logToFile("Case 2 match"); 
				//Check if passwords match
				$userWP = get_userdata($id);
				if( $userWP->user_pass == md5($user->getPassword()) ) { 
					//Found correct user in both DAP & WP, so use actual 'username' to log in
					//logToFile("Matching username found: " . $user->getUser_name() . ", so not bothering with anything else"); 
					$username = $user->getEmail();
					$matchFound = true;
				} else {
					//Username match found, but no match between DAP & WP passwords. So username already taken by someone else
					//So do not sync, and return
					//logToFile("Matching username " . $user->getUser_name() . " found. But no match between DAP and WP emails. So someone in WP already has taken this username");
					$_SESSION["dap-wp-nosync"] = "Y";
					$_SESSION[$blogName] = "Y";
					return;
				}
			}
			
			
			/**
				No username in WP same as DAP username.
				No username in WP same as DAP email.
				Now check if username exists in WP that is same as FirstNameLastName in DAP
			*/
			if( !$matchFound && ($id = username_exists($user->getFirst_name() . $user->getLast_name())) ) {
			//	logToFile("Case 3 match"); 
				//$id = username_exists($user->getFirst_name() . $user->getLast_name());
				$userWP = get_userdata($id);
				if( ($userWP->user_email == $user->getEmail()) && ( $userWP->user_pass == md5($user->getPassword()) ) ) { 
					//Found correct user in both DAP & WP, so use actual 'username' to log in
					//logToFile("Matching username found: " . $user->getUser_name() . ", so not bothering with anything else"); 
					$username = $user->getFirst_name() . $user->getLast_name();
				}  else {
					/*
						Username match found, but no match between DAP & WP passwords. 
						So FirstnameLastname already taken by someone else
						But it's ok if someone else has taken FirstnameLastName as username
						Still need to check if DAP username is different from WP Username. 
						If they are different, then this is a different user.
					*/

					if( $user->getUser_name() ==  $userWP->user_login ) {
						//Sorry, DAP username & WP username are also same. Can't use this username
						//logToFile("Username " . $user->getUser_name() . " found. But no match between DAP FirstnameLastname and WP username. Also, DAP username is same as WP username. So someone in WP already has taken this username");
						$_SESSION["dap-wp-nosync"] = "Y";
						$_SESSION[$blogName] = "Y";
						return;
					}
				}
			}
			$addUserToBBGroup = false;
			/**
				No username or email or FirstnameLastname match between DAP and WP
				Possible New User
			*/
			if (!$matchFound) {
				$addUserToBBGroup = true;
				/**
					USED TO BE...
					v<=3.9. Not forced to "sync only if username exists"
					So just sync using email
					
					Starting 03/11/2011, no longer using email as username. For now, hard-coded to FirstnameLastname.
					In next release of LL, it will become a configurable option
				*/
				//logToFile("WP_SYNC_IF_USERNAME is set to 'N' or is blank ''"); 
				//$username = $user->getEmail();			
				/* Check if username already figured out - if not, then make it FirstnameLastname */
				//logToFile("Case ELSE"); 
				if( !isset($username) || ($username=="") ) { //username not figured out
					if ( $user->getUser_name() == "" ) { //if DAP user name is also blank, then set WP username to FirstLast
						$username = $user->getFirst_name() . $user->getLast_name();
						$username = preg_replace('/\s+/', '', $username);
						
						//Now WP username is set to FirstLast
						//DAP username is still blank
						/**
							If we update DAP username also to be FirstLast, then it will be a problem for vB users
							So one option is to let it remain blank
							which means, it will never come to this block ever again, 
							because next time, WP username will have a value, and will be 
							caught by previous IF block
							
							Or better yet, do not do this if vb is installed
						*/
						
						if( !defined("VBFORUMPATH") ) {
							//logToFile("Going to choose FirstnameLastname as username"); 
							//Update DAP username with this username
							$user->setUser_name($username);
							$user->update();
						}
						
						
					} else { //DAP username is not blank - so set WP username = DAP username
						$username = $user->getUser_name();
					}
				}
			}
			
			logToFile("About to insert/update",LOG_DEBUG_DAP); 
			$userarray = array();
			$userarray['user_login'] = $username;
			$userarray['display_name'] = $username;  
			//$userarray['display_name'] = $user->getFirst_name() . $user->getLast_name();
			$dapUserId= $user->getId();
			$userarray['user_email'] = $user->getEmail();
			$userarray['user_pass'] = $user->getPassword();                 
			$userarray['first_name'] = $user->getFirst_name();
			$userarray['last_name'] = $user->getLast_name(); 
			
			//$userarray['user_url'] = "";
			//$userarray['description'] = "";
			//$userarray['aim'] = "";
			//$userarray['yim'] = "";
			//$userarray['jabber'] = "";
			$userarray['user_nicename'] = $user->getFirst_name() . $user->getLast_name();  
			
			if( (Dap_Config::get("WP_SYNC_PAID_ONLY")=="Y") && (!$user->isPaidUser()) ) {
				//Sync only paid users is true - disable everyone else, except any WP admins
			//	logToFile("Not a paid user"); 
				if ( username_exists($username) || email_exists($user->getEmail()) ) { //just do an update
					$id = username_exists($username);
					
					//Now check if the WP user we just found has WP admin role.
					//If yes, then DO NOT disable even though he may be free user
					//$user = new WP_User( $user_id );
					if ( isUserToBeSyncedAWPAdmin ( $id ) ){
						$_SESSION["dap-wp-nosync"] = "Y";
						$_SESSION[$blogName] = "Y";
						return;
					}
					
					//Coming here means user is not paid user, and needs to be disabled
					//So just updating role to blank, so user cannot use anything in WP
					//that needs user to be logged in - like forums, commenting, etc
					//for when user was previously eligible and now not eligible (eg., because of a refund)
					
			//		logToFile("Updating to nothing...");
					$userarray['ID'] = $id;
					$userarray['role'] = ""; //set role to blank
					$userarray['role'] = getDAPProductRole($dapUserId);
					if($userarray['role'] == ""){
						if ($user->isPaidUser()) {
							$userarray['role'] = Dap_Config::get("WP_DEF_ROLE_PAID");
						} else {
							$userarray['role'] = Dap_Config::get("WP_DEF_ROLE_FREE");
						}
					}
					$userarray['role'] = ($userarray['role'] == "") ? "subscriber" : $userarray['role']; //default to subscriber for v<=3.9
					wp_set_current_user($id, null);
					wp_set_auth_cookie($id,false,'');
					wp_update_user($userarray);
				} 
				return;
			} else {
				//Sync everybody
				//Check if username also exists in WP
				//logToFile("About to Sync User now");
				$id = 0;
				
				/**
					This is the case where DAP username is blank
					So update as usual
				*/
				
				if ( username_exists($username) ) {   //just do an update
				//	logToFile("Username $username exists in WP, so just doing an update");
					$userarrayupd = array();
					$id = username_exists($username);
					
					// do not sync a DAP user to a WP "admin" user
					if( $id && (!is_user_logged_in() )){
						logToFile("DAP-WP-LiveLinks: dap_wp_sync(): user not logged-in to wp");
						$wpuser = get_userdata( $id );
						// Get all the user roles for this user as an array.
						if(isset($wpuser)) {
							$user_roles = $wpuser->roles;	
							if ( in_array( 'administrator', $user_roles, true ) ) {
								logToFile("DAP-WP-LiveLinks: dap_wp_sync(): User is an admin in WP");
							  // user is an administrator
							   $_SESSION["dap-wp-nosync"] = "Y";
								$_SESSION[$blogName] = "Y";
							   return;
							} 
						}
					}
					
					
					$userarrayupd['ID'] = $id;
					$userarrayupd['user_login'] = $username;
					$userarrayupd['user_pass'] = $user->getPassword();                 
					$userarrayupd['user_email'] = $user->getEmail();
					$userarrayupd['first_name'] = $user->getFirst_name();
					$userarrayupd['last_name'] = $user->getLast_name();
					$userarrayupd['role'] = "";
					$userarrayupd['role'] = getDAPProductRole($dapUserId);
					
				//	logToFile("getDAPProductRole is : " . $userarrayupd['role']); 
					if($userarrayupd['role'] == ""){
						if ($user->isPaidUser()) {
							$userarrayupd['role'] = Dap_Config::get("WP_DEF_ROLE_PAID");
						} else {
							$userarrayupd['role'] = Dap_Config::get("WP_DEF_ROLE_FREE");
						}
					}
					$userarrayupd['role'] = ($userarrayupd['role'] == "") ? "subscriber" : $userarrayupd['role']; //default to subscriber for v<=3.9
					//$userarrayupd['role'] = $userarray['role'];
					//$userarrayupd['display_name'] = $user->getFirst_name() . $user->getLast_name();
				//	logToFile("Updating user role to: " . $userarrayupd['role']); 

					wp_update_user($userarrayupd);
				} 
				
				else { 
					//New User in WP - First time sync
				//	logToFile("Username $username does not exist in WP, so doing an insert");
					//logToFile("New user"); 
					//logToFile("username: $username"); 
					$userarray['role'] = "";
					$userarray['role'] = getDAPProductRole($dapUserId);
					if($userarray['role'] == ""){
						if ($user->isPaidUser()) {
							$userarray['role'] = Dap_Config::get("WP_DEF_ROLE_PAID");
						} else {
							$userarray['role'] = Dap_Config::get("WP_DEF_ROLE_FREE");
						}
					}
					$userarray['role'] = ($userarray['role'] == "") ? "subscriber" : $userarray['role']; //default to subscriber for v<=3.9
					
					logToFile("Updating user role to: " . $userarray['role']); 
					
					wp_insert_user($userarray); //otherwise create			
					
					//retrieve login
					$id = username_exists($username);
					//logToFile("Got user's id: $id"); 
				}
			
				//Auto login user into WP
				//ob_end_clean();
				//ob_start();
				//logToFile("About to log username - $username - in to WP"); 
				wp_set_current_user($id, $username);
				
				$always_use_cookie = Dap_Config::get("ALWAYS_USE_COOKIE");
				
				if( isset($_SESSION["dapRememberMe"]) && ($_SESSION["dapRememberMe"] == "dapRememberMe") ) {
					logToFile("Remember me is ON. Doing wp_set_auth_cookie for id: $id"); 
					wp_set_auth_cookie($id,true,'');
					
					//added for dap settings ALWAYS_USE_COOKIE
				//} else if( isset($_SESSION["ALWAYSUSECOOKIE"]) && ($_SESSION["ALWAYSUSECOOKIE"] == "ALWAYSUSECOOKIE") ) {					
				} else if($always_use_cookie == "Y" ) {												
						logToFile("Remember me is OFF. Doing wp_set_auth_cookie for id:".$id." always_use_cookie = ".$always_use_cookie); 
													
						//added to change the default cookie days value	
						add_filter( 'auth_cookie_expiration', 'dapwp_change_expire_time', 10, 3 );
									
						wp_set_auth_cookie($id,true,'');  
						
				}else{
						logToFile("Remember me is OFF. Doing wp_set_auth_cookie for id: $id"); 
						wp_set_auth_cookie($id,false,'');				
				}
				
				//added newly for php 7.2
				$user = get_user_by('id',$id);
                 
				//logToFile("Autologging in $username"); 
				do_action('wp_login', $username, $user);
				$activatedPlugin = Dap_Config::get('BUDDYBOSSINTEGRATION');
	
				if($activatedPlugin == 'Y'){
					logToFile("DAP-WP-LiveLinks.php dap_wp_sync(): activatedPlugin".$activatedPlugin , LOG_DEBUG_DAP); 
					if($addUserToBBGroup && function_exists( 'groups_join_group' )){
						$bbGroupRules = dapGetAllBBGroupRules();
						if(isset($bbGroupRules) && is_array($bbGroupRules)){
							$groupListData = dapGetAllActiveProducts($dapUserId , $bbGroupRules);	
							$groupList = $groupListData['groupList'];
							$removegroupList = $groupListData['removegroupList'];
							
							if($groupList != ''){
								logToFile("DAP-WP-LiveLinks.php dap_wp_sync(): groupList is not empty".$groupList , LOG_DEBUG_DAP); 
								$groupList = explode(',',$groupList);	
								foreach($groupList as $gid){
									logToFile("gid is ".$gid);
									groups_join_group( $gid, $id );
								}
							}
							if($removegroupList != ''){
								foreach($removegroupList as $gid){
									logToFile("gid is ".$gid);
									groups_leave_group( $gid, $id );
								}	
							}
							$dapuser = Dap_User::loadUserById($dapUserId);
							dapAddUserToBBProfile($dapuser, '');
							
						}
					}
				}
				//logToFile("Autologging in $username"); 
				//do_action('wp_login', $username, 10, 2);
				$_SESSION["wpUsername"] = $username;
			}
			
			//Set sync to something. Setting to "Y" so it won't try to sync again for the duration of this session
			//Unless of course a) user updates profile, or b) logs out and logs back in
			//logToFile("Setting dap-wp-nosync so no more sync for this session - until User Profile is updated");
			$_SESSION["dap-wp-nosync"] = "Y";
			$_SESSION[$blogName] = "Y";
			return;
		} catch (PDOException $e) {
			logToFile($e->getMessage(),LOG_DEBUG_DAP);
			//throw $e;
		} catch (Exception $e) {
			logToFile($e->getMessage(),LOG_DEBUG_DAP);
			//throw $e;
		}
	}
}




function getDAPProductRole($userId){
	//logToFile("DAP-WP-LiveLinks.php: getDAPProductRole() enter userId=".$userId, LOG_DEBUG_DAP);
	$user = Dap_User::loadUserById($userId);
	$priority=0;
	$role="";
	
	if( isset($user) ) {
	//	logToFile("DAP-WP-LiveLinks.php: getDAPProductRole() got user details ", LOG_DEBUG_DAP);
		$userProductArr= Dap_UsersProducts::loadProducts($user->getId());
		
		foreach ($userProductArr as $userProduct) {
			$productId=$userProduct->getProduct_id();
		//	logToFile("DAP-WP-LiveLinks.php: getDAPProductRole() productId= ".$productId, LOG_DEBUG_DAP);
			$hasAccess = $user->hasAccessTo($productId);
			if($hasAccess){
			//	logToFile("DAP-WP-LiveLinks.php: getDAPProductRole() user has access", LOG_DEBUG_DAP);
				$productRolePriority= getDAPProductRolePriority($productId); //7
				if(isset($productRolePriority)){
					
					$currentrole = $productRolePriority[0];
					$currentpriority = $productRolePriority[1];
					
				//	logToFile("DAP-WP-LiveLinks.php: getDAPProductRole() currentrole=".$currentrole, LOG_DEBUG_DAP);
				//	logToFile("DAP-WP-LiveLinks.php: getDAPProductRole() currentpriority=".$currentpriority, LOG_DEBUG_DAP);
					
					if ($currentpriority > $priority) {
						$priority = $currentpriority ; 
						$role = $currentrole;
						
					//	logToFile("DAP-WP-LiveLinks.php: getDAPProductRole() role set to =".$role, LOG_DEBUG_DAP);
					
					}
				}
			}
		}
		if($role != ''){
			$roleArr = Dap_Role::loadByID($role);
			$role = $roleArr->getName();
			$role = strtolower($role);
		//	logToFile("DAP-WP-LiveLinks.php: getDAPProductRole() lowercase role set to =".$role, LOG_DEBUG_DAP);
		}
	}
	
	return $role;
}

function getDAPProductRolePriority($pId){
	logToFile("DAP-WP-LiveLinks.php: getDAPProductRolePriority() enter ", LOG_DEBUG_DAP);
	$productRolePriorityArr = Dap_ProductRoleMapping::loadByProductId($pId , '');
	$productRolePriority = array();
	if(isset($productRolePriorityArr)) {
		$productRolePriority[0] =  $productRolePriorityArr->getRoleId();
		$productRolePriority[1] =  $productRolePriorityArr->getNumber();
	}
	return $productRolePriority;
}

// Convert any properly structed HTML (or XML) into nested multidimensional arrays
function dap_xml2ary(&$string) {
    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parse_into_struct($parser, $string, $vals, $index);
    xml_parser_free($parser);

    $mnary=array();
    $ary=&$mnary;
    foreach ($vals as $r) {
        $t=$r['tag'];
        if ($r['type']=='open') {
            if (isset($ary[$t])) {
                if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
                $cv=&$ary[$t][count($ary[$t])-1];
            } else $cv=&$ary[$t];
            if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;}
            $cv['_c']=array();
            $cv['_c']['_p']=&$ary;
            $ary=&$cv['_c'];
        } elseif ($r['type']=='complete') {
            if (isset($ary[$t])) { // same as open
                if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
                $cv=&$ary[$t][count($ary[$t])-1];
            } else $cv=&$ary[$t];
            if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;}
            $cv['_v']=(isset($r['value']) ? $r['value'] : '');
        } elseif ($r['type']=='close') $ary=&$ary['_p'];
    }
    _dap_del_p($mnary);
    return $mnary;
}

// _Internal: Remove recursion in result array
function _dap_del_p(&$ary) {
    foreach ($ary as $k=>$v) {
        if ($k==='_p') unset($ary[$k]);
        elseif (is_array($ary[$k])) _dap_del_p($ary[$k]);
    }
}

// Array to XML
function dap_ary2xml($cary, $d=0, $forcetag='') {
	//logToFile($_SESSION['dap_url_cache']);
    $cache = $_SESSION['dap_url_cache'];
    if (!is_array($cache)) $cache = array();
	$size = count($cache);
	
	$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	$url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
	$tagPostID = dap_url_to_postid($url);
	
	$homeUrl = get_home_url();
	$homeArray = explode('/', $homeUrl);
	$blogPath = '';
	if(isset($homeArray[3])){
			$blogPath = $homeArray[3];
	}
	
	//logToFile("Cache size: " . $size); 
    
    $res=array();
    foreach ($cary as $tag=>$r) {
        if (isset($r[0])) $res[] = dap_ary2xml($r, $d, $tag);
        else {
            if ($forcetag) $tag=$forcetag;
            $sp=str_repeat("\t", $d);
            
            if ($tag == "li")
	        	if (isset($r["_c"]["a"]["_a"]["href"])) {
	            	// Should always go here, since all LIs should contain an A tag
					$permalink = getResourceFromString($r["_c"]["a"]["_a"]["href"]);
					
					if (array_key_exists($permalink, $cache)) {
						//logToFile("Page permalink exists: $permalink"); 
						//logToFile("cache[permalink]: " . $cache[$permalink]); 
						if ($cache[$permalink] == 'hide') {
							unset($cary[$tag]);
						}
					} else {
						$resource = isURLAllowed($permalink, $tagPostID, $blogPath);
						$errId = $resource->getError_id();
						// Something wrong with link, so unset it
						if (isset($errId)) {
							$cache[$permalink] = 'hide';
							unset($cary[$tag]);
						} else $cache[$permalink] = 'show';
					}
	            }
            // Only output the link and go to sublinks if permitted
            if ($cache[$permalink] != 'hide') {
	            $res[]="$sp<$tag";
	            if (isset($r['_a'])) {foreach ($r['_a'] as $at=>$av) $res[]=" $at=\"$av\"";}
	            $res[]=">".((isset($r['_c'])) ? "\n" : '');
	            if (isset($r['_c'])) $res[] = dap_ary2xml($r['_c'], $d+1);
	            elseif (isset($r['_v'])) $res[]=$r['_v'];
	            $res[]=(isset($r['_c']) ? $sp : '')."</$tag>\n";
	        }
        }
    }
	$_SESSION['dap_url_cache'] = $cache;
    return implode('', $res);
}

function dap_list_pages($content) {
	if( is_admin() && user_can($current_user->ID, 'administrator') ) {
		return $content;
	}
	//logToFile($_SESSION['dap_list_pages_cached_already']); 
	//logToFile("dap_list_pages BEFORE: " . $content); 
	
	//logToFile("in dap_list_pages"); 
	$lldocroot = "";
	if( defined('SITEROOT') ) {
		$lldocroot = SITEROOT;
	} else {
		$lldocroot = $_SERVER['DOCUMENT_ROOT'];
	}
	include_once ($lldocroot . "/dap/dap-config.php");	
	
	$showProtectedLinksInMenu = Dap_Config::get("SHOW_PROT_MENULINKS");
	$sneak_peek = Dap_Config::get("SNEAK_PEEK");
	
	// No filtering is done if Sneak Peek=Y or showProtectedLinksInMenu=N
	if(($showProtectedLinksInMenu == "Y") || ($sneak_peek == "Y")) {
		//logToFile("showProtectedLinksInMenu = Y or sneak peek = Y - so returning"); 
		return $content;
	}
	
	// Add wrapping UL tag, since wp_list_pages doesn't include it
	$content = "<ul>$content</ul>";
	
	// Convert the HTML returned by wp_list_pages into nested associative arrays
	$ary_content = dap_xml2ary($content);
	
	//if ($_GET["showlog"] == 1) var_dump($_SESSION["dap_url_cache"]);
			
	// The heavy lifting: filter the array for "allowed" pages
	// and convert array back into HTML (nested ULs)
	$content = dap_ary2xml($ary_content);
		
	// Remove the outermost UL tag we added at the start
	$content = preg_replace('/^([^<]*)<ul>(.*)<\/ul>([^<]*)$/s', '\1\2\3', $content);
	
	//logToFile("dap_list_pages AFTER: " . $content); 
	return $content;
}
//add_filter('get_pages', 'dap_list_pages');



function load_dap_widgets() {
	register_widget( 'DAP_LoginLogout' );
	register_widget('DAP_ProductLinks');
}


function wp_noautop($pee) {
	global $post;
	$noautop = get_post_meta($post->ID, 'noautop', true);
	if ( $noautop == '1' || $noautop = '') {
		return $pee;
	}
	else {
		return wpautop($pee);
	}
}

// disable auto-p
function less_filters(){
	// add conditional auto-p
	// disable auto-p
	remove_filter('the_content', 'wpautop');
	// add conditional auto-p
	add_filter('the_content', 'wp_noautop');
	
	// disable texturize
	remove_filter('comment_text', 'wptexturize');
	remove_filter('the_excerpt', 'wptexturize');
	remove_filter('the_content', 'wptexturize');
	#remove_filter('the_title', 'wptexturize');

	disable_kses_content();
}

// disable KSES for content, Working now
function disable_kses_content() {
	remove_filter('content_save_pre', 'wp_filter_post_kses');
	remove_filter('excerpt_save_pre', 'wp_filter_post_kses');
	remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
}


function dap_product_links($data) {
	$lldocroot = "";
	if( defined('SITEROOT') ) {
		$lldocroot = SITEROOT;
	} else {
		$lldocroot = $_SERVER['DOCUMENT_ROOT'];
	}
	include_once ($lldocroot . "/dap/dap-config.php");	
	
	//include ($_SERVER['DOCUMENT_ROOT'] . "/dap/dap-config.php");	

	if (strpos($data,'%%PRODUCT_DETAILS')!== false) {//found the string - so replace with session data
		if ( !Dap_Session::isLoggedIn() ) {
			return "Sorry, please <a href=\"" . Dap_Config::get("LOGIN_URL") . "\">login</a> before you can view this page.";
		}
		
		$session = Dap_Session::getSession();
		$user = $session->getUser();
		$content = "Sorry, you do not have access to this Product.";
		
		preg_match_all("/%%PRODUCT_DETAILS_(.*?)%%/", $data, $matches);
		$productId = $matches[1][0];
		
		$userProduct = Dap_UsersProducts::load($user->getId(), $productId);
		
		if( isset($userProduct) && ($userProduct != null) ) {
			$product = Dap_Product::loadProduct($productId);
		
			$content = getCss() . 
			'
	
			  <table id="dap_single_product_links_table"> 
					<tr> 
					  <td><strong>Product Name</strong>: ' . $product->getName() . '</span></td> 
					</tr> 
					<tr> 
					  <td><strong>Access Start Date</strong>: ' . $userProduct->getAccess_start_date() . '</td> 
					</tr> 
					<tr> 
					  <td><strong>Access End Date</strong>: ' . $userProduct->getAccess_end_date() . '</td> 
					</tr> 

					<tr> 
					  <td><strong>Description</strong>: ' . $product->getDescription() . '</td> 
					</tr> 
					<tr> 
					  <td>&nbsp;</td> 
					</tr> 
					<tr> 
					  <td><strong>Links</strong>: ' . $userProduct->getActiveResources() . '</td> 
					</tr> 
			   </table><br/><br/>';
		}
		  
		//logToFile("Content: $content"); 
		$data = str_replace("%%PRODUCT_DETAILS_".$matches[1][0]."%%", $content, $data);
	}

	return $data;
}

function addUserFacingCss() {
	$dapCssFile = "/dap/inc/content/userfacing.css";
	$lldocroot = "";
	if( defined('SITEROOT') ) {
		$lldocroot = SITEROOT;
	} else {
		$lldocroot = $_SERVER['DOCUMENT_ROOT'];
	}
	
	if( file_exists($lldocroot . "/dap/inc/content/customuserfacing.css") ) {
		$dapCssFile = "/dap/inc/content/customuserfacing.css";
	}
	
	wp_register_style('dapUserFacingCss', $dapCssFile);
	wp_enqueue_style( 'dapUserFacingCss');
}

function dap_user_profile_update($id) {
	if ( is_admin() && current_user_can('administrator') ) return;
	
	//logToFile("User being updated: id: $id"); 
	if( Dap_Session::isLoggedIn() ) { 
		$userWP = get_userdata($id);
		$session = Dap_Session::getSession();
		$user = $session->getUser();
		
		$wpFirstName = $userWP->user_firstname;
		$wpLastName = $userWP->user_lastname;
		$wpEmail = $userWP->user_email;
		//$wpPassword = $userWP->pre_user_user_pass;
		//$wpPassword = $old_user_data->user_firstname;
		//logToFile("$wpEmail | $wpFirstName | $wpLastName"); 
		
		$user->setFirst_name($wpFirstName);
		$user->setLast_name($wpLastName);
		$user->setEmail($wpEmail);
		try {
			$user->update();
		} catch (Exception $e) {
			logToFile($e->getMessage(),LOG_FATAL_DAP);
		}
		$session->setUser($user);
		unset($_SESSION["dap-wp-nosync"]);
		unset($_SESSION[$blogName]);
	}
}

function dap_logoutofdap() {
	//logToFile("User logging out of WP"); 
	$redirect = isset($_GET['redirect']) ? $_GET['redirect'] : Dap_Config::get("LOGGED_OUT_URL");
	if($redirect == "") $redirect = "/";
	pluginLogout();
	Dap_Session::closeSession();
	header("Location: $redirect");
	exit;
}

function disable_password_fields() {
	if ( !current_user_can('administrator') )
		$show_password_fields = add_filter( 'show_password_fields', '__return_false' );
}

function dap_clean_shortcode_content( $content ) {

    /* Parse nested shortcodes and add formatting. */
    //$content = trim( wpautop($content) );

    /* Remove '</p>' from the start of the string. */
    if ( substr( $content, 0, 4 ) == '</p>' )
        $content = substr( $content, 4 );

    /* Remove '<p>' from the end of the string. */
    if ( substr( $content, -3, 3 ) == '<p>' )
        $content = substr( $content, 0, -3 );

    /* Remove any instances of '<p></p>'. */
    $content = str_replace( array( '<p></p>' ), '', $content );

    return $content;
}


//-------------------------------------------------------------//
add_action('admin_menu', 'dap_add_pages');

add_filter('wp_insert_post' , 'dap_permalink_dump_menu_fix');
add_filter('deleted_post' , 'dap_permalink_dump');
add_filter('pre_post_update' , 'dap_permalink_dump_menu_fix');
add_filter('mod_rewrite_rules', 'dap_permalink_dump');	
add_filter('publish_page', 'dap_permalink_dump');	

register_activation_hook( __FILE__, 'dap_livelinks_activate');

add_filter('the_posts', 'dap_filter_posts'); 
add_filter('the_content_feed', 'dap_filter_posts'); 
add_filter('mod_rewrite_rules', 'dap_mod_rewrite');	

//Personalization
add_filter('the_content', 'dap_login'); 
add_filter('the_content', 'dap_personalize',99);
add_filter('the_content', 'dap_personalize_error');
add_filter('the_content', 'dap_product_links');
add_filter('the_title', 'dap_personalize');

add_action( 'widgets_init', 'load_dap_widgets' );
//DO NOT USE add_action('plugins_loaded', 'dap_loginform_widget_init');
//DO NOT USE add_action('wp_print_styles', 'addUserFacingCss');

add_filter('get_pages', 'dap_filter_posts_menu');
add_filter('wp_nav_menu_items', 'dap_list_pages');

add_action('profile_update','dap_user_profile_update');
add_action('wp_logout','dap_logoutofdap');
if ( is_admin() ) {
	add_action( 'init', 'disable_password_fields', 10 );
}
add_action( 'wp_enqueue_scripts', 'addDAPCSS' );


function isUserToBeSyncedAWPAdmin( $id ) {
	//logToFile("in isUserToBeSyncedAWPAdmin"); 
	$userWP = get_userdata($id);
	if ( !empty( $userWP->roles ) && is_array( $userWP->roles ) ) {
		foreach ( $userWP->roles as $role ) {
			//logToFile("------------------------------ ROLE: $role");
			if( $role == "administrator" ) { //Leave WP admins alone
				return true;
			}
		}
	}
	return false;
}

// wc order - cancel
function dap_woocommerce_order_status_cancelled( $order_id ) {

  $lldocroot = defined('SITEROOT') ? SITEROOT : $_SERVER['DOCUMENT_ROOT'];
  if(file_exists($lldocroot . "/dap/dap-config.php")) include_once ($lldocroot . "/dap/dap-wcpayment.php");
  
  logToFile("DAP-WP-LiveLinks.php:dap_woocommerce_order_status_cancelled(): ENTER... order_id=$order_id, order_status=" . $order_status,LOG_DEBUG_DAP);
  $order = new WC_Order( $order_id );
  processWCOrderCancellation($order, $post, "DAP-WP-Livelinks.dap_woocommerce_order_status_cancelled(): ");
  logToFile("DAP-WP-LiveLinks.php:dap_woocommerce_order_status_cancelled(): EXIT",LOG_DEBUG_DAP);
  return $order_status;
}

add_action( 'woocommerce_order_status_cancelled', 'dap_woocommerce_order_status_cancelled' );


// wc order - refund
function dap_woocommerce_order_status_refunded( $order_id ) {

  $lldocroot = defined('SITEROOT') ? SITEROOT : $_SERVER['DOCUMENT_ROOT'];
  if(file_exists($lldocroot . "/dap/dap-config.php")) include_once ($lldocroot . "/dap/dap-wcpayment.php");
  
  logToFile("DAP-WP-LiveLinks.php:dap_woocommerce_order_status_refunded(): ENTER... order_id=$order_id",LOG_DEBUG_DAP);
  $order = new WC_Order( $order_id );
  processWCSubscriptionRefund($order, $post, "DAP-WP-Livelinks.dap_woocommerce_order_status_refunded(): ");
  logToFile("DAP-WP-LiveLinks.php:dap_woocommerce_order_status_refunded(): EXIT",LOG_DEBUG_DAP);
  return $order_status;
}

add_action("woocommerce_order_status_refunded", "dap_woocommerce_order_status_refunded");

// wc order - complete
function dap_woocommerce_order_status_completed( $order_id ) {
	
  logToFile("DAP-WP-LiveLinks.php:dap_woocommerce_order_status_completed(): ENTER... order_id=$order_id",LOG_DEBUG_DAP);
  processPayment("completed", $order_id,"FIRST_PAYMENT");
  logToFile("DAP-WP-LiveLinks.php:dap_woocommerce_order_status_completed(): EXIT",LOG_DEBUG_DAP);
  return;
}

add_action( 'woocommerce_order_status_completed', 'dap_woocommerce_order_status_completed' );


//subscription order complete 
function processWCSubscriptionPayment( $order_status, $order_id ) {
	
  logToFile("DAP-WP-LiveLinks.php:processWCSubscriptionPayment(): ENTER... order_id=$order_id, order_status=" . $order_status,LOG_DEBUG_DAP);
  processPayment($order_status, $order_id,"FIRST_PAYMENT");
  // non-virtual order, return original status
  logToFile("DAP-WP-LiveLinks.php:processWCSubscriptionPayment(): EXIT",LOG_DEBUG_DAP);
  return $order_status;
}

add_filter( 'woocommerce_payment_complete_order_status', 'processWCSubscriptionPayment', 10, 2 );

function processPayment($order_status, $order_id, $paymentType, $recur_item_name="",$complete_payment="", $product_id="") {
	
	$lldocroot = defined('SITEROOT') ? SITEROOT : $_SERVER['DOCUMENT_ROOT'];
	if(file_exists($lldocroot . "/dap/dap-config.php")) include_once ($lldocroot . "/dap/dap-wcpayment.php");

	$order = new WC_Order( $order_id );
    $post=array();
	logToFile("DAP-WP-LiveLinks.php:processPayment(): ENTER... $order_status, $order_id",LOG_DEBUG_DAP);
	processSuccessfulWCPayment($order, $order_status, $order_id, $paymentType, $recur_item_name,$complete_payment, $product_id);
	logToFile("DAP-WP-LiveLinks.php:processPayment(): EXIT... $user_id, $subscription_key",LOG_DEBUG_DAP);

}

// subscription process cancellation
function processWCSubscriptionCancellation($user_id, $subscription_key) {
  logToFile("DAP-WP-LiveLinks.php:processWCSubscriptionCancellation(): ENTER... $user_id, $subscription_key",LOG_DEBUG_DAP);
  global $woocommerce;
  
  $lldocroot = defined('SITEROOT') ? SITEROOT : $_SERVER['DOCUMENT_ROOT'];
  if(file_exists($lldocroot . "/dap/dap-config.php")) include_once ($lldocroot . "/dap/dap-wcpayment.php");

  $subscription = WC_Subscriptions_Manager::get_users_subscription( $user_id, $subscription_key );
  processDAPWCSubscriptionCancellation($subscription, $post, "DAP-WP-Livelinks.processPaymentCancellation(): ");
  logToFile("DAP-WP-LiveLinks.php:processWCSubscriptionCancellation(): EXIT",LOG_DEBUG_DAP);
}

add_action("cancelled_subscription", "processWCSubscriptionCancellation", 10, 2);

//add_action("refunded_subscription", "processPaymentRefund", 10, 2);

//add_action("activated_subscription", "processRenewalOrder", 10, 2);

//public static function processRenewalOrder( $user_id, $subscription_key ) {

//recurring / subscription payment
function processSubscriptionRenewal(  $user_id, $subscription_key ) {
	
	logToFile("DAP-WP-Livelinks.php:processRenewalOrder(): ENTER processRenewalOrder : user=".$user_id);
	
	sendAdminEmail("WooCommerce->DAP: subscription payment received", "Subscription payment received for user_id=".$user_id);
	
	global $woocommerce;
	$lldocroot = defined('SITEROOT') ? SITEROOT : $_SERVER['DOCUMENT_ROOT'];
    if(file_exists($lldocroot . "/dap/dap-config.php")) include_once ($lldocroot . "/dap/dap-wcpayment.php");
	
	$subscription = WC_Subscriptions_Manager::get_users_subscription( $user_id, $subscription_key );
	processWCRenewals( $subscription, "DAP-WP-Livelinks.processSubscriptionRenewal(): " );
	
}

//add_action( 'processed_subscription_payment', 'processSubscriptionRenewal', 10, 2 );


add_action( 'user_register', 'wp_dap_registration_save', 10, 1 );

function wp_dap_registration_save( $user_id ) {
	
	if(isset($_SESSION["SQBUSER"]) && ($_SESSION["SQBUSER"] == "Y")) {
		logToFile("DAP-WP-Livelinks.php:wp_dap_registration_save(): SQB User - don't sync to DAP");
		return;
	}
	
    $user_info = get_userdata($user_id);
    $username = $user_info->user_login;
    $user_email = $user_info->user_email;
	$first_name = $user_info->first_name;
    $last_name = $user_info->last_name;
	
	if($first_name=="") {
		logToFile("DAP-WP-Livelinks.php:wp_dap_registration_save(): firstname empty, get from post data");
		if ( isset( $_POST['billing_first_name'] ) ) {
			$first_name = $_POST['billing_first_name'];
		}
		
	}
		
    $last_name = $user_info->last_name;
	if($last_name=="") {
		logToFile("DAP-WP-Livelinks.php:wp_dap_registration_save(): lastname empty, get from post data");
		if ( isset( $_POST['billing_last_name'] ) ) {
			$last_name = $_POST['billing_last_name'];
		}
		
	}
	
	
	//$password = $user_info->user_pass;
	$password=$_POST['account_password'];
	logToFile("DAP-WP-Livelinks.php:wp_dap_registration_save(): WP user=".$user_id.", email=".$user_email.", password=".$password);
	
	$user = new Dap_User();

	$user->setFirst_name( $first_name );
	$user->setLast_name( $last_name );
	
	$user->setUser_name( $username );	
	$user->setEmail( $user_email );	
	$user->setPassword( $password );	
	
	$user->setStatus("A");
	
	try {
		$user->create();
	}
	catch (PDOException $e) {
		logToFile($e->getMessage(),LOG_DEBUG_DAP);
	} catch (Exception $e) {
		logToFile($e->getMessage(),LOG_DEBUG_DAP);
	}
	
	logToFile("DAP-WP-Livelinks.php:wp_dap_registration_save(): created WP user in DAP successfully");
}


add_filter('send_password_change_email', 'wpPasswordNotification');


function wpPasswordNotification( ) {

  if ( !current_user_can('administrator') ) {
	  return false;
  }
  
  return true;
}

add_action('wp_ajax_live_links_invoice_logo_image_url', 'live_links_invoice_logo_image_url');
add_action('wp_ajax_nopriv_live_links_invoice_logo_image_url', 'live_links_invoice_logo_image_url');

function live_links_invoice_logo_image_url(){
	$filename = $_FILES['file']['name'];
	$temp = $_FILES['file']['tmp_name'];
	echo $path = WP_PLUGIN_DIR.'/DAP-WP-LiveLinks/includes/images/'.$filename;
	move_uploaded_file($temp,$path);
	exit;
}

add_action('wp_ajax_live_links_cancel_image_upload', 'live_links_cancel_image_upload');
function live_links_cancel_image_upload(){
	$filename = $_FILES['file']['name'];
	$temp = $_FILES['file']['tmp_name'];
	echo $path = WP_PLUGIN_DIR.'/DAP-WP-LiveLinks/includes/images/'.$filename;
	move_uploaded_file($temp,$path);
	exit;
}


/********addFileResourceToProduct  live_links_protected_content*******/
add_action('wp_ajax_live_links_protected_content', 'live_links_protected_content');
add_action('wp_ajax_nopriv_live_links_protected_content', 'live_links_protected_content');

function live_links_protected_content(){
	global $wpdb;
	global $current_user;
	if(!is_admin() && !user_can($current_user->ID, 'administrator')) return;
	logToFile("live_links_protected_content() called",LOG_DEBUG_DAP);
	$productIds =  $_POST['productId'];
	$url =  $_POST['url'];
	$name =  $_POST['name'];
	$display_in_list =  $_POST['display_in_list'];
	$start_day =  $_POST['start_day'];
	$end_day =  $_POST['end_day'];
	$start_date =  $_POST['start_date'];
	$end_date =  $_POST['end_date'];
	
	if(empty($start_day)){
		$start_day =0;
	}
	if(empty($end_day)){
		$end_day =0;
	}
	
	$dap_dbh = Dap_Connection::getConnection();
	
	foreach ($productIds as $productId){
		if(empty($productId) || $productId == 0){
		} else{
			$fr = new Dap_FileResource();
			$value = $fr->addFileResourceToProduct($productId, $url, $start_day, $credits_assigned=NULL,$cond_drip_order="");
	
			$row = $fr->getResourceId($url);
			if(!empty($row)) {
				$resourceId = $row["id"];
				$value1 = $fr->updateFileResource($productId, $resourceId, $name, $display_in_list, $product_resource_status="F", $is_free="N", $start_day, $end_day, $start_date, $end_date, $num_clicks="0", $credits_assigned="", $pay_per_post="0",$order="1", $excerpt="");
			}
		} 
	}
	$productList = null;
	$productList = Dap_Product::loadProducts("","A"); 

	$rows=$fr->getAllProductsForProtectedResource($url);
	if(!empty($rows)) { 
		foreach ($productList as $prod) {
			$product_ids[] = $prod->getId();
			$product_names[] = $prod->getName();
		}
		foreach($rows as $row){
			$rowid = $row["id"];
			$resource_id = $row["resource_id"];
			$product_id = $row["product_id"];
			$start_day = $row["start_day"];
			foreach ($productList as $prod) {

				if($prod->getId() == $product_id){ 
					$prodname =  $prod->getName();
					if(strlen($prodname) > 15){
						$productname[] =  $prod->getName(); 
						$product_name =  trim($prod->getName()); 
						$product_name_short[] = substr($product_name, 0, 15)."...";
					}else{ 
						$productname[] =  $prod->getName(); 
						$product_name_short[]  = $prodname;
					}
				}
			}  
		}
	}

	$all_row_data = array("total_rows"=> $rows, "product_name_short"=> $product_name_short,"productname"=> $productname,  "product_ids"=> $product_ids ,  "product_names"=> $product_names,  "productList"=> $productList);
	echo json_encode($all_row_data);
	exit;
} 


add_action('wp_ajax_delete_live_links_protected_content', 'delete_live_links_protected_content');
add_action('wp_ajax_nopriv_delete_live_links_protected_content', 'delete_live_links_protected_content');

function delete_live_links_protected_content(){
	global $current_user;
	if(!is_admin() && !user_can($current_user->ID, 'administrator')) return;
	
	$productId = $_POST['productId'];
	$resourceId = $_POST['resourceId'];
	$fr = new Dap_FileResource();
	$value2 = $fr->removeFileResourceFromProduct($productId, $resourceId);
	exit;
}

add_action('wp_ajax_delete_all_protected_content', 'delete_all_protected_content');
add_action('wp_ajax_nopriv_delete_all_protected_content', 'delete_all_protected_content');

function delete_all_protected_content(){
	global $current_user;
	if(!is_admin() && !user_can($current_user->ID, 'administrator')) return;
	
	$productIdsall = $_POST['productIds'];
	$resourceId = $_POST['resourceId'];
	$productIds_arr = rtrim($productIdsall, ',');
	$productIds = explode(",",$productIds_arr);
	foreach ($productIds as $productId){
		/* $frda = new Dap_FileResource();
		$value3 = $frda->removeFileResourcesFromAllProducts($productId,$resourceId); */
		$value3 = removeFileResourcesFromProducts($productId,$resourceId); 
	}
	exit;
}

add_action('wp_ajax_drip_day_settings_edit', 'drip_day_settings_edit');
add_action('wp_ajax_nopriv_drip_day_settings_edit', 'drip_day_settings_edit');

function drip_day_settings_edit(){
	global $wpdb;
	global $current_user;
	if(!is_admin() && !user_can($current_user->ID, 'administrator')) return;
	
	$rowId =  $_POST['rowId'];
	$start_day =  $_POST['dripval'];

	$dap_dbh = Dap_Connection::getConnection();
	$sql = "UPDATE dap_products_resources_jn SET start_day =:start_day where id=:id";
	$stmt = $dap_dbh->prepare($sql);
	$stmt->bindParam(':start_day', $start_day, PDO::PARAM_INT);
	$stmt->bindParam(':id', $rowId, PDO::PARAM_INT);
	$stmt->execute();
	exit;
}

function removeFileResourcesFromProducts($productId, $resourceId) {
		global $current_user;
		if(!is_admin() && !user_can($current_user->ID, 'administrator')) return;
		//Remove Resource from Product
		try {
			
			Dap_FileResource::removeFileResourceFromProduct($productId, $resourceId);			
			return;
			
		} catch (PDOException $e) {
			logToFile($e->getMessage(),LOG_FATAL_DAP);
			throw $e;
		} catch (Exception $e) {
			logToFile($e->getMessage(),LOG_FATAL_DAP);
			throw $e;
		}	
}

// Backend dapSecurityScan
add_action('wp_ajax_dapSecurityScanDelete', 'dapSecurityScanDelete');
add_action('wp_ajax_nopriv_dapSecurityScanDelete', 'dapSecurityScanDelete');

add_action('wp_ajax_dapCompareFiles', 'dapCompareFiles');
add_action('wp_ajax_nopriv_dapCompareFiles', 'dapCompareFiles');

add_action('wp_ajax_dapDeleteComparedFiles', 'dapDeleteComparedFiles');
add_action('wp_ajax_nopriv_dapDeleteComparedFiles', 'dapDeleteComparedFiles');

add_action('wp_ajax_getComparedFilesFromTable', 'getComparedFilesFromTable');
add_action('wp_ajax_nopriv_getComparedFilesFromTable', 'getComparedFilesFromTable');

add_action('wp_ajax_dapSecurityScan', 'dapSecurityScan');
add_action('wp_ajax_nopriv_dapSecurityScan', 'dapSecurityScan');

function dapSecurityScan(){
	
	global $wpdb;
	global $current_user;
	if(!is_admin() && !user_can($current_user->ID, 'administrator')) return;	 
	
	$scan_name = $_POST['scan_name'];
	$scan_value = $_POST['scan_scheduled'];
	
	$dapscan =  new Dap_SecurityScan();
	$dapscan->setName($scan_name);
	$dapscan->setValue($scan_value);
	 
	$record = Dap_SecurityScan::loadByName($scan_name);
 
	if(count($record) < 1){
		$id = $dapscan->create();		
	}else{
		$id = $dapscan->update();		
	}	 
	die;
}

function dapCompareFiles(){
	
	$lldocroot = defined('SITEROOT') ? SITEROOT : $_SERVER['DOCUMENT_ROOT'];
	$dapver = floatval(DAP_VERSION);
	
	$url = "https://digitalaccesspass.com/securityupdates/".$dapver.".php";
	$raw_response = wp_remote_post($url);
	$listOfFiles = unserialize($raw_response['body']);
	
	
	Dap_SecurityScanReport::delete();
	if(count($listOfFiles) && $listOfFiles != ''){	
		if (file_exists($lldocroot . "/dap/dap-config.php"))
			include_once ($lldocroot . "/dap/dap-config.php");  
		
		$dir = $lldocroot.'/dap';
		
		$results = getDirContents($dir);
		foreach($listOfFiles as $files){
			logToFile("functions.php: dapCompareFiles path".$lldocroot, LOG_DEBUG_DAP);
			$newListOfFiles[] = $lldocroot.$files;
		}
		$extraFiles = array();
		
		foreach($results as $result){
			
			if(substr($result, -1) == '/') {
				$result_new = substr($result, 0, -1);
				
				$result_new = explode('/' , $result_new);
				$finalValue = end($result_new);
				array_pop($result_new);
				
				$folder = implode('/', $result_new);
			}else{
				$result_new = explode('/' , $result);
				$finalValue = end($result_new);
				array_pop($result_new);
				
				$folder = implode('/', $result_new);
			}
			
			if(!in_array($result , $newListOfFiles)){
				array_push($extraFiles, $result);
				
				$scanReport = new Dap_SecurityScanReport();
				
				$scanReport->setFileName($finalValue);
				$scanReport->setFilePath($folder);
				$scanReport->setDate(date('Y-m-d H:m:s'));
				
				$scanReport->create();
				
			}
		}
	}else{
		if(isset($_REQUEST['callByAjax'])){
			echo json_encode('Not Supported');
			die;
		}else{
			return 'Not Supported';
		}
	}	
	if(isset($_REQUEST['callByAjax'])){
		echo json_encode($extraFiles);
		die;
	}else{
		return $extraFiles;
	}
}

function getDirContents($dir, &$results = array()){
	
    $files = scandir($dir);

    foreach($files as $key => $value){
        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
        if(!is_dir($path)) {
            $results[] = $path;
        } else if($value != "." && $value != "..") {
            getDirContents($path, $results);
            $results[] = $path;
        }
    }

    return $results;
}

function dapDeleteComparedFiles(){
	$fullPath  = $_REQUEST['fullPath'];
	$id  = $_REQUEST['id'];
	
	if(is_dir($fullPath)){
		rmdir($fullPath);
	}else{
		unlink($fullPath);	
	}
	
	$result = Dap_SecurityScanReport::delete($id);  
	
	
}


function getComparedFilesFromTable(){
	$rows = Dap_SecurityScanReport::load();
	    $html .= '<table class="table hover table-striped cell-border" id="dap_security_scan_table">';
		$html .= '<thead>';
	    $html .= '<tr>';
		$html .= '<th>id</th>';
		$html .= '<th>File Path</th>';
	    $html .= '<th>File Name</th>';
		$html .= '<th>Date</th>';
		$html .= '<th>Action</th>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody id="security_scan_result_table_body">';
	 foreach($rows as $row){ 
        
		$html .= '<tr id="pid_'.$row->getId().'" class="">';
		$html .= '<td class="table-checkbox-outer">';
		$html .= '<input type="hidden" id="file_full_path_'.$row->getId().'" value="'. $row->getFilePath(). "/".$row->getFileName().'" >';
		$html .= '<input type="checkbox" class="template_action" name="template_action" value="'. $row->getId() .'" id="'. $row->getId() .'">';
		$html .= '</td>';
		$html .= '<td class="product-name text-left">';
		if($row->getFilePath() != ''){  
		$html .= $row->getFilePath(); 
		} else{ 
		$html .=  '-';
		}  
		$html .= '</td>';					   
		$html .= '<td class="product-name text-left">';
		if($row->getFileName() != ''){  
			$html .= $row->getFileName(); 
		}else{
			$html .= '-';
		}   
		$html .= '</td>';	
		$html .= '<td class="updated_datel text-center">';
		$html .=  $row->getDate();
		$html .= '</td>';
		$html .= '<td class="editable-button text-center" >';
		$html .= '<div id="'. $row->getId() .'" name="select_action" class="btn-group">';								 
		$html .= '<a  title="Delete" data-id="'. $row->getId() .'" class="del_file_full_path" href="" >Delete </a>'; 
		$html .= '</div>';
		$html .= '</td>';
		$html .= '</tr>';
	} 
	$html .= '</tbody>';
	$html .= '</table>';					 
	echo json_encode($html);die;
	
}


add_action( 'wp_ajax_dap_member_login_authenticate', 'DapMemberLoginAuthenticateAjax' );
add_action( 'wp_ajax_nopriv_dap_member_login_authenticate','DapMemberLoginAuthenticateAjax');

function DapMemberLoginAuthenticateAjax(){
	$output = array();
	if(isset($_POST['email']) && isset($_POST['pass']) && class_exists('Dap_User')){
		
		$email = $_POST['email']; 
		$password = $_POST['pass']; 
		$action_id = $_POST['dap_action_id']; 
		if(dapMemberLoginCheckedCaptchaEnable($action_id)){			
		
		
			if(isset($_POST['recaptcharesponse'])){
			  $captcha=$_POST['recaptcharesponse'];
			}
			if(!$captcha){
			$output['error'] = dapMemberGetMessageByKeyAndAction('login','invalid_captcha');
			if($output['error'] == ''){
				$output['error'] = 'Please check the captcha form.';
			}
			echo json_encode($output);die;
			}
			
			if(isset($_POST['recaptcharesponse'])){
				if(!dapMemberLoginValidateCaptcha($_POST['recaptcharesponse'])){
					 $output['error'] = 'You are spammer ! Get the @$%K out.';
					echo json_encode($output);die;
				}
			}
		}
		
		
		if(($email != "") && ($password != "") && validateLogins($email, getIpOfUser()) && validateUserOnly($email,$password) ) {	
		
		  $output['success'] = dapMemberGetMessageByKeyAndAction('login','login_success');
		  $output['post_login_url']  = dapMemberGetPostLoginURl($action_id);
		  $output['form_action'] = '/dap/authenticate.php';
		  $gdpr_obj = DAP_MemberPagesValues::loadByActionIdAndName($action_id,'gdpr');
		  unset($_SESSION['gdprEnabled']);
		  if($gdpr_obj){
				$gdpr = $gdpr_obj->getValue();
				if($gdpr == 'yes'){
					$_SESSION['gdprEnabled'] = 'Y';
					
				}
		   }
		   
		   // set fb alias email
		    if(isset($_POST['dap_fblogin_email']) && ($_POST['dap_fblogin_email'] != '')){
				$dap_fblogin_email = $_POST['dap_fblogin_email'];
				$userObj = Dap_User::loadBasicUserInfo($email);
				if(isset($userObj)){
					$emailaliasObj = new Dap_EmailAlias();
					logToFile("autenticateUser: user= " .$userObj->getId());
					try{
						$emailaliasObj->setUser_id($userObj->getId());
						$emailaliasObj->setEmail($dap_fblogin_email);
						$emailaliasObj->setSource('FACEBOOK'); 
						$emailaliasObj->create();
					} catch (PDOException $e) {
						logToFile($e->getMessage(),LOG_FATAL_DAP);
					}
				}	
		   }

		   
		   
		}else{
			$output['error'] = dapMemberGetMessageByKeyAndAction('login','email_password_wrong');
			
		}
		 		
	}else{
		$output['error'] = dapMemberGetMessageByKeyAndAction('login','email_password_wrong');
		
	}
	
	echo json_encode($output);die;
}



function dapMemberGetPostLoginURl($action_id = 0){
	
	    $mpv_obj = DAP_MemberPagesValues::loadByActionId($action_id);
		$post_login_url = '';
		if($mpv_obj){
			$post_login_obj = DAP_MemberPagesValues::loadByActionIdAndName($action_id,'post_login_url');
			if($post_login_obj){
					$post_login_url = $post_login_obj->getValue();
			}
		}	
		if($post_login_url == ''){
			return $post_login_url;	
		}
		$postloginurlpos = strpos($post_login_url, "http");
		if( ($postloginurlpos === false)){
			//$site_url_dap = Dap_Config::get("SITE_URL_DAP");		
			//$post_login_url = $site_url_dap.$post_login_url;
			$post_login_url = site_url($post_login_url);		
		} 
		return $post_login_url;			
	
}


function dapMemberLoginValidateCaptcha($recaptcha = ''){
	
		
		$secret_key=Dap_Config::get("GOOGLE_SECRET_KEY");
		 
		$url = 'https://www.google.com/recaptcha/api/siteverify';
		$data = array(
			'secret' => $secret_key,
			'response' => $recaptcha
		);
		$options = array(
			'http' => array (
				'method' => 'POST',
				'content' => http_build_query($data)
			)
		);
		$context  = stream_context_create($options);
		$verify = file_get_contents($url, false, $context);
		$captcha_success=json_decode($verify);
		
		if(!isset($captcha_success) && $captcha_success == ""){
				$data = array(
				'secret' => $secret_key,
				'response' => $recaptcha
			);

			$verify = curl_init();
			curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
			curl_setopt($verify, CURLOPT_POST, true);
			curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
			curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
			$response = curl_exec($verify);
			$captcha_success = json_decode($response);
		}
		
		if ($captcha_success->success) {	
			return true;
		}	
		return true;
}

 
function dapMemberLoginCheckedCaptchaEnable($action_id = 0){
	$mp_obj = DAP_MemberPages::loadById($action_id);
	if($mp_obj){
		$styling_options = $mp_obj->getStylingOptions();
		$styling_options = explode("|||",$styling_options);
		if(isset($styling_options[0])){
			$dm_login_temp = explode("||",$styling_options[0]);
			$dm_login_temp_captcha =  $dm_login_temp[8];
				if($dm_login_temp_captcha == 'yes'){			
				return true;
			}
		}
	}
	return false;
}


add_action( 'wp_ajax_dap_lesson_status', 'dap_lesson_status' );
add_action( 'wp_ajax_nopriv_dap_lesson_status','dap_lesson_status');
//function called when Mark As Complete Button is clicked
function dap_lesson_status(){
	logToFile("DAP-WP-Livelinks.php: dap_lesson_status() enter ", LOG_DEBUG_DAP);	
	$course_id = $_POST['course_id']; 
	$module_id = $_POST['module_id']; 
	$lesson_id = $_POST['lesson_id']; 
	$module_name = $_POST['mod_name']; 
	$lesson_name = $_POST['lesson_name']; 
	$product_structure = $_POST['product_structure']; 
	$userId = $_POST['user_id']; 	 
	$seconds = $_POST['seconds']; 	 
	$next_btn = $_POST['next_btn']; 
	$start_date = $_POST['start_date']; 
	$course_name = $_POST['course_name']; 
	$current_url = $_POST['current_url'];
	$sendcourseemail = $_POST['sendcourseemail']; 	 
	$sendmoduleemail = $_POST['sendmoduleemail']; 	 
	$sendlessonemail = $_POST['sendlessonemail']; 	 	
	$sendcourseemail = trim(preg_replace('/\s+/', ' ', $sendcourseemail));
	$sendmoduleemail = trim(preg_replace('/\s+/', ' ', $sendmoduleemail));
	$sendlessonemail = trim(preg_replace('/\s+/', ' ', $sendlessonemail));
	$give_lesson_points =  false;
	//if click on the next button, then insert the time in user progress table
	if($next_btn =="yes"){
		if($module_id == ""){
		    $module_id =0;
		}
		$id =insertInitalAndTotalTime($course_id, $module_id, $lesson_id,$userId,$seconds ,$next_btn, $start_date);
		echo $id; die;
	}
	
	//  get Products Details By ResourceId
	$getproducts = Dap_Product::getProductsDetailsByResourceId($lesson_id);
    foreach($getproducts as $pdata){
		$user_obj = new Dap_User();		
		//$course_id = $pdata['id']; 
		$module_id = $pdata['module_id']; 		
		if($module_id == ""){
		    $module_id =0;
		}		
		$user_obj->setId($userId);
		//check if user has access to the product   
		$hasAccess = $user_obj->hasAccessTo($course_id);
		if(!$hasAccess){
			continue;
		}
 
		//insert the data in dap_user_course_progress
		$data = new DAP_UserCourseProgress(); 		
		$alreadyExists = DAP_UserCourseProgress::loadByCourseIdModuleIdlessonIduserId($course_id,$module_id,$lesson_id,$userId);
		
		if(isset($alreadyExists)){
			//if click on the next button, then insert the time in user progress table
			 insertInitalAndTotalTime($course_id, $module_id, $lesson_id,$userId, $seconds,"n",$start_date);
		}else{
			//if click on the "Mark As Complete" button, then insert the time in user progress table
			$id = insertInitalAndTotalTime($course_id, $module_id, $lesson_id,$userId, $seconds,"n",$start_date);
			
			//get the module data  
			$getmoduleid  =  Dap_Product::displayFileResourcesWithCourseIdLessonId($course_id, $lesson_id);	
			if(isset($getmoduleid)){					
				$module_id = $getmoduleid['module_id'];
				$lesson_name = $getmoduleid['name'];
				
				if($lesson_name == ""){
					$lesson_name = $getmoduleid['url'];
				} 
				if($product_structure != "lesson"){
					if(isset($module_id)){
						$moduledata = DAP_CourseModule::loadById($module_id) ;
						if(isset($moduledata)){				 
							 $module_name = $moduledata->getModuleName();
						} 
					}
				}
			}
	
			$course_complete = "no" ;	
			//send email when lesson is completed
			if($sendlessonemail =="Y"){
				logToFile("DAP-WP-Livelinks.php:send mail course_id ".$course_id.", module_id".$module_id. " lesson_name ".$lesson_name." ,userId:".$userId, LOG_DEBUG_DAP);
				//send module completed	 email to user	
				sendEmailNotificationCourseCompleted("lesson", $userId, $course_id, $lesson_name, $module_name ); 						
			}else{ //donot send email			 
			}	
				
			//assign tag to lesson
			try {  
				assignLessonCompletedTag($course_id, $lesson_id, $userId );				
			} catch (PDOException $e) {
				logToFile("DAP-WP-Livelinks.php: lessoncount1 ".$e->getMessage(), LOG_DEBUG_DAP);
			} catch (Exception $e) { 
				logToFile("DAP-WP-Livelinks.php: lessoncount1 ".$e->getMessage(), LOG_DEBUG_DAP);
			}
			
			//give points to lesson 
			$type = "dap_lesson_completed";
			$title = $lesson_name."||".$module_name."||".$course_name;
			$allids= $lesson_id."||".$module_id. "||" .$course_id ; 			 		
			$give_lesson_points = givePointsToLesson($type ,$title, $course_id , $userId, $allids, $current_url,$start_date, $module_id, $lesson_id );	
			
			//send email when module is completed
			if($product_structure != "lesson"){	
				if($sendmoduleemail =="Y"){
					$lessoncount =0;
					$lessonurlcount =0;
								
					if(isset($module_id)){
						$lessonurls  =  Dap_Product::displayFileResourcesWithModuleIdCourseId($course_id, $module_id);	
						$lessonurlcount = count($lessonurls);			
						$lessoncount = DAP_UserCourseProgress::lessonCountByCourseIdModuleIduserId($course_id , $module_id , $userId );			
						if($lessoncount >= $lessonurlcount)	{	
							//send module completed	 email to user						
							sendEmailNotificationCourseCompleted("module", $userId, $course_id, "", $module_name );		
						}		
					}		
				}		
			}
	 
			//send email when course is completed
			if($sendcourseemail == "Y" ){ // send course email
				
				$lessonurlcount1 =0;
				$lessoncount=0;			 			 				
				$unit_url_list = array();		
				// module loop	
				
				if($product_structure == "lesson"){						
						$lessonurls  =  Dap_Product::displayFileResourcesWithCourseId($course_id);
						$lessoncount = DAP_UserCourseProgress::lessonCountByCourseIduserId($course_id , $userId );	 
				}else{
					
					$moduledata = DAP_CourseModule::loadByCourseId($course_id) ;	
					if(isset($moduledata)) {							 
						$lessonurls = array();
						
						// module loop					
						foreach($moduledata as $mod){													
							 $lessonurls[]  =  Dap_Product::displayFileResourcesWithModuleIdCourseId($course_id, $mod->getId());
							 $lessoncount += DAP_UserCourseProgress::lessonCountByCourseIdModuleIduserId($course_id , $mod->getId(), $userId );				 							
						}							
						
						if(count($lessonurls)){
							$lessonurls_new = array();
							foreach($lessonurls as $lessonurl){
								foreach($lessonurl as $lessonurl_single){
									$lessonurls_new[] = $lessonurl_single;										 
								}
							}								
							$lessonurls = $lessonurls_new;								
						}				 
					}
				}				
			
				if(isset($lessonurls)) {							 
					 foreach($lessonurls as $lessonurl){
						$unit_url_list[]  = $lessonurl['url'];							 					 
					 }						  
				 }	
				 
				 $lessonurlcount1 = count($unit_url_list);		 		
				 if($lessoncount == $lessonurlcount1){	
					//send course completed	 email to user  			 
					sendEmailNotificationCourseCompleted("course", $userId, $course_id, "","" );			 
					$course_complete = "yes" ;
				 }					 
						
			}else{ // donot send course email				
				
				$lessonurlcount1 =0;
				$lessoncount=0;			 			 				
				$unit_url_list = array();		
				// module loop	
				
				if($product_structure == "lesson"){						
						$lessonurls  =  Dap_Product::displayFileResourcesWithCourseId($course_id);
						$lessoncount = DAP_UserCourseProgress::lessonCountByCourseIduserId($course_id , $userId );	 
				}else{
					
					$moduledata = DAP_CourseModule::loadByCourseId($course_id) ;	
					if(isset($moduledata)) {							 
						$lessonurls = array();
						
						// module loop					
						foreach($moduledata as $mod){													
							 $lessonurls[]  =  Dap_Product::displayFileResourcesWithModuleIdCourseId($course_id, $mod->getId());
							 $lessoncount += DAP_UserCourseProgress::lessonCountByCourseIdModuleIduserId($course_id , $mod->getId(), $userId );				 							
						}							
						
						if(count($lessonurls)){
							$lessonurls_new = array();
							foreach($lessonurls as $lessonurl){
								foreach($lessonurl as $lessonurl_single){
									$lessonurls_new[] = $lessonurl_single;										 
								}
							}								
							$lessonurls = $lessonurls_new;								
						}				 
					}
				}				
				
				if(isset($lessonurls)) {							 
					 foreach($lessonurls as $lessonurl){
						$unit_url_list[]  = $lessonurl['url'];							 					 
					 }						  
				}	
			 
				$lessonurlcount1 = count($unit_url_list);			
				if($lessoncount == $lessonurlcount1){						 
					$course_complete = "yes" ;
				}
			} 
		}	
	}
	$course_id = $_POST['course_id'];
	//get the data from  user progress table and File Resources
	$lessonurlsNew  =  Dap_Product::displayFileResourcesWithCourseId($course_id);
	$lessoncount1 = DAP_UserCourseProgress::lessonCountByCourseIduserId($course_id , $userId );	
	if(isset($lessonurlsNew)) {	
		$unit_url_listNew = array();
		// lesson loop		 
		foreach($lessonurlsNew  as $lessonurl1){				 
		  $unit_url_listNew[]= $lessonurl1['url'];
		}						   
	}
	
	logToFile("DAP-WP-Livelinks.php:send type ".$type.", course_id".$course_id. " lesson_id ".$lesson_id." ,userId:".$userId, LOG_DEBUG_DAP);
	
	if($lessoncount1 == count($unit_url_listNew)){
		//check if course is completed  		
		try {  
			//assign tag to course
			assignCourseCompletedTag($course_id, $userId );	
			
			//give points to course
			$type ="dap_course_completed";	
			$title = $course_name;	
			//check if course is eligible for points , then give points		
			$givePoint = checkIfEligibleForCredits($type, $course_id, $userId);		 
			if($givePoint >= 0){
				addUserCredits($type, $course_id , $userId, $course_id, $current_url,$title );			 
			}			
		} catch (PDOException $e) {
			logToFile("DAP-WP-Livelinks.php:  ".$e->getMessage(), LOG_DEBUG_DAP);
		} catch (Exception $e) { 
			logToFile("DAP-WP-Livelinks.php:  ".$e->getMessage(), LOG_DEBUG_DAP);
		}						
	}
	
	//if points awared it true then show animation and message
	if($give_lesson_points == true){
		$give_lesson_points = "yes";
		$animation = "N";
		$animationval = "";
		$message = "";
		$animationmessage = showMessageAndAnimation("dap_lesson_completed",$course_id,$module_id,$lesson_id);
		if($animationmessage !=""){
			$animationmessage = explode("||",$animationmessage);			 
			$animation = $animationmessage[0];
			$animationval = $animationmessage[1];
			$message = $animationmessage[2];
			if($message != ""){
				$message ='<div class="ponits_msg_container" ><div>'.$message.'</div></div>';
			}
			if($animation == "Y"){
				$animationval ='<div class="animation_container" ><img src="'.$animationval.'" /></div>';
			}
		}
	}	
	echo json_encode(array(
		'course_complete' => $course_complete ,
		'give_lesson_points'=> $give_lesson_points,
		'animation'=> $animation,
		'animationval'=> $animationval,
		'message'=> $message	
	));
	die;		 	
	 
}


add_action( 'wp_ajax_dap_setcoursesession', 'dap_setcoursesession' );
add_action( 'wp_ajax_nopriv_dap_setcoursesession','dap_setcoursesession');
// done this for the course shortcode (course outline)
function dap_setcoursesession(){
	unset($_SESSION["DAPCOURSEID"]);
	$course_id = $_POST['course_id']; 
	$_SESSION["DAPCOURSEID"] = $course_id;
	logToFile("DAP-WP-Livelinks.php: dap_setcoursesession() enter ".$_SESSION["DAPCOURSEID"], LOG_DEBUG_DAP);	
	echo "true"; die;
}
	

//added to change the default wp_login_cookie
function dapwp_change_expire_time( $expire, $user_id, $remember){
    //The $remember variable indicates whether the user has elected to be 'remembered'.
    //By default, if true, WP sets expire to 14 days if false, 2 days, but now we are passing the custom days
    //$expire is time in seconds 

	$days =1;
	$always_use_cookie = Dap_Config::get("ALWAYS_USE_COOKIE");
	if( $always_use_cookie == "Y"){
		$days = Dap_Config::get("USER_LOGGED_IN_DAYS");
		if($days !="" || $days >0){
			logToFile("DAP-WP-Livelinks.php: dapwp_change_expire_time() days ".$days, LOG_DEBUG_DAP);	 
			return $days*24*60*60;
		}else{
			return $days*24*60*60;
		}
	}	
}


add_action ( 'wp_ajax_dap_create_bulk_user', 'dap_create_bulk_user' );
add_action ( 'wp_ajax_nopriv_dap_create_bulk_user', 'dap_create_bulk_user' );


function dap_create_bulk_user(){
	$pId = $_REQUEST['pId'];
	$productId = $_REQUEST['productId'];
	$userId = $_REQUEST['userId'];	
	$b_f1 = $_REQUEST['b_f1'];	
	$b_f2 = $_REQUEST['b_f2'];	
	$b_f3 = $_REQUEST['b_f3'];	

	$b_data = explode(PHP_EOL, $_POST['b_data']);


	$dontIncrease = 'N';	
	$seatsAvailable = 'yes';
	
	
	$seatsDetails = DAP_UserGroupAccount::loadByUserAndProductID($userId, $pId);
	if(isset($seatsDetails)){
		$seats = $seatsDetails[0]['seats'];
		$created = $seatsDetails[0]['total_created'];	
		if($seats <= $created){
			$seatsAvailable = 'no';	
			echo json_encode(array('msg' => 'limit_reached'));die;
		}
	}
	$i = 0;
	foreach($b_data as  $data){
		$seatsDetails = DAP_UserGroupAccount::loadByUserAndProductID($userId, $pId);
		if(isset($seatsDetails)){
			$seats = $seatsDetails[0]['seats'];
			$created = $seatsDetails[0]['total_created'];	
			if($seats <= $created){
				$seatsAvailable = 'no';	
				echo json_encode(array('msg' => 'created_some' , 'num' => $i));die;
			}
		}
		$uid = Dap_UsersProducts::addExtNewUserToProduct($productId, 'Y', $b_f1.'|'.$b_f2.'|'.$b_f3 ,$data, 'YYYY-MM-DD', 'no', $pId);
		
		$user = Dap_User::loadUserById($uid);	

		if(isset($user)){
			Dap_User::updateParentId($userId, $user->getId(), 'C');
			$userGroupAccount = new DAP_UserGroupAccount();
			if(isset($seatsDetails) && $dontIncrease == 'N'){
				$id = $seatsDetails[0]['id'];
				$user_id = $seatsDetails[0]['userid'];
				$product_id = $seatsDetails[0]['productid'];
				$seats = $seatsDetails[0]['seats'];
				$created = $seatsDetails[0]['total_created'];
				
				$userGroupAccount->setId($id);
				$userGroupAccount->setUserId($user_id);
				$userGroupAccount->setProductId($pId);
				$userGroupAccount->setSeats($seats);
				$userGroupAccount->setTotalCreated($created+1);
							
				$userGroupAccount->update();
				
			}
		}
		$i++;
	}
	
}


add_action ( 'wp_ajax_dap_create_new_user', 'dap_create_new_user' );
add_action ( 'wp_ajax_nopriv_dap_create_new_user', 'dap_create_new_user' );

function dap_create_new_user(){
	$usersList = $_REQUEST['usersList'];
	
	$pId = $_REQUEST['pId'];
	$requestid = $_REQUEST['id'];
	$userId = $_REQUEST['userId'];
	$productId = $_REQUEST['productId'];
	$first_name = $_REQUEST['first_name'];
	$last_name = $_REQUEST['last_name'];
	$email = trim($_REQUEST['email']);
	$address1 = $_REQUEST['address1'];
	$address2 = $_REQUEST['address2'];
	$city = $_REQUEST['city'];
	$state = $_REQUEST['state'];
	$zip = $_REQUEST['zip'];
	$country = $_REQUEST['country'];
	$fieldValue = $_REQUEST['fieldValue'];
	$fieldName = $_REQUEST['fieldName'];
	$ispaid = 'Y';
	$dateformat = 'YYYY-MM-DD';
	
	$seatsAvailable = 'yes';
	
	$seatsDetails = DAP_UserGroupAccount::loadByUserAndProductID($userId, $pId);
	
	$dontIncrease = 'N';	 
	if(in_array($email, $usersList)){
		$dontIncrease = 'Y';	
	}
			
	
	if(isset($seatsDetails) && $requestid == '' && $dontIncrease == 'N'){
		$seats = $seatsDetails[0]['seats'];
		$created = $seatsDetails[0]['total_created'];	
		if($seats <= $created){
			$seatsAvailable = 'no';	
			echo 'limit_reached';die;
		}
	}
	if($requestid == ''){
		
		$fieldlist = 'email|first_name|last_name|address1|address2|city|state|zip|country|'.$fieldName;
		$data = $email.','.$first_name.','.$last_name.','.$address1.','.$address2.','.$city.','.$state.','.$zip.','.$country.','.$fieldValue;
		$addToUserAccount = 'no';
		Dap_UsersProducts::addExtNewUserToProduct($productId, $ispaid, $fieldlist, $data, $dateformat, $addToUserAccount, $pId);
		$user = Dap_User::loadUserByEmail($email);
		if(isset($user)){
			Dap_User::updateParentId($userId, $user->getId(), 'C');
			
			$userGroupAccount = new DAP_UserGroupAccount();
			if(isset($seatsDetails) && $dontIncrease == 'N'){
				$id = $seatsDetails[0]['id'];
				$user_id = $seatsDetails[0]['userid'];
				$product_id = $seatsDetails[0]['productid'];
				$seats = $seatsDetails[0]['seats'];
				$created = $seatsDetails[0]['total_created'];
				
				$userGroupAccount->setId($id);
				$userGroupAccount->setUserId($user_id);
				$userGroupAccount->setProductId($product_id);
				$userGroupAccount->setSeats($seats);
				$userGroupAccount->setTotalCreated($created+1);
							
				$userGroupAccount->update();
				
			}
		}
	}else{
		$user = Dap_User::loadUserById($requestid);	
		$userNew = new Dap_User();
		
		if(isset($user)){
			$userNew->setId($requestid);
			$userNew->setFirst_name($first_name);
			$userNew->setLast_name($last_name);
			$userNew->setEmail($email);
			
			if($address1 == ''){
				$address1 = $user->getAddress1();
			}
			if($address2 == ''){
				$address2 = $user->getAddress2();
			}
			if($city == ''){
				$city = $user->getCity();
			}
			if($state == ''){
				$state = $user->getState();
			}
			if($zip == ''){
				$zip = $user->getZip();
			}
			if($country == ''){
				$country = $user->getCountry();
			}
			
			$userNew->setAddress1($address1);
			$userNew->setAddress2($address2);
			$userNew->setCity($city);
			$userNew->setState($state);
			$userNew->setZip($zip);
			$userNew->setCountry($country);
			$userNew->setPhone($user->getPhone());
			$userNew->setFax($user->getFax());
			$userNew->setShipping_address($user->getShipping_address());
			$userNew->setShipping_country($user->getShipping_country());
			$userNew->setShipping_city($user->getShipping_city());
			$userNew->setShipping_state($user->getShipping_state());
			$userNew->setShipping_zip($user->getShipping_zip());
			$userNew->setCompany($user->getCompany());
			$userNew->setTitle($user->getTitle());	
			$userNew->setStatus($user->getStatus());	
			$userNew->setPaypal_email($user->getPaypal_email());	
			$userNew->setCredits_available($user->getCredits_available());	
			$userNew->setExclude_iplogging($user->getExclude_iplogging());	
			$userNew->setReset_password_key($user->getReset_password_key());	
			$userNew->setGDPRConsent($user->getGDPRConsent());	
			$userNew->setGDPRCompliance_date($user->getGDPRCompliance_date());	
			$userNew->setSubaccountType($user->getSubaccountType());
			$userNew->setParentId($user->getParentId());
						
			$userNew->update();
		}
	}
	
	echo 'success';die;
	
		
}

add_action ( 'wp_ajax_dap_delete_user', 'dap_delete_user' );
add_action ( 'wp_ajax_nopriv_dap_delete_user', 'dap_delete_user' );

function dap_delete_user(){
	$user_id = $_REQUEST['user_id'];
	$prod_id = $_REQUEST['prod_id'];
	$main_id = $_REQUEST['main_id'];
	
	$userObj = new Dap_User();
	
	$userObj->setId($user_id);
	$userObj->delete();
	
	$seatsDetails = DAP_UserGroupAccount::loadByUserAndProductID($main_id, $prod_id);
		
	$userGroupAccount = new DAP_UserGroupAccount();
	if(isset($seatsDetails)){
		$id = $seatsDetails[0]['id'];
		$user_id = $seatsDetails[0]['userid'];
		$product_id = $seatsDetails[0]['productid'];
		$seats = $seatsDetails[0]['seats'];
		$created = $seatsDetails[0]['total_created'];
		
		$userGroupAccount->setId($id);
		$userGroupAccount->setUserId($user_id);
		$userGroupAccount->setProductId($product_id);
		$userGroupAccount->setSeats($seats);
		$userGroupAccount->setTotalCreated($created-1);
		
		$userGroupAccount->update();
		
	}
}


add_action ( 'wp_ajax_dap_user_details', 'dap_user_details' );
add_action ( 'wp_ajax_nopriv_dap_user_details', 'dap_user_details' );

function dap_user_details(){
	$user_id = $_REQUEST['user_id'];

	$user = Dap_User::loadUserById($user_id);
	
	if(isset($user)){
		echo json_encode(array('user' => $user  ,'error'=> ''));
		die;
	}else{
		echo json_encode(array('user' => ''  ,'error'=> 'No user found'));
		die;	
	}
	
}
function get_all_page_ids_data() {	
	global $wpdb;	
	$page_ids = wp_cache_get( 'all_page_ids', 'posts' );	
	if ( ! is_array( $page_ids ) ) {	
		$page_ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_type = 'page'  order by ID desc" );	
		wp_cache_add( 'all_page_ids', $page_ids, 'posts' );	
	}	
	return $page_ids;	
}

/*	
* Added for pay-per-post	
*/
//add_filter( 'tve_landing_page_content', 'dap_custom_metabox' , 999);

//add_filter('the_content', 'dap_custom_metabox'); 	
	

if ( !is_admin() ){
	
	add_filter('the_posts', 'dap_custom_metabox', 99999); 
	add_filter('the_content_feed', 'dap_custom_metabox', 99999); 
	add_filter('mod_rewrite_rules', 'dap_mod_rewrite', 99999);	
}




function dap_custom_metabox($post) {	
	//global $showPPP;	
	$hasAccess = false;

	if($_SESSION['showPPP'] == 'yes'){
			
		//$content = $post->post_content;	
		if(isset($_REQUEST['tve']) && $_REQUEST['tve'] == true){return $post;}			
		
		//$content = $post[0]->post_content;	
		
		if(!is_admin() && $GLOBALS['pagenow'] !== 'post.php'){	
			
			$pageid = $post[0]->ID;
			
			if($pageid == ''){
				$pageid = $_SESSION['pppposts_id'];		
			}
			
			$payPerPostData = Dap_PayPerPost::loadPayPerPostByPostId($pageid);	
				
			if(isset($payPerPostData)){	
			
				$before_more_tag_text = '';	
					
				ob_start();	
				eval("?>" . file_get_contents(plugin_dir_path(__FILE__)."/includes/frontend/payPerPost.php"));		
				$output = ob_get_contents();	
				ob_end_clean();	
				
				if(!$hasAccess && $enable_pay_per_post == 'Y'){
					//print_r($post);die;
					
					
					if(defined('THRIVE_ENABLED')) {  
						global $wpdb;
						$results = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}postmeta WHERE `post_id` = $posts_id AND `meta_key` LIKE '%tve_globals%'" ); 	 
						
						if(isset($results) && count($results) > 0){ 	
							
						
							$title = $post[0]->post_title;
							$post = NULL;
							$post[0]['post_content'] = $output;
													
							$post[0] = createPost1($output, $title);
						}else{
							$post[0]->post_content = $output;	
						}
					}else{
						$post[0]->post_content = $output;	
					}
				}else if($enable_pay_per_post == 'Y' && $hasAccess && $_SESSION['pppposts_id'] != ''){
					$post = $_SESSION['post']; 
				
				}
				
				return $post;		
				
			}else{ // pay per post is not enabled, display the content	
				return $post;		
			}		
		}	
	}else{
		return $post;			
	}
}

function createPost1($output, $title){
	$post = new stdClass;
	$post->post_author = 1;
	$post->post_name = "error";
	$post->guid = get_bloginfo('wpurl');
	$post->post_title = $title;
	$post->post_content = $output;
	$post->ID = -1;
	//$post->post_status = 'static';
	$post->comment_status = 'closed';
	//$post->ping_status = $this->ping_status;
	$post->comment_count = 0;
	$post->post_date = current_time('mysql');
	$post->post_date_gmt = current_time('mysql', 1);
	return($post);		
}

function pppLoadHtmlToShow($postId, $payPerPostData){
	$button_layout = $payPerPostData->getButtonLayoutoption();
	$showAboveMsg = $payPerPostData->getShowMsgAboveBtn();
	$currencySymbol = $payPerPostData->getCurrencySymbol();
	$productId = $payPerPostData->getProductId();
	
	/**get cusstomize messages */
	$dapwp_freetrail    =  dapMemberGetMessageByKeyAndAction('ppp_membership','free_trial');
	if($dapwp_freetrail == ''){
		$dapwp_freetrail = 'Free trial';	
	}

	$dapwp_trail    =  dapMemberGetMessageByKeyAndAction('ppp_membership','trial');
	if($dapwp_trail == ''){
		$dapwp_trail = 'trial';	
	}

	$dapwp_month    =  dapMemberGetMessageByKeyAndAction('ppp_membership','month');
	if($dapwp_month == ''){
		$dapwp_month = 'month';	
	}
	$dapwp_year     =  dapMemberGetMessageByKeyAndAction('ppp_membership','year');
	if($dapwp_year == ''){
		$dapwp_year = 'year';	
	}
	$dapwp_daily    =  dapMemberGetMessageByKeyAndAction('ppp_membership','daily');
	if($dapwp_daily == ''){
		$dapwp_daily = 'daily';	
	}
	$dapwp_weekly   =  dapMemberGetMessageByKeyAndAction('ppp_membership','weekly');
	if($dapwp_weekly == ''){
		$dapwp_weekly = 'weekly';	
	}
	$dapwp_per_days =  dapMemberGetMessageByKeyAndAction('ppp_membership','per_days');
	if($dapwp_per_days == ''){
		$dapwp_per_days = 'days';	
	}
	
	/**get cusstomize messages end */

	
	$html = '';
	if($postId != ''){
		
		$postMetaData = Dap_PayPerPostMeta::loadPayPerPostMetaByPostId($postId);
		
		if(isset($postMetaData)){
			
			$button_html = '';
			$buttonsAlignment = 'left';	
			foreach($postMetaData as $data){
					
				$buttonType = $data->getButtonType();
				
				if($buttonType != 'membership'){
					$price = $data->getPrice();
				}else{
					
					if($productId != '' && $productId != 0){
						
						$productData = Dap_Product::loadProduct($productId);
						
						if(isset($productData)){
							
							$price = $productData->getPrice();
							$trial_price = $productData->getTrial_price();
							$is_recur = $productData->getIs_recurring();
							$offer_trial = $productData->getOfferTrial();
							$recurringCycle1 = $productData->getRecurring_cycle_1();
							$recurringCycle3 = $productData->getRecurring_cycle_3();

							if($is_recur == 'Y'){
								if($offertrial == 'Y'){
									if($freetrial == 'Y'){
										$price = $dapwp_freetrail;
									}else{
										$price = $trial_price . ' '.$dapwp_trail;
									}
								}else{
									if($recurringCycle1 > 99){
										$recurringCycle1 = $recurringCycle3;	
									}
									
									if($recurringCycle1 == 1){
										$recurringCycle1 = ' / '.$dapwp_daily;	
									}else if($recurringCycle1 == 7){
										$recurringCycle1 =  ' / '.$dapwp_weekly;	
									}else if($recurringCycle1 == 30){
										$recurringCycle1 = ' / '.$dapwp_month;	
									}else if($recurringCycle1 == 365){
										$recurringCycle1 = ' / '.$dapwp_year;	
									}else{
										$recurringCycle1 = ' / '.$recurringCycle1.' '.$dapwp_per_days;	
									}	
									
									$price = $price .$recurringCycle1;	
								}
							}else{
						
								if($recurringCycle1 == 1){
									$recurringCycle1 = ' / '.$dapwp_daily;	
								}else if($recurringCycle1 == 7){
									$recurringCycle1 =  ' / '.$dapwp_weekly;	
								}else if($recurringCycle1 == 30){
									$recurringCycle1 = ' / '.$dapwp_month;	
								}else if($recurringCycle1 == 365){
									$recurringCycle1 = ' / '.$dapwp_year;	
								}else{
									$recurringCycle1 = ' / '.$recurringCycle1.' '.$dapwp_per_days;	
								}	
								
								$price = $price .$recurringCycle1;	
							}
					
						}
					}	
				}
				
				//$price = number_format((float)$price, 2, '.', '');
				
				$buttonData = DAP_PayPerPostCustomizer::loadByType($buttonType);
				
				if($buttonData){
					
					$customizedData = $buttonData->getButtonCustomizer();
					
					if($customizedData != ''){
						$customizedData = explode('||' , $customizedData);	
						
						$buttonWidth = $customizedData[0].'px';
						$buttonHeight = $customizedData[1].'px';
						$backgroundColor = $customizedData[2];
						$borderStyle = $customizedData[3];
						$borderWidth = $customizedData[4].'px';
						$borderColor = $customizedData[5];
						$borderRadius = $customizedData[6].'px';
						$fontSize = $customizedData[7].'px';
						$fontWeight = $customizedData[8];
						$fontFamily = $customizedData[9];
						$buttonsBetweenSpacing = $customizedData[10];
						$buttonsAlignment = $customizedData[11];
						$color = '#fff';
						
						$buttonStyle = 'style=width:'.$buttonWidth.';padding:'.$buttonHeight.';background:'.$backgroundColor.';border-width:'.$borderWidth.';border-style:'.$borderStyle.';border-color:'.$borderColor.';border-radius:'.$borderRadius.';font-size:'.$fontSize.';font-weight:'.$fontWeight.';font-family:'.$fontFamily.';color:'.$color.'';						
					}
				
					if($button_layout == 'template1'){
						$button_html .= '<div class="temp1Outer" style="margin-right:'.$buttonsBetweenSpacing.'px;"><label class="amountOuter"><span class="frontendCurrecny">'.$currencySymbol.'</span>'.$price.'</label><a href="'.$data->getBuyLink().'"><div '.$buttonStyle.'>'.$data->getBtnText().'</div></a></div>';
					}else if($button_layout == 'template2'){
						
						$button_html .= '<div class="button-vertical--style" style="margin-bottom:'.$buttonsBetweenSpacing.'px;"><div class="button-vertical-label"><label class="amountOuter" style="width:'.$buttonWidth.'"><span class="frontendCurrecny">'.$currencySymbol.'</span>'.$price.'</label></div><a href="'.$data->getBuyLink().'"><div '.$buttonStyle.'>'.$data->getBtnText().'</div></a></div>';	
					}
					
				}else{
					continue;
				}
			}
			$html .= '<div class="pp-post-actions" style="text-align:'.$buttonsAlignment.';">';
			if($showAboveMsg == 'Y'){
				$html .= '<label>';
				$html .= $postMetaData[0]->getBtnAboveText();
				$html .= '</label>';
			}
			$html .= $button_html;
			$html .= '</div>';
			
				
		}else{
			return $html;
		}
		return $html;
	}else{
		return $html;
	}
		
}

function checkIfUserHasAccessViaPPP($postId , $userId){
	$hasAccess = DAP_UserPayPerPost::hasAccessTo($userId,$postId);	
	return $hasAccess;
}


/*get currency symbols*/
function pppGetCurrencySymbol(){
	if(isset($_REQUEST['curr'])){
		$curr = $_REQUEST['curr'];
	}
	$currency_symbols = array(
		'AED' => '&#1583;.&#1573;', // ?
		'AFN' => '&#65;&#102;',
		'ALL' => '&#76;&#101;&#107;',
		'AMD' => '',
		'ANG' => '&#402;',
		'AOA' => '&#75;&#122;', // ?
		'ARS' => '&#36;',
		'AUD' => '&#36;',
		'AWG' => '&#402;',
		'AZN' => '&#1084;&#1072;&#1085;',
		'BAM' => '&#75;&#77;',
		'BBD' => '&#36;',
		'BDT' => '&#2547;', // ?
		'BEF' => 'fr', // ?
		'BGN' => '&#1083;&#1074;',
		'BHD' => '.&#1583;.&#1576;', // ?
		'BIF' => '&#70;&#66;&#117;', // ?
		'BMD' => '&#36;',
		'BND' => '&#36;',
		'BOB' => '&#36;&#98;',
		'BRR' => '&#82;&#36;',
		'BSD' => '&#36;',
		'BTN' => '&#78;&#117;&#46;', // ?
		'BWP' => '&#80;',
		'BYR' => '&#112;&#46;',
		'BZD' => '&#66;&#90;&#36;',
		'CAD' => '&#36;',
		'CDF' => '&#70;&#67;',
		'CHF' => '&#67;&#72;&#70;',
		'CLF' => '', // ?
		'CLP' => '&#36;',
		'CNY' => '&#165;',
		'COP' => '&#36;',
		'CRC' => '&#8353;',
		'CUP' => '&#8396;',
		'CVE' => '&#36;', // ?
		'CZK' => '&#75;&#269;',
		'DJF' => '&#70;&#100;&#106;', // ?
		'DKK' => '&#107;&#114;',
		'DOP' => '&#82;&#68;&#36;',
		'DZD' => '&#1583;&#1580;', // ?
		'EGP' => '&#163;',
		'ETB' => '&#66;&#114;',
		'EUR' => '&#8364;',
		'FJD' => '&#36;',
		'FKP' => '&#163;',
		'GBP' => '&#163;',
		'GEL' => '&#4314;', // ?
		'GHS' => '&#162;',
		'GIP' => '&#163;',
		'GMD' => '&#68;', // ?
		'GNF' => '&#70;&#71;', // ?
		'GTQ' => '&#81;',
		'GYD' => '&#36;',
		'HKD' => '&#36;',
		'HNL' => '&#76;',
		'HRK' => '&#107;&#110;',
		'HTG' => '&#71;', // ?
		'HUF' => '&#70;&#116;',
		'IDR' => '&#82;&#112;',
		'ILS' => '&#8362;',
		'INR' => '&#8377;',
		'IQD' => '&#1593;.&#1583;', // ?
		'IRR' => '&#65020;',
		'ISK' => '&#107;&#114;',
		'JEP' => '&#163;',
		'JMD' => '&#74;&#36;',
		'JOD' => '&#74;&#68;', // ?
		'JPY' => '&#165;',
		'KES' => '&#75;&#83;&#104;', // ?
		'KGS' => '&#1083;&#1074;',
		'KHR' => '&#6107;',
		'KMF' => '&#67;&#70;', // ?
		'KPW' => '&#8361;',
		'KRW' => '&#8361;',
		'KWD' => '&#1583;.&#1603;', // ?
		'KYD' => '&#36;',
		'KZT' => '&#1083;&#1074;',
		'LAK' => '&#8365;',
		'LBP' => '&#163;',
		'LKR' => '&#8360;',
		'LRD' => '&#36;',
		'LSL' => '&#76;', // ?
		'LTL' => '&#76;&#116;',
		'LVL' => '&#76;&#115;',
		'LYD' => '&#1604;.&#1583;', // ?
		'MAD' => '&#1583;.&#1605;.', //?
		'MDL' => '&#76;',
		'MGA' => '&#65;&#114;', // ?
		'MKD' => '&#1076;&#1077;&#1085;',
		'MMK' => '&#75;',
		'MNT' => '&#8366;',
		'MOP' => '&#77;&#79;&#80;&#36;', // ?
		'MRO' => '&#85;&#77;', // ?
		'MUR' => '&#8360;', // ?
		'MVR' => '.&#1923;', // ?
		'MWK' => '&#77;&#75;',
		'MXN' => '&#36;',
		'MYR' => '&#82;&#77;',
		'MZN' => '&#77;&#84;',
		'NAD' => '&#36;',
		'NGN' => '&#8358;',
		'NIO' => '&#67;&#36;',
		'NOK' => '&#107;&#114;',
		'NPR' => '&#8360;',
		'NZD' => '&#36;',
		'OMR' => '&#65020;',
		'PAB' => '&#66;&#47;&#46;',
		'PEN' => '&#83;&#47;&#46;',
		'PGK' => '&#75;', // ?
		'PHP' => '&#8369;',
		'PKR' => '&#8360;',
		'PLN' => '&#122;&#322;',
		'PYG' => '&#71;&#115;',
		'QAR' => '&#65020;',
		'RON' => '&#108;&#101;&#105;',
		'RSD' => '&#1044;&#1080;&#1085;&#46;',
		'RUB' => '&#1088;&#1091;&#1073;',
		'RWF' => '&#1585;.&#1587;',
		'SAR' => '&#65020;',
		'SBD' => '&#36;',
		'SCR' => '&#8360;',
		'SDG' => '&#163;', // ?
		'SEK' => '&#107;&#114;',
		'SGD' => '&#36;',
		'SHP' => '&#163;',
		'SLL' => '&#76;&#101;', // ?
		'SOS' => '&#83;',
		'SRD' => '&#36;',
		'STD' => '&#68;&#98;', // ?
		'SVC' => '&#36;',
		'SYP' => '&#163;',
		'SZL' => '&#76;', // ?
		'THB' => '&#3647;',
		'TJS' => '&#84;&#74;&#83;', // ? TJS (guess)
		'TMT' => '&#109;',
		'TND' => '&#1583;.&#1578;',
		'TOP' => '&#84;&#36;',
		'TRY' => '&#8356;', // New Turkey Lira (old symbol used)
		'TTD' => '&#36;',
		'TWD' => '&#78;&#84;&#36;',
		'TZS' => '',
		'UAH' => '&#8372;',
		'UGX' => '&#85;&#83;&#104;',
		'USD' => '&#36;',
		'UYU' => '&#36;&#85;',
		'UZS' => '&#1083;&#1074;',
		'VEF' => '&#66;&#115;',
		'VND' => '&#8363;',
		'VUV' => '&#86;&#84;',
		'WST' => '&#87;&#83;&#36;',
		'XAF' => '&#70;&#67;&#70;&#65;',
		'XCD' => '&#36;',
		'XDR' => '',
		'XOF' => '',
		'XPF' => '&#70;',
		'YER' => '&#65020;',
		'ZAR' => '&#82;',
		'ZMK' => '&#90;&#75;', // ?
		'ZWL' => '&#90;&#36;',
	);
	
	if(isset($curr) && $curr != ''){
		echo html_entity_decode($currency_symbols[$curr]);
		die;
	}else{
		return $currency_symbols;
	}

}

add_action( 'wp_ajax_pppGetFullPageContent', 'pppGetFullPageContent' );

function pppGetFullPageContent(){
	
	$postId = $_REQUEST['dapwp_post_id'];
	ob_start();
	
	eval("?>" . file_get_contents(plugin_dir_path(__FILE__)."/includes/admin/dap_ppp_postdata.php"));		
	$output = ob_get_contents();
	ob_end_clean();
	echo json_encode($output);  	die;	
}


/******currency codes********/

/*get currency symbols*/
function LiveLinksGetCurrencySymbol(){
	
	$currency_symbols = array(
		'AED' => '&#1583;.&#1573;', // ?
		'AFN' => '&#65;&#102;',
		'ALL' => '&#76;&#101;&#107;',
		'AMD' => '',
		'ANG' => '&#402;',
		'AOA' => '&#75;&#122;', // ?
		'ARS' => '&#36;',
		'AUD' => '&#36;',
		'AWG' => '&#402;',
		'AZN' => '&#1084;&#1072;&#1085;',
		'BAM' => '&#75;&#77;',
		'BBD' => '&#36;',
		'BDT' => '&#2547;', // ?
		'BEF' => 'fr', // ?
		'BGN' => '&#1083;&#1074;',
		'BHD' => '.&#1583;.&#1576;', // ?
		'BIF' => '&#70;&#66;&#117;', // ?
		'BMD' => '&#36;',
		'BND' => '&#36;',
		'BOB' => '&#36;&#98;',
		'BRR' => '&#82;&#36;',
		'BSD' => '&#36;',
		'BTN' => '&#78;&#117;&#46;', // ?
		'BWP' => '&#80;',
		'BYR' => '&#112;&#46;',
		'BZD' => '&#66;&#90;&#36;',
		'CAD' => '&#36;',
		'CDF' => '&#70;&#67;',
		'CHF' => '&#67;&#72;&#70;',
		'CLF' => '', // ?
		'CLP' => '&#36;',
		'CNY' => '&#165;',
		'COP' => '&#36;',
		'CRC' => '&#8353;',
		'CUP' => '&#8396;',
		'CVE' => '&#36;', // ?
		'CZK' => '&#75;&#269;',
		'DJF' => '&#70;&#100;&#106;', // ?
		'DKK' => '&#107;&#114;',
		'DOP' => '&#82;&#68;&#36;',
		'DZD' => '&#1583;&#1580;', // ?
		'EGP' => '&#163;',
		'ETB' => '&#66;&#114;',
		'EUR' => '&#8364;',
		'FJD' => '&#36;',
		'FKP' => '&#163;',
		'GBP' => '&#163;',
		'GEL' => '&#4314;', // ?
		'GHS' => '&#162;',
		'GIP' => '&#163;',
		'GMD' => '&#68;', // ?
		'GNF' => '&#70;&#71;', // ?
		'GTQ' => '&#81;',
		'GYD' => '&#36;',
		'HKD' => '&#36;',
		'HNL' => '&#76;',
		'HRK' => '&#107;&#110;',
		'HTG' => '&#71;', // ?
		'HUF' => '&#70;&#116;',
		'IDR' => '&#82;&#112;',
		'ILS' => '&#8362;',
		'INR' => '&#8377;',
		'IQD' => '&#1593;.&#1583;', // ?
		'IRR' => '&#65020;',
		'ISK' => '&#107;&#114;',
		'JEP' => '&#163;',
		'JMD' => '&#74;&#36;',
		'JOD' => '&#74;&#68;', // ?
		'JPY' => '&#165;',
		'KES' => '&#75;&#83;&#104;', // ?
		'KGS' => '&#1083;&#1074;',
		'KHR' => '&#6107;',
		'KMF' => '&#67;&#70;', // ?
		'KPW' => '&#8361;',
		'KRW' => '&#8361;',
		'KWD' => '&#1583;.&#1603;', // ?
		'KYD' => '&#36;',
		'KZT' => '&#1083;&#1074;',
		'LAK' => '&#8365;',
		'LBP' => '&#163;',
		'LKR' => '&#8360;',
		'LRD' => '&#36;',
		'LSL' => '&#76;', // ?
		'LTL' => '&#76;&#116;',
		'LVL' => '&#76;&#115;',
		'LYD' => '&#1604;.&#1583;', // ?
		'MAD' => '&#1583;.&#1605;.', //?
		'MDL' => '&#76;',
		'MGA' => '&#65;&#114;', // ?
		'MKD' => '&#1076;&#1077;&#1085;',
		'MMK' => '&#75;',
		'MNT' => '&#8366;',
		'MOP' => '&#77;&#79;&#80;&#36;', // ?
		'MRO' => '&#85;&#77;', // ?
		'MUR' => '&#8360;', // ?
		'MVR' => '.&#1923;', // ?
		'MWK' => '&#77;&#75;',
		'MXN' => '&#36;',
		'MYR' => '&#82;&#77;',
		'MZN' => '&#77;&#84;',
		'NAD' => '&#36;',
		'NGN' => '&#8358;',
		'NIO' => '&#67;&#36;',
		'NOK' => '&#107;&#114;',
		'NPR' => '&#8360;',
		'NZD' => '&#36;',
		'OMR' => '&#65020;',
		'PAB' => '&#66;&#47;&#46;',
		'PEN' => '&#83;&#47;&#46;',
		'PGK' => '&#75;', // ?
		'PHP' => '&#8369;',
		'PKR' => '&#8360;',
		'PLN' => '&#122;&#322;',
		'PYG' => '&#71;&#115;',
		'QAR' => '&#65020;',
		'RON' => '&#108;&#101;&#105;',
		'RSD' => '&#1044;&#1080;&#1085;&#46;',
		'RUB' => '&#1088;&#1091;&#1073;',
		'RWF' => '&#1585;.&#1587;',
		'SAR' => '&#65020;',
		'SBD' => '&#36;',
		'SCR' => '&#8360;',
		'SDG' => '&#163;', // ?
		'SEK' => '&#107;&#114;',
		'SGD' => '&#36;',
		'SHP' => '&#163;',
		'SLL' => '&#76;&#101;', // ?
		'SOS' => '&#83;',
		'SRD' => '&#36;',
		'STD' => '&#68;&#98;', // ?
		'SVC' => '&#36;',
		'SYP' => '&#163;',
		'SZL' => '&#76;', // ?
		'THB' => '&#3647;',
		'TJS' => '&#84;&#74;&#83;', // ? TJS (guess)
		'TMT' => '&#109;',
		'TND' => '&#1583;.&#1578;',
		'TOP' => '&#84;&#36;',
		'TRY' => '&#8356;', // New Turkey Lira (old symbol used)
		'TTD' => '&#36;',
		'TWD' => '&#78;&#84;&#36;',
		'TZS' => '',
		'UAH' => '&#8372;',
		'UGX' => '&#85;&#83;&#104;',
		'USD' => '&#36;',
		'UYU' => '&#36;&#85;',
		'UZS' => '&#1083;&#1074;',
		'VEF' => '&#66;&#115;',
		'VND' => '&#8363;',
		'VUV' => '&#86;&#84;',
		'WST' => '&#87;&#83;&#36;',
		'XAF' => '&#70;&#67;&#70;&#65;',
		'XCD' => '&#36;',
		'XDR' => '',
		'XOF' => '',
		'XPF' => '&#70;',
		'YER' => '&#65020;',
		'ZAR' => '&#82;',
		'ZMK' => '&#90;&#75;', // ?
		'ZWL' => '&#90;&#36;',
	);
	
	return $currency_symbols;
	

}

/******currency codes********/


function dap_url_to_postid($page_url) {
	 if (file_exists(dirname(__FILE__) . "/../../../wp-load.php"))
        require_once( dirname(__FILE__) . "/../../../wp-load.php" );
        
    global $wpdb;
    $where = $wpdb->prepare("post_name LIKE %s", $wpdb->esc_like(basename(untrailingslashit($page_url))) . '%');
    $postid = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE $where AND post_status = 'publish'");
    return $postid;
}

function downloadCertificateButton($prodId,$certificate_id,$btnStyle= '',$btnText = 'Download Certificate'){
		 
	//pdf script
	$script_certificate =' <script>						 
		function dapCertificatePdf( formname, prodId, certificate_id,  blogpath) {
			var user_id ="";
			var submiturl="'.get_option("siteurl").'/wp-content/plugins/DAP-WP-LiveLinks/includes/tcpdf/data/certificate.php";
			var url = "'.get_option("siteurl").'/wp-content/plugins/DAP-WP-LiveLinks/includes/tcpdf/data/certificate.php?productId="+prodId+"&certificate_id="+certificate_id;
		   
			jQuery("body").append("<form action='.''.get_option("siteurl").'/wp-content/plugins/DAP-WP-LiveLinks/includes/tcpdf/data/certificate.php'.' method='.'post'.' name='.'certficateform'.' target='.'_blank'.'>");					  
			jQuery("form[name='.'certficateform'.']").append("<input type='.'hidden'.' name='.'productId'.' value='.'"+prodId+"'.'>");
			jQuery("form[name='.'certficateform'.']").append("<input type='.'hidden'.' name='.'certificate_id'.' value='.'"+certificate_id+"'.'>");
			jQuery("form[name='.'certficateform'.']").append("<input type='.'hidden'.' name='.'user_id'.' value='.'"+user_id+"'.'>");						 
			jQuery("form[name='.'certficateform'.']").submit();							
			jQuery("form[name='.'certficateform'.']").remove();
			return false;							 
			window.open(url);		 
			return;
		  }
	  </script>';	
					  
	//pdf gen
	$btnText =  str_replace('contenteditable="true"', "", $btnText); 	
	$pdf .='<a class="certDownloadBtn" style="'.$btnStyle.'" href="" onclick="';	
	$pdf .="return dapCertificatePdf('certficateform','$prodId', '$certificate_id', '" . ABSPATH . "');";
	$pdf .='">'.$btnText.'</a>';
	return  $script_certificate."<div class='certificate_container' style='display:none;  '>".$pdf."</div>"; 
}



// certificate shortcode button page functionality
function dapCertificateShortcode($atts, $content=null){
	
	/***Added this line to fix the elementor ,  for non-admin users content was not showing*****/
	if(isset($_REQUEST['tve']) && $_REQUEST['tve'] == true){return $posts;}
	if(isset($_REQUEST['action']) && ($_REQUEST['action']  == "elementor" || isset($_REQUEST['elementor-preview']))){
		return $posts;
	}

	global $wpdb,$posts;
	extract(shortcode_atts(array(
	   'id' => '',
	), $atts));
	   
	if( !Dap_Session::isLoggedIn() ) {
		return;
	}
	  
	//get userid
	$session = Dap_Session::getSession();
	$user = $session->getUser();
	if (isset($user)) {
		
		$userId = $user->getId();
		$courseCertificate = Dap_CourseCertificate::loadByCourseId($id);
		
		if($courseCertificate !== false){
			
			$courseId = $courseCertificate->getCourseId();
			$certificateId = $courseCertificate->getCertificateId();
			$certificateType = $courseCertificate->getCertificateGenerationCriteria();
			$btnText = $courseCertificate->getDownloadBtnHtml();
			$userCertificateData = Dap_UserCertificate::loadByCourseIdAndUserId($courseId,$userId);
			
			
			if($userCertificateData != false){
				//display download button
				$btnData = downloadCertificateButton($courseId,$certificateId,'', $btnText);
				$btnData .= "<script type=''>
	jQuery('.dap_cerficate_tiny_mce_editor').each(function(){
		jQuery(this).attr('contenteditable',false);
	})
</script>";
				$btnData_style = '<style>.certificate_container{display:block !important}</style>';
				$output = $btnData.$btnData_style;
			}else{		
					
				$productobj = Dap_Product::loadProduct($courseId) ;
				$course_id = $courseId;
				if(isset($productobj)){
					 $product_structure = $productobj->getProductStructure();
				}
														
				if($product_structure == "lesson"){						
					$lessonurls  =  Dap_Product::displayFileResourcesWithCourseId($course_id);
					$lessoncount = DAP_UserCourseProgress::lessonCountByCourseIduserId($course_id , $userId );	 
				}else{
						
					$moduledata = DAP_CourseModule::loadByCourseId($course_id) ;	
					if(isset($moduledata)) {	
						$lessonurls = array();

						// module loop					
						foreach($moduledata as $mod){	
							$lessonurls[]  =  Dap_Product::displayFileResourcesWithModuleIdCourseId($course_id, $mod->getId());
							$lessoncount += DAP_UserCourseProgress::lessonCountByCourseIdModuleIduserId($course_id , $mod->getId(), $userId );				 							
						}							
						
						if(count($lessonurls)){
							$lessonurls_new = array();
							foreach($lessonurls as $lessonurl){
								foreach($lessonurl as $lessonurl_single){
									$lessonurls_new[] = $lessonurl_single;										 
								}
							}								
							$lessonurls = $lessonurls_new;								
						}				 
					}
				}	
				
				//currentpage url
				$current_url = home_url(add_query_arg(array()));
				$pageid = url_to_postid($current_url);
				$permalink = get_permalink($pageid);
				$permalink = getResourceFromString($permalink);
				$page_name = get_the_title($pageid);			
				$current_lesson_id = '';
			
				$lastLessonData = end($lessonurls);
				$lastLessonId = $lastLessonData['url'];
				if($permalink == $lastLessonData['url']){
					$current_lesson_id = $lastLessonId;
				}
				
				
				$insertInTable = 'N';	
				
				if($current_lesson_id != ''){
					$insertInTable = 'Y';	
				}
				
				$certifcate_html =  dapCheckIfCertificateDownloadShouldDisplay($courseId,$userId, $certificateType,$insertInTable);
				
				$output = $certifcate_html;
				 
			}
			
			
			return do_shortcode($output); 
		}
	}
}


add_action( 'wp_ajax_dap_insert_course_certificate', 'dap_insert_course_certificate' );
add_action( 'wp_ajax_nopriv_dap_insert_course_certificate','dap_insert_course_certificate');

function dap_insert_course_certificate(){	 
	$course_id = $_POST['course_id']; 
	$user_id = $_POST['user_id']; 
	$use_ajax = $_POST['use_ajax']; 
	$insert_certificate_data = insertUserCertificate($course_id ,$user_id, $use_ajax);  	
}

