<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class DateBook_Utilities
 *
 * @class DateBook_Utilities
 * @package DateBook/Classes
 * @author Pagick Themes
 */
class DateBook_Utilities {


	private static $datebook_options = null;

    public function __construct($datebook_options_array) {

		self::$datebook_options = $datebook_options_array;

		self::init();

	}

	/**
	 * Hook actions and filters.
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function init() {

		if(self::$datebook_options['what_pagebuilder_for_profile'] > 1 || is_admin()) {
			add_action( 'template_redirect', array( __CLASS__, 'datebook_get_current_user') );
		} else {
			add_action( 'get_header', array( __CLASS__, 'datebook_get_current_user') );
		}
		
		add_action( 'datebook_check_validated_email', array( __CLASS__, 'process_check_validated_email' ) );
		add_action( 'datebook_profile_all_statuses', array( __CLASS__, 'process_profile_statuses' ) );
		add_action( 'datebook_related_profiles_bycountry', array( __CLASS__, 'load_related_profiles_bycountry' ) );

		add_action( 'datebook_login_register_links', array( __CLASS__, 'login_register_links' ) );
		add_shortcode( 'datebook_login_register_links', array( __CLASS__, 'pre_login_register_links' ) );

		add_action( 'datebook_copyright', array( __CLASS__, 'copyright_text' ) );

		add_action( 'datebook_online_status', array( __CLASS__, 'process_online_status' ), 10, 4 );
		
	}


	/**
	 * Detect user device: mobile, tablet, iPad, Android, desktop and so on
	 * 
	 * @access public
	 */
	public static function mobile_detect() {

		$detect = new Mobile_Detect;

		if ($detect->isMobile() || $detect->isTablet()) {
			// MOBILE OR TABLET DEVICE
			$device = 'mobile';

		} else {
			// DESKTOP
			$device = 'desktop';

		}

		return $device;
	}


	/**
	 * Replace Administrator ID by User ID so that Administrator can edit user's data on frontend
	 * $retrieve_only: 1 = Get user's Profile ID; 0 = Get and update user's Profile ID
	 * @access public
	 */
	public static function datebook_replace_user_by_admin($currentauth_id = 0, $retrieve_only = 1) {

		if ($retrieve_only == 1 && is_super_admin()) {

			$get_user_id = get_option('datebook_user_id_by_admin') > 0 ? get_option('datebook_user_id_by_admin') : $currentauth_id;

			$profile_id = get_user_meta($get_user_id, 'profile_postid', true);

			$current_user_id = isset($profile_id) && $profile_id > 0 ? $get_user_id : $currentauth_id;

		} else if ($retrieve_only == 0 && is_super_admin()) {

			// We need to disable PREV and NEXT links in wp_head 
			// because it prevents from detecting the user ID of Profile
			remove_action('wp_head', 'wp_shortlink_wp_head');
			remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');

			$currentauth_id = absint($currentauth_id);

			$current_user_id = update_option('datebook_user_id_by_admin', $currentauth_id);

		} else {

			$current_user_id = $currentauth_id;

		}

		return $current_user_id;

	}


	/**
	 * Get current user ID
	 * 
	 * @since 4.4.1
	 * @access public
	 */
	public static function datebook_get_current_user($current_user_id = 0) {

		// Detect page ID
		$page_id = get_the_ID();

		// If ID of page is not detected then detect it with another method
		if(isset($page_id) && $page_id > 0){
			$page_id = $page_id;
		} else {
			$url = add_query_arg(array());
			$page_id = url_to_postid($url);
		}

		define('DATEBOOK_PAGE_ID', $page_id);

		$is_super_admin = is_super_admin() ? 1 : 0;

		$get_user_id = 0;

		if ($is_super_admin == 1) {

			global $post;

			if(isset($post->post_author) && $post->post_author > 0){
				$profile_id = isset($post->ID) && $post->ID > 0 ? $post->ID : 0;
				$user_id = $post->post_author;
				$post_type = isset($post->post_type) ? $post->post_type : '';
			} else {
				$profile_post = get_post($page_id);
				$profile_id = isset($profile_post->ID) && $profile_post->ID > 0 ? $profile_post->ID : 0;
				$user_id = isset($profile_post->post_author) && $profile_post->post_author > 0 ? $profile_post->post_author : 0;
				$post_type = isset($profile_post->post_type) ? $profile_post->post_type : '';
			}

			$post_type = !empty(get_post_type()) ? get_post_type() : (!empty($post_type) ? $post_type : '');
			
			define('DATEBOOK_PROFILE_ID', $profile_id);
			define('DATEBOOK_USER_ID', $user_id);
			define('DATEBOOK_PROFILE_TYPE', $post_type);

			if ($post_type == DATEBOOK_POST_TYPE){

				$get_user_id = $user_id;

				$datebook_replace_user_by_admin = DateBook_Utilities::datebook_replace_user_by_admin($user_id, 0);

			}
		}
		

		if($current_user_id > 0){

			$current_user_id = $current_user_id;

		} else {

			global $current_user;
			wp_get_current_user();
			$current_user_id = self::datebook_replace_user_by_admin($current_user->ID, 1);

		}

		define('DATEBOOK_CURRENT_USER_ID', $current_user_id);

	}


	/**
	 * Show some part of the website to logged in users only
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function datebook_show_to_logged_in_users( $what_to_show ) {

		if ($what_to_show == 1) {

			if (is_user_logged_in()) {

				$shown_result = 1;

			} else {

				$shown_result = 0;

			}

		} else {

			$shown_result = 1;

		}

		return $shown_result;

	}


	/**
	 * Check Google reCaptcha
	 * 
	 * @since 3.2
	 * @access public
	 */
	public static function datebook_google_recaptcha_response($type) {

		$google_recaptcha_error = 0;
		$google_recaptcha = self::$datebook_options['google_recaptcha'];

		if (!is_user_logged_in() && ($google_recaptcha[1] == 1 && $type = 'login' || $google_recaptcha[2] == 1 && $type = 'register')) {

			$google_recaptcha_response = isset($_POST['g-recaptcha-response']) ? $_POST['g-recaptcha-response'] : '';

			if(!$google_recaptcha_response){

				$google_recaptcha_error = 1;

			} else {
				
				$response = '';

				$google_recaptcha_secretkey = self::$datebook_options['google_recaptcha_secretkey'];
				$user_ip = $_SERVER['REMOTE_ADDR'];
				
				$google_verify_url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . $google_recaptcha_secretkey . '&response=' . $google_recaptcha_response . '&remoteip=' . $user_ip;

				if(in_array ('curl', get_loaded_extensions()) || function_exists('curl_init') !== false) {

					$ch = curl_init();
					curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
					curl_setopt($ch, CURLOPT_HEADER, 0);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
					curl_setopt($ch, CURLOPT_URL, $google_verify_url);
					curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
					$response = curl_exec($ch);
					curl_close($ch);

				} else if( ini_get('allow_url_fopen') ) {

					$response = file_get_contents($google_verify_url);

				}

				$responseKeys = json_decode($response,true);

				if(intval($responseKeys['success']) !== 1){

					$google_recaptcha_error = 1;

				}
			}
		}
		
		return $google_recaptcha_error;
	}


	/**
	 * Return "Online" status
	 * 
	 * @since 3.5
	 * @access public
	 */
	public static function return_online_status( $current_user_id, $gender, $profile_or_search, $force_small ) {

		$last_online_out = $last_online = '';

		$online_time = get_user_meta( $current_user_id, 'online_status', true );

		if ( !empty($online_time) && $online_time >= 0 ) {

			if($profile_or_search == 1){
				$indicator_type = self::$datebook_options['online_indicator_profile'] ? self::$datebook_options['online_indicator_profile'] : 2;
			} else if($profile_or_search == 2){
				$indicator_type = self::$datebook_options['online_indicator_search'] ? self::$datebook_options['online_indicator_search'] : 1;
			}

			if ($indicator_type < 5){

				$online_indicator_look = self::$datebook_options['online_indicator_look'] ? absint(self::$datebook_options['online_indicator_look']) : 4;

				switch($online_indicator_look) {
					case 1 : $design_look = 'badge-pill badge'; $design_look_location = 'datebook-online-top'; break;
					case 2 : $design_look = 'badge-pill badge'; $design_look_location = 'datebook-online-bottom';  break;
					case 3 : $design_look = 'badge'; $design_look_location = 'datebook-online-top';  break;
					case 4 : $design_look = 'badge'; $design_look_location = 'datebook-online-bottom';  break;
					default: $design_look = 'badge'; $design_look_location = 'datebook-online-bottom';  break;
				}

				$last_logout = get_user_meta( $current_user_id, 'last_logout', true );

				if($last_logout == 1){

					$check_online_status = 0; // 0 seconds

				} else {

					$check_online_status = self::$datebook_options['check_online_status'] ? self::$datebook_options['check_online_status'] : 120; // 120 seconds = 2 minutes

				}

				$now = time();

				if (($indicator_type < 5) && $now - $online_time < $check_online_status){
				
					switch($indicator_type) {
						case 1 : $online_text = '&nbsp;'; $online_css = 'datebook-online-round'; $online_tooltip_text = esc_html__( 'Online', 'datebook' ); break;
						case 2 : $online_text = esc_html__( 'Online', 'datebook' ); $online_css = ''; $online_tooltip_text = ''; break;
						case 3 : $online_text = esc_html__( 'Online', 'datebook' ); $online_css = ''; $online_tooltip_text = ''; break;
						case 4 : $online_text = esc_html__( 'Online', 'datebook' ); $online_css = ''; $online_tooltip_text = ''; break;
						default: $online_text = esc_html__( 'Online', 'datebook' ); $online_css = ''; $online_tooltip_text = ''; break;
					}
					
					$online_tooltip_out = $online_tooltip_text ? 'data-toggle="tooltip" data-placement="top" data-original-title="' . $online_tooltip_text . '"' : '';

					$last_online = '<span class="badge ' . $design_look . '-success shadow-none datebook-badge-online ' . $online_css . '" ' . $online_tooltip_out . '>' . $online_text . '</span>';

				} else if ($indicator_type == 3 || $indicator_type == 4) {


					// Array of time period chunks
					$chunks = array(
						array( 60 * 60 * 24 * 365 , esc_html__( 'year', 'datebook' ), esc_html__( 'years', 'datebook' ) ),
						array( 60 * 60 * 24 * 30 , esc_html__( 'month', 'datebook' ), esc_html__( 'months', 'datebook' ) ),
						array( 60 * 60 * 24 * 7, esc_html__( 'week', 'datebook' ), esc_html__( 'weeks', 'datebook' ) ),
						array( 60 * 60 * 24 , esc_html__( 'day', 'datebook' ), esc_html__( 'days', 'datebook' ) ),
						array( 60 * 60 , esc_html__( 'hour', 'datebook' ), esc_html__( 'hours', 'datebook' ) ),
						array( 60 , esc_html__( 'minute', 'datebook' ), esc_html__( 'minutes', 'datebook' ) ),
						array( 1, esc_html__( 'second', 'datebook' ), esc_html__( 'seconds', 'datebook' ) )
					);

					// Difference in seconds
					$since = $now - $online_time;

					// Something went wrong with date calculation and we ended up with a negative date.
					if ( 0 > $since )
						return esc_html__( 'Sometime', 'datebook' );

					// We only want to output one chunks of time here, eg: x years, xx months
					// so there's only one bit of calculation below:

					//Step one: the first chunk
					for ( $i = 0, $j = count($chunks); $i < $j; $i++) {
	
						$seconds = $chunks[$i][0];

						// Finding the biggest chunk (if the chunk fits, break)
						if ( ( $count = floor($since / $seconds) ) != 0 )
							break;

					}

					if ($gender == 1) {
						$gender_was_here = esc_html__( 'Last seen', 'datebook' ); // She was here
					} else if ($gender == 2) {
						$gender_was_here = esc_html__( 'Last seen', 'datebook' ); // He was here
					} else {
						$gender_was_here = esc_html__( 'Last seen', 'datebook' ); // Was here
					}

					if($count == 1){
						$get_online_time = '1 ' . $chunks[$i][1];
					} else if($i < 7){
						$get_online_time = $count . ' ' . $chunks[$i][2];
					} else {
						$get_online_time = 0;
					}

					if ( !(int)trim($get_online_time) ){
						$get_online_time = '0 ' . esc_html__( 'seconds', 'datebook' );
					}

					// Create text
					$change_online_words_places = self::$datebook_options['change_online_words_places'] ? self::$datebook_options['change_online_words_places'] : array( 'es_ES', 'fr_FR', 'ro_RO' ); // es_ES = Spanish, fr_FR = French, ro_RO = Romanian by default if not set in Admin Dashboard

					if ( isset($change_online_words_places[strtolower(DATEBOOK_WPLANG)]) && $change_online_words_places[strtolower(DATEBOOK_WPLANG)] == 1) {

						$last_online_text_ago = esc_html__( 'ago', 'datebook' ) . ' ' . $get_online_time;

					} else {

						$last_online_text_ago = $get_online_time . ' ' . esc_html__( 'ago', 'datebook' );

					}
					
					if($force_small == 'small'){
						$indicator_type = 4;
					}

					switch($indicator_type) {
						case 1 : $online_text = '';					$online_full_text = $gender_was_here . ' ' . $last_online_text_ago; break;
						case 2 : $online_text = $gender_was_here;	$online_full_text = ''; break;
						case 3 : $online_text = $gender_was_here;	$online_full_text = ''; break;
						case 4 : $online_text = '';					$online_full_text = $gender_was_here . ' ' . $last_online_text_ago; break;
						default: $online_text = $gender_was_here;	$online_full_text = ''; break;
					}

					// Set output design
					$last_online = '<span class="badge ' . $design_look . '-light font-weight-light shadow-none datebook-badge-online" data-toggle="tooltip" data-placement="top" data-original-title="' . $online_full_text . '">';

					$last_online .= $online_text . ' ' . $last_online_text_ago;

					$last_online .= '</span>';

				}

				$last_online_out = '<span class="datebook-online-caption ' . $design_look_location . '">' . $last_online . '</span>';


				$allowedposttags = array( 'span' => array( 'class' => array(), 'data-toggle' => array(), 'data-placement' => array(), 'data-original-title' => array() ));

				return wp_kses( $last_online_out, $allowedposttags );

			}
		}
	}


