<?php
/**
 *
 * @version        开发 QQ 3149518909
 * @link           https://www.lol9.cn 六久阁织梦模板网
 *
 */
require_once(dirname(__FILE__)."/../include/common.inc.php");
require_once(DEDEINC.'/archives.func.php');
echo "<title>织梦自动审核V3.5稳定版</title>";
$sql = "SELECT msg,utime,dtime,tonum,info FROM `#@__auto`";
$rows = $dsql->GetOne($sql);
if(!is_array($rows)) tips("配置失败");
/*数据*/
$row=unserialize($rows['msg']);
$log=$row['log'];
$debug=$row['debug'];
$baidu=$row['baidu'];
$htwj=$row['htwj'];
$tagon=$row['tagon'];
$tagauto=$row['tagauto'];
$baiduurl=$row['baiduurl'];
$xiong_push=$row['xiong_push'];
$xiong_day_url=$row['xiong_day_url'];
$xiong_url=$row['xiong_url'];
if($row['wnum']==""||$row['otime']=="") tips("时间间隔，最大编数未填写!");
if($row['start']=="0") tips("自动审核被关闭");
/*时间*/
// var_dump($baidu);die;
$utime=$rows['utime'];
$dtime=$rows['dtime'];
$tonum=$rows['tonum'];
$info=unserialize($rows['info']);
/*现在时间*/
$newtime=time();
$newhour=date('G');

/*时段是否允许*/
if (!array_key_exists($newhour,$row['ktime'])){
tips("审核时段不在范围内",$row['tip']);
}
/*时间间隔是否允许*/
if(($utime-$newtime)>0){
tips("允许".$row['wnum']."编已审".$tonum."编还需".($utime-$newtime)."秒才能运行审核!",$row['tip']);
}else{
/*抗拒第二天重置*/
$newday=strtotime(date("Y-m-d",time()));
$sqlday=strtotime(date("Y-m-d",$dtime));
if($newday!=$sqlday){$query = "UPDATE `#@__auto` SET dtime='$newtime',tonum='0',info=''";
$dsql->ExecuteNoneQuery($query);
tips("时间已重新配置!",$row['tip']);
}
/*更新时间间隔*/
$utime=$newtime+$row['otime'];
$query = "UPDATE `#@__auto` SET utime='$utime'";
$dsql->ExecuteNoneQuery($query);
}
/*编数是否允许*/
if($tonum>=$row['wnum']){
tips("允许".$row['wnum']."编已审".$tonum."编",$row['tip']);
}


/*这里可以检测文章了*/
$istype=join(",",$row['type']);
$arc = $dsql->GetOne("Select * From #@__arctiny  where arcrank='-1' and typeid in($istype) order by id");
if(!is_array($arc)) tips("没有可审核的文章了");
$upquery = "Update `#@__archives` set ismake=1,arcrank =0,pubdate ='$newtime',senddate='$newtime',sortrank='$newtime' where id='$arc[id]';"; 
$upquery1 = "Update `#@__arctiny` set arcrank =0,senddate='$newtime',sortrank='$newtime' where id='$arc[id]';"; 
$rs = $dsql->ExecuteNoneQuery($upquery);
$rs1 = $dsql->ExecuteNoneQuery($upquery1);
if($rs==''&&$rs1=='') {tips("审核中遇到未知错误");}else{
$tonum=$tonum+1;
$utime=$newtime+$row['otime'];
$query = "UPDATE `#@__auto` SET utime='$utime',tonum='$tonum'";
$dsql->ExecuteNoneQuery($query);
}
// ===========================================

