<?
require_once('include/global.php');
require_once("include/mail_lib.php");
require_once('include/pager.php');
require_once("include/member_lib.php");
require_once('include/member_group_lib.php');
require_once('conf.inc.php');


// check
	if ($G['DINFO']['d_mbrgrp_isuse'] == 'N')
		msg("조직도 사용이 제한되었습니다.\\n\\n관리자에게 문의하여 주십시오.");

	if (member_group_deny_check())
		msg("조직도를 사용할 수 없는 [".$AUTH['auth_mg_name']."]조직입니다.\\n\\n관리자에게 문의하여 주십시오.");


// set
	$CFG['TITLE'] = '<b>조직도</b>';


	// 주소록 색인
		$addr_idxs_key = array('ㄱ', 'ㄴ', 'ㄷ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅅ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ', 'A~Z', '0~9'); 
		$addr_idxs_val = array('가', '나', '다', '라', '마', '바', '사', '아', '자', '차', '카', '타', '파', '하', 'A', '1');


	// list field
		$CFG['ADDR_LIST_FIELD'] = array(
			//'mgr.mg_no' => '조직',
			'm.m_name' => '이름',
			'mc.mc_name' => '직위',
			'm.m_email' => '이메일'
			);
		$q_add = '';
		if (!is_array($G_SYS['MEMBER_LIST_ADD_FIELD']))
		{
			/*
			$G_SYS['MEMBER_LIST_ADD_FIELD'] = array(
				'm.m_mobile' => '휴대폰',
				'm.m_office_tel' => '전화'
				);
			*/
			// [2011-01-10] 조직도 항목관리
			$G_SYS['MEMBER_LIST_ADD_FIELD'] = array();
			if ($G['DINFO']['d_mbrgrp_list'] != '')
			{
				$mf = get_member_field();
				$_field = explode('|', $G['DINFO']['d_mbrgrp_list']);
				for ($i=0; $i<sizeof($_field); $i++)
				{
					if ($_field[$i] != '' && $mf[$_field[$i]][isuse] == "Y" && !in_array($_field[$i], array('m_file1', 'm_file2', 'm_file3', 'm_file4', 'm_file5', 'm_pwd', 'm_birthday_east', 'm_home_addr2', 'm_office_addr2')))
					{
						$G_SYS['MEMBER_LIST_ADD_FIELD']['m.'.$_field[$i]] = $mf[$_field[$i]][text];
					}	// if()
				}	// for()
			}	// if()
		}	// if()
		$CFG['ADDR_LIST_FIELD'] = array_merge($CFG['ADDR_LIST_FIELD'], $G_SYS['MEMBER_LIST_ADD_FIELD']);


