<?php
  function promptMessage($nextUrl, $promptContent, $displayTime='2', $fromFlag='')
  {
    global $adminHttpImgPath;
?>
    <!-- display the prompt content on the page. -->
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style>
    table{ font-size:12px;}
    </style>
    <table width="100%" height="100%" border="0" align="center" cellpadding="0" cellspacing="0">
      <tr>
        <td align="center" valign="middle">
            <table width="440" height="200" border="0" cellpadding="0" cellspacing="0" bordercolor="#DDDDDD" background="<?php echo $adminHttpImgPath; ?>prompt_03.gif" style="border:1px solid #DDDDDD;">
              <tr>
                <td height="56" align="center"><img src="<?php echo $adminHttpImgPath; ?>prompt_05.gif" width="440" height="56" /></td>
              </tr>
              <tr>
                <td height="32" bgcolor="#007BD2"><img src="<?php echo $adminHttpImgPath; ?>prompt_08.gif" width="150" height="31" style="margin-left:20px;"/></td>
              </tr>
              <tr>
                <td align="center" valign="middle" style="padding:10px;">                
            <?php
                        global $promptBottomWaiting;
                        global $promptBottomClickMe;
                        echo "$promptContent<br>";
                        echo "<br>{$promptBottomWaiting}<br>";
              echo "<br><a href=\"".$nextUrl."\">".$promptBottomClickMe."</a><br>";
                      ?>
                </td>
            </tr>
          </table>

        </td>
      </tr>
    </table>
<!-- end of display the prompt content on the page. -->
<?php
    if($fromFlag == 'eidtpassword')
    {
      echo "<script>setTimeout(\"window.parent.location='index.php?lang={$kuWebsiteEditVersionLanguage}&path=login&menu=login'\", $displayTime*1000);</script>";
      exit;
    }
    else
    {
      echo "<script language=\"javascript\"> setTimeout(\"window.location.href='".$nextUrl."'\", $displayTime*1000) </script>";
      exit();
    }
  }


function getIP()
{ 
  if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {$ip = getenv("HTTP_CLIENT_IP");}
  else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {$ip = getenv("HTTP_X_FORWARDED_FOR"); }
  else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {$ip = getenv("REMOTE_ADDR"); }
  else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")){$ip = $_SERVER['REMOTE_ADDR']; } 
  else {$ip = "unknown"; }
  return($ip); 
}


function checkDir($fileDirPath)
{
  if(is_dir($fileDirPath))  //判断该路径下的文件目录是否存在
  {
    $dh = opendir($fileDirPath);  //打开文件目录句柄
    while(($file = readdir($dh)) !== false)  //返回目录中下一个文件的文件名
    {
      if($file != '.' && $file != '..')  
      {
        if(!is_dir($fileDirPath.'/'.$file))  //文件处理
        {
          $arrFileName[] = $file;
        }
      }
    }
    closedir($dh); //关闭文件目录句柄
  }
  return $arrFileName;
}

  
function template($labelFile, $templateName='default')
{
  $file = KUWEBS_ADMIN_PATH."template/$templateName/$labelFile";
  if(!file_exists($file))
  {
    $file = KUWEBS_ADMIN_PATH."template/kuwebs/$labelFile";
  }
  //echo $file.'<br>';
  return $file;
}
  
