<?php


/****
 * ACTION: activation by user [+]
 ****/
 if ($action == "activate") {
    $ua = trim($_REQUEST["ua"]);
    $aa = trim($_REQUEST["aa"]);
    
    if ($ua) {
      //user activation
      $sql = "update `" . $ftable_prefix . "users` set status = '1' where md5(concat(id,user)) = " . dbquote($ua) . " and status = '0';";
      dbquery($sql);
      if (mysql_affected_rows()) $success = lang("success_activated");
    } elseif ($aa) {
      //user activation
      $sql = "update `" . $ftable_prefix . "users` set status = '1' where md5(concat(user,id*7)) = " . dbquote($aa) . " and status = '0';";
      dbquery($sql);
      if (mysql_affected_rows()) {
        //get user info
        $sql = "select * from `" . $ftable_prefix . "users` where md5(concat(user,id*7)) = " . dbquote($aa) . ";";
        $res = dbquery($sql);
        $row = mysql_fetch_object($res);
        //Template Variables
        $USERNAME = $row->user;
        $BOARD_ADMIN = $conf_board_admin;

        /************
         * initiate template and assign variables
         ************/                 
        $mailVARS = array('CONF_FORUMTITLE' => $GLOBAL_TEMPLATE_VARS["FORUMTITLE"], 'USERNAME' => $USERNAME, 'BOARD_ADMIN' => $BOARD_ADMIN);
        $QuickSkin = new QuickSkin("mail_welcome_activated.txt");
        $QuickSkin->set("template_dir","$www_dir/lang/$f_lang/");
        $QuickSkin->assign($mailVARS);
        $mail_mess = $QuickSkin->result();
        unset($QuickSkin);
        
        mail ($row->email, sprintf(lang("subject_activated"),$CONF_FORUMTITLE), $mail_mess, "From: $conf_board_mailfrom");
        $success = lang("success_activated");
      }
    }
    if ($ua) $todo = "login";
 }
 
/****
 * ACTION: activation by user [-]
 ****/


/****
 * ACTION: act/deact user [+]
 ****/
 if ($action == "chgstat" && $is_mod) {
    $uid = intval($_REQUEST["uid"]);
    $stat = intval($_REQUEST["stat"]);
    $sql = "update `" . $ftable_prefix . "users` set status = '" . ($stat ? 0 : 1) . "' where id = '$uid' and deleteable = 1;";
    dbquery($sql);
    $success = sprintf(lang("success_userstatchg"),($stat?"de":""));
    $todo = "adminusers";
 }
 
/****
 * ACTION: act/deact user [-]
 ****/


/****
 * ACTION: like/dislike post [+]
 ****/
 if ($action == "likepost" || $action == "dislikepost") {
    $tid = intval($_REQUEST["tid"]);
    $pid = intval($_REQUEST["pid"]);
    if (!$tid && !$pid) $error[] = lang("error_notenough");
    if (!$error) {
      $sql = "select * from `" . $ftable_prefix . "question` where id = '$tid'";
      $res = dbquery($sql);
      if (!mysql_num_rows($res)) $error[] = lang("error_topicnotfound");
      else {
        if (!$pid) {
          $row = mysql_fetch_object($res);
          $uid = $row->uid;
        } else {
          $sql = "select * from `" . $ftable_prefix . "answer` where a_id = '$pid' and question_id = '$tid'";
          $res = dbquery($sql);
          if (!mysql_num_rows($res)) $error[] = lang("error_topicnotfound");
          else $uid = $row->a_uid;
        }
      }
    }
    if (!$error) {
      $ratingInfo = rating_permission($uid,$tid,$pid);
      if ($ratingInfo === false) $error[] = lang("error_noperm");
      elseif (in_array($ratingInfo, array(1,-1))) $info = lang("info_already_rated");
    }
    if (!$error && !$info) {
      $sql = "insert into `" . $ftable_prefix . "ratings` set tid = '$tid', pid = '$pid', uid = '$f_auth_uid', username = " . dbquote($SBBAuth->user) . ", rating = '" . ($action == "likepost" ? "1" : "-1") . "', created = now()";
      dbquery($sql);
      $success = lang($action == "likepost" ? "success_likepost" : "success_dislikepost");
    }
    $todo = "viewtopic";
 }
/****
 * ACTION: like/dislike post [-]
 ****/

 
/****
 * ACTION: watch topic [+]
 ****/
 if ($action == "watchtopic") {
    $tid = intval($_REQUEST["tid"]);
    //first delete to prevent of doubles
    $sql = "delete from `" . $ftable_prefix . "watchlist` where uid = '$f_auth_uid' and tid = '$tid';";
    dbquery($sql);
    //add watch
    $sql = "insert into `" . $ftable_prefix . "watchlist` set uid = '$f_auth_uid', tid = '$tid';";
    dbquery($sql);
    $success = lang("success_watchtopic");
    $todo = "viewtopic";
 }
/****
 * ACTION: watch topic [-]
 ****/

 /****
 * ACTION: unwatch topic [+]
 ****/
 if ($action == "unwatchtopic") {
    $tid = intval($_REQUEST["tid"]);
    //first delete to prevent of doubles
    $sql = "delete from `" . $ftable_prefix . "watchlist` where uid = '$f_auth_uid' and tid = '$tid';";
    dbquery($sql);
    $success = lang("success_unwatchtopic");
    $todo = "viewtopic";
 }
/****
 * ACTION: unwatch topic [-]
 ****/
 
/****
 * ACTION: watch forum [+]
 ****/
 if ($action == "watchforum") {
    $fid = intval($_REQUEST["fid"]);
    //first delete to prevent of doubles
    $sql = "delete from `" . $ftable_prefix . "watchlist` where uid = '$f_auth_uid' and fid = '$fid';";
    dbquery($sql);
    //add watch
    $sql = "insert into `" . $ftable_prefix . "watchlist` set uid = '$f_auth_uid', fid = '$fid';";
    dbquery($sql);
    $success = lang("success_watchforum");
    $todo = "show_topics";
 }
/****
 * ACTION: watch forum [-]
 ****/

 /****
 * ACTION: unwatch forum [+]
 ****/
 if ($action == "unwatchforum") {
    $fid = intval($_REQUEST["fid"]);
    //first delete to prevent of doubles
    $sql = "delete from `" . $ftable_prefix . "watchlist` where uid = '$f_auth_uid' and fid = '$fid';";
    dbquery($sql);
    $success = lang("success_unwatchforum");
    $todo = "show_topics";
 }
/****
 * ACTION: unwatch forum [-]
 ****/

/****
 * ACTION: reset password [+]
 ****/
if ($action == "reset_password") {
  $fuser = trim(strip_tags($_REQUEST["fuser"]));
  $femail = trim(strtolower($_REQUEST["femail"]));
  if (!$fuser) $error[] = lang("error_nonickname");
  if (!$femail) $error[] = lang("error_nomail");
  elseif (!is_email($femail)) $error[] = lang("error_invalidmail");
  if (!$error) {
    $sql = "select * from `" . $ftable_prefix . "users` where user like " . dbquote($fuser) . " and email = '$femail' and status = '1';";
    $res = dbquery($sql);
    if (!mysql_num_rows($res)) $error[] = lang("error_nickemailkombinotfound");
    else {
      $row = mysql_fetch_object($res);
      $newpwd = genPWD(6);
      $sql = "update `" . $ftable_prefix . "users` set pwd = password('$newpwd') where id = '" . $row->id . "';";
      dbquery($sql);
      //creating, parsing and sending the email
      //Template Variables
      $RCPT_NAME = $row->user;
      $NEWPWD = $newpwd;
      $BOARD_ADMIN = $conf_board_admin;      

      /************
       * initiate template and assign variables
       ************/                 
      $mailVARS = array('CONF_FORUMTITLE' => $GLOBAL_TEMPLATE_VARS["FORUMTITLE"], 'RCPT_NAME' => $RCPT_NAME, 'NEWPWD' => $NEWPWD, 'BOARD_ADMIN' => $BOARD_ADMIN);
      $QuickSkin = new QuickSkin("mail_reset_password.txt");
      $QuickSkin->set("template_dir","$www_dir/lang/$f_lang/");
      $QuickSkin->assign($mailVARS);
      $mail_mess = $QuickSkin->result();
      unset($QuickSkin);

      mail ($row->email, sprintf(lang("subject_reset_password"),$GLOBAL_TEMPLATE_VARS["FORUMTITLE"]), $mail_mess, "From: $conf_board_mailfrom");
      $success = lang("success_passsent");
    }
  }
  if (!$error) {
    
    $todo = "login";
  } else {
    $todo = "reset_password";
  } 
}
/****
 * ACTION: reset password [+]
 ****/


/****
 * ACTION: VOTE [+]
 ****/
 if ($action == "vote" && $f_auth_uid) {
    $tid = intval($_REQUEST["tid"]);
    $poll_option_ids = $_REQUEST["poll_id"];
    
    if (!$tid) $error[] = lang("error_notenough");
    if (!$poll_option_ids) $error[] = lang("error_nopolls");
    if (voted($tid)) $error[] = lang("error_allreadyvoted");
    
    if (!$error) {
      for ($i=0;$i<count($poll_option_ids);$i++) {
        $this_options_id = $poll_option_ids[$i];
        dbquery("update `" . $ftable_prefix . "poll_options` set votes = votes + 1 where id = '$this_options_id' and tid = '$tid';");
        if (mysql_affected_rows()) dbquery("insert into `" . $ftable_prefix . "polls` set poll_option_id = '$this_options_id', uid = '$f_auth_uid', created = now();");
      }
      $success = lang("success_vote");
    }
    $todo = "viewtopic";
 }
 
/****
 * ACTION: VOTE [-]
 ****/


/****
 * ACTION: create/edit user [+]
 ****/
