<?php
include_once('./_common.php');
include_once('./simple_html_dom.php');
/*
  제작자 : oldccc@gmail.com ccc  
*/    

function server_comm($uri, $postdata = null, $post = false, $timeout=20) {
	$ch = curl_init($uri);
	if( $postdata ){
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
	}
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); # 시간제한:초(제한 없음 : 0 )
	$result = curl_exec($ch);

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if (curl_errno($ch))
    {
        return false; //probably you want to return false
    }
    if ($httpCode != 200)
    {
        return false; //probably you want to return false
    }
    curl_close($ch);
	return $result;
}

function GetDom($url) {
    $html = server_comm(str_replace("&amp;", "&",$url));
    $h = str_get_html($html);
    return $h;
}
function  SetCatName($ca_name) {
    global $g5, $board, $bo_table;
    $cat_list=array();
    $tmp_list=array();
    $cat_list=explode('|',$board['bo_category_list']);
    
    $chk = 0;
    for($i=0,$cnt=count($cat_list);$i<$cnt;$i++) { 
        if($cat_list[$i]==$ca_name) $chk = 1;
    }       
    
    if(!$chk) {
        $cat_list[]=$ca_name;
        sql_fetch(" UPDATE FROM {$g5['board_table']} SET bo_category_list = '".implode('|',$cat_list)."' where bo_table = '$bo_table' ");
    }
}

function GetLastPage($h) {
    $pg = $h->find('a.pg_page', -1);
    $page = explode("page=",$pg->href);
    return $page[1];
}
function SetSync($row) {
    global $bo_table;
    preg_match("/wr_id=[0-9]*/", $row['href'], $match);
    $wr_id = str_replace("wr_id=","",$match[0]);
    $chk=sql_fetch(" SELECT count(*) as cnt FROM cm_sync WHERE bo_table = '$bo_table' and wr_id = '$wr_id' ");
    if(!$chk['cnt']) {
        sql_query(" INSERT INTO cm_sync SET bo_table = '$bo_table', wr_id = '$wr_id', ca_name = '$row[ca_name]', wr_subject = '".mysql_escape_string($row[wr_subject])."', url = '$row[href]' ");
        echo $row['href'].'<br>';
    } else {
        echo '[이미 가져옴]<br>';
        exit;   // 더 이상 진행 안함
    }
}

function GetList($url) { 
    echo $url.'<br>';
    $h = GetDom($url);
    foreach($h->find('td.mw_basic_list_subject ') as $el) {
        $row=array();
        $row['ca_name'] = $el->parent()->children(1)->plaintext;
        if($row['ca_name']!='공지') {
            SetCatName($row['ca_name']);
            $row['wr_subject'] = $el->children(1)->plaintext;
            $row['href'] = $el->children(1)->href;
            SetSync($row);  // 이미 가져왔는지 체크하여 DB에 저장
        }
    }
}

// 테이블 생성 한번 실행후 삭제 또는 주석처리 
sql_query("
CREATE TABLE IF NOT EXISTS `cm_sync` (
 `no` int(11) NOT NULL AUTO_INCREMENT,
 `bo_table` varchar(20) CHARACTER SET utf8 NOT NULL,
 `wr_id` int(11) NOT NULL,
 `ca_name` varchar(80) CHARACTER SET utf8 NOT NULL,
 `wr_subject` varchar(200) CHARACTER SET utf8 NOT NULL,
 `url` varchar(255) CHARACTER SET utf8 NOT NULL,
 `sync` tinyint(4) DEFAULT NULL,
 PRIMARY KEY (`no`)
) ENGINE=MyISAM");


    echo 'start<br>';
    // 저장할 사이트 주소
    $site = 'http://ccsoft.kr';
    // 가져오 게시판 
    $bo_table = 'toon';
    // 가져올 사이트 주소
    $url = 'http://test.com/bbs/board.php?bo_table='.$bo_table;

    $board = sql_fetch(" select * from {$g5['board_table']} where bo_table = '$bo_table' ");

    if(!$startpg) $startpg=1; // 기본 시작 페이지값
    if(!$lastpg) {
        // 마지막 페이지를 모른 경우 마지막 페이지 크로링해서 가져옴
        $h = GetDom($url);
        $lastpg = GetLastPage($h);
    }


    for($i=$startpg;$i<=$lastpg;$i++) {
        GetList($url.'&page='.$i);
        flush(); usleep(1000);
    }
    echo 'end';
?>    