<?php

require_once($staticpath.'functions/extra/StudentsFunctional.fnc.php');
include_once($staticpath.'classes/Fields.class.php');
$DBFields = new DBFields;
$button = new Button;
include_once($staticpath.'classes/InputButton.php');
$submitButton = new InputButton;
//echo "<pre>";print_r($_REQUEST);die;
if(!$_REQUEST['include'])
{
	$_REQUEST['include'] = 'stuaddlinfo';
}

if(get_user('PROFILE')!='admin' && $_REQUEST['user_id'] && $_REQUEST['user_id']!='new' && $_REQUEST['user_id']!=get_user('USER_ID'))
{


if(get_user('USERNAME'))
	{
		echo "You are not allowed to access this function! This attempted violation has been logged and your IP address was captured.";
		Basic('footer');
		if($IntegralNotifyAddress)
			mail($IntegralNotifyAddress,'HACKING ATTEMPT',"INSERT INTO HACKING_LOG (HOST_NAME,IP_ADDRESS,LOGIN_DATE,VERSION,PHP_SELF,DOCUMENT_ROOT,SCRIPT_NAME,MODNAME,USERNAME) values('$_SERVER[SERVER_NAME]','$_SERVER[REMOTE_ADDR]','".date('Y-m-d')."','$IntegralVersion','$_SERVER[PHP_SELF]','$_SERVER[DOCUMENT_ROOT]','$_SERVER[SCRIPT_NAME]','$_REQUEST[servicemod] - tried to access user','".get_user('USERNAME')."')");
	}
	exit;
}
//die('ff');

/*
if(($_REQUEST['DeleteFileOK'])&&($_REQUEST['FileID'])&&($_REQUEST['Upload_file_field_id']))
{
	//Deleting file ID from Students Table
	$sql = "UPDATE USERS SET ".$_REQUEST['Upload_file_field_id']." = '' WHERE user_id = '".$_REQUEST['user_id']."' AND ".$_REQUEST['Upload_file_field_id']." = '".$_REQUEST['FileID']."'";
	db_execute($sql);
	//Phisically deleting file
	$FilePath = db_request(db_execute("SELECT LOCATION FROM PROGRAM_UPLOADED_FILES WHERE ID='".$_REQUEST['FileID']."'"));
	if(file_exists($FilePath[1]['LOCATION']))
	 unlink($path);
	//Deleting file from the PROGRAM_UPLOADED_FILES table
	$sql = "DELETE FROM PROGRAM_UPLOADED_FILES WHERE ID='".$_REQUEST['FileID']."'";
	db_execute($sql);
	$Message[1] = "File was successfully deleted.";
}
*/
if(get_user('PROFILE')=='teacher')
{
	$can_edit = db_request(db_execute("SELECT ALLOW_TEACHER_MODIFY FROM USER_FIELD_CATEGORIES WHERE ID='".$_REQUEST['category_id']."'"));
	if($can_edit[1]['ALLOW_TEACHER_MODIFY']=='Y')
		$_SYSTEM['allow_edit'] = true;
}

