<?PHP

/**
* this is private for core
*/
class Access{

	function __getAccess(){

		$this->__Login();
		return $_SESSION['object']['pages'];
	}

	function __Access($role_id = 0){

		if(!$_SESSION['object']['access'] || !$_SESSION['object']['pages']){

			$this->getAccess($role_id);
			$this->Pages();
		}
	}

	function __ReAssign(){

		unset($_SESSION['object']['pages']);
		unset($_SESSION['object']['access']);

		$role_id = $_SESSION['UserData']['role_id'] ? $_SESSION['UserData']['role_id'] : 1;
		$this->__Access($role_id);
	}

	function getAccess($role_id){

		if($role_id){

			$rows = $this->Sql->Query("select * from permissions where role_id=".$role_id." ", true);

			foreach($rows as $v){

				$access[$v['table_name']][] = $v;
			}

			$_SESSION['object']['access'] = $access;
		}
	}

	function Pages(){

		if(!$_SESSION['object']['pages'] && is_array($_SESSION['object']['access']['templates'])){

			foreach($_SESSION['object']['access']['templates'] as $v){

				if($v['allow_access'] == true){

					$page_id .= $page_id ? ", ".$v['table_id'] : $v['table_id'];
				}
			}

			//this is ordering for models what is represented in all positions
			$positions = array();
			$content = file_get_contents(_CurrentTemplate.'/'._TemplateGraphicPublic.'.php');
			preg_match_all('/position\(\'(.*?)\'\)/se', $content, $matches);
			foreach ($matches[1] as $k => $v){

				$positions[$v] = $v;
			}

			$content = file_get_contents(_CurrentTemplate.'/'._TemplateGraphicAdmin.'.php');
			preg_match_all('/position\(\'(.*?)\'\)/se', $content, $matches);
			foreach ($matches[1] as $k => $v){

				$positions[$v] = $v;
			}

			$content = file_get_contents(_CurrentTemplate.'/'._TemplateGraphicAjax.'.php');
			preg_match_all('/position\(\'(.*?)\'\)/se', $content, $matches);
			foreach ($matches[1] as $k => $v){

				$positions[$v] = $v;
			}

			$pages = array();
			$Rows = $this->Sql->Query("select distinct p1.id AS template_id, p1.position, p1.name, p1.page, p1.type, p1.is_static, p1.is_first_page, p1.page_position, p1.is_active, p1.queue from templates as p1
			where p1.is_active=1 and p1.id in (".$page_id.") and p1.position != '' and p1.type = 'MODEL'
			order by queue", true);

			if(is_array($Rows)){

				foreach($positions as $v){

					foreach($Rows as $v1){

						if($v1['position'] == $v || $v1['position'] == 'all'){

							$pages[trim($v)][] = array('model' => trim($v1['name']), 'page' => trim($v1['page']), 'is_static' => $v1['is_static'], 'type' => $v1['type'], 'is_first_page' => $v1['is_first_page'], 'page_position' => $v1['page_position'], 'position' => $v1['position'], 'queue' => $v1['queue']);
						}
					}
				}
			}
			$_SESSION['object']['pages'] = $pages;
		}
	}

	function login_query($user, $password){

		return $this->Sql->Query("select p1.*, p1.id as user_id, p1.name as user_name, CASE WHEN  p1.password_expires_at < NOW() and p1.password_expires_at IS NOT NULL THEN TRUE ELSE FALSE END as is_password_expired, p2.level, p2.type from users as p1 ".
		"join roles as p2 on p2.id=p1.role_id ".
		"where p1.name='".$user."' and p1.password='".$password."' and p1.is_enabled=1 and ( p1.account_expires_at>NOW() or p1.account_expires_at IS NULL or p1.account_expires_at = '0000-00-00')", true);
	}

	function temp_login_query($user, $password){

		return $this->Sql->Query("select p1.*, p1.id as user_id, p1.name as user_name, CASE WHEN  p1.password_expires_at < NOW() and p1.password_expires_at IS NOT NULL THEN TRUE ELSE FALSE END as is_password_expired, p2.level, p2.type from users as p1 ".
		"join roles as p2 on p2.id=p1.role_id ".
		"where p1.name='".$user."' and p1.temp_password='".$password."' and p1.is_enabled=TRUE and p2.is_enabled=1 and ( p1.account_expires_at>NOW() or p1.account_expires_at IS NULL)", true);
	}

	function lost_password_update($rows){

		if($this->Sql->Numrows > 0){

			$this->Sql->Query("UPDATE users SET password = temp_password, temp_password = '' WHERE id = ".$rows[0]['user_id']);
		}
	}

	function __Login($user='', $password=''){

		if($_GET['action'] == 'logout'){

			session_destroy();
			session_unset();
			unset($_SESSION);
			die('<script>window.location.href = "'._RootUrl.'";</script>');
		}
		if($_GET['action'] == 'reload'){

			session_destroy();
			session_unset();
			unset($_SESSION);
			$this->__ReAssign();
			die('<script>window.location.href = "'._RootUrl.'/admin/";</script>');
		}
		if($_GET['action'] == 'reassign'){

			$this->__ReAssign();
			die('<script>window.location.href = "'._RootUrl.'/admin/";</script>');
		}

		if(isset($_GET['userdata'])){

			print '<pre>';
			print_r ($_SESSION['UserData']);
			print '</pre>';
			exit;
		}

		if($user && $password){

			$user = strip_tags($user);
			$password = strip_tags($password);

			$rows = $this->login_query($user, md5($password));

			if($this->Sql->Numrows > 0){

				unset($_SESSION['logged']);
				unset($_SESSION['object']);
				unset($_SESSION['UserData']);
				$role_id = $rows[0]['role_id'];

				$rows2 = $this->Sql->Query("select *, id as client_id from clients where user_id=".$rows[0]['user_id'], true);
				$rows2['name'] = $rows2['first_name'].' '.$rows2['last_name'];
				if(is_array($rows[0]) && is_array($rows2[0])){

					$rows = array_merge( $rows[0], $rows2[0]);
				}

				$rows2 = $this->Sql->Query("select *, id as client_details_id from client_details  where client_id=".$rows['client_id'], true);
				if(is_array($rows) && is_array($rows2[0])){

					$rows = array_merge( $rows, $rows2[0]);
				}
				$rows['name'] = $rows['first_name'].' '.$rows['last_name'];

				if($this->Sql->Numrows > 0){

					$_SESSION['logged'] = true;
					$_SESSION['UserData'] = $rows;
					$_SESSION['UserData']['sess_id'] = $this->RandomString(25);

					$this->Sql->Query("INSERT INTO logs (`table_name`, `table_id`, `created_by`, `created_by_id`, `created_at`, `action`) VALUES ('users', ".$_SESSION['UserData']['user_id'].", '".$_SESSION['UserData']['user_name']."', ".$_SESSION['UserData']['user_id'].", NOW(), 'LOGIN')");
				}
			}
		}

		if($_POST['login']){

			$_POST['user'] = $_POST['login_user'] ? $_POST['login_user'] : $_POST['user'];
			$_POST['user'] = $_POST['login_user_2'] ? $_POST['login_user_2'] : $_POST['user'];

			$_POST['user'] = strip_tags($_POST['user']);
			$_POST['password'] = strip_tags($_POST['password']);

			$rows = $this->login_query($_POST['user'], md5($_POST['password']));
			if($this->Sql->Numrows == 0){

				$rows = $this->temp_login_query($_POST['user'], md5($_POST['password']));
				$this->lost_password_update($rows);
			}

			if($this->Sql->Numrows > 0){

				unset($_SESSION['logged']);
				unset($_SESSION['object']);
				unset($_SESSION['UserData']);
				$role_id = $rows[0]['role_id'];

				$rows2 = $this->Sql->Query("select *, id as client_id from clients where user_id=".$rows[0]['user_id'], true);
				$rows2['name'] = $rows2['first_name'].' '.$rows2['last_name'];
				if(is_array($rows[0]) && is_array($rows2[0])){

					$rows = array_merge( $rows[0], $rows2[0]);
				}

				$rows2 = $this->Sql->Query("select *, id as client_details_id from client_details  where client_id=".$rows['client_id'], true);
				if(is_array($rows) && is_array($rows2[0])){

					$rows = array_merge( $rows, $rows2[0]);
				}
				$rows['name'] = $rows['first_name'].' '.$rows['last_name'];

				if($this->Sql->Numrows > 0){

					$_SESSION['logged'] = true;
					$_SESSION['UserData'] = $rows;
					$_SESSION['UserData']['sess_id'] = $this->RandomString(25);

					$this->Sql->Query("INSERT INTO logs (`table_name`, `table_id`, `created_by`, `created_by_id`, `created_at`, `action`) VALUES ('users', ".$_SESSION['UserData']['user_id'].", '".$_SESSION['UserData']['user_name']."', ".$_SESSION['UserData']['user_id'].", NOW(), 'LOGIN')");
					$this->Sql->Query("INSERT INTO logs_session (action, created_by, created_by_id, created_at) VALUES ('login', '".$_SESSION['UserData']['user_name']."', ".$_SESSION['UserData']['user_id'].", NOW())");
				}
			}
		}

		if($_POST['relogin']){

			$rows = $this->login_query($_SESSION['UserData']['name'], $_SESSION['UserData']['password']);
			//$this->users->login_user($_SESSION['UserData']['name'], $_SESSION['UserData']['password']);

			if($this->Sql->Numrows > 0){

				unset($_SESSION['logged']);
				unset($_SESSION['object']);
				unset($_SESSION['UserData']);
				$role_id = $rows[0]['role_id'];

				$rows2 = $this->Sql->Query("select *, id as client_id from clients where user_id=".$rows[0]['user_id'], true);
				$rows = array_merge( $rows[0], $rows2[0]);

				$rows2 = $this->Sql->Query("select *, id as client_details_id from client_details  where client_id=".$rows['client_id'], true);
				$rows = array_merge( $rows, $rows2[0]);
				$rows['name'] = $rows['first_name'].' '.$rows['last_name'];

				if($this->Sql->Numrows > 0){

					$_SESSION['logged'] = true;
					$_SESSION['UserData'] = $rows[0];
					$_SESSION['UserData']['sess_id'] = $this->RandomString(25);

					$this->Sql->Query("INSERT INTO logs (`table_name`, `table_id`, `created_by`, `created_by_id`, `created_at`, `action`) VALUES ('users', ".$_SESSION['UserData']['user_id'].", '".$_SESSION['UserData']['user_name']."', ".$_SESSION['UserData']['user_id'].", NOW(), 'LOGIN')");
				}
			}
		}

		if($_GET['action'] == 'login'){

			if($_GET['from_role_type']){

				$from_user_id = $_SESSION['UserData']['user_id'];
			}

			$_GET['user'] = strip_tags($_GET['user']);
			$_GET['password'] = strip_tags($_GET['password']);

			$rows = $this->login_query($_GET['user'], md5($_GET['password']));

			if($this->Sql->Numrows > 0){

				unset($_SESSION['logged']);
				unset($_SESSION['object']);
				unset($_SESSION['UserData']);
				$role_id = $rows[0]['role_id'];

				$rows2 = $this->Sql->Query("select *, id as client_id from clients where user_id=".$rows[0]['user_id'], true);
				$rows = array_merge( $rows[0], $rows2[0]);

				$rows2 = $this->Sql->Query("select *, id as client_details_id from client_details  where client_id=".$rows['client_id'], true);
				$rows = array_merge( $rows, $rows2[0]);
				$rows['name'] = $rows['first_name'].' '.$rows['last_name'];

				if($this->Sql->Numrows > 0){

					$_SESSION['logged'] = true;
					$_SESSION['UserData'] = $rows;
					$_SESSION['UserData']['sess_id'] = $this->RandomString(25);

					$this->Sql->Query("INSERT INTO logs (`table_name`, `table_id`, `created_by`, `created_by_id`, `created_at`, `action`) VALUES ('users', ".$_SESSION['UserData']['user_id'].", '".$_SESSION['UserData']['user_name']."', ".$_SESSION['UserData']['user_id'].", NOW(), 'LOGIN')");
				}
			}
		}

		if(!$_SESSION['UserData']){

			$rows = $this->Sql->Query("SELECT *, id AS role_id FROM roles WHERE type = 'USER' ", true);

			unset($_SESSION['logged']);
			unset($_SESSION['object']);
			unset($_SESSION['UserData']);
			$role_id = $rows[0]['id'];

			$_SESSION['UserData'] = $rows[0];
			$_SESSION['UserData']['sess_id'] = $this->RandomString(25);
		}

		if($_GET['from_role_type']){

			$_SESSION['UserData']['from_role_type'] = $_GET['from_role_type'];
			$_SESSION['UserData']['from_user_id'] = $from_user_id;
		}

		$this->__Access($role_id);
	}

	function RandomString($length){

	    $array1=array(
		    'q','w','e','r','t','y','u','i','o','p','a','s','d',
			'f','g','h','j','k','z','x','c','v','b','n','m',
	        'Q','W','E','R','T','Y','U','O','P','A','S','D','F',
		    'G','H','J','K','Z','X','C','V','B','N','M');
	    $array2=array(1,2,3,4,5,6,7,8,9);

		if ($length>0) {

			$i=0;
	        $m=false;
		    while ($i<$length) {

			    srand((double)microtime()*10000000);
				$array=$m ? $array2 : $array1;
	            $arrayrandom=array_rand($array, 2);
		        $string.=$array[$arrayrandom[0]];
			    $m=!$m;
				$i++;
	        }
		}
	    return $string;
	}
}

?>