<?php
/**
 * Copyright (C) 2009  Honghao Geng (genghonghao@gmail.com)
 * $Id: image.php 246 2009-10-09 16:33:27Z genghonghao $
 */

define('IN_ADMIN', TRUE);

require_once dirname(__FILE__) . '/includes/init.php';
require_once GEN_ROOT . '/languages/' . $_CONF['lang'] . '/admin/content.lang.php';
$image = new image();

// 验证用户是否登录
if (false === verify_user()) {;
    header("Location: ../login.php");
}

$tpl->assign('lang', $lang);

$action = isset($_REQUEST['act']) ? $_REQUEST['act'] : 'image_list';

// 获得当前页面的完整URL
$current_page_url = $base_url . '/' . $current_file . '?' . get_uri_param_string();

$tpl->assign('current_page_url', $current_page_url);
$tpl->assign('base_root_url', $base_root_url);

$default_dir_pic = array('yes'=>"images/folder.png", 'no'=>"images/folderEmpty.png");


// 图片列表首页
if ($action == 'image_list') {

// 如果是从写博客页面跳过来的（即选择图片的）
    if (isset($_REQUEST['func']) &&  trim($_REQUEST['func']) == 'set_content') {
        $tpl->assign('select_func', trim($_REQUEST['func']));
    }

    // 添加新目录
    if (isset($_REQUEST['sub_add_dir']) && !empty($_REQUEST['sub_add_dir'])) {
        $dir_name = isset($_REQUEST['text_dir_name']) ? trim($_REQUEST['text_dir_name']) : null;
        $user_id = $_SESSION['user']['userid'];
        $username = $_SESSION['user']['username'];
        $default_pic = $default_dir_pic['no'];
        if (!empty($dir_name)) {
            $query = $db->query("INSERT INTO " . $db->get_table(TB_IMAGE_CATEGORY) . "
                (`cate_id`, `admin_user_id`, `admin_user_name`, `is_default_dir`, `cate_name`, `default_pic`, `image_total`)
                VALUES(NULL, '$user_id', '$username', '0', '$dir_name', '$default_pic', '0')");
            if (false !== $query) {
                redirect('Success', $lang['insert_success_text'], $current_page_url);
            } else {
                redirect('Failure', $lang['insert_db_failure'], $current_page_url);
            }
        } else {
            redirect('Failure', $lang['data_not_null'], $current_page_url);
        }
    }
    // 所在位置
    $location_link = array("<a href='content.php'>" . $lang['2_content_manage']['name'] . "</a>",
        "<a href='image.php?act=$action'>" . $lang['6_image_manage']['image_list'] . "</a>"
    );
    // 相关操作
    $location_other = array("<a class='realbutton' href='content.php?act=add_content'>" . $lang['2_content_manage']['add_content'] . "</a>",
        "<a class='realbutton' href='content.php?act=content_list'>" . $lang['2_content_manage']['content_list'] . "</a>"
    );
    // 取出标签数据
    $cate_dir = $db->result("SELECT cate_id, cate_name, default_pic, image_total FROM " . $db->get_table(TB_IMAGE_CATEGORY) . " ORDER BY cate_id ASC");

    $tpl->assign('location_link', $location_link);
    $tpl->assign('location_other', $location_other);
    $tpl->assign('cate_dir', $cate_dir);
    $tpl->display('image_list.html');
}

// 上传图片和图片列表页
if ($action == 'images') {

// 如果是从写博客页面跳过来的（即选择图片的）
    if (isset($_REQUEST['func']) &&  trim($_REQUEST['func']) == 'set_content') {
        $select_func = trim($_REQUEST['func']);
        $tpl->assign('select_func', $select_func);
    }

    $where = isset($_REQUEST['cate_id']) ? " WHERE cate_id='" . intval($_REQUEST['cate_id']) . "'" : '';
    $cate_id = intval($_REQUEST['cate_id']);

    // 取当前目录数据
    $query = $db->query("SELECT cate_name FROM " . $db->get_table(TB_IMAGE_CATEGORY) . $where);
    $cate_dir = $db->fetch_row($query);
    // 上传图片
    if (isset($_REQUEST['sub_upload_file']) && !empty($_REQUEST['sub_upload_file'])) {
    // 如果找不到目录则跳转至目录列表页面
        if (empty($cate_id) || $cate_id == 0) {
            redirect('Failure', $lang['not_find_dir'], 'image.php?act=image_list');
            exit;
        }
        if (isset($_REQUEST['text_upload_one'])) {
            $current_page_url = 'image.php?act=images&cate_id=' . $cate_id;
        }
        // 图片名称
        $img_name = (isset($_REQUEST['text_pic_name']) && !empty($_REQUEST['text_pic_name'])) ? trim($_REQUEST['text_pic_name']) : $lang['default_pic_name'];

        // 如果是安全模式，检查目录是否存在
        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'));
                $tpl->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'));
            $tpl->assign('warning', $warning);
        }

        // 是否处理缩略图
        $proc_thumb = !isset($proc_thumb) ? true : true;

        /* 检查图片：如果有错误，检查尺寸是否超过最大值；否则，检查文件类型 */
        if (isset($_FILES['upfile']['error'])) {
        // 最大上传文件大小
            $php_maxsize = ini_get('upload_max_filesize');
            $htm_maxsize = '2M';

            // 上传的图片
            if ($_FILES['upfile']['error'] == 0) {
                if (!$image->check_img_type($_FILES['upfile']['type'])) {
                    sys_msg($lang['notice_invalid_img'], 1, array(), false);
                }
            }
            elseif ($_FILES['upfile']['error'] == 1) {
                sys_msg(sprintf($lang['upfile_img_too_big'], $php_maxsize), 1, array(), false);
            }
            elseif ($_FILES['upfile']['error'] == 2) {
                sys_msg(sprintf($lang['upfile_img_too_big'], $htm_maxsize), 1, array(), false);
            }

            // 缩略图
            if (isset($_FILES['img_thumb'])) {
                if ($_FILES['img_thumb']['error'] == 0) {
                    if (!$image->check_img_type($_FILES['img_thumb']['type'])) {
                        sys_msg($lang['invalid_goods_thumb'], 1, array(), false);
                    }
                }
                elseif ($_FILES['img_thumb']['error'] == 1) {
                    sys_msg(sprintf($lang['upfile_thumb_too_big'], $php_maxsize), 1, array(), false);
                }
                elseif ($_FILES['img_thumb']['error'] == 2) {
                    sys_msg(sprintf($lang['upfile_thumb_too_big'], $htm_maxsize), 1, array(), false);
                }
            }

            // 如果上传了图片，相应处理
            if ($_FILES['upfile']['tmp_name'] != '' && $_FILES['upfile']['tmp_name'] != 'none') {
                $original_img   = $image->upload_image($_FILES['upfile']); // 原始图片
                if ($original_img === false) {
                    sys_msg($image->error_msg(), 1, array(), false);
                }
                $upfile      = $original_img;   // 图片

                // 如果系统支持GD，缩放图片
                if ($proc_thumb && $image->gd_version() > 0 && $image->check_img_function($_FILES['upfile']['type'])) {
                // 生成小的缩略图
                    if ($theme_small['width'] != 0 || $theme_small['height'] != 0) {
                        $small_file = $image->make_thumb('../'. $upfile , $theme_small['width'],  $theme_small['height']);
                        if ($small_file === false) {
                            sys_msg($image->error_msg(), 1, array(), false);
                        }
                    }
                    // 生成中等大小的图片
                    if ($theme_middle['width'] != 0 || $theme_middle['height'] != 0) {
                        $middle_file = $image->make_thumb('../'. $upfile , $theme_middle['width'],  $theme_middle['height']);
                        if ($middle_file === false) {
                            sys_msg($image->error_msg(), 1, array(), false);
                        }
                    }
                }
            }

            $cur_time = time();

            $sql = "INSERT INTO " . $db->get_table(TB_IMAGE) .
                "(`pic_id`,`pic_name`, `small_pic`, `middle_pic`, `original_pic`, `pic_cate_id`, `pic_cate_name`,  `upload_time`)" .
                " VALUE(NULL, '$img_name', '$small_file', '$middle_file', '$upfile', '$cate_id', '{$cate_dir[0]}', $cur_time)";
            // 数片写入数据库中
            $query = $db->query($sql);
            // 更新当前目录中的图片数量
            $db->query("UPDATE " . $db->get_table(TB_IMAGE_CATEGORY) . " SET image_total=image_total+1, default_pic='{$default_dir_pic['yes']}' WHERE cate_id = '$cate_id'");
            if (false !== $query) {
                redirect('Success', $lang['pic_upload_success'], $current_page_url);
            } else {
                redirect('Failure', $lang['pic_upload_failure'], $current_page_url);
            }
        }
    }

    // 删除图片
    if (isset($_REQUEST['mod']) && $_REQUEST['mod'] == 'del') {
        $pic_id = intval($_REQUEST['pic_id']);
        del_cur_pic($pic_id);
        $current_page_url = str_replace("&mod=del&pic_id=$pic_id",'', $current_page_url);
        redirect('Failure', $lang['pic_delete_success'], $current_page_url);
    }

    // 所在位置
    $location_link = array("<a href='content.php'>" . $lang['2_content_manage']['name'] . "</a>",
        "<a href='image.php?act=image_add'>" . $lang['6_image_manage']['image_list'] . "</a>"
    );

    // 相关操作
    if (isset($select_func)) {
         $location_other = array("<a class='realbutton' href='image.php?act=image_list&func=$select_func'>" . $lang['6_image_manage']['image_list'] . "</a>");
    } else {
        $location_other = array(
            "<a class='realbutton' href='image.php?act=image_list'>" . $lang['6_image_manage']['image_list'] . "</a>",
            "<a class='realbutton' href='content.php?act=add_content'>" . $lang['2_content_manage']['add_content'] . "</a>",
            "<a class='realbutton' href='content.php?act=content_list'>" . $lang['2_content_manage']['content_list'] . "</a>"
        );
    }

    // 分页数据
    $temp = $db->result("SELECT COUNT(*) AS num FROM " . $db->get_table(TB_IMAGE) . " WHERE pic_cate_id='$cate_id'");
    $total = $temp[0]['num'];
    $perpage = 15;
    if (!isset($_REQUEST['page']) || is_int($_REQUEST['page'])) {
        $p = 0;
    }
    else {
        $p = ((int)$_REQUEST['page'] - 1) * $perpage;
        if ($p >= $total) {
            $p = 0;
        }
    }

    // 分页
    require GEN_ROOT . 'includes/page.class.php';
    $page = new page(array('total'=>$total,'perpage'=>$perpage));
    $tpl->assign('page', $page->show(4));

    // 取出当前分类下的图片
    $pic_list = $db->result("SELECT * FROM " . $db->get_table(TB_IMAGE) . " WHERE pic_cate_id='$cate_id' ORDER BY pic_id ASC LIMIT $p, $perpage");

    $tpl->assign('location_link', $location_link);
    $tpl->assign('location_other', $location_other);
    $tpl->assign('cate_dir', $cate_dir[0]);
    $tpl->assign('pic_list', $pic_list);
    $tpl->display('images.html');
}

