#!/usr/bin/php
<?
chdir(dirname(__FILE__));
require_once('../nmail/include/global.php');
require_once("include/mail_lib.php");
require_once('include/admin_lib.php');
require_once("include/file.php");

// 웹상에서의 실행방지.
if ($_SERVER['DOCUMENT_ROOT'] || $_SERVER['SERVER_SOFTWARE'])
{
	die("Access Denied");
}	// if()

$_time = time();

// [2009-05-06] root권한으로만 실행되도록 함.
	if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
	{
		ob_start();
		system('whoami');
		$whoami = trim(ob_get_contents());
		ob_end_clean();
		if ($whoami != '' && $whoami != 'root')
		{
			die("[에러]root 계정에서 실행하셔야 합니다.  업데이트가 적용되지 않았습니다.\n");
		}	// if()
	}	// if()


echo "[Nmail PHP 3] 업데이트를 적용중입니다.  완료 메세지가 나올때까지 중단하지 마십시오.\n\n";
echo "  안내) 작업도중 이미 업데이트된 부분은 자동으로 넘어가므로, 중복실행하더라도 에러가 생기지는 않습니다.\n\n";


// [2009-05-07] Windows UTF-8 버젼에서는 한글출력을 위해 update_db.php 파일이 euc-kr로 되어 있음.  그러나 DB나 파일에 저장되는 부분은 UTF-8로 변환필요.
function win_utf8_conv($str)
{
	if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' && strtoupper($G_SYS[CHARSET]) == 'UTF-8')
		$str = iconv_fix('CP949', $str, 'UTF-8');
	return $str;
}	// function()


// set
set_time_limit(0);

// [2008-10-21] 업데이트시 한번만 실행하는 루틴의 임시파일 저장 디렉토리
$updated_dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'updated';
if (!is_dir($updated_dir))
	mkdir($updated_dir);

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
{
	$cmd_mv = 'move';
	$cmd_rm = 'rmdir/q/s';
	$crlf = "\r\n";
} else {
	$cmd_mv = 'mv';
	$cmd_rm = 'rm -rf';
	$crlf   = "\n";
}

################################################################################

$_start = getmicrotime();

$patch_query = array();

$patch_query[drop] = "
ALTER TABLE nmail_domain DROP d_quota_mbr_use ;
";

$patch_query[create] = "
CREATE TABLE nmail_spam_reject (
  m_no int(10) unsigned NOT NULL default '0',
  sr_email varchar(255) NOT NULL default '',
  sr_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (m_no, sr_email),
  INDEX (sr_regdate)
);

CREATE TABLE nmail_auto_filter
(
  as_no bigint(20) unsigned NOT NULL auto_increment,
  m_no int(10) unsigned NOT NULL default '0',
  as_name varchar(255),
  as_condition varchar(255),
  as_condition_text text,
  as_exec varchar(255),
  as_exec_text text,
  as_econdition varchar(255),
  as_econdition_text text,
  as_is_use enum('Y','N') default 'Y',
  as_sort tinyint unsigned NOT NULL default '0',
  PRIMARY KEY  (as_no),
  KEY as_m_no (m_no)
);

CREATE TABLE nmail_spam_allow (
  m_no int(10) unsigned NOT NULL default '0',
  sa_email varchar(255) NOT NULL default '',
  sa_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (m_no,sa_email),
  KEY sa_regdate (sa_regdate)
) ;

CREATE TABLE nmail_spam_config (
  m_no int(10) unsigned NOT NULL default '0',
  sc_addr_allow enum('Y','N') NOT NULL default 'Y',
  sc_fake_del enum('Y','N') NOT NULL default 'N',
  sc_foreign_spam enum('Y','N') NOT NULL default 'N',
  sc_write_allow_add enum('Y','N') NOT NULL default 'Y',
  sc_from_subj_null_dell enum('Y','N') NOT NULL default 'N',
  sc_moddate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (m_no)
) ;

CREATE TABLE nmail_member_group (
  mg_no int(10) unsigned NOT NULL auto_increment,
  d_no int(10) unsigned NOT NULL default '0',
  mg_name varchar(50) default NULL,
  mg_quota_default int(10) unsigned NOT NULL default '0',
  PRIMARY KEY  (mg_no),
  KEY mg_d_no (d_no)
);

CREATE TABLE nmail_auto_reply_loop_check (
  m_no int(10) unsigned NOT NULL default '0',
  ar_lc_email varchar(255) NOT NULL default '',
  ar_lc_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (m_no,ar_lc_email),
  KEY ar_lc_regdate (ar_lc_regdate)
) ;