if(empty($htwj)) tips("未检测到后台文件，请返回保存即可");	
if(!empty($htwj) && $tagon=="1"){
	if(is_dir(dirname(__FILE__)."/../".$htwj."/taghtml")){
    // print_r($typeids);
    // ================TAG更新======================
    $all_id = array();
    $new_id = array();
    
    $sql="select id,maketime,tag from `#@__tagindex` order by tag desc"; 
    $dsql->Execute('al',$sql);
    while($row=$dsql->GetArray('al')){  
        if ($row['maketime'] == 0) {
            $new_id[] = $row['id'];
        } else {
            $sql="select a.senddate from #@__taglist l left join #@__archives a on l.aid=a.id  where a.arcrank<>-1 and l.tid=".$row['id']."  order by a.senddate desc"; 
            $row2=$dsql->GetOne($sql);
            if ($row2['senddate'] > $row['maketime']) {
                $new_id[] = $row['id'];
            }
        }
        $all_id[] = $row['id'];
    } 

    $all_total = count($all_id);
    $new_total = count($new_id);
    // print_r($new_id);die;
    
    $make_cache_file = DEDEDATA.'/maketag.cache.php';
    file_put_contents($make_cache_file,"<"."?php\r\n"."\$all_ids = '".implode(',',$all_id)."';\r\n"."\$new_ids = '".implode(',',$new_id)."';\r\n");
    // print_r($make_cache_file);die;
    // $fp = fopen($make_cache_file,"wb") or die("你指定的文件名有问题，无法创建文件");
    // flock($fp,3);
    // fwrite($fp,"<"."?php\r\n");
    // fwrite($fp,"\$all_ids = '".implode(',',$all_id)."';\r\n");
    // fwrite($fp,"\$new_ids = '".implode(',',$new_id)."';\r\n");
    // fclose($fp); 



    if(!isset($pageno)) $pageno = 0;
    if(!isset($mkpage)) $mkpage = 1;
    if(!isset($uppage)) $uppage = 0;
    if(empty($maxpagesize)) $maxpagesize = 50;
    
    $tag_basedir = trim($GLOBALS['cfg_tag_basedir'],'/\ ');
    $tag_basedir = empty($tag_basedir) ? 'tag' : $tag_basedir; 

	if(file_exists(dirname(__FILE__)."/../".$htwj."/taghtml/arc.taghtml.class.php")){
	require_once(dirname(__FILE__)."/../".$htwj."/taghtml/arc.taghtml.class.php");
	if($tagauto=="0"){
		$tagidarr=$new_id;
	}else{
		$tagidarr=$all_id;
	}
	// var_dump(!empty($tagidarr));die;
	if(!empty($tagidarr)){
    	foreach ($tagidarr as $k=>$v){
        $lv = new TagListView($v);
        $reurl = $lv->MakeHtml();
        $lv->Close();
        $rec_sql="update #@__tagindex set maketime=".time()." where id=".$v; 
    	$dsql->Execute('rec',$rec_sql);
    	}

	} 
	}
	
	if(file_exists($GLOBALS['cfg_basedir'].$GLOBALS['cfg_templets_dir']."/".$GLOBALS['cfg_df_style']."/tagindex.htm")){
    // tag首页
	$tag_basedir = trim($GLOBALS['cfg_tag_basedir'],'/\ ');
    $tag_basedir = empty($tag_basedir) ? 'tag' : $tag_basedir; 
    CreateDir($GLOBALS['cfg_cmspath'].'/'.$tag_basedir);
    
    $tagFile = DEDEDATA."/../{$tag_basedir}/index.html";
	$fp = fopen($tagFile,"w") or die("你指定的文件名有问题，无法创建文件");
	fclose($fp);	
	
    $pv = new PartView();
	$GLOBALS['_arclistEnv'] = 'index';    
	$pv->SetTemplet($GLOBALS['cfg_basedir'].$GLOBALS['cfg_templets_dir']."/".$GLOBALS['cfg_df_style']."/tagindex.htm");  //打开TAG页模板
	
	// print_r($pv->SaveToHtml($tagFile));die;
    $pv->SaveToHtml($tagFile);
	}
    
    
    
    // tag地图
    $tag_basedir = trim($GLOBALS['cfg_tag_basedir'],'/\ ');
	$tag_basedir = empty($tag_basedir) ? 'tag' : $tag_basedir; 
	$templet_file = $GLOBALS['cfg_basedir'].$GLOBALS['cfg_templets_dir']."/".$GLOBALS['cfg_df_style']."/tagmap.htm";
	 
	if(file_exists($templet_file)){ 
	// $tagMap = DEDEDATA."/../{$tag_basedir}/tags.xml";
	$tagMap = $GLOBALS['cfg_basedir'].$GLOBALS['cfg_cmspath'].'/tag.xml';
	// print_r();die;
	$pv = new PartView();
	$GLOBALS['_arclistEnv'] = 'index';
	$pv->SetTemplet($templet_file);
	$pv->SaveToHtml($_SERVER['DOCUMENT_ROOT']."/tag.xml");
    }
}
}



// ===============================================
/*生成文章*/
$artUrl = MakeArt($arc[id], TRUE);
global $cfg_multi_site,$cfg_basehost; 
$cfg_domain = $cfg_multi_site == 'N' ? $cfg_basehost : ''; 
if(!empty($artUrl)){
$urls[]=$cfg_domain.$artUrl;
	// 百度推送
	if($baidu=="1" && !empty($baiduurl)){
			echo baidu_put("tui","",$baiduurl,$urls)."<br>";
	}
// 熊掌号推送
	if($xiong_push=="1" && !empty($urls)){
		// 天级推送
		if(!empty($xiong_day_url)){
			echo baidu_put("xiong","天级",$xiong_day_url,$urls)."<br>";
		}
		
		// 周级推送
		if(!empty($xiong_url)){
			echo baidu_put("xiong","周级",$xiong_url,$urls)."<br>";
		}
		
	
	}
}


/*生成栏目*/
$typediarr = array();
array_push($typediarr,$arc['typeid']);
$row3 = $dsql->GetOne("Select reid,topid From `#@__arctype` where id=".$arc['typeid']);
if(!in_array($row3['reid'],$typediarr) and $row3['reid']!=0) array_push($typediarr,$row3['reid']);
if(!in_array($row3['topid'],$typediarr) and $row3['topid']!=0) array_push($typediarr,$row3['topid']);
  require_once(DEDEDATA."/cache/inc_catalog_base.inc");
  require_once(DEDEINC."/channelunit.func.php");
  require_once(DEDEINC."/arc.listview.class.php");
