<?php

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
include_once(ROOT_PATH . '/includes/cls_image.php');
$exc = new exchange($ecs->table('portal'), $db, 'id', 'name');
$image = new cls_image($_CFG['bgcolor']);

/*------------------------------------------------------ */
//-- 遊戲列表
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'list')
{
//    admin_priv('games_view');

    /* 模板赋值 */
    $ur_here = $_LANG['01_games_list'];
    $smarty->assign('ur_here', $ur_here);
    $action_link = array('href' => 'portal.php?act=add', 'text' => '加入入口');
    $smarty->assign('action_link',  $action_link);
    $smarty->assign('lang',         $_LANG);

    $portal_list = portal_list();
    $smarty->assign('portal_list',  $portal_list['portal']);
    $smarty->assign('filter',       $portal_list['filter']);
    $smarty->assign('record_count', $portal_list['record_count']);
    $smarty->assign('page_count',   $portal_list['page_count']);
    $smarty->assign('full_page',    1);
    /* 排序标记 */
    $sort_flag  = sort_flag($portal_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    /* 显示商品列表页面 */
    assign_query_info();
    $smarty->display('portal_list.htm');
}

/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    $portal_list = portal_list();

    $smarty->assign('portal_list',  $portal_list['portal']);
    $smarty->assign('filter',       $portal_list['filter']);
    $smarty->assign('record_count', $portal_list['record_count']);
    $smarty->assign('page_count',   $portal_list['page_count']);
    $smarty->assign('full_page',    0);

    /* 排序标记 */
    $sort_flag  = sort_flag($portal_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);


    make_json_result($smarty->fetch('portal_list.htm'), '',
        array('filter' => $portal_list['filter'], 'page_count' => $portal_list['page_count']));
}

/*------------------------------------------------------ */
//-- 添加新商品 编辑商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
{
    include_once(ROOT_PATH . 'includes/fckeditor/fckeditor.php'); // 包含 html editor 类文件

    $is_add = $_REQUEST['act'] == 'add'; // 添加还是编辑的标识
//    admin_priv('games_manage'); // 检查权限

    /* 如果是安全模式，检查目录是否存在 */
    if (ini_get('safe_mode') == 1 && (!file_exists('../' . IMAGE_DIR . '/'.date('Ym')) || !is_dir('../' . IMAGE_DIR . '/'.date('Ym'))))
    {
        if (@!mkdir('../' . IMAGE_DIR . '/'.date('Ym'), 0777))
        {
            $warning = sprintf($_LANG['safe_mode_warning'], '../' . IMAGE_DIR . '/'.date('Ym'));
            $smarty->assign('warning', $warning);
        }
    }

    /* 如果目录存在但不可写，提示用户 */
    elseif (file_exists('../' . IMAGE_DIR . '/'.date('Ym')) && file_mode_info('../' . IMAGE_DIR . '/'.date('Ym')) < 2)
    {
        $warning = sprintf($_LANG['not_writable_warning'], '../' . IMAGE_DIR . '/'.date('Ym'));
        $smarty->assign('warning', $warning);
    }

    /* 取得商品信息 */
    if ($is_add)
    {
        /* 默认值 */
        $last_choose = array(0, 0);
        if (!empty($_COOKIE['ECSCP']['last_choose']))
        {
            $last_choose = explode('|', $_COOKIE['ECSCP']['last_choose']);
        }
        $portal = array(
            'id'      	=> 0,
            'name'    	=> '',
            'domain'    => '',
            'mtitle'    => '',
            'mdesc'     => '',
            'mkeyword'  => '',
        );

        /* 图片列表 */
        $img_list = array();
    }
    else
    {
        /* 商品信息 */
        $sql = "SELECT * FROM " . $ecs->table('portal') . " WHERE id = '$_REQUEST[id]'";
        $portal = $db->getRow($sql);

        if (empty($portal) === true)
        {
            /* 默认值 */
			$portal = array(
				'id'      	=> 0,
				'name'    	=> '',
				'domain'    => '',
				'mtitle'    => '',
				'mdesc'     => '',
				'mkeyword'  => '',
			);
        }
        /* 商品图片路径 */
        if (isset($GLOBALS['shop_id']) && ($GLOBALS['shop_id'] > 10) && !empty($games['original_img']))
        {
            $games['games_img'] = get_image_path($_REQUEST['games_id'], $games['games_img']);
            $games['games_thumb'] = get_image_path($_REQUEST['games_id'], $games['games_thumb'], true);
        }
    }

    /* 创建 html editor */
//    create_html_editor('games_desc', $games['games_desc']);
//    create_html_editor('mobile_desc', $games['mobile_desc'],'FCKeditor2');
	
    /* 模板赋值 */
    $smarty->assign('ur_here', $is_add ? (empty($code) ? '加入入口' : $_LANG['51_virtual_card_add']) : ($_REQUEST['act'] == 'edit' ? '編輯入口' : $_LANG['copy_games']));
    $smarty->assign('action_link', list_link($is_add));
    $smarty->assign('portal', $portal);
    $smarty->assign('form_act', $is_add ? 'insert' : ($_REQUEST['act'] == 'edit' ? 'update' : 'insert'));
    if ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
    {
        $smarty->assign('is_add', true);
    }
    $smarty->assign('lang',         $_LANG);
    $smarty->assign('img_list', $img_list);
    $smarty->assign('gd', gd_version());
    $smarty->assign('thumb_width', $_CFG['thumb_width']);
    $smarty->assign('thumb_height', $_CFG['thumb_height']);
    /* 显示商品信息页面 */
    assign_query_info();
    $smarty->display('portal_info.htm');
}

