<?php // αβγδεζηθικλμνξοπρστυφχψως
/*
https://ctrlq.org/beautifier/
TODO:
echo "<div class=uerror>Authentication error</div>"; --> uerror('Authentication error');
*/
header('X-Frame-Options: sameorigin');
header('Strict-Transport-Security: max-age=86400; includeSubDomains');
$host = (string) @$_SERVER['HTTP_HOST'];
switch ($host)
{
case 'e-invoice-gr.info':
case 'www.e-invoice-gr.info':
case 'e-invoice.gr':
case 'www.e-invoice.gr':
   if ($_SERVER['SERVER_PORT'] == 80 || $_SERVER['REQUEST_SCHEME'] === 'http')
   { // is unsecure
      $ar1 = explode('.', $host);
      if ($ar1[0] !== 'www') { array_unshift($ar1, 'www'); }
      $url = 'https://'.implode('.', $ar1).'/iform/'.basename(__FILE__);
      header("Location: $url");
      exit();
   }
   break;
}

$sess_name= session_name();
if (session_start()) {
   $isSecure = false;
   if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
      $isSecure = true;
   }
   else if ((!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
      || (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] === 'on'))
   {
      $isSecure = true;
   }

   if ($isSecure) {
      // Remove unsecure cookie
      setcookie($sess_name, null, -1, '/');
      // Set secure cookie
      setcookie(
         $sess_name,    // name
         session_id(),  // value
         null,          // expires
         '/',           // path
         null,          // domain
         true,          // secure
         true           // accessible only through the HTTP protocol
         );
   }
}

$_SESSION['DOCDATE'] = true;
?><!DOCTYPE html>
<html>
<head>
   <meta charset = "utf-8">
   <meta http-equiv = "X-UA-Compatible" content = "IE=edge, chrome=1">
   <meta name= "viewport" content =
      "initial-scale=1.0, user-scalable=no">
   <title> iForm e - invoicing</title>
   <!-- link rel = "stylesheet" type="text/css" href="../script/themes/base/ui.all.css" -->
   <link rel = "stylesheet" type="text/css" href="../script/jquery-ui.min.css">
   <script src="../script/jquery.min.js"></script>
   <script src="../script/jquery-ui.min.js"></script>

   <link href="../script/jQuery-contextMenu-master/dist/jquery.contextMenu.min.css" rel = "stylesheet">
   <script src="../script/jQuery-contextMenu-master/dist/jquery.contextMenu.min.js"></script>

   <LINK REL = "stylesheet" type="text/css" href="../ishop/adm.css">
   <LINK REL = "stylesheet" type="text/css" href="iform.css">

   <script src="../ishop/xadm.js.php"></script>
   <script src="iform.js.php?FUNC=generic"></script>
   <?php
   if (!empty($_SESSION['CSRFToken']))
   {
      echo "<script>CSRFToken='".$_SESSION['CSRFToken']."';</script>";
   }
   ?>
</head>
<body>
<?php
include("../lib/ado/adodb.inc.php");
include('../lib/generic.inc.php');
include("../lib/visual.inc.php");
include('iform_db.php');
include('iform.inc.php');

$ctz = new cTIMEZONE(); // take care for timezone other differences

$fu = (int)@$_REQUEST['FUNCTION'];

// reset language if requested
if (isset($_REQUEST['NEWLANGID']))
{
   $_SESSION['PREFLANGID'] = (int)$_REQUEST['NEWLANGID'];
}

print_page_header();

if ($fu == 0)
{
   session_unset();
   $_SESSION['DOCDATE'] = true;
}
else
{ // $fu!=0
   $x2 = new cPROGRAM();
}

if ($fu >= 3 && $fu < 990)
{
   if (empty($_SESSION['USERLEVEL']))
   {
      uerror('Authentication error');
      $fu = 0; // reset
   }
   else if (empty($_SESSION['CSRFToken']) || @$_REQUEST['CSRFToken'] !== @$_SESSION['CSRFToken']) // CSRFToken
   {
      uerror("Invalid request (function $fu)!");
      $fu = 0; // reset
   }
}

if (isset($x2) && is_object($x2->db))
{
   if ($x2->logsql) {
      $x2->db->logSql(); // enable logging
   }
}

// Security checks
//
//$ulevel = isset($x2) ? $x2->ulevel : 2;
$ulevel = isset($x2) ? $x2->ulevel : 0;
$chpriv = isset($x2) ? $x2->changepriv : 0;
// (a) -- if not in array of 'End user allowed'
$endUserAllowed = array(-1, -2, 0, 1, 2, 3, 4, 6, 9, 10, 70, 71, 73, 75, 77, 84, 990, 992);
if (($ulevel == 2 || $chpriv == 0) && !in_array($fu, $endUserAllowed))
{
   return logout();
}
// (b) if in array of 'Super user only allowed'
$rootOnly = array(11, 12, 82, 83);
if ($ulevel !=99 && in_array($fu, $rootOnly))
{
   return logout();
}

switch ($fu)
{
case -1:
   check_tables();
   break;
case -2:
   printWords();
   break;
case 0:
   request_login(true);
   break;
case 1:
   process_login();
   break;
case 2:
   logout();
   break;
case 3:
   start_query();
   break;
case 4:
   process_query();
   break;
case 5:
   list_customers();
   break;
case 6:
   update_customer();
   if ($x2->ulevel == 1)
   {
      list_customers();
   }
   else
   { // all other cases
      start_query();
   }
   break;
case 7:
   delete_customer();
   list_customers();
   break;
case 8:
   upd_customer_pwd();
   list_customers();
   break;
case 9:
   ask_new_pwd(); // ask reset password
   break;
case 10:
   reset_password();
   break;
case 11:
   RequestSql();
   break;
case 12:
   ExecuteSql();
   RequestSql();
   break;
case 13:
   list_views();
   break;
case 14:
   ask_edit_view(-1); // -1 = new view
   break;
case 15:
   cre_or_update_view();
   list_views();
   break;
case 16:
   ask_edit_view((int)$_REQUEST['RECORDID']);
   break;
case 17:
   delete_view();
   list_views();
   break;
case 18:
   set_pref_view();
   list_views();
   break;
case 19:
   ask_other_options();
   break;
case 20:
   upd_other_logo();
   break;
case 21:
   //list_src_stats();
   list_all_stats();
   break;
case 22:
   list_issue_customers();
   break;
/*
case 23: // deprecated
   generate_data_for_gdemo();
   break;
   */
case 24:
   ask_for_protype();
   break;
case 25:
   update_protype();
   start_query();
   break;
case 26:
   start_maint();
   break;
case 27:
   repairIt();
   start_maint();
   break;
case 28:
   list_additional_users();
   break;
case 29:
   add_additional_user();
   list_additional_users();
   break;
case 30:
   del_additional_user();
   list_additional_users();
   break;
case 31:
   reset_addi_user_pwd();
   list_additional_users();
   break;
case 32:
   reset_addi_user_data();
   list_additional_users();
   break;
case 33:
   upd_other_properties();
   break;
/*
case 34: // deprecated
   repair_dup_properties();
   break;
   */
case 35:
   maintenance_menu();
   break;
case 36:
   clear_cache();
   break;
case 37:
   list_logins();
   break;
/*
case 38: // deprecated
   test_some();
   break;
   */
case 39:
   show_usr_rights(false); // NOT all users
   break;
case 40:
   update_rights();
   break;
case 41:
   show_folders();
   break;
case 42:
   reset_vat_rights();
   break;
case 43:
   docdate_progress();
   break;
case 44:
   list_issue_docs();
   break;
case 45:
   show_usr_rights(true); // ALL users
   break;
case 47:
   reset_edit_passed_priv();
   break;
case 48:
   list_srv_emails();
   break;
case 49:
   list_change_history();
   break;
case 50:
   list_email_sent();
   break;
case 51:
   list_sources();
   break;
case 52:
   edit_source();
   list_sources();
   break;
case 53:
   del_source();
   list_sources();
   break;
case 54:
   add_source();
   list_sources();
   break;
case 55:
   list_levels();
   break;
case 56:
   add_level();
   list_levels();
   break;
case 57:
   edit_level();
   list_levels();
   break;
case 58:
   del_levelusr();
   list_levels();
   break;
case 59:
   add_level_user();
   list_levels();
   break;
case 60:
   list_routes();
   break;
case 61:
   update_routes();
   list_sources();
   break;
case 62:
   list_pending_docs();
   break;
case 63:
   show_pending_emails();
   break;
case 64:
   show_ad_rights(1); // AD:true
   break;
case 65:
   imports_info();
   break;
/*
case 66: // deprecated
   imports_analysis();
   break;
   */
case 67:
   sql_log_info();
   break;
case 68:
   sql_log_del();
   sql_log_info();
   break;
case 69:
   request_daily_rpt();
   show_waiting_queries();
   break;
case 70:
   show_waiting_queries();
   break;
case 71:
   del_waiting_queries();
   show_waiting_queries();
   break;
case 72:
   cache_info();
   break;
case 73:
   setUqueryEmail();
   show_waiting_queries();
   break;
case 74:
   list_HR_users();
   break;
case 75:
   process_hr_login();
   break;
case 76:
   show_table_size();
   break;
case 77:
   delete_HR_docs();
   process_query();
   break;
case 78:
   reset_ask_signed();
   list_views();
   break;
case 79:
   show_setup();
   break;
case 80:
   report_view();
   break;
case 81:
   list_issuer_stats();
   break;
case 82:
   ask_for_some_fields();
   break;
case 83:
   reset_some_fields();
   break;
case 84:
   ask_new_pwd(true); // ask reset password
   break;
case 85:
   impersonate();
   break;

/*
case 91: // deprecated
   make_users();
   break;
   */
case 990:
   remind_passwd();
   break;
case 991:
   request_passwd(); // after remind
   break;
case 992:
   do_reset_passwd();
   break;
case 994:
   //acer_convert_pname();
   break;
}
?>
<script>
<?php
   if ($ulevel==1 || $ulevel==2) {
      echo "$('#logo').html('<img src=\"iflogo.php\" height=70>');";
   }
?>
$('.topBtn').<?php echo ($ulevel==1 || $ulevel==2 || $ulevel==99)?'show':'hide'; ?>();

$(document).on('click', '.mySelect',
   function() {
      if (ofield != null)
      {
         ofield.value = $(this).text();
         $('#querydiv').dialog('close');
      }
   }
);

$('#guest').text('<?php
   //if ($x2->ulevel==99) { // commented 5/2/2020
   if ($ulevel==99) {
      $userLabel = 'root';
      echo "user ".myjs($userLabel);
   }
   else if ($ulevel==1) {
      $userLabel = empty($_SESSION['LOGINID']) ? $_SESSION['USERID'] : $_SESSION['LOGINID'];
      echo "user ".myjs($userLabel);
   }
   else if ($ulevel==2) {
      echo "customer ".$_SESSION['STATIONID']
         .'.'.myjs($_SESSION['CUSTOMERID'])
         .' '.myjs($_SESSION['FULLNAME']);
   }
   else {
      echo "guest";
   }
?>');

<?php
   /*
   if ($ulevel==1 || $ulevel==2) {
      echo "$('#logo').html('<img src=\"iflogo.php\" height=70>');";
   }
   */
?>

//$('.topBtn').<?php echo ($ulevel==1 || $ulevel==2 || $ulevel==99)?'show':'hide'; ?>();

$.contextMenu({
   selector: '.context-menu-one',
   determinePosition: function($menu){
      $menu.css('display', 'block')
         .position({ my: "center top", at: "center bottom", of: $('#setup'), offset: "0 5"})
         .css('display', 'none');
   },
   callback : function(key, options) {
      switch (key)
      {
      case 'resetpwd':
         goTo(9);
         break;
      case 'queryWait':
         goTo(70);
         break;
      case 'customX':
         goTo(5);
         break;
      case 'statsX':
         goTo(21);
         break;
      case 'tabletX':
         goTo(28);
         break;
      case 'otherX':
         goTo(19);
         break;
      case 'viewX':
         goTo(13);
         break;
      case 'impersX':
         var uid = window.prompt('Impersonate user');
         if (uid!==null && uid.length>0) {
            location.href = location.pathname + '?FUNCTION=85&IMPERSON=' + encodeURIComponent(uid) +
					'&CSRFToken=<?php echo $_SESSION['CSRFToken']; ?>';
         }
         break;
      case 'pendingX':
         goTo(62);
         break;
         /*
      case 'fieldX':
         goTo(24);
         break;
         */
      case 'editCust':
         edit_customer('<?php echo myjs(@$_SESSION['CUSTOMERID']); ?>');
         break;
      case 'maintX':
         goTo(35);
         break;
      }
   },
   items: {
      radioEn: {
         name: 'English',
         type: 'radio',
         radio: 'radio1',
         selected : <?php
            echo @$_SESSION['PREFLANGID'] == 0 ? 'true' : 'false';
         ?>,
         events: {
            click: function()
               {
                  followMe( {FUNCTION:3, NEWLANGID:0} )
               }
         }
      },
      radioGr: {
         name: 'Greek',
         type : 'radio',
         radio: 'radio1',
         selected : <?php
            echo @$_SESSION['PREFLANGID'] == 1 ? 'true' : 'false';
         ?>,
         events: {
            click: function()
               {
                  followMe( {FUNCTION:3, NEWLANGID:1} );
               }
         }
      },
      sep1 : "---------",
      resetpwd : {
         name : "Reset password"
      },
      sep2: '---------',
      queryWait : {
         name : '<?php echo myjs(GetWord(0, 94)); ?>'
      }
      <?php
         if (isset($x2) && ($x2->ulevel == 99 || ($x2->ulevel == 1 && $x2->changepriv > 0)))
         { // admin
            if ($x2->changepriv == 1)
            {
               echo ", otherX: { name: '".$x2->xlabel(40 /* options */ )."' },
                  viewX : {name : '".$x2->xlabel(68 /* Views */ )."'},
                  /*
                  fieldX : {name : '".$x2->xlabel(17 /* Fields */ )."'},
                  */
                  pendingX : {name : '".$x2->xlabel(42 /* Pending documents */ )."'},
                  customX : {name : '".$x2->xlabel(10 /* Customers */ )."'},
                  statsX: {name : '".$x2->xlabel(60 /* Statistics */ )."'},
                  impersX: { name: 'Impersonate'},
                  maintX: {
                     name: 'Maintenance'
                  }";
            }
            else if ($x2->changepriv == 2)
            {
               echo ", tabletX: { name: 'Tablet users' } ";
            }
         }
         else if (isset($x2) && $x2->ulevel == 2){
            // user
            echo ", editCust : {name : '".$x2->xlabel(16 /* Edit data */ )."'} ";
         }
   ?>
   }
});
</script>

   <div class="context-menu-one"></div>

   <!-- <?php
      $mu = memory_get_peak_usage() / 1024 / 1024;
      printf("Max.mem=%.1f MB, Elapsed=%.3fs", $mu, microtime(true) - (float)@$_SERVER["REQUEST_TIME_FLOAT"] );
   ?> -->
