A live bird collage card for your Home Assistant dashboard.
Consolidate code in remaining pages, setting page updates
jaredb7ac9a0e4cbe35
diff --git a/homepage/views.php b/homepage/views.phpindex 987f5227..d4b45f33 100644--- a/homepage/views.php+++ b/homepage/views.php@@ -1,42 +1,13 @@<?php-$sys_timezone = "";-// If we can get the timezome from the systems timezone file ust that-if (file_exists('/etc/timezone')) {- $tz_data = file_get_contents('/etc/timezone');- if ($tz_data !== false) {- $sys_timezone = trim($tz_data);- }-} else {-// Else get timezone from the timedatectl command- $tz_data = shell_exec('timedatectl show');- $tz_data_array = parse_ini_string($tz_data);- if (is_array($tz_data_array) && array_key_exists('Timezone', $tz_data_array)) {- $sys_timezone = $tz_data_array['Timezone'];- }-}-//Finally if we have a valod timezone, set it as the one PHP uses-if ($sys_timezone !== "") {- date_default_timezone_set($sys_timezone);+if(file_exists('./scripts/common.php')){+ include_once "./scripts/common.php";+}else{+ include_once "./common.php";}session_start();-$user = shell_exec("awk -F: '/1000/{print $1}' /etc/passwd");-$user = trim($user);-$home = shell_exec("awk -F: '/1000/{print $6}' /etc/passwd");-$home = trim($home);if(!isset($_SESSION['behind'])) {- $fetch = shell_exec("sudo -u".$user." git -C ".$home."/BirdNET-Pi fetch 2>&1");- $str = trim(shell_exec("sudo -u".$user." git -C ".$home."/BirdNET-Pi status"));- if (preg_match("/behind '.*?' by (\d+) commit(s?)\b/", $str, $matches)) {- $num_commits_behind = $matches[1];- $_SESSION['behind'] = $num_commits_behind;- }- if (preg_match('/\b(\d+)\b and \b(\d+)\b different commits each/', $str, $matches)) {- $num1 = (int) $matches[1];- $num2 = (int) $matches[2];- $sum = $num1 + $num2;- $_SESSION['behind'] = $sum;- }+ $_SESSION['behind'] = getGitStatus();if(isset($_SESSION['behind'])&&intval($_SESSION['behind']) >= 99) {?><style>.updatenumber {@@ -45,11 +16,7 @@ if(!isset($_SESSION['behind'])) {</style><?php }}-if (file_exists('./scripts/thisrun.txt')) {- $config = parse_ini_file('./scripts/thisrun.txt');-} elseif (file_exists('./scripts/firstrun.ini')) {- $config = parse_ini_file('./scripts/firstrun.ini');-}+parseConfig();if ($config["LATITUDE"] == "0.000" && $config["LONGITUDE"] == "0.000") {echo "<center style='color:red'><b>WARNING: Your latitude and longitude are not set properly. Please do so now in Tools -> Settings.</center></b>";@@ -187,25 +154,25 @@ if(isset($_GET['view'])){if($_GET['view'] == "Advanced"){include('scripts/advanced.php');}if($_GET['view'] == "Included"){if(isset($_GET['species']) && isset($_GET['add'])){- $file = './scripts/include_species_list.txt';+ $file = getFilePath('include_species_list.txt');$str = file_get_contents("$file");$str = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $str);file_put_contents("$file", "$str");if(isset($_GET['species'])){foreach ($_GET['species'] as $selectedOption)- file_put_contents("./scripts/include_species_list.txt", $selectedOption."\n", FILE_APPEND);+ file_put_contents( getFilePath('include_species_list.txt'), $selectedOption."\n", FILE_APPEND);}} elseif(isset($_GET['species']) && isset($_GET['del'])){- $file = './scripts/include_species_list.txt';+ $file = getFilePath('include_species_list.txt');$str = file_get_contents("$file");$str = preg_replace('/^\h*\v+/m', '', $str);file_put_contents("$file", "$str");foreach($_GET['species'] as $selectedOption) {- $content = file_get_contents("../BirdNET-Pi/include_species_list.txt");+ $content = file_get_contents( getFilePath('include_species_list.txt'));$newcontent = str_replace($selectedOption, "", "$content");- file_put_contents("./scripts/include_species_list.txt", "$newcontent");+ file_put_contents( getFilePath('include_species_list.txt'), "$newcontent");}- $file = './scripts/include_species_list.txt';+ $file = getFilePath('include_species_list.txt');$str = file_get_contents("$file");$str = preg_replace('/^\h*\v+/m', '', $str);file_put_contents("$file", "$str");@@ -214,23 +181,23 @@ if(isset($_GET['view'])){}if($_GET['view'] == "Excluded"){if(isset($_GET['species']) && isset($_GET['add'])){- $file = './scripts/exclude_species_list.txt';+ $file = getFilePath('exclude_species_list.txt');$str = file_get_contents("$file");$str = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $str);file_put_contents("$file", "$str");foreach ($_GET['species'] as $selectedOption)- file_put_contents("./scripts/exclude_species_list.txt", $selectedOption."\n", FILE_APPEND);+ file_put_contents(getFilePath('exclude_species_list.txt'), $selectedOption."\n", FILE_APPEND);} elseif (isset($_GET['species']) && isset($_GET['del'])){- $file = './scripts/exclude_species_list.txt';+ $file = getFilePath('exclude_species_list.txt');$str = file_get_contents("$file");$str = preg_replace('/^\h*\v+/m', '', $str);file_put_contents("$file", "$str");foreach($_GET['species'] as $selectedOption) {- $content = file_get_contents("./scripts/exclude_species_list.txt");+ $content = file_get_contents(getFilePath('exclude_species_list.txt'));$newcontent = str_replace($selectedOption, "", "$content");- file_put_contents("./scripts/exclude_species_list.txt", "$newcontent");+ file_put_contents(getFilePath('exclude_species_list.txt'), "$newcontent");}- $file = './scripts/exclude_species_list.txt';+ $file = getFilePath('exclude_species_list.txt');$str = file_get_contents("$file");$str = preg_replace('/^\h*\v+/m', '', $str);file_put_contents("$file", "$str");@@ -241,11 +208,7 @@ if(isset($_GET['view'])){echo "<iframe src='scripts/filemanager/filemanager.php'></iframe>";}if($_GET['view'] == "Webterm"){- if (file_exists('./scripts/thisrun.txt')) {- $config = parse_ini_file('./scripts/thisrun.txt');- } elseif (file_exists('./scripts/firstrun.ini')) {- $config = parse_ini_file('./scripts/firstrun.ini');- }+ parseConfig();$caddypwd = $config['CADDY_PWD'];if (!isset($_SERVER['PHP_AUTH_USER'])) {header('WWW-Authenticate: Basic realm="My Realm"');@@ -267,11 +230,7 @@ if(isset($_GET['view'])){}}} elseif(isset($_GET['submit'])) {- if (file_exists('./scripts/thisrun.txt')) {- $config = parse_ini_file('./scripts/thisrun.txt');- } elseif (file_exists('./scripts/firstrun.ini')) {- $config = parse_ini_file('./scripts/firstrun.ini');- }+ parseConfig();$caddypwd = $config['CADDY_PWD'];if (!isset($_SERVER['PHP_AUTH_USER'])) {header('WWW-Authenticate: Basic realm="My Realm"');@@ -281,48 +240,48 @@ if(isset($_GET['view'])){} else {$submittedpwd = $_SERVER['PHP_AUTH_PW'];$submitteduser = $_SERVER['PHP_AUTH_USER'];- $allowedCommands = array('sudo systemctl stop livestream.service && sudo systemctl stop icecast2.service',- 'sudo systemctl restart livestream.service && sudo systemctl restart icecast2.service',- 'sudo systemctl disable --now livestream.service && sudo systemctl disable icecast2 && sudo systemctl stop icecast2.service',- 'sudo systemctl enable icecast2 && sudo systemctl start icecast2.service && sudo systemctl enable --now livestream.service',- 'sudo systemctl stop web_terminal.service',- 'sudo systemctl restart web_terminal.service',- 'sudo systemctl disable --now web_terminal.service',- 'sudo systemctl enable --now web_terminal.service',- 'sudo systemctl stop birdnet_log.service',- 'sudo systemctl restart birdnet_log.service',- 'sudo systemctl disable --now birdnet_log.service',- 'sudo systemctl enable --now birdnet_log.service',- 'sudo systemctl stop extraction.service',- 'sudo systemctl restart extraction.service',- 'sudo systemctl disable --now extraction.service',- 'sudo systemctl enable --now extraction.service',- 'sudo systemctl stop birdnet_server.service',- 'sudo systemctl restart birdnet_server.service',- 'sudo systemctl disable --now birdnet_server.service',- 'sudo systemctl enable --now birdnet_server.service',- 'sudo systemctl stop birdnet_analysis.service',- 'sudo systemctl restart birdnet_analysis.service',- 'sudo systemctl disable --now birdnet_analysis.service',- 'sudo systemctl enable --now birdnet_analysis.service',- 'sudo systemctl stop birdnet_stats.service',- 'sudo systemctl restart birdnet_stats.service',- 'sudo systemctl disable --now birdnet_stats.service',- 'sudo systemctl enable --now birdnet_stats.service',- 'sudo systemctl stop birdnet_recording.service',- 'sudo systemctl restart birdnet_recording.service',- 'sudo systemctl disable --now birdnet_recording.service',- 'sudo systemctl enable --now birdnet_recording.service',- 'sudo systemctl stop chart_viewer.service',- 'sudo systemctl restart chart_viewer.service',- 'sudo systemctl disable --now chart_viewer.service',- 'sudo systemctl enable --now chart_viewer.service',- 'sudo systemctl stop spectrogram_viewer.service',- 'sudo systemctl restart spectrogram_viewer.service',- 'sudo systemctl disable --now spectrogram_viewer.service',- 'sudo systemctl enable --now spectrogram_viewer.service',- 'stop_core_services.sh',- 'restart_services.sh',+ $allowedCommands = array('service stop livestream.service && service stop icecast2.service',+ 'service restart livestream.service && service restart icecast2.service',+ 'service disable livestream.service && service disable icecast2 && service stop icecast2.service',+ 'service enable icecast2 && service start icecast2.service && service enable livestream.service',+ 'service stop web_terminal.service',+ 'service restart web_terminal.service',+ 'service disable web_terminal.service',+ 'service enable web_terminal.service',+ 'service stop birdnet_log.service',+ 'service restart birdnet_log.service',+ 'service disable birdnet_log.service',+ 'service enable birdnet_log.service',+ 'service stop extraction.service',+ 'service restart extraction.service',+ 'service disable extraction.service',+ 'service enable extraction.service',+ 'service stop birdnet_server.service',+ 'service restart birdnet_server.service',+ 'service disable birdnet_server.service',+ 'service enable birdnet_server.service',+ 'service stop birdnet_analysis.service',+ 'service restart birdnet_analysis.service',+ 'service disable birdnet_analysis.service',+ 'service enable birdnet_analysis.service',+ 'service stop birdnet_stats.service',+ 'service restart birdnet_stats.service',+ 'service disable birdnet_stats.service',+ 'service enable birdnet_stats.service',+ 'service stop birdnet_recording.service',+ 'service restart birdnet_recording.service',+ 'service disable birdnet_recording.service',+ 'service enable birdnet_recording.service',+ 'service stop chart_viewer.service',+ 'service restart chart_viewer.service',+ 'service disable chart_viewer.service',+ 'service enable chart_viewer.service',+ 'service stop spectrogram_viewer.service',+ 'service restart spectrogram_viewer.service',+ 'service disable spectrogram_viewer.service',+ 'service enable spectrogram_viewer.service',+ 'system stop core.services',+ 'system restart core.services','sudo reboot','update_birdnet.sh','sudo shutdown now',@@ -331,33 +290,43 @@ if(isset($_GET['view'])){if($submittedpwd == $caddypwd && $submitteduser == 'birdnet' && in_array($command,$allowedCommands)){if(isset($command)){$initcommand = $command;- if (strpos($command, "systemctl") !== false) {+ $results = "";+ //Process the system commands differently+ if (strpos($command, "system") !== false) {+ $results = serviceMaintenance($command);+ //clear the command so we skip the next bits and go straight to output processing+ $command = '';+ }+ if (strpos($command, "service") !== false) {//If there more than one command to execute, processes then separately//currently only livestream service uses multiple commands to interact with the required servicesif (strpos($command, " && ") !== false) {$separate_commands = explode("&&", trim($command));$new_multiservice_status_command = "";foreach ($separate_commands as $indiv_service_command) {+ //Action the command+ serviceMaintenance($indiv_service_command);//explode the string by " " space so we can get each individual component of the command//and eventually the service name at the end$separate_command_tmp = explode(" ", trim($indiv_service_command));- //get the service names+ //get the service names so we can poll th status$new_multiservice_status_command .= " " . trim(end($separate_command_tmp));}$service_names = $new_multiservice_status_command;} else {- //only one service needs restarting so we only need to query the status of one service+ serviceMaintenance($command);+ //only one service needs restarting so we only need to query the status of one service$tmp = explode(" ", trim($command));$service_names = end($tmp);}-- $command .= " & sleep 3;sudo systemctl status " . $service_names;+ //Build up the command that will query the service status+ $command = "sleep 3;sudo systemctl status " . $service_names;}if($initcommand == "update_birdnet.sh") {unset($_SESSION['behind']);}- $results = shell_exec("$command 2>&1");+ $results .= shell_exec("$command 2>&1");$results = str_replace("FAILURE", "<span style='color:red'>FAILURE</span>", $results);$results = str_replace("failed", "<span style='color:red'>failed</span>",$results);$results = str_replace("active (running)", "<span style='color:green'><b>active (running)</b></span>",$results);diff --git a/scripts/advanced.php b/scripts/advanced.phpindex ae46ac3b..dd03e673 100644--- a/scripts/advanced.php+++ b/scripts/advanced.php@@ -1,11 +1,8 @@<?php-ini_set('display_errors', 1);-error_reporting(E_ERROR);--if (file_exists('./scripts/thisrun.txt')) {- $config = parse_ini_file('./scripts/thisrun.txt');-} elseif (file_exists('firstrun.ini')) {- $config = parse_ini_file('firstrun.ini');+if(file_exists('./scripts/common.php')){+ include_once "./scripts/common.php";+}else{+ include_once "./common.php";}$caddypwd = $config['CADDY_PWD'];@@ -26,332 +23,148 @@ if (!isset($_SERVER['PHP_AUTH_USER'])) {}if(isset($_GET['submit'])) {- $contents = file_get_contents('/etc/birdnet/birdnet.conf');- $contents2 = file_get_contents('./scripts/thisrun.txt');-if(isset($_GET["caddy_pwd"])) {$caddy_pwd = $_GET["caddy_pwd"];- if(strcmp($caddy_pwd,$config['CADDY_PWD']) !== 0) {- $contents = preg_replace("/CADDY_PWD=.*/", "CADDY_PWD=\"$caddy_pwd\"", $contents);- $contents2 = preg_replace("/CADDY_PWD=.*/", "CADDY_PWD=\"$caddy_pwd\"", $contents2);- $fh = fopen('/etc/birdnet/birdnet.conf', "w");- $fh2 = fopen("./scripts/thisrun.txt", "w");- fwrite($fh, $contents);- fwrite($fh2, $contents2);- exec('sudo /usr/local/bin/update_caddyfile.sh > /dev/null 2>&1 &');- }+ setSetting('CADDY_PWD', "\"$caddy_pwd\"",'update_caddyfile');}if(isset($_GET["ice_pwd"])) {$ice_pwd = $_GET["ice_pwd"];- if(strcmp($ice_pwd,$config['ICE_PWD']) !== 0) {- $contents = preg_replace("/ICE_PWD=.*/", "ICE_PWD=$ice_pwd", $contents);- $contents2 = preg_replace("/ICE_PWD=.*/", "ICE_PWD=$ice_pwd", $contents2);- }+ setSetting('ICE_PWD', $ice_pwd);}if(isset($_GET["birdnetpi_url"])) {$birdnetpi_url = $_GET["birdnetpi_url"];// remove trailing slash to prevent conf from becoming broken$birdnetpi_url = rtrim($birdnetpi_url, '/');- if(strcmp($birdnetpi_url,$config['BIRDNETPI_URL']) !== 0) {- $contents = preg_replace("/BIRDNETPI_URL=.*/", "BIRDNETPI_URL=$birdnetpi_url", $contents);- $contents2 = preg_replace("/BIRDNETPI_URL=.*/", "BIRDNETPI_URL=$birdnetpi_url", $contents2);- $fh = fopen('/etc/birdnet/birdnet.conf', "w");- $fh2 = fopen("./scripts/thisrun.txt", "w");- fwrite($fh, $contents);- fwrite($fh2, $contents2);- exec('sudo /usr/local/bin/update_caddyfile.sh > /dev/null 2>&1 &');- }+ setSetting('BIRDNETPI_URL', $birdnetpi_url,'update_caddyfile');}if(isset($_GET["rtsp_stream"])) {$rtsp_stream = str_replace("\r\n", ",", $_GET["rtsp_stream"]);- if(strcmp($rtsp_stream,$config['RTSP_STREAM']) !== 0) {- $contents = preg_replace("/RTSP_STREAM=.*/", "RTSP_STREAM=\"$rtsp_stream\"", $contents);- $contents2 = preg_replace("/RTSP_STREAM=.*/", "RTSP_STREAM=\"$rtsp_stream\"", $contents2);- $fh = fopen('/etc/birdnet/birdnet.conf', "w");- $fh2 = fopen("./scripts/thisrun.txt", "w");- fwrite($fh, $contents);- fwrite($fh2, $contents2);- exec('sudo systemctl restart birdnet_recording.service');- exec('sudo systemctl restart livestream.service');- }+ setSetting('RTSP_STREAM', "\"$rtsp_stream\"", ['restart birdnet_recording', 'restart livestream']);}if (isset($_GET["rtsp_stream_to_livestream"])) {$rtsp_stream_selected = trim($_GET["rtsp_stream_to_livestream"]);-- //Setting exists already, see if the value changed- if (strcmp($rtsp_stream_selected, $config['RTSP_STREAM_TO_LIVESTREAM']) !== 0) {- $contents = preg_replace("/RTSP_STREAM_TO_LIVESTREAM=.*/", "RTSP_STREAM_TO_LIVESTREAM=\"$rtsp_stream_selected\"", $contents);- $contents2 = preg_replace("/RTSP_STREAM_TO_LIVESTREAM=.*/", "RTSP_STREAM_TO_LIVESTREAM=\"$rtsp_stream_selected\"", $contents2);- $fh = fopen("/etc/birdnet/birdnet.conf", "w");- $fh2 = fopen("./scripts/thisrun.txt", "w");- fwrite($fh, $contents);- fwrite($fh2, $contents2);- sleep(1);- exec("sudo systemctl restart livestream.service");- }+ setSetting('RTSP_STREAM_TO_LIVESTREAM', "\"$rtsp_stream_selected\"", 'restart livestream');}if(isset($_GET["overlap"])) {$overlap = $_GET["overlap"];- if(strcmp($overlap,$config['OVERLAP']) !== 0) {- $contents = preg_replace("/OVERLAP=.*/", "OVERLAP=$overlap", $contents);- $contents2 = preg_replace("/OVERLAP=.*/", "OVERLAP=$overlap", $contents2);- }+ setSetting('OVERLAP', $overlap);}if(isset($_GET["confidence"])) {$confidence = $_GET["confidence"];- if(strcmp($confidence,$config['CONFIDENCE']) !== 0) {- $contents = preg_replace("/CONFIDENCE=.*/", "CONFIDENCE=$confidence", $contents);- $contents2 = preg_replace("/CONFIDENCE=.*/", "CONFIDENCE=$confidence", $contents2);- }+ setSetting('CONFIDENCE', $confidence);}if(isset($_GET["sensitivity"])) {$sensitivity = $_GET["sensitivity"];- if(strcmp($sensitivity,$config['SENSITIVITY']) !== 0) {- $contents = preg_replace("/SENSITIVITY=.*/", "SENSITIVITY=$sensitivity", $contents);- $contents2 = preg_replace("/SENSITIVITY=.*/", "SENSITIVITY=$sensitivity", $contents2);- }+ setSetting('SENSITIVITY', $sensitivity);}if(isset($_GET["freqshift_hi"]) && is_numeric($_GET['freqshift_hi'])) {$freqshift_hi = $_GET["freqshift_hi"];- if(strcmp($freqshift_hi,$config['FREQSHIFT_HI']) !== 0) {- $contents = preg_replace("/FREQSHIFT_HI=.*/", "FREQSHIFT_HI=$freqshift_hi", $contents);- $contents2 = preg_replace("/FREQSHIFT_HI=.*/", "FREQSHIFT_HI=$freqshift_hi", $contents2);- }+ setSetting('FREQSHIFT_HI', $freqshift_hi);}if(isset($_GET["freqshift_lo"]) && is_numeric($_GET['freqshift_lo'])) {$freqshift_lo = $_GET["freqshift_lo"];- if(strcmp($freqshift_lo,$config['FREQSHIFT_LO']) !== 0) {- $contents = preg_replace("/FREQSHIFT_LO=.*/", "FREQSHIFT_LO=$freqshift_lo", $contents);- $contents2 = preg_replace("/FREQSHIFT_LO=.*/", "FREQSHIFT_LO=$freqshift_lo", $contents2);- }+ setSetting('FREQSHIFT_HI', $freqshift_hi);}if(isset($_GET["freqshift_pitch"]) && is_numeric($_GET['freqshift_pitch'])) {$freqshift_pitch = $_GET["freqshift_pitch"];- if(strcmp($freqshift_pitch,$config['FREQSHIFT_PITCH']) !== 0) {- $contents = preg_replace("/FREQSHIFT_PITCH=.*/", "FREQSHIFT_PITCH=$freqshift_pitch", $contents);- $contents2 = preg_replace("/FREQSHIFT_PITCH=.*/", "FREQSHIFT_PITCH=$freqshift_pitch", $contents2);- }+ setSetting('FREQSHIFT_PITCH', $freqshift_pitch);}if(isset($_GET["freqshift_tool"])) {$freqshift_tool = $_GET["freqshift_tool"];- if(strcmp($freqshift_tool,$config['FREQSHIFT_TOOL']) !== 0) {- $contents = preg_replace("/FREQSHIFT_TOOL=.*/", "FREQSHIFT_TOOL=$freqshift_tool", $contents);- $contents2 = preg_replace("/FREQSHIFT_TOOL=.*/", "FREQSHIFT_TOOL=$freqshift_tool", $contents2);- }+ setSetting('FREQSHIFT_TOOL', $freqshift_tool);}if(isset($_GET["full_disk"])) {$full_disk = $_GET["full_disk"];- if(strcmp($full_disk,$config['FULL_DISK']) !== 0) {- $contents = preg_replace("/FULL_DISK=.*/", "FULL_DISK=$full_disk", $contents);- $contents2 = preg_replace("/FULL_DISK=.*/", "FULL_DISK=$full_disk", $contents2);- }+ setSetting('FULL_DISK', $full_disk);}if(isset($_GET["privacy_threshold"])) {$privacy_threshold = $_GET["privacy_threshold"];- if(strcmp($privacy_threshold,$config['PRIVACY_THRESHOLD']) !== 0) {- $contents = preg_replace("/PRIVACY_THRESHOLD=.*/", "PRIVACY_THRESHOLD=$privacy_threshold", $contents);- $contents2 = preg_replace("/PRIVACY_THRESHOLD=.*/", "PRIVACY_THRESHOLD=$privacy_threshold", $contents2);- exec('restart_services.sh');- }+ setSetting('PRIVACY_THRESHOLD', $privacy_threshold,'restart_services');}if(isset($_GET["rec_card"])) {- $rec_card = $_GET["rec_card"];- if(strcmp($rec_card,$config['REC_CARD']) !== 0) {- $contents = preg_replace("/REC_CARD=.*/", "REC_CARD=\"$rec_card\"", $contents);- $contents2 = preg_replace("/REC_CARD=.*/", "REC_CARD=\"$rec_card\"", $contents2);- }+ $rec_card = trim($_GET["rec_card"]);+ setSetting('REC_CARD', "\"$rec_card\"");}if(isset($_GET["channels"])) {$channels = $_GET["channels"];- if(strcmp($channels,$config['CHANNELS']) !== 0) {- $contents = preg_replace("/CHANNELS=.*/", "CHANNELS=$channels", $contents);- $contents2 = preg_replace("/CHANNELS=.*/", "CHANNELS=$channels", $contents2);- }+ setSetting('CHANNELS', $channels);}if(isset($_GET["recording_length"])) {$recording_length = $_GET["recording_length"];- if(strcmp($recording_length,$config['RECORDING_LENGTH']) !== 0) {- $contents = preg_replace("/RECORDING_LENGTH=.*/", "RECORDING_LENGTH=$recording_length", $contents);- $contents2 = preg_replace("/RECORDING_LENGTH=.*/", "RECORDING_LENGTH=$recording_length", $contents2);- }+ setSetting('RECORDING_LENGTH', $recording_length);}if(isset($_GET["extraction_length"])) {$extraction_length = $_GET["extraction_length"];- if(strcmp($extraction_length,$config['EXTRACTION_LENGTH']) !== 0) {- $contents = preg_replace("/EXTRACTION_LENGTH=.*/", "EXTRACTION_LENGTH=$extraction_length", $contents);- $contents2 = preg_replace("/EXTRACTION_LENGTH=.*/", "EXTRACTION_LENGTH=$extraction_length", $contents2);- }+ setSetting('EXTRACTION_LENGTH', $extraction_length);}if(isset($_GET["audiofmt"])) {$audiofmt = $_GET["audiofmt"];- if(strcmp($audiofmt,$config['AUDIOFMT']) !== 0) {- $contents = preg_replace("/AUDIOFMT=.*/", "AUDIOFMT=$audiofmt", $contents);- $contents2 = preg_replace("/AUDIOFMT=.*/", "AUDIOFMT=$audiofmt", $contents2);- }+ setSetting('AUDIOFMT', $audiofmt);}if(isset($_GET["silence_update_indicator"])) {$silence_update_indicator = 1;- if(strcmp($silence_update_indicator,$config['SILENCE_UPDATE_INDICATOR']) !== 0) {- $contents = preg_replace("/SILENCE_UPDATE_INDICATOR=.*/", "SILENCE_UPDATE_INDICATOR=$silence_update_indicator", $contents);- $contents2 = preg_replace("/SILENCE_UPDATE_INDICATOR=.*/", "SILENCE_UPDATE_INDICATOR=$silence_update_indicator", $contents2);- }+ setSetting('SILENCE_UPDATE_INDICATOR', $silence_update_indicator);} else {- $contents = preg_replace("/SILENCE_UPDATE_INDICATOR=.*/", "SILENCE_UPDATE_INDICATOR=0", $contents);- $contents2 = preg_replace("/SILENCE_UPDATE_INDICATOR=.*/", "SILENCE_UPDATE_INDICATOR=0", $contents2);+ setSetting('SILENCE_UPDATE_INDICATOR', 0);}if(isset($_GET["raw_spectrogram"])) {$raw_spectrogram = 1;- if(strcmp($RAW_SPECTROGRAM,$config['RAW_SPECTROGRAM']) !== 0) {- $contents = preg_replace("/RAW_SPECTROGRAM=.*/", "RAW_SPECTROGRAM=$raw_spectrogram", $contents);- $contents2 = preg_replace("/RAW_SPECTROGRAM=.*/", "RAW_SPECTROGRAM=$raw_spectrogram", $contents2);- }+ setSetting('RAW_SPECTROGRAM', $raw_spectrogram);} else {- $contents = preg_replace("/RAW_SPECTROGRAM=.*/", "RAW_SPECTROGRAM=0", $contents);- $contents2 = preg_replace("/RAW_SPECTROGRAM=.*/", "RAW_SPECTROGRAM=0", $contents2);+ setSetting('RAW_SPECTROGRAM', 0);}if(isset($_GET["custom_image"])) {$custom_image = $_GET["custom_image"];- if(strcmp($custom_image,$config['CUSTOM_IMAGE']) !== 0) {- $contents = preg_replace("/CUSTOM_IMAGE=.*/", "CUSTOM_IMAGE=$custom_image", $contents);- $contents2 = preg_replace("/CUSTOM_IMAGE=.*/", "CUSTOM_IMAGE=$custom_image", $contents2);- }++ setSetting('CUSTOM_IMAGE', $custom_image);}if(isset($_GET["custom_image_label"])) {$custom_image_label = $_GET["custom_image_label"];- if(strcmp($custom_image_label,$config['CUSTOM_IMAGE_TITLE']) !== 0) {- $contents = preg_replace("/CUSTOM_IMAGE_TITLE=.*/", "CUSTOM_IMAGE_TITLE=\"$custom_image_label\"", $contents);- $contents2 = preg_replace("/CUSTOM_IMAGE_TITLE=.*/", "CUSTOM_IMAGE_TITLE=\"$custom_image_label\"", $contents2);- }++ setSetting('CUSTOM_IMAGE_TITLE', "\"$custom_image_label\"");}if (isset($_GET["LogLevel_BirdnetRecordingService"])) {$birdnet_recording_service_log_level = trim($_GET["LogLevel_BirdnetRecordingService"]);- //If setting exists change it's value- if (array_key_exists('LogLevel_BirdnetRecordingService', $config)) {- //Setting exists already, see if the value changed- if (strcmp($birdnet_recording_service_log_level, $config['LogLevel_BirdnetRecordingService']) !== 0) {- $contents = preg_replace("/LogLevel_BirdnetRecordingService=.*/", "LogLevel_BirdnetRecordingService=\"$birdnet_recording_service_log_level\"", $contents);- $contents2 = preg_replace("/LogLevel_BirdnetRecordingService=.*/", "LogLevel_BirdnetRecordingService=\"$birdnet_recording_service_log_level\"", $contents2);- $fh = fopen("/etc/birdnet/birdnet.conf", "w");- $fh2 = fopen("./scripts/thisrun.txt", "w");- fwrite($fh, $contents);- fwrite($fh2, $contents2);- sleep(1);- exec("sudo systemctl restart birdnet_recording.service");- }- } else {- //Create the setting in the setting file - same as what update_birdnet_snippets.sh does but will take the users selected log level as the value- shell_exec('sudo echo "LogLevel_BirdnetRecordingService=\"' . $birdnet_recording_service_log_level . '\"" >> /etc/birdnet/birdnet.conf');- //also update this run txt file- shell_exec('sudo echo "LogLevel_BirdnetRecordingService=\"' . $birdnet_recording_service_log_level . '\"" >> ./scripts/thisrun.txt');-- //Reload the config files as we've changed the contents, we need to make sure the contents of the existing variables reflects contents of the config file- sleep(1);- $contents = file_get_contents('/etc/birdnet/birdnet.conf');- $contents2 = file_get_contents('./scripts/thisrun.txt');-- exec("sudo systemctl restart birdnet_recording.service");- }+ setSetting('LogLevel_BirdnetRecordingService', "\"$birdnet_recording_service_log_level\"",'restart birdnet_recording');}if (isset($_GET["LogLevel_SpectrogramViewerService"])) {$spectrogram_viewer_service_log_level = trim($_GET["LogLevel_SpectrogramViewerService"]);- //If setting exists change it's value- if (array_key_exists('LogLevel_SpectrogramViewerService', $config)) {- //Setting exists already, see if the value changed- if (strcmp($spectrogram_viewer_service_log_level, $config['LogLevel_SpectrogramViewerService']) !== 0) {- $contents = preg_replace("/LogLevel_SpectrogramViewerService=.*/", "LogLevel_SpectrogramViewerService=\"$spectrogram_viewer_service_log_level\"", $contents);- $contents2 = preg_replace("/LogLevel_SpectrogramViewerService=.*/", "LogLevel_SpectrogramViewerService=\"$spectrogram_viewer_service_log_level\"", $contents2);- $fh = fopen("/etc/birdnet/birdnet.conf", "w");- $fh2 = fopen("./scripts/thisrun.txt", "w");- fwrite($fh, $contents);- fwrite($fh2, $contents2);- sleep(1);- exec("sudo systemctl restart spectrogram_viewer.service");- }- } else {- //Create the setting in the setting file - same as what update_birdnet_snippets.sh does but will take the users selected log level as the value- shell_exec('sudo echo "LogLevel_SpectrogramViewerService=\"' . $spectrogram_viewer_service_log_level . '\"" >> /etc/birdnet/birdnet.conf');- //also update this run txt file- shell_exec('sudo echo "LogLevel_SpectrogramViewerService=\"' . $spectrogram_viewer_service_log_level . '\"" >> ./scripts/thisrun.txt');-- //Reload the config files as we've changed the contents, we need to make sure the contents of the existing variables reflects contents of the config file- sleep(1);- $contents = file_get_contents('/etc/birdnet/birdnet.conf');- $contents2 = file_get_contents('./scripts/thisrun.txt');-- exec("sudo systemctl restart spectrogram_viewer.service");- }+ setSetting('LogLevel_SpectrogramViewerService', "\"$spectrogram_viewer_service_log_level\"",'restart spectrogram_viewer');}if (isset($_GET["LogLevel_LiveAudioStreamService"])) {$livestream_audio_service_log_level = trim($_GET["LogLevel_LiveAudioStreamService"]);- //If setting exists change it's value- if (array_key_exists('LogLevel_LiveAudioStreamService', $config)) {- //Setting exists already, see if the value changed- if (strcmp($livestream_audio_service_log_level, $config['LogLevel_LiveAudioStreamService']) !== 0) {- $contents = preg_replace("/LogLevel_LiveAudioStreamService=.*/", "LogLevel_LiveAudioStreamService=\"$livestream_audio_service_log_level\"", $contents);- $contents2 = preg_replace("/LogLevel_LiveAudioStreamService=.*/", "LogLevel_LiveAudioStreamService=\"$livestream_audio_service_log_level\"", $contents2);- //Write the settings to the config files, so we can restart the relevant services- $fh = fopen("/etc/birdnet/birdnet.conf", "w");- $fh2 = fopen("./scripts/thisrun.txt", "w");- fwrite($fh, $contents);- fwrite($fh2, $contents2);- sleep(1);- exec("sudo systemctl restart livestream.service && sudo systemctl restart icecast2.service");- }- } else {- //Create the setting in the setting file - same as what update_birdnet_snippets.sh does but will take the users selected log level as the value- shell_exec('sudo echo "LogLevel_LiveAudioStreamService=\"' . $livestream_audio_service_log_level . '\"" >> /etc/birdnet/birdnet.conf');- //also update this run txt file- shell_exec('sudo echo "LogLevel_LiveAudioStreamService=\"' . $livestream_audio_service_log_level . '\"" >> ./scripts/thisrun.txt');-- //Reload the config files as we've changed the contents, we need to make sure the contents of the existing variables reflects contents of the config file- sleep(1);- $contents = file_get_contents('/etc/birdnet/birdnet.conf');- $contents2 = file_get_contents('./scripts/thisrun.txt');-- exec("sudo systemctl restart livestream.service && sudo systemctl restart icecast2.service");- }+ setSetting('LogLevel_LiveAudioStreamService', "\"$livestream_audio_service_log_level\"",['restart livestream','restart icecast2']);}-- //Finally write the data out. some sections do this themselves in order to have the new settings ready for the services that will be restarted- //but will doubly ensure the settings are saved after any modification- $fh = fopen('/etc/birdnet/birdnet.conf', "w");- $fh2 = fopen("./scripts/thisrun.txt", "w");- fwrite($fh, $contents);- fwrite($fh2, $contents2);}-$user = trim(shell_exec("awk -F: '/1000/{print $1}' /etc/passwd"));-$home = trim(shell_exec("awk -F: '/1000/{print $6}' /etc/passwd"));--$count_labels = count(file($home."/BirdNET-Pi/model/labels.txt"));-$count = $count_labels;+$count = getLabelsCount();?><meta name="viewport" content="width=device-width, initial-scale=1"><style>@@ -360,11 +173,7 @@ $count = $count_labels;<div class="settings"><?php-if (file_exists('./scripts/thisrun.txt')) {- $newconfig = parse_ini_file('./scripts/thisrun.txt');-} elseif (file_exists('./scripts/firstrun.ini')) {- $newconfig = parse_ini_file('./scripts/firstrun.ini');-}+$newconfig = $config;?><div class="brbanner"><h1>Advanced Settings</h1></div><br><form action="" method="GET">@@ -415,8 +224,7 @@ if (file_exists('./scripts/thisrun.txt')) {<select name="audiofmt"><option selected="<?php print($newconfig['AUDIOFMT']);?>"><?php print($newconfig['AUDIOFMT']);?></option><?php- $formats = array("8svx", "aif", "aifc", "aiff", "aiffc", "al", "amb", "amr-nb", "amr-wb", "anb", "au", "avr", "awb", "caf", "cdda", "cdr", "cvs", "cvsd", "cvu", "dat", "dvms", "f32", "f4", "f64", "f8", "fap", "flac", "fssd", "gsm", "gsrt", "hcom", "htk", "ima", "ircam", "la", "lpc", "lpc10", "lu", "mat", "mat4", "mat5", "maud", "mp2", "mp3", "nist", "ogg", "paf", "prc", "pvf", "raw", "s1", "s16", "s2", "s24", "s3", "s32", "s4", "s8", "sb", "sd2", "sds", "sf", "sl", "sln", "smp", "snd", "sndfile", "sndr", "sndt", "sou", "sox", "sph", "sw", "txw", "u1", "u16", "u2", "u24", "u3", "u32", "u4", "u8", "ub", "ul", "uw", "vms", "voc", "vorbis", "vox", "w64", "wav", "wavpcm", "wv", "wve", "xa", "xi");-foreach($formats as $format){+foreach($audio_formats as $format){echo "<option value='$format'>$format</option>";}?>@@ -577,10 +385,9 @@ foreach($formats as $format){<select name="freqshift_tool"><option selected="<?php print($newconfig['FREQSHIFT_TOOL']);?>"><?php print($newconfig['FREQSHIFT_TOOL']);?></option><?php- $formats = array("sox","ffmpeg");- $formats = array_diff($formats, array($newconfig['FREQSHIFT_TOOL']));- foreach($formats as $format){+ $freqshift_tools = array_diff($freqshift_tools, array($newconfig['FREQSHIFT_TOOL']));+ foreach($freqshift_tools as $format){echo "<option value='$format'>$format</option>";}?>@@ -686,7 +493,7 @@ foreach($formats as $format){</table><br><br><input type="hidden" name="view" value="Advanced">- <button onclick="if(<?php print($newconfig['PRIVACY_THRESHOLD']);?> != document.getElementById('privacy_threshold').value){return confirm('This will take about 90 seconds.')} collectrtspUrls();" type="submit" name="submit" value="advanced">+ <button onclick="if(<?php print($newconfig['PRIVACY_THRESHOLD']); ?> != document.getElementById('privacy_threshold').value){collectrtspUrls(); return confirm('This will take about 90 seconds.');}else{collectrtspUrls();}" type="submit" name="submit" value="advanced"><?phpif(isset($_GET['submit'])){echo "Success!";diff --git a/scripts/common.php b/scripts/common.phpindex b1cfe920..d8991bb2 100644--- a/scripts/common.php+++ b/scripts/common.php@@ -4,8 +4,16 @@ ini_set('user_agent', 'PHP_Flickr/1.0');ini_set('display_errors', 1);error_reporting(E_ERROR);+//Setup the session if we're not using the API, since the API endpoint sets up it's own session+if (!isset($api_incl)) {+ $api_incl = false;+ session_set_cookie_params(7200);+ session_start();+}+//Get the user and home directory for the first user in the system (userid 1000)$user = shell_exec("awk -F: '/1000/{print $1}' /etc/passwd");+$user = trim($user);$home = shell_exec("awk -F: '/1000/{print $6}' /etc/passwd");$home = trim($home);@@ -30,19 +38,10 @@ if ($sys_timezone !== "") {date_default_timezone_set($sys_timezone);}-//Setup the session if we're not using the API, since the API endpoint sets up it's own session-if (!isset($api_incl)) {- $api_incl = false;- session_set_cookie_params(7200);- session_start();-}////////// PARSES THE CONFIG FILE //////////-if (file_exists('./scripts/thisrun.txt')) {- $config = parse_ini_file('./scripts/thisrun.txt');-} elseif (file_exists('./scripts/firstrun.ini')) {- $config = parse_ini_file('./scripts/firstrun.ini');-}+$config = [];+parseConfig();//Set a default site name if nothing iss configuredif ($config["SITE_NAME"] == "") {@@ -51,6 +50,43 @@ if ($config["SITE_NAME"] == "") {$site_name = $config['SITE_NAME'];}+$models = array("BirdNET_6K_GLOBAL_MODEL", "BirdNET_GLOBAL_3K_V2.3_Model_FP16");+$audio_formats = array("8svx", "aif", "aifc", "aiff", "aiffc", "al", "amb", "amr-nb", "amr-wb", "anb", "au", "avr", "awb", "caf", "cdda", "cdr", "cvs", "cvsd", "cvu", "dat", "dvms", "f32", "f4", "f64", "f8", "fap", "flac", "fssd", "gsm", "gsrt", "hcom", "htk", "ima", "ircam", "la", "lpc", "lpc10", "lu", "mat", "mat4", "mat5", "maud", "mp2", "mp3", "nist", "ogg", "paf", "prc", "pvf", "raw", "s1", "s16", "s2", "s24", "s3", "s32", "s4", "s8", "sb", "sd2", "sds", "sf", "sl", "sln", "smp", "snd", "sndfile", "sndr", "sndt", "sou", "sox", "sph", "sw", "txw", "u1", "u16", "u2", "u24", "u3", "u32", "u4", "u8", "ub", "ul", "uw", "vms", "voc", "vorbis", "vox", "w64", "wav", "wavpcm", "wv", "wve", "xa", "xi");+$freqshift_tools = array("sox", "ffmpeg");++//Database Languages+$langs = array(+ 'not-selected' => 'Not Selected',+ "af" => "Afrikaans",+ "ca" => "Catalan",+ "cs" => "Czech",+ "zh" => "Chinese",+ "hr" => "Croatian",+ "da" => "Danish",+ "nl" => "Dutch",+ "en" => "English",+ "et" => "Estonian",+ "fi" => "Finnish",+ "fr" => "French",+ "de" => "German",+ "hu" => "Hungarian",+ "is" => "Icelandic",+ "id" => "Indonesia",+ "it" => "Italian",+ "ja" => "Japanese",+ "lv" => "Latvian",+ "lt" => "Lithuania",+ "no" => "Norwegian",+ "pl" => "Polish",+ "pt" => "Portugues",+ "ru" => "Russian",+ "sk" => "Slovak",+ "sl" => "Slovenian",+ "es" => "Spanish",+ "sv" => "Swedish",+ "th" => "Thai",+ "uk" => "Ukrainian"+);//Reference to database connection$DB_CONN = null;@@ -107,7 +143,7 @@ function disconnect_from_birdsdb()*/function db_execute_query($query, $bind_params = [], $fetchAllRecords = false, $fetchMode = SQLITE3_ASSOC){- global $DB_CONN, $api_incl;+ global $DB_CONN;$success = false;$message = '';$data_to_return = null;@@ -190,6 +226,15 @@ function getDetectionCountToday()return db_execute_query('SELECT COUNT(*) FROM detections WHERE Date == DATE(\'now\', \'localtime\')');}+/**+ * Returns detection info for the most recent detection today+ * @return array+ */+function getMostRecentDetectionToday()+{+ return db_execute_query('SELECT * FROM detections WHERE Date == DATE(\'now\', \'localtime\') ORDER BY TIME DESC LIMIT 1', [], true);+}+/*** Returns a count of detections in the past hour* @return array@@ -936,6 +981,41 @@ function getLastWeekDates()return ['start_date' => $startdate, 'end_date' => $enddate];}+/**+ * Change Database Language+ *+ * @param $model+ * @param $language+ * @return string|null+ */+function changeLanguage($model, $language)+{+ global $config, $user;+ //Re-parse the config just in case+ parseConfig();+ $result = "";++ // Update Language settings only if a change is requested+ if ($model != $config['MODEL'] || $language != $config['DATABASE_LANG']) {+ if (strlen($language) == 2) {+ $scripts_dir = getDirectory('scripts');++ // Archive old language file+ $result = syslog_shell_exec("cp -f " . getFilePath('labels.txt') . " " . getFilePath('labels.txt.old'), $user);++ if ($model == "BirdNET_GLOBAL_3K_V2.3_Model_FP16") {+ // Install new language label file+ $result = syslog_shell_exec("sudo chmod +x $scripts_dir/install_language_label_nm.sh && $scripts_dir/install_language_label_nm.sh -l $language", $user);+ } else {+ $result = syslog_shell_exec("$scripts_dir/install_language_label.sh -l $language", $user);+ }++ syslog(LOG_INFO, "Successfully changed language to '$language' and model to '$model'");+ }+ }+ return $result;+}+/*** Directory Path Helper, returns a full directory path for a supplied directory name e.g home, processed, extracted*@@ -972,6 +1052,8 @@ function getDirectory($dir)return getDirectory('birdnet_pi') . '/config';} elseif ($dir == "models" || $dir == "model") {return getDirectory('birdnet_pi') . '/model';+ } elseif ($dir == "python3_ve") {+ return getDirectory('birdnet_pi') . '/birdnet/bin';} elseif ($dir == "scripts") {return getDirectory('birdnet_pi') . '/scripts';} elseif ($dir == "templates") {@@ -993,45 +1075,596 @@ function getFilePath($filename){if ($filename == "analyzing_now.txt") {return getDirectory('birdnet_pi') . "/analyzing_now.txt";+ //} else if ($filename == "apprise.txt") {return getDirectory('birdnet_pi') . "/apprise.txt";+ //} else if ($filename == "birdnet.conf") {return getDirectory('birdnet_pi') . "/birdnet.conf";+ //} else if ($filename == "BirdDB.txt") {return getDirectory('birdnet_pi') . "/BirdDB.txt";+ //} else if ($filename == "birds.db") {return getDirectory('scripts') . "/birds.db";+ //} else if ($filename == "blacklisted_images.txt") {return getDirectory('scripts') . "/blacklisted_images.txt";+ //} else if ($filename == "disk_check_exclude.txt") {return getDirectory('scripts') . "/disk_check_exclude.txt";+ //} else if ($filename == "exclude_species_list.txt") {- return getDirectory('home') . "/exclude_species_list.txt";+ return getDirectory('scripts') . "/exclude_species_list.txt";+ //} else if ($filename == "firstrun.ini") {return getDirectory('home') . "/firstrun.ini";+ //} else if ($filename == "HUMAN.txt") {return getDirectory('birdnet_pi') . "/HUMAN.txt";+ //} else if ($filename == "include_species_list.txt") {- return getDirectory('birdnet_pi') . "/include_species_list.txt";- } else if ($filename == "labels.txt") {- return getDirectory('model') . "/labels.txt";+ return getDirectory('scripts') . "/include_species_list.txt";+ //+ } else if ($filename == "labels.txt" || $filename == "labels.txt.old") {+ return getDirectory('model') . "/$filename";+ //} else if ($filename == "labels_flickr.txt") {return getDirectory('model') . "/labels_flickr.txt";+ //} else if ($filename == "labels_l18n.zip") {return getDirectory('model') . "/labels_l18n.zip";+ //} else if ($filename == "labels_lang.txt") {return getDirectory('model') . "/labels_lang.txt";+ //} else if ($filename == "labels_nm.zip") {return getDirectory('model') . "/labels_nm.zip";+ //} else if ($filename == "lastrun.txt") {return getDirectory('scripts') . "/lastrun.txt";+ //+ } else if ($filename == "python3") {+ return getDirectory('python3_ve') . "/python3 ";+ //+ } else if ($filename == "python3_appraise") {+ return getDirectory('python3_ve') . "/apprise ";+ //+ } else if ($filename == "species.py") {+ return getDirectory('scripts') . "/species.py";+ //} else if ($filename == "thisrun.txt") {return getDirectory('scripts') . "/thisrun.txt";+ //}return "";}+/**+ * Updates the setting value for the supplied setting name, if the setting doesn't exist it will be created+ *+ * @param $setting_name string Setting Name e.g SITE_NAME, BIRDWEATHER_ID, MODEL etc+ * @param $setting_value string|int Setting value - This value has to be exactly how it needs to be stored (same as what was used in preg_replace) and properly escaped eg "\"asetting"\"+ * @param $post_save_command string CommaAnd to execute after saving+ * @return void+ */+function setSetting($setting_name, $setting_value, $post_save_command = null)+{+ global $config;++ //Setting exists already, see if the value changed+ if (array_key_exists($setting_name, $config)) {+ //Strip any outer quotes from the setting value (e.g "$rec_card") and then test if it change how it was originally tested+ //https://stackoverflow.com/questions/9734758/remove-quotes-from-start-and-end-of-string-in-php+ $setting_value_clean = preg_replace('~^"?(.*?)"?$~', '$1', $setting_value);++ if (strcmp($setting_value_clean, $config[$setting_name]) !== 0) {+ $contents = file_get_contents(getFilePath('birdnet.conf'));+ $contents2 = file_get_contents(getFilePath('thisrun.txt'));+ //+ if ($contents !== false && $contents2 !== false) {+ //Update the value+ $contents = preg_replace("/$setting_name=.*/", "$setting_name=$setting_value", $contents);+ $contents2 = preg_replace("/$setting_name=.*/", "$setting_name=$setting_value", $contents2);++ //Write all the data out again to the the respective files+ // $fh = fopen("/etc/birdnet/birdnet.conf", "w");+ $fh = fopen(getFilePath('birdnet.conf'), "w");+ $fh2 = fopen(getFilePath('thisrun.txt'), "w");++ if ($fh !== false && $fh2 !== false) {+ fwrite($fh, $contents);+ fwrite($fh2, $contents2);+ //Check if we need to execute a command after saving+ if (isset($post_save_command)) {+ sleep(1);+ if (!is_array($post_save_command)) {+ executeSysCommand($post_save_command);+ } else {+ //array of commands+ foreach ($post_save_command as $single_command) {+ executeSysCommand($single_command);+ }+ }+ }+ //Reload the settings to update our global $config variable+ parseConfig();+ }+ }+ }+ } else {+ //Create the setting in the setting file+ shell_exec('sudo echo "' . $setting_name . '=' . $setting_value . '" >> ' . getFilePath('birdnet.conf'));+ //also update this run txt file+ shell_exec('sudo echo "' . $setting_name . '=' . $setting_value . '" >> ' . getFilePath('thisrun.txt'));++ //Check if we need to execute a command after saving+ if (isset($post_save_command)) {+ sleep(1);+ if (!is_array($post_save_command)) {+ executeSysCommand($post_save_command);+ } else {+ //array of commands+ foreach ($post_save_command as $single_command) {+ executeSysCommand($single_command);+ }+ }+ }+ //Reload the settings to update our global $config variable+ parseConfig();+ }+}++/**+ * Returns the value for the supplied setting name+ *+ * @param $setting_name+ * @return mixed|null+ */+function getSetting($setting_name)+{+ global $config;+ $setting_value = null;+ if (array_key_exists($setting_name, $config)) {+ $setting_value = $config[$setting_name];+ }++ return $setting_value;+}++/**+ * Returns the username of the user with User ID 1000+ *+ * @return string+ */+function getUser()+{+ global $user;+ return $user;+}++/**+ * Executes commands against the system through a shorthand command type+ *+ * @param $command_type string+ * @param $extra_data_to_pass string|[] Data or params that will be passed through to the command+ * @return false|string|null+ */+function executeSysCommand($command_type, $extra_data_to_pass = null)+{+ global $user, $home;++ $command_type = strtolower($command_type);+ $result = null;++ if ($command_type == "appraise_notification") {+ $result = shell_exec(getFilePath('python3_appraise') . " -vv --plugin-path " . $home . "/.apprise/plugins " . " -t '" . escapeshellcmd($extra_data_to_pass['title']) . "' -b '" . escapeshellcmd($extra_data_to_pass['body']) . "' " . $extra_data_to_pass['attach'] . " " . $extra_data_to_pass['cf'] . " ");+ //+ } else if ($command_type == "current_timezone") {+ $result = shell_exec("cat /etc/timezone");+ //+ } else if ($command_type == "disable_ntp") {+ $result = shell_exec("sudo timedatectl set-ntp false");+ //+ } else if ($command_type == "enable_ntp") {+ $result = shell_exec("sudo timedatectl set-ntp true");+ //+ } else if ($command_type == "is_ntp_active") {+ $result = shell_exec("sudo timedatectl | grep \"NTP service: active\"");+ //+ } else if ($command_type == "restart_php") {+ $result = serviceMaintenance('restart php.service');+ //+ } else if ($command_type == "restart_services") {+ syslog(LOG_INFO, "Restarting Services");+ $result = serviceMaintenance('restart core.services');+ //+ } else if ($command_type == "restart birdnet_recording") {+ $result = serviceMaintenance('restart birdnet_recording.service');+ //+ } else if ($command_type == "restart icecast2") {+ $result = serviceMaintenance('restart icecast2.service');+ //+ } else if ($command_type == "restart livestream") {+ $result = serviceMaintenance('restart livestream.service');+ //+ } else if ($command_type == "restart spectrogram_viewer") {+ $result = serviceMaintenance('restart spectrogram_viewer.service');+ //+ } else if ($command_type == "set_date") {+ $command = "sudo date -s '" . $extra_data_to_pass['date'] . " " . $extra_data_to_pass['time'] . "'";+ $result = shell_exec($command);+ //+ } else if ($command_type == "set_timezone") {+ $command = "sudo timedatectl set-timezone $extra_data_to_pass";+ $result = shell_exec($command);+ //+ } else if ($command_type == "test_threshold") {+ $command = "sudo -u $user " . getFilePath('python3') . ' ' . getFilePath('species.py') . " --threshold " . escapeshellcmd($extra_data_to_pass) . " 2>&1";+ $result = shell_exec($command);+ //+ } else if ($command_type == "update_caddyfile") {+ $result = exec("sudo /usr/local/bin/update_caddyfile.sh > /dev/null 2>&1 &");+ //+ } else if ($command_type == "update_birdnet") {+ $result = shell_exec("update_birdnet.sh");+ //+ } else if ($command_type == "reboot_birdnet") {+ $result = shell_exec("sudo reboot");+ //+ } else if ($command_type == "shutdown_birdnet") {+ $result = shell_exec("sudo shutdown now");+ //+ } else if ($command_type == "clear_all_data") {+ $result = shell_exec("sudo clear_all_data.sh");+ //+ }++ return $result;+}++/**+ * Performs tasks such as stop, restart, disable and enable on the supplied service+ * input command must contain the service name and must contain a keyword that describes the action+ * positioning does not matter+ * eg. restart livestream.service, stop birdnet_recording.service+ *+ * @param $command String Command containing a keyword [stop,restart,disable,enable] and the service name+ * @return false|string|null+ */+function serviceMaintenance($command)+{+ $command = trim($command);+ $result = "";++ ///e.g $command = 'service stop livestream.service', match the service name+ ////// BIRDNET LOG SERVICE //////+ if (strpos($command, 'birdnet_log.service') !== false) {+ if (strpos($command, 'stop') !== false) {+ $result = shell_exec('sudo systemctl stop birdnet_log.service 2>&1');+ } else if (strpos($command, 'restart') !== false) {+ $result = shell_exec('sudo systemctl restart birdnet_log.service 2>&1');+ } else if (strpos($command, 'disable') !== false) {+ $result = shell_exec('sudo systemctl disable --now birdnet_log.service 2>&1');+ } else if (strpos($command, 'enable') !== false) {+ $result = shell_exec('sudo systemctl enable --now birdnet_log.service 2>&1');+ }+ } ////// BIRDNET SERVER SERVICE //////+ else if (strpos($command, 'birdnet_server.service') !== false) {+ if (strpos($command, 'stop') !== false) {+ $result = shell_exec('sudo systemctl stop birdnet_server.service 2>&1');+ } else if (strpos($command, 'restart') !== false) {+ $result = shell_exec('sudo systemctl restart birdnet_server.service 2>&1');+ } else if (strpos($command, 'disable') !== false) {+ $result = shell_exec('sudo systemctl disable --now birdnet_server.service 2>&1');+ } else if (strpos($command, 'enable') !== false) {+ $result = shell_exec('sudo systemctl enable --now birdnet_server.service 2>&1');+ }+ } ////// BIRDNET ANALYSIS SERVICE //////+ else if (strpos($command, 'birdnet_analysis.service') !== false) {+ if (strpos($command, 'stop') !== false) {+ $result = shell_exec('sudo systemctl stop birdnet_analysis.service 2>&1');+ } else if (strpos($command, 'restart') !== false) {+ $result = shell_exec('sudo systemctl restart birdnet_analysis.service 2>&1');+ } else if (strpos($command, 'disable') !== false) {+ $result = shell_exec('sudo systemctl disable --now birdnet_analysis.service 2>&1');+ } else if (strpos($command, 'enable') !== false) {+ $result = shell_exec('sudo systemctl enable --now birdnet_analysis.service 2>&1');+ }+ } ////// BIRDNET STATS SERVICE //////+ else if (strpos($command, 'birdnet_stats.service') !== false) {+ if (strpos($command, 'stop') !== false) {+ $result = shell_exec('sudo systemctl stop birdnet_stats.service 2>&1');+ } else if (strpos($command, 'restart') !== false) {+ $result = shell_exec('sudo systemctl restart birdnet_stats.service 2>&1');+ } else if (strpos($command, 'disable') !== false) {+ $result = shell_exec('sudo systemctl disable --now birdnet_stats.service 2>&1');+ } else if (strpos($command, 'enable') !== false) {+ $result = shell_exec('sudo systemctl enable --now birdnet_stats.service 2>&1');+ }+ } ////// BIRDNET RECORDING SERVICE //////+ else if (strpos($command, 'birdnet_recording.service') !== false) {+ if (strpos($command, 'stop') !== false) {+ $result = shell_exec('sudo systemctl stop birdnet_recording.service 2>&1');+ } else if (strpos($command, 'restart') !== false) {+ $result = shell_exec('sudo systemctl restart birdnet_recording.service 2>&1');+ } else if (strpos($command, 'disable') !== false) {+ $result = shell_exec('sudo systemctl disable --now birdnet_recording.service 2>&1');+ } else if (strpos($command, 'enable') !== false) {+ $result = shell_exec('sudo systemctl enable --now birdnet_recording.service 2>&1');+ }+ } ////// LIVESTREAM SERVICE //////+ else if (strpos($command, 'livestream.service') !== false) {+ //Check which keyword exists+ if (strpos($command, 'stop') !== false) {+ $result = shell_exec('sudo systemctl stop livestream.service && sudo systemctl stop icecast2.service 2>&1');+ } else if (strpos($command, 'restart') !== false) {+ $result = shell_exec('sudo systemctl restart livestream.service && sudo systemctl restart icecast2.service 2>&1');+ } else if (strpos($command, 'disable') !== false) {+ $result = shell_exec('sudo systemctl disable --now livestream.service && sudo systemctl disable icecast2 && sudo systemctl stop icecast2.service 2>&1');+ } else if (strpos($command, 'enable') !== false) {+ $result = shell_exec('sudo systemctl enable icecast2 && sudo systemctl start icecast2.service && sudo systemctl enable --now livestream.service 2>&1');+ }+ } ////// WEB TERMINAL SERVICE //////+ else if (strpos($command, 'web_terminal.service') !== false) {+ if (strpos($command, 'stop') !== false) {+ $result = shell_exec('sudo systemctl stop web_terminal.service 2>&1');+ } else if (strpos($command, 'restart') !== false) {+ $result = shell_exec('sudo systemctl restart web_terminal.service 2>&1');+ } else if (strpos($command, 'disable') !== false) {+ $result = shell_exec('sudo systemctl disable --now web_terminal.service 2>&1');+ } else if (strpos($command, 'enable') !== false) {+ $result = shell_exec('sudo systemctl enable --now web_terminal.service 2>&1');+ }+ } ////// EXTRACTION SERVICE //////+ else if (strpos($command, 'extraction.service') !== false) {+ if (strpos($command, 'stop') !== false) {+ $result = shell_exec('sudo systemctl stop extraction.service 2>&1');+ } else if (strpos($command, 'restart') !== false) {+ $result = shell_exec('sudo systemctl restart extraction.service 2>&1');+ } else if (strpos($command, 'disable') !== false) {+ $result = shell_exec('sudo systemctl disable --now extraction.service 2>&1');+ } else if (strpos($command, 'enable') !== false) {+ $result = shell_exec('sudo systemctl enable --now extraction.service 2>&1');+ }+ }////// CHART VIEWER SERVICE //////+ else if (strpos($command, 'chart_viewer.service') !== false) {+ if (strpos($command, 'stop') !== false) {+ $result = shell_exec('sudo systemctl stop chart_viewer.service 2>&1');+ } else if (strpos($command, 'restart') !== false) {+ $result = shell_exec('sudo systemctl restart chart_viewer.service 2>&1');+ } else if (strpos($command, 'disable') !== false) {+ $result = shell_exec('sudo systemctl disable --now chart_viewer.service 2>&1');+ } else if (strpos($command, 'enable') !== false) {+ $result = shell_exec('sudo systemctl enable --now chart_viewer.service 2>&1');+ }+ } ////// SPECTROGRAM VIEWER SERVICE //////+ else if (strpos($command, 'spectrogram_viewer.service') !== false) {+ if (strpos($command, 'stop') !== false) {+ $result = shell_exec('sudo systemctl stop spectrogram_viewer.service 2>&1');+ } else if (strpos($command, 'restart') !== false) {+ $result = shell_exec('sudo systemctl restart spectrogram_viewer.service 2>&1');+ } else if (strpos($command, 'disable') !== false) {+ $result = shell_exec('sudo systemctl disable --now spectrogram_viewer.service 2>&1');+ } else if (strpos($command, 'enable') !== false) {+ $result = shell_exec('sudo systemctl enable --now spectrogram_viewer.service 2>&1');+ }+ } ////// CORE SERVICES //////+ else if ((strpos($command, 'core.services') !== false) || (strpos($command, 'core services') !== false)) {+ if (strpos($command, 'stop') !== false) {+ $result = shell_exec('stop_core_services.sh 2>&1');+ } else if (strpos($command, 'restart') !== false) {+ $result = shell_exec('restart_services.sh 2>&1');+ }+ } ////// PHP FPM //////+ else if (strpos($command, 'php.service') !== false) {+ if (strpos($command, 'restart') !== false) {+ $result = shell_exec("sudo service php7.4-fpm restart");+ }+ }++ return $result;+}++/**+ * Returns a the supplied timestamp as sometime human-readable+ * from https://stackoverflow.com/questions/2690504/php-producing-relative-date-time-from-timestamps+ *+ * @param $ts+ * @return false|string+ */+function relativeTime($ts)+{+ if (!ctype_digit($ts))+ $ts = strtotime($ts);++ $diff = time() - $ts;+ if ($diff == 0)+ return 'now';+ elseif ($diff > 0) {+ $day_diff = floor($diff / 86400);+ if ($day_diff == 0) {+ if ($diff < 60) return 'just now';+ if ($diff < 120) return '1 minute ago';+ if ($diff < 3600) return floor($diff / 60) . ' minutes ago';+ if ($diff < 7200) return '1 hour ago';+ if ($diff < 86400) return floor($diff / 3600) . ' hours ago';+ }+ if ($day_diff == 1) return 'Yesterday';+ if ($day_diff < 7) return $day_diff . ' days ago';+ if ($day_diff < 31) return ceil($day_diff / 7) . ' weeks ago';+ if ($day_diff < 60) return 'last month';+ return date('F Y', $ts);+ } else {+ $diff = abs($diff);+ $day_diff = floor($diff / 86400);+ if ($day_diff == 0) {+ if ($diff < 120) return 'in a minute';+ if ($diff < 3600) return 'in ' . floor($diff / 60) . ' minutes';+ if ($diff < 7200) return 'in an hour';+ if ($diff < 86400) return 'in ' . floor($diff / 3600) . ' hours';+ }+ if ($day_diff == 1) return 'Tomorrow';+ if ($day_diff < 4) return date('l', $ts);+ if ($day_diff < 7 + (7 - date('w'))) return 'next week';+ if (ceil($day_diff / 7) < 4) return 'in ' . ceil($day_diff / 7) . ' weeks';+ if (date('n', $ts) == date('n') + 1) return 'next month';+ return date('F Y', $ts);+ }+}++/**+ * Execute system command as SUDO and logs it's output in the syslog+ *+ * @param $cmd string Command to Execute+ * @param $sudo_user string User to execute as+ * @return string+ */+function syslog_shell_exec($cmd, $sudo_user = null)+{+ if ($sudo_user) {+ $cmd = "sudo -u $sudo_user $cmd";+ }+ $output = shell_exec($cmd);++ if (strlen($output) > 0) {+ syslog(LOG_INFO, $output);+ }++ return $output;+}++/**+ * Loads in configuration settings from either this or firstrun.txt+ *+ * @return void+ */+function parseConfig()+{+ global $config;++ if (file_exists(getFilePath('thisrun.txt'))) {+ $config = parse_ini_file(getFilePath('thisrun.txt'));+ } elseif (file_exists(getFilePath('firstrun.txt'))) {+ $config = parse_ini_file(getFilePath('firstrun.txt'));+ }+}++/**+ * Updates the apprise config file+ *+ * @param $apprise_config+ * @return void+ */+function updateAppriseConfig($apprise_config)+{+ if (isset($apprise_config)) {+ $appriseconfig = fopen(getFilePath("apprise.txt"), "w");+ fwrite($appriseconfig, $apprise_config);+ }+}++/**+ * Returns the apprise config in apprise.txt+ * @return false|string+ */+function getAppriseConfig()+{+ if (file_exists(getFilePath('apprise.txt'))) {+ $apprise_config = file_get_contents(getFilePath('apprise.txt'));+ } else {+ $apprise_config = "";+ }++ return $apprise_config;+}++/**+ * Return the linecount of labels.txt+ * @return int+ */+function getLabelsCount()+{+ return count(file(getFilePath('labels.txt')));+}++/**+ * Returns the current git commit hash of the BirdNET-Pi respository+ * @return false|string|null+ */+function getGitCurrentHash()+{+ global $user;+ return shell_exec("cd " . getDirectory('home') . "/BirdNET-Pi && sudo -u " . $user . " git rev-list --max-count=1 HEAD");+}++/**+ * Runs git fetch against the BirdNET-Pi repository+ * @return false|string|null+ */+function doGitFetch()+{+ global $user;+ return shell_exec("sudo -u" . $user . " git -C " . getDirectory('home') . "/BirdNET-Pi fetch 2>&1");+}++/**+ * Get the git status of the BirdNET-Pi repository+ * @return false|string|null+ */+function getGitStatus()+{+ global $user;+ $behind = 0;+ //Fetch latest updates+ doGitFetch();+ $git_status = trim(shell_exec("sudo -u" . $user . " git -C " . getDirectory('home') . "/BirdNET-Pi status"));++ //Extract the text numberof commits from 'Your branch is behind '....' by XX commits,+ if (preg_match("/behind '.*?' by (\d+) commit(s?)\b/", $git_status, $matches)) {+ $num_commits_behind = $matches[1];+ $behind = $num_commits_behind;+ }++ if (preg_match('/\b(\d+)\b and \b(\d+)\b different commits each/', $git_status, $matches)) {+ $num1 = (int)$matches[1];+ $num2 = (int)$matches[2];+ $sum = $num1 + $num2;+ $behind = $sum;+ }++ return $behind;+}++/**+ * Returns the status of the specified service+ *+ * @param $name string Name of the service+ * @return string[]+ */+function getServiceStatus($name)+{+ $message = '';+ $status = '';++ if ($name == "birdnet_server.service") {+ $filesinproc = trim(shell_exec("ls " . getDirectory('home') . "/BirdSongs/Processed | wc -l"));+ if ($filesinproc > 200) {+ $message = "stalled - backlog of " . $filesinproc . " files in ~/BirdSongs/Processed/";++ }+ }+ $status = shell_exec("sudo systemctl status " . $name . " | grep Active | grep ' active\| activating\|running\|waiting\|start'");+ if (strlen($status) > 0) {+ $message = "(active)";+ } else {+ $message = "(inactive)";+ }++ return ["status" => $status, "message" => $message];+}+/*** Logging helper to accept a message and process it accordingly* @param $message@@ -1040,7 +1673,7 @@ function getFilePath($filename)*/function birdnet_error_log($message, $level = 'error'){- $logfile_path = "./scripts/web-ui-error.log";+ $logfile_path = getDirectory('scripts') . "/web-ui-error.log";if (!file_exists($logfile_path)) {touch($logfile_path);diff --git a/scripts/config.php b/scripts/config.phpindex 0dcdbe5a..c5073862 100644--- a/scripts/config.php+++ b/scripts/config.php@@ -1,16 +1,8 @@<?php-error_reporting(E_ERROR);-ini_set('display_errors',1);--function syslog_shell_exec($cmd, $sudo_user = null) {- if ($sudo_user) {- $cmd = "sudo -u $sudo_user $cmd";- }- $output = shell_exec($cmd);-- if (strlen($output) > 0) {- syslog(LOG_INFO, $output);- }+if(file_exists('./scripts/common.php')){+ include_once "./scripts/common.php";+}else{+ include_once "./common.php";}if(isset($_GET['threshold'])) {@@ -19,19 +11,12 @@ if(isset($_GET['threshold'])) {die('Invalid threshold value');}- $user = trim(shell_exec("awk -F: '/1000/{print $1}' /etc/passwd"));- $home = trim(shell_exec("awk -F: '/1000/{print $6}' /etc/passwd"));-- $command = "sudo -u $user ".$home."/BirdNET-Pi/birdnet/bin/python3 ".$home."/BirdNET-Pi/scripts/species.py --threshold $threshold 2>&1";-- $output = shell_exec($command);-- echo $output;+ echo executeSysCommand('test_threshold', $threshold);die();}if(isset($_GET['restart_php']) && $_GET['restart_php'] == "true") {- shell_exec("sudo service php7.4-fpm restart");+ executeSysCommand('restart_php');die();}@@ -78,7 +63,7 @@ if(isset($_GET["latitude"])){}if(isset($timezone) && in_array($timezone, DateTimeZone::listIdentifiers())) {- shell_exec("sudo timedatectl set-timezone ".$timezone);+ executeSysCommand('set_timezone',$timezone);date_default_timezone_set($timezone);echo "<script>setTimeout(function() {@@ -91,88 +76,84 @@ if(isset($_GET["latitude"])){// logic for setting the date and time based on user inputs from the form belowif(isset($_GET['date']) && isset($_GET['time'])) {// can't set the date manually if it's getting it from the internet, disable ntp- exec("sudo timedatectl set-ntp false");+ executeSysCommand('disable_ntp');// check if valid date and time$datetime = DateTime::createFromFormat('Y-m-d H:i', $_GET['date'] . ' ' . $_GET['time']);if ($datetime && $datetime->format('Y-m-d H:i') === $_GET['date'] . ' ' . $_GET['time']) {- exec("sudo date -s '".$_GET['date']." ".$_GET['time']."'");+ executeSysCommand('set_date', ['date' => $_GET['date'], 'time' => $_GET['time']]);}} else {// user checked 'use time from internet if available,' so make sure that's on- if(strlen(trim(exec("sudo timedatectl | grep \"NTP service: active\""))) == 0){- exec("sudo timedatectl set-ntp true");- sleep(3);+ if(strlen(trim(executeSysCommand('is_ntp_active'))) == 0){+ executeSysCommand('enable_ntp');+ sleep(3);}}// Update Language settings only if a change is requested- if (file_exists('./scripts/thisrun.txt')) {- $lang_config = parse_ini_file('./scripts/thisrun.txt');- } elseif (file_exists('./scripts/firstrun.ini')) {- $lang_config = parse_ini_file('./scripts/firstrun.ini');- }-- if ($model != $lang_config['MODEL'] || $language != $lang_config['DATABASE_LANG']){- if(strlen($language) == 2){- $user = trim(shell_exec("awk -F: '/1000/{print $1}' /etc/passwd"));- $home = trim(shell_exec("awk -F: '/1000/{print $6}' /etc/passwd"));-- // Archive old language file- syslog_shell_exec("cp -f $home/BirdNET-Pi/model/labels.txt $home/BirdNET-Pi/model/labels.txt.old", $user);-- if($model == "BirdNET_GLOBAL_3K_V2.3_Model_FP16"){- // Install new language label file- syslog_shell_exec("sudo chmod +x $home/BirdNET-Pi/scripts/install_language_label_nm.sh && $home/BirdNET-Pi/scripts/install_language_label_nm.sh -l $language", $user);- } else {- syslog_shell_exec("$home/BirdNET-Pi/scripts/install_language_label.sh -l $language", $user);- }-- syslog(LOG_INFO, "Successfully changed language to '$language' and model to '$model'");- }- }--- $contents = file_get_contents("/etc/birdnet/birdnet.conf");- $contents = preg_replace("/SITE_NAME=.*/", "SITE_NAME=\"$site_name\"", $contents);- $contents = preg_replace("/LATITUDE=.*/", "LATITUDE=$latitude", $contents);- $contents = preg_replace("/LONGITUDE=.*/", "LONGITUDE=$longitude", $contents);- $contents = preg_replace("/BIRDWEATHER_ID=.*/", "BIRDWEATHER_ID=$birdweather_id", $contents);- $contents = preg_replace("/APPRISE_NOTIFICATION_TITLE=.*/", "APPRISE_NOTIFICATION_TITLE=\"$apprise_notification_title\"", $contents);- $contents = preg_replace("/APPRISE_NOTIFICATION_BODY=.*/", "APPRISE_NOTIFICATION_BODY='$apprise_notification_body'", $contents);- $contents = preg_replace("/APPRISE_NOTIFY_EACH_DETECTION=.*/", "APPRISE_NOTIFY_EACH_DETECTION=$apprise_notify_each_detection", $contents);- $contents = preg_replace("/APPRISE_NOTIFY_NEW_SPECIES=.*/", "APPRISE_NOTIFY_NEW_SPECIES=$apprise_notify_new_species", $contents);- $contents = preg_replace("/APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY=.*/", "APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY=$apprise_notify_new_species_each_day", $contents);- $contents = preg_replace("/APPRISE_WEEKLY_REPORT=.*/", "APPRISE_WEEKLY_REPORT=$apprise_weekly_report", $contents);- $contents = preg_replace("/FLICKR_API_KEY=.*/", "FLICKR_API_KEY=$flickr_api_key", $contents);- $contents = preg_replace("/DATABASE_LANG=.*/", "DATABASE_LANG=$language", $contents);- $contents = preg_replace("/FLICKR_FILTER_EMAIL=.*/", "FLICKR_FILTER_EMAIL=$flickr_filter_email", $contents);- $contents = preg_replace("/APPRISE_MINIMUM_SECONDS_BETWEEN_NOTIFICATIONS_PER_SPECIES=.*/", "APPRISE_MINIMUM_SECONDS_BETWEEN_NOTIFICATIONS_PER_SPECIES=$minimum_time_limit", $contents);- $contents = preg_replace("/MODEL=.*/", "MODEL=$model", $contents);- $contents = preg_replace("/SF_THRESH=.*/", "SF_THRESH=$sf_thresh", $contents);- $contents = preg_replace("/APPRISE_ONLY_NOTIFY_SPECIES_NAMES=.*/", "APPRISE_ONLY_NOTIFY_SPECIES_NAMES=\"$only_notify_species_names\"", $contents);- $contents = preg_replace("/APPRISE_ONLY_NOTIFY_SPECIES_NAMES_2=.*/", "APPRISE_ONLY_NOTIFY_SPECIES_NAMES_2=\"$only_notify_species_names_2\"", $contents);-- $contents2 = file_get_contents("./scripts/thisrun.txt");- $contents2 = preg_replace("/SITE_NAME=.*/", "SITE_NAME=\"$site_name\"", $contents2);- $contents2 = preg_replace("/LATITUDE=.*/", "LATITUDE=$latitude", $contents2);- $contents2 = preg_replace("/LONGITUDE=.*/", "LONGITUDE=$longitude", $contents2);- $contents2 = preg_replace("/BIRDWEATHER_ID=.*/", "BIRDWEATHER_ID=$birdweather_id", $contents2);- $contents2 = preg_replace("/APPRISE_NOTIFICATION_TITLE=.*/", "APPRISE_NOTIFICATION_TITLE=\"$apprise_notification_title\"", $contents2);- $contents2 = preg_replace("/APPRISE_NOTIFICATION_BODY=.*/", "APPRISE_NOTIFICATION_BODY='$apprise_notification_body'", $contents2);- $contents2 = preg_replace("/APPRISE_NOTIFY_EACH_DETECTION=.*/", "APPRISE_NOTIFY_EACH_DETECTION=$apprise_notify_each_detection", $contents2);- $contents2 = preg_replace("/APPRISE_NOTIFY_NEW_SPECIES=.*/", "APPRISE_NOTIFY_NEW_SPECIES=$apprise_notify_new_species", $contents2);- $contents2 = preg_replace("/APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY=.*/", "APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY=$apprise_notify_new_species_each_day", $contents2);- $contents2 = preg_replace("/APPRISE_WEEKLY_REPORT=.*/", "APPRISE_WEEKLY_REPORT=$apprise_weekly_report", $contents2);- $contents2 = preg_replace("/FLICKR_API_KEY=.*/", "FLICKR_API_KEY=$flickr_api_key", $contents2);- $contents2 = preg_replace("/DATABASE_LANG=.*/", "DATABASE_LANG=$language", $contents2);- $contents2 = preg_replace("/FLICKR_FILTER_EMAIL=.*/", "FLICKR_FILTER_EMAIL=$flickr_filter_email", $contents2);- $contents2 = preg_replace("/APPRISE_MINIMUM_SECONDS_BETWEEN_NOTIFICATIONS_PER_SPECIES=.*/", "APPRISE_MINIMUM_SECONDS_BETWEEN_NOTIFICATIONS_PER_SPECIES=$minimum_time_limit", $contents2);- $contents2 = preg_replace("/MODEL=.*/", "MODEL=$model", $contents2);- $contents2 = preg_replace("/SF_THRESH=.*/", "SF_THRESH=$sf_thresh", $contents2);- $contents2 = preg_replace("/APPRISE_ONLY_NOTIFY_SPECIES_NAMES=.*/", "APPRISE_ONLY_NOTIFY_SPECIES_NAMES=\"$only_notify_species_names\"", $contents2);- $contents2 = preg_replace("/APPRISE_ONLY_NOTIFY_SPECIES_NAMES_2=.*/", "APPRISE_ONLY_NOTIFY_SPECIES_NAMES_2=\"$only_notify_species_names_2\"", $contents2);-+ changeLanguage($model, $language);+++//+// $contents = file_get_contents("/etc/birdnet/birdnet.conf");+// $contents = preg_replace("/SITE_NAME=.*/", "SITE_NAME=\"$site_name\"", $contents);+// $contents = preg_replace("/LATITUDE=.*/", "LATITUDE=$latitude", $contents);+// $contents = preg_replace("/LONGITUDE=.*/", "LONGITUDE=$longitude", $contents);+// $contents = preg_replace("/BIRDWEATHER_ID=.*/", "BIRDWEATHER_ID=$birdweather_id", $contents);+// $contents = preg_replace("/APPRISE_NOTIFICATION_TITLE=.*/", "APPRISE_NOTIFICATION_TITLE=\"$apprise_notification_title\"", $contents);+// $contents = preg_replace("/APPRISE_NOTIFICATION_BODY=.*/", "APPRISE_NOTIFICATION_BODY='$apprise_notification_body'", $contents);+// $contents = preg_replace("/APPRISE_NOTIFY_EACH_DETECTION=.*/", "APPRISE_NOTIFY_EACH_DETECTION=$apprise_notify_each_detection", $contents);+// $contents = preg_replace("/APPRISE_NOTIFY_NEW_SPECIES=.*/", "APPRISE_NOTIFY_NEW_SPECIES=$apprise_notify_new_species", $contents);+// $contents = preg_replace("/APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY=.*/", "APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY=$apprise_notify_new_species_each_day", $contents);+// $contents = preg_replace("/APPRISE_WEEKLY_REPORT=.*/", "APPRISE_WEEKLY_REPORT=$apprise_weekly_report", $contents);+// $contents = preg_replace("/FLICKR_API_KEY=.*/", "FLICKR_API_KEY=$flickr_api_key", $contents);+// $contents = preg_replace("/DATABASE_LANG=.*/", "DATABASE_LANG=$language", $contents);+// $contents = preg_replace("/FLICKR_FILTER_EMAIL=.*/", "FLICKR_FILTER_EMAIL=$flickr_filter_email", $contents);+// $contents = preg_replace("/APPRISE_MINIMUM_SECONDS_BETWEEN_NOTIFICATIONS_PER_SPECIES=.*/", "APPRISE_MINIMUM_SECONDS_BETWEEN_NOTIFICATIONS_PER_SPECIES=$minimum_time_limit", $contents);+// $contents = preg_replace("/MODEL=.*/", "MODEL=$model", $contents);+// $contents = preg_replace("/SF_THRESH=.*/", "SF_THRESH=$sf_thresh", $contents);+// $contents = preg_replace("/APPRISE_ONLY_NOTIFY_SPECIES_NAMES=.*/", "APPRISE_ONLY_NOTIFY_SPECIES_NAMES=\"$only_notify_species_names\"", $contents);+// $contents = preg_replace("/APPRISE_ONLY_NOTIFY_SPECIES_NAMES_2=.*/", "APPRISE_ONLY_NOTIFY_SPECIES_NAMES_2=\"$only_notify_species_names_2\"", $contents);+//+// $contents2 = file_get_contents("./scripts/thisrun.txt");+// $contents2 = preg_replace("/SITE_NAME=.*/", "SITE_NAME=\"$site_name\"", $contents2);+// $contents2 = preg_replace("/LATITUDE=.*/", "LATITUDE=$latitude", $contents2);+// $contents2 = preg_replace("/LONGITUDE=.*/", "LONGITUDE=$longitude", $contents2);+// $contents2 = preg_replace("/BIRDWEATHER_ID=.*/", "BIRDWEATHER_ID=$birdweather_id", $contents2);+// $contents2 = preg_replace("/APPRISE_NOTIFICATION_TITLE=.*/", "APPRISE_NOTIFICATION_TITLE=\"$apprise_notification_title\"", $contents2);+// $contents2 = preg_replace("/APPRISE_NOTIFICATION_BODY=.*/", "APPRISE_NOTIFICATION_BODY='$apprise_notification_body'", $contents2);+// $contents2 = preg_replace("/APPRISE_NOTIFY_EACH_DETECTION=.*/", "APPRISE_NOTIFY_EACH_DETECTION=$apprise_notify_each_detection", $contents2);+// $contents2 = preg_replace("/APPRISE_NOTIFY_NEW_SPECIES=.*/", "APPRISE_NOTIFY_NEW_SPECIES=$apprise_notify_new_species", $contents2);+// $contents2 = preg_replace("/APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY=.*/", "APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY=$apprise_notify_new_species_each_day", $contents2);+// $contents2 = preg_replace("/APPRISE_WEEKLY_REPORT=.*/", "APPRISE_WEEKLY_REPORT=$apprise_weekly_report", $contents2);+// $contents2 = preg_replace("/FLICKR_API_KEY=.*/", "FLICKR_API_KEY=$flickr_api_key", $contents2);+// $contents2 = preg_replace("/DATABASE_LANG=.*/", "DATABASE_LANG=$language", $contents2);+// $contents2 = preg_replace("/FLICKR_FILTER_EMAIL=.*/", "FLICKR_FILTER_EMAIL=$flickr_filter_email", $contents2);+// $contents2 = preg_replace("/APPRISE_MINIMUM_SECONDS_BETWEEN_NOTIFICATIONS_PER_SPECIES=.*/", "APPRISE_MINIMUM_SECONDS_BETWEEN_NOTIFICATIONS_PER_SPECIES=$minimum_time_limit", $contents2);+// $contents2 = preg_replace("/MODEL=.*/", "MODEL=$model", $contents2);+// $contents2 = preg_replace("/SF_THRESH=.*/", "SF_THRESH=$sf_thresh", $contents2);+// $contents2 = preg_replace("/APPRISE_ONLY_NOTIFY_SPECIES_NAMES=.*/", "APPRISE_ONLY_NOTIFY_SPECIES_NAMES=\"$only_notify_species_names\"", $contents2);+// $contents2 = preg_replace("/APPRISE_ONLY_NOTIFY_SPECIES_NAMES_2=.*/", "APPRISE_ONLY_NOTIFY_SPECIES_NAMES_2=\"$only_notify_species_names_2\"", $contents2);++ setSetting('SITE_NAME', "\"$site_name\"");+ setSetting('LATITUDE', $latitude);+ setSetting('LONGITUDE', $longitude);+ setSetting('BIRDWEATHER_ID', $birdweather_id);+ setSetting('APPRISE_NOTIFICATION_TITLE', "\"$apprise_notification_title\"");+ setSetting('APPRISE_NOTIFICATION_BODY', "'$apprise_notification_body'");+ setSetting('APPRISE_NOTIFY_EACH_DETECTION', $apprise_notify_each_detection);+ setSetting('APPRISE_NOTIFY_NEW_SPECIES', $apprise_notify_new_species);+ setSetting('APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY', $apprise_notify_new_species_each_day);+ setSetting('APPRISE_WEEKLY_REPORT', $apprise_weekly_report);+ setSetting('FLICKR_API_KEY', $flickr_api_key);+ setSetting('DATABASE_LANG', $language);+ setSetting('FLICKR_FILTER_EMAIL', $flickr_filter_email);+ setSetting('APPRISE_MINIMUM_SECONDS_BETWEEN_NOTIFICATIONS_PER_SPECIES', $minimum_time_limit);+ setSetting('MODEL', $model);+ setSetting('SF_THRESH', $sf_thresh);+ setSetting('APPRISE_ONLY_NOTIFY_SPECIES_NAMES', "\"$only_notify_species_names\"");+ setSetting('APPRISE_ONLY_NOTIFY_SPECIES_NAMES_2', "\"$only_notify_species_names_2\"");if($site_name != $config["SITE_NAME"]) {@@ -182,43 +163,17 @@ if(isset($_GET["latitude"])){}, 1000);</script>";}- $fh = fopen("/etc/birdnet/birdnet.conf", "w");- $fh2 = fopen("./scripts/thisrun.txt", "w");- fwrite($fh, $contents);- fwrite($fh2, $contents2);-- if(isset($apprise_input)){- $user = shell_exec("awk -F: '/1000/{print $1}' /etc/passwd");- $home = shell_exec("awk -F: '/1000/{print $6}' /etc/passwd");- $home = trim($home);+ updateAppriseConfig($apprise_input);- $appriseconfig = fopen($home."/BirdNET-Pi/apprise.txt", "w");- fwrite($appriseconfig, $apprise_input);- }-- syslog(LOG_INFO, "Restarting Services");- shell_exec("sudo restart_services.sh");+ serviceMaintenance('restart core.services');}if(isset($_GET['sendtest']) && $_GET['sendtest'] == "true") {- $db = new SQLite3('./birds.db', SQLITE3_OPEN_CREATE | SQLITE3_OPEN_READWRITE);-- $user = shell_exec("awk -F: '/1000/{print $1}' /etc/passwd");- $home = shell_exec("awk -F: '/1000/{print $6}' /etc/passwd");- $home = trim($home);-- if (file_exists('./thisrun.txt')) {- $config = parse_ini_file('./thisrun.txt');- } elseif (file_exists('./firstrun.ini')) {- $config = parse_ini_file('./firstrun.ini');- }-$cf = explode("\n",$_GET['apprise_config']);$cf = "'".implode("' '", $cf)."'";- $statement0 = $db->prepare('SELECT * FROM detections WHERE Date == DATE(\'now\', \'localtime\') ORDER BY TIME DESC LIMIT 1');- $result0 = $statement0->execute();- while($todaytable=$result0->fetchArray(SQLITE3_ASSOC))+ $result0 = getMostRecentDetectionToday();+ foreach ($result0['data'] as $todaytable){$sciname = $todaytable['Sci_Name'];$comname = $todaytable['Com_Name'];@@ -280,7 +235,7 @@ if(isset($_GET['sendtest']) && $_GET['sendtest'] == "true") {$body = str_replace("\$overlap", $overlap, $body);$body = str_replace("\$flickrimage", $exampleimage, $body);- echo "<pre class=\"bash\">".shell_exec($home."/BirdNET-Pi/birdnet/bin/apprise -vv --plugin-path ".$home."/.apprise/plugins "." -t '".escapeshellcmd($title)."' -b '".escapeshellcmd($body)."' ".$attach." ".$cf." ")."</pre>";+ echo "<pre class=\"bash\">" . executeSysCommand('appraise_notification', ['title' => $title, 'body' => $body, 'attach' => $attach, 'cf' => $cf]) . "</pre>";die();}@@ -294,19 +249,7 @@ if(isset($_GET['sendtest']) && $_GET['sendtest'] == "true") {<div class="brbanner"><h1>Basic Settings</h1></div><br><form id="basicform" action="" method="GET"><?php-if (file_exists('./scripts/thisrun.txt')) {- $config = parse_ini_file('./scripts/thisrun.txt');-} elseif (file_exists('./scripts/firstrun.ini')) {- $config = parse_ini_file('./scripts/firstrun.ini');-}-$user = shell_exec("awk -F: '/1000/{print $1}' /etc/passwd");-$home = shell_exec("awk -F: '/1000/{print $6}' /etc/passwd");-$home = trim($home);-if (file_exists($home."/BirdNET-Pi/apprise.txt")) {- $apprise_config = file_get_contents($home."/BirdNET-Pi/apprise.txt");-} else {- $apprise_config = "";-}+$apprise_config = getAppriseConfig();$caddypwd = $config['CADDY_PWD'];if (!isset($_SERVER['PHP_AUTH_USER'])) {header('WWW-Authenticate: Basic realm="My Realm"');@@ -323,12 +266,12 @@ if (!isset($_SERVER['PHP_AUTH_USER'])) {exit;}}-?>+?><script>document.addEventListener('DOMContentLoaded', function() {document.getElementById('modelsel').addEventListener('change', function() {- if(this.value == "BirdNET_GLOBAL_3K_V2.3_Model_FP16"){+ if(this.value == "BirdNET_GLOBAL_3K_V2.3_Model_FP16"){document.getElementById("soft").style.display="unset";} else {document.getElementById("soft").style.display="none";@@ -344,13 +287,13 @@ function sendTestNotification(e) {var apprise_config = encodeURIComponent(document.getElementsByName("apprise_input")[0].value);var xmlHttp = new XMLHttpRequest();- xmlHttp.onreadystatechange = function() {+ xmlHttp.onreadystatechange = function() {if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {document.getElementById("testsuccessmsg").innerHTML = this.responseText+" Test sent! Make sure to <b>Update Settings</b> below."e.classList.remove("disabled");}}- xmlHttp.open("GET", "scripts/config.php?sendtest=true&apprise_notification_title="+apprise_notification_title+"&apprise_notification_body="+apprise_notification_body+"&apprise_config="+apprise_config, true); // true for asynchronous+ xmlHttp.open("GET", "scripts/config.php?sendtest=true&apprise_notification_title="+apprise_notification_title+"&apprise_notification_body="+apprise_notification_body+"&apprise_config="+apprise_config, true); // true for asynchronousxmlHttp.send(null);}</script>@@ -360,7 +303,6 @@ function sendTestNotification(e) {<label for="model">Select a Model: </label><select id="modelsel" name="model"><?php- $models = array("BirdNET_6K_GLOBAL_MODEL", "BirdNET_GLOBAL_3K_V2.3_Model_FP16");foreach($models as $modelName){$isSelected = "";if($config['MODEL'] == $modelName){@@ -575,39 +517,6 @@ https://discordapp.com/api/webhooks/{WebhookID}/{WebhookToken}<label for="language">Database Language: </label><select name="language"><?php- $langs = array(- 'not-selected' => 'Not Selected',- "af" => "Afrikaans",- "ca" => "Catalan",- "cs" => "Czech",- "zh" => "Chinese",- "hr" => "Croatian",- "da" => "Danish",- "nl" => "Dutch",- "en" => "English",- "et" => "Estonian",- "fi" => "Finnish",- "fr" => "French",- "de" => "German",- "hu" => "Hungarian",- "is" => "Icelandic",- "id" => "Indonesia",- "it" => "Italian",- "ja" => "Japanese",- "lv" => "Latvian",- "lt" => "Lithuania",- "no" => "Norwegian",- "pl" => "Polish",- "pt" => "Portugues",- "ru" => "Russian",- "sk" => "Slovak",- "sl" => "Slovenian",- "es" => "Spanish",- "sv" => "Swedish",- "th" => "Thai",- "uk" => "Ukrainian"- );-// Create options for each languageforeach($langs as $langTag => $langName){$isSelected = "";@@ -638,7 +547,7 @@ https://discordapp.com/api/webhooks/{WebhookID}/{WebhookToken}</script><?php// if NTP service is active, show the checkboxes as checked, and disable the manual input- $tdc = trim(exec("sudo timedatectl | grep \"NTP service: active\""));+ $tdc = trim(executeSysCommand('is_ntp_active'));if (strlen($tdc) > 0) {$checkedvalue = "checked";$disabledvalue = "disabled";@@ -663,7 +572,7 @@ https://discordapp.com/api/webhooks/{WebhookID}/{WebhookToken}Select a timezone</option><?php- $current_timezone = trim(shell_exec("cat /etc/timezone"));+ $current_timezone = trim(executeSysCommand('current_timezone'));$timezone_identifiers = DateTimeZone::listIdentifiers(DateTimeZone::ALL);$n = 425;diff --git a/scripts/exclude_list.php b/scripts/exclude_list.phpindex d8d90f47..a4f7d7d9 100644--- a/scripts/exclude_list.php+++ b/scripts/exclude_list.php@@ -12,10 +12,7 @@<select name="species[]" id="species" multiple size="auto"><option>Choose a species below to add to the Excluded Species List</option><?php- error_reporting(E_ALL);- ini_set('display_errors',1);-- $filename = './scripts/labels.txt';+ $filename = getFilePath('labels.txt');$eachline = file($filename, FILE_IGNORE_NEW_LINES);foreach($eachline as $lines){echo@@ -43,7 +40,7 @@<br><br><select name="species[]" id="value2" multiple size="auto"><?php- $filename = './scripts/exclude_species_list.txt';+ $filename = getFilePath('exclude_species_list.txt');$eachline = file($filename, FILE_IGNORE_NEW_LINES);foreach($eachline as $lines){echodiff --git a/scripts/include_list.php b/scripts/include_list.phpindex ad663be5..77c6b3f2 100644--- a/scripts/include_list.php+++ b/scripts/include_list.php@@ -3,10 +3,7 @@</style><?php-error_reporting(E_ALL);-ini_set('display_errors',1);--$filename = './scripts/labels.txt';+$filename = getFilePath('labels.txt');$eachlines = file($filename, FILE_IGNORE_NEW_LINES);?>@@ -47,7 +44,7 @@ $eachlines = file($filename, FILE_IGNORE_NEW_LINES);<select name="species[]" id="value2" multiple size="30"><option selected value="base">Please Select</option><?php- $filename = './scripts/include_species_list.txt';+ $filename = getFilePath('include_species_list');$eachlines = file($filename, FILE_IGNORE_NEW_LINES);foreach($eachlines as $lines){echo"<option value=\"".$lines."\">$lines</option>";}diff --git a/scripts/service_controls.php b/scripts/service_controls.phpindex 18885995..ed88538e 100644--- a/scripts/service_controls.php+++ b/scripts/service_controls.php@@ -1,17 +1,19 @@-<?php-function service_status($name) {- $user = shell_exec("awk -F: '/1000/{print $1}' /etc/passwd");- $home = shell_exec("awk -F: '/1000/{print $6}' /etc/passwd");- $home = trim($home);+<?php+if(file_exists('./scripts/common.php')){+ include_once "./scripts/common.php";+}else{+ include_once "./common.php";+}+function service_status($name) {if($name == "birdnet_server.service") {- $filesinproc=trim(shell_exec("ls ".$home."/BirdSongs/Processed | wc -l"));- if($filesinproc > 200) {+ $filesinproc=trim(shell_exec("ls ".getDirectory('home')."/BirdSongs/Processed | wc -l"));+ if($filesinproc > 200) {echo "<span style='color:#fc6603'>(stalled - backlog of ".$filesinproc." files in ~/BirdSongs/Processed/)</span>";return;}- }- $op = shell_exec("sudo systemctl status ".$name." | grep Active | grep ' active\| activating\|running\|waiting\|start'");+ }+ $op = getServiceStatus($name)['status'];if(strlen($op) > 0) {echo "<span style='color:green'>(active)</span>";} else {@@ -25,78 +27,78 @@ function service_status($name) {<div class="servicecontrols"><form action="" method="GET"><h3>Live Audio Stream <?php echo service_status("livestream.service");?></h3>- <button type="submit" name="submit" value="sudo systemctl stop livestream.service && sudo systemctl stop icecast2.service">Stop</button>- <button type="submit" name="submit" value="sudo systemctl restart livestream.service && sudo systemctl restart icecast2.service">Restart </button>- <button type="submit" name="submit" value="sudo systemctl disable --now livestream.service && sudo systemctl disable icecast2 && sudo systemctl stop icecast2.service">Disable</button>- <button type="submit" name="submit" value="sudo systemctl enable icecast2 && sudo systemctl start icecast2.service && sudo systemctl enable --now livestream.service">Enable</button>+ <button type="submit" name="submit" value="service stop livestream.service && service stop icecast2.service">Stop</button>+ <button type="submit" name="submit" value="service restart livestream.service && service restart icecast2.service">Restart </button>+ <button type="submit" name="submit" value="service disable livestream.service && service disable icecast2 && service stop icecast2.service">Disable</button>+ <button type="submit" name="submit" value="service enable icecast2 && service start icecast2.service && service enable livestream.service">Enable</button></form><form action="" method="GET"><h3>Web Terminal <?php echo service_status("web_terminal.service");?></h3>- <button type="submit" name="submit" value="sudo systemctl stop web_terminal.service">Stop</button>- <button type="submit" name="submit" value="sudo systemctl restart web_terminal.service">Restart </button>- <button type="submit" name="submit" value="sudo systemctl disable --now web_terminal.service">Disable</button>- <button type="submit" name="submit" value="sudo systemctl enable --now web_terminal.service">Enable</button>+ <button type="submit" name="submit" value="service stop web_terminal.service">Stop</button>+ <button type="submit" name="submit" value="service restart web_terminal.service">Restart </button>+ <button type="submit" name="submit" value="service disable web_terminal.service">Disable</button>+ <button type="submit" name="submit" value="service enable web_terminal.service">Enable</button></form><form action="" method="GET"><h3>BirdNET Log <?php echo service_status("birdnet_log.service");?></h3>- <button type="submit" name="submit" value="sudo systemctl stop birdnet_log.service">Stop</button>- <button type="submit" name="submit" value="sudo systemctl restart birdnet_log.service">Restart </button>- <button type="submit" name="submit" value="sudo systemctl disable --now birdnet_log.service">Disable</button>- <button type="submit" name="submit" value="sudo systemctl enable --now birdnet_log.service">Enable</button>+ <button type="submit" name="submit" value="service stop birdnet_log.service">Stop</button>+ <button type="submit" name="submit" value="service restart birdnet_log.service">Restart </button>+ <button type="submit" name="submit" value="service disable birdnet_log.service">Disable</button>+ <button type="submit" name="submit" value="service enable birdnet_log.service">Enable</button></form><form action="" method="GET"><h3>Extraction Service <?php echo service_status("extraction.service");?></h3>- <button type="submit" name="submit" value="sudo systemctl stop extraction.service">Stop</button>- <button type="submit" name="submit" value="sudo systemctl restart extraction.service">Restart </button>- <button type="submit" name="submit" value="sudo systemctl disable --now extraction.service">Disable</button>- <button type="submit" name="submit" value="sudo systemctl enable --now extraction.service">Enable</button>+ <button type="submit" name="submit" value="service stop extraction.service">Stop</button>+ <button type="submit" name="submit" value="service restart extraction.service">Restart </button>+ <button type="submit" name="submit" value="service disable extraction.service">Disable</button>+ <button type="submit" name="submit" value="service enable extraction.service">Enable</button></form><form action="" method="GET"><h3>BirdNET Analysis Server <?php echo service_status("birdnet_server.service");?></h3>- <button type="submit" name="submit" value="sudo systemctl stop birdnet_server.service">Stop</button>- <button type="submit" name="submit" value="sudo systemctl restart birdnet_server.service">Restart</button>- <button type="submit" name="submit" value="sudo systemctl disable --now birdnet_server.service">Disable</button>- <button type="submit" name="submit" value="sudo systemctl enable --now birdnet_server.service">Enable</button>+ <button type="submit" name="submit" value="service stop birdnet_server.service">Stop</button>+ <button type="submit" name="submit" value="service restart birdnet_server.service">Restart</button>+ <button type="submit" name="submit" value="service disable birdnet_server.service">Disable</button>+ <button type="submit" name="submit" value="service enable birdnet_server.service">Enable</button></form><form action="" method="GET"><h3>BirdNET Analysis Client <?php echo service_status("birdnet_analysis.service");?></h3>- <button type="submit" name="submit" value="sudo systemctl stop birdnet_analysis.service">Stop</button>- <button type="submit" name="submit" value="sudo systemctl restart birdnet_analysis.service">Restart</button>- <button type="submit" name="submit" value="sudo systemctl disable --now birdnet_analysis.service">Disable</button>- <button type="submit" name="submit" value="sudo systemctl enable --now birdnet_analysis.service">Enable</button>+ <button type="submit" name="submit" value="service stop birdnet_analysis.service">Stop</button>+ <button type="submit" name="submit" value="service restart birdnet_analysis.service">Restart</button>+ <button type="submit" name="submit" value="service disable birdnet_analysis.service">Disable</button>+ <button type="submit" name="submit" value="service enable birdnet_analysis.service">Enable</button></form><form action="" method="GET"><h3>Streamlit Statistics <?php echo service_status("birdnet_stats.service");?></h3>- <button type="submit" name="submit" value="sudo systemctl stop birdnet_stats.service">Stop</button>- <button type="submit" name="submit" value="sudo systemctl restart birdnet_stats.service">Restart</button>- <button type="submit" name="submit" value="sudo systemctl disable --now birdnet_stats.service">Disable</button>- <button type="submit" name="submit" value="sudo systemctl enable --now birdnet_stats.service">Enable</button>+ <button type="submit" name="submit" value="service stop birdnet_stats.service">Stop</button>+ <button type="submit" name="submit" value="service restart birdnet_stats.service">Restart</button>+ <button type="submit" name="submit" value="service disable birdnet_stats.service">Disable</button>+ <button type="submit" name="submit" value="service enable birdnet_stats.service">Enable</button></form><form action="" method="GET"><h3>Recording Service <?php echo service_status("birdnet_recording.service");?></h3>- <button type="submit" name="submit" value="sudo systemctl stop birdnet_recording.service">Stop</button>- <button type="submit" name="submit" value="sudo systemctl restart birdnet_recording.service">Restart</button>- <button type="submit" name="submit" value="sudo systemctl disable --now birdnet_recording.service">Disable</button>- <button type="submit" name="submit" value="sudo systemctl enable --now birdnet_recording.service">Enable</button>+ <button type="submit" name="submit" value="service stop birdnet_recording.service">Stop</button>+ <button type="submit" name="submit" value="service restart birdnet_recording.service">Restart</button>+ <button type="submit" name="submit" value="service disable birdnet_recording.service">Disable</button>+ <button type="submit" name="submit" value="service enable birdnet_recording.service">Enable</button></form><form action="" method="GET"><h3>Chart Viewer <?php echo service_status("chart_viewer.service");?></h3>- <button type="submit" name="submit" value="sudo systemctl stop chart_viewer.service">Stop</button>- <button type="submit" name="submit" value="sudo systemctl restart chart_viewer.service">Restart</button>- <button type="submit" name="submit" value="sudo systemctl disable --now chart_viewer.service">Disable</button>- <button type="submit" name="submit" value="sudo systemctl enable --now chart_viewer.service">Enable</button>+ <button type="submit" name="submit" value="service stop chart_viewer.service">Stop</button>+ <button type="submit" name="submit" value="service restart chart_viewer.service">Restart</button>+ <button type="submit" name="submit" value="service disable chart_viewer.service">Disable</button>+ <button type="submit" name="submit" value="service enable chart_viewer.service">Enable</button></form><form action="" method="GET"><h3>Spectrogram Viewer <?php echo service_status("spectrogram_viewer.service");?></h3>- <button type="submit" name="submit" value="sudo systemctl stop spectrogram_viewer.service">Stop</button>- <button type="submit" name="submit" value="sudo systemctl restart spectrogram_viewer.service">Restart</button>- <button type="submit" name="submit" value="sudo systemctl disable --now spectrogram_viewer.service">Disable</button>- <button type="submit" name="submit" value="sudo systemctl enable --now spectrogram_viewer.service">Enable</button>+ <button type="submit" name="submit" value="service stop spectrogram_viewer.service">Stop</button>+ <button type="submit" name="submit" value="service restart spectrogram_viewer.service">Restart</button>+ <button type="submit" name="submit" value="service disable spectrogram_viewer.service">Disable</button>+ <button type="submit" name="submit" value="service enable spectrogram_viewer.service">Enable</button></form><form action="" method="GET">- <button type="submit" name="submit" value="stop_core_services.sh">Stop Core Services</button>+ <button type="submit" name="submit" value="system stop core.services">Stop Core Services</button></form><form action="" method="GET">- <button type="submit" name="submit" value="restart_services.sh">Restart Core Services</button>+ <button type="submit" name="submit" value="system restart core.services">Restart Core Services</button></form></div>diff --git a/scripts/system_controls.php b/scripts/system_controls.phpindex 067b3148..c9935651 100644--- a/scripts/system_controls.php+++ b/scripts/system_controls.php@@ -1,21 +1,11 @@<?php-session_start();-$user = shell_exec("awk -F: '/1000/{print $1}' /etc/passwd");-$user = trim($user);-$home = shell_exec("awk -F: '/1000/{print $6}' /etc/passwd");-$home = trim($home);-$fetch = shell_exec("sudo -u".$user." git -C ".$home."/BirdNET-Pi fetch 2>&1");-$str = trim(shell_exec("sudo -u".$user." git -C ".$home."/BirdNET-Pi status"));-if (preg_match("/behind '.*?' by (\d+) commit(s?)\b/", $str, $matches)) {- $num_commits_behind = $matches[1];- $_SESSION['behind'] = $num_commits_behind;-}-if (preg_match('/\b(\d+)\b and \b(\d+)\b different commits each/', $str, $matches)) {- $num1 = (int) $matches[1];- $num2 = (int) $matches[2];- $sum = $num1 + $num2;- $_SESSION['behind'] = $sum;+if(file_exists('./scripts/common.php')){+ include_once "./scripts/common.php";+}else{+ include_once "./common.php";}++$_SESSION['behind'] = getGitStatus();?><html><meta name="viewport" content="width=device-width, initial-scale=1"><br>@@ -45,8 +35,7 @@ function update() {<button type="submit" name="submit" value="sudo clear_all_data.sh" onclick="return confirm('Clear ALL Data? Note that this cannot be undone and will take up to 90 seconds.')">Clear ALL data</button></form><?php- $cmd="cd ".$home."/BirdNET-Pi && sudo -u ".$user." git rev-list --max-count=1 HEAD";- $curr_hash = shell_exec($cmd);+ $curr_hash = getGitCurrentHash()?><p style="font-size:11px;text-align:center"></br></br>Running version: </p><a href="https://github.com/mcguirepr89/BirdNET-Pi/commit/<?php echo $curr_hash; ?>" target="_blank">diff --git a/scripts/todays_detections.php b/scripts/todays_detections.phpindex 5068f129..96c6d2f6 100644--- a/scripts/todays_detections.php+++ b/scripts/todays_detections.php@@ -64,52 +64,6 @@ die();}-// from https://stackoverflow.com/questions/2690504/php-producing-relative-date-time-from-timestamps-function relativeTime($ts)-{- if(!ctype_digit($ts))- $ts = strtotime($ts);-- $diff = time() - $ts;- if($diff == 0)- return 'now';- elseif($diff > 0)- {- $day_diff = floor($diff / 86400);- if($day_diff == 0)- {- if($diff < 60) return 'just now';- if($diff < 120) return '1 minute ago';- if($diff < 3600) return floor($diff / 60) . ' minutes ago';- if($diff < 7200) return '1 hour ago';- if($diff < 86400) return floor($diff / 3600) . ' hours ago';- }- if($day_diff == 1) return 'Yesterday';- if($day_diff < 7) return $day_diff . ' days ago';- if($day_diff < 31) return ceil($day_diff / 7) . ' weeks ago';- if($day_diff < 60) return 'last month';- return date('F Y', $ts);- }- else- {- $diff = abs($diff);- $day_diff = floor($diff / 86400);- if($day_diff == 0)- {- if($diff < 120) return 'in a minute';- if($diff < 3600) return 'in ' . floor($diff / 60) . ' minutes';- if($diff < 7200) return 'in an hour';- if($diff < 86400) return 'in ' . floor($diff / 3600) . ' hours';- }- if($day_diff == 1) return 'Tomorrow';- if($day_diff < 4) return date('l', $ts);- if($day_diff < 7 + (7 - date('w'))) return 'next week';- if(ceil($day_diff / 7) < 4) return 'in ' . ceil($day_diff / 7) . ' weeks';- if(date('n', $ts) == date('n') + 1) return 'next month';- return date('F Y', $ts);- }-}-if(isset($_GET['ajax_detections']) && $_GET['ajax_detections'] == "true" ) {$result0 = getTodaysDetections($_GET['display_limit'], $_GET['searchterm'], $_GET['hard_limit']);