<?php
 
function template($tFile, $tPath='')
{
  global $kuTemplateName;
  if('' == $tPath)$tPath = ($kuTemplateName ? $kuTemplateName : 'default');
  $tFileNew = preg_replace( '/\.html$/', '', $tFile);
  $tFile = KUWEBS_TEMPLATE_PATH.'/'.$tPath.'/'.$tFileNew.'.html';
  $cFile = KUWEBS_COMPILED_PATH.'/'.$tPath.'/'.$tFileNew.'.php';
  
  if(!file_exists($tFile))die("Template File $tFile Not Exist!!");
  if(!file_exists(dirname($cFile)))
  {
    if(!mkdir(dirname($cFile)))die("No");
  }
  
  if(!file_exists($cFile) || @filemtime($tFile) > @filemtime($cFile))
  {
    $tContent = file_get_contents($tFile);
    $tContent = template_parse($tContent);
    file_put_contents($cFile, $tContent);
  }
  return $cFile;
}

function template_parse($str) 
{
  $str = preg_replace( '/^(\xef\xbb\xbf)/', '', $str ); //EFBBBF   
  $str = preg_replace("/\<\!\-\-\s*\\\$\{(.+?)\}\s*\-\-\>/ies", "template_replace('<?php \\1; ?>')", $str);
  $str = preg_replace("/\{(\\\$[a-zA-Z0-9_\[\]\\\ \-\'\,\%\*\/\.\(\)\>\'\"\$\x7f-\xff]+)\}/s", "<?php echo \\1; ?>", $str);
  $str = preg_replace("/\\\$\{(.+?)\}/ies", "template_replace('<?php echo \\1; ?>')", $str);
  $str = preg_replace("/\<\!\-\-\s*\{else\s*if\s+(.+?)\}\s*\-\-\>/ies", "template_replace('<?php } else if(\\1) { ?>')", $str);
  $str = preg_replace("/\<\!\-\-\s*\{elif\s+(.+?)\}\s*\-\-\>/ies", "template_replace('<?php } else if(\\1) { ?>')", $str);
  $str = preg_replace("/\<\!\-\-\s*\{else\}\s*\-\-\>/is", "<?php } else { ?>", $str);

  for($i = 0; $i < 5; ++$i) 
  {
    $str = preg_replace("/\<\!\-\-\s*\{loop\s+(\S+)\s+(\S+)\s+(\S+)\s*\}\s*\-\-\>(.+?)\<\!\-\-\s*\{\/loop\}\s*\-\-\>/ies", "template_replace('<?php if(is_array(\\1)){foreach(\\1 AS \\2=>\\3) { ?>\\4<?php }}?>')", $str);
    $str = preg_replace("/\<\!\-\-\s*\{loop\s+(\S+)\s+(\S+)\s*\}\s*\-\-\>(.+?)\<\!\-\-\s*\{\/loop\}\s*\-\-\>/ies", "template_replace('<?php if(is_array(\\1)){foreach(\\1 AS \\2) { ?>\\3<?php }}?>')", $str);
    $str = preg_replace("/\<\!\-\-\s*\{if\s+(.+?)\}\s*\-\-\>(.+?)\<\!\-\-\s*\{\/if\}\s*\-\-\>/ies", "template_replace('<?php if(\\1){?>\\2<?php }?>')", $str);
  }

  //Add for call <!--{include othertpl}-->
  $str = preg_replace("#<!--\s*{\s*include\s+([^\{\}]+)\s*\}\s*-->#i", '<?php include_once template("\\1");?>', $str);
  
  return $str;
}

function template_replace($string) {
  return str_replace('\"', '"', $string);
}



class CommTool
{
  

  
  static function cutstrutf8($string, $length, $code='utf-8') 
  {
        $content = mb_substr($string, 0, $length, $code);
        if(CommTool::utf8_strlen($string) > $length)$content .= "...";
        return $content;
  }
  
