1
0
moha/daemons/presenceDaemon.php

101 lines
2.1 KiB
PHP
Raw Normal View History

2022-09-01 18:48:20 +02:00
#!/usr/bin/php
<?php
define("EOL", "\n");
$title = "PresenceDaemon";
cli_set_process_title($title);
file_put_contents("/proc/".getmypid()."/comm",$title);
declare(ticks = 1);
require "/etc/moha/liste_telephones.php";
$msg = "";
$result = array();
$presence = array();
$curlErr = 0;
$command = "sudo nmap -n -sP 192.168.1.*"; //need to configure /etc/sudo/sudoers to permit execution of nmap as superuser
echo "presenceDaemon is starting\n";
while (1)
{
//echo "presenceDaemon is testing\n";
$msg = "";
exec($command, $result);
foreach ($macAddresses as $name =>$value)
{
if (!array_key_exists($name, $presence))
{
$presence[] = $name;
$presence[$name] = false;
}
$r = search($value, $result);
if ($r === true)
{
echo "présent\n";
if ($presence[$name] === false)
{
$presence[$name] = true;
$msg .= "nom=" . $name . _("&presence=true");
send($msg);
echo $name . " est mis présent dans tableau\n";
}
}elseif ($presence[$name] === true)
{
$presence[$name] = false;
echo $name . " est mis absent dans tableau\n";
$msg .= "nom=" . $name . _("&presence=false");
send($msg);
}
}
sleep(1);
}
function search($needle, $array)
{
foreach ($array as $string)
{
if (str_contains($string, $needle))
{
echo "found\n";
return true;
}
}
return false;
}
function send($msg)
{
global $curlErr;
$ch = curl_init();
$msg = "http://localhost:1025/present&" . $msg;
// set url
curl_setopt($ch, CURLOPT_URL, $msg );
// return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $result contains the output string
echo _("Curl sending message -") . __FILE__ . ":" . __LINE__ . EOL;
if ($curlErr <= 5)
{
echo $msg . EOL;
curl_exec($ch);
if (curl_errno($ch) != 0)
{
$curlErr += 1;
echo sprintf( _("Sleeping 1 minute because Curl return error %d: %s when sending notification - "), curl_errno($ch), curl_error($ch)) . __FILE__ . ":" . __LINE__ . EOL;
sleep (60);
}else
{
echo _("Curl return no error - ") . __FILE__ . ":" . __LINE__ . EOL;
$curlErr = 0;
}
}
}
?>