<?php  if(!defined('DEDEINC')) exit('AutoHtml For DedeCms Request Error!');
require_once(DEDEINC."/autohtml.inc.php");
/**
 * @自动更新HTML静态文件模块
 * 
 * 
 * @适合用于使用虚拟主机的个人站点
 * 
 * @织梦技术研究中心   http://bbs.dedejs.com
 *
 * @版本	AutoHtml V5.7.4 Final
 */
$nowtime = Time();
$ah = new AutoHtml();
class AutoHtml
{
    var $dsql;
    var $ver;
    var $type;
    var $text;
    var $code;
    var $msgcon;
    var $tplfile;
    var $filecon;
    var $content;
    var $msgtitle;

    function __construct()
    {
        global $dsql,$mod,$type,$ah_text,$ah_code;

        $this->ver = 'V5.7.4';
        $this->mod = $mod;
        $this->type = $type;
        $this->dsql = $dsql;
        $this->text = $ah_text;
        $this->code = $ah_code;
	$this->doreload = false;
	$this->SetCachefile();
	$this->make = new AutoHtmlMake();
	$this->make->SetAutoHtmlMakeAh($this);
    }

    function AutoHtml()
    {
        $this->__construct();
    }

    function SetCachefile()
    {
	$this->cacheglobal = DEDEDATA.'/cache/autohtml/global.php';

	if($this->type=='archives')
	{
		$this->cachefile = DEDEDATA.'/cache/autohtml/arcuptime'.ceil($this->Getver('id')/1000).'.php';
	}
	else if(in_array($this->type,array('list','rss','freelist','spec')))
	{
		$this->cachefile = DEDEDATA.'/cache/autohtml/'.$this->type.'uptime.php';
	}
	else
	{
		$this->cachefile = $this->cacheglobal;
	}
    }

    function UpTime()
    {
	if(in_array($this->type,array('index','check','spec')))
	{
		$this->doreload = true;
		$this->Replace($this->type.'_uptime',Time());
	}
	else if(in_array($this->type,array('list','rss','freelist','archives','arc')))
	{
		$this->doreload = true;
		$this->Replace($this->type.'_uptime',Time(),$this->Getver('id'));
	}
    }

    function UpTpl($arr)
    {
	if(empty($arr))
	{
		$this->msgcon = "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>未选择任何文件！</td></tr>";
		return false;
	}
	$mbarr = $this->Getver('mbarr');
	$this->msgcon = "<tr bgcolor=\"#FFFFFF\"><th style=\"width:200px;\">模板文件名称</th><th>模板文件说明</th><th>更新情况</th></tr>";

	foreach ($arr as $k => $v)
	{
		$rs = $this->UpTplCheck($k);
		if(!file_exists($this->tplfile)) continue;

		$file_bak = DEDEROOT.'/templets/'.$this->Getver('df_style').'/autohtml_old_'.$k.'.htm';
		if(in_array($this->mod,array('delone','delall')))
		{
			if($rs)
			{
				if(!file_exists($file_bak))
				{
					@copy($this->tplfile, $file_bak) or die("请确认模板目录是否有写入权限或手工更改模版！");
				}
				$content = str_replace($this->text['tag']."\r\n","",$this->filecon);
				$this->PutFile($this->tplfile,$content);
				$this->Replace('settpl_'.$k,'N');
				$this->msgcon .= "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>$k</td><td>$mbarr[$k]</td><td>已清除JS触发代码。</td></tr>";
			}
			else
			{
				$this->msgcon .= "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>$k</td><td>$mbarr[$k]</td><td>检测不到JS触发代码。</td></tr>";
			}
		}
		if(in_array($this->mod,array('upone','upall','mb_update')))
		{
			if(!$rs)
			{
				if(!file_exists($file_bak))
				{
					@copy($this->tplfile, $file_bak) or die("请确认模板目录是否有写入权限或手工更改模版,".$this->tplfile."，或者购买JS触发服务！");
				}
				$find = "</head>";
				$replace = $this->text['tag']."\r\n".$find;
				$content = str_replace($find,$replace,$this->filecon);
				$this->PutFile($this->tplfile,$content);
				$this->Replace('settpl_'.$k,'Y');
				$this->msgcon .= "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>$k</td><td>$mbarr[$k]</td><td>本次添加触发JS脚本。</td></tr>";
			}
			else
			{
				$this->msgcon .= "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>$k</td><td>$mbarr[$k]</td><td>已添加触发JS脚本，本次不更新。</td></tr>";
			}
		}
	}
    }

