<?php
class InstallTool
{
  static function getFileContent($filePath, $method = 'rb')
  {
    if (!file_exists($filePath))
    {
?>
<script type="text/javascript">
alert('对不起，数据库建立失败，SQL语句脚本不存在，install/kuwebs.sql不存在，请重新安装。');
location.href='javascript:history.go(-1)';
exit;
</script>
<?php      
    }
    if ($handle = fopen($filePath, $method))
    {
      flock($handle, LOCK_SH); //排它锁
      $fileContent = @fread($handle, filesize($filePath));
      fclose($handle); //解锁
    }
    return $fileContent;
  }
  
  //根据$content创建数据库表
  static function createTable($fileContent, $dbPrefix)
  {
    global $setUp, $installInfo;
    $installInfo = array();
    $query = '';
    $setUp = ''; //标记SQL执行错误跳转方向  
    $array = explode("\n", $fileContent);
    $tableIndex = 0;
    foreach ( $array as $key => $value )
    {
      $value = trim($value); //去掉$value两头的空格
      if (! $value || '#' == $value) //去掉空行和注释代码
      {
        continue; //跳出本次循环
      }
      if (eregi("\;$", $value)) //匹配以分号结尾的
      {
        $query .= $value; //拼接完整的SQL来创建数据库中一张表  
        if (eregi("^CREATE", $query))
        {
          //echo $query."<br />";
          $tableName = substr($query, 13, strpos($query, '(') - 13);
          //echo $tableName;
          //exit;
          $createTableName = str_replace('kuwebs_', $dbPrefix, $tableName);
        }
        $query = str_replace('kuwebs_', $dbPrefix, $query); //sql语句替换表前缀
        @mysql_query("SET NAMES 'utf8'");
        if (! mysql_query($query)) //执行数据库表的创建，失败返回false
        {
      
          $setUp = '';
      /*
          if (0 == $tableIndex)
          {
      */  
            $installInfo ['error'] .= '<li><font color="red">Error:' . mysql_error() . '<br/>sql:' . $query . '</font></li>';
          /*
      }
      */
        }
        else
        {
          $tableIndex ++;
          $setUp = 'dbFillIn';
          if (eregi("^CREATE", $query))
          {
            $installInfo ['correct'] .= '<li><font color="#0000EE">create table' . ' </font>' . $createTableName . ' ... <font color="#0000EE">finish</font></li>';
          }
          $query = '';
        }
      }
      else
      {
        $query .= $value;
      }
    }
    return $installInfo;
  }
}
?>
