<?php
/***************************************************************************
                           functions.php  -  description
                             -------------------
    begin                : Sat June 17 2000
    copyright            : (C) 2001 The phpBB Group
    email                : support@phpbb.com

    $Id: functions.php,v 1.115 2001/05/30 20:45:59 thefinn Exp $

 ***************************************************************************/

/***************************************************************************
 *                                         				                                
 *   This program is free software; you can redistribute it and/or modify  	
 *   it under the terms of the GNU General Public License as published by  
 *   the Free Software Foundation; either version 2 of the License, or	    	
 *   (at your option) any later version.
 *
 ***************************************************************************/

/*
 * Gets the total number of topics in a form
 */
function get_total_topics($forum_id="") {
	global $xoopsDB;
	if($forum_id){
		$sql = "SELECT COUNT(*) AS total FROM ".$xoopsDB->prefix("bb_topics")." WHERE forum_id = '$forum_id'";
	}else{
		$sql = "SELECT COUNT(*) AS total FROM ".$xoopsDB->prefix("bb_topics")."";
	}
	if(!$result = $xoopsDB->query($sql))
		return(_MD_ERROR);
	if(!$myrow = $xoopsDB->fetchArray($result))
		return(_MD_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.
 */ 
function get_total_posts($id, $type) {
   global $xoopsDB;
   switch($type) {
    case 'users':
      $sql = "SELECT count(*) AS total FROM ".$xoopsDB->prefix("users")." u WHERE (u.uid != 0) AND (level != -1)";
      break;
    case 'all':
      $sql = "SELECT count(*) AS total FROM ".$xoopsDB->prefix("bb_posts")."";
      break;
    case 'forum':
      $sql = "SELECT count(*) AS total FROM ".$xoopsDB->prefix("bb_posts")." WHERE forum_id = '$id'";
      break;
    case 'topic':
      $sql = "SELECT count(*) AS total FROM ".$xoopsDB->prefix("bb_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.");
   }
   if(!$result = $xoopsDB->query($sql))
     return("ERROR");
   if(!$myrow = $xoopsDB->fetchArray($result))
     return("0");
   
   return($myrow['total']);
   
}

/*
 * Returns the most recent post in a forum, or a topic
 */
function get_last_post($id, $type) {
   global $xoopsDB;
   switch($type) {
    case 'time_fix':
      $sql = "SELECT p.post_time FROM ".$xoopsDB->prefix("bb_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 ".$xoopsDB->prefix("bb_posts")." p, ".$xoopsDB->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 ".$xoopsDB->prefix("bb_posts")." p, ".$xoopsDB->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 ".$xoopsDB->prefix("bb_posts")." p WHERE p.uid = '$id'";
      break;
   }
   if(!$result = $xoopsDB->query($sql,1,0))
     return(_MD_ERROR);
   
   if(!$myrow = $xoopsDB->fetchArray($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);
}

/*
 * Returns an array of all the moderators of a forum
 */
function get_moderators($forum_id) {
	global $xoopsDB;
   $sql = "SELECT u.uid, u.uname FROM ".$xoopsDB->prefix("users")." u, ".$xoopsDB->prefix("bb_forum_mods")." f WHERE f.forum_id = '$forum_id' and f.user_id = u.uid";
	//echo $sql;
    if(!$result = $xoopsDB->query($sql))
     return(array());
   if(!$myrow = $xoopsDB->fetchArray($result))
     return(array());
   do {
      $array[] = array($myrow['uid'] => $myrow['uname']);
   } while($myrow = $xoopsDB->fetchArray($result));
   return($array);
}

/*
 * Checks if a user (user_id) is a moderator of a perticular forum (forum_id)
 * Retruns 1 if TRUE, 0 if FALSE or Error
 */
function is_moderator($forum_id, $user_id) {
	global $xoopsDB;
   $sql = "SELECT user_id FROM ".$xoopsDB->prefix("bb_forum_mods")." WHERE forum_id = '$forum_id' AND user_id = '$user_id'";
   if(!$result = $xoopsDB->query($sql))
     return("0");
   if(!$myrow = $xoopsDB->fetchArray($result))
     return("0");
   if($myrow['user_id'] != '')
     return("1");
   else
     return("0");
}

/*
 * Checks if a forum or a topic exists in the database. Used to prevent
 * users from simply editing the URL to post to a non-existant forum or topic
 */
function does_exists($id, $type) {
	global $xoopsDB;
	switch($type) {
		case 'forum':
			$sql = "SELECT forum_id FROM ".$xoopsDB->prefix("bb_forums")." WHERE forum_id = '$id'";
		break;
		case 'topic':
			$sql = "SELECT topic_id FROM ".$xoopsDB->prefix("bb_topics")." WHERE topic_id = '$id'";
		break;
	}
	if(!$result = $xoopsDB->query($sql))
		return(0);
	if(!$myrow = $xoopsDB->fetchArray($result)) 
		return(0);
	return(1);
}

/*
 * Checks if a topic is locked
 */
function is_locked($topic) {
	global $xoopsDB;
	$sql = "SELECT topic_status FROM ".$xoopsDB->prefix("bb_topics")." WHERE topic_id = '$topic'";
	if(!$r = $xoopsDB->query($sql))
		return(FALSE);
	if(!$m = $xoopsDB->fetchArray($r))
		return(FALSE);
	if($m[topic_status] == 1)
		return(TRUE);
	else
		return(FALSE);
}

/*
 * Changes :) to an <IMG> tag based on the smiles table in the database.
 *
 * Smilies must be either: 
 * 	- at the start of the message.
 * 	- at the start of a line.
 * 	- preceded by a space or a period.
 * This keeps them from breaking HTML code and BBCode.
 * TODO: Get rid of global variables.
 */
/*
function smile($message) {
   global $bbUrl;
   
   // Pad it with a space so the regexp can match.
   $message = ' ' . $message;
   
   if ($getsmiles = $xoopsDB->query("SELECT *, length(code) as length FROM smiles ORDER BY length DESC"))
   {
      while ($smiles = $xoopsDB->fetchArray($getsmiles)) 
      {
			$smile_code = preg_quote($smiles[code]);
			$smile_code = str_replace('/', '//', $smile_code);
			$message = preg_replace("/([\n\\ \\.])$smile_code/si", '\1<IMG SRC="' . $bbUrl['smilies'] . '/' . $smiles[smile_url] . '">', $message);
      }
   }
   
   // Remove padding, return the new string.
   $message = substr($message, 1);
   return($message);
}

*/


/*
 * Returns the name of the forum based on ID number
 */
function get_forum_name($forum_id) {
	global $xoopsDB;
	$sql = "SELECT forum_name FROM ".$xoopsDB->prefix("bb_forums")." WHERE forum_id = '$forum_id'";
	if(!$r = $xoopsDB->query($sql))
		return(_MD_ERROR);
	if(!$m = $xoopsDB->fetchArray($r))
		return("None");
	return($m[forum_name]);
}

/**
 * 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.
 */
function check_priv_forum_auth($userid, $forumid, $is_posting)
{
global $xoopsDB;
	$sql = "SELECT count(*) AS user_count FROM ".$xoopsDB->prefix("bb_forum_access")." WHERE (user_id = $userid) AND (forum_id = $forumid) ";
	
	if ($is_posting)
	{
		$sql .= "AND (can_post = 1)";
	}
	
	if (!$result = $xoopsDB->query($sql))
	{
		// no good..
		return FALSE;
	}
	
	if(!$row = $xoopsDB->fetchArray($result))
	{
		return FALSE;
	}
   
  	if ($row[user_count] <= 0)
  	{
  		return FALSE;
  	}
  	
  	return TRUE;

}

/**
 * Displays an error message and exits the script. Used in the posting files.
 */
function error_die($msg){
	global $bbWidth;
	print("<br />
		<table border='0' cellpadding='1' cellspacing='0' align='center' valign='top' width='$bbWidth'>
		<tr><td class='bg2'>
			<table border=\"0\" callpadding=\"1\" cellspaceing=\"1\" width=\"100%\">
			<tr class='bg3' align='left'>
				<td>
					<p><ul>$msg</ul></p>
				</td>
			</tr>
			</table>
		</td></tr>
	 	</table>
	 <br>");
	 include("page_tail.php");
	 exit;
}

function make_jumpbox(){
	global $xoopsDB;
	$myts = MyTextSanitizer::getInstance();
	?>
	<form action="viewforum.php" method="get">
	<select name="forum"><option value="-1"><?php echo _MD_SELFORUM?></option>
	<?php
	  $sql = "SELECT cat_id, cat_title FROM ".$xoopsDB->prefix("bb_categories")." ORDER BY cat_order";
	if($result = $xoopsDB->query($sql)) {
	   $myrow = $xoopsDB->fetchArray($result);
		$myrow[cat_title] = $myts->makeTboxData4Show($myrow[cat_title]);
	   do {
	      echo "<option value=\"-1\">&nbsp;</option>\n";
	      echo "<option value=\"-1\">".$myrow['cat_title']."</option>\n";
	      echo "<option value=\"-1\">----------------</option>\n";
	      $sub_sql = "SELECT forum_id, forum_name FROM ".$xoopsDB->prefix("bb_forums")." WHERE cat_id =
	'$myrow[cat_id]' ORDER BY forum_id";
	      if($res = $xoopsDB->query($sub_sql)) {
	    if($row = $xoopsDB->fetchArray($res)) {
	       do {
		  $name = $myts->makeTboxData4Show($row['forum_name']);
		  echo "<option value='".$row['forum_id']."'>$name</option>\n";
	       } while($row = $xoopsDB->fetchArray($res));
	    }
	    else {
	       echo "<option value=\"0\">No More Forums</option>\n";
	    }
	      }
	      else {
	    echo "<option value=\"0\">Error Connecting to DB</option>\n";
	      }
	   } while($myrow = $xoopsDB->fetchArray($result));
	}
	else {
	   echo "<option value=\"-1\">ERROR</option>\n";
	}
	echo "</select>\n<input type=\"submit\" value=\""._MD_GO."\" />\n</form>";
}


function sync($id, $type) {
	global $xoopsDB;
   switch($type) {
   	case 'forum':
   		$sql = "SELECT max(post_id) AS last_post FROM ".$xoopsDB->prefix("bb_posts")." WHERE forum_id = $id";
   		if(!$result = $xoopsDB->query($sql))
   		{
   			die("Could not get post ID");
   		}
   		if($row = $xoopsDB->fetchArray($result))
   		{
   			$last_post = $row["last_post"];
   		}
   		
   		$sql = "SELECT count(post_id) AS total FROM ".$xoopsDB->prefix("bb_posts")." WHERE forum_id = $id";
   		if(!$result = $xoopsDB->query($sql))
   		{
   			die("Could not get post count");
   		}
   		if($row = $xoopsDB->fetchArray($result))
   		{
   			$total_posts = $row["total"];
   		}
   		
   		$sql = "SELECT count(topic_id) AS total FROM ".$xoopsDB->prefix("bb_topics")." WHERE forum_id = $id";
   		if(!$result = $xoopsDB->query($sql))
   		{
   			die("Could not get topic count");
   		}
   		if($row = $xoopsDB->fetchArray($result))
   		{
   			$total_topics = $row["total"];
   		}
   		
   		$sql = "UPDATE ".$xoopsDB->prefix("bb_forums")." SET forum_last_post_id = '$last_post', forum_posts = $total_posts, forum_topics = $total_topics WHERE forum_id = $id";
   		if(!$result = $xoopsDB->queryF($sql))
   		{
   			die("Could not update forum $id");
   		}
   	break;

   	case 'topic':
   		$sql = "SELECT max(post_id) AS last_post FROM ".$xoopsDB->prefix("bb_posts")." WHERE topic_id = $id";
   		if(!$result = $xoopsDB->query($sql))
   		{
   			die("Could not get post ID");
   		}
   		if($row = $xoopsDB->fetchArray($result))
   		{
   			$last_post = $row["last_post"];
   		}
   		if ( $last_post > 0 ) {
   			$sql = "SELECT count(post_id) AS total FROM ".$xoopsDB->prefix("bb_posts")." WHERE topic_id = $id";
   			if(!$result = $xoopsDB->query($sql)){
   				die("Could not get post count");
   			}
   			if($row = $xoopsDB->fetchArray($result)){
   				$total_posts = $row["total"];
   			}
   			$total_posts -= 1;
   			$sql = "UPDATE ".$xoopsDB->prefix("bb_topics")." SET topic_replies = $total_posts, topic_last_post_id = $last_post WHERE topic_id = $id";
   			if(!$result = $xoopsDB->queryF($sql)){
   				die("Could not update topic $id");
   			}
		}
   	break;

   	case 'all forums':
   		$sql = "SELECT forum_id FROM ".$xoopsDB->prefix("bb_forums")."";
   		if(!$result = $xoopsDB->query($sql))
   		{
   			die("Could not get forum IDs");
   		}
   		while($row = $xoopsDB->fetchArray($result))
   		{
   			$id = $row["forum_id"];
   			sync($id, "forum");
   		}
   	break;
   	case 'all topics':
   		$sql = "SELECT topic_id FROM ".$xoopsDB->prefix("bb_topics")."";
   		if(!$result = $xoopsDB->query($sql))
   		{
   			die("Could not get topic ID's");
   		}
   		while($row = $xoopsDB->fetchArray($result))
   		{
   			$id = $row["topic_id"];
   			sync($id, "topic");
   		}
   	break;
   }
   return(TRUE);
}


?>