<? /*

Common library script for Intellect Board 2

(c) 2004, XXXX Pro, United Open Project
Visit us online: http://intboard.ru
*/

if (!$IBOARD) die ("Hack attempt!");

$GLOBALS['common']=1;

return;

function check_post() {
  if ($_SERVER['REQUEST_METHOD']!="POST") global_error('HACK ATTEMPT! Only POST method allowed here!');
}

function load_style($file) {
    $link=$GLOBALS['link'];
    if (file_exists($GLOBALS['opt_dir']."/styles/".$GLOBALS['inuser']['st_file']."/".$file)) {
      require_once($GLOBALS['opt_dir']."/styles/".$GLOBALS['inuser']['st_file']."/".$file);
    }
    else {
      $dir=$GLOBALS['inuser']['st_parent'];
      $curdir=$GLOBALS['opt_dir']."/styles/".$dir."/";
      while ($dir && !file_exists($curdir.$file)) {
        $sql = "SELECT st_parent FROM ".$GLOBALS['DBprefix']."StyleSet WHERE st_file=\"$dir\"";
        $res=db_query($sql,$link);
        list($dir)=db_fetch_row($res);
        $curdir=$GLOBALS['opt_dir']."/styles/".$dir."/";
      }
      if (file_exists($curdir.$file)) require_once($curdir.$file);
      else global_error("File not found in styles: $file");
    }
}

function load_lang($file) {
    require_once ($GLOBALS['opt_dir']."/langs/".$GLOBALS['inuser']['ln_file']."/".$file);
}

function build_msg_select($sql,$value="") {
    $res = db_query($sql,$GLOBALS['link']);
    $tmp = "";
    while ($tmpdata=db_fetch_row($res)) {
        if ($tmpdata[0]==$value) $tmp.="<option value=\"".$tmpdata[0]."\" selected>".constant($tmpdata[1]);
        else $tmp.="<option value=\"".$tmpdata[0]."\">".constant($tmpdata[1]);
    }
    db_free_result($res);
    return $tmp;
}

function build_forum_select($level,$tpid=0,$condition="",$select="") {
    if ($condition) $condition=" AND ($condition)";
    $link = $GLOBALS['link'];
    $uid = $GLOBALS['inuserid'];
    if ($tpid) $tpidsql = " f_tpid=".$tpid." AND ";
    $sql="SELECT f_id,f_title,ct_name FROM ".$GLOBALS['DBprefix']."Forum f, ".$GLOBALS['DBprefix']."Category ct ".
    "LEFT JOIN ".$GLOBALS['DBprefix']."UserAccess ua ON (ua.uid=$uid AND ua.fid=f.f_id) ".
    "WHERE $tpidsql IFNULL(ua_level,".$GLOBALS['inuserbasic'].")>=$level AND f_ctid=ct_id $condition".
    " ORDER BY ct_sortfield, f_sortfield";
    $res = db_query($sql,$GLOBALS['link']);
    $flist = "";
    $oldcat = "0";
    while ($tmpdata=db_fetch_row($res)) {
        if ($tmpdata[2]!=$oldcat) {
          if ($flist) $flist.="</OPTGROUP>";
          $flist.="<OPTGROUP label=\"".$tmpdata[2]."\">";
          $oldcat=$tmpdata[2];
        }
        if ($tmpdata[0]==$value) $flist.="<option value=\"".$tmpdata[0]."\" selected>".$tmpdata[1];
        else $flist.="<option value=\"".$tmpdata[0]."\">".$tmpdata[1];
    }
    db_free_result($res);
    $flist.="</optgroup>";
    return $flist;
}

function build_level_select() {
    $sql = "SELECT * FROM ".$GLOBALS['DBprefix']."UserLevel ORDER BY l_level";
    return build_select($sql,$udata['u__level']);
}

function build_userlevel_select($level=0) {
    $sql = "SELECT * FROM ".$GLOBALS['DBprefix']."UserLevel WHERE l_level!=0 AND l_level<1024";
    return build_select($sql,$level);
}

function error($errmsg) {
    if (!$GLOBALS['admin']) load_style("message.php");
    $tmp_link1 = "<a href=\"".$_SERVER['HTTP_REFERER']."\">".MSG_go_back."</a>";
    $tmp_link2 = "<a href=\"index.php\">".MSG_go_mainpage."</a>";
    output_message(MSG_e.$errmsg,$tmp_link1,$tmp_link2,"");
    exit();
}

function message($textmsg,$golink=0) {
    if ($_POST['refpage'])    $tmp_link1 = $_POST['refpage'];
    elseif ($GLOBALS['refpage']) $tmp_link1 = $GLOBALS['refpage'];
    elseif ($_SERVER['HTTP_REFERER']) $tmp_link1 =$_SERVER['HTTP_REFERER'];
    else $tmp_link1 = "javascript:document.history(-1)";
    $tmp_link2 = "<a href=\"index.php\">".MSG_go_mainpage."</a>";
    if ($golink) $newlink=$tmp_link1;
    output_message($textmsg,"<a href=\"$tmp_link1\">".MSG_go_back."</a>",$tmp_link2,"",$newlink);
}

function topic_message($textmsg,$golink=0) {
    $tmp_message = $textmsg;
    $tmp_link1 = "<a href=\"index.php?f=".$GLOBALS['forum']."&t=".$GLOBALS['topic']."\">".MSG_go_topic."</a>";
    $tmp_link2 = "<a href=\"index.php?f=".$GLOBALS['forum']."\">".MSG_go_forum."</a>";
    $tmp_link3 = "<a href=\"index.php\">".MSG_go_mainpage."</a>";
    if ($golink) $newlink="index.php?f=".$GLOBALS['forum']."&t=".$GLOBALS['topic'];
    output_message($tmp_message,$tmp_link1,$tmp_link2,$tmp_link3,$newlink);
}

function month_replace($date) {
  $date=str_replace("January",MSG_January,$date);
  $date=str_replace("February",MSG_February,$date);
  $date=str_replace("March",MSG_March,$date);
  $date=str_replace("April",MSG_April,$date);
  $date=str_replace("May",MSG_May,$date);
  $date=str_replace("June",MSG_June,$date);
  $date=str_replace("July",MSG_July,$date);
  $date=str_replace("August",MSG_August,$date);
  $date=str_replace("September",MSG_September,$date);
  $date=str_replace("October",MSG_October,$date);
  $date=str_replace("November",MSG_November,$date);
  $date=str_replace("December",MSG_December,$date);
  $date=str_replace("Jan",MSG_Jan,$date);
  $date=str_replace("Feb",MSG_Feb,$date);
  $date=str_replace("Mar",MSG_Mar,$date);
  $date=str_replace("Apr",MSG_Apr,$date);
  $date=str_replace("May",MSG_May,$date);
  $date=str_replace("Jun",MSG_Jun,$date);
  $date=str_replace("Jul",MSG_Jul,$date);
  $date=str_replace("Aug",MSG_Aug,$date);
  $date=str_replace("Sep",MSG_Sep,$date);
  $date=str_replace("Oct",MSG_Oct,$date);
  $date=str_replace("Nov",MSG_Nov,$date);
  $date=str_replace("Dec",MSG_Dec,$date);
  return $date;
}

function long_date_out($date) {
  $date=$date+$GLOBALS['inuser']['u_timeregion']-$GLOBALS['opt_timeregion'];
  if ($date<0) $date=0;
  if ($date) $date=date($GLOBALS['inuser']['u_lformat'],$date);
  else $date=MSG_none;
  return month_replace($date);
}

function short_date_out($date) {
  $date=$date+$GLOBALS['inuser']['u_timeregion']-$GLOBALS['opt_timeregion'];
  if ($date<0) $date=0;
  if ($date) $date=date($GLOBALS['inuser']['u_sformat'],$date);
  else $date=MSG_none;
  return month_replace($date);
}

function addlinks(&$text) {
 $text = "  ".$text."  ";
 $text = str_replace("<"," <",$text);
 $text = str_replace(">","> ",$text);
 $text = preg_replace("/\n/","",$text);
 $text = preg_replace("/\r/","",$text);
 $text = preg_replace("/ ([^:\t \n\[]+?\@[^\t \n\[]+?) /is","  <a href=\"mailto:$1\">$1</a>  ",$text);
 $text = preg_replace("/ (http:\/\/\S+?) /is","  <a href=\"$1\" target=_blank>$1</a>  ",$text);
 $text = preg_replace("/ (www\.\S+?) /is","  <a href=\"http://$1\" target=_blank>$1</a>  ",$text);
 $text = preg_replace("/ ([\w-\.]+?\.ru) /is","  <a href=\"http://$1\" target=_blank>$1</a>  ",$text);
 $text = preg_replace("/ ([\w-\.]+?\.com) /is","  <a href=\"http://$1\" target=_blank>$1</a>  ",$text);
 $text = preg_replace("/ ([\w-\.]+?\.net) /is","  <a href=\"http://$1\" target=_blank>$1</a>  ",$text);
 $text = preg_replace("/ ([\w-\.]+?\.org) /is","  <a href=\"http://$1\" target=_blank>$1</a>  ",$text);
 $text = str_replace(" <","<",$text);
 $text = str_replace("> ",">",$text);
}

function check_hidden($posts,$text) {
  if (!$GLOBALS['inuserposts'] && $GLOBALS['inuserid']>3) {
    $link=$GLOBALS['link'];
    $sql = "SELECT COUNT(*) FROM ".$GLOBALS['DBprefix']."Post WHERE p_uid=".$GLOBALS['inuserid']." AND p__premoderate=0";
    $res = db_query($sql,$link);
    list($count)=db_fetch_row($res);
    db_free_result($res);
    $GLOBALS['inuserposts']=$count;
  }
  if ($posts<=$GLOBALS['inuserposts']) return $text;
  else return "<hr width=80% align=left>".MSG_p_posthide." ".format_word($posts,MSG_p1,MSG_p2,MSG_p3).".<hr width=80% align=left>";
}

function check_level($level,$text) {
  if ($level<=$GLOBALS['inuserlevel']) return $text;
  else return "<hr width=80% align=left>".MSG_p_levelhide.".<hr width=80% align=left>";
}

function check_url($url) {
  $url=strtolower($url);
  $res=1;
  if (strpos($url,"script:")!==false) $res=0;
  if (strpos($url,"/admin")===0) $res=0;
  $forumurl=strtolower($GLOBALS['opt_url']);
  $forumurl=str_replace("www.","",$forumurl);
  $forumurl=preg_replace("|/$|s","",$forumurl);
  $url=str_replace("www.","",$url);
  if (strpos($url,$forumurl."/admin")!==false) $res=0;
  if (strpos($url,"a=do_logout")!==false) $res=0;
  if (strpos($url,"\"")!==false) $res=0;
  return $res;
}