/*------------------------------------------------------ */
//-- 插入商品 更新商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')
{

    /* 是否处理缩略图 */
//    admin_priv('games_manage'); // 检查权限
	//domain處理
	if($_REQUEST['act'] == 'insert'){
		if(strlen($_REQUEST['domain'])){
			if(preg_match("/".$_CFG['cf_domain']."$/",$_REQUEST['domain']) && $_CFG['cf_domain']!=$_REQUEST['domain']){ 
				$sub_domain=str_replace($_CFG['cf_domain'],'',$_REQUEST['domain']);
				if(strlen($sub_domain)>0){
					include_once(ROOT_PATH . 'admin/includes/cls_cloudflare.php');
					$cf_obj = new cloudflare;
					$ad_ret=$cf_obj->add_domain(trim($sub_domain));
					if(!$ad_ret){
						sys_msg('網域自動新增失敗,請重新操作',1, array(), false);			
					}else{
						$cf_iden=$ad_ret;
					}
				}
			}	
		}else{
			exit;
		}
	}

	if(!strlen($_REQUEST['name'])){
		sys_msg('入口名稱', 1, array(), false);
		exit;
	}

	if (isset($_FILES['logo']['error'])) // php 4.2 版本才支持 error
    {
        // 最大上传文件大小
        $php_maxsize = ini_get('upload_max_filesize');
        $htm_maxsize = '20M';

        // 商品图片
        if ($_FILES['logo']['error'] == 0)
        {
            if (!$image->check_img_type($_FILES['logo']['type']))
            {
                sys_msg($_LANG['invalid_games_img'], 1, array(), false);
            }
        }
        elseif ($_FILES['logo']['error'] == 1)
        {
            sys_msg(sprintf($_LANG['games_img_too_big'], $php_maxsize), 1, array(), false);
        }
        elseif ($_FILES['logo']['error'] == 2)
        {
            sys_msg(sprintf($_LANG['games_img_too_big'], $htm_maxsize), 1, array(), false);
        }
    }
    /* 4.1版本 */
    else
    {
        // 商品图片
        if ($_FILES['logo']['tmp_name'] != 'none')
        {
            if (!$image->check_img_type($_FILES['logo']['type']))
            {

                sys_msg($_LANG['invalid_games_img'], 1, array(), false);
            }
        }
    }

	if (isset($_FILES['slogo']['error'])) // php 4.2 版本才支持 error
    {
        // 最大上传文件大小
        $php_maxsize = ini_get('upload_max_filesize');
        $htm_maxsize = '20M';

        // 商品图片
        if ($_FILES['slogo']['error'] == 0)
        {
            if (!$image->check_img_type($_FILES['slogo']['type']))
            {
                sys_msg($_LANG['invalid_games_img'], 1, array(), false);
            }
        }
        elseif ($_FILES['slogo']['error'] == 1)
        {
            sys_msg(sprintf($_LANG['games_img_too_big'], $php_maxsize), 1, array(), false);
        }
        elseif ($_FILES['slogo']['error'] == 2)
        {
            sys_msg(sprintf($_LANG['games_img_too_big'], $htm_maxsize), 1, array(), false);
        }
    }
    /* 4.1版本 */
    else
    {
        // 商品图片
        if ($_FILES['slogo']['tmp_name'] != 'none')
        {
            if (!$image->check_img_type($_FILES['slogo']['type']))
            {

                sys_msg($_LANG['invalid_games_img'], 1, array(), false);
            }
        }
    }

    /* 插入还是更新的标识 */
    $is_insert = $_REQUEST['act'] == 'insert';

    /* 处理商品图片 */
    $logo        		= '';  // 初始化商品图片
    $logo_thumb      	= '';  // 初始化商品缩略图
    $original_img     	= '';  // 初始化原始图片
    $old_original_img 	= '';  // 初始化原始图片旧图

    // 如果上传了商品图片，相应处理
    if (($_FILES['logo']['tmp_name'] != '' && $_FILES['logo']['tmp_name'] != 'none'))
    {
        if ($_REQUEST['id'] > 0)
        {
            /* 删除原来的图片文件 */
            $sql = "SELECT logo " .
                    " FROM " . $ecs->table('portal') .
                    " WHERE id = '$_REQUEST[id]'";
            $row = $db->getRow($sql);
            if ($row['logo'] != '' && is_file('../' . $row['logo']))
            {
                @unlink('../' . $row['logo']);
            }
            /* 清除原来商品图片 */
            if ($proc_thumb === false)
            {
                get_image_path($_REQUEST[id], $row['logo'], false, 'portal', true);
            }
        }

        $original_img   = $image->upload_image($_FILES['logo']); // 原始图片
        if ($original_img === false)
        {
            sys_msg($image->error_msg(), 1, array(), false);
        }
        $logo      = $original_img;   // 商品图片


        // 如果系统支持GD，缩放商品图片，且给商品图片和相册图片加水印
/*        if ($proc_thumb && $image->gd_version() > 0 && $image->check_img_function($_FILES['games_img']['type']) || $is_url_games_img)
        {

            if (empty($is_url_games_img))
            {
                // 如果设置大小不为0，缩放图片
                if ($_CFG['image_width'] != 0 || $_CFG['image_height'] != 0)
                {
                    $games_img = $image->make_thumb('../'. $games_img , $GLOBALS['_CFG']['image_width'],  $GLOBALS['_CFG']['image_height']);
                    if ($games_img === false)
                    {
                        sys_msg($image->error_msg(), 1, array(), false);
                    }
                }
            }
        }
*/		
    }
    /* 处理商品图片 */
    $slogo        		= '';  // 初始化商品图片
    $slogo_thumb      	= '';  // 初始化商品缩略图
    $original_simg     	= '';  // 初始化原始图片
    $old_original_simg 	= '';  // 初始化原始图片旧图

    if (($_FILES['slogo']['tmp_name'] != '' && $_FILES['slogo']['tmp_name'] != 'none'))
    {
        if ($_REQUEST['id'] > 0)
        {
            /* 删除原来的图片文件 */
            $sql = "SELECT slogo " .
                    " FROM " . $ecs->table('portal') .
                    " WHERE id = '$_REQUEST[id]'";
            $row = $db->getRow($sql);
            if ($row['slogo'] != '' && is_file('../' . $row['slogo']))
            {
                @unlink('../' . $row['slogo']);
            }
            /* 清除原来商品图片 */
            if ($proc_thumb === false)
            {
                get_image_path($_REQUEST[id], $row['slogo'], false, 'portal', true);
            }
        }

        $original_simg   = $image->upload_image($_FILES['slogo']); // 原始图片
        if ($original_simg === false)
        {
            sys_msg($image->error_msg(), 1, array(), false);
        }
        $slogo      = $original_simg;   // 商品图片
    }


    /* 入库 */
    if ($is_insert)
    {
            $sql = "INSERT INTO " . $ecs->table('portal') . " (name, domain," .
                    "mtitle,mdesc,mkeyword, logo,slogo,type,cf_iden)" .
                "VALUES ('$_POST[name]','$_POST[domain]', " .
                    "'$_POST[mtitle]','$_POST[mdesc]','$_POST[mkeyword]','$logo','$slogo','$_POST[type]','$cf_iden')";
    }
    else
    {
        /* 如果有上传图片，删除原来的商品图 */
        $sql = "SELECT * " .
                    " FROM " . $ecs->table('portal') .
                    " WHERE id = '$_REQUEST[id]'";
        $row = $db->getRow($sql);
		if($row['domain'] != $_POST['domain']){
			/* 更新domain */
			if(strlen($_POST['domain'])){
				if(preg_match("/".$_CFG['cf_domain']."$/",$_POST['domain']) && $_CFG['cf_domain']!=$_POST['domain']){ 
					$sub_domain=str_replace($_CFG['cf_domain'],'',$_POST['domain']);
					include_once(ROOT_PATH . 'admin/includes/cls_cloudflare.php');
					$cf_obj = new cloudflare;
					$ret=$cf_obj->update_domain($row['cf_iden'],trim($sub_domain));
					if(!$ret){
						sys_msg('網域自動修改失敗,請重新操作',1, array(), false);
					}
				}	
			}
			
		}
//        if ($proc_thumb && $games_img && $row['games_img'] && !games_parse_url($row['games_img']))
//        {
//            @unlink(ROOT_PATH . $row['games_img']);
//            @unlink(ROOT_PATH . $row['original_img']);
//        }

        $sql = "UPDATE " . $ecs->table('portal') . " SET " .
                "name = '$_POST[name]', " .
                "domain = '$_POST[domain]', " .
                "type = '$_POST[type]', " .
                "mtitle = '$_POST[mtitle]', " .
                "mdesc = '$_POST[mdesc]', ";

        /* 如果有上传图片，需要更新数据库 */
        if ($logo)
        {
            $sql .= "logo = '$logo',  ";
        }
        if ($slogo)
        {
            $sql .= "slogo = '$slogo', ";
        }
        $sql .= "mkeyword = '$_POST[mkeyword]' ".
				" WHERE id = '$_REQUEST[id]' LIMIT 1";
    }
    $db->query($sql);

    /* 商品编号 */
    $id = $is_insert ? $db->insert_id() : $_REQUEST['id'];

    /* 记录日志 */
    if ($is_insert)
    {
        admin_log($_POST['name'], 'add', 'portal');
    }
    else
    {
        admin_log($_POST['name'], 'edit', 'portal');
    }
    /* 重新格式化图片名称 */
//    $logo = reformat_image_name('logo', $id, $logo, 'portal');

//    if ($logo !== false)
//    {
//        $db->query("UPDATE " . $ecs->table('portal') . " SET logo = '$logo' WHERE id='$id'");
//    }

    /* 不保留商品原图的时候删除原图 */
//    if ($proc_thumb && !$_CFG['retain_original_img'] && !empty($original_img))
//    {
//        $db->query("UPDATE " . $ecs->table('games') . " SET original_img='' WHERE `games_id`='{$games_id}'");
//        @unlink('../' . $original_img);
//        @unlink('../' . $img);
//    }

    /* 记录上一次选择的分类和品牌 */
//    setcookie('ECSCP[last_choose]', $catgory_id . '|' . $brand_id, gmtime() + 86400);
    /* 清空缓存 */
    clear_cache_files();

    /* 提示页面 */
    $link = array();
    if ($is_insert)
    {
        $link[0] = add_link($code);
    }
    $link[1] = list_link($is_insert);


    //$key_array = array_keys($link);
    for($i=0;$i<count($link);$i++)
    {
       $key_array[]=$i;
    }
    krsort($link);
    $link = array_combine($key_array, $link);

    sys_msg($is_insert ? '新增成功' : '編輯成功', 0, $link);
}

