Login
Username: Password:
Remember me

[Sign Up] / [Recover Password]

Theme / Language

Popular
New Torrents
new name
Size: 18.40 MB
Most active
new name
S: 74 L: 3
New Posters
Torrent Trader PDO Update Beta Test
Controls ·  Search New posts · Mark unread

You are in: Forum / Forum / M-BiTsy / M-BiTsy Support

Unknown User
2020-02-23 11:37:13
I have an idea, we should make a native plugin system like the themes.
Unknown User
2020-02-23 12:40:52
"Minzord, post: 67964, member: 20360":

I have an idea, we should make a native plugin system like the themes.

Not easy to do, it will require hooks and plugins manager menu to activate / deactivate plugins.
2020-02-23 15:54:44
I've removed that line of code and should work on 7.4
Pdo is the future but the original 2.08 code is so old and could be simplified, we will slowly get there.
As for theme everyone has different taste so the plan is to make everything generic and replace with bootstrap for example all block css (blockframe) could be replaced with theme css (frame) , all image buttons could be replaced with input buttons etc and just remove as much as possible
We can separate ui into view files
Unknown User
2020-02-23 17:24:21
"m-jay, post: 67970, member: 20288":

I've removed that line of code and should work on 7.4
Pdo is the future but the original 2.08 code is so old and could be simplified, we will slowly get there.
As for theme everyone has different taste so the plan is to make everything generic and replace with bootstrap for example all block css (blockframe) could be replaced with theme css (frame) , all image buttons could be replaced with input buttons etc and just remove as much as possible
We can separate ui into view files
Good idea
2020-03-15 06:45:06
been thinking of how to break the code down better for oop so here is the login - going to start separating everything. ive added links to github comments see you can see full differences

first the autoloader added to init for our classes my database connection is in a class so i dont need to include that anymore
<?php
mb_internal_encoding('UTF-8');

define("TTROOT", dirname(__DIR__));
define("TTCORE", str_replace(__DIR__."backend/", "", dirname(__FILE__)));

include(TTCORE.'/exceptionhelper.php');
// Register custom exception handler
set_exception_handler("handleUncaughtException");

if (function_exists("date_default_timezone_set"))
   date_default_timezone_set("Europe/London"); // Do NOT change this. All times are converted to user's chosen timezone.

require_once (TTCORE."/config.php");  //Get Site Settings and Vars ($site_config)

// require_once (TTCORE."/dbclass.php"); //Get MYSQL Connection Info
require_once (TTCORE."/cache.php"); // Caching
require_once (TTCORE."/mail.php"); // Mail functions
require_once (TTCORE."/tzs.php"); // Get Timezones
require_once (TTCORE."/languages.php");
require_once (TTCORE."/functions.php");
require_once (TTCORE."/bootstraphelper.php");

$GLOBALS['tstart'] = array_sum(explode(" ", microtime()));

// Autoload
spl_autoload_register(function($className) {
   include_once TTROOT . '/classes/' . $className . '.php';
});


the autoloader can be called different ways the database is static and here is the changes i made to use db from autoloader  https://github.com/M-jay84/Torrent-Trader-2020-PDO/commit/553bb408995d2e41f6d9806eae2ce9417a2f7863#diff-5813ce26acf65766e90206a59fc7ae99L5
 (new class)->
or
$class = new class;
$class->
or
Class::


next something small but important move the cookies to a class this is just the two cookie functions and the class has been added before each function is called example  (new Cookie)->logoutcookie https://github.com/M-jay84/Torrent-Trader-2020-PDO/commit/5086ac0dd2228458061398ac384f26bdd1a13f5f
<?php

class Cookie {

   function logincookie($id, $password, $secret, $updatedb = 1, $expires = 0x7fffffff) {
   $hash = $id.$secret.$password.getip().$secret;
   $hash = password_hash($hash, PASSWORD_BCRYPT);
   setcookie("pass", $hash, $expires, "/");
   setcookie("uid", $id, $expires, "/");

   if ($updatedb)
   $stmt = DB::run("UPDATE users SET last_login=? WHERE id=?", [get_date_time(),$id]);
   }

   function logoutcookie() {
   setcookie("pass", null, time(), "/");
   setcookie("uid", null, time(), "/");
   }

}


if where going through all functions and pages we might as well start separating the ui with a template class
<?php

class View {
   //Path to template
   protected $template;
   //Variables passed in
   protected $vars = array();

   //Constructor
   public function __construct($template){
       $this->template = $template;
   }

   //Get template variables
   public function __get($key){
       return $this->vars[$key];
   }

   //Set template variables
   public function __set($key, $value){
       $this->vars[$key] = $value;
   }

   //Convert Object to String
   public function __toString(){
       extract($this->vars);
       chdir(dirname($this->template));
       ob_start();

       include basename($this->template);
       return ob_get_clean();
   }
}


ive just moved this to a template folder
<form method="post" action="account-login.php">
 <table border="0" cellpadding="3" align="center">
       <tr><td align="center"><b><?php echo T_("USERNAME"); ?>:</b> <input type="text" size="40" name="username" /></td></tr>
       <tr><td align="center"><b><?php echo T_("PASSWORD"); ?>:</b> <input type="password" size="40" name="password" /></td></tr>
       <tr><td colspan="2" align="center"><input type="submit" value="<?php echo T_("LOGIN"); ?>" /><br /><br /><i><?php echo T_("COOKIES");?></i></td></tr>
   </table>

</form>
<p align="center"><a href="account-signup.php"><?php echo T_("SIGNUP"); ?></a> | <a href="account-recover.php"><?php echo T_("RECOVER_ACCOUNT"); ?></a></p>


and use this to call template, template vars can be added as well https://github.com/M-jay84/Torrent-Trader-2020-PDO/commit/bae7b153e2beae2f5e92c7ea52056841f673710a
$template = new View('views/login.php');
echo $template;


ive moved the stdhead, stdfoot & blocks functions to a layouthelper to seperate that then the ip functions i was going to have a ip class but i dont think you need it.
Im not sure you need all the ip functions you only use them in admin ban ip section the only exception is getip im sure one function can be enough but for now i put it all in a ip helper the only difference is i removed ip banned from the login function and added it to helper https://github.com/M-jay84/Torrent-Trader-2020-PDO/commit/ba310df2351e791e4a769e73aaa8c53c9a375121
function checkipban($ip) {
   //Check IP bans
   if (is_ipv6($ip))
       $nip = ip2long6($ip);
   else
       $nip = ip2long($ip);
   $res = DB::run('SELECT * FROM bans WHERE true');
   while ($row = $res->fetch(PDO::FETCH_ASSOC)){
       $banned = false;
       if (is_ipv6($row["first"]) && is_ipv6($row["last"]) && is_ipv6($ip)) {
           $row["first"] = ip2long6($row["first"]);
           $row["last"] = ip2long6($row["last"]);
           $banned = bccomp($row["first"], $nip) != -1 && bccomp($row["last"], $nip) != -1;
       } else {
           $row["first"] = ip2long($row["first"]);
           $row["last"] = ip2long($row["last"]);
           $banned = $nip >= $row["first"] && $nip <= $row["last"];
       }
       if ($banned) {
       header("HTTP/1.0 403 Forbidden");
       echo '
   <html>
   <head>
   <title>Forbidden</title>
   </head>
   <body>
   <h1>Forbidden</h1>Unauthorized IP address.
   <br>
   Reason for banning: ', $row['comment'], '
   </body>
   </html>';
       die;
       }
   }
}


now the login function has been added to a class and is called in dbconn function with (new Login)->userlogin();
<?php

class Login {

function userlogin() {
   $ip = getip();
   // If there's no IP a script is being ran from CLI. Any checks here will fail, skip all.
   if ($ip == '') return;

   GLOBAL $CURUSER;
   unset($GLOBALS["CURUSER"]);

   checkipban($ip);

   //Check The Cookie and get CURUSER details  
   if (strlen($_COOKIE["pass"]) != 60 || !is_numeric($_COOKIE["uid"])) {  
       (new Cookie)->logoutcookie();  
       return;  
   }  
   //Get User Details And Permissions
   $res = DB::run("SELECT * FROM users INNER JOIN groups ON users.class=groups.group_id WHERE id=$_COOKIE[uid] AND users.enabled='yes' AND users.status = 'confirmed'");
   $row = $res->fetch(PDO::FETCH_ASSOC);
   $hash = $row["id"].$row["secret"].$row["password"].$ip.$row["secret"];
   if (!$row || !password_verify($hash,$_COOKIE["pass"])){
       (new Cookie)->logoutcookie();
       return;
   }

   $where = where ($_SERVER["SCRIPT_FILENAME"], $row["id"], 0);
   $id = $row['id'];

   $stmt = DB::run("UPDATE users SET last_access=?,ip=?,page=? WHERE id=?", [get_date_time(),$ip,$where,$id]);
   $GLOBALS["CURUSER"] = $row;
   unset($row);
}

}


this is the account-login
<?php

require_once("backend/init.php");
dbconn();

$user_name = $_POST['username'] ?? false;
$user_password = $_POST['password'] ?? false;
$message = '';

if ($user_name && $user_password) {

   $password = $user_password;
   $row = DB::run("SELECT id, password, secret, status, enabled FROM users WHERE username =? ", [$user_name])->fetch();

       if ( !$row || !password_verify($password,$row["password"]))
           $message = T_("LOGIN_INCORRECT");
       elseif ($row["status"] == "pending")
           $message = T_("ACCOUNT_PENDING");
       elseif ($row["enabled"] == "no")
           $message = T_("ACCOUNT_DISABLED");


   if (!$message){

       (new Cookie)->logincookie($row["id"], $row["password"], $row["secret"]);
       if (!empty($_POST)) {
           header("Refresh: 0; url=index.php");
           die();
       }
   }else{
       show_error_msg(T_("ACCESS_DENIED"), $message, 1);
   }
}

(new Cookie)->logoutcookie();

stdhead(T_("LOGIN"));
   
begin_frame(T_("LOGIN"));

if ($site_config["MEMBERSONLY"]) {
   $message = T_("MEMBERS_ONLY");
print("<center><b>" . $message . "</b></center>\n");
}

$template = new View('views/login.php');
echo $template;

end_frame();
stdfoot();



This could be added to cookie class from login class for example to put all cookie stuff together
function wrongcookie() {
//Check The Cookie and get CURUSER details  
   if (strlen($_COOKIE["pass"]) != 60 || !is_numeric($_COOKIE["uid"])) {
self::logoutcookie();
return;
}  
}
Unknown User
2020-03-16 14:32:20
Here's the example I did for one user who requested oop pdo and wanted to pay for it so i can't really release it in full

init example:

<?php
// Additional included files
include 'config.inc.php';

// Autoload classes
spl_autoload_register('autoLoader');
function autoLoader($class)
{
   include_once 'classes/' . strtolower($class) . '.class.php';
}

//Connect to database
$GLOBALS['db_handler'] = new TTCore(DATABASE['type'] . ':host=' . DATABASE['host'] . ';dbname=' . DATABASE['name'] . ';charset=' . DATABASE['charset'], DATABASE['user'], DATABASE['password']);


Config example:

