<?php
// $Id: functions.php,v 1.2 2004/07/19 20:34:53 Farsus Exp $
// -------------------------------------------------------------------------//
//			       RUNCMS
//
//	 Relaible - Unique - Nocost &  Simplicity & ease off use
//                       < http://www.runcms.org >
// -------------------------------------------------------------------------//
// Based on:
// phpBB: http://www.phpBB.com
// License type: GPL
// ------------------------------------------------------------------------- //

if ( !defined('NEWBBPLUS_FUNCTIONS_INCLUDED') ) {
	define('NEWBBPLUS_FUNCTIONS_INCLUDED', 1);

//---------------------------------------------------------------------------------------//
/**
* Gets the total number of topics in a form
*
* @param type $var description
* @return type description
*/
function get_total_topics($forum_id="") {
global $db, $bbTable;

if ($forum_id) {
	$sql = "SELECT COUNT(*) AS total FROM ".$bbTable['topics']." WHERE forum_id = '$forum_id'";
	} else {
		$sql = "SELECT COUNT(*) AS total FROM ".$bbTable['topics'];
	}

if (!$result = $db->query($sql)) {
	return(_ERROR);
}

if (!$myrow = $db->fetch_array($result)) {
	return(_ERROR);
}

return($myrow['total']);
}

//---------------------------------------------------------------------------------------//
/**
* Returns the total number of posts in the whole system, a forum, or a topic
* Also can return the number of users on the system.
*
* @param type $var description
* @return type description
*/
function get_total_posts($id, $type) {
global $db, $bbTable;

switch($type) {
case 'users':
	$sql = "SELECT COUNT(*) AS total FROM ".$db->prefix("users")." u WHERE (u.uid != 0) AND (level != -1)";
	break;

case 'all':
	$sql = "SELECT COUNT(*) AS total FROM ".$bbTable['posts']."";
	break;

case 'forum':
	$sql = "SELECT COUNT(*) AS total FROM ".$bbTable['posts']." WHERE forum_id = '$id'";
	break;

case 'topic':
	$sql = "SELECT COUNT(*) AS total FROM ".$bbTable['posts']." WHERE topic_id = '$id'";
	break;

// Old, we should never get this.
case 'user':
	die("Should be using the users.user_posts column for this.");
	break;
}

if (!$result = $db->query($sql)) {
	return("ERROR");
}

if (!$myrow = $db->fetch_array($result)) {
	return("0");
}

return($myrow['total']);
}

//---------------------------------------------------------------------------------------//
/**
* Returns the most recent post in a forum, or a topic
*
* @param type $var description
* @return type description
*/
function get_last_post($id, $type) {
global $db, $bbTable;

switch($type) {
case 'time_fix':
	$sql = "SELECT p.post_time FROM ".$bbTable['posts']." p WHERE p.topic_id = '$id' ORDER BY post_time DESC";
	break;

case 'forum':
	$sql = "SELECT p.post_time, p.uid, u.uname FROM ".$bbTable['posts']." p, ".$db->prefix("users")." u WHERE p.forum_id = '$id' AND p.uid = u.uid ORDER BY post_time DESC";
	break;

case 'topic':
	$sql = "SELECT p.post_time, u.uname FROM ".$bbTable['posts']." p, ".$db->prefix("users")." u WHERE p.topic_id = '$id' AND p.uid = u.uid ORDER BY post_time DESC";
	break;

case 'user':
	$sql = "SELECT p.post_time FROM ".$bbTable['posts']." p WHERE p.uid = '$id'";
	break;
}

if (!$result = $db->query($sql,1,0)) {
	return(_ERROR);
}

if (!$myrow = $db->fetch_array($result)) {
	return(_MD_NOPOSTS);
}

if (($type != 'user') && ($type != 'time_fix')) {
	$val = sprintf("%s <br /> %s %s", $myrow['post_time'], _MD_BY, $myrow['uname']);
	} else {
		$val = $myrow['post_time'];
	}

return($val);
}

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function list_moderators($forum_id=0) {
global $db, $myts, $bbTable;

$sql = "
	SELECT
	u.uid, u.uname
	FROM
	".$db->prefix("users")." u,
	".$bbTable['forum_mods']." f
	WHERE
	f.forum_id=$forum_id
	AND
	f.user_id=u.uid";

if ($result = $db->query($sql)) {
	if ($db->num_rows($result) > 1) {
		echo "
		<select class='select' name='moderators' onchange='top.location.href=\"".XOOPS_URL."/userinfo.php?uid=\" + this.options[this.options.selectedIndex].value + \"\";'>
		<option value='1'>------</option>";
		while (list($uid, $uname) = $db->fetch_row($result)) {
			echo "<option value='$uid'>".$myts->makeTboxData4Show($uname)."</option>";
		}
		echo "</select>";
		} else {
			list($uid, $uname) = $db->fetch_row($result);
			echo " <a href='".XOOPS_URL."/userinfo.php?uid=".$uid."'>".$myts->makeTboxData4Show($uname)."</a>";
		}
	} else {
		echo " ?";
	}
}

//---------------------------------------------------------------------------------------//
/**
* Checks if a user (user_id) is a moderator of a perticular forum (forum_id)
* Retruns 1 if TRUE, 0 if FALSE or Error
*
* @param type $var description
* @return type description
*/
function is_moderator($forum_id, $user_id) {
global $db, $bbTable;

$sql = "SELECT user_id FROM ".$bbTable['forum_mods']." WHERE forum_id = '$forum_id' AND user_id = '$user_id'";

if (!$result = $db->query($sql)) {
	return("0");
}

if (!$myrow = $db->fetch_array($result)) {
	return("0");
}

if ($myrow['user_id'] != '') {
	return("1");
	} else {
		return("0");
	}
}

//---------------------------------------------------------------------------------------//
/**
* Checks if a topic is locked
*
* @param type $var description
* @return type description
*/
function is_locked($topic) {
global $db, $bbTable;

$sql = "SELECT topic_status FROM ".$bbTable['topics']." WHERE topic_id = '$topic'";

if (!$r = $db->query($sql)) {
	return(FALSE);
}

if (!$m = $db->fetch_array($r)) {
	return(FALSE);
}

if ($m[topic_status] == 1) {
	return(TRUE);
	} else {
		return(FALSE);
	}
}

function get_forum_auth($forumid)
{
	global $xoopsUser, $xoopsModule;

	$userid = 0; // anonymous
	$permissions = array();
	$permissions['can_view'] = 0;
	$permissions['can_post'] = 0;
	$permissions['can_reply'] = 0;
	$permissions['can_edit'] = 0;
	$permissions['can_delete'] = 0;
	$permissions['can_addpoll'] = 0;
	$permissions['can_vote'] = 0;
	$permissions['can_attach'] = 0;
	
	$mid = 0;	

	if ($xoopsUser)
	{
		$userid = $xoopsUser->getVar('uid');
		if($xoopsModule && $xoopsModule->dirname == 'newbb_plus')
			$mid = $xoopsModule->mid();
		else if($module = XoopsModule::getByDirName('newbb_plus'))
			$mid = $module->mid();
	}

	if($xoopsUser && ($xoopsUser->isAdmin($mid) || is_moderator($forumid,$userid)))
	{
		$permissions['can_view'] = 1;
		$permissions['can_post'] = 1;
		$permissions['can_reply'] = 1;
		$permissions['can_edit'] = 1;
		$permissions['can_delete'] = 1;
		$permissions['can_addpoll'] = 1;
		$permissions['can_vote'] = 1;
		$permissions['can_attach'] = 1;
	}
	else
	{
		if (!get_forum_auth_user($userid, $forumid, $permissions))
		{
			get_forum_auth_group($userid, $forumid, $permissions);
		}
	}

	return $permissions;
}



//---------------------------------------------------------------------------------------//
/**
* Checks if the given userid is allowed to log into the given (private) forumid.
* If the "is_posting" flag is true, checks if the user is allowed to post to that forum.
*
* @param type $var description
* @return type description
*/
function get_forum_auth_group($userid, $forumid, &$permissions)
{
global $db, $bbTable;

	$sql = '';
	if ($userid == 0) // anonymous
	{
		$sql = "SELECT * FROM "
			.$bbTable['forum_group_access']
			." WHERE group_id=3 AND (forum_id = $forumid) ";
	}
	else
	{
		$sql = "SELECT * FROM "
			.$bbTable['forum_group_access']." AS a LEFT JOIN "
			.$db->prefix("groups_users_link")." AS g ON a.group_id = g.groupid "
			."WHERE (g.uid = $userid) AND (forum_id = $forumid) ";
	}
	
	if ($result = $db->query($sql))
	{
		while ($row = $db->fetch_object($result))
		{
			$permissions['can_view']    |= $row->can_view;
			$permissions['can_post']    |= $row->can_post;
			$permissions['can_reply']   |= $row->can_reply;
			$permissions['can_edit']    |= $row->can_edit;
			$permissions['can_delete']  |= $row->can_delete;
			$permissions['can_addpoll'] |= $row->can_addpoll;
			$permissions['can_vote']    |= $row->can_vote;
			$permissions['can_attach']  |= $row->can_attach;
		}
	}
}

//---------------------------------------------------------------------------------------//
/**
* Checks if the given userid is allowed to log into the given (private) forumid.
* If the "is_posting" flag is true, checks if the user is allowed to post to that forum.
*
* @param type $var description
* @return type description
*/
function get_forum_auth_user($userid, $forumid, &$permissions)
{
global $db, $bbTable;

$bFound = false;
$sql = "SELECT * FROM ".$bbTable['forum_access']." WHERE (user_id = $userid) AND (forum_id = $forumid) ";
if ($result = $db->query($sql))
{
	if ($row = $db->fetch_object($result))
	{
			$permissions['can_view']    |= $row->can_view;
			$permissions['can_post']    |= $row->can_post;
			$permissions['can_reply']   |= $row->can_reply;
			$permissions['can_edit']    |= $row->can_edit;
			$permissions['can_delete']  |= $row->can_delete;
			$permissions['can_addpoll'] |= $row->can_addpoll;
			$permissions['can_vote']    |= $row->can_vote;
			$permissions['can_attach']  |= $row->can_attach;

			$bFound = true;
	}
}

return $bFound;
}

function get_viewable_forums()
{
	global $db, $bbTable, $xoopsUser;
	
	$uid = ($xoopsUser) ? $xoopsUser->getvar('uid') : 0;
	
	$viewable = array();
	$sql = "SELECT * FROM ".$bbTable['forum_access']." WHERE (user_id = $uid) AND can_view=1";
	if ($result = $db->query($sql))
	{
		while($row = $db->fetch_object($result))
		{
			$viewable[$row->forum_id] = 1;
		}
	}
	
	$sql = '';
        $bCheckModerators = false;
	if ($uid == 0) // anonymous
	{
                $sql = "SELECT forum_id FROM ".$bbTable['forum_group_access']." WHERE group_id=3 AND can_view=1";
        }
        else if ($xoopsUser && $xoopsUser->isAdmin())
        {
                 $sql = "select forum_id from ".$bbTable['forums'];
	}
	else
	{
                $sql = "SELECT forum_id FROM ".$bbTable['forum_group_access']." AS a LEFT JOIN "
			.$db->prefix("groups_users_link")." AS g ON a.group_id = g.groupid "
			."WHERE (g.uid = $uid) AND can_view=1";

                $bCheckModerators = true;
	}
	if ($result = $db->query($sql))
	{
		while($row = $db->fetch_object($result))
		{
			$viewable[$row->forum_id] = 1;
		}
	}
	
        if ($bCheckModerators && $xoopsUser)
        {
            $sql = "SELECT forum_id from ".$bbTable['forum_mods']." where user_id=$uid";
            if ($result = $db->query($sql))
            {
                while($row = $db->fetch_object($result))
                {
                    $viewable[$row->forum_id] = 1;
                }
            }
            else echo $db->error();

        }

	return $viewable;
}

//---------------------------------------------------------------------------------------//
/**
* Displays an error message and exits the script. Used in the posting files.
*
* @param type $var description
* @return type description
*/
function error_die($msg) {
global $bbWidth;

?>
<br />
<table border="0" cellpadding="1" cellspacing="0" align="center" valign="top" width="<?php echo $bbWidth;?>"><tr>
<td class="bg2">
<table border="0" cellpadding="1" cellspacing="1" width="100%"><tr class="bg3" align="left">
<td><p><ul><?php echo $msg;?></ul></p></td>
</tr></table>
</td></tr></table>
<br />

<?php
CloseTable();
include_once(XOOPS_ROOT_PATH . "/footer.php");
exit();
}

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function make_jumpbox() {
global $db, $myts, $xoopsUser, $xoopsModule, $bbTable;

echo '<form action="viewforum.php" method="get">';
echo '<select class="select" name="forum"><option value="-1">'._MD_SELFORUM.'</option>';

$sql = "SELECT cat_id, cat_title FROM ".$bbTable['categories']." ORDER BY cat_order";

if ($result = $db->query($sql)) {
	$myrow = $db->fetch_array($result);
	$myrow['cat_title'] = $myts->makeTboxData4Show($myrow['cat_title']);
	do {
		echo "
		<option value='-1'>&nbsp;</option>
		<option value='-1'>".$myrow['cat_title']."</option>
		<option value='-1'>----------------</option>";
		$sub_sql = "SELECT forum_id, forum_name FROM ".$bbTable['forums']." WHERE cat_id ='$myrow[cat_id]' ORDER BY forum_id";
		if ($res = $db->query($sub_sql)) {
			while (list($forum_id, $forum_name) = $db->fetch_row($res))
			{
				$permissions = get_forum_auth($forum_id);
				if ($permissions['can_view'] == 0)
				{
					continue;
				}
			$name = $myts->makeTboxData4Show($forum_name);
			echo "<option value='".$forum_id."'>$name</option>";
			}
			} else {
				echo "<option value='0'>Error Connecting to DB</option>";
			}
		} while ($myrow = $db->fetch_array($result));
	} else {
		echo "<option value='-1'>ERROR</option>";
	}

echo "</select> <input type='submit' class='button' value='"._GO."' /></form>";
}

//---------------------------------------------------------------------------------------//
/**
* Description
*
* @param type $var description
* @return type description
*/
function sync($id, $type) {
global $db, $bbTable;

switch($type) {

case 'forum':
	$sql = "SELECT max(post_id) AS last_post FROM ".$bbTable['posts']." WHERE forum_id = $id";

	if (!$result = $db->query($sql)) {
		die("Could not get post ID");
	}

	if ($row = $db->fetch_array($result)) {
		$last_post = $row["last_post"];
	}

	$sql = "SELECT count(post_id) AS total FROM ".$bbTable['posts']." WHERE forum_id = $id";

	if (!$result = $db->query($sql)) {
		die("Could not get post count");
	}

	if ($row = $db->fetch_array($result)) {
		$total_posts = $row["total"];
	}

	$sql = "SELECT count(topic_id) AS total FROM ".$bbTable['topics']." WHERE forum_id = $id";

	if (!$result = $db->query($sql)) {
		die("Could not get topic count");
	}

	if ($row = $db->fetch_array($result)) {
		$total_topics = $row["total"];
	}

	$sql = "UPDATE ".$bbTable['forums']." SET forum_last_post_id = '$last_post', forum_posts = $total_posts, forum_topics = $total_topics WHERE forum_id = $id";

	if (!$result = $db->query($sql)) {
		die("Could not update forum $id");
	}
	break;

case 'topic':
	$sql = "SELECT max(post_id) AS last_post FROM ".$bbTable['posts']." WHERE topic_id = $id";
	if (!$result = $db->query($sql)) {
		die("Could not get post ID");
	}

	if ($row = $db->fetch_array($result)) {
		$last_post = $row["last_post"];
	}

	if ( $last_post > 0 ) {
		$sql = "SELECT count(post_id) AS total FROM ".$bbTable['posts']." WHERE topic_id = $id";

	if (!$result = $db->query($sql)) {
		die("Could not get post count");
	}

	if ($row = $db->fetch_array($result)) {
		$total_posts = $row["total"];
	}

	$total_posts -= 1;
	$sql = "UPDATE ".$bbTable['topics']." SET topic_replies = $total_posts, topic_last_post_id = $last_post WHERE topic_id = $id";

	if (!$result = $db->query($sql)) {
		die("Could not update topic $id");
	}
	}
	break;

case 'all forums':
	$sql = "SELECT forum_id FROM ".$bbTable['forums']."";
	if (!$result = $db->query($sql)) {
		die("Could not get forum IDs");
	}

	while ($row = $db->fetch_array($result)) {
		$id = $row["forum_id"];
		sync($id, "forum");
	}
	break;

case 'all topics':
	$sql = "SELECT topic_id FROM ".$bbTable['topics']."";
	if (!$result = $db->query($sql)) {
		die("Could not get topic ID's");
	}

	while ($row = $db->fetch_array($result)) {
		$id = $row["topic_id"];
		sync($id, "topic");
	}
	break;
}

return(TRUE);
}

function build_rss()
{
	global $db, $bbTable, $newbbConfig, $bbPath, $myts;

	include (XOOPS_ROOT_PATH.'/class/xml-rss.php');
	if ($newbbConfig['rss_enable'] == 1)
	{
		$sql= "SELECT t.* FROM ".$bbTable['topics']." AS t, ".$bbTable['forum_group_access']." AS g WHERE t.forum_id=g.forum_id AND g.group_id=3 ORDER BY t.topic_last_post_id DESC";
		$query = $db->query($sql, $newbbConfig['rss_maxitems']);
		if ($query)
		{
			$rss = new xml_rss($bbPath['path'] . 'cache/forum.xml');
			$rss->channel_title .= " :: "._MI_NEWBBPLUS_NAME;
			$rss->image_title   .= " :: "._MI_NEWBBPLUS_NAME;
			$rss->max_items            = $newbbConfig['rss_maxitems'];
			$rss->max_item_description = $newbbConfig['rss_maxdescription'];

			while ( $row = $db->fetch_object($query) )
			{
				$link = $bbPath['url'] . 'viewtopic.php?topic_id=' . $row->topic_id . '&amp;forum=' . $row->forum_id;
				$title = $myts->makeTareaData4Show($row->topic_title);
				$description = '';
				
				$sql = "SELECT * FROM ".$bbTable['posts']." WHERE topic_id=".$row->topic_id." ORDER BY post_id";
				if($res = $db->query($sql))
				{
					if($post_row = $db->fetch_object($res))
					{
						$description .= "\"".$post_row->post_text."\"";
						$description .= " <BR> "._MD_POSTED_BY." ";
						$description .= XoopsUser::getUnameFromID($post_row->uid);
						$description .= " (".formatTimestamp($post_row->post_time).")";
					}
				}

				$rss->build($title, $link, $description);
			}
			$rss->save();
		}
	}
}

function print_colorbar_combo($name, $selected='')
{
	global $bbPath;
	
	$content = "<select name='$name' class='select'>";
	$path = $bbPath['path']."images/colorbars/"; 
	$d = dir($path); 	
	while (false !== ($entry = $d->read()))
	{
	   if(!is_dir($path.$entry) && substr($entry, -4)=='.gif')
	   {
	   		$content .= "<option";
			if ($selected == $entry) $content .= " selected ";
			$content .= ">$entry</option>";
	   }
	}
	$d->close();
	$content .= "</select>";
	return $content;
}

function get_current_version()
{
        global $db;
        $xoopsModule = XoopsModule::getByDirname('newbb_plus');

        $sql = 'select version from '.$db->prefix('modules').' WHERE mid='.$xoopsModule->mid();
        if($result = $db->query($sql))
        {
                if($db->num_rows($result) == 1)
                {
                        $row = $db->fetch_object($result);
                        return $row->version;
                }
        }
        return '';
}

} // End NEWBBPLUS_FUNCTIONS_INCLUDED
?>