class CommTool
{
  static function cutstrutf8($string, $length) 
  {
     preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $string, $info);  
     for($i=0; $i<count($info[0]); $i++)
     {
        $wordscut .= $info[0][$i];
        $j = ord($info[0][$i]) > 127 ? $j + 2 : $j + 1;
        if ($j > $length - 3) 
        {
           return $wordscut."..";
        }
     }
     return join('', $info[0]);
  }
  
  static function checkIncludeByAdminPhp()
  {
    if(!ereg("(index.php){1}", $_SERVER['PHP_SELF']))
    {
      echo 'Can not access me directly. Exit';
      exit;
    }
  }
  
  static function encryptMd5($password, $encryptTimes=3)
  {
    for($i=1; $i<$encryptTimes; $i++) $password = md5($password.'%!#kuwebs#%$');
    return $password;
  }
  
  static function getSexNameById($sex)
  {
    if(1 == $sex) return 'male';
    else if(2 == $sex) return 'female';
    else return 'unknown';    
  }
  
  static function mkdir($dir, $mode=0777)
  {
    if(is_dir($dir) || @mkdir($dir, $mode)) return true;
    return @mkdir($dir, $mode);
  }
  
    
    static function writeLog($str = '', $fileName = "admin.log")
    {
      global $configLogPath;
      $fileLog = $configLogPath.$fileName;
      $sizeLog = 0;
      if(is_file($fileLog))$sizeLog = filesize($fileLog);
      if(5*1024*1024 < $sizeLog)
      {
        $fileBackup = $configLogPath.date('YmdHis', time()).'.log';
        copy($fileLog, $fileBackup);
        unlink ($fileLog);
      }
      
      if(empty($str))
      {
        $str = "\r\n";
      }
      else
      {
        $formatTime = date("Y-m-d H:i:s", time());
        list($usec, $sec) = explode(" ", microtime());
        $iUSec = (float)$usec * 1000000;
        $str = '['.$formatTime.' '.$iUSec.']:'.$str."\r\n";
      }
      $fp = fopen($fileLog, 'a');
      @fwrite($fp, $str);
      @fclose($fp);  
    }

    static function utf8ToGbk($str)
    {
      return iconv('utf-8','gbk', $str);
    }
    
  static function debug2File($str)
  {
    $strOldFile = file_get_contents('debug.txt');
    $strNewFile = $strOldFile.$str."\n";
    file_put_contents('debug.txt', $strNewFile);
  }
  
  static function judgeUnusualCharacter($str)
  {//if some unusual character, then return FALSE; No unusual charater, return TRUE;
    if($str == addslashes("$str") && !ereg("[\}{\[\&\^\%\$\#\@\!\;\:\~\`\；\：\‘\“\”\，\。\？\／\）\（\＊\—\…\％\￥\＃\·\！\～\…\｀\,\.\?\<\>\*\(\)\+\_\=\/\ˇ\¨\〃\々\‖\〈\〉\《\》\「\」\『\』\〖\〗\【\】\±\-]","$str") && !strpos("$str","]")) return true;
    else return false;
  }

  //The user name only include character, digit, _, -, .   and the length must >4 and <20; normal:return true; not normal return false;
  static function judgeUserName($str)
  {
    if(ereg("^[0-9a-zA-Z]+([0-9a-zA-Z]|_|\.|-)+[0-9a-zA-Z]$","$str")&& strlen("$str")>=4 && strlen("$str")<20) return true;
    else return false;
  }

  static function judgeEmail($str)
  {
    if(ereg("^[0-9a-zA-Z]+([0-9a-zA-Z]|_|\.|-)+[0-9a-zA-Z]+@(([0-9a-zA-Z]+\.)|([0-9a-zA-Z]+-))+[0-9a-zA-Z]+$","$str") && strrpos("$str","-") < strrpos("$str",".")) return true;
    else return false;
  }  

  static function createIndexBlockFile($templateFile, $destinationFile, $indexTitle, $dbSeq)
  {
    $strFile = file_get_contents('../'.$templateFile.'.inc.php');
    //CommTool::debug2File($strFile);
    $strFile = str_replace('{INDEX_BLOCK_TITLE}', $indexTitle, $strFile);
    $strFile = str_replace('{INDEX_BLOCK_FILE}', $destinationFile, $strFile);
    $strFile = str_replace('{INDEX_BLOCK_DBSEQ}', $dbSeq, $strFile);
    file_put_contents('../'.$destinationFile.'.inc.php', $strFile);
  }
    
    static function getFileContent($filePath, $method='rb')
    {
        if($handle = fopen($filePath, $method))
        {
            flock($handle, LOCK_SH);        //排它锁
            $fileContent = @fread($handle, filesize($filePath));
            fclose($handle);                //解锁
        }
        return $fileContent;
    }
      
    static function editConfigParam($filePath, $find, $replace)
    {
        if(is_writable($filePath))                 //判断文件是否是可写状态
        {
            if($handle = fopen($filePath, 'rb'))
            {
                flock($handle, LOCK_SH);        //排它锁
                $fileContent = @fread($handle, filesize($filePath));
                fclose($handle);                //解锁
            }
            $start = strrpos($fileContent, $find);
            str_replace($file, $replace, $fileContent);
            fputs($file, $dbConfig);                                  //写入  
            fclose($file);                                            //关闭文件流
        }
    }  
    
    
    static function fileUnlink($file_name) 
    {
      if(file_exists($file_name)) 
      {
        @chmod($file_name,0777);
        $area_lord = @unlink($file_name);
      }
      return $areaLord;
    }
}

