<?php
class wpa
{
    public $wpa_supplicant = [];
	public $wpa_supplicantconf = "";

	
    function __construct() {
		$filename = "/etc/wpa_supplicant/wpa_supplicant.conf";
		$handle = fopen($filename, "r");
		$input_lines = fread($handle, filesize($filename));
		fclose($handle);
		$this->wpa_supplicantconf = $input_lines; //this line for backup wpa_supplicant.conf to var
		$priority = 1;
		$primary_output = [];
		preg_match_all("/network={[\r\n\t]([^}]*)}/m", $input_lines, $primary_output);
		foreach($primary_output[1] as $output_line){
			$secondary_output = [];
			$tmp = [];
			preg_match_all('/([^=\t\n\r]*)=["]{0,1}([^"\n]*)["]{0,1}/', $output_line, $secondary_output);
			for($i = 0; $i <= sizeof($secondary_output[1]); $i++){ 
				if(isset($secondary_output[1][$i]) && isset($secondary_output[2][$i])){
					$tmp[$secondary_output[1][$i]] = $secondary_output[2][$i];
				}
			}
			if(!isset($tmp["priority"])){
				$tmp["priority"] = $priority;
			}
			$priority += 1;
			array_push($this->wpa_supplicant,$tmp);
		}
		$this->sort_wpa();
    }
	
	function sort_wpa(){
		usort($this->wpa_supplicant, function ($a, $b) {return $a['priority'] <=> $b['priority'];});
		$wifipriority = 1;
		foreach($this->wpa_supplicant as &$wifiarray){
			$wifiarray["priority"] = $wifipriority;
			$wifipriority += 1;
		}
	}
	
	function remove($ssid){
		$i = 0;
		foreach($this->wpa_supplicant as $wifiarray){
			if($wifiarray["ssid"] == $ssid){
				unset($this->wpa_supplicant[$i]);
				break;
			}
			$i += 1;
		}
		$this->sort_wpa();
	}
	
	function add($array){
		array_push($this->wpa_supplicant,$array);
		$this->sort_wpa();
	}
	
	function restart(){
		exec("sudo wpa_cli reconfigure");
	}
	
	function scan(){
		$result = [];
		$output = shell_exec('sudo iwlist wlan0 scan |grep -e ESSID -e IEEE -e "Encryption key" -e "Quality" -e "Cell" -e "Authentication Suites (1) :"');
		$prased_data = explode("Cell",$output);
		array_shift($prased_data);
		foreach ($prased_data as $data){
			preg_match_all("/.+Address: ([0-9A-Fa-f]+:[0-9A-Fa-f]+:[0-9A-Fa-f]+:[0-9A-Fa-f]+:[0-9A-Fa-f]+:[0-9A-Fa-f]+)/", $data, $tmp);
			$split["Address"] = $tmp[1][0];

			preg_match_all("/.+Quality=([0-9]+\/[0-9]+)/", $data, $tmp);
			$split["Quality"] = $tmp[1][0];
			if($split["Quality"] == null){
				$split["Quality"] = "0/70";
			}

			preg_match_all("/.+Signal level=-([0-9]+ dBm)/", $data, $tmp);
			$split["Signal_Level"] = $tmp[1][0];
			if($split["Encryption_Key"] == null){
				$split["Encryption_Key"] = "0 dBm";
			}

			preg_match_all("/.+Encryption key:(on|off)/", $data, $tmp);
			$split["Encryption_Key"] = $tmp[1][0];
			if($split["Encryption_Key"] == null){
				$split["Encryption_Key"] = "off";
			}

			preg_match_all('/.+ESSID:"(.+)"/', $data, $tmp);
			if(strpos($tmp[1][0],"\\x00") !== false){
				$split["ESSID"] = "-Hidden Network-";
			}else{
				$split["ESSID"] = $tmp[1][0];
			}
			if($split["ESSID"] == null){
				$split["ESSID"] = "-NO SSID-";
			}

			preg_match_all('/.+IE: (.+)/', $data, $tmp);
			$split["Encrpytion_Method"] = explode("Authentication Suites (1) : ",$tmp[1][0])[0];
			if($split["Encrpytion_Method"] == null){
				$split["Encrpytion_Method"] = "No Encryption";
			}
			
			if($split["Encryption_Key"] == "on" && $split["Encrpytion_Method"] !== null){
				if(strpos($split["Encrpytion_Method"],"WPA2") !== false){
					$split["Encrpytion_Method_Shortname"] = "WPA2";
				}else if(strpos($split["Encrpytion_Method"],"802.1x") !== false){
					$split["Encrpytion_Method_Shortname"] = "802.1x";
				}else{
					$split["Encrpytion_Method_Shortname"] = "No";
				}
			}else{
				$split["Encrpytion_Method_Shortname"] = "No";
			}
			
			
			preg_match_all('/.+Authentication Suites \(1\) : (.+)/', $data, $tmp);
			$split["Encryption_Suites"] = $tmp[1][0];
			if($split["Encryption_Suites"] == null){
				$split["Encryption_Suites"] = "No encryption";
			}

			array_push($result,$split);
		}
		return $result;
	}
	
