пятница, 31 мая 2019 г.

Хочу на FreePBX динамические конференции с одноразовым паролем

Имеем: FreePBX, Exchange.
Задача: хочу динамические конференции, чтобы постоянно пароль менялся сам на произвольный и чтобы оповещение участников по почте приходило.

yum update -y && yum install epel-release -y && yum install ssmtp -y

Далее пишем файлы:
/var/www/html/conf.php:
<html>
<meta><title>It's easy to create new conference</title></meta>
<body>
<form method='POST' action='/makeconf.php'>
Please, enter emails of conference participants:<br>
<textarea name='emails' cols=80 rows=10>
username@domain.com
</textarea><br>
Enter here any additional text to include in email message:<br>
<textarea name='msg' cols=80 rows=10>
</textarea><br>
<input type='submit' value='Create'><br>
</form>
<br><br><br>
<font color=red><center><h3>WARNING!!!</h3>Conferences is valid only in today!!!<br>This conference will be automatically removed in 00:00</center></font>
</body>
</html>

/var/www/html/makeconf.php:
<?php
#
# Read values from conf.php
#
$emails=$_POST['emails'];
$msg=$_POST['msg'];
if (empty($emails)) {
echo "No emails were sent";
exit();
}
if ($email="") { echo "No emails were sent"; exit (); }
#
# Set default timezone
#
date_default_timezone_set('Asia/Yekaterinburg');
#
# Set database connection variables
#
$dbuser="freepbxuser";
$dbpass="5f2ecaef00a5bda7e7f16f00c616e484";
$dbname="asterisk";
#
# Trying to connect
#
echo "Connecting DB...";
$conn=mysqli_connect('localhost',$dbuser,$dbpass,$dbname);
if (!$conn) {
        die('Error connecting MySQL DB');
        exit();
} else {
        echo "OK<br>";
}
#
# Get MAX of extension number
#
echo "Get new conference number...";
$res=mysqli_query($conn,"SELECT MAX(exten) FROM meetme;");
if ( $res ) {
        echo "OK<br>";
} else {
        echo "Error";
        exit();
}
$row=mysqli_fetch_row($res);
#
# +1
#
$conf_num=$row[0];
$conf_num++;
#$res=mysqli_close($conn);
#
# Show conference number to user
#
echo "Conference Number: " .$conf_num ."<br>";
#
# Generate random PIN
#
echo "Generate new PIN...";
$newpin1=mt_rand(1000,9999);
$newpin=$newpin1;
echo $newpin."<br>";
#
# Convert current date/time to YYYY-MM-DD format
#
$date=date('Y-m-d');
#
# And insert it to the database
#
echo "Inserting values to MySQL DB for new conference...";

$query="insert into meetme (exten,options,userpin,description,timeout,adminpin,music) values (".$conf_num.",\"oTc\",".$newpin.",\"".$date."\",21600,\"\",\"inherit\");";
$res=mysqli_query($conn,$query);
#echo $query ."<br>";
if ( $res == TRUE ) {
        echo "OK<br>";
} else {
        echo "Error<br>";
        exit();
}
exec("asterisk -rx 'database put CONFERENCE/".$conf_num." userpin ".$newpin."'");
exec('mysqladmin refresh');
exec("fwconsole reload");
$pin=$newpin;
#
# Prepare email message
#
$message="Hello\nYou are invited to join conference ".$conf_num." with PIN:".$pin."\n\n".$msg;
$email=explode("\n",$emails);
$z=0;
#
# And send the emails
#
echo "Sending emails...<br>";
while ($email[$z]<>"") {
echo $email[$z]."...";
$res=mail($email[$z],"Conference invitation",$message);
if ( $res == TRUE ) {
        echo "OK<br>";
} else {
        echo "Error<br>";
}
$z++;
}
echo "Done<br>";
#
# Reload FreePBX configuration
#
echo "Reloading configuration of FreePBX<br>";
exec("fwconsole reload");
?>
<a href="/conf.php">Create another conference</a>


/var/www/html/remove_old_conf.php:
<?php
#
# This will remove all conferences by filter
# We are writing current date to the description field in makeconf.php
# So, if date from conference is lower than current date - we should remove it
#

#
# Set default timezone
#
date_default_timezone_set('Asia/Yekaterinburg');
#
# Database connection variables
#
$dbuser="freepbxuser";
$dbpass="freepbxuser_mysql_password";
$dbname="asterisk";
#
# And connecting
#
$conn=mysqli_connect('localhost',$dbuser,$dbpass,$dbname);
if (!$conn) {
        die('Error connecting MySQL DB');
        exit();
}
#
# Get conf numbers and descriptions
# If you have static conferences you won't remove - you should exclude it here or below or some other way
#
$res=mysqli_query($conn, "SELECT description,exten from meetme");
#
# Convert current date/time to YYYY-MM-DD format
#
$date=date('Y-m-d');
$z=0;
#
# And compare with exten description in cycle
#
while ($row=mysqli_fetch_row($res)) {
        $d=$row[0];
        $e=$row[1];
        if ($date > $d ) {
                #
                # If match - remove it and increment counter
                #
                echo "Remove ".$e."<br>\n";
                mysqli_query($conn, "DELETE FROM `meetme` where exten=".$e);
                $z++;
        }
}
#
# Show counter to user
#
echo "Removed ".$z ." items<br>\n";
#
# Reload FreePBX configuration
#
if ($z > "0") { exec("fwconsole reload"); } else { echo "nothing to reload<br>\n"; }
?>

/etc/crontab:
  59 23 *  *  * root php /var/www/html/remove_old_conf.php

/etc/ssmtp/revaliases:
asterisk:voip@domain.com:mail.domain.com:25

/etc/ssmtp/ssmtp.conf:
root=voip@domain.com
mailhub=mail.domain.com
RewriteDomain=domain.com
Hostname=voip.domain.com
FromLineOverride=Yes
UseStartTLS=No
Debug=No
AuthUser=voip
AuthPass=P@$$w)rD

Теперь сделаем, чтобы из IVR можно было добраться до конференции. У меня IVR, с которого я хочу сделать возможность звонить в конференцию - ivr-1.
/etc/asterisk/extensions_custom.conf:
[ivr-1-custom]
include =>ext-meetme

Делаем: mv /usr/sbin/sendmail /usr/sbin/sendmail.bak && ln -s /usr/sbin/ssmtp /usr/sbin/sendmail && service asterisk restart && service crond restart
И все должно заработать.
Это не совсем готовая инструкция, применяйте голову.
Теперь это готовый код. Проблема была в том, что нужно вручную записывать значение userpin через обращение к AstDB (ищите в коде database put)

Авторизацию на эту "админку" сами прикручивайте какую хотите.