CVE-2022-4630: Incorrect Permission Assignment for Critical Resource (CWE-732)
value: Sensitive Cookie Without 'HttpOnly' Flag in GitHub repository lirantal/daloradius prior to master.
CWE description: The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.
CVSS v3 base score: 5.3
Published: 2022-12-21T18:15Z
Repository: https://github.com/lirantal/daloradius
Language: PHP
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 date: 2022-12-16 14:45:00 +0100
Commit message: Improved attribute dictionaries management feature (#316)

Improved layout and other minor features
Diff: diff --git a/acct-active.php b/acct-active.php
index e3c645b3..f47a76c3 100644
--- a/acct-active.php
+++ b/acct-active.php
@@ -25,12 +25,13 @@
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
     include_once('library/config_read.php');
 
-    // include validation utils
+    include_once("lang/main.php");
     include("library/validation.php");
+    include("library/layout.php");
 
     // validate this parameter before including menu
     $username = (array_key_exists('username', $_GET) && isset($_GET['username']))
                     ? str_replace("%", "", $_GET['username']) : "";
     $username_enc = (!empty($username)) ? htmlspecialchars($username, ENT_QUOTES, 'UTF-8') : "";
@@ -53,14 +54,10 @@
     // init logging variables
     $log = "visited page: ";
     $logQuery = "performed query for user [$username] and start date [$startdate] and end date [$enddate] on page: ";
     $logDebugSQL = "";
     
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
-
     // print HTML prologue
     $title = t('Intro','acctactive.php');
     $help = t('helpPage','acctactive');
 
     print_html_prologue($title, $langCode);
diff --git a/acct-all.php b/acct-all.php
index 09898577..826b3fd9 100644
--- a/acct-all.php
+++ b/acct-all.php
@@ -25,22 +25,19 @@
     $operator = $_SESSION['operator_user'];
     
     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 logging variables
     $log = "visited page: ";
     $logQuery = "performed query for all accounting records on page: ";
     $logDebugSQL = "";
 
-    include("library/validation.php");
-
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
-
     // print HTML prologue
     $title = t('Intro','acctall.php');
     $help = t('helpPage','acctall');
 
     print_html_prologue($title, $langCode);
diff --git a/acct-custom-query.php b/acct-custom-query.php
index 5eb8afd1..6b52fec1 100644
--- a/acct-custom-query.php
+++ b/acct-custom-query.php
@@ -23,23 +23,24 @@
 
     include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     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 logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
 
     // set session's page variable
     $_SESSION['PREV_LIST_PAGE'] = $_SERVER['REQUEST_URI'];
 
-    include_once('library/config_read.php');
-    
-    include("library/validation.php");
-    
     $sqlfields = (array_key_exists('sqlfields', $_GET) && !empty($_GET['sqlfields']) && is_array($_GET['sqlfields']) &&
                   array_intersect($_GET['sqlfields'], $acct_custom_query_options_all) == $_GET['sqlfields'])
                ? $_GET['sqlfields'] : $acct_custom_query_options_default;
     
     $cols = array();
@@ -84,13 +85,10 @@
     //feed the sidebar variables
     $accounting_custom_startdate = $startdate;
     $accounting_custom_enddate = $enddate;
     $accounting_custom_value = $where_value_enc;
 
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
 
     // print HTML prologue
     $extra_js = array(
         "library/javascript/ajax.js",
         "library/javascript/ajaxGeneric.js"
@@ -201,16 +199,18 @@
             
         echo '</thead>'
            . '<tbody>';
 
         // inserting the values of each field from the database to the table
+        $count = 0;
         while($row = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
-            echo "<tr>";
+            printf('<tr id="row-%d">', $count);
             foreach ($sqlfields as $field) {
                 printf("<td>%s</td>", htmlspecialchars($row[$field], ENT_QUOTES, 'UTF-8'));
             }
-            echo "</tr>";
+            echo '</tr>';
+            $count++;
         }
 
         echo '</tbody>';
 
         // tfoot
diff --git a/acct-custom.php b/acct-custom.php
index d598c02e..7c652251 100644
--- a/acct-custom.php
+++ b/acct-custom.php
@@ -25,14 +25,12 @@
     $operator = $_SESSION['operator_user'];
 
     include_once('library/config_read.php');
     $log = "visited page: ";
 
-    include("library/validation.php");
-
     include_once("lang/main.php");
-    
+    include("library/validation.php");
     include("library/layout.php");
 
     // print HTML prologue
     $title = t('Intro','acctcustom.php');
     $help = t('helpPage','acctcustom');
diff --git a/acct-date.php b/acct-date.php
index 870c278e..145f7829 100644
--- a/acct-date.php
+++ b/acct-date.php
@@ -25,12 +25,13 @@
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
     include_once('library/config_read.php');
 
-    // include validation utils
+    include_once("lang/main.php");
     include("library/validation.php");
+    include("library/layout.php");
     
     // validate this parameter before including menu
     $username = (array_key_exists('username', $_GET) && isset($_GET['username']))
                     ? str_replace("%", "", $_GET['username']) : "";
     $username_enc = (!empty($username)) ? htmlspecialchars($username, ENT_QUOTES, 'UTF-8') : "";
@@ -53,13 +54,10 @@
     // init logging variables
     $log = "visited page: ";
     $logQuery = "performed query for user [$username] and start date [$startdate] and end date [$enddate] on page: ";
     $logDebugSQL = "";
 
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
 
     // print HTML prologue
     $title = t('Intro','acctdate.php');
     $help = t('helpPage','acctdate');
 
diff --git a/acct-ipaddress.php b/acct-ipaddress.php
index f4948162..df8e6fb2 100644
--- a/acct-ipaddress.php
+++ b/acct-ipaddress.php
@@ -25,11 +25,13 @@
     $operator = $_SESSION['operator_user'];
 
     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");
     
     // validate this parameter before including menu
     $ipaddress = (array_key_exists('ipaddress', $_GET) && isset($_GET['ipaddress']) &&
                   preg_match(LOOSE_IP_REGEX, $_GET['ipaddress'], $m) !== false) ? $_GET['ipaddress'] : "";
     $ipaddress_enc = (!empty($ipaddress)) ? htmlspecialchars($ipaddress, ENT_QUOTES, 'UTF-8') : "";
@@ -41,14 +43,12 @@
     $log = "visited page: ";
     $logQuery = sprintf("performed query for %s on page: ",
                         ((!empty($ipaddress)) ? "IP address [$ipaddress]" : "all IP addresses"));
     $logDebugSQL = "";
     
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
     
+    // print HTML prologue
     $title = t('Intro','acctipaddress.php');
     $help = t('helpPage','acctipaddress');
     
     print_html_prologue($title, $langCode);
 
diff --git a/acct-main.php b/acct-main.php
index f3c5c2a8..bc2bdc5f 100644
--- a/acct-main.php
+++ b/acct-main.php
@@ -42,6 +42,7 @@
     echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
     
     include('include/config/logging.php');
     print_footer_and_html_epilogue();
+
 ?>
diff --git a/acct-nasipaddress.php b/acct-nasipaddress.php
index a41340c6..4f2ee10a 100644
--- a/acct-nasipaddress.php
+++ b/acct-nasipaddress.php
@@ -25,11 +25,13 @@
     $operator = $_SESSION['operator_user'];
 
     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");
 
     // validate this parameter before including menu
     $onlyactive = (array_key_exists('only-active', $_GET) && isset($_GET['only-active']));
     
     // validate this parameter before including menu
@@ -44,14 +46,11 @@
     $log = "visited page: ";
     $logQuery = sprintf("performed query for %s on page: ",
                         ((!empty($nasipaddress)) ? "NAS IP address [$nasipaddress]" : "all NAS IP addresses"));
     $logDebugSQL = "";
     
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
-    
+    // print HTML prologue
     $title = t('Intro','acctnasipaddress.php');
     $help = t('helpPage','acctnasipaddress');
     
     print_html_prologue($title, $langCode);
 
diff --git a/acct-username.php b/acct-username.php
index eaa1337d..53c534b0 100644
--- a/acct-username.php
+++ b/acct-username.php
@@ -25,13 +25,17 @@
     $operator = $_SESSION['operator_user'];
     
     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");
+
     // validate this parameter before including menu
-    $username = (array_key_exists('username', $_GET) && isset($_GET['username']))
-                    ? str_replace("%", "", $_GET['username']) : "";
+    $username = (array_key_exists('username', $_GET) && !empty(str_replace("%", "", trim($_GET['username']))))
+              ? str_replace("%", "", trim($_GET['username'])) : "";
     $username_enc = (!empty($username)) ? htmlspecialchars($username, ENT_QUOTES, 'UTF-8') : "";
 
     // init logging variables
     $log = "visited page: ";
     $logQuery = "performed query ";
@@ -42,15 +46,10 @@
     $logDebugSQL = "";
 
     //feed the sidebar variables
     $accounting_username = $username_enc;
     
-    include("library/validation.php");
-
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
 
     // print HTML prologue
     $title = t('Intro','acctusername.php');
     $help = t('helpPage','acctusername');
 
diff --git a/bill-history-query.php b/bill-history-query.php
index 825f56f4..39ebc0c2 100644
--- a/bill-history-query.php
+++ b/bill-history-query.php
@@ -1,6 +1,6 @@
-<?php
+<?php 
 /*
  *********************************************************************************************************
  * daloRADIUS - RADIUS Web Platform
  * Copyright (C) 2007 - Liran Tal <liran@enginx.com> All Rights Reserved.
  *
@@ -13,273 +13,200 @@
  * along with this program; if not, write to the Free Software
  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  *
  *********************************************************************************************************
  *
- * Authors:	Liran Tal <liran@enginx.com>
+ * Authors:    Liran Tal <liran@enginx.com>
+ *             Filippo Lauria <filippo.lauria@iit.cnr.it>
  *
  *********************************************************************************************************
  */
 
-    include ("library/checklogin.php");
+    include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
-	include('library/check_operator_perm.php');
-	
-	//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";
+    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");
 
-	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');
+    // init loggin variables
     $log = "visited page: ";
-    $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';
+    $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();
 
 ?>
-
-
-
-<?php
-	include('include/config/logging.php');
-?>
-
-		</div>
-		
-		<div id="footer">
-		
-								<?php
-        include 'page-footer.php';
-?>
-
-		
-		</div>
-		
-</div>
-</div>
-
-
-</body>
-</html>
diff --git a/bill-history.php b/bill-history.php
index c61c1d09..600778dd 100644
--- a/bill-history.php
+++ b/bill-history.php
@@ -26,16 +26,16 @@
 
     include_once('library/config_read.php');
     $log = "visited page: ";
 
     include_once("lang/main.php");
-    
+    include("library/validation.php");
     include("library/layout.php");
 
     // print HTML prologue
     $title = t('Intro','billhistorymain.php');
-    $help = t('helpPage','billhistorymain');
+    $help = "";
     
     print_html_prologue($title, $langCode);
 
     include("menu-bill-history.php");
     
diff --git a/bill-main.php b/bill-main.php
index ce30e648..ef0cd0c4 100644
--- a/bill-main.php
+++ b/bill-main.php
@@ -39,20 +39,10 @@
 
     include("menu-bill-pos.php");
     
     echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
-    echo '</div><!-- #contentnorightbar -->'
-       . '<div id="footer">';
 
     include('include/config/logging.php');
-    include('page-footer.php');
-    
-    echo '</div><!-- #footer -->';
+    print_footer_and_html_epilogue();
 
 ?>
-
-        </div>
-    </div>
-
-</body>
-</html>
diff --git a/bill-merchant-transactions.php b/bill-merchant-transactions.php
index 0b47a717..0c2fa050 100644
--- a/bill-merchant-transactions.php
+++ b/bill-merchant-transactions.php
@@ -22,308 +22,214 @@
 
     include ("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
 	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['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);
+	include_once('library/config_read.php');
+    
+    include_once("lang/main.php");
+    include("library/validation.php");
+    include("library/layout.php");
 
-	//feed the sidebar variables
+    // 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_date_startdate = $startdate;
 	$billing_date_enddate = $enddate;
-	//$billing_paypal_firstname = $value;
-	$billing_paypal_payeremail = $payer_email;
-	$billing_paypal_paymentaddressstatus = $payment_address_status;
-	$billing_paypal_payerstatus = $payer_status;
+	$billing_paypal_payeremail = $payer_email_enc;
 	$billing_paypal_paymentstatus = $payment_status;
 	$billing_paypal_vendor_type = $vendor_type;
 
-
-	include_once('library/config_read.php');
-    $log = "visited page: ";
-    $logQuery = "performed query for all accounting records on page: ";
-
-?>
-
-<?php
+    //~ $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);
+    
 	include("menu-bill-merchant.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';
+    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();
 
 ?>
-
-
-
-<?php
-	include('include/config/logging.php');
-?>
-
-		</div>
-		
-		<div id="footer">
-		
-								<?php
-        include 'page-footer.php';
-?>
-
-		
-		</div>
-		
-</div>
-</div>
-
-
-</body>
-</html>
diff --git a/bill-merchant.php b/bill-merchant.php
index 742c65da..5d3d1953 100644
--- a/bill-merchant.php
+++ b/bill-merchant.php
@@ -26,11 +26,11 @@
 
     include_once('library/config_read.php');
     $log = "visited page: ";
 
     include_once("lang/main.php");
-    
+    include("library/validation.php");
     include("library/layout.php");
 
     // print HTML prologue
     $title = t('Intro','paypalmain.php');
     $help = "";
diff --git a/bill-pos-edit.php b/bill-pos-edit.php
index ee6aa553..d0920e50 100644
--- a/bill-pos-edit.php
+++ b/bill-pos-edit.php
@@ -23,21 +23,21 @@
 
     include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
+    include_once('library/config_read.php');
 
+    include_once("lang/main.php");
+    include_once("library/validation.php");
+    include("library/layout.php");
+    
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
     
-    include_once('library/config_read.php');
-    
-    // we import validation facilities
-    include_once("library/validation.php");
-    
     // required later
     $currDate = date('Y-m-d H:i:s');
     $currBy = $operator;
     
     include('library/opendb.php');
@@ -383,14 +383,10 @@
     include('library/closedb.php');
 
     $hiddenPassword = (strtolower($configValues['CONFIG_IFACE_PASSWORD_HIDDEN']) == "yes")
                     ? 'password' : 'text';
     
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
-
     // print HTML prologue
     $extra_css = array(
         // css tabs stuff
         "css/tabs.css"
     );
@@ -675,16 +671,10 @@ window.onload = function(){
     </div><!-- #OtherInfo-tab -->
 
 <?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']);
-    }
+    print_back_to_previous_page();
     
     include('include/config/logging.php');
     print_footer_and_html_epilogue();
 ?>
diff --git a/bill-pos-new.php b/bill-pos-new.php
index bd4b4bb7..8b05ebe9 100644
--- a/bill-pos-new.php
+++ b/bill-pos-new.php
@@ -25,20 +25,21 @@
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
     include_once('library/config_read.php');
 
+    include_once("lang/main.php");
+    include_once("library/validation.php");
+    include("library/layout.php");
+
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
 
     include('include/management/pages_common.php');
 
-    // we import validation facilities
-    include_once("library/validation.php");
-
     // if cleartext passwords are not allowed, 
     // we remove Cleartext-Password from the $valid_passwordTypes array
     if (isset($configValues['CONFIG_DB_PASSWORD_ENCRYPTION']) &&
         strtolower($configValues['CONFIG_DB_PASSWORD_ENCRYPTION']) !== 'cleartext') {
         $valid_passwordTypes = array_diff($valid_passwordTypes, array("Cleartext-Password"));
@@ -453,13 +454,10 @@
     include_once('library/config_read.php');
     
     $hiddenPassword = (strtolower($configValues['CONFIG_IFACE_PASSWORD_HIDDEN']) == "yes")
                     ? 'password' : 'text';
     
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
 
     // print HTML prologue
     $extra_css = array(
         // css tabs stuff
         "css/tabs.css"
diff --git a/bill-rates-date.php b/bill-rates-date.php
index 6da71d14..dbe98b29 100644
--- a/bill-rates-date.php
+++ b/bill-rates-date.php
@@ -25,11 +25,18 @@
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
     include_once('library/config_read.php');
 
+    // init loggin variables
+    $log = "visited page: ";
+    $logQuery = "performed query for listing of records on page: ";
+    $logDebugSQL = "";
+
+    include_once("lang/main.php");
     include("library/validation.php");
+    include("library/layout.php");
 
     //setting values for the order by and order type variables
     // and in other cases we partially strip some character,
     // and leave validation/escaping to other functions used later in the script
     $ratename = (array_key_exists('ratename', $_GET) && isset($_GET['ratename']))
@@ -55,19 +62,11 @@
     $billing_date_ratename = $ratename;
     $billing_date_username = $username;
     $billing_date_startdate = $startdate;
     $billing_date_enddate = $enddate;
 
-    // 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");
-
     // print HTML prologue
     $extra_css = array();
     
     $extra_js = array(
         "library/javascript/ajax.js",
diff --git a/config-db.php b/config-db.php
index 02e5ba23..02c281cc 100644
--- a/config-db.php
+++ b/config-db.php
@@ -23,17 +23,17 @@
 
     include ("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
-
     include_once('library/config_read.php');
-    $log = "visited page: ";
     
     include_once("lang/main.php");
-    
     include("library/validation.php");
+    include("library/layout.php");
+    
+    $log = "visited page: ";
     
     $db_tbl_param_label = array(
                                     'CONFIG_DB_TBL_RADCHECK' => t('all','radcheck'), 
                                     'CONFIG_DB_TBL_RADREPLY' => t('all','radreply'),
                                     'CONFIG_DB_TBL_RADGROUPREPLY' => t('all','radgroupreply'), 
@@ -111,12 +111,10 @@
             $logAction .= "$failureMsg on page: ";
         }
     }
     
     
-    include("library/layout.php");
-
     // print HTML prologue
     $extra_css = array(
         // css tabs stuff
         "css/tabs.css"
     );
diff --git a/config-lang.php b/config-lang.php
index 4e15ca67..c2585585 100644
--- a/config-lang.php
+++ b/config-lang.php
@@ -23,15 +23,17 @@
 
     include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
-
     include_once('library/config_read.php');
-    $log = "visited page: ";
 
+    include_once("lang/main.php");
     include("library/validation.php");
+    include("library/layout.php");
+    
+    $log = "visited page: ";
 
     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         if (array_key_exists('csrf_token', $_POST) && isset($_POST['csrf_token']) && dalo_check_csrf_token($_POST['csrf_token'])) {
         
             if (array_key_exists('CONFIG_LANG', $_POST) && !empty(strtolower(trim($_POST['CONFIG_LANG']))) &&
@@ -46,14 +48,11 @@
             $failureMsg = "CSRF token error";
             $logAction .= "$failureMsg on page: ";
         }
     }
 
-    include_once("lang/main.php");
     
-    include("library/layout.php");
-
     // print HTML prologue
     $title = t('Intro','configlang.php');
     $help = t('helpPage','configlang');
     
     print_html_prologue($title, $langCode);
diff --git a/config-reports.php b/config-reports.php
index 8e2fba9a..803244fb 100644
--- a/config-reports.php
+++ b/config-reports.php
@@ -1,6 +1,6 @@
-<?php
+<?php 
 /*
  *********************************************************************************************************
  * daloRADIUS - RADIUS Web Platform
  * Copyright (C) 2007 - Liran Tal <liran@enginx.com> All Rights Reserved.
  *
@@ -18,17 +18,17 @@
  * Authors:    Liran Tal <liran@enginx.com>
  *             Filippo Lauria <filippo.lauria@iit.cnr.it>
  *
  *********************************************************************************************************
  */
- 
-    include("library/checklogin.php");
+
+    include ("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     include_once('library/config_read.php');
-    
-    
+    $log = "visited page: ";
+
     include_once("lang/main.php");
     
     include("library/layout.php");
 
     // print HTML prologue
@@ -36,29 +36,13 @@
     $help = t('helpPage','configmain');
     
     print_html_prologue($title, $langCode);
 
     include("menu-config-reports.php");
-
-?>
-                
-        <div id="contentnorightbar">
-
-<?php
+    
+    echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
-?>
-
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
-    $log = "visited page: ";
-
+    
     include('include/config/logging.php');
-    include('page-footer.php');
-?>
-        </div><!-- #footer -->
-    </div>
-</div>
+    print_footer_and_html_epilogue();
 
-</body>
-</html>
+?>
diff --git a/gis-main.php b/gis-main.php
index 7273cc61..ec601bbe 100644
--- a/gis-main.php
+++ b/gis-main.php
@@ -72,20 +72,10 @@
     
     echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
     
     include_once('include/management/actionMessages.php');
-?>
-
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
+    
     include('include/config/logging.php');
-    include('page-footer.php');
-?>
-        </div><!-- #footer -->
-    </div>
-</div>
+    print_footer_and_html_epilogue();
 
-</body>
-</html>
+?>
diff --git a/graph-main.php b/graph-main.php
index 9626e617..749400ee 100644
--- a/graph-main.php
+++ b/graph-main.php
@@ -1,6 +1,6 @@
-<?php
+<?php 
 /*
  *********************************************************************************************************
  * daloRADIUS - RADIUS Web Platform
  * Copyright (C) 2007 - Liran Tal <liran@enginx.com> All Rights Reserved.
  *
@@ -19,13 +19,13 @@
  *             Filippo Lauria <filippo.lauria@iit.cnr.it>
  *
  *********************************************************************************************************
  */
 
-    include("library/checklogin.php");
+    include ("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
-        
+
     include_once('library/config_read.php');
     $log = "visited page: ";
 
     include_once("lang/main.php");
     
@@ -36,25 +36,13 @@
     $help = t('helpPage','graphmain');
     
     print_html_prologue($title, $langCode);
 
     include("menu-graphs.php");
-
-?>
-        <div id="contentnorightbar">
-<?php
+    
+    echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
-?>
-
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
+    
     include('include/config/logging.php');
-    include('page-footer.php');
-?>
-        </div><!-- #footer -->
-    </div>
-</div>
+    print_footer_and_html_epilogue();
 
-</body>
-</html>
+?>
diff --git a/help-main.php b/help-main.php
index 8451cb4b..cb423c74 100644
--- a/help-main.php
+++ b/help-main.php
@@ -59,31 +59,11 @@
                 is required first <a href="https://lists.sourceforge.net/lists/listinfo/daloradius-users">here</a><br/><br/>
 
                 <b>daloRADIUS IRC</b>: you can find us at #daloradius on irc.freenode.net
             </p>
 
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
-    include('include/config/logging.php');
-    include('page-footer.php');
-?>
-        </div><!-- #footer -->
-    </div>
-</div>
-
-</body>
-</html>
-
-
 <?php
 
-    include ("library/checklogin.php");
-    $operator = $_SESSION['operator_user'];
-        
-	include_once('library/config_read.php');
-    $log = "visited page: ";
     include('include/config/logging.php');
+    print_footer_and_html_epilogue();
 
 ?>
-
diff --git a/include/management/userBilling.php b/include/management/userBilling.php
index 297e5166..54294744 100644
--- a/include/management/userBilling.php
+++ b/include/management/userBilling.php
@@ -12,135 +12,136 @@
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  *
  *********************************************************************************************************
- * Description:
- *              returns user billing information (rates, plans, etc)
+ * 
+ * Description:    returns user billing information (rates, plans, etc)
  *
- * Authors:     Liran Tal <liran@enginx.com>
+ * 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;
+}
 
 
 /*
  *********************************************************************************************************
  * userInvoiceAdd
  * general billing function to add invoices to the user based on the user_id
  *
- * $userId 				   the userbillinfo user id or the username (autodetects)
+ * $userId                    the userbillinfo user id or the username (autodetects)
  * $invoiceInfo            array holding the invoice information
  * $invoiceItems           array holding the invoice items information
  *
  *********************************************************************************************************
  */
 function userInvoiceAdd($userId, $invoiceInfo = array(), $invoiceItems = array()) {
 
-	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;
+    include(dirname(__FILE__).'/../../library/opendb.php');
 
+    $user_id = false;
 
-	$currDate = date('Y-m-d H:i:s');
-	$currBy = $_SESSION['operator_user'];
+    // 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
 
-	if (!$invoiceInfo)
-		$invoiceInfo = array();
+        $username = $dbSocket->escapeSimple($userId);
+        $sql = 'SELECT id FROM '.$configValues['CONFIG_DB_TBL_DALOUSERBILLINFO'].
+                ' WHERE username="'.$username.'"';
+        $res = $dbSocket->query($sql);
+        $logDebugSQL .= $sql . "\n";
 
-	// 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);
+        $row = $res->fetchRow();
+        $user_id = $row[0];
 
+    }
 
-	$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 something is not right with the user id (set to null, false, whatever) we abort
+    if (!$user_id)
+        return false;
 
-	// 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']."`" );
+    $currDate = date('Y-m-d H:i:s');
+    $currBy = $_SESSION['operator_user'];
 
-		if (!$invoice_id)
-			return false;
+    if (!$invoiceInfo)
+        $invoiceInfo = array();
 
-		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);
-			*/
+    // 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);
 
-			// 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";
+    $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');
+    include(dirname(__FILE__).'/../../library/closedb.php');
 
-	return true;
+    return true;
 
 }
 
 
-
-
-
 /*
  *********************************************************************************************************
  * userInvoicesStatus
  * $username            username to provide information of
  * $drawTable           if set to 1 (enabled) a toggled on/off table will be drawn
@@ -149,152 +150,134 @@ function userInvoiceAdd($userId, $invoiceInfo = array(), $invoiceItems = array()
  *
  *********************************************************************************************************
  */
 function userInvoicesStatus($user_id, $drawTable) {
 
-	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 ";
+    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);
+    $res = $dbSocket->query($sql);
+    $row = $res->fetchRow(DB_FETCHMODE_ASSOC);
 
-	$totalInvoices = $row['TotalInvoices'];
-	$totalBilled = $row['totalbilled'];
-	$totalPayed = $row['totalpayed'];
-	$openInvoices = $row['openInvoices'];
+    $totalInvoices = $row['TotalInvoices'];
+    $totalBilled = $row['totalbilled'];
+    $totalPayed = $row['totalpayed'];
+    $openInvoices = $row['openInvoices'];
 
-	include 'library/closedb.php';
+    include 'library/closedb.php';
 
-	if ($drawTable == 1) {
-		echo '
-				<fieldset>
+    if ($drawTable == 1) {
+        echo '
+                <fieldset>
 
                 <h302> User Invoices </h302>
-				<br/>
+                <br/>
 
-				<ul>
+                <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="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 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.'\';" />
+                    <input class="button" type="button" value="Show Payments"
+                        onClick="javascript:window.location = \'bill-payments-list.php?user_id='.$user_id.'\';" />
 
-					<br/><br/>
+                    <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="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>
+                    <li class="fieldset">
+                        <label for="totalbilled" class="form">Open Invoices</label>
+                        <input type="text" value="'.$openInvoices.'" disabled />
+                    </li>
 
-					<br/>
+                    <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 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">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">
+                        <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>
+                    <li class="fieldset">
+                    <br/>
+                    <hr><br/>
+                    <input type="submit" name="submit" value="Apply" tabindex=10000 class="button" />
+                    </li>
 
-			</ul>
+            </ul>
 
-			</fieldset>
+            </fieldset>
 
-			';
+            ';
 
-	}
+    }
 
 
 }
 
 
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
 /*
  *********************************************************************************************************
  * userBillingRatesSummary
  * $username            username to provide information of
- * $startdate		starting date, first accounting session
- * $enddate		ending date, last accounting session
- * $ratename		the rate to use for calculations
+ * $startdate        starting date, first accounting session
+ * $enddate        ending date, last accounting session
+ * $ratename        the rate to use for calculations
  * $drawTable           if set to 1 (enabled) a toggled on/off table will be drawn
  *
  * returns user connection information: uploads, download, session time, total billed, etc...
  *
  *********************************************************************************************************
  */
 function userBillingRatesSummary($username, $startdate, $enddate, $ratename, $drawTable) {
 
-	include_once('include/management/pages_common.php');
-	include 'library/opendb.php';
+    include_once('include/management/pages_common.php');
+    include 'library/opendb.php';
 
-	$username = $dbSocket->escapeSimple($username);			// sanitize variable for sql statement
+    $username = $dbSocket->escapeSimple($username);            // sanitize variable for sql statement
     $startdate = $dbSocket->escapeSimple($startdate);
     $enddate = $dbSocket->escapeSimple($enddate);
     $ratename = $dbSocket->escapeSimple($ratename);
 
     // get rate type
     $sql = "SELECT rateType FROM ".$configValues['CONFIG_DB_TBL_DALOBILLINGRATES']." WHERE ".$configValues['CONFIG_DB_TBL_DALOBILLINGRATES'].".rateName = '$ratename'";
     $res = $dbSocket->query($sql);
 
-	if ($res->numRows() == 0)
-		return;
+    if ($res->numRows() == 0)
+        return;
 
         $row = $res->fetchRow();
         list($ratetypenum, $ratetypetime) = explode("/",$row[0]);
 
         switch ($ratetypetime) {                                        // we need to translate any kind of time into seconds, so a minute is 60 seconds, an hour is 3600,
@@ -325,43 +308,43 @@ function userBillingRatesSummary($username, $startdate, $enddate, $ratename, $dr
         $rateDivisor = ($ratetypenum * $multiplicate);
 
         $sql = "SELECT distinct(".$configValues['CONFIG_DB_TBL_RADACCT'].".username), ".$configValues['CONFIG_DB_TBL_RADACCT'].".NASIPAddress, ".
                 $configValues['CONFIG_DB_TBL_RADACCT'].".AcctStartTime, SUM(".$configValues['CONFIG_DB_TBL_RADACCT'].".AcctSessionTime) AS AcctSessionTime, ".
                 $configValues['CONFIG_DB_TBL_DALOBILLINGRATES'].".rateCost, SUM(".$configValues['CONFIG_DB_TBL_RADACCT'].".AcctInputOctets) AS AcctInputOctets, ".
-		" SUM(".$configValues['CONFIG_DB_TBL_RADACCT'].".AcctOutputOctets) AS AcctOutputOctets ".
+        " SUM(".$configValues['CONFIG_DB_TBL_RADACCT'].".AcctOutputOctets) AS AcctOutputOctets ".
                 " FROM ".$configValues['CONFIG_DB_TBL_RADACCT'].", ".$configValues['CONFIG_DB_TBL_DALOBILLINGRATES']." WHERE (AcctStartTime >= '$startdate') and (AcctStartTime <= '$enddate') and (UserName = '$username') and (".$configValues['CONFIG_DB_TBL_DALOBILLINGRATES'].".rateName = '$ratename') GROUP BY UserName";
-	$res = $dbSocket->query($sql);
-	$row = $res->fetchRow(DB_FETCHMODE_ASSOC);
+    $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'];
+    $rateCost = $row['rateCost'];
+    $userUpload = toxbyte($row['AcctInputOctets']);
+    $userDownload = toxbyte($row['AcctOutputOctets']);
+    $userOnlineTime = time2str($row['AcctSessionTime']);
+    $sessionTime = $row['AcctSessionTime'];
 
-	$sumBilled = (($sessionTime/$rateDivisor)*$rateCost);
+    $sumBilled = (($sessionTime/$rateDivisor)*$rateCost);
 
         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('divBillingRatesSummary')\">Billing Summary</a>
-        	                </th>
-        	                </tr>
-        		</thead>
-        		</table>
-        	";
+                <thead>
+                    <tr>
+                            <th colspan='10' align='left'>
+                        <a class=\"table\" href=\"javascript:toggleShowDiv('divBillingRatesSummary')\">Billing Summary</a>
+                            </th>
+                            </tr>
+                </thead>
+                </table>
+            ";
 
                 echo "
                         <div id='divBillingRatesSummary' style='display:none;visibility:visible'>
-               		<table border='0' class='table1'>
-        		<thread>
+                       <table border='0' class='table1'>
+                <thread>
 
                         <tr>
                         <th scope='col' align='right'>
                         Username
                         </th>
@@ -434,191 +417,143 @@ function userBillingRatesSummary($username, $startdate, $enddate, $ratename, $dr
                         </th>
                         </tr>
 
                         </table>
 
-        		</div>
-        	";
+                </div>
+            ";
 
-	}
+    }
 
 
 }
 
 
-
 /*
  *********************************************************************************************************
  * userBillingPayPalSummary
- * $startdate		starting date, first accounting session
- * $enddate		ending date, last accounting session
+ * $startdate        starting date, first accounting session
+ * $enddate        ending date, last accounting session
  * $drawTable           if set to 1 (enabled) a toggled on/off table will be drawn
  *
  * returns user connection information: uploads, download, session time, total billed, etc...
  *
  *********************************************************************************************************
  */
-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>
-        	";
+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');
 
 }
diff --git a/library/validation.php b/library/validation.php
index 093023da..436d9504 100644
--- a/library/validation.php
+++ b/library/validation.php
@@ -63,10 +63,26 @@ $valid_passwordTypes = array(
 $valid_ops = array(
                     "=", ":=", ":=", "==", "+=", "!=", ">",
                     ">=", "<", "<=", "=~", "!~", "=*", "!*"
                   );
 
+$valid_recommendedHelpers = array(
+                                    "date", "datetime", "authtype", "framedprotocol", "servicetype",
+                                    "kbitspersecond", "bitspersecond", "volumebytes", "mikrotikRateLimit",
+                                 );
+
+$valid_attributeTypes = array(
+                                "string",
+                                "integer",
+                                "ipaddr",
+                                "date",
+                                "octets",
+                                "ipv6addr",
+                                "ifid",
+                                "abinary",
+                             );
+
 $valid_db_engines = array(
                             "mysql" => "MySQL",
                             "pgsql" => "PostgreSQL",
                             "odbc" => "ODBC",
                             "mssql" => "MsSQL",
@@ -84,10 +100,11 @@ $valid_db_engines = array(
 $valid_nastypes = array(
                          "other", "cisco", "computone", "livingston", "juniper", "max40xx", "multitech",
                          "netserver", "pathras", "patton", "portslave", "tc", "usrhiper"
                        );
 
+// accounting custom-query options list
 $acct_custom_query_options_all = array(
                                         "RadAcctId",
                                         "AcctSessionId",
                                         "AcctUniqueId",
                                         "UserName",
@@ -110,18 +127,114 @@ $acct_custom_query_options_all = array(
                                         "FramedProtocol",
                                         "FramedIPAddress",
                                         "AcctStartDelay",
                                         "AcctStopDelay"
                                     );
-                                    
+
+// accounting custom-query options selected by default
 $acct_custom_query_options_default = array(
                                             "UserName", "Realm", "NASIPAddress", "AcctStartTime", "AcctStopTime",
                                             "AcctSessionTime", "AcctInputOctets", "AcctOutputOctets", "CalledStationId",
                                             "CallingStationId", "AcctTerminateCause", "FramedIPAddress"
                                           );
 
+// 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"
+                                                   );
+
 // validating values
+
+$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" );
+
 $valid_languages = array(
                             "en" => "English", 
                             "it" => "Italian", 
                             "hu" => "Hungarian", 
                             "ro" => "Romanian",
diff --git a/menu-accounting-custom.php b/menu-accounting-custom.php
index b7d3e35f..0324dff0 100644
--- a/menu-accounting-custom.php
+++ b/menu-accounting-custom.php
@@ -21,11 +21,11 @@
  *********************************************************************************************************
  */
 
 // prevent this file to be directly accessed
 if (strpos($_SERVER['PHP_SELF'], '/menu-accounting-custom.php') !== false) {
-    header("Location: /index.php");
+    header("Location: index.php");
     exit;
 }
 
 include_once("lang/main.php");
 
diff --git a/menu-bill-history.php b/menu-bill-history.php
index 9eeaf39f..6eb0a83b 100644
--- a/menu-bill-history.php
+++ b/menu-bill-history.php
@@ -21,57 +21,21 @@
  *********************************************************************************************************
  */
 
 // prevent this file to be directly accessed
 if (strpos($_SERVER['PHP_SELF'], '/menu-bill-history.php') !== false) {
-    header("Location: /index.php");
+    header("Location: index.php");
     exit;
 }
 
 include_once("lang/main.php");
 
 $m_active = "Billing";
 
 include_once("include/menu/menu-items.php");
 include_once("include/menu/billing-subnav.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"
-                           );
-
 ?>
 
             <div id="sidebar">
                 <h2>Billing</h2>
                 
@@ -80,76 +44,102 @@ $checkboxes_checked = array(
                     <li>
                         <form name="billhistory" action="bill-history-query.php" method="GET" class="sidebar">
                             <input class="sidebutton" type="submit" name="submit" value="<?= t('button','ProcessQuery') ?>">
                             
                             <br><br>
-
-                            <h109><?= t('button','BetweenDates') ?></h109><br>
+<?php
+/*                            <h109><?= t('button','BetweenDates') ?></h109><br>
                             <label style="user-select: none" for="startdate"><?= t('all','StartingDate') ?></label>
                             <input name="startdate" type="date" id="startdate" tooltipText="<?= t('Tooltip','Date') ?>"
                                 value="<?= (isset($billing_date_startdate)) ? $billing_date_startdate : date("Y-m-01") ?>">
 
                             <label style="user-select: none" for="enddate"><?= t('all','EndingDate') ?></label>
                             <input name="enddate" type="date" id="enddate" tooltipText="<?= t('Tooltip','Date') ?>"
                                 value="<?= (isset($billing_date_enddate)) ? $billing_date_enddate : date("Y-m-t") ?>">
-                            
-                            <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>
+                            <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);
+?>
+
                             <br><br>
-                                
-                            <h109><?= t('button','AccountingFieldsinQuery') ?></h109><br>
 <?php
-                            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);
-                            }
+                            
+                            $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);
+                            
 ?>
-
-                            <br>Select:
-                            <a class="table" href="javascript:SetChecked(1,'sqlfields[]','billhistory')">All</a>
-                            <a class="table" href="javascript:SetChecked(0,'sqlfields[]','billhistory')">None</a>
-
+                            <a style="display: inline" href="#" onclick="select('all')">Select All</a>
+                            <a style="display: inline" href="#" onclick="select('none')">Select None</a>
                             <br><br>
-            
-                            <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>
+<?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>
    
                             <input class="sidebutton" type="submit" name="submit" value="<?= t('button','ProcessQuery') ?>">
                         </form>
                     </li>
                 </ul><!-- .subnav -->
             </div><!-- #sidebar -->
 
 <script>
+    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;
+        }
+    }
+    
     var tooltipObj = new DHTMLgoodies_formTooltip();
     tooltipObj.setTooltipPosition('right');
     tooltipObj.setPageBgColor('#EEEEEE');
     tooltipObj.setTooltipCornerSize(15);
     tooltipObj.initFormFieldTooltip();
diff --git a/menu-bill-merchant.php b/menu-bill-merchant.php
index 62690181..7dd76836 100644
--- a/menu-bill-merchant.php
+++ b/menu-bill-merchant.php
@@ -21,68 +21,20 @@
  *********************************************************************************************************
  */
 
 // prevent this file to be directly accessed
 if (strpos($_SERVER['PHP_SELF'], '/menu-bill-merchant.php') !== false) {
-    header("Location: /index.php");
+    header("Location: index.php");
     exit;
 }
 
 include_once("lang/main.php");
 
 $m_active = "Billing";
 
 include_once("include/menu/menu-items.php");
 include_once("include/menu/billing-subnav.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"
-                           );
 
 ?>
 
                 <div id="sidebar">
                     <h2>Billing</h2>
@@ -97,85 +49,86 @@ $checkboxes_checked = array(
                                 
                                 <h109><?= t('button','BetweenDates'); ?></h109><br>
                                 
                                 <label style="user-select: none" for="startdate"><?= t('all','StartingDate') ?></label>
                                 <input name="startdate" type="date" id="startdate" tooltipText="<?= t('Tooltip','Date') ?>"
-                                    value="<?= (isset($billing_date_startdate)) ? $billing_date_startdate : date("Y-m-01") ?>">
+                                    value="<?= (!empty($billing_date_startdate)) ? $billing_date_startdate : date("Y-m-01") ?>">
 
                                 <label style="user-select: none" for="enddate"><?= t('all','EndingDate') ?></label>
-                                <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>
+                                <input name="enddate" type="date" id="enddate" tooltipText="<?= t('Tooltip','Date') ?>"
+                                    value="<?= (!empty($billing_date_enddate)) ? $billing_date_enddate : date("Y-m-t") ?>">
 
                                 <br><br>
-
-                                <h109><?= t('button','AccountingFieldsinQuery'); ?></h109><br>
 <?php
-                                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);
-                                }
+                            $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);
+                            
 ?>
-                                <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>
-
+                                <a style="display: inline" href="#" onclick="select('all')">Select All</a>
+                                <a style="display: inline" href="#" onclick="select('none')">Select None</a>
                                 <br><br>
-                                
-                                <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>
 
+<?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);
+?>
+                               
                                 <br><br>
                                 
                                 <input class="sidebutton" type="submit" name="submit" value="<?= t('button','ProcessQuery') ?>">
 
                             </form>
@@ -183,10 +136,19 @@ $checkboxes_checked = array(
 
                 </ul><!-- .subnav -->
             </div><!-- #sidebar -->
 
 <script>
+    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;
+        }
+    }
+    
     var tooltipObj = new DHTMLgoodies_formTooltip();
     tooltipObj.setTooltipPosition('right');
     tooltipObj.setPageBgColor('#EEEEEE');
     tooltipObj.setTooltipCornerSize(15);
     tooltipObj.initFormFieldTooltip();
diff --git a/mng-batch-add.php b/mng-batch-add.php
index b85ef7ef..5090c51f 100644
--- a/mng-batch-add.php
+++ b/mng-batch-add.php
@@ -25,21 +25,22 @@
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
     include_once('library/config_read.php');
 
-    // set session's page variable
-    $_SESSION['PREV_LIST_PAGE'] = $_SERVER['REQUEST_URI'];
-
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
     
-    // we import validation facilities
-    include_once("library/validation.php");
-
+    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'];
+    
     // if cleartext passwords are not allowed, 
     // we remove Cleartext-Password from the $valid_passwordTypes array
     if (isset($configValues['CONFIG_DB_PASSWORD_ENCRYPTION']) &&
         strtolower($configValues['CONFIG_DB_PASSWORD_ENCRYPTION']) !== 'cleartext') {
         $valid_passwordTypes = array_diff($valid_passwordTypes, array("Cleartext-Password"));
@@ -98,13 +99,10 @@
         // if the INSERT to the batch_history table was succesful and there exist
         // only 1 record (meaning, we don't have a duplicate) then we return the id
         return ($res->numRows() == 1) ? intval($res->fetchRow()[0]) : 0;        
     }
     
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
 
     // print HTML prologue
     $extra_css = array(
         // css tabs stuff
         "css/tabs.css"
diff --git a/mng-edit.php b/mng-edit.php
index 89f71b63..0c677d86 100644
--- a/mng-edit.php
+++ b/mng-edit.php
@@ -30,12 +30,13 @@
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
     
-    // we import validation facilities
-    include_once("library/validation.php");
+    include_once("lang/main.php");
+    include("library/validation.php");
+    include("library/layout.php");
     include_once("include/management/functions.php");
     
     
     include('library/opendb.php');
     
@@ -385,14 +386,11 @@
     include('library/closedb.php');
 
     $hiddenPassword = (strtolower($configValues['CONFIG_IFACE_PASSWORD_HIDDEN']) == "yes")
                     ? 'password' : 'text';
     
-    include_once("lang/main.php");
     
-    include("library/layout.php");
-
     // print HTML prologue
     $extra_css = array(
         // css tabs stuff
         "css/tabs.css"
     );
diff --git a/mng-hs-edit.php b/mng-hs-edit.php
index a1ae179b..87c4ee45 100644
--- a/mng-hs-edit.php
+++ b/mng-hs-edit.php
@@ -30,12 +30,14 @@
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
 
-    // we import validation facilities
-    include_once("library/validation.php");
+    include_once("lang/main.php");
+    include("library/validation.php");
+    include("library/layout.php");
+    
 
     include('library/opendb.php');
 
     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         $name = (array_key_exists('name', $_POST) && isset($_POST['name']) && trim(str_replace("%", "", $_POST['name'])))
@@ -167,13 +169,10 @@
             ) = $res->fetchRow();
     }
 
     include('library/closedb.php');
 
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
 
     // print HTML prologue
     $extra_css = array(
         // css tabs stuff
         "css/tabs.css"
diff --git a/mng-hs-list.php b/mng-hs-list.php
index 435be199..7be13e20 100644
--- a/mng-hs-list.php
+++ b/mng-hs-list.php
@@ -30,16 +30,16 @@
     // 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");
+
     // set session's page variable
     $_SESSION['PREV_LIST_PAGE'] = $_SERVER['REQUEST_URI'];
 
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
 
     // print HTML prologue
     $extra_js = array(
         "library/javascript/ajax.js",
         "library/javascript/ajaxGeneric.js"
@@ -139,22 +139,22 @@
             </tr>
         </thead>
         
         <tbody>
 <?php
-        $count = 1;
+        $li_style = 'margin: 7px auto';
+        $count = 0;
         while ($row = $res->fetchRow()) {
             $rowlen = count($row);
         
             // escape row elements
             for ($i = 0; $i < $rowlen; $i++) {
                 $row[$i] = htmlspecialchars($row[$i], ENT_QUOTES, 'UTF-8');
             }
         
             list($name, $owner, $company, $type) = $row;
             
-            $li_style = 'margin: 7px auto';
             $tooltipText = '<ul style="list-style-type: none">'
                          . sprintf('<li style="%s"><a class="toolTip" href="mng-hs-edit.php?name=%s">%s</a></li>',
                                    $li_style, urlencode($name), t('Tooltip','HotspotEdit'))
                          . sprintf('<li style="%s"><a class="toolTip" href="acct-hotspot-compare.php">%s</a></li>',
                                    $li_style, t('all','Compare'))
@@ -199,28 +199,18 @@
         $failureMsg = "Nothing to display";
         include_once("include/management/actionMessages.php");
     }
     
     include('library/closedb.php');
-?>
-                
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
+
     include('include/config/logging.php');
-    include('page-footer.php');
-?>
-        </div><!-- #footer -->
-    </div>
-</div>
+    
+    $inline_extra_js = "
+var tooltipObj = new DHTMLgoodies_formTooltip();
+tooltipObj.setTooltipPosition('right');
+tooltipObj.setPageBgColor('#EEEEEE');
+tooltipObj.setTooltipCornerSize(15);
+tooltipObj.initFormFieldTooltip()";
 
-<script>
-    var tooltipObj = new DHTMLgoodies_formTooltip();
-    tooltipObj.setTooltipPosition('right');
-    tooltipObj.setPageBgColor('#EEEEEE');
-    tooltipObj.setTooltipCornerSize(15);
-    tooltipObj.initFormFieldTooltip();
-</script>
+    print_footer_and_html_epilogue($inline_extra_js);
 
-</body>
-</html>
+?>
diff --git a/mng-import-users.php b/mng-import-users.php
index 1358df8d..bd46b03f 100644
--- a/mng-import-users.php
+++ b/mng-import-users.php
@@ -30,30 +30,32 @@
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
 
-    // we import validation facilities
-    include_once("library/validation.php");
-    include("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('include/management/populate_selectbox.php');
 
     // custom valid authTypes
     $valid_authTypes = array(
                                 "userAuth" => "Based on username and password",
                                 "otherAuth" => "Based on MAC addr/PIN code"
                             );
 
+    $valid_groups = get_groups();
+    $valid_planNames = get_plans();
+
     // if cleartext passwords are not allowed, 
     // we remove Cleartext-Password from the $valid_passwordTypes array
     if (isset($configValues['CONFIG_DB_PASSWORD_ENCRYPTION']) &&
         strtolower($configValues['CONFIG_DB_PASSWORD_ENCRYPTION']) !== 'cleartext') {
         $valid_passwordTypes = array_diff($valid_passwordTypes, array("Cleartext-Password"));
     }
-    
-    include_once('include/management/populate_selectbox.php');
-    $valid_groups = get_groups();
-    $valid_planNames = get_plans();
 
     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         if (array_key_exists('csrf_token', $_POST) && isset($_POST['csrf_token']) && dalo_check_csrf_token($_POST['csrf_token'])) {
             
             $authType = (array_key_exists('authType', $_POST) && isset($_POST['authType']) &&
@@ -182,12 +184,10 @@
             $failureMsg = "CSRF token error";
             $logAction .= "$failureMsg on page: ";
         }
     }
 
-    include_once("lang/main.php");
-    include("library/layout.php");
 
     // print HTML prologue
     $extra_css = array();
     
     $extra_js = array(
diff --git a/mng-list-all.php b/mng-list-all.php
index f4dbb457..29a0b7f5 100644
--- a/mng-list-all.php
+++ b/mng-list-all.php
@@ -99,13 +99,14 @@
     $_SESSION['reportTable'] = $configValues['CONFIG_DB_TBL_RADCHECK'];
     $_SESSION['reportQuery'] = "";
     $_SESSION['reportType'] = "usernameListGeneric";
 
     // we use this simplified query just to initialize $numrows
-    $sql0 = sprintf("SELECT COUNT(DISTINCT(username)) AS username
-                       FROM %s
-                      WHERE attribute='Auth-Type' OR attribute LIKE '%%-Password'", $configValues['CONFIG_DB_TBL_RADCHECK']);
+    $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']);
     $res = $dbSocket->query($sql0);
     $logDebugSQL .= "$sql0;\n";
     $numrows = $res->fetchrow()[0];
     
     if ($numrows > 0) {
@@ -169,26 +170,29 @@
             );
             // in the same pass we init the $usernamelist
             $usernamelist[] = sprintf("'%s'", $dbSocket->escapeSimple($this_username));
         }
         
-        // 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";
+        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'];
+            // 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'));
+                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'));
+                }
             }
         }
         
         // this can be passed as form attribute and 
         // printTableFormControls function parameter
@@ -272,11 +276,11 @@
                         <input type="checkbox" name="username[]" id="<?= "checkbox-$count" ?>" value="<?= $username ?>">
                     </label>
                 </td>
                 <td><?= "$fullname" ?></td>
                 <td><?= "$img $tooltip" . sprintf(' <span class="badge badge-%s">%s</span>', strtolower($type), $type); ?></td>
-                <td><?= ($type == 'USER') ? $auth : "" ?></td>
+                <td><?= ($type == 'USER') ? $auth : "(n/a)" ?></td>
                 <td><?= $grouplist ?></td>
             </tr>
 <?php
         } 
 ?>
diff --git a/mng-new-quick.php b/mng-new-quick.php
index 2ed1801d..c6eb71e5 100644
--- a/mng-new-quick.php
+++ b/mng-new-quick.php
@@ -30,13 +30,14 @@
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
 
-    // we import validation facilities
-    include_once("library/validation.php");
-    include("include/management/functions.php");
+    include_once("lang/main.php");
+    include("library/validation.php");
+    include("library/layout.php");
+    include_once("include/management/functions.php");
     
     // if cleartext passwords are not allowed, 
     // we remove Cleartext-Password from the $valid_passwordTypes array
     if (isset($configValues['CONFIG_DB_PASSWORD_ENCRYPTION']) &&
         strtolower($configValues['CONFIG_DB_PASSWORD_ENCRYPTION']) !== 'cleartext') {
@@ -271,14 +272,11 @@
         }
     }
 
     $hiddenPassword = (strtolower($configValues['CONFIG_IFACE_PASSWORD_HIDDEN']) == "yes")
                     ? 'password' : 'text';
-    
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
+
 
     // print HTML prologue
     $extra_css = array(
         // css tabs stuff
         "css/tabs.css"
diff --git a/mng-new.php b/mng-new.php
index e4072c9d..287d54f6 100644
--- a/mng-new.php
+++ b/mng-new.php
@@ -30,13 +30,14 @@
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
 
-    // we import validation facilities
-    include_once("library/validation.php");
-    include("include/management/functions.php");
+    include_once("lang/main.php");
+    include("library/validation.php");
+    include("library/layout.php");
+    include_once("include/management/functions.php");
 
     // if cleartext passwords are not allowed, 
     // we remove Cleartext-Password from the $valid_passwordTypes array
     if (isset($configValues['CONFIG_DB_PASSWORD_ENCRYPTION']) &&
         strtolower($configValues['CONFIG_DB_PASSWORD_ENCRYPTION']) !== 'cleartext') {
@@ -319,14 +320,11 @@
     }
 
     $hiddenPassword = (strtolower($configValues['CONFIG_IFACE_PASSWORD_HIDDEN']) == "yes")
                     ? 'password' : 'text';
     
-    include_once("lang/main.php");
     
-    include("library/layout.php");
-
     // print HTML prologue
     $extra_css = array(
         // css tabs stuff
         "css/tabs.css"
     );
diff --git a/mng-rad-attributes-edit.php b/mng-rad-attributes-edit.php
index a2592144..e9fcf7e9 100644
--- a/mng-rad-attributes-edit.php
+++ b/mng-rad-attributes-edit.php
@@ -30,85 +30,121 @@
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
 
-    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_once("lang/main.php");
+    include("library/validation.php");
+    include("library/layout.php");
 
-        include 'library/opendb.php';
+    // custom validation structures
+    $valid_tables = array("check", "reply");
 
-        $sql = "SELECT * FROM ".$configValues['CONFIG_DB_TBL_DALODICTIONARY']." WHERE vendor='".$dbSocket->escapeSimple($vendor).
-            "' AND attribute='".$dbSocket->escapeSimple($attribute)."'";
+    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));
         $res = $dbSocket->query($sql);
-        $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: ";
+        $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: ";
             } else {
-                $failureMsg = "you must provide atleast a vendor name and attribute";    
-                $logAction .= "Failed updating vendor [$vendor] and attribute [$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 { 
-            $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: ";        
+
+        } else {
+            // csrf
+            $failureMsg = "CSRF token error";
+            $logAction .= "$failureMsg on page: ";
         }
-    
-        include 'library/closedb.php';
+    } 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';
-
-    $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");
-
     // print HTML prologue
     $title = t('Intro','mngradattributesedit.php');
     $help = t('helpPage','mngradattributesedit');
     
     print_html_prologue($title, $langCode);
@@ -116,139 +152,149 @@
     include ("menu-mng-rad-attributes.php");
     
     echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
 
-    include_once('include/management/actionMessages.php');
+    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');
 
-        <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>
+    if (!isset($successMsg) && !empty($vendor) && !empty($attribute)) {
+        
+        $fieldset0_descriptor = array(
+                                        "title" => t('title','VendorAttribute'),
+                                     );
 
-    </form>
+        
+        $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();
+    }
 
-<?php
     include('include/config/logging.php');
     print_footer_and_html_epilogue();
+
 ?>
diff --git a/mng-rad-attributes-new.php b/mng-rad-attributes-new.php
index a3c997aa..1a5d8306 100644
--- a/mng-rad-attributes-new.php
+++ b/mng-rad-attributes-new.php
@@ -30,56 +30,106 @@
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
 
-    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";
+    include_once("lang/main.php");
+    include("library/validation.php");
+    include("library/layout.php");
 
-                $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: ";
+    // 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: ";
             } else {
-                $failureMsg = "You must provide atleast a vendor name and attribute";    
-                $logAction .= "Failed adding new vendor [$vendor] and attribute [$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 { 
-            $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: ";        
+            
+        } else {
+            // csrf
+            $failureMsg = "CSRF token error";
+            $logAction .= "$failureMsg on page: ";
         }
-    
-        include 'library/closedb.php';
-
     }