if ($action == "edit_account") {
  $fuser = trim(strip_tags($_REQUEST["fuser"]));
  $fpwd = trim($_REQUEST["fpwd"]);
  $fpwdconf = trim($_REQUEST["fpwdconf"]);
  $femail = trim(strtolower($_REQUEST["femail"]));
  $fusermail = intval($_REQUEST["fusermail"]);
  $fforummail = intval($_REQUEST["fforummail"]);
  $codec2 = intval($_REQUEST["codec2"]);
  $captchacode = $_REQUEST["captchacode"];
  $signature = substr(trim($_REQUEST["signature"]),0,250);
  $website = trim($_REQUEST["website"]);
  $interests = trim($_REQUEST["interests"]);
  $occupation = trim($_REQUEST["occupation"]);
  $location = trim($_REQUEST["location"]);
  $bd = $_REQUEST["bd"];
  $bm = $_REQUEST["bm"];
  $by = intval($_REQUEST["by"]);
  $gravatar = intval($_REQUEST["gravatar"]);
  $sbb_avatar = trim($_REQUEST["sbb_avatar"]);
  $sbb_avatar = preg_replace('/.*\/images\/avatars\//','',$sbb_avatar);
  
  if ($website && !preg_match('/^http/i',$website)) $website = "http://$website";
  if ($bm && $bd) {
    if ($by && $by<100) $by += 1900;
    if (!$by) $by = 1900;
    $birthday = "$by-$bm-$bd";
  }
  
  //avatar
  $delavatar = intval($_REQUEST["delavatar"]);
  $afile = $_FILES["avf"];
  $afile_name = $afile["name"];
  $afile_type = $afile["type"];
  $atmp_name = $afile["tmp_name"];
  $afile_type = $afile["type"];
  $afname = tidyup($afile_name);
  if ($afile_name) {
    $ext = explode(".",$afile_name);
    $ext = array_pop($ext);
    if (!in_array(strtolower($ext),$img_ext_arr)) $error[] = sprintf(lang("error_wrongimgext"),implode(", ",$img_ext_arr));
    else {
      list ($w,$h) = getimagesize($atmp_name);
      if ($w > $board_config->avatar_width || $h > $board_config->avatar_height) {
        if (!function_exists("gd_info")) $error[] = lang("error_imgdimensions");
      }
    }
  }

  if (!$fuser && !$forum_user) $error[] = lang("error_nonickname");
  elseif (!preg_match("/^[a-zA-Z0-9\.\-\* ]*$/",$fuser)) $error[] = lang("error_nickchar");
  if (!$f_auth_uid && !$fpwd) $error[] = lang("error_nopass");
  if (!$error && $fpwd) {
      if ($fpwd != $fpwdconf) $error[] = lang("error_passnomatch");
    }
  if (!$femail) $error[] = lang("error_nomail");
  elseif (!is_email($femail)) $error[] = lang("error_invalidmail");
  if (!$error && ($fuser != $forum_user->user) && $board_config->reserved_users) {
    //prevent from registering this users
    $reserved_users = explode(",",$board_config->reserved_users);
    for ($i=0;$i<count($reserved_users);$i++) {
      if (strtolower($fuser) == trim($reserved_users[$i])) {
        $error[] = lang("error_reserved");
        break;
      }
    }
  }

  if (!$error) {
    //username registered?
    $sql = "select * from `" . $ftable_prefix . "users` where user like " . dbquote($fuser) . " and id != '$f_auth_uid';";
    $res = dbquery($sql);
    if (mysql_num_rows($res)) $error[] = sprintf(lang("error_userregistered"), $fuser);
  }
  //is the user about to register and use_captcha is enabled - so check the code
  if ($board_config->use_cap && !$forum_user) {

    //recaptcha
    if ($board_config->use_cap == 3) {
      require_once("$rel_path/includes/recaptchalib.php");
      $recap = recaptcha_check_answer ($board_config->recaptcha_privkey,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]);
      if (!$recap->is_valid) $error[] = lang("error_wrongcaptcha") . " &rarr; <small>reCAPTCHA: " . $recap->error . "</small>";
    } else {
      if (!$captchacode) $error[] = lang("error_nocaptcha");
      else {
        if ($board_config->use_cap == 1) { //GD CAPTCHA ... 1
          include("$rel_path/cap1/securimage.php");
          $cap_img = new Securimage();
          if(!$cap_img->check($captchacode)) $error[] = lang("error_wrongcaptcha");
        } else { //GD-less CAPTCHA ... 2
          include("$rel_path/cap2/codes.php");
          $captchacode = trim(strtolower($captchacode));
          if($cap2_keys[$codec2] != $captchacode) $error[] = lang("error_wrongcaptcha");
        }
      }
    }
  }
  
  if (!$error) {
    $add2sql = "email = " . dbquote($femail) . ", website = " . dbquote($website) . ", interests = " . dbquote($interests) . ", occupation = " . dbquote($occupation) . ", location = " . dbquote($location) . ", birthday = " . ($birthday ? dbquote($birthday) : "NULL") . ", forummail = '$fforummail', usermail = '$fusermail', gravatar = '$gravatar', sbb_avatar = " . dbquote($sbb_avatar) . ", signature = " . dbquote($signature) . ($fpwd ? ", pwd = password(" . dbquote($fpwd) . ")" : "");
    if ($forum_user) { //update
      //new avatar pic or deleting avatar?
      if ($afile_name) {
        $target = $www_data_dir;
        $target .= "/" . $f_auth_uid;
        if (!is_dir($target)) mkdir($target);
        $target .= "/avatar";
        if (!is_dir($target)) mkdir($target);

        //delete current avatar - if existing
        if ($forum_user->avatar && is_file($target . "/" . $forum_user->avatar)) unlink($target . "/" . $forum_user->avatar);

        $afname = strrev(substr(strrev($afname),0,20));
        move_uploaded_file($atmp_name, $target . "/" . $afname);
        
        if ($w > $board_config->avatar_width || $h > $board_config->avatar_height) {
          if (create_av_thumb("$target/$afname")) $afname = "tn_" . $afname; 
        }
        
        $add2sql .= ", avatar = '$afname'";
      } elseif ($delavatar) {
        //delete current avatar - if existing
        if ($forum_user->avatar && is_file("$www_data_dir/$f_auth_uid/avatar/" . $forum_user->avatar)) unlink("$www_data_dir/$f_auth_uid/avatar/" . $forum_user->avatar);
        $add2sql .= ", avatar = NULL";
      }
      $sql = "update `" . $ftable_prefix . "users` set $add2sql, edited = now() where id = '$f_auth_uid';";
      dbquery($sql);
      unset($todo);
      $success = lang("success_userupd");
    } else { //insert
      $sql = "insert into `" . $ftable_prefix . "users` set user = " . dbquote($fuser) . ", $add2sql, created = now(), status = '" . ($board_config->activation > 0 ? 0 : 1) . "';";
      dbquery($sql);
      $new_uid = mysql_insert_id();
      //activation and mailing part
      //Template Variables
      $USERNAME = $fuser;
      $PASSWORD = $fpwd;
      $BOARD_URL = "http://" . $base_url . $main_script;
      $BOARD_ADMIN = $conf_board_admin;
      $UACTIVATION_URL = "http://" . $base_url . $main_script . "?ua=" . md5($new_uid . $fuser);
      $AACTIVATION_URL = "http://" . $base_url . $main_script . "?aa=" . md5($fuser . ($new_uid * 7));
      $USERMAIL = $femail;
      
      /************
       * initiate template and assign variables
       ************/                 
      $mailVARS = array('CONF_FORUMTITLE' => $GLOBAL_TEMPLATE_VARS["FORUMTITLE"], 'USERNAME' => $USERNAME, 'PASSWORD' => $PASSWORD, 'BOARD_ADMIN' => $BOARD_ADMIN, 'BOARD_URL' => $BOARD_URL, 'UACTIVATION_URL' => $UACTIVATION_URL, 'AACTIVATION_URL' => $AACTIVATION_URL, 'USERMAIL' => $USERMAIL);
      if ($board_config->activation == 0) {
        $QuickSkin = new QuickSkin("mail_welcome.txt");
        $QuickSkin->set("template_dir","$www_dir/lang/$f_lang/");
        $QuickSkin->assign($mailVARS);
        $mail_mess = $QuickSkin->result();
        unset($QuickSkin);
        mail ($femail, sprintf(lang("subject_welcome"),$GLOBAL_TEMPLATE_VARS["FORUMTITLE"]), $mail_mess, "From: $conf_board_mailfrom");
      } elseif ($board_config->activation == 1) {
        $QuickSkin = new QuickSkin("mail_welcome_useract.txt");
        $QuickSkin->set("template_dir","$www_dir/lang/$f_lang/");
        $QuickSkin->assign($mailVARS);
        $mail_mess = $QuickSkin->result();
        unset($QuickSkin);
        mail ($femail, sprintf(lang("subject_welcome"),$GLOBAL_TEMPLATE_VARS["FORUMTITLE"]), $mail_mess, "From: $conf_board_mailfrom");
        $info = sprintf(lang("info_uact"),$femail);
      } elseif ($board_config->activation == 2) {
        //mail to user
        $QuickSkin = new QuickSkin("mail_welcome_admact.txt");
        $QuickSkin->set("template_dir","$www_dir/lang/$f_lang/");
        $QuickSkin->assign($mailVARS);
        $mail_mess = $QuickSkin->result();
        unset($QuickSkin);
        mail ($femail, sprintf(lang("subject_welcome"),$GLOBAL_TEMPLATE_VARS["FORUMTITLE"]), $mail_mess, "From: $conf_board_mailfrom");
        //mail to admin
        $QuickSkin = new QuickSkin("mail_admin_act.txt");
        $QuickSkin->set("template_dir","$www_dir/lang/$f_lang/");
        $QuickSkin->assign($mailVARS);
        $mail_mess = $QuickSkin->result();
        unset($QuickSkin);
        mail ($board_config->email_board_admin, lang("subject_activate"), $mail_mess, "From: $conf_board_mailfrom");
        $info = lang("info_aact");
      }
      
      $todo = "login";
      $success = lang("success_usercreated");
    }
  } else {
    $todo = "edit_account";
    $hide_login_form = true;
  }
}
/****
 * ACTION: create/edit user [-]
 ****/
 
 
/****
 * ACTION: create/edit rank [+]
 ****/
if ($action == "edit_userrank" && $is_admin) {
  $todo = "adminuserranks";
  $rank_id = intval($_REQUEST["rank_id"]);
  $descr = trim(strip_tags($_REQUEST["descr"]));
  $img = trim($_REQUEST["img"]);
  $img = preg_replace('/.*\/images\/ranks\//','',$img);
  if (!$descr) $error[] = lang("error_nodescr");
  if (!$img) $error[] = lang("error_noimg_selected");
  if (!$error) {
    $add2sql = "descr = " . dbquote($descr) . ", img = " . dbquote($img);
    if ($rank_id) $sql = "update `" . $ftable_prefix . "ranks` set $add2sql where id = '$rank_id'";
    else $sql = "insert into `" . $ftable_prefix . "ranks` set $add2sql";
    dbquery($sql);
    $success = lang($rank_id ? "success_upd_rank" : "success_new_rank");
  } else {
    $section = "edit";
  }
}
/****
 * ACTION: create/edit rank [-]
 ****/
if ($action == "delrank" && $is_admin) {
  $todo = "adminuserranks";
  $rank_id = intval($_REQUEST["rank_id"]);
  if (!$rank_id) $error[] = lang("error_notenough");
  else {
    $sql = "delete from `" . $ftable_prefix . "ranks` where id = '$rank_id'";
    dbquery($sql);
    //reset users
    $sql = "update `" . $ftable_prefix . "users` set rank_id = 0 where rank_id = '$rank_id'";
    dbquery($sql);
    $success = lang("success_del_rank");
  }
}
/****
 * ACTION: delete rank [+]
 ****/
 