CREATE TABLE nmail_white_ip (
  ip_ipaddr varchar(15) NOT NULL default '',
  ip_netmask varchar(15) NOT NULL default '',
  ip_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (ip_ipaddr,ip_netmask),
  KEY ip_regdate (ip_regdate)
) ;
CREATE TABLE nmail_black_ip (
  ip_ipaddr varchar(15) NOT NULL default '',
  ip_netmask varchar(15) NOT NULL default '',
  ip_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (ip_ipaddr,ip_netmask),
  KEY ip_regdate (ip_regdate)
) ;
CREATE TABLE nmail_relay_ip (
  ip_ipaddr varchar(15) NOT NULL default '',
  ip_netmask varchar(15) NOT NULL default '',
  ip_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (ip_ipaddr,ip_netmask),
  KEY ip_regdate (ip_regdate)
) ;
CREATE TABLE nmail_mailing_list (
  m_no int(10) unsigned NOT NULL default '0',
  ml_email varchar(255) NOT NULL default '',
  ml_perms char(2) NOT NULL default 'RW',
  ml_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (m_no,ml_email),
  KEY ml_regdate (ml_regdate)
) ;
CREATE TABLE nmail_member_size (
m_no int(10) unsigned NOT NULL default '0',
ms_mail BIGINT UNSIGNED NOT NULL DEFAULT '0',
ms_bigfile BIGINT UNSIGNED NOT NULL DEFAULT '0',
ms_webhard BIGINT UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY  (m_no)
) ;
CREATE TABLE nmail_webhard_folder (
wfd_key INT UNSIGNED NOT NULL AUTO_INCREMENT ,
m_no INT UNSIGNED,
ws_key INT UNSIGNED,
wfd_parent INT UNSIGNED DEFAULT '0' NOT NULL ,
wfd_depth TINYINT UNSIGNED NOT NULL ,
wfd_name VARCHAR( 255 ) NOT NULL ,
wfd_issystem ENUM( 'Y', 'N' ) DEFAULT 'N' NOT NULL ,
wfd_memo TEXT,
wfd_regdate DATETIME NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY ( wfd_key ) ,
KEY wdf_m_no (m_no, wfd_parent),
KEY wdf_ws_key (ws_key)
);
CREATE TABLE nmail_webhard_file (
wf_key BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
m_no INT UNSIGNED DEFAULT '0' NOT NULL ,
wfd_key INT UNSIGNED NOT NULL,
wf_name VARCHAR( 255 ) NOT NULL ,
wf_size INT UNSIGNED DEFAULT '0' NOT NULL ,
wf_type VARCHAR( 10 ) ,
wf_memo TEXT,
wf_regdate DATETIME NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY ( wf_key ) ,
KEY wf_wfd_key (wfd_key),
KEY wf_m_no (m_no)
);
CREATE TABLE nmail_webhard_share (
ws_key BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
d_no INT UNSIGNED DEFAULT '0' NOT NULL ,
ws_name VARCHAR( 255 ) NOT NULL ,
ws_quota INT UNSIGNED DEFAULT '0' NOT NULL ,
ws_quota_use BIGINT UNSIGNED DEFAULT '0' NOT NULL ,
ws_mg_no TEXT,
ws_admin_id TEXT,
ws_perm VARCHAR( 7 ),
ws_memo TEXT,
ws_isuse ENUM( 'Y', 'N' ) DEFAULT 'Y' NOT NULL ,
ws_regdate DATETIME NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY ( ws_key ) ,
KEY ws_d_no (d_no)
);
CREATE TABLE nmail_bigfile (
bf_key BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
m_no INT UNSIGNED NOT NULL,
wf_key BIGINT UNSIGNED,
wfd_key INT UNSIGNED,
mf_no bigint(20) unsigned,
bf_to TEXT,
bf_subject VARCHAR( 255 ),
bf_type ENUM( 'B', 'W' ) DEFAULT 'B' NOT NULL ,
bf_name VARCHAR( 255 ) NOT NULL ,
bf_size INT UNSIGNED DEFAULT '0' NOT NULL ,
bf_down INT UNSIGNED DEFAULT '0' ,
bf_expire ENUM( 'Y', 'N' ) NOT NULL DEFAULT 'N' ,
bf_regdate DATETIME NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY ( bf_key ) ,
KEY bf_m_no (m_no)
);
CREATE TABLE nmail_log_smtp (
s_date date default NULL,
s_time time default NULL,
s_ip varchar(255) default NULL,
s_sender_user varchar(255) default NULL,
s_sender_dom varchar(255) default NULL,
s_rcpt_user varchar(255) default NULL,
s_rcpt_dom varchar(255) default NULL,
s_msgid varchar(255) default NULL,
s_status varchar(100) default NULL,
s_authuser varchar(255) default NULL,
s_msgsize bigint(20) unsigned default '0',
s_smail_type varchar(20) default NULL,
s_smail_rcpt_user varchar(255) default NULL,
s_smail_rcpt_dom varchar(255) default NULL,
s_smail_mx varchar(255) default NULL,
s_smail_date date default NULL,
s_smail_time time default NULL,
KEY ls_s_date (s_date,s_msgid(4))
);
CREATE TABLE nmail_log_pop3 (
p_date date default NULL,
p_time time default NULL,
p_ip varchar(255) default NULL,
p_user varchar(255) default NULL,
p_dom varchar(255) default NULL,
KEY lp_p_date (p_date)
);
CREATE TABLE nmail_member_group_rel (
mg_no int(10) unsigned NOT NULL default '0',
m_no int(10) unsigned NOT NULL default '0',
PRIMARY KEY  (mg_no, m_no)
);
CREATE TABLE nmail_member_class (
mc_no INT UNSIGNED NOT NULL AUTO_INCREMENT ,
d_no int(10) unsigned NOT NULL default '0',
mc_name VARCHAR(50) NOT NULL,
mc_sort TINYINT UNSIGNED NOT NULL DEFAULT '1',
PRIMARY KEY  (mc_no),
KEY mc_d_no (d_no)
);
CREATE TABLE nmail_letter_group (
lg_no INT UNSIGNED NOT NULL AUTO_INCREMENT ,
lg_name VARCHAR(50) NOT NULL,
lg_sort TINYINT UNSIGNED NOT NULL DEFAULT '1',
PRIMARY KEY  (lg_no)
);
CREATE TABLE nmail_letter (
l_no BIGINT UNSIGNED NOT NULL AUTO_INCREMENT ,
lg_no INT UNSIGNED NOT NULL,
l_name VARCHAR( 255 ) NOT NULL,
l_preview VARCHAR( 255 ),
l_top VARCHAR( 255 ),
l_top_w SMALLINT UNSIGNED NULL,
l_top_h SMALLINT UNSIGNED NULL,
l_middle VARCHAR( 255 ),
l_bottom VARCHAR( 255 ),
l_bottom_w SMALLINT UNSIGNED NULL,
l_bottom_h SMALLINT UNSIGNED NULL,
l_bgcolor VARCHAR( 20 ),
l_color VARCHAR( 20 ),
l_sort TINYINT UNSIGNED NOT NULL DEFAULT '1',
l_isuse ENUM( 'Y', 'N' ) NOT NULL DEFAULT 'Y' ,
l_memo TEXT,
l_regdate DATETIME NOT NULL default '0000-00-00 00:00:00',
l_send_cnt INT UNSIGNED DEFAULT '0' ,
l_lastsenddate DATETIME default '0000-00-00 00:00:00',
PRIMARY KEY ( l_no ) ,
KEY l_lg_no (lg_no)
);
CREATE TABLE nmail_log_return (
mr_no bigint(20) unsigned NOT NULL auto_increment,
mr_mail_from varchar(255) default NULL,
mr_rcpt_to varchar(255) default NULL,
mr_smtp_error_type tinyint(4) unsigned default NULL,
mr_smtp_error varchar(255) default NULL,
mr_smtp_error_str varchar(255) default NULL,
mr_smtp_server varchar(255) default NULL,
mr_msgid varchar(255) default NULL,
mr_hdr_subject varchar(255) default NULL,
mr_hdr_date datetime NOT NULL default '0000-00-00 00:00:00',
mr_date datetime NOT NULL default '0000-00-00 00:00:00',
mr_body text,
PRIMARY KEY  (mr_no),
KEY mr_hdr_date (mr_hdr_date),
KEY mr_msgid (mr_msgid)
);
CREATE TABLE nmail_log_filter (
f_no bigint(20) unsigned NOT NULL auto_increment,
m_no bigint(20) unsigned NOT NULL,
f_code varchar(10) NOT NULL,
f_action char(1) NOT NULL,
f_msgid varchar(255) default NULL,
f_memo varchar(255) default NULL,
f_mail_from varchar(255) default NULL,
f_rcpt_to varchar(255) default NULL,
f_hdr_from varchar(255) default NULL,
f_hdr_subject varchar(255) default NULL,
f_date datetime NOT NULL default '0000-00-00 00:00:00',
f_ip varchar(15) default NULL,
PRIMARY KEY  (f_no),
KEY lf_date (f_date),
KEY lf_msgid (f_msgid)
);
CREATE TABLE nmail_board_read_log (
  br_no bigint(20) unsigned NOT NULL auto_increment,
  ba_no smallint(5) unsigned NOT NULL default '0',
  b_no bigint(20) unsigned NOT NULL default '0',
  m_no int(10) unsigned NOT NULL default '0',
  br_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  br_reghost varchar(15) NOT NULL default '',
  PRIMARY KEY  (br_no),
  KEY br_b_no (b_no)
);
CREATE TABLE nmail_board_draft (
  bd_no bigint(20) unsigned NOT NULL auto_increment,
  m_no int(10) unsigned NOT NULL default '0',
  b_subject varchar(255) NOT NULL default '',
  b_memo mediumtext NOT NULL,
  bd_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  bd_reghost varchar(15) NOT NULL default '',
  PRIMARY KEY  (bd_no),
  KEY bd_m_no (m_no)
);
CREATE TABLE nmail_board_menu (
  bm_no smallint(5) unsigned NOT NULL auto_increment,
  d_no int(10) unsigned NOT NULL default '0',
  bm_name varchar(255) NOT NULL,
  bm_sort tinyint(3) unsigned NOT NULL default '1',
  PRIMARY KEY  (bm_no),
  KEY bm_d_no (d_no)
);
CREATE TABLE nmail_quota_alert (
  qa_no bigint(20) unsigned NOT NULL auto_increment,
  m_no int(10) unsigned NOT NULL default '0',
  qa_cursize bigint(20) unsigned NOT NULL default '0',
  qa_maxsize bigint(20) unsigned NOT NULL default '0',
  qa_date datetime NOT NULL default '0000-00-00 00:00:00',
  qa_type char(1) NOT NULL default 'L',
  PRIMARY KEY  (qa_no),
  KEY qa_m_no_date (m_no, qa_date)
);
CREATE TABLE nmail_domain_alias (
  da_no int(10) unsigned NOT NULL auto_increment,
  d_no int(10) unsigned NOT NULL default '0',
  da_name varchar(255) NOT NULL default '',
  da_regdate DATETIME NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (da_no),
  UNIQUE KEY da_name (d_no,da_name)
);
CREATE TABLE nmail_log_login (
d_no int(10) unsigned NOT NULL,
m_no int(10) unsigned NOT NULL,
m_id VARCHAR( 50 ) NOT NULL,
l_date date NOT NULL,
l_time time NOT NULL,
l_ip varchar(15) NOT NULL,
l_status enum('OK','FI','FP','LID','LIP') NOT NULL,
KEY l_l_date_time (l_date, l_time),
KEY l_l_date_ip (l_date, l_ip),
KEY l_l_date_m_no (l_date, m_no),
KEY l_l_date_d_no (l_date, d_no)
);
CREATE TABLE nmail_log_member (
d_no int(10) unsigned NOT NULL,
m_no int(10) unsigned NOT NULL,
m_id VARCHAR( 50 ) NOT NULL,
l_date date NOT NULL,
l_time time NOT NULL,
l_ip varchar(15) NOT NULL,
l_admin_id VARCHAR( 255 ) NOT NULL,
l_status enum('ADD','DEL','MODP') NOT NULL,
KEY l_m_date_time (l_date, l_time),
KEY l_m_date_ip (l_date, l_ip),
KEY l_m_date_m_no (l_date, m_no),
KEY l_m_date_d_no (l_date, d_no)
);
CREATE TABLE nmail_web_allow_ip (
  d_no int(10) unsigned NOT NULL,
  ip_ipaddr varchar(15) NOT NULL default '',
  ip_netmask varchar(15) NOT NULL default '',
  ip_memo varchar(255),
  ip_regdate datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY (d_no, ip_ipaddr,ip_netmask),
  KEY wa_ip_regdate (ip_regdate)
);
CREATE TABLE nmail_sadmin_spam_addr (
  ssa_email varchar(255) NOT NULL DEFAULT '',
  ssa_regdate datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (ssa_email),
  KEY ssa_regdate (ssa_regdate)
);
CREATE TABLE nmail_sadmin_spam_word (
  ssw_word varchar(255) NOT NULL DEFAULT '',
  ssw_regdate datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (ssw_word),
  KEY ssw_regdate (ssw_regdate)
);
CREATE TABLE nmail_smtp_send (
s_date date default NULL,
s_time time default NULL,
s_ip varchar(15) default NULL,
m_no int(10) unsigned NOT NULL default '0',
s_rcpt_user varchar(255) default NULL,
s_rcpt_dom varchar(255) default NULL,
s_subject varchar(255) default NULL,
s_msgsize bigint(20) unsigned default '0',
KEY smtp_s_date_ip (s_date,s_ip),
KEY smtp_s_date_mno (s_date,m_no)
);
CREATE TABLE nmail_smtp_send_deny (
s_date date default NULL,
s_time time default NULL,
s_ip varchar(15) default NULL,
m_no int(10) unsigned NOT NULL default '0',
s_limit_cnt int(10) unsigned NOT NULL default '0',
s_limit_msg char(3) default NULL,
KEY smtp_sd_date (s_date)
);
CREATE TABLE nmail_team_mail (
tm_no int(10) unsigned NOT NULL auto_increment,
d_no int(10) unsigned NOT NULL default '0',
m_id varchar(50) NOT NULL default '',
team_m_id varchar(50) NOT NULL default '',
tm_is_use enum('Y','N') default 'Y',
tm_memo text,
tm_regdate DATETIME NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY  (tm_no),
UNIQUE KEY da_name (d_no, m_id, team_m_id)
);
CREATE TABLE nmail_member_device (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
m_no INT UNSIGNED NOT NULL,
os VARCHAR(255) NOT NULL,
user_agent VARCHAR(255) NOT NULL,
device_token VARCHAR(128) NOT NULL,
is_trusted enum('Y','N') default 'N',
ip VARCHAR(15),
created_at DATETIME DEFAULT '0000-00-00 00:00:00',
last_logindate datetime default '0000-00-00 00:00:00',
last_loginhost VARCHAR(15),
PRIMARY KEY (id),
UNIQUE KEY token (m_no, device_token)
);
CREATE TABLE nmail_mail_star (
id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
ms_m_no INT UNSIGNED NOT NULL,
ms_mf_no bigint(20) unsigned,
created_at DATETIME DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (id),
UNIQUE KEY token (ms_m_no, ms_mf_no)
);
CREATE TABLE nmail_monitor (
     id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
     cmd TEXT NOT NULL,
     result MEDIUMTEXT NOT NULL,
     df MEDIUMTEXT NOT NULL,
     created_at DATETIME DEFAULT '0000-00-00 00:00:00',
     PRIMARY KEY (id)
);
";

