<?php
/*
 * ********************************************************
 * TatterTools DB  v1.1.1 to Classic
 * ********************************************************
 * Created on 2007. 01. 25 to 2007. 01. 28
 * by 함기훈.
 * ********************************************************
 *
 * [ 라이센스 ]
 * GPL v2를 따릅니다. 
 *
 * [ 주의 ]
 * 이 프로그램으로 인한 책임은 스스로가 지셔야 합니다. 다만 이 프로그램은
 * 태터툴즈 v1.1.1 비바체 버전에 맞추어 제작되었으며, 그곳의 DB에 일체
 * 영향을 주지 않습니다.
 *
 * [ 프로그램 소개 ]
 * 이 프로그램은 1.1.1 비바체 버전의 태터툴즈의 DB를 클래식 버전에서 사용할
 * 수 있는 백업파일로 변환하여 출력해줍니다. 이 출력된 파일로 클래식 태터
 * 툴즈에서 복원을 하면, 내용 그대로 옮겨지게 됩니다 ~ ♡
 * 다만 클래식 버전 특성상 업로드한 파일들은 직접 옮겨주셔야 합니다.
 * 백업되는 항목>
 * - 프로필, 블로그 이름 등의 기본적인 블로그 정보
 * - 본문, 키로그, 트랙백, 덧글, 위치로그, 태그, 카테고리 일체 (키로그는 모두 비공개 설정됨)
 * - 방명록
 * - 카운터와 리퍼러 로그. 단 플러그인 정보 등은 취급불가.(클래식에 맞춰짐)
 * - 링크와 rss 리더 주소록, 스크랩한 피드
 * - 댓글 알리미
 *
 * [ 사용법 ]
 * 태터툴즈 v1.1.1 비바체가 설치된 폴더(config.php 파일이 있는 곳)에
 * classic.php 파일을 복사해 넣고 그 파일이 위치한 곳으로 접속하시면
 * 변환된 백업파일을 다운로드 할 수 있습니다.
 * 예) http://aaa.bbb.ccc/tt/  라면
 *     http://aaa.bbb.ccc/tt/classic.php
 * 로 접속하시면 됩니다.
 *
 * [ 변환 후 해야할 일 ]
 * 0. 변환된 클래식용 백업파일을 다운로드 후, 이 프로그램을 꼭 삭제하세요!!!
 *    이 프로그램이 있는 한, 여러분처럼 다른 누군가도 똑같이 백업파일을
 *    다운로드 할 수 있습니다!!!
 *
 * 1. 업로드 파일을 옮깁니다. 아래 설명을 참고하세요.
 *    v1.1.1를 설치한 곳에  attach 라는 폴더가 있습니다. 이 안에 있는
 *    폴더와 파일들을 그대로 클래식 버전의 태터툴즈를 설치한 곳에 있는
 *    attach 폴더 안에 복사해 주면 됩니다. 참! 옮긴 파일/폴더들의  권한이
 *    777로 되어있는지 꼭 확인하세요!
 *
 * 2. 키로그가 기본적으로 비공개로 되게 만들었습니다. 사용하시는 분은 공개로
 * 	    변환해 주세요.
 *
 * 3. rss리더 주소록의 분류를 확인하세요. v1.1.1에서 다중 분류가 되어
 *    되어 있었다면, 다르게 분류되어있을 수도 있습니다.
 * 4. 당연하지만 스킨 설정, 글 출력 수 등의 버전에 민감한 설정은 클래식
 *    설치상태의 설정으로 변환됩니다. 취향에 맞게 수정하세요~
 *
 * 5. 프로필 이미지를 교체하세요. v1.1.1 비바체에서는 프로필 이미지도 업
 * 	    로드 디렉토리 안에 존재하는데, 클래식에서는 약간 다른 경로에 위치하게
 *    됩니다. 일단은 변환 후 그대로 출력되게 손을 봐놨습니다만, 제대로된
 *    위치에 위치한 것은 아니기 때문에 환경설정에서는 파일이 없는 것으로
 * 	    나옵니다. 변환 후 보여지는 프로필 사진을 다운받아서(다른이름으로 저장),
 * 	    다시 업로드 하는 방법을 추천합니다.
 *
 * ********************************************************
 */

/*
 * 개발용 확인 루틴.
 */
#header("Content-Type: text/html; charset=utf-8");

/*
 * 배표용 다운로드 루틴.
 */
header("Content-type: application");
header("Content-Disposition: attachment; filename=tt111_to_classic_backup_".date("Ymd").".sql");
header("Content-Description: PHP4 Generated Data");


if (!@include ("config.php")) {
	echo ("config.php 파일을 불러올 수 없습니다.");
	exit(1);
}

if (!mysql_connect($database['server'], $database['username'], $database['password'])) {
	echo "mysql에 접속할 수 없습니다!";
	exit(1);
}
mysql_select_db($database['database']); // db 선택
mysql_query('SET CHARACTER SET utf8'); // utf-8 모드로 작동

/*
 * 공용 변수 선언
 */
