<?php
/**
 *  网站sitemap
 *
 * 支持栏目类型
 * 4 = 企业博客栏目
 * 7 = 论坛栏目
 * 10 = 商品栏目
 * 11 = 多级文章栏目
 * 12 = 单页栏目
 * 14 = 服务频道
 * 15 = 一级文章栏目(原多项目栏目)
 * 18 = 图片栏目
 * 19 = 招聘栏目
 * 31 = 行业百科栏目
 * 32 = 行业知道栏目
 * 36 = 团购栏目
 * 38 = 积分栏目
 * 46 = 会议活动栏目
 * 47 = 公司团队栏目
 * 49 = 场地预定栏目
 * 51 = 视频课程栏目
 * 71 = 限时购栏目
 * 76 = pc空白页栏目
 *
 */

use SelfColumnModel\Evyun\SiteTypeFnColumnModel;
use SelfVendor\WebsiteVersion\WebsiteVersionDb;

include_once("/home/work/www/vip/include/conntent.php");

if (ENVIRONMENT == 'development' && isset($_REQUEST['aaa']) && $_REQUEST['aaa']) {
    ini_set('display_errors', 1);
    error_reporting(E_ALL & ~E_NOTICE);
} else {
    header('Content-Type: text/xml; charset=utf-8');
}

include_once("/home/work/www/vip/include/functions.php");
include_once("/home/work/www/vip/include/360_safe3.php");
include_once("/home/work/www/vip/self_define/include/channel_info.php");
include_once("/home/work/www/vip/Public/RedisClient.php");

$isAiSitemap = 0;
if (strpos($_SERVER['REQUEST_URI'], 'ai-sitemap.xml') !== false) {
    $isAiSitemap = 1;
}

if (!defined('TIME_STAMP')) {
    date_default_timezone_set("PRC");
    $sysTime = $_SERVER['REQUEST_TIME'] ?: time();
    define('TIME_STAMP', $sysTime);
    define('DATE_STR', date('Y-m-d', TIME_STAMP));
    define('TIME_STR', date('Y-m-d H:i:s', TIME_STAMP));
    define('TIME_HIS', date('H:i:s', TIME_STAMP));
    define('TIME_HI', date('H:i', TIME_STAMP));
    define('TIME_H', date('H', TIME_STAMP));
    define('TIME_I', date('i', TIME_STAMP));
    define('TIME_S', date('s', TIME_STAMP));
    define('SYS_MICRO_TIME', microtime());
}

$user_name  = $_REQUEST['username'] ? substr(new_format_mysql_insert($_REQUEST['username']), 0, 20) : '';
$channel_id = $_REQUEST['channel_id'] ? (int)$_REQUEST['channel_id'] : 0;
$host       = new_format_mysql_insert($_SERVER['HTTP_HOST']);

$hostHttpShow = '';

if (!$user_name) {
    $hostInfo = hostQuery(
        11,
        [
            'where'  => " is_del=0 && host='{$host}' ",
            'fields' => ' user_id,is_https ',
        ]
    );

    if ($hostInfo) {
        $userId       = $hostInfo->user_id;
        $hostHttpShow = $hostInfo->is_https ? 'https://' : 'http://';
    }

    if ($userId) {
        $sql       = "select username from website.user where userid={$userId}";
        $user_name = $DB_Ev123->get_var($sql);
    }
}

if (!$user_name) {
    echo '';
    exit();
}

$sql      = "select userid,siteid,is_short_link,update_time from user where userlevel=3 and username='".$user_name."' and is_del=0";
$userInfo = $DB_Ev123->get_row($sql, 'O');
if (!$userInfo) {
    echo '';
    exit();
}

if ($isAiSitemap) {
    $websiteVersionInfo = WebsiteVersionDb::info($userInfo->siteid);
    if (!$websiteVersionInfo) {
        exit();
    }
    if ($websiteVersionInfo['fn_is_geo'] != SiteTypeFnColumnModel::FN_IS_GEO_1) {
        exit();
    }
}

$user_id = $userInfo->userid;
define('IS_SHORT_LINK', $userInfo->is_short_link);
$redisObj = RedisClient::getInstance();

if (!$hostHttpShow) {
    $isHttps = hostQuery(
        12,
        [
            'where' => " is_del=0 && user_id='{$user_id}' ",
            'field' => ' is_https ',
        ]
    );

    $hostHttpShow = $isHttps ? 'https://' : 'http://';
}

$chWhere = '';
if ($channel_id) {
    $chWhere = " && id={$channel_id} ";
}

$sql    = "
            select id,type,url,update_time 
            from ev_user_channel where userid={$user_id} && type in(4,7,10,11,12,14,15,18,19,31,32,36,38,46,47,49,51,71,76) && is_del=0
            {$chWhere}
            order by id desc limit 30";