/*------------------------------------------------------ */
//-- 批量操作
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'batch')
{
    $code = '';

    /* 取得要操作的商品编号 */
    $games_id = !empty($_POST['checkboxes']) ? join(',', $_POST['checkboxes']) : 0;

    if (isset($_POST['type']))
    {
        /* 放入回收站 */
        if ($_POST['type'] == 'trash')
        {
            /* 检查权限 */
            admin_priv('remove_back');

            update_games($games_id, 'is_delete', '1');

            /* 记录日志 */
            admin_log('', 'batch_trash', 'games');
        }
        /* 上架 */
        elseif ($_POST['type'] == 'on_sale')
        {
            /* 检查权限 */
            admin_priv('games_manage');
            update_games($games_id, 'is_on_sale', '1');
        }

        /* 下架 */
        elseif ($_POST['type'] == 'not_on_sale')
        {
            /* 检查权限 */
            admin_priv('games_manage');
            update_games($games_id, 'is_on_sale', '0');
        }

        /* 转移到分类 */
        elseif ($_POST['type'] == 'move_to')
        {
            /* 检查权限 */
            admin_priv('games_manage');
            update_games($games_id, 'cat_id', $_POST['target_cat']);
        }
        /* 删除 */
        elseif ($_POST['type'] == 'drop')
        {
            /* 检查权限 */
            admin_priv('remove_back');

            delete_games($games_id);

            /* 记录日志 */
            admin_log('', 'batch_remove', 'games');
        }
    }

    /* 清除缓存 */
    clear_cache_files();

    if ($_POST['type'] == 'drop' || $_POST['type'] == 'restore')
    {
        $link[] = array('href' => 'games.php?act=trash', 'text' => $_LANG['11_games_trash']);
    }
    else
    {
        $link[] = list_link(true);
    }
    sys_msg($_LANG['batch_handle_ok'], 0, $link);
}
/*------------------------------------------------------ */
//-- 显示图片
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'show_image')
{

//        $img_url = $_GET['img_url'];
        $img_url = '../' . $_GET['img_url'];
    $smarty->assign('img_url', $img_url);
    $smarty->display('show_image.htm');
}

