<?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
*/

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

require_once(dirname(__FILE__).'/../../../components/com_rstickets/config.php');


//create the RST_adapter
$GLOBALS['RST_adapter'] = new RST_adapter();
$RST_adapter = $GLOBALS['RST_adapter'];

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

$user = $RST_adapter->user();

if (intval($user['id']) > 0 && (!isset($_SESSION['RST_User']['UserId']) || (isset($_SESSION['RST_User']['UserId']) && $_SESSION['RST_User']['UserId'] != intval($user['id'])))) rst_login();
if (intval($user['id']) == 0  && isset($_SESSION['RST_User']['UserId'])) rst_logout();

//require classes
require_once(RST_BACKEND_ABS_PATH.'/admin.rstickets.html.php');
require_once(RST_FRONTEND_ABS_PATH.'/rstickets.class.php');

//get task
$task = $RST_adapter->getParam($_REQUEST, 'task');

// MUST HAVE A DEFAULT ACTION & DEFAULT PAGE
if (!isset($_GET['action'])) $_GET['action'] = 'default';
if (!isset($_GET['page'])) $_GET['page'] = 'home';

$_GET['page'] = $task;

// SWITCH BETWEEN ACTIONS.
switch($_GET['action'])
{
	// ADD DEPARTMENT
	case 'add_department':
	if (count($_POST) > 0)
	{
		$t_error = rst_add_department($_POST['DepartmentId'],$_POST['DepartmentName'],$_POST['DepartmentPrefix'],$_POST['TicketAssignmentType'],$_POST['TicketGenerationRule'],$_POST['DepartmentPriority'],$_POST['UserEmailTicket'],$_POST['StaffEmailTicket'],$_POST['FileUpload'],$_POST['FileUploadExtensions'],$_POST['NotifyNewTicketEmails'],$_POST['NotifyAssign']);
		if ($t_error > 0)
		{
			$_POST['DepartmentName'] = rst_clean($_POST['DepartmentName']);
			$_POST['DepartmentPrefix'] = rst_clean($_POST['DepartmentPrefix']);
			$_POST['TicketAssignmentType'] = rst_clean($_POST['TicketAssignmentType']);
			$_POST['TicketGenerationRule'] = rst_clean($_POST['TicketGenerationRule']);
			$_POST['UserEmailTicket'] = rst_clean($_POST['UserEmailTicket']);
			$_POST['StaffEmailTicket'] = rst_clean($_POST['StaffEmailTicket']);
			$_POST['FileUpload'] = rst_clean($_POST['FileUpload']);
			$_POST['FileUploadExtensions'] = rst_clean($_POST['FileUploadExtensions']);
			$_POST['NotifyNewTicketEmails'] = rst_clean($_POST['NotifyNewTicketEmails']);
		}
		else
		{
			if ($_POST['DepartmentId'] > 0)
				rst_admin_redirect('?option=com_rstickets&task=departments&edit_department=1');
			else
				rst_admin_redirect('?option=com_rstickets&task=departments&add_department=1');
		}
	}
	break;
	
	// DELETE DEPARTMENT
	case 'delete_department':
	if (isset($_GET['id']))
		$t_error = rst_delete_department($_GET['id']);
	break;
	
	// ORDER DEPARTMENT
	case 'order_department':
	if (isset($_GET['id']) && isset($_GET['direction']))
		rst_order_department($_GET['id'],$_GET['direction']);
	break;
	
	// DELETE CUSTOM FIELD
	case 'delete_custom_field':
	if (isset($_GET['cid']))
		$t_error = rst_delete_custom_field($_GET['cid']);
	break;
	
	// ADD GROUP
	case 'add_group':
	if (count($_POST) > 0)
	{
		$t_error = rst_add_group((isset($_POST['GroupId']) ? $_POST['GroupId'] : ''),(isset($_POST['GroupName']) ? $_POST['GroupName'] : ''),(isset($_POST['CanAddTicket']) ? $_POST['CanAddTicket'] : ''),(isset($_POST['CanAddTicketUsers']) ? $_POST['CanAddTicketUsers'] : ''),(isset($_POST['CanAddTicketStaff']) ? $_POST['CanAddTicketStaff'] : ''),(isset($_POST['CanUpdateTicket']) ? $_POST['CanUpdateTicket'] : ''),(isset($_POST['CanDeleteTicket']) ? $_POST['CanDeleteTicket'] : ''),(isset($_POST['CanAnswerTicket']) ? $_POST['CanAnswerTicket'] : ''),(isset($_POST['CanDeleteTicketReplies']) ? $_POST['CanDeleteTicketReplies'] : ''),(isset($_POST['CanUpdateTicketReplies']) ? $_POST['CanUpdateTicketReplies'] : ''),(isset($_POST['CanAssignTickets']) ? $_POST['CanAssignTickets'] : ''),(isset($_POST['CanChangeTicketStatus']) ? $_POST['CanChangeTicketStatus'] : ''),(isset($_POST['CanSeeUnallocatedTickets']) ? $_POST['CanSeeUnallocatedTickets'] : ''),(isset($_POST['CanSeeOtherTickets']) ? $_POST['CanSeeOtherTickets'] : ''),(isset($_POST['CanMoveTicket']) ? $_POST['CanMoveTicket'] : ''));
		
		if ($t_error > 0)
			$_POST['GroupName'] = rst_clean($_POST['GroupName']);
		else
		{
			if ($_POST['GroupId'] > 0)
				rst_admin_redirect('?option=com_rstickets&task=groups&edit_group=1');
			else
				rst_admin_redirect('?option=com_rstickets&task=groups&add_group=1');
		}
	}
	break;
	
	// DELETE GROUP
	case 'delete_group':
	if (isset($_GET['id']))
		$t_error = rst_delete_group($_GET['id']);
	break;
	
	// ADD STAFF
	case 'add_staff':
	if (count($_POST) > 0)
	{
		$t_error = rst_add_staff(isset($_POST['GroupId']) ? $_POST['GroupId'] : 0,isset($_POST['UserId']) ? $_POST['UserId'] : 0,isset($_POST['DepartmentId']) ? $_POST['DepartmentId'] : '');
	if ($t_error == 1006)
		rst_admin_redirect('?option=com_rstickets&task=staff&add_staff=1');
	elseif ($t_error == 1007)
		rst_admin_redirect('?option=com_rstickets&task=staff&edit_staff=1');
	}
	break;
	
	// DELETE STAFF
	case 'delete_staff':
	if (isset($_GET['id']))
		$t_error = rst_delete_staff($_GET['id']);
	break;
	
	// UPDATE EMAIL SETTINGS
	case 'update_email_settings':
	if (count($_POST) > 0)
		$t_error = rst_update_email_settings(isset($_POST['Email_Address']) ? $_POST['Email_Address'] : '',isset($_POST['Email_Server']) ? $_POST['Email_Server'] : '',isset($_POST['Email_Server_Protocol']) ? $_POST['Email_Server_Protocol'] : '',isset($_POST['Email_Server_Security']) ? $_POST['Email_Server_Security'] : '', isset($_POST['Email_Server_Port']) ? $_POST['Email_Server_Port'] : '',isset($_POST['Email_Address_Account']) ? $_POST['Email_Address_Account'] : '',isset($_POST['Email_Address_Password']) ? $_POST['Email_Address_Password'] : '',isset($_POST['Email_Address_Fullname']) ? $_POST['Email_Address_Fullname'] : '',isset($_POST['Email_Cron_Type']) ? $_POST['Email_Cron_Type'] : 'include',isset($_POST['Email_Cron_Interval']) ? $_POST['Email_Cron_Interval'] : '1',isset($_POST['Email_Accept_New_Tickets']) ? $_POST['Email_Accept_New_Tickets'] : 'no',isset($_POST['Email_Default_Department']) ? $_POST['Email_Default_Department'] : '0');
	break;
	
	// TEST EMAIL SETTINGS
	case 'test_email_settings':
	echo 'Testing your email settings ...';
	if (function_exists('cron_open_connection'))
		$mbox = cron_open_connection();
	else
		$mbox = @imap_open("{".$T_SETTINGS['Email_Server'].":".$T_SETTINGS['Email_Server_Port'].$T_SETTINGS['Email_Server_Protocol'].$T_SETTINGS['Email_Server_Security']."/novalidate-cert}INBOX", $T_SETTINGS['Email_Address_Account'], $T_SETTINGS['Email_Address_Password']);
	$imap_errors = imap_errors();
	if ($mbox)
	{
		echo '<strong style="color: #264D00">SUCCESS!</strong> Connection was successful !';
		imap_close($mbox);
	}
	else
	{
		echo '<strong style="color: #990000">ERROR:</strong> Could not connect !';
		if (count($imap_errors) > 0)
			foreach ($imap_errors as $imap_error)
				echo '<p>'.$imap_error.'</p>';
	}
	break;
	
	// UPDATE LISTING SETTINGS
	case 'update_listing_settings':
	if (count($_POST) > 0)
		$t_error = rst_update_listing_settings($_POST['Backend_TicketTime'],$_POST['Backend_TicketCode'],$_POST['Backend_TicketSubject'],$_POST['Backend_StaffFullname'],$_POST['Backend_CustomerFullname'],$_POST['Backend_TicketPriority'],$_POST['Backend_TicketStatus'],$_POST['Frontend_TicketTime'],$_POST['Frontend_TicketCode'],$_POST['Frontend_TicketSubject'],$_POST['Frontend_StaffFullname'],$_POST['Frontend_CustomerFullname'],$_POST['Frontend_TicketPriority'],$_POST['Frontend_TicketStatus']);
	break;
	
	// UPDATE AUTOCLOSE SETTINGS
	case 'update_autoclose_settings':
	if (count($_POST) > 0)
		$t_error = rst_update_autoclose_settings($_POST['Autoclose_Cron_Interval'],$_POST['Autoclose_Email_Interval'],$_POST['Autoclose_Interval']);
	break;
	
	// UPDATE GENERAL SETTINGS
	case 'update_general_settings':
	if (count($_POST) > 0)
		$t_error = rst_update_general_settings($_POST['Date_Format'],$_POST['License_Code'],$_POST['RStickets_Link'],$_POST['RStickets_Show_Menu'],isset($_POST['Date_Timezone']) ? $_POST['Date_Timezone'] : '',$_POST['RStickets_Add_Tickets'],$_POST['RStickets_MySQL_UTF8'],$_POST['RStickets_Custom_User_Link'],$_POST['Staff_Can_Add_Tickets']);
	break;
	
	// UPDATE CAPTCHA SETTINGS
	case 'update_captcha_settings':
	if (count($_POST) > 0)
		$t_error = rst_update_captcha_settings($_POST['Captcha_Enabled'],$_POST['Captcha_Characters'],$_POST['Captcha_Dots'],$_POST['Captcha_Lines'],$_POST['Captcha_Case_Sensitive'],isset($_POST['Captcha_Enabled_For']) ? $_POST['Captcha_Enabled_For'] : array());
	break;
	
	// UPDATE PLUGIN SETTINGS
	case 'install_plugin':
	print_r($_FILES);
	break;
	
	// SEARCH USERS
	case 'search_users':
	if (isset($_GET['q']))
		rst_search_users($_GET['q'],0,1,0);
	exit();
	break;
	
	// UNINSTALL A PLUGIN
	case 'plugins.uninstall':
		if (isset($_GET['pluginId']))
			pluginsUninstall($_GET['pluginId']);
	break;
}

	if (isset($t_error) && $t_error > 0 && $t_error < 1000)
		echo '<p class="rst_message rst_error">'.$errors_array[$t_error].'</p>';

	elseif (isset($t_error) && $t_error >= 1000)
		echo '<p class="rst_message rst_success">'.$errors_array[$t_error].'</p>';

	elseif (isset($_GET['add_department'])) // NEW DEPARTMENT ADDED MESSAGE
		echo '<p class="rst_message rst_success">'.$errors_array[1000].'</p>';
		
	elseif (isset($_GET['edit_department'])) // DEPARTMENT MODIFIED MESSAGE
		echo '<p class="rst_message rst_success">'.$errors_array[1001].'</p>';
	
	elseif (isset($_GET['add_group'])) // NEW GROUP ADDED MESSAGE
		echo '<p class="rst_message rst_success">'.$errors_array[1003].'</p>';
		
	elseif (isset($_GET['edit_group'])) // GROUP MODIFIED MESSAGE
		echo '<p class="rst_message rst_success">'.$errors_array[1004].'</p>';	

	elseif (isset($_GET['add_staff'])) // NEW STAFF ADDED MESSAGE
		echo '<p class="rst_message rst_success">'.$errors_array[1006].'</p>';
		
	elseif (isset($_GET['edit_staff'])) // STAFF MODIFIED MESSAGE
		echo '<p class="rst_message rst_success">'.$errors_array[1007].'</p>';	
		
	if (!is_writable(RST_FRONTEND_ABS_PATH.'/files/'))
		echo '<p class="rst_message rst_error">'.$errors_array[34].'</p>';