define('DATABASE', [
   'type' => 'mysql',
   'host' => 'localhost',
   'name' => 'test',
   'user' => 'root',
   'password' => '',
   'charset' => 'utf8mb4'
]);

define('GENERAL', [
   'site_name' => 'TorrentTrader PDO',
   'site_url' => 'https://example.com',
   'site_email' => 'your_email@example.com',
   'members_only' => FALSE,
   'invite_only' => FALSE,
   'allow_external' => FALSE,
   'enable_invites' => FALSE,
   'confirm_email' => FALSE,
   'anonymous_upload' => FALSE,

]);


user.class.php (Includes for both reset password, register, login, and all other checks)

class User
{
   /* @var TTCore */
   protected $db;

   protected $data;

   public function __construct(TTCore $db)
   {
       $this->db = $db;
   }

   /*
    * Find the specific user
    */
   public function find($id)
   {
       $this->data = $this->db->run("SELECT * FROM users WHERE id = ?", [$id])->fetch();
       return $this->data;
   }

   /*
    * Check if email is already in use
    */
   public function emailInUse($email)
   {
       $stmt = $this->db->prepare("SELECT * FROM users WHERE email = ?");
       $stmt->execute([$email]);
       $user = $stmt->fetch();

       if ($user)
       {
           return true;
       }
       else
       {
           return false;
       }
....
   }


And example of login.php


<?php
include 'includes/init.inc.php';
global $db_handler;

$user = new User($db_handler);

if ($user->emailInUse('test@test.com') === TRUE)
{
  $message = 'This email is already in use';
}

.....

if ($message === '')
{
  $user->loginCookies();
}

....
2020-03-17 13:38:46
thanks shadows i like that config i had a class but it seemed a bit overkill just for settings, defines better for scope

breaking it all down (classes/helpers) seems pretty straight forward but one thing that i cant decide on is the global $CURUSER if you have any pointers mate