-
-
-    include_once("lang/main.php");
-    include("library/layout.php");
-
+    
+    
     // print HTML prologue
     $title = t('Intro','mngradattributesnew.php');
     $help = t('helpPage','mngradattributesnew');
     
     print_html_prologue($title, $langCode);
@@ -89,115 +139,103 @@
     echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
 
     include_once('include/management/actionMessages.php');
 
-?>
-
-<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
-    
-    <fieldset>
-
-        <h302> <?php echo t('title','VendorAttribute'); ?> </h302>
-        <br/>
+    if (!isset($successMsg)) {
 
-        <ul>
+        $fieldset0_descriptor = array(
+                                        "title" => t('title','VendorAttribute'),
+                                     );
 
-        <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')" />
+        $input_descriptors0 = array();
         
-        <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')" />
+        $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'),
+                                     );
         
-        <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')" />
+        $input_descriptors0[] = array(
+                                        "name" => "RecommendedOP",
+                                        "caption" => t('all','RecommendedOP'),
+                                        "type" => "text",
+                                        "datalist" => $valid_ops,
+                                        "value" => ((isset($op)) ? $op : ""),
+                                        "tooltipText" => t('Tooltip','RecommendedOPTooltip'),
+                                     );
         
-        <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>
-
+        $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();
+    }
     