/****
 * ACTION: delete rank [-]
 ****/

 
 /****
 * ACTION: create/edit user for ADMINS and MODS only [+]
 ****/
if ($action == "edit_account_adm" && $is_mod) {
  $fuser = trim(strip_tags($_REQUEST["fuser"]));
  $fpwd = trim($_REQUEST["fpwd"]);
  $fpwdconf = trim($_REQUEST["fpwdconf"]);
  $femail = trim(strtolower($_REQUEST["femail"]));
  $fusermail = intval($_REQUEST["fusermail"]);
  $fforummail = intval($_REQUEST["fforummail"]);
  $uid = intval($_REQUEST["uid"]);
  $userlevel = $_REQUEST["userlevel"];
  $fstatus = intval($_REQUEST["fstatus"]);
  $deluser = intval($_REQUEST["deluser"]);
  $delposts = intval($_REQUEST["delposts"]);
  $signature = substr(trim($_REQUEST["signature"]),0,250);
  $delavatar = intval($_REQUEST["delavatar"]);
  $curravatar = $_REQUEST["curravatar"];
  $rank_id = intval($_REQUEST["rank_id"]);
  
  $website = trim($_REQUEST["website"]);
  $interests = trim($_REQUEST["interests"]);
  $occupation = trim($_REQUEST["occupation"]);
  $location = trim($_REQUEST["location"]);
  $bd = $_REQUEST["bd"];
  $bm = $_REQUEST["bm"];
  $by = intval($_REQUEST["by"]);
  
  if ($website && !preg_match('/^http/i',$website)) $website = "http://$website";
  if ($bm && $bd) {
    if ($by && $by<100) $by += 1900;
    if (!$by) $by = 1900;
    $birthday = "$by-$bm-$bd";
  }
  
  
  if (!$fuser) $error[] = lang("error_nonickname");
  elseif (!preg_match('/^[a-zA-Z0-9\.\-\* ]*$/',$fuser)) $error[] = lang("error_nickchar");
  if (!$uid && !$fpwd) $error[] = lang("error_nopass");
  if (!$error && $fpwd) {
     if ($fpwd != $fpwdconf) $error[] = lang("error_passnomatch");
  }
  if (!$femail) $error[] = lang("error_nomail");
  elseif (!is_email($femail)) $error[] = lang("error_invalidmail");

  if (!$error && ($fuser != $forum_user->user) && $board_config->reserved_users) {
    //prevent from registering this users
    $reserved_users = explode(",",$board_config->reserved_users);
    for ($i=0;$i<count($reserved_users);$i++) {
      if (strtolower($fuser) == trim($reserved_users[$i])) {
        $error[] = lang("error_reserved");
        break;
      }
    }
  }

  if (!$error) {
    //name allready registered??
    $sql = "select * from `" . $ftable_prefix . "users` where user like " . dbquote($fuser) . " and id != '$uid';";
    $res = dbquery($sql);
    if (mysql_num_rows($res)) $error[] = sprintf(lang("error_userregistered"), $fuser);
  }
  if (!$error) {
    if ($deluser) {
      $sql = "delete from `" . $ftable_prefix . "users` where id = " . dbquote($uid) . " and deleteable = '1';";
      dbquery($sql);
      //and now the user's datadir
      if (mysql_affected_rows() && $uid) xrmdir("$www_data_dir/$uid"); 
      if (mysql_affected_rows() && $delposts) {
        //get the views and fids for the resyncing process
        $sql = "select id, view, fid from `" . $ftable_prefix . "question` where uid = '$uid';";
        $res = dbquery($sql);
        while ($row = mysql_fetch_object($res)) {
          $q_views[$row->id] = $row->view;
          $q_fids[$row->id] = $row->fid;
        
          //poll options
          $sql0 = "select id from `" . $ftable_prefix . "poll_options` where tid = '" . $row->id . "';";
          $res0 = dbquery($sql0);
          while ($row0 = mysql_fetch_object($res0)) {
            dbquery("delete from `" . $ftable_prefix . "polls` where poll_option_id = '" . $row0->id . "';");  
          }
          dbquery("delete from `" . $ftable_prefix . "poll_options` where tid = '$tid';");
          
          //attachments
          $sql0 = "select * from `" . $ftable_prefix . "attachments` where tid = '" . $row->id . "' and uid = '$uid';";
          $res0 = dbquery($sql0);
          while ($row0 = mysql_fetch_object($res0)) {
            xrmdir("$www_data_dir/attachments/" . $row0->id);    
          }
          dbquery("delete from `" . $ftable_prefix . "attachments` where tid = '" . $row->id . "' and uid = '$uid';");        
        }
        $sql = "delete from `" . $ftable_prefix . "answer` where a_uid = '$uid';";
        dbquery($sql);
        $sql = "delete from `" . $ftable_prefix . "question` where uid = '$uid';";
        dbquery($sql);
        
        //delete private messages
        $sql = "select * from `" . $ftable_prefix . "pm` where to_uid = '$uid' or from_uid = '$uid'";
        $res = dbquery($sql);
        while ($row = mysql_fetch_object($res)) {
          if ((!$row->seen && $row->from_uid == $uid) ||       //really delete if unsent(unseen) and user is sender
              ($row->to_uid == $uid && $row->deleted_from) ||  //really delete if recipient is user and sender set the delete flag
              ($row->from_uid == $uid && $row->deleted_to) ||  //really delete if sender is user and recipient set the delete flag
              ($row->from_uid == $row->from_uid)) {            //really delete if sender and recipient is the same person            
            dbquery("delete from `" . $ftable_prefix . "pm` where id ='" . $row->id . "' and (to_uid = '$uid' or from_uid = '$uid')");
          } else {
            if ($row->to_uid == $uid) {
              //set recpient's the delete flag
              dbquery("update `" . $ftable_prefix . "pm` set deleted_to = '1' where id ='" . $row->id . "' and to_uid = '$uid'");
            } elseif ($row->from_uid == $uid) {
              //set sender's the delete flag
              dbquery("update `" . $ftable_prefix . "pm` set deleted_from = '1' where id ='" . $row->id . "' and from_uid = '$uid'");
            }
          }
        }
        
        $action = "resync_topics";
      }
      $success = lang("success_userdel");
    } else {
      if ($userlevel == "is_admin") {
        $fis_admin = 1;
        $fis_mod = 0;
      } elseif ($userlevel == "is_mod") {
        $fis_admin = 0;
        $fis_mod = 1;
      } else $fis_admin = $fis_mod = 0;
      if ($delavatar) {
        //delete current avatar - if existing
        if ($curravatar && is_file("$www_data_dir/$uid/avatar/$curravatar")) unlink("$www_data_dir/$uid/avatar/$curravatar");
      }
      $add2sql = "user = " . dbquote($fuser) . ", email = " . dbquote($femail) . ", website = " . dbquote($website) . ", interests = " . dbquote($interests) . ", occupation = " . dbquote($occupation) . ", location = " . dbquote($location) . ", birthday = " . ($birthday ? dbquote($birthday) : "NULL") . ", forummail = '$fforummail', usermail = '$fusermail', rank_id = '$rank_id', signature = " . dbquote($signature) . ($fpwd ? ", pwd = password(" . dbquote($fpwd) . ")" : "") . " " . ($delavatar ? ", avatar = NULL" : "");
      
      if ($uid) {
        $sql = "update `" . $ftable_prefix . "users` set $add2sql, edited = now() where id = '$uid'";
      } else {
        $sql = "insert into `" . $ftable_prefix . "users` set $add2sql, created = now()";
      }
      dbquery($sql);
      //now the status and the userlevelsetting for the deleteables
      //boardadmins can set stats of admins, mods and lower ones
      if ($is_board_admin) $sql = "update `" . $ftable_prefix . "users` set is_mod = '$fis_mod', is_admin = '$fis_admin', status = '$fstatus', edited = now() where id = '$uid' and deleteable = 1;";
      //admins can set stats of mods and lower ones
      elseif ($is_admin) $sql = "update `" . $ftable_prefix . "users` set is_mod = '$fis_mod', status = '$fstatus', edited = now() where id = '$uid' and is_admin = '0' and deleteable = 1;";
      //mods can set stats of lower normal users
      elseif ($is_mod) $sql = "update `" . $ftable_prefix . "users` set status = '$fstatus', edited = now() where id = '$uid' and is_mod = '0' and is_admin = '0' and deleteable = 1;";
      dbquery($sql);
      $success = lang("success_userupd");
    }
  } else {
    $section = "edit";
  }
  if ($_REQUEST["cf"] == "adminusers") $todo = "adminusers";
  else $todo = "showusers";
}
/****
 * ACTION: create/edit user for ADMINS and MODS only [-]
 ****/
 
/****
 * ACTION: resync topics [+]
 ****/
if ($action == "resync_topics") {
  //get ORPHANS and make them to parents
  $sql = "select * from `" . $ftable_prefix . "answer` where question_id not in (select id from `" . $ftable_prefix . "question`) order by question_id, a_id;";
  $res = dbquery($sql);
  //first found answer will now be the question
  while ($row = mysql_fetch_object($res)) {
    if ($tmp_q_id != $row->question_id) {
      dbquery("insert into `" . $ftable_prefix . "question` set id = '" . $row->question_id . "', topic = " . dbquote($row->a_topic ? $row->a_topic : "Starting topic deleted") . ", detail = " . dbquote($row->a_answer) . ", uid = '" . $row->a_uid . "', name = " . dbquote($row->a_name) . ", email = " . dbquote($row->a_email) . ", datetime = '" . $row->a_datetime . "', view = '" . $q_views[$row->question_id] . "', fid = '" . $q_fids[$row->question_id] . "';");
      $q_ids[] = $row->question_id;
      //remove converted answer
      dbquery("delete from `" . $ftable_prefix . "answer` where a_id = '" . $row->a_id . "' and question_id = '" . $row->question_id . "';"); 
    }
    $tmp_q_id = $row->question_id;
  }
  //through the answers again
  if ($q_ids) {
    for ($l=0;$l<count($q_ids);$l++) {
      $sql = "select * from `" . $ftable_prefix . "answer` where question_id = '" . $q_ids[$l] . "' order by a_id;";
      $res = dbquery($sql);
      $i = 0;
      unset ($lastanswer);
      while ($row = mysql_fetch_object($res)) {
        $i++;
        $sql = "update `" . $ftable_prefix . "answer` set a_id = '$i' where question_id = '" . $q_ids[$l] . "' and a_id = '" . $row->a_id . "';";
        dbquery($sql);
        //attachment
        $sql = "update `" . $ftable_prefix . "attachments` set pid = '$i' where tid = '" . $q_ids[$l] . "' and pid = '" . $row->a_id . "';";
        dbquery($sql);
        //last answerinfos
        $lastanswer = $row;
      }
      if ($lastanswer) {
        //update maintopic infos
        $sql = "update `" . $ftable_prefix . "question` set reply = '$i', a_datetime = " . ($lastanswer->a_datetime ? "'" . $lastanswer->a_datetime . "'" : "datetime") . ", a_uid = '" . $lastanswer->a_uid . "' where id = '" . $q_ids[$l] . "';";
        dbquery($sql);
      }
    }
  } 
  //reset all others
  $sql0 = "select * from `" . $ftable_prefix . "question` order by id;";
  $res0 = dbquery($sql0);
  while ($row0 = mysql_fetch_object($res0)) {
    $sql = "select * from `" . $ftable_prefix . "answer` where question_id = '" . $row0->id . "' order by a_id;";
    $res = dbquery($sql);
    $i = 0;
    unset ($lastanswer);
    while ($row = mysql_fetch_object($res)) {
      $i++;
      $sql = "update `" . $ftable_prefix . "answer` set a_id = '$i' where question_id = '" . $row0->id . "' and a_id = '" . $row->a_id . "';";
      dbquery($sql);
      //attachment
      $sql = "update `" . $ftable_prefix . "attachments` set pid = '$i' where tid = '" . $row0->id . "' and pid = '" . $row->a_id . "';";
      dbquery($sql);
      //last answerinfos
      $lastanswer = $row;
    }
    if ($lastanswer) {
      //update maintopic infos
      $sql = "update `" . $ftable_prefix . "question` set reply = '$i', a_datetime = " . ($lastanswer->a_datetime ? "'" . $lastanswer->a_datetime . "'" : "datetime") . ", a_uid = '" . $lastanswer->a_uid . "' where id = '" . $row0->id . "';";
      dbquery($sql);
    }
  }
  //reset all attachments
  dbquery("update `" . $ftable_prefix . "question` set attachment = '0';");
  $sql = "select tid from `" . $ftable_prefix . "attachments` group by tid;";
  $res = dbquery($sql);
  while ($row = mysql_fetch_object($res)) {
    dbquery("update `" . $ftable_prefix . "question` set attachment = '1' where id = '" . $row->tid . "';");
  }
}
/****
 * ACTION: resync topics [-]
 ****/
 
