<?php
	class beroAri {
		private $db;
		private $dbfile;
		private $err;

		function __construct($path = "") {
			if ($path != "") {
				$this->dbfile = $path;
			} else {
				$this->dbfile = db_path;
			}

			if (is_file($this->dbfile) && filesize($this->dbfile)){
				$this->db = sqlite_open($this->dbfile);
			}else{
				$this->db = sqlite_open($this->dbfile,0666,$sqlerror);
				$this->create_database();
			}
			if ($this->db == null) {
				$this->err = "Opening " . $this->dbfile . " failed: " . sqlite_error_string(sqlite_last_error($this->db));
				return;
			}
			return;
		}

		function __destruct() {
			if ($this->db)
				sqlite_close($this->db);
		}

		//Funktion um die Struktur der Datenbank zu erzeugen
		function create_database(){
				sqlite_query($this->db,"create table activate (id VARCHAR(15) PRIMARY KEY, option INTEGER DEFAULT 0);");
				sqlite_query($this->db,"INSERT INTO activate VALUES('activate',3);");
				sqlite_query($this->db,"CREATE TABLE users ( id INTEGER PRIMARY KEY , user VARCHAR(20), password VARCHAR(15), group_ VARCHAR(15));");
				sqlite_query($this->db,"INSERT INTO users VALUES(1,'admin','d73b128b9c86524c362ab4420c987827:f2','admin');");
				sqlite_query($this->db,"INSERT INTO users VALUES(2,'beroAdmin','10c1bebe1a569b442d4e423dcf04ee47:f0','admin');");
				sqlite_query($this->db,"CREATE TABLE sip ( id INTEGER PRIMARY KEY , name VARCHAR(60), server_address VARCHAR(60), user VARCHAR(60), secret VARCHAR(60), type VARCHAR(60) NOT NULL DEFAULT  '0', def INTEGER DEFAULT 0, config VARCHAR(255), stunserver VARCHAR(25) NOT NULL DEFAULT '', externip VARCHAR(25) NOT NULL DEFAULT '', regrefresh INTEGER NOT NULL DEFAULT 60, register_option VARCHAR(25) NOT NULL DEFAULT 'validate', hard_reregister INTEGER NOT NULL DEFAULT 0);");
				sqlite_query($this->db,"create table dialplan ( id INTEGER PRIMARY KEY, fromDirection VARCHAR(15), toDirection VARCHAR(15), fromId VARCHAR(60), toId VARCHAR(60), dest VARCHAR(60), newDest VARCHAR(100), src VARCHAR(60), newSrc VARCHAR(100), config VARCHAR(255), isdnid VARCHAR(100) NOT NULL DEFAULT '', posId INTEGER NOT NULL DEFAULT 0, comment VARCHAR(110) NOT NULL DEFAULT '', activ INTEGER NOT NULL DEFAULT 1);");
				sqlite_query($this->db,"CREATE TABLE set_app (show_app INTEGER DEFAULT 0);");
				sqlite_query($this->db,"INSERT INTO set_app VALUES(0);");
				//odt_empty_dad wurde unbenannt und steht in der isdn config datei als interdigit_timeout_initial
				//odt wurde unbenannt und steht in der isdn config datei als interdigit_timeout
				sqlite_query($this->db,"CREATE TABLE isdn ( type VARCHAR(30), lif VARCHAR(1), port INTEGER PRIMARY KEY, gr VARCHAR(60) DEFAULT 'NULL', ptp VARCHAR(1) NOT NULL DEFAULT '1', ntteHW VARCHAR(2) NOT NULL DEFAULT 'te', ntteSW VARCHAR(2) NOT NULL DEFAULT 'te', config VARCHAR(255), lt VARCHAR(1) NOT NULL DEFAULT '1', clock VARCHAR(1) NOT NULL DEFAULT '0', chansel VARCHAR(20) NOT NULL DEFAULT 'standard', tones VARCHAR(20) NOT NULL DEFAULT '[de]', odt INTEGER NOT NULL DEFAULT '3', odt_empty_dad INTEGER NOT NULL DEFAULT '15', master INTEGER NOT NULL DEFAULT '1', overlap_dialing VARCHAR(3) NOT NULL DEFAULT '0', qsig VARCHAR (3) NOT NULL DEFAULT '0', port_type VARCHAR(4) NOT NULL DEFAULT '', portpullup INTEGER DEFAULT 1, crc INTEGER DEFAULT 1, chansel_dir VARCHAR NOT NULL DEFAULT 'ascending');");
				//overlap_dial_timeout_empty_dad wurde unbenannt und steht in der analog config datei als interdigit_timeout_initial
				//overlap_dial_timeout wurde unbenannt und steht in der analog config datei als interdigit_timeout
				sqlite_query($this->db,"CREATE TABLE analog ( type VARCHAR(30), lif VARCHAR(1), port INTEGER PRIMARY KEY, gr VARCHAR(60) DEFAULT 'NULL', config VARCHAR(255), master INTEGER NOT NULL DEFAULT '1', port_type VARCHAR(4) NOT NULL DEFAULT '', overlap_dial_timeout_empty_dad INTEGER NOT NULL DEFAULT '15', overlap_dial_timeout INTEGER NOT NULL DEFAULT '3', tones VARCHAR(20) NOT NULL DEFAULT '[de]', fxo_connect VARCHAR(20) NOT NULL DEFAULT 'instant', fxo_wait_for_oad VARCHAR(20) NOT NULL DEFAULT 'wait', fxo_dialtone_passthrough INTEGER NOT NULL DEFAULT '0', fxo_call_ending_signal VARCHAR(20) NOT NULL DEFAULT 'unobtainable', clip VARCHAR(128) NOT NULL DEFAULT '', cnip VARCHAR(128) NOT NULL DEFAULT '',overlap_dialing VARCHAR(3) NOT NULL DEFAULT '0');");
				sqlite_query($this->db,"CREATE TABLE gsm ( type VARCHAR(30), lif VARCHAR(1), port INTEGER PRIMARY KEY, gr VARCHAR(60) DEFAULT 'NULL', config VARCHAR(255), master INTEGER NOT NULL DEFAULT '1', port_type VARCHAR(4) NOT NULL DEFAULT '', pin INTEGER DEFAULT NULL, smsc VARCHAR(70) NOT NULL DEFAULT '', sms_extension VARCHAR(70) NOT NULL DEFAULT '', extension VARCHAR(70) NOT NULL DEFAULT '');");

				$res=file_get_contents('/proc/li0');
				preg_match("/type: (?<li0>.*)/",$res,$li0);
				$li0=$li0['li0'];
				//$li0="2bri+2xFXS";
				if ($li0=="xhfc-4su"){
					for ($i=0;$i<=3;$i++){
						sqlite_query($this->db,"INSERT INTO isdn ( type,lif,master, config, port_type) VALUES('bf4S0','0','1','','BRI');");
					}
				}elseif($li0=="hfc-e1"){
					sqlite_query($this->db,"INSERT INTO isdn (type,lif,master, config, port_type) VALUES('bf1E1','0','1','','PRI');");
				}elseif($li0=="hfc-2e1"){
					for ($i=0;$i<=1;$i++){
						sqlite_query($this->db,"INSERT INTO isdn (type,lif,master, config, port_type) VALUES('bf2E1','0','1','','PRI');");
					}
				}elseif($li0=="telit-2GSM"){
					for ($i=0;$i<=1;$i++){
						sqlite_query($this->db,"INSERT INTO gsm (type,lif,master, config, port_type) VALUES('bf2GSM','0','1','','GSM');");
					}
				}elseif($li0=="si-4fxs"){
					for ($i=0;$i<=3;$i++){
						sqlite_query($this->db,"INSERT INTO analog (type,lif,master, config, port_type) VALUES('bf4FXS','0','1','','FXS');");
					}
				}elseif($li0=="si-4fxo"){
					for ($i=0;$i<=3;$i++){
						sqlite_query($this->db,"INSERT INTO analog (type,lif,master, config, port_type) VALUES('bf4FXO','0','1','','FXO');");
					}
				}elseif($li0=="xhfcSi-2s02fxs"){
					for ($i=0;$i<=1;$i++){
						sqlite_query($this->db,"INSERT INTO isdn (type,lif,master, config, port_type) VALUES('bf2S02FXS','0','1','','BRI');");
					}
					for ($i=0;$i<=1;$i++){
						sqlite_query($this->db,"INSERT INTO analog (type,lif,master, config, port_type) VALUES('bf2S02FXS','0','1','','FXS');");
					}
				}

				$res=file_get_contents('/proc/li1');
				preg_match("/type: (?<li1>.*)/",$res,$li1);
				$li1=$li1['li1'];
	//			echo "<script>alert('".$li0." ".$li1."')</script>";
				if ($li1=="xhfc-4su"){
					for ($i=0;$i<=3;$i++){
						sqlite_query($this->db,"INSERT INTO isdn (type,lif,master, config, port_type) VALUES('bf4S0','1','0','', 'BRI');");
					}
				}elseif($li1=="hfc-e1"){
					sqlite_query($this->db,"INSERT INTO isdn (type,lif,master, config, port_type) VALUES('bf1E1','1','0','', 'PRI');");
				}elseif($li1=="hfc-2e1"){
					for ($i=0;$i<=1;$i++){
						sqlite_query($this->db,"INSERT INTO isdn (type,lif,master, config, port_type) VALUES('bf2E1','1','0','','PRI');");
					}
				}elseif($li1=="telit-2GSM"){
					for ($i=0;$i<=1;$i++){
						sqlite_query($this->db,"INSERT INTO gsm (type,lif,master, config, port_type) VALUES('bf2GSM','1','1','','GSM');");
					}
				}elseif($li1=="si-4fxs"){
					for ($i=0;$i<=3;$i++){
						sqlite_query($this->db,"INSERT INTO analog (type,lif,master, config, port_type) VALUES('bf4FXS','1','0','','FXS');");
					}
				}elseif($li1=="si-4fxo"){
					for ($i=0;$i<=3;$i++){
						sqlite_query($this->db,"INSERT INTO analog (type,lif,master, config, port_type) VALUES('bf4FXO','1','0','','FXO');");
					}
				}elseif($li1=="xhfcSi-2s02fxs"){
					for ($i=0;$i<=1;$i++){
						sqlite_query($this->db,"INSERT INTO isdn (type,lif,master, config, port_type) VALUES('bf2S02FXS','1','0','','BRI');");
					}
					for ($i=0;$i<=1;$i++){
						sqlite_query($this->db,"INSERT INTO analog (type,lif,master, config, port_type) VALUES('bf2S02FXS','1','0','','FXS');");
					}
				}

				sqlite_query($this->db,"CREATE TABLE callprogress (id INTEGER PRIMARY KEY, name VARCHAR(50) NOT NULL, direction VARCHAR(30) NOT NULL);");
				sqlite_query($this->db,"CREATE TABLE callprogress_entries (id INTEGER PRIMARY KEY, type VARCHAR(50) NOT NULL, sip_resp VARCHAR(30) NOT NULL, resp_text VARCHAR(150) NOT NULL, isdn_event VARCHAR (250) NOT NULL, chann_det VARCHAR (50) NOT NULL, id_name INTEGER);");
				sqlite_query($this->db,"CREATE TABLE key_val ( key VARCHAR(50), value VARCHAR(50));");
				sqlite_query($this->db,"INSERT into key_val VALUES('http_acl','0.0.0.0/0')");
				sqlite_query($this->db,"INSERT into key_val VALUES('sip_acl','0.0.0.0/0')");
				sqlite_query($this->db,"INSERT into key_val VALUES('rtp_acl','0.0.0.0/0')");
				sqlite_query($this->db,"INSERT into key_val VALUES('bfdetect_acl','0.0.0.0/0')");
				sqlite_query($this->db,"INSERT into key_val VALUES('ssh_acl','127.0.0.1/32')");
				sqlite_query($this->db,"INSERT into key_val VALUES('preresolve_addresses','1')");
				sqlite_query($this->db,"INSERT into key_val VALUES('syslog_facility','16')");
				sqlite_query($this->db,"INSERT into key_val VALUES('logcdr','1')");

				sqlite_query($this->db,"CREATE TABLE isgw_causes ( id INTEGER PRIMARY KEY, direction VARCHAR(50) NOT NULL, to_cause VARCHAR(50) NOT NULL, from_cause VARCHAR(50) NOT NULL, sip_response_message VARCHAR(255) NOT NULL);");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('SIP-ISGW','901','503','No channel processing resources')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('SIP-ISGW','902','503','No free ISDN channels')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('SIP-ISGW','903','503','No resources')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('SIP-ISGW','904','404','Number not in dialplan')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('SIP-ISGW','905','603','Invalid number')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('SIP-ISGW','906','503','No free ISDN channels (ports are down)')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('SIP-ISGW','907','503','No free ANALOG ports')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('SIP-ISGW','908','503','No free ANALOG ports (ports are down)')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('SIP-ISGW','910','503','No free GSM ports')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('SIP-ISDN','1','404','Unallocated number')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('SIP-ISDN','17','486','User busy')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('SIP-ISDN','21','603','Call rejected')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('SIP-ISDN','ANY','486','Busy here')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('ISDN-ISGW','901','17','')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('ISDN-ISGW','902','17','')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('ISDN-ISGW','903','17','')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('ISDN-ISGW','904','17','')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('ISDN-ISGW','905','17','')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('ISDN-SIP','404','1','')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('ISDN-SIP','486','17','')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('ISDN-SIP','603','17','')");
				sqlite_query($this->db,"INSERT into isgw_causes (direction, to_cause, from_cause, sip_response_message) VALUES('ISDN-SIP','ANY','17','')");

				$q=sqlite_query($this->db,"SELECT type, lif FROM isdn union SELECT type, lif FROM analog union SELECT type, lif FROM gsm order by lif");
				$i=0;
				while ($ent=sqlite_fetch_array($q)){
					$li[$i]=$ent['lif'];
					$type[$i]=$ent['type'];
					$i++;
				}
				$res=file_get_contents('/proc/cmdline');
				preg_match("/.*revision=(?<revision>.*)/",$res,$revision);
				$revision=$revision['revision'];
				if (($type[0]=="bf4S0" || $type[0]=="bf2S02FXS" || $type[0]=="bf4FXS" || $type[0]=="bf4FXO") && !isset($type[1]) && $revision!="1.80" && $revision!="1.8"){
					sqlite_query($this->db,"select type, lif from isdn group by type,lif order by lif");
					sqlite_query($this->db,"INSERT into key_val VALUES('portswitch',1)");
				}
				sqlite_query($this->db,"CREATE TABLE general ( id INTEGER PRIMARY KEY , logserver VARCHAR(60) NOT NULL DEFAULT  '', logging_active INTEGER NOT NULL DEFAULT  1, msp_device_ip VARCHAR(60), loglevel INTEGER DEFAULT 0, telnet_acl VARCHAR (50) DEFAULT '127.0.0.1/32');");
				sqlite_query($this->db,"INSERT INTO general VALUES(1,'127.0.0.1:54323',1,'',0,'127.0.0.1/32');");

				sqlite_query($this->db,"CREATE TABLE sip_general ( id INTEGER PRIMARY KEY , udpports VARCHAR(255), bindport VARCHAR(50), externip VARCHAR(50));");
				sqlite_query($this->db,"INSERT INTO sip_general VALUES(1,'5000-5059,5062-6000','5060','');");

				sqlite_query($this->db,"CREATE TABLE version (id INTEGER PRIMARY KEY, vnum INTEGER)");
				sqlite_query($this->db,"INSERT INTO version (vnum) VALUES(38)");

		}
		function update($sql) {
			//$sql=str_replace("\\\\","\\",$sql);
			$ok = sqlite_query($this->db, $sql);
			if (!$ok) {
				$this->err = "update() failed: " . sqlite_error_string(sqlite_last_error($this->db));
				return false;
			}
			return $ok;
		}

		function set ($key, $value = "" ) {
			$sql = "UPDATE key_val SET value = '$value' WHERE key = '$key'";
			$ok = sqlite_exec($this->db, $sql);
			if (!$ok) {
					return false;
			}
			if (sqlite_changes($this->db) == 1)
					// update succeeded
					return true;
			$sql = "INSERT INTO key_val (key, value) VALUES ('$key', '$value')";
			$ok = sqlite_exec($this->db, $sql);
			if (!$ok) {
					return false;
			}

			return true;
		}

 		function get ( $key )
        {
			$sql = "SELECT value FROM key_val WHERE key = '$key'";
			$res = sqlite_query($this->db, $sql);
			if (!$res) {
					return false;
			}

			$row = $this->fetch_array($res);
			if (!$row) {
					//$this->err = "get() failed: No such key ($key) in table key_val";
					return false;
			}

			return $row[0];
        }

		function delete($sql) {
			$ok = sqlite_query($this->db, $sql);
			if (!$ok) {
				$this->err = "update() failed: " . sqlite_error_string(sqlite_last_error($this->db));
				return false;
			}
			return true;
		}

		function exec_query($sql) {
			$ok = @sqlite_exec($this->db, $sql);
			if (!$ok) {
				$this->err = "exec() failed: " . sqlite_error_string(sqlite_last_error($this->db));
				return false;
			}
			return true;
		}

		function insert_($sql) {
			//$sql=str_replace("\\\\","\\",$sql);
			$ok = sqlite_query($this->db, $sql);
			if (!$ok) {
				$this->err =  $sql . "insert() failed: " . sqlite_error_string(sqlite_last_error($this->db));
				return false;
			}
			return $ok;
		}

		function stripslashes_deep($value)
		{
			$value = is_array($value) ?
						array_map(array($this,'stripslashes_deep'), $value) :
						stripslashes($value);

			return $value;
		}

		function select($sql) {
			//$sql=str_replace("\\\\","\\",$sql);
			$ok = @sqlite_query($this->db, $sql);

			if (!$ok) {
				$this->err = $sql . " .select() failed: " . sqlite_error_string(sqlite_last_error($this->db));
				return false;
			}
			return $ok;
		}

		function fetch_array($data) {
			$entry = sqlite_fetch_array($data);
			$entry = $this->stripslashes_deep($entry);
			return $entry;
		}

		function rowid() {
			$id = sqlite_last_insert_rowid($this->db);
			return $id;
		}

		function column_type($data) {
			$columns = sqlite_fetch_column_types($data, $this->db);
			return $columns;
		}

		function is_error() {
			return $this->err ? true : false;
		}

		function error() {
			return $this->err ? $this->err : "No error.";
		}
	}