class MenuTool
{
  
  static function showNav($nav)
  {
    global $labelSystemMenuNavigationNotDisplay, $labelSystemMenuMainNavigationDisplay, $labelSystemMenuFooterNavigationDisplay, $labelSystemMenuNavigationAllDisplay;
    if('1' == $nav){$label = "$labelSystemMenuNavigationNotDisplay";}
    else if('2' == $nav){$label = "$labelSystemMenuMainNavigationDisplay";}
    else if('3' == $nav){$label = "$labelSystemMenuFooterNavigationDisplay";}
    else if('4' == $nav){$label = "$labelSystemMenuNavigationAllDisplay";}
    else{$label = "$labelSystemMenuNavigationNotDisplay";}    
    
    return $label;
  }
  
  
  static function showType($type)
  {
    global $labelSystemMenuInsideNavigation, $labelSystemMenuOutsideLink;
    if('1' == $type){$label = "$labelSystemMenuInsideNavigation";}
    else if('2' == $type){$label = "$labelSystemMenuOutsideLink";}
    else{$label = "$labelSystemMenuInsideNavigation";}
    
    return $label;
  }
  
  
  static function showModule($module)
  {
    global $labelSystemMenuBindAboutsModel, $labelSystemMenuBindNewsModel, $labelSystemMenuBindProductModel,
 $labelSystemMenuBindImgModel, $labelSystemMenuBindDownloadModel, $labelSystemMenuBindJobModel,
 $labelSystemMenuBindMessageModel, $labelSystemMenuBindFaqModel;
    if('1' == $module){$label = "$labelSystemMenuBindAboutsModel";}        //简介
    else if('2' == $module){$label = "$labelSystemMenuBindNewsModel";}    //新闻
    else if('3' == $module){$label = "$labelSystemMenuBindProductModel";}  //产品
    else if('4' == $module){$label = "$labelSystemMenuBindImgModel";}      //图片
    else if('5' == $module){$label = "$labelSystemMenuBindDownloadModel";}//下载
    else if('6' == $module){$label = "$labelSystemMenuBindJobModel";}      //招聘
    else if('7' == $module){$label = "$labelSystemMenuBindMessageModel";}  //留言
    else if('8' == $module){$label = "$labelSystemMenuBindFaqModel";}      //Faq
    
    return $label;
  }  
}

function is_ie()
{
  $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
  if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
  if(strpos($useragent, 'msie ') !== false) return true;
  return false;
}