/****
 * ACTION: edit topic/post [+]
 * currently only ADMINs and MODs 
 ****/
 
if ($action == "edit_post") {
  $topic = trim(strip_tags($_REQUEST["topic"]));
  $message = trim($_REQUEST["message"]);
  $tid = intval($_REQUEST["tid"]);
  $pid = intval($_REQUEST["pid"]);
  $sticky = intval($_REQUEST["sticky"]);
  
  $poll_title = trim(strip_tags($_REQUEST["poll_title"]));
  $poll_options = trim(strip_tags($_REQUEST["poll_options"]));
  $poll_multiple = intval($_REQUEST["poll_multiple"]);
  $poll_duration = intval($_REQUEST["poll_duration"]);
  
  $attachment = $_FILES["attachment"];
  $att_descr = trim($_REQUEST["att_descr"]);
  
  if (!$tid && !$pid) $error[] = lang("error_notenough");
  if (!$pid && !$topic) $error[] = lang("error_no_title");
  if (!$message) $error[] = lang("error_no_message");
  
  if (!has_edit_permission($tid,$pid)) $error[] = lang("error_noperm");
  
  if ($attachment && $board_config->max_attachment_size) {
    if ($attachment["size"] > ($board_config->max_attachment_size * 1024 * 1024)) $error[] = sprintf(lang("error_attachment_filesize"),$board_config->max_attachment_size);
  }
  
  if ($board_config->en_polls && $poll_title && $poll_options) {
    $poll = true;
    //check options
    $po = explode("\n",$poll_options);
    if ($board_config->max_poll_options && count($po) > $board_config->max_poll_options) $error[] = sprintf(lang("error_too_much_options"),$board_config->max_poll_options);
  } else {
    unset ($poll_title, $poll_options);
    $poll_multiple = $poll_duration = 0;
  }  
  
  if (!$error) {
    
      //code in the message
      //close nonclosed bbcodes
      $bbcode = array("b","i","u","quote","code","list","img","url");
      for ($i=0;$i<count($bbcode);$i++) {
        if ($bbcode[$i] == "url") $open_cnt = substr_count($message,"[" . $bbcode[$i]);
        else $open_cnt = substr_count($message,"[" . $bbcode[$i] . "]");
        $close_cnt = substr_count($message,"[/" . $bbcode[$i] . "]");
        if ($open_cnt > $close_cnt) {
          $message .= str_repeat("[/" . $bbcode[$i] . "]",($open_cnt-$close_cnt));
        }
      }
      $message = preg_replace("/\[code\](.*?)\[\/code\]/e", ("'[code]'.htmlentities('$1').'[/code]'"), $message);
  
    if (!$pid && $tid) { //edit topic
      $sql = "update `" . $ftable_prefix . "question` set topic = " . dbquote($topic) . ", detail = " . dbquote(strip_tags($message)) . ($is_mod ? ", sticky = '$sticky'" : "") . ", poll_title = " . dbquote($poll_title) . ",
      poll_multiple = '$poll_multiple', poll_duration = '$poll_duration' where id = '$tid';";
      dbquery($sql);
      
      //checkout poll_options
      //if ($poll) {
        //orig
        $sql = "select * from `" . $ftable_prefix . "poll_options` where tid = '$tid' order by pos;";
        $res = dbquery($sql);
        if (mysql_num_rows($res) == count($po)) $update = true;
        else {
          //delete old votes
          while ($row = mysql_fetch_object($res)) {
            dbquery("delete from `" . $ftable_prefix . "polls` where poll_option_id = '" . $row->id . "';");
          }
          //delete old options
          dbquery("delete from `" . $ftable_prefix . "poll_options` where tid = '$tid';");
        }
        $pos = 0;
        for ($i=0;$i<count($po);$i++) {
          $this_option = trim($po[$i]);
          if ($this_option) {
            $pos++;
            if ($update) $sql = "update `" . $ftable_prefix . "poll_options` set poll_option = " . dbquote($this_option) . "where pos = '$pos' and tid = '$tid';";
            else $sql = "insert into `" . $ftable_prefix . "poll_options` set tid = '$tid', poll_option = " . dbquote($this_option) . ", pos = '$pos', created = now();";
            dbquery($sql);
          }
        }
      //}
      
      //attachment
      if ($attachment["name"]) {
        $file_name = tidyup($attachment["name"]);
        $file_name = strrev(substr(strrev($file_name),0,100));
        //db creation
        $sql = "insert into `" . $ftable_prefix . "attachments` set tid = '$tid', uid = '$f_auth_uid', descr = " . dbquote($att_descr) . ", file_name = " . dbquote($file_name) . ", created = now();";
        dbquery($sql);
        $new_attid = mysql_insert_id();
        $target = $www_data_dir . "/attachments";
        if (!is_dir($target)) mkdir($target);
        $target .= "/" . $new_attid;
        if (!is_dir($target)) mkdir($target);
        move_uploaded_file($attachment["tmp_name"], $target . "/" . $file_name);
        
        $sql = "update `" . $ftable_prefix . "question` set attachment = '1' where id = '$tid';";
        dbquery($sql);        
      }
      $success = lang("success_upd_post");
    } elseif ($pid && $tid) { //edit answer
      $sql = "update `" . $ftable_prefix . "answer` set a_topic = " . dbquote($topic) . ", a_answer = " . dbquote(strip_tags($message)) . " where a_id = '$pid' and question_id = '$tid';";
      dbquery($sql);
      
      //attachment
      if ($attachment["name"]) {
        $file_name = tidyup($attachment["name"]);
        $file_name = strrev(substr(strrev($file_name),0,100));
        //db creation
        $sql = "insert into `" . $ftable_prefix . "attachments` set pid = '$pid', tid = '$tid', uid = '$f_auth_uid', descr = " . dbquote($att_descr) . ", file_name = " . dbquote($file_name) . ", created = now();";
        dbquery($sql);
        $new_attid = mysql_insert_id();
        $target = $www_data_dir . "/attachments";
        if (!is_dir($target)) mkdir($target);
        $target .= "/" . $new_attid;
        if (!is_dir($target)) mkdir($target);
        move_uploaded_file($attachment["tmp_name"], $target . "/" . $file_name);
        
        $sql = "update `" . $ftable_prefix . "question` set attachment = '1' where id = '$tid';";
        dbquery($sql);        
      }
      
      
      $success = lang("success_upd_post");
      $todo = "show_topics";
    }
  } else {
    $todo = "edit_post";
  } 
}
/****
 * ACTION: create topic/post [-]
 ****/



/****
 * ACTION: create topic/post [+]
 ****/
 
