<?php

require '../system/start.php';
require '../system/functions.php';
$communitys = mysql_result(mysql_query("select count(*) from `community`"),0); 
switch($act)
{
default:
$str['mesto'] = 'Сообщества';
$str['block'] = $set['site'].' / Сообщества';
$mycom = mysql_result(mysql_query("select count(*) from `community` where `id_user` = ".$user['id'].""),0);
include '../style/'.$style.'/head.php';
$soo = mysql_result(mysql_query("select count(*) from `users` where `where` = 'Сообщества' and time > ".(time()-300).""),0);
$query = mysql_query("select * from `community_selections` order by `id`");


if($mycom == 0)
{
	echo '<div class="mess"><a href="index.php?act=add">Создать сообщества</a></div>';
}
else
{
	echo '<div class="mess"><a href="user.php?id='.$user['id'].'">Мои сообщества</a></div>';
}
echo '<div class="forum1"><strong>Категории:</strong><br />';
while($row = mysql_fetch_assoc($query))
{
	$result = mysql_result(mysql_query("select count(*) from `community` where `id_sel` = ".$row['id'].""),0);
	echo '<a href="index.php?act=selection&amp;id='.$row['id'].'">'.$row['title'].'</a> ('.$result.')<br />';
}
echo '</div>';
if ($user)
{
echo '<div class="where">В сообществах '.$soo.' человек</div>';
}
break;
case 'add':
$str['mesto'] = 'Создать сообщество';
$str['block'] = $set['site'].' / Сообщества';
include '../style/'.$style.'/head.php';
echo '<div class="where">Создать сообщество</div>';
if (isset($_GET['isset'])=='repeat')
{
	echo '<div class="mess">Такое сообщество уже существует!</div>';
}
if(isset($_POST['title']) and !empty($_POST['title']) and !empty($_POST['deviz']) and !empty($_POST['interests']) and !empty($_POST['opis']) and !empty($_POST['rules']) and !empty($_POST['enter']) and !empty($_POST['write']) and !empty($_POST['read']))
{
	$flood = mysql_fetch_assoc(mysql_query("select * from `community` where `id_maker` = ".$user['id']." order by `time` desc limit 1"));
    if($flood['time']<(time()-30))
    {
		$title = protect($_POST['title']);
		$deviz = protect($_POST['deviz']);
		$interests = protect($_POST['interests']);
		$opis = protect($_POST['opis']);
		$rules = protect($_POST['rules']);
		$enter = int($_POST['enter']);
		$read = int($_POST['read']);
		$write = int($_POST['write']);
		$sel = int($_POST['sel']);
		$repeat = mysql_query("select * from `community` WHERE `title` = '".$title."'");
		if (mysql_num_rows($repeat))
		{
			header ("Location: index.php?act=add&isset=repeat");
			exit;
		}
		$dir = '../community/files/'; //Папка в которую загружаем файл
		$file = protect(strtolower(basename($_FILES['files']['name'])));
		$image = array('jpg', 'jpeg', 'gif', 'png', 'bmp'); //Возможные форматы для загрузки
		$rand = rand(111111, 999999);
		if (isset($_FILES['files']) and !empty($_FILES['files']))
		{
			if (!in_array(pathinfo($file, PATHINFO_EXTENSION), $image))
			{
					mysql_query ("INSERT INTO `community` (id_maker,id_sel,title,deviz,interests,descript,rules,time,enter) VALUES (".$user['id'].",'".$sel."','".$title."','".$deviz."','".$interests."','".$opis."','".$rules."',".time().",".$enter.")") or die(mysql_error());
					$ins_id = mysql_insert_id();
					mysql_query("UPDATE `community` SET `read` = '".$read."' WHERE `id` = ".$ins_id."");
					mysql_query("UPDATE `community` SET `write` = '".$write."' WHERE `id` = ".$ins_id."");
					mysql_query("UPDATE `community` SET `logo` = '".$rand.'_'.$file."' WHERE `id` = ".$ins_id."");
					mysql_query ("INSERT INTO `community_users` (id_community,id_user) VALUES ('".$ins_id."','".$user['id']."')");
			}
			else
			{
				if (move_uploaded_file($_FILES['files']['tmp_name'], $dir.$rand.'_'.$file))
				{
					echo '<div class="forum1">Файл '.$file.' успешно загружен!<br />';
					mysql_query ("INSERT INTO `community` (id_maker,id_sel,title,deviz,interests,descript,rules,time,enter) VALUES (".$user['id'].",'".$sel."','".$title."','".$deviz."','".$interests."','".$opis."','".$rules."',".time().",".$enter.")") or die(mysql_error());
					$ins_id = mysql_insert_id();
					mysql_query("UPDATE `community` SET `read` = '".$read."' WHERE `id` = ".$ins_id."");
					mysql_query("UPDATE `community` SET `write` = '".$write."' WHERE `id` = ".$ins_id."");
					mysql_query("UPDATE `community` SET `logo` = '".$rand.'_'.$file."' WHERE `id` = ".$ins_id."");
					mysql_query ("INSERT INTO `community_users` (id_community,id_user) VALUES ('".$ins_id."','".$user['id']."')");
				}
			}
		}
		else
		{
			mysql_query ("INSERT INTO `community` (id_maker,id_sel,title,deviz,interests,descript,rules,time,enter) VALUES (".$user['id'].",'".$sel."','".$title."','".$deviz."','".$interests."','".$opis."','".$rules."',".time().",".$enter.")") or die(mysql_error());
			$ins_id = mysql_insert_id();
			mysql_query("UPDATE `community` SET `read` = '".$read."' WHERE `id` = ".$ins_id."");
			mysql_query("UPDATE `community` SET `write` = '".$write."' WHERE `id` = ".$ins_id."");
			mysql_query("UPDATE `community` SET `logo` = '".$rand.'_'.$file."' WHERE `id` = ".$ins_id."");
			mysql_query ("INSERT INTO `community_users` (id_community,id_user) VALUES ('".$ins_id."','".$user['id']."')");
		}
              mysql_query("update `users` set `balls`=`balls`+1 where `id` = ".$user['id']."");
	echo '<div class="on">Сообщество успешно создано!<br /><a href="index.php?act=view&amp;id='.$ins_id.'">Перейти &gt;&gt;</a></div>';
	break;
	}
    else
    {
        echo '<div class="where">&raquo; Антифлуд 30 секунд!</div>';
    }
}
echo '<div class="mess">
<form action="index.php?act=add" method="post" enctype="multipart/form-data">
<div>
Категория сообщества:<br/>
<select size="1" name="sel">';
$query = mysql_query("select * from `community_selections` order by `id`");
while($row = mysql_fetch_assoc($query))
{
 	echo '<option value="'.$row['id'].'">'.$row['title'].'</option>';
}
echo '</select><br/>
Название:<br/>
<input name="title" type="text" value=""/><br/>
Логотип:<br/>
<input name="files" type="file"/><br/>
Девиз:<br/>
<input name="deviz" type="text" value=""/><br/>
Интересы:<br/>
<input name="interests" type="text" value=""/><br/>
Описание:<br/>
<textarea cols="20" rows="2" name="opis"></textarea><br/>
Правила:<br/>
<textarea cols="20" rows="2" name="rules"></textarea><br/>
Вступление:<br/>
<select size="1" name="enter">
<option value="1">Открыто</option>
<option value="2">Модерация</option>
<option value="3">Закрыто</option>
</select><br/>
Читать могут:<br/>
<select size="1" name="read">
<option value="1">Все</option>
<option value="2">Только члены</option>
</select><br/>
Писать могут:<br/>
<select size="1" name="write">
<option value="1">Все</option>
<option value="2">Только члены</option>
</select><br/>
<input type="submit" value="Создать"/></div></form></div>';
break;
case 'selection':
$selection = mysql_fetch_assoc(mysql_query("select * from `community_selections` where `id` = ".int($_GET['id']).""));
$str['mesto'] = $selection['title'];
$str['block'] = $set['site'].' / Сообщества';
include '../style/'.$style.'/head.php';
echo '<div class="where"> '.$selection['title'].'</div>';
if(empty($selection['title']))
{
	echo '<div class="forum1">Раздел не найден!</div>';
	break;
}
$query = mysql_query("select * from `community` where `id_sel` = ".$selection['id']." order by `id` desc limit ".$page.",".$set['str']."");
$total = mysql_result(mysql_query("select count(*) from `community` where `id_sel` = ".$selection['id'].""),0);
if($total == 0)
{
	echo '<div class="forum1">Сообществ в данном разделе еще не созданы!</div>';
	break;
}
while($row = mysql_fetch_assoc($query))
{
	$i++;
	if($i%2)
	{
		echo '<div class="forum1">';
	}
	else
	{
		echo '<div class="forum2">';
	}
	$result = mysql_result(mysql_query("select count(*) from `community_users` where `id_community` = ".$row['id'].""),0);
	echo '<img class="ico" src="../style/'.$style.'/ico/'.$row['enter'].'.gif" alt="" /> <a href="index.php?act=view&amp;id='.$row['id'].'">'.$row['title'].'</a> ('.$result.') (<a href="forum.php?id='.$row['id'].'">Форум</a>)<br/>'.$row['deviz'].'</div>';
}
if($total > $set['str'])
{
	pages($page, $total, 'index.php?act=selection&amp;id='.$selection['id'].'&amp;', $set['str']);
}
break;
case 'view':
$query = mysql_fetch_assoc(mysql_query("select * from `community` where `id` = ".int($_GET['id']).""));
$selection = mysql_fetch_assoc(mysql_query("select * from `community_selections` where `id` = ".$query['id_sel'].""));
$str['mesto'] = $selection['title'];
$str['block'] = $set['site'].' / Сообщества';
include '../style/'.$style.'/head.php';
if(empty($query['title']))
{
	echo '<div class="forum1">Сообщество не найдено!</div>';
	break;
}
echo '
<div class="location"><b>'.$query['title'].'</b></div>
<div class="on">'.$query['deviz'].'</div>
<div class="location"><img class="ico" src="../style/'.$style.'/ico/'.$query['enter'].'.gif" alt="" /> (';
if($query['enter'] == 1)
{
	echo 'открыто для вступления)<br/>';
}
elseif($query['enter'] == 2)
{
	echo 'вступление после модерации)<br/>';
}
elseif($query['enter'] == 3)
{
	echo 'закрыто для вступления)<br/>';
}
if(!empty($query['logo']) and strlen($query['logo']) >= 8)
{
	echo '</div><div class="on"><img class="ico" src="files/'.$query['logo'].'" width="100" height="100" alt=""/><br/>';
}
$result = mysql_result(mysql_query("select count(*) from `community_users` where `id_community` = ".$query['id'].""),0);
if($user['id'] == $query['id_maker'] and $query['enter'] == 2)
{
	$count = mysql_result(mysql_query("select count(*) from `community_application` where `id_community` = ".$query['id'].""),0);
	echo '<a href="index.php?act=application&amp;id='.$query['id'].'">Заявки</a> ('.$count.')<br />';
}
echo '<a href="index.php?act=info&amp;id='.$query['id'].'">Информация</a><br/>
<a href="index.php?act=users&amp;id='.$query['id'].'">Участники ('.$result.')</a><br/>
<a href="forum.php?id='.$query['id'].'">Форум</a><br/>
<a href="chat.php?id='.$query['id'].'">Чат</a></div>';
$res = mysql_result(mysql_query("select count(*) from `community_users` where `id_community` = ".$query['id']." and `id_user` = ".$user['id'].""),0);
if($res == 0)
{
	echo '<div class="where"><a href="index.php?act=enter&amp;id='.$query['id'].'">Вступить в сообщество</a></div>';
}
else
{
	echo '<div class="where"><a href="index.php?act=exit&amp;id='.$query['id'].'">Выйти из сообщества</a></div>';
}
break;
case 'info':
$row = mysql_fetch_assoc(mysql_query("select * from `community` where `id` = ".int($_GET['id']).""));
$selection = mysql_fetch_assoc(mysql_query("select * from `community_selections` where `id` = ".$row['id_sel'].""));
$maker = mysql_fetch_assoc(mysql_query("select `login` from `users` where `id` = ".$row['id_maker'].""));
$str['mesto'] = $selection['title'];
$str['block'] = $set['site'].' / Сообщества';
include '../style/'.$style.'/head.php';
echo '<div class="where"> '.$selection['title'].' / '.$row['title'].' / Информация</div>';
if(empty($row['title']))
{
	echo '<div class="forum1">Сообщество не найдено!</div>';
	break;
}
echo '<div class="forum1">
<b>Название: </b>'.$row['title'].'<br/>
<b>Создано: </b>'.clock($row['time']).'<br/>
<b>Категория: </b><a href="index.php?act=selection&amp;id='.$selection['id'].'">'.$selection['title'].'</a><br/>
<b>Девиз: </b>'.$row['deviz'].'<br/>
<b>Интересы: </b>'.$row['interests'].'<br/>
<b>Описание: </b>'.$row['descript'].'<br/>
<b>Правила: </b>'.$row['rules'].'<br/>
<b>Создатель: </b><a href="../p/'.$maker['login'].'">'.$maker['login'].'</a><br/>
<b>Вступление: </b>';
if($row['enter'] == 1)
{
	echo 'открыто<br/>';
}
elseif($row['enter'] == 2)
{
	echo 'после модерации<br/>';
}
elseif($row['enter'] == 3)
{
	echo 'закрыто<br/>';
}
echo '<b>Читатели: </b>';
if($row['read'] == 1)
{
	echo 'все пользователи<br/>';
}
elseif($row['read'] == 2)
{
	echo 'только члены<br/>';
}
echo '<b>Писатели: </b>';
if($row['write'] == 1)
{
	echo 'все пользователи<br/>';
}
elseif($row['write'] == 2)
{
	echo 'только члены<br/>';
}
echo '</div>
<div class="on2">
<img class="ico" src="../style/'.$style.'/ico/newpost.png" alt="" /> <a href="index.php?act=view&amp;id='.$row['id'].'">'.$row['title'].'</a></div>';
break;
case 'users':
$row = mysql_fetch_assoc(mysql_query("select * from `community` where `id` = ".int($_GET['id']).""));
$selection = mysql_fetch_assoc(mysql_query("select * from `community_selections` where `id` = ".$row['id_sel'].""));
$str['mesto'] = $selection['title'];
$str['block'] = $set['site'].' / Сообщества ';
include '../style/'.$style.'/head.php';
echo '<div class="where"> '.$selection['title'].' / '.$row['title'].' / Пользователи</div>';
if(empty($row['title']))
{
	echo '<div class="forum1">Сообщество не найдено!</div>';
	break;
}
$query = mysql_query("select * from `community_users` where `id_community` = ".int($_GET['id'])." limit ".$page.",".$set['str']."");
$total = mysql_result(mysql_query("select count(*) from `community_users` where `id_community` = ".int($_GET['id']).""),0);
if($total == 0)
{
	echo '<div class="forum1">Пользователей еще нет!</div>';
}
while ($r = mysql_fetch_assoc($query))
{
	$i++;
	if($i%2)
	{
		echo '<div class="forum1">';
	}
	else
	{
		echo '<div class="forum2">';
	}
	$u = mysql_fetch_assoc(mysql_query("select * from `users` where `id` = ".$r['id_user'].""));
	echo '<img class="ico" src="../style/'.$style.'/ico/personal.gif" alt="" /> <a href="../p/'.$u['login'].'">'.$u['login'].'</a>'; 	if ($row['id_maker'] == $u['id']) { echo '<span style="color:#FFA500"> [Создатель]</span>'; } echo '<br />';
	echo '</div>';
}
if($total > $set['str'])
{
	pages($page, $total, 'index.php?act=users&amp;id='.$row['id'].'&amp;', $set['str']);
}
echo '<div class="on2">
<img class="ico" src="../style/'.$style.'/ico/newpost.png" alt="" /> <a href="index.php?act=view&amp;id='.$row['id'].'">'.$row['title'].'</a></div>';
break;
case 'enter':
$str['mesto'] = 'Вступить в сообщество';
$str['block'] = $set['site'].' / Сообщества';
include '../style/'.$style.'/head.php';
echo '<div class="where">Вступить в сообщество</div>';
$row = mysql_fetch_assoc(mysql_query("select * from `community` where `id` = ".int($_GET['id']).""));
if(empty($row['title']))
{
	echo '<div class="forum1">Сообщество не найдено!</div>';
	break;
}
$check = mysql_query("select * from `community_users` where `id_user` = ".$user['id']." and `id_community` = ".$row['id']."");
if (mysql_num_rows($check))
{
	echo '<div class="on">Вы уже состоите в данной группе!</div>';
	}
	else
	{
		if($row['enter'] == 2)
		{
			$chk = mysql_query("select * from `community_application` where `id_user` = ".$user['id']." and `id_community` = ".$row['id']."");
			if (mysql_num_rows($chk))
			{
				echo '<div class="on">Вы уже подавали заявку на вступление в данное сообщество!</div>';
				break;
			}
			else
			{
				mysql_query ("INSERT INTO `community_application` (id_community,id_user,time) VALUES ('".$row['id']."','".$user['id']."',".time().")");
				echo '<div class="on">Заявка на вступление в сообщество успешно подана!</div>';
				break;
			}
		}
		elseif($row['enter'] == 1)
		{
                                          mysql_query("update `users` set `balls`=`balls`+1 where `id` = ".$user['id']."");
			mysql_query ("INSERT INTO `community_users` (id_group,id_user) VALUES ('".$row['id']."','".$user['id']."')");
			echo '<div class="on">Вы успешно вступили в сообщество</div>';
			break;
		}
		elseif($row['enter'] == 3)
		{
			echo '<div class="on">Это закрытое сообщество! Вы не можете вступить в него!</div>';
			break;
		}
	}
break;

case 'exit':
$str['mesto'] = 'Выйти из сообщества';
$str['block'] = $set['site'].' / Сообщества';
include '../style/'.$style.'/head.php';
echo '<div class="where">Выйти из сообщества</div>';
$row = mysql_fetch_assoc(mysql_query("select * from `community` where `id` = ".int($_GET['id']).""));
$check = mysql_query("select * from `community_users` where `id_user` = ".$user['id']." and `id_community` = ".$row['id']."");
if (mysql_num_rows($check) > 0)
{
	echo '<div class="on">Вы успешно вышли из сообщества!</div>';
    mysql_query ("delete from `community_users` where `id_user` = ".$user['id']." and `id_community` = ".$row['id']."");
}
else
{
	echo '<div class="on">Вы не вступали в сообщество!</div>';
}
break;

case 'application':
$str['mesto'] = 'Заявки';
$str['block'] = $set['site'].' / Сообщества';
include '../style/'.$style.'/head.php';
echo '<div class="where">Заявки</div>';
$row = mysql_fetch_assoc(mysql_query("select * from `community` where `id` = ".int($_GET['id']).""));
if(empty($row['title']))
{
	echo '<div class="forum1">Сообщество не найдено!</div>';
	break;
}
if($row['id_maker'] != $user['id'])
{
	echo '<div class="forum1">Вы не автор сообщества!</div>';
	break;
}
if(isset($_GET['do']) and $_GET['do'] == 1)
{
	$chek = mysql_result(mysql_query("select count(*) from `community_application` where `id_user` = ".int($_GET['id_user']).""),0);
	if($chek == 0)
	{
		echo '<div class="on">Заявка не найдена!</div>';
		break;
	}
	mysql_query ("INSERT INTO `community_users` (id_community,id_user) VALUES ('".$row['id']."','".int($_GET['id_user'])."')");
	mysql_query ("delete from `community_application` where `id_user` = ".int($_GET['id_user'])." and `id_community` = ".$row['id']."");
	echo '<div class="on">Пользователь успешно принят в сообщество!</div>';
	break;
}
if(isset($_GET['do']) and $_GET['do'] == 2)
{
	$chek = mysql_result(mysql_query("select count(*) from `community_application` where `id_user` = ".int($_GET['id_user']).""),0);
	if($chek == 0)
	{
		echo '<div class="on">Заявка не найдена!</div>';
		break;
	}
	mysql_query ("delete from `community_application` where `id_user` = ".int($_GET['id_user'])." and `id_community` = ".$row['id']."");
	echo '<div class="on">Пользователь не принят в сообщество!</div>';
	break;
}
$query = mysql_query("select * from `community_application` where `id_community` = ".$row['id']."");
$total = mysql_result(mysql_query("select count(*) from `community_application` where `id_community` = ".$row['id'].""),0);
echo '<div class="forum1">';
if($total == 0)
{
	echo 'Заявок еще нет!</div>';
	break;
}
while($r = mysql_fetch_assoc($query))
{
	$suser = mysql_fetch_assoc(mysql_query("select `login` from `users` where `id` = ".$r['id_user'].""));
	echo $suser['login'].' <a href="index.php?act=application&amp;id='.$row['id'].'&amp;id_user='.$r['id_user'].'&amp;do=1">[принять]</a><a href="index.php?act=application&amp;id='.$row['id'].'&amp;id_user='.$r['id_user'].'&amp;do=2">[отклонить]</a>';
}
echo '</div>';
if ($total > $set['str'])
{
pages($page, $total, 'index.php?act=application&amp;id='.$row['id'].'&amp;', 10);
}
break;
case 'my':
$str['mesto'] = 'Сообщества';
$str['block'] = $set['site'].' / Сообщества';
include '../style/'.$style.'/head.php';
if($mycom == 0)
{
	echo '<div class="mess"><a href="index.php?act=add">Создать сообщества</a></div>';
}
else
{
	echo '<div class="mess"><a href="user.php?id='.$user['id'].'">Мои сообщества</a></div>';
}
$query = mysql_fetch_assoc(mysql_query("select `id`,`login` from `users` where `id` = '".int($_GET['id'])."'"));
if (!$query)
{
	echo '<div class="on">Пользователь не найден!</div>';
	include '../style/'.$style.'/foot.php';
	exit;
}
#Выводим группы
//берем список групп
$count = mysql_result(mysql_query("SELECT COUNT(*) FROM `community_users` WHERE `id_user` = ".$user['id']),0);
$group_r = mysql_query("SELECT * FROM `community_users` WHERE `id_user` =".$user['id']." ORDER BY `id` LIMIT ".$page.",".$set['str']."");
if(!mysql_num_rows($group_r)) echo '<div class="on">Пользователь не состоит в группе!</div>';
else
{
while($group_arr=mysql_fetch_assoc($group_r))
{
$group_info=mysql_fetch_assoc(mysql_query("SELECT * FROM `community` WHERE `id` = ".$group_arr['id_community']));
echo '<div class="forum1"><a href="?act=view&amp;id='.$group_info['id'].'">'.$group_info['title'].'</a></div>';
}
if ($total > $set['str'])
{
pages($page, $total, 'index.php?act=my&amp;id='.$u['id'].'&amp;', 10);
}
}
echo '<div class="on2"><img class="ico" src="../style/'.$style.'/ico/newpost.png" alt="" /> <a href="index.php">Всего сообщества</a> ('.$communitys.')</div>';
break;
}
echo '<hr>»<a href="../p/'.$user['login'].'">Моя страница</a> »<a href="index.php">Сообщества</a> »<a href="index.php?act=view&amp;id='.$query['id'].'">'.$query['title'].'</a>';
include '../style/'.$style.'/foot.php'; ?>