	function current_connecting(){
		$result=[];
		if(exec('iw dev wlan0 link') !== 'Not connected.'){
			$ssid = exec("iwgetid -r");
			$result["ssid"] = $ssid;
			$c = exec("iwgetid -c -r");
			$result["channel"] = $c;
			$f = exec("iwgetid -f -r");
			$result["frequency"] = $f;
		}else{
			$result["ssid"] = "";
			$result["channel"] = "";
			$result["frequency"] = "";	
		}
		return $result;
	}
	function view_wifistorage(){
		return $this->wpa_supplicant;
	}
	
	function top_priority($ssid){
		$i = 0;
		foreach($this->wpa_supplicant as $wifiarray){
			if($wifiarray["ssid"] == $ssid){
				$this->wpa_supplicant[$i]["priority"] = 0;
				break;
			}
			$i += 1;
		}
		$this->sort_wpa();
	}
	
	function save(){
		$noquote = array("disabled","auth_alg","scan_ssid","key_mgmt","proto","pairwise","eap","priority");
		$fp = fopen('/etc/wpa_supplicant/wpa_supplicant.conf', 'w');
		fwrite($fp, 'country=DE'.PHP_EOL);
		fwrite($fp, 'ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev'.PHP_EOL);
		fwrite($fp, 'update_config=1'.PHP_EOL);
		fwrite($fp, PHP_EOL);
		
		foreach($this->wpa_supplicant as $wifiarray){
			fwrite($fp, 'network={'.PHP_EOL);
			foreach($wifiarray as $key => $value){
				if(in_array($key,$noquote)){
					fwrite($fp, "	".$key.'='.$value.''.PHP_EOL);
				}else{
					fwrite($fp, "	".$key.'="'.$value.'"'.PHP_EOL);
				}
			}
			fwrite($fp, '}'.PHP_EOL);
			fwrite($fp, PHP_EOL);
		}
		
		fclose($fp);
		$this->restart_wifi();
	}
	
	function restart_wifi(){
		shell_exec('sudo ifconfig wlan0 up');
		shell_exec('sudo ifconfig wlan1 up');
		shell_exec('sudo /etc/init.d/networking restart');
		$loss = shell_exec("ping -c 1 -q 255.255.255.0 -I wlan0 | grep -oP '\d+(?=% packet loss)'");
		if($loss == "0"){
			$failed = false;
			$output = shell_exec('sudo journalctl -xu networking.service -o json --since="$(sudo systemctl show networking --property=ExecMainStartTimestamp --value)"');
			$outputarr = preg_split('/\r\n|\r|\n/', $output);
			foreach($outputarr as $msg){
				$msgarray = json_decode($msg,true);
				if(isset($msgarray["MESSAGE"])){
					if(strpos($msgarray["MESSAGE"],"reason=WRONG_KEY") !== false){
						$failed = true;
					}
					if(strpos($msgarray["MESSAGE"],"Failed to read or parse configuration") !== false){
						$failed = true;
					}
					if(strpos($msgarray["MESSAGE"],"Failed to start Raise network interfaces") !== false){
						$failed = true;
					}
				}
			}
			if($failed){
				$fpwpa_supplicant_bk = fopen('/etc/wpa_supplicant/wpa_supplicant.conf', 'w');
				fwrite($fpwpa_supplicant_bk, $this->wpa_supplicantconf);
				fclose($fpwpa_supplicant_bk);
				return "ERROR_RESETED";
			}else{
				$fpwpa_supplicant_bk = fopen('/etc/wpa_supplicant/wpa_supplicant.conf', 'w');
				fwrite($fpwpa_supplicant_bk, $this->wpa_supplicantconf);
				fclose($fpwpa_supplicant_bk);
				return "ERROR_UNKNOWN_RESETED";
				
			}
		}else{
			return "SUCCESS";
		}
	}
}

class ifconfig
{
	function is_connected(){
		$connected = fopen("http://www.google.com:80/","r");
	  if($connected){
		 return true;
	  } else {
	   return false;
		}
	}
	