$ctMapArray = array();    	// 카테고리 변환을 위한 맵핑테이블
$ctMapArray[0]['ct1'] = 0;
$ctMapArray[0]['ct2'] = 0;
$ownerMapArray = array(); 	// 글쓴이 이름 맵핑 테이블. 일단 넣긴 했는데 있으나 마나하기도..
							// 어차피 싱글 유저 블로그의 이동용이니까.

# 글쓴이 id와 이름을 $ownerMapArray에 저장
get_ttusers();

# 블로그 세팅
echo get_ttsetting();

# 카테고리 - 메인/서브 카테고리
echo get_ttcts();

# 태그
echo get_tttags();

# 키로그
echo get_ttkeylogs();

# 블로그 엔트리 - 본문글, 위치로그
echo get_tt();

# 블로그 일반/키로그 첨부파일
echo get_ttfiles();

# 블로그 덧글과 덧덧글
echo get_ttreply();

# 방명록과 방명록덧글
echo get_ttguest();

# 블로그 받은 트랙백
echo get_tttrackback();

# 블로그 보낸 트랙백 기록
echo get_tttblog();

# 블로그 카운트 & 마지막 접속 ip
echo get_ttcount();

# 블로그 레퍼런스 로그
echo get_ttreferlogs();

# 블로그 링크
echo get_ttlink();

# rss 구독 주소들과 분류, 스크랩한 글들.
echo get_ttrss();

# 마지막 - 덧글알리미~ 얏호~
echo get_ttnotice_log();

function get_ttnotice_log(){

	global $database;
	$output = '';

	$sql = "SELECT n.id as seq, ";
	$sql .= "n.remoteId as no, ";
	$sql .= "n.parent as pno, ";
	$sql .= "n2.remoteId as rno, ";
	$sql .= "n.name as name, ";
	$sql .= "n.homepage as homepage, ";
	$sql .= "n.comment as body, ";
	$sql .= "n.url as r_url, ";
	$sql .= "s.url as url, ";
	$sql .= "n.isNew as is_new, ";
	$sql .= "n.modified as check_date, ";
	$sql .= "n.written as regdate, ";
	$sql .= "s.title as s_home_title, ";
	$sql .= "s.name as s_name, ";
	$sql .= "n.entryTitle as s_post_title, ";
	$sql .= "n.entry as s_no, ";
	$sql .= "n.entryUrl as s_url  ";
	$sql .= "FROM " . $database['prefix'] . "CommentsNotified as n ";
	$sql .= "inner join " . $database['prefix'] . "CommentsNotifiedSiteInfo as s on s.id = n.siteId ";
	$sql .= "left join " . $database['prefix'] . "CommentsNotified as n2 on n.parent = n2.id ";
	$sql .= "order by seq asc, pno asc";

	/*
	 * 이번 건은 꽤 골치아픈 부분이 있다. 하지만 차근차근 해나가면 어렵지 않다.
	 * 마지막 보스같은 것인가... -_-+
	 */
	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){
		$pno = 0;	// 부모값이면 pno와 rno가 0이다.
		$rno = 0;

		if (!is_null($fetch_result['pno'])){				//  부모글이 아니면  부모값 넣음.
			$pno = $fetch_result['pno'];
			$rno = $fetch_result['rno'];
		}

	    $output .= "insert into t3_[##_dbid_##]_notice_log ";
		$output .= "( seq, no, pno, rno, ";
	    $output .= "name, homepage, body, r_url, url, is_new, check_date, regdate, ";
		$output .= "s_home_title, s_name, s_post_title, s_no, s_url ) values ( ";
	    $output .= $fetch_result['seq']. ", ";
	    $output .= $fetch_result['no']. ", ";
	    $output .= $pno. ", ";
		$output .= $rno. ", ";
	    $output .= "'" .get_ttbody($fetch_result['name']). "', ";
	    $output .= "'" .get_ttbody($fetch_result['homepage']). "', ";
	    $output .= "'" .get_ttbody($fetch_result['body'] ). "', ";
	    $output .= "'" .$fetch_result['r_url']. "', ";
	    $output .= "'" .$fetch_result['url']. "', ";
	    $output .= $fetch_result['is_new']. ", ";
	    $output .= $fetch_result['check_date']. ", ";
	    $output .= $fetch_result['regdate']. ", ";
	    if ($pno == 0){
		    $output .= "'" .get_ttbody($fetch_result['s_home_title'] ). "', ";
		    $output .= "'" .get_ttbody($fetch_result['s_name'] ). "', ";
			$output .= "'" .get_ttbody($fetch_result['s_post_title'] ). "', ";
	    	$output .= $fetch_result['s_no']. ", ";
	    }else{
	    	$output .= "'', '', '', 0, ";
	    }
	    $output .= "'" .$fetch_result['s_url']. "' )\n";

	}
	return $output;
}


