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 4452 additions and 26 deletions
<?php
# Admin Users 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 users
function getAdminUsers($params) {
# Filters and sorts are the same here
$filtersorts = array(
'ID' => '@TP@users.ID',
'Username' => '@TP@users.Username',
'Disabled' => '@TP@users.Disabled',
);
# Perform query
$res = DBSelectSearch("SELECT ID, Username, Disabled FROM @TP@users",$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['Username'] = $row->username;
$item['Disabled'] = $row->disabled;
# Push this row onto main array
array_push($resultArray,$item);
}
# Return results
return array($resultArray,$numResults);
}
# Return specific user
function getAdminUser($params) {
# Perform query
$res = DBSelect("SELECT ID, Username, Disabled FROM @TP@users 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['Username'] = $row->username;
$resultArray['Disabled'] = $row->disabled;
# Return results
return $resultArray;
}
# Remove admin user
function removeAdminUser($params) {
# Begin transaction
DBBegin();
# Delete user information, if any
$res = DBDo("DELETE FROM @TP@wisp_userdata WHERE UserID = ?",array($params[0]));
# Delete user attribtues
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@user_attributes WHERE UserID = ?",array($params[0]));
}
# Remove user from groups
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@users_to_groups WHERE UserID = ?",array($params[0]));
}
# Get list of topups and delete summaries
if ($res !== FALSE) {
$topupList = array();
$res = DBSelect("
SELECT
@TP@topups_summary.TopupID
FROM
@TP@topups_summary, @TP@topups
WHERE
@TP@topups_summary.TopupID = @TP@topups.ID
AND @TP@topups.UserID = ?",
array($params[0])
);
if (!is_object($res)) {
$res = FALSE;
} else {
while ($row = $res->fetchObject()) {
array_push($topupList,$row->topupid);
}
$res = TRUE;
}
if (sizeof($topupList) > 0 && $res !== FALSE) {
# Remove topup summaries
foreach ($topupList as $id) {
if ($res !== FALSE) {
$res = DBDo("
DELETE FROM
@TP@topups_summary
WHERE
TopupID = ?",
array($id)
);
}
}
}
}
# Remove topups
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@topups WHERE UserID = ?",array($params[0]));
}
# Delete user
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@users WHERE ID = ?",array($params[0]));
}
# Return result
if ($res !== TRUE) {
DBRollback();
return $res;
} else {
DBCommit();
}
return NULL;
}
# Add admin user
function createAdminUser($params) {
# Perform query
$res = DBDo("INSERT INTO @TP@users (Username,Disabled) VALUES (?,?)",array($params[0]['Username'],$params[0]['Disabled']));
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Edit admin user
function updateAdminUser($params) {
# Perform query
$res = DBDo("UPDATE @TP@users SET Username = ?, Disabled = ? WHERE ID = ?",array($params[0]['Username'],$params[0]['Disabled'],$params[0]['ID']));
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# vim: ts=4
# SMRadius Utility Functions
# Copyright (C) 2007-2009, AllWorldIT
#
<?php
# WiSP Location 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");
## @class smradius::util
# Utility functions
package smradius::util;
# Remove location member
function removeWiSPLocationMember($params) {
use strict;
use warnings;
# Exporter stuff
require Exporter;
our (@ISA,@EXPORT);
@ISA = qw(Exporter);
@EXPORT = qw(
niceUndef
templateReplace
);
## @fn niceUndef($string)
# If string defined return 'string', or if undefined return -undef-
#
# @param string String to check
#
# @return Return 'string' if defined, or -undef- otherwise
sub niceUndef
{
my $string = shift;
# Perform query
$res = DBDo("UPDATE @TP@wisp_userdata SET LocationID = NULL WHERE UserID = ?",array($params[0]));
# Return result
if ($res !== TRUE) {
return $res;
}
return defined($string) ? "'$string'" : '-undef-';
return NULL;
}
# Return list of location members
function getWiSPLocationMembers($params) {
# Filters and sorts are the same here
$filtersorts = array(
'ID' => '@TP@users.ID',
'Username' => '@TP@users.Username'
);
# Perform query
$res = DBSelectSearch("
SELECT
@TP@users.ID, @TP@users.Username
FROM
@TP@wisp_userdata, @TP@users
WHERE
@TP@wisp_userdata.LocationID = ".DBQuote($params[0])."
AND
@TP@users.ID = @TP@wisp_userdata.UserID
",$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;
}
## @fn templateReplace($string,$hashref)
# Template string replacer function
#
# @param string String to replace template items in
# @param hashref Hashref containing the hash of tempalte items & values
#
# @return String with replaced items
sub templateReplace
{
my ($string,$hashref) = @_;
# Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) {
# Build array for this row
$item = array();
my @valueArray = ();
$item['ID'] = $row->id;
$item['Username'] = $row->username;
# Replace blanks
while (my ($entireMacro,$section,$item,$default) = ($string =~ /(\%{([a-z]+)\.([a-z0-9\-]+)(?:=([^}]+))?})/i )) {
# Replace macro with ?
$string =~ s/$entireMacro/\?/;
# Add value onto our array
push(@valueArray,$hashref->{$section}->{$item});
# Push this row onto array
array_push($resultArray,$item);
}
return ($string, @valueArray);
# Return results
return array($resultArray,$numResults);
}
1;
# vim: ts=4
<?php
# WiSP Locations 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 locations
function getWiSPLocations($params) {
# Filters and sorts are the same here
$filtersorts = array(
'ID' => '@TP@wisp_locations.ID',
'Name' => '@TP@wisp_locations.Name'
);
# Perform query
$res = DBSelectSearch("SELECT ID, Name FROM @TP@wisp_locations",$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()) {
# Build array for this row
$item = array();
$item['ID'] = $row->id;
$item['Name'] = $row->name;
# Push this row onto array
array_push($resultArray,$item);
}
# Return results
return array($resultArray,$numResults);
}
# Return specific location row
function getWiSPLocation($params) {
# Perform query
$res = DBSelect("SELECT ID, Name FROM @TP@wisp_locations WHERE ID = ?",array($params[0]));
# Return if error or nothing to return
if (!is_object($res)) {
return $res;
}
# Build array of results
$resultArray = array();
$row = $res->fetchObject();
$resultArray['ID'] = $row->id;
$resultArray['Name'] = $row->name;
# Return results
return $resultArray;
}
# Remove wisp location
function removeWiSPLocation($params) {
# Begin transaction
DBBegin();
# Unlink users from this location
$res = DBDo("UPDATE @TP@wisp_userdata SET LocationID = NULL WHERE LocationID = ?",array($params[0]));
# Delete location
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@wisp_locations WHERE ID = ?",array($params[0]));
}
# Return result
if ($res !== TRUE) {
DBRollback();
return $res;
} else {
DBCommit();
}
return NULL;
}
# Add wisp location
function createWiSPLocation($params) {
# Perform query
$res = DBDo("INSERT INTO @TP@wisp_locations (Name) VALUES (?)",array($params[0]['Name']));
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Edit wisp location
function updateWiSPLocation($params) {
# Perform query
$res = DBDo("UPDATE @TP@wisp_locations SET Name = ? WHERE ID = ?",array($params[0]['Name'],$params[0]['ID']));
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# vim: ts=4
<?php
# WiSP 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 getWiSPUserLogsSummary($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 getWiSPUserLogs($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
# WiSP 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 createWiSPUserTopup($params) {
# Current datetime
$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 updateWiSPUserTopup($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 removeWiSPUserTopup($params) {
# Perform query
$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 getWiSPUserTopup($params) {
# Perform query
$res = DBSelect("SELECT ID, Type, Value, ValidFrom, ValidTo FROM @TP@topups WHERE ID = ?",array($params[0]));
# Return if error or no result
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 getWiSPUserTopups($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
<?php
# WiSP Users 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 wisp users
function getWiSPUsers($params) {
# Filters and sorts are the same here
$filtersorts = array(
'Username' => '@TP@users.Username',
'Disabled' => '@TP@users.Disabled',
'ID' => '@TP@wisp_userdata.UserID',
'Firstname' => '@TP@wisp_userdata.Firstname',
'Lastname' => '@TP@wisp_userdata.Lastname',
'Email' => '@TP@wisp_userdata.Email',
'Phone' => '@TP@wisp_userdata.Phone'
);
# Perform query
$res = DBSelectSearch("
SELECT
@TP@users.Username,
@TP@users.Disabled,
@TP@wisp_userdata.UserID,
@TP@wisp_userdata.FirstName,
@TP@wisp_userdata.LastName,
@TP@wisp_userdata.Email,
@TP@wisp_userdata.Phone
FROM
@TP@users, @TP@wisp_userdata
WHERE
@TP@wisp_userdata.UserID = @TP@users.ID
",$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->userid;
$item['Username'] = $row->username;
$item['Disabled'] = $row->disabled;
$item['Firstname'] = $row->firstname;
$item['Lastname'] = $row->lastname;
$item['Email'] = $row->email;
$item['Phone'] = $row->phone;
# Push this row onto array
array_push($resultArray,$item);
}
# Return results
return array($resultArray,$numResults);
}
# Return specific wisp user row
function getWiSPUser($params) {
# Query for userdata and username
$res = DBSelect("
SELECT
@TP@wisp_userdata.UserID,
@TP@wisp_userdata.FirstName,
@TP@wisp_userdata.LastName,
@TP@wisp_userdata.Phone,
@TP@wisp_userdata.Email,
@TP@wisp_userdata.LocationID,
@TP@users.Username,
@TP@users.Disabled
FROM
@TP@wisp_userdata, @TP@users
WHERE
@TP@wisp_userdata.UserID = ?
AND
@TP@users.ID = @TP@wisp_userdata.UserID
",array($params[0])
);
# Return if error
if (!is_object($res)) {
return $res;
}
# Build array of results
$resultArray = array();
$row = $res->fetchObject();
# Set userdata fields
$resultArray['ID'] = $row->userid;
$resultArray['Username'] = $row->username;
$resultArray['Disabled'] = $row->disabled;
if (isset($row->firstname)) {
$resultArray['Firstname'] = $row->firstname;
} else {
$resultArray['Firstname'] = null;
}
if (isset($row->lastname)) {
$resultArray['Lastname'] = $row->lastname;
} else {
$resultArray['Lastname'] = null;
}
if (isset($row->phone)) {
$resultArray['Phone'] = $row->phone;
} else {
$resultArray['Phone'] = null;
}
if (isset($row->email)) {
$resultArray['Email'] = $row->email;
} else {
$resultArray['Email'] = null;
}
if (isset($row->locationid)) {
$resultArray['LocationID'] = $row->locationid;
} else {
$resultArray['LocationID'] = null;
}
# Password query
$res = DBSelect("
SELECT
Value
FROM
@TP@user_attributes
WHERE
Name = ?
AND @TP@user_attributes.UserID = ?
",array('User-Password',$params[0])
);
# Return if error
if (!is_object($res)) {
return $res;
}
# Set password
$row = $res->fetchObject();
if (isset($row->value)) {
$resultArray['Password'] = $row->value;
} else {
$resultArray['Password'] = null;
}
# Set number of results
$numResults = count($resultArray);
# Return results
return array($resultArray,$numResults);
}
# Get wisp user attributes
function getWiSPUserAttributes($params) {
# Attributes query
$res = DBSelect("
SELECT
ID, Name, Operator, Value
FROM
@TP@user_attributes
WHERE
@TP@user_attributes.UserID = ?",
array($params[0])
);
# Return if error
if (!is_object($res)) {
return $res;
}
# Set attributes
$i = 0;
$attributes = array();
while ($row = $res->fetchObject()) {
$attributes[$i] = array();
$attributes[$i]['ID'] = $row->id;
$attributes[$i]['Name'] = $row->name;
$attributes[$i]['Operator'] = $row->operator;
$attributes[$i]['Value'] = $row->value;
$i++;
}
# Set number of results
$numResults = count($attributes);
# Return results
return array($attributes,$numResults);
}
# Get wisp user groups
function getWiSPUserGroups($params) {
# Groups query
$res = DBSelect("
SELECT
@TP@groups.Name, @TP@groups.ID
FROM
@TP@users_to_groups, @TP@groups
WHERE
@TP@users_to_groups.GroupID = @TP@groups.ID
AND @TP@users_to_groups.UserID = ?",
array($params[0])
);
# Return if error
if (!is_object($res)) {
return $res;
}
# Set groups
$i = 0;
$groups = array();
while ($row = $res->fetchObject()) {
$groups[$i]['ID'] = $row->id;
$groups[$i]['Name'] = $row->name;
$i++;
}
# Set number of results
$numResults = count($groups);
# Return results
return array($groups,$numResults);
}
# Remove wisp user
function removeWiSPUser($params) {
# Begin transaction
DBBegin();
# Delete user information
$res = DBDo("DELETE FROM @TP@wisp_userdata WHERE UserID = ?",array($params[0]));
# Delete user attribtues
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@user_attributes WHERE UserID = ?",array($params[0]));
}
# Remove user from groups
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@users_to_groups WHERE UserID = ?",array($params[0]));
}
# Get list of topups and delete summaries
if ($res !== FALSE) {
$topupList = array();
$res = DBSelect("
SELECT
@TP@topups_summary.TopupID
FROM
@TP@topups_summary, topups
WHERE
@TP@topups_summary.TopupID = @TP@topups.ID
AND @TP@topups.UserID = ?",
array($params[0])
);
if (!is_object($res)) {
$res = FALSE;
} else {
while ($row = $res->fetchObject()) {
array_push($topupList,$row->topupid);
}
}
if ($res !== FALSE && sizeof($topupList) > 0) {
# Remove topup summaries
foreach ($topupList as $id) {
if ($res !== FALSE) {
$res = DBDo("
DELETE FROM
@TP@topups_summary
WHERE
TopupID = ?",
array($id)
);
}
}
}
}
# Remove topups
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@topups WHERE UserID = ?",array($params[0]));
}
# Delete user
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@users WHERE ID = ?",array($params[0]));
}
# Return result
if ($res !== TRUE) {
DBRollback();
return $res;
} else {
DBCommit();
}
return NULL;
}
# Add wisp user
function createWiSPUser($params) {
# We need this to send notification
global $adminEmails;
# Begin transaction
DBBegin();
# Perform first query
$res = "Username required for single user. For adding multiple users an integer is required.";
# If we adding single user
if (empty($params[0]['Number']) && !empty($params[0]['Username'])) {
# Insert username
$res = DBDo("INSERT INTO @TP@users (Username,Disabled) VALUES (?,?)",array($params[0]['Username'],$params[0]['Disabled']));
# Continue with others if successful
if ($res !== FALSE) {
$userID = DBLastInsertID();
$res = DBDo("
INSERT INTO
@TP@user_attributes (UserID,Name,Operator,Value)
VALUES
(?,?,?,?)",
array($userID,
'User-Password',
'==',
$params[0]['Password'])
);
}
# Link users ID to make user a wisp user
if ($res !== FALSE) {
$res = DBDo("INSERT INTO @TP@wisp_userdata (UserID) VALUES (?)",array($userID));
}
# Add personal information
if ($res !== FALSE && isset($params[0]['Firstname'])) {
$res = DBDo("UPDATE @TP@wisp_userdata SET FirstName = ? WHERE UserID = ?",array($params[0]['Firstname'],$userID));
}
if ($res !== FALSE && isset($params[0]['Lastname'])) {
$res = DBDo("UPDATE @TP@wisp_userdata SET LastName = ? WHERE UserID = ?",array($params[0]['Lastname'],$userID));
}
if ($res !== FALSE && isset($params[0]['Phone'])) {
$res = DBDo("UPDATE @TP@wisp_userdata SET Phone = ? WHERE UserID = ?",array($params[0]['Phone'],$userID));
}
if ($res !== FALSE && isset($params[0]['Email'])) {
$res = DBDo("UPDATE @TP@wisp_userdata SET Email = ? WHERE UserID = ?",array($params[0]['Email'],$userID));
}
if ($res !== FALSE && !empty($params[0]['LocationID'])) {
$res = DBDo("UPDATE @TP@wisp_userdata SET LocationID = ? WHERE UserID = ?",array($params[0]['LocationID'],$userID));
}
# Grab each attribute and add it's details to the database
if ($res !== FALSE && count($params[0]['Attributes']) > 0) {
foreach ($params[0]['Attributes'] as $attr) {
# We only want to add attributes with all values
if (
isset($attr['Name']) && $attr['Name'] != "" &&
isset($attr['Operator']) && $attr['Operator'] != "" &&
isset($attr['Value']) && $attr['Value'] != ""
) {
# Default value without modifier
$attrValue = $attr['Value'];
if ($attr['Name'] == 'SMRadius-Capping-Traffic-Limit' || $attr['Name'] == 'SMRadius-Capping-Uptime-Limit') {
# If modifier is set we need to work out attribute value
if (isset($attr['Modifier'])) {
switch ($attr['Modifier']) {
case "Seconds":
$attrValue = $attr['Value'] / 60;
break;
case "Minutes":
$attrValue = $attr['Value'];
break;
case "Hours":
$attrValue = $attr['Value'] * 60;
break;
case "Days":
$attrValue = $attr['Value'] * 1440;
break;
case "Weeks":
$attrValue = $attr['Value'] * 10080;
break;
case "Months":
$attrValue = $attr['Value'] * 44640;
break;
case "MBytes":
$attrValue = $attr['Value'];
break;
case "GBytes":
$attrValue = $attr['Value'] * 1000;
break;
case "TBytes":
$attrValue = $attr['Value'] * 1000000;
break;
}
}
}
# Add attribute
$res = DBDo("
INSERT INTO
@TP@user_attributes (UserID,Name,Operator,Value)
VALUES
(?,?,?,?)",
array(
$userID,
$attr['Name'],
$attr['Operator'],
$attrValue
)
);
}
}
}
# Link user to groups if any selected
if ($res !== FALSE && count($params[0]['Groups']) > 0) {
$refinedGroups = array();
# Filter out unique group ID's
foreach ($params[0]['Groups'] as $group) {
foreach ($group as $ID=>$value) {
$refinedGroups[$value] = $value;
}
}
# Loop through groups
foreach ($refinedGroups as $groupID) {
$res = DBDo("INSERT INTO @TP@users_to_groups (UserID,GroupID) VALUES (?,?)",array($userID,$groupID));
}
}
# We adding multiple users
} elseif (!empty($params[0]['Number']) && $params[0]['Number'] > 1) {
$wispUser = array();
# Loop for number of chosen numbers
for ($i = 0; $i < $params[0]['Number']; $i++) {
# Check for duplicates and add
$usernameReserved = 1;
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
while ($usernameReserved == 1) {
# Generate random username
$string = '';
for ($c = 0; $c < 7; $c++) {
$string .= $characters[rand(0, strlen($characters) - 1)];
}
$thisUsername = $string;
# Add prefix to string
if (!empty($params[0]['Prefix'])) {
$thisUsername = $params[0]['Prefix'].$string;
}
# Check if username used
$res = DBSelect("
SELECT
@TP@users.Username
FROM
@TP@users
WHERE
@TP@users.Username = ?
",array($thisUsername)
);
# If there are no rows we may continue
if ($res->rowCount() == 0 && !isset($wispUser[$thisUsername])) {
$usernameReserved = 0;
# Generate random username
$string = '';
for ($c = 0; $c < 7; $c++) {
$string .= $characters[rand(0, strlen($characters) - 1)];
}
# Add username and password onto array
$wispUser[$thisUsername] = $string;
}
}
}
# Insert users from array into database
foreach ($wispUser as $username => $password) {
$res = DBDo("INSERT INTO @TP@users (Username,Disabled) VALUES (?,?)",array($username,$params[0]['Disabled']));
if ($res !== FALSE) {
$id = DBLastInsertID();
$res = DBDo("INSERT INTO @TP@user_attributes (UserID,Name,Operator,Value) VALUES (?,?,?,?)",
array($id,'User-Password','==',$password)
);
# Grab each attribute and add it's details to the database
if ($res !== FALSE && count($params[0]['Attributes']) > 0) {
foreach ($params[0]['Attributes'] as $attr) {
# We only want to add attributes with all values
if (
isset($attr['Name']) && $attr['Name'] != "" &&
isset($attr['Operator']) && $attr['Operator'] != "" &&
isset($attr['Value']) && $attr['Value'] != ""
) {
# Default value without modifier
$attrValue = $attr['Value'];
if ($attr['Name'] == 'SMRadius-Capping-Traffic-Limit' || $attr['Name'] == 'SMRadius-Capping-Uptime-Limit') {
# If modifier is set we need to work out attribute value
if (isset($attr['Modifier'])) {
switch ($attr['Modifier']) {
case "Seconds":
$attrValue = $attr['Value'] / 60;
break;
case "Minutes":
$attrValue = $attr['Value'];
break;
case "Hours":
$attrValue = $attr['Value'] * 60;
break;
case "Days":
$attrValue = $attr['Value'] * 1440;
break;
case "Weeks":
$attrValue = $attr['Value'] * 10080;
break;
case "Months":
$attrValue = $attr['Value'] * 44640;
break;
case "MBytes":
$attrValue = $attr['Value'];
break;
case "GBytes":
$attrValue = $attr['Value'] * 1000;
break;
case "TBytes":
$attrValue = $attr['Value'] * 1000000;
break;
}
}
}
# Add attribute
$res = DBDo("
INSERT INTO
@TP@user_attributes (UserID,Name,Operator,Value)
VALUES
(?,?,?,?)",
array(
$id,
$attr['Name'],
$attr['Operator'],
$attrValue
)
);
}
}
}
# Link user to groups if any selected
if ($res !== FALSE && count($params[0]['Groups']) > 0) {
$refinedGroups = array();
# Filter out unique group ID's
foreach ($params[0]['Groups'] as $group) {
foreach ($group as $ID=>$value) {
$refinedGroups[$value] = $value;
}
}
# Loop through groups
foreach ($refinedGroups as $groupID) {
$res = DBDo("INSERT INTO @TP@users_to_groups (UserID,GroupID) VALUES (?,?)",array($id,$groupID));
}
}
# Link to wisp users
if ($res !== FALSE) {
$res = DBDo("INSERT INTO @TP@wisp_userdata (UserID) VALUES (?)",
array($id)
);
}
}
}
# Email userlist to admin
if ($res !== FALSE && isset($adminEmails)) {
// multiple recipients
$to = $adminEmails;
// subject
$subject = count($wispUser).' WiSP users added';
// html
$html = '';
foreach ($wispUser as $key => $val) {
$html .= '<tr><td>'.$key.'</td><td>'.$val.'</td></tr>';
}
// message
$message = '
<html>
<head>
<title>User List</title>
</head>
<body>
<table cellspacing="10">
<tr>
<th>Username</th><th>Password</th>
</tr>'.$html.'
</table>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'From: SMRadius';
// Mail it
$res = mail($to, $subject, $message, $headers);
}
}
# Commit changes if all was successful, else rollback
if ($res !== TRUE) {
DBRollback();
return $res;
} else {
DBCommit();
}
return NULL;
}
# Edit wisp user
function updateWiSPUser($params) {
DBBegin();
$res = TRUE;
# Perform query
$res = DBDo("UPDATE @TP@users SET Username = ?, Disabled = ? WHERE ID = ?",array($params[0]['Username'],$params[0]['Disabled'],$params[0]['ID']));
# Change password
if ($res !== FALSE) {
$res = DBDo("UPDATE @TP@user_attributes SET Value = ? WHERE UserID = ? AND Name = ?",
array($params[0]['Password'],$params[0]['ID'],'User-Password'));
}
# If successful, continue
if ($res !== FALSE) {
$res = DBDo("
UPDATE
@TP@wisp_userdata
SET
FirstName = ?,
LastName = ?,
Phone = ?,
Email = ?
WHERE
UserID = ?",
array($params[0]['Firstname'],
$params[0]['Lastname'],
$params[0]['Phone'],
$params[0]['Email'],
$params[0]['ID'])
);
}
# If successful, add location if any
if ($res !== FALSE && !empty($params[0]['LocationID'])) {
$res = DBDo("UPDATE @TP@wisp_userdata SET LocationID = ? WHERE UserID = ?",
array($params[0]['LocationID'],$params[0]['ID'])
);
}
# Process attributes being removed
if ($res !== FALSE && count($params[0]['RAttributes']) > 0) {
foreach ($params[0]['RAttributes'] as $attr) {
if ($res !== FALSE) {
# Perform query
$res = DBDo("DELETE FROM @TP@user_attributes WHERE ID = ?",array($attr));
}
}
}
# Process groups being removed
if ($res !== FALSE && count($params[0]['RGroups']) > 0) {
foreach ($params[0]['RGroups'] as $attr) {
if ($res !== FALSE) {
# Perform query
$res = DBDo("
DELETE FROM
@TP@users_to_groups
WHERE
UserID = ?
AND GroupID = ?",
array($params[0]['ID'],$attr)
);
}
}
}
# Grab each attribute and add it's details to the database
if ($res !== FALSE && count($params[0]['Attributes']) > 0) {
foreach ($params[0]['Attributes'] as $attr) {
# We only want to add attributes with all values
if (
isset($attr['Name']) && $attr['Name'] != "" &&
isset($attr['Operator']) && $attr['Operator'] != "" &&
isset($attr['Value']) && $attr['Value'] != ""
) {
# Default value without modifier
$attrValue = $attr['Value'];
if ($attr['Name'] == 'SMRadius-Capping-Traffic-Limit' || $attr['Name'] == 'SMRadius-Capping-Uptime-Limit') {
# If modifier is set we need to work out attribute value
if (isset($attr['Modifier'])) {
switch ($attr['Modifier']) {
case "Seconds":
$attrValue = $attr['Value'] / 60;
break;
case "Minutes":
$attrValue = $attr['Value'];
break;
case "Hours":
$attrValue = $attr['Value'] * 60;
break;
case "Days":
$attrValue = $attr['Value'] * 1440;
break;
case "Weeks":
$attrValue = $attr['Value'] * 10080;
break;
case "Months":
$attrValue = $attr['Value'] * 44640;
break;
case "MBytes":
$attrValue = $attr['Value'];
break;
case "GBytes":
$attrValue = $attr['Value'] * 1000;
break;
case "TBytes":
$attrValue = $attr['Value'] * 1000000;
break;
}
}
}
# Check if we adding or updating
if ($res !== FALSE) {
# We adding an attribute..
if ($attr['ID'] < 0) {
$res = DBDo("
INSERT INTO
@TP@user_attributes (UserID,Name,Operator,Value)
VALUES
(?,?,?,?)",
array(
$params[0]['ID'],
$attr['Name'],
$attr['Operator'],
$attrValue
)
);
# We updating an attribute..
} else {
$res = DBDo("
UPDATE
@TP@user_attributes
SET
Name = ?,
Operator = ?,
Value = ?
WHERE
ID = ?",
array($attr['Name'],$attr['Operator'],$attrValue,$attr['ID'])
);
}
}
}
}
}
# Link user to groups if any selected
if ($res !== FALSE && count($params[0]['Groups']) > 0) {
$refinedGroups = array();
# Filter out unique group ID's
foreach ($params[0]['Groups'] as $group) {
foreach ($group as $ID=>$value) {
$refinedGroups[$value] = $value;
}
}
# Loop through groups
foreach ($refinedGroups as $groupID) {
if ($res !== FALSE) {
$res = DBSelect("
SELECT
ID
FROM
@TP@users_to_groups
WHERE
UserID = ?
AND GroupID = ?",
array($params[0]['ID'],$groupID)
);
}
if (is_object($res)) {
if ($res->rowCount() == 0) {
$res = DBDo("INSERT INTO @TP@users_to_groups (UserID,GroupID) VALUES (?,?)",array($params[0]['ID'],$groupID));
} else {
$res = TRUE;
}
}
}
}
# Commit changes if all was successful, else break
if ($res !== TRUE) {
DBRollback();
return $res;
} else {
DBCommit();
}
return NULL;
}
# vim: ts=4
<?php
# JSON interface
# 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.
class json_response {
private $_fields = array();
private $_id;
private $_results;
private $_datasetSize;
private $_status = RES_OK;
## @method setID($id)
# Set ID column
#
# @param id ID column name
public function setID($id) {
$this->_id = $id;
}
## @method setStatus($status)
# Set response status
#
# @param status Either RES_OK (default) or RES_ERROR
public function setStatus($status) {
$this->_status = $status;
}
## @method addField($name,$type)
# Add a field to our return results
#
# @param name Field name
# @param type Field type, 'int', 'string', 'float', 'boolean', 'date'
public function addField($name,$type) {
# Build field
$field = array(
'name' => $name,
'type' => $type
);
# Set ISO date format
if ($field['type'] == "date") {
$field['dateFormat'] = "Y-m-d";
}
# Add field to list
array_push($this->_fields,$field);
}
## @method setDatasetSize($size)
# Set how many records are returned in the dataset
#
# @param size Dataset size
public function setDatasetSize($size) {
$this->_datasetSize = $size;
}
## @method parseArrayRef($array)
# Parse in the array of results and fix it up
#
# @param arrayref Array ref containing the results
public function parseArray($array) {
$this->_results = array();
# Loop with array items
foreach ($array as $aitem) {
$item = array();
# Loop with fields we want
foreach ($this->_fields as $field) {
# FIXME - typecast?
$item[$field['name']] = $aitem[$field['name']];
}
array_push($this->_results,$item);
}
}
## @method parseHash($hashref)
# Parse in the hash of results and fix it up
#
# @param hashref Hash ref containing the results
public function parseHash($hash) {
$this->_results = array();
foreach ($this->_fields as $field) {
# FIXME - typecast?
$this->_results[$field['name']] = $hash[$field['name']];
}
}
## @method export
# Export response into something we return
#
# @return JSON hash
# @li result - Result code/status
# @li data - Ref containing results
# @li metaData - Metadata containing info about the results being returned
# Metadata contains properties..
# - root: root element, which is always 'data'
# - fields: Optional field description, arrayref of hash refs, name = 'name', type 'type' and 'dateFormat' = 'Y-m-d'
# - id: Optional ID field name
# - totalProperty: Optional property name containing the number of records, always 'datasetSize'
# @li datasetSize Optional, number of records we're rturning
public function export() {
# Build result
$ret = array(
'result' => $this->_status,
# Additional stuff for other things to make life easier
'success' => $this->_status == RES_OK ? 1 : 0,
'metaData' => array(
'successProperty' => 'success'
)
);
# If we have results, add them
if (isset($this->_results)) {
$ret['data'] = $this->_results;
$ret['metaData']['root'] = 'data';
# If we have fields, set them up
if (isset($this->_fields)) {
$ret['metaData']['fields'] = $this->_fields;
}
}
# Check if we have an ID set
if (isset($this->_id)) {
$ret['metaData']['totalProperty'] = 'datasetSize';
$ret['datasetSize'] = $this->_datasetSize;
}
return $ret;
}
}
function jsonSuccess($name = 'Result',$type = 'int',$value = 0) {
# Build response
$res = new json_response;
$res->addField($name,$type);
$res->parseHash(array(
$name => $value
));
# Export
echo json_encode($res->export());
}
function jsonError($code,$reason) {
# Build response
$res = new json_response;
$res->setStatus(-1);
$res->addField('ErrorCode','int');
$res->addField('ErrorReason','string');
$res->parseHash(array(
'ErrorCode' => $code,
'ErrorReason' => $reason
));
# Export
echo json_encode($res->export());
}
# vim: ts=4
<?php
# Web Admin UI Config
# Copyright (C) 2007-2009, AllWorldIT
# 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
......@@ -32,6 +32,12 @@ $DB_PASS="root";
$DB_TABLE_PREFIX="";
# Email address/addresses to receive notifications
# Seperated by commas, eg. "admin@example.org,admin@example.net"
# $adminEmails="admin@example.org";
#
# THE BELOW SECTION IS UNSUPPORTED AND MEANT FOR THE ORIGINAL SPONSOR OF V2
#
......@@ -40,4 +46,5 @@ $DB_TABLE_PREFIX="";
#$DB_POSTFIX_USER="root";
#$DB_POSTFIX_PASS="";
# vim: ts=4
?>
<?php
# Database Interface
# 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.
require_once('include/config.php');
# Connect to DB
function connect_db()
{
global $DB_DSN;
global $DB_USER;
global $DB_PASS;
try {
$dbh = new PDO($DB_DSN, $DB_USER, $DB_PASS, array(
PDO::ATTR_PERSISTENT => false
));
$dbh->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
} catch (PDOException $e) {
die("Error connecting to SMRadius DB: " . $e->getMessage());
}
return $dbh;
}
# Connect to postfix DB
function connect_postfix_db()
{
global $DB_POSTFIX_DSN;
global $DB_POSTFIX_USER;
global $DB_POSTFIX_PASS;
try {
$dbh = new PDO($DB_POSTFIX_DSN, $DB_POSTFIX_USER, $DB_POSTFIX_PASS, array(
PDO::ATTR_PERSISTENT => false
));
$dbh->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER);
} catch (PDOException $e) {
die("Error connecting to Postfix DB: " . $e->getMessage());
}
return $dbh;
}
## @fn DBSelect($query,$args)
# Return database selection results...
#
# @param query Query to run
# @param args Array of arguments we substitute in ?'s place
#
# @return DBI statement handle, undef on error
function DBSelect($query,$args = array())
{
global $db;
# Replace table prefix template
$result = ReplacePrefix($query, $args);
$rawQuery = $result[0]; $rawArgs = $result[1];
# Try prepare, and catch exceptions
try {
$stmt = $db->prepare($rawQuery);
} catch (PDOException $e) {
return $e->getMessage();
}
# Execute query
$res = $stmt->execute($rawArgs);
if ($res === FALSE) {
return $stmt->errorInfo();
}
return $stmt;
}
## @fn DBDo($query,$args)
# Perform a database command
#
# @param command Command to execute in database
# @param args Arguments to quote in the command string
#
# @return Number of results, undef on error
function DBDo($command,$args = array())
{
global $db;
# Replace table prefix template
$result = ReplacePrefix($command, $args);
$rawCommand = $result[0]; $rawArgs = $result[1];
# Try prepare, and catch exceptions
try {
$stmt = $db->prepare($rawCommand);
} catch (PDOException $e) {
return $e->getMessage();
}
# Execute query
$res = $stmt->execute($rawArgs);
if ($res === FALSE) {
return $stmt->errorInfo();
}
return $res;
}
## @fn DBSelectNumResults($query,$args)
# Return how many results came up from the specific SELECT query
#
# @param query Query to perform, minus "SELECT COUNT(*) AS num_results"
# @param args Arguments to quote in the query string
#
# @return Number of results, undef on error
function DBSelectNumResults($query,$args = array())
{
global $db;
# Replace table prefix template
$result = ReplacePrefix($query, $args);
$rawQuery = $result[0]; $rawArgs = $result[1];
$res = DBSelect("SELECT COUNT(*) AS num_results $rawQuery",$rawArgs);
if (!is_object($res)) {
return $res;
}
# Grab row
$row = $res->fetchObject();
# Pull number
$num_results = $row->num_results;
return $num_results;
}
## @fn DBSelectSearch($query,$search,$filters,$sorts)
# Select results from database and return the total number aswell
#
# @param query Base query
#
# @param search Search array
# @li Filter - Filter based on this...
# [filter] => Array (
# [0] => Array (
# [field] => Name
# [data] => Array (
# [type] => string
# [value] => hi there
# )
# )
# )
# { 'data' => { 'comparison' => 'gt', 'value' => '5', 'type' => 'numeric' }, 'field' => 'ID' }
# @li Start - Start item number, indexed from 0 onwards
# @li Limit - Limit number of results
# @li Sort - Sort by this item
# @li SortDirection - Sort in this direction, either ASC or DESC
#
# @param filters Filter array ref
# Hash: 'Column' -> 'Table.DBColumn'
#
# @param sorts Hash ref of valid sort criteria, indexed by what we get, pointing to the DB column in the query
# Hash: 'Column' -> 'Table.DBColumn'
#
# @return Number of results, undef on error
function DBSelectSearch($query,$search,$filters,$sorts) {
global $db;
# Stuff we need to add to the SQL query
$where = array(); # Where clauses
$sqlWhere = "";
$sqlLimit = "";
$sqlOffset = "";
$sqlOrderBy = "";
$sqlOrderByDirection = "";
# Check if we're searching
if (isset($search)) {
# Check it is a array
if (gettype($search) != "array") {
return array(NULL,"Parameter 'search' is not a array");
}
# Check if we need to filter
if (isset($search['Filter']) && !empty($search['Filter'])) {
# We need filters in order to use filtering
if (!isset($filters)) {
return array(NULL,"Parameter 'search' element 'Filter' requires 'filters' to be defined");
}
# Check type of Filter
if (isset($search['Filter']) != "array") {
return array(NULL,"Parameter 'search' element 'Filter' is of invalid type, it must be an array'");
}
# Loop with filters
foreach ($search['Filter'] as $item) {
$data = $item['data']; # value, type, comparison
$field = $item['field'];
# Check if field is in our allowed filters
if (!isset($filters[$field])) {
return array(NULL,"Parameter 'search' element 'Filter' has invalid field item '$field' according to 'filters'");
}
$column = $filters[$field];
# Check data
if (!isset($data['type'])) {
return array(NULL,"Parameter 'search' element 'Filter' requires field data element 'type' for field '$field'");
}
if (!isset($data['value'])) {
return array(NULL,"Parameter 'search' element 'Filter' requires field data element 'value' for field '$field'");
}
# match =, LIKE, IN (
# matchEnd '' or )
$match;
$matchEnd = "";
# value is the $db->quote()'d value
$value;
# Check what type of comparison
if ($data['type'] == "boolean") {
$match = '=';
$value = $db->quote($data['value']);
} elseif ($data['type'] == "date") {
# The comparison type must be defined
if (!isset($data['comparison'])) {
return array(NULL,"Parameter 'search' element 'Filter' requires field data element 'comparison' for date field '$field'");
}
# Check comparison type
if ($data['comparison'] == "gt") {
$match = ">";
} elseif ($data['comparison'] == "lt") {
$match = "<";
} elseif ($data['comparison'] == "eq") {
$match = "=";
}
# Convert to ISO format
$date = new DateTime($data['value']);
$value = $db->quote($date->format('Y-m-d'));
} elseif ($data['type'] == "list") {
# Quote all values
$valueList = array();
foreach (explode(",",$data['value']) as $i) {
array_push($valueList,$db->quote($i));
}
$match = "IN (";
# Join up 'xx','yy','zz'
$value = implode(',',$valueList);
$matchEnd = ")";
} elseif ($data['type'] == "numeric") {
# The comparison type must be defined
if (!isset($data['comparison'])) {
return array(NULL,"Parameter 'search' element 'Filter' requires field data element 'comparison' for numeric field '$field'");
}
# Check comparison type
if ($data['comparison'] == "gt") {
$match = ">";
} elseif ($data['comparison'] == "lt") {
$match = "<";
} elseif ($data['comparison'] == "eq") {
$match = "=";
}
$value = $db->quote($data['value']);
} elseif ($data['type'] == "string") {
$match = "LIKE";
$value = $db->quote("%".$data['value']."%");
}
# Add to list
array_push($where,"$column $match $value $matchEnd");
}
# Check if we have any WHERE clauses to add ...
if (count($where) > 0) {
# Check if we have WHERE clauses in the query
if (preg_match("/\sWHERE\s/i",$query)) {
# If so start off with AND
$sqlWhere .= "AND ";
} else {
$sqlWhere = "WHERE ";
}
$sqlWhere .= implode(" AND ",$where);
}
}
# Check if we starting at an OFFSET
if (isset($search['Start'])) {
# Check if Start is valid
if (!is_numeric($search['Start']) || $search['Start'] < 0) {
return array(NULL,"Parameter 'search' element 'Start' invalid value '".$search['Start']."'");
}
$sqlOffset = sprintf("OFFSET %d",$search['Start']);
}
# Check if results will be LIMIT'd
if (isset($search['Limit'])) {
# Check if Limit is valid
if (!is_numeric($search['Limit']) || $search['Limit'] < 1) {
return array(NULL,"Parameter 'search' element 'Limit' invalid value '".$search['Limit']."'");
}
$sqlLimit = sprintf("LIMIT %d",$search['Limit']);
}
# Check if we going to be sorting
if (isset($search['Sort']) && !empty($search['Sort'])) {
# We need sorts in order to use sorting
if (!isset($sorts)) {
return array(NULL,"Parameter 'search' element 'Filter' requires 'filters' to be defined");
}
# Check if sort is defined
if (!isset($sorts[$search['Sort']])) {
return array(NULL,"Parameter 'search' element 'Sort' invalid item '".$search['Sort']."' according to 'sorts'");
}
# Build ORDER By
$sqlOrderBy = "ORDER BY ".$sorts[$search['Sort']];
# Check for sort ORDER
if (isset($search['SortDirection']) && !empty($search['SortDirection'])) {
# Check for valid directions
if (strtolower($search['SortDirection']) == "asc") {
$sqlOrderByDirection = "ASC";
} elseif (strtolower($search['SortDirection']) == "desc") {
$sqlOrderByDirection = "DESC";
} else {
return array(NULL,"Parameter 'search' element 'SortDirection' invalid value '".$search['SortDirection']."'");
}
}
}
}
# Select row count, pull out "SELECT .... " as we replace this in the NumResults query
$queryCount = $query; $queryCount = preg_replace("/^\s*SELECT\s.*\sFROM/is","FROM",$queryCount);
$numResults = DBSelectNumResults("$queryCount $sqlWhere");
if (!isset($numResults)) {
return array(NULL,"Backend database query 1 failed");
}
# Add Start, Limit, Sort, Direction
$sth = DBSelect("$query $sqlWhere $sqlOrderBy $sqlOrderByDirection $sqlLimit $sqlOffset");
if (!isset($sth)) {
return array(NULL,"Backend database query 2 failed");
}
return array($sth,$numResults);
}
## @fn DBLastInsertID($table,$column)
# Function to get last insert id
#
# @param table Table to check
# @param column Column to get last insert on
#
# @return Last insert ID or undef on error
function DBLastInsertID()
{
global $db;
# TODO: Implement $table nad $column??
$res = $db->lastInsertID();
return $res;
}
# Function to begin a transaction
# Args: none
function DBBegin()
{
global $db;
$res = $db->beginTransaction();
return $res;
}
# Function to commit a transaction
# Args: none
function DBCommit()
{
global $db;
$res = $db->commit();
return $res;
}
# Function to quote a variable
# Args: none
function DBQuote($var)
{
global $db;
$res = $db->quote($var);
return $res;
}
# Function to rollback a transaction
# Args: none
function DBRollback()
{
global $db;
$res = $db->rollback();
return $res;
}
# Connet to database when we load this file
$db = connect_db();
## @fn ReplacePrefix($query,$args)
# Return raw query and args based on table prefix
#
# @param query Query string
# @param args Array of arguments
#
# @return string rawQuery, array rawArgs
function ReplacePrefix($query, $args = array())
{
global $DB_TABLE_PREFIX;
# Fetch table prefix from config
$table_prefix = isset($DB_TABLE_PREFIX) ? $DB_TABLE_PREFIX : "";
# Replace query
$rawQuery = preg_replace('/\@TP\@/', $table_prefix, $query);
# Replace args
$rawArgs = array();
foreach ($args as $argItem) {
$rawArgItem = preg_replace('/\@TP\@/', $table_prefix, $argItem);
array_push($rawArgs, $rawArgItem);
}
return array($rawQuery, $rawArgs);
}
# vim: ts=4
<?php
# Radius term code mappings
# Copyright (C) 2007-2009, AllWorldIT
# 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
......@@ -23,41 +23,58 @@
function strRadiusTermCode($errCode) {
if (is_numeric($errCode)) {
# Terminate codes RFC 2866
switch ($errCode) {
case 0:
return "Still logged in";
case 45: # Unknown
case 46: # Unknown
case 63: # Unknown
case 1:
return "User request";
return "User Request";
case 2:
case 816: # TCP connection reset? unknown
return "Carrier loss";
return "Lost Carrier";
case 3:
return "Lost Service";
case 4:
return "Idle Timeout";
case 5:
return "Session timeout";
case 6: # Admin reset
case 10: # NAS request
case 11: # NAS reboot
case 831: # NAS request? unknown
case 841: # NAS request? unknown
return "Router reset/reboot";
case 8: # Port error
return "Port error";
case 180: # Unknown
return "Local hangup";
case 827: # Unknown
return "Service unavailable";
return "Session Timeout";
case 6:
return "Admin Reset";
case 7:
return "Admin Reboot";
case 8:
return "Port Error";
case 9:
return "NAS Error";
case 10:
return "NAS Request";
case 11:
return "NAS Reboot";
case 12:
return "Port Unneeded";
case 13:
return "Port Preempted";
case 14:
return "Port Suspended";
case 15:
return "Service Unavailable";
case 16:
return "Callback";
case 17:
return "User Error";
case 18:
return "Host Request";
default:
return "Unkown";
}
} else {
return "Unknown";
switch ($errCode) {
case NULL:
return "Still logged in";
default:
return "Unkown";
}
}
}
# vim: ts=4
?>
<?php
# Utility functions
# Copyright (C) 2010-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.
## @fn isBoolean($param)
# Check if a variable is boolean
#
# @param var Variable to check
#
# @return 1, 0 or -1 on unknown
function isBoolean($param) {
# Check if we're set
if (!isset($param)) {
return -1;
}
# If it's already bool, just return it
if (is_bool($param)) {
return $param;
}
# If it's a string..
if (is_string($param)) {
# Nuke whitespaces
trim($param);
# Allow true, on, set, enabled, 1, false, off, unset, disabled, 0
if (preg_match('/^(?:true|on|set|enabled|1)$/i', $param)) {
return 1;
}
if (preg_match('/^(?:false|off|unset|disabled|0)$/i', $param)) {
return 0;
}
}
# Invalid or unknown
return -1;
}
# vim: ts=4
?>
<!-- Index.html - load all our code
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. -->
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
#loading-mask{
position:absolute;
left:0;
top:0;
width:100%;
height:100%;
z-index:20000;
background-color:white;
}
#loading{
position:absolute;
left:45%;
top:40%;
padding:2px;
z-index:20001;
height:auto;
}
#loading a {
color:#225588;
}
#loading .loading-indicator{
background:white;
color:#444;
font:bold 13px tahoma,arial,helvetica;
padding:10px;
margin:0;
height:auto;
}
#loading-msg {
font: normal 10px arial,tahoma,sans-serif;
}
</style>
</head>
<body>
<div id="loading-mask" style=""></div>
<div id="loading">
<div class="loading-indicator">
<img src="awitef/resources/extjs/images/extanim32.gif" width="32" height="32" style="margin-right:8px;float:left;vertical-align:top;"/>
SMRadius WebGUI - <a href="http://smradius.org">smradius.org</a><br /><span id="loading-msg">Loading styles and images...</span>
</div>
</div>
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Loading stylesheets...';</script>
<link rel="stylesheet" type="text/css" href="awitef/resources/extjs/css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="awitef/resources/custom/css/silk-icons.css" />
<link rel="stylesheet" type="text/css" href="icons.css" />
<link rel="stylesheet" type="text/css" href="awitef/resources/extjs/css/examples.css" />
<link rel="stylesheet" type="text/css" href="awitef/js/custom/GridFilters/icons/style.css" />
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Loading core API...';</script>
<script type="text/javascript" src="awitef/js/extjs/ext-base.js"></script>
<script type="text/javascript" src="awitef/js/extjs/ext-all.js"></script>
<!--
Our own libraries
-->
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Loading libraries...';</script>
<script type="text/javascript" src="awitef/js/custom/util.js"></script>
<script type="text/javascript" src="awitef/js/custom/sprintf.js"></script>
<script type="text/javascript" src="awitef/js/custom/regexes.js"></script>
<script type="text/javascript" src="awitef/js/custom/vtypes.js"></script>
<script type="text/javascript" src="awitef/js/custom/GridFilters/GridFilters.js"></script>
<script type="text/javascript" src="awitef/js/custom/GridFilters/menu/EditableItem.js"></script>
<script type="text/javascript" src="awitef/js/custom/GridFilters/menu/RangeMenu.js"></script>
<script type="text/javascript" src="awitef/js/custom/GridFilters/filter/Filter.js"></script>
<script type="text/javascript" src="awitef/js/custom/GridFilters/filter/StringFilter.js"></script>
<script type="text/javascript" src="awitef/js/custom/GridFilters/filter/DateFilter.js"></script>
<script type="text/javascript" src="awitef/js/custom/GridFilters/filter/ListFilter.js"></script>
<script type="text/javascript" src="awitef/js/custom/GridFilters/filter/NumericFilter.js"></script>
<script type="text/javascript" src="awitef/js/custom/GridFilters/filter/BooleanFilter.js"></script>
<script type="text/javascript" src="awitef/js/custom/ProgressFormPanel.js"></script>
<script type="text/javascript" src="awitef/js/custom/StatusBar.js"></script>
<script type="text/javascript" src="awitef/js/custom/common.js"></script>
<script type="text/javascript" src="awitef/js/custom/generic.js"></script>
<!--
Main application
-->
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Loading configuration...';</script>
<script type="text/javascript" src="js/app/config.js"></script>
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Loading menus...';</script>
<script type="text/javascript" src="js/app/menus.js"></script>
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Loading windows...';</script>
<script type="text/javascript" src="js/app/windows/WiSPUsers.js"></script>
<script type="text/javascript" src="js/app/windows/WiSPUserLogs.js"></script>
<script type="text/javascript" src="js/app/windows/WiSPUserTopups.js"></script>
<script type="text/javascript" src="js/app/windows/WiSPLocations.js"></script>
<script type="text/javascript" src="js/app/windows/WiSPLocationMembers.js"></script>
<script type="text/javascript" src="js/app/windows/WiSPResellers.js"></script>
<script type="text/javascript" src="js/app/windows/AdminUsers.js"></script>
<script type="text/javascript" src="js/app/windows/AdminUserLogs.js"></script>
<script type="text/javascript" src="js/app/windows/AdminUserAttributes.js"></script>
<script type="text/javascript" src="js/app/windows/AdminUserGroups.js"></script>
<script type="text/javascript" src="js/app/windows/AdminUserTopups.js"></script>
<script type="text/javascript" src="js/app/windows/AdminRealms.js"></script>
<script type="text/javascript" src="js/app/windows/AdminRealmAttributes.js"></script>
<script type="text/javascript" src="js/app/windows/AdminRealmMembers.js"></script>
<script type="text/javascript" src="js/app/windows/AdminClients.js"></script>
<script type="text/javascript" src="js/app/windows/AdminClientAttributes.js"></script>
<script type="text/javascript" src="js/app/windows/AdminClientRealms.js"></script>
<script type="text/javascript" src="js/app/windows/AdminGroups.js"></script>
<script type="text/javascript" src="js/app/windows/AdminGroupAttributes.js"></script>
<script type="text/javascript" src="js/app/windows/AdminGroupMembers.js"></script>
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Loading layout...';</script>
<script type="text/javascript" src="js/app/main-layout.js"></script>
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Starting...';</script>
<script type="text/javascript" src="js/app/main.js"></script>
</body>
</html>
/*
Webgui Global Config
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.
*/
var globalConfig = {
soap: {
username: 'admin',
password: 'password',
authtype: 'Admin'
}
};
/*
Webgui Main Layout
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.
*/
// Main viewport
function initViewport() {
// Create viewport
var viewport = new Ext.Viewport({
layout: 'border',
items: [
{
// Top bar
region:'north',
height: 30,
border: false,
items: [
{
// Add toolbar
xtype: 'toolbar',
items: [
{
text: "Radius Control Panel",
menu: radiusMenu
},
{
text: "WiSP Control Panel",
menu: wispMenu
}
]
}
]
},
// Main content
{
xtype: 'panel',
region: 'center',
autoScroll: true,
border: true,
margins:'5 5 5 5'
// items: [
// mainWindow
// ]
},
{
id: 'main-statusbar',
xtype: 'panel',
region: 'south',
border: true,
height: 30,
bbar: new Ext.ux.StatusBar({
id: 'my-status',
// defaults to use when the status is cleared:
defaultText: 'Default status text',
defaultIconCls: 'default-icon',
// values to set initially:
text: 'Ready',
iconCls: 'ready-icon'
// any standard Toolbar items:
// items: [{
// text: 'A Button'
// }, '-', 'Plain Text']
})
}
/*
{
region: 'east',
html: '<img src="resources/custom/images/smarty_icon.gif"></img>',
margins:'5 5 5 5',
border: true
}
*/
]
});
}
/*
* Ext JS Library 2.1
* Copyright(c) 2006-2008, Ext JS, LLC.
* licensing@extjs.com
*
* http://extjs.com/license
*/
Ext.onReady(function(){
// Enable tips
Ext.QuickTips.init();
// Turn on validation errors beside the field globally
Ext.form.Field.prototype.msgTarget = 'side';
// Turn off the loading icon
var hideMask = function () {
Ext.get('loading').remove();
Ext.fly('loading-mask').fadeOut({
remove: true,
callback: function() {
// Fire everything up
initViewport();
}
});
}
hideMask.defer(250);
});
/*
Webgui Menus
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.
*/
var radiusMenu = new Ext.menu.Menu({
items: [
{
text: 'Users',
iconCls: 'silk-user',
handler: function() {
showAdminUserWindow();
}
},
{
text: 'Groups',
iconCls: 'silk-group',
handler: function() {
showAdminGroupWindow();
}
},
{
text: 'Realms',
iconCls: 'silk-world',
handler: function() {
showAdminRealmWindow();
}
},
{
text: 'Clients',
iconCls: 'silk-server',
handler: function() {
showAdminClientWindow();
}
}
]
});
var wispMenu = new Ext.menu.Menu({
items: [
{
text: 'Users',
iconCls: 'silk-user',
handler: function() {
showWiSPUserWindow();
}
},
// {
// text: 'Resellers',
// handler: function() {
// showWiSPResellersWindow();
// }
// },
{
text: 'Locations',
iconCls: 'silk-map',
handler: function() {
showWiSPLocationWindow();
}
}
]
});
/*
Admin Client Attributes
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.
*/
function showAdminClientAttributesWindow(clientID) {
var AdminClientAttributesWindow = new Ext.ux.GenericGridWindow(
// Window config
{
title: "Attributes",
iconCls: 'silk-table',
width: 600,
height: 335,
minWidth: 600,
minHeight: 335
},
// Grid config
{
// Inline toolbars
tbar: [
{
text:'Add',
tooltip:'Add attribute',
iconCls:'silk-table_add',
handler: function() {
showAdminClientAttributeAddEditWindow(AdminClientAttributesWindow,clientID);
}
},
'-',
{
text:'Edit',
tooltip:'Edit attribute',
iconCls:'silk-table_edit',
handler: function() {
var selectedItem = Ext.getCmp(AdminClientAttributesWindow.gridPanelID).getSelectionModel().getSelected();
// Check if we have selected item
if (selectedItem) {
// If so display window
showAdminClientAttributeAddEditWindow(AdminClientAttributesWindow,clientID,selectedItem.data.ID);
} else {
AdminClientAttributesWindow.getEl().mask();
// Display error
Ext.Msg.show({
title: "Nothing selected",
msg: "No attribute selected",
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.CANCEL,
modal: false,
fn: function() {
AdminClientAttributesWindow.getEl().unmask();
}
});
}
}
},
'-',
{
text:'Remove',
tooltip:'Remove attribute',
iconCls:'silk-table_delete',
handler: function() {
var selectedItem = Ext.getCmp(AdminClientAttributesWindow.gridPanelID).getSelectionModel().getSelected();
// Check if we have selected item
if (selectedItem) {
// If so display window
showAdminClientAttributeRemoveWindow(AdminClientAttributesWindow,selectedItem.data.ID);
} else {
AdminClientAttributesWindow.getEl().mask();
// Display error
Ext.Msg.show({
title: "Nothing selected",
msg: "No attribute selected",
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.CANCEL,
modal: false,
fn: function() {
AdminClientAttributesWindow.getEl().unmask();
}
});
}
}
}
],
// Column model
colModel: new Ext.grid.ColumnModel([
{
id: 'ID',
header: "ID",
sortable: true,
dataIndex: 'ID'
},
{
header: "Name",
sortable: true,
dataIndex: 'Name'
},
{
header: "Operator",
sortable: true,
dataIndex: 'Operator'
},
{
header: "Value",
sortable: true,
dataIndex: 'Value'
},
{
header: "Disabled",
sortable: true,
dataIndex: 'Disabled'
}
]),
autoExpandColumn: 'Name'
},
// Store config
{
baseParams: {
ID: clientID,
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminClientAttributes',
SOAPFunction: 'getAdminClientAttributes',
SOAPParams: 'ID,__search'
}
},
// Filter config
{
filters: [
{type: 'numeric', dataIndex: 'ID'},
{type: 'string', dataIndex: 'Name'},
{type: 'string', dataIndex: 'Operator'},
{type: 'string', dataIndex: 'Value'},
{type: 'boolean', dataIndex: 'Disabled'}
]
}
);
AdminClientAttributesWindow.show();
}
// Display edit/add form
function showAdminClientAttributeAddEditWindow(AdminClientAttributesWindow,clientID,attrID) {
var submitAjaxConfig;
var icon;
// We doing an update
if (attrID) {
icon = 'silk-table_edit';
submitAjaxConfig = {
params: {
ID: attrID,
SOAPFunction: 'updateAdminClientAttribute',
SOAPParams:
'0:ID,'+
'0:Name,'+
'0:Operator,'+
'0:Value,'+
'0:Disabled:boolean'
},
onSuccess: function() {
var store = Ext.getCmp(AdminClientAttributesWindow.gridPanelID).getStore();
store.load({
params: {
limit: 25
}
});
}
};
// We doing an Add
} else {
icon = 'silk-table_add';
submitAjaxConfig = {
params: {
ClientID: clientID,
SOAPFunction: 'addAdminClientAttribute',
SOAPParams:
'0:ClientID,'+
'0:Name,'+
'0:Operator,'+
'0:Value,'+
'0:Disabled:boolean'
},
onSuccess: function() {
var store = Ext.getCmp(AdminClientAttributesWindow.gridPanelID).getStore();
store.load({
params: {
limit: 25
}
});
}
};
}
// Create window
var adminClientAttributesFormWindow = new Ext.ux.GenericFormWindow(
// Window config
{
title: "Attribute Information",
iconCls: icon,
width: 310,
height: 200,
minWidth: 310,
minHeight: 200
},
// Form panel config
{
labelWidth: 85,
baseParams: {
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminClientAttributes'
},
items: [
{
fieldLabel: 'Name',
name: 'Name',
allowBlank: false
},
{
xtype: 'combo',
fieldLabel: 'Operator',
name: 'Operator',
allowBlank: false,
width: 157,
store: [
[ '=', '=' ],
[ ':=', ':=' ],
[ '==', '==' ],
[ '+=', '+=' ],
[ '!=', '!=' ],
[ '<', '<' ],
[ '>', '>' ],
[ '<=', '<=' ],
[ '>=', '>=' ],
[ '=~', '=~' ],
[ '!~', '!~' ],
[ '=*', '=*' ],
[ '!*', '!*' ],
[ '||==', '||==' ]
],
displayField: 'Operator',
valueField: 'Operator',
hiddenName: 'Operator',
forceSelection: false,
triggerAction: 'all',
editable: true
},
{
fieldLabel: "Value",
name: "Value",
allowBlank: false
},
{
xtype: 'checkbox',
fieldLabel: 'Disabled',
name: 'Disabled'
}
]
},
// Submit button config
submitAjaxConfig
);
adminClientAttributesFormWindow.show();
if (attrID) {
Ext.getCmp(adminClientAttributesFormWindow.formPanelID).load({
params: {
ID: attrID,
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminClientAttributes',
SOAPFunction: 'getAdminClientAttribute',
SOAPParams: 'ID'
}
});
}
}
// Display remove form
function showAdminClientAttributeRemoveWindow(AdminClientAttributesWindow,id) {
// Mask AdminClientAttributesWindow window
AdminClientAttributesWindow.getEl().mask();
// Display remove confirm window
Ext.Msg.show({
title: "Confirm removal",
msg: "Are you very sure you wish to remove this attribute?",
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.YESNO,
modal: false,
fn: function(buttonId,text) {
// Check if user clicked on 'yes' button
if (buttonId == 'yes') {
// Do ajax request
uxAjaxRequest(AdminClientAttributesWindow,{
params: {
ID: id,
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminClientAttributes',
SOAPFunction: 'removeAdminClientAttribute',
SOAPParams: 'ID'
},
customSuccess: function() {
var store = Ext.getCmp(AdminClientAttributesWindow.gridPanelID).getStore();
store.load({
params: {
limit: 25
}
});
}
});
// Unmask if user answered no
} else {
AdminClientAttributesWindow.getEl().unmask();
}
}
});
}
// vim: ts=4
/*
Admin Client Realms
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.
*/
function showAdminClientRealmsWindow(clientID) {
var AdminClientRealmsWindow = new Ext.ux.GenericGridWindow(
// Window config
{
title: "Realms",
iconCls: 'silk-world',
width: 400,
height: 335,
minWidth: 400,
minHeight: 335
},
// Grid config
{
// Inline toolbars
tbar: [
{
text:'Add',
tooltip:'Add realm',
iconCls: 'silk-world_add',
handler: function() {
showAdminClientRealmAddWindow(AdminClientRealmsWindow,clientID);
}
},
'-',
{
text:'Remove',
tooltip:'Remove realm',
iconCls: 'silk-world_delete',
handler: function() {
var selectedItem = Ext.getCmp(AdminClientRealmsWindow.gridPanelID).getSelectionModel().getSelected();
// Check if we have selected item
if (selectedItem) {
// If so display window
showAdminClientRealmRemoveWindow(AdminClientRealmsWindow,selectedItem.data.ID);
} else {
AdminClientRealmsWindow.getEl().mask();
// Display error
Ext.Msg.show({
title: "Nothing selected",
msg: "No realm selected",
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.CANCEL,
modal: false,
fn: function() {
AdminClientRealmsWindow.getEl().unmask();
}
});
}
}
}
],
// Column model
colModel: new Ext.grid.ColumnModel([
{
id: 'ID',
header: "ID",
sortable: true,
dataIndex: 'ID'
},
{
header: "Name",
sortable: true,
dataIndex: 'Name'
}
]),
autoExpandColumn: 'Name'
},
// Store config
{
baseParams: {
ID: clientID,
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminClientRealms',
SOAPFunction: 'getAdminClientRealms',
SOAPParams: 'ID,__search'
}
},
// Filter config
{
filters: [
{type: 'numeric', dataIndex: 'ID'},
{type: 'string', dataIndex: 'Name'}
]
}
);
AdminClientRealmsWindow.show();
}
// Display edit/add form
function showAdminClientRealmAddWindow(AdminClientRealmsWindow,clientID,id) {
var submitAjaxConfig;
var icon;
// We doing an update
if (id) {
icon = 'silk-world_edit',
submitAjaxConfig = {
params: {
ID: id,
SOAPFunction: 'updateAdminRealm',
SOAPParams:
'0:ID,'+
'0:RealmID'
},
onSuccess: function() {
var store = Ext.getCmp(AdminClientRealmsWindow.gridPanelID).getStore();
store.load({
params: {
limit: 25
}
});
}
};
// We doing an Add
} else {
icon = 'silk-world_add',
submitAjaxConfig = {
params: {
ClientID: clientID,
SOAPFunction: 'addAdminClientRealm',
SOAPParams:
'0:ClientID,'+
'0:RealmID'
},
onSuccess: function() {
var store = Ext.getCmp(AdminClientRealmsWindow.gridPanelID).getStore();
store.load({
params: {
limit: 25
}
});
}
};
}
// Create window
var adminRealmFormWindow = new Ext.ux.GenericFormWindow(
// Window config
{
title: "Realm Information",
iconCls: icon,
width: 310,
height: 113,
minWidth: 310,
minHeight: 113
},
// Form panel config
{
labelWidth: 85,
baseParams: {
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminRealms'
},
items: [
{
xtype: 'combo',
//id: 'combo',
fieldLabel: 'Realm',
name: 'Realm',
allowBlank: false,
width: 160,
store: new Ext.ux.JsonStore({
sortInfo: { field: "Name", direction: "ASC" },
baseParams: {
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminClientRealms',
SOAPFunction: 'getAdminRealms',
SOAPParams: '__null,__search'
}
}),
displayField: 'Name',
valueField: 'ID',
hiddenName: 'RealmID',
forceSelection: true,
triggerAction: 'all',
editable: false
}
]
},
// Submit button config
submitAjaxConfig
);
adminRealmFormWindow.show();
if (id) {
Ext.getCmp(adminRealmFormWindow.formPanelID).load({
params: {
ID: id,
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminRealms',
SOAPFunction: 'getAdminRealm',
SOAPParams: 'ID'
}
});
}
}
// Display remove form
function showAdminClientRealmRemoveWindow(AdminClientRealmsWindow,id) {
// Mask AdminClientRealmsWindow window
AdminClientRealmsWindow.getEl().mask();
// Display remove confirm window
Ext.Msg.show({
title: "Confirm removal",
msg: "Are you very sure you wish to unlink this realm?",
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.YESNO,
modal: false,
fn: function(buttonId,text) {
// Check if user clicked on 'yes' button
if (buttonId == 'yes') {
// Do ajax request
uxAjaxRequest(AdminClientRealmsWindow,{
params: {
ID: id,
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminClientRealms',
SOAPFunction: 'removeAdminClientRealm',
SOAPParams: 'ID'
},
customSuccess: function() {
var store = Ext.getCmp(AdminClientRealmsWindow.gridPanelID).getStore();
store.load({
params: {
limit: 25
}
});
}
});
// Unmask if user answered no
} else {
AdminClientRealmsWindow.getEl().unmask();
}
}
});
}
// vim: ts=4
/*
Admin Clients
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.
*/
function showAdminClientWindow() {
var AdminClientWindow = new Ext.ux.GenericGridWindow(
// Window config
{
title: "Clients",
width: 600,
height: 335,
minWidth: 600,
minHeight: 335
},
// Grid config
{
// Inline toolbars
tbar: [
{
text:'Add',
tooltip:'Add client',
iconCls:'silk-server_add',
handler: function() {
showAdminClientAddEditWindow(AdminClientWindow);
}
},
'-',
{
text:'Edit',
tooltip:'Edit client',
iconCls:'silk-server_edit',
handler: function() {
var selectedItem = Ext.getCmp(AdminClientWindow.gridPanelID).getSelectionModel().getSelected();
// Check if we have selected item
if (selectedItem) {
// If so display window
showAdminClientAddEditWindow(AdminClientWindow,selectedItem.data.ID);
} else {
AdminClientWindow.getEl().mask();
// Display error
Ext.Msg.show({
title: "Nothing selected",
msg: "No client selected",
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.CANCEL,
modal: false,
fn: function() {
AdminClientWindow.getEl().unmask();
}
});
}
}
},
{
text:'Remove',
tooltip:'Remove client',
iconCls:'silk-server_delete',
handler: function() {
var selectedItem = Ext.getCmp(AdminClientWindow.gridPanelID).getSelectionModel().getSelected();
// Check if we have selected item
if (selectedItem) {
// If so display window
showAdminClientRemoveWindow(AdminClientWindow,selectedItem.data.ID);
} else {
AdminClientWindow.getEl().mask();
// Display error
Ext.Msg.show({
title: "Nothing selected",
msg: "No client selected",
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.CANCEL,
modal: false,
fn: function() {
AdminClientWindow.getEl().unmask();
}
});
}
}
},
'-',
{
text:'Attributes',
tooltip:'Client attributes',
iconCls:'silk-table',
handler: function() {
var selectedItem = Ext.getCmp(AdminClientWindow.gridPanelID).getSelectionModel().getSelected();
// Check if we have selected item
if (selectedItem) {
// If so display window
showAdminClientAttributesWindow(selectedItem.data.ID);
} else {
AdminClientWindow.getEl().mask();
// Display error
Ext.Msg.show({
title: "Nothing selected",
msg: "No client selected",
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.CANCEL,
modal: false,
fn: function() {
AdminClientWindow.getEl().unmask();
}
});
}
}
},
'-',
{
text:'Realms',
tooltip:'Realms',
iconCls:'silk-world',
handler: function() {
var selectedItem = Ext.getCmp(AdminClientWindow.gridPanelID).getSelectionModel().getSelected();
// Check if we have selected item
if (selectedItem) {
// If so display window
showAdminClientRealmsWindow(selectedItem.data.ID);
} else {
AdminClientWindow.getEl().mask();
// Display error
Ext.Msg.show({
title: "Nothing selected",
msg: "No client selected",
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.CANCEL,
modal: false,
fn: function() {
AdminClientWindow.getEl().unmask();
}
});
}
}
}
],
// Column model
colModel: new Ext.grid.ColumnModel([
{
id: 'ID',
header: "ID",
sortable: true,
dataIndex: 'ID'
},
{
header: "Name",
sortable: true,
dataIndex: 'Name'
},
{
header: "AccessList",
sortable: true,
dataIndex: 'AccessList'
}
]),
autoExpandColumn: 'Name'
},
// Store config
{
baseParams: {
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminClients',
SOAPFunction: 'getAdminClients',
SOAPParams: '__null,__search'
}
},
// Filter config
{
filters: [
{type: 'numeric', dataIndex: 'ID'},
{type: 'string', dataIndex: 'Name'},
{type: 'string', dataIndex: 'AccessList'}
]
}
);
AdminClientWindow.show();
}
// Display edit/add form
function showAdminClientAddEditWindow(AdminClientWindow,id) {
var submitAjaxConfig;
var icon;
// We doing an update
if (id) {
icon = 'silk-server_edit';
submitAjaxConfig = {
params: {
ID: id,
SOAPFunction: 'updateAdminClient',
SOAPParams:
'0:ID,'+
'0:Name,'+
'0:AccessList'
},
onSuccess: function() {
var store = Ext.getCmp(AdminClientWindow.gridPanelID).getStore();
store.load({
params: {
limit: 25
}
});
}
};
// We doing an Add
} else {
icon = 'silk-server_add';
submitAjaxConfig = {
params: {
SOAPFunction: 'createAdminClient',
SOAPParams:
'0:Name,'+
'0:AccessList'
},
onSuccess: function() {
var store = Ext.getCmp(AdminClientWindow.gridPanelID).getStore();
store.load({
params: {
limit: 25
}
});
}
};
}
// Create window
var adminClientFormWindow = new Ext.ux.GenericFormWindow(
// Window config
{
title: "Client Information",
iconCls: icon,
width: 310,
height: 143,
minWidth: 310,
minHeight: 143
},
// Form panel config
{
labelWidth: 85,
baseParams: {
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminClients'
},
items: [
{
fieldLabel: 'Name',
name: 'Name',
allowBlank: false
},
{
fieldLabel: 'AccessList',
name: 'AccessList',
allowBlank: true
}
]
},
// Submit button config
submitAjaxConfig
);
adminClientFormWindow.show();
if (id) {
Ext.getCmp(adminClientFormWindow.formPanelID).load({
params: {
ID: id,
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminClients',
SOAPFunction: 'getAdminClient',
SOAPParams: 'ID'
}
});
}
}
// Display remove form
function showAdminClientRemoveWindow(AdminClientWindow,id) {
// Mask AdminClientWindow window
AdminClientWindow.getEl().mask();
// Display remove confirm window
Ext.Msg.show({
title: "Confirm removal",
msg: "Are you very sure you wish to remove this client?",
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.YESNO,
modal: false,
fn: function(buttonId,text) {
// Check if user clicked on 'yes' button
if (buttonId == 'yes') {
// Do ajax request
uxAjaxRequest(AdminClientWindow,{
params: {
ID: id,
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminClients',
SOAPFunction: 'removeAdminClient',
SOAPParams: 'ID'
},
customSuccess: function() {
var store = Ext.getCmp(AdminClientWindow.gridPanelID).getStore();
store.load({
params: {
limit: 25
}
});
}
});
// Unmask if user answered no
} else {
AdminClientWindow.getEl().unmask();
}
}
});
}
// vim: ts=4
/*
Admin Group Attributes
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.
*/
function showAdminGroupAttributesWindow(groupID) {
var AdminGroupAttributesWindow = new Ext.ux.GenericGridWindow(
// Window config
{
title: "Attributes",
iconCls: 'silk-table',
width: 600,
height: 335,
minWidth: 600,
minHeight: 335
},
// Grid config
{
// Inline toolbars
tbar: [
{
text:'Add',
tooltip:'Add attribute',
iconCls:'silk-table_add',
handler: function() {
showAdminGroupAttributeAddEditWindow(AdminGroupAttributesWindow,groupID);
}
},
'-',
{
text:'Edit',
tooltip:'Edit attribute',
iconCls:'silk-table_edit',
handler: function() {
var selectedItem = Ext.getCmp(AdminGroupAttributesWindow.gridPanelID).getSelectionModel().getSelected();
// Check if we have selected item
if (selectedItem) {
// If so display window
showAdminGroupAttributeAddEditWindow(AdminGroupAttributesWindow,groupID,selectedItem.data.ID);
} else {
AdminGroupAttributesWindow.getEl().mask();
// Display error
Ext.Msg.show({
title: "Nothing selected",
msg: "No attribute selected",
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.CANCEL,
modal: false,
fn: function() {
AdminGroupAttributesWindow.getEl().unmask();
}
});
}
}
},
'-',
{
text:'Remove',
tooltip:'Remove attribute',
iconCls:'silk-table_delete',
handler: function() {
var selectedItem = Ext.getCmp(AdminGroupAttributesWindow.gridPanelID).getSelectionModel().getSelected();
// Check if we have selected item
if (selectedItem) {
// If so display window
showAdminGroupAttributeRemoveWindow(AdminGroupAttributesWindow,selectedItem.data.ID);
} else {
AdminGroupAttributesWindow.getEl().mask();
// Display error
Ext.Msg.show({
title: "Nothing selected",
msg: "No attribute selected",
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.CANCEL,
modal: false,
fn: function() {
AdminGroupAttributesWindow.getEl().unmask();
}
});
}
}
}
],
// Column model
colModel: new Ext.grid.ColumnModel([
{
id: 'ID',
header: "ID",
sortable: true,
dataIndex: 'ID'
},
{
header: "Name",
sortable: true,
dataIndex: 'Name'
},
{
header: "Operator",
sortable: true,
dataIndex: 'Operator'
},
{
header: "Value",
sortable: true,
dataIndex: 'Value'
},
{
header: "Disabled",
sortable: true,
dataIndex: 'Disabled'
}
]),
autoExpandColumn: 'Name'
},
// Store config
{
baseParams: {
ID: groupID,
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminGroupAttributes',
SOAPFunction: 'getAdminGroupAttributes',
SOAPParams: 'ID,__search'
}
},
// Filter config
{
filters: [
{type: 'numeric', dataIndex: 'ID'},
{type: 'string', dataIndex: 'Name'},
{type: 'string', dataIndex: 'Operator'},
{type: 'string', dataIndex: 'Value'},
{type: 'boolean', dataIndex: 'Disabled'}
]
}
);
AdminGroupAttributesWindow.show();
}
// Display edit/add form
function showAdminGroupAttributeAddEditWindow(AdminGroupAttributesWindow,groupID,attrID) {
var submitAjaxConfig;
var icon;
// We doing an update
if (attrID) {
icon = 'silk-table_edit';
submitAjaxConfig = {
params: {
ID: attrID,
SOAPFunction: 'updateAdminGroupAttribute',
SOAPParams:
'0:ID,'+
'0:Name,'+
'0:Operator,'+
'0:Value,'+
'0:Disabled:boolean'
},
onSuccess: function() {
var store = Ext.getCmp(AdminGroupAttributesWindow.gridPanelID).getStore();
store.load({
params: {
limit: 25
}
});
}
};
// We doing an Add
} else {
icon = 'silk-table_add';
submitAjaxConfig = {
params: {
GroupID: groupID,
SOAPFunction: 'addAdminGroupAttribute',
SOAPParams:
'0:GroupID,'+
'0:Name,'+
'0:Operator,'+
'0:Value,'+
'0:Disabled:boolean'
},
onSuccess: function() {
var store = Ext.getCmp(AdminGroupAttributesWindow.gridPanelID).getStore();
store.load({
params: {
limit: 25
}
});
}
};
}
// Create window
var adminGroupAttributesFormWindow = new Ext.ux.GenericFormWindow(
// Window config
{
title: "Attribute Information",
iconCls: icon,
width: 310,
height: 200,
minWidth: 310,
minHeight: 200
},
// Form panel config
{
labelWidth: 85,
baseParams: {
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminGroupAttributes'
},
items: [
{
fieldLabel: 'Name',
name: 'Name',
allowBlank: false
},
{
xtype: 'combo',
fieldLabel: 'Operator',
name: 'Operator',
allowBlank: false,
width: 157,
store: [
[ '=', '=' ],
[ ':=', ':=' ],
[ '==', '==' ],
[ '+=', '+=' ],
[ '!=', '!=' ],
[ '<', '<' ],
[ '>', '>' ],
[ '<=', '<=' ],
[ '>=', '>=' ],
[ '=~', '=~' ],
[ '!~', '!~' ],
[ '=*', '=*' ],
[ '!*', '!*' ],
[ '||==', '||==' ]
],
displayField: 'Operator',
valueField: 'Operator',
hiddenName: 'Operator',
forceSelection: false,
triggerAction: 'all',
editable: true
},
{
fieldLabel: "Value",
name: "Value",
allowBlank: false
},
{
xtype: 'checkbox',
fieldLabel: 'Disabled',
name: 'Disabled'
}
]
},
// Submit button config
submitAjaxConfig
);
adminGroupAttributesFormWindow.show();
if (attrID) {
Ext.getCmp(adminGroupAttributesFormWindow.formPanelID).load({
params: {
ID: attrID,
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminGroupAttributes',
SOAPFunction: 'getAdminGroupAttribute',
SOAPParams: 'ID'
}
});
}
}
// Display remove form
function showAdminGroupAttributeRemoveWindow(AdminGroupAttributesWindow,id) {
// Mask AdminGroupAttributesWindow window
AdminGroupAttributesWindow.getEl().mask();
// Display remove confirm window
Ext.Msg.show({
title: "Confirm removal",
msg: "Are you very sure you wish to remove this attribute?",
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.YESNO,
modal: false,
fn: function(buttonId,text) {
// Check if user clicked on 'yes' button
if (buttonId == 'yes') {
// Do ajax request
uxAjaxRequest(AdminGroupAttributesWindow,{
params: {
ID: id,
SOAPUsername: globalConfig.soap.username,
SOAPPassword: globalConfig.soap.password,
SOAPAuthType: globalConfig.soap.authtype,
SOAPModule: 'AdminGroupAttributes',
SOAPFunction: 'removeAdminGroupAttribute',
SOAPParams: 'ID'
},
customSuccess: function() {
var store = Ext.getCmp(AdminGroupAttributesWindow.gridPanelID).getStore();
store.load({
params: {
limit: 25
}
});
}
});
// Unmask if user answered no
} else {
AdminGroupAttributesWindow.getEl().unmask();
}
}
});
}
// vim: ts=4