	function list_nic(){
		if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
			exec("getNICinfo.exe");
			sleep(1);
			$nics = [];
			$content = remove_utf8_bom(file_get_contents("NICinfo.txt"));
			$data = explode(PHP_EOL,$content);
			foreach ($data as $nicinfo){
				array_push($nics,explode(",",$nicinfo)[0]);
			}
			return $nics;
		} else {
			$result = [];
			exec('sudo ifconfig',$arrayoutput);
			if($arrayoutput == []){
			    exec('sudo ip a',$arrayoutput);
			}
			//print_r($arrayoutput);
			foreach ($arrayoutput as $line){
					$line = trim($line);
					$inlinedoutput .= $line."\n";
			}

		$InterfaceRawInformation = explode("\n\n",$inlinedoutput);
		array_pop($InterfaceRawInformation);
		//$prased_data = preg_split("/wlan.|lo|eth./", $unprased_data,-1,PREG_SPLIT_NO_EMPTY);
		foreach ($InterfaceRawInformation as $data){
			$data = preg_replace('/\n/', '', $data);
			preg_match('/(wlan[0-9]+|eth[0-9]+|lo)/', $data, $tmp);
			if(isset($tmp[1])){
				//$exported_information["InterfaceName"] = $tmp[1];
				$exported_information["InterfaceID"] = preg_replace('/\w+([0-9]+)/', '$1', $tmp[1]);
				if(strpos($tmp[1], 'eth') !== false){
					$exported_information["InterfaceIcon"] = "Ethernet";
				}else if(strpos($tmp[1], 'wlan') !== false){
					$exported_information["InterfaceIcon"] = "WiFi";
				}else if(strpos($tmp[1], 'lo') !== false){
					continue;
				}else{
					$exported_information["InterfaceIcon"] = "Unknown";
				}
			}else{
				$exported_information["InterfaceName"] = "Unknown";
				$exported_information["InterfaceID"] = "";
				$exported_information["InterfaceIcon"] = "Unknown";
				
			}
			
			preg_match('/HWaddr ([0-9A-Za-z][0-9A-Za-z]:[0-9A-Za-z][0-9A-Za-z]:[0-9A-Za-z][0-9A-Za-z]:[0-9A-Za-z][0-9A-Za-z]:[0-9A-Za-z][0-9A-Za-z]:[0-9A-Za-z][0-9A-Za-z])/', $data, $tmp);
			if(isset($tmp[1])){
				$exported_information["HardwareAddress"] = $tmp[1];
			}else{
				preg_match('/ether ([0-9A-Za-z][0-9A-Za-z]:[0-9A-Za-z][0-9A-Za-z]:[0-9A-Za-z][0-9A-Za-z]:[0-9A-Za-z][0-9A-Za-z]:[0-9A-Za-z][0-9A-Za-z]:[0-9A-Za-z][0-9A-Za-z])/', $data, $tmp);
				if(isset($tmp[1])){
					$exported_information["HardwareAddress"] = $tmp[1];
				}else{
					$exported_information["HardwareAddress"] = "Unknown";
				}
			}
			
			preg_match('/inet addr:([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/', $data, $tmp);
			if(isset($tmp[1])){
				$exported_information["IPv4Address"] = $tmp[1];
			}else{
				preg_match('/inet ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/', $data, $tmp);
				if(isset($tmp[1])){
					$exported_information["IPv4Address"] = $tmp[1];
				}else{
					$exported_information["IPv4Address"] = "Unknown";
				}
			}
			
			preg_match('/Mask:([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/', $data, $tmp);
			if(isset($tmp[1])){
				$exported_information["IPv4SubNetMask"] = $tmp[1];
			}else{
				preg_match('/mask ([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/', $data, $tmp);
				if(isset($tmp[1])){
					$exported_information["IPv4SubNetMask"] = $tmp[1];
				}else{
					$exported_information["IPv4SubNetMask"] = "Unknown";
				}
			}
			
			preg_match('/inet6 addr: ([a-zA-Z0-9:]+\/[0-9]+)/', $data, $tmp);
			if(isset($tmp[1])){
				$exported_information["IPv6Address"] = $tmp[1];
			}else{
				preg_match('/inet6 ([a-zA-Z0-9:]+)/', $data, $tmp);
				if(isset($tmp[1])){
					$exported_information["IPv6Address"] = $tmp[1];
				}else{
					$exported_information["IPv6Address"] = "Unknown";
				}
			}

			array_push($result,$exported_information);
		}

		return $result;
		}
	}
}

class ap
{
    public $settings = [];
	
    function __construct() {
		$filename = "/etc/hostapd/hostapd.conf";
		$handle = fopen($filename, "r");
		$input_lines = fread($handle, filesize($filename));
		fclose($handle);
		$primary_output = [];
		preg_match_all('/([^=\t\n\r]*)=["]{0,1}([^"\n]*)["]{0,1}/', $input_lines, $primary_output);
		for($i = 0; $i <= sizeof($primary_output[1]); $i++){ 
			if(isset($primary_output[1][$i]) && isset($primary_output[2][$i])){
				$this->settings[$primary_output[1][$i]] = $primary_output[2][$i];
			}
		}
    }
	
	function view_ap_settings(){
		return $this->settings;
	}
	
	function change_ap_settings($key,$val){
		$this->settings[$key] = $val;
	}
}