function get_ttrss(){
	global $database;
	/*
	 * rss 그룹을 복원 후 rss 주소들을 가져온다.
	 * 그 후 체크한(별표) 아이템들을 가져온다. 일반 아이템들은
	 * 어차피 구독기에서 리딩하면 되는 것이니 가져오지 않는다.
	 */
	$output = '';

	/*
	 * 	RSS 그룹 복원
	 */
	$sql = "SELECT id as no, title, unix_timestamp() as regdate ";
	$sql .= "FROM " . $database['prefix'] . "FeedGroups ";
	$sql .= "where id > 0 order by id asc";
	/*
	 * unix_timestampe()로 컨버팅 하는 시점으로 시간 세팅. db에 없어도 되는 필드인듯..
	 * 그리고 tt111에서는 id가 0인 카테고리가 존재하지만 클래식에서는 없으므로 제외.
	 */
	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){
	    $output .= "insert into t3_[##_dbid_##]_rss_group ( no, sortno, title, regdate ) values ( ";
	    $output .= $fetch_result['no']. ", ";
	    $output .= $fetch_result['no']. ", ";		// sortno와 no를 일치시킴. tt111에는 특별히 정렬 값이 없다.
	    $output .= "'" .get_ttbody($fetch_result['title']). "', ";
	    $output .= $fetch_result['regdate']. ")\n";	// 컨버팅 하는 시점으로 시간 세팅. db에 없어도 되는 필드인듯..
	}
	/*
	 * 	RSS 주소들 복원
	 */
	$sql = "SELECT g.groupId as pno, f.id as no, f.xmlURL as xml_url, ";
	$sql .= "f.title as title, f.blogURL as link, f.description as description, ";
	$sql .= "modified as regdate ";
	$sql .= "FROM  tt111_Feeds as f ";
	$sql .= "left join tt111_FeedGroupRelations as g on f.id = g.feed ";
	$sql .= "order by no asc, pno desc ";
	$no_check = 0;
	/*
	 * 추가설명: 클래식은 하나의 주소가 하나의 분류를 가지게 되어 있다. 하지만 tt111은 복수의 분류에 속할 수 있게
	 * 되어있어, 딱히 좋은 방법이 생각나지 않았다. 따라서, 중복된 rss 주소가 나올 경우 분류된 마지막 것만 넣고 중복된
	 * 것은 추가하지 않게 하였다. 대개 중복된 rss 주소는 0, 즉 분류가 안된 상태기 때문이다.
	 */
	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){
		if ($no_check != $fetch_result['no']){
			$no_check = $fetch_result['no'];
		}else{
			continue;
		}

	    $output .= "insert into t3_[##_dbid_##]_rss ( pno, no, xml_url, title, ";
	    $output .= "link, description, regdate, mdate, is_sync, is_public ) values ( ";
	    $output .= $fetch_result['pno']. ", ";
	    $output .= $fetch_result['no']. ", ";
	    $output .= "'" .$fetch_result['xml_url']. "', ";
	    $output .= "'" .get_ttbody($fetch_result['title']). "', ";
	    $output .= "'" .$fetch_result['link']. "', ";
	    $output .= "'" .get_ttbody($fetch_result['discription']). "', ";
	    $output .= $fetch_result['regdate']. ", ";
	    $output .= "'', ";				// mdate. 싱크 실패한 마지막 날짜가 아닐지?
	    $output .= "0, ";				// sync 성공 여부.
	    $output .= "0 )\n";				// 이웃로그로 표시 여부
	}



	/*
	 * 	RSS 스크랩한 글 복원.
	 */
	$sql = "SELECT f.id as no, f.feed as rno, f.title, ";
	$sql .= "f.permalink as link, f.description as description,  ";
	$sql .= "f.tags as subject, f.author as creator,  ";
	$sql .= "date_format( from_unixtime(f.written), '%a, %d %b %Y %T +0900' ) as `date`, ";
	$sql .= "f.written as regdate, 1 as is_read, 1 as is_scrap ";
	$sql .= "FROM tt111_FeedItems as f ";
	$sql .= "join tt111_FeedStarred as s on f.id = s.item ";
	$sql .= "order by f.id asc ";

	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){
	    $output .= "insert into t3_[##_dbid_##]_rss_item ( no, rno, title, ";
	    $output .= "link, description, subject, creator, `date`, regdate, is_read, is_scrap ) values ( ";
	    $output .= $fetch_result['no']. ", ";
	    $output .= $fetch_result['rno']. ", ";
	    $output .= "'" .get_ttbody($fetch_result['title']). "', ";
	    $output .= "'" .$fetch_result['link']. "', ";
	    $output .= "'" .get_ttbody($fetch_result['description']). "', ";
	    $output .= "'" .get_ttbody($fetch_result['subject']). "', ";
		$output .= "'" .get_ttbody($fetch_result['creator']). "', ";
	    $output .= "'" .$fetch_result['date']. "', ";
	    $output .= $fetch_result['regdate']. ", ";
	    $output .= $fetch_result['is_read']. ", ";
	    $output .= $fetch_result['is_scrap']. ")\n";
	}

	return $output;
}


