Location: PHPKode > projects > OpenBizMap > openbizmap/mydata/script/inc_functions.txt
<?php
/*
OpenDataBag - Data Web Interface
Copyright (C) 2004 Nawara

This program 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 2
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/
define('INFO','2007.46'); //2007-10-09

define('MyURI',($_SERVER['HTTPS']=='on'?'https://':'http://').$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);

define('CRLF', "\r\n");
define('ref_max', 200);
define('odb_mtime',filemtime(cfg_data_path.'/script/inc_functions.txt'));


exec('grep -V 2>&1',$out,$grep_err); //echo implode('<br>',$out); echo $grep_err;
define('cfg_grep_path','grep');
if($grep_err==0)
  define('cfg_grep_available',1);
else
  define('cfg_grep_available',0);

if(isset($_SERVER["HTTPS"]))
  $selflink='https://'.$_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"];
else
  $selflink='http://'.$_SERVER["SERVER_NAME"].$_SERVER["PHP_SELF"];

$content='<script type="text/javascript">'.CRLF;
$content.='/* <![CDATA[ */'.CRLF;
$content.='function check(n,fo,fr,to)';
$content.='{var c=false;for(j=0;j<fo.length;j++){f=fo[j]; for(i=0;i<f.length;i++){if(f[i].id==fr)c=true;if(f[i].id==to)c=false;if(c && f[i].type==\'checkbox\' && f[i].className==\'checkme\')f[i].checked=n;}}}function on(){';

  for($action_count=0;$action_count<6;$action_count++)
    $content.='if(document.getElementById("odb_action'.$action_count.'")!=null)document.forms[1].odb_action'.$action_count.'.disabled=false;';

$content.='document.getElementById("odb_delete_p").style.display="block";document.forms[1].odb_delete.disabled=false;document.forms[1].odb_copy.disabled=false;document.getElementById("odb_compare_p").style.display="block";document.forms[1].odb_compare.disabled=false;}';

$content.='/* ]]> */'.CRLF;
$content.='</script>'.CRLF;
define('ODBJAVASCRIPT',$content);

define('SOURCEMARK','__source__mark__');
define('DATA',0);

define('SOLVE',1);
define('DONTSOLVE',0);

//display modes
define('DISP_SINGLE',0);
define('DISP_FEW',1);
define('DISP_MANY',2);

//record metadata
define('ID',0);
define('BASEID',1);
define('CONFIG',2);
define('CONTENT',3);
define('SORTBY',4);
define('GROUPBY',5);
define('LISTCUTOFF',6);
define('VALID',7);
define('VALIDFROM',8);
define('VALIDTO',9);
define('MODINFO',10);

//field metadata
define('TEMPLATE',0);
define('VALUE',1);
define('FORMULA',2);
define('DICTIONARY',3);
define('SHOW_COND',4);

//dictionary aliases
define('CFG_SEARCH',1);
define('CFG_SHOW',2);
define('CFG_EDIT',3);
define('CFG_SAVE',4);
define('CFG_LOAD',5);
define('CFG_NEW',6);

//display aliases
define('CFG_DETAIL',15);
define('CFG_LIST',16);


$nothing_found=0;

// ----------------- Translations ------------------------

if(!defined('cfg_base_path'))
  define('cfg_base_path', getcwd());
$myecho_path=cfg_base_path.'/myecho';
require_once($myecho_path.'/myecho.php');

// ----------------- Error reporting ------------------------

// error handler function
function errorlog($errno, $errstr, $errfile, $errline)
{
  $content='';
  
  switch ($errno) {
  case E_ERROR:
   $content=CRLF.date('Y.m.d H:i:s').' ERROR ['.$errno.'] '.$errstr.' '.$errfile.' line '.$errline;
   echo "ERROR [$errno] $errstr";
   exit(1);
   break;
  case E_WARNING:
    $content=CRLF.date('Y.m.d H:i:s').' WARNING ['.$errno.'] '.$errstr.' '.$errfile.' line '.$errline;
   break;
  default:
   if($errno!=2048)
    $content=CRLF.date('Y.m.d H:i:s').' NOTICE ['.$errno.'] '.$errstr.' '.$errfile.' line '.$errline;
   break;
  }

  if(strlen($content) and strpos($content,'Undefined offset')==0 and strpos($content,'Undefined index')==0)
  {
    addpath(cfg_data_path.'/temp/errors');
    $fp=fopen(cfg_data_path.'/temp/errors/'.date('Ym').'.log','ab');
    fwrite($fp,$content);
    fclose($fp);
  }
}

set_error_handler("errorlog");

function conv($text,$from,$to='utf-8')
{
  $new_text=$text;
  
  if(strlen($text) and strtolower($from)!='utf-8')
  {
    require_once(cfg_data_path.'/script/conv/convertcharset.class.php');
    
    $NewEncoding = new ConvertCharset;
    $new_text = $NewEncoding->Convert($text, $from, $to, 0);

    if(strlen($new_text)==0)
      $new_text=$text;
  }
  
  return $new_text;
}

// ----------------- Calculations ------------------------

function calculate($formula,$variable_array='',$fn_previous_value='')
{
  global $_charset;
  global $_formula_mask;
  global $bag;


  $formula=trim($formula);
  $formula=str_replace('  ',' ',$formula);
  $formula=str_replace('  ',' ',$formula);
  $formula=str_replace('  ',' ',$formula);
  $formula=str_replace('  ',' ',$formula);

  $bracket_pos=strpos($formula,'(');
  if($bracket_pos<2)
  {
    $formula='=void('.substr($formula,1).')';
    $bracket_pos=strpos($formula,'(');
  }

  $fn_name=substr($formula,1,$bracket_pos-1);
  $comma_pos=strpos($formula,',')-strlen($fn_name)-2;
  if($comma_pos>0)
  {
    $fn_search=substr($formula,strlen($fn_name)+2,$comma_pos);
    $fn_inner=substr($formula,strpos($formula,',')+1,-1);
  }
  else
  {
    $fn_search=substr($formula,strlen($fn_name)+2,-1);
    $fn_inner='';
  }

  if(sizeof($variable_array)>0)
  {
    //$value='sysValidOn:$sysValidFrom '.$fn_search; //20050712 gna strlen...
    $value=$fn_search;

    $pos=strpos('_'.$value,'[');
    while($pos>0)
    {
      $variable=substr($value,$pos,strpos($value.']',']',$pos)-$pos);
      if(strlen($variable_array[$variable]))
      {
        $value=str_replace('['.$variable.']',$variable_array[$variable],$value);
        $pos=strpos('_'.$value,'[');
      }
      else
      {
        $value=str_replace('['.$variable.']','',$value);
        $value=trim(str_replace('  ',' ',$value));
        if($pos+1<strlen('_'.$value))
          $pos=strpos('_'.$value,'[',$pos+1);
        else
          $pos=0;
      }
    }
    $fn_search=$value;
  }

  //echo '<br>'.$fn_name.'():'.$fn_search.':'.$fn_inner;
  if($fn_name=='void')
  {
    $fn_ret=eval_formula($fn_search,$variable_array);
  }
  else
  {
    include(cfg_data_path.'/script/fn_'.$fn_name.'.txt');
  }

  $result_array=array();
  $result_array['result']=$fn_ret;
  $result_array['search']=$fn_search;

  return($result_array);
}

function check_range(&$variable,$value_if_empty=0,$value_min=-9999999,$value_max=-9999999)
{
  $value=str_replace(' ','',$variable);
  $value=str_replace(',','.',$variable);

  if($variable=='')
    $variable=$value_if_empty;
  elseif($value_min!=-9999999 and $value_if_empty>=0 and $value_min==0 and $value<0)
    $variable=-$variable;
  elseif($value_min!=-9999999 and $value_if_empty<0 and $value_min==0 and $value>0)
    $variable=-$variable;
  elseif($value_min!=-9999999 and $value_min!=0 and $value_if_empty<0 and $value<$value_min)
    $variable=$value_min;
  elseif($value_max!=-9999999 and $value>$value_max)
  {
    if($value_max==0)
      $variable=-$variable;
    else
    $variable=$value_max;
  }
}

function datafile_path($file_name) //: file_path
{
  $ext=strtolower(substr($file_name,strrpos($file_name,'.')));
  $name=purename(substr($file_name,0,strrpos($file_name,'.')));
  $preamble=substr(purename($file_name),0,1).'/'.substr(purename($file_name),0,2);
  addpath(cfg_data_path.'/data/files/'.$preamble);

  $tmpcnt=0;
  $filename=$name.$ext;
  while(file_exists(cfg_data_path.'/data/files/'.$preamble.'/'.$filename.'.file'))
  {
    $tmpcnt++;
    $filename=$name.'_'.$tmpcnt.$ext;
  }

  return (cfg_data_path.'/data/files/'.$preamble.'/'.$filename.'.file');
}


function eval_formula($fn_inner,$variable_array) //:$value
{
  global $_charset;
  global $_formula_mask;

  /*
  $trans=array('$'=>' $',
           '('=>' (',
           ')'=>' )',
           '*'=>' *',
           '/'=>' /',
           '+'=>' +',
           '-'=>' -');
  $value=strtr($fn_inner,$trans);
  */

  $value=$fn_inner;
  $variable_array=line2array($variable_array);

  $pos=strpos('_'.$value,'[');
  while($pos>0)
  {
    $variable=substr($value,$pos,strpos($value.']',']',$pos)-$pos);
    if(strlen($variable_array[$variable]))
    {
      $repl_value=$variable_array[$variable];
      $value=str_replace('['.$variable.']',$repl_value,$value);
    }
    else
    {
      $value=str_replace('['.$variable.']','',$value);
      $value=trim(str_replace('  ',' ',$value));
      if($pos+1<strlen('_'.$value))
        $pos=strpos('_'.$value,'[',$pos+1);
      else
        $pos=0;
    }
  }

  //$value=strtr($value,$_charset,$_formula_mask);
  $a='';
  @eval('$a='.$value.';');

  //echo '<pre>'.$value.'</pre><br />_RESULT_('.$a.') _TRANS_('.$value.') _ORIG_('.$fn_inner.')';

  return $a;
}

// ----------------- Basic functions ------------------------

// version check for deamons usage: while(check_version()){}
function check_version() //: none
{
  //~ clearstatcache();
  //~ if(odb_mtime!=filemtime(cfg_data_path.'/script/inc_functions.txt'))
  //~ {
    //~ myecho('ODB version has changed - stopping script');
    //~ die();
  //~ }
  return(1);
}

