<?php
// CONTROL LOGIN, HIDE WP PVTCONTENT USERS AND TURN THEM AS EXTERNAL VISITORS ALSO IF LOGGED
// file called only if sync is active


// login control - check pvtContent user status
function pc_wp_user_login($user_login, $user) {
	global $wpdb, $pc_wp_user;
	
	// if login is performed by PvtContent - skip
	if(isset($GLOBALS['pc_manual_wp_user_login'])) {
		return true;	
	}
	
	include_once(PC_DIR .'/functions.php');
	$user_data = $pc_wp_user->wp_user_is_linked($user->ID);
	
	if($user_data) {
		
		// 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);


		// check wheter perform redirects - avoid on ajax forms submission
		if(
			(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') ||
			strpos(pc_curr_url(), 'wp-admin/admin-ajax.php') !== false	
		) {
			$is_ajax_call = true;	
		}
		else {$is_ajax_call = false;}
		
		
		//// check status
		// login failed
		if((int)$user_data->status !== 1 || $custom_check !== false) {
			// Clear cookies -> log user out
			wp_clear_auth_cookie();
			
			if(!$is_ajax_call) {
				// redirect adding disabling parameter - for pc_wp_user_login_message() function 
				$login_url = site_url('wp-login.php', 'login');

				if(!$custom_check) {
					$login_url = add_query_arg('pc_disabled', $user_data->status, $login_url);
				} else {
					$login_url = add_query_arg('pc_cust_err', base64_encode(urlencode($custom_check)), $login_url);	
				}
				
				wp_redirect($login_url);
				exit;
			}
		}
		
		// login ok
		else {
			include_once(PC_DIR . '/functions.php');
		
			//// login in pvtContent	
			// setup user session, cookie and global
			$_SESSION['pc_user_id'] = $user_data->id;
			$GLOBALS['pc_user_id'] = $user_data->id;
			
			// set cookie
			$cookie_time = (isset($_POST['rememberme'])) ? (3600 * 24 * 30 * 6) : (3600 * 6); // 6 month or 6 hours
			setcookie('pc_user', $user_data->id.'|||'.$user_data->psw, time() + $cookie_time, '/');
			
			// update last login date
			$wpdb->update(PC_USERS_TABLE, array('last_access' => current_time('mysql')), array('id' => $user_data->id)); 
			
			
			//// redirect after login
			if(!$is_ajax_call) {
				// check for custom categories redirects
				$custom_cat_redirect = pc_user_cats_login_redirect(unserialize($user_data->categories));
				
				// pvtContent login redirect
				$pc_login_redirect = pc_man_redirects('pg_logged_user_redirect');
				
				if($custom_cat_redirect) {
					$redirect_url = $custom_cat_redirect;	
				}
				elseif($pc_login_redirect) {
					$redirect_url = $pc_login_redirect;		
				}
				elseif(isset($_REQUEST['redirect_to']) && filter_var($_REQUEST['redirect_to'], FILTER_VALIDATE_URL)) {
					$redirect_url = $_REQUEST['redirect_to'];	
				}	
				else {$redirect_url = site_url();}	
				
				wp_redirect($redirect_url);
				exit;
			}
		}
	}
}
add_action('wp_login', 'pc_wp_user_login', 10, 999);



// login message management
function pc_wp_login_mess($user, $username, $password) {
	
	if(isset($_GET['pc_disabled']) && ((int)$_GET['pc_disabled'] === 3 || (int)$_GET['pc_disabled'] == 2)) {
		$error = new WP_Error();
		$error->add('pc_login_error', pc_get_message('pc_default_pu_mex')); // pending user message
			
		return $error;
	}
	
	else if(isset($_GET['pc_cust_err'])) {
		$error = new WP_Error();
		$error->add('pc_login_error', urldecode(base64_decode($_GET['pc_cust_err']))); // custom errors
			
		return $error;
	}
	
	return $user;
}
add_filter('authenticate', 'pc_wp_login_mess', 999, 3);




// if WP "remember me" is still active - re-log on PrivateContent (might happen using WP forms)
function pc_wp_user_is_still_logged() {
	global $pc_wp_user, $pc_users;
	
	if(isset($GLOBALS['pc_user_id'])) {
		return true;	
	}
	
	$user = wp_get_current_user();
	if(!$user->exists()) {return true;} // no user logged
	
	if(isset($user->ID) && !empty($user->ID)) {
		$user_data = $pc_wp_user->wp_user_is_linked($user->ID);
		
		if($user_data) {
			if(pc_user_logged(false)) {return true;} // also pvtContent user is logged
			
			// synced user isn't active - logout WP user
			if($user_data->status !== 1) {
				pc_logout();			
			}
			
			// perform login
			else {
				pc_login($user_data->username, $pc_users->decrypt_psw( $user_data->psw ));	
			}
		}
	}
}
add_action('wp_loaded', 'pc_wp_user_is_still_logged', 1);




// manage WP logout - if is linked to a pvtContent user
function pc_wp_user_logout() {
    global $wpdb, $pc_wp_user;
	
	// if is updating user - avoid
	if(isset($GLOBALS['pc_updating_user']) && $GLOBALS['pc_updating_user']) {return false;}
	if(isset($GLOBALS['pc_is_updating_wp_user']) && $GLOBALS['pc_is_updating_wp_user']) {return false;}
	
    $user = wp_get_current_user();
	
	if(isset($user->ID) && !empty($user->ID)) {
		$user_data = $pc_wp_user->wp_user_is_linked($user->ID);
		
		if($user_data) {
			if(!isset($GLOBALS['pc_only_wp_logout'])) {pc_logout();}
			
			// check if a redirect is needed
			if(get_option('pg_logout_user_redirect')) {
				$redirect_url = pc_man_redirects('pg_logout_user_redirect');
				wp_redirect($redirect_url);
				exit;
			}
		}
	}
}
add_action('clear_auth_cookie', 'pc_wp_user_logout', 100);



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



// disable admin bar
function pc_wps_disable_admin_bar() {
	if(current_user_can('pvtcontent')) {	
	
		show_admin_bar(false);
		add_filter('show_admin_bar', '__return_false', 99999); 
	}
}
add_action('wp_loaded', 'pc_wps_disable_admin_bar', 2);



// avoid pvtcontent users to go into default WP dashboard
function pc_wp_user_no_admin() {
	if(is_admin()) {
		global $current_user;
		if(isset($current_user) && isset($current_user->caps) && isset($current_user->caps['pvtcontent']) && $current_user->caps['pvtcontent']) {
			ob_start();
			ob_clean();
			header('location: '.site_url());
		}
	}
}
add_action('admin_enqueue_scripts', 'pc_wp_user_no_admin', 1);



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



// track synced user edit - edit main fields also on pvtContent user
function pc_wps_sync_wp_edit_to_pvtcontent($user_id, $old_user_data) {
	global $wpdb, $pc_wp_user;
	
	// not if profile updated by pvtContent
	if(isset($GLOBALS['pc_is_updating_wp_user'])) {
		return false;	
	}
	
	$synced_user_data = $pc_wp_user->wp_user_is_linked($user_id);
	if($synced_user_data) {
		
		$wp_user_data = get_userdata($user_id);
		$wp_user_meta = get_user_meta($user_id);
		
		$args = array(
			'username'	=> $wp_user_data->user_login, 
			'psw'		=> $wp_user_data->user_pass, 
			'email'		=> $wp_user_data->user_email, 
			'psw'		=> $wp_user_data->user_pass, 
			'name'		=> (string)$wp_user_meta['first_name'][0],
			'surname'	=> (string)$wp_user_meta['last_name'][0],
		);
		$response = $wpdb->update(PC_USERS_TABLE, $args, array('id' => $synced_user_data->id));

		// force pvtContent capabilities!
		$pc_wp_user->set_wps_custom_roles($user_id);
	}
}
add_action('profile_update', 'pc_wps_sync_wp_edit_to_pvtcontent', 100, 2);



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



// Allow direct pvtContent sync in "edit user" page 
function pc_wps_edit_user_pc_sync($user_data) {
	global $wpdb, $pc_wp_user;
	include_once(PC_DIR .'/functions.php');
	
	if($pc_wp_user->wp_user_is_linked($user_data->ID) || !current_user_can($GLOBALS['pc_cuc_edit'])) {
		return false;	
	}
	
	// admins can't be synced
	if(in_array('administrator', $user_data->roles)) {
		return false;	
	}
	?>
	
    <div id="pc_wps_eus_wrap" class="form-field">
		<h2 id="pc_wps_eus_heading">PrivateContent - <?php _e('User Sync', 'pc_ml') ?></h2>
			
        <table class="form-table" id="pc_wps_eus_table"> 
           <tr>
                <th>
                	<label for="pc_wps_eus_cat"><?php _e('User categories', 'pc_ml') ?></label>
                </th>
                <td>
                    <select id="pc_wps_eus_field" name="pc_wps_eus_cat[]" multiple="multiple" autocomplete="off">
                        <?php
						foreach(pc_user_cats() as $cat_id => $cat_name) {
							echo '<option value="'. $cat_id .'">'. $cat_name .'</option>';  
						}	
						?>
                    </select>
                </td>
            </tr>
            <tr>
            	<th style="padding-top: 0px;">
                	<input type="button" class="button-secondary" name="pc_wps_eus_btn" value="<?php echo esc_attr( __('Sync user', 'pc_ml')) ?>" />
                </th>
                <td id="pc_wps_eus_response" style="padding-top: 0px;"></td>
            </tr>
        </table>    
            	
        <script src="<?php echo PC_URL ?>/js/chosen/chosen.jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            var pc_wps_is_syncing = false;
			
			// sync
			$(document).delegate('[name=pc_wps_eus_btn]', 'click', function(e) {
				var cats = $('#pc_wps_eus_field').serialize();
				if(!cats || pc_wps_is_syncing) {return false;}
				
				if(confirm("<?php _e("Do you really want to turn this user into a PrivateContent user? Won't be possible to have it back in future", 'pc_ml') ?>")) {
					pc_wps_is_syncing = true;
					var $btn = $(this);
					
					$('#pc_wps_eus_response').empty();
					$btn.fadeTo(200, 0.7);		
										
					var data = 'action=wp_to_pc_single_user_sync&pc_nonce=<?php echo wp_create_nonce('lcwp_ajax') ?>&wp_user_id=<?php echo $user_data->ID ?>&'+ cats;
					
					$.post(ajaxurl, data, function(response) {
						var resp = $.parseJSON(response);

						if(resp.status == 'success') {
							$('#pc_wps_eus_response').html("<?php _e('User synced successfully!', 'pc_ml') ?>");
							
							setTimeout(function() {
								window.location.href = '<?php echo admin_url() ?>admin.php?page=pc_add_user&user='+ resp.user_id;
							}, 1000);
						}
						else {
							pc_wps_is_syncing = false;
							$btn.fadeTo(200, 1);	
							 
							$('#pc_wps_eus_response').html( resp.message );
						}
					});	
				}
			});
			

			
            // chosen
            $("#pc_wps_eus_field").each(function() {
                var w = $(this).css("width");
                $(this).chosen({width: w}); 
            });
            $(".pc_restr_wiz_chosen-deselect").chosen({allow_single_deselect:true});
        });
        </script>
    </div>
	<?php
}
add_action('show_user_profile', 'pc_wps_edit_user_pc_sync', 999);
add_action('edit_user_profile', 'pc_wps_edit_user_pc_sync', 999);




