<?php


/**
 * @author Marijuana
 */
class sqlutility
{
  var $sql = array();
  var $create = array();
  var $dirname;
  var $safetables = array(
    'avatar',
    'avatar_user_link',
    'block_module_link',
    'config',
    'configcategory',
    'configoption',
    'group_permission',
    'groups',
    'groups_users_link',
    'modules',
    'newblocks',
    'users');
  
  
  function sqlutility($dirname,$file)
  {
    $this->dirname = $dirname;
    $i = 0;

	//
	// If sql file is created in Mac OS, file() can not detect the line end.
	//    
    ini_set("auto_detect_line_endings" ,true);
    $sql_query = file(XOOPS_MODULE_PATH.'/'.$dirname.'/'.$file);

    $pattern = "/^(INSERT INTO|CREATE TABLE|UPDATE)(\s)+/siU";
    foreach ( $sql_query as $fline ) {
      $fline=trim($fline);
      if ( preg_match($pattern,$fline) ) {
        $i++;
        $this->sql[$i] = trim($fline)."\n";
      } elseif (strlen($fline)>0 && strpos($fline,"#")===false) {
		if(isset($this->sql[$i])) {
			$this->sql[$i] .= trim($fline)."\n";
		}
		else {
			$this->sql[$i] = trim($fline)."\n";
		}
      }
    }
    
    foreach ( $this->sql as $i => $sql ) {
      $sql = $this->prefix($sql);
      $this->sql[$i] = $this->etcchange($sql);
    }
  }
  
  function prefix($sql)
  {
    $pattern = "/^(INSERT INTO|CREATE TABLE|UPDATE)(\s)+([`]?)([^`\s]+)\\3(\s)+/siU";
    if ( preg_match($pattern, $sql, $matches) ) {
      $replace = "\\1 ".XOOPS_DB_PREFIX."_\\4\\5";
      $sql = preg_replace($pattern, $replace, $sql);
      if ( preg_match("/^CREATE TABLE/siU", $sql) && !in_array($matches[4],$this->safetables) ) {
        $this->create[] = $matches[4];
      }
    }
    return $sql;
  }
  
  function etcchange($sql)
  {
    $patterns[] = '{dirname}';
    $replacements[] = $this->dirname;
    $sql = str_replace($patterns,$replacements,$sql);
    $sql = preg_replace('/;\s*$/s','',$sql);
    return $sql;
  }
  
  function get_sql()
  {
    return $this->sql;
  }
  
  function get_create()
  {
    return $this->create;
  }
  
  /*
  function changesql($dirname,$file)
  {
    $sql = array();
    $i = 0;
    $sql_query = file(ORETEKI_ROOT_PATH.'/modules/'.$dirname.'/'.$file);
    $pattern = "/^(INSERT INTO|CREATE TABLE|UPDATE)/siU";
    foreach ( $sql_query as $fline ) {
      if ( preg_match($pattern,$fline) ) {
        $i++;
        $sql[$i] = trim($fline)."\n";
      } else {
        $sql[$i].= trim($fline)."\n";
      }
    }
    
    $pattern = "/^(INSERT INTO|CREATE TABLE|UPDATE)(\s)+([`]?)([^`\s]+)\\3(\s)+/siU";
    foreach ( $sql as $i => $query ) {
      if ( preg_match($pattern, $query, $matches) ) {
        $replace = "\\1 ".ORETEKI_DB_PREFIX."_\\4\\5";
        $sql[$i] = preg_replace($pattern, $replace, $query);
      }
    }
    $patterns[] = '{dirname}';
    $replacements[] = $dirname;
    $sql = str_replace($patterns,$replacements,$sql);
    return $sql;
  }
  */
}
?>