$patch_query[add] = "
ALTER TABLE nmail_member ADD m_forwarding_type ENUM( 'N', 'Y', 'C' ) DEFAULT 'N' NOT NULL AFTER m_forwarding ;
ALTER TABLE nmail_member_field ADD d_no INT UNSIGNED DEFAULT '0' NOT NULL AFTER mbf_no ;
ALTER TABLE nmail_domain ADD d_quota_mbr_count INT UNSIGNED DEFAULT '100' NOT NULL AFTER d_quota_mbr_default ;
ALTER TABLE nmail_domain ADD d_memo TEXT;
ALTER TABLE nmail_domain ADD d_regdate DATETIME NOT NULL ;

ALTER TABLE nmail_mail_receive_check
ADD mrcext_m_id VARCHAR( 50 ) default NULL,
ADD mrcext_d_name VARCHAR( 255 ) default NULL,
ADD mrcext_key VARCHAR( 10 ) default NULL,
ADD mrcext_ip VARCHAR( 15 ) default NULL;

ALTER TABLE nmail_member ADD mg_no INT UNSIGNED AFTER d_no ;
ALTER TABLE nmail_member ADD m_autoreply_isuse ENUM( 'Y', 'N' ) DEFAULT 'N' NOT NULL;
ALTER TABLE nmail_member ADD m_autoreply_subject VARCHAR( 255 );
ALTER TABLE nmail_member ADD m_autoreply_body TEXT;

ALTER TABLE nmail_domain ADD d_saveday TINYINT UNSIGNED DEFAULT '0'  AFTER d_quota_mbr_count ;
ALTER TABLE nmail_mail_box ADD mb_saveday TINYINT UNSIGNED DEFAULT '0' ;

ALTER TABLE nmail_member ADD m_suspend_start DATE;
ALTER TABLE nmail_member ADD m_suspend_end DATE;
ALTER TABLE nmail_member ADD m_use_start DATE;
ALTER TABLE nmail_member ADD m_use_end DATE;

ALTER TABLE nmail_domain ADD d_skin_main VARCHAR( 20 ) NOT NULL DEFAULT 'basic' AFTER d_saveday;
ALTER TABLE nmail_domain ADD d_skin_webmail VARCHAR( 20 ) NOT NULL DEFAULT 'basic' AFTER d_skin_main;
ALTER TABLE nmail_domain ADD d_skin_member VARCHAR( 20 ) NOT NULL DEFAULT 'basic' AFTER d_skin_webmail;
ALTER TABLE nmail_domain ADD d_skin_board VARCHAR( 20 ) NOT NULL DEFAULT 'basic' AFTER d_skin_member;

ALTER TABLE nmail_domain ADD d_shareaddr_isuse ENUM( 'Y', 'N' ) NOT NULL DEFAULT 'Y' AFTER d_skin_board ;
ALTER TABLE nmail_domain ADD d_shareaddr_reg ENUM( 'U', 'A' ) NOT NULL DEFAULT 'U' AFTER d_shareaddr_isuse ;
ALTER TABLE nmail_domain ADD d_sharediary_isuse ENUM( 'Y', 'N' ) NOT NULL DEFAULT 'Y' AFTER d_shareaddr_isuse ;
ALTER TABLE nmail_domain ADD d_sharediary_reg ENUM( 'U', 'A' ) NOT NULL DEFAULT 'U' AFTER d_sharediary_isuse ;

ALTER TABLE nmail_addr_group ADD d_no INT UNSIGNED NULL ;
ALTER TABLE nmail_addr ADD ad_no_share BIGINT unsigned;

ALTER TABLE nmail_diary ADD d_no INT UNSIGNED NULL ;
ALTER TABLE nmail_diary ADD di_no_share BIGINT UNSIGNED NULL ;

ALTER TABLE nmail_domain ADD d_quota_board INT UNSIGNED NOT NULL DEFAULT '2097152' AFTER d_quota_mbr_count ;
ALTER TABLE nmail_board ADD b_file_size INT UNSIGNED NOT NULL DEFAULT '0' AFTER b_file ;

ALTER TABLE nmail_member ADD m_cfg_new_mail_box VARCHAR( 255 ) NULL DEFAULT 'inbox|spam';
ALTER TABLE nmail_member ADD m_cfg_new_cnt TINYINT UNSIGNED NULL DEFAULT '7';
ALTER TABLE nmail_member ADD m_cfg_week_diray_cnt TINYINT UNSIGNED NULL DEFAULT '5';
ALTER TABLE nmail_member ADD m_cfg_from_name VARCHAR( 255 ) NULL ;
ALTER TABLE nmail_member ADD m_cfg_mail_list_cnt TINYINT UNSIGNED NULL DEFAULT '20';

ALTER TABLE nmail_domain ADD d_site_name VARCHAR( 255 ) NULL AFTER d_shareaddr_reg ;
ALTER TABLE nmail_domain ADD d_site_owner VARCHAR( 255 ) NULL AFTER d_site_name ;
ALTER TABLE nmail_domain ADD d_site_title VARCHAR( 255 )  NULL AFTER d_site_owner ;
ALTER TABLE nmail_domain ADD d_site_license TEXT NULL AFTER d_site_title ;

ALTER TABLE nmail_domain ADD d_svc_smtp enum('Y', 'N') DEFAULT 'Y' NOT NULL AFTER d_saveday ;
ALTER TABLE nmail_domain ADD d_svc_pop3 enum('Y', 'N') DEFAULT 'Y' NOT NULL AFTER d_svc_smtp ;
ALTER TABLE nmail_domain ADD d_svc_forward enum('Y', 'N') DEFAULT 'Y' NOT NULL AFTER d_svc_pop3 ;
ALTER TABLE nmail_member ADD m_svc_smtp enum('Y', 'N') DEFAULT 'Y' NOT NULL;
ALTER TABLE nmail_member ADD m_svc_pop3 enum('Y', 'N') DEFAULT 'Y' NOT NULL;

ALTER TABLE nmail_mail_receive_check ADD mrc_status CHAR( 1 ) NULL AFTER mrc_readdate;

ALTER TABLE nmail_member ADD m_usertype CHAR( 1 ) NULL ;

ALTER TABLE nmail_domain
ADD  d_bigfile_isuse enum('Y','N') NOT NULL default 'Y' AFTER d_svc_forward ,
ADD  d_bigfile_quota int(10) unsigned NOT NULL default '1048576' AFTER d_bigfile_isuse ,
ADD  d_bigfile_quota_default int(10) unsigned NOT NULL default '10240' AFTER d_bigfile_quota ,
ADD  d_webhard_isuse enum('Y','N') NOT NULL default 'N' AFTER d_bigfile_quota_default ,
ADD  d_webhard_quota int(10) unsigned NOT NULL default '0' AFTER d_webhard_isuse ,
ADD  d_webhard_quota_default int(10) unsigned NOT NULL default '102400' AFTER d_webhard_quota ;

ALTER TABLE nmail_member ADD m_bigfile_quota INT UNSIGNED NOT NULL DEFAULT '10240' AFTER m_quota ,
ADD m_webhard_quota INT UNSIGNED NOT NULL DEFAULT '0' AFTER m_bigfile_quota ;

ALTER TABLE nmail_domain ADD d_skin_webhard VARCHAR( 20 ) NOT NULL DEFAULT 'basic' AFTER d_skin_board ;

ALTER TABLE nmail_board_admin ADD ba_mg_no TEXT NULL AFTER ba_mbronly_reply ,
ADD ba_use_id TEXT NULL AFTER ba_mg_no ;

ALTER TABLE nmail_domain ADD d_site_logo1 VARCHAR( 255 ) NULL AFTER d_site_license ,
ADD d_site_logo2 VARCHAR( 255 ) NULL AFTER d_site_logo1 ;
ALTER TABLE nmail_domain ADD d_site_logo1_w SMALLINT UNSIGNED NULL AFTER d_site_logo1 ,
ADD d_site_logo1_h SMALLINT UNSIGNED NULL AFTER d_site_logo1_w ;
ALTER TABLE nmail_domain ADD d_site_logo2_w SMALLINT UNSIGNED NULL AFTER d_site_logo2 ,
ADD d_site_logo2_h SMALLINT UNSIGNED NULL AFTER d_site_logo2_w ;

ALTER TABLE nmail_board ADD b_files TEXT NULL AFTER b_file ;

ALTER TABLE nmail_member_group ADD mg_parent INT UNSIGNED NOT NULL DEFAULT '0' AFTER d_no ,
ADD mg_depth TINYINT UNSIGNED NOT NULL DEFAULT '1' AFTER mg_parent ,
ADD mg_sort TINYINT UNSIGNED NOT NULL DEFAULT '1' AFTER mg_depth ;
ALTER TABLE nmail_member ADD mc_no INT UNSIGNED NULL AFTER mg_no ;

ALTER TABLE nmail_domain ADD d_mbrgrp_isuse ENUM( 'Y', 'N' ) NOT NULL DEFAULT 'N' AFTER d_skin_webhard ;

ALTER TABLE nmail_webhard_share ADD ws_guest_id TEXT NULL AFTER ws_mg_no ;

ALTER TABLE nmail_member ADD m_cfg_from_addr VARCHAR( 255 ) NULL AFTER m_cfg_from_name ;

ALTER TABLE nmail_board_admin ADD ba_isuse_rewrite CHAR( 1 ) NOT NULL DEFAULT 'N' AFTER ba_isuse_reply ;
ALTER TABLE nmail_board_admin ADD ba_isuse_read_log CHAR( 1 ) NOT NULL DEFAULT 'N' AFTER ba_isuse_rewrite ;

ALTER TABLE nmail_board_admin ADD ba_perm_rewrite tinyint(3) unsigned NOT NULL default '3' AFTER ba_perm_reply;
ALTER TABLE nmail_board_admin ADD ba_perm_read_log tinyint(3) unsigned NOT NULL default '3' AFTER ba_perm_rewrite;

