<?
  //extract the correct parameter value. Convert entity id to entity name...
  function prepareMacro($macro,$parameter) {
    global $db,$ivrPrefix;
    
    $qry="SELECT * FROM cw_macro WHERE id=$macro";
    $resM=$db->Execute($qry);
    $arrM=$resM->FetchRow();
    $macroName=$arrM["name"];

    //extract the parameters
    $params=xml2array($arrM["parameter"]);
      
    $pArr=split("\|",$parameter);
    if (is_array($pArr))
    foreach ($pArr as $v) {
      $keyvalue=split("=",$v);
      $selParamsArr[$keyvalue[0]]=$keyvalue[1];
    } 
    
    $arg="";
    if (is_array($params))
    foreach($params as $p) {
      if ($p["name"]!="param") continue;
      $pName=$p["attributes"]["name"];
      $pType=$p["attributes"]["type"];
      switch ($pType) {
        case "QUEUE":
          $r=$db->Execute("SELECT * FROM cw_queue WHERE id=".$selParamsArr[$pName]);
          $q=$r->FetchRow();
          $arg.="|\"".$q["name"]."\"";
        break;
        case "GROUP":
          $resG=$db->Execute("SELECT * FROM cw_group_entity WHERE group_id=".$selParamsArr[$pName]);
          while ($arrG=$resG->FetchRow()) {
            $r=$db->Execute("SELECT * FROM `cw_channel` WHERE `key`=".$arrG["entity_id"]);
            $a=$r->FetchRow();
            $grp.=$a["name"]."&";
          }
          $grp=substr($grp,0,-1);
          $arg.="|".$grp;
        break;
        case "EXTENSION":
          $r=$db->Execute("SELECT * FROM `cw_channel` WHERE `key`=".$selParamsArr[$pName]);
          $a=$r->FetchRow();
          $arg.="|".$a["name"];
        break;
        case "IVR":
          $context=$ivrPrefix.$selParamsArr[$pName];
          $arg.="|".$context;
        break;
        case "EMAIL_EXTENSION":
        break;
        case "OUTGOING_RULE":
        case "TEXTFIELD":
          $arg.="|\"".varEval($selParamsArr[$pName])."\"";
        break;
      }
    }
      
    return array($macroName,$arg);      
  }
  
  //search for some variable and evaluate it
  function varEval($txt) {
    global $agi;
    if (substr(trim($txt),0,2)=="\${") {
      $ret=$agi->get_variable(substr(trim($txt),2,-1));
      $txt=$ret["data"];
    }
    return $txt;
  }

  function _getGroup($entity_id) {
    global $db;
    if ($entity_id=="") return 0;
    $qry="SELECT * FROM cw_group_entity WHERE entity_id=$entity_id";
    $res=$db->Execute($qry);
    while ($arr=$res->FetchRow()) $ret[]=$arr["group_id"];
    return $ret;
  }

  function _getTrunk($r) {
    global $db;
    $arr=split("\|",$r);
    if (is_array($arr)) 
    foreach ($arr as $t) {
      $qry="SELECT * FROM cw_channel WHERE id=$t";
      $res=$db->Execute($qry);
      $arr=$res->FetchRow();
      $ret.=$arr["name"]."&";
    }
    $ret=substr($ret,0,-1);
    return $ret;
  }

  function _extractTech($entity_id) {
    global $db;
    $qry="SELECT * FROM cw_entity WHERE id=$entity_id";
    $res=$db->Execute($qry);
    $arr=$res->FetchRow();
    $type=$arr["type"];
    switch ($type) {
      case EXTENSION:
        $qry="SELECT t.name as techName FROM cw_client c INNER JOIN cw_technology t ON c.technology=t.id WHERE c.id=$entity_id";
        $resTech=$db->Execute($qry);
        $clientArr=$resTech->FetchRow();
        $techName=$clientArr["techName"];
        $ret=$techName;
        break;
/*
      case TRUNK: 
        $qry="SELECT * FROM cw_trunk WHERE id=$entity_id";
        $res=$db->Execute($qry);
        $arr=$res->FetchRow();
        $ret=$arr["name"];
        break;       
*/
    }
    return $ret;
  }
  
  function checkTime($ts=0) {
    global $db;
    
    if ($ts==0) {
      return true;
    }      
    
    //check the time segment
    $qry="SELECT * FROM cw_time_segment WHERE id=$ts";
    $res=$db->Execute($qry);
    $arrTs=$res->FetchRow();

    $id=$arrTs["id"];
    $name=$arrTs["name"];
    $date_from=$arrTs["date_from"];
    $date_to=$arrTs["date_to"];
    $hour_from=$arrTs["hour_from"];
    $hour_to=$arrTs["hour_to"];
    $week_day=$arrTs["week_day"];
    $day=$arrTs["day"];
    $month=$arrTs["month"];  
    
    if ($date_from != "") $qry=$qry." AND NOW()>=date_from";

    if ($date_to != "") $qry=$qry." AND NOW()<=date_to";

    if ($hour_from != "") {
      $qryTmp="";
      $hour_fromArr=split("\|",$hour_from);
      $hour_toArr=split("\|",$hour_to);
      foreach ($hour_fromArr as $i=>$h) {
        if ($h=="") continue;
        $h=extractTime($h);
        $h2=extractTime($hour_toArr[$i]);
        $qryTmp=$qryTmp." OR (TIME(NOW())>=$h AND TIME(NOW())<=$h2) ";
      }
      $qry.=" AND (".substr($qryTmp,3).")";
    }


    if ($week_day != "") {
      $qryTmp="";
      $week_dayArr=split("\|",$week_day);
      foreach ($week_dayArr as $w) {
        $qryTmp.=" OR DAYOFWEEK(NOW())='$w'";
      }
      $qry.=" AND (".substr($qryTmp,3).")";
    }

    if ($day != "") {
      $qryTmp="";
      $dayArr=split("\|",$day);
      foreach ($dayArr as $d) {
        $qryTmp.=" OR DAYOFMONTH(NOW())='$d'";
      }
      $qry.=" AND (".substr($qryTmp,3).")";
    } 

    if ($month != "") {
      $qryTmp="";
      $monthArr=split("\|",$month);
      foreach ($monthArr as $m) {
        $qryTmp.=" OR MONTH(NOW())='$m'";
      }    
      $qry.=" AND (".substr($qryTmp,3).")";
    } 

    $res=$db->Execute($qry);
    if ($res->RecordCount()==0) {
      error_log("  TimeSegment return false");
      return false;
    } else {
      error_log("  TimeSegment return true");
      return true;
    }
  }

  if (!function_exists("errArr")) {
  function errArr($arr) {
    if (count($arr)==0) error_log("[No item in this array]");
    else {
      ob_start();
        print_r($arr);
      $contents=ob_get_contents();
      ob_end_clean();
      error_log($contents);     
    }
    unset($arr);
    return;
  }
  }
  
  if (!function_exists("xml2array")) {
  function xml2array ($xml)
  {
     $xmlary = array ();
  
     if ((strlen ($xml) < 256) && is_file ($xml))
       $xml = file_get_contents ($xml);
    
     $ReElements = '/<(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*?)<(\/\s*\1\s*)>)/s';
     $ReAttributes = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/';
    
     preg_match_all ($ReElements, $xml, $elements);
     foreach ($elements[1] as $ie => $xx) {
     $xmlary[$ie]["name"] = $elements[1][$ie];
       if ( $attributes = trim($elements[2][$ie])) {
           preg_match_all ($ReAttributes, $attributes, $att);
           foreach ($att[1] as $ia => $xx)
             // all the attributes for current element are added here
             $xmlary[$ie]["attributes"][$att[1][$ia]] = $att[2][$ia];
       } // if $attributes
       
       // get text if it's combined with sub elements
     $cdend = strpos($elements[3][$ie],"<");
     if ($cdend > 0) {
             $xmlary[$ie]["text"] = substr($elements[3][$ie],0,$cdend -1);
         } // if cdend
         
       if (preg_match ($ReElements, $elements[3][$ie])){        
           $xmlary[$ie]["elements"] = xml2array ($elements[3][$ie]);
           }
       else if (isset($elements[3][$ie])){
           $xmlary[$ie]["text"] = $elements[3][$ie];
           }
       $xmlary[$ie]["closetag"] = $elements[4][$ie];
     }//foreach ?
     return $xmlary;
  } 
  }
    
function extractTime($t) {
  $t=str_replace(",",":",$t);
  $t=str_replace(".",":",$t);
  
  $arr=split(":",$t);
  for ($i=0; $i<3; $i++) {
    if (isset($arr[$i])) $arg.=$arr[$i].",";
    else $arg.="0,";
  }
  $ret="MAKETIME(".substr($arg,0,-1).")";
  return $ret;  
}  
  
?>
