<?php
/**
* @version 1.0.0
* @package RStickets! 1.0.0
* @copyright (C) 2007-2008 www.rsjoomla.com
* @license GPL, http://www.gnu.org/copyleft/gpl.html
*/

// DIE()
defined('_JEXEC') or die('Restricted access');

// CLEAN A STRING SO AN ATTACKER CAN'T COMPROMISE IT
function rst_clean($string, $html=true)
{
	$db = JFactory::getDBO();
	if (!is_array($string))
	{
		$string = $html ? htmlentities($string,ENT_QUOTES,'UTF-8') : $string;
		$string = get_magic_quotes_gpc() ? $db->getEscaped(stripslashes($string)) : $db->getEscaped($string);
			
		return $string;
	}
	else
		return $string;
}

// CONVERT ENCODING
function rst_convert_encoding($string)
{
	if (!function_exists('mb_convert_encoding')) return $string;
	return mb_convert_encoding($string,'UTF-8');
}

// CHECK IF A STAFF MEMBER IS LOGGED IN
function rst_is_staff_logged()
{
	return (isset($_SESSION['RST_User']['UserId']) && isset($_SESSION['RST_User']['Group']['GroupId']));
}

// CHECK IF A CUSTOMER IS LOGGED IN
function rst_is_customer_logged()
{
	return (isset($_SESSION['RST_User']['UserId']) && !isset($_SESSION['RST_User']['Group']['GroupId']));
}

// CHECK IF SOMEBODY IS LOGGED IN
function rst_is_logged()
{
	return (isset($_SESSION['RST_User']['UserId']));
}

// PARSE LINKS SO THEY ARE CLICKABLE
function rst_parse_links($string)
{
	$string = str_replace('&amp;','&',$string);
	$string = eregi_replace('(((f|ht){1}tps?://)[-a-zA-Z0-9@:%_\+.,~#?&//=]+)', '<a href="\\1" target="_blank">\\1</a>', $string);
	// old
	// $string = eregi_replace('([[:space:]]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1<a href="http://\\2" target="_blank">\\2</a>', $string);
	// new
	   $string = eregi_replace('([[:space:]]{1,})(www.[-a-zA-Z0-9@:%_\+.,~#?&//=]+)', '\\1<a href="http://\\2" target="_blank">\\2</a>', $string);
	$string = eregi_replace('([_\.0-9a-z-]+@([0-9a-z.][0-9a-z.-]+\.)+[a-z]{2,4})', '<a href="mailto:\\1">\\1</a>', $string);
	return $string; 
}

// RESET SEARCH TIKCETS
function reset_search_tickets($what)
{
	$what = 'search_'.$what;
	$_SESSION[$what]['TicketCode'] = '';
	$_SESSION[$what]['TicketSubject'] = '';
	$_SESSION[$what]['TicketMessage'] = '';
	$_SESSION[$what]['TicketTime'] = '';
	$_SESSION[$what]['from'] = '';
	$_SESSION[$what]['to'] = '';
	$departments = array();
	if (isset($_SESSION['RST_User']['Department']) && count($_SESSION['RST_User']['Department']) > 0)
		foreach ($_SESSION['RST_User']['Department'] as $department)
			$departments[] = $department['DepartmentId'];
	elseif (rst_is_customer_logged())
	{
		$departments_array = rst_get_departments();
		foreach ($departments_array as $department)
			$departments[] = $department['DepartmentId'];
	}
	$_SESSION[$what]['DepartmentId'] = $departments;
	$_SESSION[$what]['TicketStatus'] = array('open','on-hold');
	$_SESSION[$what]['TicketPriority'] = array('low','normal','high');
	// CUSTOMER
	$_SESSION[$what]['CustomerUsername'] = '';
	$_SESSION[$what]['CustomerFullname'] = '';
	$_SESSION[$what]['CustomerEmail'] = '';
	// STAFF
	$_SESSION[$what]['StaffUsername'] = '';
	$_SESSION[$what]['StaffFullname'] = '';
	$_SESSION[$what]['StaffEmail'] = '';
	$_SESSION[$what]['predefined'] = '';
	return 1012;
}

// LOGIN
function rst_login(/*$username,$password*/)
{
	rst_logout();
	$RST_adapter = $GLOBALS['RST_adapter'];
	
	$my = $RST_adapter->user();
	
	//`#__users`.`Username`='".$username."' AND `#__users`.`Password`='".$password."'
	
	$db = JFactory::getDBO();
	
	if (!empty($my['id']))
	{
		// GET USER DETAILS
		$_SESSION['RST_User']['UserId'] = $my['id'];
		$_SESSION['RST_User']['Fullname'] = $my['name'];
		$_SESSION['RST_User']['Username'] = $my['username'];
		$_SESSION['RST_User']['Email'] = $my['email'];
		
		//ADMIN
		$_SESSION['RST_User']['Admin'] = $my['admin'];
		
		// GET GROUP DETAILS
		$db->setQuery("SELECT * FROM `#__rstickets_staff` INNER JOIN `#__rstickets_groups` ON (`#__rstickets_staff`.`GroupId`=`#__rstickets_groups`.`GroupId`) WHERE `#__rstickets_staff`.`UserId`='".$_SESSION['RST_User']['UserId']."'");
		$_SESSION['RST_User']['Group'] = $db->loadAssoc();
		if (empty($_SESSION['RST_User']['Group']['GroupId']) && $_SESSION['RST_User']['Admin'] == 1)
		{
			$_SESSION['RST_User']['Group']['GroupId'] = 1;
			$_SESSION['RST_User']['Group']['GroupName'] = 'Administrator';
			$_SESSION['RST_User']['Group']['CanAddTicket'] = 1;
			$_SESSION['RST_User']['Group']['CanAddTicketUsers'] = 1;
			$_SESSION['RST_User']['Group']['CanAddTicketStaff'] = 1;
			$_SESSION['RST_User']['Group']['CanUpdateTicket'] = 1;
			$_SESSION['RST_User']['Group']['CanDeleteTicket'] = 1;
			$_SESSION['RST_User']['Group']['CanAnswerTicket'] = 1;
			$_SESSION['RST_User']['Group']['CanDeleteTicketReplies'] = 1;
			$_SESSION['RST_User']['Group']['CanUpdateTicketReplies'] = 1;
			$_SESSION['RST_User']['Group']['CanAssignTickets'] = 1;
			$_SESSION['RST_User']['Group']['CanChangeTicketStatus'] = 1;
			$_SESSION['RST_User']['Group']['CanSeeUnallocatedTickets'] = 1;
			$_SESSION['RST_User']['Group']['CanSeeOtherTickets'] = 1;
			$_SESSION['RST_User']['Group']['CanMoveTicket'] = 1;
			/*
			$_SESSION['RST_User']['Group']['CanAddTicketNote'] = 1;
			$_SESSION['RST_User']['Group']['CanUpdateTicketNote'] = 1;
			$_SESSION['RST_User']['Group']['CanDeleteTicketNote'] = 1;
			*/
		}
		// GET DEPARTMENT DETAILS
		if ($_SESSION['RST_User']['Admin'] == 1)
			$db->setQuery("SELECT * FROM `#__rstickets_departments`");
		else
			$db->setQuery("SELECT * FROM `#__rstickets_staff_to_department` INNER JOIN `#__rstickets_departments` ON (`#__rstickets_departments`.`DepartmentId`=`#__rstickets_staff_to_department`.`DepartmentId`) WHERE `#__rstickets_staff_to_department`.`UserId`='".$_SESSION['RST_User']['UserId']."'");
			
		$rows = $db->loadAssocList();
		foreach ($rows as $row)
		{
			$row['FileUploadExtensions'] = explode("\n",$row['FileUploadExtensions']);
			foreach ($row['FileUploadExtensions'] as $index => $ext)
				$row['FileUploadExtensions'][$index] = trim($ext);
			$_SESSION['RST_User']['Department'][] = $row;
		}
		
		if (isset($_SESSION['RST_User']['Group']['GroupId']))
		{
			$db->setQuery("SELECT `SearchId` FROM `#__rstickets_searches` WHERE `UserId`='".$_SESSION['RST_User']['UserId']."' AND `SearchType`='tickets' AND `SearchDefault`='1'");
			$searchid = $db->loadResult();
			if (!empty($searchid))
				rst_predefined_search($searchid, true);
			
			$db->setQuery("SELECT `SearchId` FROM `#__rstickets_searches` WHERE `UserId`='".$_SESSION['RST_User']['UserId']."' AND `SearchType`='my_tickets' AND `SearchDefault`='1'");
			$searchid = $db->loadResult();
			if (!empty($searchid))
				rst_predefined_search($searchid, true);
		}
	}
	else
		return 3; // USERNAME & PASSWORD INCORRECT
}

// LOGOUT
function rst_logout()
{
	if (isset($_SESSION['RST_User']['UserId']))
	{
		$_SESSION['RST_User'] = array();
		unset($_SESSION['RST_User']);
	}
	if (isset($_SESSION['search_tickets']))
	{
		$_SESSION['search_tickets'] = array();
		unset($_SESSION['search_tickets']);
	}
	if (isset($_SESSION['search_my_tickets']))
	{
		$_SESSION['search_my_tickets'] = array();
		unset($_SESSION['search_my_tickets']);
	}
}

// REDIRECT
function rst_redirect($url, $sec=0)
{
	global $mainframe;
	$mainframe->redirect(JRoute::_($url, false));
}

function rst_admin_redirect($url, $sec=0)
{
	$RST_adapter = $GLOBALS['RST_adapter'];
	if(isset($sec) && is_numeric($sec) && $sec > 0)
	{
		header("Refresh: ".$sec."; url=".RST_BACKEND_SCRIPT_PATH.$url);
		ob_end_flush();
	}
	else
	{
		header("Location: ".RST_BACKEND_SCRIPT_PATH.$url);
		ob_end_flush();
		die;
	}
}

function rst_is_searching($search)
{
	// CHECK IF THESE ARE THE RESULTS OF A SEARCH
	$searching = false;
	
	if ($_SESSION[$search]['TicketCode'] != '' || $_SESSION[$search]['TicketSubject'] != '' || $_SESSION[$search]['TicketMessage'] != '' || $_SESSION[$search]['CustomerUsername'] != '' || $_SESSION[$search]['CustomerFullname'] != '' || $_SESSION[$search]['CustomerEmail'] != '' || $_SESSION[$search]['StaffUsername'] != '' || $_SESSION[$search]['StaffFullname'] != '' || $_SESSION[$search]['StaffEmail'] != '' || $_SESSION[$search]['from'] != '' || $_SESSION[$search]['to'] != '')
		$searching = true;
		
	if (count($_SESSION[$search]['TicketPriority']) != 3)
		$searching = true;
	
	//if ((!in_array('open',$_SESSION[$search]['TicketStatus']) || !in_array('on-hold',$_SESSION[$search]['TicketStatus'])) && in_array('closed',$_SESSION[$search]['TicketStatus']))
	//	$searching = true;
		
	if (!in_array('open',$_SESSION[$search]['TicketStatus']) || !in_array('on-hold',$_SESSION[$search]['TicketStatus']))
		$searching = true;
	
	$departments = (!isset($_SESSION['RST_User']['Group']['GroupId']) ? rst_get_departments() : (isset($_SESSION['RST_User']['Department']) && count($_SESSION['RST_User']['Department']) > 0 ? $_SESSION['RST_User']['Department'] : array()));
	$departments_array = array();
	
	$verified = array();
	
	if (count($departments) > 0)
		foreach ($departments as $department)
			foreach ($_SESSION[$search]['DepartmentId'] as $departmentsearching)
				if ($departmentsearching == $department['DepartmentId'])
					$verified[] = '1';
	
	if (in_array(0,$_SESSION[$search]['DepartmentId']))
		$searching = true;
	elseif (count($verified) != count($departments))
		$searching = true;
	
	return $searching;
}

// CHECK IF THE USER CAN SEE ALL TICKETS
function rst_can_see_all()
{
	return ($_GET['page'] == 'tickets' && rst_is_staff_logged() && $_SESSION['RST_User']['Group']['CanSeeUnallocatedTickets'] == 1 && $_SESSION['RST_User']['Group']['CanSeeOtherTickets'] == 1);
}

// CHECK IF CLOSED TICKETS ARE SHOWN
function rst_show_closed_tickets($search)
{
	return (in_array('closed',$_SESSION[$search]['TicketStatus']));
}

function rst_save_search($what,$id=0,$userid,$name,$default=0)
{
	$db = JFactory::getDBO();
	
	$what = rst_clean($what);
	$id = intval($id);
	$userid = intval($userid);
	$name = rst_clean($name);
	$default = intval($default);
	$saved_search = '';
	foreach ($_SESSION['search_'.$what] as $item => $value)
	{
		if (is_array($value))
			$saved_search .= $item."=".implode(',',$value)."||\n";
		else
			$saved_search .= $item."=".$value."||\n";
	}
	if ($default)
	{
		$db->setQuery("UPDATE `#__rstickets_searches` SET `SearchDefault`='0' WHERE `UserId`='".$userid."' AND `SearchType`='".$what."'");
		$db->query();
	}
		
	if ($id > 0)
		$db->setQuery("UPDATE `#__rstickets_searches` SET `SearchName`='".$name."',`SearchDefault`='".$default."' WHERE `UserId`='".$userid."' AND `SearchType`='".$what."' AND `SearchId`='".$id."' LIMIT 1");
	else
		$db->setQuery("INSERT INTO `#__rstickets_searches` SET `UserId`='".$userid."',`SearchType`='".$what."',`SearchName`='".$name."',`SearchParameters`='".$saved_search."',`SearchDefault`='".$default."'");
	$db->query();

	if ($db->getAffectedRows() == 1)
		return 1029;
}

function rst_get_searches($what,$userid,$strict=false)
{
	$db = JFactory::getDBO();
	
	$userid = intval($userid);
	$what = rst_clean($what);
	
	$db->setQuery("SELECT `SearchId`,`SearchName`,`SearchDefault`,`SearchType` FROM `#__rstickets_searches` WHERE `SearchType`='".$what."' AND `UserId`='".$userid."' ".($strict != false ? " OR `UserId`='0'" : ""));
	$return = $db->loadAssocList();
	
	return $return;
}

function rst_get_search($id)
{
	$db = JFactory::getDBO();
	
	$id = intval($id);
	$db->setQuery("SELECT * FROM `#__rstickets_searches` WHERE `SearchId`='".$id."' LIMIT 1");
	$row = $db->loadAssoc();
	if (count($row) == 0) return array();
	if ($row['UserId'] > 0 && $_SESSION['RST_User']['UserId'] != $row['UserId']) return array();
	return $row;
}

function rst_delete_search($id)
{
	$db = JFactory::getDBO();
	
	$id = intval($id);
	$getsearch = rst_get_search($id);
	if (count($getsearch) > 0)
	{
		$db->setQuery("DELETE FROM `#__rstickets_searches` WHERE `SearchId`='".$id."' LIMIT 1");
		$db->query();
		if ($db->getAffectedRows() == 1)
			return 1030;
	}
}

function rst_predefined_search($id,$noredirect=false)
{
	$db = JFactory::getDBO();
	
	$id = intval($id);
	$db->setQuery("SELECT * FROM `#__rstickets_searches` WHERE `SearchId`='".$id."' LIMIT 1");
	$row = $db->loadAssoc();
	
	if (count($row) == 0) return;
	if ($row['UserId'] > 0 && $_SESSION['RST_User']['UserId'] != $row['UserId']) return;
	
	$parameters = explode("||\n",$row['SearchParameters']);
	if (count($parameters) == 0) return;
	
	// CLEAN THE LAST PARAMETER - WHICH IS USUALLY EMPTY
	if ($parameters[count($parameters) - 1] == '') array_pop($parameters);
	
	$session = array();
	
	foreach ($parameters as $parameter)
	{
		$pos = strpos($parameter,'=');
		$session[substr($parameter,0,$pos)] = substr($parameter,$pos+1);
	}
	
	if (count($session) > 0)
		foreach ($session as $sessionitem => $sessionvalue)
			switch ($sessionitem)
			{
				case 'DepartmentId':
				case 'TicketStatus':
				case 'TicketPriority':
				$values = explode(',',$sessionvalue);
				$_SESSION['search_'.$row['SearchType']][$sessionitem] = $values;
				break;
				default:
				$_SESSION['search_'.$row['SearchType']][$sessionitem] = $sessionvalue;
				break;
			}
	$_SESSION['search_'.$row['SearchType']]['predefined'] = $id;
	
	if ($noredirect == false)
		rst_redirect('index.php?option=com_rstickets&page='.$row['SearchType']);
		
	
}

// GENERATE MENU BASED ON USER PRIVILEGES
function rst_gen_menu()
{
	global $T_SETTINGS;
	if ($T_SETTINGS['RStickets_Show_Menu'] == 0) return;
	$return = '';
	// ADMIN MENU
	$admin = array(
		array('title' => LBL_TICKETS, 'link' => 'index.php?option=com_rstickets&page=tickets'),
		array('title' => LBL_MY_TICKETS, 'link' => 'index.php?option=com_rstickets&page=my_tickets')
	);
	if (rst_is_staff_logged() && ($_SESSION['RST_User']['Group']['CanAddTicket'] == 1 || $_SESSION['RST_User']['Group']['CanAddTicketUsers'] == 1 || $_SESSION['RST_User']['Group']['CanAddTicketStaff'] == 1))
		$admin[] = array('title' => LBL_SUBMIT_TICKET, 'link' => 'index.php?option=com_rstickets&page=add_ticket');
	
	// STAFF MENU
	$staff = array(
		array('title' => LBL_TICKETS, 'link' => 'index.php?option=com_rstickets&page=tickets'),
		array('title' => LBL_MY_TICKETS, 'link' => 'index.php?option=com_rstickets&page=my_tickets')
	);
	if (rst_is_staff_logged() && ($_SESSION['RST_User']['Group']['CanAddTicket'] == 1 || $_SESSION['RST_User']['Group']['CanAddTicketUsers'] == 1 || $_SESSION['RST_User']['Group']['CanAddTicketStaff'] == 1))
		$staff[] = array('title' => LBL_SUBMIT_TICKET, 'link' => 'index.php?option=com_rstickets&page=add_ticket');
	
	// USER MENU
	$user = array(
		array('title' => LBL_MY_TICKETS, 'link' => 'index.php?option=com_rstickets&page=my_tickets'),
		array('title' => LBL_SUBMIT_TICKET, 'link' => 'index.php?option=com_rstickets&page=add_ticket')
	);
	
	// NOT LOGGED IN MENU
	$notlogin = array(
		array('title' => LBL_SUBMIT_TICKET, 'link' => 'index.php?option=com_rstickets&page=add_ticket')
	);
	
	if (rst_is_logged())
	{
		if ($_SESSION['RST_User']['Admin'] == 1) $menu = $admin;
		elseif (rst_is_staff_logged()) $menu = $staff;
		else $menu = $user;
	}
	else $menu = $notlogin;
	
	foreach ($menu as $item)
	{
		$return .= '<li '.(strpos($item['link'],'page='.$_GET['page']) !== false ? 'class="active"' : '').'><a href="'.JRoute::_($item['link']).'" title="'.$item['title'].'">'.$item['title'].'</a></li>';
	}
	return '<ul id="rst_menu">'.$return.'</ul>';
}

