<?php

function get_user_list(& $addition)
{	global $_SYSTEM;

	if(Preferences('NAME_FORMAT')=='WCM')
		$full_name = "s.LAST_NAME".CCAT."', '".CCAT."s.FIRST_NAME".CCAT."' '".CCAT."COALESCE(s.MIDDLE_NAME,' ')";
	else
//		$full_name = "s.FIRST_NAME".CCAT."' '".CCAT."COALESCE(s.MIDDLE_NAME,' ')".CCAT."' '".CCAT."s.LAST_NAME";
		$full_name = "s.LAST_NAME".CCAT."' '".CCAT."s.FIRST_NAME".CCAT."' '".CCAT."COALESCE(s.MIDDLE_NAME,' ')";

	if(get_user('PROFILE')=='admin')
	{
			$where_added = false;
			if($addition['SELECT_ONLY'])
				$select = $addition['SELECT_ONLY'];
			else
			{
				// Since the SchoolYear is in User table and not else where, change ssm prefix to s prefix
				if(!$addition['FROM']) $addition['SELECT'] = str_replace('ssm', 's', $addition['SELECT']);
				$select = "$full_name AS FULL_NAME,s.USER_ID,s.SCHOOLS,s.SCHOOLS as LIST_SCHOOL_ID,s.PROFILE_ID,s.PROFILE,s.USERNAME ".$addition['SELECT'];
			}
			$sql = "SELECT ".$select." FROM	USERS s ".$addition['FROM']. " WHERE ";
//					WHERE 
//						s.SCHOOL_YEAR='".get_school_year()."'";
			$sql .= "s.USER_ID IS NOT NULL";

			if($_REQUEST['_search_all_schools']!='Y' && (!$_REQUEST['profile'] || $_REQUEST['profile']!='parent'))
			{
				$where_added = true;
				$sql .= " AND (s.SCHOOLS LIKE '%,".get_school_id().",%' OR ((s.SCHOOLS IS NULL OR s.SCHOOLS='') AND s.PROFILE!='admin' AND s.PROFILE!='teacher')) ";
			}
			else
			{

				$schools = substr(get_user('SCHOOLS'),1,-1);
				if($schools)
				{
					$schools_extra = " ((s.SCHOOLS IS NULL OR s.SCHOOLS='') AND s.PROFILE!='admin' AND s.PROFILE!='teacher')";
					$schools = explode(',',$schools);
					foreach($schools as $school)
					{
						$schools_extra .= " OR s.SCHOOLS LIKE '%,".$school.",%'";
					}
					$sql .= " AND (".$schools_extra.") ";
					$where_added = true;
				}
				$addition['columns_after']['LIST_SCHOOL_ID'] = _('Schools');
				$addition['functions']['LIST_SCHOOL_ID'] = 'get_schools';
			}

			if($_REQUEST['username'])
			{
				$where_added = true;
				$sql .= "AND LOWER(s.USERNAME) LIKE '".strtolower($_REQUEST['username'])."%' ";
			}
			if($_REQUEST['profile'] && is_numeric($_REQUEST['profile']) && $where_added === true)
			{
				$where_added = true;
				$sql .= " AND s.PROFILE_ID='".$_REQUEST['profile']."' ";
			}
			elseif($_REQUEST['profile'] && is_numeric($_REQUEST['profile']))
			{
				$where_added = true;
				$sql .= " AND s.PROFILE_ID='".$_REQUEST['profile']."' ";
			}
			elseif($_REQUEST['profile'] && $where_added === true)
				$sql .= " AND s.PROFILE='".$_REQUEST['profile']."' ";
			elseif($_REQUEST['profile'])
				$sql .= " AND s.PROFILE='".$_REQUEST['profile']."' ";
			
			if($_REQUEST['stuid']) // why would this ever be set?
			{
				$old_stu_id = $_REQUEST['stuid'];
				unset($_REQUEST['stuid']);
			}
			
			if($_REQUEST['servicemod'] == 'mod_grades/MassTeacherAssign.php' && $_REQUEST['cust_search'])
			{
			    $sql .= appendSQL().' '.$addition['WHERE']." ".str_replace("\\",'',$_REQUEST['cust_search']);
			    echo "<script langiage='javascript' type='text/javascript'>";
			    echo 'document.mass_assignment.action = document.mass_assignment.action + "&cust_search=" + "'.str_replace("\\",'',$_REQUEST['cust_search']).'"</script>';
			}
			else
			    $sql .= appendSQL().' '.$addition['WHERE']." ".CustomFields('where');
			if($old_stu_id)
				$_REQUEST['stuid'] = $old_stu_id;

			if($addition['GROUP'])
				$sql .= ' GROUP BY '.$addition['GROUP'];

			if(!$addition['ORDER_BY'] && (!$addition['SELECT_ONLY'] || strpos($addition['SELECT_ONLY'],'FULL_NAME')!==false))
				$sql .= "ORDER BY FULL_NAME";
			elseif($addition['ORDER_BY'])
				$sql .= ' ORDER BY '.$addition['ORDER_BY'];
		//echo $sql.'<br>';
			if($addition['DEBUG']===true)
				echo '<!-- '.$sql.' -->';

			$array =  db_request(db_execute($sql),$addition['functions'],$addition['group']);

			if($addition['GridOutputCount']!==false && (true))
			{
				if($_REQUEST['GridSortingBy'])
				{
					$result_count = count($array);
					foreach($array as $sort)
					{	
						if(substr($sort[$_REQUEST['GridSortingBy']],0,4)!='<!--')
							$sort_array[] = $sort[$_REQUEST['GridSortingBy']];
						else
							$sort_array[] = substr($sort[$_REQUEST['GridSortingBy']],4,strpos($sort[$_REQUEST['GridSortingBy']],'-->')-5);
					}
					if($_REQUEST['GridOrder']==-1)
						$dir = SORT_DESC;
					else
						$dir = SORT_ASC;
					
					if($result_count>1)	
					{
						if(is_int($sort_array[1]) || is_double($sort_array[1]))	
							array_multisort($sort_array,$dir,SORT_NUMERIC,$array); 		
						else
							array_multisort($sort_array,$dir,$array);
						for($i=$result_count-1;$i>=0;$i--)
							$array[$i+1] = $array[$i];
						unset($array[0]);
					}
					$_SYSTEM['GridSorted'] = true;
				}
		
				$i = 0;
				$_SESSION['user_list'] = array();
				foreach($array as $index=>$user)
				{
					$i++;
					$_SESSION['user_list'][] = array('user_id'=>$user['USER_ID'],'schools'=>$user['SCHOOLS']);
					$array[$index]['index'] = $i;
				}
			}
	
			return $array;
	}
	elseif(get_user('PROFILE')=='teacher' && teacher_access($_REQUEST['servicemod'])==true)
	{
			$where_added = false;
			if($addition['SELECT_ONLY'])
				$select = $addition['SELECT_ONLY'];
			else
			{
				// Since the SchoolYear is in User table and not else where, change ssm prefix to s prefix
				if(!$addition['FROM']) $addition['SELECT'] = str_replace('ssm', 's', $addition['SELECT']);
				$select = "$full_name AS FULL_NAME,s.USER_ID,s.SCHOOLS,s.SCHOOLS as LIST_SCHOOL_ID,s.PROFILE_ID,s.PROFILE,s.USERNAME ".$addition['SELECT'];
			}
			
			$sql = "SELECT ".$select." FROM	USERS s ".$addition['FROM']. " WHERE ";
//					WHERE 
//						s.SCHOOL_YEAR='".get_school_year()."'";
			$sql .= "s.USER_ID IS NOT NULL";

			if($_REQUEST['_search_all_schools']!='Y' && (!$_REQUEST['profile'] || $_REQUEST['profile']!='parent'))
			{
				$where_added = true;
				if(Preferences('teacher_search_access')=='teacher_school')
				{
                                    $schools = substr(get_user('SCHOOLS'),1,-1);
                                    $schools = explode(',',$schools);
                                    $sql.=" AND (";
                                    $count=0;
                                    $scls="(";
                                    foreach($schools as $school)
                                    {
                                            $count++;
                                            if(sizeof($schools)>$count)
                                            {
                                                    $scls.= "s.SCHOOLS LIKE '%,$school,%' OR ";
                                            }
                                            elseif(sizeof($schools)==$count)
                                            {
                                                    $scls.= "s.SCHOOLS LIKE '%,$school,%')";
                                            }
                                    }
                                    
				}
				elseif(Preferences('teacher_search_access')=='all_school')
				{
					$sql.=" AND (";
					$scls="s.SCHOOLS LIKE '%%'";
				}
                               /* else
                                {
                                    $sql.=" AND (";
                                    $scls="s.SCHOOLS LIKE '%%'";
                                }*/
				$sql .= $scls." OR ((s.SCHOOLS IS NULL OR s.SCHOOLS='' AND s.PROFILE!='admin') AND s.PROFILE!='teacher'))";
				//echo $sql;
			}
				/*else
				{

				$schools = substr(get_user('SCHOOLS'),1,-1);
				if($schools)
				{
					$schools_extra = " ((s.SCHOOLS IS NULL OR s.SCHOOLS='') AND s.PROFILE!='admin' AND s.PROFILE!='teacher')";
					$schools = explode(',',$schools);
					foreach($schools as $school)
					{
						$schools_extra .= " OR s.SCHOOLS LIKE '%,".$school.",%'";
					}
					$sql .= " AND (".$schools_extra.") ";
					$where_added = true;
				}
				$addition['columns_after']['LIST_SCHOOL_ID'] = _('Schools');
				$addition['functions']['LIST_SCHOOL_ID'] = 'get_schools';
			}*/
			
			if($_REQUEST['username'])
			{
				$where_added = true;
				$sql .= "AND LOWER(s.USERNAME) LIKE '".strtolower($_REQUEST['username'])."%' ";
			}
			if($_REQUEST['profile'] && is_numeric($_REQUEST['profile']) && $where_added === true)
			{
				$where_added = true;
				$sql .= "AND s.PROFILE_ID='".$_REQUEST['profile']."' ";
			}
			elseif($_REQUEST['profile'] && is_numeric($_REQUEST['profile']))
			{
				$where_added = true;
				$sql .= "s.PROFILE_ID='".$_REQUEST['profile']."' ";
			}
			elseif($_REQUEST['profile'] && $where_added === true)
				$sql .= "AND s.PROFILE='".$_REQUEST['profile']."' ";
			elseif($_REQUEST['profile'])
				$sql .= " AND s.PROFILE='".$_REQUEST['profile']."' ";
			
			if($_REQUEST['stuid']) // why would this ever be set?
			{
				$old_stu_id = $_REQUEST['stuid'];
				unset($_REQUEST['stuid']);
			}
			
			if($_REQUEST['servicemod'] == 'mod_grades/MassTeacherAssign.php' && $_REQUEST['cust_search'])
			{
			    $sql .= appendSQL().' '.$addition['WHERE']." ".str_replace("\\",'',$_REQUEST['cust_search']);
			    echo "<script langiage='javascript' type='text/javascript'>";
			    echo 'document.mass_assignment.action = document.mass_assignment.action + "&cust_search=" + "'.str_replace("\\",'',$_REQUEST['cust_search']).'"</script>';
			}
			else
			    $sql .= appendSQL().' '.$addition['WHERE']." ".CustomFields('where');

			if($old_stu_id)
				$_REQUEST['stuid'] = $old_stu_id;

			if($addition['GROUP'])
				$sql .= ' GROUP BY '.$addition['GROUP'];

			if(!$addition['ORDER_BY'] && (!$addition['SELECT_ONLY'] || strpos($addition['SELECT_ONLY'],'FULL_NAME')!==false))
				$sql .= "ORDER BY FULL_NAME";
			elseif($addition['ORDER_BY'])
				$sql .= ' ORDER BY '.$addition['ORDER_BY'];
		//echo $sql.'<br>';
			if($addition['DEBUG']===true)
				echo '<!-- '.$sql.' -->';

			$array =  db_request(db_execute($sql),$addition['functions'],$addition['group']);

			if($addition['GridOutputCount']!==false && (true))
			{
				if($_REQUEST['GridSortingBy'])
				{
					$result_count = count($array);
					foreach($array as $sort)
					{	
						if(substr($sort[$_REQUEST['GridSortingBy']],0,4)!='<!--')
							$sort_array[] = $sort[$_REQUEST['GridSortingBy']];
						else
							$sort_array[] = substr($sort[$_REQUEST['GridSortingBy']],4,strpos($sort[$_REQUEST['GridSortingBy']],'-->')-5);
					}
					if($_REQUEST['GridOrder']==-1)
						$dir = SORT_DESC;
					else
						$dir = SORT_ASC;
					
					if($result_count>1)	
					{
						if(is_int($sort_array[1]) || is_double($sort_array[1]))	
							array_multisort($sort_array,$dir,SORT_NUMERIC,$array); 		
						else
							array_multisort($sort_array,$dir,$array);
						for($i=$result_count-1;$i>=0;$i--)
							$array[$i+1] = $array[$i];
						unset($array[0]);
					}
					$_SYSTEM['GridSorted'] = true;
				}
		
				$i = 0;
				$_SESSION['user_list'] = array();
				foreach($array as $index=>$user)
				{
					$i++;
					$_SESSION['user_list'][] = array('user_id'=>$user['USER_ID'],'schools'=>$user['SCHOOLS']);
					$array[$index]['index'] = $i;
				}
			}
	
			return $array;
	}
}

function get_schools($schools)
{	global $_SYSTEM;

	if(!$schools)
		return _('All');
	
	$schools = explode(',',substr($schools,1,-1));
	foreach($schools as $school)
		$return .= ', '.get_school($school);
	
	return substr($return,2);
}
function teacher_access($servicemod)
{
    if($servicemod=='mod_messaging/Internal_mail.php')
        return true;
    elseif($servicemod=='mod_messaging/Mailing_of_group.php')
        return true;
    return false;
}
?>