<?php
/**
* @author 龙虾 <15108148@qq.com>
* @version 2.0 2020-08-27
* @copyright 睿谷信息 <www.rgxx.com>
*/
namespace app\admin\controller;
use app\common\model\Site;
use app\common\model\Navlist;
use app\common\model\Cmsmodels;
use think\Controller;
use Request;
use Db;

class Sitemap extends Base
{
	protected function initialize()
    {
        parent::initialize();
        if(Request::isPost()) {
        	$ip_arr = explode('.',Request::ip());
			if($ip_arr[0] == '127' || ($ip_arr[0] == '192' && $ip_arr[1] == '168')) $this->error('本地环境不可操作');
        }
    }
	// Sitemap
	public function index()
	{
		if(file_exists("sitemap.xml")) {
			$sitemap = '上次生成日期'.date('Y-m-d H:i:s',filemtime("sitemap.xml"));
		} else {
			$sitemap = '文件不存在';
		}
		if(Request::isPost()) {
			$action = Request::post('action');
			$sitemap = $this->getsitemap();
			if($action == 'getlink') {
                return ['code' => 1, 'msg' => lang('get_success'), 'data' => implode(PHP_EOL, array_column($sitemap,'url'))];
			} else if($action == 'createsitemap') {
				try {
					$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>".PHP_EOL."<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">".PHP_EOL;
	                foreach ($sitemap as $v) {
	                    $xml .= "<url>".PHP_EOL."<loc>".$v['url']."</loc>".PHP_EOL."<priority>0.6</priority>".PHP_EOL."<lastmod>".$v['time']."</lastmod>".PHP_EOL."<changefreq>weekly</changefreq>".PHP_EOL."</url>".PHP_EOL;
	                }
	                $xml .= '</urlset>';
	                $fp = fopen("sitemap.xml","w");
	                fwrite($fp,$xml);
	                fclose($fp);
				} catch (\Exception $e) {
                    $this->error($e->getMessage());
                }
                $this->success('Sitemap.xml生成成功');
			}
		}
		return $this->fetch('',compact('sitemap'));
	}

	private function getsitemap($siteid='')
    {
        $data = [];
        $sitelist = Site::when(!empty($siteid),function($query)use($siteid){
        	$query->whereId($siteid);
        })->with('navlist,navlist.cmsmodels')->append(['url','navlist.url'])->order('isdefault desc,torder asc')->select();
        foreach ($sitelist as $s) {
            $data[] = [
                'title' => $s['title'],
                'url'   => request()->domain().$s['url'],
                'time'  => date('Y-m-d')
                ];
            $navlist = $s['navlist'];
            foreach ($navlist as $n) {
            	if($n['type'] !== 'link') {
            		$data[] = [
                        'title' => $n['name'],
                        'url'   => request()->domain().$n['url'],
                        'time'  => date("Y-m-d",strtotime($n['create_time']))
                        ];
            	}
            	if($n['type'] == 'model') {
            		$class = 'app\\common\\model\\'.$n['cmsmodels']['classname'];
            		$Class = new $class;
            		$content = $Class::whereNavlistId($n['id'])->whereStatus(1)->append(['url'])->select();
            		foreach ($content as $c) {
	                    $data[] = [
	                        'title' => $c['title'],
	                        'url'   => request()->domain().$c['url'],
	                        'time'  => date("Y-m-d",strtotime($c['create_time']))
	                        ];
	                }
            	}
            }
        }
        return $data;
    }

	// 主动推送
	public function tobaidu()
	{
		if(Request::isPost()) {
			$domain = Request::host();
			$token = config('app.seo.baidutoken') ?: $this->error('请配置百度站长平台准入密钥');
			$type = Request::post('type');
			$urls = Request::post('urls');
			switch ($type) {
				case 1:
					$action = 'urls';
					break;
				case 2:
					$action = 'update';
					break;
				case 3:
					$action = 'del';
					break;
			}
			$api = 'http://data.zz.baidu.com/'.$action.'?site='.$domain.'&token='.$token;
			$ch = curl_init();
			$options =  array(
				CURLOPT_URL => $api,
				CURLOPT_POST => true,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => $urls,
				CURLOPT_HTTPHEADER => array('Content-Type: text/plain')
				);
			curl_setopt_array($ch, $options);
			$result = json_decode(curl_exec($ch));
			if(isset($result->error)) {
				return $data = ['code' => 0, 'msg' => $result->message];
			} else {
				return $data = ['code' => 1, 'msg' => '成功推送'.$result->success.'条'];
			}
		}
	}	
}