function check_img($imgtext) {
  $imgtext=stripslashes($imgtext);
  preg_match("/src=\"([^\"]+?)\"[\s>]/is",$imgtext,$matches);
  if (!$matches[1]) preg_match("/src='([^']+?)'[\s>]/is",$imgtext,$matches);
  if (!$matches[1]) preg_match("/src=(\S+?)/is",$imgtext,$matches);
  $tmptext=str_replace($matches[1],"",$imgtext);
  if (preg_match("/\Won\w+?=/is",$tmptext) || preg_match("/\Wurl\(/is",$tmptext)) {
    $GLOBALS['hackattempt']++;
    return "<br><font color=red><b>HACK ATTEMPT:</b> ".htmlspecialchars($imgtext)."</font><br>";
  }
  $imgtext=preg_replace("|<(img .*?)>|is","<$1 onLoad=\"ch_img(this)\">",$imgtext);
  if (check_url($matches[1])) return $imgtext;
  else {
    $GLOBALS['hackattempt']++;
    return "<br><font color=red><b>HACK ATTEMPT:</b> ".$matches[1]."</font><br>";
  }
}

function check_link($linktext) {
  $linktext=stripslashes($linktext);
  preg_match("/href=\"([^\"]+?)\"[\s>]/is",$linktext,$matches);
  if (!$matches[1]) preg_match("/href='([^']+?)'[\s>]/is",$linktext,$matches);
  if (!$matches[1]) preg_match("/href=(\S+?)[\s>]/is",$linktext,$matches);
  $tmptext=str_replace($matches[1],"",$linktext);
  if (preg_match("/\Won\w+?=/is",$tmptext) || preg_match("/\Wurl\(/is",$tmptext)) {
    $GLOBALS['hackattempt']++;
    return "<br><font color=red><b>HACK ATTEMPT:</b> ".htmlspecialchars($linktext)."</font><br>";
  }
  if (check_url($matches[1])) return $linktext;
  else {
    $GLOBALS['hackattempt']++;
    return "<br><font color=red><b>HACK ATTEMPT:</b> ".$matches[1]."</font><br>";
  }
}

function boardcode(&$text) {
 if (strpos($text,"[")!==false) {
  $text = str_replace("[hr]","<hr width=50% align=left>",$text);
  $text = str_replace("[br]","<br>",$text);

  $text = preg_replace("/\[quote\](.*?)\[\/quote\]/is","<table style=\"quote\" width=80% border=1 cellspacing=0 cellpadding=0><tr><td class=\"quote\">$1</td></tr></table>",$text);
  $text = preg_replace("/\[q\](.*?)\[\/q\]/is","<table style=\"quote\" width=80% border=1 cellspacing=0 cellpadding=0><tr><td class=\"quote\">$1</td></tr></table>",$text);
  $text = preg_replace("/\[quote=(.+?)\](.*?)\[\/quote\]/is","$1 ".MSG_written.":<table style=\"quote\" width=80% border=1 cellspacing=0 cellpadding=0><tr><td class=\"quote\">$2</td></tr></table>",$text);//.short_date_out($2)."
  $text = preg_replace("/\[q=(.+?)\](.*?)\[\/q\]/is","$1 ".MSG_written.":<table style=\"quote\" width=80% border=1 cellspacing=0 cellpadding=0><tr><td class=\"quote\">$2</td></tr></table>",$text);
  $text = preg_replace("/\[q(\d+)\](.*?)\[\/q$1\]/is","<table style=\"quote$1\" width=80% border=1 cellspacing=0 cellpadding=0><tr><td class=\"quote2\">$2</td></tr></table>",$text);

  $text = preg_replace("/\[url\](http:\/\/[^\"]+?)\[\/url\]/is","<a href=\"$1\" target=_blank>$1</a>",$text);
  $text = preg_replace("/\[url\](https:\/\/[^\"]+?)\[\/url\]/is","<a href=\"$1\" target=_blank>$1</a>",$text);
  $text = preg_replace("/\[url\](ftp:\/\/[^\"]+?)\[\/url\]/is","<a href=\"$1\" target=_blank>$1</a>",$text);
  $text = preg_replace("/\[url\]([^\"]+?)\[\/url\]/is","<a href=\"http://$1\" target=_blank>$1</a>",$text);
  $text = preg_replace("/\[url=(http:\/\/[^\"]+?)\](.+?)\[\/url\]/is","<a href=\"$1\" target=_blank>$2</a>",$text);
  $text = preg_replace("/\[url=(https:\/\/[^\"]+?)\](.+?)\[\/url\]/is","<a href=\"$1\" target=_blank>$2</a>",$text);
  $text = preg_replace("/\[url=(ftp:\/\/[^\"]+?)\](.+?)\[\/url\]/is","<a href=\"$1\" target=_blank>$2</a>",$text);
  $text = preg_replace("/\[url=([^\"]+?)\]([^\"]+?)\[\/url\]/is","<a href=\"http://$1\" target=_blank>$2</a>",$text);
  $text = preg_replace("/\[url2=([^\"]+?)\](.+?)\[\/url2\]/is","<a href=\"$1\">$2</a>",$text);

  $text = preg_replace("/\[email\](\S+?\@\S+?)\[\/email\]/is","<a href=\"mailto:$1\">$1</a>",$text);
  $text = preg_replace("/\[email=(\S+?\@\S+?)\](.+?)\[\/email\]/is","<a href=\"mailto:$1\">$2</a>",$text);

  $text = str_replace("[b]","<b>",$text);
  $text = str_replace("[/b]","</b>",$text);
  $text = str_replace("[i]","<i>",$text);
  $text = str_replace("[/i]","</i>",$text);
  $text = str_replace("[u]","<u>",$text);
  $text = str_replace("[/u]","</u>",$text);
  $text = str_replace("[s]","<s>",$text);
  $text = str_replace("[/s]","</s>",$text);

  $text = preg_replace("/\[font=([\w ]+?)\]/is","<font face=\"$1\">",$text);
  $text = preg_replace("/\[color=([#\w\d]+?)\]/is","<font color=\"$1\">",$text);
  $text = preg_replace("/\[size=(\d+?)\]/is","<font size=\"$1\">",$text);
  $text = str_replace("[/font]","</font>",$text);
  $text = str_replace("[/color]","</font>",$text);
  $text = str_replace("[/size]","</font>",$text);

  $text = str_replace("[list]","<ul>",$text);
  $text = str_replace("[*]","<li>",$text);
  $text = str_replace("[/list]","</ul>",$text);

  if (!$GLOBALS['opt_imgtag']) {
  $text = preg_replace("/\[img\](.+?)\[\/img\]/is","<img src=\"$1\">",$text);
  $text = preg_replace("/\[img=(.+?)\]/is","<img src=\"$1\">",$text);
  } else {
    $text = preg_replace("/\[img\](\S+?)\[\/img\]/is","<a href=\"$1\"><img src=\"styles/image.gif\" border=0 alt=\"".MSG_image."\"></a>",$text);
    $text = preg_replace("/\[img=(\S+?)\]/is","<a href=\"$1\"><img src=\"styles/image.gif\" border=0 alt=\"".MSG_image."\"></a>",$text);
  }
  
  $text = preg_replace("/(<br \/>)?\[table\](.*?)\[\/table\](<br \/>)?/is","<table width=90% align=center class=\"usertable\">$2</table>",$text);
  $text = preg_replace("/\[tr\](.*?)\[\/tr\]/is","<tr>$1</tr>",$text);
  $text = preg_replace("/\[td\](.*?)\[\/td\]/is","<td>$1</td>",$text);
  $text = preg_replace("/\[td colspan=(\d+)\](.*?)\[\/td\]/is","<td colspan=\"$1\">$2</td>",$text);
  
  $text = preg_replace("/<\/td>(\s*<br \/>\s*)+</is","</td><",$text);
  $text = preg_replace("/<\/tr>(\s*<br \/>\s*)+</is","</tr><",$text);
  $text = preg_replace("/<tr(.*?)>(\s*<br \/>\s*)+</is","<tr$1><",$text);
  $text = preg_replace("/<table(.*?)>(\s*<br \/>\s*)+</is","<table$1><",$text);  

  $text = preg_replace("/\[code\](.*?)\[\/code\]/is","<hr><div class=\"code\">$1</div><hr>",$text);
  $text = preg_replace("/\[off\](.*?)\[\/off\]/is","<div class=\"offtopic\">".MSG_offtopic.": $1</div>",$text);

  $text = preg_replace("/\[center\](.*?)\[\/center\]/is","<div style=\"text-align : center\">$1</div>",$text);
  $text = preg_replace("/\[right\](.*)\[\/right\]/is","<div style=\"text-align : right\">$1</div>",$text);

  $text = preg_replace("/\[translit\](.*)\[\/translit\]/esi","untransliterate(\"$1\")",$text);

  $text = preg_replace("/(<img .*?>)/ise","check_img(\"$1\")",$text);
  $text = preg_replace("/(<a .*?>)/ise","check_link(\"$1\")",$text);
  $text = preg_replace("/(<script.*?<\/script>)/ise","\"<br><font color=red><b>HACK ATTEMPT:</b> \".htmlspecialchars(\"$1\").\"</font><br>\"",$text);

  $text = preg_replace("/\[hide=(\d+?)\](.*?)\[\/hide\]/esi","check_hidden($1,\"$2\")",$text);
  $text = preg_replace("/\[level=(\d+?)\](.*?)\[\/level\]/esi","check_level($1,\"$2\")",$text);
 }
 $text = str_replace("(c)","&copy;",$text);
 $text = str_replace("(C)","&copy;",$text);
 $text = str_replace("(r)","&reg;",$text);
 $text = str_replace("(R)","&reg;",$text);
 $text = str_replace("(tm)","&trade;",$text);
 $text = str_replace("(TM)","&trade;",$text);
}

function sign_code(&$text) {
    if (strpos($text,"[")!==false) {
      $text = preg_replace("/\[br\]/","<br>",$text);

      $text = str_replace("[b]","<b>",$text);
      $text = str_replace("[/b]","</b>",$text);
      $text = str_replace("[i]","<i>",$text);
      $text = str_replace("[/i]","</i>",$text);
      $text = str_replace("[u]","<u>",$text);
      $text = str_replace("[/u]","</u>",$text);
      $text = str_replace("[s]","<s>",$text);
      $text = str_replace("[/s]","</s>",$text);

      $text = preg_replace("/\[font=([^<>]+?)\]/is","<font face=\"$1\">",$text);
      $text = preg_replace("/\[color=([^<>]+?)\]/is","<font color=\"$1\">",$text);
      $text = preg_replace("/\[size=([^<>]+?)\]/is","<font size=\"$1\">",$text);
      $text = str_replace("[/font]","</font>",$text);
      $text = str_replace("[/color]","</font>",$text);
      $text = str_replace("[/size]","</font>",$text);

      $text = preg_replace("/\[url\](http:\/\/\S+?)\[\/url\]/is","<a href=\"$1\" target=_blank>$1</a>",$text);
      $text = preg_replace("/\[url\](\S+?)\[\/url\]/is","<a href=\"http://$1\" target=_blank>$1</a>",$text);
      $text = preg_replace("/\[url=(http:\/\/\S+?)\](.+?)\[\/url\]/is","<a href=\"$1\" target=_blank>$2</a>",$text);
      $text = preg_replace("/\[url=(\S+?)\](.+?)\[\/url\]/is","<a href=\"http://$1\" target=_blank>$2</a>",$text);

      $text = preg_replace("/\[email\](\S+?\@\S+?)\[\/email\]/is","<a href=\"mailto:$1\">$1</a>",$text);
      $text = preg_replace("/\[email=(\S+?\@\S+?)\](.+?)\[\/email\]/is","<a href=\"mailto:$1\">$2</a>",$text);
  }
  $text = str_replace("(c)","&copy;",$text);
  $text = str_replace("(C)","&copy;",$text);
  $text = str_replace("(r)","&reg;",$text);
  $text = str_replace("(R)","&reg;",$text);
  $text = str_replace("(tm)","&trade;",$text);
  $text = str_replace("(TM)","&trade;",$text);

  if ($GLOBALS['opt_sigpics']) {
    $text = preg_replace("/\[img\](\S+?)\[\/img\]/is","<img src=\"$1\">",$text);
    $text = preg_replace("/\[img=(\S+?)\]/is","<img src=\"$1\">",$text);
    $text = preg_replace("/\[email\](\S+?\@\S+?)\[\/email\]/is","<a href=\"mailto:$1\">$1</a>",$text);
    $text = preg_replace("/\[email=(\S+?\@\S+?)\](.+?)\[\/email\]/is","<a href=\"mailto:$1\">$2</a>",$text);
   $text = preg_replace("/(<img .*?>)/ise","check_img(\"$1\")",$text);
   $text = preg_replace("/(<a .*?>.*<\/a>)/ise","check_link(\"$1\")",$text);

  }

  return $text;
}

