Page MenuHomePhabricator

No OneTemporary

This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/provisioning.phtml b/provisioning.phtml
index b07ca8f..f7758a9 100644
--- a/provisioning.phtml
+++ b/provisioning.phtml
@@ -1,72 +1,74 @@
<?
include("./global.inc");
page_open(
array("sess" => "CDRTool_Session",
"auth" => "CDRTool_Auth",
"perm" => "CDRTool_Perm"));
$title="Provisioning interface";
if (is_readable("local/header.phtml")) {
include("local/header.phtml");
} else {
include("header.phtml");
}
set_time_limit(600);
//$perm->check("admin");
require_once("provisioning/provisioning_soap_library.phtml");
require_once("provisioning/provisioning_logic.phtml");
$layout = new pageLayoutLocal();
$layout->showTopMenu();
// $soapEngines must be defined in global.inc
global $CDRTool;
if ($CDRTool['reseller']) {
$loginCredentials=array(
'reseller' => $CDRTool['reseller'],
'loginType' => 'reseller'
);
} else {
$loginCredentials=array(
'loginType' => 'admin'
);
}
$extraFormElements=array();
if ($_REQUEST['generatorId']) {
$generator = new recordGenerator($_REQUEST['generatorId'],$recordGenerators,$soapEngines,$extraFormElements,$loginCredentials);
if ($_REQUEST['action']=='Generate') {
$generator->generateRecords();
$generator->showGeneratorForm();
} else {
$generator->showGeneratorForm();
}
} else {
$SOAPEngine = new SOAPEngine($_REQUEST['service'],$soapEngines,$extraFormElements,$loginCredentials);
$_class = $SOAPEngine->recordsClass;
$RECORDS = new $_class(&$SOAPEngine);
if ($_REQUEST['action']=='Add') $RECORDS->addRecord();
if ($_REQUEST['action']=='Delete') $RECORDS->deleteRecord();
+ if ($_REQUEST['action']=='Update') $RECORDS->updateRecord();
+
if ($_REQUEST['action']=='PerformActions') {
$RECORDS->performActions();
} else {
$RECORDS->listRecords();
}
}
$layout->showFooter();
print "
</body>
</html>
";
page_close();
?>
\ No newline at end of file
diff --git a/provisioning/provisioning_logic.phtml b/provisioning/provisioning_logic.phtml
index b4ea101..f4cfec0 100644
--- a/provisioning/provisioning_logic.phtml
+++ b/provisioning/provisioning_logic.phtml
@@ -1,6091 +1,6255 @@
<?
class recordGenerator extends SOAPEngine {
var $template=array();
function recordGenerator($generatorId,$recordGenerators,$soapEngines,$extraFormElements,$loginCredentials) {
$this->recordGenerators = $recordGenerators;
$this->generatorId=$generatorId;
$keys = array_keys($this->recordGenerators);
if (!$generatorId) $generatorId=$keys[0];
if (!in_array($generatorId,array_keys($this->recordGenerators))) {
return false;
}
// sip zones
$sipEngine = $this->recordGenerators[$generatorId]['sipEngineId'].'@'.'SIP accounts';
$this->SipSOAPEngine = new SOAPEngine($sipEngine,$soapEngines,$extraFormElements,$loginCredentials);
$_sip_class = $this->SipSOAPEngine->recordsClass;
$this->sipRecords = new $_sip_class(&$this->SipSOAPEngine);
$this->sipRecords->getAllowedDomains();
// enum mappings
$enumEngine = $this->recordGenerators[$generatorId]['enumEngineId'].'@'.'ENUM Numbers';
$this->EnumSOAPEngine = new SOAPEngine($enumEngine,$soapEngines,$extraFormElements,$loginCredentials);
$_enum_class = $this->EnumSOAPEngine->recordsClass;
$this->enumRecords = new $_enum_class(&$this->EnumSOAPEngine);
$this->enumRecords->getAllowedDomains();
}
function generateRecords() {
print "<p>Generating records
<ol>";
if (!$this->checkGenerateRequest()) return false;
$i=0;
while ($i < $this->template['nr_records']) {
$number = sprintf("%.0f", $this->start_padded + $i);
$username = substr($number,$this->template['strip_digits']);
$mapto = 'sip:'.$username.'@'.$this->template['domain'];
print "<li>";
printf ('Generating number +%s with mapping %s ',$number,$mapto);
flush();
$enumMapping = array('tld' => $this->template['tld'],
'number' => $number,
'type' => 'sip',
'mapto' => $mapto,
'owner' => $this->template['owner']
);
if ($this->template['create_sip']) {
$groups=array();
if ($this->template['pstn']) $groups[]='free-pstn';
printf ('and sip account %s@%s ',$username,$this->template['domain']);
$sipAccount = array('account' => $username.'@'.$this->template['domain'],
'owner' => $this->template['owner'],
'quota' => $this->template['quota'],
'prepaid' => $this->template['prepaid'],
'password' => $this->template['password'],
'groups' => $groups
);
} else {
unset($sipAccount);
}
if (is_array($enumMapping)) $this->enumRecords->addRecord($enumMapping);
if (is_array($sipAccount)) $this->sipRecords->addRecord($sipAccount);
$i++;
}
print "</ol>";
return true;
}
function checkGenerateRequest() {
// check number of records
$this->template['create_sip']=trim($_REQUEST['create_sip']);
$nr_records=trim($_REQUEST['nr_records']);
if (!is_numeric($nr_records) || $nr_records < 1 || $nr_records > 200) {
print "Error: number of records must be a number between 1 and 200.";
return false;
}
$this->template['nr_records'] = $nr_records;
// length of generated record
$len=trim($_REQUEST['len']);
if (!is_numeric($len) || $len < 4 || $len > 15) {
print "Error: number length must be a number between 4 and 15.";
return false;
}
$this->template['len'] = $len;
// sip domain
$domain=trim($_REQUEST['domain']);
if (!strlen($domain)) {
print "Error: SIP domain missing";
return false;
}
$this->template['domain'] = $domain;
$nr_start=trim($_REQUEST['nr_start']);
if (strlen($nr_start) && !is_numeric($nr_start)) {
print "Error: Use prefix must be numeric";
return false;
}
$this->template['nr_start'] = $nr_start;
// check ENUM TLD
list($prefix,$tld)=explode('@',trim($_REQUEST['range']));
$this->template['prefix'] = intval($prefix);
$this->template['tld'] = $tld;
$this->template['quota'] = intval($_REQUEST['quota']);
$this->template['owner'] = intval($_REQUEST['owner']);
$this->template['pstn'] = intval($_REQUEST['pstn']);
$this->template['prepaid'] = intval($_REQUEST['prepaid']);
$this->template['password'] = trim($_REQUEST['password']);
///////////////////////////////////////
// logical checks
if (strlen($this->template['nr_start'])) {
$start = $this->template['nr_start'];
} else {
$start = 0;
}
$digits = $this->template['len']-strlen($this->template['prefix']);
$this->start_padded = $this->template['prefix'].str_pad($start,$digits,'0');
$this->top = sprintf("%.0f", $this->start_padded + pow(10,$digits-strlen($this->template['nr_start'])));
$maxNumbers = pow(10,$digits-strlen($this->template['nr_start']));
if ($maxNumbers < $this->template['nr_records']) {
printf ("Error: Insufficient numbers in range, requested = %d, available = %d",$this->template['nr_records'],$maxNumbers);
return false;
}
return true;
}
function showGeneratorForm() {
if (!count($this->enumRecords->ranges)) return false;
print "
<form method=post target=_new>
<table cellspacing=1 cellpadding=1 bgcolor=black>
<tr>
<td>
<table cellspacing=3 cellpadding=4 width=100% bgcolor=#444444>
<tr>
<td>
<font color=white>
<b>";
print _("Record generator");
print "</b>
</font>
</td>
</tr>
</table>
</tr>
<tr>
<td colspan=100%>
<table cellpadding=2 bgcolor=white width=100%>
<tr>
<td colspan=3>
</td>
</tr>
";
print "
<tr>
<td>";
print _("Range");
print "
<td align=right>";
if (is_array($this->enumRecords->ranges)) {
print "<select name=range>";
$selected_range[$_REQUEST['range']]='selected';
foreach ($this->enumRecords->ranges as $_range) {
$rangeId=$_range['prefix'].'@'.$_range['tld'];
printf ("<option value=%s %s>+%s under %s",$rangeId,$selected_range[$rangeId],$_range['prefix'],$_range['tld']);
}
print "</select>";
}
print "<td>
</tr>
";
print "
<tr>
<td colspan=2>
";
print "<b>";
print _("ENUM mapping template");
print "</b>";
print "</td>
</tr>
";
print "
<tr>
<td>";
print _("Use prefix:");
printf ("
<td align=right>
<input type=text name=nr_start size=10 maxsize=15 value='%s'>
</td>
</tr>
",$_REQUEST['nr_start']);
print "
<tr>
<td>";
print _("Number length:");
printf ("
<td align=right>
<input type=text name=len size=10 maxsize=15 value='%s'>
<tr>
<td>
",$_REQUEST['len']);
print _("SIP domain");
print "
<td align=right>
";
if (count($this->sipRecords->allowedDomains)) {
print "
<select name=domain>
";
$selected_range[$_REQUEST['domain']]='selected';
foreach ($this->sipRecords->allowedDomains as $domain) {
printf ("<option value='%s' %s>%s",$domain,$selected_range[$domain],$domain);
}
print "</select> ";
} else {
print "<input type=text size=15 name=domain>";
}
print "
</td>
<td>";
print "
</td>
</tr>
";
print "
<tr>
<td>";
print _("Strip from username");
printf ("
<td align=right>first
<input type=text size=5 name=strip_digits value='%s'>digits
</td>
</tr>
",$_REQUEST['strip_digits']);
print "
<tr>
<td>";
print _("Owner");
printf ("
<td align=right><input type=text size=6 maxsize=6 name=owner value='%s'>
<td>",$_REQUEST['owner']);
print "
</td>
</tr>";
if (count($this->sipRecords->allowedDomains)) {
print "
<tr>
<td colspan=3><hr noshade size=1>
</td>
</tr>
";
print "
<tr>
<td colspan=2>
";
print "<b>";
print _("SIP account template");
print "</b>";
print "</td>
</tr>
";
print "
<tr>
<td>";
print _("Create SIP records");
if ($_REQUEST['create_sip']) {
$checked_create_sip='checked';
} else {
$checked_create_sip='';
}
printf ("
<td align=right><input type=checkbox name=create_sip value=1 %s>
</td>
</tr>
",$checked_create_sip);
if ($_REQUEST['pstn']) {
$checked_pstn='checked';
} else {
$checked_pstn='';
}
print "
<tr>
<td>";
print _("PSTN");
printf ("
<td align=right><input type=checkbox name=pstn value=1 %s>
</td>
</tr>
",$checked_pstn);
if ($_REQUEST['prepaid']) {
$checked_prepaid='checked';
} else {
$checked_prepaid='';
}
print "
<tr>
<td>";
print _("Prepaid");
printf ("
<td align=right><input type=checkbox name=prepaid value=1 %s>
</td>
</tr>
",$checked_prepaid);
print "
<tr>
<td>";
print _("Prefix Caller-ID");
printf ("
<td align=right><input type=text size=5 name=rpid_prefix value='%s'>
</td>
</tr>
",$_REQUEST['rpid_prefix']);
print "
<tr>
<td>";
print _("Quota");
printf ("
<td align=right><input type=text size=5 name=quota value='%s'>
</td>
</tr>
",$_REQUEST['quota']);
print "
<tr>
<td>";
print _("Password");
printf ("
<td align=right><input type=text size=15 name=password value='%s'>
</td>
</tr>
",$_REQUEST['password']);
print "
<tr>
<td colspan=3>
<hr noshade size=1 with=100%>
</td>
</tr>
";
print "
<tr>
<td>
";
if ($_REQUEST['nr_records']) {
$nr_records=$_REQUEST['nr_records'];
} else {
$nr_records=1;
}
print "<input type=hidden value=Generate>";
print "<input type=submit value=";
print _("Generate");
print ">";
printf ("<td align=right>
<input type=text size=4 name=nr_records value='%s'>
",$nr_records);
print _("records");
print "<td>";
print "
</tr>
";
print "
<tr>
<td colspan=2>
<br>
<input type=hidden name=action value=Generate>
<p>";
print _("Existing records will not be overwritten. ");
print "</td>
</tr>
";
}
$this->printHiddenFormElements();
print "
</table>
</form>
</td>
</tr>
</table>
";
}
function printHiddenFormElements () {
printf("<input type=hidden name=generatorId value='%s'>",$this->generatorId);
if ($this->adminonly) {
printf("<input type=hidden name=adminonly value='%s'>",$this->adminonly);
}
foreach (array_keys($this->extraFormElements) as $element) {
if (!strlen($this->extraFormElements[$element])) continue;
printf ("<input type=hidden name=%s value='%s'>\n",$element,$this->extraFormElements[$element]);
}
}
}
class SOAPEngine {
var $version = 1;
var $adminonly = 0;
var $reseller = 0;
var $loginType = 'reseller';
var $services=array(
'SIP accounts' => array('recordsClass' => 'SipAccounts',
'soapClass' => 'WebService_NGNPro_SipPort'
),
'SIP Aliases' => array('recordsClass' => 'SipAliases',
'soapClass' => 'WebService_NGNPro_SipPort'
),
'SIP Domains' => array('recordsClass' => 'Domains',
'soapClass' => 'WebService_NGNPro_SipPort'
),
'SIP Usage' => array('recordsClass' => 'DomainStatistics',
'soapClass' => 'WebService_NGNPro_SipPort'
),
'ENUM Numbers' => array('recordsClass' => 'EnumMappings',
'soapClass' => 'WebService_NGNPro_EnumPort'
),
'ENUM Ranges' => array('recordsClass' => 'EnumRanges',
'soapClass' => 'WebService_NGNPro_EnumPort'
),
'Trusted Peers' => array('recordsClass' => 'TrustedPeers',
'soapClass' => 'WebService_NGNPro_SipPort'
),
'PSTN Gateways' => array('recordsClass' => 'Gateways',
'soapClass' => 'WebService_NGNPro_NetworkPort'
),
'Gateway groups' => array('recordsClass' => 'GatewayGroups',
'soapClass' => 'WebService_NGNPro_NetworkPort'
),
'PSTN Routes' => array('recordsClass' => 'Routes',
'soapClass' => 'WebService_NGNPro_NetworkPort'
),
'Operators' => array('recordsClass' => 'Customers',
'soapClass' => 'WebService_NGNPro_CustomerPort'
)
);
function SOAPEngine($service,$soapEngines,$extraFormElements,$loginCredentials) {
/*
$soapEngines=array(
'mdns' => array('name'=> 'Managed DNS',
'username'=> 'soapadmin',
'password'=> 'passwd',
'url' => 'http://example.com:9200/',
'impersonate' => 1745
),
*/
if ($loginCredentials['loginType'] == 'admin') $this->adminonly = 1;
$this->loginType = $loginCredentials['loginType'];
$this->soapEngines = $soapEngines;
if (is_array($this->soapEngines)) {
if (!$service) {
$_services = array_keys($this->services);
$_soapids = array_keys($this->soapEngines);
$service = $_soapids[0].'@'.$_services[0];
}
if (is_array($extraFormElements)) {
$this->extraFormElements = $extraFormElements;
}
$this->service = $service;
$_els=explode('@',$this->service);
$this->soapEngineId = $_els[0];
$this->soapEngineIdSettingsPage=$this->soapEngineId;
$this->soapEnginePort = $_els[1];
$this->recordsClass = $this->services[$this->soapEnginePort]['recordsClass'];
$this->soapClass = $this->services[$this->soapEnginePort]['soapClass'];
foreach(array_keys($this->soapEngines) as $_key ) {
$this->skipServices[$_key]=$this->soapEngines[$_key]['skipServices'];
$this->skip[$_key]=$this->soapEngines[$_key]['skip'];
}
if (strlen($this->soapEngines[$this->soapEngineId]['version'])) {
$this->version = $this->soapEngines[$this->soapEngineId]['version'];
}
$this->defaultEnumTLD = $this->soapEngines[$this->soapEngineId]['defaultEnumTLD'];
if (!$loginCredentials['reseller'] && $this->soapEngines[$this->soapEngineId]['impersonate']) {
$this->reseller = $this->soapEngines[$this->soapEngineId]['impersonate'];
} else if (strlen($loginCredentials['reseller'])) {
$this->reseller = $loginCredentials['reseller'];
}
if (strlen($loginCredentials['customer'])) {
$this->reseller = $loginCredentials['customer'];
}
if (strlen($this->soapEngines[$this->soapEngineId]['soapEngineIdSettingsPage'])) {
$this->soapEngineIdSettingsPage=$this->soapEngines[$this->soapEngineId]['soapEngineIdSettingsPage'];
}
if (strlen($this->soapEngines[$this->soapEngineId]['recordGenerator'])) {
$this->recordGenerator=$this->soapEngines[$this->soapEngineId]['recordGenerator'];
}
$this->SOAPlogin = array(
"username" => $this->soapEngines[$this->soapEngineId]['username'],
"password" => $this->soapEngines[$this->soapEngineId]['password'],
"admin" => true,
"impersonate" => intval($this->reseller)
);
$this->SOAPurl=$this->soapEngines[$this->soapEngineId]['url'];
printf ("Connection to %s at <a href=%swsdl target=wsdl>%s</a> as %s/%s ",$this->soapClass,$this->SOAPurl,$this->SOAPurl,$this->soapEngines[$this->soapEngineId]['username'],$this->reseller);
$this->SoapAuth = array('auth', $this->SOAPlogin , 'urn:AGProjects:NGNPro', 0, '');
// Instantiate the SOAP client
if (!class_exists($this->soapClass)) return ;
$this->soapclient = new $this->soapClass($this->SOAPurl);
$this->soapclient->setOpt('curl', CURLOPT_TIMEOUT, 5);
$this->soapclient->setOpt('curl', CURLOPT_SSL_VERIFYPEER, 0);
$this->soapclient->setOpt('curl', CURLOPT_SSL_VERIFYHOST, 0);
$this->soapRemoteId=$this->soapEngines[$this->soapEngineId]['depends'];
if (strlen($this->soapRemoteId) && in_array($this->soapRemoteId,array_keys($this->soapEngines))) {
$this->soapEngineIdRemote = $this->soapEngines[$this->soapRemoteId];
$impersonateRemote=intval($this->soapEngines[$this->soapRemoteId]['impersonate']);
$this->SOAPloginRemote = array(
"username" => $this->soapEngines[$this->soapRemoteId]['username'],
"password" => $this->soapEngines[$this->soapRemoteId]['password'],
"admin" => true,
"impersonate" => $impersonateRemote
);
//print_r($this->SOAPloginRemote);
$this->SOAPurlRemote=$this->soapEngines[$this->soapRemoteId]['url'];
printf ("and syncronize writes at <a href=%swsdl target=wsdl>%s</a>",$this->SOAPurlRemote,$this->SOAPurlRemote);
$this->SoapAuthRemote = array('auth', $this->SOAPloginRemote , 'urn:AGProjects:NGNPro', 0, '');
// Instantiate the SOAP client depends
$this->soapclientRemote = new $this->soapClass($this->SOAPurlRemote);
$this->soapclientRemote->setOpt('curl', CURLOPT_TIMEOUT, 5);
$this->soapclientRemote->setOpt('curl', CURLOPT_SSL_VERIFYPEER, 0);
$this->soapclientRemote->setOpt('curl', CURLOPT_SSL_VERIFYHOST, 0);
}
if ($this->version > 1) {
$this->soapclientCustomers = new WebService_NGNPro_CustomerPort($this->SOAPurl);
$this->soapclientCustomers->setOpt('curl', CURLOPT_TIMEOUT, 5);
$this->soapclientCustomers->setOpt('curl', CURLOPT_SSL_VERIFYPEER, 0);
$this->soapclientCustomers->setOpt('curl', CURLOPT_SSL_VERIFYHOST, 0);
}
} else {
print "<font color=red>Error: No SOAP credentials defined.</font>";
}
$this->url = $_SERVER['PHP_SELF']."?1=1";
foreach (array_keys($this->extraFormElements) as $element) {
if (!strlen($this->extraFormElements[$element])) continue;
$this->url .= sprintf('&%s=%s',$element,urlencode($this->extraFormElements[$element]));
}
}
function execute($function) {
/*
$function=array('commit' => array('name' => 'addAccount',
'parameters' => array($param1,$param2),
'logs' => array('success' => 'The function was a success',
'failure' => 'The function has failed'
)
),
'rollback' => array('name' => 'addAccount',
'parameters' => array($param1,$param2),
'logs' => array('success' => 'The function was a success',
'failure' => 'The function has failed'
)
)
);
*/
if (!$function['commit']['name']) {
print "<font color=red>Error: no function name supplied</font>";
return false;
}
if (is_object($this->soapclientRemote)) {
$this->soapclientRemote->addHeader($this->SoapAuthRemote);
$resultRemote = call_user_func_array(array($this->soapclientRemote,$function['commit']['name']),$function['commit']['parameters']);
if (PEAR::isError($resultRemote)) {
$error_msg=$resultRemote->getMessage();
$error_fault=$resultRemote->getFault();
$error_code=$resultRemote->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPurlRemote,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>%s %s </font>",$function['commit']['logs']['success'],$this->SOAPurlRemote);
$this->soapclient->addHeader($this->SoapAuth);
$result = call_user_func_array(array($this->soapclient,$function['commit']['name']),$function['commit']['parameters']);
if (PEAR::isError($result)) {
$error_msg=$result->getMessage();
$error_fault=$result->getFault();
$error_code=$result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
if ($function['rollback']['name']) {
$this->soapclientRemote->addHeader($this->SoapAuthRemote);
$this->counterRemote++;
$resultRemote = call_user_func_array(array($this->soapclientRemote,$function['rollback']['name']),$function['rollback']['parameters']);
if (PEAR::isError($result)) {
$error_msg=$result->getMessage();
$error_fault=$result->getFault();
$error_code=$result->getCode();
printf ("<p><font color=red>Error roll back at %s: %s (%s): %s</font>",$this->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
} else {
printf ("<p><font color=green>Rolled back action at %s </font>",$this->SOAPurlRemote);
}
}
return false;
} else {
if ($function['commit']['logs']['success']) {
printf ("<p><font color=green>%s %s </font>",$function['commit']['logs']['success'],$this->SOAPurl);
}
}
}
} else {
$this->soapclient->addHeader($this->SoapAuth);
$result = call_user_func_array(array($this->soapclient,$function['commit']['name']),$function['commit']['parameters']);
if (PEAR::isError($result)) {
$error_msg=$result->getMessage();
$error_fault=$result->getFault();
$error_code=$result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
if ($function['commit']['logs']['success']) {
printf ("<p><font color=green>%s </font>",$function['commit']['logs']['success']);
}
}
}
return true;
}
}
class Records {
var $maxrowsperpage = '15';
var $SipSettingsPage = 'sip_settings.phtml';
var $allowedDomains = false;
var $selectionActive = false;
var $selectionKeys = array();
var $resellers = array();
var $customers = array();
var $recordGenerator = false;
function Records(&$SOAPEngine) {
$this->SOAPEngine = &$SOAPEngine;
$this->version = $this->SOAPEngine->version;
$this->sorting['sortBy'] = trim($_REQUEST['sortBy']);
$this->sorting['sortOrder'] = trim($_REQUEST['sortOrder']);
$this->next = $_REQUEST['next'];
$this->adminonly = $this->SOAPEngine->adminonly;
$this->reseller = $this->SOAPEngine->reseller;
$this->url = $this->SOAPEngine->url;
$this->loginType = $this->SOAPEngine->loginType;
foreach(array_keys($this->filters) as $_filter) {
if (strlen($this->filters[$_filter])) {
$this->selectionActive=true;
break;
}
}
if ($this->adminonly) {
$this->url .= sprintf('&adminonly=%s',$this->adminonly);
}
$this->filters['customer']=trim($_REQUEST['customer_filter']);
if (!$this->adminonly && $this->reseller) {
// Force filter if reseller
$this->filters['reseller']=$this->reseller;
} else {
$this->filters['reseller']=trim($_REQUEST['reseller_filter']);
}
$this->getResellers();
$this->getCustomers();
//printf ('<p>%s',$this->url);
}
function showEngineSelection() {
$selected_soapEngine[$this->SOAPEngine->service]='selected';
printf ("<select name=service onChange=\"document.soapengine.submit.disabled = true; location.href = '%s&service=' + this.options[this.selectedIndex].value\">",$this->url);
$j=1;
foreach (array_keys($this->SOAPEngine->soapEngines) as $_engine) {
if ($this->SOAPEngine->skip[$_engine]) continue;
if ($j>1) printf ("<option value=''>--------");
$k=1;
foreach (array_keys($this->SOAPEngine->services) as $_service) {
$idx=$_engine.'@'.$_service;
if (in_array($_service,$this->SOAPEngine->skipServices[$_engine])) continue;
if ($_engine == 'Operators' && $this->version <= 1) continue;
printf ("<option value='%s@%s' %s>%d.%d %s@%s",$_engine,$_service,$selected_soapEngine[$idx],$j,$k,ucfirst($_service),$this->SOAPEngine->soapEngines[$_engine]['name']);
$k++;
}
$j++;
}
printf ("</select>");
print "OP";
if ($this->adminonly) {
$this->showResellerForm();
if ($this->filters['reseller']) {
print ".";
$this->showCustomerForm();
}
} else {
printf ("%s",$this->reseller);
print ".";
$this->showCustomerForm();
}
}
function showPagination($maxrows) {
$url .= $this->url.'&'.$this->addFiltersToURL().
sprintf("&service=%s&sortBy=%s&sortOrder=%s",
urlencode($this->SOAPEngine->service),
urlencode($this->sorting['sortBy']),
urlencode($this->sorting['sortOrder'])
);
print "
<p>
<table border=0 align=center>
<tr>
<td>
";
if ($this->next != 0 ) {
$show_next=$this->maxrowsperpage-$this->next;
if ($show_next < 0) {
$mod_show_next = $show_next-2*$show_next;
}
if (!$mod_show_next) $mod_show_next=0;
if ($mod_show_next/$this->maxrowsperpage >= 1) {
printf ("<a href='%s&next=0'>Begin</a> ",$url);
}
printf ("<a href='%s&next=%s'>Previous</a> ",$url,$mod_show_next);
}
print "
</td>
<td>
";
if ($this->next + $this->maxrowsperpage < $this->rows) {
$show_next = $this->maxrowsperpage + $this->next;
printf ("<a href='%s&next=%s'>Next</a> ",$url,$show_next);
}
print "
</td>
</tr>
</table>
";
}
function showSeachFormCustom() {
}
function showSeachForm() {
print "
<p>
<table border=0 class=border width=100%>
<tr>
";
printf ("<form method=post name=soapengine action=%s>",$_SERVER['PHP_SELF']);
print "
<td align=left>
";
$this->showEngineSelection();
$this->showSeachFormCustom();
print "
</td>
<td align=right>
";
$this->showSortForm();
print "
<input type=submit name=action value=Search>
";
$this->printHiddenFormElements();
print "
</td>
</form>
</tr>
</table>
";
if ($_REQUEST['action'] != 'Delete') $this->showAddForm();
}
function listRecords() {
}
function getRecordKeys() {
}
function addRecord() {
}
function deleteRecord() {
}
function tel2enum($tel,$tld) {
if (strlen($tld) == 0) $tld="e164.arpa";
// transform telephone number in FQDN Enum style domain name
if (preg_match("/^[+]?(\d+)$/",$tel,$m)) {
$l=strlen($m[1]);
$rev_num="";
$z=0;
while ($z < $l) {
$ss=substr($m[1],$z,1);
$enum=$ss.".".$enum;
$z++;
}
preg_match("/^(.*)\.$/",$enum,$m);
$enum=$m[1];
$enum=$enum.".$tld.";
return($enum);
} else {
return($tel);
}
}
function showAddForm() {
if ($this->selectionActive) return;
}
function showSortForm() {
if (!count($this->sortElements)) {
return;
}
$selected_sortBy[$this->sorting['sortBy']]='selected';
//print " Sort ";
print "<select name=sortBy>";
foreach (array_keys($this->sortElements) as $key) {
printf ("<option value='%s' %s>%s",$key,$selected_sortBy[$key],$this->sortElements[$key]);
}
print "</select>";
$selected_sortOrder[$this->sorting['sortOrder']]='selected';
print "<select name=sortOrder>";
printf ("<option value='DESC' %s>DESC",$selected_sortOrder['DESC']);
printf ("<option value='ASC' %s>ASC",$selected_sortOrder['ASC']);
print "</select>";
}
function showTimezones() {
if (!$fp = fopen("timezones", "r")) {
print _("Failed to open timezone file.");
return false;
}
print "<select name=timezone>";
print "<option>";
while ($buffer = fgets($fp,1024)) {
$buffer=trim($buffer);
if ($this->timezone==$buffer) {
$selected="selected";
} else {
$selected="";
}
printf ("<option %s>%s>",$selected,$buffer);
}
print "</select>";
fclose($fp);
}
function printHiddenFormElements () {
printf("<input type=hidden name=service value='%s'>",$this->SOAPEngine->service);
if ($this->adminonly) {
printf("<input type=hidden name=adminonly value='%s'>",$this->adminonly);
}
foreach (array_keys($this->SOAPEngine->extraFormElements) as $element) {
if (!strlen($this->SOAPEngine->extraFormElements[$element])) continue;
printf ("<input type=hidden name=%s value='%s'>\n",$element,$this->SOAPEngine->extraFormElements[$element]);
}
}
function getAllowedDomains() {
}
function showActionsForm() {
if (!$this->selectionActive) {
return;
}
$class_name=get_class($this).'Actions';
if (class_exists($class_name)) {
$actions=new $class_name(&$this->SOAPEngine);
$actions->showActionsForm($this->filters,$this->sorting);
}
}
function performActions() {
$this->showSeachForm();
$this->getRecordKeys();
//print_r($this->selectionKeys);
$class_name=get_class($this).'Actions';
if (class_exists($class_name)) {
$actions=new $class_name(&$this->SOAPEngine);
$actions->performActions(&$this->selectionKeys,$_REQUEST['sub_action'],trim($_REQUEST['sub_action_parameter']));
}
}
function getCustomers() {
if (!$this->version <= 1 ) return;
if (!$this->filters['reseller']) {
return;
}
// Filter
$filter=array('reseller'=>intval($this->filters['reseller']));
$range=array('start' => 0,
'count' => 100
);
// Order
$orderBy = array('attribute' => 'customer',
'direction' => 'ASC'
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
// Insert credetials
$this->SOAPEngine->soapclientCustomers->addHeader($this->SOAPEngine->SoapAuth);
// Call function
$result = $this->SOAPEngine->soapclientCustomers->getCustomers($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
if ($result->total > $range['count']) return;
if ($range['count'] <= $result->total) {
$max=$range['count'];
} else {
$max=$result->total;
}
$i=0;
while ($i < $max) {
$customer=$result->accounts[$i];
$this->customers[$customer->id] = $customer->firstName.' '.$customer->lastName;
$i++;
}
return true;
}
}
function getResellers() {
if (!$this->version <= 1 ) return;
if (!$this->adminonly) {
return;
}
// Filter
$filter=array('reseller'=>intval($this->filters['reseller']));
$range=array('start' => 0,
'count' => 200
);
// Order
$orderBy = array('attribute' => 'customer',
'direction' => 'ASC'
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
// Insert credetials
$this->SOAPEngine->soapclientCustomers->addHeader($this->SOAPEngine->SoapAuth);
// Call function
$result = $this->SOAPEngine->soapclientCustomers->getResellers($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
//if ($result->total > $range['count']) return;
if ($range['count'] <= $result->total) {
$max=$range['count'];
} else {
$max=$result->total;
}
$i=0;
while ($i < $max) {
$reseller = $result->accounts[$i];
if (strlen($reseller->organization) && $reseller->organization!= 'N/A') {
$this->resellers[$reseller->id] = $reseller->organization;
} else {
$this->resellers[$reseller->id] = $reseller->firstName.' '.$reseller->lastName;
}
$i++;
}
//print_r($this->resellers);
return true;
}
}
function showCustomerForm($name='customer_filter') {
if (count($this->customers) && count($this->customers) < 200) {
$select_customer[$this->filters['customer']]='selected';
printf ("<select name=%s>",$name);
print "<option>";
foreach (array_keys($this->customers) as $_res) {
printf ("<option value='%s' %s>%s (%s)\n",$_res,$select_customer[$_res],$_res,$this->customers[$_res]);
}
print "</select>";
} else {
printf ("<input type=text size=5 name=%s value='%s'>",$name,$this->filters['customer']);
}
}
function showResellerForm($name='reseller_filter') {
if (count($this->resellers) && count($this->resellers) < 200) {
$select_reseller[$this->filters['reseller']]='selected';
printf ("<select name=%s>",$name);
print "<option>";
foreach (array_keys($this->resellers) as $_res) {
printf ("<option value='%s' %s>%s (%s)\n",$_res,$select_reseller[$_res],$_res,$this->resellers[$_res]);
}
print "</select>";
} else {
printf ("<input type=text size=5 name=%s value='%s'>",$name,$this->filters['reseller']);
}
}
function addFiltersToURL() {
$j=0;
foreach(array_keys($this->filters) as $filter) {
if (strlen(trim($this->filters[$filter]))) {
if ($j) $url .='&';
$url .= sprintf('%s_filter=%s',$filter,urlencode(trim($this->filters[$filter])));
}
$j++;
}
return $url;
}
+
+ function printFiltersToForm() {
+ foreach(array_keys($this->filters) as $filter) {
+ if (strlen(trim($this->filters[$filter]))) {
+ printf("<input type=hidden name=%s_filter value='%s'>",$filter,trim($this->filters[$filter]));
+ }
+ }
+ }
+
+ function updateRecord () {
+ }
}
class Domains extends Records {
var $maxrowsperpage= 200;
function Domains(&$SOAPEngine) {
$this->filters = array(
'domain' => trim($_REQUEST['domain_filter'])
);
$this->Records(&$SOAPEngine);
}
function listRecords() {
$this->showSeachForm();
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$filter=$this->filters['domain'];
// Call function
$result = $this->SOAPEngine->soapclient->getDomains($filter);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
$this->rows = count($result);
if ($this->rows && $_REQUEST['action'] != 'PerformActions' && $_REQUEST['action'] != 'Delete') {
$this->showActionsForm();
}
print "
<table border=0 align=center>
<tr><td>$this->rows records found</td></tr>
</table>
<p>
<table border=0 cellpadding=2 width=100%>
<tr bgcolor=lightgrey>
<td><b>Id</b></th>
";
if ($this->version > 1) print "<td><b>Operator</b></td>";
print"
<td><b>Domain</b></td>
<td><b>Last change</b></td>
<td><b>Action</b></td>
</tr>
";
if (!$this->next) $this->next=0;
if ($this->rows > $this->maxrowsperpage) {
$maxrows = $this->maxrowsperpage + $this->next;
if ($maxrows > $this->rows) $maxrows = $this->maxrowsperpage;
} else {
$maxrows=$this->rows;
}
$i=0;
if ($this->rows) {
while ($i < $maxrows) {
$domain = $result[$i];
$index = $this->next+$i+1;
$rr=floor($index/2);
$mod=$index-$rr*2;
if ($mod ==0) {
$bgcolor="lightgrey";
} else {
$bgcolor="white";
}
$_url = $this->url.sprintf("&service=%s&action=Delete&domain_filter=%s",
urlencode($this->SOAPEngine->service),
urlencode($domain)
);
if ($_REQUEST['action'] == 'Delete' &&
$_REQUEST['domain_filter'] == $domain) {
$_url .= "&confirm=1";
$actionText = "<font color=red>Confirm</font>";
} else {
$actionText = "Delete";
}
if ($this->version > 1) {
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>%s.%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
$index,
$domain->customer,
$domain->reseller,
$domain,
$domain->changeDate,
$_url,
$actionText
);
} else {
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
$index,
$domain,
$domain->changeDate,
$_url,
$actionText
);
}
$i++;
}
}
print "</table>";
$this->showPagination($maxrows);
return true;
}
}
function showSeachFormCustom() {
printf (" Domain<input type=text size=15 name=domain_filter value='%s'>",$this->filters['domain']);
}
function deleteRecord() {
if (!$_REQUEST['confirm']) {
print "<p><font color=red>Please press on Confirm to confirm the delete. </font>";
return 1;
}
if (!strlen($this->filters['domain']) || !strlen($this->filters['domain'])) {
print "<p><font color=red>Error: missing SIP domain. </font>";
return 0;
}
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->deleteDomain($this->filters['domain']);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>SIP domain %s has been deleted. </font> ",$this->filters['domain']);
unset($this->filters);
return 1;
}
}
function showAddForm() {
if ($this->selectionActive) return;
print "
<p>
<table border=0 class=border width=100%>
<tr>
";
printf ("<form method=post name=addform action=%s>",$_SERVER['PHP_SELF']);
print "
<td align=left>
";
print "
<input type=submit name=action value=Add>
";
printf (" Domain<input type=text size=20 name=domain>");
print "OP";
if ($this->adminonly) {
$this->showResellerForm('reseller');
print ".";
$this->showCustomerForm('customer');
} else {
$this->showCustomerForm('customer');
}
print "
</td>
<td align=right>
";
print "
</td>
";
$this->printHiddenFormElements();
print "
</form>
</tr>
</table>
";
}
function addRecord() {
$domain = trim($_REQUEST['domain']);
if ($this->adminonly) {
$reseller = trim($_REQUEST['reseller']);
$customer = trim($_REQUEST['customer']);
} else {
$reseller = $this->reseller;
$customer = trim($_REQUEST['customer']);
if (!$customer || !in_array($customer,array_keys($this->customers))) {
$customer=$reseller;
}
}
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->addDomain($domain);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>SIP domain %s has been added. </font>",$domain);
return true;
}
}
}
class SIPAccounts extends Records {
var $sortElements=array('changeDate' => 'Change date',
'username' => 'Username',
'domain' => 'Domain'
);
function SIPAccounts(&$SOAPEngine) {
$this->filters = array('username' => trim($_REQUEST['username_filter']),
'domain' => trim($_REQUEST['domain_filter']),
'fullname' => trim($_REQUEST['fullname_filter'])
);
$this->Records(&$SOAPEngine);
}
function getRecordKeys() {
if (preg_match("/^(.*)@(.*)$/",$this->filters['username'],$m)) {
$this->filters['username'] = $m[1];
$this->filters['domain'] = $m[2];
}
if ($this->filters['domain'] && $this->allowedDomains && !in_array($this->filters['domain'],$this->allowedDomains)) {
$this->filters['domain'] = $this->allowedDomains[0];
}
// Filter
$filter=array('username' => $this->filters['username'],
'domain' => $this->filters['domain'],
'name' => $this->filters['fullname']
);
// Range
$range=array('start' => 0,
'count' => 1000
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'changeDate';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'DESC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
// Call function
$result = $this->SOAPEngine->soapclient->getAccounts($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
foreach ($result->accounts as $account) {
$this->selectionKeys[]=array('username' => $account->id->username,
'domain' => $account->id->domain
);
}
return true;
}
return false;
}
function listRecords() {
$this->getAllowedDomains();
if (preg_match("/^(.*)@(.*)$/",$this->filters['username'],$m)) {
$this->filters['username'] = $m[1];
$this->filters['domain'] = $m[2];
}
// Make sure we apply the domain filter from the login credetials
if ($this->allowedDomains && !$this->filters['domain']) {
//$this->filters['domain'] = $this->allowedDomains[0];
}
if ($this->filters['domain'] && $this->allowedDomains && !in_array($this->filters['domain'],$this->allowedDomains)) {
$this->filters['domain'] = $this->allowedDomains[0];
}
$this->showSeachForm();
// Filter
$filter=array('username' => $this->filters['username'],
'domain' => $this->filters['domain'],
'name' => $this->filters['fullname'],
'customer' => intval($this->filters['customer']),
'reseller' => intval($this->filters['reseller'])
);
// Range
$range=array('start' => intval($this->next),
'count' => intval($this->maxrowsperpage)
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'changeDate';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'DESC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
// Call function
$result = $this->SOAPEngine->soapclient->getAccounts($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
$this->rows = $result->total;
if ($this->rows && $_REQUEST['action'] != 'PerformActions' && $_REQUEST['action'] != 'Delete') {
$this->showActionsForm();
}
print "
<p>
<table border=0 align=center>
<tr><td>$this->rows records found</td></tr>
</table>
<p>
<table border=0 cellpadding=2 width=100%>
<tr bgcolor=lightgrey>
<td><b>Id</b></th>
";
if ($this->version > 1) print "<td><b>Operator</b></td>";
print"
<td><b>SIP account</b></td>
<td><b>Name</b></td>
<td><b>Email</b></td>
<td><b>Caller Id</b></td>
<td><b>Quota</b></td>
<td><b>Groups</b></td>
<td><b>Last change</b></td>
<td><b>Owner</b></td>
<td><b>Action</b></td>
</tr>
";
if (!$this->next) $this->next=0;
if ($this->rows > $this->maxrowsperpage) {
$maxrows = $this->maxrowsperpage + $this->next;
if ($maxrows > $this->rows) $maxrows = $this->maxrowsperpage;
} else {
$maxrows=$this->rows;
}
$i=0;
//print "<pre>";
//print_r($result->accounts);
if ($this->rows) {
while ($i < $maxrows) {
if (!$result->accounts[$i]) break;
$account = $result->accounts[$i];
$index=$this->next+$i+1;
$rr=floor($index/2);
$mod=$index-$rr*2;
if ($mod ==0) {
$bgcolor="lightgrey";
} else {
$bgcolor="white";
}
$_url = $this->url.sprintf("&service=%s&action=Delete&username_filter=%s&domain_filter=%s",
urlencode($this->SOAPEngine->service),
urlencode($account->id->username),
urlencode($account->id->domain)
);
if ($_REQUEST['action'] == 'Delete' &&
$_REQUEST['username_filter'] == $account->id->username &&
$_REQUEST['domain_filter'] == $account->id->domain) {
$_url .= "&confirm=1";
$actionText = "<font color=red>Confirm</font>";
} else {
$actionText = "Delete";
}
if ($account->reseller) {
$resellerSipSettingsPage=$account->reseller;
} else {
$resellerSipSettingsPage=$this->reseller;
}
if ($this->SipSettingsPage) {
$url=sprintf('%s?account=%s@%s&reseller=%s&soapEngineIdSipPort=%s',$this->SipSettingsPage,$account->id->username,$account->id->domain,
$resellerSipSettingsPage,$this->SOAPEngine->soapEngineIdSettingsPage);
if ($this->adminonly) $url .= sprintf('&adminonly=%s',$this->adminonly);
foreach (array_keys($this->SOAPEngine->extraFormElements) as $element) {
if (!strlen($this->SOAPEngine->extraFormElements[$element])) continue;
$url .= sprintf('&%s=%s',$element,urlencode($this->SOAPEngine->extraFormElements[$element]));
}
$sip_account=sprintf("
<a href=\"javascript:void(null);\" onClick=\"return window.open('%s', 'SIP_Settings',
'toolbar=1,status=1,menubar=1,scrollbars=1,resizable=1,width=800,height=720')\">
%s@%s</a>",$url,$account->id->username,$account->id->domain);
} else {
$sip_account=sprintf("%s@%s",$account->id->username,$account->id->domain);
}
unset($groups);
foreach ($account->groups as $_grp) $groups.=$_grp.' ';
if ($this->version > 1) {
printf("
<tr bgcolor=%s>
<td>%s </td>
<td>%s.%s</td>
<td>%s</td>
<td>%s %s</td>
<td><a href=mailto:%s>%s</a></td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>
",
$bgcolor,
$index,
$account->reseller,
$account->customer,
$sip_account,
$account->firstName,
$account->lastName,
$account->email,
$account->email,
$account->rpid,
$account->quota,
$groups,
$account->changeDate,
$account->owner,
$_url,
$actionText
);
} else {
printf("
<tr bgcolor=%s>
<td>%s </td>
<td>%s</td>
<td>%s %s</td>
<td><a href=mailto:%s>%s</a></td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>
",
$bgcolor,
$index,
$sip_account,
$account->firstName,
$account->lastName,
$account->email,
$account->email,
$account->rpid,
$account->quota,
$groups,
$account->changeDate,
$account->owner,
$_url,
$actionText
);
}
$i++;
}
}
print "</table>";
$this->showPagination($maxrows);
return true;
}
}
function showSeachFormCustom() {
printf ("User<input type=text size=15 name=username_filter value='%s'>",$this->filters['username']);
printf ("@");
if ($this->allowedDomains) {
$selected_domain[$this->filters['domain']]='selected';
printf ("<select name=domain_filter>
<option>");
foreach ($this->allowedDomains as $_domain) {
printf ("<option value='$_domain' %s>$_domain",$selected_domain[$_domain]);
}
printf ("</select>");
} else {
printf ("<input type=text size=15 name=domain_filter value='%s'>",$this->filters['domain']);
}
printf (" Name<input type=text size=15 name=fullname_filter value='%s'>",$this->filters['fullname']);
}
function deleteRecord() {
if (!$_REQUEST['confirm']) {
print "<p><font color=red>Please press on Confirm to confirm the delete. </font>";
return 1;
}
if (!strlen($this->filters['username']) || !strlen($this->filters['domain'])) {
print "<p><font color=red>Error: missing SIP account username or domain. </font>";
return 0;
}
$account=array('username' => $this->filters['username'],
'domain' => $this->filters['domain']
);
$function=array('commit' => array('name' => 'deleteAccount',
'parameters' => array($account),
'logs' => array('success' => sprintf('<p>SIP account %s@%s has been deleted',$this->filters['username'],$this->filters['domain'])
)
)
);
if ($this->SOAPEngine->execute($function)) {
unset($this->filters);
}
return true;
}
function showAddForm() {
if ($this->selectionActive) return;
print "
<p>
<table border=0 class=border width=100%>
<tr>
";
printf ("<form method=post name=addform action=%s>",$_SERVER['PHP_SELF']);
print "
<td align=left>
";
print "
<input type=submit name=action value=Add>
";
printf (" User<input type=text size=15 name=account value='%s'>",$_REQUEST['account']);
if (is_array($this->allowedDomains)) {
print "@<select name=domain>";
foreach ($this->allowedDomains as $_domain) {
print "<option value=$_domain>$_domain\n";
}
print "</select>";
}
printf (" Pass<input type=password size=10 name=password value='%s'>",$_REQUEST['password']);
printf (" Name<input type=text size=15 name=fullname value='%s'>",$_REQUEST['fullname']);
printf (" Email<input type=text size=15 name=email value='%s'>",$_REQUEST['email']);
//printf (" CallerId<input type=text size=11 name=rpid value='%s'>",$_REQUEST['rpid']);
printf ("<nobr>Owner<input type=text size=5 name=owner value='%s'></nobr> ",$_REQUEST['owner']);
printf ("<nobr>PSTN<input type=checkbox name=pstn value=1></nobr> ");
printf ("<nobr>Quota<input type=text size=5 name=quota value='%s'></nobr> ",$_REQUEST['quota']);
printf ("<nobr>Prepaid<input type=checkbox name=prepaid value=1></nobr> ");
print "<nobr>OP";
if ($this->adminonly) {
$this->showResellerForm('reseller');
print ".";
$this->showCustomerForm('customer');
} else {
$this->showCustomerForm('customer');
}
print "</nobr>";
print "
</td>
<td align=right>
";
print "
</td>
";
$this->printHiddenFormElements();
print "
</form>
</tr>
</table>
";
}
function addRecord($dictionary=array()) {
if ($dictionary['account']) {
$account_els = explode("@", $dictionary['account']);
} else {
$account_els = explode("@", trim($_REQUEST['account']));
}
if ($this->adminonly) {
if ($dictionary['reseller']) {
$reseller = $dictionary['reseller'];
} else {
$reseller = trim($_REQUEST['reseller']);
}
if ($dictionary['customer']) {
$customer = $dictionary['customer'];
} else {
$customer = trim($_REQUEST['customer']);
}
if (!$customer) $customer=$reseller;
} else {
$reseller = $this->reseller;
if ($dictionary['customer']) {
$customer = $dictionary['customer'];
} else {
$customer = trim($_REQUEST['customer']);
}
if (!$customer || !in_array($customer,array_keys($this->customers))) {
$customer=$reseller;
}
}
$username=$account_els[0];
if (strlen($account_els[1])) {
$domain=$account_els[1];
} else if ($dictionary['domain']) {
$domain=$dictionary['domain'];
} else if ($_REQUEST['domain']) {
$domain=trim($_REQUEST['domain']);
} else {
printf ("<p><font color=red>Error: Missing SIP domain</font>");
return false;
}
if (is_array($this->allowedDomains) && !in_array($domain,$this->allowedDomains)) {
printf ("<p><font color=red>Error: SIP domain %s is not allowed</font>",$domain);
return false;
}
if ($dictionary['fullname']) {
$name_els = explode(" ", $dictionary['fullname']);
} else {
$name_els = explode(" ", trim($_REQUEST['fullname']));
}
if (strlen($name_els[0])) {
$firstName=$name_els[0];
} else {
$firstName='Account';
}
if (strlen($name_els[1])) {
$lastName=$name_els[1];
} else {
$lastName=$username;
}
if (strlen($dictionary['timezone'])) {
$timezone=$dictionary['timezone'];
} else if (strlen(trim($_REQUEST['timezone']))) {
$timezone=trim($_REQUEST['timezone']);
} else {
$timezone='Europe/Amsterdam';
}
if (strlen($dictionary['password'])) {
$password=$dictionary['password'];
} else if (strlen(trim($_REQUEST['password']))) {
$password=trim($_REQUEST['password']);
} else {
$password=$this->RandomPassword(6);
}
$groups=array();
if($dictionary['pstn'] || $_REQUEST['pstn']) $groups[]='free-pstn';
if (strlen($dictionary['email'])) {
$email=$dictionary['email'];
} else {
$email=trim($_REQUEST['email']);
}
if (strlen($dictionary['owner'])) {
$owner=intval($dictionary['owner']);
} else {
$owner=intval($_REQUEST['owner']);
}
if (strlen($dictionary['quota'])) {
$quota=intval($dictionary['quota']);
} else {
$quota=intval($_REQUEST['quota']);
}
if (strlen($dictionary['prepaid'])) {
$prepaid=intval($dictionary['prepaid']);
} else {
$prepaid=intval($_REQUEST['prepaid']);
}
$regexp = "/^([a-z0-9][a-z0-9_.-]*)@([a-z0-9][a-z0-9-]*\.)+([a-z0-9]{2,})$/i";
if (!preg_match($regexp, $uri)) $email=$username.'@'.$domain;
$account=array(
'id' => array('username' => $username,
'domain' => $domain),
'firstName' => $firstName,
'lastName' => $lastName,
'password' => $password,
'timezone' => $timezone,
'email' => $email,
'owner' => $owner,
'customer' => intval($customer),
'reseller' => intval($reseller),
'groups' => $groups,
'prepaid' => $prepaid,
'quota' => $quota,
'region' => ''
);
//print_r($account);
$deleteAccount=array('username' => $username,
'domain' => $domain);
$function=array('commit' => array('name' => 'addAccount',
'parameters' => array($account),
'logs' => array('success' => sprintf('<p>SIP account %s@%s has been added',$username,$domain))),
'rollback' => array('name' => 'deleteAlias',
'parameters' => array($deleteAccount))
);
return $this->SOAPEngine->execute($function);
}
function RandomPassword($len=11) {
$alf=array("a","b","c","d","e","f",
"h","i","j","k","l","m",
"n","p","r","s","t","w",
"x","y","1","2","3","4",
"5","6","7","8","9");
$i=0;
while($i < $len) {
srand((double)microtime()*1000000);
$randval = rand(0,28);
$string="$string"."$alf[$randval]";
$i++;
}
return $string;
}
function getAllowedDomains() {
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
//print_r($this->SOAPEngine->soapclient->headersOut);
$result = $this->SOAPEngine->soapclient->getDomains();
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error in getAllowedDomains from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
//return false;
} else {
$this->allowedDomains=$result;
}
}
}
class SIPAliases extends Records {
var $sortElements=array(
'aliasUsername' => 'Alias user',
'aliasDomain' => 'Alias domain',
'targetUsername' => 'Target user',
'targetDomain' => 'Target domain'
);
function SIPAliases(&$SOAPEngine) {
$this->filters = array('aliasUsername' => trim($_REQUEST['alias_username_filter']),
'aliasDomain' => trim($_REQUEST['alias_domain_filter']),
'targetUsername' => trim($_REQUEST['target_username_filter']),
'targetDomain' => trim($_REQUEST['target_domain_filter'])
);
$this->Records(&$SOAPEngine);
}
function getRecordKeys() {
// Make sure we apply the domain filter from the login credetials
if ($this->allowedDomains && !$this->filters['aliasDomain']) {
//$this->filters['aliasDomain'] = $this->allowedDomains[0];
}
if ($this->filters['aliasDomain'] && $this->allowedDomains && !in_array($this->filters['aliasDomain'],$this->allowedDomains)) {
$this->filters['aliasDomain'] = $this->allowedDomains[0];
}
// Filter
$filter=array('aliasUsername' => $this->filters['aliasUsername'],
'aliasDomain' => $this->filters['aliasDomain'],
'targetUsername' => $this->filters['targetUsername'],
'targetDomain' => $this->filters['targetDomain']
);
// Range
$range=array('start' => 0,
'count' => 1000
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'aliasUsername';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'DESC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
//print_r($Query);
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
// Call function
$result = $this->SOAPEngine->soapclient->getAliases($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
foreach ($result->aliases as $alias) {
$this->selectionKeys[]=array('username' => $alias->id->username,
'domain' => $alias->id->domain);
}
return true;
}
}
function listRecords() {
$this->getAllowedDomains();
// Make sure we apply the domain filter from the login credetials
if ($this->allowedDomains && !$this->filters['aliasDomain']) {
//$this->filters['aliasDomain'] = $this->allowedDomains[0];
}
if ($this->filters['aliasDomain'] && $this->allowedDomains && !in_array($this->filters['aliasDomain'],$this->allowedDomains)) {
$this->filters['aliasDomain'] = $this->allowedDomains[0];
}
$this->showSeachForm();
// Filter
$filter=array('aliasUsername' => $this->filters['aliasUsername'],
'aliasDomain' => $this->filters['aliasDomain'],
'targetUsername' => $this->filters['targetUsername'],
'targetDomain' => $this->filters['targetDomain'],
'customer' => intval($this->filters['customer']),
'reseller' => intval($this->filters['reseller'])
);
// Range
$range=array('start' => intval($this->next),
'count' => intval($this->maxrowsperpage)
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'aliasUsername';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'DESC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
// Call function
$result = $this->SOAPEngine->soapclient->getAliases($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
$this->rows = $result->total;
if ($this->rows && $_REQUEST['action'] != 'PerformActions' && $_REQUEST['action'] != 'Delete') {
$this->showActionsForm();
}
print "
<p>
<table border=0 align=center>
<tr><td>$this->rows records found</td></tr>
</table>
<p>
<table border=0 cellpadding=2 width=100%>
<tr bgcolor=lightgrey>
<td><b>Id</b></th>
";
if ($this->version > 1) print "<td><b>Operator</b></td>";
print"
<td><b>Alias</b></td>
<td><b>Target</b></td>
<td><b>Owner</b></td>
<td><b>Last change</b></td>
<td><b>Action</b></td>
</tr>
";
if (!$this->next) $this->next=0;
if ($this->rows > $this->maxrowsperpage) {
$maxrows = $this->maxrowsperpage + $this->next;
if ($maxrows > $this->rows) $maxrows = $this->maxrowsperpage;
} else {
$maxrows=$this->rows;
}
$i=0;
if ($this->rows) {
while ($i < $maxrows) {
if (!$result->aliases[$i]) break;
$alias = $result->aliases[$i];
$index=$this->next+$i+1;
$rr=floor($index/2);
$mod=$index-$rr*2;
if ($mod ==0) {
$bgcolor="lightgrey";
} else {
$bgcolor="white";
}
$_url = $this->url.sprintf("&service=%s&action=Delete&alias_username_filter=%s&alias_domain_filter=%s",
urlencode($this->SOAPEngine->service),
urlencode($alias->id->username),
urlencode($alias->id->domain)
);
if ($_REQUEST['action'] == 'Delete' &&
$_REQUEST['alias_username_filter'] == $alias->id->username &&
$_REQUEST['alias_domain_filter'] == $alias->id->domain) {
$_url .= "&confirm=1";
$actionText = "<font color=red>Confirm</font>";
} else {
$actionText = "Delete";
}
if ($this->version > 1) {
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>%s.%s</td>
<td>%s@%s</td>
<td>%s@%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>
",
$bgcolor,
$index,
$alias->reseller,
$alias->customer,
$alias->id->username,
$alias->id->domain,
$alias->target->username,
$alias->target->domain,
$alias->owner,
$alias->changeDate,
$_url,
$actionText
);
} else {
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>%s@%s</td>
<td>%s@%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>
",
$bgcolor,
$index,
$alias->id->username,
$alias->id->domain,
$alias->target->username,
$alias->target->domain,
$alias->owner,
$alias->changeDate,
$_url,
$actionText
);
}
$i++;
}
}
print "</table>";
$this->showPagination($maxrows);
return true;
}
}
function deleteRecord() {
if (!$_REQUEST['confirm']) {
print "<p><font color=red>Please press on Confirm to confirm the delete. </font>";
return 1;
}
if (!strlen($this->filters['aliasUsername']) || !strlen($this->filters['aliasDomain'])) {
print "<p><font color=red>Error: missing SIP alias username or domain. </font>";
return 0;
}
$alias=array('username' => $this->filters['aliasUsername'],
'domain' => $this->filters['aliasDomain']
);
$function=array('commit' => array('name' => 'deleteAlias',
'parameters' => array($alias),
'logs' => array('success' => sprintf('<p>SIP alias %s@%s has been deleted',$this->filters['aliasUsername'],$this->filters['aliasDomain'])
)
)
);
if ($this->SOAPEngine->execute($function)) {
unset($this->filters);
return true;
} else {
return flase;
}
}
function showSeachFormCustom() {
printf (" Alias<input type=text size=10 name=alias_username_filter value='%s'>",$this->filters['aliasUsername']);
printf ("@");
if ($this->allowedDomains) {
$selected_domain[$this->filters['aliasDomain']]='selected';
printf ("<select name=alias_domain_filter>
<option>");
foreach ($this->allowedDomains as $_domain) {
printf ("<option value='$_domain' %s>$_domain",$selected_domain[$_domain]);
}
printf ("</select>");
} else {
printf ("<input type=text size=10 name=alias_domain_filter value='%s'>",$this->filters['aliasDomain']);
}
printf (" Target<input type=text size=10 name=target_username_filter value='%s'>",$this->filters['targetUsername']);
printf (" @<input type=text size=10 name=target_domain_filter value='%s'>",$this->filters['targetDomain']);
}
function showAddForm() {
if ($this->selectionActive) return;
print "
<p>
<table border=0 class=border width=100%>
<tr>
";
printf ("<form method=post name=addform action=%s>",$_SERVER['PHP_SELF']);
print "
<td align=left>
";
print "
<input type=submit name=action value=Add>
";
printf (" Alias<input type=text size=15 name=alias>");
if (is_array($this->allowedDomains)) {
print "@<select name=domain>";
foreach ($this->allowedDomains as $_domain) {
print "<option value=$_domain>$_domain\n";
}
print "</select>";
}
printf (" Target<input type=text size=35 name=target>");
print "OP";
if ($this->adminonly) {
$this->showResellerForm('reseller');
print ".";
$this->showCustomerForm('customer');
} else {
$this->showCustomerForm('customer');
}
printf (" Owner<input type=text size=5 name=owner>");
print "
</td>
<td align=right>
";
print "
</td>
";
$this->printHiddenFormElements();
print "
</form>
</tr>
</table>
";
}
function addRecord() {
$alias_els = explode("@", trim($_REQUEST['alias']));
$target_els = explode("@", trim($_REQUEST['target']));
$username=$alias_els[0];
if (strlen($alias_els[1])) {
$domain=$alias_els[1];
} else if (trim($_REQUEST['domain'])) {
$domain=trim($_REQUEST['domain']);
} else {
printf ("<p><font color=red>Error: Missing SIP domain</font>");
return false;
}
if (is_array($this->allowedDomains) && !in_array($domain,$this->allowedDomains)) {
printf ("<p><font color=red>Error: SIP domain %s is not allowed</font>",$domain);
return false;
}
if ($this->adminonly) {
$reseller = trim($_REQUEST['reseller']);
$customer = trim($_REQUEST['customer']);
if (!$customer) $customer=$reseller;
} else {
$reseller = $this->reseller;
$customer = trim($_REQUEST['customer']);
if (!$customer || !in_array($customer,array_keys($this->customers))) {
$customer=$reseller;
}
}
$alias=array(
'id' => array('username' => $username,
'domain' => $domain
),
'target' => array('username' => $target_els[0],
'domain' => $target_els[1]
),
'owner' => intval($_REQUEST['owner']),
'customer' => intval($customer),
'reseller' => intval($reseller)
);
//print_r($alias);
$deleteAlias=array('username' => $username,
'domain' => $domain);
$function=array('commit' => array('name' => 'addAlias',
'parameters' => array($alias),
'logs' => array('success' => sprintf('<p>SIP alias %s@%s has been added',$username,$domain))),
'rollback' => array('name' => 'deleteAlias',
'parameters' => array($deleteAlias))
);
return $this->SOAPEngine->execute($function);
}
function getAllowedDomains() {
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getDomains();
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
$this->allowedDomains=$result;
}
}
}
class ENUMranges extends Records {
function ENUMranges(&$SOAPEngine) {
$this->filters = array('prefix' => trim($_REQUEST['prefix_filter']),
'tld' => trim($_REQUEST['tld_filter'])
);
$this->Records(&$SOAPEngine);
if ($this->version > 1) {
$this->sortElements=array('changeDate' => 'Change date',
'prefix' => 'Prefix',
'tld' => 'TLD'
);
}
}
function listRecords() {
$this->getAllowedDomains();
$this->showSeachForm();
if ($this->version > 1) {
// Filter
$filter=array('prefix' => $this->filters['prefix'],
'tld' => $this->filters['tld'],
'customer' => intval($this->filters['customer']),
'reseller' => intval($this->filters['reseller'])
);
// Range
$range=array('start' => intval($this->next),
'count' => intval($this->maxrowsperpage)
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'changeDate';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'DESC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getRanges($Query);
} else {
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getRanges();
}
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
if ($this->version > 1) {
$this->rows = $result->total;
} else {
$this->rows = count($result);
}
if ($this->rows && $_REQUEST['action'] != 'PerformActions' && $_REQUEST['action'] != 'Delete') {
$this->showActionsForm();
}
print "
<p>
<table border=0 align=center>
<tr><td>$this->rows records found</td></tr>
</table>
<p>
<table border=0 cellpadding=2 width=100%>
<tr bgcolor=lightgrey>
<td><b>Id</b></th>
";
if ($this->version > 1) print "<td><b>Operator</b></td>";
print"
<td><b>Prefix </b></td>
<td><b>TLD</b></td>
<td><b>TTL</b></td>
<td><b>Min digits</b></td>
<td><b>Max digits</b></td>
<td><b>Used</b></td>
<td><b>Last change</b></td>
<td><b>Action</b></td>
</tr>
";
if (!$this->next) $this->next=0;
if ($this->rows > $this->maxrowsperpage) {
$maxrows = $this->maxrowsperpage + $this->next;
if ($maxrows > $this->rows) $maxrows = $this->maxrowsperpage;
} else {
$maxrows=$this->rows;
}
$i=0;
if ($this->rows) {
while ($i < $maxrows) {
if ($this->version > 1) {
if (!$result->ranges[$i]) break;
$range = $result->ranges[$i];
} else {
$range = $result[$i];
}
$index=$this->next+$i+1;
$rr=floor($index/2);
$mod=$index-$rr*2;
if ($mod ==0) {
$bgcolor="lightgrey";
} else {
$bgcolor="white";
}
$_url = $this->url.sprintf("&service=%s&action=Delete&prefix_filter=%s&tld_filter=%s",
urlencode($this->SOAPEngine->service),
urlencode($range->id->prefix),
urlencode($range->id->tld)
);
if ($_REQUEST['action'] == 'Delete' &&
$_REQUEST['prefix_filter'] == $range->id->prefix &&
$_REQUEST['tld_filter'] == $range->id->tld) {
$_url .= "&confirm=1";
$actionText = "<font color=red>Confirm</font>";
} else {
$actionText = "Delete";
}
if (strlen($this->SOAPEngine->recordGenerator)) {
$range_link=sprintf('<a href=%s&generatorId=%s&range=%s@%s&len=%s target=generator>%s</a>',$this->url,$this->SOAPEngine->recordGenerator,$range->id->prefix,$range->id->tld,$range->maxDigits,$range->id->prefix);
} else {
$range_link=$range->id->prefix;
}
if ($this->version > 1) {
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>%s.%s</td>
<td>+%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
$index,
$range->reseller,
$range->customer,
$range_link,
$range->id->tld,
$range->ttl,
$range->minDigits,
$range->maxDigits,
$range->used,
$range->changeDate,
$_url,
$actionText
);
} else {
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>+%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
$index,
$range_link,
$range->id->tld,
$range->ttl,
$range->minDigits,
$range->maxDigits,
$range->used,
$range->changeDate,
$_url,
$actionText
);
}
printf("
</tr>
");
$i++;
}
}
print "</table>";
$this->showPagination($maxrows);
return true;
}
}
function deleteRecord() {
if (!$_REQUEST['confirm']) {
print "<p><font color=red>Please press on Confirm to confirm the delete. </font>";
return 1;
}
if (!strlen($this->filters['prefix']) || !strlen($this->filters['tld'])) {
print "<p><font color=red>Error: missing ENUM range id </font>";
return 0;
}
$rangeId=array('prefix'=>$this->filters['prefix'],
'tld'=>$this->filters['tld']);
$function=array('commit' => array('name' => 'deleteRange',
'parameters' => array($rangeId),
'logs' => array('success' => sprintf('<p>ENUM range +%s under %s has been deleted',$this->filters['prefix'],$this->filters['tld'])
)
)
);
unset($this->filters);
return $this->SOAPEngine->execute($function);
}
function showAddForm() {
if ($this->selectionActive) return;
print "
<p>
<table border=0 class=border width=100%>
<tr>
";
printf ("<form method=post name=addform action=%s>",$_SERVER['PHP_SELF']);
print "
<td align=left>
";
print "
<input type=submit name=action value=Add>
";
printf ("Prefix +<input type=text size=5 name=prefix> ");
printf (" TLD");
/*
if (is_array($this->allowedDomains)) {
print "<select name=tld>";
foreach ($this->allowedDomains as $_tld) {
print "<option value=$_tld>$_tld\n";
}
print "</select>";
} else {
print "<input type=text size=15 name=tld>";
}
*/
print "<input type=text size=15 name=tld>";
printf ("TTL<input type=text size=5 name=ttl value=3600> ");
printf ("Min Digits<input type=text size=3 name=minDigits value=11> ");
printf ("Max Digits<input type=text size=3 name=maxDigits value=11> ");
print "OP";
if ($this->adminonly) {
$this->showResellerForm('reseller');
print ".";
$this->showCustomerForm('customer');
} else {
$this->showCustomerForm('customer');
}
//printf ("Info<input type=text size=15 name=info> ");
print "
</td>
<td align=right>
";
print "
</td>
";
$this->printHiddenFormElements();
print "
</form>
</tr>
</table>
";
}
function addRecord() {
$tld = trim($_REQUEST['tld']);
$prefix = trim($_REQUEST['prefix']);
$info = trim($_REQUEST['info']);
if (!strlen($tld)) {
if (strlen($this->SOAPEngine->defaultEnumTLD)) {
$tld=$this->SOAPEngine->defaultEnumTLD;
} else {
$tld='e164.arpa';
}
}
if (!strlen($tld) || !strlen($prefix) || !is_numeric($prefix)) {
printf ("<p><font color=red>Error: Missing TLD or prefix. </font>");
return false;
}
if ($this->adminonly) {
$reseller = trim($_REQUEST['reseller']);
$customer = trim($_REQUEST['customer']);
if (!$customer) $customer=$reseller;
} else {
$reseller = $this->reseller;
$customer = trim($_REQUEST['customer']);
if (!$customer || !in_array($customer,array_keys($this->customers))) {
$customer=$reseller;
}
}
if (!trim($_REQUEST['ttl'])) {
$ttl=3600;
} else {
$ttl=intval(trim($_REQUEST['ttl']));
}
$range=array(
'id' => array('prefix' => $prefix,
'tld' => $tld),
'ttl' => $ttl,
'minDigits' => intval(trim($_REQUEST['minDigits'])),
'maxDigits' => intval(trim($_REQUEST['maxDigits'])),
'customer' => intval($customer),
'reseller' => intval($reseller)
);
$deleteRange=array('prefix'=>$prefix,
'tld'=>$tld);
$function=array('commit' => array('name' => 'addRange',
'parameters' => array($range),
'logs' => array('success' => sprintf('<p>ENUM range +%s under %s has been added',$prefix,$tld))),
'rollback' => array('name' => 'deleteRange',
'parameters' => array($deleteRange))
);
return $this->SOAPEngine->execute($function);
}
function showSeachFormCustom() {
if ($this->version > 1) {
printf (" Prefix<input type=text size=10 name=prefix_filter value='%s'>",$this->filters['prefix']);
printf (" TLD");
if ($this->allowedDomains) {
$selected_tld[$this->filters['tld_filter']]='selected';
printf ("<select name=tld_filter>
<option>");
foreach ($this->allowedDomains as $_tld) {
printf ("<option value='$_tld' %s>$_tld",$selected_tld[$_tld]);
}
printf ("</select>");
} else {
printf ("<input type=text size=10 name=tld_filter value='%s'>",$this->filters['tld']);
}
}
}
function getAllowedDomains() {
// Insert credetials
if ($this->version > 1) {
// Filter
$filter=array('prefix' => '');
// Range
$range=array('start' => 0,
'count' => 200
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'changeDate';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'DESC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getRanges($Query);
} else {
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getRanges();
}
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
if ($this->version > 1) {
foreach($result->ranges as $range) {
$this->ranges[]=array('prefix' => $range->id->prefix,
'tld' => $range->id->tld,
'minDigits' => $range->minDigits,
'maxDigits' => $range->maxDigits
);
if (in_array($range->id->tld,$this->allowedDomains)) continue;
$this->allowedDomains[]=$range->id->tld;
$seen[$range->id->tld]++;
}
} else {
foreach($result as $range) {
$this->ranges[]=array('prefix' => $range->id->prefix,
'tld' => $range->id->tld,
'minDigits' => $range->minDigits,
'maxDigits' => $range->maxDigits
);
if (in_array($range->id->tld,$this->allowedDomains)) continue;
$this->allowedDomains[]=$range->id->tld;
$seen[$range->id->tld]++;
}
}
if (strlen($this->SOAPEngine->defaultEnumTLD) && !$seen[$this->SOAPEngine->defaultEnumTLD]) {
$this->allowedDomains[]=$this->SOAPEngine->defaultEnumTLD;
}
}
}
}
class ENUMmappings extends Records {
var $sortElements=array('changeDate' => 'Change date',
'number' => 'Number',
'tld' => 'TLD',
'owner' => 'Owner'
);
var $ranges=array();
var $NAPTR_services=array(
"sip" => array("service"=>"sip",
"webname"=>"SIP",
"schemas"=>array("sip:","sips:")),
"mailto" => array("service"=>"mailto",
"webname"=>"Email",
"schemas"=>array("mailto:")),
"web:http" => array("service"=>"web:http",
"webname"=>"WEB (http)",
"schemas"=>array("http://")),
"web:https" => array("service"=>"web:https",
"webname"=>"WEB (https)",
"schemas"=>array("https://")),
"x-skype:callto" => array("service"=>"x-skype:callto",
"webname"=>"Skype",
"schemas"=>array("callto:")),
"h323" => array("service"=>"h323",
"webname"=>"H323",
"schemas"=>array("h323:")),
"iax" => array("service"=>"iax",
"webname"=>"IAX",
"schemas"=>array("iax:")),
"iax2" => array("service"=>"iax2",
"webname"=>"IAX2",
"schemas"=>array("iax2:")),
"mms" => array("service"=>"mms",
"webname"=>"MMS",
"schemas"=>array("tel:","mailto:")),
"sms" => array("service"=>"sms",
"webname"=>"SMS",
"schemas"=>array("tel:","mailto:")),
"ems" => array("service"=>"ems",
"webname"=>"EMS",
"schemas"=>array("tel:","mailto:")),
"im" => array("service"=>"im",
"webname"=>"IM",
"schemas"=>array("im:")),
"npd:tel" => array("service"=>"npd+tel",
"webname"=>"Portability",
"schemas"=>array("tel:")),
"void:mailto" => array("service"=>"void:mailto",
"webname"=>"VOID(mail)",
"schemas"=>array("mailto:")),
"void:http" => array("service"=>"void:http",
"webname"=>"VOID(http)",
"schemas"=>array("http://")),
"void:https" => array("service"=>"void:https",
"webname"=>"VOID(https)",
"schemas"=>array("https://")),
"voice" => array("service"=>"voice",
"webname"=>"Voice",
"schemas"=>array("voice:","tel:")),
"tel" => array("service"=>"tel",
"webname"=>"Tel",
"schemas"=>array("tel:")),
"fax:tel" => array("service"=>"fax:tel",
"webname"=>"Fax",
"schemas"=>array("tel:")),
"ifax:mailto" => array("service"=>"ifax:mailto",
"webname"=>"iFax",
"schemas"=>array("mailto:")),
"pres" => array("service"=>"pres",
"webname"=>"Presence",
"schemas"=>array("pres:")),
"ft:ftp" => array("service"=>"ft:ftp",
"webname"=>"FTP",
"schemas"=>array("ftp://")),
"loc:http" => array("service"=>"loc:http",
"webname"=>"GeoLocation",
"schemas"=>array("http://")),
"key:http" => array("service"=>"key:http",
"webname"=>"Public key",
"schemas"=>array("http://"))
);
function ENUMmappings(&$SOAPEngine) {
$this->filters = array('number' => trim($_REQUEST['number_filter']),
'tld' => trim($_REQUEST['tld_filter']),
'type' => trim($_REQUEST['type_filter']),
'mapto' => trim($_REQUEST['mapto_filter']),
'owner' => trim($_REQUEST['owner_filter'])
);
$this->Records(&$SOAPEngine);
}
function listRecords() {
$this->getAllowedDomains();
$this->showSeachForm();
// Filter
$filter=array('number' => $this->filters['number'],
'type' => $this->filters['type'],
'mapto' => $this->filters['mapto'],
'customer' => intval($this->filters['customer']),
'reseller' => intval($this->filters['reseller'])
);
// Range
$range=array('start' => intval($this->next),
'count' => intval($this->maxrowsperpage)
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'changeDate';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'DESC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
// Call function
$result = $this->SOAPEngine->soapclient->getNumbers($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
$this->rows = $result->total;
if ($this->rows && $_REQUEST['action'] != 'PerformActions' && $_REQUEST['action'] != 'Delete') {
$this->showActionsForm();
}
print "
<p>
<table border=0 align=center>
<tr><td>$this->rows records found</td></tr>
</table>
<p>
<table border=0 cellpadding=2 width=100%>
<tr bgcolor=lightgrey>
<td><b>Id</b></th>
";
if ($this->version > 1) print "<td><b>Operator</b></td>";
print"
<td><b>Number</b></td>
<td><b>TLD</b></td>
<td><b>DNS name</b></td>
<td><b>Srv</b></td>
<td><b>Map to</b></td>
<td><b>TTL</b></td>
<td><b>Prio</b></td>
<td><b>Owner</b></td>
<td><b>Last change</b></td>
<td><b>Action</b></td>
</tr>
";
if (!$this->next) $this->next=0;
if ($this->rows > $this->maxrowsperpage) {
$maxrows = $this->maxrowsperpage + $this->next;
if ($maxrows > $this->rows) $maxrows = $this->maxrowsperpage;
} else {
$maxrows=$this->rows;
}
$i=0;
if ($this->rows) {
while ($i < $maxrows) {
if (!$result->numbers[$i]) break;
$number = $result->numbers[$i];
$index=$this->next+$i+1;
$rr=floor($index/2);
$mod=$index-$rr*2;
if ($mod ==0) {
$bgcolor="lightgrey";
} else {
$bgcolor="white";
}
$j=1;
foreach ($number->mappings as $_mapping) {
$_url = $this->url.sprintf("&service=%s&action=Delete&number_filter=%s&tld_filter=%s&mapto_filter=%s",
urlencode($this->SOAPEngine->service),
urlencode($number->id->number),
urlencode($number->id->tld),
urlencode($_mapping->mapto)
);
if ($_REQUEST['action'] == 'Delete' &&
$_REQUEST['number_filter'] == $number->id->number &&
$_REQUEST['tld_filter'] == $number->id->tld &&
$_REQUEST['mapto_filter'] == $_mapping->mapto) {
$_url .= "&confirm=1";
$actionText = "<font color=red>Confirm</font>";
} else {
$actionText = "Delete";
}
if ($j==1) {
if ($this->version > 1) {
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>%s.%s</td>
<td>+%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
$index,
$number->reseller,
$number->customer,
$number->id->number,
$number->id->tld,
$this->tel2enum($number->id->number,$number->id->tld),
ucfirst($_mapping->type),
$_mapping->mapto,
$_mapping->ttl,
$_mapping->priority,
$number->owner,
$_mapping->lastChange,
$_url,
$actionText
);
} else {
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>+%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
$index,
$number->id->number,
$number->id->tld,
$this->tel2enum($number->id->number,$number->id->tld),
ucfirst($_mapping->type),
$_mapping->mapto,
$_mapping->ttl,
$_mapping->priority,
$number->owner,
$_mapping->lastChange,
$_url,
$actionText
);
}
} else {
if ($this->version > 1) {
printf("
<tr bgcolor=%s>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td></td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
ucfirst($_mapping->type),
$_mapping->mapto,
$_mapping->ttl,
$_mapping->priority,
$_mapping->lastChange,
$_url,
$actionText
);
} else {
printf("
<tr bgcolor=%s>
<td></td>
<td></td>
<td></td>
<td></td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td></td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
ucfirst($_mapping->type),
$_mapping->mapto,
$_mapping->ttl,
$_mapping->priority,
$_mapping->lastChange,
$_url,
$actionText
);
}
}
$j++;
}
printf("
</tr>
");
$i++;
}
}
print "</table>";
$this->showPagination($maxrows);
return true;
}
}
function getLastNumber() {
// Filter
$filter=array('number' => ''
);
// Range
$range=array('start' => 0,
'count' => 1
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'changeDate';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'DESC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
// Call function
$result = $this->SOAPEngine->soapclient->getNumbers($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
if ($result->total) {
$number = array('number' => $result->numbers[0]->id->number,
'tld' => $result->numbers[0]->id->tld,
'mappings' => $result->numbers[0]->mappings
);
return $number;
}
}
return false;
}
function showSeachFormCustom() {
printf (" Number<input type=text size=15 name=number_filter value='%s'>",$this->filters['number']);
printf (" TLD");
if ($this->allowedDomains) {
$selected_tld[$this->filters['tld_filter']]='selected';
printf ("<select name=tld_filter>
<option>");
foreach ($this->allowedDomains as $_tld) {
printf ("<option value='$_tld' %s>$_tld",$selected_tld[$_tld]);
}
printf ("</select>");
} else {
printf ("<input type=text size=10 name=tld_filter value='%s'>",$this->filters['tld']);
}
printf (" Srv");
print "<select name=type_filter>
<option>
";
reset($this->NAPTR_services);
$selected_naptr_service[$this->filters['mapto']];
while (list($k,$v) = each($this->NAPTR_services)) {
printf ("<option value='%s' %s>%s",$k,$selected_naptr_service[$k],$this->NAPTR_services[$k]['webname']);
}
print "
</select>
";
printf (" <nobr>Map to<input type=text size=20 name=mapto_filter value='%s'></nobr>",$this->filters['mapto']);
}
function deleteRecord($dictionary=array()) {
if (!$dictionary['confirm'] && !$_REQUEST['confirm']) {
print "<p><font color=red>Please press on Confirm to confirm the delete. </font>";
return 1;
}
if ($dictionary['number']) {
$number=$dictionary['number'];
} else {
$number=$this->filters['number'];
}
if ($dictionary['tld']) {
$tld=$dictionary['tld'];
} else {
$tld=$this->filters['tld'];
}
if ($dictionary['mapto']) {
$mapto=$dictionary['mapto'];
} else {
$mapto=$this->filters['mapto'];
}
if (!strlen($number) || !strlen($tld)) {
print "<p><font color=red>Error: missing ENUM number or TLD </font>";
return 0;
}
$enum_id=array('number'=>$number,
'tld'=>$tld);
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getNumber($enum_id);
if (!PEAR::isError($result)) {
// the number exists and we make an update
$result_new=$result;
if (count($result->mappings) > 1) {
foreach ($result->mappings as $_mapping) {
if ($_mapping->mapto != $mapto) {
$mappings_new[]=array('type' => $_mapping->type,
'mapto' => $_mapping->mapto,
'ttl' => $_mapping->ttl,
'priority' => $_mapping->priority
);
}
}
$result_new->mappings=$mappings_new;
$function=array('commit' => array('name' => 'updateNumber',
'parameters' => array($result_new),
'logs' => array('success' => sprintf('<p>ENUM mapping %s has been deleted',$mapto))),
'rollback' => array('name' => 'updateNumber',
'parameters' => array($result))
);
} else {
$function=array('commit' => array('name' => 'deleteNumber',
'parameters' => array($enum_id),
'logs' => array('success' => sprintf('<p>ENUM number +%s under %s has been deleted',$number,$tld))),
'rollback' => array('name' => 'addNumber',
'parameters' => array($result))
);
}
unset($this->filters);
return $this->SOAPEngine->execute($function);
} else {
return false;
}
}
function showAddForm() {
if ($this->selectionActive) return;
print "
<p>
<table border=0 class=border width=100%>
<tr>
";
printf ("<form method=post name=addform action=%s>",$_SERVER['PHP_SELF']);
print "
<td align=left>
";
print "
<input type=submit name=action value=Add>
";
printf (" Number +<input type=text size=15 name=number>");
printf (" TLD");
if (is_array($this->allowedDomains)) {
print "<select name=tld>";
foreach ($this->allowedDomains as $_tld) {
print "<option value=$_tld>$_tld\n";
}
print "</select>";
} else {
print "<input type=text size=15 name=tld>";
}
printf (" Map to");
print "<select name=type>
";
reset($this->NAPTR_services);
while (list($k,$v) = each($this->NAPTR_services)) {
printf ("<option value='%s' %s>%s",$k,$selected_naptr_service[$k],$this->NAPTR_services[$k]['webname']);
}
print "
</select>
";
printf (" <input type=text size=25 name=mapto>");
printf (" TTL<input type=text size=5 name=ttl value=3600>");
print "OP";
if ($this->adminonly) {
$this->showResellerForm('reseller');
print ".";
$this->showCustomerForm('customer');
} else {
$this->showCustomerForm('customer');
}
printf (" Owner<input type=text size=5 name=owner>");
printf (" Prio<input type=text size=3 name=priority>");
print "
</td>
<td align=right>
";
print "
</td>
";
$this->printHiddenFormElements();
print "
</form>
</tr>
</table>
";
}
function getAllowedDomains() {
if ($this->version > 1) {
// Filter
$filter=array('prefix' => $this->filters['prefix'],
'tld' => $this->filters['tld'],
'customer' => intval($this->filters['customer']),
'reseller' => intval($this->filters['reseller'])
);
// Range
$range=array('start' => 0,
'count' => 200
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'changeDate';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'DESC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getRanges($Query);
} else {
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getRanges();
}
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
if ($this->version > 1) {
foreach($result->ranges as $range) {
$this->ranges[]=array('prefix' => $range->id->prefix,
'tld' => $range->id->tld,
'minDigits' => $range->minDigits,
'maxDigits' => $range->maxDigits
);
if (in_array($range->id->tld,$this->allowedDomains)) continue;
$this->allowedDomains[]=$range->id->tld;
$seen[$range->id->tld]++;
}
} else {
foreach($result as $range) {
$this->ranges[]=array('prefix' => $range->id->prefix,
'tld' => $range->id->tld,
'minDigits' => $range->minDigits,
'maxDigits' => $range->maxDigits
);
if (in_array($range->id->tld,$this->allowedDomains)) continue;
$this->allowedDomains[]=$range->id->tld;
$seen[$range->id->tld]++;
}
}
if (strlen($this->SOAPEngine->defaultEnumTLD) && !$seen[$this->SOAPEngine->defaultEnumTLD]) {
$this->allowedDomains[]=$this->SOAPEngine->defaultEnumTLD;
}
}
}
function addRecord($dictionary=array()) {
if ($dictionary['tld']) {
$tld=$dictionary['tld'];
} else {
$tld = trim($_REQUEST['tld']);
}
if ($dictionary['number']) {
$number=$dictionary['number'];
} else {
$number = trim($_REQUEST['number']);
}
if (!strlen($tld)) {
if (strlen($this->SOAPEngine->defaultEnumTLD)) {
$tld=$this->SOAPEngine->defaultEnumTLD;
} else {
$tld='e164.arpa';
}
}
if (!strlen($tld) || !strlen($number) || !is_numeric($number)) {
printf ("<p><font color=red>Error: Missing TLD or number. </font>");
return false;
}
if ($this->adminonly) {
if ($dictionary['reseller']) {
$reseller=$dictionary['reseller'];
} else {
$reseller = trim($_REQUEST['reseller']);
}
if ($dictionary['customer']) {
$customer=$dictionary['customer'];
} else {
$customer = trim($_REQUEST['customer']);
}
if (!$customer) $customer=$reseller;
} else {
$reseller = $this->reseller;
if ($dictionary['customer']) {
$customer=$dictionary['customer'];
} else {
$customer = trim($_REQUEST['customer']);
}
if (!$customer || !in_array($customer,array_keys($this->customers))) {
$customer=$reseller;
}
}
if ($dictionary['ttl']) {
$ttl = intval($dictionary['ttl']);
} else {
$ttl = intval(trim($_REQUEST['ttl']));
}
if (!$ttl) $ttl=3600;
if ($dictionary['priority']) {
$priority = intval($dictionary['priority']);
} else {
$priority = intval(trim($_REQUEST['priority']));
}
if ($dictionary['owner']) {
$owner = intval($dictionary['owner']);
} else {
$owner = intval(trim($_REQUEST['owner']));
}
if (!$priority) $priority=5;
$enum_id=array('number' => $number,
'tld' => $tld);
if ($dictionary['mapto']) {
$mapto = $dictionary['mapto'];
} else {
$mapto = trim($_REQUEST['mapto']);
}
if ($dictionary['type']) {
$type = $dictionary['type'];
} else {
$type = trim($_REQUEST['type']);
}
if (preg_match("/^([a-z0-9]+:\/\/)(.*)$/i",$mapto,$m)) {
$_scheme = $m[1];
$_value = $m[2];
} else if (preg_match("/^([a-z0-9]+:)(.*)$/i",$mapto,$m)) {
$_scheme = $m[1];
$_value = $m[2];
} else {
$_scheme = '';
$_value = $mapto;
}
if (!$_value) {
$lastNumber=$this->getLastNumber();
foreach($lastNumber['mappings'] as $_mapping) {
if ($_mapping->type == trim($type)) {
if (preg_match("/^(.*)@(.*)$/",$_mapping->mapto,$m)) {
$_value = $number.'@'.$m[2];
break;
}
}
}
}
if (!$_scheme || !in_array($_scheme,$this->NAPTR_services[trim($type)]['schemas'])) {
$_scheme=$this->NAPTR_services[trim($type)]['schemas'][0];
}
$mapto=$_scheme.$_value;
$enum_number=array('id' => $enum_id,
'owner' => $owner,
'customer' => intval($customer),
'reseller' => intval($reseller),
'mappings' => array(array('type' => $type,
'mapto' => $mapto,
'ttl' => $ttl,
'priority' => $priority
)
)
);
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getNumber($enum_id);
if (PEAR::isError($result)) {
$error_msg=$result->getMessage();
$error_fault=$result->getFault();
$error_code=$result->getCode();
if ($error_fault->detail->exception->errorcode == "3002") {
$function=array('commit' => array('name' => 'addNumber',
'parameters' => array($enum_number),
'logs' => array('success' => sprintf('<p>ENUM number +%s under %s has been added',$number,$tld))),
'rollback' => array('name' => 'deleteNumber',
'parameters' => array($enumId))
);
return $this->SOAPEngine->execute($function);
} else {
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
}
} else {
// the number exists and we make an update
$result_new=$result;
foreach ($result->mappings as $_mapping) {
$mappings_new[]=array('type' => $_mapping->type,
'mapto' => $_mapping->mapto,
'ttl' => $_mapping->ttl,
'priority' => $_mapping->priority
);
if ($_mapping->mapto == $mapto) {
printf ("<p><font color=blue>Info: ENUM mapping %s for number %s already exists</font>",$mapto,$number);
return true;
break;
}
}
$mappings_new[]=array('type' => trim($type),
'mapto' => $mapto,
'ttl' => intval(trim($_REQUEST['ttl'])),
'priority'=> intval(trim($_REQUEST['priority'])),
);
// add mapping
$result_new->mappings=$mappings_new;
$function=array('commit' => array('name' => 'updateNumber',
'parameters' => array($result_new),
'logs' => array('success' => sprintf('<p>ENUM number +%s under %s has been updated',$number,$tld))),
'rollback' => array('name' => 'updateNumber',
'parameters' => array($result))
);
return $this->SOAPEngine->execute($function);
}
return true;
}
function getRecordKeys() {
// Filter
$filter=array('number' => $this->filters['number'],
'type' => $this->filters['type'],
'mapto' => $this->filters['mapto']
);
// Range
$range=array('start' => 0,
'count' => 1000
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'changeDate';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'DESC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
// Call function
$result = $this->SOAPEngine->soapclient->getNumbers($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
foreach ($result->numbers as $number) {
$this->selectionKeys[]=array('number' => $number->id->number,
'tld' => $number->id->tld);
}
return true;
}
}
}
class TrustedPeers extends Records {
var $sortElements=array(
'description' => 'Description',
'ip' =>'IP address'
);
function TrustedPeers(&$SOAPEngine) {
$this->filters = array('ip' => trim($_REQUEST['ip_filter']),
'description' => trim($_REQUEST['description_filter'])
);
$this->Records(&$SOAPEngine);
}
function listRecords() {
$this->showSeachForm();
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
// Filter
$filter=array('ip' => $this->filters['ip'],
'description' => $this->filters['description']
);
// Range
$range=array('start' => intval($this->next),
'count' => intval($this->maxrowsperpage)
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'description';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'ASC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
// Call function
$result = $this->SOAPEngine->soapclient->getTrustedPeers($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
$this->rows = $result->total;
if ($this->rows && $_REQUEST['action'] != 'PerformActions' && $_REQUEST['action'] != 'Delete') {
$this->showActionsForm();
}
print "
<table border=0 align=center>
<tr><td>$this->rows records found</td></tr>
</table>
<p>
<table border=0 cellpadding=2 width=100%>
<tr bgcolor=lightgrey>
<td><b>Id</b></th>
";
if ($this->version > 1) print "<td><b>Operator</b></td>";
print"
<td><b>IP address</b></td>
<td><b>Protocol</b></td>
<td><b>From pattern</b></td>
<td><b>Description</b></td>
<td><b>Owner</b></td>
<td><b>Action</b></td>
</tr>
";
if (!$this->next) $this->next=0;
if ($this->rows > $this->maxrowsperpage) {
$maxrows = $this->maxrowsperpage + $this->next;
if ($maxrows > $this->rows) $maxrows = $this->maxrowsperpage;
} else {
$maxrows=$this->rows;
}
$i=0;
if ($this->rows) {
while ($i < $maxrows) {
if (!$result->peers[$i]) break;
$peer = $result->peers[$i];
$index=$this->next+$i+1;
$rr=floor($index/2);
$mod=$index-$rr*2;
if ($mod ==0) {
$bgcolor="lightgrey";
} else {
$bgcolor="white";
}
$_url = $this->url.sprintf("&service=%s&action=Delete&ip_filter=%s",
urlencode($this->SOAPEngine->service),
urlencode($peer->ip)
);
if ($_REQUEST['action'] == 'Delete' &&
$_REQUEST['ip_filter'] == $peer->ip) {
$_url .= "&confirm=1";
$actionText = "<font color=red>Confirm</font>";
} else {
$actionText = "Delete";
}
if ($this->version > 1) {
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>%s.%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
$index,
$peer->reseller,
$peer->customer,
$peer->ip,
$peer->protocol,
$peer->fromPattern,
$peer->description,
$peer->owner,
$_url,
$actionText
);
} else {
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
$index,
$peer->ip,
$peer->protocol,
$peer->fromPattern,
$peer->description,
$peer->owner,
$_url,
$actionText
);
}
printf("
</tr>
");
$i++;
}
}
print "</table>";
$this->showPagination($maxrows);
return true;
}
}
function showAddForm() {
if ($this->selectionActive) return;
print "
<p>
<table border=0 class=border width=100%>
<tr>
";
printf ("<form method=post name=addform action=%s>",$_SERVER['PHP_SELF']);
print "
<td align=left>
";
print "
<input type=submit name=action value=Add>
";
printf (" IP address<input type=text size=20 name=ipaddress>");
printf (" Description<input type=text size=30 name=description>");
print "OP";
if ($this->adminonly) {
$this->showResellerForm('reseller');
print ".";
$this->showCustomerForm('customer');
} else {
$this->showCustomerForm('customer');
}
printf (" Owner<input type=text size=5 name=owner>");
print "
</td>
<td align=right>
";
print "
</td>
";
$this->printHiddenFormElements();
print "
</form>
</tr>
</table>
";
}
function addRecord() {
$ipaddress = trim($_REQUEST['ipaddress']);
$description = trim($_REQUEST['description']);
$owner = trim($_REQUEST['owner']);
if ($this->adminonly) {
$reseller = trim($_REQUEST['reseller']);
$customer = trim($_REQUEST['customer']);
if (!$customer) $customer=$reseller;
} else {
$reseller = $this->reseller;
$customer = trim($_REQUEST['customer']);
if (!$customer || !in_array($customer,array_keys($this->customers))) {
$customer=$reseller;
}
}
if (!strlen($ipaddress) || !strlen($description)) {
printf ("<p><font color=red>Error: Missing IP or description. </font>");
return false;
}
$peer=array(
'ip' => $ipaddress,
'description' => $description,
'owner' => intval($_REQUEST['owner']),
'customer' => intval($customer),
'reseller' => intval($reseller)
);
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->addTrustedPeer($peer);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>Trusted peers %s has been added. </font>",$ipaddress);
return 1;
}
}
function deleteRecord() {
if (!$_REQUEST['confirm']) {
print "<p><font color=red>Please press on Confirm to confirm the delete. </font>";
return 1;
}
if (!strlen($this->filters['ip']) || !strlen($this->filters['ip'])) {
print "<p><font color=red>Error: missing IP address. </font>";
return 0;
}
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->deleteTrustedPeer($this->filters['ip']);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>Trusted peer %s has been deleted. </font> ",$this->filters['ip']);
unset($this->filters);
return 1;
}
}
}
class GatewayGroups extends Records {
var $sortElements=array(
'name' => 'Name'
);
function GatewayGroups(&$SOAPEngine) {
$this->filters = array('group' => trim($_REQUEST['group_filter'])
);
$this->Records(&$SOAPEngine);
}
function listRecords() {
$this->showSeachForm();
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
// Filter
$filter=array('name' => $this->filters['group']
);
// Range
$range=array('start' => intval($this->next),
'count' => intval($this->maxrowsperpage)
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'name';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'ASC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
// Call function
$result = $this->SOAPEngine->soapclient->getGatewayGroups($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
$this->rows = $result->total;
print "
<table border=0 align=center>
<tr><td>$this->rows records found</td></tr>
</table>
<p>
<table border=0 cellpadding=2 width=100%>
<tr bgcolor=lightgrey>
<td><b>Id</b></th>
<td><b>Name</b></th>
<td><b>Action</b></td>
</tr>
";
if (!$this->next) $this->next=0;
if ($this->rows > $this->maxrowsperpage) {
$maxrows = $this->maxrowsperpage + $this->next;
if ($maxrows > $this->rows) $maxrows = $this->maxrowsperpage;
} else {
$maxrows=$this->rows;
}
$i=0;
if ($this->rows) {
while ($i < $maxrows) {
if (!$result->groups[$i]) break;
$group = $result->groups[$i];
$index=$this->next+$i+1;
$rr=floor($index/2);
$mod=$index-$rr*2;
if ($mod ==0) {
$bgcolor="lightgrey";
} else {
$bgcolor="white";
}
$_url = $this->url.sprintf("&service=%s&action=Delete&group_filter=%s",
urlencode($this->SOAPEngine->service),
urlencode($group)
);
if ($_REQUEST['action'] == 'Delete' &&
$_REQUEST['group_filter'] == $group) {
$_url .= "&confirm=1";
$actionText = "<font color=red>Confirm</font>";
} else {
$actionText = "Delete";
}
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
$index,
$group,
$_url,
$actionText
);
printf("
</tr>
");
$i++;
}
}
print "</table>";
$this->showPagination($maxrows);
return true;
}
}
function showAddForm() {
if ($this->selectionActive) return;
print "
<p>
<table border=0 class=border width=100%>
<tr>
";
printf ("<form method=post name=addform action=%s>",$_SERVER['PHP_SELF']);
print "
<td align=left>
";
print "
<input type=submit name=action value=Add>
";
printf (" Name<input type=text size=20 name=name>");
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getGatewayGroups();
print "
</td>
<td align=right>
";
print "
</td>
";
$this->printHiddenFormElements();
print "
</form>
</tr>
</table>
";
}
function addRecord() {
$name = trim($_REQUEST['name']);
if (!strlen($name)) {
printf ("<p><font color=red>Error: Missing name. </font>");
return false;
}
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->addGatewayGroup($name);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>Gateway group %s has been added. </font>",$name);
return 1;
}
}
function deleteRecord() {
if (!$_REQUEST['confirm']) {
print "<p><font color=red>Please press on Confirm to confirm the delete. </font>";
return 1;
}
if (!strlen($this->filters['group'])) {
print "<p><font color=red>Error: missing gateway group. </font>";
return 0;
}
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->deleteGatewayGroup($this->filters['group']);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>Gateway %s has been deleted. </font> ",$this->filters['group']);
unset($this->filters);
return 1;
}
}
function showSeachFormCustom() {
printf (" Group<input type=text size=15 name=group_filter value='%s'>",$this->filters['group']);
}
}
class Gateways extends Records {
var $sortElements=array(
'name' => 'Name',
'group' => 'Group',
'ip' => 'IP address',
'prefix' => 'Prefix'
);
function Gateways(&$SOAPEngine) {
$this->filters = array('name' => trim($_REQUEST['name_filter']),
'group' => trim($_REQUEST['group_filter'])
);
$this->Records(&$SOAPEngine);
}
function listRecords() {
$this->showSeachForm();
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
// Filter
$filter=array('name' => $this->filters['name'],
'group' => $this->filters['group']
);
// Range
$range=array('start' => intval($this->next),
'count' => intval($this->maxrowsperpage)
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'name';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'ASC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
// Call function
$result = $this->SOAPEngine->soapclient->getGateways($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
$this->rows = $result->total;
print "
<table border=0 align=center>
<tr><td>$this->rows records found</td></tr>
</table>
<p>
<table border=0 cellpadding=2 width=100%>
<tr bgcolor=lightgrey>
<td><b>Id</b></th>
<td><b>Name</b></th>
<td><b>Group</b></td>
<td><b>Address</b></td>
<td><b>Strip</b></td>
<td><b>Prefix</b></td>
<td><b>Action</b></td>
</tr>
";
if (!$this->next) $this->next=0;
if ($this->rows > $this->maxrowsperpage) {
$maxrows = $this->maxrowsperpage + $this->next;
if ($maxrows > $this->rows) $maxrows = $this->maxrowsperpage;
} else {
$maxrows=$this->rows;
}
$i=0;
if ($this->rows) {
while ($i < $maxrows) {
if (!$result->gateways[$i]) break;
$gateway = $result->gateways[$i];
$index=$this->next+$i+1;
$rr=floor($index/2);
$mod=$index-$rr*2;
if ($mod ==0) {
$bgcolor="lightgrey";
} else {
$bgcolor="white";
}
$_url = $this->url.sprintf("&service=%s&action=Delete&name_filter=%s",
urlencode($this->SOAPEngine->service),
urlencode($gateway->name)
);
if ($_REQUEST['action'] == 'Delete' &&
$_REQUEST['name_filter'] == $gateway->name) {
$_url .= "&confirm=1";
$actionText = "<font color=red>Confirm</font>";
} else {
$actionText = "Delete";
}
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s:%s:%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
$index,
$gateway->name,
$gateway->group,
$gateway->transport,
$gateway->ip,
$gateway->port,
$gateway->strip,
$gateway->prefix,
$_url,
$actionText
);
printf("
</tr>
");
$i++;
}
}
print "</table>";
$this->showPagination($maxrows);
return true;
}
}
function showAddForm() {
if ($this->selectionActive) return;
print "
<p>
<table border=0 class=border width=100%>
<tr>
";
printf ("<form method=post name=addform action=%s>",$_SERVER['PHP_SELF']);
print "
<td align=left>
";
print "
<input type=submit name=action value=Add>
";
printf (" Name<input type=text size=20 name=name>");
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getGatewayGroups();
printf (" Group: ");
// Compose query
$Query=array('filter' => array('name'=>''),
'orderBy' => array('attribute' => 'name',
'direction' => 'ASC'
),
'range' => array('start' => 0,
'count' => 1000)
);
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getGatewayGroups($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
print "<select name=group> ";
foreach ($result->groups as $_grp) {
printf ("<option value='%s'>%s",$_grp,$_grp);
}
printf (" </select>");
}
printf (" Address<input type=text size=25 name=address>");
printf (" Strip: <select name=strip>");
$t=0;
while ($t<10) {
print "<option value=$t>$t";
$t++;
}
print "</select>";
printf (" Prefix<input type=text size=5 name=prefix>");
print "
</td>
<td align=right>
";
print "
</td>
";
$this->printHiddenFormElements();
print "
</form>
</tr>
</table>
";
}
function addRecord() {
$name = trim($_REQUEST['name']);
$group = trim($_REQUEST['group']);
$address = trim($_REQUEST['address']);
$strip = trim($_REQUEST['strip']);
$prefix = trim($_REQUEST['prefix']);
if (!strlen($name) || !strlen($group) || !strlen($address)) {
printf ("<p><font color=red>Error: Missing name, group or address. </font>");
return false;
}
$address_els=explode(':',$address);
if (count($address_els) == 1) {
$ip=$address_els[0];
$transport='udp';
$port='5060';
} else if (count($address_els) == 2) {
$ip=$address_els[0];
$port=$address_els[1];
$transport='udp';
} else if (count($address_els) == 3) {
$ip=$address_els[1];
$port=intval($address_els[2]);
if ($address_els[0] == 'tcp' || $address_els[0] == 'tls' || $address_els[0] == 'udp') {
$transport=$address_els[0];
} else {
$transport='udp';
}
}
$gateway=array(
'name' => $name,
'group' => $group,
'ip' => $ip,
'port' => intval($port),
'uriScheme' => 'sip',
'transport' => $transport,
'strip' => intval($_REQUEST['strip']),
'prefix' => $_REQUEST['prefix']
);
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->addGateway($gateway);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>Gateway %s has been added. </font>",$address);
return 1;
}
}
function deleteRecord() {
if (!$_REQUEST['confirm']) {
print "<p><font color=red>Please press on Confirm to confirm the delete. </font>";
return 1;
}
if (!strlen($this->filters['name'])) {
print "<p><font color=red>Error: missing gateway name. </font>";
return 0;
}
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->deleteGateway($this->filters['name']);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>Gateway %s has been deleted. </font> ",$this->filters['address']);
unset($this->filters);
return 1;
}
}
function showSeachFormCustom() {
printf (" Name<input type=text size=15 name=name_filter value='%s'>",$this->filters['name']);
printf (" Group<input type=text size=15 name=group_filter value='%s'>",$this->filters['group']);
}
}
class Routes extends Records {
var $gatewayGroups=array();
var $sortElements=array(
'prefix' => 'Prefix',
'fromURI' => 'From URI',
'priority' => 'Priority'
);
function Routes(&$SOAPEngine) {
$this->filters = array('prefix' => trim($_REQUEST['prefix_filter']),
'gatewayGroup' => trim($_REQUEST['gatewayGroup_filter']),
'fromURI' => trim($_REQUEST['fromURI_filter'])
);
$this->Records(&$SOAPEngine);
}
function listRecords() {
// Get gateway groups
$Query=array('filter' => array('name'=>''),
'orderBy' => array('attribute' => 'name',
'direction' => 'ASC'
),
'range' => array('start' => 0,
'count' => 1000)
);
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getGatewayGroups($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
$this->gatewayGroups=$result->groups;
}
$this->showSeachForm();
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
// Filter
$filter=array('prefix' => $this->filters['prefix'],
'gatewayGroup' => $this->filters['gatewayGroup'],
'fromURI' => $this->filters['fromURI']
);
// Range
$range=array('start' => intval($this->next),
'count' => intval($this->maxrowsperpage)
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'prefix';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'ASC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
// Call function
$result = $this->SOAPEngine->soapclient->getRoutes($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
$this->rows = $result->total;
print "
<table border=0 align=center>
<tr><td>$this->rows records found</td></tr>
</table>
<p>
<table border=0 cellpadding=2 width=100%>
<tr bgcolor=lightgrey>
<td><b>Id</b></th>
<td><b>Prefix</b></th>
<td><b>Gateway Group</b></td>
<td><b>From URI</b></td>
<td><b>Priority</b></td>
<td><b>Action</b></td>
</tr>
";
if (!$this->next) $this->next=0;
if ($this->rows > $this->maxrowsperpage) {
$maxrows = $this->maxrowsperpage + $this->next;
if ($maxrows > $this->rows) $maxrows = $this->maxrowsperpage;
} else {
$maxrows=$this->rows;
}
$i=0;
if ($this->rows) {
while ($i < $maxrows) {
if (!$result->routes[$i]) break;
$route = $result->routes[$i];
$index=$this->next+$i+1;
$rr=floor($index/2);
$mod=$index-$rr*2;
if ($mod ==0) {
$bgcolor="lightgrey";
} else {
$bgcolor="white";
}
$_url = $this->url.sprintf("&service=%s&action=Delete&prefix_filter=%s&gatewayGroup_filter=%s&fromURI_filter=%s&priority_filter=%s",
urlencode($this->SOAPEngine->service),
urlencode($route->prefix),
urlencode($route->gatewayGroup),
urlencode($route->fromURI),
urlencode($route->priority)
);
if ($_REQUEST['action'] == 'Delete' &&
$_REQUEST['prefix_filter'] == $route->prefix &&
$_REQUEST['gatewayGroup_filter'] == $route->gatewayGroup &&
$_REQUEST['fromURI_filter'] == $route->fromURI &&
$_REQUEST['priority_filter'] == $route->priority) {
$_url .= "&confirm=1";
$actionText = "<font color=red>Confirm</font>";
} else {
$actionText = "Delete";
}
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
$index,
$route->prefix,
$route->gatewayGroup,
$route->fromURI,
$route->priority,
$_url,
$actionText
);
printf("
</tr>
");
$i++;
}
}
print "</table>";
$this->showPagination($maxrows);
return true;
}
}
function showAddForm() {
if ($this->selectionActive) return;
print "
<p>
<table border=0 class=border width=100%>
<tr>
";
printf ("<form method=post name=addform action=%s>",$_SERVER['PHP_SELF']);
print "
<td align=left>
";
print "
<input type=submit name=action value=Add>
";
printf (" Prefix<input type=text size=20 name=prefix>");
printf (" Group: ");
print "<select name=gatewayGroup> ";
foreach ($this->gatewayGroups as $_grp) {
printf ("<option value='%s'>%s",$_grp,$_grp);
}
printf (" </select>");
printf (" From<input type=text size=25 name=fromURI>");
printf (" Priority<input type=text size=5 name=priority>");
print "
</td>
<td align=right>
";
print "
</td>
";
$this->printHiddenFormElements();
print "
</form>
</tr>
</table>
";
}
function addRecord() {
$prefix = trim($_REQUEST['prefix']);
$gatewayGroup = trim($_REQUEST['gatewayGroup']);
$fromURI = trim($_REQUEST['fromURI']);
$priority = trim($_REQUEST['priority']);
if (!strlen($prefix) || !strlen($gatewayGroup)) {
printf ("<p><font color=red>Error: Missing prefix or gatewayGroup. </font>");
return false;
}
$route=array(
'prefix' => $prefix,
'gatewayGroup' => $gatewayGroup,
'fromURI' => $fromURI,
'priority' => intval($priority)
);
$routes=array($route);
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->addRoutes($routes);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>Route %s has been added. </font>",$prefix);
return 1;
}
}
function deleteRecord() {
if (!$_REQUEST['confirm']) {
print "<p><font color=red>Please press on Confirm to confirm the delete. </font>";
return 1;
}
if (!strlen($this->filters['prefix']) || !strlen($this->filters['gatewayGroup'])) {
print "<p><font color=red>Error: missing route prefix or gatewayGroup. </font>";
return 0;
}
$route=array(
'prefix' => $this->filters['prefix'],
'gatewayGroup' => $this->filters['gatewayGroup'],
'fromURI' => $this->filters['fromURI'],
'priority' => intval($this->filters['priority'])
);
$routes=array($route);
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->deleteRoutes($routes);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>Route %s has been deleted. </font> ",$this->filters['prefix']);
unset($this->filters);
return 1;
}
}
function showSeachFormCustom() {
printf (" Prefix<input type=text size=15 name=prefix_filter value='%s'>",$this->filters['prefix']);
print "<select name=gatewayGroup_filter>
<option>";
$selected_gatewayGroups[$this->filters['gatewayGroup']]='selected';
foreach ($this->gatewayGroups as $_grp) {
printf ("<option value='%s' %s>%s",$_grp,$selected_gatewayGroups[$_grp],$_grp);
}
printf (" </select>");
printf (" From URI<input type=text size=15 name=fromURI_filter value='%s'>",$this->filters['fromURI']);
}
}
class DomainStatistics extends Records {
var $maxrowsperpage= 200;
function DomainStatistics(&$SOAPEngine) {
$this->filters = array(
'domain' => trim($_REQUEST['domain_filter'])
);
$this->Records(&$SOAPEngine);
}
function listRecords() {
$this->showSeachForm();
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$filter=$this->filters['domain'];
// Call function
$result = $this->SOAPEngine->soapclient->getDomainStatistics($filter);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
$this->rows = count($result);
//print_r($result);
print "
<table border=0 align=center>
<tr><td>$this->rows records found</td></tr>
</table>
<p>
<table border=0 cellpadding=2 width=100%>
<tr bgcolor=lightgrey>
<td><b>Id</b></th>
<td><b>SIP domain</b></td>
<td><b>SIP subscribers</b></td>
<td><b>Online subscribers</b></td>
<td><b>Online SIP devices</b></td>
</tr>
";
if (!$this->next) $this->next=0;
if ($this->rows > $this->maxrowsperpage) {
$maxrows = $this->maxrowsperpage + $this->next;
if ($maxrows > $this->rows) $maxrows = $this->maxrowsperpage;
} else {
$maxrows=$this->rows;
}
$i=0;
if ($this->rows) {
while ($i < $maxrows) {
$domain = $result[$i];
if (!strlen($domain->users)) break;
$index = $this->next+$i+1;
$rr=floor($index/2);
$mod=$index-$rr*2;
if ($mod ==0) {
$bgcolor="lightgrey";
} else {
$bgcolor="white";
}
$_url = $this->url.sprintf("&service=%s&action=Delete&domain_filter=%s",
urlencode($this->SOAPEngine->service),
urlencode($domain->domain)
);
if ($_REQUEST['action'] == 'Delete' &&
$_REQUEST['domain_filter'] == $domain->domain) {
$_url .= "&confirm=1";
$actionText = "<font color=red>Confirm</font>";
} else {
$actionText = "Delete";
}
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>",
$bgcolor,
$index,
$domain->domain,
$domain->users,
$domain->onlineUsers,
$domain->onlineDevices
);
$i++;
}
}
print "</table>";
$this->showPagination($maxrows);
return true;
}
}
function showSeachFormCustom() {
printf (" Domain<input type=text size=15 name=domain_filter value='%s'>",$this->filters['domain']);
}
function deleteRecord() {
if (!$_REQUEST['confirm']) {
print "<p><font color=red>Please press on Confirm to confirm the delete. </font>";
return 1;
}
if (!strlen($this->filters['domain']) || !strlen($this->filters['domain'])) {
print "<p><font color=red>Error: missing SIP domain. </font>";
return 0;
}
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->deleteDomain($this->filters['domain']);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>SIP domain %s has been deleted. </font> ",$this->filters['domain']);
unset($this->filters);
return 1;
}
}
function addRecord() {
$domain=trim($_REQUEST['domain']);
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->addDomain($domain);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>SIP domain %s has been added. </font>",$domain);
return 1;
}
}
}
class Customers extends Records {
var $maxrowsperpage= 20;
var $sortElements=array(
'customer' => 'Customer',
'reseller' => 'Reseller',
'username' => 'Username',
'changeDate' => 'Change date'
);
var $preferenceItems = array('sip_credit' => array('name' => 'Credit for SIP account creation',
'category' => 'admin'),
'enum_credit' => array('name' => 'Credit for ENUM numbers creation',
'category' => 'admin'),
'sipa_credit' => array('name' => 'Credit for SIP alias creation',
'category' => 'admin'),
'pstn_access' => array('name' => 'Access to PSTN',
'category' => 'admin'),
'language' => array('name' => 'Language',
'category' => 'general'),
'timezone' => array('name' => 'Timezone',
'category' => 'general'),
'voicemail_server' => array('name' => 'Voicemail server address',
'category' => 'sip'),
'sip_proxy_server' => array('name' => 'SIP Proxy server address',
'category' => 'sip'),
- 'support_web_site' => array('name' => 'Support web site',
+ 'support_web' => array('name' => 'Support web site',
+ 'category' => 'sip'),
+ 'support_email' => array('name' => 'Support email address',
+ 'category' => 'sip'),
+ 'support_cdrtool' => array('name' => 'CDRTool address',
'category' => 'sip'),
'default_sip_domain' => array('name' => 'Default SIP domain',
'category' => 'sip'),
'default_enum_range' => array('name' => 'Default ENUM range',
'category' => 'sip'),
'default_enum_tld' => array('name' => 'Default ENUM Top Level Domain',
'category' => 'sip')
);
+ var $customerFields=array(
+ 'id',
+ 'username',
+ 'reseller',
+ 'firstName',
+ 'lastName',
+ 'organization',
+ 'tel',
+ 'fax',
+ 'sip',
+ 'mobile',
+ 'email',
+ 'web',
+ 'address',
+ 'postcode',
+ 'city',
+ 'state',
+ 'country'
+ );
function Customers(&$SOAPEngine) {
$this->filters = array(
'username' => trim($_REQUEST['username_filter'])
);
$this->Records(&$SOAPEngine);
}
function listRecords() {
// Filter
$filter=array('username' => $this->filters['username'],
'customer' => intval($this->filters['customer']),
'reseller' => intval($this->filters['reseller'])
);
// Range
$range=array('start' => intval($this->next),
'count' => intval($this->maxrowsperpage)
);
// Order
if (!$this->sorting['sortBy']) $this->sorting['sortBy'] = 'customer';
if (!$this->sorting['sortOrder']) $this->sorting['sortOrder'] = 'DESC';
$orderBy = array('attribute' => $this->sorting['sortBy'],
'direction' => $this->sorting['sortOrder']
);
// Compose query
$Query=array('filter' => $filter,
'orderBy' => $orderBy,
'range' => $range
);
$this->showSeachForm();
// Insert credetials
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
// Call function
$result = $this->SOAPEngine->soapclient->getCustomers($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
$this->rows = $result->total;
if ($this->rows && $_REQUEST['action'] != 'PerformActions' && $_REQUEST['action'] != 'Delete') {
$this->showActionsForm();
}
print "
<table border=0 align=center>
<tr><td>$this->rows records found</td></tr>
</table>
<p>
<table border=0 cellpadding=2 width=100%>
<tr bgcolor=lightgrey>
<td><b>Id</b></th>
";
if ($this->version > 1) print "<td><b>Operator</b></td>";
print"
<td><b>Name</b></td>
<td><b>Organization</b></td>
<td><b>E-mail</b></td>
<td><b>Telephone</b></td>
<td><b>Web</b></td>
<td><b>Action</b></td>
</tr>
";
if (!$this->next) $this->next=0;
if ($this->rows > $this->maxrowsperpage) {
$maxrows = $this->maxrowsperpage + $this->next;
if ($maxrows > $this->rows) $maxrows = $this->maxrowsperpage;
} else {
$maxrows=$this->rows;
}
$i=0;
if ($this->rows) {
while ($i < $maxrows) {
if (!$result->accounts[$i]) break;
$customer = $result->accounts[$i];
$index = $this->next+$i+1;
$rr=floor($index/2);
$mod=$index-$rr*2;
if ($mod ==0) {
$bgcolor="lightgrey";
} else {
$bgcolor="white";
}
$_url = $this->url.sprintf("&service=%s&action=Delete&customer_filter=%s",
urlencode($this->SOAPEngine->service),
urlencode($customer->id)
);
if ($_REQUEST['action'] == 'Delete' &&
$_REQUEST['customer_filter'] == $customer->id) {
$_url .= "&confirm=1";
$actionText = "<font color=red>Confirm</font>";
} else {
$actionText = "Delete";
}
printf("
<tr bgcolor=%s>
<td>%s</td>
<td>%s.%s</td>
<td>%s %s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td><a href=%s>%s</a></td>
</tr>",
$bgcolor,
$index,
$customer->reseller,
$customer->id,
$customer->firstName,
$customer->lastName,
$customer->organization,
$customer->email,
$customer->tel,
$customer->web,
$_url,
$actionText
);
$i++;
}
}
print "</table>";
$this->showPagination($maxrows);
+ if ($this->rows == 1 ) {
+ $this->showCustomer($customer->id);
+ }
+
return true;
}
}
function showSeachFormCustom() {
if (!$this->filters['reseller']) {
printf (" Customer<input type=text size=6 name=customer_filter value='%s'>",$this->filters['customer']);
}
printf (" Username<input type=text size=10 name=username_filter value='%s'>",$this->filters['username']);
}
function deleteRecord() {
if (!$_REQUEST['confirm']) {
print "<p><font color=red>Please press on Confirm to confirm the delete. </font>";
return 1;
}
if (!strlen($this->filters['customer']) || !strlen($this->filters['customer'])) {
print "<p><font color=red>Error: missing customer id. </font>";
return 0;
}
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->deleteAccount(intval($this->filters['customer']));
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
printf ("<p><font color=green>Customer id %s has been deleted. </font> ",$this->filters['customer']);
unset($this->filters);
return 1;
}
}
+
+ function getCustomer($id) {
+
+ $this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
+ $result = $this->SOAPEngine->soapclient->getAccount(intval($id));
+
+ if (PEAR::isError($result)) {
+ $error_msg = $result->getMessage();
+ $error_fault= $result->getFault();
+ $error_code = $result->getCode();
+ printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
+ return false;
+ } else {
+ return $result;
+ }
+ }
+
+ function showCustomer($id) {
+ $customerInfo=$this->getCustomer($id);
+
+
+ print "<table border=0 cellpadding=10>";
+ printf ("<form method=post name=addform action=%s>",$_SERVER['PHP_SELF']);
+ print "<input type=hidden name=action value=Update>";
+ print "
+ <tr>
+ <td valign=top>
+ <h3>Customer data</h3>
+ <table border=1>";
+ printf ("<tr bgcolor=lightgrey>
+ <td class=border>Property</td>
+ <td class=border>Value</td>
+ </tr>");
+ foreach ($this->customerFields as $item) {
+ printf ("<tr>
+ <td class=border>%s</td>
+ <td class=border>%s</td>
+ </tr>",
+ ucfirst($item),
+ $customerInfo->$item
+ );
+ }
+
+ print "
+ </table>
+ ";
+
+ /*
+ print "<pre>";
+ print_r($customerInfo);
+ print "</pre>";
+ */
+
+ print "</td>
+ <td valign=top>
+ <h3>Customer properties</h3>
+ <table border=1>";
+ printf ("<tr bgcolor=lightgrey>
+ <td class=border>Category</td>
+ <td class=border>Property</td>
+ <td class=border>Value</td>
+ </tr>");
+
+ foreach (array_keys($this->preferenceItems) as $item) {
+ printf ("<tr><td class=border>%s</td>
+ <td class=border>%s</td>
+ <td class=border><input type=text name='%s_form' value='%s'></td>
+ </tr>",
+ ucfirst($this->preferenceItems[$item]['category']),
+ $item,
+ $item,
+ $customerInfo->preferences[$item]['value']
+ );
+ }
+
+ print "<tr>
+ <td colspan=3 class=border><input type=submit value=Update>
+ </td></tr>";
+ print "
+ </table>
+ </td>
+ </tr>
+ </table>
+ ";
+ $this->printFiltersToForm();
+
+ $this->printHiddenFormElements();
+
+ print "</form>";
+ }
+
+
+ function updateRecord () {
+ print "<p>Updating customer ...";
+ if (!$_REQUEST['customer_filter']) return;
+ $customerInfo=$this->getCustomer($_REQUEST['customer_filter']);
+ foreach (array_keys($this->preferenceItems) as $item) {
+ $var_name=$item.'_form';
+ $properties[]=array('name' => $item,
+ 'value' => trim($_REQUEST[$var_name]),
+ 'category' => $this->preferenceItems[$item]['category']
+ );
+
+ }
+
+ /*
+ print "<pre>";
+ print_r($properties);
+ print "</pre>";
+ */
+
+ $customerInfo->properties=$properties;
+
+ $this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
+ $result = $this->SOAPEngine->soapclient->updateAccount($customerInfo);
+
+ if (PEAR::isError($result)) {
+ $error_msg = $result->getMessage();
+ $error_fault= $result->getFault();
+ $error_code = $result->getCode();
+ printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
+ return false;
+ } else {
+ return true;
+ }
+ }
}
class recordsGenerator {
function recordsGenerator() {
}
function showAddForm() {
print "
<p>
<table border=0 class=border width=100%>
<tr>
";
printf ("<form method=post name=addform action=%s>",$_SERVER['PHP_SELF']);
print "
<td align=left>
";
print "
<input type=submit name=action value=Generate>
";
printf (" Name<input type=text size=20 name=name>");
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getGatewayGroups();
printf (" Group: ");
// Compose query
$Query=array('filter' => array('name'=>''),
'orderBy' => array('attribute' => 'name',
'direction' => 'ASC'
),
'range' => array('start' => 0,
'count' => 1000)
);
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getGatewayGroups($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error from %s: %s (%s): %s</font>",$this->SOAPEngine->SOAPurl,$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
} else {
print "<select name=group> ";
foreach ($result->groups as $_grp) {
printf ("<option value='%s'>%s",$_grp,$_grp);
}
printf (" </select>");
}
printf (" Address<input type=text size=25 name=address>");
printf (" Strip: <select name=strip>");
$t=0;
while ($t<10) {
print "<option value=$t>$t";
$t++;
}
print "</select>";
printf (" Prefix<input type=text size=5 name=prefix>");
print "
</td>
<td align=right>
";
print "
</td>
";
$this->printHiddenFormElements();
print "
</form>
</tr>
</table>
";
}
}
class Actions {
var $actions=array();
function Actions(&$SOAPEngine) {
$this->SOAPEngine = $SOAPEngine;
$this->adminonly = $this->SOAPEngine->adminonly;
}
function performActions($selectionKeys,$action,$sub_action_parameter) {
}
function showActionsForm($filters,$sorting,$hideParameter=false) {
if (!count($this->actions)) return;
print "
<p>
<table border=0 class=border width=100%>
<tr>
";
printf ("<form method=post name=actionform action=%s>",$_SERVER['PHP_SELF']);
print "
<td align=left>
";
print "
<input type=submit value='Perform this action on the selection:'>
<input type=hidden name=action value=PerformActions>
";
if ($this->adminonly) {
print "
<input type=hidden name=adminonly value=$this->adminonly>
";
}
print "<select name=sub_action>";
$j=0;
foreach (array_keys($this->actions) as $_action) {
$j++;
printf ("<option value='%s'>%d. %s",$_action,$j,$this->actions[$_action]);
}
print "</select>";
if (!$hideParameter) {
print "
<input type=text size=15 name=sub_action_parameter>
";
}
print "
</td>
<td align=right>
";
print "
</td>
";
foreach (array_keys($filters) as $_filter) {
printf ("<input type=hidden name='%s_filter' value='%s'>\n", $_filter,$filters[$_filter]);
}
foreach (array_keys($sorting) as $_sorting) {
printf ("<input type=hidden name='%s' value='%s'>\n", $_sorting,$sorting[$_sorting]);
}
printf("<input type=hidden name=service value='%s'>",$this->SOAPEngine->service);
foreach (array_keys($this->SOAPEngine->extraFormElements) as $element) {
if (!strlen($this->SOAPEngine->extraFormElements[$element])) continue;
printf ("<input type=hidden name=%s value='%s'>\n",$element,$this->SOAPEngine->extraFormElements[$element]);
}
print "
</form>
</tr>
</table>
";
}
}
class SIPAccountsActions extends Actions {
var $actions=array('block' => 'Block SIP accounts',
'deblock' => 'Deblock SIP accounts',
'enable_pstn' => 'Enable access to PSTN for the SIP accounts',
'disable_pstn' => 'Disable access to PSTN for the SIP accounts',
'deblock_quota' => 'Deblock SIP accounts blocked by quota',
'prepaid' => 'Make SIP accounts prepaid',
'postpaid' => 'Make SIP accounts postpaid',
'delete' => 'Delete SIP accounts',
'setquota' => 'Set quota of SIP account to:',
'rpidasusername' => 'Set PSTN caller ID as the username',
'prefixtorpid' => 'Add to PSTN caller ID this prefix:',
'rmdsfromrpid' => 'Remove from PSTN caller ID digits:',
'addtogroup' => 'Add SIP accounts to group:',
'removefromgroup'=> 'Remove SIP accounts from group:',
'addbalance' => 'Add to prepaid balance value:'
);
function SIPAccountsActions(&$SOAPEngine) {
$this->Actions(&$SOAPEngine);
}
function performActions($selectionKeys,$action,$sub_action_parameter) {
if (!in_array($action,array_keys($this->actions))) {
print "<font color=red>Error: Invalid action $action</font>";
return false;
}
print "<ol>";
foreach($selectionKeys as $key) {
print "<li>";
flush();
//printf ("Performing action=%s on key=%s",$action,$key);
$account=array('username' => $key['username'],
'domain' => $key['domain']
);
if ($action=='block') {
$function=array('commit' => array('name' => 'addToGroup',
'parameters' => array($account,'block'),
'logs' => array('success' => sprintf('SIP account %s@%s has been blocked',$key['username'],$key['domain'])
)
)
);
$this->SOAPEngine->execute($function);
} else if ($action=='deblock') {
$function=array('commit' => array('name' => 'removeFromGroup',
'parameters' => array($account,'block'),
'logs' => array('success' => sprintf('SIP account %s@%s has been de-blocked',$key['username'],$key['domain'])
)
)
);
$this->SOAPEngine->execute($function);
} else if ($action=='removefromgroup') {
if (!strlen($sub_action_parameter)) {
printf ("<font color=red>Error: you must enter a group name</font>");
break;
}
$function=array('commit' => array('name' => 'removeFromGroup',
'parameters' => array($account,$sub_action_parameter),
'logs' => array('success' => sprintf('SIP account %s@%s has been removed from group',$key['username'],$key['domain'],$sub_action_parameter)
)
)
);
$this->SOAPEngine->execute($function);
} else if ($action=='addtogroup') {
if (!strlen($sub_action_parameter)) {
printf ("<font color=red>Error: you must enter a group name</font>");
break;
}
$function=array('commit' => array('name' => 'addToGroup',
'parameters' => array($account,$sub_action_parameter),
'logs' => array('success' => sprintf('SIP account %s@%s is now in group %s',$key['username'],$key['domain'],$sub_action_parameter)
)
)
);
$this->SOAPEngine->execute($function);
} else if ($action=='deblock_quota') {
$function=array('commit' => array('name' => 'removeFromGroup',
'parameters' => array($account,'quota'),
'logs' => array('success' => sprintf('SIP account %s@%s has been deblocked from quota',$key['username'],$key['domain'])
)
)
);
$this->SOAPEngine->execute($function);
} else if ($action=='disable_pstn') {
$function=array('commit' => array('name' => 'removeFromGroup',
'parameters' => array($account,'free-pstn'),
'logs' => array('success' => sprintf('SIP account %s@%s has no access to the PSTN',$key['username'],$key['domain'])
)
)
);
$this->SOAPEngine->execute($function);
} else if ($action=='enable_pstn') {
$function=array('commit' => array('name' => 'addToGroup',
'parameters' => array($account,'free-pstn'),
'logs' => array('success' => sprintf('SIP account %s@%s has access to the PSTN',$key['username'],$key['domain'])
)
)
);
$this->SOAPEngine->execute($function);
} else if ($action=='delete') {
$function=array('commit' => array('name' => 'deleteAccount',
'parameters' => array($account),
'logs' => array('success' => sprintf('SIP account %s@%s has been deleted',$key['username'],$key['domain'])
)
)
);
$this->SOAPEngine->execute($function);
} else if ($action=='prepaid') {
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getAccount($account);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<font color=red>Error: %s (%s): %s</font>",$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
break;
} else {
//print_r($result);
// Sanitize data types due to PHP bugs
if (!is_array($result->properties)) $result->properties=array();
if (!is_array($result->groups)) $result->groups=array();
$result->quota = intval($result->quota);
$result->answerTimeout = intval($result->answerTimeout);
$result->prepaid=1;
$function=array('commit' => array('name' => 'updateAccount',
'parameters' => array($result),
'logs' => array('success' => sprintf('SIP account %s@%s is now prepaid',$key['username'],$key['domain'])
)
)
);
$this->SOAPEngine->execute($function);
}
} else if ($action=='postpaid') {
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getAccount($account);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<font color=red>Error: %s (%s): %s</font>",$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
break;
} else {
//print_r($result);
// Sanitize data types due to PHP bugs
if (!is_array($result->properties)) $result->properties=array();
if (!is_array($result->groups)) $result->groups=array();
$result->quota = intval($result->quota);
$result->answerTimeout = intval($result->answerTimeout);
$result->prepaid=0;
$function=array('commit' => array('name' => 'updateAccount',
'parameters' => array($result),
'logs' => array('success' => sprintf('SIP account %s@%s is now postpaid',$key['username'],$key['domain'])
)
)
);
$this->SOAPEngine->execute($function);
}
} else if ($action=='setquota') {
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getAccount($account);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<font color=red>Error: %s (%s): %s</font>",$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
break;
} else {
//print_r($result);
// Sanitize data types due to PHP bugs
if (!is_array($result->properties)) $result->properties=array();
if (!is_array($result->groups)) $result->groups=array();
$result->quota = intval($sub_action_parameter);
$result->answerTimeout = intval($result->answerTimeout);
$function=array('commit' => array('name' => 'updateAccount',
'parameters' => array($result),
'logs' => array('success' => sprintf('SIP account %s@%s has quota set to %s',$key['username'],$key['domain'],$sub_action_parameter)
)
)
);
$this->SOAPEngine->execute($function);
}
} else if ($action=='rmdsfromrpid') {
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getAccount($account);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<font color=red>Error: %s (%s): %s</font>",$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
break;
} else {
//print_r($result);
// Sanitize data types due to PHP bugs
if (!is_array($result->properties)) $result->properties=array();
if (!is_array($result->groups)) $result->groups=array();
if (is_numeric($sub_action_parameter) && strlen($result->rpid) > $sub_action_parameter) {
printf("%s %s",$result->rpid,$sub_action_parameter);
$result->rpid=substr($result->rpid,$sub_action_parameter);
printf("%s %s",$result->rpid,$sub_action_parameter);
} else {
printf ("<font color=red>Error: '%s' must be numeric and less than caller if length</font>",$sub_action_parameter);
continue;
}
$result->quota = intval($result->quota);
$result->answerTimeout = intval($result->answerTimeout);
$function=array('commit' => array('name' => 'updateAccount',
'parameters' => array($result),
'logs' => array('success' => sprintf('SIP account %s@%s has PSTN caller ID set to %s',$key['username'],$key['domain'],$result->rpid)
)
)
);
$this->SOAPEngine->execute($function);
}
} else if ($action=='rpidasusername') {
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getAccount($account);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<font color=red>Error: %s (%s): %s</font>",$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
break;
} else {
//print_r($result);
// Sanitize data types due to PHP bugs
if (!is_array($result->properties)) $result->properties=array();
if (!is_array($result->groups)) $result->groups=array();
if (is_numeric($key['username'])) $result->rpid=$key['username'];
$result->quota = intval($result->quota);
$result->answerTimeout = intval($result->answerTimeout);
$function=array('commit' => array('name' => 'updateAccount',
'parameters' => array($result),
'logs' => array('success' => sprintf('SIP account %s@%s has PSTN caller ID set to %s',$key['username'],$key['domain'],$key['username'])
)
)
);
$this->SOAPEngine->execute($function);
}
} else if ($action=='prefixtorpid') {
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getAccount($account);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<font color=red>Error: %s (%s): %s</font>",$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
break;
} else {
//print_r($result);
// Sanitize data types due to PHP bugs
if (!is_array($result->properties)) $result->properties=array();
if (!is_array($result->groups)) $result->groups=array();
if (is_numeric($sub_action_parameter)) {
$result->rpid=$sub_action_parameter.$result->rpid;
} else {
printf ("<font color=red>Error: '%s' must be numeric</font>",$sub_action_parameter);
continue;
}
$result->quota = intval($result->quota);
$result->answerTimeout = intval($result->answerTimeout);
$function=array('commit' => array('name' => 'updateAccount',
'parameters' => array($result),
'logs' => array('success' => sprintf('SIP account %s@%s has PSTN caller ID set to %s ',$key['username'],$key['domain'],$result->rpid)
)
)
);
$this->SOAPEngine->execute($function);
}
} else if ($action=='addbalance') {
if (!is_numeric($sub_action_parameter)) {
printf ("<font color=red>Error: you must enter a positive balance</font>");
break;
}
$this->SOAPEngine->soapclient->addHeader($this->SOAPEngine->SoapAuth);
$result = $this->SOAPEngine->soapclient->getAccount($account);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<font color=red>Error: %s (%s): %s</font>",$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
break;
}
if (!$result->prepaid) {
printf ("<font color=red>Info: SIP account %s@%s is not prepaid, no action performed</font>",$key['username'],$key['domain']);
continue;
}
$function=array('commit' => array('name' => 'addBalance',
'parameters' => array($account,$sub_action_parameter),
'logs' => array('success' => sprintf('SIP account %s@%s balance has been increased with %s',$key['username'],$key['domain'],$sub_action_parameter)
)
)
);
$this->SOAPEngine->execute($function);
}
}
print "</ol>";
}
}
class SIPAliasesActions extends Actions {
var $actions=array(
'delete' => 'Delete SIP aliases'
);
function SIPAliases(&$SOAPEngine) {
$this->Actions(&$SOAPEngine);
}
function performActions($selectionKeys,$action,$sub_action_parameter) {
if (!in_array($action,array_keys($this->actions))) {
print "<font color=red>Error: Invalid action $action</font>";
return false;
}
print "<ol>";
foreach($selectionKeys as $key) {
print "<li>";
flush();
//printf ("Performing action=%s on key=%s",$action,$key);
$alias=array('username' => $key['username'],
'domain' => $key['domain']
);
if ($action=='delete') {
$function=array('commit' => array('name' => 'deleteAlias',
'parameters' => array($alias),
'logs' => array('success' => sprintf('SIP alias %s@%s has been deleted',$key['username'],$key['domain'])
)
)
);
//$this->SOAPEngine->execute($function);
}
}
print "</ol>";
}
}
class ENUMMappingsActions extends Actions {
var $actions=array(
'delete' => 'Delete ENUM mappings'
);
function ENUMMappingsActions(&$SOAPEngine) {
$this->Actions(&$SOAPEngine);
}
function performActions($selectionKeys,$action,$sub_action_parameter) {
if (!in_array($action,array_keys($this->actions))) {
print "<font color=red>Error: Invalid action $action</font>";
return false;
}
print "<ol>";
foreach($selectionKeys as $key) {
flush();
print "<li>";
if ($action=='delete') {
//printf ("Performing action=%s on key=%s",$action,$key);
$enum_id=array('number' => $key['number'],
'tld' => $key['tld']
);
$function=array('commit' => array('name' => 'deleteNumber',
'parameters' => array($enum_id),
'logs' => array('success' => sprintf('ENUM number +%s under %s has been deleted',$key['number'],$key['tld'])
)
)
);
$this->SOAPEngine->execute($function);
}
}
print "</ol>";
}
}
?>
diff --git a/rating_lib.phtml b/rating_lib.phtml
index f142c0e..2b2a78a 100644
--- a/rating_lib.phtml
+++ b/rating_lib.phtml
@@ -1,4522 +1,4522 @@
<?
class Rate {
var $priceDenominator = 10000; // allow sub cents
var $priceDecimalDigits = 4; // web display
var $minimumDurationCharged = 0; // 0 to cancel it
var $durationPeriodRated = 60; // in seconds
var $trafficSizeRated = 1024; // in KBytes, default 1MByte
var $minimumDuration = 0; // minimum duration to rate, if call is shorter the price is zero
function Rate(&$parent) {
$this->CDRS = &$parent->CDRS;
if ($this->CDRS->CDRTool['rating']['priceDenominator']) {
$this->priceDenominator=$this->CDRS->CDRTool['rating']['priceDenominator'];
}
if ($this->CDRS->CDRTool['rating']['priceDecimalDigits']) {
$this->priceDecimalDigits=$this->CDRS->CDRTool['rating']['priceDecimalDigits'];
}
if ($this->CDRS->CDRTool['rating']['minimumDurationCharged']) {
// round call for rating to minimum X seconds, is overwritten by settings per customer
$this->minimumDurationCharged=$this->CDRS->CDRTool['rating']['minimumDurationCharged'];
}
if ($this->CDRS->CDRTool['rating']['durationPeriodRated']) {
$this->durationPeriodRated=$this->CDRS->CDRTool['rating']['durationPeriodRated'];
}
if ($this->CDRS->CDRTool['rating']['trafficSizeRated']) {
$this->trafficSizeRated=$this->CDRS->CDRTool['rating']['trafficSizeRated'];
}
if ($this->CDRS->CDRTool['rating']['minimumDuration']) {
// if call is shorter than this, it has zero cost
$this->minimumDuration=$this->CDRS->CDRTool['rating']['minimumDuration'];
}
$this->fromEmail = $this->CDRS->CDRTool['provider']['fromEmail'];
$this->toEmail = $this->CDRS->CDRTool['provider']['toEmail'];
$this->bccEmail = $this->CDRS->CDRTool['provider']['bccEmail'];
if ($this->fromEmail) $this->extraHeaders="From: $fromEmail\r\nBCC: $this->fromEmail";
if ($this->bccEmail) $this->extraHeaders=$this->extraHeaders.",".$this->bccEmail;
}
function GetBillingTimezone() {
if ($this->RatingTables->customers[$this->BillingPartyId]['timezone']) {
dprint("Found billing party = $this->BillingPartyId");
return $this->RatingTables->customers[$this->BillingPartyId]['timezone'];
} elseif ($this->RatingTables->customers[$this->domain]['timezone']) {
dprint("Found billing party = $this->domain");
return $this->RatingTables->customers[$this->domain]['timezone'];
} elseif ($this->RatingTables->customers[$this->gateway]['timezone']) {
dprint("Found billing party = $this->gateway");
return $this->RatingTables->customers[$this->gateway]['timezone'];
} else {
dprint("Found billing party = default");
return $this->CDRS->CDRTool['provider']['timezone'];
}
}
function getRateFromNetwork(&$RateDictionary,&$fp) {
$countEndofLines=0;
//dprint_r($RateDictionary);
$cmd="ShowPrice";
foreach (array_keys(&$RateDictionary) as $key) {
$cmd=$cmd." ".$key."=".$RateDictionary[$key]." ";
}
dprint("command: $cmd");
$this->price = "0";
$this->pricePrint = "";
$this->rateInfo = "";
if (fputs($fp,"$cmd\n") !== false) {
$i=0;
while ($i < 200) {
$i++;
$line = fgets($fp,1024);
if (!$line) {
syslog(LOG_NOTICE, "Error: getRateFromNetwork(): connection to network socket died");
break;
}
//dprint("read: $line");
if (preg_match("/^\n/",$line) || preg_match("/^END/",$line)) {
dprint("Found \\n or END");
break;
}
if ($i == 1) {
$this->price = trim($line);
$this->pricePrint = number_format($this->price,4);
continue;
}
$this->rateInfo.=$line;
}
//dprint_r($this->rateInfo);
}
}
function calculate(&$dictionary) {
dprint("<b>Rate->calculate(&dictionary)</b>");
$this->price=0;
if ($this->duration > $this->minimumDuration) return 0;
//dprint_r($dictionary);
/////////////////////////////////////////////////////
// required fields passed from a CDR structure
//
// Session start time
$this->id = $dictionary['id'];
$this->callId = $dictionary['callId'];
$this->timestamp = $dictionary['timestamp'];
// Session usage, type and destination Id
$this->duration = $dictionary['duration'];
$this->traffic = $dictionary['traffic'];
$this->applicationType = $dictionary['applicationType'];
$this->DestinationId = $dictionary['DestinationId'];
// Billable entities we try to best match the rating tables
// against
$this->BillingPartyId = $dictionary['BillingPartyId'];
$this->domain = $dictionary['domain'];
$this->gateway = $dictionary['gateway'];
// Contain all rating tables load once when
// normalization process starts in CDRS parent class
$this->RatingTables = &$dictionary['RatingTables'];
//
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
// informational fields from CDR structure
$this->destinationName = $dictionary['destinationName'];
$this->aNumber = $dictionary['aNumber'];
$this->cNumber = $dictionary['cNumber'];
//////////////////////////////////////////////////////////
if (!$this->duration) $this->duration = 0;
if (!$this->traffic) $this->traffic = 0;
if (!strlen($this->applicationType)) $this->applicationType='audio';
$trafficRate = 0;
$durationRate = 0;
$foundRates=array();
if (!$this->DestinationId) {
dprint("Could not find destination id for $this->cNumber");
}
$this->billingTimezone = $this->GetBillingTimezone();
$this->startTimeBilling = getLocalTime($this->billingTimezone,$this->timestamp);
list($dateText,$timeText) = explode(" ",trim($this->startTimeBilling));
$Bdate = explode("-",$dateText);
$Btime = explode(":",$timeText);
$this->timestampBilling = mktime($Btime[0], $Btime[1], $Btime[2], $Bdate[1], $Bdate[2], $Bdate[0]);
$this->startTimeBilling = Date("Y-m-d H:i:s",$this->timestampBilling);
dprint("Billing timezone = $this->billingTimezone ");
dprint("Billing start time: $this->startTimeBilling");
dprint("BillingPartyId: $this->BillingPartyId");
dprint("Billing domain: $this->domain");
dprint("Billing gateway: $this->gateway");
if (!$this->GetProfiles()) {
return 0;
}
$this->trafficKB=number_format($this->traffic/1024,0,"","");
if (!$this->destinationName) {
$this->destinationNamePrint="Internet";
} else {
$this->destinationNamePrint=$this->destinationName;
}
if ($this->increment >= 1) {
// increase the billed duration to the next increment
$this->duration = $this->increment * ceil($this->duration / $this->increment);
}
if ($this->min_duration >= 1) {
$this->minimumDurationCharged = $this->min_duration;
}
if ($this->duration && $this->DestinationId) {
dprint("Rate $this->applicationType session having $this->duration seconds to $this->cNumber DestinationId=$this->DestinationId ($this->destinationName)");
unset($IntervalsForPricing);
$this->rateInfo .=
" App: $this->applicationType\n".
" Destination: $this->DestinationId ($this->destinationNamePrint)\n".
" Customer: $this->CustomerProfile\n";
if ($this->increment > 1) {
$this->rateInfo .=
" Increment: $this->increment s\n";
}
if ($this->min_duration > 1) {
$this->rateInfo .=
" Min duration: $this->min_duration s\n";
}
$i=0;
$durationRatedTotal=0;
// get recursively a set of arrays with rates
// until we billed the whole duration
while ($durationRatedTotal < $this->duration) {
dprint("Getting rate $i");
if ($i == "0") {
$dayofweek = date("w",$this->timestampBilling);
$hourofday = date("G",$this->timestampBilling);
$dayofyear = date("Y-m-d",$this->timestampBilling);
} else {
$dayofweek = date("w",$this->timestampBilling+$durationRatedTotal);
$hourofday = $foundRate["nextHourOfDay"];
$dayofyear = date("Y-m-d",$this->timestampBilling+$durationRatedTotal);
}
$foundRate = $this->GetRate($dayofyear,$dayofweek,$hourofday,$durationRatedTotal);
$durationRatedTotal = $durationRatedTotal + $foundRate["duration"];
if (!$foundRate['rate']) {
return 0;
}
$foundRates[] = $foundRate;
$i++;
if ($i > 10) {
// possible loop because of wrong coding make sure we can end this somehow
$body="Rating of call $this->id (DestId=$this->DestinationId) has more than 10 spans. It could be a serious bug.\n";
mail($this->toEmail, "CDRTool rating problem", $body , $this->extraHeaders);
syslog(LOG_NOTICE, "Error: Rating of call $this->id (DestId=$this->DestinationId) has more than 10 spans.");
return 0;
break;
}
}
}
$j=0;
$span=0;
foreach ($foundRates as $thisRate) {
$spanPrice=0;
$span++;
if ($j > 0) {
$payConnect=0;
$durationForRating=$thisRate['duration'];
} else {
$payConnect=1;
if ($this->minimumDurationCharged && $this->duration < $this->minimumDurationCharged) {
$durationForRating=$this->minimumDurationCharged;
} else {
$durationForRating=$thisRate['duration'];
}
}
$connectCost = $thisRate[values][connectCost];
$durationRate = $thisRate[values][durationRate];
$trafficRate = $thisRate[values][trafficRate];
if ($span=="1") {
$connectCostSpan=$connectCost;
} else {
$connectCostSpan=0;
}
$connectCostPrint = number_format($connectCostSpan/$this->priceDenominator,$this->priceDecimalDigits);
$durationRatePrint = number_format($durationRate/$this->priceDenominator,$this->priceDecimalDigits);
$trafficRatePrint = number_format($trafficRate/$this->priceDenominator,$this->priceDecimalDigits);
if (!$connectCostSpan) $connectCostSpan=0;
if (!$durationRate) $durationRate=0;
if (!$trafficRate) $trafficRate=0;
if (!$this->inputTraffic) $this->inputTraffic=0;
if (!$this->outputTraffic) $this->outputTraffic=0;
if ($span>1) $this->rateInfo .= "--\n";
dprint("price=price+connectCostSpan/priceDenominator*payConnect+
durationRate*durationForRating/durationPeriodRated/priceDenominator+
trafficRate/priceDenominator/trafficSizeRated*(inputTraffic+outputTraffic)/8");
dprint("price=$this->price+$connectCostSpan/$this->priceDenominator*$payConnect+
$durationRate*$durationForRating/$this->durationPeriodRated/$this->priceDenominator+
$trafficRate/$this->priceDenominator/$this->trafficSizeRated*($this->inputTraffic+$this->outputTraffic)/8");
$spanPrice = $durationRate*$durationForRating/$this->durationPeriodRated/$this->priceDenominator+
$trafficRate/$this->priceDenominator/$this->trafficSizeRated*($this->inputTraffic+$this->outputTraffic)/8;
$this->price = $this->price+$spanPrice;
$spanPricePrint = number_format($spanPrice,$this->priceDecimalDigits);
$this->rateSyslog="";
if ($span=="1" && $thisRate[profile]) {
$this->rateInfo .=
" Connect fee: $connectCostPrint\n".
"--\n";
$this->rateSyslog=$this->rateSyslog."ConnectFee=$connectCostPrint ";
$this->price = $this->price+$connectCostSpan/$this->priceDenominator*$payConnect;
}
$this->rateInfo .=
" Span: $span\n".
" Duration: $durationForRating s\n";
$this->rateSyslog=$this->rateSyslog."Span=$span Duration=$durationForRating DestId=$this->DestinationId $thisRate[customer]";
if ($this->CDRS->CSCODE) {
// We found a Peer Carrier so we will change BillingPartyId
if ($this->CDRS->CDRTool[normalize][CS_CODES][$this->CDRS->CSCODE][name]) {
$CarrierName = $this->CDRS->CDRTool[normalize][CS_CODES][$this->CDRS->CSCODE][name];
} else {
$CarrierName=$this->CDRS->CSCODE;
}
$this->rateInfo .=
" Carrier: $CarrierName\n";
}
if ($thisRate[profile]) {
$this->rateInfo .=
" StartTime: $this->startTimeBilling ($this->billingTimezone)\n".
" ProfileId: $thisRate[profile] for $thisRate[day]\n".
" RateId: $thisRate[rate] for $thisRate[interval]h\n".
" Rate: $durationRatePrint / $this->durationPeriodRated s\n".
" Price: $spanPricePrint\n";
#" TrafficRate: $trafficRatePrint / $this->trafficSizeRated KBytes\n".
$this->rateSyslog=$this->rateSyslog." Profile=$thisRate[profile] Period=$thisRate[day] Rate=$thisRate[rate] Interval=$thisRate[interval] Cost=$durationRatePrint/$this->durationPeriodRated";
} else {
$this->rateInfo .=
" ProfileId: none\n".
" RateId: none\n";
$this->rateSyslog=$this->rateSyslog." Profile=none, Rate=none";
}
$this->rateSyslog=$this->rateSyslog." Price=".sprintf("%.4f",$spanPrice);
syslog(LOG_NOTICE, $this->rateSyslog);
dprint ($this->price);
$j++;
}
$this->rateInfo=trim($this->rateInfo);
$this->price=sprintf("%.4f",$this->price);
if ($this->price > 0) {
$this->pricePrint=number_format($this->price,$this->priceDecimalDigits);
} else if ($thisRate[profile]) {
if ($j) {
if ($this->DestinationId && !strlen($durationRate)) {
if (!$this->CDRS->brokenRates[$this->DestinationId]) {
dprint ("<font color=red>Warning: Found destination $this->DestinationId ($this->destinationName) with no Rate</font>\n");
}
$this->CDRS->brokenRates[$this->DestinationId]++;
}
}
$this->pricePrint="";
}
return 1;
}
function GetProfiles() {
/*
lookup the profile_name in billing_customers in the following order:
subscriber, domain, gateway (based on $dayofweek):
- profile1 matches days [1-5] (Work-day)
- profile2 matches days [6-0] (Week-end)
- week starts with 0 Sunday and ends with 6 Saturday
Alternatively look for profile1_alt and profile2_alt
If no rates are found for destination in the profileX,
than lookup rates in profileX_alt
*/
if ($this->RatingTables->customers[$this->BillingPartyId]['profile1'] && $this->RatingTables->customers[$this->BillingPartyId]['profile2']) {
// Account XXX@domain.com has rating profiles assigned
$this->allProfiles = $this->RatingTables->customers[$this->BillingPartyId];
$this->CustomerProfile = "subscriber=$this->BillingPartyId";
$this->increment = $this->RatingTables->customers[$this->BillingPartyId]['increment'];
$this->min_duration = $this->RatingTables->customers[$this->BillingPartyId]['min_duration'];
} elseif ($this->RatingTables->customers[$this->domain]['profile1'] && $this->RatingTables->customers[$this->domain]['profile2']) {
// Domain domain.com has rating profiles assigned
$this->allProfiles = $this->RatingTables->customers[$this->domain];
$this->CustomerProfile = "domain=$this->domain";
$this->increment = $this->RatingTables->customers[$this->domain]['increment'];
$this->min_duration = $this->RatingTables->customers[$this->domain]['min_duration'];
} elseif ($this->RatingTables->customers[$this->gateway]['profile1'] && $this->RatingTables->customers[$this->gateway]['profile2']) {
// Gateway (Source IP) has rating profiles assigned
$this->allProfiles = $this->RatingTables->customers[$this->gateway];
$this->CustomerProfile = "gateway=$this->gateway";
$this->increment = $this->RatingTables->customers[$this->gateway]['increment'];
$this->min_duration = $this->RatingTables->customers[$this->gateway]['min_duration'];
} elseif ($this->RatingTables->customers['default']['profile1'] && $this->RatingTables->customers['default']['profile2']) {
// Otherwise we use the default profiles
$this->allProfiles = $this->RatingTables->customers['default'];
$this->CustomerProfile = "default";
$this->increment = $this->RatingTables->customers['default']['increment'];
$this->min_duration = $this->RatingTables->customers['default']['min_duration'];
}
if ($this->min_duration > 1) $this->minimumDurationCharged = $this->min_duration;
if (!$this->allProfiles[profile1] || !$this->allProfiles[profile2] ) {
dprint("Cannot find billing profiles for $this->BillingPartyId");
return 0;
}
return 1;
}
function GetRate($dayofyear,$dayofweek,$hourofday,$durationRatedAlready) {
dprint("<b>GetRate(DayOfYear=$dayofyear,DayOfWeek=$dayofweek,HourOfDay=$hourofday,durationRatedAlready=$durationRatedAlready)</b>");
/*
// Required information from CDR structure
$this->BillingPartyId # calling subscriber
$this->domain # multiple callers may belong to same domain
$this->gateway # multiple callers may belong to the same gateway
$this->cNumber # E164 destination prefixed with 00 (e.g. 0041 CH)
$this->DestinationId # longest matched DestinationId
// pertinent to the curent rating SPAN (a span = same profile like evening hours)
$hourofday # which hour of teh day started for peak/ofpeak rates
$dayofweek # which day of the week for matching profiles
$dayofyear # which day of the year for matching holidays
$durationRatedAlready= the full duration for which a profile is defined (e.g. 0800-1800)
// the call is called recursively until the $durationRatedAlready = $CDR->duration
// when a call spans multiple profiles. If we span multiple profiles we must call
// the function again to lookup the corect rates
Rating logic
------------
1. using the profile_name found, lookup the rate_name based
on $hourofday in billing_profiles
- the day may be split in maximum 4 periods
- each day starts with hour 0 and ends with hour 24
- rate_name1 defines the first interval after hour 0
- rate_name2 defines the first interval after rate_name1
- rate_name3 defines the first interval after rate_name2
- rate_name4 defines the first interval after rate_name3
When the hour matches an interval use the rate_nameX found
to lookup the rate in billing_rates
- if no record is found use the rate called 'default'
2. lookup in billing_rates the record having same name found above
and billing_rates.destination = $this->DestinationId
- return an array with all the values to
$this->calculate() function that called us
*/
// get work-day or weekend profile
if ($this->RatingTables->holidays[$dayofyear]) {
$this->profileName = $this->allProfiles[profile2];
$this->profileNameAlt = $this->allProfiles[profile2_alt];
$this->PeriodOfProfile = "weekend";
} else {
if ($dayofweek >=1 && $dayofweek <=5 ) {
$this->profileName = $this->allProfiles[profile1];
$this->profileNameAlt = $this->allProfiles[profile1_alt];
$this->PeriodOfProfile = "weekday";
} else {
$this->profileName = $this->allProfiles[profile2];
$this->profileNameAlt = $this->allProfiles[profile2_alt];
$this->PeriodOfProfile = "weekend";
}
}
dprint("Found profile=$this->profileName for $this->PeriodOfProfile day=$dayofweek hour=$hourofday");
if ($this->profileNameAlt) dprint ("Alternative profile=$this->profileNameAlt");
// get rate for the time of the day
$timestampNextProfile = $this->timestampBilling + $durationRatedAlready;
$profileValues = $this->RatingTables->profiles[$this->profileName];
$profileValuesAlt = $this->RatingTables->profiles[$this->profileNameAlt];
if (is_array($profileValues)) {
if ($hourofday < $profileValues['hour1'] ) {
$this->rateName = $profileValues['rate_name1'];
$this->timeInterval = "0-".$profileValues['hour1'];
$foundProfile = $profileValues['hour1'];
$this->nextProfile = $profileValues['hour1'];
} else if ($hourofday < $profileValues['hour2']) {
$this->rateName = $profileValues['rate_name2'];
$this->timeInterval = $profileValues['hour1']."-".$profileValues['hour2'];
$foundProfile = $profileValues['hour2'];
$this->nextProfile = $profileValues['hour2'];
} else if ($hourofday < $profileValues['hour3']) {
$this->rateName = $profileValues['rate_name3'];
$this->timeInterval = $profileValues['hour2']."-".$profileValues['hour3'];
$foundProfile = $profileValues['hour3'];
$this->nextProfile = $profileValues['hour3'];
} else if ($hourofday < $profileValues['hour4']) {
$this->rateName = $profileValues['rate_name4'];
$this->timeInterval = $profileValues['hour3']."-".$profileValues['hour4'];
$foundProfile = $profileValues['hour4'];
$this->nextProfile = 0;
}
if ($this->rateName) {
dprint("Found rate=$this->rateName for interval=$this->timeInterval in profile=$this->profileName");
$found_history=false;
//get historical rating if exists
if (is_array($this->RatingTables->ratesHistory[$this->rateName][$this->DestinationId][$this->applicationType])) {
dprint('Found historical rates for this destination');
dprint_r(($this->RatingTables->ratesHistory[$this->rateName][$this->DestinationId][$this->applicationType]));
$h=0;
foreach (($this->RatingTables->ratesHistory[$this->rateName][$this->DestinationId][$this->applicationType]) as $_idx) {
$h++;
dprint("Checking rate history id $h");
if ($_idx['startDate'] <= $this->timestamp) {
if ($_idx['endDate'] > $this->timestamp) {
// found historical rate
dprint("Found historical rate $h");
$found_history=true;
$this->rateValues=$_idx;
break;
} else {
$_log=sprintf("Interval missmatch %s < %s",$_idx['endDate'],$this->timestamp);
dprint($_log);
continue;
}
} else {
$_log=sprintf("Interval missmatch %s > %s",$_idx['startDate'],$this->timestamp);
dprint($_log);
continue;
}
}
}
if (!$found_history) {
$this->rateValues=$this->RatingTables->rates[$this->rateName][$this->DestinationId][$this->applicationType];
}
} else {
dprint("No rates for destination=$this->DestinationId. Trying alternative profile=$this->profileNameAlt");
dprint_r($profileValues);
}
if (!$this->rateValues && is_array($profileValuesAlt)) {
dprint("No rates for destination=$this->DestinationId in rate=$this->rateName. Trying alternative profile=$this->profileNameAlt");
if ($hourofday < $profileValuesAlt['hour1'] ) {
$this->rateName = $profileValuesAlt['rate_name1'];
$this->timeInterval = "0-".$profileValuesAlt['hour1'];
$foundProfile = $profileValuesAlt['hour1'];
$this->nextProfile = $profileValuesAlt['hour1'];
} else if ($hourofday < $profileValuesAlt['hour2']) {
$this->rateName = $profileValuesAlt['rate_name2'];
$this->timeInterval = $profileValuesAlt['hour1']."-".$profileValuesAlt['hour2'];
$foundProfile = $profileValuesAlt['hour2'];
$this->nextProfile = $profileValuesAlt['hour2'];
} else if ($hourofday < $profileValuesAlt['hour3']) {
$this->rateName = $profileValuesAlt['rate_name3'];
$this->timeInterval = $profileValuesAlt['hour2']."-".$profileValuesAlt['hour3'];
$foundProfile = $profileValuesAlt['hour3'];
$this->nextProfile = $profileValuesAlt['hour3'];
} else if ($hourofday < $profileValuesAlt['hour4']) {
$this->rateName = $profileValuesAlt['rate_name4'];
$this->timeInterval = $profileValuesAlt['hour3']."-".$profileValuesAlt['hour4'];
$foundProfile = $profileValuesAlt['hour4'];
$this->nextProfile = 0;
}
if ($this->rateName) {
dprint("Found rate=$this->rateName for interval=$this->timeInterval in alternative profile=$this->profileNameAlt");
$found_history=false;
//get historical rating if exists
if (is_array($this->RatingTables->ratesHistory[$this->rateName][$this->DestinationId][$this->applicationType])) {
dprint('Found historical rates for this destination');
dprint_r(($this->RatingTables->ratesHistory[$this->rateName][$this->DestinationId][$this->applicationType]));
$h=0;
foreach (($this->RatingTables->ratesHistory[$this->rateName][$this->DestinationId][$this->applicationType]) as $_idx) {
$h++;
dprint("Checking rate history id $h");
if ($_idx['startDate'] <= $this->timestamp) {
if ($_idx['endDate'] > $this->timestamp) {
// found historical rate
dprint("Found historical rate $h");
$found_history=true;
$this->rateValues=$_idx;
break;
} else {
$_log=sprintf("Interval missmatch %s < %s",$_idx['endDate'],$this->timestamp);
dprint($_log);
continue;
}
} else {
$_log=sprintf("Interval missmatch %s > %s",$_idx['startDate'],$this->timestamp);
dprint($_log);
continue;
}
}
}
if (!$found_history) {
$this->rateValues=$this->RatingTables->rates[$this->rateName][$this->DestinationId][$this->applicationType];
}
} else {
dprint("No rates for destination $this->DestinationId in alternative profile=$this->profileNameAlt.");
}
}
}
if (!$this->rateValues) {
$this->rateNotFound=true;
$log=sprintf("Error: Cannot find rates for callid=%s, customer %s, destination=%s, profile=%s, app=%s",
$this->callId,$this->CustomerProfile,$this->DestinationId,$this->profileName,$this->applicationType);
dprint($log);
$subject=$this->CDRS->CDRTool['provider']['service']." - CDRTool rating problem";
mail($this->toEmail, $subject, $log, $this->extraHeaders);
syslog(LOG_NOTICE, $log);
return 0;
}
if ($this->nextProfile == "24") $this->nextProfile = 0;
$DST = Date("I",$timestampNextProfile);
if (!$this->nextProfile) {
// check it we change daylight saving time tomorrow
// yes this cann happen and we must apply a different rate
$timestampNextProfile =$timestampNextProfile+24*3600;
$DSTNext = Date("I",$timestampNextProfile);
if ($DST != $DSTNext) {
if ($DSTNext==0) {
$timestampNextProfile=$timestampNextProfile+3600;
dprint("DST change: adding one hour");
} else if ($DSTNext==1) {
$timestampNextProfile=$timestampNextProfile-3600;
dprint("DST change: substracting one hour");
}
}
}
$durationToRate=$this->duration-$durationRatedAlready;
$month = Date("m",$timestampNextProfile);
$day = Date("d",$timestampNextProfile);
$year = Date("Y",$timestampNextProfile);
$nextProfileTimestamp=mktime($this->nextProfile, 0, 0, $month,$day,$year);
$npdt=Date("Y-m-d H:i", $nextProfileTimestamp);
dprint("Next profile datetime: $npdt");
$timeTillNextProfile=$nextProfileTimestamp-$this->timestampBilling;
if ($timeTillNextProfile < 0) {
$body = "Negative period till next billing profile for call id $this->callId\n";
mail($this->toEmail, "CDRTool rating problem", $body , $this->extraHeaders);
syslog(LOG_NOTICE, "Error: Negative period till next billing profile for call id $this->callId");
}
dprint("Time till next profile: $timeTillNextProfile seconds");
if ($durationToRate > $timeTillNextProfile) {
$diff=$durationToRate-$timeTillNextProfile;
dprint("Call of $durationToRate seconds will extend $diff seconds into next profile $this->nextProfile ");
$this->durationRated=$timeTillNextProfile;
} else {
dprint("Call of $durationToRate seconds fits within curent profile");
$this->durationRated=$durationToRate;
}
$rate=array(
"customer" =>$this->CustomerProfile,
"application" =>$this->applicationType,
"profile" =>$this->profileName,
"day" =>$this->PeriodOfProfile,
"destinationId" =>$this->DestinationId,
"duration" =>$this->durationRated,
"rate" =>$this->rateName,
"values" =>$this->rateValues,
"interval" =>$this->timeInterval,
"nextHourOfDay" =>$this->nextProfile
);
return $rate;
}
function MaxSessionTime($dictionary) {
// Used for prepaid application
dprint("<b>Rate->MaxSessionTime()</b>");
$trafficRate = 0;
$durationRate = 0;
/////////////////////////////////////////////////////
// required fields passed from the CDR structure
//
$this->timestamp = time();
$this->callId = $dictionary['callId'];
$this->DestinationId = $dictionary['DestinationId'];
$this->BillingPartyId = $dictionary['BillingPartyId'];
$this->domain = $dictionary['domain'];
$this->duration = $dictionary['duration'];
$this->aNumber = $dictionary['aNumber'];
$this->cNumber = $dictionary['cNumber'];
$this->RatingTables = $dictionary['RatingTables'];
$this->applicationType = $dictionary['Application'];
$Balance = $dictionary['Balance'];
if (!strlen($this->applicationType)) $this->applicationType='audio';
if (!$this->DestinationId) {
dprint("Could not find any destination id found for $this->cNumber");
return 0;
}
$this->billingTimezone = $this->GetBillingTimezone();
$this->startTimeBilling = getLocalTime($this->billingTimezone,$this->timestamp);
list($dateText,$timeText) = explode(" ",trim($this->startTimeBilling));
$Bdate = explode("-",$dateText);
$Btime = explode(":",$timeText);
$this->timestampBilling = mktime($Btime[0], $Btime[1], $Btime[2], $Bdate[1], $Bdate[2], $Bdate[0]);
$this->startTimeBilling = Date("Y-m-d H:i:s",$this->timestampBilling);
dprint("Billing timezone = $this->billingTimezone ");
dprint("Billing start time: $this->startTimeBilling");
dprint("Get rate of PSTN call to $this->cNumber DestId = $this->DestinationId, Balance = $Balance");
$i=0;
$durationRatedTotal=0;
$this->GetProfiles();
while ($Balance > 0 ) {
$span++;
//syslog(LOG_NOTICE,"Getting rate $i");
if ($i == "0") {
$dayofweek = date("w",$this->timestampBilling);
$hourofday = date("G",$this->timestampBilling);
$dayofyear = date("Y-m-d",$this->timestampBilling);
} else {
$dayofweek = date("w",$this->timestampBilling+$durationRatedTotal);
$hourofday = $foundRate["nextHourOfDay"];
$dayofyear = date("Y-m-d",$this->timestampBilling+$durationRatedTotal);
}
$foundRate = $this->GetRate($dayofyear,$dayofweek,$hourofday,$durationRatedTotal);
if ($this->rateNotFound) {
// break here to avoid loops
break;
}
dprint_r($foundRate);
$thisRate=$foundRate;
if ($j > 0) {
$payConnect=0;
$durationForRating = $thisRate['duration'];
} else {
$payConnect=1;
if ($this->minimumDurationCharged && $this->duration < $this->minimumDurationCharged) {
$durationForRating=$this->minimumDurationCharged;
} else {
$durationForRating=$thisRate['duration'];
}
}
$j++;
$connectCost = $thisRate[values][connectCost];
$durationRate = $thisRate[values][durationRate];
if ($span=="1") {
$connectCostSpan=$connectCost;
$setupBalanceRequired=$connectCost/$this->priceDenominator;
if ($connectCost && $Balance <= $setupBalanceRequired) {
syslog(LOG_NOTICE,"Balance too small: $Balance <= $setupBalanceRequired");
return 0;
}
$Balance = $Balance-$setupBalanceRequired;
} else {
$connectCostSpan=0;
$setupBalanceRequired=0;
}
$connectCostPrint = number_format($connectCostSpan/$this->priceDenominator,$this->priceDecimalDigits);
$durationRatePrint = number_format($durationRate/$this->priceDenominator,$this->priceDecimalDigits);
$spanPrice = $this->price+$setupBalanceRequired*$payConnect+
$durationRate*$durationForRating/$this->durationPeriodRated/$this->priceDenominator;
//syslog(LOG_NOTICE,"price=$this->price+$connectCostSpan/$this->priceDenominator*$payConnect+$durationRate*$durationForRating/$this->durationPeriodRated/$this->priceDenominator=$spanPrice");
if ($Balance > $spanPrice) {
$Balance = $Balance-$spanPrice;
$durationRatedTotal = $durationRatedTotal+ $foundRate["duration"];
} else {
$durationAllowedinThisSpan = $Balance /
$durationRate * $this->durationPeriodRated * $this->priceDenominator;
$rateOfThisSpan=$durationRate/$this->priceDenominator;
/*
syslog(LOG_NOTICE,"Balance = $Balance");
syslog(LOG_NOTICE,"setupBalanceRequired = $setupBalanceRequired");
syslog(LOG_NOTICE,"rateOfThisSpan = $rateOfThisSpan");
syslog(LOG_NOTICE,"spanPrice = $spanPrice");
syslog(LOG_NOTICE,"durationRatedTotal = $durationRatedTotal");
syslog(LOG_NOTICE,"durationPeriodRated = $this->durationPeriodRated");
syslog(LOG_NOTICE,"durationAllowedinThisSpan = $durationAllowedinThisSpan");
*/
$durationRatedTotal=$durationRatedTotal + $durationAllowedinThisSpan;
$Balance=$Balance-$spanPrice;
return $durationRatedTotal;
}
if ($durationRatedTotal >= $this->duration) {
return sprintf("%f",$durationRatedTotal);
}
$i++;
if ($i>10) {
return sprintf("%f",$durationRatedTotal);
break;
}
}
return 0;
}
}
class RatingTables {
var $filesToImport=array();
var $importFilesPatterns=array('rates_history',
'rates',
'profiles',
'destinations',
'customers'
);
function RatingTables () {
global $CDRTool;
$this->cdrtool = new DB_cdrtool;
$this->CDRTool = $CDRTool;
$this->cdrtool->Halt_On_Error="no";
$period=$CDRTool['rating'][durationPeriodRated] = 60;
$this->tables=array(
"destinations"=>array("name"=>"Destinations",
"keys"=>array("id"),
"exceptions" =>array(),
"domainFilterColumn"=>"domain",
"fields"=>array(
"gateway"=>array("size"=>15,
"name"=>"Gateway"
),
"domain"=>array("size"=>15,
"name"=>"Domain"
),
"subscriber"=>array("size"=>15,
"name"=>"Subscriber"
),
"dest_id"=>array("size"=>20,
"name"=>"Destination Id"
),
"dest_name"=>array("size"=>20,
"name"=>"Description"
)
)
),
"billing_customers"=>array("name"=>"Customers",
"keys"=>array("id"),
"domainFilterColumn"=>"domain",
"exceptions" =>array('country_code'),
"fields"=>array("gateway"=>array("size"=>15,
"name"=>"Gateway"
),
"domain"=>array("size"=>15,
"name"=>"Domain"
),
"subscriber"=>array("size"=>15,
"name"=>"Subscriber"
),
"profile_name1"=>array("size"=>8,
"name"=>"WeekDay"
),
"profile_name1_alt"=>array("size"=>8,
"name"=>"Fallback"
),
"profile_name2"=>array("size"=>8,
"name"=>"WeekEnd"
),
"profile_name2_alt"=>array("size"=>8,
"name"=>"Fallback"
),
"timezone" =>array("size"=>16,
"name"=>"Timezone"
),
"increment" =>array("size"=>3,
"name"=>"Incr"
),
"min_duration" =>array("size"=>3,
"name"=>"Minim"
),
"country_code" =>array("size"=>3,
"name"=>"CC"
)
)
),
"billing_profiles"=>array("name"=>"Profiles",
"keys"=>array("id"),
"exceptions" =>array(),
"size"=>6,
"domainFilterColumn"=>"domain",
"fields"=>array(
"gateway"=>array("size"=>15,
"name"=>"Gateway"
),
"domain"=>array("size"=>15,
"name"=>"Domain"
),
"subscriber"=>array("size"=>15,
"name"=>"Subscriber"
),
"name"=>array("size"=>10,
"name"=>"Profile Id"
),
"rate_name1"=>array("size"=>10,
"name"=>"Rate Id1"
),
"hour1"=>array("size"=>3,
"name"=>"00-H1"
),
"rate_name2"=>array("size"=>10,
"name"=>"Rate Id2"
),
"hour2"=>array("size"=>3,
"name"=>"H1-H2"
),
"rate_name3"=>array("size"=>10,
"name"=>"Rate Id3"
),
"hour3"=>array("size"=>3,
"name"=>"H2-H3"
),
"rate_name4"=>array("size"=>10,
"name"=>"Rate Id4"
),
"hour4"=>array("size"=>3,
"name"=>"H3-24"
),
)
),
"billing_rates"=>array("name"=>"Rates",
"keys"=>array("id"),
"size"=>10,
"domainFilterColumn"=>"domain",
"exceptions" =>array('trafficRate'),
"fields"=>array(
"gateway"=>array("size"=>15,
"name"=>"Gateway"
),
"domain"=>array("size"=>15,
"name"=>"Domain"
),
"subscriber"=>array("size"=>15,
"name"=>"Subscriber"
),
"name"=>array("size"=>10,
"name"=>"Rate Id"
),
"destination"=>array("size"=>20,
"name"=>"Destination"
),
"durationRate"=>array("size"=>10,
"name"=>"Price"
),
"application"=>array("size"=>6,
"name"=>"App"
),
"connectCost"=>array("size"=>10,
"name"=>"Connect"
)
)
),
"billing_rates_history"=>array("name"=>"Rates history",
"keys"=>array("id"),
"size"=>10,
"domainFilterColumn"=>"domain",
"exceptions" =>array('trafficRate'),
"fields"=>array(
"gateway"=>array("size"=>15,
"name"=>"Gateway"
),
"domain"=>array("size"=>15,
"name"=>"Domain"
),
"subscriber"=>array("size"=>15,
"name"=>"Subscriber"
),
"name"=>array("size"=>10,
"name"=>"Rate Id"
),
"destination"=>array("size"=>20,
"name"=>"Destination"
),
"durationRate"=>array("size"=>10,
"name"=>"Price"
),
"application"=>array("size"=>6,
"name"=>"App"
),
"connectCost"=>array("size"=>10,
"name"=>"Connect"
),
"startDate"=>array("size"=>11,
"name"=>"Start Date"
),
"endDate"=>array("size"=>11,
"name"=>"End Date"
)
)
),
"prepaid"=>array("name"=>"Prepaid",
"keys"=>array("id"),
"size"=>15,
"exceptions" =>array(),
"domainFilterColumn"=>"account",
"fields"=>array("account"=>array("size"=>35,
"name"=>"Account",
"readonly"=>0
),
"balance"=>array("size"=>10,
"name"=>"Balance"
),
"change_date"=>array("size"=>19,
"name"=>"Last change",
"readonly"=>1
),
"call_lock"=>array("size"=>1,
"name"=>"Lock",
"readonly"=>0
),
"call_in_progress"=>array("size"=>18,
"name"=>"Start time",
"readonly"=>1
),
"last_call_price"=>array("size"=>10,
"name"=>"Last price",
"readonly"=>1
),
"maxsessiontime"=>array("size"=>5,
"name"=>"Max",
"readonly"=>1
),
"destination"=>array("size"=>15,
"name"=>"Destination",
"readonly"=>1
)
)
),
);
}
function ImportCSVFiles($dir=false) {
$mustReload=0;
if (!$dir) $dir=$this->CDRTool["Path"]."/csv";
$this->scanFilesForImport($dir);
foreach ($this->filesToImport as $file) {
$importFunction="Import".ucfirst($file['type']);
printf("Reading file %s\n",$file['path']);
$results = $this->$importFunction($file['path']);
$this->logImport($dir,$file['name'],$file['watermark'],$results);
$mustReload=$mustReload+$results;
}
return $mustReload;
}
function ImportRates($file) {
dprint("ImportRates($file)");
if (!$file || !is_readable($file) || !$fp = fopen($file, "r")) return 0;
$i=0;
$inserted = 0;
$updated = 0;
$deleted = 0;
print "Importing Rates:\n";
while ($buffer = fgets($fp,1024)) {
$buffer=trim($buffer);
$p = explode(",", $buffer);
$ops = trim($p[0]);
$gateway = trim($p[1]);
$domain = trim($p[2]);
$subscriber = trim($p[3]);
$profile = trim($p[4]);
$destination = trim($p[5]);
$durationRate = trim($p[6]);
//$trafficRate = trim($p[7]);
$application = trim($p[7]);
$connectCost = trim($p[8]);
if (!strlen($application)) $application='audio';
if ($ops=="1") {
$query=sprintf("insert into billing_rates
(
gateway,
domain,
subscriber,
name,
destination,
durationRate,
trafficRate,
application,
connectCost
) values (
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($profile),
addslashes($destination),
addslashes($durationRate),
addslashes($trafficRate),
addslashes($application),
addslashes($connectCost)
);
//dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$inserted++;
} else {
$failed++;
}
} else if ($ops=="3") {
$query=sprintf("delete from billing_rates
where gateway = '%s'
and domain = '%s'
and subscriber = '%s'
and name = '%s'
and destination = '%s'
and application = '%s'",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($profile),
addslashes($destination),
addslashes($application)
);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$deleted++;
}
} else if ($ops=="2") {
$query=sprintf("select * from billing_rates
where name = '%s'
and destination = '%s'
and gateway = '%s'
and domain = '%s'
and subscriber = '%s'
and application = '%s'
",
addslashes($profile),
addslashes($destination),
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($application)
);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->num_rows()) {
$query=sprintf("update billing_rates set
durationRate = '%s',
trafficRate = '%s',
connectCost = '%s'
where name = '%s'
and destination = '%s'
and gateway = '%s'
and domain = '%s'
and subscriber = '%s'
and application = '%s'
",
addslashes($durationRate),
addslashes($trafficRate),
addslashes($application),
addslashes($connectCost),
addslashes($profile),
addslashes($destination),
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($application)
);
dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$updated++;
}
} else {
$query=sprintf("insert into billing_rates
(
gateway,
domain,
subscriber,
name,
destination,
durationRate,
trafficRate,
application,
connectCost
) values (
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($profile),
addslashes($destination),
addslashes($durationRate),
addslashes($trafficRate),
addslashes($application),
addslashes($connectCost)
);
//dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$inserted++;
} else {
$failed++;
}
}
}
$j++;
if ($j=="10000") {
dprint("Loaded another $j rates");
flush();
$j=0;
}
$i++;
}
if ($i) print "Read $i records\n";
if ($inserted) print "Inserted $inserted records\n";
if ($updated) print "Updated $updated records\n";
if ($deleted) print "Delete $deleted records\n";
$results=$inserted+$updated+$deleted;
return $results;
}
function ImportRatesHistory($file) {
dprint("ImportRatesHistory($file)");
if (!$file || !is_readable($file) || !$fp = fopen($file, "r")) return 0;
$i=0;
$inserted = 0;
$updated = 0;
$deleted = 0;
print "Importing Rates history:\n";
while ($buffer = fgets($fp,1024)) {
$buffer=trim($buffer);
$p = explode(",", $buffer);
$ops = trim($p[0]);
$gateway = trim($p[1]);
$domain = trim($p[2]);
$subscriber = trim($p[3]);
$profile = trim($p[4]);
$destination = trim($p[5]);
$durationRate = trim($p[6]);
$trafficRate = trim($p[7]);
$application = trim($p[8]);
$connectCost = trim($p[9]);
$startDate = trim($p[10]);
$endDate = trim($p[11]);
if ($ops=="1") {
$query=sprintf("insert into billing_rates_history
(
gateway,
domain,
subscriber,
name,
destination,
durationRate,
trafficRate,
application,
connectCost,
startDate,
endDate
) values (
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($profile),
addslashes($destination),
addslashes($durationRate),
addslashes($trafficRate),
addslashes($application),
addslashes($connectCost),
addslashes($startDate),
addslashes($endDate)
);
//dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$inserted++;
} else {
$failed++;
}
} else if ($ops=="3") {
$query=sprintf("delete from billing_rates_history
where gateway = '%s'
and domain = '%s'
and subscriber = '%s'
and name = '%s'
and destination = '%s'
and startDate = '%s'
and endDate = '%s'",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($profile),
addslashes($destination),
addslashes($startDate),
addslashes($endDate)
);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$deleted++;
}
} else if ($ops=="2") {
$query=sprintf("select * from billing_rates_history
where name = '%s'
and destination = '%s'
and gateway = '%s'
and domain = '%s'
and subscriber = '%s'
and startDate = '%s'
and endDate = '%s'
",
addslashes($profile),
addslashes($destination),
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($startDate),
addslashes($endDate)
);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->num_rows()) {
$query=sprintf("update billing_rates_history set
durationRate = '%s',
trafficRate = '%s',
application = '%s',
connectCost = '%s'
where name = '%s'
and destination = '%s'
and gateway = '%s'
and domain = '%s'
and subscriber = '%s'
and startDate = '%s'
and endDate = '%s'
",
addslashes($durationRate),
addslashes($trafficRate),
addslashes($application),
addslashes($connectCost),
addslashes($profile),
addslashes($destination),
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($startDate),
addslashes($endDate)
);
dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$updated++;
}
} else {
$query=sprintf("insert into billing_rates_history
(
gateway,
domain,
subscriber,
name,
destination,
durationRate,
trafficRate,
application,
connectCost,
startDate,
endDate
) values (
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($profile),
addslashes($destination),
addslashes($durationRate),
addslashes($trafficRate),
addslashes($application),
addslashes($connectCost),
addslashes($startDate),
addslashes($endDate)
);
dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$inserted++;
} else {
$failed++;
}
}
}
$j++;
if ($j=="10000") {
dprint("Loaded another $j rates history");
flush();
$j=0;
}
$i++;
}
if ($i) print "Read $i records\n";
if ($inserted) print "Inserted $inserted records\n";
if ($updated) print "Updated $updated records\n";
if ($deleted) print "Delete $deleted records\n";
$results=$inserted+$updated+$deleted;
return $results;
}
function ImportCustomers($file) {
dprint("ImportCustomers($file)");
if (!$file || !is_readable($file) || !$fp = fopen($file, "r")) return 0;
$i=0;
$inserted = 0;
$updated = 0;
$deleted = 0;
print "Importing Customers:\n";
while ($buffer = fgets($fp,1024)) {
$buffer=trim($buffer);
$p = explode(",", $buffer);
$ops = trim($p[0]);
$gateway = trim($p[1]);
$domain = trim($p[2]);
$subscriber = trim($p[3]);
$profile_name1 = trim($p[4]);
$profile_name1_alt = trim($p[5]);
$profile_name2 = trim($p[6]);
$profile_name2_alt = trim($p[7]);
$timezone = trim($p[8]);
$increment = trim($p[9]);
$min_duration = trim($p[10]);
$country_code = trim($p[11]);
if ($ops=="1") {
$query=sprintf("insert into billing_customers
(
gateway,
domain,
subscriber,
profile_name1,
profile_name2,
timezone,
profile_name1_alt,
profile_name2_alt,
increment,
min_duration,
country_code
) values (
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($profile_name1),
addslashes($profile_name2),
addslashes($timezone),
addslashes($profile_name1_alt),
addslashes($profile_name2_alt),
addslashes($increment),
addslashes($min_duration),
addslashes($country_code)
);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$inserted++;
} else {
$failed++;
}
} else if ($ops=="3") {
$query=sprintf("delete from billing_customers
where gateway = '%s'
and domain = '%s'
and subscriber = '%s'
",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber)
);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$deleted++;
}
} else if ($ops=="2") {
$query=sprintf("select * from billing_customers
where gateway = '%s'
and domain = '%s'
and subscriber = '%s'
",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber)
);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->num_rows()) {
$query=sprintf("update billing_customers set
profile_name1 = '%s',
profile_name2 = '%s',
profile_name1_alt = '%s',
profile_name2_alt = '%s',
timezone = '%s',
increment = '%s',
min_duration = '%s',
country_code = '%s'
where gateway = '%s'
and domain = '%s'
and subscriber = '%s'\n",
addslashes($profile_name1),
addslashes($profile_name2),
addslashes($profile_name1_alt),
addslashes($profile_name2_alt),
addslashes($timezone),
addslashes($increment),
addslashes($min_duration),
addslashes($country_code),
addslashes($gateway),
addslashes($domain),
addslashes($subscriber)
);
dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows()) {
$updated++;
}
} else {
$query=sprintf("insert into billing_customers
(
gateway,
domain,
subscriber,
profile_name1,
profile_name2,
timezone,
profile_name1_alt,
profile_name2_alt,
increment,
min_duration,
country_code
) values (
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($profile_name1),
addslashes($profile_name2),
addslashes($timezone),
addslashes($profile_name1_alt),
addslashes($profile_name2_alt),
addslashes($increment),
addslashes($min_duration),
addslashes($country_code)
);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows()) {
$inserted++;
}
}
}
$i++;
}
if ($i) print "Read $i records\n";
if ($inserted) print "Inserted $inserted records\n";
if ($updated) print "Updated $updated records\n";
if ($deleted) print "Delete $deleted records\n";
$results=$inserted+$updated+$deleted;
return $results;
}
function ImportDestinations($file) {
dprint("ImportDestinations($file)");
if (!$file || !is_readable($file) || !$fp = fopen($file, "r")) return 0;
$i=0;
$inserted = 0;
$updated = 0;
$deleted = 0;
print "Importing Destinations:\n";
while ($buffer = fgets($fp,1024)) {
$buffer=trim($buffer);
$p = explode(",", $buffer);
$ops = trim($p[0]);
$gateway = trim($p[1]);
$domain = trim($p[2]);
$subscriber = trim($p[3]);
$dest_id = trim($p[4]);
$dest_name = trim($p[5]);
if ($ops=="1") {
$query=sprintf("insert into destinations
(
gateway,
domain,
subscriber,
dest_id,
dest_name
) values (
'%s',
'%s',
'%s',
'%s',
'%s'
)",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($dest_id),
addslashes($dest_name)
);
dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$inserted++;
} else {
$failed++;
}
} elseif ($ops=="3") {
$query=sprintf("delete from destinations
where gateway = '%s'
and domain = '%s'
and subscriber = '%s'
and dest_id = '%s'
",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($dest_id)
);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$deleted++;
}
} elseif ($ops=="2") {
$query=sprintf("select * from destinations
where gateway = '%s'
and domain = '%s'
and subscriber = '%s'
and dest_id = '%s'
",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($dest_id)
);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->num_rows()) {
$query=sprintf("update destinations set
dest_name = '%s'
where gateway = '%s'
and domain = '%s'
and subscriber = '%s'
and dest_id = '%s'
",
addslashes($dest_name),
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($dest_id)
);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows()) {
$updated++;
}
} else {
$query=sprintf("insert into destinations
(
gateway,
domain,
subscriber,
dest_id,
dest_name
) values (
'%s',
'%s',
'%s',
'%s',
'%s'
)",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($dest_id),
addslashes($dest_name)
);
dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$inserted++;
} else {
$failed++;
}
}
}
$i++;
}
if ($i) print "Read $i records\n";
if ($inserted) print "Inserted $inserted records\n";
if ($updated) print "Updated $updated records\n";
if ($deleted) print "Delete $deleted records\n";
$results=$inserted+$updated+$deleted;
return $results;
}
function ImportProfiles($file) {
dprint("ImportProfiles($file)");
if (!$file || !is_readable($file) || !$fp = fopen($file, "r")) return 0;
$i=0;
$inserted = 0;
$updated = 0;
$deleted = 0;
print "Importing Profiles:\n";
while ($buffer = fgets($fp,1024)) {
$buffer=trim($buffer);
$p = explode(",", $buffer);
$ops = trim($p[0]);
$gateway = trim($p[1]);
$domain = trim($p[2]);
$subscriber = trim($p[3]);
$profile = trim($p[4]);
$rate1 = trim($p[5]);
$hour1 = trim($p[6]);
$rate2 = trim($p[7]);
$hour2 = trim($p[8]);
$rate3 = trim($p[9]);
$hour3 = trim($p[10]);
$rate4 = trim($p[11]);
$hour4 = trim($p[12]);
if (!$hour1) $hour1=0;
if (!$hour2) $hour2=0;
if (!$hour3) $hour3=0;
if (!$hour4) $hour4=0;
if ($ops=="1") {
$query=sprintf("insert into billing_profiles
(
gateway,
domain,
subscriber,
name,
rate_name1,
hour1,
rate_name2,
hour2,
rate_name3,
hour3,
rate_name4,
hour4
) values (
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($profile),
addslashes($rate1),
addslashes($hour1),
addslashes($rate2),
addslashes($hour2),
addslashes($rate3),
addslashes($hour3),
addslashes($rate4),
addslashes($hour4)
);
dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$inserted++;
} else {
$failed++;
}
} else if ($ops=="3") {
$query=sprintf("delete from billing_profiles
where name = '%s'
and gateway = '%s'
and domain = '%s'
and subscriber = '%s'
",
addslashes($profile),
addslashes($gateway),
addslashes($domain),
addslashes($subscriber)
);
dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$deleted++;
}
} else if ($ops=="2") {
$query=sprintf("select * from billing_profiles
where name = '%s'
and gateway = '%s'
and domain = '%s'
and subscriber = '%s'\n",
addslashes($profile),
addslashes($gateway),
addslashes($domain),
addslashes($subscriber)
);
dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->num_rows()) {
$query=sprintf("update billing_profiles set
rate_name1 = '%s',
rate_name2 = '%s',
rate_name3 = '%s',
rate_name4 = '%s',
hour1 = '%s',
hour2 = '%s',
hour3 = '%s',
hour4 = '%s'
where name = '%s'
and gateway = '%s'
and domain = '%s'
and subscriber = '%s'\n",
addslashes($rate1),
addslashes($rate2),
addslashes($rate3),
addslashes($rate4),
addslashes($hour1),
addslashes($hour2),
addslashes($hour3),
addslashes($hour4),
addslashes($profile),
addslashes($gateway),
addslashes($domain),
addslashes($subscriber)
);
dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows()) {
$updated++;
}
} else {
$query=sprintf("insert into billing_profiles
(
gateway,
domain,
subscriber,
name,
rate_name1,
hour1,
rate_name2,
hour2,
rate_name3,
hour3,
rate_name4,
hour4
) values (
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
'%s'
)",
addslashes($gateway),
addslashes($domain),
addslashes($subscriber),
addslashes($profile),
addslashes($rate1),
addslashes($hour1),
addslashes($rate2),
addslashes($hour2),
addslashes($rate3),
addslashes($hour3),
addslashes($rate4),
addslashes($hour4)
);
dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($this->cdrtool->affected_rows() >0) {
$inserted++;
} else {
$failed++;
}
}
}
$i++;
}
if ($i) print "Read $i records\n";
if ($inserted) print "Inserted $inserted records\n";
if ($updated) print "Updated $updated records\n";
if ($deleted) print "Delete $deleted records\n";
$results=$inserted+$updated+$deleted;
return $results;
}
function LoadRatingTables () {
$loaded=array();
$loaded['customers'] = $this->LoadCustomersTable();
$loaded['profiles'] = $this->LoadProfilesTable();
$loaded['rates'] = $this->LoadRatesTable();
$loaded['ratesHistory'] = $this->LoadRatesHistoryTable();
$loaded['holidays'] = $this->LoadHolidaysTable();
foreach(array_keys($loaded) as $_load) {
syslog(LOG_NOTICE, "Loaded $loaded[$_load] $_load");
}
$log=sprintf("Memory usage: %0.2f MB",memory_get_usage()/1024/1024);
syslog(LOG_NOTICE, $log);
return $loaded;
}
function LoadCustomersTable($customerFilter='') {
$query="select * from billing_customers";
if (is_array($customerFilter)) {
if (strlen(trim($customerFilter['customer'])) &&
(
$customerFilter['type'] == "subscriber" ||
$customerFilter['type'] == "domain" ||
$customerFilter['type'] == "gateway"
)) {
$query.=sprintf (" where %s = '%s'",
$customerFilter['type'],
trim($customerFilter['customer']));
$updateCustomer=true;
}
}
dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
if ($updateCustomer && !$this->cdrtool->num_rows()) {
$log=sprintf("Customer %s of type %s not found ",$customerFilter['customer'],$customerFilter['type']);
syslog(LOG_NOTICE, $log);
return 0;
}
$i=0;
while($this->cdrtool->next_record()) {
$subscriber = $this->cdrtool->Record['subscriber'];
$domain = $this->cdrtool->Record['domain'];
$gateway = $this->cdrtool->Record['gateway'];
$profile1 = $this->cdrtool->Record['profile_name1'];
$profile1_alt = $this->cdrtool->Record['profile_name1_alt'];
$profile2 = $this->cdrtool->Record['profile_name2'];
$profile2_alt = $this->cdrtool->Record['profile_name2_alt'];
$timezone = $this->cdrtool->Record['timezone'];
$increment = $this->cdrtool->Record['increment'];
$min_duration = $this->cdrtool->Record['min_duration'];
$country_code = $this->cdrtool->Record['country_code'];
if ($profile1 || $profile2) {
$i++;
if ($subscriber) {
$_els=explode(" ",trim($subscriber));
foreach ($_els as $_el) {
$_el=trim($_el);
$_customers[$_el]=
array (
"profile1" => $profile1,
"profile2" => $profile2,
"profile1_alt" => $profile1_alt,
"profile2_alt" => $profile2_alt,
"timezone" => $timezone,
"increment" => $increment,
"min_duration" => $min_duration,
"country_code" => $country_code
);
}
continue;
}
if ($domain) {
$_els=explode(" ",trim($domain));
foreach ($_els as $_el) {
$_el=trim($_el);
$_customers[$_el]=
array (
"profile1" => $profile1,
"profile2" => $profile2,
"profile1_alt" => $profile1_alt,
"profile2_alt" => $profile2_alt,
"timezone" => $timezone,
"increment" => $increment,
"min_duration" => $min_duration,
"country_code" => $country_code
);
}
continue;
}
if ($gateway) {
$_els=explode(" ",trim($gateway));
foreach ($_els as $_el) {
$_el=trim($_el);
$_customers[$_el]=
array (
"profile1" => $profile1,
"profile2" => $profile2,
"profile1_alt" => $profile1_alt,
"profile2_alt" => $profile2_alt,
"timezone" => $timezone,
"increment" => $increment,
"min_duration" => $min_duration,
"country_code" => $country_code
);
}
continue;
}
$_customers['default']=
array (
"profile1" => $profile1,
"profile2" => $profile2,
"profile1_alt" => $profile1_alt,
"profile2_alt" => $profile2_alt,
"timezone" => $timezone,
"increment" => $increment,
"min_duration" => $min_duration,
"country_code" => $country_code
);
}
}
if ($updateCustomer) {
if ($this->customers[$customerFilter['customer']]) {
// update customer
$this->customers[$customerFilter['customer']]=$_customers;
$log=sprintf("Updated customer %s",$customerFilter['customer']);
syslog(LOG_NOTICE, $log);
} else {
// append customer
$this->customers=array_merge($this->customers,$_customers);
$log=sprintf("Added customer %s",$customerFilter['customer']);
syslog(LOG_NOTICE, $log);
}
} else {
// load all customers
$this->customers=$_customers;
}
dprint("Loaded $i customers");
return $i;
}
function LoadRatesTable() {
$query="select * from billing_rates order by destination";
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
$i=0;
$rows=$this->cdrtool->num_rows();
while($this->cdrtool->next_record()) {
if ($this->cdrtool->Record['name'] && $this->cdrtool->Record['destination']) {
$i++;
$_app=$this->cdrtool->Record['application'];
if (!strlen($_app)) $_app='audio';
$_rates[$this->cdrtool->Record['name']][$this->cdrtool->Record['destination']][$_app]=
array(
"durationRate" => $this->cdrtool->Record['durationRate'],
"trafficRate" => $this->cdrtool->Record['trafficRate'],
"connectCost" => $this->cdrtool->Record['connectCost']
);
}
}
$this->rates=$_rates;
$this->ratesCount=$i;
dprint("Loaded $i rates");
return $i;
}
function LoadRatesHistoryTable() {
$query="select *,
UNIX_TIMESTAMP(startDate) as startDateTimestamp,
UNIX_TIMESTAMP(endDate) as endDateTimestamp
from billing_rates_history
order by name ASC,destination ASC,startDate DESC";
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
$i=0;
$rows=$this->cdrtool->num_rows();
while($this->cdrtool->next_record()) {
if ($this->cdrtool->Record['name'] && $this->cdrtool->Record['destination']) {
$i++;
$_app=$this->cdrtool->Record['application'];
if (!strlen($_app)) $_app='audio';
$_rates[$this->cdrtool->Record['name']][$this->cdrtool->Record['destination']][$_app][$this->cdrtool->Record['id']]=
array(
"durationRate" => $this->cdrtool->Record['durationRate'],
"trafficRate" => $this->cdrtool->Record['trafficRate'],
"connectCost" => $this->cdrtool->Record['connectCost'],
"startDate" => $this->cdrtool->Record['startDateTimestamp'],
"endDate" => $this->cdrtool->Record['endDateTimestamp']
);
}
}
$this->ratesHistory=$_rates;
$this->ratesHistoryCount=$i;
dprint("Loaded $i rates history");
//dprint_r($this->ratesHistory);
return $i;
}
function LoadProfilesTable() {
$query="select * from billing_profiles order by name";
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
$i=0;
while($this->cdrtool->next_record()) {
$i++;
if ($this->cdrtool->Record['name'] && $this->cdrtool->Record['hour1'] > 0 ) {
$_profiles[$this->cdrtool->Record['name']]=
array(
"rate_name1" => $this->cdrtool->Record['rate_name1'],
"hour1" => $this->cdrtool->Record['hour1'],
"rate_name2" => $this->cdrtool->Record['rate_name2'],
"hour2" => $this->cdrtool->Record['hour2'],
"rate_name3" => $this->cdrtool->Record['rate_name3'],
"hour3" => $this->cdrtool->Record['hour3'],
"rate_name4" => $this->cdrtool->Record['rate_name4'],
"hour4" => $this->cdrtool->Record['hour4'],
);
}
}
$this->profiles=$_profiles;
dprint("Loaded $i profiles");
return $i;
}
function LoadHolidaysTable() {
$query="select * from billing_holidays order by day";
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
$i=0;
while($this->cdrtool->next_record()) {
if ($this->cdrtool->Record['day']) {
$i++;
$_holidays[$this->cdrtool->Record['day']]++;
}
}
$this->holidays=$_holidays;
dprint("Loaded $i holidays");
return $i;
}
function checkRatingEngineConnection () {
global $RatingEngine;
if ($RatingEngine["socketIP"] && $RatingEngine["socketPort"] &&
$fp = fsockopen ($RatingEngine["socketIP"], $RatingEngine["socketPort"], $errno, $errstr, 2)) {
fclose($fp);
return 1;
}
return 0;
}
function showCustomers($filter) {
foreach (array_keys($this->customers) as $key) {
if (strlen($filter)) {
if (preg_match("/$filter/",$key)) {
$customers=$customers.$key."\n";
}
} else {
$customers=$customers.$key."\n";
}
}
return $customers;
}
function showProfiles() {
foreach (array_keys($this->profiles) as $key) {
$profiles=$profiles.$key."\n";
}
return $profiles;
}
function showRates() {
foreach (array_keys($this->rates) as $key) {
$rates=$rates.$key."\n";
}
return $rates;
}
function scanFilesForImport($dir) {
if (!$dir) $dir=$this->CDRTool["Path"]."/csv";
if ($handle = opendir($dir)) {
while (false !== ($filename = readdir($handle))) {
if ($filename != "." && $filename != "..") {
foreach ($this->importFilesPatterns as $_pattern) {
if (strstr($filename,$_pattern) && preg_match("/\.csv$/",$filename)) {
//if (!in_array($filename,$files)) {
$fullPath=$dir."/".$filename;
if ($content=file_get_contents($fullPath)) {
$watermark=$filename."-".md5($content);
if ($this->hasFileBeenImported($filename,$watermark)) break;
$this->filesToImport[]=array( 'name' => $filename,
'watermark' => $watermark,
'type' => $_pattern,
'path' => $fullPath
);
}
//}
break;
}
}
}
}
}
}
function hasFileBeenImported($filename,$watermark) {
$query=sprintf("select * from log where url = '%s'\n",$watermark);
dprint($query);
if ($this->cdrtool->query($query)) {
if ($this->cdrtool->num_rows()) {
$this->cdrtool->next_record();
$log=sprintf ("File %s has already been imported at %s.\n",$filename,$this->cdrtool->f('date'));
syslog(LOG_NOTICE, $log);
print $log;
return 1;
} else {
return 0;
}
} else {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return 0;
}
}
function logImport($dir,$filename,$watermark,$results=0) {
$query=sprintf("insert into log (date,login,ip,url,results,description,datasource)
values (NOW(),'ImportScript','localhost','%s','%s','Imported %s','%s')",
$watermark,$results,$filename,$dir
);
dprint($query);
if (!$this->cdrtool->query($query)) {
printf ("Database error: %s (%s)",$this->cdrtool->Error,$this->cdrtool->Errno);
return false;
}
}
}
class SERQuota {
var $localDomains = array();
var $quotaGroup = 'quota'; // group set if subscriber was blocked by quota
function SERQuota(&$parent) {
global $DATASOURCES;
$this->AccountsDBClass = &$parent->AccountsDBClass;
$this->CDRdb = &$parent->CDRdb;
$this->table = &$parent->table;
$this->CDRTool = &$parent->CDRTool;
$this->cdr_source = &$parent->cdr_source;
if (!class_exists($this->AccountsDBClass)) {
print("Info: No database defined for SIP accounts $this->cdr_source.\n");
return 0;
}
$this->AccountsDB = new $this->AccountsDBClass;
$this->enableThor = $parent->enableThor;
$parent->LoadDomains();
$this->localDomains = &$parent->localDomains;
$this->cdr_source = &$parent->cdr_source;
$this->BillingPartyIdField = &$parent->CDRFields['BillingPartyId'];
$this->parent = &$parent;
$this->db = new DB_cdrtool;
$this->db->Halt_On_Error="no";
$this->CDRS = &$parent;
$this->mc_key_accounts = $this->cdr_source.':accounts';
$this->mc_key_init = $this->cdr_source.':quotaCheckInit';
// load e-mail addresses for quota notifications
$query="select * from settings
where var_module = 'notifications'";
dprint($query);
if ($this->db->query($query) && $this->db->num_rows()) {
while ($this->db->next_record()) {
$_bp =$this->db->f('billing_party');
$_name =$this->db->f('var_name');
$_value =$this->db->f('var_value');
if ($_bp && $_name && $_value) {
$this->notificationAddresses[$_bp][$_name]=$_value;
}
}
}
dprint_r($this->notificationAddresses);
if ($DATASOURCES[$this->cdr_source]['SoapEngineId']) {
- require_once("provisioning_soap_library.phtml");
+ require_once("provisioning/provisioning_soap_library.phtml");
require("soap_engines.inc");
if (in_array($SoapEngineId,array_keys($soapEngines))) {
$this->SOAPurl = $soapEngines[$SoapEngineId]['url'];
$this->SOAPlogin = array(
"username" => $soapEngines[$SoapEngineId]['username'],
"password" => $soapEngines[$SoapEngineId]['password'],
"admin" => $soapEngines[$SoapEngineId]['admin']
);
$this->SoapAuth=array('auth', $this->SOAPlogin , 'urn:AGProjects:NGNPro', 0, '');
$this->soapclient = new WebService_NGNPro_SipPort($this->SOAPurl);
$this->soapclient->setOpt('curl', CURLOPT_SSL_VERIFYPEER, 0);
$this->soapclient->setOpt('curl', CURLOPT_SSL_VERIFYHOST, 0);
$this->soapclient->setOpt('curl', CURLOPT_TIMEOUT, 2);
}
}
$this->initOK=1;
}
function LoadAccounts() {
$b=time();
if (!$this->AccountsDBClass) {
print("Info: No database defined for SIP accounts.\n");
return 0;
}
if (!$this->LoadAccountsfromCache()) {
if ($this->enableThor) {
$query=sprintf("select * from sip_accounts");
dprint($query);
if (!$this->AccountsDB->query($query)) {
$log=sprintf("Error: %s (%s)",$this->AccountsDB->Error,$this->AccountsDB->Errno);
syslog(LOG_NOTICE,$log);
return 0;
}
$log=sprintf("Read %d accounts from Thor database\n",$this->AccountsDB->num_rows());
print $log;
syslog(LOG_NOTICE,$log);
while ($this->AccountsDB->next_record()) {
$i++;
$_account=$this->AccountsDB->f('username')."@".$this->AccountsDB->f('domain');
$_profile=json_decode(trim($this->AccountsDB->f('profile')));
$_accounts[$_account]=array('timezone' => $_profile->timezone,
'quota' => $_profile->quota,
'email' => $_profile->email,
'first_name' => $_profile->firstName,
'last_name' => $_profile->lastName
);
if (in_array('quota',$_profile->groups)) {
$_accounts[$account]['block_by_quota']= 1;
}
}
} else {
$query=sprintf("select * from subscriber");
dprint($query);
if (!$this->AccountsDB->query($query)) {
$log=sprintf("Error: %s (%s)",$this->AccountsDB->Error,$this->AccountsDB->Errno);
syslog(LOG_NOTICE,$log);
return 0;
}
$log=sprintf("Read %d accounts from SER database\n",$this->AccountsDB->num_rows());
print $log;
syslog(LOG_NOTICE,$log);
while ($this->AccountsDB->next_record()) {
if (strlen($this->AccountsDB->f('domain'))) {
$_account = $this->AccountsDB->f('username')."@".$this->AccountsDB->f('domain');
} else {
$_account = $this->AccountsDB->f('username');
}
$_accounts[$_account]=array('timezone' => $this->AccountsDB->f('timezone'),
'quota' => $this->AccountsDB->f('quota'),
'email' => $this->AccountsDB->f('email_address'),
'first_name' => $this->AccountsDB->f('first_name'),
'last_name' => $this->AccountsDB->f('last_name')
);
}
$query = sprintf("select * from grp where grp = '%s'",$this->quotaGroup);
dprint($query);
if (!$this->AccountsDB->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->AccountsDB->Error,$this->AccountsDB->Errno);
print $log;
syslog(LOG_NOTICE,$log);
return false;
}
while($this->AccountsDB->next_record()) {
$account=$this->AccountsDB->f('username')."@".$this->AccountsDB->f('domain');
$_accounts[$account]['block_by_quota']= 1;
}
}
$this->Accounts = &$_accounts;
$this->SaveAccountsToCache();
}
$count=count($this->Accounts);
$e=time();
$d=$e-$b;
if ($d >0 ) syslog(LOG_NOTICE, "Loaded $count SIP accounts in $d seconds");
return $count;
}
function SaveAccountsToCache() {
$b=time();
unset($mc_value);
foreach (array_keys($this->Accounts) as $account) {
if (!strlen($account)) continue;
$mc_value.= sprintf("%s:quota=%s;email=%s;fn=%s%s;block_by_quota=%d\n",
$account,
$this->Accounts[$account]['quota'],
$this->Accounts[$account]['email'],
$this->Accounts[$account]['first_name'],
$this->Accounts[$account]['last_name'],
$this->Accounts[$account]['block_by_quota']
);
}
if (is_object($this->CDRS->mc)) {
$this->CDRS->mc->set($this->mc_key_accounts,$mc_value,MEMCACHE_COMPRESSED,3600);
$log=sprintf("Saved compressed %d accounts in memcache key %s (%.02f MB)\n",count($this->Accounts),$this->mc_key_accounts,strlen($mc_value)/1024/1024);
print $log;
syslog(LOG_NOTICE,$log);
$mc_stats=$this->CDRS->mc->getStats();
$mc_usage=$mc_stats['bytes']/$mc_stats['limit_maxbytes']*100;
$log=sprintf ("Memcache usage %.0f%s\n",$mc_usage,"%");
print $log;
syslog(LOG_NOTICE,$log);
}
$e=time();
$d=$e-$b;
if ($d >0 ) syslog(LOG_NOTICE, "Saved SIP accounts to memcache in $d seconds");
}
function LoadAccountsfromCache() {
if ($this->CDRS->mc && $mc_value = $this->CDRS->mc->get($this->mc_key_accounts)) {
$_accounts_tmp=explode("\n",$mc_value);
foreach ($_accounts_tmp as $_account_tmp) {
$_avps=explode(":",$_account_tmp);
$_properties = explode(";",$_avps[1]);
foreach ($_properties as $_property) {
$_els=explode("=",$_property);
$_accounts[$_avps[0]][$_els[0]]=$_els[1];
}
}
$log=sprintf("Load %d accounts from memcache key %s (%.02f MB)\n",count($_accounts),$this->mc_key_accounts,strlen($mc_value)/1024/1024);
//print $log;
syslog(LOG_NOTICE,$log);
$this->Accounts = &$_accounts;
return true;
}
return false;
}
function ShowAccountsWithQuota($treshhold='') {
if (!$this->LoadAccounts()) return 0;
foreach (array_keys($this->Accounts) as $_subscriber) {
if ($this->Accounts[$_subscriber]['quota'] ) {
$usage = $this->CDRS->getMonthlyUsageFromCache($_subscriber);
if ($usage['cost'] > 0) {
if ($this->Accounts[$_subscriber]['block_by_quota']) {
$blockedStatus="blocked";
} else {
$blockedStatus='';;
}
$usageRatio=$usage['cost']*100/$this->Accounts[$_subscriber]['quota'];
if ($treshhold && $treshhold > $usageRatio) continue;
$usageStatus=sprintf("usage=%-10s",$usage['cost']);
printf ("%-35s quota=%-6s %s %.2f%s %s\n",$_subscriber,$this->Accounts[$_subscriber]['quota'],$usageStatus,$usageRatio,'%',$blockedStatus);
}
}
}
}
function Reset() {
if (!$this->AccountsDBClass) {
print("Info: No database defined for SIP accounts.\n");
return 0;
}
if ($this->enableThor) {
$query=sprintf("select * from sip_accounts");
dprint($query);
if (!$this->AccountsDB->query($query)) {
$log=sprintf("Error: %s (%s)",$this->AccountsDB->Error,$this->AccountsDB->Errno);
syslog(LOG_NOTICE,$log);
return 0;
}
while ($this->AccountsDB->next_record()) {
$i++;
$_account=$this->AccountsDB->f('username')."@".$this->AccountsDB->f('domain');
$_profile=json_decode(trim($this->AccountsDB->f('profile')));
if (in_array('quota',$_profile->groups)) {
$blockedAccounts[]=$this->AccountsDB->f('account');
}
}
} else {
$query=sprintf("select CONCAT(username,'@',domain) as account from grp where grp = '%s'",$this->quotaGroup);
if (!$this->AccountsDB->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->AccountsDB->Error,$this->AccountsDB->Errno);
print $log;
syslog(LOG_NOTICE,$log);
return false;
}
while ($this->AccountsDB->next_record()) {
$blockedAccounts[]=$this->AccountsDB->f('account');
}
}
if (count($blockedAccounts) >0 ) {
$this->unBlockRemoteAccounts($blockedAccounts);
if (!$this->enableThor) {
$query=sprintf("delete from grp where grp = '%s'",$this->quotaGroup);
dprint($query);
if (!$this->AccountsDB->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->AccountsDB->Error,$this->AccountsDB->Errno);
print $log;
syslog(LOG_NOTICE,$log);
return false;
}
}
}
if (count($blockedAccounts)) {
$log=sprintf ("Reset %d users blocked by quota\n",count($blockedAccounts));
print $log;
syslog(LOG_NOTICE, $log);
}
}
function getMonthlyUsageFromDatabaseCache() {
$query=sprintf("select * from memcache where `key` like '%s%s'",
$this->CDRS->mc_key_mu_prefix,"%");
dprint($query);
if (!$this->db->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->db->Error,$this->db->Errno);
print $log;
syslog(LOG_NOTICE,$log);
return false;
}
while($this->db->next_record()) {
$account = substr($this->db->f('key'),strlen($this->CDRS->mc_key_mu_prefix));
$_usage = $this->CDRS->parseMonthlyUsage($this->db->f('value'));
$this->Accounts[$account]['usage']=$_usage;
}
}
function initMonthlyUsageFromDatabase($month="") {
if (!$month) {
$this->startTime=Date("Y-m-01 00:00",time());
} else {
$this->startTime=$month."-01 00:00";
}
$this->LoadAccounts();
$j=0;
$query=sprintf("select %s,
count(*) as calls,
sum(AcctSessionTime) as duration,
sum(Price) as cost,
sum(AcctInputOctets + AcctOutputOctets)/2 as traffic
from %s
where AcctStartTime >= '%s'
and Normalized = '1'
group by %s\n",
addslashes($this->BillingPartyIdField),
addslashes($this->table),
addslashes($this->startTime),
addslashes($this->BillingPartyIdField)
);
dprint($query);
if (!$this->CDRdb->query($query)) {
if ($this->CDRdb->Errno != 1146) {
$log=sprintf ("Database error: %s (%s)",$this->CDRdb->Error,$this->CDRdb->Errno);
print $log;
syslog(LOG_NOTICE,$log);
return false;
}
}
$rows=$this->CDRdb->num_rows();
$log=sprintf ("%d callers generated traffic in %s\n",$rows,Date("Y-m",time()));
print $log;
syslog(LOG_NOTICE, $log);
$j=0;
while($this->CDRdb->next_record()) {
if (!$this->Accounts[$this->CDRdb->f($this->BillingPartyIdField)]) continue;
$this->Accounts[$this->CDRdb->f($this->BillingPartyIdField)]['usage']['calls'] = $this->CDRdb->f('calls');
$this->Accounts[$this->CDRdb->f($this->BillingPartyIdField)]['usage']['duration'] = $this->CDRdb->f('duration');
$this->Accounts[$this->CDRdb->f($this->BillingPartyIdField)]['usage']['cost'] = $this->CDRdb->f('cost');
$this->Accounts[$this->CDRdb->f($this->BillingPartyIdField)]['usage']['traffic'] = $this->CDRdb->f('traffic');
$j++;
}
}
function initMonthlyUsageFromCache () {
dprint("initMonthlyUsageFromCache");
if (!$this->AccountsDBClass) {
print("Info: No database defined for SIP accounts.\n");
return 0;
}
$this->cachedUsage=array();
if (is_object($this->CDRS->mc)) {
if ($this->enableThor) {
$query="select * from sip_accounts";
} else {
$query="select * from subscriber";
}
dprint($query);
if (!$this->AccountsDB->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->AccountsDB->Error,$this->AccountsDB->Errno);
print $log;
syslog(LOG_NOTICE,$log);
return false;
}
while($this->AccountsDB->next_record()) {
$_account=$this->AccountsDB->f('username')."@".$this->AccountsDB->f('domain');;
$this->cachedUsage[$_account]['usage'] = $this->CDRS->getMonthlyUsageFromCache($_account);
}
}
return 1;
}
function checkQuota($notify) {
dprint("checkQuota($notify)");
global $UserQuota;
if (!$this->initOK) return ;
$this->cacheMonthlyUsage();
$this->LoadAccounts();
$toNotify=array();
if (!is_object($this->CDRS->mc)) {
$this->getMonthlyUsageFromDatabaseCache();
}
$_checks=0;
foreach (array_keys($this->Accounts) as $account) {
if (!$account['quota']) continue;
list($username,$domain)=explode("@",$account);
if (is_object($this->CDRS->mc)) $this->Accounts[$account]['usage']=$this->CDRS->getMonthlyUsageFromCache($account);
if ($reason=$this->checkLimit($account,$this->Accounts[$account]['usage'])) {
$exceeding_accounts++;
if (!$this->Accounts[$account]['block_by_quota']) {
if (!$seen_title) {
$line=sprintf ("%40s %6s %8s %8s %13s %s\n","User","Calls","Price","Minutes","Traffic","Reason");
print $line;
$email_body=$line;
$seen_title++;
}
$traffic = number_format($this->Accounts[$account]['usage']['traffic']/1024/1024,2);
$duration = number_format($this->Accounts[$account]['usage']['duration']/60,0,"","");
$line = sprintf ("%40s %6s %8s %8s %10s MB %s\n",$account,$this->Accounts[$account]['usage']['calls'],$this->Accounts[$account]['usage']['cost'],$duration,$traffic,$reason);
$email_body = $email_body.$line;
print $line;
$log=sprintf("Quota exceeded for %s: %s",$account, $reason);
syslog(LOG_NOTICE, $log);
$log_query=sprintf("insert into log
(date,login,ip,datasource,results,description)
values (NOW(),'quotacheck','localhost','QuotaCheck','1','%s')",
addslashes($log)
);
dprint($log_query);
if (!$this->db->query($log_query)) {
$log=sprintf ("Database error: %s (%s)",$this->db->Error,$this->db->Errno);
print $log;
syslog(LOG_NOTICE,$log);
}
if ($this->blockAccount($account)) {
if ($notify && $this->Accounts[$account]['email']) {
$toNotify[]=$account;
}
$blocked_now++;
$blockedAccountsNow=$blockedAccountsNow.$account."\n";
}
} else {
$blockedAccountsPrevious=$blockedAccountsPrevious.$account."\n";
$blocked_previous++;
}
}
$_checks++;
}
if ($exceeding_accounts) {
$line=sprintf("%6d accounts have exceeded their traffic limits\n",$exceeding_accounts);
print $line;
$email_body=$email_body.$line;
} else {
$log=sprintf("No quota has been exceeded\n");
syslog(LOG_NOTICE, $log);
}
if ($blocked_now) {
$line=sprintf("%6d accounts have been blocked now\n",$blocked_now);
$email_body=$email_body.$line;
if (is_object($this->CDRS->mc)) $this->CDRS->mc->delete($this->CDRS->mc_key_accounts);
}
if ($blockedAccountsNow) {
$line="Blocked accounts now:\n".$blockedAccountsNow;
print $line;
$email_body=$email_body.$line.$batch_block;
}
if ($blockedAccountsPrevious) {
$line="Blocked acccounts previously:\n".$blockedAccountsPrevious;
print $line;
$email_body=$email_body.$line.$batch_unblock;
}
// send notification to the provider
if ($this->CDRTool[provider][toEmail] && $blockedAccountsNow) {
$from = $this->CDRTool[provider][fromEmail];
$to = $this->CDRTool[provider][toEmail];
$bcc = $this->CDRTool[provider][bccEmail];
$service = $this->CDRTool[provider][service];
if (!$service) $service = "SIP";
if ($from) $extraHeaders="From: $from\r\nBCC: $from";
if ($bcc) $extraHeaders=$extraHeaders.",".$bcc;
print("Notify CDRTool provider at $to\n");
mail($to, "$service platform - CDRTool quota check", $email_body, $extraHeaders);
}
dprint("Notify accounts");
if ($notify && is_array($toNotify) && count($toNotify) >0) {
dprint_r($toNotify);
// send notification to accounts
foreach($toNotify as $rcpt) {
$this->notifyAccount($rcpt);
}
}
}
function checkLimit($account,$usage) {
global $UserQuota;
$maxcost = "";
$maxtraffic = "";
if ($this->Accounts[$account]['quota']) {
$maxcost = $this->Accounts[$account]['quota'];
} elseif ($UserQuota['default']['cost']) {
$maxcost = $UserQuota['default']['cost'];
}
if ($maxcost && ($usage['cost'] > $maxcost)) {
return "Cost $usage[cost] > $maxcost";
}
if ($this->Accounts[$account]['quota_traffic']) {
$maxtraffic = $this->Accounts[$account]['quota_traffic'];
} elseif ($UserQuota['default']['traffic']) {
$maxtraffic = $UserQuota['default']['traffic'];
}
if ($maxtraffic && ($usage['traffic'] > $maxtraffic*1024*1024)) {
$trafficMB=number_format($usage['traffic']/1024/1024,0,".","");
return "Traffic $trafficMB > $maxtraffic MB";
}
return 0;
}
function notifyAccount($account) {
dprint("notifyAccount($account)");
global $DATASOURCES;
list($username,$domain)=explode("@",$account);
if (!$DATASOURCES[$this->cdr_source][UserQuotaNotify]) {
return 0;
}
$providerName=$this->notificationAddresses[$domain]['providerName'];
if (!strlen($providerName)) $providerName="your SIP service provider";
$body=sprintf("Dear __NAME__,\n\n".
"Your SIP account %s has been temporarily blocked\n".
"because your monthly quota has been exceeded.\n\n".
"To unblock your account you may contact %s.\n\n".
"N.B. This is an automatically generated message. Do not reply to it.\n",
$account,
$providerName);
$fromEmail = $this->CDRTool[provider][fromEmail];
$bccEmail = $this->CDRTool[provider][bccEmail];
$seen_bcc[$bccEmail]++;
if (strlen($this->notificationAddresses[$domain]['fromEmail'])) {
$fromEmail=$this->notificationAddresses[$domain]['fromEmail'];
}
if (strlen($this->notificationAddresses[$domain]['quotaBody'])) {
$body=$this->notificationAddresses[$domain]['quotaBody'];
}
if (strlen($this->notificationAddresses[$domain]['quotaSubject'])) {
$subject=$this->notificationAddresses[$domain]['quotaSubject'];
}
$fullname=$this->Accounts[$account]['first_name']." ".$this->Accounts[$account]['last_name'];
$body=preg_replace("/__NAME__/",$fullname,$body);
$body=preg_replace("/__ACCOUNT__/",$account,$body);
if (!strlen($subject)) {
$subject=sprintf("Monthly quota exceeded for SIP account %s",$account);
} else {
$subject=preg_replace("/__ACCOUNT__/",$account,$subject);
}
$toEmail=$this->Accounts[$account]['email'];
if (!$toEmail || !$fromEmail) {
dprint("missing From or Rcpt");
return 0;
}
$seen_bcc[$toEmail]++;
$extraHeaders="From: $fromEmail";
if ($this->notificationAddresses[$domain][bccEmail]) {
if ($bccEmail) $bccEmail.= ",";
$bccEmail.=$this->notificationAddresses[$domain][bccEmail];
}
if ($bccEmail) $extraHeaders = $extraHeaders."\r\nBCC: ".$bccEmail;
mail($toEmail,$subject,$body, $extraHeaders);
$log_msg=sprintf("Monthly quota exceeded for %s. Notified To:%s From:%s\n",$account, $toEmail,$fromEmail);
syslog(LOG_NOTICE, $log_msg);
print $log_msg;
}
function blockAccount($account) {
list($username,$domain)=explode("@",$account);
$this->blockAccountRemote($account);
$query=sprintf("delete from grp
where username = '%s'
and domain = '%s'
and grp = '%s'",
addslashes($username),
addslashes($domain),
addslashes($this->quotaGroup)
);
dprint($query);
if (!$this->AccountsDB->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->AccountsDB->Error,$this->AccountsDB->Errno);
print $log;
syslog(LOG_NOTICE,$log);
return false;
}
$query=sprintf("insert into grp
(username,domain,grp,last_modified)
values
('%s','%s','%s',NOW())",
addslashes($username),
addslashes($domain),
addslashes($this->quotaGroup)
);
dprint($query);
if (!$this->AccountsDB->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->AccountsDB->Error,$this->AccountsDB->Errno);
print $log;
syslog(LOG_NOTICE,$log);
return false;
}
return 1;
}
function blockAccountRemote($account) {
if (!is_object($this->soapclient)) {
return 1;
}
list($username,$domain)=explode("@",$account);
if (!$username || !$domain) return 1;
$this->soapclient->addHeader($this->SoapAuth);
$result = $this->soapclient->addToGroup(array("username" => $username,"domain"=> $domain), "quota");
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault = $result->getFault();
$error_code = $result->getCode();
$log1=sprintf("%s: %s",$error_fault->faultstring,$error_fault->faultcode);
syslog(LOG_NOTICE, "SOAP error: $log1");
if ($error_fault->faultcode == "SOAP-ENV:Client") {
$log2=sprintf ("%s %s\n",$error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
syslog(LOG_NOTICE, "SOAP client error: $log2");
}
if ($error_fault->detail->exception->errorcode!="1030") {
$from = $this->CDRTool[provider][fromEmail];
$to = $this->CDRTool[provider][toEmail];
$extraHeaders = "From: $from";
$email_body = "Remote SOAP request failure when calling blockAccountRemote(): \n\n".$log1." ".$log2;
mail($to, "CDRTool remote SOAP failure", $email_body, $extraHeaders);
}
return 0;
} else {
$log=sprintf ("Block remote account %s at %s",$account,$this->NGNProURL);
syslog(LOG_NOTICE, $log);
return 1;
}
}
function unBlockRemoteAccounts($accounts) {
if (!is_object($this->soapclient)) {
return;
}
foreach ($accounts as $account) {
list($username,$domain)=explode("@",$account);
if (!$username || !$domain) return 1;
$this->soapclient->addHeader($this->SoapAuth);
$result = $this->soapclient->removeFromGroup(array("username" => $username,"domain"=> $domain), "quota");
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault = $result->getFault();
$error_code = $result->getCode();
if ($error_fault->detail->exception->errorcode &&
$error_fault->detail->exception->errorcode != "1030" &&
$error_fault->detail->exception->errorcode != "1031"
) {
$from = $this->CDRTool[provider][fromEmail];
$to = $this->CDRTool[provider][toEmail];
$extraHeaders="From: $from";
$email_body="SOAP request failure: \n\n".
$log=sprintf ("SOAP client error: %s %s\n",$error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
syslog(LOG_NOTICE, $log);
mail($to, "CDRTool SOAP failure", $email_body, $extraHeaders);
}
} else {
$log=sprintf ("Unblock remote account %s at %s",$account,$this->NGNProURL);
syslog(LOG_NOTICE, $log);
}
}
}
function saveQuotaInitFlag() {
if (is_object($this->CDRS->mc)) {
if ($this->CDRS->mc->set($this->mc_key_init,'1',0,0)) {
return 1;
} else {
return 0;
}
} else {
$query=sprintf("delete from memcache where `key`= '%s'",$this->mc_key_init);
dprint($query);
if (!$this->db->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->db->Error,$this->db->Errno);
print $log;
syslog(LOG_NOTICE,$log);
return false;
}
$query=sprintf("insert into memcache (`key`,`value`) values ('%s','1')",$this->mc_key_init);
dprint($query);
if ($this->db->query($query) && $this->db->affected_rows()) {
return 1;
} else {
return 0;
}
}
}
function deleteQuotaInitFlag() {
if (is_object($this->CDRS->mc)) {
if (!$this->CDRS->mc->delete($this->mc_key_init)) {
return 0;
}
}
$query=sprintf("delete from memcache where `key`= '%s'",$this->mc_key_init);
dprint($query);
if (!$this->db->query($query)) return 0;
return 1;
}
function cacheMonthlyUsage() {
if (is_object($this->CDRS->mc)) {
if (!$this->CDRS->mc->get($this->mc_key_init)) {
$this->Reset();
$this->deleteMonthlyUsageFromCache();
$this->initMonthlyUsageFromDatabase();
$this->CDRS->cacheMonthlyUsage(&$this->Accounts);
if ($this->CDRS->status['cached_keys']['saved_keys']) {
$log=sprintf("Saved %d usage keys in cache\n",$this->CDRS->status['cached_keys']['saved_keys']);
print $log;
syslog(LOG_NOTICE, $log);
}
if ($this->CDRS->status['cached_keys']['failed_keys']) {
$log=sprintf("Error: failed to save %d usage keys\n",$this->CDRS->status['cached_keys']['failed_keys']);
print $log;
syslog(LOG_NOTICE, $log);
}
if ($this->saveQuotaInitFlag()) {
return 1;
} else {
$log=sprintf ("Error: failed to save key quotaCheckInit in memcache");
syslog(LOG_NOTICE, $log);
return 0;
}
}
} else {
$query=sprintf("select * from memcache where `key` = '%s'",$this->mc_key_init);
dprint($query);
if (!$this->db->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->db->Error,$this->db->Errno);
print $log;
syslog(LOG_NOTICE,$log);
return false;
}
if (!$this->db->num_rows()) {
$this->Reset();
$this->deleteMonthlyUsageFromCache();
$this->initMonthlyUsageFromDatabase();
if ($this->CDRS->status['cached_keys']['saved_keys']) {
$log=sprintf("Saved %d keys\n",$this->CDRS->status['cached_keys']['saved_keys']);
print $log;
syslog(LOG_NOTICE, $log);
}
if ($this->CDRS->status['cached_keys']['failed_keys']) {
$log=sprintf("Error: failed to save %d keys\n",$this->CDRS->status['cached_keys']['failed_keys']);
print $log;
syslog(LOG_NOTICE, $log);
}
if ($this->saveQuotaInitFlag()) {
return 1;
} else {
$log=sprintf ("Error: failed to save key quotaCheckInit in memcache");
syslog(LOG_NOTICE, $log);
return 0;
}
}
}
return 1;
}
function deleteMonthlyUsageFromCache () {
$deleted_keys=0;
if (!$this->AccountsDBClass) {
print("Info: No database defined for SIP accounts.\n");
return 0;
}
if (is_object($this->CDRS->mc)) {
if ($this->enableThor) {
$query="select * from sip_accounts";
} else {
$query="select * from subscriber";
}
dprint($query);
if (!$this->AccountsDB->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->AccountsDB->Error,$this->AccountsDB->Errno);
print $log;
syslog(LOG_NOTICE,$log);
return false;
}
while($this->AccountsDB->next_record()) {
$mc_key=$this->CDRS->mc_key_mu_prefix.$this->AccountsDB->f('username')."@".$this->AccountsDB->f('domain');;
if ($this->CDRS->mc->delete($mc_key)) {
$deleted_keys++;
}
}
if ($deleted_keys) {
$log=sprintf("Deleted %d keys from cache\n",$deleted_keys);
print $log;
syslog(LOG_NOTICE, $log);
}
}
$query=sprintf("delete from memcache where `key` like '%s%s'",
$this->CDRS->mc_key_mu_prefix,"%");
dprint($query);
if (!$this->db->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->db->Error,$this->Accountsdb->Errno);
print $log;
syslog(LOG_NOTICE,$log);
return false;
}
if ($this->db->affected_rows()) {
$log=sprintf("Deleted %d mysql keys\n",$this->db->affected_rows());
print $log;
syslog(LOG_NOTICE, $log);
}
return 1;
}
function compareUsage() {
$this->initMonthlyUsageFromCache();
$this->initMonthlyUsageFromDatabase();
foreach (array_keys($this->cachedUsage) as $_key) {
if ($this->Accounts[$_key]['usage']['calls'] && $this->Accounts[$_key]['usage']['calls'] != $this->cachedUsage[$_key]['usage']['calls']) {
$errorMargin=($this->cachedUsage[$_key]['usage']['calls']/$this->Accounts[$_key]['usage']['calls']-1)*100;
printf ("%50s Database=%10d Cached=%10d Error=%.4f%s\n",$_key,$this->Accounts[$_key]['usage']['calls'],$this->cachedUsage[$_key]['usage']['calls'],$errorMargin,"%");
$errors++;
}
}
if (!$errors) print "Cached usage is up to date with database usage.\n";
}
}
class RatingEngine {
function RatingEngine (&$CDRS) {
$this->CDRS = &$CDRS;
$this->db = new DB_CDRTool;
$this->table = "prepaid";
$this->sessionCounter = 0;
$this->beginStatisticsTime = time();
$this->lastMinuteSessionCounter = 0;
$this->lastMinuteStatisticsTime = time();
$this->lastHourSessionCounter = 0;
$this->lastHourStatisticsTime = time();
$this->lastDaySessionCounter = 0;
$this->lastDayStatisticsTime = time();
}
function loadPrepaidAccounts($account='') {
$query=sprintf("select * from %s",$this->table);
if ($account) $query.= sprintf(" where account = '%s' ",addslashes($account));
dprint($query);
if (!$this->db->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->db->Error,$this->db->Errno);
print $log;
syslog(LOG_NOTICE,$log);
return false;
}
if ($account) {
if ($this->db->num_rows()) {
$this->db->next_record();
$this->balance[$this->db->f('account')] = $this->db->f('balance');
$log=sprintf("Loaded prepaid account %s with balance %s",$this->db->f('account'),$this->db->f('balance'));
syslog(LOG_NOTICE, $log);
return 1;
} else {
$log=sprintf("Error: Prepaid account %s does not exist",$account);
syslog(LOG_NOTICE, $log);
return 0;
}
} else {
while($this->db->next_record()) {
$_balance[$this->db->f('account')] = $this->db->f('balance');
}
if (is_array($_balance)) {
$this->balance=$_balance;
} else {
$this->balance=array();
}
$log=sprintf("Loaded %d prepaid accounts",count($this->balance));
syslog(LOG_NOTICE, $log);
return 1;
}
}
function reloadRatingTables () {
$b=time();
if (is_object($this->CDRS->mc)) $this->CDRS->mc->delete('destinations');
$i=$this->CDRS->LoadDestinations();
syslog(LOG_NOTICE, "Loaded $i destinations");
$this->CDRS->RatingTables->LoadRatingTables();
$this->loadPrepaidAccounts();
$e=time();
$d=$e-$b;
if ($d >0 ) syslog(LOG_NOTICE, "Loaded rating tables in $d seconds");
$this->db->query("update settings set var_value ='' where var_name = 'reloadRating'");
return 1;
}
function reloadCustomers ($customerFilter) {
$b=time();
$this->CDRS->RatingTables->LoadCustomersTable($customerFilter);
$e=time();
$d=$e-$b;
if ($d >0 ) syslog(LOG_NOTICE, "Reloaded customers in $d seconds");
return 1;
}
function reloadDomains () {
if (is_object($this->CDRS->mc)) $this->CDRS->mc->delete($this->CDRS->mc_key_domains);
return 1;
}
function reloadSipAccountsWithQuota () {
if (is_object($this->CDRS->mc)) {
if ($this->CDRS->mc->delete($this->CDRS->mc_key_accounts)) {
$log=sprintf("Deleted %s key from memcache",$this->CDRS->mc_key_accounts);
syslog(LOG_NOTICE, $log);
}
}
return 1;
}
function reloadPrepaidAccounts($account='') {
return $this->loadPrepaidAccounts($account);
}
function showPrepaidAccounts($filter) {
foreach (array_keys($this->balance) as $key) {
if (strlen($filter)) {
if (preg_match("/$filter/",$key)) {
$accounts=$accounts.sprintf("Account=%-35s Balance=%8.4f",$key,$this->balance[$key])."\n";
}
} else {
$accounts=$accounts.sprintf("Account=%-35s Balance=%8.4f",$key,$this->balance[$key])."\n";
}
}
return $accounts;
}
function DebitBalance($BillingPartyId,$balance) {
$BillingPartyId=trim($BillingPartyId);
if (preg_match("/^(.*):(.*)$/",$BillingPartyId,$m)) {
$BillingPartyId=$m[2];
}
if (!$BillingPartyId) {
syslog(LOG_NOTICE, "DebitBalance() error: missing BillingPartyId");
return 0;
}
if (strlen($BillingPartyId) > 254) {
syslog(LOG_NOTICE, "DebitBalance() error: BillingPartyId > 254 chars");
return 0;
}
if (!$BillingPartyId || !strlen($balance)) {
syslog(LOG_NOTICE, "DebitBalance() error: missing BillingPartyId or balance");
return 0;
}
if ($this->balance[$BillingPartyId]) {
$query=sprintf("update %s
set balance = balance - '%s',
change_date = NOW(),
last_call_price = '%s',
call_in_progress = '0000-00-00 00:00:00',
call_lock = '0',
maxsessiontime = '0'
where account = '%s'",
addslashes($this->table),
addslashes($balance),
addslashes($balance),
addslashes($BillingPartyId)
);
dprint($query);
if ($this->db->query($query)) {
$query=sprintf("select balance from %s where account = '%s'",
addslashes($this->table),
addslashes($BillingPartyId)
);
dprint($query);
$this->db->query($query);
$this->db->next_record();
$this->balance[$BillingPartyId]=$this->db->f('balance');
return 1;
} else {
$log=sprintf ("DebitBalance error: %s (%s)",$this->db->Error,$this->db->Errno);
syslog(LOG_NOTICE, $log);
return 0;
}
} else {
syslog(LOG_NOTICE, "DebitBalance() error: BillingPartyId=$BillingPartyId does not exist");
return "none";
}
}
function CreditBalance($BillingPartyId,$balance) {
if (!is_numeric($balance)) {
syslog(LOG_NOTICE, "CreditBalance() error: balance \"$balance\"is invalid");
return 0;
}
$BillingPartyId=trim($BillingPartyId);
if (preg_match("/^(.*):(.*)$/",$BillingPartyId,$m)) {
$BillingPartyId=$m[2];
}
if (!$BillingPartyId) {
syslog(LOG_NOTICE, "CreditBalance() error: missing BillingPartyId");
return 0;
}
if (strlen($BillingPartyId) > 254) {
syslog(LOG_NOTICE, "CreditBalance() error: BillingPartyId > 254 chars");
return 0;
}
if ($this->balance[$BillingPartyId]) {
$query=sprintf("update %s
set balance = balance + '%s',
change_date = NOW()
where account = '%s'",
addslashes($this->table),
addslashes($balance),
addslashes($BillingPartyId)
);
dprint($query);
$this->db->query($query);
if ($this->db->affected_rows()) {
$this->balance[$BillingPartyId]=$this->balance[$BillingPartyId]+$balance;
$log=sprintf ("Prepaid account $BillingPartyId credited with $balance");
syslog(LOG_NOTICE, $log);
return 1;
} else {
$error_msg=$this->db->Error;
$log=sprintf ("CreditBalance() error: failed to debit balance ($error_msg)");
syslog(LOG_NOTICE, $log);
return 0;
}
} else {
$query=sprintf("insert into %s
(balance, account, change_date)
values ('%s','%s',NOW())",
addslashes($this->table),
addslashes($balance),
addslashes($BillingPartyId)
);
dprint($query);
$this->db->query($query);
if ($this->db->affected_rows()) {
$this->balance[$BillingPartyId]=$this->balance[$BillingPartyId]+$balance;
$log=sprintf ("Added prepaid account $BillingPartyId with balance=$balance");
syslog(LOG_NOTICE, $log);
return 1;
} else {
$error_msg=$this->db->Error;
$log=sprintf ("CreditBalance() error: failed to credit balance ($error_msg)");
syslog(LOG_NOTICE, $log);
return 0;
}
}
}
function showHelp() {
$help=
"Version\n".
"Help\n".
"ShowAccounts\n".
"MaxSessionTime From=sip:123@example.com To=sip:0031650222333 Duration=7200 Lock=1\n".
"DebitBalance From=sip:123@example.com To=sip:0031650222333 Duration=59\n".
"ShowPrice From=sip:123@example.com To=sip:0031650222333 Duration=59\n".
"AddBalance From=sip:123@example.com Value=10.00\n".
"GetBalance From=sip:123@example.com\n".
"ReloadRatingTables\n".
"ReloadCustomers Customer=123@example.com Type=[Subscriber|Domain|Gateway]\n".
"ShowCustomers Filter=123@example.com\n".
"ShowRates\n".
"ShowProfiles\n".
"ReloadPrepaidAccounts Account=abc@example.com\n".
"ShowPrepaidAccounts Filter=123@example.com\n".
"ShowMemory\n".
"ReloadSipAccountsWithQuota\n".
"ReloadDomains";
return $help;
}
function processNetworkInput($tinput) {
// Read key=value pairs from input
// Strip any unnecessary spaces
$tinput=preg_replace("/=\s{1,}/","= ",$tinput);
$tinput=preg_replace("/\s{1,}=/","= ",$tinput);
$tinput=preg_replace("/\s+/"," ",$tinput);
$_els=explode(" ",trim($tinput));
dprint_r($_els);
syslog(LOG_NOTICE, $tinput);
if (!$_els[0]) return 0;
// read fields from input
unset($NetFields);
unset($seenField);
$i=0;
while ($i < count($_els)) {
$i++;
$_dict = explode("=",$_els[$i]);
$_key = strtolower(trim($_dict[0]));
$_value = strtolower(trim($_dict[1]));
if (strlen($_key) && $seenField[$_key]) {
$log=sprintf ("Error: '$_key' attribute is present more than once in $tinput");
syslog(LOG_NOTICE, $log);
return 0;
} else {
if (strlen($_key)) {
$NetFields[$_key]=$_value;
$seenField[$_key]++;
}
}
}
$NetFields['action']=strtolower($_els[0]);
/*
foreach(array_keys($NetFields) as $_field) {
$log.=sprintf("Field=%s Value=%s ",$_field,$NetFields[$_field]);
}
syslog(LOG_NOTICE, $log);
*/
// begin processing
if ($NetFields['action']=="maxsessiontime") {
if (!$NetFields['from']) {
dprint("Missing From parameter.");
$log=sprintf ("Error: Missing From parameter");
syslog(LOG_NOTICE, $log);
return 0;
}
if (!$NetFields['to']) {
dprint("Missing To parameter.");
$log=sprintf ("Error: Missing To parameter");
syslog(LOG_NOTICE, $log);
return 0;
}
if (!strlen($NetFields['duration'])) {
$NetFields['duration']=12*3600; // 12 hours
}
$this->sessionCounter++;
$this->lastMinuteSessionCounter++;
$this->lastHourSessionCounter++;
$this->lastDaySessionCounter++;
$_now=time();
$_runtime = time() - $this->beginStatisticsTime;
$_intervalMinute = $_now - $this->lastMinuteStatisticsTime;
if ( $_now > $this->lastMinuteStatisticsTime + 60 && $_intervalMinute > 0) {
$log=sprintf("Normalization done in %d s, memory usage: %0.2f MB",$d,memory_get_usage()/1024/1024);
$_cpsTotal = $this->sessionCounter/$_runtime;
$_cpsMinute = $this->lastMinuteSessionCounter/$_intervalMinute;
$this->statistics = array (
'lastMinute' => array('calls' => $this->lastMinuteSessionCounter,
'interval' => $_intervalMinute,
'cps' => $_cpsMinute ),
'total' => array('calls' => $this->sessionCounter,
'interval' => $_runtime,
'cps' => $_cpsTotal)
);
$this->lastMinuteSessionCounter=0;
$this->lastMinuteStatisticsTime=time();
$log=sprintf ("Load last minute: %s calls @ %s cps, memory: %0.2f MB",
$this->statistics['lastMinute']['calls'],
sprintf("%.2f",$this->statistics['lastMinute']['cps']),
memory_get_usage()/1024/1024);
syslog(LOG_NOTICE, $log);
$_intervalHour = $_now - $this->lastHourStatisticsTime;
if ( $_now > $this->lastHourStatisticsTime + 3600 && $_intervalHour > 0) {
$_cpsHour = $this->lastHourSessionCounter/$_intervalHour;
$this->statistics['lastHour'] = array('calls' => $this->lastHourSessionCounter,
'interval' => $_intervalHour,
'cps' => $_cpsHour );
$this->lastHourSessionCounter=0;
$this->lastHourStatisticsTime=time();
$log=sprintf ("Load last hour: %s calls @ %s cps",
$this->statistics['lastHour']['calls'],
sprintf("%.2f",$this->statistics['lastHour']['cps']));
syslog(LOG_NOTICE, $log);
$log=sprintf ("Load since start: %s sessions @ %s cps",
$this->statistics['total']['calls'],
sprintf("%.2f",$this->statistics['total']['cps']));
syslog(LOG_NOTICE, $log);
}
$_intervalDay = $_now - $this->lastDayStatisticsTime;
if ( $_now > $this->lastDayStatisticsTime + 3600*24 && $_intervalDay > 0) {
$_cpsDay = $this->lastDaySessionCounter/$_intervalDay;
$this->statistics['lastDay'] = array('calls' => $this->lastDaySessionCounter,
'interval' => $_intervalDay,
'cps' => $_cpsDay );
$this->lastDaySessionCounter=0;
$this->lastDayStatisticsTime=time();
$log=sprintf ("Load last day: %s calls @ %s cps",
$this->statistics['lastDay']['calls'],
sprintf("%.2f",$this->statistics['lastDay']['cps']));
syslog(LOG_NOTICE, $log);
}
}
$CDRStructure=array (
$this->CDRS->CDRFields['callId'] => $NetFields['callid'],
$this->CDRS->CDRFields['aNumber'] => $NetFields['from'],
$this->CDRS->CDRFields['cNumber'] => $NetFields['to'],
$this->CDRS->CDRFields['RemoteAddress'] => $NetFields['to'],
$this->CDRS->CDRFields['CanonicalURI'] => $NetFields['to'],
$this->CDRS->CDRFields['duration'] => $NetFields['duration'],
$this->CDRS->CDRFields['timestamp'] => time()
);
dprint_r($CDRStructure);
$CDR = new $this->CDRS->CDR_class($this->CDRS, $CDRStructure);
$CDR->normalize();
$Balance=$this->balance[$CDR->BillingPartyId];
$c=count($this->balance);
if (!strlen($Balance)) {
return "none";
}
$query=sprintf("select * from %s
where account = '%s'",
addslashes($this->table),
addslashes($CDR->BillingPartyId)
);
if (!$this->db->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->db->Error,$this->db->Errno);
syslog(LOG_NOTICE,$log);
return "none";
}
if ($this->db->num_rows()) {
$this->db->next_record();
if ($this->db->f('call_lock') == "1") {
$_cip=$this->db->f('call_in_progress');
$log = sprintf ("Account locked, call in progres since $_cip");
syslog(LOG_NOTICE, $log);
return "locked";
}
} else {
$log = sprintf ("Prepaid $CDR->BillingPartyId does not exist");
syslog(LOG_NOTICE, $log);
return "none";
}
if (!preg_match("/^0/",$CDR->RemoteAddressNormalized)) {
$log = sprintf ("Call to %s, no limit imposed",$CDR->RemoteAddressNormalized);
syslog(LOG_NOTICE, $log);
return "none";
} else {
if (!$CDR->DestinationId) {
$log = sprintf ("Error: cannot figure out the destination id for $CDR->RemoteAddress");
syslog(LOG_NOTICE, $log);
return "0";
}
}
if ($Balance) {
$maxduration=0;
// Build Rate dictionary containing normalized CDR fields plus customer Balance
$RateDictionary=array(
'duration' => $CDR->duration,
'callId' => $CDR->callId,
'Balance' => $Balance,
'timestamp' => $CDR->timestamp,
'DestinationId' => $CDR->DestinationId,
'destinationName' => $CDR->destinationName,
'domain' => $CDR->domain,
'BillingPartyId' => $CDR->BillingPartyId,
'RatingTables' => &$this->CDRS->RatingTables
);
$Rate = new Rate(&$CDR);
$maxduration = round($Rate->MaxSessionTime($RateDictionary));
if ($maxduration<0) {
$log = sprintf ("Error: maxduration is negative ($maxduration)");
syslog(LOG_NOTICE, $log);
return 0;
}
if (!$Rate->billingTimezone) {
$log = sprintf ("Error: cannot figure out the billing timezone");
syslog(LOG_NOTICE, $log);
return 0;
}
if (!$Rate->startTimeBilling) {
$log = sprintf ("Error: cannot figure out the billing start time");
syslog(LOG_NOTICE, $log);
return 0;
}
$log=sprintf ("CallId=%s BillingParty=%s DestId=%s Balance=%s MaxSessionTime=%s",
$NetFields['callid'],
$CDR->BillingPartyId,
$CDR->DestinationId,
$RateDictionary['Balance'],
$maxduration
);
syslog(LOG_NOTICE, $log);
if ($NetFields['lock'] && $maxduration > 0) {
// mark the account that is locked during call
$query=sprintf("update %s
set call_in_progress = NOW(),
call_lock = '1',
destination = '%s',
maxsessiontime = '%s'
where account = '%s'",
addslashes($this->table),
addslashes($CDR->destinationPrint),
addslashes($maxduration),
addslashes($CDR->BillingPartyId));
dprint($query);
if (!$this->db->query($query)) {
$log=sprintf ("Database error: %s (%s)",$this->db->Error,$this->db->Errno);
syslog(LOG_NOTICE,$log);
return false;
}
if (!$this->db->affected_rows()) {
$log=sprintf ("$CDR->BillingPartyId is already locked");
syslog(LOG_NOTICE, $log);
}
}
return $maxduration;
} else {
return 0;
}
} else if ($NetFields['action'] == "debitbalance") {
if (!$NetFields['from']) {
dprint("Missing From parameter.");
$log=sprintf ("Error: Missing From parameter");
syslog(LOG_NOTICE, $log);
return "Failed";
}
if (!$NetFields['to']) {
dprint("Missing To parameter.");
$log=sprintf ("Error: Missing To parameter");
syslog(LOG_NOTICE, $log);
return "Failed";
}
if (!strlen($NetFields['duration'])) {
dprint("Missing Duration parameter.");
$log=sprintf ("Error: Missing Duration parameter");
syslog(LOG_NOTICE, $log);
return "Failed";
}
$CDRStructure=array (
$this->CDRS->CDRFields['aNumber'] => $NetFields['from'],
$this->CDRS->CDRFields['cNumber'] => $NetFields['to'],
$this->CDRS->CDRFields['RemoteAddress'] => $NetFields['to'],
$this->CDRS->CDRFields['CanonicalURI'] => $NetFields['to'],
$this->CDRS->CDRFields['duration'] => $NetFields['duration'],
$this->CDRS->CDRFields['timestamp'] => time(),
);
dprint_r($CDRStructure);
// Init CDR
$CDR = new $this->CDRS->CDR_class($this->CDRS, $CDRStructure);
$CDR->normalize();
if (!is_array($this->balance) || !array_key_exists($CDR->BillingPartyId,$this->balance)) {
$log=sprintf ("Warning: Account %s is not prepaid",$CDR->BillingPartyId);
syslog(LOG_NOTICE, $log);
return "Not Prepaid";
}
// Build Rate dictionary containing normalized CDR fields plus customer Balance
$RateDictionary=array(
'duration' => $CDR->duration,
'timestamp' => $CDR->timestamp,
'DestinationId' => $CDR->DestinationId,
'destinationName' => $CDR->destinationName,
'domain' => $CDR->domain,
'traffic' => $CDR->traffic,
'BillingPartyId' => $CDR->BillingPartyId,
'RatingTables' => &$this->CDRS->RatingTables
);
$Rate = new Rate(&$CDR);
$Rate->calculate($RateDictionary);
$result = $this->DebitBalance($CDR->BillingPartyId,$Rate->price);
if ($CDR->duration) {
$oldBalance=$this->balance[$CDR->BillingPartyId];
$log=sprintf ("CallId=%s BillingParty=%s DestId=%s Duration=%s Price=%s Balance=%s",
$NetFields['callid'],
$CDR->BillingPartyId,
$CDR->DestinationId,
$CDR->duration,
$Rate->price,
$this->balance[$CDR->BillingPartyId]
);
syslog(LOG_NOTICE, $log);
}
if ($result) {
return "Ok";
} else {
return "Failed";
}
} else if ($NetFields['action'] == "addbalance") {
if (!$NetFields['from']) {
dprint("Missing From parameter.");
$log=sprintf ("Error: Missing From parameter");
syslog(LOG_NOTICE, $log);
return 0;
}
if (!$NetFields['value']) {
dprint("Missing Value parameter.");
$log=sprintf ("Error: Missing Value parameter");
syslog(LOG_NOTICE, $log);
return 0;
}
$log=sprintf ("Customer : %s",$NetFields['from']);
syslog(LOG_NOTICE, $log);
$log=sprintf ("Balance : %s",$this->balance[$NetFields['from']]);
syslog(LOG_NOTICE, $log);
$result = $this->CreditBalance($NetFields['from'],$NetFields['value']);
$log=sprintf ("New Balance : %s",$this->balance[$NetFields['from']]);
syslog(LOG_NOTICE, $log);
if ($result) {
return $result;
} else {
return 0;
}
} else if ($NetFields['action'] == "showprice") {
if (!$NetFields['from']) {
dprint("Missing From parameter.");
$log=sprintf ("Error: Missing From parameter");
syslog(LOG_NOTICE, $log);
return 0;
}
if (!$NetFields['to']) {
dprint("Missing To parameter.");
$log=sprintf ("Error: Missing To parameter");
syslog(LOG_NOTICE, $log);
return 0;
}
if (!strlen($NetFields['duration'])) {
dprint("Missing Duration parameter.");
$log=sprintf ("Error: Missing Duration parameter");
syslog(LOG_NOTICE, $log);
return 0;
}
if ($NetFields['timestamp']) {
$timestamp=$NetFields['timestamp'];
} else {
$timestamp=time();
}
$application="audio";
if ($NetFields['application']) $application=$NetFields['application'];
$CDRStructure=array (
$this->CDRS->CDRFields['id'] => $NetFields['id'],
$this->CDRS->CDRFields['timestamp'] => $timestamp,
$this->CDRS->CDRFields['duration'] => $NetFields['duration'],
$this->CDRS->CDRFields['aNumber'] => $NetFields['from'],
$this->CDRS->CDRFields['cNumber'] => $NetFields['to'],
$this->CDRS->CDRFields['RemoteAddress'] => $NetFields['to'],
$this->CDRS->CDRFields['CanonicalURI'] => $NetFields['to'],
$this->CDRS->CDRFields['inputTraffic'] => $NetFields['inputTraffic'],
$this->CDRS->CDRFields['outputTraffic'] => $NetFields['outputTraffic'],
$this->CDRS->CDRFields['applicationType'] => $application,
$this->CDRS->CDRFields['gateway'] => $NetFields['gateway']
);
// Init CDR
$CDR = new $this->CDRS->CDR_class($this->CDRS, $CDRStructure);
$CDR->normalize();
// Build Rate dictionary containing normalized CDR fields
$RateDictionary=array(
'id' => $CDR->id,
'timestamp' => $CDR->timestamp,
'duration' => $CDR->duration,
'DestinationId' => $CDR->DestinationId,
'traffic' => $CDR->traffic,
'BillingPartyId' => $CDR->BillingPartyId,
'domain' => $CDR->domain,
'gateway' => $CDR->gateway,
'RatingTables' => &$this->CDRS->RatingTables,
'applicationType' => $CDR->applicationType,
'aNumber' => $CDR->aNumber,
'cNumber' => $CDR->cNumber,
'destinationName' => $CDR->destinationName
);
$Rate = new Rate(&$CDR);
$Rate->calculate($RateDictionary);
if (strlen($Rate->price)) {
$RateReturn=$Rate->price;
if (strlen($Rate->rateInfo)) {
$RateReturn.="\n".trim($Rate->rateInfo);
}
} else {
$RateReturn="0";
}
//if ($Rate->price) syslog(LOG_NOTICE, "Price=$Rate->price");
return $RateReturn;
} else if ($NetFields['action'] == "getbalance") {
if (!$NetFields['from']) {
dprint("Missing From parameter.");
$log=sprintf ("Error: Missing From parameter");
syslog(LOG_NOTICE, $log);
return 0;
}
$log=sprintf ("Customer : %s",$NetFields['from']);
syslog(LOG_NOTICE, $log);
$log=sprintf ("Balance : %s",$this->balance[$NetFields['from']]);
syslog(LOG_NOTICE, $log);
if (!$this->balance[$NetFields['from']]) {
$balance="0.00";
} else {
$balance=number_format($this->balance[$NetFields['from']],4,".","");
}
return $balance;
} else if ($NetFields['action'] == "showprepaidaccounts") {
return trim($this->showPrepaidAccounts($NetFields['filter']));
} else if ($NetFields['action'] == "showcustomers") {
return trim($this->CDRS->RatingTables->showCustomers($NetFields['filter']));
} else if ($NetFields['action'] == "showprofiles") {
return trim($this->CDRS->RatingTables->showProfiles());
} else if ($NetFields['action'] == "showrates") {
return trim($this->CDRS->RatingTables->showRates());
} else if ($NetFields['action'] == "version") {
$version_file=$this->CDRS->CDRTool['Path']."/version";
$version="CDRTool version ".trim(file_get_contents($version_file));
return $version;
} else if ($NetFields['action'] == "help") {
return $this->showHelp();
} else if ($NetFields['action'] == "reloadratingtables") {
return $this->reloadRatingTables();
} else if ($NetFields['action'] == "reloadsipaccountswithquota") {
return $this->reloadSipAccountsWithQuota();
} else if ($NetFields['action'] == "reloaddomains") {
return $this->CDRS->LoadDomains();
} else if ($NetFields['action'] == "reloadcustomers") {
if ($NetFields['customer'] && $NetFields['type']) {
$_customerFilter=array('customer'=>$NetFields['customer'],
'type'=>$NetFields['type']);
}
return $this->reloadCustomers($_customerFilter);
} else if ($NetFields['action'] == "reloadprepaidaccounts") {
return $this->reloadPrepaidAccounts($NetFields['account']);
} else if ($NetFields['action'] == "showmemory") {
$return = sprintf ("%s destinations\n%s customers\n%s profiles\n%s rates\n%s holidays\n%s prepaid accounts\n%s sessions\n%s sessions last minute\n%s sessions last hour\n%s sessions last day",
$this->CDRS->destinationsCount,
count($this->CDRS->RatingTables->customers),
count($this->CDRS->RatingTables->profiles),
$this->CDRS->RatingTables->ratesCount,
count($this->CDRS->RatingTables->holidays),
count($this->balance),
count($this->sessionCounter),
count($this->lastMinuteSessionCounter),
count($this->lastHourSessionCounter),
count($this->lastDaySessionCounter)
);
return $return;
} else {
dprint("Invalid request. ");
$log=sprintf ("Error: Invalid request");
syslog(LOG_NOTICE, $log);
return 0;
}
}
}
function reloadRatingEngineTables () {
global $RatingEngine;
if ($RatingEngine["socketIP"] && $RatingEngine["socketPort"] &&
$fp = fsockopen ($RatingEngine["socketIP"], $RatingEngine["socketPort"], $errno, $errstr, 2)) {
fputs($fp, "ReloadRatingTables\n");
fclose($fp);
return 1;
}
return 0;
}
function reloadPrepaidAccounts($account='') {
global $RatingEngine;
if ($RatingEngine["socketIP"] && $RatingEngine["socketPort"] &&
$fp = fsockopen ($RatingEngine["socketIP"], $RatingEngine["socketPort"], $errno, $errstr, 2)) {
$account=trim($account);
$cmd="ReloadPrepaidAccounts";
if (strlen($account)) $cmd .= sprintf(" Account=%s",$account);
$cmd.="\n";
fputs($fp,$cmd);
fclose($fp);
return 1;
}
return 0;
}
function reloadSipAccountsWithQuota () {
global $RatingEngine;
if ($RatingEngine["socketIP"] && $RatingEngine["socketPort"] &&
$fp = fsockopen ($RatingEngine["socketIP"], $RatingEngine["socketPort"], $errno, $errstr, 2)) {
fputs($fp, "reloadSipAccountsWithQuota\n");
fclose($fp);
return 1;
}
return 0;
}
?>
diff --git a/sip_statistics_lib.phtml b/sip_statistics_lib.phtml
index 4c08707..edc6da1 100644
--- a/sip_statistics_lib.phtml
+++ b/sip_statistics_lib.phtml
@@ -1,675 +1,675 @@
<?
class SIPstatistics {
var $SipEnabledZones = array();
var $online = array();
var $StatisticsPresentities = array();
function SIPstatistics () {
global $CDRTool;
$this->mrtgcfg_file = $CDRTool['Path']."/status/usage/sip_statistics.mrtg";
$this->harvest_file = "/tmp/CDRTool-sip-statistics.txt";
$this->mrtgcfg_dir = $CDRTool['Path']."/status/usage";
$this->index_file = $CDRTool['Path']."/status/usage/index.phtml";
$this->harvest_script = $CDRTool['Path']."/scripts/harvestStatistics.php";
$this->generateMrtgDataScript = $CDRTool['Path']."/scripts/generateMrtgData.php";
$this->generateMrtgConfigScript = $CDRTool['Path']."/scripts/generateMrtgConfig.php";
$this->db = new DB_cdrtool();
$this->ser_db = new DB_ser();
if (class_exists('DB_siponline')) {
$this->online_db = new DB_siponline();
} else {
$this->online_db = new DB_ser();
}
if (is_array($CDRTool['StatisticsPresentities'])) {
$this->StatisticsPresentities = $CDRTool['StatisticsPresentities'];
}
}
function getSipEnabledZones () {
global $CDRTool;
$query="select domain from domain";
dprint($query);
if (!$this->ser_db->query($query)) return 0;
if (!$this->ser_db->num_rows()) return 0;
while ($this->ser_db->next_record()) {
$zName=$this->ser_db->f('domain');
if (is_array($CDRTool['statistics']['zoneFilter']) && !in_array($zName,$CDRTool['statistics']['zoneFilter'])) continue;
if (!$seen[$zName]) {
$this->SipEnabledZones[$zName] = $zName;
$this->statistics[$zName] =
array( 'online_users' => '0',
'sessions' => '0',
'traffic' => '0',
'caller' => '0',
'called' => '0'
);
$seen[$zName]++;
}
}
if (is_array($CDRTool['statistics']['extraZones'])) {
foreach ($CDRTool['statistics']['extraZones'] as $zName) {
if (!$seen[$zName]) {
$this->SipEnabledZones[$zName] = $zName;
$this->statistics[$zName] =
array( 'online_users' => '0',
'sessions' => '0',
'traffic' => '0',
'caller' => '0',
'called' => '0'
);
$seen[$zName]++;
}
}
}
//dprint_r($this->SipEnabledZones);
//dprint_r($this->statistics);
}
function generateHTMLUsageIndexPage () {
global $CDRTool;
$this->getSipEnabledZones();
if (!$handle = fopen($this->index_file, 'w+')) {
echo "Error opening {$this->index_file}.\n";
return 0;
}
// printing cfg header
$title=$CDRTool['provider']['name']." SIP statistics";
fwrite($handle,"<?
include(\"../../global.inc\");
page_open(
array(\"sess\" => \"CDRTool_Session\",
\"auth\" => \"CDRTool_Auth\",
\"perm\" => \"CDRTool_Perm\"
));
\$perm->check(\"statistics\");
global \$CDRTool;
if (strlen(\$CDRTool['filter']['domain'])) {
\$allowedDomains=explode(' ',\$CDRTool['filter']['domain']);
}
?>
<HTML>
<HEAD>
<TITLE>$title</TITLE>
<META HTTP-EQUIV='Refresh' CONTENT='300'>
<META HTTP-EQUIV='Cache-Control' content='no-cache'>
<META HTTP-EQUIV='Pragma' CONTENT='no-cache'>
<META HTTP-EQUIV='Expires' CONTENT='Thu, 16 Dec 2004 16:08:32 GMT'>
</HEAD>
<BODY bgcolor='#ffffff' text='#000000' link='#000000' vlink='#000000' alink='#000000'>
<DIV align='left'><font size='5' face=verdana><B>$title</B></font></DIV>
<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=10>
<? if (\$perm->have_perm('admin')) { ?>
");
$key="total";
$block=sprintf("
<TR>
<TD><DIV align='center'><B> Online Users for %s </B></DIV>
<DIV><A HREF='%s_users.html'><IMG BORDER=0 ALT='%s_users Traffic Graph' SRC='%s_users-day.png'></A>
<SMALL><!--#flastmod file='%s_users.html' --></SMALL></DIV>
</TD><TD><DIV align='center'><B> Active Sessions for %s </B></DIV>
<DIV><A HREF='%s_sessions.html'><IMG BORDER=0 ALT='%s_sessions Traffic Graph' SRC='%s_sessions-day.png'></A>
<SMALL><!--#flastmod file='%s_sessions.html' --></SMALL></DIV>
</TD><TD><DIV align='center'><B> IP Traffic for %s </B></DIV>
<DIV><A HREF='%s_traffic.html'><IMG BORDER=0 ALT='%s_traffic Traffic Graph' SRC='%s_traffic-day.png'></A>
<SMALL><!--#flastmod file='%s_traffic.html' --></SMALL></DIV>
</TD></TR>
<TR>
<? } ?>
",
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key
);
fwrite($handle,$block);
while(list($key,$value) = each($this->SipEnabledZones)) {
$block=sprintf("
<? if (in_array('$key',\$allowedDomains)) { ?>
<TR>
<TD><DIV align='center'><B> Online Users for %s </B></DIV>
<DIV><A HREF='%s_users.html'><IMG BORDER=0 ALT='%s_users Traffic Graph' SRC='%s_users-day.png'></A>
<SMALL><!--#flastmod file='%s_users.html' --></SMALL></DIV>
</TD><TD><DIV align='center'><B> Active Sessions for %s </B></DIV>
<DIV><A HREF='%s_sessions.html'><IMG BORDER=0 ALT='%s_sessions Traffic Graph' SRC='%s_sessions-day.png'></A>
<SMALL><!--#flastmod file='%s_sessions.html' --></SMALL></DIV>
</TD><TD><DIV align='center'><B> IP Traffic for %s </B></DIV>
<DIV><A HREF='%s_traffic.html'><IMG BORDER=0 ALT='%s_traffic Traffic Graph' SRC='%s_traffic-day.png'></A>
<SMALL><!--#flastmod file='%s_traffic.html' --></SMALL></DIV>
</TD></TR>
<TR>
<? } ?>
",
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key,
$key
);
fwrite($handle,$block);
}
fwrite($handle,"
</TABLE>
</BODY>
</HTML>
<?
page_close();
?>");
fclose($handle);
}
function generateMrtgConfigFile () {
$this->getSipEnabledZones();
if (!$handle = fopen($this->mrtgcfg_file, 'w+')) {
echo "Error opening {$this->mrtgcfg_file}.\n";
return 0;
}
// printing cfg header
fwrite($handle,"
### Global Config Options
WorkDir: {$this->mrtgcfg_dir}
IconDir: {$this->mrtgcfg_dir}/images
Refresh: 300
#WriteExpires: Yes
");
$_zones=$this->SipEnabledZones;
$_zones['total']='total';
while(list($key,$value) = each($_zones)) {
fwrite($handle,"\n\n
## {$key}
Target[{$key}_users]: `{$this->generateMrtgDataScript} {$key} users`
Options[{$key}_users]: growright, gauge, nobanner
BodyTag[{$key}_users]: <BODY LEFTMARGIN=\"1\" TOPMARGIN=\"1\">
#PNGTitle[{$key}_users]: <center>Online Users for {$key}</center>
MaxBytes[{$key}_users]: 5000000
Title[{$key}_users]: Online Users for {$key}
ShortLegend[{$key}_users]: U
XSize[{$key}_users]: 300
YSize[{$key}_users]: 75
Ylegend[{$key}_users]: Users
Legend1[{$key}_users]: Online Users
LegendI[{$key}_users]: Online Users
LegendO[{$key}_users]:
PageTop[{$key}_users]: <H1> Online Users for {$key} </H1>
Target[{$key}_sessions]: `{$this->generateMrtgDataScript} {$key} sessions`
Options[{$key}_sessions]: growright, nobanner, gauge
BodyTag[{$key}_sessions]: <BODY LEFTMARGIN=\"1\" TOPMARGIN=\"1\">
MaxBytes[{$key}_sessions]: 50000
Title[{$key}_sessions]: Sessions Statistics for {$key}
ShortLegend[{$key}_sessions]: Ses
XSize[{$key}_sessions]: 300
YSize[{$key}_sessions]: 75
Ylegend[{$key}_sessions]: Sessions
Legend1[{$key}_sessions]: Active Sessions
LegendI[{$key}_sessions]: Active Sessions
LegendO[{$key}_sessions]:
PageTop[{$key}_sessions]: <H1> Active Sessions for {$key} </H1>
Target[{$key}_traffic]: `{$this->generateMrtgDataScript} {$key} traffic`
Options[{$key}_traffic]: gauge, growright, bits, nobanner
BodyTag[{$key}_traffic]: <BODY LEFTMARGIN=\"1\" TOPMARGIN=\"1\">
#PNGTitle[{$key}_traffic]: {$key} traffic
MaxBytes[{$key}_traffic]: 1250000000
Title[{$key}_traffic]: IP traffic for {$key}
XSize[{$key}_traffic]: 300
YSize[{$key}_traffic]: 75
Legend1[{$key}_traffic]: Caller Traffic in Bits per Second
Legend2[{$key}_traffic]: Called Traffic in Bits per Second
LegendI[{$key}_traffic]: caller
LegendO[{$key}_traffic]: called
PageTop[{$key}_traffic]: <H1> IP Traffic for {$key} </H1>
");
}
fclose($handle);
}
function generateMrtgData($domain,$dataType) {
$value1=0;
$value2=0;
$lines=explode("\n",file_get_contents($this->harvest_file));
foreach ($lines as $line) {
if (preg_match("/^$domain\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/",$line,$m)) {
if ($dataType == 'sessions') {
$value1 = $m[2];
$value2 = $m[2];
} else if ($dataType == 'traffic') {
$value1 = $m[3];
$value2 = $m[4];
} else if ($dataType == 'users') {
$value1 = $m[1];
$value2 = $m[1];
}
}
}
printf ("%d\n%d\n0\n0\n\n",$value1,$value2);
}
function getSIPOnlineUsers() {
$query="select count(*) as c, domain from location group by domain";
dprint($query);
if (!$this->online_db->query($query)) return 0;
if (!$this->online_db->num_rows()) return 0;
while ($this->online_db->next_record()) {
$this->online[$this->online_db->f('domain')]=$this->online_db->f('c');
}
dprint_r($this->online);
}
function harvestStatistics() {
if (!$handle = fopen($this->harvest_file, 'w+')) {
echo "Error opening $this->harvest_file\n";
return 0;
}
$path = dirname(realpath($_SERVER['PHP_SELF']));
include($path."/../status/config/media_servers.php");
$this->mediaServers=$servers;
fwrite($handle,"domains\t\t\tonline_users\tsessions\tcaller\tcalled\n\n");
$this->getSipEnabledZones();
$this->getSIPOnlineUsers();
foreach($this->mediaServers as $server) {
$this->statistics = $this->getrtpsessions($server, "25060", $this->statistics);
}
$domains=array_keys($this->SipEnabledZones);
ksort($domains);
foreach($domains as $_domain) {
foreach (array_keys($this->online) as $_domain_online) {
if ($_domain == $_domain_online) {
// update online users in big stats array
$this->statistics[$_domain]['online_users']=$this->online[$_domain];
}
}
}
// we must multiply the IP traffic by 2 when traffic enters and exists the network where the relay is located
// this depends however on topology, if IP traffic is relayed to a node on the same physical network as the media relay
// the relayed traffic will not corespond with the IP traffic monitored at the edge of the network
$totals=array('online_users' =>0,
'sessions' =>0,
'caller' =>0,
'called' =>0
);
dprint_r($this->statistics);
while(list($key, $usage) = each($this->statistics)) {
if ($usage['online_users']) {
$online_users=$usage['online_users'];
$totals['online_users']+=$usage['online_users'];
} else {
$online_users=0;
}
if ($usage['sessions']) {
$sessions=$usage['sessions'];
$totals['sessions']+=$usage['sessions'];
} else {
$sessions=0;
}
if ($usage['caller']) {
$caller=$usage['caller']*2;
$totals['caller']+=$usage['caller']*2;
} else {
$caller=0;
}
if ($usage['called']) {
$called=$usage['called']*2;
$totals['called']+=$usage['called']*2;
} else {
$called=0;
}
fwrite($handle,"{$key}\t\t{$online_users}\t\t{$sessions}\t\t{$caller}\t{$called}\n");
if (in_array($key,array_keys($this->StatisticsPresentities))) {
if (!$online_users) {
$activity='busy';
} else {
$activity='open';
}
$note=sprintf("%s: Sessions %d, Online %d",$key, $sessions,$online_users);
$this->publishPresence ($this->StatisticsPresentities[$key]['SoapEngineId'],
$this->StatisticsPresentities[$key]['SIPaccount'],
$note,
$activity);
}
}
$total_text=sprintf("total\t\t%d\t\t%d\t\t%s\t%s\n",
$totals['online_users'],
$totals['sessions'],
$totals['caller'],
$totals['called']
);
fwrite($handle,$total_text);
fclose($handle);
}
function getrtpsessions($ip, $port, $_domains) {
if ($fp = fsockopen ($ip, $port, $errno, $errstr, "5") ) {
fputs($fp, "status\n");
$proxy = array('status' => 'Ok');
$crtSession = 'None';
while (!feof($fp)) {
$j++;
$line = fgets($fp, 2048);
$elements = explode(" ", $line);
if ($elements[0] == 'proxy' && count($elements)==3) {
$proxy['sessionCount'] = $elements[1];
$traffic = explode("/", $elements[2]);
$proxy['traffic'] = array('caller' => $traffic[0],
'called' => $traffic[1],
'relayed' => $traffic[2]);
$proxy['sessions'] = array();
} else if ($elements[0]=='session' && count($elements)==7) {
$crtSession = $elements[1];
$info = array('from' => $elements[2],
'to' => $elements[3],
'fromAgent' => "'".$elements[4]."'",
'toAgent' => "'".$elements[5]."'",
'duration' => $elements[6],
'streams' => array());
$proxy['sessions'][$crtSession] = $info;
list($caller, $caller_domain) = explode("@", $proxy['sessions'][$crtSession]['from']);
$caller_domain_els=explode(":",$caller_domain);
$caller_domain=$caller_domain_els[0];
$_domains[$caller_domain]['sessions'] += 1;
} else if ($elements[0] == 'stream' && count($elements)==9 && $proxy['sessions'][$crtSession]['duration'] > 0) {
$stream = array('caller' => $elements[1],
'called' => $elements[2],
'via' => $elements[3],
'bytes' => explode("/", $elements[4]),
'status' => $elements[5],
'codec' => $elements[6],
'type' => $elements[7],
'idletime' => $elements[8]);
$proxy['sessions'][$crtSession]['streams'][] = $stream;
$_domains[$caller_domain]['caller'] += floor($proxy['sessions'][$crtSession]['streams'][0]['bytes'][0]/$proxy['sessions'][$crtSession]['duration']);
$_domains[$caller_domain]['called'] += floor($proxy['sessions'][$crtSession]['streams'][0]['bytes'][1]/$proxy['sessions'][$crtSession]['duration']);
$_domains[$caller_domain]['traffic'] += $proxy['sessions'][$crtSession]['streams'][0]['bytes'][0];
$_domains[$caller_domain]['traffic'] += $proxy['sessions'][$crtSession]['streams'][0]['bytes'][1];
}
}
return $_domains;
}
}
function normalizeBytes($bytes) {
$mb = $bytes/1024/1024.0;
$kb = $bytes/1024.0;
if ($mb >= 0.95) {
return sprintf("%.2fM", $mb);
} else if ($kb >= 1) {
return sprintf("%.2fk", $kb);
} else {
return sprintf("%d", $bytes);
}
}
function normalizeTraffic($traffic) {
// input is in bytes/second
$traffic = $traffic * 8;
$mb = $traffic/1024/1024.0;
$kb = $traffic/1024.0;
if ($mb >= 0.95) {
return sprintf("%.2fMbps", $mb);
} else if ($kb >= 1) {
return sprintf("%.2fkbps",$kb);
} else {
return sprintf("%dbps",$traffic);
}
}
function buildStatistics() {
system($this->generateMrtgConfigScript);
system($this->harvest_script);
system("mrtg $this->mrtgcfg_file");
}
function getOnlineTrend() {
$ips_old=array();
$ips_new=array();
$query="select count(*) as c from location";
$this->online_db->query($query);
$this->online_db->next_record();
$count_new=$this->online_db->f('c');
printf ("%d Contacts new registerd\n",$count_new);
$query="select count(*) as c from count_contacts";
$this->online_db->query($query);
$this->online_db->next_record();
$count_old=$this->online_db->f('c');
printf ("%d Contacts old registerd\n",$count_old);
$query="select * from online_ips";
dprint($query);
$this->online_db->query($query);
while ($this->online_db->next_record()) {
$els=explode(";",$this->online_db->f('ip'));
$ips_old[]=$els[0];
}
sort($ips_old);
printf ("%d IPs old registerd\n",count($ips_old));
$query="select distinct(SUBSTRING_INDEX(SUBSTRING_INDEX(contact, '@',-1),':',1))
as ip from location";
dprint($query);
$this->online_db->query($query);
while ($this->online_db->next_record()) {
$els=explode(";",$this->online_db->f('ip'));
$ips_new[]=$els[0];
}
sort($ips_new);
printf ("%d IPs new registerd\n",count($ips_new));
$left=array_diff($ips_old,$ips_new);
$join=array_diff($ips_new,$ips_old);
sort($left);
sort($join);
if (count($join)) {
printf ("%d IPs joined: ",count($join));
foreach ($join as $var) print "$var ";
print "\n";
}
if (count($left)) {
printf ("%d IPs left: ",count($left));
foreach ($left as $var) print "$var ";
print "\n";
}
//print_r($left);
$query="drop table if exists online_ips";
dprint($query);
$this->online_db->query($query);
$query="create table online_ips
select distinct(SUBSTRING_INDEX(SUBSTRING_INDEX(contact, '@',-1),':',1))
as ip from location";
dprint($query);
$this->online_db->query($query);
$query="drop table if exists count_contacts";
dprint($query);
$this->online_db->query($query);
$query="create table count_contacts
select count(*)a as c from location";
dprint($query);
$this->online_db->query($query);
//dprint_r($this->online);
}
function publishPresence ($SoapEngineId,$SIPaccount,$note,$activity) {
- require_once("provisioning_soap_library.phtml");
+ require_once("provisioning/provisioning_soap_library.phtml");
require("soap_engines.inc");
$this->soapEngines = $soapEngines;
if (!in_array($SoapEngineId,array_keys($this->soapEngines))) {
print "Error: SoapEngineId '$SoapEngineId' does not exist.\n";
return false;
}
$this->SOAPurl = $this->soapEngines[$SoapEngineId]['url'];
$this->PresencePort = new WebService_SoapSIMPLEProxy_PresencePort($this->SOAPurl);
$this->PresencePort->setOpt('curl', CURLOPT_SSL_VERIFYPEER, 0);
$this->PresencePort->setOpt('curl', CURLOPT_SSL_VERIFYHOST, 0);
$this->PresencePort->setOpt('curl', CURLOPT_TIMEOUT, 1);
$this->SOAPloginPresence = array(
"username" => $this->soapEngines[$SoapEngineId]['username'],
"password" => $this->soapEngines[$SoapEngineId]['password'],
"admin" => true
);
$this->SoapAuthPresence = array('auth', $this->SOAPloginPresence, 'urn:AGProjects:PresenceEngine', 0, '');
$allowed_activities=array('open',
'idle',
'busy',
'available'
);
if (in_array($activity,$allowed_activities)) {
$presentity['activity'] = $activity;
} else {
$presentity['activity'] = 'open';
}
$presentity['note'] = $note;
$this->PresencePort->addHeader($this->SoapAuthPresence);
$result = $this->PresencePort->setPresenceInformation(array("username" =>$SIPaccount['username'],"domain" =>$SIPaccount['domain']),$SIPaccount['password'], $presentity);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
printf ("<p><font color=red>Error: %s (%s): %s</font>",$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
return false;
}
return true;
}
}
?>

File Metadata

Mime Type
text/x-diff
Expires
Sat, Feb 1, 12:37 PM (1 d, 8 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3489338
Default Alt Text
(435 KB)

Event Timeline