/*------------------------------------------------------ */
//-- 修改遊戲名稱
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_games_name')
{
    check_authz_json('games_manage');

    $games_id   = intval($_POST['id']);
    $games_name = json_str_iconv(trim($_POST['val']));

    if ($exc->edit("games_name = '$games_name', last_update=" .gmtime(), $games_id))
    {
        clear_cache_files();
        make_json_result(stripslashes($games_name));
    }
}


/*------------------------------------------------------ */
//-- 修改上架状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_on_sale')
{
    check_authz_json('games_manage');

    $games_id       = intval($_POST['id']);
    $on_sale        = intval($_POST['val']);

    if ($exc->edit("is_on_sale = '$on_sale', last_update=" .gmtime(), $games_id))
    {
        clear_cache_files();
        make_json_result($on_sale);
    }
}

/*------------------------------------------------------ */
//-- 修改維修狀態
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_is_check')
{
    check_authz_json('games_manage');

    $games_id       = intval($_POST['id']);
    $is_check       = intval($_POST['val']);

    if ($exc->edit("is_check = '$is_check', last_update=" .gmtime(), $games_id))
    {
        clear_cache_files();
        make_json_result($is_check);
    }
}

/*------------------------------------------------------ */
//-- 修改排序
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_sort_order')
{
    check_authz_json('games_manage');

    $games_id       = intval($_POST['id']);
    $sort_order     = intval($_POST['val']);

    if ($exc->edit("sort_order = '$sort_order', last_update=" .gmtime(), $games_id))
    {
        clear_cache_files();
        make_json_result($sort_order);
    }
}

elseif ($_REQUEST['act'] == 'remove')
{
    // 检查权限
//    check_authz_json('remove_back');

    // 取得参数
    $id = intval($_REQUEST['id']);
    if ($id <= 0)
    {
        make_json_error('invalid params');
    }

    /* 取得商品信息 */
    $sql = "SELECT * " .
            "FROM " . $ecs->table('portal') .
            " WHERE id = '$id'";
    $portal = $db->getRow($sql);

    if (empty($portal))
    {
        make_json_error('入口不存在');
    }

//    if ($games['is_delete'] != 1)
//    {
//        make_json_error($_LANG['games_not_in_recycle_bin']);
//    }

    /* 删除商品图片和轮播图片 */
    if (!empty($portal['logo']))
    {
        @unlink('../' . $portal['logo']);
    }

    if (!empty($portal['slogo']))
    {
        @unlink('../' . $portal['slogo']);
    }

    /* 删除商品 */
    $exc->drop($id);
	/* 刪除domain */
	if(strlen($portal['domain'])){
		if(preg_match("/".$_CFG['cf_domain']."$/",$portal['domain']) && $_CFG['cf_domain']!=$portal['domain']){ 
			include_once(ROOT_PATH . 'admin/includes/cls_cloudflare.php');
			$cf_obj = new cloudflare;
			$cf_obj->del_domain(trim($portal['cf_iden']));
		}	
	}

    /* 记录日志 */
    admin_log(addslashes($protal['name']), 'remove', 'portal');

    clear_cache_files();
    $url = 'portal.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");

    exit;
}

/*------------------------------------------------------ */
//-- 切换商品类型
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'get_attr')
{
    check_authz_json('games_manage');

    $games_id   = empty($_GET['games_id']) ? 0 : intval($_GET['games_id']);
    $games_type = empty($_GET['games_type']) ? 0 : intval($_GET['games_type']);

    $content    = build_attr_html($games_type, $games_id);

    make_json_result($content);
}

/*------------------------------------------------------ */
//-- 删除图片
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_image')
{
    check_authz_json('games_manage');

    $img_id = empty($_REQUEST['img_id']) ? 0 : intval($_REQUEST['img_id']);

    /* 删除图片文件 */
    $sql = "SELECT img_url, thumb_url, img_original " .
            " FROM " . $GLOBALS['ecs']->table('games_gallery') .
            " WHERE img_id = '$img_id'";
    $row = $GLOBALS['db']->getRow($sql);

    if ($row['img_url'] != '' && is_file('../' . $row['img_url']))
    {
        @unlink('../' . $row['img_url']);
    }
    if ($row['thumb_url'] != '' && is_file('../' . $row['thumb_url']))
    {
        @unlink('../' . $row['thumb_url']);
    }
    if ($row['img_original'] != '' && is_file('../' . $row['img_original']))
    {
        @unlink('../' . $row['img_original']);
    }

    /* 删除数据 */
    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('games_gallery') . " WHERE img_id = '$img_id' LIMIT 1";
    $GLOBALS['db']->query($sql);

    clear_cache_files();
    make_json_result($img_id);
}