function textout($text,$html,$bcode,$smiles) {
    if ($html) $text=nl2br($text);
    else $text=nl2br(htmlspecialchars($text));
    $text=str_replace("&quot;","\"",$text);      
    addlinks($text);
    if ($smiles) smiles($text);
    if ($bcode) boardcode($text);
    $text=stripslashes($text);
    if ($hlight=getvar('hl')) {
      $hlight=preg_replace("/[.,:;-?()\\!]+/"," ",$hlight);
      $hls=explode(" ",$hlight);
      foreach ($hls as $curhl) {
        if ($curhl) $text=preg_replace("|([ >.,:;-?()\\!]+)($curhl\S*?)([ <.,:;-?()\\!]+)|is","$1<span class=\"hligh\">$2</span>$3",$text);
      }
    }
    return $text;
}

function build_avatar_select() {
    $dir=opendir($GLOBALS['opt_dir']."/avatars");
    while ($curfile=readdir($dir)) if (!is_dir($GLOBALS['opt_dir']."/avatars/".$curfile)) $avatarselect.="<option value=\"$curfile\">$curfile";
    closedir($dir);
    return $avatarselect;
}

function load_smiles() {
    $link = $GLOBALS['link'];
    $sql = "SELECT sm_code,sm_file,sm_show FROM ".$GLOBALS['DBprefix']."Smile";
    $res = db_query($sql,$link);
    while ($smile=db_fetch_row($res)) {
      $GLOBALS['smiles'][$smile[0]]=$smile[1];
      $GLOBALS['smileshow'][$smile[0]]=$smile[2];
    }
    if (db_num_rows($res)==0) $GLOBALS['smiles']=array();
    db_free_result($res);
}

function smiles(&$text) {
    if (!is_array($GLOBALS['smiles'])) load_smiles();
    foreach ($GLOBALS['smiles'] as $sm_code=>$sm_file) if ($GLOBALS['smileshow'][$sm_code]) {
        $text=str_replace($sm_code,"<img src=\"smiles/".$sm_file."\" alt=\"$sm_code\">",$text);
    }
}

function show_email_q($email,$showtype,$uid) {
    if ($showtype==1) {
        $buffer="<a href=\"mailto:$email\">Email</a>";
    }
    elseif ($showtype==2) {
        $curpos=0;
        $email="<a href=\"mailto:$email\">Email</a>";
        $buffer="<SCRIPT><!--\n";
        while ($curpos<strlen($email)) {
            $pos=rand() % 8 +1;
            $buffer.="document.write('".substr($email,$curpos,$pos)."');\n";
            $curpos+=$pos;
        }
        $buffer.="--></SCRIPT>";
    }
    elseif ($showtype==3) {
        $buffer="<a href=\"index.php?m=misc&a=sendmail&u=$uid\">Email</a>";
    }
    return $buffer;
}

function show_email_f($email,$showtype,$uid) {
    if ($showtype==1) {
        echo "<a href=\"mailto:$email\">$email</a>";
    }
    elseif ($showtype==2) {
        $curpos=0;
        $email="<a href=\"mailto:$email\">$email</a>";
        echo "<SCRIPT><!--\n";
        while ($curpos<strlen($email)) {
            $pos=rand() % 5 +1;
            echo "document.write('".substr($email,$curpos,$pos)."');\n";
            $curpos+=$pos;
        }
        echo "--></SCRIPT>";
    }
    elseif ($showtype==3) {
        echo "<img src=\"agent.php?a=email&u=$uid\" alt=\"E-mail\">";
    }
}

function push_parents(&$locations,$fid) {
    if ($fid!=0) {
        $link=$GLOBALS['link'];
        $sql = "SELECT f_title,f_parent FROM ".$GLOBALS['DBprefix']."Forum WHERE f_id=$fid";
        $res = db_query($sql,$link);
        $fname = db_fetch_row($res);
        push_parents($locations,$fname[1]);
        array_push($locations,"<a href=\"index.php?f=$fid\">".$fname[0]."</a>");
    }
}

function user_out($uname,$uid) {
    if ($uid==1 || !$uid) $output = $uname;
    else $output = "<a class=\"username\" href=\"index.php?m=profile&u=$uid\">$uname</a>";
    return $output;
}

function load_mail($filename) {
    if (!file_exists($GLOBALS['opt_dir']."/langs/".$GLOBALS['inuser']['ln_file']."/$filename")) error(MSG_e_nomail);
    $size = filesize($GLOBALS['opt_dir']."/langs/".$GLOBALS['inuser']['ln_file']."/$filename");
    $fh = fopen($GLOBALS['opt_dir']."/langs/".$GLOBALS['inuser']['ln_file']."/$filename","r");
    $buffer = fread($fh,$size);
    fclose($fh);
  return $buffer;
}

function process_mail($filename,$email,$subject) {
    $buffer=load_mail($filename);
    replace_mail($buffer,$email,$subject);
}

function replace_mail($buffer,$email,$subject) {
  if (ereg("^[a-zA-Z0-9_.\-]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$", $email)) {
    preg_match_all("/\\$(\\w+)/s",$buffer,$matches);
    foreach ($matches[1] as $curmatch) {
        $buffer = str_replace("\$".$curmatch,$GLOBALS[$curmatch],$buffer);
    }
    if ($GLOBALS['opt_noname_mail']==0 && $GLOBALS['username']) $email=$GLOBALS['username']." <".$email.">";
    $buffer=stripslashes($buffer);
    mail($email,$subject,$buffer,"From: ".$GLOBALS['opt_mailout']."\r\nX-Mailer: Intellect Board 2 Forum Script\r\nContent-Type: text/plain; charset=".$GLOBALS['inuser']['ln_charset']);
  }
}

function show_avatar(&$udata) {
    if ($GLOBALS['opt_avatarx']) $size=" width=".$GLOBALS['opt_avatarx'];
    if ($GLOBALS['opt_avatary']) $size.=" height=".$GLOBALS['opt_avatary'];
    if ($udata['u_avatartype']==1) {
        $tmp="<img src=\"avatars/".$udata['u__avatar']."\" border=0 alt=\"".$udata['u__name']."\"$size>";
    }
    elseif ($udata['u_avatartype']==2) {
        $tmp="<img src=\"".$udata['u__avatar']."\" border=0 alt=\"".$udata['u__name']."\"$size>";
    }
    elseif ($udata['u_avatartype']==3) {
        $tmp="<img src=\"file.php?fid=".$udata['u__pavatar_id']."\" border=0 alt=\"".$udata['u__name']."\"$size>";
    }
    return $tmp;
}

function check_image($name,$maxsize,$maxx,$maxy,$errsize,$errtype,$errxy) {
    if (!is_uploaded_file($_FILES[$name]['tmp_name']) || $_FILES[$name]['size']==0 ||
    $_FILES[$name]['size']>$maxsize || strpos($_FILES[$name]['type'],"image")===false) error($errsize);
    if ($GLOBALS['opt_graphics']) {
        $imdata=getimagesize($_FILES[$name]['tmp_name']);
        if (!$imdata) error($errtype);
        if (($maxx && $imdata[0]>$maxx) || ($$maxy && $imdata[1]>$maxy)) error($errxy);
    }
}

function is_new($tviews,$maxdata) {
    if ($GLOBALS['opt_fixviews'] && intval($maxdata)>$GLOBALS['inuser']['lv_markall']) $tmp = $tviews;
    else $tmp = (intval($maxdata)<$GLOBALS['userlast2']);
    if ($GLOBALS['inuserid']<=3) $tmp=1;
    return !$tmp;
}

function check_moderate(&$udata,$level) {
    $tmp=0;
    if ($udata['ua_level'] && $udata['ua_level']>$level) $tmp=1;
    elseif ($udata['u__level']>$level) $tmp=1;
    return $tmp;
}

function user_substr(&$udata,$forum) {
    $link=$GLOBALS['link'];
    if (is_array($udata)) foreach ($udata as $uid=>$count) {
      $sql="UPDATE ".$GLOBALS['DBprefix']."UserStat SET us_count=us_count-$count WHERE fid=\"$forum\" AND uid=\"$uid\"";
      $res = db_query($sql,$link);
    }
}

function user_summ(&$udata,$forum) {
    $link=$GLOBALS['link'];
    if (is_array($udata)) foreach ($udata as $uid=>$count) {
      $sql="UPDATE ".$GLOBALS['DBprefix']."UserStat SET us_count=us_count+$count WHERE fid=\"$forum\" AND uid=\"$uid\"";
      $res = db_query($sql,$link);
    }
}

function send_pm($urecv,$usend,$text,$subj,$sqldata) {
    $link = $GLOBALS['link'];
    if ($sqldata) $sqldata=", ".$sqldata;
    $curtime = $GLOBALS['curtime'];
    $sql = "INSERT INTO ".$GLOBALS['DBprefix']."PersonalMessage SET pm__box=0, pm__owner=$urecv, pm__senddate=$curtime, pm__readdate=0, pm__correspondent=$usend, pm_subj=\"$subj\", pm_text=\"$text\" $sqldata";
    $res = db_query($sql,$link);
    $pmid = db_insert_id($res);
    $sql = "UPDATE ".$GLOBALS['DBprefix']."User SET u__pmcount=u__pmcount+1 WHERE u_id=$urecv";
    $res = db_query($sql,$link);
    $sql = "SELECT u_pmnotify, u__name, u__email FROM ".$GLOBALS['DBprefix']."User WHERE u_id=$urecv";
    $res=db_query($sql,$link);
    list($notify,$name,$email)=db_fetch_row($res);
    if ($notify) {
      $GLOBALS['username']=$name;
      $GLOBALS['subj']=$subj;
      $GLOBALS['text']=$text;
      $GLOBALS['sender']=$GLOBALS['inuser']['u__name'];
      process_mail("newpm.txt",$email,MSG_pm_recived);
    }
    return $pmid;
}