if(get_user('PROFILE')=='student')
{
	$can_edit = db_request(db_execute("SELECT ALLOW_STUDENT_MODIFY FROM USER_FIELD_CATEGORIES WHERE ID='".$_REQUEST['category_id']."'"));
	if($can_edit[1]['ALLOW_STUDENT_MODIFY']=='Y')
		$_SYSTEM['allow_edit'] = true;
}
//die('kkkkkkk');
if($_REQUEST['servicefunction']=='update')
    {
    /*
  if(isset($_FILES['file']))
	{
	$file = $_FILES['file']['tmp_name'];
	$upload_dir=$uploaded_assets_dir.$title.'/'.$_REQUEST['user_id'].'/';
	$ext=strtolower(pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION));
	// and assemble this into somthing useful
	do
	  {
	  $upload_fullpath=$upload_dir.time().'-'.rand().'.'.$ext;
	  }
	while (file_exists($upload_fullpath));

	// double check to ensure that the directory exists and is writeable
	if(file_exists($upload_dir))
	  {
	  if(!is_writable($upload_dir))
		echo _("At this time administration has disabled file uploads.<br>");
	  }
	else
	  {
	  mkdir($upload_dir,0755,true);
	  }

	//now we will rename the temporary file to its final position
	if(!move_uploaded_file($file, $upload_fullpath))
	  {
	  $error = _("The image you tried to upload could not be saved.  This is likely a system-configuration issue.  See a system administrator.");
	  $Message[1] = "File upload is failed.";
	  }
	else
	  {
	  $sql = "INSERT INTO PROGRAM_UPLOADED_FILES (id, title, location, uploaded_date, filesize) VALUES (".db_seq_nextval("PROGRAM_UPLOADED_FILES_seq").", '".$_FILES['file']['name']."', '".$upload_fullpath."', '".get_db_date()."', '".filesize($upload_fullpath)."')";
	  db_execute($sql);
	  $id = db_seq_currval('PROGRAM_UPLOADED_FILES_seq');
	  $sql = "UPDATE USERS SET ".$_POST['Upload_file_field_id']." = '".$id."' WHERE USER_ID = '".$_REQUEST['user_id']."'";
	  db_execute($sql);
	  $Message[1] = "Your file has been successfully saved.";
	  }
	}
 */
     
    if(is_array($_REQUEST['month_user']))
    {
		foreach($_REQUEST['month_user'] as $column=>$value)
		{
        
        
			$_REQUEST['user'][$column] = $_REQUEST['year_user'][$column].'-'.$_REQUEST['month_user'][$column].'-'.$_REQUEST['day_user'][$column];
			if($_REQUEST['user'][$column]=='--')
				$_REQUEST['user'][$column] = '';
			elseif(!VerifyDate($_REQUEST['user'][$column]))
			{
				unset($_REQUEST['user'][$column]);
				$note = _("The invalid date could not be saved.");
			}
		}
    }
    unset($_REQUEST['day_user']); unset($_REQUEST['month_user']); unset($_REQUEST['year_user']);
    if($_REQUEST['user']['SCHOOLS'])
    {
	foreach($_REQUEST['user']['SCHOOLS'] as $school_id=>$yes)
	{
	    if($yes=='Y')
	    	$schools .= ','.$school_id;
	    if(!empty($yes) && $yes != 'Y')
		$schools .= ','.$yes[0];
	}
	if($schools)
		$_REQUEST['user']['SCHOOLS'] = $schools.',';
    
    
	else
		$_REQUEST['user']['SCHOOLS'] = '';
    }


    if(is_numeric($_REQUEST['user']['PROFILE']))
    {
	$_REQUEST['user']['PROFILE_ID'] = $_REQUEST['user']['PROFILE'];

	$profile_array = db_request(db_execute("SELECT PROFILE FROM USER_PROFILES WHERE ID='".$_REQUEST['user']['PROFILE']."'"));
	$_REQUEST['user']['PROFILE'] = $profile_array[1]['PROFILE'];
    }
    elseif($_REQUEST['user']['PROFILE'])
		$_REQUEST['user']['PROFILE_ID'] = '';
    if(count($_POST) && ((get_user('PROFILE')=='admin' || basename($_SERVER['PHP_SELF'])=='index.php') || (get_user('PROFILE')=='teacher' && $_SYSTEM['allow_edit'] === true)))
    {
    	if($_REQUEST['user']['USERNAME'])
	{
		if($_REQUEST['user_id'] && $_REQUEST['user_id']!='new')
			$users_extra = " AND USER_ID!='".$_REQUEST['user_id']."'";

		$username = $_REQUEST['user']['USERNAME'];
		$i = '';
		do
		{
			$_REQUEST['user']['USERNAME'] = $username.$i;
			$i++;
		}
        
       
		while(count(db_request(db_execute("SELECT STUDENT_ID FROM STUDENTS WHERE USERNAME='".str_replace("\'","''",$_REQUEST['user']['USERNAME'])."'"))) || count(db_request(db_execute("SELECT '' FROM ADDRESS WHERE USERNAME='".str_replace("\'","''",$_REQUEST['user']['USERNAME'])."'"))) || count(db_request(db_execute("SELECT '' FROM USERS WHERE USERNAME='".str_replace("\'","''",$_REQUEST['user']['USERNAME'])."' ".$users_extra))));
	}
    
   

	if($_REQUEST['user_id'] && $_REQUEST['user_id']!='new')
	{
		$profile_array = db_request(db_execute("SELECT PROFILE,PROFILE_ID,USERNAME FROM USERS WHERE USER_ID='".get_user_id()."'"));

    //die('aa');
		// CHANGE FROM A PROFILE TO CUSTOM PERMISSIONS
		if(is_numeric($profile_array[1]['PROFILE_ID']) && $_REQUEST['user']['PROFILE'] == 'admin')
		{
			db_execute("DELETE FROM USER_SETTINGS WHERE USERNAME='".str_replace("'","''",$profile_array[1]['USERNAME'])."'");
			db_execute("INSERT INTO USER_SETTINGS (USERNAME,MODNAME,VIEWER,EDITOR) SELECT s.USERNAME,e.MODNAME,e.VIEWER,e.EDITOR FROM USERS s,PROFILE_SETTINGS e WHERE s.USERNAME='".str_replace("'","''",$profile_array[1]['USERNAME'])."' AND s.PROFILE_ID=e.PROFILE_ID");
		}
		elseif(is_numeric($_REQUEST['user']['PROFILE_ID']) && $profile_array[1]['PROFILE']=='admin')
			db_execute("DELETE FROM USER_SETTINGS WHERE USERNAME='".str_replace("'","''",$profile_array[1]['USERNAME'])."'");

		// CHANGE THE USERNAME
		if($_REQUEST['user']['USERNAME'] && $_REQUEST['user']['USERNAME']!=$profile_array[1]['USERNAME'])
		{
			db_execute("UPDATE USER_SETTINGS SET USERNAME='".str_replace("\'","''",$_REQUEST['user']['USERNAME'])."' WHERE USERNAME='".str_replace("'","''",$profile_array[1]['USERNAME'])."'");
			db_execute("UPDATE SYSTEM_USER_SETTINGS SET USERNAME='".str_replace("\'","''",$_REQUEST['user']['USERNAME'])."' WHERE USERNAME='".str_replace("'","''",$profile_array[1]['USERNAME'])."'");
		}

		$go = true;
		if($_REQUEST['user'])
		{
				/* ---------- Edit Rules Block start ---------------*/
				/*
					already, we have this array with the old values. If user changed one of it
					we will add its new value into the array
				*/
				foreach($_REQUEST['user'] as $column_name=>$value)
				{
					$_SESSION['customValues'][$column_name] = $value;
					$fieldId = explode('CFIELD_',$column_name);
					$fieldIdArr[] = $fieldId[1];
				}

				_saveUsersEnteredValues($_REQUEST);

				/*
					now we have the array with field id's, we will use it for search the Edit Rules
				*/
				$resWithEdits = _getAllEditsRules($fieldIdArr, 1);

				$border = array();
				$go = true;
				/* check user values using Edits Rules when we try to add a new user */
				$errorArr = _executeEditRulesAndGetMsg($_REQUEST['user'], 'user', $resWithEdits);
				/* ---------- Edit Rules Block end ---------------*/
			}
//echo "<pre>";print_r( $_REQUEST);die;
			$sql = "UPDATE USERS SET ";
   		 //$_REQUEST['user']=array();
    		//if(!empty($_REQUEST['user'])){
				foreach($_REQUEST['user'] as $column_name=>$value)
				{
    
            
           
                                if($column_name == 'PASSWORD' && $_Config['EncriptPassword'] == true)
                                            $value = Encript($value);
					if(!is_array($value))
						$sql .= "$column_name='".str_replace("\'","''",str_replace('``','"',$value))."',";
            
            
					else
					{
						$sql .= $column_name."='||";
						foreach($value as $val)
						{
							if($val)
								$sql .= str_replace("\'","''",str_replace('``','"',$val)).'||';
						}
						$sql .= "',";
					}	
				}
   		 	//}  
			/*
				if there are some errors, will show it and return $go = false
			*/
			$go = _showErrorWarningMsg($errorArr);

			if($_REQUEST['override'] == true AND $_SESSION['overrideDisabled'])
			{
				/*
					if user click on the 'Override' button, we will unset all
					override error messages and a red border for this field
				*/
				unset($_SESSION['overrideDisabled']);
				unset($errorArr['override_error']);
				unset($forceFieldName);
				unset($border);
				unset($_SESSION['_REQUEST_vars']['user']);
				$go = true;
			}

    
    
			$sql = substr($sql,0,-1) . " WHERE USER_ID='$_REQUEST[user_id]'";
			//echo $sql; die('hellllllllllOOOOOO');
			if(((get_user('PROFILE')=='admin') || (get_user('PROFILE')=='teacher' && $_SYSTEM['allow_edit'] === true)) AND ($go) AND $_REQUEST['user']){
            	//$aupe_userID = $_REQUEST['user_id'];
            	//$aupe_UserOldData = db_request(db_execute("select * from users where user_id='".$aupe_userID."' "));
            	db_execute($sql);
            }
		}
		else
		{
			/* ---------- Edit Rules Block start ---------------*/
			/*
			   we need this array, because admin (user) can use in the Edits rule
			   condition with the field name. So, we will make a foreach and will have
			   the required for us values
			*/
			$_SESSION['customValues'] = _makeInternalArrayWithCustomFields($_REQUEST['user']);
			/*
				save all user values into the $_SYSTEM
			*/
			_saveUsersEnteredValues($_REQUEST);

			$fieldIdArr = _getIDsForEditRules($_REQUEST['user'], 'user');
			/*
				now we have the array with field id's, we will use it for search the Edit Rules
			*/
			$resWithEdits = _getAllEditsRules($fieldIdArr, 1);

			$go = true;
			/* check user values using Edits Rules when we try to add a new user */
			$errorArr = _executeEditRulesAndGetMsg($_REQUEST['user'], 'user', $resWithEdits);
			/* ---------- Edit Rules Block end ---------------*/
			/*
				if there are some errors, will show it and return $go = false
			*/
			$go = _showErrorWarningMsg($errorArr);
			$show = true;

			if($_REQUEST['override'] == true AND $_SESSION['overrideDisabled'])
			{
				unset($_SESSION['overrideDisabled']);
				$go = true;
			}

			// here, we should CHECK TO SEE IF USER WITH SAME NAME EXISTS ... PROMPT IF USER SHOULD BE CREATED ANYWAY.
			if($go)
			{
				$user_id = db_request(db_execute('SELECT '.db_seq_nextval('USERS_SEQ').' AS USER_ID'.FROM_DUAL));
				$user_id = $user_id[1]['USER_ID'];
			}


			if(empty($_REQUEST['user']['FORCE_PASSWORD_CHANGE']))
				$_REQUEST['user']['FORCE_PASSWORD_CHANGE'] = 'N';

			$sql = "INSERT INTO USERS ";
			$fields = 'USER_ID,SCHOOL_YEAR,';
			$values = "'$user_id','".get_school_year()."',";
        
			if(basename($_SERVER['PHP_SELF'])=='index.php')
			{
				$fields .= 'PROFILE,';
				$values .= "'none',";
			}
			foreach($_REQUEST['user'] as $column=>$value)
			{  		
            		
				if($value)
				{
					$fields .= $column.',';
					if(!is_array($value))
						$values .= "'".str_replace("\'","''",$value)."',";
					else
					{
						$values .= "'||";
						foreach($value as $val)
						{
							if($val)
								$values .= $val.'||';
						}
						$values .= "',";
					}
				}
			}
			$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';

        
        //=========== rakesh user create api  ( START )   ============//
        	$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['function'] = "core_user_create_users"; 
        	$required_fields = array('USER_ID','USERNAME','PASSWORD','FIRST_NAME','MIDDLE_NAME','LAST_NAME','EMAIL');
       		// echo "<pre>"; print_r($courseData_Iomad);die;
        	foreach($_REQUEST['user'] as $key =>$val){
            	if(in_array($key,$required_fields)){
                	
            		$courseData_Iomad[$key] = $val;
                }
  
            }
        	$courseData_Iomad['idnumber'] = $courseData_Iomad['EMAIL'];   //added on 24-10-2020
        	$courseData_Iomad['table'] = "users"; 
      		 // echo "<pre>";print_r($courseData_Iomad);die;
      	//=========== rakesh user create api  ( END )   ============//
		
				if($go)
				{ 		               
					$_SYSTEM['use_sequence_insert'] = true;
                	//=========== rakesh user create api  ( START )   ============//
 					if($_REQUEST['user_id'] == 'new'){
                    		//fields check
                    	if(!empty($_REQUEST['user'])){
                        		$userReqFlds = array();
                        		$req_fileds = array('FIRST_NAME','LAST_NAME','USERNAME','EMAIL','PASSWORD');
                        		foreach($_REQUEST['user'] as $key => $val){
                                	if(empty($val) && in_array($key,$req_fileds)){
                                    	$userReqFlds[$key] = $key;
                                    }
                                }
                        		
                        		if(!empty($userReqFlds)){
                                    foreach($userReqFlds as $key => $val){
                            			echo "<strong>".$val."<strong> field is required..<br>";
                            		}
                        			unset($userReqFlds);
                        			die;
                        		}
                        		
                        
                        }
                    	
                    	$sql .= " RETURNING *";
                    	//echo $sql;die;
                    	$new_userData = db_request(db_execute($sql));
                    	$iomad_userDataQuery = "SELECT * FROM mdl_user WHERE username ='".$new_userData[1]['USERNAME']."' OR email='".$new_userData[1]['EMAIL']."' ";
              			$iomad_userData = pg_query($iomadDBconn, $iomad_userDataQuery);
		      			$iomad_userDetials = pg_fetch_all($iomad_userData);
           					// user doesn't exist in moodle
            			if(empty($iomad_userDetials)) {
            		  		include_once($staticpath.'iomadAPI/newUser.php');   //   moodle user create api                  
               			 } else {
                        	db_execute("Delete from users where user_id='". $new_userData[1]['USER_ID']."' ");
                        	die("USER already exists...");
                        }
                    	//echo "<pre>";print_r($new_userData[1]['USER_ID']);die;
                    } else {
						db_execute($sql);
                    }

            		//=========== rakesh user create api  ( End )   ============//
					$_SYSTEM['just_added_user_id'] = $user_id;
					$_REQUEST['user_id'] = $user_id;
				}
       // die('hehhehe');
		}
	}



	if($_REQUEST['log_values'] && $_POST['log_values'])
	{
		if(count($_REQUEST['month_log_values']))
		{
			foreach($_REQUEST['month_log_values'] as $student_field_id=>$records)
			{
				foreach($records as $id=>$columns)
				{
					foreach($columns as $field_name=>$month)
					{
						$_REQUEST['log_values'][$student_field_id][$id][$field_name] = $_REQUEST['year_log_values'][$student_field_id][$id][$field_name].'-'.$month.'-'.$_REQUEST['day_log_values'][$student_field_id][$id][$field_name];
						if(!VerifyDate($_REQUEST['log_values'][$student_field_id][$id][$field_name]))
						{
							if($_REQUEST['log_values'][$student_field_id][$id][$field_name]!='--')
								$note = '<IMG SRC=images/warning_button.gif>'._('The date you specified is not valid, so was not used.  The other data was saved.');
							unset($_REQUEST['log_values'][$student_field_id][$id][$field_name]);
						}
					}
				}
			}
		}
		foreach($_REQUEST['log_values'] as $user_field_id=>$records)
		{
			foreach($records as $id=>$columns)
			{
				if($id!='new')
				{
					$sql = "UPDATE USER_LF_DATA SET ";
					
					if(count($columns))
					{
						foreach($columns as $column=>$value)
						{
							$sql .= $column."='".str_replace("\'","''",$value)."',";
						}
						$sql = substr($sql,0,-1) . " WHERE ID='$id'";
						echo $sql;
						db_execute($sql);
						
					}
				}
				else
				{
					$sql_temp = $sql = "INSERT INTO USER_LF_DATA ";

					$fields = 'ID,SCHOOL_ID,USER_ID,USER_FIELD_ID,';
					$values = db_seq_nextval('USER_LF_DATA_SEQ').",'".get_school_id()."','".get_user_id()."','".$user_field_id."',";

					$go = 0;
					foreach($columns as $column=>$value)
					{
						if($value)
						{
							$fields .= $column.',';
							$values .= "'".str_replace("\'","''",$value)."',";
							if($column!='LOG_DATE' && $column!='LOG_DATE2') // SINCE THE LOG_DATE HAS A DEFAULT
								$go = true;
						}
					}
					    
					$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
					echo $sql;
					if($go)
						db_execute($sql);
				}
			}
		}
	}
	unset($_REQUEST['user']);
	unset($_REQUEST['servicefunction']);
	/*
		commented, because we need these values for using, when there is the override error
	*/
	unset($_SESSION['_REQUEST_vars']['servicefunction']);

}
//changed at 04.02.2010
//line start. be careful
$justadded = false;
if(get_user_id())
    $userID = get_user_id();