ALTER TABLE nmail_board_admin ADD bm_no SMALLINT UNSIGNED AFTER d_no ;
ALTER TABLE nmail_board_admin ADD ba_sort tinyint(3) unsigned NOT NULL default '1' AFTER bm_no ;

ALTER TABLE nmail_domain ADD d_mbrgrp_list TEXT AFTER d_mbrgrp_isuse;
ALTER TABLE nmail_domain ADD d_mbrgrp_view TEXT AFTER d_mbrgrp_list;

ALTER TABLE nmail_mail_receive_check ADD mrc_reserve_status char(1);

ALTER TABLE nmail_addr_group ADD adg_parent BIGINT UNSIGNED NOT NULL DEFAULT '0' AFTER adg_name;
ALTER TABLE nmail_addr_group ADD adg_depth TINYINT UNSIGNED NOT NULL DEFAULT '1' AFTER adg_parent;
ALTER TABLE nmail_addr_group ADD adg_sort TINYINT UNSIGNED NOT NULL DEFAULT '1' AFTER adg_depth;

ALTER TABLE nmail_domain_alias ADD da_mail_from_select ENUM( 'Y', 'N' ) NOT NULL DEFAULT 'N' AFTER da_name;

ALTER TABLE nmail_domain_alias ADD da_memo TEXT NULL AFTER da_mail_from_select ;

ALTER TABLE nmail_smtp_send ADD s_rcpt_count SMALLINT UNSIGNED NOT NULL DEFAULT '1';

ALTER TABLE nmail_smtp_send ADD s_msgid varchar(255) default NULL;

ALTER TABLE nmail_log_pop3 ADD p_login varchar(16) default NULL;

ALTER TABLE nmail_pop3 ADD p3_authtype varchar(10) default 'CLR';

ALTER TABLE nmail_pop3 ADD p3_leave varchar(10) default NULL;

ALTER TABLE nmail_member ADD m_team_mail_is_use ENUM( 'Y', 'N' ) NOT NULL DEFAULT 'N';

ALTER TABLE nmail_mail_box ADD mb_parent varchar(5) NOT NULL DEFAULT '0' AFTER mb_is_system ,
ADD mb_depth TINYINT UNSIGNED NOT NULL DEFAULT '1' AFTER mb_parent;

ALTER TABLE nmail_member ADD m_2fa_isuse enum('Y', 'N') NOT NULL DEFAULT 'N';
ALTER TABLE nmail_member ADD m_2fa_code varchar(255) NULL;
ALTER TABLE nmail_member ADD m_2fa_ip varchar(15) NULL;
ALTER TABLE nmail_member ADD m_2fa_date DATETIME NULL;

ALTER TABLE nmail_domain ADD d_svc_2fa enum('Y', 'N') DEFAULT 'N' NOT NULL AFTER d_svc_forward;

ALTER TABLE nmail_member ADD m_2fa_required enum('Y', 'N') NOT NULL DEFAULT 'N' AFTER m_2fa_isuse;

ALTER TABLE nmail_member_device ADD session_id VARCHAR(255) NOT NULL;

ALTER TABLE nmail_web_allow_ip ADD m_id VARCHAR(255) NOT NULL DEFAULT '' AFTER d_no;

ALTER TABLE nmail_white_ip ADD ip_memo varchar(255) AFTER ip_netmask;
ALTER TABLE nmail_relay_ip ADD ip_memo varchar(255) AFTER ip_netmask;
ALTER TABLE nmail_black_ip ADD ip_memo varchar(255) AFTER ip_netmask;

ALTER TABLE nmail_sadmin_spam_word ADD ssw_memo varchar(255) AFTER ssw_word;
ALTER TABLE nmail_sadmin_spam_addr ADD ssa_memo varchar(255) AFTER ssa_email;

ALTER TABLE nmail_sadmin_spam_word DROP PRIMARY KEY, ADD ssw_no bigint(20) unsigned NOT NULL auto_increment FIRST, ADD PRIMARY KEY (ssw_no);

ALTER TABLE nmail_smtp_send ADD s_send_user VARCHAR(255) NOT NULL DEFAULT '' AFTER m_no;
ALTER TABLE nmail_smtp_send ADD s_send_dom VARCHAR(255) NOT NULL DEFAULT '' AFTER s_send_user;
ALTER TABLE nmail_domain ADD d_webmail_url VARCHAR(255) NULL AFTER d_name;
ALTER TABLE nmail_domain ADD d_svc_external_pop3 enum('Y','N') default 'Y' AFTER d_svc_forward;
ALTER TABLE nmail_domain ADD d_svc_mailing_list enum('Y','N') default 'Y' AFTER d_svc_external_pop3;
ALTER TABLE nmail_domain ADD d_site_top_notice TEXT NULL AFTER d_site_title;
ALTER TABLE nmail_domain ADD d_site_bottom_notice TEXT NULL AFTER d_site_top_notice;
ALTER TABLE nmail_domain ADD d_site_favicon VARCHAR(255) NULL AFTER d_site_logo2_h;
ALTER TABLE nmail_domain ADD d_skin_limit_level enum('7','9') default '7' AFTER d_saveday;
ALTER TABLE nmail_domain ADD d_skin_birthday enum('Y','N') default 'Y' AFTER d_skin_webhard;
ALTER TABLE nmail_domain ADD d_sharediary_target enum('0', '1') default '1' AFTER d_sharediary_reg;
ALTER TABLE nmail_domain ADD d_login_signup enum('Y','N') default 'Y' AFTER d_site_favicon;
ALTER TABLE nmail_domain ADD d_login_account_recovery enum('Y','N') default 'Y' AFTER d_login_signup;
ALTER TABLE nmail_domain ADD d_login_profile_edit enum('Y','N') default 'Y' AFTER d_login_account_recovery;
ALTER TABLE nmail_domain ADD d_login_account_delete enum('Y','N') default 'Y' AFTER d_login_account_recovery;
ALTER TABLE nmail_domain ADD d_modifydate datetime NOT NULL default '0000-00-00 00:00:00';

ALTER TABLE nmail_log_member ADD d_name varchar(255) NOT NULL AFTER d_no;
ALTER TABLE nmail_log_login ADD d_name varchar(255) NOT NULL AFTER d_no;
ALTER TABLE nmail_member ADD m_emp_no varchar(255) default NULL AFTER m_level;

ALTER TABLE nmail_sign ADD sg_files TEXT NULL;
ALTER TABLE nmail_sign ADD sg_file_size INT UNSIGNED NOT NULL DEFAULT '0';

ALTER TABLE nmail_board ADD b_image_files TEXT NULL after b_file_size;
ALTER TABLE nmail_board ADD b_image_size INT UNSIGNED NOT NULL DEFAULT '0' after b_image_files;
ALTER TABLE nmail_member ADD m_send_preview enum('Y','N') DEFAULT 'N';
ALTER TABLE nmail_member ADD m_mail_box_backup_type enum('filename','subject') DEFAULT 'filename';

ALTER TABLE nmail_member_device ADD browser VARCHAR(255) NOT NULL;

ALTER TABLE nmail_member ADD m_smtp_auth_date datetime default NULL;
ALTER TABLE nmail_member ADD m_pop3_auth_date datetime default NULL;
ALTER TABLE nmail_member ADD m_receive_date datetime default NULL;

ALTER  TABLE nmail_log_pop3 ADD p_count bigint(20) unsigned NOT NULL;
ALTER  TABLE nmail_log_pop3 ADD p_size bigint(20) unsigned NOT NULL;

ALTER TABLE nmail_mail_box ADD mb_open enum('Y','N') DEFAULT 'Y';

ALTER TABLE nmail_mail_box ADD html_limit enum('Y', 'N') DEFAULT 'N';

ALTER TABLE nmail_team_mail ADD tm_is_from_use enum('Y','N') default 'N' after tm_is_use;
";