/*------------------------------------------------------ */
//-- 搜索商品，仅返回名称及ID
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'get_games_list')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);

    $arr = get_games_list($filters);
    $opt = array();

    foreach ($arr AS $key => $val)
    {
        $opt[] = array('value' => $val['games_id'],
                        'text' => $val['games_name'],
                        'data' => $val['shop_price']);
    }

    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 把商品加入关联
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add_link_games')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    check_authz_json('games_manage');

    $linked_array   = $json->decode($_GET['add_ids']);
    $linked_games   = $json->decode($_GET['JSON']);
    $games_id       = $linked_games[0];
    $is_double      = $linked_games[1] == true ? 0 : 1;

    foreach ($linked_array AS $val)
    {
        if ($is_double)
        {
            /* 双向关联 */
            $sql = "INSERT INTO " . $ecs->table('link_games') . " (games_id, link_games_id, is_double, admin_id) " .
                    "VALUES ('$val', '$games_id', '$is_double', '$_SESSION[admin_id]')";
            $db->query($sql, 'SILENT');
        }

        $sql = "INSERT INTO " . $ecs->table('link_games') . " (games_id, link_games_id, is_double, admin_id) " .
                "VALUES ('$games_id', '$val', '$is_double', '$_SESSION[admin_id]')";
        $db->query($sql, 'SILENT');
    }

    $linked_games   = get_linked_games($games_id);
    $options        = array();

    foreach ($linked_games AS $val)
    {
        $options[] = array('value'  => $val['games_id'],
                        'text'      => $val['games_name'],
                        'data'      => '');
    }

    clear_cache_files();
    make_json_result($options);
}

/*------------------------------------------------------ */
//-- 删除关联商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_link_games')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    check_authz_json('games_manage');

    $drop_games     = $json->decode($_GET['drop_ids']);
    $drop_games_ids = db_create_in($drop_games);
    $linked_games   = $json->decode($_GET['JSON']);
    $games_id       = $linked_games[0];
    $is_signle      = $linked_games[1];

    if (!$is_signle)
    {
        $sql = "DELETE FROM " .$ecs->table('link_games') .
                " WHERE link_games_id = '$games_id' AND games_id " . $drop_games_ids;
    }
    else
    {
        $sql = "UPDATE " .$ecs->table('link_games') . " SET is_double = 0 ".
                " WHERE link_games_id = '$games_id' AND games_id " . $drop_games_ids;
    }
    if ($games_id == 0)
    {
        $sql .= " AND admin_id = '$_SESSION[admin_id]'";
    }
    $db->query($sql);

    $sql = "DELETE FROM " .$ecs->table('link_games') .
            " WHERE games_id = '$games_id' AND link_games_id " . $drop_games_ids;
    if ($games_id == 0)
    {
        $sql .= " AND admin_id = '$_SESSION[admin_id]'";
    }
    $db->query($sql);

    $linked_games = get_linked_games($games_id);
    $options      = array();

    foreach ($linked_games AS $val)
    {
        $options[] = array(
                        'value' => $val['games_id'],
                        'text'  => $val['games_name'],
                        'data'  => '');
    }

    clear_cache_files();
    make_json_result($options);
}

/*------------------------------------------------------ */
//-- 货品列表
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'product_list')
{
    admin_priv('games_manage');

    /* 是否存在商品id */
    if (empty($_GET['games_id']))
    {
        $link[] = array('href' => 'games.php?act=list', 'text' => $_LANG['cannot_found_games']);
        sys_msg($_LANG['cannot_found_games'], 1, $link);
    }
    else
    {
        $games_id = intval($_GET['games_id']);
    }

    /* 取出商品信息 */
    $sql = "SELECT games_name, games_type, shop_price FROM " . $ecs->table('games') . " WHERE games_id = '$games_id'";
    $games = $db->getRow($sql);
    if (empty($games))
    {
        $link[] = array('href' => 'games.php?act=list', 'text' => $_LANG['01_games_list']);
        sys_msg($_LANG['cannot_found_games'], 1, $link);
    }
    $smarty->assign('sn', sprintf($_LANG['good_games_sn'], $games['games_sn']));
    $smarty->assign('games_name', sprintf($_LANG['products_title'], $games['games_name']));


    /* 获取商品规格列表 */
    $attribute = get_games_specifications_list($games_id);
    if (empty($attribute))
    {
        $link[] = array('href' => 'games.php?act=edit&games_id=' . $games_id, 'text' => $_LANG['edit_games']);
        sys_msg($_LANG['not_exist_games_attr'], 1, $link);
    }
    foreach ($attribute as $attribute_value)
    {
        //转换成数组
        $_attribute[$attribute_value['attr_id']]['attr_values'][] = $attribute_value['attr_value'];
        $_attribute[$attribute_value['attr_id']]['attr_id'] = $attribute_value['attr_id'];
        $_attribute[$attribute_value['attr_id']]['attr_name'] = $attribute_value['attr_name'];
    }
    $attribute_count = count($_attribute);

    $smarty->assign('attribute_count',          $attribute_count);
    $smarty->assign('attribute_count_3',        ($attribute_count + 3));
    $smarty->assign('attribute',                $_attribute);
    $smarty->assign('product_sn',               $games['games_sn'] . '_');
    $smarty->assign('product_number',           $_CFG['default_storage']);

    /* 取商品的货品 */
    $product = product_list($games_id, '');

    $smarty->assign('ur_here',      $_LANG['18_product_list']);
    $smarty->assign('action_link',  array('href' => 'games.php?act=list', 'text' => $_LANG['01_games_list']));
    $smarty->assign('product_list', $product['product']);
    $smarty->assign('product_null', empty($product['product']) ? 0 : 1);
    $smarty->assign('use_storage',  empty($_CFG['use_storage']) ? 0 : 1);
    $smarty->assign('games_id',     $games_id);
    $smarty->assign('filter',       $product['filter']);
    $smarty->assign('full_page',    1);

    /* 显示商品列表页面 */
    assign_query_info();

    $smarty->display('product_info.htm');
}

