<?php
$aeupe_url= $_SERVER['HTTP_ORIGIN'].'/acis/ais/';
//print_r($aeupe_url);die;

//echo "<pre>";print_r($_SERVER);die;
if(file_exists('status'))
{
    $status = fopen('status','r');
    $stat = fgets($status);
    if($stat == '0')
    {
	echo 'Your Integral is deactivated yet. Please wait while we bring it up.';
	die();
    }
}
//error_reporting(E_ERROR | E_PARSE);
//if(!function_exists('pg_connect'))
//	echo 'Your version of PHP does not include PostgreSQL support.  <UL><LI>If you\'ve install AIS Integral on a Mac OS X machine, download and install the PHP and PostgreSQL packages from Marc Liyanage\'s <A HREF=http://www.entropy.ch>Entropy.ch</A> site.  <LI>If using Windows, open the php.ini file in a text editor like WordPad and remove the semi-colon before the line ";pg_sql.dll."<LI> If you\'re using a Linux or Unix server, you\'ll probably need to recompile PHP using the --with-pgsql option.</UL>';
$lock=false;
//echo "DEMO IS OFFLINE. SORRY FOR INCONVENIENCE!";
//die();


require_once('Basic.php');
include('googleapi/google/config1.php');


/*
if($lock && file_exists('install/index.php'))
{
//	rename('/home/atomov/www/integral/install','/home/atomov/www/integral/install_12');
	die("<HTML><HEAD><TITLE>"._('Delete the folder install')."</TITLE></HEAD><BODY><H1>"._('Delete the folder install')."</H1></BODY></HTML>");
}
elseif(!$lock && file_exists('install/index.php'))
header("Location: install/index.php");
*/ 

/*  ======== rakesh ===============*/
  if(isset($_REQUEST['Add_UserEmail_Btn']) && !empty($_REQUEST['Add_UserEmail_Btn'])){
		$_SESSION['imd_Uname'] ;
		switch($_REQUEST['table_type']){
       	  case 'stud':
        	 db_execute("UPDATE students SET CFIELD_2='".$_REQUEST['ADD_USER_EMAIL']."' WHERE username='".$_SESSION['imd_Uname']."'"); 
    	  	 break;
          case 'user':
        	 db_execute("UPDATE users SET email='".$_REQUEST['ADD_USER_EMAIL']."' WHERE username='".$_SESSION['imd_Uname']."'");
    	     break;     
        }	
}
 /* ========  rakesh  ============*/



if(!$_GET)
	array_rwalk($_REQUEST,'addslashes');

