<?php

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

if (!$tid) exit("Unsufficient data provided");
$www_dir = realpath(dirname(__FILE__));
include ("$www_dir/functions.php");
include ("$www_dir/conf.php");

if (!$board_config->en_guest_viewing && !$_SESSION["SBBauth"]) exit("Permission denied"); 

include ("$www_dir/classes/topics.class.php");
$SBBTopics = new SBBTopics();
$SBBTopics->tid = $tid;

$output = $board_config->title . "\r\n";
$output .= str_repeat("-", strlen($board_config->title)) . "\r\n\r\n";

$SBBTopics->GetPosts(false); 

if ($SBBTopics->posts["main"]) {
  $row = $SBBTopics->posts["main"];
  
  $this_user = forum_user($row->uid);
  
  $this_post_title = $row->topic;
  
  $output .= $row->topic . "\r\n";
  $output .= str_repeat("-", strlen($row->title)) . "\r\n\r\n";
  $output .= str_repeat("=", 80) . "\r\n";
  $output .= "Author: " . ($this_user ? $this_user->user : "Guest") . "[". date($date_time_format,strtotime($row->datetime)) . "]\r\n";
  $output .= "Title: " . $row->topic . "\r\n";
  $output .= str_repeat("~", 80) . "\r\n";
  $output .= strip_bbcodes($row->detail) . "\r\n\r\n";
  $output .= strip_bbcodes($this_user->signature) . "\r\n\r\n\r\n";
  $output .= str_repeat("=", 80) . "\r\n";
  
  //replies
  if ($SBBTopics->posts["replies"]) {
    for ($i=0;$i<$SBBTopics->count;$i++) {
      $row = $SBBTopics->posts["replies"][$i];
      $this_user = forum_user($row->a_uid);
      
      $output .= "Author: " . ($this_user ? $this_user->user : "Guest") . "[". date($date_time_format,strtotime($row->a_datetime)) . "]\r\n";
      $output .= "Title: " . $row->a_topic . "\r\n";
      $output .= str_repeat("~", 80) . "\r\n";
      $output .= strip_bbcodes($row->a_answer) . "\r\n";
      $output .= strip_bbcodes($this_user->signature) . "\r\n";
      $output .= str_repeat("=", 80) . "\r\n\r\n\r\n";
    }
  }
} else {
  exit("404 - Document not found");
}
mysql_free_result($res);

$fname = "SBB-$tid-" . tidyup($this_post_title) . "-" . date("dmGi") . ".txt";

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=$fname;");
header("Content-Transfer-Encoding: binary");
echo $output;

exit();
?>