// 1회만 실행되는 쿼리 - updated/patch_query_normal 파일에 쿼리 문자열 기록후 중복 방지
//   index drop & add, update, delete, alter table change
$patch_query[normal] = "
ALTER TABLE nmail_member_field DROP INDEX mbf_name , ADD UNIQUE mbf_name ( d_no , mbf_name ) ;
UPDATE nmail_member_field SET mbf_issystem='N' WHERE mbf_name IN ('m_jumin', 'm_lostpwd_q', 'm_lostpwd_a');
ALTER TABLE nmail_domain CHANGE d_quota d_quota INT( 10 ) UNSIGNED DEFAULT '2097152' NOT NULL;
ALTER TABLE nmail_domain CHANGE d_quota_mbr_default d_quota_mbr_default INT( 10 ) UNSIGNED DEFAULT '20480' NOT NULL;
ALTER TABLE nmail_member_field CHANGE mbf_no mbf_no INT UNSIGNED NOT NULL AUTO_INCREMENT;
UPDATE nmail_diary SET di_content='기념일' WHERE m_no='0' AND di_subject='식목일' AND di_startdate='1900-04-05' AND di_content='공휴일';
UPDATE nmail_diary SET di_startdate='1900-05-15', di_enddate='1900-05-15' WHERE m_no='0' AND di_subject='스승의 날' AND di_startdate='1900-05-08' AND di_content='기념일';
UPDATE nmail_mail_receive_check SET mrc_status='N' WHERE mrc_readdate IS NULL AND mrc_status IS NULL;
UPDATE nmail_mail_receive_check SET mrc_status='R' WHERE mrc_readdate IS NOT NULL AND mrc_status IS NULL;
ALTER TABLE nmail_diary_lunar CHANGE lunar_date lunar_date VARCHAR( 10 ) NOT NULL DEFAULT '0000-00-00';
ALTER TABLE nmail_log_smtp DROP INDEX ls_s_date , ADD INDEX ls_s_date ( s_date , s_msgid ( 7 ) );
ALTER TABLE nmail_log_smtp CHANGE s_msgid s_msgid VARCHAR( 20 ) NULL DEFAULT NULL ;
UPDATE nmail_diary SET di_content='기념일' WHERE m_no='0' AND di_subject='제헌절' AND di_startdate='1900-07-17' AND di_content='공휴일';
ALTER TABLE nmail_board CHANGE b_memo b_memo MEDIUMTEXT NOT NULL;
UPDATE nmail_domain SET d_mbrgrp_list='m_mobile|m_office_tel', d_mbrgrp_view='m_mobile|m_office_tel' WHERE d_mbrgrp_list IS NULL;
UPDATE nmail_member SET m_etc2='0' WHERE m_usertype='M' AND m_etc2='';
ALTER TABLE nmail_log_login CHANGE l_status l_status ENUM( 'OK', 'FI', 'FP', 'LID', 'LIP', 'DIP' ) NOT NULL DEFAULT 'OK';
ALTER TABLE nmail_spam_config CHANGE sc_fake_del sc_fake_del enum('N') NOT NULL default 'N';
ALTER TABLE nmail_domain CHANGE d_skin_main d_skin_main VARCHAR( 20 ) NOT NULL DEFAULT 'bootstrap' AFTER d_saveday;
ALTER TABLE nmail_domain CHANGE d_skin_webmail d_skin_webmail VARCHAR( 20 ) NOT NULL DEFAULT 'bootstrap' AFTER d_skin_main;
ALTER TABLE nmail_domain CHANGE d_skin_member d_skin_member VARCHAR( 20 ) NOT NULL DEFAULT 'bootstrap' AFTER d_skin_webmail;
ALTER TABLE nmail_domain CHANGE d_skin_board d_skin_board VARCHAR( 20 ) NOT NULL DEFAULT 'bootstrap' AFTER d_skin_member;
ALTER TABLE nmail_domain CHANGE d_skin_webhard d_skin_webhard VARCHAR( 20 ) NOT NULL DEFAULT 'bootstrap' AFTER d_skin_board ;
ALTER TABLE nmail_domain MODIFY d_quota BIGINT ( 10 ) unsigned NOT NULL default '2097152';
ALTER TABLE nmail_member ADD m_last_pwdchgdate DATETIME NULL;
ALTER TABLE nmail_domain MODIFY d_quota BIGINT unsigned NOT NULL default '2097152';
ALTER TABLE nmail_domain MODIFY d_quota_board BIGINT unsigned NOT NULL default '2097152';
ALTER TABLE nmail_domain MODIFY d_bigfile_quota BIGINT unsigned NOT NULL default '10485760';
ALTER TABLE nmail_domain MODIFY d_webhard_quota BIGINT unsigned NOT NULL default '10485760';
ALTER TABLE nmail_webhard_file MODIFY wf_size BIGINT unsigned NOT NULL default 0;
ALTER TABLE nmail_mail_box MODIFY mb_name varchar(255) NOT NULL DEFAULT '';
ALTER TABLE nmail_web_allow_ip DROP PRIMARY KEY, ADD PRIMARY KEY (d_no, ip_ipaddr, ip_netmask, m_id);
ALTER TABLE nmail_log_login CHANGE l_status l_status ENUM( 'OK', 'FI', 'FP', 'LID', 'LIP', 'DID', 'DIP') NOT NULL DEFAULT 'OK';
ALTER TABLE nmail_sadmin_spam_word ADD UNIQUE KEY (ssw_word);
ALTER TABLE nmail_log_member CHANGE l_status l_status enum('ADD', 'DEL', 'MODP', 'SMTPS', 'SMTPUS', 'POP3S', 'POP3US', 'FORWARDS', 'FORWARDUS', '2FAS', '2FAUS', '2FARS', '2FARUS', 'MODMA', 'MODMU') NOT NULL;
UPDATE nmail_member_field SET mbf_maxlength=50 WHERE mbf_name='m_id' and mbf_maxlength=20;
ALTER TABLE nmail_member MODIFY m_id VARCHAR(255)  NOT NULL DEFAULT '';
ALTER TABLE nmail_member MODIFY m_pwd VARCHAR(255)  NOT NULL DEFAULT '';
ALTER TABLE nmail_board MODIFY b_pwd VARCHAR(255)  NOT NULL DEFAULT '';
ALTER TABLE nmail_board_comment MODIFY bc_pwd VARCHAR(255)  NOT NULL DEFAULT '';
UPDATE nmail_member_field SET mbf_text='이름' WHERE mbf_name='m_name' and mbf_text='이름(실명)';
UPDATE nmail_member_field SET mbf_text='휴대폰' WHERE mbf_name='m_mobile' and mbf_text='핸드폰(PCS)';
ALTER TABLE nmail_log_member CHANGE l_status l_status enum('ADD', 'DEL', 'WITHDRAWAL', 'MODP', 'LOSTOK', 'SMTPS', 'SMTPUS', 'POP3S', 'POP3US', 'FORWARDS', 'FORWARDUS', '2FAS', '2FAUS', '2FARS', '2FARUS', 'MODMA', 'MODMU') NOT NULL;
UPDATE nmail_mail_box SET html_limit = 'Y' WHERE mb_id IN ('spam', 'trash') AND html_limit = 'N';
";

$patch_query[index_add] = "
ALTER TABLE nmail_member ADD INDEX mg_no ( mg_no ) ;
ALTER TABLE nmail_member ADD INDEX m_quota ( d_no , m_quota );
ALTER TABLE nmail_addr ADD INDEX ad_email ( adg_no , ad_email ) ;
ALTER TABLE nmail_mail_receive_check ADD INDEX m_no ( m_no ) ;
ALTER TABLE nmail_addr_group ADD INDEX m_no ( m_no ) ;
ALTER TABLE nmail_addr_group ADD INDEX d_no ( d_no ) ;
ALTER TABLE nmail_diary ADD INDEX d_no ( d_no ) ;
ALTER TABLE nmail_board ADD INDEX ba_no ( ba_no ) ;
ALTER TABLE nmail_board_comment ADD INDEX b_no ( b_no ) ;
ALTER TABLE nmail_board_admin ADD INDEX d_no ( d_no ) ;
ALTER TABLE nmail_board ADD INDEX b_ref_list ( ba_no , b_ref , b_re_step ) ;
ALTER TABLE nmail_mail_receive_check ADD INDEX mrc_reserve_status ( mrc_reserve_status );
ALTER TABLE nmail_mail_receive_check ADD INDEX mrc_m_no_senddate ( m_no, mrc_senddate );
ALTER TABLE nmail_log_pop3 ADD INDEX lp_date_time ( p_date , p_time );
ALTER TABLE nmail_mail_receive_check ADD INDEX mrc_m_no_readdate ( m_no, mrc_readdate );
";

$patch_query[index_drop] = "
ALTER TABLE nmail_mail_receive_check DROP INDEX mrc_no_2 ;
ALTER TABLE nmail_mail_receive_check DROP INDEX mrc_no ;
ALTER TABLE nmail_addr_group DROP INDEX adg_no ;
ALTER TABLE nmail_board_category DROP INDEX ba_no ;
ALTER TABLE nmail_log_pop3 DROP INDEX lp_p_date;
";




################################################################################

function table_exists($table)
{
	global $db, $G_SYS;

	if ($G_SYS[DB] == 'oracle')
	{
		$q = "SELECT COUNT(*) FROM USER_OBJECTS WHERE OBJECT_NAME = '" . strtoupper($table) . "' AND OBJECT_TYPE = 'TABLE'";
	} else
	{
		$q = "SHOW TABLES LIKE '$table'";
	}	// if()
	$chk_objName = db_get_one($q);
	$table_exists = ($chk_objName) ? true : false;

	return $table_exists;
}	// function()


function field_exists($table, $name)
{
	global $db;

	$ti = $db->tableInfo($table);
	$field_exists = 0;
	for ($i=0; $i<sizeof($ti); $i++)
	{
		if ($ti[$i]['name'] == $name)
		{
			$field_exists = 1;
			break;
		}	// if()
	}	// for()
	return $field_exists;
}	// function()

function index_exists($table, $name)
{
	global $db;

	$q = "SHOW INDEX FROM $table";
	$idxs = db_get_rows($q);

	$field_exists = 0;
	for ($i=0; $i<sizeof($idxs); $i++)
	{
		if ($idxs[$i]['key_name'] == $name)
		{
			$field_exists = 1;
			break;
		}	// if()
	}	// for()

	return $field_exists;
}	// function()

function get_query_name($query, $str)
{
	$pt = '/'.$str.'[ `\r\n\t]+([a-z0-9_\-]+)/i';
	preg_match($pt, $query, $mc);

	if (!$mc[1])
		die("[Error]업데이트 작업중 다음 쿼리를 분석하는 과정에서 알 수 없는 원인으로 실패하였습니다.=>\n".$query);

	return $mc[1];
}	// function()


function db_index_diff($table, $idxs, $key_name, $colmun_name_chk)
{
	$cols = array();
	for ($i=0; $i<sizeof($idxs['key_name']); $i++)
	{
		if ($idxs['key_name'][$i] == $key_name)
		{
			$cols[] = $idxs['column_name'][$i];
		}	// if()
	}	// for()
	#vd($cols);

	if ($key_name == 'PRIMARY')
	{
		$idx_str = 'PRIMARY KEY';
	} else
	{
		$idx_str = 'INDEX '.$key_name;
	}	// if()

	if (sizeof($cols) > 0)
	{
		$diff = array_diff($colmun_name_chk, $cols);
		$diff2 = array_diff($cols, $colmun_name_chk);
		if (sizeof($diff) > 0 || sizeof($diff2) > 0)
		{
			#echo "인덱스 구성이 다르므로 삭제후 생성.";
			$q = "ALTER TABLE ".$table." DROP ".$idx_str.", ADD ".$idx_str." ( ".implode(',', $colmun_name_chk)." )";
			db_query_debug($q);
		}	// if()
	} else
	{
		#echo "인덱스가 없으므로 바로 생성.";
		$q = "ALTER TABLE ".$table." ADD ".$idx_str." ( ".implode(',', $colmun_name_chk)." )";
		db_query_debug($q);
	}	// if()
}	// function()