// GET DEPARTMENTS
function rst_get_departments($id=0)
{
	$db = JFactory::getDBO();
	
	$id = intval($id);
	$db->setQuery("SELECT * FROM `#__rstickets_departments` ".($id > 0 ? "WHERE `DepartmentId`='".$id."'" : "")." ORDER BY `DepartmentOrder` ASC");
	$rows = $db->loadAssocList();
	$return = array();
	foreach ($rows as $row)
	{
		$row['FileUploadExtensions'] = explode("\n",$row['FileUploadExtensions']);
		foreach ($row['FileUploadExtensions'] as $index => $ext)
			$row['FileUploadExtensions'][$index] = trim($ext);
		$return[] = $row;
	}
	
	return $return;
}

function rst_order_department($id,$direction)
{
	$db = JFactory::getDBO();
	
	$id = intval($id);
	$direction = $direction == 'up' ? 'up' : 'down';
	$department = rst_get_departments($id);
	$department = $department[0];
	if ($department['DepartmentOrder'] == 1 && $direction == 'up') return;
	
	$neworder = ($direction == 'up' ? $department['DepartmentOrder']-1 : $department['DepartmentOrder']+1);
	
	$db->setQuery("SELECT `DepartmentId` FROM `#__rstickets_departments` WHERE `DepartmentOrder`='".$neworder."' LIMIT 1");
	$oldid = $db->loadResult();
	
	$db->setQuery("UPDATE `#__rstickets_departments` SET `DepartmentOrder`='".$neworder."' WHERE `DepartmentId`='".$id."'");
	$db->query();
	
	if ($oldid > 0)
	{
		$db->setQuery("UPDATE `#__rstickets_departments` SET `DepartmentOrder`='".$department['DepartmentOrder']."' WHERE `DepartmentId`='".$oldid."'");
		$db->query();
	}
}

function rst_add_department($id=0,$name,$prefix,$assign,$genrule,$priority,$useremail,$staffemail,$fileupload,$fileuploadext,$notifynewticketemails,$notifyassign)
{
	$db = JFactory::getDBO();
	
	$id = intval($id);
	$name = rst_clean($name);
	$prefix = strtoupper(rst_clean($prefix));
	$assign = rst_clean($assign);
	$genrule = rst_clean($genrule);
	$priority_array = array('low','normal','high');
	if (!in_array($priority,$priority_array)) $priority = 'normal';
	$useremail = intval($useremail);
	$staffemail = intval($staffemail);
	$fileupload_array = array('yes','users','no');
	if (!in_array($fileupload,$fileupload_array)) $fileupload = 'yes';
	$fileuploadext = rst_clean($fileuploadext);
	$notifynewticketemails = rst_clean($notifynewticketemails);
	$notifyassign = intval($notifyassign);
	
	if (!isset($name) || $name == "") return;
	if (!isset($prefix) || $prefix == "") return;
	if ($id > 0)
	{
		$db->setQuery("SELECT `DepartmentId` FROM `#__rstickets_departments` WHERE (`DepartmentName`='".$name."' OR `DepartmentPrefix`='".$prefix."') AND `DepartmentId`!='".$id."' LIMIT 1");
		$db->query();
		if ($db->getNumRows() == 0)
		{
			$db->setQuery("UPDATE `#__rstickets_departments` SET `DepartmentName`='".$name."', `DepartmentPrefix`='".$prefix."', `TicketAssignmentType`='".$assign."', `TicketGenerationRule`='".$genrule."', `DepartmentPriority`='".$priority."', `UserEmailTicket`='".$useremail."', `StaffEmailTicket`='".$staffemail."', `FileUpload`='".$fileupload."', `FileUploadExtensions`='".$fileuploadext."', `NotifyNewTicketEmails`='".$notifynewticketemails."', `NotifyAssign`='".$notifyassign."' WHERE `DepartmentId`='".$id."' LIMIT 1");
			$db->query();
			rst_add_departments_custom_fields($id,$_POST['CustomFieldId'],$_POST['CustomFieldName'],$_POST['CustomFieldLabel'],$_POST['CustomFieldType'],$_POST['CustomFieldValues'],$_POST['Required']);
		}
		else
			return 4;
	}
	else
	{
		$db->setQuery("SELECT `DepartmentId` FROM `#__rstickets_departments` WHERE (`DepartmentName`='".$name."' OR `DepartmentPrefix`='".$prefix."') LIMIT 1");
		$db->query();
		if ($db->getNumRows() == 0)
		{			
			$db->setQuery("SELECT MAX(`DepartmentOrder`) FROM `#__rstickets_departments`");
			$maxorder = $db->loadResult() + 1;
			
			$db->setQuery("INSERT INTO `#__rstickets_departments` SET `DepartmentName`='".$name."', `DepartmentPrefix`='".$prefix."', `TicketAssignmentType`='".$assign."', `TicketGenerationRule`='".$genrule."', `DepartmentPriority`='".$priority."', `UserEmailTicket`='".$useremail."', `StaffEmailTicket`='".$staffemail."', `FileUpload`='".$fileupload."', `FileUploadExtensions`='".$fileuploadext."', `NotifyNewTicketEmails`='".$notifynewticketemails."', `NotifyAssign`='".$notifyassign."', `DepartmentOrder`='".$maxorder."'");
			$db->query();
			$id = $db->insertid();
			rst_add_departments_custom_fields($id,$_POST['CustomFieldId'],$_POST['CustomFieldName'],$_POST['CustomFieldLabel'],$_POST['CustomFieldType'],$_POST['CustomFieldValues'],$_POST['Required']);
		}
		else
			return 4;
	}
	return 0;
}

function rst_delete_department($id)
{
	$db = JFactory::getDBO();
	
	$id = intval($id);
	if ($id == 0) return;
	
	$db->setQuery("SELECT COUNT(`StaffToDepartmentId`) FROM `#__rstickets_staff_to_department` WHERE `DepartmentId`='".$id."'");
	$stafftodepartment = $db->loadResult();
	
	$db->setQuery("SELECT COUNT(`TicketId`) FROM `#__rstickets_tickets` WHERE `DepartmentId`='".$id."'");
	$tickets = $db->loadResult();
	
	if ($stafftodepartment == 0 && $tickets == 0)
	{
		$department = rst_get_departments($id);
		$department = $department[0];
		$db->setQuery("DELETE FROM `#__rstickets_departments` WHERE `DepartmentId`='".$id."' LIMIT 1");
		$db->query();
		$db->setQuery("DELETE FROM `#__rstickets_custom_fields` WHERE `DepartmentId`='".$id."' LIMIT 1");
		$db->query();
		if ($department['DepartmentOrder'] > 1)
		{
			$db->setQuery("UPDATE `#__rstickets_departments` SET `DepartmentOrder`=`DepartmentOrder`-1 WHERE `DepartmentOrder`>'".$department['DepartmentOrder']."'");
			$db->query();
		}
		return 1002;
	}
	else return 13;
}

// GET DEPARTMENT CUSTOM FIELDS
function rst_get_departments_custom_fields($id)
{
	$db = JFactory::getDBO();
	
	$id = intval($id);
	$db->setQuery("SELECT * FROM `#__rstickets_custom_fields` WHERE `DepartmentId`='".$id."'");
	$return = $db->loadAssocList();
	return $return;
}

function rst_add_departments_custom_fields($departmentid,$customfieldid,$name,$label,$type,$values,$required)
{
	$db = JFactory::getDBO();
	
	$departmentid = intval($departmentid);
	$num = count($customfieldid);
	if (!is_array($customfieldid) || !is_array($name) || !is_array($label) || !is_array($type) || !is_array($values) || !is_array($required)) return;
	for ($id=0;$id<$num;$id++)
	{
		if ($customfieldid[$id] > 0)
			$db->setQuery("UPDATE `#__rstickets_custom_fields` SET `CustomFieldName`='".rst_clean($name[$id])."', `CustomFieldLabel`='".rst_clean($label[$id])."', `CustomFieldType`='".rst_clean($type[$id])."', `CustomFieldValues`='".rst_clean($values[$id])."', `Required`='".intval($required[$id])."' WHERE `CustomFieldId`='".intval($customfieldid[$id])."' LIMIT 1");
		else
			$db->setQuery("INSERT INTO `#__rstickets_custom_fields` SET `DepartmentId`='".intval($departmentid)."',`CustomFieldName`='".rst_clean($name[$id])."', `CustomFieldLabel`='".rst_clean($label[$id])."', `CustomFieldType`='".rst_clean($type[$id])."', `CustomFieldValues`='".rst_clean($values[$id])."', `Required`='".rst_clean($required[$id])."'");
		$db->query();
	}
}

function rst_delete_custom_field($id)
{
	$id = intval($id);
	if ($id == 0) return;
	
	$db = JFactory::getDBO();
	
	$db->setQuery("SELECT COUNT(`CustomFieldValueId`) FROM `#__rstickets_custom_fields_value` WHERE `CustomFieldId`='".$id."'");
	if ($db->loadResult() == 0)
	{
		$db->setQuery("DELETE FROM `#__rstickets_custom_fields` WHERE `CustomFieldId`='".$id."' LIMIT 1");
		$db->query();
		$db->setQuery("DELETE FROM `#__rstickets_custom_fields_value` WHERE `CustomFieldId`='".$id."'");
		$db->query();
	}
	else return 16;
}

// GET GROUPS
function rst_get_groups($id=0)
{
	$db = JFactory::getDBO();
	
	$db->setQuery("SELECT * FROM `#__rstickets_groups` ".($id > 0 ? "WHERE `GroupId`='".rst_clean($id)."'" : ""));
	$return = $db->loadAssocList();
	
	return $return;
}

function rst_add_group($id=0,$name,$add=0,$addusers=0,$addstaff=0,$update=0,$delete=0,$answer=0,$deleter=0,$updater=0,$assign=0,$status=0,$unalloc=0,$other=0,$move=0)
{
	$db = JFactory::getDBO();
	
	$id = intval($id);
	$name = rst_clean($name);
	$add = intval($add);
	$addusers = intval($addusers);
	$addstaff = intval($addstaff);
	$update = intval($update);
	$delete = intval($delete);
	$answer = intval($answer);
	$deleter = intval($deleter);
	$updater = intval($updater);
	$assign = intval($assign);
	$status = intval($status);
	$unalloc = intval($unalloc);
	$other = intval($other);
	$move = intval($move);
	if ($id > 0)
	{
		$db->setQuery("SELECT `GroupName` FROM `#__rstickets_groups` WHERE `GroupName`='".$name."' AND `GroupId`!='".$id."' LIMIT 1");
		$db->query();
		if ($db->getNumRows() == 0)
		{
			$db->setQuery("UPDATE `#__rstickets_groups` SET `GroupName`='".$name."', `CanAddTicket`='".$add."', `CanAddTicketUsers`='".$addusers."', `CanAddTicketStaff`='".$addstaff."', `CanUpdateTicket`='".$update."', `CanDeleteTicket`='".$delete."', `CanAnswerTicket`='".$answer."', `CanDeleteTicketReplies`='".$deleter."', `CanUpdateTicketReplies`='".$updater."', `CanAssignTickets`='".$assign."', `CanChangeTicketStatus`='".$status."', `CanSeeUnallocatedTickets`='".$unalloc."', `CanSeeOtherTickets`='".$other."', `CanMoveTicket`='".$move."' WHERE `GroupId`='".$id."' LIMIT 1");
			$db->query();
		}
		else
			return 5;
	}
	else
	{
		$db->setQuery("SELECT `GroupName` FROM `#__rstickets_groups` WHERE `GroupName`='".$name."' LIMIT 1");
		$db->query();
		if ($db->getNumRows() == 0)
		{
			$db->setQuery("INSERT INTO `#__rstickets_groups` SET `GroupName`='".$name."', `CanAddTicket`='".$add."', `CanAddTicketUsers`='".$addusers."', `CanAddTicketStaff`='".$addstaff."', `CanUpdateTicket`='".$update."', `CanDeleteTicket`='".$delete."', `CanAnswerTicket`='".$answer."', `CanDeleteTicketReplies`='".$deleter."', `CanUpdateTicketReplies`='".$updater."', `CanAssignTickets`='".$assign."', `CanChangeTicketStatus`='".$status."', `CanSeeUnallocatedTickets`='".$unalloc."', `CanSeeOtherTickets`='".$other."', `CanMoveTicket`='".$move."'");
			$db->query();
		}
		else
			return 5;
	}
}

function rst_delete_group($id)
{
	$id = intval($id);
	if ($id == 0) return;
	
	$db = JFactory::getDBO();
	
	$db->setQuery("SELECT COUNT(`StaffId`) FROM `#__rstickets_staff` WHERE `GroupId`='".$id."'");
	
	if ($db->loadResult() == 0)
	{
		$db->setQuery("DELETE FROM `#__rstickets_groups` WHERE `GroupId`='".$id."' LIMIT 1");
		$db->query();
		return 1005;
	}
	else
		return 14;
}

// STAFF
function rst_get_staff($id=0,$departments=array(),$permissions=array())
{
	$db = JFactory::getDBO();
	
	$id = intval($id);
	if (count($departments) > 0)
		foreach ($departments as $key => $department)
			$departments[$key] = intval($department);
	if (count($permissions) > 0)
		foreach ($permissions as $key => $permission)
			$permissions[$key] = "`#__rstickets_groups`.`".$permission."`='1'";
	$db->setQuery("SELECT `#__users`.`id` AS `UserId`, `#__users`.`name` AS `Fullname`, `#__users`.`username` AS `Username`, `#__users`.`email` AS `Email`,`#__rstickets_groups`.`GroupName`,`#__rstickets_groups`.`GroupId`,`#__rstickets_staff_to_department`.`OpenTickets` FROM `#__users` INNER JOIN `#__rstickets_staff` ON (`#__rstickets_staff`.`UserId`=`#__users`.`id`) INNER JOIN `#__rstickets_groups` ON (`#__rstickets_groups`.`GroupId`=`#__rstickets_staff`.`GroupId`) INNER JOIN `#__rstickets_staff_to_department` ON (`#__rstickets_staff_to_department`.`UserId`=`#__users`.`id`) WHERE 1 ".(count($permissions) > 0 ? " AND ".implode(' AND ',$permissions) : "").(count($departments) > 0 ? " AND `#__rstickets_staff_to_department`.`DepartmentId` IN (".implode(',',$departments).")" : "").($id > 0 ? " AND `#__rstickets_staff`.`UserId`='".$id."'" : "")." GROUP BY `#__users`.`id` ORDER BY `#__users`.`username`");
	$return = $db->loadAssocList();
	
	return $return;
}

function rst_add_staff($group,$user,$departments_array)
{
	$db = JFactory::getDBO();
	
	$user = intval($user);
	if ($user == 0) return 26;
	$group = intval($group);
	if ($group == 0) return 27;
	if (!is_array($departments_array) || (is_array($departments_array) && count($departments_array) < 1)) return 25;
	
	$db->setQuery("SELECT `StaffId` FROM `#__rstickets_staff` WHERE `UserId`='".$user."' LIMIT 1");
	$db->query();
	if ($db->getNumRows() == 0)
	{
		$db->setQuery("INSERT INTO `#__rstickets_staff` SET `GroupId`='".$group."',`UserId`='".$user."'");
		$db->query();
		$what = 'add';
	}
	else
	{
		$db->setQuery("UPDATE `#__rstickets_staff` SET `GroupId`='".$group."' WHERE `UserId`='".$user."' LIMIT 1");
		$db->query();
		$what = 'edit';
	}
	$db->setQuery("DELETE FROM `#__rstickets_staff_to_department` WHERE `UserId`='".$user."'");
	$db->query();
	if (count($departments_array) > 0)
		foreach ($departments_array as $department)
		{
			$db->setQuery("INSERT INTO `#__rstickets_staff_to_department` SET `UserId`='".$user."',`DepartmentId`='".$department."'");
			$db->query();
		}
	if ($what == 'add')
		return 1006;
	else
		return 1007;
}

function rst_delete_staff($id)
{
	$id = intval($id);
	if ($id == 0) return;
	
	$db = JFactory::getDBO();
	$db->setQuery("SELECT COUNT(`TicketId`) FROM `#__rstickets_tickets` WHERE `UserId`='".$id."'");
	
	if ($db->loadResult() == 0)
	{
		$db->setQuery("DELETE FROM `#__rstickets_staff` WHERE `UserId`='".$id."' LIMIT 1");
		$db->query();
		$db->setQuery("DELETE FROM `#__rstickets_staff_to_department` WHERE `UserId`='".$id."'");
		$db->query();
		$db->setQuery("DELETE FROM `#__rstickets_ticket_message` WHERE `UserId`='".$id."'");
		$db->query();
		return 1008;
	}
	else
		return 15;
}

