#!/usr/bin/php -q
<?php
/*
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
*/
$apiVersion="2.1";
/*
 * Einbindung der nötigen externen Klassen
 */
require_once('/usr/local/www/berogui/misc/database.php');
require_once('/usr/local/www/berogui/includes/isgwtelnet.php');
require_once('/usr/local/php/beroConf.php');

$apiUrl='https://berocloud.beronet.com/index.php?r=api';

/*
 * Datenbank Klassen instanziieren
 */
$bc = new beroConf('root');
$ba=new beroAri('/usr/conf/ari.db');

/*
 * Seriennummer der Karte herausfinden
 */
$res=file_get_contents('/proc/cmdline');
preg_match("/[^a-zA-Z0-9=]*?d=(?<serial>.+) /",$res,$serial);
$serial=$serial['serial'];
$apiKey=$bc->get("root","cloud_key"); //Dummy

$pstn_to_sip_arr=array();
$sip_to_pstn_arr=array();

$sleep_interval=$bc->get('root', 'cloud_interval');
if (!$sleep_interval) $sleep_interval=60;

$cloud_enable=$bc->get('root', 'cloud_enable');
if ($cloud_enable != 1 ) exit(1);

set_time_limit(0);

/*
 * Diese Schleife macht dass der Skript immer alle X Sekunden durchgeführt wird
 * die Anzahl an Sekunden wird in der Variable $sleep_interval definiert.
 */
while (1) {
	try {
		alive();
		getTask();
		isdnStatus();
		gsmStatus();
		analogStatus();
		sipStatus();
		sleep ($sleep_interval);
	}catch(Exception $e){
		file_put_contents ( "/tmp/api-error.log" , $e->getMessage()." ".$e->getFile()." ".$e->getLine()."\n" , FILE_APPEND );
	}
}

/**
  * Geplante Aufgaben aus dem Server lesen
  *
  * Diese Funktion ist eine rekursive Funktion, und wird so oft
  * ausgeführt, wie es geplante fällige Aufgaben auf dem Server gibt.
  *
  * @return void
  */
function getTask(){
	global $serial, $apiKey, $apiUrl;

	$ch = curl_init();

	$data = array('cmd'=>'getTask', 'serial'=>$serial, 'key'=>$apiKey);

	curl_setopt($ch, CURLOPT_URL, $apiUrl);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	$contents = curl_exec($ch);
	curl_close($ch);
	$response=unserialize($contents);

	//var_dump($response);
	$task=$response['task'];
	$next=$response['next'];
	/**
	 * Es wird überptüft welche Task vom Server empfangen wurde
	 * und die entsprechende Funktion wird ausgeführt.
	 */
	switch($task):
	case 'updateFW':
		$handle = @fopen("/tmp/".$response['file_name'], "w");
		$ch = curl_init();
		$data = array('cmd'=>'firmwareDownload', 'serial'=>$serial, 'key'=>$apiKey);
		curl_setopt($ch, CURLOPT_URL, $apiUrl);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_FILE, $handle);
		curl_exec($ch);
		curl_close($ch);
		fclose($handle);

		$fileName=$response['file_name'];
		updateFW($fileName);
		break;

	case 'reboot':
		reboot();
		break;

	case 'createTunnel':

		$key=$response['sshKey'];
		$command=$response['sysCmd'];
		createTunnel($key,$command);
		break;

	case 'activate':
		activate();
		break;

	case 'updateConfig':
		$file=$response['file'];
		updateConfig($file);
		break;

	case 'backupConfig':
		backupConfig();
		break;

	case 'coredump':
		coredump();
		break;

	case 'deleteCoredump':
		deleteCoredump();
		break;

	case 'Query':
		query();
                break;

        case 'updateAPI':
            $file=$response['file'];
            updateAPI($file);
            break;

	endswitch;

	if ($next) getTask();
}

/**
  * Firmware der Karte aktualisieren
  *
  * Die Alte Firmwares dir sich auf der Karte befinden werden gelöscht
  * und die neue Firmware wird installiert, die die aus der beroCloud
  * heruntergeladen wurde.
  *
  * @param  $fileName Name der neuen Firmware
  * @return void
  */