if ($action == "add_topic") {
  $topic = trim(strip_tags($_REQUEST["topic"]));
  $detail = $message = trim($_POST["message"]);
  $tid = intval($_POST["tid"]);
  $fid = intval($_POST["fid"]);
  $fts = intval($_POST["fts"]); 
  $sticky = intval($_REQUEST["sticky"]);
  
  $poll_title = trim(strip_tags($_REQUEST["poll_title"]));
  $poll_options = trim(strip_tags($_REQUEST["poll_options"]));
  $poll_multiple = intval($_REQUEST["poll_multiple"]);
  $poll_duration = intval($_REQUEST["poll_duration"]);
    
  $attachment = $_FILES["attachment"];
  $att_descr = trim($_REQUEST["att_descr"]);
  
  if (!$topic && !$tid) $error[] = lang("error_no_title");
  if (!$detail) $error[] = lang("error_no_message");
  if (!$fts) $error[] = lang("error_notenough");
  
  if (!$f_auth_uid) {
    $f_auth_uid = 0;    
    $guest_name = trim(strip_tags($_REQUEST["guest_name"]));
    $guest_name = preg_replace('([^a-zA-Z0-9\.\-_ ])', '', $guest_name);
    $forum_user->user = ($guest_name ? $guest_name : "Anonymous");
    $forum_user->email = "no.one@nowhere.com";
    //guest is posting>/replying :)
    
  }
  
  if ($attachment && $board_config->max_attachment_size) {
    if ($attachment["size"] > ($board_config->max_attachment_size * 1024 * 1024)) $error[] = sprintf(lang("error_attachment_filesize"),$board_config->max_attachment_size);
  }
  
  if ($board_config->en_polls && $poll_title && $poll_options) {
    $poll = true;
    //check options
    $po = explode("\n",$poll_options);
    if ($board_config->max_poll_options && count($po) > $board_config->max_poll_options) $error[] = sprintf(lang("error_too_much_options"),$board_config->max_poll_options);
  } else {
    unset ($poll_title, $poll_options);
    $poll_multiple = $poll_duration = 0;
  }

  //doublepost prevention [+]
  if (!$error) {
    if (!$tid) $res = dbquery("select id from `" . $ftable_prefix . "question` where uid = '$f_auth_uid' and form_ts = '$fts';");
    else $res = dbquery("select * from `" . $ftable_prefix . "answer` where a_uid = '$f_auth_uid' and a_form_ts = '$fts';");
    if (mysql_num_rows($res)) $error[] = lang("error_doublepost");
    $doubleposterror = true;
  }
  //doublepost prevention [-]
  
  //additional permission check
  if (!$error) {
    if (!$tid && !$forum[$fid]->allowed2post) $error[] = lang("error_noperm");
    if ($tid && !$forum[$fid]->allowed2reply) $error[] = lang("error_noperm");
  }
  
  if (!$error && !$tid) { //new Topic
    //code in the message
    //close nonclosed bbcodes
    $bbcode = array("b","i","u","quote","code","list","img","url");
    for ($i=0;$i<count($bbcode);$i++) {
      if ($bbcode[$i] == "url") $open_cnt = substr_count($detail,"[" . $bbcode[$i]);
      else  $open_cnt = substr_count($detail,"[" . $bbcode[$i] . "]");
      $close_cnt = substr_count($detail,"[/" . $bbcode[$i] . "]");
      if ($open_cnt > $close_cnt) {
        $detail .= str_repeat("[/" . $bbcode[$i] . "]",($open_cnt-$close_cnt));
      }
    }
    
    $detail = preg_replace("/\[code\](.*?)\[\/code\]/e", ("'[code]'.htmlentities('$1').'[/code]'"), $detail);
  
    //create topic mailing could be placed here
  
    $sql = "insert into `" . $ftable_prefix . "question` set topic = " . dbquote($topic) . ", fid = '$fid', detail = " . dbquote(strip_tags($detail)) . ", name = " . dbquote($forum_user->user) . ", 
      email = " . dbquote($forum_user->email) . ", `datetime` = now(), uid = '$f_auth_uid', a_datetime = now(), form_ts = '$fts', sticky = '" . ($is_mod ? $sticky : 0) . "', poll_title = " . dbquote($poll_title) . ",
      poll_multiple = '$poll_multiple', poll_duration = '$poll_duration';";
    $res = dbquery($sql);
    $new_tid = mysql_insert_id();
    
    //polls
    if ($poll) {
      $pos = 0;
      for ($i=0;$i<count($po);$i++) {
        $this_option = trim($po[$i]);
        if ($this_option) {
          $pos++;
          $sql = "insert into `" . $ftable_prefix . "poll_options` set tid = '$new_tid', poll_option = " . dbquote($this_option) . ", pos = '$pos', created = now();";
          dbquery($sql);
        }
      }
    }
    
    //attachment
    if ($attachment["name"]) {
      $file_name = tidyup($attachment["name"]);
      $file_name = strrev(substr(strrev($file_name),0,100));
      //db creation
      $sql = "insert into `" . $ftable_prefix . "attachments` set tid = '$new_tid', uid = '$f_auth_uid', descr = " . dbquote($att_descr) . ", file_name = " . dbquote($file_name) . ", created = now();";
      dbquery($sql);
      $new_attid = mysql_insert_id();
      $target = $www_data_dir . "/attachments";
      if (!is_dir($target)) mkdir($target);
      $target .= "/" . $new_attid;
      if (!is_dir($target)) mkdir($target);
      move_uploaded_file($attachment["tmp_name"], $target . "/" . $file_name);
      
      $sql = "update `" . $ftable_prefix . "question` set attachment = '1' where id = '$new_tid';";
      dbquery($sql);
      
    }
    
    $success = lang("success_new_topic");
    
    if ($board_config->en_board_notification) {
      //inform watching users
      //if user is not the poster
      //and forum_messages are allowed
      
      //collect uids
      $sql = "select uid from `" . $ftable_prefix . "watchlist` where fid = '$fid' and uid != '$f_auth_uid';";
      $res = dbquery($sql);
      while ($row = mysql_fetch_object($res)) {
        $mailuids[] = $row->uid;
      }
      if ($mailuids) {
        $mailuids = array_unique($mailuids);
        for ($i=0;$i<count($mailuids);$i++) {
          $this_user = forum_user($mailuids[$i]);
          if ($this_user->forummail) {
            //creating, parsing and sending the email
            //Template Variables
            $RCPT_NAME = $this_user->user;
            $FORUM_TITLE = $forum[$fid]->title;
            $POST_URL = "http://" . $base_url . $main_script . "?todo=viewtopic&tid=$new_tid";
            $BOARD_ADMIN = $conf_board_admin;
            
            /************
             * initiate template and assign variables
             ************/                 
            $mailVARS = array('CONF_FORUMTITLE' => $GLOBAL_TEMPLATE_VARS["FORUMTITLE"], 'RCPT_NAME' => $RCPT_NAME, 'FORUM_TITLE' => $FORUM_TITLE, 'BOARD_ADMIN' => $BOARD_ADMIN, 'POST_URL' => $POST_URL);
            $QuickSkin = new QuickSkin("mail_newtopic.txt");
            $QuickSkin->set("template_dir","$www_dir/lang/$f_lang/");
            $QuickSkin->assign($mailVARS);
            $mail_mess = $QuickSkin->result();
            unset($QuickSkin);
            mail ($this_user->email, sprintf(lang("subject_new_topic"),$FORUM_TITLE), $mail_mess, "From: $conf_board_mailfrom");
          }
        }
      }
    } 
    $todo = "show_topics";
  }
  
  if (!$error && $tid) { //check if topic is locked and create an topic-title if isn't set by form
    
    $res = dbquery("select locked, topic from `" . $ftable_prefix . "question` where id = '$tid';");
    $row = mysql_fetch_object($res);
    if (!$topic) $topic = (!preg_match('/^re: /i',$row->topic) ?"Re: " : "") . $row->topic;
    if ($row->locked) $error[] = lang("error_topiclocked");
  }
  
  
  if (!$error && $tid) { //Answer to existing topic
    $a_answer = $detail;
    
    $sql = "SELECT MAX(a_id) AS maxid FROM `" . $ftable_prefix . "answer` WHERE question_id = '$tid';";
    $res = dbquery($sql);
    if (!mysql_num_rows($res)) $maxid = 1;
    else {
      $row = mysql_fetch_object($res);
      $maxid = ($row->maxid + 1);
    }
    $sql = "insert into `" . $ftable_prefix . "answer` set question_id = '$tid', a_id = '$maxid', a_name = " . dbquote($forum_user->user) . ", a_email = " . dbquote($forum_user->email) . ", a_answer = " . dbquote(strip_tags($a_answer)) . ", a_topic = " . dbquote($topic) . ", a_datetime = now(), a_uid = '$f_auth_uid', a_form_ts = '$fts';";
    dbquery($sql);
    
    //attachment
    if ($attachment["name"]) {
      $file_name = tidyup($attachment["name"]);
      $file_name = strrev(substr(strrev($file_name),0,100));
      //db creation
      $sql = "insert into `" . $ftable_prefix . "attachments` set pid = '$maxid', tid = '$tid', uid = '$f_auth_uid', descr = " . dbquote($att_descr) . ", file_name = " . dbquote($file_name) . ", created = now();";
      dbquery($sql);
      $new_attid = mysql_insert_id();
      $target = $www_data_dir . "/attachments";
      if (!is_dir($target)) mkdir($target);
      $target .= "/" . $new_attid;
      if (!is_dir($target)) mkdir($target);
      move_uploaded_file($attachment["tmp_name"], $target . "/" . $file_name);
      
      $sql = "update `" . $ftable_prefix . "question` set attachment = '1' where id = '$tid';";
      dbquery($sql);
      
    }
    $success = lang("success_new_reply");
    $todo = "viewtopic";
    
    $sql = "UPDATE `" . $ftable_prefix . "question` SET reply = '$maxid', a_uid = '$f_auth_uid', a_datetime = now(), a_name = " . dbquote($forum_user->user) . " WHERE id = '$tid';";
    dbquery($sql);
    
    if ($board_config->en_board_notification) {
      //inform user
      //if user is not the poster
      //and forum_messages are allowed
      
      //collect uids
      $sql = "select uid, topic from `" . $ftable_prefix . "question` where id = '$tid';";
      $res = dbquery($sql);
      $row = mysql_fetch_object($res);
      if ($row->uid != $f_auth_uid) $mailuids[] = $row->uid;
      $topictitle = $row->topic;
      $sql = "select a_uid from `" . $ftable_prefix . "answer` where question_id = '$tid' and a_uid != '$f_auth_uid';";
      $res = dbquery($sql);
      while ($row = mysql_fetch_object($res)) {
        $mailuids[] = $row->a_uid;
      }
      //add watchlist ids
      $sql = "select uid from `" . $ftable_prefix . "watchlist` where (tid = '$tid' or fid = '$fid') and uid != '$f_auth_uid';";
      $res = dbquery($sql);
      while ($row = mysql_fetch_object($res)) {
        $mailuids[] = $row->uid;
      }
      if ($mailuids) {
        $mailuids = array_unique($mailuids);
        for ($i=0;$i<count($mailuids);$i++) {
          $this_user = forum_user($mailuids[$i]);
          if ($this_user->forummail) {
            //creating, parsing and sending the email
            //Template Variables
            $RCPT_NAME = $this_user->user;
            $TOPIC_TITLE = $topictitle;
            $POST_URL = "http://" . $base_url . $main_script . "?todo=viewtopic&tid=$tid#t$maxid";
            $BOARD_ADMIN = $conf_board_admin;
            

            /************
             * initiate template and assign variables
             ************/                 
            $mailVARS = array('CONF_FORUMTITLE' => $GLOBAL_TEMPLATE_VARS["FORUMTITLE"], 'RCPT_NAME' => $RCPT_NAME, 'TOPIC_TITLE' => $TOPIC_TITLE, 'BOARD_ADMIN' => $BOARD_ADMIN, 'POST_URL' => $POST_URL);
            $QuickSkin = new QuickSkin("mail_newreply.txt");
            $QuickSkin->set("template_dir","$www_dir/lang/$f_lang/");
            $QuickSkin->assign($mailVARS);
            $mail_mess = $QuickSkin->result();
            unset($QuickSkin);
            mail ($this_user->email, sprintf(lang("subject_new_post"),$topictitle), $mail_mess, "From: $conf_board_mailfrom");
          }
        }
      }
    } 
  }
  if ($error) {
    if (!$doubleposterror) $todo = "add_topic";
  }
}
/****
 * ACTION: create topic/post [-]
 ****/
 
/****
 * ACTION: Send private message [+]
 ****/
