<?php

require_once('inc/logincheck.php');
CommTool::checkIncludeByAdminPhp();

set_time_limit(0);    
$frontTempHttpPath = substr($adminHttpPath, 0, strlen($adminHttpPath)-6);    
$frontTempAbsolutePath = substr(KUWEBS_ADMIN_PATH, 0, strlen(KUWEBS_ADMIN_PATH)-6);
$kuWebsiteTempHTMLType = transferHTMLType($kuWebsiteHTMLType);  

if("modify" == $action)                                  
{
  include_once('system/saveconfig.php');    
  $kuWebsiteTempHTMLType = transferHTMLType($kuWebsiteHTMLType);  
  
  if(1 != $kuWebsiteHTMLStartType)
  {
    if($configIsLog)CommTool::writeLog("{$_SESSION['adminuser']} modify html settings");         
    promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html", $promptEditDataSuccess, $configJumpTime);
    exit;
  }
  else //关闭静态页面生成，则删除静态页面
  {    
    
    foreach(glob("../index*.htm*") as $indexFileName)unlink($indexFileName);
    promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html", $promptEditDataSuccess, $configJumpTime);
    exit;
  }
}
else if("deleteall" == $action)
{
  if(2 == $kuWebsiteHTMLStartType)    
  {
    promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html", $promptHTMLStartCreateHTML, $configJumpTime);
    exit;
  }
  else
  {
    $arrPath = array($frontTempAbsolutePath.'news', $frontTempAbsolutePath.'product', 
                     $frontTempAbsolutePath.'img', $frontTempAbsolutePath.'download', $frontTempAbsolutePath.'job', $frontTempAbsolutePath.'message', 
                     $frontTempAbsolutePath.'faq');
    $arrModule = array('news',  'product', 'img',  'download',  'job',  'message', 'faq');
    foreach($arrPath as $key=>$path)
    {//每个路径下删除所有htm*文件
      foreach(glob("$path/index_{$kuWebsiteEditVersionLanguage}.htm*") as $indexFileName)unlink($indexFileName);
      foreach(glob("$path/{$arrModule[$key]}*.htm*") as $indexFileName)unlink($indexFileName);
    }
    foreach(glob($frontTempAbsolutePath."index_{$kuWebsiteEditVersionLanguage}.htm*") as $indexFileName)unlink($indexFileName);
    foreach(glob($frontTempAbsolutePath."sitemap_{$kuWebsiteEditVersionLanguage}.htm*") as $indexFileName)unlink($indexFileName);
    foreach(glob($frontTempAbsolutePath.'about/'.'*.htm*') as $indexFileName)unlink($indexFileName);
  }
}
else if("add" == $action)
{
  if(1 != $kuWebsiteHTMLStartType)    
  {
    
    if('all' == $createflag)
    {
        foreach(glob("../index_{$kuWebsiteEditVersionLanguage}.htm*") as $indexFileName)unlink($indexFileName);
        $result = makeSinglePage('', 'index', $kuWebsiteEditVersionLanguage);//主页
        if(!$result){promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html", $promptHTMLCreateHTMLFail, $configJumpTime);exit;}
        $result = makeSinglePage('', 'sitemap', $kuWebsiteEditVersionLanguage);//站点地图
        if(!$result){promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html", $promptHTMLCreateHTMLFail, $configJumpTime);exit;}
        
        for($iModule=1; $iModule<=8; $iModule++)
        {
            $moduleName = $arrAllModule[$iModule];
            
            $pageNumberLabel = 'kuWebsitePagingNumber'.$moduleName;
            $pageNumber = $$pageNumberLabel;
            if('about' == $moduleName)$pageNumber=1;
            $arrMenu = $dbInstance->getList("select * from {$configTableHead}menu where menumodule={$iModule} order by id asc");
            
            foreach($arrMenu as $menuInfo)
            {
                $menuid = $menuInfo['id'];
                $menuModule = $menuInfo['menumodule'];
                if(1 == $menuModule)$strSql = "select count(*) from {$configTableHead}{$moduleName} where id={$menuid};";
                else $strSql = "select count(*) from {$configTableHead}{$moduleName} where type1=$menuid or type2=$menuid or type3=$menuid;";
                $contentCount = $dbInstance->getCount($strSql);
                $iTimes = ceil($contentCount/$pageNumber);
                if(0 == $iTimes)$iTimes = 1;
                //echo $iTimes, $pageNumber;
                for($page=1; $page<=$iTimes; $page++)
                {
                    $result = makeModuleList($menuid, $page, $moduleName);
                    if(!$result){promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html", $promptHTMLCreateHTMLFail, $configJumpTime);exit;}
                }
            }
            
            
            if('about' == $moduleName)continue;
            $arrItem = $dbInstance->getList("select * from {$configTableHead}{$moduleName} order by id asc");
            foreach($arrItem as $itemInfo)
            {
                $result = makeModuleItem($itemInfo['id'], $moduleName);
                if(!$result){promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html", $promptHTMLCreateHTMLFail, $configJumpTime);exit;}
            }
        }
    }
    else if('index' == $createflag || 'sitemap' == $createflag)
    {
        foreach(glob("../index_{$kuWebsiteEditVersionLanguage}.htm*") as $indexFileName)unlink($indexFileName);
        $result = makeSinglePage('', $createflag, $kuWebsiteEditVersionLanguage);
        if(!$result){promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html", $promptHTMLCreateHTMLFail, $configJumpTime);exit;}
    }
    else
    {
        for($iModule=1; $iModule<=8; $iModule++)
        {
            $moduleName = $arrAllModule[$iModule];
            if($createflag != $moduleName)continue;
            
            $pageNumberLabel = 'kuWebsitePagingNumber'.$moduleName;
            $pageNumber = $$pageNumberLabel;
            if('about' == $moduleName)$pageNumber=1;
            $arrMenu = $dbInstance->getList("select * from {$configTableHead}menu where menumodule={$iModule} order by id asc");
            //print_r($arrMenu);
            foreach($arrMenu as $menuInfo)
            {
                $menuid = $menuInfo['id'];
                $menuModule = $menuInfo['menumodule'];
                if(1 == $menuModule)$strSql = "select count(*) from {$configTableHead}{$moduleName} where id={$menuid};";
                else $strSql = "select count(*) from {$configTableHead}{$moduleName} where type1=$menuid or type2=$menuid or type3=$menuid;";
                $contentCount = $dbInstance->getCount($strSql);
                $iTimes = ceil($contentCount/$pageNumber);
                if(0 == $iTimes)$iTimes = 1;
                //echo $iTimes, $pageNumber;
                for($page=1; $page<=$iTimes; $page++)
                {
                    $result = makeModuleList($menuid, $page, $moduleName);
                    if(!$result){promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html", $promptHTMLCreateHTMLFail, $configJumpTime);exit;}
                }
            }
            
            
            if('about' == $moduleName)continue;
            $arrItem = $dbInstance->getList("select * from {$configTableHead}{$moduleName} order by id asc");
            foreach($arrItem as $itemInfo)
            {
                $result = makeModuleItem($itemInfo['id'], $moduleName);
                if(!$result){promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html", $promptHTMLCreateHTMLFail, $configJumpTime);exit;}
            }
        }
    }
    
    
    fopen('http://www.k'.'uwe'.'bs.com'."/plus/add_rec.php?action=login&url={$adminHttpPath}", "r");
    if('all' == $createflag) 
    {
      if($configIsLog)CommTool::writeLog("{$_SESSION['adminuser']} create all html files");         
      promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html", $promptHTMLCreateAllHTMLSuccess, $configJumpTime);
      exit;
    }
    else
    {
        if($configIsLog)CommTool::writeLog("{$_SESSION['adminuser']} create all html files");         
        promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html", $promptHTMLCreateHTMLSuccess, $configJumpTime);
        exit;
    }
  }
  else
  {
    promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html", $promptHTMLStartCreateHTML, $configJumpTime);
    exit;
  }
}
else if("" == $action)                                  
{
  $userName = trim($_POST['username']);
  $password = $_POST['pass'];
  if(1 > strlen($userName) || 1 > strlen($password))
  {
    promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=login&menu=login", $promptNonLogin, $configJumpTime);
    exit;
  }
  $userPassword = CommTool::encryptMd5($password, $configEncryptTimes);
  $strSql = "select id, adminuser, adminpassword from {$configTableHead}admin where adminuser = '$userName' and adminpassword = '$userPassword';";
  $row = $dbInstance->getOne($strSql);
  if(1 > $row['id'])
  {
    promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=login&menu=login", $promptLoginFail, $configJumpTime);
    exit;
  }
  else
  {
    $_SESSION['adminid'] = $row['id'];
    $_SESSION['adminuser'] = $row['adminuser'];
    $_SESSION['adminpassword'] = $row['adminpassword'];
    if($configIsLog)CommTool::writeLog("{$_SESSION['adminuser']} login to system");
    promptMessage($adminHttpPath.'index.php', $promptLoginSuccess, $configJumpTime);
    exit;
  }
}



function makeHtmlFile($fileName, $content)
{
  if(!file_exists(dirname($fileName)))
  {
    if(!@mkdir(dirname($fileName)) || !@chmod(dirname($fileName), 0777))
    {
      if(!file_exists(dirname(dirname($fileName))))
      {
        if(!@mkdir(dirname(dirname($fileName))))die($fileName.' Create parent dir failed. '.$fileName.' parent dir: '.dirname(dirname($fileName)));
        @chmod(dirname(dirname($fileName)), 0777);
        if(!@mkdir(dirname($fileName)))die($fileName.' Create curr dir failed.');
        @chmod(dirname($fileName), 0777);
      }
    }
  }
  
  $fp = '';
  if(!@$fp = fopen($fileName, 'w'))
  {
    die($fileName.' Create file failed.');
  }
  //echo 'aaaa'.$content;die();
  if('' != $content)
  {
    if(!@fwrite($fp, $content))
    {
      fclose($fp);
      die($fileName.' Write data to file failed.');
    }
  }
  
  fclose($fp);
  return true;
}


function makeModuleList($menuid, $page, $moduleName)
{
    global $kuHttpPathUrl, $kuWebsiteEditVersionLanguage, $kuWebAbsolutePath, $kuWebsiteTempHTMLType, $menuHtmlList;
    $content = '';

    // echo $kuHttpPathUrl.$moduleName."/index.php?lang=".$kuWebsiteEditVersionLanguage."&menuid=$menuid&page=$page";
    $content = file_get_contents($kuHttpPathUrl.$moduleName."/index.php?lang=".$kuWebsiteEditVersionLanguage."&menuid=$menuid&page=$page");
    //echo $content; 
    $content = repalcePhpToHtml($content);
    //echo $content; 
    
    $filePath = "";
    if('about' == $moduleName)$filePath = $kuWebAbsolutePath."/{$moduleName}/".($menuHtmlList[$menuid] ? $menuHtmlList[$menuid] : "index_{$kuWebsiteEditVersionLanguage}_{$menuid}").$kuWebsiteTempHTMLType;
    else $filePath = $kuWebAbsolutePath."/{$moduleName}/index_{$kuWebsiteEditVersionLanguage}_{$menuid}_{$page}{$kuWebsiteTempHTMLType}";
    //echo '<br>filePath:'.$filePath;
    return makeHtmlFile($filePath, $content);
}


function makeModuleItem($itemid, $moduleName)
{
    global $kuHttpPathUrl, $kuWebsiteEditVersionLanguage, $kuWebAbsolutePath, $kuWebsiteTempHTMLType;
    $content = '';
    //echo $kuHttpPathUrl.$moduleName."/$moduleName.php?lang=".$kuWebsiteEditVersionLanguage."&itemid=$itemid";
    $content = file_get_contents($kuHttpPathUrl.$moduleName."/{$moduleName}.php?lang=".$kuWebsiteEditVersionLanguage."&itemid={$itemid}");
    
    $content = repalcePhpToHtml($content);
    //echo $content;
    
    $filePath = $kuWebAbsolutePath."/{$moduleName}/{$moduleName}_{$kuWebsiteEditVersionLanguage}_{$itemid}{$kuWebsiteTempHTMLType}";
    return makeHtmlFile($filePath, $content);
}

function makeSinglePage($path, $file)
{
    global $kuHttpPathUrl, $kuWebsiteEditVersionLanguage, $kuWebAbsolutePath, $kuWebsiteTempHTMLType;
    $content = file_get_contents($kuHttpPathUrl.$path.'/'.$file.'.php?lang='.$kuWebsiteEditVersionLanguage);
    $content = repalcePhpToHtml($content, $itemid, $moduleName);
    $filePath = $kuWebAbsolutePath."/{$path}/{$file}_{$kuWebsiteEditVersionLanguage}{$kuWebsiteTempHTMLType}";
    return makeHtmlFile($filePath, $content);
}

function repalcePhpToHtml($content)
{
    global $arrAllModule, $kuWebsiteTempHTMLType, $adminHostName, $menuHtmlList;
    $arrLink = getAllURL($content);
    //echo $content;
    $arrUrlLink = $arrLink[url];
    // echo 'All Link:';print_r($arrLink);
    foreach($arrUrlLink as $link)
    {
        if(!stristr($link, '.php'))continue;
        $isModule = false;
        $lang = $menuid = '';
        $type1 = $type2 = $type3 = '';
        $itemid = $page = '';
        $newUrl = '';
        $arrUrl = parse_url($link);
        if(empty($arrUrl['scheme']) || empty($arrUrl['host']) || empty($arrUrl['path']))continue; 
        $file = basename($arrUrl['path'], '.php');
        $path = dirname($arrUrl['path']);
        //echo $path.'<br>';
        // echo $arrUrl['query']."\n";
        parse_str($arrUrl['query']);
        // echo $menuid.$file.$arrUrl['path']."\n";
        // echo "query:".$arrUrl['query']."  $page\n";
        
        foreach($arrAllModule as $mName)
        {
            if(stristr($path, $mName))
            {
                if(stristr($file, $mName))
                {
                    $newUrl = $arrUrl['scheme'].'://'.$arrUrl['host'].$path.'/'.$file.'_'.$lang.'_'.$itemid.$kuWebsiteTempHTMLType;
                    $content = str_replace("\"".$link."\"", "\"".$newUrl."\"", $content);
                    $content = str_replace("\'".$link."\'", "\'".$newUrl."\'", $content);//die();
                    break;
                }
                else if(stristr($file, 'index'))
                {
                    if('' == $page)$page = 1;
                    if('about' == $mName)$newUrl = $arrUrl['scheme'].'://'.$arrUrl['host'].$path.'/'.($menuHtmlList[$menuid]? $menuHtmlList[$menuid] : $file.'_'.$lang.'_'.$menuid).$kuWebsiteTempHTMLType;
                    else $newUrl = $arrUrl['scheme'].'://'.$arrUrl['host'].$path.'/'.$file.'_'.$lang.'_'.$menuid.'_'.$page.$kuWebsiteTempHTMLType;
                    $content = str_replace("\"".$link."\"", "\"".$newUrl."\"", $content);
                    $content = str_replace("\'".$link."\'", "\'".$newUrl."\'", $content);//die();
                    break;
                }
                
                $isModule = true;
            }
            
        }
        
        //echo 'adminhost:'.$arrUrl['host'].$adminHostName.'<br>';
        if(!$isModule && stristr($arrUrl['host'], $adminHostName) && (stristr($file, 'index') || stristr($file, 'sitemap'))) //本站内的其他链接，目前只有index,sitemap
        {
            //echo $file."\n New Url:";
            $newUrl = $arrUrl['scheme'].'://'.$arrUrl['host'].$path.'/'.$file.'_'.$lang.$kuWebsiteTempHTMLType;
            //echo $newUrl."\n";
            $content = str_replace("\"".$link."\"", "\"".$newUrl."\"", $content);//die();
            $content = str_replace("'".$link."'", "'".$newUrl."'", $content);//die();
        }
        
    }
    return $content;
}

function getAllURL($code)
{
  preg_match_all('/<a\s+.*?href=["|\']?([^>"\' ]+)["|\']?\s*[^>]*>(.*?)<\/a>/is',$code,$arr);
  return array('name'=>$arr[2],'url'=>$arr[1]);
}

?>