// init()
function init()
{
  global $_charset;
  global $_search_mask;
  global $_formula_mask;
  global $_charset_mask;
  global $_purename_mask;
  global $_linkname_mask;
  global $time_start;
  global $reference_cache_full;


  $reference_cache_full='';
  $time_start = getmicrotime();

  set_magic_quotes_runtime(0);

  $_charset='';
  $_charset_mask='';
  $_formula_mask='';
  $_purename_mask='';
  $_linkname_mask='';
  for($ii=0;$ii<256;$ii++)
  {
    $_charset.=chr($ii);

    if($ii>47 and $ii<58) //0..9 -> 0..9
      $_linkname_mask.=chr($ii);
    elseif($ii>64 and $ii<91) //A..Z -> a..z
      $_linkname_mask.=chr($ii+32);
    elseif($ii>96 and $ii<123) //a..z -> a..z
      $_linkname_mask.=chr($ii);
    elseif(chr($ii)=='-')
      $_linkname_mask.='-';
    //elseif(chr($ii)=='/')
    //  $_charset_mask.='_';
    //elseif(chr($ii)=='.')
    //  $_charset_mask.='_';
    else  // any -> space
      $_linkname_mask.=' ';
      
    if($ii>47 and $ii<58) //0..9 -> 0..9
      $_charset_mask.=chr($ii);
    elseif($ii>64 and $ii<91) //A..Z -> a..z
      $_charset_mask.=chr($ii+32);
    elseif($ii>96 and $ii<123) //a..z -> a..z
      $_charset_mask.=chr($ii);
    elseif(chr($ii)=='_')
      $_charset_mask.='_';
    //elseif(chr($ii)=='/')
    //  $_charset_mask.='_';
    //elseif(chr($ii)=='.')
    //  $_charset_mask.='_';
    else  // any -> space
      $_charset_mask.=' ';

    if($ii>47 and $ii<58) //0..9 -> 0..9
      $_search_mask.=chr($ii);
    elseif($ii>64 and $ii<91) //A..Z -> a..z
      $_search_mask.=chr($ii+32);
    elseif($ii>96 and $ii<123) //a..z -> a..z
      $_search_mask.=chr($ii);
    elseif(chr($ii)=='_')
      $_search_mask.='_';
    elseif(chr($ii)==':')
      $_search_mask.=':';
    elseif(chr($ii)=='>')
      $_search_mask.='>';
    elseif(chr($ii)=='<')
      $_search_mask.='<';
    elseif(chr($ii)=='-')
      $_search_mask.='-';
    elseif(chr($ii)=='\'')
      $_search_mask.='\'';
    else  // any -> space
      $_search_mask.=' ';

    if($ii>47 and $ii<58) //0..9 -> 0..9
      $_purename_mask.=chr($ii);
    elseif($ii>64 and $ii<91) //A..Z -> a..z
      $_purename_mask.=chr($ii+32);
    elseif($ii>96 and $ii<123) //a..z -> a..z
      $_purename_mask.=chr($ii);
    elseif(chr($ii)=='_')
      $_purename_mask.='_';
    //elseif(chr($ii)=='/')
    //  $_charset_mask.='_';
    //elseif(chr($ii)=='.')
    //  $_charset_mask.='_';
    else  // any -> space
      $_purename_mask.=' ';

    if($ii>47 and $ii<58) //0..9 -> 0..9
      $_formula_mask.=chr($ii);
    elseif(chr($ii)=='*' or chr($ii)=='/' or chr($ii)=='+' or chr($ii)=='-' or chr($ii)=='=' or chr($ii)=='\'') //*+-/ -> *+-/
      $_formula_mask.=chr($ii);
    elseif(chr($ii)=='(' or chr($ii)==')' or chr($ii)=='.') //.() -> .()
      $_formula_mask.=chr($ii);
    elseif(chr($ii)=='<' or chr($ii)=='>') //.() -> .()
      $_formula_mask.=chr($ii);
    else
      $_formula_mask.=' ';
  }
}

// get() reading gpc
function get($variable_name) //:$variable_value
{
  global $session_array;
  global $inner_get_array;
  
  $variable_value='';
  $variable_name='odb_'.$variable_name;

  if($variable_name!='odb_search' and isset($_COOKIE[$variable_name]))
    $variable_value=$_COOKIE[$variable_name];

  if($variable_name!='odb_compare' and isset($session_array[substr($variable_name,4)]))
  {
    $variable_value=$session_array[substr($variable_name,4)];
  }

  if(isset($_GET[$variable_name]))
    $variable_value=$_GET[$variable_name];
  elseif(isset($_GET[substr($variable_name,4)]))
    $variable_value=$_GET[substr($variable_name,4)];

  if(isset($_POST[$variable_name]))
    $variable_value=$_POST[$variable_name];

  if(isset($inner_get_array[$variable_name]))
    $variable_value=replace_const($inner_get_array[$variable_name]);
  elseif(isset($inner_get_array[substr($variable_name,4)]))
    $variable_value=replace_const($inner_get_array[substr($variable_name,4)]);
    
  if(get_magic_quotes_gpc())
    $variable_value=stripcslashes($variable_value);

  if(isset($_FILES[$variable_name]['size']))
  {
    addpath(cfg_data_path.'/upload/');

    $ext=strtolower(substr($_FILES[$variable_name]['name'],-4));
    if(strpos('..txt.xml.pdf.zip.tgz.tar.jpg.gif.png.tif.doc.xls',$ext)==0)
      $ext='';

    $tmpcnt=0;
    $pre_filename=purename(basename($_FILES[$variable_name]['name']));
    $filename=$pre_filename.'_'.date('Ymd').'_'.$tmpcnt.$ext;
    while(file_exists(cfg_data_path.'/upload/'.$filename))
    {
      $tmpcnt++;
      $filename=$pre_filename.'_'.date('Ymd').'_'.$tmpcnt.$ext;
    }

    if(move_uploaded_file($_FILES[$variable_name]['tmp_name'], cfg_data_path.'/upload/'.$filename))
      $variable_value=$filename;
  }

  return(''.$variable_value);
}

function replace_const($variable_value)
{  
  $variable_value=str_replace('TODAY',date('Ymd'),$variable_value);
  $variable_value=str_replace('THISMONTH',date('Ym'),$variable_value);
  $variable_value=str_replace('LASTMONTH',date('Ym',mktime(0,0,0,date('m')-1,1,date('Y'))),$variable_value);
  $variable_value=str_replace('NOW',date('H:i:s'),$variable_value);
  $variable_value=str_replace('USERNAME',USERNAME,$variable_value);
  $variable_value=str_replace('USERGROUP',USERGROUP,$variable_value);
  $variable_value=str_replace('FILTER',FILTER,$variable_value);
  $variable_value=str_replace('USERDESCRIPTION',USERDESCRIPTION,$variable_value);
  $variable_value=str_replace('TOMORROW',date('Ymd',mktime(0,0,0,date('m'),date('d')+1,date('Y'))),$variable_value);
  $variable_value=str_replace('YESTERDAY',date('Ymd',mktime(0,0,0,date('m'),date('d')-1,date('Y'))),$variable_value);
  $variable_value=str_replace('WEEKAGO',date('Ymd',mktime(0,0,0,date('m'),date('d')-7,date('Y'))),$variable_value);

  return $variable_value;
}

// system log
function mylog($text)
{
  /*
  addpath(cfg_data_path.'/logs');
  $fp=fopen(cfg_data_path.'/logs/'.date('Ym').'.log','a');
  fwrite($fp,date('d.m.Y H:i:s').' '.cfg_lang_file.' '.USERNAME.' '.USERGROUP.' '.$text.CRLF);
  fclose($fp);
  */

  $variable_array=array();
  $variable_array['Date']=date('Ymd');
  $variable_array['Time']=date('H:i:s');
  if(defined('USERNAME'))
    $variable_array['User']=USERNAME;
  if(defined('USERGROUP'))
    $variable_array['Group']=USERGROUP;
  $variable_array['Browser Language']=cfg_lang_file;
  $variable_array['Message']=$text;
  $variable_array['MyBag']='logs';
  $variable_array['sysGroupBy']='logs';

  save($variable_array);
}

// addpath() recurential adding directories
function addpath($dir)
{
	if(!file_exists(dirname($dir)))
		addpath(dirname($dir));

	if(!file_exists($dir))
		mkdir($dir,0777);
}

// split_label() splitting MyOwnLabel into My Own Label
function split_label($label)
{
  //gan off due to spaces allowed everywhere
  /*
  $tmp_label='';
  for($ii=0;$ii<strlen($label);$ii++)
  {
    if(ord($label[$ii])>64 and ord($label[$ii])<91) //A..Z -> space A..Z
    {
      if((strlen($label)==($ii+1) and ord($label[$ii-1])>64 and ord($label[$ii-1])<91) or (ord($label[$ii+1])>64 and ord($label[$ii+1])<91)) //A..Z -> space A..Z
        $tmp_label.=$label[$ii];
      else
        $tmp_label.=' '.$label[$ii];
    }
    else  // any -> any
      $tmp_label.=$label[$ii];
  }
  */

  return trim($label);
}

//converting names to pure form
function purename($fullname)
{
  global $_charset;
  global $_purename_mask;

  $purename=str_replace(' ','',strtr($fullname,$_charset,$_purename_mask));

  return $purename;
}

//converting names to pure form
function linkname($fullname)
{
  global $_charset;
  global $_linkname_mask;

  $fullname=str_replace(' ','-',$fullname);
  $fullname=str_replace('ż','z',$fullname);
  $fullname=str_replace('ź','z',$fullname);
  $fullname=str_replace('ą','a',$fullname);
  $fullname=str_replace('ś','s',$fullname);
  $fullname=str_replace('ł','l',$fullname);
  $fullname=str_replace('ć','c',$fullname);
  $fullname=str_replace('ń','n',$fullname);
  $fullname=str_replace('ę','e',$fullname);
  $fullname=str_replace('ó','o',$fullname);
  
  $fullname=str_replace('Å»','z',$fullname);
  $fullname=str_replace('Ź','z',$fullname);
  $fullname=str_replace('Ą','a',$fullname);
  $fullname=str_replace('Ś','s',$fullname);
  $fullname=str_replace('Ł','l',$fullname);
  $fullname=str_replace('Ć','c',$fullname);
  $fullname=str_replace('Ń','n',$fullname);
  $fullname=str_replace('Ę','e',$fullname);
  $fullname=str_replace('Ó','o',$fullname);
  
  $linkname=str_replace(' ','',strtr($fullname,$_charset,$_linkname_mask));

  return $linkname;
}