if ($action == "sendpm") {
  $uid = intval($_REQUEST["uid"]);
  $subject = trim($_REQUEST["subject"]);
  $message = trim($_REQUEST["message"]);
  $this_user = forum_user($uid);
  if (!$this_user) $error[] = lang("error_usernotfound");
  if (!$error) {
    if (!$subject) $error[] = lang("error_nosubject");
    if (!$message) $error[] = lang("error_nomailmess");
    if (!$error) {
    
      //code in the message
      //close nonclosed bbcodes
      $bbcode = array("b","i","u","quote","code","list","img","url");
      for ($i=0;$i<count($bbcode);$i++) {
        if ($bbcode[$i] == "url") $open_cnt = substr_count($message,"[" . $bbcode[$i]);
        else  $open_cnt = substr_count($message,"[" . $bbcode[$i] . "]");
        $close_cnt = substr_count($message,"[/" . $bbcode[$i] . "]");
        if ($open_cnt > $close_cnt) {
          $message .= str_repeat("[/" . $bbcode[$i] . "]",($open_cnt-$close_cnt));
        }
      }
      $message = preg_replace("/\[code\](.*?)\[\/code\]/e", ("'[code]'.htmlentities('$1').'[/code]'"), $message);
      
      //insert into database
      $sql = "insert into `" . $ftable_prefix . "pm` set from_uid = '$f_auth_uid', to_uid = '$uid', from_name = " . dbquote($forum_user->user) . ", to_name = " . dbquote($this_user->user) . ", subject = " . dbquote($subject) . ", message = " . dbquote(strip_tags($message)) . ", sent = now()";
      dbquery($sql);
    
      //inform recipient if his board notification is enabled
      if ($this_user->forummail) {
        //creating, parsing and sending the email
        //Template Variables
        $RCPT_NAME = $this_user->user;
        $PM_SUBJECT = $subject;
        $FROM_NAME = $forum_user->user;
        $PM_URL = "http://" . $base_url . $main_script . "?todo=showpms";
        $BOARD_ADMIN = $conf_board_admin;
        
        /************
         * initiate template and assign variables
         ************/                 
        $mailVARS = array('CONF_FORUMTITLE' => $GLOBAL_TEMPLATE_VARS["FORUMTITLE"], 'RCPT_NAME' => $RCPT_NAME, 'PM_SUBJECT' => $PM_SUBJECT, 'BOARD_ADMIN' => $BOARD_ADMIN, 'FROM_NAME' => $FROM_NAME, 'PM_URL' => $PM_URL);
        $QuickSkin = new QuickSkin("mail_newpm.txt");
        $QuickSkin->set("template_dir","$www_dir/lang/$f_lang/");
        $QuickSkin->assign($mailVARS);
        $mail_mess = $QuickSkin->result();
        unset($QuickSkin);

        mail ($this_user->email, lang("subject_new_pm"), $mail_mess, "From: $conf_board_mailfrom");
      }
      $success = sprintf(lang("success_message_sent"), $this_user->user);
    } else {
      $todo = "sendpm";
    }
  } else $todo = "sendpm";
}
/****
 * ACTION: Send private message [-]
 ****/
 

 /****
 * ACTION: delete multiple or single private messages [+]
 ****/
if ($action == "delpm") {
  $pmid = intval($_REQUEST["pmid"]);
  if ($pmid) $pmids = array($pmid);
  else $pmids = $_REQUEST["pmids"];
  if (!$pmids) $error[] = lang("error_notenough");
  if (!$error) {
    $sql = "select * from `" . $ftable_prefix . "pm` where id in (" . implode(",",$pmids) . ") and (to_uid = '$f_auth_uid' or from_uid = '$f_auth_uid')";
    $res = dbquery($sql);
    if (!mysql_num_rows($res)) $error[] = lang("error_pm_notfound");
    else {
      while ($row = mysql_fetch_object($res)) {
        if ((!$row->seen && $row->from_uid == $f_auth_uid) ||       //really delete if unsent(unseen) and user is sender
            ($row->to_uid == $f_auth_uid && $row->deleted_from) ||  //really delete if recipient is user and sender set the delete flag
            ($row->from_uid == $f_auth_uid && $row->deleted_to) ||  //really delete if sender is user and recipient set the delete flag
            ($row->from_uid == $row->from_uid)) {                   //really delete if sender and recipient is the same person            
          dbquery("delete from `" . $ftable_prefix . "pm` where id ='" . $row->id . "' and (to_uid = '$f_auth_uid' or from_uid = '$f_auth_uid')");
        } else {
          if ($row->to_uid == $f_auth_uid) {
            //set recpient's the delete flag
            dbquery("update `" . $ftable_prefix . "pm` set deleted_to = '1' where id ='" . $row->id . "' and to_uid = '$f_auth_uid'");
          } elseif ($row->from_uid == $f_auth_uid) {
            //set sender's the delete flag
            dbquery("update `" . $ftable_prefix . "pm` set deleted_from = '1' where id ='" . $row->id . "' and from_uid = '$f_auth_uid'");
          }
        }
      }
      $success = lang($pmid ? "success_del_pm" : "success_del_pms");
    }
  }
  $todo = "showpms";
}
/****
 * ACTION: delete multiple or single private messages [-]
 ****/
 
 
 /****
 * ACTION: Sendmail [+]
 ****/
if ($action == "sendmail") {
  $uid = intval($_REQUEST["uid"]);
  $subject = trim($_REQUEST["subject"]);
  $message = trim($_REQUEST["message"]);
  $this_user = forum_user($uid);
  if (!$board_config->en_user_mess)  $error[] = lang("error_noperm");
  if (!$this_user) $error[] = lang("error_usernotfound");
  if (!$this_user->usermail) $error[] = lang("error_nousermess");
  if (!$error) {
    if (!$subject) $error[] = lang("error_nosubject");
    if (!$message) $error[] = lang("error_nomailmess");
    if (!$error) {
      //creating, parsing and sending the email
      //Template Variables
      $RCPT_NAME = $this_user->user;
      $FROM_NAME = $forum_user->user;
      $BOARD_ADMIN = $conf_board_admin;
      $MESSAGE = $message;

      /************
       * initiate template and assign variables
       ************/                 
      $mailVARS = array('CONF_FORUMTITLE' => $GLOBAL_TEMPLATE_VARS["FORUMTITLE"], 'RCPT_NAME' => $RCPT_NAME, 'FROM_NAME' => $FROM_NAME, 'BOARD_ADMIN' => $BOARD_ADMIN, 'MESSAGE' => $MESSAGE);
      $QuickSkin = new QuickSkin("mail_sendmess.txt");
      $QuickSkin->set("template_dir","$www_dir/lang/$f_lang/");
      $QuickSkin->assign($mailVARS);
      $mail_mess = $QuickSkin->result();
      unset($QuickSkin);
    
      mail ($this_user->email, $subject, $mail_mess, "From: " . $forum_user->email);
      $success = sprintf(lang("success_message_sent"), $this_user->user);
    } else {
      $todo = "sendmail";
    }
  } else $todo = "sendmail";
}
/****
 * ACTION: Sendmail [-]
 ****/

/****
 * ACTION: Sendmail to all users by Administrator [+]
 ****/
if ($action == "sendmail2all") {
  $subject = trim($_REQUEST["subject"]);
  $message = trim($_REQUEST["message"]);
  if (!$is_board_admin)  $error[] = lang("error_noperm");
  if (!$error) {
    if (!$subject) $error[] = lang("error_nosubject");
    if (!$message) $error[] = lang("error_nomailmess");
    if (!$error) {
      $sql = "select * from `" . $ftable_prefix . "users` where status = '1'";
      $res = dbquery($sql);
      while ($row = mysql_fetch_object($res)) {
        $mailuids[] = $row->id;
      }
      if ($mailuids) {
        $mailuids = array_unique($mailuids);
        $FROM_NAME = $forum_user->user;
        $BOARD_ADMIN = $conf_board_admin;
        $MESSAGE = $message;
        $QuickSkin = new QuickSkin("mail_sendmess.txt");
        $QuickSkin->set("template_dir","$www_dir/lang/$f_lang/");
        $mailVARS = array('CONF_FORUMTITLE' => $GLOBAL_TEMPLATE_VARS["FORUMTITLE"], 'FROM_NAME' => $FROM_NAME, 'BOARD_ADMIN' => $BOARD_ADMIN, 'MESSAGE' => $MESSAGE);
        for ($i=0;$i<count($mailuids);$i++) {
          $this_user = forum_user($mailuids[$i]);
          //creating, parsing and sending the email
          $mailVARS["RCPT_NAME"] = $this_user->user;
          $QuickSkin->assign($mailVARS);
          $mail_mess = $QuickSkin->result();
          mail ($this_user->email, $subject, $mail_mess, "From: " . $forum_user->email);

          $succUsers[] = $this_user->user;
        }
        if ($succUsers) $success = sprintf(lang("success_message_sent"), implode(", ", $succUsers));
        unset($QuickSkin);
      }
    } else {
      $section = "sendmail2all";
    }
  } else $section = "sendmail2all";
  $todo = "adminusers";
}
/****
 * ACTION: Sendmail to all users by Administrator [-]
 ****/


/****
 * ACTION: delete complete topic [+]
 ****/
if ($action == "deltopic") {
  $tid = intval($_REQUEST["tid"]);
  if (!$is_mod) $error[] = lang("error_accessdenied");
  else {
    if (!$tid) $error[] = lang("error_notenough");
    else {
      $sql = "select * from `" . $ftable_prefix . "question` where id = '$tid';";
      $res = dbquery($sql);
      if (!mysql_num_rows($res)) $error[] = lang("error_topicnotfound");
    }
  }
  if (!$error) {
    $sql = "delete from `" . $ftable_prefix . "question` where id = '$tid';";
    dbquery($sql);
    $sql = "delete from `" . $ftable_prefix . "answer` where question_id = '$tid';";
    dbquery($sql);
    //poll options
    $sql = "select id from `" . $ftable_prefix . "poll_options` where tid = '$tid';";
    $res = dbquery($sql);
    while ($row = mysql_fetch_object($res)) {
      dbquery("delete from `" . $ftable_prefix . "polls` where poll_option_id = '" . $row->id . "';");  
    }
    $sql = "delete from `" . $ftable_prefix . "poll_options` where tid = '$tid';";
    dbquery($sql);
    //check out if there are any attachments - delete
    $sql = "select * from `" . $ftable_prefix . "attachments` where tid = '$tid';";
    $res = dbquery($sql);
    while ($row = mysql_fetch_object($res)) {
      xrmdir("$www_data_dir/attachments/" . $row->id);    
    }
    dbquery("delete from `" . $ftable_prefix . "attachments` where tid = '$tid';");
    $success = lang("success_topicdel");
  }
  $todo = "show_topics";
}
/****
 * ACTION: delete complete topic [-]
 ****/

/****
 * ACTION: delete complete topics [+]
 ****/