$chList = $DB_Ev123->get_results($sql);
if (!$chList) {
    echo '';
    exit();
}

$dateTime = date("Y-m-d");



$sitemapChStr  = $sitemapConStr = '';

foreach ($chList as $tmpChInfo) {
    $tmpChId   = $tmpChInfo['id'];
    $tmpChType = $tmpChInfo['type'];

    $tmpChUrl = get_channel_url($user_name, $tmpChType, $tmpChId, $tmpChInfo['url']);
    $tmpChUrl = "{$hostHttpShow}{$host}{$tmpChUrl}";

    $sitemapChStr .= getSitemapXml(
        [
            'loc'      => $tmpChUrl,
            'lastmod'  => $tmpChInfo['update_time'],
            'priority' => '0.9',
        ]
    );

    if (in_array($tmpChType, [12, 76])) {
        continue;
    }

    $conList = getSitemapConList(
        [
            'chInfo'   => $tmpChInfo,
            'userInfo' => $userInfo,
            'redisObj' => $redisObj,
        ]
    );

    if (!$conList) {
        continue;
    }

    foreach ($conList as $tmpConInfo) {
        $tmpConUrl = get_detail_url($user_name, $tmpChType, $tmpChId, $tmpConInfo['id']);
        $tmpConUrl = "{$hostHttpShow}{$host}{$tmpConUrl}";

        $sitemapConStr .= getSitemapXml(
            [
                'loc'     => $tmpConUrl,
                'lastmod' => $tmpConInfo['update_time'],
            ]
        );
    }
}

echo '<?xml version="1.0" encoding="UTF-8" ?>';
$sitemapStr = "<urlset>{$sitemapChStr}{$sitemapConStr}</urlset>";

echo $sitemapStr;
exit();

/**
 * 返回
 *
 * @param  array  $param
 *
 * @return string
 */
function getSitemapXml(array $param)
{
    $loc        = $param['loc'] ?? ''; // 必填,URL 链接地址,长度不得超过 256 字节
    $lastmod    = $param['lastmod'] ?? ''; // 可以不提交该标签,用来指定该链接的最后更新时间
    $changefreq = $param['changefreq'] ?? 'daily'; // 可以不提交该标签,用这个标签告诉此链接可能会出现的更新频率
    $priority   = $param['priority'] ?? '0.8'; // 可以不提交该标签,用来指定此链接相对于其他链接的优先权比值，此值定于 0.0-1.0 之间


    $str = <<<ETO
<url>
    <loc><![CDATA[ {$loc} ]]></loc>
    <lastmod>{$lastmod}</lastmod>
    <changefreq>{$changefreq}</changefreq>
    <priority>{$priority}</priority>
</url>
ETO;

    return $str;
}

/**
 * 获取栏目内容
 *
 * @param  array  $param
 *
 * @return array
 */