    function UpTplCheck($v)
    {
	$this->tplfile = file_exists($v) ? $v : DEDEROOT.'/templets/'.$this->Getver('df_style').'/'.$v.'.htm';
	if(!file_exists($this->tplfile)) return false;
	$this->filecon = @file_get_contents($this->tplfile);
	if(empty($this->filecon)) return false;
	if(ereg('dede:autohtml',$this->filecon)) return true;
	return false;
    }

    function UpModule()
    {
	require_once(DEDEINC."/dedemodule.class.php");
	$moddir = DEDEDATA.'/module';
	$modfile = $moddir.'/AutoHtmlUpdate.xml';

	foreach($this->code[0] as $v) $vu .= ParCv($v);
	$xml = $this->DownFile($vu.$this->Getver('newver').ParCv(95).$this->Getver('soft_lang').ParCv(46).ParCv(120).ParCv(109).ParCv(108));
	$this->PutFile($modfile,$xml);
	$this->msgcon = "<tr bgcolor=\"#FFFFFF\"><th style=\"width:200px;\">原模块版本</th><th>本次更新模块版本</th><th>更新情况</th></tr>";
	$dm = new DedeModule($moddir);
	$infos = $dm->GetModuleInfo($modfile,'file');
	extract($infos, EXTR_SKIP);
	if(empty($infos['hash']))
	{
		$this->msgcon .= "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>{$this->ver}</td><td>{$this->Getver('newver')}</td><td>更新失败。</td></tr>";
	}
	else
	{
		$menustring = addslashes($dm->GetSystemFile($hash,'menustring'));
		$indexurl = str_replace('**', '=', $indexurl);

		$query = "INSERT INTO `#@__sys_module`(`hashcode` , `modname` , `indexname` , `indexurl` , `ismember` , `menustring` )
                                    VALUES ('$hash' , '$name' , '$indexname' , '$indexurl' , '$ismember' , '$menustring' ) ";

		$rs = $this->dsql->ExecuteNoneQuery("DELETE FROM `#@__sys_module` WHERE hashcode LIKE '$hash' ");
		$rs = $this->dsql->ExecuteNoneQuery($query);
		if(!$rs)
		{
			$this->msgcon = "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>保存数据库信息失败,请在模块管理中安装。</td></tr>";
		}

		$hashfile = $moddir.'/'.$infos['hash'].'.xml';
		@copy($modfile,$hashfile);
		$dm->WriteFiles($infos['hash'],1);
		$dm->WriteSystemFile($hash,'readme');
		$dm->Clear();

		@unlink($modfile);
		//@unlink($hashfile);
		$this->msgcon .= "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>{$this->ver}</td><td>{$this->Getver('newver')}</td><td>更新成功。</td></tr>";
	}
    }

    //http://www.lancui.com/apps/autohtml/ver.txt 
    function CheckVer()
    {
	$vu = '';
	foreach($this->code[1] as $v) $vu .= ParCv($v);
	$newver = $this->DownFile($vu);
	$newcode = $nowcode = '';
	$newvers = explode('.',str_replace('V','',$newver));
	$nowvers = explode('.',str_replace('V','',$this->ver));
	foreach($nowvers as $v) $nowcode .= is_numeric($v)?$v:'';
	foreach($newvers as $v) $newcode .= is_numeric($v)?$v:'';
	$this->msgtitle = "模块更新";
	if($newcode!=''&&$nowcode!='')
	{
		$this->msgcon = "<tr bgcolor=\"#FFFFFF\"><th style=\"width:200px;\">当前版本</th><th>最新版本</th></tr>";
		if($newcode>$nowcode)
		{
			$this->msgcon .= "
			<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>$this->ver</td><td>$newver</td></tr>
			<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td colspan=\"2\"><a href=\"?act=checkver&mod=update&newver=$newver\">点这里升级到最新版本</a></td></tr>";
		}
		else
		{
			$this->msgcon .= "
			<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>$this->ver</td><td>$newver</td></tr>
			<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td colspan=\"2\">您使用的是最新版，没有更新！</td></tr>";
		}
	}
	else
	{
		$this->msgcon = "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>系统错误，请联系QQ6155040。</td></tr>";
	}
    }

