<?php
require("includes/global.php");
$maxPerPage = $pageInfo['maxPerPage'];
$p = @$_GET['p'] ? @$_GET['p'] : 1;
$offset = ($p * $maxPerPage) - $maxPerPage;

$id = @$_GET['id'];
if (!$id) {header("Location: index.php");
exit;}

$query = mysqli_query($connection,"SELECT * FROM `threads` WHERE id='$id'");
$q = mysqli_fetch_array($query);

$query2 = mysqli_query($connection,"SELECT * FROM `forums` WHERE id='".$q['inForum']."'");
$q2 = mysqli_fetch_array($query2);
$locked = $q2['locked'];

if (!$q) {header("Location: index.php");
exit;}

$views = $q['views'] + 1;
mysqli_query($connection,"UPDATE `threads` SET views='$views' WHERE id='$id'");

$oldquery = mysqli_query($connection,"SELECT * FROM `posts` WHERE inThread='$id'");
$oldcount = mysqli_num_rows($oldquery);

$pageInfo['title'] = "View Thread: ".$q['title'];

$pageInfo['homelink'] .= " -> <a href=\"viewforum.php?id=".$q2['id']."\">".$q2['name']."</a>";
$pageInfo['homelink'] .= " -> <a href=\"viewthread.php?id=".$q['id']."\">".$q['title']."</a>";

fetchTemplate("header");

fetchTemplate("viewthreadtop");

$query2 = mysqli_query($connection,"SELECT * FROM `posts` WHERE inThread='$id' ORDER BY `id` ASC  LIMIT $offset,$maxPerPage");
while ($q2 = mysqli_fetch_array($query2)) {
 $posterId = $q2['posterId'];
 $query3 = mysqli_query($connection,"SELECT * FROM `users` WHERE id='$posterId'");
 $poster = mysqli_fetch_array($query3);

 $q2['post'] = nl2br($q2['post']);
 $q2['post'] = stripslashes($q2['post']);

 // formatting
 $bbcode = array(
  "/\[b\](.+)\[&#47b\]/",
  "/\[i\](.+)\[&#47i\]/",
  "/\[u\](.+)\[&#47u\]/",
  "/\[url\](.+)\[&#47url\]/",
  "/\[url=(.+)\](.+)\[&#47url\]/",
  "/\[img\](.+)\[&#47img\]/"
 );
 $htmlbb = array(
  "<b>$1</b>",
  "<i>$1</i>",
  "<u>$1</u>",
  "<a href=\"$1\" target=\"_blank\">$1</a>",
  "<a href=\"$1\" target=\"_blank\">$2</a>",
  "<img src=\"$1\">"
 );
 $q3 = mysqli_query($connection,"SELECT * FROM `smileys`");
 while ($row = mysqli_fetch_array($q3)) {
  $k = $row['keyVal'];
  $val = array("/\(/", "/\)/", "/\[/", "/\]/");
  $rpl = array("\\(", "\\)", "\\[", "\\]");
  $k = preg_replace($val, $rpl, $k);
  $bbcode[count($bbcode)] = "/{$k}/";
  $htmlbb[count($htmlbb)] = "<img src=\"images/smileys/{$row['src']}\" alt=\"{$row['keyVal']}\" title=\"{$row['keyVal']}\">";
 }
$q2['post'] = preg_replace($bbcode, $htmlbb, $q2['post']);
 fetchTemplate("threadbody");
}

fetchTemplate("viewthreadend");

fetchTemplate("footer");
?>