function db_query_debug($q)
{
	global $_start;
	if ( ! isset($_SERVER['argv'][1]) || $_SERVER['argv'][1] == 'DEBUG')
	{
		echo "    - Execute Query : " . trim($q)." (" . round((getmicrotime() - $_start),4) . "sec)\n";
		flush();
		db_query($q);
	} else if ($_SERVER['argv'][1] == 'TEST')
	{
		echo "    - View Query : " . trim($q)." (" . round((getmicrotime() - $_start),4) . "sec)\n";
		flush();
	} else
	{
		db_query($q);
	}	// if()
}	// function()


function scanf($msg, $values=array(), $length=64, $isupper=true, $allownull=false, $defalut_value=true)
{
	echo $msg;
	// [2006-09-06] AnNyung 1.2 에서 php stdin 사용시 문제가 발견됨.
	// [2006-11-13] Windows PHP 5.2.0 에서 입력안되던 문제 수정.
	// [2006-11-14] RWAPM 에서 STDIN 이 지원되지 않는 문제 발견.
	// [2007-01-29] 일부 Linux 에서 엔터를 2byte로 인식해서 scanf()가 반복되는 문제 해결.
	// [2013-07-18] 일부 Windows 에서 첫번째 입력시 Y 나 N을 입력한 경우, 두번째 항목은 자동으로 기본 선택이 되던 문제 해결.
	if (defined('STDIN'))
	{
		//$data = trim(fgets(STDIN,$length+1));
		$data = trim(fread(STDIN,$length+1));
	} else
	{
		$stdin = (file_exists("/dev/stdin")) ? "/dev/stdin" : "php://stdin";
		$fp = fopen($stdin,"r");
		//$data = trim(fgets($fp,$length+1));
		$data = trim(fread($fp,$length+1));
		fclose($fp);
	}	// if()
	if ($isupper)
		$data = strtoupper($data);

	if ($defalut_value && $values && $data == '')
	{
		$data = $values[0];
	}	// if()

	if (!$allownull && ($data == '' || ($values && sizeof($values) > 1 && !in_array($data, $values))))
	{
		$data = scanf($msg, $values, $length, $isupper, $allownull, $defalut_value);
	}	// if()

	return $data;
}	// function()


function title($msg)
{
	global $__TITLE_NO;
	global $crlf;
	if (!$__TITLE_NO)
	{
		$__TITLE_NO = 1;
	} else
	{
		$__TITLE_NO++;
	}	// if()
	echo $crlf;
	echo "==============================================================================".$crlf;
	echo "= [".$__TITLE_NO."] ".$msg.$crlf;
	echo "==============================================================================".$crlf;
}	// function()


################################################################################


nm_update_exec();

if ($G_SYS[DB] != 'oracle')
{
	title("DB 업데이트 시작 (updated/ 하위 락 파일을 통해 DB 중복 업데이트 방지됨)");

	$patch_query_key = array();
	$patch_query_key = array_keys($patch_query);


	for ($p=0; $p<sizeof($patch_query); $p++)
	{
		$ar_query = array();
		$ar_query = explode(";", $patch_query[$patch_query_key[$p]]);
		for ($i=0; $i<sizeof($ar_query)-1; $i++)		// 마지막 세미콜론(;)뒤의 문장은 주석뿐이거나 공백이므로 생략함.
		{
			$ar_query[$i] = trim($ar_query[$i]);
			if ($ar_query[$i] == '')
				continue;

			$isExecute = 1;

			if ($patch_query_key[$p] == 'normal')
			{
				$_table = '';
			} else
			{
				$_table = get_query_name($ar_query[$i], "TABLE");
			}	// if()

			switch($patch_query_key[$p])
			{
				case "drop":
					$_field = get_query_name($ar_query[$i], "DROP");
					if (!field_exists($_table, $_field))
					{
						$isExecute = 0;
					}	// if()
					break;

				case "create":
					if (table_exists($_table))
					{
						$isExecute = 0;
					}	// if()
					break;

				case "add":
					$_field = get_query_name($ar_query[$i], "ADD");
					if (field_exists($_table, $_field))
					{
						$isExecute = 0;
					}	// if()
					break;

				case "index_add":
					$_field = get_query_name($ar_query[$i], "ADD INDEX");
					if (index_exists($_table, $_field))
					{
						$isExecute = 0;
					}	// if()
					break;

				case "index_drop":
					$_field = get_query_name($ar_query[$i], "DROP INDEX");
					if (!index_exists($_table, $_field))
					{
						$isExecute = 0;
					}	// if()
					break;

				default:		// normal
					// 중복실행해도 되는부분
					// [2009-06-25] 업데이트 속도 개선을 위해 1회만 실행하도록 변경.
					$patch_query_normal = $updated_dir.DIRECTORY_SEPARATOR.'patch_query_normal';
					$_data = '';
					if (file_exists($patch_query_normal))
					{
						$_data = file_get_contents($patch_query_normal);
					}	// if()
					if (strpos($_data, $ar_query[$i]) !== false)
					{
						$isExecute = 0;
					} else
					{
						file_write($patch_query_normal, $_data.$crlf.$ar_query[$i].';');
					}	// if()
					break;
			}	// switch()

			if ($isExecute == 1)
			{
				db_query_debug($ar_query[$i]);
			}	// if()
		}	// for();
	}	// for()

	################################################################################
	# nmail_mail_file_?_????
	################################################################################

	$q = "SHOW TABLES LIKE 'nmail_mail_file_%'";
	$db->setFetchMode(DB_FETCHMODE_ORDERED);
	$mft = db_get_rows($q);
	$db->setFetchMode(DB_FETCHMODE_ASSOC);


	for ($i=0; $i<sizeof($mft); $i++)
	{
		#echo "\n".$mft[$i][0];

		// column
		if (!field_exists($mft[$i][0], 'mf_spam_point'))
		{
			$q = "ALTER TABLE ".$mft[$i][0]." ADD mf_spam_point FLOAT( 2 ) DEFAULT '0' NOT NULL";
			db_query_debug($q);
		}	// if()
		if (!field_exists($mft[$i][0], 'mf_is_userauth'))
		{
			$q = "ALTER TABLE ".$mft[$i][0]." ADD mf_is_userauth enum('Y', 'N')";
			db_query_debug($q);
		}	// if()
		if (!field_exists($mft[$i][0], 'mfext1'))
		{
			$q = "ALTER TABLE ".$mft[$i][0]." ADD mfext1 CHAR(1)";
			db_query_debug($q);
		}	// if()
		if (!field_exists($mft[$i][0], 'mfext2'))
		{
			$q = "ALTER TABLE ".$mft[$i][0]." ADD mfext2 VARCHAR( 20 )";
			db_query_debug($q);
		}	// if()
		if (!field_exists($mft[$i][0], 'mfext3'))
		{
			$q = "ALTER TABLE ".$mft[$i][0]." ADD mfext3 VARCHAR( 255 )";
			db_query_debug($q);
		}	// if()

		// index
		$q = "SHOW INDEX FROM ".$mft[$i][0];
		$idxs = db_get_rows($q, true);
		#vd($idxs['key_name']); vd($idxs['column_name']);
//		db_index_diff($mft[$i][0], $idxs, 'PRIMARY', array('mf_no'));
		db_index_diff($mft[$i][0], $idxs, 'mf_no', array('m_no', 'mb_id', 'mf_no'));
		db_index_diff($mft[$i][0], $idxs, 'mf_filename', array('mf_filename'));
		db_index_diff($mft[$i][0], $idxs, 'mno_mbid', array('m_no', 'mb_id', 'mf_is_read', 'mf_filesize'));
		db_index_diff($mft[$i][0], $idxs, 'mf_arrival_date', array('m_no', 'mb_id', 'mf_arrival_date'));
		db_index_diff($mft[$i][0], $idxs, 'm_no', array('m_no', 'mf_arrival_date'));
	}	// for()

	echo "\nDB 업데이트 작업이 완료되었습니다. (" . round((getmicrotime() - $_start),4) . "sec)\n";



	// [2025-12-11] utf8mb4_general_ci 사용시, utf8mb4_unicode_ci 으로 변환
	$convert_utf8mb4_unicode_ci = $updated_dir.DIRECTORY_SEPARATOR.'convert_utf8mb4_unicode_ci';
	if (!file_exists($convert_utf8mb4_unicode_ci))
	{
		if (
				$G_SYS[DB_CHARSET] === 'utf8mb4'
				&& (!isset($G_SYS[DB_CCOLLATE]) || $G_SYS[DB_CCOLLATE] !== 'utf8mb4_general_ci' )
		) {
			echo $crlf;
			title("DB collations 변경 : utf8mb4_general_ci -> utf8mb4_unicode_ci");

			$q = "SELECT default_character_set_name, default_collation_name FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?";
			$row = db_get_row($q, array($G_SYS[DB_NAME]));
			if ($row['default_character_set_name'] === 'utf8mb4' && $row['default_collation_name'] === 'utf8mb4_unicode_ci') {
				$q = "select table_name, engine, table_collation from information_schema.tables where table_schema = '" . $G_SYS[DB_NAME] . "' and table_collation != 'utf8mb4_unicode_ci' order by table_name";
				$rows = db_get_rows($q);
				if (count($rows) > 0) {
					foreach ($rows as $row) {
						if ($row['table_collation'] === 'utf8mb4_general_ci') {
							$q = "ALTER TABLE `" . $row['table_name']
									. "` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
							db_query_debug($q);
						}
					}
					echo "\nDB collations 변경이 " . count($rows) . "건 완료되었습니다. (" . round((getmicrotime() - $_start),4) . "sec)\n";
				} else {
					echo "\n변경이 필요한 DB 테이블이 없습니다. (" . round((getmicrotime() - $_start),4) . "sec)\n";
				}
			}
		}

		touch($convert_utf8mb4_unicode_ci);
	}	// if()

	// [2025-12-23] utf8_general_ci 사용시, utf8_unicode_ci 으로 변환
	$convert_utf8_unicode_ci = $updated_dir.DIRECTORY_SEPARATOR.'convert_utf8_unicode_ci';
	if (!file_exists($convert_utf8_unicode_ci))
	{
		if (
				$G_SYS[DB_CHARSET] === 'utf8'
				&& (!isset($G_SYS[DB_CCOLLATE]) || $G_SYS[DB_CCOLLATE] !== 'utf8_general_ci' )
		) {
			echo $crlf;
			title("DB collations 변경 : utf8_general_ci -> utf8_unicode_ci");

			$q = "SELECT default_character_set_name, default_collation_name FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?";
			$row = db_get_row($q, array($G_SYS[DB_NAME]));
			if ($row['default_character_set_name'] === 'utf8' && $row['default_collation_name'] === 'utf8_unicode_ci') {
				$q = "select table_name, engine, table_collation from information_schema.tables where table_schema = '" . $G_SYS[DB_NAME] . "' and table_collation != 'utf8_unicode_ci' order by table_name";
				$rows = db_get_rows($q);
				if (count($rows) > 0) {
					foreach ($rows as $row) {
						if ($row['table_collation'] === 'utf8_general_ci') {
							$q = "ALTER TABLE `" . $row['table_name']
									. "` CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci";
							db_query_debug($q);
						}
					}
					echo "\nDB collations 변경이 " . count($rows) . "건 완료되었습니다. (" . round((getmicrotime() - $_start),4) . "sec)\n";
				} else {
					echo "\n변경이 필요한 DB 테이블이 없습니다. (" . round((getmicrotime() - $_start),4) . "sec)\n";
				}
			}
		}

		touch($convert_utf8_unicode_ci);
	}	// if()


	// [2026-01-12] utf8mb3_general_ci 사용시, utf8mb3_unicode_ci 으로 변환
	$convert_utf8mb3_unicode_ci = $updated_dir.DIRECTORY_SEPARATOR.'convert_utf8mb3_unicode_ci';
	if (!file_exists($convert_utf8mb3_unicode_ci))
	{
		if (
			$G_SYS[DB_CHARSET] === 'utf8mb3'
			&& (!isset($G_SYS[DB_CCOLLATE]) || $G_SYS[DB_CCOLLATE] !== 'utf8mb3_general_ci' )
		) {
			echo $crlf;
			title("DB collations 변경 : utf8mb3_general_ci -> utf8mb3_unicode_ci");

			$q = "SELECT default_character_set_name, default_collation_name FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?";
			$row = db_get_row($q, array($G_SYS[DB_NAME]));
			if ($row['default_character_set_name'] === 'utf8mb3' && $row['default_collation_name'] === 'utf8mb3_unicode_ci') {
				$q = "select table_name, engine, table_collation from information_schema.tables where table_schema = '" . $G_SYS[DB_NAME] . "' and table_collation != 'utf8mb3_unicode_ci' order by table_name";
				$rows = db_get_rows($q);
				if (count($rows) > 0) {
					foreach ($rows as $row) {
						if ($row['table_collation'] === 'utf8mb3_general_ci') {
							$q = "ALTER TABLE `" . $row['table_name']
								. "` CONVERT TO CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci";
							db_query_debug($q);
						}
					}
					echo "\nDB collations 변경이 " . count($rows) . "건 완료되었습니다. (" . round((getmicrotime() - $_start),4) . "sec)\n";
				} else {
					echo "\n변경이 필요한 DB 테이블이 없습니다. (" . round((getmicrotime() - $_start),4) . "sec)\n";
				}
			}
		}

		touch($convert_utf8mb3_unicode_ci);
	}	// if()
}	// if()		// oracle