// Automatic sync for WP users registered in frontend
function wp_to_pc_sync_on_register_errors($errors, $sanitized_user_login, $user_email) {
	global $pc_users, $pc_wp_user;

	if($pc_wp_user->wp_user_sync && get_option('wp_to_pc_sync_on_register')) {
			
		// can't detect roles - then match against any user	
		$args = array(
			'limit'  			=> 1,
			'search_operator' 	=> 'OR',
			'count'				=> true,
			'search' 			=> array(
				array('key' => 'username', 'operator' => '=', 'val' => $sanitized_user_login),
				array('key' => 'email',    'operator' => '=', 'val' => $user_email),
			)
		);
		if($pc_users->get_users($args)) {
			$errors->add('pc wps - username or mail exists', __("Another user has this username or e-mail", 'pc_ml'));		
		}
	}
    return $errors;
}
add_filter('registration_errors', 'wp_to_pc_sync_on_register_errors', 999, 3);


function wp_to_pc_sync_on_register($wp_user_id) {
	global $pc_wp_user;

	if(!$pc_wp_user->wp_user_sync || !get_option('wp_to_pc_sync_on_register') || is_admin() || isset($GLOBALS['pc_wp_user_register'])) {
		return false;
	}
	
	// match against role?
	$allowed_roles = get_option('wp_to_pc_sync_on_register_roles', array());
	if(!empty($allowed_roles)) {
		
		$user_data = new WP_User($wp_user_id);
		$matched = false;
		
		foreach($allowed_roles as $ar) {
			if(in_array($ar, $user_data->roles)) {
				$matched = true;
				break;	
			}
		}
		
		if(!$matched) {
			return false;	
		}
	}
	
	// sync
	$pc_user_id = $pc_wp_user->pc_user_from_wp($wp_user_id, get_option('wp_to_pc_sync_on_register_cats', array()) );
	
	if(!is_wp_error($pc_user_id)) {
		
		// PC-ACTION - pvtcontent user created from WP user registered on frontend
		do_action('pc_user_created_from_wp_register', $pc_user_id, $wp_user_id);	
	}
}
add_action('user_register', 'wp_to_pc_sync_on_register', 999999);




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



