CVE-2023-0338 (PHP, published 2023-01-17T16:15Z)
Description: value: Cross-site Scripting (XSS) - Reflected in GitHub repository lirantal/daloradius prior to master-branch.
Severity: nan (CVSS v3 base score: 6.1)
Weakness: CWE-79 \u2014 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
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.
Repository: https://github.com/lirantal/daloradius
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 message: Fixed acct and hs management (#341)

* Fixed bugs in some accounting related feature

* Fixed hs management ui components

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);
        }