	/**
	 * Show "Online" status on the Profile page
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function process_online_status( $current_user_id, $gender, $profile_or_search = 1, $force_small = 'full' ) {

		echo self::return_online_status( $current_user_id, $gender, $profile_or_search, $force_small );

	}



	/**
	 * Count all online users
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function datebook_count_online_users( $args = array() ) {
		
		$check_online_status = self::$datebook_options['check_online_status'] ? absint(self::$datebook_options['check_online_status']) : 120; // 120 seconds = 2 minutes
		
		$args = wp_parse_args( $args, array(
			'meta_key' => 'online_status',
			'meta_value' => time() - $check_online_status,
			'meta_compare' => '>',
			'count_total' => false,
		));
		
		$users = count(get_users( $args ));
		
		return $users;
		
	}


	/**
	 * Set email in html format
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function datebook_set_html_mail_content_type() {
		
		return 'text/html';
		
	}

	/**
	 * Send email
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function datebook_email_send($fromname, $fromemail, $to, $subj, $body) {

		add_action( 'wp_mail_content_type', array( __CLASS__, 'datebook_set_html_mail_content_type' ) );

		// Name of sender
		if (empty($fromname)) {
			$fromname = self::$datebook_options['email_sitename'];
		}
		$fromname = sanitize_text_field($fromname);

		// Email of sender
		if (empty($fromemail)) {
			$fromemail = self::$datebook_options['email_siteemail'];
		}
		$fromemail = sanitize_email($fromemail);

		$to = sanitize_email($to);
		$subj = sanitize_text_field($subj);
		$body = wp_kses_post($body);

		$headers = 'From: <' . self::$datebook_options['email_siteemail'] . '>' . "\r\n";

		if(self::$datebook_options['show_name_text_in_notification'] == 1){
			$headers .= 'Reply-To: ' . $fromname . ' <' . $fromemail . '>' . "\r\n";
		}

		$headers .= "Content-Type: text/html; charset=UTF-8";

		$wp_mail = wp_mail($to, $subj, $body, $headers);

		// Reset content-type to avoid conflicts -- https://core.trac.wordpress.org/ticket/23578
		remove_filter( 'wp_mail_content_type', array( __CLASS__, 'datebook_set_html_mail_content_type' ) );

		return $wp_mail;

	}


	/**
	 * Translate month and weekday
	 * Borrowed from WordPress function date_i18n
	 *
	 * @access public
	 */
	public static function datebook_date_i18n($dateformat_select, $unixtimestamp = false, $strtotime = true, $gmt = false){

		global $wp_locale;

		switch ( $dateformat_select ) {

			case 1 : $dateformatstring = get_option('date_format'); break;
			case 2 : $dateformatstring = get_option('date_format') . ' ' . get_option('time_format'); break;
			case 3 : $dateformatstring = get_option('time_format'); break;
			default: $dateformatstring = get_option('date_format');

		}

		if($dateformatstring == 'm/d/Y'){
			$unixtimestamp = explode("/", $unixtimestamp);
			$unixtimestamp = $unixtimestamp[1]. '-' . $unixtimestamp[0]. '-' . $unixtimestamp[2];
		}


		if($strtotime){
			$unixtimestamp = str_replace('/', '-', $unixtimestamp);
			$unixtimestamp = strtotime($unixtimestamp);
		}


		// Get local time and covert date of message to local time.
		$unixtimestamp_date = date('Y-m-d H:i:s', $unixtimestamp);
		$unixtimestamp = Class_DateBook_IP::local_timezone($unixtimestamp_date);


		$i = $unixtimestamp;

		if ($i === false) {
			$i = current_time( 'timestamp', $gmt );
		}

		/*
		 * Store original value for language with untypical grammars.
		 * See https://core.trac.wordpress.org/ticket/9396
		 */
		$req_format = $dateformatstring;

		if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
			$datemonth = esc_html__( $wp_locale->get_month( date( 'm', $i ) ), 'datebook' );
			$datemonth_abbrev = $wp_locale->get_month_abbrev( $wp_locale->get_month( date( 'm', $i ) ) );
			$dateweekday = esc_html__( $wp_locale->get_weekday( date( 'w', $i ) ), 'datebook' );
			$dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $wp_locale->get_weekday( date( 'w', $i ) ) );
			$datemeridiem = $wp_locale->get_meridiem( date( 'a', $i ) );
			$datemeridiem_capital = $wp_locale->get_meridiem( date( 'A', $i ) );
			$dateformatstring = ' '.$dateformatstring;
			$dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
			$dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
			$dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
			$dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
			$dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
			$dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );

			$dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
		}
		$timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
		$timezone_formats_re = implode( '|', $timezone_formats );
		if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) ) {
			$timezone_string = get_option( 'timezone_string' );
			if ( $timezone_string ) {
				$timezone_object = timezone_open( $timezone_string );
				$date_object = date_create( null, $timezone_object );
				foreach ( $timezone_formats as $timezone_format ) {
					if ( false !== strpos( $dateformatstring, $timezone_format ) ) {
						$formatted = date_format( $date_object, $timezone_format );
						$dateformatstring = ' '.$dateformatstring;
						$dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring );
						$dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
					}
				}
			}
		}
		$j = @date( $dateformatstring, $i );

		return $j;
	}


	/**
	 * Encode photo name
	 *
	 * @access private
	 * @return void
	 */
	public static function datebook_encode($image_title){

		$encoded_title = str_replace(array('=', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'), '', strtolower(base64_encode($image_title)));

		return $encoded_title;

	}


	/**
	 * Detect who can see my profile
	 * 
	 * @since 4.3
	 * @access public
	 */
	public static function who_can_see_my_profile($current_user_id, $currentauth, $profile_id, $datebook_get_data){

		$can_see_profile_array = array();
		$can_see_profile = 1;
		$can_see_profile_text = '';

		if(isset($currentauth->ID) && $currentauth->ID > 0 && $currentauth->ID != $current_user_id && !is_super_admin()){

			$allow_choose_who_can_see_profile = self::$datebook_options['allow_choose_who_can_see_profile'] ? self::$datebook_options['allow_choose_who_can_see_profile'] : array();

			$count_allow_choose_who_can_see_profile = count(array_keys($allow_choose_who_can_see_profile, 1));

			if (isset($count_allow_choose_who_can_see_profile) && $count_allow_choose_who_can_see_profile > 0) {

				$datebook_who_can_see_my_profile = isset($datebook_get_data['datebook_who_can_see_my_profile']) ? $datebook_get_data['datebook_who_can_see_my_profile'] : '';

				if($datebook_who_can_see_my_profile == ''){
					foreach($allow_choose_who_can_see_profile as $key => $value){
						if($value == 1){
							$datebook_who_can_see_my_profile = $key;
							break;
						}
					}
				}

				if(array_key_exists($datebook_who_can_see_my_profile, $allow_choose_who_can_see_profile)){

					$can_see_profile = 0;

					if($datebook_who_can_see_my_profile == 'everyone'){
						$can_see_profile = 1;
					} else if($datebook_who_can_see_my_profile == 'noone'){
						$can_see_profile = 0;
						$can_see_profile_text = esc_html__( 'Author closed the content', 'datebook' );
					} else if($datebook_who_can_see_my_profile == 'friends' && self::$datebook_options['enable_friendship'] == 1){
						if(is_user_logged_in()){

							$friends = get_user_meta($current_user_id, 'friends', true);
							if ($friends) {
								$friends = array_unique(explode(",", $friends));
							} else {
								$friends = array();
							}

							if (in_array($profile_id, $friends)) {

								// If profile ID is not set in post_meta table then let's insert it
								$profile_id_of_current_user = get_user_meta( $current_user_id, 'profile_postid', true );

								if(isset($profile_id_of_current_user) && isset($datebook_get_data['friends'][$profile_id_of_current_user]['status']) && $datebook_get_data['friends'][$profile_id_of_current_user]['status'] == 'approved'){
									$can_see_profile = 1;
								}
							} else {
								$can_see_profile = 0;
								$can_see_profile_text = esc_html__( 'Only friends can see the content', 'datebook' );
							}
						} else {
							$can_see_profile = 0;
							$can_see_profile_text = esc_html__( 'Only friends can see the content', 'datebook' );
						}

					} else if($datebook_who_can_see_my_profile == 'loggedinusers'){
						if(is_user_logged_in()){
							$can_see_profile = 1;
						} else {
							$can_see_profile = 0;
							$can_see_profile_text = esc_html__( 'Only registered users can see the content', 'datebook' );
						}
					} else if($datebook_who_can_see_my_profile == 'subscribedusers'){
						if(is_user_logged_in()){
							// Check if Payment and Subscription are activated
							if (self::check_if_gateway_activated()){
								$user_selected_subscription_plan = DateBook_Profile_Subscription::user_selected_subscription_plan($current_user_id);
								if($user_selected_subscription_plan > 0){
									$can_see_profile = 1;
								} else {
									$can_see_profile = 0;
									$can_see_profile_text = esc_html__( 'Only subscribed members can see the content', 'datebook' );
								}
							} else {
								$can_see_profile = 1;
							}
						} else {
							$can_see_profile = 0;
							$can_see_profile_text = esc_html__( 'Only subscribed members can see the content', 'datebook' );
						}
					} else if($datebook_who_can_see_my_profile == 'askforpermission' && is_user_logged_in()){
						$can_see_profile = 0;
						$can_see_profile_text = esc_html__( 'You can send request to see the content', 'datebook' );
					}
				}
			}
		}
		
		$can_see_profile_array['allow'] = $can_see_profile;
		$can_see_profile_array['text'] = $can_see_profile_text;

		return $can_see_profile_array;

	}


	/**
	 * Detect who can see my images
	 * 
	 * @since 4.3
	 * @access public
	 */
	public static function who_can_see_my_images($current_user_id, $currentauth, $profile_id, $datebook_get_data){

		$can_see_images_array = array();
		$can_see_images = 1;
		$can_see_images_text = '';

		if(isset($currentauth->ID) && $currentauth->ID > 0 && $currentauth->ID != $current_user_id && !is_super_admin()){

			$allow_choose_who_can_see_images = self::$datebook_options['allow_choose_who_can_see_images'] ? self::$datebook_options['allow_choose_who_can_see_images'] : array();

			$count_allow_choose_who_can_see_images = count(array_keys($allow_choose_who_can_see_images, 1));
			
			if (isset($count_allow_choose_who_can_see_images) && $count_allow_choose_who_can_see_images > 0) {
				
				$datebook_who_can_see_my_images = isset($datebook_get_data['datebook_who_can_see_my_images']) ? $datebook_get_data['datebook_who_can_see_my_images'] : '';

				if($datebook_who_can_see_my_images == ''){
					foreach($allow_choose_who_can_see_images as $key => $value){
						if($value == 1){
							$datebook_who_can_see_my_images = $key;
							break;
						}
					}
				}

				if(array_key_exists($datebook_who_can_see_my_images, $allow_choose_who_can_see_images)){

					$can_see_images = 0;

					if($datebook_who_can_see_my_images == 'everyone'){
						$can_see_images = 1;
					} else if($datebook_who_can_see_my_images == 'noone'){
						$can_see_images = 0;
						$can_see_images_text = esc_html__( 'Photo is closed', 'datebook' );
					} else if($datebook_who_can_see_my_images == 'friends' && self::$datebook_options['enable_friendship'] == 1){
						if(is_user_logged_in()){
							$friends = get_user_meta($current_user_id, 'friends', true);
							if ($friends) {
								$friends = array_unique(explode(',', $friends));
							} else {
								$friends = array();
							}

							if (in_array($profile_id, $friends)) {

								// If profile ID is not set in post_meta table then let's insert it
								$profile_id_of_current_user = get_user_meta( $current_user_id, 'profile_postid', true );

								if(isset($profile_id_of_current_user) && isset($datebook_get_data['friends'][$profile_id_of_current_user]['status']) && $datebook_get_data['friends'][$profile_id_of_current_user]['status'] == 'approved'){
									$can_see_images = 1;
								}
							} else {
								$can_see_images = 0;
								$can_see_images_text = esc_html__( 'Photo shown to friends', 'datebook' );
							}
						} else {
							$can_see_images = 0;
							$can_see_images_text = esc_html__( 'Photo shown to friends', 'datebook' );
						}

					} else if($datebook_who_can_see_my_images == 'loggedinusers'){
						if(is_user_logged_in()){
							$can_see_images = 1;
						} else {
							$can_see_images = 0;
							$can_see_images_text = esc_html__( 'Photo shown to registered users', 'datebook' );
						}
					} else if($datebook_who_can_see_my_images == 'subscribedusers'){
						if(is_user_logged_in()){
							// Check if Payment and Subscription are activated
							if (self::check_if_gateway_activated()){
								$user_selected_subscription_plan = DateBook_Profile_Subscription::user_selected_subscription_plan($current_user_id);
								if($user_selected_subscription_plan > 0){
									$can_see_images = 1;
								} else {
									$can_see_images = 0;
									$can_see_images_text = esc_html__( 'Photo shown to subscribed members', 'datebook' );
								}
							} else {
								$can_see_images = 1;
							}
						} else {
							$can_see_images = 0;
							$can_see_images_text = esc_html__( 'Photo shown to subscribed members', 'datebook' );
						}
					} else if($datebook_who_can_see_my_images == 'askforpermission' && is_user_logged_in()){
						$can_see_images = 0;
						$can_see_images_text = esc_html__( 'Send request to see the photo', 'datebook' );
					}
				}
			}
		}

		$can_see_images_array['allow'] = $can_see_images;
		$can_see_images_array['text'] = $can_see_images_text;

		return $can_see_images_array;

	}


	/**
	 * Upload photo
	 *
	 * @access private
	 * @return void
	 */
	public static function process_upload_photo($datebook_post_image_upload, $datebook_files_images, $datebook_photo_type, $datebook_photo_formats, $profile_id, $default_thumbnail_show, $current_user_id) {

		if( isset( $datebook_post_image_upload ) && !empty( $datebook_files_images )) {

			$profile_personal_data_updated = 0;

			if ($profile_id) {

				$postvals = array();

				// Allowed file extension
				$datebook_allowed_extensions = self::$datebook_options['allowed_file_extensions'] ? array_map('trim', explode(',', self::$datebook_options['allowed_file_extensions'])) : array('jpg','gif','png','bmp'); // jpg,gif,png,bmp by default id not set in Admin Dashboard

				// Get personal data
				$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
				$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

				$upload_folder = isset($datebook_get_data['upload_folder']) ? $datebook_get_data['upload_folder'] : '';

				if (!$upload_folder) {

					$datebook_get_data['upload_folder'] = time().rand(1,999);

					// Update the post meta
					$profile_personal_data_updated = 1;

				}

				$upload_dir = wp_upload_dir();

				if($datebook_photo_type == DATEBOOK_IMAGE_CHAT){
					$upload_folder = 'datebook-chat';
				}

				$targetURL = $upload_dir['baseurl'] . '/' . $upload_folder;
				$targetPath = $upload_dir['basedir'] . '/' . $upload_folder;

				if ( ! file_exists( $targetPath ) ) {

					wp_mkdir_p( $targetPath );

				}

				$count_all_found_posts = $quantity_photos = 0;

				if ($datebook_photo_type != DATEBOOK_VERIFICATION_IMAGE_TYPE || $datebook_photo_type != DATEBOOK_IMAGE_CHAT) {

					$subscription_exists = 1;
					$allow_upload_photos = 1;
					$quantity_photos = absint(self::$datebook_options['quantity_images_per_profile']);

					// Check if Payment and Subscription are activated
					if (self::check_if_gateway_activated()) {

						// Get user subscription id
						$member_subscriptions = datebook_get_member_subscriptions( array( 'user_id' => $current_user_id ) );
						$member_splan_id = isset($member_subscriptions[0]->subscription_plan_id) ? $member_subscriptions[0]->subscription_plan_id : NULL;
						if($member_splan_id > 0){

							$subscription_exists = 1;

							$all_splans = get_option('datebook_subscription_plans');
							if(isset($all_splans[$member_splan_id]['upload_images']) && $all_splans[$member_splan_id]['upload_images'] == '1') {
								$allow_upload_photos = 1;
								if(isset($all_splans[$member_splan_id]['subscription_id']) && isset($member_splan_id) && $member_splan_id > 0 && $all_splans[$member_splan_id]['subscription_id'] == $member_splan_id) {
									$quantity_photos = absint($all_splans[$member_splan_id]['subscription_limitphotos']);
								}
							} else {
								$subscription_exists = 0;
								$allow_upload_photos = 0;
								$quantity_photos = 0;
							}

						} else {
							$subscription_exists = 1;
							$allow_upload_photos = 1;
							$quantity_photos = $quantity_photos;
						}
					}

					$all_photos_args = array(
						'post_parent' => $profile_id, 
						'post_status' => 'inherit', 
						'post_type' => 'attachment', 
						'post_mime_type' => 'image', 
						'order' => 'ASC', 
						'orderby' => 'menu_order ID',
						'posts_per_page' => -1,
						'meta_query' => array(
							array('key' => DATEBOOK_IMAGE_TYPE, 'value' => DATEBOOK_PROFILE_IMAGE_TYPE, 'compare' => '=' )
						)
					);

					$all_photos = new WP_Query( $all_photos_args );

					$count_all_found_posts = $all_photos->found_posts;

					wp_reset_postdata();

				}

				if ($allow_upload_photos == 0) {

					$postvals['success'] = 0; // 1 - success, 0 - error
					$postvals['successtext'] = '<div class="alert alert-warning">' . sprintf( esc_html__( 'Sorry! Your subscription does not include the possbility to upload images', 'datebook' ), $quantity_photos ) . '</div>';

				} else if ($subscription_exists == 0) {
					
					$postvals['success'] = 0; // 1 - success, 0 - error
					$postvals['successtext'] = '<div class="alert alert-warning">' . sprintf( esc_html__( 'Sorry! You must first select a subscription plan to upload images.', 'datebook' ), $quantity_photos ) . '</div>';
					
				} else {
					
					if (($datebook_photo_type != DATEBOOK_VERIFICATION_IMAGE_TYPE || $datebook_photo_type != DATEBOOK_IMAGE_CHAT) && $quantity_photos > 0 && $count_all_found_posts >= $quantity_photos) {
						
						$quantity_photos_text = sprintf( _n( '%s image', '%s images', $quantity_photos, 'datebook' ), $quantity_photos );

						$postvals['success'] = 0; // 1 - success, 0 - error
						$postvals['successtext'] = '<div class="alert alert-warning">' . sprintf( esc_html__( 'Sorry! You may upload up to', 'datebook' ), $quantity_photos_text ) . ' ' . $quantity_photos_text . '</div>';

					} else {


						//check file extension
						$extension = str_replace('image/', '', $datebook_files_images['type']);
						$extension = str_replace('jpeg', 'jpg', $extension);

						if ( !in_array( $extension, $datebook_allowed_extensions ) ) {

							$postvals['success'] = 0; // 1 - success, 0 - error
							$postvals['successtext'] = '<div class="alert alert-danger">' . sprintf( esc_html__( "Oops! Your image have not been uploaded due to wrong extension. You may upload only these extensions: %s", 'datebook' ), $datebook_allowed_extensions ) . '</div>';

						} else {

							global $datebook_image_sizes;

							// Image width and height sizes
							$datebook_minimal_image_dimensions = self::$datebook_options['minimal_image_dimensions'] ? explode(',', self::$datebook_options['minimal_image_dimensions']) : array($datebook_image_sizes['image_medium']['width'],$datebook_image_sizes['image_profile']['height']); // default is taken from variable $datebook_image_sizes if not set in Admin Dashboard
						
							// If minimum sizes in Theme Options set less than default then place default sizes
							$min_width = isset($datebook_minimal_image_dimensions[0]) && $datebook_minimal_image_dimensions[0] > $datebook_image_sizes['image_medium']['width'] ? $datebook_minimal_image_dimensions[0] : $datebook_image_sizes['image_medium']['width'];
							$min_height = isset($datebook_minimal_image_dimensions[1]) && $datebook_minimal_image_dimensions[1] > $datebook_image_sizes['image_profile']['height'] ? $datebook_minimal_image_dimensions[1] : $datebook_image_sizes['image_profile']['height'];


							// Check if Retina enabled in Theme Options
							$enable_retina_images = self::$datebook_options['enable_retina_images'] ? 2 : 1;

							$min_width = $min_width * $enable_retina_images;
							$min_height = $min_height * $enable_retina_images;

							// Check width and height of uploaded image
							$image_width_height = getimagesize($datebook_files_images['tmp_name']);
							$uploaded_width = $image_width_height[0];
							$uploaded_height = $image_width_height[1];


							//Get the Size of the File
							$file_size = $datebook_files_images['size'];

							// Max file size allowed to upload
							$datebook_max_upload_size = self::$datebook_options['allowed_max_image_size'] > 0 ? absint(self::$datebook_options['allowed_max_image_size']) : wp_max_upload_size();

							//Make sure that file width and height size is not too small
							if ($min_width > $uploaded_width && $min_height > $uploaded_height) {

								$postvals['success'] = 0; // 1 - success, 0 - error
								$postvals['successtext'] = '<div class="alert alert-warning">' . sprintf( esc_html__( 'Oops! Upload an image not less than width %spx and height %spx', 'datebook' ), $min_width, $min_height ) . '</div>';

							} else if ($file_size > $datebook_max_upload_size) {

								$postvals['success'] = 0; // 1 - success, 0 - error
								$postvals['successtext'] = '<div class="alert alert-warning">' . esc_html__( 'Oops! You are trying to upload too big image. Please, choose an image of smaller size.', 'datebook' ) . '</div>';

							} else if ($file_size == 0) {

								$postvals['success'] = 0; // 1 - success, 0 - error
								$postvals['successtext'] = '<div class="alert alert-warning">' . esc_html__( 'Oops! You are trying to upload an empty image. Please, choose another image.', 'datebook' ) . '</div>';

							} else {
			

								if(!function_exists('wp_handle_upload')){
						        	include_once(ABSPATH . 'wp-admin/includes/file.php');
						    	}
								include_once(ABSPATH . 'wp-admin/includes/image.php');

								// Override the default upload path
								function datebook_upload_dir( $dirs ) {

									global $profile_id;

									$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
									$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

									$upload_folder = isset($datebook_get_data['upload_folder']) ? $datebook_get_data['upload_folder'] : '';

								    $dirs['subdir'] = '/' . $upload_folder;
								    $dirs['path'] = $dirs['basedir'] . '/' . $upload_folder;
							    	$dirs['url'] = $dirs['baseurl'] . '/' . $upload_folder;

								    return $dirs;
								}

								// If image uploaded from chat then change folder to WordPress month folder
								if($datebook_photo_type != DATEBOOK_IMAGE_CHAT){
									add_filter( 'upload_dir', 'datebook_upload_dir' );
								}


								function datebook_hash_filename( $filename ) {
									$info = pathinfo( $filename );
									$ext  = empty( $info['extension'] ) ? '' : '.jpg';//$info['extension'];
									$name = basename( $filename, $ext );

									$generate_picName = time().rand(1, 999);

									$targetFile = $generate_picName.$ext;

									return $targetFile;
								}
								add_filter( 'sanitize_file_name', 'datebook_hash_filename', 10 );


								// Do our thing. WordPress will move the file to 'uploads/mycustomdir'.
								$uploaded_file = wp_handle_upload( $datebook_files_images, array( 'test_form' => false ) );



								// Set everything back to normal.
								remove_filter( 'sanitize_file_name', 'datebook_hash_filename', 10 );

								if($datebook_photo_type != DATEBOOK_IMAGE_CHAT){
									remove_filter( 'upload_dir', 'datebook_upload_dir' );
								}

								// remove it
								function remove_image_sizes($sizes){

									unset( $sizes['thumbnail']);
									unset( $sizes['medium']);
									unset( $sizes['large']);
									unset( $sizes['datebook-featured']);
									unset( $sizes['medium_large']);

									return $sizes;

								}

								add_filter('intermediate_image_sizes_advanced', 'remove_image_sizes' );
								add_filter('image_size_names_choose', 'remove_image_sizes' );


								if( $uploaded_file && ! isset( $uploaded_file['error'] ) ) {

									$enable_watermark = self::$datebook_options['enable_watermark'] == '1' ? 1 : 0;

									$enable_retina_images = self::$datebook_options['enable_retina_images'] == '1' ? 1 : 0;

									$blur_variant = self::$datebook_options['blur_variant'] ? self::$datebook_options['blur_variant'] : 0;

									$filename = $uploaded_file['file'];
									$targetFile = sanitize_file_name(basename($filename));
									$explode_picName = explode('.', $targetFile);
									$generate_picName = $explode_picName[0];

									$path_to_original_file = $uploaded_file['file']; //$targetPath . '/' . $targetFile;


									add_filter( 'wp_image_editors', function( $editors ) {
										require_once DATEBOOK_DIR . 'includes/class-datebook-watermark.php';
										if ( ! is_array( $editors ) ) return $editors; //someone broke the filtered value

										array_unshift( $editors, 'DateBook_Watermark');
										return $editors;
									});


									// Let's create images of defined formats only
									foreach($datebook_photo_formats as $format => $actions) {
										
										$thumb_width = $datebook_image_sizes[$format]['width'];
										$thumb_height = $datebook_image_sizes[$format]['height'];

										// Create this format image
										$different_thumbnail = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height']) . '.jpg';//$extension;
										$different_thumbnail_blur = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height'] . '-blur') . '.jpg';//$extension;
										if (!file_exists($targetPath . '/' . $different_thumbnail)) {

											$image = wp_get_image_editor($filename);
											if ( ! is_wp_error( $image ) ) {
												$image->resize($datebook_image_sizes[$format]['width'], $datebook_image_sizes[$format]['height'], $actions['crop']);
												if($enable_watermark == 1 && $actions['watermark']){
													$image->add_watermark($datebook_image_sizes[$format]['width'], $datebook_image_sizes[$format]['height']);
												}
												$image->save($targetPath . '/' . $different_thumbnail);

												// Create and blur a new image
												if($blur_variant > 0){
													$image->save($targetPath . '/' . $different_thumbnail_blur);
													$image->add_blur($targetPath . '/' . $different_thumbnail_blur);
												}
											}
										}
										
										// Create Retina images
										if($enable_retina_images == 1){

											// Get size of original image
											list($orig_thumb_width, $orig_thumb_height) = getimagesize($filename);

											// Create retina 2x size
											$retina_thumbnail_url = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height']) . '@2x.jpg';
											$retina_thumbnail_url_blur = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height'] . '-blur') . '@2x.jpg';

											if (!file_exists($targetPath . '/' . $retina_thumbnail_url)){
												$image = wp_get_image_editor($filename);
												if (!is_wp_error($image)){
													$thumb_width = $datebook_image_sizes[$format]['width'] * 2;
													$thumb_height = $datebook_image_sizes[$format]['height'] * 2;

													// Compare original image to retina sizes
													$thumb_width = $orig_thumb_width < $thumb_width ? $orig_thumb_width : $thumb_width;
													$thumb_height = $orig_thumb_height < $thumb_height ? $orig_thumb_height : $thumb_height;

													$image->resize($thumb_width, $thumb_height, $actions['crop']);
													if($enable_watermark == 1 && $actions['watermark']){
														$image->add_watermark($thumb_width, $thumb_height);
													}
													$image->save($targetPath . '/' . $retina_thumbnail_url);

													// Create and blur a new image
													if($blur_variant > 0){
														$image->save($targetPath . '/' . $retina_thumbnail_url_blur);
														$image->add_blur($targetPath . '/' . $retina_thumbnail_url_blur);
													}
												}
											}

											// Create retina 1.5x size
											$retina_thumbnail_url_15 = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height']) . '@1.5x.jpg';
											$retina_thumbnail_url_blur_15 = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height'] . '-blur') . '@1.5x.jpg';

											if (!file_exists($targetPath . '/' . $retina_thumbnail_url_15)){
												$image = wp_get_image_editor($filename);
												if (!is_wp_error($image)){

													$percentage = 50;
													$thumb_width = round(($percentage / 100) * $datebook_image_sizes[$format]['width'] + $datebook_image_sizes[$format]['width']);
													$thumb_height = round(($percentage / 100) * $datebook_image_sizes[$format]['height'] + $datebook_image_sizes[$format]['height']);

													// Compare original image to retina sizes
													$thumb_width = $orig_thumb_width < $thumb_width ? $orig_thumb_width : $thumb_width;
													$thumb_height = $orig_thumb_height < $thumb_height ? $orig_thumb_height : $thumb_height;

													$image->resize($thumb_width, $thumb_height, $actions['crop']);
													if($enable_watermark == 1 && $actions['watermark']){
														$image->add_watermark($thumb_width, $thumb_height);
													}
													$image->save($targetPath . '/' . $retina_thumbnail_url_15);

													// Create and blur a new image
													if($blur_variant > 0){
														$image->save($targetPath . '/' . $retina_thumbnail_url_blur_15);
														$image->add_blur($targetPath . '/' . $retina_thumbnail_url_blur_15);
													}
												}
											}
	
											// Create retina 1.25x size
											$retina_thumbnail_url_125 = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height']) . '@1.25x.jpg';
											$retina_thumbnail_url_blur_125 = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$format]['width'] . 'x' . $datebook_image_sizes[$format]['height'] . '-blur') . '@1.25x.jpg';

											if (!file_exists($targetPath . '/' . $retina_thumbnail_url_125)){
												$image = wp_get_image_editor($filename);
												if (!is_wp_error($image)){

													$percentage = 25;
													$thumb_width = round(($percentage / 100) * $datebook_image_sizes[$format]['width'] + $datebook_image_sizes[$format]['width']);
													$thumb_height = round(($percentage / 100) * $datebook_image_sizes[$format]['height'] + $datebook_image_sizes[$format]['height']);

													// Compare original image to retina sizes
													$thumb_width = $orig_thumb_width < $thumb_width ? $orig_thumb_width : $thumb_width;
													$thumb_height = $orig_thumb_height < $thumb_height ? $orig_thumb_height : $thumb_height;

													$image->resize($thumb_width, $thumb_height, $actions['crop']);
													if($enable_watermark == 1 && $actions['watermark']){
														$image->add_watermark($thumb_width, $thumb_height);
													}
													$image->save($targetPath . '/' . $retina_thumbnail_url_125);

													// Create and blur a new image
													if($blur_variant > 0){
														$image->save($targetPath . '/' . $retina_thumbnail_url_blur_125);
														$image->add_blur($targetPath . '/' . $retina_thumbnail_url_blur_125);
													}
												}
											}
										}
									}

									$attachment = array(
										'post_mime_type' => $datebook_files_images['type'],
										'guid' => $targetURL . '/' . $targetFile,
										'post_status ' => 'inherit',
										'post_parent' => $profile_id,
										'post_title' => $targetFile,
										'post_type' => 'attachment'
									);

									// Save the attachment metadata
									$attach_id = wp_insert_attachment($attachment, $path_to_original_file, $profile_id);

									$attach_data = wp_generate_attachment_metadata( $attach_id, $path_to_original_file );

									wp_update_attachment_metadata( $attach_id, $attach_data );


									// Insert post meta for Verification
									if ($datebook_photo_type == DATEBOOK_VERIFICATION_IMAGE_TYPE) {

										$verification_photo_ID = isset($datebook_get_data[DATEBOOK_VERIFICATION_CONFIRM_PHOTO]) ? $datebook_get_data[DATEBOOK_VERIFICATION_CONFIRM_PHOTO] : 0;

										if ($verification_photo_ID > 0) {

											$verification_title = get_post($verification_photo_ID);
											wp_delete_attachment( $verification_photo_ID, $force_delete = true );
											// Delete all selected images
											self::datebook_delete_all_photos($upload_folder, $verification_title->post_title);

										}

										// Save the post meta for verification
										$datebook_get_data[DATEBOOK_VERIFICATION_CONFIRM_PHOTO] = $attach_id;

										// Update the post meta
										$profile_personal_data_updated = 1;

										DateBook_Profile_Verification::datebook_send_message_to_admin($profile_id);

									}

									if($datebook_photo_type != DATEBOOK_IMAGE_CHAT){

										// Add what type of photo we uploaded. We will need this information later
										update_post_meta($attach_id, DATEBOOK_IMAGE_TYPE, $datebook_photo_type);

									}


									// Get profile photo set as default
									$profile_photo_id = isset($datebook_get_data['profile_photo_id']) ? $datebook_get_data['profile_photo_id'] : '';
									// Check if default photo set
									if ($profile_photo_id == ''){
										update_post_meta($profile_id, 'profile_photo_id', $targetFile);
										$datebook_get_data['profile_photo_id'] = $targetFile;
										// Update the post meta
										$profile_personal_data_updated = 1;
									}


									// Retrieve default image to show after uploading
									$thumbnail_url = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$default_thumbnail_show['format']]['width'] . 'x' . $datebook_image_sizes[$default_thumbnail_show['format']]['height']) . '.jpg';//$extension;
									$thumbnail_url_blur = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes[$default_thumbnail_show['format']]['width'] . 'x' . $datebook_image_sizes[$default_thumbnail_show['format']]['height'] . '-blur') . '.jpg';//$extension;
									if (!file_exists($targetPath . '/' . $thumbnail_url)) {

										$image = wp_get_image_editor($filename);
										if ( ! is_wp_error( $image ) ) {
											$image->resize($datebook_image_sizes[$default_thumbnail_show['format']]['width'], $datebook_image_sizes[$default_thumbnail_show['format']]['height'], $default_thumbnail_show['crop']);

											if($enable_watermark == 1 && $default_thumbnail_show['watermark']){
												$image->add_watermark($datebook_image_sizes[$default_thumbnail_show['format']]['width'], $datebook_image_sizes[$default_thumbnail_show['format']]['height']);
											}
											$image->save($targetPath . '/' . $thumbnail_url);

											// Create and blur a new image
											if($blur_variant > 0){
												$image->save($targetPath . '/' . $thumbnail_url_blur);
												$image->add_blur($targetPath . '/' . $thumbnail_url_blur);
											}
										}
									}
								
									list($width, $height, $type, $attr) = getimagesize($targetPath . '/' . $thumbnail_url);

									// Retrieve big image to show after uploading
									$big_thumbnail_url = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes['image_big']['width'] . 'x' . $datebook_image_sizes['image_big']['height']) . '.jpg';//$extension;
									$big_thumbnail_url_blur = DateBook_Utilities::datebook_encode($generate_picName . '-' . $datebook_image_sizes['image_big']['width'] . 'x' . $datebook_image_sizes['image_big']['height'] . '-blur') . '.jpg';//$extension;
									if (!file_exists($targetPath . '/' . $big_thumbnail_url)) {

										$image = wp_get_image_editor($filename);
										if ( ! is_wp_error( $image ) ) {
											$image->resize($datebook_image_sizes['image_big']['width'], $datebook_image_sizes['image_big']['height'], false);
											if($enable_watermark == 1){
												$image->add_watermark($datebook_image_sizes['image_big']['width'], $datebook_image_sizes['image_big']['height']);
											}
											$image->save($targetPath . '/' . $big_thumbnail_url);

											// Create and blur a new image
											if($blur_variant > 0){
												$image->save($targetPath . '/' . $big_thumbnail_url_blur);
												$image->add_blur($targetPath . '/' . $big_thumbnail_url_blur);
											}
										}
									}


									$postvals['success'] = 1; // 1 - success, 0 - error
									$postvals['imgid'] = $attach_id;
									$postvals['imgbig'] = $targetURL . '/' . $big_thumbnail_url;
									$postvals['imgurl'] = $targetURL . '/' . $thumbnail_url;

									$postvals['width'] = $width;
									$postvals['height'] = $height;

									$postvals['datebook_get_data'] = isset($datebook_get_data) && !empty($datebook_get_data) ? $datebook_get_data : '';

									$postvals['successtext'] = '<div class="alert alert-success">'. esc_html__( 'Your image has been uploaded successfully!', 'datebook' ).'</div>';

								} else {

									$postvals['success'] = 0; // 1 - success, 0 - error
									$postvals['imgid'] = '';
									$postvals['imgbig'] = '';
									$postvals['imgurl'] = '';
									$postvals['width'] = '';
									$postvals['height'] = '';
									$postvals['datebook_get_data'] = 0;
									$postvals['successtext'] = '<div class="alert alert-warning">' . $uploaded_file['error'] . '</div>';

								}
							}
						}
					}
				}


			} else {

				$postvals['success'] = 0; // 1 - success, 0 - error
				$postvals['imgid'] = '';
				$postvals['imgbig'] = '';
				$postvals['imgurl'] = '';
				$postvals['width'] = '';
				$postvals['height'] = '';
				$postvals['datebook_get_data'] = 0;
				$postvals['successtext'] = '<div class="alert alert-warning">' . esc_html__( 'Oops! Something went wrong. We cannot detect your profile ID', 'datebook' ) . '</div>';

			}
			
			// Post meta updated
			if($profile_personal_data_updated == 1){
				update_post_meta($profile_id, 'profile_personal_data', $datebook_get_data);
			}

			return $postvals;

		}
	}


	/**
	 * Show thumbnail of profile
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function datebook_profile_thumbnail($profile_id, $thumbsize, $gender, $crop, $datebook_get_data = '', $search_default_thumbnail = 0) {

		global $datebook_image_sizes;
		
		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

		$profile_id = absint($profile_id);
		if($profile_id == 0){
			$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );
		}

		$profile = get_post($profile_id);
		$profile_user_id = isset($profile->post_author) && $profile->post_author > 0 ? $profile->post_author : 0;
		$currentauth = get_userdata($profile_user_id);

		// Get profile data
		if(empty($datebook_get_data)){
			$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
			$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();
		}

		$upload_folder = isset($datebook_get_data['upload_folder']) ? $datebook_get_data['upload_folder'] : '';

		$upload_dir = wp_upload_dir();

		$targetURL = $upload_dir['baseurl'] . '/' . $upload_folder;
		$targetPath = $upload_dir['basedir'] . '/' . $upload_folder;
		if ( ! file_exists( $targetPath ) ) {
			wp_mkdir_p( $targetPath );
		}

		$can_see_images_array = self::who_can_see_my_images($current_user_id, $currentauth, $profile_id, $datebook_get_data);
		$can_see_images = $can_see_images_array['allow'];
		$can_see_images_text = $can_see_images_array['text'];

		$blur_variant = self::$datebook_options['blur_variant'] > 0 ? self::$datebook_options['blur_variant'] : 0;

		$thumbnail_url = array();


		if($crop == true) {
			$crop = true;
		} else {
			$crop = false;
		}

		$thumbsize = isset($thumbsize) && !empty($thumbsize) ? $thumbsize : 'image_medium';

		$thumb_noimage_name = str_replace('_','-', $thumbsize);

		if ($gender == 1) {
			$gender_img = '-f';
		} else if ($gender == 2) {
			$gender_img = '-m';
		} else {
			$gender_img = '-m';
		}


		$no_thumbnail = DATEBOOK_URL . 'assets/images/no-' . $thumb_noimage_name . '' . $gender_img . '.png';
		$no_thumbnail_blur = DATEBOOK_URL . 'assets/images/no-blur-image/no-blur-' . $thumb_noimage_name . '' . $gender_img . '-1.jpg';
		
		if($can_see_images == 0){
			
			global $wp_filesystem;

			$assets_blur_folder = DATEBOOK_DIR . 'assets/images/no-blur-image/';
			if(!function_exists('WP_Filesystem')){
				require_once(ABSPATH . 'wp-admin/includes/file.php');
			}
			
			WP_Filesystem();

			$filelist = $wp_filesystem->dirlist($assets_blur_folder);

			foreach($filelist as $i => $file){
				$pos = strpos($file['name'], $thumb_noimage_name . $gender_img);
				if ($pos !== false){
					$no_blur_image_array[] = $file['name'];
				}
			}

			if(is_array($no_blur_image_array) && !empty($no_blur_image_array)){

				$no_image_rand = $no_blur_image_array[ rand( 0, ( sizeof($no_blur_image_array) -1 ) ) ];

				$no_thumbnail_blur = DATEBOOK_URL . 'assets/images/no-blur-image/' . $no_image_rand;

			}

		}

		add_filter( 'wp_image_editors', function( $editors ) {
		require_once DATEBOOK_DIR . 'includes/class-datebook-watermark.php';
		if ( ! is_array( $editors ) ) return $editors; //someone broke the filtered value
			array_unshift( $editors, 'DateBook_Watermark');
			return $editors;
		});

		$thumb_width = $datebook_image_sizes[$thumbsize]['width'];
		$thumb_height = $datebook_image_sizes[$thumbsize]['height'];


		// Get profile photo set as default
		$profile_photo_id = isset($datebook_get_data['profile_photo_id']) ? $datebook_get_data['profile_photo_id'] : '';


		$profile_photo_id_parse = explode('/', $profile_photo_id);
		$profile_photo_id = count($profile_photo_id_parse) > 1 ? $profile_photo_id_parse[1] : $profile_photo_id_parse[0];

		// Check if default photo set
		if ($profile_photo_id != ''){

			$photo_url = explode('.', $profile_photo_id);

			$thumbnail_url['img_name_ext'] = DateBook_Utilities::datebook_encode($photo_url[0] . '-' . $thumb_width . 'x' . $thumb_height) . '.' . strtolower($photo_url[1]);
			$thumbnail_url['img_blur_ext'] = DateBook_Utilities::datebook_encode($photo_url[0] . '-' . $thumb_width . 'x' . $thumb_height . '-blur') . '.' . strtolower($photo_url[1]);

			// Check if thumbnail exists
			if (!file_exists($targetPath . '/' . $thumbnail_url['img_name_ext'])) {

				// Check if original big image exists
				if (!file_exists($targetPath . '/' . $profile_photo_id)) {

					$thumbnail_url['image_exists'] = 'no';
					$thumbnail_url['img_full_url'] = $no_thumbnail;
					$thumbnail_url['img_blur_url'] = $no_thumbnail_blur;

				} else {

					// Create thumbnail of original big image
					$image = wp_get_image_editor($targetPath . '/' . $profile_photo_id);

					if ( ! is_wp_error( $image ) ) {
						$image->resize( $thumb_width, $thumb_height, $crop );
						$image->save($targetPath . '/' . $thumbnail_url['img_name_ext'] );

						// Create and blur a new image
						if($blur_variant > 0){
							$image->save($targetPath . '/' . $thumbnail_url['img_blur_ext'] );
							$image->add_blur($targetPath . '/' . $thumbnail_url['img_blur_ext'] );
						}
					}

					$thumbnail_url['image_exists'] = 'yes';
					$thumbnail_url['img_full_url'] = $targetURL . '/' . $thumbnail_url['img_name_ext'];
					$thumbnail_url['img_full_uri'] = $targetPath . '/' . $thumbnail_url['img_name_ext'];
					
					$thumbnail_url['img_blur_url'] = $targetURL . '/' . $thumbnail_url['img_blur_ext'];
					$thumbnail_url['img_blur_uri'] = $targetPath . '/' . $thumbnail_url['img_blur_ext'];

				}

			} else {

				if ($can_see_images == 0 && $blur_variant > 0 && !file_exists($targetPath . '/' . $thumbnail_url['img_blur_ext'])) {

					// Create thumbnail of original big image
					$image = wp_get_image_editor($targetPath . '/' . $profile_photo_id);

					if ( ! is_wp_error( $image ) ) {
						$image->resize( $thumb_width, $thumb_height, $crop );
						// Create and blur a new image
						if($blur_variant > 0){
							$image->save($targetPath . '/' . $thumbnail_url['img_blur_ext'] );
							$image->add_blur($targetPath . '/' . $thumbnail_url['img_blur_ext'] );
						}
					}
				}

				$thumbnail_url['image_exists'] = 'yes';
				$thumbnail_url['img_full_url'] = $targetURL . '/' . $thumbnail_url['img_name_ext'];
				$thumbnail_url['img_full_uri'] = $targetPath . '/' . $thumbnail_url['img_name_ext'];

				$thumbnail_url['img_blur_url'] = $targetURL . '/' . $thumbnail_url['img_blur_ext'];
				$thumbnail_url['img_blur_uri'] = $targetPath . '/' . $thumbnail_url['img_blur_ext'];

				list($thumb_width, $thumb_height) = getimagesize($targetPath . '/' . $thumbnail_url['img_name_ext']);

			}

			$thumbnail_url['image_exists'] = ($can_see_images == 1 ? $thumbnail_url['image_exists'] : ($blur_variant > 0 ? $thumbnail_url['image_exists'] : 'no'));
			$thumbnail_url['img_full_url'] = ($can_see_images === 1 ? $thumbnail_url['img_full_url'] : ($blur_variant > 0 ? $thumbnail_url['img_blur_url'] : $no_thumbnail_blur));
			$thumbnail_url['img_blur_url'] = ($blur_variant > 0 ? $thumbnail_url['img_blur_url'] : $no_thumbnail_blur);

		} else {

			global $wpdb;

			if ($search_default_thumbnail == 0) {

				$profile_photo_id = $wpdb->get_var($wpdb->prepare("
				SELECT `post_title` 
				FROM `".$wpdb->posts."` as wp_posts 
				INNER JOIN `".$wpdb->postmeta."` as wp_postmeta ON wp_posts.ID = wp_postmeta.post_id 
				WHERE wp_posts.post_parent = %d AND ( wp_postmeta.meta_key = %s AND wp_postmeta.meta_value = %s ) AND wp_posts.post_type = 'attachment' AND (wp_posts.post_status = 'inherit') 
				GROUP BY wp_posts.ID 
				ORDER BY wp_posts.ID ASC LIMIT 1", $profile_id, DATEBOOK_IMAGE_TYPE, DATEBOOK_PROFILE_IMAGE_TYPE));

			}

			if (isset($profile_photo_id) && strlen(($profile_photo_id)) > 0) {

				$photo_url = explode('.', $profile_photo_id);

				$thumbnail_url['img_name_ext'] = DateBook_Utilities::datebook_encode($photo_url[0] . '-' . $thumb_width . 'x' . $thumb_height) . '.' . strtolower($photo_url[1]);
				$thumbnail_url['img_blur_ext'] = DateBook_Utilities::datebook_encode($photo_url[0] . '-' . $thumb_width . 'x' . $thumb_height . '-blur') . '.' . strtolower($photo_url[1]);

				if (!file_exists($targetPath . '/' . $thumbnail_url['img_name_ext'])){
					$image = wp_get_image_editor($targetPath . '/' . $profile_photo_id);
					if ( ! is_wp_error($image)){
						$image->resize($thumb_width, $thumb_height, $crop);
						$image->save($targetPath . '/' . $thumbnail_url['img_name_ext']);

						// Create and blur a new image
						if($blur_variant > 0){
							$image->save($targetPath . '/' . $thumbnail_url['img_blur_ext']);
							$image->add_blur($targetPath . '/' . $thumbnail_url['img_blur_ext']);
						}
					}

				}

				$datebook_get_data['profile_photo_id'] = $profile_photo_id;

				// Update the post meta
				update_post_meta($profile_id, 'profile_personal_data', $datebook_get_data);
				update_post_meta($profile_id, 'profile_photo_id', $profile_photo_id);

				set_post_thumbnail($profile_id, $profile_photo_id);


				if (file_exists($targetPath . '/' . $thumbnail_url['img_name_ext'])) {

					$thumbnail_url['image_exists'] = 'yes';
					$thumbnail_url['img_full_url'] = $targetURL . '/' . $thumbnail_url['img_name_ext'];
					$thumbnail_url['img_full_uri'] = $targetPath . '/' . $thumbnail_url['img_name_ext'];

					$thumbnail_url['img_blur_url'] = $targetURL . '/' . $thumbnail_url['img_blur_ext'];
					$thumbnail_url['img_blur_uri'] = $targetPath . '/' . $thumbnail_url['img_blur_ext'];

					list($thumb_width, $thumb_height) = getimagesize($targetPath . '/' . $thumbnail_url['img_name_ext']);

				} else {
					
					$thumbnail_url['image_exists'] = 'no';
					$thumbnail_url['img_full_url'] = $no_thumbnail;
					$thumbnail_url['img_blur_url'] = $no_thumbnail_blur;

				}

				$thumbnail_url['image_exists'] = ($can_see_images == 1 ? $thumbnail_url['image_exists'] : ($blur_variant > 0 ? $thumbnail_url['image_exists'] : 'no'));
				$thumbnail_url['img_full_url'] = ($can_see_images == 1 ? $thumbnail_url['img_full_url'] : ($blur_variant > 0 ? $thumbnail_url['img_blur_url'] : $no_thumbnail_blur));
				$thumbnail_url['img_blur_url'] = ($blur_variant > 0 ? $thumbnail_url['img_blur_url'] : $no_thumbnail_blur);

			} else {

				$thumbnail_url['image_exists'] = 'no';
				$thumbnail_url['img_full_url'] = $no_thumbnail;
				$thumbnail_url['img_blur_url'] = $no_thumbnail_blur;

			}

		}

		$thumbnail_url['width'] = $thumb_width;
		$thumbnail_url['height'] = $thumb_height;


		// Retina Image
		if(isset($photo_url) && self::$datebook_options['enable_retina_images'] == '1') {

			if (file_exists($targetPath . '/' . $profile_photo_id)) {

				// Get size of original image
				list($orig_thumb_width, $orig_thumb_height) = getimagesize($targetPath . '/' . $profile_photo_id);

				// Create retina 2x size
				$retina_thumbnail_url = DateBook_Utilities::datebook_encode($photo_url[0] . '-' . $datebook_image_sizes[$thumbsize]['width'] . 'x' . $datebook_image_sizes[$thumbsize]['height']) . '@2x.' . strtolower($photo_url[1]);
				$retina_thumbnail_url_blur = DateBook_Utilities::datebook_encode($photo_url[0] . '-' . $datebook_image_sizes[$thumbsize]['width'] . 'x' . $datebook_image_sizes[$thumbsize]['height'] . '-blur') . '@2x.' . strtolower($photo_url[1]);

				if (!file_exists($targetPath . '/' . $retina_thumbnail_url)){
					$image = wp_get_image_editor($targetPath . '/' . $photo_url[0] . '.' . strtolower($photo_url[1]));
					if (!is_wp_error($image)){
						$thumb_width_r2 = $datebook_image_sizes[$thumbsize]['width'] * 2;
						$thumb_height_r2 = $datebook_image_sizes[$thumbsize]['height'] * 2;

						// Compare original image to retina sizes
						$thumb_width_r2 = $orig_thumb_width < $thumb_width_r2 ? $orig_thumb_width : $thumb_width_r2;
						$thumb_height_r2 = $orig_thumb_height < $thumb_height_r2 ? $orig_thumb_height : $thumb_height_r2;

						$image->resize($thumb_width_r2, $thumb_height_r2, $crop);
						$image->save($targetPath . '/' . $retina_thumbnail_url);

						// Create and blur a new image
						if($blur_variant > 0){
							$image->save($targetPath . '/' . $retina_thumbnail_url_blur);
							$image->add_blur($targetPath . '/' . $retina_thumbnail_url_blur);
						}
					}
				}

				// Create retina 1.5x size
				$retina_thumbnail_url_15 = DateBook_Utilities::datebook_encode($photo_url[0] . '-' . $datebook_image_sizes[$thumbsize]['width'] . 'x' . $datebook_image_sizes[$thumbsize]['height']) . '@1.5x.' . strtolower($photo_url[1]);
				$retina_thumbnail_url_blur_15 = DateBook_Utilities::datebook_encode($photo_url[0] . '-' . $datebook_image_sizes[$thumbsize]['width'] . 'x' . $datebook_image_sizes[$thumbsize]['height'] . '-blur') . '@1.5x.' . strtolower($photo_url[1]);

				if (!file_exists($targetPath . '/' . $retina_thumbnail_url_15)){
					$image = wp_get_image_editor($targetPath . '/' . $photo_url[0] . '.' . strtolower($photo_url[1]));
					if (!is_wp_error($image)){

						$percentage = 50;
						$thumb_width_r15 = round(($percentage / 100) * $datebook_image_sizes[$thumbsize]['width'] + $datebook_image_sizes[$thumbsize]['width']);
						$thumb_height_r15 = round(($percentage / 100) * $datebook_image_sizes[$thumbsize]['height'] + $datebook_image_sizes[$thumbsize]['height']);

						// Compare original image to retina sizes
						$thumb_width_r15 = $orig_thumb_width < $thumb_width_r15 ? $orig_thumb_width : $thumb_width_r15;
						$thumb_height_r15 = $orig_thumb_height < $thumb_height_r15 ? $orig_thumb_height : $thumb_height_r15;

						$image->resize($thumb_width_r15, $thumb_height_r15, $crop);
						$image->save($targetPath . '/' . $retina_thumbnail_url_15);

						// Create and blur a new image
						if($blur_variant > 0){
							$image->save($targetPath . '/' . $retina_thumbnail_url_blur_15);
							$image->add_blur($targetPath . '/' . $retina_thumbnail_url_blur_15);
						}
					}
				}

				// Create retina 1.25x size
				$retina_thumbnail_url_125 = DateBook_Utilities::datebook_encode($photo_url[0] . '-' . $datebook_image_sizes[$thumbsize]['width'] . 'x' . $datebook_image_sizes[$thumbsize]['height']) . '@1.25x.' . strtolower($photo_url[1]);
				$retina_thumbnail_url_blur_125 = DateBook_Utilities::datebook_encode($photo_url[0] . '-' . $datebook_image_sizes[$thumbsize]['width'] . 'x' . $datebook_image_sizes[$thumbsize]['height'] . '-blur') . '@1.25x.' . strtolower($photo_url[1]);

				if (!file_exists($targetPath . '/' . $retina_thumbnail_url_125)){
					$image = wp_get_image_editor($targetPath . '/' . $photo_url[0] . '.' . strtolower($photo_url[1]));
					if (!is_wp_error($image)){

						$percentage = 25;
						$thumb_width_r125 = round(($percentage / 100) * $datebook_image_sizes[$thumbsize]['width'] + $datebook_image_sizes[$thumbsize]['width']);
						$thumb_height_r125 = round(($percentage / 100) * $datebook_image_sizes[$thumbsize]['height'] + $datebook_image_sizes[$thumbsize]['height']);

						// Compare original image to retina sizes
						$thumb_width_r125 = $orig_thumb_width < $thumb_width_r125 ? $orig_thumb_width : $thumb_width_r125;
						$thumb_height_r125 = $orig_thumb_height < $thumb_height_r125 ? $orig_thumb_height : $thumb_height_r125;

						$image->resize($thumb_width_r125, $thumb_height_r125, $crop);
						$image->save($targetPath . '/' . $retina_thumbnail_url_125);

						// Create and blur a new image
						if($blur_variant > 0){
							$image->save($targetPath . '/' . $retina_thumbnail_url_blur_125);
							$image->add_blur($targetPath . '/' . $retina_thumbnail_url_blur_125);
						}
					}
				}
			}
		}

		return $thumbnail_url;

	}


	/**
	 * Get last part of URL - profile slug
	 *
	 * @access private
	 */
	public static function detect_post_slug($post_type) {

		global $post;

		$profile_id = isset($post->ID) ? $post->ID : 0 ;
		$profile_type = isset($post->post_type) ? $post->post_type : '';

		if(isset($profile_id) > 0 && isset($profile_type) && ($profile_type == DATEBOOK_POST_TYPE || $profile_type == DATEBOOK_CLASSIFIEDS_TYPE)){

			$profile_data = $post;

		} else {

			$basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
			$uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
			if (strstr($uri, '?')) $uri = substr($uri, 0, strpos($uri, '?'));
			$profile_slug = basename(trim($uri, '/'));

			$post_type_defined = '';

			if(isset($post_type) && $post_type == DATEBOOK_POST_TYPE){
				$post_type_defined = DATEBOOK_POST_TYPE;
			} else if(isset($post_type) && DATEBOOK_CLASSIFIEDS_TYPE){
				$post_type_defined = DATEBOOK_CLASSIFIEDS_TYPE;
			}

			$profile_data = get_page_by_path($profile_slug, OBJECT, $post_type_defined);

		}

		return $profile_data;

	}


	/**
	 * Create url of text
	 * 
	 * @since 1.6
	 * @access public
	 */
	public static function datebook_slugify($text) {
		
		// replace non letter or digits by -
		$text = preg_replace('~[^\pL\d]+~u', '-', $text);
		
		$text = utf8_encode($text);
		
		// transliterate
		$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text, PHP_EOL);

		// remove unwanted characters
		$text = preg_replace('~[^-\w]+~', '', $text);
		
		// remove duplicate -
		$text = preg_replace('~-+~', '-', $text);

		// lowercase
		$text = strtolower($text);

		// trim
		$text = trim($text, '-');

		if (empty($text)) {
			return 'n-a';
		}

		return $text;

	}


	/**
	 * Create slug of text - different variant
	 * 
	 * @since 1.6
	 * @access public
	 */
	public static function datebook_makeslug($text) {

		$text = strtolower($text);

		$text = strip_tags($text);

		$text = stripslashes($text);

		$text = html_entity_decode($text);

		$text = preg_replace('/[^a-z0-9]+/', '-', $text);

		$text = str_replace(array('\'', '039'), '', $text);

		$text = trim($text, '-');

		if (empty($text)) {
			return;
		}
		
		return $text;
		
	}


	/**
	 * Create formatted text for price, currency code and currency symbol
	 * 
	 * @since 1.8
	 * @access public
	 */
	public static function datebook_spellplural($num, $one, $many) {
						
	    if ($num > 1){
	        return $many;
		} else {
			return $one;
		}

	}


	/**
	 * Create formatted text for days
	 * 
	 * @since 1.8
	 * @access public
	 */
	public static function datebook_plural_text($period_number, $period_title) {

		switch ( $period_title ) {

			case 1 : 
				$one = esc_html__( 'minute', 'datebook' ); 
				$many = esc_html__( 'minutes', 'datebook' ); 
				break;
			case 2 : 
				$one = esc_html__( 'hour', 'datebook' ); 
				$many = esc_html__( 'hours', 'datebook' ); 
				break;
			case 3 : 
				$one = esc_html__( 'day', 'datebook' ); 
				$many = esc_html__( 'days', 'datebook' ); 
				break;
			case 4 : 
				$one = esc_html__( 'week', 'datebook' ); 
				$many = esc_html__( 'weeks', 'datebook' ); 
				break;
			case 5 : 
				$one = esc_html__( 'month', 'datebook' ); 
				$many = esc_html__( 'months', 'datebook' ); 
				break;
			case 6 : 
				$one = esc_html__( 'year', 'datebook' ); 
				$many = esc_html__( 'years', 'datebook' ); 
				break;

		}

		$period_text = $period_number . ' ' . self::datebook_spellplural($period_number, $one, $many);

		return $period_text;
		
	}


	/**
	 * Show "New" label on the Profile
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function datebook_new_profile_labels($date) {
		
		$days_to_show_label = self::$datebook_options['new_label_days'] ? absint(self::$datebook_options['new_label_days']) : 7; // New label shown for 7 days if not set in Admin Dashboard

		$new_profile_label = '';

		$daysago = strtotime('-' . $days_to_show_label . ' days');
		
		$date = strtotime($date);
		
		if ($date > $daysago) {
			$new_profile_label .= '<span class="badge badge-info light-blue darken-2 shadow-none datebook-new-label" title="' . sprintf( esc_html__( 'Joined within %s days', 'datebook' ), $days_to_show_label ) . '">'.esc_html__( 'New', 'datebook' ).'</span>';

		}

		return $new_profile_label;

	}


	/**
	 * Create random color
	 * 
	 * @since 3.6
	 * @access public
	 */
	public static function create_random_color($color_hex, $color_gamma) {

		if($color_hex){

			$out = $color_hex;

		} else {
			
			if(isset($color_gamma) && $color_gamma == 'light'){
				$color_gamma_array = array('125' , '255');
			} else if(isset($color_gamma) && $color_gamma == 'dark'){
				$color_gamma_array = array('0', '125');
			} else {
				$color_gamma_array = array('0', '255');
			}

			$out = '#';

			for($o = 1; $o <= 3; $o++){
				$out .= str_pad( dechex( mt_rand( $color_gamma_array[0], $color_gamma_array[1] ) ), 2, '0', STR_PAD_LEFT);
			}
		}

		return $out;
	}


	/**
	 * Count all activated profiles and show amount in the Primary menu
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function count_all_profiles($shortcode, $style = '', $size = 0) {

		$profiles_count = wp_count_posts( 'profile' )->publish;

		if($shortcode == 1){

			$out = '';

			$split_number = str_split($profiles_count);

			for($i = 0; $i < count($split_number); $i++){

				if(isset($style) && ($style == 'light' || $style == 'dark')){
					$style_out = ' style="color: ' . self::create_random_color('', $style) . ' !important;"';
				} else {
					$style_out = '';
				}

				$out .= '<span' . $style_out . '>' . $split_number[$i] . '</span>';
			}

		} else {

			$out = $profiles_count;

		}

		return $out;
		
	}


	/**
	 * Count all comments on someone's profile and show amount on the Profile's comment
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function datebook_count_profile_comments($profile_id) {

		$profile_id = absint($profile_id);
		
		$args = array(
				'orderby' => 'comment_date_gmt',
				'order' => 'DESC',
				'post_id' => $profile_id,
				'status'  => 'approve',
				'meta_key' => 'comment_type',
				'meta_value' => DATEBOOK_COMMENT_TYPE,
				'count' => true //return only the count
		);

		$comments_count = get_comments($args);
	
		return $comments_count;

	}


	/**
	 * Count all reviews on someone's profile and show amount on the Profile's reviews
	 * 
	 * @since 3.7
	 * @access public
	 */
	public static function datebook_count_profile_reviews($profile_id) {

		$profile_id = absint($profile_id);
		
		$args = array(
				'orderby' => 'comment_date_gmt',
				'order' => 'DESC',
				'post_id' => $profile_id,
				'status'  => 'approve',
				'meta_key' => 'comment_type',
				'meta_value' => DATEBOOK_REVIEW_TYPE,
				'count' => true //return only the count
		);

		$comments_count = get_comments($args);
	
		return $comments_count;

	}


	/**
	 * Check if genders must pay for subscription
	 *
	 * @access private
	 * @return void
	 */
	private static function check_if_genders_must_not_pay_global(){

		$genders_must_not_pay = 0;
		
		if (is_user_logged_in()) {

			// Check if genders selected who must pay for a subscription plan
			$get_free_for_genders = self::$datebook_options['free_for_genders'];

			if (is_array($get_free_for_genders) && !empty($get_free_for_genders)){

				if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
					$current_user_id = DATEBOOK_CURRENT_USER_ID;
				} else {
					global $current_user;
					wp_get_current_user();
					$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
				}

				$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );

				$gender = get_post_meta($profile_id, 'gender', true);

				foreach($get_free_for_genders as $key => $value){
					if($gender == $key && $value == 1){
						$genders_must_not_pay += 1;
					}
				}
			}
		}

		return $genders_must_not_pay;

	}


	/**
	 * Check if the user has validated his email by clicking the validation link
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function process_check_validated_email() {

		if (isset($_GET['verifyemail'])) {
			
			global $wpdb, $datebook_user_info;

			$verifyemail = preg_replace("/([^a-zA-Z0-9])/", '', $_GET['verifyemail']);

			if($verifyemail == 'activationkeybyadmin' && isset($_GET['action']) && $_GET['action'] == 'activatedemailbyadmin' && is_super_admin()){

				if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
					$current_user_id = DATEBOOK_CURRENT_USER_ID;
				} else {
					global $current_user;
					wp_get_current_user();
					$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
				}

			} else {

				$current_user_id = $wpdb->get_var($wpdb->prepare("SELECT `user_id` FROM `".$wpdb->usermeta."` WHERE `meta_key` = 'emailhash' AND `meta_value` = '%s' LIMIT 1", $verifyemail));

			}

			// Detect page ID
			$page_id = get_the_ID();

			// If ID of page is not detected then detect it with another method
			if(isset($page_id) && $page_id > 0){
				$page_id = $page_id;
			} else {
				$url = add_query_arg(array());
				$page_id = url_to_postid($url);
			}

			$profile_get_permalink = get_permalink($page_id);

			if (isset($current_user_id) && $current_user_id > 0) {

				$user_type = get_user_meta( $current_user_id, 'profile_type', true );

				if ($user_type == DATEBOOK_POST_TYPE) {

					delete_user_meta( $current_user_id, 'emailhash' );

					$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );
					
					$profile_get_permalink = get_permalink($profile_id);
					
					// Check if Payment and Subscription are activated
					$plans_count = $subscribe_invisible = $default_subscription_plan = 0;

					$post_status = 'publish';

					if (self::$datebook_options['activate_manual_new_profile'] == '1') {

						$post_status = 'private';

					} else {

						// Check if Payment and Subscription are activated

						if (self::check_if_gateway_activated()) {

							// Get Subscription plans
							$get_subscription_plans = get_option('datebook_subscription_plans');

							if (is_array($get_subscription_plans)){

								foreach($get_subscription_plans as $key => $value){

									if (isset($value['active']) && $value['active'] == 1) {

										$plans_count++;

										if (isset($value['activate_by_default']) && $value['activate_by_default'] == 1) {

											$subscribe_invisible++;

											$default_subscription_plan = $value['subscription_id'];

										}
									}
								}
							}
						}
						
						// Check if user has a subscription
						$get_subsciption_status = DateBook_Profile_Subscription::get_subsciption_status($current_user_id);

						if ($plans_count > 0 && isset($get_subsciption_status) && $get_subsciption_status != 'active'){

							// If subscription plan exists then do not publish profile
							$post_status = 'private';

						} else {

							// If subscription plan does not exist then publish profile
							$post_status = 'publish';

						}
					
					}


					// Login after registration
					if (!is_user_logged_in()) {
						//delete the cookies of the user if he is already logged in. for example if he is the admin
						wp_clear_auth_cookie();
						//add login cookies to the user so we can indentify him
						wp_set_auth_cookie($current_user_id, true, '');
						
						// Remember when user logged in
						$activity_time = strtotime(gmdate( 'Y-m-d H:i:s' ) . ' GMT');
						update_user_meta($current_user_id, 'login_time', $activity_time);
					}
					
					$redirect_profile = $profile_get_permalink;

					// Get personal data
					$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
					$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();
					
					// 2. Check a profile completed
					$profile_must_complete = 1;
					if(isset(self::$datebook_options['user_must_complete_profile']) && self::$datebook_options['user_must_complete_profile'] == '1'){
						$profile_must_complete = isset($datebook_get_data['profile_must_complete']) && $datebook_get_data['profile_must_complete'] == 1 ? 1 : 0;

						$redirect_profile = add_query_arg( array(
							'message' => 'mustcompleteprofile',
							'stop' => 1,
						), get_permalink(self::$datebook_options['my_edit_profile_page']) );
					}

					// 1. Check a profile has a photo
					$profile_photo_id = 'yes';
					if(self::$datebook_options['user_must_upload_photo'] == '1'){
						$profile_photo_id = isset($datebook_get_data['profile_photo_id']) ? $datebook_get_data['profile_photo_id'] : '';
						$profile_photo_id_parse = explode('/', $profile_photo_id);
						$profile_photo_id = count($profile_photo_id_parse) > 1 ? $profile_photo_id_parse[1] : $profile_photo_id_parse[0];
						
						$redirect_profile = add_query_arg( array(
							'message' => 'mustuploadphoto',
							'stop' => 1,
						), get_permalink(self::$datebook_options['my_photos_page']) );
					}

					// Send plan by POST and subscribe a new registered user
					if($profile_photo_id != '' && $profile_must_complete == 1){

						$post_profile = array( 'ID' => $profile_id, 'post_status' => $post_status );
						wp_update_post( $post_profile );


						// Insert location counter after user validated his email
						if($post_status == 'publish'){
						
							$table_countries = strtolower($wpdb->prefix) . 'datebook_countries';

							$get_profile_city = get_post_meta($profile_id, 'city', true);

							if(isset($get_profile_city) && $get_profile_city > 0){

								// increment counts in counter in city
								$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $get_profile_city) );

							}

							$get_profile_region = get_post_meta($profile_id, 'region', true);

							if(isset($get_profile_region) && $get_profile_region > 0){

								// increment counts in counter in region
								$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $get_profile_region) );

							}

							$get_profile_country = get_post_meta($profile_id, 'country', true);

							if(isset($get_profile_country) && $get_profile_country > 0){

								// increment counts in counter in country
								$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter + 1 WHERE id = %d", $get_profile_country) );

							}

							// if admin activates email then do not send email to user
							if($verifyemail != 'activationkeybyadmin' && !isset($_GET['action']) && !is_super_admin()){

								$datebook_user_info = get_userdata($current_user_id);

								$to_email = $datebook_user_info->user_email;

								// Put all data to an array
								$datebook_email_var = array(
									'profile_name' => $datebook_user_info->display_name,
									'user_login' => $datebook_user_info->user_login,
									'emailaddress' => $datebook_user_info->user_email,
									'profile_get_permalink' => $profile_get_permalink
								);

								set_query_var( 'datebook_email_var', $datebook_email_var );

								// Send email to profile
								$select_email_template = 'profile_activated_to_profile';

								include DateBook_Template_Loader::locate( 'misc/email-templates' );

							
								$subject_in_email = esc_html__( 'Welcome to', 'datebook' ) . ' ' . self::$datebook_options['email_sitename'];

								self::datebook_email_send(NULL, NULL, $to_email, $subject_in_email, $body);

								// Send email to Admin
								if (self::$datebook_options['email_when_activate_profile'] == '1') {

									// Email
									$to_email = self::$datebook_options['email_website'] ? self::$datebook_options['email_website'] : get_bloginfo('admin_email');

									// Subject
									$subject_in_email = esc_html__('New profile has been activated', 'datebook');

									// Message
									$body = esc_html__( 'Hello', 'datebook' ) . ', ' . esc_html__( 'Admin', 'datebook' ) . '!<br /><br />';
									$body .= esc_html__( 'Profile has been activated', 'datebook' ) . '.<br /><br />';
									$body .= esc_html__( 'Profile', 'datebook' ).': <a href="' . $profile_get_permalink . '">' . $profile_get_permalink . '</a>';

									// Send email to admin
									$datebook_mail = DateBook_Utilities::datebook_email_send(NULL, NULL, $to_email, $subject_in_email, $body);

								}
							}

							// Send plan by POST and subscribe a new registered user
							if($plans_count > 0 && $subscribe_invisible > 0){
								$_POST['current_user_id'] = $current_user_id;
								$_POST['subscriptionplan'] = $default_subscription_plan;
								$_POST['subscriptionplan_period_key'] = 0;
								$_POST['subscribe_invisible'] = 1;
								$_POST['pay_gate'] = 'free';
								$_POST['action'] = 'payment_page';
								$_POST['payment_page'] = 3;
								$_POST['notredirect_to_subscription_page'] = 1;
								do_action('datebook_redirect_subscription_to_gateway');
							}
						}
					}

					$redirect_to_after_email_confirmation = self::$datebook_options['redirect_to_after_email_confirmation'] > 0 ? get_permalink(self::$datebook_options['redirect_to_after_email_confirmation']) : $redirect_profile;

					$redirect_url = add_query_arg( array(
						'message' => 'emailverified'
					), $redirect_to_after_email_confirmation );

					wp_redirect($redirect_url);
					exit;

				}

			} else {
				
				$redirect_url = add_query_arg( array(
					'message' => 'emailnotfound'
				), $profile_get_permalink );

				wp_redirect($redirect_url);
				exit;

			}

		} else if (isset($_GET['verifynewemail'])) {

			// Detect page ID
			$profile_id = get_the_ID();

			// If ID of page is not detected then detect it with another method
			if(isset($profile_id) && $profile_id > 0){
				$profile_id = $profile_id;
			} else {
				$url = add_query_arg(array());
				$profile_id = url_to_postid($url);
			}

			// Get the profile meta
			if($profile_id > 0){

				$profile_get_permalink = get_permalink($profile_id);

				$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
				$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

				// Remove email temp
				if(isset($datebook_get_data['emailaddress_temp'])){
					
					$profile = get_post($profile_id);
					$current_user_id = $profile->post_author;

					$update_user_args = array(
						'ID' => $current_user_id, 
						'user_email' => $datebook_get_data['emailaddress_temp']
					);

					// Update user email
					wp_update_user($update_user_args);

					unset($datebook_get_data['emailaddress_temp']);

					// Update the profile meta
					update_post_meta($profile_id, 'profile_personal_data', $datebook_get_data);
					
					$redirect_url = add_query_arg( array(
						'message' => 'emailverified'
					), $profile_get_permalink );
					
					wp_redirect($redirect_url);
					exit;
				}
			}
		}
	}


	/**
	 * Check if any payment gateway is activated
	 *
	 * @access public
	 * @return void
	 */
	public static function check_if_gateway_activated() {

		$gateway_by = 0;

		$activate_woocommerce_subscription = self::$datebook_options['activate_woocommerce_subscription'] == '1' ? 1 : 2;

		if($activate_woocommerce_subscription == 1){

			$item = get_option('datebook_gateways');

			if(isset($item['paypal_standard']['enabled']) && $item['paypal_standard']['enabled'] == 1){
				$gateway_by += 1;
			}
			if(isset($item['paystack']['enabled']) && $item['paystack']['enabled'] == 1){
				$gateway_by += 1;
			}
			if(isset($item['bank']['enabled']) && $item['bank']['enabled'] == 1){
				$gateway_by += 1;
			}

		} else {

			$gateway_by += 1;

		}
		
		// Check if genders must pay for a subscription plan
		if($gateway_by > 0 && self::check_if_genders_must_not_pay_global() == 1){
			return false;
		}

		if($gateway_by > 0){
			return true;
		}

		return false;

	}


	/**
	 * Check and notify the user to click the validation link
	 *
	 * @access public
	 * @return void
	 */
	public static function check_if_email_verified($current_user_id){

		$email_data = array('emailhash' => '');

		$user_must_validate_email = self::$datebook_options['user_must_validate_email'] == '1' ? 1 : 0;

		if ($user_must_validate_email == '1') {

			$email_data['emailhash'] = get_user_meta( $current_user_id, 'emailhash', true );

		}

		return $email_data;

	}


	/**
	 * Check all profile statuses and redirect to a related page: photo upload, subscription plan and etc
	 * 
	 * @since 3.4.9
	 * @access public
	 */
	public static function check_profile_statuses_in_header($page_id, $current_user_id) {

		$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );
		
		if($profile_id > 0){

			// Get Profile personal data
			$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
			$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

			// 1. Check and notify the user to click the validation link
			$user_verified_email_array = self::check_if_email_verified($current_user_id);
			
			$emailhash = isset($user_verified_email_array['emailhash']) && $user_verified_email_array['emailhash'] != '' ? 1 : 0;

			// 2. Check a profile has a photo
			$profile_photo_id = isset($datebook_get_data['profile_photo_id']) ? $datebook_get_data['profile_photo_id'] : '';
			$profile_photo_id_parse = explode('/', $profile_photo_id);
			$profile_photo_id = count($profile_photo_id_parse) > 1 ? $profile_photo_id_parse[1] : $profile_photo_id_parse[0];

			$profile_must_complete = isset($datebook_get_data['profile_must_complete']) ? $datebook_get_data['profile_must_complete'] : 0;

			$stop_redirect = $change_profile_form = 0;

			$stop = isset($_GET['stop']) && $_GET['stop'] == 1 ? 1 : 0;

			$action = '';
			if (isset($_REQUEST['action'])) {
				$action = preg_replace("/([^a-zA-Z0-9])/", '', esc_attr($_REQUEST['action']));
			}

			if (($emailhash == 1 && $page_id != self::$datebook_options['my_edit_profile_page']) || $action == 'resendactivation') {

				$stop_redirect = 1;

				if ($action == 'resendactivation') {

					$send_verification = 0;

					$currentauth = get_userdata($current_user_id);

					if (isset($_REQUEST['email'])) {

						$get_email = sanitize_email($_REQUEST['email']);

					} else if (isset($currentauth->user_email)) {

						$get_email = sanitize_email($currentauth->user_email);

					}

					if(isset($get_email) && !empty($get_email) && is_email($get_email)){

						$to_email = $get_email;

						if ( email_exists($to_email) ) {

							if (isset($currentauth->user_email) && $currentauth->user_email == $to_email) {

								$send_verification = 1;

								$to_email = $currentauth->user_email;

							} else {

								$send_verification = 0;

							}

						} else {

							$send_verification = 1;

						}

						if($send_verification == 1){

							// Update email
							$update_user_args = array(
								'ID' => $current_user_id, 
								'user_email' => $to_email
							);

							wp_update_user($update_user_args);

							$profile = get_post($profile_id);
							$profile_name = $profile->post_title;

							$select_email_template = 'activation_link_to_profile';

							$profile_get_permalink = get_permalink($profile_id);

							$emailhashkey = add_query_arg( array(
								'verifyemail' => $user_verified_email_array['emailhash']
							), $profile_get_permalink );

							include DateBook_Template_Loader::locate( 'misc/email-templates' );

							$subject_in_email = esc_html__( 'Verify your email address', 'datebook' );

							self::datebook_email_send('', '', $to_email, $subject_in_email, $body);

							$verifyemailsent = 'verifyemailsent';

						} else {

							$verifyemailsent = 'verifyemailnotsent';

						}

					} else {

						$verifyemailsent = 'verifyemailnotsent';

					}

					$redirect_my_edit_profile_page = add_query_arg( array(
						'stop' => $stop_redirect,
						'message' => $verifyemailsent,
					), get_permalink(self::$datebook_options['my_edit_profile_page']) );

					// Redirect to My profile edit page
					wp_redirect($redirect_my_edit_profile_page);

					exit();

				} else {
					
					$force_redirect_to_validate_email = self::$datebook_options['force_redirect_to_validate_email'] ? 1 : 0;

					$get_payment_page = !empty($_POST['payment_page']) ? $_POST['payment_page'] : 0;

					if (isset($_POST['action']) && $_POST['action'] == 'payment_page' && $get_payment_page == '3') {

						$get_splan = isset($_POST['subscriptionplan']) && strlen($_POST['subscriptionplan']) > 1 ? $_POST['subscriptionplan'] : 0;
						$get_splan_period_key = !empty($_POST['subscriptionplan_period_key']) ? $_POST['subscriptionplan_period_key'] : 0;
						$wp_verify_nonce = !empty($_REQUEST['datebooktkn']) ? $_REQUEST['datebooktkn'] : '';

						if ($get_splan > 0 && ( isset($wp_verify_nonce) || wp_verify_nonce( $wp_verify_nonce, 'datebook_new_subscription_form_nonce' ) )) {

							if($force_redirect_to_validate_email == 1){

								$redirect_my_edit_profile_page = add_query_arg( array(
									'stop' => $stop_redirect,
									'message' => 'mustverifyemail',
								), get_permalink(self::$datebook_options['my_edit_profile_page']) );

								// Redirect to My profile edit page
								wp_redirect($redirect_my_edit_profile_page);
								exit();

							}

						}

					} else if ($page_id != self::$datebook_options['my_edit_profile_page']) {

						if($force_redirect_to_validate_email == 1){

							$redirect_my_edit_profile_page = add_query_arg( array(
								'stop' => $stop_redirect,
								'message' => 'mustverifyemail',
							), get_permalink(self::$datebook_options['my_edit_profile_page']) );

							// Redirect to My profile edit page
							wp_redirect($redirect_my_edit_profile_page);
							exit();
							
						}
					}
				}
			}

			// User must upload photo
			if ($stop_redirect == 0 && $stop == 0 && $emailhash == 0 && self::$datebook_options['user_must_upload_photo'] == '1' && self::$datebook_options['force_redirect_user_to_upload_photo'] == '1' && $profile_photo_id == '' && $page_id != self::$datebook_options['my_photos_page']) {

				$stop_redirect = 1;

				$redirect_my_photos_page = add_query_arg( array(
					'stop' => $stop_redirect,
					'message' => 'mustuploadphoto',
				), get_permalink(self::$datebook_options['my_photos_page']) );

				// Redirect to photo page
				wp_redirect($redirect_my_photos_page);
				exit();

			}

			// User must complete profile
			if ($stop_redirect == 0 && $stop == 0 && $emailhash == 0 && self::$datebook_options['user_must_complete_profile'] == '1' && self::$datebook_options['force_redirect_user_to_complete_profile'] == '1' && $profile_must_complete == 0 && $page_id != self::$datebook_options['my_edit_profile_page']) {

				$stop_redirect = 1;

				$change_profile_form = isset($_POST['change_profile_form']) ? 1 : 0;

				// Redirect to photo page
				if($change_profile_form == 0){

					$redirect_my_edit_profile_page = add_query_arg( array(
						'stop' => $stop_redirect,
						'message' => 'mustcompleteprofile',
					), get_permalink(self::$datebook_options['my_edit_profile_page']) );

					wp_redirect($redirect_my_edit_profile_page);
					exit();

				}

			}

			// User must subscribe
			if ($stop_redirect == 0 && $stop == 0 && $emailhash == 0 && $change_profile_form == 0 && $page_id != self::$datebook_options['my_edit_profile_page'] && self::check_if_gateway_activated()){

				global $post;

				$stop_redirect = 1;

				// Check if user selected a subscription plan. Check if not subscribed users may access the Search and Profile pages
				$plans_count = $user_selected_plan = 0;

				$profile_subscription_plan = isset($datebook_get_data['profile_subscription']['plan']) ? $datebook_get_data['profile_subscription']['plan'] : '';

				$user_id = isset($post->post_author) ? $post->post_author : 0;
				$currentauth = get_userdata($user_id);

				// Get Subscription plans
				$get_subscription_plans = get_option('datebook_subscription_plans');

				if (is_array($get_subscription_plans)){

					foreach($get_subscription_plans as $key => $value){

						if (isset($value['active']) && $value['active'] == 1) {

							$plans_count++;

						}

						if ($profile_subscription_plan == $value['slug']) {

							$user_selected_plan++;

						}
					}
				}


				if ($plans_count > 0) {

					if (self::$datebook_options['force_redirect_to_subscription_page'] == 1) {

						$get_subsciption_status = DateBook_Profile_Subscription::get_subsciption_status($current_user_id);

						if ($get_subsciption_status != 'active') {

							do_action('datebook_currentuser_check_login', $page_id);

							if ($page_id != self::$datebook_options['my_upgrade_page'] && $page_id != self::$datebook_options['my_cart_page'] && $page_id != self::$datebook_options['my_checkout_page']){

								$redirect_my_upgrade_page = add_query_arg( array(
									'stop' => $stop_redirect,
									'message' => 'mustsubscribe',
								), get_permalink(self::$datebook_options['my_upgrade_page']) );

								wp_redirect($redirect_my_upgrade_page);
								exit();

							}
						}

					} else {

						$allow_notsubscribed_users = self::$datebook_options['allow_notsubscribed_users'];

						if (($page_id == self::$datebook_options['search_results_page'] && $allow_notsubscribed_users['1'] == 1) || (get_post_type() == DATEBOOK_POST_TYPE && is_single() && $allow_notsubscribed_users['2'] == 1) && (isset($currentauth->ID) && $currentauth->ID > 0 && $currentauth->ID != $current_user_id)) {

							// Get user subscription data
							$check_member_subscription = DateBook_Profile_Subscription::get_member_subsciption_data($current_user_id);

							$check_member_subscription_status = isset($check_member_subscription['status']) && $check_member_subscription['status'] == 'active' ? 1 : 0;

							if($check_member_subscription_status == 0) {

								if ($page_id != self::$datebook_options['my_upgrade_page'] && $page_id != self::$datebook_options['my_cart_page'] && $page_id != self::$datebook_options['my_checkout_page']){

									$redirect_my_upgrade_page = add_query_arg( array(
										'stop' => $stop_redirect,
										'message' => 'mustsubscribe',
									), get_permalink(self::$datebook_options['my_upgrade_page']) );

									// redirect to subscription page
									wp_redirect($redirect_my_upgrade_page);
									exit();

								}
							}

						} else if ($page_id == self::$datebook_options['registration_page']) {

							// Redirect to Custom page
							wp_redirect(get_permalink(self::$datebook_options['redirect_to_after_login']));
							exit();

						}
					}

				} else if ($page_id == self::$datebook_options['registration_page']) {

					// Redirect to Custom page
					wp_redirect(get_permalink(self::$datebook_options['redirect_to_after_login']));
					exit();

				}
			}


			// Finally redirect to this page if no confirmation is required
			/*if ($stop_redirect == 0 && $stop == 0 && $emailhash == 0 && $change_profile_form == 0) {

				// Redirect to Custom page
				if (isset($page_id) && $page_id > 0 && self::$datebook_options['registration_page'] > 0 && $page_id == self::$datebook_options['registration_page']) {
					$redirect_to_after_all = self::$datebook_options['redirect_to_after_login'];
				} else {
					$redirect_to_after_all = $profile_id;
				}

				// This redirect is not required but could help if the blank page after registration appears.
				wp_redirect(get_permalink($redirect_to_after_all));
				exit();

			}*/
		}
	}


	/**
	 * Check all profile statuses: email verification, profile published, subscription plan selected
	 * 
	 * @since 2.1
	 * @access public
	 */
	public static function process_profile_statuses() {

		if (isset($_GET['message']) && $_GET['message'] == 'emailverified') {

			echo '<div class="datebook-custom-card card"><div class="alert alert-success m-0">' . esc_html__( 'Thank you for verifying your email address', 'datebook' ) . '</div></div>';

		} else if (isset($_GET['message']) && $_GET['message'] == 'emailnotfound') {

			echo '<div class="datebook-custom-card card"><div class="alert alert-warning m-0">' . esc_html__( 'The email address you are trying to verify was not found in our database. It may already have been verified.', 'datebook' ) . '</div></div>';

		}

		if (is_user_logged_in()){
			
			$page_id = get_the_ID();

			if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
				$current_user_id = DATEBOOK_CURRENT_USER_ID;
			} else {
				global $current_user;
				wp_get_current_user();
				$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
			}

			$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );
			$profile = get_post($profile_id);
			
			if(isset($profile->ID) && $profile->ID > 0){
				
				// Display the Notification about necessity of email validation
				$pages_of_get_option = array(
					self::$datebook_options['my_edit_profile_page'], 
					self::$datebook_options['my_messages_page'], 
					self::$datebook_options['my_photos_page'], 
					self::$datebook_options['my_comments_page'], 
					self::$datebook_options['my_tours_page'], 
					self::$datebook_options['my_verification_page'], 
					self::$datebook_options['my_friends_page'], 
					self::$datebook_options['my_blacklist_page'], 
					self::$datebook_options['my_favorites_page'], 
					self::$datebook_options['my_classifieds_page'], 
					self::$datebook_options['my_views_page'], 
					self::$datebook_options['my_settings_page'], 
					self::$datebook_options['my_privacy_page'], 
					self::$datebook_options['my_upgrade_page'], 
					self::$datebook_options['my_cart_page'], 
					self::$datebook_options['my_checkout_page'], 
					self::$datebook_options['my_notification_page']
				);

				// Get Profile personal data
				$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
				$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();
				
				// Check a profile has a photo
				$profile_photo_id = isset($datebook_get_data['profile_photo_id']) ? $datebook_get_data['profile_photo_id'] : '';
				$profile_photo_id_parse = explode('/', $profile_photo_id);
				$profile_photo_id = count($profile_photo_id_parse) > 1 ? $profile_photo_id_parse[1] : $profile_photo_id_parse[0];
				
				// Check a profile is completed
				$profile_must_complete = isset($datebook_get_data['profile_must_complete']) && $datebook_get_data['profile_must_complete'] == 1 ? 1 : 0;

				$go_ahead = 1;

				$profile_name = isset($profile->post_title) ? $profile->post_title : '';

				// Check and notify the user to click the validation link
				$user_verified_email_array = self::check_if_email_verified($current_user_id);

				if (isset($user_verified_email_array['emailhash']) && $user_verified_email_array['emailhash'] != '') {

					$go_ahead = 0;

					$action = '';

					if (isset($_GET['action'])) {
						$action = preg_replace("/([^a-zA-Z0-9])/", '', $_GET['action']);
					}

					if ($action == 'resendactivation' || (isset($_GET['message']) && $_GET['message'] == 'verifyemailsent')) {

						// display the Notification that the activation link has been resent again
						echo DateBook_Template_Loader::load( 'misc/notification-activation-link-resent' );

					} else if ($action == 'resendactivation' || (isset($_GET['message']) && $_GET['message'] == 'verifyemailnotsent')) {

						// display the Notification that the activation link has been resent again
						echo DateBook_Template_Loader::load( 'misc/notification-activation-link-notsent' );

					} else {

						$get_payment_page = !empty($_POST['payment_page']) ? $_POST['payment_page'] : 0;

						if (isset($_POST['action']) && $_POST['action'] == 'payment_page' && $get_payment_page == '3') {

							$get_splan = isset($_POST['subscriptionplan']) && strlen($_POST['subscriptionplan']) > 1 ? $_POST['subscriptionplan'] : 0;
							$get_splan_period_key = !empty($_POST['subscriptionplan_period_key']) ? $_POST['subscriptionplan_period_key'] : 0;
							$wp_verify_nonce = !empty($_REQUEST['datebooktkn']) ? $_REQUEST['datebooktkn'] : '';

							if ($get_splan > 0 && ( isset($wp_verify_nonce) || wp_verify_nonce( $wp_verify_nonce, 'datebook_new_subscription_form_nonce' ) )) {

								$go_ahead = 0;

								// Display a message about necessity of email verification
								echo DateBook_Template_Loader::load( 'misc/notification-email-verify-first' );

							}

						} else {

							if (in_array($page_id, $pages_of_get_option)) {

								$go_ahead = 0;

								echo DateBook_Template_Loader::load( 'misc/notification-email-verify' );

							}
						}
					}
				}

				if ($go_ahead == 1 && self::$datebook_options['user_must_upload_photo'] == '1' && $profile_photo_id == '' && (in_array($page_id, $pages_of_get_option) || isset($_GET['message']) && $_GET['message'] == 'mustuploadphoto')) {

					$go_ahead = 0;

					// Display a message that the profile must upload photo
					echo DateBook_Template_Loader::load( 'misc/profile-must-upload-photo' );

					if (self::$datebook_options['user_must_complete_profile'] == '1' && $profile_must_complete == 0) {

						// Display a message that the profile must upload photo
						$profile_must_complete_options = array('class' => 'd-none');
						echo DateBook_Template_Loader::load( 'misc/profile-must-complete-profile', $profile_must_complete_options );

					}
				}

				if ($go_ahead == 1 && self::$datebook_options['user_must_complete_profile'] == '1' && $profile_must_complete == 0 && (in_array($page_id, $pages_of_get_option) || isset($_GET['message']) && $_GET['message'] == 'mustcompleteprofile')) {

					$go_ahead = 0;

					// Display a message that the profile must upload photo
					echo DateBook_Template_Loader::load( 'misc/profile-must-complete-profile' );

				}

				if ($go_ahead == 1 && get_post_meta($profile_id, 'notactive', true) == '1') {

					$go_ahead = 0;

					// Display a message that the profile will be active after approval by the administrator
					echo DateBook_Template_Loader::load( 'misc/profile-activated-by-admin' );

				}

				if ($go_ahead == 1 && isset($_GET['message']) && $_GET['message'] == 'mustsubscribe') {

					$go_ahead = 0;

					// display the panel with form to select Subsciption plan
					echo DateBook_Template_Loader::load( 'payment/profile-subscription-not-selected' );

				} else {

					$get_payment_page = !empty($_POST['payment_page']) ? $_POST['payment_page'] : 0;

					if (isset($_POST['action']) && $_POST['action'] == 'payment_page' && $get_payment_page == '3') {

						$get_splan = isset($_POST['subscriptionplan']) && strlen($_POST['subscriptionplan']) > 1 ? $_POST['subscriptionplan'] : 0;
						$get_splan_period_key = !empty($_POST['subscriptionplan_period_key']) ? $_POST['subscriptionplan_period_key'] : 0;
						$wp_verify_nonce = !empty($_REQUEST['datebooktkn']) ? $_REQUEST['datebooktkn'] : '';

						if ($get_splan > 0 && ( isset($wp_verify_nonce) || wp_verify_nonce( $wp_verify_nonce, 'datebook_new_subscription_form_nonce' ) )) {
							
							if(self::$datebook_options['user_must_upload_photo'] == '1'){
								
								if ($go_ahead == 1 && $profile_photo_id == ''){

									$go_ahead = 0;

									// Display a message about necessity of photo upload
									echo DateBook_Template_Loader::load( 'misc/profile-must-upload-photo' );
									
								}
							}
							
							if ($go_ahead == 1 && self::$datebook_options['user_must_complete_profile'] == '1' && $profile_must_complete == 0) {

								// Display a message about necessity of complete profile fields
								echo DateBook_Template_Loader::load( 'misc/profile-must-complete-profile' );

							}
						}

					} else {
						
						// Remove Checkout and Cart pages
						$pages_of_get_option = array(
							self::$datebook_options['my_cart_page'],
							self::$datebook_options['my_checkout_page'],
							self::$datebook_options['my_upgrade_page']
						);

						if (isset(self::$datebook_options['my_upgrade_page']) && self::$datebook_options['my_upgrade_page'] > 0 && !in_array($page_id, $pages_of_get_option)) {

							// Check if Payment and Subscription are activated
							if (self::check_if_gateway_activated()){

								$user_selected_subscription_plan = DateBook_Profile_Subscription::user_selected_subscription_plan($current_user_id);
								if($go_ahead == 1 && $user_selected_subscription_plan == 0){

									// Display a message about necessity of selecting a subscription plan
									echo DateBook_Template_Loader::load( 'payment/profile-subscription-not-selected' );

								}
							}
						}
					}
				}
			}
		}
	}


	/**
	 * Delete folder with images of Profile
	 * 
	 * @since 4.4.4
	 * @access private
	 */
	private static function deleteDirectory($dir) {

		if (!file_exists($dir)) {
			return true;
		}

		if (!is_dir($dir)) {
			return unlink($dir);
		}

		foreach (scandir($dir) as $item) {
			if ($item == '.' || $item == '..') {
				continue;
			}

			if (!self::deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
				return false;
			}

		}

		return rmdir($dir);

	}


	/**
	 * Delete Profile, Classifieds, Tours, Comments, and its photos
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function final_delete_profile($profile_id, $user_id = 0) {

		global $wpdb;

		if (isset($user_id) && $user_id > 0) {
			$user_id = $user_id;
		} else {
			$profile_post = get_post($profile_id);
			$user_id = isset($profile_post->post_author) && $profile_post->post_author > 0 ? $profile_post->post_author : 0;
		}

		if (isset($profile_id) && $profile_id > 0 && isset($user_id) && $user_id > 0) {

			$table_countries = strtolower($wpdb->prefix) . 'datebook_countries';

			$get_profile_country = get_post_meta($profile_id, 'country', true);
			$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter - 1 WHERE id = %d", $get_profile_country) );

			$get_profile_region = get_post_meta($profile_id, 'region', true);
			$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter - 1 WHERE id = %d", $get_profile_region) );

			$get_profile_city = get_post_meta($profile_id, 'city', true);
			$wpdb->query( $wpdb->prepare("UPDATE " . $table_countries . " SET counter = counter - 1 WHERE id = %d", $get_profile_city) );


			//delete all classifieds
			$args = array(
				'post_type' => DATEBOOK_CLASSIFIEDS_TYPE,
				'posts_per_page' => -1,
				'meta_query' => array(
					array(
						'key' => 'profile_classifieds_id',
						'value' => $profile_id,
						'compare' => '='
					)
				)
			);

			$the_query = new WP_Query( $args );

			if ($the_query->have_posts()) :

				while ( $the_query->have_posts() ) : $the_query->the_post();

					wp_delete_post( absint(get_the_ID()), true ); //delete post

				endwhile;

			endif;

			wp_reset_postdata();

			//delete all tours
			$args = array(
				'post_type' => DATEBOOK_TOUR_TYPE,
				'posts_per_page' => -1,
				'meta_query' => array(
					array(
						'key' => 'profile_tour_id',
						'value' => $profile_id,
						'compare' => '='
					)
				)
			);

			$the_query = new WP_Query( $args );

			if ($the_query->have_posts()) :

				while ( $the_query->have_posts() ) : $the_query->the_post();

					wp_delete_post( absint(get_the_ID()), true ); //delete post

				endwhile;

			endif;

			wp_reset_postdata();


			//delete all comments/reviews
			$args = array(
				'post_type' => DATEBOOK_COMMENT_TYPE,
				'posts_per_page' => -1,
				'meta_query' => array(
					array(
						'key' => 'profile_type',
						'value' => $profile_id,
						'compare' => '='
					)
				)
			);

			$the_query = new WP_Query( $args );

			if ($the_query->have_posts()) :

				while ( $the_query->have_posts() ) : $the_query->the_post();

					wp_delete_post( absint(get_the_ID()), true ); //delete post

				endwhile;

			endif;

			wp_reset_postdata();


			// Delete all images
			$get_profile_data = get_post_meta($profile_id, 'profile_personal_data', true);
			$datebook_get_data = !empty($get_profile_data) ? $get_profile_data : array();

			if(isset($datebook_get_data['upload_folder']) && !empty($datebook_get_data['upload_folder'])){

				$upload_folder = $datebook_get_data['upload_folder'];

				$upload_dir = wp_upload_dir();
				$dirtodelete = $upload_dir['basedir'] . '/' . $upload_folder;

				self::deleteDirectory($dirtodelete);

			}


			// Delete Profile
			wp_delete_post( $profile_id, true );


			// Delete User and User Meta
			if (get_user_meta( $user_id, 'profile_type', true ) == DATEBOOK_POST_TYPE) {

				// load file from admin area
				load_template( ABSPATH . 'wp-admin/includes/user.php' );

				wp_delete_user($user_id);

				delete_user_meta( $user_id, 'profile_postid' );
				delete_user_meta( $user_id, 'profile_type' );

				$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d", $user_id) );
				$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->users WHERE ID = %d", $user_id) );

			}

			return true;

		} else {

			return false;

		}
	}


	public static function datebook_search_pagination($total, $current, $query_search_link){

		$range = 5;

		if(empty($current)) $current = 1;

		if($total == ''){

			$total = $total;

			if(!$total){
				$total = 1;
			}
		}

		if($total != 1){

			$showitems = ($range * 2) + 1;

			echo '<div class="datebook-custom-card card">';
			echo '<div class="card-body">';

			echo '<nav>';
			echo '<span class="sr-only">' . esc_html__( 'Page navigation', 'datebook' ) . '</span>';
			echo '<ul class="pagination justify-content-center">';

		 	if($current > 2 && $current > $range+1 && $showitems < $total){
				echo '<li class="page-item"><a class="page-link" href="' . esc_url(get_pagenum_link(1) . $query_search_link) . '" aria-label="' . esc_html__( 'First page', 'datebook' ) . '">&laquo;</a></li>';
			}

			if($current > 1 && $showitems < $total){
				echo '<li class="page-item"><a class="page-link" href="' . esc_url(get_pagenum_link($current - 1) . $query_search_link) . '" aria-label="' . esc_html__( 'Previous page', 'datebook' ) . '">&lsaquo;</a></li>';
			}


			for ($i=1; $i <= $total; $i++){
				if (1 != $total &&( !($i >= $current+$range+1 || $i <= $current-$range-1) || $total <= $showitems )){
					echo ($current == $i)? '<li class="page-item active"><span class="page-link"><span class="sr-only">' . esc_html__( 'Current page', 'datebook' ) . '</span> ' . $i . '</span></li>' : '<li class="page-item"><a class="page-link" href="' . esc_url(get_pagenum_link($i) . $query_search_link) . '"><span class="sr-only">' . esc_html__( 'Page', 'datebook' ) . '</span> ' . $i . '</a></li>';
				}
			}

			if ($current < $total && $showitems < $total){
				echo '<li class="page-item"><a class="page-link" href="' . esc_url(get_pagenum_link($current + 1) . $query_search_link) . '" aria-label="' . esc_html__( 'Next page', 'datebook' ) . '">&rsaquo;</a></li>';
			}

			if ($current < $total-1 &&  $current+$range-1 < $total && $showitems < $total){
				echo '<li class="page-item"><a class="page-link" href="' . esc_url(get_pagenum_link($total) . $query_search_link) . '" aria-label="' . esc_html__( 'Last page', 'datebook' ) . '">&raquo;</a></li>';
			}

			echo '</ul>';
			echo '</nav>';

			echo '</div>';
			echo '</div>';

		}
	}


	/**
	 * Custom pagination
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function datebook_custom_pagination($total, $current, $format = '', $base = '', $country = '', $gender = '', $agefrom = '', $ageto = '') {

		if ( $total > 1 ) {

			if (!$format) { $format = get_option('permalink_structure') ? 'page/%#%/' : '?paged=%#%'; }
			if (!$base) { $base = get_pagenum_link(1); }

			$country = $country ? 'country=' . (int)$country . '&amp;' : '';
			$gender = $gender ? 'gender=' . (int)$gender . '&amp;' : '';
			$agerange = $agefrom && $ageto ? 'agerange=' . (int)$agefrom . '-' . (int)$ageto : '';
		
			if ($country || $gender || $agerange) {
		
				$question_sign = '?' . $country . $gender . $agerange;
		
			} else {

				$question_sign = $country . $gender . $agerange;

			}

			if ($current == 0) { $current = 1; }

			$paginate = paginate_links(array(
					'base' => esc_url($base) . '%_%' . $question_sign,
					'format' => $format,
					'total' => $total,
					'current' => $current,
					'end_size' => '1',
					'mid_size' => '3',
					'class' => 'pagination',
					'type' => 'array'
				));
			
			echo '<nav>';
			echo '<span class="sr-only">' . esc_html__( 'Page navigation', 'datebook' ) . '</span>';
			echo '<ul class="pagination justify-content-center">';

			foreach ($paginate as $i => $page) {

				$page_number = strip_tags($page);
				
				$page = str_replace(array( 'page-numbers' ), array( 'page-link' ), $page );

				if ($current == 1 && $page_number == 1) {

					echo '<li class="page-item active"><span class="page-link"><span class="sr-only">' . esc_html__( 'Current page', 'datebook' ) . '</span> ' . $page_number . '</span></li>';

				} else {

					if ($current != 1 && $current == $page_number) {

						echo '<li class="page-item active">' . $page . '</li>';

					} else {

						echo '<li class="page-item">' . $page . '</li>';

					}
				}
			}

			echo '</ul>';
			echo '</nav>';

		}

	}


	/**
	 * Show field on registration or/and search page
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function datebook_show_field($name, $section = 1) {

		$fields = DateBook_Forms::get_all_custom_fields($name);

		if ($section == 1 && isset($fields['active']) && $fields['active'] == 1) {

			// show in Registration form
			return true;

		} else if ($section == 2 && isset($fields['active']) && $fields['active'] == 1 && isset($fields['required']) && $fields['required'] == 1) {

			// show in Search form
			return true;
		
		} else if ($section == 3 && isset($fields['active']) && $fields['active'] == 1 && isset($fields['searchable']) && $fields['searchable'] == 1) {

			// show in Search form
			return true;

		} else if ($section == 4 && isset($fields['visible_to_admin_only']) && $fields['visible_to_admin_only'] == '1') {

			// show to administrator only
			return true;

		} else {

			// do not show
			return false;

		}

	}


	/**
	 * Field is required in registration page
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function datebook_required_field($name, $show = 1) {

		$fields = self::$datebook_options[$name];

		if ($show == 1) {

			if ($fields[2] == 1) {

				return '';
				
			} else {

				return '<small class="text-muted"> (' . esc_html__( 'optional', 'datebook' ) . ')</small>';

			}

		} else {

			if ($fields[2] == 1) {

				return true;
				
			} else {

				return false;

			}

		}

		return false;

	}


	/**
	 * Delete all photos
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function datebook_delete_all_photos($upload_folder, $image_title, $delete_original = 1) {
		
		global $datebook_image_sizes;

		$upload_dir = wp_upload_dir();
		$targetPath = $upload_dir['basedir'] . '/' . $upload_folder;

		//list($orig_thumb_width, $orig_thumb_height) = getimagesize($targetPath . '/' . $image_title);

		$title_only = explode('.', $image_title);

		foreach ( $datebook_image_sizes as $key => $value ) {

			// Delete original image
			$photo_path = $targetPath . '/' . $title_only[0] . '-' . $value['width'] . 'x' . $value['height'] . '.' . $title_only[1];
			if (file_exists($photo_path)) { unlink($photo_path); }

			// Delete normal image
			$photo_path = $targetPath . '/' . DateBook_Utilities::datebook_encode($title_only[0] . '-' . $value['width'] . 'x' . $value['height']) . '.' . $title_only[1];
			if (file_exists($photo_path)) { unlink($photo_path); }

			// Delete blur image
			$photo_path = $targetPath . '/' . DateBook_Utilities::datebook_encode($title_only[0] . '-' . $value['width'] . 'x' . $value['height'] . '-blur') . '.' . $title_only[1];
			if (file_exists($photo_path)) { unlink($photo_path); }

			// Delete Retina image @2x
			$retina_path = $targetPath . '/' . DateBook_Utilities::datebook_encode($title_only[0] . '-' . $value['width'] . 'x' . $value['height']) . '@2x.' . $title_only[1];
			if (file_exists($retina_path)) { unlink($retina_path); }
			$retina_blur = $targetPath . '/' . DateBook_Utilities::datebook_encode($title_only[0] . '-' . $value['width'] . 'x' . $value['height'] . '-blur') . '@2x.' . $title_only[1];
			if (file_exists($retina_blur)) { unlink($retina_blur); }

			// Delete Retina image @1.5x
			$retina_path = $targetPath . '/' . DateBook_Utilities::datebook_encode($title_only[0] . '-' . $value['width'] . 'x' . $value['height']) . '@1.5x.' . $title_only[1];
			if (file_exists($retina_path)) { unlink($retina_path); }
			$retina_blur = $targetPath . '/' . DateBook_Utilities::datebook_encode($title_only[0] . '-' . $value['width'] . 'x' . $value['height'] . '-blur') . '@1.5x.' . $title_only[1];
			if (file_exists($retina_blur)) { unlink($retina_blur); }

			// Delete Retina image @1.25x
			$retina_path = $targetPath . '/' . DateBook_Utilities::datebook_encode($title_only[0] . '-' . $value['width'] . 'x' . $value['height']) . '@1.25x.' . $title_only[1];
			if (file_exists($retina_path)) { unlink($retina_path); }
			$retina_blur = $targetPath . '/' . DateBook_Utilities::datebook_encode($title_only[0] . '-' . $value['width'] . 'x' . $value['height'] . '-blur') . '@1.25x.' . $title_only[1];
			if (file_exists($retina_blur)) { unlink($retina_blur); }

		}

		if (file_exists($targetPath . '/' . $image_title)) { unlink($targetPath . '/' . $image_title); }

	}


	/**
	 * Create random password for new user
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function datebook_random_symbols( $length = 8, $chars =  'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) {

		return substr( str_shuffle( $chars ), 0, $length );

	}
	

	/**
	 * Detect Emoji icons in the text
	 * 
	 * @since 4.3.9
	 * @access public
	 */
	public static function detect_emoji_symbols($input) {

		$layout = '';

		$emoji = Emoji\detect_emoji($input);

		foreach($emoji as $key => $value){
			$layout .= '<span class="datebook-single-emoji" data-emoji="' . $value['emoji'] . '">' . $value['emoji'] . '</span>';
		}
		
		return $layout;

	}


	/**
	 * Get term
	 * 
	 * @since 1.6
	 * @access public
	 */
	public static function datebook_get_term_by( $datebook_column, $datebook_term_by, $country_deep_level = 1 ) {

		global $wpdb;

		$datebook_term = array();

		$table_name = strtolower($wpdb->prefix) . 'datebook_countries';

		$get_fields = $get_join_fields = '';

		$cities = 'cities';
		$regions = 'regions';
		$countries = 'countries';

		$cities_fields = $cities . '.id as city_id, ' . $cities . '.name as city, ' . $cities . '.parent_id as city_parent_id, ';
		$regions_fields = $regions . '.id as region_id, ' . $regions . '.name as region, ' . $regions . '.parent_id as region_parent_id, ';
		$countries_fields = $countries . '.id as country_id, ' . $countries . '.name as country, ' . $countries . '.parent_id as country_parent_id ';

		$regions_join_fields = "LEFT JOIN `{$table_name}` as " . $regions . " ON " . $cities . ".parent_id = " . $regions . ".id ";
		$countries_join_fields = "LEFT JOIN `{$table_name}` as " . $countries . " ON regions.parent_id = " . $countries . ".id ";

		if($country_deep_level == 1){
			$get_fields .= $cities_fields;
			$get_fields .= $regions_fields;
			$get_fields .= $countries_fields;
			$get_join_fields .= $regions_join_fields;
			$get_join_fields .= $countries_join_fields;
			$get_table_name = $cities;
		}
		if($country_deep_level == 2){
			$get_fields .= $regions_fields;
			$get_fields .= $countries_fields;
			$get_join_fields .= $countries_join_fields;
			$get_table_name = $regions;
		}
		if($country_deep_level == 3){
			$get_fields .= $countries_fields;
			$get_table_name = $countries;
		}

		if($datebook_column == 'id'){
			$where_clause = 'id';
			$prepare_clause = "%d";
		} else if($datebook_column == 'slug'){
			$where_clause = 'slug';
			$prepare_clause = "%s";
		} else if($datebook_column == 'parent_id'){
			$where_clause = 'parent_id';
			$prepare_clause = "%d";
		}
		
		$datebook_query = "
			SELECT 
			" . $get_fields . " 
			FROM `{$table_name}` as " . $get_table_name . " 
			" . $get_join_fields . " 
			WHERE " . $get_table_name . "." . $where_clause . " = " . $prepare_clause;
			
		$datebook_terms = $wpdb->get_results($wpdb->prepare($datebook_query, $datebook_term_by));

		if($datebook_terms){

			// If only one match was found, it's the one we want.
			if ( 1 === count( $datebook_terms ) ) {
				foreach ( $datebook_terms as $key => $match ) {
					$datebook_term[$key] = $match;
				}
			} else {
				foreach ( $datebook_terms as $key => $match ) {
					$datebook_term[$key] = $match;
				}
			}

			if(isset($datebook_terms[0]->city)){
			
				$get_city_name = maybe_unserialize( $datebook_terms[0]->city );

				if(is_array($get_city_name)){

					// if foreign language do not exist, then show title in English (en_US)
					$get_city_name = isset($get_city_name[DATEBOOK_WPLANG]) ? $get_city_name[DATEBOOK_WPLANG] : $get_city_name['en_US'];

					$datebook_term[0]->city = $get_city_name;
				} else {
					$datebook_term[0]->city = $datebook_term;
				}
			
			}

			if(isset($datebook_terms[0]->region)){
			
				$get_region_name = maybe_unserialize( $datebook_terms[0]->region );

				if(is_array($get_region_name)){

					// if foreign language do not exist, then show title in English (en_US)
					$get_region_name = isset($get_region_name[DATEBOOK_WPLANG]) ? $get_region_name[DATEBOOK_WPLANG] : $get_region_name['en_US'];

					$datebook_term[0]->region = $get_region_name;
				} else {
					$datebook_term[0]->region = $datebook_term;
				}

			}
			
			if(isset($datebook_terms[0]->country)){

				$get_country_name = maybe_unserialize( $datebook_terms[0]->country );

				if(is_array($get_country_name)){

					// if foreign language do not exist, then show title in English (en_US)
					$get_country_name = isset($get_country_name[DATEBOOK_WPLANG]) ? $get_country_name[DATEBOOK_WPLANG] : $get_country_name['en_US'];

					$datebook_term[0]->country = $get_country_name;
				} else {
					$datebook_term[0]->country = $datebook_term;
				}
				
			} else {
				
				$datebook_term[0]->country_id = $datebook_term[0]->region_id;
				$datebook_term[0]->country = $datebook_term[0]->region;
				$datebook_term[0]->country_parent_id = $datebook_term[0]->region_parent_id;
				
				$datebook_term[0]->region_id = '';
				$datebook_term[0]->region = '';
				$datebook_term[0]->region_parent_id = '';
				
			}

			return $datebook_term[0];

		}

		return $datebook_term;

	}


	/**
	 * Checks if the user is signed in and redirects to required page.
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_protect() {

		if ( ! is_user_logged_in() ) {

			$login_required_page = self::$datebook_options['login_page'];

			if ( ! empty( $login_required_page ) ) {

				wp_redirect( get_permalink( $login_required_page ) );

			} else {

				wp_redirect(home_url());

			}
			
			exit();

		}
	}

	/**
	 * Filter words in text: profile, chat, classifieds, tours and etc.
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_word_filter($text) {

		$filtered_text = $text;

		if(self::$datebook_options['enable_prohibited_words']) {

			$filtered_text = $text;

			$blacklisted_words = self::$datebook_options['prohibited_words'];

			if(!empty($blacklisted_words)) {

				$blacklisted_words_array = explode(',', strtr($blacklisted_words, array("\r\n" => ',', "\r" => ',', "\n" => ',')));
				$blacklisted_words_1 = is_array($blacklisted_words_array) ? $blacklisted_words_array : array();

				$blacklisted_words_2 = explode(',', $blacklisted_words);

				$filter_terms = array_merge($blacklisted_words_1, $blacklisted_words_2);

				foreach($filter_terms as $word){

					if(!empty($word) && strlen($word) > 0) {

						$word = trim($word);

						$match_count = preg_match_all("/\b" . $word . "?\b/i", $text, $matches);

						for($i = 0; $i < $match_count; $i++){
							$bwstr = trim($matches[0][$i]);
							$filtered_text = preg_replace('/\b' . $bwstr . '\b/', str_repeat("*", strlen($bwstr)), $filtered_text);
						}
					}
				}
			}
		}

		return $filtered_text;

	}


	/**
	 * Set and get cookie with redirect link
	 *
	 * @access public
	 */
	public static function set_redirect_to($page_id){

		if(isset($page_id) && $page_id > 0){

			$datebook_redirect_to = get_permalink($page_id);

			// Local timzone of visitor
			setcookie('datebook_redirect_to', $datebook_redirect_to, strtotime('+1 hour'), "/");  /* expires in 1 hour */

		}
	}


	/**
	 * Show profiles on sidebar by country
	 *
	 * @access public
	 * @return void
	 */
	public static function load_related_profiles_bycountry() {

		// display the Edit Profile form
		echo DateBook_Template_Loader::load( 'widgets/related-profiles-by-country' );		

	}


	/**
	 * Return Login and Registration links
	 *
	 * @access public
	 * @return void
	 */
	public static function pre_login_register_links() {

		return DateBook_Template_Loader::load( 'login/login-register-links' );

	}


	/**
	 * Login and Registration links in Footer
	 *
	 * @access public
	 * @return void
	 */
	public static function login_register_links() {

		echo self::pre_login_register_links();

	}


	/**
	 * Copyright in Footer
	 *
	 * @access public
	 * @return void
	 */
	public static function copyright_text() {

		// display the Edit Profile form
		echo DateBook_Template_Loader::load( 'misc/copyright-text' );		

	}
	
	
}

//DateBook_Utilities::init();
$dateBook_utilities = new DateBook_Utilities($datebook_options_array);