// hide privateContent from dropdown choiches in users.php
// remove ability to edit or delete user
function pc_hide_pvtcontent_role_dd() {
	global $current_screen;

	if(isset($current_screen->base) && $current_screen->base == 'users') {
		?>
    	<script type="text/javascript">
		jQuery(document).ready(function(e) {
        	jQuery('select#new_role option[value=pvtcontent]').remove();  
			
			jQuery('#the-list tr').each(function() {
                var $row = jQuery(this);
				if($row.find('.column-role').text() == 'PrivateContent') {
					$row.find('.check-column').empty();
					$row.find('.row-actions').remove();
					
					$row.find('.username a').each(function() {
                        var content = jQuery(this).contents();
						jQuery(this).replaceWith(content);
                    });	
				}
            });
        });
		</script>    
    	<?php	
	}
	elseif(isset($current_screen->base) && ($current_screen->base == 'user-edit' || $current_screen->base == 'user')) {
		?>
        <script type="text/javascript">
		jQuery(document).ready(function(e) {
        	jQuery('select#role option[value=pvtcontent]').remove();  
        });
		</script> 
    	<?php			
	}
}
add_action('admin_footer', 'pc_hide_pvtcontent_role_dd', 1);



// avoid users to edit synced through user-edit.php interface
function pc_avoid_pvtcontent_edit() {
	include_once(PC_DIR . '/functions.php');
	$curr_url = pc_curr_url();

	if(strpos($curr_url, 'user-edit.php') !== false) {
		global $pc_wp_user;
		$check = $pc_wp_user->wp_user_is_linked((int)$_REQUEST['user_id']);
		if(!empty($check)) {
			
			
			// always allow access - isn't possible to track referer because of errors
			//if(isset($_GET['wp_http_referer']) && $_GET['wp_http_referer'] == 'http://pc') {
				add_action('admin_head', 'pc_wps_edit_user_special_codes', 900);	
			/*}
			else {
				ob_start();
				ob_clean();
				header('location: '.admin_url('admin.php?page=pc_add_user&user='. $check->id ));	// move to pvtContent edit page
			}*/
		}
	}
}
add_action('admin_init', 'pc_avoid_pvtcontent_edit', 1);


