<?php
/* 
 * SETUP USER SESSION
 * HANDLES FRONTEND AJAX REQUEST TO LOGIN/LOGOUT USERS
 * READS USER'S COOKIE TO RE-LOG
 */



// setting up session | then check for logged user through session or cookie
function pc_init_session_check_cookie() {
	global $wpdb, $pc_users, $pc_wp_user;
	
	if (!session_id()) {
		ob_start();
		ob_clean();
		@session_start();
	}


	// WP synced user is logged - be sure it is logged also in pvtContent
	if(is_user_logged_in() && current_user_can('pvtcontent')) {
		$user_data = $pc_wp_user->wp_user_is_linked( get_current_user_id() );
		
		if($user_data->status == 1) {
			$GLOBALS['pc_user_id'] = $user_data->id;
		}	
	}
	
	
	// if isset pvtContent session - move into globals
	elseif(isset($_SESSION['pc_user_id'])) {
		$GLOBALS['pc_user_id'] = $_SESSION['pc_user_id'];
		
		// is synced and not logged in WP ? log it!
		if($pc_users->wp_user_sync && !is_user_logged_in()) {
			
			$wp_user_id = $pc_wp_user->pvtc_is_synced($GLOBALS['pc_user_id'], true);
			if($wp_user_id) {
				$pc_wp_user->manual_user_login($user_data->wp_user_id, $user_data->username);	
			}
		}
	}
	
	
	// otherwise perform a cookie check
	elseif(isset($_COOKIE['pc_user'])) {	
		
		// get user ID and crypted password
		$c_data = explode('|||', $_COOKIE['pc_user']);
		if(count($c_data) < 2) {return false;}
		
		$user_data = $wpdb->get_row(
			$wpdb->prepare( 
				"SELECT id, username, psw, status, wp_user_id FROM ".PC_USERS_TABLE." WHERE status = 1 AND id = %d AND psw = %s LIMIT 1",
				$c_data[0],
				$c_data[1]
			)
		);
		
		// user found 
		if($wpdb->num_rows && $user_data->status == 1) {
			
			// perform checks
			$custom_check = apply_filters('pc_login_custom_check', false, $user_data->id);
			if($custom_check !== false) {
				return false;	
			}
			
			
			// setup login elements
			$GLOBALS['pc_cookie_login'] = true;
			
			if(session_id()) {
				$_SESSION['pc_user_id'] = $user_data->id;
			}
			
			// 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);
			}
			
			// update last login date
			$wpdb->update(PC_USERS_TABLE, array('last_access' => current_time('mysql')), array('id' => $user_data->id));
			
			// setup global
			$GLOBALS['pc_user_id'] = $user_data->id;
		}
	}	


	############################################################################
	
	
	// try forcing (damned) WP-supercache cleaning on loading
	if(function_exists('wp_cache_clear_cache')) {
		wp_cache_clear_cache();	
	}
	
	
	############################################################################
	
	
	// PC-ACTION - give an hook to safely perform operations after session and cookie check - passes logged user ID or false 
	$uid = (isset($GLOBALS['pc_user_id']) && $GLOBALS['pc_user_id']) ? $GLOBALS['pc_user_id'] : false; 
	do_action('pc_user_session_checked', $uid);
	
	
	// add body class
	add_filter('body_class', 'pc_body_class', 10);	
}
add_action('init', 'pc_init_session_check_cookie', 1);



// add body class informing if user is logged or not
function pc_body_class($classes) {
	$classes[] = (isset($GLOBALS['pc_user_id']) && $GLOBALS['pc_user_id']) ? 'pc_logged' : 'pc_unlogged';
	return $classes;	
}



////////////////////////////////////////////////////////////////



// execute logout
function pc_logout_user() {
	if((isset($_REQUEST['type']) && $_REQUEST['type'] == 'pc_logout') || isset($_REQUEST['pc_logout']) || isset($_REQUEST['pg_logout'])) {
		include_once(PC_DIR . '/functions.php');

		$GLOBALS['pc_is_logging_out'] = true;
		pc_logout();	
		
		$logout_redirect = pc_man_redirects('pg_logout_user_redirect');
		
		// if logging out through URL parameter - directly perform redirect 
		if(!isset($_REQUEST['type'])) {
			pc_strip_pclogout();
		}
		
		// ajax logout - check if a redirect is needed and shut down
		echo $logout_redirect;
		die();
	}
}
add_action('init', 'pc_logout_user', 2); // IMPORTANT - execute as second to let user_id global to be setup