-        <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
     include('include/config/logging.php');
     print_footer_and_html_epilogue();
+
 ?>
diff --git a/mng-rad-attributes-search.php b/mng-rad-attributes-search.php
index b6832c9d..8af6bb0d 100644
--- a/mng-rad-attributes-search.php
+++ b/mng-rad-attributes-search.php
@@ -30,13 +30,13 @@
     // init loggin variables
     $log = "visited page: ";
     $logQuery = "performed query for listing of records on page: ";
     $logDebugSQL = "";
 
-    // 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']) : "";
+    // 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'])) : "";
 
     include_once("lang/main.php");
     
     include("library/layout.php");
 
@@ -79,11 +79,11 @@
     include('library/opendb.php');
     include('include/management/pages_common.php');
 
     $sql_WHERE = array();
     $sql_WHERE[] = "(type <> '' OR type IS NOT NULL)";
-    if (!empty($vendor)) {
+    if (!empty($attribute)) {
         $sql_WHERE[] = sprintf("attribute LIKE '%s%%'", $dbSocket->escapeSimple($attribute));
     }
     
     // we use this simplified query just to initialize $numrows
     $sql = sprintf("SELECT COUNT(id) FROM %s", $configValues['CONFIG_DB_TBL_DALODICTIONARY']);
diff --git a/mng-rad-groupcheck-new.php b/mng-rad-groupcheck-new.php
index 6f5fd051..989c258a 100644
--- a/mng-rad-groupcheck-new.php
+++ b/mng-rad-groupcheck-new.php
@@ -30,12 +30,13 @@
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
 
-    // we import validation facilities
-    include_once("library/validation.php");
+    include_once("lang/main.php");
+    include("library/validation.php");
+    include("library/layout.php");
 
     include_once('include/management/populate_selectbox.php');
     
 
     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
@@ -77,14 +78,10 @@
             
         } // profile name not empty    
     }
 
 
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
-
     // print HTML prologue
     $extra_js = array(
         "library/javascript/ajax.js",
         "library/javascript/dynamic_attributes.js",
         "library/javascript/ajaxGeneric.js",
diff --git a/mng-rad-groupreply-new.php b/mng-rad-groupreply-new.php
index 1dca62f9..6f94dfd5 100644
--- a/mng-rad-groupreply-new.php
+++ b/mng-rad-groupreply-new.php
@@ -30,12 +30,13 @@
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
 
-    // we import validation facilities
-    include_once("library/validation.php");
+    include_once("lang/main.php");
+    include("library/validation.php");
+    include("library/layout.php");
 
     include_once('include/management/populate_selectbox.php');
     
 
     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
@@ -77,14 +78,10 @@
             
         } // profile name not empty    
     }
 
 
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
-
     // print HTML prologue
     $extra_js = array(
         "library/javascript/ajax.js",
         "library/javascript/dynamic_attributes.js",
         "library/javascript/ajaxGeneric.js",
diff --git a/mng-rad-nas-new.php b/mng-rad-nas-new.php
index 82d4c0de..8a481aa6 100644
--- a/mng-rad-nas-new.php
+++ b/mng-rad-nas-new.php
@@ -23,22 +23,20 @@
 
     include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
+    include_once('library/config_read.php');
 
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
 
-    include_once('library/config_read.php');
-    
     include_once("lang/main.php");
-    
-    // we import validation facilities
-    include_once("library/validation.php");
+    include("library/validation.php");
+    include("library/layout.php");
     
     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         $nasname = (array_key_exists('nasname', $_POST) && isset($_POST['nasname'])) ? trim(str_replace("%", "", $_POST['nasname'])) : "";
         $nassecret = (array_key_exists('nassecret', $_POST) && isset($_POST['nassecret'])) ? trim(str_replace("%", "", $_POST['nassecret'])) : "";
         
@@ -93,11 +91,10 @@
             include('library/closedb.php');
         }
 
     }
 