// special inline CSS and JS in WP user edit to be used in lightbox - leave only custom fields
function pc_wps_edit_user_special_codes() {
?>
	<style type="text/css">
	#adminmenuwrap,
	#adminmenuback,
	#wpadminbar,
	#wpfooter,
	#wpcontent > :not(#wpbody),
	#contextual-help-link-wrap,
	.wp-heading-inline,
	a.page-title-action,
	hr.wp-header-end,
	#message p:nth-of-type(2) {
		display: none !important;	
	}
	#wpcontent {
		margin-left: 0 !important;	
	}
	html.wp-toolbar {
		padding-top: 0 !important;	
	}
	#your-profile {
		opacity: 0;	
	}
	#your-profile > h2:not(:first-of-type) {
		margin-top: 40px;	
	}
	</style>


	<script type="text/javascript">
	jQuery(document).ready(function($) {

		// cycle sections and hide fields that must NOT be managed
		$('#your-profile > h2').each(function(i, v) {
			$(this).next().hide();
			
			// keep "Personal Options" heading	
			if(i != 0) {
				$(this).hide();
			}
			
			// stop when finding password
			if( $(this).next().find('#password').length ) {
				
				$('#your-profile').fadeTo(300, 1);
				return false;	
			}
        });
		
		
		// keep "language / nickame / display name" fields
		$('#your-profile > h2').first().after('<table class="form-table pc_wps_ftk"><tbody></tbody></table>');
		
		$('#locale, #nickname, #display_name').each(function() {
			var classes = $(this).attr('class');
			var html  = $(this).parents('tr').html();
			$(this).parents('tr').remove();
			
			$('.pc_wps_ftk').append('<tr class="'+ classes +'">'+ html +'</tr>');
        });
		

		// add multiple "update user" buttons to be quicker
		var cloned_btn = $("<div />").append($('p.submit').clone()).html();
		
		// cycle sections and hide fields that must NOT be managed
		$('#your-profile > h2, #your-profile > h3').each(function(i, v) {
			
			if( i && $(this).is(':visible') ) {
				$(this).before(cloned_btn);
			}
		});
    });
	</script>