function build_diff_list($topic) {
    $link=$GLOBALS['link'];
    $sql = "SELECT p_uid,COUNT(p_id) AS ucount FROM ".$GLOBALS['DBprefix']."Post WHERE p_tid=\"$topic\" GROUP BY p_uid";
    $res = db_query($sql,$link);
    while ($udata=db_fetch_row($res)) {
      $userdif[$udata[0]]=$udata[1];
    }
    return $userdif;
}

function delete_topic($topic) {
    $link = $GLOBALS['link'];

    $userdif=build_diff_list($topic);

    $sql = "SELECT t_fid FROM ".$GLOBALS['DBprefix']."Topic WHERE t_id=\"$topic\"";
    $res = db_query($sql,$link);
    list($fid)=db_fetch_row($res);
    db_free_result($res);

    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."Topic WHERE t_id=\"$topic\"";
    $res = db_query($sql,$link);
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."Bookmark WHERE tid=\"$topic\"";
    $res = db_query($sql,$link);
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."Subscription WHERE tid=\"$topic\"";
    $res = db_query($sql,$link);
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."TopicView WHERE tid=\"$topic\"";
    $res = db_query($sql,$link);
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."TopicRate WHERE tid=\"$topic\"";
    $res = db_query($sql,$link);
    $sql = "SELECT * FROM ".$GLOBALS['DBprefix']."Poll WHERE pl_tid=\"$topic\"";
    $res = db_query($sql,$link);

    if (db_num_rows($res)>0) {
        $plid=db_fetch_row($res);
        db_free_result($res);
        $sql = "SELECT pv_id FROM ".$GLOBALS['DBprefix']."PollVariant WHERE pv_plid=".$plid[0];
        $res = db_query($sql,$link);
        while ($pvid=db_fetch_row) {
            if ($sqldata) $sqldata.=" OR ";
            $sqldata = "pvid=".$pvid[0];
        }
        db_free_result($res);
        $sql = "DELETE FROM ".$GLOBALS['DBprefix']."Vote WHERE $sqldata";
        $res = db_query($sql,$link);
        $sql = "DELETE FROM ".$GLOBALS['DBprefix']."PollVariant WHERE pv_plid=".$plid[0];
        $res = db_query($sql,$link);
        $sql = "DELETE FROM ".$GLOBALS['DBprefix']."Poll WHERE pl_id=".$plid[0];
        $res = db_query($sql,$link);
    }
    
    $sql = "SELECT MAX(p__time) FROM ".$GLOBALS['DBprefix']."Post WHERE p_tid=\"$topic\"";
    $res=db_query($sql,$link);
    list($maxtime)=db_fetch_row($res);
    db_free_result($res);
    
    if ($maxtime) {
      $sql = "UPDATE ".$GLOBALS['DBprefix']."LastVisit SET lv_markcount=lv_markcount-1 WHERE lv_markall>$maxtime";
      $res=db_query($sql,$link);
    }

    $sql = "SELECT p_attach FROM ".$GLOBALS['DBprefix']."Post WHERE p_tid=\"$topic\" AND p_attach!=0";
    $res = db_query($sql,$link);
    $attachcount=db_num_rows($res);
    if ($attachcount) {
      while ($pnumber=db_fetch_row($res)) {
        if ($sqldata) $sqldata.=" OR ";
        $sqldata.="file_id=".$pnumber[0];
        }
        db_free_result($res);
        $sql = "DELETE FROM ".$GLOBALS['DBprefix']."File WHERE $sqldata";
        $res = db_query($sql,$link);
    }
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."Post WHERE p_tid=\"$topic\"";
    $res=db_query($sql,$link);
    user_substr($userdif,$fid);
}

function forum_resync($fid) {
    $link = $GLOBALS['link'];
    $sql = "SELECT MAX(p_id),COUNT(p_id) FROM ".$GLOBALS['DBprefix']."Post p, ".$GLOBALS['DBprefix']."Topic t ".
    "WHERE p_tid=t_id AND t_fid=$fid AND p__premoderate=0";
    $res = db_query($sql,$link);
    list($pmax,$pcount)=db_fetch_row($res);
    db_free_result($res);

    $sql= "SELECT MAX(t__startpostid), COUNT(t_id) FROM ".$GLOBALS['DBprefix']."Topic t WHERE t_fid=$fid AND t__pcount>0";
    $res = db_query($sql,$link);
    list($pstart,$tcount)=db_fetch_row($res);

    if ($GLOBALS['forum']!=$fid || $GLOBALS['inforum']['f__premoderate']) {
      $sql = "SELECT COUNT(p_id) FROM ".$GLOBALS['DBprefix']."Post, ".$GLOBALS['DBprefix']."Topic ".
      " WHERE p_tid=t_id AND t_fid=$fid AND p__premoderate=1";
      $res = db_query($sql,$link);
      list($premod)=db_fetch_row($res);
      db_free_result($res);
    }
    else $premod="0";

    $sql = "UPDATE ".$GLOBALS['DBprefix']."Forum SET f__pcount=".intval($pcount).", f__lastpostid=".intval($pmax).", f__premodcount=".intval($premod).", f__startpostid=".intval($pstart).", f__tcount=".intval($tcount)." WHERE f_id=$fid";
    $res = db_query($sql,$link);
}

function topic_resync($topic) {
    $link=$GLOBALS['link'];
    $sql = "SELECT MAX(p_id),COUNT(p_id),MIN(p_id) FROM ".$GLOBALS['DBprefix']."Post p, ".$GLOBALS['DBprefix']."Topic t ".
    "WHERE p_tid=t_id AND t_id=$topic AND p__premoderate=0";
    $res = db_query($sql,$link);
    list($pmax,$pcount,$pmin)=db_fetch_row($res);
    db_free_result($res);
    $sql = "UPDATE ".$GLOBALS['DBprefix']."Topic SET t__pcount=".intval($pcount).", t__lastpostid=".intval($pmax).", t__startpostid=".intval($pmin)." WHERE t_id=$topic";
    $res = db_query($sql,$link);
}

function check_selfmod() {
    return ($GLOBALS['inforum']['f_selfmod'] && $GLOBALS['intopic']['p_uid']==$GLOBALS['inuserid']);
}

function out_online($prefix,$starttime,$endtime,$group,$more="") {
    $link=$GLOBALS['link'];
    if ($group==1) $grpsql="AND sid.uo_lasttime=uo.uo_time";
    $sql = "SELECT sid.*,uo.*,u.u_id,u.u__name,f.f_id,f.f_title,f.f_lview,t.t_id,t.t_title ".
            "FROM ".$GLOBALS['DBprefix']."LogSession sid, ".$GLOBALS['DBprefix']."LogEntry uo, ".$GLOBALS['DBprefix']."User u LEFT JOIN ".$GLOBALS['DBprefix']."Forum f ON ".
            "(uo.uo_fid=f.f_id) LEFT JOIN ".$GLOBALS['DBprefix']."Topic t ON (uo.uo_tid=t.t_id) WHERE sid.uo_curid=u.u_id AND sid.sid_id=uo.uo_id $grpsql AND uo_time<=$endtime AND uo_time>=$starttime ".
            "ORDER BY uo_time DESC";
    $res = db_query($sql,$link);
    while ($udata=db_fetch_array($res)) {
       if ($udata['uo_module']=="main") $comment = MSG_view_mainpage;
       elseif ($udata['f_id'] && $udata['f_lview']>$GLOBALS['inuserlevel']) $comment = MSG_view_mainpage;
       elseif (strpos($udata['uo_action'],"_view")!==false && $udata['t_id']) $comment = MSG_view_topic." \"<a href=\"$prefix"."index.php?t=".
           $udata['t_id']."\">".$udata['t_title']."</a>\" ".MSG_view_inforum." \"<a href=\"$prefix"."index.php?f=".$udata['f_id'].
           "\">".$udata['f_title']."</a>\"";
       elseif (strpos($udata['uo_action'],"_view")!==false && $udata['f_id']) $comment = MSG_view_forum." \"<a href=\"index.php?f=".
           $udata['f_id']."\">".$udata['f_title']."</a>\"";
       elseif ($udata['uo_action']=="do_post") $comment = MSG_view_dopost." \"<a href=\"$prefix"."$prefix"."index.php?t=".
           $udata['t_id']."\">".$udata['t_title']."</a>\" ".MSG_view_inforum." \"<a href=\"$prefix"."index.php?f=".$udata['f_id'].
           "\">".$udata['f_title']."</a>\"";
       elseif ($udata['uo_action']=="do_topic") $comment = MSG_view_dotopic." ".MSG_view_inforum.
       " \"<a href=\"$prefix"."index.php?f=".$udata['f_id']."\">".$udata['f_title']."</a>\"";
       elseif ($udata['uo_module']=="stdforum" && $udata['uo_action']=="rules") $comment = MSG_view_rules." ".
       MSG_view_inforum." \"<a href=\"$prefix"."index.php?f=".$udata['f_id']."\">".$udata['f_title']."</a>\"";
       elseif ($udata['uo_module']=="profile") {
         if ($udata['uo_action']=="rules") $comment = MSG_view_rules." ".MSG_view_before_register;
         elseif ($udata['uo_action']=="register") $comment = MSG_view_registering;
         elseif ($udata['uo_action']=="do_register") $comment = MSG_view_registered;
         elseif ($udata['uo_action']=="login") $comment = MSG_view_logging_in;
         elseif ($udata['uo_action']=="do_login") $comment = MSG_view_logged_in;
         elseif ($udata['uo_action']=="do_logout") $comment = MSG_view_logged_out;
         elseif ($udata['uo_action']=="view") $comment = MSG_view_profile;
         elseif ($udata['uo_action']=="listusers") $comment = MSG_view_userlist;
         elseif ($udata['uo_action']=="online") $comment = MSG_view_online;
       }
       elseif ($udata['uo_module']=="search") {
         if ($udata['uo_action']=="view") $comment = MSG_view_start_search;
         elseif ($udata['uo_action']=="topic") $comment = MSG_view_search_topic;
         elseif ($udata['uo_action']=="post") $comment = MSG_view_search_post;
         elseif ($udata['uo_action']=="user") $comment = MSG_view_search_user;
       }
       else $comment = MSG_view_undescribed;
       online_entry($udata,$comment);
    }
}