// 上传图片
elseif ($action == 'image_add') {

// 所在位置
    $location_link = array("<a href='content.php'>" . $lang['2_content_manage']['name'] . "</a>",
        "<a href='image.php?act=$action'>" . $lang['6_image_manage']['image_list'] . "</a>"
    );
    // 相关操作
    $location_other = array(
        "<a class='realbutton' href='image.php?act=image_list'>" . $lang['6_image_manage']['image_list'] . "</a>",
        "<a class='realbutton' href='content.php?act=add_content'>" . $lang['2_content_manage']['add_content'] . "</a>",
        "<a class='realbutton' href='content.php?act=content_list'>" . $lang['2_content_manage']['content_list'] . "</a>"
    );

    // 取出所有图片目录数据
    $img_cate_list = $db->result("SELECT cate_name, cate_id FROM " . $db->get_table(TB_IMAGE_CATEGORY));

    $tpl->assign('location_link', $location_link);
    $tpl->assign('location_other', $location_other);
    $tpl->assign('img_cate_list', $img_cate_list);
    $tpl->display('image_add.html');
}

// 删除图片
function del_cur_pic($pic_id) {
    global $db, $default_dir_pic;
    // 取出图片的路径
    $pic_info = $db->result("SELECT * FROM " . $db->get_table(TB_IMAGE) . " WHERE pic_id='$pic_id'");

    if (isset($pic_info[0])) {
    // 删除目录中的图片
        @unlink(GEN_ROOT . $pic_info[0]['small_pic']);
        @unlink(GEN_ROOT . $pic_info[0]['middle_pic']);
        @unlink(GEN_ROOT . $pic_info[0]['original_pic']);

        // 更改数据库中当前目录中的图片个数
        $db->query("UPDATE " . $db->get_table(TB_IMAGE_CATEGORY) . " SET image_total=image_total-1 WHERE cate_id = '{$pic_info[0]['pic_cate_id']}'");

        // 检察当前数片所在分类中是否还有图片
        $cate = $db->result("SELECT image_total FROM " . $db->get_table(TB_IMAGE_CATEGORY) . " WHERE cate_id='{$pic_info[0]['pic_cate_id']}'");

        // 如果当前图片所属的目录中已经没有了图片，则更将当前目录的默认图标
        if ($cate[0]['image_total'] < 1) {
            $db->query("UPDATE " . $db->get_table(TB_IMAGE_CATEGORY) . " SET default_pic='{$default_dir_pic['no']}' WHERE cate_id = '{$pic_info[0]['pic_cate_id']}'");
        }

    }

    // 删除数据库中的当前图片数据
    $db->query("DELETE FROM " . $db->get_table(TB_IMAGE) . " WHERE pic_id='$pic_id'");
}
?>