<?php #pgs/board/index.php

function boardLoadThread($mysqli, $userID, $ID, $tpl, $lvl = 0, $recursive = true) {
  $ret = "";
  $qry = "SELECT m.ID,m.deleted,m.dttm,m.title,m.text,g.prenames,g.surnames,u.groupID=g.groupID own "
        ."FROM board_messages m LEFT JOIN guests g ON g.ID=m.guestID "
        ."LEFT JOIN users u ON u.ID=".$userID." "
        ."WHERE m.".($lvl ? "parent" : "")."ID = ".$ID;
  if ($res = $mysqli->query($qry)) {
    while ($row = $res->fetch_assoc()) {
      $replace = array(
        "###BOARDMSG.LEVEL###" => ($lvl < 10 ? $lvl : 9),
        "###BOARDMSG.ID###" => $row["ID"],
        "###BOARDMSG.DATETIME###" => $row["dttm"],
        "###BOARDMSG.TITLE###" => $row["deleted"]==0 ? cntCipherTextSym($row["title"], SYM_CIPHER_KEY) : "",
        "###BOARDMSG.TEXT###" => $row["deleted"]==0 ? str_replace("\\r\\n", "<br />", cntCipherTextSym($row["text"], SYM_CIPHER_KEY)) : "<s>Nachricht wurde gelöscht</s>"
      );
      preg_match_all("/([\s-]?)([A-Z])/", $row["surnames"], $matches);
      $replace["###BOARDMSG.AUTHOR###"] = $row["prenames"]." ".implode(".", $matches[0]).".";
      $msg = tplReplMarkerArray($tpl, $replace);
      
      $indent_in_tpl = tplExtrSection($tpl, "###BOARDMSG.INDENT.IN###");
      $indent_out_tpl = tplExtrSection($tpl, "###BOARDMSG.INDENT.OUT###");
      $indent_in = "";
      $indent_out = "";
      for ($i = 0; $i<$lvl; $i++) {
        $class = "";
        if ($i==0) {
          $class.= " boardmsg_indent_first";
        }
        if ($i==$lvl-1) {
          $class.= " boardmsg_indent_last";
        }
        $indent_in.= tplReplMarker($indent_in_tpl, "###BOARDMSG.INDENT.CLASS###", $class);
        $indent_out.= $indent_out_tpl;
      }
      $msg = tplReplSection($msg, "###BOARDMSG.INDENT.IN###", $indent_in);
      $msg = tplReplSection($msg, "###BOARDMSG.INDENT.OUT###", $indent_out);
      
      if ($row["deleted"]==1) {
        $msg = tplReplSection($msg, "###BOARDMSG.FOOTER###", "");
      } elseif ($row["own"]=="0" && !lgnCheckRight($mysqli, "BOARD_DEL", $userID)) {
        $msg = tplReplSection($msg, "###BOARDMSG.DEL###", "");
      }
      $ret.= $msg.($recursive ? boardLoadThread($mysqli, $userID, $row["ID"], $tpl, $lvl+1) : "");
    }
  } else {
    addError("Mysql", $mysqli->error." // Query: ".$qry);
  }
  return $ret;
}
function boardCleanDeletedParents($mysqli, $ID) {
  $res = $mysqli->query("SELECT parentID FROM board_messages m WHERE m.ID=".$ID." AND m.deleted=1 "
                       ." AND (SELECT COUNT(*) FROM board_messages ms WHERE ms.parentID=".$ID.")=0");
  if ($res->num_rows==1) {
    $parentID = $res->fetch_assoc()["parentID"];
    $mysqli->query("DELETE FROM board_messages WHERE ID = ".$ID);
    if ($parentID!=null) {
      boardCleanDeletedParents($mysqli, $parentID);
    }
  }
}