    function GetIndexName()
    {
	$id = 'index';
	$it = $this->Getver('index_templet');
	if($it)
	{
		$inpi = pathinfo($it);
		$inpifile = explode( '.' , $inpi['basename']);
		$id = $inpifile['0'];
	}
	return $id;
    }

    function Getcontent()
    {
	if(!empty($this->content)) return $this->content;

	if(file_exists($this->cachefile))
	{
		$this->content = file_get_contents($this->cachefile);
	}
	else
	{
		$this->content = "<?php\r\n?>";
		$this->PutFile($this->cachefile,$this->content); 
	}
	return $this->content;
    }

    function WriteGlobals($arr)
    {
	foreach ($arr as $k => $v)
	{
		$this->$k = $v;
		$this->Replace($k,$v);
	}
	$this->WriteGlobalsText();
    }

    function WriteGlobalsText()
    {
	$rs = false;
	$mbarr2 = $this->Getver('mbarr2');
	if(isset($this->{$this->mod.'_open'})) $type = $this->{$this->mod.'_open'};
	if(isset($this->{$this->mod.'_pages'})) $num = $this->{$this->mod.'_pages'};

	if(in_array($this->mod,array('index','list','freelist','rss','arc','spec')))
	{
		if(in_array($this->mod,array('index','arc'))) $num='';
		$rehtml = ereg_replace('#modname#',$this->text['name'][$this->mod],$this->text['open'][$type]);
		$rehtml .= (is_numeric($num) && $type=='Y') ? ereg_replace('#autohtmlnum#',$num,$this->text['htmlnum']) : '';
		$this->msgcon = "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>$rehtml</td></tr>";

		if(in_array($this->mod,array('list','freelist','arc','spec')))
		{
			foreach ($mbarr2[$this->mod] as $k => $v)
			{
				if(!$this->UpTplCheck($k)){if(file_exists($this->tplfile)){$rs = true; break;}}
			}
		}
		else if($this->mod=='index')
		{
			if($this->index_open == 'Y' && $this->Getver('act') == 'save')
			{
				if(!$this->UpTplCheck($this->index_templet)){$rs = true;}
			}
		}
	}
	else if($this->mod=='filedir')
	{
		$this->msgcon = "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>触发文件目录【{$this->focus_dir}】</td><td><a href=\"{$this->Getver('basehost')}{$this->focus_dir}autohtml.php?type=test\" target=\"stafrm\">测试</a></td></tr>";
	}
	else
	{
		$this->msgcon = "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>设置成功！</td></tr>";
		$this->msgcon .= "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>请确认是否设置模板触发代码，<a href=\"?act=mb_update\" target=\"main\">点这里设置！</a></td></tr>" ;
	}
	if( $rs && $type == 'Y' )
	{
		$this->msgcon .= "<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>检测到您<font color=\"red\">未设置</font>模板触发代码，请<a href=\"?act=mb_update\" target=\"main\">点这里设置！</a></td></tr>" ;
	}
    }

    function Msg($msg)
    {
	if($this->type == 'check') return;
	@header("Pragma:no-cache,must-revalidate\r\n");
        @header("Cache-Control:no-cache\r\n");
        @header("Expires:0\r\n");
	if($this->doreload && $this->Getver($this->type.'_reload') == 'Y')
	{
		echo "document.write(\"<script> setTimeout(\\\"location.reload();\\\",\\\"1500\\\");</script>\");\r\n";
	}
	else
	{
		$this->doreload = false;
		echo "document.write(\"<meta name='autohtml' content='".$msg."' />\");\r\n";
	}
    }

    function Author()
    {
	$this->msgcon = "
			<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>Email</td><td>admin@dedejs.com</td></tr>
			<tr bgcolor=\"#FFFFFF\"  align=\"center\"><td>织梦技术研究中心：</td><td><a href=\"http://bbs.dedejs.com\" target=\"_blank\">http://bbs.dedejs.com</a></td></tr>
		";
    }

    function Replace($name,$value,$id='N')
    {
	$content = $this->Getcontent();
	if(is_numeric($id))
	{
		$this->Insert($content,'/\$'.$name.'\["'.$id.'"\] \= \".*?\";/i','$'.$name.'["'.$id.'"] = "'.$value.'";');
	}
	else
	{
		$this->Insert($content,'/\$'.$name.' \= \".*?\";/i', '$'.$name.' = "'.$value.'";');
	}
    }

