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 3437 additions and 452 deletions
<?php
# Admin Realms functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php");
# Return list of users
# Return list of realms
function getAdminRealms($params) {
global $db;
$sql = "SELECT ID, Name, Disabled FROM realms";
$res = $db->query($sql);
# Filters and sorts are the same here
$filtersorts = array(
'ID' => '@TP@realms.ID',
'Name' => '@TP@realms.Name',
'Disabled' => '@TP@realms.Disabled'
);
# Perform query
$res = DBSelectSearch("SELECT ID, Name, Disabled FROM @TP@realms",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) {
return $res;
}
# Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) {
$item = array();
$item['ID'] = $row->id;
$item['Name'] = htmlspecialchars($row->name);
$item['Disabled'] = $row->disabled;
# Push this row onto array
array_push($resultArray,$item);
}
# Return results
return array($resultArray,$numResults);
}
# Return specific realm row
function getAdminRealm($params) {
# loop through rows
while ($row = $res->fetchObject()) {
$item = array();
# Perform query
$res = DBSelect("SELECT ID, Name, Disabled FROM @TP@realms WHERE ID = ?",array($params[0]));
# Return error if failed
if (!is_object($res)) {
return $res;
}
# Build array of results
$resultArray = array();
$row = $res->fetchObject();
$resultArray['ID'] = $row->id;
$resultArray['Name'] = $row->name;
$resultArray['Disabled'] = $row->disabled;
# Return results
return $resultArray;
}
# Remove admin realm
function removeAdminRealm($params) {
# Begin transaction
DBBegin();
# Perform query
$res = DBDo("DELETE FROM @TP@realm_attributes WHERE RealmID = ?",array($params[0]));
# Perform next query if successful
if ($res !== FALSE) {
$res = DBDo("DELETE FROM @TP@realms WHERE ID = ?",array($params[0]));
}
# Return result
if ($res !== TRUE) {
DBRollback();
return $res;
} else {
DBCommit();
}
return NULL;
}
# Add admin realm
function createAdminRealm($params) {
# Perform query
$res = DBDo("INSERT INTO @TP@realms (Name) VALUES (?)",array($params[0]['Name']));
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
$item['ID'] = $row->id;
$item['Name'] = $row->name;
$item['Disabled'] = $row->disabled;
# Edit admin realm
function updateAdminRealm($params) {
# push this row onto array
array_push($resultArray,$item);
}
# Perform query
$res = DBDo("UPDATE @TP@realms SET Name = ? WHERE ID = ?",array($params[0]['Name'],$params[0]['ID']));
# get number of rows
$sql = "SELECT count(*) FROM realms";
$res = $db->query($sql);
$numResults = $res->fetchColumn();
# Return result
if ($res !== TRUE) {
return $res;
}
return array($numResults,$resultArray);
return NULL;
}
?>
# vim: ts=4
<?php
# Admin User Attributes functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php");
include_once("include/util.php");
# Add user attribute
function addAdminUserAttribute($params) {
# Check Disabled param
$disabled = isBoolean($params[0]['Disabled']);
if ($disabled < 0) {
return NULL;
}
# Perform query
$res = DBDo("
INSERT INTO
@TP@user_attributes (UserID,Name,Operator,Value,Disabled)
VALUES
(?,?,?,?,?)",
array( $params[0]['UserID'],
$params[0]['Name'],
$params[0]['Operator'],
$params[0]['Value'],
$disabled)
);
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Remove user attribute
function removeAdminUserAttribute($params) {
# Perform query
$res = DBDo("DELETE FROM @TP@user_attributes WHERE ID = ?",array($params[0]));
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Edit attribute
function updateAdminUserAttribute($params) {
# Check Disabled param
$disabled = isBoolean($params[0]['Disabled']);
if ($disabled < 0) {
return NULL;
}
# Perform query
$res = DBDo("UPDATE @TP@user_attributes SET Name = ?, Operator = ?, Value = ?, Disabled = ? WHERE ID = ?",
array($params[0]['Name'],
$params[0]['Operator'],
$params[0]['Value'],
$disabled,
$params[0]['ID'])
);
# Return error
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Return specific attribute row
function getAdminUserAttribute($params) {
# Perform query
$res = DBSelect("SELECT ID, Name, Operator, Value, Disabled FROM @TP@user_attributes WHERE ID = ?",array($params[0]));
# Return error if failed
if (!is_object($res)) {
return $res;
}
# Build array of results
$resultArray = array();
$row = $res->fetchObject();
$resultArray['ID'] = $row->id;
$resultArray['Name'] = $row->name;
$resultArray['Operator'] = $row->operator;
$resultArray['Value'] = $row->value;
$resultArray['Disabled'] = $row->disabled;
# Return results
return $resultArray;
}
# Return list of attributes
function getAdminUserAttributes($params) {
# Filters and sorts are the same here
$filtersorts = array(
'ID' => '@TP@user_attributes.ID',
'Name' => '@TP@user_attributes.Name',
'Operator' => '@TP@user_attributes.Operator',
'Value' => '@TP@user_attributes.Value',
'Disabled' => '@TP@user_attributes.Disabled'
);
# Perform query
$res = DBSelectSearch("
SELECT
ID, Name, Operator, Value, Disabled
FROM
@TP@user_attributes
WHERE
UserID = ".DBQuote($params[0])."
",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) {
return $res;
}
# Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) {
$item = array();
$item['ID'] = $row->id;
$item['Name'] = $row->name;
$item['Operator'] = $row->operator;
$item['Value'] = $row->value;
$item['Disabled'] = $row->disabled;
# Push this row onto array
array_push($resultArray,$item);
}
# Return results
return array($resultArray,$numResults);
}
# vim: ts=4
<?php
# Radius Location Add
# Copyright (C) 2007-2009, AllWorldIT
# Admin User Groups functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
......@@ -16,81 +16,77 @@
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("includes/header.php");
include_once("includes/footer.php");
include_once("includes/db.php");
$db = connect_db();
printHeader(array(
"Tabs" => array(
"Back to locations list" => "wisp-locations-main.php"
),
));
if (isset($_POST['frmaction']) && $_POST['frmaction'] == "add") {
?>
<p class="pageheader">Add location</p>
<form method="post" action="wisp-locations-add.php">
<div>
<input type="hidden" name="frmaction" value="add2" />
</div>
<table class="entry">
<tr>
<td class="entrytitle">Location</td>
<td><input type="text" name="location" /></td>
</tr>
<tr>
<td class="textcenter" colspan="2">
<input type="submit" />
</td>
</tr>
</table>
</form>
include_once("include/db.php");
<?php
# Check we have all params
} elseif (isset($_POST['frmaction']) && $_POST['frmaction'] == "add2") {
?>
<p class="pageheader">Location Add Results</p>
<?php
# Link user to group
function addAdminUserGroup($params) {
# Check name
if (empty($_POST['location'])) {
?>
<div class="warning">Location cannot be empty</div>
<?php
# Perform query
$res = DBDo("INSERT INTO @TP@users_to_groups (UserID,GroupID) VALUES (?,?)",array($params[0]['UserID'],$params[0]['GroupID']));
# Add to database
} else {
$stmt = $db->prepare("INSERT INTO ${DB_TABLE_PREFIX}wisp_locations (Location) VALUES (?)");
$res = $stmt->execute(array(
$_POST['location'],
));
# Was it successful?
if ($res !== FALSE) {
?>
<div class="notice">Location added</div>
<?php
} else {
?>
<div class="warning">Failed to add location</div>
<div class="warning"><?php print_r($stmt->errorInfo()) ?></div>
<?php
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Unlink user from group
function removeAdminUserGroup($params) {
# Perform query
$res = DBDo("DELETE FROM @TP@users_to_groups WHERE ID = ?",array($params[0]));
}
# Return result
if ($res !== TRUE) {
return $res;
}
} else {
?>
<div class="warning">Invalid invocation</div>
<?php
return NULL;
}
# Return list of groups
function getAdminUserGroups($params) {
# Filters and sorts are the same here
$filtersorts = array(
'ID' => '@TP@users_to_groups.ID',
'Name' => '@TP@groups.Name'
);
# Perform query
$res = DBSelectSearch("
SELECT
@TP@users_to_groups.ID, @TP@groups.Name
FROM
@TP@users_to_groups, @TP@groups
WHERE
@TP@users_to_groups.GroupID = @TP@groups.ID
AND @TP@users_to_groups.UserID = ".DBQuote($params[0])."
",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) {
return $res;
}
printFooter();
# Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) {
$item = array();
$item['ID'] = $row->id;
$item['Name'] = $row->name;
# Push this row onto array
array_push($resultArray,$item);
}
# Return results
return array($resultArray,$numResults);
}
# vim: ts=4
?>
<?php
# Admin User Logs functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php");
# Return user logs summary
function getAdminUserLogsSummary($params) {
# Get group attributes
# fixme - user might be member of multiple groups
$res = DBSelect("
SELECT
@TP@group_attributes.Name,
@TP@group_attributes.Value
FROM
@TP@group_attributes, @TP@users_to_groups, @TP@groups
WHERE
@TP@group_attributes.GroupID = @TP@groups.ID
AND @TP@groups.ID = @TP@users_to_groups.GroupID
AND @TP@users_to_groups.UserID = ?",
array($params[0]['ID'])
);
# Return if error
if (!is_object($res)) {
return $res;
}
# Fetch uptime and traffic limits, if not found, this is prepaid account.. use -1 as we need int
$trafficCap = -1;
$uptimeCap = -1;
while ($row = $res->fetchObject()) {
if ($row->name == 'SMRadius-Capping-Traffic-Limit') {
$trafficCap = (int)$row->value;
}
if ($row->name == 'SMRadius-Capping-Uptime-Limit') {
$uptimeCap = (int)$row->value;
}
}
# Get user attributes
$res = DBSelect("
SELECT
Name,
Value
FROM
@TP@user_attributes
WHERE
UserID = ?",
array($params[0]['ID'])
);
# Return if error
if (!is_object($res)) {
return $res;
}
# Fetch uptime and traffic limits, if not found, this is prepaid account.. use -1 as we need int
while ($row = $res->fetchObject()) {
if ($row->name == 'SMRadius-Capping-Traffic-Limit') {
$trafficCap = (int)$row->value;
}
if ($row->name == 'SMRadius-Capping-Uptime-Limit') {
$uptimeCap = (int)$row->value;
}
}
# Add caps to result
$resultArray = array();
$resultArray['trafficCap'] = $trafficCap;
$resultArray['uptimeCap'] = $uptimeCap;
# Dates we want to use to search search
$periodKey = new DateTime($params[0]['PeriodKey']."-01");
# Return if error
if (!is_object($periodKey)) {
return $periodKey;
}
# Fetch user uptime and traffic summary
$res = DBSelect("
SELECT
@TP@topups_summary.Balance,
@TP@topups.ID,
@TP@topups.Type,
@TP@topups.Value,
@TP@topups.ValidTo
FROM
@TP@topups_summary,
@TP@topups
WHERE
@TP@topups_summary.TopupID = @TP@topups.ID
AND @TP@topups.UserID = ?
AND @TP@topups_summary.PeriodKey = ?
AND @TP@topups_summary.Depleted = 0
ORDER BY
@TP@topups.Timestamp ASC",
array($params[0]['ID'],$periodKey->format('Y-m'))
);
# Return if error
if (!is_object($res)) {
return $res;
}
# Store summary topups
$topups = array();
$i = 0;
while ($row = $res->fetchObject()) {
$topups[$i] = array();
$topups[$i]['ID'] = $row->id;
$topups[$i]['ValidTo'] = $row->validto;
$topups[$i]['Type'] = $row->type;
$topups[$i]['CurrentLimit'] = $row->balance;
$topups[$i]['Limit'] = $row->value;
$i++;
}
# Fetch user uptime and traffic topups
$periodKeyEnd = new DateTime($periodKey->format('Y-m-d'));
$periodKeyEnd->modify("+1 month");
$res = DBSelect("
SELECT
ID, Value, Type, ValidTo
FROM
@TP@topups
WHERE
UserID = ?
AND ValidFrom = ?
AND ValidTo >= ?
AND Depleted = 0
ORDER BY
Timestamp ASC",
array($params[0]['ID'],$periodKey->format('Y-m-d'),$periodKeyEnd->format('Y-m-d'))
);
# Return if error
if (!is_object($res)) {
return $res;
}
# Store normal topups
while ($row = $res->fetchObject()) {
$topups[$i] = array();
$topups[$i]['ID'] = $row->id;
$topups[$i]['ValidTo'] = $row->validto;
$topups[$i]['Type'] = $row->type;
$topups[$i]['Limit'] = $row->value;
$i++;
}
$res = DBSelect("
SELECT
SUM(@TP@accounting.AcctSessionTime) / 60 AS TotalSessionTime,
SUM(@TP@accounting.AcctInputOctets) / 1024 / 1024 +
SUM(@TP@accounting.AcctInputGigawords) * 4096 +
SUM(@TP@accounting.AcctOutputOctets) / 1024 / 1024 +
SUM(@TP@accounting.AcctOutputGigawords) * 4096 AS TotalTraffic
FROM
@TP@accounting, @TP@users
WHERE
@TP@users.ID = ?
AND @TP@accounting.PeriodKey = ?
AND @TP@accounting.Username = @TP@users.Username",
array($params[0]['ID'],$periodKey->format('Y-m'))
);
if (!is_object($res)) {
return $res;
}
# Set total traffic and uptime used
$row = $res->fetchObject();
# Add usage to our return array
$resultArray['trafficUsage'] = 0;
$resultArray['uptimeUsage'] = 0;
if (isset($row->totaltraffic) && $row->totaltraffic > 0) {
$resultArray['trafficUsage'] += $row->totaltraffic;
}
if (isset($row->totalsessiontime) && $row->totalsessiontime > 0) {
$resultArray['uptimeUsage'] += $row->totalsessiontime;
}
# Excess usage
$excessTraffic = 0;
if ($trafficCap == -1) {
$excessTraffic = $resultArray['trafficUsage'];
} else {
$excessTraffic = $resultArray['trafficUsage'] > $trafficCap ? ($resultArray['trafficUsage'] - $trafficCap) : 0;
}
$excessUptime = 0;
if ($uptimeCap == -1) {
$excessUptime = $resultArray['uptimeUsage'];
} else {
$excessUptime = $resultArray['uptimeUsage'] > $uptimeCap ? ($resultArray['uptimeUsage'] - $uptimeCap) : 0;
}
# Loop through topups and add to return array
$resultArray['trafficTopups'] = 0;
$resultArray['uptimeTopups'] = 0;
$resultArray['TotalTrafficTopups'] = 0;
$resultArray['TotalUptimeTopups'] = 0;
# Traffic and uptime topups
$resultArray['AllTrafficTopups'] = array();
$resultArray['AllUptimeTopups'] = array();
$t = 0; $u = 0;
foreach ($topups as $topupItem) {
if ($topupItem['Type'] == 1) {
# Topup not currently in use
if ($excessTraffic <= 0) {
# Add stats to topup array
$resultArray['AllTrafficTopups'][$t] = array();
$resultArray['AllTrafficTopups'][$t]['Used'] = isset($topupItem['CurrentLimit']) ? ($topupItem['Limit'] - $topupItem['CurrentLimit']) : 0;
$resultArray['AllTrafficTopups'][$t]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllTrafficTopups'][$t]['ID'] = $topupItem['ID'];
$resultArray['AllTrafficTopups'][$t]['ValidTo'] = $topupItem['ValidTo'];
$t++;
# Set total available topups
$resultArray['trafficTopups'] += isset($topupItem['CurrentLimit']) ? $topupItem['CurrentLimit'] : $topupItem['Limit'];
$resultArray['TotalTrafficTopups'] += $topupItem['Limit'];
# Topup currently in use
} elseif (!isset($topupItem['CurrentLimit']) && $excessTraffic < $topupItem['Limit']) {
# Add stats to topup array
$resultArray['AllTrafficTopups'][$t] = array();
$resultArray['AllTrafficTopups'][$t]['Used'] = $excessTraffic;
$resultArray['AllTrafficTopups'][$t]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllTrafficTopups'][$t]['ID'] = $topupItem['ID'];
$resultArray['AllTrafficTopups'][$t]['ValidTo'] = $topupItem['ValidTo'];
$t++;
# Set total available topups
$resultArray['trafficTopups'] += $topupItem['Limit'];
$resultArray['TotalTrafficTopups'] += $topupItem['Limit'];
# If we hit this topup then all the rest of them are available
$excessTraffic = 0;
} elseif (isset($topupItem['CurrentLimit']) && $excessTraffic < $topupItem['CurrentLimit']) {
# Add stats to topup array
$resultArray['AllTrafficTopups'][$t] = array();
$resultArray['AllTrafficTopups'][$t]['Used'] = ($topupItem['Limit'] - $topupItem['CurrentLimit']) + $excessTraffic;
$resultArray['AllTrafficTopups'][$t]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllTrafficTopups'][$t]['ID'] = $topupItem['ID'];
$resultArray['AllTrafficTopups'][$t]['ValidTo'] = $topupItem['ValidTo'];
$t++;
# Set total available topups
$resultArray['trafficTopups'] += $topupItem['CurrentLimit'];
$resultArray['TotalTrafficTopups'] += $topupItem['Limit'];
# If we hit this topup then all the rest of them are available
$excessTraffic = 0;
# Topup has been used up
} else {
# Add stats to topup array
$resultArray['AllTrafficTopups'][$t] = array();
$resultArray['AllTrafficTopups'][$t]['Used'] = (int)$topupItem['Limit'];
$resultArray['AllTrafficTopups'][$t]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllTrafficTopups'][$t]['ID'] = $topupItem['ID'];
$resultArray['AllTrafficTopups'][$t]['ValidTo'] = $topupItem['ValidTo'];
$t++;
$resultArray['trafficTopups'] += isset($topupItem['CurrentLimit']) ? $topupItem['CurrentLimit'] : $topupItem['Limit'];
$resultArray['TotalTrafficTopups'] += $topupItem['Limit'];
# Subtract this topup from excessTraffic usage
$excessTraffic -= isset($topupItem['CurrentLimit']) ? $topupItem['CurrentLimit'] : $topupItem['Limit'];
}
}
if ($topupItem['Type'] == 2) {
# Topup not currently in use
if ($excessUptime <= 0) {
# Add stats to topup array
$resultArray['AllUptimeTopups'][$u] = array();
$resultArray['AllUptimeTopups'][$u]['Used'] = isset($topupItem['CurrentLimit']) ? ($topupItem['Limit'] - $topupItem['CurrentLimit']) : 0;
$resultArray['AllUptimeTopups'][$u]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllUptimeTopups'][$u]['ID'] = $topupItem['ID'];
$resultArray['AllUptimeTopups'][$u]['ValidTo'] = $topupItem['ValidTo'];
$u++;
# Set total available topups
$resultArray['uptimeTopups'] += isset($topupItem['CurrentLimit']) ? $topupItem['CurrentLimit'] : $topupItem['Limit'];
$resultArray['TotalUptimeTopups'] += $topupItem['Limit'];
# Topup currently in use
} elseif (!isset($topupItem['CurrentLimit']) && $excessUptime < $topupItem['Limit']) {
# Add stats to topup array
$resultArray['AllUptimeTopups'][$u] = array();
$resultArray['AllUptimeTopups'][$u]['Used'] = $excessTraffic;
$resultArray['AllUptimeTopups'][$u]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllUptimeTopups'][$u]['ID'] = $topupItem['ID'];
$resultArray['AllUptimeTopups'][$u]['ValidTo'] = $topupItem['ValidTo'];
$u++;
# Set total available topups
$resultArray['uptimeTopups'] += $topupItem['Limit'];
$resultArray['TotalUptimeTopups'] += $topupItem['Limit'];
# If we hit this topup then all the rest of them are available
$excessUptime = 0;
} elseif (isset($topupItem['CurrentLimit']) && $excessUptime < $topupItem['CurrentLimit']) {
# Add stats to topup array
$resultArray['AllUptimeTopups'][$u] = array();
$resultArray['AllUptimeTopups'][$u]['Used'] = ($topupItem['Limit'] - $topupItem['CurrentLimit']) + $excessTraffic;
$resultArray['AllUptimeTopups'][$u]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllUptimeTopups'][$u]['ID'] = $topupItem['ID'];
$resultArray['AllUptimeTopups'][$u]['ValidTo'] = $topupItem['ValidTo'];
$u++;
# Set total available topups
$resultArray['uptimeTopups'] += $topupItem['CurrentLimit'];
$resultArray['TotalUptimeTopups'] += $topupItem['Limit'];
# If we hit this topup then all the rest of them are available
$excessUptime = 0;
# Topup has been used up
} else {
# Add stats to topup array
$resultArray['AllUptimeTopups'][$u] = array();
$resultArray['AllUptimeTopups'][$u]['Used'] = (int)$topupItem['Limit'];
$resultArray['AllUptimeTopups'][$u]['Cap'] = (int)$topupItem['Limit'];
$resultArray['AllUptimeTopups'][$u]['ID'] = $topupItem['ID'];
$resultArray['AllUptimeTopups'][$u]['ValidTo'] = $topupItem['ValidTo'];
$u++;
$resultArray['uptimeTopups'] += isset($topupItem['CurrentLimit']) ? $topupItem['CurrentLimit'] : $topupItem['Limit'];
$resultArray['TotalUptimeTopups'] += $topupItem['Limit'];
# Subtract this topup from excessUptime usage
$excessUptime -= isset($topupItem['CurrentLimit']) ? $topupItem['CurrentLimit'] : $topupItem['Limit'];
}
}
}
# Return results
return array($resultArray, 1);
}
# Return list of user logs
function getAdminUserLogs($params) {
# Filters and sorts are the same here
$filtersorts = array(
'ID' => '@TP@accounting.ID',
'EventTimestamp' => '@TP@accounting.EventTimestamp',
'AcctStatusType' => '@TP@accounting.AcctStatusType',
'ServiceType' => '@TP@accounting.ServiceType',
'FramedProtocol' => '@TP@accounting.FramedProtocol',
'NASPortType' => '@TP@accounting.NASPortType',
'NASPortID' => '@TP@accounting.NASPortID',
'CallingStationID' => '@TP@accounting.CallingStationID',
'CalledStationID' => '@TP@accounting.CalledStationID',
'AcctSessionID' => '@TP@accounting.AcctSessionID',
'FramedIPAddress' => '@TP@accounting.FramedIPAddress',
);
# Perform query
$res = DBSelectSearch("
SELECT
@TP@accounting.ID,
@TP@accounting.EventTimestamp,
@TP@accounting.AcctStatusType,
@TP@accounting.ServiceType,
@TP@accounting.FramedProtocol,
@TP@accounting.NASPortType,
@TP@accounting.NASPortID,
@TP@accounting.CallingStationID,
@TP@accounting.CalledStationID,
@TP@accounting.AcctSessionID,
@TP@accounting.FramedIPAddress,
@TP@accounting.AcctInputOctets / 1024 / 1024 +
@TP@accounting.AcctInputGigawords * 4096 AS AcctInput,
@TP@accounting.AcctOutputOctets / 1024 / 1024 +
@TP@accounting.AcctOutputGigawords * 4096 AS AcctOutput,
@TP@accounting.AcctTerminateCause,
@TP@accounting.AcctSessionTime / 60 AS AcctSessionTime
FROM
@TP@accounting, @TP@users
WHERE
@TP@users.Username = @TP@accounting.Username
AND
@TP@users.ID = ".DBQuote($params[0])."
",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) {
return $res;
}
# Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) {
# Input
$acctInput = 0;
if (isset($row->acctinput) && $row->acctinput > 0) {
$acctInput += $row->acctinput;
}
# Output
$acctOutput = 0;
if (isset($row->acctoutput) && $row->acctoutput > 0) {
$acctOutput += $row->acctoutput;
}
# Uptime
$acctSessionTime = 0;
if (isset($row->acctsessiontime) && $row->acctsessiontime > 0) {
$acctSessionTime += $row->acctsessiontime;
}
# Build array for this row
$item = array();
$item['ID'] = $row->id;
# Convert to ISO format
$date = new DateTime($row->eventtimestamp);
$value = $date->format("Y-m-d H:i:s");
$item['EventTimestamp'] = $value;
$item['AcctStatusType'] = $row->acctstatustype;
$item['ServiceType'] = $row->servicetype;
$item['FramedProtocol'] = $row->framedprotocol;
$item['NASPortType'] = $row->nasporttype;
$item['NASPortID'] = $row->nasportid;
$item['CallingStationID'] = $row->callingstationid;
$item['CalledStationID'] = $row->calledstationid;
$item['AcctSessionID'] = $row->acctsessionid;
$item['FramedIPAddress'] = $row->framedipaddress;
$item['AcctInput'] = $acctInput;
$item['AcctOutput'] = $acctOutput;
$item['AcctSessionTime'] = (int)$acctSessionTime;
$item['ConnectTermReason'] = strRadiusTermCode($row->acctterminatecause);
# Push this row onto main array
array_push($resultArray,$item);
}
# Return results
return array($resultArray,$numResults);
}
# vim: ts=4
<?php
# Admin User Topups functions
# Copyright (C) 2007-2011, AllWorldIT
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include_once("include/db.php");
# Add new topup
function createAdminUserTopup($params) {
# Get today's date
$timestamp = date('Y-m-d H:i:s');
# Perform query
$res = DBDo("INSERT INTO @TP@topups (UserID,Timestamp,Type,Value,ValidFrom,ValidTo) VALUES (?,?,?,?,?,?)",
array($params[0]['UserID'],$timestamp,$params[0]['Type'],$params[0]['Value'],$params[0]['ValidFrom'],
$params[0]['ValidTo'])
);
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Edit topup
function updateAdminUserTopup($params) {
# Perform query
$res = DBDo("UPDATE @TP@topups SET Value = ?, Type = ?, ValidFrom = ?, ValidTo = ? WHERE ID = ?",
array($params[0]['Value'],
$params[0]['Type'],
$params[0]['ValidFrom'],
$params[0]['ValidTo'],
$params[0]['ID'])
);
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Delete user topup
function removeAdminUserTopup($params) {
# Delete topup summary
$res = DBDo("DELETE FROM @TP@topups_summary WHERE TopupID = ?",array($params[0]));
# Return result
if ($res !== TRUE) {
return $res;
}
# Delete topup
$res = DBDo("DELETE FROM @TP@topups WHERE ID = ?",array($params[0]));
# Return result
if ($res !== TRUE) {
return $res;
}
return NULL;
}
# Return specific topup row
function getAdminUserTopup($params) {
# Perform query
$res = DBSelect("SELECT ID, Type, Value, ValidFrom, ValidTo FROM @TP@topups WHERE ID = ?",array($params[0]));
# Return error if failed
if (!is_object($res)) {
return $res;
}
# Build array of results
$resultArray = array();
$row = $res->fetchObject();
$resultArray['ID'] = $row->id;
$resultArray['Type'] = $row->type;
$resultArray['Value'] = $row->value;
# Convert to ISO format
$date = new DateTime($row->validfrom);
$value = $date->format("Y-m-d");
$resultArray['ValidFrom'] = $value;
# Convert to ISO format
$date = new DateTime($row->validto);
$value = $date->format("Y-m-d");
$resultArray['ValidTo'] = $value;
# Return results
return $resultArray;
}
# Return list of topups
function getAdminUserTopups($params) {
# Filters and sorts are the same here
$filtersorts = array(
'ID' => '@TP@topups.ID',
'Type' => '@TP@topups.Type',
'Value' => '@TP@topups.Value',
'ValidFrom' => '@TP@topups.ValidFrom',
'ValidTo' => '@TP@topups.ValidTo'
);
# Perform query
$res = DBSelectSearch("
SELECT
ID, Timestamp, Type, Value, ValidFrom, ValidTo
FROM
@TP@topups
WHERE
Depleted = 0
AND
UserID = ".DBQuote($params[0]['UserID'])."
ORDER BY
Timestamp
DESC
",$params[1],$filtersorts,$filtersorts);
$sth = $res[0]; $numResults = $res[1];
# If STH is blank, return the error back to whoever requested the data
if (!isset($sth)) {
return $res;
}
# Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) {
# Array for this row
$item = array();
$item['ID'] = $row->id;
$item['Timestamp'] = $row->timestamp;
$item['Type'] = $row->type;
$item['Value'] = $row->value;
# Convert to ISO format
$date = new DateTime($row->validfrom);
$value = $date->format("Y-m-d");
$item['ValidFrom'] = $value;
# Convert to ISO format
$date = new DateTime($row->validto);
$value = $date->format("Y-m-d");
$item['ValidTo'] = $value;
# Push this row onto array
array_push($resultArray,$item);
}
# Return results
return array($resultArray,$numResults);
}
# vim: ts=4
<?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) {
global $db;
$sql = "SELECT ID, Username, Disabled FROM users";
$res = $db->query($sql);
# 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) {
# loop through rows
while ($row = $res->fetchObject()) {
$item = array();
# Begin transaction
DBBegin();
$item['ID'] = $row->id;
$item['Username'] = $row->username;
$item['Disabled'] = $row->disabled;
# Delete user information, if any
$res = DBDo("DELETE FROM @TP@wisp_userdata WHERE UserID = ?",array($params[0]));
# push this row onto array
array_push($resultArray,$item);
# 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']));
# get number of rows
$sql = "SELECT count(*) FROM users";
$res = $db->query($sql);
$numResults = $res->fetchColumn();
# Return result
if ($res !== TRUE) {
return $res;
}
return array($numResults,$resultArray);
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) = @_;
my @valueArray = ();
# Loop through rows
$resultArray = array();
while ($row = $sth->fetchObject()) {
# Replace blanks
while (my ($entireMacro,$section,$item,$default) = ($string =~ /(\%{([a-z]+)\.([a-z0-9\-]+)(?:=([^}]+))?})/i )) {
# Replace macro with ?
$string =~ s/$entireMacro/\?/;
# Build array for this row
$item = array();
# Get value to substitute
my $value = defined($hashref->{$section}->{$item}) ? $hashref->{$section}->{$item} : $default;
$item['ID'] = $row->id;
$item['Username'] = $row->username;
# Add value onto our array
push(@valueArray,$value);
# 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-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
......@@ -102,7 +102,7 @@ class json_response {
foreach ($this->_fields as $field) {
# FIXME - typecast?
$this_results[$field['name']] = $hash[$field['name']];
$this->_results[$field['name']] = $hash[$field['name']];
}
}
......@@ -153,5 +153,37 @@ class json_response {
}
}
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-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
......@@ -63,42 +63,96 @@ function connect_postfix_db()
}
## @fn DBSelect($query)
## @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)
function DBSelect($query,$args = array())
{
# Prepare query
if (!($sth = $db->query($query))) {
return NULL;
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 $sth;
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();
}
## @fn DBSelectNumResults($query)
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)
function DBSelectNumResults($query,$args = array())
{
# Prepare query
if (!($sth = $dbh->query("SELECT COUNT(*) AS num_results $query"))) {
return NULL;
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 = $sth->fetchObject();
if (!defined($row)) {
return NULL;
}
$row = $res->fetchObject();
# Pull number
$num_results = $row->num_results;
......@@ -113,7 +167,7 @@ function DBSelectNumResults($query)
#
# @param query Base query
#
# @param search Search hash ref
# @param search Search array
# @li Filter - Filter based on this...
# [filter] => Array (
# [0] => Array (
......@@ -130,7 +184,7 @@ function DBSelectNumResults($query)
# @li Sort - Sort by this item
# @li SortDirection - Sort in this direction, either ASC or DESC
#
# @param filters Filter hash ref
# @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
......@@ -138,6 +192,8 @@ function DBSelectNumResults($query)
#
# @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 = "";
......@@ -148,32 +204,33 @@ function DBSelectSearch($query,$search,$filters,$sorts) {
# Check if we're searching
if (isset($search)) {
# Check it is a hash
if (gettype($search) != "ARRAY") {
return array(NULL,"Parameter 'search' is not a hashtable");
# 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'])) {
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'");
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) {
foreach ($search['Filter'] as $item) {
$data = $item['data']; # value, type, comparison
$field = $item['field'];
$column = $filters[$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'");
......@@ -212,12 +269,10 @@ function DBSelectSearch($query,$search,$filters,$sorts) {
} elseif ($data['comparison'] == "eq") {
$match = "=";
}
# Convert to ISO format
# FIXME
# $unixtime = str2time($data['value']);
# $date = DateTime->from_epoch( epoch => $unixtime );
# $value = $db->quote($date->ymd());
# Convert to ISO format
$date = new DateTime($data['value']);
$value = $db->quote($date->format('Y-m-d'));
} elseif ($data['type'] == "list") {
# Quote all values
......@@ -279,40 +334,40 @@ function DBSelectSearch($query,$search,$filters,$sorts) {
# Check if we starting at an OFFSET
if (isset($search['Start'])) {
# Check if Start is valid
if ($search['Start'] < 0) {
if (!is_numeric($search['Start']) || $search['Start'] < 0) {
return array(NULL,"Parameter 'search' element 'Start' invalid value '".$search['Start']."'");
}
$sqlOffset = sprintf("OFFSET %i",$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 ($search['Limit'] < 1) {
if (!is_numeric($search['Limit']) || $search['Limit'] < 1) {
return array(NULL,"Parameter 'search' element 'Limit' invalid value '".$search['Limit']."'");
}
$sqlLimit = sprintf("LIMIT %i",$search['Limit']);
$sqlLimit = sprintf("LIMIT %d",$search['Limit']);
}
# Check if we going to be sorting
if (isset($search['Sort'])) {
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']})) {
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']};
$sqlOrderBy = "ORDER BY ".$sorts[$search['Sort']];
# Check for sort ORDER
if (isset($search['SortDirection'])) {
if (isset($search['SortDirection']) && !empty($search['SortDirection'])) {
# Check for valid directions
if (strtolower($search['SortDirection']) == "asc") {
......@@ -329,25 +384,118 @@ function DBSelectSearch($query,$search,$filters,$sorts) {
}
# Select row count, pull out "SELECT .... " as we replace this in the NumResults query
$queryCount = $query; preg_replace("/^\s*SELECT\s.*\sFROM/is","FROM",$queryCount);
$queryCount = $query; $queryCount = preg_replace("/^\s*SELECT\s.*\sFROM/is","FROM",$queryCount);
$numResults = DBSelectNumResults("$queryCount $sqlWhere");
if (!isset($numResults)) {
return NULL;
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 NULL;
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
# Footer
# Copyright (C) 2007-2009, AllWorldIT
#
# 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.
# Print page footer
function printFooter()
{
?>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td id="footer">SMRadius - Copyright &copy; 2007-2009, <a href="http://www.allworldit.com" ?>AllWorldIT</a></td>
</tr>
<tr>
<td>
<div id="footerimages">
<img src="images/valid-xhtml10.png" alt="XHTML 1.0 Valid Logo"/>
<img src="images/valid-css2.png" alt="CSS 2.0 Valid Logo"/>
<img src="images/wcag1AAA.png" alt="Level Tripple-A Conformance"/>
</div>
</td>
</tr>
</table>
</body>
</html>
<?php
## @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
?>
<html>
<head>
<style type="text/css">
#loading {
position:absolute;
left:45%;
top:40%;
padding:2px;
z-index:20001;
height:auto;
}
#loading-msg {
font: normal 10px arial,tahoma,sans-serif;
}
</style>
</head>
<body>
<div id="loading">
<div class="loading-indicator">
Loading: <span id="loading-msg"></span>
</div>
<div>
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Stylesheets...';</script>
<link rel="stylesheet" type="text/css" href="resources/extjs/css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="icons.css" />
<link rel="stylesheet" type="text/css" href="resources/extjs/css/examples.css" />
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Core API...';</script>
<script type="text/javascript" src="js/extjs/ext-base.js"></script>
<script type="text/javascript" src="js/extjs/ext-all.js"></script>
<!--
Our own libraries
-->
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Libraries...';</script>
<script type="text/javascript" src="js/app/util.js"></script>
<script type="text/javascript" src="js/app/sprintf.js"></script>
<script type="text/javascript" src="js/custom/regexes.js"></script>
<script type="text/javascript" src="js/custom/vtypes.js"></script>
<script type="text/javascript" src="js/custom/menu/EditableItem.js"></script>
<script type="text/javascript" src="js/custom/menu/RangeMenu.js"></script>
<script type="text/javascript" src="js/custom/GridFilters.js"></script>
<script type="text/javascript" src="js/custom/GridFilters/Filter.js"></script>
<script type="text/javascript" src="js/custom/GridFilters/StringFilter.js"></script>
<script type="text/javascript" src="js/custom/GridFilters/DateFilter.js"></script>
<script type="text/javascript" src="js/custom/GridFilters/ListFilter.js"></script>
<script type="text/javascript" src="js/custom/GridFilters/NumericFilter.js"></script>
<script type="text/javascript" src="js/custom/GridFilters/BooleanFilter.js"></script>
<script type="text/javascript" src="js/custom/ProgressFormPanel.js"></script>
<script type="text/javascript" src="js/custom/common.js"></script>
<script type="text/javascript" src="js/app/generic.js"></script>
<!--
Main application
-->
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Configuration...';</script>
<script type="text/javascript" src="js/app/config.js"></script>
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Menus...';</script>
<script type="text/javascript" src="js/app/menus.js"></script>
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = 'Windows...';</script>
<script type="text/javascript" src="js/app/windows/WiSPResellers.js"></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/AdminUsers.js"></script>
<script type="text/javascript" src="js/app/windows/AdminGroups.js"></script>
<script type="text/javascript" src="js/app/windows/AdminRealms.js"></script>
<script type="text/javascript">document.getElementById('loading-msg').innerHTML = '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>
<!-- 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',
......
// FIXME
function storeLoadException(requestConfig, storeObj, xmlEr, except) {
printStr = 'An exception occured while trying to load data.<br /><br /><br />';
printStr += '<b>Exception:</b> '+except.toString()+'<br />';
// add http status description
printStr += '<b>Service:</b> '+storeObj.url+'<br />';
printStr += '<b>Status:</b> '+xmlEr.status+' - '+xmlEr.statusText+'<br />';
if (xmlEr.response && xmlEr.response.errors) {
// If this is a return object with errors, display them...
printStr += '<b>Response:</b>';
for (var i = 0; i < xmlEr.response.errors.length; i++) {
printStr += xmlEr.response.errors[i] + '<br />';
}
} else {
// add response text
printStr += '<b>Response:</b><br />'+xmlEr.responseText;
}
Ext.Msg.show({
title: "Exception occured: ",
msg: printStr,
icon: Ext.MessageBox.ERROR
});
}
// Generic jason store
Ext.ux.JsonStore = function(config) {
config = Ext.apply({
url: 'ajax.php',
remoteSort: true
}, config);
var store = new Ext.data.JsonStore(config);
Ext.data.JsonStore.superclass.constructor.call(this, config);
}
Ext.extend(Ext.ux.JsonStore, Ext.data.JsonStore, {
});
// Create a generic window and specify the window, form and submission ajax configuration
Ext.ux.GenericFormWindow = function(windowConfig,formConfig,submitAjaxConfig) {
// Form configuration
formConfig = Ext.apply({
xtype: 'progressformpanel',
id: 'formpanel',
// AJAX connector
url: 'ajax.php',
// Space stuff a bit so it looks better
bodyStyle: 'padding: 5px',
// Default form item is text field
defaultType: 'textfield',
// Button uses formBind = true, this is undocumented
// we may need to define an event to call 'clientvalidation'
monitorValid: true,
// Buttons for the form
buttons: [
{
text: 'Save',
formBind: true,
handler: function() {
var panel = this.ownerCt;
var win = panel.ownerCt;
// Submit panel
panel.submit({
params: submitAjaxConfig,
// Close window on success
success: function() {
win.close();
}
});
}
},{
text: 'Cancel',
handler: function() {
var panel = this.ownerCt;
var win = panel.ownerCt;
win.close();
}
}
]
}, formConfig);
// Add any extra buttons we may have
if (formConfig.extrabuttons) {
// Loop and add
for (i = 0; i < formConfig.extrabuttons.length; i += 1) {
formConfig.buttons.push(formConfig.extrabuttons[i]);
}
}
// Apply our own window configuration
windowConfig = Ext.apply({
layout: 'fit',
items: [
new Ext.ux.ProgressFormPanel(formConfig)
]
}, windowConfig);
Ext.Window.superclass.constructor.call(this, windowConfig);
}
Ext.extend(Ext.ux.GenericFormWindow, Ext.Window, {
// Override functions here
});
// Generic grid window
Ext.ux.GenericGridWindow = function(windowConfig,gridConfig,storeConfig,filtersConfig) {
// Setup data store
storeConfig = Ext.apply({
autoLoad: false,
}, storeConfig);
var store = new Ext.ux.JsonStore(storeConfig);
store.on('loadexception', storeLoadException);
// Setup filters for the grid
var filters = new Ext.grid.GridFilters(filtersConfig);
// Grid configuration
gridConfig = Ext.apply({
xtype: 'gridpanel',
id: 'gridpanel',
plain: true,
height: 300,
// Link store
store: store,
// Plugins
plugins: filters,
// View configuration
viewConfig: {
forceFit: true
},
// Set row selection model
selModel: new Ext.grid.RowSelectionModel({
singleSelect: true
}),
// Inline buttons
buttons: [
{
text:'Close',
handler: function() {
var grid = this.ownerCt;
var win = grid.ownerCt;
win.close();
}
}
],
buttonAlign:'center',
// Bottom bar
bbar: new Ext.PagingToolbar({
pageSize: 25,
store: store,
displayInfo: true,
displayMsg: 'Displaying items {0} - {1} of {2}',
emptyMsg: "No data to display",
plugins: filters
})
}, gridConfig);
// Apply our own window configuration
windowConfig = Ext.apply({
items: [
new Ext.grid.GridPanel(gridConfig)
]
}, windowConfig);
// If we have additional items, push them onto the item list
if (windowConfig.uxItems) {
for (i = 0; i < windowConfig.uxItems.length; i += 1) {
windowConfig.items.push(windowConfig.uxItems[i]);
}
}
Ext.Window.superclass.constructor.call(this, windowConfig);
}
Ext.extend(Ext.ux.GenericGridWindow, Ext.Window, {
// Override functions here
show: function() {
Ext.ux.GenericGridWindow.superclass.show.call(this,arguments);
// Load initial records
this.getComponent('gridpanel').store.load({
params: {
start: 0,
limit: 25
}
});
}
});
// Generic ajax request
uxAjaxRequest = function(parent,config) {
config = Ext.apply({
url: 'ajax.php',
success: function(response,options) {
if (parent) {
parent.getEl().unmask();
}
},
// Failure function
failure: function(response,options) {
Ext.Msg.show({
title: "Exception occured:",
msg: response.responseText,
icon: Ext.MessageBox.ERROR,
fn: function() {
if (parent) {
parent.getEl().unmask();
}
}
});
}
}, config);
Ext.Ajax.request(config);
}
/*
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() {
......@@ -40,11 +59,29 @@ function initViewport() {
// mainWindow
// ]
},
{
id: 'main-statusbar',
xtype: 'statusbar',
xtype: 'panel',
region: 'south',
border: true
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']
})
}
/*
{
......