function fileExt($filename)
{
  return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

function file_down($filepath, $filename = '')
{
  if(!$filename) $filename = basename($filepath);
  if(is_ie()) $filename = rawurlencode($filename);
  $filetype = fileExt($filename);
  $filesize = sprintf("%u", filesize($filepath));
  if(ob_get_length() !== false) @ob_end_clean();
  header('Pragma: public');
  header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
  header('Cache-Control: no-store, no-cache, must-revalidate');
  header('Cache-Control: pre-check=0, post-check=0, max-age=0');
  header('Content-Transfer-Encoding: binary');
  header('Content-Encoding: none');
  header('Content-type: '.$filetype);
  header('Content-Disposition: attachment; filename="'.$filename.'"');
  header('Content-length: '.$filesize);
  readfile($filepath);
  exit;
}
function cache_write($file, $array, $path = '')
{
  if(!is_array($array)) return false;
  $array = "<?php\nreturn ".var_export($array, true).";\n?>";
  $cachefile = ($path ? $path : CACHE_PATH).$file;
  $strlen = file_put_contents($cachefile, $array);
  @chmod($cachefile, 0777);
  return $strlen;
}

function cache_read($file, $path = '', $iscachevar = 0)
{
  if(!$path) $path = CACHE_PATH;
  $cachefile = $path.$file;
  if($iscachevar)
  {
    global $TEMP;
    $key = 'cache_'.substr($file, 0, -4);
    return isset($TEMP[$key]) ? $TEMP[$key] : $TEMP[$key] = include $cachefile;
  }
  return include $cachefile;
}

function cache_delete($file, $path = '')
{
  $cachefile = ($path ? $path : CACHE_PATH).$file;
  return @unlink($cachefile);
}

function sqlExecute($sql)
{
  global $dbInstance;
  
  $sqls = sql_split($sql);
  ////print_r($sqls);
  if(is_array($sqls))
  {
    foreach($sqls as $sql)
    {
      if(trim($sql) != '')
      {
        //echo "$sql<br>";
        $dbInstance->query($sql);
      }
    }
  }
  else
  {
    $dbInstance->query($sqls);
  }
  return true;
}

function sql_split($sql)
{
  global $dbInstance;
  global $configDefaultDBLang;
  if($dbInstance->version() > '4.1' && $configDefaultDBLang)
  {
    $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "TYPE=\\1 DEFAULT CHARSET=".$configDefaultDBLang, $sql);
  }
  $sql = str_replace("\r", "\n", $sql);
  $ret = array();
  $num = 0;
  $queriesarray = explode(";\n", trim($sql));
  unset($sql);
  foreach($queriesarray as $query)
  {
    $ret[$num] = '';
    $queries = explode("\n", trim($query));
    $queries = array_filter($queries);
    foreach($queries as $query)
    {
      $str1 = substr($query, 0, 1);
      if($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
    }
    $num++;
  }
  return($ret);
}



function checkDateFormat($dateTime, $firstSplit='-', $secondSplit=':')
{
  $dateFormatFlag = true;
  if(!empty($dateTime))
  {
    $dateTime = trim($dateTime);//去除前后空格
    $length = strlen($dateTime);
    //19位：年月日时分秒：2010-08-20 11:26:19，16位：年月日时分：2010-08-20 11:26， 10位：年月日：2010-08-20
    if(19 == $length || 16 == $length || 10 == $length)
    {
      $arrDateTimeYMD = explode($firstSplit, substr($dateTime, 0, 10)); //获取年月日
      if(!checkdate($arrDateTimeYMD[1], $arrDateTimeYMD[2], $arrDateTimeYMD[0]))  //第一步检测年月日合法性
      {
        $dateFormatFlag = false;
      }
      else
      {
        //检测时分秒合法性
        if(19 == $length)
        {
          $arrDateTimeHSM = explode($secondSplit, substr($dateTime, 11, 8)); //获取时分秒
          if(! ereg("^[0-9]+$", $arrDateTimeHSM [0]) || ! ereg("^[0-9]+$", $arrDateTimeHSM [1]) || ! ereg("^[0-9]+$", $arrDateTimeHSM [2]) || 24 <= $arrDateTimeHSM [0] || 60 <= $arrDateTimeHSM [1] || 60 <= $arrDateTimeHSM [2])
          {
            $dateFormatFlag = false;
          }
        }
        else if(16 == $length)
        {
          $arrDateTimeHS = explode($secondSplit, substr($dateTime, 11, 5)); //获取时分
          print_r($arrDateTimeHS);
          if(! ereg("^[0-9]+$", $arrDateTimeHS [0]) || ! ereg("^[0-9]+$", $arrDateTimeHS [1]) || 24 <= $arrDateTimeHS [0] || 60 <= $arrDateTimeHS [1])
          {
            $dateFormatFlag = false;
          }
        }
      }
    }
    else
    {
      $dateFormatFlag = false;
    }
  }
  else
  {
    $dateFormatFlag = false;
  }
  return $dateFormatFlag;
}

function findNavId($id)
{
  global $configTableHead, $kuWebsiteEditVersionLanguage, $dbInstance;
  for($navType = 1; $navType <= 3; $navType ++)
  {
    $strFindFatherIdSql = "select id, fatherid from {$configTableHead}menu where id={$id} and lang='{$kuWebsiteEditVersionLanguage}';";
    $result = $dbInstance->query($strFindFatherIdSql);
    while($fatherIdRow = $dbInstance->fetchArray($result))
    {
      if (1 == $navType) //保存第一次循环的值，导航的type属性值
      {
        $temp1 = $fatherIdRow ['id'];
      }
      else if (2 == $navType)
      {
        $temp2 = $fatherIdRow ['id'];
      }
      else if (3 == $navType)
      {
        $temp3 = $fatherIdRow ['id'];
      }
      
      if (0 == $fatherIdRow ['fatherid'])
      {
        if (1 == $navType)       //需要查询是1级导航
        {
          $arrPara ['type1'] = $fatherIdRow ['id'];
        }
        else if (2 == $navType)  //需要查询是2级导航
        {
          $arrPara ['type1'] = $temp2;
          $arrPara ['type2'] = $temp1; 
        }
        else if (3 == $navType) //需要查询时3级导航
        {
          $arrPara ['type1'] = $temp3;
          $arrPara ['type2'] = $temp2;
          $arrPara ['type3'] = $temp1;
        }
        return $arrPara;
      }
      else
      {
        $id = $fatherIdRow ['fatherid'];
      }
    }
  }
  return '';
}

function createHTML($url, $savePath)
{
  global $kuWebsiteHTMLStartType, $labelCreateHTMLCreateFile, $labelCreateHTMLSuccessful, $labelCreateHTMLFail, $labelCreateHTMLNotWrite, $labelCreateHTMLWritingFail;
  $createHTMLFlag = true;
  if(1 != $kuWebsiteHTMLStartType) //开启静态页面生成
  {
    $content = file_get_contents($url);
    $handle = fopen($savePath, "w");  //以写的方式打开资源
    if (! is_writable($savePath))    //判断是否可写
    {
      echo "<font color='#FF9900'>".$labelCreateHTMLCreateFile.$labelCreateHTMLFail.$savePath.$labelCreateHTMLNotWrite."</font><br />";
      $createHTMLFlag = false;
    }
    if (! fwrite($handle, $content))   //判断是否写入成功
    {
      echo "<font color='#FF0000'>".$labelCreateHTMLCreateFile.$labelCreateHTMLFail.$savePath.$labelCreateHTMLWritingFail."</font><br />";
      $createHTMLFlag = false;
    }
    else 
    {
      //echo "<font color='#00CC00'>".$labelCreateHTMLCreateFile.$savePath.$labelCreateHTMLSuccessful."</font><br />"; 
    }
    fclose($handle);
  }
  else
  {
    $createHTMLFlag = false;
  }
  return $createHTMLFlag;
}


function transferHTMLType($kuWebsiteHTMLType)
{
  $tempKuWebsiteHTMLType;
  if(!empty($kuWebsiteHTMLType))
  {
    switch($kuWebsiteHTMLType)
    {
      case '1' :  $tempKuWebsiteHTMLType='.htm';  break;
      case '2' :  $tempKuWebsiteHTMLType='.html';  break;
      default : $tempKuWebsiteHTMLType='.html';
    }
    return $tempKuWebsiteHTMLType;
  }
}



function createModelHTML($modelDirName, $menumodule, $dbModulTableName, $isCreateShowPageHTML=1, $createflag)
{
  global $frontTempHttpPath, $frontTempAbsolutePath, $kuWebsiteTempHTMLType, $kuWebsiteHTMLStartType, $kuWebsiteEditVersionLanguage, $promptHTMLCreateHTMLSuccess, $promptHTMLCreateHTMLFail, 
          $configJumpTime, $kuWebsiteNewsPagingNumber, $dbInstance, $configTableHead ;
 
  
  $strFirstSql = "select * from {$configTableHead}menu 
        where lang='{$kuWebsiteEditVersionLanguage}' and menumodule={$menumodule} and fatherid=0 
        order by sortnum asc;";
  $firstResult = $dbInstance->query($strFirstSql);
  while($firstRow = $dbInstance->fetchArray($firstResult))
  {
    if(1 == $firstRow['menutype'])    //静态页面（只静态化内部链接，外部链接不静态化）
    {
      
      $strFirstNavSql = "select count(*) as amount from {$configTableHead}{$dbModulTableName} 
            where lang='{$kuWebsiteEditVersionLanguage}' and type1={$firstRow['id']};";
      $firstNavPageNumResult = $dbInstance->query($strFirstNavSql);
      $firstNavPageNumRow = $dbInstance->fetchArray($firstNavPageNumResult);
      $firstNavTotalNumber = $firstNavPageNumRow['amount'];
      $firstNavTotalPage = @ceil ( $firstNavTotalNumber / $kuWebsiteNewsPagingNumber );
      if(0 == $firstNavTotalPage){$firstNavTotalPage = 1;}//如果无内容，也读出页面内容
      for($page=1; $page<=$firstNavTotalPage; $page++)
      {
        $frontUrl = $frontTempHttpPath.$modelDirName."/".$modelDirName.".php?lang=".$kuWebsiteEditVersionLanguage."&menuid=".$firstRow['id']."&page=".$page;  //拼凑前台动态代码路径
//        $savePath = $frontTempAbsolutePath.$modelDirName."/".$modelDirName."_".$kuWebsiteEditVersionLanguage."_".$firstRow['id']."_".$page.$kuWebsiteTempHTMLType;  //拼凑前台静态页面路径
        if(1 == $menumodule)
        {
          if(!empty($firstRow['menuhtmlname']))//如果about数据库中menuhtmlname不为空，则静态页面名称为menuhtmlname的值
          {
            $savePath = $frontTempAbsolutePath.$modelDirName."/".$firstRow['menuhtmlname'].'_'.$kuWebsiteEditVersionLanguage.$kuWebsiteTempHTMLType;  //拼凑前台静态页面路径
          }
          else
          {
            $savePath = $frontTempAbsolutePath.$modelDirName."/".$modelDirName."_".$kuWebsiteEditVersionLanguage."_".$firstRow['id']."_".$page.$kuWebsiteTempHTMLType;  //拼凑前台静态页面路径
          }
        }
        else
        {
          $savePath = $frontTempAbsolutePath.$modelDirName."/".$modelDirName."_".$kuWebsiteEditVersionLanguage."_".$firstRow['id']."_".$page.$kuWebsiteTempHTMLType;  //拼凑前台静态页面路径
        }
        if(!createHTML($frontUrl, $savePath))  //静态页面创建出现异常，即刻终止
        {
          promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html_add", '静态页面创建失败', $configJumpTime);
          exit;
        }  
      }
    }
    
    
    $strSecondSql = "select * from {$configTableHead}menu 
        where lang='{$kuWebsiteEditVersionLanguage}' and fatherid={$firstRow['id']} 
        order by sortnum asc;";    //二级导航
    $secondResult = $dbInstance->query($strSecondSql);
    while($secondRow = $dbInstance->fetchArray($secondResult))
    {
      if(1 == $secondRow['menutype'])    //静态页面（只静态化内部链接，外部链接不静态化）
      {
        
        $strSecondNavSql = "select count(*) as amount from {$configTableHead}{$dbModulTableName} 
              where lang='{$kuWebsiteEditVersionLanguage}' and type2={$secondRow['id']};";
        $secondNavPageNumResult = $dbInstance->query($strSecondNavSql);
        $secondNavPageNumRow = $dbInstance->fetchArray($secondNavPageNumResult);
        $secondNavTotalNumber = $secondNavPageNumRow['amount'];
        $secondNavTotalPage = @ceil ( $secondNavTotalNumber / $kuWebsiteNewsPagingNumber );
        if(0 == $secondNavTotalPage){$secondNavTotalPage = 1;}//如果无内容，也读出页面内容
        for($page=1; $page<=$secondNavTotalPage; $page++)
        {
          $frontUrl = $frontTempHttpPath.$modelDirName."/".$modelDirName.".php?lang=".$kuWebsiteEditVersionLanguage."&menuid=".$firstRow['id']."&type2=".$secondRow['id']."&page=".$page;  //拼凑前台动态代码路径
//          $savePath = $frontTempAbsolutePath.$modelDirName."/".$modelDirName."_".$kuWebsiteEditVersionLanguage."_".$secondRow['id']."_".$page.$kuWebsiteTempHTMLType;  //拼凑前台静态页面路径
          if(1 == $menumodule)
          {
            if(!empty($secondRow['menuhtmlname']))//如果about数据库中menuhtmlname不为空，则静态页面名称为menuhtmlname的值
            {
              $savePath = $frontTempAbsolutePath.$modelDirName."/".$secondRow['menuhtmlname'].'_'.$kuWebsiteEditVersionLanguage.$kuWebsiteTempHTMLType;  //拼凑前台静态页面路径
            }
            else
            {
              $savePath = $frontTempAbsolutePath.$modelDirName."/".$modelDirName."_".$kuWebsiteEditVersionLanguage."_".$secondRow['id']."_".$page.$kuWebsiteTempHTMLType;  //拼凑前台静态页面路径
            }
          }
          else
          {
            $savePath = $frontTempAbsolutePath.$modelDirName."/".$modelDirName."_".$kuWebsiteEditVersionLanguage."_".$secondRow['id']."_".$page.$kuWebsiteTempHTMLType;  //拼凑前台静态页面路径
          }
          if(!createHTML($frontUrl, $savePath))  //静态页面创建出现异常，即刻终止
          {
            promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html_add", $promptHTMLCreateHTMLFail, $configJumpTime);
            exit;
          }  
        }
      }
      
      
      $strThirdSql = "select * from {$configTableHead}menu 
        where lang='{$kuWebsiteEditVersionLanguage}' and fatherid={$secondRow['id']} 
        order by sortnum asc;";    //一级导航
      $thirdResult = $dbInstance->query($strThirdSql);
      while($thirdRow = $dbInstance->fetchArray($thirdResult))
      {
        if(1 == $thirdRow['menutype'])    //静态页面（只静态化内部链接，外部链接不静态化）
        {
          
          $strThirdNavSql = "select count(*) as amount from {$configTableHead}{$dbModulTableName} 
                where lang='{$kuWebsiteEditVersionLanguage}' and type3={$thirdRow['id']};";
          $thirdNavPageNumResult = $dbInstance->query($strThirdNavSql);
          $thirdNavPageNumRow = $dbInstance->fetchArray($thirdNavPageNumResult);
          $thirdNavTotalNumber = $secondNavPageNumRow['amount'];
          $thirdNavTotalPage = @ceil ( $thirdNavTotalNumber / $kuWebsiteNewsPagingNumber );
          if(0 == $thirdNavTotalPage){$thirdNavTotalPage = 1;}//如果无内容，也读出页面内容
          for($page=1; $page<=$thirdNavTotalPage; $page++)
          {
            $frontUrl = $frontTempHttpPath.$modelDirName."/".$modelDirName.".php?lang=".$kuWebsiteEditVersionLanguage."&menuid=".$firstRow['id']."&type3=".$thirdRow['id']."&page=".$page;  //拼凑前台动态代码路径
//            $savePath = $frontTempAbsolutePath.$modelDirName."/".$modelDirName."_".$kuWebsiteEditVersionLanguage."_".$thirdRow['id']."_".$page.$kuWebsiteTempHTMLType;  //拼凑前台静态页面路径
            if(1 == $menumodule)
            {
              if(!empty($thirdRow['menuhtmlname']))//如果about数据库中menuhtmlname不为空，则静态页面名称为menuhtmlname的值
              {
                $savePath = $frontTempAbsolutePath.$modelDirName."/".$thirdRow['menuhtmlname'].'_'.$kuWebsiteEditVersionLanguage.$kuWebsiteTempHTMLType;  //拼凑前台静态页面路径
              }
              else
              {
                $savePath = $frontTempAbsolutePath.$modelDirName."/".$modelDirName."_".$kuWebsiteEditVersionLanguage."_".$thirdRow['id']."_".$page.$kuWebsiteTempHTMLType;  //拼凑前台静态页面路径
              }
            }
            else
            {
              $savePath = $frontTempAbsolutePath.$modelDirName."/".$modelDirName."_".$kuWebsiteEditVersionLanguage."_".$thirdRow['id']."_".$page.$kuWebsiteTempHTMLType;  //拼凑前台静态页面路径
            }
            if(!createHTML($frontUrl, $savePath))  //静态页面创建出现异常，即刻终止
            {
              promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html_add", $promptHTMLCreateHTMLFail, $configJumpTime);
              exit;
            }  
          }
        }
      }
    }
    
    
    if(1 == $isCreateShowPageHTML) //1：表示开启生成模块show页面的静态页面的生成
    {
      $strSql = "select * from {$configTableHead}{$dbModulTableName} where lang='{$kuWebsiteEditVersionLanguage}'";
      $result = $dbInstance->query($strSql);
      while($row = $dbInstance->fetchArray($result))
      {
        $frontUrl = $frontTempHttpPath.$modelDirName."/".$modelDirName."show.php?lang=".$kuWebsiteEditVersionLanguage."&menuid=".$row['type1']."&".$modelDirName."id=".$row['id'];  //拼凑前台动态代码路径
        $savePath = $frontTempAbsolutePath.$modelDirName."/".$modelDirName."show_".$kuWebsiteEditVersionLanguage."_".$row['id'].$kuWebsiteTempHTMLType;  //拼凑前台静态页面路径
        if(!createHTML($frontUrl, $savePath))  //静态页面创建出现异常，即刻终止
        {
          promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html_add", $promptHTMLCreateHTMLFail, $configJumpTime);
          exit;
        }
      }
    }
    
    
    if('all' != $createflag && 'message' != $createflag)
    {
      promptMessage("index.php?lang={$kuWebsiteEditVersionLanguage}&path=html&menu=html_add", $promptHTMLCreateHTMLSuccess, $configJumpTime);
      exit;
    }
  }        
}


function deleteFile($fileDirPath, $fileExtFormat, $lang='cn')
{
  if(is_dir($fileDirPath))  
  {
    $dh = opendir($fileDirPath);  
    while(($file = readdir($dh)) !== false)  
    {
      if($file != '.' && $file != '..')  
      {
        if(!is_dir($fileDirPath.'/'.$file))  
        {
          $tempStr = strstr($file, '_'.$lang);
          if(!empty($tempStr))
          {
            $fileExt = strtolower(trim(substr(strrchr($file, '.'), 1, 10)));
            if($fileExt == strtolower($fileExtFormat))
            {
              @chmod($fileDirPath.'/'.$file, 0777);        
              if(!@unlink($fileDirPath.'/'.$file))      
              {
                return false;
              }
            } 
          }
        }
      }
    }
    closedir($dh); 
  }
  else
  {
    return false;
  }
  return true;
}


function removeXSS($val) {
   // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
   // this prevents some character re-spacing such as <java\0script>
   // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
   $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
   // straight replacements, the user should never need these since they're normal characters
   // this prevents like <IMG SRC=@avascript:alert('XSS')>
   $search = 'abcdefghijklmnopqrstuvwxyz';
   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
   $search .= '1234567890!@#$%^&*()';
   $search .= '~`";:?+/={}[]-_|\'\\';
   for ($i = 0; $i < strlen($search); $i++) {
      // ;? matches the ;, which is optional
      // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars

      // @ @ search for the hex values
      $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
      // @ @ 0{0,7} matches '0' zero to seven times
      $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
   }

   // now the only remaining whitespace attacks are \t, \n, and \r
   $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
   $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
   $ra = array_merge($ra1, $ra2);

   $found = true; // keep replacing as long as the previous round replaced something
   while ($found == true) {
      $val_before = $val;
      for ($i = 0; $i < sizeof($ra); $i++) {
         $pattern = '/';
         for ($j = 0; $j < strlen($ra[$i]); $j++) {
            if ($j > 0) {
               $pattern .= '(';
               $pattern .= '(&#[xX]0{0,8}([9ab]);)';
               $pattern .= '|';
               $pattern .= '|(&#0{0,8}([9|10|13]);)';
               $pattern .= ')*';
            }
            $pattern .= $ra[$i][$j];
         }
         $pattern .= '/i';
         $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
         $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
         if ($val_before == $val) {
            // no replacements were made, so exit the loop
            $found = false;
         }
      }
   }
   return $val;
}

?>