function rst_search_users($what,$remove_self=0,$show_users=1,$show_staff=0)
{
	$db = JFactory::getDBO();
	
	$what = str_replace(' ','%',rst_clean($what));
	
	$remove_array = rst_get_users(0,$remove_self,$show_users,$show_staff);
	
	$staff_array = array();
	foreach ($remove_array as $remove)
		$staff_array[] = $remove['UserId'];
	
	@ob_clean();
	echo '<select size="5" name="UserId">';
	
	$db->setQuery("SELECT `id` AS `UserId`,`username` AS `Username`, `name` AS `Fullname` FROM `#__users` WHERE (`email` LIKE '%".$what."%' OR `name` LIKE '%".$what."%' OR `username` LIKE '%".$what."%') ".(count($staff_array) > 0 ? " AND `#__users`.`id` IN (".implode(",",$staff_array).") " : "")." ORDER BY `#__users`.`username` ASC");
	
	$rows = $db->loadAssocList();
	
	foreach ($rows as $row)
		echo '<option value="'.$row['UserId'].'">'.$row['Username'].' ('.$row['Fullname'].')</option>';
		
	echo '</select>';
}

//function rst_get_users($id=0,$is_in_staff=false,$admin=0)
function rst_get_users($id=0,$remove_self=0,$show_users=1,$show_staff=0)
{
	$db = JFactory::getDBO();
	
	$RST_adapter = $GLOBALS['RST_adapter'];
	$user = $RST_adapter->user($id);
	
	$id = intval($id);
	
	if ($id > 0)
	{
		$db->setQuery("SELECT * FROM `#__users` WHERE `#__users`.`id`='".$id."'");
		$rows = $db->loadAssocList();
		
		$return = array();
		foreach ($rows as $row)
			$return[] = array('UserId'=>$row['id'], 'Fullname'=>$row['name'], 'Username'=>$row['username'], 'Email'=>$row['email'], 'Admin'=>$user['admin']);
			
		return $return;
	}
	
	$remove_array = array();
	
	if ($remove_self == 1 && rst_is_logged())
		$remove_array[] = $_SESSION['RST_User']['UserId'];
	
	if ($show_staff == 0)
	{
		// MYSQL 4 HACK
		$db->setQuery("SELECT `#__rstickets_staff`.`UserId` FROM `#__rstickets_staff`");
		$rows = $db->loadAssocList();
		
		foreach ($rows as $row)
			$remove_array[] = $row['UserId'];
	}
	
	if ($show_users == 0)
	{
		$staff_array = array();
		// MYSQL 4 HACK
		$db->setQuery("SELECT `#__rstickets_staff`.`UserId` FROM `#__rstickets_staff`");
		$rows = $db->loadAssocList();
		
		foreach ($rows as $row)
			$staff_array[] = $row['UserId'];
				
		$db->setQuery("SELECT `#__users`.`id` FROM `#__users` ".(count($staff_array) > 0 ? " WHERE `#__users`.`id` NOT IN (".implode(",",$staff_array).")" : ""));
		$rows = $db->loadAssocList();
		
		foreach ($rows as $row)
			$remove_array[] = $row['id'];
	}
	
	$db->setQuery("SELECT * FROM `#__users` WHERE 1 ".(count($remove_array) > 0 ? " AND `#__users`.`id` NOT IN (".implode(",",$remove_array).")" : "").($id > 0 ? " AND `#__users`.`id`='".$id."'" : "")." ORDER BY `#__users`.`username` ASC");
	$rows = $db->loadAssocList();
	
	$return = array();
	foreach ($rows as $row)
		$return[] = array('UserId'=>$row['id'], 'Fullname'=>$row['name'], 'Username'=>$row['username'], 'Email'=>$row['email'], 'Admin'=>$user['admin']);
		
	return $return;
}

function rst_get_permission_by_userid($id,$permission)
{
	$id = intval($id);
	if ($id == 0) return;
	$permission = rst_clean($permission);
	
	$db = JFactory::getDBO();
	$db->setQuery("SELECT `".$permission."` FROM `#__rstickets_staff` LEFT JOIN `#__rstickets_groups` ON (`#__rstickets_groups`.`GroupId`=`#__rstickets_staff`.`GroupId`) WHERE `UserId`='".$id."'");
	return ($db->loadResult() == 1);
}

function rst_get_userid_by_email($email)
{
	$email = rst_clean($email);
	if (!rst_is_email($email)) return;
	
	$db = JFactory::getDBO();
	$db->setQuery("SELECT `id` AS `UserId` FROM `#__users` WHERE `Email`='".$email."' LIMIT 1");
	return $db->loadResult();
}

function rst_get_email_by_userid($id)
{
	$id = intval($id);
	if ($id == 0) return;
	
	$db = JFactory::getDBO();
	$db->setQuery("SELECT `email` AS `Email` FROM `#__users` WHERE `id`='".$id."' LIMIT 1");
	return $db->loadResult();
}

function rst_get_fullname_by_userid($id)
{
	$id = intval($id);
	if ($id == 0) return;
	
	$db = JFactory::getDBO();
	$db->setQuery("SELECT `name` AS `Fullname` FROM `#__users` WHERE `id`='".$id."' LIMIT 1");
	return $db->loadResult();
}

function rst_get_customer_email_by_ticketid($id)
{
	$id = intval($id);
	if ($id == 0) return;
	
	$db = JFactory::getDBO();
	$db->setQuery("SELECT `CustomerId` FROM `#__rstickets_tickets` WHERE `TicketId`='".$id."' LIMIT 1");
	$userid = $db->loadResult();
	return rst_get_email_by_userid($userid);
}

function rst_get_subject_by_ticketid($id)
{
	$id = intval($id);
	if ($id == 0) return;
	
	$db = JFactory::getDBO();
	$db->setQuery("SELECT `TicketSubject` FROM `#__rstickets_tickets` WHERE `TicketId`='".$id."' LIMIT 1");
	return $db->loadResult();
}

function rst_get_user_is_in_staff($userid)
{
	$userid = intval($userid);
	
	$db = JFactory::getDBO();
	$db->setQuery("SELECT `StaffId` FROM `#__rstickets_staff` WHERE `UserId`='".$userid."'");
	$db->query();
	return ($db->getNumRows() > 0);
}

function rst_get_staff_to_departments($id=0)
{
	$id = intval($id);
	
	$db = JFactory::getDBO();
	$db->setQuery("SELECT `#__rstickets_staff_to_department`.*, `#__rstickets_departments`.`DepartmentName` FROM `#__rstickets_staff_to_department` INNER JOIN `#__rstickets_departments` ON (`#__rstickets_departments`.`DepartmentId`=`#__rstickets_staff_to_department`.`DepartmentId`)".($id > 0 ? " WHERE `#__rstickets_staff_to_department`.`UserId`='".$id."'" : ""));
	
	$return = $db->loadAssocList();
	
	return $return;
}

function rst_get_tickets($code, $subject, $message, $time='', $from, $to, $departments_array, $status=array('open','on-hold','closed'), $priority=array('low','normal','high'), $page=1, $order='TicketTime', $direction='DESC', $staffusername='', $stafffullname='', $staffemail='',$customerusername='',$customerfullname='',$customeremail='',$mystafftickets=0,$mycustomertickets=0)
{
	$mystafftickets = intval($mystafftickets);
	$mycustomertickets = intval($mycustomertickets);

	$db = JFactory::getDBO();
	
	// PAGE MUST BE > 0
	$page = intval($page) == 0 ? 1 : $page;
	// ORDER
	$order_array = array('TicketTime','TicketCode','TicketSubject','TicketPriority','TicketStatus','StaffFullname','CustomerFullname');
	if (!in_array($order,$order_array)) $order = 'TicketTime';
	// DIRECTION
	$direction = $direction == 'DESC' ? 'DESC' : 'ASC';
	// CODE
	$code = rst_clean($code);
	// SUBJECT
	$subject = rst_clean($subject);
	// MESSAGE
	$message = rst_clean($message);
	// TIME
	if ($time != '')
	{
		$from = strlen($time) > 0 ? strtotime(rst_parse_date($time)) : 0;
		$to = strlen($time) > 0 ? strtotime(rst_parse_date($time)) + 86399 : 86399;
	}
	else
	{
		$from = strlen($from) > 0 ? strtotime(rst_parse_date($from)) : 0;
		$to = strlen($to) > 0 ? strtotime(rst_parse_date($to)) + 86399 : 86399;
	}
	if (is_array($departments_array) && count($departments_array) > 0)
		foreach ($departments_array as $key => $department)
			$departments_array[$key] = intval($department);
	// PRIORITY - in case we need it
	// $priority_array = array('low','normal','high');
	// if (!in_array($priority,$priority_array)) $priority = 'normal';
	// STATUS
	$status_array = array('open','on-hold','closed');
	foreach ($status as $key => $statussent)
		if (!in_array($statussent,$status_array)) unset($status[$key]);
	$status = isset($status) ? $status : $status_array;
	// PRIORITY
	$priority_array = array('low','normal','high');
	foreach ($priority as $key => $prioritysent)
		if (!in_array($prioritysent,$priority_array)) unset($priority[$key]);
	$priority = isset($priority) ? $priority : $priority_array;
	// STAFF
	$staffusername = rst_clean($staffusername);
	$stafffullname = rst_clean($stafffullname);
	$staffemail = rst_clean($staffemail);
	// CUSTOMER
	$customerusername = rst_clean($customerusername);
	$customerfullname = rst_clean($customerfullname);	
	$customeremail = rst_clean($customeremail);
	
	$customers_array = array();
	if ($customerusername != '' || $customeremail != '' || $customerfullname != '')
	{		
		$db->setQuery("SELECT `id` AS `UserId` FROM `#__users` WHERE 1 ".($customerusername != '' ? " AND `username` LIKE '%".$customerusername."%'" : "").($customeremail != '' ? " AND `email` LIKE '%".$customeremail."%'" : "").($customerfullname != '' ? " AND `name` LIKE '%".$customerfullname."%'" : ""));
		$rows = $db->loadAssocList();
		
		if (count($rows) > 0)
			foreach ($rows as $row)
				$customers_array[] = $row['UserId'];
		else
			$customers_array[] = '-1';
	}
	
	$staff_array = array();
	if ($staffusername != '' || $staffemail != '' || $stafffullname != '')
	{
		$db->setQuery("SELECT `id` AS `UserId` FROM `#__users` WHERE 1 ".($staffusername != '' ? " AND `username` LIKE '%".$staffusername."%'" : "").($staffemail != '' ? " AND `email` LIKE '%".$staffemail."%'" : "").($stafffullname != '' ? " AND `name` LIKE '%".$stafffullname."%'" : ""));
		$rows = $db->loadAssocList();
		
		if (count($rows) > 0)
			foreach ($rows as $row)
				$staff_array[] = $row['UserId'];
		else
			$staff_array[] = '-1';
	}
		
	// MYSQL 4 HACK
	$ticket_array = array();
	if ($message != '')
	{
		$db->setQuery("SELECT DISTINCT `TicketId` FROM `#__rstickets_ticket_message` WHERE `TicketMessage` LIKE '%".$message."%'");
		$rows = $db->loadAssocList();
		
		if (count($rows) > 0)
			foreach ($rows as $row)
				$ticket_array[] = $row['TicketId'];
		else
			$ticket_array[] = '-1';
	}
	
	// GET TICKETS
	
	// START THE SQL
	$sql = "SELECT SQL_CALC_FOUND_ROWS `#__rstickets_tickets`.*,IFNULL(`ext1`.`name`,'".$db->getEscaped(LBL_UNASSIGNED)."') AS `StaffFullname`,`ext2`.`name` AS `CustomerFullname` FROM `#__rstickets_tickets` LEFT JOIN `#__users` AS `ext1` ON (`ext1`.`id`=`#__rstickets_tickets`.`UserId`) LEFT JOIN `#__users` AS `ext2` ON (`ext2`.`id`=`#__rstickets_tickets`.`CustomerId`) WHERE 1 ";
	
	// SEARCHING THROUGH A DATE ?
	$sql .= ($from > 0 && $to > 86399 ? " AND (`#__rstickets_tickets`.`TicketTime` BETWEEN '".$from."' AND '".$to."')" : "");
	// SEARCHING FOR A SUBJECT ?
	$sql .= ($subject != '' ? " AND `#__rstickets_tickets`.`TicketSubject` LIKE '%".$subject."%'" : "");
	// SEARCHING FOR A CODE ?
	$sql .= ($code != '' ? " AND `#__rstickets_tickets`.`TicketCode` LIKE '%".$code."%'" : "");
	// SEARCHING FOR A STAFF MEMBER ?
	$sql .= (count($staff_array) > 0 ? " AND `#__rstickets_tickets`.`UserId` IN (".implode(',',$staff_array).")" : "");
	// SEARCHING FOR A CUSTOMER ?
	$sql .= (count($customers_array) > 0 ? " AND `#__rstickets_tickets`.`CustomerId` IN (".implode(',',$customers_array).")" : "");
	// SEARCHING FOR STATUSES ?
	$sql .= ($status != $status_array ? " AND `TicketStatus` IN ('".implode("','",$status)."')" : "");
	// SEARCHING FOR PRIORITIES ?
	$sql .= ($priority != $priority_array ? " AND `TicketPriority` IN ('".implode("','",$priority)."')" : "");
	// SEARCHING FOR DEPARTMENTS ?
	$sql .= (count($departments_array) > 0 ? " AND `DepartmentId` IN (".implode(",",$departments_array).")" : "");
	// SEARCHING FOR A MESSAGE ?
	$sql .= (count($ticket_array) > 0 ? " AND `TicketId` IN (".implode(",",$ticket_array).")" : "");
	
	// THE TICKETS TAB IS DISPLAYED ...
	if ($mycustomertickets == 0 && $mystafftickets == 0 && rst_is_staff_logged())
	{
		// SHOW ONLY UNASSIGNED TICKETS ?
		if ($_SESSION['search_tickets']['Unassigned'] == 1)
			$sql .= ($_SESSION['RST_User']['Group']['CanSeeUnallocatedTickets'] == 1 ? " AND `#__rstickets_tickets`.`UserId`='0' " : " AND `#__rstickets_tickets`.`UserId`!='0' ");
		else
		// SHOW ALL TICKETS ?
			$sql .= ($_SESSION['RST_User']['Group']['CanSeeUnallocatedTickets'] == 1 && $_SESSION['RST_User']['Group']['CanSeeOtherTickets'] == 1 ? " AND `#__rstickets_tickets`.`UserId`>='0'" : ($_SESSION['RST_User']['Group']['CanSeeUnallocatedTickets'] == 1 ? " AND `#__rstickets_tickets`.`UserId`='0'" : ($_SESSION['RST_User']['Group']['CanSeeOtherTickets'] == 1 ? " AND `#__rstickets_tickets`.`UserId`!='0'" : " AND `#__rstickets_tickets`.`UserId`='-1'")));
			
		$sql .= " AND `#__rstickets_tickets`.`UserId` != '".$_SESSION['RST_User']['UserId']."' AND `#__rstickets_tickets`.`CustomerId` != '".$_SESSION['RST_User']['UserId']."' ";
	}
	else
	{
		// STAFF MY TICKETS TAB IS DISPLAYED ...
		if ($mystafftickets == 1)
			$sql .= $_SESSION['RST_User']['Group']['CanAddTicket'] == 1 ? " AND (`#__rstickets_tickets`.`UserId`='".$_SESSION['RST_User']['UserId']."' OR `#__rstickets_tickets`.`CustomerId`='".$_SESSION['RST_User']['UserId']."')" : " AND `#__rstickets_tickets`.`UserId`='".$_SESSION['RST_User']['UserId']."'";
		
		// CUSTOMER MY TICKETS TAB IS DISPLAYED ...
		if ($mycustomertickets == 1)
			$sql .= " AND `#__rstickets_tickets`.`CustomerId`='".$_SESSION['RST_User']['UserId']."'";
	}
	
	// END THE SQL
	$sql .= " ORDER BY `".$order."` ".$direction." LIMIT ".($page*15-15).",15";
	
	$db->setQuery($sql);
	$rows = $db->loadAssocList();
	
	$db->setQuery("SELECT FOUND_ROWS()");
	$total = $db->loadResult();
	$total_pages = $total == 0 ? 1 : ceil($total/15);
	$return = array('totalpages' => $total_pages);
	
	foreach ($rows as $row)
	{
		$db->setQuery("SELECT COUNT(`TicketMessageId`) FROM `#__rstickets_ticket_message` WHERE `TicketId`='".$row['TicketId']."'");
		$row['TicketReplies'] = $db->loadResult();
		if ($row['TicketReplies'] > 0)
			$row['TicketReplies'] -= 1;
		$return['tickets'][] = $row;
	}

	return $return;
}

