<?php

/* 
 * CHECK IF AN USER IS LOGGED 
 * @since 5.0
 *
 * @param (mixed) $get_data = whether to return logged in user data. 
 *	true (default) to return full user data + meta
 *	false to return only a boolean value
 *	fields array to return only them
 *
 * @return (mixed) 
 *	false if user is not logged, 
 *	true if user is logged and no data must be returned,
 *	associative array in case of multiple data to return (key => val)
 *	mixed if want to get only one value (directly returns value)	
 */
function pc_user_logged($get_data = true) {
	if(!isset($GLOBALS['pc_user_id']) && !isset($_SESSION['pc_user_id'])) {
		return false;
	}
	else {
		global $pc_users;
		$user_id = (isset($_SESSION['pc_user_id'])) ? $_SESSION['pc_user_id'] : $GLOBALS['pc_user_id'];
		
		//// check if actual user is active		
		// if just check user without getting data
		if(!$get_data) {
			if(isset($GLOBALS['PC_VER_LOGGED_USER']) && $GLOBALS['PC_VER_LOGGED_USER'] == $user_id) {
				return true;
			}
			$result = $pc_users->get_users(array('user_id' => $user_id, 'count' => true));
			
			// check only once in this case
			if($result && !isset($GLOBALS['PC_VER_LOGGED_USER'])) {
				$GLOBALS['PC_VER_LOGGED_USER'] = $user_id;
				return ($result) ? true : false;	
			}
			else {
				return true; // user already verified
			} 
		}
		else {
			$args = array('status' => 1);
			if($get_data !== true) {$get_data = (array)$get_data;}
			$args['to_get'] = $get_data;
			
			$result = $pc_users->get_user($user_id, $args);
			
			// if getting single field - return only that
			if(count($get_data) == 1) {
				$result = $result[$get_data[0]];	
			}
			
			// if result is ok - set constant to check verified user logged
			if($result && !isset($GLOBALS['PC_VER_LOGGED_USER'])) {$GLOBALS['PC_VER_LOGGED_USER'] = $user_id;}
			return $result;	
		}
	}
}
function pg_user_logged($get_data = true) {return pc_user_logged($get_data);} // retrocompatibility




/* CHECK IF CURRENT USER CAN ACCESS TO AN AREA
 * @since 5.0
 *
 * given the allowed param, check if user has right permissions - eventually checks WP users pass
 *
 * @param (array) allowed = allowed users - may contain
 *		all			= any logged in user
 *		unlogged 	= unlogged users
 *		user categories id or any custom key bindable through hook
 *
 * @param (array) blocked = specifically blocked users among allowed ones - may contain
 *		user categories id or any custom key bindable through hook
 *
 * @param (bool) wp_user_pass - whether to count logged WP users checking permission (check 'testing mode' in settings)
 * @param (bool) allow_filter - whether to apply filter if "all" and "unlogged" options are selected
 *
 *
 * @return (mixed)
 *	false = not logged
 *	2 = user doesnt' have right permissions
 *	1 = has got permissions
 */
