Current File : //root/panel/modules/cron/code/controller.ext.php
<?php

/**
 * @copyright 2014-2015 Sentora Project (http://www.sentora.org/) 
 * Sentora is a GPL fork of the ZPanel Project whose original header follows:
 *
 * ZPanel - A Cross-Platform Open-Source Web Hosting Control panel.
 *
 * @package ZPanel
 * @version $Id$
 * @author Bobby Allen - ballen@bobbyallen.me
 * @copyright (c) 2008-2014 ZPanel Group - http://www.zpanelcp.com/
 * @license http://opensource.org/licenses/gpl-3.0.html GNU Public License v3
 *
 * This program (ZPanel) is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Change P.Peyremorte:
 * - cleaned WriteCronFile() (removed duplicate parts).
 * - reformated header inserted in crontab file (heading spaces and wrong EOL encoding)
 * - removed daemon task that is handled by independant crontab /etc/cron.d/zdaemon (linux)
 */
class module_controller extends ctrl_module
{

    static $error;
    static $noexists;
    static $cronnoexists;
    static $cronnowrite;
    static $alreadyexists;
    static $blank;
    static $ok;
    static $execscript;
    static $createEmail;
    static $createEmailFail;
    static $deleteCronEmail;
    static $deleteCronEmailFail;
    static $commad_dir_err;

    static function getCrons()
    {
        global $zdbh;
        global $controller;
        $currentuser = ctrl_users::GetUserDetail();

	$line = "<h2>" . ui_language::translate("Current Email") . "</h2>";
	$sql = $zdbh->prepare("SELECT * FROM x_cronemail WHERE ce_acc_fk=:userid AND ce_deleted_ts IS NULL");
        $sql->bindParam(':userid', $currentuser['userid']);
	$sql->execute();
	$result = $sql->fetch();
        if ($result) {
		$line .= "<form action=\"./?module=cron&action=DeleteEmail\" method=\"post\">";
                $line .= "<table class=\"table table-striped\">";
                $line .= "<tr>";
                $line .= "<th>" . ui_language::translate("Email") . "</th>";
                $line .= "<th></th>";
                $line .= "</tr>";
		//print_r($sql->fetch());exit;
                //while ($rowcrons = $sql->fetch()) {
                    $line .= "<tr>";
                    $line .= "<td>" . $result['ce_email_vc'] . "</td>";
                    //$line .= "<td>" . ui_language::translate(self::TranslateTiming($rowcrons['ct_timing_vc'])) . "</td>";
                    //$line .= "<td>" . $rowcrons['ct_description_tx'] . "</td>";
                    //$line .= "<td><button class=\"button-loader delete btn btn-danger\" type=\"submit\" name=\"inDelete_" . $rowcrons['ct_id_pk'] . "\" id=\"button\" value=\"inDelete_" . $rowcrons['ct_id_pk'] . "\">" . ui_language::translate("Delete") . "</button></td>";
                    $line .= "</tr>";
                //}
                $line .= "</table>";
                //$line .= runtime_csfr::Token();
                $line .= "</form>";
	}
        $line .= "<h2>" . ui_language::translate("Current Cron Tasks") . "</h2>";
        $sql = "SELECT COUNT(*) FROM x_cronjobs WHERE ct_acc_fk=:userid AND ct_deleted_ts IS NULL";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':userid', $currentuser['userid']);