// [2008-10-21] 수정화면에서 메일용량을 변경할 경우 실제 서버에 반영안되는 문제수정.
$mbr_quota_update = $updated_dir.DIRECTORY_SEPARATOR.'mbr_quota_update';
if (!file_exists($mbr_quota_update))
{
	$q = "
		SELECT
			m.m_id, m.m_quota, d.d_name
		FROM
			".$TB['MEMBER']." m,
			".$TB['DOMAIN']." d
		WHERE
			m.d_no=d.d_no
			AND m.m_usertype IS NULL
		";
	$rows = db_get_rows($q);
	for ($i=0; $i<sizeof($rows); $i++)
	{
		$G_SYS['MAIL_DOMAIN'] = $rows[$i]['d_name'];
		mbr_quota_mod($rows[$i]['m_id'], $rows[$i]['m_quota']);
	}	// for()
	touch($mbr_quota_update);

	echo " [OK]메일계정의 메일용량이 제대로 수정되지 않았던 문제가 일괄 수정되었습니다.\n\n";
}	// if()


// [2009-03-27] White IP 에서는 RBL 체크 생략
// 설정파일과 디비간의 차이가 있을 경우 동기화를 시켜줌.
// 동기화조건 : 디비에 없는 설정파일의 내용을 디비에 추가한 다음, 디비를 기준으로 설정파일을 새로 생성함.
nm_iptab_dbsync($TB['WHITE_IP'], 'smtp.ipprop.tab');
nm_iptab_dbsync($TB['BLACK_IP'], 'spammers.tab');
nm_iptab_dbsync($TB['RELAY_IP'], 'smtprelay.tab');

set_time_limit(0);
function nmail_skin_auto_update($backup_dir, $skins, $search, $replace)
{
	global $G_SYS;

	$modify_files = array();
	foreach ($skins as $skin_dir=>$skin_files)
	{
		$skin_main = $G_SYS[PAGE_ROOT].'/skin/'.$skin_dir.'/';
		if (is_dir($skin_main))
		{
			$handle=opendir($skin_main);
			while ($node = readdir($handle))
			{
			   if ($node!="." && $node!=".." && is_dir($skin_main.$node))
			   {
				   // test - 특정 스킨만
				   //if ($node == 'basic2.5_up_test')
				   if (1)
				   {
					   $_is_ok = true;
					   foreach ($skin_files as $key=>$val)
					   {
						   if (!file_exists($skin_main.$node.DIRECTORY_SEPARATOR.$val))
						   {
							   $_is_ok = false;
							   break;
						   }	// if()
					   }	// foreach()
					   if ($_is_ok)
					   {
							if (!is_dir($backup_dir.DIRECTORY_SEPARATOR.$skin_dir))
								mkdir($backup_dir.DIRECTORY_SEPARATOR.$skin_dir);

							if (!is_dir($backup_dir.DIRECTORY_SEPARATOR.$skin_dir.DIRECTORY_SEPARATOR.$node))
								mkdir($backup_dir.DIRECTORY_SEPARATOR.$skin_dir.DIRECTORY_SEPARATOR.$node);
						   foreach ($skin_files as $key=>$val)
						   {
							   // modify
								$skinfile = $skin_main.$node.DIRECTORY_SEPARATOR.$val;

								$fd = fopen($skinfile, "r");
								$contents = fread($fd, filesize($skinfile));
								$fstat = fstat($fd);
								$modtime = $fstat['mtime'];
								fclose($fd);

							   // backup
								copy($skinfile, $backup_dir.DIRECTORY_SEPARATOR.$skin_dir.DIRECTORY_SEPARATOR.$node.DIRECTORY_SEPARATOR.$val);
								touch($backup_dir.DIRECTORY_SEPARATOR.$skin_dir.DIRECTORY_SEPARATOR.$node.DIRECTORY_SEPARATOR.$val, $modtime);

								$sp = strpos($contents, $replace);
								if ($sp === false)
								{
									$contents2 = str_replace($search, $replace, $contents);
									if (strcmp($contents, $contents2))
									{
										$fh = fopen($skinfile, 'w');
										fwrite($fh, $contents2);
										fclose($fh);
										// [2013-06-07] touch($skinfile, $modtime);
										$modify_files[] = $skinfile;
									}	// if()
								}	// if()
						   }	// foreach()
					   }	// if()
				   }	// if()
			   }
			}
			closedir($handle);
		} else
		{
			die("[Error/ie11_skin_auto_update]웹메일 스킨 디렉토리가 존재하지 않습니다.=> ".$skin_main);
		}	// if()

	}	// foreach()

	return $modify_files;
}	// function()


// [2013-07-08] robots.txt 자동 추가
$robots_add = $updated_dir.DIRECTORY_SEPARATOR.'robots_add';
if (!file_exists($robots_add))
{
	if (!file_exists(dirname($G_SYS[PAGE_ROOT]).'/nmail/robots.txt'))
		copy(dirname($G_SYS[PAGE_ROOT]).'/tools/updated/robots.txt', dirname($G_SYS[PAGE_ROOT]).'/nmail/robots.txt');
	touch($robots_add);
}	// if()


// [2013-07-09] custom
if (file_exists(dirname($G_SYS[PAGE_ROOT]).'/tools/__custom_update_db.php'))
{
	include(dirname($G_SYS[PAGE_ROOT]).'/tools/__custom_update_db.php');
}	// if()

// [2025-09-08] [관리자메뉴 >> 회원관리 >> 가입항목관리] 사번 항목 추가, MEMBER_FIELD 테이블의 d_no 를 기준으로 사번 항목 추가.
$q = "SELECT d_no FROM ".$TB['MEMBER_FIELD']." GROUP BY d_no";
$rows = db_get_rows($q);
$rows_cnt = sizeof($rows);
for ($i=0; $i<$rows_cnt; $i++)
{
	$q = "SELECT COUNT(*) FROM ".$TB['MEMBER_FIELD']." WHERE mbf_name='m_emp_no' AND d_no='".$rows[$i]['d_no']."'";
	$member_field_cnt = db_get_one($q);
	if ($member_field_cnt == 0)
	{
		$q = "INSERT INTO ".$TB['MEMBER_FIELD']." VALUES (".db_sqc_next($TB['MEMBER_FIELD']).", ".$rows[$i]['d_no'].", 0, 'm_emp_no', '사번', 255, 255, 'N', 'N', 'N', 'N')";
		db_query($q);
	}	// if()
}	// for()


################################################################################
# 사용자 질의후 처리
################################################################################