    function Insert(&$content,$find,$replace)
    {
	if(preg_match($find,$content))
	{
		$content = preg_replace($find,$replace,$content);
	}
	else
	{
		$content .= "\r\n<?php".$replace."\r\n?>";
	}
	$this->content = preg_replace("/\?>(.+?)\s<\?php/","",$content);
	$this->PutFile($this->cachefile,$this->content);
    }

    function Getver($k)
    {
	if(isset($GLOBALS[$k]))
	{
		return $GLOBALS[$k];
	}
	else if(isset($GLOBALS['cfg_'.$k]))
	{
		return $GLOBALS['cfg_'.$k];
	}
	else
	{
		return false;
	}
    }

    function DownFile($url)
    {
	require_once(DEDEINC.'/dedehttpdown.class.php');
	$content = '';
	$dhd = new DedeHttpDown();
	$dhd->OpenUrl($url);
	$content = trim($dhd->GetHtml());
	$dhd->Close();

	if(empty($content) && ini_get('allow_url_fopen'))
	{
		$content = file_get_contents($url);
	}
	else if(empty($content) && function_exists('pfsockopen'))
	{
		exit($this->text['downerror']);
	}
	return $content;
    }

    function PutFile($file, $content, $flag = 0)
    {
        $pathinfo = pathinfo ( $file );
        if (! empty ( $pathinfo ['dirname'] ))
        {
            if (file_exists ( $pathinfo ['dirname'] ) === FALSE)
            {
                if (@mkdir ( $pathinfo ['dirname'], 0777, TRUE ) === FALSE)
                {
                    return FALSE;
                }
            }
        }
        if ($flag === FILE_APPEND)
        {
            return @file_put_contents ( $file, $content, FILE_APPEND );
        }
        else
        {
            return @file_put_contents ( $file, $content, LOCK_EX );
        }
    }

    function MyDate($format='Y-m-d H:i:s', $timest=0)
    {
	$sq = $this->Getver(cli_time);
        $addtime = $sq * 3600;
        if(empty($format))
        {
            $format = 'Y-m-d H:i:s';
        }
        return gmdate ($format, $timest+$addtime);
    }
}

class AutoHtmlMake
{
    var $ah;
    var $autohtmlmakever;

    function __construct()
    {
	$thes->autohtmlmakever = '5.0.2';
    }

    function AutoHtmlMake()
    {
        $this->__construct();
    }

    function SetAutoHtmlMakeAh($ah)
    {
        $this->ah = $ah;
    }

    function arc($id)
    {
	require_once(DEDEINC.'/arc.archives.class.php');

	$arc = new Archives($id);
	if($arc->Fields['ismake']==-1||$arc->Fields['arcrank']!=0||$arc->Fields['typeid']==0||$arc->Fields['money']>0)
	{
		$this->ah->Msg($title.'：动态文章、收费文章、未审核文章、被移入回收站，无法生成终止处理。');
	}
	else
	{
  		$reurl = $arc->MakeHtml();
		$this->ah->UpTime();
		$this->ah->Msg('已经重新生成ID为：'.$id.'，标题为：'.$arc->Fields['title'].'的文档的静态文件。');
	}
	$arc->Close();
    }

    function arclist($id,$list_pages)
    {
	if($this->ah->Getver('sg') == 'sg')
	{
		require_once(DEDEINC.'/arc.sglistview.class.php');
		$list = new SgListView($id);
	}
	else
	{
		require_once(DEDEINC.'/arc.listview.class.php');
		$list = new ListView($id);
	}

	$isdefault = $list->TypeLink->TypeInfos['isdefault'];
	$typename  = $list->TypeLink->TypeInfos['typename'];

	if( $isdefault != '-1' )
	{
		$reurl = $list->MakeHtml(1,$list_pages);
		$this->ah->UpTime();
		$this->ah->Msg('重新生成栏目 “'.$typename.'” 前 '.$list_pages.' 页静态文件。');
	}
	else
	{
		$this->ah->Msg( '“'.$typename.'”是动态栏目，不需要生成静态文件。');
	}
	$list->Close();
    }

    function rss($id,$rss_pages)
    {
	require_once(DEDEINC."/arc.rssview.class.php");
	$rss = new RssView($id,$rss_pages);
	$rssurl = $rss->MakeRss();
	$rss->Close();
	$this->ah->type = 'rss';
	$this->ah->UpTime();
	$this->ah->Msg;('重新生成栏目 “'.$typename.'” RSS文件。');
    }