        if ($numrows->execute()) {
            if ($numrows->fetchColumn() <> 0) {

                $sql = $zdbh->prepare("SELECT * FROM x_cronjobs WHERE ct_acc_fk=:userid AND ct_deleted_ts IS NULL");
                $sql->bindParam(':userid', $currentuser['userid']);
                $sql->execute();
                //$line .= "<form action=\"./?module=cron&action=DeleteCron\" method=\"post\">";
                $line .= "<form action=\"./?module=cron&action=EditCron\" method=\"post\">";
                $line .= "<table class=\"table table-striped\">";
                $line .= "<tr>";
                $line .= "<th>" . ui_language::translate("Script") . "</th>";
                $line .= "<th>" . ui_language::translate("Timing") . "</th>";
                $line .= "<th>" . ui_language::translate("Description") . "</th>";
                $line .= "<th></th>";
                $line .= "</tr>";
                while ($rowcrons = $sql->fetch()) {
                    $line .= "<tr>";
                    $line .= "<td>" . $rowcrons['ct_script_vc'] . "</td>";
                    $line .= "<td>" . $rowcrons['ct_timing_vc'] . "</td>";
                    $line .= "<td>" . stripslashes(trim($rowcrons['ct_fullpath_vc'],"'")) . "</td>";
                    //$line .= "<td><button class=\"button-loader delete btn btn-danger\" type=\"submit\" name=\"inDelete_" . $rowcrons['ct_id_pk'] . "\" id=\"button\" value=\"inDelete_" . $rowcrons['ct_id_pk'] . "\">" . ui_language::translate("Delete") . "</button></td>";
                    $line .= "<td><button class=\"button-loader btn btn-default\" type=\"submit\" name=\"inEdit_" . $rowcrons['ct_id_pk'] . "\" id=\"inEdit_" . $rowcrons['ct_id_pk'] . "\" value=\"inEdit_" . $rowcrons['ct_id_pk'] . "\">" . ui_language::translate("Edit") . "</button>";
                    $line .= "<button class=\"button-loader delete btn btn-danger\" type=\"submit\" name=\"inDelete_" . $rowcrons['ct_id_pk'] . "\" id=\"inDelete_" . $rowcrons['ct_id_pk'] . "\" value=\"inDelete_" . $rowcrons['ct_id_pk'] . "\">" . ui_language::translate("Delete") . "</button></td>";
                    $line .= "</tr>";
                }
                $line .= "</table>";
                $line .= runtime_csfr::Token();
                $line .= "</form>";
            } else {
                $line .= ui_language::translate("You currently do not have any tasks setup.");
            }
            return $line;
        }
    }
    static function gethelpicon()
    {
    	global $zdbh;
    	global $controller;
   	$temp=$controller->GetControllerRequest('URL','module') ;
    	$val = '/assets/one.txt';
    	$val1 = '/modules/';
   	$name=file_get_contents("modules/$temp/assets/helpicon.txt");
   	return $name;
    }

    static function getCreateCron()
    {
        global $zdbh;
        global $controller;
        $currentuser = ctrl_users::GetUserDetail();

        $line = "<h2>Create a new task</h2>";
        $line .= "<form action=\"./?module=cron&action=CreateCron\" method=\"post\">";
        $line .= "<table class=\"table table-striped\">";
        $line .= "<tr valign=\"top\">";
        $line .= "<th>" . ui_language::translate("Script") . ":</th>";
        $line .= '<td><input name="inScript" type="text" id="inScript" size="50" /><br />'
                . ui_language::translate("example") . ': /folder/task.php<br>'
                . ui_language::translate('Note 1 : Script path is relative to your sentora-user root directory:') . '<br>'
                . ' &nbsp; <b>' . ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username'] . '/</b><br>'
                . ui_language::translate('Note 2 : Each file access in your script must use absolute directory path as above.')
                . '</td>';
        $line .= "</tr>";
        $line .= "<tr>";
        $line .= "<th>" . ui_language::translate("Comment") . ":</th>";
        $line .= "<td><input name=\"inDescription\" type=\"text\" id=\"inDescription\" size=\"50\" maxlength=\"50\" /></td>";
        $line .= "</tr>";
        $line .= "<tr>";
        $line .= "<th>" . ui_language::translate("Executed") . ":</th>";
        $line .= "<td><select name=\"inTiming\" id=\"inTiming\">";
        $line .= "<option value=\"* * * * *\">" . ui_language::translate("Every 1 minute") . "</option>";
        $line .= "<option value=\"0,5,10,15,20,25,30,35,40,45,50,55 * * * *\">" . ui_language::translate("Every 5 minutes") . "</option>";
        $line .= "<option value=\"0,10,20,30,40,50 * * * *\">" . ui_language::translate("Every 10 minutes") . "</option>";
        $line .= "<option value=\"0,30 * * * *\">" . ui_language::translate("Every 30 minutes") . "</option>";
        $line .= "<option value=\"0 * * * *\">" . ui_language::translate("Every 1 hour") . "</option>";
        $line .= "<option value=\"0 0,2,4,6,8,10,12,14,16,18,20,22 * * *\">" . ui_language::translate("Every 2 hours") . "</option>";
        $line .= "<option value=\"0 0,8,16 * * *\">" . ui_language::translate("Every 8 hours") . "</option>";
        $line .= "<option value=\"0 0,12 * * *\">" . ui_language::translate("Every 12 hours") . "</option>";
        $line .= "<option value=\"0 0 * * *\">" . ui_language::translate("Every 1 day") . "</option>";
        $line .= "<option value=\"0 0 * * 0\">" . ui_language::translate("Every week") . "</option>";
        $line .="<option value=\"0 0 1 * *\">" . ui_language::translate("Every month") . "</option>";
        $line .= "</select></td>";
        $line .= "</tr>";
        $line .= "<tr>";
        $line .= "<th colspan=\"2\" align=\"right\"><input type=\"hidden\" name=\"inReturn\" value=\"GetFullURL\" />";
        $line .= "<input type=\"hidden\" name=\"inUserID\" value=\"" . $currentuser['userid'] . "\" />";
        $line .= runtime_csfr::Token();
        $line .= "<button class=\"button-loader btn btn-primary\" type=\"submit\" id=\"button\">" . ui_language::translate("Create") . "</button></th>";
        $line .= "</tr>";
        $line .= "</table>";
        $line .= "</form>";

        return $line;
    }
    static function getCreateCronNew()
    {
	global $zdbh;
        global $controller;
	$cron_script="";$cron_file="";$cron_timing="";$cron_desc="";$cron_timing="";$minute_setting="";$hour_setting="";$day_setting="";
        $month_setting="";$weekday_setting="";$cron_type="";$command_type="checked";$url_type="";
	$cron_url_script="";$cron_url_file="";$cron_url_desc="";
        $currentuser = ctrl_users::GetUserDetail();
	$vhost_path = ctrl_options::GetSystemOption('hosted_dir');
	$default_path= $currentuser['username']."/";
	
	if($controller->GetControllerRequest('URL', 'show') == 'Edit' ) {
		$submit_label = ui_language::translate('Update');
		$form_action  = "UpdateCron";
		$current_cron_values = self::ListCurrentCron($controller->GetControllerRequest('URL', 'other'));
		foreach ($current_cron_values as $row) {
			$cron_script   	= $row['cron_script'];
			$cron_file	= trim($row['cron_file'],"'");
			//$script_cmd 	= "/var/sentora/hostdata/".$default_path;
			$script_cmd 	= $vhost_path.$default_path;
			$cron_file 	= str_replace($script_cmd, "", $cron_file);
			$cron_timing	= $row['cron_timing']; 
			$cron_desc	= $row['cron_desc'];
			$cron_desc      = str_replace($script_cmd, "", $cron_desc);
			$cron_id	= $row['id'];
			if (filter_var($cron_file, FILTER_VALIDATE_URL) == TRUE ) {
				$cron_type="url";
				$command_type = "";
				$url_type = "checked";
				$cron_url_script = $cron_script;
				$cron_url_file = $cron_file;
				$cron_url_desc = $cron_desc;
				$cron_script = "";
				$cron_file   = "";
				$cron_desc   = "";

				$settings_type ='<tr id="cron_url_settings" style="display:block">';
				$settings_type .='<td class ="hrcronlbltd"><label>URL:</label></td>';
				$settings_type .='<td class ="hrcroncmdexectd"><input type="text" id="exec_url" name="exec_url" placeholder="eg:- curl or wget" value="'.$cron_url_script.'"/></td>';
				$settings_type .='<td class ="hrcroncmdexectd"><input type="text" id="script_url" name="script_url" placeholder="Enter the url here" value="'.$cron_url_file.'"/></td>';
				$settings_type .='<td class ="hrcroncmdexectd"><input type="text" id="log_url" name="log_url" placeholder="log(optional)" value="'.$cron_url_desc.'" /></td>';
				$settings_type .='</tr>';
			
				$settings_type .= '<tr id="cron_command_settings" style="display:none">';
                                $settings_type .= '<td class ="hrcronlbltd"><label>Command:</label></td>';
                                $settings_type .= '<td class ="hrcroncmdexectd"><input type="text" id="exec_command" name="exec_command" placeholder="eg:- php or sh" value="'.$cron_script.'" /></td>';
                                $settings_type .= '<td class ="hrcroncmdscrtd"><input type="text" id="scr_def_path" name="scr_def_path" value="'.$default_path.'" style="width: 200px !important;text-align: center; background-color: #e7e7e7;border-radius: 0px;" readonly /><input type="text" id="script_command" name ="script_command" placeholder="command" style="width: 391px !important;margin-left: -27px;" value="'.$cron_file.'" /></td>';
                                $settings_type .= '<td class ="hrcroncmdexectd"><input type="text" id="log_def_path" name="log_def_path" value="'.$default_path.'" style="width: 200px !important;text-align: center;background-color: #e7e7e7;border-radius: 0px;" readonly /><input type="text" id="log_command" name="log_command" placeholder="log(optional)" style="width: 391px !important;margin-left: -27px;" value="'.$cron_desc.'" /></td>';
                                $settings_type .= '<input type="hidden" name ="cron_id" id="cron_id" value="'.$cron_id.'">';
                                $settings_type .= '</tr>';

				//echo "<script>document.getElementById('cron_command_settings').css('display','none');</script>";
				//echo "<script>document.getElementById('cron_url_settings').css('display','block');</script>";
			} else {
				$cron_type="command";
				$command_type = "checked";
                                $url_type = "";

				$settings_type ='<tr id="cron_url_settings" style="display:none">';
                                $settings_type .='<td class ="hrcronlbltd"><label>URL:</label></td>';
                                $settings_type .='<td class ="hrcroncmdexectd"><input type="text" id="exec_url" name="exec_url" placeholder="eg:- curl or wget" value="'.$cron_url_script.'"/></td>';
                                $settings_type .='<td class ="hrcroncmdexectd"><input type="text" id="script_url" name="script_url" placeholder="Enter the url here" value="'.$cron_url_file.'"/></td>';
                                $settings_type .='<td class ="hrcroncmdexectd"><input type="text" id="log_url" name="log_url" placeholder="log(optional)" value="'.$cron_url_desc.'" /></td>';
                                $settings_type .='</tr>';

				$settings_type .= '<tr id="cron_command_settings" style="display:block">';
				$settings_type .= '<td class ="hrcronlbltd"><label>Command:</label></td>';
				$settings_type .= '<td class ="hrcroncmdexectd"><input type="text" id="exec_command" name="exec_command" placeholder="eg:- php or sh" value="'.$cron_script.'" /></td>';
				$settings_type .= '<td class ="hrcroncmdscrtd"><input type="text" id="scr_def_path" name="scr_def_path" value="'.$default_path.'" style="width: 200px !important;text-align: center; background-color: #e7e7e7;border-radius: 0px;" readonly /><input type="text" id="script_command" name ="script_command" placeholder="command" style="width: 391px !important;margin-left: -27px;" value="'.$cron_file.'" /></td>';
				$settings_type .= '<td class ="hrcroncmdexectd"><input type="text" id="log_def_path" name="log_def_path" value="'.$default_path.'" style="width: 200px !important;text-align: center;background-color: #e7e7e7;border-radius: 0px;" readonly /><input type="text" id="log_command" name="log_command" placeholder="log(optional)" style="width: 391px !important;margin-left: -27px;" value="'.$cron_desc.'" /></td>';
				$settings_type .= '<input type="hidden" name ="cron_id" id="cron_id" value="'.$cron_id.'">';
				$settings_type .= '</tr>';
			}
		}
		$cron_timings = explode(" ",$cron_timing);
		$minute_setting = $cron_timings[0];
		$hour_setting = $cron_timings[1];
		$day_setting = $cron_timings[2];
		$month_setting = $cron_timings[3];
		$weekday_setting = $cron_timings[4];
	} else{
		$submit_label = ui_language::translate('Create');
		$form_action  = "CreateCron";
		$settings_type = '<tr id="cron_command_settings">';
        	$settings_type .= '<td class ="hrcronlbltd"><label>Command:</label></td>';
        	$settings_type .= '<td class ="hrcroncmdexectd"><input type="text" id="exec_command" name="exec_command" placeholder="eg:- php or sh" value="'.$cron_script.'" /></td>';
        	$settings_type .= '<td class ="hrcroncmdscrtd"><input type="text" id="scr_def_path" name="scr_def_path" value="'.$default_path.'" style="width: 200px !important;text-align: center; background-color: #e7e7e7;border-radius: 0px;" readonly /><input type="text" id="script_command" name ="script_command" placeholder="command" style="width: 391px !important;margin-left: -27px;" value="'.$cron_file.'" /></td>';
        	$settings_type .= '<td class ="hrcroncmdexectd"><input type="text" id="log_def_path" name="log_def_path" value="'.$default_path.'" style="width: 200px !important;text-align: center;background-color: #e7e7e7;border-radius: 0px;" readonly /><input type="text" id="log_command" name="log_command" placeholder="log(optional)" style="width: 391px !important;margin-left: -27px;" value="'.$cron_desc.'" /></td>';
        	$settings_type .= '</tr>';
	
	        $settings_type .='<tr id="cron_url_settings" style="display:none">';
	        $settings_type .='<td class ="hrcronlbltd"><label>URL:</label></td>';
	        $settings_type .='<td class ="hrcroncmdexectd"><input type="text" id="exec_url" name="exec_url" placeholder="eg:- curl or wget" value="'.$cron_url_script.'"/></td>';
	        $settings_type .='<td class ="hrcroncmdexectd"><input type="text" id="script_url" name="script_url" placeholder="Enter the url here" value="'.$cron_url_file.'"/></td>';
	        $settings_type .='<td class ="hrcroncmdexectd"><input type="text" id="log_url" name="log_url" placeholder="log(optional)" value="'.$cron_url_desc.'" /></td>';
		$settings_type .= '<input type="hidden" name ="cron_id" id="cron_id" value="'.$cron_id.'">';
	        $settings_type .='</tr>';
	}

	$line = '<div id="cron_head">';
	$line .= '<div id="cron_email">';
	$line .= '<form action="./?module=cron&action=CreateCronEmail" method="post">';
	$line .= '<div id="cron_add_email">';
	$line .= '<label style="padding-right: 55px;">Add Email</label>';
	$line .= '<input type="email" id ="cronemail" name ="cronemail" style="width: 404px;"/>';
	$line .= '<button class="button-loader btn btn-primary" type="submit" id="button">'.ui_language::translate("CreateEmail").'</button>';
	$line .= '</div>';
	$line .= '</form>';
	$line .= '</div>';
	$line .= '</div>';

	$line .= '<div id="cronjob">';
	$line .= '<form action="./?module=cron&action='.$form_action.'" method="post">';
	$line .= '<div id="cron_body">';
	$line .= '<h2>Add New Cron Job</h2>';
	$line .= '<table>';
	$line .= '<tr><div id="cron_comm_settings">';
	$line .= '<td class ="hrcronlbltd"><label>'.ui_language::translate("Common Settings").'</label></td>';
	$line .= '<td class ="hrcroncomseltd" colspan="2">';
	$line .= '<input type="hidden" name ="cron_id" id="cron_id" value="'.$cron_id.'">';
	$line .= '<select id="com_setting" name ="com_setting" onchange="commonSettingChanges()" >';
	$line .= '<option value ="--" >Common Settings</option>';
	$line .= '<option value ="0,30 * * * *" '.(trim($cron_timing)=="0,30 * * * *"?'selected="selected"':'').' >Twice per hour(0,30 * * * *)</option>';
	$line .= '<option value ="0 * * * *" '.(trim($cron_timing)=="0 * * * *"?'selected="selected"':'').' >Once per hour(0 * * * *)</option>';
	$line .= '<option value ="0 0,12 * * *" '.(trim($cron_timing)=="0 0,12 * * *"?'selected="selected"':'').' >Twice per day(0 0,12 * * *)</option>';
	$line .= '<option value ="* * * * *" '.(trim($cron_timing)=="* * * * *"?'selected="selected"':'').' >Once per Minute(* * * * *)</option>';
	$line .= '<option value ="*/5 * * * *" '.(trim($cron_timing)=="*/5 * * * *"?'selected="selected"':'').' >Once per 5 minutes(*/5 * * * *)</option>';
	$line .= '<option value ="0 0 * * 0" '.(trim($cron_timing)=="0 0 * * 0"?'selected="selected"':'').' >Once per week(0 0 * * 0)</option>';
	$line .= '<option value ="0 0 1,15 * *" '.(trim($cron_timing)=="0 0 1,15 * *"?'selected="selected"':'').' >Twice per Month(1st and 15th/month)(0 0 1,15 * *)</option>';
	$line .= '<option value ="0 0 1 * *" '.(trim($cron_timing)=="0 0 1 * *"?'selected="selected"':'').' >Once per Month(0 0 1 * *)</option>';
	$line .= '<option value ="0 0 1 1 *" '.(trim($cron_timing)=="0 0 1 1 *"?'selected="selected"':'').' >Once Per Year(0 0 1 1 *)</option>';
	$line .= '</select></td>';
	$line .= '</div></tr>';
			
	$line .= '<tr><div id="cron_minute_settings">';
	$line .= '<td><label class ="hrcronlbltd">Minute:</label></td>';
	$line .= '<td class ="hrcrontxttd"><input type="text" id="minute_text" name="minute_text" value="'.$minute_setting.'" onblur="changeTxtSettings(\'minute\')" />';
	$line .= '<select id="minute_setting" name ="minute_setting" onchange="changeSettings(\'minute\')" >';							
	$line .= '<option value ="">Minute Settings</option>';
	$line .= '<option value ="*" '.(trim($minute_setting)=="*"?'selected="selected"':'').'>Once per minute(*)</option>';
	$line .= '<option value ="*/2" '.(trim($minute_setting)=="*/2"?'selected="selected"':'').'>Twice per two minutes(*/2)</option>';
	$line .= '<option value ="*/5" '.(trim($minute_setting)=="*/5"?'selected="selected"':'').'>Twice per five minutes(*/5)</option>';
	$line .= '<option value ="*/10" '.(trim($minute_setting)=="*/10"?'selected="selected"':'').'>Twice per ten minutes(*/10)</option>';
	$line .= '<option value ="*/15" '.(trim($minute_setting)=="*/15"?'selected="selected"':'').'>Twice per fifteen minutes(*/15)</option>';
	$line .= '<option value ="0,30" '.(trim($minute_setting)=="0,30"?'selected="selected"':'').'>Twice per thirty minutes(0,30)</option>';	
	$line .= '<option value ="--" >--Minute--</option>';
	for($i=0;$i<60;$i++)
	{
		if($i<10) {
			$mins = "0".$i;
		} else {
			$mins = $i;
		}
		$line .= '<option value ='.$i.' '.(trim($minute_setting)==$i?'selected="selected"':'').' >'.$mins.' ('.$i.')</option>';
	}

	$line .= '</select></td>';
	$line .= '</div></tr>';
	$line .= '<tr><div id="cron_hour_settings">';
	$line .= '<td><label class ="hrcronlbltd">Hour:</label></td>';
	$line .= '<td class ="hrcrontxttd"><input type="text" id="hour_text" name="hour_text" value="'.$hour_setting.'" onblur="changeTxtSettings(\'hour\')"/>';
	$line .= '<select id="hour_setting" name ="hour_setting" onchange="changeSettings(\'hour\')" >';
	$line .= '<option value ="--">Hour Settings</option>';
	$line .= '<option value ="*" '.(trim($hour_setting)=="*"?'selected="selected"':'').' >Every Hour(*)</option>';
	$line .= '<option value ="*/2" '.(trim($hour_setting)=="*/2"?'selected="selected"':'').' >Every Other Hour(*/2)</option>';
	$line .= '<option value ="*/3" '.(trim($hour_setting)=="*/3"?'selected="selected"':'').' >Every Three Hour(*/3)</option>';
	$line .= '<option value ="*/4" '.(trim($hour_setting)=="*/4"?'selected="selected"':'').' >Every Four Hour(*/4)</option>';
	$line .= '<option value ="*/6" '.(trim($hour_setting)=="*/6"?'selected="selected"':'').' >Every Six Hour(*/6)</option>';
	$line .= '<option value ="0,12" '.(trim($hour_setting)=="0,12"?'selected="selected"':'').' >Every Twelve Hour(0,12)</option>';
	$line .= '<option value ="--">Hours</option>';
	$time = "";
	$meridiem = "";
	for($i=0; $i<24; $i++) {
		if($i<13) {
			if($i==0) {
				$time = "12:00";
				$meridiem = "AM";
			} else if($i==12) {
				$time = "12:00";
				$meridiem = "PM";
			} else {
				$time = $i.":00";
				$meridiem = "AM";
			}
			$time 	= $time.$meridiem."(".$i.")";
		} else {
			$time = $i-12;
			$time = $time. ":00";
			$meridiem = "PM";
			$time   = $time.$meridiem."(".$i.")";
		}
		$line .= '<option value ="'.$i.'" '.(trim($hour_setting)==$i?'selected="selected"':'').' >'.$time.'</option>';
	}
	$line .= '</select></td>';
	$line .= '</div></tr>';
	$line .= '<tr><div id="cron_day_settings">';
	$line .= '<td class ="hrcronlbltd"><label>Day:</label></td>';
	$line .= '<td class ="hrcrontxttd"><input type="text" id="day_text" name ="day_text" value="'.$day_setting.'" onblur="changeTxtSettings(\'day\')"/>';
	$line .= '<select id="day_setting" name ="day_setting" onchange="changeSettings(\'day\')">';
	$line .= '<option value="--">Day Settings</option>';
	$line .= '<option value="*" '.(trim($day_setting)=="*"?'selected="selected"':'').' >Every Day(*)</option>';
	$line .= '<option value="*/2" '.(trim($day_setting)=="*/2"?'selected="selected"':'').' >Every Other Day(*/2)</option>';
	$line .= '<option value="1,15" '.(trim($day_setting)=="1,15"?'selected="selected"':'').'>Every 1st and 15th of the Month(1,15)</option>';
	$line .= '<option value="--">--Days--</option>';
	for($i=1; $i<=31; $i++) {
		if($i== 1 || $i== 21 || $i==31) {
			$ordinal = "st";
		} else if($i==2 || $i == 22 || $i == 23) {
			$ordinal = "nd";
		} else if($i==3) {
                        $ordinal = "rd";
                } else {
			$ordinal = "th";
		}
		$day = $i.$ordinal."(".$i.")";
		$line .= '<option value="'.$i.'" '.(trim($day_setting)==$i?'selected="selected"':'').' >'.$day.'</option>';
	}
	$line .= '</select></td>';
	$line .= '</div></tr>';
	$line .= '<tr><div id="cron_month_settings">';
	$line .= '<td class ="hrcronlbltd"><label>Month:</label></td>';
	$line .= '<td class ="hrcrontxttd"><input type="text" id="month_text" name="month_text" value="'.$month_setting.'" onblur="changeTxtSettings(\'month\')"/>';
	$line .= '<select id="month_setting" name ="month_setting" onchange="changeSettings(\'month\')">';
	$line .= '<option value="--">--Month Settings--</option>';
	$line .= '<option value="*" '.(trim($month_setting)=="*"?'selected="selected"':'').' >Every Month(*)</option>';
	$line .= '<option value="*/2" '.(trim($month_setting)=="*/2"?'selected="selected"':'').' >Every Other Month(*/2)</option>';
	$line .= '<option value="*/3" '.(trim($month_setting)=="*/3"?'selected="selected"':'').' >Every Three Month(*/3)</option>';
	$line .= '<option value="1,7" '.(trim($month_setting)=="1,7"?'selected="selected"':'').' >Every Six Month(1,7)</option>';
	$line .= '<option value="--">--Months--</option>';
	$line .= '<option value="1" '.(trim($month_setting)=="1"?'selected="selected"':'').' >January(1)</option>';
	$line .= '<option value="2" '.(trim($month_setting)=="2"?'selected="selected"':'').' >February(2)</option>';
	$line .= '<option value="3" '.(trim($month_setting)=="3"?'selected="selected"':'').' >March(3)</option>';
	$line .= '<option value="4" '.(trim($month_setting)=="4"?'selected="selected"':'').' >April(4)</option>';
	$line .= '<option value="5" '.(trim($month_setting)=="5"?'selected="selected"':'').' >May(5)</option>';
	$line .= '<option value="6" '.(trim($month_setting)=="6"?'selected="selected"':'').' >June(6)</option>';
	$line .= '<option value="7" '.(trim($month_setting)=="7"?'selected="selected"':'').' >July(7)</option>';
	$line .= '<option value="8" '.(trim($month_setting)=="8"?'selected="selected"':'').' >August(8)</option>';
	$line .= '<option value="9"> '.(trim($month_setting)=="9"?'selected="selected"':'').' September(9)</option>';
	$line .= '<option value="10" '.(trim($month_setting)=="10"?'selected="selected"':'').' >October(10)</option>';
	$line .= '<option value="11" '.(trim($month_setting)=="11"?'selected="selected"':'').' >November(11)</option>';
	$line .= '<option value="12" '.(trim($month_setting)=="12"?'selected="selected"':'').' >December(12)</option>';
	$line .= '</select></td>';
	$line .= '</div></tr>';
	$line .= '<tr><div id="cron_weekday_settings">';
	$line .= '<td class ="hrcronlbltd"><label>Weekday:</label></td>';
	$line .= '<td class ="hrcrontxttd"><input type = "text" id="weekday_text" name ="weekday_text" value="'.$weekday_setting.'" onblur="changeTxtSettings(\'weekday\')"/>';
	$line .= '<select id="weekday_setting" name ="weekday_setting" onchange="changeSettings(\'weekday\')" >';
	$line .= '<option value ="--">Weekday Settings</option>';
	$line .= '<option value ="*" '.(trim($weekday_setting)=="*"?'selected="selected"':'').' >Every Day(*)</option>';
	$line .= '<option value ="1-5" '.(trim($weekday_setting)=="1-5"?'selected="selected"':'').' >Every Weekday(1-5)</option>';
	$line .= '<option value ="6,0" '.(trim($weekday_setting)=="6,0"?'selected="selected"':'').' >Every Weekend Day(6,0)</option>';
	$line .= '<option value ="1,3,5" '.(trim($weekday_setting)=="1,3,5"?'selected="selected"':'').' >Every Monday, Wedeneseday, and Friday(1,3,5)</option>';
	$line .= '<option value ="2,4" '.(trim($weekday_setting)=="2,4"?'selected="selected"':'').' >Every Tuesday and Thursday(2,4)</option>';
	$line .= '<option value ="0" '.(trim($weekday_setting)=="0"?'selected="selected"':'').' >Sunday(0)</option>';
	$line .= '<option value ="1" '.(trim($weekday_setting)=="1"?'selected="selected"':'').' >Monday(1)</option>';
	$line .= '<option value ="2" '.(trim($weekday_setting)=="2"?'selected="selected"':'').' >Tuesday(2)</option>';
	$line .= '<option value ="3" '.(trim($weekday_setting)=="3"?'selected="selected"':'').' >Wednesday(3)</option>';
	$line .= '<option value ="4" '.(trim($weekday_setting)=="4"?'selected="selected"':'').' >Thursday(4)</option>';
	$line .= '<option value ="5" '.(trim($weekday_setting)=="5"?'selected="selected"':'').' >Friday(5)</option>';
	$line .= '<option value ="6" '.(trim($weekday_setting)=="6"?'selected="selected"':'').' >Saturday(6)</option>';
	$line .= '</select></td>';
	$line .= '</div></tr>';

	$line .= '<tr><input id="command" type="radio" name="crontype" value="command" onclick="changeCommandOrUrl();" '.$command_type.' > Command';
	$line .= '<input id="url" type="radio" name="crontype" value="url" onclick="changeCommandOrUrl();" '.$url_type.' > URL';
	$line .= '</tr>';

	$line .= $settings_type;	

	$line .= '<tr><div id="cron_submit">';
	$line .= '<td><input type="hidden" name="inUserID" value="' . $currentuser["userid"] . '" /></td>';
	$line .= '<td><button class="button-loader btn btn-primary" type="submit" id="button">' .$submit_label. '</button></td>';
	$line .= '</div></tr></table>';
	$line .= '</div>';
	$line .= "</form>";
	$line .= '</div>';
	return $line;
    }

    static function doUpdateCron()
    {
	global $zdbh;
        global $controller;
        //runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
	$vhost_path = ctrl_options::GetSystemOption('hosted_dir'); 

	$minute_timing      = $controller->GetControllerRequest('FORM', 'minute_text');
        $hour_timing        = $controller->GetControllerRequest('FORM', 'hour_text');
        $day_timing         = $controller->GetControllerRequest('FORM', 'day_text');
        $month_timing       = $controller->GetControllerRequest('FORM', 'month_text');
        $weekday_timing     = $controller->GetControllerRequest('FORM', 'weekday_text');
        $common_timing      = $minute_timing." ".$hour_timing." ".$day_timing." ".$month_timing." ".$weekday_timing;

        $cron_type          = $controller->GetControllerRequest('FORM', 'crontype');
        if($cron_type == "url") {
            $exec_command   = $controller->GetControllerRequest('FORM', 'exec_url');
            $script_command = $controller->GetControllerRequest('FORM', 'script_url');
            $log_command    = $controller->GetControllerRequest('FORM', 'log_url');
        } else {
            $exec_command       = $controller->GetControllerRequest('FORM', 'exec_command');
            $script_command     = $controller->GetControllerRequest('FORM', 'script_command');
            $log_command        = $controller->GetControllerRequest('FORM', 'log_command');
        }

        if(strpos($script_command, " ")) {
            $script_cmd = addcslashes($script_command, " ");
        } else {
            $script_cmd = $script_command;
        }
        $script_path        = explode("/",$script_cmd);
        $script_name        = $script_path[sizeof($script_path)-1];
        if(strpos($exec_command,"/")) {
            $exec_script    = explode("/",$exec_command);
            $exec_script    = $exec_script[sizeof($exec_script)-1];
        } else {
            $exec_script    = $exec_command;
        }
        if($cron_type != 'url') {
            //$script_cmd = "/var/sentora/hostdata/".$currentuser['username']."/public_html/".$script_cmd;
            $script_cmd = $vhost_path.$currentuser['username']."/".$script_cmd;
        } else {
            $script_cmd = "'".$script_cmd."'";
        }
	if($log_command) {
            if(strpos($log_command, " ")) {
                $log_cmd = addcslashes($log_command, " ");
            } else {
                $log_cmd = $log_command;
            }
        }
        //$log_command = $log_cmd ? "/var/sentora/hostdata/".$currentuser['username']."/public_html/".$log_cmd : "";
        $log_command = $log_cmd ? $vhost_path.$currentuser['username']."/".$log_cmd : "";

        $whereis_execscript = trim(shell_exec('whereis '.$exec_script.' | awk \'{print $2}\''));
        if($whereis_execscript) {
           if($log_command || $log_command !="") {
                //$script_to_exec = $whereis_execscript." ".$script_command." >> " .$log_command;
                $script_to_exec = $whereis_execscript." ".$script_cmd." >> " .$log_command;
            } else {
                //$script_to_exec = $whereis_execscript." ".$script_command;
                $script_to_exec = $whereis_execscript." ".$script_cmd;
            }
        } else {
            self::$execscript = TRUE;
            return FALSE;
        }
        $description = $currentuser['username']."/".$script_command;
	$cron_id = $controller->GetControllerRequest('FORM', 'cron_id');
        $sql = $zdbh->prepare("UPDATE x_cronjobs SET ct_script_vc=:script, ct_timing_vc=:timing, ct_fullpath_vc=:fullpath, ct_description_tx=:description, ct_created_ts=:time WHERE ct_id_pk=:cron_id") ;
        $sql->bindParam(':script', $whereis_execscript);
        $sql->bindParam(':timing', $common_timing);
        $sql->bindParam(':fullpath', $script_cmd);
        $sql->bindParam(':description', $log_command);
	$sql->bindParam(':time', time());
	$sql->bindParam(':cron_id', $cron_id);
        $sql->execute();
        self::WriteCronFile();
        self::$ok = TRUE;
        return;   
    }

    static function doCreateCronEmail()
    {
	global $zdbh;
        global $controller;
        //runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();

	$cronemail = $controller->GetControllerRequest('FORM', 'cronemail');
	$cronemail = str_replace(" ","",$cronemail);

	if(!$cronemail || $cronemail == "") {
		$sql = $zdbh->prepare("UPDATE x_cronemail SET ce_deleted_ts=:time WHERE ce_acc_fk=:userid AND ce_deleted_ts is NULL");
                $time = time();
                $sql->bindParam(':userid',$currentuser["userid"]);
                $sql->bindParam(':time',$time);
                $cron_email_delete_count = $sql->execute();
		//$cron_email_delete_count = $sql->rowCount();
		if($cron_email_delete_count) {
			self::$deleteCronEmail = TRUE;
			self::WriteCronFile();
		} else {
			self::$deleteCronEmailFail = TRUE;
		}
	} else {
		$sql = $zdbh->prepare("SELECT * FROM x_cronemail WHERE ce_acc_fk=:userid AND ce_deleted_ts is NULL");
        	$sql->bindParam(':userid',$currentuser["userid"]);
        	$sql->execute();
		$cron_email_count = $sql->fetchColumn();
		if($cron_email_count) {
		//while($sql->fetch()) {
			$sql = $zdbh->prepare("UPDATE x_cronemail SET ce_email_vc=:cronemail, ce_created_ts=:time WHERE ce_acc_fk=:userid AND ce_deleted_ts is NULL");
			$time = time();
        		$sql->bindParam(':userid',$currentuser["userid"]);
        		$sql->bindParam(':cronemail',$cronemail);
        		$sql->bindParam(':time',$time);
        		$sql->execute();
			$cron_email_update_count = $sql->rowCount();
        		//$cron_email_count = $sql->fetchColumn();
			if($cron_email_update_count) {
				self::$createEmail = TRUE;
                        	self::WriteCronFile();
			} else {
				self::$createEmailFail = TRUE;
			}			
		//}
		} else {

			$sql=$zdbh->prepare("INSERT INTO x_cronemail(ce_acc_fk,ce_email_vc,ce_created_ts)VALUES(:userid,:cronemail,".time().")");
			$sql->bindParam(':userid',$currentuser["userid"]); 
			$sql->bindParam(':cronemail', $cronemail);
			$sql->execute();
			$inserted_id = $zdbh->lastInsertId();
			if($inserted_id) {
				self::$createEmail = TRUE;
				self::WriteCronFile();
			} else {
				self::$createEmailFail = TRUE; 
			}
		}
	}
    }

    static function doCreateCron()
    {
        global $zdbh;
        global $controller;
        //runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
	$vhost_path = ctrl_options::GetSystemOption('hosted_dir');
      	if (fs_director::CheckForEmptyValue(self::CheckCronForErrors())) {
	    $minute_timing 	= $controller->GetControllerRequest('FORM', 'minute_text');
	    $hour_timing 	= $controller->GetControllerRequest('FORM', 'hour_text');
	    $day_timing 	= $controller->GetControllerRequest('FORM', 'day_text');
	    $month_timing 	= $controller->GetControllerRequest('FORM', 'month_text');
	    $weekday_timing 	= $controller->GetControllerRequest('FORM', 'weekday_text');
	    $common_timing  	= $minute_timing." ".$hour_timing." ".$day_timing." ".$month_timing." ".$weekday_timing;
	
	    $cron_type		= $controller->GetControllerRequest('FORM', 'crontype');
	    if($cron_type == "url") {
		$exec_command 	= $controller->GetControllerRequest('FORM', 'exec_url');
	    	$script_command	= $controller->GetControllerRequest('FORM', 'script_url');
	    	$log_command 	= $controller->GetControllerRequest('FORM', 'log_url');
	    } else {
		$exec_command       = $controller->GetControllerRequest('FORM', 'exec_command');
	        $script_command     = $controller->GetControllerRequest('FORM', 'script_command');
        	$log_command        = $controller->GetControllerRequest('FORM', 'log_command');
	    }
	    
	    if(strpos($script_command, " ")) {
		$script_cmd = addcslashes($script_command, " ");
	    } else {
		$script_cmd = $script_command;
	    }
	    $script_path        = explode("/",$script_cmd);
            $script_name        = $script_path[sizeof($script_path)-1];
	    if(strpos($exec_command,"/")) {
		$exec_script 	= explode("/",$exec_command);
		$exec_script 	= $exec_script[sizeof($exec_script)-1];
	    } else {
		$exec_script	= $exec_command;
	    }
	    if($cron_type != 'url') {
	    	//$script_cmd = "/var/sentora/hostdata/".$currentuser['username']."/public_html/".$script_cmd;
	    	$script_cmd = $vhost_path.$currentuser['username']."/".$script_cmd;
	    } else {
		$script_cmd = "'".$script_cmd."'";
	    }
	
	    if($log_command) { 
		if(strpos($log_command, " ")) {
                	$log_cmd = addcslashes($log_command, " ");
            	} else {
                	$log_cmd = $log_command;
            	}
	    }
	    //$log_command = $log_cmd ? "/var/sentora/hostdata/".$currentuser['username']."/public_html/".$log_cmd : "";
	    $log_command = $log_cmd ? $vhost_path.$currentuser['username']."/".$log_cmd : "";

	    $whereis_execscript	= trim(shell_exec('whereis '.$exec_script.' | awk \'{print $2}\''));
	    if($whereis_execscript) {
		if($log_command || $log_command !="") {	
			//$script_to_exec = $whereis_execscript." ".$script_command." >> " .$log_command;
			$script_to_exec = $whereis_execscript." ".$script_cmd." >> " .$log_command;
		} else {
			//$script_to_exec = $whereis_execscript." ".$script_command;
			$script_to_exec = $whereis_execscript." ".$script_cmd;
                }
	    } else {
		self::$execscript = TRUE;
		return FALSE;	
	    }			
	    $description = $currentuser['username']."/".$script_command;

	    $sql = $zdbh->prepare("INSERT INTO x_cronjobs (ct_acc_fk, ct_script_vc, ct_timing_vc, ct_fullpath_vc, ct_description_tx, ct_created_ts) VALUES (:userid, :script, :timing, :fullpath, :description, " . time() . ")");
            $sql->bindParam(':userid', $controller->GetControllerRequest('FORM', 'inUserID'));
            $sql->bindParam(':script', $whereis_execscript);
            $sql->bindParam(':timing', $common_timing);
            $sql->bindParam(':fullpath', $script_cmd);
            $sql->bindParam(':description', $log_command);
            $sql->execute();
            self::WriteCronFile();
            self::$ok = TRUE;
            return;    
      	}
        self::$error = TRUE;
        return;
    }

    static function doDeleteCron()
    {
        global $zdbh;
        global $controller;
	$cron_id = $controller->GetControllerRequest('FORM', 'inDelete');
        runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
	$sql = $zdbh->prepare("UPDATE x_cronjobs SET ct_deleted_ts=:time WHERE ct_id_pk=:cronid");
	$sql->bindParam(':cronid', $cron_id);
	$sql->bindParam(':time', time());
	$sql->execute();
	self::WriteCronFile();
	self::$ok = TRUE;
	return;
    }

    static function CheckCronForErrors()
    {
        global $zdbh;
        global $controller;
        $retval = FALSE;
	
	$cron_type = $controller->GetControllerRequest('FORM', 'crontype');
	$vhost_path = ctrl_options::GetSystemOption('hosted_dir');
	if ($cron_type != "url") {
		//Try to create the cron file if it doesnt exist...
		if (!file_exists(ctrl_options::GetSystemOption('cron_file'))) {
		    fs_filehandler::UpdateFile(ctrl_options::GetSystemOption('cron_file'), 0644, "");
		}
		$currentuser = ctrl_users::GetUserDetail();
		$script_command = $controller->GetControllerRequest('FORM', 'script_command');
		//$script_command = "/var/sentora/hostdata/".$currentuser['username']."/public_html/".$script_command;
		$script_command = $vhost_path.$currentuser['username']."/".$script_command;
		if(strpos(" ",$script_command)) {
			$script_command = addcslashes($script_command, " ");
		}
		// Check to make sure the cron is not blank before we go any further...
		if ($script_command == '') {
		    self::$blank = TRUE;
		    $retval = TRUE;
		}
		// Check to make sure the cron script exists before we go any further...
		if (!is_file(fs_director::RemoveDoubleSlash($script_command))) {
		    self::$noexists = TRUE;
		    $retval = TRUE;
		}
		if(is_dir(fs_director::RemoveDoubleSlash($script_command)))
		{
			self::$commad_dir_err= TRUE;
			$retval=TRUE; 

		}
		// Check to see if creating system cron file was successful...
		if (!is_file(ctrl_options::GetSystemOption('cron_file'))) {
		    self::$cronnoexists = TRUE;
		    $retval = TRUE;
		}
		// Check to makesystem cron file is writable...
		if (!is_writable(ctrl_options::GetSystemOption('cron_file'))) {
		    self::$cronnowrite = TRUE;
		    $retval = TRUE;
		}
		// Check to make sure the cron is not a duplicate...
		$sql = "SELECT COUNT(*) FROM x_cronjobs WHERE ct_acc_fk=:userid AND ct_script_vc=:inScript AND ct_deleted_ts IS NULL";
		$numrows = $zdbh->prepare($sql);
		$numrows->bindParam(':userid', $currentuser['userid']);
		$numrows->bindParam(':inScript', $script_command);
		//$numrows->bindParam(':inScript', $controller->GetControllerRequest('FORM', 'inScript'));
		if ($numrows->execute()) {
		    if ($numrows->fetchColumn() <> 0) {
			self::$alreadyexists = TRUE;
			$retval = TRUE;
		    }
		}
	} else {
		$retval = FALSE;
	}
        return $retval;
    }

    static function WriteCronFile()
    {
        global $zdbh;
        $currentuser = ctrl_users::GetUserDetail();
        $line = "";

	/*$cronemailsql = $zdbh->prepare("SELECT * FROM x_cronemail WHERE ce_acc_fk=:userid AND ce_deleted_ts IS NULL");
        $cronemailsql->bindParam(':userid', $currentuser['userid']);
        $cronemailsql->execute();
        $cronemailres = $cronemailsql->fetch();
        /*if ($result) {
		foreach($result as $res) {
			$line .= 'MAILTO='.$res['ce_email_vc']. fs_filehandler::NewLine();
		}
	}*/
	$line .= 'MAILTO=""'. fs_filehandler::NewLine();
        $sql = "SELECT * FROM x_cronjobs WHERE ct_deleted_ts IS NULL";
        $numrows = $zdbh->query($sql);

        //common header whatever there are some cron task or not
        if (sys_versions::ShowOSPlatformVersion() != "Windows") {
            $line .= 'SHELL=/bin/bash' . fs_filehandler::NewLine();
            $line .= 'PATH=/sbin:/bin:/usr/sbin:/usr/bin' . fs_filehandler::NewLine();
            $line .= 'HOME=/' . fs_filehandler::NewLine();
            $line .= fs_filehandler::NewLine();
        }
       // $restrictinfos = ctrl_options::GetSystemOption('php_exer') . " -d suhosin.executor.func.blacklist=\"passthru, show_source, shell_exec, system, pcntl_exec, popen, pclose, proc_open, proc_nice, proc_terminate, proc_get_status, proc_close, leak, apache_child_terminate, posix_kill, posix_mkfifo, posix_setpgid, posix_setsid, posix_setuid, escapeshellcmd, escapeshellarg, exec\" -d open_basedir=\"" . ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username'] . "/" . ctrl_options::GetSystemOption('openbase_seperator') . ctrl_options::GetSystemOption('openbase_temp') . "\" ";
	$restrictinfos = ctrl_options::GetSystemOption('php_exer') . " -d open_basedir=\"" . ctrl_options::GetSystemOption('hosted_dir') . $currentuser['username'] . "/" . ctrl_options::GetSystemOption('openbase_seperator') . ctrl_options::GetSystemOption('openbase_temp') . "\" ";

        $line .= "#################################################################################" . fs_filehandler::NewLine();
        $line .= "# CRONTAB FOR SENTORA CRON MANAGER MODULE                                        " . fs_filehandler::NewLine();
        $line .= "# Module Developed by Bobby Allen, 17/12/2009                                    " . fs_filehandler::NewLine();
        $line .= "# File automatically generated by Sentora " . sys_versions::ShowSentoraVersion() . fs_filehandler::NewLine();
        if (sys_versions::ShowOSPlatformVersion() == "Windows") {
            $line .= "# Cron Debug infomation can be found in file C:\WINDOWS\System32\crontab.txt " . fs_filehandler::NewLine();
            $line .= "#################################################################################" . fs_filehandler::NewLine();
            $line .= "" . ctrl_options::GetSystemOption('daemon_timing') . " " . $restrictinfos . ctrl_options::GetSystemOption('daemon_exer') . fs_filehandler::NewLine();
        }
        $line .= "#################################################################################" . fs_filehandler::NewLine();
        $line .= "# NEVER MANUALLY REMOVE OR EDIT ANY OF THE CRON ENTRIES FROM THIS FILE,          " . fs_filehandler::NewLine();
        $line .= "#  -> USE SENTORA INSTEAD! (Menu -> Advanced -> Cron Manager)                    " . fs_filehandler::NewLine();
        $line .= "#################################################################################" . fs_filehandler::NewLine();


        //Write command lines in crontab, if any
        if ($numrows->fetchColumn() <> 0) {
            $sql = $zdbh->prepare($sql);
            $sql->execute();
            while ($rowcron = $sql->fetch()) {
                //$fetchRows = $zdbh->prepare("SELECT * FROM x_accounts WHERE ac_id_pk=:userid AND ac_deleted_ts IS NULL");

                $fetchRows = $zdbh->prepare("SELECT A.*, B.ce_acc_fk, B.ce_email_vc FROM x_accounts as A LEFT JOIN x_cronemail as B ON (A.ac_id_pk = B.ce_acc_fk AND B.ce_deleted_ts IS NULL  ) WHERE A.ac_id_pk=:userid AND A.ac_deleted_ts is NULL");
                $fetchRows->bindParam(':userid', $rowcron['ct_acc_fk']);
                $fetchRows->execute();
                $rowclient = $fetchRows->fetch();
                if ($rowclient && $rowclient['ac_enabled_in'] <> 0) {
                    $line .= "# CRON ID: " . $rowcron['ct_id_pk'] . fs_filehandler::NewLine();
		    $log_command = trim($rowcron['ct_description_tx']);
		    $cron_email  = trim($rowclient['ce_email_vc']);

		    $cron_email  = $cron_email ? " | mail -s 'HRPanel - Cron Update' ".$rowclient['ce_email_vc'] : "";
		    if($log_command || $log_command !="") {
			$cron_email  = $cron_email ? " 2>&1 | tee ".$rowcron['ct_description_tx']." | mail -s 'HRPanel - Cron Update' ".$rowclient['ce_email_vc'] : " >> ".$rowcron['ct_description_tx'];
			//$line .= $rowcron['ct_timing_vc'] ." ". $rowcron['ct_script_vc']." ". $rowcron['ct_fullpath_vc'] ." 2>&1 | tee ".$rowcron['ct_description_tx']." | mail -s 'HRPanel - Cron Update' ".$rowclient['ce_email_vc']." ". fs_filehandler::NewLine();
			$line .= $rowcron['ct_timing_vc'] ." ". $rowcron['ct_script_vc']." ". $rowcron['ct_fullpath_vc']."".$cron_email." ". fs_filehandler::NewLine();
		    } else {
			$cron_email  = $cron_email ? " 2>&1 | mail -s 'HRPanel - Cron Update' ".$rowclient['ce_email_vc'] : "";
			//$line .= $rowcron['ct_timing_vc'] ." ". $rowcron['ct_script_vc']." ". $rowcron['ct_fullpath_vc'] ." 2>&1 | mail -s 'HRPanel - Cron Update' ".$cronemailres['ce_email_vc']." ". fs_filehandler::NewLine();
			$line .= $rowcron['ct_timing_vc'] ." ". $rowcron['ct_script_vc']." ". $rowcron['ct_fullpath_vc'] ." ".$cron_email." ". fs_filehandler::NewLine();
		    }
                    //$line .= $rowcron['ct_timing_vc'] . " " . $restrictinfos . $rowcron['ct_fullpath_vc'] . fs_filehandler::NewLine();
                    $line .= "# END CRON ID: " . $rowcron['ct_id_pk'] . fs_filehandler::NewLine();
                }
            }
        }
	//$cron_file_path = "/var/spool/cron/".$currentuser['username'];
	//fs_director::SetFileSystemPermissions(ctrl_options::GetSystemOption('cron_file'), 0777);
	//self::commandcreation("command CronPermissionChange ".$cron_file_path);
        //if (fs_filehandler::UpdateFile($cron_file_path, 0777, $line)) {	
	if (fs_filehandler::UpdateFile(ctrl_options::GetSystemOption('cron_file'), 0644, $line)) {
            if (sys_versions::ShowOSPlatformVersion() != "Windows") {
                $returnValue = ctrl_system::systemCommand(
                                   ctrl_options::GetSystemOption('zsudo'), array(
                                      ctrl_options::GetSystemOption('cron_reload_command'),
                                      ctrl_options::GetSystemOption('cron_reload_flag'),
                                      ctrl_options::GetSystemOption('cron_reload_user'),
                                      ctrl_options::GetSystemOption('cron_reload_path'),
                                   )
                               );
		/*self::commandcreation("command ownershipChange ".$cron_file_path." ".$currentuser['username']);
		
		$sh_path = trim(shell_exec("whereis sh | awk '{print $2}'"));
		$sh_cmd  = $sh_path." /scripts/OwnerChange.sh ".$cron_file_path." ".$currentuser['username'];
		//echo $sh_cmd;exit;
            	$cmnd_exe_dkim = shell_exec($sh_cmd);*/
            }
            return true;
        } else {
            return false;
        }
    }
    static function commandcreation($in)
    {
	$service_port = 4444;
	$address = gethostbyname('localhost');
	$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	if ($socket === false) {
		self::$error= TRUE;
		return FALSE;
	} 
	$result = socket_connect($socket, $address, $service_port);
	if ($result === false) {
		self::$error= TRUE;
		return FALSE;
	} 
	socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 2000, "usec" =>0));
	$out = '';
	socket_write($socket, $in, strlen($in));
	socket_close($socket);
	sleep(1);
    }
    
    static function doEditCron()
    {
        global $controller;
        runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
	foreach($formvars as $key => $value) {
		if (strpos($key,'Delete')) {
			$delete_id = explode("_",$key);
			$delete_id = $delete_id[1];
			header("location: ./?module=" . $controller->GetCurrentModule() . '&show=Delete&other=' . $delete_id);
            		exit;
		} else if (strpos($key,'Edit')) {
			$edit_id = explode("_",$key);
                        $edit_id = $edit_id[1];
                        header("location: ./?module=" . $controller->GetCurrentModule() . '&show=Edit&other=' . $edit_id);
                        exit; 
		} else {}
	}
        return true;
    }
	
    static function getisDeleteCron()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        return (isset($urlvars['show'])) && ($urlvars['show'] == "Delete");
    }

    static function getisEditCron()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        return (isset($urlvars['show'])) && ($urlvars['show'] == "Edit");
    }

    static function getEditCurrentCron()
    {
        global $controller;
        if ($controller->GetControllerRequest('URL', 'other')) {
            $current = self::ListCurrentCron($controller->GetControllerRequest('URL', 'other'));
            return $current[0]['id'];
        } else {
            return '';
        }
    }

    static function ListCurrentCron($cronid)
    {
        global $zdbh;
        global $controller;        
        $sql = "SELECT * FROM x_cronjobs WHERE ct_id_pk=:cronid AND ct_deleted_ts IS NULL";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':cronid', $cronid);
        $numrows->execute();
	if ($numrows->rowCount()) {
            $res = array();
            while ($row = $numrows->fetch()) {
                $res[] = array( 'cron_script' => $row['ct_script_vc'],
				'cron_file' => $row['ct_fullpath_vc'],
				'cron_timing' => $row['ct_timing_vc'],
				'cron_desc' => $row['ct_description_tx'],
                                'id' => $row['ct_id_pk']);
            }
            return $res;
        } else {
            return false;
        }
    }

    static function TranslateTiming($timing)
    {
        $timing = trim($timing);
        $retval = NULL;
        if ($timing == "* * * * *") {
            $retval = "Every 1 minute";
        }
        if ($timing == "0,5,10,15,20,25,30,35,40,45,50,55 * * * *") {
            $retval = "Every 5 minutes";
        }
        if ($timing == "0,10,20,30,40,50 * * * *") {
            $retval = "Every 10 minutes";
        }
        if ($timing == "0,30 * * * *") {
            $retval = "Every 30 minutes";
        }
        if ($timing == "0 * * * *") {
            $retval = "Every 1 hour";
        }
        if ($timing == "0 0,2,4,6,8,10,12,14,16,18,20,22 * * *") {
            $retval = "Every 2 hours";
        }
        if ($timing == "0 0,8,16 * * *") {
            $retval = "Every 8 hours";
        }
        if ($timing == "0 0,12 * * *") {
            $retval = "Every 12 hours";
        }
        if ($timing == "0 0 * * *") {
            $retval = "Every day";
        }
        if ($timing == "0 0 * * 0") {
            $retval = "Every week";
        }
        if ($timing == "0 0 1 * *") {
            $retval = "Every month";
        }
        return $retval;
    }

    static function getResult()
    {
        if (!fs_director::CheckForEmptyValue(self::$blank)) {
            return ui_sysmessage::shout(ui_language::translate("<strong>Error:</strong> You need to specify a valid location for your script."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$commad_dir_err)) {
            return ui_sysmessage::shout(ui_language::translate("<strong>Error:</strong>You have tried to update a cron for folder. Kindly update the cron for file."), "zannounceerror");
        }
        
        if (!fs_director::CheckForEmptyValue(self::$noexists)) {
            return ui_sysmessage::shout(ui_language::translate("<strong>Error:</strong> Your script does not appear to exist at that location."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$cronnoexists)) {
            return ui_sysmessage::shout(ui_language::translate("<strong>Error:</strong> System Cron file could not be created."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$cronnowrite)) {
            return ui_sysmessage::shout(ui_language::translate("<strong>Error:</strong> Could not write to the System Cron file."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$alreadyexists)) {
            return ui_sysmessage::shout(ui_language::translate("<strong>Error:</strong> You can not add the same cron task more than once."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$error)) {
            return ui_sysmessage::shout(ui_language::translate("<strong>Error:</strong> Please try again Later. Server service not available."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$ok)) {
            return ui_sysmessage::shout(ui_language::translate("<strong>Success:</strong> Cron updated successfully."), "zannounceok");
        }
	if (!fs_director::CheckForEmptyValue(self::$execscript)) {
            return ui_sysmessage::shout(ui_language::translate("<strong>Error:</strong> You need to specify a valid execution script."), "zannounceerror");
        }
	if (!fs_director::CheckForEmptyValue(self::$createEmail)) {
            return ui_sysmessage::shout(ui_language::translate("<strong>Success:</strong> Cron email has been added successfully."), "zannounceok");
        }
	if (!fs_director::CheckForEmptyValue(self::$createEmailFail)) {
            return ui_sysmessage::shout(ui_language::translate("<strong>Error:</strong> There is having some problem with adding cron email. Please try again later or contact your system administrator"), "zannounceerror");
        }
	if (!fs_director::CheckForEmptyValue(self::$deleteCronEmail)) {
            return ui_sysmessage::shout(ui_language::translate("<strong>Success:</strong> Cron email has been deleted successfully."), "zannounceok");
        }
        if (!fs_director::CheckForEmptyValue(self::$deleteCronEmailFail)) {
            return ui_sysmessage::shout(ui_language::translate("<strong>Error:</strong> There is having some problem with deleting cron email. Please try again later or contact your system administrator"), "zannounceerror");
        }
        return;
    }

}