function getSitemapConList(array $param)
{
    global $DB_Product, $DB_Ev123, $DB_User_Doc, $DB_Server, $DB_Dom;

    $chInfo    = $param['chInfo'] ?? []; // 栏目信息
    $userInfo  = $param['userInfo'] ?? []; // 用户信息
    $redisObj  = $param['redisObj'] ?? []; // redis 对象

    if (!$chInfo || !$userInfo) {
        return [];
    }

    $userId = $userInfo->userid;
    $chId   = $chInfo['id'];
    $chType = $chInfo['type'];

    $conList         = [];
    $tableList       = [
        "4"  => [
            "user_blog_doc",
            "is_del=0 and user_id=".$userId,
            "DB_Ev123",
        ],
        "7"  => [
            "user_bbs_threads",
            "is_del=0 and user_id=".$userId,
            "DB_Ev123",
        ],
        "10" => [
            "proinfo",
            "infostate!='freeze' and channel_id!='' and  on_line=1 and is_del=0 and userid=".$userId,
            "DB_Product",
        ],
        "11" => [
            "ev_user_doc_content",
            "infostate='publish' and is_del=0 and channel_id=".$chId." and userid=".$userId,
            "DB_User_Doc",
        ],
        "14" => [
            "serverinfo",
            "is_del=0 and user_userid is null and channel_id='".$chId."' and userid=".$userId,
            "DB_Server",
        ],
        "15" => [
            "ev_user_item_doc",
            "is_del=0 and channel_id=".$chId." and user_id=".$userId,
            "DB_Ev123",
        ],
        "18" => [
            "ev_user_pic_index",
            "is_del=0 and channel_id=".$chId." and user_id=".$userId,
            "DB_Ev123",
        ],
        "19" => [
            "job_zhaopin_class",
            "is_del=0 and channel_id=".$chId." and user_id=".$userId,
            "DB_Product",
        ],
        "31" => [
            "user_baike_index",
            "state=1 and is_del=0 and vip_user_id=".$userId,
            "DB_Ev123",
        ],
        "32" => [
            "zhidao",
            "is_del=0 and userid=".$userId,
            "DB_Ev123",
        ],
        "36" => [
            "user_group_info",
            "is_del = 0 and user_id=".$userId,
            "DB_Product",
        ],
        "38" => [
            "integral_product",
            "is_del = 0 and user_id=".$userId,
            "DB_Product",
        ],
        "46" => [
            "meet_info",
            "(delete_time_stamp is null or delete_time_stamp='') and is_del = 0 and user_id=".$userId,
            "DB_Dom",
        ],
        "47" => [
            "person_info",
            "is_del = 0 and delete_time_stamp is null and user_id=".$userId,
            "DB_Dom",
        ],
        "49" => [
            "area_info",
            "is_del = 0 and user_id=".$userId,
            "DB_Dom",
        ],
        "51" => [
            "video_course",
            "is_del=0 and user_id=".$userId,
            "DB_Product",
        ],
        "71" => [
            "time_buy_product",
            "is_del=0 and user_id=".$userId,
            "DB_Product",
        ],
        "76" => [
            "ev_user_channel",
            "is_del=0 and type=76 and userid=".$userId,
            "DB_Ev123",
        ],
    ];
    $redisChTypeList = [10,11,15,]; // 支持缓存的栏目类型

    if (!isset($tableList[$chType])) {
        return $conList;
    }

    $tableName = $tableList[$chType][0];
    $where     = $tableList[$chType][1];
    $DBName    = $tableList[$chType][2];

    if (in_array($chType, [4,7,18,19,31,32,])) {
        $sql = "select id,input_time as update_time from {$tableName} where {$where}";
    } elseif (in_array($chType, $redisChTypeList)) {
        $redisKey  = "sitemap_xml_{$userId}_{$chId}";
        $redisData = $redisObj->get1($redisKey);
        $redisTime = $redisObj->get($redisKey."_time");

        $isQueryDb = ($_REQUEST['refresh'] || !$redisTime || ($redisTime < strtotime($userInfo->update_time))) ? true : false;

        if ($isQueryDb) {
            if ($chType == 10) {
                $sql            = "select s.id as id from proclass as s where is_del != 0 && channel_id={$chId} && userid={$userId} && type=1";
                $classDelIdList = $DB_Product->get_results($sql, 'O');

                $classDelIdWhere = '';
                if ($classDelIdList) {
                    $classDelIds = [];
                    foreach ($classDelIdList as $k => $v) {
                        $classDelIds[] = $v->id;
                    }

                    $classDelIds     = implode(',', $classDelIds);
                    $classDelIdWhere = " && p.bigclassid NOT IN ({$classDelIds}) && c.big_id NOT IN ({$classDelIds}) ";
                }

                $sql = "
                    SELECT 
                      p.pid AS id,
                      p.update_time AS update_time
                    FROM
                      proinfo AS p 
                      INNER JOIN proinfo_relevance_class_".ceil($userId / 500000)." AS c 
                        ON p.pid = c.pro_id && c.user_id={$userId} && c.channel_id={$chId} 
                        AND c.is_del = 0 
                    WHERE p.is_del = 0 && p.userid={$userId} 
                      AND p.infostate != 'freeze' && p.on_line = 1 && (
                        p.user_userid = 0 || (
                          p.user_status = 2 && p.user_userid != 0
                        )
                      ) 
                      {$classDelIdWhere}
                    GROUP BY p.pid 
                    LIMIT 0, 10000 
                ";
            }  else {
                $sql = "select id,input_time as update_time from {$tableName} where {$where} order by id desc limit 10000";
            }

            $conList = ${$DBName}->get_results($sql);

            $redisObj->set1($redisKey, $conList, 24 * 60 * 60);
            $redisObj->set($redisKey."_time", strtotime($userInfo->update_time), 24 * 60 * 60);
        } else {
            $conList = $redisData;
        }
    } elseif ($chType == 14) {
        $sql = "select id,modidate as update_time from {$tableName} where {$where}";
    } elseif ($chType == 11) {
        $sql = "select id,modi_date as update_time from {$tableName} where {$where}";
    } else {
        $sql = "select id,update_time from {$tableName} where {$where}";
    }

    if (!in_array($chType, $redisChTypeList)) {
        $conList = ${$DBName}->get_results("{$sql} order by id desc limit 2000");
    }

    return $conList;
}