function delete_user($uid) {
    $link=$GLOBALS['link'];

    $sql = "UPDATE ".$GLOBALS['DBprefix']."Post SET p_uid=1 WHERE p_uid=$uid";
    $res = db_query($sql,$link);
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."UGroupMember WHERE uid=$uid";
    $res = db_query($sql,$link);
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."UserRating WHERE uid=$uid";
    $res = db_query($sql,$link);
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."UserWarning WHERE uw_id=$uid";
    $res = db_query($sql,$link);
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."PersonalMessage WHERE pm__owner=$uid";
    $res = db_query($sql,$link);
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."TopicView WHERE uid=$uid";
    $res = db_query($sql,$link);
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."UserAccess WHERE uid=$uid";
    $res = db_query($sql,$link);
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."LastVisit WHERE uid=$uid";
    $res = db_query($sql,$link);
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."UserStat WHERE uid=$uid";
    $res = db_query($sql,$link);

    $sql = "SELECT u__pavatar_id,u__photo_id FROM ".$GLOBALS['DBprefix']."User WHERE u_id=$uid";
    $res = db_query($sql,$link);
    list($avatar,$photo)=db_fetch_row($res);
    db_free_result($res);

    if ($avatar) {
        $sql = "DELETE FROM ".$GLOBALS['DBprefix']."File WHERE file_id=\"$avatar\"";
        $res = db_query($sql,$link);
    }
    if ($photo) {
        $sql = "DELETE FROM ".$GLOBALS['DBprefix']."File WHERE file_id=\"$photo\"";
        $res = db_query($sql,$link);
    }
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."User WHERE u_id=$uid";
    $res = db_query($sql,$link);
}

function delete_post($pid) {
  $link=$GLOBALS['link'];
  $sql = "SELECT u.u__level,ua.ua_level,p.p_attach,p.p_tid,p_uid,t_fid,t__pcount ".
  "FROM ".$GLOBALS['DBprefix']."Post p, ".$GLOBALS['DBprefix']."Topic t,  ".$GLOBALS['DBprefix']."User u ".
  "LEFT JOIN ".$GLOBALS['DBprefix']."UserAccess ua ON (ua.uid=u.u_id AND ua.fid=".$GLOBALS['forum'].") ".
  "WHERE p_id=\"$pid\" AND p_tid=t_id AND u.u_id=p.p_uid";
  $res = db_query($sql,$link);
  if (db_num_rows($res)!=1) error(MSG_e_p_notfound);
  $pdata=db_fetch_array($res);
  db_free_result($res);
  if ($pdata['p_uid']!=$GLOBALS['inuserid'] && check_moderate($pdata,$GLOBALS['inuserlevel'])) error(MSG_e_mod_subordinate);
  if ($pdata['p_attach']) {
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."File WHERE file_id=".$pdata['p_attach'];
    $res = db_query($sql,$link);
  }
  $sql = "DELETE FROM ".$GLOBALS['DBprefix']."Post WHERE p_id=\"$pid\"";
  $res = db_query($sql,$link);
  $sql = "UPDATE ".$GLOBALS['DBprefix']."UserStat SET us_count=us_count-1 WHERE uid=".$pdata['p_uid']." AND fid=".$pdata['t_fid'];
  $res = db_query($sql,$link);
  if ($pdata['t__pcount']==1) delete_topic($pdata['p_tid']);
}

function common_topic_view($topic) {
    $link=$GLOBALS['link'];
    if ($GLOBALS['opt_fixviews'] && !$GLOBALS['intopic']['visited'] && $GLOBALS['inuserid']>3 && $GLOBALS['intopic']['lasttime']>$GLOBALS['intopic']['lv_markall']) {
      $sql = "INSERT INTO ".$GLOBALS['DBprefix']."TopicView VALUES (\"$topic\",".$GLOBALS['inuserid'].")";
      $res = db_query($sql,$link);
    }    

    $sql = "UPDATE ".$GLOBALS['DBprefix']."Topic SET t__views=t__views+1 WHERE t_id=\"$topic\"";
    $res = db_query($sql,$link);

    $sql = "UPDATE ".$GLOBALS['DBprefix']."Forum SET f__views=f__views+1 WHERE f_id=\"".$GLOBALS['forum']."\"";
    $res = db_query($sql,$link);

    $sql = "SELECT COUNT(*) FROM ".$GLOBALS['DBprefix']."TopicRate WHERE tid=\"$topic\" AND uid=\"".$GLOBALS['inuserid']."\"";
    $res = db_query($sql,$link);
    list($rate) = db_fetch_row($res);
    db_free_result($res);

    return $rate;
}

function process_post($topic) {
    $link=$GLOBALS['link'];
    $inforum=$GLOBALS['inforum'];
    $inuserlevel=$GLOBALS['inuserlevel'];
    $inuser=$GLOBALS['inuser'];
    $inuserid=$GLOBALS['inuserid'];
    $intopic=$GLOBALS['intopic'];

    if ($inuserlevel<$inforum['f_lpost']) error(MSG_e_p_norights);
    if ($intopic['t__status']!=0) error(MSG_e_t_closed);
    if ($inforum['f_status']!=0) error(MSG_e_f_closed);
    if (!$text=db_slashes($_POST['p_text'])) error(MSG_e_p_empty);

    if (strlen($text)<$GLOBALS['opt_minpost']) error(MSG_e_p_toosmall);
    if ($GLOBALS['opt_maxpost'] && strlen($text)>$GLOBALS['opt_maxpost']) error(MSG_e_p_toolarge);

    if (is_uploaded_file($_FILES['attach']['tmp_name'])) {
        if ($inuserlevel<$inforum['f_lattach']) error(MSG_e_p_norightsattach);
        if ($inforum['f_attachpics']) {
            check_image("attach",$GLOBALS['opt_maxfileattach'],0,0,MSG_e_p_toobig,MSG_e_p_onlypics,"");
        }
        elseif ($_FILES['attach']['size']>$GLOBALS['opt_maxfileattach']) error(MSG_e_p_toobig);
        $fsize=$_FILES['attach']['size'];
        $fh=fopen($_FILES['attach']['tmp_name'],"r");
        $buffer=fread($fh,$fsize);
        fclose($fh);
        $sql = "INSERT INTO ".$GLOBALS['DBprefix']."File VALUES(0,\"".db_slashes($buffer)."\",\"".$_FILES['attach']['type'].
               "\",\"".db_slashes($_FILES['attach']['name'])."\")";
        $res = db_query($sql,$link);
        $pattach = db_insert_id($res);
    }
    else { $pattach=0; }

    if ($GLOBALS['inuser']['u_detrans']) {
        load_smiles();
        $_POST['p_text']=untransliterate($_POST['p_text']);
    }

    $text=" ".$text." ";
    $sql = "SELECT * FROM ".$GLOBALS['DBprefix']."BadWord";
    $res = db_query($sql,$link);
    while ($wdata=db_fetch_array($res)) {
      $wdata['w_bad']=str_replace("/","\\/",$wdata['w_bad']);
      $wdata['w_bad']="/([\s,\.:;-\?!\(\)\[\]\{\}])".str_replace("*","\S*?",$wdata['w_bad'])."([\s,\.:;-\?!\(\)\[\]\{\}])/is";
      $text=preg_replace($wdata['w_bad'],"$1".$wdata['w_good']."$2",$text);
    }
    $text=substr($text,1,strlen($text)-2);
    unset($_POST['p_text']);
    db_free_result($res);

    $inname=getvar("inname");
    $uid=$inuserid;
    $sqldata = build_sql("p_");
    if ($inuserid<=3) {
      $pname=getvar("inusername");
      if (!$pname) $pname="Guest";
      $sql = "SELECT COUNT(*) FROM ".$GLOBALS['DBprefix']."User WHERE u__name=\"$pname\" AND u_id>1";
      $res = db_query($sql,$link);
      list($count)=db_fetch_row($res);
      if ($count>0) error(MSG_e_p_reguser);
    }
    elseif ($GLOBALS['inuserlevel']>=1000 && $GLOBALS['opt_impersonation'] && $inname!=$GLOBALS['inuser']['u__name'] && $inname!="") {
      $sql = "SELECT u_id FROM ".$GLOBALS['DBprefix']."User WHERE u__name=\"$inname\"";
      $res = db_query($sql,$link);
      if ($tmp=db_fetch_row($res)) {
        $uid=$tmp[0];
      }
      else $uid=1;
      $pname=$inname;
    }
    else $pname=$inuser['u__name'];
    $time = $GLOBALS['curtime'];
    if ($inuserlevel<$inforum['f_lmoderate']) {
        if ($inuserid>3) {
          $sql = "SELECT COUNT(*) FROM ".$GLOBALS['DBprefix']."Post WHERE p_uid=$inuserid AND p__time>".($time-$GLOBALS['opt_flood']);
      }
      else {
          $sql = "SELECT COUNT(*) FROM ".$GLOBALS['DBprefix']."Post WHERE p__ip=\"".getip()."\" AND p__time>".($time-$GLOBALS['opt_flood']);
      }
      $res = db_query($sql,$link);
      $count=db_fetch_row($res);
      if ($count[0]>0) error(MSG_e_p_flood);
      db_free_result($res);
    }

  if ($sqldata) $sqldata.=", ";
  $sqldata.="p_uname=\"$pname\", ";
  $sqldata.="p_uid=\"$uid\", ";
  $sqldata.="p_tid=$topic, ";
  $sqldata.="p__time=\"$time\", ";
  $sqldata.="p__ip=\"".iptonum(getip())."\", ";
  $sqldata.="p_attach=$pattach, ";
  $premoderate=intval($GLOBALS['inforum']['f_premoderate']);
  $sqldata.="p__premoderate=$premoderate";
  $sqldata.=check_post_params();

  $sql = "INSERT INTO ".$GLOBALS['DBprefix']."Post SET p_text=\"$text\", $sqldata";
  $res = db_query($sql,$link);
  $pid = db_insert_id($res);
  if (!$GLOBALS['inuser']['l_custom'] && $inuserid>3) {
    $sql = "SELECT SUM(us_count) AS pcount FROM ".$GLOBALS['DBprefix']."UserStat us, ". $GLOBALS['DBprefix']."Forum f WHERE us.uid=".$GLOBALS['inuserid']." AND f.f_id=us.fid AND f_nostats=0";
    $res = db_query($sql,$link);
    list($count)=db_fetch_row($res);
    db_free_result($res);
    $sql = "SELECT l_level FROM ".$GLOBALS['DBprefix']."UserLevel WHERE l_custom=0 AND l_minpost<".intval($count)." ORDER BY l_minpost DESC LIMIT 1";
    $res = db_query($sql,$link);
    if (db_num_rows($res)>0) {
        $tmp=db_fetch_array($res);
        $sql = "UPDATE ".$GLOBALS['DBprefix']."User SET u__level=".$tmp['l_level']." WHERE u_id=".$inuserid." AND u__level<".$tmp['l_level'];
        $res = db_query($sql,$link);
    }
  }

  if ($premoderate==0) {
    $sql = "UPDATE ".$GLOBALS['DBprefix']."Topic SET t__pcount=t__pcount+1, t__lastpostid=$pid WHERE t_id=".$topic;
    $res = db_query($sql,$link);
    $sql = "UPDATE ".$GLOBALS['DBprefix']."Forum SET f__pcount=f__pcount+1, f__lastpostid=$pid WHERE f_id=".$GLOBALS['forum'];
    $res = db_query($sql,$link);
    $sql = "UPDATE ".$GLOBALS['DBprefix']."UserStat SET us_count=us_count+1 WHERE uid=$uid AND  fid=".$GLOBALS['forum'];
    $res = db_query($sql,$link);
    if (db_affected_rows($res)==0) {
      $sql = "INSERT INTO ".$GLOBALS['DBprefix']."UserStat SET uid=$uid, fid=".$GLOBALS['forum'].", us_count=1";
      $res = db_query($sql,$link);
    }
  }
  else {
    $sql = "UPDATE ".$GLOBALS['DBprefix']."Forum SET f__premodcount=f__premodcount+1 WHERE f_id=".$GLOBALS['forum'];
    $res = db_query($sql,$link);
  }

  if ($GLOBALS['opt_fixviews']==1) {
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."TopicView WHERE tid=\"$topic\"";
    $res = db_query($sql,$link);
    $sql = "INSERT INTO ".$GLOBALS['DBprefix']."TopicView (tid,uid) VALUES (\"$topic\",".$GLOBALS['inuserid'].")";
    $res = db_query($sql,$link);
    if ($GLOBALS['intopic']['lasttime']) {
      $sql = "UPDATE ".$GLOBALS['DBprefix']."LastVisit SET lv_markcount=lv_markcount-1 WHERE lv_markall>".$GLOBALS['intopic']['lasttime']." AND fid=".$GLOBALS['forum'];
      $res=db_query($sql,$link);
    }
  }

  if (($GLOBALS['inforum']['f_lmoderate']<=$GLOBALS['inuserlevel'] || check_selfmod()) && getvar("close")) {
      $sql = "UPDATE ".$GLOBALS['DBprefix']."Topic SET t__status=1 WHERE t_id=\"".$GLOBALS['topic']."\"";
      $res = db_query($sql,$link);
  }

  if (getvar("subscr") && $GLOBALS['inuserid']>3 && !$GLOBALS['intopic']['subscr']) {
      $sql = "INSERT INTO ".$GLOBALS['DBprefix']."Subscription VALUES (\"$inuserid\",\"$topic\",\"".$inforum['f_id']."\")";
      $res = db_query($sql,$link);
  }

  if (!$GLOBALS['inforum']['f_premoderate'] || $GLOBALS['inuserlevel']>=$GLOBALS['inforum']['f_lmoderate']) {
    $sql = "SELECT u__name,u__email,u_id,u__key FROM ".$GLOBALS['DBprefix']."Subscription sb, ".$GLOBALS['DBprefix']."User u WHERE sb.uid=u.u_id ".
    " AND sb.tid=\"".$GLOBALS['topic']."\" AND sb.uid!=".$GLOBALS['inuserid'];
    $buffer=load_mail("std_post.txt");
  }
  else {
    $sql = "SELECT u__name,u__email,u_id,u__key FROM ".$GLOBALS['DBprefix']."Subscription sb, ".$GLOBALS['DBprefix']."User u ".
    "LEFT JOIN ".$GLOBALS['DBprefix']."UserAccess ua ON (ua.uid=u.u_id AND ua.fid=".$GLOBALS['forum'].") ".
    "WHERE sb.uid=u.u_id AND sb.tid=\"".$GLOBALS['topic']."\" AND sb.uid!=".$GLOBALS['inuserid'].
    " AND ((ua_level IS NULL AND u__level<=".$GLOBALS['inforum']['f_lmoderate'].") OR (ua_level IS NOT NULL AND ua_level<=".$GLOBALS['inforum']['f_lmoderate']."))";
    $buffer=load_mail("std_pmod.txt");
    $GLOBALS['premod_link']=$GLOBALS['opt_url']."/index.php?m=moderate&a=premod&f=".$GLOBALS['forum'];
  }
  $res = db_query($sql,$link);
  $GLOBALS['ttitle']=$GLOBALS['intopic']['t_title'];
  $GLOBALS['ftitle']=$GLOBALS['inforum']['f_title'];
  $GLOBALS['text']=stripslashes($text);
  $GLOBALS['postername']=$GLOBALS['inuser']['u__name'];
  while ($email=db_fetch_row($res)) {
    $GLOBALS['username']=$email[0];
    $GLOBALS['flink']=$GLOBALS['opt_url']."/index.php?t=".$GLOBALS['topic'];
    $GLOBALS['unsublink']=$GLOBALS['opt_url']."/agent.php?a=unsub&u=".$email[2].
     "&f=".$GLOBALS['forum']."&t=".$GLOBALS['topic']."&key=".md5($GLOBALS['topic'].$email[3]);
    replace_mail($buffer,$email[1],$GLOBALS['ttitle']);
  }
  return $pid;
}

