<?php
/**
 * @version $Id: msg.inc.php v2.0 $
 * @package PBDigg
 * @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved.
 * @license PBDigg is free software and use is subject to license terms
 */

if (!defined('IN_PBDIGG'))
{
	exit('Access Denied!');
}

function PMsg($var, $save = FALSE, $sys = 0)
{
	global $DB, $db_prefix, $timestamp;
	foreach ($var as $key => $value)
	{
		$rt = $DB->db_fetch_one_array("SELECT COUNT(*) total FROM {$db_prefix}message WHERE tuid = $key AND type = 'r'");
		$totalMsg = intval($rt['total']);
		$rt = $DB->db_fetch_one_array("SELECT groupid FROM {$db_prefix}members WHERE uid = $key");
		$groupid = $rt['groupid'];
		if ($groupid == '-1')
		{
			$SQL = "SELECT u.groupid FROM {$db_prefix}usergroups u 
					LEFT JOIN {$db_prefix}memberdata md 
					ON (md.currency >= u.uplower AND md.currency < u.uphigher) 
					WHERE md.uid = $key";
	
			$group = $DB->db_fetch_one_array($SQL);
			$groupid = $group['groupid'];
		}
		$groupid = (int)$groupid;
		require (PBDIGG_ROOT.'data/cache/cache_usergroup_'.$groupid.'.php');
		if (!$sys && ($totalMsg >= $msgmax))
		{
			return FALSE;
		}
		$SQL = "INSERT INTO {$db_prefix}message (fuid, tuid, title, content, type, postdate, ifread, ifsys) 
				VALUES({$value[0]}, {$key}, '{$value[1]}', '{$value[2]}', 'r', $timestamp, 0, $sys)";
		$DB->db_query($SQL);
		if ($save && !$sys)
		{
			$SQL = "INSERT INTO {$db_prefix}message (fuid, tuid, title, content, type, postdate, ifread, ifsys) 
					VALUES({$value[0]}, {$key}, '{$value[1]}', '{$value[2]}', 's', $timestamp, 1, $sys)";
			$DB->db_query($SQL);
		}
		//new msg
		$newmsg = $DB->db_fetch_one_array("SELECT COUNT(*) num FROM {$db_prefix}message WHERE tuid = $key AND type = 'r' AND ifread = 0");
		$DB->db_query("UPDATE {$db_prefix}memberdata SET newmsg = ".(int)$newmsg['num']." WHERE uid = $key");
	}
	return TRUE;
}
?>