function pc_user_check($allowed = array('all'), $blocked = array(), $wp_user_pass = false, $allow_filter = true) {
	global $pc_users;
	
	// be sure to have only arrays
	if(!is_array($allowed)) {$allowed = explode(',', $allowed);}
	if(!is_array($blocked)) {$blocked = explode(',', $blocked);}
	
	
	// if WP user can pass
	if($wp_user_pass && is_user_logged_in() && !isset($GLOBALS['pc_user_id'])) {	
		// be sure constant is initiated
		pc_testing_mode_flag();
		
		// if only unlogged users are allowed
		if(defined('PC_WP_USER_PASS')) {
			if(in_array('unlogged', $allowed)) {
				return (PC_WP_USER_PASS) ? false : 1;
			} else {
				return (PC_WP_USER_PASS) ? 1 : false;	
			}
		}
	}
		
	///////////////////////////////////	
	
	// no allowed specified - pass 
	if(empty($allowed)) {
		return 1;
	}
	
	// if any logged is allowed - be sure it is the only field
	if(in_array('all', $allowed)) {
		$allowed = array('all');
		
		if(empty($blocked)) {
			return (pc_user_logged(false) !== false) ? 1 : false;		
		}
	}
	
	// if allowed only unlogged
	else if(implode('', $allowed) == 'unlogged') {
		return (pc_user_logged(false) === false) ? 1 : false;	
	}
	
	
	////////
	// user categories matching 	
	
	// cache user categories to avoid double calls
	if(isset($GLOBALS['pc_curr_user_cats'])) {
		$user_cats = (array)$GLOBALS['pc_curr_user_cats']; 	
	} else {
		$user_cats = (array)pc_user_logged('categories'); 	
		$GLOBALS['pc_curr_user_cats'] = $user_cats;	
	}
	
	
	// no user logged == empty array or index #0 == false
	if(empty($user_cats) || $user_cats[0] == false) {return false;}

	
	// check blocked
	$blocked = (array)array_diff($blocked, $allowed); // strip allowed from blocked
	if(count($blocked) && count(array_diff($user_cats, $blocked)) != count($user_cats)) { // if a user category is among blocked
		return 2;	
	}
	
	
	// calculate privateContent (not add-ons) allowance - strip custom values assuming they are not pure numbers
	$pc_allowed = array();
	foreach($allowed as $aa) {
		if($aa == 'unlogged' || filter_var($aa, FILTER_VALIDATE_INT)) {
			$pc_allowed[] = $aa;	
		}
	}

	if(!count($pc_allowed)) { // no pc allowed specified - let it pass
		$to_return = 1;
	}
	elseif(in_array('unlogged', $pc_allowed) && pc_user_logged(false) === false) { // if unlogged users are allowed and user is not logged
		$to_return = 1;	
	}
	else {
		$to_return = (count(array_diff($user_cats, $pc_allowed)) != count($user_cats)) ? 1 : 2;
	}
	
	// filter?
	if($allow_filter) {
		
		//// PC-FILTER - give chance to perform further checks - passes default check result, user categories, allowed users, blocked users
		// user is logged then ID can be retrieved through global and filter must return a proper value (1 or 2)
		$to_return = apply_filters('pc_extra_user_check', $to_return, $user_cats, $allowed, $blocked);	
		return $to_return;
	}
	else {
		return $to_return;	
	}
}
function pg_user_check($allowed = 'all', $blocked = '') {return pc_user_check($allowed, $blocked);} // retrocompatibility




/* GET LOGIN FORM
 * @since 5.0
 *
 * @param (string) redirect = forces a specific redirect after login - must be a valid URL or "refresh"
 * @param (string) align = form alignment - center/left/right
 *
 * @return (string) the login form code or empty if a logged user is found
 */