function get_ttlink(){
	global $database;
	/*
	 * 링크.
	 * type 1이면 rss 주소가 있는 블로그, 2이면 일반 사이트로 되어있음(클래식)
	 */
	$output = '';

	$sql = "SELECT id as no, rss as xml_url, name as title, url as link, written as regdate ";
	$sql .= "FROM " . $database['prefix'] . "Links ";
	$sql .= "order by id asc";

	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){
	    $output .= "insert into t3_[##_dbid_##]_link ( no, type, xml_url, title, link, regdate ) values ( ";
	    $output .= $fetch_result['no']. ", ";
	    if ($fetch_result['xml_url']!=''){
	    	$output .= "1, ";
	    }else{
	    	$output .= "2, ";
	    }
	    $output .= "'" .$fetch_result['xml_url']. "', ";
	    $output .= "'" .get_ttbody($fetch_result['title']). "', ";
	    $output .= "'" .$fetch_result['link']. "', ";
	    $output .= $fetch_result['regdate']. ")\n";

	}
	return $output;
}

function get_ttreferlogs(){
	global $database;
	$no = 1;
	/*
	 * 리퍼러와 리퍼러 통계 테이블.
	 */
	$output = '';

	$sql = "SELECT host, url as refer, referred as regdate ";
	$sql .= "FROM " . $database['prefix'] . "RefererLogs ";
	$sql .= "order by referred asc";

	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){

	    $output .= "insert into t3_[##_dbid_##]_referlog ( no, host, refer, regdate ) values ( ";
	    $output .= $no.", ";
	    $output .= "'" .$fetch_result['host']. "', ";
	    $output .= "'" .$fetch_result['refer']. "', ";
	    $output .= $fetch_result['regdate']. " )\n ";

	    $no ++;
	}

	$sql = "SELECT host, count as cnt ";
	$sql .= "FROM " . $database['prefix'] . "RefererStatistics ";

	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){

	    $output .= "insert into t3_[##_dbid_##]_referstat ( host, cnt ) values ( ";
	    $output .= "'" .$fetch_result['host']. "', ";
	    $output .= $fetch_result['cnt']. " )\n ";

	}

	return $output;
}

function get_ttcount(){
	global $database;
	/*
	 * 날짜마다의 접속 수.
	 */
	$output = '';

	$sql = "SELECT `date` as set_date, visits as count ";
	$sql .= "FROM " . $database['prefix'] . "DailyStatistics ";
	$sql .= "order by `date` asc";

	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){
	    $output .= "insert into t3_[##_dbid_##]_count ( set_date, count, set_ip ) values ( ";
	    $output .= "'" .$fetch_result['set_date']. "', ";
	    $output .= $fetch_result['count']. ", ";
	    $output .= "'127.0.0.1' )\n";	//마지막 접속 ip 주소. but tt111은 해당필드가 없어서 복구 불가.
	    								//이 값이 비어있으면 마지막 ip와 대조가 안되어 카운터가 올라가지 않으므로
	    								//127.0.0.1을 넣었음.
	}
	return $output;
}

function get_tttblog(){
	global $database;
	/*
	 * 1.1.1과 거의 구조가 같으므로 그대로 가져와서 저장.
	 */
	$output = '';

	$sql = "SELECT id as no, entry as pno, written as regdate, url as ping_url ";
	$sql .= "FROM " . $database['prefix'] . "TrackbackLogs ";
	$sql .= "order by id asc";

	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){

	    $output .= "insert into t3_[##_dbid_##]_tblog (no, pno, regdate, ping_url) values ( ";
	    $output .= $fetch_result['no']. ", ";
	    $output .= $fetch_result['pno']. ", ";			// 본문 번호
	    $output .= $fetch_result['regdate']. ", ";
	    $output .= "'" .$fetch_result['ping_url']. "' )\n";
	}
	return $output;
}

function get_tttrackback(){
	global $database;
	$no = 1;
	/*
	 * 1.1.1에서는 날짜기준으로 역으로 계산해서 출력하나 클래식은 no 역순으로 출력한다.
	 * 이상하게도 1.1.1은 후에 쓰여진 글이 id가 이전의 글보다 앞선 경우가 발생해서
	 * 그대로 id를 no로 바꾸어 넣으면 클래식에서 최근 트랙백이 엉망으로 출력된다.
	 * 따라서 다시 no를 만들어 준다.
	 */
	$output = '';

	$sql = "SELECT id as no, entry as pno, site, url, subject as title, excerpt as body, ";
	$sql .= "written as regdate, ip ";
	$sql .= "FROM " . $database['prefix'] . "Trackbacks ";
	$sql .= "order by regdate asc";

	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){

	    $output .= "insert into t3_[##_dbid_##]_trackback (no, pno, site, url, title, body, ";
	    $output .= "regdate, ip) values ( ";
	    $output .= $no. ", ";
	    $output .= $fetch_result['pno']. ", ";			// 본문 번호
	    $output .= "'" .get_ttbody( $fetch_result['site'] ). "', ";
	    $output .= "'" .$fetch_result['url']. "', ";
	    $output .= "'" .get_ttbody( $fetch_result['title'] ). "', ";
	    $output .= "'" .get_ttbody( $fetch_result['body'] ). "', ";
	    $output .= $fetch_result['regdate']. ", ";
	    $output .= "'" .$fetch_result['ip']. "' )\n";
		$no ++;
	}
	return $output;
}

