get('bbs', $wr_id, $wr_bo_table);
if( !$write || $is_cache == false ){
$sql = " select * from {$write_table} where wr_id = '{$wr_id}' ";
$write = sql_fetch($sql);
$g5_object->set('bbs', $wr_id, $write, $wr_bo_table);
}
return $write;
}
// 게시판의 다음글 번호를 얻는다.
function get_next_num($table)
{
// 가장 작은 번호를 얻어
$sql = " select min(wr_num) as min_wr_num from $table ";
$row = sql_fetch($sql);
// 가장 작은 번호에 1을 빼서 넘겨줌
return isset($row['min_wr_num']) ? (int)($row['min_wr_num'] - 1) : -1;
}
// 그룹 설정 테이블에서 하나의 행을 읽음
function get_group($gr_id, $is_cache=false)
{
global $g5;
if( is_array($gr_id) ){
return array();
}
static $cache = array();
$gr_id = preg_replace('/[^a-z0-9_]/i', '', $gr_id);
$cache = run_replace('get_group_db_cache', $cache, $gr_id, $is_cache);
$key = md5($gr_id);
if( $is_cache && isset($cache[$key]) ){
return $cache[$key];
}
$sql = " select * from {$g5['group_table']} where gr_id = '$gr_id' ";
$group = run_replace('get_group', sql_fetch($sql), $gr_id, $is_cache);
$cache[$key] = array_merge(array('gr_device'=>'', 'gr_subject'=>''), (array) $group);
return $cache[$key];
}
/**
* 회원 정보를 얻는다
*
* @param string $mb_id
* @param string $fields
* @param bool $is_cache
*
* @return array
*/
function get_member($mb_id, $fields = '*', $is_cache = false)
{
global $g5;
$mb_id = trim($mb_id);
if (preg_match("/[^0-9a-z_]+/i", $mb_id)) {
return array();
}
static $cache = array();
$key = md5($fields);
if ($is_cache && isset($cache[$mb_id]) && isset($cache[$mb_id][$key])) {
return $cache[$mb_id][$key];
}
$sql = " SELECT {$fields} from {$g5['member_table']} where mb_id = '{$mb_id}' ";
$cache[$mb_id][$key] = run_replace('get_member', sql_fetch($sql), $mb_id, $fields, $is_cache);
return $cache[$mb_id][$key];
}
// 날짜, 조회수의 경우 높은 순서대로 보여져야 하므로 $flag 를 추가
// $flag : asc 낮은 순서 , desc 높은 순서
// 제목별로 컬럼 정렬하는 QUERY STRING
function subject_sort_link($col, $query_string='', $flag='asc')
{
global $sst, $sod, $sfl, $stx, $page, $sca;
$q1 = "sst=$col";
if ($flag == 'asc')
{
$q2 = 'sod=asc';
if ($sst == $col)
{
if ($sod == 'asc')
{
$q2 = 'sod=desc';
}
}
}
else
{
$q2 = 'sod=desc';
if ($sst == $col)
{
if ($sod == 'desc')
{
$q2 = 'sod=asc';
}
}
}
$arr_query = array();
$arr_query[] = $query_string;
$arr_query[] = $q1;
$arr_query[] = $q2;
$arr_query[] = 'sfl='.$sfl;
$arr_query[] = 'stx='.$stx;
$arr_query[] = 'sca='.$sca;
$arr_query[] = 'page='.$page;
$qstr = implode("&", $arr_query);
parse_str(html_entity_decode($qstr), $qstr_array);
$url = short_url_clean(get_params_merge_url($qstr_array));
return '';
}
// 관리자 정보를 얻음
function get_admin($admin='super', $fields='*')
{
global $config, $group, $board;
global $g5;
$is = false;
if ($admin == 'board') {
$mb = sql_fetch("select {$fields} from {$g5['member_table']} where mb_id in ('{$board['bo_admin']}') limit 1 ");
$is = true;
}
// if (($is && !$mb['mb_id']) || $admin == 'group') {
if (($is && !isset($mb['mb_id'])) || $admin == 'group') {
$mb = sql_fetch("select {$fields} from {$g5['member_table']} where mb_id in ('{$group['gr_admin']}') limit 1 ");
$is = true;
}
// if (($is && !$mb['mb_id']) || $admin == 'super') {
if (($is && !isset($mb['mb_id'])) || $admin == 'super') {
$mb = sql_fetch("select {$fields} from {$g5['member_table']} where mb_id in ('{$config['cf_admin']}') limit 1 ");
}
return $mb;
}
// 관리자인가?
function is_admin($mb_id)
{
global $config, $group, $board;
if (!$mb_id) return '';
$is_authority = '';
if ($config['cf_admin'] == $mb_id){
$is_authority = 'super';
} else if (isset($group['gr_admin']) && ($group['gr_admin'] == $mb_id)){
$is_authority = 'group';
} else if (isset($board['bo_admin']) && ($board['bo_admin'] == $mb_id)){
$is_authority = 'board';
}
return run_replace('is_admin', $is_authority, $mb_id);
}
// 분류 옵션을 얻음
// 4.00 에서는 카테고리 테이블을 없애고 보드테이블에 있는 내용으로 대체
function get_category_option($bo_table='', $ca_name='')
{
global $g5, $board, $is_admin;
$categories = explode("|", $board['bo_category_list'].($is_admin?"|공지":"")); // 구분자가 | 로 되어 있음
$str = "";
for ($i=0; $i\n";
for ($i=0; $row=sql_fetch_array($result); $i++) {
if ($i == 0) $str .= "";
$str .= option_selected($row['gr_id'], $selected, $row['gr_subject']);
}
$str .= "";
return $str;
}
function option_selected($value, $selected, $text='')
{
if (!$text) $text = $value;
if ($value == $selected)
return "\n";
else
return "\n";
}
// '예', '아니오'를 SELECT 형식으로 얻음
function get_yn_select($name, $selected='1', $event='')
{
$str = "";
return $str;
}
// 포인트 부여
function insert_point($mb_id, $point, $content='', $rel_table='', $rel_id='', $rel_action='', $expire=0)
{
global $config;
global $g5;
global $is_admin;
// 포인트 사용을 하지 않는다면 return
if (!$config['cf_use_point']) { return 0; }
// 포인트가 없다면 업데이트 할 필요 없음
if ($point == 0) { return 0; }
// 회원아이디가 없다면 업데이트 할 필요 없음
if ($mb_id == '') { return 0; }
$mb = sql_fetch(" select mb_id from {$g5['member_table']} where mb_id = '$mb_id' ");
if (!$mb['mb_id']) { return 0; }
// 회원포인트
$mb_point = get_point_sum($mb_id);
// 이미 등록된 내역이라면 건너뜀
if ($rel_table || $rel_id || $rel_action)
{
$sql = " select count(*) as cnt from {$g5['point_table']}
where mb_id = '$mb_id'
and po_rel_table = '$rel_table'
and po_rel_id = '$rel_id'
and po_rel_action = '$rel_action' ";
$row = sql_fetch($sql);
if ($row['cnt'])
return -1;
}
// 포인트 건별 생성
$po_expire_date = '9999-12-31';
if($config['cf_point_term'] > 0) {
if($expire > 0)
$po_expire_date = date('Y-m-d', strtotime('+'.($expire - 1).' days', G5_SERVER_TIME));
else
$po_expire_date = date('Y-m-d', strtotime('+'.($config['cf_point_term'] - 1).' days', G5_SERVER_TIME));
}
$po_expired = 0;
if($point < 0) {
$po_expired = 1;
$po_expire_date = G5_TIME_YMD;
}
$po_mb_point = $mb_point + $point;
$sql = " insert into {$g5['point_table']}
set mb_id = '$mb_id',
po_datetime = '".G5_TIME_YMDHIS."',
po_content = '".addslashes($content)."',
po_point = '$point',
po_use_point = '0',
po_mb_point = '$po_mb_point',
po_expired = '$po_expired',
po_expire_date = '$po_expire_date',
po_rel_table = '$rel_table',
po_rel_id = '$rel_id',
po_rel_action = '$rel_action' ";
sql_query($sql);
// 포인트를 사용한 경우 포인트 내역에 사용금액 기록
if($point < 0) {
insert_use_point($mb_id, $point);
}
// 포인트 UPDATE
$sql = " update {$g5['member_table']} set mb_point = '$po_mb_point' where mb_id = '$mb_id' ";
sql_query($sql);
return 1;
}
// 사용포인트 입력
function insert_use_point($mb_id, $point, $po_id='')
{
global $g5, $config;
if($config['cf_point_term'])
$sql_order = " order by po_expire_date asc, po_id asc ";
else
$sql_order = " order by po_id asc ";
$point1 = abs($point);
$sql = " select po_id, po_point, po_use_point
from {$g5['point_table']}
where mb_id = '$mb_id'
and po_id <> '$po_id'
and po_expired = '0'
and po_point > po_use_point
$sql_order ";
$result = sql_query($sql);
for($i=0; $row=sql_fetch_array($result); $i++) {
$point2 = $row['po_point'];
$point3 = $row['po_use_point'];
if(($point2 - $point3) > $point1) {
$sql = " update {$g5['point_table']}
set po_use_point = po_use_point + '$point1'
where po_id = '{$row['po_id']}' ";
sql_query($sql);
break;
} else {
$point4 = $point2 - $point3;
$sql = " update {$g5['point_table']}
set po_use_point = po_use_point + '$point4',
po_expired = '100'
where po_id = '{$row['po_id']}' ";
sql_query($sql);
$point1 -= $point4;
}
}
}
// 사용포인트 삭제
function delete_use_point($mb_id, $point)
{
global $g5, $config;
if($config['cf_point_term'])
$sql_order = " order by po_expire_date desc, po_id desc ";
else
$sql_order = " order by po_id desc ";
$point1 = abs($point);
$sql = " select po_id, po_use_point, po_expired, po_expire_date
from {$g5['point_table']}
where mb_id = '$mb_id'
and po_expired <> '1'
and po_use_point > 0
$sql_order ";
$result = sql_query($sql);
for($i=0; $row=sql_fetch_array($result); $i++) {
$point2 = $row['po_use_point'];
$po_expired = $row['po_expired'];
if($row['po_expired'] == 100 && ($row['po_expire_date'] == '9999-12-31' || $row['po_expire_date'] >= G5_TIME_YMD))
$po_expired = 0;
if($point2 > $point1) {
$sql = " update {$g5['point_table']}
set po_use_point = po_use_point - '$point1',
po_expired = '$po_expired'
where po_id = '{$row['po_id']}' ";
sql_query($sql);
break;
} else {
$sql = " update {$g5['point_table']}
set po_use_point = '0',
po_expired = '$po_expired'
where po_id = '{$row['po_id']}' ";
sql_query($sql);
$point1 -= $point2;
}
}
}
// 소멸포인트 삭제
function delete_expire_point($mb_id, $point)
{
global $g5, $config;
$point1 = abs($point);
$sql = " select po_id, po_use_point, po_expired, po_expire_date
from {$g5['point_table']}
where mb_id = '$mb_id'
and po_expired = '1'
and po_point >= 0
and po_use_point > 0
order by po_expire_date desc, po_id desc ";
$result = sql_query($sql);
for($i=0; $row=sql_fetch_array($result); $i++) {
$point2 = $row['po_use_point'];
$po_expired = '0';
$po_expire_date = '9999-12-31';
if($config['cf_point_term'] > 0)
$po_expire_date = date('Y-m-d', strtotime('+'.($config['cf_point_term'] - 1).' days', G5_SERVER_TIME));
if($point2 > $point1) {
$sql = " update {$g5['point_table']}
set po_use_point = po_use_point - '$point1',
po_expired = '$po_expired',
po_expire_date = '$po_expire_date'
where po_id = '{$row['po_id']}' ";
sql_query($sql);
break;
} else {
$sql = " update {$g5['point_table']}
set po_use_point = '0',
po_expired = '$po_expired',
po_expire_date = '$po_expire_date'
where po_id = '{$row['po_id']}' ";
sql_query($sql);
$point1 -= $point2;
}
}
}
// 포인트 내역 합계
function get_point_sum($mb_id)
{
global $g5, $config;
if($config['cf_point_term'] > 0) {
// 소멸포인트가 있으면 내역 추가
$expire_point = get_expire_point($mb_id);
if($expire_point > 0) {
$mb = get_member($mb_id, 'mb_point');
$content = '포인트 소멸';
$rel_table = '@expire';
$rel_id = $mb_id;
$rel_action = 'expire'.'-'.uniqid('');
$point = $expire_point * (-1);
$po_mb_point = $mb['mb_point'] + $point;
$po_expire_date = G5_TIME_YMD;
$po_expired = 1;
$sql = " insert into {$g5['point_table']}
set mb_id = '$mb_id',
po_datetime = '".G5_TIME_YMDHIS."',
po_content = '".addslashes($content)."',
po_point = '$point',
po_use_point = '0',
po_mb_point = '$po_mb_point',
po_expired = '$po_expired',
po_expire_date = '$po_expire_date',
po_rel_table = '$rel_table',
po_rel_id = '$rel_id',
po_rel_action = '$rel_action' ";
sql_query($sql);
// 포인트를 사용한 경우 포인트 내역에 사용금액 기록
if($point < 0) {
insert_use_point($mb_id, $point);
}
}
// 유효기간이 있을 때 기간이 지난 포인트 expired 체크
$sql = " update {$g5['point_table']}
set po_expired = '1'
where mb_id = '$mb_id'
and po_expired <> '1'
and po_expire_date <> '9999-12-31'
and po_expire_date < '".G5_TIME_YMD."' ";
sql_query($sql);
}
// 포인트합
$sql = " select sum(po_point) as sum_po_point
from {$g5['point_table']}
where mb_id = '$mb_id' ";
$row = sql_fetch($sql);
return $row['sum_po_point'];
}
// 소멸 포인트
function get_expire_point($mb_id)
{
global $g5, $config;
if($config['cf_point_term'] == 0)
return 0;
$sql = " select sum(po_point - po_use_point) as sum_point
from {$g5['point_table']}
where mb_id = '$mb_id'
and po_expired = '0'
and po_expire_date <> '9999-12-31'
and po_expire_date < '".G5_TIME_YMD."' ";
$row = sql_fetch($sql);
return $row['sum_point'];
}
// 포인트 삭제
function delete_point($mb_id, $rel_table, $rel_id, $rel_action)
{
global $g5;
$result = false;
if ($rel_table || $rel_id || $rel_action)
{
// 포인트 내역정보
$sql = " select * from {$g5['point_table']}
where mb_id = '$mb_id'
and po_rel_table = '$rel_table'
and po_rel_id = '$rel_id'
and po_rel_action = '$rel_action' ";
$row = sql_fetch($sql);
if (! (isset($row['po_id']) && $row['po_id'])) {
return true;
}
if(isset($row['po_point']) && $row['po_point'] < 0) {
$mb_id = $row['mb_id'];
$po_point = abs($row['po_point']);
delete_use_point($mb_id, $po_point);
} else {
if(isset($row['po_use_point']) && $row['po_use_point'] > 0) {
insert_use_point($row['mb_id'], $row['po_use_point'], $row['po_id']);
}
}
$result = sql_query(" delete from {$g5['point_table']}
where mb_id = '$mb_id'
and po_rel_table = '$rel_table'
and po_rel_id = '$rel_id'
and po_rel_action = '$rel_action' ", false);
// po_mb_point에 반영
if(isset($row['po_point'])) {
$sql = " update {$g5['point_table']}
set po_mb_point = po_mb_point - '{$row['po_point']}'
where mb_id = '$mb_id'
and po_id > '{$row['po_id']}' ";
sql_query($sql);
}
// 포인트 내역의 합을 구하고
$sum_point = get_point_sum($mb_id);
// 포인트 UPDATE
$sql = " update {$g5['member_table']} set mb_point = '$sum_point' where mb_id = '$mb_id' ";
$result = sql_query($sql);
}
return $result;
}
// 회원 레이어
function get_sideview($mb_id, $name='', $email='', $homepage='')
{
global $config;
global $g5;
global $bo_table, $sca, $is_admin, $member;
static $cache = array();
$name = get_text($name, 0, true);
if (isset($cache['id:' . $mb_id]) && $cache['id:' . $mb_id]) {
return $cache['id:' . $mb_id];
} else if (
isset($name)
&& isset($cache['name:' . $name])
&& $cache['name:' . $name]
) {
return $cache['name:' . $name];
}
$email = get_string_encrypt($email);
$email = get_text($email);
$homepage = set_http(clean_xss_tags($homepage));
$homepage = get_text($homepage);
$en_mb_id = $mb_id;
$name_tag = array();
$menus = array();
if ($mb_id) {
// $tmp_name = "$name";
$name_tag_open = '';
if ($config['cf_use_member_icon']) {
$mb_dir = substr($mb_id, 0, 2);
$icon_file = G5_DATA_PATH . '/member/' . $mb_dir . '/' . get_mb_icon_name($mb_id) . '.gif';
if (file_exists($icon_file)) {
$icon_filemtile = (defined('G5_USE_MEMBER_IMAGE_FILETIME') && G5_USE_MEMBER_IMAGE_FILETIME) ? '?' . filemtime($icon_file) : '';
$width = $config['cf_member_icon_width'];
$height = $config['cf_member_icon_height'];
$icon_file_url = G5_DATA_URL . '/member/' . $mb_dir . '/' . get_mb_icon_name($mb_id) . '.gif' . $icon_filemtile;
$name_tag['profile_image'] = '
';
// 회원아이콘+이름
if ($config['cf_use_member_icon'] == 2) {
$name_tag['name'] = $name;
}
} else {
if (defined('G5_THEME_NO_PROFILE_IMG')) {
$name_tag['profile_image'] = G5_THEME_NO_PROFILE_IMG;
} else if (defined('G5_NO_PROFILE_IMG')) {
$name_tag['profile_image'] = G5_NO_PROFILE_IMG;
}
// 회원아이콘+이름
if ($config['cf_use_member_icon'] == 2) {
$name_tag['name'] = $name;
}
}
} else {
$name_tag['name'] = $name;
}
} else {
if (!$bo_table) {
return $name;
}
$name_tag_open = '';
$name_tag['name'] = $name;
}
if ($mb_id) {
$menus['memo'] = '쪽지보내기';
}
if ($email) {
$menus['email'] = '메일보내기';
}
if ($homepage) {
$menus['homepage'] = '홈페이지';
}
if ($mb_id) {
$menus['profile'] = '자기소개';
}
if ($bo_table) {
if ($mb_id) {
$menus['search_id'] = '아이디로 검색';
} else {
$menus['search_name'] = '이름으로 검색';
}
}
if ($mb_id) {
$menus['search_all'] = '전체게시물';
if ($is_admin == 'super') {
$menus['admin_member_modify'] = '회원정보변경';
$menus['admin_member_point'] = '포인트내역';
}
}
$name_tag_close = '';
$items = run_replace('member_sideview_items', array(
'name_tag_open' => $name_tag_open,
'name_tag_close' => $name_tag_close,
'name_tag' => $name_tag,
'menus' => $menus
), array(
'mb_id' => $mb_id,
'name' => $name,
'bo_table' => $bo_table,
)
);
$str = '';
$str .= $items['name_tag_open'] . implode(' ', $items['name_tag']) . $items['name_tag_close'];
$str2 = '';
$str2 .= implode("\n", $items['menus']);
$str2 .= '';
$str .= $str2;
$str .= '';
$str .= "";
if ($mb_id) {
$cache['id:' . $mb_id] = $str;
} else {
$cache['name:' . $name] = $str;
}
return $str;
}
// 파일을 보이게 하는 링크 (이미지, 플래쉬, 동영상)
function view_file_link($file, $width, $height, $content='')
{
global $config, $board;
global $g5;
static $ids;
if (!$file) return;
$ids++;
// 파일의 폭이 게시판설정의 이미지폭 보다 크다면 게시판설정 폭으로 맞추고 비율에 따라 높이를 계산
if ($board && $width > $board['bo_image_width'] && $board['bo_image_width'])
{
$rate = $board['bo_image_width'] / $width;
$width = $board['bo_image_width'];
$height = (int)($height * $rate);
}
// 폭이 있는 경우 폭과 높이의 속성을 주고, 없으면 자동 계산되도록 코드를 만들지 않는다.
if ($width)
$attr = ' width="'.$width.'" height="'.$height.'" ';
else
$attr = '';
if (preg_match("/\.({$config['cf_image_extension']})$/i", $file) && isset($board['bo_table'])) {
$attr_href = run_replace('thumb_view_image_href', G5_BBS_URL.'/view_image.php?bo_table='.$board['bo_table'].'&fn='.urlencode($file), $file, $board['bo_table'], $width, $height, $content);
$img = '';
$img .= '
';
$img .= '';
return $img;
}
}
// view_file_link() 함수에서 넘겨진 이미지를 보이게 합니다.
// {img:0} ... {img:n} 과 같은 형식
function view_image($view, $number, $attribute)
{
if ($view['file'][$number]['view'])
return preg_replace("/>$/", " $attribute>", $view['file'][$number]['view']);
else
//return "{".$number."번 이미지 없음}";
return "";
}
/*
// {link:0} ... {link:n} 과 같은 형식
function view_link($view, $number, $attribute)
{
global $config;
if ($view['link'][$number]['link'])
{
if (!preg_match("/target/i", $attribute))
$attribute .= " target='$config['cf_link_target']'";
return "{$view['link'][$number]['link']}";
}
else
return "{".$number."번 링크 없음}";
}
*/
function cut_str($str, $len, $suffix="…")
{
$arr_str = preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
$str_len = count($arr_str);
if ($str_len >= $len) {
$slice_str = array_slice($arr_str, 0, $len);
$str = join("", $slice_str);
return $str . ($str_len > $len ? $suffix : '');
} else {
$str = join("", $arr_str);
return $str;
}
}
// TEXT 형식으로 변환
function get_text($str, $html=0, $restore=false)
{
$source[] = "<";
$target[] = "<";
$source[] = ">";
$target[] = ">";
$source[] = "\"";
$target[] = """;
$source[] = "\'";
$target[] = "'";
if($restore)
$str = str_replace($target, $source, $str);
// 3.31
// TEXT 출력일 경우 & 등의 코드를 정상으로 출력해 주기 위함
if ($html == 0) {
$str = html_symbol($str);
}
if ($html) {
$source[] = "\n";
$target[] = "
";
}
return str_replace($source, $target, $str);
}
/*
// HTML 특수문자 변환 htmlspecialchars
function hsc($str)
{
$trans = array("\"" => """, "'" => "'", "<"=>"<", ">"=>">");
$str = strtr($str, $trans);
return $str;
}
*/
// 3.31
// HTML SYMBOL 변환
// & · 등을 정상으로 출력
function html_symbol($str)
{
return $str ? preg_replace("/\&([a-z0-9]{1,20}|\#[0-9]{0,3});/i", "&\\1;", $str) : "";
}
/*************************************************************************
**
** SQL 관련 함수 모음
**
*************************************************************************/
// DB 연결
function sql_connect($host, $user, $pass, $db=G5_MYSQL_DB)
{
global $g5;
if(function_exists('mysqli_connect') && G5_MYSQLI_USE) {
mysqli_report(MYSQLI_REPORT_OFF);
$link = @mysqli_connect($host, $user, $pass, $db) or die('MySQL Host, User, Password, DB 정보에 오류가 있습니다.');
// 연결 오류 발생 시 스크립트 종료
if (mysqli_connect_errno()) {
die('Connect Error: '.mysqli_connect_error());
}
} else {
if (!function_exists('mysql_connect')) {
die('MySQL이 설치되지 않아 mysql_connect 함수를 사용할 수 없습니다.');
}
$link = mysql_connect($host, $user, $pass) or die('MySQL Host, User, Password 정보에 오류가 있습니다.');
}
return $link;
}
// DB 선택
function sql_select_db($db, $connect)
{
global $g5;
if(function_exists('mysqli_select_db') && G5_MYSQLI_USE)
return @mysqli_select_db($connect, $db);
else
return @mysql_select_db($db, $connect);
}
function sql_set_charset($charset, $link=null)
{
global $g5;
if(!$link)
$link = $g5['connect_db'];
if(function_exists('mysqli_set_charset') && G5_MYSQLI_USE)
mysqli_set_charset($link, $charset);
else
mysql_query(" set names {$charset} ", $link);
}
function sql_data_seek($result, $offset=0)
{
if ( ! $result ) return;
if(function_exists('mysqli_set_charset') && G5_MYSQLI_USE)
mysqli_data_seek($result, $offset);
else
mysql_data_seek($result, $offset);
}
// mysqli_query 와 mysqli_error 를 한꺼번에 처리
// mysql connect resource 지정 - 명랑폐인님 제안
function sql_query($sql, $error=G5_DISPLAY_SQL_ERROR, $link=null)
{
global $g5, $g5_debug;
if(!$link)
$link = $g5['connect_db'];
// Blind SQL Injection 취약점 해결
$sql = trim($sql);
// union의 사용을 허락하지 않습니다.
//$sql = preg_replace("#^select.*from.*union.*#i", "select 1", $sql);
$sql = preg_replace("#^select.*from.*[\s\(]+union[\s\)]+.*#i ", "select 1", $sql);
// `information_schema` DB로의 접근을 허락하지 않습니다.
$sql = preg_replace("#^select.*from.*where.*`?information_schema`?.*#i", "select 1", $sql);
$is_debug = get_permission_debug_show();
$start_time = ($is_debug || G5_COLLECT_QUERY) ? get_microtime() : 0;
if(function_exists('mysqli_query') && G5_MYSQLI_USE) {
if ($error) {
$result = @mysqli_query($link, $sql) or die("$sql
" . mysqli_errno($link) . " : " . mysqli_error($link) . "
error file : {$_SERVER['SCRIPT_NAME']}");
} else {
try {
$result = @mysqli_query($link, $sql);
} catch (Exception $e) {
$result = null;
}
}
} else {
if ($error) {
$result = @mysql_query($sql, $link) or die("
$sql
" . mysql_errno() . " : " . mysql_error() . "
error file : {$_SERVER['SCRIPT_NAME']}");
} else {
$result = @mysql_query($sql, $link);
}
}
$end_time = ($is_debug || G5_COLLECT_QUERY) ? get_microtime() : 0;
$error = null;
$source = array();
if ($is_debug || G5_COLLECT_QUERY) {
if(function_exists('mysqli_error') && G5_MYSQLI_USE) {
$error = array(
'error_code' => mysqli_errno($link),
'error_message' => mysqli_error($link),
);
} else {
$error = array(
'error_code' => mysql_errno($link),
'error_message' => mysql_error($link),
);
}
$stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$found = false;
foreach ($stack as $index => $trace) {
if ($trace['function'] === 'sql_query') {
$found = true;
}
if (isset($stack[$index + 1]) && $stack[$index + 1]['function'] === 'sql_fetch') {
continue;
}
if ($found) {
$trace['file'] = str_replace($_SERVER['DOCUMENT_ROOT'], '', $trace['file']);
$source['file'] = $trace['file'];
$source['line'] = $trace['line'];
$parent = (isset($stack[$index + 1])) ? $stack[$index + 1] : array();
if (isset($parent['function'])) {
if (in_array($trace['function'], array('sql_query', 'sql_fetch')) && (isset($parent['function']) && !in_array($parent['function'], array('sql_fetch', 'include', 'include_once', 'require', 'require_once')))) {
if (isset($parent['class']) && $parent['class']) {
$source['class'] = $parent['class'];
$source['function'] = $parent['function'];
$source['type'] = $parent['type'];
} else {
$source['function'] = $parent['function'];
}
}
}
break;
}
}
$g5_debug['sql'][] = array(
'sql' => $sql,
'result' => $result,
'success' => !!$result,
'source' => $source,
'error_code' => $error['error_code'],
'error_message' => $error['error_message'],
'start_time' => $start_time,
'end_time' => $end_time,
);
}
run_event('sql_query_after', $result, $sql, $start_time, $end_time, $error, $source);
return $result;
}
// 쿼리를 실행한 후 결과값에서 한행을 얻는다.
function sql_fetch($sql, $error=G5_DISPLAY_SQL_ERROR, $link=null)
{
global $g5;
if(!$link)
$link = $g5['connect_db'];
$result = sql_query($sql, $error, $link);
//$row = @sql_fetch_array($result) or die("
$sql
" . mysqli_errno() . " : " . mysqli_error() . "
error file : $_SERVER['SCRIPT_NAME']");
$row = sql_fetch_array($result);
return $row;
}
// 결과값에서 한행 연관배열(이름으로)로 얻는다.
function sql_fetch_array($result)
{
if( ! $result) return array();
if(function_exists('mysqli_fetch_assoc') && G5_MYSQLI_USE)
try {
$row = @mysqli_fetch_assoc($result);
} catch (Exception $e) {
$row = null;
}
else
$row = @mysql_fetch_assoc($result);
return $row;
}
// $result에 대한 메모리(memory)에 있는 내용을 모두 제거한다.
// sql_free_result()는 결과로부터 얻은 질의 값이 커서 많은 메모리를 사용할 염려가 있을 때 사용된다.
// 단, 결과 값은 스크립트(script) 실행부가 종료되면서 메모리에서 자동적으로 지워진다.
function sql_free_result($result)
{
if(!is_resource($result)) return;
if(function_exists('mysqli_free_result') && G5_MYSQLI_USE)
return mysqli_free_result($result);
else
return mysql_free_result($result);
}
/**
* MySQL PASSWORD() 함수로 생성된 비밀번호의 hash 값을 반환
*
* MySQL 버전에 따라 결과가 다르게 나올 수 있음.
* MySQL 8.0.11 버전 이상에서는 오류 발생(PASSWORD 함수가 제거됨)으로 사용할 수 없음.
*
* @deprecated 이 함수는 안전하지 않으므로 사용하지 않는 것을 권장 함
* @see get_encrypt_string() and check_password()
* @param string $value
* @return string
*/
function sql_password($value)
{
// mysql 4.0x 이하 버전에서는 password() 함수의 결과가 16bytes
// mysql 4.1x 이상 버전에서는 password() 함수의 결과가 41bytes
$row = sql_fetch(" SELECT password('{$value}') as pass ");
return $row['pass'];
}
function sql_insert_id($link=null)
{
global $g5;
if(!$link)
$link = $g5['connect_db'];
if(function_exists('mysqli_insert_id') && G5_MYSQLI_USE)
return mysqli_insert_id($link);
else
return mysql_insert_id($link);
}
function sql_num_rows($result)
{
if(function_exists('mysqli_num_rows') && G5_MYSQLI_USE)
return mysqli_num_rows($result);
else
return mysql_num_rows($result);
}
function sql_field_names($table, $link=null)
{
global $g5;
if(!$link)
$link = $g5['connect_db'];
$columns = array();
$sql = " select * from `$table` limit 1 ";
$result = sql_query($sql, $link);
if(function_exists('mysqli_fetch_field') && G5_MYSQLI_USE) {
while($field = mysqli_fetch_field($result)) {
$columns[] = $field->name;
}
} else {
$i = 0;
$cnt = mysql_num_fields($result);
while($i < $cnt) {
$field = mysql_fetch_field($result, $i);
$columns[] = $field->name;
$i++;
}
}
return $columns;
}
function sql_error_info($link=null)
{
global $g5;
if(!$link)
$link = $g5['connect_db'];
if(function_exists('mysqli_error') && G5_MYSQLI_USE) {
return mysqli_errno($link) . ' : ' . mysqli_error($link);
} else {
return mysql_errno($link) . ' : ' . mysql_error($link);
}
}
// PHPMyAdmin 참고
function get_table_define($table, $crlf="\n")
{
global $g5;
// For MySQL < 3.23.20
$schema_create = 'CREATE TABLE ' . $table . ' (' . $crlf;
$sql = 'SHOW FIELDS FROM ' . $table;
$result = sql_query($sql);
while ($row = sql_fetch_array($result))
{
$schema_create .= ' ' . $row['Field'] . ' ' . $row['Type'];
if (isset($row['Default']) && $row['Default'] != '')
{
$schema_create .= ' DEFAULT \'' . $row['Default'] . '\'';
}
if ($row['Null'] != 'YES')
{
$schema_create .= ' NOT NULL';
}
if ($row['Extra'] != '')
{
$schema_create .= ' ' . $row['Extra'];
}
$schema_create .= ',' . $crlf;
} // end while
sql_free_result($result);
$schema_create = preg_replace('/,' . $crlf . '$/', '', $schema_create);
$sql = 'SHOW KEYS FROM ' . $table;
$result = sql_query($sql);
while ($row = sql_fetch_array($result))
{
$kname = $row['Key_name'];
$comment = (isset($row['Comment'])) ? $row['Comment'] : '';
$sub_part = (isset($row['Sub_part'])) ? $row['Sub_part'] : '';
if ($kname != 'PRIMARY' && $row['Non_unique'] == 0) {
$kname = "UNIQUE|$kname";
}
if ($comment == 'FULLTEXT') {
$kname = 'FULLTEXT|$kname';
}
if (!isset($index[$kname])) {
$index[$kname] = array();
}
if ($sub_part > 1) {
$index[$kname][] = $row['Column_name'] . '(' . $sub_part . ')';
} else {
$index[$kname][] = $row['Column_name'];
}
} // end while
sql_free_result($result);
foreach((array) $index as $x => $columns){
$schema_create .= ',' . $crlf;
if ($x == 'PRIMARY') {
$schema_create .= ' PRIMARY KEY (';
} else if (substr($x, 0, 6) == 'UNIQUE') {
$schema_create .= ' UNIQUE ' . substr($x, 7) . ' (';
} else if (substr($x, 0, 8) == 'FULLTEXT') {
$schema_create .= ' FULLTEXT ' . substr($x, 9) . ' (';
} else {
$schema_create .= ' KEY ' . $x . ' (';
}
$schema_create .= implode(', ', $columns) . ')';
} // end while
$schema_create .= $crlf . ') ENGINE=MyISAM DEFAULT CHARSET=utf8';
return get_db_create_replace($schema_create);
} // end of the 'PMA_getTableDef()' function
// 리퍼러 체크
function referer_check($url='')
{
/*
// 제대로 체크를 하지 못하여 주석 처리함
global $g5;
if (!$url)
$url = G5_URL;
if (!preg_match("/^http['s']?:\/\/".$_SERVER['HTTP_HOST']."/", $_SERVER['HTTP_REFERER']))
alert("제대로 된 접근이 아닌것 같습니다.", $url);
*/
}
// 한글 요일
function get_yoil($date, $full=0)
{
$arr_yoil = array ('일', '월', '화', '수', '목', '금', '토');
$yoil = date("w", strtotime($date));
$str = $arr_yoil[$yoil];
if ($full) {
$str .= '요일';
}
return $str;
}
// 날짜를 select 박스 형식으로 얻는다
function date_select($date, $name='')
{
global $g5;
$s = '';
if (substr($date, 0, 4) == "0000") {
$date = G5_TIME_YMDHIS;
}
preg_match("/([0-9]{4})-([0-9]{2})-([0-9]{2})/", $date, $m);
// 년
$s .= "