function pc_login_form($redirect = '', $align = 'center') {
	include_once(PC_DIR.'/classes/pc_form_framework.php');
	include_once(PC_DIR.'/functions.php');

	$f_fw = new pc_form();
	
	$custom_redirect 	= (!empty($redirect)) ?  'data-pc_redirect="'.$redirect.'"' : '';
	$remember_me 		= get_option('pg_use_remember_me');
	$rm_class 			= ($remember_me) ? 'pc_rm_login' : '';
	$is_widget_class 	= (isset($GLOBALS['pc_login_widget'])) ? 'pc_widget_login' : '';
	
	// fields icon
	$un_icon_class 	= (get_option('pg_username_icon')) ? 'pc_field_w_icon' : '';
	$psw_icon_class = (get_option('pg_psw_icon')) ? 'pc_field_w_icon' : '';
	
	$un_icon 	= ($un_icon_class) ? '<span class="pc_field_icon" title="'. esc_attr( __('Username', 'pc_ml') ) .'"><i class="fa '.get_option('pg_username_icon').'"></i></span>' : '';
	$psw_icon 	= ($psw_icon_class) ? '<span class="pc_field_icon" title="'. esc_attr( __('Password', 'pc_ml') ) .'"><i class="fa '.get_option('pg_psw_icon').'"></i></span>' : '';
	
	// login also through e-mail
	if(get_option('pg_allow_email_login')) {
		$user_label 		= __('Username or e-mail', 'pc_ml');
		$long_labels_class 	= 'pc_lf_long_labels'; // force long labels 		
	}
	else {
		$user_label 		= __('Username', 'pc_ml');
		$long_labels_class 	= '';
	}
	
	// placeholders only if no-label is active
	$un_placeh 	= (get_option('pg_nolabel')) ? 'placeholder="'. esc_attr($user_label) .'"' : '';
	$psw_placeh = (get_option('pg_nolabel')) ? 'placeholder="'. esc_attr(__('Password', 'pc_ml')) .'"' : '';
	
	// button's icon
	$icon = (get_option('pg_login_btn_icon')) ? '<i class="fa '. get_option('pg_login_btn_icon') .'"></i>' : '';
	
	
	$form = '
	<form class="pc_login_form '. $rm_class .' '. $is_widget_class .' '. $long_labels_class .'" '. $custom_redirect .'>
		<div class="pc_login_row '.$un_icon_class.'">
			<label for="pc_auth_username">'. $user_label .'</label>
			
			<div class="pc_field_container">
				'. $un_icon .'
				<input type="text" name="pc_auth_username" value="" '.$un_placeh.' autocapitalize="off" autocomplete="off" autocorrect="off" maxlength="150" />
			</div>	
		</div>
		<div class="pc_login_row '.$psw_icon_class.'">
			<label for="pc_auth_psw">'. __('Password', 'pc_ml') .'</label>
			
			<div class="pc_field_container">
				'. $psw_icon .'
				<input type="password" name="pc_auth_psw" value="" '.$psw_placeh.' autocapitalize="off" autocomplete="off" autocorrect="off" />
			</div>
		</div>
		'.$f_fw->honeypot_generator().'
		
		<div id="pc_auth_message"></div>
		
		<div class="pc_login_smalls">';
		
		  if($remember_me) {
			$form .= '
			<div class="pc_login_remember_me">
				<input type="checkbox" name="pc_remember_me" value="1" autocomplete="off" />
				<small>'. __('remember me', 'pc_ml') .'</small>
			</div>';
		  }
			
			//////////////////////////////////////////////////////////////
			// PSW RECOVERY TRIGGER - MAIL ACTIONS ADD-ON
			$form = apply_filters('pcma_psw_recovery_trigger', $form);	
			//////////////////////////////////////////////////////////////
		
		$form .= '
		</div>
		<button class="pc_auth_btn"><span class="pc_inner_btn">'.$icon. __('Login', 'pc_ml') .'</span></button>';
		
		
		//////////////////////////////////////////////////////////////
		// PSW RECOVERY CODE - MAIL ACTIONS ADD-ON
		$form = apply_filters('pcma_psw_recovery_code', $form);	
		//////////////////////////////////////////////////////////////
	
	$form .= '
	</form>';
	
	return (pc_user_logged(false)) ? '' : pc_form_align($form, $align);
}
function pg_login_form($redirect = '') {return pc_login_form($redirect);} // retrocompatibility




/* GET LOGOUT BUTTON
 * @since 5.0
 *
 * @param (string) redirect = forces a specific redirect after login - must be a valid URL
 * @return (string) the logout button code or empty if a logged user is found
 */