function get_ttguest(){
	global $database;
	$sortno = 1;
	$output = '';

	$sql = "SELECT id as no, parent as pno, name, homepage, comment as body, ";
	$sql .= "`password`, written as regdate, ip ";
	$sql .= "FROM " . $database['prefix'] . "Comments ";
	$sql .= "where entry = 0 order by regdate asc";
	/*
	 * entry가 0이면 방명록임..
	 *
	 * 5분간 어리둥절하고 3분간 생각해서 처리 방법 생각해냄. -_-;
	 * 일단 데이터를 guest와 guest_reply 모두 가지고 온다. 다만 regdate로 asc 정렬을 한 후,
	 * sortno을 매겨서 준다. 이 sortno는 방명록에서 '최근글 보기'에서 쓰이는데, 두 db를 합쳐서
	 * 순서를 준다.
	 *
	 */
	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){

		if (is_null($fetch_result['pno'])){
			/*
			 * 부모글. guest 테이블로 들어감.
			 */
		    $output .= "insert into t3_[##_dbid_##]_guest (no, sortno, ";
		    $output .= "name, homepage, icon, icon_width, icon_height, body, password, regdate, ip) values ( ";
		    $output .= $fetch_result['no']. ", ";
			$output .= $sortno. ", ";
		    $output .= "'" .$fetch_result['name']. "', ";
		    $output .= "'" .$fetch_result['homepage']. "', ";
		    $output .= "'', ";
		    $output .= "0, ";
		    $output .= "0, ";
		    $output .= "'" .get_ttbody($fetch_result['body'] ). "', ";
		    $output .= "'" .$fetch_result['password']. "', ";
		    $output .= $fetch_result['regdate']. ", ";
		    $output .= "'" .$fetch_result['ip']. "' )\n";
		}else{
			/*
			 * 덧글. guest_reply 테이블로 들어감.
			 */
		    $output .= "insert into t3_[##_dbid_##]_guest_reply (no, pno, ";
		    $output .= "name, homepage, icon, icon_width, icon_height, body, password, regdate, ip) values ( ";
		    $output .= $fetch_result['no']. ", ";
			$output .= $fetch_result['pno']. ", ";
		    $output .= "'" .$fetch_result['name']. "', ";
		    $output .= "'" .$fetch_result['homepage']. "', ";
		    $output .= "'', ";
		    $output .= "0, ";
		    $output .= "0, ";
		    $output .= "'" .get_ttbody($fetch_result['body'] ). "', ";
		    $output .= "'" .$fetch_result['password']. "', ";
		    $output .= $fetch_result['regdate']. ", ";
		    $output .= "'" .$fetch_result['ip']. "' )\n";
		}
		$sortno ++;
	}
	return $output;
}

function get_ttreply(){
	global $database;
	$output = '';

	$sql = "SELECT id as no, entry as pno, parent as rno, name, homepage, comment as body, ";
	$sql .= "`password`, secret as is_secret, written as regdate, ip ";
	$sql .= "FROM " . $database['prefix'] . "Comments ";
	$sql .= "where entry != 0 order by regdate asc";
	/*
	 * pno가 0이면 방명록임..
	 */
	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){
		$rno = 0;
		$is_root = 1;
		if (!is_null($fetch_result['rno'])){				// is_root 항목. 부모글이면 1 아니면 0
			$rno = $fetch_result['rno'];
			$is_root = 0;
		}

	    $output .= "insert into t3_[##_dbid_##]_reply (no, pno, rno, sortno, ";
	    $output .= "name, homepage, body, is_root, password, is_secret, regdate, ip) values ( ";
	    $output .= $fetch_result['no']. ", ";
	    $output .= $fetch_result['pno']. ", ";			// 덧글이 위치한 본문 번호
	    $output .= $rno. ", ";			// 리플글일 경우 부모덧글 번호
	    $output .= "0, ";								// 사용하지 않는, 만들어져만 있는 필드1
	    $output .= "'" .$fetch_result['name']. "', ";
	    $output .= "'" .$fetch_result['homepage']. "', ";

	   // $output .= "'" .str_replace('\'', '&#39;', $fetch_result['body'] ). "', ";
	    $output .= "'" .get_ttbody($fetch_result['body'] ). "', ";
	    $output .= $is_root . ", ";
	    $output .= "'" .$fetch_result['password']. "', ";
	    $output .= $fetch_result['is_secret']. ", ";
	    $output .= $fetch_result['regdate']. ", ";
	    $output .= "'" .$fetch_result['ip']. "' )\n";

	}
	return $output;
}

