Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • smradius/smradius
  • centiva-shail/smradius
  • nkukard/smradius
3 results
Show changes
Showing
with 3805 additions and 481 deletions
...@@ -8,7 +8,11 @@ ...@@ -8,7 +8,11 @@
#group= #group=
# Filename to store pid of parent process # Filename to store pid of parent process
#pid_file=/var/run/smradiusd.pid #pid_file=/var/run/smradius/smradiusd.pid
# Cache file
#cache_file=/var/run/smradius/cache
# Uncommenting the below option will prevent awradiusd going into the background # Uncommenting the below option will prevent awradiusd going into the background
#background=no #background=no
...@@ -16,8 +20,8 @@ ...@@ -16,8 +20,8 @@
# Preforking configuration # Preforking configuration
# #
# min_server - Minimum servers to keep around # min_server - Minimum servers to keep around
# min_spare_servers - Minimum spare servers to keep around ready to # min_spare_servers - Minimum spare servers to keep around ready to
# handle requests # handle requests
# max_spare_servers - Maximum spare servers to have around doing nothing # max_spare_servers - Maximum spare servers to have around doing nothing
# max_servers - Maximum servers alltogether # max_servers - Maximum servers alltogether
# max_requests - Maximum number of requests each child will serve # max_requests - Maximum number of requests each child will serve
...@@ -40,14 +44,14 @@ ...@@ -40,14 +44,14 @@
# 1 - Warnings and errors # 1 - Warnings and errors
# 2 - Notices, warnings, errors # 2 - Notices, warnings, errors
# 3 - Info, notices, warnings, errors # 3 - Info, notices, warnings, errors
# 4 - Debugging # 4 - Debugging
#log_level=2 #log_level=2
# File to log to instead of stdout # File to log to instead of stdout
#log_file=/var/log/smradiusd.log #log_file=/var/log/smradiusd.log
# Things to log in extreme detail # Things to log in extreme detail
# modules - Log detailed module running information # modules - Log detailed module running information
# #
# There is no default for this configuration option. Options can be # There is no default for this configuration option. Options can be
# separated by commas. ie. modules # separated by commas. ie. modules
...@@ -61,18 +65,56 @@ ...@@ -61,18 +65,56 @@
#timeout=120 #timeout=120
# cidr_allow/cidr_deny # cidr_allow/cidr_deny
# Comma, whitespace or semi-colon separated. Contains a CIDR block to # Comma, whitespace or semi-colon separated. Contains a CIDR block to
# compare the clients IP to. If cidr_allow or cidr_deny options are # compare the clients IP to. If cidr_allow or cidr_deny options are
# given, the incoming client must match a cidr_allow and not match a # given, the incoming client must match a cidr_allow and not match a
# cidr_deny or the client connection will be closed. # cidr_deny or the client connection will be closed.
#cidr_allow=0.0.0.0/0 #cidr_allow=0.0.0.0/0
#cidr_deny= #cidr_deny=
# Event timestamp timezone, in "Continent/City" format
# Defaults to "GMT"
event_timezone=GMT
# SMTP server to use when sending email
#smtp_server=127.0.0.1
[radius]
# Use packet timestamp, if unset, the default is to use the server
# timestamp at the moment the packet is received.
#
# WARNING!!!!
# Not all routers keep time, it may occur that some routers depend on
# getting date & time apon reboot from an ntp server. The problem
# will arise when the router cannot get the date and time before the
# first user logs in .. BAM, you'll have sessions with a period key
# in current month but an event timestamp in 1970.
#
# Defaults to "no"
#use_packet_timestamp=yes
# Radius server abuse prevention
#
# Abuse prevention will drop packets which flood the radius server,
# or are duplicated in a short timeframe. You probably want this if
# you are not being fed by a radius proxy.
#
# Defaults to "no"
#use_abuse_prevention=yes
# How fast can a NAS spam the same type of request
#
# Access-Request defaults to 10s
#access_request_abuse_threshold=10
#
# Accounting-Request defaults to 5s
#accounting_request_abuse_threshold=5
[database] [database]
#DSN=DBI:SQLite:dbname=sitemanager.sqlite #DSN=DBI:SQLite:dbname=smradius.sqlite
DSN=DBI:mysql:database=sitemanager;host=localhost DSN=DBI:mysql:database=smradius;host=localhost
Username=root Username=root
Password= Password=
...@@ -91,6 +133,7 @@ load=<<EOT ...@@ -91,6 +133,7 @@ load=<<EOT
dicts/dictionary dicts/dictionary
dicts/dictionary.microsoft dicts/dictionary.microsoft
dicts/dictionary.mikrotik dicts/dictionary.mikrotik
dicts/dictionary.wispr
EOT EOT
...@@ -108,151 +151,404 @@ EOT ...@@ -108,151 +151,404 @@ EOT
[system] [system]
plugins=<<EOT modules=<<EOT
mod_config_sql mod_config_sql
mod_config_sql_topups
EOT EOT
[features] [features]
plugins=<<EOT modules=<<EOT
mod_feature_capping mod_feature_capping
mod_feature_validity
mod_feature_fup
mod_feature_user_stats
mod_feature_update_user_stats_sql
EOT EOT
[accounting] [accounting]
plugins=<<EOT modules=<<EOT
mod_accounting_sql mod_accounting_sql
EOT EOT
# MOD_CONFIG_SQL
[mod_config_sql]
get_config_realm_id_query=<<EOT
SELECT
ID
FROM
@TP@realms
WHERE
Name = ?
EOT
get_config_realm_attributes_query=<<EOT
SELECT
Name,
Operator,
Value
FROM
@TP@realm_attributes
WHERE
RealmID = ?
EOT
get_config_accesslist_query=<<EOT
SELECT
@TP@clients.AccessList,
@TP@clients.ID
FROM
@TP@clients,
@TP@clients_to_realms
WHERE
@TP@clients.ID = @TP@clients_to_realms.ClientID
AND @TP@clients_to_realms.RealmID = ?
EOT
get_config_client_attributes_query=<<EOT
SELECT
Name,
Operator,
Value
FROM
@TP@client_attributes
WHERE
ClientID = ?
EOT
# MOD_CONFIG_SQL_TOPUPS
[mod_config_sql_topups]
get_topups_summary_query=<<EOT
SELECT
@TP@topups_summary.Balance,
@TP@topups.Type,
@TP@topups.ID
FROM
@TP@topups_summary,
@TP@topups,
@TP@users
WHERE
@TP@topups.ID = @TP@topups_summary.TopupID
AND @TP@topups.UserID = @TP@users.ID
AND @TP@topups_summary.PeriodKey = ?
AND @TP@topups.Depleted = 0
AND @TP@users.Username = ?
EOT
get_topups_query=<<EOT
SELECT
@TP@topups.ID,
@TP@topups.Type,
@TP@topups.Value
FROM
@TP@topups,
@TP@users
WHERE
@TP@topups.UserID = @TP@users.ID
AND @TP@topups.ValidFrom = ?
AND @TP@topups.ValidTo >= ?
AND @TP@topups.Depleted = 0
AND @TP@users.Username = ?
EOT
topups_add_query=<<EOT
INSERT INTO @TP@topups (
UserID,
Timestamp,
ValidFrom,
ValidTo,
Type,
Value,
Depleted
) VALUES (
%{user.ID},
%{query.Timestamp},
%{query.ValidFrom},
%{query.ValidTo},
%{query.Type},
%{query.Value},
%{query.Depleted}
)
EOT
# MOD_ACCOUNTING_SQL
[mod_accounting_sql] [mod_accounting_sql]
accounting_start_query=<<EOT accounting_start_query=<<EOT
INSERT INTO @TP@accounting INSERT INTO
( @TP@accounting
Username, (
ServiceType, Username,
FramedProtocol, ServiceType,
NASPort, FramedProtocol,
NASPortType, NASPort,
CallingStationID, NASPortType,
CalledStationID, CallingStationID,
NASPortID, CalledStationID,
AcctSessionID, NASPortID,
FramedIPAddress, AcctSessionID,
AcctAuthentic, FramedIPAddress,
EventTimestamp, AcctAuthentic,
AcctStatusType, EventTimestamp,
NASIdentifier, AcctStatusType,
NASIPAddress, NASIdentifier,
AcctDelayTime NASIPAddress,
) AcctDelayTime,
VALUES AcctSessionTime,
( AcctInputOctets,
%{request.User-Name}, AcctInputGigawords,
%{request.Service-Type}, AcctInputPackets,
%{request.Framed-Protocol}, AcctOutputOctets,
%{request.NAS-Port}, AcctOutputGigawords,
%{request.NAS-Port-Type}, AcctOutputPackets,
%{request.Calling-Station-Id}, PeriodKey
%{request.Called-Station-Id}, )
%{request.NAS-Port-Id}, VALUES
%{request.Acct-Session-Id}, (
%{request.Framed-IP-Address}, %{user.Username},
%{request.Acct-Authentic}, %{request.Service-Type},
%{request.Timestamp}, %{request.Framed-Protocol},
%{request.Acct-Status-Type}, %{request.NAS-Port},
%{request.NAS-Identifier}, %{request.NAS-Port-Type},
%{request.NAS-IP-Address}, %{request.Calling-Station-Id},
%{request.Acct-Delay-Time} %{request.Called-Station-Id},
) %{request.NAS-Port-Id},
%{request.Acct-Session-Id},
%{request.Framed-IP-Address},
%{request.Acct-Authentic},
%{request.Timestamp},
%{request.Acct-Status-Type},
%{request.NAS-Identifier},
%{request.NAS-IP-Address},
%{request.Acct-Delay-Time},
%{request.Acct-Session-Time},
%{request.Acct-Input-Octets},
%{request.Acct-Input-Gigawords},
%{request.Acct-Input-Packets},
%{request.Acct-Output-Octets},
%{request.Acct-Output-Gigawords},
%{request.Acct-Output-Packets},
%{query.PeriodKey}
)
EOT
accounting_update_get_records_query=<<EOT
SELECT
SUM(AcctInputOctets) AS AcctInputOctets,
SUM(AcctInputPackets) AS AcctInputPackets,
SUM(AcctOutputOctets) AS AcctOutputOctets,
SUM(AcctOutputPackets) AS AcctOutputPackets,
SUM(AcctInputGigawords) AS AcctInputGigawords,
SUM(AcctOutputGigawords) AS AcctOutputGigawords,
SUM(AcctSessionTime) AS AcctSessionTime,
PeriodKey
FROM
@TP@accounting
WHERE
Username = %{user.Username}
AND AcctSessionID = %{request.Acct-Session-Id}
AND NASIPAddress = %{request.NAS-IP-Address}
AND NASPort = %{request.NAS-Port}
GROUP BY
PeriodKey
ORDER BY
ID ASC
EOT EOT
accounting_update_query=<<EOT accounting_update_query=<<EOT
UPDATE @TP@accounting UPDATE
SET @TP@accounting
AcctSessionTime = %{request.Acct-Session-Time}, SET
AcctInputOctets = %{request.Acct-Input-Octets}, AcctSessionTime = %{query.Acct-Session-Time},
AcctInputGigawords = %{request.Acct-Input-Gigawords}, AcctInputOctets = %{query.Acct-Input-Octets},
AcctInputPackets = %{request.Acct-Input-Packets}, AcctInputGigawords = %{query.Acct-Input-Gigawords},
AcctOutputOctets = %{request.Acct-Output-Octets}, AcctInputPackets = %{query.Acct-Input-Packets},
AcctOutputGigawords = %{request.Acct-Output-Gigawords}, AcctOutputOctets = %{query.Acct-Output-Octets},
AcctOutputPackets = %{request.Acct-Output-Packets}, AcctOutputGigawords = %{query.Acct-Output-Gigawords},
AcctStatusType = %{request.Acct-Status-Type} AcctOutputPackets = %{query.Acct-Output-Packets},
WHERE AcctStatusType = %{request.Acct-Status-Type}
UserName = %{request.User-Name} WHERE
AND AcctSessionID = %{request.Acct-Session-Id} Username = %{user.Username}
AND NASIPAddress = %{request.NAS-IP-Address} AND AcctSessionID = %{request.Acct-Session-Id}
AND NASIPAddress = %{request.NAS-IP-Address}
AND NASPort = %{request.NAS-Port}
AND PeriodKey = %{query.PeriodKey}
EOT EOT
accounting_stop_query=<<EOT accounting_stop_status_query=<<EOT
UPDATE @TP@accounting UPDATE
SET @TP@accounting
AcctSessionTime = %{request.Acct-Session-Time}, SET
AcctInputOctets = %{request.Acct-Input-Octets}, AcctStatusType = %{request.Acct-Status-Type},
AcctInputGigawords = %{request.Acct-Input-Gigawords}, AcctTerminateCause = %{request.Acct-Terminate-Cause}
AcctInputPackets = %{request.Acct-Input-Packets}, WHERE
AcctOutputOctets = %{request.Acct-Output-Octets}, Username = %{user.Username}
AcctOutputGigawords = %{request.Acct-Output-Gigawords}, AND AcctSessionID = %{request.Acct-Session-Id}
AcctOutputPackets = %{request.Acct-Output-Packets}, AND NASIPAddress = %{request.NAS-IP-Address}
AcctStatusType = %{request.Acct-Status-Type}, AND NASPort = %{request.NAS-Port}
AcctTerminateCause = %{request.Acct-Terminate-Cause}
WHERE
UserName = %{request.User-Name}
AND AcctSessionID = %{request.Acct-Session-Id}
AND NASIPAddress = %{request.NAS-IP-Address}
EOT EOT
accounting_usage_query=<<EOT accounting_usage_query=<<EOT
SELECT SELECT
SUM(AcctInputOctets) AS InputOctets, SUM(AcctInputOctets) AS AcctInputOctets,
SUM(AcctOutputOctets) AS OutputOctets, SUM(AcctOutputOctets) AS AcctOutputOctets,
SUM(AcctInputGigawords) AS InputGigawords, SUM(AcctInputGigawords) AS AcctInputGigawords,
SUM(AcctOutputGigawords) AS OutputGigawords, SUM(AcctOutputGigawords) AS AcctOutputGigawords,
SUM(AcctSessionTime) AS SessionTime SUM(AcctSessionTime) AS AcctSessionTime
FROM FROM
@TP@accounting @TP@accounting
WHERE WHERE
Username = %{request.User-Name} Username = %{user.Username}
AND PeriodKey = %{query.PeriodKey}
EOT EOT
accounting_select_duplicates_query=<<EOT
SELECT
ID
FROM
@TP@accounting
WHERE
Username = %{user.Username}
AND AcctSessionID = %{request.Acct-Session-Id}
AND NASIPAddress = %{request.NAS-IP-Address}
AND NASPort = %{request.NAS-Port}
AND PeriodKey = %{query.PeriodKey}
ORDER BY
ID DESC
LIMIT 99 OFFSET 1
EOT
accounting_delete_duplicates_query=<<EOT
DELETE FROM
@TP@accounting
WHERE
ID = %{query.DuplicateID}
EOT
# This is how long we going to cache the usage query for
# Default: 300 (seconds)
#
# You can use "no", "0", "false" to disable, specify a number > 1, or use
# "yes", "1", "true" to enable with the default value
accounting_usage_cache_time=300
# MOD_USERDB_SQL
[mod_userdb_sql] [mod_userdb_sql]
userdb_find_query=<<EOT userdb_find_query=<<EOT
SELECT SELECT
ID ID, Disabled
FROM FROM
@TP@users @TP@users
WHERE WHERE
UserName = %{request.User-Name} Username = %{user.Username}
EOT EOT
userdb_get_group_attributes_query=<<EOT userdb_get_group_attributes_query=<<EOT
SELECT SELECT
group_attributes.Name, group_attributes.Operator, group_attributes.Value group_attributes.Name, group_attributes.Operator, group_attributes.Value
FROM FROM
@TP@group_attributes, @TP@users_to_groups @TP@group_attributes, @TP@users_to_groups
WHERE WHERE
users_to_groups.UserID = %{userdb.id} users_to_groups.UserID = %{user.ID}
AND group_attributes.GroupID = users_to_groups.GroupID AND group_attributes.GroupID = users_to_groups.GroupID
AND group_attributes.Disabled = 0
EOT EOT
userdb_get_user_attributes_query=<<EOT userdb_get_user_attributes_query=<<EOT
SELECT SELECT
Name, Operator, Value Name, Operator, Value
FROM FROM
@TP@user_attributes @TP@user_attributes
WHERE WHERE
UserID = %{userdb.id} UserID = %{user.ID}
AND Disabled = 0
EOT EOT
users_data_set_query=<<EOT
INSERT INTO
@TP@users_data (UserID, LastUpdated, Name, Value)
VALUES
(
%{user.ID},
%{query.LastUpdated},
%{query.Name},
%{query.Value}
)
EOT
users_data_update_query=<<EOT
UPDATE
@TP@users_data
SET
LastUpdated = %{query.LastUpdated},
Value = %{query.Value}
WHERE
UserID = %{user.ID}
AND Name = %{query.Name}
EOT
users_data_get_query=<<EOT
SELECT
LastUpdated, Name, Value
FROM
@TP@users_data
WHERE
UserID = %{user.ID}
AND Name = %{query.Name}
EOT
users_data_delete_query=<<EOT
DELETE FROM
@TP@users_data
WHERE
UserID = %{user.ID}
AND Name = %{query.Name}
EOT
# This is how long we going to cache the data query for
# Default: 300 (seconds)
#
# You can use "no", "0", "false" to disable, specify a number > 1, or use
# "yes", "1", "true" to enable with the default value
userdb_data_cache_time=300
# MOD_FEATURE_UPDATE_USER_STATS_SQL
[mod_feature_update_user_stats_sql]
update_user_stats_query=<<EOT
UPDATE
@TP@users
SET
PeriodKey = %{query.PeriodKey},
TotalTraffic = %{query.TotalTraffic},
TotalUptime = %{query.TotalUptime},
NASIdentifier = %{request.NAS-Identifier},
LastAcctUpdate = now()
WHERE
Username = %{user.Username}
EOT
# MOD_FEATURE_CAPPING
[mod_feature_capping]
# Enable Mikrotik-specific return vattributes
#enable_mikrotik=1
# Enable caveat for SMRadius-Capping-Traffic-Limit having the meaning of 0 and -undef- swapped up to v1.0.x
#caveat_captrafzero=1
<?php # Test harness for module loading
# Tool Tip Data # Copyright (C) 2014-2016, AllWorldIT
# Copyright (C) 2007-2009, AllWorldIT #
#
# This program is free software; you can redistribute it and/or modify # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or # the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
# #
# You should have received a copy of the GNU General Public License along # You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc., # with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
$tooltips['user_attributes_name'] = "Please refer to the manual for a list of allowed attribute names";
?>
use Test::More;
use strict;
use warnings;
require_ok("smradius::daemon");
require_ok("smradius::client");
done_testing();
use strict;
use warnings;
use AWITPT::Util;
use Data::Dumper;
use Date::Parse;
use POSIX qw(:sys_wait_h);
use Test::Most;
use Test::Most::Exception 'throw_failure';
#
# Check that database tests are enabled
#
# We need DBTESTS enabled to run this
if (!$ENV{'DBTESTS'}) {
plan skip_all => 'DBTESTS not set in ENV';
done_testing();
exit 0;
}
#
# Load database handling libraries
#
require_ok('AWITPT::DB::DBILayer');
require_ok('AWITPT::DB::DBLayer');
use AWITPT::DB::DBLayer;
#
# Load our server and client
#
require_ok("smradius::daemon");
require_ok("smradius::client");
#
# Daemon help
#
can_ok("smradius::daemon","displayHelp");
#
# Try connect to database
#
my $dbh = AWITPT::DB::DBILayer->new({
'Username' => 'root',
'DSN' => 'DBI:mysql:database=smradiustest;host=localhost',
});
# If we cannot connect, just bail out
if ($dbh->connect()) {
BAIL_OUT("ERROR: Failed to connect to database for testing purposes: ".$dbh->error());
}
AWITPT::DB::DBLayer::setHandle($dbh);
#
# Make sure DB is clean
#
my $sth;
$sth = DBDo("DELETE FROM topups");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'topups");
$sth = DBDo("DELETE FROM accounting");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'accounting");
$sth = DBDo("DELETE FROM user_attributes");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'user_attributes");
$sth = DBDo("DELETE FROM client_attributes");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'client_attributes");
$sth = DBDo("DELETE FROM users");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'users'");
$sth = DBDo("DELETE FROM clients_to_realms");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'clients_to_realms'");
$sth = DBDo("DELETE FROM clients");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'clients'");
$sth = DBDo("DELETE FROM realms");
is(AWITPT::DB::DBLayer::error(),"","Clean table 'realms'");
#
# Run server and client
#
our $child;
if ($child = fork()) {
# CHLD handler
local $SIG{CHLD} = sub {
warn "SIGCHLD TRIGGER";
waitpid($child,-1);
};
# Install signal handlers to cleanup if we get a TERM or INT
local $SIG{TERM} = local $SIG{INT} = \&cleanup;
# Wait before starting
sleep(2);
# Setup failure handler
set_failure_handler( sub { my @params = @_; cleanup(); throw_failure } );
my $res;
#
# Make sure basic test without any config does not authenticate users
#
$res = smradius::client->run(
"--raddb","dicts",
"127.0.0.1",
"auth",
"secret123",
'User-Name=testuser1',
'User-Password=test123',
);
is(ref($res),"","smradclient ref should return ''");
is($res,1,"smradclient result should be 1");
#
# Create test case data
#
my $client1_ID = testDBInsert("Create client 'localhost'",
"INSERT INTO clients (Name,AccessList,Disabled) VALUES ('localhost','127.0.0.0/8',0)"
);
my $client1attr1_ID = testDBInsert("Create client 'localhost' secret",
"INSERT INTO client_attributes (ClientID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$client1_ID,'SMRadius-Config-Secret',':=','secret123'
);
# Blank realm
my $realm1_ID = testDBInsert("Create realm ''",
"INSERT INTO realms (Name,Disabled) VALUES ('',0)"
);
my $clientTOrealm1_ID = testDBInsert("Link client 'localhost' to realm ''",
"INSERT INTO clients_to_realms (ClientID,RealmID,Disabled) VALUES (?,?,0)",$client1_ID,$realm1_ID
);
#
# Check we get an Access-Accept for a bare user using a blank realm
#
my $user1_ID = testDBInsert("Create user 'testuser1'",
"INSERT INTO users (UserName,Disabled) VALUES ('testuser1',0)"
);
my $user1attr1_ID = testDBInsert("Create user 'testuser1' attribute 'User-Password'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user1_ID,'User-Password','==','test123'
);
my $user1attr2_ID = testDBInsert("Create user 'testuser1' attribute 'Framed-IP-Address'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user1_ID,'Framed-IP-Address',':=','10.0.0.1'
);
my $user1attr3_ID = testDBInsert("Create user 'testuser1' vendor attribute '[14988:Mikrotik-Rate-Limit]'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user1_ID,'[14988:Mikrotik-Rate-Limit]',':=','1024k/512k'
);
$res = smradius::client->run(
"--raddb","dicts",
"127.0.0.1",
"auth",
"secret123",
'User-Name=testuser1',
'User-Password=test123',
);
is(ref($res),"HASH","smradclient should return a HASH");
is($res->{'response'}->{'code'},"Access-Accept","Check our return is 'Access-Accept' for bare user blank '' realm");
# Test the normal attribute and vendor attribute
is($res->{'response'}->{'attributes'}->{'Framed-IP-Address'},"10.0.0.1","Check that attribute 'Framed-IP-Address' is".
" returned");
is($res->{'response'}->{'vattributes'}->{'14988'}->{'Mikrotik-Rate-Limit'}->[0],"1024k/512k","Check that the vendor attribute".
"'14988:Mikrotik-Rate-Limit' is returned");
# Add filter attributes
my $user1attr4_ID = testDBInsert("Create user 'testuser1' filter attribute for 'Framed-IP-Address'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user1_ID,'SMRadius-Config-Filter-Reply-Attribute',':=','Framed-IP-Address'
);
my $user1attr5_ID = testDBInsert("Create user 'testuser1' filter vattribute for 'Mikrotik-Rate-Limit'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user1_ID,'SMRadius-Config-Filter-Reply-VAttribute',':=','Mikrotik-Rate-Limit'
);
$res = smradius::client->run(
"--raddb","dicts",
"127.0.0.1",
"auth",
"secret123",
'User-Name=testuser1',
'User-Password=test123',
);
is(ref($res),"HASH","smradclient should return a HASH");
# We shouldn't....
isnt($res->{'response'}->{'attributes'}->{'Framed-IP-Address'},"10.0.0.1","Check that attribute 'Framed-IP-Address' is".
" returned");
#
# Modify data for the default realm
#
testDBDelete("Delete blank realm '' link to client",
"DELETE FROM clients_to_realms WHERE ID = ?",$clientTOrealm1_ID
);
testDBDelete("Delete blank realm '' for realm '<DEFAULT>' test",
"DELETE FROM realms WHERE ID = ?",$realm1_ID
);
my $realm1b_ID = testDBInsert("Create default realm '<DEFAULT>'",
"INSERT INTO realms (Name,Disabled) VALUES ('<DEFAULT>',0)"
);
my $clientTOrealm1b_ID = testDBInsert("Link client 'localhost' to realm '<DEFAULT>'",
"INSERT INTO clients_to_realms (ClientID,RealmID,Disabled) VALUES (?,?,0)",$client1_ID,$realm1b_ID
);
#
# Check we get an Access-Accept for a bare user using the default realm
#
$res = smradius::client->run(
"--raddb","dicts",
"127.0.0.1",
"auth",
"secret123",
'User-Name=testuser1',
'User-Password=test123',
);
is(ref($res),"HASH","smradclient should return a HASH");
is($res->{'response'}->{'code'},"Access-Accept","Check our return is 'Access-Accept' for bare user on <DEFAULT> realm");
#
# Check we get a Access-Reject for a traffic topup user
#
my $user2_ID = testDBInsert("Create user 'testuser2'",
"INSERT INTO users (UserName,Disabled) VALUES ('testuser2',0)"
);
my $user2attr1_ID = testDBInsert("Create user 'testuser2' attribute 'User-Password'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user2_ID,'User-Password','==','test123'
);
my $user2attr2_ID = testDBInsert("Create user 'testuser2' attribute 'SMRadius-Capping-Traffic-Limit'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user2_ID,'SMRadius-Capping-Traffic-Limit',':=','0'
);
$res = smradius::client->run(
"--raddb","dicts",
"127.0.0.1",
"auth",
"secret123",
'User-Name=testuser2',
'User-Password=test123',
);
is(ref($res),"HASH","smradclient should return a HASH");
is($res->{'response'}->{'code'},"Access-Reject","Check our return is 'Access-Reject' for a traffic topup user");
#
# Check we get a Access-Reject for a uptime topup user
#
my $user2b_ID = testDBInsert("Create user 'testuser2b'",
"INSERT INTO users (UserName,Disabled) VALUES ('testuser2b',0)"
);
my $user2battr1_ID = testDBInsert("Create user 'testuser2b' attribute 'User-Password'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user2b_ID,'User-Password','==','test123'
);
my $user2battr3_ID = testDBInsert("Create user 'testuser2b' attribute 'SMRadius-Capping-Uptime-Limit'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user2b_ID,'SMRadius-Capping-Uptime-Limit',':=','0'
);
$res = smradius::client->run(
"--raddb","dicts",
"127.0.0.1",
"auth",
"secret123",
'User-Name=testuser2b',
'User-Password=test123',
);
is(ref($res),"HASH","smradclient should return a HASH");
is($res->{'response'}->{'code'},"Access-Reject","Check our return is 'Access-Reject' for a uptime topup user");
#
# Test accounting START packet
#
my $session1_ID = "09d15244";
my $session1_Timestamp = time();
my $session1_Timestamp_str = DateTime->from_epoch(epoch => $session1_Timestamp,time_zone => 'UTC')
->strftime('%Y-%m-%d %H:%M:%S');
$res = smradius::client->run(
"--raddb","dicts",
"127.0.0.1",
"acct",
"secret123",
'NAS-IP-Address=10.0.0.3',
'Acct-Delay-Time=11',
'NAS-Identifier=Test-NAS1',
'Acct-Status-Type=Start',
'Event-Timestamp='.$session1_Timestamp,
'Framed-IP-Address=10.0.1.3',
'Acct-Session-Id='.$session1_ID,
'NAS-Port-Id=test iface name1',
'Called-Station-Id=testservice1',
'Calling-Station-Id=00:00:0C:EE:47:AA',
'User-Name=testuser1',
'NAS-Port-Type=Ethernet',
'NAS-Port=45355555',
'Framed-Protocol=PPP',
'Service-Type=Framed-User',
);
is(ref($res),"HASH","smradclient should return a HASH");
testDBResults("Check accounting record is created correctly",'accounting',{'AcctSessionID' => $session1_ID},
{
'NASIPAddress' => '10.0.0.3',
'AcctDelayTime' => '11',
'NASIdentifier' => 'Test-NAS1',
'AcctStatusType' => 1,
'EventTimestamp' => sub{ _timestampCheck(shift,$session1_Timestamp_str) },
'FramedIPAddress' => '10.0.1.3',
'AcctSessionId' => $session1_ID,
'NASPortId' => 'test iface name1',
'CalledStationId' => 'testservice1',
'CallingStationId' => '00:00:0C:EE:47:AA',
'Username' => 'testuser1',
'NASPortType' => 15,
'NASPort' => '45355555',
'FramedProtocol' => 1,
'ServiceType' => 2,
'AcctOutputPackets' => undef,
'AcctOutputGigawords' => undef,
'AcctOutputOctets' => undef,
'AcctInputPackets' => undef,
'AcctInputGigawords' => undef,
'AcctInputOctets' => undef,
'AcctSessionTime' => undef,
}
);
#
# Test accounting ALIVE packet
#
$res = smradius::client->run(
"--raddb","dicts",
"127.0.0.1",
"acct",
"secret123",
'Acct-Status-Type=Interim-Update',
'Acct-Output-Packets=800000',
'Acct-Output-Gigawords=0',
'Acct-Output-Octets=810000000',
'Acct-Input-Packets=777777',
'Acct-Input-Gigawords=0',
'Acct-Input-Octets=123456789',
'Acct-Session-Time=999',
'User-Name=testuser1',
'Acct-Session-Id='.$session1_ID,
'NAS-IP-Address=10.0.0.3',
'NAS-Port=45355555',
);
is(ref($res),"HASH","smradclient should return a HASH");
testDBResults("Check accounting record is updated correctly",'accounting',{'AcctSessionID' => $session1_ID},
{
'NASIPAddress' => '10.0.0.3',
'AcctDelayTime' => '11',
'NASIdentifier' => 'Test-NAS1',
'AcctStatusType' => 3,
'EventTimestamp' => sub{ _timestampCheck(shift,$session1_Timestamp_str) },
'FramedIPAddress' => '10.0.1.3',
'AcctSessionId' => $session1_ID,
'NASPortId' => 'test iface name1',
'CalledStationId' => 'testservice1',
'CallingStationId' => '00:00:0C:EE:47:AA',
'Username' => 'testuser1',
'NASPortType' => 15,
'NASPort' => '45355555',
'FramedProtocol' => 1,
'ServiceType' => 2,
'AcctOutputPackets' => '800000',
'AcctOutputGigawords' => '0',
'AcctOutputOctets' => '810000000',
'AcctInputPackets' => '777777',
'AcctInputGigawords' => '0',
'AcctInputOctets' => '123456789',
'AcctSessionTime' => '999',
}
);
#
# Test accounting STOP packet
#
$res = smradius::client->run(
"--raddb","dicts",
"127.0.0.1",
"acct",
"secret123",
'Acct-Status-Type=Stop',
'Acct-Output-Packets=999999',
'Acct-Output-Gigawords=0',
'Acct-Output-Octets=888888888',
'Acct-Input-Packets=1111111',
'Acct-Input-Gigawords=0',
'Acct-Input-Octets=222222222',
'Acct-Session-Time=3998',
'Acct-Terminate-Cause=Session-Timeout',
'User-Name=testuser1',
'Acct-Session-Id='.$session1_ID,
'NAS-IP-Address=10.0.0.3',
'NAS-Port=45355555',
);
is(ref($res),"HASH","smradclient should return a HASH");
testDBResults("Check accounting record is stopped correctly",'accounting',{'AcctSessionID' => $session1_ID},
{
'NASIPAddress' => '10.0.0.3',
'AcctDelayTime' => '11',
'NASIdentifier' => 'Test-NAS1',
'AcctStatusType' => 2,
'EventTimestamp' => sub{ _timestampCheck(shift,$session1_Timestamp_str) },
'FramedIPAddress' => '10.0.1.3',
'AcctSessionId' => $session1_ID,
'NASPortId' => 'test iface name1',
'CalledStationId' => 'testservice1',
'CallingStationId' => '00:00:0C:EE:47:AA',
'Username' => 'testuser1',
'NASPortType' => 15,
'NASPort' => '45355555',
'FramedProtocol' => 1,
'ServiceType' => 2,
'AcctOutputPackets' => '999999',
'AcctOutputGigawords' => '0',
'AcctOutputOctets' => '888888888',
'AcctInputPackets' => '1111111',
'AcctInputGigawords' => '0',
'AcctInputOctets' => '222222222',
'AcctSessionTime' => '3998',
'AcctTerminateCause' => '5',
}
);
#
# Test missing accounting START packet
#
my $session2_ID = "817a0f1b";
my $session2_Timestamp = time();
my $session2_Timestamp_str = DateTime->from_epoch(epoch => $session2_Timestamp,time_zone => 'UTC')
->strftime('%Y-%m-%d %H:%M:%S');
$res = smradius::client->run(
"--raddb","dicts",
"127.0.0.1",
"acct",
"secret123",
'User-Name=testuser2',
'NAS-IP-Address=10.0.0.1',
'Acct-Delay-Time=12',
'NAS-Identifier=Test-NAS2',
'Acct-Status-Type=Interim-Update',
'Acct-Output-Packets=786933',
'Acct-Output-Gigawords=0',
'Acct-Output-Octets=708163705',
'Acct-Input-Packets=670235',
'Acct-Input-Gigawords=0',
'Acct-Input-Octets=102600046',
'Acct-Session-Time=800',
'Event-Timestamp='.$session2_Timestamp,
'Framed-IP-Address=10.0.1.1',
'Acct-Session-Id='.$session2_ID,
'NAS-Port-Id=wlan1',
'Called-Station-Id=testservice2',
'Calling-Station-Id=00:00:0C:EE:47:BF',
'NAS-Port-Type=Ethernet',
'NAS-Port=15729175',
'Framed-Protocol=PPP',
'Service-Type=Framed-User',
);
is(ref($res),"HASH","smradclient should return a HASH");
testDBResults("Check missing accounting record is created correctly",'accounting',{'AcctSessionID' => $session2_ID},
{
'Username' => 'testuser2',
'NASIPAddress' => '10.0.0.1',
'AcctDelayTime' => '12',
'NASIdentifier' => 'Test-NAS2',
'AcctStatusType' => 3,
'AcctOutputPackets' => '786933',
'AcctOutputGigawords' => '0',
'AcctOutputOctets' => '708163705',
'AcctInputPackets' => '670235',
'AcctInputGigawords' => '0',
'AcctInputOctets' => '102600046',
'AcctSessionTime' => '800',
'EventTimestamp' => sub{ _timestampCheck(shift,$session2_Timestamp_str) },
'FramedIPAddress' => '10.0.1.1',
'AcctSessionId' => $session2_ID,
'NASPortId' => 'wlan1',
'CalledStationId' => 'testservice2',
'CallingStationId' => '00:00:0C:EE:47:BF',
'NASPortType' => 15,
'NASPort' => '15729175',
'FramedProtocol' => 1,
'ServiceType' => 2,
}
);
#
# Check we get a Access-Accept for a traffic autotopup user
#
my $topuptest1_amount = 100;
my $user3_ID = testDBInsert("Create user 'testuser3'",
"INSERT INTO users (UserName,Disabled) VALUES ('testuser3',0)"
);
my $user3attr1_ID = testDBInsert("Create user 'testuser3' attribute 'User-Password'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user3_ID,'User-Password','==','test456'
);
my $user3attr2_ID = testDBInsert("Create user 'testuser3' attribute 'SMRadius-AutoTopup-Traffic-Enabled'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user3_ID,'SMRadius-AutoTopup-Traffic-Enabled',':=','yes'
);
my $user3attr3_ID = testDBInsert("Create user 'testuser3' attribute 'SMRadius-AutoTopup-Traffic-Amount'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user3_ID,'SMRadius-AutoTopup-Traffic-Amount',':=',$topuptest1_amount
);
my $user3attr4_ID = testDBInsert("Create user 'testuser3' attribute 'SMRadius-AutoTopup-Traffic-Limit'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user3_ID,'SMRadius-AutoTopup-Traffic-Limit',':=','500'
);
my $user3attr5_ID = testDBInsert("Create user 'testuser3' attribute 'SMRadius-Capping-Traffic-Limit'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user3_ID,'SMRadius-Capping-Traffic-Limit',':=','0'
);
$res = smradius::client->run(
"--raddb","dicts",
"127.0.0.1",
"auth",
"secret123",
'User-Name=testuser3',
'User-Password=test456',
);
is(ref($res),"HASH","smradclient should return a HASH");
is($res->{'response'}->{'code'},"Access-Accept","Check our return is 'Access-Accept' for a traffic autotopup user");
# Get the time now
my $topuptest1_now = time();
my $topuptest1 = DateTime->from_epoch( 'epoch' => $topuptest1_now, 'time_zone' => 'UTC');
# Use truncate to set all values after 'month' to their default values
my $topuptest1_thisMonth = $topuptest1->clone()->truncate( to => "month" );
# This month, in string form
my $topuptest1_thisMonth_str = $topuptest1_thisMonth->strftime("%Y-%m-%d %H:%M:%S");
# Next month..
my $topuptest1_nextMonth = $topuptest1_thisMonth->clone()->add( months => 1 );
my $topuptest1_nextMonth_str = $topuptest1_nextMonth->strftime("%Y-%m-%d %H:%M:%S");
testDBResults("Check autotopup is added correctly",'topups',{'UserID' => $user3_ID},
{
'UserID' => $user3_ID,
'Timestamp' => sub { return _timestampCheck(shift,$topuptest1_now) },
'Type' => 5,
'ValidFrom' => $topuptest1_thisMonth_str,
'ValidTo' => $topuptest1_nextMonth_str,
'Value' => $topuptest1_amount,
'Depleted' => 0,
'SMAdminDepletedOn' => undef,
}
);
#
# Check we get a Access-Accept for a uptime autotopup user
#
my $topuptest1b_amount = 100;
my $user3b_ID = testDBInsert("Create user 'testuser3b'",
"INSERT INTO users (UserName,Disabled) VALUES ('testuser3b',0)"
);
my $user3battr1_ID = testDBInsert("Create user 'testuser3b' attribute 'User-Password'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user3b_ID,'User-Password','==','test456'
);
my $user3battr2_ID = testDBInsert("Create user 'testuser3b' attribute 'SMRadius-AutoTopup-Uptime-Enabled'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user3b_ID,'SMRadius-AutoTopup-Uptime-Enabled',':=','yes'
);
my $user3battr3_ID = testDBInsert("Create user 'testuser3b' attribute 'SMRadius-AutoTopup-Uptime-Amount'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user3b_ID,'SMRadius-AutoTopup-Uptime-Amount',':=',$topuptest1b_amount
);
my $user3battr4_ID = testDBInsert("Create user 'testuser3b' attribute 'SMRadius-AutoTopup-Uptime-Limit'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user3b_ID,'SMRadius-AutoTopup-Uptime-Limit',':=','500'
);
my $user3battr5_ID = testDBInsert("Create user 'testuser3b' attribute 'SMRadius-Capping-Uptime-Limit'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user3b_ID,'SMRadius-Capping-Uptime-Limit',':=','0'
);
$res = smradius::client->run(
"--raddb","dicts",
"127.0.0.1",
"auth",
"secret123",
'User-Name=testuser3b',
'User-Password=test456',
);
is(ref($res),"HASH","smradclient should return a HASH");
is($res->{'response'}->{'code'},"Access-Accept","Check our return is 'Access-Accept' for a uptime autotopup user");
# Get the time now
my $topuptest1b_now = time();
my $topuptest1b = DateTime->from_epoch( 'epoch' => $topuptest1b_now, 'time_zone' => 'UTC');
# Use truncate to set all values after 'month' to their default values
my $topuptest1b_thisMonth = $topuptest1b->clone()->truncate( to => "month" );
# This month, in string form
my $topuptest1b_thisMonth_str = $topuptest1b_thisMonth->strftime("%Y-%m-%d %H:%M:%S");
# Next month..
my $topuptest1b_nextMonth = $topuptest1b_thisMonth->clone()->add( months => 1 );
my $topuptest1b_nextMonth_str = $topuptest1b_nextMonth->strftime("%Y-%m-%d %H:%M:%S");
testDBResults("Check autotopup is added correctly",'topups',{'UserID' => $user3b_ID},
{
'UserID' => $user3b_ID,
'Timestamp' => sub { return _timestampCheck(shift,$topuptest1b_now) },
'Type' => 6,
'ValidFrom' => $topuptest1b_thisMonth_str,
'ValidTo' => $topuptest1b_nextMonth_str,
'Value' => $topuptest1b_amount,
'Depleted' => 0,
'SMAdminDepletedOn' => undef,
}
);
#
# Check that if we send an accounting ALIVE we update the auto-topups
#
my $topuptest2_amount = 100;
my $user4_ID = testDBInsert("Create user 'testuser4'",
"INSERT INTO users (UserName,Disabled) VALUES ('testuser4',0)"
);
my $user4attr1_ID = testDBInsert("Create user 'testuser4' attribute 'User-Password'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user4_ID,'User-Password','==','test456'
);
my $user4attr2_ID = testDBInsert("Create user 'testuser4' attribute 'SMRadius-AutoTopup-Traffic-Enabled'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user4_ID,'SMRadius-AutoTopup-Traffic-Enabled',':=','yes'
);
my $user4attr3_ID = testDBInsert("Create user 'testuser4' attribute 'SMRadius-AutoTopup-Traffic-Amount'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user4_ID,'SMRadius-AutoTopup-Traffic-Amount',':=',$topuptest2_amount
);
my $user4attr4_ID = testDBInsert("Create user 'testuser4' attribute 'SMRadius-AutoTopup-Traffic-Limit'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user4_ID,'SMRadius-AutoTopup-Traffic-Limit',':=','500'
);
my $user4attr5_ID = testDBInsert("Create user 'testuser4' attribute 'SMRadius-Capping-Traffic-Limit'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user4_ID,'SMRadius-Capping-Traffic-Limit',':=','0'
);
my $user4attr6_ID = testDBInsert("Create user 'testuser4' attribute 'SMRadius-AutoTopup-Traffic-Notify'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user4_ID,'SMRadius-AutoTopup-Traffic-Notify',':=','root@localhost'
);
my $session3_ID = "9c5f24a";
my $session3_Timestamp = time();
$res = smradius::client->run(
"--raddb","dicts",
"127.0.0.1",
"acct",
"secret123",
'User-Name=testuser4',
'NAS-IP-Address=10.0.0.1',
'Acct-Delay-Time=12',
'NAS-Identifier=Test-NAS2',
'Acct-Status-Type=Interim-Update',
'Acct-Output-Packets=786933',
'Acct-Output-Gigawords=0',
'Acct-Output-Octets=708163705',
'Acct-Input-Packets=670235',
'Acct-Input-Gigawords=0',
'Acct-Input-Octets=102600046',
'Acct-Session-Time=800',
'Event-Timestamp='.$session3_Timestamp,
'Framed-IP-Address=10.0.1.1',
'Acct-Session-Id='.$session3_ID,
'NAS-Port-Id=wlan1',
'Called-Station-Id=testservice2',
'Calling-Station-Id=00:00:0C:EE:47:BF',
'NAS-Port-Type=Ethernet',
'NAS-Port=15729175',
'Framed-Protocol=PPP',
'Service-Type=Framed-User',
);
is(ref($res),"HASH","smradclient should return a HASH");
# Get the time now
my $topuptest2_now = time();
my $topuptest2 = DateTime->from_epoch( 'epoch' => $topuptest2_now, 'time_zone' => 'UTC');
# Use truncate to set all values after 'month' to their default values
my $topuptest2_thisMonth = $topuptest2->clone()->truncate( to => "month" );
# This month, in string form
my $topuptest2_thisMonth_str = $topuptest2_thisMonth->strftime("%Y-%m-%d %H:%M:%S");
# Next month..
my $topuptest2_nextMonth = $topuptest2_thisMonth->clone()->add( months => 1 );
my $topuptest2_nextMonth_str = $topuptest2_nextMonth->strftime("%Y-%m-%d %H:%M:%S");
testDBResults("Check autotopup is added correctly after acct_log",'topups',{'UserID' => $user4_ID},
{
'UserID' => $user4_ID,
'Timestamp' => sub { return _timestampCheck(shift,$topuptest2_now) },
'Type' => 5,
'ValidFrom' => $topuptest2_thisMonth_str,
'ValidTo' => $topuptest2_nextMonth_str,
'Value' => $topuptest2_amount,
'Depleted' => 0,
'SMAdminDepletedOn' => undef,
}
);
#
# Check that if we send an accounting ALIVE we do not trigger FUP
#
my $user5_ID = testDBInsert("Create user 'testuser5'",
"INSERT INTO users (UserName,Disabled) VALUES ('testuser5',0)"
);
my $user5attr1_ID = testDBInsert("Create user 'testuser5' attribute 'User-Password'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user5_ID,'User-Password','==','test456'
);
my $user5attr2_ID = testDBInsert("Create user 'testuser5' attribute 'SMRadius-FUP-Period'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user5_ID,'SMRadius-FUP-Period',':=','1'
);
my $user5attr3_ID = testDBInsert("Create user 'testuser5' attribute 'SMRadius-FUP-Traffic-Threshold'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user5_ID,'SMRadius-FUP-Traffic-Threshold',':=',800
);
# Add an attribute so we can check the FUP match results
my $user5attr4_ID = testDBInsert("Create user 'testuser5' attribute 'SMRadius-Evaluate'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user5_ID,'SMRadius-Evaluate','||+=',"SMRadius_FUP > 0 ? [14988:Mikrotik-Rate-Limit] = 1638k/8m : [14988:Mikrotik-Rate-Limit] = 1k/1m"
);
my $session4_ID = "a8abc40";
my $session4_Timestamp = time();
$res = smradius::client->run(
"--raddb","dicts",
"--listen","127.0.0.1:1700",
"127.0.0.1",
"acct",
"secret123",
'User-Name=testuser5',
'NAS-IP-Address=10.0.0.1',
'Acct-Delay-Time=12',
'NAS-Identifier=Test-NAS2',
'Acct-Status-Type=Interim-Update',
'Acct-Output-Packets=786933',
'Acct-Output-Gigawords=0',
'Acct-Output-Octets=708163705',
'Acct-Input-Packets=670235',
'Acct-Input-Gigawords=0',
'Acct-Input-Octets=102600046',
'Acct-Session-Time=800',
'Event-Timestamp='.$session4_Timestamp,
'Framed-IP-Address=10.0.1.1',
'Acct-Session-Id='.$session4_ID,
'NAS-Port-Id=wlan1',
'Called-Station-Id=testservice2',
'Calling-Station-Id=00:00:0C:EE:47:BF',
'NAS-Port-Type=Ethernet',
'NAS-Port=15729175',
'Framed-Protocol=PPP',
'Service-Type=Framed-User',
);
is(ref($res),"HASH","smradclient should return a HASH");
is($res->{'listen'}->{'response'}->{'code'},"CoA-Request","Check that the packet we got back is infact a ".
"CoA-Request");
is($res->{'listen'}->{'response'}->{'vattributes'}->{'14988'}->{'Mikrotik-Rate-Limit'}->[0],"1k/1m","Check that the vendor attribute".
"'14988:Mikrotik-Rate-Limit' is returned on the negative side of the IF");
testDBResults("Check FUP state was added to the user stats table as 0",'users_data',
{'UserID' => $user5_ID, 'Name' => "mod_feature_fup/State"},
{'Value' => "0"},
1, # Disable order
);
#
# Check that if we send an accounting ALIVE with a usage amount that exceeds FUP, that we trigger it
#
my $user6_ID = testDBInsert("Create user 'testuser6'",
"INSERT INTO users (UserName,Disabled) VALUES ('testuser6',0)"
);
my $user6attr1_ID = testDBInsert("Create user 'testuser6' attribute 'User-Password'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user6_ID,'User-Password','==','test456'
);
my $user6attr2_ID = testDBInsert("Create user 'testuser6' attribute 'SMRadius-FUP-Period'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user6_ID,'SMRadius-FUP-Period',':=','1'
);
my $user6attr3_ID = testDBInsert("Create user 'testuser6' attribute 'SMRadius-FUP-Traffic-Threshold'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user6_ID,'SMRadius-FUP-Traffic-Threshold',':=',800
);
# Add an attribute so we can check the FUP match results
my $user6attr4_ID = testDBInsert("Create user 'testuser6' attribute 'SMRadius-Evaluate'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user6_ID,'SMRadius-Evaluate','||+=',"SMRadius_FUP > 0 ? [14988:Mikrotik-Rate-Limit] = 1638k/8m : [14988:Mikrotik-Rate-Limit] = 1k/1m"
);
my $session5_ID = "582dc00";
my $session5_Timestamp = time();
$res = smradius::client->run(
"--raddb","dicts",
"--listen","127.0.0.1:1700",
"127.0.0.1",
"acct",
"secret123",
'User-Name=testuser6',
'NAS-IP-Address=10.0.0.1',
'Acct-Delay-Time=12',
'NAS-Identifier=Test-NAS2',
'Acct-Status-Type=Interim-Update',
'Acct-Output-Packets=786933',
'Acct-Output-Gigawords=0',
'Acct-Output-Octets=808163705',
'Acct-Input-Packets=670235',
'Acct-Input-Gigawords=0',
'Acct-Input-Octets=202600046',
'Acct-Session-Time=800',
'Event-Timestamp='.$session5_Timestamp,
'Framed-IP-Address=10.0.1.1',
'Acct-Session-Id='.$session5_ID,
'NAS-Port-Id=wlan1',
'Called-Station-Id=testservice2',
'Calling-Station-Id=00:00:0C:EE:47:BF',
'NAS-Port-Type=Ethernet',
'NAS-Port=15729175',
'Framed-Protocol=PPP',
'Service-Type=Framed-User',
);
is(ref($res),"HASH","smradclient should return a HASH");
is($res->{'listen'}->{'response'}->{'code'},"CoA-Request","Check that the packet we got back is infact a ".
"CoA-Request");
is($res->{'listen'}->{'response'}->{'vattributes'}->{'14988'}->{'Mikrotik-Rate-Limit'}->[0],"1638k/8m","Check that the ".
"vendor attribute '14988:Mikrotik-Rate-Limit' is returned on the success side of the FUP check");
testDBResults("Check FUP state was added to the user stats table as 1",'users_data',
{'UserID' => $user6_ID, 'Name' => "mod_feature_fup/State"},
{'Value' => "1"},
1, # Disable order
);
#
# Check that if we send an accounting ALIVE with a usage amount that exceeds capping, that we trigger a POD
#
my $user7_ID = testDBInsert("Create user 'testuser7'",
"INSERT INTO users (UserName,Disabled) VALUES ('testuser7',0)"
);
my $user7attr1_ID = testDBInsert("Create user 'testuser7' attribute 'User-Password'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user7_ID,'User-Password','==','test456'
);
# Add an attribute so we can check the capping does a POD
my $user7attr4_ID = testDBInsert("Create user 'testuser7' attribute 'SMRadius-Capping-Traffic-Limit'",
"INSERT INTO user_attributes (UserID,Name,Operator,Value,Disabled) VALUES (?,?,?,?,0)",
$user7_ID,'SMRadius-Capping-Traffic-Limit',':=','1'
);
my $session6_ID = "5209dac0";
my $session6_Timestamp = time();
$res = smradius::client->run(
"--raddb","dicts",
"--listen","127.0.0.1:1700",
"127.0.0.1",
"acct",
"secret123",
'User-Name=testuser7',
'NAS-IP-Address=10.0.0.1',
'Acct-Delay-Time=12',
'NAS-Identifier=Test-NAS2',
'Acct-Status-Type=Interim-Update',
'Acct-Output-Packets=786933',
'Acct-Output-Gigawords=0',
'Acct-Output-Octets=808163705',
'Acct-Input-Packets=670235',
'Acct-Input-Gigawords=0',
'Acct-Input-Octets=202600046',
'Acct-Session-Time=800',
'Event-Timestamp='.$session6_Timestamp,
'Framed-IP-Address=10.0.1.1',
'Acct-Session-Id='.$session6_ID,
'NAS-Port-Id=wlan1',
'Called-Station-Id=testservice2',
'Calling-Station-Id=00:00:0C:EE:47:BF',
'NAS-Port-Type=Ethernet',
'NAS-Port=15729175',
'Framed-Protocol=PPP',
'Service-Type=Framed-User',
);
is(ref($res),"HASH","smradclient should return a HASH");
is($res->{'listen'}->{'response'}->{'code'},"Disconnect-Request","Check that the packet we got back is infact a ".
"Disconnect-Request");
sleep(5);
} else {
smradius::daemon->run(
"--fg",
"--debug",
"--config", "smradiusd.conf.test",
);
sleep 4;
exit 0;
}
cleanup();
done_testing();
# Cleanup function
sub cleanup
{
if ($child) {
# Kill the child if it exists
if (kill(0,$child)) {
kill('TERM',$child);
}
# Wait for it to be reaped
waitpid($child,-1);
}
}
# Function to quickly and easily insert data into the DB and generate 2 tests out of it
sub testDBInsert
{
my ($name,@params) = @_;
# Do the work...
DBDo(@params);
# Make sure we got no error
is(AWITPT::DB::DBLayer::error(),"",$name);
# Grab the last insert ID
my $id = DBLastInsertID();
# Make sure its > 0
is($id > 0,1,"$name, insert ID > 0");
return $id;
}
# Function to quickly and easily delete data from the DB
sub testDBDelete
{
my ($name,@params) = @_;
# Do the work...
DBDo(@params);
# Make sure we got no error
is(AWITPT::DB::DBLayer::error(),"",$name);
return 1;
}
# Test DB select results
sub testDBResults
{
my ($name,$table,$where,$resultCheck,$disableOrder) = @_;
# Build column list
my $columnList_str = join(',',keys %{$resultCheck});
# Create where criteria
my @whereLines = ();
my @whereData = ();
foreach my $columnName (keys %{$where}) {
# Add template placeholders
push(@whereLines,"$columnName = ?");
# Add data for template placeholders
push(@whereData,$where->{$columnName});
}
my $whereLines_str = join(' AND ',@whereLines);
# Check if we're not disabling ordering
my $extraSQL = "";
if (!defined($disableOrder)) {
$extraSQL = "ORDER BY ID DESC";
}
my $sqlQuery = "
SELECT
$columnList_str
FROM
$table
WHERE
$whereLines_str
$extraSQL
";
# Do select
my $sth = DBSelect($sqlQuery,@whereData);
# Make sure we got no error
is(AWITPT::DB::DBLayer::error(),"","Errors on DBSelect ($sqlQuery interpolated with ".join(', ',$extraSQL).": $name");
# We should get one result...
my $row = hashifyLCtoMC($sth->fetchrow_hashref(),keys %{$resultCheck});
is(defined($row),1,"DBSelect row defined: $name");
# Loop through results and check if they match
foreach my $resultName (keys %{$resultCheck}) {
# Check if the result is a code-based subroutine
if (ref(my $result = $resultCheck->{$resultName}) eq "CODE") {
is($resultCheck->{$resultName}($row->{$resultName}),1,"$name: $resultName sub{} check");
} else {
is($row->{$resultName},$resultCheck->{$resultName},"$name: $resultName check");
}
}
}
sub _timestampCheck
{
my ($testVal,$rightVal) = @_;
# Make sure testVal is defined
return "_timestampCheck: NO \$testVal" if (!defined($testVal));
# Make sure $testVal_time is returned form str2time
my $testVal_time = str2time($testVal,'UTC');
# Check if $rightVal is defined
my $rightVal_time;
if (!defined($rightVal)) {
$rightVal_time = time();
} elsif ($rightVal =~ /^\d+$/) {
$rightVal_time = $rightVal;
} else {
$rightVal_time = str2time($rightVal,'UTC');
}
# Make sure rightVal_time is defined
return "_timestampCheck: NO \$rightVal_time" if (!defined($rightVal_time));
# Grab the absolute difference
my $diff = abs($testVal_time - $rightVal_time);
return ($diff < 10) // "TIME DEVIATION: $diff";
}
#!/bin/bash
git submodule update --recursive --init
pushd 3rdparty/awitpt
git checkout v1.0.x
git pull
popd
pushd webgui/awitef
git checkout v0.0.x
git pull
popd
<?php <?php
# Ajax to PHP
# Copyright (C) 2007-2015, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# Requires / Includes # Requires / Includes
include_once("include/ajax/json.php"); include_once("include/ajax/json.php");
...@@ -6,14 +23,28 @@ ...@@ -6,14 +23,28 @@
include_once("include/ajax/functions/AdminUsers.php"); include_once("include/ajax/functions/AdminUsers.php");
include_once("include/ajax/functions/AdminUserAttributes.php"); include_once("include/ajax/functions/AdminUserAttributes.php");
include_once("include/ajax/functions/AdminUserGroups.php"); include_once("include/ajax/functions/AdminUserGroups.php");
include_once("include/ajax/functions/AdminUserLogs.php");
include_once("include/ajax/functions/AdminUserTopups.php");
include_once("include/ajax/functions/AdminGroups.php"); include_once("include/ajax/functions/AdminGroups.php");
include_once("include/ajax/functions/AdminGroupAttributes.php"); include_once("include/ajax/functions/AdminGroupAttributes.php");
include_once("include/ajax/functions/AdminGroupMembers.php"); include_once("include/ajax/functions/AdminGroupMembers.php");
include_once("include/ajax/functions/AdminRealms.php"); include_once("include/ajax/functions/AdminRealms.php");
include_once("include/ajax/functions/WiSPLocations.php"); include_once("include/ajax/functions/AdminRealmAttributes.php");
include_once("include/ajax/functions/AdminRealmMembers.php");
include_once("include/ajax/functions/AdminClients.php");
include_once("include/ajax/functions/AdminClientAttributes.php");
include_once("include/ajax/functions/AdminClientRealms.php");
include_once("include/ajax/functions/WiSPUsers.php"); include_once("include/ajax/functions/WiSPUsers.php");
include_once("include/ajax/functions/WiSPLocations.php");
include_once("include/ajax/functions/WiSPLocationMembers.php");
include_once("include/ajax/functions/WiSPUserLogs.php");
include_once("include/ajax/functions/WiSPUserTopups.php");
include_once("include/radiuscodes.php");
define('RES_OK',0); define('RES_OK',0);
define('RES_ERR',-1); define('RES_ERR',-1);
...@@ -34,7 +65,8 @@ ...@@ -34,7 +65,8 @@
); );
echo json_encode($res); echo json_encode($res);
*/ */
echo json_encode($msg); // echo json_encode($msg);
jsonError(-1,$msg);
exit; exit;
} }
...@@ -142,7 +174,7 @@ ...@@ -142,7 +174,7 @@
ajaxException("Unknown AJAX=>SOAP type: '$array_type'"); ajaxException("Unknown AJAX=>SOAP type: '$array_type'");
} }
} else { } else {
$item_value = $_REQUEST[$array_item]; $item_value = isset($_REQUEST[$array_item]) ? $_REQUEST[$array_item] : NULL;
} }
# Set item # Set item
$soapParams[$array_pos][$array_item] = $item_value; $soapParams[$array_pos][$array_item] = $item_value;
...@@ -153,8 +185,363 @@ ...@@ -153,8 +185,363 @@
} }
} }
switch ($function) { switch ($function) {
# addAdminClientRealm.js functions
case "addAdminClientRealm":
$res = addAdminClientRealm($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
case "removeAdminClientRealm":
$res = removeAdminClientRealm($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
case "getAdminClientRealms":
$res = getAdminClientRealms($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Name','string');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
# AdminClients.js functions
case "updateAdminClient":
$res = updateAdminClient($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
case "createAdminClient":
$res = createAdminClient($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
case "removeAdminClient":
$res = removeAdminClient($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
case "getAdminClients":
$res = getAdminClients($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Name','string');
$res->addField('AccessList','string');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
case "getAdminClient":
$rawData = getAdminClient($soapParams);
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Name','string');
$res->addField('AccessList','string');
$res->parseHash($rawData);
echo json_encode($res->export());
break;
# AdminClientAttributes.js functions
case "addAdminClientAttribute":
$res = addAdminClientAttribute($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
case "updateAdminClientAttribute":
$res = updateAdminClientAttribute($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
case "getAdminClientAttribute":
$rawData = getAdminClientAttribute($soapParams);
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Name','string');
$res->addField('Operator','string');
$res->addField('Value','string');
$res->addField('Disabled','boolean');
$res->parseHash($rawData);
echo json_encode($res->export());
break;
case "getAdminClientAttributes":
$res = getAdminClientAttributes($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Name','string');
$res->addField('Operator','string');
$res->addField('Value','string');
$res->addField('Disabled','boolean');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
case "removeAdminClientAttribute":
$res = removeAdminClientAttribute($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
# Logs Summary
case "getWiSPUserLogsSummary":
$res = getWiSPUserLogsSummary($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response;
$res->addField('uptimeCap','int');
$res->addField('trafficCap','int');
$res->addField('trafficUsage','int');
$res->addField('uptimeUsage','int');
$res->addField('trafficTopups','int');
$res->addField('uptimeTopups','int');
$res->addField('TotalTrafficTopups','int');
$res->addField('TotalUptimeTopups','int');
$res->addField('AllTrafficTopups','array');
$res->addField('AllUptimeTopups','array');
$res->parseHash($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
case "getAdminUserLogsSummary":
$res = getAdminUserLogsSummary($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response;
$res->addField('uptimeCap','int');
$res->addField('trafficCap','int');
$res->addField('trafficUsage','int');
$res->addField('uptimeUsage','int');
$res->addField('trafficTopups','int');
$res->addField('uptimeTopups','int');
$res->addField('TotalTrafficTopups','int');
$res->addField('TotalUptimeTopups','int');
$res->addField('AllTrafficTopups','array');
$res->addField('AllUptimeTopups','array');
$res->parseHash($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
# AdminUserTopups.js functions
case "getAdminUserTopups":
$res = getAdminUserTopups($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Timestamp','date');
$res->addField('Type','int');
$res->addField('Value','int');
$res->addField('ValidFrom','string');
$res->addField('ValidTo','string');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
case "createAdminUserTopup":
$res = createAdminUserTopup($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
case "updateAdminUserTopup":
$res = updateAdminUserTopup($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
case "getAdminUserTopup":
$rawData = getAdminUserTopup($soapParams);
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Type','int');
$res->addField('Value','int');
$res->addField('ValidFrom','date');
$res->addField('ValidTo','date');
$res->parseHash($rawData);
echo json_encode($res->export());
break;
case "removeAdminUserTopup":
$res = removeAdminUserTopup($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
# WiSPUserTopups.js functions
case "getWiSPUserTopups":
$res = getWiSPUserTopups($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Timestamp','date');
$res->addField('Type','int');
$res->addField('Value','int');
$res->addField('ValidFrom','string');
$res->addField('ValidTo','string');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
case "createWiSPUserTopup":
$res = createWiSPUserTopup($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
case "updateWiSPUserTopup":
$res = updateWiSPUserTopup($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
case "getWiSPUserTopup":
$rawData = getWiSPUserTopup($soapParams);
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Type','int');
$res->addField('Value','int');
$res->addField('ValidFrom','date');
$res->addField('ValidTo','date');
$res->parseHash($rawData);
echo json_encode($res->export());
break;
case "removeWiSPUserTopup":
$res = removeWiSPUserTopup($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
# AdminGroupMembers.js functions # AdminGroupMembers.js functions
case "getAdminGroupMembers": case "getAdminGroupMembers":
...@@ -164,7 +551,7 @@ ...@@ -164,7 +551,7 @@
$res = new json_response; $res = new json_response;
$res->setID('ID'); $res->setID('ID');
$res->addField('ID','int'); $res->addField('ID','int');
$res->addField('Name','string'); $res->addField('Username','string');
$res->addField('Disabled','boolean'); $res->addField('Disabled','boolean');
$res->parseArray($rawData); $res->parseArray($rawData);
$res->setDatasetSize($numResults); $res->setDatasetSize($numResults);
...@@ -178,6 +565,36 @@ ...@@ -178,6 +565,36 @@
$res = removeAdminGroupMember($soapParams); $res = removeAdminGroupMember($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
}
break;
# AdminRealmMembers.js functions
case "getAdminRealmMembers":
$res = getAdminRealmMembers($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Name','string');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
case "removeAdminRealmMember":
$res = removeAdminRealmMember($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -185,22 +602,28 @@ ...@@ -185,22 +602,28 @@
# AdminUserLogs.js functions # AdminUserLogs.js functions
case "getAdminUserLogs": case "getAdminUserLogs":
$rawData = getAdminUserLogs($soapParams); $res = getAdminUserLogs($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response; $res = new json_response;
$res->setID('ID'); $res->setID('ID');
$res->addField('ID','int'); $res->addField('ID','int');
$res->addField('EventTimestamp','string');
$res->addField('AcctStatusType','int'); $res->addField('AcctStatusType','int');
$res->addField('ServiceType','int'); $res->addField('ServiceType','int');
$res->addField('FramedProtocol','int'); $res->addField('FramedProtocol','int');
$res->addField('NASPort','string');
$res->addField('NASPortType','int'); $res->addField('NASPortType','int');
$res->addField('NASPortID','string'); $res->addField('NASPortID','string');
$res->addField('CallingStationID','string'); $res->addField('CallingStationID','string');
$res->addField('CalledStationID','string'); $res->addField('CalledStationID','string');
$res->addField('AcctSessionID','string'); $res->addField('AcctSessionID','string');
$res->addField('FramedIPAddress','string'); $res->addField('FramedIPAddress','string');
$res->parseHash($rawData); $res->addField('AcctInput','float');
$res->addField('AcctOutput','float');
$res->addField('AcctSessionTime','int');
$res->addField('ConnectTermReason','string');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export()); echo json_encode($res->export());
...@@ -212,6 +635,8 @@ ...@@ -212,6 +635,8 @@
$res = addAdminUserGroup($soapParams); $res = addAdminUserGroup($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -221,6 +646,8 @@ ...@@ -221,6 +646,8 @@
$res = removeAdminUserGroup($soapParams); $res = removeAdminUserGroup($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -241,12 +668,81 @@ ...@@ -241,12 +668,81 @@
break; break;
# AdminRealmAttributes.js functions
case "addAdminRealmAttribute":
$res = addAdminRealmAttribute($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
case "updateAdminRealmAttribute":
$res = updateAdminRealmAttribute($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
case "getAdminRealmAttribute":
$rawData = getAdminRealmAttribute($soapParams);
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Name','string');
$res->addField('Operator','string');
$res->addField('Value','string');
$res->addField('Disabled','boolean');
$res->parseHash($rawData);
echo json_encode($res->export());
break;
case "getAdminRealmAttributes":
$res = getAdminRealmAttributes($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Name','string');
$res->addField('Operator','string');
$res->addField('Value','string');
$res->addField('Disabled','boolean');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
case "removeAdminRealmAttribute":
$res = removeAdminRealmAttribute($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break;
# AdminGroupAttributes.js functions # AdminGroupAttributes.js functions
case "addAdminGroupAttribute": case "addAdminGroupAttribute":
$res = addAdminGroupAttribute($soapParams); $res = addAdminGroupAttribute($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -256,6 +752,8 @@ ...@@ -256,6 +752,8 @@
$res = updateAdminGroupAttribute($soapParams); $res = updateAdminGroupAttribute($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -267,6 +765,9 @@ ...@@ -267,6 +765,9 @@
$res->setID('ID'); $res->setID('ID');
$res->addField('ID','int'); $res->addField('ID','int');
$res->addField('Name','string'); $res->addField('Name','string');
$res->addField('Operator','string');
$res->addField('Value','string');
$res->addField('Disabled','boolean');
$res->parseHash($rawData); $res->parseHash($rawData);
echo json_encode($res->export()); echo json_encode($res->export());
...@@ -295,6 +796,8 @@ ...@@ -295,6 +796,8 @@
$res = removeAdminGroupAttribute($soapParams); $res = removeAdminGroupAttribute($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -305,6 +808,8 @@ ...@@ -305,6 +808,8 @@
$res = addAdminUserAttribute($soapParams); $res = addAdminUserAttribute($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -314,6 +819,8 @@ ...@@ -314,6 +819,8 @@
$res = updateAdminUserAttribute($soapParams); $res = updateAdminUserAttribute($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -325,6 +832,9 @@ ...@@ -325,6 +832,9 @@
$res->setID('ID'); $res->setID('ID');
$res->addField('ID','int'); $res->addField('ID','int');
$res->addField('Name','string'); $res->addField('Name','string');
$res->addField('Operator','string');
$res->addField('Value','string');
$res->addField('Disabled','boolean');
$res->parseHash($rawData); $res->parseHash($rawData);
echo json_encode($res->export()); echo json_encode($res->export());
...@@ -353,6 +863,8 @@ ...@@ -353,6 +863,8 @@
$res = removeAdminUserAttribute($soapParams); $res = removeAdminUserAttribute($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -363,6 +875,8 @@ ...@@ -363,6 +875,8 @@
$res = updateWiSPUser($soapParams); $res = updateWiSPUser($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -372,6 +886,8 @@ ...@@ -372,6 +886,8 @@
$res = createWiSPUser($soapParams); $res = createWiSPUser($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -381,6 +897,8 @@ ...@@ -381,6 +897,8 @@
$res = removeWiSPUser($soapParams); $res = removeWiSPUser($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -406,15 +924,112 @@ ...@@ -406,15 +924,112 @@
break; break;
case "getWiSPUser": case "getWiSPUser":
$rawData = getWiSPUser($soapParams); $res = getWiSPUser($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response; $res = new json_response;
$res->setID('ID'); $res->setID('ID');
$res->addField('ID','int'); $res->addField('ID','int');
$res->addField('Username','string'); $res->addField('Username','string');
$res->addField('Disabled','boolean');
$res->addField('Password','string');
$res->addField('Firstname','string');
$res->addField('Lastname','string');
$res->addField('Phone','string');
$res->addField('Email','string');
$res->addField('LocationID','int');
$res->parseHash($rawData); $res->parseHash($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
case "getWiSPUserAttributes":
$res = getWiSPUserAttributes($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Name','string');
$res->addField('Operator','string');
$res->addField('Value','string');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
case "getWiSPUserGroups":
$res = getWiSPUserGroups($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Name','string');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
# WiSPUserLogs.js functions
case "getWiSPUserLogs":
$res = getWiSPUserLogs($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('EventTimestamp','string');
$res->addField('AcctStatusType','int');
$res->addField('ServiceType','int');
$res->addField('FramedProtocol','int');
$res->addField('NASPortType','int');
$res->addField('NASPortID','string');
$res->addField('CallingStationID','string');
$res->addField('CalledStationID','string');
$res->addField('AcctSessionID','string');
$res->addField('FramedIPAddress','string');
$res->addField('AcctInput','float');
$res->addField('AcctOutput','float');
$res->addField('AcctSessionTime','int');
$res->addField('ConnectTermReason','string');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export()); echo json_encode($res->export());
break;
# WiSPLocationMembers.js functions
case "getWiSPLocationMembers":
$res = getWiSPLocationMembers($soapParams);
$rawData = $res[0]; $numResults = $res[1];
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Username','string');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
case "removeWiSPLocationMember":
$res = removeWiSPLocationMember($soapParams);
if (isset($res)) {
ajaxException($res);
} else {
jsonSuccess();
}
break; break;
# WiSPLocations.js functions # WiSPLocations.js functions
...@@ -423,6 +1038,8 @@ ...@@ -423,6 +1038,8 @@
$res = updateWiSPLocation($soapParams); $res = updateWiSPLocation($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -432,6 +1049,8 @@ ...@@ -432,6 +1049,8 @@
$res = createWiSPLocation($soapParams); $res = createWiSPLocation($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -441,6 +1060,8 @@ ...@@ -441,6 +1060,8 @@
$res = removeWiSPLocation($soapParams); $res = removeWiSPLocation($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -478,6 +1099,8 @@ ...@@ -478,6 +1099,8 @@
$res = updateAdminUser($soapParams); $res = updateAdminUser($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -487,6 +1110,8 @@ ...@@ -487,6 +1110,8 @@
$res = createAdminUser($soapParams); $res = createAdminUser($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -496,6 +1121,8 @@ ...@@ -496,6 +1121,8 @@
$res = removeAdminUser($soapParams); $res = removeAdminUser($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -535,6 +1162,8 @@ ...@@ -535,6 +1162,8 @@
$res = updateAdminRealm($soapParams); $res = updateAdminRealm($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -544,6 +1173,8 @@ ...@@ -544,6 +1173,8 @@
$res = createAdminRealm($soapParams); $res = createAdminRealm($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -553,6 +1184,8 @@ ...@@ -553,6 +1184,8 @@
$res = removeAdminRealm($soapParams); $res = removeAdminRealm($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -592,6 +1225,8 @@ ...@@ -592,6 +1225,8 @@
$res = updateAdminGroup($soapParams); $res = updateAdminGroup($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -601,6 +1236,8 @@ ...@@ -601,6 +1236,8 @@
$res = createAdminGroup($soapParams); $res = createAdminGroup($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -610,6 +1247,8 @@ ...@@ -610,6 +1247,8 @@
$res = removeAdminGroup($soapParams); $res = removeAdminGroup($soapParams);
if (isset($res)) { if (isset($res)) {
ajaxException($res); ajaxException($res);
} else {
jsonSuccess();
} }
break; break;
...@@ -687,137 +1326,9 @@ ...@@ -687,137 +1326,9 @@
echo json_encode($res->export()); echo json_encode($res->export());
break; break;
case "getWiSPUsers":
$rawData = array (
array(
'ID' => 10,
'AgentID' => 5,
'AgentName' => 'joe agent',
'Username' => 'johnsmith',
'UsageCap' => 1000,
'ClassID' => 7,
'ClassDesc' => 'ClassTest',
'RealmDesc' => 'My Realm',
'Service' => 'My Service',
'AgentDisabled' => FALSE,
'Disabled' => FALSE,
'AgentRef' => 'Reseller ref'
)
);
$numResults = 1;
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('AgentID','int');
$res->addField('AgentName','string');
$res->addField('Username','string');
$res->addField('UsageCap','int');
$res->addField('ClassID','int');
$res->addField('ClassDesc','string');
$res->addField('RealmDesc','string');
$res->addField('Service','string');
$res->addField('AgentDisabled','boolean');
$res->addField('Disabled','boolean');
$res->addField('AgentRef','string');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
case "getWiSPUserLogs":
$rawData = array (
array(
'ID' => 10,
'Username' => 'johnsmith',
'Status' => 1,
'Timestamp' => '10/03/2009',
'AcctSessionID' => '24234',
'AcctSessionTime' => '10:30',
'NASIPAddress' => '192.168.1.254',
'NASPortType' => '2',
'NASPort' => '3128',
'CalledStationID' => '282282',
'CallingStationID' => '2782872',
'NASTransmitRate' => '2000',
'NASReceiveRate' => '4000',
'FramedIPAddress' => '192.168.1.30',
'AcctInputMbyte' => '1241',
'AcctOutputMbyte' => '229',
'LastAcctUpdate' => '1282893',
'ConnectTermReason' => 'Failboat'
)
);
$numResults = 1;
$res = new json_response;
$res->setID('ID');
$res->addField('ID','int');
$res->addField('Username','int');
$res->addField('Status','string');
$res->addField('Timestamp','string');
$res->addField('AcctSessionID','int');
$res->addField('AcctSessionTime','int');
$res->addField('NASIPAddress','string');
$res->addField('NASPortType','string');
$res->addField('NASPort','string');
$res->addField('CalledStationID','boolean');
$res->addField('CallingStationID','boolean');
$res->addField('NASTransmitRate','string');
$res->addField('NASReceiveRate','string');
$res->addField('FramedIPAddress','string');
$res->addField('AcctInputMbyte','string');
$res->addField('AcctOutputMbyte','string');
$res->addField('LastAcctUpdate','string');
$res->addField('ConnectTermReason','string');
$res->parseArray($rawData);
$res->setDatasetSize($numResults);
echo json_encode($res->export());
break;
}
exit;
# Connect via soap
$soap = new SoapClient(null,
array(
'location' => "http://localhost:1080/?Auth=$authType",
'uri' => $module,
'login' => $username,
'password' => $password
)
);
# Try soap call
try {
$soapRes = $soap->__call($function,$soapParams);
} catch (Exception $e) {
# Build msg string
if (is_soap_fault($e)) {
header("$SERVER_PROTOCOL 500 Internal Server Error");
$msg = "SOAP Fault: ".$e->faultstring;
if (!empty($e->detail)) {
$msg .= " (".$e->detail.")";
}
} else {
header("$SERVER_PROTOCOL 400 Bad Request");
$msg = "Fault: ".$e->getMessage();
}
ajaxException($msg);
} }
echo json_encode($soapRes); exit;
# vim: ts=4 # vim: ts=4
awitef @ e81e0f67
Subproject commit e81e0f67579cbfda8090563f11cf9c5ccda453b2
body .x-panel {
margin-bottom:20px;
}
.icon-grid {
background-image:url(resources/extjs/icons/fam/grid.png) !important;
}
#button-grid .x-panel-body {
border:1px solid #99bbe8;
border-top:0 none;
}
.add {
background-image:url(resources/extjs/icons/fam/add.gif) !important;
}
.edit {
background-image:url(resources/extjs/icons/fam/plugin.gif) !important;
}
.option {
background-image:url(resources/extjs/icons/fam/plugin.gif) !important;
}
.remove {
background-image:url(resources/extjs/icons/fam/delete.gif) !important;
}
.save {
background-image:url(resources/extjs/icons/save.gif) !important;
}
<?php
# Admin Client Attributes functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php");
# Add client attribute
function addAdminClientAttribute($params) {
# Perform query
$res = DBDo("
INSERT INTO
@TP@client_attributes (ClientID,Name,Operator,Value,Disabled)
VALUES
(?,?,?,?,?)",
array( $params[0]['ClientID'],
$params[0]['Name'],
$params[0]['Operator'],
$params[0]['Value'],
$params[0]['Disabled'])
);
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Remove client attribute
function removeAdminClientAttribute($params) {
# Perform query
$res = DBDo("DELETE FROM @TP@client_attributes WHERE ID = ?",array($params[0]));
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Edit client attribute
function updateAdminClientAttribute($params) {
# Perform query
$res = DBDo("UPDATE @TP@client_attributes SET Name = ?, Operator = ?, Value = ?, Disabled = ? WHERE ID = ?",
array($params[0]['Name'],
$params[0]['Operator'],
$params[0]['Value'],
$params[0]['Disabled'],
$params[0]['ID'])
);
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Return specific attribute row
function getAdminClientAttribute($params) {
# Perform query
$res = DBSelect("SELECT ID, Name, Operator, Value, Disabled FROM @TP@client_attributes WHERE ID = ?",array($params[0]));
# Return error if failed
if (!is_object($res)) {
return $res;
}
# Build array of results
$resultArray = array();
$row = $res->fetchObject();
$resultArray['ID'] = $row->id;
$resultArray['Name'] = $row->name;
$resultArray['Operator'] = $row->operator;
$resultArray['Value'] = $row->value;
$resultArray['Disabled'] = $row->disabled;
# Return results
return $resultArray;
}
# Return list of attributes
function getAdminClientAttributes($params) {
# Filters and sorts are the same here
$filtersorts = array(
'ID' => '@TP@client_attributes.ID',
'Name' => '@TP@client_attributes.Name',
'Operator' => '@TP@client_attributes.Operator',
'Value' => '@TP@client_attributes.Value',
'Disabled' => '@TP@client_attributes.Disabled'
);
# Perform query
$res = DBSelectSearch("
SELECT
ID, Name, Operator, Value, Disabled
FROM
@TP@client_attributes
WHERE
ClientID = ".DBQuote($params[0])."
",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) {
return $res;
}
# Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) {
$item = array();
$item['ID'] = $row->id;
$item['Name'] = $row->name;
$item['Operator'] = $row->operator;
$item['Value'] = $row->value;
$item['Disabled'] = $row->disabled;
# Push this row onto array
array_push($resultArray,$item);
}
# Return results
return array($resultArray,$numResults);
}
# vim: ts=4
<?php <?php
# Radius Location Add # Admin Client Realms functions
# Copyright (C) 2007-2009, AllWorldIT # Copyright (C) 2007-2011, AllWorldIT
# #
# This program is free software; you can redistribute it and/or modify # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU General Public License as published by
...@@ -16,81 +16,77 @@ ...@@ -16,81 +16,77 @@
# with this program; if not, write to the Free Software Foundation, Inc., # with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("includes/header.php"); include_once("include/db.php");
include_once("includes/footer.php");
include_once("includes/db.php");
$db = connect_db();
printHeader(array(
"Tabs" => array(
"Back to locations list" => "wisp-locations-main.php"
),
));
if (isset($_POST['frmaction']) && $_POST['frmaction'] == "add") {
?>
<p class="pageheader">Add location</p>
<form method="post" action="wisp-locations-add.php">
<div>
<input type="hidden" name="frmaction" value="add2" />
</div>
<table class="entry">
<tr>
<td class="entrytitle">Location</td>
<td><input type="text" name="location" /></td>
</tr>
<tr>
<td class="textcenter" colspan="2">
<input type="submit" />
</td>
</tr>
</table>
</form>
<?php
# Check we have all params # Link client to realm
} elseif (isset($_POST['frmaction']) && $_POST['frmaction'] == "add2") { function addAdminClientRealm($params) {
?>
<p class="pageheader">Location Add Results</p>
<?php
# Check name # Perform query
if (empty($_POST['location'])) { $res = DBDo("INSERT INTO @TP@clients_to_realms (ClientID,RealmID) VALUES (?,?)",array($params[0]['ClientID'],$params[0]['RealmID']));
?>
<div class="warning">Location cannot be empty</div>
<?php
# Add to database # Return result
} else { if ($res !== TRUE) {
$stmt = $db->prepare("INSERT INTO ${DB_TABLE_PREFIX}wisp_locations (Location) VALUES (?)"); return $res;
$res = $stmt->execute(array( }
$_POST['location'],
)); return NULL;
}
# Was it successful?
if ($res !== FALSE) { # Unlink client from realm
?> function removeAdminClientRealm($params) {
<div class="notice">Location added</div>
<?php # Perform query
} else { $res = DBDo("DELETE FROM @TP@clients_to_realms WHERE ID = ?",array($params[0]));
?>
<div class="warning">Failed to add location</div>
<div class="warning"><?php print_r($stmt->errorInfo()) ?></div>
<?php
} # Return result
if ($res !== TRUE) {
return $res;
} }
} else { return NULL;
?>
<div class="warning">Invalid invocation</div>
<?php
} }
# Return list of realms
function getAdminClientRealms($params) {
# Filters and sorts are the same here
$filtersorts = array(
'ID' => '@TP@clients_to_realms.ID',
'Name' => '@TP@realms.Name'
);
# Perform query
$res = DBSelectSearch("
SELECT
@TP@clients_to_realms.ID, @TP@realms.Name
FROM
@TP@clients_to_realms, @TP@realms
WHERE
@TP@clients_to_realms.RealmID = @TP@realms.ID
AND @TP@clients_to_realms.ClientID = ".DBQuote($params[0])."
",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) {
return $res;
}
printFooter(); # Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) {
$item = array();
$item['ID'] = $row->id;
$item['Name'] = htmlspecialchars($row->name);
# Push this row onto array
array_push($resultArray,$item);
}
# Return results
return array($resultArray,$numResults);
}
# vim: ts=4 # vim: ts=4
?>
<?php
# Admin Clients functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php");
# Return list of clients
function getAdminClients($params) {
# Filters and sorts are the same here
$filtersorts = array(
'ID' => '@TP@clients.ID',
'Name' => '@TP@clients.Name',
'AccessList' => '@TP@clients.AccessList'
);
# Perform query
$res = DBSelectSearch("SELECT ID, Name, AccessList FROM @TP@clients",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) {
return $res;
}
# Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) {
$item = array();
$item['ID'] = $row->id;
$item['Name'] = $row->name;
$item['AccessList'] = $row->accesslist;
# Push this row onto array
array_push($resultArray,$item);
}
# Return results
return array($resultArray,$numResults);
}
# Return specific client row
function getAdminClient($params) {
# Perform query
$res = DBSelect("SELECT ID, Name, AccessList FROM @TP@clients WHERE ID = ?",array($params[0]));
# Return error if failed
if (!is_object($res)) {
return $res;
}
# Build array of results
$resultArray = array();
$row = $res->fetchObject();
$resultArray['ID'] = $row->id;
$resultArray['Name'] = $row->name;
$resultArray['AccessList'] = $row->accesslist;
# Return results
return $resultArray;
}
# Remove admin client
function removeAdminClient($params) {
# Begin transaction
DBBegin();
# Perform query
$res = DBDo("DELETE FROM @TP@client_attributes WHERE ClientID = ?",array($params[0]));
# Remove client from realms
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@clients_to_realms WHERE ClientID = ?",array($params[0]));
}
# Perform next query if successful
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@clients WHERE ID = ?",array($params[0]));
}
# Return result
if ($res !== TRUE) {
DBRollback();
return $res;
} else {
DBCommit();
}
return NULL;
}
# Add admin client
function createAdminClient($params) {
# Perform query
$res = DBDo("INSERT INTO @TP@clients (Name,AccessList) VALUES (?,?)",array($params[0]['Name'],$params[0]['AccessList']));
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Edit admin client
function updateAdminClient($params) {
# Perform query
$res = DBDo("UPDATE @TP@clients SET Name = ?, AccessList = ? WHERE ID = ?",
array($params[0]['Name'],$params[0]['AccessList'],$params[0]['ID']));
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# vim: ts=4
<?php <?php
# Admin Group Attributes functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php"); include_once("include/db.php");
include_once("include/util.php");
# Add user attribute # Add group attribute
function addAdminGroupAttribute($params) { function addAdminGroupAttribute($params) {
global $db;
$res = DBDo("INSERT INTO group_attributes (GroupID,Name) VALUES (?,?)",array($params[0]['GroupID'],$params[0]['Name'])); # Check Disabled param
if (!is_numeric($res)) { $disabled = isBoolean($params[0]['Disabled']);
if ($disabled < 0) {
return NULL;
}
$res = DBDo("
INSERT INTO
@TP@group_attributes (GroupID,Name,Operator,Value,Disabled)
VALUES
(?,?,?,?,?)",
array( $params[0]['GroupID'],
$params[0]['Name'],
$params[0]['Operator'],
$params[0]['Value'],
$disabled)
);
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
return NULL; return NULL;
} }
# Remove user attribute # Remove group attribute
function removeAdminGroupAttribute($params) { function removeAdminGroupAttribute($params) {
global $db;
$res = DBDo("DELETE FROM group_attributes WHERE ID = ?",array($params[0])); $res = DBDo("DELETE FROM @TP@group_attributes WHERE ID = ?",array($params[0]));
if (!is_numeric($res)) {
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
return NULL; return NULL;
} }
# Edit attribute # Edit group attribute
function updateAdminGroupAttribute($params) { function updateAdminGroupAttribute($params) {
global $db;
$res = DBDo("UPDATE group_attributes SET Name = ? WHERE ID = ?",array($params[0]['Name'],$params[0]['ID'])); # Check Disabled param
if (!is_numeric($res)) { $disabled = isBoolean($params[0]['Disabled']);
if ($disabled < 0) {
return NULL;
}
$res = DBDo("UPDATE @TP@group_attributes SET Name = ?, Operator = ?, Value = ?, Disabled = ? WHERE ID = ?",
array($params[0]['Name'],
$params[0]['Operator'],
$params[0]['Value'],
$disabled,
$params[0]['ID'])
);
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
...@@ -40,10 +88,8 @@ function updateAdminGroupAttribute($params) { ...@@ -40,10 +88,8 @@ function updateAdminGroupAttribute($params) {
# Return specific attribute row # Return specific attribute row
function getAdminGroupAttribute($params) { function getAdminGroupAttribute($params) {
global $db;
$res = DBSelect("SELECT ID, Name FROM group_attributes WHERE ID = ?",array($params[0])); $res = DBSelect("SELECT ID, Name, Operator, Value, Disabled FROM @TP@group_attributes WHERE ID = ?",array($params[0]));
if (!is_object($res)) { if (!is_object($res)) {
return $res; return $res;
} }
...@@ -54,28 +100,31 @@ function getAdminGroupAttribute($params) { ...@@ -54,28 +100,31 @@ function getAdminGroupAttribute($params) {
$resultArray['ID'] = $row->id; $resultArray['ID'] = $row->id;
$resultArray['Name'] = $row->name; $resultArray['Name'] = $row->name;
$resultArray['Operator'] = $row->operator;
$resultArray['Value'] = $row->value;
$resultArray['Disabled'] = $row->disabled;
return $resultArray; return $resultArray;
} }
# Return list of attributes # Return list of attributes
function getAdminGroupAttributes($params) { function getAdminGroupAttributes($params) {
global $db;
# Filters and sorts are the same here # Filters and sorts are the same here
$filtersorts = array( $filtersorts = array(
'ID' => 'group_attributes.ID', 'ID' => '@TP@group_attributes.ID',
'Name' => 'group_attributes.Name', 'Name' => '@TP@group_attributes.Name',
'Operator' => 'group_attributes.Operator', 'Operator' => '@TP@group_attributes.Operator',
'Value' => 'group_attributes.Value', 'Value' => '@TP@group_attributes.Value',
'Disabled' => 'group_attributes.Disabled' 'Disabled' => '@TP@group_attributes.Disabled'
); );
# Fetch attributes
$res = DBSelectSearch(" $res = DBSelectSearch("
SELECT SELECT
ID, Name, Operator, Value, Disabled ID, Name, Operator, Value, Disabled
FROM FROM
group_attributes @TP@group_attributes
WHERE WHERE
GroupID = ".DBQuote($params[0])." GroupID = ".DBQuote($params[0])."
",$params[1],$filtersorts,$filtersorts); ",$params[1],$filtersorts,$filtersorts);
...@@ -88,7 +137,7 @@ function getAdminGroupAttributes($params) { ...@@ -88,7 +137,7 @@ function getAdminGroupAttributes($params) {
$resultArray = array(); $resultArray = array();
# loop through rows # Loop through rows
while ($row = $sth->fetchObject()) { while ($row = $sth->fetchObject()) {
$item = array(); $item = array();
...@@ -98,11 +147,12 @@ function getAdminGroupAttributes($params) { ...@@ -98,11 +147,12 @@ function getAdminGroupAttributes($params) {
$item['Value'] = $row->value; $item['Value'] = $row->value;
$item['Disabled'] = $row->disabled; $item['Disabled'] = $row->disabled;
# push this row onto array # Push this row onto array
array_push($resultArray,$item); array_push($resultArray,$item);
} }
# Return results
return array($resultArray,$numResults); return array($resultArray,$numResults);
} }
?> # vim: ts=4
<?php <?php
# Admin Group Members functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php"); include_once("include/db.php");
# Add group attribute # Remove group member
function addAdminGroupMember($params) {
global $db;
$res = DBDo("INSERT INTO group_attributes (GroupID,Name) VALUES (?,?)",array($params[0]['GroupID'],$params[0]['Name']));
if (!is_numeric($res)) {
return $res;
}
return NULL;
}
# Remove group attribute
function removeAdminGroupMember($params) { function removeAdminGroupMember($params) {
global $db;
$res = DBDo("DELETE FROM users_to_groups WHERE ID = ?",array($params[0])); $res = DBDo("DELETE FROM @TP@users_to_groups WHERE ID = ?",array($params[0]));
if (!is_numeric($res)) {
return $res;
}
return NULL; # Return result
} if ($res !== TRUE) {
# Edit attribute
function updateAdminGroupMember($params) {
global $db;
$res = DBDo("UPDATE group_attributes SET Name = ? WHERE ID = ?",array($params[0]['Name'],$params[0]['ID']));
if (!is_numeric($res)) {
return $res; return $res;
} }
return NULL; return NULL;
} }
# Return specific attribute row # Return list of members
function getAdminGroupMember($params) {
global $db;
$res = DBSelect("SELECT ID, Name FROM group_attributes WHERE ID = ?",array($params[0]));
if (!is_object($res)) {
return $res;
}
$resultArray = array();
$row = $res->fetchObject();
$resultArray['ID'] = $row->id;
$resultArray['Name'] = $row->name;
return $resultArray;
}
# Return list of attributes
function getAdminGroupMembers($params) { function getAdminGroupMembers($params) {
global $db;
# Filters and sorts are the same here # Filters and sorts are the same here
$filtersorts = array( $filtersorts = array(
'ID' => 'users_to_groups.ID', 'ID' => '@TP@users_to_groups.ID',
'Name' => 'group_attributes.Name', 'Username' => '@TP@group_attributes.Username',
'Disabled' => 'group_attributes.Disabled' 'Disabled' => '@TP@group_attributes.Disabled'
); );
# Fetch members
$res = DBSelectSearch(" $res = DBSelectSearch("
SELECT SELECT
ID, Name, Operator, Value, Disabled @TP@users_to_groups.ID, @TP@users.Username, @TP@users.Disabled
FROM FROM
group_attributes @TP@users_to_groups, @TP@users
WHERE WHERE
GroupID = ".DBQuote($params[0])." @TP@users.ID = @TP@users_to_groups.UserID
AND
@TP@users_to_groups.GroupID = ".DBQuote($params[0])."
",$params[1],$filtersorts,$filtersorts); ",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1]; $sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data # If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) { if (!isset($sth)) {
return $res; return $res;
} }
$resultArray = array();
# loop through rows # Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) { while ($row = $sth->fetchObject()) {
$item = array(); $item = array();
$item['ID'] = $row->id; $item['ID'] = $row->id;
$item['Name'] = $row->name; $item['Username'] = $row->username;
$item['Disabled'] = $row->disabled; $item['Disabled'] = $row->disabled;
# push this row onto array # Push this row onto array
array_push($resultArray,$item); array_push($resultArray,$item);
} }
return array($resultArray,$numResults); return array($resultArray,$numResults);
} }
?> # vim: ts=4
<?php <?php
# Admin Groups functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php"); include_once("include/db.php");
# Return list of groups # Return list of groups
function getAdminGroups($params) { function getAdminGroups($params) {
global $db;
# Filters and sorts are the same here # Filters and sorts are the same here
$filtersorts = array( $filtersorts = array(
'ID' => 'groups.ID', 'ID' => '@TP@groups.ID',
'Name' => 'groups.Name', 'Name' => '@TP@groups.Name',
'Priority' => 'groups.Priority', 'Priority' => '@TP@groups.Priority',
'Disabled' => 'groups.Disabled', 'Disabled' => '@TP@groups.Disabled',
'Comment' => 'groups.Comment' 'Comment' => '@TP@groups.Comment'
); );
$res = DBSelectSearch("SELECT ID, Name, Priority, Disabled, Comment FROM groups",$params[1],$filtersorts,$filtersorts); # Perform query
$res = DBSelectSearch("SELECT ID, Name, Priority, Disabled, Comment FROM @TP@groups",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1]; $sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data # If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) { if (!isset($sth)) {
return $res; return $res;
} }
# Loop through rows
$resultArray = array(); $resultArray = array();
# loop through rows
while ($row = $sth->fetchObject()) { while ($row = $sth->fetchObject()) {
$item = array(); $item = array();
...@@ -35,25 +51,27 @@ function getAdminGroups($params) { ...@@ -35,25 +51,27 @@ function getAdminGroups($params) {
$item['Disabled'] = $row->disabled; $item['Disabled'] = $row->disabled;
$item['Comment'] = $row->comment; $item['Comment'] = $row->comment;
# push this row onto array # Push this row onto array
array_push($resultArray,$item); array_push($resultArray,$item);
} }
# Return results
return array($resultArray,$numResults); return array($resultArray,$numResults);
} }
# Return specific group row # Return specific group row
function getAdminGroup($params) { function getAdminGroup($params) {
global $db;
# Perform query
$res = DBSelect("SELECT ID, Name, Priority, Disabled, Comment FROM @TP@groups WHERE ID = ?",array($params[0]));
$res = DBSelect("SELECT ID, Name, Priority, Disabled, Comment FROM groups WHERE ID = ?",array($params[0])); # Return error if failed
if (!is_object($res)) { if (!is_object($res)) {
return $res; return $res;
} }
# Build array of results
$resultArray = array(); $resultArray = array();
$row = $res->fetchObject(); $row = $res->fetchObject();
$resultArray['ID'] = $row->id; $resultArray['ID'] = $row->id;
...@@ -62,16 +80,35 @@ function getAdminGroup($params) { ...@@ -62,16 +80,35 @@ function getAdminGroup($params) {
$resultArray['Disabled'] = $row->disabled; $resultArray['Disabled'] = $row->disabled;
$resultArray['Comment'] = $row->comment; $resultArray['Comment'] = $row->comment;
# Return results
return $resultArray; return $resultArray;
} }
# Remove admin group # Remove admin group
function removeAdminGroup($params) { function removeAdminGroup($params) {
global $db;
$res = DBDo("DELETE FROM groups WHERE ID = ?",array($params[0])); # Begin transaction
if (!is_numeric($res)) { DBBegin();
# Unlink users from group
$res = DBDo("DELETE FROM @TP@users_to_groups WHERE GroupID = ?",array($params[0]));
# Delete group attribtues
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@group_attributes WHERE GroupID = ?",array($params[0]));
}
# Delete group
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@groups WHERE ID = ?",array($params[0]));
}
# Return result
if ($res !== TRUE) {
DBRollback();
return $res; return $res;
} else {
DBCommit();
} }
return NULL; return NULL;
...@@ -79,10 +116,12 @@ function removeAdminGroup($params) { ...@@ -79,10 +116,12 @@ function removeAdminGroup($params) {
# Add admin group # Add admin group
function createAdminGroup($params) { function createAdminGroup($params) {
global $db;
$res = DBDo("INSERT INTO groups (Name) VALUES (?)",array($params[0]['Name'])); # Perform query
if (!is_numeric($res)) { $res = DBDo("INSERT INTO @TP@groups (Name) VALUES (?)",array($params[0]['Name']));
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
...@@ -91,14 +130,16 @@ function createAdminGroup($params) { ...@@ -91,14 +130,16 @@ function createAdminGroup($params) {
# Edit admin group # Edit admin group
function updateAdminGroup($params) { function updateAdminGroup($params) {
global $db;
$res = DBDo("UPDATE groups SET Name = ? WHERE ID = ?",array($params[0]['Name'],$params[0]['ID'])); # Perform query
if (!is_numeric($res)) { $res = DBDo("UPDATE @TP@groups SET Name = ? WHERE ID = ?",array($params[0]['Name'],$params[0]['ID']));
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
return NULL; return NULL;
} }
?> # vim: ts=4
<?php <?php
# Admin Realm Attributes functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php"); include_once("include/db.php");
# Add user attribute # Add realm attribute
function addAdminRealmAttribute($params) { function addAdminRealmAttribute($params) {
global $db;
$res = DBDo("INSERT INTO realm_attributes (RealmID,Name) VALUES (?,?)",array($params[0]['RealmID'],$params[0]['Name'])); # Perform query
if (!is_numeric($res)) { $res = DBDo("
INSERT INTO
@TP@realm_attributes (RealmID,Name,Operator,Value,Disabled)
VALUES
(?,?,?,?,?)",
array( $params[0]['RealmID'],
$params[0]['Name'],
$params[0]['Operator'],
$params[0]['Value'],
$params[0]['Disabled'])
);
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
return NULL; return NULL;
} }
# Remove user attribute # Remove realm attribute
function removeAdminRealmAttribute($params) { function removeAdminRealmAttribute($params) {
global $db;
$res = DBDo("DELETE FROM realm_attributes WHERE ID = ?",array($params[0])); # Perform query
if (!is_numeric($res)) { $res = DBDo("DELETE FROM @TP@realm_attributes WHERE ID = ?",array($params[0]));
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
return NULL; return NULL;
} }
# Edit attribute # Edit realm attribute
function updateAdminRealmAttribute($params) { function updateAdminRealmAttribute($params) {
global $db;
$res = DBDo("UPDATE realm_attributes SET Name = ? WHERE ID = ?",array($params[0]['Name'],$params[0]['ID'])); # Perform query
if (!is_numeric($res)) { $res = DBDo("UPDATE @TP@realm_attributes SET Name = ?, Operator = ?, Value = ?, Disabled = ? WHERE ID = ?",
array($params[0]['Name'],
$params[0]['Operator'],
$params[0]['Value'],
$params[0]['Disabled'],
$params[0]['ID'])
);
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
...@@ -40,55 +78,59 @@ function updateAdminRealmAttribute($params) { ...@@ -40,55 +78,59 @@ function updateAdminRealmAttribute($params) {
# Return specific attribute row # Return specific attribute row
function getAdminRealmAttribute($params) { function getAdminRealmAttribute($params) {
global $db;
# Perform query
$res = DBSelect("SELECT ID, Name, Operator, Value, Disabled FROM @TP@realm_attributes WHERE ID = ?",array($params[0]));
$res = DBSelect("SELECT ID, Name FROM realm_attributes WHERE ID = ?",array($params[0])); # Return error if failed
if (!is_object($res)) { if (!is_object($res)) {
return $res; return $res;
} }
# Build array of results
$resultArray = array(); $resultArray = array();
$row = $res->fetchObject(); $row = $res->fetchObject();
$resultArray['ID'] = $row->id; $resultArray['ID'] = $row->id;
$resultArray['Name'] = $row->name; $resultArray['Name'] = $row->name;
$resultArray['Operator'] = $row->operator;
$resultArray['Value'] = $row->value;
$resultArray['Disabled'] = $row->disabled;
# Return results
return $resultArray; return $resultArray;
} }
# Return list of attributes # Return list of attributes
function getAdminRealmAttributes($params) { function getAdminRealmAttributes($params) {
global $db;
# Filters and sorts are the same here # Filters and sorts are the same here
$filtersorts = array( $filtersorts = array(
'ID' => 'realm_attributes.ID', 'ID' => '@TP@realm_attributes.ID',
'Name' => 'realm_attributes.Name', 'Name' => '@TP@realm_attributes.Name',
'Operator' => 'realm_attributes.Operator', 'Operator' => '@TP@realm_attributes.Operator',
'Value' => 'realm_attributes.Value', 'Value' => '@TP@realm_attributes.Value',
'Disabled' => 'realm_attributes.Disabled' 'Disabled' => '@TP@realm_attributes.Disabled'
); );
# Perform query
$res = DBSelectSearch(" $res = DBSelectSearch("
SELECT SELECT
ID, Name, Operator, Value, Disabled ID, Name, Operator, Value, Disabled
FROM FROM
realm_attributes @TP@realm_attributes
WHERE WHERE
RealmID = ".DBQuote($params[0])." RealmID = ".DBQuote($params[0])."
",$params[1],$filtersorts,$filtersorts); ",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1]; $sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data # If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) { if (!isset($sth)) {
return $res; return $res;
} }
# Loop through rows
$resultArray = array(); $resultArray = array();
# loop through rows
while ($row = $sth->fetchObject()) { while ($row = $sth->fetchObject()) {
$item = array(); $item = array();
...@@ -98,11 +140,12 @@ function getAdminRealmAttributes($params) { ...@@ -98,11 +140,12 @@ function getAdminRealmAttributes($params) {
$item['Value'] = $row->value; $item['Value'] = $row->value;
$item['Disabled'] = $row->disabled; $item['Disabled'] = $row->disabled;
# push this row onto array # Push this row onto array
array_push($resultArray,$item); array_push($resultArray,$item);
} }
# Return results
return array($resultArray,$numResults); return array($resultArray,$numResults);
} }
?> # vim: ts=4
<?php <?php
# Database Interface # Admin Realm Members functions
# Copyright (C) 2007-2009, AllWorldIT # Copyright (C) 2007-2011, AllWorldIT
# #
# This program is free software; you can redistribute it and/or modify # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU General Public License as published by
...@@ -16,52 +16,63 @@ ...@@ -16,52 +16,63 @@
# with this program; if not, write to the Free Software Foundation, Inc., # with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
require_once('includes/config.php'); include_once("include/db.php");
# Remove realm member
function removeAdminRealmMember($params) {
# Connect to DB $res = DBDo("DELETE FROM @TP@clients_to_realms WHERE ID = ?",array($params[0]));
function connect_db()
{
global $DB_DSN;
global $DB_USER;
global $DB_PASS;
try { # Return result
$dbh = new PDO($DB_DSN, $DB_USER, $DB_PASS, array( if ($res !== TRUE) {
PDO::ATTR_PERSISTENT => false return $res;
));
$dbh->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
} catch (PDOException $e) {
die("Error connecting to Policyd v2 DB: " . $e->getMessage());
} }
return $dbh; return NULL;
} }
# Return list of members
function getAdminRealmMembers($params) {
# Connect to postfix DB # Filters and sorts are the same here
function connect_postfix_db() $filtersorts = array(
{ 'ID' => '@TP@clients_to_realms.ID',
global $DB_POSTFIX_DSN; 'Name' => '@TP@realm_attributes.Name'
global $DB_POSTFIX_USER; );
global $DB_POSTFIX_PASS;
try { # Fetch members
$dbh = new PDO($DB_POSTFIX_DSN, $DB_POSTFIX_USER, $DB_POSTFIX_PASS, array( $res = DBSelectSearch("
PDO::ATTR_PERSISTENT => false SELECT
)); @TP@clients_to_realms.ID, @TP@clients.Name
FROM
@TP@clients_to_realms, @TP@clients
WHERE
@TP@clients.ID = @TP@clients_to_realms.ClientID
AND
@TP@clients_to_realms.RealmID = ".DBQuote($params[0])."
",$params[1],$filtersorts,$filtersorts);
$dbh->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER); $sth = $res[0]; $numResults = $res[1];
} catch (PDOException $e) { # If STH is blank, return the error back to whoever requested the data
die("Error connecting to Postfix DB: " . $e->getMessage()); if (!isset($sth)) {
return $res;
} }
return $dbh;
}
# Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) {
$item = array();
$item['ID'] = $row->id;
$item['Name'] = $row->name;
# Push this row onto array
array_push($resultArray,$item);
}
return array($resultArray,$numResults);
}
# vim: ts=4 # vim: ts=4
?>
<?php <?php
# Admin Realms functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php"); include_once("include/db.php");
# Return list of realms # Return list of realms
function getAdminRealms($params) { function getAdminRealms($params) {
global $db;
# Filters and sorts are the same here # Filters and sorts are the same here
$filtersorts = array( $filtersorts = array(
'ID' => 'realms.ID', 'ID' => '@TP@realms.ID',
'Name' => 'realms.Name', 'Name' => '@TP@realms.Name',
'Disabled' => 'realms.Disabled' 'Disabled' => '@TP@realms.Disabled'
); );
$res = DBSelectSearch("SELECT ID, Name, Disabled FROM realms",$params[1],$filtersorts,$filtersorts); # Perform query
$res = DBSelectSearch("SELECT ID, Name, Disabled FROM @TP@realms",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1]; $sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data # If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) { if (!isset($sth)) {
return $res; return $res;
} }
# Loop through rows
$resultArray = array(); $resultArray = array();
# loop through rows
while ($row = $sth->fetchObject()) { while ($row = $sth->fetchObject()) {
$item = array(); $item = array();
$item['ID'] = $row->id; $item['ID'] = $row->id;
$item['Name'] = $row->name; $item['Name'] = htmlspecialchars($row->name);
$item['Disabled'] = $row->disabled; $item['Disabled'] = $row->disabled;
# push this row onto array # Push this row onto array
array_push($resultArray,$item); array_push($resultArray,$item);
} }
# Return results
return array($resultArray,$numResults); return array($resultArray,$numResults);
} }
# Return specific realm row # Return specific realm row
function getAdminRealm($params) { function getAdminRealm($params) {
global $db;
# Perform query
$res = DBSelect("SELECT ID, Name, Disabled FROM @TP@realms WHERE ID = ?",array($params[0]));
$res = DBSelect("SELECT ID, Name, Disabled FROM realms WHERE ID = ?",array($params[0])); # Return error if failed
if (!is_object($res)) { if (!is_object($res)) {
return $res; return $res;
} }
# Build array of results
$resultArray = array(); $resultArray = array();
$row = $res->fetchObject(); $row = $res->fetchObject();
$resultArray['ID'] = $row->id; $resultArray['ID'] = $row->id;
$resultArray['Name'] = $row->name; $resultArray['Name'] = $row->name;
$resultArray['Disabled'] = $row->disabled; $resultArray['Disabled'] = $row->disabled;
# Return results
return $resultArray; return $resultArray;
} }
# Remove admin realm # Remove admin realm
function removeAdminRealm($params) { function removeAdminRealm($params) {
global $db;
$res = DBDo("DELETE FROM realms WHERE ID = ?",array($params[0])); # Begin transaction
if (!is_numeric($res)) { DBBegin();
# Perform query
$res = DBDo("DELETE FROM @TP@realm_attributes WHERE RealmID = ?",array($params[0]));
# Perform next query if successful
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@realms WHERE ID = ?",array($params[0]));
}
# Return result
if ($res !== TRUE) {
DBRollback();
return $res; return $res;
} else {
DBCommit();
} }
return NULL; return NULL;
...@@ -73,10 +105,12 @@ function removeAdminRealm($params) { ...@@ -73,10 +105,12 @@ function removeAdminRealm($params) {
# Add admin realm # Add admin realm
function createAdminRealm($params) { function createAdminRealm($params) {
global $db;
$res = DBDo("INSERT INTO realms (Name) VALUES (?)",array($params[0]['Name'])); # Perform query
if (!is_numeric($res)) { $res = DBDo("INSERT INTO @TP@realms (Name) VALUES (?)",array($params[0]['Name']));
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
...@@ -85,14 +119,16 @@ function createAdminRealm($params) { ...@@ -85,14 +119,16 @@ function createAdminRealm($params) {
# Edit admin realm # Edit admin realm
function updateAdminRealm($params) { function updateAdminRealm($params) {
global $db;
$res = DBDo("UPDATE realms SET Name = ? WHERE ID = ?",array($params[0]['Name'],$params[0]['ID'])); # Perform query
if (!is_numeric($res)) { $res = DBDo("UPDATE @TP@realms SET Name = ? WHERE ID = ?",array($params[0]['Name'],$params[0]['ID']));
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
return NULL; return NULL;
} }
?> # vim: ts=4
<?php <?php
# Admin User Attributes functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php"); include_once("include/db.php");
include_once("include/util.php");
# Add user attribute # Add user attribute
function addAdminUserAttribute($params) { function addAdminUserAttribute($params) {
global $db;
$res = DBDo("INSERT INTO user_attributes (UserID,Name) VALUES (?,?)",array($params[0]['UserID'],$params[0]['Name'])); # Check Disabled param
if (!is_numeric($res)) { $disabled = isBoolean($params[0]['Disabled']);
if ($disabled < 0) {
return NULL;
}
# Perform query
$res = DBDo("
INSERT INTO
@TP@user_attributes (UserID,Name,Operator,Value,Disabled)
VALUES
(?,?,?,?,?)",
array( $params[0]['UserID'],
$params[0]['Name'],
$params[0]['Operator'],
$params[0]['Value'],
$disabled)
);
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
...@@ -16,10 +51,12 @@ function addAdminUserAttribute($params) { ...@@ -16,10 +51,12 @@ function addAdminUserAttribute($params) {
# Remove user attribute # Remove user attribute
function removeAdminUserAttribute($params) { function removeAdminUserAttribute($params) {
global $db;
$res = DBDo("DELETE FROM user_attributes WHERE ID = ?",array($params[0])); # Perform query
if (!is_numeric($res)) { $res = DBDo("DELETE FROM @TP@user_attributes WHERE ID = ?",array($params[0]));
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
...@@ -28,10 +65,24 @@ function removeAdminUserAttribute($params) { ...@@ -28,10 +65,24 @@ function removeAdminUserAttribute($params) {
# Edit attribute # Edit attribute
function updateAdminUserAttribute($params) { function updateAdminUserAttribute($params) {
global $db;
$res = DBDo("UPDATE user_attributes SET Name = ? WHERE ID = ?",array($params[0]['Name'],$params[0]['ID'])); # Check Disabled param
if (!is_numeric($res)) { $disabled = isBoolean($params[0]['Disabled']);
if ($disabled < 0) {
return NULL;
}
# Perform query
$res = DBDo("UPDATE @TP@user_attributes SET Name = ?, Operator = ?, Value = ?, Disabled = ? WHERE ID = ?",
array($params[0]['Name'],
$params[0]['Operator'],
$params[0]['Value'],
$disabled,
$params[0]['ID'])
);
# Return error
if ($res !== TRUE) {
return $res; return $res;
} }
...@@ -40,55 +91,59 @@ function updateAdminUserAttribute($params) { ...@@ -40,55 +91,59 @@ function updateAdminUserAttribute($params) {
# Return specific attribute row # Return specific attribute row
function getAdminUserAttribute($params) { function getAdminUserAttribute($params) {
global $db;
# Perform query
$res = DBSelect("SELECT ID, Name, Operator, Value, Disabled FROM @TP@user_attributes WHERE ID = ?",array($params[0]));
$res = DBSelect("SELECT ID, Name FROM user_attributes WHERE ID = ?",array($params[0])); # Return error if failed
if (!is_object($res)) { if (!is_object($res)) {
return $res; return $res;
} }
# Build array of results
$resultArray = array(); $resultArray = array();
$row = $res->fetchObject(); $row = $res->fetchObject();
$resultArray['ID'] = $row->id; $resultArray['ID'] = $row->id;
$resultArray['Name'] = $row->name; $resultArray['Name'] = $row->name;
$resultArray['Operator'] = $row->operator;
$resultArray['Value'] = $row->value;
$resultArray['Disabled'] = $row->disabled;
# Return results
return $resultArray; return $resultArray;
} }
# Return list of attributes # Return list of attributes
function getAdminUserAttributes($params) { function getAdminUserAttributes($params) {
global $db;
# Filters and sorts are the same here # Filters and sorts are the same here
$filtersorts = array( $filtersorts = array(
'ID' => 'user_attributes.ID', 'ID' => '@TP@user_attributes.ID',
'Name' => 'user_attributes.Name', 'Name' => '@TP@user_attributes.Name',
'Operator' => 'user_attributes.Operator', 'Operator' => '@TP@user_attributes.Operator',
'Value' => 'user_attributes.Value', 'Value' => '@TP@user_attributes.Value',
'Disabled' => 'user_attributes.Disabled' 'Disabled' => '@TP@user_attributes.Disabled'
); );
# Perform query
$res = DBSelectSearch(" $res = DBSelectSearch("
SELECT SELECT
ID, Name, Operator, Value, Disabled ID, Name, Operator, Value, Disabled
FROM FROM
user_attributes @TP@user_attributes
WHERE WHERE
UserID = ".DBQuote($params[0])." UserID = ".DBQuote($params[0])."
",$params[1],$filtersorts,$filtersorts); ",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1]; $sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data # If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) { if (!isset($sth)) {
return $res; return $res;
} }
# Loop through rows
$resultArray = array(); $resultArray = array();
# loop through rows
while ($row = $sth->fetchObject()) { while ($row = $sth->fetchObject()) {
$item = array(); $item = array();
...@@ -98,11 +153,12 @@ function getAdminUserAttributes($params) { ...@@ -98,11 +153,12 @@ function getAdminUserAttributes($params) {
$item['Value'] = $row->value; $item['Value'] = $row->value;
$item['Disabled'] = $row->disabled; $item['Disabled'] = $row->disabled;
# push this row onto array # Push this row onto array
array_push($resultArray,$item); array_push($resultArray,$item);
} }
# Return results
return array($resultArray,$numResults); return array($resultArray,$numResults);
} }
?> # vim: ts=4
<?php <?php
# Admin User Groups functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php"); include_once("include/db.php");
# Link user to group # Link user to group
function addAdminUserGroup($params) { function addAdminUserGroup($params) {
global $db;
$res = DBDo("INSERT INTO users_to_groups (UserID,GroupID) VALUES (?,?)",array($params[0]['UserID'],$params[0]['GroupID'])); # Perform query
if (!is_numeric($res)) { $res = DBDo("INSERT INTO @TP@users_to_groups (UserID,GroupID) VALUES (?,?)",array($params[0]['UserID'],$params[0]['GroupID']));
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
...@@ -17,10 +35,12 @@ function addAdminUserGroup($params) { ...@@ -17,10 +35,12 @@ function addAdminUserGroup($params) {
# Unlink user from group # Unlink user from group
function removeAdminUserGroup($params) { function removeAdminUserGroup($params) {
global $db;
$res = DBDo("DELETE FROM users_to_groups WHERE ID = ?",array($params[0])); # Perform query
if (!is_numeric($res)) { $res = DBDo("DELETE FROM @TP@users_to_groups WHERE ID = ?",array($params[0]));
# Return result
if ($res !== TRUE) {
return $res; return $res;
} }
...@@ -29,44 +49,44 @@ function removeAdminUserGroup($params) { ...@@ -29,44 +49,44 @@ function removeAdminUserGroup($params) {
# Return list of groups # Return list of groups
function getAdminUserGroups($params) { function getAdminUserGroups($params) {
global $db;
# Filters and sorts are the same here # Filters and sorts are the same here
$filtersorts = array( $filtersorts = array(
'ID' => 'users_to_groups.ID', 'ID' => '@TP@users_to_groups.ID',
'Name' => 'groups.Name' 'Name' => '@TP@groups.Name'
); );
# Perform query
$res = DBSelectSearch(" $res = DBSelectSearch("
SELECT SELECT
users_to_groups.ID, groups.Name @TP@users_to_groups.ID, @TP@groups.Name
FROM FROM
users_to_groups, groups @TP@users_to_groups, @TP@groups
WHERE WHERE
groups.ID = users_to_groups.GroupID @TP@users_to_groups.GroupID = @TP@groups.ID
AND users_to_groups.UserID = ".DBQuote($params[0])." AND @TP@users_to_groups.UserID = ".DBQuote($params[0])."
",$params[1],$filtersorts,$filtersorts); ",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1]; $sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data # If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) { if (!isset($sth)) {
return $res; return $res;
} }
# Loop through rows
$resultArray = array(); $resultArray = array();
# loop through rows
while ($row = $sth->fetchObject()) { while ($row = $sth->fetchObject()) {
$item = array(); $item = array();
$item['ID'] = $row->id; $item['ID'] = $row->id;
$item['Name'] = $row->name; $item['Name'] = $row->name;
# push this row onto array # Push this row onto array
array_push($resultArray,$item); array_push($resultArray,$item);
} }
# Return results
return array($resultArray,$numResults); return array($resultArray,$numResults);
} }
?> # vim: ts=4
<?php
# Admin User Logs functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php");
# Return user logs summary
function getAdminUserLogsSummary($params) {
# Get group attributes
# fixme - user might be member of multiple groups
$res = DBSelect("
SELECT
@TP@group_attributes.Name,
@TP@group_attributes.Value
FROM
@TP@group_attributes, @TP@users_to_groups, @TP@groups
WHERE
@TP@group_attributes.GroupID = @TP@groups.ID
AND @TP@groups.ID = @TP@users_to_groups.GroupID
AND @TP@users_to_groups.UserID = ?",
array($params[0]['ID'])
);
# Return if error
if (!is_object($res)) {
return $res;
}
# Fetch uptime and traffic limits, if not found, this is prepaid account.. use -1 as we need int
$trafficCap = -1;
$uptimeCap = -1;
while ($row = $res->fetchObject()) {
if ($row->name == 'SMRadius-Capping-Traffic-Limit') {
$trafficCap = (int)$row->value;
}
if ($row->name == 'SMRadius-Capping-Uptime-Limit') {
$uptimeCap = (int)$row->value;
}
}
# Get user attributes
$res = DBSelect("
SELECT
Name,
Value
FROM
@TP@user_attributes
WHERE
UserID = ?",
array($params[0]['ID'])
);
# Return if error
if (!is_object($res)) {
return $res;
}
# Fetch uptime and traffic limits, if not found, this is prepaid account.. use -1 as we need int
while ($row = $res->fetchObject()) {
if ($row->name == 'SMRadius-Capping-Traffic-Limit') {
$trafficCap = (int)$row->value;
}
if ($row->name == 'SMRadius-Capping-Uptime-Limit') {
$uptimeCap = (int)$row->value;
}
}
# Add caps to result
$resultArray = array();
$resultArray['trafficCap'] = $trafficCap;
$resultArray['uptimeCap'] = $uptimeCap;
# Dates we want to use to search search
$periodKey = new DateTime($params[0]['PeriodKey']."-01");
# Return if error
if (!is_object($periodKey)) {
return $periodKey;
}
# Fetch user uptime and traffic summary
$res = DBSelect("
SELECT
@TP@topups_summary.Balance,
@TP@topups.ID,
@TP@topups.Type,
@TP@topups.Value,
@TP@topups.ValidTo
FROM
@TP@topups_summary,
@TP@topups
WHERE
@TP@topups_summary.TopupID = @TP@topups.ID
AND @TP@topups.UserID = ?
AND @TP@topups_summary.PeriodKey = ?
AND @TP@topups_summary.Depleted = 0
ORDER BY
@TP@topups.Timestamp ASC",
array($params[0]['ID'],$periodKey->format('Y-m'))
);
# Return if error
if (!is_object($res)) {
return $res;
}
# Store summary topups
$topups = array();
$i = 0;
while ($row = $res->fetchObject()) {
$topups[$i] = array();
$topups[$i]['ID'] = $row->id;
$topups[$i]['ValidTo'] = $row->validto;
$topups[$i]['Type'] = $row->type;
$topups[$i]['CurrentLimit'] = $row->balance;
$topups[$i]['Limit'] = $row->value;
$i++;
}
# Fetch user uptime and traffic topups
$periodKeyEnd = new DateTime($periodKey->format('Y-m-d'));
$periodKeyEnd->modify("+1 month");
$res = DBSelect("
SELECT
ID, Value, Type, ValidTo
FROM
@TP@topups
WHERE
UserID = ?
AND ValidFrom = ?
AND ValidTo >= ?
AND Depleted = 0
ORDER BY
Timestamp ASC",
array($params[0]['ID'],$periodKey->format('Y-m-d'),$periodKeyEnd->format('Y-m-d'))
);
# Return if error
if (!is_object($res)) {
return $res;
}
# Store normal topups
while ($row = $res->fetchObject()) {
$topups[$i] = array();
$topups[$i]['ID'] = $row->id;
$topups[$i]['ValidTo'] = $row->validto;
$topups[$i]['Type'] = $row->type;
$topups[$i]['Limit'] = $row->value;
$i++;
}
$res = DBSelect("
SELECT
SUM(@TP@accounting.AcctSessionTime) / 60 AS TotalSessionTime,
SUM(@TP@accounting.AcctInputOctets) / 1024 / 1024 +
SUM(@TP@accounting.AcctInputGigawords) * 4096 +
SUM(@TP@accounting.AcctOutputOctets) / 1024 / 1024 +
SUM(@TP@accounting.AcctOutputGigawords) * 4096 AS TotalTraffic
FROM
@TP@accounting, @TP@users
WHERE
@TP@users.ID = ?
AND @TP@accounting.PeriodKey = ?
AND @TP@accounting.Username = @TP@users.Username",
array($params[0]['ID'],$periodKey->format('Y-m'))
);
if (!is_object($res)) {
return $res;
}
# Set total traffic and uptime used
$row = $res->fetchObject();
# Add usage to our return array
$resultArray['trafficUsage'] = 0;
$resultArray['uptimeUsage'] = 0;
if (isset($row->totaltraffic) && $row->totaltraffic > 0) {
$resultArray['trafficUsage'] += $row->totaltraffic;
}
if (isset($row->totalsessiontime) && $row->totalsessiontime > 0) {
$resultArray['uptimeUsage'] += $row->totalsessiontime;
}
# Excess usage
$excessTraffic = 0;
if ($trafficCap == -1) {
$excessTraffic = $resultArray['trafficUsage'];
} else {
$excessTraffic = $resultArray['trafficUsage'] > $trafficCap ? ($resultArray['trafficUsage'] - $trafficCap) : 0;
}
$excessUptime = 0;
if ($uptimeCap == -1) {
$excessUptime = $resultArray['uptimeUsage'];
} else {
$excessUptime = $resultArray['uptimeUsage'] > $uptimeCap ? ($resultArray['uptimeUsage'] - $uptimeCap) : 0;
}
# Loop through topups and add to return array
$resultArray['trafficTopups'] = 0;
$resultArray['uptimeTopups'] = 0;
$resultArray['TotalTrafficTopups'] = 0;
$resultArray['TotalUptimeTopups'] = 0;
# Traffic and uptime topups
$resultArray['AllTrafficTopups'] = array();
$resultArray['AllUptimeTopups'] = array();
$t = 0; $u = 0;
foreach ($topups as $topupItem) {
if ($topupItem['Type'] == 1) {
# Topup not currently in use
if ($excessTraffic <= 0) {
# Add stats to topup array
$resultArray['AllTrafficTopups'][$t] = array();
$resultArray['AllTrafficTopups'][$t]['Used'] = isset($topupItem['CurrentLimit']) ? ($topupItem['Limit'] - $topupItem['CurrentLimit']) : 0;
$resultArray['AllTrafficTopups'][$t]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllTrafficTopups'][$t]['ID'] = $topupItem['ID'];
$resultArray['AllTrafficTopups'][$t]['ValidTo'] = $topupItem['ValidTo'];
$t++;
# Set total available topups
$resultArray['trafficTopups'] += isset($topupItem['CurrentLimit']) ? $topupItem['CurrentLimit'] : $topupItem['Limit'];
$resultArray['TotalTrafficTopups'] += $topupItem['Limit'];
# Topup currently in use
} elseif (!isset($topupItem['CurrentLimit']) && $excessTraffic < $topupItem['Limit']) {
# Add stats to topup array
$resultArray['AllTrafficTopups'][$t] = array();
$resultArray['AllTrafficTopups'][$t]['Used'] = $excessTraffic;
$resultArray['AllTrafficTopups'][$t]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllTrafficTopups'][$t]['ID'] = $topupItem['ID'];
$resultArray['AllTrafficTopups'][$t]['ValidTo'] = $topupItem['ValidTo'];
$t++;
# Set total available topups
$resultArray['trafficTopups'] += $topupItem['Limit'];
$resultArray['TotalTrafficTopups'] += $topupItem['Limit'];
# If we hit this topup then all the rest of them are available
$excessTraffic = 0;
} elseif (isset($topupItem['CurrentLimit']) && $excessTraffic < $topupItem['CurrentLimit']) {
# Add stats to topup array
$resultArray['AllTrafficTopups'][$t] = array();
$resultArray['AllTrafficTopups'][$t]['Used'] = ($topupItem['Limit'] - $topupItem['CurrentLimit']) + $excessTraffic;
$resultArray['AllTrafficTopups'][$t]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllTrafficTopups'][$t]['ID'] = $topupItem['ID'];
$resultArray['AllTrafficTopups'][$t]['ValidTo'] = $topupItem['ValidTo'];
$t++;
# Set total available topups
$resultArray['trafficTopups'] += $topupItem['CurrentLimit'];
$resultArray['TotalTrafficTopups'] += $topupItem['Limit'];
# If we hit this topup then all the rest of them are available
$excessTraffic = 0;
# Topup has been used up
} else {
# Add stats to topup array
$resultArray['AllTrafficTopups'][$t] = array();
$resultArray['AllTrafficTopups'][$t]['Used'] = (int)$topupItem['Limit'];
$resultArray['AllTrafficTopups'][$t]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllTrafficTopups'][$t]['ID'] = $topupItem['ID'];
$resultArray['AllTrafficTopups'][$t]['ValidTo'] = $topupItem['ValidTo'];
$t++;
$resultArray['trafficTopups'] += isset($topupItem['CurrentLimit']) ? $topupItem['CurrentLimit'] : $topupItem['Limit'];
$resultArray['TotalTrafficTopups'] += $topupItem['Limit'];
# Subtract this topup from excessTraffic usage
$excessTraffic -= isset($topupItem['CurrentLimit']) ? $topupItem['CurrentLimit'] : $topupItem['Limit'];
}
}
if ($topupItem['Type'] == 2) {
# Topup not currently in use
if ($excessUptime <= 0) {
# Add stats to topup array
$resultArray['AllUptimeTopups'][$u] = array();
$resultArray['AllUptimeTopups'][$u]['Used'] = isset($topupItem['CurrentLimit']) ? ($topupItem['Limit'] - $topupItem['CurrentLimit']) : 0;
$resultArray['AllUptimeTopups'][$u]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllUptimeTopups'][$u]['ID'] = $topupItem['ID'];
$resultArray['AllUptimeTopups'][$u]['ValidTo'] = $topupItem['ValidTo'];
$u++;
# Set total available topups
$resultArray['uptimeTopups'] += isset($topupItem['CurrentLimit']) ? $topupItem['CurrentLimit'] : $topupItem['Limit'];
$resultArray['TotalUptimeTopups'] += $topupItem['Limit'];
# Topup currently in use
} elseif (!isset($topupItem['CurrentLimit']) && $excessUptime < $topupItem['Limit']) {
# Add stats to topup array
$resultArray['AllUptimeTopups'][$u] = array();
$resultArray['AllUptimeTopups'][$u]['Used'] = $excessTraffic;
$resultArray['AllUptimeTopups'][$u]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllUptimeTopups'][$u]['ID'] = $topupItem['ID'];
$resultArray['AllUptimeTopups'][$u]['ValidTo'] = $topupItem['ValidTo'];
$u++;
# Set total available topups
$resultArray['uptimeTopups'] += $topupItem['Limit'];
$resultArray['TotalUptimeTopups'] += $topupItem['Limit'];
# If we hit this topup then all the rest of them are available
$excessUptime = 0;
} elseif (isset($topupItem['CurrentLimit']) && $excessUptime < $topupItem['CurrentLimit']) {
# Add stats to topup array
$resultArray['AllUptimeTopups'][$u] = array();
$resultArray['AllUptimeTopups'][$u]['Used'] = ($topupItem['Limit'] - $topupItem['CurrentLimit']) + $excessTraffic;
$resultArray['AllUptimeTopups'][$u]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllUptimeTopups'][$u]['ID'] = $topupItem['ID'];
$resultArray['AllUptimeTopups'][$u]['ValidTo'] = $topupItem['ValidTo'];
$u++;
# Set total available topups
$resultArray['uptimeTopups'] += $topupItem['CurrentLimit'];
$resultArray['TotalUptimeTopups'] += $topupItem['Limit'];
# If we hit this topup then all the rest of them are available
$excessUptime = 0;
# Topup has been used up
} else {
# Add stats to topup array
$resultArray['AllUptimeTopups'][$u] = array();
$resultArray['AllUptimeTopups'][$u]['Used'] = (int)$topupItem['Limit'];
$resultArray['AllUptimeTopups'][$u]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllUptimeTopups'][$u]['ID'] = $topupItem['ID'];
$resultArray['AllUptimeTopups'][$u]['ValidTo'] = $topupItem['ValidTo'];
$u++;
$resultArray['uptimeTopups'] += isset($topupItem['CurrentLimit']) ? $topupItem['CurrentLimit'] : $topupItem['Limit'];
$resultArray['TotalUptimeTopups'] += $topupItem['Limit'];
# Subtract this topup from excessUptime usage
$excessUptime -= isset($topupItem['CurrentLimit']) ? $topupItem['CurrentLimit'] : $topupItem['Limit'];
}
}
}
# Return results
return array($resultArray, 1);
}
# Return list of user logs
function getAdminUserLogs($params) {
# Filters and sorts are the same here
$filtersorts = array(
'ID' => '@TP@accounting.ID',
'EventTimestamp' => '@TP@accounting.EventTimestamp',
'AcctStatusType' => '@TP@accounting.AcctStatusType',
'ServiceType' => '@TP@accounting.ServiceType',
'FramedProtocol' => '@TP@accounting.FramedProtocol',
'NASPortType' => '@TP@accounting.NASPortType',
'NASPortID' => '@TP@accounting.NASPortID',
'CallingStationID' => '@TP@accounting.CallingStationID',
'CalledStationID' => '@TP@accounting.CalledStationID',
'AcctSessionID' => '@TP@accounting.AcctSessionID',
'FramedIPAddress' => '@TP@accounting.FramedIPAddress',
);
# Perform query
$res = DBSelectSearch("
SELECT
@TP@accounting.ID,
@TP@accounting.EventTimestamp,
@TP@accounting.AcctStatusType,
@TP@accounting.ServiceType,
@TP@accounting.FramedProtocol,
@TP@accounting.NASPortType,
@TP@accounting.NASPortID,
@TP@accounting.CallingStationID,
@TP@accounting.CalledStationID,
@TP@accounting.AcctSessionID,
@TP@accounting.FramedIPAddress,
@TP@accounting.AcctInputOctets / 1024 / 1024 +
@TP@accounting.AcctInputGigawords * 4096 AS AcctInput,
@TP@accounting.AcctOutputOctets / 1024 / 1024 +
@TP@accounting.AcctOutputGigawords * 4096 AS AcctOutput,
@TP@accounting.AcctTerminateCause,
@TP@accounting.AcctSessionTime / 60 AS AcctSessionTime
FROM
@TP@accounting, @TP@users
WHERE
@TP@users.Username = @TP@accounting.Username
AND
@TP@users.ID = ".DBQuote($params[0])."
",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) {
return $res;
}
# Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) {
# Input
$acctInput = 0;
if (isset($row->acctinput) && $row->acctinput > 0) {
$acctInput += $row->acctinput;
}
# Output
$acctOutput = 0;
if (isset($row->acctoutput) && $row->acctoutput > 0) {
$acctOutput += $row->acctoutput;
}
# Uptime
$acctSessionTime = 0;
if (isset($row->acctsessiontime) && $row->acctsessiontime > 0) {
$acctSessionTime += $row->acctsessiontime;
}
# Build array for this row
$item = array();
$item['ID'] = $row->id;
# Convert to ISO format
$date = new DateTime($row->eventtimestamp);
$value = $date->format("Y-m-d H:i:s");
$item['EventTimestamp'] = $value;
$item['AcctStatusType'] = $row->acctstatustype;
$item['ServiceType'] = $row->servicetype;
$item['FramedProtocol'] = $row->framedprotocol;
$item['NASPortType'] = $row->nasporttype;
$item['NASPortID'] = $row->nasportid;
$item['CallingStationID'] = $row->callingstationid;
$item['CalledStationID'] = $row->calledstationid;
$item['AcctSessionID'] = $row->acctsessionid;
$item['FramedIPAddress'] = $row->framedipaddress;
$item['AcctInput'] = $acctInput;
$item['AcctOutput'] = $acctOutput;
$item['AcctSessionTime'] = (int)$acctSessionTime;
$item['ConnectTermReason'] = strRadiusTermCode($row->acctterminatecause);
# Push this row onto main array
array_push($resultArray,$item);
}
# Return results
return array($resultArray,$numResults);
}
# vim: ts=4
<?php
# Admin User Topups functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php");
# Add new topup
function createAdminUserTopup($params) {
# Get today's date
$timestamp = date('Y-m-d H:i:s');
# Perform query
$res = DBDo("INSERT INTO @TP@topups (UserID,Timestamp,Type,Value,ValidFrom,ValidTo) VALUES (?,?,?,?,?,?)",
array($params[0]['UserID'],$timestamp,$params[0]['Type'],$params[0]['Value'],$params[0]['ValidFrom'],
$params[0]['ValidTo'])
);
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Edit topup
function updateAdminUserTopup($params) {
# Perform query
$res = DBDo("UPDATE @TP@topups SET Value = ?, Type = ?, ValidFrom = ?, ValidTo = ? WHERE ID = ?",
array($params[0]['Value'],
$params[0]['Type'],
$params[0]['ValidFrom'],
$params[0]['ValidTo'],
$params[0]['ID'])
);
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Delete user topup
function removeAdminUserTopup($params) {
# Delete topup summary
$res = DBDo("DELETE FROM @TP@topups_summary WHERE TopupID = ?",array($params[0]));
# Return result
if ($res !== TRUE) {
return $res;
}
# Delete topup
$res = DBDo("DELETE FROM @TP@topups WHERE ID = ?",array($params[0]));
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Return specific topup row
function getAdminUserTopup($params) {
# Perform query
$res = DBSelect("SELECT ID, Type, Value, ValidFrom, ValidTo FROM @TP@topups WHERE ID = ?",array($params[0]));
# Return error if failed
if (!is_object($res)) {
return $res;
}
# Build array of results
$resultArray = array();
$row = $res->fetchObject();
$resultArray['ID'] = $row->id;
$resultArray['Type'] = $row->type;
$resultArray['Value'] = $row->value;
# Convert to ISO format
$date = new DateTime($row->validfrom);
$value = $date->format("Y-m-d");
$resultArray['ValidFrom'] = $value;
# Convert to ISO format
$date = new DateTime($row->validto);
$value = $date->format("Y-m-d");
$resultArray['ValidTo'] = $value;
# Return results
return $resultArray;
}
# Return list of topups
function getAdminUserTopups($params) {
# Filters and sorts are the same here
$filtersorts = array(
'ID' => '@TP@topups.ID',
'Type' => '@TP@topups.Type',
'Value' => '@TP@topups.Value',
'ValidFrom' => '@TP@topups.ValidFrom',
'ValidTo' => '@TP@topups.ValidTo'
);
# Perform query
$res = DBSelectSearch("
SELECT
ID, Timestamp, Type, Value, ValidFrom, ValidTo
FROM
@TP@topups
WHERE
Depleted = 0
AND
UserID = ".DBQuote($params[0]['UserID'])."
ORDER BY
Timestamp
DESC
",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) {
return $res;
}
# Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) {
# Array for this row
$item = array();
$item['ID'] = $row->id;
$item['Timestamp'] = $row->timestamp;
$item['Type'] = $row->type;
$item['Value'] = $row->value;
# Convert to ISO format
$date = new DateTime($row->validfrom);
$value = $date->format("Y-m-d");
$item['ValidFrom'] = $value;
# Convert to ISO format
$date = new DateTime($row->validto);
$value = $date->format("Y-m-d");
$item['ValidTo'] = $value;
# Push this row onto array
array_push($resultArray,$item);
}
# Return results
return array($resultArray,$numResults);
}
# vim: ts=4