function pc_logout_btn($redirect = '') {
	$custom_redirect = (!empty($redirect)) ?  'data-pc_redirect="'.$redirect.'"' : '';
	
	// button's icon
	$icon = (get_option('pg_logout_btn_icon')) ? '<i class="fa '. get_option('pg_logout_btn_icon') .'"></i>' : '';
	
	$logout = '<mark class="pc_logout_btn" '.$custom_redirect.'><span class="pc_inner_btn">'.$icon. __('Logout', 'pc_ml') .'</span></mark>';
	return (!pc_user_logged(false)) ? '' : $logout;
}
function pg_logout_btn($redirect = '') {return pc_logout_btn($redirect);} // retrocompatibility




/* LOGGING IN USER - passing username and password, check and setup session/cookie and WP login 
 * @since 5.0
 *
 * @param (string) username - you may pass also user e-mail if related option is enabled in settings
 * @param (string) password
 * @param (bool) remember_me - whether to use extended cookies (6 months)
 * @return (mixed) 
 	false if not found
	true if logged sucessfully 
	otherwise user status (2 or 3) 
	or custom message for custom check
 */
function pc_login($username, $psw, $remember_me = false) {
	global $wpdb, $pc_users, $pc_wp_user;
		
	if(isset($_REQUEST['pc_logout']) || isset($_REQUEST['pg_logout'])) {return 'user is being logged out';}


	// only username or also e-mail?
	$username_part = (get_option('pg_allow_email_login')) ? '(username = %s OR email = %s)' : 'username = %s';
	$wpdb_prepare_vars = (get_option('pg_allow_email_login')) ? array(trim($username), trim($username)) : array(trim($username));

	// query
	$user_data = $wpdb->get_row( 
		$wpdb->prepare(
			"SELECT id, username, psw, status, wp_user_id FROM  ".PC_USERS_TABLE." WHERE ". $username_part ." LIMIT 1",
			$wpdb_prepare_vars
		) 
	);
	if(empty($user_data)) {return false;}
	
	
	// match password (using WP functions)
	if(!wp_check_password($psw, $user_data->psw)) {
		return false;	
	}
	
	
	// PC-FILTER - custom login control for custom checks - passes false and user id - return message to abort login otherwise false
	$custom_check = apply_filters('pc_login_custom_check', false, $user_data->id);
	
	if($custom_check !== false) {
		return $custom_check;		
	}
	
	// setup user session
	elseif($user_data->status == 1) {
		
		// PHP session
		if(session_id()) {
			$_SESSION['pc_user_id'] = $user_data->id;
		}


		// setup cookie
		if(!isset($GLOBALS['pc_cookie_login'])) {
			$basic_cookie_time = (get_option('pg_no_cookie_login')) ? 60 : (3600 / 2); // 1 or 30 minutes
			$cookie_time = (!empty($remember_me)) ? (3600 * 24 * 14) : $basic_cookie_time; // 2 weeks (WP remember me timing) or what stated before		
			
			// cookie structure = user id - encrypted password
			$cookie_data = array($user_data->id, $user_data->psw);
			setcookie('pc_user', implode('|||', $cookie_data), (time() + $cookie_time), '/');
		}
		
		
		// wp user sync - login also there
		if($pc_users->wp_user_sync && $user_data->wp_user_id) {
			$pc_wp_user->manual_user_login($user_data->wp_user_id, $user_data->username);
		}
		
		
		// setup global
		$GLOBALS['pc_user_id'] = $user_data->id;
		
		// update last login date
		$wpdb->update(PC_USERS_TABLE, array('last_access' => current_time('mysql')), array('id' => $user_data->id));
		
		// try avoiding page cache
		header("Cache-Control: no-cache, must-revalidate");
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		

		// PC-ACTION - user is logged in - passes user id and remember-me flag
		do_action('pc_user_login', $user_data->id, $remember_me);
		return true;
	}
	else {
		return $user_data->status;	
	}
}




/* 
 * LOGGING OUT USER - deletes logged user session/cookies 
 * @since 5.0
 */