function topic_increment($forum,$topic,$pid) {
  $link=$GLOBALS['link'];
  if (!$GLOBALS['inforum']['f_premoderate'] || $GLOBALS['inuserlevel']>$GLOBALS['inforum']['f_lmoderate']) {
    $sql = "UPDATE ".$GLOBALS['DBprefix']."Forum SET f__tcount=f__tcount+1, f__startpostid=$pid WHERE f_id=$forum";
    $res=db_query($sql,$link);
    $sql = "UPDATE ".$GLOBALS['DBprefix']."Topic SET t__startpostid=$pid WHERE t_id=$topic";
    $res=db_query($sql,$link);
  }
}

function build_mod_list($forum,$flevel) {
  $link=$GLOBALS['link'];
  $GLOBALS['modlist']="";
  $sql = "SELECT u_id,u__name FROM ".$GLOBALS['DBprefix']."User ".
  "WHERE u_id>3 AND u__level>=$flevel AND u__level<1000";
  $res = db_query($sql,$link);
  while ($udata=db_fetch_array($res)) {
      if ($GLOBALS['modlist']) $GLOBALS['modlist'].=", ";
      $GLOBALS['modlist'].= user_out($udata['u__name'],$udata['u_id']);
  }

  $sql = "SELECT u_id,u__name FROM ".$GLOBALS['DBprefix']."User, ".
  $GLOBALS['DBprefix']."UserAccess WHERE u_id=uid AND fid=$forum ".
  "AND u_id>3 AND ua_level>=$flevel";
  $res = db_query($sql,$link);
  while ($udata=db_fetch_array($res)) {
      if ($GLOBALS['modlist']) $GLOBALS['modlist'].=", ";
      $GLOBALS['modlist'].= user_out($udata['u__name'],$udata['u_id']);
  }
  if (db_num_rows($res)==1) $GLOBALS['modlist']=MSG_moderator.": ".$GLOBALS['modlist'];
  elseif (db_num_rows($res)>1) $GLOBALS['modlist']=MSG_moderators.": ".$GLOBALS['modlist'];
}

function check_premod(&$fdata) {
    $link=$GLOBALS['link'];
    if ($GLOBALS['inuserbasic']>=$fdata['f_lmoderate'] || $fdata['ua_level']>=$fdata['f_lmoderate']) {
        $sql="SELECT COUNT(*) FROM ".$GLOBALS['DBprefix']."Post p, ".$GLOBALS['DBprefix']."Topic t ".
        "WHERE t_fid=".$fdata['f_id']." AND p_tid=t_id AND p__premoderate=1";
        $res = db_query($sql,$link);
        $pcount=db_fetch_row($res);
  }
  return $pcount[0];
}

function big_search_form($text,$starttime,$endtime,$type=0,$mode=0) {
  load_style("search.php");
  $link = $GLOBALS['link'];

//  if ($mode==0 || getvar("fs")=="all") {
    $sql = "SELECT f_id,f_title,ct_id,ct_name FROM ".$GLOBALS['DBprefix']."Category ct, ".$GLOBALS['DBprefix']."Forum f, ".$GLOBALS['DBprefix']."ForumType tp ".
    "LEFT JOIN ".$GLOBALS['DBprefix']."UserAccess ua ON (ua.uid=".$GLOBALS['inuserid']." AND ua.fid=f.f_id) ".
    "WHERE f_tpid=tp_id AND ct_id=f_ctid AND tp_searchable=1 AND f_lread<=IFNULL(ua_level, \"".$GLOBALS['inuserbasic']."\") ".
    "ORDER BY ct_sortfield,f_sortfield";
    $res = db_query($sql,$link);
    if (!$text) {
      $_POST['a']="do_post";
      $_POST['res']="post";
      $_POST['o']="relevancy";
    }
//  }
  search_form_start($mode,$text,$starttime,$endtime,$type);
  $oldcat=0;
//  if ($mode==0 || getvar("fs")=="all") {
    while ($fdata=db_fetch_array($res)) {
        if ($oldcat!=$fdata['ct_id']) {
            search_form_category($fdata['ct_id'],$fdata['ct_name']);
            $oldcat=$fdata['ct_id'];
        }
        search_form_entry($fdata);
    }
//  }
/*  elseif (is_array($_POST['fs'])) {
    foreach ($_POST['fs'] as $key=>$value)
     if (is_numeric($key) && is_numeric($value)) $buffer.="<input type=hidden name=\"fs[$key]\" value=\"$value\">";
  }
  elseif (is_array($_GET['fs'])) {
    foreach ($_GET['fs'] as $key=>$value)
     if (is_numeric($key) && is_numeric($value)) $buffer.="<input type=hidden name=\"fs[$key]\" value=\"$value\">";
  }*/
  search_form_end($buffer);
}

function last_topics($topics=10,$onlyforum=0) {
    $link=$GLOBALS['link'];

    if ($onlyforum) $sqldata=" AND f_tpid=1";
    $sql = "SELECT t_id,t_title FROM ".$GLOBALS['DBprefix']."Topic,  ".$GLOBALS['DBprefix']."Forum f ".
    "LEFT JOIN ".$GLOBALS['DBprefix']."UserAccess ua ON (ua.uid=".$GLOBALS['inuserid']." AND ua.fid=f.f_id) ".
    "WHERE t_fid=f_id AND t__pcount>0 $sqldata AND ".
    "f.f_lview<=IFNULL(ua_level,".$GLOBALS['inuserbasic'].") ".
    "ORDER BY t_id DESC LIMIT $topics";
    $res = db_query($sql,$link);
    tlist_start(MSG_t_lasts." ".format_word($topics,MSG_t1,MSG_t2,MSG_t3));
    while ($tdata=db_fetch_row($res)) {
      $list.=tlist_entry($tdata);
    }
    tlist_end();
}

function active_topics($topics=10,$onlyforum=0) {
    $link=$GLOBALS['link'];
    
    if ($onlyforum) $sqldata=" AND f_tpid=1";
    $sql = "SELECT t_id,t_title FROM ".$GLOBALS['DBprefix']."Topic, ".$GLOBALS['DBprefix']."Forum f ".
    "LEFT JOIN ".$GLOBALS['DBprefix']."UserAccess ua ON (ua.uid=".$GLOBALS['inuserid']." AND ua.fid=f.f_id) ".
    "WHERE t_fid=f_id AND  f.f_lview<=IFNULL(ua_level,".$GLOBALS['inuserbasic'].") AND t__pcount>0 $sqldata ".
    "ORDER BY t__pcount DESC LIMIT $topics";
    $res = db_query($sql,$link);
    tlist_start(MSG_t_actives." ".format_word($topics,MSG_t1,MSG_t2,MSG_t3));
    while ($tdata=db_fetch_row($res)) {
        $list.=tlist_entry($tdata);
    }
    tlist_end();
}

function check_system_pass($password) {
    $link=$GLOBALS['link'];
    $sql = "SELECT u__password FROM ".$GLOBALS['DBprefix']."User WHERE u_id=2";
    $res = db_query($sql,$link);
    list($rightpass)=db_fetch_row($res);
    db_free_result($res);

    if (md5($password)==$rightpass) $result=1;
    else $result=0;
    return $result;
}