  static function utf8_strlen($string = null) 
  {
    
    preg_match_all("/./us", $string, $match);
    // 返回单元个数
    return count($match[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)
  {
    $mNowTime = time();
    $fNowTime = date('Y-m-d H:i:s', $mNowTime); 
    $strLog = "[$fNowTime]: ".$str;
    $strOldFile = file_get_contents('log/admin.log');
    $strNewFile = $strOldFile.$strLog."\n";
    file_put_contents('log/admin.log', $strNewFile);
  }  
  
  
  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($str == addslashes("$str") && !ereg("[\}{\[\&\^\%\$\#\@\!\;\:\~\`\；\：\‘\“\”\，\。\？\／\）\（\＊\—\…\％\￥\＃\·\！\～\…\｀\,\.\?\<\>\*\(\)\+\_\=\/\ˇ\¨\〃\々\‖\〈\〉\《\》\「\」\『\』\〖\〗\【\】\±\-]","$str") && !strpos("$str","]")) return true;
    else 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');
    
    $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($fileName) 
  {
    if(file_exists($fileName)) 
    {
      @chmod($fileName,0777);
      $areaLord = @unlink($fileName);
    }
    return $areaLord;
  }
  
  
  static function getCurrPageURL() 
  {
    $pageURL = 'http';
    if ($_SERVER["HTTPS"] == "on") 
    {
      $pageURL .= "s";
    }
    $pageURL .= "://";

    if ($_SERVER["SERVER_PORT"] != "80") 
    {
      $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } 
    else 
    {
      $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
  }
}

class MenuTool
{
  static function showNav($nav)
  {
    if('1' == $nav){$label = "都不显示";}
    else if('2' == $nav){$label = "主导航栏显示";}
    else if('3' == $nav){$label = "底部导航栏显示";}
    else if('4' == $nav){$label = "都显示";}
    else{$label = "不显示";}
    
    return $label;
  }
  
  static function showType($type)
  {
    if('1' == $type){$label = "内部栏目";}
    else if('2' == $type){$label = "外部链接";}
    else{$label = "内部栏目";}
    
    return $label;
  }
  
  static function showModule($module)
  {
    global $labelChangePasswordTitle;
    if('1' == $module){$label = "$labelChangePasswordTitle";}
    else if('2' == $module){$label = "新闻";}
    else if('3' == $module){$label = "产品";}
    else if('4' == $module){$label = "图片";}
    else if('5' == $module){$label = "下载";}
    else if('6' == $module){$label = "招聘";}
    else if('7' == $module){$label = "留言";}
    else if('8' == $module){$label = "常见问题";}
    
    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 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 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 findMenuFatherId($id)
{
  global $configTableHead, $kuWebsiteCurrLanguage, $dbInstance;
  for($navType = 1; $navType <= 3; $navType ++)
  {
    $strFindFatherIdSql = "select id, fatherid from {$configTableHead}menu where id={$id} and lang='{$kuWebsiteCurrLanguage}';";
    $result = $dbInstance->query($strFindFatherIdSql);
    while($fatherIdRow = $dbInstance->fetchArray($result))
    {
      if (1 == $navType) 
      {
        $temp1 = $fatherIdRow ['id'];
      }
      else if (2 == $navType)
      {
        $temp2 = $fatherIdRow ['id'];
      }
      else if (3 == $navType)
      {
        $temp3 = $fatherIdRow ['id'];
      }
      
      if (0 == $fatherIdRow ['fatherid'])
      {
        $arrPara ['menuid'] = $fatherIdRow ['id']; 
        if (1 == $navType)       
        {
          $arrPara ['type1'] = $fatherIdRow ['id'];
        }
        else if (2 == $navType)  
        {
          $arrPara ['type1'] = $temp2;
          $arrPara ['type2'] = $temp1; 
        }
        else if (3 == $navType) 
        {
          $arrPara ['type1'] = $temp3;
          $arrPara ['type2'] = $temp2;
          $arrPara ['type3'] = $temp1;
        }
        return $arrPara;
      }
      else
      {
        $id = $fatherIdRow ['fatherid'];
      }
    }
  }
  return '';
}


function getMenuIdInfo($id)
{
    if('' == $id || 0 > $id)return;
    global $configTableHead, $kuWebsiteCurrLanguage, $dbInstance;
    $strSql = "select id, fatherid from {$configTableHead}menu where id={$id};";
    $row1 = $dbInstance->getOne($strSql);
    if(!is_array($row1))return;
    if(0 == intval($row1['fatherid']))
    {
        $arrInfo['level'] = 1;
        $arrInfo['type1'] = $id;
        $arrInfo['type2'] = '';
        $arrInfo['type3'] = '';
        return $arrInfo;
    }
    
    $strSql = "select id, fatherid from {$configTableHead}menu where id={$row1[fatherid]};";
    $row2 = $dbInstance->getOne($strSql);
    if(!is_array($row2))return;
    if(0 == intval($row2['fatherid']))
    {
        $arrInfo['level'] = 2;
        $arrInfo['type1'] = $row1['fatherid'];
        $arrInfo['type2'] = $id;
        $arrInfo['type3'] = '';
        return $arrInfo;
    }

    $strSql = "select id, fatherid from {$configTableHead}menu where id={$row2[fatherid]};";
    $row3 = $dbInstance->getOne($strSql);
    if(!is_array($row3))return;
    if(0 == intval($row3['fatherid']))
    {
        $arrInfo['level'] = 3;
        $arrInfo['type1'] = $row2['fatherid'];
        $arrInfo['type2'] = $row1['fatherid'];
        $arrInfo['type3'] = $id;
        return $arrInfo;
    }
    return;
}

function getSqlOrderByOfSortType($sortType)
{
  $str = "";
  switch($sortType)
  {
    case 11 : $str = ' addtime desc ';
    case 21 : $str = ' updatetime desc ';
    case 31 : $str = ' clicknum desc ';
    case 12 : $str = ' updatetime asc ';
    case 22 : $str = ' addtime asc ';
    case 32 : $str = ' clicknum asc ';
    default : $str = ' addtime desc ';
  }
    return ' sortnum asc, '.$str;
}


function getPagingUrl($menuid, $type2, $type3, $modelDirName)
{
  global $kuWebsiteCurrLanguage, $instancePage, $kuWebsiteHTMLStartType;
  $arrNavPaging = array();
  if(!empty($menuid) && empty($type2) && empty($type3))     
  {
    if(1 == $kuWebsiteHTMLStartType)  
    {
      $kuFirstNavPaging = $instancePage->disp('page', $modelDirName.".php?lang={$kuWebsiteCurrLanguage}&menuid={$menuid}"); 
    }
    else    
    {
      $kuFirstNavPaging = $instancePage->disp('page', $modelDirName."_".$kuWebsiteCurrLanguage."_".$menuid); 
    }
    $arrNavPaging['kuFirstNavPaging'] = $kuFirstNavPaging;
  }      
  else if(!empty($menuid) && !empty($type2))    
  {
    if(1 == $kuWebsiteHTMLStartType)  
    {
      $kuSecondNavPaging = $instancePage->disp('page', $modelDirName.".php?lang={$kuWebsiteCurrLanguage}&menuid={$menuid}&type2={$type2}"); 
    }
    else    
    {
      $kuSecondNavPaging = $instancePage->disp('page', $modelDirName."_".$kuWebsiteCurrLanguage."_".$type2);
    }
    $arrNavPaging['kuSecondNavPaging'] = $kuSecondNavPaging;  
  }
  else if(!empty($menuid) && !empty($type3))     
  {
    if(1 == $kuWebsiteHTMLStartType)  
    {
      $kuThirdNavPaging = $instancePage->disp('page', $modelDirName.".php?lang={$kuWebsiteCurrLanguage}&menuid={$menuid}&type3={$type3}"); 
    }
    else    
    {
      $kuThirdNavPaging = $instancePage->disp('page', $modelDirName."_".$kuWebsiteCurrLanguage."_".$type3);
    }
    $arrNavPaging['kuThirdNavPaging'] = $kuThirdNavPaging;  
  }
  return $arrNavPaging;
}

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 getPreNext($module, $itemid, $lang='')
{
    global $dbInstance, $kuWebsiteCurrLanguage, $kuHttpPath, $configTableHead;
    global $kuCaptionCommonPre, $kuCaptionCommonNotExist, $kuCaptionCommonNext;
    $strPreNext = "";
    
    $getLang = $lang ? $lang : $kuWebsiteCurrLanguage;
    $strSql = "select * from {$configTableHead}{$module} where lang='$getLang' and id<'{$itemid}' and status>0 order by id desc limit 1;";
    $rowPre = $dbInstance->getOne($strSql);
    if('' == $rowPre[$module.'title'])
    {
        $strPreNext = "<div class='pre'>{$kuCaptionCommonPre}{$kuCaptionCommonNotExist}</div>";
    }
    else
    {
        $preTitle = $rowPre[$module.'title'];
        $preUrl = $kuHttpPath."{$module}/{$module}.php?lang={$kuWebsiteCurrLanguage}&itemid={$rowPre['id']}";
        $strPreNext = "<div class='pre'>{$kuCaptionCommonPre}<a href='{$preUrl}' title='{$preTitle}'>{$preTitle}</a></div>";
    }

    $strSql = "select * from {$configTableHead}{$module} where lang='$getLang' and id>'{$itemid}' and status>0 order by id asc limit 1;";
    $rowNext = $dbInstance->getOne($strSql);
    if('' == $rowNext[$module.'title'])
    {
        $strPreNext .= "<div class='next'>{$kuCaptionCommonNext}{$kuCaptionCommonNotExist}</div>";
    }
    else
    {
        $nextTitle = $rowNext[$module.'title'];
        $nextUrl = $kuHttpPath."{$module}/{$module}.php?lang={$kuWebsiteCurrLanguage}&itemid={$rowNext['id']}";
        $strPreNext .= "<div class='next'>{$kuCaptionCommonNext}<a href='{$nextUrl}' title='{$nextTitle}'>{$nextTitle}</a></div>";
    }
    return $strPreNext;
}


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;
}


function filterSearch($keyword)
{
  $keyword = ereg_replace("[\"\r\n\t\$\\><'/]",'',$keyword);
  if($keyword != stripslashes($keyword))
  {
    return '';
  }
  else
  {
    return $keyword;
  }
  return $restr;
}
?>