// getmicrotime()
function getmicrotime()
{
  list($usec, $sec) = explode(" ",microtime());
  return ((float)$usec + (float)$sec);
}

// showtime($text='') timeed debug
function showtime($text='')
{
  global $time_start;

  if($text=='')
    $time_start = getmicrotime();
  else
  {
    $time_end = getmicrotime();
    $time = $time_end - $time_start;

    //if($time>1)
    {
      echo '<br />=='.$text.' '.$time.'==';
    }
  }
}

function readable_size($size)
{
  $sizes = Array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB');
  $ext = $sizes[0];
  for ($i=1; (($i < count($sizes)) && ($size >= 1024)); $i++) {
   $size = $size / 1024;
   $ext  = $sizes[$i];
  }
  return round($size, 2).$ext;
}

// ----------------- Index/Search functions ------------------------
// index_explode($words) explodes content to index names
function index_explode($words) //:$index_name_array
{
  $index_name_array=array();

  $words=str_replace('[','"',$words);
  $words=str_replace(']','"',$words);
  //$words=str_replace('"','"',$words);
  $content_array=explode('"',$words);
  $words='';
  for($ii=0;$ii<sizeof($content_array);$ii++)
  {
    if($ii%2==0) //out of the brackets
      $words.=$content_array[$ii];
    else //in the brackets
      $words.=str_replace(' ',chr(2),$content_array[$ii]);
  }

  //echo $words;

  $word_array=explode(' ',$words);
  for($kk=0;$kk<sizeof($word_array);$kk++)
  {
    $index_name=trim(str_replace(chr(2),' ',$word_array[$kk]));
    if(strlen($index_name))
    {
      $index_name_array[$index_name]='';
      //echo '<br >Next word:'.$index_name;
    }
  }

  return($index_name_array);
}

// index_clear($word) clears index name
function index_clear($word) //:$word
{
  return str_replace('>','',str_replace('<','',str_replace('=','',$word)));
}

// index_name($word) converts word to proper index name
function index_name($word) //:$index_name
{
  return 'word_'.md5(strtolower(index_clear($word)));
}

function check_words($search)
{
  $all_words_array=check_index($search);

  $alt_search='';
  $alt_search_show='';
  $search=str_replace(':',' : ',$search);
  $search_array=explode(' ',$search);
  for($ii=0;$ii<sizeof($search_array);$ii++)
  {
    $search_array[$ii]=trim($search_array[$ii]);

    if(strlen($search_array[$ii])>0)
    {
      if($all_words_array[strtolower($search_array[$ii])] or $search_array[$ii]==':')
      {
        $alt_search_show.=$search_array[$ii].' ';
        $alt_search.=$search_array[$ii].' ';
      }
      else
      {
        $max_word=$search_array[$ii];
        $max_similarity=0;

        reset($all_words_array);
        while(list($word,$val)=each($all_words_array))
        {
          if(trim($word))
          {
            $similarity=similar_text($word,$search_array[$ii])/(abs(strlen($word)-strlen($search_array[$ii]))+6.5); //6
            if($max_similarity<$similarity)
            {
              $max_similarity=$similarity;
              $max_word=$word;
            }
          }
        }

        if($max_similarity>0.2)
        {
          //$alt_search_show.='<b>'.$max_word.'('.$max_similarity.')</b> ';
          $alt_search_show.='<b>'.$max_word.' </b> ';
          $alt_search.=$max_word.' ';
        }
      }
    }
  }

  $alt_search=str_replace(' : ',':',$alt_search);
  $alt_search_show=str_replace(' : ',':',$alt_search_show);

  if(strlen($alt_search)>0)
    echo '<p>Try: <a href="index.php?odb_choosebag=nobag&amp;odb_search='.rawurlencode($alt_search).''.$context_params.'">'.$alt_search_show.'</a></p>';
}

function serialize_content($variable_array) //:$content
{
  $v=$variable_array;
  $content=serialize($v);
  $content='gzip'.base64_encode(gzcompress($content,9));
  return($content);
}

function unserialize_content($content) //:$variable_array
{
  $sysId=0;
  $sysValid=1;

  if(substr($content,0,4)=='gzip')
    $content=gzuncompress(base64_decode(substr($content,4)));

  if(substr($content,0,1)=='0')
  {
    $sysId=0+substr($content,0,10);
    $sysValid=0+substr($content,10,1);

    $content=substr($content,11);
  }

  $v=unserialize($content);

  $v['sysId']['value']=$sysId;
  $v['sysValid']['value']=$sysValid;

  return($v);
}

function solve($variable_array, $variable_array2='') //:$variable_array
{
  if(count($variable_array)>0)
  {
    reset($variable_array);
    while(list($variable_name,$value)=each($variable_array))
    {
      if(strlen($variable_array[$variable_name])>0)
      {
        //* problem
        $pos=strpos('_'.$value,'[');
        while($pos>0)
        {
          $variable=substr($value,$pos,strpos($value.']',']',$pos)-$pos);
          if(strlen($variable_array[$variable]))
          {
            $repl_value=$variable_array[$variable];
            $value=str_replace('['.$variable.']',$repl_value,$value);
            $pos=strpos('_'.$value,'[');
          }
          else
          {
            $value=str_replace('['.$variable.']','',$value);
            $value=trim(str_replace('  ',' ',$value));
            if($pos+1<strlen('_'.$value))
              $pos=strpos('_'.$value,'[',$pos+1);
            else
              $pos=0;
          }
        }
        //*/
        $variable_array[$variable_name]=$value;
      }
    }
  }
  else
    $variable_array=array();

  return $variable_array;
}

function parse_content($content,$config,$solve_formula=SOLVE) //:$variable_array
{
  $tmp_array=unserialize_content(load_config($config));
  $variable_array=unserialize_content($content);
  reset($tmp_array);
  while(list($key,$val)=each($tmp_array))
  {
    if(!isset($variable_array[$key]))
    {
      $variable_array[$key]=$val;
    }
  }

  if($solve_formula)
  {
    reset($variable_array);
    while(list($variable_name,$val)=each($variable_array))
    {
      if(strlen($variable_array[$variable_name]['formula'])>0 and strlen($variable_array[$variable_name]['value'])==0)
      {
        $value=$variable_array[$variable_name]['formula'];

        /*
        $pos=strpos('_'.$value,'$');
        while($pos>0)
        {
          $variable=substr($value,$pos,strpos($value.' ',' ',$pos)-$pos);
          if(strlen($variable_array[$variable]['value']))
          {
            $repl_value=$variable_array[$variable]['value'];
            $value=str_replace('$'.$variable,$repl_value,$value);
          }
          $pos=strpos('_'.$value,'$',$pos+1);
        }
        */
        $pos=strpos('_'.$value,'[');
        while($pos>0)
        {
          $variable=substr($value,$pos,strpos($value.']',']',$pos)-$pos);
          if(strlen($variable_array[$variable]['value']))
          {
            $repl_value=$variable_array[$variable]['value'];
            $value=str_replace('['.$variable.']',$repl_value,$value);
            $pos=strpos('_'.$value,'[');
          }
          else
          {
            $value=str_replace('['.$variable.']','',$value);
            $value=trim(str_replace('  ',' ',$value));
            if($pos+1<strlen('_'.$value))
              $pos=strpos('_'.$value,'[',$pos+1);
            else
              $pos=0;
          }
        }
        $variable_array[$variable_name]['value']=$value;
      }
    }
  }

  return $variable_array;
}

function auto_transport(&$variable_array, $object_name, $key1_variable_name, $key2_variable_name='')
{
  if(strlen($variable_array[$key1_variable_name])>0)
  {
    $config_array=load_config($object_name);
    $transport_variable_array=array();

    $tmp_search='['.$key1_variable_name.'='.$variable_array[$key1_variable_name].'] sysGroupBy='.$object_name;
    if($key2_variable_name!='')
      $tmp_search.=' ['.$key2_variable_name.'='.$variable_array[$key2_variable_name].']';
    $tmp_result_array=search($tmp_search);

    if(count($tmp_result_array)>0)
    {
      reset($config_array);
      foreach($config_array as $temp_variable_name => $tmp)
      {
        if(substr($temp_variable_name,0,3)!='sys' and $temp_variable_name!='MyBag' and strlen($variable_array[$temp_variable_name])==0 and strlen(read($tmp_result_array[0],$temp_variable_name))>0)
          $variable_array[$temp_variable_name]=read($tmp_result_array[0],$temp_variable_name);
      }
      $transport_variable_array=line2array($tmp_result_array[0]);
    }

    if($transport_variable_array['sysModDate']=='' or $transport_variable_array['sysModDate']<=$variable_array['sysModDate'])
    {
      $changes=0;
      reset($config_array);
      foreach($config_array as $temp_variable_name => $tmp)
      {
        if(substr($temp_variable_name,0,3)!='sys' and $temp_variable_name!='MyBag')
        {
          if(strlen($variable_array[$temp_variable_name])>0)
          if(read($tmp_result_array[0],$temp_variable_name)!=$variable_array[$temp_variable_name])
          {
            $transport_variable_array[$temp_variable_name]=$variable_array[$temp_variable_name];
            $changes=1;
          }
          else
            $transport_variable_array[$temp_variable_name]=$variable_array[$temp_variable_name];
        }
      }
    }

    if($changes)
    {
      $transport_variable_array['sysGroupBy']=$object_name;
      $transport_variable_array['sysComment']='Auto Transport - '.$object_name;
      //~ echo '<pre>';
      //~ print_r($transport_variable_array);
      //~ echo '</pre>'; exit;
      save($transport_variable_array);
    }
  }
}


