<?php
include_once('./_common.php');
include('./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;
}
// 서버 html을 가져와서 dom처리
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=split('|',$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 WriteBoard($row) { 
    global $g5, $bo_table, $board, $member;



    $write_table = $g5['write_prefix'] . $bo_table;
    // 카테고리 자동추가
    SetCatName($row['ca_name']);
        
    if ($member['mb_id']) {
        $mb_id = $member['mb_id'];
        $wr_name = addslashes(clean_xss_tags($board['bo_use_name'] ? $member['mb_name'] : $member['mb_nick']));
        $wr_password = $member['mb_password'];
        $wr_email = addslashes($member['mb_email']);
        $wr_homepage = addslashes(clean_xss_tags($member['mb_homepage']));
    }
    $wr_num = get_next_num($write_table);
    $wr_reply = '';
   
    $sql = " insert into $write_table
                set wr_num = '$wr_num',
                     wr_reply = '$wr_reply',
                     wr_comment = 0,
                     wr_option = 'html2',
                     ca_name = '".addslashes($row[ca_name])."',
                     wr_subject = '".addslashes($row[v_subject])."',
                     wr_content = '".addslashes($row[wr_content])."',
                     wr_link1 = '',
                     wr_link2 = '',
                     wr_link1_hit = 0,
                     wr_link2_hit = 0,
                     wr_hit = 0,
                     wr_good = 0,
                     wr_nogood = 0,
                     mb_id = '{$member['mb_id']}',
                     wr_password = '$wr_password',
                     wr_name = '$wr_name',
                     wr_email = '$wr_email',
                     wr_homepage = '$wr_homepage',
                     wr_datetime = '".G5_TIME_YMDHIS."',
                     wr_last = '".G5_TIME_YMDHIS."',
                     wr_ip = '{$_SERVER['REMOTE_ADDR']}' ";
    sql_query($sql);
    $wr_id = sql_insert_id();

    // 부모 아이디에 UPDATE
    sql_query(" update $write_table set wr_parent = '$wr_id' where wr_id = '$wr_id' ");

    // 새글 INSERT
    sql_query(" insert into {$g5['board_new_table']} ( bo_table, wr_id, wr_parent, bn_datetime, mb_id ) values ( '{$bo_table}', '{$wr_id}', '{$wr_id}', '".G5_TIME_YMDHIS."', '{$member['mb_id']}' ) ");

    // 게시글 1 증가
    sql_query("update {$g5['board_table']} set bo_count_write = bo_count_write + 1 where bo_table = '{$bo_table}'");    
    
    // 가져옴 처리
    sql_query(" UPDATE cm_sync_view SET v_sync = '1' WHERE v_no = '$row[v_no]' ");
}
// 특정 URL 파일 다운로드
function GetRemoteDownload($url) { 
    global $site, $bo_table;    

    echo $url.'<br>';
    $urls=array();
    $urls = split('/',$url);

    $file_name = $urls[(count($urls)-1)];
    $dir = $urls[(count($urls)-2)];

    $img_url = $site.'data/editor/'.$dir.'/'.$file_name;        
    $path = '../data/editor/'.$dir; 

    @mkdir($path, G5_DIR_PERMISSION);
    @chmod($path, G5_DIR_PERMISSION);

    $ch = curl_init($url);
    $fp = fopen($path.'/'.$file_name, 'wb');
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);    
    return $img_url;
//     return "<a href='{$site}bbs/view_image.php?fn=".urlencode($img_url)."' target=\"_blank\" class=\"view_image\"><img src=\"{$img_url}\" width=\"600\"></a>";   썸네일과 보기 파일 일괄시
}

// view 페이지내 링크 페이지 가져오기
function GetFileView($row) {
    global $site, $g5, $bo_table, $board;

    echo $row['v_url'].'<br>';        

    $h = GetDom(urldecode($row['v_url']));    
    $h = str_get_html($h->find('div.view-content',0)->outertext);
    $row['wr_content'] = '';
    
    foreach($h->find('a.view_image') as $link) {
        $img = '';
        $href= urldecode($link->href);
        $img_href=explode("fn=",$href);
        $thumb_img = $link->find('img',0)->src;            
        $thumb_img = str_replace('yabam9', 'yabam10', $thumb_img);
        $img = 'http://test.com'.$img_href[1];
        echo $img.'<br>';        
        
        // 썸네일 파일 포함 문제는 다중다운로드로 인하 차단확률은 올라감
        $row['wr_content'] .= "<a href='{$site}bbs/view_image.php?fn=".urlencode(GetRemoteDownload($img))."' target=\"_blank\" class=\"view_image\"><img src=\"".GetRemoteDownload($thumb_img)."\" width=\"600\"></a><br>";            
//         $row['wr_content'] .= GetRemoteDownload($img);            
       flush(); usleep(100);        
    }          
    WriteBoard($row);
    
}

    echo 'start<br>';
    // 저장할 사이트 주소
    $site = 'http://ccsoft.kr/';
    // 가져오 게시판 
    $bo_table = 'toon';
    $board = sql_fetch(" select * from {$g5['board_table']} where bo_table = '$bo_table' ");
    $member=get_member('admin');
    $rows = 1;       // 한번에 가져와 등록하는 게싯물 수

            
   $rs=sql_query(" SELECT a.*, b.* FROM cm_sync_view a left join cm_sync b on(a.no=b.no) WHERE a.v_sync is NULL order by a.v_no asc limit $rows ");
   while($row=sql_fetch_array($rs)) {
        GetFileView($row);
       // 서버 먹통방지 딜레이
       flush(); usleep(1000);
   }
    echo '<br>end';
?>    