switch ($_GET['page'])
{
	//DEPARTMENTS
	case 'departments':
		include(RST_BACKEND_ABS_PATH.'/page/admin/departments.php');
		redirectForm($option);
	break;
	case 'add_department':
		include(RST_BACKEND_ABS_PATH.'/page/admin/add_department.php');
		redirectForm($option);
	break;
	//GROUPS
	case 'groups':
		include(RST_BACKEND_ABS_PATH.'/page/admin/groups.php');
		redirectForm($option);
	break;
	case 'add_group':
		include(RST_BACKEND_ABS_PATH.'/page/admin/add_group.php');
		redirectForm($option);
	break;
	//STAFF
	case 'staff':
		include(RST_BACKEND_ABS_PATH.'/page/admin/staff.php');
		redirectForm($option);
	break;
	case 'add_staff':
		include(RST_BACKEND_ABS_PATH.'/page/admin/add_staff.php');
		redirectForm($option);
	break;
	//SETTINGS
	case 'settings':
		include(RST_BACKEND_ABS_PATH.'/page/admin/settings.php');
		redirectForm($option);
	break;
	
	// CONFIGURATION
	case 'configuration.save':
		configurationSave($option);
	break;

	case 'configuration.edit':
		configurationEdit($option);
	break;
	
	// UPDATE
	case 'updates.manage':
		updatesManage($option);
	break;

	case 'update.upload.process':
		updateUploadProcess($option);
	break;
	
	// PLUGINS
	case 'plugins.upload.process':
		pluginsUploadProcess($option);
	break;
	
	// CONTROL PANEL
    case 'saveRegistration':
        rst_save_registration();
    break;

	default:
		rstickets_HTML::controlPanel();
	break;
}

