<?php if (!defined('HTTP_SERVER')) die('You can not access this file directly!');
/**
  @licence GPL 2005-2011  The osCSS developers - osCSS Open Source E-commerce
  @portion code Copyright (c) 2002 osCommerce
  @package osCSS-2 <www http://www.oscss.org>
  @version 2.1.0
  @date  22/03/11, 21:28
  @author oscim <mail aurelien@oscim.fr> <www http://www.oscim.fr>
  @encode UTF-8
  @class cronjob
*/

class cronjob
  implements ExtModPage, InterfacedTJsonS, InterfaceModule {

  const FILENAME =FILENAME_CRONJOB;

  const DIR_MODULE = 'cronjob/';

  public static $code;

  public static $action;

  public static $list=array();
  /**
    @var interval repeat
  */
  public static $interval=array();
  /**
    @var object load base info db cron
  */
  public static $cInfo;
  /**
    @var object module child , type cronjob
  */
  public static $CronMod;
  /**
    @var int count require module config tabs, just for module cronjob config
  */
  public static $ConfigCount;
  /**
    @var object convert array config module child cronjob , a object
  */
  public static $mInfo;


  /**
    class constructor
  */
  public function __construct() {
    self::$code=__CLASS__;

    //! active datatable in ajax, precise les GET necessaire
    define('JSONSTATMENT', 'mod=page&type='.self::$code.(isset($_GET['cID'])?'&cID='.$_GET['cID'] : '' ) );

    self::$interval[]=array('id'=>1, 'text'=>__('text 1 min'));
    self::$interval[]=array('id'=>5, 'text'=>__('text 5 min'));
    self::$interval[]=array('id'=>15, 'text'=>__('text 15 min'));
    self::$interval[]=array('id'=>30, 'text'=>__('text 30 min'));
    self::$interval[]=array('id'=>60, 'text'=>__('text 1 h'));
    self::$interval[]=array('id'=>120, 'text'=>__('text 2 h'));
    self::$interval[]=array('id'=>240, 'text'=>__('text 4 h'));
    self::$interval[]=array('id'=>480, 'text'=>__('text 8 h'));
    self::$interval[]=array('id'=>720, 'text'=>__('text 12 h'));
    self::$interval[]=array('id'=>1440, 'text'=>__('text 1 jour'));
    self::$interval[]=array('id'=>2880, 'text'=>__('text 2 jour'));
    self::$interval[]=array('id'=>4320, 'text'=>__('text 3 jour'));
    self::$interval[]=array('id'=>10080, 'text'=>__('text 1 semaine'));
    self::$interval[]=array('id'=>20160, 'text'=>__('text 2 semaine'));
    self::$interval[]=array('id'=>43646, 'text'=>__('text 1 mois'));
  }

  public function check_action($actions){
    global $messageStack;

    self::$action=$actions;

    $DB=Database::getInstance();

    switch (self::$action) {
      case 'setflag':
	if ( ($_GET['flag'] == '0') || ($_GET['flag'] == '1') ) {
	  $_id = tep_db_prepare_input($_GET['cID']);

	  if (!empty($_id))
	    $DB->query("update " . TABLE_CRONJOB . " set status = '" .(int) $_GET['flag'] . "' where id = '" . (int)$_id . "'");
	}

	tep_redirect(tep_href_link(self::FILENAME, 'cID=' . $_id));
      break;
      case 'deleteconfirm':
	$id=(int) $_GET['cID'];
	$DB->query("DELETE FROM ".TABLE_CRONJOB." WHERE id='".(int)$id."'");
	tep_redirect(tep_href_link(self::FILENAME));
      break;
      case 'insert':
	$name=substr(tep_db_prepare_input($_POST['name']),0,-4);
	$scriptpath=DIR_WS_MODULES.self::DIR_MODULE.$name;
	$time_interval=(int)tep_db_prepare_input($_POST['time_interval']);
	$fire_time=tep_date_raw(tep_db_prepare_input($_POST['fire_time'])).' '.tep_db_prepare_input($_POST['fire_time_begin_hour']).':00';
	$run_only_once=tep_db_prepare_input($_POST['run_only_once']);


	$mod=self::loadCronMod($name);
	if(self::$CronMod->config)
	  $string=$mod->insert($_POST['configuration']);

	$query="INSERT INTO ".TABLE_CRONJOB." (id,scriptpath, name, time_interval, fire_time, time_last_fired,run_only_once, status,extra) VALUES ('','$scriptpath','$name','$time_interval','$fire_time','0','$run_only_once',0,'".$string."' )";
	$res=$DB->query($query);
	$id= tep_db_insert_id($res);
	tep_redirect(tep_href_link(self::FILENAME,'action=edit&cID=' . $id ));
      break;
      case 'update':
	$id=(int) $_GET['cID'];
	$name=substr(tep_db_prepare_input($_POST['name']),0,-4);
	$scriptpath=DIR_WS_MODULES.self::DIR_MODULE.$name;
	$time_interval=(int)tep_db_prepare_input($_POST['time_interval']);
	$fire_time=tep_date_raw(tep_db_prepare_input($_POST['fire_time'])).' '.tep_db_prepare_input($_POST['fire_time_begin_hour']).':00';
	$run_only_once=tep_db_prepare_input($_POST['run_only_once']);

	$mod=self::loadCronMod($name);
	if(self::$CronMod->config)
	  $string=$mod->update($_POST['configuration']);


	$query="UPDATE ".TABLE_CRONJOB." SET name='$name', scriptpath='$scriptpath', time_interval='$time_interval', fire_time='$fire_time', run_only_once='$run_only_once', extra='".$string."'  WHERE id='$id'";

	$DB->query($query);
	tep_redirect(tep_href_link(self::FILENAME, 'cID=' . $id));
      break;
      case 'edit':
	require_once(DIR_WS_FUNCTIONS.'lib.configuration.php');
      break;
      case 'new':

	self::$cInfo=new objectInfo(array('id'=>'',
					  'scriptpath'=>'',
					  'name'=>'',
					  'time_interval'=>'',
					  'fire_time'=>'',
					  'time_last_fired'=>'',
					  'run_only_once'=>'',
					  'status'=>''
						) );
      break;
    }

    return self::$action;
  }


/**
  @fn loadCronMod($name)
  @brief load module cron for insert/update/edit specific Interface IntModCronJob
  @param $name le nom du module
  @return object  module file loaded
*/
  static public function loadCronMod($name){
//     if(is_object(self::$CronMod)) return self::$CronMod;
    $name=(string)$name;
    if(!class_exists($name))
      include_once(DIR_WS_MODULES.self::DIR_MODULE.(string)$name.'.php');
    return self::$CronMod = new $name ;
  }

  static public function loadCronModConfig(){
    $extra=self::$cInfo->extra;

    if(self::$CronMod->config) {
      $module_arrayConfig = self::$CronMod->Config($extra);
      self::$mInfo = new objectInfo($module_arrayConfig);
      self::$ConfigCount = count($module_arrayConfig);
    }
    else {
      self::$mInfo = new objectInfo(array());
      self::$ConfigCount = 0;
    }
  }

/**
  @param $name string
  @param $extra value string
*/
  static public function HelpCronMod(){
    if( ($help=self::$CronMod->help()) !=false) return $help;
  }

/**
  @param $name string
  @param $extra value string
  @param
*/
  static public function EditCronMod($tabs=0){
    $keys='';
    // just for call methode  by configuration module
    $Module=self::$CronMod;

    $mod=self::$mInfo->$tabs;

    return configUtility::FormatEditAuto($mod);
  }



  public function get_header(){
    global $languages_selected, $current_theme;

    tep_include_file ("includes/template/". $current_theme ."/jquery-ui-".$_SESSION['login_groups_id'].".css",true);
    tep_include_file ("includes/javascript/jquery-ui.min.js",true);
    tep_include_file ("includes/javascript/timepicker.js",true);
    if ($languages_selected != 'en') tep_include_file ("includes/javascript/jquery-ui-i18n.min.js",true);

    echo " <script type=\"text/javascript\"><!--
	    $(function() {
	    $.datepicker.setDefaults($.extend({
	      duration: '',
	      changeMonth: true,
	      changeYear: true,
	      showOn: 'button',
	      showTime: true,
	      time24h: true,
	      buttonImage: '".DIR_WS_ICONS . 'calendar.gif'."',
	      buttonImageOnly: true
	    }";
	    if ($languages_selected != 'en') echo ",\n"."$.datepicker.regional['".$languages_selected."']"."\n";
	    echo "));
	    $('#bt_fire_time').datepicker({altField: '#fire_time', altTimeField: '#fire_time_begin_hour'});
	  });
		// -->
	  </script>";
  }


  public static function load_db_values($ID){

    $DB=Database::getInstance();

    $_query_raw = "select * from " . TABLE_CRONJOB . " WHERE id='".$ID."' ";
    $_query = $DB->query($_query_raw);
    $res=$_query->fetchAssoc();
    $res['begin_hour']=substr($res['fire_time'], 11,5) ;

    return new objectInfo( $res );

  }

  public function display_view(){
    switch (self::$action) {
      case 'delete':
	self::$cInfo=self::load_db_values(@$_GET['cID']);
	return tep_get_include_contents(__CLASS__.'.delete');
      break;
      case 'new':
	return tep_get_include_contents(__CLASS__.'.edit');
      break;
      case 'edit':
	self::$cInfo=self::load_db_values(@$_GET['cID']);

	self::loadCronMod(self::$cInfo->name);

	if(self::$CronMod->config) {
	  self::loadCronModConfig();
	}

	return tep_get_include_contents(__CLASS__.'.edit');
      break;
      default:
	self::tep_get_list();
	return tep_get_include_contents(__CLASS__.'.listing');
    }

  }


  /** public static InterfacedTJsonS */

  private static function get_item_action($array){
    return  sprintf(
		  CsrtAction::getFormat('row_action'),
		  '',
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_EDIT, 'edit'), '',  tep_href_link(self::FILENAME,  'cID=' . $array['id']. '&amp;action=edit') ,'' ).
		  sprintf(CsrtAction::getLink('row_action_right', IMAGE_DELETE, 'delete'), 'fancy',  tep_href_link(self::FILENAME,  'cID=' . $array['id'] . '&amp;action=delete') ,'' )
	      );

  }

  private static function get_item_status($array){
    if ($array['status'] == '1')
      return  tep_image(DIR_WS_ICONS . 'icon_status_green.gif', IMAGE_ICON_STATUS_GREEN) . '&nbsp;<a href="' . tep_href_link(self::FILENAME, 'action=setflag&amp;flag=0&amp;cID=' .$array['id']) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_red_light.gif', IMAGE_ICON_STATUS_RED_LIGHT) . '</a>';
    else
      return '<a href="' . tep_href_link(self::FILENAME,  'action=setflag&amp;flag=1&amp;cID=' . $array['id'] ) . '">' . tep_image(DIR_WS_ICONS . 'icon_status_green_light.gif', IMAGE_ICON_STATUS_GREEN_LIGHT) . '</a>&nbsp;' . tep_image(DIR_WS_ICONS . 'icon_status_red.gif', IMAGE_ICON_STATUS_RED);

  }

  /**
    @brief modele for use table listing and rows sort possible
  */
  public static function tep_get_modele(){
    return array( 'id'=>true,
                  'name'=>true,
                  'time_interval'=>true,
                  'fire_time'=>true,
                  'time_last_fired'=>true,
                  'run_only_once'=>true,
		  'status'=>false,
		  'action'=>false
                );
  }

  /**
    @brief construct list array for call by ajax and JSON format
  */
  public static function tep_get_list($page=1,$rowbyp=10,$sOrder='',$sWhere='',$options=''){
    global $query_numrows;

    $DB=Database::getInstance();

    $query_raw = "select * from " . TABLE_CRONJOB . " ".$sWhere." ORDER BY ".((!empty($sOrder)) ? $sOrder : " id ASC ");
    $currency_split = new splitPageResults($page, $rowbyp, $query_raw, $query_numrows);

    $currency_query = $DB->query($query_raw);

    while ($currency = $currency_query->fetchAssoc() ) {
      $currency['status']=self::get_item_status($currency);
      $currency['action']=self::get_item_action($currency);
      $currency['name']=__('module txt name '.$currency['name']) ;
      self::$list[]=$currency;
    }

    $li=$res=array();
    foreach(self::$list as $item){
      foreach(self::tep_get_modele() as $k=>$v) $li[$k]=$item[$k];
      $res[]=$li;
    }

    return $res;
  }


  static public function list_of_module(){
    $sor= array();

    foreach(scan(DIR_WS_MODULES.self::DIR_MODULE) as $module)
      $sor[]=array('id'=>$module, 'text'=>__('module txt name '.substr($module,0, -4)) );

    return $sor;
  }


  /**
    @brief call execution of tache cron shop
  */
  static public function ExeCron(){

    $DB=Database::getInstance();
    $_query_raw = "select * from " . TABLE_CRONJOB . " WHERE  fire_time <= NOW() AND status=1 ";
    $_query = $DB->query($_query_raw);

    while($cron_module = $_query->fetchAssoc() ){
      self::ExecModCron($cron_module);
    }


  }

  /**
    @brief appel unique pour le chargement et execution du module
    @param $module array detail module
  */
  static public function ExecModCron($module){
    if(!is_array($module)) return false;

    include($module['scriptpath'] .'.php');

    $class =$module['name'];
    $object=new $class();

    var_dump($class);
    flush();

    $object->ClassExec($module['extra']);

    $sql_array['time_last_fired']=date('Y-m-d H:i:s');
    // dessactive
    if((bool)$module['run_only_once']) $sql_array['status']='0';

    // prepare sequence suivante
    if((int)$module['time_interval']>0) $sql_array['fire_time']=date('Y-m-d H:i:s', (date('U') + (int)$module['time_interval'] * 60 ) );
    else $sql_array['status']='0';

    tep_db_perform(TABLE_CRONJOB ,$sql_array ,'update', " id='".(int)$module['id']."' ");

  }



/** Interface module */

  function check() { return false; }
  function install() { return false; }
  function remove() { return false;  }
  function keys() { return false; }
}

?>