<?php
/**
*
* @package phpBB3
* @version $Id: viewchat.php 1.000 2008-08-02 21:28:00 PPK $
* @copyright (c) 2008 PPK
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);
include($phpbb_root_path . 'includes/functions_display.' . $phpEx);

// Start session
$user->session_begin();
$auth->acl($user->data);

// Start initial var setup
$forum_id	= request_var('f', 0);
$chat=request_var('chat', '');

// Check if the user has actually sent a forum ID with his/her request
// If not give them a nice error page.
if (!$forum_id)
{
	trigger_error('NO_FORUM');
}

$sql_from = FORUMS_TABLE . ' f';

$sql = "SELECT f.*
	FROM $sql_from
	WHERE f.forum_id = $forum_id";
$result = $db->sql_query($sql);
$forum_data = $db->sql_fetchrow($result);
$db->sql_freeresult($result);

if (!$forum_data)
{
	trigger_error('NO_FORUM');
}

($forum_data['forum_type'] == FORUM_POST && $forum_data['forumas']==2) ? $forum_aschat=1 : $forum_aschat=0;

if(!$forum_aschat)
{
	header('Location: index.'.$phpEx);
	exit();
}

// Configure style, language, etc.
$user->setup('viewforum', $forum_data['forum_style']);

// Redirect to login upon emailed notification links
if (isset($_GET['e']) && !$user->data['is_registered'])
{
	login_box('', $user->lang['LOGIN_NOTIFY_FORUM']);
}

// Permissions check
if (!$auth->acl_gets('f_list', 'f_read', $forum_id) || ($forum_data['forum_type'] == FORUM_LINK && $forum_data['forum_link'] && !$auth->acl_get('f_read', $forum_id)))
{
	if ($user->data['user_id'] != ANONYMOUS)
	{
		trigger_error('SORRY_AUTH_READ');
	}

	login_box('', $user->lang['LOGIN_VIEWFORUM']);
}

// Forum is passworded ... check whether access has been granted to this
// user this session, if not show login box
if ($forum_data['forum_password'])
{
	login_forum_box($forum_data);
}

// Is this forum a link? ... User got here either because the
// number of clicks is being tracked or they guessed the id
if ($forum_data['forum_type'] == FORUM_LINK && $forum_data['forum_link'])
{
	// Does it have click tracking enabled?
	if ($forum_data['forum_flags'] & FORUM_FLAG_LINK_TRACK)
	{
		$sql = 'UPDATE ' . FORUMS_TABLE . '
			SET forum_posts = forum_posts + 1
			WHERE forum_id = ' . $forum_id;
		$db->sql_query($sql);
	}

	redirect($forum_data['forum_link']);
}

// Build navigation links
generate_forum_nav($forum_data);

// Forum Rules
if ($auth->acl_get('f_read', $forum_id))
{
	generate_forum_rules($forum_data);
}

// Do we have subforums?
$active_forum_ary = $moderators = array();

if ($forum_data['left_id'] != $forum_data['right_id'] - 1)
{
	list($active_forum_ary, $moderators) = display_forums($forum_data, $config['load_moderators'], $config['load_moderators']);
}
else
{
	$template->assign_var('S_HAS_SUBFORUM', false);
	get_moderators($moderators, $forum_id);
}

// Dump out the page header and load viewchat template
page_header($user->lang['VIEW_FORUM'] . ' - ' . $forum_data['forum_name']);

$template->set_filenames(array(
	'body' => 'viewforum_chat_body.html')
);


make_jumpbox(append_sid("{$phpbb_root_path}viewforum.$phpEx"), $forum_id);

$template->assign_vars(array(
	'U_VIEW_FORUM'			=> append_sid("{$phpbb_root_path}viewchat.$phpEx", "f=$forum_id"),
));

// Not postable forum or showing active topics?
if (!($forum_data['forum_type'] == FORUM_POST || (($forum_data['forum_flags'] & FORUM_FLAG_ACTIVE_TOPICS) && $forum_data['forum_type'] == FORUM_CAT)))
{
	page_footer();
}

// Ok, if someone has only list-access, we only display the forum list.
// We also make this circumstance available to the template in case we want to display a notice. ;)
if (!$auth->acl_get('f_read', $forum_id))
{
	$template->assign_vars(array(
		'S_NO_READ_ACCESS'		=> true,
		'S_AUTOLOGIN_ENABLED'	=> ($config['allow_autologin']) ? true : false,
		'S_LOGIN_ACTION'		=> append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=login') . '&amp;redirect=' . urlencode(str_replace('&amp;', '&', build_url())),
	));

	page_footer();
}

// Forum rules and subscription info
$s_watching_forum = array(
	'link'			=> '',
	'title'			=> '',
	'is_watching'	=> false,
);
// Basic pagewide vars
$post_alt = ($forum_data['forum_status'] == ITEM_LOCKED) ? $user->lang['FORUM_LOCKED'] : 0;

if(!$post_alt)
{
	$user->add_lang('chat');

	$query=('SELECT * FROM ' .CHAT_USERS_TABLE. " WHERE room='$forum_id'");
	$result=$db->sql_query($query);

	$chat_user='';
	$users=array();
	$del_users=array();

	while($row=$db->sql_fetchrow($result))
	{
		if(time() - $row['lastaccess'] < $config['ppkbb_chat_inactive_time'])
		{
			if($row['user_id']==$user->data['user_id'])
			{
				$chat_user=$row;
			}
			$users[$row['user_id']]=$row;
		}
		else
		{
			$del_users[]=$row['id'];
		}
	}
	$db->sql_freeresult($result);

	if($del_users)
	{
		$query=('DELETE FROM ' .CHAT_USERS_TABLE. " WHERE id IN(".implode(', ', $del_users).")");
		$result=$db->sql_query($query);
	}

	$chat_link=array();
	$chat_link['exit']='<a href="'.append_sid("{$phpbb_root_path}viewchat.$phpEx", "f=$forum_id&amp;chat=exit").'">'.$user->lang['CHAT_EXIT'].'</a>';
	$chat_link['enter']='<a href="'.append_sid("{$phpbb_root_path}viewchat.$phpEx", "f=$forum_id&amp;chat=enter").'">'.$user->lang['CHAT_ENTER'].'</a>';

	$is_mod=($auth->acl_get('m_') || $auth->acl_getf_global('m_')) ? 1 : 0;
	$is_adm=$auth->acl_get('a_') ? 1 : 0;
	$is_canaddchatm=$auth->acl_get('f_canaddchatm', $forum_id) && $auth->acl_get('u_canaddchatm') ? 1 : 0;
	$is_canviewchatu=$auth->acl_get('f_canviewchatu', $forum_id) && $auth->acl_get('u_canviewchatu') ? 1 : 0;
	$is_canviewchatm=$auth->acl_get('f_canviewchatm', $forum_id) && $auth->acl_get('u_canviewchatm') ? 1 : 0;
	$is_candelchatm=$auth->acl_get('f_candelchatm', $forum_id) && $auth->acl_get('u_candelchatm') ? 1 : 0;
	$is_canskipchatktime=$auth->acl_get('f_canskipchatktime', $forum_id) && $auth->acl_get('u_canskipchatktime') ? 1 : 0;
	$is_canhiddeninchat=$auth->acl_get('f_canhiddeninchat', $forum_id) && $auth->acl_get('u_canhiddeninchat') ? 1 : 0;
	$is_canviewhiddinchat=$auth->acl_get('f_canviewhiddinchat', $forum_id) && $auth->acl_get('u_canviewhiddinchat') ? 1 : 0;
	$is_cansendchatpm=$auth->acl_get('f_cansendchatpm', $forum_id) && $auth->acl_get('u_cansendchatpm') ? 1 : 0;
	$is_canskipdisbutton=$auth->acl_get('f_canskipdisbutton', $forum_id) && $auth->acl_get('u_canskipdisbutton') ? 1 : 0;
	$is_canusesmilies=$auth->acl_get('f_canusesmilies', $forum_id) && $auth->acl_get('u_canusesmilies') ? 1 : 0;
	$is_canusebbcodes=$auth->acl_get('f_canusebbcodes', $forum_id) && $auth->acl_get('u_canusebbcodes') ? 1 : 0;

	$rights="$is_adm $is_mod $is_canaddchatm $is_canviewchatu $is_canviewchatm $is_candelchatm $is_canskipchatktime $is_canhiddeninchat $is_canviewhiddinchat $is_cansendchatpm $is_canskipdisbutton $is_canusesmilies $is_canusebbcodes";

	if($chat=='exit' && $chat_user)
	{
		$query=('DELETE FROM ' .CHAT_USERS_TABLE. " WHERE user_id='{$user->data['user_id']}' AND room='$forum_id'");
		$result=$db->sql_query($query);

		$sql = 'UPDATE ' . USERS_TABLE . "
			SET user_chatkey = ''
			WHERE user_id = '" . $user->data['user_id'] ."' LIMIT 1";
		$result=$db->sql_query($sql);

		$chat_action='enter';
		unset($users[$user->data['user_id']]);
		$chat_user=0;
	}
	if($chat=='enter' && $chat_user)
	{
		$chat_action='exit';
	}
	$chat_key='';
	if($chat=='enter' && !$chat_user && $is_canaddchatm && $is_canviewchatu && $is_canviewchatm)
	{
		intval($config['ppkbb_chat_murefresh']) > 9 ? '' : $config['ppkbb_chat_murefresh']=10;
		$chat_key=create_chatkey();
		$css_link=(!@$user->theme['theme_storedb']) ? "styles/" . @$user->theme['theme_path'] . '/theme/stylesheet.css' : "chat/stylesheet.css";
		$query=('INSERT INTO ' .CHAT_USERS_TABLE. " VALUES ('0', '{$user->data['username']}', '{$user->data['user_lang']}//$css_link//$rights', '".(time()-$config['ppkbb_chat_waittime'])."', '$forum_id', '".(time()-$config['ppkbb_chat_murefresh'])."', '{$user->data['user_id']}', '$chat_key')");
		$result=$db->sql_query($query);
		$chat_action='exit';
	}

	@!$chat_action ? $chat_action='enter' : '';
	!$chat ? $chat='exit' : '';
	$link=$chat_link[$chat_action];

	$s_forum_rules = '';
	gen_forum_auth_level('forum', $forum_id, $forum_data['forum_status']);

	$message_window='';
	if(($is_canviewchatm || $is_canviewchatu) && $chat!='exit')
	{
		$message_window='<iframe marginwidth="0" marginheight="0" frameborder="0" scrolling="no" id="message" src="'.append_sid("{$phpbb_root_path}chat/message_user.$phpEx", "f=$forum_id&chatkey=$chat_key").'" name="message" width="100%" height="400"></iframe>';
	}
	else
	{
		if(!$is_canviewchatm)
		{
			$message_window=$user->lang['CHAT_CANT_VIEWCHATM'];
		}
		if(!$is_canviewchatu)
		{
			$message_window=($message_window ? '<br />' : '').$user->lang['CHAT_CANT_VIEWCHATM'];
		}
	}

	$user_window='';
	if($is_canviewchatu && $chat!='exit')
	{
		$user_window='<iframe marginwidth="0" marginheight="0" frameborder="0" scrolling="auto" id="user" src="'.append_sid("{$phpbb_root_path}chat/user.$phpEx", "f=$forum_id&chatkey=$chat_key").'" name="user" width="100%" height="400"></iframe>';
	}
	else
	{
		if(!$is_canviewchatu)
		{
			$message_window=$user->lang['CHAT_CANT_VIEWCHATU'];
		}
		else
		{
			if($users)
			{
				foreach($users as $k => $v)
				{
					$user_rights=explode(' ', $v['rights']);
					if(!$user_rights[7] && !$is_canviewhiddinchat)
					{
						$users[$k]='<a href="'.append_sid("{$phpbb_root_path}memberlist.$phpEx", "mode=viewprofile&amp;u=".$v['user_id']).'">'.$v['username'].'</a>';
					}
				}
			}
			$message_window='<b>'.$user->lang['CHAT_IN'].': </b>'. ($users ? implode(', ', $users).' ('.sizeof($users).')' : '(0)');
		}
	}

	$form_window='';
	$bar_window='';
	if($is_canaddchatm && $is_canviewchatm && $chat_action=='exit')
	{
		$form_window='<iframe marginwidth="0" marginheight="0" frameborder="0" scrolling="no" id="form" src="'.append_sid("{$phpbb_root_path}chat/form.$phpEx", "f=$forum_id&chatkey=$chat_key").'" name="form" width="100%" height="100%"></iframe>';
		if($is_canusesmilies || $is_canusebbcodes)
		{
			$bar_window='<iframe marginwidth="0" marginheight="0" frameborder="0" scrolling="auto" id="bar" src="'.append_sid("{$phpbb_root_path}chat/bar.$phpEx", "f=$forum_id&chatkey=$chat_key").'" name="bar" width="100%" height="20"></iframe>';
		}
	}
	else
	{
		if(!$is_canaddchatm || !$is_canviewchatm)
		{
			$form_window=$user->lang['CHAT_CANT_ADDCHATM'];
		}
	}
}

$template->assign_vars(array(
	'MODERATORS'	=> (!empty($moderators[$forum_id])) ? implode(', ', $moderators[$forum_id]) : '',

	'NEWEST_POST_IMG'			=> $user->img('icon_topic_newest', 'VIEW_NEWEST_POST'),
	'LAST_POST_IMG'				=> $user->img('icon_topic_latest', 'VIEW_LATEST_POST'),
	'FOLDER_IMG'				=> $user->img('topic_read', 'NO_NEW_POSTS'),
	'FOLDER_NEW_IMG'			=> $user->img('topic_unread', 'NEW_POSTS'),
	'FOLDER_HOT_IMG'			=> $user->img('topic_read_hot', 'NO_NEW_POSTS_HOT'),
	'FOLDER_HOT_NEW_IMG'		=> $user->img('topic_unread_hot', 'NEW_POSTS_HOT'),
	'FOLDER_LOCKED_IMG'			=> $user->img('topic_read_locked', 'NO_NEW_POSTS_LOCKED'),
	'FOLDER_LOCKED_NEW_IMG'		=> $user->img('topic_unread_locked', 'NEW_POSTS_LOCKED'),
	'FOLDER_STICKY_IMG'			=> $user->img('sticky_read', 'POST_STICKY'),
	'FOLDER_STICKY_NEW_IMG'		=> $user->img('sticky_unread', 'POST_STICKY'),
	'FOLDER_ANNOUNCE_IMG'		=> $user->img('announce_read', 'POST_ANNOUNCEMENT'),
	'FOLDER_ANNOUNCE_NEW_IMG'	=> $user->img('announce_unread', 'POST_ANNOUNCEMENT'),
	'FOLDER_MOVED_IMG'			=> $user->img('topic_moved', 'TOPIC_MOVED'),
	'REPORTED_IMG'				=> $user->img('icon_topic_reported', 'TOPIC_REPORTED'),
	'UNAPPROVED_IMG'			=> $user->img('icon_topic_unapproved', 'TOPIC_UNAPPROVED'),
	'GOTO_PAGE_IMG'				=> $user->img('icon_post_target', 'GOTO_PAGE'),

	'L_NO_TOPICS' 			=> ($forum_data['forum_status'] == ITEM_LOCKED) ? $user->lang['POST_FORUM_LOCKED'] : 0,

	'S_DISPLAY_POST_INFO'	=> ($forum_data['forum_type'] == FORUM_POST && ($auth->acl_get('f_post', $forum_id) || $user->data['user_id'] == ANONYMOUS)) ? true : false,

	'S_IS_POSTABLE'			=> ($forum_data['forum_type'] == FORUM_POST) ? true : false,
	'S_USER_CAN_POST'		=> ($auth->acl_get('f_post', $forum_id)) ? true : false,

	'S_WATCH_FORUM_LINK'	=> $s_watching_forum['link'],
	'S_WATCH_FORUM_TITLE'	=> $s_watching_forum['title'],
	'S_WATCHING_FORUM'		=> $s_watching_forum['is_watching'],
	'S_FORUM_ACTION'		=> append_sid("{$phpbb_root_path}viewchat.$phpEx", "f=$forum_id"),
	'S_DISPLAY_SEARCHBOX'	=> ($auth->acl_get('u_search') && $auth->acl_get('f_search', $forum_id) && $config['load_search']) ? true : false,
	'S_SEARCHBOX_ACTION'	=> append_sid("{$phpbb_root_path}search.$phpEx", 'fid[]=' . $forum_id),
	'S_SINGLE_MODERATOR'	=> (!empty($moderators[$forum_id]) && sizeof($moderators[$forum_id]) > 1) ? false : true,
	'S_IS_LOCKED'			=> ($forum_data['forum_status'] == ITEM_LOCKED) ? true : false,
	'S_VIEWFORUM'			=> true,

	'U_POST_NEW_TOPIC'	=> ($auth->acl_get('f_post', $forum_id) || $user->data['user_id'] == ANONYMOUS) ? append_sid("{$phpbb_root_path}posting.$phpEx", 'mode=post&amp;f=' . $forum_id) : '',
	'U_VIEW_FORUM'		=> append_sid("{$phpbb_root_path}viewchat.$phpEx", "f=$forum_id"),
	'U_MESSAGE_WINDOW'		=> @$message_window,
	'U_USER_WINDOW'		=> @$user_window,
	'U_FORM_WINDOW'		=> @$form_window,
	'U_BAR_WINDOW'		=> @$bar_window,
	'U_CHAT_LINK'		=> @$link,
));

// Grab icons
$icons = $cache->obtain_icons();

page_footer();

function create_chatkey()
{
	global $user, $db;

	$str=microtime().date('Y-m-d H:i:s').$user->data['username'].$user->data['user_form_salt'];
	$str=md5($str);

	$sql = 'UPDATE ' . USERS_TABLE . "
		SET user_chatkey = '$str'
		WHERE user_id = '" . $user->data['user_id'] ."' LIMIT 1";
	$result=$db->sql_query($sql);
	if(!$result)
	{
		return false;
	}

	return $str;
}

?>