function get_tttags(){
  global $database;
  $no = 1;				// tag의 no를 새로 부여해주어야 한다. 비정규화 작업! ~_~
  $output = '';

	$sql = "select t2.entry as pno, t1.name as tag, e1.published as regdate ";
	$sql .= "from  " . $database['prefix'] . "TagRelations as t2 ";
	$sql .= "left join " . $database['prefix'] . "Tags as t1  on t1.id = t2.tag ";
	$sql .= "left join " . $database['prefix'] . "Entries as e1 on t2.entry = e1.id ";
	$sql .= "where e1.published != 0 ";				// 어떤 이유로 같은 글에 중복으로 연결된 태그 제외.
	$sql .= "order by t2.entry asc, t1.id asc"; 		// 최대한 날짜, id 순으로 정리하여 ASC 정렬.

	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){

	    $output .= "insert into t3_[##_dbid_##]_tag (no, pno, tag, regdate) values ( ";
	    $output .= $no. ", ";
	    $output .= $fetch_result['pno']. ", ";
	    $output .= "'" .$fetch_result['tag']. "', ";
	    $output .= $fetch_result['regdate']. " )\n";

	    $no ++;
	}
	return $output;
}

function get_ttkeylogs(){

  global $database;
  $sortno = 1;
  $output = '';

 	$sql = "SELECT id as no, owner, title as keyword, content as body, published as regdate, ";
 	$sql .= "visibility ";
	$sql .= "FROM " . $database['prefix'] . "Entries where category = -1 and draft = 0 ORDER BY id ";
	######################################################
	# category = -2 공지사항
	# category = -1 키로그
	# category = 0 카테고리 없음 --> 원래 클래식에서는 반드시 하나가 선택되어 있어야 함.
	# draft = 0 본문글
	# draft = 1 임시 저장글. but 클래식에서는 지원하지 않으므로 무시. (같은 id값에 draft 0, 1 인 중복 글 다수 발견;;)
	######################################################
	/*
	 * 추가사항: 확인결과, 수동으로 공개, 비공개를 해주어야 키로그가 적용되는 것을 발견하여, 무조건 비공개
	 * 상태로 저장되게 함. 그냥 db상으로만 옮겼더니, 키로그가 적용이 잘 되지 않았다.
	 */
	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){
    $is_public = 0;
    $is_sync = 0;

    $output .= "insert into t3_[##_dbid_##]_keyword (no, sortno, keyword, body, image_file_path1, ";
    $output .= "image_file_path2, regdate, is_public, is_sync) values (";
    $output .= $fetch_result['no']. ", ";
    $output .= $sortno. ", '";
    $output .= str_replace('\'', '&#39;', $fetch_result['keyword']). "', '";
    $output .= get_ttbody($fetch_result['body']). "', '";
    $output .= $fetch_result['owner']. "/', '";
    $output .= "', ";
    $output .= $fetch_result['regdate']. ", ";

    if ($fetch_result['visibility'] > 1) {       	// 2면 공개, 3이면 싱크.
      $is_public = 0;								//!!!! 무조건 공개를 off. 직접 공개하게 설정함.
      if ($fetch_result['visibility'] > 2 )
        $is_sync = 1;
    }
    $output .= $is_public. ", ";
    $output .= $is_sync. " ";
    $output .= ")\n";

    $sortno ++;

    # 디버깅용
    #break;
 	}

 	return $output;
}

function get_tt(){

  global $database;
  global $ctMapArray;
  global $ownerMapArray;
  $output = '';

 	$sql = "SELECT id as no, category as ct, title, content as body, owner, location, published as regdate, ";
 	$sql .= "visibility, comments as rp_cnt, trackbacks as tb_cnt, acceptComment as perm_rp, acceptTrackback as perm_tb ";
	$sql .= "FROM " . $database['prefix'] . "Entries where category != -1 and draft = 0 ORDER BY id ";
	######################################################
	# category = -2 공지사항
	# category = -1 키로그
	# category = 0 카테고리 없음 --> 원래 클래식에서는 반드시 하나가 선택되어 있어야 함.
	# draft = 0 본문글
	# draft = 1 임시 저장글. but 클래식에서는 지원하지 않으므로 무시. (같은 id값에 draft 0, 1 인 중복 글 다수 발견;;)
	######################################################

	$result = mysql_query($sql);

	while ($fetch_result = mysql_fetch_array($result)){
    $is_public = 0;
    $is_sync = 0;

    $output .= "insert into t3_[##_dbid_##] (no, category1, category2, title, body, user_id, image_file_path1, ";
    $output .= "image_file_path2, local_info, regdate, is_public, is_sync, rp_cnt, tb_cnt, perm_rp, perm_tb, subscription) values (";
    $output .= $fetch_result['no']. ", ";
    $output .= $ctMapArray[$fetch_result['ct']]['ct1']. ", ";
    $output .= $ctMapArray[$fetch_result['ct']]['ct2']. ", '";
    $output .= str_replace('\'', '&#39;', $fetch_result['title']). "', '";
    $output .= get_ttbody($fetch_result['body']). "', '";
    $output .= $ownerMapArray[$fetch_result['owner']]['name']. "', '";
    $output .= $fetch_result['owner']. "/', '";
    $output .= "', '";

    $output .= str_replace('/', ' > ', substr ($fetch_result['location'], 1) ) . "', ";
    $output .= $fetch_result['regdate']. ", ";

    if ($fetch_result['visibility'] > 1) {        // 2면 공개, 3이면 싱크.
      $is_public = 1;
      if ($fetch_result['visibility'] > 2 )
        $is_sync = 1;
    }
    $output .= $is_public. ", ";
    $output .= $is_sync. ", ";

    $output .= $fetch_result['rp_cnt']. ", ";
    $output .= $fetch_result['tb_cnt']. ", ";
    $output .= $fetch_result['perm_rp']. ", ";
    $output .= $fetch_result['perm_tb']. ", ";
    $output .= "0)\n";

    # 디버깅용
    #break;
 	}

 	return $output;
}