$shlisthtml=$row['htmlnum']?$$row['htmlnum']:2;
  foreach($typediarr as $typeid)
	{
	    $lv = new ListView($typeid);
		$reurl = $lv->MakeHtml(1,$shlisthtml);
	}
/*更新首页*/
$index=index_do();
if($index){
if($log=="1"){
$info[]=$artUrl;
$infod=serialize($info);
$query = "UPDATE `#@__auto` SET `info`='$infod'";
$dsql->ExecuteNoneQuery($query);
}
tips("\n审核成功:".$artUrl.$result,$row['tip']);
}

function MakeArt($aid, $ismakesign=FALSE)
{
    global $cfg_makeindex,$cfg_basedir,$cfg_templets_dir,$cfg_df_style;
    include_once(DEDEINC.'/arc.archives.class.php');
    if($ismakesign)
    {
        $envs['makesign'] = 'yes';
    }
    $arc = new Archives($aid);
    $reurl = $arc->MakeHtml();
    if(isset($typeid))
    {
        $preRow =  $arc->dsql->GetOne("SELECT id FROM `#@__arctiny` WHERE id<$aid AND arcrank>-1 AND typeid='$typeid' order by id desc");
        $nextRow = $arc->dsql->GetOne("SELECT id FROM `#@__arctiny` WHERE id>$aid AND arcrank>-1 AND typeid='$typeid' order by id asc");
        if(is_array($preRow))
        {
            $arc = new Archives($preRow['id']);
            $arc->MakeHtml();
        }
        if(is_array($nextRow))
        {
            $arc = new Archives($nextRow['id']);
            $arc->MakeHtml();
        }
    }
    return $reurl;
}
function baidu_put($type,$name='',$api,$urls){
$ch = curl_init();
$options =  array(
    CURLOPT_URL => $api,
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS => implode("\n", $urls),
    CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result, true);

if($type=="xiong"){
	if(isset($result['error'])){
	return '推送失败，错误码：'.$result['error'].' message：'.$result['message'];
	}else{
	$not_same_site = isset($result['not_same_site'][0]) ? " <font style='color:#f00;'>推送链接与熊掌绑定站点不一致</font> " : "";
	$not_valid = isset($result['not_valid'][0]) ? " <font style='color:#f00;'>推送链接不合法</font> " : "";
	return $not_same_site . $not_valid . $name .'熊掌主动推送成功 '.$result['success_batch'].$result['success_realtime'].' 条！当天剩余 '.$result['remain_batch'].$result['remain_realtime'].' 条可推送！'.$artlist;
	}
}
if($type=="tui"){
	if(isset($result['success'])){
	$not_same_site = isset($result['not_same_site'][0]) ? " <font style='color:#f00;'>推送链接与百度绑定站点不一致</font> " : "";
	$not_valid = isset($result['not_valid'][0]) ? " <font style='color:#f00;'>推送链接不合法</font> " : "";
	return $not_same_site . $not_valid . '百度主动推送成功 '.$result['success'].' 条！当天剩余 '.$result['remain'].' 条可推送！'.$artlist;
	}else{
	return '百度主动推送失败，错误码：'.$result['error'].'<a href="https://ziyuan.baidu.com/college/courseinfo?id=267&page=2#h2_article_title12" target="_blank">详情</a>';
	}	
}

}
function index_do(){
require_once(DEDEINC."/arc.partview.class.php");
global $dsql,$cfg_basedir,$cfg_templets_dir;
$envs = $_sys_globals = array(); 
$envs['aid'] = 0; 
$indexs = $dsql->GetOne("select * from`#@__homepageset`");
$templet = str_replace("{style}", $cfg_df_style, $indexs['templet']); 
$homeFile = str_replace("../", "",$indexs['position']);
$homeFile=$cfg_basedir.'/'.$homeFile;
$fp = fopen($homeFile, 'w') or die("无法更新网站主页到：$homeFile 位置"); 
fclose($fp); 
$tpl = $cfg_basedir.$cfg_templets_dir.'/'.$templet; 
if(!file_exists($tpl)) exit("无法找到主页模板：$tpl "); 
$GLOBALS['_arclistEnv'] = 'index'; 
$pv = new PartView();
$pv->SetTemplet($tpl); 
$pv->SaveToHtml($homeFile); 
$pv->Close();
return true;
}
function tips($msg,$tips=1){
global $debug;
if($debug){
$msg=date("Y-m-d H:i:s",time()).$msg;
$cookie_file = DEDEDATA."/ajax_sh.txt"; //COOKIE存放地址
$fp=fopen($cookie_file,"a");
fwrite($fp,$msg."\n");
fclose($fp); 
}
if($tips){
exit($msg);
}else{
exit;
}
}