<?php		
}




// avoid users to delete synced through user-edit.php interface
function pc_avoid_pvtcontent_del() {
	include_once(PC_DIR . '/functions.php');
	$curr_url = pc_curr_url();

	if(strpos($curr_url, 'users.php') !== false && strpos($curr_url, 'action=delete') !== false) {
		global $pc_wp_user;
		
		if(isset($_REQUEST['user'])) {$users = array($_REQUEST['user']);}
		elseif(isset($_REQUEST['users'])) {
			$users = $_REQUEST['users'];	
		}

		foreach($users as $user_id) {
			$user_data = get_userdata($user_id);
			
			if(isset($user_data->caps['pvtcontent'])) {
				ob_start();
				ob_clean();
				header('location: '.admin_url('users.php'));	
				break;
			}
		}
	}
}
add_action('admin_init', 'pc_avoid_pvtcontent_del', 1);



// hide pvtcontent user filter from wp-admin/users.php 
function pc_no_pvtcontent_role_users_list($roles) {
    
	if(isset($roles['pvtcontent'])) {
		unset( $roles['pvtcontent'] );	
	}
	
    return $roles;
}
add_filter('views_users', 'pc_no_pvtcontent_role_users_list');





// Hide users with "pvtcontent" role from WP users table
function pc_filter_wp_users_list( $query ) {
    if(!function_exists('get_current_screen')) {
		return false;	
	}
	
	$screen = get_current_screen();
    if( is_admin() && 'users' == $screen->base ){
        $query->set('role__not_in', 'pvtcontent');
    }
}
add_action('pre_get_users', 'pc_filter_wp_users_list');




// Hide users with "pvtcontent" role from WP users table count
function pc_filter_wp_users_list_count($query) {
	global $current_screen;
	
	if(is_null($current_screen) || $current_screen->base != 'users') {
		return $query;	
	}
	
	if(strpos($query, "COUNT(NULLIF(") === false || strpos($query, "pvtcontent") === false) {
		return $query;	
	}
	

	$query = str_replace(
		"WHERE meta_key = 'wp_capabilities'",
		"WHERE meta_key = 'wp_capabilities' AND meta_value NOT LIKE '%pvtcontent%'",
		$query
	);
	return $query;
}
add_filter('query', 'pc_filter_wp_users_list_count');