if ($action == "deltopics") {
  $tids = ($_REQUEST["tids"]);
  if (!$is_mod) $error[] = lang("error_accessdenied");
  elseif (!$tids) $error[] = lang("error_notenough");
  if (!$error) {
    $sql = "delete from `" . $ftable_prefix . "question` where id in (" . implode(",",$tids) . ")";
    dbquery($sql);
    $sql = "delete from `" . $ftable_prefix . "answer` where question_id in (" . implode(",",$tids) . ")";
    dbquery($sql);
    //poll options
    $sql = "select id from `" . $ftable_prefix . "poll_options` where tid in (" . implode(",",$tids) . ")";
    $res = dbquery($sql);
    while ($row = mysql_fetch_object($res)) {
      dbquery("delete from `" . $ftable_prefix . "polls` where poll_option_id = '" . $row->id . "'");  
    }
    $sql = "delete from `" . $ftable_prefix . "poll_options` where tid in (" . implode(",",$tids) . ")";
    dbquery($sql);
    //check out if there are any attachments - delete
    $sql = "select * from `" . $ftable_prefix . "attachments` where tid in (" . implode(",",$tids) . ")";
    $res = dbquery($sql);
    while ($row = mysql_fetch_object($res)) {
      xrmdir("$www_data_dir/attachments/" . $row->id);    
    }
    dbquery("delete from `" . $ftable_prefix . "attachments` where tid in (" . implode(",",$tids) . ")");
    $success = lang("success_topicsdel");
  }
  $todo = "show_topics";
}
/****
 * ACTION: delete complete topics [-]
 ****/


/****
 * ACTION: move topic [+]
 ****/
if ($action == "movetopic") {
  $tid = intval($_REQUEST["tid"]);
  $fid = intval($_REQUEST["forum_id"]);
  if (!$is_mod) $error[] = lang("error_accessdenied");
  else {
    if (!$tid || !$fid) $error[] = lang("error_notenough");
    else {
      $sql = "select * from `" . $ftable_prefix . "question` where id = '$tid'";
      $res = dbquery($sql);
      if (!mysql_num_rows($res)) $error[] = lang("error_topicnotfound");
      $sql = "select * from `" . $ftable_prefix . "forums` where id = '$fid'";
      $res = dbquery($sql);
      if (!mysql_num_rows($res)) $error[] = lang("forum_notfound");
    }
  }
  if (!$error) {
    $sql = "update `" . $ftable_prefix . "question` set fid = '$fid' where id = '$tid'";
    dbquery($sql);
    $success = lang("success_move_topic");
  }
  $todo = "show_topics";
}
/****
 * ACTION: move topic [-]
 ****/
 
/****
 * ACTION: lock/unlock topic [+]
 ****/
if ($action == "chglock") {
  $tid = intval($_REQUEST["tid"]);
  $currlock = intval($_REQUEST["currlock"]);
  if (!$is_mod) $error[] = lang("error_accessdenied");
  else {
    if (!$tid) $error[] = lang("error_notenough");
    else {
      $sql = "select * from `" . $ftable_prefix . "question` where id = '$tid';";
      $res = dbquery($sql);
      if (!mysql_num_rows($res)) $error[] = lang("error_topicnotfound");
    }
  }
  if (!$error) {
    $sql = "update `" . $ftable_prefix . "question` set locked = '" . ($currlock ? 0 : 1) . "' where id = '$tid';";
    dbquery($sql);
    $success = lang ("success_topic" . ($currlock ? "un" : "") . "lock");
  }
  $todo = "viewtopic";
}
/****
 * ACTION: lock/unlock topic [-]
 ****/

/****
 * ACTION: delete single post [+]
 ****/
if ($action == "delpost") {
  //prevent from double deletion
  $tid = intval($_REQUEST["tid"]);
  $pid = intval($_REQUEST["pid"]);
  if (!$is_mod) $error[] = lang("error_accessdenied");
  else {
    if (!$tid || !$pid) $error[] = lang("error_notenough");
    else {
      $sql = "select * from `" . $ftable_prefix . "question` where id = '$tid';";
      $res = dbquery($sql);
      if (!mysql_num_rows($res)) $error[] = lang("error_topicnotfound");
    }
  }
  if (!$error) {
    //delete
    $sql = "delete from `" . $ftable_prefix . "answer` where question_id = '$tid' and a_id = '$pid';";
    dbquery($sql);
    //resort
    $sql = "select * from `" . $ftable_prefix . "answer` where question_id = '$tid' order by a_id;";
    $res = dbquery($sql);
    $i = 0;
    unset ($lastanswer);
    while ($row = mysql_fetch_object($res)) {
      $i++;
      $sql = "update `" . $ftable_prefix . "answer` set a_id = '$i' where question_id = '$tid' and a_id = '" . $row->a_id . "';";
      dbquery($sql);
      //last answerinfos
      $lastanswer = $row;
    }
    //update maintopic infos
    $sql = "update `" . $ftable_prefix . "question` set reply = '$i', a_datetime = " . ($lastanswer->a_datetime ? "'" . $lastanswer->a_datetime . "'" : "datetime") . ", a_uid = '" . $lastanswer->a_uid . "' where id = '$tid';";
    dbquery($sql);
    
    //check out if there are any attachments - delete
    $sql = "select * from `" . $ftable_prefix . "attachments` where tid = '$tid' and pid = '$pid';";
    $res = dbquery($sql);
    while ($row = mysql_fetch_object($res)) {
      xrmdir("$www_data_dir/attachments/" . $row->id);    
    }
    dbquery("delete from `" . $ftable_prefix . "attachments` where tid = '$tid' and pid = '$pid';");
    //check out if there are still any attachments
    $sql = "select * from `" . $ftable_prefix . "attachments` where tid = '$tid';";
    $res = dbquery($sql);
    if (!mysql_num_rows($res)) dbquery("update `" . $ftable_prefix . "question` set attachment = '0' where id = '$tid';");
    else {
      //update attachment_pids
      $sql = "update `" . $ftable_prefix . "attachments` set pid = pid-1 where tid = '$tid' and pid > $pid;";
      dbquery($sql);
    }
    
    $success = lang("success_postdel");
    $todo = "viewtopic";
  }
}
/****
 * ACTION: delete single post [-]
 ****/

/****
 * ACTION: delete single attachments [+]
 ****/
 if ($action == "delattachment") {
    $id = intval($_REQUEST["id"]);
    $tid = intval($_REQUEST["tid"]);
    $pid = intval($_REQUEST["pid"]);
    
    if (!$id || !$tid) {
      $error[] = lang("error_notenough");
      unset($todo);
    }
    if (!has_edit_permission($tid,$pid)) $error[] = lang("error_noperm");
    
    if (!$error) {
      //get infos
      $sql = "select * from `" . $ftable_prefix . "attachments` where id = '$id' and (tid = '$tid' or pid = '$pid');";
      $res = dbquery($sql);
      if (!mysql_num_rows($res)) $error[] = lang("error_attachmentnotfound");
      else {
        $sql = "delete from `" . $ftable_prefix . "attachments` where id = '$id' and (tid = '$tid' or pid = '$pid');";
        dbquery($sql);
        xrmdir("$www_data_dir/attachments/$id");
        
        //check out if there are any attachments
        $sql = "select * from `" . $ftable_prefix . "attachments` where tid = '$tid';";
        $res = dbquery($sql);
        if (!mysql_num_rows($res)) dbquery("update `" . $ftable_prefix . "question` set attachment = '0' where id = '$tid';");
                
        $success = lang("success_attdel"); 
      }
      $todo = "edit_post";
    }
    unset($action);
 }
 
/****
 * ACTION: delete single attachments [-]
 ****/



 
/****
 * ACTION: configure board [+]
 ****/
if ($action == "admin_board") {
  if (!$is_board_admin) lang("error_accessdenied");
  else {
  
    $board_template = trim($_REQUEST["board_template"]);
    $board_en_registering = intval($_REQUEST["board_en_registering"]);
    $board_guest_viewing = intval($_REQUEST["board_guest_viewing"]);
    $board_avatar = intval($_REQUEST["board_avatar"]);
    $board_title = trim($_REQUEST["board_title"]);
    $board_descr = trim($_REQUEST["board_descr"]);
    $board_use_cap = intval($_REQUEST["board_use_cap"]);
    $board_en_seo = intval($_REQUEST["board_en_seo"]);
    $board_reserved_users = trim(strtolower($_REQUEST["board_reserved_users"]));
    $board_lang = trim($_REQUEST["board_lang"]);
    $board_topics_per_page = intval($_REQUEST["board_topics_per_page"]);
    $board_posts_per_page = intval($_REQUEST["board_posts_per_page"]);
    $board_users_per_page = intval($_REQUEST["board_users_per_page"]);
    $board_results_per_page = intval($_REQUEST["board_results_per_page"]);

    $board_socialrow = intval($_REQUEST["board_socialrow"]);

    $board_max_img_width = intval($_REQUEST["board_max_img_width"]);
    $board_avatar_height = intval($_REQUEST["board_avatar_height"]);
    $board_avatar_width = intval($_REQUEST["board_avatar_width"]);
    
    $board_en_user_mess = intval($_REQUEST["board_en_user_mess"]);
    $board_en_board_notification = intval($_REQUEST["board_en_board_notification"]);
    $board_email_board_admin = trim(strtolower($_REQUEST["board_email_board_admin"]));
    $board_email_board_mailfrom = trim(strtolower($_REQUEST["board_email_board_mailfrom"]));
    
    $board_date_format = trim($_REQUEST["board_date_format"]);
    $board_date_time_format = trim($_REQUEST["board_date_time_format"]);
    $board_date_md_format = trim($_REQUEST["board_date_md_format"]);
    $board_default_timezone = trim($_REQUEST["board_default_timezone"]);
    
    $board_mod_minutes = intval($_REQUEST["board_mod_minutes"]);
    $board_en_polls = intval($_REQUEST["board_en_polls"]);
    $board_en_pms = intval($_REQUEST["board_en_pms"]);
    $board_max_pms = intval($_REQUEST["board_max_pms"]);
    $board_default_avatar = intval($_REQUEST["board_default_avatar"]);
    $board_en_gravatar = intval($_REQUEST["board_en_gravatar"]);
    $board_max_poll_options = intval($_REQUEST["board_max_poll_options"]);
    
    $board_en_attachments = intval($_REQUEST["board_en_attachments"]);
    $board_max_attachment_size = intval($_REQUEST["board_max_attachment_size"]);
    
    $board_activation = intval($_REQUEST["board_activation"]);
    
    $board_main_script = trim($_REQUEST["board_main_script"]);
    $board_main_path = trim($_REQUEST["board_main_path"]);
    if (!$board_main_script) $board_main_script = $main_script;
    if (!$board_main_path) $board_main_path = $main_path;
    
    if ($board_use_cap == 3) {
      $board_recaptcha_privkey = trim($_REQUEST["board_recaptcha_privkey"]);
      $board_recaptcha_pubkey = trim($_REQUEST["board_recaptcha_pubkey"]);
      $board_recaptcha_style = trim($_REQUEST["board_recaptcha_style"]);
    }

    $board_en_likes = intval($_REQUEST["board_en_likes"]);
    $board_en_dislikes = intval($_REQUEST["board_en_dislikes"]);
    
    if (!is_dir("$www_dir/templates/$board_template")) $error[] = lang("error_templnotfound");
    if (!$board_title) $error[] = lang("error_no_boardtitle");

    //recaptcha
    if ($board_use_cap == 3 && (!$board_recaptcha_privkey || !$board_recaptcha_pubkey)) $error[] = lang("error_no_recaptcha_keys");

    if (!$board_lang) $board_lang = "en";
    if (!$board_email_board_admin) $error[] = lang("error_noboardmail");
    elseif (!is_email($board_email_board_admin)) $error[] = lang("error_invalidboardmail");
    if (!$board_email_board_mailfrom) $error[] = lang("error_nosendermail");
    elseif (!is_email($board_email_board_mailfrom)) $error[] = lang("error_invalidsendermail");
  
    if (!$board_date_format) $board_date_format = "Y-m-d";
    if (!$board_date_time_format) $board_date_time_format = "Y-m-d H:i";
    if (!$board_date_md_format) $board_date_md_format = "M d";

  
    if (!$error) {
      $sql = "update `" . $ftable_prefix . "config` set template = '$board_template', en_registering = '$board_en_registering', en_guest_viewing = '$board_guest_viewing', en_avatar = '$board_avatar', title = " . dbquote($board_title) . ", descr = " . dbquote($board_descr) . ", use_cap = '$board_use_cap', seo = '$board_en_seo', reserved_users = " . dbquote($board_reserved_users) . ", lang = " . dbquote($board_lang) . ", topics_per_page = '$board_topics_per_page', posts_per_page = '$board_posts_per_page', users_per_page = '$board_users_per_page', results_per_page = '$board_results_per_page', max_img_width = '$board_max_img_width', avatar_height = '$board_avatar_height', avatar_width = '$board_avatar_width', en_user_mess = '$board_en_user_mess', en_board_notification = '$board_en_board_notification', email_board_admin = '$board_email_board_admin', email_board_mailfrom = '$board_email_board_mailfrom', date_format = " . dbquote($board_date_format) . ", date_time_format = " . dbquote($board_date_time_format) . ", date_md_format = " . dbquote($board_date_md_format) . ", default_timezone = " . dbquote($board_default_timezone) . ", mod_minutes = '$board_mod_minutes', en_polls = '$board_en_polls', en_pms = '$board_en_pms', max_pms = '$board_max_pms', default_avatar = '$board_default_avatar', en_gravatar = '$board_en_gravatar', max_poll_options = '$board_max_poll_options', activation = '$board_activation', en_attachments = '$board_en_attachments', max_attachment_size = '$board_max_attachment_size', main_script = " . dbquote($board_main_script) . ", main_path = " . dbquote($board_main_path) . ", socialrow = '$board_socialrow', en_likes = '$board_en_likes', en_dislikes = '$board_en_dislikes'" . 
      ($board_use_cap == 3 ? ", recaptcha_pubkey = " . dbquote($board_recaptcha_pubkey) . ", recaptcha_privkey = " . dbquote($board_recaptcha_privkey) . ", recaptcha_style = " . dbquote($board_recaptcha_style) : "") . 
      " where id = '" . $board_config->id . "';";
      dbquery($sql);
      $success = lang("success_upd_board");
    }
    $todo = "admin";
  } 
}
/****
 * ACTION: configure board [-]
 ****/