// data

	// search
		$q_where = ' AND m.m_usertype IS NULL ';

		// [2011-07-08] 가입대기, 탈퇴회원은 조직이 할당되어 있더라도 제외시킴.
		$q_where .= " AND m.m_level > '" . $G[LEVEL][wait] . "' ";

		if ($_GET['s_word'])
		{
			set_q_search($_GET['s_word']);

			$q_m_id = '';
			if (strpos($_GET['s_word'], '@') !== false)
			{
				$_ex = explode('@', $_GET['s_word']);
				if ($_ex[1] == '')
				{
					$q_m_id = $_ex[0];
				} else if (strpos($G['DINFO']['d_name'], $_ex[1]) === 0)		// 다른 도메인일때는 회원테이블에서 검색할 필요없음.
				{
					$q_m_id = $_ex[0];
				}	// if()
				$q_m_id_like = " m.m_id = '" . $q_m_id . "' ";
			} else
			{
				$q_m_id = $_GET['s_word'];
				$q_m_id_like = " m.m_id LIKE '" . $q_m_id . "%' ";
			}	// if()

			$q_where .= " AND ( ".$q_m_id_like." OR m.m_name LIKE '%" . $_GET['s_word'] . "%' ";
			if (is_array($G_SYS['MEMBER_LIST_ADD_FIELD']))
			{
				foreach ($G_SYS['MEMBER_LIST_ADD_FIELD'] as $key=>$val)
				{
					$q_where .= " OR ".$key." LIKE '%" . $_GET['s_word'] . "%' ";
				}	// foreach()
			}	// if()
			$q_where .= " ) ";

			$v_s_word = htmlspecialchars_fix(stripslashes($_GET['s_word']));
		}	// if()

		if ($_GET['s_mg_no'])
			$q_where .= " AND mgr.mg_no = '" . $_GET['s_mg_no'] . "' ";			

		if ($_GET['s_idx'])
		{
			$s_idx_key = array_search($_GET['s_idx'], $addr_idxs_val);
			if ($s_idx_key !== false && $s_idx_key !== NULL)
			{
				switch ($_GET['s_idx'])
				{
					case '하':
						$q_where .= " AND m.m_name >= '하' ";
						break;

					case 'A':
						$q_where .= " AND m.m_name >= 'A' AND m.m_name < '{' ";
						break;

					case '1':
						$q_where .= " AND m.m_name >= '0' AND m.m_name < ':' ";
						break;

					default:
						$q_where .= " AND m.m_name >= '" . $addr_idxs_val[$s_idx_key] . "' AND m.m_name < '" . $addr_idxs_val[$s_idx_key+1] . "' ";
						break;
				}	// switch()
			}	// if()
		}	// if()

		// [2011-08-25] 회원직위
		if ($_GET['s_mc_no'])
		{
			set_q_search($_GET['s_mc_no']);
			$q_where .= " AND m.mc_no = '" . $_GET['s_mc_no'] . "' ";
		}	// if()


	// sort
		//$q_add = ', '.implode(', ', array_keys($G_SYS['MEMBER_LIST_ADD_FIELD']));

		if (!$_GET['s_key2'])
			$_GET['s_key2'] = 'ASC';
		$order_set = get_order(array_keys($CFG['ADDR_LIST_FIELD']), 'mc.d_no DESC, mc.mc_sort, m.m_name', $_GET['s_key'], $_GET['s_key2']);
		$order_img = get_order_img(array_keys($CFG['ADDR_LIST_FIELD']), $_GET['s_key'], $_GET['s_key2'], false, 'common_skin');		// array

	// db - pager
		$DEBUG['db_cnt']['start'] = getmicrotime();
		$q = "
			SELECT
				COUNT(DISTINCT m.m_no)
			FROM
				".$TB['MEMBER']." m,
				".$TB['MEMBER_GROUP_REL']." mgr
			WHERE
				m.d_no='" . $G['DINFO']['d_no'] . "'
				".$q_where."
				AND m.m_no=mgr.m_no
			";
		$pager_params['totalItems'] = db_get_one($q);
		$pager_params['perPage'] = 20;

		$DEBUG['db_cnt']['exec'] += getmicrotime() - $DEBUG['db_cnt']['start'];

		$pager = &new Pager_Sliding($pager_params);
		$pager_links = $pager->getLinks();
		$pager_limit = get_pager_limit($pager->getCurrentPageID(), $pager_params['perPage']);

	// db - select
		$DEBUG['db_select']['start'] = getmicrotime();
		if ($G_SYS[DB] == 'oracle')
		{
			/*
			$q = "
				SELECT
					DISTINCT m.m_no, m.m_id, m.m_name, mc.mc_name, m.mg_no".$q_add."
				FROM
					".$TB['MEMBER']." m,
					".$TB['MEMBER_CLASS']." mc,
					".$TB['MEMBER_GROUP_REL']." mgr
				WHERE
					m.d_no='" . $G['DINFO']['d_no'] . "'
					".$q_where."
					AND m.mc_no=mc.mc_no(+)
					AND m.m_no=mgr.m_no
				ORDER BY
				" . $order_set['query'] . "
				";
			*/
			$q = "
				SELECT *
				FROM (
					SELECT
						m.*, mc.mc_name
						, ROW_NUMBER() OVER(PARTITION BY m.m_no ORDER BY m.m_no) rn
					FROM
						".$TB['MEMBER']." m,
						".$TB['MEMBER_CLASS']." mc,
						".$TB['MEMBER_GROUP_REL']." mgr
					WHERE
						m.d_no='" . $G['DINFO']['d_no'] . "'
						".$q_where."
						AND m.mc_no=mc.mc_no(+)
						AND m.m_no=mgr.m_no
					ORDER BY
					" . $order_set['query'] . "
				)
				 WHERE rn = 1
				";
		} else
		{
			// 직위, 이름 순서
			$q = "
				SELECT
					m.*, mc.mc_name
				FROM
					".$TB['MEMBER']." m LEFT JOIN
					".$TB['MEMBER_CLASS']." mc ON (m.mc_no=mc.mc_no),
					".$TB['MEMBER_GROUP_REL']." mgr
				WHERE
					m.d_no='" . $G['DINFO']['d_no'] . "'
					AND m.m_no=mgr.m_no
					".$q_where."
				GROUP BY
					m.m_no
				ORDER BY
				" . $order_set['query'] . "
				";
		}	// if()
		$rows = db_get_rows($q, $pager_limit['from'], $pager_limit['count']);
		$DEBUG['db_select']['exec'] += getmicrotime() - $DEBUG['db_select']['start'];

	// process data
		$DEBUG['db_fetch_all']['start'] = getmicrotime();
		for ($i=0; $i<sizeof($rows); $i++)
		{
			$_eml = $rows[$i]['m_id'].'@'.$G['DINFO']['d_name'];
			if ($_GET['is_iframe'])
			{
				$rows[$i]['m_email'] = get_mailto_url($_eml, $rows[$i]['m_name'], true, NULL, ' target="_parent" ');
			} else 
			{
				$rows[$i]['m_email'] = get_mailto_url($_eml, $rows[$i]['m_name'], true);
			}	// if()
			$q = "SELECT mg_name FROM ".$TB['MEMBER_GROUP']." WHERE d_no='" . $G['DINFO']['d_no'] . "' AND mg_no='" . $rows[$i]['mg_no'] . "'";
			$rows[$i]['mg_no'] = db_get_one($q);

			// [2011-01-07] 조직도 상세정보
			$rows[$i]['m_name'] = '<a href="JavaScript:window_open(\''.$nmpath.'/member_info.php?m_no='.$rows[$i]['m_no'].'\', \'\', 750, 550);">'.$rows[$i]['m_name'].'</a>';

			// [2011-01-10] 조직도 항목관리
			if (is_array($G_SYS['MEMBER_LIST_ADD_FIELD']))
			{
				foreach ($G_SYS['MEMBER_LIST_ADD_FIELD'] as $key=>$val)
				{
					$key = str_replace('m.', '', $key);
					if ($rows[$i][$key] == '--' || $rows[$i][$key] == '-' || $rows[$i][$key] == '0000-00-00')
						$rows[$i][$key] = '';
					switch ($key)
					{
						case 'm_birthday':		// 생년월일 - 음력여부를 함께 표시.
							$rows[$i][$key] = $rows[$i][$key];
							if ($rows[$i]['m_birthday_east'] != '')
								$rows[$i][$key] .= ' ('.$G[BIRTHDAY_EAST][$rows[$i]['m_birthday_east']].')';
							break;

						case 'm_home_addr1':	// 주소 - 상세주소를 함께 표시.
							$rows[$i][$key] = $rows[$i][$key].' '.$rows[$i]['m_home_addr2'];
							break;

						case 'm_office_addr1':	// 주소 - 상세주소를 함께 표시.
							$rows[$i][$key] = $rows[$i][$key].' '.$rows[$i]['m_office_addr2'];
							break;

						case 'm_homepage':	// 홈페이지 - 링크
							$rows[$i][$key] = '<a href="'.$rows[$i][$key].'" target="_blank">'.$rows[$i][$key].'</a>';
							break;

						case 'm_sex':
							$rows[$i][$key] = $G[SEX][$rows[$i][$key]];
							break;

						case 'm_ismarry':
							$rows[$i][$key] = $G[ISMARRY][$rows[$i][$key]];
							break;

						case 'm_memo':	// 자기소개 - 줄바꿈
							$rows[$i][$key] = han_substr($rows[$i][$key], 40);
							break;
					}	// switch()
				}	// foreach()				
			}	// if()
		}	// for()
		$rows = db_rows_fieldtokey($rows);
		$rows_cnt = getarraycount($rows['m_name']);

		$DEBUG['db_fetch_all']['exec'] += getmicrotime() - $DEBUG['db_fetch_all']['start'];

	// 주소록수
		$addr_all_cnt = number_format($pager_params['totalItems']);


	// [2011-08-25] 회원직위
	$q = "SELECT * FROM ".$TB['MEMBER_CLASS']." WHERE d_no='".$G['DINFO']['d_no']."' ORDER BY mc_sort, mc_name";
	$mbr_class = db_get_rows($q, true);
	if ($mbr_class)
	{
		$select_mbr_class = select_list_value($_GET['s_mc_no'], $mbr_class['mc_name'], $mbr_class['mc_no'], '전체 직위', 0, 1);
	}	// if()


// skin view
	$layout = ($_GET['is_iframe']) ? 'iframe' : 'self';
	nskinset('webmail', 'member_list.html', $layout);
	include($NSKIN['view_layout']);

	// [2008-08-22] 주소록 그룹이 좌측에 보여지는 스킨일때
	if ($_GET['is_iframe'])
		nm_iframe_load('_nm_address_list_frame', '_nm_address_list_title', $CFG['TITLE']);

require_once('include/global_end.php');
?>