//////////////////////////////////////// CONFIGURATION ////////////////////////////////////////
function redirectForm($option)
{
	$RST_adapter = $GLOBALS['RST_adapter'];

    //$RST_adapter=new RST_adapter();
    $RST_adapter->addHeadTag(RST_BACKEND_REL_PATH.'/style.css','css');
 	$RST_adapter->addHeadTag( RST_FRONTEND_REL_PATH.'/js/script.js','js' );
	?>
		<form action="<?php echo RST_BACKEND_SCRIPT_PATH;?>?option=com_rstickets" id="adminForm" name="adminForm">
			<input type="hidden" name="task"/>
			<input type="hidden" name="option" value="com_rstickets"/>
			<input type="hidden" name="hidemainmenu" value="0"/>
		</form>
	<?php
}

//////////////////////////////////////// UPDATES ////////////////////////////////////////

function pluginsUploadProcess($option)
{
	updateUploadProcess($option);
}

function updateUploadProcess($option) {
	$RST_adapter = $GLOBALS['RST_adapter'];

    // Check that the zlib is available
    if(!extension_loaded('zlib')) {
        echo "The installer can't continue before zlib is installed";
        exit() ;
    }

    $userfile = $RST_adapter->getParam( $_FILES, 'userfile' );
    $filetype = $RST_adapter->getParam( $_POST, 'filetype');

    if (!$userfile) {
        echo "No file selected";
        exit();
    }

    $userfile_name = $userfile['name'];

    $msg = @constant('RST_BACKEND_UPDATECHECK_STATUS_'.strtoupper($filetype));

    $resultdir = RST_upload_file( $userfile['tmp_name'], $userfile['name'], $msg );

    $has_errors = 0;
    //check if file is a valid plugin
    if ($resultdir !== false) {
        $baseDir = $RST_adapter->getConfig('absolute_path') . '/media/' ;

        require_once( RST_JOOMLA_XML_PATH );
        $installer = new RSinstaller();
        $installer->archivename = $userfile['name'];
        if($installer->upload($userfile['name']))
        {
        	if($installer->readInstall())
        	{
        	 	$RSinstall = $installer->xmldoc->documentElement;
        	 	if($installer->installType!=$filetype)
        	 	{
                    $msg = constant('RST_BACKEND_UPDATECHECK_'.strtoupper($filetype));
                }
                else
                {

                    $tasks_node = &$RSinstall->getElementsByPath('tasks', 1);
                    if (!is_null($tasks_node)) {
                        $tasks = $tasks_node->childNodes;
                        $has_errors = false;
                        foreach($tasks as $task){
                            if(rst_process_task($option, $task, $installer->installDir)===FALSE)$has_errors = true;
                        }
                        //if($has_errors) die();
                    }

                    //clean up
                    @unlink($baseDir.$userfile['name']);
                    $installer->cleanup($userfile['name'], $installer->installDir);
                	$msg = RST_BACKEND_UPDATECHECK_OK;
                }

        	}else{
                $msg = RST_BACKEND_UPDATECHECK_NOINSTALL;
			}
        }else{
            $msg = RST_BACKEND_UPDATECHECK_BADFILE;
            @unlink($baseDir.$userfile['name']);
        }
    }

    
    if(!$has_errors)
    switch($filetype){
        case 'rstbackup':
            $RST_adapter->redirect(RST_BACKEND_SCRIPT_PATH.'?option='.$option.'&task=backup.restore',$msg);
        break;
        case 'rstupdate':
            $RST_adapter->redirect(RST_BACKEND_SCRIPT_PATH.'?option='.$option.'&task=updates.manage',$msg);
        break;
        case 'rstplugin':
            $RST_adapter->redirect(RST_BACKEND_SCRIPT_PATH.'?option='.$option.'&task=settings',$msg);
        break;

    }
}

function updatesManage($option){
	rstickets_HTML::updatesManage($option);
}

function pluginsUninstall($pluginId)
{
	$RST_adapter = $GLOBALS['RST_adapter'];
	$pluginId = rst_clean($pluginId);
	
	$db = JFactory::getDBO();
	$db->setQuery("SELECT `PluginId` FROM `#__rstickets_plugins` WHERE `PluginId`='".$pluginId."' LIMIT 1");
	$db->query();
	
	if ($db->getNumRows() == 1)
	{
		$db->setQuery("UPDATE `#__rstickets_plugins` SET `PluginInstalled`='0' WHERE `PluginId`='".$pluginId."' LIMIT 1");
		$db->query();
		@unlink(RST_FRONTEND_ABS_PATH.'/plugins/'.$pluginId.'.php');
		$RST_adapter->redirect(RST_BACKEND_SCRIPT_PATH.'?option=com_rstickets&task=settings',RST_BACKEND_UPDATECHECK_OK);
	}
}
?>