function rst_add_ticket($departmentid,$subject,$message,$priority,$userid=0,$email=0,$fullname=0,$customfields,$cron=false,$antispam='')
{
	$RST_adapter = $GLOBALS['RST_adapter'];
	global $T_SETTINGS, $T_EVENTS;
	if (isset($T_EVENTS['BeforeAddTicket'])) eval($T_EVENTS['BeforeAddTicket']);
	
	$db = JFactory::getDBO();
	
	if ($T_SETTINGS['Captcha_Enabled'] == 1 && $cron == false && ((strpos($T_SETTINGS['Captcha_Enabled_For'],'unregistered') !== false && !rst_is_logged()) || (strpos($T_SETTINGS['Captcha_Enabled_For'],'users') !== false && rst_is_customer_logged()) || (strpos($T_SETTINGS['Captcha_Enabled_For'],'staff') !== false && rst_is_staff_logged())))
	{
		if (empty($_SESSION['RST_CAPTCHA_Code']) || empty($antispam))
			return 32;
		if ($T_SETTINGS['Captcha_Case_Sensitive'] == 1)
		{
			if ($antispam != $_SESSION['RST_CAPTCHA_Code'])
				return 32;
		}
		else
		{
			if ($antispam != $_SESSION['RST_CAPTCHA_Code'] && $antispam != strtolower($_SESSION['RST_CAPTCHA_Code']))
				return 32;
		}
	}
	unset($_SESSION['RST_CAPTCHA_Code']);
	
	// MUST HAVE A DEPARTMENT
	$departmentid = intval(rst_clean($departmentid));
	if ($departmentid == 0 && $cron == false) return 6;
	
	// MUST HAVE A SUBJECT
	$subject2 = $subject;
	$subject = rst_clean($subject);
	if ($subject == '') return 7;
	
	// MUST HAVE A MESSAGE
	//$email_message = nl2br(htmlentities(trim(rst_convert_encoding($message)),ENT_QUOTES,'utf-8'));
	$email_message = nl2br($message);
	$message = rst_clean($message);
	
	if ($message == '') return 8;
	
	// TICKET PRIORITY
	$priority = rst_clean($priority);
	
	// USERID
	$userid = intval($userid);
	if ($userid > 0) $was_logged_in = true;
	else $was_logged_in = false;
	
	// EMAIL
	$email = rst_clean($email);
	if (rst_is_email($email) == 0) return 9;
	
	// FULL NAME
	$fullname = rst_clean($fullname);
	if ($fullname == '') return 10;

	if ($cron == true)
	{
		$_SERVER['HTTP_USER_AGENT'] = 'Cron Plugin';
		$_SERVER['HTTP_REFERER'] = '';
		$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
	}
	
	$ticketinfo['user-agent'] = '<strong>{agent}</strong>: '.rst_clean($_SERVER['HTTP_USER_AGENT']);
	$ticketinfo['referer'] = '<strong>{referer}</strong>: '.rst_clean($_SERVER['HTTP_REFERER']);
	$ticketinfo['ip'] = '<strong>{ip}</strong>: '.rst_clean($_SERVER['REMOTE_ADDR']);
	$ticketinfo['logged'] = '<strong>{logged}</strong>: '.($was_logged_in ? '{yes}' : '{no}');
	
	// GET DEPARTMENT SETTINGS
	if ($departmentid > 0)
		$departments = rst_get_departments($departmentid);
	else
		$departments[0] = array('DepartmentId' => 0, 'DepartmentName' => LBL_UNASSIGNED_DEPARTMENT, 'DepartmentPrefix' => 'UNASSIGNED', 'TicketAssignmentType' => 'static', 'TicketGenerationRule' => 'random', 'UserEmailTicket' => 0, 'StaffEmailTicket' => 0, 'FileUpload' => 'no', 'FileUploadExtensions' => array(), 'NotifyNewTicketEmails' => '');
	
	if (isset($_FILES['FileName']) && count($_FILES['FileName']) > 0 && $_FILES['FileName']['tmp_name'] != '')
	{
		if (!is_writable(RST_FRONTEND_ABS_PATH.'/files/')) return 33;
		if (!rst_is_allowed_extension(rst_get_extension($_FILES['FileName']['name']),$departments[0]['FileUploadExtensions'])) return 28;
	}
	
	// GET CUSTOM FIELDS FOR THE DEPARTMENT
	$totalcustomfields = rst_get_departments_custom_fields($departmentid);
	
	// LET'S TRIM THE CUSTOM FIELDS
	if (count($totalcustomfields) > 0 && $cron == false)
	{
		foreach ($customfields as $customfield => $value)
		{
			// WE RECEIVED THE WHOLE POST, MUST REMOVE EXTRA FIELDS
			if (str_replace('rstcf_','',$customfield) == $customfield)
			{
				unset($customfields[$customfield]);
				continue;
			}
			else 
			{
				$customfields[str_replace('rstcf_','',$customfield)] = $value;
				unset($customfields[$customfield]);
			}
		}				
		
		foreach ($customfields as $customfield => $value)
		{
			// THIS IS WHERE THE TRIMMING TAKES PLACE - ALL FIELDS THAT DO NOT BELONG TO THE DEPARTMENT ARE REMOVED
			$found = 0;
			foreach ($totalcustomfields as $totalcustomfield)
				if ($totalcustomfield['CustomFieldId'] == $customfield) $found = 1;
			if ($found == 0) unset($customfields[$customfield]);
		}
		
		// CHECK IF REQUIRED CUSTOM FIELDS HAVE A VALUE
		foreach ($totalcustomfields as $totalcustomfield)
		{
			if ($totalcustomfield['Required'] == 1)
				if (!isset($customfields[$totalcustomfield['CustomFieldId']]) || $customfields[$totalcustomfield['CustomFieldId']] == '')
					return 11;
		}
		
		// CHECK IF CUSTOM FIELDS HAVE THE RIGHT VALUE
		foreach ($customfields as $customfield => $value)
			foreach ($totalcustomfields as $totalcustomfield)
				if ($totalcustomfield['CustomFieldId'] == $customfield && ($totalcustomfield['CustomFieldId'] == 'select' || $totalcustomfield['CustomFieldId'] == 'multipleselect' || $totalcustomfield['CustomFieldId'] == 'checkbox' || $totalcustomfield['CustomFieldId'] == 'radio'))
					if (strlen($value) > 0 && strpos($totalcustomfield['CustomFieldValues'],$value) === false)
							return 11;	
	}
	else
		$customfields = array();
	
	// IF $userid == 0 => 1) MUST GENERATE USER ($email IS REQUIRED) 2) MUST VERIFY IF EMAIL ALREADY EXISTS
	if ($userid == '0' && $email != '0')
	{
		$db->setQuery("SELECT `id` as `UserId` FROM `#__users` WHERE `email`='".$email."' LIMIT 1");
		$result = $db->loadResult();
		if ($result > 0)
			$userid = $result;
		else
		{
			// GENERATE A NEW USER - CHECK IF USER EXISTS
			list($username, $domain) = split("@", $email);
			$db->setQuery("SELECT `id` as `UserId` FROM `#__users` WHERE `username` LIKE '".$username."' LIMIT 1");
			$resultuser = $db->loadResult();
			$db->query();
			if ($resultuser > 0)
				while ($db->getNumRows() > 0)
				{
					$username = $username.mt_rand(0,9);
					$db->setQuery("SELECT `id` as `UserId` FROM `#__users` WHERE `username`='".$username."' LIMIT 1");
					$db->query();
				}
			// CREATE A NEW USER & SEND WELCOME EMAIL
			
			$temppass = rst_random_pass();
			
			$db->setQuery("INSERT INTO `#__users` (`name`, `username`, `email`, `password`, `usertype`, `block`, `sendEmail`, `gid`, `registerDate`, `lastvisitDate`, `activation`, `params`) VALUES('".$fullname."', '".$username."', '".$email."', '".md5($temppass)."', '', 0, 0, 18, now(), now(), '', '');");
			$db->query();
			$userid = $db->insertid();
			
			$db->setQuery("INSERT INTO `#__core_acl_aro` (`".($RST_adapter->version == 'j15x' ? 'id':'aro_id')."`, `section_value`, `value`, `order_value`, `name`, `hidden`) VALUES('', 'users', '".$userid."', 0, '".$fullname."', 0);");
			$db->query();
			$aro_id = $db->insertid();
			
			$db->setQuery("INSERT INTO `#__core_acl_groups_aro_map` (`group_id`,`section_value`,`aro_id`) VALUES ('18','','$aro_id')");
			$db->query();
				
			rst_send_email($email,RST_NEW_USER_SUBJECT,array('username' => $username,'password' => $temppass),'new_user',$fullname);
		}
	}
	
	// CHECK THE DEPARTMENT TICKET ASSIGNMENT TYPE
	if ($departments[0]['TicketAssignmentType'] == 'automatic')
	{
		// CHECK IF THERE ARE ANY STAFF MEMBERS WITH NO TICKETS
		$db->setQuery("SELECT `UserId` FROM `#__rstickets_staff_to_department` WHERE `DepartmentId`='".$departmentid."' ORDER BY `OpenTickets` ASC LIMIT 1");
		$automatic_userid = $db->loadResult();
		
		// IF THERE AREN'T ANY, ASSIGN THIS TICKET TO NOBODY
		if ($automatic_userid === false)
			$automatic_userid = 0;
	}
	else
		$automatic_userid = 0;
	
	// CHECK THE DEPARTMENT TICKET GENERATION RULE
	if ($departments[0]['TicketGenerationRule'] == 'sequential')
	{
		$ticketcode = $departments[0]['NextTicketNumber'];
		$db->setQuery("UPDATE `#__rstickets_departments` SET `NextTicketNumber`='".($ticketcode+1)."' WHERE `DepartmentId`='".$departmentid."'");
		$db->query();
		$ticketcode = str_pad($ticketcode, 10, "0", STR_PAD_LEFT);
	}
	elseif ($departments[0]['TicketGenerationRule'] == 'random')
	{
		$ticketcode = strtoupper(rst_random_pass(10));
		$db->setQuery("SELECT `TicketId` FROM `#__rstickets_tickets` WHERE `TicketCode`='".$departments[0]['DepartmentPrefix']."-".$ticketcode."' LIMIT 1");
		$result = $db->loadResult();
		
		if ($result > 0)
			while ($this->getNumRows())
			{
				$ticketcode = strtoupper(rst_random_pass(10));
				$db->setQuery("SELECT `TicketId` FROM `#__rstickets_tickets` WHERE `TicketCode`='".$departments[0]['DepartmentPrefix']."-".$ticketcode."' LIMIT 1");
				$db->query();
			}	
	}
	
	// ADD A NEW TICKET
	$tickettime = time();
	$db->setQuery("INSERT INTO `#__rstickets_tickets` SET `DepartmentId`='".$departmentid."', `UserId`='".$automatic_userid."', `CustomerId`='".$userid."', `TicketCode`='".$departments[0]['DepartmentPrefix']."-".$ticketcode."', `TicketSubject`='".$subject."', `TicketStatus`='open', `TicketPriority`='".$priority."', `TicketTime`='".$tickettime."', `TicketInfo`='".implode($ticketinfo,'<br />')."'");
	$db->query();
	$ticketid = $db->insertid();
	
	if ($ticketid > 0 && $automatic_userid > 0)
	{
		$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets`=`OpenTickets`+1 WHERE `UserId`='".$automatic_userid."' AND `DepartmentId`='".$departmentid."' LIMIT 1");
		$db->query();
	}
		
	$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets` = '0' WHERE `OpenTickets` < 0");
	$db->query();
	
	// ADD THE TICKET BODY
	$db->setQuery("INSERT INTO `#__rstickets_ticket_message` SET `TicketId`='".$ticketid."', `UserId`='".$userid."', `TicketMessage`='".$message."', `TicketTime`='".$tickettime."'");
	$db->query();
	$ticketmessageid = $db->insertid();
	
	// ADD THE CUSTOM FIELDS
	if (count($totalcustomfields) > 0 && $cron == false)
		foreach ($customfields as $customfield => $value)
		{
			if (is_array($value))
				foreach ($value as $value2)
				{
					$db->setQuery("INSERT INTO `#__rstickets_custom_fields_value` SET `CustomFieldId`='".$customfield."', `TicketId`='".$ticketid."', `CustomFieldValue`='".rst_clean($value2)."'");
					$db->query();
				}
			else
			{
				$db->setQuery("INSERT INTO `#__rstickets_custom_fields_value` SET `CustomFieldId`='".$customfield."', `TicketId`='".$ticketid."', `CustomFieldValue`='".rst_clean($value)."'");
				$db->query();
			}
		}
	
	// ADD THE TICKET ATTACHMENTS
	if ($departments[0]['FileUpload'] == 'yes' || ($departments[0]['FileUpload'] == 'users' && $was_logged_in == true))
	if (isset($_FILES['FileName']) && count($_FILES['FileName']) > 0 && $_FILES['FileName']['tmp_name'] != '' && rst_is_allowed_extension(rst_get_extension($_FILES['FileName']['name']),$departments[0]['FileUploadExtensions']))
	{
		$file = $ticketmessageid.'_'.mt_rand(10,99).'_'.(basename($_FILES['FileName']['name']));
		if(move_uploaded_file($_FILES['FileName']['tmp_name'], RST_FRONTEND_ABS_PATH.'/files/'.$file))
		{
			$db->setQuery("INSERT INTO `#__rstickets_files` SET `TicketMessageId`='".$ticketmessageid."', `UserId`='".$userid."', `FileName`='".$file."'");
			$db->query();
		}
	}
	
	$email_subject = '['.$departments[0]['DepartmentPrefix']."-".$ticketcode.'] '.$subject2;
	// SEND A COPY TO THE SUBMITTER
	if ($departments[0]['UserEmailTicket'] == 1)
		rst_send_email($email,$email_subject,$email_message,'add_ticket_customer',$fullname,(isset($file) && $file != '' ? array(RST_FRONTEND_ABS_PATH.'/files/'.$file) : null),$customfields,$totalcustomfields);
		
	// SEND A COPY TO THE STAFF
	if ($departments[0]['StaffEmailTicket'] == 1 && $automatic_userid > 0)
		rst_send_email(rst_get_email_by_userid($automatic_userid),$email_subject,$email_message,'add_ticket_staff',$fullname,(isset($file) && $file != '' ? array(RST_FRONTEND_ABS_PATH.'/files/'.$file) : null),$customfields,$totalcustomfields);
	
	// ARE THERE ANY EMAILS TO BE SENT ?
	if (strlen($departments[0]['NotifyNewTicketEmails']) > 0)
	{
		$emails = explode("\n",$departments[0]['NotifyNewTicketEmails']);
		$verified_emails = array();
		if (count($emails) > 0)
			foreach ($emails as $emailaddr)
				if (rst_is_email(trim($emailaddr)))
					$verified_emails[] = trim($emailaddr);
		if (count($verified_emails) > 0)
			foreach ($verified_emails as $verified_email)
				rst_send_email($verified_email,$email_subject,$email_message,'add_ticket_staff',$fullname,(isset($file) && $file != '' ? array(RST_FRONTEND_ABS_PATH.'/files/'.$file) : null),$customfields,$totalcustomfields);
	}
	
	if (isset($T_EVENTS['AfterAddTicket'])) eval($T_EVENTS['AfterAddTicket']);
	
	return 1010;
}

function rst_update_ticket_custom_fields($customfields,$ticketid)
{
	$ticketid = intval($ticketid);
	if ($ticketid == 0) return;
	
	$db = JFactory::getDBO();
	
	$db->setQuery("SELECT `UserId`,`DepartmentId` FROM `#__rstickets_tickets` WHERE `TicketId`='".$ticketid."' LIMIT 1");
	$ticket = $db->loadAssoc();	
	
	$departmentid = $ticket['DepartmentId'];
	$userid = $ticket['UserId'];
	
	if ($departmentid == '' || $userid == '') return;
	
	if ($_SESSION['RST_User']['Group']['CanUpdateTicket'] == 0) return;
	if ($_SESSION['RST_User']['Group']['CanSeeUnallocatedTickets'] == 0 && $userid == 0) return;
	if ($_SESSION['RST_User']['Group']['CanSeeOtherTickets'] == 0 && $userid > 0 && $_SESSION['RST_User']['UserId'] != $userid) return;
	
	$continue = false;
	foreach ($_SESSION['RST_User']['Department'] as $department)
		if ($department['DepartmentId'] == $departmentid) $continue = true;
	if ($continue == false) return;
	
	// GET CUSTOM FIELDS FOR THE DEPARTMENT
	$totalcustomfields = rst_get_departments_custom_fields($departmentid);

	// LET'S TRIM THE CUSTOM FIELDS
	if (count($totalcustomfields) > 0)
	{
		foreach ($customfields as $customfield => $value)
		{
		// WE RECEIVED THE WHOLE POST, MUST REMOVE EXTRA FIELDS
		//	if (intval($customfield) == 0) unset($customfields[$customfield]);
			if (str_replace('rstcf_','',$customfield) == $customfield)
				unset($customfields[$customfield]);
			else 
			{
				$customfields[str_replace('rstcf_','',$customfield)] = $value;
				unset($customfields[$customfield]);
			}
			
			// THIS IS WHERE THE TRIMMING TAKES PLACE - ALL FIELDS THAT DO NOT BELONG TO THE DEPARTMENT ARE REMOVED
			$found = 0;
			foreach ($totalcustomfields as $totalcustomfield)
				if ($totalcustomfield['CustomFieldId'] == $customfield) $found = 1;
			if ($found == 0) unset($customfields[$customfield]);
		}
		
		// CHECK IF REQUIRED CUSTOM FIELDS HAVE A VALUE
		foreach ($totalcustomfields as $totalcustomfield)
		{
			if ($totalcustomfield['Required'] == 1)
				if (!isset($customfields[$totalcustomfield['CustomFieldId']]) || $customfields[$totalcustomfield['CustomFieldId']] == '')
					return 11;
		}
		
		// CHECK IF CUSTOM FIELDS HAVE THE RIGHT VALUE
		foreach ($customfields as $customfield => $value)
			foreach ($totalcustomfields as $totalcustomfield)
				if ($totalcustomfield['CustomFieldId'] == $customfield && ($totalcustomfield['CustomFieldId'] == 'select' || $totalcustomfield['CustomFieldId'] == 'multipleselect' || $totalcustomfield['CustomFieldId'] == 'checkbox' || $totalcustomfield['CustomFieldId'] == 'radio'))
					if (strlen($value) > 0 && strpos($totalcustomfield['CustomFieldValues'],$value) === false)
							return 11;	
	
		
		$db->setQuery("DELETE FROM `#__rstickets_custom_fields_value` WHERE `TicketId`='".$ticketid."'");
		$db->query();
		
		// ADD THE CUSTOM FIELDS
		foreach ($customfields as $customfield => $value)
		{
			if (is_array($value))
				foreach ($value as $value2)
				{
					$db->setQuery("INSERT INTO `#__rstickets_custom_fields_value` SET `CustomFieldId`='".$customfield."', `TicketId`='".$ticketid."', `CustomFieldValue`='".rst_clean($value2)."'");
					$db->query();
				}
			else
			{
				$db->setQuery("INSERT INTO `#__rstickets_custom_fields_value` SET `CustomFieldId`='".$customfield."', `TicketId`='".$ticketid."', `CustomFieldValue`='".rst_clean($value)."'");
				$db->query();
			}
		}
		
		return 1017;
	}
}

function rst_add_ticket_reply($id,$message,$userid,$is_in_staff=false,$date=false,$cron=false)
{
	global $T_EVENTS;
	
	$db = JFactory::getDBO();
	
	if (isset($T_EVENTS['BeforeAddTicketReply'])) eval($T_EVENTS['BeforeAddTicketReply']);
	$id = intval($id);
	if ($id == 0) return;
	
	$db->setQuery("SELECT * FROM `#__rstickets_tickets` WHERE `TicketId`='".$id."' LIMIT 1");
	$ticket = $db->loadAssoc();

	$departments = rst_get_departments($ticket['DepartmentId']);
	$emailticket['UserEmailTicket'] = $departments[0]['UserEmailTicket'];
	$emailticket['StaffEmailTicket'] = $departments[0]['StaffEmailTicket'];
	
	//$email_message = nl2br(htmlentities(trim($message),ENT_QUOTES,'utf-8'));
	$email_message = nl2br($message);
	$message = rst_clean($message);
	if ($message == '') return;
	
	$userid = intval($userid);
	if ($userid == 0) return;
	
	if ($ticket['TicketStatus'] == 'closed') return;
	
	if ($is_in_staff == false)
	{
		if ($userid != $ticket['CustomerId']) return;
	}
	else
	{
		if ($cron == false)
		{
			if ($_SESSION['RST_User']['Group']['CanAnswerTicket'] == 0) return;
			if ($_SESSION['RST_User']['Group']['CanSeeUnallocatedTickets'] == 0 && $ticket['UserId'] == 0) return;
			if ($_SESSION['RST_User']['Group']['CanSeeOtherTickets'] == 0 && $ticket['UserId'] > 0 && $_SESSION['RST_User']['UserId'] != $ticket['UserId'] && $_SESSION['RST_User']['UserId'] != $ticket['CustomerId']) return;
			if ($ticket['DepartmentId'] > 0)
			{
				$continue = false;
				foreach ($_SESSION['RST_User']['Department'] as $department)
					if ($department['DepartmentId'] == $ticket['DepartmentId']) $continue = true;
				if ($continue == false) return;
			}
		}
	}
	
	if (isset($_FILES['FileName']) && count($_FILES['FileName']) > 0 && $_FILES['FileName']['tmp_name'] != '')
	{
		if (!is_writable(RST_FRONTEND_ABS_PATH.'/files/')) return 33;
		if (!rst_is_allowed_extension(rst_get_extension($_FILES['FileName']['name']),$departments[0]['FileUploadExtensions'])) return 28;
	}
	
	// ADD THE MESSAGE BODY
	$db->setQuery("INSERT INTO `#__rstickets_ticket_message` SET `TicketId`='".$id."', `UserId`='".$userid."', `TicketMessage`='".$message."', `TicketTime`='".($date == false ? time() : $date)."'");
	$db->query();
	$ticketmessageid = $db->insertid();
	// NO NEED TO AUTOCLOSE ANYMORE
	if ($is_in_staff == false)
	{
		$db->setQuery("UPDATE `#__rstickets_tickets` SET `TicketAutocloseSent`='0' WHERE `TicketId`='".$id."' LIMIT 1");
		$db->query();
	}
	// ASSIGN THIS TICKET
	$db->setQuery("SELECT `TicketAssignmentType` FROM `#__rstickets_departments` WHERE `DepartmentId`='".$ticket['DepartmentId']."'");
	if ($db->loadResult() == 'static' && $ticket['UserId'] == '0' && $is_in_staff == true)
	{
		$db->setQuery("UPDATE `#__rstickets_tickets` SET `UserId`='".$userid."' WHERE `TicketId`='".$id."' LIMIT 1");
		$db->query();
		$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets`=`OpenTickets`+1 WHERE `UserId`='".$userid."' AND `DepartmentId`='".$ticket['DepartmentId']."' LIMIT 1");
		$db->query();
		$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets` = '0' WHERE `OpenTickets` < 0");
		$db->query();
		$ticket['UserId'] = $userid;
	}
	// UPDATE THE STATUS
	$db->setQuery("UPDATE `#__rstickets_tickets` SET `TicketStatus`='".($is_in_staff == true ? 'on-hold' : 'open')."' WHERE `TicketId`='".$id."' AND `TicketStatus`='".($is_in_staff == true ? 'open' : 'on-hold')."' LIMIT 1");
	$db->query();
	
	// ADD THE TICKET ATTACHMENTS
	if ($departments[0]['FileUpload'] != 'no' && isset($_FILES['FileName']) && count($_FILES['FileName']) > 0 && $_FILES['FileName']['tmp_name'] != '' && rst_is_allowed_extension(rst_get_extension($_FILES['FileName']['name']),$departments[0]['FileUploadExtensions']))
	{
		$file = $ticketmessageid.'_'.mt_rand(10,99).'_'.(basename($_FILES['FileName']['name']));
		if(move_uploaded_file($_FILES['FileName']['tmp_name'], RST_FRONTEND_ABS_PATH.'/files/'.$file))
		{
			$db->setQuery("INSERT INTO `#__rstickets_files` SET `TicketMessageId`='".$ticketmessageid."', `UserId`='".$userid."', `FileName`='".$file."'");
			$db->query();
		}
	}
	
	$email_subject = '['.$ticket['TicketCode'].'] '.$ticket['TicketSubject'];
	
	// IF CUSTOMER REPLIED, SEND EMAIL TO STAFF
	if ($userid == $ticket['CustomerId'] && $ticket['UserId'] > 0 && $emailticket['StaffEmailTicket'] == 1)
		rst_send_email(rst_get_email_by_userid($ticket['UserId']),$email_subject,$email_message,'add_ticket_reply_staff',rst_get_fullname_by_userid($userid),(isset($file) && $file != '' ? array(RST_FRONTEND_ABS_PATH.'/files/'.$file) : null));
	
	// IF STAFF REPLIED, SEND AN EMAIL TO THE CUSTOMER
	elseif ($userid == $ticket['UserId'] && $emailticket['UserEmailTicket'] == 1)
		rst_send_email(rst_get_email_by_userid($ticket['CustomerId']),$email_subject,$email_message,'add_ticket_reply_customer',rst_get_fullname_by_userid($userid),(isset($file) && $file != '' ? array(RST_FRONTEND_ABS_PATH.'/files/'.$file) : null));
	
	// IT'S PROBABLY A GOOD IDEA TO CHECK IF THE STAFF DIDN'T REPLY BY NOW
	if ($ticket['UserId'] > 0 && $userid != $ticket['UserId'] && $userid != $ticket['CustomerId'])
	{
		if ($emailticket['UserEmailTicket'] == 1)
			rst_send_email(rst_get_email_by_userid($ticket['CustomerId']),$email_subject,$email_message,'add_ticket_reply_other',rst_get_fullname_by_userid($userid),(isset($file) && $file != '' ? array(RST_FRONTEND_ABS_PATH.'/files/'.$file) : null));
		if ($emailticket['StaffEmailTicket'] == 1)
			rst_send_email(rst_get_email_by_userid($ticket['UserId']),$email_subject,$email_message,'add_ticket_reply_other',rst_get_fullname_by_userid($userid),(isset($file) && $file != '' ? array(RST_FRONTEND_ABS_PATH.'/files/'.$file) : null));
	}
	
	if (isset($T_EVENTS['AfterAddTicketReply'])) eval($T_EVENTS['AfterAddTicketReply']);
	
	return 1019;
}

function rst_get_ticketid_by_code($code)
{
	$code = rst_clean($code);
	$db = JFactory::getDBO();
	$db->setQuery("SELECT `TicketId` FROM `#__rstickets_tickets` WHERE `TicketCode`='".$code."' LIMIT 1");
	
	return $db->loadResult();
}

function rst_close_ticket($id)
{
	$id = intval($id);
	if ($id == 0) return;
	
	$db = JFactory::getDBO();
	$db->setQuery("SELECT `UserId`,`DepartmentId`,`CustomerId` FROM `#__rstickets_tickets` WHERE `TicketId`='".$id."' AND `TicketStatus`!='closed' LIMIT 1");
	
	$ticket = $db->loadAssoc();
	if (isset($_SESSION['RST_User']['Group']['GroupId']))
	{
		if ($ticket['UserId'] == 0 && $_SESSION['RST_User']['Group']['CanSeeUnallocatedTickets'] == 0 && $_SESSION['RST_User']['Group']['CanChangeTicketStatus'] == 0) return;
		if ($ticket['UserId'] > 0 && $ticket['UserId'] != $_SESSION['RST_User']['UserId'] && $_SESSION['RST_User']['Group']['CanSeeOtherTickets'] == 0 && $_SESSION['RST_User']['Group']['CanChangeTicketStatus'] == 0) return;
		if ($ticket['DepartmentId'] > 0)
		{
			$continue = false;
			foreach ($_SESSION['RST_User']['Department'] as $department)
				if ($department['DepartmentId'] == $ticket['DepartmentId']) $continue = true;
			if ($continue == false) return;
		}
	}
	else
		if ($ticket['CustomerId'] != $_SESSION['RST_User']['UserId']) return;
	
	$db->setQuery("UPDATE `#__rstickets_tickets` SET `TicketStatus`='closed' WHERE `TicketId`='".$id."' AND `TicketStatus`!='closed' LIMIT 1");
	$db->query();
	
	$closed = $db->getAffectedRows();
	
	if ($closed == 1 && $ticket['UserId'] > 0)
	{
		$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets`=`OpenTickets`-1 WHERE `UserId`='".$ticket['UserId']."' AND `DepartmentId`='".$ticket['DepartmentId']."' LIMIT 1");
		$db->query();
		$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets` = '0' WHERE `OpenTickets` < 0");
		$db->query();
	}
	
	if ($closed == 0)
		return 17;
	else
		return 1015;
}

function rst_delete_ticket($tickets)
{
	if (is_array($tickets))
		foreach ($tickets as $key => $ticket)
			$tickets[$key] = intval($ticket);
	else
		$tickets = array(intval($tickets));
	
	if (count($tickets) == 0) return;
	
	$db = JFactory::getDBO();
	
	$db->setQuery("SELECT `TicketId`,`DepartmentId`,`UserId`,`TicketStatus` FROM `#__rstickets_tickets` WHERE `TicketId` IN (".implode(',',$tickets).")");
	$rows = $db->loadAssocList();
	foreach ($rows as $ticket)
	{
		if ($ticket['UserId'] == 0 && $_SESSION['RST_User']['Group']['CanSeeUnallocatedTickets'] == 0) continue;
		if ($ticket['UserId'] > 0 && $ticket['UserId'] != $_SESSION['RST_User']['UserId'] && $_SESSION['RST_User']['Group']['CanSeeOtherTickets'] == 0) continue;
		
		if ($ticket['DepartmentId'] > 0)
		{
			$continue = false;
			foreach ($_SESSION['RST_User']['Department'] as $department)
				if ($department['DepartmentId'] == $ticket['DepartmentId']) $continue = true;
			if ($continue == false) continue;
		}
		
		// MYSQL 4 HACK
		$ticketmessage_array = array();
		$db->setQuery("SELECT `TicketMessageId` FROM `#__rstickets_ticket_message` WHERE `TicketId`='".$ticket['TicketId']."'");
		$subrows = $db->loadAssocList();
		foreach ($subrows as $subrow)
			$ticketmessage_array[] = $subrow['TicketMessageId'];
		
		if (count($ticketmessage_array) > 0)
		{
			$db->setQuery("SELECT `FileName`,`TicketMessageId` FROM `#__rstickets_files` WHERE `TicketMessageId` IN (".implode(",",$ticketmessage_array).")");
			$files = $db->loadAssocList();
			foreach ($files as $file)
			{
				@unlink(RST_FRONTEND_ABS_PATH.'/files/'.$files['FileName']);
				$db->setQuery("DELETE FROM `#__rstickets_files` WHERE `TicketMessageId`='".$files['TicketMessageId']."'");
				$db->query();
			}
		}
		$db->setQuery("DELETE FROM `#__rstickets_ticket_message` WHERE `TicketId`='".$ticket['TicketId']."'");
		$db->query();
		$db->setQuery("DELETE FROM `#__rstickets_tickets` WHERE `TicketId`='".$ticket['TicketId']."'");
		$db->query();
		$db->setQuery("DELETE FROM `#__rstickets_custom_fields_value` WHERE `TicketId`='".$ticket['TicketId']."'");
		$db->query();
		if ($db->getAffectedRows() == 1)
		{
			if ($ticket['TicketStatus'] != 'closed' && $ticket['UserId'] > 0)
			{
				$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets`=`OpenTickets`-1 WHERE `UserId`='".$ticket['UserId']."' AND `DepartmentId`='".$ticket['DepartmentId']."' LIMIT 1");
				$db->query();
			}
				$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets` = '0' WHERE `OpenTickets` < 0");
				$db->query();
		}
	}
	return 1020;
}

function rst_update_ticket($id=false,$subject=false,$userid=false,$status=false,$priority=false)
{
	$id = intval($id);
	if ($id == 0) return;
	
	$subject = is_bool($subject) && $subject == false ? $subject : rst_clean($subject);
	$userid = is_bool($userid) && $userid == false ? $userid : intval($userid);
	$status = is_bool($status) && $status == false ? $status : rst_clean($status);
	$priority = is_bool($priority) && $priority == false ? $priority : rst_clean($priority);
	
	$db = JFactory::getDBO();
	
	$db->setQuery("SELECT * FROM `#__rstickets_tickets` WHERE `TicketId`='".$id."' LIMIT 1");
	$ticket = $db->loadAssoc();
	
	if ($userid != false && $userid > 0)
		if (rst_get_ticket_department_consistency($id,$userid) == false) return;
	
	$update_array = array();
	if (!is_bool($userid) && $userid != $ticket['UserId'] && $_SESSION['RST_User']['Group']['CanAssignTickets'] == 1) $update_array[] = "`UserId`='".$userid."'";
	if (!is_bool($subject) && $subject != $ticket['TicketSubject'] && $_SESSION['RST_User']['Group']['CanUpdateTicket'] == 1) $update_array[] = "`TicketSubject`='".$subject."'";
	if (!is_bool($priority) && $priority != $ticket['TicketPriority'] && $_SESSION['RST_User']['Group']['CanUpdateTicket'] == 1) $update_array[] = "`TicketPriority`='".$priority."'";
	if (!is_bool($userid) && $ticket['UserId'] == '0' && $userid > 0 && $_SESSION['RST_User']['Group']['CanSeeUnallocatedTickets'] == 1) $update_array[] = "`UserId`='".$userid."'";
	if (!is_bool($userid) && $ticket['UserId'] > 0 && $userid == 0 && $_SESSION['RST_User']['Group']['CanSeeOtherTickets'] == 1) $update_array[] = "`UserId`='".$userid."'";
	if (!is_bool($status) && $status != $ticket['TicketStatus'] && $_SESSION['RST_User']['Group']['CanChangeTicketStatus'] == 1) $update_array[] = "`TicketStatus`='".$status."'";
	
	if (count($update_array) > 0)
	{
		$db->setQuery("UPDATE `#__rstickets_tickets` SET ".implode(',',$update_array)." WHERE `TicketId`='".$id."' LIMIT 1");
		$db->query();
		
		if (in_array("`TicketStatus`='".$status."'",$update_array))
		{
			if ($ticket['TicketStatus'] != 'closed' && $status == 'closed' && $ticket['UserId'] > 0)
			{
				$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets`=`OpenTickets`-1 WHERE `UserId`='".$ticket['UserId']."' AND `DepartmentId`='".$ticket['DepartmentId']."' LIMIT 1");
				$db->query();
			}
			if ($ticket['TicketStatus'] == 'closed' && $status == 'open' && $ticket['UserId'] > 0)
			{
				$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets`=`OpenTickets`+1 WHERE `UserId`='".$ticket['UserId']."' AND `DepartmentId`='".$ticket['DepartmentId']."' LIMIT 1");
				$db->query();
			}
			
			if ($status == 'open' || $status == 'on-hold')
			{
				$db->setQuery("UPDATE `#__rstickets_tickets` SET `TicketAutocloseSent`='0' WHERE `TicketId`='".$id."' LIMIT 1");
				$db->query();
			}
			$ticket['TicketStatus'] = $status;
		}
		
		if (in_array("`UserId`='".$userid."'",$update_array) && $ticket['TicketStatus'] != 'closed')
		{
			if ($ticket['UserId'] > 0 && $userid > 0)
			{
				$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets`=`OpenTickets`-1 WHERE `UserId`='".$ticket['UserId']."' AND `DepartmentId`='".$ticket['DepartmentId']."' LIMIT 1");
				$db->query();
				$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets`=`OpenTickets`+1 WHERE `UserId`='".$userid."' AND `DepartmentId`='".$ticket['DepartmentId']."' LIMIT 1");
				$db->query();
			}
			
			if ($ticket['UserId'] > 0 && $userid == 0)
			{
				$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets`=`OpenTickets`-1 WHERE `UserId`='".$ticket['UserId']."' AND `DepartmentId`='".$ticket['DepartmentId']."' LIMIT 1");
				$db->query();
			}
				
			if ($ticket['UserId'] == 0 && $userid > 0)
			{
				$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets`=`OpenTickets`+1 WHERE `UserId`='".$userid."' AND `DepartmentId`='".$ticket['DepartmentId']."' LIMIT 1");
				$db->query();
			}
		
			if ($ticket['UserId'] != $userid && $userid > 0)
			{
				$ticket = rst_get_ticket_messages($ticket['TicketId']);
				$ticketcustomfields = rst_get_ticket_custom_fields($ticket['TicketId']);
				$departments = rst_get_departments($ticket['DepartmentId']);
				$totalcustomfields = rst_get_departments_custom_fields($ticket['DepartmentId']);
				$ticketmessage = end($ticket['messages']);
				
				$email_subject = '['.$ticket['TicketCode'].'] '.$ticket['TicketSubject'];
				$email_message = nl2br($ticketmessage['TicketMessage']);
				$fullname = $ticketmessage['Fullname'];
				$file = $ticketmessage['FileName'];
				
				$customfields = array();
				foreach ($ticketcustomfields as $ticketcustomfieldid => $ticketcustomfield)
					$customfields[$ticketcustomfieldid] = $ticketcustomfield['CustomFieldValues'];
				
				if ($departments[0]['NotifyAssign'])
					rst_send_email(rst_get_email_by_userid($userid),$email_subject,$email_message,'assign_email',$fullname,(isset($file) && $file != '' ? array(RST_FRONTEND_ABS_PATH.'/files/'.$file) : null),$customfields,$totalcustomfields);
			}
		}
		
		$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets` = '0' WHERE `OpenTickets` < 0");
		$db->query();
		
		return 1018;
	}
}

function rst_update_tickets($userid=false,$status=false,$priority=false,$delete=false,$tickets_array=array())
{
	$userid = is_bool($userid) && $userid == false ? $userid : intval($userid);
	$status = is_bool($status) && $status == false ? $status : rst_clean($status);
	$priority = is_bool($priority) && $priority == false ? $priority : rst_clean($priority);
	$delete = rst_clean($delete);
	if (is_array($tickets_array) && count($tickets_array) > 0)
		foreach ($tickets_array as $key => $ticket)
			$tickets_array[$key] = intval($ticket);
	$departments_array = array();
	$departments_array[] = 0;
	foreach ($_SESSION['RST_User']['Department'] as $department)
		$departments_array[] = $department['DepartmentId'];
	
	$db = JFactory::getDBO();
	
	if ($delete == 'selected' && is_array($tickets_array) && count($tickets_array) > 0 && $_SESSION['RST_User']['Group']['CanDeleteTicket'] == 1)
	{
		$db->setQuery("SELECT `TicketId` FROM `#__rstickets_tickets` WHERE `TicketId` IN (".implode(',',$tickets_array).") AND `DepartmentId` IN (".implode(',',$departments_array).")");
		$rows = $db->loadAssocList();
		unset($tickets_array);
		$tickets_array = array();
		foreach ($rows as $row)
			$tickets_array[] = $row['TicketId'];
		rst_delete_ticket($tickets_array);
		return 1014;
	}
	if (is_array($tickets_array) && count($tickets_array) > 0)
	{
		foreach ($tickets_array as $ticket)
			rst_update_ticket($ticket,false,$userid,$status,$priority);
		return 1013;
	}
}

function rst_update_ticket_reply($id,$message)
{
	$id = intval($id);
	if ($id == 0) return;
	
	$db = JFactory::getDBO();
	
	$message = rst_clean($message);
	if ($_SESSION['RST_User']['Group']['CanUpdateTicketReplies'] == 0) return;
	$db->setQuery("SELECT `TicketId` FROM `#__rstickets_ticket_message` WHERE `TicketMessageId`='".$id."' LIMIT 1");
	$ticketid = $db->loadResult();
	$db->setQuery("SELECT `UserId` FROM `#__rstickets_tickets` WHERE `TicketId`='".$ticketid."' LIMIT 1");
	$userid = $db->loadResult();
	$db->setQuery("SELECT `DepartmentId` FROM `#__rstickets_tickets` WHERE `TicketId`='".$ticketid."' LIMIT 1");
	$departmentid = $db->loadResult();
	
	if ($userid == '0' && $_SESSION['RST_User']['Group']['CanSeeUnallocatedTickets'] == 0) return;
	if ($userid > 0 && $userid != $_SESSION['RST_User']['UserId'] && $_SESSION['RST_User']['Group']['CanSeeOtherTickets'] == 0) return;
	
	$continue = false;
	foreach ($_SESSION['RST_User']['Department'] as $department)
		if ($department['DepartmentId'] == $departmentid) $continue = true;
	if ($continue == false) return;
	
	$db->setQuery("UPDATE `#__rstickets_ticket_message` SET `TicketMessage`='".$message."' WHERE `TicketMessageId`='".$id."' LIMIT 1");
	$db->query();
	if ($db->getAffectedRows() == 1) return 1022;
}

function rst_delete_ticket_reply($id)
{
	$id = intval($id);
	if ($id == 0) return;
	
	if ($_SESSION['RST_User']['Group']['CanDeleteTicketReplies'] == 0) return;
	
	$db = JFactory::getDBO();
	
	$db->setQuery("SELECT `TicketId` FROM `#__rstickets_ticket_message` WHERE `TicketMessageId`='".$id."' LIMIT 1");
	$ticketid = $db->loadResult();
	$db->setQuery("SELECT `UserId`,`DepartmentId`,`CustomerId`,`TicketStatus` FROM `#__rstickets_tickets` WHERE `TicketId`='".$ticketid."' LIMIT 1");
	$ticket = $db->loadAssoc();
	if (count($ticket) == 0) return;
	$userid = $ticket['UserId'];
	$customerid = $ticket['CustomerId'];
	$departmentid = $ticket['DepartmentId'];
	if ($userid == '0' && $_SESSION['RST_User']['Group']['CanSeeUnallocatedTickets'] == 0) return;
	if ($userid > 0 && $userid != $_SESSION['RST_User']['UserId'] && $_SESSION['RST_User']['Group']['CanSeeOtherTickets'] == 0) return;
	
	$continue = false;
	foreach ($_SESSION['RST_User']['Department'] as $department)
		if ($department['DepartmentId'] == $departmentid) $continue = true;
	if ($continue == false) return;
	
	$db->setQuery("SELECT `FileName` FROM `#__rstickets_files` WHERE `TicketMessageId`='".$id."' LIMIT 1");
	$filename = $db->loadResult();
	if ($filename !== false)
	{
		@unlink(RST_FRONTEND_ABS_PATH.'/files/'.$filename);
		$db->setQuery("DELETE FROM `#__rstickets_files` WHERE `TicketMessageId`='".$id."'");
		$db->query();
	}
	$deleted = 0;
	$db->setQuery("DELETE FROM `#__rstickets_ticket_message` WHERE `TicketMessageId`='".$id."' LIMIT 1");
	$db->query();
	if ($db->getAffectedRows() == 1) $deleted = 1;
	if ($deleted == 1 && $ticket['TicketStatus'] != 'closed')
	{
		$db->setQuery("SELECT `UserId` FROM `#__rstickets_ticket_message` WHERE `TicketId`='".$ticketid."' ORDER BY `TicketTime` DESC ");
		$lastid = $db->loadResult();
		if ($lastid == $customerid)
		{
			$db->setQuery("UPDATE `#__rstickets_tickets` SET `TicketStatus`='open' WHERE `TicketId`='".$ticketid."' LIMIT 1");
			$db->query();
		}
		if ($lastid == $userid)
		{
			$db->setQuery("UPDATE `#__rstickets_tickets` SET `TicketStatus`='on-hold' WHERE `TicketStatus`='on-hold' AND `TicketId`='".$ticketid."'");
			$db->query();
		}
	}
	if ($deleted == 1) return 1021;
}

function rst_get_ticket_messages($id)
{
	$id = intval($id);
	$return = array();
	
	$db = JFactory::getDBO();
	
	$db->setQuery("SELECT `#__rstickets_tickets`.*,IFNULL(`#__users`.`name`,'Unassigned') AS `Fullname` FROM `#__rstickets_tickets` LEFT JOIN `#__users` ON (`#__users`.`id`=`#__rstickets_tickets`.`UserId`) WHERE `TicketId`='".$id."'");
	
	$return = $db->loadAssoc();
	
	$db->setQuery("SELECT `#__rstickets_files`.`FileName` , `#__rstickets_files`.`FileId` , `#__rstickets_ticket_message`. * , `ext1`.`id` AS `UserId` , `ext1`.`name` AS `Fullname` , `ext1`.`username` AS `Username` , `ext1`.`email` AS `Email`, `ext2`.`id` AS `NUserId`, `ext2`.`name` AS `NFullname`, `ext2`.`email` AS `NEmail`, `#__rstickets_ticket_notes`.`TicketNoteId`,  `#__rstickets_ticket_notes`.`TicketNote`, `#__rstickets_ticket_notes`.`TicketNoteTime`
FROM `#__rstickets_ticket_message`
LEFT JOIN `#__rstickets_ticket_notes` ON ( `#__rstickets_ticket_notes`.`TicketMessageId` = `#__rstickets_ticket_message`.`TicketMessageId` )
LEFT JOIN `#__users` AS `ext1` ON ( `ext1`.`id` = `#__rstickets_ticket_message`.`UserId` )
LEFT JOIN `#__users` AS `ext2` ON ( `ext2`.`id` = `#__rstickets_ticket_notes`.`UserId` )
LEFT JOIN `#__rstickets_files` ON ( `#__rstickets_files`.`TicketMessageId` = `#__rstickets_ticket_message`.`TicketMessageId` )
WHERE `TicketId` = '".$id."'
ORDER BY `TicketTime` DESC");
	
	$rows = $db->loadAssocList();
	foreach ($rows as $row)
	{
		$row['TicketMessage'] = rst_parse_links($row['TicketMessage']);
		$return['messages'][] = $row;
	}
			
	return $return;
}

function rst_get_ticket_user_consistency($ticketid,$userid,$is_in_staff)
{
	$ticketid = intval($ticketid);
	$userid = intval($userid);
	
	$db = JFactory::getDBO();
	
	if ($is_in_staff == true)
		$db->setQuery("SELECT `TicketId` FROM `#__rstickets_tickets` WHERE `UserId`='".$userid."' AND `TicketId`='".$ticketid."' LIMIT 1");
	else
		$db->setQuery("SELECT `TicketId` FROM `#__rstickets_tickets` WHERE `CustomerId`='".$userid."' AND `TicketId`='".$ticketid."' LIMIT 1");
		
	$db->query();
	
	return ($db->getNumRows() == 1);
}

function rst_get_ticket_department_consistency($ticketid,$userid)
{
	$ticketid = intval($ticketid);
	$userid = intval($userid);
	
	$db = JFactory::getDBO();
	
	$db->setQuery("SELECT `DepartmentId` FROM `#__rstickets_tickets` WHERE `TicketId`='".$ticketid."' LIMIT 1");
	$departmentid = $db->loadResult();
	$db->setQuery("SELECT `DepartmentId` FROM `#__rstickets_staff_to_department` WHERE `UserId`='".$userid."' AND `DepartmentId`='".$departmentid."' LIMIT 1");
	$d = $db->loadResult();
	
	if ($departmentid > 0 && $d > 0)
		return ($departmentid == $d);
}

function rst_get_ticket_custom_fields($id)
{
	$id = intval($id);
	$return = array();
	$temp = array();
	
	$db = JFactory::getDBO();
	
	$db->setQuery("SELECT `#__rstickets_custom_fields_value`.*,`#__rstickets_custom_fields`.`CustomFieldLabel` FROM `#__rstickets_custom_fields_value` INNER JOIN `#__rstickets_custom_fields` ON (`#__rstickets_custom_fields`.`CustomFieldId`=`#__rstickets_custom_fields_value`.`CustomFieldId`) WHERE `TicketId`='".$id."'");
	$temp = $db->loadAssocList();
			
	if (!empty($temp))
		foreach ($temp as $tempitem)
		{
			if (!isset($return[$tempitem['CustomFieldId']]))
				$return[$tempitem['CustomFieldId']] = array('CustomFieldLabel' => $tempitem['CustomFieldLabel'], 'CustomFieldValues' => array($tempitem['CustomFieldValue']));
			else
				$return[$tempitem['CustomFieldId']]['CustomFieldValues'][] = $tempitem['CustomFieldValue'];
		}
	
	return $return;	
}

function rst_move_ticket($ticketid,$departmentid,$customfields)
{
	if ($departmentid > 0)
		$departments = rst_get_departments($departmentid);
	else
		$departments[0] = array('TicketGenerationRule' => 'random','DepartmentPrefix' => 'UNASSIGNED');
	
	if (count($departments) == 0) return;

	$ticket = rst_get_ticket_messages($ticketid);
	
	if (count($ticket) == 0) return;
	
	$db = JFactory::getDBO();
	
	// CHECK THE DEPARTMENT TICKET GENERATION RULE
	if ($departments[0]['TicketGenerationRule'] == 'sequential')
	{
		$ticketcode = $departments[0]['NextTicketNumber'];
		$db->setQuery("UPDATE `#__rstickets_departments` SET `NextTicketNumber`='".($ticketcode+1)."' WHERE `DepartmentId`='".$departmentid."'");
		$db->query();
		$ticketcode = str_pad($ticketcode, 10, "0", STR_PAD_LEFT);
	}
	elseif ($departments[0]['TicketGenerationRule'] == 'random')
	{
		$ticketcode = strtoupper(rst_random_pass(10));
		$db->setQuery("SELECT `TicketId` FROM `#__rstickets_tickets` WHERE `TicketCode`='".$departments[0]['DepartmentPrefix']."-".$ticketcode."' LIMIT 1");
		$db->query();
		while ($db->getNumRows() > 0)
		{
			$ticketcode = strtoupper(rst_random_pass(10));
			$db->setQuery("SELECT `TicketId` FROM `#__rstickets_tickets` WHERE `TicketCode`='".$departments[0]['DepartmentPrefix']."-".$ticketcode."' LIMIT 1");
			$db->query();
		}
	}

	// GET CUSTOM FIELDS FOR THE DEPARTMENT
	if ($departmentid > 0)
		$totalcustomfields = rst_get_departments_custom_fields($departmentid);
	else
		$totalcustomfields = array();
	
	// LET'S TRIM THE CUSTOM FIELDS
	if (count($totalcustomfields) > 0)
	{
		foreach ($customfields as $customfield => $value)
		{
			// WE RECEIVED THE WHOLE POST, MUST REMOVE EXTRA FIELDS
			if (str_replace('rstcf_','',$customfield) == $customfield)
			{
				unset($customfields[$customfield]);
				continue;
			}
			else 
			{
				$customfields[str_replace('rstcf_','',$customfield)] = $value;
				unset($customfields[$customfield]);
			}
		}				
		
		foreach ($customfields as $customfield => $value)
		{	
			//if (intval($customfield) == 0)
			//	unset($customfields[$customfield]);
			// THIS IS WHERE THE TRIMMING TAKES PLACE - ALL FIELDS THAT DO NOT BELONG TO THE DEPARTMENT ARE REMOVED
			$found = 0;
			foreach ($totalcustomfields as $totalcustomfield)
				if ($totalcustomfield['CustomFieldId'] == $customfield) $found = 1;
			if ($found == 0) unset($customfields[$customfield]);
		}
		
		// CHECK IF REQUIRED CUSTOM FIELDS HAVE A VALUE
		foreach ($totalcustomfields as $totalcustomfield)
		{
			if ($totalcustomfield['Required'] == 1)
				if (!isset($customfields[$totalcustomfield['CustomFieldId']]) || $customfields[$totalcustomfield['CustomFieldId']] == '')
					return 11;
		}
		
		// CHECK IF CUSTOM FIELDS HAVE THE RIGHT VALUE
		foreach ($customfields as $customfield => $value)
			foreach ($totalcustomfields as $totalcustomfield)
				if ($totalcustomfield['CustomFieldId'] == $customfield && ($totalcustomfield['CustomFieldId'] == 'select' || $totalcustomfield['CustomFieldId'] == 'multipleselect' || $totalcustomfield['CustomFieldId'] == 'checkbox' || $totalcustomfield['CustomFieldId'] == 'radio'))
					if (strlen($value) > 0 && strpos($totalcustomfield['CustomFieldValues'],$value) === false)
							return 11;	
	}

	// ADD THE CUSTOM FIELDS
	$db->setQuery("DELETE FROM `#__rstickets_custom_fields_value` WHERE `TicketId`='".$ticketid."'");
	$db->query();
	if (count($totalcustomfields) > 0)
	{
		foreach ($customfields as $customfield => $value)
		{
			if (is_array($value))
				foreach ($value as $value2)
				{
					$db->setQuery("INSERT INTO `#__rstickets_custom_fields_value` SET `CustomFieldId`='".$customfield."', `TicketId`='".$ticketid."', `CustomFieldValue`='".rst_clean($value2)."'");
					$db->query();
				}
			else
			{
				$db->setQuery("INSERT INTO `#__rstickets_custom_fields_value` SET `CustomFieldId`='".$customfield."', `TicketId`='".$ticketid."', `CustomFieldValue`='".rst_clean($value)."'");
				$db->query();
			}
		}
	}
	$db->setQuery("UPDATE `#__rstickets_tickets` SET `DepartmentId`='".$departmentid."',`TicketCode`='".$departments[0]['DepartmentPrefix']."-".$ticketcode."' WHERE `TicketId`='".$ticketid."' LIMIT 1");
	$db->query();
	
	if ($ticket['TicketStatus'] != 'closed' && $ticket['UserId'] > 0)
	{
		$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets`=`OpenTickets`-1 WHERE `UserId`='".$ticket['UserId']."' AND `DepartmentId`='".$ticket['DepartmentId']."' LIMIT 1");
		$db->query();
		$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets`=`OpenTickets`+1 WHERE `UserId`='".$ticket['UserId']."' AND `DepartmentId`='".$departmentid."' LIMIT 1");
		$db->query();
	}
	
	$db->setQuery("UPDATE `#__rstickets_staff_to_department` SET `OpenTickets` = '0' WHERE `OpenTickets` < 0");
	$db->query();
	
	return 1028;
}

function rst_random_pass($length=6)
{
    $chars = "abcdefghijkmnopqrstuvwxyz0123456789";
    $i = 1;
    $pass = '';
    while ($i<=$length)
	{
       $num = mt_rand(0,34);
       $tmp = substr($chars, $num, 1);
       $pass = $pass . $tmp;
       $i++;
    }
    return $pass;
}

function rst_gen_custom_fields($departmentid=0)
{
	global $T_SETTINGS;
	$departmentid = intval($departmentid);
	$return = '';
	
	$db = JFactory::getDBO();
	
	$db->setQuery("SELECT `DepartmentId` FROM `#__rstickets_departments` ".($departmentid > 0 ? " WHERE `DepartmentId`='".$departmentid."'" : ""));
	$rows = $db->loadAssocList();
	foreach($rows as $row)
	{
		$db->setQuery("SELECT * FROM `#__rstickets_custom_fields` WHERE `DepartmentId`='".$row['DepartmentId']."'");
		$rows2 = $db->loadAssocList();
		foreach ($rows2 as $row2)
		{
			$return .= '<tr class="'.(isset($_POST['DepartmentId']) && $_POST['DepartmentId'] == $row['DepartmentId'] ? '' : 'custom_fields').'">';
			$return .= '<td><input type="hidden" name="DepartmentIdHolder" value="'.$row['DepartmentId'].'" />'.($row2['Required'] == 1 ? '<strong>'.$row2['CustomFieldLabel'].'</strong>' : $row2['CustomFieldLabel']).'</td>
			<td>';
			switch ($row2['CustomFieldType'])
			{
				case 'textbox':
				$return .= '<input type="text" name="rstcf_'.$row2['CustomFieldId'].'" id="rstcf_'.$row2['CustomFieldId'].'" value="'.(isset($_POST['rstcf_'.$row2['CustomFieldId']]) ? strip_tags($_POST['rstcf_'.$row2['CustomFieldId']]) : (strip_tags($row2['CustomFieldValues']))).'" />';
				break;
				
				case 'textarea':
				$return .= '<textarea name="rstcf_'.$row2['CustomFieldId'].'" id="rstcf_'.$row2['CustomFieldId'].'" rows="5" cols="20">'.(isset($_POST['rstcf_'.$row2['CustomFieldId']]) ? strip_tags($_POST['rstcf_'.$row2['CustomFieldId']]) : '').'</textarea>';
				break;
				
				case 'select':
				$return .= '<select name="rstcf_'.$row2['CustomFieldId'].'" id="rstcf_'.$row2['CustomFieldId'].'"><option value="">'.LBL_PLEASE_SELECT.'</option>';
				$values = explode("\n",$row2['CustomFieldValues']);
				foreach ($values as $value)
					$return .= '<option '.(isset($_POST['rstcf_'.$row2['CustomFieldId']]) && $_POST['rstcf_'.$row2['CustomFieldId']] == trim($value) ? 'selected="selected"' : '').' value="'.trim($value).'">'.trim($value).'</option>';
				$return .= '</select>';
				break;
				
				case 'multipleselect':
				if (isset($_POST['rstcf_'.$row2['CustomFieldId']]) && !is_array($_POST['rstcf_'.$row2['CustomFieldId']]))
					$_POST['rstcf_'.$row2['CustomFieldId']] = array($_POST['rstcf_'.$row2['CustomFieldId']]);
				$return .= '<select name="rstcf_'.$row2['CustomFieldId'].'[]" id="rstcf_'.$row2['CustomFieldId'].'" multiple="multiple">';
				$values = explode("\n",$row2['CustomFieldValues']);
				foreach ($values as $value)
					$return .= '<option '.(isset($_POST['rstcf_'.$row2['CustomFieldId']]) && is_array($_POST['rstcf_'.$row2['CustomFieldId']]) && in_array(trim($value),$_POST['rstcf_'.$row2['CustomFieldId']]) ? 'selected="selected"' : '').' value="'.trim($value).'">'.trim($value).'</option>';
				$return .= '</select>';
				break;
				
				case 'checkbox':
				if (isset($_POST['rstcf_'.$row2['CustomFieldId']]) && !is_array($_POST['rstcf_'.$row2['CustomFieldId']]))
					$_POST['rstcf_'.$row2['CustomFieldId']] = array($_POST['rstcf_'.$row2['CustomFieldId']]);
				$values = explode("\n",$row2['CustomFieldValues']);
				foreach ($values as $nr => $value)
					$return .= '<input type="checkbox" '.(isset($_POST['rstcf_'.$row2['CustomFieldId']]) && in_array(trim($value), $_POST['rstcf_'.$row2['CustomFieldId']]) ? 'checked="checked"' : '').' name="rstcf_'.$row2['CustomFieldId'].'[]" id="rstcf_'.$row2['CustomFieldId'].'_'.$nr.'" value="'.trim($value).'" class="rst_checkbox" />'.trim($value).'<br/>';
				break;
				
				case 'radio':
				$values = explode("\n",$row2['CustomFieldValues']);
				foreach ($values as $value)
					$return .= '<input type="radio" '.(isset($_POST['rstcf_'.$row2['CustomFieldId']]) && $_POST['rstcf_'.$row2['CustomFieldId']] == trim($value) ? 'checked="checked"' : '').' name="rstcf_'.$row2['CustomFieldId'].'" id="rstcf_'.$row2['CustomFieldId'].'" value="'.trim($value).'" class="rst_checkbox" />'.trim($value).'<br/>';
				break;
				
				case 'calendar':
				$return .= '<input type="text" name="rstcf_'.$row2['CustomFieldId'].'" id="rstcf_'.$row2['CustomFieldId'].'" value="'.(isset($_POST['rstcf_'.$row2['CustomFieldId']]) ? strip_tags($_POST['rstcf_'.$row2['CustomFieldId']]) : (strip_tags($row2['CustomFieldValues']))).'" onclick="displayCalendar(this,\''.$T_SETTINGS['Date_Format_JS'].'\',this)" />';
				break;
				
				case 'calendartime':
				$return .= '<input type="text" name="rstcf_'.$row2['CustomFieldId'].'" id="rstcf_'.$row2['CustomFieldId'].'" value="'.(isset($_POST['rstcf_'.$row2['CustomFieldId']]) ? strip_tags($_POST['rstcf_'.$row2['CustomFieldId']]) : (strip_tags($row2['CustomFieldValues']))).'" onclick="displayCalendar(this,\''.$T_SETTINGS['Date_Format_JS'].' hh:ii\',this,true)" />';
				break;
			}
			$return .= '</td></tr>';
		}
	}
	return $return;
}

function rst_send_email($email,$subject,$message,$message_type,$fullname='',$attachment=null,$customfields=array(),$totalcustomfields=array())
{
	global $T_SETTINGS;
	$RST_adapter = $GLOBALS['RST_adapter'];
	
	$customfields_placeholder = '';
	if (count($totalcustomfields) > 0 && count($customfields) > 0)
		foreach ($totalcustomfields as $totalcustomfield)
			if (isset($customfields[$totalcustomfield['CustomFieldId']]))
				$customfields_placeholder .= $totalcustomfield['CustomFieldLabel'].': '.(is_array($customfields[$totalcustomfield['CustomFieldId']]) ? implode(',',$customfields[$totalcustomfield['CustomFieldId']]) : $customfields[$totalcustomfield['CustomFieldId']]).'<br />';
	
	if (!rst_is_email($email)) return;
	// DEFINE HEADERS
	$headers  = 'MIME-Version: 1.0' . "\r\n";
	$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
	$headers .= 'To: '.$fullname.' <'.$email.'>' . "\r\n";
	$headers .= 'From: '.$T_SETTINGS['Email_Address_Fullname'].' <'.$T_SETTINGS['Email_Address'].'>' . "\r\n";
	
	$top = RST_TEMPLATE_TOP;
	$bottom = RST_TEMPLATE_BOTTOM;
	
	//$message = rst_clean($message);
	
	switch ($message_type)
	{
		// NEW USER -> WELCOME EMAIL
		case 'new_user':
		$email_message = $top.(rst_replace_placeholder(array('{live_site}','{username}','{password}'),array($RST_adapter->getConfig('live_site_no_slash'),$message['username'],$message['password']),RST_NEW_USER)).$bottom;
		break;
		
		// ADD A NEW TICKET -> CUSTOMER'S COPY
		case 'add_ticket_customer':
		$email_message = $top.(rst_replace_placeholder(array('{live_site}','{reply_above}','{fullname}','{message}','{custom_fields}'),array($RST_adapter->getConfig('live_site_no_slash'),$T_SETTINGS['Email_Reply_Above'],$fullname,$message,$customfields_placeholder),RST_ADD_TICKET_CUSTOMER)).$bottom;
		break;
		
		// ADD A NEW TICKET -> STAFF'S COPY
		case 'add_ticket_staff':
		$email_message = $top.(rst_replace_placeholder(array('{live_site}','{reply_above}','{fullname}','{message}','{custom_fields}'),array($RST_adapter->getConfig('live_site_no_slash'),$T_SETTINGS['Email_Reply_Above'],$fullname,$message,$customfields_placeholder),RST_ADD_TICKET_STAFF)).$bottom;
		break;
		
		// MAIL THAT ARRIVES IN STAFF'S INBOX
		case 'add_ticket_reply_staff':
		case 'add_ticket_reply_other':
		$email_message = $top.(rst_replace_placeholder(array('{live_site}','{reply_above}','{fullname}','{message}'),array($RST_adapter->getConfig('live_site_no_slash'),$T_SETTINGS['Email_Reply_Above'],$fullname,$message),RST_ADD_TICKET_REPLY_STAFF)).$bottom;
		break;
		
		// MAIL THAT ARRIVES IN CUSTOMER'S INBOX
		case 'add_ticket_reply_customer':
		$email_message = $top.(rst_replace_placeholder(array('{live_site}','{reply_above}','{fullname}','{message}'),array($RST_adapter->getConfig('live_site_no_slash'),$T_SETTINGS['Email_Reply_Above'],$fullname,$message),RST_ADD_TICKET_REPLY_CUSTOMER)).$bottom;
		break;
		
		// SEND NOTIFICATION EMAIL
		case 'autoclose_email':
		$email_message = $top.(rst_replace_placeholder(array('{live_site}','{subject}','{email_interval}','{close_interval}'),array($RST_adapter->getConfig('live_site_no_slash'),rst_get_subject_by_ticketid($message),$T_SETTINGS['Autoclose_Email_Interval'],$T_SETTINGS['Autoclose_Interval']),RST_NOTIFICATION_EMAIL)).$bottom;
		break;
		
		case 'rejected_email':
		switch ($T_SETTINGS['Email_Accept_New_Tickets'])
		{
			case 'yes':$accept = LBL_EVERYONE;break;
			case 'users':$accept = LBL_REGISTERED;break;
			case 'no':$accept = LBL_NOBODY;break;
		}
		$email_message = $top.(rst_replace_placeholder(array('{live_site}','{accept}'),array($RST_adapter->getConfig('live_site_no_slash'),$accept),RST_REJECT_EMAIL)).$bottom;
		break;
		
		case 'assign_email':
		$email_message = $top.(rst_replace_placeholder(array('{live_site}','{reply_above}','{fullname}','{message}','{custom_fields}'),array($RST_adapter->getConfig('live_site_no_slash'),$T_SETTINGS['Email_Reply_Above'],$fullname,$message,$customfields_placeholder),RST_ADD_TICKET_STAFF)).$bottom;
		break;
	}
	
	//if (function_exists('html_entity_decode'))
	//	$subject = html_entity_decode($subject);
	
	$RST_adapter->mail($T_SETTINGS['Email_Address'],$T_SETTINGS['Email_Address_Fullname'],$email, $subject, stripslashes($email_message), 1,null,null,$attachment);
	//@mail($email,$subject,$email_message,$headers);
}

function rst_update_email_settings($email,$server,$protocol,$security,$port,$account,$pass,$fullname,$crontype,$croninterval,$accept,$defaultdept)
{
	global $T_SETTINGS;
	
	$db = JFactory::getDBO();
	
	$port = intval($port);
	$croninterval = intval($croninterval);
	$account = rst_clean($account);
	$pass = rst_clean($pass, false);
	$fullname = rst_clean($fullname, false);
	$crontype = $crontype == 'cron' ? 'cron' : 'include';
	$protocol = $protocol == '/pop3' ? '/pop3' : '/imap';
	$security = $security == '/ssl' ? '/ssl' : '';
	$accept = rst_clean($accept, false);
	$defaultdept = intval($defaultdept);
	
	if (rst_is_email($email))
		$T_SETTINGS['Email_Address'] = $email;
	else
		return 18;
		
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Email_Address']."' WHERE `setting`='Email_Address'");
	$db->query();
	
	if ($fullname == '') return 24;
	$T_SETTINGS['Email_Address_Fullname'] = $fullname;
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Email_Address_Fullname']."' WHERE `setting`='Email_Address_Fullname'");
	$db->query();
	
	if(defined('RST_PLUGIN_CRON'))
	{
		if ($server == '') return 21;
		$T_SETTINGS['Email_Server'] = $server;
		
		if (is_numeric($port) && $port > 0 && $port <= 65535) $T_SETTINGS['Email_Server_Port'] = $port;
		else return 19;
		
		if ($account == '') return 22;
		$T_SETTINGS['Email_Address_Account'] = $account;
		
		if ($pass == '') return 23;
		$T_SETTINGS['Email_Address_Password'] = $pass;
		
		if (is_numeric($croninterval) && $croninterval > 0 && $croninterval <= 1440) $T_SETTINGS['Email_Cron_Interval'] = $croninterval;
		else return 20;
		
		$T_SETTINGS['Email_Cron_Type'] = $crontype;
		$T_SETTINGS['Email_Server_Protocol'] = $protocol;
		$T_SETTINGS['Email_Server_Security'] = $security;
		$T_SETTINGS['Email_Accept_New_Tickets'] = $accept;
		$T_SETTINGS['Email_Default_Department'] = $defaultdept;
		
		$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Email_Server']."' WHERE `setting`='Email_Server'");
		$db->query();
		
		$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Email_Server_Port']."' WHERE `setting`='Email_Server_Port'");
		$db->query();
		
		$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Email_Server_Protocol']."' WHERE `setting`='Email_Server_Protocol'");
		$db->query();
		
		$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Email_Server_Security']."' WHERE `setting`='Email_Server_Security'");
		$db->query();
		
		$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Email_Address_Account']."' WHERE `setting`='Email_Address_Account'");
		$db->query();
		
		$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Email_Address_Password']."' WHERE `setting`='Email_Address_Password'");
		$db->query();
		
		$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Email_Cron_Type']."' WHERE `setting`='Email_Cron_Type'");
		$db->query();
		
		$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Email_Cron_Interval']."' WHERE `setting`='Email_Cron_Interval'");
		$db->query();
		
		$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Email_Accept_New_Tickets']."' WHERE `setting`='Email_Accept_New_Tickets'");
		$db->query();
		
		$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Email_Default_Department']."' WHERE `setting`='Email_Default_Department'");
		$db->query();
	}
	return 1009;
}

function rst_update_listing_settings($btime,$bcode,$bsubject,$bstaff,$bcustomer,$bpriority,$bstatus,$ftime,$fcode,$fsubject,$fstaff,$fcustomer,$fpriority,$fstatus)
{
	global $T_SETTINGS;
	$T_SETTINGS['Backend_TicketTime'] = intval($btime);
	$T_SETTINGS['Backend_TicketCode'] = intval($bcode);
	$T_SETTINGS['Backend_TicketSubject'] = intval($bsubject);
	$T_SETTINGS['Backend_StaffFullname'] = intval($bstaff);
	$T_SETTINGS['Backend_CustomerFullname'] = intval($bcustomer);
	$T_SETTINGS['Backend_TicketPriority'] = intval($bpriority);
	$T_SETTINGS['Backend_TicketStatus'] = intval($bstatus);
	$T_SETTINGS['Frontend_TicketTime'] = intval($ftime);
	$T_SETTINGS['Frontend_TicketCode'] = intval($fcode);
	$T_SETTINGS['Frontend_TicketSubject'] = intval($fsubject);
	$T_SETTINGS['Frontend_StaffFullname'] = intval($fstaff);
	$T_SETTINGS['Frontend_CustomerFullname'] = intval($fcustomer);
	$T_SETTINGS['Frontend_TicketPriority'] = intval($fpriority);
	$T_SETTINGS['Frontend_TicketStatus'] = intval($fstatus);
	
	$db = JFactory::getDBO();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Backend_TicketTime']."' WHERE `setting`='Backend_TicketTime'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Backend_TicketCode']."' WHERE `setting`='Backend_TicketCode'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Backend_TicketSubject']."' WHERE `setting`='Backend_TicketSubject'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Backend_StaffFullname']."' WHERE `setting`='Backend_StaffFullname'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Backend_CustomerFullname']."' WHERE `setting`='Backend_CustomerFullname'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Backend_TicketPriority']."' WHERE `setting`='Backend_TicketPriority'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Backend_TicketStatus']."' WHERE `setting`='Backend_TicketStatus'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Frontend_TicketTime']."' WHERE `setting`='Frontend_TicketTime'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Frontend_TicketCode']."' WHERE `setting`='Frontend_TicketCode'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Frontend_TicketSubject']."' WHERE `setting`='Frontend_TicketSubject'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Frontend_StaffFullname']."' WHERE `setting`='Frontend_StaffFullname'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Frontend_CustomerFullname']."' WHERE `setting`='Frontend_CustomerFullname'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Frontend_TicketPriority']."' WHERE `setting`='Frontend_TicketPriority'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Frontend_TicketStatus']."' WHERE `setting`='Frontend_TicketStatus'");
	$db->query();
	
	return 1009;
}

function rst_update_general_settings($dateformat, $license_code, $rstickets_link, $rstickets_menu, $timezone='', $rstickets_addtickets, $rstickets_mysql_utf8, $rstickets_custom_user_link, $staff_can_add_tickets)
{
	global $T_SETTINGS;
	
	$db = JFactory::getDBO();
	
	switch ($dateformat)
	{
		case 'd.m':$dateformatjs = 'dd.mm';break;
		case 'm.d':$dateformatjs = 'mm.dd';break;
		case 'd.m.Y':$dateformatjs = 'dd.mm.yyyy';break;
		case 'm.d.Y':$dateformatjs = 'mm.dd.yyyy';break;
		default:case 'd/m/Y':$dateformatjs = 'dd/mm/yyyy';break;
		case 'm/d/Y':$dateformatjs = 'mm/dd/yyyy';break;
		case 'Y-m-d':$dateformatjs = 'yyyy-mm-dd';break;
	}
	$T_SETTINGS['License_Code'] = rst_clean($license_code);
	$T_SETTINGS['Date_Format'] = $dateformat;
	$T_SETTINGS['Date_Format_JS'] = $dateformatjs;
	$T_SETTINGS['RStickets_Link'] = intval($rstickets_link);
	$T_SETTINGS['RStickets_Show_Menu'] = intval($rstickets_menu);
	$T_SETTINGS['Date_Timezone'] = rst_clean($timezone);
	$T_SETTINGS['RStickets_Add_Tickets'] = rst_clean($rstickets_addtickets);
	$T_SETTINGS['RStickets_MySQL_UTF8'] = intval($rstickets_mysql_utf8);
	$T_SETTINGS['RStickets_Custom_User_Link'] = rst_clean($rstickets_custom_user_link, false);
	$T_SETTINGS['Staff_Can_Add_Tickets'] = rst_clean($staff_can_add_tickets);
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Date_Format']."' WHERE `setting`='Date_Format'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Date_Format_JS']."' WHERE `setting`='Date_Format_JS'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['License_Code']."' WHERE `setting`='License_Code'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['RStickets_Link']."' WHERE `setting`='RStickets_Link'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['RStickets_Show_Menu']."' WHERE `setting`='RStickets_Show_Menu'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Date_Timezone']."' WHERE `setting`='Date_Timezone'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['RStickets_Add_Tickets']."' WHERE `setting`='RStickets_Add_Tickets'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['RStickets_MySQL_UTF8']."' WHERE `setting`='RStickets_MySQL_UTF8'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['RStickets_Custom_User_Link']."' WHERE `setting`='RStickets_Custom_User_Link'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Staff_Can_Add_Tickets']."' WHERE `setting`='Staff_Can_Add_Tickets'");
	$db->query();
	
	if (function_exists('date_default_timezone_set') && $T_SETTINGS['Date_Timezone'] != '')
		@date_default_timezone_set($T_SETTINGS['Date_Timezone']);
	return 1009;
}

function rst_update_captcha_settings($enabled, $characters, $dots, $lines, $case, $enabledfor_array)
{
	global $T_SETTINGS;
	$T_SETTINGS['Captcha_Enabled'] = intval($enabled);
	$db = JFactory::getDBO();
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Captcha_Enabled']."' WHERE `setting`='Captcha_Enabled'");
	$db->query();
	if (intval($characters) < 3) return 31;
	$T_SETTINGS['Captcha_Characters'] = intval($characters);
	$T_SETTINGS['Captcha_Dots'] = intval($dots);
	$T_SETTINGS['Captcha_Lines'] = intval($lines);
	$T_SETTINGS['Captcha_Case_Sensitive'] = intval($case);
	
	$enabledfor = '';
	if (count($enabledfor_array) > 0)
		foreach ($enabledfor_array as $value)
			$enabledfor .= rst_clean($value).',';
	
	$T_SETTINGS['Captcha_Enabled_For'] = $enabledfor;
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Captcha_Characters']."' WHERE `setting`='Captcha_Characters'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Captcha_Dots']."' WHERE `setting`='Captcha_Dots'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Captcha_Lines']."' WHERE `setting`='Captcha_Lines'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Captcha_Case_Sensitive']."' WHERE `setting`='Captcha_Case_Sensitive'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Captcha_Enabled_For']."' WHERE `setting`='Captcha_Enabled_For'");
	$db->query();
	return 1009;
}

function rst_disable_captcha()
{
	global $T_SETTINGS;
	$T_SETTINGS['Captcha_Enabled'] = 0;
	
	$db = JFactory::getDBO();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Captcha_Enabled']."' WHERE `setting`='Captcha_Enabled'");
	$db->query();
}

function rst_update_autoclose_settings($croninterval,$emailinterval,$closeinterval)
{
	global $T_SETTINGS;
	
	$emailinterval = intval($emailinterval);
	$closeinterval = intval($closeinterval);
	$croninterval = intval($croninterval);
	
	if ($croninterval < 10) return 29;
	
	$T_SETTINGS['Autoclose_Cron_Interval'] = $croninterval;
	$T_SETTINGS['Autoclose_Email_Interval'] = $emailinterval;
	$T_SETTINGS['Autoclose_Interval'] = $closeinterval;
	
	$db = JFactory::getDBO();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Autoclose_Cron_Interval']."' WHERE `setting`='Autoclose_Cron_Interval'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Autoclose_Email_Interval']."' WHERE `setting`='Autoclose_Email_Interval'");
	$db->query();
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['Autoclose_Interval']."' WHERE `setting`='Autoclose_Interval'");
	$db->query();
	
	return 1009;
}

function rst_parse_date($date)
{
	global $T_SETTINGS;
	
	switch ($T_SETTINGS['Date_Format'])
	{
		case 'd.m':
		$exp = explode('.',$date);
		$parsed_date = $exp[0].'-'.$exp[1].'-'.date('Y');
		break;
		
		case 'm.d':
		$exp = explode('.',$date);
		$parsed_date = $exp[1].'-'.$exp[0].'-'.date('Y');
		break;
		
		case 'd.m.Y':
		$exp = explode('.',$date);
		$parsed_date = $exp[0].'-'.$exp[1].'-'.$exp[2];
		break;
		
		case 'm.d.Y':
		$exp = explode('.',$date);
		$parsed_date = $exp[1].'-'.$exp[0].'-'.$exp[2];
		break;
		
		case 'd/m/Y':
		$exp = explode('/',$date);
		$parsed_date = $exp[0].'-'.$exp[1].'-'.$exp[2];
		break;
		
		case 'm/d/Y':
		$exp = explode('/',$date);
		$parsed_date = $exp[1].'-'.$exp[0].'-'.$exp[2];
		break;
		
		case 'Y-m-d':
		$exp = explode('-',$date);
		$parsed_date = $exp[2].'-'.$exp[1].'-'.$exp[0];
		break;
	}
	return $parsed_date;
}

function rst_full_date($time)
{
	global $day_array_lang, $month_array_lang;
	$day = $day_array_lang[date('w',$time)];
	$nday = date('d',$time);
	$month = $month_array_lang[date('n',$time)];
	$part2 = date('Y H:i:s O', $time);
	return $day.', '.$nday.' '.$month.' '.$part2;
}

function rst_custom_sess()
{
	global $T_SETTINGS;
	return md5($T_SETTINGS['License_Code'].RST_KEY);
}

function rst_replace_placeholder($placeholder,$value,$string)
{
	return str_replace($placeholder,$value,$string);
}

function rst_is_email($email)
{
	// OLD VERSION
    // return preg_match('|^[_a-z0-9._%+-]+(\.[_a-z0-9-]+)*@[a-z0-9.-]+(\.[a-z0-9-]{2,4})+$|i', $email);
	// NEW VERSION
	if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email))
		return false;
		
	$email_array = explode("@", $email);
	$local_array = explode(".", $email_array[0]);
	for ($i = 0; $i < sizeof($local_array); $i++)
		if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
			return false;
			
	if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))
	{
		$domain_array = explode(".", $email_array[1]);
		if (sizeof($domain_array) < 2)
			return false;
			
		for ($i = 0; $i < sizeof($domain_array); $i++)
			if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
				return false;
	}
	return true;
}