if($_REQUEST['servicefunction']=='QUIT')
{
	if($_SESSION['USER_NAME'] || $_SESSION['STUDENT_ID'])
	{
    	session_destroy();	
    	//echo '<a href="https://arrupe.ac.zw/acis/iomad/login/logout.php" style="display:none;" id="imd_logout">Logout</a>';
    	$site_urll = explode('ais'," https://". $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']))[0]; 
    	$site_urll =  $site_urll."iomad/login/logout.php";
    	echo '<a href="'.$site_urll.'" style="display:none;" id="imd_logout">Logout</a>';
    	?>
		<script type="text/javascript" language="javascript"> 
        
			function iomad_logout(){
            	var imd_logout = document.getElementById("imd_logout");
            	imd_logout.click();
            	 window.location.href = document.location.origin+'/acis/ais/index.php?servicefunction=QUIT';
			}
        
       		iomad_logout();
        
		</script>
		<?php
    	die;
		header("Location: $_SERVER[PHP_SELF]?servicefunction=QUIT".(($_REQUEST['reason'])?'&reason='.$_REQUEST['reason']:''));
    	
		exit;
	}
}


if($DBType == 'mssql')
    if(Preferences('LOGIN_DATE_FORMAT')=='12')
	$LoginDateFormat = 'Month d, HH12:MI AM';
    else
	$LoginDateFormat = 'Month d, HH24:MI';
else
{
    if(Preferences('LOGIN_DATE_FORMAT')=='12')
	$LoginDateFormat = 'Month DD, HH12:MI AM';
    else
	$LoginDateFormat = 'Month DD, HH24:MI';
}


                                                            /****google api connection*/


 if(isset($_GET['code'])){
//print_r($_GET['code']);die('jhbgjfbgjkbgjk');


 	if(strlen($_GET['code']) > 5){
		if($googleClient->authenticate($_GET['code'])){  
      
 			$_SESSION['token'] = $googleClient->getAccessToken();
       // print_r($_SESSION['token']);die;
       // print_r($_SESSION['token']);die;
        
 			//header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL));
 			$token = $googleClient->getAccessToken();
      //  print_r($token);die;
       // print_r($token);die;
 			$googleClient->setAccessToken($token);
       // print_r($googleClient);die;
 			if ($googleClient->getAccessToken()) {
    			$gpUserProfile 	= 	$google_oauthV2->userinfo->get();
            //print_r($gpUserProfile);die;
    			$email 			= 	$gpUserProfile['email'];
            	
           
    			$first_name 	=	strtolower($gpUserProfile['given_name']);
    			$last_name 		=	strtolower($gpUserProfile['family_name']);
 
                $UserData 		= 	db_request(db_execute("Select * from users where email='".$email."'"));
           // print_r($UserData);die;
                $StudentData 	= 	db_request(db_execute("Select * from students where CFIELD_2='".$email."'"));
    
      
    			if($UserData){
      
    			$_REQUEST['USER_NAME'] =$UserData[1]['USERNAME'];
    			$_REQUEST['USER_PASSWORD'] =$UserData[1]['PASSWORD'];
      
    			}
    			elseif($StudentData){  
   
                $student_username = str_replace(' ', '', $StudentData[1]['USERNAME']);
                $student_password = str_replace(' ', '', $StudentData[1]['PASSWORD']);
              	$_REQUEST['USER_NAME'] = $student_username;
        	    $_REQUEST['USER_PASSWORD'] =$student_password; 
           
               // header (" Location :https:www.arrupe.ac.zw/acis/ais/index.php?USER_NAME=".$_REQUEST['USER_NAME']."&USER_PASSWORD=".$_REQUEST['USER_PASSWORD']);

     			}
            	else {
                	// if(count($UserData) == 0){
                    	if(count($StudentData) == 0){
                        
                  $student_password2 = strtolower($first_name.$last_name.'@123');
                  $string_pass =  strtolower($student_password2); 
                  $student_password = str_replace(' ', '', $string_pass);
                  $user_name2 =  strtolower($gpUserProfile['given_name']); 
                  $user_name = str_replace(' ', '', $user_name2); 
                  $id_query = "select max(student_id) from students";
                  $id_query_data =  db_request(db_execute($id_query));    
                  $student_id2 =  $id_query_data[1]['MAX'];   
                  $student_id3 = $student_id2+1;      
           
 	     $student_id = db_request(db_execute("INSERT INTO STUDENTS(STUDENT_ID,cfield_14,last_name,middle_name,first_name,cfield_2,username,password,cfield_7,
			cfield_25,cfield_8,cfield_95,cfield_96,cfield_97,cfield_15,cfield_50002,profile,LAST_LOGIN) 
			VALUES('".$student_id3."','', '".$last_name."','".$last_name."', '".$first_name."','".$email."','".$user_name."','".$student_password."',
			'','','','', 
			'','', '', '', 'student', current_timestamp) RETURNING student_id"));

                // ADDRESS
        	$address_id = db_request(db_execute("INSERT INTO ADDRESS (ADDRESS_ID,address,city,state,zipcode,Phone,force_password_change)
        	values(".db_seq_nextval('ADDRESS_SEQ').",'Test Address','Test City','Test State','133201',
        	'1234567890','Y') RETURNING address_id"));  


                // STUDENTS_IN_ADDRESS
        	$stud_address_id = db_request(db_execute("INSERT INTO students_in_address (id,student_id,address_id,residence)
        	values(".db_seq_nextval('STUDENTS_IN_ADDRESS_SEQ').",'".$student_id[1]['STUDENT_ID']."','".$address_id[1]['ADDRESS_ID']."','Y') RETURNING id"));
            //echo "<pre>";print_r($stud_address_id); echo "</pre>";


            // student_registration
        	$class_level_data = db_request(db_execute("select * from school_classlevels where title='BAUZYR3'"));
        	$school_calendars = db_request(db_execute("select * from school_calendars where SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' "));

                        
        	$res_sql = "INSERT INTO STUDENT_REGISTRATION (ID,SCHOOL_YEAR,SCHOOL_ID,STUDENT_ID,CLASSLEVEL_ID,calendar_id,start_date,next_school)
        	values(".db_seq_nextval('STUDENT_REGISTRATION_SEQ').",'".get_school_year()."','".get_school_id()."','".$student_id[1]['STUDENT_ID']."',
        	".$class_level_data[1]['ID'].",'".$school_calendars[1]['CALENDAR_ID']."','".date('Y-m-d')."','".get_school_id()."') RETURNING id";
        	$stud_registration = db_request(db_execute($res_sql)); 
                        
                        
                    $_REQUEST['USER_NAME'] =  $user_name;
         			$_REQUEST['USER_PASSWORD'] = $student_password;
        	if(empty($res_sql) ){
        	$failed_users[] = $val['Login name'];
        	echo "Something Went Wrong...";
        	} else {
        	$success_users[] = $val['Login name'];
        	echo "User Created Successfully";
        	}
                        

                        } 
                
                }

 			}
    	}
    }
 
 }
                            /* Google api end */




// if (isset($_SESSION['token'])) {
//    $googleClient->setAccessToken($_SESSION['token']);
// }

//print_r($_REQUEST);die;

//die;

if($_REQUEST['USER_NAME'] && $_REQUEST['USER_PASSWORD'])
{

    $error_message = '';
	// 	$con = pg_connect("host=$DBServer dbname=$DBName user=$DBUsername password=$DBPassword") or die("Cannot connect to database");

	// 	$query = "SELECT ID,TIME_UNLOCK,FAILED_LOGIN FROM BLOCK_IP WHERE DATE = '".date("Y-m-d")."' AND IP = '".$_SERVER['REMOTE_ADDR']."'";
	// 	$count_failed = pg_query($con, $query) or die("Cannot execute query: $query\n");
	$count_failed  = db_request(db_execute("SELECT ID,TIME_UNLOCK,FAILED_LOGIN FROM BLOCK_IP WHERE DATE = '".date("Y-m-d")."' AND IP = '".$_SERVER['REMOTE_ADDR']."'"));
          //print_r($count_failed);die;        
		
    if($count_failed[1]['TIME_UNLOCK']<>'')
    {
        $sec = intval(intval(strtotime($count_failed[1]['TIME_UNLOCK']))-intval(strtotime(date('Y-m-d H:i:s'))));
        $h = intval($sec / 3600);
        $m = intval($sec / 60) % 60;
        $s = intval($sec % 60);
        if(strlen($s) == 1) $s ='0'.$s;
        if(strlen($m) == 1) $m ='0'.$m;
        $tleft = $h.':'.$m.':'.$s;
        if(strtotime($count_failed[1]['TIME_UNLOCK'])>strtotime(date('Y-m-d H:i:s')))
        {
            $error_message= (_("You can't re-login again until ").$count_failed[1]['TIME_UNLOCK']).' '._('Time left: ').$tleft;
        }
        else
        {
            db_execute("UPDATE BLOCK_IP SET FAILED_LOGIN = NULL,TIME_UNLOCK = NULL WHERE DATE = '".date('Y-m-d')."' AND IP = '".$_SERVER['REMOTE_ADDR']."'");
        }
    }
    if($error_message == ''){
    		//die('rrrr');
    	
    //print_r($_LDAP['auth']);die;
        if($_LDAP['auth']==true){
        //die('ssssss');
			$try_db_auth = false;
			ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
			$ldap_QI = ldap_connect($_LDAP['host'],$_LDAP['port']) or die('no connect');
        	$LOGINSUCCESSFUL = ldap_bind($ldap_QI,str_replace("\'","'",$_REQUEST['USER_NAME']).$_LDAP['suffix'],str_replace("\'","'",$_REQUEST['USER_PASSWORD']));
				
        if(!$LOGINSUCCESSFUL && $addonPath && file_exists($addonPath.'/authentification.php'))
			include($addonPath.'/authentification.php');

		if($LOGINSUCCESSFUL)
		{
     
			$_REQUEST['USER_NAME'] = DBEscapeString($_REQUEST['USER_NAME']);

   
        	//echo "<pre>";print_r($_REQUEST);die;
			/*
			$login_array = db_request(db_execute(
				"SELECT USERNAME,PROFILE,USER_ID,".db_to_char('LAST_LOGIN', $LoginDateFormat)." AS LAST_LOGIN FROM USERS
				WHERE SCHOOL_YEAR='".$DefaultYear."' AND
					LOWER(USERNAME)='".strtolower($_REQUEST['USER_NAME'])."'"
			));
			*/
			$login_array = db_request(db_execute("SELECT USERNAME,PROFILE,PROFILE_ID,USER_ID,".db_to_char('LAST_LOGIN', $LoginDateFormat)." AS LAST_LOGIN FROM USERS WHERE LOWER(USERNAME)='".strtolower($_REQUEST['USER_NAME'])."'"));
			//print_r($login_array);die;
        	$_SESSION['WORK_DATE'] = get_db_date();
			$student_array = db_request(db_execute("SELECT USERNAME,PROFILE_ID,STUDENT_ID,".db_to_char('LAST_LOGIN',$LoginDateFormat)." AS LAST_LOGIN FROM STUDENTS WHERE LOWER(USERNAME)='".strtolower($_REQUEST['USER_NAME'])."'"));
			$address_array = db_request(db_execute("SELECT a.USERNAME,a.PROFILE_ID,a.FORCE_PASSWORD_CHANGE,a.ADDRESS_ID,".db_to_char('a.LAST_LOGIN',$LoginDateFormat)." AS LAST_LOGIN,a.FAILED_LOGIN FROM ADDRESS a WHERE LOWER(a.USERNAME)=LOWER('$_REQUEST[USER_NAME]')"));
 
			if(strtoupper($login_array[1]['USERNAME'])==strtoupper(str_replace("''","'",$_REQUEST['USER_NAME'])) && $login_array[1]['PROFILE']!='none')
			{
				$_SESSION['LAST_LOGIN'] = $login_array[1]['LAST_LOGIN'];
				$_SESSION['USER_NAME'] = str_replace("'","''",$login_array[1]['USERNAME']);
				$_SESSION['USER_ID'] = $login_array[1]['USER_ID'];
				$_SESSION['USER_PASSWORD'] = $_REQUEST['USER_PASSWORD']; // used for webmail
				db_execute("UPDATE USERS SET LAST_LOGIN='".get_db_date('timestamp')."',FAILED_LOGIN=NULL WHERE USER_ID='".$login_array[1]['USER_ID']."'");
			}
			elseif(strtoupper($student_array[1]['USERNAME'])==strtoupper(str_replace("''","'",$_REQUEST['USER_NAME'])))
			{
          
				$_SESSION['STUDENT_ID'] = $student_array[1]['STUDENT_ID'];
				$_SESSION['USER_NAME'] = str_replace("'","''",$student_array[1]['USERNAME']);
				$_SESSION['LAST_LOGIN'] = $student_array[1]['LAST_LOGIN'];
				$_SESSION['USER_PASSWORD'] = $_REQUEST['USER_PASSWORD']; // used for webmail
				db_execute("UPDATE STUDENTS SET LAST_LOGIN='".get_db_date('timestamp')."' WHERE STUDENT_ID='".$student_array[1]['STUDENT_ID']."'");
			}
			elseif(strtoupper($address_array[1]['USERNAME'])==strtoupper(str_replace("''","'",$_REQUEST['USER_NAME'])))
			{
				$_SESSION['ADDRESS_ID'] = $address_array[1]['ADDRESS_ID'];
				$_SESSION['USER_NAME'] = str_replace("'","''",$address_array[1]['USERNAME']);
				$_SESSION['LAST_LOGIN'] = $address_array[1]['LAST_LOGIN'];
				$_SESSION['USER_PASSWORD'] = $_REQUEST['USER_PASSWORD']; // used for webmail
				db_execute("UPDATE ADDRESS SET LAST_LOGIN='".get_db_date('timestamp')."' WHERE ADDRESS_ID='".$address_array[1]['ADDRESS_ID']."'");
			}

			if($_REQUEST['servicefunction']!='SUCCESS')
			{
            	//echo "helllooo"; die;
     
				header("Location: index.php?servicefunction=SUCCESS");
				exit;
			}
		}
		else
			$try_db_auth = true;
	}
	
	if($_LDAP['auth']!==true || $try_db_auth==true )
	{
	//die('test');
		$_REQUEST['USER_NAME'] = DBEscapeString($_REQUEST['USER_NAME']);
		$_REQUEST['USER_PASSWORD'] = DBEscapeString($_REQUEST['USER_PASSWORD']);
    
      /*===================== rakesh - Session Variable  START =======================*/
//      echo $_SESSION['imd_Uname'];
//    echo $_SESSION['imd_Upswd'];
// exit('testing');
        	$_SESSION['imd_Uname'] = $_REQUEST['USER_NAME'] ;
			//print_r($_SESSION['imd_Uname']);die;
        	$_SESSION['imd_Upswd'] = $_REQUEST['USER_PASSWORD'];
   
        //echo "<pre>";print_r($_SESSION);die;
      /*===================== rakesh - Session Variable  END =======================*/
        
    
      /*===================== rakesh - iomad user exist checking  START =======================*/
   		$aeupe_url = $_SERVER['HTTP_ORIGIN'].'/acis/ais/';
        $username = $_SESSION['imd_Uname'];
        $pswd = $_SESSION['imd_Upswd'];
        $iomad_userDataQuery = "SELECT * FROM mdl_user WHERE username ='".$username."' ";
 
    
   // print_r($iomad_userDataQuery);die;
    
        $iomad_userData = pg_query($iomadDBconn, $iomad_userDataQuery);
		$iomad_userDetials = pg_fetch_all($iomad_userData);
    	$auepe_UserData = db_request(db_execute("Select * from users where username='".$username."'"));
    
    	$auepe_StudentData = db_request(db_execute("Select * from students where username='".$username."'"));
  //    echo "<pre>";
  // print_r($auepe_StudentData);die;
   
    	if(isset($auepe_UserData[1]['EMAIL']) && !empty($auepe_UserData[1]['EMAIL'])){
        	$imd_UpdEmail = $auepe_UserData[1]['EMAIL'];
        
        } elseif(isset($auepe_StudentData[1]['CFIELD_2']) && !empty($auepe_StudentData[1]['CFIELD_2'])){
            $imd_UpdEmail = $auepe_StudentData[1]['CFIELD_2'];
       // exit('testing2');
        }
       		// user doesn't exists
    //echo "<pre>"; print_r($iomad_userDetials);die;
        if(empty($iomad_userDetials)){ 
        
          // echo "<pre>"; print_r($iomad_userDetials);die('if empty userdetails');
        	$form2_data =   db_request(db_execute("select * from form2 where id='9'"));
        	$courseData_Iomad = array();
        	$courseData_Iomad['domain'] = $form2_data[1]['URL'] ;
            $courseData_Iomad['token'] = $form2_data[1]['TOKEN'] ;  
           // $courseData_Iomad['token'] = "62156ea14d3633d410915dfd804bf1c8" ;  
            $courseData_Iomad['function'] = "core_user_create_users";        
        	if(!empty($auepe_UserData)){
            	if(empty($auepe_UserData[1]['EMAIL']) ){  
               
                 header("Location:".$aeupe_url."modules/mod_ssetup/add_email.php?type=user");
				 exit;	 
                
                } else {

                    $courseData_Iomad['USERNAME'] = $auepe_UserData[1]['USERNAME'] ;
            		$courseData_Iomad['PASSWORD'] = strtolower($auepe_UserData[1]['PASSWORD']);
            		$courseData_Iomad['FIRST_NAME'] = strtolower($auepe_UserData[1]['FIRST_NAME']) ;
            		$courseData_Iomad['MIDDLE_NAME'] = (empty($auepe_UserData[1]['MIDDLE_NAME'] ))?'middlename':$auepe_UserData[1]['MIDDLE_NAME'] ;
            		$courseData_Iomad['LAST_NAME'] = $auepe_UserData[1]['LAST_NAME'] ;
            		$courseData_Iomad['EMAIL'] = $auepe_UserData[1]['EMAIL'] ;
                	$courseData_Iomad['idnumber'] = $auepe_UserData[1]['EMAIL'] ; 
                
                }
            	
            }
        
        	if(!empty($auepe_StudentData) ){           
            	if(empty($auepe_StudentData[1]['CFIELD_2']) ){
            
                	header("Location:".$aeupe_url."modules/mod_ssetup/add_email.php?type=stud");
					exit;
            		
               	 } else {
                	//echo "<pre>";print_r($auepe_StudentData);die;
                	$courseData_Iomad['USERNAME'] =  strtolower($auepe_StudentData[1]['USERNAME']) ;
            		$courseData_Iomad['PASSWORD'] = strtolower($auepe_StudentData[1]['PASSWORD']) ;
            		$courseData_Iomad['FIRST_NAME'] = strtolower($auepe_StudentData[1]['FIRST_NAME']) ;
            		$courseData_Iomad['MIDDLE_NAME'] = (empty($auepe_StudentData[1]['MIDDLE_NAME'] ))?'middlename':$auepe_StudentData[1]['MIDDLE_NAME'] ;
            		$courseData_Iomad['LAST_NAME'] = strtolower($auepe_StudentData[1]['LAST_NAME']) ;
            		$courseData_Iomad['EMAIL'] = $auepe_StudentData[1]['CFIELD_2'] ; 
            		$courseData_Iomad['idnumber'] = $auepe_StudentData[1]['CFIELD_2'] ; 
            
                	//echo "<pre>";print_r($courseData_Iomad);die('ssssss');
                }
            	
            }
        //echo "<pre>";print_r($courseData_Iomad);die;
        	include_once($staticpath.'iomadAPI/oldUser.php');   
        	    //die('heelleleojjiiiiii');
        
        } else {  
        	//echo $imd_UpdEmail;
         //echo "<br>data iomad found";die;
                   // echo "<pre>"; print_r($iomad_userDetials);die('else  userdetails');     	
        
        	$iomad_UserPswd = $iomad_userDetials[0]['password'];
        	$iomad_userUpdateQuery = "UPDATE mdl_user SET password='".md5($pswd)."', email='".$imd_UpdEmail."'   WHERE username='".$username ."'  ";
        	$iomad_userUpdateData = pg_query($iomadDBconn, $iomad_userUpdateQuery); 
  
        }

      /*===================== rakesh - iomad user exist checking end =======================*/
        
    
    
    
//echo "<pre>"; print_r($_REQUEST);die;
		//		$login_array = db_request(db_execute("SELECT USERNAME,PROFILE,FORCE_PASSWORD_CHANGE,USER_ID,".db_to_char('LAST_LOGIN',$LoginDateFormat)." AS LAST_LOGIN,FAILED_LOGIN FROM USERS WHERE SCHOOL_YEAR='$DefaultYear' AND LOWER(USERNAME)=LOWER('$_REQUEST[USER_NAME]') AND LOWER(PASSWORD)=LOWER('$_REQUEST[USER_PASSWORD]')"));
		
		
		$login_array = db_request(db_execute("SELECT USERNAME,PROFILE,PROFILE_ID,FORCE_PASSWORD_CHANGE,USER_ID,".db_to_char('LAST_LOGIN',$LoginDateFormat)." AS LAST_LOGIN,FAILED_LOGIN FROM USERS WHERE LOWER(USERNAME)=LOWER('$_REQUEST[USER_NAME]') AND LOWER(PASSWORD)=LOWER('".(($_Config['EncriptPassword'])?Encript($_REQUEST['USER_PASSWORD']):$_REQUEST['USER_PASSWORD'])."')"));
		$student_array = db_request(db_execute("SELECT s.USERNAME,s.FORCE_PASSWORD_CHANGE,s.PROFILE,s.PROFILE_ID,s.STUDENT_ID,".db_to_char('s.LAST_LOGIN',$LoginDateFormat)." AS LAST_LOGIN,s.FAILED_LOGIN FROM STUDENTS s,STUDENT_REGISTRATION se WHERE LOWER(s.USERNAME)=LOWER('$_REQUEST[USER_NAME]') AND LOWER(s.PASSWORD)=LOWER('".(($_Config['EncriptPassword'])?Encript($_REQUEST['USER_PASSWORD']):$_REQUEST['USER_PASSWORD'])."') AND se.STUDENT_ID=s.STUDENT_ID AND se.SCHOOL_YEAR=$DefaultYear AND ('".get_db_date()."' BETWEEN se.START_DATE AND se.END_DATE OR se.END_DATE IS NULL)"));
		$address_array = db_request(db_execute("SELECT a.USERNAME,a.FORCE_PASSWORD_CHANGE,a.ADDRESS_ID,".db_to_char('a.LAST_LOGIN',$LoginDateFormat)." AS LAST_LOGIN,a.FAILED_LOGIN FROM ADDRESS a WHERE LOWER(a.USERNAME)=LOWER('$_REQUEST[USER_NAME]') AND LOWER(a.PASSWORD)=LOWER('".(($_Config['EncriptPassword'])?Encript($_REQUEST['USER_PASSWORD']):$_REQUEST['USER_PASSWORD'])."')"));
		$_SESSION['WORK_DATE'] = get_db_date();
//print_r($student_array);die;
		if(!$login_array && !$student_array && !$address_array && $AdminsGroup)
		{
        
			$admin_array = db_request(db_execute("SELECT USER_ID FROM USERS WHERE PROFILE='admin' AND USER_ID IN ($AdminsGroup) AND UPPER(PASSWORD)=UPPER('".(($_Config['EncriptPassword'])?Encript($_REQUEST['USER_PASSWORD']):$_REQUEST['USER_PASSWORD'])."')"));
			if($admin_array)
			{
				$login_array = db_request(db_execute("SELECT USERNAME,PROFILE,PROFILE_ID,USER_ID,LAST_LOGIN,FAILED_LOGIN FROM USERS WHERE LOWER(USERNAME)=LOWER('$_REQUEST[USER_NAME]')"));
				$student_array = db_request(db_execute("SELECT s.USERNAME,s.STUDENT_ID,s.PROFILE,s.PROFILE_ID,s.LAST_LOGIN,s.FAILED_LOGIN FROM STUDENTS s,STUDENT_REGISTRATION se WHERE LOWER(s.USERNAME)=LOWER('$_REQUEST[USER_NAME]') AND se.STUDENT_ID=s.STUDENT_ID AND se.SCHOOL_YEAR=$DefaultYear AND ('".get_db_date()."' BETWEEN se.START_DATE AND se.END_DATE OR se.END_DATE IS NULL)"));
				$address_array = db_request(db_execute("SELECT a.USERNAME,a.PROFILE_ID,a.ADDRESS_ID,".db_to_char('a.LAST_LOGIN',$LoginDateFormat)." AS LAST_LOGIN,a.FAILED_LOGIN FROM ADDRESS a WHERE LOWER(a.USERNAME)=LOWER('$_REQUEST[USER_NAME]') "));
			}
		}

    	if($student_array && $student_array[1]['PROFILE']!='none')
		{  
         
   //   print_r($login_array);die;
			$_SESSION['USER_NAME'] = str_replace("'","''",$student_array[1]['USERNAME']);
			$_SESSION['USER_ID'] = $student_array[1]['USER_ID'];
                        LoginHistory(_('Success'),$student_array[1]['USER_ID'],$student_array[1]['USERNAME'],$student_array[1]['PROFILE_ID']);
			$_SESSION['LAST_LOGIN'] = $student_array[1]['LAST_LOGIN'];
			$failed_login = $student_array[1]['FAILED_LOGIN'];
         
			if($admin_array)
				db_execute("UPDATE USERS SET LAST_LOGIN='".get_db_date('timestamp')."' WHERE USER_ID='".$admin_array[1]['USER_ID']."'");
           
			else
				db_execute("UPDATE USERS SET LAST_LOGIN='".get_db_date('timestamp')."',FAILED_LOGIN=NULL WHERE USER_ID='".$student_array[1]['USER_ID']."'");

			$LOGINSUCCESSFUL = 1;
			//print_r($_REQUEST);die;
			if($_REQUEST['servicefunction']!='SUCCESS')
			{
         
				if($_LDAP['auth']!=true && ($login_array[1]['FORCE_PASSWORD_CHANGE'] == 'Y' || $student_array[1]['FORCE_PASSWORD_CHANGE'] == 'Y' || $address_array[1]['FORCE_PASSWORD_CHANGE'] == 'Y'))
				{
                    
				    echo "
					<HTML>
					    <HEAD><TITLE>".$GeneralTitle."</TITLE></HEAD>";
				    echo "<noscript><META http-equiv=REFRESH content='0';url=index.php?servicefunction=QUIT&reason=javascript' /></noscript>";
				    echo "<frameset id=mainframeset rows='*,32' border=0 framespacing=0 frameborder=0>
					<frame name='body' onbeforeunload='return check_rb_state();' src='modloader.php?servicemod=mod_users/UsrPrefnProper.php&tab=password' frameborder='1' />
					<frame name='fr_bottom' src='footermenu.php' />
					    </frameset>
					</HTML>";
				    exit;
				}else{
				    //header("Location: index.php?servicefunction=SUCCESS");
            // print_r($student_array);die; 
				     //exit;
				}
			}
		}
    
    
    
		if($login_array && $login_array[1]['PROFILE']!='none')
		{  
         
   //   print_r($login_array);die;
			$_SESSION['USER_NAME'] = str_replace("'","''",$login_array[1]['USERNAME']);
			$_SESSION['USER_ID'] = $login_array[1]['USER_ID'];
                        LoginHistory(_('Success'),$login_array[1]['USER_ID'],$login_array[1]['USERNAME'],$login_array[1]['PROFILE_ID']);
			$_SESSION['LAST_LOGIN'] = $login_array[1]['LAST_LOGIN'];
			$failed_login = $login_array[1]['FAILED_LOGIN'];
         
			if($admin_array)
				db_execute("UPDATE USERS SET LAST_LOGIN='".get_db_date('timestamp')."' WHERE USER_ID='".$admin_array[1]['USER_ID']."'");
           
			else
				db_execute("UPDATE USERS SET LAST_LOGIN='".get_db_date('timestamp')."',FAILED_LOGIN=NULL WHERE USER_ID='".$login_array[1]['USER_ID']."'");

			$LOGINSUCCESSFUL = 1;
			
			if($_REQUEST['servicefunction']!='SUCCESS')
			{
         
				if($_LDAP['auth']!=true && ($login_array[1]['FORCE_PASSWORD_CHANGE'] == 'Y' || $student_array[1]['FORCE_PASSWORD_CHANGE'] == 'Y' || $address_array[1]['FORCE_PASSWORD_CHANGE'] == 'Y'))
				{
                    
				    echo "
					<HTML>
					    <HEAD><TITLE>".$GeneralTitle."</TITLE></HEAD>";
				    echo "<noscript><META http-equiv=REFRESH content='0';url=index.php?servicefunction=QUIT&reason=javascript' /></noscript>";
				    echo "<frameset id=mainframeset rows='*,32' border=0 framespacing=0 frameborder=0>
					<frame name='body' onbeforeunload='return check_rb_state();' src='modloader.php?servicemod=mod_users/UsrPrefnProper.php&tab=password' frameborder='1' />
					<frame name='fr_bottom' src='footermenu.php' />
					    </frameset>
					</HTML>";
				    exit;
				}else{
				   header("Location: index.php?servicefunction=SUCCESS");
                
				    exit;
				}
			}
		}
	}
//die('jjjj');
	if(!$LOGINSUCCESSFUL && $login_array[1]['PROFILE']=='none')
		$error[] = _("Your account has not yet been activated.  When your account has been verified by school administration, you will be notified by email.");
	elseif(strtoupper($student_array[1]['USERNAME'])==strtoupper($_REQUEST['USER_NAME']))
	{
   
		$_SESSION['STUDENT_ID'] = $student_array[1]['STUDENT_ID'];
		$_SESSION['USER_NAME'] = str_replace("'","''",$student_array[1]['USERNAME']);
		$_SESSION['LAST_LOGIN'] = $student_array[1]['LAST_LOGIN'];
		db_execute("UPDATE STUDENTS SET LAST_LOGIN='".get_db_date('timestamp')."' WHERE STUDENT_ID='".$student_array[1]['STUDENT_ID']."'");
                LoginHistory(_('Success'),$student_array[1]['STUDENT_ID'],strtoupper($_REQUEST['USER_NAME']),$student_array[1]['PROFILE']);
	}
	elseif(strtoupper($address_array[1]['USERNAME'])==strtoupper($_REQUEST['USER_NAME']))
	{
		$_SESSION['ADDRESS_ID'] = $address_array[1]['ADDRESS_ID'];
		$_SESSION['USER_NAME'] = str_replace("'","''",$address_array[1]['USERNAME']);
		$_SESSION['LAST_LOGIN'] = $address_array[1]['LAST_LOGIN'];
		db_execute("UPDATE ADDRESS SET LAST_LOGIN='".get_db_date('timestamp')."' WHERE ADDRESS_ID='".$address_array[1]['ADDRESS_ID']."'");
                LoginHistory(_('Success'),$address_array[1]['ADDRESS_ID'],strtoupper($_REQUEST['USER_NAME']),'Parent');
	}
	else
        {
            
            if($error_message == '')
            {
                $count_failed  = db_request(db_execute("SELECT ID,FAILED_LOGIN FROM BLOCK_IP WHERE DATE = '".date("Y-m-d")."' AND IP = '".$_SERVER['REMOTE_ADDR']."'"));
                if($count_failed[1]['ID']<>'')
                    $count_id = $count_failed[1]['ID'];
                $count_failed = intval($count_failed[1]['FAILED_LOGIN']);
                $count_failed++;
                if(!isset($_Config['AMOUNT_OF_LOGIN_ATEMPTS'])) $_Config['AMOUNT_OF_LOGIN_ATEMPTS'] = 1000;
                if($count_failed > $_Config['AMOUNT_OF_LOGIN_ATEMPTS'])
                {
                    if((date('H')+3)>24)
                    {
                	if(date("d") == '31')
                	    $uday = date("d");
                	else
                    	    $uday = date("d") + 1;
                        $uday = ($uday<10)?'0'.$uday:$uday;
                        $uhour = (date('H')+3) - 24;
                        $uhour = ($uhour<10)?'0'.$uhour:$uhour;
                    }
                    else
                    {
                        $uhour = (date('H')+3);
                        $uday = ($uday<10)?'0'.$uday:$uday;
                        $uday = date("d");
                        $uhour = ($uhour<10)?'0'.$uhour:$uhour;
                    }
                    if($uhour == '24') $uhour = '0';
                    $time_unlock  = date('Y-m-').$uday.' '.$uhour.date(':i:s');                    
                    db_execute("UPDATE BLOCK_IP SET FAILED_LOGIN = NULL,TIME_UNLOCK = '".$time_unlock."' WHERE IP = '".$_SERVER['REMOTE_ADDR']."'");
                    echo "UPDATE BLOCK_IP SET FAILED_LOGIN = NULL,TIME_UNLOCK = '".$time_unlock."' WHERE IP = '".$_SERVER['REMOTE_ADDR']."'";
                    LoginHistory(_('Block by IP'),false,$_REQUEST['USER_NAME']);
                }
                else
                {
                    if(!$count_id)
                        db_execute("INSERT INTO BLOCK_IP (DATE,FAILED_LOGIN,TIME_UNLOCK,IP) VALUES ('".date("Y-m-d")."','".$count_failed."',NULL,'".$_SERVER['REMOTE_ADDR']."')");
                    else
                        db_execute("UPDATE BLOCK_IP SET FAILED_LOGIN = '".$count_failed."',TIME_UNLOCK = NULL WHERE ID = '$count_id' ");
                }
                LoginHistory(_('Failed'),false,strtoupper($_REQUEST['USER_NAME']),'none');
                $error[] = _("Incorrect login name or password.<BR>Check login name and password then try again.");
            }
            else
                $error[] = $error_message;
                
        }
    }
    else
        $error[] = $error_message;
}
elseif($_REQUEST['USER_NAME']<>'')
{
    LoginHistory(_('Failed'),false,$_REQUEST['USER_NAME']);
}
if(get_user('PROFILE')=='applicant')
    $_SESSION['is_applicant'] = 'applicant';

if($_REQUEST['servicefunction']=='create_user_account')
{
//exit('user create');
	$_SYSTEM['allow_edit'] = true;
	if($_REQUEST['user']['USERNAME'])
		$_REQUEST['servicefunction'] = 'update';
	else
		$_REQUEST['user_id'] = 'new';
	include('modules/mod_users/Users.php');

	if(!$_REQUEST['user']['USERNAME'])
		Basic('footer_plain');
	else
	{
		$note[] = _('Your account has been created.  You will be notified by email when it is verified by school administration and you can log in.');
		session_destroy();
	}
}

if(!$_SESSION['USER_NAME'] && !$_SESSION['STUDENT_ID'] && $_REQUEST['servicefunction']!='create_account')
{
	if($_SESSION['login_REQUEST'])
		$error[] = '<CENTER>'._("Your session has timed out. If you log in right away,<BR> you can return to your last location without losing any data.").'<CENTER>';

	Basic('header');
	$result = db_execute("SELECT * FROM LH_TEMPLATES WHERE TITLE = 'login';");
	if($plogin = db_request($result))
	{
		echo $plogin[1]['HEADER'];
		
		if($_REQUEST['reason'])
			$note[] = _('You must have javascript enabled to use AIS Integral.');
		//$content .= ErrorMessage($error,'Error');
		echo '<font color=red><B>'.$error[0].'</b></font>';
		echo ErrorMessage($note,'Note');

		echo "<form name=loginform method='post' action='index.php'><table><tr>";
		echo "<td>"._('Login Name')."</td><td><input type='text' name='USER_NAME' size='25' maxlength='25' /></td></tr><tr>";
		echo "<td>"._('Password')."</td><td><input type='password' name='USER_PASSWORD' size='25' maxlength='25' />";
		echo "<INPUT type=submit value='"._('Login')."'></td></tr>";
		echo "</table></form>";
		echo "<BR><center><small><A HREF=http://www.jesuits-africa.education>ACIS</A> version $IntegralVersion &copy; 2009-".date('Y')."</small></center>";
		echo $plogin[1]['FOOTER'];		
	}
	else
	{
		echo "<BODY height=100% leftmargin=0 marginwidth=0 style='margin-top:20;margin-bottom:0;' background=themes/".Preferences('HIGHLIGHT_MENU')."/bg_dark.png onLoad='document.loginform.USER_NAME.focus()'>";
		echo '<CENTER>';
		echo '<TABLE height=100% width=100% align=center bgcolor=white><TR><TD height=100% width=100% valign=top align=center>';
		echo '<BR><BR>';
	
    
   
    $loginURL	=	"";
    	$authUrl 	= 	$googleClient->createAuthUrl();
    	$loginURL 	= 	filter_var($authUrl, FILTER_SANITIZE_URL);
   // print_r($loginURL);die;
       
  //  print_r($loginURL);
    /** google api connection end**/
    
    
    
		$content = '';
		$content_login = '';
	
		$content_login .= "<form name=loginform method='post' action='index.php'>
		<center><table border='0' cellspacing='0' cellpadding='5'>
		<tr>
			<td align=".ALIGN_RIGHT." colspan=2>";
		$content .= DrawPNG('../images/themes/logo_new.png','border=0');
		$content .= '<BR><BR><font size=-2 color=gray>'.$GeneralTitle.'</font>';

		$content .= '<BR><BR>';
		if($_REQUEST['reason'])
			$note[] = _('You must have javascript enabled to use AIS Integral.');

		$content_login .= '<font color=red><B>'.$error[0].'</b></font>';
		$content_login .= ErrorMessage($note,'Note');
		$content_login .= '</td></tr>';
		$content_login .= "<tr>
			<td align=".ALIGN_RIGHT."><font color=gray><b>"._('Login Name')."</b></font></td>
			<td align=".ALIGN_LEFT."><input type='text' name='USER_NAME' size='25' maxlength='25' /></td>
		</tr>
		<tr>
			<td align=".ALIGN_RIGHT."><font color=gray><b>"._('Password')."</b></font></td>
			<td align=".ALIGN_LEFT."><input type='password' name='USER_PASSWORD' size='25' maxlength='25' /></td>
		</tr>



<tr>
        
        <a href=".$loginURL.">
        <!--<img src='https://miro.medium.com/max/552/1*HHM0sJKRnksQxoEebvbZmQ.png' width=40%>-->
        <img src='https://jesuits-africa.education/wp-content/uploads/2021/09/loginpix.png' width=60%> 
 	<!-- <img src='https://support.clever.com/hc/article_attachments/360054105332/google.png' height=20% width=35%>-->
        </a>
        </tr>
		<td align=".'CENTER'." colspan=2><INPUT type=submit value='"._('Login')."'></td>

		</table></center>";
		if($ShowCreateAccount)
			$content_login .= "<center><font size=-1 color=black>[ <A HREF=index.php?servicefunction=create_account>Create Account</A> ]</font></center>";
		$content_login .= '</form>';
		//$content .= '<IMG SRC=images/pixel_trans.gif height=1 width=400>';
	
		echo $content;
		echo '<TABLE height=10% width=50% align=center bgcolor=white><TR><TD height=100% width=100% valign=top align=center bgcolor=white>';
		echo DisplayBlock(_('JVC Authorization: Protect Your Login Details'),$content_login,$tabcolor='333366',$textcolor='FFFFFF');
		
		//echo DrawRoundedRect($content,'','F0F0F0');
		echo '</TABLE></TD></TR>';
//		echo '<TR><TD>';
		echo '<TR><TD width=100% valign=bottom style="text-align:justify;" border=4>';
	
		// System disclaimer.                                                                                                                 L
//		echo "<BR><BR>
//		<font size=-3 color=gray style='justification:full;'>
//		</font>
//		<br /><br />";
	        echo '</TD></TR>';
		echo "<td style='text-align:right;height:20px;width:100%;float:right;background-image:url(themes/".Preferences('HIGHLIGHT_MENU')."/bg_light.png);background-position:bottom'><A HREF=https://jesuits-africa.education>ACIS</A> version $IntegralVersion &copy; 2009-".date('Y')."</td></table>";
	
	}
	Basic("footer");
}
elseif($_REQUEST['servicefunction']!='create_user_account')
{
	//echo($_REQUEST['USER_NAME'].' -- '.$_REQUEST['USER_PASSWORD'].' -- '.$_REQUEST['servicefunction']);
	// this part is used to download a file that is stored outside of the document root
	if(isset($_GET['download']))
	{
		$fileinfo = db_request(db_execute("SELECT * FROM PROGRAM_UPLOADED_FILES WHERE id = '".$_GET['download']."';"));
		if ($fileinfo)
		{
        if(function_exists(finfo_open))
          {
          $finfo=finfo_open(FILEINFO_MIME);
          $Content_type=finfo_file($finfo, $fileinfo[1]['LOCATION']);
          finfo_close($finfo);
          }
        elseif(function_exists(mime_content_type))
		  $Content_type=mime_content_type($fileinfo[1]['LOCATION']);
	    else
	      $Content_type="mixed";
                header('Content-type: '.$Content_type);
		header('Content-Disposition: attachment; filename="'.$fileinfo[1]['TITLE'].'"');
		readfile($fileinfo[1]['LOCATION']);
		die();
		}
		else
		{
        echo "<HTML><HEAD><TITLE>".$GeneralTitle."</TITLE></HEAD>";
        echo "<noscript><META http-equiv=REFRESH content='0';url=index.php?servicefunction=QUIT&reason=javascript' /></noscript>";
        $title = "No file selected";
        $content = '<INPUT TYPE="button" VALUE="<Back" onClick="history.back()">';
		DisplayBlock($title,$content,$tabcolor='333366',$textcolor='FFFFFF');
		exit;
        }
	}
	$_SYSTEM = array();

	if($_LDAP['auth']!=true && ($login_array[1]['FORCE_PASSWORD_CHANGE'] == 'Y' || $student_array[1]['FORCE_PASSWORD_CHANGE'] == 'Y' || $address_array[1]['FORCE_PASSWORD_CHANGE'] == 'Y'))
	{
    

		echo "<HTML><HEAD><TITLE>".$GeneralTitle."</TITLE></HEAD>";
		echo "<noscript><META http-equiv=REFRESH content='0';url=index.php?servicefunction=QUIT&reason=javascript' /></noscript>";
		echo "<frameset id=mainframeset rows='*,32' border=0 framespacing=0 frameborder=0>
					<frame name='body' onbeforeunload='return check_rb_state();' src='modloader.php?servicemod=mod_users/UsrPrefnProper.php&tab=password' frameborder='1' />
					<frame name='fr_bottom' src='footermenu.php' />
				</frameset>
			</HTML>";
			exit;
	}
	if(Preferences('MENU')!='Top' && get_user('PROFILE')!='student')
	{
	}else{
		echo "<HTML><HEAD><TITLE>".$GeneralTitle."</TITLE></HEAD>";
		echo "<noscript><META http-equiv=REFRESH content='0';url=index.php?servicefunction=QUIT&reason=javascript' /></noscript>";
		echo "<frameset id=mainframeset rows='*,32' border=0 framespacing=0 frameborder=0>
					<frame name='body' onbeforeunload='return check_rb_state();' src='modloader.php?servicemod=mod_portal/Portal.php' frameborder='0' />
					<frame name='fr_bottom' src='footermenu.php' />
				</frameset>
			</HTML>";
	}
//	echo Preferences('HIGHLIGHT');
}
?>		