function pc_logout() {
	global $pc_users;
	$wp_user_id = pc_user_logged('wp_user_id');
	
	if($wp_user_id !== false) {

		// PC-ACTION - user is logged out - passes user id
		do_action('pc_user_logout', $GLOBALS['pc_user_id']);
		
		// try avoiding page cache
		header("Cache-Control: no-cache, must-revalidate");
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		
		if(isset($_SESSION['pc_user_id'])) unset($_SESSION['pc_user_id']);
		if(isset($GLOBALS['pc_user_id'])) unset($GLOBALS['pc_user_id']);
		
		setcookie('pc_user', '', time() - (3600 * 25), '/');

		// wp user sync - unlog if WP logged is the one synced
		if($pc_users->wp_user_sync) {
			$current_user = wp_get_current_user();
			if($current_user && $wp_user_id == $current_user->ID) {
				wp_destroy_current_session();
	
				setcookie( AUTH_COOKIE,        ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH,   COOKIE_DOMAIN );
				setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH,   COOKIE_DOMAIN );
				setcookie( AUTH_COOKIE,        ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
				setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
				setcookie( LOGGED_IN_COOKIE,   ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,          COOKIE_DOMAIN );
				setcookie( LOGGED_IN_COOKIE,   ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH,      COOKIE_DOMAIN );
			
				// Old cookies
				setcookie( AUTH_COOKIE,        ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,     COOKIE_DOMAIN );
				setcookie( AUTH_COOKIE,        ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
				setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,     COOKIE_DOMAIN );
				setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
			
				// Even older cookies
				setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,     COOKIE_DOMAIN );
				setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,     COOKIE_DOMAIN );
				setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
				setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
				
				//wp_clear_auth_cookie(); // don't use the function to avoid interferences with do_action( 'clear_auth_cookie' );	
			}
		}
		
		if(isset($GLOBALS['PC_VER_LOGGED_USER'])) {
			unset($GLOBALS['PC_VER_LOGGED_USER']);
		}
	}
	
	return true;	
}
function pg_logout() {return pc_logout();} // retrocompatibility




/* REGISTRATION FORM 
 * @since 5.0
 *
 * @param (int) form_id = registration form ID to use - if invalid or null, uses first form in DB
 * @param (string) layout = form layout to use, overrides global one (one_col or fluid) 
 * @param (string) forced_cats = user category ID or IDs list (comma split) to assign to registered users
 * @param (string) redirect = custom form redirect for registered users (url or "refresh")
 * @param (string) align = form alignment - center/left/right
 *
 * @return (string) the registration form's code
 */