function rst_get_extension($filename)
{
	return strtolower(end(explode('.', $filename)));
}

function rst_is_allowed_extension($ext,$ext_array)
{
	if (!is_array($ext_array)) return true;
	if (count($ext_array) == 0) return true;
	if (count($ext_array) == 1 && $ext_array[0] == '') return true;
	if (in_array('*',$ext_array)) return true;
	return in_array($ext,$ext_array);
}

function rst_cut_text($str, $max=30)
{
	$exp = explode(' ',$str);
	$die = $mimi = '';
	
	preg_match_all('/&[a-zA-Z0-9]{1,};/',$str,$matches);
	
	if (count($matches[0]) > 0)
		foreach ($matches[0] as $match)
			$max += strlen($match) - 1;
	
	for ( $i = 0; $i < count($exp); $i++)
	{
		if ($die != 'yes')
		{
			if ( strlen( $mimi ) + strlen( $exp[$i] ) < $max ) $mimi .= $exp[$i].' ';
			else $die = 'yes';
		}
	}
	return substr($mimi,0,-1).(strlen($str) >= strlen($mimi) ? "..." : '');
}

function rst_is_overdue($id)
{
	global $T_SETTINGS;
	$id = intval($id);
	
	$db = JFactory::getDBO();
	
	// CHECK IF THIS TICKET IS 'OVERDUABLE'
	$db->setQuery("SELECT `TicketId`,`CustomerId`,`UserId` FROM `#__rstickets_tickets` WHERE `TicketId`='".$id."' AND `TicketStatus`!='closed' LIMIT 1");
	$ticket = $db->loadAssoc();
	// NOT CLOSED ?
	if (count($ticket) == 0)
		return false;
	$ticketid = $ticket['TicketId'];
	$customerid = $ticket['CustomerId'];
	$userid = $ticket['UserId'];
	// SELECT THE NEWEST MESSAGE
	$db->setQuery("SELECT `TicketTime`,`UserId` FROM `#__rstickets_ticket_message` WHERE `TicketId`='".$ticketid."' ORDER BY `TicketTime` DESC LIMIT 1");
	$ticketmessage = $db->loadAssoc();
	// NO MESSAGES ?
	if (count($ticketmessage) == 0)
		return false;
	// LAST USER THAT WROTE A MESSAGE
	$lastuserid = $ticketmessage['UserId'];
	if ($lastuserid == $customerid)
		return false;
	$tickettime = $ticketmessage['TicketTime'];
	// CHECK IF IT'S OVERDUE
	if ($tickettime > 0 && ($tickettime + $T_SETTINGS['Autoclose_Email_Interval']*86400 <= time()))
		return true;
	else
		return false;
}