-    include("library/layout.php");
 
     // print HTML prologue
     $extra_css = array(
         // css tabs stuff
         "css/tabs.css"
diff --git a/mng-rad-profiles-edit.php b/mng-rad-profiles-edit.php
index e99ea49e..db091733 100644
--- a/mng-rad-profiles-edit.php
+++ b/mng-rad-profiles-edit.php
@@ -30,12 +30,13 @@
     // init logging variables
     $log = "visited page: ";
     $logAction = "";
     $logDebugSQL = "";
 
-    // we import validation facilities
-    include_once("library/validation.php");
+    include_once("lang/main.php");
+    include("library/validation.php");
+    include("library/layout.php");
 
     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
         $profile_name = (array_key_exists('profile_name', $_POST) && !empty($_POST['profile_name']) &&
                          str_replace("%", "", trim($_POST['profile_name'])))
                       ? str_replace("%", "", trim($_POST['profile_name'])) : "";
@@ -45,13 +46,10 @@
                       ? str_replace("%", "", trim($_REQUEST['profile_name'])) : "";
     }
     
     $profile_name_enc = (!empty($profile_name)) ? htmlspecialchars($profile_name, ENT_QUOTES, 'UTF-8') : "";
 
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
 
     // print HTML prologue
     $extra_css = array(
         // css tabs stuff
         "css/tabs.css"
diff --git a/mng-rad-profiles-new.php b/mng-rad-profiles-new.php
index 1592d0dc..c100f1f2 100644
--- a/mng-rad-profiles-new.php
+++ b/mng-rad-profiles-new.php
@@ -30,12 +30,13 @@
     // init logging variables
     $logAction = "";
     $logDebugSQL = "";
     $log = "visited page: ";
 
-    // we import validation facilities
-    include_once("library/validation.php");
+    include_once("lang/main.php");
+    include("library/validation.php");
+    include("library/layout.php");
 
     if ($_SERVER['REQUEST_METHOD'] === 'POST') {
     
         $profile = (array_key_exists('profile', $_POST) && !empty(str_replace("%", "", trim($_POST['profile']))))
                  ? str_replace("%", "", trim($_POST['profile'])) : "";
@@ -73,14 +74,11 @@
             
             include('library/closedb.php');
             
         } // profile name not empty    
     }
