CVE-2022-4630 (PHP, published 2022-12-21T18:15Z)
Description: value: Sensitive Cookie Without 'HttpOnly' Flag in GitHub repository lirantal/daloradius prior to master.
Severity: nan (CVSS v3 base score: 5.3)
Weakness: CWE-732 \u2014 Incorrect Permission Assignment for Critical Resource
The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.
Repository: https://github.com/lirantal/daloradius
Files changed:
acct-active.php
acct-all.php
acct-custom-query.php
acct-custom.php
acct-date.php
acct-ipaddress.php
acct-main.php
acct-nasipaddress.php
acct-username.php
bill-history-query.php
bill-history.php
bill-main.php
bill-merchant-transactions.php
bill-merchant.php
bill-pos-edit.php
bill-pos-new.php
bill-rates-date.php
config-db.php
config-lang.php
config-reports.php
gis-main.php
graph-main.php
help-main.php
include/management/userBilling.php
library/validation.php
menu-accounting-custom.php
menu-bill-history.php
menu-bill-merchant.php
mng-batch-add.php
mng-edit.php
mng-hs-edit.php
mng-hs-list.php
mng-import-users.php
mng-list-all.php
mng-new-quick.php
mng-new.php
mng-rad-attributes-edit.php
mng-rad-attributes-new.php
mng-rad-attributes-search.php
mng-rad-groupcheck-new.php
mng-rad-groupreply-new.php
mng-rad-nas-new.php
mng-rad-profiles-edit.php
mng-rad-profiles-new.php
mng-rad-usergroup-list-user.php
mng-rad-usergroup-list.php
mng-search.php
msg-error-permissions.php
rep-batch.php
rep-hb.php
rep-lastconnect.php
rep-logs-boot.php
rep-logs-radius.php
rep-logs-system.php
rep-logs.php
rep-main.php
rep-newusers.php
rep-stat-server.php
rep-stat-services.php
rep-stat-ups.php
rep-status.php
rep-topusers.php
rep-username.php
Commit message: Improved attribute dictionaries management feature (#316)

Improved layout and other minor features

Vulnerable code:
    // include validation utils
    include_once("lang/main.php");
    
    include("library/layout.php");

    include("library/validation.php");

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

    include_once('library/config_read.php');
    
    include("library/validation.php");
    
    include_once("lang/main.php");
    
    include("library/layout.php");
            echo "<tr>";
            echo "</tr>";
    include("library/validation.php");

    
    // include validation utils
    include_once("lang/main.php");
    
    include("library/layout.php");
    include_once("lang/main.php");
    
    include("library/layout.php");
    include_once("lang/main.php");
    
    include("library/layout.php");
    
    $username = (array_key_exists('username', $_GET) && isset($_GET['username']))
                    ? str_replace("%", "", $_GET['username']) : "";
    include("library/validation.php");

    include_once("lang/main.php");
    
    include("library/layout.php");
<?php
 * Authors:	Liran Tal <liran@enginx.com>
    include ("library/checklogin.php");
	include('library/check_operator_perm.php');
	
	//setting values for the order by and order type variables
	isset($_GET['orderBy']) ? $orderBy = $_GET['orderBy'] : $orderBy = "radacctid";
	isset($_GET['orderType']) ? $orderType = $_GET['orderType'] : $orderType = "asc";
	isset($_GET['username']) ? $username = trim($_GET['username']) : $username = "%";
	isset($_GET['billaction']) ? $billaction = trim($_GET['billaction']) : $billaction = "";
	isset($_GET['sqlfields']) ? $sqlfields = $_GET['sqlfields'] : $sqlfields = "";
	isset($_GET['startdate']) ? $startdate = $_GET['startdate'] : $startdate = "";
	isset($_GET['enddate']) ? $enddate = $_GET['enddate'] : $enddate = "";


	$username = str_replace('*', '%', $username);

	//feed the sidebar variables
	$billing_date_startdate = $startdate;
	$billing_date_enddate = $enddate;
	$billing_history_username = $username;
	$billing_history_billaction = $billaction;


	include_once('library/config_read.php');
    $logQuery = "performed query for all accounting records on page: ";

?>

<?php
	include("menu-bill-history.php");
?>

		<div id="contentnorightbar">
		
		<h2 id="Intro"><a href="#" onclick="javascript:toggleShowDiv('helpPage')"><?php echo t('Intro','billhistoryquery.php')?>
		<h144>&#x2754;</h144></a></h2>
				
		<div id="helpPage" style="display:none;visibility:visible" >
			<?php echo t('helpPage','billhistoryquery') ?>
			<br/>
		</div>
		<br/>



<?php

		include 'library/opendb.php';
		include 'include/management/pages_common.php';	
		include 'include/management/pages_numbering.php';		// must be included after opendb because it needs to read the CONFIG_IFACE_TABLES_LISTING variable from the config file

		// let's sanitize the values passed to us:
		$username = $dbSocket->escapeSimple($username);
		$billaction = $dbSocket->escapeSimple($billaction);
		$startdate = $dbSocket->escapeSimple($startdate);
		$enddate = $dbSocket->escapeSimple($enddate);

//	        include_once('include/management/userBilling.php');
//	        userBillingPayPalSummary($startdate, $enddate, $payer_email, $payment_address_status, $payer_status, $payment_status, 1);
									                         // draw the billing rates summary table


	        include 'library/opendb.php';
		// since we need to span through pages, which we do using GET queries I can't rely on this page
		// to be processed through POST but rather using GET only (with the current design anyway).
		// For this reason, I need to build the GET query which I will later use in the page number's links

		$getFields = "";
		$counter = 0;
		foreach ($sqlfields as $elements) {
			$getFields .= "&sqlfields[$counter]=$elements";
			$counter++;
		}

		// we should also sanitize the array that we will be passing to this page in the next query
		$getFields = $dbSocket->escapeSimple($getFields);


		$getQuery = "";
		$getQuery .= "&username=$username";
		$getQuery .= "&billAction=$billaction";
		$getQuery .= "&startdate=$startdate&enddate=$enddate";


		$select = implode(",", $sqlfields);
		// sanitizing the array passed to us in the get request
		$select = $dbSocket->escapeSimple($select);


		$sql = "SELECT $select FROM ".$configValues['CONFIG_DB_TBL_DALOBILLINGHISTORY']." WHERE ".
			" (username LIKE '$username') AND ".
			" (billAction LIKE '$billaction') ";
		$res = $dbSocket->query($sql);
		$numrows = $res->numRows();


		$sql = "SELECT $select FROM ".$configValues['CONFIG_DB_TBL_DALOBILLINGHISTORY']." WHERE ".
			" (username LIKE '$username') AND ".
			" (billAction LIKE '$billaction') ".
			" ORDER BY $orderBy $orderType LIMIT $offset, $rowsPerPage;";
		$res = $dbSocket->query($sql);
		$logDebugSQL = "";
		$logDebugSQL .= $sql . "\n";


	/* START - Related to pages_numbering.php */
	$maxPage = ceil($numrows/$rowsPerPage);
	/* END */


	echo "<table border='0' class='table1'>\n";
	echo "
					<thead>
							<tr>
							<th colspan='25'>".t('all','Records')."</th>
							</tr>

                                                        <tr>
                                                        <th colspan='25' align='left'>
                <br/>
        ";

        if ($configValues['CONFIG_IFACE_TABLES_LISTING_NUM'] == "yes")
                setupNumbering($numrows, $rowsPerPage, $pageNum, $orderBy, $orderType, $getFields, $getQuery);

        echo " </th></tr>
                                        </thead>

                        ";


	// building the dybamic table list fields
	echo "<thread> <tr>";
	foreach ($sqlfields as $value) {
		switch($value) {

		case "id":
			$title = t('all','ID');
			break;
		case "username":
			$title = t('all','Username');
			break;
		case "planId":
			$title = t('all','PlanId');
			break;
		case "billAmount":
			$title = t('all','BillAmount');
			break;
		case "billAction":
			$title = t('all','BillAction');
			break;
		case "billPerformer":
			$title = t('all','BillPerformer');
			break;
		case "billReason":
			$title = t('all','BillReason');
			break;
		case "paymentmethod":
			$title = t('ContactInfo','PaymentMethod');
			break;
		case "cash":
			$title = t('ContactInfo','Cash');
			break;
		case "creditcardname":
			$title = t('ContactInfo','CreditCardName');
			break;
		case "creditcardnumber":
			$title = t('ContactInfo','CreditCardNumber');
			break;
		case "creditcardverification":
			$title = t('ContactInfo','CreditCardVerificationNumber');
			break;
		case "creditcardtype":
			$title = t('ContactInfo','CreditCardType');
			break;
		case "creditcardexp":
			$title = t('ContactInfo','CreditCardExpiration');
			break;
		case "coupon":
			$title = t('all','Coupon');
			break;
		case "discount":
			$title = t('all','Discount');
			break;
		case "notes":
			$title = t('ContactInfo','Notes');
			break;
		case "creationdate":
			$title = t('all','CreationDate');
			break;
		case "creationby":
			$title = t('all','CreationBy');
			break;
		case "updatedate":
			$title = t('all','UpdateDate');
			break;
		case "updateby":
			$title = t('all','UpdateBy');
			break;
		default:
			$title = $value;
			break;
		}

		echo "<th scope='col'> $title   </th>";
	} //foreach $sqlfields
	echo "</tr> </thread>";


	// inserting the values of each field from the database to the table
	while($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
		echo "<tr>";
		foreach ($sqlfields as $value) {
			echo "<td> " . $row[$value] . "</td>";
		}
		echo "</tr>";
	}

        echo "
                                        <tfoot>
                                                        <tr>
                                                        <th colspan='25' align='left'>
        ";
        setupLinks($pageNum, $maxPage, $orderBy, $orderType, $getFields, $getQuery);
        echo "
                                                        </th>
                                                        </tr>
                                        </tfoot>
                ";

	echo "</table>";

	include 'library/closedb.php';



<?php
	include('include/config/logging.php');
?>

		</div>
		
		<div id="footer">
		
								<?php
        include 'page-footer.php';
?>

		
		</div>
		
</div>
</div>


</body>
</html>
    
    $help = t('helpPage','billhistorymain');
    echo '</div><!-- #contentnorightbar -->'
       . '<div id="footer">';
    include('page-footer.php');
    
    echo '</div><!-- #footer -->';

        </div>
    </div>

</body>
</html>
	
	//setting values for the order by and order type variables
	isset($_GET['orderBy']) ? $orderBy = $_GET['orderBy'] : $orderBy = "radacctid";
	isset($_GET['orderType']) ? $orderType = $_GET['orderType'] : $orderType = "asc";


	isset($_GET['payer_email']) ? $payer_email = $_GET['payer_email'] : $payer_email = "%";
	isset($_GET['payment_address_status']) ? $payment_address_status = $_GET['payment_address_status'] : $payment_address_status = "%";
	isset($_GET['payer_status']) ? $payer_status = $_GET['payer_status'] : $payer_status = "%";
	isset($_GET['payment_status']) ? $payment_status = $_GET['payment_status'] : $payment_status = "%";
	isset($_GET['vendor_type']) ? $vendor_type = $_GET['vendor_type'] : $vendor_type = "%";
	isset($_GET['sqlfields']) ? $sqlfields = $_GET['sqlfields'] : $sqlfields = "";
	isset($_GET['startdate']) ? $startdate = $_GET['startdate'] : $startdate = "";
	isset($_GET['enddate']) ? $enddate = $_GET['enddate'] : $enddate = "";


	$payer_email = str_replace('*', '%', $payer_email);
	//feed the sidebar variables
	//$billing_paypal_firstname = $value;
	$billing_paypal_payeremail = $payer_email;
	$billing_paypal_paymentaddressstatus = $payment_address_status;
	$billing_paypal_payerstatus = $payer_status;

	include_once('library/config_read.php');
    $log = "visited page: ";
    $logQuery = "performed query for all accounting records on page: ";

?>

<?php
?>

		<div id="contentnorightbar">
		
		<h2 id="Intro"><a href="#" onclick="javascript:toggleShowDiv('helpPage')"><?php echo t('Intro','billpaypaltransactions.php')?>
		<h144>&#x2754;</h144></a></h2>
				
		<div id="helpPage" style="display:none;visibility:visible" >
			<?php echo t('helpPage','billpaypaltransactions') ?>
			<br/>
		</div>
		<br/>



<?php

		include 'library/opendb.php';
		include 'include/management/pages_common.php';	
		include 'include/management/pages_numbering.php';		// must be included after opendb because it needs to read the CONFIG_IFACE_TABLES_LISTING variable from the config file

		// let's sanitize the values passed to us:
		$payer_email = $dbSocket->escapeSimple($payer_email);
		$payment_address_status = $dbSocket->escapeSimple($payment_address_status);
		$payer_status = $dbSocket->escapeSimple($payer_status);
		$payment_status = $dbSocket->escapeSimple($payment_status);
		$vendor_type = $dbSocket->escapeSimple($vendor_type);
		$startdate = $dbSocket->escapeSimple($startdate);
		$enddate = $dbSocket->escapeSimple($enddate);

	        include_once('include/management/userBilling.php');
	        userBillingPayPalSummary($startdate, $enddate, $payer_email, $payment_address_status, $payer_status, $payment_status, $vendor_type, 1);
									                         // draw the billing rates summary table


	        include 'library/opendb.php';
		// since we need to span through pages, which we do using GET queries I can't rely on this page
		// to be processed through POST but rather using GET only (with the current design anyway).
		// For this reason, I need to build the GET query which I will later use in the page number's links

		$getFields = "";
		$counter = 0;
		foreach ($sqlfields as $elements) {
			$getFields .= "&sqlfields[$counter]=$elements";
			$counter++;
		}

		// we should also sanitize the array that we will be passing to this page in the next query
		$getFields = $dbSocket->escapeSimple($getFields);


		$getQuery = "";
		$getQuery .= "&payer_email=$payer_email";
		$getQuery .= "&payment_address_status=$payment_address_status";
		$getQuery .= "&payer_status=$payer_status";
		$getQuery .= "&payment_status=$payment_status";
		$getQuery .= "&vendor_type=$vendor_type";
		$getQuery .= "&startdate=$startdate&enddate=$enddate";


		$select = implode(",", $sqlfields);
		// sanitizing the array passed to us in the get request
		$select = $dbSocket->escapeSimple($select);


		$sql = "SELECT $select FROM ".$configValues['CONFIG_DB_TBL_DALOBILLINGMERCHANT']." WHERE ".
			" (payer_email LIKE '$payer_email') AND ".
			" (payment_address_status LIKE '$payment_address_status') AND ".
			" (payer_status LIKE '$payer_status') AND ".
			" (payment_status LIKE '$payment_status') AND ".
			" (vendor_type LIKE '$vendor_type') AND ".
			" (payment_date>'$startdate' AND payment_date<'$enddate')";
		$res = $dbSocket->query($sql);
		$numrows = $res->numRows();


		$sql = "SELECT $select FROM ".$configValues['CONFIG_DB_TBL_DALOBILLINGMERCHANT']." WHERE ".
			" (payer_email LIKE '$payer_email') AND ".
			" (payment_address_status LIKE '$payment_address_status') AND ".
			" (payer_status LIKE '$payer_status') AND ".
			" (payment_status LIKE '$payment_status') AND ".
			" (vendor_type LIKE '$vendor_type') AND ".
			" (payment_date>'$startdate' AND payment_date<'$enddate') ".
			" ORDER BY $orderBy $orderType LIMIT $offset, $rowsPerPage;";
		$res = $dbSocket->query($sql);
		$logDebugSQL = "";
		$logDebugSQL .= $sql . "\n";


	/* START - Related to pages_numbering.php */
	$maxPage = ceil($numrows/$rowsPerPage);
	/* END */


	echo "<table border='0' class='table1'>\n";
	echo "
					<thead>
							<tr>
							<th colspan='25'>".t('all','Records')."</th>
							</tr>

                                                        <tr>
                                                        <th colspan='25' align='left'>
                <br/>
        ";

        if ($configValues['CONFIG_IFACE_TABLES_LISTING_NUM'] == "yes")
                setupNumbering($numrows, $rowsPerPage, $pageNum, $orderBy, $orderType, $getFields, $getQuery);

        echo " </th></tr>
                                        </thead>

                        ";


	// building the dybamic table list fields
	echo "<thread> <tr>";
	foreach ($sqlfields as $value) {
		switch($value) {

		case "id":
			$title = t('all','ID');
			break;
		case "username":
			$title = t('all','Username');
			break;
		case "password":
			$title = t('all','Password');
			break;
		case "txnId":
			$title = t('all','TxnId');
			break;
		case "planId":
			$title = t('all','PlanId');
			break;
		case "quantity":
			$title = t('all','Quantity');
			break;
		case "business_email":
			$title = t('all','ReceiverEmail');
			break;
		case "business_id":
			$title = t('all','Business');
			break;
		case "payment_tax":
			$title = t('all','Tax');
			break;
		case "payment_cost":
			$title = t('all','Cost');
			break;
		case "payment_fee":
			$title = t('all','TransactionFee');
			break;
		case "payment_total":
			$title = t('all','TotalCost');
			break;
		case "payment_currency":
			$title = t('all','PaymentCurrency');
			break;
		case "first_name":
			$title = t('all','FirstName');
			break;
		case "last_name":
			$title = t('all','LastName');
			break;
		case "payer_email":
			$title = t('all','PayerEmail');
			break;
		case "payer_address_name":
			$title = t('all','AddressRecipient');
			break;
		case "payer_address_street":
			$title = t('all','Street');
			break;
		case "payer_address_country":
			$title = t('all','Country');
			break;
		case "payer_address_country_code":
			$title = t('all','CountryCode');
			break;
		case "payer_address_city":
			$title = t('all','City');
			break;
		case "payer_address_state":
			$title = t('all','State');
			break;
		case "payer_address_zip":
			$title = t('all','Zip');
			break;
		case "payment_date":
			$title = t('all','PaymentDate');
			break;
		case "payment_status":
			$title = t('all','PaymentStatus');
			break;
		case "payer_status":
			$title = t('all','PayerStatus');
			break;
		case "vendor_type":
			$title = t('all','VendorType');
			break;
		case "payment_address_status":
			$title = t('all','PaymentAddressStatus');
			break;
		default:
			$title = $value;
			break;
		}

		echo "<th scope='col'> $title   </th>";
	} //foreach $sqlfields
	echo "</tr> </thread>";


	// inserting the values of each field from the database to the table
	while($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
		echo "<tr>";
		foreach ($sqlfields as $value) {
			echo "<td> " . $row[$value] . "</td>";
		}
		echo "</tr>";
	}

        echo "
                                        <tfoot>
                                                        <tr>
                                                        <th colspan='25' align='left'>
        ";
        setupLinks($pageNum, $maxPage, $orderBy, $orderType, $getFields, $getQuery);
        echo "
                                                        </th>
                                                        </tr>
                                        </tfoot>
                ";

	echo "</table>";

	include 'library/closedb.php';



<?php
	include('include/config/logging.php');
?>

		</div>
		
		<div id="footer">
		
								<?php
        include 'page-footer.php';
?>

		
		</div>
		
</div>
</div>


</body>
</html>
    
    include_once('library/config_read.php');
    
    // we import validation facilities
    include_once("library/validation.php");
    
    include_once("lang/main.php");
    
    include("library/layout.php");

    if (array_key_exists('PREV_LIST_PAGE', $_SESSION) && !empty(trim($_SESSION['PREV_LIST_PAGE']))) {
        echo '<div style="float: right; text-align: right; margin: 0; font-size: small">';
        printf('<a href="%s" title="Back to Previous Page">Back to Previous Page</a>', trim($_SESSION['PREV_LIST_PAGE']));
        echo '</div>';
        
        unset($_SESSION['PREV_LIST_PAGE']);
    }
    // we import validation facilities
    include_once("library/validation.php");

    include_once("lang/main.php");
    
    include("library/layout.php");
    // init loggin variables
    $log = "visited page: ";
    $logQuery = "performed query for listing of records on page: ";
    $logDebugSQL = "";

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


    $log = "visited page: ";
    
    include("library/layout.php");


    $log = "visited page: ";
    include_once("lang/main.php");
    include("library/layout.php");

<?php
 
    include("library/checklogin.php");
    
    

?>
                
        <div id="contentnorightbar">

<?php
?>

        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    $log = "visited page: ";

    include('page-footer.php');
?>
        </div><!-- #footer -->
    </div>
</div>
</body>
</html>
?>

        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    include('page-footer.php');
?>
        </div><!-- #footer -->
    </div>
</div>
</body>
</html>
<?php
    include("library/checklogin.php");
        

?>
        <div id="contentnorightbar">
<?php
?>

        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    include('page-footer.php');
?>
        </div><!-- #footer -->
    </div>
</div>
</body>
</html>
        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    include('include/config/logging.php');
    include('page-footer.php');
?>
        </div><!-- #footer -->
    </div>
</div>

</body>
</html>


    include ("library/checklogin.php");
    $operator = $_SESSION['operator_user'];
        
	include_once('library/config_read.php');
    $log = "visited page: ";

 * Description:
 *              returns user billing information (rates, plans, etc)
 * Authors:     Liran Tal <liran@enginx.com>


 * $userId 				   the userbillinfo user id or the username (autodetects)
	include(dirname(__FILE__).'/../../library/opendb.php');

	$user_id = false;

	// if provided a numeric user id then this is the user_id that we need
	if (is_numeric($userId)) {
		$user_id = $dbSocket->escapeSimple($userId);			// sanitize variable for sql statement
	} else {
		// otherwise this is the username and we need to look up the user id from the userbillinfo table

		$username = $dbSocket->escapeSimple($userId);
		$sql = 'SELECT id FROM '.$configValues['CONFIG_DB_TBL_DALOUSERBILLINFO'].
				' WHERE username="'.$username.'"';
		$res = $dbSocket->query($sql);
		$logDebugSQL .= $sql . "\n";

		$row = $res->fetchRow();
		$user_id = $row[0];

	}

	// if something is not right with the user id (set to null, false, whatever) we abort
	if (!$user_id)
		return false;
	$currDate = date('Y-m-d H:i:s');
	$currBy = $_SESSION['operator_user'];
	if (!$invoiceInfo)
		$invoiceInfo = array();
	// create default invoice information if nothing was provided
	$myinvoiceInfo['date'] = $currDate;
	$myinvoiceInfo['status_id'] = 1;			 // defaults to invoice status of 'open'
	$myinvoiceInfo['type_id'] = 1;			 // defaults to invoice type of 'Plans'
	$myinvoiceInfo['notes'] = 'provisioned new user from daloRADIUS platform';
	$invoiceInfo = array_merge($myinvoiceInfo, $invoiceInfo);
	$sql = "INSERT INTO ".$configValues['CONFIG_DB_TBL_DALOBILLINGINVOICE'].
			" (id, user_id, date, status_id, type_id, notes, creationdate, creationby, updatedate, updateby) ".
			" VALUES (0, '".$user_id."', '".
			$dbSocket->escapeSimple($invoiceInfo['date'])."', '".
			$dbSocket->escapeSimple($invoiceInfo['status_id'])."', '".
			$dbSocket->escapeSimple($invoiceInfo['type_id'])."', '".
			$dbSocket->escapeSimple($invoiceInfo['notes'])."', ".
			" '$currDate', '$currBy', NULL, NULL)";
	$res = $dbSocket->query($sql);
	$logDebugSQL .= $sql . "\n";
	// if there hasn't been any errors with inserting the invoice record
	if (!PEAR::isError($res)) {
		// get the added invoice id from the database
		$invoice_id = $dbSocket->getOne( "SELECT LAST_INSERT_ID() FROM `".$configValues['CONFIG_DB_TBL_DALOBILLINGINVOICE']."`" );
		if (!$invoice_id)
			return false;
		foreach($invoiceItems as $invoiceItem) {
			// set default information for the invoice items
			/*
			$myinvoiceItems['plan_id'] = '' ;
			$myinvoiceItems['amount'] = '' ;
			$myinvoiceItems['tax'] = '' ;
			$myinvoiceItems['notes'] = '' ;
			$invoiceItems = array_merge($myinvoiceItems, $invoiceItems);
			*/
			// now add an invoice item
			$sql = "INSERT INTO ".$configValues['CONFIG_DB_TBL_DALOBILLINGINVOICEITEMS'].
				" (id, invoice_id, plan_id, amount, tax_amount, notes, ".
				" creationdate, creationby, updatedate, updateby) ".
				" VALUES (0, '".$invoice_id."', '".
				$dbSocket->escapeSimple($invoiceItem['plan_id'])."', '".
				$dbSocket->escapeSimple($invoiceItem['amount'])."', '".
				$dbSocket->escapeSimple($invoiceItem['tax'])."', '".
				$dbSocket->escapeSimple($invoiceItem['notes'])."', ".
				" '$currDate', '$currBy', NULL, NULL)";
			$res = $dbSocket->query($sql);
			$logDebugSQL .= $sql . "\n";
		}
	}
	include(dirname(__FILE__).'/../../library/closedb.php');
	return true;



	include_once('include/management/pages_common.php');
	include 'library/opendb.php';

	$user_id = $dbSocket->escapeSimple($user_id);			// sanitize variable for sql statement

	$sql = "SELECT COUNT(distinct(a.id)) AS TotalInvoices, a.id, a.date, a.status_id, a.type_id, b.contactperson, b.username, ".
			" c.value AS status, COALESCE(SUM(e2.totalpayed), 0) as totalpayed, COALESCE(SUM(d2.totalbilled), 0) as totalbilled, ".
			" SUM(a.status_id = 1) as openInvoices ".
			" FROM ".$configValues['CONFIG_DB_TBL_DALOBILLINGINVOICE']." AS a".
			" INNER JOIN ".$configValues['CONFIG_DB_TBL_DALOUSERBILLINFO']." AS b ON (a.user_id = b.id) ".
			" INNER JOIN ".$configValues['CONFIG_DB_TBL_DALOBILLINGINVOICESTATUS']." AS c ON (a.status_id = c.id) ".
			" LEFT JOIN (SELECT SUM(d.amount + d.tax_amount) ".
					" as totalbilled, invoice_id FROM ".$configValues['CONFIG_DB_TBL_DALOBILLINGINVOICEITEMS']." AS d ".
			" GROUP BY d.invoice_id) AS d2 ON (d2.invoice_id = a.id) ".
			" LEFT JOIN (SELECT SUM(e.amount) as totalpayed, invoice_id FROM ".
			$configValues['CONFIG_DB_TBL_DALOPAYMENTS']." AS e GROUP BY e.invoice_id) AS e2 ON (e2.invoice_id = a.id) ".
			" WHERE (a.user_id = $user_id)".
			" GROUP BY b.id ";
	$res = $dbSocket->query($sql);
	$row = $res->fetchRow(DB_FETCHMODE_ASSOC);
	$totalInvoices = $row['TotalInvoices'];
	$totalBilled = $row['totalbilled'];
	$totalPayed = $row['totalpayed'];
	$openInvoices = $row['openInvoices'];
	include 'library/closedb.php';
	if ($drawTable == 1) {
		echo '
				<fieldset>
				<br/>
				<ul>
					<input class="button" type="button" value="New Invoice"
						onClick="javascript:window.location = \'bill-invoice-new.php?user_id='.$user_id.'\';" />
					<input class="button" type="button" value="Show Invoices"
						onClick="javascript:window.location = \'bill-invoice-list.php?user_id='.$user_id.'\';" />
					<input class="button" type="button" value="Show Payments"
						onClick="javascript:window.location = \'bill-payments-list.php?user_id='.$user_id.'\';" />
					<br/><br/>
					<li class="fieldset">
						<label for="totalInvoices" class="form">Total Invoices</label>
						<input type="text" value="'.$totalInvoices.'" disabled />
					</li>
					<li class="fieldset">
						<label for="totalbilled" class="form">Open Invoices</label>
						<input type="text" value="'.$openInvoices.'" disabled />
					</li>
					<br/>
					<li class="fieldset">
						<label for="totalbilled" class="form">Total Billed</label>
						<input type="text" value="'.$totalBilled.'" disabled />
					</li>
					<li class="fieldset">
						<label for="totalbilled" class="form">Total Payed</label>
						<input type="text" value="'.$totalPayed.'" disabled />
					</li>
					<li class="fieldset">
						<label for="totalbilled" class="form">Balance</label>
						<input type="text" value="'.($totalPayed - $totalBilled).'" disabled />
					</li>
					<li class="fieldset">
					<br/>
					<hr><br/>
					<input type="submit" name="submit" value="Apply" tabindex=10000 class="button" />
					</li>
			</ul>
			</fieldset>
			';
	}


















 * $startdate		starting date, first accounting session
 * $enddate		ending date, last accounting session
 * $ratename		the rate to use for calculations
	include_once('include/management/pages_common.php');
	include 'library/opendb.php';
	$username = $dbSocket->escapeSimple($username);			// sanitize variable for sql statement
	if ($res->numRows() == 0)
		return;
		" SUM(".$configValues['CONFIG_DB_TBL_RADACCT'].".AcctOutputOctets) AS AcctOutputOctets ".
	$res = $dbSocket->query($sql);
	$row = $res->fetchRow(DB_FETCHMODE_ASSOC);
	$rateCost = $row['rateCost'];
	$userUpload = toxbyte($row['AcctInputOctets']);
	$userDownload = toxbyte($row['AcctOutputOctets']);
	$userOnlineTime = time2str($row['AcctSessionTime']);
	$sessionTime = $row['AcctSessionTime'];
	$sumBilled = (($sessionTime/$rateDivisor)*$rateCost);
        		<thead>
        			<tr>
        	                <th colspan='10' align='left'>
        				<a class=\"table\" href=\"javascript:toggleShowDiv('divBillingRatesSummary')\">Billing Summary</a>
        	                </th>
        	                </tr>
        		</thead>
        		</table>
        	";
               		<table border='0' class='table1'>
        		<thread>
        		</div>
        	";
	}

 * $startdate		starting date, first accounting session
 * $enddate		ending date, last accounting session