######################################################
function get_ttcts(){
	global $database;
	global $ctMapArray;
	$output = '';
	$no = 1;

	$sql = "SELECT id, name as label, priority as sortno, entriesInLogin as cnt ";
	$sql .= "FROM " . $database['prefix'] . "Categories where parent IS NULL ORDER BY sortno";

	$result = mysql_query($sql);
	while ( $fetch_result = mysql_fetch_array($result) ){
		$output .= "insert into t3_[##_dbid_##]_ct1 (no, sortno, label, cnt) values (";
		$output .= "'" .$no. "', '";					// no 새로 할당함.
		$output .= $no. "', '";					// sortno <- no와 같음 (sql에서 sortno대로 소팅해서 가져왔기에.)
		$output .= $fetch_result['label']. "', '";
		$output .= $fetch_result['cnt']. "')\n";
		$ctMapArray[$fetch_result['id']]['ct1'] = $no;
		$ctMapArray[$fetch_result['id']]['ct2'] = 0;
		$no ++;
	}

  $no = 1;  // $no 리셋.

	$sql = "SELECT id, name as label, parent as pno, priority as sortno, entriesInLogin as cnt ";
	$sql .= "FROM " . $database['prefix'] . "Categories where parent IS not NULL ORDER BY sortno";

	$result = mysql_query($sql);
	while ( $fetch_result = mysql_fetch_array($result) ){
		$output .= "insert into t3_[##_dbid_##]_ct2 (no, pno, sortno, label, cnt) values (";
		$output .= "'" .$no. "', '";					// no 새로 할당함.
		$output .= $ctMapArray[$fetch_result['pno']]['ct1']. "', '";					// 새로 할당된 no로 치환.
		$output .= $no. "', '";					// sortno <- no와 같음 (sql에서 sortno대로 소팅해서 가져왔기에.)
		$output .= $fetch_result['label']. "', '";
		$output .= $fetch_result['cnt']. "')\n";
		$ctMapArray[$fetch_result['id']]['ct1'] = $ctMapArray[$fetch_result['pno']]['ct1'];
		$ctMapArray[$fetch_result['id']]['ct2'] = $no;
		$no ++;
	}

  # 디버깅용
	#print_r2($ctMapArray);

	return $output;
}

function get_ttfiles(){

/*
 * Todo
 *
 * entry를 체크하여 Category가 -1인 pno을 따로 빼서 저장,
 * attachment에서 나온 pno를 검색하여 해당 pno가 있다면
 * 키로그의 attachment로 저장하도록 다시 짜야함...
 * 흠.. 차라리 처음부터 전역변수 생성해서 붙여나가기로
 * 만들어야 하나 난감하다..  뭐 생각해보면
 * no 만 하나 더 따로 해서 no_key 등으로 지정, insert하게
 * 해도 상관없을 것 같다.
 *
 */

	global $database;
	$output = '';
	/*
	 * 이 곳에서 no를 다시 새로 부여한다.
	 */
	$no = 1;			// 일반 엔트리의 첨부파일의 no 필드.
	$no_keylog = 1;		// 키로그용 첨부파일의 no 필드.

	$sql = "SELECT a1.parent AS pno, a1.name AS attachname, ";
	$sql .= "a1.label AS filename, a1.size AS filesize, ";
	$sql .= "a1.width, a1.height, a1.attached AS regdate, ";
	$sql .= "e1.category as cat ";
	$sql .= "FROM " . $database['prefix'] . "Attachments as a1 ";
	$sql .= "left join " . $database['prefix'] . "Entries as e1 on a1.parent = e1.id ";
	$sql .= "ORDER BY pno ";
	/*
	 * cat 값이
	 * NULL 이면 프로필용 사진
	 * -1 이면 키로그용 업로드 파일
	 * 그 외의 값이면 일반 업로드 파일.
	 */

	$result = mysql_query($sql);
	while ( $fetch_result = mysql_fetch_array($result) ){
		if (is_null($fetch_result['cat'])){
			/*
			 * 프로필용 이미지 처리
			 * 특별히 하지 않음.
			 */
		} else if ($fetch_result['cat'] == -1)  {
			/*
			 * 키로그 업로드 처리
			 */
			$output .= "insert into t3_[##_dbid_##]_keyword_files (no, pno, attachname, filename, filesize, width, height, regdate) values (";
			$output .= "'" .$no_keylog. "', '";
			$output .= $fetch_result['pno']. "', '";
			$output .= $fetch_result['attachname']. "', '";
			$output .= $fetch_result['filename']. "', '";
			$output .= $fetch_result['filesize']. "', '";
			$output .= $fetch_result['width']. "', '";
			$output .= $fetch_result['height']. "', '";
			$output .= $fetch_result['regdate']. "')\n";
			$no_keylog ++;
		} else {
			/*
			 * 일반 업로드 처리
			 */
			$output .= "insert into t3_[##_dbid_##]_files (no, pno, attachname, filename, filesize, width, height, regdate) values (";
			$output .= "'" .$no. "', '";
			$output .= $fetch_result['pno']. "', '";
			$output .= $fetch_result['attachname']. "', '";
			$output .= $fetch_result['filename']. "', '";
			$output .= $fetch_result['filesize']. "', '";
			$output .= $fetch_result['width']. "', '";
			$output .= $fetch_result['height']. "', '";
			$output .= $fetch_result['regdate']. "')\n";
			$no ++;
		}



	}

	return $output;
}