elseif(get_user('PROFILE')=='teacher')
    $userID = $_SESSION['USER_ID'];
    //this is for just created user w/o profile selection
//var_dump($_REQUEST);
//die('aaaaaa');
if(!$userID && $_REQUEST['users_search_servicefunction']!='search' && $_REQUEST['users_search_servicefunction']!='list')
{
	$userID = $_REQUEST['user_id'];
//	$justadded = true;
}
elseif($userID && $_REQUEST['users_search_servicefunction']!='search' && $_REQUEST['users_search_servicefunction']!='list')
{
	$justadded = true;
}

//die('aaaaaaa');
if(($userID || $_REQUEST['user_id']=='new') && ((basename($_SERVER['PHP_SELF'])!='index.php') || !$_REQUEST['user']['USERNAME']) && $_REQUEST['servicefunction']!='delete')
{
	if($_REQUEST['user_id']!='new')
	{
		if(get_user_id())
			$sql = "SELECT * FROM USERS s WHERE s.USER_ID='".get_user_id()."'";
		else
			$sql = "SELECT * FROM USERS s WHERE s.USER_ID='".$userID."'";
		$QI = db_execute($sql);
		$user = db_request($QI);
   
		$user = $user[1];
		echo "<FORM name=user enctype=multipart/form-data action=modloader.php?servicemod=$_REQUEST[servicemod]&user_id=$_REQUEST[user_id]&user_id=".get_user_id()."&servicefunction=update&category_id=$_REQUEST[category_id] id=user method=POST>";
		$user_cats_array = db_request(db_execute("SELECT ID,TITLE,ADMIN,TEACHER,PARENT,ALLOW_TEACHER_MODIFY FROM USER_FIELD_CATEGORIES"),array(),array('ID'));
	}
	elseif(basename($_SERVER['PHP_SELF'])!='index.php')
		echo "<FORM name=user enctype=multipart/form-data action=modloader.php?servicemod=mod_users/Users.php&user_id=$_REQUEST[user_id]&servicefunction=update id=user method=POST>";
	else
		echo "<FORM name=user enctype=multipart/form-data action=index.php?servicefunction=create_user_account id=user METHOD=POST>";

	if(basename($_SERVER['PHP_SELF'])=='index.php')
		DisplayHeader(_('Create Account'));
	else
	{
		if(get_user_id() && get_user('PROFILE')=='admin' && $_REQUEST['user_id']!='new' && AllowEdit())
			$delete_button = '<INPUT style="width:100px;" type=button value='._('Delete').' onclick="window.location=\'modloader.php?servicemod='.$_REQUEST['servicemod'].'&user_id='.$_REQUEST['user_id'].'&servicefunction=delete\'"> &nbsp; &nbsp;';
	}

	if($errorArr['override_error'])
	{
		if(!$errorArr['err'])
		{
			$overrideDisabled = '';
			$_SESSION['overrideDisabled'] = true;
		}
		else
			$overrideDisabled = 'DISABLED';

		$override_button = '<INPUT type=button value='._('Override').' '.$overrideDisabled.' onclick="checkOverride(\'user\');"> &nbsp; ';
	}

	if(!$_REQUEST['category_id'])
		$_REQUEST['category_id'] = 1;
	$uc_allow_edit = $user_cats_array[$_REQUEST['category_id']][1]['ALLOW_TEACHER_MODIFY'];
//	echo "->".$uc_allow_edit;
	if(get_user('PROFILE')!='teacher' || $uc_allow_edit == 'Y')
		$save_button = $submitButton->createSButton(_('Save'));
	

	if($_SESSION['user_id']!='new')
	{
	    if(isset($_SESSION['GridOutputCount']))
	    {
			$tmp_REQUEST = $_REQUEST;
			unset($tmp_REQUEST['GridOutputCount']);
			unset($tmp_REQUEST['values']);
			unset($tmp_REQUEST['address_id']);
	        	unset($tmp_REQUEST['person_id']);
			unset($tmp_REQUEST['student_id']);
			unset($tmp_REQUEST['user_id']);
			unset($tmp_REQUEST['discipline_ir_id']);
			unset($tmp_REQUEST['users_search_servicefunction']);
			if($_SESSION['GridOutputCount']>1)
			{
			    $but_left =  '<A HREF='.SetRequestOptions($tmp_REQUEST).'&GridOutputCount='.($_SESSION['GridOutputCount']-1).'><IMG SRC=images/arrow_left.gif border=0></A>';
			}
      // die('qqqqqq');
			if($_SESSION['GridOutputCount']<count($_SESSION['user_list']))
			{
         //echo "<pre>";   print_r($_SESSION['user_list']); echo "</pre>";die('sssssss');
            
			    $but_right =  '<A HREF='.SetRequestOptions($tmp_REQUEST).'&GridOutputCount='.($_SESSION['GridOutputCount']+1).'><IMG SRC=images/arrow_right.gif border=0></A>';
			
            
            }
	    }else{
			unset($_SESSION['user_list']);
       
	    }
	    if($_REQUEST['servicemod'] == 'mod_users/UsrMyInfo.php')
	    {
		    unset($delete_button);
		    unset($but_left);
		    unset($but_right);
	    }
	    if($user['LAST_NAME'])
	    {
			DisplayHeader(".:".ProgramTitle().":. - <i>".$but_left." ".$user['LAST_NAME']." ".$user['FIRST_NAME']." ".$user['MIDDLE_NAME']."</i> ".$but_right);
	    }else{
			DisplayHeader(".:".ProgramTitle().":.");
	    }
	}
//	if($_REQUEST['servicemod'] == 'mod_users/UsrMyInfo.php')
//		unset($delete_button);


	DisplayHeader('',$override_button.$delete_button.$save_button);
	echo '<BR>';
	if($_REQUEST['user_id']=='new')
	{
		$tabs = false;
	}
	
	else
	{
		$tabs = array(array('title'=>_('General Info'),'link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&user_id=$_REQUEST[user_id]&category_id=1"));
		if(get_user_id())
			$profile_array = db_request(db_execute("SELECT PROFILE FROM USERS WHERE USER_ID='".get_user_id()."'"));
		else
			$profile_array = db_request(db_execute("SELECT PROFILE FROM USERS WHERE USER_ID='".$userID."'"));
		if($profile_array[1]['PROFILE']=='teacher')
			$tabs[] = array('title'=>_('Schedule'),'link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&user_id=$_REQUEST[user_id]&servicefunction=teacher_schedlist");

		$categories_array = db_request(db_execute("SELECT ID,TITLE,ADMIN,TEACHER,PARENT,ALLOW_TEACHER_MODIFY FROM USER_FIELD_CATEGORIES WHERE ID>1"));
		foreach($categories_array as $category)
		{
			if(!$can_use_array['mod_users/Users.php&category_id='.$category['ID']] && $category[strtoupper($user['PROFILE'])]=='Y')
				$tabs[] = array('title'=>$category['TITLE'],'link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&user_id=$_REQUEST[user_id]&category_id=".$category['ID']);
		}
	}

	if($_REQUEST['servicefunction']=='teacher_schedlist')
		$_SYSTEM['selected_tab'] = "modloader.php?servicemod=$_REQUEST[servicemod]&user_id=$_REQUEST[user_id]&servicefunction=teacher_schedlist";
	else
	{
		$_SYSTEM['selected_tab'] = "modloader.php?servicemod=$_REQUEST[servicemod]&user_id=$_REQUEST[user_id]";
		if($_REQUEST['category_id'])
			$_SYSTEM['selected_tab'] .= '&category_id='.$_REQUEST['category_id'];
	}

	if(Preferences('MENU')=='Top')
		$width = 'width=80%';
	else
		$width = 'width=99%';

	/*
		if there are some errors, we will show them
	*/
	_showErrorWarningMsg($errorArr, $show, true);
    Echo(ErrorMessage($Message,'Note'));
	
    //get photo url
	$photo_name = get_user_id();

//if($photoPath && $_REQUEST['user_id']!='new' && ($file = @fopen($photoPath.'/user_image_'.$photo_name.($jpg = '.JPG'),'r') || $file = @fopen($photoPath.'/user_image_'.$photo_name.($jpg = '.jpg'),'r')))
	
if($photoPath && $_REQUEST['user_id']!='new' && ( $file = @fopen($photoPath.'/user_image_'.$photo_name.($jpg = '.jpg'),'r')))
	{			
		if($_REQUEST['CREATEPDF'] && substr($photoPath,0,7)!='http://')
		{
			if($_SERVER['HTTPS']=='on')
				$http = 'https://';
			else
				$http = 'http://';

			if(!$_SERVER['SCRIPT_URI'])
				$uri = $http.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
			else
				$uri = $_SERVER['SCRIPT_URI'];
			$uri = substr($uri,0,strrpos($uri,'/')).'/';
		}
		else
			$uri = '';
	
		$userPhoto = '<img src="'.$uri.$photoPath.'/user_image_'.$photo_name.$jpg.'" width=153>';
		//when new user added we need to get id from REQUEST['user_id']
//die('qqqqqqq');
		$user_id = get_user_id();
//		if($user_id == 'new') $user_id = $_REQUEST['user_id'];
	if($user_id=='new') $user_id=$_REQUEST['user_id'];	
		if(get_user('PROFILE')=='admin' && !$_REQUEST['CREATEPDF'])
			$userPhoto .= "<div><a href=# onclick=\"window.open('modules/mod_students/AddPhoto.php?staticpath=$staticpath&user_id=$user_id&user_profile=user&photo_path=$photoPath','','scrollbars=yes,resizable=yes,width=400,height=300')\">"._('Change image')."</a></div>";
		
		//$file=@fopen($photoPath.'/user_image_'.$photo_name.($jpg = '.JPG'));
               fclose($file);
//print_r($file);
    //print_r($file);
	}
	else
	{
		$user_id = get_user_id();
		if($user_id == 'new') $user_id = $_REQUEST['user_id'];
		$userPhoto = '<div style="padding:0 10px;">'.$button->drawImage('images/nophoto.png','width=156').'</div>';
		
		if(get_user('PROFILE')=='admin')
			$userPhoto .= "<div><a href=# onclick=\"window.open('modules/mod_students/AddPhoto.php?staticpath=$staticpath&user_id=$user_id&user_profile=user&photo_path=$photoPath','','scrollbars=yes,resizable=yes,width=400,height=300')\">"._('Change image')."</a></div>";
	}	
    
	PopTable('header',$tabs,$width,'0');
	if($_REQUEST['servicefunction']=='teacher_schedlist')
	{
		if(!$_REQUEST['dftype'])
			$_REQUEST['dftype'] = 'course_list';

		if($_REQUEST['dftype']=='course_list')
		{
			$header .= $button->createButton(_('Course List'),SetRequestOptions(null,array('dftype','search_servicefunction')).'&amp;dftype=course_list');
			$header .= $button->createText(_('Weekly Timetable'),SetRequestOptions(null,array('dftype','search_servicefunction')).'&amp;dftype=timetable');
			echo TabsHeader($header);

			$schedule_array = db_request(db_execute("SELECT cs.SCHOOL_PERIOD_ID,cs.ROOM,cs.WEEK,c.TITLE,cs.COURSE_CREDIT_TITLE,cs.SCHOOL_TERM_ID,cs.DAYS FROM COURSE_SECTIONS cs,COURSES c WHERE cs.COURSE_ID=c.COURSE_ID AND cs.TEACHER_ID='".get_user_id()."' AND cs.SCHOOL_YEAR='".get_school_year()."'"),array('SCHOOL_PERIOD_ID'=>'get_period','SCHOOL_TERM_ID'=>'get_school_term','WEEK'=>'get_week'));
			$i=0;
			foreach($schedule_array as $key=>$info)
			{
				$i++;
				$daystrlength = strlen($info['DAYS']);
				$schedule_array[$i]['DAYS'] = '';
				for($k=0; $k<=$daystrlength; $k+=3)
				{	
					if(substr($info['DAYS'],$k,3) <> '')
						$schedule_array[$i]['DAYS'] .=_(substr($info['DAYS'],$k,3)).' ';
				}
			}
			$columns = array('TITLE'=>_('Course Name'),
						       'SCHOOL_PERIOD_ID'=>_('School Period'),
						       'DAYS'=>_('Meeting Days'),
						       'WEEK'=>_('Week'),
						       'ROOM'=>_('Class-room'),
						       'SCHOOL_TERM_ID'=>_('School Term'));
			if(SystemPreferences('ODD_EVEN_WEEKS','system') != 'Y')			
				unset($columns['WEEK']);
			Gridoutput($schedule_array,$columns,
				_('Courses'),_('Amount of Courses'));
		}
		elseif($_REQUEST['dftype']=='timetable')
		{
			$_REQUEST['user_id'] = get_user_id();
			$header .= $button->createText(_('Course List'),SetRequestOptions(null,array('dftype','search_servicefunction')).'&amp;dftype=course_list');
			$header .= $button->createButton(_('Weekly Timetable'),SetRequestOptions(null,array('dftype','search_servicefunction')).'&amp;dftype=timetable');
			echo TabsHeader($header);
			
			echo '</tr><tr>';
			include($staticpath.'modules/mod_ssetup/SchInventoryCenter.php');
			echo '<table><tr><td>';
		}
	}
	else
	{
		if($_REQUEST['user_id']=='new')
			$div = true;
		else
			$div = 'force';

		if($_REQUEST['category_id']==1)
		{
			echo '<TABLE class="tuser" border=0 cellpadding=0 cellspacing=0 style="padding-top:10px; width:100%;"><TR><TD width=200 align=center rowspan=6>'.$userPhoto.'</TD> <TD height=30px width=270px  '.$borderstyle.'><font color=gray>'._('Name').'<font color=red>*</font></TD><TD '.$borderstyle.'>';
			// single-quotes mess up the next line (add html within addhtml) ... it's not worth the brain power to fix this ...
			if($_REQUEST['servicemod'] == 'mod_users/UsrMyInfo.php')
				$_SYSTEM['AllowEdit'] = array('mod_users/UsrMyInfo.php'=>array('allow'=>'N'));
			$prefix_dump = db_request(db_execute("SELECT VALUE FROM SYSTEM_CONFIG WHERE TITLE='NAME_TITLE'"));
     	    
			for($i=1;$i<count($prefix_dump)+1;$i++)
				$prefix_array[$prefix_dump [$i]['VALUE']] = $prefix_dump [$i]['VALUE'];
       
      
	   /************************  rakesh  :created and  used $name_prefix  **************************/
	   /*
        $name_prefix =  '<select name="user[TITLE]" id="inputuser[TITLE]"><option value="">N/A</option>';
              			     foreach($prefix_array as $val) 
                			  {
                        		$name_prefix .=	 ' <option value='.$val.'>'.$val.'</option>';
                 			   }	
				$name_prefix .='	</select>';
        */
			if(isset($_REQUEST['CREATEPDF']) || $_REQUEST['category_id']!='1')
				echo ((SystemPreferences('USE_PREFIX')=='Y') ? $user['TITLE'] : '').' '.$user['FIRST_NAME'].' '.$user['MIDDLE_NAME'].' '.$user['LAST_NAME'].' ';
			elseif(Preferences('HIDDEN')!='Y' || ($_REQUEST['user_id']=='new' || strpos($user['FIRST_NAME'],"'")!==false || strpos($user['LAST_NAME'],"'")!==false || strpos($user['MIDDLE_NAME'],"'")!==false))
				echo '<TABLE><TR>Prefix:'.$name_prefix.''.((SystemPreferences('USE_PREFIX')=='Y') ? SelectInput($user['TITLE'],'user[TITLE]',_('Prefix').':',$prefix_array,'','',$div): '&nbsp;').'<TD>'.
				TextInput($user['FIRST_NAME'],'user[FIRST_NAME]',_('First').':','size=12 maxlength=50',$div).' </TD><TD>'.
				TextInput($user['MIDDLE_NAME'],'user[MIDDLE_NAME]',_('Middle').':','size=12 maxlength=50',$div).' </TD><TD>'.
				TextInput($user['LAST_NAME'],'user[LAST_NAME]',_('Last').':','size=12 maxlength=50',$div).
				'</TD></TR></TABLE>';

			else
          //  echo "<pre>";print_r($_SESSION);die;
            echo '<DIV id=user_name><div onclick=\'addHTML("<TABLE><TR>'.
				     ((SystemPreferences('USE_PREFIX')=='Y') ? substr_replace('"','\"',SelectInput($user['TITLE'],'user[TITLE]',_('Prefix').':',$prefix_array,'N/A','',false)) : '').
				     ' <TD>'.str_replace('"','\"',TextInput($user['FIRST_NAME'],'user[FIRST_NAME]','<font color=gray>'._('First').':</font>','maxlength=50',false)).
				     ' </TD><TD>'.str_replace('"','\"',TextInput($user['MIDDLE_NAME'],'user[MIDDLE_NAME]','<font color=gray>'._('Middle').':</font>','size=12 maxlength=50',false)).
				     ' </TD><TD>'.str_replace('"','\"',TextInput($user['LAST_NAME'],'user[LAST_NAME]','<font color=gray>'._('Last').':</font>','maxlength=50',false)).
				     '</TD></TR></TABLE>","user_name",true);\'><span style=\'border-bottom-style:dotted;border-bottom-width:1;border-bottom-color:#0033CC;\'>'.
				     ((SystemPreferences('USE_PREFIX')=='Y') ? $user['TITLE'] : '').' '.$user['FIRST_NAME'].' '.$user['MIDDLE_NAME'].' '.$user['LAST_NAME'].'</span></div></DIV>';
			echo '</TD>';
			echo '</TR>';
//echo "<pre>"; print_r($prefix_array);die;
			echo '<TR '.$bgstyle.'><TD height=30px '.$borderstyle.'><font color=gray>'._('Login Name').'</TD><TD '.$borderstyle.'>';
			echo TextInput($user['USERNAME'],'user[USERNAME]','','size=14 maxlength=100',$div);
        
        //************* rakesh sharma (start)******************* //
        echo '<TR '.$bgstyle.'><TD height=30px '.$borderstyle.'><font color=gray>'._('Login Email').'</TD><TD '.$borderstyle.'>';
			echo TextInput($user['EMAIL'],'user[EMAIL]','','size=14 maxlength=100',$div);
        
        //************* rakesh sharma (end)******************* //
        
			echo '</TD></TR>';
			echo '<TR><TD height=30px '.$borderstyle.'><font color=gray>'._('Password').'</TD><TD '.$borderstyle.'>';
			echo TextInput(array($user['PASSWORD'],str_repeat('*',strlen($user['PASSWORD']))),'user[PASSWORD]','','size=12 maxlength=100',$div);
			echo '</TD></TR>';
			echo '<TR '.$bgstyle.'><TD height=30px '.$borderstyle.'><font color=gray>'._('User Profile').'</TD><TD '.$borderstyle.'>';
			if(basename($_SERVER['PHP_SELF'])!='index.php')
			{
				if($user['PROFILE']=='parent')
					$parent = true;

				if($user['PROFILE_ID'])
					$user['PROFILE'] = $user['PROFILE_ID'];

				unset($options);
				$profiles_array = db_request(db_execute("SELECT ID,TITLE,PROFILE FROM USER_PROFILES WHERE PROFILE!='student' ORDER BY PROFILE DESC,TITLE"));
				if(count($profiles_array))
				{
					foreach($profiles_array as $profile)
						$options[$profile['ID']] = $profile['TITLE'];
				}
				else
					$options = array();
				$options += array('teacher'=>_('Teacher with modified access permissions'),
						  'parent'=>_('Parent with modified access permissions'),
						  'admin'=>_('Administrator with modified access permissions'),
						  'none'=>_('The Profile has no permission for access'));
				echo SelectInput($user['PROFILE'],'user[PROFILE]','',$options);
				echo '</TD></TR>';
				echo '<TR><TD height=30px '.$borderstyle.'><font color=gray>'._('Change Password on Next Login').'</TD><TD '.$borderstyle.'>';

				if($_REQUEST['user_id'] == 'new')
				{
					$new = true;
 					$chkCalue = 'Y';
				}
				else
					$chkCalue = $user['FORCE_PASSWORD_CHANGE'];

				echo CheckBoxInput($chkCalue,'user[FORCE_PASSWORD_CHANGE]','','CHECKED',$new);

				echo '</TD></TR>';
				if($parent!==true)
				{
					echo '<TR '.$bgstyle.'><TD><font color=gray>'._('Choose the School(s)').'</TD><TD >';
					$sql = "SELECT ID,TITLE FROM SCHOOLS ORDER BY TITLE";
					$QI = db_execute($sql);
					$schools_array = db_request($QI);
					unset($options);
					if($_REQUEST['user_id']=='new' && count($schools_array)==1)
					{
						echo '<INPUT type=hidden name=user[SCHOOLS]['.$schools_array[1]['ID'].'] value=Y>';
					}
					elseif(count($schools_array))
					{
						$opt = '||';
						foreach($schools_array as $value)
						{
							$opt .= ((strpos($user['SCHOOLS'],','.$value['ID'].',')!==false)?$value['ID'].'||':'');
							$schools_options[$value['ID']] = $value['TITLE'];
						}
						if($_REQUEST['user_id']=='new')
							$div = false;
						echo SelectMultipleInput($opt, 'user[SCHOOLS][]','', $schools_options,null,null,$div,2);
					}
					echo '</TD>';
				}
				else
					echo '<TD></TD>';
				echo '</TR><TR><TD colspan=3 background=themes/'.Preferences('HIGHLIGHT_FRAME').'/gline.png width=22>&nbsp;</TD></TR>';
			}
        //die('eeeeeee');
			if($_REQUEST['user_id'] == 'new')
				echo '</TABLE>';
		}
		if($_REQUEST['servicemod'] == 'mod_users/UsrMyInfo.php')
			unset($_SYSTEM['AllowEdit']);
		if($_REQUEST['user_id']=='new')
		{
			$_REQUEST['category_id'] = 'required';
			include($staticpath.'modules/mod_students/includes/stuaddlinfo.inc.php');
			$_REQUEST['category_id'] = 1;
		}
		else
		{
			include($staticpath.'modules/mod_students/includes/stuaddlinfo.inc.php');
		}
		if(get_user('PROFILE')!='teacher' || $uc_allow_edit == 'Y')
			echo '<CENTER>'.$submitButton->createSButton(_('Save')).'</CENTER>';
	}
	PopTable('footer');
	echo '</FORM>';
}

//line end.
//die('yyyy');
if($_REQUEST['user_id']=='new')
{
//ProgramTitle();
//	DisplayHeader(_('Add a User'));
}
elseif($_SESSION['user_id']=='' && get_user('PROFILE') == 'admin' && $justadded!=true)
{
	DisplayHeader(".:".ProgramTitle().":.");
}
else
{
//var_dump($_SESSION['user_id']);
//var_dump($_REQUEST['user_id']);

	if($_SESSION['user_id'] && get_user('PROFILE') != 'teacher' && $_REQUEST['servicefunction']!='delete' && !$user['LAST_NAME'] && $_REQUEST['dftype']!='timetable')
	{
		DisplayHeader(".:".ProgramTitle().":.");
	}
		
}
//echo get_user('PROFILE');
if(basename($_SERVER['PHP_SELF'])!='index.php' && get_user('PROFILE') == 'admin' && $_REQUEST['servicemod'] != 'mod_users/UsrMyInfo.php')
{
//echo "sfgsdfgdfg";
	Search('user_id');
}
//die();
if($_REQUEST['servicefunction']=='delete' && basename($_SERVER['PHP_SELF'])!='index.php' && AllowEdit() && $_SESSION['user_id'] && !$_REQUEST['delete_list_fields'])
{
	DisplayHeader(".:".ProgramTitle().":.");
	if(DeletePrompt(_(' user')))
	{	
    	//echo "<pre>";print_r($_REQUEST);die;
		db_execute("DELETE FROM STUDENTS_IN_USERS WHERE USER_ID='".get_user_id()."'");
		db_execute("DELETE FROM USERS WHERE USER_ID='".get_user_id()."'");
// Delete all other related tables
		db_execute("DELETE FROM USER_LF_DATA WHERE USER_ID='".get_user_id()."'");
		unset($_SESSION['user_id']);
		unset($_REQUEST['user_id']);
		unset($_SESSION['REQUEST_vars']['user_id']);

		unset($_REQUEST['user_id']);
		unset($_SESSION['user_id']);
		unset($_REQUEST['servicefunction']);
		unset($_SESSION['_REQUEST_vars']['servicefunction']);
		Search('user_id');
	}
}

if($_REQUEST['servicefunction']=='delete' && $_REQUEST['id'] && get_user('PROFILE')=='admin' && $_REQUEST['delete_list_fields'] == true)
{
	if(!$_REQUEST['delete_ok'] && !$_REQUEST['delete_cancel'])
		echo '</FORM>';
	DisplayHeader(".:".ProgramTitle().":.");
			
	if(DeletePrompt(_('log entry')))
	{
		db_execute("DELETE FROM USER_LF_DATA WHERE ID='$_REQUEST[id]'");
		unset($_REQUEST['servicefunction']);
		unset($_SESSION['_REQUEST_vars']['servicefunction']);
		unset($_REQUEST['id']);
		unset($_REQUEST['delete_list_fields']);
		unset($_SESSION['_REQUEST_vars']['id']);
		echo '<script language=JavaScript>window.location.href="modloader.php?servicemod='.$_REQUEST['servicemod'].'&user_id='.$_SESSION['user_id'].'";</script>';
	}
}
?>