CVE-2023-0337: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') (CWE-79)
value: Cross-site Scripting (XSS) - Reflected in GitHub repository lirantal/daloradius prior to master-branch.
CWE description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
CVSS v3 base score: 6.1
Published: 2023-01-17T16:15Z
Repository: https://github.com/lirantal/daloradius
Language: PHP
Files changed: acct-date.php, acct-maintenance-cleanup.php, acct-maintenance-delete.php, include/management/contactinfo.php, mng-hs-edit.php, mng-hs-new.php
Commit date: 2023-01-17 14:16:13 +0100
Commit message: Fixed acct and hs management (#341)

* Fixed bugs in some accounting related feature

* Fixed hs management ui components
Diff: diff --git a/acct-date.php b/acct-date.php
index 5c91eaf15..20538e5ea 100644
--- a/acct-date.php
+++ b/acct-date.php
@@ -30,23 +30,23 @@
     include_once("lang/main.php");
     include("library/validation.php");
     include("library/layout.php");
     
     // validate this parameter before including menu
-    $username = (array_key_exists('username', $_GET) && isset($_GET['username']))
-                    ? str_replace("%", "", $_GET['username']) : "";
+    $username = (array_key_exists('username', $_GET) && !empty(str_replace("%", "", trim($_GET['username']))))
+              ? str_replace("%", "", trim($_GET['username'])) : "";
     $username_enc = (!empty($username)) ? htmlspecialchars($username, ENT_QUOTES, 'UTF-8') : "";
 
-    $startdate = (array_key_exists('startdate', $_GET) && isset($_GET['startdate']) &&
-                  preg_match(DATE_REGEX, $_GET['startdate'], $m) !== false &&
+    $startdate = (array_key_exists('startdate', $_GET) && !empty(trim($_GET['startdate'])) &&
+                  preg_match(DATE_REGEX, trim($_GET['startdate']), $m) !== false &&
                   checkdate($m[2], $m[3], $m[1]))
-               ? $_GET['startdate'] : "";
+               ? trim($_GET['startdate']) : "";
 
-    $enddate = (array_key_exists('enddate', $_GET) && isset($_GET['enddate']) &&
-                preg_match(DATE_REGEX, $_GET['enddate'], $m) !== false &&
+    $enddate = (array_key_exists('enddate', $_GET) && !empty(trim($_GET['enddate'])) &&
+                preg_match(DATE_REGEX, trim($_GET['enddate']), $m) !== false &&
                 checkdate($m[2], $m[3], $m[1]))
-             ? $_GET['enddate'] : "";
+             ? trim($_GET['enddate']) : "";
     
     //feed the sidebar variables
     $accounting_date_username = $username_enc;
     $accounting_date_startdate = $startdate;
     $accounting_date_enddate = $enddate;
@@ -56,10 +56,12 @@
     $logQuery = "performed query for user [$username] and start date [$startdate] and end date [$enddate] on page: ";
     $logDebugSQL = "";
 
 
     $extra_js = array(
+        "library/javascript/ajax.js",
+        "library/javascript/ajaxGeneric.js",
         "library/javascript/pages_common.js",
     );
 
     // print HTML prologue
     $title = t('Intro','acctdate.php');
@@ -70,28 +72,28 @@
     include("menu-accounting.php");
 
     $cols = array(
                     "radacctid" => t('all','ID'),
                     "hotspot" => t('all','HotSpot'),
+                    "nasipaddress" => t('all','NASIPAddress'),
                     "username" => t('all','Username'),
                     "framedipaddress" => t('all','IPAddress'),
                     "acctstarttime" => t('all','StartTime'),
                     "acctstoptime" => t('all','StopTime'),
                     "acctsessiontime" => t('all','TotalTime'),
                     "acctinputoctets" => sprintf("%s (%s)", t('all','Upload'), t('all','Bytes')),
                     "acctoutputoctets" => sprintf("%s (%s)", t('all','Download'), t('all','Bytes')),
                     "acctterminatecause" => t('all','Termination'),
-                    "nasipaddress" => t('all','NASIPAddress'),
                  );
     $colspan = count($cols);
     $half_colspan = intval($colspan / 2);
     
-    $orderBy = (array_key_exists('orderBy', $_GET) && isset($_GET['orderBy']) &&
+    $orderBy = (array_key_exists('orderBy', $_GET) && !empty($_GET['orderBy']) &&
                 in_array($_GET['orderBy'], array_keys($cols)))
              ? $_GET['orderBy'] : array_keys($cols)[0];
 
-    $orderType = (array_key_exists('orderType', $_GET) && isset($_GET['orderType']) &&
+    $orderType = (array_key_exists('orderType', $_GET) && !empty($_GET['orderType']) &&
                   preg_match(ORDER_TYPE_REGEX, $_GET['orderType']) !== false)
                ? strtolower($_GET['orderType']) : "asc";
 
 
     echo '<div id="contentnorightbar">';
@@ -167,11 +169,11 @@
         <tr style="background-color: white">
 <?php
             // page numbers are shown only if there is more than one page
             if ($drawNumberLinks) {
                 printf('<td style="text-align: left" colspan="%s">go to page: ', $half_colspan + ($colspan % 2));
-                setupNumbering($numrows, $rowsPerPage, $pageNum, $orderBy, $orderType);
+                setupNumbering($numrows, $rowsPerPage, $pageNum, $orderBy, $orderType, $partial_query_string);
                 echo '</td>';
             }
 ?>
             <td style="text-align: right" colspan="<?= ($drawNumberLinks) ? $half_colspan : $colspan ?>">
                 <input class="button" type="button" value="CSV Export"
@@ -186,55 +188,80 @@
             printTableHead($cols, $orderBy, $orderType, $partial_query_string);
             echo "</tr>";
 ?>
     </thead>
 
-    <tbody>
 <?php
-            $simple_td_format = '<td>%s</td>';
+            echo '<tbody>';
+
+            
             $li_style = 'margin: 7px auto';
+            $trs = array();
 
             while ($row = $res->fetchRow()) {
-                foreach ($row as $i => $value) {
-                    $row[$i] = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
-                }
                 
-                echo "<tr>";
-                printf($simple_td_format, $row[0]);
+                list(
+                        $radacctid, $hotspot, $username, $framedipaddress,
+                        $acctstarttime, $acctstoptime, $acctsessiontime, $acctinputoctets,
+                        $acctoutputoctets, $acctterminatecause, $nasipaddress
+                    ) = $row;
+                
+                $tr = array();
                 
-                $onclick = "javascript:ajaxGeneric('include/management/retHotspotInfo.php','retHotspotGeneralStat','divContainerHotspotInfo'"
-                         . sprintf(",'hotspot=%s');return false;", $row[1]);
+                // radacctid
+                $tr[] = intval($radacctid);
+                
+                // hotspot
+                $hotspot = htmlspecialchars($hotspot, ENT_QUOTES, 'UTF-8');
+                $onclick = "ajaxGeneric('include/management/retHotspotInfo.php','retHotspotGeneralStat','divContainerHotspotInfo'"
+                         . sprintf(",'hotspot=%s');return false;", $hotspot);
                 $tooltip = '<ul style="list-style-type: none">'
                          . sprintf('<li style="%s"><a class="toolTip" href="mng-hs-edit.php?name=%s">%s</a></li>',
-                                   $li_style, urlencode($row[1]), t('Tooltip','HotspotEdit'))
+                                   $li_style, urlencode($hotspot), t('Tooltip','HotspotEdit'))
                          . sprintf('<li style="%s"><a class="toolTip" href="acct-hotspot-compare.php">%s</a></li>',
                                    $li_style, t('all','Compare'))
                          . '</ul>'
                          . '<div style="margin: 15px auto" id="divContainerHotspotInfo">Loading...</div>';
                 
-                printf('<td><a class="tablenovisit" href="#" onclick="%s" ' . "tooltipText='%s'>%s</a></td>",
-                       $onclick, $tooltip, $row[1]);
+                $tr[] = sprintf('<a class="tablenovisit" href="#" onclick="%s" ' . "tooltipText='%s'>%s</a>",
+                                $onclick, $tooltip, $hotspot);
+                
+                // nasipaddress
+                $tr[] = htmlspecialchars($nasipaddress, ENT_QUOTES, 'UTF-8');
                 
+                // username
+                $username = htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
                 $onclick = "javascript:ajaxGeneric('include/management/retUserInfo.php','retBandwidthInfo','divContainerUserInfo',"
-                         . sprintf("'username=%s');return false;", $row[2]);
-                $tooltip = sprintf('<a class="toolTip" href="mng-edit.php?username=%s">%s</a>', $row[2], t('Tooltip','UserEdit'))
+                         . sprintf("'username=%s');return false;", $username);
+                $tooltip = sprintf('<a class="toolTip" href="mng-edit.php?username=%s">%s</a>', urlencode($username), t('Tooltip','UserEdit'))
                          . '<div style="margin: 15px auto" id="divContainerUserInfo">Loading...</div>';
-                printf('<td><a class="tablenovisit" href="#" onclick="%s" ' . "tooltipText='%s'>%s</a></td>",
-                       $onclick, $tooltip, $row[2]);
+                $tr[] = sprintf('<a class="tablenovisit" href="#" onclick="%s" ' . "tooltipText='%s'>%s</a>",
+                                $onclick, $tooltip, $username);
+                
+                // other values
+                $tr[] = htmlspecialchars($framedipaddress, ENT_QUOTES, 'UTF-8');
+                $tr[] = htmlspecialchars($acctstarttime, ENT_QUOTES, 'UTF-8');
+                $tr[] = htmlspecialchars($acctstoptime, ENT_QUOTES, 'UTF-8');
+                $tr[] = time2str($acctsessiontime);
+                $tr[] = toxbyte($acctinputoctets);
+                $tr[] = toxbyte($acctoutputoctets);
+                $tr[] = htmlspecialchars($acctterminatecause, ENT_QUOTES, 'UTF-8');
+                
+                $trs[] = $tr;
+            }
+
+            // draw tr(s)
+            $simple_td_format = '<td>%s</td>' . "\n";
 
-                printf($simple_td_format, $row[3]);
-                printf($simple_td_format, $row[4]);
-                printf($simple_td_format, $row[5]);
+            foreach ($trs as $tr) {
+                echo '<tr>';
                 
-                printf($simple_td_format, time2str($row[6]));
-                printf($simple_td_format, toxbyte($row[7]));
-                printf($simple_td_format, toxbyte($row[8]));
-                printf($simple_td_format, $row[9]);
-                printf($simple_td_format, $row[10]);
-            
-                echo "</tr>";
-            
+                foreach ($tr as $td) {
+                    printf($simple_td_format, $td);
+                }
+                
+                echo '</tr>';
             }
 
             echo '</tbody>';
 
             // tfoot
diff --git a/acct-maintenance-cleanup.php b/acct-maintenance-cleanup.php
index 67cd302f3..a00add9a9 100644
--- a/acct-maintenance-cleanup.php
+++ b/acct-maintenance-cleanup.php
@@ -20,86 +20,130 @@
  *             Filippo Lauria <filippo.lauria@iit.cnr.it>
  *
  *********************************************************************************************************
  */
 
-    include ("library/checklogin.php");
+    include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
+    include_once('library/config_read.php');
+    
+    // init logging variables
+    $logAction = "";
+    $logDebugSQL = "";
+    $log = "visited page: ";
 
-    isset($_REQUEST['username']) ? $username = trim($_REQUEST['username']) : $username = '';
-    isset($_REQUEST['enddate']) ? $enddate = trim($_REQUEST['enddate']) : $enddate = "";
-
-    $logAction = '';
-    $logDebugSQL = '';
-
-    if (isset($_POST['submit'])) {
-
-        if ($username != '') {
-
-            include 'library/opendb.php';
-
-            $sql = 'SELECT count(*) FROM ' . $configValues['CONFIG_DB_TBL_RADACCT'] .
-                   ' WHERE username = "' . $username . '" AND acctstoptime is NULL;';
-
-            $res = $dbSocket->query($sql);
-
-            $logDebugSQL .= $sql . "\n";
-
-            $row = $res->fetchRow();
-
-            if($row[0] > 0) {
+    include_once("lang/main.php");
+    include("library/validation.php");
+    include("library/layout.php");
 
-                $sql = 'UPDATE ' . $configValues['CONFIG_DB_TBL_RADACCT'] .
-                       ' SET acctstoptime = NOW(), acctterminatecause = "Admin-Reset"'.
-                       ' WHERE username = "' . $username . '" AND acctstoptime is NULL;'; 
 
+    include('library/opendb.php');
+    
+    // valid min/max dates
+    $sql = sprintf("SELECT DATE(MIN(acctstarttime)), DATE(MAX(acctstarttime)) FROM %s", $configValues['CONFIG_DB_TBL_RADACCT']);
+    $res = $dbSocket->query($sql);
+    $logDebugSQL .= "$sql;\n";
+    
+    list($mindate, $maxdate) = $res->fetchrow();
+    
+    // valid usernames
+    $sql = sprintf("SELECT DISTINCT(username) FROM %s ORDER BY username ASC", $configValues['CONFIG_DB_TBL_RADACCT']);
+    $res = $dbSocket->query($sql);
+    $logDebugSQL .= "$sql;\n";
+    
+    $valid_usernames = array();
+    while ($row = $res->fetchrow()) {
+        $valid_usernames[] = $row[0];
+    }
+    
+    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
+        if (array_key_exists('csrf_token', $_POST) && isset($_POST['csrf_token']) && dalo_check_csrf_token($_POST['csrf_token'])) {
+            
+            $username = (array_key_exists('username', $_POST) && !empty(trim($_POST['username'])) &&
+                         in_array(trim($_POST['username']), $valid_usernames))
+                      ? trim($_POST['username']) : "";
+            
+            $enddate = (array_key_exists('enddate', $_POST) && isset($_POST['enddate']) &&
+                        preg_match(DATE_REGEX, $_POST['enddate'], $m) !== false &&
+                        checkdate($m[2], $m[3], $m[1]))
+                     ? $_POST['enddate'] : "";
+                     
+            if (!empty($username)) {
+                
+                $username_enc = htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
+                
+                $sql = sprintf("SELECT COUNT(radacctid) FROM %s WHERE username='%s' AND acctstoptime IS NULL",
+                               $configValues['CONFIG_DB_TBL_RADACCT'], $dbSocket->escapeSimple($username));
                 $res = $dbSocket->query($sql);
+                $logDebugSQL .= "$sql;\n";
                 
-                $logDebugSQL .= $sql . "\n";
-
-                $successMsg = "Cleaned up stale sessions for username: <b> $username </b>";
-                $logAction .= "Successfully cleaned up stale sessions for username [$username] on page: ";
-            }
-            else {
-
-                $failureMsg = "There are no stale sessions for user [$username]";
-                $logAction .= "Failed performing close stale sessions on user [$username] because there are no stale sessions for that user on page: ";
+                $numrows = intval($res->fetchrow()[0]);
+                
+                if ($numrows > 0) {
+                    $sql = sprintf("UPDATE %s SET acctstoptime=NOW(), acctterminatecause='Admin-Reset'
+                                     WHERE username='%s' AND acctstoptime IS NULL",
+                                   $configValues['CONFIG_DB_TBL_RADACCT'],
+                                   $dbSocket->escapeSimple($username)); 
+                    $res = $dbSocket->query($sql);
+                    $logDebugSQL .= "$sql;\n";
+
+                    if (!DB::isError($res)) {
+                        $successMsg = "Cleaned up stale sessions for user: $username_enc";
+                        $logAction .= "Successfully cleaned up stale sessions for username [$username] on page: ";
+                    } else {
+                        $failureMsg = "Cannot clean up stale sessions for user: $username_enc";
+                        $logAction .= "$failureMsg page: ";
+                    }
+
+                } else {
+                    // nothing to delete
+                    $failureMsg = "There are no stale sessions for user [$username_enc]";
+                    $logAction .= "Cannot clean up stale sessions for user $username [no stale sessions for this user] on page: ";
+                }
+                
+            } else if (!empty($enddate)) {
+                if ($enddate >= $mindate && $enddate <= $maxdate) {
+                
+                    // delete all stale sessions in the database that occur until $enddate
+                    $sql = sprintf("DELETE FROM %s
+                                          WHERE acctstarttime < '%s'
+                                            AND (acctstoptime = '0000-00-00 00:00:00' OR acctstoptime IS NULL)",
+                                   $configValues['CONFIG_DB_TBL_RADACCT'], $enddate);
+                    $res = $dbSocket->query($sql);
+                    $logDebugSQL .= "$sql\n";
+
+                    if (!DB::isError($res)) {
+                        $successMsg = "Cleaned up stale sessions until date: $enddate";
+                        $logAction .= "Successfully cleaned up stale sessions until date [$enddate] on page: ";
+                    } else {
+                        $failureMsg = "Cannot clean up stale sessions until date: $enddate";
+                        $logAction .= "$failureMsg page: ";
+                    }
+
+                    
+                } else {
+                    // invalid
+                    $failureMsg = "Cannot clean up stale sessions: $enddate is invalid";
+                    $logAction .= "$failureMsg page: ";
+                }
+            } else {
+                // invalid
+                $failureMsg = "Cannot clean up stale sessions: provided empty/invalid username or ending date";
+                $logAction .= "$failureMsg page: ";
             }
-
-            include 'library/closedb.php';
-        }
-        else if ($enddate != '') {
-
-            include 'library/opendb.php';
-
-            // delete all stale sessions in the database that occur until $enddate
-            $sql = "DELETE FROM ".$configValues['CONFIG_DB_TBL_RADACCT'].
-                    " WHERE AcctStartTime<'".$dbSocket->escapeSimple($enddate)."'".
-                    " AND (AcctStopTime='0000-00-00 00:00:00' OR AcctStopTime IS NULL)";
-            $res = $dbSocket->query($sql);
-            $logDebugSQL .= $sql . "\n";
-
-            $successMsg = "Cleaned up stale sessions until date: <b> $enddate </b>";
-            $logAction .= "Successfully cleaned up stale sessions until date [$enddate] on page: ";
-
-            include 'library/closedb.php';
-
-        }
-        else {
-            $failureMsg = "No username or ending date was entered, please specify a username or ending date for cleaning up stale sessions from the database";
-            $logAction .= "Failed cleaning up stale sessions due to lack of username or ending date on page: ";
+            
+        } else {
+            // csrf
+            $failureMsg = "CSRF token error";
+            $logAction .= "$failureMsg on page: ";
         }
     }
 
-    include_once('library/config_read.php');
-    $log = "visited page: ";
-    
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
+    include('library/closedb.php');
+
 
     // print HTML prologue
     $extra_css = array(
         // css tabs stuff
         "css/tabs.css"
@@ -114,94 +158,102 @@
     $help = t('helpPage','acctmaintenancecleanup');
     
     print_html_prologue($title, $langCode, $extra_css, $extra_js);
 
     include("menu-accounting-maintenance.php");
+    
     echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
     
     include_once('include/management/actionMessages.php');
     
     // set navbar stuff
-    $navbuttons = array(
-                          'CleanupRecordsByUsername-tab' => t('title','CleanupRecordsByUsername'),
-                          'CleanupRecordsByDate-tab' => t('title','CleanupRecordsByDate'),
-                       );
-
-    print_tab_navbuttons($navbuttons);
-?>
-
-
-        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
-
-            
+    $navkeys = array( 'CleanupRecordsByUsername', 'CleanupRecordsByDate', );
 
-                <div class="tabcontent" id="CleanupRecordsByUsername-tab" style="display: block">
-
-                    <fieldset>
-
-                        <h302> <?php echo t('title','CleanupRecordsByUsername'); ?> </h302>
-                        <br/>
-
-                        <label for='username' class='form'><?php echo t('all','Username')?></label>
-                        <input name="username" type="text" id="usernameEdit" autocomplete="off"
-                        tooltipText='<?php echo t('Tooltip','Username'); ?> <br/>'
-                        value="<?php if (isset($username)) echo $username; ?>" tabindex=100>
+    // print navbar controls
+    print_tab_header($navkeys);
+    
+    $options = $valid_usernames;
+    array_unshift($options , '');
+
+    $input_descriptors0 = array();
+    $input_descriptors0[] = array(
+                                    'name' => 'username',
+                                    'type' => 'select',
+                                    'caption' => t('all','Username'),
+                                    'options' => $options,
+                                    'selected_value' => $username
+                                 );
+    
+    $fieldset0_descriptor = array(
+                                    "title" => t('title','CleanupRecordsByUsername'),
+                                    "disabled" => (count($valid_usernames) == 0)
+                                 );           
+    
+    $input_descriptors1 = array();
+    $input_descriptors1[] = array(
+                                    'name' => 'enddate',
+                                    'caption' => t('all','CleanupSessions'),
+                                    'type' => 'date',
+                                    'value' => $enddate,
+                                    'min' => $mindate,
+                                    'max' => $maxdate,
+                                 );
+
+    $fieldset1_descriptor = array(
+                                    "title" => t('title','CleanupRecordsByDate'),
+                                    "disabled" => (count($valid_usernames) == 0)
+                                 );
+
+    open_form();
+    
+    // open tab 0
+    open_tab($navkeys, 0, true);
+    
+    open_fieldset($fieldset0_descriptor);
 
-<?php
-    include_once("include/management/autocomplete.php");
-
-    if ($autoComplete) {
-        echo "<script type=\"text/javascript\">
-                /** Making usernameEdit interactive **/
-                autoComEdit = new DHTMLSuite.autoComplete();
-                autoComEdit.add('usernameEdit','include/management/dynamicAutocomplete.php','_small','getAjaxAutocompleteUsernames');
-                </script>";
+    foreach ($input_descriptors0 as $input_descriptor) {
+        print_form_component($input_descriptor);
     }
-?>
-                        <br/><br/>
-                        <hr><br/>
-
-                        <input type='submit' name='submit' value='<?php echo t('buttons','apply') ?>' class='button' />
-
-                    </fieldset>
-
-                </div>
-
-                <div class="tabcontent" id="CleanupRecordsByDate-tab">
-
-                    <fieldset>
-                        <h302> <?php echo t('title','CleanupRecordsByDate') ?> </h302>
-                        <br/>
-
-                        <label for='enddate' class='form'><?php echo t('all','CleanupSessions')?></label>
-                        <input name='enddate' type='text' id='enddate' value='<?php echo $enddate ?>' tabindex=100 />
-                        <img src="library/js_date/calendar.gif" onclick=
-                        "showChooser(this, 'enddate', 'chooserSpan', 1950, <?php echo date('Y', time());?>, 'Y-m-d H:i:s', true);" >
-
-                        <br/><br/>
-                        <hr><br/>
-                        <input type="submit" name="submit" value="<?php echo t('buttons','apply') ?>" tabindex=1000 class='button' />
-                    </fieldset>
-
-                    <div id="chooserSpan" class="dateChooser select-free"
-                        style="display: none; visibility: hidden; width: 160px;">
-                    </div>
+    
+    close_fieldset();
+    
+    close_tab($navkeys, 0);
 
-                </div>
+    // open tab 1
+    open_tab($navkeys, 1);
+    
+    open_fieldset($fieldset1_descriptor);
 
+    foreach ($input_descriptors1 as $input_descriptor) {
+        print_form_component($input_descriptor);
+    }
+    
+    close_fieldset();
+    
+    close_tab($navkeys, 1);
+    
+    $input_descriptors2 = array();
+    $input_descriptors2[] = array(
+                                    "name" => "csrf_token",
+                                    "type" => "hidden",
+                                    "value" => dalo_csrf_token(),
+                                 );
+    
+    $input_descriptors2[] = array(
+                                    "type" => "submit",
+                                    "name" => "submit",
+                                    "value" => t('buttons','apply')
+                                  );
+
+    foreach ($input_descriptors2 as $input_descriptor) {
+        print_form_component($input_descriptor);
+    }
 
-    </form>
+    close_form();
+    
+    print_back_to_previous_page();
 
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
     include('include/config/logging.php');
-    include('page-footer.php');
-?>
-        </div><!-- #footer -->
-    </div>
-</div>
+    print_footer_and_html_epilogue();
 
-</body>
-</html>
+?>
diff --git a/acct-maintenance-delete.php b/acct-maintenance-delete.php
index 740979f57..b3e4958c8 100644
--- a/acct-maintenance-delete.php
+++ b/acct-maintenance-delete.php
@@ -18,126 +18,193 @@
  * Authors:    Liran Tal <liran@enginx.com>
  *             Filippo Lauria <filippo.lauria@iit.cnr.it>
  *
  *********************************************************************************************************
  */
-
+ 
     include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
- 
-    isset($_REQUEST['enddate']) ? $enddate = $_REQUEST['enddate'] : $enddate = "";
-    isset($_REQUEST['startdate']) ? $startdate = $_REQUEST['startdate'] : $startdate = "";
-    isset($_REQUEST['username']) ? $username = $_REQUEST['username'] : $username = "";
-
-    $logAction =  "";
+    include_once('library/config_read.php');
+    
+    // init logging variables
+    $logAction = "";
     $logDebugSQL = "";
+    $log = "visited page: ";
 
-    if (isset($_POST['submit'])) {
-
-        if ( (trim($startdate) != "") || (trim($enddate) != "") || (trim($username) != "") ) {
+    include_once("lang/main.php");
+    include("library/validation.php");
+    include("library/layout.php");
+    
+    
+    include('library/opendb.php');
+    
+    // valid min/max dates
+    $sql = sprintf("SELECT DATE(MIN(acctstarttime)), DATE(MAX(acctstarttime)) FROM %s", $configValues['CONFIG_DB_TBL_RADACCT']);
+    $res = $dbSocket->query($sql);
+    $logDebugSQL .= "$sql;\n";
+    
+    list($mindate, $maxdate) = $res->fetchrow();
+    
+    // valid usernames
+    $sql = sprintf("SELECT DISTINCT(username) FROM %s ORDER BY username ASC", $configValues['CONFIG_DB_TBL_RADACCT']);
+    $res = $dbSocket->query($sql);
+    $logDebugSQL .= "$sql;\n";
+    
+    $valid_usernames = array();
+    while ($row = $res->fetchrow()) {
+        $valid_usernames[] = $row[0];
+    }
+    
+    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
+        if (array_key_exists('csrf_token', $_POST) && isset($_POST['csrf_token']) && dalo_check_csrf_token($_POST['csrf_token'])) {
+            $required_fields = array();
+            $sql_WHERE = array();
             
-            include 'library/opendb.php';
-
-            $deleteUsername = "";
-            if (trim($username) != "")
-                $deleteUsername = " AND Username='$username'";
-
-            $deleteEnddate = "";
-            if (trim($enddate) != "")
-                $deleteEnddate = " AND AcctStartTime<'".$dbSocket->escapeSimple($enddate)."'";
-
-            $deleteStartdate = "";
-            if (trim($startdate) != "")
-                $deleteStartdate = " AND AcctStartTime>'".$dbSocket->escapeSimple($startdate)."'";
-
-
-            $sql = "DELETE FROM ".$configValues['CONFIG_DB_TBL_RADACCT'].
-                " WHERE 1=1".
-                " $deleteStartdate".
-                " $deleteEnddate".
-                " $deleteUsername ";
-            $res = $dbSocket->query($sql);
-            $logDebugSQL .= $sql . "\n";
-
-            $successMsg = "Deleted records between <b>$startdate</b> to <b>$enddate</b> for user <b>$username</b>";
-            $logAction .= "Successfully deleted records between [$startdate] and [$enddate] for user [$username] on page: ";
-
-            include 'library/closedb.php';
-
-        }  else { 
-            $failureMsg = "no username, ending date or starting date was provided, please at least one of those";
-            $logAction .= "Failed deleting records from database, missing fields on page: ";
+            $username = (array_key_exists('username', $_POST) && !empty(trim($_POST['username'])) &&
+                         in_array(trim($_POST['username']), $valid_usernames))
+                      ? trim($_POST['username']) : "";
+            if (empty($username)) {
+                $required_fields['username'] = t('all','Username');
+            } else {
+                $username_enc = htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
+                $sql_WHERE[] = sprintf("username='%s'", $dbSocket->escapeSimple($username));
+            }
+            
+            $startdate = (array_key_exists('startdate', $_POST) && isset($_POST['startdate']) &&
+                          preg_match(DATE_REGEX, $_POST['startdate'], $m) !== false &&
+                          checkdate($m[2], $m[3], $m[1]))
+                       ? $_POST['startdate'] : "";
+            if (empty($startdate)) {
+                $required_fields['startdate'] = t('all','StartingDate');
+            } else {
+                $sql_WHERE[] = sprintf("AcctStartTime > '%s'", $startdate);
+            }
+            
+            $enddate = (array_key_exists('enddate', $_POST) && isset($_POST['enddate']) &&
+                        preg_match(DATE_REGEX, $_POST['enddate'], $m) !== false &&
+                        checkdate($m[2], $m[3], $m[1]))
+                     ? $_POST['enddate'] : "";
+            if (empty($enddate)) {
+                $required_fields['enddate'] = t('all','EndingDate');
+            } else {
+                $sql_WHERE[] = sprintf("AcctStartTime < '%s'", $enddate);
+            }
+            
+            // further checks
+            if (!empty($startdate) && !empty($enddate) && $startdate >= $mindate && $enddate <= $maxdate && $startdate > $enddate) {
+                $required_fields['startdate'] = t('all','StartingDate');
+                $required_fields['enddate'] = t('all','EndingDate');
+            }
+            
+            if (count($required_fields) > 0) {
+                // required/invalid
+                $failureMsg = sprintf("Empty or invalid required field(s) [%s]", implode(", ", array_values($required_fields)));
+                $logAction .= "$failureMsg on page: ";
+            } else {
+                
+                $sql = sprintf("DELETE FROM %s WHERE %s", $configValues['CONFIG_DB_TBL_RADACCT'],
+                                                          implode(" AND ", $sql_WHERE));
+                $res = $dbSocket->query($sql);
+                $logDebugSQL .= "$sql;\n";
+                
+                if (!DB::isError($res)) {
+                    $successMsg = sprintf("Deleted accounting records for user %s [period: %s - %s]",
+                                          $username_enc, $startdate, $enddate);
+                    $logAction .= "$successMsg on page: ";
+                } else {
+                    $failureMsg = sprintf("Failed to deleted accounting records for user %s [period: %s - %s]",
+                                          $username_enc, $startdate, $enddate);
+                    $logAction .= "$failureMsg page: ";
+                }
+            }
+            
+        } else {
+            // csrf
+            $failureMsg = "CSRF token error";
+            $logAction .= "$failureMsg on page: ";
         }
-
     }
 
-
-    include_once('library/config_read.php');
-    $log = "visited page: ";
-
-    include_once("lang/main.php");
+    include('library/closedb.php');
     
-    include("library/layout.php");
 
     // print HTML prologue
     $title = t('Intro','acctmaintenancedelete.php');
     $help = t('helpPage','acctmaintenancedelete');
     
     print_html_prologue($title, $langCode);
 
     include("menu-accounting-maintenance.php");
+    
     echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
     
     include_once('include/management/actionMessages.php');
-?>
-
-        
-<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
-    <fieldset>
-
-        <h302> <?php echo t('title','DeleteRecords') ?> </h302>
-        <br/>
-
-        <label for='username' class='form'><?php echo t('all','Username')?></label>
-        <input name='username' type='text' id='username' value='<?php echo $username ?>' tabindex=100 />
-        <br />
-
-        <label for='startdate' class='form'><?php echo t('all','StartingDate')?></label>
-        <input name='startdate' type='text' id='startdate' value='<?php echo $startdate ?>' tabindex=100 />
-        <img src="library/js_date/calendar.gif" onclick=
-        "showChooser(this, 'startdate', 'chooserSpan', 1950, <?php echo date('Y', time());?>, 'Y-m-d H:i:s', true);" >
-        <br />
-
-        <label for='enddate' class='form'><?php echo t('all','EndingDate')?></label>
-        <input name='enddate' type='text' id='enddate' value='<?php echo $enddate ?>' tabindex=100 />
-        <img src="library/js_date/calendar.gif" onclick=
-        "showChooser(this, 'enddate', 'chooserSpan', 1950, <?php echo date('Y', time());?>, 'Y-m-d H:i:s', true);" >
-        <br />
-
-        <br/><br/>
-        <hr><br/>
-        <input type="submit" name="submit" value="<?php echo t('buttons','apply') ?>" tabindex=1000 class='button' />
-
-    </fieldset>
+    
+    $options = $valid_usernames;
+    array_unshift($options , '');
+    
+    $input_descriptors0 = array();
+
+    $input_descriptors0[] = array(
+                                    'name' => 'username',
+                                    'type' => 'select',
+                                    'caption' => t('all','Username'),
+                                    'options' => $options,
+                                    'selected_value' => $username
+                                 );
+
+    $input_descriptors0[] = array(
+                                    'name' => 'startdate',
+                                    'caption' => t('all','StartingDate'),
+                                    'type' => 'date',
+                                    'value' => $startdate,
+                                    'min' => $mindate,
+                                    'max' => $maxdate,
+                                 );
+                                 
+    $input_descriptors0[] = array(
+                                    'name' => 'enddate',
+                                    'caption' => t('all','EndingDate'),
+                                    'type' => 'date',
+                                    'value' => $enddate,
+                                    'min' => $mindate,
+                                    'max' => $maxdate,
+                                 );
+                                 
+    $input_descriptors0[] = array(
+                                    "name" => "csrf_token",
+                                    "type" => "hidden",
+                                    "value" => dalo_csrf_token(),
+                                 );
+    
+    $input_descriptors0[] = array(
+                                    "type" => "submit",
+                                    "name" => "submit",
+                                    "value" => t('buttons','apply')
+                                  );
+    
+    $fieldset0_descriptor = array(
+                                    "title" => t('title','DeleteRecords'),
+                                    "disabled" => (count($valid_usernames) == 0)
+                                 );
+                                 
+    open_form();
+    
+    open_fieldset($fieldset0_descriptor);
 
-    <div id="chooserSpan" class="dateChooser select-free" 
-        style="display: none; visibility: hidden; width: 160px;">
-    </div>
+    foreach ($input_descriptors0 as $input_descriptor) {
+        print_form_component($input_descriptor);
+    }
+    
+    close_fieldset();
+    
+    close_form();
 
-</form>
+    print_back_to_previous_page();
 
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
     include('include/config/logging.php');
-    include('page-footer.php');
+    print_footer_and_html_epilogue();
+    
 ?>
-        </div><!-- #footer -->
-    </div>
-</div>
-
-</body>
-</html>
diff --git a/include/management/contactinfo.php b/include/management/contactinfo.php
index 91740e16f..5e652eaa8 100644
--- a/include/management/contactinfo.php
+++ b/include/management/contactinfo.php
@@ -25,83 +25,70 @@
 if (strpos($_SERVER['PHP_SELF'], '/include/management/contactinfo.php') !== false) {
     header("Location: ../../index.php");
     exit;
 }
 
-$input_descriptors1 = array();
-$input_descriptors1[] = array( "name" => "ownername", "caption" => t('ContactInfo','OwnerName'),
-                               "type" => "text", "value" => ((isset($owner)) ? $owner : ""), );
-$input_descriptors1[] = array( "name" => "emailowner", "caption" => t('ContactInfo','OwnerEmail'),
-                               "type" => "text", "value" => ((isset($email_owner)) ? $email_owner : "") , );
-$input_descriptors1[] = array( "name" => "managername", "caption" => t('ContactInfo','ManagerName'),
-                               "type" => "text", "value" => ((isset($manager)) ? $manager : "") , );
-$input_descriptors1[] = array( "name" => "emailmanager", "caption" => t('ContactInfo','ManagerEmail'),
-                               "type" => "text", "value" => ((isset($email_manager)) ? $email_manager : "") , );
-$input_descriptors1[] = array( "name" => "company", "caption" => t('ContactInfo','Company'),
-                               "type" => "text", "value" => ((isset($company)) ? $company : "") , );
-$input_descriptors1[] = array( "name" => "address", "caption" => t('ContactInfo','Address'),
-                               "type" => "textarea", "content" => ((isset($address)) ? $address : ""), );                               
-$input_descriptors1[] = array( "name" => "phone1", "caption" => t('ContactInfo','Phone1'),
-                               "type" => "text", "value" => ((isset($phone1)) ? $phone1 : "") , );
-$input_descriptors1[] = array( "name" => "phone2", "caption" => t('ContactInfo','Phone2'),
-                               "type" => "text", "value" => ((isset($phone2)) ? $phone2 : "") , );
-$input_descriptors1[] = array( "name" => "hotspot_type", "caption" => t('ContactInfo','HotspotType'),
-                               "type" => "text", "value" => ((isset($hotspot_type)) ? $hotspot_type : "") , );
-$input_descriptors1[] = array( "name" => "companywebsite", "caption" => t('ContactInfo','CompanyWebsite'),
-                               "type" => "text", "value" => ((isset($companywebsite)) ? $companywebsite : "") , );
-$input_descriptors1[] = array( "name" => "companyemail", "caption" => t('ContactInfo','CompanyEmail'),
-                               "type" => "text", "value" => ((isset($companyemail)) ? $companyemail : "") , );
-$input_descriptors1[] = array( "name" => "companyphone", "caption" => t('ContactInfo','CompanyPhone'),
-                               "type" => "text", "value" => ((isset($companyphone)) ? $companyphone : "") , );
-$input_descriptors1[] = array( "name" => "companycontact", "caption" => t('ContactInfo','CompanyContact'),
-                               "type" => "text", "value" => ((isset($companycontact)) ? $companycontact : "") , );
+$_input_descriptors1 = array();
+$_input_descriptors1[] = array( "name" => "ownername", "caption" => t('ContactInfo','OwnerName'),
+                                "type" => "text", "value" => ((isset($owner)) ? $owner : ""), );
+$_input_descriptors1[] = array( "name" => "emailowner", "caption" => t('ContactInfo','OwnerEmail'),
+                                "type" => "text", "value" => ((isset($email_owner)) ? $email_owner : "") , );
+$_input_descriptors1[] = array( "name" => "managername", "caption" => t('ContactInfo','ManagerName'),
+                                "type" => "text", "value" => ((isset($manager)) ? $manager : "") , );
+$_input_descriptors1[] = array( "name" => "emailmanager", "caption" => t('ContactInfo','ManagerEmail'),
+                                "type" => "text", "value" => ((isset($email_manager)) ? $email_manager : "") , );
+$_input_descriptors1[] = array( "name" => "company", "caption" => t('ContactInfo','Company'),
+                                "type" => "text", "value" => ((isset($company)) ? $company : "") , );
+$_input_descriptors1[] = array( "name" => "address", "caption" => t('ContactInfo','Address'),
+                                "type" => "textarea", "content" => ((isset($address)) ? $address : ""), );                               
+$_input_descriptors1[] = array( "name" => "phone1", "caption" => t('ContactInfo','Phone1'),
+                                "type" => "text", "value" => ((isset($phone1)) ? $phone1 : "") , );
+$_input_descriptors1[] = array( "name" => "phone2", "caption" => t('ContactInfo','Phone2'),
+                                "type" => "text", "value" => ((isset($phone2)) ? $phone2 : "") , );
+$_input_descriptors1[] = array( "name" => "hotspot_type", "caption" => t('ContactInfo','HotspotType'),
+                                "type" => "text", "value" => ((isset($hotspot_type)) ? $hotspot_type : "") , );
+$_input_descriptors1[] = array( "name" => "companywebsite", "caption" => t('ContactInfo','CompanyWebsite'),
+                                "type" => "text", "value" => ((isset($companywebsite)) ? $companywebsite : "") , );
+$_input_descriptors1[] = array( "name" => "companyemail", "caption" => t('ContactInfo','CompanyEmail'),
+                                "type" => "text", "value" => ((isset($companyemail)) ? $companyemail : "") , );
+$_input_descriptors1[] = array( "name" => "companyphone", "caption" => t('ContactInfo','CompanyPhone'),
+                                "type" => "text", "value" => ((isset($companyphone)) ? $companyphone : "") , );
+$_input_descriptors1[] = array( "name" => "companycontact", "caption" => t('ContactInfo','CompanyContact'),
+                                "type" => "text", "value" => ((isset($companycontact)) ? $companycontact : "") , );
 
-$input_descriptors2 = array();
-$input_descriptors2[] = array( 'name' => 'creationdate', 'caption' => t('all','CreationDate'), 'type' => 'text',
-                               'disabled' => true, 'value' => ((isset($creationdate)) ? $creationdate : '') );
-$input_descriptors2[] = array( 'name' => 'creationby', 'caption' => t('all','CreationBy'), 'type' => 'text',
-                               'disabled' => true, 'value' => ((isset($creationby)) ? $creationby : '') );
-$input_descriptors2[] = array( 'name' => 'updatedate', 'caption' => t('all','UpdateDate'), 'type' => 'text',
-                               'disabled' => true, 'value' => ((isset($updatedate)) ? $updatedate : '') );
-$input_descriptors2[] = array( 'name' => 'updateby', 'caption' => t('all','UpdateBy'), 'type' => 'text',
-                               'disabled' => true, 'value' => ((isset($updateby)) ? $updateby : '') );
 
-$button_descriptor = array(
-                            "type" => "submit",
-                            "name" => "submit",
-                            "value" => t('buttons','apply')
-                          );
+$_fieldset1_descriptor = array(
+                                "title" => t('title','ContactInfo'),
+                              );
+                          
+open_fieldset($_fieldset1_descriptor);
 
-?>
+foreach ($_input_descriptors1 as $input_descriptor) {
+    print_form_component($input_descriptor);
+}
 
-<fieldset>
-    <h302>Contact Info</h302>
-    <h301>Contact Info</h301>
+close_fieldset();
 
-    <ul>
-<?php
 
-    foreach ($input_descriptors1 as $input_descriptor) {
-        print_form_component($input_descriptor);
-    }
+$_input_descriptors2 = array();
+$_input_descriptors2[] = array( 'name' => 'creationdate', 'caption' => t('all','CreationDate'), 'type' => 'text',
+                                'disabled' => true, 'value' => ((isset($creationdate)) ? $creationdate : '') );
+$_input_descriptors2[] = array( 'name' => 'creationby', 'caption' => t('all','CreationBy'), 'type' => 'text',
+                                'disabled' => true, 'value' => ((isset($creationby)) ? $creationby : '') );
+$_input_descriptors2[] = array( 'name' => 'updatedate', 'caption' => t('all','UpdateDate'), 'type' => 'text',
+                                'disabled' => true, 'value' => ((isset($updatedate)) ? $updatedate : '') );
+$_input_descriptors2[] = array( 'name' => 'updateby', 'caption' => t('all','UpdateBy'), 'type' => 'text',
+                                'disabled' => true, 'value' => ((isset($updateby)) ? $updateby : '') );
 
-?>
-    </ul>
-</fieldset>
+$_fieldset2_descriptor = array(
+                                "title" => "Other",
+                              );
 
-<fieldset>
-    <h302>Other</h302>
-    <h301>Other</h301>
-    <ul>
-<?php
+open_fieldset($_fieldset2_descriptor);
 
-    foreach ($input_descriptors2 as $input_descriptor) {
-        print_form_component($input_descriptor);
-    }
+foreach ($_input_descriptors2 as $input_descriptor) {
+    print_form_component($input_descriptor);
+}
 
-?>
-    </ul>
-</fieldset>
+close_fieldset();
 
-<?php
-    print_form_component($button_descriptor);
 ?>
diff --git a/mng-hs-edit.php b/mng-hs-edit.php
index 383b75451..27a75d83a 100644
--- a/mng-hs-edit.php
+++ b/mng-hs-edit.php
@@ -39,11 +39,11 @@
 
     include('library/opendb.php');
 
     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         $name = (array_key_exists('name', $_POST) && !empty(str_replace("%", "", trim($_POST['name']))))
-              ? str_replace("%", "", trim($_POST['name']))) : "";
+              ? str_replace("%", "", trim($_POST['name'])) : "";
     } else {
         $name = (array_key_exists('name', $_REQUEST) && !empty(str_replace("%", "", trim($_REQUEST['name']))))
               ? str_replace("%", "", trim($_REQUEST['name'])) : "";
     }
 
@@ -205,22 +205,10 @@
     if (!empty($name)) {
     
         // set form component descriptors
         $input_descriptors0 = array();
         
-        $input_descriptors0[] = array(
-                                        "type" => "hidden",
-                                        "value" => dalo_csrf_token(),
-                                        "name" => "csrf_token"
-                                     );
-        
-        $input_descriptors0[] = array(
-                                        "type" => "hidden",
-                                        "value" => $name_enc,
-                                        "name" => "name"
-                                     );
-
         $input_descriptors0[] = array(
                                         "name" => "name_presentation",
                                         "caption" => t('all','HotSpotName'),
                                         "type" => "text",
                                         "value" => ((isset($name)) ? $name : ""),
@@ -242,11 +230,24 @@
                                         "type" => "text",
                                         "value" => ((isset($geocode)) ? $geocode : ""),
                                         "tooltipText" => t('Tooltip','geocodeTooltip')
                                      );
         
-        $input_descriptors0[] = array(
+        $input_descriptors1 = array();
+        $input_descriptors1[] = array(
+                                        "type" => "hidden",
+                                        "value" => dalo_csrf_token(),
+                                        "name" => "csrf_token"
+                                     );
+        
+        $input_descriptors1[] = array(
+                                        "type" => "hidden",
+                                        "value" => $name_enc,
+                                        "name" => "name"
+                                     );
+        
+        $input_descriptors1[] = array(
                                         "type" => "submit",
                                         "name" => "submit",
                                         "value" => t('buttons','apply')
                                   );
         
@@ -282,10 +283,14 @@
         
         include_once('include/management/contactinfo.php');
         
         close_tab($navkeys, 1);
         
+        foreach ($input_descriptors1 as $input_descriptor) {
+            print_form_component($input_descriptor);
+        }
+        
         close_form();
         
     }
 
     include('include/config/logging.php');
diff --git a/mng-hs-new.php b/mng-hs-new.php
index 4a8021e1b..9dc34f47a 100644
--- a/mng-hs-new.php
+++ b/mng-hs-new.php
@@ -156,16 +156,10 @@
     if (!isset($successMsg)) {
 
         // set form component descriptors
         $input_descriptors0 = array();
         
-        $input_descriptors0[] = array(
-                                        "type" => "hidden",
-                                        "value" => dalo_csrf_token(),
-                                        "name" => "csrf_token"
-                                     );
-        
         $input_descriptors0[] = array(
                                         "name" => "name",
                                         "caption" => t('all','HotSpotName'),
                                         "type" => "text",
                                         "value" => ((isset($name)) ? $name : ""),
@@ -186,11 +180,19 @@
                                         "type" => "text",
                                         "value" => ((isset($geocode)) ? $geocode : ""),
                                         "tooltipText" => t('Tooltip','geocodeTooltip')
                                      );
         
-        $input_descriptors0[] = array(
+        $input_descriptors1 = array();
+        
+        $input_descriptors1[] = array(
+                                        "type" => "hidden",
+                                        "value" => dalo_csrf_token(),
+                                        "name" => "csrf_token"
+                                     );
+        
+        $input_descriptors1[] = array(
                                         "type" => "submit",
                                         "name" => "submit",
                                         "value" => t('buttons','apply')
                                      );
 
@@ -226,10 +228,14 @@
         
         include_once('include/management/contactinfo.php');
         
         close_tab($navkeys, 1);
         
+        foreach ($input_descriptors1 as $input_descriptor) {
+            print_form_component($input_descriptor);
+        }
+        
         close_form();
 
     }
 
     include('include/config/logging.php');

Vulnerable code:     $username = (array_key_exists('username', $_GET) && isset($_GET['username']))
                    ? str_replace("%", "", $_GET['username']) : "";
    $startdate = (array_key_exists('startdate', $_GET) && isset($_GET['startdate']) &&
                  preg_match(DATE_REGEX, $_GET['startdate'], $m) !== false &&
               ? $_GET['startdate'] : "";
    $enddate = (array_key_exists('enddate', $_GET) && isset($_GET['enddate']) &&
                preg_match(DATE_REGEX, $_GET['enddate'], $m) !== false &&
             ? $_GET['enddate'] : "";
                    "nasipaddress" => t('all','NASIPAddress'),
    $orderBy = (array_key_exists('orderBy', $_GET) && isset($_GET['orderBy']) &&
    $orderType = (array_key_exists('orderType', $_GET) && isset($_GET['orderType']) &&
                setupNumbering($numrows, $rowsPerPage, $pageNum, $orderBy, $orderType);
    <tbody>
            $simple_td_format = '<td>%s</td>';
                foreach ($row as $i => $value) {
                    $row[$i] = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
                }
                echo "<tr>";
                printf($simple_td_format, $row[0]);
                $onclick = "javascript:ajaxGeneric('include/management/retHotspotInfo.php','retHotspotGeneralStat','divContainerHotspotInfo'"
                         . sprintf(",'hotspot=%s');return false;", $row[1]);
                                   $li_style, urlencode($row[1]), t('Tooltip','HotspotEdit'))
                printf('<td><a class="tablenovisit" href="#" onclick="%s" ' . "tooltipText='%s'>%s</a></td>",
                       $onclick, $tooltip, $row[1]);
                         . sprintf("'username=%s');return false;", $row[2]);
                $tooltip = sprintf('<a class="toolTip" href="mng-edit.php?username=%s">%s</a>', $row[2], t('Tooltip','UserEdit'))
                printf('<td><a class="tablenovisit" href="#" onclick="%s" ' . "tooltipText='%s'>%s</a></td>",
                       $onclick, $tooltip, $row[2]);
                printf($simple_td_format, $row[3]);
                printf($simple_td_format, $row[4]);
                printf($simple_td_format, $row[5]);
                printf($simple_td_format, time2str($row[6]));
                printf($simple_td_format, toxbyte($row[7]));
                printf($simple_td_format, toxbyte($row[8]));
                printf($simple_td_format, $row[9]);
                printf($simple_td_format, $row[10]);
            
                echo "</tr>";
            
    include ("library/checklogin.php");
    isset($_REQUEST['username']) ? $username = trim($_REQUEST['username']) : $username = '';
    isset($_REQUEST['enddate']) ? $enddate = trim($_REQUEST['enddate']) : $enddate = "";

    $logAction = '';
    $logDebugSQL = '';

    if (isset($_POST['submit'])) {

        if ($username != '') {

            include 'library/opendb.php';

            $sql = 'SELECT count(*) FROM ' . $configValues['CONFIG_DB_TBL_RADACCT'] .
                   ' WHERE username = "' . $username . '" AND acctstoptime is NULL;';

            $res = $dbSocket->query($sql);

            $logDebugSQL .= $sql . "\n";

            $row = $res->fetchRow();

            if($row[0] > 0) {
                $sql = 'UPDATE ' . $configValues['CONFIG_DB_TBL_RADACCT'] .
                       ' SET acctstoptime = NOW(), acctterminatecause = "Admin-Reset"'.
                       ' WHERE username = "' . $username . '" AND acctstoptime is NULL;'; 
                $logDebugSQL .= $sql . "\n";

                $successMsg = "Cleaned up stale sessions for username: <b> $username </b>";
                $logAction .= "Successfully cleaned up stale sessions for username [$username] on page: ";
            }
            else {

                $failureMsg = "There are no stale sessions for user [$username]";
                $logAction .= "Failed performing close stale sessions on user [$username] because there are no stale sessions for that user on page: ";

            include 'library/closedb.php';
        }
        else if ($enddate != '') {

            include 'library/opendb.php';

            // delete all stale sessions in the database that occur until $enddate
            $sql = "DELETE FROM ".$configValues['CONFIG_DB_TBL_RADACCT'].
                    " WHERE AcctStartTime<'".$dbSocket->escapeSimple($enddate)."'".
                    " AND (AcctStopTime='0000-00-00 00:00:00' OR AcctStopTime IS NULL)";
            $res = $dbSocket->query($sql);
            $logDebugSQL .= $sql . "\n";

            $successMsg = "Cleaned up stale sessions until date: <b> $enddate </b>";
            $logAction .= "Successfully cleaned up stale sessions until date [$enddate] on page: ";

            include 'library/closedb.php';

        }
        else {
            $failureMsg = "No username or ending date was entered, please specify a username or ending date for cleaning up stale sessions from the database";
            $logAction .= "Failed cleaning up stale sessions due to lack of username or ending date on page: ";
    include_once('library/config_read.php');
    $log = "visited page: ";
    
    include_once("lang/main.php");
    
    include("library/layout.php");
    $navbuttons = array(
                          'CleanupRecordsByUsername-tab' => t('title','CleanupRecordsByUsername'),
                          'CleanupRecordsByDate-tab' => t('title','CleanupRecordsByDate'),
                       );

    print_tab_navbuttons($navbuttons);
?>


        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

            
                <div class="tabcontent" id="CleanupRecordsByUsername-tab" style="display: block">

                    <fieldset>

                        <h302> <?php echo t('title','CleanupRecordsByUsername'); ?> </h302>
                        <br/>

                        <label for='username' class='form'><?php echo t('all','Username')?></label>
                        <input name="username" type="text" id="usernameEdit" autocomplete="off"
                        tooltipText='<?php echo t('Tooltip','Username'); ?> <br/>'
                        value="<?php if (isset($username)) echo $username; ?>" tabindex=100>
<?php
    include_once("include/management/autocomplete.php");

    if ($autoComplete) {
        echo "<script type=\"text/javascript\">
                /** Making usernameEdit interactive **/
                autoComEdit = new DHTMLSuite.autoComplete();
                autoComEdit.add('usernameEdit','include/management/dynamicAutocomplete.php','_small','getAjaxAutocompleteUsernames');
                </script>";
?>
                        <br/><br/>
                        <hr><br/>

                        <input type='submit' name='submit' value='<?php echo t('buttons','apply') ?>' class='button' />

                    </fieldset>

                </div>

                <div class="tabcontent" id="CleanupRecordsByDate-tab">

                    <fieldset>
                        <h302> <?php echo t('title','CleanupRecordsByDate') ?> </h302>
                        <br/>

                        <label for='enddate' class='form'><?php echo t('all','CleanupSessions')?></label>
                        <input name='enddate' type='text' id='enddate' value='<?php echo $enddate ?>' tabindex=100 />
                        <img src="library/js_date/calendar.gif" onclick=
                        "showChooser(this, 'enddate', 'chooserSpan', 1950, <?php echo date('Y', time());?>, 'Y-m-d H:i:s', true);" >

                        <br/><br/>
                        <hr><br/>
                        <input type="submit" name="submit" value="<?php echo t('buttons','apply') ?>" tabindex=1000 class='button' />
                    </fieldset>

                    <div id="chooserSpan" class="dateChooser select-free"
                        style="display: none; visibility: hidden; width: 160px;">
                    </div>
                </div>
    </form>
        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    include('page-footer.php');
?>
        </div><!-- #footer -->
    </div>
</div>
</body>
</html>

 
    isset($_REQUEST['enddate']) ? $enddate = $_REQUEST['enddate'] : $enddate = "";
    isset($_REQUEST['startdate']) ? $startdate = $_REQUEST['startdate'] : $startdate = "";
    isset($_REQUEST['username']) ? $username = $_REQUEST['username'] : $username = "";

    $logAction =  "";
    if (isset($_POST['submit'])) {

        if ( (trim($startdate) != "") || (trim($enddate) != "") || (trim($username) != "") ) {
            include 'library/opendb.php';

            $deleteUsername = "";
            if (trim($username) != "")
                $deleteUsername = " AND Username='$username'";

            $deleteEnddate = "";
            if (trim($enddate) != "")
                $deleteEnddate = " AND AcctStartTime<'".$dbSocket->escapeSimple($enddate)."'";

            $deleteStartdate = "";
            if (trim($startdate) != "")
                $deleteStartdate = " AND AcctStartTime>'".$dbSocket->escapeSimple($startdate)."'";


            $sql = "DELETE FROM ".$configValues['CONFIG_DB_TBL_RADACCT'].
                " WHERE 1=1".
                " $deleteStartdate".
                " $deleteEnddate".
                " $deleteUsername ";
            $res = $dbSocket->query($sql);
            $logDebugSQL .= $sql . "\n";

            $successMsg = "Deleted records between <b>$startdate</b> to <b>$enddate</b> for user <b>$username</b>";
            $logAction .= "Successfully deleted records between [$startdate] and [$enddate] for user [$username] on page: ";

            include 'library/closedb.php';

        }  else { 
            $failureMsg = "no username, ending date or starting date was provided, please at least one of those";
            $logAction .= "Failed deleting records from database, missing fields on page: ";


    include_once('library/config_read.php');
    $log = "visited page: ";

    include_once("lang/main.php");
    include("library/layout.php");
?>

        
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <fieldset>

        <h302> <?php echo t('title','DeleteRecords') ?> </h302>
        <br/>

        <label for='username' class='form'><?php echo t('all','Username')?></label>
        <input name='username' type='text' id='username' value='<?php echo $username ?>' tabindex=100 />
        <br />

        <label for='startdate' class='form'><?php echo t('all','StartingDate')?></label>
        <input name='startdate' type='text' id='startdate' value='<?php echo $startdate ?>' tabindex=100 />
        <img src="library/js_date/calendar.gif" onclick=
        "showChooser(this, 'startdate', 'chooserSpan', 1950, <?php echo date('Y', time());?>, 'Y-m-d H:i:s', true);" >
        <br />

        <label for='enddate' class='form'><?php echo t('all','EndingDate')?></label>
        <input name='enddate' type='text' id='enddate' value='<?php echo $enddate ?>' tabindex=100 />
        <img src="library/js_date/calendar.gif" onclick=
        "showChooser(this, 'enddate', 'chooserSpan', 1950, <?php echo date('Y', time());?>, 'Y-m-d H:i:s', true);" >
        <br />

        <br/><br/>
        <hr><br/>
        <input type="submit" name="submit" value="<?php echo t('buttons','apply') ?>" tabindex=1000 class='button' />

    </fieldset>
    <div id="chooserSpan" class="dateChooser select-free" 
        style="display: none; visibility: hidden; width: 160px;">
    </div>
</form>
        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    include('page-footer.php');
        </div><!-- #footer -->
    </div>
</div>

</body>
</html>
$input_descriptors1 = array();
$input_descriptors1[] = array( "name" => "ownername", "caption" => t('ContactInfo','OwnerName'),
                               "type" => "text", "value" => ((isset($owner)) ? $owner : ""), );
$input_descriptors1[] = array( "name" => "emailowner", "caption" => t('ContactInfo','OwnerEmail'),
                               "type" => "text", "value" => ((isset($email_owner)) ? $email_owner : "") , );
$input_descriptors1[] = array( "name" => "managername", "caption" => t('ContactInfo','ManagerName'),
                               "type" => "text", "value" => ((isset($manager)) ? $manager : "") , );
$input_descriptors1[] = array( "name" => "emailmanager", "caption" => t('ContactInfo','ManagerEmail'),
                               "type" => "text", "value" => ((isset($email_manager)) ? $email_manager : "") , );
$input_descriptors1[] = array( "name" => "company", "caption" => t('ContactInfo','Company'),
                               "type" => "text", "value" => ((isset($company)) ? $company : "") , );
$input_descriptors1[] = array( "name" => "address", "caption" => t('ContactInfo','Address'),
                               "type" => "textarea", "content" => ((isset($address)) ? $address : ""), );                               
$input_descriptors1[] = array( "name" => "phone1", "caption" => t('ContactInfo','Phone1'),
                               "type" => "text", "value" => ((isset($phone1)) ? $phone1 : "") , );
$input_descriptors1[] = array( "name" => "phone2", "caption" => t('ContactInfo','Phone2'),
                               "type" => "text", "value" => ((isset($phone2)) ? $phone2 : "") , );
$input_descriptors1[] = array( "name" => "hotspot_type", "caption" => t('ContactInfo','HotspotType'),
                               "type" => "text", "value" => ((isset($hotspot_type)) ? $hotspot_type : "") , );
$input_descriptors1[] = array( "name" => "companywebsite", "caption" => t('ContactInfo','CompanyWebsite'),
                               "type" => "text", "value" => ((isset($companywebsite)) ? $companywebsite : "") , );
$input_descriptors1[] = array( "name" => "companyemail", "caption" => t('ContactInfo','CompanyEmail'),
                               "type" => "text", "value" => ((isset($companyemail)) ? $companyemail : "") , );
$input_descriptors1[] = array( "name" => "companyphone", "caption" => t('ContactInfo','CompanyPhone'),
                               "type" => "text", "value" => ((isset($companyphone)) ? $companyphone : "") , );
$input_descriptors1[] = array( "name" => "companycontact", "caption" => t('ContactInfo','CompanyContact'),
                               "type" => "text", "value" => ((isset($companycontact)) ? $companycontact : "") , );
$input_descriptors2 = array();
$input_descriptors2[] = array( 'name' => 'creationdate', 'caption' => t('all','CreationDate'), 'type' => 'text',
                               'disabled' => true, 'value' => ((isset($creationdate)) ? $creationdate : '') );
$input_descriptors2[] = array( 'name' => 'creationby', 'caption' => t('all','CreationBy'), 'type' => 'text',
                               'disabled' => true, 'value' => ((isset($creationby)) ? $creationby : '') );
$input_descriptors2[] = array( 'name' => 'updatedate', 'caption' => t('all','UpdateDate'), 'type' => 'text',
                               'disabled' => true, 'value' => ((isset($updatedate)) ? $updatedate : '') );
$input_descriptors2[] = array( 'name' => 'updateby', 'caption' => t('all','UpdateBy'), 'type' => 'text',
                               'disabled' => true, 'value' => ((isset($updateby)) ? $updateby : '') );
$button_descriptor = array(
                            "type" => "submit",
                            "name" => "submit",
                            "value" => t('buttons','apply')
                          );
?>
<fieldset>
    <h302>Contact Info</h302>
    <h301>Contact Info</h301>
    <ul>
<?php
    foreach ($input_descriptors1 as $input_descriptor) {
        print_form_component($input_descriptor);
    }
?>
    </ul>
</fieldset>
<fieldset>
    <h302>Other</h302>
    <h301>Other</h301>
    <ul>
<?php
    foreach ($input_descriptors2 as $input_descriptor) {
        print_form_component($input_descriptor);
    }
?>
    </ul>
</fieldset>
<?php
    print_form_component($button_descriptor);
              ? str_replace("%", "", trim($_POST['name']))) : "";
        $input_descriptors0[] = array(
                                        "type" => "hidden",
                                        "value" => dalo_csrf_token(),
                                        "name" => "csrf_token"
                                     );
        
        $input_descriptors0[] = array(
                                        "type" => "hidden",
                                        "value" => $name_enc,
                                        "name" => "name"
                                     );

        $input_descriptors0[] = array(
        $input_descriptors0[] = array(
                                        "type" => "hidden",
                                        "value" => dalo_csrf_token(),
                                        "name" => "csrf_token"
                                     );
        
        $input_descriptors0[] = array(
Fixed code:     $username = (array_key_exists('username', $_GET) && !empty(str_replace("%", "", trim($_GET['username']))))
              ? str_replace("%", "", trim($_GET['username'])) : "";
    $startdate = (array_key_exists('startdate', $_GET) && !empty(trim($_GET['startdate'])) &&
                  preg_match(DATE_REGEX, trim($_GET['startdate']), $m) !== false &&
               ? trim($_GET['startdate']) : "";
    $enddate = (array_key_exists('enddate', $_GET) && !empty(trim($_GET['enddate'])) &&
                preg_match(DATE_REGEX, trim($_GET['enddate']), $m) !== false &&
             ? trim($_GET['enddate']) : "";
        "library/javascript/ajax.js",
        "library/javascript/ajaxGeneric.js",
                    "nasipaddress" => t('all','NASIPAddress'),
    $orderBy = (array_key_exists('orderBy', $_GET) && !empty($_GET['orderBy']) &&
    $orderType = (array_key_exists('orderType', $_GET) && !empty($_GET['orderType']) &&
                setupNumbering($numrows, $rowsPerPage, $pageNum, $orderBy, $orderType, $partial_query_string);
            echo '<tbody>';

            
            $trs = array();
                list(
                        $radacctid, $hotspot, $username, $framedipaddress,
                        $acctstarttime, $acctstoptime, $acctsessiontime, $acctinputoctets,
                        $acctoutputoctets, $acctterminatecause, $nasipaddress
                    ) = $row;
                
                $tr = array();
                // radacctid
                $tr[] = intval($radacctid);
                
                // hotspot
                $hotspot = htmlspecialchars($hotspot, ENT_QUOTES, 'UTF-8');
                $onclick = "ajaxGeneric('include/management/retHotspotInfo.php','retHotspotGeneralStat','divContainerHotspotInfo'"
                         . sprintf(",'hotspot=%s');return false;", $hotspot);
                                   $li_style, urlencode($hotspot), t('Tooltip','HotspotEdit'))
                $tr[] = sprintf('<a class="tablenovisit" href="#" onclick="%s" ' . "tooltipText='%s'>%s</a>",
                                $onclick, $tooltip, $hotspot);
                
                // nasipaddress
                $tr[] = htmlspecialchars($nasipaddress, ENT_QUOTES, 'UTF-8');
                // username
                $username = htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
                         . sprintf("'username=%s');return false;", $username);
                $tooltip = sprintf('<a class="toolTip" href="mng-edit.php?username=%s">%s</a>', urlencode($username), t('Tooltip','UserEdit'))
                $tr[] = sprintf('<a class="tablenovisit" href="#" onclick="%s" ' . "tooltipText='%s'>%s</a>",
                                $onclick, $tooltip, $username);
                
                // other values
                $tr[] = htmlspecialchars($framedipaddress, ENT_QUOTES, 'UTF-8');
                $tr[] = htmlspecialchars($acctstarttime, ENT_QUOTES, 'UTF-8');
                $tr[] = htmlspecialchars($acctstoptime, ENT_QUOTES, 'UTF-8');
                $tr[] = time2str($acctsessiontime);
                $tr[] = toxbyte($acctinputoctets);
                $tr[] = toxbyte($acctoutputoctets);
                $tr[] = htmlspecialchars($acctterminatecause, ENT_QUOTES, 'UTF-8');
                
                $trs[] = $tr;
            }

            // draw tr(s)
            $simple_td_format = '<td>%s</td>' . "\n";
            foreach ($trs as $tr) {
                echo '<tr>';
                foreach ($tr as $td) {
                    printf($simple_td_format, $td);
                }
                
                echo '</tr>';
    include("library/checklogin.php");
    include_once('library/config_read.php');
    
    // init logging variables
    $logAction = "";
    $logDebugSQL = "";
    $log = "visited page: ";
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    include('library/opendb.php');
    
    // valid min/max dates
    $sql = sprintf("SELECT DATE(MIN(acctstarttime)), DATE(MAX(acctstarttime)) FROM %s", $configValues['CONFIG_DB_TBL_RADACCT']);
    $res = $dbSocket->query($sql);
    $logDebugSQL .= "$sql;\n";
    
    list($mindate, $maxdate) = $res->fetchrow();
    
    // valid usernames
    $sql = sprintf("SELECT DISTINCT(username) FROM %s ORDER BY username ASC", $configValues['CONFIG_DB_TBL_RADACCT']);
    $res = $dbSocket->query($sql);
    $logDebugSQL .= "$sql;\n";
    
    $valid_usernames = array();
    while ($row = $res->fetchrow()) {
        $valid_usernames[] = $row[0];
    }
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (array_key_exists('csrf_token', $_POST) && isset($_POST['csrf_token']) && dalo_check_csrf_token($_POST['csrf_token'])) {
            
            $username = (array_key_exists('username', $_POST) && !empty(trim($_POST['username'])) &&
                         in_array(trim($_POST['username']), $valid_usernames))
                      ? trim($_POST['username']) : "";
            
            $enddate = (array_key_exists('enddate', $_POST) && isset($_POST['enddate']) &&
                        preg_match(DATE_REGEX, $_POST['enddate'], $m) !== false &&
                        checkdate($m[2], $m[3], $m[1]))
                     ? $_POST['enddate'] : "";
                     
            if (!empty($username)) {
                
                $username_enc = htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
                
                $sql = sprintf("SELECT COUNT(radacctid) FROM %s WHERE username='%s' AND acctstoptime IS NULL",
                               $configValues['CONFIG_DB_TBL_RADACCT'], $dbSocket->escapeSimple($username));
                $logDebugSQL .= "$sql;\n";
                $numrows = intval($res->fetchrow()[0]);
                
                if ($numrows > 0) {
                    $sql = sprintf("UPDATE %s SET acctstoptime=NOW(), acctterminatecause='Admin-Reset'
                                     WHERE username='%s' AND acctstoptime IS NULL",
                                   $configValues['CONFIG_DB_TBL_RADACCT'],
                                   $dbSocket->escapeSimple($username)); 
                    $res = $dbSocket->query($sql);
                    $logDebugSQL .= "$sql;\n";

                    if (!DB::isError($res)) {
                        $successMsg = "Cleaned up stale sessions for user: $username_enc";
                        $logAction .= "Successfully cleaned up stale sessions for username [$username] on page: ";
                    } else {
                        $failureMsg = "Cannot clean up stale sessions for user: $username_enc";
                        $logAction .= "$failureMsg page: ";
                    }

                } else {
                    // nothing to delete
                    $failureMsg = "There are no stale sessions for user [$username_enc]";
                    $logAction .= "Cannot clean up stale sessions for user $username [no stale sessions for this user] on page: ";
                }
                
            } else if (!empty($enddate)) {
                if ($enddate >= $mindate && $enddate <= $maxdate) {
                
                    // delete all stale sessions in the database that occur until $enddate
                    $sql = sprintf("DELETE FROM %s
                                          WHERE acctstarttime < '%s'
                                            AND (acctstoptime = '0000-00-00 00:00:00' OR acctstoptime IS NULL)",
                                   $configValues['CONFIG_DB_TBL_RADACCT'], $enddate);
                    $res = $dbSocket->query($sql);
                    $logDebugSQL .= "$sql\n";

                    if (!DB::isError($res)) {
                        $successMsg = "Cleaned up stale sessions until date: $enddate";
                        $logAction .= "Successfully cleaned up stale sessions until date [$enddate] on page: ";
                    } else {
                        $failureMsg = "Cannot clean up stale sessions until date: $enddate";
                        $logAction .= "$failureMsg page: ";
                    }

                    
                } else {
                    // invalid
                    $failureMsg = "Cannot clean up stale sessions: $enddate is invalid";
                    $logAction .= "$failureMsg page: ";
                }
            } else {
                // invalid
                $failureMsg = "Cannot clean up stale sessions: provided empty/invalid username or ending date";
                $logAction .= "$failureMsg page: ";
            
        } else {
            // csrf
            $failureMsg = "CSRF token error";
            $logAction .= "$failureMsg on page: ";
    include('library/closedb.php');

    
    $navkeys = array( 'CleanupRecordsByUsername', 'CleanupRecordsByDate', );
    // print navbar controls
    print_tab_header($navkeys);
    
    $options = $valid_usernames;
    array_unshift($options , '');

    $input_descriptors0 = array();
    $input_descriptors0[] = array(
                                    'name' => 'username',
                                    'type' => 'select',
                                    'caption' => t('all','Username'),
                                    'options' => $options,
                                    'selected_value' => $username
                                 );
    
    $fieldset0_descriptor = array(
                                    "title" => t('title','CleanupRecordsByUsername'),
                                    "disabled" => (count($valid_usernames) == 0)
                                 );           
    
    $input_descriptors1 = array();
    $input_descriptors1[] = array(
                                    'name' => 'enddate',
                                    'caption' => t('all','CleanupSessions'),
                                    'type' => 'date',
                                    'value' => $enddate,
                                    'min' => $mindate,
                                    'max' => $maxdate,
                                 );

    $fieldset1_descriptor = array(
                                    "title" => t('title','CleanupRecordsByDate'),
                                    "disabled" => (count($valid_usernames) == 0)
                                 );

    open_form();
    
    // open tab 0
    open_tab($navkeys, 0, true);
    
    open_fieldset($fieldset0_descriptor);
    foreach ($input_descriptors0 as $input_descriptor) {
        print_form_component($input_descriptor);
    
    close_fieldset();
    
    close_tab($navkeys, 0);
    // open tab 1
    open_tab($navkeys, 1);
    
    open_fieldset($fieldset1_descriptor);
    foreach ($input_descriptors1 as $input_descriptor) {
        print_form_component($input_descriptor);
    }
    
    close_fieldset();
    
    close_tab($navkeys, 1);
    
    $input_descriptors2 = array();
    $input_descriptors2[] = array(
                                    "name" => "csrf_token",
                                    "type" => "hidden",
                                    "value" => dalo_csrf_token(),
                                 );
    
    $input_descriptors2[] = array(
                                    "type" => "submit",
                                    "name" => "submit",
                                    "value" => t('buttons','apply')
                                  );

    foreach ($input_descriptors2 as $input_descriptor) {
        print_form_component($input_descriptor);
    }
    close_form();
    
    print_back_to_previous_page();
    print_footer_and_html_epilogue();
?>
 
    include_once('library/config_read.php');
    
    // init logging variables
    $logAction = "";
    $log = "visited page: ";
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    
    
    include('library/opendb.php');
    
    // valid min/max dates
    $sql = sprintf("SELECT DATE(MIN(acctstarttime)), DATE(MAX(acctstarttime)) FROM %s", $configValues['CONFIG_DB_TBL_RADACCT']);
    $res = $dbSocket->query($sql);
    $logDebugSQL .= "$sql;\n";
    
    list($mindate, $maxdate) = $res->fetchrow();
    
    // valid usernames
    $sql = sprintf("SELECT DISTINCT(username) FROM %s ORDER BY username ASC", $configValues['CONFIG_DB_TBL_RADACCT']);
    $res = $dbSocket->query($sql);
    $logDebugSQL .= "$sql;\n";
    
    $valid_usernames = array();
    while ($row = $res->fetchrow()) {
        $valid_usernames[] = $row[0];
    }
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (array_key_exists('csrf_token', $_POST) && isset($_POST['csrf_token']) && dalo_check_csrf_token($_POST['csrf_token'])) {
            $required_fields = array();
            $sql_WHERE = array();
            $username = (array_key_exists('username', $_POST) && !empty(trim($_POST['username'])) &&
                         in_array(trim($_POST['username']), $valid_usernames))
                      ? trim($_POST['username']) : "";
            if (empty($username)) {
                $required_fields['username'] = t('all','Username');
            } else {
                $username_enc = htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
                $sql_WHERE[] = sprintf("username='%s'", $dbSocket->escapeSimple($username));
            }
            
            $startdate = (array_key_exists('startdate', $_POST) && isset($_POST['startdate']) &&
                          preg_match(DATE_REGEX, $_POST['startdate'], $m) !== false &&
                          checkdate($m[2], $m[3], $m[1]))
                       ? $_POST['startdate'] : "";
            if (empty($startdate)) {
                $required_fields['startdate'] = t('all','StartingDate');
            } else {
                $sql_WHERE[] = sprintf("AcctStartTime > '%s'", $startdate);
            }
            
            $enddate = (array_key_exists('enddate', $_POST) && isset($_POST['enddate']) &&
                        preg_match(DATE_REGEX, $_POST['enddate'], $m) !== false &&
                        checkdate($m[2], $m[3], $m[1]))
                     ? $_POST['enddate'] : "";
            if (empty($enddate)) {
                $required_fields['enddate'] = t('all','EndingDate');
            } else {
                $sql_WHERE[] = sprintf("AcctStartTime < '%s'", $enddate);
            }
            
            // further checks
            if (!empty($startdate) && !empty($enddate) && $startdate >= $mindate && $enddate <= $maxdate && $startdate > $enddate) {
                $required_fields['startdate'] = t('all','StartingDate');
                $required_fields['enddate'] = t('all','EndingDate');
            }
            
            if (count($required_fields) > 0) {
                // required/invalid
                $failureMsg = sprintf("Empty or invalid required field(s) [%s]", implode(", ", array_values($required_fields)));
                $logAction .= "$failureMsg on page: ";
            } else {
                
                $sql = sprintf("DELETE FROM %s WHERE %s", $configValues['CONFIG_DB_TBL_RADACCT'],
                                                          implode(" AND ", $sql_WHERE));
                $res = $dbSocket->query($sql);
                $logDebugSQL .= "$sql;\n";
                
                if (!DB::isError($res)) {
                    $successMsg = sprintf("Deleted accounting records for user %s [period: %s - %s]",
                                          $username_enc, $startdate, $enddate);
                    $logAction .= "$successMsg on page: ";
                } else {
                    $failureMsg = sprintf("Failed to deleted accounting records for user %s [period: %s - %s]",
                                          $username_enc, $startdate, $enddate);
                    $logAction .= "$failureMsg page: ";
                }
            }
            
        } else {
            // csrf
            $failureMsg = "CSRF token error";
            $logAction .= "$failureMsg on page: ";
    include('library/closedb.php');
    
    
    $options = $valid_usernames;
    array_unshift($options , '');
    
    $input_descriptors0 = array();

    $input_descriptors0[] = array(
                                    'name' => 'username',
                                    'type' => 'select',
                                    'caption' => t('all','Username'),
                                    'options' => $options,
                                    'selected_value' => $username
                                 );

    $input_descriptors0[] = array(
                                    'name' => 'startdate',
                                    'caption' => t('all','StartingDate'),
                                    'type' => 'date',
                                    'value' => $startdate,
                                    'min' => $mindate,
                                    'max' => $maxdate,
                                 );
                                 
    $input_descriptors0[] = array(
                                    'name' => 'enddate',
                                    'caption' => t('all','EndingDate'),
                                    'type' => 'date',
                                    'value' => $enddate,
                                    'min' => $mindate,
                                    'max' => $maxdate,
                                 );
                                 
    $input_descriptors0[] = array(
                                    "name" => "csrf_token",
                                    "type" => "hidden",
                                    "value" => dalo_csrf_token(),
                                 );
    
    $input_descriptors0[] = array(
                                    "type" => "submit",
                                    "name" => "submit",
                                    "value" => t('buttons','apply')
                                  );
    
    $fieldset0_descriptor = array(
                                    "title" => t('title','DeleteRecords'),
                                    "disabled" => (count($valid_usernames) == 0)
                                 );
                                 
    open_form();
    
    open_fieldset($fieldset0_descriptor);
    foreach ($input_descriptors0 as $input_descriptor) {
        print_form_component($input_descriptor);
    }
    
    close_fieldset();
    
    close_form();
    print_back_to_previous_page();
    print_footer_and_html_epilogue();
    
$_input_descriptors1 = array();
$_input_descriptors1[] = array( "name" => "ownername", "caption" => t('ContactInfo','OwnerName'),
                                "type" => "text", "value" => ((isset($owner)) ? $owner : ""), );
$_input_descriptors1[] = array( "name" => "emailowner", "caption" => t('ContactInfo','OwnerEmail'),
                                "type" => "text", "value" => ((isset($email_owner)) ? $email_owner : "") , );
$_input_descriptors1[] = array( "name" => "managername", "caption" => t('ContactInfo','ManagerName'),
                                "type" => "text", "value" => ((isset($manager)) ? $manager : "") , );
$_input_descriptors1[] = array( "name" => "emailmanager", "caption" => t('ContactInfo','ManagerEmail'),
                                "type" => "text", "value" => ((isset($email_manager)) ? $email_manager : "") , );
$_input_descriptors1[] = array( "name" => "company", "caption" => t('ContactInfo','Company'),
                                "type" => "text", "value" => ((isset($company)) ? $company : "") , );
$_input_descriptors1[] = array( "name" => "address", "caption" => t('ContactInfo','Address'),
                                "type" => "textarea", "content" => ((isset($address)) ? $address : ""), );                               
$_input_descriptors1[] = array( "name" => "phone1", "caption" => t('ContactInfo','Phone1'),
                                "type" => "text", "value" => ((isset($phone1)) ? $phone1 : "") , );
$_input_descriptors1[] = array( "name" => "phone2", "caption" => t('ContactInfo','Phone2'),
                                "type" => "text", "value" => ((isset($phone2)) ? $phone2 : "") , );
$_input_descriptors1[] = array( "name" => "hotspot_type", "caption" => t('ContactInfo','HotspotType'),
                                "type" => "text", "value" => ((isset($hotspot_type)) ? $hotspot_type : "") , );
$_input_descriptors1[] = array( "name" => "companywebsite", "caption" => t('ContactInfo','CompanyWebsite'),
                                "type" => "text", "value" => ((isset($companywebsite)) ? $companywebsite : "") , );
$_input_descriptors1[] = array( "name" => "companyemail", "caption" => t('ContactInfo','CompanyEmail'),
                                "type" => "text", "value" => ((isset($companyemail)) ? $companyemail : "") , );
$_input_descriptors1[] = array( "name" => "companyphone", "caption" => t('ContactInfo','CompanyPhone'),
                                "type" => "text", "value" => ((isset($companyphone)) ? $companyphone : "") , );
$_input_descriptors1[] = array( "name" => "companycontact", "caption" => t('ContactInfo','CompanyContact'),
                                "type" => "text", "value" => ((isset($companycontact)) ? $companycontact : "") , );
$_fieldset1_descriptor = array(
                                "title" => t('title','ContactInfo'),
                              );
                          
open_fieldset($_fieldset1_descriptor);
foreach ($_input_descriptors1 as $input_descriptor) {
    print_form_component($input_descriptor);
}
close_fieldset();
$_input_descriptors2 = array();
$_input_descriptors2[] = array( 'name' => 'creationdate', 'caption' => t('all','CreationDate'), 'type' => 'text',
                                'disabled' => true, 'value' => ((isset($creationdate)) ? $creationdate : '') );
$_input_descriptors2[] = array( 'name' => 'creationby', 'caption' => t('all','CreationBy'), 'type' => 'text',
                                'disabled' => true, 'value' => ((isset($creationby)) ? $creationby : '') );
$_input_descriptors2[] = array( 'name' => 'updatedate', 'caption' => t('all','UpdateDate'), 'type' => 'text',
                                'disabled' => true, 'value' => ((isset($updatedate)) ? $updatedate : '') );
$_input_descriptors2[] = array( 'name' => 'updateby', 'caption' => t('all','UpdateBy'), 'type' => 'text',
                                'disabled' => true, 'value' => ((isset($updateby)) ? $updateby : '') );
$_fieldset2_descriptor = array(
                                "title" => "Other",
                              );
open_fieldset($_fieldset2_descriptor);
foreach ($_input_descriptors2 as $input_descriptor) {
    print_form_component($input_descriptor);
}
close_fieldset();
              ? str_replace("%", "", trim($_POST['name'])) : "";
        $input_descriptors1 = array();
        $input_descriptors1[] = array(
                                        "type" => "hidden",
                                        "value" => dalo_csrf_token(),
                                        "name" => "csrf_token"
                                     );
        
        $input_descriptors1[] = array(
                                        "type" => "hidden",
                                        "value" => $name_enc,
                                        "name" => "name"
                                     );
        
        $input_descriptors1[] = array(
        foreach ($input_descriptors1 as $input_descriptor) {
            print_form_component($input_descriptor);
        }
        
        $input_descriptors1 = array();
        
        $input_descriptors1[] = array(
                                        "type" => "hidden",
                                        "value" => dalo_csrf_token(),
                                        "name" => "csrf_token"
                                     );
        
        $input_descriptors1[] = array(
        foreach ($input_descriptors1 as $input_descriptor) {
            print_form_component($input_descriptor);
        }