function save_config($group,$variable_array) //:void
{
  global $cache_content_array;

  $old_variable_array=load_config($group);
  
  $variable_array['sysId']['mod']=USERNAME.' '.date('Y-m-d');
  
  $names_array=array();
  $pure_variable_array=array();
  reset($variable_array);
  while(list($variable_name,$tmp)=each($variable_array))
  {
    $pure_variable_name=purename($variable_name);

    if(!isset($names_array[$pure_variable_name]))
      $names_array[$pure_variable_name]=$variable_name;

    if(!isset($old_variable_array[$names_array[$pure_variable_name]])
      or $old_variable_array[$names_array[$pure_variable_name]]['template']!=$variable_array[$variable_name]['template']
      or $old_variable_array[$names_array[$pure_variable_name]]['dict']!=$variable_array[$variable_name]['dict']
      or $old_variable_array[$names_array[$pure_variable_name]]['tab']!=$variable_array[$variable_name]['tab']
      or $old_variable_array[$names_array[$pure_variable_name]]['size']!=$variable_array[$variable_name]['size']
      or $old_variable_array[$names_array[$pure_variable_name]]['formula']!=$variable_array[$variable_name]['formula']
      or $old_variable_array[$names_array[$pure_variable_name]]['show_cond']!=$variable_array[$variable_name]['show_cond']
      or $old_variable_array[$names_array[$pure_variable_name]]['hl']!=$variable_array[$variable_name]['hl']
    )
    {
      $variable_array[$variable_name]['mod']=USERNAME.' '.date('Y-m-d');
    }
    
    $pure_variable_array[$names_array[$pure_variable_name]]=$variable_array[$variable_name];
  }
  $variable_array=$pure_variable_array;

  //$content=serialize_content($variable_array);
  $groupfile=purename($group);

  $add_first_record=0;
  //if(!file_exists(cfg_data_path.'/config/structure/grp_'.$groupfile.'.php') and !file_exists(cfg_data_path.'/config/structure/'.cfg_structure.'/grp_'.$groupfile.'.txt'))
  //  $add_first_record=1;

  addpath(cfg_data_path.'/config/structure/');
  clearstatcache();
  $tmp_bak=1;
  while(file_exists(cfg_data_path.'/config/structure/bak'.$tmp_bak.'_'.$groupfile.'.bak'))
    $tmp_bak++;
  copy(cfg_data_path.'/config/structure/grp_'.$groupfile.'.php',cfg_data_path.'/config/structure/bak'.$tmp_bak.'_'.$groupfile.'.bak');
    
  $fp=fopen(cfg_data_path.'/config/structure/grp_'.$groupfile.'.php','wb');
  fwrite($fp,'<'.'?php $structure='.var_export($variable_array,true).'; ?'.'>');
  fclose($fp);
  $cache_content_array=array();

  $fp=fopen(cfg_data_path.'/data/.lastmod','wb');
  fwrite($fp,date('Ymd H:i:s'));
  fclose($fp);

  //mylog('GROUP CHANGE '.$groupfile);

  $cache_content_array[$groupfile]=$variable_array;

  /*
  if($add_first_record)
  {
    $variable_array=array();
    $variable_array['sysGroupBy']=$groupfile;
    $variable_array['sysValidFrom']=date('Ymd');
    $variable_array['sysValidTo']=99991231;
    $variable_array['sysValid']=1;
    $variable_array['sysComment']='First empty record';

    $id=save($variable_array);
    global $search;
    $search='sysId='.$id;
    //echo 'SAVE:'.$id;
    //index($id,$variable_array);
    //set_valid($id);
  }
  */
}

$cache_content_array=array();
function load_config($config) //:variable_array
{
  global $cache_content_array;

  if($config=='')
  {
    $cache_content_array[$config]=array();
  }
  elseif(!isset($cache_content_array[$config]))
  {
    $groupfile=purename($config);

    if(file_exists(cfg_data_path.'/config/structure/grp_'.$groupfile.'.php'))
    {
      include(cfg_data_path.'/config/structure/grp_'.$groupfile.'.php');
      $variable_array=$structure;
      $variable_array['sysId']['value']='';
    }
    elseif(file_exists(cfg_data_path.'/script/structure/grp_'.$groupfile.'.php'))
    {
      include(cfg_data_path.'/script/structure/grp_'.$groupfile.'.php');
      $variable_array=$structure;
      $variable_array['sysId']['value']='';
    }
    else
    {
      $variable_array=array();
      $variable_array['sysId']['value']='';
    }

    if(!isset($variable_array['Latitude']))
      $variable_array['Latitude']['tab']='...';
    if(!isset($variable_array['Longitude']))
      $variable_array['Longitude']['tab']='...';

    $variable_array['sysFTell']['value']='';
    $variable_array['sysGroupBy']['value']=$config;
    $cache_content_array[$config]=$variable_array;
  }

  return $cache_content_array[$config];
}

function save_session($force_close=0)
{
  global $sid;
  global $session_array;

  //$tmp_session_array=$session_array;

  reset($session_array);
  foreach($session_array as $key => $value)
    if(strlen($value))
      $tmp_session_array[$key]=$value;

  addpath(cfg_sso_path.'/temp/users/');

  $fp=fopen(cfg_sso_path.'/temp/users/'.$sid.'.tmp','wb');
  if(fwrite($fp,'<'.'?php $session_array='.var_export($tmp_session_array,true).'; ?'.'>') === FALSE)
  {
  	fclose($fp);
    echo '<div style="background-color:#f00; color:#fff;">Warning: Cannot save session. Check available disk space.</div>';
    if($force_close)
      unlink(cfg_sso_path.'/temp/users/'.$sid);
  }
  else
  {
    fclose($fp);
    if(file_exists(cfg_sso_path.'/temp/users/'.$sid))
      unlink(cfg_sso_path.'/temp/users/'.$sid);

    if(copy(cfg_sso_path.'/temp/users/'.$sid.'.tmp',cfg_sso_path.'/temp/users/'.$sid)) 
      unlink(cfg_sso_path.'/temp/users/'.$sid.'.tmp');
  }

}