function updateFW($fileName){
	global $bc;
		$image_dir = "/tmp/images";
		system("mkdir -p ".$image_dir);
	if (is_dir($image_dir) && ($dh = opendir($image_dir))) {
			while (($file = readdir($dh)) != false) {
				if (strlen($file) > 7 && substr_compare($file, ".tar.gz", -7, 7) == 0) {
					$file_ = $image_dir . '/' . $file;
					if (strlen($file_) != 0 && file_exists($file_)) unlink($file_);
				}
				if ($file=="content.txt"){
					$file_ = $image_dir . '/' . $file;
					if (strlen($file_) != 0 && file_exists($file_)) unlink($file_);
				}
			}
		}
			$split_ext=explode(".",$fileName);

			if ($split_ext[count($split_ext)-1]=="gz" && $split_ext[count($split_ext)-2]=="tar" && count($split_ext)>=3){
			$upload_file = $image_dir . '/' . $fileName;
		if ((filesize("/tmp/".$fileName)/1024)/1024<=7.9){
				system ("/bin/mv /tmp/".$fileName." ".$image_dir);
				if (strlen($fileName) != 0 && file_exists($image_dir . '/' . $fileName)) system("/usr/local/sbin/install.sh $fileName >/tmp/cloud-updateFW.log");


			}
		}
}

/**
 * Karte neu starten
 *
 * @return void
 */
function reboot(){
			exec ('/sbin/reboot');
			exit;
}


/**
 * Coredump datei löschen
 *
 * @return void
 */
function deleteCoredump(){
			@unlink("/tmp/debug-info.tar.gz");
			@unlink("/tmp/core");
			@unlink("/tmp/corelink");
}

function createTunnel($key,$command){
	global $apiKey, $serial, $apiUrl;
	$sshKey="80.244.243.46 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDCFbXKdrCoPOPdWc6IWj5XaR76JJ65WjTeBUjhewYnKVteTwXu3VQ4YL55tBpcTLCiTbYg+KX/96rONbTAFryBSIeQSCRcTgD/NZ2iF16gaLsUQDPcs6ABQb6IuC3nfsCg/VSJAO9p4aC70ZJJU6yl3hPpQmx0gPUncK/xI60lArE4k3i2dtsFuXAJGtP29ng6ztwOjIbXOwCQ+YSKc29nfr7UcaHjBnExeCBsK9Ux/KlrrppHckkzbR6vtiiHHfJ2lnOlKlr15tm73kLUUBI55C9F0g+N55LFp2f7q/jbIriqAVUHSiHFhzsnJdacsMFosa8keYj/zSfYAo8sPo87";
	if (file_put_contents("/tmp/key",$key)!==false && file_put_contents("/tmp/known_hosts",$sshKey)!==false && chmod("/tmp/key", 0600)!==false) exec("/sbin/".$command);
	file_put_contents("/tmp/migue",$command);
	$ch = curl_init();
	$data = array('cmd'=>'createTunnelResponse', 'serial'=>$serial, 'key'=>$apiKey, 'result'=>'success');

	curl_setopt($ch, CURLOPT_URL, $apiUrl);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	$response=curl_exec($ch);
	curl_close($ch);
}

/**
 * Eine Aktivierung der Konfiguration wird duschgeführt
 *
 * @return void
 */
