Page MenuHomePhabricator

No OneTemporary

diff --git a/bootstrap/js-used/application.js b/bootstrap/js-used/application.js
index 4c70eed..cbc45c6 100644
--- a/bootstrap/js-used/application.js
+++ b/bootstrap/js-used/application.js
@@ -1,179 +1,180 @@
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT
// IT'S ALL JUST JUNK FOR OUR DOCS!
// ++++++++++++++++++++++++++++++++++++++++++
!function ($) {
$(function(){
$('#timepicker1').timepicker();
$('#timepicker2').timepicker();
$('#begin_date').datepicker();
$('#end_date').datepicker();
$('tr[rel=tooltip]').tooltip()
$('.tooltip-test').tooltip()
$('.popover-test').popover()
// popover demo
$("select[rel=popover]")
.popover()
.click(function(e) {
e.preventDefault()
})
$("a[rel=popover]")
.popover()
.click(function(e) {
e.preventDefault()
})
$("button[rel=popover]")
.popover();
$("input[rel=popover]")
.popover()
.click(function(e) {
e.preventDefault()
})
// request built javascript
$('.download-btn').on('click', function () {
var css = $("#components.download input:checked")
.map(function () { return this.value })
.toArray()
, js = $("#plugins.download input:checked")
.map(function () { return this.value })
.toArray()
, vars = {}
, img = ['glyphicons-halflings.png', 'glyphicons-halflings-white.png']
$("#variables.download input")
.each(function () {
$(this).val() && (vars[ $(this).prev().text() ] = $(this).val())
})
$.ajax({
type: 'POST'
, url: /\?dev/.test(window.location) ? 'http://localhost:3000' : 'http://bootstrap.herokuapp.com'
, dataType: 'jsonpi'
, params: {
js: js
, css: css
, vars: vars
, img: img
}
})
})
});
// Modified from the original jsonpi https://github.com/benvinegar/jquery-jsonpi
$.ajaxTransport('jsonpi', function(opts, originalOptions, jqXHR) {
var url = opts.url;
return {
send: function(_, completeCallback) {
var name = 'jQuery_iframe_' + jQuery.now()
, iframe, form
iframe = $('<iframe>')
.attr('name', name)
.appendTo('head')
form = $('<form>')
.attr('method', opts.type) // GET or POST
.attr('action', url)
.attr('target', name)
$.each(opts.params, function(k, v) {
$('<input>')
.attr('type', 'hidden')
.attr('name', k)
.attr('value', typeof v == 'string' ? v : JSON.stringify(v))
.appendTo(form)
})
form.appendTo('body').submit()
}
}
});
Highcharts.theme = {
chart: {
backgroundColor: 'transparent',
plotBackgroundColor: 'transparent',
plotShadow: false,
plotBorderWidth: 0
},
title: {
style: {
color: '#5177bd',
font: 'bold 16px Verdana, Arial,Telex, sans-serif'
}
},
subtitle: {
style: {
color: '#5177bd',
font: 'bold 12px Verdana, Arial,Telex, sans-serif'
}
},
xAxis: {
minorTickInterval: 'auto',
+ //majorTickInterval: '',
lineColor: '#000',
lineWidth: 1,
tickWidth: 1,
tickColor: '#000',
labels: {
style: {
color: '#000',
font: '10px Verdana, Arial,Telex, sans-serif'
}
},
},
yAxis: {
minorTickInterval: 'auto',
lineColor: '#000',
lineWidth: 1,
tickWidth: 1,
tickColor: '#000',
labels: {
style: {
color: '#000',
font: '10px Verdana, Arial,Telex, sans-serif'
}
},
},
legend: {
itemStyle: {
font: '11px Verdana, Arial,Telex, sans-serif',
color: '#333'
},
itemHoverStyle: {
color: '#039'
},
itemHiddenStyle: {
color: 'gray'
}
},
navigation: {
buttonOptions: {
theme: {
stroke: '#e6e6e6'
}
}
}
};
// Apply the theme
var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
}(window.jQuery)
diff --git a/library/provisioning_statistics.php b/library/provisioning_statistics.php
index 5112b17..ad5549d 100644
--- a/library/provisioning_statistics.php
+++ b/library/provisioning_statistics.php
@@ -1,476 +1,503 @@
<?
/*
Copyright (c) 2013 AG Projects
http://ag-projects.com
Author Tijmen de Mes
*/
class ProvisioningStatistics {
// obtain statistics from Database for NGNPro
function getTopRequestsProvisioning($class) {
global $CDRTool;
$number_of_requests=0;
$requests=array();
$requests_ip=array();
$temp=array();
if (!class_exists($class)) return array();
$db = new $class();
-
- $query = "select substring_index(function,':',1) as port,count(*) as number from ngnpro_logs group by port order by number desc limit 0, 5";
+ $start = (float) array_sum(explode(' ',microtime()));
+ $query = "select substring_index(function,':',1) as port, total as number from ngnpro_logs_new_functions group by port order by number desc limit 0, 5";
dprint($query);
if (!$db->query($query)) {
$log = sprintf ("Database error for query %s: %s (%s)",$query,$db->Error,$db->Errno);
print $log;
syslog(LOG_NOTICE, $log);
return array();
}
if (!$db->num_rows()) return array();
$requests['total'] = 0;
while ($db->next_record()) {
$temp[$db->f('port')] = intval($db->f('number'));
$requests['total'] = intval($db->f('number')) + $requests['total'];
}
foreach($temp as $key=> $value) {
- $query = "select count(*)as number, function, substring_index(function,':',1) as port,substring_index(function,':',-1) as method from ngnpro_logs where function like '$key:%' group by function order by number desc limit 0,5 ;";
+ $query = "select total as number, function, substring_index(function,':',1) as port,substring_index(function,':',-1) as method from ngnpro_logs_new_functions where function like '$key:%' group by function order by number desc limit 0,5 ";
dprint("$query");
if (!$db->query($query)) {
$log=sprintf ("Database error for query %s: %s (%s)",$query,$db->Error,$db->Errno);
print $log;
syslog(LOG_NOTICE, $log);
return array();
}
if (!$db->num_rows()) return array();
while ($db->next_record()) {
$requests[$db->f('port')][$db->f('method')] = intval($db->f('number'));
$requests[$db->f('port')]['total'] = $requests[$db->f('port')]['total'] + intval($db->f('number'));
}
- $query ="select count(*) as number, function, substring_index(function,':',1) as port,substring_index(function,':',-1) as method, ip from ngnpro_logs group by ip,function order by number desc";
- dprint("$query");
+ }
+ $end = (float) array_sum(explode(' ',microtime()));
+ dprint("Processing time: ". sprintf("%.4f", ($end-$start))." seconds<br>");
- if (!$db->query($query)) {
- $log = sprintf ("Database error for query %s: %s (%s)",$query,$db->Error,$db->Errno);
- print $log;
- syslog(LOG_NOTICE, $log);
- return array();
- }
+ $start = (float) array_sum(explode(' ',microtime()));
+ $query ="select total as number, function, ip from ngnpro_logs_new_functions group by ip,function order by number desc";
+ dprint("$query");
- if (!$db->num_rows()) return array();
- while ($db->next_record()) {
- $requests_ip[$db->f('port')][$db->f('method')][$db->f('ip')] = intval($db->f('number'));
- }
+ if (!$db->query($query)) {
+ $log = sprintf ("Database error for query %s: %s (%s)",$query,$db->Error,$db->Errno);
+ print $log;
+ syslog(LOG_NOTICE, $log);
+ return array();
}
+ if (!$db->num_rows()) return array();
+ while ($db->next_record()) {
+ list($port,$method) = explode(":", $db->f('function'));
+ $requests_ip[$port][$method][$db->f('ip')] = intval($db->f('number'));
+ }
+
+ $end = (float) array_sum(explode(' ',microtime()));
+ dprint("Processing time for getTopRequestsProvisioningNew: ". sprintf("%.4f", ($end-$start))." seconds");
return array($requests,$requests_ip);
}
function getPeriod($class) {
global $CDRTool;
$temp = array();
if (!class_exists($class)) return array();
$db = new $class();
- $query = "select MIN(date) as min_date,MAX(date) as max_date, count(*) as total from ngnpro_logs";
+ $query = "select MIN(date) as min_date,MAX(date) as max_date, sum(total) as total from ngnpro_logs_new";
dprint($query);
if (!$db->query($query)) {
$log = sprintf ("Database error for query %s: %s (%s)",$query,$db->Error,$db->Errno);
print $log;
syslog(LOG_NOTICE, $log);
return array();
}
if (!$db->num_rows()) return array();
$requests['total']=0;
while ($db->next_record()) {
$temp = array($db->f('min_date'),$db->f('max_date'),$db->f('total'));
}
return $temp;
}
function getCategories($requests) {
$total = $requests['total'];
$port_data= array();
$colors = array(
'#2f7ed8', '#0d233a', '#8bbc21',
'#910000', '#1aadce', '#492970','#f28f43',
'#77a1e5', '#c42525', '#a6c96a'
);
$num=0;
foreach($requests as $key => $value) {
if ($key != 'total'){
$port_data[] = array(
"name" => $key,
"y" => round(($requests[$key]['total']/$total)*100,2),
"color" => $colors[$num],
"id" => "$key"
);
$num++;
}
}
$return=json_encode($port_data);
return $return;
}
function getSecondCategories($requests) {
$total = $requests['total'];
$method_data= array();
foreach($requests as $key => $value) {
if ($key != 'total'){
foreach($value as $key1 => $value1) {
if ($key1 != 'total'){
$method_data[$key][] = array(
"name" => $key1,
"y" => round(($value[$key1]/$total)*100,2),
"parentId" => "$key",
"value" => "$value[$key1]");
}
}
}
}
dprint("<pre>");
dprint_r($method_data);
dprint("</pre>");
$return = json_encode($method_data);
return $return;
}
function printChartDonut($titlex,$titley,$num,$categories, $second_categories,$requests_ip) {
// Create the chart
$requests_ip=json_encode($requests_ip);
$chart = "
<script type=\"text/javascript\">
$(function () {
var colors = Highcharts.getOptions().colors,
methods = [$second_categories];
ports = $categories;
var new_methods = [];
total_data = $requests_ip;
// console.log(total_data['Sip']);
for (var j = 0; j < methods.length; j++) {
// console.log(methods[j]);
num=0;
$.each( methods[j], function( key, value ) {
// console.log( value[0] );
for (var i = 0; i < value.length; i++) {
var brightness = 0.2 - (i / value.length) / 5 ;
name = value[i].name;
new_methods.push ({
name : name,
y : value[i].y,
color : Highcharts.Color(ports[num].color).brighten(brightness).get(),
parentId : value[i].parentId,
});
}
num++;
});
}
new_methods.sort();
$('#sub_container$num').fadeIn();
renderSubPie(new_methods[0].parentId+':'+new_methods[0].name+' by IP', total_data[new_methods[0].parentId][new_methods[0].name]);
// console.log(new_methods);
$('#container$num').highcharts({
chart : {
type : 'pie',
height : 350,
},
title : {
text : '$titlex',
},
plotOptions : {
pie : {
allowPointSelect : true,
shadow : false,
center : ['50%', '50%']
},
series : {
cursor : 'pointer',
point : {
events : {
click : function() {
// console.log(this.selected);
if (total_data[this.parentId] !== undefined) {
if (!this.selected){
$('#sub_container$num').fadeIn();
// console.log(total_data[this.parentId][this.name]);
renderSubPie(this.parentId+':'+this.name+' by IP', total_data[this.parentId][this.name]);
} else {
$('#sub_container$num').fadeOut();
}
} else {
$('#sub_container$num').fadeOut();
}
}
}
}
}
},
tooltip : {
valueSuffix : '%'
},
credits : {
enabled : false
},
series: [{
name : 'Requests',
data : $categories,
size : '60%',
dataLabels : {
formatter : function() {
return this.y > 12 ? this.point.name : null;
},
color : 'white',
distance : -50
}
},{
name : 'Function',
data : new_methods,
size : '80%',
innerSize : '60%',
dataLabels : {
formatter : function() {
// display only if larger than 3
return this.y > 3 ? '<b>'+ this.point.name +'</b><br />'+ this.y +'%' : null;
}
}
}],
});
function renderSubPie(title,data) {
var new_data = [];
var total = 0;
$.each( data, function( key, value ) {
total = total + value;
});
$.each( data, function( key, value ) {
val = (value/total)*100;
new_data.push ({
name : key,
y : val,
});
});
$('#sub_container$num').highcharts({
chart : {
type : 'pie',
height : 350,
},
title : {
text : title,
},
subtitle : {
text : total + ' requests',
},
plotOptions : {
pie : {
shadow : false,
center : ['50%', '50%']
},
},
tooltip : {
formatter : function() {
return '<b>'+ this.point.name +'</b>: '+ Math.round(this.percentage) +' %';
}
},
credits : {
enabled : false
},
series : [{
name : 'Requests',
data : new_data,
size : '80%',
dataLabels : {
formatter : function() {
return this.y > 12 ? '<b>'+ this.point.name +'</b><br/>'+ Math.round(this.percentage) +'%' : null;
},
},
}],
});
}
});
</script>
<div id='container$num' class='span5'></div>
<div class='span1'></div>
<div id='sub_container$num' class='span5 pull-right' style='display:none'></div>";
print $chart;
}
- function getRequestsProvisioning($class) {
+ function getRequestsProvisioning($class,$days) {
global $CDRTool;
$requests = array();
-
+ $period = '300';
if (!class_exists($class)) return array();
$db = new $class();
- $query = "select count(*) as number,date from ngnpro_logs GROUP BY UNIX_TIMESTAMP(date) DIV 300";
+ $query = "select sum(total) as number,date from ngnpro_logs_new GROUP BY UNIX_TIMESTAMP(date) DIV 300";
dprint($query);
if (!$db->query($query)) {
$log = sprintf ("Database error for query %s: %s (%s)",$query,$db->Error,$db->Errno);
print $log;
syslog(LOG_NOTICE, $log);
return array();
}
if (!$db->num_rows()) return array();
while ($db->next_record()) {
- $requests[] = array($db->f('date'),intval($db->f('number')));
+ $requests[] = array($db->f('date'),(intval($db->f('number')))/5);
}
return json_encode($requests);
}
- function getRequestsTime($class) {
+ function getRequestsTime($class, $days) {
global $CDRTool;
$requests = array();
+ $period = '300';
if (!class_exists($class)) return array();
-
+ $start = (float) array_sum(explode(' ',microtime()));
$db = new $class();
- $query = "select count(*) as number, date,sum(execution_time) as total from ngnpro_logs GROUP BY UNIX_TIMESTAMP(date) DIV 300";
+ if ($days <= 10) {
+ $period='600';
+ } else if ($days <= 20) {
+ $period='1200';
+ } else if ($days > 20) {
+ $period='2400';
+ }
+
+ #$query = "select sum(total) as number, date, concat('[',group_concat(data),']') as data from ngnpro_logs_new GROUP BY UNIX_TIMESTAMP(date) DIV 60 order by date";
+ $query = "select sum(total) as number, date, sum(total_time) as data from ngnpro_logs_new GROUP BY UNIX_TIMESTAMP(date) DIV 300 order by date";
dprint($query);
if (!$db->query($query)) {
$log = sprintf ("Database error for query %s: %s (%s)",$query,$db->Error,$db->Errno);
print $log;
syslog(LOG_NOTICE, $log);
return array();
}
if (!$db->num_rows()) return array();
while ($db->next_record()) {
- $requests[] = array($db->f('date'),(floatval($db->f('total'))/intval($db->f('number'))*1000));
+ $total= $db->f('data');
+ $requests[] = array($db->f('date'),($total/intval($db->f('number')))*1000);
}
-
+ $end = (float) array_sum(explode(' ',microtime()));
+ dprint("<br>Processing time for getRequestsTime: ". sprintf("%.4f", ($end-$start))." seconds<br>");
+ // echo "<pre>";
+ // print_r($requests);
+ // echo "</pre>";
return json_encode($requests);
}
function printChartLine($num,$requests,$requests_time) {
+ $num=$num+1;
$chart = "
<script type=\"text/javascript\">
$(function () {
var requests = $requests;
for (var j = 0; j < requests.length; j++) {
var t = requests[j][0].split(/[- :]/);
requests[j][0] = Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
- requests[j][1] = requests[j][1]/5;
+ //requests[j][1] = requests[j][1]/5;
}
var request_time = $requests_time;
for (var j = 0; j < request_time.length; j++) {
var t = request_time[j][0].split(/[- :]/);
request_time[j][0] = Date.UTC(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
}
- //console.log(requests);
+ console.log(requests);
$('#container_line$num').highcharts({
chart : {
type : 'spline',
zoomType : 'x',
height : 280,
+ marginRight: 80
},
credits : {
enabled : false
},
title : {
text : 'Provisioning requests - Average execution time',
},
xAxis : {
type : 'datetime',
title : {
text : null
},
minRange : 3600000,
+ endOnTick: true,
},
plotOptions : {
spline : {
marker : {
enabled: false
},
lineWidth : 1,
shadow : false,
states : {
hover : {
lineWidth : 1
}
},
threshold : null
}
},
yAxis : [{
title : {
text : 'Requests'
},
},{
title : {
text : 'Execution time (ms)'
},
opposite : true
}],
series: [{
name: 'Requests per minute',
data: requests
- },{
+ }
+ ,{
name: 'Average execution time',
data: request_time,
color: '#8A0808',
yAxis: 1,
- }],
+ }
+ ],
});
});
</script>
<div style='float:left; width: 100%;'>
<div id='container_line$num' class='span12' style='width: 75%; margin-left: auto; display:table ;margin-right: auto; text-align:center;float:none;'></div>";
print $chart;
}
}
?>
diff --git a/phplib/local.inc b/phplib/local.inc
index c99108e..ac412fc 100644
--- a/phplib/local.inc
+++ b/phplib/local.inc
@@ -1,1600 +1,1600 @@
<?php
class CDRTool_CT_Sql extends CT_Sql
{
public $database_class = "DB_CDRTool"; ## Which database to connect...
public $database_table = "active_sessions"; ## and find our session data in this table.
}
class CDRTool_Session extends Session
{
public $classname = "CDRTool_Session";
public $auto_init = "setup.inc";
public $cookiename = "CDRc"; ## defaults to classname
public $magic = "bzssdgaune"; ## ID seed
public $mode = "cookie"; ## We propagate session IDs with cookies
public $fallback_mode = "get";
public $allowcache = "no";
public $allowcache_expires = "5";
public $lifetime = 0; ## 0 = do session cookies, else minutes
public $that_class = "CDRTool_CT_Sql"; ## name of data storage container
public $gc_probability = 5;
}
class CDRTool_User extends User
{
public $classname = "CDRTool_User";
public $magic = "Abraacdascadabra"; ## ID seed
public $that_class = "CDRTool_CT_Sql"; ## data storage container
}
class CDRTool_Auth extends Auth
{
public $classname = "CDRTool_Auth";
public $lifetime = 240;
public $database_class = "DB_CDRTool";
public $database_table = "auth_user";
function auth_loginform()
{
global $sess;
global $_PHPLIB;
global $max_login_attempts;
global $CDRTool;
$username = $_POST["username"];
$sendotp = $_POST["sendotp"];
$password = $_POST["password"];
$challenge = $_POST["challenge"];
$response = $_POST["response"];
$max_login_attempts=5;
$sess->register("challenge");
if (!$challenge) {
$challenge = md5(uniqid($this->magic));
}
$query=sprintf("select * from spam where ip = '%s'", addslashes($_SERVER['REMOTE_ADDR']));
$this->db->query($query);
if ($this->db->num_rows()) {
$this->db->next_record();
$spam_login_ip = $this->db->f('ip');
$spam_login_tries = $this->db->f('tries');
$spam_login_stamp = $this->db->f('stamp');
$next_try = $spam_login_stamp+120;
$remains = $next_try-time();
$next_try = Date("Y-m-d H:i:s", $next_try);
$now = Date("Y-m-d H:i:s", time());
}
if ($remains < 0) {
$query=sprintf("delete from spam where ip = '%s'", addslashes($spam_login_ip));
if ($this->db->query($query)) {
unset($spam_login_tries);
}
}
if ($spam_login_tries < $max_login_attempts) {
$title="Login";
if (is_readable("/etc/cdrtool/local/header.phtml")) {
include("/etc/cdrtool/local/header.phtml");
} else {
include("$CDRTool[Path]/header.phtml");
}
$layout = new pageLayoutLocal();
$layout->showLoginForm($this);
$layout->showFooter();
} else {
if ($spam_login_tries == $max_login_attempts) {
$log_time=Date("Y-m-d H:i:s", time());
$log_query=sprintf(
"insert into log (date,login,ip,description,results) values ('%s','%s','%s','%s attempts to wrong login', 'IP blocked until %s')",
addslashes($log_time),
addslashes($username),
addslashes($_SERVER['REMOTE_ADDR']),
addslashes($spam_login_tries),
addslashes($next_try)
);
$this->db->query($log_query);
}
$new_stamp=time();
$query=sprintf(
"update spam set tries = tries + 1 where ip = '%s' ",
addslashes($_SERVER['REMOTE_ADDR'])
);
$this->db->query($query);
print "
<html>
<body>
<p>The current time on this system is $now.</p>
<p>Too many wrong attempts to login, wait until $next_try (over $remains seconds) and try again.</p>
<p>If you forgot your password please contact your system administrator for obtaining a new one.</p>
</body>
</html>
";
exit;
}
}
function auth_validatelogin()
{
global $d_cli, $d_card, $prepaid_login, $cust_form, $codeFilter, $aNumberFilter,$login_for;
global $CDRTool;
global $otp_error, $otpasswd;
global $verbose;
global $DATASOURCES;
$username = $_POST["username"];
$sendotp = $_POST["sendotp"];
$password = $_POST["password"];
$challenge = $_POST["challenge"];
$response = $_POST["response"];
$response_ha1 = $_POST["response_ha1"];
$REMOTE_ADDR = $_SERVER["REMOTE_ADDR"];
//dprint_r("response: $response");
$otp_yubikey = $_POST["yubikey"];
$yubi_id = substr($otp_yubikey, 0, 12);
$use_yubikey=0;
if (stream_resolve_include_path('Auth/Yubico.php')) {
require_once 'Auth/Yubico.php';
$use_yubikey=1;
} else {
require_once 'PEAR.php';
}
if(isset($username)) {
$this->auth["uname"]=$username; ## This provides access for "loginform.ihtml"
}
$uid = false;
if ($username || $use_yubikey ) {
$username=trim($username);
if (preg_match ("/\@/",$username)) {
$a=explode("@",$username);
$domainAuth = new DomainAuthLocal();
$ret=$domainAuth->validate($a[0], $a[1], $password, $response_ha1, $otp_yubikey);
//dprint("here");
//dprint_r($ret);
if ($ret[0]) {
foreach ($ret[2] as $allowedDS) {
$CDRTool[dataSourcesAllowed][]=$allowedDS;
}
if ($ret[1] == "subscriber") {
$CDRTool[filter][aNumber] = $username;
$this->auth["perm"] = "callsearch,statistics,showPrice,showCallerId";
} else {
$CDRTool[filter][domain] = $a[1];
$this->auth["perm"] = "callsearch,statistics,showPrice,showCallerId";
}
}
return $ret[0];
} else {
$query = sprintf(
"select * from auth_user where (username = '%s' or (yubikey='%s' and yubikey !='')) and expire > NOW()",
addslashes($username),
addslashes($yubi_id)
);
$this->db->query($query);
$this->db->next_record();
$otp_enabled_db = $this->db->f('otp_enable');
$otp_email = $this->db->f('email');
$otp_tel = $this->db->f('tel');
$otp_passwd = $this->db->f('otp_passwd');
$otp_passwd_md5 = md5($this->db->f('otp_passwd'));
if ($sendotp) {
if ($otp_email || $otp_tel) {
$interval="15";
print "<p>Sending OneTimePassword ";
$random_otp = random_passwd_gen();
$expire_otp = date("Y-m-d H:i:s", mktime(date("H"), date("i") + $interval, 0, date("m") ,date("d"), date("Y")));
$update = sprintf(
"UPDATE auth_user SET otp_passwd='%s', otp_expire = '%s' WHERE username = '%s'",
addslashes($random_otp),
addslashes($expire_otp),
addslashes($username)
);
if ($this->db->query($update)) {
if ($otp_email) {
$body=sprintf("%s valid until %s CET (GMT+1) requested from %s", $random_otp, $expire_otp, $_SERVER['REMOTE_ADDR']);
mail($otp_email, "OTP for CDRTool", $body, "From: support@ag-projects.com");
}
if ($otp_tel) {
$body = sprintf("Password is %s valid until %s CET (GMT+1) from %s", $random_otp, $expire_otp, $_SERVER['REMOTE_ADDR']);
$otp_tel=preg_replace("/[^0-9+]/", "", $otp_tel);
otp_sms($otp_tel, $body, "1");
}
print "<p>Password will expire at: $expire_otp (in $interval minutes)</p>";
}
} else {
print "<p>No OTP recipient exists for this account. ";
}
}
$this->db->query(
sprintf(
"SELECT *,UNIX_TIMESTAMP(otp_expire) as timestamp_otp, UNIX_TIMESTAMP() as timestamp_now FROM %s
WHERE (username = '%s' OR (yubikey='%s' AND yubikey != '')) AND expire > NOW()",
addslashes($this->database_table),
addslashes($username),
addslashes($yubi_id)
)
);
$this->db->next_record();
$uid = $this->db->f("user_id");
$perm = $this->db->f("perms");
$yubikey = $this->db->f("yubikey");
$auth_method = $this->db->f("auth_method");
$user_db = $this->db->f("username");
$aclFilter = array();
foreach (explode(" ", $this->db->f("aclFilter")) as $ip) {
$ip = trim($ip);
if ($ip) {
$aclFilter[] = $ip;
}
}
$acl_filter = false;
if ($aclFilter) {
$acl_filter = true;
foreach ($aclFilter as $f) {
if (startsWith($_SERVER['REMOTE_ADDR'], $f)) {
$acl_filter = false;
break;
}
}
}
if ($acl_filter){
$log = sprintf("CDRTool login with username %s using method %s from IP %s denied by ACL", $username, $auth_method, $_SERVER['REMOTE_ADDR']);
syslog(LOG_NOTICE, $log);
return false;
}
if ($CDRTool['provider']['clear_text_passwords'] != 1) {
// Update hashed pass if none set and we need hashed ones
if ($this->db->f("password_hashed") == '' && $this->db->f("password") != '') {
$newpassmd5=md5($this->db->f("password"));
$this->db->query(
sprintf(
"UPDATE %s SET password_hashed='%s', password='' WHERE username='%s'",
addslashes($this->database_table),
addslashes($newpassmd5),
addslashes($username)
)
);
$pass = $newpassmd5;
$pass_md5 = $newpassmd5;
} else {
$pass = $this->db->f("password_hashed");
$pass_md5 = $this->db->f("password_hashed");
}
} else {
$pass = $this->db->f("password");
$pass_md5 = md5($this->db->f("password"));
}
$otp_passwd = $this->db->f("otp_passwd");
if (strlen($this->db->f('otp_passwd'))) {
$otp_passwd_md5 = md5($this->db->f('otp_passwd'));
} else {
$otp_passwd_md5 = "garbage";
}
$timestamp_otp = $this->db->f("timestamp_otp");
$timestamp_now = $this->db->f("timestamp_now");
$CDRTool['loginName'] = $this->db->f("name");
$CDRTool['loginEmail'] = $this->db->f("email");
$_dataSourcesAllowed = explode(",", $this->db->f("sources"));
$_datasourceDefined = array_keys($DATASOURCES);
$CDRTool['dataSourcesAllowed'] = array_intersect($_dataSourcesAllowed, $_datasourceDefined);
// limits per CDRTool login account
$CDRTool['filter']['user_id'] = $this->db->f("user_id");
$CDRTool['filter']['aNumber'] = $this->db->f('aNumberFilter');
$CDRTool['filter']['displayA'] = $this->db->f('display_cli');
$CDRTool['filter']['domain'] = $this->db->f('domainFilter');
$CDRTool['filter']['gateway'] = $this->db->f('gatewayFilter');
$CDRTool['filter']['compid'] = $this->db->f('compidFilter');
$CDRTool['filter']['cscode'] = $this->db->f('cscodeFilter');
if (preg_match("/^(\d+)\.(\d+)$/", $this->db->f('impersonate'), $m)) {
$CDRTool['filter']['customer'] = $m[1];
$CDRTool['filter']['reseller'] = $m[2];
} else if (preg_match("/^(\d+)$/", $this->db->f('impersonate'), $m)) {
$CDRTool['filter']['customer'] = $m[1];
$CDRTool['filter']['reseller'] = $m[1];
} else {
$CDRTool['filter']['customer'] = '';
$CDRTool['filter']['reseller'] = '';
}
$CDRTool['impersonate'] = $this->db->f('impersonate');
if ($this->db->f('afterDateFilter') && $this->db->f('afterDateFilter') != "0000-00-00") {
$CDRTool['filter']['after_date']=$this->db->f('afterDateFilter');
}
if ($CDRTool['filter']['customer']) {
// get soap credentials from NGNPro database
global $soapEngines ;
require_once('SOAP/Client.php');
require("/etc/cdrtool/ngnpro_engines.inc");
require_once("ngnpro_soap_library.php");
$this->SOAPlogin=array(
"username" => $soapEngines[$CDRTool['ngnpro_reseller_engine']]['username'],
"password" => $soapEngines[$CDRTool['ngnpro_reseller_engine']]['password'],
"admin" => true
);
$this->SoapAuth = array('auth', $this->SOAPlogin , 'urn:AGProjects:NGNPro', 0, '');
$this->CustomerPort = new WebService_NGNPro_CustomerPort($soapEngines[$CDRTool['ngnpro_reseller_engine']]['url']);
$this->CustomerPort->setOpt('curl', CURLOPT_TIMEOUT, 5);
$this->CustomerPort->setOpt('curl', CURLOPT_SSL_VERIFYPEER, 0);
$this->CustomerPort->setOpt('curl', CURLOPT_SSL_VERIFYHOST, 0);
$filter = array('customer' => intval($CDRTool['filter']['customer']));
$range = array('start' => 0,'count' => 1);
$orderBy = array('attribute' => 'customer', 'direction' => 'ASC');
$Query=array('filter' => $filter,'orderBy' => $orderBy,'range' => $range);
// Call function
$this->CustomerPort->addHeader($this->SoapAuth);
$result = $this->CustomerPort->getCustomers($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
$log = sprintf(
"SOAP request error from %s: %s (%s): %s",
$this->SoapEngine->SOAPurl,
$error_msg,
$error_fault->detail->exception->errorcode,
$error_fault->detail->exception->errorstring
);
syslog(LOG_NOTICE, $log);
} else {
if (count($result->accounts) == 1) {
if ($result->accounts[0]->impersonate) {
// get the credentials of the impersonate field
$filter = array('customer' => intval($result->accounts[0]->impersonate), 'reseller' => intval($result->accounts[0]->reseller));
$range = array('start' => 0,'count' => 1);
$orderBy = array('attribute' => 'customer', 'direction' => 'ASC');
$Query=array('filter' => $filter,'orderBy' => $orderBy,'range' => $range);
// Call function
$this->CustomerPort->addHeader($this->SoapAuth);
$result = $this->CustomerPort->getCustomers($Query);
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
$log = sprintf(
"SOAP request error from %s: %s (%s): %s",
$this->SoapEngine->SOAPurl,
$error_msg,
$error_fault->detail->exception->errorcode,
$error_fault->detail->exception->errorstring
);
syslog(LOG_NOTICE, $log);
} else {
if (count($result->accounts) == 1) {
$CDRTool["soap_username"] = $result->accounts[0]->username;
$CDRTool["soap_password"] = $result->accounts[0]->password;
} else {
print "<p>Error retrieving customer data from the provisioning server, there is no such impersonate id. ";
}
}
} else {
$CDRTool["soap_username"] = $result->accounts[0]->username;
$CDRTool["soap_password"] = $result->accounts[0]->password;
}
} else {
print "<p>Error retrieving customer data from the provisioning server, there is no such customer id. ";
}
}
}
$expected_response = md5("$username:$pass_md5:$challenge");
$expect_otp=md5("$username:$otp_passwd_md5:$challenge");
if ($use_yubikey == 1) {
$yubi = new Auth_Yubico('11334', 'NDSXQN1QpwUvqtR5v5sYbwhPQ70=');
$auth = $yubi->verify($otp_yubikey);
}
//print_r($result);
## True when JS is disabled
if ($response == "") {
if ($CDRTool['provider']['clear_text_passwords']!= 1 ) {
$password=md5($password);
}
if ($password == $pass
|| (!PEAR::isError($auth) && $yubikey == $yubi_id && $username == $user_db && $expected_response == $response && $auth_method=='7')
|| (!PEAR::isError($auth) && $yubikey == $yubi_id && $username == $user_db && $auth_method=='5')
|| (!PEAR::isError($auth) && $auth_method =='4' )
|| ($password == $otp_passwd && $timestamp_otp > $timestamp_now)
) {
$log=sprintf("CDRTool login with username %s using method %s from IP %s", $username, $auth_method, $_SERVER['REMOTE_ADDR']);
syslog(LOG_NOTICE, $log);
if ($this->db->f("yubikey") == '' && $otp_yubikey != '') {
$this->db->query(
sprintf(
"UPDATE %s SET yubikey='%s' WHERE username='%s'",
addslashes($this->database_table),
addslashes($otp_yubikey),
addslashes($username)
)
);
}
$this->auth["perm"] = $perm;
return $uid;
} else {
return false;
}
} else {
## Response is set, JS is enabled
// we check if either otp or normal password match
//print "<p>$response == $expected_response <p>$response == $expect_otp";
if ($expected_response == $response
|| (!PEAR::isError($auth) && $yubikey == $yubi_id && $username == $user_db && $expected_response == $response && $auth_method=='7')
|| (!PEAR::isError($auth) && $yubikey == $yubi_id && $username == $user_db && $auth_method=='5')
|| (!PEAR::isError($auth) && $auth_method =='4' )
|| ($response == $expect_otp && $timestamp_otp > $timestamp_now)
) {
$log=sprintf("CDRTool login with username %s using method %s from IP %s", $username, $auth_method, $_SERVER['REMOTE_ADDR']);
syslog(LOG_NOTICE, $log);
if ($this->db->f("yubikey") == '' && $otp_yubikey != '') {
$this->db->query(
sprintf(
"UPDATE %s SET yubikey='%s' WHERE username='%s'",
addslashes($this->database_table),
addslashes($otp_yubikey),
addslashes($username)
)
);
}
$this->auth["perm"] = $perm;
return $uid;
} else {
return false;
}
}
}
} else {
if ($use_yubikey == 1){
$yubi = new Auth_Yubico('11334', 'NDSXQN1QpwUvqtR5v5sYbwhPQ70=');
$auth = $yubi->verify($otp_yubikey);
$yubi_id = substr($otp_yubikey, 0, 12);
if (!PEAR::isError($auth)) {
$this->db->query(
sprintf(
"SELECT *,UNIX_TIMESTAMP(otp_expire) as timestamp_otp, UNIX_TIMESTAMP() as timestamp_now FROM %s WHERE yubikey = '%s' AND expire > NOW()",
addslashes($this->database_table),
addslashes($yubi_id)
)
);
$this->db->next_record();
$username = $this->db->f("username");
$this->auth["uname"]=$username;
$uid = $this->db->f("user_id");
$perm = $this->db->f("perms");
$auth_method = $this->db->f("auth_method");
$log=sprintf("CDRTool login with username %s using method %s from IP %s", $username, $auth_method, $_SERVER['REMOTE_ADDR']);
syslog(LOG_NOTICE, $log);
$this->auth["perm"] = $perm;
return $uid;
}
}
}
}
}
class CDRTool_Perm extends Perm
{
public $classname = "CDRTool_Perm";
public $permissions = array(
"admin" => 1,
"callsearch" => 2,
"statistics" => 4,
"sqlquery" => 8,
"soapclient" => 16,
"rates" => 32,
"showCallerId" => 64,
"showPrice" => 128,
"provisioning" => 256,
"readonly" => 512
);
function perm_invalid($does_have, $must_have)
{
global $perm, $auth, $sess;
global $_PHPLIB;
include($_PHPLIB["libdir"] . "perminvalid.phtml");
}
}
class SIP_Subscriber_Session extends Session
{
public $classname = "SIP_Subscriber_Session";
public $auto_init = "SIP_setup.inc";
public $cookiename = "SIPCookie2"; ## defaults to classname
public $magic = "3333jhjjjss13"; ## ID seed
public $mode = "cookie"; ## We propagate session IDs with cookies
public $fallback_mode = "get";
public $allowcache = "public";
public $lifetime = 0; ## 0 = do session cookies, else minutes
public $that_class = "CDRTool_CT_Sql"; ## name of data storage container
public $gc_probability = 5;
}
class SIP_Subscriber_Auth extends Auth
{
// use this auth for SIP accounts
public $classname = "SIP_Subscriber_Auth";
public $lifetime = 0;
public $magic = "d66mmmg111dsgzz"; ## Challenge seed
function auth_loginform()
{
global $sess;
global $max_login_attempts;
$username = $_POST["username"];
$password = $_POST["password"];
$challenge = $_POST["challenge"];
$step = $_POST["step"];
$REMOTE_ADDR = $_SERVER["REMOTE_ADDR"];
$yubikey_p = $_POST['yubikey'];
$sess->register("challenge");
if (!$challenge) {
$challenge = md5(uniqid($this->magic));
}
include("sip_login.phtml");
}
function auth_validatelogin()
{
global $SIP;
$username = $_POST["username"];
$password = $_POST["password"];
$challenge = $_POST["challenge"];
$response = $_POST["response"];
$response_ha1= $_POST["response_ha1"];
$yubikey_p = $_POST['yubikey'];
$use_yubikey=0;
if (stream_resolve_include_path('Auth/Yubico.php')) {
require_once 'Auth/Yubico.php';
$use_yubikey=1;
} else {
require_once 'PEAR.php';
}
if (isset($username)) {
$this->auth["uname"]=$username;
}
$a=explode("@", $username);
$domain= $a[1];
if (count($a) !=2) {
return false;
}
global $domainFilters, $resellerFilters, $soapEngines ;
require_once('SOAP/Client.php');
require("/etc/cdrtool/ngnpro_engines.inc");
require_once("ngnpro_soap_library.php");
$SIP['account'] = $username;
if ($domainFilters[$domain]['sip_engine']) {
$SIP['engine'] = $domainFilters[$domain]['sip_engine'];
} else if ($domainFilters['default']['sip_engine']) {
$SIP['engine']=$domainFilters['default']['sip_engine'];
} else {
print "Error: cannot authenticate SIP subscriber, no domainFilter defined in ngnpro_engines.inc";
return false;
}
$this->SOAPlogin=array(
"username" => $soapEngines[$SIP['engine']]['username'],
"password" => $soapEngines[$SIP['engine']]['password'],
"admin" => true
);
$this->SoapAuth = array('auth', $this->SOAPlogin , 'urn:AGProjects:NGNPro', 0, '');
$this->SipPort = new WebService_NGNPro_SipPort($soapEngines[$SIP['engine']]['url']);
$this->SipPort->setOpt('curl', CURLOPT_TIMEOUT, 5);
$this->SipPort->setOpt('curl', CURLOPT_SSL_VERIFYPEER, 0);
$this->SipPort->setOpt('curl', CURLOPT_SSL_VERIFYHOST, 0);
$this->SipPort->addHeader($this->SoapAuth);
$result = $this->SipPort->getAccount(array("username" =>$a[0],"domain" =>$domain));
if (PEAR::isError($result)) {
$error_msg = $result->getMessage();
$error_fault= $result->getFault();
$error_code = $result->getCode();
$log = printf(
"SOAP error from %s (SipPort): %s (%s): %s",
$soapEngines[$SIP['engine']]['url'],
$error_msg,
$error_fault->detail->exception->errorcode,
$error_fault->detail->exception->errorstring
);
syslog(LOG_NOTICE, $log);
return false;
}
//dprint_r($result->properties);
$web_password='';
foreach ($result->properties as $_property) {
if ($_property->name == 'web_password') {
$web_password=$_property->value;
break;
}
if ($_property->name == 'yubikey') {
$yubikey=$_property->value;
break;
}
}
if (!$web_password) $web_password=$result->password;
$pass_md5 = md5($web_password);
$expected_response = md5("$username:$pass_md5:$challenge");
$SIP['customer'] = $result->customer;
$SIP['reseller'] = $result->reseller;
$parts=explode(':', $pass_md5);
dprint_r($result);
dprint($expected_response);
dprint($parts['0']);
if ($result->ha1 && $result->ha1 == $response_ha1) {
$log=sprintf("SIP settings page: %s logged in from %s", $username, $_SERVER['REMOTE_ADDR']);
syslog(LOG_NOTICE, $log);
return true;
}
if ($use_yubikey == 1) {
$yubi = new Auth_Yubico('11334', 'NDSXQN1QpwUvqtR5v5sYbwhPQ70=');
$auth = $yubi->verify($yubikey_p);
$yubi_id = substr($yubikey_p, 0, 12);
}
if (!PEAR::isError($auth) && $yubikey == $yubi_id && $use_yubikey == 1) {
$log=sprintf("SIP settings page: %s logged in with yubikey from %s", $username, $_SERVER['REMOTE_ADDR']);
syslog(LOG_NOTICE, $log);
return true;
}
if ($pass_md5 && $parts[0] == $response_ha1) {
$log=sprintf("SIP settings page: %s logged in from %s", $username, $_SERVER['REMOTE_ADDR']);
syslog(LOG_NOTICE, $log);
return true;
}
if ($expected_response == $response) {
$log=sprintf("SIP settings page: %s logged in from %s", $username, $_SERVER['REMOTE_ADDR']);
syslog(LOG_NOTICE, $log);
return true;
}
return false;
}
}
function otp_sms($tel,$message,$hideoutput)
{
$tel=preg_replace("/[^0-9]/", "", $tel);
$tel="+".$tel;
$message = substr($message, 0, 135);
if (!$tel || !$message) {
return 0;
}
$cmd="/usr/bin/sms --destination $tel --message \"$message\"";
exec($cmd, $output, $returnCode);
if ($returnCode == "0") {
if (!$hideoutput) {
print "<p>";
printf(_("SMS sent succesfully to %s. "), $tel);
}
} else {
print "<p>";
print "<b>";
print "OTP ";
print _("Error");
}
}
function random_passwd_gen()
{
# Calculating random password
$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");
while($i < 5) {
srand((double)microtime()*1000000);
$randval = rand(0,28);
$random_otp="$random_otp"."$alf[$randval]";
$i++;
}
return $random_otp;
}
function dprint($msg = "")
{
global $verbose;
if ($verbose) {
print "<br>$msg\n";
}
}
function dprint_r($obj)
{
global $verbose;
if ($verbose) {
print "<pre>\n";
print_r($obj);
print "</pre>\n";
}
}
function dprint_sql($sql = "")
{
global $verbose;
require_once('SqlFormatter.php');
if ($verbose) {
echo SqlFormatter::format($sql);
}
}
function checkEmail($email)
{
global $verbose;
dprint("<b>checkEmail($email)</b>");
if (stristr($email, "-.")
|| !preg_match("/^[a-zA-Z0-9][a-zA-Z0-9_.-]*@([a-zA-Z0-9][a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}$/i", $email)
) {
return 0;
}
return 1;
}
class OpenSIPS_DomainAuth
{
function OpenSIPS_DomainAuth ()
{
$this->userDB = new DB_opensips;
$this->allowedDataSourcesSubscriber = array('opensips_radius','sip_trace','media_trace');
}
function validate ($user, $domain, $password)
{
$ha1 = md5($user. ':' . $domain . ':' . $password);
$query = sprintf(
"SELECT * FROM subscriber WHERE username = '%s' AND domain = '%s' AND (password = '%s' or ha1 = '%s') ",
addslashes($user),
addslashes($domain),
addslashes($password),
addslashes($ha1)
);
if ($this->userDB->query($query)) {
$this->userDB->next_record();
$uid = $this->userDB->f('username');
if ($uid) {
return array($uid, "subscriber", $this->allowedDataSourcesSubscriber);
}
}
}
}
class SipThor_DomainAuth
{
function SipThor_DomainAuth ()
{
$this->userDB = new DB_sipthor;
$this->allowedDataSourcesSubscriber = array('sipthor','sip_trace_thor','media_trace_thor');
}
function validate ($user, $domain, $password,$response,$otp_yubikey)
{
$query = sprintf(
"SELECT * FROM sip_accounts WHERE username = '%s' AND domain = '%s'",
addslashes($user),
addslashes($domain)
);
$use_yubikey=0;
if (stream_resolve_include_path('Auth/Yubico.php')) {
require_once 'Auth/Yubico.php';
$use_yubikey=1;
} else {
require_once 'PEAR.php';
}
if ($this->userDB->query($query)) {
$this->userDB->next_record();
$profile = json_decode($this->userDB->f('profile'), 'true');
$check_password = $profile['password'];
$check_password_ha1=$profile['ha1'];
if ($profile['properties']['web_password']) {
$web_pass=$profile['properties']['web_password'];
if (strstr($web_pass, ":")){
$split = explode(":", $web_pass);
//if (preg_match('/^[a-f0-9]{32}$/', split[0])) {
$check_web_password=$split[0];
//}
} else {
$check_web_password = $profile['properties']['web_password'];
}
}
if ($use_yubikey == 1 && $profile['properties']['yubikey']) {
$yubi = new Auth_Yubico('11334', 'NDSXQN1QpwUvqtR5v5sYbwhPQ70=');
$yubikey=$profile['properties']['yubikey'];
$auth = $yubi->verify($otp_yubikey);
$yubi_id = substr($otp_yubikey, 0, 12);
}
$check_password_md5 = md5("$check_password");
$expected_response_pass = md5("$user:$domain:$check_password");
$expected_response_pass_ha1 = md5("$user:$domain:$check_password_ha1");
$expected_response_web = $check_password;
//dprint($expected_response_pass_ha1);
if ($expected_response_pass == $response) {
$uid = $this->userDB->f('username');
if ($uid) {
return array($uid, "subscriber", $this->allowedDataSourcesSubscriber);
}
} else if ($check_password == $password) {
$uid = $this->userDB->f('username');
if ($uid) {
return array($uid, "subscriber", $this->allowedDataSourcesSubscriber);
}
} else if ($expected_response_web == $response) {
$uid = $this->userDB->f('username');
if ($uid) {
return array($uid, "subscriber", $this->allowedDataSourcesSubscriber);
}
} else if ($expected_response_pass_ha1 == $response) {
$uid = $this->userDB->f('username');
if ($uid) {
return array($uid, "subscriber", $this->allowedDataSourcesSubscriber);
}
} else if (!PEAR::isError($auth) && $yubikey == $yubi_id) {
$uid = $this->userDB->f('username');
if ($uid) {
return array($uid, "subscriber", $this->allowedDataSourcesSubscriber);
}
}
}
}
}
class pageLayout
{
function showLoginForm(&$parentAuth)
{
global $username, $otp_error, $CDRTool;
$auth=$parentAuth;
$use_yubikey=0;
if (stream_resolve_include_path('Auth/Yubico.php')) {
require_once 'Auth/Yubico.php';
$use_yubikey=1;
}
$username = $auth->auth["uname"];
print "
<script language=javascript src=md5.js></script>
<script language=javascript>
function doChallengeResponse() {
str = document.login.username.value + \":\" +
MD5(document.login.password.value) + \":\" +
document.login.challenge.value;
document.login.response.value = MD5(str);
items = document.login.username.value.split(\"@\");
if (items.length == 2) {
username = items[0];
domain = items[1];
} else {
username = domain = \"\";
}
str = username + \":\" + domain + \":\" + document.login.password.value;
document.login.response_ha1.value = MD5(str);
//var pass= document.login.password.value;
return false ;
//document.login.submit();
//document.login.password.value = \"\";
}
</script>
";
$url = $auth->url();
print "
<div id=wrapper2>
<br>
";
$this->hasAGProjectslogo=1;
$logo = $CDRTool['tld']."/images/CDRTool.png";
print "<center><a href=http://cdrtool.ag-projects.com target=agprojects><img src=$logo border=0 style='max-width:176px'></a></center><br>";
print "
<form class=form-horizontal style='margin-bottom:0' action=\"$url\" method=post name=login onsubmit='doChallengeResponse();'>
<p>
";
if ($CDRTool[provider][sampleLoginSubscriber]) {
$sampleLoginSubscriber = $CDRTool[provider][sampleLoginSubscriber];
} else {
$sampleLoginSubscriber="account@sip2sip.info";
}
if ($CDRTool[provider][sampleLoginDomain]) {
$sampleLoginDomain = $CDRTool[provider][sampleLoginDomain];
} else {
$sampleLoginDomain="sip2sip.info";
}
$web_username=$auth->auth["uname"];
print "
<div class=control-group>
<label class=control-label>
Username
</label>
<div class=controls>
<input rel='popover'
placeholder='Please identify yourself'
data-original-title='User name types supported'
data-content=' <ul>
<li>Subscriber account<br>(e.g. $sampleLoginSubscriber)</li>
<li>Domain account<br>(e.g. $sampleLoginDomain)</li>
<li>Administrator account
</ul>
'
type=text name=username value=\"$web_username\" size=40 maxlength=255>
</div>
</div>
<div class=control-group>
<label class=control-label>
Password</label>
<div class=controls>
<input type=password name=password size=40 maxlength=32>
</div>
</div>";
//dprint_r($CDRTool);
if ($use_yubikey == 1) {
print "
<div class=control-group>
<label class=control-label>Yubikey</label>
<div class=controls>
<input rel='popover' placeholder='This field is optional' data-trigger='hover' data-delay='1000'
data-original-title='OTP hardware authentication'
data-content=\"With this field you can login using a hardware OTP device called 'yubikey'.<br>
If you login the first time with a CDRTool account and the username, password and OTP key filled in, the key identifier is stored into you account.<br>
For info and purchase of this key see <a href='http://www.yubico.com' target='_blank'>http://www.yubico.com</a>
\" type=text name=yubikey size=40>
</div>
</div>
";
}
print "
<div class='controls'>
<input type=submit name=submitbtn class='btn btn-primary' value=\"Login\">
<input type=\"hidden\" name=\"response_ha1\" value=\"\">
</div>
<br>
";
if (isset($username)) {
if (!$sendotp || $username) {
print "
<p class='alert alert-error'>
Invalid username/password combination. <br>
$otp_error
</p>
";
$spam=new DB_CDRTool;
$query=sprintf("select * from spam where ip = '%s'",addslashes($_SERVER[REMOTE_ADDR]));
$spam->query($query);
if (!$spam->num_rows()) {
$query=sprintf("insert into spam (ip,tries,login,stamp)
values ('%s','1','%s','%s')
",$_SERVER[REMOTE_ADDR],addslashes($username),time());
} else {
$query=sprintf("update spam set
tries = tries +1 where ip = '%s'", addslashes($_SERVER[REMOTE_ADDR]));
}
$spam->query($query);
} else {
print "Please fill in your One Time Password!";
}
}
print "
<div class='p-footer'>
<div class=row-fluid>
<div class=pull-left>
If you make use of <b>O</b>ne <b>T</b>ime <b>P</b>asswords:
<ul class=s>
<li>Fill in your username
<li>Press the Send OTP button
<li>Collect the password
<li>Fill it in the password field
<li>Press the Login Now button to login
</ul></div><div class=pull-right style='height:100px; vertical-align:bottom'>
<input class='btn' type=submit name=sendotp style='position:relative; top:60px;' value=\"Send OTP\">
</div></div></div>
</div>
";
print "<input type=\"hidden\" name=\"response\" value=\"\">";
print "<input type=\"hidden\" name=\"challenge\" value=\"$challenge\">";
print "
</table>
</form>
<script language=JavaScript>
<!--
if (document.login.username.value != '') {
document.login.password.focus();
} else {
document.login.username.focus();
}
// -->
</script>
";
}
function showHeader($title = '')
{
}
function showTopMenu($title = '')
{
global $DATASOURCES, $CDRTool, $cdr_source, $perm;
$version = trim(file_get_contents('version'));
print '
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
';
$now_print = Date("Y-m-d H:i:s", time());
$tz = $CDRTool['provider']['timezone'];
if (is_readable($CDRTool['Path']."/images/logo.gif")) {
printf("<span style='margin-left: -20px; padding: 0px 20px 0px; float:left'><img style=\"height: 35px\" src=\"%s/images/logo.gif\"></span>\n",$CDRTool['tld']);
} else if (is_readable($CDRTool['Path']."/images/logo.jpg")) {
printf("<span style='margin-left: -20px; padding: 0px 20px 0px; float:left'><img style=\"height:35px\" src=\"%s/images/logo.jpg\"></span>\n",$CDRTool['tld']);
} else if (is_readable($CDRTool['Path']."/images/logo.png")) {
printf("<span style='margin-left: -20px; padding: 0px 20px 0px; float:left'><img style=\"height: 35px\" src=\"%s/images/logo.png\"></span>\n",$CDRTool['tld']);
} else {
$this->hasAGProjectslogo=1;
print '<a class="brand" href=http://cdrtool.ag-projects.com target=agprojects>CDRTool</a>';
}
print'
<div id="menu" class="btn-group pull-right">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
<i class="icon-user"></i> ';
print $CDRTool['loginName'];
print '
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>
<a style="font-size: 11px" href="http://cdrtool.ag-projects.com" target=changelog>About v. ';
print "$version";
print ' </a></li>
<li class="divider"></li>
<li><a href=logout.phtml target=_top>Logout</a></li>
</ul>
</div>
<div class="nav-collapse">
<ul class="nav">';
if ($perm->have_perm("callsearch")) {
print "
<li><a href=callsearch.phtml>CDR</a></li>";
}
if ($perm->have_perm("rates")) {
print "
<li><a href=rating_tables.phtml>Rating</a></li>";
print "
<li><a href=rating_tables.phtml?table=prepaid>Prepaid</a></li>";
print "
<li><a href=rating_tables.phtml?table=quota_usage>Quota</a></li>";
}
if ($perm->have_perm("statistics")) {
print "
<li><a href=network_status.phtml>Network</a></li>";
print "
<li><a href=media_sessions.phtml>Sessions</a></li>";
print "
<li><a href=sip_usage.phtml>Usage</a></li>";
}
if ($perm->have_perm("admin")) {
print "<li><a href=mysql_replication_status.phtml>Replication</a></li>";
}
if ($perm->have_perm("provisioning")) {
print "<li><a href=provisioning.phtml>Provisioning</a></li>";
}
print "<li><a href=accounts.phtml>Accounts</a></li>";
print "<li><a href=log.phtml>Logs</a></li>";
print '
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>';
print "<div class='container-fluid' ><div class='main'>";
print "<div class=\"page-header\">";
print "<h1>";
print "$title";
print $DATASOURCES[$cdr_source]['name'];
// Dirty hack
if ($title == 'Provisioning' && $perm->have_perm("provisioning")) {
- print "<div class=pull-right><a class='btn btn-info' href='provisioning_status.phtml'>Usage statistics</a>";
+ print "<div class=pull-right><a class='btn btn-info' href='provisioning_status.phtml'> <i class='icon-bar-chart'></i> Usage statistics</a>";
}
print "</h1></div>";
// print "<table width=100% cellpadding=5 CELLSPACING=0 border=5 align=center>
// <tr>
// ";
// if (is_readable($CDRTool['Path']."/images/logo.gif")) {
// printf ("<td valign=middle><img src=\"%s/images/logo.gif\"></td>",$CDRTool['tld']);
// } else if (is_readable($CDRTool['Path']."/images/logo.jpg")) {
// printf ("<td valign=middle><img src=\"%s/images/logo.jpg\"></td>",$CDRTool['tld']);
// } else if (is_readable($CDRTool['Path']."/images/logo.png")) {
// printf ("<td valign=middle><img src=\"%s/images/logo.png\"></td>",$CDRTool['tld']);
// } else {
// $this->hasAGProjectslogo=1;
// print "<td>";
// printf ("<a href=http://cdrtool.ag-projects.com target=agprojects><img src='%s/images/CDRTool.png' border=0></a>",$CDRTool['tld']);
// print "</td>";
// }
// print "
// <td width=100%>
// <table width=100%>
// </tr>
// <td>";
// print "<h1>$title";
// print " ";
// print $DATASOURCES[$cdr_source]['name'];
// print "</h1><p>";
// print "<td align=right>";
// print "</td></tr>
// </table>
// ";
// print "<table width=100%>
// <tr>
// <td align=left>
// <table border=0 width=100%>
// <tr>
// ";
// if ($perm->have_perm("callsearch")) {
// print " <td class=tab><a href=callsearch.phtml>CDRs</a></td> ";
// }
// if ($perm->have_perm("rates")) {
// print " <td class=tab><a href=rating_tables.phtml>Rating</a></td>";
// print " <td class=tab><a href=rating_tables.phtml?table=prepaid>Prepaid</a></td>";
// print " <td class=tab><a href=rating_tables.phtml?table=quota_usage>Quota</a></td>";
// }
// if ($perm->have_perm("statistics")) {
// print " <td class=tab><a href=network_status.phtml>Network</a></td>";
// print " <td class=tab><a href=media_sessions.phtml>Sessions</a></td>";
// print " <td class=tab><a href=status/usage/index.phtml target=usage>Usage</a></td>";
// }
// if ($perm->have_perm("admin")) {
// print " <td class=tab><a href=mysql_replication_status.phtml>Replication</a></td>";
// }
// if ($perm->have_perm("provisioning")) {
// print " <td class=tab><a href=provisioning.phtml>Provisioning</a></td>";
// }
// print " <td class=tab><a href=accounts.phtml>Accounts</a></td>";
// print " <td class=tab><a href=log.phtml>Logs</a></td>";
// $now_print=Date("Y-m-d H:i:s",time());
// $tz=$CDRTool['provider']['timezone'];
// //print " <td>$now_print | <a href=doc/changelog target=changelog>v. $version</a></td>";
// print " <td><a href=doc/changelog target=changelog>v. $version</a></td>";
// print "
// </tr>
// </table>
// </td>
// <td align=right>
// ";
// printf ("<a href=logout.phtml target=_top><b>Logout %s</b></a>",$CDRTool['loginName']);
// print "
// </tr>
// </table>
// </td>
// </tr>
// </table>
// <p>
//";
}
function showTopMenuSubscriber($title = "")
{
global $DATASOURCES, $CDRTool, $cdr_source, $perm;
$version=trim(file_get_contents(version));
$now_print=Date("Y-m-d H:i:s", time());
$tz=getenv('TZ');
print '
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
';
print "<a class=\"brand\" href=http://cdrtool.ag-projects.com target=agprojects>CDRTool</a>";
print'
<div id="menu" class="btn-group pull-right">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
<i class="icon-user"></i> ';
print $CDRTool['loginName'];
print '
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>
<a style="font-size: 11px" href="http://cdrtool.ag-projects.com" target=changelog>About v. ';
print "$version";
print ' </a></li>
<li class="divider"></li>
<li><a href=logout.phtml target=_top>Logout</a></li>
</ul>
</div>
<div class="nav-collapse">
<ul class="nav">';
if ($perm->have_perm("callsearch")) {
print "
<li><a href=callsearch.phtml>Call detail records</a></li>";
}
print '
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>';
print "<div class='container-fluid' ><div class='main'>";
print "<div class=\"page-header\">";
print "<h1>";
print "$title";
print $DATASOURCES[$cdr_source]['name'];
print "</h1></div>";
}
function showLegalNotice () {
global $loginname, $CDRTool;
$CDRTool_company=$CDRTool[provider][name];
$legalNotice="Legal Notice".
"\n\n".
"This software is intended for the use of $CDRTool_company, ".
"resellers of $CDRTool_company and the customers of $CDRTool_company. ".
"The use of this software by any natural or legal person that does ".
"not belong to $CDRTool_company, its Resellers or is a not a ".
"customer of $CDRTool_company or its resellers is therefore ".
"expressly prohibited.".
"\n\n".
"All the information stored on, and accessible through this software ".
"are personal data protected as such by international and domestic ".
"legislation relating to the processing of personal data and ".
"the protection of the right to privacy. For these reasons: ".
"1. This software shall exclusively be used to the extent that it ".
"is necessary for the provision of services to $CDRTool_company ".
"customers and its resellers; ".
"2. No information displayed on, and accessible through this software ".
"shall be communicated to any natural or legal person outside ".
"$CDRTool_company and its resellers, without prejudice to the ".
"possibility for competent authorities (namely government bodies, ".
"courts, regulatory authorities) to be informed of billing or ".
"traffic data in conformity with the applicable legislation. ".
"\n\n";
$loginName=$CDRTool[loginName];
$this->hasAGProjectslogo=1;
print "
<div id=wrapper2>
<center>
<a href=http://cdrtool.ag-projects.com target=agprojects><img src=images/CDRTool.png style='max-width: 176px' border=0></a>
</center>
<h2 class=page-header>Terms and conditions</h2>
<div class='row-fluid'>
<form class='form-horizontal' action=callsearch.phtml method=post>
<textarea class=span12 name=legal rows=20 cols=60 wrap=virtual readonly=yes>$legalNotice</textarea>
<p>
You are currently logged in as $loginname
<center>
<p>
If you agree with the Terms and Conditions, <br>
press on <b>I agree</b> button to continue.</p>
<input type=submit class=btn value=\"I agree\">
</center>
<input type=hidden name=previous_page value=license_page>
</div>
</form>
</div>
";
}
function showFooter() {
global $CDRTool;
if (!$CDRTool['filter']['aNumber'] && !$this->hasAGProjectslogo) {
$thisYear=date("Y",time());
print "
<p>
<table width=100% border=0 align=center>
<tr>
<td align=right>
<a href=http://cdrtool.ag-projects.com target=agprojects><img src=images/PoweredbyAGProjects.png border=0>
</td>
</tr>
</table>
";
}
}
function showLogout($loginname)
{
print "
<table width=70% align=center>
<td>
<br>
<br>
<h1>Logout</h1>
<p>
You have been logged in as $loginname.</b>
<p>
You have been logged out.
<br>
<br>
<p>
<a href=index.phtml>Login again</a>
</td>
</table>
";
}
}
function unLockTables($dbid)
{
$dbid->query("unlock tables");
}
function changeLanguage($lang = 'en', $domain = 'cdrtool')
{
// run dpkg-reconfigure locales and select support languages .utf8
$lang = languageCodeFor(isset($lang) ? $lang : 'en');
$lang.='.utf8';
setlocale(LC_ALL, $lang);
bindtextdomain($domain, '/var/www/CDRTool/po/locale');
bind_textdomain_codeset($domain, 'UTF-8');
textdomain($domain);
}
// return full language code for given 2 letter language code
function languageCodeFor($lang='en')
{
$lang = isset($lang) ? strtolower($lang) : 'en';
switch ($lang) {
case 'en': return 'en_US'; // this can be C or en_US
case 'ja': return 'ja_JP';
default : return ($lang . '_' . strtoupper($lang));
}
return 'C'; // this will never be reached
}
function RandomString($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;
$string = '';
while($i < $len) {
srand((double)microtime()*1000000);
$randval = rand(0,28);
$string = "$string"."$alf[$randval]";
$i++;
}
return $string;
}
function RandomNumber($len=5,$skipzero=false)
{
$alf=array("1","2","3","4","5",
"9","8","7","6");
if (!$skipzero) $alf[]="0";
$i=0;
while($i < $len) {
srand((double)microtime()*1000000);
$randval = rand(0,9);
$string="$string"."$alf[$randval]";
$i++;
}
return $string;
}
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function sec2hms($duration)
{
// return seconds in HH:MM:SS format
$sum1=$duration;
$duration_print="";
$duration_hour=floor($sum1/3600);
if ($duration_hour > 0) {
$sum1=$sum1-($duration_hour*3600);
$duration_print="$duration_hour:";
}
$duration_min=floor($sum1/60);
if ($duration_min > 0) {
$sum1=$sum1-($duration_min*60);
if ($duration_min < 10) {
$duration_min="0"."$duration_min";
}
$duration_print="$duration_print"."$duration_min:";
} else {
$duration_print="$duration_print"."00:";
}
if ($sum1< 10) {
$duration_sec="0"."$sum1";
} else {
$duration_sec=$sum1;
}
$duration_print="$duration_print"."$duration_sec";
return $duration_print;
}
function get_location($ip)
{
$geo_location=array();
$geo_location['country'] = '';
$geo_location['city'] = '' ;
$geo_location['code'] = '';
$geo_location['region'] = '';
if ($_loc=geoip_record_by_name($ip)) {
if ($_loc['city']) {
$geo_location['city'] = $_loc['city'];
}
$geo_location['country'] = $_loc['country_name'];
$geo_location['code'] = $_loc['country_code'];
$geo_location['region'] = $_loc['region'];
}
return json_encode($geo_location);
}
function startsWith($haystack, $needle, $case=true)
{
if ($case) {
return strpos($haystack, $needle, 0) === 0;
}
return stripos($haystack, $needle, 0) === 0;
}
?>
diff --git a/provisioning_status.phtml b/provisioning_status.phtml
index a8cedf6..07b4a32 100644
--- a/provisioning_status.phtml
+++ b/provisioning_status.phtml
@@ -1,51 +1,58 @@
<?
require("/etc/cdrtool/global.inc");
page_open(
array("sess" => "CDRTool_Session",
"auth" => "CDRTool_Auth",
"perm" => "CDRTool_Perm"
));
require("provisioning_statistics.php");
$perm->check("statistics");
$title="Provisioning usage statistics";
include("header.phtml");
global $CDRTool;
if (strlen($CDRTool['filter']['domain'])) $allowedDomains=explode(' ',$CDRTool['filter']['domain']);
$layout = new pageLayoutLocal();
$layout->showTopMenu($title);
$num=0;
foreach (array_keys($DATASOURCES) as $datasource) {
if ($DATASOURCES[$datasource]['db_ngnpro_stats']) {
$stats= new ProvisioningStatistics();
- list($data,$data1) = $stats->getTopRequestsProvisioning($DATASOURCES[$datasource]['db_ngnpro_stats']);
- $categories = $stats->getCategories($data);
- $second_categories = $stats->getSecondCategories($data);
+ list($datan,$datan1) = $stats->getTopRequestsProvisioning($DATASOURCES[$datasource]['db_ngnpro_stats']);
- $requests = $stats->getRequestsProvisioning($DATASOURCES[$datasource]['db_ngnpro_stats']);
- $requests_time = $stats->getRequestsTime($DATASOURCES[$datasource]['db_ngnpro_stats']);
+ $categories = $stats->getCategories($datan);
+ $second_categories = $stats->getSecondCategories($datan);
$period = $stats->getPeriod($DATASOURCES[$datasource]['db_ngnpro_stats']);
+//flush();
+ $date1 = new DateTime($period[0]);
+ $date2 = new DateTime($period[1]);
+ $interval = $date1->diff($date2);
+
+ $requests_time_new = $stats->getRequestsTime($DATASOURCES[$datasource]['db_ngnpro_stats'],$interval->days);
+ $requests_new = $stats->getRequestsProvisioning($DATASOURCES[$datasource]['db_ngnpro_stats'],$interval->days);
+
print "<div class='alert alert-success'><center>$period[2] requests between ".$period[0]." and ".$period[1]."</center></div>";
print "<div class='row-fluid' style='min-height:350px'>";
- $stats->printChartDonut("Top 5 distribution of request types",'',$num,$categories, $second_categories,$data1);
+ $stats->printChartDonut("Top 5 distribution of request types",'',$num+2,$categories, $second_categories,$datan1);
print "</div>";
print "<div class='row-fluid' style='min-height:280px'>";
- $stats->printChartLine($num,$requests,$requests_time);
+ //$stats->printChartLine($num,$requests,$requests_time);
+ $stats->printChartLine($num,$requests_new,$requests_time_new);
print "</div>";
$num++;
}
}
$layout->showFooter();
page_close();
?>

File Metadata

Mime Type
text/x-diff
Expires
Sat, Dec 28, 4:43 PM (1 d, 3 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3454323
Default Alt Text
(88 KB)

Event Timeline