function rst_is_notified($id)
{
	global $T_SETTINGS;
	
	if ($T_SETTINGS['Autoclose_Email_Interval'] == 0 && $T_SETTINGS['Autoclose_Interval'] == 0) return false;
	
	$id = intval($id);
	$db = JFactory::getDBO();
	// MYSQL 4 HACK
	$db->setQuery("SELECT `TicketTime` FROM `#__rstickets_ticket_message` WHERE `TicketId`='".$id."' ORDER BY `TicketTime` DESC LIMIT 1");
	$ticketautoclosesent = $db->loadResult();
	if ($ticketautoclosesent === false) $ticketautoclosesent = 0;
	
	$db->setQuery("SELECT `TicketId` FROM `#__rstickets_tickets` WHERE `TicketId`='".$id."' AND `TicketAutocloseSent` >= '".$ticketautoclosesent."' + '".($T_SETTINGS['Autoclose_Email_Interval']*(86400))."' LIMIT 1");
	
	return ($id == $db->loadResult());
}

function rst_notify_customer($id)
{
	global $T_SETTINGS;
	
	$db = JFactory::getDBO();
	
	$id = intval($id);
	if ($id == 0) return;
	
	$db->setQuery("SELECT `TicketId`,`DepartmentId`,`UserId`,`TicketStatus` FROM `#__rstickets_tickets` WHERE `TicketId`='".$id."' LIMIT 1");
	$ticket = $db->loadAssoc();
	
	if ($ticket['UserId'] == 0 && $_SESSION['RST_User']['Group']['CanSeeUnallocatedTickets'] == 0) return;
	if ($ticket['UserId'] > 0 && $ticket['UserId'] != $_SESSION['RST_User']['UserId'] && $_SESSION['RST_User']['Group']['CanSeeOtherTickets'] == 0) return;
	
	if ($ticket['DepartmentId'] > 0)
	{
		$continue = false;
		foreach ($_SESSION['RST_User']['Department'] as $department)
			if ($department['DepartmentId'] == $ticket['DepartmentId']) $continue = true;
		if ($continue == false) return;
	}
	
	$db->setQuery("UPDATE `#__rstickets_tickets` SET `TicketAutocloseSent`='".time()."' WHERE `TicketId`='".$ticket['TicketId']."'");
	$db->query();
	
	rst_send_email(rst_get_customer_email_by_ticketid($ticket['TicketId']),rst_replace_placeholder('{email_interval}',$T_SETTINGS['Autoclose_Email_Interval'],RST_NOTIFICATION_EMAIL_SUBJECT),$id,'autoclose_email');
	return 1025;
}