function check_ddos($name) {
    $code = getvar($name);
    $link=$GLOBALS['link'];
    $sid=session_id();
    $sql = "SELECT code FROM ".$GLOBALS['DBprefix']."Code WHERE sid=\"$sid\"";
    $res = db_query($sql,$link);
    list($rightcode)=db_fetch_row($res);
    $res = db_query($sql,$link);
    if ($code!=$rightcode) error(MSG_e_badcode);
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."Code WHERE sid=\"$sid\"";
    $res = db_query($sql,$link);
}

function do_rate() {
    $link=$GLOBALS['link'];
    if ($GLOBALS['inuserid']<=3) error(MSG_e_t_rnoguest);
    $sql = "SELECT COUNT(*) FROM ".$GLOBALS['DBprefix']."TopicRate WHERE tid=\"".$GLOBALS['topic']."\" AND uid=\"".$GLOBALS['inuserid']."\"";
    $res = db_query($sql,$link);
    $rate = db_fetch_row($res);
    db_free_result($res);

    if ($rate[0]>0) error(MSG_e_t_rated);
    $trvalue=getvar("tr_value");
    if ($trvalue<1 || $trvalue>7) error(MSG_e_t_badvalue);
    $sql = "INSERT INTO ".$GLOBALS['DBprefix']."TopicRate VALUES(\"".$GLOBALS['topic']."\", \"".$GLOBALS['inuserid']."\",\"$trvalue\")";
    $res = db_query($sql,$link);

    $sql = "UPDATE ".$GLOBALS['DBprefix']."Topic SET t__ratingsum=t__ratingsum+$trvalue, t__ratingcount=t__ratingcount+1 WHERE t_id=".$GLOBALS['topic'];
    $res = db_query($sql,$link);
    topic_message(MSG_t_rated,1);
}

function format_calendar($vardate,$mindate,$reflink) {
    $day = date("j",$vardate);
    $month = date("n",$GLOBALS['curtime']);
    $year = date("Y",$GLOBALS['curtime']);
    $curdate=mktime(0,0,0,$month,$day,$year);
    $testdate=mktime(0,0,0,date("n",$mindate),1,date("Y",$mindate));
    $first_day=date("w",mktime(0,0,0,date("n",$vardate),1,date("Y",$vardate)));
    if ($first_day==0) $first_day=7;
    while ($curdate>=$testdate) {
        $monthselect.="<option value=\"$curdate\">1-".date("t",$curdate)." ".date("F",$curdate)." ".date("Y",$curdate);
        $month--;
        if ($month<1) { $month=12; $year--; }
        $curdate=mktime(0,0,0,$month,$day,$year);
    }
    $days_in_month=date("t",$vardate);
    $monthselect=month_replace($monthselect);
    $reflen=strlen($reflink);
    if ($reflink[$reflen-1]!="&" && $reflink[$reflen-1]!="?") {
        if (strpos($reflink,"?")===false) $reflink.="?";
        else $reflink.="&";
    }
    calendar_out($vardate,$monthselect,$days_in_month,$mindate,$first_day,$reflink);
}

function f_rules() {
    $ref=$_ENV['HTTP_REFERER'];
    if (!$ref) $ref="index.php?f=".$GLOBALS['forum'];
    forum_rules($ref,$GLOBALS['inforum']['f_rules']);
}

function fast_switch($button=true) {
    $flist = build_forum_select("f_lview");
    fast_switch_form($flist,$button);
}

function present_list() {
$link=$GLOBALS['link'];
$mode=$GLOBALS['opt_showpresent'];
$forum=$GLOBALS['forum'];
$topic=$GLOBALS['topic'];
$action=$GLOBALS['action'];
$module=$GLOBALS['module'];
$inuserid=$GLOBALS['inuserid'];

if ($action && $action!="view" && $action!="contnr_view" && ($module=="main" || $module==$inforum['tp_library'])) $mode=0;
if ($mode==1 && $forum) $mode=0;
if ($mode==2 && $topic) $mode=0;
if ($mode) {
  $lasttime = $GLOBALS['curtime']-$GLOBALS['opt_heretime']*60;
  $query="";
  if ($forum) $query=" AND uo_fid=\"$forum\"";
  elseif ($topic) $query.=" AND uo_tid=\"$topic\"";
  $sql = "SELECT u_id,u__name,u_hidden,uo_ip ".
  "FROM ".$GLOBALS['DBprefix']."LogSession sid, ".$GLOBALS['DBprefix']."LogEntry uo, ".$GLOBALS['DBprefix']."User ".
  "WHERE u_id=uo_curid AND sid_id=uo_id AND uo_lasttime=uo_time AND uo_lasttime>$lasttime ".
  "$query ORDER BY uo_lasttime DESC";
  $res = db_query($sql,$link);
  $visited=array();
  $visitip=array();
  while ($udata=db_fetch_array($res)) {
        if ($udata['sid_id']==$_SESSION['sid_num']) $found=1;
        if ($udata['u_id']>3 && !$visited[$udata['u_id']]) {
          if ($udata['u_hidden']) {
            $hidden++;
          }
          elseif (!$udata['u_hidden']) {
            $users++;
            $userlist.=" &raquo; ".user_out($udata['u__name'],$udata['u_id']);
          }
        $visited[$udata['u_id']]++;
        }
        elseif ($udata['u_id']<=3 && !$visitip[$udata['uo_ip']]) { $guests++; $visitip[$udata['uo_ip']]++; }
  }
  if (!$visited[$GLOBALS['inuserid']] && $GLOBALS['inuserid']>3 && !$GLOBALS['inuser']['u_hidden']) {
        $users++;
        $userlist.=" &raquo; ".user_out($GLOBALS['inuser']['u__name'],$GLOBALS['inuserid']);
  }
  elseif (!$visited[$GLOBALS['inuserid']] && $GLOBALS['inuserid']>3) $hidden++;
  elseif ($GLOBALS['inuserid']<=3 && !$visitip[iptonum(getip())]) $guests++;
  if ($users+$hidden+$guests>$GLOBALS['opt_record_count']) {
    $GLOBALS['opt_record_count']=$users+$hidden+$guests;
    $GLOBALS['opt_record_guests']=$guests;
    $GLOBALS['opt_record_date']=$GLOBALS['curtime'];
    options_save();
  }
  $GLOBALS['totalmsg']=format_word($users+$hidden+$guests,MSG_u1." ".MSG_uv1,MSG_u2." ".MSG_uv2,MSG_u3." ".MSG_uv3);
  $GLOBALS['timemsg']=format_word($GLOBALS['opt_heretime'],MSG_m1,MSG_m2,MSG_m2,MSG_lm1,MSG_lm2,MSG_lm3);
  $usercount=format_word($guests,MSG_ug1,MSG_ug2,MSG_ug3).", ".format_word($hidden,MSG_uh1,MSG_uh2,MSG_uh3);
  if (($action=="view" || !$action) && $module=="main") {
    $GLOBALS['recordmsg']=format_word($GLOBALS['opt_record_count'],MSG_u1,MSG_u2,MSG_u3,MSG_uv1,MSG_uv2,MSG_uv3);
    $GLOBALS['guestmsg']=format_word($GLOBALS['opt_record_guests'],MSG_ug1,MSG_ug2,MSG_ug3);
  }
  $visited=array();
  $visitip=array();
  $fount=0;
  if ($module=="main" && $action=="view") {
    $curtime=$GLOBALS['curtime'];
    $todaytime=$curtime-($curtime % (24*60*60))-$GLOBALS['inuser']['u_timeregion'];
    if ($curtime-$todaytime>24*60*60) $todaytime=$todaytime+24*60*60;
    $sql = "SELECT u_id,u__name,u_hidden,uo_ip FROM ".$GLOBALS['DBprefix']."LogSession, ".$GLOBALS['DBprefix']."User WHERE u_id=uo_maxuid AND uo_lasttime>=$todaytime ".
     " ORDER BY uo_lasttime DESC";
    $res = db_query($sql,$link);
    while ($udata=db_fetch_array($res)) {
       if ($udata['u_id']>3 && !$visited[$udata['u_id']]) {
          if ($udata['u_hidden']) {
            $today_hidden++;
          }
          elseif (!$udata['u_hidden']) {
            $today_users++;
            $today_userlist.=" &raquo; ".user_out($udata['u__name'],$udata['u_id']);
          }
          $visited[$udata['u_id']]++;
       }
       elseif ($udata['u_id']<=3 && !$visitip[$udata['uo_ip']]) { $today_guests++; $visitip[$udata['uo_ip']]++; }
    }
    if (!$visited[$GLOBALS['inuserid']] && $GLOBALS['inuserid']>3 && !$GLOBALS['inuser']['u_hidden']) {
        $today_users++;
        $today_userlist.=" &raquo; ".user_out($GLOBALS['inuser']['u__name'],$GLOBALS['inuserid']);
    }
    elseif (!$visited[$GLOBALS['inuserid']] && $GLOBALS['inuserid']>3) $today_hidden++;
    elseif ($GLOBALS['inuserid']<=3 && !$visitip[iptonum(getip())]) $today_guests++;
    $today_usercount=format_word($today_guests,MSG_ug1,MSG_ug2,MSG_ug3).", ".format_word($today_hidden,MSG_uh1,MSG_uh2,MSG_uh3);
  }

  if ($forum && !$topic) main_present_users(MSG_f_in,$userlist,$users,$usercount,$today_userlist,$today_users,$today_usercount);
  if ($forum && $topic) main_present_users(MSG_topic_in,$userlist,$users,$usercount,$today_userlist,$today_users,$today_usercount);
  if (!$forum && !$topic) main_present_users(MSG_forum_in,$userlist,$users,$usercount,$today_userlist,$today_users,$today_usercount);
 }
}

function check_post_params() {
  check_post();
  if ($GLOBALS['inforum']['f_smiles']) $sqldata.=", p__smiles=\"".getvar("p__smiles")."\"";
  if ($GLOBALS['inforum']['f_bcode']) $sqldata.=", p__bcode=\"".getvar("p__bcode")."\"";
  if ($GLOBALS['inuserlevel']>=$GLOBALS['inforum']['f_lhtml']) $sqldata.=", p__html=\"".getvar("p__html")."\"";
  if ($GLOBALS['inuserlevel']>=$GLOBALS['inforum']['f_lmoderate']) $sqldata.=", p__modcomment=\"".getvar('p__modcomment')."\" ";
  if (!isset($_POST['p_signature'])) $sqldata.=", p_signature=0 ";
  return $sqldata;
}