function get_ttsetting(){
	global $database;
	global $ownerMapArray;

	$sql = "select owner, title, description, logo, logoLabel, logoWidth, logoHeight from ".$database['prefix']."BlogSettings" ;
	$result = mysql_query($sql);
	$fetch_result = mysql_fetch_array($result);

	// 블로그 세팅을 리턴하는 함수.
	$output = "insert into t3_[##_dbid_##]_setting (user_pass, user_nick, icount, title, description, imagefile, imagelabel, width, height, page_cnt, article_cnt, keyword_cnt, xml_cnt, perm_rp, perm_tb, skin, rct_ps_cnt, rct_rp_cnt, rct_tb_cnt, rct_ps_trunc, rct_rp_trunc, rct_tb_trunc, link_trunc, tree, tree_limit, tree_back, tree_c, tree_c2, tree_bc, tree_bc2, read_cycle, delete_cycle, show_preview, reader_address_mig, show_member, show_tree_cnt, select_cat_view, select_arc_view, l_key_cache, g_key_cache, rssv_type, rss_public, ip_block, box1_style, box2_style, box3_style, box4_style, rssp_type, rssp_limit, gue_page_cnt, gue_perm) values (";
	// 암호는 무엇이 들어있던간에 무시되므로 빈칸으로 냅둠.
	$output .= "'', ";
	$output .= "'".$ownerMapArray[$fetch_result['owner']]['name']."', ";
	$output .= "'0', ";
	$output .= "'".$fetch_result['title']."', ";
	$output .= "'".$fetch_result['description']."', ";
	$output .= "'../".$fetch_result['owner']."/".$fetch_result['logo']."', ";
	$output .= "'".$fetch_result['logoLabel']."', ";
	$output .= "'".$fetch_result['logoWidth']."', ";
	$output .= "'".$fetch_result['logoHeight']."', ";
	$output .= "'3', '10', '10', '5', '1', '1', '100_quan', '10', '10', '5', '30', '30', '30', '26', 'folder1', '30', '', '000030', 'FFFFFF', '', '0A246A', '120', '30', '0', '0', '1', '0', '1', '3', '', '', '2', '1', '', 'padding:10; background-color:#F0F0F0;', 'padding:10; background-color:#DEEFFF;', 'padding:10; background-color:#D6F7E0;', 'padding:10; background-color:#FFE6E6;', '1', '3', ";

	$sql = "select visits from ".$database['prefix']."BlogStatistics limit 1" ;
	$result = mysql_query($sql);
	$fetch_result = mysql_fetch_array($result);
	$output .= "'" .$fetch_result['visits']. "', ";

	$sql = "select visits from ".$database['prefix']."DailyStatistics order by date desc limit 1" ;
	$result = mysql_query($sql);
	$fetch_result = mysql_fetch_array($result);

	$output .= "'" .$fetch_result['visits']. "')\n";
	return $output;
}

function get_ttusers(){
	global $database;
	global $ownerMapArray;

	$sql = "select userid, name from " .$database['prefix']. "Users" ;
	$result = mysql_query($sql);
	while ( $fetch_result = mysql_fetch_array($result) ){
    $ownerMapArray[$fetch_result['userid']]['name'] = $fetch_result['name'];
	}
	# 디버깅용
  #	print_r2($ownerMapArray);

	return ;
}

function print_r2($arr){
  echo "<pre>";
  print_r($arr);
  echo "</pre>";
  }

function get_ttbody( $body ){
  # 본문 변환처리.... 클래식과 1.1.1과 다르기 때문에 필요.
  $body = str_replace('\'', '&#39;', $body );
  $body = str_replace("\n", '\r\n', $body);
  $body = str_replace("\r\r", '\r', $body);
  $body = str_replace('<br />\r\n', '\r\n', $body);
  $body = str_replace('\r\n<br />', '\r\n', $body);
  $body = str_replace('<br >', '\r\n', $body);
  $body = str_replace('<br>', '\r\n', $body);
  $body = str_replace('<br/>', '\r\n', $body);
  $body = str_replace('<br />', '\r\n', $body);
  $body = str_replace('&lt;', '<', $body);
  $body = str_replace('&gt;', '>', $body);
  $body = str_replace('&amp;', '&', $body);

  return $body;
}

?>