    // the query
   $row =  DB::run("
   SELECT *
   FROM users INNER JOIN groups ON users.class=groups.group_id
   WHERE id=$_COOKIE[uid] AND users.enabled='yes'
   AND users.status = 'confirmed'
   ")->fetch();

   // verify with cookie
   $hash = $row["id"].$row["secret"].$row["password"].$ip.$row["secret"];
   if (!$row || !password_verify($hash,$_COOKIE["pass"])){
       (new Cookie)->logoutcookie();
       return;
   }

   // get current user
   $GLOBALS["CURUSER"] = $row;


$CURUSER is used 415 times and im trying to find a quick way to change to a user class
write_log("A Mass PM was sent by ($CURUSER[username])");

$sender_id = ($_POST['sender'] == 'system' ? 0 : $CURUSER['id']);


i was thinking something like, but how do i return the row from the class
write_log("A Mass PM was sent by ($user->get(username))");

$sender_id = ($_POST['sender'] == 'system' ? 0 : $user->get('id'));
Unknown User
2020-03-17 15:08:18
Try something like this:

Class:
public function curuser()
{
   $stmt = $this->db->run("SELECT * FROM users WHERE id = 1");

   if ($stmt && password_verify(/** */))
   {
       foreach ($stmt as $item => $value)
       {
           return $data[$item] = $value;
       }
   }

   /*
    * If not current user / return false
    */
   return false;
}


Inside app

$user = new User();
echo $user->curuser()['username'];

// Strict check
if ($user->curuser() === false)
{
   echo 'Not logged in';
}
// Less strict check
if (!$user->curuser())
{
   echo 'Not logged in';
}


Or you can create a check for if logged in

Class:
public function loggedIn()
{
   if ($this->curuser() === false)
   {
       return false;
   }

   return true;
}


And in app

if ($user->loggedIn())
{
   echo $user->curuser()['username'];
}


---------

Edit:
You can also use GLOBALS like this:
Class:

public function curuser()
{
   $stmt = $this->db->query("SELECT * FROM users WHERE id = 2");

   if ($stmt && password_verify(/** */))
   {
       foreach ($stmt as $item => $value)
       {
           return $data[$item] = $GLOBALS['CURUSER'] = $value;

       }
   }

   /*
    * If not current user / return false
    */
   return false;
}

App:

/*
* User class included
*/
global $CURUSER;
$user = new User($db_handler);
$user->curuser();

echo $CURUSER['username'];
2020-03-17 21:35:13
thanks for help seem to have got this working just need to put it in user class now

function curuser(){
       $sql = DB::run("SELECT * FROM users WHERE id=$_COOKIE[uid]");
       $rows = $sql->fetch(PDO::FETCH_ASSOC);

       if($sql->rowCount() >= 1){
           return $rows;
       }
   }
   
var_dump(curuser());

$user = curuser();

if($user !== null) {
   echo $user['email'];
}

if (!$user['class'] == '5')
{
   echo 'Is Not Moderator</br>';
}

if ($user['class'] == '7')
{
   echo 'Is Admin</br>';
}


ill check curuser with cookie class then build on the user class
eg
isloggedin = is curuser
isadmin - is curuser class admin
Unknown User
2020-03-18 17:26:06
That's not safe, anyone can make random cookie with uid = 1 and get access. You must password_verify it
Unknown User
2020-03-22 14:33:24
[USER=20288]@m-jay[/USER] there are several flaws with your isValidCookie

1. This has a flawed logic, strlen($_COOKIE['pass'] ?? '') != 60 will never work, because you can't expect cookie to be always 60 characters, it will pass that number often or be lower.
2. !is_numeric($_COOKIE['uid'] ?? 0)) will never work the way you want ( ?? return only 1 / 0) so anyone setting cookie as 0, your if statement will read it as 1 and that is security flaw :D

$p = '21';
$a = 21;
$k = '0';
$t = 're';

echo is_numeric($p ?? 0) . "\n";
echo is_numeric($a ?? 0) . "\n";
echo is_numeric($k ?? 0) . "\n";
echo is_numeric($t ?? 0) . "\n";

// output
1
1
1



3. You should just check if it's integer and bigger than zero.
4. No need to use return in new row.

Here's the optimal return
    public function isvalidcookie() {
   if (!is_numeric($_COOKIE['uid']) || (int) $_COOKIE['uid'] < 1 || !isset($_COOKIE['pass']) ) {
       return (new Cookie)->logoutcookie();
   }
   }
2020-03-23 05:37:32
thanks shadows i used ?? ''  trying to remove some of the ini display error warning so many warnings lol.
that curuser function was just a test and has now been moved to a class i stilled used the global $CURUSER
For mass editing it made sense but it now calls a object
    // Get user info
   $CURUSER = (new Curuser)->getuser();
   $GLOBALS["CURUSER"] = $CURUSER;


And then the class idea
<?php

class Curuser {
   
public function getuser(){
   // Get Ip.
   $ip = getip();
   if ($ip == '') return;
   checkipban($ip);

   // check cookie
   (new Cookie)->isvalidcookie();
   
   //Get User Details And Permissions
   $sql = DB::run("SELECT * FROM users INNER JOIN groups ON users.class=groups.group_id WHERE id=? AND users.enabled=? AND users.status =?", [$_COOKIE['uid'], 'yes', 'confirmed']);
   $rows = $sql->fetch(PDO::FETCH_ASSOC);

   $hash = $rows["id"].$rows["secret"].$rows["password"].$ip.$rows["secret"];
   if($rows || password_verify($hash,$_COOKIE['pass'])){
       return $rows;
   }
}

public  function priv($name, $descr) {
   if (self::getuser()["privacy"] == $name)
       return "<input type=\"radio\" name=\"privacy\" value=\"$name\" checked=\"checked\" /> $descr";
   return "<input type=\"radio\" name=\"privacy\" value=\"$name\" /> $descr";
}
   
   
public function loggedinonly() {
   if (!self::getuser()) {
       header("Refresh: 0; url=account-login.php");
       exit();
   }
}

public function get_user_class_name($i){
   if ($i == self::getuser()["class"])
       return self::getuser()["level"];

   $res=DB::run("SELECT level FROM groups WHERE group_id=".$i."");
   $row=$res->fetch(PDO::FETCH_LAZY);
   return $row[0];
}

public function get_user_class(){
   return self::getuser()["class"];
}

public function class_colour($name)
{
   global $site_config;
   $classy = DB::run("SELECT u.class, u.donated, u.warned, u.enabled, g.Color, g.level, u.uploaded, u.downloaded FROM `users` `u` INNER JOIN `groups` `g` ON g.group_id=u.class WHERE username ='" . $name . "'")->fetch();
   $gcolor = $classy['Color'];
   if ($classy['donated'] > 0) {
       $star = "<img src='" . $site_config['SITEURL'] . "/images/donor.png' alt='donated' border='0' width='15' height='15'>";
   } else {
       $star = "";
   }
   if ($classy['warned'] == "yes") {
       $warn = "<img src='" . $site_config['SITEURL'] . "/images/warn.png' alt='Warn' border='0'>";
   } else {
       $warn = "";
   }
  if ($classy['enabled'] == "no") {
       $disabled = "<img src='".$site_config['SITEURL']."/images/disabled.png' title='Disabled' border='0'>";
  } else {
      $disabled = "";
  }

   return unesc("<font color='" . $gcolor . "'>" . $name . "" . $star . "" . $warn . "" . $disabled . "</font>");
}

}


[color=rgb(247, 218, 100)]started thinking of forum and so far i have split it down like this still messy, but ill keep going back to it [/color]
i dont like the actions some could be functions and others could be independent pages like viewtopic

[color=rgb(255, 255, 255)]forum class[/color]
<?php

class Forum {

public function showerror($heading = "Error", $text, $sort = "Error") {
   stdhead("$sort: $heading");
   begin_frame("<font class='error'>$sort: $heading</font>");
   echo $text;
   end_frame();
   stdfoot();
   die;
}

//setup the forum head aread
public function forumheader($location){
echo "<div class='f-header'>
 <div class='f-logo'>
 <table width='100%' cellspacing='6'>
   <tr>
     <td align='left' valign='top'><a href='forums.php'>".T_("FORUM_WELCOME")."</a></td>
     <td align='right' valign='top'><img src='images/forum/help.png'  alt='' />&nbsp;<a href='faq.php'>".T_("FORUM_FAQ")."</a>&nbsp; &nbsp;&nbsp;<img src='images/forum/search.png' alt='' />&nbsp;<a href='forums.php?action=search'>".T_("SEARCH")."</a></td>
   </tr>
   <tr>
     <td align='left' valign='bottom'>&nbsp;</td>
     <td align='right' valign='bottom'><b>".T_("FORUM_CONTROL")."</b> &middot; <a href='forums.php?action=viewunread'>".T_("FORUM_NEW_POSTS")."</a> &middot; <a href='?catchup'>".T_("FORUM_MARK_READ")."</a></td>
   </tr>
 </table>
 </div>
</div>
<br />";
print ("<div class='f-location'><div class='f-nav'>".T_("YOU_ARE_IN").": &nbsp;<a href='forums.php'>".T_("FORUMS")."</a> <b style='vertical-align:middle'>/ $location</b></div></div>");
}

// Mark all forums as read
public function catch_up(){
   global $CURUSER;
   
   if (!$CURUSER)
        return;
   
   $userid = $CURUSER["id"];
   $res = DB::run("SELECT id, lastpost FROM forum_topics");
   while ($arr = $res->fetch(PDO::FETCH_ASSOC)) {
       $topicid = $arr["id"];
       $postid = $arr["lastpost"];
       $r = DB::run("SELECT id,lastpostread FROM forum_readposts WHERE userid=? and topicid=?", [$userid, $topicid]);
       if ($r->rowCount() == 0){
           DB::run("INSERT INTO forum_readposts (userid, topicid, lastpostread) VALUES(?, ?, ?), [$userid, $topicid, $postid]");
       }else{
           $a = $r->fetch(PDO::FETCH_ASSOC);
           if ($a["lastpostread"] < $postid)
               DB::run("UPDATE forum_readposts SET lastpostread=$postid WHERE id=?", [$a["id"]]);
       }
   }
}

// Returns the minimum read/write class levels of a forum
public function get_forum_access_levels($forumid){
   $res = DB::run("SELECT minclassread, minclasswrite FROM forum_forums WHERE id=?", [$forumid]);
   if ($res->rowCount() != 1)
       return false;
   $arr = $res->fetch(PDO::FETCH_ASSOC);
       return array("read" => $arr["minclassread"], "write" => $arr["minclasswrite"]);
}

// Returns the forum ID of a topic, or false on error
public function get_topic_forum($topicid) {
   $res = DB::run("SELECT forumid FROM forum_topics WHERE id=?", [$topicid]);
   if ($res->rowCount() != 1)
     return false;
   $arr = $res->fetch(PDO::FETCH_LAZY);
   return $arr[0];
}

// Returns the ID of the last post of a forum
public function update_topic_last_post($topicid) {
   $res = DB::run("SELECT id FROM forum_posts WHERE topicid=? ORDER BY id DESC LIMIT 1", [$topicid]);
   $arr = $res->fetch(PDO::FETCH_LAZY) or self::showerror(T_("FORUM_ERROR"), "No post found");
   $postid = $arr[0];
   DB::run("UPDATE forum_topics SET lastpost=? WHERE id=?", [$postid, $topicid]);
}

public function get_forum_last_post($forumid)  {
   $res = DB::run("SELECT lastpost FROM forum_topics WHERE forumid=? ORDER BY lastpost DESC LIMIT 1", [$forumid]);
   $arr = $res->fetch(PDO::FETCH_LAZY);
   $postid = $arr[0];
   if ($postid)
     return $postid;
   else
     return 0;

}

//Top forum posts

public function forumpostertable($res) {
   print("<br /><table class='f-topten' width='160' cellspacing='0'><tr><td>\n");
   print("<table class='ttable_headinner' width='100%'>");
   
   ?>

   <tr class='ttable_head'>
     <th width='10' align='center'>
     <font size='1'><?php echo T_("FORUM_RANK"); ?></font>
     </th>
     <th width='140' align='center'>
     <font size='1'><?php echo T_("FORUM_USER"); ?></font>
     </th>
     <th width='10' align='center'>
     <font size='1'><?php echo T_("FORUM_POST"); ?></font>
     </th>
   </tr>
   
   <?php

   $num = 0;
   while ($a = $res->fetch(PDO::FETCH_ASSOC))
   {
     ++$num;
     print("<tr class='t-row'><td align='center' class='ttable_col1'>$num</td><td class='ttable_col2' style='text-align: justify'><a href='account-details.php?id=$a[id]'><b>$a[username]</b></a></td><td align='center' class='ttable_col1'>$a[num]</td></tr>\n");
   }
   
   if ($num == 0)
   print("<tr class='t-row'><td align='center' class='ttable_col1' colspan='3'><b>No Forum Posters</b></td></tr>");
   
 print("</table>");
    print("</td></tr></table>\n");
}

// Inserts a quick jump menu
public function insert_quick_jump_menu($currentforum = 0) {
   print("<div style='text-align:right'><form method='get' action='?' name='jump'>\n");
   print("<input type='hidden' name='action' value='viewforum' />\n");
   $res = DB::run("SELECT * FROM forum_forums ORDER BY name");
 
   if ( $res->rowCount() > 0 )
   {
        print( T_("FORUM_JUMP") . ": ");
        print("<select class='styled' name='forumid' onchange='if(this.options[this.selectedIndex].value != -1){ forms[jump].submit() }'>\n");
 
        while ($arr = $res->fetch(PDO::FETCH_ASSOC))
        {
            if ((new Curuser)->get_user_class() >= $arr["minclassread"] || (!$CURUSER && $arr["guest_read"] == "yes"))
                print("<option value='" . $arr["id"] . "'" . ($currentforum == $arr["id"] ? " selected='selected'>" : ">") . $arr["name"] . "</option>\n");
        }
       
        print("</select>\n");
        print("<input type='submit' value='".T_("GO")."' />\n");
   }

  // print("<input type='submit' value='Go!'>\n");
   print("</form>\n</div>");
}

// Inserts a compose frame
public function insert_compose_frame($id, $newtopic = true) {
   global $maxsubjectlength;

   if ($newtopic) {
       $res = DB::run("SELECT name FROM forum_forums WHERE id=$id");
       $arr = $res->fetch(PDO::FETCH_ASSOC) or self::showerror(T_("FORUM_ERROR"), T_("FORUM_BAD_FORUM_ID"));
       $forumname = stripslashes($arr["name"]);

       print("<p align='center'><b>".T_("FORUM_NEW_TOPIC")." <a href='forums.php?action=viewforum&amp;forumid=$id'>$forumname</a></b></p>\n");
   }else{
       $res = DB::run("SELECT * FROM forum_topics WHERE id=$id");
       $arr = $res->fetch(PDO::FETCH_ASSOC) or self::showerror(T_("FORUM_ERROR"), T_("FORUMS_NOT_FOUND_TOPIC"));
       $subject = stripslashes($arr["subject"]);
       print("<p align='center'>".T_("FORUM_REPLY_TOPIC").": <a href='forums.php?action=viewtopic&amp;topicid=$id'>$subject</a></p>");
   }

   # Language Marker #
   print("<p align='center'>".T_("FORUM_RULES")."\n");
   print("<br />".T_("FORUM_RULES2")."<br /></p>\n");


 #begin_frame("Compose Message", true);
    print("<fieldset class='download'>");
    print("<legend><b>Compose Message</b></legend>");
    print("<div>");
   print("<form name='Form' method='post' action='?action=post'>\n");
   if ($newtopic)
     print("<input type='hidden' name='forumid' value='$id' />\n");
   else
     print("<input type='hidden' name='topicid' value='$id' />\n");

   if ($newtopic){
           print("<center><br /><table cellpadding='3' cellspacing='0'><tr><td><strong>Subject:</strong>  <input type='text' size='70' maxlength='$maxsubjectlength' name='subject' /></td></tr>");
           print("<tr><td align='center'>");
           textbbcode("Form", "body");
           print("</td></tr><tr><td align='center'><br /><input type='submit' value='".T_("SUBMIT")."' /><br /><br /></td></tr></table>
           ");
   
   }
   print("<br /></center>");
   print("</form>\n");
   print("</div>");
   print("</fieldset><br />");
   #end_frame();

   self::insert_quick_jump_menu();
}

//LASTEST FORUM POSTS
public function latestforumposts() {
print("<div class='f-border f-latestpost'><table width='100%' cellspacing='0'><tr class='f-title'>".
"<th align='left'  width=''>Latest Topic Title</th>".
"<th align='center' width='47'>Replies</th>".
"<th align='center' width='47'>Views</th>".
"<th align='center' width='85'>Author</th>".
"<th align='right' width='150'>Last Post</th>".
"</tr>");


/// HERE GOES THE QUERY TO RETRIEVE DATA FROM THE DATABASE AND WE START LOOPING ///
$for = DB::run("SELECT * FROM forum_topics ORDER BY lastpost DESC LIMIT 5");

if ($for->rowCount() == 0)
   print("<tr class='f-row'><td class='alt1' align='center' colspan='5'><b>No Latest Topics</b></td></tr>");

while ($topicarr = $for->fetch(PDO::FETCH_ASSOC)) {
// Set minclass
$res = DB::run("SELECT name,minclassread,guest_read FROM forum_forums WHERE id=$topicarr[forumid]");
$forum = $res->fetch(PDO::FETCH_ASSOC);

if ($forum && (new Curuser)->get_user_class() >= $forum["minclassread"] || $forum["guest_read"] == "yes") {
$forumname = "<a href='?action=viewforum&amp;forumid=$topicarr[forumid]'><b>" . htmlspecialchars($forum["name"]) . "</b></a>";

$topicid = $topicarr["id"];
$topic_title = stripslashes($topicarr["subject"]);
$topic_userid = $topicarr["userid"];
// Topic Views
$views = $topicarr["views"];
// End

/// GETTING TOTAL NUMBER OF POSTS ///
$res = DB::run("SELECT COUNT(*) FROM forum_posts WHERE topicid=?", [$topicid]);
$arr = $res->fetch(PDO::FETCH_LAZY);
$posts = $arr[0];
$replies = max(0, $posts - 1);

/// GETTING USERID AND DATE OF LAST POST ///  
$res = DB::run("SELECT * FROM forum_posts WHERE topicid=? ORDER BY id DESC LIMIT 1", [$topicid]);
$arr = $res->fetch(PDO::FETCH_ASSOC);
$postid = 0 + $arr["id"];
$userid = 0 + $arr["userid"];
$added = utc_to_tz($arr["added"]);

/// GET NAME OF LAST POSTER ///
$res = DB::run("SELECT id, username FROM users WHERE id=$userid");
if ($res->rowCount() == 1) {
$arr = $res->fetch(PDO::FETCH_ASSOC);
$username = "<a href='account-details.php?id=$userid'>".(new Curuser)->class_colour($arr['username'])."</a>";
}
else
$username = "Unknown[$topic_userid]";

/// GET NAME OF THE AUTHOR ///
$res = DB::run("SELECT username FROM users WHERE id=?", [$topic_userid]);
if ($res->rowCount() == 1) {
$arr = $res->fetch(PDO::FETCH_ASSOC);
$author = "<a href='account-details.php?id=$topic_userid'>".(new Curuser)->class_colour($arr['username'])."</a>";
}
else
$author = "Unknown[$topic_userid]";

/// GETTING THE LAST INFO AND MAKE THE TABLE ROWS ///
$r = DB::run("SELECT lastpostread FROM forum_readposts WHERE userid=$userid AND topicid=$topicid");
$a = $r->fetch(PDO::FETCH_LAZY);
$new = !$a || $postid > $a[0];
$subject = "<a href='forums.php?action=viewtopic&amp;topicid=$topicid'><b>" . stripslashes(encodehtml($topicarr["subject"])) . "</b></a>";

print("<tr class='f-row'><td class='f-img' width='100%'>$subject</td>".
"<td class='alt2' align='center'>$replies</td>" .
"<td class='alt3' align='center'>$views</td>" .
"<td class='alt2' align='center'>$author</td>" .
"<td class='alt3' align='right'><small>by&nbsp;$username<br /></small><small style='white-space: nowrap'>$added</small></td>");

print("</tr>");
} // while
}
print("</table></div><br />");
} // end function

}


forums.php
<?php
require_once("backend/init.php");
require_once("backend/bbcode.php");
dbconn();

// Set Forum class
$FORUMS = new Forum;
$GLOBALS["FORUMS"] = $FORUMS;

if (!$site_config["FORUMS_GUESTREAD"])
   (new Curuser)->loggedinonly();

$action = strip_tags($_REQUEST["action"]);
   
if (!$CURUSER && ($action == "newtopic" || $action == "post"))
   $FORUMS->showerror(T_("FORUM_ERROR"), T_("FORUM_NO_ID"));

if ($CURUSER["forumbanned"] == "yes" || $CURUSER["view_forum"] == "no")
   $FORUMS->showerror(T_("FORUM_BANNED"), T_("FORUM_BANNED"));

//Here we decide if the forums is on or off
if ($site_config["FORUMS"]) {
$themedir = "themes/".$THEME."/forums/";


//Global variables
$postsperpage = 20;
$maxsubjectlength = 50;

// change to class/controller
include("forums-actions.php");

///////////////////////////////////////////////////////// Action: DEFAULT ACTION (VIEW FORUMS)
if (isset($_GET["catchup"]))
   $FORUMS->catch_up();

///////////////////////////////////////////////////////// Action: SHOW MAIN FORUM INDEX
$forums_res = DB::run("SELECT forumcats.id AS fcid, forumcats.name AS fcname, forum_forums.* FROM forum_forums LEFT JOIN forumcats ON forumcats.id = forum_forums.category ORDER BY forumcats.sort, forum_forums.sort, forum_forums.name");

stdhead("Forums");
begin_frame("Forum Home");
$FORUMS->forumheader("Index");
$FORUMS->latestforumposts();

print("<div class='f-border f-forums'><table width='100%' cellspacing='0'>");// MAIN LAYOUT

print("<tr class='f-title'><th align='left' colspan='2'>Forum</th><th width='37' align='right'>Topics</th><th width='47' align='right'>Posts</th><th align='right' width='180'>Last post</th></tr>\n");// head of forum index

if ($forums_res->rowCount() == 0)
   print("<tr class='f-cat'><td colspan='5' align='center'>No Forum Categories</td></tr>\n");

$fcid = 0;

while ($forums_arr = $forums_res->fetch(PDO::FETCH_ASSOC)){
   
   if ((new Curuser)->get_user_class() < $forums_arr["minclassread"] && $forums_arr["guest_read"] == "no")
       continue;
       
   if ($forums_arr['fcid'] != $fcid) {// add forum cat headers
       print("<tr class='f-cat'><td colspan='5' align='center'>".htmlspecialchars($forums_arr['fcname'])."</td></tr>\n");

       $fcid = $forums_arr['fcid'];
   }

   $forumid = 0 + $forums_arr["id"];

   $forumname = htmlspecialchars($forums_arr["name"]);

   $forumdescription = htmlspecialchars($forums_arr["description"]);
   $postcount = number_format(get_row_count("forum_posts", "WHERE topicid IN (SELECT id FROM forum_topics WHERE forumid=$forumid)"));
   $topiccount = number_format(get_row_count("forum_topics", "WHERE forumid = $forumid"));


   // Find last post ID
   $lastpostid = $FORUMS->get_forum_last_post($forumid);

   // Get last post info
   $post_res = DB::run("SELECT added,topicid,userid FROM forum_posts WHERE id=$lastpostid");
   if ($post_res->rowCount() == 1) {
       $post_arr = $post_res->fetch(PDO::FETCH_ASSOC) or $FORUMS->showerror(T_("ERROR"), "Bad forum last_post");
       $lastposterid = $post_arr["userid"];
       $lastpostdate = utc_to_tz($post_arr["added"]);
       $lasttopicid = $post_arr["topicid"];
       $user_res = DB::run("SELECT username FROM users WHERE id=$lastposterid");
       $user_arr = $user_res->fetch(PDO::FETCH_ASSOC);
       $lastposter = (new Curuser)->class_colour($user_arr["username"]);
       $topic_res = DB::run("SELECT subject FROM forum_topics WHERE id=$lasttopicid");
       $topic_arr = $topic_res->fetch(PDO::FETCH_ASSOC);
       $lasttopic = stripslashes(htmlspecialchars($topic_arr['subject']));
       
       //cut last topic
       $latestleng = 10;

       $lastpost = "<small><a href='forums.php?action=viewtopic&amp;topicid=$lasttopicid&amp;page=last#last'>" . CutName($lasttopic, $latestleng) . "</a> by <a href='account-details.php?id=$lastposterid'>$lastposter</a><br />$lastpostdate</small>";


       if ($CURUSER) {
           $a = DB::run("SELECT lastpostread FROM forum_readposts WHERE userid=$CURUSER[id] AND topicid=$lasttopicid")->fetch();
       }

       //define the images for new posts or not on index
       if ($a && $a[0] == $lastpostid)
           $img = "folder";
       else
       $img = "folder_new";
   }else{
       $lastpost = "<span class='small'>No Posts</span>";
       $img = "folder";
   }
   //following line is each forums display
   print("<tr class='f-row'><td class='f-img'><img src='". $themedir ."$img.png' alt='' /></td><td align='left' width='100%' class='alt1'><a href='forums.php?action=viewforum&amp;forumid=$forumid'><b>$forumname</b></a><br />\n" .
   "<small>- $forumdescription</small></td><td class='alt2' align='center' width='40'>$topiccount</td><td class='alt3' align='center' width='40'>$postcount</td>" .
   "<td class='alt2' align='right' width='110'><small style='white-space: nowrap'>$lastpost</small></td></tr>\n");
}
print("</table></div>");
//forum Key
print("<table cellspacing='0' cellpadding='3'><tr valign='middle'>\n");
print("<td><img src='". $themedir ."folder_new.png' style='margin: 5px' alt='' /></td><td>New posts</td>\n");
print("<td><img src='". $themedir ."folder.png' style='margin: 5px' alt='' /></td><td>No New posts</td>\n");
print("<td><img src='". $themedir ."folder_locked.png' style='margin: 5px' alt='' /></td><td>".T_("FORUMS_LOCKED")." topic</td>\n");
print("<td><img src='". $themedir ."folder_sticky.png' style='margin: 5px' alt='' /></td><td>".T_("FORUMS_STICKY")." topic</td>\n");
print("</tr></table>\n");

//Top posters
$r = DB::run("SELECT users.id, users.username, COUNT(forum_posts.userid) as num FROM forum_posts LEFT JOIN users ON users.id = forum_posts.userid GROUP BY userid ORDER BY num DESC LIMIT 10");
$FORUMS->forumpostertable($r);

//topic count and post counts
$postcount = number_format(get_row_count("forum_posts"));
$topiccount = number_format(get_row_count("forum_topics"));
print("<br /><center>Our members have made " . $postcount . " posts in  " . $topiccount . " topics</center><br />");

$FORUMS->insert_quick_jump_menu();
end_frame();
stdfoot();

}else{//HEY IF FORUMS ARE OFF, SHOW THIS...
   $FORUMS->showerror("Notice", "Unfortunatley the forums are not currently available.");
}

?>


forum-action.php
<?php

//Action: New topic
if ($action == "newtopic") {
   $forumid = $_GET["forumid"];
   if (!is_valid_id($forumid))
   $FORUMS->showerror(T_("FORUM_ERROR"), "No Forum ID $forumid");

   stdhead("New topic");
   begin_frame("New topic");

   $FORUMS->forumheader("Compose New Thread");

   $FORUMS->insert_compose_frame($forumid);
   end_frame();
   stdfoot();
   die;
}

///////////////////////////////////////////////////////// Action: POST
if ($action == "post") {
   $forumid = $_POST["forumid"];
   $topicid = $_POST["topicid"];

   if (!is_valid_id($forumid) && !is_valid_id($topicid))
           $FORUMS->showerror(T_("FORUM_ERROR"), "w00t");
   $newtopic = $forumid > 0;
   $subject = $_POST["subject"];
   if ($newtopic) {
       if (!$subject)
           $FORUMS->showerror(T_("ERROR"), "You must enter a subject.");
       $subject = trim($subject);
       //if (!$subject)
           //$FORUMS->showerror(T_("ERROR"), "You must enter a subject.");
       //$FORUMS->showerror(T_("ERROR"), "Subject is limited to $maxsubjectlength characters.");
   }else{
     $forumid = $FORUMS->get_topic_forum($topicid) or $FORUMS->showerror(T_("FORUM_ERROR"),"Bad topic ID");
   }

   ////// Make sure sure user has write access in forum
   $arr = $FORUMS->get_forum_access_levels($forumid) or $FORUMS->showerror(T_("FORUM_ERROR"),"Bad forum ID");
   if ((new Curuser)->get_user_class() < $arr["write"])
       $FORUMS->showerror(T_("FORUM_ERROR"),T_("FORUMS_NOT_PERMIT"));
   $body = trim($_POST["body"]);
   if (!$body)
       $FORUMS->showerror(T_("ERROR"), "No body text.");
   $userid = $CURUSER["id"];

   if ($newtopic) { //Create topic
       $subject = $subject;
       DB::run("INSERT INTO forum_topics (userid, forumid, subject) VALUES(?,?,?)", [$userid, $forumid, $subject]);
       $topicid = DB::lastInsertId()or $FORUMS->showerror(T_("FORUM_ERROR"),"Topics id n/a");

   }else{
       //Make sure topic exists and is unlocked
       $res = DB::run("SELECT * FROM forum_topics WHERE id=?", [$topicid]);
       $arr = $res->fetch(PDO::FETCH_ASSOC) or $FORUMS->showerror(T_("FORUM_ERROR"),"Topic id n/a");
       if ($arr["locked"] == 'yes')
       $FORUMS->showerror(T_("FORUM_ERROR"),"Topic locked");
       //Get forum ID
       $forumid = $arr["forumid"];
   }

   //Insert the new post
   $added = "'" . get_date_time() . "'";
   $body = $body;
   DB::run("INSERT INTO forum_posts (topicid, userid, added, body) VALUES(?, ?, ?, ?)", [$topicid, $userid, get_date_time(), $body]);
   $postid = DB::lastInsertId() or $FORUMS->showerror(T_("FORUM_ERROR"),"Post id n/a");

   //Update topic last post
   $FORUMS->update_topic_last_post($topicid);

   //All done, redirect user to the post
   $headerstr = "Location: $site_config[SITEURL]/forums.php?action=viewtopic&topicid=$topicid&page=last";
   if ($newtopic)
       header($headerstr);
   else
       header("$headerstr#post$postid");
   die;
}

///////////////////////////////////////////////////////// Action: VIEW TOPIC
if ($action == "viewtopic") {
   $topicid = $_GET["topicid"];
   $page = $_GET["page"];

   if (!is_valid_id($topicid))
       $FORUMS->showerror(T_("FORUM_ERROR"),"Topic Not Valid");
   $userid = $CURUSER["id"];

   //------ Get topic info
   $res = DB::run("SELECT * FROM forum_topics WHERE id=?", [$topicid]);
   $arr = $res->fetch(PDO::FETCH_ASSOC) or $FORUMS->showerror(T_("FORUM_ERROR"), "Topic not found");
   $locked = ($arr["locked"] == 'yes');
   $subject = stripslashes($arr["subject"]);
   $sticky = $arr["sticky"] == "yes";
   $forumid = $arr["forumid"];
   
   // Check if user has access to this forum
   $res2 = DB::run("SELECT minclassread, guest_read FROM forum_forums WHERE id=?", [$forumid]);
   $arr2 = $res2->fetch(PDO::FETCH_ASSOC);
   if (!$arr2 || (new Curuser)->get_user_class() < $arr2["minclassread"] && $arr2["guest_read"] == "no")
       show_error_msg("Error: Access Denied","You do not have access to the forum this topic is in.");

   // Update Topic Views
   $viewsq = DB::run("SELECT views FROM forum_topics WHERE id=$topicid");
   $viewsa = $viewsq->fetch(PDO::FETCH_LAZY);
   $views = $viewsa[0];
   $new_views = $views+1;
   $uviews = DB::run("UPDATE forum_topics SET views = $new_views WHERE id=$topicid");
   // End

   //------ Get forum
   $res = DB::run("SELECT * FROM forum_forums WHERE id=?", [$forumid]);
   $arr = $res->fetch(PDO::FETCH_ASSOC) or $FORUMS->showerror(T_("FORUM_ERROR"), "Forum is empty");
   $forum = stripslashes($arr["name"]);

   //------ Get post count
   $res = DB::run("SELECT COUNT(*) FROM forum_posts WHERE topicid=?", [$topicid]);
   $arr = $res->fetch(PDO::FETCH_LAZY);
   $postcount = $arr[0];        

   //------ Make page menu
   $pagemenu = "<br /><small>\n";
   $perpage = $postsperpage;
   $pages = floor($postcount / $perpage);
   if ($pages * $perpage < $postcount)
       ++$pages;
   if ($page == "last")
       $page = $pages;
   else {
       if($page < 1)
           $page = 1;
       elseif ($page > $pages)
           $page = $pages;
   }
   $offset = max( 0, ( $page * $perpage ) - $perpage );
   
   //
   if ($page == 1)
     $pagemenu .= "<b>&lt;&lt; Prev</b>";
   else
     $pagemenu .= "<a href='forums.php?action=viewtopic&amp;topicid=$topicid&amp;page=" . ($page - 1) . "'><b>&lt;&lt; Prev</b></a>";
   //
   $pagemenu .= "&nbsp;&nbsp;";
       for ($i = 1; $i <= $pages; ++$i) {
     if ($i == $page)
       $pagemenu .= "<b>$i</b>\n";
     else
       $pagemenu .= "<a href='forums.php?action=viewtopic&amp;topicid=$topicid&amp;page=$i'><b>$i</b></a>\n";
   }
   //
   $pagemenu .= "&nbsp;&nbsp;";
   if ($page == $pages)
     $pagemenu .= "<b>Next &gt;&gt;</b><br /><br />\n";
   else
     $pagemenu .= "<a href='forums.php?action=viewtopic&amp;topicid=$topicid&amp;page=" . ($page + 1) . "'><b>Next &gt;&gt;</b></a><br /><br />\n";
   $pagemenu .= "</small>";
     
//Get topic posts
   $res = DB::run("SELECT * FROM forum_posts WHERE topicid=$topicid ORDER BY id LIMIT $offset,$perpage");
   stdhead("View Topic: $subject");
   begin_frame("$forum &gt; $subject");
   $FORUMS->forumheader("<a href='forums.php?action=viewforum&amp;forumid=$forumid'>$forum</a> <b style='font-size:16px; vertical-align:middle'>/</b> $subject");
   
   print ("<div style='padding: 6px'>");
   
   $levels = $FORUMS->get_forum_access_levels($forumid) or die;
   if ((new Curuser)->get_user_class() >= $levels["write"])
       $maypost = true;
   else
       $maypost = false;
   
   if (!$locked && $maypost){
       print ("<div align='right'><a href='#bottom'><img src='". $themedir ."button_reply.png' border='0' alt='' /></a></div>");
   }else{
       print ("<div align='right'><img src='" . $themedir . "button_locked.png'  alt='".T_("FORUMS_LOCKED")."' /></div>");
   }
   print ("</div>");

//------ Print table of posts
   $pc = $res->rowCount();
   $pn = 0;
   if ($CURUSER) {
       $r = DB::run("SELECT lastpostread FROM forum_readposts WHERE userid=? AND topicid=?", [$CURUSER['id'], $topicid]);
       $a = $r->fetch(PDO::FETCH_LAZY);
       $lpr = $a[0];
       if (!$lpr)
           DB::run("INSERT INTO forum_readposts (userid, topicid) VALUES($userid, $topicid)");
   }
   
   while ($arr = $res->fetch(PDO::FETCH_ASSOC)) {
       ++$pn;
       $postid = $arr["id"];
       $posterid = $arr["userid"];
       $added = utc_to_tz($arr["added"])."(" . (get_elapsed_time(sql_timestamp_to_unix_timestamp($arr["added"]))) . " ago)";

       //---- Get poster details
       $res4 = DB::run("SELECT COUNT(*) FROM forum_posts WHERE userid=?", [$posterid]);
       $arr33 = $res4->fetch(PDO::FETCH_LAZY);
       $forumposts = $arr33[0];

       $res2 = DB::run("SELECT * FROM users WHERE id=?", [$posterid]);
       $arr2 = $res2->fetch(PDO::FETCH_ASSOC);
       $postername = (new Curuser)->class_colour($arr2["username"]);

           if ($postername == "") {
               $by = "Deluser";
               $title = "Deleted Account";
               $privacylevel = "strong";
               $usersignature = "";
               $userdownloaded = "0";
               $useruploaded = "0";
               $avatar = "";
               $nposts = "-";
               $tposts = "-";
           }else{
               $avatar = htmlspecialchars($arr2["avatar"]);
               $userdownloaded = mksize($arr2["downloaded"]);
               $useruploaded = mksize($arr2["uploaded"]);
               $privacylevel = $arr2["privacy"];
               $usersignature = stripslashes(format_comment($arr2["signature"]));
                   if ($arr2["downloaded"] > 0) {
                       $userratio = number_format($arr2["uploaded"] / $arr2["downloaded"], 2);
                   }else
                       if ($arr2["uploaded"] > 0)
                           $userratio = "Inf.";
                       else
                           $userratio = "---";
       
                   if(!$arr2["country"]){
                       $usercountry = "unknown";
                   }else{
                       $res4 = DB::run("SELECT name,flagpic FROM countries WHERE id=? LIMIT 1", [$arr2['country']]);
                       $arr4 = $res4->fetch(PDO::FETCH_ASSOC);
                       $usercountry = $arr4["name"];
                   }

               $title = format_comment($arr2["title"]);
               $donated = $arr2['donated'];
               $by = "<a href='account-details.php?id=$posterid'>$postername</a>" . ($donated > 0 ? "<img src='".$site_config['SITEURL']."/images/star.png' alt='Donated' />" : "") . "";
           }

        if (!$avatar)
           $avatar = $site_config['SITEURL']."/images/default_avatar.png";
     # print("<a name=$postid>\n");
       print("<a id='post$postid'></a>");
       if ($pn == $pc) {
           print("<a name='last'></a>\n");
           if ($postid > $lpr && $CURUSER)
               DB::run("UPDATE forum_readposts SET lastpostread=$postid WHERE userid=? AND topicid=?", [$userid, $topicid]);
       }
//working here
//Post Top

       print("<div class='f-border f-post'><table width='100%' cellspacing='0'><tr class='p-title'><th width='150'>$by</th><th align='left'><small>Posted at $added </small></th></tr>");

//Post Middle

       $body = stripslashes(format_comment($arr["body"]));

       if (is_valid_id($arr['editedby'])) {
           $res2 = DB::run("SELECT username FROM users WHERE id=?", [$arr['editedby']]);

           if ($res2->rowCount() == 1) {
               $arr2 = $res2->fetch(PDO::FETCH_ASSOC);
               //edited by comment out if needed
               $body .= "<br /><br /><small><i>Last edited by <a href='account-details.php?id=$arr[editedby]'>$arr2[username]</b></a> on ".utc_to_tz($arr["editedat"])."</i></small><br />\n";
               $body .= "\n";
           }
       }

       $quote = htmlspecialchars($arr["body"]);

       $postcount1 = DB::run("SELECT COUNT(forum_posts.userid) FROM forum_posts WHERE id=$posterid") or forumsqlerr();

       while($row = $postcount1->fetch(PDO::FETCH_LAZY)) {

           if  ($privacylevel == "strong" && $CURUSER["control_panel"] != "yes"){//hide stats, but not from staff
               $useruploaded = "---";
               $userdownloaded = "---";
               $userratio = "---";
               $nposts = "-";
               $tposts = "-";
           }
           print ("<tr valign='top''><td width='150' align='left' class='comment-details'><center><i>$title</i></center><br /><center><img width='80' height='80' src='$avatar' alt='' /></center><br />Uploaded: $useruploaded<br />Downloaded: $userdownloaded<br />Posts: $forumposts<br /><br />Ratio: $userratio<br />Location: $usercountry<br /><br /></td>");

           print ("<td class='comment'><br />$body<br />");

           if (!$usersignature){
               print("<br /></td></tr>\n");
           }else{
               print("<br /><hr /><br /><div class='f-sig' align='center'>$usersignature</div></td></tr>\n");
           }
       }

//Post Bottom

   print("<tr class='p-foot'><td width='150' align='center'><a href='account-details.php?id=$posterid'><img src='".$themedir."icon_profile.png' border='0' alt='' /></a> <a href='mailbox.php?compose&amp;id=$posterid'><img src='".$themedir."icon_pm.png' border='0' alt='' /></a></td><td>");

   print ("<div style='float: left;'><a href='report.php?forumid=$topicid&amp;forumpost=$postid'><img src='".$themedir."p_report.png' border='0' alt='".T_("FORUMS_REPORT_POST")."' /></a>&nbsp;<a href='javascript:scroll(0,0);'><img src='".$themedir."p_up.png'  alt='".T_("FORUMS_GOTO_TOP_PAGE")."' /></a></div><div align='right'>");
   
   //define buttons and who can use them
   if ($CURUSER["id"] == $posterid || $CURUSER["edit_forum"] == "yes" || $CURUSER["delete_forum"] == "yes"){
       print ("<a href='forums.php?action=editpost&amp;postid=$postid'><img src='".$themedir."p_edit.png' border='0' alt='' /></a>&nbsp;");
   }
   if ($CURUSER["delete_forum"] == "yes"){
       print ("<a href='forums.php?action=deletepost&amp;postid=$postid&amp;sure=0'><img src='".$themedir."p_delete.png' border='0' alt='' /></a>&nbsp;");
   }
   if (!$locked && $maypost) {
       print ("<a href=\"javascript:SmileIT('
$postername:
$quote
', 'Form', 'body');\"><img src='".$themedir."p_quote.png' border='0' alt='' /></a>&nbsp;");
       print ("<a href='#bottom'><img src='".$themedir."p_reply.png' alt='' /></a>");
   }
       print("&nbsp;</div></td></tr></table></div>");
   }
//-------- end posts table ---------//
   print($pagemenu);

   //quick reply
   if (!$locked && $CURUSER){
   //begin_frame("Reply", $newtopic = false);
   print ("<fieldset class='download'><legend><b>".T_("FORUMS_POST_REPLY")."</b></legend>");
   $newtopic = false;
   print("<a name='bottom'></a>");
   print("<form name='Form' method='post' action='?action=post'>\n");
   if ($newtopic)
       print("<input type='hidden' name='forumid' value='$id' />\n");
   else
       print("<input type='hidden' name='topicid' value='$topicid' />\n");

   print("<table cellspacing='0' cellpadding='0' align='center'>");
   if ($newtopic)
       print("<tr><td class='alt2'>".T_("FORUMS_SUBJECT")."</td><td class='alt1' align='left' style='padding: 0px'><input type='text' size='100' maxlength='$maxsubjectlength' name='subject' style='border: 0px; height: 19px' /></td></tr>\n");

   echo "<tr><td align='center' colspan='3'>";
   textbbcode("Form", "body");
   echo "</td></tr>\n";
   print("<tr><td colspan='3' align='center'><br /><input type='image' src='". $themedir ."button_reply.png' alt='' /></td></tr>\n");
   print("</table></form>\n");
   //end_frame();
   print (" </fieldset>");
   }else{
   print ("<img src='".$themedir."button_locked.png' alt='".T_("FORUMS_LOCKED")."' /><br />");
   }
   //end quick reply

   if ($locked)
       print(T_("FORUMS_TOPIC_LOCKED")."\n");
   elseif (!$maypost)
       print("<i>".T_("FORUMS_YOU_NOT_PERM_POST_FORUM")."</i>\n");
   //insert page numbers and quick jump

  // $FORUMS->insert_quick_jump_menu($forumid);

   // MODERATOR OPTIONS
    if ($CURUSER["delete_forum"] == "yes" || $CURUSER["edit_forum"] == "yes") {
     print("<br /><div class='f-border f-mod_options' align='center'><table width='100%' cellspacing='0'><tr class='f-title'><th>".T_("FORUMS_MOD_OPTIONS")."</th></tr>\n");
    $res = DB::run("SELECT id,name,minclasswrite FROM forum_forums ORDER BY name");
     print("<tr><td class='ttable_col2'>\n");
     print("<form method='post' action='forums.php?action=renametopic'>\n");
     print("<input type='hidden' name='topicid' value='$topicid' />\n");
     print("<input type='hidden' name='returnto' value='forums.php?action=viewtopic&amp;topicid=$topicid' />\n");
     print("<div align='center'  style='padding:3px'>Rename topic: <input type='text' name='subject' size='60' maxlength='$maxsubjectlength' value='" . stripslashes(htmlspecialchars($subject)) . "' />\n");
     print("<input type='submit' value='Apply' />");
     print("</div></form>\n");
     print("<form method='post' action='forums.php?action=movetopic&amp;topicid=$topicid'>\n");
     print("<div align='center' style='padding:3px'>");
     print("Move this thread to: <select name='forumid'>");
     while ($arr = $res->fetch(PDO::FETCH_ASSOC))
       if ($arr["id"] != $forumid && (new Curuser)->get_user_class() >= $arr["minclasswrite"])
         print("<option value='" . $arr["id"] . "'>" . $arr["name"] . "</option>\n");
     print("</select> <input type='submit' value='Apply' /></div></form>\n");
print("<div align='center'>\n");
           if ($locked)
               print(T_("FORUMS_LOCKED").": <a href='forums.php?action=unlocktopic&amp;forumid=$forumid&amp;topicid=$topicid&amp;page=$page' title='Unlock'><img src='". $themedir ."topic_unlock.png' alt='UnLock Topic' /></a>\n");
           else
               print(T_("FORUMS_LOCKED").": <a href='forums.php?action=locktopic&amp;forumid=$forumid&amp;topicid=$topicid&amp;page=$page' title='Lock'><img src='". $themedir ."topic_lock.png' alt='Lock Topic' /></a>\n");
           print("Delete Entire Topic: <a href='forums.php?action=deletetopic&amp;topicid=$topicid&amp;sure=0' title='Delete'><img src='". $themedir ."topic_delete.png' alt='Delete Topic' /></a>\n");
           if ($sticky)
              print(T_("FORUMS_STICKY").": <a href='forums.php?action=unsetsticky&amp;forumid=$forumid&amp;topicid=$topicid&amp;page=$page' title='UnStick'><img src='". $themedir ."folder_sticky_new.png' alt='UnStick Topic' /></a>\n");
           else
              print(T_("FORUMS_STICKY").": <a href='forums.php?action=setsticky&amp;forumid=$forumid&amp;topicid=$topicid&amp;page=$page' title='Stick'><img src='". $themedir ."folder_sticky.png' alt='Stick Topic' /></a>\n");
           print("</div><br /></td></tr></table></div>\n");

   }
   end_frame();

   stdfoot();
   die;
}

///////////////////////////////////////////////////////// Action: REPLY
if ($action == "reply") {
   $topicid = $_GET["topicid"];
   if (!is_valid_id($topicid))
   $FORUMS->showerror(T_("FORUM_ERROR"), sprintf(T_("FORUMS_NO_ID_FORUM"), $topicid));
   stdhead(T_("FORUMS_POST_REPLY"));
   begin_frame(T_("FORUMS_POST_REPLY"));
   $FORUMS->insert_compose_frame($topicid, false);
   end_frame();
   stdfoot();
   die;
}

///////////////////////////////////////////////////////// Action: MOVE TOPIC
if ($action == "movetopic") {
   $forumid = $_POST["forumid"];
   $topicid = $_GET["topicid"];
   if (!is_valid_id($forumid) || !is_valid_id($topicid) || $CURUSER["delete_forum"] != "yes" || $CURUSER["edit_forum"] != "yes")
        $FORUMS->showerror(T_("FORUM_ERROR"), sprintf(T_("FORUMS_NO_ID_FORUM"),$forumid,$topicid));

   // Make sure topic and forum is valid
   $res = DB::run("SELECT minclasswrite FROM forum_forums WHERE id=?", [$forumid]);
   if ($res->rowCount() != 1)
     $FORUMS->showerror(T_("ERROR"), T_("FORUMS_NOT_FOUND"));
   $arr = $res->fetch(PDO::FETCH_LAZY);
   if ((new Curuser)->get_user_class() < $arr[0])
   $FORUMS->showerror(T_("FORUM_ERROR"), T_("FORUMS_NOT_ALLOWED"));
   $res = DB::run("SELECT subject,forumid FROM forum_topics WHERE id=?", [$topicid]);
   if ($res->rowCount() != 1)
     $FORUMS->showerror(T_("ERROR"), T_("FORUMS_NOT_FOUND_TOPIC"));
   $arr = $res->fetch(PDO::FETCH_ASSOC);
   if ($arr["forumid"] != $forumid)
       DB::run("UPDATE forum_topics SET forumid=$forumid, moved='yes' WHERE id=$topicid");

   // Redirect to forum page
   header("Location: $site_config[SITEURL]/forums.php?action=viewforum&forumid=$forumid");
   die;
}

///////////////////////////////////////////////////////// Action: DELETE TOPIC
if ($action == "deletetopic") {
   $topicid = $_GET["topicid"];
   if (!is_valid_id($topicid) || $CURUSER["delete_forum"] != "yes")
       $FORUMS->showerror(T_("ERROR"), T_("FORUMS_DENIED"));
   
   $sure = $_GET["sure"];
   if ($sure == "0")
       $FORUMS->showerror(T_("FORUMS_DEL_TOPIC"), sprintf(T_("FORUMS_DEL_TOPIC_SANITY_CHK"), $topicid));

   DB::run("DELETE FROM forum_topics WHERE id=?", [$topicid]);
   DB::run("DELETE FROM forum_posts WHERE topicid=?", [$topicid]);
   DB::run("DELETE FROM forum_readposts WHERE topicid=?", [$topicid]);
   header("Location: $site_config[SITEURL]/forums.php");
   die;
}

///////////////////////////////////////////////////////// Action: EDIT TOPIC
if ($action == "editpost") {
   $postid = $_GET["postid"];
   if (!is_valid_id($postid))
       $FORUMS->showerror(T_("ERROR"), T_("FORUMS_DENIED"));
   $res = DB::run("SELECT * FROM forum_posts WHERE id=?", [$postid]);
   if ($res->rowCount() != 1)
       $FORUMS->showerror(T_("ERROR"), sprintf(T_("FORUMS_NO_ID_POST"), $postid));
   $arr = $res->fetch(PDO::FETCH_ASSOC);
   if ($CURUSER["id"] != $arr["userid"] && $CURUSER["delete_forum"] != "yes" && $CURUSER["edit_forum"] != "yes")
       $FORUMS->showerror(T_("ERROR"), T_("FORUMS_DENIED"));

   if ($_SERVER['REQUEST_METHOD'] == 'POST') {
       $body = $_POST['body'];
           if ($body == "")
               $FORUMS->showerror(T_("ERROR"), "Body cannot be empty!");
       $body = $body;
       $editedat = get_date_time();
       DB::run("UPDATE forum_posts SET body=?, editedat=?, editedby=? WHERE id=?", [$body, $editedat, $CURUSER['id'], $postid]);
       $returnto = $_POST["returnto"];
           if ($returnto != "")
               header("Location: $returnto");
           else
               $FORUMS->showerror(T_("SUCCESS"), "Post was edited successfully.");
   }

   stdhead();

   begin_frame(T_("FORUMS_EDIT_POST"));
   print("<form name='Form' method='post' action='?action=editpost&amp;postid=$postid'>\n");
   print("<input type='hidden' name='returnto' value='" . htmlspecialchars($_SERVER["HTTP_REFERER"]) . "' />\n");
   print("<center><table  cellspacing='0' cellpadding='5'>\n");
   print("<tr><td colspan='2'>\n");
   textbbcode("Form", "body", htmlspecialchars($arr["body"]));
   print("</td></tr>");

   
   print("<tr><td align='center' colspan='2'><input type='submit' value='".T_("SUBMIT")."' /></td></tr>\n");
   print("</table></center>\n");
   print("</form>\n");
   end_frame();
   stdfoot();
   die;
}

///////////////////////////////////////////////////////// Action: DELETE POST
if ($action == "deletepost") {
   $postid = $_GET["postid"];
   $sure = $_GET["sure"];
   if ($CURUSER["delete_forum"] != "yes" || !is_valid_id($postid))
       $FORUMS->showerror(T_("ERROR"), T_("FORUMS_DENIED"));

   //SURE?
   if ($sure == "0") {
       $FORUMS->showerror(T_("FORUMS_DEL_POST"), sprintf(T_("FORUMS_DEL_POST_SANITY_CHK"), $postid));
   }

   //------- Get topic id
   $res = DB::run("SELECT topicid FROM forum_posts WHERE id=?", [$postid]);
   $arr = $res->fetch(PDO::FETCH_LAZY) or $FORUMS->showerror(T_("ERROR"), T_("FORUMS_NOT_FOUND_POST"));
   $topicid = $arr[0];

   //------- We can not delete the post if it is the only one of the topic
   $res = DB::run("SELECT COUNT(*) FROM forum_posts WHERE topicid=?", [$topicid]);
   $arr =$res->fetch(PDO::FETCH_LAZY);
   if ($arr[0] < 2)
       $FORUMS->showerror(T_("ERROR"), sprintf(T_("FORUMS_DEL_POST_ONLY_POST"), $topicid));

   //------- Delete post
   DB::run("DELETE FROM forum_posts WHERE id=?", [$postid]);

   //------- Update topic
   $FORUMS->update_topic_last_post($topicid);
   header("Location: $site_config[SITEURL]/forums.php?action=viewtopic&topicid=$topicid");
   die;
}

///////////////////////////////////////////////////////// Action: LOCK TOPIC
if ($action == "locktopic") {
   $forumid = $_GET["forumid"];
   $topicid = $_GET["topicid"];
   $page = $_GET["page"];
   if (!is_valid_id($topicid) || $CURUSER["delete_forum"] != "yes" || $CURUSER["edit_forum"] != "yes")
       $FORUMS->showerror(T_("ERROR"), T_("FORUMS_DENIED"));
       DB::run("UPDATE forum_topics SET locked='yes' WHERE id=$topicid");
       header("Location: $site_config[SITEURL]/forums.php?action=viewforum&forumid=$forumid&page=$page");
   die;
}

///////////////////////////////////////////////////////// Action: UNLOCK TOPIC
if ($action == "unlocktopic") {
   $forumid = $_GET["forumid"];
   $topicid = $_GET["topicid"];
   $page = $_GET["page"];
   if (!is_valid_id($topicid) || $CURUSER["delete_forum"] != "yes" || $CURUSER["edit_forum"] != "yes")
       $FORUMS->showerror(T_("ERROR"), T_("FORUMS_DENIED"));
       DB::run("UPDATE forum_topics SET locked='no' WHERE id=$topicid");
       header("Location: $site_config[SITEURL]/forums.php?action=viewforum&forumid=$forumid&page=$page");
   die;
}

///////////////////////////////////////////////////////// Action: STICK TOPIC
if ($action == "setsticky") {
  $forumid = $_GET["forumid"];
  $topicid = $_GET["topicid"];
  $page = $_GET["page"];
  if (!is_valid_id($topicid) || ($CURUSER["delete_forum"] != "yes" && $CURUSER["edit_forum"] != "yes"))
       $FORUMS->showerror(T_("ERROR"), T_("FORUMS_DENIED"));
       DB::run("UPDATE forum_topics SET sticky='yes' WHERE id=$topicid");
       header("Location: $site_config[SITEURL]/forums.php?action=viewforum&forumid=$forumid&page=$page");
  die;
}

///////////////////////////////////////////////////////// Action: UNSTICK TOPIC
if ($action == "unsetsticky") {
  $forumid = $_GET["forumid"];
  $topicid = $_GET["topicid"];
  $page = $_GET["page"];
  if (!is_valid_id($topicid) || ($CURUSER["delete_forum"] != "yes" && $CURUSER["edit_forum"] != "yes"))
       $FORUMS->showerror(T_("ERROR"), T_("FORUMS_DENIED"));
       DB::run("UPDATE forum_topics SET sticky='no' WHERE id=$topicid");
       header("Location: $site_config[SITEURL]/forums.php?action=viewforum&forumid=$forumid&page=$page");
  die;
}

///////////////////////////////////////////////////////// Action: RENAME TOPIC
if ($action == 'renametopic') {
   if ($CURUSER["delete_forum"] != "yes" && $CURUSER["edit_forum"] != "yes")
       $FORUMS->showerror(T_("ERROR"), T_("FORUMS_DENIED"));
     $topicid = $_POST['topicid'];
     if (!is_valid_id($topicid))
       $FORUMS->showerror(T_("ERROR"), T_("FORUMS_DENIED"));
     $subject = $_POST['subject'];
    if ($subject == '')
       $FORUMS->showerror(T_("ERROR"), T_("FORUMS_YOU_MUST_ENTER_NEW_TITLE"));
     $subject = $subject;
   DB::run("UPDATE forum_topics SET subject=$subject WHERE id=$topicid");
     $returnto = $_POST['returnto'];
     if ($returnto)
       header("Location: $returnto");
     die;
}

///////////////////////////////////////////////////////// Action: VIEW FORUM
if ($action == "viewforum") {
   $forumid = $_GET["forumid"];
   if (!is_valid_id($forumid))
       $FORUMS->showerror(T_("ERROR"), T_("FORUMS_DENIED"));
       $page = $_GET["page"];
       $userid = $CURUSER["id"];

   //------ Get forum name
   $res = DB::run("SELECT name, minclassread, guest_read FROM forum_forums WHERE id=?", [$forumid]);
   $arr = $res->fetch(PDO::FETCH_ASSOC);
   $forumname = $arr["name"];
   if (!$forumname || (new Curuser)->get_user_class() < $arr["minclassread"] && $arr["guest_read"] == "no")
       $FORUMS->showerror(T_("ERROR"), T_("FORUMS_NOT_PERMIT"));

   //------ Get topic count
   $perpage = 20;
   $res = DB::run("SELECT COUNT(*) FROM forum_topics WHERE forumid=$forumid");
   $arr = $res->fetch(PDO::FETCH_LAZY);
   $num = $arr[0];
   
//    $num = DB::run("SELECT COUNT(*) FROM forum_topics WHERE forumid=$forumid")->fetchColumn();
   
   if ($page == 0)
     $page = 1;
   $first = ($page * $perpage) - $perpage + 1;
   $last = $first + $perpage - 1;
   if ($last > $num)
     $last = $num;
   $pages = floor($num / $perpage);
   if ($perpage * $pages < $num)
     ++$pages;

   //------ Build menu
   $menu = "<p align='center'><b>\n";
   $lastspace = false;
   for ($i = 1; $i <= $pages; ++$i) {
     if ($i == $page)
       $menu .= "<span class='next-prev'>$i</span>\n";
     elseif ($i > 3 && ($i < $pages - 2) && ($page - $i > 3 || $i - $page > 3)) {
       if ($lastspace)
         continue;
          $menu .= "... \n";
       $lastspace = true;
     }
     else {
       $menu .= "<a href='forums.php?action=viewforum&amp;forumid=$forumid&amp;page=$i'>$i</a>\n";
       $lastspace = false;
     }
     if ($i < $pages)
       $menu .= "</b>|<b>\n";
   }
   $menu .= "<br />\n";
   if ($page == 1)
     $menu .= "<span class='next-prev'>&lt;&lt; Prev</span>";
   else
     $menu .= "<a href='forums.php?action=viewforum&amp;forumid=$forumid&amp;page=" . ($page - 1) . "'>&lt;&lt; Prev</a>";
   $menu .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
   if ($last == $num)
     $menu .= "<span class='next-prev'>Next &gt;&gt;</span>";
   else
     $menu .= "<a href='forums.php?action=viewforum&amp;forumid=$forumid&page=" . ($page + 1) . "'>Next &gt;&gt;</a>";
   $menu .= "</b></p>\n";
   $offset = $first - 1;

   //------ Get topics data and display category
   $topicsres = DB::run("SELECT * FROM forum_topics WHERE forumid=$forumid ORDER BY sticky, lastpost DESC LIMIT $offset,$perpage")->fetchAll();

   stdhead("Forum : $forumname");
 //  $numtopics = $topicsres->fetch(PDO::FETCH_LAZY);
   begin_frame("$forumname");
   $FORUMS->forumheader("<a href='forums.php?action=viewforum&amp;forumid=$forumid'>$forumname</a>");
   
   if ($CURUSER)
       print ("<table cellpadding='0' cellspacing='5' width='100%'><tr><td><div align='right'><a href='forums.php?action=newtopic&amp;forumid=$forumid'><img src='". $themedir. "button_new_post.png' alt='' /></a></div></td></tr></table>");

   if ($topicsres > 0) {
   print("<div class='f-border f-sub_forum'> <table width='100%' cellspacing='0'>");

   print("<tr class='f-title'><th align='left' colspan='2' width='100%'>Topic</th><th>Replies</th><th>Views</th><th>Author</th><th align='right'>Last post</th>\n");
       if ($CURUSER["edit_forum"] == "yes" || $CURUSER["delete_forum"] == "yes")
           print("<th>Moderator</th>");
     print("</tr>\n");
     foreach ($topicsres as $topicarr) {
           $topicid = $topicarr["id"];
           $topic_userid = $topicarr["userid"];
           $locked = $topicarr["locked"] == "yes";
           $moved = $topicarr["moved"] == "yes";
           $sticky = $topicarr["sticky"] == "yes";
           //---- Get reply count
           $res = DB::run("SELECT COUNT(*) FROM forum_posts WHERE topicid=$topicid");
           $arr = $res->fetch(PDO::FETCH_LAZY);
           $posts = $arr[0];
           $replies = max(0, $posts - 1);
           $tpages = floor($posts / $postsperpage);
           if ($tpages * $postsperpage != $posts)
             ++$tpages;
           if ($tpages > 1) {
             $topicpages = " (<img src='". $site_config['SITEURL'] ."/images/forum/multipage.png' alt='' />";
             for ($i = 1; $i <= $tpages; ++$i)
               $topicpages .= " <a href='forums.php?action=viewtopic&amp;topicid=$topicid&amp;page=$i'>$i</a>";
             $topicpages .= ")";
       }
       else
         $topicpages = "";

       //---- Get userID and date of last post
       $res = DB::run("SELECT * FROM forum_posts WHERE topicid=$topicid ORDER BY id DESC LIMIT 1");
       $arr = $res->fetch(PDO::FETCH_ASSOC);
       $lppostid = $arr["id"];
       $lpuserid = ( int ) $arr["userid"];
       $lpadded = utc_to_tz($arr["added"]);

       //------ Get name of last poster
       if ($lpuserid > 0) {
       $res = DB::run("SELECT * FROM users WHERE id=$lpuserid");
       if ($res->rowCount() == 1) {
         $arr = $res->fetch(PDO::FETCH_ASSOC);
         $lpusername = "<a href='account-details.php?id=$lpuserid'>".(new Curuser)->class_colour($arr['username'])."</a>";
       }
       else
         $lpusername = "Deluser";
       }
       else
         $lpusername = "Deluser";

       //------ Get author
       if ($topic_userid > 0) {
       $res = DB::run("SELECT username FROM users WHERE id=$topic_userid");
       if ($res->rowCount() == 1) {
         $arr = $res->fetch(PDO::FETCH_ASSOC);
         $lpauthor = "<a href='account-details.php?id=$topic_userid'>".(new Curuser)->class_colour($arr['username'])."</a>";
       }
       else
         $lpauthor = "Deluser";
       }
       else
         $lpauthor = "Deluser";

       // Topic Views
       $viewsq = DB::run("SELECT views FROM forum_topics WHERE id=$topicid");
       $viewsa = $viewsq->fetch(PDO::FETCH_LAZY);
       $views = $viewsa[0];
       // End

       //---- Print row
       if ($CURUSER) {
           $r = DB::run("SELECT lastpostread FROM forum_readposts WHERE userid=$userid AND topicid=$topicid");
           $a = $r->fetch(PDO::FETCH_LAZY);
       }
       $new = !$a || $lppostid > $a[0];
       $topicpic = ($locked ? ($new ? "folder_locked_new" : "folder_locked") : ($new ? "folder_new" : "folder"));
       $subject = ($sticky ? "<b>".T_("FORUMS_STICKY").": </b>" : "") . "<a href='forums.php?action=viewtopic&amp;topicid=$topicid'><b>" .
       encodehtml(stripslashes($topicarr["subject"])) . "</b></a>$topicpages";
       print("<tr class='f-row'><td class='f-img' valign='middle'><img src='". $themedir ."$topicpic.png' alt='' />" .
        "</td><td class='alt1' align='left' width='100%'>\n" .
        "$subject</td><td class='alt2' align='center'>$replies</td>\n" .
        "<td class='alt3' align='center'>$views</td>\n" .
        "<td class='alt2' align='center'>$lpauthor</td>\n" .
        "<td class='alt3' align='right'><span class='small'>by&nbsp;$lpusername<br /><span style='white-space: nowrap'>$lpadded</span></span></td>\n");
        if ($CURUSER["edit_forum"] == "yes" || $CURUSER["delete_forum"] == "yes") {
             print("<td class='alt2' align='center'><span style='white-space: nowrap'>\n");
           if ($locked)
               print("<a href='forums.php?action=unlocktopic&amp;forumid=$forumid&amp;topicid=$topicid&amp;page=$page' title='Unlock'><img src='". $themedir ."topic_unlock.png' alt='UnLock Topic' /></a>\n");
           else
               print("<a href='forums.php?action=locktopic&amp;forumid=$forumid&amp;topicid=$topicid&amp;page=$page' title='Lock'><img src='". $themedir ."topic_lock.png' alt='Lock Topic' /></a>\n");
               print("<a href='forums.php?action=deletetopic&amp;topicid=$topicid&amp;sure=0' title='Delete'><img src='". $themedir ."topic_delete.png' alt='Delete Topic' /></a>\n");
           if ($sticky)
              print("<a href='forums.php?action=unsetsticky&amp;forumid=$forumid&amp;topicid=$topicid&amp;page=$page' title='UnStick'><img src='". $themedir ."folder_sticky_new.png' alt='Unstick Topic' /></a>\n");
           else
              print("<a href='forums.php?action=setsticky&amp;forumid=$forumid&amp;topicid=$topicid&amp;page=$page' title='Stick'><img src='". $themedir ."folder_sticky.png' alt='Stick Topic' /></a>\n");
             print("</span></td>\n");
       }
       print("</tr>\n");
     } // while
  //   end_table();
  print("</table></div>");
     print($menu);
   } // if
   else
     print("<p align='center'>No topics found</p>\n");
   print("<table cellspacing='5' cellpadding='0'><tr valign='middle'>\n");
   print("<td><img src='". $themedir ."folder_new.png' style='margin-right: 5px' alt='' /></td><td >New posts</td>\n");
    print("<td><img src='". $themedir ."folder.png' style='margin-left: 10px; margin-right: 5px' alt='' />" .
    "</td><td>No New posts</td>\n");
   print("<td><img src='". $themedir ."folder_locked.png' style='margin-left: 10px; margin-right: 5px' alt='' />" .
    "</td><td>".T_("FORUMS_LOCKED")." topic</td></tr></table>\n");
   $arr = $FORUMS->get_forum_access_levels($forumid) or die;
   $maypost = (new Curuser)->get_user_class() >= $arr["write"];
   if (!$maypost)
       print("<p><i>".T_("FORUMS_YOU_NOT_PERM_POST_FORUM")."</i></p>\n");
   print("<table cellspacing='0' cellpadding='0'><tr>\n");

   if ($maypost)
       print("<td><a href='forums.php?action=newtopic&amp;forumid=$forumid'><img src='" . $themedir . "button_new_post.png' alt='' /></a></td>\n");
   print("</tr></table>\n");
   $FORUMS->insert_quick_jump_menu($forumid);
   end_frame();
   stdfoot();
   die;
}

///////////////////////////////////////////////////////// Action: VIEW NEW POSTS
if ($action == "viewunread") {
   $userid = $CURUSER['id'];
   $maxresults = 25;
   $res = DB::run("SELECT id, forumid, subject, lastpost FROM forum_topics ORDER BY lastpost");
   stdhead();
   begin_frame("Topics with unread posts");
   $FORUMS->forumheader("New Topics");

   $n = 0;
   $uc = (new Curuser)->get_user_class();
   while ($arr = $res->fetch(PDO::FETCH_ASSOC)) {
     $topicid = $arr['id'];
     $forumid = $arr['forumid'];

     //---- Check if post is read
     if ($CURUSER) {
       $a = DB::run("SELECT lastpostread FROM forum_readposts WHERE userid=$userid AND topicid=$topicid")->fetch();
     }
     if ($a && $a[0] == $arr['lastpost'])
       continue;

     //---- Check access & get forum name
     $a = DB::run("SELECT name, minclassread, guest_read FROM forum_forums WHERE id=$forumid")->fetch();
     if ($uc < $a['minclassread'] && $a["guest_read"] == "no")
       continue;
     ++$n;
     if ($n > $maxresults)
       break;
     $forumname = $a['name'];
     if ($n == 1) {
       print("<div class='f-border f-unread'><table width='100%' cellspacing='0'>\n");
       print("<tr class='f-title'><th align='left'>Topic</th><th align='left' colspan='2'>Forum</th></tr>\n");
     }
     print("<tr class='f-row'><td class='f-img' valign='middle'>" .
      "<img src='". $themedir ."folder_unlocked_new.png' style='margin: 5px' alt='' /></td><td class='alt1'>" .
      "<a href='forums.php?action=viewtopic&amp;topicid=$topicid&amp;page=last#last'><b>" . stripslashes(htmlspecialchars($arr["subject"])) ."</b></a></td><td class='alt2' align='left'><a href='forums.php?action=viewforum&amp;forumid=$forumid'><b>$forumname</b></a></td></tr>\n");
   }
   if ($n > 0) {
     print("</table></div><br />\n");
     if ($n > $maxresults)
       print("<p>More than $maxresults items found, displaying first $maxresults.</p>\n");
     print("<center><a href='forums.php?catchup'><b>Mark All Forums Read.</b></a></center><br />\n");
   }
   else
     print("<b>Nothing found</b>");
    end_frame();
   stdfoot();
   die;
}

///////////////////////////////////////////////////////// Action: SEARCH
if ($action == "search") {
   stdhead("Forum Search");
   begin_frame("Search Forum");
   $FORUMS->forumheader("Search Forums");
           
   $keywords = trim($_GET["keywords"]);
   
   if ($keywords != ""){
       print("<p>Search Phrase: <b>" . htmlspecialchars($keywords) . "</b></p>\n");
       $maxresults = 50;
       $ekeywords = $keywords;

       $res = "SELECT forum_posts.topicid, forum_posts.userid, forum_posts.id, forum_posts.added,
               MATCH ( forum_posts.body ) AGAINST ( ". $ekeywords ." ) AS relevancy
               FROM forum_posts
               WHERE MATCH ( forum_posts.body ) AGAINST ( ". $ekeywords ." IN BOOLEAN MODE )
               ORDER BY relevancy DESC";
       
       $res = DB::run($res);
       // search and display results...
       $num = $res->rowCount();

       if ($num > $maxresults) {
           $num = $maxresults;
           print("<p>Found more than $maxresults posts; displaying first $num.</p>\n");
       }
       
       if ($num == 0)
           print("<p><b>Sorry, nothing found!</b></p>");
       else {
           print("<p><center><div class='f-border f-srch_results'><table width='100%' cellspacing='0'>\n");
           print("<tr class='f-title'><th>Post ID</th><th align='left'>Topic</th><th align='left'>Forum</th><th align='left'>Posted by</th></tr>\n");

           for ($i = 0; $i < $num; ++$i){
               $post = $res->fetch(PDO::FETCH_ASSOC);

               $res2 = DB::run("SELECT forumid, subject FROM forum_topics WHERE id=$post[topicid]");
               $topic = $res2->fetch(PDO::FETCH_ASSOC);

               $res2 = DB::run("SELECT name,minclassread, guest_read FROM forum_forums WHERE id=$topic[forumid]");
               $forum = $res2->fetch(PDO::FETCH_ASSOC);

               if ($forum["name"] == "" || ($forum["minclassread"] > $CURUSER["class"] && $forum["guest_read"] == "no"))
                   continue;
               
               $res2 = DB::run("SELECT username FROM users WHERE id=$post[userid]");
               $user = $res2->fetch(PDO::FETCH_ASSOC);
               if ($user["username"] == "")
                   $user["username"] = "Deluser";
               print("<tr class='f-row'><td>$post[id]</td><td align='left'><a href='forums.php?action=viewtopic&amp;topicid=$post[topicid]#post$post[id]'><b>" . htmlspecialchars($topic["subject"]) . "</b></a></td><td align='left'><a href='forums.php?action=viewforum&amp;forumid=$topic[forumid]'><b>" . htmlspecialchars($forum["name"]) . "</b></a></td><td align='left'><a href='account-details.php?id=$post[userid]'><b>$user[username]</b></a><br />at ".utc_to_tz($post["added"])."</td></tr>\n");
           }
           print("</table></div></center></p>\n");
           print("<p><b>Search again</b></p>\n");
       }
   }

   print("<center><form method='get' action='?'>\n");
   print("<input type='hidden' name='action' value='search' />\n");
   print("<table cellspacing='0' cellpadding='5'>\n");
   print("<tr><td valign='bottom' align='right'>Search For: </td><td align='left'><input type='text' size='40' name='keywords' /><br /></td></tr>\n");
   print("<tr><td colspan='2' align='center'><input type='submit' value='Search' /></td></tr>\n");
   print("</table>\n</form></center>\n");
   end_frame();
   stdfoot();
   die;
}

///////////////////////////////////////////////////////// Action: UNKNOWN
if ($action != "")
   $FORUMS->showerror("Forum Error", "Unknown action '$action'.");

?>
2020-03-23 06:42:37
I would personally scrap forums.php altogether, its a complete mess by god is it outdated. Getting pretty close to running with MyBB...
2020-03-23 09:28:28
I did think about replacing it with a blog but I'd like to keep all TT functionality in core php and I haven't been able to find that many examples of pdo oop forums might look for a few videos on YouTube
Stuff like forumheader function that should be template, action unset sticky could just be a button. the code is there but like you say needs a major revamp
Unknown User
2020-03-23 10:10:15
[USER=20288]@m-jay[/USER], warning are shown because of undefined stuff.

You can't go like this for example because it will throw an warning and we should NOT supress warnings.

foreach ($stmt as $row)
{
  $random = $row['username'];
}

Should be:

$random = '';
foreach ($stmt as $row)
{
  $random = $row['username'];
}


You must either check in every file if curuser is set

if (isset($CURUSER) && $CURUSER['class'] === 1)

or

$GLOBALS['CURUSER'] = (isset($CURUSER) ? $CURUSER : null);
Users online

No users online

Search



Statistics

    Torrents

  • Tracking: 3
  • Todays torrents: 0
  • Seeders: 0
  • Leechers: 0
  • Peers: 0
  • Downloaded: 89.96 GB
  • Uploaded: 9.86 GB

  • Members

  • We have: 838
  • New today: 0
  • Guest today: 9

  • Online

  • Total online: 1
  • Members: 0
  • Guests online: 1
  • Comments: 3
  • Messages: 1,728