<?php

/**
 * @todo Write code for password modification form (actually, don't do anything)
 * @todo When textVerification::verifUnixPath will be modified (adding an optional param for directory existence verification),
 * modify code below to correspond to this modification (errors codes are ready in the form template)
 * @todo Add code to really add a new vhost in database (actually, only the $_POST vars check is done)
 * Need vhost class modifications (for optionnals customized php values)
 */
 
require_once('../system/configuration.php');
require(PATH_SYSTEM.'core.php');
try 
{
	if ( !isset($_GET['frm_id']) ) throw new myException('The ID of action is not set');
	$ajax_id = $_GET['frm_id'];
	if ( !textVerification::verifAjaxID($ajax_id)) throw new myException('The syntax of ID is not correct.');
	switch ($ajax_id) 
	{
		// Modify Data account
		case 'form_myaccount':
			$_SESSION['user']->userCheckAccess(1);
			$ret_code = array();
			$ret_code[]= 1;
			// Verify the inputs
			if ( !isset($_POST['req_first_name']) ) $ret_code[] = 'err_req_first_name_missing';
			if ( !textVerification::verifFirstName($_POST['req_first_name']) ) 	$ret_code[] = 'err_req_first_name';
			
			if ( !isset($_POST['req_last_name']) ) $ret_code[] = 'err_req_last_name_missing';
			if ( !textVerification::verifLastName($_POST['req_last_name']) ) 	$ret_code[] = 'err_req_last_name';
			
			if ( isset($_POST['company']) ) {
				if ( !textVerification::verifCompany($_POST['company']) ) 	$ret_code[] = 'err_company';
			} else $_POST['company']='';
			
			if ( !isset($_POST['req_address']) ) $ret_code[] = 'err_req_address_missing';
			if ( !textVerification::verifAddress($_POST['req_address']) ) 	$ret_code[] = 'err_req_address';
			
			if ( !isset($_POST['req_city']) ) $ret_code[] = 'err_req_city_missing';
			if ( !textVerification::verifLastName($_POST['req_city']) ) 	$ret_code[] = 'err_req_city';
			
			if ( !isset($_POST['req_zipcode']) ) $ret_code[] = 'err_req_zipcode_missing';
			if ( !textVerification::verifZipcode($_POST['req_zipcode']) ) 	$ret_code[] = 'err_req_zipcode';
			
			if ( !isset($_POST['req_email']) ) $ret_code[] = 'err_req_email_missing';
			if ( !textVerification::verifEmail($_POST['req_email']) ) 	$ret_code[] = 'err_req_email';
			
			if ( !isset($_POST['req_pseudo']) ) $ret_code[] = 'err_req_pseudo_missing';
			if ( !textVerification::verifPseudo($_POST['req_pseudo']) ) 	$ret_code[] = 'err_req_pseudo';
			
			// Verification of the syntax of countrie and lang
			if ( !isset($_POST['countrie']) or !textVerification::verifCountrieID($_POST['countrie']) ) 
				throw new myException('Countrie ID is not an int');
			if ( !isset($_POST['lang']) or !textVerification::verifLangID($_POST['lang']) )
				throw new myException('Lang ID is not an int');

			// Verification of the syntaxe of template and existence
			if ( !isset($_POST['template']) or !textVerification::verifTemplate($_POST['template']) ) 
				throw new myException('Syntax of the template is incorrect');
			if ( !$_SESSION['template']->checkTemplateExistence($_POST['template']) )
				throw new myException('User want to use an inexistant template');

			// Verification of the existence of the countrie and lang
			if ( !$_SESSION['user']->checkCountrieExistence($_POST['countrie']) ) throw new myException('The ID of countrie is not found in db');
			if ( !$_SESSION['user']->checkLangExistence($_POST['lang']) ) throw new myException('The ID of lang it not found or not lang');

			// Verif the username
			if ( !$_SESSION['user']->checkUsernameExistence($_POST['req_pseudo']) 
				and $_SESSION['user']->information_user->user != $_POST['req_pseudo'] )
				$ret_code[] = 'pseudo_used';

			if ( count($ret_code) == 1) {
				//Verification of the actions of lang template
				$lang_info = $_SESSION['user']->getCountrieInformations($_POST['lang']);
				if ( (!TEMPLATE_USE_OTHERS) and ( $_SESSION['template']->userGetTemplate() != $_POST['template']) ) $ret_code[] = 'tpl_forbidden';
				if ( (!LANG_USE_OTHERS) and ( $lang_info->flag != $_SESSION['user']->information_user->lang) ) $ret_code[] = 'lang_forbidden';

				$_SESSION['user']->userEdit(
					$_POST['req_first_name'], 
					$_POST['req_last_name'], 
					$_POST['company'], 
					$_POST['req_address'], 
					$_POST['req_city'], 
					$_POST['req_zipcode'], 
					$_POST['req_email'], 
					$_POST['req_pseudo'], 
					$_POST['countrie'], 
					$_POST['lang'], 
					$_POST['template']
				);
				$ret_code[] = 'account_is_ok';
			} else $ret_code[0]=0;
			echo json_encode($ret_code);
		break;
		
		
		case 'form_password':
			$ret_code = array();
			$ret_code[]= 1;
			
			$ret_code[]='pwd_is_ok';
			echo json_encode($ret_code);
		break;
		
		case 'form_new_ticket':
			$_SESSION['user']->userCheckAccess(LEVEL_REGISTER);
			$ret_code = array();
			$ret_code[]= 1;
			// Verify the inputs
			if ( !isset($_POST['hosting_id']) or !textVerification::verifHostingID($_POST['hosting_id']) ) 	$ret_code[] = 'err_hosting_id';
			if ( !isset($_POST['req_subject']) ) $ret_code[] = 'err_req_subject_missing';
			if ( !textVerification::verifSubject($_POST['req_subject']) ) 	$ret_code[] = 'err_req_subject';
			if ( !isset($_POST['req_message']) ) $ret_code[] = 'err_req_message_missing';
			if ( !textVerification::verifMessage($_POST['req_message']) ) 	$ret_code[] = 'err_req_message';
			// If no errors encountered, try to add the ticket in database
			if ( count($ret_code) == 1) {
				$support = new support();
				if ($support->userCreateTicket($_POST['req_subject'], $_POST['req_message'], ($_POST['hosting_id']==0?NULL:$_POST['hosting_id']))==false) {
					throw new myException('Error while creating a new ticket in database.');
				} else {
					$ret_code[]='all_is_ok';
				}
			} else $ret_code[0]=0;
			echo json_encode($ret_code);
		break;
		
		case 'form_user_reply':
			$_SESSION['user']->userCheckAccess(LEVEL_REGISTER);
			$ret_code = array();
			$ret_code[]= 1;
			// Verify the inputs
			if ( !isset($_POST['req_message']) ) $ret_code[] = 'err_req_message_missing';
			if ( !textVerification::verifMessage($_POST['req_message']) ) 	$ret_code[] = 'err_req_message';
			if ( !isset($_POST['reply_ticket_id']) or !textVerification::verifID($_POST['reply_ticket_id']) ) {
				$ret_code[] = 'err_ticket_id';
				throw new myException('Error in user ticket response : ticket id was not valid !');
			}
			// If no errors encountered, try to add the message in database
			if ( count($ret_code) == 1 ) {
				$support = new support();
				if ( !$support->userAddResponse($_POST['reply_ticket_id'], $_POST['req_message'])) {
					throw new myException('Error while posting a new ticket reply in database.');
				} else {
					$ret_code[] = 'reply_is_ok';
				}
			} else $ret_code[0] = 0;
			echo json_encode($ret_code);
		break;
		
		case 'form_user_close':
			$_SESSION['user']->userCheckAccess(LEVEL_REGISTER);
			$ret_code = array();
			$ret_code[]= 1;
			// Verify the inputs
			if ( !isset($_POST['close_ticket_id']) or !textVerification::verifID($_POST['close_ticket_id']) ) {
				$ret_code[] = 'err_ticket_id';
				throw new myException('Error in user close ticket form : ticket id was not valid !');
			}
			// If no errors encountered, try to close the message in database
			if ( count($ret_code) == 1 ) {
				$support = new support();
				if ( !$support->userCloseTicket($_POST['close_ticket_id'])) {
					throw new myException('Error while closing a ticket (from user) in database.');
				} else {
					$ret_code[] = 'close_ok';
				}
			} else $ret_code[0] = 0;
			echo json_encode($ret_code);
		break;
		
		case 'form_admin_reply':
			$_SESSION['user']->userCheckAccess(LEVEL_SUPPORT);
			$ret_code = array();
			$ret_code[]= 1;
			// Verify the inputs
			if ( !isset($_POST['req_message']) ) $ret_code[] = 'err_req_message_missing';
			if ( !textVerification::verifMessage($_POST['req_message']) ) 	$ret_code[] = 'err_req_message';
			if ( !isset($_POST['reply_ticket_id']) or !textVerification::verifID($_POST['reply_ticket_id']) ) {
				$ret_code[] = 'err_ticket_id';
				throw new myException('Error in support response : ticket id was not valid !');
			}
			// If no errors encountered, try to add the message in database
			if ( count($ret_code) == 1 ) {
				$support = new support();
				if ( !$support->addResponse($_POST['reply_ticket_id'], $_POST['req_message'], false)) {
					throw new myException('Error while posting a new ticket reply in database.');
				} else {
					$ret_code[] = 'reply_is_ok';
				}
			} else $ret_code[0] = 0;
			echo json_encode($ret_code);
		break;

		case 'form_admin_close':
			$_SESSION['user']->userCheckAccess(LEVEL_SUPPORT);
			$ret_code = array();
			$ret_code[]= 1;
			// Verify the inputs
			if ( !isset($_POST['close_ticket_id']) or !textVerification::verifID($_POST['close_ticket_id']) ) {
				$ret_code[] = 'err_ticket_id';
				throw new myException('Error in admin close ticket form : ticket id was not valid !');
			}
			// If no errors encountered, try to close the message in database
			if ( count($ret_code) == 1 ) {
				$support = new support();
				if ( !$support->closeTicket($_POST['close_ticket_id'], false)) {
					throw new myException('Error while closing a ticket (from support) in database.');
				} else {
					$ret_code[] = 'close_ok';
				}
			} else $ret_code[0] = 0;
			echo json_encode($ret_code);
		break;
		
		case 'tbl_history': // Pagination for page 'History'
			$_SESSION['user']->userCheckAccess(LEVEL_REGISTER);
			// Verify the inputs
			if ( !isset($_GET['p']) || !textVerification::verifID($_GET['p']) || $_GET['p']<1) {
				throw new myException('Error in history page : number of page to show not valid !');
			}
			// Create the history class instance
			$history = new history();
			// Check page number
			$pages_count = $history->userCountTotalPages();
			if ( $_GET['p'] > $pages_count ) {
				throw new myException('Error in history page : number of page to show too big !');
			}
			// Get Page datas
			$start=($_GET['p']-1) * RECORD_BY_PAGE;
			$history_list = $history->userListHistory($start, RECORD_BY_PAGE);
			// Create a pagination class instance
			$paging = new pagination();
			foreach( $history_list as $key => $value )
			{
				$line_index = $paging->addLine();
				$paging->addCell( $value->date );
				$paging->addCell( $value->action );
				$paging->addCell( $value->hosting );
				$paging->addCell( $value->ip );
			}
			// Return result to js engine
			echo $paging->getResult();
		break;
		
		case 'tbl_myhostings': // Pagination for page 'MyHostings'
			$_SESSION['user']->userCheckAccess(LEVEL_REGISTER);
			// Verify the inputs
			if ( !isset($_GET['p']) || !textVerification::verifID($_GET['p']) || $_GET['p']<1) {
				throw new myException('Error in myhostings page : number of page to show not valid !');
			}
			// Check page number
			$pages_count = $_SESSION['hosting']->userCountTotalPages();
			if ( $_GET['p'] > $pages_count ) {
				throw new myException('Error in myhostings page : number of page to show too big !');
			}
			// Get Page datas
			$start=($_GET['p']-1) * RECORD_BY_PAGE;
			$hostings = $_SESSION['hosting']->userListHostings( $start, RECORD_BY_PAGE);
			
			$lang = new lang();
			$paging = new pagination();
			foreach ( $hostings as $key => $value )
			{
				$value->hosting_begin = date($lang->userGetDateFormat(), $value->start_date).' '.date($lang->userGetTimeFormat(), $value->start_date);
				$value->hosting_end = date($lang->userGetDateFormat(), $value->end_date).' '.date($lang->userGetTimeFormat(), $value->end_date);
				$value->full_name = $value->base_name . $lang->getWordFromLangFile('hosting_address');
				$value->statusText = ucfirst($lang->getWordFromLangFile( ($value->hosting_active == 'true' ? 'functional':'suspended')));
				
				$line_index = $paging->addLine();
				$paging->addCell( html::makeHtmlForMyHostings( 0, $value) );
				$paging->addCell( $value->offer_name );
				$paging->addCell( $value->hosting_begin );
				$paging->addCell( $value->hosting_end );
				$paging->addCell( html::makeHtmlForMyHostings( 4, $value) );
			}
			echo $paging->getResult();
		break;
		
		case 'tbl_user_tickets': // Pagination for page 'Support'
			$_SESSION['user']->userCheckAccess(LEVEL_REGISTER);
			// Verify the inputs
			if ( !isset($_GET['p']) || !textVerification::verifID($_GET['p']) || $_GET['p']<1) {
				throw new myException('Error in support page : number of page to show not valid !');
			}
			// Create the support class instance
			$support = new support();
			// Check page number
			$pages_count = $support->userCountTotalPages();
			if ( $_GET['p'] > $pages_count ) {
				throw new myException('Error in support page : number of page to show too big !');
			}
			// Get Page datas
			$start=($_GET['p']-1) * RECORD_BY_PAGE;
			$tickets_list = $support->userGetTickets($start, RECORD_BY_PAGE);
			// Create a pagination class instance
			$paging = new pagination();
			$lang = new lang();
			foreach( $tickets_list as $key => $value )
			{
				$value->label_text = date($lang->userGetDateFormat().' '.$lang->userGetTimeFormat(), $value->open_date);
				$paging->addLine();
				$paging->addCell( html::makeHtmlForSupport( 0, $value ) );
				$paging->addCell( $value->subject );
				$keyword = '';
				switch ( $value->status )
				{
					case 'asked':
						$keyword = 'ticket_status_asked';
						break;
					case 'replied':
						$keyword = 'ticket_status_replied';
						break;
					case 'closed_by_user':
						$keyword = 'ticket_status_closed_user';
						break;
					case 'closed_by_support':
						$keyword = 'ticket_status_closed_support';
						break;
					case 'auto_closed':
						$keyword = 'ticket_status_auto_closed';
						break;
				}
				$paging->addCell( $lang->getWordFromLangFile( $keyword ) );
			}
			// Return result to js engine
			echo $paging->getResult();
		break;
		
		case 'tbl_admin_wtickets': // Pagination for page 'Admin/Support' (table "Waiting tickets")
		case 'tbl_admin_rtickets': // Pagination for page 'Admin/Support' (table "Replied tickets")
			$_SESSION['user']->userCheckAccess(LEVEL_SUPPORT);
			// Verify the inputs
			if ( !isset($_GET['p']) || !textVerification::verifID($_GET['p']) || $_GET['p']<1) {
				throw new myException('Error in admin/support page : number of page to show not valid !');
			}
			// Create the support class instance
			$support = new support();
			// Check page number
			if ( $ajax_id == 'tbl_admin_wtickets' ) {
				$pages_count = $support->countWaitingTicketsTotalPages();
			} else {
				$pages_count = $support->countRepliedTicketsTotalPages();
			}
			if ( $_GET['p'] > $pages_count ) {
				throw new myException('Error in admin/support page : number of page to show too big !');
			}
			// Get Page datas
			$start=($_GET['p']-1) * RECORD_BY_PAGE;
			if ( $ajax_id == 'tbl_admin_wtickets' ) {
				$tickets_list = $support->getWaitingTickets($start, RECORD_BY_PAGE);
			} else {
				$tickets_list = $support->getRepliedTickets($start, RECORD_BY_PAGE);
			}
			// Create a pagination class instance
			$paging = new pagination();
			$lang = new lang();
			foreach( $tickets_list as $key => $value )
			{
				$value->open_date = date($lang->userGetDateFormat().' '.$lang->userGetTimeFormat(), $value->open_date);
				$value->last_msg_date = date($lang->userGetDateFormat().' '.$lang->userGetTimeFormat(), $value->last_msg_date);
				$paging->addLine();
				$paging->addCell( html::makeHtmlForAdminSupport( 0, $value ) );
				$paging->addCell( $value->last_msg_date );
				$paging->addCell( $value->subject );
			}
			// Return result to js engine
			echo $paging->getResult();
		break;
		
		case 'tbl_user_ticket_details': // Pagination for page 'Support - Ticket details'
			$_SESSION['user']->userCheckAccess(LEVEL_REGISTER);
			// Verify the inputs
			if ( !isset($_GET['p']) || !textVerification::verifID($_GET['p']) || $_GET['p']<1) {
				throw new myException('Error in ticket details page : number of page to show not valid !');
			}
			if ( !isset($_GET['value']) || !textVerification::verifID($_GET['value']) ) {
				throw new myException('Error in ticket details page : id of ticket not valid !');
			}
			// Create the support class instance
			$support = new support();
			// Check page number
			$pages_count = $support->countTicketTotalPages($_GET['value']);
			if ( $_GET['p'] > $pages_count ) {
				throw new myException('Error in ticket details page : number of page to show too big !');
			}
			// Get Page datas
			$start=($_GET['p']-1) * RECORD_BY_PAGE;
			$details = $support->getTicketDetails( $_GET['value'], $start, RECORD_BY_PAGE );
			// Remove Tickets informations
			unset($details[0]);
			if ( is_null($details) ) {
				throw new myException('Error in ticket details page : ticket id not allowed !');
			}
			// Create a pagination class instance
			$paging = new pagination();
			$lang = new lang();
			foreach( $details as $key => $value )
			{
				$paging->addLine();
				$value->msg_author = ( $value->is_reply=='true' ? $lang->getWordFromLangFile( 'ticket_msg_author_us' ) : $lang->getWordFromLangFile( 'ticket_msg_author_you' ) );
				$value->msg_date = date($lang->userGetDateFormat().' '.$lang->userGetTimeFormat(), $value->posted);
				$value->message=nl2br($value->message);
				$paging->addCell( html::makeHtmlForTicketDetails( 0, $value ) );
				$paging->addCell( $value->message );
			}
			// Return result to js engine
			echo $paging->getResult();
		break;
		
		case 'tbl_admin_ticket_details': // Pagination for page 'Admin/Support - Ticket details'
			$_SESSION['user']->userCheckAccess(LEVEL_SUPPORT);
			// Verify the inputs
			if ( !isset($_GET['p']) || !textVerification::verifID($_GET['p']) || $_GET['p']<1) {
				throw new myException('Error in admin ticket details page : number of page to show not valid !');
			}
			if ( !isset($_GET['value']) || !textVerification::verifID($_GET['value']) ) {
				throw new myException('Error in admin ticket details page : id of ticket not valid !');
			}
			// Create the support class instance
			$support = new support();
			// Check page number
			$pages_count = $support->countTicketTotalPages($_GET['value']);
			if ( $_GET['p'] > $pages_count ) {
				throw new myException('Error in admin ticket details page : number of page to show too big !');
			}
			// Get Page datas
			$start=($_GET['p']-1) * RECORD_BY_PAGE;
			$details = $support->getTicketDetails( $_GET['value'], $start, RECORD_BY_PAGE );
			
			$ticket_user_name = $details[0]->user_name;
			// Remove Ticket summary informations
			unset($details[0]);
			if ( is_null($details) ) {
				throw new myException('Error in admin ticket details page : ticket id not allowed !');
			}
			
			// Create a pagination class instance
			$paging = new pagination();
			$lang = new lang();
			foreach( $details as $key => $value )
			{
				$paging->addLine();
				$value->msg_author = ( $value->is_reply=='true' ? $lang->getWordFromLangFile( 'ticket_msg_author_us' ) : $ticket_user_name );
				$value->msg_date = date($lang->userGetDateFormat().' '.$lang->userGetTimeFormat(), $value->posted);
				$value->message=nl2br($value->message);
				$paging->addCell( html::makeHtmlForTicketDetails( 0, $value ) );
				$paging->addCell( $value->message );
			}
			// Return result to js engine
			echo $paging->getResult();
		break;
		
		case 'tbl_cron':
			$cron = new cron();
			$lang = new lang();
			$paging = new pagination();
			$_SESSION['user']->userCheckAccess(LEVEL_CUSTOMER);
			// Verify the inputs
			if ( !isset($_GET['p']) || !textVerification::verifID($_GET['p']) || $_GET['p']<1) {
				throw new myException('Error in myhostings page : number of page to show not valid !');
			}
			// Check page number
			$pages_count = $cron->userCountTotalPages();
			if ( $_GET['p'] > $pages_count ) {
				throw new myException('Error in myhostings page : number of page to show too big !');
			}
			// Get Page datas
			$start=($_GET['p']-1) * RECORD_BY_PAGE;
			$cronlist = $cron->userListCrons( $_SESSION['hosting']->information_hosting->id, $start, RECORD_BY_PAGE);
			foreach ($cronlist as $key => $value)
			{
				$value->current_page = $_GET['p'];
				$value->max_pages = $pages_count;
				$start_stop_title = ( $value->is_active == 'true' ? 'cron_stop_title':'cron_start_title');
				$value->start_stop_title = $lang->getWordFromLangFile($start_stop_title);
				$value->delete_title = $lang->getWordFromLangFile('cron_delete_title');
				$time_to_execute = $value->execute_every / 60;
				$unit = $lang->getWordFromLangFile('minutes');
				if ( $time_to_execute > 60 ) {
					$time_to_execute = $time_to_execute / 60;
					$unit = $lang->getWordFromLangFile('hours');
				}
				$paging->addLine();
				$paging->addCell( html::makeHtmlForCron(1, $value->address) );
				$paging->addCell( date($lang->userGetTimeFormat().' '.$lang->userGetDateFormat(), $value->executed_at) );
				$paging->addCell( round($time_to_execute, 0).' '.$unit);
				$paging->addCell( html::makeHtmlForCron(0, $value));
				$paging->setCellAttribute( $paging->getLinesCount() -1, 0, 'title', htmlentities($value->address) );
			}
			echo $paging->getResult();
		break;
		
		case 'form_new_cron':
			$_SESSION['user']->userCheckAccess(LEVEL_REGISTER);
			$ret_code = array();
			$ret_code[]= 1;
			// Check the task's url
			if ( !isset($_POST['req_url']) ) $ret_code[] = 'req_url_missing';
			if ( !textVerification::verifUrl($_POST['req_url']) ) 	$ret_code[] = 'err_req_url';
			// Check the activation value
			if ( !textVerification::verifBoolean($_POST['active']) ) {
				throw new myException('Error in from new cron : boolean for task activation not valid !');
			}
			// Check and convert the task's execution frequency
			if ( !isset($_POST['req_frequency']) ) $ret_code[] = 'err_req_frequency_missing';
			if ( !textVerification::verifInteger($_POST['req_frequency']) ) $ret_code[] = 'err_req_frequency';
			
			if ( !textVerification::verifInteger($_POST['freq_unit'], 0, 3 ) ) {
				throw new myException('Error in from new cron : frequency unit index not valid !');
			}
			$freq = $_POST['req_frequency'] * 60; // Minutes
			$freq *= ($_POST['freq_unit']=='1' ? 60:1); // Hours
			$freq *= ($_POST['freq_unit']=='2' ? 1440:1); // Days
			$freq *= ($_POST['freq_unit']=='3' ? 10080:1); // Weeks
			
			if ( $freq < CRON_MIN_TIME ) $ret_code[] = 'err_freq_too_small';
			
			// Check and convert the task's first start
			if ( !isset($_POST['first_start']) ) {
				$_POST['first_start']=0;
			}
			if ( !textVerification::verifInteger($_POST['first_start']) ) $ret_code[] = 'err_first_start';
			
			if ( !textVerification::verifInteger($_POST['first_start_unit'], 0, 3 ) ) {
				throw new myException('Error in from new cron : first start unit index not valid !');
			}
			$first_start = $_POST['first_start'] * 60;
			$first_start *= ($_POST['first_start_unit']=='1' ? 60:1); // Hours
			$first_start *= ($_POST['first_start_unit']=='2' ? 1440:1); // Days
			$first_start *= ($_POST['first_start_unit']=='3' ? 10080:1); // Weeks
			$first_start += strtotime('now');

			// If no errors encountered at verification time, try to add the task in database
			if ( count($ret_code) == 1) {
				$cron = new cron();
				$result= $cron->userAddCron($_POST['req_url'], $freq, $first_start, $_POST['active']);
				switch($result)
				{
					case 0: // Script not reacheable
						$ret_code[] = 'err_not_reacheable';
						$ret_code[0]=0;
						break;
					case 1: // Cron task added successfully
						$ret_code[] = 'all_is_ok';
						break;
					case 2: // Limit of cronjob reached
						$ret_code[] = 'err_max_cronjobs_reached';
						break;
				}
			} else $ret_code[0]=0;
			echo json_encode($ret_code);
		break;
		
		case 'cronStopTask':
		case 'cronStartTask':
			$_SESSION['user']->userCheckAccess(LEVEL_REGISTER);
			// Verify the inputs
			if ( !isset($_POST['value']) || !textVerification::verifID($_POST['value']) ) {
				throw new myException('Error in '.$ajax_id.' : id of the task not valid !');
			}
			$cron = new cron();
			if ( $ajax_id == 'cronStopTask' ) {
				$res=$cron->userDeactiveCron($_POST['value']);
			} else {
				$res=$cron->userActiveCron($_POST['value']);
			}
			if ( $res != 1 ) {
				throw new myException('Error in '.$ajax_id.' : action returned '.$res);
			}
			echo json_encode(array('1'));
		break;
		
		case 'cronDeleteTask':
			$_SESSION['user']->userCheckAccess(LEVEL_REGISTER);
			// Verify the inputs
			if ( !isset($_POST['value']) || !textVerification::verifID($_POST['value']) ) {
				throw new myException('Error in cronDeleteTask : id of the task not valid !');
			}
			$cron = new cron();
			if ( $cron->userDeleteCron( $_POST['value'] ) === true )
				$res=1;
			else
				$res=0;
			echo json_encode(array($res));
		break;
		
		case 'form_new_vhost':
			$_SESSION['user']->userCheckAccess(LEVEL_REGISTER);
			$ret_code = array();
			$ret_code[]= 1;
			// Verify the inputs
			if ( !isset($_POST['req_host']) ) $ret_code[] = 'err_req_host_missing';
			if ( !textVerification::verifHost($_POST['req_host']) ) $ret_code[] = 'err_req_host';
			if ( !isset($_POST['req_usrfldr_root']) ) $ret_code[] = 'err_req_usrfldr_root_missing';
			if ( !textVerification::verifUnixPath($_POST['req_usrfldr_root']) ) $ret_code[] = 'err_req_usrfldr_root';
			if ( !textVerification::verifBoolean($_POST['active']) ) {
				throw new myException('Error in from new vhost : boolean for activation is not valid !');
			}
			
			if ( strlen( $_POST['email']) )
			{
				if ( !textVerification::verifEmail($_POST['email']) ) $ret_code[] = 'err_email';
			} else $_POST['email'] = NULL;
			
			$php_values = array();
			
			if ( strlen( $_POST['usrfldr_openbasedir']) )
			{
				if ( !textVerification::verifUnixPath($_POST['usrfldr_openbasedir']) ) $ret_code[] = 'err_usrfldr_openbasedir';
			} else {
				$_POST['usrfldr_openbasedir'] = $_POST['req_usrfldr_root'];
			}
			$php_values['open_basedir'] = $_POST['usrfldr_openbasedir'];
			
			if ( strlen( $_POST['sql_def_host']) )
			{
				if ( !textVerification::verifHost($_POST['sql_def_host']) )
					$ret_code[] = 'err_sql_def_host';
				else
					$php_values['sql_default_host'] = $_POST['sql_def_host'];
			}
			
			if ( strlen( $_POST['sql_def_user']) )
			{
				if ( !textVerification::verifPseudo($_POST['sql_def_user']) )
					$ret_code[] = 'err_sql_def_user';
				else
					$php_values['sql_default_user'] = $_POST['sql_def_user'];
			}
			
			if ( strlen( $_POST['sql_def_pwd']) )
			{
				if ( !textVerification::verifPassword($_POST['sql_def_pwd']) )
					$ret_code[] = 'err_sql_def_pwd';
				else
					$php_values['sql_default_pwd'] = $_POST['sql_def_pwd'];
			}
			
			if ( strlen( $_POST['tmp_usrfldr']) )
			{
				if ( !textVerification::verifUnixPath($_POST['tmp_usrfldr']) )
					$ret_code[] = 'tmp_usrfldr';
				else
					$php_values['temp_folder'] = $_POST['tmp_usrfldr'];
				
			}
			
			if ( strlen( $_POST['sess_usrfldr']) )
			{
				if ( !textVerification::verifUnixPath($_POST['sess_usrfldr']) )
					$ret_code[] = 'sess_usrfldr';
				else
					$php_values['sessions_folder'] = $_POST['sess_usrfldr'];
			}
			
			// Check all optional boolean values
			foreach ( array('allowindexes','allow_url_fopen','allow_url_include','display_errors','short_open_tag','session_autostart','magic_quotes','register_globals') as $key)
			{
				if ( !textVerification::verifBoolean($_POST[$key]) ) {
					throw new myException('Error in from new vhost : boolean "'.$key.'" is not valid !');
				} else {
					$php_values[$key] = $_POST[$key];
				}
			}
			
			// If no errors encountered at verification time, try to add the vhost in database
			if ( count($ret_code) == 1) {
				$vhost = new vhost();
				$res = $vhost->userAddVhost( $_POST['req_host'], $_POST['req_usrfldr_root'], $_POST['active'], $_POST['email'], $php_values );
				if ( true === $res) {
					$ret_code[] = 'all_is_ok';
				} else {
					$ret_code[0]=0;
					if ( $res == -1 )
					$ret_code[] = 'err_vhosts_max_reached';
					else
					$ret_code[] = 'err_host_exists';
				}
			} else $ret_code[0]=0;
			echo json_encode($ret_code); 
		break;
		
		case 'tbl_vhost':
			$vhost = new vhost();
			$lang = new lang();
			$paging = new pagination();
			$_SESSION['user']->userCheckAccess(LEVEL_CUSTOMER);
			// Verify the inputs
			if ( !isset($_GET['p']) || !textVerification::verifID($_GET['p']) || $_GET['p']<1) {
				throw new myException('Error in vhosts list page : number of page to show not valid !');
			}
			// Check page number
			$pages_count = $vhost->userCountTotalPages();
			if ( $_GET['p'] > $pages_count ) {
				throw new myException('Error in vhosts list page : number of page to show too big !');
			}
			// Get Page datas
			$start=($_GET['p']-1) * RECORD_BY_PAGE;
			$vhost_list = $vhost->userListVHosts( $_SESSION['hosting']->information_hosting->id, $start, RECORD_BY_PAGE);
			foreach ($vhost_list as $key => $value)
			{
				$value->current_page = $_GET['p'];
				$value->max_pages = $pages_count;
				$active_state = ( $value->is_active == 'true' ? '_yes':'_no');
				$value->active_state = $lang->getWordFromLangFile($active_state);
				
				$paging->addLine();
				$paging->addCell( $value->host );
				$paging->addCell( $value->doc_root );
				$paging->addCell( $value->server_admin );
				$paging->addCell( $value->active_state);
			}
			echo $paging->getResult();
		break;

	}
} catch (myException $error) {
	$error->displayCriticalError();
}
?>