function activate(){
	global $ba;
    $res=$ba->update("update activate set option=0");
    echo $ba->error();
    system ("/usr/bin/wget -q http://localhost/app/berogui/includes/create_files.php");
    sleep(3);
    system('
		for i in /usr/local/init/S??* ; do
				# Ignore dangling symlinks (if any).
				[ ! -f "$i" ] && continue

				services[${#services[@]}]=$i
		done

		num=${#services[@]}

		for (( i = num - 1 ; i >= 0 ; i-- )) ; do
				if [ ${services[$i]} != "/usr/local/init/S60cloud" ]
						then ${services[$i]} stop
				fi
		done
	');
	sleep(10);
    reboot();
}
/**
  * Kartenkonfiguration aktualisieren
  *
  * Die aus dem Server heruntergeladenen Konfiguration, wird auf die Karte
  * installiert.
  *
  * @param $file Konfigurationsdatei
  * @return void
  */
function updateConfig($file){
	$handle = @fopen("/tmp/beroGui.tar.gz", "w");
	fwrite($handle, $file);
	fclose($handle);
	 $strpath="/usr/conf/";

	system("/bin/tar -xvvz -f/tmp/beroGui.tar.gz -C /tmp/");
	//Alte Konfigurationsdateien sichern und löschen
	chdir("/usr/conf");
	if (!is_dir("backup")) mkdir("backup");
	copy("isgw.conf","backup/isgw.conf");
	copy("isgw.sip","backup/isgw.sip");
	copy("isgw.isdn","backup/isgw.isdn");
	copy("isgw.analog","backup/isgw.analog");
	copy("isgw.gsm","backup/isgw.gsm");
	copy("isgw.causes","backup/isgw.causes");
	copy("isgw.cpt","backup/isgw.cpt");
	copy("isgw.dialplan","backup/isgw.dialplan");
	copy("misc.conf","backup/misc.conf");
	copy("hardware.conf","backup/hardware.conf");
	unlink("isgw.conf");
	unlink("isgw.sip");
	unlink("isgw.isdn");
	unlink("isgw.analog");
	unlink("isgw.gsm");
	unlink("isgw.causes");
	unlink("isgw.cpt");
	unlink("isgw.dialplan");
	unlink("misc.conf");
	unlink("hardware.conf");

    //Neue Konfigurationsdateien in dem Order /usr/conff kopieren
	if (is_file("/tmp/isgw.conf")) copy("/tmp/isgw.conf","/usr/conf/isgw.conf");
	if (is_file("/tmp/isgw.sip")) copy("/tmp/isgw.sip","/usr/conf/isgw.sip");
	if (is_file("/tmp/isgw.isdn")) copy("/tmp/isgw.isdn","/usr/conf/isgw.isdn");
	if (is_file("/tmp/isgw.analog")) copy("/tmp/isgw.analog","/usr/conf/isgw.analog");
	if (is_file("/tmp/isgw.gsm")) copy("/tmp/isgw.gsm","/usr/conf/isgw.gsm");
	if (is_file("/tmp/isgw.causes")) copy("/tmp/isgw.causes","/usr/conf/isgw.causes");
	if (is_file("/tmp/isgw.cpt")) copy("/tmp/isgw.cpt", "/usr/conf/isgw.cpt");
	if (is_file("/tmp/isgw.dialplan")) copy("/tmp/isgw.dialplan","/usr/conf/isgw.dialplan");
	if (is_file("/tmp/hardware.conf")) copy("/tmp/hardware.conf","/usr/conf/hardware.conf");
	if (is_file("/tmp/misc.conf")) copy("/tmp/misc.conf","/usr/conf/misc.conf");
	require_once( "/usr/local/www/berogui/misc/ini_to_db_functions.php");

	/*
	 * Wenn die Datenbank nicht aus den Konfigurationsdateien erstellt werden kann
	 * werden die Dateien aus der Sicherungskopie wiederhergestellt.
	 */
	if (!ini_to_db(1)){
		copy("backup/isgw.conf","isgw.conf");
		copy("backup/isgw.sip","isgw.sip");
		copy("backup/isgw.isdn","isgw.isdn");
		copy("backup/isgw.analog","isgw.analog");
		copy("backup/isgw.gsm","isgw.gsm");
		copy("backup/isgw.causes","isgw.causes");
		copy("backup/isgw.cpt","isgw.cpt");
		copy("backup/isgw.dialplan","isgw.dialplan");
		copy("backup/misc.conf","misc.conf");
		copy("backup/hardware.conf","hardware.conf");
	}else{
		global $ba;
		$res=$ba->update("update activate set option=3");
	}
	chdir("/tmp/");
	unlink("isgw.conf");
	unlink("isgw.sip");
	unlink("isgw.isdn");
	unlink("isgw.analog");
	unlink("isgw.gsm");
	unlink("isgw.causes");
	unlink("isgw.cpt");
	unlink("isgw.dialplan");
	unlink("misc.conf");
	unlink("hardware.conf");
	unlink("beroGui.tar.gz");

}

function updateAPI($file){
	$handle = @fopen("/tmp/cloud-api.php", "w");
	fwrite($handle, $file);
	fclose($handle);

    system("/bin/mount -o remount,rw /usr/local/");
    system("/bin/cp /tmp/cloud-api.php /usr/local/php/");
    system("/bin/sync");
	system("/bin/mount -o remount,ro /usr/local/");
}


/*
 * Sicherung der Konfigurationsdateien
 *
 * Die Konfigurationsdateien werden gesichert und diese werden auf dem Server
 * hochgeladen.
 *
 * @return void
 */
function backupConfig(){
	global $apiKey, $serial, $apiUrl;
	$files="";
	if (file_exists("/usr/conf/isgw.conf")){
		$files.=" isgw.conf";
	}
	if (file_exists("/usr/conf/isgw.sip")){
		$files.=" isgw.sip";
	}
	if (file_exists("/usr/conf/isgw.isdn")){
		$files.=" isgw.isdn";
	}
	if (file_exists("/usr/conf/isgw.analog")){
		$files.=" isgw.analog";
	}
	if (file_exists("/usr/conf/isgw.gsm")){
		$files.=" isgw.gsm";
	}
	if (file_exists("/usr/conf/isgw.causes")){
		$files.=" isgw.causes";
	}
	if (file_exists("/usr/conf/isgw.causes")){
		$files.=" isgw.cpt";
	}
	if (file_exists("/usr/conf/isgw.dialplan")){
		$files.=" isgw.dialplan";
	}
	if (file_exists("/usr/conf/hardware.conf")) {
		 $files.=" hardware.conf";
	}
	if (file_exists("/usr/conf/misc.conf")) {
		 $files.=" misc.conf";
	}
	exec("/bin/tar -cvz -f/tmp/beroGui.tar.gz -C /usr/conf ".$files);

	$ch = curl_init();

	$data = array('cmd'=>'backupConfigResponse', 'file_name' => 'beroGui.tar.gz', 'file' => '@/tmp/beroGui.tar.gz', 'serial'=>$serial, 'key'=>$apiKey);

	curl_setopt($ch, CURLOPT_URL, $apiUrl);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	echo curl_exec($ch);
	curl_close($ch);
}

/*
 * Coredump hochladen
 *
 * Das core dump wird auf dem Server hochgeladen.
 *
 * @return void
 */
function coredump(){
	global $apiKey, $serial, $apiUrl;

	if (file_exists("/tmp/debug-info.tar.gz")){
/*
		$file ="/tmp/debug-info.tar.gz";
		if (file_exists("/tmp/core")) $file.=" /tmp/core";
		ob_start();
		passthru("tar -f - -c ".$file);
		$content_grabbed=ob_get_contents();
		ob_end_clean();
*/


	$ch = curl_init();

	$data = array('cmd'=>'coredumpResponse', 'file_name' => 'coredump.tar.gz', 'file'=> '@/tmp/debug-info.tar.gz', 'serial'=>$serial, 'key'=>$apiKey);

	curl_setopt($ch, CURLOPT_URL, $apiUrl);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	echo curl_exec($ch);
	curl_close($ch);
	}
}

/**
 * Eckdaten der Karte zum Server schicken.
 *
 * Die istallierte Line Inferfacesm die Firmware Version, die IP Adresse,
 * die Hardware Revision, die Root Filesystem Version, die FPGA Version, die
 * konfigurierte SIP Peers werden dem Server gesendet werden
 *
 * @return void
 */
function query(){
	global $ba, $bc, $serial,$apiKey, $apiUrl, $apiVersion;
	$res=file_get_contents('/proc/li0');
	preg_match("/type: (?<li0>.*)/",$res,$li0);
	$li0=$li0['li0'];

	$res=file_get_contents('/proc/li1');
	preg_match("/type: (?<li1>.*)/",$res,$li1);
	$li1=$li1['li1'];

    $nameLi0=getLiName($li0);
	$nameLi1=getLiName($li1);
	$sip=array();
	$query=$ba->select("select * from sip");
	$i=0;
	while ($entry=$ba->fetch_array($query)):
		$sip[$i]['name']=$entry['name'];
		$sip[$i++]['monitor']=$entry['type'];
	endwhile;

	//Firmware Version
	$fw_version=$bc->get("root", "app-image");

	//IP Address
	$ip=$bc->get("root", "lan-ipaddr");

	//Rootfs Version
	$f=@file("/VERSION");
	$tmp=explode("=",$f[1]);
	$rootfs=$tmp[1];

	//FPGA Version
	$fpga=file("/proc/FPGA_VERSION");

	//HW Revision
	$res=file_get_contents('/proc/cmdline');
	preg_match("/.*revision=(?<revision>.*)/",$res,$revision);
	$revision=$revision['revision'];

	$ch = curl_init();

	$data = array('cmd'=>'queryResponse', 'lineInterface0' => $nameLi0, 'lineInterface1' => $nameLi1, 'fw_version' => $fw_version, 'ip' => $ip, 'hw_rev' => $revision, 'rootfs_version' => $rootfs, 'fpga_version' => $fpga[0], 'sip'=> serialize($sip), 'serial'=>$serial, 'key'=>$apiKey,'apiVersion'=>$apiVersion);

	curl_setopt($ch, CURLOPT_URL, $apiUrl);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	echo curl_exec($ch);
	curl_close($ch);
}

/**
 * Line Interfaces Name (beroCloud Name) zurückliefern
 *
 * Anhand der technischen Bezechnung der Line Interfaces wird der
 * Name generiert. Der generierte Name wird zurückgegeben
 *
 * @param String $li Technische Bezeichnung des Line Interfaces
 * @return String $name
 */
function getLiName($li){
	if ($li=="xhfc-4su") $name='bf4S0';
	elseif($li=="hfc-e1") $name='bf1E1';
	elseif($li=="hfc-2e1") $name='bf2E1';
	elseif($li=="si-4fxs") $name='bf4FXS';
	elseif($li=="si-4fxo") $name='bf4FXO';
	elseif($li=="xhfcSi-2s02fxs") $name='bf2S02FXS';
	elseif($li=="telit-2GSM") $name='bf2GSM';
	else $name='none';
	return $name;
}

/**
 * Status Nachrichten an dem Server senden.
 *
 * Der Load-, Calls-, Memory- und Alive-Status werden an dem Server gesendet.
 *
 * @return void
 */
function alive(){
	global $serial,$apiKey, $apiUrl;
	$ch = curl_init();
	$isgw = new isgwtelnet();
	$result=$isgw->isgw_login();
	$isgw_state=1;
	if ($result==false) {
		$isgw_state=0;
	}
	$isgw_uptime=$isgw->isgw_uptime();
        $isgw_uptime=preg_split("/: /",$isgw_uptime);
        $isgw_actualcalls=$isgw->isgw_actualcalls();
        $isgw_acutalcalls=split("\n", $isgw_actualcalls);

        preg_match("/.*PSTN_TO_SIP.*\((.*) connected\).*/", $isgw_actualcalls, $pstn_to_sip);
        preg_match("/.*SIP_TO_PSTN.*\((.*) connected\).*/", $isgw_actualcalls, $sip_to_pstn);

        if (count($pstn_to_sip_arr)==20) array_pop($pstn_to_sip_arr);
		$pstn_to_sip_arr[]=$pstn_to_sip[1];

		if (count($sip_to_pstn_arr)==20) array_pop($sip_to_pstn_arr);
		$sip_to_pstn_arr[]=$sip_to_pstn[1];

		$sip_to_pstn_avg=0;
		$pstn_to_sip_avg=0;

		foreach($sip_to_pstn_arr as $value) $sip_to_pstn_avg+=$value;
		$sip_to_pstn_avg=$sip_to_pstn_avg/(count($sip_to_pstn_arr));

		foreach($pstn_to_sip_arr as $value) $pstn_to_sip_avg+=$value;
		$pstn_to_sip_avg=$pstn_to_sip_avg/(count($pstn_to_sip_arr));

		$uptime_sec = strtok( file_get_contents( "/proc/uptime" ), "." );




	exec('/usr/bin/uptime',$resup);
        preg_match("/(?<t>.+), load /",$resup[0],$uptime);
        preg_match("/.*load average: (.*),.*,.*/",$resup[0],$load);
	exec('/usr/bin/free',$resup);
        preg_match("/.*Mem:[ ]*[0-9]*[ ]*[0-9]*[ ]*([0-9]*)[ ]*[0.9]*[ ]*[0-9]*[ ]*/",$resup[2],$free_mem);

        //Coredump
        (file_exists("/tmp/debug-info.tar.gz")) ? $coredump=1 : $coredump=0;


	$data = array('cmd'=>'alive', 'serial'=>$serial, 'key'=>$apiKey, 'uptime'=>$uptime['t'], 'uptime_sec'=>$uptime_sec, 'isgw_state'=>$isgw_state, 'coredump'=>$coredump, 'isgw_uptime'=>$isgw_uptime[1], 'load'=>$load[1], 'free_mem' => $free_mem[1], 'pstn_to_sip'=>$pstn_to_sip_avg, 'sip_to_pstn'=>$sip_to_pstn_avg);

	curl_setopt($ch, CURLOPT_URL, $apiUrl);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	echo curl_exec($ch);
	curl_close($ch);
}

/**
 * ISDN Status Nachrichten an dem Server senden.
 *
 * @return void
 */
function isdnStatus(){
	global $serial,$apiKey, $apiUrl;

	$isgw = new isgwtelnet();
	$result=$isgw->isgw_login();
	if ($result==false) return;
	$isdnresult=$isgw->isgw_isdnstate();
	$rows = "";
	$rows = explode("\n", $isdnresult);
	$l1=file("/proc/l1_stats");
	foreach($l1 as $key => $value){
		$v=explode(";",$value);
		foreach($v as $werte){
			$wert=explode("=",$werte);
			if ($wert[0]=="port") {$port=$wert[1]; $l1_stats[$wert[1]]="";}
			//if ($wert[0]=="physw") {$l1_stats[$port].="Physical Link Switch: ".$wert[1]."\n";}
			if ($wert[0]=="crc") {$crc[$port]=$wert[1]; $l1_stats[$port].="CRC Error: ".$wert[1]."\n";}
			//if ($wert[0]=="fr") {$l1_stats[$port].="Frame Resent: ".$wert[1]."\n";}
			//if ($wert[0]=="fs") {$l1_stats[$port].="Frame Resync: ".$wert[1]."\n";}
			//if ($wert[0]=="los") {$l1_stats[$port].="Loss of Signal: ".$wert[1];}
		}
	}

	$l2=file("/proc/l2_stats");
	foreach($l2 as $key => $value){
		$v=explode(";",$value);
		foreach($v as $werte){
			$wert=explode("=",$werte);
			if ($wert[0]=="port") {$port=$wert[1]; $l2_stats[$wert[1]]="";}
			if ($wert[0]=="mdl") {$l2_stats[$port].="L2 Error: ".$wert[1]."\n";}
			if ($wert[0]=="frm") {$l2_stats[$port].="L2 Frame Error: ".$wert[1]."\n";}
		}
	}

	$isdnStatus=array();
	$i=0;
	foreach ($rows as $value){
			$pos=strpos($value,"Port");
			if($pos !== false){
				preg_match("&\* Port (?<port>\d+) Type (?<type>\w+) Prot. (?<prot>\w+) L2Link (?<l2>\w+) L1Link:(?<l1>\w+) Blocked:0&isU",$value,$arr);
				//$message = "Port:" . $arr['port'] . "\n";
				//$message .= "Type:" . $arr['type'] . "\n";
				//$message .= "Prot:" . $arr['prot'] . "\n";
				$message = "L2Link:" . $arr['l2'] . "\n";
				$message .= "L1Link:" . $arr['l1'] . "\n";
				//$message .=$l2_stats[$arr['port']];
				$message .=$l1_stats[$arr['port']];
				$isdnStatus[$i]['port']=$arr['port'];
				$isdnStatus[$i]['state']=$arr['l2'];
				$isdnStatus[$i]['ISDN CRC Error']=$crc[$arr['port']];
				$isdnStatus[$i]['ISDN Port State L1']=($arr['l1']=="UP") ? "1" : "0";
				$isdnStatus[$i]['ISDN Port State L2']=($arr['l2']=="UP") ? "1" : "0";
				$isdnStatus[$i]['state']=$arr['l2'];
				$isdnStatus[$i++]['message']=$message;
			}//endif
		}//endforeach


	$ch = curl_init();

	$data = array('cmd'=>'isdnStatus', 'serial'=>$serial, 'status'=>serialize($isdnStatus), 'key'=>$apiKey);

	curl_setopt($ch, CURLOPT_URL, $apiUrl);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	echo curl_exec($ch);
	curl_close($ch);
}
/**
 * GSM Status Nachrichten an dem Server senden.
 *
 * @return void
 */
function gsmStatus(){
	global $serial,$apiKey, $apiUrl;

	$isgw = new isgwtelnet();
	$result=$isgw->isgw_login();
	if ($result==false) return;
	$gsmresult=$isgw->isgw_gsmstate();
	$rows = "";
	$rows = explode("\n", $gsmresult);


	$gsmStatus=array();
	$i=0;
	foreach ($rows as $value){
			$pos=strpos($value,"Port");
			if($pos !== false){
				$tmp = explode("Port ", $value);
				$port = explode("Provider:", $tmp[1]);
				$message = "Port: " . $port[0] . "\n";
				$gsmStatus[$i]['port']=$port[0];
				$provider = explode("Pin Counter:", $port[1]);
				$message .= "Provider: " . $provider[0] . "\n";
				$counter = explode("Reg Status:", $provider[1]);
				$message .= "PIN Counter: " . $counter[0] . "\n";
				$state = explode("RSSI:", $counter[1]);
				if (trim($state[0])=="NOT READY"){ $gsmStatus[$i]['state']="DOWN"; $message .= "Reg Status: Not ready\n";}
				elseif (trim($state[0])==0){ $gsmStatus[$i]['state']="DOWN"; $message .= "Reg Status: not registered, ME is <b>not</b> currently searching a new operator to register to\n";}
				elseif (trim($state[0])==1){ $gsmStatus[$i]['state']="UP"; $message .= "Reg Status: registered, home network\n";}
				elseif (trim($state[0])==2){ $gsmStatus[$i]['state']="DOWN"; $message .= "Reg Status: not registered, but ME is currently searching a new operator to register to\n";}
				elseif (trim($state[0])==3){ $gsmStatus[$i]['state']="DOWN"; $message .= "Reg Status: registration denied\n";}
				elseif (trim($state[0])==4){ $gsmStatus[$i]['state']="DOWN"; $message .= "Reg Status: unknown\n";}
				elseif (trim($state[0])==5){ $gsmStatus[$i]['state']="UP"; $message .= "Reg Status: registered, roaming\n";}

				$rssi = explode("BER:", $state[1]);
				$rssiNumber=explode(" ",trim($rssi[0]));
				if ($rssiNumber[0]==-1 || $rssiNumber[0]==99) $message.="Signal: -\n";
				elseif ($rssiNumber[0]>-60) $message.="Signal: VERY HIGH\n";
				elseif ($rssiNumber[0]<=-60 && $rssiNumber[0]>-75) $message.="Signal: HIGH\n";
				elseif ($rssiNumber[0]<=-75 && $rssiNumber[0]>-100) $message.="Signal: OK\n";
				elseif ($rssiNumber[0]<=-100) $message.="Signal: LOW\n";
				$message.="RSSI: ".$rssi[0]."\n";
				$ber=$rssi[1];
				$message.="BER: ".$ber."\n";



				$gsmStatus[$i++]['message']=$message;
			}//endif
		}//endforeach
	$ch = curl_init();

	$data = array('cmd'=>'gsmStatus', 'serial'=>$serial, 'status'=>serialize($gsmStatus), 'key'=>$apiKey);

	curl_setopt($ch, CURLOPT_URL, $apiUrl);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	echo curl_exec($ch);
	curl_close($ch);
}

/**
 * Analog Status Nachrichten an dem Server senden.
 *
 * @return void
 */
function analogStatus(){
	global $serial,$apiKey, $apiUrl;

	$isgw = new isgwtelnet();
	$result=$isgw->isgw_login();
	if ($result==false) return;
	$analogresult=$isgw->isgw_analogstate();
	$rows = "";
	$rows = explode("\n", $analogresult);

	$analogStatus=array();
	$i=0;
	foreach ($rows as $value){
				$pos=strpos($value,"Port");
				if($pos !== false){
					$ret .= "<tr>";
					$tmp = split("Port ", $value);
					$port = split("type:", $tmp[1]);
					$message = "Port: " . $port[0] . "\n";
					$analogStatus[$i]['port']=$port[0];
					$type = split("state:", $port[1]);
					$message .= "Type: " . $type[0] . "\n";
					$state = split("linevoltage:", $type[1]);
					$message .= "State: " . $state[0] . "\n";
					$linevoltage = split("pol:", $state[1]);
					$message .= "Line voltage: " . $linevoltage[0] . "\n";
					if ($linevoltage[0] >= 30)
						$analogStatus[$i]['state']="UP";
					else
						$analogStatus[$i]['state']="DOWN";
					$pol = split("rtlc:", $linevoltage[1]);
					$message .= "Polarity: " . $pol[0] . "\n";

					$analogStatus[$i++]['message']=$message;
				}//endif
			}//endforeach


	$ch = curl_init();

	$data = array('cmd'=>'analogStatus', 'serial'=>$serial, 'status'=>serialize($analogStatus), 'key'=>$apiKey);

	curl_setopt($ch, CURLOPT_URL, $apiUrl);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	echo curl_exec($ch);
	curl_close($ch);
}

/**
 * SIP Status Nachrichten an dem Server senden.
 *
 * @return void
 */
function sipStatus(){
	global $serial, $apiKey, $apiUrl;

	$isgw = new isgwtelnet();
	$result=$isgw->isgw_login();
	if ($result==false) return;
	$sipresult=$isgw->isgw_sipstate();

	$sipStatus=array();
	$index=0;

	$rows = explode("\n", $sipresult);
	$i=0;

	$message="";

	for ($j=0;$j < count($rows)-3;$j++){
		if ($i>0){
			if (in_array($i,array(1,2,3,4))){

				$sp = explode("=>", $rows[$j]);
				$v = trim($sp[1]);
				if ($i==1) $name=$v;
				$message.=$text = preg_replace("/\s+/", "",  $rows[$j]) ."\n";
			}
			if ($i == 5) {
				$sp = explode("=>", $rows[$j]);
				$state = trim($sp[1]);
				$message.= preg_replace("/\s+/", "",  $rows[$j])."\n";
			}

		}
		$i++;
		if ($i==10) {
			$sipStatus[$index]['name']=$name;
			$sipStatus[$index]['state']=$state;
			$sipStatus[$index++]['message']=$message;
			$message="";
			$i=0;
		}
	}


	$ch = curl_init();

	$data = array('cmd'=>'sipStatus', 'serial'=>$serial, 'status'=>serialize($sipStatus), 'key'=>$apiKey);

	curl_setopt($ch, CURLOPT_URL, $apiUrl);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	echo curl_exec($ch);
	curl_close($ch);
}

?>