/*------------------------------------------------------ */
//-- 货品排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'product_query')
{
    /* 是否存在商品id */
    if (empty($_REQUEST['games_id']))
    {
        make_json_error($_LANG['sys']['wrong'] . $_LANG['cannot_found_games']);
    }
    else
    {
        $games_id = intval($_REQUEST['games_id']);
    }

    /* 取出商品信息 */
    $sql = "SELECT games_sn, games_name, games_type, shop_price FROM " . $ecs->table('games') . " WHERE games_id = '$games_id'";
    $games = $db->getRow($sql);
    if (empty($games))
    {
        make_json_error($_LANG['sys']['wrong'] . $_LANG['cannot_found_games']);
    }
    $smarty->assign('sn', sprintf($_LANG['good_games_sn'], $games['games_sn']));
    $smarty->assign('price', sprintf($_LANG['good_shop_price'], $games['shop_price']));
    $smarty->assign('games_name', sprintf($_LANG['products_title'], $games['games_name']));
    $smarty->assign('games_sn', sprintf($_LANG['products_title_2'], $games['games_sn']));


    /* 获取商品规格列表 */
    $attribute = get_games_specifications_list($games_id);
    if (empty($attribute))
    {
        make_json_error($_LANG['sys']['wrong'] . $_LANG['cannot_found_games']);
    }
    foreach ($attribute as $attribute_value)
    {
        //转换成数组
        $_attribute[$attribute_value['attr_id']]['attr_values'][] = $attribute_value['attr_value'];
        $_attribute[$attribute_value['attr_id']]['attr_id'] = $attribute_value['attr_id'];
        $_attribute[$attribute_value['attr_id']]['attr_name'] = $attribute_value['attr_name'];
    }
    $attribute_count = count($_attribute);

    $smarty->assign('attribute_count',          $attribute_count);
    $smarty->assign('attribute',                $_attribute);
    $smarty->assign('attribute_count_3',        ($attribute_count + 3));
    $smarty->assign('product_sn',               $games['games_sn'] . '_');
    $smarty->assign('product_number',           $_CFG['default_storage']);

    /* 取商品的货品 */
    $product = product_list($games_id, '');

    $smarty->assign('ur_here', $_LANG['18_product_list']);
    $smarty->assign('action_link', array('href' => 'games.php?act=list', 'text' => $_LANG['01_games_list']));
    $smarty->assign('product_list',  $product['product']);
    $smarty->assign('use_storage',  empty($_CFG['use_storage']) ? 0 : 1);
    $smarty->assign('games_id',    $games_id);
    $smarty->assign('filter',       $product['filter']);

    /* 排序标记 */
    $sort_flag  = sort_flag($product['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('product_info.htm'), '',
        array('filter' => $product['filter'], 'page_count' => $product['page_count']));
}

/*------------------------------------------------------ */
//-- 货品删除
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'product_remove')
{
    /* 检查权限 */
    check_authz_json('remove_back');

    /* 是否存在商品id */
    if (empty($_REQUEST['id']))
    {
        make_json_error($_LANG['product_id_null']);
    }
    else
    {
        $product_id = intval($_REQUEST['id']);
    }

    /* 货品库存 */
    $product = get_product_info($product_id, 'product_number, games_id');

    /* 删除货品 */
    $sql = "DELETE FROM " . $ecs->table('products') . " WHERE product_id = '$product_id'";
    $result = $db->query($sql);
    if ($result)
    {
        /* 修改商品库存 */
        if (update_games_stock($product['games_id'], $product_number - $product['product_number']))
        {
            //记录日志
            admin_log('', 'update', 'games');
        }

        //记录日志
        admin_log('', 'trash', 'products');

        $url = 'games.php?act=product_query&' . str_replace('act=product_remove', '', $_SERVER['QUERY_STRING']);

        ecs_header("Location: $url\n");
        exit;
    }
}

/*------------------------------------------------------ */
//-- 修改货品价格
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_product_sn')
{
    check_authz_json('games_manage');

    $product_id       = intval($_POST['id']);
    $product_sn       = json_str_iconv(trim($_POST['val']));
    $product_sn       = ($_LANG['n_a'] == $product_sn) ? '' : $product_sn;

    if (check_product_sn_exist($product_sn, $product_id))
    {
        make_json_error($_LANG['sys']['wrong'] . $_LANG['exist_same_product_sn']);
    }

    /* 修改 */
    $sql = "UPDATE " . $ecs->table('products') . " SET product_sn = '$product_sn' WHERE product_id = '$product_id'";
    $result = $db->query($sql);
    if ($result)
    {
        clear_cache_files();
        make_json_result($product_sn);
    }
}

/*------------------------------------------------------ */
//-- 修改货品库存
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_product_number')
{
    check_authz_json('games_manage');

    $product_id       = intval($_POST['id']);
    $product_number       = intval($_POST['val']);

    /* 货品库存 */
    $product = get_product_info($product_id, 'product_number, games_id');

    /* 修改货品库存 */
    $sql = "UPDATE " . $ecs->table('products') . " SET product_number = '$product_number' WHERE product_id = '$product_id'";
    $result = $db->query($sql);
    if ($result)
    {
        /* 修改商品库存 */
        if (update_games_stock($product['games_id'], $product_number - $product['product_number']))
        {
            clear_cache_files();
            make_json_result($product_number);
        }
    }
}

