Skip to content

A live bird collage card for your Home Assistant dashboard.

Revert "Code Consolidation for API preparations & hard coded path replacements"

ehpersonal389c1f4175e2a0
diff --git a/config/filepath_map.json b/config/filepath_map.json
deleted file mode 100644
index 15c00621..00000000
--- a/config/filepath_map.json
+++ /dev/null
@@ -1,280 +0,0 @@
-{
- "directories": {
- "home": {
- "description": "The home path for the user with User ID of 1000, this is normally the 'pi' user",
- "read_setting": null,
- "return_var": "home"
- },
- "birdnet-pi": {
- "alias_for": "birdnet_pi"
- },
- "birdnet_pi": {
- "description": "The root directory of the BirdNET-pi install",
- "lives_under": "home",
- "read_setting": "",
- "replace_setting_text": "",
- "replace_setting_text_with": "",
- "append": "\/BirdNET-Pi",
- "return_var": ""
- },
- "recs_dir": {
- "alias_for": "recordings_dir"
- },
- "recordings_dir": {
- "description": "The recording directory as specified in the config file (default: BirdSongs)",
- "lives_under": "home",
- "read_setting": "RECS_DIR",
- "replace_setting_text": "$HOME",
- "replace_setting_text_with": "",
- "append": ""
- },
- "processed": {
- "description": "The directory which holds the recordings that have been processed",
- "lives_under": "recordings_dir",
- "read_setting": "PROCESSED",
- "replace_setting_text": "${RECS_DIR}",
- "replace_setting_text_with": "",
- "append": ""
- },
- "extracted": {
- "description": "The directory which holds the extraction related data from detections",
- "lives_under": "recordings_dir",
- "read_setting": "EXTRACTED",
- "replace_setting_text": "${RECS_DIR}",
- "replace_setting_text_with": "",
- "append": ""
- },
- "extracted_bydate": {
- "alias_for": "extracted_by_date"
- },
- "extracted_by_date": {
- "description": "The directory which holds the the extractions from detections as folders by date",
- "lives_under": "extracted",
- "read_setting": "",
- "replace_setting_text": "",
- "replace_setting_text_with": "",
- "append": "\/By_Date"
- },
- "extracted_charts": {
- "description": "The directory which holds the spectrogram charts for detections",
- "lives_under": "extracted",
- "read_setting": "",
- "replace_setting_text": "",
- "replace_setting_text_with": "",
- "append": "\/Charts"
- },
- "shifted_dir": {
- "alias_for": "shifted_audio"
- },
- "shifted_audio": {
- "description": "The directory which stores any frequency shifted audio",
- "lives_under": "extracted_by_date",
- "read_setting": "",
- "replace_setting_text": "",
- "replace_setting_text_with": "",
- "append": "\/shifted"
- },
- "database": {
- "description": "**NOT CURRENTLY USED** The directory which holds files related to the detections database",
- "lives_under": "birdnet_pi",
- "read_setting": "",
- "replace_setting_text": "",
- "replace_setting_text_with": "",
- "append": "\/database"
- },
- "config": {
- "description": "The directory which holds configuration files for BirdNET-pi",
- "lives_under": "birdnet_pi",
- "read_setting": "",
- "replace_setting_text": "",
- "replace_setting_text_with": "",
- "append": "\/config"
- },
- "models": {
- "alias_for": "model"
- },
- "model": {
- "description": "The directory which holds AI detection models",
- "lives_under": "birdnet_pi",
- "read_setting": "",
- "replace_setting_text": "",
- "replace_setting_text_with": "",
- "append": "\/model"
- },
- "python3_ve": {
- "description": "The directory which contains the Python 3 Virtual Environment",
- "lives_under": "birdnet_pi",
- "read_setting": "",
- "replace_setting_text": "",
- "replace_setting_text_with": "",
- "append": "\/birdnet\/bin"
- },
- "scripts": {
- "description": "The directory which contains the script files like PHP and Shell scripts",
- "lives_under": "birdnet_pi",
- "read_setting": "",
- "replace_setting_text": "",
- "replace_setting_text_with": "",
- "append": "\/scripts"
- },
- "stream_data": {
- "description": "The directory which contains the recordings from RTSP streams",
- "lives_under": "recordings_dir",
- "read_setting": "",
- "replace_setting_text": "",
- "replace_setting_text_with": "",
- "append": "\/StreamData"
- },
- "templates": {
- "description": "The directory which contains the templates, like html, CRON script templates",
- "lives_under": "birdnet_pi",
- "read_setting": "",
- "replace_setting_text": "",
- "replace_setting_text_with": "",
- "append": "\/templates"
- },
- "www": {
- "alias_for": "web"
- },
- "web": {
- "description": "The directory which any files related to generating the Web UI, index.php, views.php, stylesheets etc",
- "lives_under": "birdnet_pi",
- "read_setting": "",
- "replace_setting_text": "",
- "replace_setting_text_with": "",
- "append": "\/homepage"
- },
- "www_fonts": {
- "alias_for": "web_fonts"
- },
- "web_fonts": {
- "description": "The directory which any fonts used by the WebUI or Python scripts",
- "lives_under": "www",
- "read_setting": "",
- "replace_setting_text": "",
- "replace_setting_text_with": "",
- "append": "\/static"
- }
- },
- "files": {
- "analyzing_now.txt": {
- "lives_under": "birdnet_pi",
- "append": "\/analyzing_now.txt"
- },
- "apprise.txt": {
- "lives_under": "birdnet_pi",
- "append": "\/apprise.txt"
- },
- "birdnet.conf": {
- "lives_under": "birdnet_pi",
- "append": "\/birdnet.conf"
- },
- "etc_birdnet.conf": {
- "lives_under": "",
- "append": "",
- "return_var": "\/etc\/birdnet\/birdnet.conf"
- },
- "BirdDB.txt": {
- "lives_under": "birdnet_pi",
- "append": "\/BirdDB.txt"
- },
- "birds.db": {
- "lives_under": "scripts",
- "append": "\/birds.db"
- },
- "blacklisted_images.txt": {
- "lives_under": "scripts",
- "append": "\/blacklisted_images.txt"
- },
- "disk_check_exclude.txt": {
- "lives_under": "scripts",
- "append": "\/disk_check_exclude.txt"
- },
- "email_template": {
- "lives_under": "scripts",
- "append": "\/email_template"
- },
- "email_template2": {
- "lives_under": "scripts",
- "append": "\/email_template2"
- },
- "exclude_species_list.txt": {
- "lives_under": "scripts",
- "append": "\/exclude_species_list.txt"
- },
- "filepath_map.json": {
- "lives_under": "config",
- "append": "\/filepath_map.json"
- },
- "firstrun.ini": {
- "lives_under": "birdnet_pi",
- "append": "\/firstrun.ini"
- },
- ".gotty": {
- "lives_under": "home",
- "append": "\/.gotty"
- },
- "HUMAN.txt": {
- "lives_under": "birdnet_pi",
- "append": "\/HUMAN.txt"
- },
- "IDFILE": {
- "alias_for": "IdentifiedSoFar.txt"
- },
- "IdentifiedSoFar.txt": {
- "lives_under": "home",
- "read_setting": "IDFILE",
- "replace_setting_text": "$HOME",
- "replace_setting_text_with": "",
- "append": ""
- },
- "include_species_list.txt": {
- "lives_under": "scripts",
- "append": "\/include_species_list.txt"
- },
- "labels.txt": {
- "lives_under": "model",
- "append": "\/labels.txt"
- },
- "labels.txt.old": {
- "lives_under": "model",
- "append": "\/labels.txt.old"
- },
- "labels_flickr.txt": {
- "lives_under": "model",
- "append": "\/labels_flickr.txt"
- },
- "labels_lang.txt": {
- "lives_under": "model",
- "append": "\/labels_lang.txt"
- },
- "labels_l18n.zip": {
- "lives_under": "model",
- "append": "\/labels_l18n.zip"
- },
- "labels_nm.zip": {
- "lives_under": "model",
- "append": "\/labels_nm.zip"
- },
- "lastrun.txt": {
- "lives_under": "scripts",
- "append": "\/lastrun.txt"
- },
- "python3": {
- "lives_under": "python3_ve",
- "append": "\/python3 "
- },
- "python3_appraise": {
- "lives_under": "python3_ve",
- "append": "\/apprise "
- },
- "species.py": {
- "lives_under": "scripts",
- "append": "\/species.py"
- },
- "thisrun.txt": {
- "lives_under": "scripts",
- "append": "\/thisrun.txt"
- }
- }
-}
\ No newline at end of file
diff --git a/config/generate_filepath_map_file.php b/config/generate_filepath_map_file.php
deleted file mode 100644
index 06cfbdb7..00000000
--- a/config/generate_filepath_map_file.php
+++ /dev/null
@@ -1,327 +0,0 @@
-<?php
-/**
- * Script to allow easy manipulation and generation of ../config/filepath_map.json
- * Execute this script with php -a ./generate_filepath_map_file.php
- */
-
-############################
-# FILE PATH DECLARATIONS
-############################
-$file_path_map_array['directories']['home'] = array(
- 'description' => "The home path for the user with User ID of 1000, this is normally the 'pi' user",
- 'read_setting' => null,
- 'return_var' => 'home'
-);
-
-
-$file_path_map_array['directories']['birdnet-pi'] = array('alias_for' => 'birdnet_pi');
-$file_path_map_array['directories']['birdnet_pi'] = array(
- 'description' => "The root directory of the BirdNET-pi install",
- 'lives_under' => 'home',
- 'read_setting' => '',
- 'replace_setting_text' => '',
- 'replace_setting_text_with' => '',
- 'append' => '/BirdNET-Pi',
- 'return_var' => ''
-);
-
-
-$file_path_map_array['directories']['recs_dir'] = array('alias_for' => 'recordings_dir');
-$file_path_map_array['directories']['recordings_dir'] = array(
- 'description' => "The recording directory as specified in the config file (default: BirdSongs)",
- 'lives_under' => 'home',
- 'read_setting' => 'RECS_DIR',
- 'replace_setting_text' => '$HOME',
- 'replace_setting_text_with' => '',
- 'append' => '',
-);
-
-
-$file_path_map_array['directories']['processed'] = array(
- 'description' => "The directory which holds the recordings that have been processed",
- 'lives_under' => 'recordings_dir',
- 'read_setting' => 'PROCESSED',
- 'replace_setting_text' => '${RECS_DIR}',
- 'replace_setting_text_with' => '',
- 'append' => '',
-);
-
-
-$file_path_map_array['directories']['extracted'] = array(
- 'description' => "The directory which holds the extraction related data from detections",
- 'lives_under' => 'recordings_dir',
- 'read_setting' => 'EXTRACTED',
- 'replace_setting_text' => '${RECS_DIR}',
- 'replace_setting_text_with' => '',
- 'append' => '',
-);
-
-
-$file_path_map_array['directories']['extracted_bydate'] = array('alias_for' => 'extracted_by_date');
-$file_path_map_array['directories']['extracted_by_date'] = array(
- 'description' => "The directory which holds the the extractions from detections as folders by date",
- 'lives_under' => 'extracted',
- 'read_setting' => '',
- 'replace_setting_text' => '',
- 'replace_setting_text_with' => '',
- 'append' => '/By_Date',
-);
-
-
-$file_path_map_array['directories']['extracted_charts'] = array(
- 'description' => "The directory which holds the spectrogram charts for detections",
- 'lives_under' => 'extracted',
- 'read_setting' => '',
- 'replace_setting_text' => '',
- 'replace_setting_text_with' => '',
- 'append' => '/Charts',
-);
-
-$file_path_map_array['directories']['shifted_dir'] = array('alias_for' => 'shifted_audio');
-$file_path_map_array['directories']['shifted_audio'] = array(
- 'description' => "The directory which stores any frequency shifted audio",
- 'lives_under' => 'extracted_by_date',
- 'read_setting' => '',
- 'replace_setting_text' => '',
- 'replace_setting_text_with' => '',
- 'append' => '/shifted',
-);
-
-
-$file_path_map_array['directories']['database'] = array(
- 'description' => "**NOT CURRENTLY USED** The directory which holds files related to the detections database",
- 'lives_under' => 'birdnet_pi',
- 'read_setting' => '',
- 'replace_setting_text' => '',
- 'replace_setting_text_with' => '',
- 'append' => '/database',
-);
-
-$file_path_map_array['directories']['config'] = array(
- 'description' => "The directory which holds configuration files for BirdNET-pi",
- 'lives_under' => 'birdnet_pi',
- 'read_setting' => '',
- 'replace_setting_text' => '',
- 'replace_setting_text_with' => '',
- 'append' => '/config',
-);
-
-$file_path_map_array['directories']['models'] = array('alias_for' => 'model');
-$file_path_map_array['directories']['model'] = array(
- 'description' => "The directory which holds AI detection models",
- 'lives_under' => 'birdnet_pi',
- 'read_setting' => '',
- 'replace_setting_text' => '',
- 'replace_setting_text_with' => '',
- 'append' => '/model',
-);
-
-$file_path_map_array['directories']['python3_ve'] = array(
- 'description' => "The directory which contains the Python 3 Virtual Environment",
- 'lives_under' => 'birdnet_pi',
- 'read_setting' => '',
- 'replace_setting_text' => '',
- 'replace_setting_text_with' => '',
- 'append' => '/birdnet/bin',
-);
-
-$file_path_map_array['directories']['scripts'] = array(
- 'description' => "The directory which contains the script files like PHP and Shell scripts",
- 'lives_under' => 'birdnet_pi',
- 'read_setting' => '',
- 'replace_setting_text' => '',
- 'replace_setting_text_with' => '',
- 'append' => '/scripts',
-);
-
-$file_path_map_array['directories']['stream_data'] = array(
- 'description' => "The directory which contains the recordings from RTSP streams",
- 'lives_under' => 'recordings_dir',
- 'read_setting' => '',
- 'replace_setting_text' => '',
- 'replace_setting_text_with' => '',
- 'append' => '/StreamData',
-);
-
-$file_path_map_array['directories']['templates'] = array(
- 'description' => "The directory which contains the templates, like html, CRON script templates",
- 'lives_under' => 'birdnet_pi',
- 'read_setting' => '',
- 'replace_setting_text' => '',
- 'replace_setting_text_with' => '',
- 'append' => '/templates',
-);
-
-$file_path_map_array['directories']['www'] = array('alias_for' => 'web');
-$file_path_map_array['directories']['web'] = array(
- 'description' => "The directory which any files related to generating the Web UI, index.php, views.php, stylesheets etc",
- 'lives_under' => 'birdnet_pi',
- 'read_setting' => '',
- 'replace_setting_text' => '',
- 'replace_setting_text_with' => '',
- 'append' => '/homepage',
-);
-
-$file_path_map_array['directories']['www_fonts'] = array('alias_for' => 'web_fonts');
-$file_path_map_array['directories']['web_fonts'] = array(
- 'description' => "The directory which any fonts used by the WebUI or Python scripts",
- 'lives_under' => 'www',
- 'read_setting' => '',
- 'replace_setting_text' => '',
- 'replace_setting_text_with' => '',
- 'append' => '/static',
-);
-
-
-############################
-# FILE PATH DECLARATIONS
-############################
-$file_path_map_array['files']['analyzing_now.txt'] = array(
- 'lives_under' => 'birdnet_pi',
- 'append' => '/analyzing_now.txt'
-);
-
-$file_path_map_array['files']['apprise.txt'] = array(
- 'lives_under' => 'birdnet_pi',
- 'append' => '/apprise.txt'
-);
-
-$file_path_map_array['files']['birdnet.conf'] = array(
- 'lives_under' => 'birdnet_pi',
- 'append' => '/birdnet.conf'
-);
-
-$file_path_map_array['files']['etc_birdnet.conf'] = array(
- 'lives_under' => '',
- 'append' => '',
- 'return_var' => '/etc/birdnet/birdnet.conf'
-);
-
-$file_path_map_array['files']['BirdDB.txt'] = array(
- 'lives_under' => 'birdnet_pi',
- 'append' => '/BirdDB.txt',
-);
-
-$file_path_map_array['files']['birds.db'] = array(
- 'lives_under' => 'scripts',
- 'append' => '/birds.db',
-);
-
-$file_path_map_array['files']['blacklisted_images.txt'] = array(
- 'lives_under' => 'scripts',
- 'append' => '/blacklisted_images.txt',
-);
-
-$file_path_map_array['files']['disk_check_exclude.txt'] = array(
- 'lives_under' => 'scripts',
- 'append' => '/disk_check_exclude.txt',
-);
-
-$file_path_map_array['files']['email_template'] = array(
- 'lives_under' => 'scripts',
- 'append' => '/email_template',
-);
-
-$file_path_map_array['files']['email_template2'] = array(
- 'lives_under' => 'scripts',
- 'append' => '/email_template2',
-);
-
-$file_path_map_array['files']['exclude_species_list.txt'] = array(
- 'lives_under' => 'scripts',
- 'append' => '/exclude_species_list.txt',
-);
-
-$file_path_map_array['files']['filepath_map.json'] = array(
- 'lives_under' => 'config',
- 'append' => '/filepath_map.json',
-);
-
-$file_path_map_array['files']['firstrun.ini'] = array(
- 'lives_under' => 'birdnet_pi',
- 'append' => '/firstrun.ini',
-);
-
-$file_path_map_array['files']['.gotty'] = array(
- 'lives_under' => 'home',
- 'append' => '/.gotty',
-);
-
-$file_path_map_array['files']['HUMAN.txt'] = array(
- 'lives_under' => 'birdnet_pi',
- 'append' => '/HUMAN.txt',
-);
-
-$file_path_map_array['files']['IDFILE'] = array('alias_for' => 'IdentifiedSoFar.txt');
-$file_path_map_array['files']['IdentifiedSoFar.txt'] = array(
- 'lives_under' => 'home',
- 'read_setting' => 'IDFILE',
- 'replace_setting_text' => '$HOME',
- 'replace_setting_text_with' => '',
- 'append' => '',
-);
-
-$file_path_map_array['files']['include_species_list.txt'] = array(
- 'lives_under' => 'scripts',
- 'append' => '/include_species_list.txt',
-);
-
-$file_path_map_array['files']['labels.txt'] = array(
- 'lives_under' => 'model',
- 'append' => '/labels.txt',
-);
-
-$file_path_map_array['files']['labels.txt.old'] = array(
- 'lives_under' => 'model',
- 'append' => '/labels.txt.old',
-);
-
-$file_path_map_array['files']['labels_flickr.txt'] = array(
- 'lives_under' => 'model',
- 'append' => '/labels_flickr.txt',
-);
-
-$file_path_map_array['files']['labels_lang.txt'] = array(
- 'lives_under' => 'model',
- 'append' => '/labels_lang.txt',
-);
-
-$file_path_map_array['files']['labels_l18n.zip'] = array(
- 'lives_under' => 'model',
- 'append' => '/labels_l18n.zip',
-);
-
-$file_path_map_array['files']['labels_nm.zip'] = array(
- 'lives_under' => 'model',
- 'append' => '/labels_nm.zip',
-);
-
-
-$file_path_map_array['files']['lastrun.txt'] = array(
- 'lives_under' => 'scripts',
- 'append' => '/lastrun.txt',
-);
-
-
-$file_path_map_array['files']['python3'] = array(
- 'lives_under' => 'python3_ve',
- 'append' => '/python3 ',
-);
-
-$file_path_map_array['files']['python3_appraise'] = array(
- 'lives_under' => 'python3_ve',
- 'append' => '/apprise ',
-);
-
-$file_path_map_array['files']['species.py'] = array(
- 'lives_under' => 'scripts',
- 'append' => '/species.py',
-);
-
-$file_path_map_array['files']['thisrun.txt'] = array(
- 'lives_under' => 'scripts',
- 'append' => '/thisrun.txt',
-);
-
-//Output array as JSON and pretty print it
-file_put_contents('./filepath_map.json', json_encode($file_path_map_array, JSON_PRETTY_PRINT));
\ No newline at end of file
diff --git a/homepage/index.php b/homepage/index.php
index e4e51b18..eeae4231 100644
--- a/homepage/index.php
+++ b/homepage/index.php
@@ -1,10 +1,34 @@
<?php
-if(file_exists('./scripts/common.php')){
- include_once "./scripts/common.php";
-}else{
- include_once "./common.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/thisrun.txt')) {
+ $config = parse_ini_file('./scripts/thisrun.txt');
+ } elseif (file_exists('./scripts/firstrun.ini')) {
+ $config = parse_ini_file('./scripts/firstrun.ini');
+ }
+ if($config["SITE_NAME"] == "") {
+ $site_name = "BirdNET-Pi";
+ } else {
+ $site_name = $config['SITE_NAME'];
+ }
?>
<title><?php echo $site_name; ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
@@ -29,14 +53,33 @@ echo "<a href=\"https://github.com/mcguirepr89/BirdNET-Pi.git\" target=\"_blank\
<div class="stream">
<?php
if(isset($_GET['stream'])){
- $user_is_authenticated = authenticateUser('You cannot listen to the live audio stream');
- if ($user_is_authenticated) {
- echo "
+ 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');
+ }
+ $caddypwd = $config['CADDY_PWD'];
+ if (!isset($_SERVER['PHP_AUTH_USER'])) {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo 'You cannot listen to the live audio stream';
+ exit;
+ } else {
+ $submittedpwd = $_SERVER['PHP_AUTH_PW'];
+ $submitteduser = $_SERVER['PHP_AUTH_USER'];
+ if($submittedpwd == $caddypwd && $submitteduser == 'birdnet'){
+ echo "
<audio controls autoplay><source src=\"/stream\"></audio>
</div>
<h1><a href=\"/\"><img class=\"topimage\" src=\"images/bnp.png\"></a></h1>
</div><div class=\"centered\"><h3>$site_name</h3></div>";
- }
+ } else {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo 'You cannot listen to the live audio stream';
+ exit;
+ }
+ }
} else {
echo "
<form action=\"\" method=\"GET\">
diff --git a/homepage/views.php b/homepage/views.php
index 235676f8..e7537002 100644
--- a/homepage/views.php
+++ b/homepage/views.php
@@ -1,14 +1,42 @@
<?php
-if(file_exists('./scripts/common.php')){
- include_once "./scripts/common.php";
-}else{
- include_once "./common.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);
}
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'])) {
- $_SESSION['behind'] = getGitStatus();
+ $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(isset($_SESSION['behind'])&&intval($_SESSION['behind']) >= 99) {?>
<style>
.updatenumber {
@@ -17,7 +45,11 @@ if(!isset($_SESSION['behind'])) {
</style>
<?php }}
-parseConfig();
+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');
+}
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>";
@@ -118,11 +150,18 @@ if(isset($_GET['view'])){
if($_GET['view'] == "Streamlit"){echo "<iframe src=\"/stats\"></iframe>";}
if($_GET['view'] == "Daily Charts"){include('history.php');}
if($_GET['view'] == "Tools"){
- //Authenticate before proceeding
- $user_is_authenticated = authenticateUser();
- if ($user_is_authenticated) {
- $url = $_SERVER['SERVER_NAME'] . "/scripts/adminer.php";
- echo "<div class=\"centered\">
+ $caddypwd = $config['CADDY_PWD'];
+ if (!isset($_SERVER['PHP_AUTH_USER'])) {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo '<table><tr><td>You cannot edit the settings for this installation</td></tr></table>';
+ exit;
+ } else {
+ $submittedpwd = $_SERVER['PHP_AUTH_PW'];
+ $submitteduser = $_SERVER['PHP_AUTH_USER'];
+ if($submittedpwd == $caddypwd && $submitteduser == 'birdnet'){
+ $url = $_SERVER['SERVER_NAME']."/scripts/adminer.php";
+ echo "<div class=\"centered\">
<form action=\"\" method=\"GET\" id=\"views\">
<button type=\"submit\" name=\"view\" value=\"Settings\" form=\"views\">Settings</button>
<button type=\"submit\" name=\"view\" value=\"System Info\" form=\"views\">System Info</button>
@@ -135,33 +174,38 @@ if(isset($_GET['view'])){
<button type=\"submit\" name=\"view\" value=\"Excluded\" form=\"views\">Excluded Species List</button>
</form>
</div>";
- }
+ } else {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo '<table><tr><td>You cannot edit the settings for this installation</td></tr></table>';
+ exit;
+ }
+ }
}
if($_GET['view'] == "Recordings"){include('play.php');}
if($_GET['view'] == "Settings"){include('scripts/config.php');}
if($_GET['view'] == "Advanced"){include('scripts/advanced.php');}
if($_GET['view'] == "Included"){
- $user_is_authenticated = authenticateUser('You cannot modify the system');
- if(isset($_GET['species']) && isset($_GET['add']) && $user_is_authenticated){
- $file = getFilePath('include_species_list.txt');
+ if(isset($_GET['species']) && isset($_GET['add'])){
+ $file = './scripts/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( getFilePath('include_species_list.txt'), $selectedOption."\n", FILE_APPEND);
+ file_put_contents("./scripts/include_species_list.txt", $selectedOption."\n", FILE_APPEND);
}
} elseif(isset($_GET['species']) && isset($_GET['del'])){
- $file = getFilePath('include_species_list.txt');
+ $file = './scripts/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( getFilePath('include_species_list.txt'));
+ $content = file_get_contents("../BirdNET-Pi/include_species_list.txt");
$newcontent = str_replace($selectedOption, "", "$content");
- file_put_contents( getFilePath('include_species_list.txt'), "$newcontent");
+ file_put_contents("./scripts/include_species_list.txt", "$newcontent");
}
- $file = getFilePath('include_species_list.txt');
+ $file = './scripts/include_species_list.txt';
$str = file_get_contents("$file");
$str = preg_replace('/^\h*\v+/m', '', $str);
file_put_contents("$file", "$str");
@@ -169,25 +213,24 @@ if(isset($_GET['view'])){
include('./scripts/include_list.php');
}
if($_GET['view'] == "Excluded"){
- $user_is_authenticated = authenticateUser('You cannot modify the system');
- if(isset($_GET['species']) && isset($_GET['add']) && $user_is_authenticated){
- $file = getFilePath('exclude_species_list.txt');
+ if(isset($_GET['species']) && isset($_GET['add'])){
+ $file = './scripts/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(getFilePath('exclude_species_list.txt'), $selectedOption."\n", FILE_APPEND);
+ file_put_contents("./scripts/exclude_species_list.txt", $selectedOption."\n", FILE_APPEND);
} elseif (isset($_GET['species']) && isset($_GET['del'])){
- $file = getFilePath('exclude_species_list.txt');
+ $file = './scripts/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(getFilePath('exclude_species_list.txt'));
+ $content = file_get_contents("./scripts/exclude_species_list.txt");
$newcontent = str_replace($selectedOption, "", "$content");
- file_put_contents(getFilePath('exclude_species_list.txt'), "$newcontent");
+ file_put_contents("./scripts/exclude_species_list.txt", "$newcontent");
}
- $file = getFilePath('exclude_species_list.txt');
+ $file = './scripts/exclude_species_list.txt';
$str = file_get_contents("$file");
$str = preg_replace('/^\h*\v+/m', '', $str);
file_put_contents("$file", "$str");
@@ -198,104 +241,123 @@ if(isset($_GET['view'])){
echo "<iframe src='scripts/filemanager/filemanager.php'></iframe>";
}
if($_GET['view'] == "Webterm"){
- //Authenticate before proceeding
- $user_is_authenticated = authenticateUser("You cannot access the web terminal");
- if ($user_is_authenticated) {
+ 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');
+ }
+ $caddypwd = $config['CADDY_PWD'];
+ if (!isset($_SERVER['PHP_AUTH_USER'])) {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo '<table><tr><td>You cannot access the web terminal</td></tr></table>';
+ exit;
+ } else {
+ $submittedpwd = $_SERVER['PHP_AUTH_PW'];
+ $submitteduser = $_SERVER['PHP_AUTH_USER'];
+ if($submittedpwd == $caddypwd && $submitteduser == 'birdnet'){
#ACCESS THE WEB TERMINAL
echo "<iframe src='/terminal'></iframe>";
- }
+ } else {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo '<table><tr><td>You cannot access the web terminal</td></tr></table>';
+ exit;
+ }
+ }
}
} elseif(isset($_GET['submit'])) {
- //Authenticate before proceeding
- $user_is_authenticated = authenticateUser('You cannot modify the system');
-
- $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',
+ 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');
+ }
+ $caddypwd = $config['CADDY_PWD'];
+ if (!isset($_SERVER['PHP_AUTH_USER'])) {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo 'You cannot access the web terminal';
+ exit;
+ } 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',
'sudo reboot',
'update_birdnet.sh',
'sudo shutdown now',
'sudo clear_all_data.sh');
$command = $_GET['submit'];
- if($user_is_authenticated && in_array($command,$allowedCommands)){
+ if($submittedpwd == $caddypwd && $submitteduser == 'birdnet' && in_array($command,$allowedCommands)){
if(isset($command)){
$initcommand = $command;
- $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 (strpos($command, "systemctl") !== false) {
//If there more than one command to execute, processes then separately
//currently only livestream service uses multiple commands to interact with the required services
if (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 so we can poll the status
+ //get the service names
$new_multiservice_status_command .= " " . trim(end($separate_command_tmp));
}
$service_names = $new_multiservice_status_command;
} else {
- serviceMaintenance($command);
- //only one service needs restarting so we only need to query the status of one service
+ //only one service needs restarting so we only need to query the status of one service
$tmp = explode(" ", trim($command));
$service_names = end($tmp);
}
- //Build up the command that will query the service status
- $command = "sleep 3;sudo systemctl status " . $service_names;
+
+ $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);
@@ -347,16 +409,15 @@ if(isset($_GET['view'])){
}
echo "<table style='min-width:70%;'><tr class='relative'><th>Output of command:`".$initcommand."`<button class='copyimage' style='right:40px' onclick='copyOutput(this);'>Copy</button></th></tr><tr><td style='padding-left: 0px;padding-right: 0px;padding-bottom: 0px;padding-top: 0px;'><pre class='bash' style='text-align:left;margin:0px'>$results</pre></td></tr></table>";
} else {
- header('WWW-Authenticate: Basic realm="BirdNET-Pi"');
+ header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
- echo 'You cannot modify the system';
+ echo 'You cannot access the web terminal';
exit;
}
}
+ }
ob_end_flush();
-} else {
- include('overview.php');
-}
+} else {include('overview.php');}
?>
<script>
function myFunction() {
diff --git a/scripts/advanced.php b/scripts/advanced.php
index 74417bdd..48a33b61 100644
--- a/scripts/advanced.php
+++ b/scripts/advanced.php
@@ -1,166 +1,357 @@
<?php
-if(file_exists('./scripts/common.php')){
- include_once "./scripts/common.php";
-}else{
- include_once "./common.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');
}
-//Authenticate before going any further
-authenticateUser('You cannot edit the settings for this installation');
+$caddypwd = $config['CADDY_PWD'];
+if (!isset($_SERVER['PHP_AUTH_USER'])) {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo '<table><tr><td>You cannot edit the settings for this installation</td></tr></table>';
+ exit;
+} else {
+ $submittedpwd = $_SERVER['PHP_AUTH_PW'];
+ $submitteduser = $_SERVER['PHP_AUTH_USER'];
+ if($submittedpwd !== $caddypwd || $submitteduser !== 'birdnet'){
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo '<table><tr><td>You cannot edit the settings for this installation</td></tr></table>';
+ exit;
+ }
+}
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 &');
+ }
+ }
+
if(isset($_GET["ice_pwd"])) {
$ice_pwd = $_GET["ice_pwd"];
- saveSetting('ICE_PWD', $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);
+ }
+ }
+
+ 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 &');
+ }
}
if(isset($_GET["rtsp_stream"])) {
$rtsp_stream = str_replace("\r\n", ",", $_GET["rtsp_stream"]);
- saveSetting('RTSP_STREAM', "\"$rtsp_stream\"", ['restart birdnet_recording', 'restart livestream']);
+ 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');
+ }
}
if (isset($_GET["rtsp_stream_to_livestream"])) {
$rtsp_stream_selected = trim($_GET["rtsp_stream_to_livestream"]);
- saveSetting('RTSP_STREAM_TO_LIVESTREAM', "\"$rtsp_stream_selected\"", 'restart 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");
+ }
}
if(isset($_GET["overlap"])) {
$overlap = $_GET["overlap"];
- saveSetting('OVERLAP', $overlap);
+ if(strcmp($overlap,$config['OVERLAP']) !== 0) {
+ $contents = preg_replace("/OVERLAP=.*/", "OVERLAP=$overlap", $contents);
+ $contents2 = preg_replace("/OVERLAP=.*/", "OVERLAP=$overlap", $contents2);
+ }
}
if(isset($_GET["confidence"])) {
$confidence = $_GET["confidence"];
- saveSetting('CONFIDENCE', $confidence);
+ if(strcmp($confidence,$config['CONFIDENCE']) !== 0) {
+ $contents = preg_replace("/CONFIDENCE=.*/", "CONFIDENCE=$confidence", $contents);
+ $contents2 = preg_replace("/CONFIDENCE=.*/", "CONFIDENCE=$confidence", $contents2);
+ }
}
if(isset($_GET["sensitivity"])) {
$sensitivity = $_GET["sensitivity"];
- saveSetting('SENSITIVITY', $sensitivity);
+ if(strcmp($sensitivity,$config['SENSITIVITY']) !== 0) {
+ $contents = preg_replace("/SENSITIVITY=.*/", "SENSITIVITY=$sensitivity", $contents);
+ $contents2 = preg_replace("/SENSITIVITY=.*/", "SENSITIVITY=$sensitivity", $contents2);
+ }
}
if(isset($_GET["freqshift_hi"]) && is_numeric($_GET['freqshift_hi'])) {
$freqshift_hi = $_GET["freqshift_hi"];
- saveSetting('FREQSHIFT_HI', $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);
+ }
}
if(isset($_GET["freqshift_lo"]) && is_numeric($_GET['freqshift_lo'])) {
$freqshift_lo = $_GET["freqshift_lo"];
- saveSetting('FREQSHIFT_HI', $freqshift_hi);
+ 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);
+ }
}
if(isset($_GET["freqshift_pitch"]) && is_numeric($_GET['freqshift_pitch'])) {
$freqshift_pitch = $_GET["freqshift_pitch"];
- saveSetting('FREQSHIFT_PITCH', $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);
+ }
}
if(isset($_GET["freqshift_tool"])) {
$freqshift_tool = $_GET["freqshift_tool"];
- saveSetting('FREQSHIFT_TOOL', $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);
+ }
}
if(isset($_GET["full_disk"])) {
$full_disk = $_GET["full_disk"];
- saveSetting('FULL_DISK', $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);
+ }
}
if(isset($_GET["privacy_threshold"])) {
$privacy_threshold = $_GET["privacy_threshold"];
- saveSetting('PRIVACY_THRESHOLD', $privacy_threshold,'restart_services');
+ 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');
+ }
}
if(isset($_GET["rec_card"])) {
- $rec_card = trim($_GET["rec_card"]);
- saveSetting('REC_CARD', "\"$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);
+ }
}
if(isset($_GET["channels"])) {
$channels = $_GET["channels"];
- saveSetting('CHANNELS', $channels);
+ if(strcmp($channels,$config['CHANNELS']) !== 0) {
+ $contents = preg_replace("/CHANNELS=.*/", "CHANNELS=$channels", $contents);
+ $contents2 = preg_replace("/CHANNELS=.*/", "CHANNELS=$channels", $contents2);
+ }
}
if(isset($_GET["recording_length"])) {
$recording_length = $_GET["recording_length"];
- saveSetting('RECORDING_LENGTH', $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);
+ }
}
if(isset($_GET["extraction_length"])) {
$extraction_length = $_GET["extraction_length"];
- saveSetting('EXTRACTION_LENGTH', $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);
+ }
}
if(isset($_GET["audiofmt"])) {
$audiofmt = $_GET["audiofmt"];
- saveSetting('AUDIOFMT', $audiofmt);
+ if(strcmp($audiofmt,$config['AUDIOFMT']) !== 0) {
+ $contents = preg_replace("/AUDIOFMT=.*/", "AUDIOFMT=$audiofmt", $contents);
+ $contents2 = preg_replace("/AUDIOFMT=.*/", "AUDIOFMT=$audiofmt", $contents2);
+ }
}
if(isset($_GET["silence_update_indicator"])) {
$silence_update_indicator = 1;
- saveSetting('SILENCE_UPDATE_INDICATOR', $silence_update_indicator);
+ 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);
+ }
} else {
- saveSetting('SILENCE_UPDATE_INDICATOR', 0);
+ $contents = preg_replace("/SILENCE_UPDATE_INDICATOR=.*/", "SILENCE_UPDATE_INDICATOR=0", $contents);
+ $contents2 = preg_replace("/SILENCE_UPDATE_INDICATOR=.*/", "SILENCE_UPDATE_INDICATOR=0", $contents2);
}
if(isset($_GET["raw_spectrogram"])) {
$raw_spectrogram = 1;
- saveSetting('RAW_SPECTROGRAM', $raw_spectrogram);
+ 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);
+ }
} else {
- saveSetting('RAW_SPECTROGRAM', 0);
+ $contents = preg_replace("/RAW_SPECTROGRAM=.*/", "RAW_SPECTROGRAM=0", $contents);
+ $contents2 = preg_replace("/RAW_SPECTROGRAM=.*/", "RAW_SPECTROGRAM=0", $contents2);
}
if(isset($_GET["custom_image"])) {
$custom_image = $_GET["custom_image"];
-
- saveSetting('CUSTOM_IMAGE', $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);
+ }
}
if(isset($_GET["custom_image_label"])) {
$custom_image_label = $_GET["custom_image_label"];
-
- saveSetting('CUSTOM_IMAGE_TITLE', "\"$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);
+ }
}
if (isset($_GET["LogLevel_BirdnetRecordingService"])) {
$birdnet_recording_service_log_level = trim($_GET["LogLevel_BirdnetRecordingService"]);
- saveSetting('LogLevel_BirdnetRecordingService', "\"$birdnet_recording_service_log_level\"",'restart birdnet_recording');
+ //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");
+ }
}
if (isset($_GET["LogLevel_SpectrogramViewerService"])) {
$spectrogram_viewer_service_log_level = trim($_GET["LogLevel_SpectrogramViewerService"]);
- saveSetting('LogLevel_SpectrogramViewerService', "\"$spectrogram_viewer_service_log_level\"",'restart spectrogram_viewer');
+ //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");
+ }
}
if (isset($_GET["LogLevel_LiveAudioStreamService"])) {
$livestream_audio_service_log_level = trim($_GET["LogLevel_LiveAudioStreamService"]);
- saveSetting('LogLevel_LiveAudioStreamService', "\"$livestream_audio_service_log_level\"",['restart livestream','restart icecast2']);
- }
-
- if(isset($_GET["birdnetpi_url"])) {
- $birdnetpi_url = $_GET["birdnetpi_url"];
- // remove trailing slash to prevent conf from becoming broken
- $birdnetpi_url = rtrim($birdnetpi_url, '/');
- saveSetting('BIRDNETPI_URL', $birdnetpi_url);
- update_caddyfile();
+ //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");
+ }
}
- if(isset($_GET["caddy_pwd"])) {
- $caddy_pwd_value = "";
- $caddy_pwd = $_GET["caddy_pwd"];
- //If the BirdNET-Pi Password is empty, return a empty string instead of a string that was surrounded by double quotes
- //else return the supplied password
- //so in the ini file ['CADDY_PWD']= , instead of ['CADDY_PWD']="" (which still prompts for auth but password is required)
- //this returns the password setting to it's default state when no password is set
- $caddy_pwd_value = !empty($caddy_pwd) ? "\"$caddy_pwd\"" : "";
-
- saveSetting('CADDY_PWD', "$caddy_pwd_value");
- //Make sure the caddy file is set directly
- update_caddyfile();
- }
+ //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);
}
-$count = getLabelsCount();
+$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;
?>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
@@ -169,7 +360,11 @@ $count = getLabelsCount();
<div class="settings">
<?php
-$newconfig = $config;
+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');
+}
?>
<div class="brbanner"><h1>Advanced Settings</h1></div><br>
<form action="" method="GET">
@@ -220,7 +415,8 @@ $newconfig = $config;
<select name="audiofmt">
<option selected="<?php print($newconfig['AUDIOFMT']);?>"><?php print($newconfig['AUDIOFMT']);?></option>
<?php
-foreach($audio_formats as $format){
+ $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){
echo "<option value='$format'>$format</option>";
}
?>
@@ -382,9 +578,10 @@ foreach($audio_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");
- $freqshift_tools = array_diff($freqshift_tools, array($newconfig['FREQSHIFT_TOOL']));
- foreach($freqshift_tools as $format){
+ $formats = array_diff($formats, array($newconfig['FREQSHIFT_TOOL']));
+ foreach($formats as $format){
echo "<option value='$format'>$format</option>";
}
?>
@@ -490,7 +687,7 @@ foreach($audio_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){collectrtspUrls(); return confirm('This will take about 90 seconds.');}else{collectrtspUrls();}" type="submit" name="submit" 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">
<?php
if(isset($_GET['submit'])){
echo "Success!";
diff --git a/scripts/birdnetpi_request.php b/scripts/birdnetpi_request.php
index 6cfa606e..968c1745 100644
--- a/scripts/birdnetpi_request.php
+++ b/scripts/birdnetpi_request.php
@@ -1,10 +1,10 @@
<?php
-if(file_exists('./scripts/common.php')){
- include_once "./scripts/common.php";
-}else{
- include_once "./common.php";
-}
-$template = file_get_contents(getFilePath('email_template2'));
+if (file_exists('thisrun.txt')) {
+ $config = parse_ini_file('thisrun.txt');
+} elseif (file_exists('firstrun.ini')) {
+ $config = parse_ini_file('firstrun.ini');
+}
+$template = file_get_contents("./scripts/email_template2");
foreach($config as $key => $value)
{
diff --git a/scripts/birdweather_request.php b/scripts/birdweather_request.php
index add8e761..a8b82ab3 100644
--- a/scripts/birdweather_request.php
+++ b/scripts/birdweather_request.php
@@ -1,10 +1,10 @@
<?php
-if(file_exists('./scripts/common.php')){
- include_once "./scripts/common.php";
-}else{
- include_once "./common.php";
-}
-$template = file_get_contents(getFilePath('email_template'));
+if (file_exists('thisrun.txt')) {
+ $config = parse_ini_file('thisrun.txt');
+} elseif (file_exists('firstrun.ini')) {
+ $config = parse_ini_file('firstrun.ini');
+}
+$template = file_get_contents("./scripts/email_template");
foreach($config as $key => $value)
{
diff --git a/scripts/common.php b/scripts/common.php
deleted file mode 100644
index 25fc5145..00000000
--- a/scripts/common.php
+++ /dev/null
@@ -1,1780 +0,0 @@
-<?php
-if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) {
- header('HTTP/1.1 403 Forbidden', TRUE, 403);
-}
-
-ini_set('session.gc_maxlifetime', 7200);
-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);
-
-////////// SET TIMEZONE //////////
-// If we can get the timezome from the systems timezone file ust that
-$sys_timezone = "";
-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 valid timezone, set it as the one PHP uses
-if ($sys_timezone !== "") {
- date_default_timezone_set($sys_timezone);
-}
-
-
-////////// PARSES THE CONFIG FILE //////////
-$filePathMap_json_path = file_exists('./config/filepath_map.json') ? "./config/filepath_map.json" : "../config/filepath_map.json";
-$filePathMap_data = [];
-$config = [];
-parseConfig();
-
-//Set a default site name if nothing iss configured
-if ($config["SITE_NAME"] == "") {
- $site_name = "BirdNET-Pi";
-} else {
- $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;
-$USER_AUTHENTICATED = false;
-
-/**
- * Connects to the bird.db SQLite3 database
- * @return SQLite3
- */
-function connect_to_birdsdb()
-{
- global $DB_CONN, $api_incl;
-
- //Initially check to see if the DB is already connected, it will not be null if it has
- if ($DB_CONN == null) {
- try {
- $DB_CONN = new SQLite3(getFilePath('birds.db'), SQLITE3_OPEN_CREATE | SQLITE3_OPEN_READWRITE);
- if ($DB_CONN == False) {
- birdnet_error_log("connect_to_birdsdb:: birds.db database is busy");
- }
- } catch (Exception $sql_exec) {
- birdnet_error_log("connect_to_birdsdb:: Exception occurred while trying to open birds.db - " . $sql_exec->getMessage());
- }
- }
-
- return $DB_CONN;
-}
-
-/**
- * Disconnects the database
- *
- * @return void
- */
-function disconnect_from_birdsdb()
-{
- global $DB_CONN;
-
- if ($DB_CONN != null) {
- return $DB_CONN->close();
- }
-}
-
-/**
- * Executes the supplied query and returns all results
- *
- * @param $query string The query to execute
- * @param $bind_params string Any values that should be bound into the query
- * @param $fetchAllRecords string Any values that should be bound into the query
- * @param $fetchMode string Controls how result data is returned, default is @->default('SQLITE3_ASSOC') Associative Array;
- * @return array
- */
-function db_execute_query($query, $bind_params = [], $fetchAllRecords = false, $fetchMode = SQLITE3_ASSOC)
-{
- global $DB_CONN;
- $success = false;
- $message = '';
- $data_to_return = null;
-
- //Connect to the DB
- connect_to_birdsdb();
- try {
- $stmt = $DB_CONN->prepare($query);
- //
- if (!empty($bind_params)) {
- //Loop over the bind values and add them
- foreach ($bind_params as $bind_key => $bind_value) {
- $stmt->bindValue($bind_key, $bind_value);
- }
- }
-
- if ($stmt == False) {
- //get caller's function name
- $caller_func_name = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function'];
- $error_msg = "$caller_func_name => db_execute_custom_query:: birds.db database is busy or a query error occurred";
- //
- $success = false;
- $message = $error_msg;
- $data_to_return = null;
-
- //Log the error message
- birdnet_error_log($error_msg);
- } else {
- $result = $stmt->execute();
- //Initial result collection
- $resultArray = $result->fetchArray($fetchMode);
-
- if ($fetchAllRecords) {
- $multiArray = array(); //array to store all rows
- //Loop over the results to collect them all
- while ($resultArray !== false) {
- array_push($multiArray, $resultArray); //insert all rows to $multiArray
- $resultArray = $result->fetchArray($fetchMode);
- }
- unset($resultArray); //unset temporary variable
-
- $data_to_return = $multiArray;
- } else {
- $data_to_return = $resultArray;
- }
-
- //
- $success = true;
- $message = 'Ok';
- }
- } catch (Exception $sql_exec) {
- $caller_func_name = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function'];
- $error_msg = "$caller_func_name => db_execute_custom_query:: Exception occurred while executing query - " . $sql_exec->getMessage();
- //
- $success = false;
- $message = $error_msg;
- $data_to_return = null;
-
- birdnet_error_log($error_msg);
- }
-
- return array('success' => $success, 'message' => $message, 'data' => $data_to_return);
-}
-
-/**
- * Returns a count of detections in the database
- * @return array
- */
-function getDetectionCountAll()
-{
- return db_execute_query('SELECT COUNT(*) FROM detections');
-}
-
-/**
- * Returns today's count of detections in the database
- * @return array
- */
-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
- */
-function getDetectionCountLastHour()
-{
- return db_execute_query('SELECT COUNT(*) FROM detections WHERE Date == Date(\'now\', \'localtime\') AND TIME >= TIME(\'now\', \'localtime\', \'-1 hour\')');
-}
-
-/**
- * Returns the most recent detection
- * @return array|string
- */
-function getMostRecentDetection($limit = 1)
-{
- return db_execute_query('SELECT Com_Name, Sci_Name, Date, Time, Confidence, File_Name FROM detections ORDER BY Date DESC, Time DESC LIMIT :limit', [':limit' => $limit], true);
-}
-
-/**
- * Returns a talley for todays detected species
- * @return array
- */
-function getSpeciesTalley($range = "today", $start_date = null, $end_date = null)
-{
- $range = strtolower($range);
-
- if ($range == "today") {
- $result = db_execute_query('SELECT COUNT(DISTINCT(Com_Name)) FROM detections WHERE Date == Date(\'now\', \'localtime\')');
- } else if ($range == "custom") {
- $result = db_execute_query('SELECT COUNT(DISTINCT(Com_Name)) FROM detections WHERE Date == :start_date', [':start_date' => $start_date], false);
- } else if ($range == "range") {
- $result = db_execute_query('SELECT COUNT(DISTINCT(Com_Name)) FROM detections WHERE Date BETWEEN :start_date AND :end_date', [':start_date' => $start_date, ':end_date' => $end_date]);
- }
-
- return $result;
-}
-
-/**
- * Returns a species talley from ALL detections
- * @return array
- */
-function getAllSpeciesTalley()
-{
- return db_execute_query('SELECT COUNT(DISTINCT(Com_Name)) FROM detections');
-}
-
-/**
- * Returns the number of detections on the specified date
- *
- * @param $date string Date to count detections for
- * @return array
- */
-function getDetectionCountByDate($date, $date_range = false)
-{
- return db_execute_query("SELECT COUNT(*) FROM detections WHERE Date == :date", [':date' => $date], false);
-}
-
-/**
- * Returns detections and counts for the specified date and start & finish times
- *
- * @param $date string Date to count detections for
- * @param $starttime string Search for detections after this time
- * @param $endtime string And detections up to this time
- * @return array
- */
-function getDetectionBreakdownByTime($date, $starttime, $endtime)
-{
- return db_execute_query('SELECT DISTINCT(Com_Name), COUNT(*) FROM detections WHERE Date == :date AND Time > :start_time AND Time < :end_time AND Confidence > 0.75 GROUP By Com_Name ORDER BY COUNT(*) DESC',
- [
- ':date' => $date,
- ':start_time' => $starttime,
- ':end_time' => $endtime
- ],
- true);
-}
-
-
-/**
- * Returns the detection count for a specified bird
- * @param $birdName string Species Name to get stats for
- * @return array
- */
-function getBirdDetectionStats($birdName)
-{
- //Cleanup the bird/species name
- $birdName = str_replace("_", " ", $birdName);
-
- $birdDetections = db_execute_query('SELECT Date, COUNT(*) AS Detections FROM detections WHERE Com_Name = :com_name AND Date BETWEEN DATE("now", "-30 days") AND DATE("now") GROUP BY Date', [':com_name' => $birdName], true);
-
- // Fetch the result set as an associative array
- $data = array();
- foreach ($birdDetections as $birdDetection) {
- $data[$birdDetection['Date']] = $birdDetection['Detections'];
- }
-
- // Create an array of all dates in the last 14 days
- $last14Days = array();
- for ($i = 0; $i < 31; $i++) {
- $last14Days[] = date('Y-m-d', strtotime("-$i days"));
- }
-
- // Merge the data array with the last14Days array
- $data = array_merge(array_fill_keys($last14Days, 0), $data);
-
- // Sort the data by date in ascending order
- ksort($data);
-
- // Convert the data to an array of objects
- $data = array_map(function ($date, $count) {
- return array('date' => $date, 'count' => $count);
- }, array_keys($data), $data);
-
- // Return the data as JSON - overwrite the result data
- $birdDetections['data'] = json_encode($data);
-
- return $birdDetections;
-}
-
-/**
- * Returns detection info for the specified
- * @param $birdName string Species name to get detection info on
- * @param $date string OPTIONAL - The date on which to list species on
- * @param $sort string OPTIONAL - Whether to sort the species by confidence value (so species ranked by detection accuracy/confidence)
- * @return array|string
- */
-function getSpeciesDetectionInfo($birdName, $date = null, $sort = null)
-{
- //If no date is supplied, then list a unique list of detection dates in the DB, sorted descending
- if ($date == null) {
- //No date set so automatically search by date and time if no sort value is set
- if (isset($sort) && $sort == "confidence") {
- $detectionInfo = db_execute_query("SELECT * FROM detections where Com_Name == :birdname ORDER BY Confidence DESC", [':birdname' => $birdName], true);
- } else {
- $detectionInfo = db_execute_query("SELECT * FROM detections where Com_Name == :birdname ORDER BY Date DESC, Time DESC", [':birdname' => $birdName], true);
- }
- } else {
- //Date set so use that to filter the results depending on the sort value
- if (isset($sort) && $sort == "confidence") {
- $detectionInfo = db_execute_query("SELECT * FROM detections where Com_Name == :birdname AND Date == :date ORDER BY Confidence DESC", [':birdname' => $birdName, ':date' => $date], true);
- } else {
- $detectionInfo = db_execute_query("SELECT * FROM detections where Com_Name == :birdname AND Date == :date ORDER BY Time DESC", [':birdname' => $birdName, ':date' => $date], true);
- }
- }
-
- return $detectionInfo;
-}
-
-/**
- * Returns the detections for a specified filename
- *
- * @param $filename string The filename on which to get detections for
- * @return array|string
- */
-function getDetectionsByFilename($filename)
-{
- return db_execute_query("SELECT * FROM detections where File_name == :filename ORDER BY Date DESC, Time DESC", [':filename' => $filename], true);
-}
-
-/**
- * Returns a list of specie names on a specified date if supplied, else lists valid dates which can be passed again for specific list of species on that date
- *
- * @param $date string OPTIONAL - The date on which to list species on
- * @param $sort string OPTIONAL - Whether to sort the species by occurrence (so species ranked by number of detections)
- * @return array|string
- */
-function getDetectionsByDate($date = null, $sort = null)
-{
-
- //If no date is supplied, then list a unique list of species in the DB
- if ($date == null) {
- $detectionsByDateResult = db_execute_query('SELECT DISTINCT(Date) FROM detections GROUP BY Date ORDER BY Date DESC', null, true);
- } else {
- //Else a date was supplied, first check the sort order if any
- if (isset($sort) && $sort == "occurrences") {
- $detectionsByDateResult = db_execute_query("SELECT DISTINCT(Com_Name) FROM detections WHERE Date == :date GROUP BY Com_Name ORDER BY COUNT(*) DESC", [':date' => $date], true);
- } else {
- $detectionsByDateResult = db_execute_query("SELECT DISTINCT(Com_Name) FROM detections WHERE Date == :date ORDER BY Com_Name", [':date' => $date], true);
- }
- }
-
- return $detectionsByDateResult;
-}
-
-/**
- * Returns a list detections for a species if supplied, else lists all detected species by name
- *
- * @param $species_name string OPTIONAL - List detections for this specific species
- * @param $sort string OPTIONAL - Whether to sort the species by occurrence (so species ranked by number of detections)
- * @return array
- */
-function getDetectionsBySpecies($species_name = null, $sort = null)
-{
- //If no species is is supplied, then list all species
- if (!isset($species_name)) {
- if (isset($sort) && $sort == "occurrences") {
- //Sort by occurrences
- $speciesDetections = db_execute_query('SELECT DISTINCT(Com_Name) FROM detections GROUP BY Com_Name ORDER BY COUNT(*) DESC', null, true);
- } else {
- //Don't sort by occurrences
- $speciesDetections = db_execute_query('SELECT DISTINCT(Com_Name) FROM detections ORDER BY Com_Name ASC', null, true);
- }
- } else {
- //Else a species name was supplied, first check the sort order if any
- $speciesDetections = db_execute_query("SELECT * FROM detections WHERE Com_Name == :species_name ORDER BY Com_Name", [':species_name' => $species_name], true);
- //Also get the highest confidence record for this species
- $speciesDetections_MaxConf = db_execute_query("SELECT Date, Time, Sci_Name, MAX(Confidence), File_Name FROM detections WHERE Com_Name == :species_name ORDER BY Com_Name", [':species_name' => $species_name], true);
- }
-
- //Rearrange data
- $newReturnData = [];
- $newReturnData['species'] = $speciesDetections['data'];
- //Check to see if we have to get max confidence results for the species also
- if (isset($speciesDetections_MaxConf)) {
- $newReturnData['species_MaxConf'] = $speciesDetections_MaxConf['data'];
- }
-
- $speciesDetections['data'] = $newReturnData;
-
- return $speciesDetections;
-}
-
-/**
- * Returns a list of species either ordered alphabetically (default) or ordered by the number of detections the species has
- *
- * @param $sort string OPTIONAL - Sort result alphabetically (supply null) or by number of occurrences (supply "occurrences"
- * @return array
- */
-function getSpeciesBestRecordingList($sort = null)
-{
- if (isset($sort) && $sort == "occurrences") {
- //Sort by occurrences
- $speciesBestRecording = db_execute_query('SELECT Date, Time, File_Name, Com_Name, COUNT(*), MAX(Confidence) FROM detections GROUP BY Com_Name ORDER BY COUNT(*) DESC', null, true);
-
- } else {
- //Don't sort by occurrences, sort by alphabetical
- $speciesBestRecording = db_execute_query('SELECT Date, Time, File_Name, Com_Name, COUNT(*), MAX(Confidence) FROM detections GROUP BY Com_Name ORDER BY Com_Name ASC', null, true);
- }
-
- return $speciesBestRecording;
-}
-
-/**
- * Returns a list of best recordings for a supplied species
- *
- * @param $species_name string Name of the species
- * @return array
- */
-function getBestRecordingsForSpecies($species_name)
-{
- return db_execute_query("SELECT Com_Name, Sci_Name, COUNT(*), MAX(Confidence), File_Name, Date, Time from detections WHERE Com_Name = :species_name", [':species_name' => $species_name], true);
-}
-
-/**
- * Get a list of todays detections
- *
- * @param $display_limit string Number of results to return
- * @param $search_term string OPTIONAL: Return results that match the supplied term
- * @param $hard_limit string OPTIONAL: Return a fix number of results
- * @return array
- */
-function getTodaysDetections($display_limit, $search_term = null, $hard_limit = null)
-{
- $bind_params = [];
-
- if (isset($search_term)) {
- if (strtolower(explode(" ", $search_term)[0]) == "not") {
- $not = "NOT ";
- $operator = "AND";
- $search_term = str_replace("not ", "", $search_term);
- $search_term = str_replace("NOT ", "", $search_term);
- } else {
- $not = "";
- $operator = "OR";
- }
- $searchquery = "AND (Com_name " . $not . "LIKE :search_term " .
- $operator . " Sci_name " . $not . "LIKE :search_term " .
- $operator . " Confidence " . $not . "LIKE :search_term " .
- $operator . " File_Name " . $not . "LIKE :search_term " .
- $operator . " Time " . $not . "LIKE :search_term)";
-
- $bind_params = [':search_term' => '%' . $search_term . '%'];
- } else {
- $searchquery = "";
- }
-
- if (isset($display_limit) && is_numeric($display_limit)) {
- $bind_params[':display_limit'] = (intval($display_limit) - 40);
- $result = db_execute_query('SELECT Date, Time, Com_Name, Sci_Name, Confidence, File_Name FROM detections WHERE Date == Date(\'now\', \'localtime\') ' . $searchquery . ' ORDER BY Time DESC LIMIT :display_limit,40', $bind_params, true);
- } else {
- // legacy mode
- if (isset($hard_limit) && is_numeric($hard_limit)) {
- $bind_params[':hard_limit'] = $hard_limit;
- $result = db_execute_query('SELECT Date, Time, Com_Name, Sci_Name, Confidence, File_Name FROM detections WHERE Date == Date(\'now\', \'localtime\') ' . $searchquery . ' ORDER BY Time DESC LIMIT :hard_limit', $bind_params, true);
- } else {
- $result = db_execute_query('SELECT Date, Time, Com_Name, Sci_Name, Confidence, File_Name FROM detections WHERE Date == Date(\'now\', \'localtime\') ' . $searchquery . ' ORDER BY Time DESC', $bind_params, true);
- }
- }
-
- return $result;
-}
-
-/**
- * Returns the species talley for last week and the week prior
- *
- * @return array[]
- */
-function getWeeklyReportSpeciesTalley()
-{
- $last_week_dates = getLastWeekDates();
- $startdate = $last_week_dates['start_date'];
- $enddate = $last_week_dates['end_date'];
-
-
- $totalspeciestally = getSpeciesTalley('range', date("Y-m-d", $startdate), date("Y-m-d", $enddate));
- $priortotalspeciestally = getSpeciesTalley('range', date("Y-m-d", $startdate - (7 * 86400)), date("Y-m-d", $enddate - (7 * 86400)));
-
- return ['totalspeciestally' => $totalspeciestally, 'priortotalspeciestally' => $priortotalspeciestally];
-}
-
-/**
- * Returns the species talley for last week and the week prior
- *
- * @return array[]
- */
-function getWeeklyReportSpeciesDetectionCounts($detections_asc = false)
-{
- $last_week_dates = getLastWeekDates();
- $startdate = $last_week_dates['start_date'];
- $enddate = $last_week_dates['end_date'];
-
-
- $sort_order = $detections_asc ? 'ASC' : 'DESC';
-
- $detections = db_execute_query('SELECT DISTINCT(Com_Name), COUNT(*) FROM detections WHERE Date BETWEEN :start_date AND :end_date GROUP By Com_Name ORDER BY COUNT(*) ' . $sort_order, [':start_date' => date("Y-m-d", $startdate), ':end_date' => date("Y-m-d", $enddate)], true);
- $totalcount = db_execute_query('SELECT DISTINCT(Com_Name), COUNT(*) FROM detections WHERE Date BETWEEN :start_date AND :end_date', [':start_date' => date("Y-m-d", $startdate), ':end_date' => date("Y-m-d", $enddate)], true);
- $priortotalcount = db_execute_query('SELECT DISTINCT(Com_Name), COUNT(*) FROM detections WHERE Date BETWEEN :start_date AND :end_date', [':start_date' => date("Y-m-d", date("Y-m-d", $startdate - (7 * 86400))), ':end_date' => date("Y-m-d", date("Y-m-d", $enddate - (7 * 86400)))], true);
-
- return ['detections' => $detections, 'totalcount' => $totalcount, 'priortotalcount' => $priortotalcount];
-}
-
-/**
- * Returns last weeks detection count for the specified species
- *
- * @param string $species_name Species to get last weeks detection count for
- * @param bool $this_week Whether to find detections in or outside last week
- * @return array
- */
-function getWeeklyReportSpeciesDetection($species_name, $this_week = true)
-{
- $last_week_dates = getLastWeekDates();
- $startdate = $last_week_dates['start_date'];
- $enddate = $last_week_dates['end_date'];
-
- if ($this_week) {
- $result = db_execute_query('SELECT COUNT(*) FROM detections WHERE Com_Name == :species_name AND Date BETWEEN :start_date AND :end_date', [':species_name' => $species_name, ':start_date' => date("Y-m-d", $startdate - (7 * 86400)), ':end_date' => date("Y-m-d", $enddate - (7 * 86400))], false);
- } else {
- $result = db_execute_query('SELECT COUNT(*) FROM detections WHERE Com_Name == :species_name AND Date NOT BETWEEN :start_date AND :end_date', [':species_name' => $species_name, ':start_date' => date("Y-m-d", $startdate), ':end_date' => date("Y-m-d", $enddate)], false);
- }
-
- return $result;
-}
-
-/**
- * Deletes a specified detection by filename
- *
- * @param $filename string The filename of the detection e.g 2023-04-25/Pacific_Koel/Pacific_Koel-76-2023-04-25-birdnet-RTSP_2-16:24:05.mp3
- * @return array
- */
-function deleteDetection($filename)
-{
- global $DB_CONN, $api_incl;
- $success = false;
- $message = '';
- $data_to_return = null;
-
- //Check authentication before going any further
- //the front end would have done this check already and such should pass
- authenticateUser();
-
- $filename_exploded = explode("/", $filename);
- $actual_filename = $filename_exploded[2];
-
-
- //If the detection was successfully deleted, remove the mp3 and png spectrogram
- $file_pointer = getDirectory('home') . "/BirdSongs/Extracted/By_Date/" . $filename;
- if (!exec("sudo rm $file_pointer && sudo rm $file_pointer.png")) {
- $message = "OK";
- $statement = db_execute_query('DELETE FROM detections WHERE File_Name = :filename LIMIT 1', [':filename' => $actual_filename]);
- } else {
- $message = "Error";
- }
-
- //
- $success = true;
- //Message set above
- $data_to_return = $statement;
-
- return array('success' => $success, 'message' => $message, 'data' => $data_to_return);
-}
-
-/**
- * Protects the specified file from deletion
- *
- * @param $mode string Set the mode to add (protect) to remove (unprotect) the specified filepath from protection
- * @param $filename_to_protect string The filename of the detection to protect e.g 2023-04-25/Pacific_Koel/Pacific_Koel-76-2023-04-25-birdnet-RTSP_2-16:24:05.mp3
- * @return array
- */
-function protectDetectionFromDeletion($mode, $filename_to_protect)
-{
- global $api_incl;
- $success = false;
- $message = '';
- $data_to_return = null;
-
- $mode = strtolower($mode);
-
- $scripts_dir = getDirectory('scripts');
- $disk_check_exclude_file = $scripts_dir . "/disk_check_exclude.txt";
-
- //Initially create the file if it doesn't exist
- if (!file_exists($disk_check_exclude_file)) {
- file_put_contents($disk_check_exclude_file, "##start\n##end\n");
- }
-
- if ($mode == "protect") {
- // load the data and delete the line from the array which is ##end,
- // so that all excluded files sit between the ##start and ##end tags
- $lines = file($disk_check_exclude_file);
- $last = sizeof($lines) - 1;
- unset($lines[$last]);
-
- //Open the file and truncate contents
- if (($myfile = fopen($disk_check_exclude_file, "w")) !== false) {
- $txt = $filename_to_protect;
- //Write all existing lines
- fwrite($myfile, implode("", $lines));
- //Write out the lines for the file were trying to exclude
- fwrite($myfile, $txt . "\n");
- fwrite($myfile, $txt . ".png\n");
- //Insert the end tag again to make it the last line
- fwrite($myfile, "##end\n");
-
- fclose($myfile);
- //
- $success = true;
- $message = "OK";
- } else {
- $success = false;
- $message = "Unable to open file! " . $disk_check_exclude_file;
- }
- } else if ($mode == "unprotect") {
- $lines = file($disk_check_exclude_file);
- $search = $filename_to_protect;
-
- $result = '';
- foreach ($lines as $line) {
- if (stripos($line, $search) === false && stripos($line, $search . ".png") === false) {
- $result .= $line;
- }
- }
- if (file_put_contents($disk_check_exclude_file, $result) !== false) {
- $success = true;
- $message = "OK";
- } else {
- $success = true;
- $message = "Failed writing contents after removing file from protection, back to file $disk_check_exclude_file";
- }
- }
-
- return array('success' => $success, 'message' => $message, 'data' => $data_to_return);
-}
-
-/**
- * Frequency shifts the specified audio file to aid listening for hearing impaired people
- *
- * @param $filename
- * @param $performShift
- * @return array
- */
-function frequencyShiftDetectionAudio($filename, $performShift = null)
-{
- global $config, $api_incl;
- $success = false;
- $message = '';
- $data_to_return = null;
-
- //Check authentication before going any further
- //the front end would have done this check already and such should pass
- authenticateUser();
-
- $shifted_path = getDirectory('shifted_audio') . '/';
-
- $pp = pathinfo($filename);
- $dir = $pp['dirname'];
- $fn = $pp['filename'];
- $ext = $pp['extension'];
- $pi = getDirectory('extracted_bydate') . '/';
-
- if (isset($performShift) && $performShift == true) {
- $freqshift_tool = $config['FREQSHIFT_TOOL'];
-
- if ($freqshift_tool == "ffmpeg") {
- $cmd = "sudo /usr/bin/nohup /usr/bin/ffmpeg -y -i " . escapeshellarg($pi . $filename) . " -af \"rubberband=pitch=" . $config['FREQSHIFT_LO'] . "/" . $config['FREQSHIFT_HI'] . "\" " . escapeshellarg($shifted_path . $filename) . "";
- shell_exec("sudo mkdir -p " . $shifted_path . $dir . " && " . $cmd);
- } else if ($freqshift_tool == "sox") {
- //linux.die.net/man/1/sox
- $soxopt = "-q";
- $soxpitch = $config['FREQSHIFT_PITCH'];
- $cmd = "sudo /usr/bin/nohup /usr/bin/sox " . escapeshellarg($pi . $filename) . " " . escapeshellarg($shifted_path . $filename) . " pitch " . $soxopt . " " . $soxpitch;
- shell_exec("sudo mkdir -p " . $shifted_path . $dir . " && " . $cmd);
- }
- } else {
- $cmd = "sudo rm -f " . escapeshellarg($shifted_path . $filename);
- shell_exec($cmd);
- }
-
- //
- $success = true;
- $message = "OK";
-
- return array('success' => $success, 'message' => $message, 'data' => $data_to_return);
-}
-
-/**
- * Adds the supplied Flickr Image Id to the list of blacklisted images
- *
- * @param $imageID
- * @return array
- */
-function blacklistFlickrImage($imageID)
-{
- $success = false;
- $message = '';
- $data_to_return = null;
-
- $scripts_dir = getDirectory('scripts');
-
- //Append the Flickr Image ID the blacklist file
- if (($file_handle = fopen($scripts_dir . "/blacklisted_images.txt", 'a+')) !== false) {
- fwrite($file_handle, $imageID . "\n");
- fclose($file_handle);
- //
- $success = true;
- $message = "Ok";
- } else {
- $success = false;
- $message = "Failed";
- }
-
- return array('success' => $success, 'message' => $message, 'data' => $data_to_return);
-}
-
-/**
- * Finds and returns a flicker image for the supplied detection, detection data must have the following columns Com_Name, Sci_Name, Date, Time, Confidence, File_Name
- * getMostRecentDetections
- *
- * @param $detection_data
- * @param bool $getAll
- * @return string[][]
- */
-function getFlickrImage($detection_data, $getAll = false)
-{
- global $config;
-
- $success = false;
- $message = '';
- $data_to_return = null;
-
- $flickr_data_to_return = array(
- 'Com_Name' => 'N/A',
- 'Sci_Name' => 'N/A',
- 'Date' => 'N/A',
- 'Time' => 'N/A',
- 'Confidence' => '0',
- 'File_Name' => 'N/A',
- 'Com_Name_clean' => 'N/A',
- 'Sci_Name_clean' => 'N/A',
- 'photos' => null,
- 'filename_path' => 'N/A',
- 'filename_formatted' => 'N/A'
- );
- $foundImage = false;
-
- if (isset($detection_data)) {
- $extracted_dir = getDirectory('extracted');
- $home_dir = getDirectory('home');
-
- //Setup out flickr image cache in the session
- if (!isset($_SESSION['images'])) {
- $_SESSION['images'] = [];
- }
-
- //Cleanup the Birds common and scientic name
- $comname_clean = preg_replace('/ /', '_', $detection_data['Com_Name']);
- $sciname_clean = preg_replace('/ /', '_', $detection_data['Sci_Name']);
- $comname_clean = preg_replace('/\'/', '', $comname_clean);
- $filename_path = "/By_Date/" . $detection_data['Date'] . "/" . $comname_clean . "/" . $detection_data['File_Name'];
- $filename_formatted = $detection_data['Date'] . "/" . $comname_clean . "/" . $detection_data['File_Name'];
- $args = "&license=2%2C3%2C4%2C5%2C6%2C9&orientation=square,portrait";
- $comnameprefix = "%20bird";
-
- if (!empty($config["FLICKR_API_KEY"])) {
-
- if (!empty($config["FLICKR_FILTER_EMAIL"])) {
- if (!isset($_SESSION["FLICKR_FILTER_EMAIL"])) {
- unset($_SESSION['images']);
- $_SESSION['FLICKR_FILTER_EMAIL'] = json_decode(file_get_contents("https://www.flickr.com/services/rest/?method=flickr.people.findByEmail&api_key=" . $config["FLICKR_API_KEY"] . "&find_email=" . $config["FLICKR_FILTER_EMAIL"] . "&format=json&nojsoncallback=1"), true)["user"]["nsid"];
- }
- $args = "&user_id=" . $_SESSION['FLICKR_FILTER_EMAIL'];
- $comnameprefix = "";
- } else {
- if (isset($_SESSION["FLICKR_FILTER_EMAIL"])) {
- unset($_SESSION["FLICKR_FILTER_EMAIL"]);
- unset($_SESSION['images']);
- }
- }
-
-
- // if we already searched flickr for this species before, use the previous image rather than doing an unneccesary api call
- $key = array_search($comname_clean, array_column($_SESSION['images'], 0));
- if ($key !== false && !$getAll) {
- $flickr_image_data = $_SESSION['images'][$key];
-
- $foundImage = true;
- //Extract data out of the image data, either in our $_SESSION var already is recently pushed (new data)
- $flickr_data_to_return['photos'][0]['image_url'] = $flickr_image_data[1];
- $flickr_data_to_return['photos'][0]['photo_title'] = $flickr_image_data[2];
- $flickr_data_to_return['photos'][0]['modal_text'] = $flickr_image_data[3];
- $flickr_data_to_return['photos'][0]['author_link'] = $flickr_image_data[4];
- $flickr_data_to_return['photos'][0]['license_url'] = $flickr_image_data[5];
- } else {
- // Get license information if we haven't already
- if (empty($licenses_urls)) {
- $licenses_url = "https://api.flickr.com/services/rest/?method=flickr.photos.licenses.getInfo&api_key=" . $config["FLICKR_API_KEY"] . "&format=json&nojsoncallback=1";
- $licenses_response = file_get_contents($licenses_url);
- $licenses_data = json_decode($licenses_response, true)["licenses"]["license"];
- foreach ($licenses_data as $license) {
- $license_id = $license["id"];
- $license_name = $license["name"];
- $license_url = $license["url"];
- $licenses_urls[$license_id] = $license_url;
- }
- }
-
- // only open the file once per script execution
- if (!isset($lines)) {
- $lines = file($home_dir . "/BirdNET-Pi/model/labels_flickr.txt");
- }
- // convert sci name to English name
- foreach ($lines as $line) {
- if (strpos($line, $detection_data['Sci_Name']) !== false) {
- $sci_name_as_english_name = trim(explode("_", $line)[1]);
- break;
- }
- }
-
- // Read the blacklisted image ids from the file into an array
- $blacklisted_ids = array_map('trim', file($home_dir . "/BirdNET-Pi/scripts/blacklisted_images.txt"));
-
- // Make the API call
- $flickrjson = json_decode(file_get_contents("https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=" . $config["FLICKR_API_KEY"] . "&text=" . str_replace(" ", "%20", $sci_name_as_english_name) . $comnameprefix . "&sort=relevance" . $args . "&per_page=5&media=photos&format=json&nojsoncallback=1"), true)["photos"]["photo"];
-
- // Find the first photo that is not blacklisted or is not the specific blacklisted id
- $photo = null;
- foreach ($flickrjson as $flickrphoto) {
- if ($flickrphoto["id"] !== "4892923285" && !in_array($flickrphoto["id"], $blacklisted_ids)) {
- $photo = $flickrphoto;
-
- $license_url = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=" . $config["FLICKR_API_KEY"] . "&photo_id=" . $photo["id"] . "&format=json&nojsoncallback=1";
- $license_response = file_get_contents($license_url);
- $license_info = json_decode($license_response, true)["photo"]["license"];
- $license_url = $licenses_urls[$license_info];
-
- $modaltext = "https://flickr.com/photos/" . $photo["owner"] . "/" . $photo["id"];
- $authorlink = "https://flickr.com/people/" . $photo["owner"];
- $imageurl = 'https://farm' . $photo["farm"] . '.static.flickr.com/' . $photo["server"] . '/' . $photo["id"] . '_' . $photo["secret"] . '.jpg';
-
- if (!$getAll) {
- //Get single image then break the loop
- array_push($_SESSION['images'], array($comname_clean, $imageurl, $photo["title"], $modaltext, $authorlink, $license_url));
- $flickr_image_data = $_SESSION['images'][count($_SESSION['images']) - 1];
-
- //Extract data out of the image data, either in our $_SESSION var already is recently pushed (new data)
- $flickr_data_to_return['photos'][0]['image_url'] = $flickr_image_data[1];
- $flickr_data_to_return['photos'][0]['photo_title'] = $flickr_image_data[2];
- $flickr_data_to_return['photos'][0]['modal_text'] = $flickr_image_data[3];
- $flickr_data_to_return['photos'][0]['author_link'] = $flickr_image_data[4];
- $flickr_data_to_return['photos'][0]['license_url'] = $flickr_image_data[5];
-
- //Break out of the loop
- break;
- } else {
- //Get all images
- //Extract data out of the image data, either in our $_SESSION var already is recently pushed (new data)
- $flickr_data_to_return['photos'][(int)$flickrphoto["id"]]['image_url'] = $imageurl;
- $flickr_data_to_return['photos'][(int)$flickrphoto["id"]]['photo_title'] = $photo["title"];
- $flickr_data_to_return['photos'][(int)$flickrphoto["id"]]['modal_text'] = $modaltext;
- $flickr_data_to_return['photos'][(int)$flickrphoto["id"]]['author_link'] = $authorlink;
- $flickr_data_to_return['photos'][(int)$flickrphoto["id"]]['license_url'] = $license_url;
- }
- }
- }
-
- $foundImage = true;
- $success = true;
- $message = 'Flickr image data successfully downloaded';
- }
-
- //Fill out all other common data
- $flickr_data_to_return['Com_Name'] = $detection_data['Com_Name'];
- $flickr_data_to_return['Sci_Name'] = $detection_data['Sci_Name'];
- $flickr_data_to_return['Date'] = $detection_data['Date'];
- $flickr_data_to_return['Time'] = $detection_data['Time'];
- $flickr_data_to_return['Confidence'] = array_key_exists('Confidence', $detection_data) ? $detection_data['Confidence'] : 0;
- $flickr_data_to_return['File_Name'] = $detection_data['File_Name'];
-
- $flickr_data_to_return['Com_Name_clean'] = $comname_clean;
- $flickr_data_to_return['Sci_Name_clean'] = $sciname_clean;
-
- $flickr_data_to_return['filename_path'] = $filename_path;
- $flickr_data_to_return['filename_formatted'] = $filename_formatted;
- }
- }
-
- return array('success' => $success, 'message' => $message, 'image_found' => $foundImage, 'data' => $flickr_data_to_return);
-}
-
-
-/**
- * Returns the filename of todays species chart for the main page
- *
- * @return string
- */
-function getChartString()
-{
- $myDate = date('Y-m-d');
- $chart = "Combo-$myDate.png";
- return $chart;
-}
-
-/**
- * Returns the start and end dates for last week
- *
- * @return string[]
- */
-function getLastWeekDates()
-{
- $startdate = strtotime('last sunday') - (7 * 86400);
- $enddate = strtotime('last sunday') - (1 * 86400);
-
- 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("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;
-}
-
-/**
- * Loads in the JSON file containing data on directory and file paths
- *
- * @return array
- */
-function loadFilePathMap()
-{
- global $filePathMap_data, $filePathMap_json_path;
- if (empty($filePathMap_data)) {
- $filePathMap_data = json_decode(file_get_contents($filePathMap_json_path), true);
- }
- return $filePathMap_data;
-}
-
-/**
- * Directory Path Helper, returns a full directory path for a supplied directory name e.g home, processed, extracted
- *
- * @param string $dir The directory to obtain a path for
- * @return string
- */
-function getDirectory($dir)
-{
- global $config, $home;
- $dir = strtolower($dir);
-
- $filePathMap_directories = loadFilePathMap()['directories'];
-
- if (array_key_exists($dir, $filePathMap_directories)) {
- $filePathMap_directories_selected = $filePathMap_directories[$dir];
-
- //Check to see if directory is an alias for another
- $dir_alias = $filePathMap_directories_selected['alias_for'] ?? '';
- if (!empty($dir_alias)) {
- //If so load in the data for that directory
- $filePathMap_directories_selected = $filePathMap_directories[$dir_alias];
- }
-
- //Gather all the options into variables
- $setting_value = $filePathMap_directories_selected['read_setting'] ?? '';
- $lives_under = $filePathMap_directories_selected['lives_under'] ?? '';
- $replace_text = $filePathMap_directories_selected['replace_setting_text'] ?? '';
- $replace_text_with = $filePathMap_directories_selected['replace_setting_text_with'] ?? '';
- $append = $filePathMap_directories_selected['append'] ?? '';
- $return_var = $filePathMap_directories_selected['return_var'] ?? '';
- //
- $return_value = $under_directory = '';
-
- //Get the directory which the directory we're processing lives under
- if (!empty($lives_under)) {
- $under_directory = getDirectory($lives_under);
- }
-
- //Read the specified config file setting
- if (!empty($setting_value)) {
- $setting_value = $config[$setting_value];
- }
-
- //Replace value in setting, like ${RECS_DIR} etc as they are not expanded
- if (!empty($replace_text)) {
- $return_value = str_replace($replace_text, $replace_text_with, $setting_value);
- } else {
- $return_value = $setting_value;
- }
-
- //If a variable is specified for return, return it first
- if (!empty($return_var)) {
- //return the dynamic variable, currently this is just the users home path in $home
- return ${"{$return_var}"};
- } else if (!empty($append)) {
- //Append this to the end of the path, (models, scripts etc) do this as they reside under BirdNET-pi
- return $under_directory . $append;
- } else {
- //Else return the directory and result of the setting manipulation
- return $under_directory . $return_value;
- }
- }
-
- return "";
-}
-
-/**
- * Returns the full filepath for the specified filename
- *
- * @param $filename
- * @return string
- */
-function getFilePath($filename)
-{
- global $config;
-
- $filePathMap_files = loadFilePathMap()['files'];
-
- if (array_key_exists($filename, $filePathMap_files)) {
- $filePathMap_directories_selected = $filePathMap_files[$filename];
-
- //Gather all the options into variables
- $setting_value = $filePathMap_directories_selected['read_setting'] ?? '';
- $lives_under = $filePathMap_directories_selected['lives_under'] ?? '';
- $replace_text = $filePathMap_directories_selected['replace_setting_text'] ?? '';
- $replace_test_with = $filePathMap_directories_selected['replace_setting_text_with'] ?? '';
- $append = $filePathMap_directories_selected['append'] ?? '';
- $return_val = $filePathMap_directories_selected['return_var'] ?? '';
- //
- $under_directory = '';
-
- //Get the directory which the directory we're processing lives under
- if (!empty($lives_under)) {
- $under_directory = getDirectory($lives_under);
- }
-
- //Read the specified config file setting if any
- if (!empty($setting_value)) {
- $setting_value = $config[$setting_value];
- }
-
- //Replace value in setting, like ${RECS_DIR} etc as they are not expanded
- if (!empty($replace_text)) {
- $return_value = str_replace($replace_text, $replace_test_with, $setting_value);
- } else {
- $return_value = $setting_value;
- }
-
- //If a variable is specified for return, return it first and directly
- if (!empty($return_val)) {
- //return the dynamic variable, currently this is just the users home path in $home
- return $return_val;
- } else if (!empty($append)) {
- //Append this to the end of the path, (models, scripts etc) do this as they reside under BirdNET-pi
- return $under_directory . $append;
- } else {
- //Else return the directory and result of the setting manipulation
- return $under_directory . $return_value;
- }
- }
-
- 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 saveSetting($setting_name, $setting_value, $post_save_command = null)
-{
- global $config;
-
- //Check authentication before going any further
- //the front end would have done this check already and such should pass
- authenticateUser();
-
- //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;
-
- //Check authentication before going any further
- //the front end would have done this check already and such should pass
- authenticateUser();
-
- $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 '" . escapeshellcmd($extra_data_to_pass['date']) . " " . escapeshellcmd($extra_data_to_pass['time']) . "'";
- $result = shell_exec($command);
- //
- } else if ($command_type == "set_timezone") {
- $command = "sudo timedatectl set-timezone " . escapeshellcmd($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_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;
-}
-
-/**
- * Updates the caddy configuration, only ever called when BirdNET-Pi Password or Site URL is set
- *
- * @return void
- */
-function update_caddyfile()
-{
- exec("sudo /usr/local/bin/update_caddyfile.sh > /dev/null 2>&1 &");
-}
-
-/**
- * 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 = "";
-
- //Check authentication before going any further
- //the front end would have done this check already and such should pass
- authenticateUser();
-
- ///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
- * @link 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)
-{
- $output = "";
- //Check authentication before going any further
- //the front end would have done this check already and such should pass
- authenticateUser();
-
- 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 thisrun 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_config_file = fopen(getFilePath("apprise.txt"), "w");
- fwrite($appriseconfig_config_file, $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];
-}
-
-/**
- * Returns the boolean flag
- * @return false
- */
-function userIsAuthenticated()
-{
- global $USER_AUTHENTICATED;
- return $USER_AUTHENTICATED;
-}
-
-/**
- * When called, authenticates the user using the built-in PHP_AUTH. This is the orignial authentication code just wrapped in a function
- * This will automatically terminate the script if authentication fails
- *
- * @param $rejection_message string Message to return to the user if authentication fails
- * @return bool
- */
-function authenticateUser($rejection_message = "You cannot edit the settings for this installation")
-{
- global $config, $USER_AUTHENTICATED;
- parseConfig();
- $USER_AUTHENTICATED = false;
-
- $caddypwd = $config['CADDY_PWD'];
- if (!isset($_SERVER['PHP_AUTH_USER'])) {
- header('WWW-Authenticate: Basic realm="BirdNET-Pi"');
- header('HTTP/1.0 401 Unauthorized');
- echo '<table><tr><td>' . $rejection_message . '</td></tr></table>';
- exit;
- } else {
- //Read the supplied details
- $submittedpwd = $_SERVER['PHP_AUTH_PW'];
- $submitteduser = $_SERVER['PHP_AUTH_USER'];
- //
- if ($submittedpwd !== $caddypwd || $submitteduser !== 'birdnet') {
- header('WWW-Authenticate: Basic realm="BirdNET-Pi"');
- header('HTTP/1.0 401 Unauthorized');
- echo '<table><tr><td>' . $rejection_message . '</td></tr></table>';
- exit;
- } else {
- $USER_AUTHENTICATED = true;
- }
- }
-
- return $USER_AUTHENTICATED;
-}
-
-/**
- * Logging helper to accept a message and process it accordingly
- * @param $message
- * @param $level
- * @return void
- */
-function birdnet_error_log($message, $level = 'error')
-{
- $logfile_path = getDirectory('scripts') . "/web-ui-error.log";
-
- if (!file_exists($logfile_path)) {
- touch($logfile_path);
- }
-
- error_log($message . "\r\n", 3, $logfile_path);
-}
-
-
-register_shutdown_function('disconnect_from_birdsdb');
\ No newline at end of file
diff --git a/scripts/config.php b/scripts/config.php
index 6086f392..ceb5e0aa 100644
--- a/scripts/config.php
+++ b/scripts/config.php
@@ -1,19 +1,47 @@
<?php
-if (file_exists('./scripts/common.php')) {
- include_once "./scripts/common.php";
+error_reporting(E_ERROR);
+ini_set('display_errors',1);
+
+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 {
- include_once "./common.php";
+ $apprise_config = "";
+}
+$caddypwd = $config['CADDY_PWD'];
+if (!isset($_SERVER['PHP_AUTH_USER'])) {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo '<table><tr><td>You cannot edit the settings for this installation</td></tr></table>';
+ exit;
+} else {
+ $submittedpwd = $_SERVER['PHP_AUTH_PW'];
+ $submitteduser = $_SERVER['PHP_AUTH_USER'];
+ if($submittedpwd !== $caddypwd || $submitteduser !== 'birdnet'){
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo '<table><tr><td>You cannot edit the settings for this installation</td></tr></table>';
+ exit;
+ }
}
-//Parse the ini files to get the current config
-parseConfig();
-
-//Authenticate first before allowing further execution
-authenticateUser();
+function syslog_shell_exec($cmd, $sudo_user = null) {
+ if ($sudo_user) {
+ $cmd = "sudo -u $sudo_user $cmd";
+ }
+ $output = shell_exec($cmd);
-//Authenticated
-//Read in the apprise config
-$apprise_config = getAppriseConfig();
+ if (strlen($output) > 0) {
+ syslog(LOG_INFO, $output);
+ }
+}
if(isset($_GET['threshold'])) {
$threshold = $_GET['threshold'];
@@ -21,12 +49,19 @@ if(isset($_GET['threshold'])) {
die('Invalid threshold value');
}
- echo executeSysCommand('test_threshold', $threshold);
+ $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;
die();
}
if(isset($_GET['restart_php']) && $_GET['restart_php'] == "true") {
- executeSysCommand('restart_php');
+ shell_exec("sudo service php7.4-fpm restart");
die();
}
@@ -73,7 +108,7 @@ if(isset($_GET["latitude"])){
}
if(isset($timezone) && in_array($timezone, DateTimeZone::listIdentifiers())) {
- executeSysCommand('set_timezone',$timezone);
+ shell_exec("sudo timedatectl set-timezone ".$timezone);
date_default_timezone_set($timezone);
echo "<script>setTimeout(
function() {
@@ -86,43 +121,88 @@ if(isset($_GET["latitude"])){
// logic for setting the date and time based on user inputs from the form below
if(isset($_GET['date']) && isset($_GET['time'])) {
// can't set the date manually if it's getting it from the internet, disable ntp
- executeSysCommand('disable_ntp');
+ exec("sudo timedatectl set-ntp false");
// 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']) {
- executeSysCommand('set_date', ['date' => $_GET['date'], 'time' => $_GET['time']]);
+ exec("sudo date -s '".$_GET['date']." ".$_GET['time']."'");
}
} else {
// user checked 'use time from internet if available,' so make sure that's on
- if(strlen(trim(executeSysCommand('is_ntp_active'))) == 0){
- executeSysCommand('enable_ntp');
- sleep(3);
+ if(strlen(trim(exec("sudo timedatectl | grep \"NTP service: active\""))) == 0){
+ exec("sudo timedatectl set-ntp true");
+ 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("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);
-
- saveSetting('SITE_NAME', "\"$site_name\"");
- saveSetting('LATITUDE', $latitude);
- saveSetting('LONGITUDE', $longitude);
- saveSetting('BIRDWEATHER_ID', $birdweather_id);
- saveSetting('APPRISE_NOTIFICATION_TITLE', "\"$apprise_notification_title\"");
- saveSetting('APPRISE_NOTIFICATION_BODY', "'$apprise_notification_body'");
- saveSetting('APPRISE_NOTIFY_EACH_DETECTION', $apprise_notify_each_detection);
- saveSetting('APPRISE_NOTIFY_NEW_SPECIES', $apprise_notify_new_species);
- saveSetting('APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY', $apprise_notify_new_species_each_day);
- saveSetting('APPRISE_WEEKLY_REPORT', $apprise_weekly_report);
- saveSetting('FLICKR_API_KEY', $flickr_api_key);
- saveSetting('DATABASE_LANG', $language);
- saveSetting('FLICKR_FILTER_EMAIL', $flickr_filter_email);
- saveSetting('APPRISE_MINIMUM_SECONDS_BETWEEN_NOTIFICATIONS_PER_SPECIES', $minimum_time_limit);
- saveSetting('MODEL', $model);
- saveSetting('SF_THRESH', $sf_thresh);
- saveSetting('APPRISE_ONLY_NOTIFY_SPECIES_NAMES', "\"$only_notify_species_names\"");
- saveSetting('APPRISE_ONLY_NOTIFY_SPECIES_NAMES_2', "\"$only_notify_species_names_2\"");
if($site_name != $config["SITE_NAME"]) {
@@ -132,17 +212,43 @@ if(isset($_GET["latitude"])){
}, 1000);</script>";
}
- updateAppriseConfig($apprise_input);
+ $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);
- serviceMaintenance('restart core.services');
+ $appriseconfig = fopen($home."/BirdNET-Pi/apprise.txt", "w");
+ fwrite($appriseconfig, $apprise_input);
+ }
+
+ syslog(LOG_INFO, "Restarting Services");
+ shell_exec("sudo restart_services.sh");
}
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)."'";
- $result0 = getMostRecentDetectionToday();
- foreach ($result0['data'] as $todaytable)
+ $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))
{
$sciname = $todaytable['Sci_Name'];
$comname = $todaytable['Com_Name'];
@@ -204,7 +310,7 @@ if(isset($_GET['sendtest']) && $_GET['sendtest'] == "true") {
$body = str_replace("\$overlap", $overlap, $body);
$body = str_replace("\$flickrimage", $exampleimage, $body);
- echo "<pre class=\"bash\">" . executeSysCommand('appraise_notification', ['title' => $title, 'body' => $body, 'attach' => $attach, 'cf' => $cf]) . "</pre>";
+ 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>";
die();
}
@@ -218,10 +324,11 @@ if(isset($_GET['sendtest']) && $_GET['sendtest'] == "true") {
<div class="brbanner"><h1>Basic Settings</h1></div><br>
<form id="basicform" action="" method="GET">
+
<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";
@@ -237,13 +344,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 asynchronous
xmlHttp.send(null);
}
</script>
@@ -253,6 +360,7 @@ 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){
@@ -432,13 +540,13 @@ https://discordapp.com/api/webhooks/{WebhookID}/{WebhookToken}
<input name="apprise_notification_title" type="text" value="<?php print($config['APPRISE_NOTIFICATION_TITLE']);?>" /><br>
<label for="apprise_notification_body">Notification Body: </label>
<input name="apprise_notification_body" type="text" value='<?php print($config['APPRISE_NOTIFICATION_BODY']);?>' /><br>
- <input type="checkbox" name="apprise_notify_new_species" <?php if($config['APPRISE_NOTIFY_NEW_SPECIES'] == 1 && filesize(getFilePath('apprise.txt')) != 0) { echo "checked"; };?> >
+ <input type="checkbox" name="apprise_notify_new_species" <?php if($config['APPRISE_NOTIFY_NEW_SPECIES'] == 1 && filesize($home."/BirdNET-Pi/apprise.txt") != 0) { echo "checked"; };?> >
<label for="apprise_notify_new_species">Notify each new infrequent species detection (<5 visits per week)</label><br>
- <input type="checkbox" name="apprise_notify_new_species_each_day" <?php if($config['APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY'] == 1 && filesize(getFilePath('apprise.txt')) != 0) { echo "checked"; };?> >
+ <input type="checkbox" name="apprise_notify_new_species_each_day" <?php if($config['APPRISE_NOTIFY_NEW_SPECIES_EACH_DAY'] == 1 && filesize($home."/BirdNET-Pi/apprise.txt") != 0) { echo "checked"; };?> >
<label for="apprise_notify_new_species_each_day">Notify each species first detection of the day</label><br>
- <input type="checkbox" name="apprise_notify_each_detection" <?php if($config['APPRISE_NOTIFY_EACH_DETECTION'] == 1 && filesize(getFilePath('apprise.txt')) != 0) { echo "checked"; };?> >
+ <input type="checkbox" name="apprise_notify_each_detection" <?php if($config['APPRISE_NOTIFY_EACH_DETECTION'] == 1 && filesize($home."/BirdNET-Pi/apprise.txt") != 0) { echo "checked"; };?> >
<label for="apprise_weekly_report">Notify each new detection</label><br>
- <input type="checkbox" name="apprise_weekly_report" <?php if($config['APPRISE_WEEKLY_REPORT'] == 1 && filesize(getFilePath('apprise.txt')) != 0) { echo "checked"; };?> >
+ <input type="checkbox" name="apprise_weekly_report" <?php if($config['APPRISE_WEEKLY_REPORT'] == 1 && filesize($home."/BirdNET-Pi/apprise.txt") != 0) { echo "checked"; };?> >
<label for="apprise_weekly_report">Send <a href="views.php?view=Weekly%20Report"> weekly report</a></label><br>
<hr>
@@ -467,6 +575,39 @@ 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 language
foreach($langs as $langTag => $langName){
$isSelected = "";
@@ -497,7 +638,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(executeSysCommand('is_ntp_active'));
+ $tdc = trim(exec("sudo timedatectl | grep \"NTP service: active\""));
if (strlen($tdc) > 0) {
$checkedvalue = "checked";
$disabledvalue = "disabled";
@@ -522,7 +663,7 @@ https://discordapp.com/api/webhooks/{WebhookID}/{WebhookToken}
Select a timezone
</option>
<?php
- $current_timezone = trim(executeSysCommand('current_timezone'));
+ $current_timezone = trim(shell_exec("cat /etc/timezone"));
$timezone_identifiers = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
$n = 425;
diff --git a/scripts/exclude_list.php b/scripts/exclude_list.php
index a4f7d7d9..d8d90f47 100644
--- a/scripts/exclude_list.php
+++ b/scripts/exclude_list.php
@@ -12,7 +12,10 @@
<select name="species[]" id="species" multiple size="auto">
<option>Choose a species below to add to the Excluded Species List</option>
<?php
- $filename = getFilePath('labels.txt');
+ error_reporting(E_ALL);
+ ini_set('display_errors',1);
+
+ $filename = './scripts/labels.txt';
$eachline = file($filename, FILE_IGNORE_NEW_LINES);
foreach($eachline as $lines){echo
@@ -40,7 +43,7 @@
<br><br>
<select name="species[]" id="value2" multiple size="auto">
<?php
- $filename = getFilePath('exclude_species_list.txt');
+ $filename = './scripts/exclude_species_list.txt';
$eachline = file($filename, FILE_IGNORE_NEW_LINES);
foreach($eachline as $lines){
echo
diff --git a/scripts/history.php b/scripts/history.php
index b59b870a..a37cbe0f 100644
--- a/scripts/history.php
+++ b/scripts/history.php
@@ -1,8 +1,12 @@
<?php
-if(file_exists('./scripts/common.php')){
- include_once "./scripts/common.php";
-}else{
- include_once "./common.php";
+error_reporting(E_ALL);
+ini_set('display_errors',1);
+ini_set('display_startup_errors',1);
+
+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');
}
if(isset($_GET['date'])){
@@ -13,11 +17,12 @@ $theDate = date('Y-m-d');
$chart = "Combo-$theDate.png";
$chart2 = "Combo2-$theDate.png";
-$statement1 = getDetectionCountByDate($theDate);
-if($statement1['success'] == False){
- echo $statement1['message'];
- header("refresh: 0;");
-}
+$db = new SQLite3('./scripts/birds.db', SQLITE3_OPEN_CREATE | SQLITE3_OPEN_READWRITE);
+
+$statement1 = $db->prepare("SELECT COUNT(*) FROM detections
+ WHERE Date == \"$theDate\"");
+$result1 = $statement1->execute();
+$totalcount = $result1->fetchArray(SQLITE3_ASSOC);
if(isset($_GET['blocation']) ) {
@@ -27,6 +32,10 @@ if(isset($_GET['blocation']) ) {
header("Expires: 0");
+ $user = trim(shell_exec("awk -F: '/1000/{print $1}' /etc/passwd"));
+ $home = trim(shell_exec("awk -F: '/1000/{print $6}' /etc/passwd"));
+
+
//$sunrise = date_sunrise(time(), SUNFUNCS_RET_TIMESTAMP, $config["LATITUDE"], $config["LONGITUDE"]);
//$sunset = date_sunset(time(), SUNFUNCS_RET_TIMESTAMP, $config["LATITUDE"], $config["LONGITUDE"]);
@@ -36,17 +45,16 @@ if(isset($_GET['blocation']) ) {
$hrsinday = 24;
for($i=0;$i<$hrsinday;$i++) {
$starttime = strtotime("12 AM") + (3600*$i);
- $endtime = date("H:i",$starttime + 3600);
- $statement1 = getDetectionBreakdownByTime($theDate,$starttime,$endtime);
- if($statement1['success'] == False){
- echo $statement1['message'];
- header("refresh: 0;");
+ $statement1 = $db->prepare("SELECT DISTINCT(Com_Name), COUNT(*) FROM detections WHERE Date == \"$theDate\" AND Time > '".date("H:i", $starttime)."' AND Time < '".date("H:i",$starttime + 3600)."' AND Confidence > 0.75 GROUP By Com_Name ORDER BY COUNT(*) DESC");
+ if($statement1 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
- $result1 = $statement1['data'];
+ $result1 = $statement1->execute();
$detections = [];
- foreach ($result1 as $detection)
+ while($detection=$result1->fetchArray(SQLITE3_ASSOC))
{
$detections[$detection["Com_Name"]] = $detection["COUNT(*)"];
}
diff --git a/scripts/include_list.php b/scripts/include_list.php
index ac789901..ad663be5 100644
--- a/scripts/include_list.php
+++ b/scripts/include_list.php
@@ -3,7 +3,10 @@
</style>
<?php
-$filename = getFilePath('labels.txt');
+error_reporting(E_ALL);
+ini_set('display_errors',1);
+
+$filename = './scripts/labels.txt';
$eachlines = file($filename, FILE_IGNORE_NEW_LINES);
?>
@@ -44,7 +47,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 = getFilePath('include_species_list.txt');
+ $filename = './scripts/include_species_list.txt';
$eachlines = file($filename, FILE_IGNORE_NEW_LINES);
foreach($eachlines as $lines){echo
"<option value=\"".$lines."\">$lines</option>";}
diff --git a/scripts/overview.php b/scripts/overview.php
index 526e4ca1..2f55b528 100644
--- a/scripts/overview.php
+++ b/scripts/overview.php
@@ -1,20 +1,36 @@
<?php
-if(file_exists('./scripts/common.php')){
- include_once "./scripts/common.php";
-}else{
- include_once "./common.php";
-}
-
+error_reporting(E_ERROR);
+ini_set('display_errors',1);
+ini_set('session.gc_maxlifetime', 7200);
+ini_set('user_agent', 'PHP_Flickr/1.0');
+session_set_cookie_params(7200);
+session_start();
$myDate = date('Y-m-d');
$chart = "Combo-$myDate.png";
-$todaycount_data = getDetectionCountToday();
+$db = new SQLite3('./scripts/birds.db', SQLITE3_OPEN_CREATE | SQLITE3_OPEN_READWRITE);
+if($db == False) {
+ echo "Database is busy";
+ header("refresh: 0;");
+}
+
+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($todaycount_data['success'] == False){
- echo $todaycount_data['message'];
- header("refresh: 0;");
+$statement2 = $db->prepare('SELECT COUNT(*) FROM detections WHERE Date == DATE(\'now\', \'localtime\')');
+if($statement2 == False) {
+ echo "Database is busy";
+ header("refresh: 0;");
}
-$todaycount = $todaycount_data['data'];
+$result2 = $statement2->execute();
+$todaycount = $result2->fetchArray(SQLITE3_ASSOC);
if(isset($_GET['custom_image'])){
if(isset($config["CUSTOM_IMAGE"])) {
@@ -31,69 +47,143 @@ if(isset($_GET['custom_image'])){
}
if(isset($_GET['blacklistimage'])) {
- $user_is_authenticated = authenticateUser('You cannot modify the system');
- if($user_is_authenticated){
- $imageid = $_GET['blacklistimage'];
- $result = blacklistFlickrImage($imageid);
- unset($_SESSION['images']);
- die($result['message']);
+ if(isset($_SERVER['PHP_AUTH_USER'])) {
+ $submittedpwd = $_SERVER['PHP_AUTH_PW'];
+ $submitteduser = $_SERVER['PHP_AUTH_USER'];
+ if($submittedpwd == $config['CADDY_PWD'] && $submitteduser == 'birdnet'){
+
+ $imageid = $_GET['blacklistimage'];
+ $file_handle = fopen($home."/BirdNET-Pi/scripts/blacklisted_images.txt", 'a+');
+ fwrite($file_handle, $imageid . "\n");
+ fclose($file_handle);
+ unset($_SESSION['images']);
+ die("OK");
+ } else {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo 'You must be authenticated.';
+ exit;
}
+ } else {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo 'You must be authenticated.';
+ exit;
+ }
+
}
if(isset($_GET['fetch_chart_string']) && $_GET['fetch_chart_string'] == "true") {
- $chart = getChartString();
+ $myDate = date('Y-m-d');
+ $chart = "Combo-$myDate.png";
echo $chart;
die();
}
if(isset($_GET['ajax_detections']) && $_GET['ajax_detections'] == "true" && isset($_GET['previous_detection_identifier'])) {
- $result4 = getMostRecentDetection(15);
-
- if ($result4['success'] == False) {
- echo $result4['message'];
- header("refresh: 0;");
- }
- $result4 = $result4['data'];
-
- $iterations = 0;
- $processed_detections = 0;
-
+ $statement4 = $db->prepare('SELECT Com_Name, Sci_Name, Date, Time, Confidence, File_Name FROM detections ORDER BY Date DESC, Time DESC LIMIT 15');
+ if($statement4 == False) {
+ echo "Database is busy";
+ header("refresh: 0;");
+ }
+ $result4 = $statement4->execute();
+ if(!isset($_SESSION['images'])) {
+ $_SESSION['images'] = [];
+ }
+ $iterations = 0;
+ $lines;
+ $licenses_urls = array();
// hopefully one of the 5 most recent detections has an image that is valid, we'll use that one as the most recent detection until the newer ones get their images created
- foreach ($result4 as $mostrecent){
- $iterations++;
- $comname = preg_replace('/ /', '_', $mostrecent['Com_Name']);
+ while($mostrecent = $result4->fetchArray(SQLITE3_ASSOC)) {
+ $comname = preg_replace('/ /', '_', $mostrecent['Com_Name']);
$sciname = preg_replace('/ /', '_', $mostrecent['Sci_Name']);
$comname = preg_replace('/\'/', '', $comname);
$filename = "/By_Date/".$mostrecent['Date']."/".$comname."/".$mostrecent['File_Name'];
- // check to make sure the image actually exists, sometimes it takes a minute to be created\
- if (file_exists(getDirectory('extracted') . "/" . $filename . ".png")) {
- if ($_GET['previous_detection_identifier'] == $filename) {
- die();
- }
- if ($_GET['only_name'] == "true") {
- echo $comname . "," . $filename;
- die();
- }
- //Because the spectrogram image exists for this detection it's been processed
- $processed_detections++;
-
- //Get the flickr image for this detection
- $flickr_Image = getFlickrImage($mostrecent);
-
- if ($flickr_Image['image_found']) {
- //Remap the data from returned data into an array that is referenced in our HTML
- //to save have to rewrite or adjust it
- $flickr_Image_data = $flickr_Image['data'];
- $image = [
- 0 => $flickr_Image_data['Com_Name_clean'],
- 1 => $flickr_Image_data['photos'][0]['image_url'],
- 2 => $flickr_Image_data['photos'][0]['photo_title'],
- 3 => $flickr_Image_data['photos'][0]['modal_text'],
- 4 => $flickr_Image_data['photos'][0]['author_link'],
- 5 => $flickr_Image_data['photos'][0]['license_url']
- ];
- }
+ $args = "&license=2%2C3%2C4%2C5%2C6%2C9&orientation=square,portrait";
+ $comnameprefix = "%20bird";
+
+ // check to make sure the image actually exists, sometimes it takes a minute to be created\
+ if(file_exists($home."/BirdSongs/Extracted".$filename.".png")){
+ if($_GET['previous_detection_identifier'] == $filename) { die(); }
+ if($_GET['only_name'] == "true") { echo $comname.",".$filename;die(); }
+
+ $iterations++;
+
+ if (!empty($config["FLICKR_API_KEY"])) {
+
+ if(!empty($config["FLICKR_FILTER_EMAIL"])) {
+ if(!isset($_SESSION["FLICKR_FILTER_EMAIL"])) {
+ unset($_SESSION['images']);
+ $_SESSION['FLICKR_FILTER_EMAIL'] = json_decode(file_get_contents("https://www.flickr.com/services/rest/?method=flickr.people.findByEmail&api_key=".$config["FLICKR_API_KEY"]."&find_email=".$config["FLICKR_FILTER_EMAIL"]."&format=json&nojsoncallback=1"), true)["user"]["nsid"];
+ }
+ $args = "&user_id=".$_SESSION['FLICKR_FILTER_EMAIL'];
+ $comnameprefix = "";
+ } else {
+ if(isset($_SESSION["FLICKR_FILTER_EMAIL"])) {
+ unset($_SESSION["FLICKR_FILTER_EMAIL"]);
+ unset($_SESSION['images']);
+ }
+ }
+
+
+ // if we already searched flickr for this species before, use the previous image rather than doing an unneccesary api call
+ $key = array_search($comname, array_column($_SESSION['images'], 0));
+ if($key !== false) {
+ $image = $_SESSION['images'][$key];
+ } else {
+ // Get license information if we haven't already
+ if (empty($licenses_urls)) {
+ $licenses_url = "https://api.flickr.com/services/rest/?method=flickr.photos.licenses.getInfo&api_key=".$config["FLICKR_API_KEY"]."&format=json&nojsoncallback=1";
+ $licenses_response = file_get_contents($licenses_url);
+ $licenses_data = json_decode($licenses_response, true)["licenses"]["license"];
+ foreach ($licenses_data as $license) {
+ $license_id = $license["id"];
+ $license_name = $license["name"];
+ $license_url = $license["url"];
+ $licenses_urls[$license_id] = $license_url;
+ }
+ }
+
+ // only open the file once per script execution
+ if(!isset($lines)) {
+ $lines = file($home."/BirdNET-Pi/model/labels_flickr.txt");
+ }
+ // convert sci name to English name
+ foreach($lines as $line){
+ if(strpos($line, $mostrecent['Sci_Name']) !== false){
+ $engname = trim(explode("_", $line)[1]);
+ break;
+ }
+ }
+
+ // Read the blacklisted image ids from the file into an array
+ $blacklisted_ids = array_map('trim', file($home."/BirdNET-Pi/scripts/blacklisted_images.txt"));
+
+ // Make the API call
+ $flickrjson = json_decode(file_get_contents("https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=".$config["FLICKR_API_KEY"]."&text=".str_replace(" ", "%20", $engname).$comnameprefix."&sort=relevance".$args."&per_page=5&media=photos&format=json&nojsoncallback=1"), true)["photos"]["photo"];
+
+ // Find the first photo that is not blacklisted or is not the specific blacklisted id
+ $photo = null;
+ foreach ($flickrjson as $flickrphoto) {
+ if ($flickrphoto["id"] !== "4892923285" && !in_array($flickrphoto["id"], $blacklisted_ids)) {
+ $photo = $flickrphoto;
+ break;
+ }
+ }
+
+ $license_url = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=".$config["FLICKR_API_KEY"]."&photo_id=".$photo["id"]."&format=json&nojsoncallback=1";
+ $license_response = file_get_contents($license_url);
+ $license_info = json_decode($license_response, true)["photo"]["license"];
+ $license_url = $licenses_urls[$license_info];
+
+ $modaltext = "https://flickr.com/photos/".$photo["owner"]."/".$photo["id"];
+ $authorlink = "https://flickr.com/people/".$photo["owner"];
+ $imageurl = 'https://farm' .$photo["farm"]. '.static.flickr.com/' .$photo["server"]. '/' .$photo["id"]. '_' .$photo["secret"]. '.jpg';
+ array_push($_SESSION['images'], array($comname,$imageurl,$photo["title"], $modaltext, $authorlink, $license_url));
+ $image = $_SESSION['images'][count($_SESSION['images'])-1];
+ }
+ }
?>
<style>
@@ -133,48 +223,49 @@ if(isset($_GET['ajax_detections']) && $_GET['ajax_detections'] == "true" && isse
</table> <?php break;
}
}
+ if($iterations == 0) {
if($todaycount['COUNT(*)'] > 0) {
- if($processed_detections == 0) {
- echo "<h3>Your system is currently processing a backlog of audio. This can take several hours before normal functionality of your BirdNET-Pi resumes.</h3>";
- }
+ echo "<h3>Your system is currently processing a backlog of audio. This can take several hours before normal functionality of your BirdNET-Pi resumes.</h3>";
} else {
echo "<h3>No Detections For Today.</h3>";
}
+ }
die();
}
if(isset($_GET['ajax_left_chart']) && $_GET['ajax_left_chart'] == "true") {
- $totalcount_data = getDetectionCountAll();
- if($totalcount_data['success'] == False){
- echo $totalcount_data['message'];
- header("refresh: 0;");
- }
- $totalcount = $totalcount_data['data'];
-
-
- $hourcount_data = getDetectionCountLastHour();
- if($hourcount_data['success'] == False){
- echo $hourcount_data['message'];
- header("refresh: 0;");
- }
- $hourcount = $hourcount_data['data'];
-
+$statement = $db->prepare('SELECT COUNT(*) FROM detections');
+if($statement == False) {
+ echo "Database is busy";
+ header("refresh: 0;");
+}
+$result = $statement->execute();
+$totalcount = $result->fetchArray(SQLITE3_ASSOC);
- $speciestally_data = getSpeciesTalley();
- if($speciestally_data['success'] == False){
- echo $speciestally_data['message'];
- header("refresh: 0;");
- }
- $speciestally = $speciestally_data['data'];
+$statement3 = $db->prepare('SELECT COUNT(*) FROM detections WHERE Date == Date(\'now\', \'localtime\') AND TIME >= TIME(\'now\', \'localtime\', \'-1 hour\')');
+if($statement3 == False) {
+ echo "Database is busy";
+ header("refresh: 0;");
+}
+$result3 = $statement3->execute();
+$hourcount = $result3->fetchArray(SQLITE3_ASSOC);
+$statement5 = $db->prepare('SELECT COUNT(DISTINCT(Com_Name)) FROM detections WHERE Date == Date(\'now\',\'localtime\')');
+if($statement5 == False) {
+ echo "Database is busy";
+ header("refresh: 0;");
+}
+$result5 = $statement5->execute();
+$speciestally = $result5->fetchArray(SQLITE3_ASSOC);
- $totalspeciestally_data = getAllSpeciesTalley();
- if($totalspeciestally_data['success'] == False){
- echo $totalspeciestally_data['message'];
- header("refresh: 0;");
- }
- $totalspeciestally = $totalspeciestally_data['data'];
+$statement6 = $db->prepare('SELECT COUNT(DISTINCT(Com_Name)) FROM detections');
+if($statement6 == False) {
+ echo "Database is busy";
+ header("refresh: 0;");
+}
+$result6 = $statement6->execute();
+$totalspeciestally = $result6->fetchArray(SQLITE3_ASSOC);
?>
<table>
diff --git a/scripts/play.php b/scripts/play.php
index b25e0bc2..0d3bb340 100644
--- a/scripts/play.php
+++ b/scripts/play.php
@@ -1,63 +1,168 @@
<?php
-if(file_exists('./scripts/common.php')){
- include_once "./scripts/common.php";
-}else{
- include_once "./common.php";
+error_reporting(E_ERROR);
+ini_set('display_errors',1);
+
+$db = new SQLite3('./scripts/birds.db', SQLITE3_OPEN_CREATE | SQLITE3_OPEN_READWRITE);
+if($db == False){
+ echo "Database is busy";
+ header("refresh: 0;");
+}
+
+if (file_exists('./scripts/thisrun.txt')) {
+ $config = parse_ini_file('./scripts/thisrun.txt');
+} elseif (file_exists('firstrun.ini')) {
+ $config = parse_ini_file('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(isset($_GET['deletefile'])) {
- $user_is_authenticated = authenticateUser('You must be authenticated to change the protection of files.');
- if ($user_is_authenticated) {
- $filename_to_delete = $_GET['deletefile'];
- $message = deleteDetection($filename_to_delete)['message'];
- echo $message;
- die();
- }
+ if(isset($_SERVER['PHP_AUTH_USER'])) {
+ $submittedpwd = $_SERVER['PHP_AUTH_PW'];
+ $submitteduser = $_SERVER['PHP_AUTH_USER'];
+ if($submittedpwd == $config['CADDY_PWD'] && $submitteduser == 'birdnet'){
+ $statement1 = $db->prepare('DELETE FROM detections WHERE File_Name = "'.explode("/",$_GET['deletefile'])[2].'" LIMIT 1');
+ if($statement1 == False){
+ echo "Error";
+ header("refresh: 0;");
+ } else {
+ $file_pointer = $home."/BirdSongs/Extracted/By_Date/".$_GET['deletefile'];
+ if (!exec("sudo rm $file_pointer && sudo rm $file_pointer.png")) {
+ echo "OK";
+ } else {
+ echo "Error";
+ }
+
+ }
+ $result1 = $statement1->execute();
+ die();
+ } else {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo 'You must be authenticated to change the protection of files.';
+ exit;
+ }
+ } else {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo 'You must be authenticated to change the protection of files.';
+ exit;
+ }
}
if(isset($_GET['excludefile'])) {
- $user_is_authenticated = authenticateUser('You must be authenticated to change the protection of files.');
- if ($user_is_authenticated) {
-
- if (isset($_GET['exclude_add'])) {
- $response_data = protectDetectionFromDeletion('protect', $_GET['excludefile']);
- echo $response_data['message'];
- die();
- } else {
- $response_data = protectDetectionFromDeletion('unprotect', $_GET['excludefile']);
- echo $response_data['message'];
- die();
- }
-
- }
+ if(isset($_SERVER['PHP_AUTH_USER'])) {
+ $submittedpwd = $_SERVER['PHP_AUTH_PW'];
+ $submitteduser = $_SERVER['PHP_AUTH_USER'];
+ if($submittedpwd == $config['CADDY_PWD'] && $submitteduser == 'birdnet'){
+ if(!file_exists($home."/BirdNET-Pi/scripts/disk_check_exclude.txt")) {
+ file_put_contents($home."/BirdNET-Pi/scripts/disk_check_exclude.txt", "##start\n##end\n");
+ }
+ if(isset($_GET['exclude_add'])) {
+ $myfile = fopen($home."/BirdNET-Pi/scripts/disk_check_exclude.txt", "a") or die("Unable to open file!");
+ $txt = $_GET['excludefile'];
+ fwrite($myfile, $txt."\n");
+ fwrite($myfile, $txt.".png\n");
+ fclose($myfile);
+ echo "OK";
+ die();
+ } else {
+ $lines = file($home."/BirdNET-Pi/scripts/disk_check_exclude.txt");
+ $search = $_GET['excludefile'];
+
+ $result = '';
+ foreach($lines as $line) {
+ if(stripos($line, $search) === false && stripos($line, $search.".png") === false) {
+ $result .= $line;
+ }
+ }
+ file_put_contents($home."/BirdNET-Pi/scripts/disk_check_exclude.txt", $result);
+ echo "OK";
+ die();
+ }
+ } else {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo 'You must be authenticated to change the protection of files.';
+ exit;
+ }
+ } else {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo 'You must be authenticated to change the protection of files.';
+ exit;
+ }
}
-$shifted_path = getDirectory('shifted_dir');
+$shifted_path = $home."/BirdSongs/Extracted/By_Date/shifted/";
if(isset($_GET['shiftfile'])) {
-//Authenticate before going any further
-authenticateUser('You cannot shift files for this installation');
+ 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);
+$caddypwd = $config['CADDY_PWD'];
+if (!isset($_SERVER['PHP_AUTH_USER'])) {
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo '<table><tr><td>You cannot shift files for this installation</td></tr></table>';
+ exit;
+} else {
+ $submittedpwd = $_SERVER['PHP_AUTH_PW'];
+ $submitteduser = $_SERVER['PHP_AUTH_USER'];
+ if($submittedpwd !== $caddypwd || $submitteduser !== 'birdnet'){
+ header('WWW-Authenticate: Basic realm="My Realm"');
+ header('HTTP/1.0 401 Unauthorized');
+ echo '<table><tr><td>You cannot shift files for this installation<</td></tr></table>';
+ exit;
+ }
+}
-//Authenticated if we get this far
- $filename = $_GET['shiftfile'];
- $doShift = null;
- if (isset($_GET['doshift'])) {
- $doShift = true;
- }
+ $filename = $_GET['shiftfile'];
+ $pp = pathinfo($filename);
+ $dir = $pp['dirname'];
+ $fn = $pp['filename'];
+ $ext = $pp['extension'];
+ $pi = $home."/BirdSongs/Extracted/By_Date/";
+
+ if(isset($_GET['doshift'])) {
+ $freqshift_tool = $config['FREQSHIFT_TOOL'];
+
+ if ($freqshift_tool == "ffmpeg") {
+ $cmd = "sudo /usr/bin/nohup /usr/bin/ffmpeg -y -i ".escapeshellarg($pi.$filename)." -af \"rubberband=pitch=".$config['FREQSHIFT_LO']."/".$config['FREQSHIFT_HI']."\" ".escapeshellarg($shifted_path.$filename)."";
+ shell_exec("sudo mkdir -p ".$shifted_path.$dir." && ".$cmd);
+
+ } else if ($freqshift_tool == "sox") {
+ //linux.die.net/man/1/sox
+ $soxopt = "-q";
+ $soxpitch = $config['FREQSHIFT_PITCH'];
+ $cmd = "sudo /usr/bin/nohup /usr/bin/sox ".escapeshellarg($pi.$filename)." ".escapeshellarg($shifted_path.$filename)." pitch ".$soxopt." ".$soxpitch;
+ shell_exec("sudo mkdir -p ".$shifted_path.$dir." && ".$cmd);
+ }
+ } else {
+ $cmd = "sudo rm -f " . escapeshellarg($shifted_path.$filename);
+ shell_exec($cmd);
+ }
- $response_data = frequencyShiftDetectionAudio($filename, $doShift);
- echo $response_data['message'];
+ echo "OK";
die();
}
if(isset($_GET['bydate'])){
- $result_data = getDetectionsByDate();
- if($result_data['success'] == False){
- echo $result_data['message'];
- header("refresh: 0;");
- }
- $result = $result_data['data'];
+ $statement = $db->prepare('SELECT DISTINCT(Date) FROM detections GROUP BY Date ORDER BY Date DESC');
+ if($statement == False){
+ echo "Database is busy";
+ header("refresh: 0;");
+ }
+ $result = $statement->execute();
$view = "bydate";
#Specific Date
@@ -66,36 +171,30 @@ if(isset($_GET['bydate'])){
session_start();
$_SESSION['date'] = $date;
if(isset($_GET['sort']) && $_GET['sort'] == "occurrences") {
- $sort = $_GET['sort'];
+ $statement = $db->prepare("SELECT DISTINCT(Com_Name) FROM detections WHERE Date == \"$date\" GROUP BY Com_Name ORDER BY COUNT(*) DESC");
} else {
- $sort = null;
+ $statement = $db->prepare("SELECT DISTINCT(Com_Name) FROM detections WHERE Date == \"$date\" ORDER BY Com_Name");
}
- $result_data = getDetectionsByDate($date, $sort);
- if($result_data['success'] == False){
- echo $result_data['message'];
- header("refresh: 0;");
- }
- $result = $result_data['data'];
-
+ if($statement == False){
+ echo "Database is busy";
+ header("refresh: 0;");
+ }
+ $result = $statement->execute();
$view = "date";
#By Species
} elseif(isset($_GET['byspecies'])) {
- if(isset($_GET['sort']) && $_GET['sort'] == "occurrences") {
- $sort = $_GET['sort'];
- } else {
- $sort = null;
- }
-
+ if(isset($_GET['sort']) && $_GET['sort'] == "occurrences") {
+ $statement = $db->prepare('SELECT DISTINCT(Com_Name) FROM detections GROUP BY Com_Name ORDER BY COUNT(*) DESC');
+ } else {
+ $statement = $db->prepare('SELECT DISTINCT(Com_Name) FROM detections ORDER BY Com_Name ASC');
+ }
session_start();
-
- $resultArr_data = getDetectionsBySpecies(null, $sort);
- if($resultArr_data['success'] == False){
- echo $resultArr_data['message'];
- header("refresh: 0;");
- }
- $result = $resultArr_data['data']['species'];
-
+ if($statement == False){
+ echo "Database is busy";
+ header("refresh: 0;");
+ }
+ $result = $statement->execute();
$view = "byspecies";
#Specific Species
@@ -103,16 +202,15 @@ if(isset($_GET['bydate'])){
$species = $_GET['species'];
session_start();
$_SESSION['species'] = $species;
-
- $resultArr_data = getDetectionsBySpecies($species, null);
- if($resultArr_data['success'] == False){
- echo $resultArr_data['message'];
- header("refresh: 0;");
- }
- $result = $resultArr_data['data']['species'];
- $resul3 = $resultArr_data['data']['species_MaxConf'];
- $view = "species";
-
+ $statement = $db->prepare("SELECT * FROM detections WHERE Com_Name == \"$species\" ORDER BY Com_Name");
+ $statement3 = $db->prepare("SELECT Date, Time, Sci_Name, MAX(Confidence), File_Name FROM detections WHERE Com_Name == \"$species\" ORDER BY Com_Name");
+ if($statement == False || $statement3 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
+ }
+ $result = $statement->execute();
+ $result3 = $statement3->execute();
+ $view = "species";
} else {
session_start();
session_unset();
@@ -249,20 +347,20 @@ if(!isset($_GET['species']) && !isset($_GET['filename'])){
<?php
#By Date
if($view == "bydate") {
- foreach ($result as $bd_result){
- $date = $bd_result['Date'];
- if(realpath(getDirectory('extracted_by_date') . "/" . $date) !== false){
- echo "<td>
- <button action=\"submit\" name=\"date\" value=\"$date\">".($date == date('Y-m-d') ? "Today" : $date)."</button></td></tr>";}
- }
+ while($results=$result->fetchArray(SQLITE3_ASSOC)){
+ $date = $results['Date'];
+ if(realpath($home."/BirdSongs/Extracted/By_Date/".$date) !== false){
+ echo "<td>
+ <button action=\"submit\" name=\"date\" value=\"$date\">".($date == date('Y-m-d') ? "Today" : $date)."</button></td></tr>";}}
#By Species
} elseif($view == "byspecies") {
$birds = array();
- foreach ($result as $species_bird_name) {
- $name = $species_bird_name['Com_Name'];
- $birds[] = $name;
- }
+ while($results=$result->fetchArray(SQLITE3_ASSOC))
+ {
+ $name = $results['Com_Name'];
+ $birds[] = $name;
+ }
if(count($birds) > 45) {
$num_cols = 3;
@@ -292,12 +390,13 @@ if(!isset($_GET['species']) && !isset($_GET['filename'])){
}
} elseif($view == "date") {
$birds = array();
- foreach ($result as $species_bird_name) {
- $name = $species_bird_name['Com_Name'];
- if (realpath(getDirectory('extracted_by_date') . "/" . $date . "/" . str_replace(" ", "_", $name)) !== false) {
- $birds[] = $name;
- }
- }
+while($results=$result->fetchArray(SQLITE3_ASSOC))
+{
+ $name = $results['Com_Name'];
+ if(realpath($home."/BirdSongs/Extracted/By_Date/".$date."/".str_replace(" ", "_",$name)) !== false){
+ $birds[] = $name;
+ }
+}
if(count($birds) > 45) {
$num_cols = 3;
@@ -357,45 +456,44 @@ if(isset($_GET['species'])){ ?>
</form>
</div>
<?php
- $disk_check_exclude_path = getFilePath('disk_check_exclude.txt');
// add disk_check_exclude.txt lines into an array for grepping
- $fp = @fopen($disk_check_exclude_path, 'r');
+ $fp = @fopen($home."/BirdNET-Pi/scripts/disk_check_exclude.txt", 'r');
if ($fp) {
- $disk_check_exclude_arr = explode("\n", fread($fp, filesize($disk_check_exclude_path)));
+ $disk_check_exclude_arr = explode("\n", fread($fp, filesize($home."/BirdNET-Pi/scripts/disk_check_exclude.txt")));
}
$name = $_GET['species'];
-$confidence = null;
if(isset($_SESSION['date'])) {
$date = $_SESSION['date'];
if(isset($_GET['sort']) && $_GET['sort'] == "confidence") {
- $confidence = $_GET['sort'];
+ $statement2 = $db->prepare("SELECT * FROM detections where Com_Name == \"$name\" AND Date == \"$date\" ORDER BY Confidence DESC");
+ } else {
+ $statement2 = $db->prepare("SELECT * FROM detections where Com_Name == \"$name\" AND Date == \"$date\" ORDER BY Time DESC");
}
- $result2_data = getSpeciesDetectionInfo($name, $date, $confidence);
} else {
if(isset($_GET['sort']) && $_GET['sort'] == "confidence") {
- $confidence = $_GET['sort'];
+ $statement2 = $db->prepare("SELECT * FROM detections where Com_Name == \"$name\" ORDER BY Confidence DESC");
+ } else {
+ $statement2 = $db->prepare("SELECT * FROM detections where Com_Name == \"$name\" ORDER BY Date DESC, Time DESC");
}
- $result2_data = getSpeciesDetectionInfo($name, null, $confidence);
}
-
-if ($result2_data['success'] == False) {
- echo $result2_data['message'];
- header("refresh: 0;");
+if($statement2 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
-$result2 = $result2_data['data'];
-
-//Count number of records we have
-$num_rows = count($result2);
-
+$result2 = $statement2->execute();
+$num_rows = 0;
+while ($result2->fetchArray(SQLITE3_ASSOC)) {
+ $num_rows++;
+}
+$result2->reset(); // reset the pointer to the beginning of the result set
echo "<table>
<tr>
<th>$name</th>
</tr>";
$iter=0;
- while($iter < count($result2))
+ while($results=$result2->fetchArray(SQLITE3_ASSOC))
{
- $results = $result2[$iter];
$comname = preg_replace('/ /', '_', $results['Com_Name']);
$comname = preg_replace('/\'/', '', $comname);
$date = $results['Date'];
@@ -408,19 +506,19 @@ echo "<table>
$confidence = round((float)round($results['Confidence'],2) * 100 ) . '%';
$filename_formatted = $date."/".$comname."/".$results['File_Name'];
- $iter++;
// file was deleted by disk check, no need to show the detection in recordings
- if(!file_exists(getDirectory('extracted') . "/" . $filename)) {
+ if(!file_exists($home."/BirdSongs/Extracted/".$filename)) {
continue;
}
if(!in_array($filename_formatted, $disk_check_exclude_arr) && isset($_GET['only_excluded'])) {
continue;
}
+ $iter++;
if($num_rows < 100){
$imageelem = "<video onplay='setLiveStreamVolume(0)' onended='setLiveStreamVolume(1)' onpause='setLiveStreamVolume(1)' controls poster=\"$filename_png\" preload=\"none\" title=\"$filename\"><source src=\"$filename\"></video>";
} else {
- $imageelem = "<a target='_blank' href=\"$filename\"><img src=\"$filename_png\"></a>";
+ $imageelem = "<a href=\"$filename\"><img src=\"$filename_png\"></a>";
}
if($config["FULL_DISK"] == "purge") {
@@ -467,19 +565,18 @@ echo "<table>
}if($iter == 0){ echo "<tr><td><b>No recordings were found.</b><br><br><span style='font-size:medium'>They may have been deleted to make space for new recordings. You can prevent this from happening in the future by clicking the <img src='images/unlock.svg' style='width:20px'> icon in the top right of a recording.<br>You can also modify this behavior globally under \"Full Disk Behavior\" <a href='views.php?view=Advanced'>here.</a></span></td></tr>";}echo "</table>";}
if(isset($_GET['filename'])){
- $disk_check_exclude_path = getFilePath('disk_check_exclude.txt');
- $name = $_GET['filename'];
- $result2_data = getDetectionsByFilename($name);
- if($result2_data['success'] == False){
- echo $result2_data['message'];
- header("refresh: 0;");
- }
- $result2 = $result2_data['data'];
+ $name = $_GET['filename'];
+ $statement2 = $db->prepare("SELECT * FROM detections where File_name == \"$name\" ORDER BY Date DESC, Time DESC");
+ if($statement2 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
+ }
+ $result2 = $statement2->execute();
echo "<table>
<tr>
<th>$name</th>
</tr>";
- foreach ($result2 as $results)
+ while($results=$result2->fetchArray(SQLITE3_ASSOC))
{
$comname = preg_replace('/ /', '_', $results['Com_Name']);
$comname = preg_replace('/\'/', '', $comname);
@@ -494,9 +591,9 @@ echo "<table>
$filename_formatted = $date."/".$comname."/".$results['File_Name'];
// add disk_check_exclude.txt lines into an array for grepping
- $fp = @fopen($disk_check_exclude_path, 'r');
+ $fp = @fopen($home."/BirdNET-Pi/scripts/disk_check_exclude.txt", 'r');
if ($fp) {
- $disk_check_exclude_arr = explode("\n", fread($fp, filesize($disk_check_exclude_path)));
+ $disk_check_exclude_arr = explode("\n", fread($fp, filesize($home."/BirdNET-Pi/scripts/disk_check_exclude.txt")));
}
if($config["FULL_DISK"] == "purge") {
@@ -538,9 +635,7 @@ echo "<table>
</tr>";
}
- }
- echo "</table>";
- }?>
+ }echo "</table>";}?>
</div>
<style>
td.spec {
diff --git a/scripts/service_controls.php b/scripts/service_controls.php
index ed88538e..18885995 100644
--- a/scripts/service_controls.php
+++ b/scripts/service_controls.php
@@ -1,19 +1,17 @@
-<?php
-if(file_exists('./scripts/common.php')){
- include_once "./scripts/common.php";
-}else{
- include_once "./common.php";
-}
-
+<?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);
+
if($name == "birdnet_server.service") {
- $filesinproc=trim(shell_exec("ls ".getDirectory('home')."/BirdSongs/Processed | wc -l"));
- if($filesinproc > 200) {
+ $filesinproc=trim(shell_exec("ls ".$home."/BirdSongs/Processed | wc -l"));
+ if($filesinproc > 200) {
echo "<span style='color:#fc6603'>(stalled - backlog of ".$filesinproc." files in ~/BirdSongs/Processed/)</span>";
return;
}
- }
- $op = getServiceStatus($name)['status'];
+ }
+ $op = shell_exec("sudo systemctl status ".$name." | grep Active | grep ' active\| activating\|running\|waiting\|start'");
if(strlen($op) > 0) {
echo "<span style='color:green'>(active)</span>";
} else {
@@ -27,78 +25,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="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>
+ <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>
</form>
<form action="" method="GET">
<h3>Web Terminal <?php echo service_status("web_terminal.service");?></h3>
- <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>
+ <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>
</form>
<form action="" method="GET">
<h3>BirdNET Log <?php echo service_status("birdnet_log.service");?></h3>
- <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>
+ <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>
</form>
<form action="" method="GET">
<h3>Extraction Service <?php echo service_status("extraction.service");?></h3>
- <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>
+ <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>
</form>
<form action="" method="GET">
<h3>BirdNET Analysis Server <?php echo service_status("birdnet_server.service");?></h3>
- <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>
+ <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>
</form>
<form action="" method="GET">
<h3>BirdNET Analysis Client <?php echo service_status("birdnet_analysis.service");?></h3>
- <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>
+ <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>
</form>
<form action="" method="GET">
<h3>Streamlit Statistics <?php echo service_status("birdnet_stats.service");?></h3>
- <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>
+ <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>
</form>
<form action="" method="GET">
<h3>Recording Service <?php echo service_status("birdnet_recording.service");?></h3>
- <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>
+ <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>
</form>
<form action="" method="GET">
<h3>Chart Viewer <?php echo service_status("chart_viewer.service");?></h3>
- <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>
+ <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>
</form>
<form action="" method="GET">
<h3>Spectrogram Viewer <?php echo service_status("spectrogram_viewer.service");?></h3>
- <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>
+ <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>
</form>
<form action="" method="GET">
- <button type="submit" name="submit" value="system stop core.services">Stop Core Services</button>
+ <button type="submit" name="submit" value="stop_core_services.sh">Stop Core Services</button>
</form>
<form action="" method="GET">
- <button type="submit" name="submit" value="system restart core.services">Restart Core Services</button>
+ <button type="submit" name="submit" value="restart_services.sh">Restart Core Services</button>
</form>
</div>
diff --git a/scripts/spectrogram.php b/scripts/spectrogram.php
index f03e485e..9bbbbccc 100644
--- a/scripts/spectrogram.php
+++ b/scripts/spectrogram.php
@@ -1,14 +1,22 @@
<?php
-if(file_exists('./scripts/common.php')){
- include_once "./scripts/common.php";
-}else{
- include_once "./common.php";
+error_reporting(E_ERROR);
+ini_set('display_errors',1);
+
+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');
}
if(isset($_GET['ajax_csv'])) {
$RECS_DIR = $config["RECS_DIR"];
+
+$user = shell_exec("awk -F: '/1000/{print $1}' /etc/passwd");
+$home = shell_exec("awk -F: '/1000/{print $6}' /etc/passwd");
+$home = trim($home);
+
//Replace variables to Fix up the file paths just in case the ENV environment variables don't resolve via PHP
-$RECS_DIR = str_replace("\$HOME", getDirectory('home'), $RECS_DIR);
+$RECS_DIR = str_replace("\$HOME", $home, $RECS_DIR);
$STREAM_DATA_DIR = $RECS_DIR . "/StreamData/";
//Try find the latest file out of the soundcard recording folder
@@ -136,7 +144,12 @@ window.onload = function(){
document.body.querySelector('h1').remove();
document.getElementsByClassName("centered")[0].remove()
- <?php
+ <?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');
+ }
$refresh = $config['RECORDING_LENGTH'];
$time = time();
?>
@@ -419,7 +432,15 @@ h1 {
//maybe the list of streams has been modified
//This isn't the ideal for this, but needed a way to fix this setting without calling the advanced setting page
if (array_key_exists($config['RTSP_STREAM_TO_LIVESTREAM'], $RTSP_Stream_Config) === false) {
- saveSetting('RTSP_STREAM_TO_LIVESTREAM',"\"0\"",'restart livestream"');
+ $contents = file_get_contents('/etc/birdnet/birdnet.conf');
+ $contents2 = file_get_contents('./scripts/thisrun.txt');
+ $contents = preg_replace("/RTSP_STREAM_TO_LIVESTREAM=.*/", "RTSP_STREAM_TO_LIVESTREAM=\"0\"", $contents);
+ $contents2 = preg_replace("/RTSP_STREAM_TO_LIVESTREAM=.*/", "RTSP_STREAM_TO_LIVESTREAM=\"0\"", $contents2);
+ $fh = fopen("/etc/birdnet/birdnet.conf", "w");
+ $fh2 = fopen("./scripts/thisrun.txt", "w");
+ fwrite($fh, $contents);
+ fwrite($fh2, $contents2);
+ exec("sudo systemctl restart livestream.service");
}
//Print out the dropdown list for the RTSP streams
diff --git a/scripts/stats.php b/scripts/stats.php
index 9a818427..6706bfc3 100644
--- a/scripts/stats.php
+++ b/scripts/stats.php
@@ -1,46 +1,64 @@
<?php
-if(file_exists('./scripts/common.php')){
- include_once "./scripts/common.php";
-}else{
- include_once "./common.php";
-}
+ini_set('user_agent', 'PHP_Flickr/1.0');
+error_reporting(0);
+ini_set('display_errors', 0);
-$disk_check_exclude_path = getFilePath('disk_check_exclude.txt');
+$db = new SQLite3('./scripts/birds.db', SQLITE3_OPEN_CREATE | SQLITE3_OPEN_READWRITE);
+if($db == False) {
+ echo "Database busy";
+ header("refresh: 0;");
+}
if(isset($_GET['sort']) && $_GET['sort'] == "occurrences") {
- $sort = "occurrences";
- $result2_data = getSpeciesBestRecordingList($sort);
-
- if ($result2_data['success'] == False) {
- echo $result2_data['message'];
- header("refresh: 0;");
- }
- $result2 = $result2_data['data'];
+
+ $statement = $db->prepare('SELECT Date, Time, File_Name, Com_Name, COUNT(*), MAX(Confidence) FROM detections GROUP BY Com_Name ORDER BY COUNT(*) DESC');
+ if($statement == False) {
+ echo "Database busy";
+ header("refresh: 0;");
+ }
+ $result = $statement->execute();
+
+ $statement2 = $db->prepare('SELECT Date, Time, File_Name, Com_Name, COUNT(*), MAX(Confidence) FROM detections GROUP BY Com_Name ORDER BY COUNT(*) DESC');
+ if($statement == False) {
+ echo "Database busy";
+ header("refresh: 0;");
+ }
+ $result2 = $statement2->execute();
} else {
- $result2_data = getSpeciesBestRecordingList();
- if ($result2_data['success'] == False) {
- echo $result2_data['message'];
- header("refresh: 0;");
- }
- $result2 = $result2_data['data'];
+ $statement = $db->prepare('SELECT Date, Time, File_Name, Com_Name, COUNT(*), MAX(Confidence) FROM detections GROUP BY Com_Name ORDER BY Com_Name ASC');
+ if($statement == False) {
+ echo "Database busy";
+ header("refresh: 0;");
+ }
+ $result = $statement->execute();
+
+ $statement2 = $db->prepare('SELECT Date, Time, File_Name, Com_Name, COUNT(*), MAX(Confidence) FROM detections GROUP BY Com_Name ORDER BY Com_Name ASC');
+ if($statement == False) {
+ echo "Database busy";
+ header("refresh: 0;");
+ }
+ $result2 = $statement2->execute();
}
if(isset($_GET['species'])){
$selection = $_GET['species'];
- $result3_data = getBestRecordingsForSpecies($selection);
- if($result3_data['success'] == False){
- echo $result3_data['message'];
- header("refresh: 0;");
- }
- $result3 = $result3_data['data'];
+ $statement3 = $db->prepare("SELECT Com_Name, Sci_Name, COUNT(*), MAX(Confidence), File_Name, Date, Time from detections WHERE Com_Name = \"$selection\"");
+ if($statement3 == False) {
+ echo "Database busy";
+ header("refresh: 0;");
+ }
+ $result3 = $statement3->execute();
}
-if(!file_exists($disk_check_exclude_path) || strpos(file_get_contents($disk_check_exclude_path),"##start") === false) {
- file_put_contents($disk_check_exclude_path, "");
- file_put_contents($disk_check_exclude_path, "##start\n##end\n");
+$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/scripts/disk_check_exclude.txt") || strpos(file_get_contents($home."/BirdNET-Pi/scripts/disk_check_exclude.txt"),"##start") === false) {
+ file_put_contents($home."/BirdNET-Pi/scripts/disk_check_exclude.txt", "");
+ file_put_contents($home."/BirdNET-Pi/scripts/disk_check_exclude.txt", "##start\n##end\n");
}
?>
@@ -73,7 +91,7 @@ if(!file_exists($disk_check_exclude_path) || strpos(file_get_contents($disk_chec
<table style="padding-top:10px">
<?php
$birds = array();
- foreach($result2 as $results)
+ while($results=$result2->fetchArray(SQLITE3_ASSOC))
{
$comname = preg_replace('/ /', '_', $results['Com_Name']);
$comname = preg_replace('/\'/', '', $comname);
@@ -158,7 +176,7 @@ function setModalText(iter, title, text, authorlink) {
$species = $_GET['species'];
$iter=0;
$lines;
-foreach ($result3 as $results){
+while($results=$result3->fetchArray(SQLITE3_ASSOC)){
$count = $results['COUNT(*)'];
$maxconf = round((float)round($results['MAX(Confidence)'],2) * 100 ) . '%';
$date = $results['Date'];
@@ -186,22 +204,35 @@ foreach ($result3 as $results){
ob_flush();
flush();
- $flickr_data = getFlickrImage($results, true);
-
- //Loop over the photos data
- if ($flickr_data['image_found']) {
- $flickr_image_data = $flickr_data['data']['photos'];
- $iter = 0;
- foreach ($flickr_image_data as $key => $img_data) {
- $imageurl = $img_data['image_url'];
- $title = $img_data['photo_title'];
- $modaltext = $img_data['modal_text'];
- $authorlink = $img_data['author_link'];
-
- echo "<span style='cursor:pointer;' onclick='setModalText(" . $iter . ",\"" . $title . "\",\"" . $modaltext . "\", \"" . $authorlink . "\")'><img style='vertical-align:top' src=\"$imageurl\"></span>";
- $iter++;
- }
- }
+ 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');
+ }
+ if (! empty($config["FLICKR_API_KEY"])) {
+ // only open the file once per script execution
+ if(!isset($lines)) {
+ $lines = file($home."/BirdNET-Pi/model/labels_flickr.txt");
+ }
+ // convert sci name to English name
+ foreach($lines as $line){
+ if(strpos($line, $results['Sci_Name']) !== false){
+ $engname = trim(explode("_", $line)[1]);
+ break;
+ }
+ }
+
+ $flickrjson = json_decode(file_get_contents("https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=".$config["FLICKR_API_KEY"]."&text=\"".str_replace(' ', '%20', $engname)."\"&license=2%2C3%2C4%2C5%2C6%2C9&sort=relevance&per_page=15&format=json&nojsoncallback=1"), true)["photos"]["photo"];
+
+ foreach ($flickrjson as $val) {
+
+ $iter++;
+ $modaltext = "https://flickr.com/photos/".$val["owner"]."/".$val["id"];
+ $authorlink = "https://flickr.com/people/".$val["owner"];
+ $imageurl = 'https://farm' .$val["farm"]. '.static.flickr.com/' .$val["server"]. '/' .$val["id"]. '_' .$val["secret"]. '.jpg';
+ echo "<span style='cursor:pointer;' onclick='setModalText(".$iter.",\"".$val["title"]."\",\"".$modaltext."\", \"".$authorlink."\")'><img style='vertical-align:top' src=\"$imageurl\"></span>";
+ }
+ }
}
}
?>
@@ -215,7 +246,7 @@ foreach ($result3 as $results){
<table>
<?php
$excludelines = [];
-foreach($result2 as $results)
+while($results=$result->fetchArray(SQLITE3_ASSOC))
{
$comname = preg_replace('/ /', '_', $results['Com_Name']);
$comname = preg_replace('/\'/', '', $comname);
@@ -235,8 +266,8 @@ array_push($excludelines, $results['Date']."/".$comname."/".$results['File_Name'
<?php
}
-$file = file_get_contents($disk_check_exclude_path);
-file_put_contents($disk_check_exclude_path, "##start"."\n".implode("\n",$excludelines)."\n".substr($file, strpos($file, "##end")));
+$file = file_get_contents($home."/BirdNET-Pi/scripts/disk_check_exclude.txt");
+file_put_contents($home."/BirdNET-Pi/scripts/disk_check_exclude.txt", "##start"."\n".implode("\n",$excludelines)."\n".substr($file, strpos($file, "##end")));
?>
</table>
</form>
diff --git a/scripts/system_controls.php b/scripts/system_controls.php
index c9935651..067b3148 100644
--- a/scripts/system_controls.php
+++ b/scripts/system_controls.php
@@ -1,11 +1,21 @@
<?php
-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);
+$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();
?><html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<br>
@@ -35,7 +45,8 @@ 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
- $curr_hash = getGitCurrentHash()
+ $cmd="cd ".$home."/BirdNET-Pi && sudo -u ".$user." git rev-list --max-count=1 HEAD";
+ $curr_hash = shell_exec($cmd);
?>
<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.php
index 069a7985..f129dd41 100644
--- a/scripts/todays_detections.php
+++ b/scripts/todays_detections.php
@@ -1,113 +1,311 @@
<?php
- include_once "./scripts/common.php";
+ini_set('session.gc_maxlifetime', 7200);
+ini_set('user_agent', 'PHP_Flickr/1.0');
+session_set_cookie_params(7200);
+session_start();
+error_reporting(E_ERROR);
+ini_set('display_errors',1);
+
+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');
+ }
+
+ if($config["SITE_NAME"] == "") {
+ $site_name = "BirdNET-Pi";
+ } else {
+ $site_name = $config['SITE_NAME'];
+ }
if($kiosk == true) {
echo "<div style='margin-top:20px' class=\"centered\"><h1><a><img class=\"topimage\" src=\"images/bnp.png\"></a></h1></div>
</div><div class=\"centered\"><h3>$site_name</h3></div><hr>";
}
-$totalcount_data = getDetectionCountAll();
-if($totalcount_data['success'] == False){
- echo $totalcount_data['message'];
+$db = new SQLite3('./scripts/birds.db', SQLITE3_OPEN_CREATE | SQLITE3_OPEN_READWRITE);
+if($db == False){
+ echo "Database is busy";
header("refresh: 0;");
}
-$totalcount = $totalcount_data['data'];
-
-$todaycount_data = getDetectionCountToday();
-if($todaycount_data['success'] == False){
- echo $todaycount_data['message'];
- header("refresh: 0;");
+$statement1 = $db->prepare('SELECT COUNT(*) FROM detections');
+if($statement1 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
-$todaycount = $todaycount_data['data'];
-
+$result1 = $statement1->execute();
+$totalcount = $result1->fetchArray(SQLITE3_ASSOC);
-$hourcount_data = getDetectionCountLastHour();
-if($hourcount_data['success'] == False){
- echo $hourcount_data['message'];
- header("refresh: 0;");
+$statement2 = $db->prepare('SELECT COUNT(*) FROM detections WHERE Date == DATE(\'now\', \'localtime\')');
+if($statement2 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
-$hourcount = $hourcount_data['data'];
-
+$result2 = $statement2->execute();
+$todaycount = $result2->fetchArray(SQLITE3_ASSOC);
-$mostrecent_data = getMostRecentDetection();
-if($mostrecent_data['success'] == False){
- echo $mostrecent_data['message'];
- header("refresh: 0;");
+$statement3 = $db->prepare('SELECT COUNT(*) FROM detections WHERE Date == Date(\'now\', \'localtime\') AND TIME >= TIME(\'now\', \'localtime\', \'-1 hour\')');
+if($statement3 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
-$mostrecent = $mostrecent_data['data'];
-
+$result3 = $statement3->execute();
+$hourcount = $result3->fetchArray(SQLITE3_ASSOC);
-$todayspeciestally_data = getSpeciesTalley();
-if($todayspeciestally_data['success'] == False){
- echo $todayspeciestally_data['message'];
- header("refresh: 0;");
+$statement4 = $db->prepare('SELECT Com_Name, Sci_Name, Time, Confidence FROM detections LIMIT 1');
+if($statement4 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
-$todayspeciestally = $todayspeciestally_data['data'];
+$result4 = $statement4->execute();
+$mostrecent = $result4->fetchArray(SQLITE3_ASSOC);
+$statement5 = $db->prepare('SELECT COUNT(DISTINCT(Com_Name)) FROM detections WHERE Date == Date(\'now\', \'localtime\')');
+if($statement5 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
+}
+$result5 = $statement5->execute();
+$todayspeciestally = $result5->fetchArray(SQLITE3_ASSOC);
-$totalspeciestally_data = getAllSpeciesTalley();
-if($totalspeciestally_data['success'] == False){
- echo $totalspeciestally_data['message'];
- header("refresh: 0;");
+$statement6 = $db->prepare('SELECT COUNT(DISTINCT(Com_Name)) FROM detections');
+if($statement6 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
-$totalspeciestally = $totalspeciestally_data['data'];
+$result6 = $statement6->execute();
+$totalspeciestally = $result6->fetchArray(SQLITE3_ASSOC);
+$user = shell_exec("awk -F: '/1000/{print $1}' /etc/passwd");
+$home = shell_exec("awk -F: '/1000/{print $6}' /etc/passwd");
+$home = trim($home);
if(isset($_GET['comname'])) {
$birdName = $_GET['comname'];
$birdName = str_replace("_", " ", $birdName);
- echo getBirdDetectionStats($birdName)['data'];
+// Prepare a SQL statement to retrieve the detection data for the specified bird
+$stmt = $db->prepare('SELECT Date, COUNT(*) AS Detections FROM detections WHERE Com_Name = :com_name AND Date BETWEEN DATE("now", "-30 days") AND DATE("now") GROUP BY Date');
+
+// Bind the bird name parameter to the SQL statement
+$stmt->bindValue(':com_name', $birdName);
+
+// Execute the SQL statement and get the result set
+$result = $stmt->execute();
+
+// Fetch the result set as an associative array
+$data = array();
+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $data[$row['Date']] = $row['Detections'];
+}
+
+// Create an array of all dates in the last 14 days
+$last14Days = array();
+for ($i = 0; $i < 31; $i++) {
+ $last14Days[] = date('Y-m-d', strtotime("-$i days"));
+}
+
+// Merge the data array with the last14Days array
+$data = array_merge(array_fill_keys($last14Days, 0), $data);
+
+// Sort the data by date in ascending order
+ksort($data);
+
+// Convert the data to an array of objects
+$data = array_map(function($date, $count) {
+ return array('date' => $date, 'count' => $count);
+}, array_keys($data), $data);
+
+// Close the database connection
+$db->close();
+
+// Return the data as JSON
+echo json_encode($data);
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']);
- if($result0['success'] == False){
- echo $result0['message'];
+if(isset($_GET['ajax_detections']) && $_GET['ajax_detections'] == "true" ) {
+ if(isset($_GET['searchterm'])) {
+ if(strtolower(explode(" ", $_GET['searchterm'])[0]) == "not") {
+ $not = "NOT ";
+ $operator = "AND";
+ $_GET['searchterm'] = str_replace("not ", "", $_GET['searchterm']);
+ $_GET['searchterm'] = str_replace("NOT ", "", $_GET['searchterm']);
+ } else {
+ $not = "";
+ $operator = "OR";
+ }
+ $searchquery = "AND (Com_name ".$not."LIKE '%".$_GET['searchterm']."%' ".$operator." Sci_name ".$not."LIKE '%".$_GET['searchterm']."%' ".$operator." Confidence ".$not."LIKE '%".$_GET['searchterm']."%' ".$operator." File_Name ".$not."LIKE '%".$_GET['searchterm']."%' ".$operator." Time ".$not."LIKE '%".$_GET['searchterm']."%')";
+ } else {
+ $searchquery = "";
+ }
+ if(isset($_GET['display_limit']) && is_numeric($_GET['display_limit'])){
+ $statement0 = $db->prepare('SELECT Time, Com_Name, Sci_Name, Confidence, File_Name FROM detections WHERE Date == Date(\'now\', \'localtime\') '.$searchquery.' ORDER BY Time DESC LIMIT '.(intval($_GET['display_limit'])-40).',40');
+ } else {
+ // legacy mode
+ if(isset($_GET['hard_limit']) && is_numeric($_GET['hard_limit'])) {
+ $statement0 = $db->prepare('SELECT Time, Com_Name, Sci_Name, Confidence, File_Name FROM detections WHERE Date == Date(\'now\', \'localtime\') '.$searchquery.' ORDER BY Time DESC LIMIT '.$_GET['hard_limit']);
+ } else {
+ $statement0 = $db->prepare('SELECT Time, Com_Name, Sci_Name, Confidence, File_Name FROM detections WHERE Date == Date(\'now\', \'localtime\') '.$searchquery.' ORDER BY Time DESC');
+ }
+
+ }
+ if($statement0 == False){
+ echo "Database is busy";
header("refresh: 0;");
- }
- $result0 = $result0['data'];
+ }
+ $result0 = $statement0->execute();
+
?> <table>
<?php
+ if(!isset($_SESSION['images'])) {
+ $_SESSION['images'] = [];
+ }
$iterations = 0;
$lines=null;
$licenses_urls = array();
-foreach($result0 as $todaytable)
+ 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');
+ }
+
+
+ while($todaytable=$result0->fetchArray(SQLITE3_ASSOC))
{
$iterations++;
- //Get the flickr image for this detection
- $flickr_Image = getFlickrImage($todaytable);
-
- if ($flickr_Image['image_found']) {
- //Remap the data from returned data into an array that is referenced in our HTML
- //to save have to rewrite or adjust it
- $flickr_Image_data = $flickr_Image['data'];
-
- $image = [
- 0 => $flickr_Image_data['Com_Name_clean'],
- 1 => $flickr_Image_data['photos'][0]['image_url'],
- 2 => $flickr_Image_data['photos'][0]['photo_title'],
- 3 => $flickr_Image_data['photos'][0]['modal_text'],
- 4 => $flickr_Image_data['photos'][0]['author_link'],
- 5 => $flickr_Image_data['photos'][0]['license_url']
- ];
- }
-
- //Fill in the missing variables as they're not created at each loop anymore, getFlickrImage generates this data now as per what the orignal loop did
- $filename = $flickr_Image_data['filename_path'];
- $filename_formatted = $flickr_Image_data['filename_formatted'];
- $sciname = $flickr_Image_data['Sci_Name_clean'];
- $comname =$flickr_Image_data['Com_Name_clean'];
+ $comname = preg_replace('/ /', '_', $todaytable['Com_Name']);
+ $comname = preg_replace('/\'/', '_', $comname);
+ $filename = "/By_Date/".date('Y-m-d')."/".$comname."/".$todaytable['File_Name'];
+ $filename_formatted = $todaytable['Date']."/".$comname."/".$todaytable['File_Name'];
+ $sciname = preg_replace('/ /', '_', $todaytable['Sci_Name']);
+ $args = "&license=2%2C3%2C4%2C5%2C6%2C9&orientation=square,portrait";
+ $comnameprefix = "%20bird";
+ if (!empty($config["FLICKR_API_KEY"]) && (isset($_GET['display_limit']) || isset($_GET['hard_limit']) || $_GET['kiosk'] == true) ) {
+
+ if(!empty($config["FLICKR_FILTER_EMAIL"])) {
+ if(!isset($_SESSION["FLICKR_FILTER_EMAIL"])) {
+ unset($_SESSION['images']);
+ $_SESSION['FLICKR_FILTER_EMAIL'] = json_decode(file_get_contents("https://www.flickr.com/services/rest/?method=flickr.people.findByEmail&api_key=".$config["FLICKR_API_KEY"]."&find_email=".$config["FLICKR_FILTER_EMAIL"]."&format=json&nojsoncallback=1"), true)["user"]["nsid"];
+ }
+ $args = "&user_id=".$_SESSION['FLICKR_FILTER_EMAIL'];
+ $comnameprefix = "";
+ } else {
+ if(isset($_SESSION["FLICKR_FILTER_EMAIL"])) {
+ unset($_SESSION["FLICKR_FILTER_EMAIL"]);
+ unset($_SESSION['images']);
+ }
+ }
+
+ // if we already searched flickr for this species before, use the previous image rather than doing an unneccesary api call
+ $key = array_search($comname, array_column($_SESSION['images'], 0));
+ if($key !== false) {
+ $image = $_SESSION['images'][$key];
+ } else {
+ // Get license information if we haven't already
+ if (empty($licenses_urls)) {
+ $licenses_url = "https://api.flickr.com/services/rest/?method=flickr.photos.licenses.getInfo&api_key=".$config["FLICKR_API_KEY"]."&format=json&nojsoncallback=1";
+ $licenses_response = file_get_contents($licenses_url);
+ $licenses_data = json_decode($licenses_response, true)["licenses"]["license"];
+ foreach ($licenses_data as $license) {
+ $license_id = $license["id"];
+ $license_name = $license["name"];
+ $license_url = $license["url"];
+ $licenses_urls[$license_id] = $license_url;
+ }
+ }
+
+ // only open the file once per script execution
+ if(!isset($lines)) {
+ $lines = file($home."/BirdNET-Pi/model/labels_flickr.txt");
+ }
+ // convert sci name to English name
+ foreach($lines as $line){
+ if(strpos($line, $todaytable['Sci_Name']) !== false){
+ $engname = trim(explode("_", $line)[1]);
+ break;
+ }
+ }
+ // Read the blacklisted image ids from the file into an array
+ $blacklisted_ids = array_map('trim', file($home."/BirdNET-Pi/scripts/blacklisted_images.txt"));
+
+ // Make the API call
+ $flickrjson = json_decode(file_get_contents("https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=".$config["FLICKR_API_KEY"]."&text=".str_replace(" ", "%20", $engname).$comnameprefix."&sort=relevance".$args."&per_page=5&media=photos&format=json&nojsoncallback=1"), true)["photos"]["photo"];
+
+ // Find the first photo that is not blacklisted or is not the specific blacklisted id
+ $photo = null;
+ foreach ($flickrjson as $flickrphoto) {
+ if ($flickrphoto["id"] !== "4892923285" && !in_array($flickrphoto["id"], $blacklisted_ids)) {
+ $photo = $flickrphoto;
+ break;
+ }
+ }
+
+ $license_url = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=".$config["FLICKR_API_KEY"]."&photo_id=".$photo["id"]."&format=json&nojsoncallback=1";
+ $license_response = file_get_contents($license_url);
+ $license_info = json_decode($license_response, true)["photo"]["license"];
+ $license_url = $licenses_urls[$license_info];
+ $modaltext = "https://flickr.com/photos/".$photo["owner"]."/".$photo["id"];
+ $authorlink = "https://flickr.com/people/".$photo["owner"];
+ $imageurl = 'https://farm' .$photo["farm"]. '.static.flickr.com/' .$photo["server"]. '/' .$photo["id"]. '_' .$photo["secret"]. '.jpg';
+ array_push($_SESSION['images'], array($comname,$imageurl,$photo["title"], $modaltext, $authorlink, $license_url));
+ $image = $_SESSION['images'][count($_SESSION['images'])-1];
+ }
+ }
?>
<?php if(isset($_GET['display_limit']) && is_numeric($_GET['display_limit'])){ ?>
<tr class="relative" id="<?php echo $iterations; ?>">
diff --git a/scripts/weekly_report.php b/scripts/weekly_report.php
index fe74108c..e625d3a7 100644
--- a/scripts/weekly_report.php
+++ b/scripts/weekly_report.php
@@ -1,9 +1,7 @@
-<?php
-if(file_exists('./scripts/common.php')){
- include_once "./scripts/common.php";
-}else{
- include_once "./common.php";
-}
+<?php
+ini_set('display_errors', 1);
+ini_set('display_startup_errors', 1);
+error_reporting(E_ALL);
$startdate = strtotime('last sunday') - (7*86400);
$enddate = strtotime('last sunday') - (1*86400);
@@ -11,38 +9,51 @@ $enddate = strtotime('last sunday') - (1*86400);
$debug = false;
if(isset($_GET['ascii'])) {
- $weekly_species_counts = getWeeklyReportSpeciesDetectionCounts();
- if($weekly_species_counts['detections']['success'] == False){
- echo $weekly_species_counts['detections']['message'];
- header("refresh: 0;");
+ $db = new SQLite3('./scripts/birds.db', SQLITE3_OPEN_CREATE | SQLITE3_OPEN_READWRITE);
+ if($db == False){
+ echo "Database is busy";
+ header("refresh: 0;");
+ }
+
+ $statement1 = $db->prepare('SELECT DISTINCT(Com_Name), COUNT(*) FROM detections WHERE Date BETWEEN "'.date("Y-m-d",$startdate).'" AND "'.date("Y-m-d",$enddate).'" GROUP By Com_Name ORDER BY COUNT(*) DESC');
+ if($statement1 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
- $result1 = $weekly_species_counts['detections']['data'];
+ $result1 = $statement1->execute();
- if($weekly_species_counts['totalcount']['success'] == False){
- echo $weekly_species_counts['totalcount']['message'];
- header("refresh: 0;");
+ $statement4 = $db->prepare('SELECT DISTINCT(Com_Name), COUNT(*) FROM detections WHERE Date BETWEEN "'.date("Y-m-d",$startdate).'" AND "'.date("Y-m-d",$enddate).'"');
+ if($statement4 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
- $totalcount = $weekly_species_counts['totalcount']['data']['COUNT(*)'];
+ $result4 = $statement4->execute();
+ $totalcount = $result4->fetchArray(SQLITE3_ASSOC)['COUNT(*)'];
- if($weekly_species_counts['priortotalcount']['success'] == False){
- echo $weekly_species_counts['priortotalcount']['message'];
- header("refresh: 0;");
+ $statement5 = $db->prepare('SELECT DISTINCT(Com_Name), COUNT(*) FROM detections WHERE Date BETWEEN "'.date("Y-m-d",$startdate- (7*86400)).'" AND "'.date("Y-m-d",$enddate- (7*86400)).'"');
+ if($statement5 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
- $priortotalcount = $weekly_species_counts['priortotalcount']['data']['COUNT(*)'];
+ $result5 = $statement5->execute();
+ $priortotalcount = $result5->fetchArray(SQLITE3_ASSOC)['COUNT(*)'];
- $weekly_species_talley = getWeeklyReportSpeciesTalley();
- if($weekly_species_talley['totalspeciestally']['success'] == False){
- echo $weekly_species_talley['totalspeciestally']['message'];
- header("refresh: 0;");
+ $statement6 = $db->prepare('SELECT COUNT(DISTINCT(Com_Name)) FROM detections WHERE Date BETWEEN "'.date("Y-m-d",$startdate).'" AND "'.date("Y-m-d",$enddate).'"');
+ if($statement6 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
- $totalspeciestally = $weekly_species_talley['totalspeciestally']['data']['COUNT(DISTINCT(Com_Name))'];
+ $result6 = $statement6->execute();
+ $totalspeciestally = $result6->fetchArray(SQLITE3_ASSOC)['COUNT(DISTINCT(Com_Name))'];
- if($weekly_species_talley['priortotalspeciestally']['success'] == False){
- echo $weekly_species_talley['priortotalspeciestally']['message'];
- header("refresh: 0;");
+ $statement7 = $db->prepare('SELECT COUNT(DISTINCT(Com_Name)) FROM detections WHERE Date BETWEEN "'.date("Y-m-d",$startdate- (7*86400)).'" AND "'.date("Y-m-d",$enddate- (7*86400)).'"');
+ if($statement7 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
- $priortotalspeciestally = $weekly_species_talley['priortotalspeciestally']['data']['COUNT(DISTINCT(Com_Name))'];
+ $result7= $statement7->execute();
+ $priortotalspeciestally = $result7->fetchArray(SQLITE3_ASSOC)['COUNT(DISTINCT(Com_Name))'];
$percentagedifftotal = round( (($totalcount - $priortotalcount) / $priortotalcount) * 100 );
@@ -61,10 +72,11 @@ if(isset($_GET['ascii'])) {
$detections = [];
$i = 0;
- foreach ($result1 as $detection)
+ while($detection=$result1->fetchArray(SQLITE3_ASSOC))
{
$detections[$detection["Com_Name"]] = $detection["COUNT(*)"];
}
+
echo "# BirdNET-Pi: Week ".date('W', $enddate)." Report\n";
echo "Total Detections: <b>".$totalcount."</b> (".$percentagedifftotal.")<br>";
@@ -78,12 +90,14 @@ if(isset($_GET['ascii'])) {
$i++;
if($i <= 10) {
- $statement2 = getWeeklyReportSpeciesDetection($com_name);
- if($statement2['success'] == False){
- echo $statement2['message'];
- header("refresh: 0;");
+ $statement2 = $db->prepare('SELECT COUNT(*) FROM detections WHERE Com_Name == "'.$com_name.'" AND Date BETWEEN "'.date("Y-m-d",$startdate - (7*86400)).'" AND "'.date("Y-m-d",$enddate - (7*86400)).'"');
+ if($statement2 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
- $priorweekcount = $statement2['data']['COUNT(*)'];
+ $result2 = $statement2->execute();
+ $totalcount = $result2->fetchArray(SQLITE3_ASSOC);
+ $priorweekcount = $totalcount['COUNT(*)'];
// really percent changed
if($priorweekcount > 0){
@@ -107,12 +121,14 @@ if(isset($_GET['ascii'])) {
$newspeciescount=0;
foreach($detections as $com_name=>$scount)
{
- $statement3 = getWeeklyReportSpeciesDetection($com_name,false);
- if($statement3['success'] == False){
- echo $statement3['message'];
- header("refresh: 0;");
+ $statement3 = $db->prepare('SELECT COUNT(*) FROM detections WHERE Com_Name == "'.$com_name.'" AND Date NOT BETWEEN "'.date("Y-m-d",$startdate).'" AND "'.date("Y-m-d",$enddate).'"');
+ if($statement3 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
- $nonthisweekcount = $statement3['data']['COUNT(*)'];
+ $result3 = $statement3->execute();
+ $totalcount = $result3->fetchArray(SQLITE3_ASSOC);
+ $nonthisweekcount = $totalcount['COUNT(*)'];
if($nonthisweekcount == 0) {
$newspeciescount++;
@@ -137,27 +153,26 @@ if(isset($_GET['ascii'])) {
echo "<h1>Week ".date('W', $enddate)." Report</h1>".date('F jS, Y',$startdate)." — ".date('F jS, Y',$enddate)."<br>";
?></div><?php
-if($debug == false){
- $weekly_species_counts = getWeeklyReportSpeciesDetectionCounts();
+$db = new SQLite3('./scripts/birds.db', SQLITE3_OPEN_CREATE | SQLITE3_OPEN_READWRITE);
+if($db == False){
+ echo "Database is busy";
+ header("refresh: 0;");
+}
- if($weekly_species_counts['detections']['success'] == False){
- echo $weekly_species_counts['detections']['message'];
- header("refresh: 0;");
- }
- $result1 = $weekly_species_counts['detections']['data'];
+if($debug == false){
+$statement1 = $db->prepare('SELECT DISTINCT(Com_Name), COUNT(*) FROM detections WHERE Date BETWEEN "'.date("Y-m-d",$startdate).'" AND "'.date("Y-m-d",$enddate).'" GROUP By Com_Name ORDER BY COUNT(*) DESC');
} else {
- $weekly_species_counts = getWeeklyReportSpeciesDetectionCounts(false);
-
- if($weekly_species_counts['detections']['success'] == False){
- echo $weekly_species_counts['detections']['message'];
- header("refresh: 0;");
- }
- $result1 = $weekly_species_counts['detections']['data'];
+ $statement1 = $db->prepare('SELECT DISTINCT(Com_Name), COUNT(*) FROM detections WHERE Date BETWEEN "'.date("Y-m-d",$startdate).'" AND "'.date("Y-m-d",$enddate).'" GROUP By Com_Name ORDER BY COUNT(*) ASC');
+}
+if($statement1 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
+$result1 = $statement1->execute();
$detections = [];
$i = 0;
-foreach ($result1 as $detection)
+while($detection=$result1->fetchArray(SQLITE3_ASSOC))
{
if($debug == true){
if($i > 10) {
@@ -186,12 +201,14 @@ foreach ($result1 as $detection)
{
$i++;
if($i <= 10) {
- $statement2 = getWeeklyReportSpeciesDetection($com_name);
- if($statement2['success'] == False){
- echo $statement2['message'];
- header("refresh: 0;");
+ $statement2 = $db->prepare('SELECT COUNT(*) FROM detections WHERE Com_Name == "'.$com_name.'" AND Date BETWEEN "'.date("Y-m-d",$startdate - (7*86400)).'" AND "'.date("Y-m-d",$enddate - (7*86400)).'"');
+ if($statement2 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
- $priorweekcount = $statement2['data']['COUNT(*)'];
+ $result2 = $statement2->execute();
+ $totalcount = $result2->fetchArray(SQLITE3_ASSOC);
+ $priorweekcount = $totalcount['COUNT(*)'];
if ($priorweekcount > 0) {
$percentagediff = round( (($scount - $priorweekcount) / $priorweekcount) * 100 );
@@ -225,12 +242,14 @@ foreach ($result1 as $detection)
$newspeciescount=0;
foreach($detections as $com_name=>$scount)
{
- $statement3 = getWeeklyReportSpeciesDetection($com_name,false);
- if($statement3['success'] == False){
- echo $statement3['message'];
- header("refresh: 0;");
+ $statement3 = $db->prepare('SELECT COUNT(*) FROM detections WHERE Com_Name == "'.$com_name.'" AND Date NOT BETWEEN "'.date("Y-m-d",$startdate).'" AND "'.date("Y-m-d",$enddate).'"');
+ if($statement3 == False){
+ echo "Database is busy";
+ header("refresh: 0;");
}
- $nonthisweekcount = $statement3['data']['COUNT(*)'];
+ $result3 = $statement3->execute();
+ $totalcount = $result3->fetchArray(SQLITE3_ASSOC);
+ $nonthisweekcount = $totalcount['COUNT(*)'];
if($nonthisweekcount == 0) {
$newspeciescount++;
diff --git a/tests/test_filepath_resolver_common.php b/tests/test_filepath_resolver_common.php
deleted file mode 100644
index 5d8e90c3..00000000
--- a/tests/test_filepath_resolver_common.php
+++ /dev/null
@@ -1,210 +0,0 @@
-<?php
-include_once "../scripts/common.php";
-
-const TEST_HOMES = ['/home/pi', '/home/another_user', '/opt/birdnet'];
-
-$config = [
- "RECS_DIR" => "\$HOME/BirdSongs",
- "PROCESSED" => "\${RECS_DIR}/Processed",
- "EXTRACTED" => "\${RECS_DIR}/Extracted",
- "IDFILE" => "\$HOME/BirdNET-Pi/IdentifiedSoFar.txt"
-];
-
-function test()
-{
- global $home;
-
- foreach (TEST_HOMES as $_test_home) {
- $home = $_test_home;
-
- ############################
- ## Directory Path Tests
- ############################
- $result = getDirectory('home');
- $expected = $_test_home;
- ($result == $expected) ?: (print "failed directory 'home', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- # DIRECTORY TESTS
- $result = getDirectory('birdnet_pi');
- $expected = $_test_home . "/BirdNET-Pi";
- ($result == $expected) ?: (print "failed directory 'birdnet_pi', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('recs_dir');
- $expected = $_test_home . "/BirdSongs";
- ($result == $expected) ?: (print "failed directory 'recs_dir', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('processed');
- $expected = $_test_home . "/BirdSongs/Processed";
- ($result == $expected) ?: (print "failed directory 'processed', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('extracted');
- $expected = $_test_home . "/BirdSongs/Extracted";
- ($result == $expected) ?: (print "failed directory 'extracted', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('extracted_by_date');
- $expected = $_test_home . "/BirdSongs/Extracted/By_Date";
- ($result == $expected) ?: (print "failed directory 'extracted_by_date', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('shifted_audio');
- $expected = $_test_home . "/BirdSongs/Extracted/By_Date/shifted";
- ($result == $expected) ?: (print "failed directory 'shifted_audio', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('database');
- $expected = $_test_home . "/BirdNET-Pi/database";
- ($result == $expected) ?: (print "failed directory 'database', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('config');
- $expected = $_test_home . "/BirdNET-Pi/config";
- ($result == $expected) ?: (print "failed directory 'config', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('models');
- $expected = $_test_home . "/BirdNET-Pi/model";
- ($result == $expected) ?: (print "failed directory 'models', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('python3_ve');
- $expected = $_test_home . "/BirdNET-Pi/birdnet/bin";
- ($result == $expected) ?: (print "failed directory 'python3_ve', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('scripts');
- $expected = $_test_home . "/BirdNET-Pi/scripts";
- ($result == $expected) ?: (print "failed directory 'scripts', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('stream_data');
- $expected = $_test_home . "/BirdSongs/StreamData";
- ($result == $expected) ?: (print "failed directory 'stream_data', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('templates');
- $expected = $_test_home . "/BirdNET-Pi/templates";
- ($result == $expected) ?: (print "failed directory 'templates', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('web');
- $expected = $_test_home . "/BirdNET-Pi/homepage";
- ($result == $expected) ?: (print "failed directory 'web', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getDirectory('web_fonts');
- $expected = $_test_home . "/BirdNET-Pi/homepage/static";
- ($result == $expected) ?: (print "failed directory 'web_fonts', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- ############################
- # FILE PATH TESTS
- ############################
- $result = getFilePath('analyzing_now.txt');
- $expected = $_test_home . "/BirdNET-Pi/analyzing_now.txt";
- ($result == $expected) ?: (print "failed file path 'analyzing_now.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('apprise.txt');
- $expected = $_test_home . "/BirdNET-Pi/apprise.txt";
- ($result == $expected) ?: (print "failed file path 'apprise.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('birdnet.conf');
- $expected = $_test_home . "/BirdNET-Pi/birdnet.conf";
- ($result == $expected) ?: (print "failed file path 'birdnet.conf', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('etc_birdnet.conf');
- $expected = "/etc/birdnet/birdnet.conf";
- ($result == $expected) ?: (print "failed file path 'etc_birdnet.conf', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('BirdDB.txt');
- $expected = $_test_home . "/BirdNET-Pi/BirdDB.txt";
- ($result == $expected) ?: (print "failed file path 'BirdDB.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('birds.db');
- $expected = $_test_home . "/BirdNET-Pi/scripts/birds.db";
- ($result == $expected) ?: (print "failed file path 'birds.db', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('blacklisted_images.txt');
- $expected = $_test_home . "/BirdNET-Pi/scripts/blacklisted_images.txt";
- ($result == $expected) ?: (print "failed file path 'blacklisted_images.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('disk_check_exclude.txt');
- $expected = $_test_home . "/BirdNET-Pi/scripts/disk_check_exclude.txt";
- ($result == $expected) ?: (print "failed file path 'disk_check_exclude.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('email_template');
- $expected = $_test_home . "/BirdNET-Pi/scripts/email_template";
- ($result == $expected) ?: (print "failed file path 'email_template', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('email_template2');
- $expected = $_test_home . "/BirdNET-Pi/scripts/email_template2";
- ($result == $expected) ?: (print "failed file path 'email_template2', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('exclude_species_list.txt');
- $expected = $_test_home . "/BirdNET-Pi/scripts/exclude_species_list.txt";
- ($result == $expected) ?: (print "failed file path 'exclude_species_list.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('firstrun.ini');
- $expected = $_test_home . "/BirdNET-Pi/firstrun.ini";
- ($result == $expected) ?: (print "failed file path 'firstrun.ini', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('filepath_map.json');
- $expected = $_test_home . "/BirdNET-Pi/config/filepath_map.json";
- ($result == $expected) ?: (print "failed file path 'filepath_map.json', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('.gotty');
- $expected = $_test_home . "/.gotty";
- ($result == $expected) ?: (print "failed file path '.gotty', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('HUMAN.txt');
- $expected = $_test_home . "/BirdNET-Pi/HUMAN.txt";
- ($result == $expected) ?: (print "failed file path 'HUMAN.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('IdentifiedSoFar.txt');
- $expected = $_test_home . "/BirdNET-Pi/IdentifiedSoFar.txt";
- ($result == $expected) ?: (print "failed file path 'IdentifiedSoFar.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('include_species_list.txt');
- $expected = $_test_home . "/BirdNET-Pi/scripts/include_species_list.txt";
- ($result == $expected) ?: (print "failed file path 'include_species_list.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('labels.txt');
- $expected = $_test_home . "/BirdNET-Pi/model/labels.txt";
- ($result == $expected) ?: (print "failed file path 'labels.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('labels.txt.old');
- $expected = $_test_home . "/BirdNET-Pi/model/labels.txt.old";
- ($result == $expected) ?: (print "failed file path 'labels.txt.old', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('labels_flickr.txt');
- $expected = $_test_home . "/BirdNET-Pi/model/labels_flickr.txt";
- ($result == $expected) ?: (print "failed file path 'labels_flickr.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('labels_l18n.zip');
- $expected = $_test_home . "/BirdNET-Pi/model/labels_l18n.zip";
- ($result == $expected) ?: (print "failed file path 'labels_l18n.zip', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('labels_lang.txt');
- $expected = $_test_home . "/BirdNET-Pi/model/labels_lang.txt";
- ($result == $expected) ?: (print "failed file path 'labels_lang.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('labels_nm.zip');
- $expected = $_test_home . "/BirdNET-Pi/model/labels_nm.zip";
- ($result == $expected) ?: (print "failed file path 'labels_nm.zip', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('lastrun.txt');
- $expected = $_test_home . "/BirdNET-Pi/scripts/lastrun.txt";
- ($result == $expected) ?: (print "failed file path 'lastrun.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('python3');
- $expected = $_test_home . "/BirdNET-Pi/birdnet/bin/python3 ";
- ($result == $expected) ?: (print "failed file path 'python3', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('python3_appraise');
- $expected = $_test_home . "/BirdNET-Pi/birdnet/bin/apprise ";
- ($result == $expected) ?: (print "failed file path 'python3_appraise', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('species.py');
- $expected = $_test_home . "/BirdNET-Pi/scripts/species.py";
- ($result == $expected) ?: (print "failed file path 'species.py', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- $result = getFilePath('thisrun.txt');
- $expected = $_test_home . "/BirdNET-Pi/scripts/thisrun.txt";
- ($result == $expected) ?: (print "failed file path 'thisrun.txt', expected: " . ($expected) . " got: " . ($result) . "\r\n");
-
- }
-}
-
-
-test();
-
-
-?>
\ No newline at end of file