// [2022-12-23] TINYMCE5 웹에디터 선택
$webeditor_ischange2 = $updated_dir.DIRECTORY_SEPARATOR.'webeditor_ischange2';
if (!file_exists($webeditor_ischange2))
{
	title("새로운 웹에디터 교체여부 선택");
	echo($crlf."  기능안내)".$crlf."    편지쓰기시 본문내에 이미지 붙여넣기시 업로드가 지원되는 새로운 웹에디터(TinyMCE5)로 교체할 수 있습니다.".$crlf."  주의)".$crlf."    직접 소스를 수정하여 웹에디터를 교체하신 경우에는 아니오(n)를 누르셔야 합니다.".$crlf);
	$scan = scanf($crlf."  최신 웹에디터로 교체하시겠습니까? [Y/n] : ", array('Y', 'N'), 2);
	if ($scan == 'Y')
	{
		$file = '../nmail/include/global_var.php';
		$data = file_get_contents($file);
		$data = str_replace(array("\$G_SYS['WEBEDITOR'] = 'OPEN';", "\$G_SYS['WEBEDITOR'] = 'FCK';", "\$G_SYS['WEBEDITOR'] = 'GM';", "\$G_SYS['WEBEDITOR'] = 'TINYMCE';"), "\$G_SYS['WEBEDITOR'] = 'TINYMCE5';", $data);
		file_write($file, $data);
	}	// if()
	touch($webeditor_ischange2);
}	// if()

// [2025-11-17] 이미지 업로드시 svg 허용
$upload_file_ext_img = $updated_dir.DIRECTORY_SEPARATOR.'upload_file_ext_img';
if (!file_exists($upload_file_ext_img))
{
	$file = '../nmail/include/global_var.php';
	$data = file_get_contents($file);
	$data = str_replace('$UPLOAD[FILTER_EXT][IMG] = array("jpg", "jpeg", "gif", "png", "pcx", "bmp", "tif", "tiff");', '$UPLOAD[FILTER_EXT][IMG] = array("jpg", "jpeg", "gif", "png", "pcx", "bmp", "tif", "tiff", "svg");', $data);
	file_write($file, $data);
	touch($upload_file_ext_img);
}	// if()

// [2025-11-20] 웹메일 로그인 유지 시간, PC 기본값을 2시간에서 1일로 늘림
$session_gc_maxlifetime_1day = $updated_dir.DIRECTORY_SEPARATOR.'session_gc_maxlifetime_1day';
if (!file_exists($session_gc_maxlifetime_1day))
{
	$file = '../nmail/include/global_var.php';
	$data = file_get_contents($file);
	$data = str_replace('$G_SYS[SESSION_GC_MAXLIFETIME] = 7200;', '$G_SYS[SESSION_GC_MAXLIFETIME] = 86400;', $data);
	file_write($file, $data);
	touch($session_gc_maxlifetime_1day);
}	// if()


// [2025-11-21] 최근 2년간 메일 로그 분석후, 메일계정의 SMTP 인증, POP3 인증, 메일 수신일자 갱신
if (file_exists(__DIR__ . '/../nmail/admin_security_list.php')) {       // 프리미엄 업데이트로 [계정 보안 관리] 포함된 경우
	$mail_log_mbr_date_analyze = $updated_dir . DIRECTORY_SEPARATOR . 'mail_log_mbr_date_analyze';
	if ( ! file_exists($mail_log_mbr_date_analyze)) {
		title("최근 2년간 메일 로그 분석후, 메일계정의 SMTP 인증, POP3 인증, 메일 수신일자를 갱신합니다.");

		mail_log_mbr_date_analyze(date('Ymd'), true, 365 * 2, false);

		touch($mail_log_mbr_date_analyze);


		echo "\n메일 로그 분석 작업이 완료되었습니다. (" . round((getmicrotime() - $_start), 4) . "sec)\n";
	}    // if()
}

// [2025-12-18] v3.3 용 미사용 인코딩 소스 보관용 디렉토리로 이동
$legacy_enc_lib_move = $updated_dir . DIRECTORY_SEPARATOR . 'legacy_enc_lib_move';
if ( ! file_exists($legacy_enc_lib_move)) {
	title("v3.4 부터 사용되지 않는 mail_lib.56.php 등의 파일은 tools/updated/legacy_enc_lib/ 로 이동됩니다.");

	$php_versions = array(
			'53',
			'56',
	);
	$sources      = array(
			'admin_lib.php',
			'mail_lib.php',
			'mail_send_lib.php',
			'mail_spam_lib.php',
			'security_lib.php',
			'webhard_lib.php',
	);
	$count        = 0;

	$from_dir = $G_SYS['PAGE_ROOT'] . DIRECTORY_SEPARATOR . 'include';
	$to_dir   = __DIR__ . DIRECTORY_SEPARATOR . 'updated' . DIRECTORY_SEPARATOR . 'legacy_enc_lib';
	if ( ! is_dir($to_dir)) {
		mkdir($to_dir, 0700);
	}
	foreach ($php_versions as $php_version) {
		foreach ($sources as $source) {
			$filename = str_replace('.php', '.' . $php_version . '.php', $source);
			if (file_exists($from_dir . DIRECTORY_SEPARATOR . $filename)) {
				echo "  " . $from_dir . DIRECTORY_SEPARATOR . $filename
						. " => " . $to_dir . DIRECTORY_SEPARATOR . $filename . "\n";
				rename($from_dir . DIRECTORY_SEPARATOR . $filename, $to_dir . DIRECTORY_SEPARATOR . $filename);
				$count++;
			}
		}
	}

	touch($legacy_enc_lib_move);

	echo "\n사용되지 않는 " . $count . "개의 파일 이동이 완료되었습니다. (" . round((getmicrotime() - $_start), 4) . "sec)\n";
}    // if()



################################################################################

$skin_all_bootstrap = $updated_dir.DIRECTORY_SEPARATOR.'skin_all_bootstrap';
if (!file_exists($skin_all_bootstrap))
{
	echo $crlf;
	title("NmailPHP 3.x 최신 스킨으로 변경");
	echo($crlf."  안내)".$crlf."    NmailPHP 3.x의 최신 스킨인 부트스트랩 기반으로 변경해야 합니다.".$crlf."  주의)".$crlf."    프로그램 소스나 스킨을 직접 수정하신 경우에는 변경시 문제가 발생할 수 있으므로 따로 확인해보신후 변경하셔야 합니다.".$crlf."  참고) ".$crlf."    변경할 경우 모든 도메인에  일괄 적용됩니다.".$crlf."    필요시 [도메인관리 >> 도메인설정]이나 [메일서버관리 >> 도메인관리]에서 도메인별로 변경이 가능합니다.".$crlf);
	$scan = scanf($crlf."  최신스킨(bootstrap)으로 변경하시겠습니까? [y/N] : ", array('N', 'Y'), 2);
	if ($scan == 'Y')
	{
		$q = "UPDATE ".$TB['DOMAIN']." SET d_skin_main='bootstrap', d_skin_member='bootstrap', d_skin_webmail='bootstrap', d_skin_board='bootstrap', d_skin_webhard = 'bootstrap'";
		db_query($q);
	}	// if()
	touch($skin_all_bootstrap);
}	// if()


if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')
{
	$ini = 'nmail_dir.ini';
	if (!file_exists('../'.$ini))
	{
		echo "엔메일 설치 경로가 기록된 설정파일(".$ini.")이 존재하지 않습니다.\n nmail_dir_set.bat 배치 파일을 실행 바랍니다.";
		scanf($crlf."-- 엔터를 누르면 계속 진행됩니다. --", array(), 5, false, true);
	} else
	{
		$curr_dir = trim(implode(file('../nmail_dir.ini')));
		$home_dir = "C:\\NmailPHP";

		if ($home_dir != $curr_dir && ! is_local())
		{
			echo "  설정파일에 기록된 경로 - ".$curr_dir."\n\n";
			$target_file = array(
				'..\tools\filter_post_data.bat',
				'..\MailRoot\filters.post-data.tab'
			);

			for ($i=0; $i<sizeof($target_file); $i++)
			{
				$fp = fopen($target_file[$i], "r");
				$file_read_ori = fread($fp, filesize($target_file[$i]));
				fclose($fp);
				if(strpos($file_read_ori, $curr_dir))
				{
					break;
				}
				$file_read = $file_read_ori;
				$file_read = str_replace(str_replace('\\', '\\\\', $home_dir), str_replace('\\', '\\\\', $curr_dir), $file_read);
				$file_read = str_replace($home_dir, $curr_dir, $file_read);
				if (strcmp($file_read, $file_read_ori))
				{
					$fp = fopen($target_file[$i], "w");
					fwrite($fp, $file_read);
					fclose($fp);
					echo "  ".$target_file[$i]." - 수정완료\n";
				} else
				{
					echo "  ".$target_file[$i]." - \n  [경고]\n  수정이 되지 않았습니다.\n  직접 파일을 열어 설치 경로를 확인하시기 바랍니다.\n";
				}	// if()
			}	// for()
			echo "추가된 filter 경로가 정상적으로 변경되었습니다.\n";
		}
	}	// if()
}


if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')
{
	echo $crlf;
	title("웹메일 디렉토리 퍼미션 재조정");
	$scan = scanf($crlf."  perm_change.sh 스크립트를 실행하시겠습니까? [Y/n] : ", array('Y', 'N'), 2);
	if ($scan == 'Y')
	{
		chdir(dirname(__FILE__));
		system('./perm_change.sh');
	}	// if()
}	// if()



################################################################################

if ($G_SYS[DB] == 'oracle')
{
	die("[경고]Oracle 버젼을 사용시에는 자동 업데이트과정중 'DB 업데이트'작업이 적용되지 않습니다.\n  이 부분은 개발사에 문의하여 수작업으로 갱신해야 합니다.\n");
} else
{
	echo "\n업데이트 작업이 완료되었습니다. (" . round((getmicrotime() - $_start),4) . "sec)\n";
}	// if()


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

if (is_local()) {
//	dd('# [Dev] 업데이트시 사용된 쿼리문 출력');
}