/*------------------------------------------------------ */
//-- 货品添加 执行
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'product_add_execute')
{
    admin_priv('games_manage');

    $product['games_id']        = intval($_POST['games_id']);
    $product['attr']            = $_POST['attr'];
    $product['product_sn']      = $_POST['product_sn'];
    $product['product_number']  = $_POST['product_number'];

    /* 是否存在商品id */
    if (empty($product['games_id']))
    {
        sys_msg($_LANG['sys']['wrong'] . $_LANG['cannot_found_games'], 1, array(), false);
    }

    /* 判断是否为初次添加 */
    $insert = true;
    if (product_number_count($product['games_id']) > 0)
    {
        $insert = false;
    }

    /* 取出商品信息 */
    $sql = "SELECT games_sn, games_name, games_type, shop_price FROM " . $ecs->table('games') . " WHERE games_id = '" . $product['games_id'] . "'";
    $games = $db->getRow($sql);
    if (empty($games))
    {
        sys_msg($_LANG['sys']['wrong'] . $_LANG['cannot_found_games'], 1, array(), false);
    }

    /*  */
    foreach($product['product_sn'] as $key => $value)
    {
        //过滤
        $product['product_number'][$key] = empty($product['product_number'][$key]) ? (empty($_CFG['use_storage']) ? 0 : $_CFG['default_storage']) : trim($product['product_number'][$key]); //库存

        //获取规格在商品属性表中的id
        foreach($product['attr'] as $attr_key => $attr_value)
        {
            /* 检测：如果当前所添加的货品规格存在空值或0 */
            if (empty($attr_value[$key]))
            {
                continue 2;
            }

            $is_spec_list[$attr_key] = 'true';

            $value_price_list[$attr_key] = $attr_value[$key] . chr(9) . ''; //$key，当前

            $id_list[$attr_key] = $attr_key;
        }
        $games_attr_id = handle_games_attr($product['games_id'], $id_list, $is_spec_list, $value_price_list);

        /* 是否为重复规格的货品 */
        $games_attr = sort_games_attr_id_array($games_attr_id);
        $games_attr = implode('|', $games_attr['sort']);
        if (check_games_attr_exist($games_attr, $product['games_id']))
        {
            continue;
            //sys_msg($_LANG['sys']['wrong'] . $_LANG['exist_same_games_attr'], 1, array(), false);
        }
        //货品号不为空
        if (!empty($value))
        {
            /* 检测：货品货号是否在商品表和货品表中重复 */
            if (check_games_sn_exist($value))
            {
                continue;
                //sys_msg($_LANG['sys']['wrong'] . $_LANG['exist_same_games_sn'], 1, array(), false);
            }
            if (check_product_sn_exist($value))
            {
                continue;
                //sys_msg($_LANG['sys']['wrong'] . $_LANG['exist_same_product_sn'], 1, array(), false);
            }
        }

        /* 插入货品表 */
        $sql = "INSERT INTO " . $GLOBALS['ecs']->table('products') . " (games_id, games_attr, product_sn, product_number)  VALUES ('" . $product['games_id'] . "', '$games_attr', '$value', '" . $product['product_number'][$key] . "')";
        if (!$GLOBALS['db']->query($sql))
        {
            continue;
            //sys_msg($_LANG['sys']['wrong'] . $_LANG['cannot_add_products'], 1, array(), false);
        }

        //货品号为空 自动补货品号
        if (empty($value))
        {
            $sql = "UPDATE " . $GLOBALS['ecs']->table('products') . "
                    SET product_sn = '" . $games['games_sn'] . "g_p" . $GLOBALS['db']->insert_id() . "'
                    WHERE product_id = '" . $GLOBALS['db']->insert_id() . "'";
            $GLOBALS['db']->query($sql);
        }

        /* 修改商品表库存 */
        $product_count = product_number_count($product['games_id']);
        if (update_games($product['games_id'], 'games_number', $product_count))
        {
            //记录日志
            admin_log($product['games_id'], 'update', 'games');
        }
    }

    clear_cache_files();

    /* 返回 */
    if ($insert)
    {
         $link[] = array('href' => 'games.php?act=add', 'text' => $_LANG['02_games_add']);
         $link[] = array('href' => 'games.php?act=list', 'text' => $_LANG['01_games_list']);
         $link[] = array('href' => 'games.php?act=product_list&games_id=' . $product['games_id'], 'text' => $_LANG['18_product_list']);
    }
    else
    {
         $link[] = array('href' => 'games.php?act=list&uselastfilter=1', 'text' => $_LANG['01_games_list']);
         $link[] = array('href' => 'games.php?act=edit&games_id=' . $product['games_id'], 'text' => $_LANG['edit_games']);
         $link[] = array('href' => 'games.php?act=product_list&games_id=' . $product['games_id'], 'text' => $_LANG['18_product_list']);
    }
    sys_msg($_LANG['save_products'], 0, $link);
}

/*------------------------------------------------------ */
//-- 货品批量操作
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'batch_product')
{
    /* 定义返回 */
    $link[] = array('href' => 'games.php?act=product_list&games_id=' . $_POST['games_id'], 'text' => $_LANG['item_list']);

    /* 批量操作 - 批量删除 */
    if ($_POST['type'] == 'drop')
    {
        //检查权限
        admin_priv('remove_back');

        //取得要操作的商品编号
        $product_id = !empty($_POST['checkboxes']) ? join(',', $_POST['checkboxes']) : 0;
        $product_bound = db_create_in($product_id);

        //取出货品库存总数
        $sum = 0;
        $games_id = 0;
        $sql = "SELECT product_id, games_id, product_number FROM  " . $GLOBALS['ecs']->table('products') . " WHERE product_id $product_bound";
        $product_array = $GLOBALS['db']->getAll($sql);
        if (!empty($product_array))
        {
            foreach ($product_array as $value)
            {
                $sum += $value['product_number'];
            }
            $games_id = $product_array[0]['games_id'];

            /* 删除货品 */
            $sql = "DELETE FROM " . $ecs->table('products') . " WHERE product_id $product_bound";
            if ($db->query($sql))
            {
                //记录日志
                admin_log('', 'delete', 'products');
            }

            /* 修改商品库存 */
            if (update_games_stock($games_id, -$sum))
            {
                //记录日志
                admin_log('', 'update', 'games');
            }

            /* 返回 */
            sys_msg($_LANG['product_batch_del_success'], 0, $link);
        }
        else
        {
            /* 错误 */
            sys_msg($_LANG['cannot_found_products'], 1, $link);
        }
    }

    /* 返回 */
    sys_msg($_LANG['no_operation'], 1, $link);
}

/**
 * 列表链接
 * @param   bool    $is_add         是否添加（插入）
 * @param   string  $extension_code 虚拟商品扩展代码，实体商品为空
 * @return  array('href' => $href, 'text' => $text)
 */
