<?php
require_once 'includes/config.php';
require_once 'DB.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/lib/Smarty-2.6.9/libs/Smarty.class.php';

$base_url  = 'http://forums.htmlcenter.com';
$error_msg = array();
$internal  = array(9,19,21,23);

$smarty = new Smarty;

$smarty->template_dir   = $_SERVER['DOCUMENT_ROOT'].'/share/templates';
$smarty->compile_dir    = '../write';
$smarty->cache_dir      = '../cache';
$smarty->debugging      = false;
$smarty->caching        = true;
$smarty->cache_lifetime = 300;

if(!$smarty->is_cached('htmlcforumsrss.tpl')){

    $dsn = sprintf(
            '%s://%s:%s@%s/%s',
            $config['Database']['dbtype'],
            $config['MasterServer']['username'],
            $config['MasterServer']['password'],
            $config['MasterServer']['servername'],
            $config['Database']['dbname']
            );

    if(DB::isError($db =& DB::connect($dsn))){
        $error_msg[] = $db->getMessage();
    }
    $query = sprintf(
            "
            SELECT
            thread.threadid AS threadID,
            thread.title as threadTITLE,
            FROM_UNIXTIME(thread.lastpost, '%%m/%%d/%%Y') AS post_date,
            thread.lastposter,
            thread.replycount,
            forum.forumid,
            forum.title AS forumTITLE
            FROM thread, forum
            WHERE 1
            AND thread.forumid=forum.forumid
            AND open = 1
            AND visible = 1
            AND sticky = 0
            AND thread.forumid NOT IN(%s)
            ORDER BY dateline DESC
            LIMIT 10
            ",
            implode(', ', $internal)
            );
    $threads = array();
    if(DB::isError($rawdb = $db->query($query))){
        print $error_msg[] = $rawdb->getDebugInfo();
    }else{
        if($rawdb->numRows() > 0){
            while($row =& $rawdb->fetchRow(DB_FETCHMODE_ASSOC)){
                if($row['replycount'] > 0){
                    $query_sub = sprintf(
                                        "SELECT pagetext FROM post WHERE threadid = %s ORDER BY dateline DESC LIMIT 1",
                                        $row['threadID']
                                        );
                    if(!DB::isError($res_sub = $db->query($query_sub)) && $res_sub->numRows() > 0){
                        $row_sub =& $res_sub->fetchRow();
                        $row['pagetext'] = $row_sub[0];
                        $res_sub->free();
                    }
                }else{
                    $row['pagetext'] = 'Unanswered. Help now!';
                }
                $threads[] = $row;
            }
        }
        $rawdb->free();
    }

    $smarty->assign('threads', $threads);
    $smarty->assign('base_url', $base_url);

}
header('Content-Type:text/xml;charset=utf-8');
$smarty->display('htmlcforumsrss.tpl');
?>