function pc_registration_form($form_id = '', $layout = '', $forced_cats = false, $redirect = false, $align = 'center') {
	include_once(PC_DIR.'/classes/pc_form_framework.php');
	include_once(PC_DIR.'/functions.php');
	
	// if is not set the target user category, return an error
	if(!get_option('pg_registration_cat')) {
		return __('You have to set registered users default category in settings', 'pc_ml');
	}
	else {
		$f_fw = new pc_form(array(
			'use_custom_cat_name' => true,
			'strip_no_reg_cats' => true
		));
		
		//// get form structure
		// if form not found - get first in list
		if(!(int)$form_id) {
			$rf = get_terms('pc_reg_form', 'hide_empty=0&order=DESC&number=1');
			if(empty($rf)) {return __('No registration forms found', 'pc_ml');}
			
			$rf = $rf[0];		
		}
		else {
			$rf = get_term($form_id, 'pc_reg_form');	
			
			if(empty($rf)) {
				$rf = get_terms('pc_reg_form', 'hide_empty=0&order=DESC&number=1');
				if(empty($rf)) {return __('No registration forms found', 'pc_ml');}
				
				$rf = $rf[0];		
			}
		}
			
		$form_structure = unserialize(base64_decode($rf->description));	
		if(!is_array($form_structure) || !in_array('username', $form_structure['include']) || !in_array('psw', $form_structure['include'])) {
			return  __('Username and password fields are mandatory', 'pc_ml');
		}
		
		// disclaimer inclusion
		if(get_option('pg_use_disclaimer')) {
			$form_structure['include'][] = 'pc_disclaimer';
		}

		// PC-FILTER - manage registration form structure - passes structure array and form id
		$form_structure = apply_filters('pc_registration_form', $form_structure, $rf->term_id);
		
		
		
		// layout class
		$layout = (empty($layout)) ? get_option('pg_reg_layout', 'one_col') : $layout; 
		$layout_class = 'pc_'. $layout .'_form';
		
		// custom category parameter
		if(!empty($forced_cats) && !in_array("categories", $form_structure['include'])) {
			$cat_attr = 'data-pc_cc="'.$forced_cats.'"'; 	
		}
		else {$cat_attr = '';}
		
		// custom redirect attribute
		if(!empty($redirect)) {
			$redir_attr = 'data-pc_redirect="'.$redirect.'"';		
		}
		else {$redir_attr = '';}
		
		
		$uniqid = 'pc_rf_'.uniqid(); 
		
		//// init structure
		$form = '
		<form id="'.$uniqid.'" class="pc_registration_form pc_rf_'.$rf->term_id.' '.$layout_class.'" '.$cat_attr.' '.$redir_attr.' data-form-pag="1" rel="'.$rf->term_id.'">';
			$custom_fields = '';
			
			//// anti-spam system
			$antispam = get_option('pg_antispam_sys', 'honeypot');
			if($antispam == 'honeypot') {
				$custom_fields .= $f_fw->honeypot_generator();
			}
			else {
				$custom_fields .= '
				<div class="pc_grecaptcha g-recaptcha"
				  data-sitekey="'. get_option('pg_recaptcha_public') .'"
				  data-callback="pc_recaptcha_cb"
				  data-size="invisible"
				  data-badge="inline"></div>';
			}
			
			$form .= $f_fw->form_code($form_structure, $custom_fields);
			
			$form .= '<div class="pc_form_response pc_reg_message"></div>';
	
			// has pages?
			if($f_fw->form_pages > 1) {
				$pag_btns = '
				<input type="button" value="'. esc_attr( __('Previous', 'pc_ml') ) .'" class="pc_pag_btn pc_pag_prev" style="visibility: hidden;" />
				<input type="button" value="'. esc_attr( __('Next', 'pc_ml') ) .'" class="pc_pag_btn pc_pag_next" />';
				
				$pag_submit_class 	= 'pc_pag_submit';	
				$pag_submit_vis		= 'style="display: none;"';	
			}
			else {
				$pag_btns = '';
				$pag_submit_class 	= '';
				$pag_submit_vis		= '';	
			}
	
	
			// button's icon
			$icon = (get_option('pg_register_btn_icon')) ? '<i class="fa '. get_option('pg_register_btn_icon') .'"></i>' : '';
	
			$form .= '
			<button class="pc_reg_btn '.$pag_submit_class.'" '.$pag_submit_vis.'><span class="pc_inner_btn">'.$icon. __('Submit', 'pc_ml') .'</span></button>
			'. $pag_btns .'
		</form>';
		
		return pc_form_align($form, $align);
	}
}
function pg_registration_form($forced_cats = false) {return pc_registration_form($forced_cats);} // retrocompatibility




/* RETRIEVES REDIRECT URL CONSIDERING CUSTOM ONES AND WPML or POLYLANG
 * @since 5.056
 *
 * @param (string) $key - redirect index to retrieve - uses DB ones
 *
 *	- pc_redirect_page				=> main redirect for restricted areas
 *	- pc_blocked_users_redirect		=> redirect target for blocked users
 *	- pc_logged_user_redirect		=> redirect for logged in users
 *	- pc_logout_user_redirect		=> redirect for logged out users
 *	- pc_registered_user_redirect	=> redirect for registered users
 *
 * @return (string) redirect url
 */