// if using pc_logout URL parameter - perform redirect stripping it
function pc_strip_pclogout() {
	include_once(PC_DIR . '/functions.php');
	
	$curr_url 	= pc_curr_url();
	$url_arr 	= explode('?', $curr_url);
	$params_arr = explode('&', $url_arr[1]);
	
	$new_params = array();
	foreach($params_arr as $param) {
		if(strpos($param, 'pc_logout') === false && strpos($param, 'pcac') === false) {
			$new_params[] = $param;	
		}
	}
	
	
	$new_url = (!count($new_params)) ? $url_arr[0] : $url_arr[0] .'?'. implode('&', $new_params);
	
	// add parameter to avoid browser cache
	$new_url = (!count($new_params)) ? $new_url.'?pcac='.uniqid() : $new_url.'&pcac='.uniqid(); 
	
	header('Location: '. $new_url);
	die();	
}



////////////////////////////////////////////////////////////////



// handle ajax login form
function pc_user_auth() {
	global $wpdb, $pc_users;
	
	if(isset($_POST['type']) && $_POST['type'] == 'js_ajax_auth') {
		include_once(PC_DIR.'/classes/pc_form_framework.php');
		include_once(PC_DIR . '/classes/simple_form_validator.php');
		include_once(PC_DIR . '/functions.php');	
		
		$f_fw = new pc_form();
		$validator = new simple_fv;
		$indexes = array();
		
		$indexes[] = array('index'=>'pc_auth_username', 'label'=>'username', 'required'=>true);
		$indexes[] = array('index'=>'pc_auth_psw', 'label'=>'psw', 'required'=>true);
		$indexes[] = array('index'=>'pc_remember_me', 'label'=>'remember me');

		$validator->formHandle($indexes);
		$error = $validator->getErrors();
		$fdata = $validator->form_val;
		
		// honeypot check
		if(!$f_fw->honeypot_validaton()) {
			echo json_encode(array( 
				'resp' => 'error',
				'mess' => "Antispam - we've got a bot here!"
			));
			die();
		}
		
		// error message
		if($error) {
			die( json_encode(array( 
				'resp' => 'error',
				'mess' => __('Incorrect username or password', 'pc_ml')
			)));
		}
		else {
			//// try to login
			$response = pc_login($fdata['pc_auth_username'], $fdata['pc_auth_psw'], $fdata['pc_remember_me']);
			
			// user not found
			if(!$response) {
				echo json_encode(array( 
					'resp' => 'error',
					'mess' => __('Incorrect username or password', 'pc_ml')
				));
				die();
			}
			
			// disabled/pending user
			elseif((int)$response === 3) {
				echo json_encode(array(
					'resp' => 'error',
					'mess' => pc_get_message('pc_default_pu_mex')
				));	
				die();
			}
			
			// disabled user
			elseif((int)$response == 2) {
				echo json_encode(array(
					'resp' => 'error',
					'mess' => pc_get_message('pc_default_du_mex')
				));	
				die();
			}
			
			// custom error
			elseif($response !== true) {
				echo json_encode(array(
					'resp' => 'error',
					'mess' => $response
				));		
				die();
			}
			
			// successfully logged
			else {
				// redirect logged user to pvt page
				if(get_option('pg_redirect_back_after_login') && isset($_SESSION['pc_last_restricted']) && filter_var($_SESSION['pc_last_restricted'], FILTER_VALIDATE_URL)) {
					$redirect_url = $_SESSION['pc_last_restricted'];
				}
				else {
					// check for custom categories redirects
					$custom_cat_redirect = pc_user_cats_login_redirect( pc_user_logged('categories'));
					
					$redirect_url = ($custom_cat_redirect) ? $custom_cat_redirect : pc_man_redirects('pg_logged_user_redirect');	
				}
				
				echo json_encode(array(
					'resp' => 'success',
					'mess' => pc_get_message('pc_login_ok_mex'),
					'redirect' => $redirect_url
				));	
				die();
			}
		}
		die(); // security block
	}
}
add_action('init', 'pc_user_auth', 3);
