<?php
/** 
* @package		uForum2
* @file		inc/controllers/AdminController.class.php
* @copyright	2007-2015 (c) PioDer <piotrek@pioder.pl>
* @link    		http://www.pioder.pl/
* @license		see LICENSE.txt
**/

require ('./inc/controller.class.php');

class AdminController extends Controller
{

	public function loadDefault()
	{
		$this->main();
	}
	
	private function loadDependencies() // zależności (sesje itp)
	{
		$this->loadModel('SessionModel'); //aktywacja sesji
		$this->loadModel('ConfigModel'); //konfiguracja ogólna skryptu
		$this->loadView('MainView');
		$this->getView('MainView')->putExistingModel('SessionModel', $this->getModel('SessionModel'));
		$this->getView('MainView')->putExistingModel('ConfigModel', $this->getModel('ConfigModel'));
		
		if ($_SERVER['REQUEST_SCHEME'] == 'http')
			$this->forward(buildURL($_SERVER['REQUEST_URI']));
		
		if (!$this->getModel('SessionModel')->isLogged())
		{
			$this->getView('MainView')->forum_message('You are not logged.', 'index.php?mode=login', true);
			$lockv = true;
		}
		
		if ($this->getModel('SessionModel')->getRank() == RANK_USER && !isset($lockv))
		{
			$this->getView('MainView')->forum_message('You are not admin', 'index.php');
			$lockv = true;
		}
		
		if (!isset($lockv))
			return true;
		else
			return false;
	} 
		
	public function main()
	{
		if ($this->loadDependencies())
		{
			$this->getView('MainView')->admin_main();
		}
	}
	