if (isset($input["boardnew_submit"], $input["secToken"]) && $input["secToken"]==$_SESSION["secTokenVerify"] && ($userID = lgnCheckLogin($mysqli))) {
  // Einfügen neuer Nachricht

  // Kategorie herausfinden und testen ob erlaubt
  $categoryID = null;
  $parentID = null;
  $rootID = null;
  $replyto = isset($input["boardnew_replyto"]);
  $qry = "SELECT c.ID "
        .($replyto ? ", m.rootID FROM board_messages m LEFT JOIN board_categories c ON c.ID=m.categoryID " : "FROM board_categories c ")
        ."LEFT JOIN rolerights r ON r.rightID=c.rightID "
        ."LEFT JOIN users u ON u.roleID=r.roleID "
        ."WHERE (c.rightID IS NULL OR u.ID = ?) AND ".($replyto ? "m.ID = ? " : "c.ID = ? ");
  if ($stmt = $mysqli->prepare($qry)) {
    $whereID = $replyto ? $input["boardnew_replyto"] : $input["boardnew_cat"];
    $stmt->bind_param("ii", $userID, $whereID);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows==0) {
      addError("Access", "Kategorie nicht vorhanden oder Zugriff nicht erlaubt1");
    } else {
      $cat = $res->fetch_assoc();
      $categoryID = $cat["ID"];
      if ($replyto) {
        $parentID = $input["boardnew_replyto"];
        $rootID = $cat["rootID"] ?? $parentID;
      }
    }
  }
  
  // Autor überprüfen und gegebenenfalls überschreiben
  $guestID = null;
  $qry = "SELECT g.ID FROM guests g LEFT JOIN users u ON u.groupID=g.groupID WHERE u.ID = ? AND g.companion=0 ORDER BY g.ID = ? DESC LIMIT 1";
  if ($stmt = $mysqli->prepare($qry)) {
    $stmt->bind_param("ii", $userID, $input["boardnew_author"]);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->num_rows==0) {
      addError("Access", "Kategorie nicht vorhanden oder Zugriff nicht erlaubt");
    } else {
      $guestID = $res->fetch_assoc()["ID"];
    }
  }

  // Datensatz einfügen. Wenn Kategorie verboten war, steht sie auf NULL und wird von der Datenbank abgelehnt
  $insert = "INSERT INTO board_messages (guestID, categoryID, rootID, parentID, dttm, title, text) VALUES (?, ?, ?, ?, NOW(), ?, ?)";
  if ($stmt->prepare($insert)) {
    $encTitle = cntCipherTextSym($input["boardnew_title"], SYM_CIPHER_KEY);
    $encText = cntCipherTextSym($input["boardnew_text"], SYM_CIPHER_KEY);
    $stmt->bind_param("iiiiss", $guestID, $categoryID, $rootID, $parentID, $encTitle, $encText);
    if ($stmt->execute()) {
      if (!$replyto)
        $input["thread"] = $mysqli->insert_id;
      
      $neededRight = null;
      $res = $mysqli->query("SELECT r.name FROM board_categories c LEFT JOIN rights r ON r.ID=c.rightID WHERE c.ID=".$categoryID);
      if ($res->num_rows>0)
        $neededRight = $res->fetch_assoc()["name"];
      
      $text = tplExtrSection(tplLoadFile("pgs/board/notify.txt"), "###NOTIFICATION###");
      $text = tplReplMarker($text, "###PAGEMAIN###", $page["main"]);
      $url = parse_url("https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
      $text = tplReplMarker($text, "###PAGEURL###", "https://".$url["host"].$url["path"]);
      $text = tplReplMarker($text, "###THREADID###", $input["thread"]);
      emlSendNotification($mysqli, $userID, "Neuer Beitrag unter Diskussion", $text, $replyto ? 2 : 1, $neededRight);
    }
  }
} elseif (isset($input["del"]) && ($userID = lgnCheckLogin($mysqli))) {
  $qry = "SELECT m.ID, m.rootID, m.parentID, g.groupID=u.groupID own, (SELECT COUNT(*) FROM board_messages ms WHERE ms.parentID=m.ID) children "
        ."FROM board_messages m LEFT JOIN guests g ON g.ID=m.guestID LEFT JOIN users u ON u.ID = ? WHERE m.ID = ?";
  if ($stmt = $mysqli->prepare($qry)) {
    $stmt->bind_param("ii", $userID, $input["del"]);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($row = $res->fetch_assoc()) {
      $input["thread"] = $row["rootID"] ?? $row["ID"];
      
      // Darf löschen?
      if ($row["own"]==1 || lgnCheckRight($mysqli, "BOARD_DEL", $userID)) {
        // Wenn Antworten auf diese Nachricht existieren, nur als gelöscht markieren
        if ($row["children"]>0) {
          $mysqli->query("UPDATE board_messages SET deleted=1 WHERE ID = ".$row["ID"]);
        } else {
          $mysqli->query("DELETE FROM board_messages WHERE ID = ".$row["ID"]);
          if ($row["parentID"]!=null) {
            boardCleanDeletedParents($mysqli, $row["parentID"]);
          }
        }
        if ($row["rootID"]==null) {
          $page["sub"] = "main";
        }
      }
    }
  }
}

addStyle("pgs/board/board.css");
$tpl = array(
  "main" => ""
);
if ($sub = pgsInclSub($page["sub"]))
  include $sub;

$output["main"] = $tpl["main"];

?>