/****
 * ACTION: configure forums [+]
 ****/
if ($action == "admin_forum") {
   $todo = "adminforums";
  if (!$is_board_admin) lang("error_accessdenied");
  else {
    $saction = $_REQUEST["saction"];
    
    //edit/create single forum
    if ($saction == "edit") {
      $id = intval($_REQUEST["id"]);
      $cat_id = intval($_REQUEST["cat_id"]);
      $vperm = intval($_REQUEST["vperm"]);
      $rperm = intval($_REQUEST["rperm"]);
      $pperm = intval($_REQUEST["pperm"]);
      $forum_title = trim($_REQUEST["forum_title"]);
      $forum_descr = trim($_REQUEST["forum_descr"]);
      
      if (!$forum_title) $error[] = lang("error_no_forumtitle");
      if ($id && !$forum[$id]) $error[] = lang("error_forumnotfound");
      
      if (!$error) {
        if ($cat_id && !$category[$cat_id]) $cat_id = 0;
        $add2sql = "title = " . dbquote($forum_title) . ", descr = " . dbquote($forum_descr) . ", cat_id = '$cat_id', viewing_permission = '$vperm', posting_permission = '$pperm', reply_permission = '$rperm'";
        if ($id) {
          $sql = "update `" . $ftable_prefix . "forums` set $add2sql where id = '$id';";
        } else {
          $sql = "insert into `" . $ftable_prefix . "forums` set $add2sql, pos = '999', created = now();";
        }
        dbquery($sql);
        $success = lang("success_" . ($id?"upd":"new") . "_forum");
        $saction = "repos";
      } else $section = "edit";
    }
    
    //edit/create single category
    if ($saction == "editc") {
      $id = intval($_REQUEST["id"]);
      $category_title = trim($_REQUEST["category_title"]);
      $category_descr = trim($_REQUEST["category_descr"]);
      
      if (!$category_title) $error[] = lang("error_no_categorytitle");
      if ($id && !$category[$id]) $error[] = lang("error_categorynotfound");
      
      if (!$error) {
        $add2sql = "title = " . dbquote($category_title) . ", descr = " . dbquote($category_descr);
        if ($id) {
          $sql = "update `" . $ftable_prefix . "categories` set $add2sql where id = '$id';";
        } else {
          $sql = "insert into `" . $ftable_prefix . "categories` set $add2sql, pos = '" . ($categories[count($categories)-1]->pos + 1) . "', created = now();";
        }
        dbquery($sql);
        $success = lang("success_" . ($id?"upd":"new") . "_category");
      } else $section = "editc";
    }
    
    
    //category up
    if ($saction == "upc") {
      $id = intval($_REQUEST["id"]);
      if (!$id) $error[] = lang("error_no_category");
      elseif (!$category[$id]) $error[] = lang("error_categorynotfound");
      if (!$error) {
        $sql = "update `" . $ftable_prefix . "categories` set pos = pos-1 where id = '$id';";
        dbquery($sql);
        $sql = "update `" . $ftable_prefix . "categories` set pos = pos+1 where pos = '" . ($category[$id]->pos - 1) . "' and id != '$id';";
        dbquery($sql);
        $success = lang("success_pos_category");
        $saction = "reposc";
      }
    }
    //category down
    if ($saction == "downc") {
      $id = intval($_REQUEST["id"]);
      if (!$id) $error[] = lang("error_no_category");
      elseif (!$category[$id]) $error[] = lang("error_categorynotfound");
      if (!$error) {
        $sql = "update `" . $ftable_prefix . "categories` set pos = pos+1 where id = '$id';";
        dbquery($sql);
        $sql = "update `" . $ftable_prefix . "categories` set pos = pos-1 where pos = '" . ($category[$id]->pos + 1) . "' and id != '$id';";
        dbquery($sql);
        $success = lang("success_pos_category");
        $saction = "reposc";
      }
    }
    
    
    //forum up
    if ($saction == "up") {
      $id = intval($_REQUEST["id"]);
      if (!$id) $error[] = lang("error_no_forum");
      elseif (!$forum[$id]) $error[] = lang("error_forumnotfound");
      if (!$error) {
        $sql = "update `" . $ftable_prefix . "forums` set pos = pos-1 where id = '$id';";
        dbquery($sql);
        $sql = "update `" . $ftable_prefix . "forums` set pos = pos+1 where pos = '" . ($forum[$id]->pos - 1) . "' and id != '$id';";
        dbquery($sql);
        $success = lang("success_pos_forum");
        $saction = "repos";
      }
    }
    
    //forum down
    if ($saction == "down") {
      $id = intval($_REQUEST["id"]);
      if (!$id) $error[] = lang("error_no_forum");
      elseif (!$forum[$id]) $error[] = lang("error_forumnotfound");
      if (!$error) {
        $sql = "update `" . $ftable_prefix . "forums` set pos = pos+1 where id = '$id';";
        dbquery($sql);
        $sql = "update `" . $ftable_prefix . "forums` set pos = pos-1 where pos = '" . ($forum[$id]->pos + 1) . "' and id != '$id';";
        dbquery($sql);
        $success = lang("success_pos_forum");
        $saction = "repos";
      }
    }
    
    //delete category
    if ($saction == "delc") {
      $id = intval($_REQUEST["id"]);
      if (!$id) $error[] = lang("error_no_category");
      if (!$error) {
        //delete category
        $sql = "delete from `" . $ftable_prefix . "categories` where id = '$id';";
        $res = dbquery($sql);
        //update forums
        $sql = "update `" . $ftable_prefix . "forums` set cat_id = '0' where cat_id = '$id';";
        $res = dbquery($sql);
        //and repos the forums and the categories
        $saction = "repos";
        $reposc = true;
        $success = lang("success_del_category");
      }
    }
    
    //delete forum
    if ($saction == "del") {
      $id = intval($_REQUEST["id"]);
      if (!$id) $error[] = lang("error_no_forum");
      if (!$error) {
        //delete forum
        $sql = "delete from `" . $ftable_prefix . "forums` where id = '$id';";
        $res = dbquery($sql);
        //get topics
        $sql = "select * from `" . $ftable_prefix . "question` where fid = '$id';";
        $res = dbquery($sql);
        while ($row = mysql_fetch_object($res)) {
          //delete answers
          dbquery("delete from `" . $ftable_prefix . "answer` where question_id = '" . $row->id . "';");
        }
        //delete topics
        dbquery("delete from `" . $ftable_prefix . "question` where fid = '$id';");
        //and repos the forum
        $saction = "repos";
        $success = lang("success_del_forum");
      }
    }
    
    //repos forums reloaded (with categories)
    if ($saction == "repos") {
      $sql = "select * from `" . $ftable_prefix . "forums` order by cat_id, pos;";
      $res = dbquery($sql);
      while ($row = mysql_fetch_object($res)) {
        if ($row->cat_id == $tmp_cat_id) $pos++;
        else $pos = 1;
        dbquery("update `" . $ftable_prefix . "forums` set pos = '$pos' where id = '" . $row->id . "';");
        $tmp_cat_id = $row->cat_id;
      }
      if ($reposc) $saction = "reposc";
    }
    
    //repos categories
    if ($saction == "reposc") {
      $sql = "select * from `" . $ftable_prefix . "categories` order by pos;";
      $res = dbquery($sql);
      $pos = 1;
      while ($row = mysql_fetch_object($res)) {
        dbquery("update `" . $ftable_prefix . "categories` set pos = '" . $pos++ . "' where id = '" . $row->id . "';");
      }
    }
  }
}

/****
 * ACTION: configure forums [-]
 ****/
 
 ?>