function userBillingPayPalSummary($startdate, $enddate, $payer_email, $payment_address_status, $payer_status, $payment_status, $vendor_type, $drawTable) {

	include_once('include/management/pages_common.php');
	include 'library/opendb.php';

        $startdate = $dbSocket->escapeSimple($startdate);
        $enddate = $dbSocket->escapeSimple($enddate);
        $payer_email = $dbSocket->escapeSimple($payer_email);
        $payment_address_status = $dbSocket->escapeSimple($payment_address_status);
        $payer_status = $dbSocket->escapeSimple($payer_status);
        $payment_status = $dbSocket->escapeSimple($payment_status);

        $sql = "SELECT ".$configValues['CONFIG_DB_TBL_DALOBILLINGMERCHANT'].".Username AS Username, business_email, ".
        $configValues['CONFIG_DB_TBL_DALOBILLINGPLANS'].".planName, ".$configValues['CONFIG_DB_TBL_DALOBILLINGMERCHANT'].".planId, SUM(payment_total) AS total, SUM(payment_fee) ".
		" AS fee, SUM(payment_tax) AS tax, payment_currency, SUM(AcctSessionTime) AS AcctSessionTime, SUM(AcctInputOctets) AS AcctInputOctets, ".
		" SUM(AcctOutputOctets) AS AcctOutputOctets ".
		" FROM ".$configValues['CONFIG_DB_TBL_DALOBILLINGMERCHANT'].
		" LEFT JOIN ".$configValues['CONFIG_DB_TBL_RADACCT']." ON ".
		$configValues['CONFIG_DB_TBL_DALOBILLINGMERCHANT'].".Username=".$configValues['CONFIG_DB_TBL_RADACCT'].".Username ".
		" LEFT JOIN ".$configValues['CONFIG_DB_TBL_DALOBILLINGPLANS']." ON ".
		$configValues['CONFIG_DB_TBL_DALOBILLINGMERCHANT'].".planId=".$configValues['CONFIG_DB_TBL_DALOBILLINGPLANS'].".id ".
		" WHERE ".
	        " (business_email LIKE '$payer_email') AND ".
                " (payment_address_status LIKE '$payment_address_status') AND ".
                " (payer_status LIKE '$payer_status') AND ".
                " (payment_status LIKE '$payment_status') AND ".
                " (vendor_type LIKE '$vendor_type') AND ".
                " (payment_date>'$startdate' AND payment_date<'$enddate')".
		" GROUP BY Username";
        $res = $dbSocket->query($sql);

	if ($res->numRows() == 0)
		return;

	$row = $res->fetchRow(DB_FETCHMODE_ASSOC);

	$planTotalCost = $row['total'];
	$planTotalTax = $row['tax'];
	$planTotalFee = $row['fee'];
	$userUpload = toxbyte($row['AcctInputOctets']);
	$userDownload = toxbyte($row['AcctOutputOctets']);
	$userOnlineTime = time2str($row['AcctSessionTime']);
	$sessionTime = $row['AcctSessionTime'];
	$planCurrency = $row['payment_currency'];
	$planName = $row['planName'];
	$planId = $row['planId'];
	$payer_email = $row['business_email'];
	$username = $row['Username'];

	$grossGain = ($planTotalCost-($planTotalTax+$planTotalFee));

        include 'library/closedb.php';

        if ($drawTable == 1) {

                echo "<table border='0' class='table1'>";
                echo "
        		<thead>
        			<tr>
        	                <th colspan='10' align='left'>
        				<a class=\"table\" href=\"javascript:toggleShowDiv('divBillingPayPalSummary')\">Billing Summary</a>
        	                </th>
        	                </tr>
        		</thead>
        		</table>
        	";

                echo "
                        <div id='divBillingPayPalSummary' style='display:none;visibility:visible'>
               		<table border='0' class='table1'>
        		<thread>

                        <tr>
                        <th scope='col' align='right'>
                        Username
                        </th>

                        <th scope='col' align='left'>
                        $username (email: $payer_email)
                        </th>
                        </tr>

                        <tr>
                        <th scope='col' align='right'>
                        Billing for period of
                        </th>

                        <th scope='col' align='left'>
                        $startdate until $enddate (inclusive)
                        </th>
                        </tr>

                        <tr>
                        <th scope='col' align='right'>
                        Online Time
                        </th>

                        <th scope='col' align='left'>
                        $userOnlineTime
                        </th>
                        </tr>

                        <tr>
                        <th scope='col' align='right'>
                        User Upload
                        </th>

                        <th scope='col' align='left'>
                        $userUpload
                        </th>
                        </tr>


                        <tr>
                        <th scope='col' align='right'>
                        User Download
                        </th>

                        <th scope='col' align='left'>
                        $userDownload
                        </th>
                        </tr>


                        <tr>
                        <th scope='col' align='right'>
                        Plan name
                        </th>

                        <th scope='col' align='left'>
                        $planName (planId: $planId)
                        </th>
                        </tr>


                        <tr>
                        <th scope='col' align='right'>
                        Total Plans Cost <br/> Total Transaction Fees <br/> Total Transaction Taxs
                        </th>

                        <th scope='col' align='left'>
                        $planTotalCost <br/> $planTotalFee <br/> $planTotalTax
                        </th>
                        </tr>


                        <tr>
                        <th scope='col' align='right'>
                        Gross Gain
                        </th>

                        <th scope='col' align='left'>
                        $grossGain $planCurrency
                        </th>
                        </tr>

                        </table>

        		</div>
        	";
	}
                                    
    header("Location: /index.php");
    header("Location: /index.php");
$checkboxes = array(
                        "id" => t('all','ID'),
                        "username" => t('all','Username'),
                        "planId" => t('all','PlanId'),

                        "billAmount" => t('all','BillAmount'),
                        "billAction" => t('all','BillAction'),
                        "billPerformer" => t('all','BillPerformer'),
                        "billReason" => t('all','BillReason'),

                        "paymentmethod" => t('ContactInfo','PaymentMethod'),
                        "cash" => t('ContactInfo','Cash'),

                        "creditcardname" => t('ContactInfo','CreditCardName'),
                        "creditcardnumber" => t('ContactInfo','CreditCardNumber'),
                        "creditcardverification" => t('ContactInfo','CreditCardVerificationNumber'),
                        "creditcardtype" => t('ContactInfo','CreditCardType'),
                        "creditcardexp" => t('ContactInfo','CreditCardExpiration'),
                        "coupon" => t('all','Coupon'),
                        "discount" => t('all','Discount'),
                        "notes" => t('ContactInfo','Notes'),
                        "creationdate" => t('all','CreationDate'),
                        "creationby" => t('all','CreationBy'),
                        "updatedate" => t('all','UpdateDate'),
                        "updateby" => t('all','UpdateBy')
                    );

$checkboxes_checked = array(
                                "username",
                                "planId",
                                "billAmount",
                                "billAction",
                                "billPerformer",
                                "paymentmethod"
                           );


                            <h109><?= t('button','BetweenDates') ?></h109><br>
                            
                            <br><br>
                            <h109><?= t('all','Username') ?></h109><br>
                            <input name="username" type="text"
                                value="<?= (isset($billing_history_username)) ? $billing_history_username : "*" ?>">

                            <h109><?= t('all','BillAction') ?></h109><br>
                            <select name="billaction" size="1">
                                <option value="<?= (isset($billing_history_billaction)) ? $billing_history_billaction : "%" ?>">
                                    <?= (isset($billing_history_billaction)) ? $billing_history_billaction : "Any" ?>
                                </option>
            
                                <option value=""></option>
                                <option value="Refill Session Time">Refill Session Time</option>
                                <option value="Refill Session Traffic">Refill Session Traffic</option>
                            </select>
                                
                            <h109><?= t('button','AccountingFieldsinQuery') ?></h109><br>
                            foreach ($checkboxes as $value => $caption) {
                                $checked = in_array($value, $checkboxes_checked) ? ' checked' : '';
                                printf('<input type="checkbox" name="sqlfields[]" value="%s"%s><h109>%s</h109><br>', $value, $checked, $caption);
                            }

                            <br>Select:
                            <a class="table" href="javascript:SetChecked(1,'sqlfields[]','billhistory')">All</a>
                            <a class="table" href="javascript:SetChecked(0,'sqlfields[]','billhistory')">None</a>

            
                            <h109><?= t('button','OrderBy') ?><h109><br>         
                            <div style="text-align: center">
                                <select name="orderBy" size="1">
                                    <option value="id"> Id </option>
                                    <option value="username"> username </option>
                                    <option value="txnId"> txnId </option>
                                </select>
                                <select name="orderType" size="1">
                                    <option value="ASC"> Ascending </option>
                                    <option value="DESC"> Descending </option>
                                </select>
                            </div>

                            <br><br>
    header("Location: /index.php");
    
$checkboxes = array(
                        "id" => t('all','ID'),
                        "username" => t('all','Username'),
                        "password"  => t('all','Password'),
                        "txnId"  => t('all','TxnId'),
                        "planName" => t('all','PlanName'),
                        "planId"  => t('all','PlanId'),
                        "quantity"  => t('all','Quantity'),
                        "business_email"  => t('all','ReceiverEmail'),
                        "business_id"  => t('all','Business'),
                        "payment_tax" => t('all','Tax'),
                        "payment_cost"  => t('all','Cost'),
                        "payment_fee" => t('all','TransactionFee'),
                        "payment_total" => t('all','TotalCost'),
                        "payment_currency" => t('all','PaymentCurrency'),
                        "first_name" => t('all','FirstName'),
                        "last_name" => t('all','LastName'),
                        "payer_email" => t('all','PayerEmail'),
                        "payer_address_name"  => t('all','AddressRecipient'),
                        "payer_address_street"  => t('all','Street'),
                        "payer_address_country" => t('all','Country'),
                        "payer_address_country_code"  => t('all','CountryCode'),
                        "payer_address_city" => t('all','City'),
                        "payer_address_state" => t('all','State'),
                        "payer_address_zip"  => t('all','Zip'),
                        "payment_date" => t('all','PaymentDate'),
                        "payment_status" => t('all','PaymentStatus'),
                        "payer_status" => t('all','PayerStatus'),
                        "payment_address_status" => t('all','PaymentAddressStatus'),
                        "vendor_type" => t('all','VendorType')
                   );
$checkboxes_checked = array(
                            "username",
                            "planName",
                            "payment_fee",
                            "payment_total",
                            "payment_currency",
                            "first_name",
                            "last_name",
                            "payer_email",
                            "payer_address_country",
                            "payer_address_city",
                            "payer_address_state",
                            "payment_date",
                            "payment_status",
                            "vendor_type"
                           );
                                    value="<?= (isset($billing_date_startdate)) ? $billing_date_startdate : date("Y-m-01") ?>">
                                <input name="enddate" type="text" id="enddate" tooltipText="<?= t('Tooltip','Date') ?>"
                                    value="<?= (isset($billing_date_enddate)) ? $billing_date_enddate : date("Y-m-t") ?>">

                                <br><br>

                                <h109><?= t('all','VendorType'); ?></h109><br>
                                <select name="vendor_type" size="1">
                                    <option value="<?= (isset($billing_paypal_vendor_type)) ? $billing_paypal_vendor_type : "%" ?>">
                                        <?= (isset($billing_paypal_vendor_type)) ? $billing_paypal_vendor_type : "Any" ?>
                                    </option>
                                    <option value=""></option>
                                    <option value="%">Any</option>
                                    <option value="PayPal">PayPal</option>
                                    <option value="2Checkout">2Checkout</option>
                                </select>
                                
                                <h109><?= t('all','PayerEmail'); ?></h109><br>
                                <input name="payer_email" type="text"
                                    value="<?= (isset($billing_paypal_payeremail)) ? $billing_paypal_payeremail : "*" ?>">
			
                                <br><br>

                                <h109><?= t('all','PaymentStatus'); ?></h109><br>
                                <select name="payment_status" size="1">
                                    <option value="<?= (isset($billing_paypal_paymentstatus)) ? $billing_paypal_paymentstatus : "%" ?>">
                                        <?= (isset($billing_paypal_paymentstatus)) ? $billing_paypal_paymentstatus : "Any" ?>
                                    </option>
                                    <option value=""></option>
                                    <option value="Completed">Completed</option>
                                    <option value="Denied">Denied</option>
                                    <option value="Expired">Expired</option>
                                    <option value="Failed">Failed</option>
                                    <option value="In-Progress">In-Progress</option>
                                    <option value="Pending">Pending</option>
                                    <option value="Processed">Processed</option>
                                    <option value="Refunded">Refunded</option>
                                    <option value="Reversed">Reversed</option>
                                    <option value="Canceled-Reversal">Canceled-Reversal</option>
                                    <option value="Voided">Voided</option>
                                </select>

                                <h109><?= t('button','AccountingFieldsinQuery'); ?></h109><br>
                                foreach ($checkboxes as $value => $caption) {
                                    $checked = in_array($value, $checkboxes_checked) ? ' checked' : '';
                                    printf('<input type="checkbox" name="sqlfields[]" value="%s"%s><h109>%s</h109><br>',
                                           $value, $checked, $caption);
                                }
                                <br><h109>Select:</h109>
                                <a class="table" href="javascript:SetChecked(1,'sqlfields[]','billpaypaltransactions')">All</a>
                                <a class="table" href="javascript:SetChecked(0,'sqlfields[]','billpaypaltransactions')">None</a>

                                
                                <h109><?= t('button','OrderBy') ?></h109><br>
                                
                                <div style="text-align: center">
                                    <select name="orderBy" size="1">
                                        <option value="id"> Id </option>
                                        <option value="username"> username </option>
                                        <option value="txnId"> txnId </option>
                                    </select>

                                    <select name="orderType" size="1">
                                        <option value="ASC"> Ascending </option>
                                        <option value="DESC"> Descending </option>
                                    </select>
                                </div>
    // set session's page variable
    $_SESSION['PREV_LIST_PAGE'] = $_SERVER['REQUEST_URI'];

    // we import validation facilities
    include_once("library/validation.php");

    include_once("lang/main.php");
    
    include("library/layout.php");
    // we import validation facilities
    include_once("library/validation.php");
    include_once("lang/main.php");
    include("library/layout.php");

    // we import validation facilities
    include_once("library/validation.php");
    include_once("lang/main.php");
    
    include("library/layout.php");
    include_once("lang/main.php");
    
    include("library/layout.php");
        $count = 1;
            $li_style = 'margin: 7px auto';
?>
                
        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    include('page-footer.php');
?>
        </div><!-- #footer -->
    </div>
</div>
<script>
    var tooltipObj = new DHTMLgoodies_formTooltip();
    tooltipObj.setTooltipPosition('right');
    tooltipObj.setPageBgColor('#EEEEEE');
    tooltipObj.setTooltipCornerSize(15);
    tooltipObj.initFormFieldTooltip();
</script>
</body>
</html>
    // we import validation facilities
    include_once("library/validation.php");
    include("include/management/functions.php");
    
    include_once('include/management/populate_selectbox.php');
    $valid_groups = get_groups();
    $valid_planNames = get_plans();
    include_once("lang/main.php");
    include("library/layout.php");
    $sql0 = sprintf("SELECT COUNT(DISTINCT(username)) AS username
                       FROM %s
                      WHERE attribute='Auth-Type' OR attribute LIKE '%%-Password'", $configValues['CONFIG_DB_TBL_RADCHECK']);
        // with this second query we retrieve user status (enabled/disabled) and user groups list
        $sql2 = sprintf("SELECT username, groupname FROM %s WHERE username IN (%s)",
                        $configValues['CONFIG_DB_TBL_RADUSERGROUP'], implode(", ", $usernamelist));
        $res = $dbSocket->query($sql2);
        $logDebugSQL .= "$sql2;\n";
        // foreach user we update the enabled flag and the grouplist
        while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
            $this_username = $row['username'];
            $this_groupname = $row['groupname'];
            if ($this_groupname === 'daloRADIUS-Disabled-Users') {
                $records[$this_username]['enabled'] = false;
            } else {
                array_push($records[$this_username]['groups'],
                           htmlspecialchars($this_groupname, ENT_QUOTES, 'UTF-8'));
                <td><?= ($type == 'USER') ? $auth : "" ?></td>
    // we import validation facilities
    include_once("library/validation.php");
    include("include/management/functions.php");
    
    include_once("lang/main.php");
    
    include("library/layout.php");
    // we import validation facilities
    include_once("library/validation.php");
    include("include/management/functions.php");
    include_once("lang/main.php");
    include("library/layout.php");

    isset($_REQUEST['vendor']) ? $vendor = $_REQUEST['vendor'] : $vendor = "";
    isset($_REQUEST['attribute']) ? $attribute = $_REQUEST['attribute'] : $attribute = "";

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

        isset($_POST['vendor']) ? $vendor = $_POST['vendor'] : $vendor = "";
        isset($_POST['attributeOld']) ? $attributeOld = $_POST['attributeOld'] : $attributeOld = "";
        isset($_POST['attribute']) ? $attribute = $_POST['attribute'] : $attribute = "";
        isset($_POST['type']) ? $type = $_POST['type'] : $type = "";
        isset($_POST['RecommendedOP']) ? $RecommendedOP = $_POST['RecommendedOP'] : $RecommendedOP = "";
        isset($_POST['RecommendedTable']) ? $RecommendedTable = $_POST['RecommendedTable'] : $RecommendedTable = "";
        isset($_POST['RecommendedTooltip']) ? $RecommendedTooltip = $_POST['RecommendedTooltip'] : $RecommendedTooltip = "";
        isset($_POST['RecommendedHelper']) ? $RecommendedHelper = $_POST['RecommendedHelper'] : $RecommendedHelper = "";
        include 'library/opendb.php';
        $sql = "SELECT * FROM ".$configValues['CONFIG_DB_TBL_DALODICTIONARY']." WHERE vendor='".$dbSocket->escapeSimple($vendor).
            "' AND attribute='".$dbSocket->escapeSimple($attribute)."'";
        $logDebugSQL .= $sql . "\n";

        if ($res->numRows() == 1) {
            if (trim($vendor) != "" and trim($attribute) != "") {
                // update vendor/attribute pairs to database
                $sql = "UPDATE ".$configValues['CONFIG_DB_TBL_DALODICTIONARY']." SET 
                    type='".
                    $dbSocket->escapeSimple($type)."', attribute='".$dbSocket->escapeSimple($attribute).
                    "', RecommendedOP='".$dbSocket->escapeSimple($RecommendedOP).
                    "', RecommendedTable='".$dbSocket->escapeSimple($RecommendedTable).
                    "', RecommendedTooltip='".$dbSocket->escapeSimple($RecommendedTooltip).
                    "', RecommendedHelper='".$dbSocket->escapeSimple($RecommendedHelper).
                    "' WHERE Vendor='$vendor' AND Attribute='$attributeOld'";
                $res = $dbSocket->query($sql);
                $logDebugSQL .= $sql . "\n";

                $successMsg = "Updated database with vendor attribute: <b>$attribute</b> of vendor: <b>$vendor</b>";
                $logAction .= "Successfully update vendor [$vendor] and attribute [$attribute] on page: ";
                $failureMsg = "you must provide atleast a vendor name and attribute";    
                $logAction .= "Failed updating vendor [$vendor] and attribute [$attribute] on page: ";
        } else { 
            $failureMsg = "You have tried to update a vendor's attribute that either is not present in the database or there
                    may be more than 1 entry for this vendor attribute in database (attribute :$attribute)";
            $logAction .= "Failed updating vendor attribute already in database [$attribute] on page: ";        
    
        include 'library/closedb.php';

    include 'library/opendb.php';

    $sql = "SELECT * FROM ".$configValues['CONFIG_DB_TBL_DALODICTIONARY']." WHERE vendor='".$dbSocket->escapeSimple($vendor).
        "' AND attribute='".$dbSocket->escapeSimple($attribute)."'";
    $res = $dbSocket->query($sql);
    $logDebugSQL .= $sql . "\n";

    $row = $res->fetchRow(DB_FETCHMODE_ASSOC);

    isset($row['Attribute']) ? $attribute = $row['Attribute'] : $attribute = "";
    isset($row['Type']) ? $type = $row['Type'] : $type = "";
    isset($row['Vendor']) ? $vendor = $row['Vendor'] : $vendor = "";
    isset($row['RecommendedOP']) ? $RecommendedOP = $row['RecommendedOP'] : $RecommendedOP = "";
    isset($row['RecommendedTable']) ? $RecommendedTable = $row['RecommendedTable'] : $RecommendedTable = "";
    isset($row['RecommendedTooltip']) ? $RecommendedTooltip = $row['RecommendedTooltip'] : $RecommendedTooltip = "";
    isset($row['RecommendedHelper']) ? $RecommendedHelper = $row['RecommendedHelper'] : $RecommendedHelper = "";

    include 'library/closedb.php';

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

    include_once('include/management/actionMessages.php');
?>
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

    <fieldset>

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

        <ul>

        <input type='hidden' name='vendor' value='<?php if (isset($vendor)) echo $vendor ?>' />

        <li class='fieldset'>
        <label for='vendor' class='form'><?php echo t('all','VendorName') ?></label>
        <input disabled name='vendor' type='text' id='vendor' value='<?php if (isset($vendor)) echo $vendor ?>' tabindex=100 />
        <img src='images/icons/comment.png' alt='Tip' border='0' onClick="javascript:toggleShowDiv('vendorNameTooltip')" />
        
        <div id='vendorNameTooltip'  style='display:none;visibility:visible' class='ToolTip'>
            <img src='images/icons/comment.png' alt='Tip' border='0' />
            <?php echo t('Tooltip','vendorNameTooltip') ?>
        </div>
        </li>

        <input type='hidden' name='attributeOld' value='<?php if (isset($attribute)) echo $attribute ?>' />

        <li class='fieldset'>
        <label for='attribute' class='form'><?php echo t('all','Attribute') ?></label>
        <input name='attribute' type='text' id='attribute' value='<?php if (isset($attribute)) echo $attribute ?>' tabindex=101 />
        <img src='images/icons/comment.png' alt='Tip' border='0' onClick="javascript:toggleShowDiv('attributeTooltip')" />
        
        <div id='attributeTooltip'  style='display:none;visibility:visible' class='ToolTip'>
            <img src='images/icons/comment.png' alt='Tip' border='0' />
            <?php echo t('Tooltip','attributeTooltip') ?>
        </div>
        </li>

        <li class='fieldset'>
        <label for='type' class='form'><?php echo t('all','Type') ?></label>
        <select name='type' type='text' id='type' class='form' tabindex=102 />
        <option value='<?php echo $type; ?>'><?php echo $type; ?></option>
        <?php
            include_once('include/management/populate_selectbox.php');
            drawTypes();
        ?>
        </select>
        <img src='images/icons/comment.png' alt='Tip' border='0' onClick="javascript:toggleShowDiv('typeTooltip')" />
        
        <div id='typeTooltip'  style='display:none;visibility:visible' class='ToolTip'>
            <img src='images/icons/comment.png' alt='Tip' border='0' />
            <?php echo t('Tooltip','typeTooltip') ?>
        </div>
        </li>

        <li class='fieldset'>
        <label for='RecommendedOP' class='form'><?php echo t('all','RecommendedOP') ?></label>
        <select name='RecommendedOP' type='text' id='RecommendedOP' class='form' tabindex=103 />
        <option value='<?php echo $RecommendedOP; ?>'><?php echo $RecommendedOP; ?></option>
        <?php
            include_once('include/management/populate_selectbox.php');
            drawOptions();
        ?>
        </select>
        <img src='images/icons/comment.png' alt='Tip' border='0' onClick="javascript:toggleShowDiv('RecommendedOPTooltip')" />
        
        <div id='RecommendedOPTooltip'  style='display:none;visibility:visible' class='ToolTip'>
            <img src='images/icons/comment.png' alt='Tip' border='0' />
            <?php echo t('Tooltip','RecommendedOPTooltip') ?>
        </div>
        </li>

        <li class='fieldset'>
        <label for='RecommendedTable' class='form'><?php echo t('all','RecommendedTable') ?></label>
        <select name='RecommendedTable' type='text' id='RecommendedTable' class='form' tabindex=104 />
        <option value='<?php echo $RecommendedTable; ?>'><?php echo $RecommendedTable; ?></option>
        <?php
            include_once('include/management/populate_selectbox.php');
            drawTables();
        ?>
        </select>
        <img src='images/icons/comment.png' alt='Tip' border='0' onClick="javascript:toggleShowDiv('RecommendedTableTooltip')" />
        
        <div id='RecommendedTableTooltip'  style='display:none;visibility:visible' class='ToolTip'>
            <img src='images/icons/comment.png' alt='Tip' border='0' />
            <?php echo t('Tooltip','RecommendedTableTooltip') ?>
        </div>
        </li>

        <li class='fieldset'>
        <label for='RecommendedTooltip' class='form'><?php echo t('all','RecommendedTooltip') ?></label>
        <textarea class='form' name='RecommendedTooltip' type='text' id='RecommendedTooltip' tabindex=105 /><?php if (isset($RecommendedTooltip)) echo $RecommendedTooltip ?></textarea>
        <img src='images/icons/comment.png' alt='Tip' border='0' onClick="javascript:toggleShowDiv('RecommendedTooltipTooltip')" />
        
        <div id='RecommendedTooltipTooltip'  style='display:none;visibility:visible' class='ToolTip'>
            <img src='images/icons/comment.png' alt='Tip' border='0' />
            <?php echo t('Tooltip','RecommendedTooltipTooltip') ?>
        </div>
        </li>


        <li class='fieldset'>
        <label for='RecommendedHelper' class='form'><?php echo t('all','RecommendedHelper') ?></label>
        <select name='RecommendedHelper' type='text' id='RecommendedHelper' class='form' tabindex=104 />
        <option value='<?php echo $RecommendedHelper; ?>'><?php echo $RecommendedHelper; ?></option>
        <?php
            include_once('include/management/populate_selectbox.php');
            drawRecommendedHelper();
        ?>
        </select>
        <img src='images/icons/comment.png' alt='Tip' border='0' onClick="javascript:toggleShowDiv('RecommendedHelperTooltip')" />
        
        <div id='RecommendedHelperTooltip'  style='display:none;visibility:visible' class='ToolTip'>
            <img src='images/icons/comment.png' alt='Tip' border='0' />
            <?php echo t('Tooltip','RecommendedHelperTooltip') ?>
        </div>
        </li>
    
        <li class='fieldset'>
        <br/>
        <hr><br/>
        <input type='submit' name='submit' value='<?php echo t('buttons','apply') ?>' tabindex=10000 class='button' />
        </li>
        </ul>
    </fieldset>
    </form>
<?php
    if (isset($_POST["submit"])) {

        isset($_POST['vendor']) ? $vendor = $_POST['vendor'] : $vendor = "";
        isset($_POST['attribute']) ? $attribute = $_POST['attribute'] : $attribute = "";
        isset($_POST['type']) ? $type = $_POST['type'] : $type = "";
        isset($_POST['RecommendedOP']) ? $RecommendedOP = $_POST['RecommendedOP'] : $RecommendedOP = "";
        isset($_POST['RecommendedTable']) ? $RecommendedTable = $_POST['RecommendedTable'] : $RecommendedTable = "";
        isset($_POST['RecommendedTooltip']) ? $RecommendedTooltip = $_POST['RecommendedTooltip'] : $RecommendedTooltip = "";

        include 'library/opendb.php';

        $sql = "SELECT * FROM ".$configValues['CONFIG_DB_TBL_DALODICTIONARY']." WHERE vendor='".$dbSocket->escapeSimple($vendor).
            "' AND attribute='".$dbSocket->escapeSimple($attribute)."'";
        $res = $dbSocket->query($sql);
        $logDebugSQL .= $sql . "\n";

        if ($res->numRows() == 0) {
            if (trim($vendor) != "" and trim($attribute) != "") {
                // insert vendor/attribute pairs to database
                $sql = "INSERT INTO ".$configValues['CONFIG_DB_TBL_DALODICTIONARY'].
                    " (id, type, attribute, vendor, RecommendedOP, RecommendedTable, RecommendedTooltip) VALUES (0, '".
                    $dbSocket->escapeSimple($type)."', '".$dbSocket->escapeSimple($attribute)."','".
                    $dbSocket->escapeSimple($vendor)."','".    $dbSocket->escapeSimple($RecommendedOP)."','".
                    $dbSocket->escapeSimple($RecommendedTable)."','".$dbSocket->escapeSimple($RecommendedTooltip)."')";
                $res = $dbSocket->query($sql);
                $logDebugSQL .= $sql . "\n";
                $successMsg = "Added to database new vendor attribute: <b>$attribute</b> of vendor: <b>$vendor</b>";
                $logAction .= "Successfully added new vendor [$vendor] and attribute [$attribute] on page: ";
                $failureMsg = "You must provide atleast a vendor name and attribute";    
                $logAction .= "Failed adding new vendor [$vendor] and attribute [$attribute] on page: ";
        } else { 
            $failureMsg = "You have tried to add a vendor's attribute that already exist in the database: $attribute";
            $logAction .= "Failed adding new vendor attribute already in database [$attribute] on page: ";        
    
        include 'library/closedb.php';



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

?>

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

        <h302> <?php echo t('title','VendorAttribute'); ?> </h302>
        <br/>
        <ul>
        <li class='fieldset'>
        <label for='vendor' class='form'><?php echo t('all','VendorName') ?></label>
        <input name='vendor' type='text' id='vendor' value='' tabindex=100 />
        <img src='images/icons/comment.png' alt='Tip' border='0' onClick="javascript:toggleShowDiv('vendorNameTooltip')" />
        <div id='vendorNameTooltip'  style='display:none;visibility:visible' class='ToolTip'>
            <img src='images/icons/comment.png' alt='Tip' border='0' />
            <?php echo t('Tooltip','vendorNameTooltip') ?>
        </div>
        </li>

        <li class='fieldset'>
        <label for='attribute' class='form'><?php echo t('all','Attribute') ?></label>
        <input name='attribute' type='text' id='attribute' value='' tabindex=101 />
        <img src='images/icons/comment.png' alt='Tip' border='0' onClick="javascript:toggleShowDiv('attributeTooltip')" />

        <div id='attributeTooltip'  style='display:none;visibility:visible' class='ToolTip'>
            <img src='images/icons/comment.png' alt='Tip' border='0' />
            <?php echo t('Tooltip','attributeTooltip') ?>
        </div>
        </li>

        <li class='fieldset'>
        <label for='type' class='form'><?php echo t('all','Type') ?></label>
        <select name='type' type='text' id='type' class='form' tabindex=102 />
            <option value=''>Select Type...</option>
        <?php
            include_once('include/management/populate_selectbox.php');
            drawTypes();
        ?>
        </select>
        <img src='images/icons/comment.png' alt='Tip' border='0' onClick="javascript:toggleShowDiv('typeTooltip')" />
        <div id='typeTooltip'  style='display:none;visibility:visible' class='ToolTip'>
            <img src='images/icons/comment.png' alt='Tip' border='0' />
            <?php echo t('Tooltip','typeTooltip') ?>
        </div>
        </li>

        <li class='fieldset'>
        <label for='RecommendedOP' class='form'><?php echo t('all','RecommendedOP') ?></label>
        <select name='RecommendedOP' id='RecommendedOP' class='form' tabindex=103 />
            <option value=''>Select OP...</option>
        <?php
            include_once('include/management/populate_selectbox.php');
            drawOptions();
        ?>
        </select>
        <img src='images/icons/comment.png' alt='Tip' border='0' onClick="javascript:toggleShowDiv('RecommendedOPTooltip')" />
        <div id='RecommendedOPTooltip'  style='display:none;visibility:visible' class='ToolTip'>
            <img src='images/icons/comment.png' alt='Tip' border='0' />
            <?php echo t('Tooltip','RecommendedOPTooltip') ?>
        </div>
        </li>

        <li class='fieldset'>
        <label for='RecommendedTable' class='form'><?php echo t('all','RecommendedTable') ?></label>
                <select name='RecommendedTable' id='RecommendedTable' class='form' tabindex=104 />
        <option value=''>Select Table...</option>
        <?php
            include_once('include/management/populate_selectbox.php');
            drawTables();
        ?>
        </select>
        <img src='images/icons/comment.png' alt='Tip' border='0' onClick="javascript:toggleShowDiv('RecommendedTableTooltip')" />
        <div id='RecommendedTableTooltip'  style='display:none;visibility:visible' class='ToolTip'>
            <img src='images/icons/comment.png' alt='Tip' border='0' />
            <?php echo t('Tooltip','RecommendedTableTooltip') ?>
        </div>
        </li>

        <li class='fieldset'>
        <label for='RecommendedTooltip' class='form'><?php echo t('all','RecommendedTooltip') ?></label>
        <textarea class='form' name='RecommendedTooltip' type='text' id='RecommendedTooltip' tabindex=105 /></textarea>
        <img src='images/icons/comment.png' alt='Tip' border='0' onClick="javascript:toggleShowDiv('RecommendedTooltipTooltip')" />
        <div id='RecommendedTooltipTooltip'  style='display:none;visibility:visible' class='ToolTip'>
            <img src='images/icons/comment.png' alt='Tip' border='0' />
            <?php echo t('Tooltip','RecommendedTooltipTooltip') ?>
        </div>
        </li>

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

        </ul>
    </fieldset>

    </form>

<?php
    // get vendor name passed to us from menu-mng-rad-attributes.php
    $attribute = (array_key_exists('attribute', $_GET) && isset($_GET['attribute']))
            ? str_replace("%", "", $_GET['attribute']) : "";
    if (!empty($vendor)) {
    // we import validation facilities
    include_once("library/validation.php");
    include_once("lang/main.php");
    
    include("library/layout.php");

    // we import validation facilities
    include_once("library/validation.php");
    include_once("lang/main.php");
    
    include("library/layout.php");

    include_once('library/config_read.php');
    
    
    // we import validation facilities
    include_once("library/validation.php");
    include("library/layout.php");
    // we import validation facilities
    include_once("library/validation.php");
    include_once("lang/main.php");
    
    include("library/layout.php");
    // we import validation facilities
    include_once("library/validation.php");
    
    include_once("lang/main.php");
    
    include("library/layout.php");
        $counter = 1;
            echo '<tr>';
            $sql1 = sprintf("SELECT groupname, priority FROM %s WHERE username='%s' ORDER BY priority DESC, groupname ASC",
    
    // print HTML prologue
    $extra_js = array(
        "library/javascript/ajax.js",
        "library/javascript/ajaxGeneric.js"
    );
    
    $title = t('Intro','mngsearch.php');
    
    print_html_prologue($title, $langCode, array(), $extra_js);

    $username = (array_key_exists('username', $_GET) && isset($_GET['username']))
              ? str_replace("%", "", $_GET['username']) : "";
    
?>
    <div id="contentnorightbar">

<?php
    
?>
                <div id="contentnorightbar">
<?php
    include_once("include/management/actionMessages.php");
?>
                </div><!-- #contentnorightbar -->
                        
                <div id="footer">
<?php
    include('page-footer.php');
?>
                </div><!-- #footer -->
            </div>
        </div>
    </body>
</html>
<?php
    include("library/checklogin.php");
        
    
    // print HTML prologue   
    $log = "visited page: ";
?>
        <div id="contentnorightbar">
            <h2 id="Intro">
                <a href="#" onclick="javascript:toggleShowDiv('helpPage')">
                    <?= t('Intro','repbatch.php'); ?><h144>&#x2754;</h144>
                </a>
            </h2>

            <div id="helpPage" style="display:none;visibility:visible"><?= t('helpPage','repbatch') ?><br></div>
            <br>
<?php
?>
        </div><!-- #contentnorightbar -->
        
        <div id="footer">
        
<?php
    include('page-footer.php');

        
        </div><!-- #footer -->
    </div>
</div>


</body>
</html>
<?php
    include("library/checklogin.php");
        

?>
        <div id="contentnorightbar">
<?php
?>

        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    include('page-footer.php');
?>
        </div><!-- #footer -->
    </div>
</div>
</body>
</html>
    
    include("library/validation.php");
    
    include_once('library/config_read.php');
    $log = "visited page: ";

    include_once("lang/main.php");
    
    include("library/layout.php");
      
?>    
    <div id="contentnorightbar">
<?php
?>
         </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    include('page-footer.php');
?>
        </div><!-- #footer -->
    </div>
</div>

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

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

?>
    <div id="contentnorightbar">
<?php
?>
        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    include('page-footer.php');
?>
        </div><!-- #footer -->
    </div>
</div>
</body>
</html>
    include_once('library/config_read.php');
    $log = "visited page: ";

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

?>    
        <div id="contentnorightbar">
<?php
?>
        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    include('page-footer.php');
?>
        </div><!-- #footer -->
    </div>
</div>
</body>
</html>
    include_once("lang/main.php");
    
?>
        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    include('page-footer.php');
?>
        </div><!-- #footer -->
    </div>
</div>
</body>
</html>
<?php
    include("library/checklogin.php");
    //~ include('library/check_operator_perm.php');
    
    
    
    include("menu-reports.php");
?>
        
        <div id="contentnorightbar">
<?php
?>
        
        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    $log = "visited page: ";

    include('page-footer.php');
?>
        </div><!-- #footer -->
    </div>
</div>
</body>
</html>
    include_once("lang/main.php");
    
    include("library/layout.php");

    
?>    
        <div id="contentnorightbar">
<?php
?>

        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    include('page-footer.php');
?>
        </div><!-- #footer -->
    </div>
</div>
</body>
</html>

    include('include/config/logging.php');

    include_once("lang/main.php");
?>    
        <div id="contentnorightbar">

<?php
?>
        </div><!-- #contentnorightbar -->
        
        <div id="footer">        
<?php
        include('page-footer.php');

        </div><!-- #footer -->
    </div>
</div>


</body>
</html>

    include('include/config/logging.php');

    include_once("lang/main.php");
      
?>
        <div id="contentnorightbar">
<?php
?>
        </div>
        
        <div id="footer">
<?php
    include('page-footer.php');
?>
        </div>
        
    </div>
</div>
</body>
</html>
<?php
*
 * Authors:	Liran Tal <liran@enginx.com>
    include("library/checklogin.php");
        
	include_once('library/config_read.php');
    
    

?>
		<div id="contentnorightbar">
<?php
		
        </div><!-- #contentnorightbar -->
        
        <div id="footer">
<?php
    include_once('include/config/logging.php');
    include('page-footer.php');
?>

        </div><!-- #footer -->
    </div>
</div>

</body>
</html>
    include_once("lang/main.php");
    
    include("library/layout.php");
    $username = (array_key_exists('username', $_GET) && isset($_GET['username']))
                    ? str_replace("%", "", $_GET['username']) : "";
    $logQuery = "performed query for [$username";
    if (!empty($limit)) {
        $logQuery .= " : $limit";
    $logQuery .= "] on page: ";

    include_once('library/config_read.php');
    
    include("library/validation.php");
    include_once("lang/main.php");
    include("library/layout.php");


Fixed code:
    include_once("lang/main.php");
    include("library/layout.php");
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    include_once('library/config_read.php');

    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
        $count = 0;
            printf('<tr id="row-%d">', $count);
            echo '</tr>';
            $count++;
    include("library/validation.php");
    include_once("lang/main.php");
    include("library/layout.php");
    include_once("lang/main.php");
    include("library/layout.php");
    // print HTML prologue

    include_once("lang/main.php");
    include("library/layout.php");
    // print HTML prologue
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");

    $username = (array_key_exists('username', $_GET) && !empty(str_replace("%", "", trim($_GET['username']))))
              ? str_replace("%", "", trim($_GET['username'])) : "";
<?php 
 * Authors:    Liran Tal <liran@enginx.com>
 *             Filippo Lauria <filippo.lauria@iit.cnr.it>
    include("library/checklogin.php");
    include('library/check_operator_perm.php');
    include_once('library/config_read.php');
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    // init loggin variables
    $logQuery = "performed query for listing of records on page: ";
    $logDebugSQL = "";

    // set session's page variable
    $_SESSION['PREV_LIST_PAGE'] = $_SERVER['REQUEST_URI'];

    $sqlfields = (array_key_exists('sqlfields', $_GET) && !empty($_GET['sqlfields']) && is_array($_GET['sqlfields']) &&
                  array_intersect($_GET['sqlfields'], array_keys($bill_history_query_options_all)) == $_GET['sqlfields'])
               ? $_GET['sqlfields'] : $bill_history_query_options_default;
    
    $cols = array();
    foreach ($sqlfields as $sqlfield) {
        $cols[$sqlfield] = $bill_history_query_options_all[$sqlfield];
    }
    $colspan = count($cols);
    $half_colspan = intdiv($colspan, 2);
    
    $orderBy = (array_key_exists('orderBy', $_GET) && isset($_GET['orderBy']) &&
                in_array($_GET['orderBy'], array_keys($bill_history_query_options_all)))
             ? $_GET['orderBy'] : array_keys($bill_history_query_options_all)[0];

    $orderType = (array_key_exists('orderType', $_GET) && isset($_GET['orderType']) &&
                  preg_match(ORDER_TYPE_REGEX, $_GET['orderType']) !== false)
               ? strtolower($_GET['orderType']) : "asc";
    
    //~ $startdate = (array_key_exists('startdate', $_GET) && isset($_GET['startdate']) &&
                  //~ preg_match(DATE_REGEX, $_GET['startdate'], $m) !== false &&
                  //~ checkdate($m[2], $m[3], $m[1]))
               //~ ? $_GET['startdate'] : "";

    //~ $enddate = (array_key_exists('enddate', $_GET) && isset($_GET['enddate']) &&
                //~ preg_match(DATE_REGEX, $_GET['enddate'], $m) !== false &&
                //~ checkdate($m[2], $m[3], $m[1]))
             //~ ? $_GET['enddate'] : "";

    $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') : "";
    
    $billaction = (array_key_exists('billaction', $_GET) && isset($_GET['billaction']) &&
                   in_array($_GET['billaction'], array_slice($valid_billactions, 1))) // avoid inserting "Any" in the SQL query
                ? $_GET['billaction'] : "";
    $billaction_enc = (!empty($billaction)) ? htmlspecialchars($billaction, ENT_QUOTES, 'UTF-8') : "";
    
    // print HTML prologue
    $title = t('Intro','billhistoryquery.php');
    $help = t('helpPage','billhistoryquery');
    
    print_html_prologue($title, $langCode);
    

    //feed the sidebar variables
    $billing_date_startdate = $startdate;
    $billing_date_enddate = $enddate;
    $billing_history_username = $username;
    $billing_history_billaction = $billaction;

    include("menu-bill-history.php");
    
    echo '<div id="contentnorightbar">';
    print_title_and_help($title, $help);
    
    include('library/opendb.php');
    include('include/management/pages_common.php');
    
    // preparing the custom query
    
    $sql_WHERE = array();
    $partial_query_string_pieces = array();
    
    foreach ($sqlfields as $sqlfield) {
        $partial_query_string_pieces[] = sprintf("sqlfields[]=%s", $sqlfield);
    }
    
    //~ if (!empty($startdate)) {
        //~ $sql_WHERE[] = sprintf("AcctStartTime > '%s'", $dbSocket->escapeSimple($startdate));
        //~ $partial_query_string_pieces[] = sprintf("startdate=%s", $startdate);
    //~ }
    
    //~ if (!empty($startdate)) {
        //~ $sql_WHERE[] = sprintf("AcctStartTime < '%s'", $dbSocket->escapeSimple($enddate));
        //~ $partial_query_string_pieces[] = sprintf("enddate=%s", $enddate);
    //~ }
    
    if (!empty($username)) {
        $sql_WHERE[] = sprintf("username LIKE '%s%%'", $dbSocket->escapeSimple($username));
        $partial_query_string_pieces[] = sprintf("username=%s", $username_enc);
    }
    
    if (!empty($billaction)) {
        $sql_WHERE[] = sprintf("billaction LIKE '%s%%'", $dbSocket->escapeSimple($billaction));
        $partial_query_string_pieces[] = sprintf("billaction=%s", $billaction_enc);
    }
    
    // executing the custom query

    $sql = sprintf("SELECT %s FROM %s", implode(", ", $sqlfields), $configValues['CONFIG_DB_TBL_DALOBILLINGHISTORY']);
    
    if (count($sql_WHERE) > 0) {
        $sql .= " WHERE " . implode(" AND ", $sql_WHERE);
    }

    $res = $dbSocket->query($sql);
    $logDebugSQL .= "$sql;\n";
    
    $numrows = $res->numRows();
    
    if ($numrows > 0) {
        /* START - Related to pages_numbering.php */
        
        // when $numrows is set, $maxPage is calculated inside this include file
        include('include/management/pages_numbering.php');    // must be included after opendb because it needs to read
                                                              // the CONFIG_IFACE_TABLES_LISTING variable from the config file
        
        // here we decide if page numbers should be shown
        $drawNumberLinks = strtolower($configValues['CONFIG_IFACE_TABLES_LISTING_NUM']) == "yes" && $maxPage > 1;
        
        $sql .= sprintf(" ORDER BY %s %s LIMIT %s, %s", $orderBy, $orderType, $offset, $rowsPerPage);
        $res = $dbSocket->query($sql);
        $logDebugSQL .= "$sql;\n";
        
        $per_page_numrows = $res->numRows();
        
        // the partial query is built starting from user input
        // and for being passed to setupNumbering and setupLinks functions
        $partial_query_string = (count($partial_query_string_pieces) > 0)
                              ? "&" . implode("&", $partial_query_string_pieces) : "";
        
        echo '<table border="0" class="table1">'
           . '<thead>';
            
        // page numbers are shown only if there is more than one page
        if ($drawNumberLinks) {
            echo '<tr style="background-color: white">';
            printf('<td style="text-align: left" colspan="%s">go to page: ', $colspan);
            setupNumbering($numrows, $rowsPerPage, $pageNum, $orderBy, $orderType, $partial_query_string);
            echo '</td>' . '</tr>';
        }

        // second line of table header
        echo "<tr>";
        printTableHead($cols, $orderBy, $orderType, $partial_query_string);
        echo "</tr>";
        
        echo '</thead>'
           . '<tbody>';

        // inserting the values of each field from the database to the table
        $count = 0;
        while($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
            printf('<tr id="row-%d">', $count);
            foreach ($sqlfields as $field) {
                printf("<td>%s</td>", htmlspecialchars($row[$field], ENT_QUOTES, 'UTF-8'));
            }
            echo '</tr>';
            $count++;
        }

        echo '</tbody>';

        // tfoot
        $links = setupLinks_str($pageNum, $maxPage, $orderBy, $orderType, $partial_query_string);
        printTableFoot($per_page_numrows, $numrows, $colspan, $drawNumberLinks, $links);

        echo '</table>';
    
    } else {
        $failureMsg = "Nothing to display";
        include_once("include/management/actionMessages.php");
    }
        
    include('library/closedb.php');    

    include('include/config/logging.php');
    print_footer_and_html_epilogue();
    include("library/validation.php");
    $help = "";
    print_footer_and_html_epilogue();
	include_once('library/config_read.php');
    
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    // init loggin variables
    $log = "visited page: ";
    $logQuery = "performed query for listing of records on page: ";
    $logDebugSQL = "";

    // set session's page variable
    $_SESSION['PREV_LIST_PAGE'] = $_SERVER['REQUEST_URI'];

    $sqlfields = (array_key_exists('sqlfields', $_GET) && !empty($_GET['sqlfields']) && is_array($_GET['sqlfields']) &&
                  array_intersect($_GET['sqlfields'], array_keys($bill_merchant_transactions_options_all)) == $_GET['sqlfields'])
               ? $_GET['sqlfields'] : $bill_merchant_transactions_options_default;
    
    $cols = array();
    foreach ($sqlfields as $sqlfield) {
        $cols[$sqlfield] = $bill_merchant_transactions_options_all[$sqlfield];
    }
    $colspan = count($cols);
    $half_colspan = intdiv($colspan, 2);
    
    $orderBy = (array_key_exists('orderBy', $_GET) && isset($_GET['orderBy']) &&
                in_array($_GET['orderBy'], array_keys($bill_merchant_transactions_options_all)))
             ? $_GET['orderBy'] : array_keys($bill_merchant_transactions_options_all)[0];

    $orderType = (array_key_exists('orderType', $_GET) && isset($_GET['orderType']) &&
                  preg_match(ORDER_TYPE_REGEX, $_GET['orderType']) !== false)
               ? strtolower($_GET['orderType']) : "asc";
    
    $startdate = (array_key_exists('startdate', $_GET) && !empty($_GET['startdate']) &&
                  preg_match(DATE_REGEX, $_GET['startdate'], $m) !== false &&
                  checkdate($m[2], $m[3], $m[1]))
               ? $_GET['startdate'] : "";

    $enddate = (array_key_exists('enddate', $_GET) && !empty($_GET['enddate']) &&
                preg_match(DATE_REGEX, $_GET['enddate'], $m) !== false &&
                checkdate($m[2], $m[3], $m[1]))
             ? $_GET['enddate'] : "";
             
    $vendor_type = (array_key_exists('vendor_type', $_GET) && isset($_GET['vendor_type']) &&
                    in_array($_GET['vendor_type'], array_slice($valid_vendorTypes, 1))) // avoid inserting "Any" in the SQL query
                 ? $_GET['vendor_type'] : "";

    $payer_email = (array_key_exists('payer_email', $_GET) && !empty(str_replace("%", "", trim($_GET['payer_email']))))
                 ? str_replace("%", "", trim($_GET['payer_email'])) : "";
    $payer_email_enc = (!empty($payer_email)) ? htmlspecialchars($payer_email, ENT_QUOTES, 'UTF-8') : "";

	$payment_status = (array_key_exists('payment_status', $_GET) && isset($_GET['payment_status']) &&
                       in_array($_GET['payment_status'], array_slice($valid_paymentStatus, 1))) // avoid inserting "Any" in the SQL query
                    ? $_GET['payment_status'] : "";
    
    // FIX THIS: they aren't passed
    $payment_address_status = (array_key_exists('payment_address_status', $_GET) &&
                               !empty(str_replace("%", "", trim($_GET['payment_address_status']))))
                            ? str_replace("%", "", trim($_GET['payment_address_status'])) : "";
    $payer_status = (array_key_exists('payer_status', $_GET) && !empty(str_replace("%", "", trim($_GET['payer_status']))))
                  ? str_replace("%", "", trim($_GET['payer_status'])) : "";
	
    //feed the sidebar variables
	$billing_paypal_payeremail = $payer_email_enc;
    //~ $billing_paypal_paymentaddressstatus = $payment_address_status;
	//~ $billing_paypal_payerstatus = $payer_status;
    // print HTML prologue
    $title = t('Intro','billpaypaltransactions.php');
    $help = t('helpPage','billpaypaltransactions');
    
    print_html_prologue($title, $langCode);
    
    echo '<div id="contentnorightbar">';
    print_title_and_help($title, $help);

    // draw the billing rates summary table
    include_once('include/management/userBilling.php');
    userBillingPayPalSummary($startdate, $enddate, $payer_email, $payment_address_status, $payer_status, $payment_status, $vendor_type, 1);
									                         

    include('library/opendb.php');
    include_once('include/management/pages_common.php');
    
    // preparing the custom query
    
    $sql_WHERE = array();
    $partial_query_string_pieces = array();
    
    foreach ($sqlfields as $sqlfield) {
        $partial_query_string_pieces[] = sprintf("sqlfields[]=%s", $sqlfield);
    }
    
    if (!empty($startdate)) {
        $sql_WHERE[] = sprintf("payment_date > '%s'", $dbSocket->escapeSimple($startdate));
        $partial_query_string_pieces[] = sprintf("startdate=%s", $startdate);
    }
    
    if (!empty($startdate)) {
        $sql_WHERE[] = sprintf("payment_date < '%s'", $dbSocket->escapeSimple($enddate));
        $partial_query_string_pieces[] = sprintf("enddate=%s", $enddate);
    }
    
    if (!empty($payer_email)) {
        $sql_WHERE[] = sprintf("payer_email LIKE '%s%%'", $dbSocket->escapeSimple($payer_email));
        $partial_query_string_pieces[] = sprintf("payer_email=%s", $payer_email);
    }
    
    if (!empty($payment_status)) {
        $sql_WHERE[] = sprintf("payment_status='%s'", $dbSocket->escapeSimple($payment_status));
        $partial_query_string_pieces[] = sprintf("payment_status=%s", $payment_status);
    }
    
    if (!empty($vendor_type)) {
        $sql_WHERE[] = sprintf("vendor_type='%s'", $dbSocket->escapeSimple($vendor_type));
        $partial_query_string_pieces[] = sprintf("vendor_type=%s", $vendor_type);
    }
    
    // executing the custom query

    $sql = sprintf("SELECT %s FROM %s", implode(", ", $sqlfields), $configValues['CONFIG_DB_TBL_DALOBILLINGMERCHANT']);
    
    if (count($sql_WHERE) > 0) {
        $sql .= " WHERE " . implode(" AND ", $sql_WHERE);
    }

    $res = $dbSocket->query($sql);
    $logDebugSQL .= "$sql;\n";
    
    $numrows = $res->numRows();
			
    if ($numrows > 0) {
        /* START - Related to pages_numbering.php */
        
        // when $numrows is set, $maxPage is calculated inside this include file
        include('include/management/pages_numbering.php');    // must be included after opendb because it needs to read
                                                              // the CONFIG_IFACE_TABLES_LISTING variable from the config file
        
        // here we decide if page numbers should be shown
        $drawNumberLinks = strtolower($configValues['CONFIG_IFACE_TABLES_LISTING_NUM']) == "yes" && $maxPage > 1;
        
        $sql .= sprintf(" ORDER BY %s %s LIMIT %s, %s", $orderBy, $orderType, $offset, $rowsPerPage);
        $res = $dbSocket->query($sql);
        $logDebugSQL .= "$sql;\n";
        
        $per_page_numrows = $res->numRows();
        
        // the partial query is built starting from user input
        // and for being passed to setupNumbering and setupLinks functions
        $partial_query_string = (count($partial_query_string_pieces) > 0)
                              ? "&" . implode("&", $partial_query_string_pieces) : "";

        echo '<table border="0" class="table1">'
           . '<thead>';

        // page numbers are shown only if there is more than one page
        if ($drawNumberLinks) {
            echo '<tr style="background-color: white">';
            printf('<td style="text-align: left" colspan="%s">go to page: ', $colspan);
            setupNumbering($numrows, $rowsPerPage, $pageNum, $orderBy, $orderType, $partial_query_string);
            echo '</td>' . '</tr>';
        }

        // second line of table header
        echo "<tr>";
        printTableHead($cols, $orderBy, $orderType, $partial_query_string);
        echo "</tr>";

            
        echo '</thead>'
           . '<tbody>';
        
        // inserting the values of each field from the database to the table
        $count = 0;
        while($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
            printf('<tr id="row-%d">', $count);
            foreach ($sqlfields as $field) {
                printf("<td>%s</td>", htmlspecialchars($row[$field], ENT_QUOTES, 'UTF-8'));
            }
            echo '</tr>';
            $count++;
        }

        echo '</tbody>';
        
        // tfoot
        $links = setupLinks_str($pageNum, $maxPage, $orderBy, $orderType, $partial_query_string);
        printTableFoot($per_page_numrows, $numrows, $colspan, $drawNumberLinks, $links);

        echo '</table>';

    } else {
        $failureMsg = "Nothing to display";
        include_once("include/management/actionMessages.php");
    }
        
    include('library/closedb.php');    

    include('include/config/logging.php');
    print_footer_and_html_epilogue();
    include("library/validation.php");
    include_once('library/config_read.php');
    include_once("lang/main.php");
    include_once("library/validation.php");
    include("library/layout.php");
    
    print_back_to_previous_page();
    include_once("lang/main.php");
    include_once("library/validation.php");
    include("library/layout.php");

    // init loggin variables
    $log = "visited page: ";
    $logQuery = "performed query for listing of records on page: ";
    $logDebugSQL = "";

    include_once("lang/main.php");
    include("library/layout.php");
    include("library/layout.php");
    
    $log = "visited page: ";
    include_once("lang/main.php");
    include("library/layout.php");
    
    $log = "visited page: ";
<?php 

    include ("library/checklogin.php");
    $log = "visited page: ";

    
    echo '<div id="contentnorightbar">';
    
    print_footer_and_html_epilogue();
?>
    
    print_footer_and_html_epilogue();
?>
<?php 
    include ("library/checklogin.php");

    
    echo '<div id="contentnorightbar">';
    
    print_footer_and_html_epilogue();
?>
    print_footer_and_html_epilogue();
 * 
 * Description:    returns user billing information (rates, plans, etc)
 * Authors:        Liran Tal <liran@enginx.com>
 *                 Filippo Lauria <filippo.lauria@iit.cnr.it>
// prevent this file to be directly accessed
if (strpos($_SERVER['PHP_SELF'], '/include/management/userBilling.php') !== false) {
    header("Location: ../../index.php");
    exit;
}
 * $userId                    the userbillinfo user id or the username (autodetects)
    include(dirname(__FILE__).'/../../library/opendb.php');
    $user_id = false;
    // if provided a numeric user id then this is the user_id that we need
    if (is_numeric($userId)) {
        $user_id = $dbSocket->escapeSimple($userId);            // sanitize variable for sql statement
    } else {
        // otherwise this is the username and we need to look up the user id from the userbillinfo table
        $username = $dbSocket->escapeSimple($userId);
        $sql = 'SELECT id FROM '.$configValues['CONFIG_DB_TBL_DALOUSERBILLINFO'].
                ' WHERE username="'.$username.'"';
        $res = $dbSocket->query($sql);
        $logDebugSQL .= $sql . "\n";
        $row = $res->fetchRow();
        $user_id = $row[0];
    }
    // if something is not right with the user id (set to null, false, whatever) we abort
    if (!$user_id)
        return false;
    $currDate = date('Y-m-d H:i:s');
    $currBy = $_SESSION['operator_user'];
    if (!$invoiceInfo)
        $invoiceInfo = array();
    // create default invoice information if nothing was provided
    $myinvoiceInfo['date'] = $currDate;
    $myinvoiceInfo['status_id'] = 1;             // defaults to invoice status of 'open'
    $myinvoiceInfo['type_id'] = 1;             // defaults to invoice type of 'Plans'
    $myinvoiceInfo['notes'] = 'provisioned new user from daloRADIUS platform';
    $invoiceInfo = array_merge($myinvoiceInfo, $invoiceInfo);
    $sql = "INSERT INTO ".$configValues['CONFIG_DB_TBL_DALOBILLINGINVOICE'].
            " (id, user_id, date, status_id, type_id, notes, creationdate, creationby, updatedate, updateby) ".
            " VALUES (0, '".$user_id."', '".
            $dbSocket->escapeSimple($invoiceInfo['date'])."', '".
            $dbSocket->escapeSimple($invoiceInfo['status_id'])."', '".
            $dbSocket->escapeSimple($invoiceInfo['type_id'])."', '".
            $dbSocket->escapeSimple($invoiceInfo['notes'])."', ".
            " '$currDate', '$currBy', NULL, NULL)";
    $res = $dbSocket->query($sql);
    $logDebugSQL .= $sql . "\n";

    // if there hasn't been any errors with inserting the invoice record
    if (!PEAR::isError($res)) {

        // get the added invoice id from the database
        $invoice_id = $dbSocket->getOne( "SELECT LAST_INSERT_ID() FROM `".$configValues['CONFIG_DB_TBL_DALOBILLINGINVOICE']."`" );

        if (!$invoice_id)
            return false;

        foreach($invoiceItems as $invoiceItem) {
            // set default information for the invoice items
            /*
            $myinvoiceItems['plan_id'] = '' ;
            $myinvoiceItems['amount'] = '' ;
            $myinvoiceItems['tax'] = '' ;
            $myinvoiceItems['notes'] = '' ;
            $invoiceItems = array_merge($myinvoiceItems, $invoiceItems);
            */

            // now add an invoice item
            $sql = "INSERT INTO ".$configValues['CONFIG_DB_TBL_DALOBILLINGINVOICEITEMS'].
                " (id, invoice_id, plan_id, amount, tax_amount, notes, ".
                " creationdate, creationby, updatedate, updateby) ".
                " VALUES (0, '".$invoice_id."', '".
                $dbSocket->escapeSimple($invoiceItem['plan_id'])."', '".
                $dbSocket->escapeSimple($invoiceItem['amount'])."', '".
                $dbSocket->escapeSimple($invoiceItem['tax'])."', '".
                $dbSocket->escapeSimple($invoiceItem['notes'])."', ".
                " '$currDate', '$currBy', NULL, NULL)";

            $res = $dbSocket->query($sql);
            $logDebugSQL .= $sql . "\n";
        }
    }
    include(dirname(__FILE__).'/../../library/closedb.php');
    return true;
    include_once('include/management/pages_common.php');
    include 'library/opendb.php';

    $user_id = $dbSocket->escapeSimple($user_id);            // sanitize variable for sql statement

    $sql = "SELECT COUNT(distinct(a.id)) AS TotalInvoices, a.id, a.date, a.status_id, a.type_id, b.contactperson, b.username, ".
            " c.value AS status, COALESCE(SUM(e2.totalpayed), 0) as totalpayed, COALESCE(SUM(d2.totalbilled), 0) as totalbilled, ".
            " SUM(a.status_id = 1) as openInvoices ".
            " FROM ".$configValues['CONFIG_DB_TBL_DALOBILLINGINVOICE']." AS a".
            " INNER JOIN ".$configValues['CONFIG_DB_TBL_DALOUSERBILLINFO']." AS b ON (a.user_id = b.id) ".
            " INNER JOIN ".$configValues['CONFIG_DB_TBL_DALOBILLINGINVOICESTATUS']." AS c ON (a.status_id = c.id) ".
            " LEFT JOIN (SELECT SUM(d.amount + d.tax_amount) ".
                    " as totalbilled, invoice_id FROM ".$configValues['CONFIG_DB_TBL_DALOBILLINGINVOICEITEMS']." AS d ".
            " GROUP BY d.invoice_id) AS d2 ON (d2.invoice_id = a.id) ".
            " LEFT JOIN (SELECT SUM(e.amount) as totalpayed, invoice_id FROM ".
            $configValues['CONFIG_DB_TBL_DALOPAYMENTS']." AS e GROUP BY e.invoice_id) AS e2 ON (e2.invoice_id = a.id) ".
            " WHERE (a.user_id = $user_id)".
            " GROUP BY b.id ";
    $res = $dbSocket->query($sql);
    $row = $res->fetchRow(DB_FETCHMODE_ASSOC);
    $totalInvoices = $row['TotalInvoices'];
    $totalBilled = $row['totalbilled'];
    $totalPayed = $row['totalpayed'];
    $openInvoices = $row['openInvoices'];
    include 'library/closedb.php';
    if ($drawTable == 1) {
        echo '
                <fieldset>
                <br/>
                <ul>
                    <input class="button" type="button" value="New Invoice"
                        onClick="javascript:window.location = \'bill-invoice-new.php?user_id='.$user_id.'\';" />
                    <input class="button" type="button" value="Show Invoices"
                        onClick="javascript:window.location = \'bill-invoice-list.php?user_id='.$user_id.'\';" />
                    <input class="button" type="button" value="Show Payments"
                        onClick="javascript:window.location = \'bill-payments-list.php?user_id='.$user_id.'\';" />
                    <br/><br/>
                    <li class="fieldset">
                        <label for="totalInvoices" class="form">Total Invoices</label>
                        <input type="text" value="'.$totalInvoices.'" disabled />
                    </li>
                    <li class="fieldset">
                        <label for="totalbilled" class="form">Open Invoices</label>
                        <input type="text" value="'.$openInvoices.'" disabled />
                    </li>
                    <br/>
                    <li class="fieldset">
                        <label for="totalbilled" class="form">Total Billed</label>
                        <input type="text" value="'.$totalBilled.'" disabled />
                    </li>
                    <li class="fieldset">
                        <label for="totalbilled" class="form">Total Payed</label>
                        <input type="text" value="'.$totalPayed.'" disabled />
                    </li>
                    <li class="fieldset">
                        <label for="totalbilled" class="form">Balance</label>
                        <input type="text" value="'.($totalPayed - $totalBilled).'" disabled />
                    </li>
                    <li class="fieldset">
                    <br/>
                    <hr><br/>
                    <input type="submit" name="submit" value="Apply" tabindex=10000 class="button" />
                    </li>
            </ul>
            </fieldset>
            ';
    }
 * $startdate        starting date, first accounting session
 * $enddate        ending date, last accounting session
 * $ratename        the rate to use for calculations
    include_once('include/management/pages_common.php');
    include 'library/opendb.php';
    $username = $dbSocket->escapeSimple($username);            // sanitize variable for sql statement
    if ($res->numRows() == 0)
        return;
        " SUM(".$configValues['CONFIG_DB_TBL_RADACCT'].".AcctOutputOctets) AS AcctOutputOctets ".
    $res = $dbSocket->query($sql);
    $row = $res->fetchRow(DB_FETCHMODE_ASSOC);
    $rateCost = $row['rateCost'];
    $userUpload = toxbyte($row['AcctInputOctets']);
    $userDownload = toxbyte($row['AcctOutputOctets']);
    $userOnlineTime = time2str($row['AcctSessionTime']);
    $sessionTime = $row['AcctSessionTime'];
    $sumBilled = (($sessionTime/$rateDivisor)*$rateCost);
                <thead>
                    <tr>
                            <th colspan='10' align='left'>
                        <a class=\"table\" href=\"javascript:toggleShowDiv('divBillingRatesSummary')\">Billing Summary</a>
                            </th>
                            </tr>
                </thead>
                </table>
            ";
                       <table border='0' class='table1'>
                <thread>
                </div>
            ";
    }
 * $startdate        starting date, first accounting session
 * $enddate        ending date, last accounting session
function userBillingPayPalSummary($startdate, $enddate, $payer_email, $payment_address_status,
                                  $payer_status, $payment_status, $vendor_type, $drawTable) {
    global $logDebugSQL;
    
    include('library/opendb.php');

    $sql_WHERE = array();
    
    if (!empty($startdate)) {
        $sql_WHERE[] = sprintf("payment_date > '%s'", $dbSocket->escapeSimple($startdate));
    }
    
    if (!empty($startdate)) {
        $sql_WHERE[] = sprintf("payment_date < '%s'", $dbSocket->escapeSimple($enddate));
    }
    
    if (!empty($payer_email)) {
        $sql_WHERE[] = sprintf("payer_email LIKE '%s%%'", $dbSocket->escapeSimple($payer_email));
    }
    
    if (!empty($payment_status)) {
        $sql_WHERE[] = sprintf("payment_status='%s'", $dbSocket->escapeSimple($payment_status));
    }
    
    if (!empty($vendor_type)) {
        $sql_WHERE[] = sprintf("vendor_type='%s'", $dbSocket->escapeSimple($vendor_type));
    }
    
    if (!empty($payment_address_status)) {
        $sql_WHERE[] = sprintf("payment_address_status='%s'", $dbSocket->escapeSimple($payment_address_status));
    }
    
    if (!empty($payer_status)) {
        $sql_WHERE[] = sprintf("payer_status='%s'", $dbSocket->escapeSimple($payer_status));
    }

    $sql = sprintf("SELECT dbm.Username AS Username, business_email, dbp.planName, dbm.planId, SUM(payment_total) AS total,
                           SUM(payment_fee) AS fee, SUM(payment_tax) AS tax, payment_currency,
                           SUM(AcctSessionTime) AS AcctSessionTime, SUM(AcctInputOctets) AS AcctInputOctets,
                           SUM(AcctOutputOctets) AS AcctOutputOctets
                      FROM %s AS dbm LEFT JOIN %s AS ra ON dbm.Username = ra.Username
                                     LEFT JOIN %s AS dbp ON dbm.planId = dbp.id", $configValues['CONFIG_DB_TBL_DALOBILLINGMERCHANT'],
                                                                                  $configValues['CONFIG_DB_TBL_RADACCT'],
                                                                                  $configValues['CONFIG_DB_TBL_DALOBILLINGPLANS']);
    if (count($sql_WHERE) > 0) {
        $sql .= " WHERE " . implode(" AND ", $sql_WHERE);
        
    }
    
    $sql .= " GROUP BY Username";
    $logDebugSQL .= "$sql;\n";
    $res = $dbSocket->query($sql);
    if ($res->numRows() > 0 && $drawTable == 1) {
        
        include_once('include/management/pages_common.php');
        
        $row = $res->fetchRow();
        
        for ($i=0; $i < count($row); $i++) {
            $row[$i] = htmlspecialchars($row[$i], ENT_QUOTES, 'UTF-8');
        }
        
        list( $username, $payer_email, $planName, $planId, $planTotalCost, $planTotalFee, $planTotalTax,
              $planCurrency, $sessionTime, $userUpload, $userDownload ) = $row;
        
        $grossGain = $planTotalCost - ($planTotalTax + $planTotalFee);
        
        $userUpload = toxbyte($userUpload);
        $userDownload = toxbyte($userDownload);
        $userOnlineTime = time2str($sessionTime);

    
        $table = array(
                        array( "Username", "$username (email: $payer_email)" ),
                        array( "Billing for period of", "$startdate until $enddate (inclusive)" ),
                        array( "Online Time", $userOnlineTime ),
                        array( "User Upload", $userUpload ),
                        array( "User Download", $userDownload ),
                        array( "Plan name", "$planName (planId: $planId)" ),
                        array( "Total Plans Cost <br/> Total Transaction Fees <br/> Total Transaction Taxs",
                               "$planTotalCost <br/> $planTotalFee <br/> $planTotalTax" ),
                        array( "Gross Gain", "$grossGain $planCurrency" )
                      );

        echo '<table style="border: 0" class="table1">'
           . '<thead>'
           . '<tr>'
           . '<th colspan="10" align="left">';
        
        printf('<a class="table" href="%s">Billing Summary</a>', "toggleShowDiv('divBillingPayPalSummary')");
        
        echo '</th>'
           . '</tr>'
           . '</thead>'
           . '</table>';


        echo '<div id="divBillingPayPalSummary" style="display:none; visibility:visible">'
           . '<table style="border:0" class="table1">';
        
        foreach ($table as $tr) {
            list($td1, $td2) = $tr;
            
            echo "<tr>";
            printf('<th scope="col" align="right">%s</th>', $td1);
            printf('<th scope="col" align="left">%s</th>', $td2);
            echo "</tr>";
        }
        
        echo '</table>'
           . '</div>';
    }
    
    include('library/closedb.php');
$valid_recommendedHelpers = array(
                                    "date", "datetime", "authtype", "framedprotocol", "servicetype",
                                    "kbitspersecond", "bitspersecond", "volumebytes", "mikrotikRateLimit",
                                 );

$valid_attributeTypes = array(
                                "string",
                                "integer",
                                "ipaddr",
                                "date",
                                "octets",
                                "ipv6addr",
                                "ifid",
                                "abinary",
                             );

// accounting custom-query options list

// accounting custom-query options selected by default
// billing history query options list
$bill_history_query_options_all = array(
                                            "id" => t('all','ID'),
                                            "username" => t('all','Username'),
                                            "planId" => t('all','PlanId'),

                                            "billAmount" => t('all','BillAmount'),
                                            "billAction" => t('all','BillAction'),
                                            "billPerformer" => t('all','BillPerformer'),
                                            "billReason" => t('all','BillReason'),

                                            "paymentmethod" => t('ContactInfo','PaymentMethod'),
                                            "cash" => t('ContactInfo','Cash'),

                                            "creditcardname" => t('ContactInfo','CreditCardName'),
                                            "creditcardnumber" => t('ContactInfo','CreditCardNumber'),
                                            "creditcardverification" => t('ContactInfo','CreditCardVerificationNumber'),
                                            "creditcardtype" => t('ContactInfo','CreditCardType'),
                                            "creditcardexp" => t('ContactInfo','CreditCardExpiration'),
                                            "coupon" => t('all','Coupon'),
                                            "discount" => t('all','Discount'),
                                            "notes" => t('ContactInfo','Notes'),
                                            "creationdate" => t('all','CreationDate'),
                                            "creationby" => t('all','CreationBy'),
                                            "updatedate" => t('all','UpdateDate'),
                                            "updateby" => t('all','UpdateBy')
                                       );

// billing history query options selected by default
$bill_history_query_options_default = array(
                                                "username",
                                                "planId",
                                                "billAmount",
                                                "billAction",
                                                "billPerformer",
                                                "paymentmethod"
                                           );

$bill_merchant_transactions_options_all = array(
                                                    "id" => t('all','ID'),
                                                    "username" => t('all','Username'),
                                                    "password"  => t('all','Password'),
                                                    "txnId"  => t('all','TxnId'),
                                                    "planName" => t('all','PlanName'),
                                                    "planId"  => t('all','PlanId'),
                                                    "quantity"  => t('all','Quantity'),
                                                    "business_email"  => t('all','ReceiverEmail'),
                                                    "business_id"  => t('all','Business'),
                                                    "payment_tax" => t('all','Tax'),
                                                    "payment_cost"  => t('all','Cost'),
                                                    "payment_fee" => t('all','TransactionFee'),
                                                    "payment_total" => t('all','TotalCost'),
                                                    "payment_currency" => t('all','PaymentCurrency'),
                                                    "first_name" => t('all','FirstName'),
                                                    "last_name" => t('all','LastName'),
                                                    "payer_email" => t('all','PayerEmail'),
                                                    "payer_address_name"  => t('all','AddressRecipient'),
                                                    "payer_address_street"  => t('all','Street'),
                                                    "payer_address_country" => t('all','Country'),
                                                    "payer_address_country_code"  => t('all','CountryCode'),
                                                    "payer_address_city" => t('all','City'),
                                                    "payer_address_state" => t('all','State'),
                                                    "payer_address_zip"  => t('all','Zip'),
                                                    "payment_date" => t('all','PaymentDate'),
                                                    "payment_status" => t('all','PaymentStatus'),
                                                    "payer_status" => t('all','PayerStatus'),
                                                    "payment_address_status" => t('all','PaymentAddressStatus'),
                                                    "vendor_type" => t('all','VendorType')
                                               );
                                               
$bill_merchant_transactions_options_default = array(
                                                        "username",
                                                        "planName",
                                                        "payment_fee",
                                                        "payment_total",
                                                        "payment_currency",
                                                        "first_name",
                                                        "last_name",
                                                        "payer_email",
                                                        "payer_address_country",
                                                        "payer_address_city",
                                                        "payer_address_state",
                                                        "payment_date",
                                                        "payment_status",
                                                        "vendor_type"
                                                   );


$valid_paymentStatus = array(
                              "Any", "Completed",  "Denied",  "Expired",  "Failed",  "In-Progress",  "Pending", 
                              "Processed",  "Refunded",  "Reversed",  "Canceled-Reversal",  "Voided", 
                            );
$valid_vendorTypes = array( "Any", "2Checkout", "PayPal" );
$valid_billactions = array( "Any", "Refill Session Time", "Refill Session Traffic" );

    header("Location: index.php");
    header("Location: index.php");
<?php
/*                            <h109><?= t('button','BetweenDates') ?></h109><br>
                            <br><br>
*/

                            $descr = array(
                                            "caption" => t('all','Username'),
                                            "type" => "text",
                                            "name" => "username",
                                            "value" => ((isset($billing_history_username)) ? $billing_history_username : ""),
                                          );
                                          
                            print_form_component($descr);

                            $descr = array(
                                            "caption" => t('all','BillAction'),
                                            "type" => "select",
                                            "name" => "billaction",
                                            "options" => $valid_billactions,
                                            "selected_value" => ((isset($billaction)) ? $billaction : $valid_billactions[0]),
                                          );
                            print_form_component($descr);
?>

                            
                            $descr = array(
                                            "caption" => t('button','AccountingFieldsinQuery'),
                                            "type" => "select",
                                            "name" => "sqlfields[]",
                                            "id" => "sqlfields",
                                            "options" => $bill_history_query_options_all,
                                            "selected_value" => ((isset($sqlfields)) ? $sqlfields : $bill_history_query_options_default),
                                            "multiple" => true
                                          );
                            
                            print_form_component($descr);
                            
                            <a style="display: inline" href="#" onclick="select('all')">Select All</a>
                            <a style="display: inline" href="#" onclick="select('none')">Select None</a>
<?php
                            $descr = array(
                                            "caption" => t('button','OrderBy'),
                                            "type" => "select",
                                            "name" => "orderBy",
                                            "options" => $bill_history_query_options_all,
                                            "selected_value" => ((isset($orderBy)) ? $orderBy : $bill_history_query_options_all[0])
                                          );
                            
                            print_form_component($descr);

                            $descr = array(
                                            "caption" => "Order Type",
                                            "type" => "select",
                                            "name" => "orderType",
                                            "options" => array("asc" => "Ascending", "desc" => "Descending"),
                                            "selected_value" => ((isset($orderType)) ? $orderType : "asc")
                                          );
                            
                            print_form_component($descr);
?>
                            <br>
    function select(what) {
        var selected = (what == 'all'),
            sqlfields = document.getElementById('sqlfields');
    
        for (var i = 0; i < sqlfields.options.length; i++) {
            sqlfields.options[i].selected = selected;
        }
    }
    
    header("Location: index.php");
                                    value="<?= (!empty($billing_date_startdate)) ? $billing_date_startdate : date("Y-m-01") ?>">
                                <input name="enddate" type="date" id="enddate" tooltipText="<?= t('Tooltip','Date') ?>"
                                    value="<?= (!empty($billing_date_enddate)) ? $billing_date_enddate : date("Y-m-t") ?>">
                            $descr = array(
                                            "caption" => t('all','VendorType'),
                                            "type" => "select",
                                            "name" => "vendor_type",
                                            "options" => $valid_vendorTypes,
                                            "selected_value" => ((isset($billing_paypal_vendor_type)) ? $billing_paypal_vendor_type : $valid_vendorTypes[0])
                                          );
                            
                            print_form_component($descr);
                            
                            $descr = array(
                                            "caption" => t('all','PayerEmail'),
                                            "type" => "text",
                                            "name" => "payer_email",
                                            "value" => ((isset($billing_paypal_payeremail)) ? $billing_paypal_payeremail : ""),
                                          );
                                          
                            print_form_component($descr);

                            $descr = array(
                                            "caption" => t('all','PaymentStatus'),
                                            "type" => "select",
                                            "name" => "payment_status",
                                            "options" => $valid_paymentStatus,
                                            "selected_value" => ((isset($billing_paypal_paymentstatus)) ? $billing_paypal_paymentstatus : $valid_paymentStatus[0])
                                          );
                            
                            print_form_component($descr);

                            $descr = array(
                                            "caption" => t('button','AccountingFieldsinQuery'),
                                            "type" => "select",
                                            "name" => "sqlfields[]",
                                            "id" => "sqlfields",
                                            "options" => $bill_merchant_transactions_options_all,
                                            "selected_value" => ((isset($sqlfields)) ? $sqlfields : $bill_merchant_transactions_options_default),
                                            "multiple" => true
                                          );
                            
                            print_form_component($descr);
                            
                                <a style="display: inline" href="#" onclick="select('all')">Select All</a>
                                <a style="display: inline" href="#" onclick="select('none')">Select None</a>
<?php
                            $descr = array(
                                            "caption" => t('button','OrderBy'),
                                            "type" => "select",
                                            "name" => "orderBy",
                                            "options" => $bill_merchant_transactions_options_all,
                                            "selected_value" => ((isset($orderBy)) ? $orderBy : $bill_merchant_transactions_options_default[0])
                                          );
                            
                            print_form_component($descr);

                            $descr = array(
                                            "caption" => "Order Type",
                                            "type" => "select",
                                            "name" => "orderType",
                                            "options" => array("asc" => "Ascending", "desc" => "Descending"),
                                            "selected_value" => ((isset($orderType)) ? $orderType : "asc")
                                          );
                            
                            print_form_component($descr);
?>
                               
    function select(what) {
        var selected = (what == 'all'),
            sqlfields = document.getElementById('sqlfields');
    
        for (var i = 0; i < sqlfields.options.length; i++) {
            sqlfields.options[i].selected = selected;
        }
    }
    
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    
    // set session's page variable
    $_SESSION['PREV_LIST_PAGE'] = $_SERVER['REQUEST_URI'];
    
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    
    include_once("lang/main.php");
    include("library/layout.php");

        $li_style = 'margin: 7px auto';
        $count = 0;

    
    $inline_extra_js = "
var tooltipObj = new DHTMLgoodies_formTooltip();
tooltipObj.setTooltipPosition('right');
tooltipObj.setPageBgColor('#EEEEEE');
tooltipObj.setTooltipCornerSize(15);
tooltipObj.initFormFieldTooltip()";
    print_footer_and_html_epilogue($inline_extra_js);
?>
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    include_once("include/management/functions.php");

    include_once('include/management/populate_selectbox.php');
    $valid_groups = get_groups();
    $valid_planNames = get_plans();

    $sql0 = sprintf("SELECT COUNT(DISTINCT(rc.username)) AS username
                       FROM %s AS rc, %s AS ui
                      WHERE rc.username=ui.username AND (rc.attribute='Auth-Type' OR rc.attribute LIKE '%%-Password')",
                    $configValues['CONFIG_DB_TBL_RADCHECK'], $configValues['CONFIG_DB_TBL_DALOUSERINFO']);
        if (count($usernamelist) > 0) {
        
            // with this second query we retrieve user status (enabled/disabled) and user groups list
            $sql2 = sprintf("SELECT username, groupname FROM %s WHERE username IN (%s)",
                            $configValues['CONFIG_DB_TBL_RADUSERGROUP'], implode(", ", $usernamelist));
            $res = $dbSocket->query($sql2);
            $logDebugSQL .= "$sql2;\n";
            // foreach user we update the enabled flag and the grouplist
            while ($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
                $this_username = $row['username'];
                $this_groupname = $row['groupname'];
                if ($this_groupname === 'daloRADIUS-Disabled-Users') {
                    $records[$this_username]['enabled'] = false;
                } else {
                    array_push($records[$this_username]['groups'],
                               htmlspecialchars($this_groupname, ENT_QUOTES, 'UTF-8'));
                }
                <td><?= ($type == 'USER') ? $auth : "(n/a)" ?></td>
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    include_once("include/management/functions.php");

    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    include_once("include/management/functions.php");
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    // custom validation structures
    $valid_tables = array("check", "reply");
    function attribute_vendor_exist($dbSocket, $attribute, $vendor) {
        global $configValues, $logDebugSQL;
        
        $sql = sprintf("SELECT COUNT(DISTINCT(id)) FROM %s WHERE attribute='%s' AND vendor='%s'",
                               $configValues['CONFIG_DB_TBL_DALODICTIONARY'],
                               $dbSocket->escapeSimple($attribute),
                               $dbSocket->escapeSimple($vendor));
        $logDebugSQL .= "$sql;\n";
        
        return $res->fetchrow()[0] > 0;
    }

    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (array_key_exists('csrf_token', $_POST) && isset($_POST['csrf_token']) && dalo_check_csrf_token($_POST['csrf_token'])) {

            $vendor = (array_key_exists('vendor', $_POST) && !empty(str_replace("%", "", trim($_POST['vendor']))))
                    ? str_replace("%", "", trim($_POST['vendor'])) : "";
            $vendor_enc = (!empty($vendor)) ? htmlspecialchars($vendor, ENT_QUOTES, 'UTF-8') : "";

            $attribute = (array_key_exists('attribute', $_POST) && !empty(str_replace("%", "", trim($_POST['attribute']))))
                       ? str_replace("%", "", trim($_POST['attribute'])) : "";
            $attribute_enc = (!empty($attribute)) ? htmlspecialchars($attribute, ENT_QUOTES, 'UTF-8') : "";

            $type = (array_key_exists('type', $_POST) && !empty(trim($_POST['type'])) &&
                     in_array(trim($_POST['type']), $valid_attributeTypes))
                  ? $_POST['type'] : "";

            $op = (array_key_exists('RecommendedOP', $_POST) && isset($_POST['RecommendedOP']) &&
                   in_array($_POST['RecommendedOP'], $valid_ops))
                ? $_POST['RecommendedOP'] : "";
            
            $table = (array_key_exists('RecommendedTable', $_POST) && isset($_POST['RecommendedTable']) &&
                      in_array($_POST['RecommendedTable'], $valid_tables))
                   ? $_POST['RecommendedTable'] : "";
            
            $helper = (array_key_exists('RecommendedHelper', $_POST) && isset($_POST['RecommendedHelper']) &&
                       in_array($_POST['RecommendedHelper'], $valid_recommendedHelpers))
                    ? $_POST['RecommendedHelper'] : "";
            
            $tooltip = (array_key_exists('RecommendedTooltip', $_POST) &&
                        !empty(str_replace("%", "", trim($_POST['RecommendedTooltip']))))
                     ? str_replace("%", "", trim($_POST['RecommendedTooltip'])) : "";

            if (empty($vendor) || empty($attribute)) {
                // vendor and attribute are required
                $failureMsg = "vendor and/or attribute are empty or invalid";
                $logAction .= "Failed updating attribute [$attribute] (possible empty/invalid vendor and/or attribute) on page: ";
                
                include('library/opendb.php');
                
                $exists = attribute_vendor_exist($dbSocket, $attribute, $vendor);
                
                if (!$exists) {
                    // vendor and/or attribute invalid
                    $failureMsg = "vendor and/or attribute are invalid";
                    $logAction .= "Failed updating attribute [$attribute] (possible invalid vendor and/or attribute) on page: ";
                } else {
                    
                    $sql = sprintf("UPDATE %s
                                       SET Type='%s', RecommendedOP='%s', RecommendedTable='%s',
                                           RecommendedTooltip='%s', RecommendedHelper='%s'
                                     WHERE Vendor='%s' AND Attribute='%s'",
                                   $configValues['CONFIG_DB_TBL_DALODICTIONARY'], $dbSocket->escapeSimple($type),
                                   $dbSocket->escapeSimple($op), $dbSocket->escapeSimple($table),
                                   $dbSocket->escapeSimple($tooltip), $dbSocket->escapeSimple($helper), 
                                   $dbSocket->escapeSimple($vendor), $dbSocket->escapeSimple($attribute));
                    $res = $dbSocket->query($sql);
                    $logDebugSQL .= "$sql;\n";
                    
                    if (!DB::isError($res)) {
                        $format = "Attribute information has been updated in the dictionary (attribute: %s, vendor: %s)";
                        $successMsg = sprintf($format, $attribute_enc, $vendor_enc);
                        $logAction .= sprintf("$format on page: ", $attribute, $vendor);
                    } else {
                        $format = "An error occurred when updating attribute information in the dictionary (attribute: %s, vendor: %s)";
                        $failureMsg = sprintf($format, $attribute_enc, $vendor_enc);
                        $logAction .= sprintf("Failed to add an attribute [$format] on page: ", $attribute, $vendor);
                    }
                }
                
                include('library/closedb.php');

        } else {
            // csrf
            $failureMsg = "CSRF token error";
            $logAction .= "$failureMsg on page: ";
    } else {
        // !POST
        
        $vendor = (array_key_exists('vendor', $_REQUEST) && !empty(str_replace("%", "", trim($_REQUEST['vendor']))))
                ? str_replace("%", "", trim($_REQUEST['vendor'])) : "";
        $vendor_enc = (!empty($vendor)) ? htmlspecialchars($vendor, ENT_QUOTES, 'UTF-8') : "";
        $attribute = (array_key_exists('attribute', $_REQUEST) && !empty(str_replace("%", "", trim($_REQUEST['attribute']))))
                   ? str_replace("%", "", trim($_REQUEST['attribute'])) : "";
        $attribute_enc = (!empty($attribute)) ? htmlspecialchars($attribute, ENT_QUOTES, 'UTF-8') : "";
    include('library/opendb.php');
    
    $exists = attribute_vendor_exist($dbSocket, $attribute, $vendor);
                    
    if (!$exists) {
        // vendor and/or attribute invalid
        $failureMsg = "vendor and/or attribute are invalid";
        $logAction .= "Failed updating attribute [$attribute] (possible invalid vendor and/or attribute) on page: ";
        
    } else {
        $sql = sprintf("SELECT id, Type, Attribute, Value, Format, Vendor, RecommendedOP,
                               RecommendedTable, RecommendedHelper, RecommendedTooltip
                          FROM %s WHERE attribute='%s' AND vendor='%s' LIMIT 1",
                       $configValues['CONFIG_DB_TBL_DALODICTIONARY'],
                       $dbSocket->escapeSimple($attribute),
                       $dbSocket->escapeSimple($vendor));
        $res = $dbSocket->query($sql);
        $logDebugSQL .= "$sql;\n";
        
        list(
                $this_id, $this_Type, $this_Attribute, $this_Value, $this_Format,
                $this_Vendor, $this_OP, $this_Table, $this_Helper, $this_Tooltip
            ) = $res->fetchrow();
            
        
    }
    
    include('library/closedb.php');
    include_once('include/management/actionMessages.php');
    if (!isset($successMsg) && !empty($vendor) && !empty($attribute)) {
        
        $fieldset0_descriptor = array(
                                        "title" => t('title','VendorAttribute'),
                                     );
        
        $input_descriptors0 = array();
        
        $input_descriptors0[] = array(
                                        "name" => "vendor",
                                        "type" => "hidden",
                                        "value" => (isset($vendor) ? $vendor : ""),
                                     );
                                     
        $input_descriptors0[] = array(
                                        "name" => "attribute",
                                        "type" => "hidden",
                                        "value" => (isset($attribute) ? $attribute : ""),
                                     );
        
        $input_descriptors0[] = array(
                                        "name" => "vendor_presentation",
                                        "caption" => t('all','VendorName'),
                                        "type" => "text",
                                        "tooltipText" => t('Tooltip','vendorNameTooltip'),
                                        "value" => (isset($vendor) ? $vendor : ""),
                                        "disabled" => true
                                     );
                                     
        $input_descriptors0[] = array(
                                        "name" => "attribute_presentation",
                                        "caption" => t('all','Attribute'),
                                        "type" => "text",
                                        "tooltipText" => t('Tooltip','attributeTooltip'),
                                        "value" => (isset($attribute) ? $attribute : ""),
                                        "disabled" => true
                                     );
                              
        $input_descriptors0[] = array(
                                        "name" => "type",
                                        "caption" => t('all','Type'),
                                        "type" => "text",
                                        "datalist" => $valid_attributeTypes,
                                        "value" => ((isset($type)) ? $type : ""),
                                        "tooltipText" => t('Tooltip','typeTooltip'),
                                     );
        
        $input_descriptors0[] = array(
                                        "name" => "RecommendedOP",
                                        "caption" => t('all','RecommendedOP'),
                                        "type" => "text",
                                        "datalist" => $valid_ops,
                                        "value" => ((isset($op)) ? $op : ""),
                                        "tooltipText" => t('Tooltip','RecommendedOPTooltip'),
                                     );
        
        $input_descriptors0[] = array(
                                        "name" => "RecommendedTable",
                                        "caption" => t('all','RecommendedTable'),
                                        "type" => "text",
                                        "datalist" => $valid_tables,
                                        "value" => ((isset($table)) ? $table : ""),
                                        "tooltipText" => t('Tooltip','RecommendedTableTooltip'),
                                     );
        
        $input_descriptors0[] = array(
                                        "name" => "RecommendedHelper",
                                        "caption" => t('all','RecommendedHelper'),
                                        "type" => "text",
                                        "datalist" => $valid_recommendedHelpers,
                                        "value" => ((isset($helper)) ? $helper : ""),
                                        "tooltipText" => t('Tooltip','RecommendedHelperTooltip'),
                                     );
        
        $input_descriptors0[] = array(
                                        "name" => "RecommendedTooltip",
                                        "caption" => t('all','RecommendedTooltip'),
                                        "type" => "textarea",
                                        "tooltipText" => t('Tooltip','RecommendedTooltipTooltip'),
                                        "value" => (isset($tooltip) ? $tooltip : "")
                                     );
        
        $input_descriptors0[] = array(
                                        "name" => "csrf_token",
                                        "type" => "hidden",
                                        "value" => dalo_csrf_token(),
                                     );

        $input_descriptors0[] = array(
                                        'type' => 'submit',
                                        'name' => 'submit',
                                        'value' => t('buttons','apply')
                                     );
        
        open_form();
        
        open_fieldset($fieldset0_descriptor);
        
        foreach ($input_descriptors0 as $input_descriptor) {
            print_form_component($input_descriptor);
        }
        
        close_fieldset();
        
        close_form();
    }

    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    // custom validation structures
    $valid_tables = array("check", "reply");

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (array_key_exists('csrf_token', $_POST) && isset($_POST['csrf_token']) && dalo_check_csrf_token($_POST['csrf_token'])) {
            
            $vendor = (array_key_exists('vendor', $_POST) && !empty(str_replace("%", "", trim($_POST['vendor']))))
                    ? str_replace("%", "", trim($_POST['vendor'])) : "";
            $vendor_enc = (!empty($vendor)) ? htmlspecialchars($vendor, ENT_QUOTES, 'UTF-8') : "";

            $attribute = (array_key_exists('attribute', $_POST) && !empty(str_replace("%", "", trim($_POST['attribute']))))
                       ? str_replace("%", "", trim($_POST['attribute'])) : "";
            $attribute_enc = (!empty($attribute)) ? htmlspecialchars($attribute, ENT_QUOTES, 'UTF-8') : "";
            
            $type = (array_key_exists('type', $_POST) && isset($_POST['type']) &&
                     in_array($_POST['type'], $valid_attributeTypes))
                  ? $_POST['type'] : "";

            $op = (array_key_exists('RecommendedOP', $_POST) && isset($_POST['RecommendedOP']) &&
                   in_array($_POST['RecommendedOP'], $valid_ops))
                ? $_POST['RecommendedOP'] : "";
            
            $table = (array_key_exists('RecommendedTable', $_POST) && isset($_POST['RecommendedTable']) &&
                      in_array($_POST['RecommendedTable'], $valid_tables))
                   ? $_POST['RecommendedTable'] : "";

            $helper = (array_key_exists('RecommendedHelper', $_POST) && isset($_POST['RecommendedHelper']) &&
                       in_array($_POST['RecommendedHelper'], $valid_recommendedHelpers))
                    ? $_POST['RecommendedHelper'] : "";

            $tooltip = (array_key_exists('RecommendedTooltip', $_POST) &&
                        !empty(str_replace("%", "", trim($_POST['RecommendedTooltip']))))
                     ? str_replace("%", "", trim($_POST['RecommendedTooltip'])) : "";

            if (empty($vendor) || empty($attribute)) {
                // vendor and attribute are required
                $failureMsg = "vendor and/or attribute are empty or invalid";
                $logAction .= "Failed adding new attribute [$attribute] (possible empty/invalid vendor and/or attribute) on page: ";
                include('library/opendb.php');
                
                $sql = sprintf("SELECT DISTINCT(Vendor) FROM %s WHERE attribute='%s'",
                               $configValues['CONFIG_DB_TBL_DALODICTIONARY'], $dbSocket->escapeSimple($attribute));
                $res = $dbSocket->query($sql);
                $logDebugSQL .= "$sql;\n";

                $vendors = array();
                while ($row = $res->fetchrow()) {
                    $vendors[] = $row[0];
                }
                
                if (count($vendors) > 0) {
                    // already present
                    $format = "An attribute with the same name is already present in another dictionary (attribute: %s, vendor(s): %s)";
                    $failureMsg = sprintf($format, $attribute_enc, htmlspecialchars(implode(", ", $vendors), ENT_QUOTES, 'UTF-8'));
                    $logAction .= sprintf("Failed to add an attribute [$format] on page: ", $attribute, implode(", ", $vendors));
                    
                } else {
                    
                    $sql = sprintf("INSERT INTO %s (id, Type, Attribute, Value, Format, Vendor, RecommendedOP,
                                                    RecommendedTable, RecommendedHelper, RecommendedTooltip)
                                            VALUES (0, '%s', '%s', '', '', '%s', '%s', '%s', '%s', '%s')",
                                   $configValues['CONFIG_DB_TBL_DALODICTIONARY'],
                                   $dbSocket->escapeSimple($type), $dbSocket->escapeSimple($attribute),
                                   $dbSocket->escapeSimple($vendor), $dbSocket->escapeSimple($op),
                                   $dbSocket->escapeSimple($table), $dbSocket->escapeSimple($helper),
                                   $dbSocket->escapeSimple($tooltip));
                    $res = $dbSocket->query($sql);
                    $logDebugSQL .= "$sql;\n";
                    
                    if (!DB::isError($res)) {
                        $format = "The new attribute has been inserted in the dictionary (attribute: %s, vendor: %s)";
                        $successMsg = sprintf($format, $attribute_enc, $vendor_enc);
                        $logAction .= sprintf("$format on page: ", $attribute, $vendor);
                    } else {
                        $format = "An error occurred when adding the new attribute to a dictionary (attribute: %s, vendor: %s)";
                        $failureMsg = sprintf($format, $attribute_enc, $vendor_enc);
                        $logAction .= sprintf("Failed to add an attribute [$format] on page: ", $attribute, $vendor);
                    }
                }
                
                include('library/closedb.php');
            
        } else {
            // csrf
            $failureMsg = "CSRF token error";
            $logAction .= "$failureMsg on page: ";
    
    
    if (!isset($successMsg)) {
        $fieldset0_descriptor = array(
                                        "title" => t('title','VendorAttribute'),
                                     );
        $input_descriptors0 = array();
        $input_descriptors0[] = array(
                                        "name" => "vendor",
                                        "caption" => t('all','VendorName'),
                                        "type" => "text",
                                        "tooltipText" => t('Tooltip','vendorNameTooltip'),
                                        "value" => (isset($vendor) ? $vendor : "")
                                     );
                                     
        $input_descriptors0[] = array(
                                        "name" => "attribute",
                                        "caption" => t('all','Attribute'),
                                        "type" => "text",
                                        "tooltipText" => t('Tooltip','attributeTooltip'),
                                        "value" => (isset($attribute) ? $attribute : "")
                                     );
                              
        $input_descriptors0[] = array(
                                        "name" => "type",
                                        "caption" => t('all','Type'),
                                        "type" => "text",
                                        "datalist" => $valid_attributeTypes,
                                        "value" => ((isset($type)) ? $type : ""),
                                        "tooltipText" => t('Tooltip','typeTooltip'),
                                     );
        $input_descriptors0[] = array(
                                        "name" => "RecommendedOP",
                                        "caption" => t('all','RecommendedOP'),
                                        "type" => "text",
                                        "datalist" => $valid_ops,
                                        "value" => ((isset($op)) ? $op : ""),
                                        "tooltipText" => t('Tooltip','RecommendedOPTooltip'),
                                     );
        $input_descriptors0[] = array(
                                        "name" => "RecommendedTable",
                                        "caption" => t('all','RecommendedTable'),
                                        "type" => "text",
                                        "datalist" => $valid_tables,
                                        "value" => ((isset($table)) ? $table : ""),
                                        "tooltipText" => t('Tooltip','RecommendedTableTooltip'),
                                     );
        
        $input_descriptors0[] = array(
                                        "name" => "RecommendedHelper",
                                        "caption" => t('all','RecommendedHelper'),
                                        "type" => "text",
                                        "datalist" => $valid_recommendedHelpers,
                                        "value" => ((isset($helper)) ? $helper : ""),
                                        "tooltipText" => t('Tooltip','RecommendedHelperTooltip'),
                                     );
        
        $input_descriptors0[] = array(
                                        "name" => "RecommendedTooltip",
                                        "caption" => t('all','RecommendedTooltip'),
                                        "type" => "textarea",
                                        "tooltipText" => t('Tooltip','RecommendedTooltipTooltip'),
                                        "value" => (isset($tooltip) ? $tooltip : "")
                                     );
        
        $input_descriptors0[] = array(
                                        "name" => "csrf_token",
                                        "type" => "hidden",
                                        "value" => dalo_csrf_token(),
                                     );

        $input_descriptors0[] = array(
                                        'type' => 'submit',
                                        'name' => 'submit',
                                        'value' => t('buttons','apply')
                                     );

        open_form();
        
        open_fieldset($fieldset0_descriptor);
        
        foreach ($input_descriptors0 as $input_descriptor) {
            print_form_component($input_descriptor);
        }
        
        close_fieldset();
        
        close_form();
    }

    // get attribute name passed to us from menu-mng-rad-attributes.php
    $attribute = (array_key_exists('attribute', $_GET) && !empty(str_replace("%", "", trim($_GET['attribute']))))
               ? str_replace("%", "", trim($_GET['attribute'])) : "";
    if (!empty($attribute)) {
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    include_once('library/config_read.php');
    include("library/validation.php");
    include("library/layout.php");
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");

        $counter = 0;
            printf('<tr id="row-%d">', $counter);
    
    <input type="hidden" name="csrf_token" value="<?= dalo_csrf_token() ?>">
    
            $sql1 = sprintf("SELECT groupname, priority FROM %s WHERE username='%s' ORDER BY priority ASC, groupname ASC",
    $username = (array_key_exists('username', $_GET) && !empty(str_replace("%", "", trim($_GET['username']))))
              ? str_replace("%", "", trim($_GET['username'])) : "";

    // print HTML prologue
    $extra_js = array(
        "library/javascript/ajax.js",
        "library/javascript/ajaxGeneric.js"
    );
    
    $title = t('Intro','mngsearch.php');
    
    print_html_prologue($title, $langCode, array(), $extra_js);

    echo '<div id="contentnorightbar">';
    
    $log = "visited page: ";


    echo '<div id="contentnorightbar">';

    include_once('include/management/actionMessages.php');
    include('include/config/logging.php');
    print_footer_and_html_epilogue();

?>
<?php 
    include ("library/checklogin.php");

    $log = "visited page: ";

    // print HTML prologue
    $help = t('helpPage','repbatch');
    echo '<div id="contentnorightbar">';
    print_title_and_help($title, $help);
    
    print_footer_and_html_epilogue();
<?php 
    include ("library/checklogin.php");

    
    echo '<div id="contentnorightbar">';
    
    print_footer_and_html_epilogue();
?>
    include("library/validation.php");
    include_once('library/config_read.php');
    
    $log = "visited page: ";

    include_once("lang/main.php");
    include("library/layout.php");
    echo '<div id="contentnorightbar">';
    
    print_footer_and_html_epilogue();
?>
    include_once('library/config_read.php');
    
    $log = "visited page: ";

    include_once("lang/main.php");
    include("library/layout.php");
    echo '<div id="contentnorightbar">';
    

    print_footer_and_html_epilogue();
?>
    include_once('library/config_read.php');

    $log = "visited page: ";
    include_once("lang/main.php");
    include("library/layout.php");
    
    echo '<div id="contentnorightbar">';
    

    print_footer_and_html_epilogue();
?>
    include_once("lang/main.php");    

    print_footer_and_html_epilogue();
?>
<?php 
    include ("library/checklogin.php");
    $log = "visited page: ";

    include("menu-reports.php");
    
    echo '<div id="contentnorightbar">';
    
    print_footer_and_html_epilogue();
?>
    include_once("lang/main.php");
    include("library/layout.php");
    
    echo '<div id="contentnorightbar">';
    
    
    print_footer_and_html_epilogue();
?>
    
    include_once("lang/main.php");
    echo '<div id="contentnorightbar">';
    
    
    include('include/config/logging.php');
    print_footer_and_html_epilogue();
    
    include_once("lang/main.php");

    echo '<div id="contentnorightbar">';
    include('include/config/logging.php');
    print_footer_and_html_epilogue();

?>
<?php 
 *
 * Authors:    Liran Tal <liran@enginx.com>
 *             Filippo Lauria <filippo.lauria@iit.cnr.it>
    include ("library/checklogin.php");

    include_once('library/config_read.php');

    
    echo '<div id="contentnorightbar">';
    
    include('include/config/logging.php');
    print_footer_and_html_epilogue();
    include_once("lang/main.php");
    include("library/layout.php");
    include_once('library/config_read.php');
    
    include_once("lang/main.php");
    include("library/validation.php");
    include("library/layout.php");
    $username = (array_key_exists('username', $_GET) && !empty(str_replace("%", "", trim($_GET['username']))))
              ? str_replace("%", "", trim($_GET['username'])) : "";
    $logQuery = "performed query for ";
    if (!empty($username)) {
         $logQuery .= "username(s) starting with [$username] ";
    } else {
        $logQuery .= "all usernames ";
    $logQuery .= "on page: ";