<?php
    /* ************************************************************************
    * /usr/share/doc/capi2text/incl/capi2text-ajax.php
    *
    * Copyright (c) 2009-2024  Juergen Edner, juergen(at)eisfair(dot)org>
    *                          Rolf Bensch, rolf(at)bensch-net(dot)de
    *
    * Creation:     2016-08-25  jed
    * Last Update:  $Id: capi2text-ajax.php 44716 2017-01-22 17:17:43Z jed $
    *
    * 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.
    **************************************************************************
    */

    header('content-type: text/html; charset=utf-8;');

    error_reporting(E_ALL);         // if "require" fails

    /* capit2text AJaX-Routinen */
    require('capi2text-default-params.inc');
    require("../capi2text-params.inc");
    require('capi2text-functions.php');

    setlocale(LC_ALL, $date_locale);

    $ret = array();

    if ($debug) {
      	error_reporting(E_ALL);
    } else {
			// disable error handling in production mode
			error_reporting(0);
			// suppress php Warning|Notice|Error in output
			ob_start();       
    }



    try {
        if (! isset($_POST['do'])) throw new Exception("AJaX: missing parameter");
        $do     = $_POST["do"];

        // create config-dialog
        if ($do == "getDlgKonfigMSN" ) {
            global $msn_sort_order;
            $msn_sort_order = (isset($_POST["sort"])) ? $_POST["sort"] : $msn_sort_order;

            $arr_msn = getMsnList();

            $tr = " <div class='ui-widget-header tr'>
                    <div class='td'>MSN</div>
                    <div class='td'>Ersetzung</div>
                    <div class='td'>TF</div>
                    <div class='td'>HF</div>
                    </div>";

            foreach ($arr_msn as $msn => $val) {
                $xMSN   = str_replace("*","_", $msn);

                $fcolor = color_name_to_hex($val['fcolor']); // color out of msn-replace.txt
                $bcolor = color_name_to_hex($val['bcolor']);

                $style  = "style='color:$fcolor; background-image: linear-gradient(to bottom, $bcolor, transparent 70%)'";
                $msn    = $val['msn'];

                $tr .= "<div class='tr'>
                        <div class='td msn$xMSN' >{$val['msn']}</div>
                        <div class='td msn$xMSN' >{$val['desc']}</div>
                        <div class='td'><div class='selcolor fg' data-msn='$msn' data-defaultvalue='$fcolor'></div></div>
                        <div class='td'><div class='selcolor bg' data-msn='$msn' data-defaultvalue='$bcolor'></div></div>
                        </div>";
            }
            $ret['params']['reset']     = $config_reset;
            $ret['params']['ok']        = $config_ok;

            $ret['success']=$tr;
            die(json_encode($ret));
        }

        // create phonelist tbody
        if ($do == "getStatistik" ) {
            global $msn_sort_order, $flags;
            $msn_sort_order = $_POST['msnsort'];

            $arr_msn = getMsnList();

            $cf = fopen($call_file, 'r');
            if (! $cf) throw new Exception("Cannot open file '$call_file'!");

            $i = 0;
            while (!feof($cf)) {
                $line = rtrim(fgets($cf, 500));
                if (strlen($line) > 0) {
		           
						 $arrLine = array_pad(explode("\t",$line ), 12, '');
						 
						 $arr_phone_calls[$i]['date']			= $arrLine[0];
						 $arr_phone_calls[$i]['time']			= $arrLine[1];
						 $arr_phone_calls[$i]['from']			= $arrLine[2];
						 $arr_phone_calls[$i]['to']			= $arrLine[3];
						 $arr_phone_calls[$i]['name']			= $arrLine[4];
						 $arr_phone_calls[$i]['address']		= $arrLine[5];
						 $arr_phone_calls[$i]['to_replaced']= $arrLine[6];
						 $arr_phone_calls[$i]['flag_file']	= $arrLine[7];
						 $arr_phone_calls[$i]['fcolor']		= $arrLine[8];
		             $arr_phone_calls[$i]['bcolor']		= $arrLine[9];
		             $arr_phone_calls[$i]['direction']	= $arrLine[10];
		             $arr_phone_calls[$i]['duration']	= $arrLine[11];

		             // suppress loginfo, like '[Ws]' etc.
		             if ($no_loginfo && preg_match("/ \[[CLW]s*\]/", $arr_phone_calls[$i]['name'])) {
		                 $arr_phone_calls[$i]['name'] = preg_replace("/ \[[CLW]s*\]/", "", $arr_phone_calls[$i]['name']);
		             }

		             // replace MSN by description
		             $msn_search = $arr_phone_calls[$i]['to'];
  		             if ( array_key_exists($msn_search, $arr_msn)) {
				          $arr_phone_calls[$i]['to_replaced'] = $arr_msn[$msn_search]['desc'];
				          $arr_phone_calls[$i]['fcolor']      = $arr_msn[$msn_search]['fcolor'];
				          $arr_phone_calls[$i]['bcolor']      = $arr_msn[$msn_search]['bcolor'];
						 }
	
		             // add flag file name
		             $arr_phone_calls[$i]['flag_file'] = find_flag($arr_phone_calls[$i]['from']);
		             if (! $flags) {
		                  // add country abbreviation
		                  $arr_phone_calls[$i]['country_abbr'] = find_country_abbr($arr_phone_calls[$i]['from']);
		             }

		             // add country name
		             $arr_phone_calls[$i]['country_name']  = find_country_name($arr_phone_calls[$i]['from']);

		             $i++;
                }
            }
            $i--;

            fclose($cf);

            $maxcount   = $i;
            $firstDate  = strtotime($arr_phone_calls[0]['date']);
            $lastDate   = strtotime($arr_phone_calls[$maxcount]['date']);
            $diff       = floor(($lastDate -$firstDate)/3600/24) +1 ;
            $average    = number_format($maxcount / $diff,0);

            $firstDate  = date("d.m.Y",$firstDate);
            $lastDate   = date("d.m.Y",$lastDate);

            $Tab1   = "<table style='width:100%; height:2.2em'>
                           <tr>
                               <td>Zeitraum: $firstDate - $lastDate</td>
                               <td>$maxcount Anrufe in $diff Tagen</td>
                               <td class='right'>&Oslash; $average Anrufe pro Tag</td>
                           </tr>
                       </table>";

            foreach ($arr_msn as $nbr=>$msn_replace) {
                $z = 0;
                $calls = 0;
                $calls_yesterday = 0;
                $calls_lastweek = 0;
                $calls_wo_today = 0;
                $calls_per_day = 0;
                foreach ( $arr_phone_calls as $zeile ) {
                    if ($zeile['to']==$nbr) {
                        // overall sum
                        $calls++;
                        // sum of calls without todays
                        if ( $zeile['date']<date('Y-m-d', time()) ) $calls_wo_today++;
                        // yesterday sum
                        if ( $zeile['date']==date('Y-m-d', time()-(60*60*24)) ) $calls_yesterday++;
                        // last week sum
                        if ( date('W',strtotime($zeile['date']))==date('W',time()-(60*60*24*7)) ) $calls_lastweek++;
                    }
                    $z++;
                }
                $average = ($calls_wo_today>0 && $diff>0) ? number_format($calls_wo_today/$diff,2) : 0;
                $numbers[$nbr] = array('days'=>$diff, 'calls'=>$calls, 'avg'=>$average, 'yesterday'=>$calls_yesterday, 'lastweek'=>$calls_lastweek) ;
            }

            $thead2 = " <tr>
                            <th>Teilnehmer-Anschluss</th>
                            <th>Gestern</th>
                            <th>Letzte Woche (KW ".date('W',time()-(60*60*24*7)).")</th>
                            <th>Tagesschnitt</th>
                            <th>Gesamter Zeitraum (Anteil) </th>
                       </tr>";

            $tbody2 = "";
            foreach ($arr_msn as $nbr=>$msn_replace) {
                $bar        = bar($maxcount,$numbers[$nbr]['calls']);
                $tbody2 .= " <tr>
                                <td>{$arr_msn[$nbr]['desc']}</td>
                                <td>{$numbers[$nbr]['yesterday']}</td>
                                <td>{$numbers[$nbr]['lastweek']}</td>
                                <td>{$numbers[$nbr]['avg']}</td>
                                <td><div>{$numbers[$nbr]['calls']}</div> $bar</td>
                            </tr>";
                $i++;
            }

            $Tab2 = "<table style='width:100%'>$thead2 $tbody2</table>";
            $ret['params']['preview'] = $statistic_preview;
            $ret['params']['ok']      = $statistic_ok;
            $ret['success']           = "$Tab1 $Tab2";

            die(json_encode($ret));
        }

        // create phonelist tbody
        if ($do == "getTbody" ) {
            $lastUpdate     = (isset($_POST['lastUpdate']))     ? $_POST['lastUpdate']   : "0";
            $filter_msn     = (isset($_POST['filter_msn']))     ? $_POST['filter_msn']   : "0";
            $filter_days    = (isset($_POST['filter_days']))    ? $_POST['filter_days']  : "-1";
            $filter_inout   = (isset($_POST['filter_inout']))   ? $_POST['filter_inout'] : "INOUT";
            $listfilter     = (isset($_POST['listfilter']))     ? $_POST['listfilter']   : "0";
            $flags          = (isset($_POST['flags']))          ? ($_POST['flags'] == "true")         : (! $no_flags);
            $fromlink       = (isset($_POST['fromlink']))       ? ($_POST['fromlink'] == "true")      : (! $no_from_link);
            $calldirection  = (isset($_POST['calldirection']))  ? ($_POST['calldirection'] == "true") : (! $no_call_direction);
            $callduration   = (isset($_POST['callduration']))   ? ($_POST['callduration'] == "true")  : (! $no_call_duration);
            $viewmode   	 = (isset($_POST['viewmode']))   	 ? ($_POST['viewmode'])  				 	: "Desktop";

            if (! $call_file)              throw new Exception("getTbody: 'call_file' not defined");
            if (! file_exists($call_file)) throw new Exception("getTbody: '$call_file' not found");

            $tbody       = '';
            $callFileTS  = filemtime($call_file);
            $needUpdate  = ($lastUpdate < $callFileTS);

            if ($needUpdate) {
                $ret['needUpdate'] = $callFileTS;
                $ret['filter']     = "Filter: Days: $filter_days; MSN: ".json_encode($filter_msn)."; INOUT: $filter_inout";

                // get MSN list for select-box (filter)
                $arr_msn = getMsnList();

                // read call logfile
                //
                // 'date'         -> date stamp, e.g. '2012-03-13'
                // 'time'         -> time stamp, e.g. '14:15:59'
                // 'from'         -> incoming phone number, e.g. '0221334455'
                // 'to'           -> called MSN (extension), e.g. '31'
                // 'name'         -> name of caller, e.g. 'Hans Mueller'
                // 'address'      -> address of caller, e.g. 'Hauptstr. 111, 41472 Neuss, DE'
                // 'calldirection'-> IN/OUT
                // 'callduration' -> [m:ss]
                // 'to_replaced'  -> called MSN replacement string, e.g. '31 - fax machine'
                // 'flag_file'    -> path and name of country flag, e.g. './png/country-49.png'
                // 'country_abbr' -> abbreviation of the country, e.g. 'DE'
                // 'country_name' -> name of the country, e.g. 'Deutschland'
                // 'fcolor'       -> individual foreground color for this call, based on the MSN, e.g. '#ffee00'
                // 'bcolor'       -> individual background color for this call, based on the MSN, e.g. '#ffee00'

                $cf = fopen($call_file, 'r');
                if (! $cf) throw new Exception("Cannot open file '$call_file'!");

                $i = 0;
                while (!feof($cf)) {
                    // write calls to array
                    $linedata = explode("\t",rtrim(fgets($cf, 500)));
                         
                    $arrLine = array_pad($linedata, 12, '');
                    
                    $arr_phone_calls[$i]['date']			= $arrLine[0];
                    $arr_phone_calls[$i]['time']			= $arrLine[1];
                    $arr_phone_calls[$i]['from']			= $arrLine[2];
                    $arr_phone_calls[$i]['to']				= $arrLine[3];
                    $arr_phone_calls[$i]['name']			= $arrLine[4];
                    $arr_phone_calls[$i]['address']		= $arrLine[5];
                    $arr_phone_calls[$i]['direction']		= $arrLine[6];
                    $arr_phone_calls[$i]['duration']		= $arrLine[7];
                    $arr_phone_calls[$i]['to_replaced']	= $arrLine[8];
                    $arr_phone_calls[$i]['flag_file']		= $arrLine[9];
                    $arr_phone_calls[$i]['fcolor']			= $arrLine[10];
                    $arr_phone_calls[$i]['bcolor'] 		= $arrLine[11];

                    $arr_phone_calls[$i]['direction'] = (strlen($arr_phone_calls[$i]['direction']) == 0) ? "IN" : $arr_phone_calls[$i]['direction'];
                    $arr_phone_calls[$i]['cntFields'] = count($linedata);

                    // suppress loginfo, like '[Ws]' etc.
                    if ($no_loginfo && preg_match("/ \[[CLW]s*\]/", $arr_phone_calls[$i]['name'])) {
                        $arr_phone_calls[$i]['name'] = preg_replace("/ \[[CLW]s*\]/", "", $arr_phone_calls[$i]['name']);
                    }

                    // replace MSN by description
                    
                    $arr_phone_calls[$i]['from_replaced'] = "";

	                 if ( $arr_phone_calls[$i]['direction'] == "IN") {
	                     $msn_search = $arr_phone_calls[$i]['to'];
				  				if ( array_key_exists($msn_search, $arr_msn)) {
		                     $arr_phone_calls[$i]['to_replaced']     = $arr_msn[$msn_search]['desc'];
		                     $arr_phone_calls[$i]['from_replaced']   = $arr_phone_calls[$i]['from'];
		                  }
	                 } else {
	                     $msn_search = $arr_phone_calls[$i]['from'];
  				  				if ( array_key_exists($msn_search, $arr_msn)) {
			                  $arr_phone_calls[$i]['from_replaced']   = $arr_msn[$msn_search]['desc'];
			                  $arr_phone_calls[$i]['to_replaced']     = $arr_phone_calls[$i]['to'];
	                 		}
	                 }

                    if ($arr_phone_calls[$i]['from_replaced'] == "") $arr_phone_calls[$i]['from_replaced'] = $arr_phone_calls[$i]['from'];
                    if ($arr_phone_calls[$i]['to_replaced']   == "") $arr_phone_calls[$i]['to_replaced']   = $arr_phone_calls[$i]['to'];
                    
                    if ( array_key_exists($msn_search, $arr_msn)) {
		                 $arr_phone_calls[$i]['fcolor']              = $arr_msn[$msn_search]['fcolor'];
		                 $arr_phone_calls[$i]['bcolor']              = $arr_msn[$msn_search]['bcolor'];
						  }

                    // add flag file name
                    $check_number = ( $arr_phone_calls[$i]['direction'] == "IN") ? $arr_phone_calls[$i]['from'] : $arr_phone_calls[$i]['to'] ;
                    $arr_phone_calls[$i]['flag_file'] = find_flag($check_number);

                    if (! $flags) {
                        // add country abbreviation
                        $arr_phone_calls[$i]['country_abbr'] = find_country_abbr($check_number);
                    }

                    // add country name
                    $arr_phone_calls[$i]['country_name']  = find_country_name($check_number);

                    $i++;
                }
                $i--;

                $ret['maxcount'] = $i;

                fclose($cf);

                // output data in reverse order
                $arr_phone_calls=array_reverse($arr_phone_calls,true);

                $line_count = 0;
                $prevDate   = strtotime("1970-01-02");

                $filter_msn = json_decode($filter_msn,true);
                $filter_msn = str_replace("*","_",$filter_msn);

                foreach($arr_phone_calls as $phone_call) {
                    if ( $phone_call['date'] != "" ) {
                        // not empty, go on ...
                        $searchTO   = str_replace('*','_',$phone_call['to']);
                        $searchFROM = str_replace('*','_',$phone_call['from']);

                        $searchMSN	= ($phone_call['direction'] == "IN") ? $searchTO : $searchFROM;
								$equal = ($filter_msn == "" || sizeof($filter_msn) == 0  || in_array($searchMSN,$filter_msn));
						
                        if ( $equal) {
                            if (stripos($filter_inout, $phone_call['direction']) !== false ) {
                                // valid selection, go on ...
                                $NoButton   = ($phone_call['from'] == $call_unknown);   // no caller-number
                                $EditButton = ($NoButton) ? "" : "<img src='./pics/edit-number.png' title='edit' alt='edit entry'>";

                                // toggle background color
                                $trclass  = "call";                                            // default backgroud-color
                                if ($phone_call['direction'] == "IN") {                        // set color for MSN if defined in msn-replace
                                    $trclass .= " msn" . str_replace("*","_",$phone_call['to']);
                                } else {
                                    $trclass .= " msn" . str_replace("*","_",$phone_call['from']);
                                }
                                $trclass .= ($EditButton == "") ? "" : " editable";

                                $flag            = ($flags) ? "<img src='{$phone_call['flag_file']}' alt=''>" : $phone_call['country_abbr'] ;
                                $callFrom        = $phone_call['from'];
                                $callFromReplace = $phone_call['from_replaced'];
                                $calltime        = $phone_call['time'];
                                $callToReplace   = $phone_call['to_replaced'];
                                $callTo          = $phone_call['to'];
                                $callName        = $phone_call['name'];
                                $callAddr        = $phone_call['address'];
                                $cntFields       = $phone_call['cntFields'];

                                $callName        = (mb_detect_encoding($callName,'UTF-8', true)) ? $callName : utf8_encode($callName) ;
                                $callAddr        = (mb_detect_encoding($callAddr,'UTF-8', true)) ? $callAddr : utf8_encode($callAddr) ;;

                                $callAddr        = ($callAddr == '') ? $callName : "$callName, $callAddr";
                                $country_name    = $phone_call['country_name'];

                                // print call data        
                                $data_duration   = ""; $tdCall_duration = ""; $data_inout="";
                                $tdCall_duration = ($callduration)  ? "<td>{$phone_call['duration']}</td>" : "<td></td>";

                                if ($cntFields == 8) {
                                    $data_duration  = "data-duration=\"{$phone_call['duration']}\"";
                                    $data_inout     = "data-inout=\"{$phone_call['direction']}\"";
                                } else {
                                		$data_inout     = "data-inout='IN'";
                                }

                                $td3class 	= ($calldirection) ? "call_{$phone_call['direction']}" : '';
                                $td3class 	= ($phone_call['duration'] == '0:00') ? $td3class.'_FAILED' : $td3class;
                                $td3class 	= "class='$td3class'";
                                
                                $thisnumber	= ($phone_call['direction'] == "IN") ? $callFrom : $callTo	;	

										  if ($listfilter == 0 || $listfilter == $callFromReplace || $listfilter == $callToReplace) {
											  if ($prevDate <> strtotime($phone_call['date'])) {
		                                 $prevDate = strtotime($phone_call['date']);

		                                 // calculate the number of days
		                                 $callDate   = strtotime($phone_call['date']);
		                                 $dateDiff   = floor((strtotime("now") - $callDate)/3600/24);
		                                 if ($filter_days > -1 && $dateDiff > $filter_days ) break;

		                                 // print date header once per day
		                                 $dummyDatum = strftime($date_format,$callDate);
		                                 $tbody     .= "<tr class='dateline'><td class='headline left ui-widget-header' colspan='7'>&nbsp;$dummyDatum</td></tr>\n";
		                                 $line_count = 0;
		                             }
										  
		                             $tbody .= " <tr class='$trclass' data-cntfields='$cntFields' $data_duration $data_inout data-nbr='$thisnumber' data-date='$dummyDatum'>
		                                             <td><div class='ellipsis center'>$calltime</div></td>
		                                             <td title='$country_name'>$flag</td>
		                                             <td $td3class data-nbr='$callFrom'><div class='ellipsis left'>$callFromReplace</div></td>
		                                             <td data-nbr='$callTo'><div class='ellipsis left'>$callToReplace</div></td>
		                                             <td ><div class='left ellipsis'>$callAddr</div></td>
		                                             $tdCall_duration
		                                             <td >$EditButton</td>
		                                         </tr>";

		                              $line_count++;
                                 }
                            }
                        }
                    }
                }   // end of foreach

                $tbody = ($tbody == "") ? "<tr><td colspan='7' style='text-align:center'>$text_nbr_not_found</td></tr>" : $tbody;
            } // need update

         // if ($callduration) $ret['call_duration']=$call_duration;

            $ret['success'] = remove_tabs_and_crs($tbody);
        } // end of getTbody()

        if ($do == "save") {
            $_POST  	= str_replace(',', ' ',$_POST);  // replace commata by whitespace
            $_POST  	= array_map('trim', $_POST);     // trim strings
				$_POST 	= str_replace(array("\r", "\n", "\t"), '', $_POST);

            $nbr     = preg_replace('/[^0-9]/', '', $_POST['nbr']);
            $name    = $_POST['name'];
            $street  = $_POST['street'];
            $zip     = $_POST['zip'];
            $city    = $_POST['city'];
            $country = $_POST['country'];
            $addr    = "$street, $zip $city, $country";
            $direction  = (isset($_POST['direction'])) ? $_POST['direction'] : false;
            $duration   = (isset($_POST['duration']))  ? $_POST['duration']  : false;

            // validation of entered name and phone number
            if ($name == '') throw new Exception($data_name_missing);
            if ($nbr  == '') throw new Exception($data_number_missing);

            // ### append to phonelist ###

            // not an empty entry - make sure that number is in international format
            $nbr = preg_replace('/^0([0-9][0-9]+)/', "00$default_ccode$1", $nbr);

            if (! is_writable($phonelist_file)) throw new Exception("File $phonelist_file not writeable.");

            // read phonelist content from file
            $pf_content = file_get_contents($phonelist_file);
            $pf_content = explode("\n",$pf_content);

            // replace matching entries
            $pf_content = preg_replace("/^$nbr\t.*/", "$nbr\t$name\t$addr", $pf_content,-1,$anzahl);

				// append entry if not matched
            if ( $anzahl < 1 ) $pf_content[] = "$nbr\t$name\t$addr\n";
				
				// remove empty lines
				$pf_content = array_filter($pf_content);
				
            // throw new Exception(print_r($pf_content));
            // write phonelist content to file
            $pf_content = implode("\n",$pf_content);

            $bak_file   = "/tmp/" . basename($phonelist_file) . ".edit";
            file_put_contents($bak_file, $pf_content);
            if (! file_exists($bak_file)) throw new Exception("'$bak_file' not created.\n\nCannot update $phonelist_file");
            if (filesize($bak_file) > 5) {
                 $phonelistPath = dirname($phonelist_file);
                 clearstatcache();
                 $phonelistPerms = substr(sprintf('%o',fileperms($phonelistPath)), -4);//  & 0777;
                 if (!copy($bak_file, $phonelist_file)) throw new Exception("Cannot overwrite $phonelist_file. ($phonelistPath = $phonelistPerms)");
            }
            unlink($bak_file);

            // ### update call_file ###
            if (! is_writable($call_file)) throw new Exception("File $call_file not writeable");
            // read content of call_file
            $cf = fopen($call_file, 'r');
            if (! $cf) throw new Exception("Cannot open file '$call_file'!");

            $i = 0;
            while (!feof($cf)) {
                $linedata  = array_pad(explode("\t", rtrim(fgets($cf, 500))),8,"");

                /*list($arr_phone_calls[$i]['date'], $arr_phone_calls[$i]['time'], $arr_phone_calls[$i]['from'],
                     $arr_phone_calls[$i]['to'], $arr_phone_calls[$i]['name'], $arr_phone_calls[$i]['address'],
                     $arr_phone_calls[$i]['direction'], $arr_phone_calls[$i]['duration']) = array_pad($linedata, 8, '');*/
                     
                $arr_phone_calls[$i]['date']			= $linedata[0];
                $arr_phone_calls[$i]['time']			= $linedata[1];
                $arr_phone_calls[$i]['from']			= $linedata[2];
                $arr_phone_calls[$i]['to']			= $linedata[3];
                $arr_phone_calls[$i]['name']			= $linedata[4];
                $arr_phone_calls[$i]['address']		= $linedata[5];
                $arr_phone_calls[$i]['direction']	= $linedata[6];
                $arr_phone_calls[$i]['duration']	= $linedata[7];

                $arr_phone_calls[$i]['cntFields'] = count($linedata);

					 $testnbr = ($arr_phone_calls[$i]['direction'] == "OUT") ? $arr_phone_calls[$i]['to'] :$arr_phone_calls[$i]['from'];
					 if ($testnbr == $_POST['nbr']) {
                     // update record
                     $arr_phone_calls[$i]['name'] = $name;
                     $arr_phone_calls[$i]['address'] = $addr;
                }
                $i++;
            }
            fclose($cf);

            // rewrite call_file
            $bak_file = "/tmp/" . basename($call_file) . ".edit";
            $cf = fopen($bak_file, 'w');
            if (! $cf) throw new Exception("Cannot open file '$bak_file'!");

            foreach ($arr_phone_calls as $phone_call) {
                if (trim($phone_call['date']) <> '' ) {
                     // not an empty row - write it
                     $line = rtrim($phone_call['date'] . "\t" . $phone_call['time'] . "\t" . $phone_call['from'] .
                             "\t" . $phone_call['to'] . "\t" . $phone_call['name'] . "\t" . $phone_call['address']) ;

                     if ($phone_call['cntFields'] == 8) {
                        $line = $line . "\t" . $phone_call['direction'] . "\t" . $phone_call['duration'];
                     }

                     $done = fwrite($cf, $line . "\n");
                     if (! $done) throw new Exception("Cannot write to file '$bak_file'");
                }
            }
            fclose($cf);
            if (! file_exists($bak_file))     throw new Exception("'$bak_file' not created.\n\nCannot update $phonelist_file");
            if (filesize($bak_file) < 10)     throw new Exception("File $bak_file without content.");

            if (! copy($bak_file, $call_file))throw new Exception("Cannot overwrite $call_file.");
            unlink($bak_file);

            $ret['success'] = "Data saved successful";
        }

        if (! isset($ret['success'])) throw new Exception("Missing function: '$do'");

    } catch (Exception $e) {
        $ret['error'] = $e->getMessage();
    }
    
    if (ob_get_contents()) ob_end_clean();
    die(json_encode($ret));

    function bar($sum=0, $val=0) {
        $v = ($sum>0 && $val>0) ? number_format(100/$sum*$val,2) : 0;
        $ratio = ($sum>0 && $val>0) ? floor(0.8*$v) : 0;
        $b = "<div class=\"bar\" style=\"width:".($ratio)."%;\">&nbsp;</div>";
        return "$b<div>( $v% )</div>";
    }
?>