	public function eduser()
	{
		if ($this->loadDependencies())
		{
			$this->loadModel('UsersModel');
			$user_info = $this->getModel('UsersModel')->getUserInformation($_GET['id'], true);
		
			if ($user_info == null)
			{
				$this->getView('MainView')->forum_message('User does not exist!', 'index.php?mode=admin&amp;submode=users'); 
				$lockv = true;
			}
			else
			{
				$msg = '';
				if (isset($_POST['nick'], $_POST['passwd'], $_POST['passwd_confirm'], $_POST['email']))
				{
					//secure pools
					$_POST['nick'] = trim(strip_tags($this->db->real_escape_string($_POST['nick'])));
					$_POST['passwd'] = trim($_POST['passwd']);
					$_POST['passwd_confirm'] = trim($_POST['passwd_confirm']);
					$_POST['email'] = trim(strip_tags($this->db->real_escape_string($_POST['email'])));
					$_POST['location'] = trim(htmlspecialchars($this->db->real_escape_string($_POST['location'])));
					$_POST['signature'] = trim(htmlspecialchars($this->db->real_escape_string($_POST['signature'])));
					$_POST['user_rank'] = trim(strip_tags($this->db->real_escape_string($_POST['user_rank'])));
		
					if ($_POST['passwd'] != '')
					{
						if (strlen($_POST['passwd']) < 8)
							$msg .= 'Password is too short (min 8 characters)<br>';	
						
						if ($_POST['passwd'] != $_POST['passwd_confirm'])
							$msg .= 'Password do not match!<br>';
					}
					
					if ($_GET['id'] == $this->getModel('SessionModel')->getID() && $_POST['user_rank'] != RANK_ADMIN)
					{
						$msg .= 'You cannot set rank for your profile<br>';
						$_POST['user_rank'] = RANK_ADMIN;
					}
					
					if ($this->getModel('UsersModel')->nickExists($_POST['nick']) == true && $_POST['nick'] != $user_info['nick'])
						$msg .= 'Nick is in use. Type another one.<br>';
						
					if (strlen($_POST['nick']) < 3)
						$msg .= 'Nick is too short (min 3 characters)<br>';	
					
					if ($_POST['user_rank'] > RANK_ADMIN || $_POST['user_rank'] < RANK_USER)
						$msg .= 'Rank is not valid!<br>';
					
					//check if avatar is uploaded
					if ($_FILES['avatar']['tmp_name'] != null)
					{
						global $allowed_avatars;
						$image_size = @getimagesize($_FILES['avatar']['tmp_name']);

						if ($image_size == null)
							$msg .= 'Type of uploaded file are not allowed.<br>';
						else
							if (!in_array($image_size['mime'], $allowed_avatars))
								$msg .= 'Type of uploaded avatar is not supported.<br>';
							else
								if ($image_size[0] > 120 || $image_size[1] > 150)
									$msg .= 'Uploaded avatar is too big (maximum 120x150 px).<br>';
					}
				
					if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
						$msg .= 'Email is incorrect<br>';
				
					if ($msg == '')
					{
						if ($_FILES['avatar']['tmp_name'] != null && !isset($_POST['delete_avatar'])) //change an avatar
						{
							if ($user_info['avatar'] != '')
								unlink('./'.$user_info['avatar']);
							
							$ext = pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION);
							$av = 'images/avatars/'.$this->getModel('SessionModel')->getID().'.'.$ext;
							move_uploaded_file($_FILES['avatar']['tmp_name'], './'.$av); 
						}
						else
							if (isset($_POST['delete_avatar']))
							{
								unlink('./'.$user_info['avatar']);
								$av = '';
							}
							else
								$av = $user_info['avatar']; //if new avatar is not set
					
						if ($_POST['passwd'] != '')
							$this->getModel('UsersModel')->changeUserPassword($_GET['id'], $user_info['nick'], $_POST['passwd']);
						
						$this->getModel('UsersModel')->changeUserRank($_GET['id'], $_POST['user_rank']);
						$this->getModel('UsersModel')->updateUserProfile($_GET['id'], $_POST['nick'], $_POST['email'], $_POST['location'], $_POST['signature'], $av);
						$this->getView('MainView')->forum_message('User profile has changed.', 'index.php?mode=admin&amp;submode=users');
						$lockv = true;

					}
				}			
			
				$_POST['nick'] = (isset($_POST['nick'])) ? stripslashes($_POST['nick']) : $user_info['nick'];
				$_POST['email'] = (isset($_POST['email'])) ? stripslashes($_POST['email']) : $user_info['email'];
				$_POST['location'] = (isset($_POST['location'])) ? stripslashes($_POST['location']) : $user_info['location'];
				$_POST['signature'] = (isset($_POST['signature'])) ? stripslashes($_POST['signature']) : $user_info['signature'];
				$_POST['user_rank'] = (isset($_POST['user_rank'])) ? $_POST['user_rank'] : $user_info['rank'];
	
				$this->getView('MainView')->putExistingModel('UsersModel', $this->getModel('UsersModel'));
		
				if (!isset($lockv))
					$this->getView('MainView')->edprofile_form($msg, true);
			}
		}
	}
	
	public function users()
	{
		if ($this->loadDependencies())
		{
			if (isset($_GET['rank']))
			{
				switch ($_GET['rank'])
				{
					case 'admin':
						$_GET['rank'] = RANK_ADMIN;
						break;
					case 'mod':
						$_GET['rank'] = RANK_MOD;
						break;
					case 'user':
						$_GET['rank'] = RANK_USER;
						break;
					default:
						$_GET['rank'] = '';
						break;
				}
			}
			else
				$_GET['rank'] = '';	
				
			$_POST['sort_type'] = (isset($_POST['sort_type'])) ? $this->db->real_escape_string($_POST['sort_type']) : 'regdate';
			$allowed_sorting = array('regdate', 'lastvisit', 'nick', 'post_count');
			if (!in_array($_POST['sort_type'], $allowed_sorting))
				$_POST['sort_type'] = '';
			$_POST['sort_desc'] = (isset($_POST['sort_desc'])) ? 'DESC' : 'ASC';
		
			$this->getView('MainView')->admin_userlist();
		}
		
	}
	
	public function deluser()
	{
		if ($this->loadDependencies())
		{
			$this->loadModel('UsersModel');
			$this->getView('MainView')->putExistingModel('UsersModel', $this->getModel('UsersModel'));
		
			$_GET['id'] = (isset($_GET['id'])) ? trim(strip_tags($this->db->real_escape_string($_GET['id']))) : 0;
		
			$user_info = $this->getModel('UsersModel')->getUserInformation($_GET['id']);
			if ($user_info == null)
			{
				$this->getView('MainView')->forum_message('User does not exist!', 'index.php?mode=admin&amp;submode=users'); 
				$lockv = true;
			}
			else
			{
				if ($_GET['id'] == $this->getModel('SessionModel')->getID())
				{
					$this->getView('MainView')->forum_message('You cannot delete own profile!', 'index.php?mode=admin&amp;submode=users'); 
					$lockv = true;
				}
			}
			

			if (isset($_POST['confirmed']) && !isset($lockv))
			{
				if (!isset($_POST['rejected']))
				{ 
					$this->getModel('UsersModel')->deleteUser($_GET['id']);
					if ($user_info['avatar'] != null) //delete user's avatar
						unlink('./'.$user_info['avatar']);
					$this->getView('MainView')->forum_message('Profile deleted. Redirecting to users list...', 'index.php?mode=admin&amp;submode=users'); 
					$lockv = true;
				}
				else
				{
					$this->forward('index.php?mode=admin&submode=users');
				}
			}
			
			if (!isset($lockv))
				$this->getView('MainView')->confirm_action('Do you want delete user <span style="font-weight: bold">'.$user_info['nick'].'</span>? This operation cannot undone.');
		}
	}
	
	public function config()
	{
		if ($this->loadDependencies())
		{
			$msg = '';
			
			if (isset($_POST['forum_name'], $_POST['forum_desc']))
			{
				$_POST['forum_name'] = trim(htmlspecialchars($this->db->real_escape_string($_POST['forum_name'])));
				$_POST['forum_desc'] = trim(htmlspecialchars($this->db->real_escape_string($_POST['forum_desc'])));
				
				if (strlen($_POST['forum_name']) < 3)
				{
					$msg .= 'Forum name is too short (min 3 characters)!<br>';
				}
				
				if (strlen($_POST['forum_name']) > 30)
				{
					$msg .= 'Forum name is too long (max 30 characters)!<br>';
				}
				
				if (strlen($_POST['forum_desc']) > 50)
				{
					$msg .= 'Forum description is too long (max 50 characters)!<br>';
				}
				
				if ($msg == '')
				{
					if ($_POST['forum_name'] !=  $this->getModel('ConfigModel')->getConf('forum_name'))
						$this->getModel('ConfigModel')->updateConf('forum_name', $_POST['forum_name']);
						
					if ($_POST['forum_desc'] !=  $this->getModel('ConfigModel')->getConf('forum_desc'))
						$this->getModel('ConfigModel')->updateConf('forum_desc', $_POST['forum_desc']);
					
					$this->getView('MainView')->forum_message('Forum configuration updated. Redirecting...', 'index.php?mode=admin&amp;submode=config'); 
					$lockv = true;
				}
			}
			
			$_POST['forum_name'] = (isset($_POST['forum_name'])) ? stripslashes($_POST['forum_name']) : $this->getModel('ConfigModel')->getConf('forum_name');
			$_POST['forum_desc'] = (isset($_POST['forum_desc'])) ? stripslashes($_POST['forum_desc']) : $this->getModel('ConfigModel')->getConf('forum_desc');
			if (!isset($lockv))
			{
				$this->getView('MainView')->admin_config($msg);
			}
		}
	}
	
	public function forums()
	{
		if ($this->loadDependencies())
		{
			$this->getView('MainView')->admin_forums();
		}
	}
	
	public function addcat()
	{
		if ($this->loadDependencies())
		{
			$this->modify_cat('add');
		}
	}
	
	public function edcat()
	{
		if ($this->loadDependencies())
		{
			$this->modify_cat('edit');
		}
	}
	
	public function addforum()
	{
		if ($this->loadDependencies())
		{
			$this->modify_forum('add');
		}
	}
	
	public function edforum()
	{
		if ($this->loadDependencies())
		{
			$this->modify_forum('edit');
		}
	}
	
	public function delforum()
	{
		if ($this->loadDependencies())
		{
			$this->loadModel('ForumsModel');
			$_GET['id'] = (isset($_GET['id'])) ? trim(strip_tags($this->db->real_escape_string($_GET['id']))) : 0;
			$forum_info = $this->getModel('ForumsModel')->getForum($_GET['id']);
			
			if ($forum_info == null)
			{
				$this->getView('MainView')->forum_message('Forum does not exist!', 'index.php?mode=admin&amp;submode=forums'); 
				$lockv = true;
			}

			if (isset($_POST['confirmed']) && !isset($lockv))
			{
				if (!isset($_POST['rejected']))
				{
					$this->getModel('ForumsModel')->deleteForum($_GET['id']);
					$this->getView('MainView')->forum_message('Forum deleted. Redirecting...', 'index.php?mode=admin&amp;submode=forums');
					$lockv = true;		
				}
				else
					$this->forward('index.php?mode=admin&submode=forums');
			}
			
			if (!isset($lockv))
				$this->getView('MainView')->confirm_action('Do you REALLY want delete forum <span style="font-weight: bold">'.$forum_info['name'].'</span> with ALL CONTENT? <span style="text-decoration: underline">This operation cannot undone!</span>');
		}
		
	}
	
	public function delcat()
	{
		if ($this->loadDependencies())
		{
			$this->loadModel('ForumsModel');
			$_GET['id'] = (isset($_GET['id'])) ? trim(strip_tags($this->db->real_escape_string($_GET['id']))) : 0;
			$cat_info = $this->getModel('ForumsModel')->getCat($_GET['id']);
			
			if ($cat_info == null)
			{
				$this->getView('MainView')->forum_message('Category does not exist!', 'index.php?mode=admin&amp;submode=forums'); 
				$lockv = true;
			}

			if (isset($_POST['confirmed']) && !isset($lockv))
			{
				if (!isset($_POST['rejected']))
				{
					$this->getModel('ForumsModel')->deleteCat($_GET['id']);
					$this->getView('MainView')->forum_message('Category deleted. Redirecting...', 'index.php?mode=admin&amp;submode=forums');
					$lockv = true;		
				}
				else
					$this->forward('index.php?mode=admin&submode=forums');
			}
			
			if (!isset($lockv))
				$this->getView('MainView')->confirm_action('Do you REALLY want delete category <span style="font-weight: bold">'.$cat_info['name'].'</span> with ALL FORUMS AND CONTENT? <span style="text-decoration: underline">This operation cannot undone!</span>');
		}
		
	}
	
	private function modify_cat($m)
	{
		$msg = '';
		
		$this->loadModel('ForumsModel');
		
		if ($m == 'edit')
		{
			$_GET['id'] = (isset($_GET['id'])) ? trim(strip_tags($this->db->real_escape_string($_GET['id']))) : 0;
			$cat_info = $this->getModel('ForumsModel')->getCat($_GET['id']);
			
			if ($cat_info == null)
			{
				$this->getView('MainView')->forum_message('Category does not exist!', 'index.php?mode=admin&amp;submode=forums'); 
				$lockv = true;
			}
		}
		
		
		if (isset($_POST['name']) && !isset($lockv))
		{
			$_POST['name'] = trim(htmlspecialchars($this->db->real_escape_string($_POST['name'])));
			if (strlen($_POST['name']) < 3)
				$msg .= 'Category name is too short (min 3 characters)!<br>';
			
			if ($msg == '')
			{
				if ($m == 'add')
				{
					$this->getModel('ForumsModel')->addCat($_POST['name']);
					$this->getView('MainView')->forum_message('Category added. Redirecting...', 'index.php?mode=admin&amp;submode=forums'); 
					$lockv = true;
				}	
				else
				{
					$this->getModel('ForumsModel')->changeCat($_GET['id'], $_POST['name']);
					$this->getView('MainView')->forum_message('Category updated. Redirecting...', 'index.php?mode=admin&amp;submode=forums'); 
					$lockv = true;
				}
			}
		}
		
		if (!isset($lockv))
		{
			if ($m == 'add')
				$_POST['name'] = (isset($_POST['name'])) ? stripslashes($_POST['name']) : '';
			else
				$_POST['name'] = (isset($_POST['name'])) ? stripslashes($_POST['name']) : $cat_info['name'];
				
			$this->getView('MainView')->putExistingModel('ForumsModel', $this->getModel('ForumsModel'));
			$this->getView('MainView')->admin_cat_form($msg, $m);
		}
	}
	
	private function modify_forum($m)
	{
		$msg = '';
		
		$this->loadModel('ForumsModel');
		
		if ($m == 'edit')
		{
			$_GET['id'] = (isset($_GET['id'])) ? trim(strip_tags($this->db->real_escape_string($_GET['id']))) : 0;
			$forum_info = $this->getModel('ForumsModel')->getForum($_GET['id']);
			
			if ($forum_info == null)
			{
				$this->getView('MainView')->forum_message('Forum does not exist!', 'index.php?mode=admin&amp;submode=forums'); 
				$lockv = true;
			}
		}
		
		
		if (isset($_POST['name']) && !isset($lockv))
		{
			$_POST['name'] = trim(htmlspecialchars($this->db->real_escape_string($_POST['name'])));
			$_POST['desc'] = trim(htmlspecialchars($this->db->real_escape_string($_POST['desc'])));
			$_POST['category_id'] = trim(strip_tags($this->db->real_escape_string($_POST['category_id'])));
			$_POST['locked'] = trim(strip_tags($this->db->real_escape_string($_POST['locked'])));
			$_POST['locked'] = ($_POST['locked'] == true) ? true : false;
			
			if (strlen($_POST['name']) < 3)
				$msg .= 'Forum name is too short (min 3 characters)!<br>';
			
			$c = $this->getModel('ForumsModel')->getCat($_POST['category_id']);
			
			if ($c == null)
				$msg .= 'Category does not exist!<br>';
			
			if ($msg == '')
			{
				if ($m == 'add')
				{
					$this->getModel('ForumsModel')->addForum($_POST['name'], $_POST['desc'], $_POST['category_id'], $_POST['locked']);
					$this->getView('MainView')->forum_message('Forum added. Redirecting...', 'index.php?mode=admin&amp;submode=forums'); 
					$lockv = true;
				}	
				else
				{
					$this->getModel('ForumsModel')->changeForum($_GET['id'], $_POST['name'], $_POST['desc'], $_POST['category_id'], $_POST['locked']);
					$this->getView('MainView')->forum_message('Forum updated. Redirecting...', 'index.php?mode=admin&amp;submode=forums'); 
					$lockv = true;
				}
			}
		}
		
		if (!isset($lockv))
		{
			if ($m == 'add')
			{
				$_POST['name'] = (isset($_POST['name'])) ? stripslashes($_POST['name']) : '';
				$_POST['desc'] = (isset($_POST['desc'])) ? stripslashes($_POST['desc']) : '';
				$_POST['category_id'] = (isset($_POST['category_id'])) ? $_POST['category_id'] : '';
				$_POST['locked'] = (isset($_POST['locked'])) ? $_POST['locked'] : '';
			}
			else
			{
				$_POST['name'] = (isset($_POST['name'])) ? stripslashes($_POST['name']) : $forum_info['name'];
				$_POST['desc'] = (isset($_POST['desc'])) ? stripslashes($_POST['desc']) : $forum_info['desc'];
				$_POST['category_id'] = (isset($_POST['category_id'])) ? $_POST['category_id'] : $forum_info['category_id'];
				$_POST['locked'] = (isset($_POST['locked'])) ? $_POST['locked'] : $forum_info['locked'];
			}
				
			$this->getView('MainView')->putExistingModel('ForumsModel', $this->getModel('ForumsModel'));
			$this->getView('MainView')->admin_forum_form($msg, $m);
		}
	}
	
	public function banlist()
	{
		if ($this->loadDependencies())
			$this->getView('MainView')->admin_banlist();
	}
	
	public function delban()
	{
		if ($this->loadDependencies())
		{
			$this->loadModel('BansModel');
			$_GET['id'] = (isset($_GET['id'])) ? trim(strip_tags($this->db->real_escape_string($_GET['id']))) : 0;
			$ban_info = $this->getModel('BansModel')->getBan($_GET['id']);
			
			if ($ban_info == null)
			{
				$this->getView('MainView')->forum_message('Ban does not exist!', 'index.php?mode=admin&amp;submode=banlist'); 
				$lockv = true;
			}

			if (isset($_POST['confirmed']) && !isset($lockv))
			{
				if (!isset($_POST['rejected']))
				{
					$this->getModel('BansModel')->deleteBan($_GET['id']);
					$this->getView('MainView')->forum_message('Ban deleted. Redirecting...', 'index.php?mode=admin&amp;submode=banlist');
					$lockv = true;		
				}
				else
					$this->forward('index.php?mode=admin&submode=banlist');
			}
			
			if (!isset($lockv))
				$this->getView('MainView')->confirm_action('Do you want delete ban for user <span style="font-weight: bold">'.$ban_info['nick'].'</span>?');
		}
		
	}
	
	public function addban()
	{
		if ($this->loadDependencies())
		{
			$msg = '';
		
			$this->loadModel('BansModel');
			$this->loadModel('UsersModel');
		
			if (isset($_POST['user_id'], $_POST['reason']))
			{
				$_POST['user_id'] = trim(strip_tags($this->db->real_escape_string($_POST['user_id'])));
				$_POST['reason'] = trim(htmlspecialchars($this->db->real_escape_string($_POST['reason'])));

				if ($_POST['user_id'] == $this->getModel('SessionModel')->getID())
					$msg .= 'You cannot ban your profile!<br>';
				
				if ($this->getModel('BansModel')->getUserBan($_POST['user_id']) != null)
					$msg .= 'This user has already been banned!<br>';
					
				if ($this->getModel('UsersModel')->getUserInformation($_POST['user_id']) == null)
					$msg .= 'User does not exist!<br>';
			
				if ($msg == '')
				{
					$this->getModel('BansModel')->addBan($_POST['user_id'], $_POST['reason']);
					$this->getView('MainView')->forum_message('Ban added. Redirecting...', 'index.php?mode=admin&amp;submode=banlist'); 
					$lockv = true;
				}
			}
		
			if (!isset($lockv))
			{
				$_POST['user_id'] = (isset($_POST['user_id'])) ? $_POST['user_id'] : '';
				$_POST['reason'] = (isset($_POST['reason'])) ? stripslashes($_POST['reason']) : '';
					
				$this->getView('MainView')->admin_ban_form($msg);
			}
		}
	}
}
?>