function pc_man_redirects($key) {
	include_once(PC_DIR.'/functions.php');
	
	// prefix retrocompatibility
	$key = str_replace('pc_', 'pg_', $key);
	
	$baseval = get_option($key);
	if($baseval == '') {$url = '';}
	
	if($baseval == 'custom') {
		$url = get_option($key.'_custom');
	}
	elseif($baseval == 'use_main') { // redirect for blocked users - use main
		$url = pc_man_redirects('pc_redirect_page');	
	}
	else {
		// WPML - Polylang integration
		$baseval = pc_wpml_translated_pag_id($baseval); 
		$url = get_permalink($baseval);
	}
	
	
	// PC-FILTER - allow custom redirect url return - passes current URL and redirect index
	// @since v5.1
	$url = apply_filters('pc_custom_redirect_url', $url, str_replace('pg_', 'pc_', $key));  
	return $url;
}




/* RETRIEVES USER MESSAGES AND GIVES ABILITY TO SET CUSTOM ONES 
 * @since 5.0
 *
 * @param (string) subj - message index to retrieve - uses DB ones
 *	- pc_default_nl_mex		=> Message for not logged users
 *	- pc_default_uca_mex	=> Message if user doesn't have right permissions
 
 *	- pc_default_hc_mex		=> Message if user can't post comments
 *	- pc_default_hcwp_mex	=> Message if user doesn't have permissions to post comments 
 
 *	- pc_default_nhpa_mex	=> Message if user doesn't have reserved area
 
 *	- pc_login_ok_mex		=> Message for successful login
 *	- pc_default_pu_mex		=> Message for pending users trying to login
 *	- pc_default_du_mex		=> Message for disabled users trying to login
 
 *	- pc_default_sr_mex		=> Message if successfully registered
 *
 * @param (string) custom_txt - custom message overriding default and DB set ones
 * @return (string) the message
 */
function pc_get_message($subj, $custom_txt = '') {
	if(!empty($custom_txt)) {return $custom_txt;}
	
	// prefix retrocompatibility
	$subj = str_replace('pg_', 'pc_', $subj);
	
	$subjs = array(
		'pc_default_nl_mex'		=> __('You must be logged in to view this content', 'pc_ml'),
		'pc_default_uca_mex'	=> __("Sorry, you don't have the right permissions to view this content", 'pc_ml'),
		
		'pc_default_hc_mex'		=> __("You must be logged in to post comments", 'pc_ml'),
		'pc_default_hcwp_mex'	=> __("Sorry, you don't have the right permissions to post comments", 'pc_ml'),
		
		'pc_default_nhpa_mex'	=> __("You don't have a reserved area", 'pc_ml'),
		
		'pc_login_ok_mex'		=> __('Logged successfully, welcome!', 'pc_ml'),
		'pc_default_pu_mex'		=> __('Sorry, your account has not been activated yet', 'pc_ml'),
		'pc_default_du_mex'		=> __('Sorry, your account has been disabled', 'pc_ml'),
		
		'pc_default_sr_mex'		=> __('Registration was successful. Welcome!', 'pc_ml'),
	);
	
	foreach($subjs as $key => $default_mess) {
		if($subj == $key) {
			
			// options still use PG
			$key = str_replace('pc_', 'pg_', $subj);
			$db_val = trim(get_option($key, ''));

			$mess = (!empty($db_val)) ? $db_val : $default_mess;
			
			// PC-FILTER - customize messages - passes message text and key
			return do_shortcode( apply_filters('pc_customize_message', $mess, $subj));
		}
	}
	
	return '';
}
function pg_get_nl_message($mess = '') {return pc_get_message('pc_default_nl_mex', $mess);}
function pg_get_uca_message($mess = '') {return pc_get_message('pc_default_uca_mex', $mess);}