-    
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
+
 
     // print HTML prologue
     $extra_css = array(
         // css tabs stuff
         "css/tabs.css"
diff --git a/mng-rad-usergroup-list-user.php b/mng-rad-usergroup-list-user.php
index 1fe81d2b..6e044073 100644
--- a/mng-rad-usergroup-list-user.php
+++ b/mng-rad-usergroup-list-user.php
@@ -154,15 +154,15 @@
         </thead>
         
         <tbody>
 <?php
         $li_style = 'margin: 7px auto';
-        $counter = 1;
+        $counter = 0;
         while ($row = $res->fetchRow()) {
             $rowlen = count($row);
             
-            echo '<tr>';
+            printf('<tr id="row-%d">', $counter);
             
             for ($i = 0; $i < $rowlen; $i++) {
                 $row[$i] = htmlspecialchars($row[$i], ENT_QUOTES, 'UTF-8');
                 
                 if ($i == 0) {
@@ -199,10 +199,13 @@
         // tfoot
         $links = setupLinks_str($pageNum, $maxPage, $orderBy, $orderType);
         printTableFoot($per_page_numrows, $numrows, $colspan, $drawNumberLinks, $links, $partial_query_string);
 ?>
     </table>
+    
+    <input type="hidden" name="csrf_token" value="<?= dalo_csrf_token() ?>">
+    
 </form>
 
 <?php
     } else {
         $failureMsg = "Nothing to display";
diff --git a/mng-rad-usergroup-list.php b/mng-rad-usergroup-list.php
index 97126b1c..495bd4a7 100644
--- a/mng-rad-usergroup-list.php
+++ b/mng-rad-usergroup-list.php
@@ -194,11 +194,11 @@
             $records[$this_username] = array(
                 'fullname' => $fullname,
                 'groups' => array()
             );
             
-            $sql1 = sprintf("SELECT groupname, priority FROM %s WHERE username='%s' ORDER BY priority DESC, groupname ASC",
+            $sql1 = sprintf("SELECT groupname, priority FROM %s WHERE username='%s' ORDER BY priority ASC, groupname ASC",
                             $configValues['CONFIG_DB_TBL_RADUSERGROUP'], $dbSocket->escapeSimple($this_username));
             $res1 = $dbSocket->query($sql1);
             
             while ($row1 = $res1->fetchRow()) {
                 $row1len = count($row1);
diff --git a/mng-search.php b/mng-search.php
index 25d03688..39b11bcc 100644
--- a/mng-search.php
+++ b/mng-search.php
@@ -26,28 +26,16 @@
 
     include('library/check_operator_perm.php');
     include_once('library/config_read.php');
     
     include_once("lang/main.php");
-    
     include("library/layout.php");
 
-    // 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);
-
     // we partially strip some character and
     // leave validation/escaping to other functions used later in the script
-    $username = (array_key_exists('username', $_GET) && isset($_GET['username']))
-              ? str_replace("%", "", $_GET['username']) : "";
-    
+    $username = (array_key_exists('username', $_GET) && !empty(str_replace("%", "", trim($_GET['username']))))
+              ? str_replace("%", "", trim($_GET['username'])) : "";
     $username_enc = (!empty($username))
                   ? htmlspecialchars($username, ENT_QUOTES, 'UTF-8')
                   : "";
 
     // init logging variables
@@ -61,10 +49,21 @@
     $logQuery .= "on page: ";
 
     //feed the sidebar variables
     $search_username = $username_enc;
 
+
+    // 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);
+
     if (!empty($username_enc)) {
         $title .=  " :: " . $username_enc;
     }
 
     $help = (!empty($username_enc)) ? "looked for user $username_enc" : "no user specified";
@@ -89,16 +88,14 @@
              ? $_GET['orderBy'] : array_keys($param_cols)[0];
 
     $orderType = (array_key_exists('orderType', $_GET) && isset($_GET['orderType']) &&
                   in_array(strtolower($_GET['orderType']), array( "desc", "asc" )))
                ? strtolower($_GET['orderType']) : "desc";
-?>
 
-    <div id="contentnorightbar">
-
-<?php
+    echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
+    
     include('library/opendb.php');
     include('include/management/pages_common.php');
 
     $sql_WHERE = array();
     if (!empty($username)) {
diff --git a/msg-error-permissions.php b/msg-error-permissions.php
index c624ef33..9fb918be 100644
--- a/msg-error-permissions.php
+++ b/msg-error-permissions.php
@@ -22,36 +22,29 @@
  */
 
     include ("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
+    $log = "visited page: ";
+
     include_once("lang/main.php");
-    
     include("library/layout.php");
 
+
     // print HTML prologue
     $title = t('Intro','msgerrorpermissions.php');
     $help = t('helpPage','msgerrorpermissions');
     
     print_html_prologue($title, $langCode);
 
     include("menu-home.php");
-?>
 
-                <div id="contentnorightbar">
-<?php
+    echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
+
     $failureMsg = t('helpPage','msgerrorpermissions');
-    include_once("include/management/actionMessages.php");
-?>
-                </div><!-- #contentnorightbar -->
-                        
-                <div id="footer">
-<?php
-    include('page-footer.php');
-?>
-                </div><!-- #footer -->
-            </div>
-        </div>
-    </body>
-</html>
+    include_once('include/management/actionMessages.php');
 
+    include('include/config/logging.php');
+    print_footer_and_html_epilogue();
+
+?>
diff --git a/rep-batch.php b/rep-batch.php
index e2d2ce68..c71d5b65 100644
--- a/rep-batch.php
+++ b/rep-batch.php
@@ -1,6 +1,6 @@
-<?php
+<?php 
 /*
  *********************************************************************************************************
  * daloRADIUS - RADIUS Web Platform
  * Copyright (C) 2007 - Liran Tal <liran@enginx.com> All Rights Reserved.
  *
@@ -19,52 +19,30 @@
  *             Filippo Lauria <filippo.lauria@iit.cnr.it>
  *
  *********************************************************************************************************
  */
 
-    include("library/checklogin.php");
+    include ("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
-        
+
     include_once('library/config_read.php');
-    
+    $log = "visited page: ";
+
     include_once("lang/main.php");
     
     include("library/layout.php");
 
-    // print HTML prologue   
+    // print HTML prologue
     $title = t('Intro','repbatch.php');
+    $help = t('helpPage','repbatch');
     
     print_html_prologue($title, $langCode);
 
     include("menu-reports-batch.php");
     
-    $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
+    echo '<div id="contentnorightbar">';
+    print_title_and_help($title, $help);
+    
     include('include/config/logging.php');
-?>
+    print_footer_and_html_epilogue();
 
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-        
-<?php
-    include('page-footer.php');
 ?>
-
-        
-        </div><!-- #footer -->
-    </div>
-</div>
-
-
-</body>
-</html>
diff --git a/rep-hb.php b/rep-hb.php
index 10953737..84bf8d69 100644
--- a/rep-hb.php
+++ b/rep-hb.php
@@ -1,6 +1,6 @@
-<?php
+<?php 
 /*
  *********************************************************************************************************
  * daloRADIUS - RADIUS Web Platform
  * Copyright (C) 2007 - Liran Tal <liran@enginx.com> All Rights Reserved.
  *
@@ -19,13 +19,13 @@
  *             Filippo Lauria <filippo.lauria@iit.cnr.it>
  *
  *********************************************************************************************************
  */
 
-    include("library/checklogin.php");
+    include ("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
-        
+
     include_once('library/config_read.php');
     $log = "visited page: ";
 
     include_once("lang/main.php");
     
@@ -36,25 +36,13 @@
     $help = t('helpPage','rephb');
     
     print_html_prologue($title, $langCode);
 
     include("menu-reports-hb.php");
-
-?>
-        <div id="contentnorightbar">
-<?php
+    
+    echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
-?>
-
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
+    
     include('include/config/logging.php');
-    include('page-footer.php');
-?>
-        </div><!-- #footer -->
-    </div>
-</div>
+    print_footer_and_html_epilogue();
 
-</body>
-</html>
+?>
diff --git a/rep-lastconnect.php b/rep-lastconnect.php
index 1db2f6ef..3cf09963 100644
--- a/rep-lastconnect.php
+++ b/rep-lastconnect.php
@@ -31,11 +31,11 @@
     $log = "visited page: ";
     $logQuery = "performed query on page: ";
     $logDebugSQL = "";
     
     include_once("lang/main.php");
-    
+    include("library/validation.php");
     include("library/layout.php");
 
     // print HTML prologue
     $title = t('Intro','replastconnect.php');
     $help = t('helpPage','replastconnect');
@@ -55,12 +55,10 @@
         $tableSetting['postauth']['user'] = 'username';
         $tableSetting['postauth']['date'] = 'authdate';
         break;
     }
     
-    include("library/validation.php");
-    
     // in other cases we just check that syntax is ok
     $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'] : date("Y-m-01");
diff --git a/rep-logs-boot.php b/rep-logs-boot.php
index 9c1c9dce..22ed8688 100644
--- a/rep-logs-boot.php
+++ b/rep-logs-boot.php
@@ -23,26 +23,26 @@
 
     include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
+    include_once('library/config_read.php');
+    
+    $log = "visited page: ";
+
+    include_once("lang/main.php");
+    include("library/layout.php");
 
     // parameter validation
     $bootLineCount = (array_key_exists('bootLineCount', $_GET) && isset($_GET['bootLineCount']) &&
                       intval($_GET['bootLineCount']) > 0)
                    ? intval($_GET['bootLineCount']) : 50;
 
     // preg quoted before usage
     $bootFilter = (array_key_exists('bootFilter', $_GET) && isset($_GET['bootFilter']))
                 ? $_GET['bootFilter'] : "";
 
-    include_once('library/config_read.php');
-    $log = "visited page: ";
-
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
 
     // print HTML prologue
     $title = t('Intro','replogsboot.php') . " :: $bootLineCount Lines Count";
     if (!empty($bootFilter) && $bootFilter !== '.+') {
         $title .= " with filter set to " . htmlspecialchars($bootFilter, ENT_QUOTES, 'UTF-8');
@@ -50,29 +50,16 @@
     $help = t('helpPage','replogsboot');
     
     print_html_prologue($title, $langCode);
 
     include("menu-reports-logs.php");
-      
-?>    
-    <div id="contentnorightbar">
 
-<?php
+    echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
 
     include('library/exten-boot_log.php');
     include_once('include/management/actionMessages.php');
-?>
-         </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
+    
     include('include/config/logging.php');
-    include('page-footer.php');
-?>
-        </div><!-- #footer -->
-    </div>
-</div>
-
-</body>
-</html>
+    print_footer_and_html_epilogue();
 
+?>
diff --git a/rep-logs-radius.php b/rep-logs-radius.php
index 2b104d7f..93db862d 100644
--- a/rep-logs-radius.php
+++ b/rep-logs-radius.php
@@ -23,10 +23,16 @@
 
     include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
+    include_once('library/config_read.php');
+    
+    $log = "visited page: ";
+
+    include_once("lang/main.php");
+    include("library/layout.php");
 
     // parameter validation
     $radiusLineCount = (array_key_exists('radiusLineCount', $_GET) && isset($_GET['radiusLineCount']) &&
                         intval($_GET['radiusLineCount']) > 0)
                      ? intval($_GET['radiusLineCount']) : 50;
@@ -35,17 +41,10 @@
     $radiusFilter = (array_key_exists('radiusFilter', $_GET) && isset($_GET['radiusFilter']) &&
                      in_array($_GET['radiusFilter'], array( "Auth", "Info", "Error" )))
                   ? $_GET['radiusFilter'] : "";
 
 
-    include_once('library/config_read.php');
-    $log = "visited page: ";
-
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
-
     // print HTML prologue
     $title = t('Intro','replogsradius.php') . " :: $radiusLineCount Lines Count";
     if (!empty($radiusFilter) && $radiusFilter !== '.+') {
         $title .= " with filter set to " . htmlspecialchars($radiusFilter, ENT_QUOTES, 'UTF-8');
     }
@@ -53,25 +52,15 @@
     
     print_html_prologue($title, $langCode);
 
     include ("menu-reports-logs.php");
 
-?>
-    <div id="contentnorightbar">
-<?php
+    echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
+    
     include('library/exten-radius_log.php');
     include_once('include/management/actionMessages.php');
-?>
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
+
     include('include/config/logging.php');
-    include('page-footer.php');
-?>
-        </div><!-- #footer -->
-    </div>
-</div>
+    print_footer_and_html_epilogue();
 
-</body>
-</html>
+?>
diff --git a/rep-logs-system.php b/rep-logs-system.php
index facd0dc5..d704912f 100644
--- a/rep-logs-system.php
+++ b/rep-logs-system.php
@@ -23,53 +23,43 @@
 
     include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
+    include_once('library/config_read.php');
+
+    $log = "visited page: ";
 
+    include_once("lang/main.php");
+    include("library/layout.php");
+    
     // parameter validation
     $systemLineCount = (array_key_exists('systemLineCount', $_GET) && isset($_GET['systemLineCount']) &&
                         intval($_GET['systemLineCount']) > 0)
                      ? intval($_GET['systemLineCount']) : 50;
 
     // preg quoted before usage
     $systemFilter = (array_key_exists('systemFilter', $_GET) && isset($_GET['systemFilter']))
                   ? $_GET['systemFilter'] : "";
 
-    include_once('library/config_read.php');
-    $log = "visited page: ";
-
-    include_once("lang/main.php");
     
-    include("library/layout.php");
-
     // print HTML prologue
     $title = t('Intro','replogssystem.php') . " :: $systemLineCount Lines Count";
     if (!empty($systemFilter) && $systemFilter !== '.+') {
         $title .= " with filter set to " . htmlspecialchars($systemFilter, ENT_QUOTES, 'UTF-8');
     }
     $help = t('helpPage','replogssystem');
     
     print_html_prologue($title, $langCode);
 
     include ("menu-reports-logs.php");      
-?>    
-        <div id="contentnorightbar">
 
-<?php
+    echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
+    
     include('library/exten-syslog_log.php');
     include_once('include/management/actionMessages.php');
-?>
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
+
     include('include/config/logging.php');
-    include('page-footer.php');
-?>
-        </div><!-- #footer -->
-    </div>
-</div>
+    print_footer_and_html_epilogue();
 
-</body>
-</html>
+?>
diff --git a/rep-logs.php b/rep-logs.php
index 5639ff4c..69805165 100644
--- a/rep-logs.php
+++ b/rep-logs.php
@@ -25,34 +25,24 @@
     $operator = $_SESSION['operator_user'];
         
     include_once('library/config_read.php');
     $log = "visited page: ";
 
-    include_once("lang/main.php");
-    
+    include_once("lang/main.php");    
     include("library/layout.php");
 
+
     // print HTML prologue
     $title = t('Intro','replogs.php');
     $help = t('helpPage','replogs');
     
     print_html_prologue($title, $langCode);
 
     include("menu-reports-logs.php");
 
     echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
-?>
 
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
     include('include/config/logging.php');
-    include('page-footer.php');
-?>
-        </div><!-- #footer -->
-    </div>
-</div>
+    print_footer_and_html_epilogue();
 
-</body>
-</html>
+?>
diff --git a/rep-main.php b/rep-main.php
index 63cc9128..754d26b8 100644
--- a/rep-main.php
+++ b/rep-main.php
@@ -1,6 +1,6 @@
-<?php
+<?php 
 /*
  *********************************************************************************************************
  * daloRADIUS - RADIUS Web Platform
  * Copyright (C) 2007 - Liran Tal <liran@enginx.com> All Rights Reserved.
  *
@@ -19,46 +19,30 @@
  *             Filippo Lauria <filippo.lauria@iit.cnr.it>
  *
  *********************************************************************************************************
  */
 
-    include("library/checklogin.php");
+    include ("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
-    //~ include('library/check_operator_perm.php');
-    
     include_once('library/config_read.php');
-    
+    $log = "visited page: ";
+
     include_once("lang/main.php");
     
     include("library/layout.php");
 
     // print HTML prologue
     $title = t('Intro','repmain.php');
     $help = t('helpPage','repmain');
     
     print_html_prologue($title, $langCode);
-    
-    include("menu-reports.php");
 
-?>
-        
-        <div id="contentnorightbar">
-<?php
+    include("menu-reports.php");
+    
+    echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
-?>
-        
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
-    $log = "visited page: ";
-
+    
     include('include/config/logging.php');
-    include('page-footer.php');
-?>
-        </div><!-- #footer -->
-    </div>
-</div>
+    print_footer_and_html_epilogue();
 
-</body>
-</html>
+?>
diff --git a/rep-newusers.php b/rep-newusers.php
index 2157a3fa..27d966d3 100644
--- a/rep-newusers.php
+++ b/rep-newusers.php
@@ -26,11 +26,13 @@
     $operator = $_SESSION['operator_user'];
 
     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");
 
     // we validate starting and ending dates
     $startdate = (array_key_exists('startdate', $_GET) && isset($_GET['startdate']) &&
                   preg_match(DATE_REGEX, $_GET['startdate'], $m) !== false &&
                   checkdate($m[2], $m[3], $m[1]))
@@ -50,13 +52,10 @@
     if (!empty($enddate)) {
          $logQuery .= " to $enddate";
     }
     $logQuery .= "on page: ";
 
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
 
     // print HTML prologue
     $extra_css = array(
         // css tabs stuff
         "css/tabs.css"
diff --git a/rep-stat-server.php b/rep-stat-server.php
index 63c7d75a..7a0f2460 100644
--- a/rep-stat-server.php
+++ b/rep-stat-server.php
@@ -23,41 +23,29 @@
 
     include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
-
     include_once('library/config_read.php');
+    
     $log = "visited page: ";
 
     include_once("lang/main.php");
-    
     include("library/layout.php");
 
     // print HTML prologue
     $title = t('Intro','repstatserver.php');
     $help = t('helpPage','repstatserver');
     
     print_html_prologue($title, $langCode);
 
     include("menu-reports-status.php");
     
-?>    
-        <div id="contentnorightbar">
-<?php
+    echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
+    
     include('library/exten-server_info.php');
-?>
-
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
+    
     include('include/config/logging.php');
-    include('page-footer.php');
-?>
-        </div><!-- #footer -->
-    </div>
-</div>
+    print_footer_and_html_epilogue();
 
-</body>
-</html>
+?>
diff --git a/rep-stat-services.php b/rep-stat-services.php
index f192f455..da42406e 100644
--- a/rep-stat-services.php
+++ b/rep-stat-services.php
@@ -23,44 +23,29 @@
 
     include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
-
     include_once('library/config_read.php');
+    
     $log = "visited page: ";
-    include('include/config/logging.php');
-
-    include_once("lang/main.php");
     
+    include_once("lang/main.php");
     include("library/layout.php");
 
     // print HTML prologue
     $title = t('Intro','repstatradius.php');
     $help = t('helpPage','repstatradius');
     
     print_html_prologue($title, $langCode);
 
     include("menu-reports-status.php");
       
-?>    
-        <div id="contentnorightbar">
-
-<?php
+    echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
+    
     include('library/exten-radius_server_info.php');
-?>
+    
+    include('include/config/logging.php');
+    print_footer_and_html_epilogue();
 
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">        
-<?php
-        include('page-footer.php');
 ?>
-
-        </div><!-- #footer -->
-    </div>
-</div>
-
-
-</body>
-</html>
diff --git a/rep-stat-ups.php b/rep-stat-ups.php
index f35fdbdf..eaa8e813 100644
--- a/rep-stat-ups.php
+++ b/rep-stat-ups.php
@@ -23,32 +23,28 @@
 
     include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     include('library/check_operator_perm.php');
-
     include_once('library/config_read.php');
+    
     $log = "visited page: ";
     $logQuery = "performed query on page: ";
-    include('include/config/logging.php');
-
-    include_once("lang/main.php");
     
+    include_once("lang/main.php");
     include("library/layout.php");
 
+
     // print HTML prologue
     $title = "UPS Status";
     $help = "";
     
     print_html_prologue($title, $langCode);
 
     include("menu-reports-status.php");
-      
-?>
-        <div id="contentnorightbar">
-<?php
 
+    echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
 
     exec("which apcaccess || command -v apcaccess", $output, $retStatus);
 
     $failureMsg = "";
@@ -81,19 +77,10 @@
     }
     
     if (!empty($failureMsg)) {
         include_once('include/management/actionMessages.php');
     }
-?>
-        </div>
-        
-        <div id="footer">
-<?php
-    include('page-footer.php');
-?>
-        </div>
-        
-    </div>
-</div>
 
-</body>
-</html>
+    include('include/config/logging.php');
+    print_footer_and_html_epilogue();
+
+?>
diff --git a/rep-status.php b/rep-status.php
index 74935d16..c602ce8f 100644
--- a/rep-status.php
+++ b/rep-status.php
@@ -1,6 +1,6 @@
-<?php
+<?php 
 /*
  *********************************************************************************************************
  * daloRADIUS - RADIUS Web Platform
  * Copyright (C) 2007 - Liran Tal <liran@enginx.com> All Rights Reserved.
  *
@@ -12,49 +12,35 @@
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
  *
  *********************************************************************************************************
-*
- * Authors:	Liran Tal <liran@enginx.com>
+ *
+ * Authors:    Liran Tal <liran@enginx.com>
+ *             Filippo Lauria <filippo.lauria@iit.cnr.it>
  *
  *********************************************************************************************************
  */
 
-    include("library/checklogin.php");
+    include ("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
-        
-	include_once('library/config_read.php');
+
+    include_once('library/config_read.php');
     $log = "visited page: ";
-    
+
     include_once("lang/main.php");
-    
     include("library/layout.php");
 
     // print HTML prologue
     $title = t('Intro','repstatus.php');
     $help = t('helpPage','repstatus');
     
     print_html_prologue($title, $langCode);
 
     include("menu-reports-status.php");
-
-?>
-		<div id="contentnorightbar">
-<?php
+    
+    echo '<div id="contentnorightbar">';
     print_title_and_help($title, $help);
+    
+    include('include/config/logging.php');
+    print_footer_and_html_epilogue();
 ?>
-		
-        </div><!-- #contentnorightbar -->
-        
-        <div id="footer">
-<?php
-    include_once('include/config/logging.php');
-    include('page-footer.php');
-?>
-
-        </div><!-- #footer -->
-    </div>
-</div>
-
-</body>
-</html>
diff --git a/rep-topusers.php b/rep-topusers.php
index 8405ca19..0e410326 100644
--- a/rep-topusers.php
+++ b/rep-topusers.php
@@ -25,11 +25,13 @@
     $operator = $_SESSION['operator_user'];
 
     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");
     
     $limit = (array_key_exists('limit', $_GET) && isset($_GET['limit']) && intval($_GET['limit']) > 0)
            ? intval($_GET['limit']) : "";
     
     $startdate = (array_key_exists('startdate', $_GET) && isset($_GET['startdate']) &&
@@ -46,13 +48,10 @@
     // and leave validation/escaping to other functions used later in the script
     $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') : "";
     
-    include_once("lang/main.php");
-    
-    include("library/layout.php");
 
     // print HTML prologue
     $title = t('Intro','reptopusers.php');
     $help = t('helpPage','reptopusers') . " " . $orderBy;
     
diff --git a/rep-username.php b/rep-username.php
index 805b4fac..d91a6802 100644
--- a/rep-username.php
+++ b/rep-username.php
@@ -23,31 +23,31 @@
 
     include("library/checklogin.php");
     $operator = $_SESSION['operator_user'];
 
     //~ 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");
 
     // validate this parameter before including menu
-    $username = (array_key_exists('username', $_GET) && isset($_GET['username']))
-                    ? str_replace("%", "", $_GET['username']) : "";
+    $username = (array_key_exists('username', $_GET) && !empty(str_replace("%", "", trim($_GET['username']))))
+              ? str_replace("%", "", trim($_GET['username'])) : "";
     $username_enc = (!empty($username)) ? htmlspecialchars($username, ENT_QUOTES, 'UTF-8') : "";
     
     $log = "visited page: ";
-    $logQuery = "performed query for [$username";
-    if (!empty($limit)) {
-        $logQuery .= " : $limit";
+    $logQuery = "performed query for ";
+    if (!empty($username)) {
+         $logQuery .= "username(s) starting with [$username] ";
+    } else {
+        $logQuery .= "all usernames ";
     }
-    $logQuery .= "] on page: ";
-
-    include_once('library/config_read.php');
-    
-    include("library/validation.php");
+    $logQuery .= "on page: ";
 
-    include_once("lang/main.php");
     
-    include("library/layout.php");
-
     // print HTML prologue
     $title = t('Intro','repusername.php');
     $help = t('helpPage','repusername') . " " . $username_enc;
     
     print_html_prologue($title, $langCode);

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: ";