function check_topic_params() {
    check_post();
    $inforum=$GLOBALS['inforum'];
    if ($GLOBALS['inuserlevel']<$inforum['f_lpost']) error(MSG_e_p_norights);
    if ($inforum['f_status']!=0) error(MSG_e_f_closed);
    if (!$text=db_slashes($_POST['p_text'])) error(MSG_e_p_empty);

    if (strlen($text)<$GLOBALS['opt_minpost']) error(MSG_e_p_toosmall);
    if ($GLOBALS['opt_maxpost'] && strlen($text)>$GLOBALS['opt_maxpost']) error(MSG_e_p_toolarge);

    if (getvar("t__rate") && $GLOBALS['inforum']['f_rate']) $sqldata.=", t__rate=1";
    if ($GLOBALS['inforum']['f_lsticky']<=$GLOBALS['inuserlevel']) $sqldata.=", t__sticky=\"".getvar('t__sticky')."\"";
    if ($GLOBALS['inforum']['f_lsticky']<=$GLOBALS['inuserlevel']) $sqldata.=", t__stickypost=\"".getvar('t__stickypost')."\"";
    return $sqldata;
}

function list_smiles($func,$row=1) {
  $link=$GLOBALS['link'];
  $sql = "SELECT * FROM ".$GLOBALS['DBprefix']."Smile";
  $res = db_query($sql,$link);
  if (is_array($GLOBALS['smiles'])) foreach ($GLOBALS['smiles'] as $smcode=>$smfile) if ($GLOBALS['smileshow'][$smcode]) {
    $buffer.="<a href=\"javascript:$func(' ".$smcode." ')\"><img border=0 src=\"smiles/".$smfile."\" alt=\"".$smcode."\"></a>&nbsp;";
    $counter++;
    if ($row && ($counter % $row)==0) $buffer.="<br>";
  }
  return $buffer;
}

function show_vote($votetopic) {
  $link=$GLOBALS['link'];
  $sql = "SELECT COUNT(*) FROM ".$GLOBALS['DBprefix']."Vote WHERE uid=".$GLOBALS['inuserid']."  AND tid=$votetopic";
  $res = db_query($sql,$link);
  list($voted)=db_fetch_row($res);
  db_free_result($res);
  $sql = "SELECT pl.* FROM ".$GLOBALS['DBprefix']."Poll pl WHERE pl_tid=$votetopic";
  $res = db_query($sql,$link);

  if ($pldata=db_fetch_array($res)) {
      $pldata['voted']=$voted;
      if ($pldata['voted'] || $GLOBALS['inuserid']<=3 ||
           ($pldata['pl_enddate'] && $pldata['pl_enddate']<$GLOBALS['curtime'])) show_vote_resbegin($pldata);
      else std_vote_begin($pldata);
      $sql = "SELECT pv_id,pv_text, pv_count FROM ".$GLOBALS['DBprefix']."PollVariant pv ".
      "WHERE pv_plid=".$pldata['pl_id'];
      $res = db_query($sql,$link);
      $pv_text = array();
      while ($pv_data=db_fetch_array($res)) {
        $pv_count[$pv_data['pv_id']]=$pv_data['pv_count'];
        $pv_total+=$pv_data['pv_count'];
        $pv_text[$pv_data['pv_id']]=$pv_data['pv_text'];
      }
      db_free_result($res);
      foreach ($pv_text as $curid=>$curtext) {
        if ($pldata['voted'] || $GLOBALS['inuserid']<=3 ||
           ($pldata['pl_enddate'] && $pldata['pl_enddate']<$GLOBALS['curtime'])) show_vote_resentry($pv_text[$curid],$pv_count[$curid],$pv_total);
        else show_vote_entry($pv_text[$curid],$curid);
      }
      if ($pldata['voted'] || $GLOBALS['inuserid']<=3 ||
           ($pldata['pl_enddate'] && $pldata['pl_enddate']<$GLOBALS['curtime'])) show_vote_resend($pv_total);
      else show_vote_end();
  }
}

function options_save() {
  $fh = fopen($GLOBALS['opt_dir']."/config/iboard.php","w") or global_error("Unable to create iboard.php");
  fputs($fh,"<? if (!\$IBOARD) die(\"Hack attempt!\");\n");
  $keys = preg_grep("/opt_/",array_keys($GLOBALS));
  flock($fh,LOCK_EX);
  foreach ($keys as $curkey) {
    fputs($fh,"\$$curkey=\"".addslashes($GLOBALS[$curkey])."\";\n");
  }
  fclose($fh);
}

function check_warnings(&$udata) {
  $link=$GLOBALS['link'];
  $uw_value=$udata['u__warnings'];
  if ($udata['u_warntime']>0 && $udata['u__warntime']<$GLOBALS['curtime']) {
    $sql = "SELECT SUM(uw_value),MAX(uw_validtill) FROM ".$GLOBALS['DBprefix']."UserWarning WHERE uw_uid=".$udata['u_id']." AND uw_validtill=0 OR uw_validtill>".$GLOBALS['curtime'];
    $res = db_query($sql,$link);
    list($uw_value,$uw_validtill)=db_fetch_row($res);
    db_free_result($res);
    if ($uw_validtill<$GLOBALS['curtime']) $uw_validtill="0";
    $sql = "UPDATE ".$GLOBALS['DBprefix']."User SET u__warnings=$uw_value, u__warntime=$uw_validtill WHERE u_id=".$udata['u_id'];
    $res = db_query($sql,$link);
  }
  return $uw_value;
}

function get_premod() {
  return $GLOBALS['inforum']['f__premodcount'];
}

function debug($text) {
  if ($GLOBALS['inuserbasic']>=1000) echo $text."<br>";
}

function edit_post($func,$msg) {
  $link=$GLOBALS['link'];
  $pid=getvar("p");
  $sql = "SELECT * FROM ".$GLOBALS['DBprefix']."Post p, ".$GLOBALS['DBprefix']."User u ".
  "LEFT JOIN ".$GLOBALS['DBprefix']."UserAccess ua ON (ua.uid=u.u_id AND ua.fid=".$GLOBALS['forum'].") ".
  "WHERE p_id=\"$pid\" AND u.u_id=p.p_uid AND p_tid=".$GLOBALS['topic'];
  $res = db_query($sql,$link);
  if (db_num_rows($res)!=1) error(MSG_e_p_notfound);
  $pdata = db_fetch_array($res);
  db_free_result($res);
  if (($pdata['p_uid']!=$GLOBALS['inuserid'] || $GLOBALS['inuserlevel']<$GLOBALS['inforum']['f_ledit']) && $GLOBALS['inuserlevel']<$GLOBALS['inforum']['f_lmoderate']) error(MSG_e_p_noeditrights);
  if ($pdata['p_uid']!=$GLOBALS['inuserid'] && check_moderate($pdata,$GLOBALS['inuserlevel'])) error(MSG_e_mod_subordinate);
  if ($func!="std_post_form") call_user_func($func,$pdata,$msg,"do_edit_post");
  else std_post_form(MSG_p_edit,"do_edit_post",$pdata,0);
}

function do_edit_post() {
  if (getvar("delete")) { do_delete_comment(); return; }
  $pid=getvar("p");
  $link=$GLOBALS['link'];
  $sql = "SELECT p_uid,p_id,p_attach FROM ".$GLOBALS['DBprefix']."Post p, ".$GLOBALS['DBprefix']."User u ".
  "LEFT JOIN ".$GLOBALS['DBprefix']."UserAccess ua ON (ua.uid=u.u_id AND ua.fid=".$GLOBALS['forum'].") ".
  "WHERE p_id=\"$pid\" AND u.u_id=p.p_uid";
  $res = db_query($sql,$link);
  if (db_num_rows($res)!=1) error(MSG_e_p_notfound);
  $pdata = db_fetch_array($res);
  db_free_result($res);
  if ($GLOBALS['inuserlevel']<$GLOBALS['inforum']['f_ledit']) error(MSG_e_p_noeditrights);
  if ($pdata['p_uid']!=$GLOBALS['inuserid'] && check_moderate($pdata,$GLOBALS['inuserlevel'])) error(MSG_e_mod_subordinate);
  unset($_POST['p_uid']);
  unset($_POST['p_tid']);

  $inforum=$GLOBALS['inforum'];
  $inuserlevel=$GLOBALS['inuserlevel'];
  $sqldata = build_sql("p_");
  $sqldata.= check_post_params();

  if ($GLOBALS['inuserid']==$pdata['p_uid']) $sqldata .= ", p__edittime=".$GLOBALS['curtime'];
  if ($pdata['p_attach']==0 && is_uploaded_file($_FILES['attach']['tmp_name'])) {
    if ($inuserlevel<$inforum['f_lattach']) error(MSG_e_p_norightsattach);
    if ($inforum['f_attachpics']) {
      check_image("attach",$GLOBALS['opt_maxfileattach'],0,0,MSG_e_p_toobig,MSG_e_p_onlypics,"");
    }
    elseif ($_FILES['attach']['size']>$GLOBALS['opt_maxfileattach']) error(MSG_e_p_toobig);
    $fsize=$_FILES['attach']['size'];
    $fh=fopen($_FILES['attach']['tmp_name'],"r");
    $buffer=fread($fh,$fsize);
    fclose($fh);
    $sql = "INSERT INTO ".$GLOBALS['DBprefix']."File (file_data,file_type,file_name)  VALUES(\"".db_slashes($buffer)."\",\"".$_FILES['attach']['type'].
    "\",\"".db_slashes($_FILES['attach']['name'])."\")";
    $res = db_query($sql,$link);
    $pattach = db_insert_id($res);
    $sqldata.=", p_attach=$pattach";
  }
  elseif ($pdata['p_attach']!=0 && is_uploaded_file($_FILES['attach']['tmp_name'])) {
    if ($inuserlevel<$inforum['f_lattach']) error(MSG_e_p_norightsattach);
    if ($inforum['f_attachpics']) {
      check_image("attach",$GLOBALS['opt_maxfileattach'],0,0,MSG_e_p_toobig,MSG_e_p_onlypics,"");
    }
    elseif ($_FILES['attach']['size']>$GLOBALS['opt_maxfileattach']) error(MSG_e_p_toobig);
    $fsize=$_FILES['attach']['size'];
    $fh=fopen($_FILES['attach']['tmp_name'],"r");
    $buffer=fread($fh,$fsize);
    fclose($fh);
    $sql = "UPDATE ".$GLOBALS['DBprefix']."File SET file_data=\"".db_slashes($buffer)."\", file_type=\"".$_FILES['attach']['type'].
    "\",\"".db_slashes($_FILES['attach']['name'])."\" WHERE file_id=".$pdata['p_attach'];
    $res = db_query($sql,$link);
  }
  elseif (getvar("delattach") && $pdata['p_attach']!=0) {
    $sqldata.=", p_attach=0";
    $sql = "DELETE FROM ".$GLOBALS['DBprefix']."File WHERE file_id=".$pdata['p_attach'];
    $res = db_query($sql,$link);
  }
  $sql = "UPDATE ".$GLOBALS['DBprefix']."Post SET $sqldata WHERE p_id=\"$pid\"";
  $res = db_query($sql,$link);
  topic_message(MSG_p_edited,1);
}

function do_delete_comment() {
  if ($GLOBALS['inuserlevel']<$GLOBALS['inforum']['f_lmoderate']) error(MSG_e_mod_norights);
//  $link = $GLOBALS['link'];
  $pid=getvar("p");
  delete_post($pid);
  topic_resync($GLOBALS['topic']);
  forum_resync($GLOBALS['forum']);
  topic_message(MSG_p_deleted,1);
}
?>