function rst_is_sort($order,$search)
{
	if (!isset($_SESSION[$search]['order']))
		return false;
		
	if ($_SESSION[$search]['order'] == $order)
		return true;
	else
		return false;
}

function rst_get_plugins()
{
	$db = JFactory::getDBO();
	
	$db->setQuery("SELECT * FROM `#__rstickets_plugins`");
	$rows = $db->loadAssocList();
	$return = array();
	foreach ($rows as $row)
	{
		$row['PluginDescription'] = rst_replace_placeholder('{custom_sess}',rst_custom_sess(),constant($row['PluginDescription']));
		$row['PluginLink'] = rst_replace_placeholder('{custom_sess}',rst_custom_sess(),$row['PluginLink']);
		$return[] = $row;
	}

	return $return;
}




function rst_parse_mysql_dump($file)
{
	$RST_adapter=$GLOBALS['RST_adapter'];
	$message = '';

	$db = JFactory::getDBO();
	
	$file_content = file($file);
	foreach($file_content as $sql_line)
	{
		if( trim($sql_line) != "" )
		{
			$sql_line = str_replace('{PREFIX}',$RST_adapter->getConfig('dbprefix'), $sql_line);
	   		$db->setQuery($sql_line);
			$db->query() or $message .= '<pre>'.$sql_line.$db->getErrorMsg().'</pre><br/>';
	 	}
	}

	if($message == '') return 'ok';
	else return $message;
}