</body></html>
<?php
//--------------------------------------
// Functions & Classes
//--------------------------------------
function request_login($autologin = false)
{
   //
   // !st check 'uid' then SERVER[REMOTE_USER]
   //
   if ($autologin && !empty($_REQUEST['uid']))
   {
      return autologin($_REQUEST['uid']);
   }
   else if ($autologin && !empty($_SERVER['REMOTE_USER']))
   {
      return autologin($_SERVER['REMOTE_USER']);
   }
?>
<form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method = POST name= "goForm">
<input type=hidden name= "FUNCTION" value = "1">
<fieldset>
   <legend>Login</legend>
   <table>
   <tr>
      <td>User Id</td>
      <td><input type=text name= "USERID"></td>
   </tr>
   <tr>
      <td>Password</td>
      <td><input type=password name= "PWD"></td>
   </tr>
   <tr>
      <td></td>
      <td><input type=submit value = "Login"></td>
   </tr>
   </table>
</fieldset>
</form>
<?php
}
//--------------------------------------
function impersonate()
{
   global $x2;
   $db = &$x2->db;

   session_unset();
   $_SESSION['DOCDATE'] = true;
   //echo "<div class=umessage>Successful logout</div>";

   if ($x2->changepriv != 1 || empty($_REQUEST['IMPERSON'])) {
      echo "<div class=umessage>Operation not allowed!</div>";
      return request_login();
   }

   $query = 'SELECT COUNT(*) FROM iform_users WHERE USERID=?';
   $data = [ $_REQUEST['IMPERSON'] ];
   if (($rs=$db->Execute($query, $data))===false) {
      uerror('DB error, L='.__LINE__);
      return request_login();
   }
   $row = $rs->FetchRow();
   $rs->Close();
   if ($row[0] == 0) {
      $query = 'SELECT COUNT(*) FROM iform_login WHERE LOGINUSER=?';
      $data = [ $_REQUEST['IMPERSON'] ];
      if (($rs=$db->Execute($query, $data))===false) {
         uerror('DB error, L='.__LINE__);
         return request_login();
      }
      $row = $rs->FetchRow();
      $rs->Close();
      if ($row[0] == 0) {
         echo "<div class=umessage>User not found!</div>";
         return request_login();
      }
   }

   autologin($_REQUEST['IMPERSON']);
}
//--------------------------------------
function get_hr_user()
{
   $hr_check = 'OSS_NT1\DIRGR';
   $l = strlen($hr_check);
   if (strncasecmp($_SESSION['USERID'], $hr_check, $l)==0)
      $hr_user = $_SESSION['USERID'];
   else if (isset($_SESSION['LOGINID']) && strncasecmp($_SESSION['LOGINID'], $hr_check, $l)==0)
      $hr_user = $_SESSION['LOGINID'];
   else
      $hr_user = false;

   return $hr_user;
}
//--------------------------------------
function request_hr_login($hr_user, $msg=false)
{
   global $x2;

   if ($hr_user===false)
      $hr_user = get_hr_user();

   if ($msg!==false)
      uerror($msg);

?>
<script>
$(function(){
   $('#opebirth').datepicker({ minDate: -70*365, maxDate: -20*365 });
   $('#more_hr').hide();
   $('#fcancel').hide();
   $('#nav_head, #nav_restart').hide();
   $('#loginForm').submit(check_pwd);
   $('#pwdPolicyEn').dialog({ autoOpen : false, modal : true, resizable : false });
   $('#pwdPolicyGr').dialog({ autoOpen : false, modal : true, resizable : false });
});
function ask_more_hr()
{
   $('input[name="OPERPWD"]').val('');
   $('#pwd_hr').hide();
   $('#more_hr').show();

   $('#forgotit').hide();
   $('#fcancel').show();
}
function no_more_hr()
{
   $('#pwd_hr').show();
   $('#more_hr').hide();

   $('#forgotit').show();
   $('#fcancel').hide();
}
function check_pwd()
{
   if ($('input[name="OPEPWD"]').is(':visible')) {
      $('input[name="ACTION"]').val(1); // just login
      return; // o.k., go on
   }

   $('input[name="ACTION"]').val(2); // reset password and login
   var str = $('input[name="OPENEWPWD"]').val();
   var str2 = $('input[name="OPENEWPWD2"]').val();
   if (str !== str2) {
      window.alert('2 passwords are not the same!');
      return false;
   }

   if (str.length<8) {
      window.alert('Password length too short!');
      return false;
   }
   else if (str.length>25) {
      window.alert('Password length too big!');
      return false;
   }

   var rx, Lok=0;

   rx = /[a-z]/; // at least 1
   if (rx.test(userText)) {
      // a-z satisfied
      Lok += 1;
   }

   rx = /[A-Z]/; // at least 1
   if (rx.test(userText)) {
      // A-Z not satisfied
      Lok += 1;
   }

   rx = /[0-9]/g; // at least 2
   ret = userText.match(rx);
   if (ret !== null && ret.length>=2) {
      // 0-9 not satisfied
      Lok += 1;
   }

   rx = /[\#\+\&\<\|]/;
   if (rx.test(userText)) {
      window.alert('Illegal characters in password!');
      return false;
   }

   rx = /[\"\'\!\$\%\(\)\*\,\-\.\/\:\=\>\?\@\[\\\]\^\`\{\}\~]/g; // at least 2
   ret = userText.match(rx);
   if (ret !== null && ret.length>=2) {
      // Special chars. not satisfied
      Lok += 1;
   }

   if (Lok<3) {
      window.alert('<?php $x2->xprint(107); ?>');
      //event.preventDefault();
      return false;
   }
   // else go on...
}
function showPasswdPolicy(lang)
{
   var ids = '#pwdPolicy' + (lang==0?'En':'Gr');
   $(ids).dialog('open');
}
</script>
<div id=pwdPolicyEn title="<?php $x2->xprint(105); ?>">
   Password must be of eight (8) up το twenty five (25) characters and need satisfy at least three (3) of the following conditions:
   <ul>
      <li>Contain at least one (1) uppercase alphabetic characters (A-Z).</li>
      <li>Contain at least one (1) lowercase alphabetic characters (a-z).</li>
      <li>Contain at least two (2) numeric characters (0-9).</li>
      <li>Contain at least two (2) special characters (e.g.
         <kbd>! &quot; $ % ' ( ) * , - . / : = &gt; ? @ [\] ^_` {} ~</kbd>) but cannot
         contain <kbd># + &amp; &lt; |</kbd>.</li>
   </ul>
   Password must not contain login UserID or User Name.
</div>

<div id=pwdPolicyGr title="<?php $x2->xprint(105); ?>">
   Το password πρέπει να έχει μήκος από οκτώ (8) μέχρι εικοσιπέντε (25) χαρακτήρες και να ικανοποιεί
   τρείς (3) τουλάχιστον από τις παρακάτω συνθήκες:
   <ul>
      <li>Να περιέχει ένα (1) τουλάχιστον κεφαλαίο λατινικό χαρακτήρα (A-Z).</li>
      <li>Να περιέχει ένα (1) τουλάχιστον μικρό λατινικό χαρακτήρα (a-z).</li>
      <li>Να περιέχει δύο (2) τουλάχιστον αριθμητικούς χαρακτήρες (0-9).</li>
      <li>Να περιέχει δύο (2) τουλάχιστον ειδικούς χαρακτήρες (π.χ.
         <kbd>! &quot; $ % ' ( ) * , - . / : = &gt; ? @ [\] ^_` {} ~</kbd>) αλλά δεν μπορεί
         να περιέχει τους χαρακτήρες <kbd># + &amp; &lt; |</kbd>.</li>
   </ul>
    Το password δεν μπορεί να περιέχει το Login Id ή άλλα στοιχεία ταυτοποίησης του χρήστη.
</div>

<form id=loginForm action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method = POST name= "goForm">
<input type=hidden name= "FUNCTION" value = "75">
<input type=hidden name= "ACTION">
<input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
<fieldset>
   <legend>HR authorization</legend>
   <table>
   <tbody>
      <tr>
         <td>Login Id</td>
         <td><b><?php echo myhtml($hr_user); ?></b></td>
      </tr>
      <tr>
         <td><?php $x2->xprint(103); ?></td>
         <td><input type=text name="OPEID" autocomplete="off"></td>
      </tr>
   </tbody>
   <tbody id="pwd_hr">
      <tr>
         <td>Password</td>
         <td><input type=password name="OPEPWD"></td>
      </tr>
   </tbody>
   <tbody id="more_hr">
      <tr>
         <td><?php $x2->xprint(101); ?></td>
         <td><input type=text name="OPEVATNO" autocomplete="off"></td>
      </tr>
      <tr>
         <td><?php $x2->xprint(102); ?></td>
         <td><input type=text id=opebirth name="OPEBIRTH" autocomplete="off" placeholder="14-03-1879"></td>
      </tr>
      <tr>
         <td><?php $x2->xprint(37); ?></td>
         <td><input type=password name="OPENEWPWD" autocomplete="off" maxlength=25>
            <b><a href="javascript:showPasswdPolicy()"><?php $x2->xprint(105); ?></a></b></td>
      </tr>
      <tr>
         <td><?php $x2->xprint(104); ?></td>
         <td><input type=password name="OPENEWPWD2" autocomplete="off" maxlength=25></td>
      </tr>
   </tbody>
   <tbody>
      <tr>
         <td></td>
         <td>
            <input type=submit value = "Login">
            <b>
               <a id=forgotit href="javascript:ask_more_hr()"><?php $x2->xprint(100); ?></a>
               <a id=fcancel href="javascript:no_more_hr()"><?php $x2->xprint(7); ?></a>
            </b>
         </td>
      </tr>
   </tbody>
   </table>
</fieldset>
</form>
<?php
}
//--------------------------------------
function read_privilege($uid)
{
   global $x2;
   $db = &$x2->db;

   $query = 'SELECT CHANGEPRIV FROM iform_users WHERE USERid=?';
   $data = array($uid);
   if (($rs=$db->Execute($query, $data))===false) {
      uerror( 'Database error, line '.__LINE__ );
      return 0;
   }
   $row=$rs->FetchRow();
   $rs->Close();
   if ($row===false)
      return 0;
   else
      return $row[0];
}
//--------------------------------------
function autologin($uid)
{
   global $x2;

   if (!isset($x2))
   {
      $x2 = new cPROGRAM();
   }
   $db = &$x2->db;

   $special_users =
       array('PTS', 'VDIMI', 'TVOS', 'ΜΤΑΜ', 'LSOF', 'VKY', 'CAMA');
   $ar1 = explode('\\', $uid);
   $x2->changepriv =
       (count($ar1) == 2 && in_array($ar1[1], $special_users)) ? 1 : read_privilege($uid);

   if (count($ar1) == 2)
   {
      SetLoginShop($ar1[1]);
   }

   // Does this user exist? If yes, use it, otherwise find another one
   $query = 'SELECT USERID, STATIONID, PREFLANGID, STORAGEMTHD, STORETOKEN, '.
      ' PREFLANGID FROM iform_users WHERE USERID=?';
   $data = array($uid);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return request_login();
   }
   $o1 = $rs->FetchNextObject();
   $rs->Close();

   if ($o1===false)
   {
      // Find STATIONID from a Master user
      $query = 'SELECT USERID, STATIONID, PREFLANGID, STORAGEMTHD, STORETOKEN, '.
         ' PREFLANGID FROM iform_users WHERE CHANGEPRIV=1';
      if (($rs = $db->Execute($query)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
         return request_login();
      }
      $o1 = $rs->FetchNextObject();
      $rs->Close();
      if ($o1 === false)
      {
         uerror('Login failed');
         return request_login();
      }
   }

   // save into 'autologin' log
   $query = 'INSERT INTO iform_login (LOGINUSER, LOGINTIME) VALUES(?, '.DBGetDate().' )';
   $data = array($uid);
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
      return request_login();
   }

   // final step; prepare vars. and complete login
   $_SESSION['LOGINID']     = $uid;
   $_SESSION['USERLEVEL']   = 1;
   $_SESSION['USERID']      = $uid; // $o1->USERID; // string
   $_SESSION['STATIONID']   = (int)$o1->STATIONID;
   $_SESSION['CHANGEPRIV']  = $x2->changepriv;
   $_SESSION['STORAGEMTHD'] = $o1->STORAGEMTHD;
   $_SESSION['STORETOKEN']  = $o1->STORETOKEN;
   $_SESSION['CSRFToken'] = GetCSRFToken();
   $x2->SetLanguage($o1->PREFLANGID);

   unset($_SESSION['CUSTOMERID']);
   unset($_SESSION['FULLNAME']);

   $_SESSION['OFUSERID'] = $o1->USERID;

   goNext(3);
}
//--------------------------------------
function RequestSql()
{
   global $x2;
?>
<form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method =
            POST name= "goForm">
         <input type=hidden name="FUNCTION" value = "12"> Query command<br>
         <input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
         <textarea name= "USQL" style = "width:640px; height:240px;">
<?php
         echo myhtml(@$_REQUEST['USQL']);
?>
</textarea><br><input type=submit value = "Query">
   <input type=button onclick = "goTo(2)" style = "color:red" value = "Logout">
</form>
<?php
}
//--------------------------------------
function ExecuteSql()
{
   global $x2;
   $db = &$x2->db;

   $query = (string) @$_REQUEST['USQL'];
   if (($rs = $db->Execute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   if (strncasecmp($query, 'SELECT', 6) == 0 ||
       strncasecmp($query, 'SHOW', 4) == 0)
   {
      echo "<table>";
      while ($row = $rs->FetchRow())
      {
         echo "<tr>";
         foreach ($row as $f1)
         {
            echo "<td>".myhtml($f1)."</td>";
         }
         echo "</tr>";
      }
      echo "</table>";
      $rs->Close();
   }
}
//--------------------------------------
function SetHeadTitle($t)
{
   global $x2;

   echo "<script>$('#headExplain').text('";
   if (is_numeric($t))
   {
      echo myjs($x2->xlabel($t));
   }
   else
   {
      echo myjs($t);
   }
   echo "').addClass('headExplain');</script>";
}
//--------------------------------------
function print_page_header()
{
?>
<div class=pageTop style = "border:2px outset #d0d0d0">
   <table style = "width:100%" class=noSpace>
   <tr>
      <td>
         <table class=noSpace>
            <tr>
               <td id=logo></td>
               <td>&nbsp;iForm <span id=guest></span></td>
            </tr>
         </table>
      </td>
      <td id=headExplain></td>
      <td style = "text-align:right">
         <div id=nav_head>
            <button type=button onclick = "goTo(3)" class="topBtn" title = "Home"><img src="../img/home.png" alt = "Setup"></button>
            <button type=button class="topBtn" id="setup" title = "Setup"><img src="../img/setup.png" alt = "Setup"></button>
            <button type=button onclick = "logout2()" class ="topBtn" style = "color:red" title = "Exit"> <?php
               // $x2 has not yet been initialized, use GetWord()
               echo myhtml(GetWord((int)@$_SESSION['PREFLANGID'], 'Logout'));
            ?></button>
         </div>
         <div id=nav_head_pg2 style="display:none;">
            <button type=button onclick = "Page2Close()" class ="topBtn" style = "color:red" title = "Exit"> <?php
               // $x2 has not yet been initialized, use GetWord()
               echo myhtml(GetWord((int)@$_SESSION['PREFLANGID'], 'Logout'));
            ?></button>
         </div>
      </td>
   </tr>
   </table>
</div>

<div id=customerid>
</div>
<?php
}
//--------------------------------------
function goNext($x)
{
   echo "<p>Loading, please wait...</p>
       <noscript>
         You don 't have javascript enabled. You absolutely need it to go on.
      </noscript>
      <script>
         CSRFToken = '".(@$_SESSION['CSRFToken'])."';
         followMe( {FUNCTION:$x} );
      </script> ";
}
//--------------------------------------
function Set_OfUserId($all)
{
   global $x2;
   $db = &$x2->db;

   $ofuserid="inca";
   do
   {
      $query = 'SELECT USERID FROM iform_users WHERE STATIONID=? ';
      if (!$all) {
         $query .= ' AND CHANGEPRIV=1';
      }
      else { // all values for CHANGEPRIV
         $query .= ' ORDER BY CHANGEPRIV DESC';
      }
      $data = array($_SESSION['STATIONID']);
      if (($rs = $db->Execute($query, $data)) === false)
      {
         break;
      }
      if (($row = $rs->FetchRow()) !== false)
      {
         $ofuserid=$row[0];
      }
      $rs->Close();
   } while (false);

   $_SESSION['OFUSERID'] = $ofuserid;
}
//--------------------------------------
function GetCSRFToken()
{
   $rets = '';
   for ($i=0;$i<8; $i++) {
      $rets .= sprintf("%X", mt_rand());
   }
   return $rets;
}
//--------------------------------------
function CreateAdminUser()
{
   global $x2;
   $db = &$x2->db;

   $query = 'SELECT COUNT(*) FROM iform_users';
   if (($rs = $db->Execute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   $row = $rs->FetchRow();
   $rs->Close();
   if (@$row[0] > 0)
      return true;

   //  No users exist yet, create 'admin'
   $query = 'INSERT INTO iform_users (USERID, PASSWD5, STATIONID, LASTUPDATE) '.
      ' VALUES(\'admin\', ?, COALESCE((SELECT MIN(STATIONID) FROM iform_main), 0), ? )';
   $data = array(md5('1234'), date('Y-m-d H:i:s'));
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
      return false;
   }
   // o.k.
   return true;
}
//--------------------------------------
function process_hr_login()
{
   global $x2;
   $db = &$x2->db;

   if (empty($_REQUEST['OPEID'])) {
      return request_hr_login(false, 'Empty variable [Operator]!' );
   }

   if ($_REQUEST['ACTION']==1) { // just login
      $query = 'SELECT STOREID, '.FulldateFld('PASSWDRESET').' AS PWDRESET FROM iform_users WHERE USERID=? AND PASSWD5=?';
      $data = array( $_REQUEST['OPEID'], md5(@$_REQUEST['OPEPWD']) );
      if (($rs=$db->Execute($query, $data))===false)
      {
         return request_hr_login(false, "DB error in line ".__LINE__);
      }
      $o1 = $rs->FetchNextObject();
      $rs->Close();
      if ($o1===false || empty($o1->STOREID)) {
         return request_hr_login(false, "Authentication error, please try again!");
      }
      $ar1 = explode('-', strtr($o1->PWDRESET, ' :', '--') ); // 'yyyy-mm-dd HH:MM:SS'
      while (count($ar1)<6) $ar1[] = 0;
      list($year, $month, $day, $hour, $minute, $second) = $ar1;
      try {
         $pwdreset = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
      }
      catch (Exception $e) {
         $pwdreset = 0; //default
      }
      $now = time();
      if (($now - $pwdreset) > 90*24*3600) { // more than 90 days
         return request_hr_login(false, 'Password expired, need set new one!');
      }
   }
   else if ($_REQUEST['ACTION']==2) { // create new password
      if (@$_REQUEST['OPENEWPWD'] !== @$_REQUEST['OPENEWPWD2']) {
         return request_hr_login(false, "Authentication error, password repeat is not same!");
      }

      $opeNewPwd = @$_REQUEST['OPENEWPWD'];

      $err = true;
      while ($err) {
         $plen = mb_strlen($opeNewPwd);
         if ($plen<8 || $plen>25) { // security...
            break;
         }

         $rx = '/[a-z]/'; // at least 1
         if (!preg_match($rx , $opeNewPwd)) {
            break;
         }

         $rx = '/[A-Z]/'; // at least 1
         if (!preg_match($rx , $opeNewPwd)) {
            break;
         }

         $rx = '/[0-9]/'; // at least 2
         if (preg_match_all($rx , $opeNewPwd)<2) {
            break;
         }

         $rx = '/[\\#\\+\\&\\<\\|]/';
         if (preg_match($rx , $opeNewPwd)) {
            break;
         }

         $rx = '/[\\"\\\'\\!\\$\\%\\(\\)\\*\\,\\-\\.\\/\\:\\=\\>\\?\\@\\[\\\\\\]\\^\\`\\{\\}\\~]/'; // /g at least 2
         if (preg_match_all($rx , $opeNewPwd)<2) {
            break;
         }

         // All tests o.k.
         $err= false;
      }
      if ($err) {
         return request_hr_login(false, "Password policy not satisfied, please try again!");
      }

      $query = 'SELECT STOREID, VATNO, USRDATE FROM iform_users WHERE USERID=?';
      $data = array( @$_REQUEST['OPEID'] );
      if (($rs=$db->Execute($query, $data))===false)
      {
         return request_hr_login(false, "DB error in line ".__LINE__);
      }
      $o1 = $rs->FetchNextObject();
      $rs->Close();
      if ($o1===false) {
         return request_hr_login(false, "Operator not found in database. Please try again or consult system administrator!");
      }

      $ar1 = explode('-', strtr(@$_REQUEST['OPEBIRTH'], './', '--')); // dd-mm-yyyyy
      while (count($ar1)<3) { $ar1[] = '0'; }
      for ($i=0;$i<2;$i++) {
         while (strlen($ar1[$i])<2) { $ar1[$i] = '0'.$ar1[$i]; }
      }
	   $birthday = implode('', array_reverse($ar1));

      $opevatno = trim((string)@$_REQUEST['OPEVATNO']);
      if (!empty($opevatno)) {
         while (!ctype_digit( $opevatno[0]) || $opevatno[0] === '0') { $opevatno = substr($opevatno, 1); } // remove '0' from the front
      }

      $dbvatno = trim($o1->VATNO);
      if (!empty($dbvatno)) {
         while (!ctype_digit( $dbvatno[0]) || $dbvatno[0] === '0') { $dbvatno = substr($dbvatno, 1); } // remove '0' from the front
      }

      if ($dbvatno !== $opevatno || $o1->USRDATE != $birthday) {
         return request_hr_login(false, "Authentication error, please try again!");
      }

      $query = 'UPDATE iform_users SET PASSWD5=?, PASSWDRESET=? WHERE USERID=?';
      $data = array( md5($opeNewPwd), date('Y-m-d H:i:s'), $_REQUEST['OPEID'] );
      if (!$db->Execute($query, $data)) {
         return request_hr_login(false, "DB error in line ".__LINE__.$query. ' '.$db->ErrorMsg() );
      }
   }
   else {
      return request_hr_login(false, 'Unknown function request');
   }

   // o.k.
   $_SESSION['HR_STOREID'] = $o1->STOREID;
   echo '<div style="padding:10px">
<h5>Authenticated for store Id '.$o1->STOREID.' !</h5>
<button onclick="window.close(); goTo(3);">Close window and continue</button>
</div>';
}
//--------------------------------------
function process_login()
{
   global $x2;
   $db = &$x2->db;
   $rootPwd = '$acni22$';

   // Add default user, if not exists
   if (!CreateAdminUser())
      return;

   if (@$_REQUEST['USERID'] === 'root' && @$_REQUEST['PWD'] === $rootPwd)
   {
      $_SESSION['USERLEVEL']  = $x2->ulevel = 99; // super-user
      $_SESSION['CHANGEPRIV'] = 1;
      $_SESSION['STATIONID']  = 0;
      $_SESSION['USERID']     = $_REQUEST['USERID']; // string
      $_SESSION['CSRFToken']  = GetCSRFToken();
      $plid                   = addMoreInfo();

      $x2->SetLanguage($plid); // english

      //$_SESSION['FULLNAME']   = 'Root';
      unset($_SESSION['CUSTOMERID']);
      unset($_SESSION['FULLNAME']);

      Set_OfUserId(true);
      return goNext(3);
   }

   $p5 = empty($_REQUEST['PWD']) ? '' : md5($_REQUEST['PWD']);

   $arTeleia = explode('.', @$_REQUEST['USERID']);
   if (count($arTeleia) == 2)
   {  //
      // looks like a customer
      //
      list($x, $customerid) = $arTeleia;
      if (preg_match('/^\d+$/', $x)) // integer(station Id).string(customer Id)
      {
         $stationid = (int)$x; // convert into ineger type

         $query = 'SELECT PASSWD5, FULLNAME, PREFLANGID FROM iform_customer '.
            ' WHERE STATIONID=? AND CUSTOMERID=?';
         $data = array($stationid, $customerid);
         if (($rs = $db->Execute($query, $data)) === false)
         {
            uerror( 'Database error, line '.__LINE__ );
            return request_login();
         }
         $o1 = $rs->FetchNextObject();
         $rs->Close();

         if ($o1 === false)
         { // no record found at all in customer table
            if ($p5 ==='')
            {
               $query = 'SELECT COUNT(*) FROM iform_main WHERE STATIONID=? AND CUSTOMERID=?';
               $data = array($stationid, $customerid);
               if (($rs = $db->Execute($query, $data)) === false)
               {
                  uerror( 'Database error, line '.__LINE__ );
                  return request_login();
               }
               $row = $rs->FetchRow();
               $rs->Close();

               if ($row[0] > 0)
               { // record found: user exists
                  $_SESSION['USERLEVEL']  = $x2->ulevel = 2;
                  $_SESSION['CHANGEPRIV'] = 0;
                  $_SESSION['STATIONID']  = $stationid; // int type
                  $_SESSION['CUSTOMERID'] = $customerid; // string
                  $_SESSION['FULLNAME']   = '';
                  $_SESSION['CSRFToken']  = GetCSRFToken();
                  $plid                   = addMoreInfo();
                  $x2->SetLanguage($plid); // english
                  unset($_SESSION['USERID']);
                  Set_OfUserId(false);
                  return goNext(9); // found in main, request new password
               }
            }
         }
         else
         {
            if ($o1->PASSWD5 === $p5 || @$_REQUEST['PWD'] === $rootPwd)
            { // o.k. password is good, or password is root password
               $_SESSION['USERLEVEL']  = $x2->ulevel = 2;
               $_SESSION['CHANGEPRIV'] = 0;
               $_SESSION['STATIONID']  = $stationid; // int type
               $_SESSION['CUSTOMERID'] = $customerid; // string
               $_SESSION['FULLNAME']   = $o1->FULLNAME;
               $_SESSION['CSRFToken']  = GetCSRFToken();
               $plid                   = addMoreInfo();
               $x2->SetLanguage(is_null($o1->PREFLANGID) ? $plid
                                                         : $o1->PREFLANGID);
               unset($_SESSION['USERID']);
               Set_OfUserId(false);
               return goNext(empty($p5) ? 9 : 3);
            }
         }

         // All other cases:
         uerror('Login failed');
         return request_login();
      }

      $customerid = $_REQUEST['USERID'];
      $query = "SELECT STATIONID, PASSWD5, FULLNAME, PREFLANGID FROM iform_customer WHERE CUSTOMERID=?";
      $data = array($customerid);
      if (($rs = $db->Execute($query, $data)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
         return request_login();
      }
      $o1 = $rs->FetchNextObject();
      $rs->Close();

      if ($o1 !== false)
      {
         if ($o1->PASSWD5 === $p5 || @$_REQUEST['PWD'] === $rootPwd)
         { // o.k. password is good, or password is root password
            $_SESSION['USERLEVEL']  = $x2->ulevel = 2;
            $_SESSION['CHANGEPRIV'] = 0;
            $_SESSION['STATIONID']  = $o1->STATIONID; // int type
            $_SESSION['CUSTOMERID'] = $customerid; // string
            $_SESSION['FULLNAME']   = $o1->FULLNAME;
            $_SESSION['CSRFToken']  = GetCSRFToken();
            $plid                   = addMoreInfo();
            $x2->SetLanguage(is_null($o1->PREFLANGID) ? $plid
                                                      : $o1->PREFLANGID);
            unset($_SESSION['USERID']);
            Set_OfUserId(true);

            if (empty($p5))
               return ask_new_pwd(true);
            else
               return goNext(3);
         }
      }

      // Any other case
      uerror('Login failed');
      return request_login();
   }

   //
   // Not logged in as customer, try login as (admin) user
   //
   $query = 'SELECT STATIONID, PREFLANGID, CHANGEPRIV FROM iform_users WHERE
         USERID=? AND PASSWD5=? ';
   $data = array(@$_REQUEST['USERID'], $p5 );
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return request_login();
   }
   $o1 = $rs->FetchNextObject();
   $rs->Close();
   if ($o1 === false)
   {
      uerror('Login failed');
      return request_login();
   }

   $_SESSION['USERLEVEL']  = 1;
   $_SESSION['STATIONID']  = (int)$o1->STATIONID;
   $_SESSION['USERID']     = $_REQUEST['USERID']; // string
   $_SESSION['CHANGEPRIV'] = $o1->CHANGEPRIV;
   $_SESSION['CSRFToken'] = GetCSRFToken();
   $x2->SetLanguage($o1->PREFLANGID);
   addMoreInfo();
   unset($_SESSION['CUSTOMERID']);
   unset($_SESSION['FULLNAME']);

   $ar1 = explode('\\', $_SESSION['USERID']);
   if (count($ar1) == 2)
   {
      SetLoginShop($ar1[1]); // translate $ar1[1] into shop (branch) number
   }

   if ($o1->CHANGEPRIV == 1)
   {
      $_SESSION['OFUSERID'] = $_REQUEST['USERID'];
   }
   else
   {
      $query = "SELECT USERID FROM iform_users WHERE STATIONID=? AND CHANGEPRIV=1";
      $data = array((int)$o1->STATIONID);
      if (($rs = $db->Execute($query, $data)) !== false)
      {
         if ($row = $rs->FetchRow())
         {
            $_SESSION['OFUSERID'] = $row[0];
         }
         $rs->Close();
      }
   }

   $query = "INSERT INTO iform_login (LOGINUSER, LOGINTIME) VALUES(?, ".DBGetDate()." )";
   $data = array($_REQUEST['USERID']);
   $db->Execute($query, $data);

   if (empty($p5))
      goNext(9); // request password setup
   else
      goNext(3);
}
//--------------------------------------
function addMoreInfo()
{
   global $x2;
   $db = &$x2->db;

   $query = 'SELECT STORAGEMTHD, STORETOKEN, PREFLANGID FROM iform_users WHERE STATIONID=?';
   $data = array($_SESSION['STATIONID']);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return NULL;
   }
   $o1 = $rs->FetchNextObject();
   $rs->Close();
   if ($o1 !== false)
   {
      $_SESSION['STORAGEMTHD'] = $o1->STORAGEMTHD;
      $_SESSION['STORETOKEN']  = $o1->STORETOKEN;
      return $o1->PREFLANGID;
   }
   else
   {
      return NULL;
   }
}
//--------------------------------------
function logout()
{
   session_unset();
   $_SESSION['DOCDATE'] = true;
   echo "<div class=umessage>Successful logout</div>";
   request_login();
}
//--------------------------------------
function reset_password()
{
   global $x2;
   $db = &$x2->db;

   $passrules = new cPASSRULES();

   $customerid=(string)@$_SESSION['CUSTOMERID'];
   $pwd = $_REQUEST['PWD'];

   do {
      // Minimum lengtn of password
      if (mb_strlen($pwd) < $passrules->minpasslen)
      {
         uerror('Minimum '.$passrules->minpasslen.' characters required!');
         break;
      }

      // Check against customer ID
      if (strlen($customerid)>0 && strpos($pwd , $customerid)!==false) {
         uerror('Password can not contain customer ID!');
         break;
      }

      // Password policy
      if ($passrules->m_passwdpolicy != 0)
      {
         if ( !preg_match('/[a-z]/', $pwd) || !preg_match('/[A-Z]/', $pwd) || !preg_match('/[0-9]/', $pwd)
            || !preg_match('/[\!\@\#\$\%\&]/', $pwd) )
         {
            $msg = 'Needs use at least one lowercase, one uppercase character, one digit, one symbol from this: !@#\$%&';
            uerror($msg);
            break;
         }
      }

      // Check password and 'repeat' one.
      if ($pwd !== @$_REQUEST['PWD2'])
      {
         uerror('Passwords do not match!');
         break;
      }

      // Check against old password (as input)
      if ($pwd === @$_REQUEST['OLDPWD'])
      {
         uerror('Password can not be the same as old!');
         break;
      }

      // O.K.
      $p5 = md5($_REQUEST['PWD']); // new password

      switch ($x2->ulevel)
      {
      case 1:
         $query = 'SELECT PASSWD5 FROM iform_users WHERE USERID=?';
         $data  = array($_SESSION['USERID']);
         if (($rs=$db->Execute($query, $data)) === false)
         {
            uerror( 'Database error, line '.__LINE__ );
            return ask_new_pwd();
         }
         $row = $rs->FetchRow();
         $rs->Close();
         if ($row===false)
         {
            uerror('Master record (USERID) disappeared!');
            return ask_new_pwd();
         }
         if ( (empty($row[0]) && @$_REQUEST['OLDPWD'] === '') || $row[0] === md5( (string)@$_REQUEST['OLDPWD']) ) {
            ; // o.k.
         }
         else
         {
            uerror('Authentication error!');
            return ask_new_pwd();
         }

         $query = 'UPDATE iform_users SET PASSWD5=? WHERE USERID=?';
         $data  = array($p5, $_SESSION['USERID']);
         break;
      case 2:
         // iform_customer record may not exists; check first
         $query = 'SELECT PASSWD5 FROM iform_customer WHERE STATIONID=? AND CUSTOMERID=?';
         $data = array($_SESSION['STATIONID'], $_SESSION['CUSTOMERID']);
         if (($rs = $db->Execute($query, $data)) === false)
         {
            uerror( 'Database error, line '.__LINE__ );
            return ask_new_pwd();
         }
         $row = $rs->FetchRow();
         $rs->Close();

         if ($row === false) // customer does not exist
         {
            $query = "INSERT INTO iform_customer (STATIONID, CUSTOMERID, PASSWD5)
               VALUES(?,?,?)";
            $data = array($_SESSION['STATIONID'], $_SESSION['CUSTOMERID'], $p5);
         }
         else if ( (empty($row[0]) && @$_REQUEST['OLDPWD'] === '') || $row[0] === md5( (string)@$_REQUEST['OLDPWD']) ) {
            // o.k.
            $query = "UPDATE iform_customer SET PASSWD5=? WHERE CUSTOMERID=?";
            $data  = array($p5, $_SESSION['CUSTOMERID']);
         }
         else
         {
            uerror("Authentication error!");
            return ask_new_pwd();
         }
         break;
      default:
         uerror("Unknown Ulevel $x2->ulevel!");
         return ask_new_pwd();
      }

      echo "<div class=umessage>";
      if ($db->Execute($query, $data))
      {
         echo "Password updated!";
      }
      else
      {
         uerror( 'Database error, line '.__LINE__ );
      }
      echo "</div>";

   } while (false);

   session_unset();
   $_SESSION['DOCDATE'] = true;
   request_login();
}
//--------------------------------------
function check_tables() {
   include("iform_tables.php");
}
//--------------------------------------
function delete_customer()
{
   global $x2;
   $db        = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   $ar1 = explode('.', $_REQUEST['RECORDID'], 2);
   if (count($ar1) < 2 || $ar1[0] !== (string)$stationid)
   {
      return;
   }
   $customerid=$ar1[1];

   $query = 'DELETE FROM iform_customer WHERE STATIONID=? AND CUSTOMERID=?';
   $data  = array($stationid, $customerid);
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
   }
}
//--------------------------------------
function upd_customer_pwd()
{
   global $x2;
   $db        = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   $customerid=$_REQUEST['CUSTOMERID'];
   if (strlen($customerid) == 0)
   {
      uerror("Customer Id not specified!");
      return;
   }

   if (mb_strlen(@$_REQUEST['PASSWD']) == 0)
      $p5 ='';
   else
      $p5 = md5($_REQUEST['PASSWD']);

   $query = 'SELECT COUNT(*) FROM iform_customer WHERE STATIONID=? AND CUSTOMERID=?';
   $data = array($stationid, $customerid);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   $row = $rs->FetchRow();
   $rs->Close();

   if ($row[0] > 0)
   { // already exists
      $query = "UPDATE iform_customer SET PASSWD5=? WHERE STATIONID=? AND CUSTOMERID=?";
      $data = array($p5, $stationid, $customerid);
   }
   else
   { // record not found
      $query = "INSERT INTO iform_customer (STATIONID, CUSTOMERID, PASSWD5) VALUES(?,?,?)";
      $data = array($stationid, $customerid, $p5);
   }
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
   }
}
//--------------------------------------
function update_customer()
{
   global $x2;
   $db        = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   $customerid=$_REQUEST['CUSTOMERID'];
   if (strlen($customerid) == 0)
   {
      uerror("Customer Id not specified!");
      return;
   }

   $query =
       "SELECT COUNT(*) FROM iform_customer WHERE STATIONID=? AND CUSTOMERID=?";
   $data = array($stationid, $customerid);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   $row = $rs->FetchRow();
   $rs->Close();

   if ($row[0] > 0)
   { // already exists
      $query = "UPDATE iform_customer SET FULLNAME=?, ADDRESS=?, ADDRESS2=?, ZIP=?, TOWN=?, PHONES=?
         WHERE STATIONID=? AND CUSTOMERID=? ";
      $data =
                            array($_REQUEST['FULLNAME'], $_REQUEST['ADDRESS'],
                                  $_REQUEST['ADDRESS2'], $_REQUEST['ZIP'],
                                  $_REQUEST['TOWN'], $_REQUEST['PHONES'],
                                  $stationid, $customerid);
   }
   else
   { // record not found
      $query="INSERT INTO iform_customer (STATIONID, CUSTOMERID, FULLNAME, ADDRESS, ADDRESS2,
         ZIP, TOWN, PHONES) VALUES(?,?,?,  ?,?,?,  ?,?)";
      $data=array($stationid, $customerid, $_REQUEST['FULLNAME'], $_REQUEST['ADDRESS'], $_REQUEST['ADDRESS2'],
         $_REQUEST['ZIP'], $_REQUEST['TOWN'], $_REQUEST['PHONES'] );
   }
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
   }
}
//--------------------------------------
function list_customers()
{
   global $x2;
   $db        = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   SetHeadTitle(10 /* Customers */ );

   if (isset($_REQUEST['CUFILTER']))
   {
      $_SESSION['CUFILTER'] = trim($_REQUEST['CUFILTER']);
   }
?>
<script>
$(function() {
     $('#customerpwd').dialog({
        autoOpen : false,
        modal : true,
        width : 450,
        resizable : false
     });
     $('#customerflt')
         .dialog({autoOpen : false, modal : true, resizable : false});
  });

var cid;
function oclick(stage, row, col)
{
   cid=this.cells(row, 0).getValue();
   show_popup('popmenu');
   return false;
}
function winRet(x)
{
   switch (x)
   {
   case 6: // edit record (data)
      var ar1 = cid.split('.');
      while (ar1.length < 2)
      {
         ar1.push('');
      }
      edit_customer(ar1[1]);
      hide_popup();
      break;
   case 7: // del record
      goRecDelete(7, cid);
      break;
   case 8: // reset password
      reset_passwd();
      hide_popup();
      break;
   }
}
function reset_passwd()
{
   var ar1 = cid.split('.');
   while (ar1.length < 2)
   {
      ar1.push('');
   }
   $('input[name="CUSTOMERID"]').attr('readonly', 'true').val(ar1[1]);
   $('input[name="PASSWD"]').val('');

   $('#customerpwd')
       .dialog('option', 'title', 'Reset password')
       .dialog('open');
}
function new_customer()
{
   var url = 'iform_exp.php?FUNCTION=8';
   $('#customerid').load(url, function() {
      $('#customerid').dialog('option', 'title', 'Add new customer').dialog('open');
   });
}
function askForCutomerFilter()
{
   $('#customerflt').dialog().dialog('open');
}
</script>

       <div id=customerflt title = "(Re)set customer filter">
          <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method =
               POST name= "goForm2">
          <input type=hidden name= "FUNCTION" value = "5">
          <input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
          <table><tr>
          <td> Customer Id</td><td>
          <input type=text name= "CUFILTER" value =
               "<?php echo myhtml((string)@$_SESSION['CUFILTER']); ?>" size =
                   50 maxlength = 32></td></tr><tr><td></td><td>
          <input type=submit value = "<?php echo $x2->xlabel(65 /* Update */ ); ?>">
          </td></tr></table></form>
       </div>

       <div id=customerpwd>
          <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method =
               POST name= "goForm2">
          <input type=hidden name= "FUNCTION" value = "8">
          <input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
          <table><tr>
          <td> Station Id</td><td><var> <?php echo $stationid;
            ?> </var></td></tr><tr><td> Customer Id</td><td>
            <input type=text name= "CUSTOMERID" size = 50 maxlength = 32></td>
            </tr><tr><td> Full name</td><td><var id="FULLNAME"></var></td>
            </tr><tr><td> Password</td><td>
            <input type=password name= "PASSWD"></td></tr><tr><td></td><td>
            <input type=submit value = "<?php echo $x2->xlabel(65 /* Update */ ); ?>">
            </td></tr></table></form>
      </div>

         <?php
             // make_customer_dialog();

   $pg   = getPage();
   $pgsz = getPageSize('grid2');
   $gr1  = new cXRID('grid2');

   $query = "SELECT CUSTOMERID, PASSWD5, FULLNAME, ADDRESS, ADDRESS2, ZIP, TOWN, PHONES, PREFLANGID
      FROM iform_customer
      WHERE STATIONID=? AND CUSTOMERID ".(empty($_SESSION['CUFILTER'])?" != '' ":" LIKE ? ").
      " ORDER BY CUSTOMERID ";
   $data = array($stationid);
   if (!empty($_SESSION['CUFILTER']))
   {
      $ar1 = explode('.', $_SESSION['CUFILTER']);
      if (count($ar1) == 2)
      {
         $cufilter = $ar1[1]."%";
      }
      else
      {
         $cufilter = "%".$_SESSION['CUFILTER']."%";
      }
      $data[] = $cufilter;
   }
   if (($rs = $db->PageExecute($query, $pgsz, $pg, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }

   $gr1->cols =
       array(array('Customer Id', 200), array('Fullname', 200),
             array('Address', 200), array('ZIP/Town', 100),
             array('Phones', 100), array('Password', 100), array('PLID', 80));

   while ($o1 = $rs->FetchNextObject())
   {
      $row1 = array();

      $row1[] = $stationid.'.'.myhtml($o1->CUSTOMERID);
      $row1[] = myhtml($o1->FULLNAME);

      $address = $o1->ADDRESS;
      if (!empty($o1->ADDRESS2))
      {
         $address.= ", ".$o1->ADDRESS2;
      }
      $row1[] = myhtml($address);

      $row1[] = myhtml($o1->ZIP." ".$o1->TOWN);
      $row1[] = myhtml($o1->PHONES);
      $row1[] = ($o1->PASSWD5 == null ?'': '******');

      $row1[] = is_null($o1->PREFLANGID) ? "NULL" : $o1->PREFLANGID;

      $gr1->rows[] = $row1;
   }
   $epage = $rs->LastPageNo();
   $rs->Close();

   $gr1->click = 'oclick';
   $gr1->play();

   echo "<div id=tbar2>";
   print_page_navEx($pg, $epage, 5);
   echo
       "<button type=button onclick=\"askForCutomerFilter()\" title=\"Filter\"><input type =
         checkbox ".(empty($_SESSION['CUFILTER'])?'':'checked')." disabled><img src=\"../img/filter.png\"></button>
         <button type=button onclick =\"new_customer()\">".$x2->xlabel(1 /* Add new */ )."</button>
         <button type=button onclick =\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
         </div> ";

   $selx = array(
      array(6, '../img/button_edit.png', $x2->xlabel(16 /* Edit data */ )),
      array(8, '../img/key16x16.png', 'Reset password'),
      array(7, '../img/delete.png', $x2->xlabel(12 /* Delete */ ))
      );
   draw_popup($selx);
}
//--------------------------------------
function make_customer_dialog()
{
   global $x2;
?>
<div id=customerid>
         <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method =
              POST name= "goForm1">
         <input type=hidden name= "FUNCTION" value = "6">
         <input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
         <table><tr>
         <td> Station Id</td><td><var> <?php
            echo $_SESSION['STATIONID'];
         ?> </var></td></tr><tr><td> Customer Id</td><td>
         <input type=text name= "CUSTOMERID" size = 50 maxlength = 32></td>
         </tr><tr><td> <?php
         $x2->xprint('Full name');
   ?> </td><td><input type=text name= "FULLNAME" size = 50 maxlength = 200>
         </td></tr><tr><td> <?php $x2->xprint('Address');
   ?> </td><td><input type=text name= "ADDRESS" size = 50 maxlength = 200>
         </td></tr><tr><td> <?php $x2->xprint('Address (more)');
   ?> </td><td><input type=text name= "ADDRESS2" size = 50 maxlength = 200>
         </td></tr><tr><td> <?php $x2->xprint('Zip code');
   ?> </td><td><input type=text name= "ZIP" size = 50 maxlength = 10></td>
         </tr><tr><td> <?php $x2->xprint('Town');
   ?> </td><td><input type=text name= "TOWN" size = 50 maxlength = 100>
         </td></tr><tr><td> <?php $x2->xprint('Country');
   ?> </td><td><input type=text name= "COUNTRY" size = 50 maxlength = 100>
         </td></tr><tr><td> <?php $x2->xprint('Phone(s)');
   ?> </td><td><input type=text name= "PHONES" size = 50 maxlength = 200>
         </td></tr><tr><td></td><td>
         <input type=submit value = "<?php $x2->xprint('Update'); ?>"></td>
         </tr></table></form></div> <?php
}
//--------------------------------------
function GetPrefViewId()
{
   global $x2;
   $db = &$x2->db;

   if (isset($_SESSION['PREFVIEWID']))
      return $_SESSION['PREFVIEWID'];

   $id=0;
   if ($x2->ulevel == 1)
   { // admin user
      $query = "SELECT PREFVIEWID FROM iform_users WHERE USERID=?";
      $data  = array($_SESSION['USERID']);
      if (($rs = $db->Execute($query, $data)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
      }
      else
      {
         if ($row = $rs->FetchRow())
         {
            $id=(int)$row[0];
         }
         $rs->Close();
      }
   }
   else if ($x2->ulevel == 2)
   { // customer
      $query = "SELECT PREFVIEWID FROM iform_users WHERE STATIONID=? AND PREFVIEWID IS NOT NULL
         ORDER BY PREFVIEWID";
      $data = array($_SESSION['STATIONID']);
      if (($rs = $db->Execute($query, $data)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
      }
      else
      {
         if ($row = $rs->FetchRow())
         {
            $id=(int)$row[0];
         }
         $rs->Close();
      }
   }

   $_SESSION['PREFVIEWID'] = $id;
   return $id;
}
//--------------------------------------
function append_views_by_right(&$views)
{
   global $x2;
   $db = &$x2->db;

   $query = 'SELECT T2.VIEWID, T2.PNAME, T2.PLABEL FROM iform_rights T1 '.
      ' LEFT JOIN iform_views T2 ON (T2.VIEWID=T1.RIKEY AND T2.FIELDSEQ = 0) '.
      ' WHERE T1.STATIONID=? AND T1.LOGINUSER=? AND T1.RITYPE=2';
   $data = array($_SESSION['STATIONID'], $_SESSION['USERID']);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ ); echo $db->ErrorMsg();
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      if (!array_key_exists($o1->VIEWID, $views)) {
         $views[$o1->VIEWID] = $o1;
      }
   }
   $rs->Close();
}
//--------------------------------------
function get_views_collection($vid=false)
{
   global $x2;
   $db    = &$x2->db;
   $views = array();

   if ($x2->ulevel == 99)
   {
      $query = 'SELECT VIEWID, PNAME, PLABEL FROM iform_views WHERE FIELDSEQ = 0 '.
         ' ORDER BY VIEWID ';
      $data = array($_SESSION['USERID']);
      if (($rs = $db->Execute($query)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
         return;
      }
      while ($o1 = $rs->FetchNextObject())
      {
         $views[$o1->VIEWID] = $o1;
      }
      $rs->Close();
   }
   else if ($x2->changepriv == 1)
   { // superuser: select by StationId
      $query = 'SELECT T1.VIEWID, T1.PNAME, T1.PLABEL FROM iform_views T1 '.
	     ' LEFT JOIN iform_users T2 ON (T2.USERID=T1.USERID) '.
	     ' WHERE T1.FIELDSEQ = 0 AND T2.STATIONID=? '.
	     ' GROUP BY T1.VIEWID, T1.PNAME, T1.PLABEL '.
	     ' ORDER BY T1.VIEWID';
      $data = array($_SESSION['STATIONID']);
      if (($rs = $db->Execute($query, $data)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
         return;
      }
      while ($o1 = $rs->FetchNextObject())
      {
         $views[$o1->VIEWID] = $o1;
      }
      $rs->Close();

      append_views_by_right($views);
   }
   else if ($x2->ulevel == 1)
   { // admin user: select by userid
      $query = 'SELECT DISTINCT T3.VIEWID, T3.PNAME, T3.PLABEL FROM iform_users T1 '.
         ' LEFT JOIN iform_users T2 ON (T2.STATIONID=T1.STATIONID) '.
         ' LEFT JOIN iform_views T3 ON (T3.USERID=T2.USERID AND T3.FIELDSEQ = 0) '.
         ' WHERE T1.USERID=? AND VIEWID IS NOT NULL '.
         ' ORDER BY T3.VIEWID';
      $data = array($_SESSION['USERID']);
      if (($rs = $db->Execute($query, $data)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
         return;
      }
      while ($o1 = $rs->FetchNextObject())
      {
         if ($vid === false || in_array($o1->VIEWID, $vid))
         {
            $views[$o1->VIEWID] = $o1;
         }
      }
      $rs->Close();

      append_views_by_right($views);
   }
   else if ($x2->ulevel == 2)
   { // customer: select by StationId, apply rights filter
      $query = 'SELECT T2.VIEWID, T2.PNAME, T2.PLABEL FROM iform_users T1 '.
         ' LEFT JOIN iform_views T2 ON (T2.USERID=T1.USERID AND T2.FIELDSEQ = 0) '.
         ' WHERE T1.STATIONID=? '.
         ' ORDER BY T2.VIEWID ';
      $data = array($_SESSION['STATIONID']);
      if (($rs = $db->Execute($query, $data)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
         return;
      }
      while ($o1 = $rs->FetchNextObject())
      {
         if ($vid === false || in_array($o1->VIEWID, $vid))
         {
            $views[$o1->VIEWID] = $o1;
         }
      }
      $rs->Close();
   }

   return $views;
}
//--------------------------------------
function get_preset_filters($viewid)
{
   global $x2;
   $db = &$x2->db;

   $query = "SELECT PNAME, PLABEL FROM iform_views WHERE VIEWID=$viewid AND
      QUERYPREF=1 ORDER BY FIELDSEQ";
   if (($filters = $db->cacheGetAssoc($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      $filters = array(); // reset to empty array
   }

   return $filters;
}
//--------------------------------------
function get_field_types()
{
   global $x2;
   $db = &$x2->db;

   $query = "SELECT PNAME, PTYPE FROM iform_protype WHERE STATIONID=?";
   $data  = array($_SESSION['STATIONID']);
   if (($ftypes = $db->cacheGetAssoc($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      $ftypes = array(); // reset to empty array
   }

   return $ftypes;
}
//--------------------------------------
function get_stationid()
{
   global $x2;
   $db = &$x2->db;

   $sids = array();
   $query = 'SELECT DISTINCT STATIONID FROM iform_users ORDER BY STATIONID';
   if (($rs=$db->cacheExecute($query))===false) {
      uerror( 'Database error, line '.__LINE__ );
      return $sids;
   }
   while ($o1=$rs->FetchNextObject()) {
      $sids[] = $o1->STATIONID;
   }
   $rs->Close();

   return $sids;
}
//--------------------------------------
function ResetLangId()
{
   global $x2;
   $db = &$x2->db;

   if ($x2->ulevel == 1)
   { // admin user
      $query = "UPDATE iform_users SET PREFLANGID=? WHERE USERID=?";
      $data  = array((int)$_REQUEST['NEWLANGID'], $_SESSION['USERID']);
      if (!$db->Execute($query, $data))
      {
         uerror( 'Database error, line '.__LINE__ );
      }
   }
   else if ($x2->ulevel == 2)
   { // customer (record may not exists)
      $query = "SELECT COUNT(*) FROM iform_customer WHERE STATIONID=? AND
         CUSTOMERID=?";
      $data = array($_SESSION['STATIONID'], $_SESSION['CUSTOMERID']);
      if (($rs = $db->Execute($query, $data)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
      }
      else
      {
         $row = $rs->FetchRow();
         $rs->Close();

         if ($row[0] > 0)
         {
            $query = "UPDATE iform_customer SET PREFLANGID=? WHERE STATIONID=? AND CUSTOMERID=?";
            $data = array((int)$_REQUEST['NEWLANGID'], $_SESSION['STATIONID'],
                          $_SESSION['CUSTOMERID']);
         }
         else
         {
            $query = "INSERT INTO iform_customer (STATIONID, CUSTOMERID, PREFLANGID) VALUES(?,?,?)";
            $data = array($_SESSION['STATIONID'], $_SESSION['CUSTOMERID'], (int)$_REQUEST['NEWLANGID']);
         }
         if (!$db->Execute($query, $data))
         {
            uerror( 'Database error, line '.__LINE__ );
         }
      }
   }
}
//--------------------------------------
function start_query()
{
   global $x2;
   $db = &$x2->db;

   SetHeadTitle(20 /* Find document */ );

   $prof = new cPROFILER1();

   $stationid = (int)$_SESSION['STATIONID']; // '(int)' is used for security
   $_SESSION['RSPAGE'] = 0; // clear for future references

   if (isset($_REQUEST['NEWLANGID']))
      ResetLangId();

   if (isset($_REQUEST['PREFVIEWID']))
   {
      $prefviewid = $_REQUEST['PREFVIEWID'];
      $_SESSION['PREFVIEWID'] = $_REQUEST['PREFVIEWID']; // save for session
   }
   else
   {
      $prefviewid=GetPrefViewId();
   }

   if (!defined('I_TEMPDIR')) {
      uerror('Temp.dir not defined!');
   }
   else if (!is_dir(I_TEMPDIR)) {
      uerror('Temp.dir does not exist!');
   }

   $rret = get_rights($src, $afm, $vid); // fill rights tables
   echo "<!-- ".__LINE__." Elapsed: ".sprintf("%.5lf", $prof->elapsed())." -->";
   $prof->reset();
   if (!$rret)
   {
      return;
   }
   else if (empty($src))
   {
      if ($x2->changepriv != 1 && $x2->ulevel != 2) {
         echo "<div class=umessage>No SRC set for user!</div>";
         return;
      }
   }

   if (empty($vid))
   {
      $vid[] = $prefviewid;
   }

   // Get SRC
   $srcName = get_src($stationid);
   echo "<!-- ".__LINE__." Elapsed: ".sprintf("%.5lf", $prof->elapsed())." -->";
   $prof->reset();

   // Extend src form rigths
   $src2=array();
   foreach ($src as $key) // for the rights read
   {
      if (array_key_exists($key, $srcName)) // src exists in name collection
      {
         $src2[$key] = $srcName[$key];
      }
      else {
         $src2[$key] = $key;
      }
   }

   // Get views
   $views = get_views_collection($vid);
   echo "<!-- ".__LINE__." Elapsed: ".sprintf("%.5lf", $prof->elapsed())." -->";
   $prof->reset();

   $preFilters = get_preset_filters($prefviewid);
   echo "<!-- ".__LINE__." Elapsed: ".sprintf("%.5lf", $prof->elapsed())." -->";
   $prof->reset();

   $fieldTypes = get_field_types();
   echo "<!-- ".__LINE__." Elapsed: ".sprintf("%.5lf", $prof->elapsed())." -->";
   $prof->reset();

   $viewTitle = $x2->xlabel(59 /* Standard */ ); // default
   $askForSigned = false; // default
   foreach ($views as $o1)
   {
      if ($prefviewid == $o1->VIEWID)
      {
         $viewTitle = $o1->PNAME;
         $askForSigned = (strlen($o1->PLABEL)>0 && $o1->PLABEL[0]==1);
         break;
      }
   }

   $inpdaysback  = 0;
   $tilltoday_en = false;
   $fts_en       = false;
   $query = "SELECT PNAME, PVALUE FROM reselprefex
      WHERE AGENTID=? AND RESELID=0 AND PGROUP='admin' AND PNAME IN('INPDAYSBACK', 'FTS_EN', 'TILLTODAY_EN') ";
   $data = array($x2->agentid);
   if (($rs = $db->Execute($query, $data)) !== false)
   {
      while ($o1 = $rs->FetchNextObject())
      {
         if ($o1->PNAME=== 'INPDAYSBACK')
         {
            $inpdaysback = (int)$o1->PVALUE;
         }
         else if ($o1->PNAME=== 'TILLTODAY_EN')
         {
            $tilltoday_en = (bool)$o1->PVALUE;
         }
         else if ($o1->PNAME=== 'FTS_EN')
         {
            $fts_en = (bool)$o1->PVALUE;
         }
      }
      $rs->Close();
   }
   $fromdate = $inpdaysback >= 0 ? date('d-m-Y', time() - $inpdaysback * 24 * 3600) : "";
   $tilldate = $tilltoday_en ? date('d-m-Y') : "";
?>
<script>
$(function(){
   window.name='iform_main';
   $('#addProperty').dialog({ autoOpen: false, modal: true, resizable: false, width: 340 });
});
function doAddPropery()
{
   var url = 'iform_exp.php?' + $('#addPropForm').serialize();
   $.post(url,
      function(data){
         if (data.length>0) {
            window.alert(data);
         }
      },
      'text'
   );
}
</script>
<div id=addProperty title="Add property">
   <form id=addPropForm>
   <input type=hidden name="FUNCTION" value="28">
   <table>
      <tr>
         <td>Station Id</td>
         <td><?php
            $sids = get_stationid();
            echo '<select name="add_stationid">';
            foreach ($sids as $sti) {
               echo "<option>$sti</option>";
            }
            echo '</select>';
         ?></td>
      </tr>
      <tr>
         <td>Sequence no</td>
         <td><input type=number name="add_seqno"></td>
      </tr>
      <tr>
         <td>Property name</td>
         <td><input type=text name="add_pname" style="width:200px"></td>
      </tr>
      <tr>
         <td>Property value</td>
         <td><input type=text name="add_pvalue" style="width:200px"></td>
      </tr>
      <tr>
         <td></td>
         <td><input type=button value="Update" onclick="doAddPropery()"></td>
      </tr>
   </table>
   </form>
</div>
<?php
   echo "<form action=\"".myhtml($_SERVER['SCRIPT_NAME'])."\" name=\"goForm\" method=POST>
      <input type=hidden name=\"FUNCTION\" value=\"4\">
      <input type=hidden name=\"CSRFToken\" value=\"".$_SESSION['CSRFToken']."\">
      <input type=hidden name=\"VIEWID\" value=\"$prefviewid\">
      <table>
         <colgroup>
            <col class =\"column1\">
            <col class =\"column2\">
            <col class =\"column3\">
            <col class =\"column4\">
            <col class =\"column5\">
            <col class =\"column6\">
         </colgroup>
         <thead>
             <tr class=bgHeader>
             <td></td>
             <td></td>
             <td colspan=4 class=headPadding>
               <img src=\"../img/button_browse.png\">\n<span class=headTitle>".myhtml($viewTitle)."</span>
               <select id=prefviewid>
                  <option value=\"-1\" selected>".$x2->xlabel(47 /* Reset view */ )."</option>
                  <option value=\"0\">".$x2->xlabel(59 /* Standard */ )."</option>";
   foreach ($views as $o1)
   {
      echo "<option value=\"$o1->VIEWID\">".myhtml($o1->PNAME)."</option>";
   }
   echo "</select></td>
       </tr>
       <tr>
          <td colspan = 2></td>
          <td colspan = 2 class=gray> ".$x2->xlabel(22 /* From */ )." </td>
          <td colspan = 2 class=gray> ".$x2->xlabel(63 /* To */ )." </td>
       </tr>
       <tr>
         <td></td>
         <td>".$x2->xlabel(56 /* Source */ )." </td>
         <td></td>
         <td>
         <select name=\"SOURCE\">";
   prAssocSelect($src2);
   echo "</select></td>
      <td></td>
	   <td>";
   if (!empty($_SESSION['HR_STOREID'])) {
       echo 'HR Store ID: '.$_SESSION['HR_STOREID'];
   }
   echo "</td>
       </tr>";
   if ($askForSigned) {
      echo '<tr>
         <td></td>
         <td>'.$x2->xlabel(108 /* Signed */ ).'</td>
         <td></td>
         <td><select name="SIGNED">
            <option value="1">YES</option>
            <option value="2">No</option>
            <option value="0">All</option>
            </select></td>
         </tr>';
   }
   echo "<tr>
       <td></td>
       <td> ".$x2->xlabel(13 /* Document date */ )." </td>
       <td><button type=button class=clearButton> C</button></td>
       <td><input type=text name=\"FROMDATE\" value=\"$fromdate\" class=userdate><button id=dayF
         type=button class=daybutton>...</button></td>
      <td><button type=button class=deseqButton> &lt;&gt;</button></td>
      <td><input type=text name=\"TILLDATE\" value=\"$tilldate\" class=userdate><button id=dayT
         type=button class=daybutton>...</button></td>
      </tr> ";

       if ($fts_en){
         echo "<tr>
               <td> </td>
               <td> ".$x2->xlabel(6 /* Any word */ )." </td>
               <td> </td>
               <td><input type=text name=\"ANYWORD\"></td>
               <td colspan = 2></td>
               </tr> ";
       }

   //
   // Preset filters
   //
   $j = 0;
   foreach ($preFilters as $pf1 => $label)
   {
      if (empty($label))
      {
         $label = $pf1;
      }

      $moreParams = "";
      $readonly   = false;
      if (array_key_exists($pf1, $fieldTypes))
      {
         if ($fieldTypes[$pf1] == 3 || $fieldTypes[$pf1] == 6)
         {
            $moreParams = "class=userdate";
         }
         else if ($fieldTypes[$pf1] == 4 && !empty($_SESSION['LOGINSHOP']) && $_SESSION['LOGINSHOP']!=='ALL')
         {
            $readonly = true;
         }
      }

      echo "<tr>
          <td> </td>
          <td title =\"$pf1\">".myhtml($label)
                         ."<input type=hidden name=\"PROP[]\" value=\""
                         .myhtml(trim($pf1))
                         ."\"></td>
                     <td></td> ";
      if ($readonly)
      {
         echo "<td><input type=text name=\"FROM[]\" value=\""
             .myhtml($_SESSION['LOGINSHOP'])
             ."\" readonly><button
             disabled type=button id=b".($j++)." class=fibutton> ...</button></td><td></td><td>
                 <input type =
                      text name=\"TILL[]\" readonly><button type=button
                  disabled id=b".($j++)." class=fibutton>...</button></td> ";
      }
      else
      {
         echo "<td><input type=text name=\"FROM[]\" $moreParams><button
            type=button id=b".($j++)." class=fibutton>...</button></td>
            <td> <button type=button class=deseqButton> &lt;&gt;
            </button></td><td> <input type=text name=\"TILL[]\" $moreParams><button
            type=button id=b".($j++)." class=fibutton>...</button></td>";
      }

      echo "</tr>";
   }

   echo "</thead>";

   //
   // Rest of filters
   //
   echo "<tbody class=gray>
       <tr> <td class=opnclose>[+]</td><th> ".$x2->xlabel(44 /* Properties */ )." </th> <th colspan = 2> ".$x2->xlabel(22 /* From */ )." </th>
       <th colspan = 2> ".$x2->xlabel(63 /* To */ )." </th> </tr></tbody></table>
       <div id =
       restFilters style =\"width:720px; xmax-height:400px; overflow-y:auto;
                          border-top : 1px solid gray;
   border-left : 1px solid gray;
   border-right : 1px solid gray;
   border-bottom : 3px solid gray;\">
       <table> <colgroup><col class =\"column1\">
                           <col class=\"column2\">
                           <col class=\"column3\">
                           <col class=\"column4\">
                           <col class=\"column5\">
                           <col class=\"column6\">
               </colgroup>
                 <tbody id=props class=gray style =\"display:none;\">
                                                       <tr><td></td>
                 <td> Sequence no.</td><td></td><td>
                 <input type=text name=\"FROMSEQNO\"></td>
                                          <td>
                 <button type=button class=deseqButton> &lt;&gt;
   </button></td><td><input type=text name=\"TILLSEQNO\"></td>
                                                </tr> ";

   $query = "SELECT PNAME FROM iform_pname WHERE STATIONID=$stationid ORDER BY PNAME";
   $data = false;
   if (($rs = $db->cacheExecute($query, $data)) === false)
   {
      echo "<tr><td colspan=6>";
      uerror( 'Database error, line '.__LINE__ );
      echo "</td></tr> ";
   }
   else
   {
      while ($row = $rs->FetchRow())
      {
         $pf1 = $row[0];
         if (!array_key_exists($pf1, $preFilters))
         {

            $moreParams = "";
            $readonly   = false;
            if (array_key_exists($pf1, $fieldTypes))
            {
               if ($fieldTypes[$pf1] == 3 || $fieldTypes[$pf1] == 6)
               {
                  $moreParams = "class=userdate";
               }
               else if ($fieldTypes[$pf1] == 4 &&
                        !empty($_SESSION['LOGINSHOP']))
               {
                  $readonly = true;
               }
            }

            if ($readonly)
            {
               echo "<tr>
                   <td> </td><td> ".myhtml($row[0])." <input type=hidden
                   name=\"PROP[]\" value=\"".myhtml(trim($row[0]))."\"></td>
                             <td> </td><td>
                             <input type=text
                                  name=\"FROM[]\" value=\""
                                            .myhtml($_SESSION['LOGINSHOP'])
                                            ."\" readonly><button type=button id=b".($j++)
                                            ." class=fibutton disabled>...</button></td>
                                        <td>
                             <button type=button class=deseqButton> &lt;&gt; </button></td><td>
                   <input type=text name   =\"TILL[]\" readonly><button type=button id=b"
                                  .($j++)." class=fibutton disabled>...</button></td>
                              </tr> ";
            }
            else
            {
               echo "<tr>
                   <td> </td><td> ".myhtml($row[0])." <input type=hidden
                   name=\"PROP[]\" value=\"".myhtml(trim($row[0]))."\"></td>
                             <td> </td><td>
                             <input type=text
                                  name   =\"FROM[]\" $moreParams><button type=button id=b".($j++)
                                             ." class=fibutton>...</button></td>
                                        <td>
                             <button type=button class=deseqButton> &lt;&gt;
               </button></td><td>
                   <input type=text
                        name   =\"TILL[]\" $moreParams><button type=button id=b"
                                  .($j++)." class=fibutton>...</button></td>
                              </tr> ";
            }
         }
      }
      $rs->Close();
   }
   echo "<!-- ".__LINE__." Elapsed: ".sprintf("%.5lf", $prof->elapsed())." -->";
   $prof->reset();

   echo "<tr>
       <td> </td><td> ".$x2->xlabel(19 /* Filter relation */ )." </td> <td></td>
       <td><label>
       <input type=radio name=\"COMBINE\" value=\"1\" checked> AND</label>
                                 <label>
       <input type=radio name=\"COMBINE\" value=\"0\"> OR</label>
                                 </td><td colspan = 2></td></tr></tbody>
       </table></div> ";

   // footer
   echo "<table>
       <colgroup >
         <col class =\"column1\">
         <col class=\"column2\">
         <col class=\"column3\">
         <col class=\"column456\">
      </colgroup>
      <tfoot>
         <tr class=navBar>
            <td></td>
            <td>";
   if ($x2->ulevel==99) {
      echo "<input type=button value=\"Add property\" onclick=\"$('#addProperty').dialog('open');\">";
   }
   echo "</td>
            <td></td>
            <td>
               <input type=button value =\"".$x2->xlabel(45 /* Query */ )."\" onclick=\"GoSubmit()\">
               <label><input type=checkbox id = newwin checked> ".$x2->xlabel(52 /* Separate window */ )." </label >
            </td>
         </tr>
      </tfoot>
      </table>
      </form> ";

       ?> <div id=querydiv></div><script> var ofield = null;
   var pg;
   var pname;
   $('.userdate').attr('autocomplete', 'off').datepicker();
   $('#restFilters').resizable({handles : "s", ghost : true});
   $(function() {
      $('#prefviewid').change(function() {
         followMe( {FUNCTION:3, PREFVIEWID:$(this).val() } );
      });

      $('#querydiv').dialog({autoOpen : false, modal : true, width : 620, resizable : true});
   });
   $('.fibutton').click(function() {
      var x = parseInt(this.id.substr(1));

      if ((x % 2) == 0)
         ofield = document.goForm['FROM[]'][x / 2];
      else
         ofield = document.goForm['TILL[]'][Math.floor(x / 2)];

      pname= document.goForm['PROP[]'][Math.floor(x / 2)].value;
      $('#querydiv').text('');
      $('#querydiv')
          .load('iform_exp.php?FUNCTION=6&PNAME=' + encodeURIComponent(pname));
      $('#querydiv').dialog('option', 'title', pname).dialog('open');
   });
   $('.clearButton').attr('title', 'Clear field').click(function() {
      var td1 = this.parentNode;
      $(td1).next().children().val('');
   });
   $('.daybutton').click(function() {
      var title;
      if (this.id === 'dayF')
      {
         ofield = document.goForm.FROMDATE;
         title  = 'Date selection (FROM)';
      }
      else
      {
         ofield = document.goForm.TILLDATE;
         title  = 'Date selection (TO)';
      }
      $('#querydiv').text('');
      $('#querydiv').load('iform_exp.php?FUNCTION=11');
      $('#querydiv').dialog('option', 'title', title).dialog('open');
   });
   $('.deseqButton')
       .attr('title', 'Copy left to right OR clear right')
       .click(function() {
          var td1  = this.parentNode;
          var src  = $(td1).prev().children().val();
          var dest = $(td1).next().children().val();
          if (dest.length == 0)
          {
             $(td1).next().children().val(src);
          }
          else
          {
             $(td1).next().children().val('');
          }
       });

   function Reload(pg2)
   {
      $('#querydiv')
          .load('iform_data.php?FUNCTION=6&PG=' + pg2 + '&PNAME=' +
                encodeURIComponent(pname));
   }

   function GoSubmit()
   {
		event.preventDefault();
		var oform = $('form[name=goForm]');
      if ($('#newwin').is(':checked'))
      {
         oform.attr('target', 'query_ret');
         oform.css('target-new', 'tab');
      }
      oform.submit();
      oform.attr('target', ''); // reset (if modified)
      oform.css('target-new', 'tab');
   }

   function CheckForTill(o1)
   {
      if (o1.checked)
      {
         if ($('input[name=TILLDATE]').val() ==='')
         {
            $('input[name=TILLDATE]').val($('input[name=FROMDATE]').val());
         }
      }
   }
   </script>
<?php
}
//--------------------------------------
function clear_cache()
{
   global $ADODB_CACHE_DIR;

   if (empty($ADODB_CACHE_DIR))
   {
      echo "No Cache folder is set!";
      return;
   }

   $directories = glob($ADODB_CACHE_DIR.'/*', GLOB_ONLYDIR);
   foreach ($directories as $dir1)
   {
      $files = glob($dir1.'/*');
      foreach ($files as $f1)
      {
         unlink($f1);
      }
   }
   echo "Process completed!";

   cache_info();
}
//--------------------------------------
function del_waiting_queries()
{
   global $x2;
   $db        = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   $qdir = GetUqueriesDir();
   if (empty($qdir)) {
      uerror("UqueriesDir not set");
      return;
   }

   $db->StartTrans();

   do {
      $query = "DELETE FROM iform_usrquery WHERE RID=? AND STATIONID=? AND USERID=?"; // RID is enough, use the rest for security
      $data = array((int)$_REQUEST['RECORDID'], $stationid, $_SESSION['USERID'] );
      if (!$db->Execute($query, $data)) {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }

      // Collect 'orphan' records, if any
      // Orphans are records in iform_uxquery not referenced anywhere in iform_usrquery
      $orphan=array();
      $query = "SELECT T1.RXID FROM iform_uxquery T1 LEFT JOIN iform_usrquery T2 ON (T2.RXID=T1.RXID) WHERE T2.RID IS NULL";
      if (($rs=$db->Execute($query))===false) {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }
      while ($o1=$rs->FetchNextObject()) {
         $orphan[] = $o1->RXID;
      }
      $rs->Close();

      // Delete orphans
      if (!empty($orphan)) {
         $query = "DELETE FROM iform_uxquery WHERE RXID IN (".implode(',', $orphan).")";
         if (!$db->Execute($query)) {
            uerror( 'Database error, line '.__LINE__ );
            break;
         }
      }
   } while (false);

   $db->CompleteTrans();

   $resultFile = $qdir.DIRECTORY_SEPARATOR.$_REQUEST['RECORDID'].'.csv';
   @unlink($resultFile);
}
//--------------------------------------
function show_waiting_queries()
{
   global $x2;
   $db        = &$x2->db;
   $stationid = (int)$_SESSION['STATIONID'];

   SetHeadTitle(94);
?>
<script>
$(function(){
   $('#reportEmail').dialog({autoOpen : false, modal : true, resizable : false, width:450});
} );

var urid=0;
function oclick(stage, row, col)
{
   urid=this.cells(row, 0).getValue();
   show_popup('popmenu');
   return false;
}
function winRet(x)
{
   switch (x)
   {
   case 26: // reset email
      $('#RID').text(urid);
      $('#URID').val(urid);
      $('#reportEmail').dialog('open');
      break;
   case 25: // get results
      var url = 'iform_exp.php?FUNCTION=25&URID=' + encodeURIComponent(urid);
      PrepareForDownload();
      document.getElementById('downl').src=url;
      break;
   case 71:
      goRecDelete(71, urid);
      break;
   }
   hide_popup();
}
</script>
<div id=reportEmail title="Email for report">
   Please enter you email to be notified when report Id <b id=RID></b> is ready.
   <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method=POST name="goForm">
      <input type=hidden name="FUNCTION" value = "73">
      <input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
      <input type=hidden id="URID" name="RID">
      <table>
      <tr>
         <td>
            <input type=text name="EMAILTO" maxlength=250 style="width:400px">
         </td>
      </tr>
      <tr>
         <td>
            <input type=submit id="updButton" value="<?php echo $x2->xlabel(65); ?>">
            <input type=button value="<?php echo $x2->xlabel(7); ?>" onclick="$('#reportEmail').dialog('close');">
         </td>
      </tr>
      </table>
   </form>
</div>
<?php
   $gr1 = new cXRID('grid24');
   $gr1->cols = array(
      array('Report Id', 80),
      array('Created', 120),
      array('Query', 200),
      array('Ready', 60),
      array('Email to', 120),
      array('Start', 120),
      array('End', 120),
      array('Result', 120)
      );

   $query = "SELECT T1.RID, ".FulldateFld('T2.CREDAYTIME')." AS CREDAYTIME, T2.QRYTITLE, T2.QREADY, T1.EMAILTO, ".
      FulldateFld('T2.STARTRUN')." AS STARTRUN, ".FulldateFld('T2.ENDRUN')." AS ENDRUN, T2.QRESULT FROM iform_usrquery T1
      LEFT JOIN iform_uxquery T2 ON (T2.RXID=T1.RXID)
      WHERE T1.STATIONID=$stationid AND T1.USERID=? ORDER BY T1.RID";
   $data = array($_SESSION['USERID']);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1 = $rs->FetchNextObject())
   {
      $row1 = array($o1->RID, $o1->CREDAYTIME, myhtml($o1->QRYTITLE) );
      $row1[] = $o1->QREADY ? 'YES' : 'No';
      array_push($row1, myhtml($o1->EMAILTO), $o1->STARTRUN, $o1->ENDRUN, myhtml($o1->QRESULT) );

      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->click = 'oclick';
   $gr1->play();

   echo "<div id=tbar2><small>End of data</small></div>";

   $selx = array(
      array(26, '../img//email.gif', '(Re)set email'),
      array(25, '../img/download.png', 'Get results'),
      array(71, '../img/delete.png', $x2->xlabel(12 /* Delete */ ))
      );
   draw_popup($selx);
}
//--------------------------------------
function docdate_progress()
{
   global $x2;
   $db        = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   SetHeadTitle('Daily insertions');
?>
<script>
$(function(){
   $('#querydiv').dialog({autoOpen : false, modal : true, width : 620, resizable : true});
} );
var credate;
function oclick(stage, row, col)
{
   credate = this.cells(row, 0).getValue(); // yyyy-mm-dd
   show_popup('popmenu');
   return false;
}
function winRet(x)
{
   switch (x)
   {
   case 1:
      var url='iform_exp.php?FUNCTION=24&CREDATE=' + encodeURIComponent(credate);
      $('#querydiv').html('Loading...');
      $('#querydiv').dialog('open').load(url).
      break;
   }
   hide_popup();
}
</script>
<div id="querydiv" title="Sources"></div>
<?php
   class cDATA2
   {
      var $all    = 0;
      var $remain = 0;

      function __construct($x) { $this->all = $x; }
   }

   $data2 = array();

   $db->SetFetchMode(ADODB_FETCH_NUM); // NUM, ASSOC, BOTH

   // All
   $query = "SELECT CONVERT(NVARCHAR(10), CREDAYTIME, 120), COUNT(*) FROM iform_main
      WHERE STATIONID=$stationid
      GROUP BY CONVERT(NVARCHAR(10), CREDAYTIME, 120)
      ORDER BY CONVERT(NVARCHAR(10), CREDAYTIME, 120) DESC ";
   if (($rs = $db->cacheExecute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($row = $rs->FetchRow())
   {
      $data2[$row[0]] = new cDATA2($row[1]);
   }
   $rs->Close();

   // Remaining
   $query = "SELECT CONVERT(NVARCHAR(10), CREDAYTIME, 120), COUNT(*) FROM iform_main
      WHERE STATIONID=$stationid AND DOCDATE IS NULL GROUP BY CONVERT(NVARCHAR(10), CREDAYTIME, 120)";
   if (($rs = $db->cacheExecute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($row = $rs->FetchRow())
   {
      $data2[$row[0]]->remain = $row[1];
   }
   $rs->Close();

   $gr1 = new cXRID('grid10');

   $gr1->cols = array(
      array('Date', 150),
      array('All', 100),
      array('Remain', 100));

   foreach ($data2 as $key => $val)
   {
      $row1        = array($key, $val->all, $val->remain);
      $gr1->rows[] = $row1;
   }

   $gr1->click = 'oclick';
   $gr1->play();

   echo "<div id=tbar2><small>End of data</small></div>";

   $selx = array(
      array(1, '../img/details.gif', 'Sources')
      );
   draw_popup($selx);
}
//--------------------------------------
function show_folders($xdir = false)
{
   try
   {
      if ($xdir === false)
      {
         $xdir = 'E:\\data\\incoming';
      }

      $d1 = new DirectoryIterator($xdir);
      $nf = 0;
      $nd = 0;
      foreach ($d1 as $fi)
      {
         if ($fi->isDot())
         {
            continue;
         }
         else if ($fi->isDir())
         {
            show_folders($fi->getPathname());
            $nd++;
         }
         else
         {
            $nf++;
         }
      }
      echo "$xdir --- Files: $nf Dirs: $nd<br>";
   }
   catch (Exception $e1)
   {
      echo $e1->getMessage();
      return;
   }
}
//--------------------------------------
function sql_log_del()
{
   global $x2;
   $db = &$x2->db;

   $db->logSql(false); // disable

   $query = "DELETE FROM adodb_logsql WHERE created <= ?";
   $data=array($_REQUEST['DELDATE'].' 23:59:59');
   $db->Execute($query, $data);

   if ($x2->logsql) {
      $db->logSql(true); // re-enable
   }
}
//--------------------------------------
function sql_log_info()
{
   global $x2;
   $db = &$x2->db;

   SetHeadTitle("SQL log information");
?>
<div id="sql_log_info" title="SQL record zoom">
   <table>
      <tr>
         <td>Sql</td>
         <td id=sql_field></td>
      </tr>
      <tr class=hiLine>
         <td>Parameters</td>
         <td id=param_field></td>
      </tr>
      <tr>
         <td>Trace</td>
         <td id=trace_field></td>
      </tr>
      <tr class=hiLine>
         <td>Time</td>
         <td id=time_field></td>
      </tr>
   </table>
</div>
<script>
$(function(){
   $('#sql_log_info').dialog({autoOpen: false, modal: true, resizable: true, width: 620});
});
function DeleteSqlLog()
{
   followMe( { FUNCTION:68, DELDATE:$('#deldate').val() } );
}
function oclick(stage, row, col)
{
   $('#sql_field').text( this.cells(row, 2).getValue() );
   $('#param_field').text( this.cells(row, 3).getValue() );
   $('#trace_field').html( this.cells(row, 4).getValue() );
   $('#time_field').text( this.cells(row, 5).getValue() );
   $('#sql_log_info').dialog().dialog('open');
}
</script>
<?php
   $pg   = getPage();
   $pgsz = getPageSize('grid23');
   $gr1  = new cXRID('grid23');

   $db->logSql(false);

   $query="SELECT * FROM adodb_logsql order by created DESC";
   $db->SetFetchMode(ADODB_FETCH_NUM); // NUM, ASSOC, BOTH
   if (($rs = $db->PageExecute($query, $pgsz, $pg)) === false)
   {
      echo "SQL error on line ".__LINE__;
      if ($x2->logsql) {
         $db->logSql(true); // reset
      }
      return;
   }
   while ($row=$rs->FetchRow())
   {
      if (empty($gr1->cols))
      {
		   $n = $rs->fieldCount();
		   for ($i=0;$i<$n;$i++)
         {
			   $field = $rs->fetchField($i);
            $gr1->cols[] = array($field->name, 150);
         }
      }
      $gr1->rows[] = $row;
   }
   $epage = $rs->LastPageNo();
   $rs->Close();
   if ($x2->logsql) {
      $db->logSql(true); // reset
   }

   if (empty($gr1->rows)) {
      echo "No data available!";
   }
   else {
      $gr1->click='oclick';
      $gr1->play();
   }
   // function 67
   echo "<div id=tbar2>";
   print_page_navEx($pg, $epage, 67);
   echo "Delete up to <input type=text id=deldate placeholder=\"YYYY-MM-DD\"><button
         type=button onclick=\"DeleteSqlLog()\">DEL</button>
      <small>End of data</small>
      </div>";
}
//--------------------------------------
function imports_analysis()
{
   global $x2;
   $db = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   SetHeadTitle("Imports analysis");
?>
<script src="iform.js.php?FUNC=process_query"></script>
<script>
var cid, srcid;
function oclick(stage, row, col)
{
   cid=this.cells(row, 0).getValue(); // dd/mm/yyyy
   srcid=this.cells(row, 1).getValue();
   show_popup('popmenu');
   return false;
}
function winRet(x)
{
   switch (x)
   {
   case 22: // get records
      var url = 'iform_exp.php?FUNCTION=22&GDATE=' + encodeURIComponent(cid) + '&SRC=' + encodeURIComponent(srcid);
      PrepareForDownload();
      document.getElementById('downl').src=url;
      break;
   }
   hide_popup();
}
</script>
<?php
   $gr1  = new cXRID('grid22');

   $gr1->cols = array(
      array('Date', 200),
      array('Source', 200),
      array('Count', 100)
      );

   $ar1 = array_reverse(explode('/', $_REQUEST['RECORDID'])); // DD/MM/YYYY
   $val = implode('-', $ar1);
   $query="SELECT SRC, COUNT(*) N1 FROM iform_main ";
   if ($x2->dbt == DBType::MySql) {
      $query .= " USE INDEX (k2) ";
   }
   $query .= " WHERE STATIONID=$stationid AND ".DateFld('CREDAYTIME')."=?
      GROUP BY SRC
      ORDER BY SRC";
   $data=array($val);
   if (($rs = $db->cacheExecute($query, $data)) === false)
   {
      echo "SQL error on line ".__LINE__;
      return;
   }
   while ($o1=$rs->FetchNextObject())
   {
      $row1 = array(
         myhtml($_REQUEST['RECORDID']),
         (empty($o1->SRC) ? '(Empty)' : myhtml($o1->SRC)),
         $o1->N1
      );

      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->click='oclick';
   $gr1->play();
   echo "<div id=tbar2><small>End of data</small>
      <b><a href=\"javascript:goTo(65)\">Import dates</a></b></div>";

   $selx = array(
      array(22, '../img/download.png', 'Get records')
      );
   draw_popup($selx);
}
//--------------------------------------
function PrepareCredateTable()
{
   global $x2;
   $db = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   $db->StartTrans();

   do {
      // Find max_CREDATE
      $query = "SELECT CONVERT(NVARCHAR(10), MAX(CREDATE), 120) FROM iform_credate WHERE STATIONID=$stationid";
      if (($rs=$db->Execute($query))===false) {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }
      $row=$rs->FetchRow();
      $rs->Close();
      $maxcredate = $row[0];
      if (!empty($maxcredate)) {
         // Delete max_CREDATE
         $query = "DELETE FROM iform_credate WHERE STATIONID=$stationid AND CREDATE='$maxcredate' ";
         if (!$db->Execute($query)) {
            uerror( 'Database error, line '.__LINE__ );
            break;
         }
      }

      // Select anything >= max_CREDATE and re-insert
      $query = "INSERT INTO iform_credate (STATIONID, CREDATE, SRC, RCOUNT)
         (SELECT STATIONID,  CONVERT(NVARCHAR(10), CREDAYTIME, 120), COALESCE(SRC, ''), COUNT(*) FROM iform_main
         WHERE STATIONID=$stationid ";
      if (!empty($maxcredate)) {
         $query .= " AND CONVERT(NVARCHAR(10), CREDAYTIME, 120) >= '$maxcredate' ";
      }
      $query .= " GROUP BY STATIONID,  CONVERT(NVARCHAR(10), CREDAYTIME, 120), COALESCE(SRC, '') )";
      if (!$db->Execute($query)) {
         uerror( 'Database error, line '.__LINE__ );   echo $query;
         break;
      }
   } while (false);

   $db->CompleteTrans();
}
//--------------------------------------
function imports_info()
{
   global $x2;
   $db = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   SetHeadTitle("Imports information");
?>
<div id=querydiv title="Imports analysis">
</div>
<script src="iform.js.php?FUNC=process_query"></script>
<script>
var sdate;
var ofield = new Object();
$(function(){
   $('#querydiv').dialog({autoOpen : false, modal : true, resizable : true, width:480, close:function(evt,ui){
      if (ofield.value) {
         var url = 'iform_exp.php?FUNCTION=22&GDATE=' + encodeURIComponent(sdate) + '&SRC=' + encodeURIComponent(ofield.value);
         PrepareForDownload();
         document.getElementById('downl').src=url;
      }
   } });
} );
function oclick(stage, row, col)
{
   sdate = this.cells(row, 0).getValue();
   show_popup('popmenu');
   return false;
}
function winRet(x)
{
   switch (x)
   {
   case 23:
      var url = 'iform_exp.php?FUNCTION=23&SDATE=' + encodeURIComponent(sdate);
      if (ofield.value) { delete ofield.value; }
      $('#querydiv').html('Loading...').dialog('open');
      $('#querydiv').load(url);
      break;
   }
   hide_popup();
}
</script>
<?php
   PrepareCredateTable();

   $pg   = getPage();
   $pgsz = getPageSize('grid21');
   $gr1  = new cXRID('grid21');

   $gr1->cols = array(
      array('Date', 200),
      array('Total count', 100)
      );

   $query = "SELECT ".DateFld('CREDATE')." AS CDAY, SUM(RCOUNT) AS N1 FROM iform_credate WHERE STATIONID=$stationid
      GROUP BY ".DateFld('CREDATE')." ORDER BY ".DateFld('CREDATE')." DESC";
   if (($rs = $db->cachePageExecute(3600, $query, $pgsz, $pg)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1 = $rs->FetchNextObject())
   {
      $row1=array(
         GrDate($o1->CDAY),
         $o1->N1
      );

      $gr1->rows[] = $row1;
   }
   $epage = $rs->LastPageNo();
   $rs->Close();

   $gr1->click = 'oclick';
   $gr1->play();

   echo "<div id=tbar2>";
   print_page_navEx($pg, $epage, 65);
   echo "<button type=button onclick=\"goTo(70)\">".$x2->xlabel(97)."</button></div>";

   $selx = array(
      array(23, '../img/details.gif', 'Analysis'),
      );
   draw_popup($selx);
}
//--------------------------------------
function cache_info()
{
   global $x2, $ADODB_CACHE_DIR;

   SetHeadTitle('Cache');

   if (empty($ADODB_CACHE_DIR))
   {
      echo "No Cache folder is set!";
      return;
   }

   $gr1 = new cXRID('grid8');

   $gr1->cols = array(
      array('File', 400),
      array('Size (bytes)', 100),
      array('Creation time', 120),
      array('Last access', 120)
      );

   $directories = glob($ADODB_CACHE_DIR.'/*', GLOB_ONLYDIR);
   foreach ($directories as $dir1)
   {
      $files = glob($dir1.'/*');
      foreach ($files as $f1)
      {
         $ar1  = stat($f1);
         $atimeStr = $ar1['atime'] > $ar1['ctime'] ? date('Y-m-d H:i:s', $ar1['atime']) : '';
         $row1 = array($f1, $ar1['size'], date('Y-m-d H:i:s', $ar1['ctime']),
                       $atimeStr);
         $gr1->rows[] = $row1;
      }
   }
   $gr1->play();

   echo "<div id=tbar2>
      <input type=button onclick=\"goTo(36)\" value=\"Cleanup all\">
      </div>";
}
//--------------------------------------
function ask_for_some_fields()
{
   global $x2;

   SetHeadTitle('Check/reset PNAME/PVALUE');
?>
<form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method = POST name= "goForm">
<input type=hidden name="FUNCTION" value = "83">
<input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
<table>
<tr>
   <td>For User</td>
   <td><input type=text name="FORUSER"></td>
</tr>
<tr>
   <td>Check</td>
   <td><select name="FORFIELD">
      <option value="0">DOCDATE</option>
      <option value="1">DAILY4</option>
      <option value="2">PROGRESSIVE8</option>
      <option value="3">S11</option>
      <option value="4">ZNR</option>
      </select></td>
</tr>
<tr>
   <td></td>
   <td><input type=submit></td>
</tr>
</table>
</form>
<?php
}
//--------------------------------------
function reset_some_fields()
{
   global $x2;
   $db = &$x2->db;

   SetHeadTitle('Check/reset PNAME/PVALUE (action)');

   $query = 'SELECT STATIONID FROM iform_users WHERE USERID=?';
   $data = array($_REQUEST['FORUSER']);
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' DB error '.$db->ErrorMsg();
      return;
   }
   $om = $rs->FetchNextObject();
   $rs->Close();
   if ($om===false) {
      echo "<div class=umessage>User not found!</div>";
      return;
   }

   switch ($_REQUEST['FORFIELD'])
   {
   case 0:
      reset_docdate($om->STATIONID);
      break;
   case 1:
      reset_del_field($om->STATIONID, 'DAILY4', 'A/A Ημερήσιων Σημάνσεων', true);
      break;
   case 2:
      reset_del_field($om->STATIONID, 'PROGRESSIVE8', 'A/A Προοδευτικών Σημάνσεων', true);
      break;
   case 3:
      reset_del_field($om->STATIONID, 'S11', 'S/N  ΕΑΦΔΣΣ', false);
      break;
   case 4:
      reset_del_field($om->STATIONID, 'ZNR', 'Αριθμός Ζ', true);
      break;
   }

   echo '<p><a href="javascript:goTo(82)">Repeat</a></p>';
}
//--------------------------------------
function reset_del_field($forstationid, $fordel, $keep, $isInt)
{
   global $x2;
   $db = &$x2->db;

   $records=array();

   $query = "SELECT T1.STATIONID, T1.SEQNO, T1.DOCDATE, T2.PVALUE FORDEL, T3.PVALUE FORKEEP FROM iform_main T1
      LEFT JOIN iform_prop T2 ON (T2.STATIONID=T1.STATIONID AND T2.SEQNO=T1.SEQNO AND T2.PNAME=?)
      LEFT JOIN iform_prop T3 ON (T3.STATIONID=T1.STATIONID AND T3.SEQNO=T1.SEQNO AND T3.PNAME=?)
      WHERE T1.STATIONID=?
      ORDER BY T1.STATIONID, T1.SEQNO";
   $data = array($fordel, $keep, $forstationid);
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' DB error '.$db->ErrorMsg();
      return;
   }
   echo '<table>';
   while ($o1=$rs->FetchNextObject()) {
      echo '<tr>
         <td>'.myhtml($o1->STATIONID).'</td>
         <td>'.myhtml($o1->SEQNO).'</td>
         <td>'.myhtml($fordel).'</td>
         <td>'.myhtml($o1->FORDEL).'</td>
         <td>'.myhtml($o1->FORKEEP).'</td>
         <td>';

      if ($isInt)
      {
         if ( (int)$o1->FORDEL == (int)$o1->FORKEEP ) {
            echo 'Same';
            $records[] = $o1->SEQNO;
         }
      }
      else
      {
         if ($o1->FORDEL === $o1->FORKEEP) {
            echo 'Same';
            $records[] = $o1->SEQNO;
         }
      }

      echo '</td></tr>';
   }
   echo '<table>';

   if (!empty($records)) {
      $query = 'DELETE FROM iform_prop WHERE STATIONID=? AND SEQNO IN ('.implode(',', $records).') AND PNAME=?';
      $data = array($forstationid, $fordel);
      if ($db->Execute($query, $data))
         echo "Reset OK";
      else
         echo __LINE__.' DB error';
   }
}
//--------------------------------------
function reset_docdate($forstationid)
{
   global $x2;
   $db = &$x2->db;

   $query = "SELECT T1.STATIONID, T1.SEQNO, T1.DOCDATE, T2.PVALUE FROM iform_main T1
      LEFT JOIN iform_prop T2 ON (T2.STATIONID=T1.STATIONID AND T2.SEQNO=T1.SEQNO AND T2.PNAME='YYMMDD6')
      WHERE T1.STATIONID=?
      ORDER BY T1.STATIONID, T1.SEQNO";
   $data = array($forstationid);
   if (($rs=$db->Execute($query, $data))===false) {
      echo __LINE__.' DB error '.$db->ErrorMsg();
      return;
   }
   echo '<table>';
   while ($o1=$rs->FetchNextObject()) {
      echo '<tr>
         <td>'.myhtml($o1->STATIONID).'</td>
         <td>'.myhtml($o1->SEQNO).'</td>
         <td>'.myhtml($o1->DOCDATE).'</td>
         <td>'.myhtml($o1->PVALUE).'</td>
         <td>';

      do {
         $dto = DateTime::createFromFormat('ymd+', $o1->PVALUE);
         if ($dto === false) {
            echo 'No DATE';
            break;
         }

         if ($dto->format('Y-m-d') === substr($o1->DOCDATE, 0, 10))
            echo 'OK';
         else {
            echo 'Correct to '.$dto->format('Y-m-d');
            /*
            $query = 'UPDATE iform_main SET DOCDATE=? WHERE STATIONID=? AND SEQNO=?';
            $data = array($dto->format('Y-m-d'), $o1->STATIONID, $o1->SEQNO);
            if ($db->Execute($query, $data))
               echo ' ok';
            else
               echo ' error';
            */
         }
      } while (false);

      echo '</td></tr>';
   }
   $rs->Close();
   echo '</table>';
}
//--------------------------------------
function maintenance_menu()
{
   global $x2;

   SetHeadTitle('Maintenance');

   echo "<ul style=\"font-weight:bold;\">
      <li><a href =\"javascript:goTo(72)\">Cache status</a></li>
      <li><a href =\"javascript:goTo(65)\">".$x2->xlabel(99)."</a></li>
      <li><a href =\"javascript:goTo(26)\">Records with no TEXTIN</a></li>
      <li><a href =\"javascript:goTo(41)\">Folder contents</a></li>
      <li><a href =\"javascript:goTo(43)\">Document Date progress</a></li>
      <li><a href =\"javascript:goTo(67)\">SQL info</a></li>
      <li><a href =\"javascript:goTo(76)\">Table size</a></li>";
   if ($x2->ulevel==99) {
      echo "<li><a href=\"javascript:goTo(82)\">Check PROPERTIES</a></li>
         <li><a href =\"javascript:goTo(11)\">Execute SQL</a></li>
         <li><a href =\"javascript:goTo(79)\">Setup info.</a></li>";

   }
   echo "</ul>";
}
//--------------------------------------
function list_logins()
{
   global $x2;
   $db = &$x2->db;

   $gr1 = new cXRID('grid7');

   $query = "SELECT * FROM iform_login ORDER BY RID";
   if (($rs = $db->Execute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1 = $rs->FetchNextObject())
   {
      $row1 = array($o1->RID, myhtml($o1->LOGINUSER), myhtml($o1->LOGINTIME));
      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->cols = array(array('Id', 50), array('Login', 200), array('Time', 200));

   $gr1->play();

   echo "<div id=tbar2><small>End of data</small></div>";
}
//--------------------------------------
function start_maint()
{
   global $x2;
   $db = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   SetHeadTitle('Records with no TEXTIN');

                       // Keep using CREDAYTIME, not DOCDATE
   $query = "SELECT SEQNO, CREDAYTIME, DOCID FROM iform_main
      WHERE STATIONID=$stationid AND TEXTIN IS NULL ORDER BY SEQNO";
   if (($rs = $db->Execute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   $nrec = 0;
   echo "<table>";
   while ($o1 = $rs->FetchNextObject())
   {
      $ar1 = explode(' ', $o1->CREDAYTIME); // YYYY-MM-DD hh:mm:ss
      $ar2 = explode('-', $ar1[0]);         // YYYY-MM-DD
      echo "<tr>
          <td> ".$o1->SEQNO." <td> <td> ".$o1->CREDAYTIME." <td>
          <td> ".myhtml($o1->DOCID)." <td> <td>
          <a href =\"".basename(__FILE__)
                       ."?FUNCTION=27&SEQUENCE=".$o1->SEQNO."&DATE="
                       .implode('', $ar2)
                       ."\">Repair</a></td>
                   </tr> ";
          $nrec++;
   }
   $rs->Close();
   echo "</table>$nrec records";
}
//--------------------------------------
function deleteIt()
{
   global $x2;
   $db = &$x2->db;

   $db->StartTrans();
   do
   {
      $data = array($_SESSION['STATIONID'], $_REQUEST['SEQUENCE']);

      $query = "DELETE FROM iform_main WHERE STATIONID=? AND SEQNO=?";
      if (!$db->Execute($query, $data))
      {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }

      $query = "DELETE FROM iform_prop WHERE STATIONID=? AND SEQNO=?";
      if (!$db->Execute($query, $data))
      {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }

      $query = "DELETE FROM iform_lex WHERE STATIONID=? AND SEQNO=?";
      if (!$db->Execute($query, $data))
      {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }
   } while (false);
   $db->CompleteTrans();
}
//--------------------------------------
function repairIt()
{
   global $x2;
   $db = &$x2->db;

   $_REQUEST['STATIONID'] = $_SESSION['STATIONID'];

   $tempzip = tempnam(sys_get_temp_dir(), "IFZ"); // iform zip file
   $tempA   = tempnam(sys_get_temp_dir(), "IFA"); // iform zip file

   $cif = new cFNAME($_SESSION['STATIONID'], $_REQUEST['SEQUENCE'], $_REQUEST['DATE'], $tempzip );

   if (get_image_G_CLOUD_STORAGE($cif, $emsg))
   {
      // o.k.
      $zip = new ZipArchive;
      if (($re = $zip->open($tempzip)) !== true)
      {
         echo "Failed to open ZIP ".$_SESSION['STATIONID']
             ."_".$_REQUEST['SEQUENCE']
             ."_".$_REQUEST['DATE']
             .", error $re";
         return deleteIt();
      }

      $db->StartTrans();

      $props = array();
      for ($i = 0; $i < $zip->numFiles; $i++)
      {
         $fname= $zip->getNameIndex($i);
         $ext   = pathinfo($fname, PATHINFO_EXTENSION);
         if (strcasecmp($ext, "idx") == 0)
         {
            $fp = $zip->getStream($fname);
            if ($fp === false)
            {
               OutMessage("Failed to open file: ".$fname);
            }
            else
            {
               while (!feof($fp))
               {
                  $w1  = fgets($fp);
                  $ar1 = explode('=', $w1, 2);
                  if (count($ar1) < 2 || empty($ar1[0]))
                     continue;

                  $w2 = trim($ar1[1]);
                  if (empty($w2))
                     continue;

                  $props[ToUTF8(trim($ar1[0]))] = ToUTF8($w2);
               }
               fclose($fp);

               $query = "INSERT INTO iform_prop (STATIONID, SEQNO, SUBSEQ, PNAME, PVALUE) VALUES(?,?,0,?,?)";
               foreach ($props as $k => $v)
               {
                  $data = array($_SESSION['STATIONID'], $_REQUEST['SEQUENCE'],
                                $k, $v);
                  if (!$db->Execute($query, $data))
                  {
                     uerror( 'Database error, line '.__LINE__ );
                  }
               }
            }
         }
         else if (strcasecmp(substr($fname, -6), '_a.txt') == 0)
         {
            $txt = $zip->getFromIndex($i);
            if ($txt === false)
            {
               OutMessage("Failed to read file: ".$fname);
            }
            else
            {
               $query = "UPDATE iform_main SET TEXTIN=? WHERE STATIONID=? AND SEQNO=?";
               $data =
                   array($txt, $_SESSION['STATIONID'], $_REQUEST['SEQUENCE']);
               if (!$db->Execute($query, $data))
               {
                  uerror( 'Database error, line '.__LINE__ );
               }
            }
         }
      }
      $zip->close();

      $db->CompleteTrans();
      echo "Finished";
   }
   unlink($tempzip); // cleanup
   unlink($tempA);
}
//--------------------------------------
function process_query()
{
   global $x2;
   $db = &$x2->db;
   $stationid = (int)$_SESSION['STATIONID']; // '(int)' is used for security

   /*
   $ar1 = array('SOURCE', 'SIGNED', 'FROMDATE');
   foreach ($ar1 as $p1) {
      if (isset($_REQUEST[$p1])) {
         $_SESSION[$p1] = $_REQUEST[$p1];
      }
   }
   */

   if (isset($_REQUEST[$p1='SOURCE'])) {
		$_SESSION[$p1] = $_REQUEST[$p1];
		$_SESSION['SIGNED'] = (int)@$_REQUEST['SIGNED'];
	}
	if (isset($_REQUEST[$p1='FROMDATE'])) {
		$_SESSION[$p1] = $_REQUEST[$p1];
	}

   if (empty($_SESSION['SOURCE'])) { // precaution
      uerror('Source not set!');
      return;
   }

   // ----------- authentication for HR (start) ----------
   if (isset($_SESSION['SOURCE']) && $_SESSION['SOURCE'] === 'HR')
   {
      $hr_user = get_hr_user();
      if ($hr_user !== false) {
         if (empty($_SESSION['HR_STOREID'])) {
            return request_hr_login($hr_user);
         }
         else {
            // Force specific property value
            $propname= 'Κωδ.καταστήματος';
            if (($k1=array_search($propname, $_REQUEST['PROP']))===false) { // not found
               $_REQUEST['PROP'][] = $propname;
               $_REQUEST['FROM'][] = $_SESSION['HR_STOREID'];
               $_REQUEST['TILL'][] = '';
            }
            else {
               $_REQUEST['FROM'][$k1] = $_SESSION['HR_STOREID'];
               $_REQUEST['TILL'][$k1] = '';
            }
         }
      }
      else {
         // check rights
         $query = "SELECT COUNT(*) FROM iform_rights WHERE LOGINUSER=? AND RIKEY='HR' AND RITYPE=0 AND STATIONID=?";
         $data = array($_SESSION['USERID'], $stationid);
         if (($rs=$db->Execute($query, $data))===false) {
            uerror( 'Database error, line '.__LINE__ );
            return;
         }
         $row=$rs->FetchRow();
         $rs->Close();
         if ($row[0]==0) { // no rights
		       return request_hr_login(false);
         }
	   }
   }
   // ---------- authentication for HR (end) ----------

   $qo = new cQUERY(2);
   if ($qo->query===false)
      return;
?>
<script>
var StorageMthd = <?php echo(int) $_SESSION['STORAGEMTHD']; ?>;
$(function() {
   $('#querydesc').dialog({autoOpen : false, modal : true, width : 600});
});
function Page2Close()
{
   var mywin = window.open('iform.php?FUNCTION=2', 'iform_main');
   window.close(); // self close
}
function addMonthQuery()
{
   <?php
   if (!empty($_SESSION['FROMDATE'])) {
      echo "var url = 'iform_exp.php?FUNCTION=29';
         \$.get(url, function(data){
            if (data==='OK') { data = 'Please check \"Waiting queries\" after an hour or so!'; }
            window.alert(data);
         } )";

   }
   ?>
}
</script>
<script src="iform.js.php?FUNC=process_query"></script>

<div id=queryparams2 title="Filter parameters" style="background-color:#99CCCC"> <?php

   if (isset($_REQUEST['FROMDATE']))
   {
      $nc = 0;
      $filterDescr ='';

      if (!empty($_REQUEST['FROMSEQNO']))
      {
         $filterDescr.= "Seqno from: ".myhtml($_REQUEST['FROMSEQNO'])
                            .", Seqno to: ".myhtml($_REQUEST['TILLSEQNO']);
         $nc++;
      }

      if (!empty($_REQUEST['FROMDATE']))
      {
         $filterDescr.= "Date from: ".myhtml($_REQUEST['FROMDATE'])
                            .", Date to: ".myhtml($_REQUEST['TILLDATE']);
         $nc++;
      }

      if (strlen(trim(@$_REQUEST['ANYWORD'])) > 0)
      {
         $filterDescr.= ", Any word: ".myhtml($_REQUEST['ANYWORD']);
         $nc++;
      }

      $n = isset($_REQUEST['PROP'])?count($_REQUEST['PROP']):0;
      for ($i = 0; $i < $n; $i++)
      {
         $val = trim($_REQUEST['FROM'][$i]);
         if (strlen($val) == 0)
            continue;

         $filterDescr.= ", ".myhtml($_REQUEST['PROP'][$i])
                            ." From: ".myhtml($_REQUEST['FROM'][$i])
                            ." To: ".myhtml($_REQUEST['TILL'][$i]);
         $nc++;
      }

      if ($nc == 0)
      {
         if ($x2->preflangid == 0)
         { // English
            echo "<div style=\"font-size:14pt\">You have not setup any
               filters. Please <a href=\"javascript:goTo(3)\">repeat!</a></div>";
         }
         else
         { // Greek
            echo "<div style=\"font-size:14pt\">Δεν καθορίσατε φίλτρα,
               παρακαλούμε <a href=\"javascript:goTo(3)\">επαναλάβετε!</a></div>";
         }
         return;
      }

      $_SESSION['FILTERDESCR'] = $filterDescr;
   }

   echo $_SESSION['FILTERDESCR'];
?> </div>

   <?php
   $pg   = getPage();
   $pgsz = getPageSize('grid1');
   $gr1  = new cXRID('grid1');

   $n2 = count($qo->query2F);

	if (isset($logFile)) {
      $ss = print_r($qo, true);
      file_put_contents($logFile, $ss);
   }

   $db->SetFetchMode(ADODB_FETCH_NUM); // NUM, ASSOC, BOTH
   if ($_SESSION['SOURCE'] === 'LIANIKI' || (int)@$_SESSION['SIGNED'] > 0)
	{
		$rs = PageExecuteX2($db, $qo->query, $pgsz, $pg, $qo->parameters);
	}
	else
	{
		//$rs = $db->PageExecute($qo->query, $pgsz, $pg, $qo->parameters);
		//if (($rs = $x2->PageExecuteX($qo->query, $pgsz, $pg, $qo->parameters)) === false)
      //$rs = $db->Execute($qo->query, $qo->parameters);
      $rs = PageExecuteX2($db, $qo->query, $pgsz, $pg, $qo->parameters);
   }
	if ($rs === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }

   if ($qo->viewid == 0)
   { // std query
      $gr1->cols = array(
            array('.CH', 30), // array('<input type=checkbox>', 40),
            array('Station Id', 100),
            array('Sequence no.', 100),
            array('Created', 120),
            array('Text length', 80),
            array('KB data size', 80),
            array('Document Id', 250),
            array('Customer Id', 200));

      $autoN = count($gr1->cols);
   }
   else
   {
      // fixed (auto) first:
      $gr1->cols = array(
            array('.CH', 30), // array('<input type=checkbox>', 40),
            array('Station Id', 100),
            array('Sequence no.', 100),
            array('Created', 120));

      foreach ($qo->xfields as $j=>$xf1) {
         if (in_array($xf1, $qo->stdFields)) {
            $gr1->cols[] = array($qo->xlabels[$j], 100);
         }
      }
      if (($k2=array_search('TM.BRANCHID', $qo->stdFields)) !== false) {
			$gr1->cols[] = array($k2, 100);
		}

      $autoN = count($gr1->cols);

      // user defined cols:
      foreach ($qo->xlabels as $i=>$xf1)
      {
         if (!in_array($xf1, $qo->stdFields)) {
            $gr1->cols[] = array($qo->xlabels[$i], 100);
         }
      }
   }

   // NEW Code
   /*
   $records=array();
   while ($o1=$rs->FetchNextObject())
   {
      $records[] = $o1;
   }
   file_put_contents('c:\\tmp\\php\\1.txt', serialize($records));
   $rs->moveFirst();
   */
   // End of new code

   //
   // parse once to get SEQNO
   //
   $seqnos = array();
   while ($r1 = $rs->FetchRow())
   {
      $seqnos[] = $r1[1];
   }

   //
   // Generate 2nd query
   //
   if (!empty($seqnos))
   {
      $query2 = "SELECT SEQNO, PNAME, PVALUE FROM iform_prop
          WHERE STATIONID=$stationid AND SEQNO IN(
              ".implode(', ', $seqnos).") ";
      if (!empty($qo->query2F))
      {
         $query2 .= " AND PNAME IN (";
         $nf = 0;
         foreach ($qo->query2F as $xf1)
         {
            if ($nf++ > 0)
            {
               $query2 .= ", ";
            }
            $query2 .= $db->quote($xf1);
         }
         $query2 .= ")";
      }

      $props = ReadPageProps($query2);
   }
   else
   {
      $props = array();
   }
//echo "props = ".count($props)." ";

   //
   // parse again to get full data
   //
   $fields = array();
   $fn     = 0;
   if (!empty($seqnos))
   {
      $rs->moveFirst();
   }
   while ($row1 = $rs->FetchRow())
   {
      $stationid = 0;
      $seqno     = 0;
      $row2      = array('');

      if ($fn == 0)
      {
         $fn = $rs->FieldCount();
         for ($i = 0; $i < $fn; $i++)
         {
            $o2       = $rs->FetchField($i);
            $fields[] = $o2->name;
         }
      }

      for ($i = 0; $i < $fn; $i++)
      {
         switch ($fields[$i])
         {
         case 'STATIONID':
            $stationid=(int)$row1[$i];
            break;
         case 'SEQNO':
            $seqno = (int)$row1[$i];
            break;
         case 'IMGSIZE':
            $row1[$i] = sprintf("%.1f", $row1[$i] / 1024.0); // reset
            break;
         case 'CUSTOMERID':
            if (strlen($row1[$i]) > 0)
            {
               $row1[$i] =
                   myhtml($stationid.'.'.$row1[$i] /*CUSTOMERID*/); // reset
            }
            break;
         }

         if ($i < ($autoN - 1))
         {
            $row2[] = $row1[$i];
         }
      }

      foreach ($qo->xfields as $xf1)
      {
			/*
         if ($xf1 === 'SIGNED')
				continue;
		   */

         $fi = false;
         for ($i = $autoN; $i < $fn; $i++)
         {
            if ($fields[$i] === $xf1)
            {
               $row2[] = $row1[$i];
               $fi     = true;
               break;
            }
         }

         if (!$fi)
         {
            if (array_key_exists($seqno, $props))
            {
               $p1a = $props[$seqno];
               if (array_key_exists($xf1, $p1a))
               {
                  $row2[] = $p1a[$xf1];
               }
               else
               {
                  $row2[] = "";
               }
            }
            else
            {
               $row2[] = "";
            }
         }
      }

      $gr1->rows[] = $row2;
   }
   $epage = $rs->LastPageNo();
   $rs->Close();
   //$epage = $x2->LastPageNo();

   $gr1->click = 'oclick';
   $gr1->play();

   echo "<div id=tbar2>";
   print_page_navEx($pg, $epage, 4);
   if (VERBOSE==2)
   {
      echo '<button type=button class=NavButton onclick="ShowQuery()"
          title="Filter parameters"><img src="../img/filter.png" alt="Filter"></button>';
   }
   echo '<button id=nav_restart type=button onclick="goTo(3)">'.$x2->xlabel(28 /* Home / New query */ ).'</button>';
   if (empty($_SESSION['CUSTOMERID'])) {
      echo '<button type=button title="'.$x2->xlabel(109 /* download all */).'" onclick="oclick2()"><img src="../img/download.png"></button>';
   }
   echo '<button type=button title="Export list" ';
   if (substr(PHP_OS, 0, 3)!=="WIN") {
      echo ' disabled ';
   }
   echo ' onclick="onExportList()"><img src="../img/open_excel.png"></button>';
   if (isset($_SESSION['SOURCE']) && $_SESSION['SOURCE'] === 'HR' && $hr_user === false) {
      echo '<button type=button title="Delete all" onclick="onHRdeleteAll()"><img src="../img/drop.png"></button>';
   }
   echo '</div>';

   $selx = array(
      array(9, '../img/pdf16x16.png', 'PDF/ XPS'),
      array(3, '../img/button_notes.png', $x2->xlabel(62 /* Text */ )),
      array(4, '../img/download.png', $x2->xlabel(24 /* Get documents */ )),
      '<hr>',
      array(1, '../img/details.gif', $x2->xlabel(54 /* Show Properties */ )),
      array(2, '../img/report16x16.png', $x2->xlabel(55 /* Show Text */ )),
      array(5, '../img/browse16x16.png', $x2->xlabel(53 /* Show Keywords */ ))
      );
   draw_popup($selx);

   $selx2 = array(
      array(1001, '../img/go_next.gif', $x2->xlabel(110 /* Download all selected */) ),
      array(1002, '../img/go_next.gif', $x2->xlabel(111 /* Download full month (no other filters) */) )
   );
   draw_popup($selx2,false,'popmenu2');
   ?>
   <div id=popshow class=POPMENU></div>

   <div id=showmore title = "Details">
      <div id=tabs>
         <ul>
            <li><a href="#tabs-1"> <?php echo $x2->xlabel(44 /* Properties */ ); ?> </a></li>
            <li><a href="#tabs-2"> <?php echo $x2->xlabel(62 /* Text */ ); ?> </a></li>
            <li><a href="#tabs-4"> <?php echo $x2->xlabel(26 /* History */ ); ?> </a></li>
            <li><a href="#tabs-5"> <?php echo $x2->xlabel(30 /* Keywords */ ); ?> </a></li>
            <li><a href="#tabs-6"> Scan log </a></li>
         </ul>
         <div id="tabs-1"></div>
         <div id="tabs-4"></div>
         <div id="tabs-2"></div>
         <div id="tabs-5"></div>
         <div id="tabs-6"></div>
      </div>
   </div>

   <div id=querydesc title="Query details" style="font-size:10pt"> <?php
      if (VERBOSE==2)
      {
         echo myhtml($qo->query);
         echo "<hr>";
         echo myhtml(@$query2);
         echo "<hr>";
         foreach ($qo->parameters as $p1)
         {
            echo myhtml($p1)." -- ";
            $l = strlen($p1);
            for ($i = 0; $i < $l; $i++)
            {
               echo ord($p1[$i])." ";
            }
            echo "<br>";
         }
         echo "<hr>";
         echo $qo->msg;
      }
   ?></div>
<?php
}
//--------------------------------------
function remind_passwd()
{
   global $x2;
   $db = &$x2->db;

   if (empty($_REQUEST['USERID']))
   {
      uerror("Please specify [User Id], then repeat!");
      return request_login();
   }
   $userid=$_REQUEST['USERID'];

   $query = "SELECT PASSWD5 FROM iform_users WHERE USERID=?";
   $data  = array($userid);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return request_login();
   }
   $row = $rs->FetchRow();
   $rs->Close();
   if ($row === false)
   {
      uerror("User Id [".myhtml($data[0])."] not in database. Please
         check for any error, then repeat!");
      return request_login();
   }

   $mtitle = "iForm guest password reset";
   $msg    = "Please follow this link to reset your password:\r\n"."http://"
              .$_SERVER['HTTP_HOST']
              .myhtml($_SERVER['SCRIPT_NAME'])
              ."?FUNCTION=991&USERID=".urlencode($userid)
              ."&PID=".$row[0]
              ."-".time()
              ."\r\n"."The link is valid for one hour only!";
   if (!empty($_REQUEST['NOMAIL']))
   {
      echo "<div class=umessage>".myhtml($msg)."</div>";
   }
   else
   {
      if (!@mail($userid, $mtitle, $msg))
         uerror('An error occured to our mail system! Sorry
              for the inconvenience. Please try again later.');
      else // o.k.
         echo '<div class=umessage>An email has been sent to you with a link
              to reset your password.</div>';
   }

   return request_login();
}
//--------------------------------------
function del_additional_user()
{
   global $x2;
   $db = &$x2->db;

   $query = 'DELETE FROM iform_users WHERE USERID=?';
   $data  = array($_REQUEST['RECORDID']);
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
}
//--------------------------------------
function add_additional_user()
{
   global $x2;
   $db        = &$x2->db;
   $stationid = (int)$_SESSION['STATIONID'];

   $theUserId = trim($_REQUEST['THEUSERID']);
   if (empty($theUserId))
   {
      uerror('Empty User Id! Please try again.');
      return;
   }

   $query = 'SELECT COUNT(*) FROM iform_users WHERE USERID=?';
   $data = array($theUserId);
   if (($rs=$db->Execute($query, $data))===false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   $row = $rs->FetchRow();
   $rs->Close();
   if ($row[0]>0) {
      uerror('User '.myhtml($theUserId).' already exists!');
      return;
   }

   if ($x2->ulevel==99 && isset($_REQUEST['THESTATIONID']))
   {
      if (empty($_REQUEST['THESTATIONID']))
      {
         uerror('Empty Store ID!');
         return;
      }
      $stationid = (int)$_REQUEST['THESTATIONID'];
      $o1=(Object)array('STORAGEMTHD'=>3, 'STORETOKEN'=>'taxmail-1182;taxmail'); // default values
   }
   else
   {
      // Read data for current user
      $query = "SELECT STORAGEMTHD, STORETOKEN FROM iform_users WHERE USERID=? AND STATIONID=?";
      $data = array($_SESSION['USERID'],
                    $stationid); // stationid is added for security
      if (($rs = $db->Execute($query, $data)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
         return;
      }
      $o1 = $rs->FetchNextObject();
      $rs->Close();
      if ($o1 === false)
      {
         uerror("Main record disappeared!");
         return;
      }
   }

   $storeid=$_REQUEST['STOREID'];
   if (!empty($storeid)) {
      while (strlen($storeid) < (int)@$prop['STORAGEIDMINCHARS']) {
         $storeid = '0'.$storeid;
      }
   }
   $query="INSERT INTO iform_users (USERID, PASSWD5, STATIONID, STORAGEMTHD, STORETOKEN, CHANGEPRIV, LASTUPDATE, STOREID, PREFVIEWID)
      VALUES(?, ?, ?, ?, ?, 0, ?, ?, ?)";
   $data=array($theUserId, md5("1234"), $stationid, $o1->STORAGEMTHD, $o1->STORETOKEN, date('Y-m-d H:i:s'), $storeid, (int)@$_REQUEST['PREFVIEWID'] );
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
   }
   else
   {
      echo "<div class=umessage>Ο χρήστης <var>".myhtml($theUserId)
          ."</var> δημιουργήθηκε με password '1234'.</div>";
   }
}
//--------------------------------------
function delete_HR_docs()
{
   global $x2;
   $db        = &$x2->db;
   $stationid = (int)$_SESSION['STATIONID'];

   $ar1 = explode(',', @$_REQUEST['IDS']);
   if (empty($ar1))
      return;

   $qry1 = 'DELETE FROM iform_main WHERE STATIONID=? AND SEQNO IN ('.$_REQUEST['IDS'].')';
   $qry2 = 'DELETE FROM iform_prop WHERE STATIONID=? AND SEQNO IN ('.$_REQUEST['IDS'].')';
   $data = array($stationid);
   $db->StartTrans();
   foreach ($ar1 as $id1)
   {
      if (!$db->Execute($qry1, $data)) {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }
      if (!$db->Execute($qry2, $data)) {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }
   }
   $db->CompleteTrans();
}
//--------------------------------------
function reset_addi_user_data()
{
   global $x2;
   $db = &$x2->db;

   $storeid=$_REQUEST['STOREID'];
   while (!empty($storeid) && strlen($storeid)<4) {
      $storeid='0'.$storeid;
   }
   $query = 'UPDATE iform_users SET PREFVIEWID=?, STOREID=? WHERE USERID=?';
   $data  = array((int)$_REQUEST['PREFVIEWID'], $storeid, $_REQUEST['THEUSERID']);
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
}
//--------------------------------------
function reset_addi_user_pwd()
{
   global $x2;
   $db = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   $theUserId=trim($_REQUEST['THEUSERID']);

   $query = 'SELECT COUNT(*) FROM iform_users WHERE USERID=? AND STATIONID=?';
   $data  = array($theUserId, $stationid); // stationid is added for security
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   $row = $rs->FetchRow();
   $rc  = (int)@$row[0];
   $rs->Close();
   if ($rc == 0)
   { // no record found
      /*
      $query = 'SELECT STORAGEMTHD, STORETOKEN FROM iform_users WHERE USERID=? AND STATIONID=?';
      $data = array($_SESSION['USERID'], $stationid); // stationid is added for security
      if (($rs = $db->Execute($query, $data)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
         return;
      }
      $o1 = $rs->FetchNextObject();
      $rs->Close();
      if ($o1 === false)
      {
      */
         if ($stationid == 0) {
            uerror('Station Id not (yet) set!');
            return;
         }
         $query="INSERT INTO iform_users (USERID, PASSWD5, STATIONID, CHANGEPRIV, LASTUPDATE)
            VALUES(?, ?, $stationid, 0, ?)";
         $data=array($theUserId, md5($_REQUEST['NEWPASSWD']), date('Y-m-d H:i:s') );
         /*
      }
      */
   }
   else
   { // user already exists
      $query = "UPDATE iform_users SET PASSWD5=? WHERE USERID=?";
      $data  = array(md5($_REQUEST['NEWPASSWD']), $theUserId);
   }
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
   }
   else
   {
      echo "<div class=umessage>Το password του χρήστη <var>".myhtml($theUserId)
          ."</var> άλλαξε!</div>";
   }
}
//--------------------------------------
function reset_edit_passed_priv()
{
   global $x2;
   $db = &$x2->db;
   $userid=$_REQUEST['RECORDID'];

   do {
      $query = "SELECT CHANGEPRIV FROM iform_users WHERE USERID=?";
      $data = array($userid);
      if (($rs=$db->Execute($query, $data))===false)
      {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }
      $row=$rs->FetchRow();
      $rs->Close();

      if ($row===false) // record does not exist
      {
         $query = "INSERT INTO iform_users (USERID, PASSWD5, STATIONID, CHANGEPRIV) VALUES(?, '', ?, ?)";
         $data = array($userid, (int)$_SESSION['STATIONID'], 2);
      }
      else //if ((int)$row[0]==0 || (int)$row[0]==2)
      {
         switch ($row[0])
         {
         case 0:
            $newval = 2;
            break;
         default: // 1,2
            $newval = 0;
            break;
         }
         $query = "UPDATE iform_users SET CHANGEPRIV = ? WHERE USERID=?";
         $data = array($newval, $userid);
      }
      if (!$db->Execute($query, $data))
      {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }
   } while (false);

   list_additional_users();
}
//--------------------------------------
function edit_level()
{
   global $x2;
   $db         = &$x2->db;
   $stationid  = (int)$_SESSION['STATIONID'];

   $query='UPDATE iform_level SET FULLNAME=? WHERE STATIONID=? AND LEVELID=?';
   $data=array($_REQUEST['FULLNAME'], $stationid, (int)$_REQUEST['LEVELID']);
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
   }
}
//--------------------------------------
function edit_source()
{
   global $x2;
   $db         = &$x2->db;
   $stationid  = (int)$_SESSION['STATIONID'];

   $query = 'UPDATE iform_source SET FULLNAME=? WHERE STATIONID=? AND SRC=?';
   $data=array($_REQUEST['FULLNAME'], $stationid, $_REQUEST['SRCID']);
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
   }
}
//--------------------------------------
function del_levelusr()
{
   global $x2;
   $db         = &$x2->db;
   $stationid  = (int)$_SESSION['STATIONID'];

   list($levelid, $usergroup) = explode(';', $_REQUEST['RECORDID']);

   if ((int)$usergroup==0) { // delete complete level
      $db->StartTrans();
      do {
         $query="DELETE FROM iform_level WHERE STATIONID=? AND LEVELID=?";
         $data=array($stationid, $levelid);
         if (!$db->Execute($query, $data))
         {
            uerror( 'Database error, line '.__LINE__ );
            break;
         }

         $query="DELETE FROM iform_level_usr WHERE STATIONID=? AND LEVELID=?";
         $data=array($stationid, $levelid);
         if (!$db->Execute($query, $data))
         {
            uerror( 'Database error, line '.__LINE__ );
            break;
         }
      } while (false);
      $db->CompleteTrans();
   }
   else { // delete usergroup
      $query="DELETE FROM iform_level_usr WHERE STATIONID=? AND LEVELID=? AND USERGROUP=?";
      $data=array($stationid, $levelid, $usergroup);
      if (!$db->Execute($query, $data))
      {
         uerror( 'Database error, line '.__LINE__ );
      }
   }
}
//--------------------------------------
function del_source()
{
   global $x2;
   $db         = &$x2->db;
   $stationid  = (int)$_SESSION['STATIONID'];

   $query="DELETE FROM iform_source WHERE STATIONID=? AND SRC=?";
   $data=array($stationid, $_REQUEST['RECORDID']);
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
   }
}
//--------------------------------------
function add_level()
{
   global $x2;
   $db         = &$x2->db;
   $stationid  = (int)$_SESSION['STATIONID'];

   $query="SELECT COUNT(*) FROM iform_level WHERE STATIONID=? AND FULLNAME=?";
   $data=array($stationid, $_REQUEST['FULLNAME']);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   $row=$rs->FetchRow();
   $rs->Close();
   if ($row[0]>0) {
      uerror("Description already exists: ".myhtml($_REQUEST['FULLNAME']) );
      return;
   }

   $query="INSERT INTO iform_level (STATIONID, LEVELID, FULLNAME)
      SELECT ?, COALESCE(MAX(LEVELID), 0)+1, ? FROM iform_level
      WHERE STATIONID=?";
   $data=array($stationid, $_REQUEST['FULLNAME'], $stationid);
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
   }
}
//--------------------------------------
function add_source()
{
   global $x2;
   $db         = &$x2->db;
   $stationid  = (int)$_SESSION['STATIONID'];

   $query="SELECT COUNT(*) FROM iform_source WHERE STATIONID=? AND FULLNAME=?";
   $data=array($stationid, $_REQUEST['FULLNAME']);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   $row=$rs->FetchRow();
   $rs->Close();
   if ($row[0]>0) {
      uerror("Full name already exists: ".myhtml($_REQUEST['FULLNAME']) );
      return;
   }

   $query="INSERT INTO iform_source (STATIONID, SRC, FULLNAME)
      SELECT ?, CONCAT('ROUTE', CONCAT('ROUTE', COALESCE(MAX(CAST(SUBSTRING(SRC, 6, 100) AS INT)), 0)+1)), ? FROM iform_source
      WHERE STATIONID=?";
   $data=array($stationid, $_REQUEST['FULLNAME'], $stationid);
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
   }
}
//--------------------------------------
function add_level_user()
{
   global $x2;
   $db         = &$x2->db;
   $stationid  = (int)$_SESSION['STATIONID'];

   $usergroup = (int)$_REQUEST['USERGROUP'];
   if ($usergroup==0) { // new group
      $query="INSERT INTO iform_level_usr (STATIONID, LEVELID, USERGROUP, USERID)
         SELECT $stationid, ?, COALESCE(MAX(USERGROUP), 0)+1, ? FROM iform_level_usr
         WHERE STATIONID=$stationid AND LEVELID=?";
      $data=array($_REQUEST['LEVELID'], $_REQUEST['USERID'], $_REQUEST['LEVELID']);
   }
   else {
      $query="INSERT INTO iform_level_usr (STATIONID, LEVELID, USERGROUP, USERID) VALUES(?,?,?,?)";
      $data=array($stationid, $_REQUEST['LEVELID'], $_REQUEST['USERGROUP'], $_REQUEST['USERID']);
   }
   if (!$db->Execute($query,$data)) {
      uerror( 'Database error, line '.__LINE__ );
   }
}
//--------------------------------------
function list_levels()
{
   global $x2;
   $db         = &$x2->db;
   $stationid  = (int)$_SESSION['STATIONID'];

   SetHeadTitle(31 /* Levels */ );

   $users=array();
   $query="SELECT USERID FROM iform_users WHERE STATIONID=$stationid ORDER BY USERID";
   if (($rs=$db->Execute($query))===false) {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($row=$rs->FetchRow()) {
      $users[] = $row[0];
   }
   $rs->Close();

   $levels=array();
   $query="SELECT LEVELID, FULLNAME FROM iform_level WHERE STATIONID=$stationid ORDER BY FULLNAME";
   if (($rs=$db->Execute($query))===false) {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $levels[] = $o1;
   }
   $rs->Close();
?>
<div id=askaddlevel>
<form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method = POST name="levelForm">
<input type=hidden name="FUNCTION">
<input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
<table>
   <tr>
      <td>Department id</td>
      <td><input type=text name="LEVELID" readonly style="width:250px"></td>
   </tr>
   <tr>
      <td>Description</td>
      <td><input type=text name="FULLNAME" style="width:250px"></td>
   </tr>
   <tr>
      <td></td>
      <td><input type=submit value="Update"></td>
   </tr>
</table>
</form>
</div>

<div id=askadduser>
<form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method = POST name="userForm">
<input type=hidden name="FUNCTION">
<input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
<table>
   <tr>
      <td>Department Id</td>
      <td><input type=text name="LEVELID" readonly style="width:250px"></td>
   </tr>
   <tr>
      <td>Description</td>
      <td><input type=text name="FULLNAME" readonly style="width:250px"></td>
   </tr>
   <tr>
      <td>Group Id</td>
      <td><select name="USERGROUP"></select></td>
   </tr>
   <tr>
      <td>User id</td>
      <td><select name="USERID"><?php prSelectErr($users, false); ?></select></td>
   </tr>
   <tr>
      <td></td>
      <td><input type=submit value="Update"></td>
   </tr>
</table>
</form>
</div>

<script>
$(function() {
   $('#askaddlevel').dialog({autoOpen : false, modal : true, resizable : false, width:400});
   $('#askadduser').dialog({autoOpen : false, modal : true, resizable : false, width:400});
});

var levelid, fullname, usergroup, fprop;

function oclick(stage, row, col)
{
   levelid    = this.cells(row, 0).getValue();
   fullname   = this.cells(row, 1).getValue();
   usergroup  = this.cells(row, 2).getValue();
   // adjust
   while (levelid.length==0 && row>0) {
      levelid    = this.cells(--row, 0).getValue();
      fullname   = this.cells(row, 1).getValue();
   }
   show_popup('popmenu');
   return false;
}
function winRet(x)
{
   switch (x)
   {
   case 57: // edit record
      ask_edit_level();
      break;
   case 58: // del record
      goRecDelete(x, levelid+';'+usergroup);
      break;
   case 59:
      ask_add_user();
      break;
   }
   hide_popup();
}
function ask_edit_level()
{
   $('form[name=levelForm]').find('input[name=FUNCTION]').val(57);
   $('form[name=levelForm]').find('input[name=LEVELID]').val(levelid);
   $('form[name=levelForm]').find('input[name=FULLNAME]').val(fullname);
   $('#askaddlevel').dialog('option', 'title', 'Edit level data').dialog('open');
}
function ask_add_level()
{
   $('form[name=levelForm]').find('input[name=FUNCTION]').val(56);
   $('form[name=levelForm]').find('input[name=LEVELID]').val('New');
   $('form[name=levelForm]').find('input[name=FULLNAME]').val('');
   $('#askaddlevel').dialog('option', 'title', 'Add new level').dialog('open');
}
function ask_add_user()
{
   $('form[name=userForm]').find('input[name=FUNCTION]').val(59);
   $('form[name=userForm]').find('input[name=LEVELID]').val(levelid);
   $('form[name=userForm]').find('input[name=FULLNAME]').val(fullname);
   var osel = $('select[name=USERGROUP]');
   osel.children().remove();
   if (usergroup.length>0) {
      osel.append($('<option></option>', {text:usergroup}));
   }
   else {
      osel.append($('<option>New</option>'));
   }
   $('#askadduser').dialog('option', 'title', 'Add new user').dialog('open');
}
</script>
<?php
   $gr1 = new cXRID('grid16');
   $gr1->cols=array(
      array('Department Id', 80),
      array('Description', 200),
      array('Group Id', 80),
      array('User(s)', 100)
   );

   $query="SELECT USERGROUP, USERID FROM iform_level_usr
      WHERE STATIONID=? AND LEVELID=?
      ORDER BY USERGROUP, USERID";
   foreach ($levels as $o1) {
      $gr1->rows[] = array($o1->LEVELID, myhtml($o1->FULLNAME));

      $last_usergroup=false;
      $userids=array();
      $data=array($stationid, $o1->LEVELID);
      if (($rs=$db->Execute($query, $data))===false) {
         uerror( 'Database error, line '.__LINE__ );
         return;
      }
      while ($o2=$rs->FetchNextObject()) {
         if ($last_usergroup===false) {
            $last_usergroup = $o2->USERGROUP;
         }

         if ($o2->USERGROUP!==$last_usergroup) { // existing group
            $gr1->rows[] = array('', '', $last_usergroup, implode(',', $userids));
            $last_usergroup = $o2->USERGROUP;
            $userids=array();
         }

         $userids[] = $o2->USERID;
      }
      $rs->Close();
      if (!empty($userids)) {
         $gr1->rows[] = array('', '', $last_usergroup, implode(',', $userids));
      }
   }

   $gr1->click = 'oclick';
   $gr1->play();

   echo "<div id=tbar2>
         <button type=button onclick =\"ask_add_level()\">".$x2->xlabel(36 /* New level */ )."</button>
         <button type=button onclick =\"goTo(51)\">".$x2->xlabel(57 /* Sources */ )."</button>
         <img src=\"../img/vline.png\" style=\"position:relative; top:4px;\">
         <button type=button onclick =\"goTo(19)\">".$x2->xlabel(40 /* Options */ )."</button>
         <button type=button onclick =\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
         </div> ";

   $selx = array(
      array(57, '../img/button_edit.png', $x2->xlabel(15 /* Edit */ )), // edit level or user
      array(59, '../img/user1.png', $x2->xlabel(2 /* Add user */ )),
      array(58, '../img/delete.png', $x2->xlabel(12 /* Delete */ )) // delete level or group
      );
   draw_popup($selx);
}
//--------------------------------------
function update_routes()
{
   global $x2;
   $db         = &$x2->db;
   $stationid  = (int)$_SESSION['STATIONID'];
   $src        = $_REQUEST['SRCID'];

   $db->StartTrans();
   do {
      $query="DELETE FROM iform_src_route WHERE STATIONID=? AND SRC=?";
      $data=array($stationid, $src);
      if (!$db->Execute($query, $data)) {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }

      $err=false;
      $query="INSERT INTO iform_src_route (STATIONID, SRC, LEVELSEQ, LEVELID) VALUES(?,?,?,?)";
      $ar1=explode(';', $_REQUEST['LEVELID']);
      $levelseq=0;
      foreach ($ar1 as $levelid) {
         if (!empty($levelid)) {
            $data=array($stationid, $src, ++$levelseq, $levelid);
            if (!$db->Execute($query,$data)) {
               $err=true;
               uerror( 'Database error, line '.__LINE__ );
               break;
            }
         }
      }
      if (!$err) {
         echo "<div class=umessage>Done!</div>";
      }
   } while (false);
   $db->CompleteTrans();
}
//--------------------------------------
function draw_users($levelusr, $levelid)
{
   $title = '';
   $lastgrp=false;
   $users=array();
   foreach ($levelusr as $o1) {
      if ($o1->LEVELID != $levelid)
         continue;

      if ($lastgrp===false) {
         $lastgrp = $o1->USERGROUP;
      }
      else if ($o1->USERGROUP !== $lastgrp) {
         $title .= '- '.implode(', ', $users).'<br>';
         $users = array(); // reset
         $lastgrp = $o1->USERGROUP;
      }

      $users[] = myhtml($o1->USERID);
   }

   if (!empty($users)) {
      $title .= '- '.implode(', ', $users);
   }

   if (!empty($title)) {
      echo ' title="'.myhtml($title).'"';
   }
}
//--------------------------------------
function list_routes()
{
   global $x2;
   $db         = &$x2->db;
   $stationid  = (int)$_SESSION['STATIONID'];
   $src        = $_REQUEST['RECORDID'];

   SetHeadTitle(49 /* Route */ );

   $query="SELECT FULLNAME FROM iform_source WHERE STATIONID=? AND SRC=?";
   $data=array($stationid, $src);
   if (($rs=$db->Execute($query,$data))===false) {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   $row=$rs->FetchRow();
   $rs->Close();
   if ($row===false) {
      uerror("Record not found for SRC=".myhtml($src) );
      return;
   }

   $levels = array();
   $query="SELECT LEVELID, FULLNAME FROM iform_level WHERE STATIONID=? ORDER BY FULLNAME";
   $data=array($stationid);
   if (($rs=$db->Execute($query,$data))===false) {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1 = $rs->FetchNextObject()) {
      $levels[$o1->LEVELID] = $o1->FULLNAME;
   }
   $rs->Close();

   $route=array();
   $query="SELECT LEVELID FROM iform_src_route
      WHERE STATIONID=? AND SRC=?
      ORDER BY LEVELSEQ";
   $data=array($stationid, $src);
   if (($rs=$db->Execute($query, $data))===false) {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1 = $rs->FetchNextObject()) {
      $route[] = $o1->LEVELID;
   }
   $rs->Close();

   $levelusr=array();
   $query="SELECT LEVELID, USERGROUP, USERID FROM iform_level_usr
      WHERE STATIONID=?
      ORDER BY LEVELID, USERGROUP, USERID";
   $data=array($stationid);
   if (($rs=$db->Execute($query, $data))===false) {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1 = $rs->FetchNextObject()) {
      $levelusr[] = $o1;
   }
   $rs->Close();
?>
<div class=pageTop><?php echo myhtml($row[0]); ?></div>
<script>
$(function(){
   $('#fields').sortable();
   $( document ).tooltip({ content:function(){
      var elem = $(this);
      return elem.attr('title');
   } });
} );
function UpdateRoute()
{
   var levelids = [];
   var ar1 = $("#fields").sortable('toArray');
   for (var p in ar1)
   {
      if ($('#' + ar1[p]).find('input').is(':checked'))
      {
         levelids.push( $('#' + ar1[p]).find('input').val() );
      }
   }
   $('input[name=LEVELID]').val( levelids.join(';') );
   $('form[name=goForm]').submit();
}
</script>
<?php
   echo "<form action=\"".myhtml($_SERVER['SCRIPT_NAME'])."\" method=POST name=\"goForm\">
      <input type=hidden name=\"FUNCTION\" value=\"61\">
      <input type=hidden name=\"CSRFToken\" value=\"".$_SESSION['CSRFToken']."\">
      <input type=hidden name=\"SRCID\" value=\"".myhtml($src)."\">
      <input type=hidden name=\"LEVELID\">
      <fieldset>
      <legend>".$x2->xlabel(88 /*Route sequence*/)."</legend>
      <ul id=fields>";
   // Draw route
   $i=0;
   foreach ($route as $levelid) {
      $i++;
      echo "<li id=R$i class=\"ui-state-default\">
         <span class=\"ui-icon ui-icon-arrowthick-2-n-s\"></span>
         <label ";
      draw_users($levelusr, $levelid);
      echo ">
         <input type=checkbox value=\"$levelid\" checked>".(array_key_exists($levelid, $levels)?myhtml($levels[$levelid]):($levelid.'#'))."
         </label>
         </li>";
   }
   // Add other levels
   foreach ($levels as $levelid=>$fullname) {
      if (in_array($levelid, $route))
         continue;

      $i++;
      echo "<li id=R$i class=\"ui-state-default\">
         <span class=\"ui-icon ui-icon-arrowthick-2-n-s\"></span>
         <label ";
      draw_users($levelusr, $levelid);
      echo ">
         <input type=checkbox value=\"$levelid\">".myhtml($fullname)."
         </label>
         </li>";
   }
   echo "</ul>";

   echo "</fieldset>
      <input type=button onclick=\"UpdateRoute()\" value=\"".$x2->xlabel(65 /*Update*/)."\">
      <input type=button onclick=\"goTo(51)\" value=\"".$x2->xlabel(7 /*Cancel*/)."\">
      </form>";
}
//--------------------------------------
function list_sources()
{
   global $x2;
   $db         = &$x2->db;
   $stationid  = (int)$_SESSION['STATIONID'];

   SetHeadTitle(83 /* Sources (Procedures) */ );
?>
<div id=askaddroute>
<form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method = POST name="routeForm">
<input type=hidden name="FUNCTION">
<input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
<table>
   <tr>
      <td><?php $x2->xprint(84 /* Source (Procedure) */); ?></td>
      <td><input type=text name="SRCID" readonly style="width:250px"></td>
   </tr>
   <tr>
      <td><?php $x2->xprint(85 /* Description */); ?></td>
      <td><input type=text name="FULLNAME" style="width:250px"></td>
   </tr>
   <tr>
      <td></td>
      <td><input type=submit value="Update"></td>
   </tr>
</table>
</form>
</div>

<div id=askaddprop>
<form action="iform_exp.php" method = POST name="propForm">
<input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
<table>
   <tr>
      <td>Property name</td>
      <td>
         <input type=text name="PNAME" style="width:250px">
      </td>
   </tr>
   <tr>
      <td></td>
      <td>
         <input type=button value="Update" onclick="process_property()">
      </td>
   </tr>
</table>
</form>
</div>

<div id=showSrcDetail>
   <div id="tabs">
      <ul>
         <li><a href="#tabs-1"><?php echo $x2->xlabel(44 /* Properties */ ); ?></a></li>
         <li><a href="#tabs-2"><?php echo $x2->xlabel(49 /* Route */ ); ?></a></li>
      </ul>
      <div id="tabs-1"></div>
      <div id="tabs-2"></div>
   </div>
</div>
<script>
   var srcid, fullname, fprop, pname, last_x=0;

   $(function() {
      $('#askaddroute').dialog({autoOpen : false, modal : true, resizable : false, width:400});
      $('#askaddprop').dialog({autoOpen : false, modal : true, resizable : false, width:400});
      $('#showSrcDetail').dialog({autoOpen : false, modal : false, resizable : true});
      $( "#tabs" ).tabs({beforeActivate:function(event,ui){
         showX=parseInt(ui.newPanel.selector.split('-')[1]);
         if (showX==1) {
            last_x=1;
            show_properties();
         }
         else {
            last_x=60;
            show_routes();
         }
      } });
   });

   function oclick(stage, row, col)
   {
      srcid      = this.cells(row, 0).getValue();
      fullname   = this.cells(row, 1).getValue();
      if ($('#showSrcDetail').dialog('isOpen')) {
         if (last_x==1) {
            show_properties();
            return false;
         }
         else if (last_x==60) {
            show_routes();
            return false;
         }
      }
      // all other cases
      show_popup('popmenu');
      return false;
   }
   function oclick2(atext)
   {
      pname= atext;
      show_popup('popmenu2');
      $('#popmenu2').css('z-index', 1000);
   }
   function winRet(x)
   {
      switch (x)
      {
      case 1:
         $('#showSrcDetail').dialog('option', 'title', 'Details for '+fullname).dialog('open');
         $( "#tabs" ).tabs({active: 0});
         show_properties();
         break;
      case 13:
         ask_edit_property();
         break;
      case 14:
         ask_del_property();
         break;
      case 52: // edit record
         ask_edit_route();
         break;
      case 53: // del record
         goRecDelete(x, srcid);
         break;
      case 60: //Route
         var oldIndex = $('#tabs').tabs('option', 'active');
         $('#showSrcDetail').dialog('option', 'title', 'Details for '+fullname).dialog('open');
         if (oldIndex!=1) {
            $( "#tabs" ).tabs({active: 1});
         }
         else {
            show_routes();
         }
         break;
      }
      last_x = x; // save it
      hide_popup();
   }
   function show_properties()
   {
      var url = 'iform_exp.php?FUNCTION=12&SRCID=' + encodeURIComponent(srcid);
      $('#tabs-1').html('');
      $('#tabs-2').html('');
      $('#tabs-1').load(url);
   }
   function show_routes()
   {
      var url = 'iform_exp.php?FUNCTION=17&SRCID=' + encodeURIComponent(srcid);
      $('#tabs-1').html('');
      $('#tabs-2').html('');
      $('#tabs-2').load(url);
   }
   function process_property()
   {
      var url = 'iform_exp.php?FUNCTION=' + fprop + '&SRCID=' + encodeURIComponent(srcid) +
         '&PNAME=' + encodeURIComponent($('input[name=PNAME]').val()) +
         '&OLDPNAME=' + encodeURIComponent(pname);
      $('#askaddprop').dialog('close');
      $('#tabs-1').html('');
      $('#tabs-1').load(url);
   }
   function ask_edit_route()
   {
      $('form[name=routeForm]').find('input[name=FUNCTION]').val(52);
      $('form[name=routeForm]').find('input[name=SRCID]').val(srcid);
      $('input[name=FULLNAME]').val(fullname);
      $('#askaddroute').dialog('option', 'title', 'Edit source/route data').dialog('open');
   }
   function ask_add_route()
   {
      $('form[name=routeForm]').find('input[name=FUNCTION]').val(54);
      $('form[name=routeForm]').find('input[name=SRCID]').val('New');
      $('input[name=FULLNAME]').val('');
      $('#askaddroute').dialog('option', 'title', 'Add new source/route').dialog('open');
   }
   function ask_edit_property()
   {
      fprop=13;
      draw_add_edit_prop('Edit property', pname);
   }
   function ask_del_property()
   {
      if (!window.confirm('Realy delete record?')) {
         return;
      }

      var url = 'iform_exp.php?FUNCTION=14&SRCID=' + encodeURIComponent(srcid) +
         '&PNAME=' + encodeURIComponent(pname);
      $('#tabs-1').html('');
      $('#tabs-1').load(url);
   }
   function ask_add_property()
   {
      fprop=15;
      draw_add_edit_prop('Add new proptery', '');
   }
   function draw_add_edit_prop(title, defval)
   {
      var url = 'iform_exp.php?FUNCTION=16';
      $.get(url,
         function(data){
            $('input[name=PNAME]').val(defval).autocomplete({source: data});
            $('#askaddprop').dialog('option', 'title', title).dialog('open');
         },
         'json'
      );
   }
</script>
<?php
   $gr1  = new cXRID('grid15');

   $gr1->cols = array(
      array('Source Id', 150),
      array('Description', 250)
      );

   $query="SELECT * FROM iform_source WHERE STATIONID=? ORDER BY FULLNAME";
   $data=array($stationid);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1=array(
         myhtml($o1->SRC),
         myhtml($o1->FULLNAME)
      );
      $gr1->rows[]=$row1;
   }
   $rs->Close();

   $gr1->click = 'oclick';
   $gr1->play();

   echo "<div id=tbar2>
         <button type=button onclick =\"ask_add_route()\">".$x2->xlabel(1 /* Add new */ )."</button>
         <button type=button onclick =\"goTo(55)\">".$x2->xlabel(31 /* Levels */ )."</button>
         <img src=\"../img/vline.png\" style=\"position:relative; top:4px;\">
         <button type=button onclick =\"goTo(19)\">".$x2->xlabel(40 /* Options */ )."</button>
         <button type=button onclick =\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
         </div> ";

   $selx = array(
      array(52, '../img/button_edit.png', $x2->xlabel(15 /* Edit */ )), // was 'Prefered view'
      array(1, '../img/details.gif', $x2->xlabel(44 /* Properties */ )),
      array(60, '../img/arrow-right-icon.png', $x2->xlabel(49 /* Route */ )),
      array(53, '../img/delete.png', $x2->xlabel(12 /* Delete */ ))
      );
   draw_popup($selx);

   $selx=array(
      array(13, '../img/button_edit.png', $x2->xlabel(15 /* Edit */ ) ),
      array(14, '../img/delete.png', $x2->xlabel(12 /* Delete */ ) )
   );
   draw_popup($selx,false,'popmenu2');
}
//--------------------------------------
function show_table_size()
{
   global $x2;
   $db = &$x2->db;

   SetHeadTitle('Table size');

   if ($x2->dbt == DBType::MySql) {
      echo '<table>';
      $ar1 = array('iform_main', 'iform_prop');
      foreach ($ar1 as $t1) {
         echo "<tr>
            <td>$t1</td>
            <td>";

         $query = "SELECT COUNT(*) FROM $t1";
         if (($rs=$db->Execute($query))===false) {
            echo $db->ErrorMsg();
         }
         else {
            if (($row=$rs->FetchRow())!==false) {
               echo number_format($row[0]);
            }
            $rs->Close();
         }

         echo "</td></tr>";
      }

      echo '</table>';
   }
   else { // SQL server
      $query = "SELECT tbl.name, CAST(p.rows AS float) NREC
FROM sys.tables AS tbl
INNER JOIN sys.indexes AS idx ON idx.object_id = tbl.object_id and idx.index_id < 2
INNER JOIN sys.partitions AS p ON p.object_id=CAST(tbl.object_id AS int)
AND p.index_id=idx.index_id
WHERE ((tbl.name IN (N'iform_prop', N'iform_main')
AND SCHEMA_NAME(tbl.schema_id)='dbo'))";
      if (($rs=$db->Execute($query))===false) {
         echo $db->ErrorMsg();
      }
      else {
         echo '<table>';
         while (($row=$rs->FetchRow())!==false) {
            echo "<tr>
               <td>$row[0]</td>
               <td>".number_format($row[1])."</td>
               </tr>";
         }
         echo '</table>';
      }
   }

   echo '<div id=tbar2>
      <button type=button onclick="goTo(3)">'.$x2->xlabel(27 /* Home */ ).'</button>
      </div>';
}
//--------------------------------------
function list_HR_users()
{
   global $x2;
   $db         = &$x2->db;
   $stationid  = (int)$_SESSION['STATIONID'];
   $changepriv = $_SESSION['CHANGEPRIV'];

   SetHeadTitle('HR users');
?>
<script>
function winRet(x)
{
   goRecord(74, x);
}
</script>
<?php
   $gr1 = new cXRID('grid25');

   $gr1->cols = array(
                  array('Operator Id', 120),
                  array('Store Id', 80),
                  array('Identity', 120),
                  array('Birth date', 100),
                  array('Password reset', 140)
                  );

   $query = "SELECT USERID, STOREID, VATNO, USRDATE, ".
      FulldateFld('PASSWDRESET')." AS PASSWDRESET FROM iform_users
      WHERE STATIONID=$stationid AND USRTYPE=1";
   if (!empty($_REQUEST['RECORDID'])) {
      switch ($_REQUEST['RECORDID'])
      {
      case 1:
         $query .= " ORDER BY USERID";
         break;
      case 2:
         $query .= " ORDER BY STOREID";
         break;
      case 3:
         $query .= " ORDER BY VATNO";
         break;
      case 4:
         $query .= " ORDER BY USRDATE";
         break;
      }
   }

   if (($rs = $db->Execute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1 = $rs->FetchNextObject())
   {
      $s1 = sprintf("%08d", $o1->USRDATE);
      $row1 = array(
         myhtml($o1->USERID),
         myhtml($o1->STOREID),
         myhtml($o1->VATNO),
         substr($s1, 6, 2).'-'.substr($s1, 4,2).'-'.substr($s1,0,4),
         GrDateTime($o1->PASSWDRESET)
         );
      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->play();

   echo '<div id=tbar2>
      <button type=button onclick="show_popup(\'popmenu\');">Sort by</button>
      <button type=button onclick="goTo(3)">'.$x2->xlabel(27 /* Home */ ).'</button>
      </div>';

   $selx = array(
      array(1, '../img/go_next.gif', 'Operator Id'),
      array(2, '../img/go_next.gif', 'Store Id'),
      array(3, '../img/go_next.gif', 'Identity'),
      array(4, '../img/go_next.gif', 'Birth date'),
      );
   draw_popup($selx);
}
//--------------------------------------
function list_additional_users()
{  // Admin
   global $x2;
   $db         = &$x2->db;
   $stationid  = (int)$_SESSION['STATIONID'];
   $changepriv = $_SESSION['CHANGEPRIV'];

   SetHeadTitle(3 /* Additional users */ );

   $views = get_views_collection();
   if (!is_array($views))
      $views = array();

   $gr1 = new cXRID('grid6');

   $gr1->cols = array(
                  array('Station Id', 80),
                  array('User Id', 200),
                  array('User Type', 60),
                  array('Store Id', 100),
                  array('Prefered view', 250),
                  array('Aditional rights', 150),
                  array('Record type', 100)
                  );

   $query = "SELECT STATIONID, USERID, USRTYPE, STOREID, PREFVIEWID, CHANGEPRIV, 'Database' UTYPE FROM iform_users ";
   if ($x2->ulevel!=99) {
      $query .= " WHERE STATIONID=$stationid AND (USRTYPE IS NULL OR USRTYPE=0) AND CHANGEPRIV IN(0, 2) ";
   }
   $query .= "UNION
       SELECT DISTINCT STATIONID, LOGINUSER, '', '', 0, 0, 'Logbook' FROM iform_login t1
       LEFT JOIN iform_users t2 ON (t2.USERID=t1.LOGINUSER)
       WHERE t2.USERID IS NULL ORDER BY STATIONID, USERID ";
   if (($rs = $db->Execute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1 = $rs->FetchNextObject())
   {
      $f2 = $o1->PREFVIEWID.'#';
      foreach ($views as $ovi)
      {
         if ($ovi->VIEWID == $o1->PREFVIEWID)
         {
            $f2.= " ".$ovi->PNAME;
            break;
         }
      }

      switch ($o1->CHANGEPRIV)
      {
      case 0:
         $priv = '';
         break;
      case 1:
         $priv = 'Make any changes';
         break;
      case 2:
         $priv = 'Change users password';
         break;
      default:
         $priv = '#'.$o1->CHANGEPRIV;
      }

      $row1 = array(
         $o1->STATIONID,
         myhtml($o1->USERID),
         ($o1->USRTYPE == 1 ? 'HR' : $o1->USRTYPE),
         myhtml($o1->STOREID),
         myhtml($f2),
         $priv,
         myhtml($o1->UTYPE)
      );
      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->click = 'oclick';
   $gr1->play();
   ?>
<script>
$(function() {
     $('#askaddusr').dialog({autoOpen : false, modal : true, resizable : false});
     $('#editusrpwd').dialog({autoOpen : false, modal : true, resizable : false});
     $('#resetuploadpwd').dialog({autoOpen : false, modal : true, resizable : false});
  });
function askAddUser()
{
   $('#thestaionid').show();
   $('input[name=FUNCTION]').val(29);
   $('input[name=THEUSERID]').val('').attr('READONLY', false);
   $('#askaddusr').dialog('option', 'title', 'Add user').dialog('open');
}
var uid, storeid, prefviewid;
function oclick(stage, row, col)
{
   uid        = this.cells(row, 1).getValue();
   storeid    = this.cells(row, 2).getValue();
   prefviewid=parseInt(this.cells(row, 3).getValue());
   if (isNaN(prefviewid))
   {
      prefviewid=0;
   }
   show_popup('popmenu');
   return false;
}
function winRet(x)
{
   switch (x)
   {
   case 2:
      ask_new_upload_passwd();
      break;
   case 30: // del record
      goRecDelete(x, uid);
      break;
   case 31: // reset password
      ask_new_usr_passwd();
      break;
   case 47: // reset 'change users password' privilege
      goRecord(x, uid);
      break;
   case 32:
      ask_edit_usr();
      break;
   }
   hide_popup();
}
function ask_edit_usr()
{
   $('#thestaionid').hide();
   $('input[name=FUNCTION]').val(32);
   $('input[name=THEUSERID]').val(uid).attr('READONLY', true);
   $('input[name=STOREID]').val(storeid);
   $('input[name=PREFVIEWID]').val(prefviewid);
   $('#askaddusr').dialog('option', 'title', 'Edit user data').dialog('open');
}
function ask_new_usr_passwd()
{
   $(document.pwdForm.THEUSERID).val(uid);
   $(document.pwdForm.NEWPASSWD).val('1234');
   changePwdType(false);
   $('#editusrpwd').dialog('open');
}
function ask_new_upload_passwd()
{
   $('#THEUSERID_UP').val(uid);
   $('#NEWPASSWD_UP').val('');
   $('#resetuploadpwd').dialog('open');
   $('#msg').text('A new password will be generated');
   $('#bresetuplpwd').prop('disabled', false);
}
function changePwdType(toggle)
{
   if (toggle)
   {
      var oldType=document.pwdForm.NEWPASSWD.type;
      document.pwdForm.NEWPASSWD.type =
          oldType.toUpperCase() === 'TEXT' ? 'password' : 'text';
   }
   else
   {
      document.pwdForm.NEWPASSWD.type='password';
   }
}
</script>
<div id=askaddusr>
  <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>">
    <input type=hidden name= "FUNCTION">
    <input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
    <table>
      <?php
      if ($x2->ulevel==99) {
         echo "<tr id=thestaionid>
            <td>Station Id</td>
            <td><input type=number name= \"THESTATIONID\" MAXLENGTH = 10></td>
            </tr>";
      }
      ?>
      <tr>
        <td>User Id
        </td>
        <td>
          <input type=text name= "THEUSERID" MAXLENGTH = 128>
        </td>
      </tr>
      <tr>
        <td>Store Id
        </td>
        <td>
          <input type=text name= "STOREID" MAXLENGTH = 10>
        </td>
      </tr>
      <tr>
        <td>Prefered view
        </td>
        <td>
          <select name= PREFVIEWID>
            <?php
foreach ($views as $ovi)
{
   echo "<option value=\"$ovi->VIEWID\">$ovi->VIEWID# ".myhtml($ovi->PNAME)."</option>";
}
?>
          </select>
        </td>
      </tr>
      <tr>
        <td>
        </td>
        <td>
          <input type=submit value="<?php echo $x2->xlabel(65 /* Update */ ); ?>">
        </td>
      </tr>
    </table>
  </form>
</div>

<div id=editusrpwd title = "Reset user password">
   <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" name="pwdForm" method = POST>
   <input type=hidden name= "FUNCTION" value = "31">
   <input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
   <table>
      <tr>
         <td> User Id</td>
         <td><input type=text name= "THEUSERID" readonly></td>
      </tr>
      <tr>
         <td> New password</td>
         <td>
            <input type=password name= "NEWPASSWD"></td><td>
            <button type=button onclick = "changePwdType(true)">
               <img src="../img/eye.png"></button>
         </td>
      </tr>
      <tr>
         <td></td>
         <td>
            <input type=submit value="<?php echo $x2->xlabel(65 /* Update */ ); ?>"></td>
      </tr>
   </table>
   </form>
</div>
<?php draw_reset_upload_pwd(); ?>

<div id=tbar2> <?php
   if ($changepriv==1)
   {
      echo '<button type=button onclick="askAddUser()">'.$x2->xlabel(1 /* Add new */ )
          .'</button>';
   }

   if ($changepriv==1 || $changepriv==2)
   {
      echo ' <button type=button onclick="goTo(48)">Emails</button>
         <button type=button onclick="goTo(49)">Update History</button>
         <button type=button onclick="goTo(50)">Email sent</button>';
   }
   ?>
   <button type=button onclick = "goTo(3)"> <?php echo $x2->xlabel(27 /* Home */ ); ?> </button>
</div>
<?php
   if ($changepriv==1)
   {
      $selx = array(array(32, '../img/button_edit.png', 'Edit user data'), // was 'Prefered view'
                 array(47, '../img/users.png', 'Change password privilege'),
                 array(31, '../img/key16x16.png', 'Reset user password'),
                 array(2, '../img/key16x16.png', 'Reset upload password'),
                 array(30, '../img/delete.png', $x2->xlabel(12 /* Delete */ )));
      draw_popup($selx);
   }
   else if ($changepriv==2) {
      $selx = array(array(31, '../img/key16x16.png', 'Reset password'));
      draw_popup($selx);
   }
}
//--------------------------------------
function list_issue_customers()
{
   global $x2;
   $db        = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   SetHeadTitle(92); // 'Customers per issuer VAT no.'

   $afms = array();
   $recs = array();

   $query = "SELECT DISTINCT PVALUE FROM iform_prop_cnt
      WHERE STATIONID=$stationid AND PNAME='".STAT_PROPERTY."'
      ORDER BY PVALUE";
   if (($rs = $db->cacheExecute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($row=$rs->FetchRow())
   {
      $afms[] = $row[0];
   }
   $rs->Close();

   $now = time();
   $dateFrom  = date('Y-m', $now).'-01 00:00:00';
   $dateTo = date('Y-m-t', $now).' 23:59:59';
   $query = "SELECT PVALUE, COUNT(DISTINCT CUSTOMERID) F2 FROM iform_main T1
       LEFT JOIN iform_prop T2 ON (T2.STATIONID=T1.STATIONID AND T2.SEQNO = T1.SEQNO AND T2.SUBSEQ = 0
       AND PNAME= ? )
       WHERE T1.STATIONID=$stationid AND CREDAYTIME >= ? AND CREDAYTIME <= ?
       GROUP BY PVALUE
       ORDER BY PVALUE";
   $data=array(STAT_PROPERTY, $dateFrom, $dateTo);
   if (($rs = $db->cacheExecute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1 = $rs->FetchNextObject())
   {
      $recs[$o1->PVALUE] = $o1->F2;
   }
   $rs->Close();

   foreach ($afms as $afm1)
   {
      if (!array_key_exists($afm1, $recs))
      {
         $recs[$afm1] = 0;
      }
   }
   ksort($recs);

   $gr1 = new cXRID('grid5');

   $gr1->cols = array(array($x2->xlabel(69 /* Year-month */ ), 100));
   foreach ($afms as $afm1)
   {
      $gr1->cols[] = array(STAT_PROPERTY.': '.$afm1, 120, 'right');
   }
   $gr1->cols[] = array('Total Customers', 100, 'right');

   $row1 = array( date('Y-m', $now) );
   $total = 0;
   foreach ($recs as $afm1=>$val)
   {
      $row1[] = $val;
      $total += $val;
   }
   $row1[] = $total;
   $gr1->rows[] = $row1;

   $year = (int)date('Y', $now);
   $mon = (int)date('m', $now);
   for ($i=0;$i<12;$i++)
   {
      $mon -= 1;
      if ($mon<1)
      {
         $mon = 12;
         $year -= 1;
      }
      $row1 = array( sprintf('...%04d-%02d', $year, $mon) );
      $gr1->rows[] = $row1;
   }

   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick =\"goTo(21)\">".$x2->xlabel(89 /* Dates */ )."</button>
      <button type=button onclick =\"goTo(21)\">".$x2->xlabel(14 /* Documents */ )."</button>
      <button type=button style =\"font-weight:bold\">".$x2->xlabel(10 /* Customers */ )."</button>
      <button type=button onclick =\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
      </div> ";
?>
<script>
var ym, v2, url, k1, nk, kc;
var afms = [
   <?php
      foreach ($afms as $afm1)
      {
         echo "'$afm1',";
      }
      echo false;
   ?>
];
$(function() {
   var nr = grid5.getRowsNum();
   var nc = grid5.getColumnsNum();
   var nafm = afms.length;
   for (var i=1;i<nr;i++)
   {
      ym = grid5.cellByIndex(i,0).getValue();
      if (ym.substring(0,3)==='...')
      {
         v2 = ym.substring(3);
         var url  = 'iform_json.php?FUNCTION=4&YMON=' + encodeURIComponent(v2);
         try
         {
            $.get(url,
               function(ret) {
                  if (ret.error.length > 0) {
                     alert(ret.error);
                  }
                  else {
                     kc = '...'+ ret.rows[0];
                     // find row
                     for (var i2=1;i2<nr;i2++)
                     {
                        if (grid5.cellByIndex(i2,0).getValue() === kc)
                        {
                           grid5.cellByIndex(i2,0).setValue(ret.rows[0]);
                           nk = ret.rows.length;
                           for (k1=1;k1<nk;k1++)
                           {
                              for (var j=0;j<nafm;j++)
                              {
                                 if (afms[j] === ret.rows[k1].PVALUE)
                                 {
                                    grid5.cellByIndex(i2, j+1).setValue(ret.rows[k1].F2);
                                    break;
                                 }
                              }

                              if (ret.rows[k1].PVALUE === 'TOTAL')
                              {
                                 grid5.cellByIndex(i2, nc-1).setValue(ret.rows[k1].F2);
                              }
                           }
                           break;
                        }
                     }
                  }

               },
               'json');
         }
         catch (e1)
         {
            alert(e1.message)               ;
         }

      }
   }
});
</script>
<?php
}
//--------------------------------------
function list_issuer_stats()
{
   global $x2;
   $db = &$x2->db;
   $stationid = (int)$_SESSION['STATIONID'];

   $searchFrom = (int)@$_REQUEST['RECORDID'];
   $ar1 = explode('-', date('Y-m-d', $searchFrom)); // yyyy-mm-dd
   $searchTo = mktime(0,0,0, (int)$ar1[1]+1, 0, (int)$ar1[0]); // last day of month
   if ($searchTo === false) {
      uerror("Failed to calculate search time!");
      return;
   }

   $gr1 = new cXRID('grid27');

   $results=array();
   $afms = array();
   $query = "SELECT T1.CREDATE, T2.PVALUE, COUNT(*) N1 FROM iform_main T1 ".
      " LEFT JOIN iform_prop T2 ON (T2.STATIONID=T1.STATIONID AND T2.SEQNO=T1.SEQNO AND T2.PNAME='ΑΦΜ Εκδότη') ".
      " WHERE T1.STATIONID=$stationid AND T1.CREDATE >= ? AND T1.CREDATE <= ?".
      " GROUP BY T1.CREDATE, T2.PVALUE ORDER BY T1.CREDATE DESC, T2.PVALUE";
   $data = array( date('Y-m-d', $searchFrom), date('Y-m-d', $searchTo) );
   if (($rs = $db->cacheExecute($query, $data)) === false)
   {               echo $db->ErrorMsg();
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      if (!array_key_exists($o1->CREDATE, $results)) { $results[$o1->CREDATE] = array(); }
      $results[$o1->CREDATE][$o1->PVALUE] = $o1->N1;
      if (!in_array($o1->PVALUE, $afms)) { $afms[] = $o1->PVALUE; }
   }
   $rs->Close();

   sort($afms);
   $n1 = count($afms);
   //pre($results);

   $gr1->cols = array(
      array("Creation date", 110)
   );
   foreach ($afms as $afm1) {
      $gr1->cols[] = array($afm1, 100, 'right');
   }
   $gr1->cols[] = array("Total", 100, 'right');

   $gt = array_fill(0, $n1+1, 0);
   foreach ($results as $date1=>$data)
   {
      $horzT = 0;
      $row1 = array_fill(0, $n1+2, '');
      $row1[0] = $date1;
      foreach ($data as $afm1=>$val)
      {
         if (($i = array_search($afm1, $afms))!==false) {
            $row1[$i+1] = $val;
            $gt[$i] += $val;
            $gt[$n1] += $val;
            $horzT += $val;
         }
      }
      $row1[$n1+1] = $horzT;
      $gr1->rows[] = $row1;
   }

   $row1 = array('Total');
   for ($i=0;$i<=$n1;$i++) {
      $row1[] = $gt[$i];
   }
   $row1[] = '';
   $gr1->rows[] = $row1;

   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick=\"goRecord(21, $searchFrom)\">Group</button>
      <button type=button onclick=\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
      </div> ";
}
//--------------------------------------
function list_all_stats()
{
   global $x2;
   $db = &$x2->db;
   $stationid = (int)$_SESSION['STATIONID'];

   SetHeadTitle(60 /* Statistics */ );

   if (!empty($_REQUEST['RECORDID']))
   {
      $searchFrom = (int)@$_REQUEST['RECORDID'];
      $ar1 = explode('-', date('Y-m-d', $searchFrom)); // yyyy-mm-dd
      $searchTo = mktime(0,0,0, (int)$ar1[1]+1, 0, (int)$ar1[0]); // last day of month
      if ($searchTo === false) {
         uerror("Failed to calculate search time!");
         return;
      }
   }
   else
   {
      $query = "SELECT MAX(CREDATE) FROM iform_main WHERE STATIONID=$stationid";
      if (($rs = $db->cacheExecute($query)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
         return;
      }
      $row = $rs->FetchRow();
      $rs->Close();
      if ($row===NULL || $row[0]==NULL) {
         uerror("No data exists!");
         return;
      }

      $ar1 = explode('-', $row[0]); // yyyy-mm-dd
      $searchFrom = mktime(0,0,0, (int)$ar1[1], 1, (int)$ar1[0]); // 1st day of month
      $searchTo = mktime(0,0,0, (int)$ar1[1]+1, 0, (int)$ar1[0]); // last day of month
      if ($searchFrom === false || $searchTo === false) {
         uerror("Failed to calculate search time!");
         return;
      }
   }
   $previousFrom = mktime(0,0,0, (int)$ar1[1]-1, 1, (int)$ar1[0]); // 1st day of previous month
   $nextFrom = mktime(0,0,0, (int)$ar1[1]+1, 1, (int)$ar1[0]); // 1st day of next month

   echo '<div style="background-color:#e0e0e0; font-weight:bold; padding:0.5em;">'.date('m-Y', $searchFrom).'</div>';

   $gr1 = new cXRID('grid11');

   $gr1->cols = array(
      array("Creation date", 110),
      array("All", 100, 'right')
   );

   $gt = 0;
   $query = "SELECT CREDATE, COUNT(*) N1 FROM iform_main ".
      " WHERE STATIONID=$stationid AND CREDATE >= ? AND CREDATE <= ?".
      " GROUP BY CREDATE ORDER BY CREDATE DESC";
   $data = array( date('Y-m-d', $searchFrom), date('Y-m-d', $searchTo) );
   if (($rs = $db->cacheExecute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   // Parse once to collect SRC
   while ($o1 = $rs->FetchNextObject())
   {
      $row1 = array($o1->CREDATE, $o1->N1);
      $gr1->rows[] = $row1;

      $gt += $o1->N1;
   }
   $gr1->rows[] = array('Total', $gt);

   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick=\"goRecord(21, $previousFrom)\">Previous month</button>
      <button type=button ";
   if ($nextFrom<time())
      echo " onclick=\"goRecord(21, $nextFrom)\"";
   else
      echo " disabled";
   echo ">Next month</button>
      <button type=button onclick=\"goRecord(81, $searchFrom)\">Issuer analysis</button>
      <button type=button onclick=\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
      </div> ";
}
//--------------------------------------
function list_src_stats_OLD()
{
   global $x2;
   $db        = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   SetHeadTitle(60 /* Statistics */ );

   $src   = array();
   $query = "SELECT DISTINCT SRC FROM iform_main WHERE STATIONID=$stationid ORDER BY SRC";
   if (($rs = $db->cacheExecute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($row = $rs->FetchRow())
   {
      if (!is_null($row[0]))
      {
         $src[] = $row[0];
      }
   }
   $rs->Close();

   $query = "SELECT ".DateFld('m.CREDAYTIME').", COUNT(*)";
   foreach ($src as $k => $v)
   {
      $query .= ", COUNT(t$k.SEQNO) ";
   }
   $query .= " FROM iform_main m ";
   foreach ($src as $k => $v)
   {
      $query.= " LEFT JOIN iform_main t$k ON (t$k.STATIONID=m.STATIONID AND t$k.SEQNO=m.SEQNO
         AND t$k.SRC=".$db->quote($v).") ";
   }
   $query .= " WHERE m.STATIONID=$stationid
      GROUP BY ".DateFld('m.CREDAYTIME')." ORDER BY ".DateFld('m.CREDAYTIME')." DESC ";

   $gr1 = new cXRID('grid11');

   $gr1->cols = array(
      array("Creation date", 110),
      array("All", 100)
   );
   foreach ($src as $v)
   {
      $gr1->cols[] = array($v, 100);
   }

   if (($rs = $db->cacheExecute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($row = $rs->FetchRow())
   {
      $gr1->rows[] = $row;
   }
   $rs->Close();

   $gr1->play();

   echo "<div id=tbar2>
      <button type=button style =\"font-weight:bold\">".$x2->xlabel(89 /* Dates */ )."</button>
      <button type=button onclick =\"goTo(44)\">".$x2->xlabel(14 /* Documents */ )."</button>
      <button type=button onclick =\"goTo(22)\">".$x2->xlabel(10 /* Customers */ )."</button>
      <button type=button onclick =\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
      </div> ";
}
//--------------------------------------
function list_email_sent()
{
   global $x2;
   $db  = &$x2->db;
   $gr1 = new cXRID('grid14');

   $pg   = getPage();
   $pgsz = getPageSize('grid14');

   $query = "SELECT * FROM iform_srv_emlog WHERE STATIONID=? ORDER BY CREDAYTIME DESC";
   $data = array($_SESSION['STATIONID']);
   if (($rs = $db->PageExecute($query, $pgsz, $pg, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1 = array();

      $row1[] = GrDateTime(strtr($o1->CREDAYTIME, 'TZ', '  '));
      $row1[] = $o1->SENTOK;
      $row1[] = $o1->SEQNO;
      $row1[] = myhtml($o1->EMAIL);

      $gr1->rows[] = $row1;
   }
   $epage = $rs->LastPageNo();
   $rs->Close();

   $gr1->cols=array(
      array('Date/time', 150),
      array('Sent OK', 60),
      array('Sequence no.', 100),
      array('Email', 200)
      );
   $gr1->play();

   echo "<div id=tbar2>";
   print_page_navEx($pg, $epage, 50);
   echo "<button type=button onclick =\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
      </div> ";
}
//--------------------------------------
function list_change_history()
{
   global $x2;
   $db  = &$x2->db;
   $gr1 = new cXRID('grid13');

   $pg   = getPage();
   $pgsz = getPageSize('grid13');

   $query = "SELECT * FROM iform_changelog WHERE STATIONID=? ORDER BY LOGID DESC";
   $data = array($_SESSION['STATIONID']);
   if (($rs = $db->PageExecute($query, $pgsz, $pg, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1 = array();

      $row1[] = $o1->LOGID;
      $row1[] = $o1->SEQNO;
      $row1[] = $o1->ACTION==1?'Add signature':'Remove signature';
      $row1[] = myhtml($o1->USERID);
      $row1[] = $o1->ACTIONDATE;

      $gr1->rows[] = $row1;
   }
   $epage = $rs->LastPageNo();
   $rs->Close();

   $gr1->cols=array(
      array('Log Id', 100),
      array('Seqno', 100),
      array('Action', 100),
      array('User Id', 120),
      array('Date/time', 150)
      );
   $gr1->play();

   echo "<div id=tbar2>";
   print_page_navEx($pg, $epage, 49);
   echo "<button type=button onclick =\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
      </div> ";
}
//--------------------------------------
function list_srv_emails()
{
   global $x2;
   $db  = &$x2->db;
   $gr1 = new cXRID('grid12');

   SetHeadTitle('AFM/Emails');

   $query = "SELECT AFM, EMAIL FROM iform_srv_email WHERE STATIONID=?";
   $data = array($_SESSION['STATIONID']);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1 = array(myhtml($o1->AFM), myhtml($o1->EMAIL));
      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->cols=array(
      array('AFM', 150),
      array('Email', 300),
      );
   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick =\"goTo(63)\">".$x2->xlabel(87 /* Pending */ )."</button>
      <button type=button onclick =\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
      </div> ";
}
//--------------------------------------
function show_pending_emails()
{
   global $x2;

   if (substr(PHP_OS,0,3)==="WIN") {
      if (($shell = new COM("WScript.Shell"))===false) {
         uerror("Requires Windows Scripting Host");
         return;
      }
      $sedir = $shell->RegRead('HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\INCA Hellas\\iForm\\EmailSendFolder');
   }
   if (empty($sedir)) {
      uerror("EmailSendFolder not set");
      return;
   }

   if (!is_dir($sedir)) {
      uerror("Folder ".myhtml($sedir)." does not exist");
      return;
   }

   $gr1 = new cXRID('grid17');
   $gr1->cols = array(
      array('Filename', 300),
      array('Email(s)', 200)
      );

   $files = glob("$sedir\\*.snd");
   foreach ($files as $f1) {
      if (!is_file($f1))
         continue;

      $row1 = array($f1, '');
      if (($s1=file_get_contents($f1))!==false) {
         $row1[1] = myhtml($s1);
      }

      $gr1->rows[] = $row1;
   }

   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick =\"goTo(48)\">Emails</button>
      <button type=button onclick =\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
      </div> ";
}
//--------------------------------------
function list_issue_docs()
{
   global $x2;
   $db        = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   SetHeadTitle(91); // 'Documents per issuer VAT no.'

   $ar1 = array();
   $ar2 = array();
   $rec = array();

   $nc = 0;
   $query = "SELECT SUM(PCOUNT) FROM iform_prop_cnt WHERE STATIONID=$stationid AND PNAME='".STAT_PROPERTY."' ";
   if (($rs = $db->cacheExecute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   if (($row = $rs->FetchRow()) !== false)
   {
      $nc = $row[0];
   }
   $rs->Close();

   switch ($db->databaseType)
   {
   case 'mysqlt':
   case 'mysqli':
      if ($nc > 0)
      {
         $query = "SELECT EXTRACT(YEAR_MONTH FROM T1.CREDAYTIME) F1, PVALUE, COUNT(*) F2 FROM iform_main T1
            LEFT JOIN iform_prop T2 ON(T2.STATIONID=T1.STATIONID AND T2.SEQNO = T1.SEQNO AND T2.SUBSEQ = T1.SUBSEQ)
            WHERE T1.STATIONID=$stationid AND PNAME= '".STAT_PROPERTY."' GROUP BY F1, PVALUE ";
      }
      else
      {
         $query = "SELECT EXTRACT(YEAR_MONTH FROM T1.CREDAYTIME) F1, 'ANY' PVALUE, COUNT(*) F2 FROM iform_main T1
            WHERE T1.STATIONID=$stationid GROUP BY F1 ";
      }
      break;
   default:
      if ($nc > 0)
      {
         $query = "SELECT DATEPART(yyyy,T1.CREDAYTIME)*100 + DATEPART(mm,T1.CREDAYTIME) F1, PVALUE, COUNT(*) F2 FROM iform_main T1
            LEFT JOIN iform_prop T2 ON(T2.STATIONID=T1.STATIONID AND T2.SEQNO = T1.SEQNO AND T2.SUBSEQ = T1.SUBSEQ)
            WHERE T1.STATIONID=$stationid AND PNAME= '".STAT_PROPERTY."'
            GROUP BY DATEPART(yyyy, T1.CREDAYTIME) * 100 + DATEPART(mm, T1.CREDAYTIME), PVALUE ";
      }
      else
      {
         $query = "SELECT DATEPART(yyyy,T1.CREDAYTIME)*100 + DATEPART(mm,T1.CREDAYTIME) F1, 'ANY' PVALUE, COUNT(*) F2 FROM iform_main T1
            WHERE T1.STATIONID=$stationid
            GROUP BY DATEPART(yyyy, T1.CREDAYTIME) * 100 + DATEPART(mm, T1.CREDAYTIME) ";
      }
      break;
   }
   if (($rs = $db->cacheExecute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1 = $rs->FetchNextObject())
   {
      if (!in_array($o1->F1, $ar1))
         $ar1[] = $o1->F1;

      if (!in_array($o1->PVALUE, $ar2))
         $ar2[] = $o1->PVALUE;

      $rec[] = $o1;
   }
   $rs->Close();

   rsort($ar1); // dates, descending
   sort($ar2); // VAT
   $n2 = count($ar2);

   $gr1 = new cXRID('grid4');

   $gr1->cols = array(array($x2->xlabel(90 /* Creation Year-month */ ), 100));
   foreach ($ar2 as $vat)
   {
      $gr1->cols[] = array(STAT_PROPERTY.': '.$vat, 120, 'right');
   }
   $gr1->cols[] = array('Total Docs.', 100, 'right');

   foreach ($ar1 as $ymon)
   {
      $row1    = array_fill(0, $n2 + 2, '');
      $row1[0] = substr($ymon, 0, 4).'-'.substr($ymon, 4);
      $total   = 0;

      foreach ($rec as $o1)
      {
         if ($o1->F1 == $ymon)
         {
            $k            = array_search($o1->PVALUE, $ar2);
            $row1[$k + 1] = $o1->F2;
            $total += $o1->F2;
         }
      }

      $row1[$n2 + 1] = $total;

      $gr1->rows[] = $row1;
   }

   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick =\"goTo(21)\">".$x2->xlabel(89 /* Dates */ )."</button>
      <button type=button style =\"font-weight:bold\">".$x2->xlabel(14 /* Documents */ )."</button>
      <button type=button onclick =\"goTo(22)\">".$x2->xlabel(10 /* Customers */ )."</button>
      <button type=button onclick =\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
      </div> ";
}
//--------------------------------------
function show_setup()
{
   global $x2, $ADODB_CACHE_DIR;

   SetHeadTitle('System setup');

   echo '<table>
      <tr>
         <td>ADO db cache folder</td>
         <td>'.myhtml($ADODB_CACHE_DIR).'</td>
      </tr>
      <tr>
         <td>Cloud repository</td>
         <td>'.myhtml(G_CLOUD_REPOSITORY).'</td>
      </tr>
      <tr>
         <td>Stat.property</td>
         <td>'.myhtml(STAT_PROPERTY).'</td>
      </tr>
      <tr>
         <td>Defined Temp.folder</td>
         <td>'.myhtml(I_TEMPDIR).'</td>
      </tr>
      </table>';
}
//--------------------------------------
function list_views()
{
   global $x2;
   $db = &$x2->db;

   SetHeadTitle(68 /* Views */ );
?>
<script>
var viewid;
function oclick(stage, row, col)
{
   viewid=this.cells(row, 0).getValue();
   show_popup('popmenu');
   return false;
}
function winRet(x)
{
   switch (x)
   {
   case 14: // copy record
   case 16: // edit record (data)
   case 18: // add/remove preference
   case 78: // reset 'ask for signed'
      goRecord(x, viewid);
      break;
   case 17: // del record
      goRecDelete(17, viewid);
      break;
   }
}
</script>
<?php
   $gr1 = new cXRID('grid3');

   $query = 'SELECT T1.USERID, T1.VIEWID, T1.PNAME, T1.PLABEL, T2.PREFVIEWID FROM iform_views T1 '.
      ' LEFT JOIN iform_users T2 ON (T2.USERID=T1.USERID) '.
      ' WHERE T1.FIELDSEQ=0';
   if ($x2->ulevel!=99) {
      $query .= ' AND T1.USERID=?';
      $data = array($_SESSION['USERID']);
   }
   else {
      $data = false;
   }
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return goNext(3);
   }
   while ($o1 = $rs->FetchNextObject())
   {
      $row1 = array($o1->VIEWID, myhtml($o1->PNAME));
      $row1[] = ($o1->VIEWID == $o1->PREFVIEWID ? 'Preferred' : '');
      $row1[] = (strlen($o1->PLABEL)>0 && $o1->PLABEL[0]==1 ? 'YES' : '');
      $row1[] = myhtml($o1->USERID);
      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->cols = array(
      array('Id', 50),
      array($x2->xlabel(67 /* View name */ ), 200),
      array('Preferred', 100),
      array('Ask for signed', 100),
      array('User Id', 150)
   );

   $gr1->click = 'oclick';
   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick =\"goTo(14)\">".$x2->xlabel(1 /* Add new */ )."</button>
      <button type=button onclick =\"goTo(24)\">".$x2->xlabel(17 /* Fields */ )."</button>
      <button type=button onclick =\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
      </div> ";

   $selx = array(
      array(16, '../img/button_edit.png', $x2->xlabel(16 /* Edit data */ )),
      array(18, '../img/to_top.png', $x2->xlabel(21 /* First in preference OR no pref. */ )),
      array(78, '../img/checkmark.gif', 'Ask for signed'),
      array(14, '../img/copy.gif', 'Make a copy'),
      array(17, '../img/delete.png', $x2->xlabel(12 /* Delete */ ))
      );
   draw_popup($selx);
}
//--------------------------------------
function list_pending_docs()
{
   global $x2;
   $db        = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   SetHeadTitle(42 /* Pending documents */ );

   $gr1 = new cXRID('grid18');

   $query="SELECT rp.RID, rp.SEQNO, rp.USERID, rp.DOCLOCKED, ".FulldateFld('m.CREDAYTIME')." AS CREDAY, sr.FULLNAME
      FROM iform_route_proc rp
      LEFT JOIN iform_main m ON (m.STATIONID=rp.STATIONID AND m.SEQNO=rp.SEQNO)
      LEFT JOIN iform_source sr ON (sr.STATIONID=m.STATIONID AND sr.SRC=m.SRC)
      WHERE rp.STATIONID=$stationid AND rp.CLEVELID IS NULL AND rp.DRELEASED IS NULL
      ORDER BY rp.RID";
   if (($rs=$db->Execute($query))===false) {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1=$rs->FetchNextObject()) {
      $row1=array(
         $o1->SEQNO,
         myhtml($o1->USERID),
         $o1->CREDAY,
         myhtml($o1->FULLNAME),
         is_null($o1->DOCLOCKED)?'':'Locked'
      );

      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->cols=array(
      array('Σειριακός', 100),
      array('Χρήστης', 100),
      array('Δημιουργία', 140),
      array('Πηγή', 200),
      array('Κατάσταση', 100)
   );

   $gr1->play();
   echo "<div id=tbar2>
      <button type=button onclick =\"goTo(3)\">".$x2->xlabel(27 /* Home */ )."</button>
      </div>";
}
//--------------------------------------
function report_view()
{
   global $x2;
   $db = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   SetHeadTitle('View Report');

   $viewID = (int)$_REQUEST['VIEWID'];
   $viewname= '';
   //$fields = array();

   $qo = new cQUERY();
   $stdFields = $qo->GetStdFields();

   $gr1  = new cXRID('grid26');

   $gr1->cols=array(
      array('Sequence', 50),
      array('Filter', 50),
      array('Property', 150),
      array('Label', 200),
      array('STD', 100)
   );

   $query = 'SELECT FIELDSEQ, QUERYPREF, PNAME, PLABEL FROM iform_views
         WHERE VIEWID=? ORDER BY FIELDSEQ';
   $data=array($viewID);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return goNext(3);
   }
   while ($o1 = $rs->FetchNextObject())
   {
      if ($o1->FIELDSEQ == 0)
      { // special case: name of view
         $viewname = $o1->PNAME;
      }
      else
      {
         $o1->STD  = in_array($o1->PNAME, $stdFields);
         $row1=array(
            $o1->FIELDSEQ,
            $o1->QUERYPREF>0?'Filter':'',
            myhtml($o1->PNAME),
            myhtml(empty($o1->PLABEL) ? $o1->PNAME : $o1->PLABEL),
            $o1->STD?'STD':''
         );
         $gr1->rows[] = $row1;
      }
   }
   $rs->Close();

   $gr1->play();
   echo "<div id=tbar2><small>End of data</small>
      <button type=button onclick=\"goRecord(16. $viewID)\">Edit</button>
      <button type=button onclick=\"goTo(13)\">".$x2->xlabel(7 /* Cancel */ )."</button>
      </div>";
}
//--------------------------------------
function ask_edit_view($viewID)
{
   global $x2;
   $db = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   SetHeadTitle(16 /* Edit data */ );

   $qo = new cQUERY();
   $stdFields = $qo->GetStdFields();

   $viewname= '';
   $fields = array();

   // user fields (if exist)
   if ($viewID >= 0 || ((int)@$_REQUEST['RECORDID'])>0)
   {
      $vid = $viewID >= 0 ? $viewID : (int)@$_REQUEST['RECORDID'];
      $query = "SELECT FIELDSEQ, QUERYPREF, PNAME, PLABEL FROM iform_views
         WHERE VIEWID=? ORDER BY FIELDSEQ";
      $data = array($vid);
      if (($rs = $db->Execute($query, $data)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
         return goNext(3);
      }
      while ($o1 = $rs->FetchNextObject())
      {
         if ($o1->FIELDSEQ == 0)
         { // special case: name of view
            $viewname = $o1->PNAME;
            if ($viewID<0) {
               $viewname .= ' (αντίγραφο)';
            }
         }
         else
         {
            $o1->STD  = in_array($o1->PNAME, $qo->stdFields);
            $fields[$o1->PNAME] = $o1; // fields are indexed by FIELDSEQ
         }
      }
      $rs->Close();
   }

   // add more fields (predefined standard)
   foreach ($qo->stdFields as $plabel => $fsql)
   {
      if (array_key_exists($fsql, $fields)) {
         $fields[$fsql]->STD = true;
      }
      else
      {
         $fields[$fsql] = (object)array('PNAME' => $fsql, 'PLABEL' => $plabel,
                        'FIELDSEQ' => 0, 'QUERYPREF' => 0, 'STD' => true);
      }
   }

   // add more fields (indexed properties)
   $query = 'SELECT DISTINCT PNAME FROM iform_pname ';
   if ($x2->ulevel != 99) {
      $query .= ' WHERE STATIONID=? ';
      $data = array($stationid);
   }
   else {
      $data = false;
   }
   $query .= ' ORDER BY PNAME';
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return goNext(3);
   }
   while ($o1 = $rs->FetchNextObject())
   {
      if (!array_key_exists($o1->PNAME, $fields))
      {
         $o1->FIELDSEQ  = 0; // add property
         $o1->QUERYPREF = 0;
         $o1->PLABEL    ='';
         $o1->STD       = false;
         $fields[$o1->PNAME]      = $o1;
      }
   }
   $rs->Close();
?>
   <b> <?php echo $x2->xlabel(38 /* New view */ ); ?></b>
   <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method =
        POST name= "goForm">
      <input type=hidden name= "FUNCTION" value = "15">
      <input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
      <input type=hidden name= "VIEWID" value = "<?php echo $viewID; ?>">

      <fieldset>
      <legend> <?php echo $x2->xlabel(67 /* View name */ ); ?> </legend>
         <table>
         <tr>
            <td>Name</td>
            <td><input type=text name="VIEWNAME" value="<?php echo myhtml($viewname); ?>" style = "width:400px"></td>
         </tr>
         <?php
         if ($x2->ulevel==99 && $viewID<0)
         {
            echo '<tr>
               <td>For user</td>
               <td><input type=text name="FORUSER"></td>
               </tr>';
         }
         ?>
         </table>

      </fieldset>

      <fieldset>
      <legend> <?php echo $x2->xlabel(17 /* Fields */ ); ?> </legend>
         <ul id="fields"><?php
         $i = 1;
         foreach ($fields as $o1)
         {
            echo "<li id=i$i class=\"ui-state-default\"><span class=\"ui-icon ui-icon-arrowthick-2-n-s\"></span><label
                title =\"Include in view fields\">V <input id=V$i class=VFcheckbox type=checkbox";
            if ($o1->FIELDSEQ > 0)
            {
               echo " checked";
            }
            echo "></label>
                <label title =\"Precede in filters\">F <input id=F$i type=checkbox";
            if ($o1->FIELDSEQ == 0)
            {
               echo " disabled";
            }
            else if ($o1->QUERYPREF > 0)
            {
               echo " checked";
            }
            echo "></label>
               <label class=f10 for=F$i>".myhtml($o1->PNAME)."</label> <input type=text id=L$i value=\"".myhtml($o1->PLABEL)."\" maxlength=200>";
            if ($o1->STD)
            {
                   echo " Std";
            }
            echo "</li>\n";
            $i++;
         }
         ?></ul>
      </fieldset>

      <input type=button value="<?php echo $x2->xlabel(106 /* New field */ ); ?>" onclick = "AskNewField()">
      <input type=button value="<?php echo $x2->xlabel(65 /* Update */ ); ?>" onclick = "UpdateView()">
      <input type=button value="Report" onclick="goViewReport()">
      <input type=button value ="<?php echo $x2->xlabel(7 /* Cancel */ ); ?>" onclick = "goTo(13)">
   </form>
<script>
$('.VFcheckbox').change(function() {
   var i  = $(this).prop('id').substr(1);
   var i2 = '#F' + i;
   if ($(this).is(':checked'))
   {
      $(i2).prop("disabled", false);
   }
   else
   {
      $(i2).attr('checked', false).prop("disabled", true);
   }
});

function AskNewField()
{
   var nfi = window.prompt('New field name', '');
   if (!nfi || nfi == '')
      return;

   var i = <?php echo $i; ?>;
   var html = '<li id=i' + i + ' class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' +
      '<label title ="Include in view fields">V <input id=V' + i + ' class=VFcheckbox type=checkbox></label>' +
      '<label title ="Precede in filters">F <input id=F' + i + ' type=checkbox></label>' +
      ' <label class=f10 for=F' + i +'>' + escape_HTML(nfi) + '</label> <input type=text id=L' + i + ' maxlength=200>' +
      '</li>';
   $('#fields').append(html);
}

function UpdateView()
{
   var o2;
   var g   = GetGoForm();
   var ar1 = $("#fields").sortable('toArray');
   for (var p in ar1)
   {
      if ($('#' + ar1[p]).find('input').first().is(':checked'))
      {
         o2       = document.createElement('input');
         o2.type  = 'hidden';
         o2.name  = 'PNAME[]';
         o2.value = $('#' + ar1[p]).find('label').eq(2).text().trim();
         g.appendChild(o2);

         o2       = document.createElement('input');
         o2.type  = 'hidden';
         o2.name  = 'QUERYPREF[]';
         o2.value = $('#' + ar1[p]).find('input').eq(1).is(':checked')
                        ? 1
                        : 0; // eq(): Reduce the set of matched elements to
                             // the one at the specified index
         g.appendChild(o2);

         o2      = document.createElement('input');
         o2.type='hidden';
         o2.name= 'PLABEL[]';
         o2.value =
             $('#' + ar1[p]).find('input').eq(2).val().trim(); // eq():
                                                               // Reduce the
                                                               // set of
                                                               // matched
                                                               // elements to
                                                               // the one at
                                                               // the
                                                               // specified
                                                               // index
         g.appendChild(o2);
      }
   }
   g.submit();
}

function goViewReport()
{
   followMe( {FUNCTION:80, VIEWID:$('input[name=VIEWID]').val() } );
}
</script>
<?php
}
//--------------------------------------
function set_pref_view()
{
   global $x2;
   $db = &$x2->db;

   $prefviewid=0;
   $query      = "SELECT PREFVIEWID FROM iform_users WHERE USERID=?";
   $data       = array($_SESSION['USERID']);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   if (($row = $rs->FetchRow()) !== false)
   {
      $prefviewid=$row[0];
   }
   $rs->Close();

   if ($prefviewid == $_REQUEST['RECORDID'])
   { // already prefred, clearit
      $newid=0;
   }
   else
   {
      $newid=(int)$_REQUEST['RECORDID'];
   }

   $query = "UPDATE iform_users SET PREFVIEWID=$newid WHERE USERID=?";
   $data  = array($_SESSION['USERID']);
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
   }
}
//--------------------------------------
function reset_ask_signed()
{
   global $x2;
   $db = &$x2->db;

   $viewID=(int)$_REQUEST['RECORDID'];

   $query = "SELECT PLABEL FROM iform_views WHERE VIEWID=? AND FIELDSEQ=0 AND USERID=?"; // use USERID for security"
   $data = array($viewID, $_SESSION['USERID']);
   if (($rs=$db->Execute($query, $data))===false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   $o1 = $rs->FetchNextObject();
   $rs->Close();
   if ($o1===false)
   {
      uerror( 'Master record disappeared!');
      return;
   }

   $askForSigned = !(strlen($o1->PLABEL)>0 && $o1->PLABEL[0] == 1); // set and reverse
   $newval = ($askForSigned?'1':'0').mb_substr($o1->PLABEL, 1);
   $query = "UPDATE iform_views SET PLABEL=? WHERE VIEWID=? AND FIELDSEQ=0 AND USERID=?"; // use USERID for security"
   $data = array($newval, $viewID, $_SESSION['USERID']);
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
   }
}
//--------------------------------------
function delete_view()
{
   global $x2;
   $db = &$x2->db;

   $viewID=(int)$_REQUEST['RECORDID'];

   $query = "DELETE FROM iform_views WHERE VIEWID=? AND USERID=?"; // use USERID for security
   $data = array($viewID, $_SESSION['USERID']);
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
   }
}
//--------------------------------------
function cre_or_update_view()
{
   global $x2;
   $db = &$x2->db;

   $viewID=$_REQUEST['VIEWID'];
   $plabel = '';

   if ($viewID >= 0) // update existing view
   {
      $userid = $_SESSION['USERID']; // default
      // save PLABEL (flags)
      $query = "SELECT USERID, PLABEL FROM iform_views WHERE VIEWID=? AND FIELDSEQ=0"; // use USERID for security
      $data = array($viewID);
      if (($rs=$db->Execute($query, $data))===false)
      {
         uerror( 'Database error, line '.__LINE__ );
         return;
      }
      $o1 = $rs->FetchNextObject();
      $rs->Close();
      if ($o1!==false) {
         $plabel = $o1->PLABEL;
         $userid = $o1->USERID;
      }

      $query = "DELETE FROM iform_views WHERE VIEWID=?"; // use USERID for security
      $data = array($viewID);
      if (!$db->Execute($query, $data))
      {
         uerror( 'Database error, line '.__LINE__ );
         return;
      }
   }
   else // create new view
   {
      if ($x2->ulevel == 99) {
         if (empty($_REQUEST['FORUSER'])) {
            uerror("Field 'For user' not defined!");
            return;
         }

         $query = 'SELECT COUNT(*) FROM iform_users WHERE USERID=?';
         $data = array( $_REQUEST['FORUSER'] );
         if (($rs=$db->Execute($query, $data))===false) {
            uerror( 'Database error, line '.__LINE__ );
            return;
         }
         $row=$rs->FetchRow();
         $rs->Close();
         if ($row[0] == 0) {
            uerror('User ['.myhtml($_REQUEST['FORUSER']).'] does not exist in database!');
            return;
         }

         $userid = $_REQUEST['FORUSER'];
      }
      else {
         $userid = $_SESSION['USERID'];
      }

      $query = "SELECT MAX(VIEWID) FROM iform_views";
      if (($rs = $db->Execute($query)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
         return;
      }
      if (($row = $rs->FetchRow()) !== false)
      {
         $maxi = (int)$row[0];
      }
      else
      {
         $maxi = 0;
      }
      $rs->Close();
      $viewID = $maxi + 1;
   }

   $query = "INSERT INTO iform_views (USERID, VIEWID, FIELDSEQ, QUERYPREF, PNAME, PLABEL) VALUES (?,?,?,  ?,?,?)";
   $data = array($userid, $viewID, 0, 0, $_REQUEST['VIEWNAME'], $plabel );  // add title
   $i = 1;
   if (isset($_REQUEST['PNAME']))
   {
      foreach ($_REQUEST['PNAME'] as $j => $pname)
      {
         $query.= ", (?,?,?,?,?,?)";
         array_push($data, $_SESSION['USERID'], $viewID, $i++,
                    (int)$_REQUEST['QUERYPREF'][$j], $pname,
                    trim($_REQUEST['PLABEL'][$j]));
      }
   }
   if (!$db->Execute($query, $data))
   {
      //uerror( 'Database error, line '.__LINE__ );
      echo $db->ErrorMsg();
   }
}
//--------------------------------------
function ask_other_options()
{
   global $x2;
   $db = &$x2->db;

   SetHeadTitle(40 /* Options */ );

   $props = array();
   $query = "SELECT PNAME, PVALUE FROM reselprefex WHERE AGENTID=? AND RESELID=0 AND PGROUP='admin' ";
   $data = array($x2->agentid);
   if (($rs = $db->Execute($query, $data)) !== false)
   {
      while ($o1 = $rs->FetchNextObject())
      {
         $props[$o1->PNAME] = $o1->PVALUE;
      }
      $rs->Close();
   }
?>
<script>
function winRet(x)
{
   switch (x)
   {
   case 39:
   case 64:
      goTo(x);
      break;
   }
   hide_popup();
}
</script>

<fieldset class=options>
  <legend> Reset Logo
  </legend>
  <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method =
        POST enctype="multipart/form-data" name= "goForm">
    <input type=hidden name= "FUNCTION" value = "20">
    <input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
    <table>
      <tr>
        <td> GIF / JPG / PNG file
        </td>
        <td>
          <input type=file name= "LOGO">
        </td>
      </tr>
      <tr>
        <td>
        </td>
        <td>
          <input type=submit value =
                 "<?php echo $x2->xlabel(65 /* Update */ ); ?>">
          <input type=button value =
                 "<?php echo $x2->xlabel(7 /* Cancel */ ); ?>" onclick = "goTo(3)">
        </td>
      </tr>
    </table>
  </form>
</fieldset>

<fieldset class=options>
  <legend>Parameters</legend>
  <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method =
        POST enctype="multipart/form-data" name= "goForm">
    <input type=hidden name= "FUNCTION" value = "33">
    <input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
    <table>
      <tr>
        <td>
           Proposed days back on user date selection
        </td>
        <td>
          <select name= "INPDAYSBACK">
            <?php $ar1 = array();
               for ($i = 0; $i <= 30; $i++)
               {
                  $ar1[$i] = $i;
               }
               $ar1[-1] = "Unlimited";
               prAssocSelect($ar1, (int)@$props['INPDAYSBACK']);
            ?>
          </select>
        </td>
      </tr>
      <tr>
        <td> Auto fill[Till today]
        </td>
        <td>
          <label>
            <input type=checkbox name= "TILLTODAY_EN"
                   <?php if (!empty($props['TILLTODAY_EN']))
            {
            echo "checked";
            }
            ?> value = "1" > Enable
          </label>
        </td>
      </tr>
      <tr>
         <td>Minimum password length</td>
         <td><select type=text name="MINPASSLEN"><?php
            $x = (int)@$props['MINPASSLEN'];
            if ($x<=0) { $x=6; }
            prSelect(4,10,$x);
            ?></select></td>
      </tr>
      <tr>
         <td>Use Microsoft password policy</td>
         <td>
            <label>
               <input type=checkbox <?php if (!empty($props['M_PASSWDPOLICY']))
                  {
                     echo "checked";
                  } ?> name="M_PASSWDPOLICY" value="1">
               Enable
            </label>
         </td>
      </tr>
      <tr>
        <td> Full Text Search
        </td>
        <td>
          <label>
            <input type=checkbox name=
                   "FTS_EN"
                   <?php if (!empty($props['FTS_EN']))
            {
            echo "checked";
            }
            ?> value =
            "1" > Enable
          </label>
        </td>
      </tr>
      <tr>
         <td>Email attachment name</td>
         <td><select name="EMAIL_ATT_NAME"><?php
            $ar1 = array(
               0 => 'Document date_Document number_Branch no',
               1 => 'Document date_Branch no_Document number',
               2 => 'Document number_Document date_Branch no',
               3 => 'Document number_Branch no_Document date',
               4 => 'Branch no_Document date_Document number',
               5 => 'Branch no_Document number_Document date'
               );
            prAssocSelect($ar1, (int)@$props['EMAIL_ATT_NAME']);
         ?></select></td>
      </tr>
      <tr>
         <td>Storage Id min.chars.</td>
         <td><input type=number name="STORAGEIDMINCHARS" value="<?php echo myhtml(@$props['STORAGEIDMINCHARS']); ?>"></td>
      </tr>
      <tr>
        <td>
        </td>
        <td>
          <input type=submit value = "<?php echo $x2->xlabel(65 /* Update */ ); ?>">
          <input type=button value = "<?php echo $x2->xlabel(7 /* Cancel */ ); ?>" onclick = "goTo(3)">
        </td>
      </tr>
    </table>
  </form>
</fieldset>

<fieldset class=options>
  <legend>
    <?php echo $x2->xlabel(35 /* More options */ );
?>
  </legend>
  <input type=submit onclick = "goTo(51)" value = "<?php echo $x2->xlabel(58 /* Sources/Routes */ ); ?>">
  <input type=button onclick = "goTo(28)" value = "<?php echo $x2->xlabel(3 /* Additional users */ ); ?>">

  <input type=button onclick = "show_popup('popmenu')" value = "<?php echo $x2->xlabel(48 /* Rights */ ); ?>">

  <input type=button onclick = "goTo(74)" value = "HR users">
</fieldset>
<?php
   $selx = array(
      array(64, '../img/go_next.gif', 'Active directory Group rights'),
      array(39, '../img/go_next.gif', 'User rights'),
      );
   draw_popup($selx);
}
//--------------------------------------
function upd_other_properties()
{
   global $x2;
   $db = &$x2->db;

   $db->StartTrans();

   do
   {
      $ar1 = array('INPDAYSBACK', 'TILLTODAY_EN', 'FTS_EN', 'EMAIL_ATT_NAME', 'MINPASSLEN',
         'M_PASSWDPOLICY', 'STORAGEIDMINCHARS');

      $query = '';
      foreach ($ar1 as $fld1) {
         if (empty($query))
         {
            $query = "DELETE FROM reselprefex
               WHERE AGENTID=? AND RESELID=0 AND PGROUP='admin' AND PNAME IN ('$fld1'";
         }
         else
         {
            $query .= ", '$fld1'";
         }
         $query .= ")";
      }
      $data = array($x2->agentid);
      if (!$db->Execute($query, $data))
      {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }

      $query = "INSERT INTO reselprefex (AGENTID, RESELID, PGROUP, PNAME, PVALUE) VALUES(?, 0, 'admin', ?, ?)";
      foreach ($ar1 as $key)
      {
         if (isset($_REQUEST[$key]))
         {
            $data = array($x2->agentid, $key, $_REQUEST[$key]);
            if (!$db->Execute($query, $data))
            {
               uerror( 'Database error, line '.__LINE__ );
               break;
            }
         }
      }

      echo "Done!";

   } while (false);

   $db->CompleteTrans();
}
//--------------------------------------
function upd_other_logo()
{
   SetHeadTitle('Reset Logo');

   if (!isset($_FILES['LOGO']))
   {
      echo "<div class=error>Missing file var. 'LOGO'!</div>";
      return;
   }

   if ($_FILES['LOGO']['error'] != 0)
   {
      echo "<div class=error>Upload error ".$_FILES['LOGO']['error']."</div>";
      return;
   }

   $ftype   = $_FILES['LOGO']['type'];
   $img     = false;
   $srcPath = $_FILES['LOGO']['tmp_name'];
   switch ($ftype)
   {
   case "image/gif":
      $img = imagecreatefromgif($srcPath);
      break;
   case "image/jpeg": // Both regular and progressive jpegs
   case "image/pjpeg":
      $img = imagecreatefromjpeg($srcPath);
      break;
   case "image/png":
      $img = imagecreatefrompng($srcPath);
      break;
   }
   if ($img === false)
   {
      echo "<div class=error>Resource error (can not open image file)!</div>";
      return;
   }

   $wi = imagesx($img);
   $he = imagesy($img);
   if ($he > 120)
   {
      echo "<div class=error>Height exceeds 120 pixels!</div>";
      imagedestroy($img);
      return;
   }

   $outPath = GetLogoPath();

   switch ($ftype)
   {
   case "image/png": // copy 'as is'
      imagedestroy($img);
      if (!move_uploaded_file($srcPath, $outPath))
      {
         echo "<div class=error>Failed to update logo!</div>";
      }
      else
      {
         echo "<div class=umessage>Logo updated!</div>";
      }
      break;
   default: // convert into PNG
      if (!@imagepng($img, $outPath))
      {
         echo "<div class=error>Failed to save image file!</div>";
      }
      else
      {
         echo "<div class=umessage>Logo updated!</div>";
      }
      imagedestroy($img);
      unlink($outPath);
      break;
   }
}
//--------------------------------------
function ask_for_protype()
{
   global $x2;
   $db        = &$x2->db;

   $protype   = array();
   $stationid=(int)$_SESSION['STATIONID'];
   $types     = array('String', 'Date dd/mm/yyyy, descending', 'Number 1004.12',
                  'Date yymmdd..., descending', 'Login shop', 'Integer', 'Date yyyy-mm-dd, descending');

   SetHeadTitle(17 /* Fields */ );

   $query = "SELECT PNAME, PTYPE FROM iform_protype WHERE STATIONID=?";
   $data  = array($stationid);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return start_query();
   }
   while ($o1 = $rs->FetchNextObject())
   {
      $protype[$o1->PNAME] = $o1->PTYPE;
   }
   $rs->Close();

   $query = "SELECT PNAME FROM iform_pname WHERE STATIONID=?";
   $data  = array($stationid);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return start_query();
   }
   while ($o1 = $rs->FetchNextObject())
   {
      if (!array_key_exists($o1->PNAME, $protype))
      {
         $protype[$o1->PNAME] = 0;
      }
   }
   $rs->Close();

   ksort($protype);
   echo "<form action=\"".myhtml($_SERVER['SCRIPT_NAME'])."\" method=POST>
       <input type=hidden name=\"FUNCTION\" value=\"25\">
       <input type=hidden name=\"CSRFToken\" value=\"".$_SESSION['CSRFToken']."\">
                                   <fieldset> <legend> Field types</legend>
                                   <table> ";
   foreach ($protype as $pname=> $ptype)
   {
      echo "<tr>
          <td> <input type=hidden name=\"PNAME[]\" value=\"".myhtml($pname)
                                                ."\">".myhtml($pname)
                                                ."</td>
                                            <td> <select name=\"PTYPE[]\">";
      prAssocSelect($types, $ptype);
      echo "</select></td>
          </tr> ";
   }
   echo "<tr>
       <td> </td><td>
       <input type=submit value =\"".$x2->xlabel(65 /* Update */ )."\"></td>
                                   </tr></table></fieldset></form> ";
}
//--------------------------------------
function update_protype()
{
   global $x2;
   $db = &$x2->db;

   $query = "DELETE FROM iform_protype WHERE STATIONID=?";
   $data  = array($_SESSION['STATIONID']);
   if (!$db->Execute($query, $data))
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }

   $query = "";
   foreach ($_REQUEST['PNAME'] as $key => $pname)
   {
      $ptype=$_REQUEST['PTYPE'][$key];
      if (empty($query))
      {
         $query = "INSERT INTO iform_protype (STATIONID, PNAME, PTYPE) VALUES (?, ?, ?)";
         $data = array($_SESSION['STATIONID'], $pname, $ptype);
      }
      else
      {
         $query.= ", (?,?,?)";
         array_push($data, $_SESSION['STATIONID'], $pname, $ptype);
      }
   }
   if (!empty($query))
   {
      if (!$db->Execute($query, $data))
      {
         uerror( 'Database error, line '.__LINE__ );
         return;
      }
   }
}
//--------------------------------------
function ask_new_pwd($logout=false)
{ // Ask new password in order to reset
   global $x2;
   $db = &$x2->db;

   $prules = new cPASSRULES();
?>
<script>
var minpasslen = <?php echo (int)$prules->minpasslen; ?>;
var m_passwdpolicy = <?php echo $prules->m_passwdpolicy ?'true':'false'; ?>;
var msg = 'Needs use at least one lowercase, one uppercase character, one digit, one symbol from this: !@#$%&';
$(function(){
   if (m_passwdpolicy)
   {
      $('#msg').text(msg);
   }
});
function validatePasswd()
{
   var customerid='<?php echo myjs(@$_SESSION['CUSTOMERID']); ?>';
   var pwd = document.goForm.PWD.value;

   // 1)
   if (pwd.length<minpasslen)
   {
      alert('Minimum ' + minpasslen + ' characters required!');
      return false;
   }

   // 2)
   if (customerid.length>0  && pwd.indexOf(customerid)>=0) {
      alert('Password can not contain customer ID!');
      return false;
   }

   // 3)
   if (m_passwdpolicy)
   {
      if ( !pwd.match(/[a-z]/) || !pwd.match(/[A-Z]/) || !pwd.match(/[0-9]/) || !pwd.match(/[\!\@\#\$\%\&]/) )
      {
         var msg = 'Password must contain at least one char. of the following:\n'+
            '1 capital letter, 1 small letter, 1 digit, 1 special char. (!@#$%&).';
         alert(msg);
         return false;
      }
   }

   // 4)
   if (pwd !== document.goForm.PWD2.value)
   {
      alert('Passwords do not match!');
      return false;
   }

   return true;
}
</script>
<fieldset><legend> Reset user password</legend>
   <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method =
        POST name= "goForm" onsubmit="return validatePasswd()">
   <input type=hidden name="FUNCTION" value = "10">
   <input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
   <table>
   <tr>
      <?php
      switch ($x2->ulevel)
      {
      case 1:
         $key = 'User Id';
         $val = $_SESSION['USERID'];
         break;
      case 2:
         $key = 'Customer Id';
         $val = $_SESSION['CUSTOMERID'];
         break;
      default:
         $key = 'ULevel';
         $val = $x2->ulevel;
         break;
      }
      echo "<td>".myhtml($key)."</td>
         <td><b>".myhtml($val)."</b></td>";
      ?>
   </tr>
   <tr>
      <td><?php echo $x2->xlabel(93 /* Old password */ ); ?> </td>
      <td><input type=PASSWORD name="OLDPWD"></td>
   </tr>
   <tr>
      <td><?php echo $x2->xlabel(37 /* New password */ ); ?> </td>
      <td><input type=PASSWORD name= "PWD">
         <div id=msg style="color:#990099;"></div></td>
   </tr>
   <tr>
      <td>Repeat</td>
      <td><input type=PASSWORD name= "PWD2"></td>
   </tr>
   <tr>
      <td></td>
      <td>
         <input type=submit value = "<?php echo $x2->xlabel(65 /* Update */ ); ?>">
         <input type=button value = "<?php echo $x2->xlabel(7 /* Cancel */ ); ?>"
            onclick = "goTo(<?php echo  $logout ? 2 : 3; ?>)">
      </td>
   </tr>
   </table>
   </form>
</fieldset>

<?php
}
//--------------------------------------
function request_passwd()
{
   global $x2;
   $db = &$x2->db;

   do
   {
      if (empty($_REQUEST['USERID']))
      {
         break;
      }

      $ar1 = explode('-', $_REQUEST['PID']);
      if (count($ar1) != 2)
         break;

      if (time() - $ar1[1] > 1800)
      { // 1800 sec = 1/2 hour
         uerror("The request has expired. Please make another one!");
         break;
      }

      $query = "SELECT COUNT(*) FROM iform_users WHERE USERID=? AND PASSWD5=?";
      $data  = array($_REQUEST['USERID'], $ar1[0]);
      if (($rs = $db->Execute($query, $data)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }
      $row = $rs->FetchRow();
      $rs->Close();
      if ($row[0] == 0)
      {
         uerror("Authentication error. Please try again!");
         break;
      }

      echo "<fieldset>
          <legend > Reset password</legend>
          <form action=\"".myhtml($_SERVER['SCRIPT_NAME'])."\" method=POST name=\"goForm\">
            <input type=hidden name=\"FUNCTION\" value=\"992\">
            <input type=hidden name=\"CSRFToken\" value = \"".$_SESSION['CSRFToken']."\">
            <input type=hidden name=\"USERID\" value=\"".myhtml($_REQUEST['USERID'])."\">
            <input type=hidden name=\"OLDP5\" value=\"".myhtml($ar1[0])."\">
         <table>
            <tr>
               <td> Userid</td>
               <td><kbd> ".myhtml($_REQUEST['USERID'])." </kbd ></td>
            </tr>
            <tr>
               <td> New password</td>
               <td><input type=PASSWORD name=\"PWD\"></td>
            </tr>
            <tr>
               <td></td>
               <td><input type=submit value =\"Update\">
                  <input type=button value =\"Cancel\" onclick=\"goTo(0)\"></td>
            </tr>
         </table>
         </form>
         </fieldset> ";

          return;

   } while (false);

   request_login();
}
//--------------------------------------
function do_reset_passwd()
{
   global $x2;
   $db = &$x2->db;

   do
   {
      $query = "SELECT COUNT(*) FROM iform_users WHERE USERID=? AND PASSWD5=?";
      $data  = array($_REQUEST['USERID'], $_REQUEST['OLDP5']);
      if (($rs = $db->Execute($query, $data)) === false)
      {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }
      $row = $rs->FetchRow();
      $rs->Close();
      if ($row[0] == 0)
      {
         uerror("Authentication error. Please try again!");
         break;
      }

      $query = "UPDATE iform_users SET PASSWD5=? WHERE USERID=?";
      $data  = array(md5($_REQUEST['PWD']), $_REQUEST['USERID']);
      if (!$db->Execute($query, $data))
      {
         uerror( 'Database error, line '.__LINE__ );
      }
      else
      {
         echo "<div class=umessage>The password was updated! Please login with your new password.</div>";
      }
   } while (false);

   request_login();
}
//--------------------------------------
function OutMessage($msg)
// to be moved in library, as it also exists in iform_exp.php (a litle bit
// different)
{
   echo $msg;
}
//--------------------------------------
// FUNCTION 42:
function reset_vat_rights()
{
   global $x2;
   $db        = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   $query = "DELETE FROM iform_rights WHERE STATIONID=$stationid AND RITYPE=1";
   if (!$db->Execute($query))
   {
      uerror( 'Database error, line '.__LINE__ );
   }

   show_usr_rights(false);
}
//--------------------------------------
// FUNCTION 40:
function update_rights()
{
   global $x2;
   $db        = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];
   $done      = false;

   switch (@$_REQUEST['TYPE'])
   {
   case 'SRC':
      $ritype=0;
      break;
   case 'VATCODE':
      $ritype=1;
      break;
   case 'VIEWID':
      $ritype=2;
      break;
   default:
      uerror('Unknown RITYPE: '.myhtml(@$_REQUEST['TYPE']) );
      return;
   }

   $db->StartTrans();
   do
   {
      $query = "DELETE FROM iform_rights WHERE STATIONID=$stationid AND RITYPE=$ritype AND RIKEY=?";
      $data = array($_REQUEST['VAL']);
      if (!$db->Execute($query, $data))
      {
         uerror( 'Database error, line '.__LINE__ );
         break;
      }

      if (@$_REQUEST['CHECKED'] == 1)
      {
         // $db->quote() surrounds value with quotes, so it is safe to use for any value
         $query = "INSERT INTO iform_rights (LOGINUSER, STATIONID, RITYPE, RIKEY) ".
             " SELECT DISTINCT LOGINUSER, $stationid, $ritype, ".$db->quote($_REQUEST['VAL'])." FROM iform_login ";
         if (!$db->Execute($query))
         {
            uerror( 'Database error, line '.__LINE__ );
            break;
         }
      }

      $done = true;
   } while (false);
   $db->CompleteTrans();

   if ($done)
   {
      show_usr_rights(false);
   }
   else
   {
      ?> <p> Return to: <b>
            <input type=button onclick = "goTo(39)" value="<?php echo $x2->xlabel(48 /* Rights */ ); ?>">
            <input type=button onclick = "goTo(3)" value="<?php echo $x2->xlabel(27 /* Home */ ); ?>">
         </b></p>
      <?php
   }
}
//--------------------------------------
function HasRight($rights, $loginuser, $ritype, $val)
{
   foreach ($rights as $o1)
   {
      if ($o1->LOGINUSER === $loginuser && $o1->RITYPE == $ritype && $o1->RIKEY === (string)$val)
         return true;
   }
   // not found so far:
   return false;
}
//--------------------------------------
function show_ad_rights()
{
   global $x2;
   $db        = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   SetHeadTitle( $x2->xlabel(48).' (Active dir. Groups)' );
?>
<script>
$(function(){
   $('#moredata').dialog({
           autoOpen : false,
           modal : false,
           resizable : false
        });
} );

var ad_group;
function oclick(stage, row, col)
{
   ad_group = this.cells(row, 0).getValue();
   show_popup('popmenu');
   return false;
}
function winRet(x)
{
   switch (x)
   {
   case 1: // Users
      show_ad_users();
      break;
   case 2: // Rights
      show_ad_rights();
      break;
   }
   hide_popup();
}
function show_ad_users()
{
   var gtitle='Users of '+ad_group;
   var url = 'iform_exp.php?FUNCTION=19&AD_GROUP=' + encodeURIComponent(ad_group);
   $('#moredata').dialog({title:gtitle, width:300}).dialog('open');
   $('#datadiv').html('loading...').load(url);
}
function show_ad_rights()
{
   var gtitle='Rights for '+ad_group;
   var url = 'iform_exp.php?FUNCTION=20&AD_GROUP=' + encodeURIComponent(ad_group);
   $('#moredata').dialog({title:gtitle, width:600}).dialog('open');
   $('#datadiv').html('loading...').load(url);
}
</script>
<div id=moredata>
   <div id=datadiv style="height:480px; overflow:scroll"></div>
</div>
<?php

   $pg   = getPage();
   $pgsz = getPageSize('grid19');
   $gr1  = new cXRID('grid19');

   $gr1->cols=array(
      array('Active Dir. Group', 400),
      array('Users', 100)
   );

   $query  = 'SELECT AD_GROUP, COUNT(*) F1 FROM iform_ad_groups WHERE STATIONID=? GROUP BY AD_GROUP ORDER BY AD_GROUP';
   $data=array( $stationid );
   if (($rs = $db->cachePageExecute(3600, $query, $pgsz, $pg, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($row = $rs->FetchRow())
   {
      $row1 = array( myhtml($row[0]), $row[1] );
      $gr1->rows[] = $row1;
   }
   $epage = $rs->LastPageNo();
   $rs->Close();

   $gr1->click = 'oclick';
   $gr1->play();

   echo '<div id=tbar2>';
   print_page_navEx($pg, $epage, 64);
   echo ' <input type=button onclick = "goTo(39)" value = "User rights"> '.
      ' <input type=button onclick = "goTo(3)" value = "'.$x2->xlabel('Back').'">'.
      '</div>';

   $selx = array(
      array(1, '../img/users.png', 'Users'),
      array(2, '../img/folder_all.png', 'Rights')
      );
   draw_popup($selx);
}
//--------------------------------------
function show_usr_rights($all_users)
{
   global $x2;
   $db = &$x2->db;
   $stationid = (int)$_SESSION['STATIONID'];

   SetHeadTitle( $x2->xlabel(48).' (Users)'.($all_users?' All':'') );
?>
<script>
$(function(){
   $('#moredata').dialog({
           autoOpen : false,
           modal : false,
           resizable : false,
           width:600
        });
} );

var lguser;
function oclick(stage, row, col)
{
   lguser = this.cells(row, 0).getValue();

   var isOpen = $( '#moredata' ).dialog( 'isOpen' );

   if (isOpen)
   {
      show_usr_rights(false);
   }
   else
   {
      show_popup('popmenu');
   }
   return false;
}
function winRet(x)
{
   switch (x)
   {
   case 2: // Rights
      $('#moredata').dialog('open');
      show_usr_rights(false);
      break;
   }
   hide_popup();
}
function show_usr_rights()
{
   var gtitle='Rights for '+lguser;
   $('#moredata').dialog({title:gtitle});
   var url = 'iform_exp.php?FUNCTION=21&LGUSER=' + encodeURIComponent(lguser);
   $('#datadiv').html('loading...').load(url);
}
</script>
<div id=moredata>
   <div id=datadiv style="height:480px; overflow:scroll"></div>
</div>
<?php
   $prof = new cPROFILER1();

   $gr1  = new cXRID('grid20');

   $gr1->cols=array(
      array('Login User', 400),
      array('Station Id', 100),
      array('User type', 100),
   );

   /* commented 2-2-2020
   $query  = "SELECT DISTINCT LOGINUSER FROM iform_login
      UNION
      SELECT USERID FROM iform_users WHERE STATIONID=$stationid AND USRTYPE<>1
      ORDER BY LOGINUSER";
   */
   // Select all users from iform_login, however exclude those found in'iform_users' with a different stationid or HR
   //
   $users = array();
   $query = 'SELECT USERID, STATIONID, USRTYPE FROM iform_users ORDER BY USERID';
   if (($rs = $db->cacheExecute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1 = $rs->FetchNextObject()) {
      $users[strtolower($o1->USERID)] = $o1;
   }
   $rs->Close();

   $records = array();
   $query  = 'SELECT DISTINCT LOGINUSER FROM iform_login ORDER BY LOGINUSER';
   if (($rs = $db->cacheExecute($query)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($row = $rs->FetchRow())
   {
      $loginuser = $row[0];
      $row1 = array( myhtml($loginuser) );

      if (array_key_exists(strtolower($loginuser), $users))
      {
         $o1 = $users[strtolower($loginuser)];
         if ($x2->ulevel!=99 && ($o1->STATIONID != $stationid || $o1->USRTYPE == 1 /* HR */))
            continue;

         $row1[] = $o1->STATIONID;
         $row1[] = $o1->USRTYPE == 1 ? 'HR' : $o1->USRTYPE;
      }
      else {
         array_push($row1, '', '');
      }

      $records[ $loginuser ] = $row1;
   }
   $rs->Close();

   if ($all_users) {
      foreach ($users as $o1) {
         if (!array_key_exists($o1->USERID, $records) && $o1->USRTYPE !=1 )
            $records[ $o1->USERID ] = array( $o1->USERID, $o1->STATIONID, $o1->USRTYPE);
      }
   }

   foreach ($records as $row1)
   {
      $gr1->rows[] = $row1;
   }

   $gr1->click = 'oclick';
   $gr1->play();

   echo '<div id=tbar2>
      <button type=button onclick="askForUserFilter()" title="Filter"><input type=checkbox
         id=usrFilter disabled><img src="../img/filter.png"></button>
      <input type=button onclick = "goTo(42)" value = "Clean Vat codes">
      <input type=button onclick = "goTo(64)" value = "A.D. rights">';
   if ($x2->ulevel == 99 && !$all_users) {
      echo '<input type=button onclick="goTo(45)" value="All users">';
   }
   echo '<input type=button onclick = "goTo(3)" value = "'.$x2->xlabel('Back').'">
      </div>';

   $selx = array(
      array(2, '../img/folder_all.png', 'Rights')
      );
   draw_popup($selx);
?>
<script>
function askForUserFilter()
{
   if ($('#usrFilter').is(":checked")) {
      grid20.clearAll();
      grid20.parse(datagrid20,'json');
      $('#usrFilter').attr('checked', false);
   }
   else  { // not checked = not filtered
      var usr = window.prompt('Please enter user name (can use * wildcards)', '');
      if (usr === null || usr === '')
         return;

      /*
      var dataFilter={ "rows":[
         { id:0, data:[ "101", "98921", "" ] } ] };
      */
      var dataFilter={ "rows":[] };
      datagrid20.rows.forEach(function(it, idx) {
         if (it.data[0].search(usr) >= 0) {
            dataFilter.rows.push(it);
         }
      });
      grid20.clearAll();
      grid20.parse(dataFilter,'json');
      $('#usrFilter').attr('checked', true);
   }
}
</script>
<?php
}
//--------------------------------------
function AskDownloadReport($rxid)
{
   echo "<div class=umessage>Report Id $rxid is pending for execution or download.</div>";
   //.ready.</b> <a href=\"javascript:goTo(70)\">Go to downloads.</a>";
}
//--------------------------------------
function AskForReportEmail($rid)
{
   global $x2;
?>
<script>
$(function(){
   window.setTimeout(function(){
      $('#RID').text(<?php echo $rid; ?>);
      $('#URID').val(<?php echo $rid; ?>);
      $('#reportEmail').dialog('open');
   }, 400);
});
</script>
<?php
}
//--------------------------------------
function request_daily_rpt()
{
   global $x2;
   $db = &$x2->db;
   $stationid=(int)$_SESSION['STATIONID'];

   //SetHeadTitle(96);
   $credate = $_REQUEST['CREDATE'];
   $src=trim($_REQUEST['SRC']);

   $srcTitle = empty($src) ? '(empty)' : $src;
   $qryTitle = "Import documents for $srcTitle on ${credate}.";

   $qdir = GetUqueriesDir();
   if (empty($qdir)) {
      uerror("UqueriesDir not set");
      return;
   }

   // to be executed later (doc. import daily report)
   $uQuery = "SELECT M1.SEQNO, M1.SRC, M1.CREDAYTIME, M1.DOCDATE, T1.PVALUE, T2.PVALUE, T3.PVALUE, T4.PVALUE, T5.PVALUE FROM iform_main M1 ".
      " LEFT JOIN iform_prop T1 ON (T1.STATIONID=M1.STATIONID AND T1.SEQNO=M1.SEQNO AND (T1.PNAME='ΕΙΔΟΣ ΠΑΡΑΣΤΑΤΙΚΟΥ' OR PNAME='ΠΑΡΑΣΤΑΤΙΚΟ')) ".
      " LEFT JOIN iform_prop T2 ON (T2.STATIONID=M1.STATIONID AND T2.SEQNO=M1.SEQNO AND T2.PNAME='ΣΕΙΡΑ') ".
      " LEFT JOIN iform_prop T3 ON (T3.STATIONID=M1.STATIONID AND T3.SEQNO=M1.SEQNO AND (T3.PNAME='ΑΡΙΘΜΟΣ ΠΑΡΑΣΤΑΤΙΚΟΥ' OR T3.PNAME='Αριθμός Παραστατικού')) ".
      " LEFT JOIN iform_prop T4 ON (T4.STATIONID=M1.STATIONID AND T4.SEQNO=M1.SEQNO AND T4.PNAME='ΑΦΜ') ".
      " LEFT JOIN iform_prop T5 ON (T5.STATIONID=M1.STATIONID AND T5.SEQNO=M1.SEQNO AND T5.PNAME='ΕΠΩΝΥΜΙΑ') ".
      " WHERE M1.STATIONID=$stationid AND ".DateFld('M1.CREDAYTIME')."=".$db->quote($credate)." AND ";
   if (strlen($src)==0)
   {
      $uQuery .= " (M1.SRC='' OR M1.SRC IS NULL)";
   }
   else
   {
      $uQuery .= " M1.SRC=".$db->quote($src);
   }
   $hash = sha1($uQuery);

   // Get any record with same hash into last 12 hours of same user
   $query = "SELECT T1.RXID, T1.QREADY, T2.RID, T2.STATIONID, T2.USERID FROM iform_uxquery T1 ".
      " LEFT JOIN iform_usrquery T2 ON (T2.RXID=T1.RXID) ".
      " WHERE T1.QRYHASH=? AND T1.CREDAYTIME>=? ";
   $data = array($hash, date('Y-m-d H:i:s', time() - 12*3600) );
   if (($rs=$db->Execute($query, $data))===false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   $rxid=false;
   while ($o1=$rs->FetchNextObject())
   {
      if ($o1->STATIONID == $stationid && $o1->USERID === $_SESSION['USERID']) {
         // Pending request Id = $o1->RID
         if ($o1->QREADY == 1) {
            AskDownloadReport($o1->RID);
         }
         else {
            AskForReportEmail($o1->RID);
         }
         return;
      }
      $rxid=$o1->RXID;
   }
   $rs->Close();

   if ($rxid!==false) { // found something of different user or stationid
      $query = "INSERT INTO iform_usrquery (RXID, STATIONID, USERID) VALUES(?, $stationid, ?)";
      $data = array( $rxid, $_SESSION['USERID'] );
      if (!$db->Execute($query, $data))
      {
         uerror( 'Database error, line '.__LINE__ );
         return;
      }
      if (($rid=$db->insert_Id())===false) {
         uerror( 'Database error, line '.__LINE__ );
         uerror( "Could not insert request in waiting list!" );
         return;
      }

      // Pending request Id = $rid
      AskForReportEmail($rid);
   }
   else { // nothing found
      $db->StartTrans();
      do {
         $query = "INSERT INTO iform_uxquery (CREDAYTIME, UQUERY, QRYHASH, QRYTITLE) VALUES( ?, ?, ?, ?)";
         $data = array( date('Y-m-d H:i:s'), $uQuery, $hash, $qryTitle );
         if (!$db->Execute($query, $data))
         {
            uerror( 'Database error, line '.__LINE__ );
            break;
         }
         if (($rxid=$db->insert_Id())===false) {
            uerror( 'Database error, line '.__LINE__ );
            uerror( "Could not insert request in waiting list!" );
            break;
         }

         $query = "INSERT INTO iform_usrquery (RXID, STATIONID, USERID) VALUES(?, ?, ?)";
         $data = array($rxid, $stationid, $_SESSION['USERID'] );
         if (!$db->Execute($query, $data))
         {
            uerror( 'Database error, line '.__LINE__ .$db->ErrorMsg() );
            break;
         }
         if (($rid=$db->insert_Id())===false) {
            uerror( 'Database error, line '.__LINE__ );
            uerror( "Could not insert request in waiting list!" );
            break;
         }
      } while (false);
      $err = $db->hasFailedTrans();
      $db->CompleteTrans();
      if ($err) {
         return;
      }
   }

   echo "<div class=umessage>New request Id $rid</div>";
   AskForReportEmail($rid);
}
//--------------------------------------
function show_tablet_usr()
// deprecated
{
   global $x2;
   $db = &$x2->db;
   ?> <script> $(function() {
        $('#tabletusr').dialog({autoOpen : false, modal : true, resizable : false});
     });

   var userid, fullname;
   function oclick(stage, row, col)
   {
      userid   = this.cells(row, 0).getValue();
      fullname= this.cells(row, 1).getValue();
      show_popup('popmenu');
      return false;
   }
   function winRet(x)
   {
      switch (x)
      {
      case 43: // edit data
         edit_user();
         break;
      case 44: // reset password
         reset_passwd();
         break;
      case 45: // delete
         goRecDelete(45, userid);
         break;
      }
      hide_popup();
   }
   function edit_user()
   {
      $('input[name="FUNCTION"]').val(43);
      $('input[name="USERID"]').attr('readonly', true).val(userid);
      $('input[name="FULLNAME"]').attr('readonly', false).val(fullname);
      $('input[name="PASSWD"]').attr('readonly', true).val('');
      $('#tabletusr').dialog('option', 'title', 'Edit user name').dialog('open');
   }
   function reset_passwd()
   {
      $('input[name="FUNCTION"]').val(44);
      $('input[name="USERID"]').attr('readonly', true).val(userid);
      $('input[name="FULLNAME"]').attr('readonly', true).val(fullname);
      $('input[name="PASSWD"]').attr('readonly', false).val('');
      $('#tabletusr').dialog('option', 'title', 'Reset password').dialog('open');
   }
   function new_tablet_usr()
   {
      $('input[name="FUNCTION"]').val(46);
      $('input[name="USERID"]').attr('readonly', false).val('');
      $('input[name="FULLNAME"]').attr('readonly', false).val('');
      $('input[name="PASSWD"]').attr('readonly', false).val('');
      $('#tabletusr').dialog('option', 'title', 'Add new user').dialog('open');
   }
   </script><div id=tabletusr>
       <form action="<?php echo myhtml($_SERVER['SCRIPT_NAME']); ?>" method =
            POST name= "goForm" autocomplete = "off">
       <input type=hidden name= "FUNCTION">
       <input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
       <table><tr><td> User Id</td><td>
       <input type=text name= "USERID" size = 50 maxlength = 120></td></tr>
       <tr><td> Full name</td><td>
       <input type=text name= "FULLNAME" size = 50 maxlength = 200></td>
       </tr><tr><td> Password</td><td>
       <input type=password name= "PASSWD" size = 50></td></tr><tr><td>
       </td><td>
       <input type=submit value = "<?php echo $x2->xlabel(65 /* Update */ ); ?>">
       </td></tr></table></form></div>
<?php
   $gr1 = new cXRID('grid9');
   $gr1->cols = array(
      array('User Id', 100),
      array('Full name', 200)
      );

   $query = "SELECT USERID, FULLNAME FROM iform_tablet WHERE STATIONID=? ORDER BY USERID";
   $data = array($_SESSION['STATIONID']);
   if (($rs = $db->Execute($query, $data)) === false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   while ($o1 = $rs->FetchNextObject())
   {
      $row1        = array(myhtml($o1->USERID), myhtml($o1->FULLNAME));
      $gr1->rows[] = $row1;
   }
   $rs->Close();

   $gr1->click = 'oclick';
   $gr1->play();

   echo "<div id=tbar2>
      <button type=button onclick =\"new_tablet_usr()\">".$x2->xlabel(1 /* Add new */ )."</button>
      </div> ";

   $selx = array(
      array(43, '../img/button_edit.png', $x2->xlabel(16 /* Edit data */ )),
      array(44, '../img/key16x16.png', 'Reset password'),
      array(45, '../img/delete.png', $x2->xlabel(12 /* Delete */ ))
      );
   draw_popup($selx);
}
//--------------------------------------
function setUqueryEmail()
{
   global $x2;
   $db = &$x2->db;

   $stationid=(int)$_SESSION['STATIONID'];
   $rid=(int)$_REQUEST['RID'];

   $query = "SELECT T2.QREADY FROM iform_usrquery T1 LEFT JOIN iform_uxquery T2 ON (T2.RXID=T1.RXID)
      WHERE T1.RID=? AND STATIONID=?"; // stationid not really needed; just for security
   $data = array($rid, $stationid);
   if (($rs=$db->Execute($query, $data))===false)
   {
      uerror( 'Database error, line '.__LINE__ );
      return;
   }
   $row=$rs->FetchRow();
   $rs->Close();
   if ($row===false)
   {
      uerror( "No data record found to update!");
      return;
   }

   if ($row[0]==1)
   {
      uerror( "Statement already executed. Can not change email!");
      return;
   }

   $query = "UPDATE iform_usrquery SET EMAILTO=? WHERE RID=? AND STATIONID=?"; // stationid not really needed; just for security
   $data = array( $_REQUEST['EMAILTO'], $rid, $stationid );
   if (!$db->Execute($query, $data))
   {
      uerror("Error updating email in database!");
   }
}
//--------------------------------------
function draw_reset_upload_pwd($userid=false)
{
   global $x2;
?>
<div id=resetuploadpwd title = "Reset upload password">
   <input type=hidden name="CSRFToken" value = "<?php echo $_SESSION['CSRFToken']; ?>">
   <table>
      <tr>
         <td> User Id</td>
         <td><input type=text id="THEUSERID_UP" readonly value="<?php if ($userid!==false) { echo myhtml($userid); } ?>" style=" width:200px;"></td>
      </tr>
      <tr>
         <td>New upload password</td>
         <td>
            <input type=text id="NEWPASSWD_UP" readonly style="font-size:1.4em; width:200px;">
            <div id=msgUP style="color:#990099;"></div>
         </td>
      </tr>
      <tr>
         <td></td>
         <td>
            <div style="padding:2em; background-color:#FFFFCC;">
            Attention!<br>
            If you press [Update] you <b>must</b> then update TaxSpooler with the new password,
            otherwise TaxSpooler will stop sending documents to the WEB.
            <p></p>
            Προσοχή!<br>
            Αν πατήσετε [Update] <b>πρέπει</b> μετά να ενημερώστε τον TaxSpooler με το νέο password,
            αλλιώς ο TaxSpooler θα σταματήσει να στέλνει παραστατικά στο WEB.
            </div>
            <input id=bresetuplpwd type=button value="<?php echo $x2->xlabel(65 /* Update */ ); ?>"
               onclick="reset_upload_passwd()">
         </td>
      </tr>
   </table>
   </form>
</div>
<?php
}
//--------------------------------------
?>