function list_link($is_add = true)
{
    $href = 'portal.php?act=list';
    if (!$is_add)
    {
        $href .= '&' . list_link_postfix();
    }

    $text = '入口清單';

    return array('href' => $href, 'text' => $text);
}

/**
 * 添加链接
 * @param   string  $extension_code 虚拟商品扩展代码，实体商品为空
 * @return  array('href' => $href, 'text' => $text)
 */
function add_link($extension_code = '')
{
    $href = 'portal.php?act=add';
    $text = '新增入口';

    return array('href' => $href, 'text' => $text);
}

/**
 * 检查图片网址是否合法
 *
 * @param string $url 网址
 *
 * @return boolean
 */
function games_parse_url($url)
{
    $parse_url = @parse_url($url);
    return (!empty($parse_url['scheme']) && !empty($parse_url['host']));
}

/**
 * 保存某商品的优惠价格
 * @param   int     $games_id    商品编号
 * @param   array   $number_list 优惠数量列表
 * @param   array   $price_list  价格列表
 * @return  void
 */
function handle_volume_price($games_id, $number_list, $price_list)
{
    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('volume_price') .
           " WHERE price_type = '1' AND games_id = '$games_id'";
    $GLOBALS['db']->query($sql);


    /* 循环处理每个优惠价格 */
    foreach ($price_list AS $key => $price)
    {
        /* 价格对应的数量上下限 */
        $volume_number = $number_list[$key];

        if (!empty($price))
        {
            $sql = "INSERT INTO " . $GLOBALS['ecs']->table('volume_price') .
                   " (price_type, games_id, volume_number, volume_price) " .
                   "VALUES ('1', '$games_id', '$volume_number', '$price')";
            $GLOBALS['db']->query($sql);
        }
    }
}

/**
 * 修改商品库存
 * @param   string  $games_id   商品编号，可以为多个，用 ',' 隔开
 * @param   string  $value      字段值
 * @return  bool
 */
function update_games_stock($games_id, $value)
{
    if ($games_id)
    {
        /* $res = $games_number - $old_product_number + $product_number; */
        $sql = "UPDATE " . $GLOBALS['ecs']->table('games') . "
                SET games_number = games_number + $value,
                    last_update = '". gmtime() ."'
                WHERE games_id = '$games_id'";
        $result = $GLOBALS['db']->query($sql);

        /* 清除缓存 */
        clear_cache_files();

        return $result;
    }
    else
    {
        return false;
    }
}

function portal_list(){
    $result = get_filter();
    if ($result === false)
    {
        $filter['keyword']          = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        $filter['sort_by']          = empty($_REQUEST['sort_by']) ? 'id' : trim($_REQUEST['sort_by']);
        $filter['sort_order']       = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        /* 关键字 */
        if (!empty($filter['keyword']))
        {
//            $where .= " AND (games_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%')";
        }

        /* 记录总数 */
        $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('portal'). "  WHERE 1 $where";
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);

        /* 分页大小 */
        $filter = page_and_size($filter);

        $sql = "SELECT * " .
                    " FROM " . $GLOBALS['ecs']->table('portal') . "  WHERE 1 $where" .
                    " ORDER BY $filter[sort_by] $filter[sort_order] ".
                    " LIMIT " . $filter['start'] . ",$filter[page_size]";
        $filter['keyword'] = stripslashes($filter['keyword']);
        set_filter($filter, $sql, $param_str);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }

    $row = $GLOBALS['db']->getAll($sql);

    return array('portal' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);	
}

/**
 * 格式化商品图片名称（按目录存储）
 *
 */
function reformat_image_name($type, $id, $source_img, $position='')
{
    $rand_name = gmtime() . sprintf("%03d", mt_rand(1,999));
    $img_ext = substr($source_img, strrpos($source_img, '.'));
    $dir = 'images';
    if (defined('IMAGE_DIR'))
    {
        $dir = IMAGE_DIR;
    }
    $sub_dir = date('Ym', gmtime());
    if (!make_dir(ROOT_PATH.$dir.'/'.$sub_dir))
    {
        return false;
    }
    if (!make_dir(ROOT_PATH.$dir.'/'.$sub_dir.'/source_img'))
    {
        return false;
    }
    if (!make_dir(ROOT_PATH.$dir.'/'.$sub_dir.'/logo_img'))
    {
        return false;
    }
    if (!make_dir(ROOT_PATH.$dir.'/'.$sub_dir.'/thumb_img'))
    {
        return false;
    }
    switch($type)
    {
        case 'logo':
            $img_name = $id . '_G_' . $rand_name;
            break;
        case 'logo_thumb':
            $img_name = $id . '_thumb_G_' . $rand_name;
            break;
        case 'gallery':
            $img_name = $id . '_P_' . $rand_name;
            break;
        case 'gallery_thumb':
            $img_name = $id . '_thumb_P_' . $rand_name;
            break;
    }

    if ($position == 'source')
    {
        if (move_image_file(ROOT_PATH.$source_img, ROOT_PATH.$dir.'/'.$sub_dir.'/source_img/'.$img_name.$img_ext))
        {
            return $dir.'/'.$sub_dir.'/source_img/'.$img_name.$img_ext;
        }
    }
    elseif ($position == 'thumb')
    {
        if (move_image_file(ROOT_PATH.$source_img, ROOT_PATH.$dir.'/'.$sub_dir.'/thumb_img/'.$img_name.$img_ext))
        {
            return $dir.'/'.$sub_dir.'/thumb_img/'.$img_name.$img_ext;
        }
    }
    else
    {
        if (move_image_file(ROOT_PATH.$source_img, ROOT_PATH.$dir.'/'.$sub_dir.'/games_img/'.$img_name.$img_ext))
        {
            return $dir.'/'.$sub_dir.'/logo_img/'.$img_name.$img_ext;
        }
    }
    return false;
}

function move_image_file($source, $dest)
{
    if (@copy($source, $dest))
    {
        @unlink($source);
        return true;
    }
    return false;
}
?>