function utf2html($str)
{
  $ret = "";
  $max = strlen($str);
  $last = 0;  // keeps the index of the last regular character
  for ($i=0; $i<$max; $i++) {
   $c = $str{$i};
   $c1 = ord($c);
   if ($c1>>5 == 6) {  // 110x xxxx, 110 prefix for 2 bytes unicode
     $ret .= substr($str, $last, $i-$last); // append all the regular characters we've passed
     $c1 &= 31; // remove the 3 bit two bytes prefix
     $c2 = ord($str{++$i}); // the next byte
     $c2 &= 63;  // remove the 2 bit trailing byte prefix
     $c2 |= (($c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
     $c1 >>= 2; // c1 shifts 2 to the right
     $ret .= "&#" . ($c1 * 100 + $c2) . ";"; // this is the fastest string concatenation
     $last = $i+1;
   }
  }
  return $ret . substr($str, $last, $i); // append the last batch of regular characters
}

function showsms($phone, $sms_template, $variable_array, $memo='') //:none
{
  $tmp_result_array=search('sysGroupBy=smstemplate [SMS Template Name='.$sms_template.']');
  if(count($tmp_result_array))
  {
    reset($tmp_result_array);
    while(list($tmp,$tmp_result)=each($tmp_result_array))
    {
      if(read($tmp_result,'Body'))
      {
        $sms_content=read($tmp_result,'Body');

        $sms_content=str_replace('[USERNAME]',USERNAME,$sms_content);

        //filling variables
        if(count($variable_array)>1 and strpos('_'.$sms_content,'['))
        {
          reset($variable_array);
          while(list($key,$val)=each($variable_array))
          {
            $sms_content=str_replace('['.$key.']',$val,$sms_content);
            if(strpos('_'.$sms_content,'[')==0)
              break;
          }
        }


        if($sms_content)
        {
          $sms_link=$sms_content;
          if(strpos($sms_link,'.')>1)
            $sms_link=substr($sms_link,0,strpos($sms_link,'.'));
          $sms_content=rawurlencode(trim($sms_content));
          $memo=rawurlencode(trim($memo));

          echo '<a href="#" onclick="popup=window.open(\'index.php?odb_script=sms&amp;odb_popup=1&amp;odb_search=--- MyBag='.$variable_array['MyBag'].'&amp;odb_to='.$phone.'&amp;odb_memo='.$memo.'&amp;odb_body='.$sms_content.'\',\'popup\',\'SCROLLBARS,RESIZABLE,WIDTH=400,HEIGHT=270\'); return(false);">';
          echo '<img src="images/email.jpg" /> '.$sms_link;
          echo '</a><br />';
        }
      }
    }
  }
  else
  {
    echo '<a href="index.php?odb_script=new&odb_group=smstemplate&odb_SMS_Template_Name='.$sms_template.'&odb_search=---">';
    echo '<img src="images/email.jpg" /> ';
    myecho('New template');
    echo '</a><br />';
  }
}


function fill_variables($text, $variable_array)// :$text
{
  //filling variables
  if(count($variable_array)>1 and strpos('_'.$text,'['))
  {
    reset($variable_array);
    while(list($key,$val)=each($variable_array))
    {
      $text=str_replace('['.$key.']',$val,$text);
      if(strpos('_'.$text,'[')==0)
        break;
    }
  }

  $text=str_replace(' CRLF ',CRLF,$text);
  $text=str_replace('<br>',CRLF,$text);
  $text=str_replace('[br]',CRLF,$text);
  //$text=str_replace(CRLF,'<br>'.CRLF,$text);
  $text=replace_const($text);

  return $text;
}


function showmail($email, $mail_template, $variable_array, $memo='') //:none
{
  if(file_exists(cfg_data_path.'/config/script/mail_'.$mail_template.'.html'))
    $mail_path=cfg_data_path.'/config/script/mail_'.$mail_template.'.html';
  else
    $mail_path=cfg_data_path.'/script/mail_'.$mail_template.'.html';

  if(file_exists($mail_path))
  {
    $content_array=explode("\r\n",file_get_contents($mail_path));

    $mail_subject='';
    $mail_content='';
    $tmp_content_start_pos=0;
    reset($content_array);
    while(list($tmp_pos,$tmp_content)=each($content_array))
    {
      //filling variables
      if(count($variable_array)>1 and strpos('_'.$tmp_content,'['))
      {
        reset($variable_array);
        while(list($key,$val)=each($variable_array))
        {
          $tmp_content=str_replace('['.$key.']',$val,$tmp_content);
          if(strpos('_'.$tmp_content,'[')==0)
            break;
        }
      }

      //preparing links
      if(strpos($tmp_content,'****'))
      {
        $tmp_content_start_pos=$tmp_pos;

        if($mail_subject)
        {
          $mail_link=$mail_subject;

          //$mail_subject=str_replace('+',' ',urlencode(utf8_decode(trim($mail_subject))));
          //$mail_content=str_replace('+',' ',urlencode(utf8_decode(trim($mail_content))));


          $mail_subject=rawurlencode(trim($mail_subject));
          $mail_content=rawurlencode(trim($mail_content));
          $memo=rawurlencode(trim($memo));

          //echo '<a href="mailto:'.$email.'?subject='.$mail_subject.'&bcc=hide@address.com&body='.$mail_content.'">';// MyBag='.$variable_array['MyBag'].'
          echo '<a href="#" onclick="popup=window.open(\'index.php?odb_script=mail&amp;odb_template='.$mail_template.'&amp;odb_popup=1&amp;odb_search=---&amp;odb_to='.$email.'&amp;odb_memo='.$memo.'&amp;odb_subject='.$mail_subject.'&amp;odb_body='.$mail_content.'\',\'popup\',\'SCROLLBARS,RESIZABLE,WIDTH=500,HEIGHT=550\'); return(false);">';
          echo '<img src="images/email.jpg" /> '.$mail_link;
          echo '</a><br />';
        }

        $mail_subject='';
        $mail_content='';
      }

      if($tmp_content_start_pos+1==$tmp_pos)
        $mail_subject=trim($tmp_content);

      if($tmp_content_start_pos+1<$tmp_pos)
        $mail_content.=$tmp_content."\r\n";
    }


    $first_line_chr_count=strpos($content,"\n");
    $body=trim(substr($content,$first_line_chr_count));
    $subject=substr($content,0,$first_line_chr_count);
  }
  else
  {
    $tmp_result_array=search('sysGroupBy=emailtemplate [Email Template Name='.$mail_template.']');
    if(count($tmp_result_array))
    {
      reset($tmp_result_array);
      while(list($tmp,$tmp_result)=each($tmp_result_array))
      {
        if(read($tmp_result,'Subject'))
        {
          $mail_subject=fill_variables(read($tmp_result,'Subject'),$variable_array);
          $mail_content=fill_variables(read($tmp_result,'Body'),$variable_array);
          $mail_cc=fill_variables(read($tmp_result,'CC'),$variable_array);
          $mail_to=fill_variables(read($tmp_result,'To'),$variable_array);
          if($email and strpos('_'.$mail_to,$email)==0)
            if($mail_to)
              $mail_to=$email.','.$mail_to;
            else
              $mail_to=$email;

          if($mail_subject)
          {
            $mail_link=$mail_subject;

            //$mail_subject=str_replace('+',' ',urlencode(utf8_decode(trim($mail_subject))));
            //$mail_content=str_replace('+',' ',urlencode(utf8_decode(trim($mail_content))));

            $mail_subject=rawurlencode(trim($mail_subject));
            $mail_content=rawurlencode(trim($mail_content));
            $mail_cc=rawurlencode(trim($mail_cc));
            $mail_to=rawurlencode(trim($mail_to));
            $memo=rawurlencode(trim($memo));

            //echo '<a href="mailto:'.$email.'?subject='.$mail_subject.'&bcc=hide@address.com&body='.$mail_content.'">';// MyBag='.$variable_array['MyBag'].'
            echo '<a href="#" onclick="popup=window.open(\'index.php?odb_script=mail&amp;odb_template='.$mail_template.'&amp;odb_popup=1&amp;odb_search=---&amp;odb_to='.$mail_to.'&amp;odb_cc='.$mail_cc.'&amp;odb_memo='.$memo.'&amp;odb_subject='.$mail_subject.'&amp;odb_body='.$mail_content.'\',\'popup\',\'SCROLLBARS,RESIZABLE,WIDTH=500,HEIGHT=550\'); return(false);">';
            echo '<img src="images/email.jpg" /> '.$mail_link;
            echo '</a><br />';
          }
        }
      }
    }
    else
    {
      echo '<a href="index.php?odb_script=new&odb_group=emailtemplate&odb_To=['.$mail_template.']&odb_Email_Template_Name='.$mail_template.'&odb_search=---">';
      echo '<img src="images/email.jpg" /> ';
      myecho('New template');
      echo '</a><br />';
    }
  }

}


function send_email($email, $subject, $body, $cc='') //:none
{

  require_once(cfg_data_path.'/script/phpmailer/class.phpmailer.php');

  $mail = new PHPMailer();
  $mail->PluginDir=cfg_data_path.'/script/phpmailer/';
  $mail->SetLanguage('en',cfg_data_path.'/script/phpmailer/language/');

  $mail->IsSMTP();                    // send via SMTP
  $mail->Host     = cfg_smtp_server; // SMTP servers

  if(strlen(cfg_smtp_passwd)>0)
  {
    $mail->SMTPAuth = true;     // turn on SMTP authentication
    $mail->Username = cfg_smtp_user;  // SMTP username
    $mail->Password = cfg_smtp_passwd; // SMTP password
  }

  $mail->From     = cfg_smtp_from;
  $mail->AddAddress($email);
  $mail->AddCC($cc);
  $mail->AddReplyTo(cfg_smtp_from);

  $mail->WordWrap = 50;                              // set word wrap
  //$mail->AddAttachment("/var/tmp/file.tar.gz");      // attachment
  //$mail->AddAttachment("/tmp/image.jpg", "new.jpg");
  $mail->IsHTML(false);                               // send as HTML

  $mail->Subject  =  $subject;
  $mail->Body     =  $body;

  $variable_array['Email Status']='New';
  $variable_array['Send Date']=date('Ymd');
  $variable_array['Send Time']=date('H:i');
  $variable_array['Send From']='send_email';
  $variable_array['Send To']=$email;
  $variable_array['Send CC']=$cc;
  $variable_array['Send Subject']=$subject;
  $variable_array['Send Body']=$body;
  $variable_array['sysComment']='Email sent';
  $variable_array['sysValidFrom']=date('Ymd');
  $variable_array['sysValidTo']=99991231;
  $variable_array['sysValid']=1;
  $variable_array['sysId']='';
  $variable_array['MyBag']='emails';
  $variable_array['sysGroupBy']='email';

  //USEREXIT OnSave
  $userexit='onsave';
  if(file_exists(cfg_data_path.'/config/userexit/exit_'.$userexit.'.txt'))
  {
    include(cfg_data_path.'/config/userexit/exit_'.$userexit.'.txt');
  }
  else
  {
    include(cfg_data_path.'/script/userexit/exit_'.$userexit.'.txt');
  }

  if(!$mail->Send())
  {
     //echo "Message was not sent <p>";
     $email_file=rand(10000000,99999999);
     addpath(cfg_data_path.'/config/not_sent');
      $fp=fopen(cfg_data_path.'/config/not_sent/'.$email_file.'.txt','wb');
        fwrite($fp,$email.CRLF.'-------------------'.CRLF.''.$subject.CRLF.'-------------------'.CRLF.$body);
      fclose($fp);
     mylog('MAILER ERROR ('.$email_file.') '.$mail->ErrorInfo);
     $variable_array['Email Status']='Cannot send';
      //echo "Mailer Error: " . $mail->ErrorInfo;
     //exit;
  }
  else
  {
    //echo "Message sent";
    mylog('MESSAGE SENT '.$mail_template);
    $variable_array['Email Status']='Sent';
  }
  save($variable_array);
}


function sendmail($email, $mail_template, $variable_array) //:none
{

  require_once(cfg_data_path.'/script/phpmailer/class.phpmailer.php');

  $mail = new PHPMailer();
  $mail->PluginDir=cfg_data_path.'/script/phpmailer/';
  $mail->SetLanguage('en',cfg_data_path.'/script/phpmailer/language/');

  $mail->IsSMTP();                    // send via SMTP
  $mail->Host     = cfg_smtp_server; // SMTP servers

  if(strlen(cfg_smtp_passwd)>0)
  {
    $mail->SMTPAuth = true;     // turn on SMTP authentication
    $mail->Username = cfg_smtp_user;  // SMTP username
    $mail->Password = cfg_smtp_passwd; // SMTP password
  }

  $mail->From     = cfg_smtp_from;
  $mail->AddAddress($email);
  $mail->AddReplyTo(cfg_smtp_from);

  $mail->WordWrap = 50;                              // set word wrap
  //$mail->AddAttachment("/var/tmp/file.tar.gz");      // attachment
  //$mail->AddAttachment("/tmp/image.jpg", "new.jpg");
  $mail->IsHTML(true);                               // send as HTML

  if(file_exists(cfg_data_path.'/config/script/mail_'.$mail_template.'.html'))
    $mail_path=cfg_data_path.'/config/script/mail_'.$mail_template.'.html';
  else
    $mail_path=cfg_data_path.'/script/mail_'.$mail_template.'.html';

  if(file_exists($mail_path))
  {
    $content=file_get_contents($mail_path);

    reset($variable_array);
    while(list($key,$val)=each($variable_array))
      $content=str_replace('['.$key.']',$val,$content);

    $first_line_chr_count=strpos($content,"\n");
    $body=trim(substr($content,$first_line_chr_count));
    $subject=substr($content,0,$first_line_chr_count);
  }

  $mail->Subject  =  $subject;
  $mail->Body     =  $body;

  if(!$mail->Send())
  {
     //echo "Message was not sent <p>";
     $email_file=rand(10000000,99999999);
     addpath(cfg_data_path.'/config/not_sent');
      $fp=fopen(cfg_data_path.'/config/not_sent/'.$email_file.'.txt','wb');
        fwrite($fp,$email.CRLF.'-------------------'.CRLF.''.$subject.CRLF.'-------------------'.CRLF.$body);
      fclose($fp);
     mylog('MAILER ERROR ('.$email_file.') '.$mail->ErrorInfo);
     //echo "Mailer Error: " . $mail->ErrorInfo;
     //exit;
  }
  else
  {
    //echo "Message sent";
    mylog('MESSAGE SENT '.$mail_template);
  }
}

// ----------------- Security functions ------------------------
function check_access($mybag,$default_when_not_set=0) //: 0-none 1-read 2-write 3-owner
{
  global $bagaccess_array;
  global $popup;

  $access=$default_when_not_set;
  if($bagaccess_array['all']>$default_when_not_set)
    $access=$bagaccess_array['all'];
  $mybag=trim($mybag);

  if(isset($bagaccess_array[$mybag]))
  {
    $access=$bagaccess_array[$mybag];
    //echo '<br />SHORT:'.$mybag.':'.$tmp_array[$ii].':'.$bagaccess_array[$mybag].'/'.$bagaccess_array['all'].'='.$access;
  }
  elseif(isset($bagaccess_array[strtolower($mybag)]))
  {
    $access=$bagaccess_array[strtolower($mybag)];
    //echo '<br />SHORT:'.$tmp_array[$ii].':'.$bagaccess_array[$mybag].'/'.$bagaccess_array['all'].'='.$access;
  }
  elseif(strpos(' '.$mybag,' ')>0)
  {
    $tmp_array=explode(' ',$mybag);
    $sizeof=sizeof($tmp_array);
    for($ii=0;$ii<$sizeof;$ii++)
    {
      if(isset($tmp_array[$ii]) and isset($bagaccess_array[strtolower(trim($tmp_array[$ii]))]) and 0+$bagaccess_array[strtolower(trim($tmp_array[$ii]))]>$access)
        $access=$bagaccess_array[strtolower(trim($tmp_array[$ii]))];
      //echo '<br />CHECK:'.$tmp_array[$ii].':'.$access;
    }
    $bagaccess_array[$mybag]=$access;
  }

  if($popup and $access>1)
    $access=1;

  return $access;
}

function set_access($mybag,$access) //:
{
  global $bagaccess_array;
  $bagaccess_array[$mybag]=$access;
}

function get_owner_list($mybag) //:$owner_list
{
  $owner_list='';
  $result_array=search('bagaccess access=3 bag=\''.$mybag.'\' MyBag=access');

  $sizeof=count($result_array);
  for($ii=0;$ii<$sizeof;$ii++)
  {
    $owner=read($result_array[$ii],'User');
    if($owner_list=='')
      $owner_list.=$owner;
    if(strpos('_'.$owner_list,$owner)==0)
      $owner_list.=', '.$owner;
  }
  $owner_list=trim($owner_list);

  return($owner_list);
}

function check_category(&$variable_array, $category_definition_array=array('sysGroupBy','Person Code'),$keyword_definition_array=array('en','pl'))
{
  //preparing keyword_array
  $keyword_array=array();
  $tmp_line='';
  reset($variable_array);
  foreach($variable_array as $variable_name => $variable_value)
    $tmp_line.='$'.$variable_name.'='.$variable_value;
  $tmp_line.='$';

  reset($keyword_definition_array);
  foreach($keyword_definition_array as $keyword)
  {
    echo $keyword.' ';
    if(stristr($tmp_line,$keyword))
      $keyword_array[]=$keyword;
  }

  if(count($keyword_array)>0)
  {
    //preparing category search
    $tmp_search='';
    reset($category_definition_array);
    foreach($category_definition_array as $variable_name)
      $tmp_search.=' ['.$variable_name.']';

    //category search
    $result_array=search($tmp_search);

    //building category array
    $category_array=array();
    $category_sysCount_sum=0;
    reset($result_array);
    foreach($result_array as $tmp_line)
    {
      $category='';
      $full_category=1;
      reset($category_definition_array);
      foreach($category_definition_array as $variable_name)
      {
        $tmp_category=read($tmp_line,$variable_name);
        if(strlen($tmp_category))
          $category.=$tmp_category;
        else
          $full_category=0;
      }
      $category=trim($category);

      if($full_category)
      {
        reset($category_definition_array);
        foreach($category_definition_array as $variable_name)
          $category_array[$category][$variable_name]=read($tmp_line,$variable_name);

        //adding points for keywords 0..1
        reset($keyword_array);
        foreach($keyword_array as $keyword)
        {
          if(stristr($tmp_line,$keyword))
          {
            $category_array[$category]['sysPoints']+=1;
            //~ echo '<br />'.$category.' '.$keyword.'*';
            //~ echo '<br />'.$tmp_line;
          }
        }

        $category_array[$category]['sysCount']++;
        $category_sysCount_sum++;
      }
    }

    //adding points for category popularity 0..1
    reset($category_array);
    foreach($category_array as $category => $tmp)
      $category_array[$category]['sysPoints']+=round(1*$category_array[$category]['sysCount']/$category_sysCount_sum);

    //sorting categories by points
    $sort_category_array=array();
    reset($category_array);
    foreach($category_array as $category => $tmp)
      $sort_category_array[$category]=$category_array[$category]['sysPoints'];
    arsort($sort_category_array);

    echo '<pre>';
    echo print_r($sort_category_array);
    echo '</pre>';

    //getting winning category
    reset($sort_category_array);
    foreach($sort_category_array as $winning_category => $tmp)
      break;
    echo '<b>'.$winning_category.'</b>';
    //setting category into variable_array
    reset($category_definition_array);
    foreach($category_definition_array as $variable_name)
      if(!isset($variable_array[$variable_name]) and $variable_array[$variable_name]!='')
        $variable_array[$variable_name]=$category_array[$category][$variable_name];
  }
}

//converts $ii into A..Z
function colSymbol($col_count)
{
  if($col_count<26)
    return(chr(ord('A')+$col_count));
  else
    return(colSymbol(floor($col_count/26)-1).chr(ord('A')+($col_count%26)));
}

function remove_directory($dir) {
  if ($handle = opendir("$dir")) {
   while (false !== ($item = readdir($handle))) {
     if ($item != "." && $item != "..") {
       if (is_dir("$dir/$item")) {
         remove_directory("$dir/$item");
       } else {
         unlink("$dir/$item");
         //echo " removing $dir/$item<br>\n";
       }
     }
   }
   closedir($handle);
   rmdir($dir);
   //echo "removing $dir<br>\n";
  }
}

function fill_content($content,$result_array) //: $content
{
    reset($result_array);
    foreach($result_array as $line)
    {
      $variable_array2=load_config(read($line,'sysGroupBy'));
      $last_tablerow=0;
      $current_pos=1;
      $tmp_kk=10000;
      while($current_pos)
      {
        if(!$tmp_kk--)
          break;
          
        //echo $current_pos.' '.substr($content,$current_pos-20,40).'<br>';
        
        $multi_pos=strpos($content,'[*',$current_pos);
        $single_pos=strpos($content,'[',$current_pos);
        $tablerow_pos=strpos($content,'<table:table-row>',$current_pos);

        $current_pos=0;
        $place_found='none';
        
        if($multi_pos>0)
        {
          $current_pos=$multi_pos;
          $place_found='multi';
        }
        
        if($single_pos>0 and ($current_pos==0 or $single_pos<$current_pos))
        {  
          $current_pos=$single_pos;
          $place_found='single';
        }
  
        if($tablerow_pos>0 and ($current_pos==0 or $tablerow_pos<$current_pos))
        {  
          $current_pos=$tablerow_pos;
          $place_found='tablerow';
        }

        if($current_pos>0)
        {
          if($place_found=='multi')
          {
            $start_pos=$current_pos+2;
            $end_pos=strpos($content,']',$current_pos);
            $variable_name=strip_tags(substr($content,$start_pos,$end_pos-$start_pos));
            //echo '<br>MULTI '.$variable_name;
            
            //if(read($line,$variable_name))
            if(isset($variable_array2[$variable_name]))
            {
              if($last_tablerow)
              {
                //duplicate row
                $startrow_pos=$last_tablerow;
                $endrow_pos=strpos($content,'</table:table-row>',$current_pos)+strlen('</table:table-row>');
                $content=substr($content,0,$endrow_pos).str_replace('[*','[',substr($content,$startrow_pos,$endrow_pos-$startrow_pos)).substr($content,$endrow_pos);

                $last_tablerow=0;
                $current_pos=$endrow_pos;
              }
              else
              {
                //add with comma
                $current_pos++;
              }
            }
            else
              $current_pos=$end_pos;
          }
          elseif($place_found=='single')
          {
            $start_pos=$current_pos+1;
            $end_pos=strpos($content,']',$current_pos);
            $variable_name=strip_tags(substr($content,$start_pos,$end_pos-$start_pos));
            //echo '<br>'.$variable_name;
            $show_value=read($line,$variable_name);
            //if($show_value)
            if(isset($variable_array2[$variable_name]))
            {
              //echo '<br>'.$variable_name;
              $template=$variable_array2[$variable_name]['template'];
              $show_mode=CFG_LOAD;
              if(file_exists(cfg_data_path.'/config/script/fld_'.$template.'.txt'))
              {
                include(cfg_data_path.'/config/script/fld_'.$template.'.txt');
              }
              else
              {
                if(!file_exists(cfg_data_path.'/script/fld_'.$template.'.txt'))
                  $template='';

                include(cfg_data_path.'/script/fld_'.$template.'.txt');
              }
              $content=substr($content,0,$start_pos-1).$show_value.substr($content,$end_pos+1);
              $current_pos=$start_pos-1;
            }
            else
              $current_pos=$end_pos;
          }
          elseif($place_found=='tablerow')
          {
            $last_tablerow=$current_pos;
            $current_pos++;
          }
        }
      }
    }
  return $content;
}

function clear_content($content) //: $content
{
  $last_tablerow=0;
  $current_pos=1;
  $tmp_kk=1000;
  while($current_pos)
  {
    if(!$tmp_kk--)
      break;
      
    //echo $current_pos.' '.substr($content,$current_pos-20,40).'<br>';
    
    $multi_pos=strpos($content,'[*',$current_pos);
    $single_pos=strpos($content,'[',$current_pos);
    $tablerow_pos=strpos($content,'<table:table-row>',$current_pos);
  
    $current_pos=0;
    $place_found='none';
    
    if($multi_pos>0)
    {
      $current_pos=$multi_pos;
      $place_found='multi';
    }
    
    if($single_pos>0 and ($current_pos==0 or $single_pos<$current_pos))
    {  
      $current_pos=$single_pos;
      $place_found='single';
    }
  
    if($tablerow_pos>0 and ($current_pos==0 or $tablerow_pos<$current_pos))
    {  
      $current_pos=$tablerow_pos;
      $place_found='tablerow';
    }
  
    if($current_pos>0)
    {
      if($place_found=='multi')
      {
        $start_pos=$current_pos+2;
        $end_pos=strpos($content,']',$current_pos);
        $variable_name=strip_tags(substr($content,$start_pos,$end_pos-$start_pos));
        //echo '<br>MULTI '.$variable_name;

        if($last_tablerow)
        {
          //duplicate row
          $startrow_pos=$last_tablerow;
          $endrow_pos=strpos($content,'</table:table-row>',$current_pos)+strlen('</table:table-row>');
          $content=substr($content,0,$startrow_pos).substr($content,$endrow_pos);

          $last_tablerow=0;
          $current_pos=$startrow_pos;
        }
        else
        {
          //add with comma
          $current_pos++;
        }
      }
      elseif($place_found=='single')
      {
        $start_pos=$current_pos+1;
        $end_pos=strpos($content,']',$current_pos);
        $variable_name=strip_tags(substr($content,$start_pos,$end_pos-$start_pos));
        //echo '<br>'.$variable_name;
        $content=substr($content,0,$start_pos-1).substr($content,$end_pos+1);
        $current_pos=$end_pos;
      }
      elseif($place_found=='tablerow')
      {
        $last_tablerow=$current_pos;
        $current_pos++;
      }
    }
  }

  return $content;
}


function create_document($document_name,$template_name,$result_array)
{
  $return_file='';

  if(substr(strtolower($template_name),-5)=='.file')
    $template_name=substr($template_name,0,-5);
  
  if(substr(strtolower($template_name),-4)=='.odt')
    $template_name=substr($template_name,0,-4);
    
  $name=purename($template_name);
  $ext='.odt';
  $preamble=substr(purename($name),0,1).'/'.substr(purename($name),0,2);
  $tmp_zip_name=date('Ymd').rand(1000,9999);
  //echo cfg_data_path.'/data/files/'.$preamble.'/'.$name.$ext.'.file';
  if(!file_exists(cfg_data_path.'/temp/zip/'.$tmp_zip_name.'/content.xml') and file_exists(cfg_data_path.'/data/files/'.$preamble.'/'.$name.$ext.'.file'))
  {
    addpath(cfg_data_path.'/temp/zip');
    copy(cfg_data_path.'/data/files/'.$preamble.'/'.$name.$ext.'.file',cfg_data_path.'/temp/zip/'.$tmp_zip_name.'.zip');
    $current_dir=getcwd();
    chdir(cfg_data_path.'/temp/zip');
    exec('unzip '.$tmp_zip_name.'.zip -d '.$tmp_zip_name);
    chdir($current_dir);  
  }
  
  if(file_exists(cfg_data_path.'/temp/zip/'.$tmp_zip_name.'/content.xml'))
  {
    $content=fill_content(file_get_contents(cfg_data_path.'/temp/zip/'.$tmp_zip_name.'/content.xml'),$result_array);
    $content=clear_content($content);

    $fp=fopen(cfg_data_path.'/temp/zip/'.$tmp_zip_name.'/content.xml','wb');
    fwrite($fp,$content);
    fclose($fp);
    //----------------------------------------------------------------------

    $content=fill_content(file_get_contents(cfg_data_path.'/temp/zip/'.$tmp_zip_name.'/styles.xml'),$result_array);
    $content=clear_content($content);

    $fp=fopen(cfg_data_path.'/temp/zip/'.$tmp_zip_name.'/styles.xml','wb');
    fwrite($fp,$content);
    fclose($fp);
    //----------------------------------------------------------------------

    // create document
    $current_dir=getcwd();
    chdir(cfg_data_path.'/temp/zip/'.$tmp_zip_name);
    exec('zip -r new.zip *');
    chdir($current_dir);

    $name=$document_name;
    $ext='.odt';
    $preamble=substr(purename($name),0,1).'/'.substr(purename($name),0,2);
    addpath(cfg_data_path.'/data/files/'.$preamble);
  
    $tmpcnt=0;
    $filename=$name.$ext;
    while(file_exists(cfg_data_path.'/data/files/'.$preamble.'/'.$filename.'.file'))
    {
      $tmpcnt++;
      $filename=$name.'_'.$tmpcnt.$ext;
    }

    if(file_exists(cfg_data_path.'/temp/zip/'.$tmp_zip_name.'/new.zip'))
      if(copy(cfg_data_path.'/temp/zip/'.$tmp_zip_name.'/new.zip',cfg_data_path.'/data/files/'.$preamble.'/'.$filename.'.file'))
        $return_file=$filename.'.file';
  }

  unlink(cfg_data_path.'/temp/zip/'.$tmp_zip_name.'.zip');
  remove_directory(cfg_data_path.'/temp/zip/'.$tmp_zip_name);
  
  return $return_file;
}

//
//    utf8 encoding validation developed based on Wikipedia entry at:
//    http://en.wikipedia.org/wiki/UTF-8
//
//    Implemented as a recursive descent parser based on a simple state machine
//    copyright 2005 Maarten Meijer
//
//    This cries out for a C-implementation to be included in PHP core
//
function valid_1byte($char) {
    if(!is_int($char)) return false;
    return ($char & 0x80) == 0x00;
}

function valid_2byte($char) {
    if(!is_int($char)) return false;
    return ($char & 0xE0) == 0xC0;
}

function valid_3byte($char) {
    if(!is_int($char)) return false;
    return ($char & 0xF0) == 0xE0;
}

function valid_4byte($char) {
    if(!is_int($char)) return false;
    return ($char & 0xF8) == 0xF0;
}

function valid_nextbyte($char) {
    if(!is_int($char)) return false;
    return ($char & 0xC0) == 0x80;
}

function valid_utf8($string) {
    $return_string='';
    $replace_char='?';
    $len = strlen($string);
    $i = 0;
    while( $i < $len )
    {
      $error=0;
      $last_ok_i=$i;
      $char_string='';
      $char_string .= substr($string, $i, 1);
      $char = ord(substr($string, $i++, 1));
      
      if ($char==0) 
      {
        continue;
      }
      if(valid_1byte($char)) {    // continue
          
      } else if(valid_2byte($char)) { // check 1 byte
          $char_string .= substr($string, $i, 1);
          if(!valid_nextbyte(ord(substr($string, $i++, 1))))
            $error=1;
      } else if(valid_3byte($char)) { // check 2 bytes
          $char_string .= substr($string, $i, 1);
          if(!valid_nextbyte(ord(substr($string, $i++, 1))))
            $error=1;
          $char_string .= substr($string, $i, 1);
          if(!valid_nextbyte(ord(substr($string, $i++, 1))))
            $error=1;
      } else if(valid_4byte($char)) { // check 3 bytes
          $char_string .= substr($string, $i, 1);
          if(!valid_nextbyte(ord(substr($string, $i++, 1))))
            $error=1;
          $char_string .= substr($string, $i, 1);
          if(!valid_nextbyte(ord(substr($string, $i++, 1))))
            $error=1;
          $char_string .= substr($string, $i, 1);
          if(!valid_nextbyte(ord(substr($string, $i++, 1))))
            $error=1;
      } else {
          $error=1; // 10xxxxxx occuring alone
      } // goto next char
      
      if(!$error)
        $return_string.=$char_string;
      else
      {
        $return_string.=$replace_char;
        $i=$last_ok_i+1;
      }
    }
    return $return_string; // done
}


// Returns true if $string is valid UTF-8 and false otherwise.
function is_utf8($string) {
  
   // From http://w3.org/International/questions/qa-forms-utf-8.html
   return preg_match('%^(?:
         [\x09\x0A\x0D\x20-\x7E]            # ASCII
       | [\xC2-\xDF][\x80-\xBF]            # non-overlong 2-byte
       |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
       | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
       |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
       |  \xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
       | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
       |  \xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
   )*$%xs', $string);
  
} // function is_utf8
 

function utf8($string)
{
  if(!is_utf8($string))
  {
    //echo ' FALSE';
    $string_converted=valid_utf8($string);
    if(is_utf8($string_converted))
    {
      //echo '-TRUE';
      $string=$string_converted;
    }
    else
    {
      //echo '-FALSE';
      $string='?';

      /*
      $string_converted=utf8_encode($string);
      if(is_utf8($string_converted))
      {
        echo '-TRUE';
        $string=$string_converted;
      }
      else
      {
        echo '-FALSE';
        $string='?';
      }
      */
    }
  }
  return $string;
}


// by SkyEye
function dircopy($srcdir, $dstdir, $bakdir, $verbose = false) 
{
  $num = 0;
  if(!is_dir($dstdir)) mkdir($dstdir);
  if(!is_dir($bakdir)) mkdir($bakdir);
  if($curdir = opendir($srcdir)) {
    while($file = readdir($curdir)) {
      if($file != '.' && $file != '..') {
        $srcfile = $srcdir . '/' . $file;
        $dstfile = $dstdir . '/' . $file;
        $bakfile = $bakdir . '/' . $file;
        if(is_file($srcfile)) {
          if(is_file($dstfile)) $ow = filemtime($srcfile) - filemtime($dstfile); else $ow = 1;
          if($ow > 0) {
            //if($verbose) echo 'Copying '.$srcfile.' to '.$dstfile.'...'.CRLF;
            if(file_exists($dstfile))
              if(copy($dstfile, $bakfile))
              {
                //if($verbose) echo ' BACKUP'.CRLF;
              }
              else
              {
                echo 'Backup not possible';
                exit;
              }

            if(copy($srcfile, $dstfile)) {
              touch($dstfile, filemtime($srcfile)); $num++;
              //if($verbose) echo ' OK'.CRLF;
              if($verbose) echo $srcfile.' updated<br />';
            }
            else 
              echo 'Error: File '.$srcfile.' could not be copied!'.CRLF;
          }                  
        }
        else if(is_dir($srcfile)) {
          $num += dircopy($srcfile, $dstfile, $bakfile, $verbose);
        }
      }
    }
    closedir($curdir);
  }
  return $num;
}

function import_data($file_path,$config)
{
  if(file_exists($file_path))
  {
    addpath(cfg_data_path.'/data/import');

    $name=basename($file_path);
    $ext=strtolower(substr($name,-4));
  
    $tmpcnt=0;
    $filename=substr($name,0,-4).''.$tmpcnt.$ext;
    while(file_exists(cfg_data_path.'/data/import/'.$filename))
    {
      $tmpcnt++;
      $filename=substr($name,0,-4).''.$tmpcnt.$ext;
    }
  
    
    if(rename($file_path, cfg_data_path.'/data/import/'.$filename))
    {
      //$import_sign='';
      //$import_sign.=substr($_FILES['odb_file']['name'].str_repeat(' ',50),0,50); //50 chars
      //$import_sign.=substr(USERNAME.str_repeat(' ',50),0,50); //50 chars
      //$import_sign.='_ODB_IMPORT_END_OF_FILE_SIGN'; //28 chars
  
      $content=file_get_contents(cfg_data_path.'/data/import/'.$filename);
  
      //$fp=fopen(cfg_data_path.'/config/import/'.$filename,'a');
      //fwrite($fp,$import_sign); //name, user, sign eof
      //fclose($fp);
  
      $extension=substr($name,-3);
      if(file_exists(cfg_data_path.'/config/script/imp_'.$extension.'.txt'))
      {
        include(cfg_data_path.'/config/script/imp_'.$extension.'.txt');
      }
      else
      {
        include(cfg_data_path.'/script/imp_'.$extension.'.txt');
      }

      return (substr($filename,0,-4));
    }
  }
  else
  {
    return 0;
  }
}

function get_mime_type(&$structure)
{
  $primary_mime_type = array("TEXT", "MULTIPART","MESSAGE", "APPLICATION", "AUDIO","IMAGE", "VIDEO", "OTHER");
  if($structure->subtype)
  {
    return $primary_mime_type[(int) $structure->type] . '/' .$structure->subtype;
  }
  return "TEXT/PLAIN";
}

function get_part($stream, $msg_number, $mime_type, $structure = false,$part_number = false)
{

  if(!$structure)
  {
    $structure = imap_fetchstructure($stream, $msg_number);
  }

  if($structure)
  {
    if($mime_type == get_mime_type($structure))
    {
      if(!$part_number)
      {
        $part_number = "1";
      }
      
      $text = imap_fetchbody($stream, $msg_number, $part_number);
      if($structure->encoding == 3)
      {
        $text=imap_base64($text);
      }
      elseif($structure->encoding == 4)
      {
        $text=imap_qprint($text);
      }

      //print_r($structure);

      
      if($structure->ifparameters and $structure->parameters[0]->attribute=='CHARSET')
      {
        //echo $structure->parameters[0]->value;
        $text=conv($text,$structure->parameters[0]->value);
      }
      
      return $text;
    }

    if($structure->type == 1) /* multipart */
    {
      while(list($index, $sub_structure) = each($structure->parts))
      {
        if($part_number)
        {
          $prefix = $part_number . '.';
        }
        $data = get_part($stream, $msg_number, $mime_type, $sub_structure,$prefix.($index + 1));
        if($data)
        {
          return $data;
        }
      } // END OF WHILE
    } // END OF MULTIPART
  } // END OF STRUTURE

  return false;
} // END OF FUNCTION



function import_emails($ServerName,$UserName,$PassWord)
{
  //read seen mails list
  $bagaccess_array['all']=3;
  $tmp_search_array=search("sysGroupBy=email");
  $seen_mail_array=array();
  reset($tmp_search_array);
  while(list($tmp,$tmp_line)=each($tmp_search_array))
  {
    $seen_mail_array[trim(read($tmp_line,'Message Number'))]=1;
  }
  $tmp_search_array=array();

  $mbox = imap_open($ServerName, $UserName,$PassWord);

  if($mbox)
  {
    echo CRLF.'Mailbox opened';

    $hdr = imap_check($mbox);
    $msgCount = $hdr->Nmsgs;

    echo CRLF.'Mailbox check: '.$msgCount.' messages';
    
    //-------------------------------------------------------------------------------
    for($msgno=1;$msgno<=$msgCount;$msgno++)
    {
      echo CRLF.'Msg: '.$msgno;ob_flush();
      // GET TEXT/HTML BODY
      $dataTxt = get_part($mbox, $msgno, "TEXT/PLAIN");
      $dataHtml = get_part($mbox, $msgno, "TEXT/HTML");
  
      if ($dataHtml != '')
        $msgBody = html_entity_decode(strip_tags($dataHtml));
      else
        $msgBody = $dataTxt;
  
      //$msgBody=conv($msgBody,'iso-8859-2');
  
      // get the header info for the message
      $_theHeader=imap_headerinfo($mbox,$msgno);
      
      $variable_array=array();
      $variable_array['Message Number']=$_theHeader->message_id;  
      $variable_array['Message Number']=str_replace('<','',$variable_array['Message Number']);
      $variable_array['Message Number']=str_replace('>','',$variable_array['Message Number']);
      $variable_array['Message Number']=str_replace('&lt;','',$variable_array['Message Number']);
      $variable_array['Message Number']=str_replace('&gt;','',$variable_array['Message Number']);
      $variable_array['Message Number']=str_replace('$',' ',$variable_array['Message Number']);


      //read only unseen mails   
      if($seen_mail_array[$variable_array['Message Number']]==1)
        continue;
      else
        $seen_mail_array[$variable_array['Message Number']]=1;


      $tmp_from=array();
      while (list($k,$v)=each($_theHeader->from))
      {
        if (!empty($v->personal))
        {
          $strHead=$v->personal;
          $_address="".$strHead." <".$v->mailbox."@".$v->host.">";
        }
        else
          $_address=$v->mailbox."@".$v->host;
        $tmp_from[]=$_address;
      }
      $from=implode(',',$tmp_from);
      
      $tmp_to=array();
      if (is_array($_theHeader->to))
      {
        while(list($k,$v)=each($_theHeader->to))
        {
          if(!empty($v->personal))
          {
            $strHead=$v->personal;
            $_address="".$strHead." <".$v->mailbox."@".$v->host.">";
          }
          else
            $_address=$v->mailbox."@".$v->host;
          $tmp_to[]=$_address;
        }
      } else
        $tmp_to[]=$_theHeader->to;
      $to=implode(',',$tmp_to);
  
      $tmp_cc=array();
      if(is_array($_theHeader->cc))
      {
        while(list($k,$v)=each($_theHeader->cc))
        {
          if(!empty($v->personal))
          {
            $strHead=$v->personal;
            $_address="".$strHead." <".$v->mailbox."@".$v->host.">";
          }
          else
            $_address=$v->mailbox."@".$v->host;
          $tmp_cc[]=$_address;
        }
      }
      else
        $tmp_cc[]=$_theHeader->cc;
      $cc=implode(",",$_cc);
      
      $variable_array['sysGroupBy']='email';
      $variable_array['MyBag']='emails';
  
  
      $variable_array['Message References']=$_theHeader->references;  
      $variable_array['Message References']=str_replace('<','',$variable_array['Message References']);
      $variable_array['Message References']=str_replace('>','',$variable_array['Message References']);
      $variable_array['Message References']=str_replace('&lt;','',$variable_array['Message References']);
      $variable_array['Message References']=str_replace('&gt;','',$variable_array['Message References']);

      //echo CRLF.'in_reply_to:'.$_theHeader->in_reply_to;
      //echo CRLF.'followup_to:'.$_theHeader->followup_to;
      //echo CRLF.'references:'.$_theHeader->references;
      
  
      $variable_array['Email Status']='New';
      $variable_array['Send Date']=date('Ymd',$_theHeader->udate);
      $variable_array['Send Time']=date('H:i',$_theHeader->udate);
      $variable_array['Send From']=imap_utf8($from);
      $variable_array['Send To']=imap_utf8($to);
      $variable_array['Send CC']=imap_utf8($cc);
  
      $variable_array['Send Subject']=imap_utf8($_theHeader->subject);
      $variable_array['Send Body']=imap_utf8($msgBody);
      
      $struct = imap_fetchstructure($mbox,$msgno);
      $contentParts = count($struct->parts);

      $attachment_number=1;
      for ($ii=0;$ii<=$contentParts;$ii++)
      {
        $structure = imap_bodystruct($mbox,$msgno,$ii);
        
        if($structure->ifdisposition and $structure->disposition=='ATTACHMENT')
        {
          //print_r($structure);

          $strFileName='attachment';
          if($structure->ifdparameters and $structure->dparameters[0]->attribute=='FILENAME')
            $strFileName = imap_utf8($structure->dparameters[0]->value);

          $fileContent = imap_fetchbody($mbox,$msgno,$ii);
                   
          if($structure->encoding == 3)
            $fileContent=imap_base64($fileContent);
          elseif($structure->encoding == 4)
            $fileContent=imap_qprint($fileContent);

          $ext=strtolower(substr($strFileName,strrpos($strFileName,'.')));
          $name=purename(substr($strFileName,0,strrpos($strFileName,'.')));
          $preamble=substr(purename($name),0,1).'/'.substr(purename($name),0,2);
          addpath(cfg_data_path.'/data/files/'.$preamble);
        
          $tmpcnt=0;
          $filename=$name.$ext;
          while(file_exists(cfg_data_path.'/data/files/'.$preamble.'/'.$filename.'.file'))
          {
            $tmpcnt++;
            $filename=$name.'_'.$tmpcnt.$ext;
          }
          $variable_array['Send Attach '.$attachment_number]=$filename.'.file';
          echo CRLF.'Attachment '.$attachment_number;

          $fp=fopen(cfg_data_path.'/data/files/'.$preamble.'/'.$filename.'.file','wb');
          fwrite($fp,$fileContent);
          fclose($fp);
          
          $attachment_number++;
        }
      }

      $variable_array['sysComment']='Email received';
      $variable_array['sysModInfo']=date('Ymd H:i').' Mailbot';
      $variable_array['sysId']='0';
      $variable_array['sysValidFrom']=date('Ymd');
      $variable_array['sysValidTo']=99991231;
      $variable_array['sysValid']=1;
      $variable_array['sysId']='';
      $variable_array['MyBag']='emails';

      //USEREXIT OnSave
      $userexit='onsave';
      if(file_exists(cfg_data_path.'/config/userexit/exit_'.$userexit.'.txt'))
      {
        include(cfg_data_path.'/config/userexit/exit_'.$userexit.'.txt');
      }
      else
      {
        include(cfg_data_path.'/script/userexit/exit_'.$userexit.'.txt');
      }

      save($variable_array);
      //echo CRLF.' MAILBOT email='.$variable_array['Send Subject'];
    }
  }
  else
  {
    echo CRLF.'Cannot open mailbox';
  }
  imap_close($mbox);
}

if (!function_exists("stripos")) {
  function stripos($str,$needle) {
   return strpos(strtolower($str),strtolower($needle));
  }
}


init();
?>
Return current item: OpenBizMap