function rst_upload_file( $filename, $userfile_name, &$msg )
{
    $RST_adapter=$GLOBALS['RST_adapter'];
    
    $baseDir = $RST_adapter->processPath( $RST_adapter->getConfig('absolute_path') . '/media' );

    if (file_exists( $baseDir )) {
        if (is_writable( $baseDir )) {
            if (move_uploaded_file( $filename, $baseDir . $userfile_name )) {
            	$RST_adapter->chmod( $baseDir . $userfile_name );
            	return true;/*
                if () {

                } else {
                    $msg = 'Failed to change the permissions of the uploaded file.';
                }*/
            } else {
                $msg = 'Failed to move uploaded file to <code>/media</code> directory.';
            }
        } else {
            $msg = 'Upload failed as <code>/media</code> directory is not writable.';
        }
    } else {
        $msg = 'Upload failed as <code>/media</code> directory does not exist.'.$baseDir;
    }
    return false;
}

function rst_process_task($option, $task, $uploaddir){
    //$type,$value,$dest
    $RST_adapter=$GLOBALS['RST_adapter'];

    $type    	= $task->getAttribute('type');
    $source    	= $task->getAttribute('source');
    $value   	= $task->getText();
    
    //$source 	= eval('return "'.$source.'";');
    //$value	= eval('return "'.$value.'";');
     
	$db = JFactory::getDBO();
	 
    switch ($type){
        case 'mkdir':
            RSRmkdir($RST_adapter->getConfig('absolute_path').$value);
            //echo 'MKDIR OK '.$value;
            return true;
        break;
        case 'query':
        	$value = str_replace('{PREFIX}',$RST_adapter->getConfig('dbprefix'), $value);
			$db->setQuery(html_entity_decode($value));
        	if($db->query())
        	{
                return true;
            }else{
                echo 'QUERY ERROR '.$value."<br/>";
                return false;
            }

        break;
        case 'copy':
            if($value!=''){

                $rfile = @fopen ($uploaddir.$source, "r");
                if (!$rfile) {
                    echo 'FOPEN ERROR '.$uploaddir.$source.". Make sure the file exists.<br/>";
                    return false;
                }else{
                    $filecontents = @fread($rfile, filesize($uploaddir.$source));
                    $filename = $RST_adapter->getConfig('absolute_path').'/'.$value;

                    //check if folder exists, else mkdir it.
                    $path = str_replace('\\','/',$filename);
                    $path = explode('/',$path);
                    unset($path[count($path)-1]);
                    $path = implode('/',$path);
                    if(!is_dir($path)) rst_rmkdir($path);
					@chmod($path,0777);
                    if (!$handle = @fopen($filename, 'w')) {
                        echo 'FWRITE OPEN ERROR '.$filename.". Make sure there are write permissions (777)<br/>";
                        return false;
                        // exit;
                    }

                    // Write $filecontents to our opened file.
                    if (fwrite($handle, $filecontents) === FALSE) {
                        echo 'FWRITE ERROR '.$filename.". Make sure there are write permissions (777)<br/>";
                        return false;
                    }
                    //echo 'COPY OK '.$value;
                    return true;

                    fclose($handle);
                }
            }
        break;
        case 'rename':
        	if($value!=''){
        		$oldfile = $uploaddir.$source;
        		$newfile = $RST_adapter->getConfig('absolute_path').'/'.$value;
        		$rename = @rename($oldfile,$newfile);
        		if(!$rename){
        			 echo 'RENAME ERROR '.$newfile."<br/>";
                     return false;
        		}
        	}
        break;
        case 'eval':
        	eval($value);
        	return true;
        break;
        case 'delete':
            $filename = $RST_adapter->getConfig('absolute_path').$value;
            if(file_exists($filename)){
                if(is_dir($filename)){
                    rmdir($filename);
                }else{
                    unlink($filename);
                }
                //echo 'DELETE OK '.$value;
                return true;
            }else{
                echo 'DELETE ERROR '.$value."<br/>";
                return false;
            }
        break;

    }
}

function rst_rmkdir($path)
{
    $exp=explode("/",$path);
    $way='';
    foreach($exp as $n){
        $way.=$n.'/';
        if(!file_exists($way))
            @mkdir($way);
    }
}

function rst_save_registration()
{
	global $T_SETTINGS;
	if (empty($_POST['License_Code'])) return;
	
	$db = JFactory::getDBO();
	
	$license_code = $_POST['License_Code'];
	$T_SETTINGS['License_Code'] = rst_clean($license_code);
	
	$db->setQuery("UPDATE `#__rstickets_settings` SET `value`='".$T_SETTINGS['License_Code']."' WHERE `setting`='License_Code'");
	$db->query();
	
	global $mainframe;
	$mainframe->redirect('index.php?option=com_rstickets', OK_1009);
}
?>