    function index($tpl,$index_indexFile)
    {
	require_once(DEDEINC."/arc.partview.class.php");
	$index = new PartView();
	$GLOBALS['_arclistEnv'] = 'index';
	$index->SetTemplet($tpl);
	$index->SaveToHtml($index_indexFile);
	$index->Close();
	$this->ah->UpTime();
	$this->ah->Msg('已重新生成网站首页静态文件。');
    }

    function freelist($id,$freelist_pages)
    {
	ob_start();
	require_once(DEDEINC."/arc.freelist.class.php");
	$lv = new FreeList($id);
	$lv->MakeHtml('1',$freelist_pages);
	$lv->Close();
	ob_end_clean;
	$this->ah->UpTime();
	$this->ah->Msg( '重新生成自由列表 “'.$id.'” 前 '.$freelist_pages.' 条记录。');
    }

    function spec()
    {
	ob_start();
	require_once(DEDEINC."/arc.specview.class.php");
	$sp = new SpecView();
	$sp->MakeHtml();
	$sp->Close();
	ob_end_clean;
	$this->ah->UpTime();
	$this->ah->Msg('已重新生成专题页列表文件。');
    }


    function setcheckvar()
    {
	$this->ah->type = 'check';
	$this->ah->cachefile = $this->ah->cacheglobal;
    }

    function checkall()
    {
	$this->setcheckvar();
	$query = "select ch.id,ch.issystem,ch.maintable,ch.addtable FROM `#@__arctiny` arc 
		LEFT JOIN `#@__channeltype` ch ON ch.id=arc.channel
		where arc.senddate IN ( select max(senddate) from `#@__arctiny` where arcrank='-1' GROUP BY channel ) ORDER BY arc.senddate DESC";

	$cid = $maintable = '';
	$this->ah->dsql->SetQuery($query);
	$this->ah->dsql->Execute('ckall');
	while($row = $this->ah->dsql->GetArray('ckall'))
	{
		$cid = $row['id'];
		$maintable = ( trim($row['maintable'])=='' ? '#@__archives' : trim($row['maintable']) );

		$this->ah->dsql->ExecuteNoneQuery("UPDATE `#@__arctiny` SET arcrank='0' WHERE channel='$cid' ");
		$this->ah->dsql->ExecuteNoneQuery("UPDATE `#@__taglist` SET arcrank='0' WHERE arcrank='-1' "); 

		if($row['issystem']==-1)
		{
			$this->ah->dsql->ExecuteNoneQuery("UPDATE `".trim($row['addtable'])."` SET arcrank='0' WHERE arcrank='-1' ");
		}
		else
		{
			$this->ah->dsql->ExecuteNoneQuery("UPDATE `$maintable` SET arcrank='0' WHERE arcrank='-1' ");
		}
	}
	$this->ah->UpTime();
    }

    function checkarc()
    {
	global $check_pages,$check_makearc;

	$this->setcheckvar();
	$query = "SELECT arc.id,arc.typeid,ch.issystem,ch.maintable,ch.addtable FROM `#@__arctiny` arc
		LEFT JOIN `#@__arctype` tp ON tp.id=arc.typeid
		LEFT JOIN `#@__channeltype` ch ON ch.id=tp.channeltype
		WHERE arcrank='-1' order by arc.id asc limit 0,$check_pages";

	$aid = $maintable = '';
	$this->ah->dsql->SetQuery($query);
	$this->ah->dsql->Execute('ckall');
	while($row = $this->ah->dsql->GetArray('ckall'))
	{
		$aid = $row['id'];
		$maintable = ( trim($row['maintable'])=='' ? '#@__archives' : trim($row['maintable']) );

		$this->ah->dsql->ExecuteNoneQuery("UPDATE `#@__arctiny` SET arcrank='0' WHERE id='$aid' ");
		$this->ah->dsql->ExecuteNoneQuery("UPDATE `#@__taglist` SET arcrank='0' WHERE aid='$aid' "); 

		if($row['issystem']==-1)
		{
			$this->ah->dsql->ExecuteNoneQuery("UPDATE `".trim($row['addtable'])."` SET arcrank='0' WHERE aid='$aid' ");
		}
		else
		{
			$this->ah->dsql->ExecuteNoneQuery("UPDATE `$maintable` SET arcrank='0' WHERE id='$aid' ");
		}
		if($check_makearc == 'Y'){$this->arc($aid);}
	}
	$this->ah->UpTime();
    }
}
?>