This commit is contained in:
2023-10-25 11:20:07 +06:00
15 changed files with 11778 additions and 529 deletions

View File

@ -1,7 +1,7 @@
//Copyright (C) Ivanov I.M. file created in 2008
//For find non english chars: [^\x00-\x7F]+
//Заглушки
//Stubs
function setPropVal(uid,id,c,p){
ERec_mas[uid].setPropVal(id,c,p);
}
@ -102,7 +102,7 @@ class EdtRec
{
field.value=value;
}else{
console.error('Field "'+propName+'" not found!');
log.error('Field "'+propName+'" not found!');
}
}
@ -321,15 +321,42 @@ class EdtRec
let nList=findNode(nodeProp, "options");
if(nList!=null)
{
nodeProp.field = new TCheckboxListField(nodeProp.getAttribute("n"));
let nCheckbox = nList.firstChild;
while (nCheckbox!=null) {
if(nCheckbox.nodeName=="option") {
nodeProp.field.addCheckbox(nCheckbox.getAttribute("n"), nCheckbox.getAttribute("d"));
if(nList.getAttribute("selector")=="combo")
{
let select = document.createElement('select');
select.classList.add('DBMS');
select.style.cssText="width: 100%; height:22px; line-height: 22px;";
select.setAttribute("name",nodeProp.getAttribute("n"));
select.setAttribute("id","prop_"+this.uid+"_"+nodeProp.getAttribute("n"));
select.onchange = function(thiz,node){ return function()
{
thiz.onComboObjectChangeHandler(node);
};
}(this,nodeProp);
let nCheckbox = nList.firstChild;
while (nCheckbox != null) {
if (nCheckbox.nodeName == "option") {
let option = document.createElement('option');
option.setAttribute("value",nCheckbox.getAttribute("n"));
option.appendChild(document.createTextNode(nCheckbox.getAttribute("d")));
select.appendChild( option );
}
nCheckbox = nCheckbox.nextSibling;
}
nCheckbox = nCheckbox.nextSibling;
//select.setAttribute("value",value);// does not work because when creating no values in the list
newCell1.appendChild(select);
}else{
nodeProp.field = new TCheckboxListField(nodeProp.getAttribute("n"));
let nCheckbox = nList.firstChild;
while (nCheckbox != null) {
if (nCheckbox.nodeName == "option") {
nodeProp.field.addCheckbox(nCheckbox.getAttribute("n"), nCheckbox.getAttribute("d"));
}
nCheckbox = nCheckbox.nextSibling;
}
newCell1.appendChild(nodeProp.field.getDiv());
}
newCell1.appendChild(nodeProp.field.getDiv());
}else
{
let input = document.createElement('input');
@ -958,7 +985,7 @@ class EdtRec
let rec=new SRec();
rec.opener=this;
rec.create();
rec.create(null);
rec.f_State=1;
rec.f_PropName=nodeProp.getAttribute("n");
rec.f_Settings=settings;
@ -1074,7 +1101,7 @@ class EdtRec
}
nodeProp=nodeProp.nextSibling;
}
//console.log('Значение в XML '+prop_name+'='+val);
//log.info('Значение в XML '+prop_name+'='+val);
//The first line in the select as NULL value = 1
option = document.createElement('option');
@ -1107,7 +1134,7 @@ class EdtRec
//option.style.color="graytext"
option.setAttribute("value",id);
option.appendChild(document.createTextNode(caption));
//console.log('id='+id+' val='+val);
//log.info('id='+id+' val='+val);
if (id==val) option.selected=true;
prop.appendChild( option );
}
@ -1175,8 +1202,9 @@ class EdtRec
applyReq(req,fn,node,xmldoc,win)
{
this.hideProgressBar();
if (fn==-1) {
let fullText = findFirstNode(node,'#cdata-section').nodeValue;
if(node.errorCode>0) {
let fullText = node.errorMessage;
let smallText = '';
let pos1=fullText.indexOf('[[');
let pos2=fullText.indexOf(']]');
@ -1197,7 +1225,9 @@ class EdtRec
else
alert2(trt('Alert'), fullText);
}
} else
return;
}
if (fn==0) {
this.eRecNo(node,this.record_id);
} else
@ -1240,15 +1270,15 @@ class EdtRec
if(prop!==null) prop.value = id;
//Request a comment on the record id from the server
let xml = '';
if(filter!=''){
if(filter!=null){
//Настройка для последующего вызова формы через кнопку
xml='<prop n="'+prop_id+'"><type n="' + TypeName + '"><objects-list>'+filter+'</objects-list></type></prop>';
xml='<prop n="'+prop_id+'"><type n="' + TypeName + '"><objects-list>'+getXMLNodeSerialisation(filter)+'</objects-list></type></prop>';
applyNodeToNode(CreateXMLDOC(xml).documentElement, node, "n");
//Для запроса списка значений для выпадающего списка
xml = '<?xml version="1.0" encoding="utf-8"?>' +
'<metadata fn="6"><type n="' + TypeName + '" c="' + name + '" pn="' + prop_id + '" fn="' + name + '">' +
'<objects-list>' + filter + '</objects-list>' +
'<objects-list>' + getXMLNodeSerialisation(filter) + '</objects-list>' +
'</type></metadata>';
}else{
xml = '<?xml version="1.0" encoding="utf-8"?>' +
@ -1335,7 +1365,7 @@ class EdtRec
if (nodeProp.nodeName=="prop")
{
let value=getCdata(nodeProp).nodeValue;
//console.log("name = "+nodeProp.getAttribute("n")+" value= "+value);
//log.info("name = "+nodeProp.getAttribute("n")+" value= "+value);
if ((value=="true")||(value=="t")) value=1;
if ((value=="false")||(value=="f")) value=0;
@ -1430,7 +1460,7 @@ class EdtRec
if(document.getElementById("prop_"+this.uid+"_"+nodeProp.getAttribute("n")+"_visible").value=="")
value="";
}
//console.log("name = "+nodeProp.getAttribute("n")+" value= "+value+" object = "+document.getElementById("prop_"+this.uid+"_"+nodeProp.getAttribute("n")));
//log.info("name = "+nodeProp.getAttribute("n")+" value= "+value+" object = "+document.getElementById("prop_"+this.uid+"_"+nodeProp.getAttribute("n")));
}else{
//For special fields (look "TCheckboxListField" class)
value=nodeProp.field.getValue();
@ -1458,7 +1488,7 @@ class EdtRec
//Check the field according to its type
checkData(value,type,maybenull)
{
//console.log("checkData value = "+value+" type= "+type+" maybenull = "+maybenull);
//log.info("checkData value = "+value+" type= "+type+" maybenull = "+maybenull);
if(value==undefined) return false;
if(type=="i4")
{

78
metadata/dbms/log.js Normal file
View File

@ -0,0 +1,78 @@
// Самодельный логгер, почти аналог: https://thecode.media/winston/
class Log
{
constructor()
{
this.data = [];
this.win = null;
}
show() {
if (this.win != null) this.win.Close();
this.win = new TWin();
this.win.divsh.onclick = null;
this.win.shadow = false;
//this.win.setParent(this.parent.win);
this.win.BuildGUI(10, 10);
this.win.setCaption(trt('Log'));
this.win.setContent('<div id="log_' + this.win.uid + '" style="height:100%;width:100%;"></div>');
this.win.setSize("600px", "260px");
this.win.setCenter();
this.win.hide(false);
this.addLine(true);
}
hide(){
if(this.win!=null) this.win.Close();
this.win=null;
}
addLine(all){
if (this.win == null) return;
let elem = document.getElementById("log_" + this.win.uid);
let i = 0;
if(!all) i = this.data.length-1;
for (;i < this.data.length;i++) {
let div = document.createElement('div');
if(this.data[i].p==1){
div.style.cssText='color: maroon; width:100%;';
}
else if(this.data[i].p==2){
div.style.cssText='color: green; width:100%;';
}
else if(this.data[i].p==3){
div.style.cssText='color: orange; width:100%;';
}
else if(this.data[i].p==4){
div.style.cssText='color: red; width:100%;';
}
div.innerHTML = "["+this.data[i].t+"] "+this.data[i].d;
elem.appendChild(div);
}
}
getTime(){
let data=new Date();
return ('0'+data.getHours()).slice(-2)+":"+('0'+data.getMinutes()).slice(-2)+":"+('0'+data.getSeconds()).slice(-2)+":"+('00'+data.getMilliseconds()).slice(-3);
}
debug(msg){
this.data.push({"p":1,"d":msg,"t": this.getTime()});
this.addLine(false);
}
info(msg){
this.data.push({"p":2,"d":msg,"t": this.getTime()});
this.addLine(false);
}
warn(msg){
this.data.push({"p":3,"d":msg,"t": this.getTime()});
this.addLine(false);
}
error(msg){
this.data.push({"p":4,"d":msg,"t": this.getTime()});
this.addLine(false);
}
}
var log = new Log();
/*log.debug("log.debug");
log.info("log.info");
log.warn("log.warn");
log.error("log.error");*/

View File

@ -18,12 +18,11 @@ class DBMSUser
applyReq(req,fn,node)
{
//alert(getXMLNodeSerialisation(node));
this.showShadow(false);
if (fn==-1)
{
alert(findFirstNode(node,'#cdata-section').nodeValue);
}else
if(node.errorCode>0) {
alert2(trt('Alert'), node.errorMessage);
}
if(fn==7)
{
var nCmd=findFirstNode(node, "cmd");
@ -95,7 +94,7 @@ class DBMSUser
deleteHTML('TWin_CL_'+this.win.uid); //Удаляю кнопку закрыть
this.win.setCaption(trt('Authorization'));
this.win.setSize("350px","200px");
this.win.setSize("350px","184px");
var str='<div style="width: 100%; height: 100%; padding: 3px; text-align: left;">\n\
<table cellpadding="0" cellspacing="0" style="width: 100%; height: 100%;">\n\

View File

@ -1,4 +1,5 @@
<?php
use lfkeitel\phptotp\{Base32,Totp};
//sleep(1);
//ini_set('display_errors','Off'); //Чтоб ошибки не отправлялись клиентам
@ -37,13 +38,16 @@
return substr($path,0,$position);
}
function sendError($e)
{
header('Content-type: text/xml');
header("Cache-Control: no-cache, must-revalidate");
echo '<?xml version="1.0" encoding="utf-8"?><metadata fn="-1"><![CDATA['.$e.']]></metadata>';
Exit();
}
function sendError($code, $error)
{
$obj = new StdClass();
$obj->errorCode=$code;
$obj->errorMessage=$error;
header('Content-Type: application/json');
header("Cache-Control: no-cache, must-revalidate");
echo json_encode($obj);
exit();
}
function getSQLValue($t,$v)
{
@ -173,13 +177,13 @@
}
if($xmls!='')
{
//sendError("Metadata node \"".$name."\" not find in database!");
//sendError(1,"Metadata node \"".$name."\" not find in database!");
$objXMLDocument = new DOMDocument();
try
{
$objXMLDocument->loadXML($xmls);
} catch (Exception $e)
{ sendError($e->getMessage());
{ sendError(1,$e->getMessage());
}
$currNode=findNodeOnAttribute($objXMLDocument->documentElement, "type","n",$name);
return $currNode;
@ -190,7 +194,7 @@
function special_handler($exception)
{
sendError($exception->getMessage());
sendError(1,$exception->getMessage());
}
set_exception_handler('special_handler'); //чтоб не пойманные исключения посылались в виде XML
@ -216,10 +220,10 @@
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e)
{ sendError('Connect error '.$_SERVER['HTTP_HOST'].': "'.$e->getMessage().'"!');
{ sendError(1,'Connect error '.$_SERVER['HTTP_HOST'].': "'.$e->getMessage().'"!');
}
//Пытаемся автоматически залогинется по GUID из COOKIE
//Пытаемся автоматически залогинется по GUID из COOKIE (TODO авторизация должна быть в отдельном файле! Смотри директорию password )
/*if($_SESSION['USER_ID']==null && $_COOKIE['GUID']!=null)
{
$res = $db->query("select * from ".$Schema."p__Login(null,null,null,'".$_COOKIE['GUID']."');");
@ -242,7 +246,7 @@
$doc->loadXML($HTTP_INPUT);
} catch (Exception $e)
{
sendError($e->getMessage());
sendError(1,$e->getMessage());
}
$reqNode = $doc->documentElement;
@ -268,7 +272,6 @@
if ($fn==0) //отправить метаданные клиенту по запрошенному узлу
{
session_write_close(); //Разблокируем сессионный файл так как запросы могут быть достаточно долгими
//if (!isset($_SESSION['USER_ID']) || $_SESSION['USER_ID']=='') sendError('Вы не авторизованы! '.$_SERVER['PHP_SELF']);
$typename=findFirstNode($reqNode, "type")->getAttribute("n");
$currNode=getMetadataNode($typename);
@ -278,42 +281,32 @@
$objXMLDocument=$currNode->ownerDocument;
//Вернём значение прав доступа для запрошенного объекта
//$allow=true;
$allow=false;
//$sql_query='select a.*,at.name from _Access a, _Actions at where a.del=false and at.id=a.action_id and at.name=\'Insert_'.$typename.'\' and a.role_id in (select group_id from _UsersRoles where user_id='.$_SESSION['USER_ID'].');'
$sql_query='select '.$Schema.'p_getaccess('.getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']).',\'Insert_'.$typename.'\') as allow;';
$res = $db->query($sql_query);
while ($row = $res->fetch(PDO::FETCH_ASSOC))// $row - ассоциативный массив значений, ключи - названия столбцов
$allow_ins=false;
$allow_upd=false;
$allow_del=false;
$sql_query='select '.$Schema.'p_getaccess(:user_id1,:action_insert) as ins,'.$Schema.'p_getaccess(:user_id2,:action_update) as upd,'.$Schema.'p_getaccess(:user_id3,:action_delete) as del;';
$stmt = $db->prepare($sql_query);
$stmt->bindValue(':user_id1', $_SESSION['USER_ID'], PDO::PARAM_INT); //getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID'])
$stmt->bindValue(':user_id2', $_SESSION['USER_ID'], PDO::PARAM_INT); //getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID'])
$stmt->bindValue(':user_id3', $_SESSION['USER_ID'], PDO::PARAM_INT); //getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID'])
$stmt->bindValue(':action_insert', 'Insert_'.$typename, PDO::PARAM_STR);
$stmt->bindValue(':action_update', 'Update_'.$typename, PDO::PARAM_STR);
$stmt->bindValue(':action_delete', 'Delete_'.$typename, PDO::PARAM_STR);
$res=$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$allow=$allow || ($row['allow'] == 't');
$allow_ins=$row['ins'] == 't';
$allow_upd=$row['upd'] == 't';
$allow_del=$row['del'] == 't';
}
$xmlAttr = $objXMLDocument->createAttribute("ins"); //insert
$xmlAttr->nodeValue = $allow ? "1" : "0";
$xmlAttr->nodeValue = $allow_ins ? "1" : "0";
$currNode->setAttributeNode($xmlAttr);
$allow=false;
//$sql_query='select a.*,at.name from _Access a, _Actions at where a.del=false and at.id=a.action_id and at.name=\'Update_'.$typename.'\' and a.role_id in (select group_id from _UsersRoles where user_id='.$_SESSION['USER_ID'].');';
$sql_query='select '.$Schema.'p_getaccess('.getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']).',\'Update_'.$typename.'\') as allow;';
$res = $db->query($sql_query);
while ($row = $res->fetch(PDO::FETCH_ASSOC))// $row - ассоциативный массив значений, ключи - названия столбцов
{
$allow=$allow || ($row['allow'] == 't');
}
$xmlAttr = $objXMLDocument->createAttribute("upd"); //insert
$xmlAttr->nodeValue = $allow ? "1" : "0";
$xmlAttr = $objXMLDocument->createAttribute("upd"); //update
$xmlAttr->nodeValue = $allow_upd ? "1" : "0";
$currNode->setAttributeNode($xmlAttr);
$allow=false;
//$sql_query='select a.*,at.name from _Access a, _Actions at where a.del=false and at.id=a.action_id and at.name=\'Delete_'.$typename.'\' and a.role_id in (select group_id from _UsersRoles where user_id='.$_SESSION['USER_ID'].');';
$sql_query='select '.$Schema.'p_getaccess('.getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']).',\'Delete_'.$typename.'\') as allow;';
$res = $db->query($sql_query);
while ($row = $res->fetch(PDO::FETCH_ASSOC))// $row - ассоциативный массив значений, ключи - названия столбцов
{
$allow=$allow || ($row['allow'] == 't');
}
$xmlAttr = $objXMLDocument->createAttribute("del"); //delete
$xmlAttr->nodeValue = $allow ? "1" : "0";
$xmlAttr->nodeValue = $allow_del ? "1" : "0";
$currNode->setAttributeNode($xmlAttr);
$allow=true;
@ -334,12 +327,11 @@
Exit();
}else
{
sendError('Не найден запрошенный узел: "'.$typename.'"!');
sendError(1,'Не найден запрошенный узел: "'.$typename.'"!');
}
}else
if ($fn==1) //вставка записи (результат id записи)
{
//if (!isset($_SESSION['USER_ID']) || $_SESSION['USER_ID']=='') sendError('Вы не авторизованы! '.$_SERVER['PHP_SELF']);
session_write_close(); //Разблокируем сессионный файл так как запросы могут быть достаточно долгими
$typename=findFirstNode($reqNode,"type")->getAttribute("n");
@ -382,7 +374,7 @@
$path= $_SERVER['DOCUMENT_ROOT'].'/'.findFirstNodeOnAttribute($currNode,"prop","n",$nodePropData->getAttribute("n"))->getAttribute("path");
@mkdir($path); //Создаём папку если её нет
if(!rename($dir.$flnm, $path.$flnm))
sendError('Can\'t rename to "'.$path.$v.'"!');
sendError(1,'Can\'t rename to "'.$path.$v.'"!');
}
}else
{ $v=getSQLValue($vt, getCdataValue($nodePropData));
@ -394,7 +386,7 @@
$sql_query=str_replace('${_user_id}',getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']),$sql_query); //Потому что PostgreSQL не может хранить id пользователя привязаного к сесии
$stmt = $db->prepare($sql_query);
if($stmt === false) sendError('Error preparing Statement');
if($stmt === false) sendError(1,'Error preparing Statement');
//присваеваем параметрам значения (В записи может быть только 1 двоичное поля см bindParam или сделать несколько переменных)
$nodePropData=$nodeProp->firstChild;
@ -417,12 +409,15 @@
}
$nodePropData=$nodePropData->nextSibling;
}
try
{
$res = $stmt->execute();
} catch (Exception $e)
{ sendError($e->getMessage());
{
if(str_contains($e->getMessage(), ']]'))
sendError(1, $e->getMessage());
else
sendError(1, '[['.trt("SQL_query_error").']]'.$e->getMessage());
}
$result = $stmt->fetch(PDO::FETCH_NUM);
if($result[0]=='')
@ -430,7 +425,7 @@
if(strpos($db_connection, 'sqlite')!==false) {
$result[0] = $db->lastInsertId(); //Для SQLite
}else{
sendError(trt('Failed_to_insert_record').'!');
sendError(1,trt('Failed_to_insert_record').'!');
}
}
@ -441,13 +436,12 @@
Exit();
}else
{
sendError('Не найден запрошенный узел: "'.$typename.'"!');
sendError(1,'Не найден запрошенный узел: "'.$typename.'"!');
}
}else
if ($fn==2) //редактирование (результат id записи)
{
session_write_close(); //Разблокируем сессионный файл так как запросы могут быть достаточно долгими
//if (!isset($_SESSION['USER_ID']) || $_SESSION['USER_ID']=='') sendError('Вы не авторизованы! '.$_SERVER['PHP_SELF']);
$nodeType=findFirstNode($reqNode,"type");
$typename=$nodeType->getAttribute("n");
@ -491,8 +485,8 @@
{
$path= $_SERVER['DOCUMENT_ROOT'].'/'.findFirstNodeOnAttribute($currNode,"prop","n",$nodePropData->getAttribute("n"))->getAttribute("path");
@mkdir($path);//Создаём папку если её нет
if(!rename($dir.$flnm, $path.$flnm))
sendError('Can\'t rename to "'.$path.$v.'"!');
if(!rename($dir.$flnm, $path.$flnm))
sendError(1,'Can\'t rename to "'.$path.$v.'"!');
}
}else
{
@ -505,9 +499,9 @@
$sql_query=str_replace('${_user_id}',getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']),$sql_query); //Потому что PostgreSQL не может хранить id пользователя привязаного к сесии
$sql_query=str_replace('${'.$currNode->getAttribute("ObjectID").'}',getSQLValue(gettype($obj_id),$obj_id),$sql_query); //Так как пока идентификатор базы отдельно передаётся
//sendError($sql_query);
//sendError(1,$sql_query);
$stmt = $db->prepare($sql_query);
if($stmt === false) sendError('Error preparing Statement');
if($stmt === false) sendError(1,'Error preparing Statement');
//Присваеваем параметру двоичную информацию (Внимание! Только 1 параметр может быть в 1 записи (почему?))
$pos_v = 0;
@ -540,7 +534,7 @@
try
{ $res = $stmt->execute();
} catch (Exception $e)
{ sendError($e->getMessage()."\n".$sql_query);
{ sendError(1,$e->getMessage()."\n".$sql_query);
}
$result = $stmt->fetch(PDO::FETCH_NUM); //$obj_id
if($result[0]==''){ $result[0]=$obj_id; }
@ -551,13 +545,12 @@
Exit();
}else
{
sendError('Не найден запрошенный узел: "'.$typename.'"!');
sendError(1,'Не найден запрошенный узел: "'.$typename.'"!');
}
}else
if ($fn==3) //удаление (результат id записи)
{
session_write_close(); //Разблокируем сессионный файл так как запросы могут быть достаточно долгими
//if (!isset($_SESSION['USER_ID']) || $_SESSION['USER_ID']=='') sendError('Вы не авторизованы! '.$_SERVER['PHP_SELF']);
$nodeType=findFirstNode($reqNode,"type");
$typename=$nodeType->getAttribute("n");
@ -576,7 +569,7 @@
try
{ $res = $db->query($sql_query);
}catch (Exception $e)
{ sendError($e->getMessage());
{ sendError(1,$e->getMessage());
}
//записываем id удалённой записи для удаления без перезагрузки страницы через javascript
$xmlstring="";
@ -590,13 +583,12 @@
Exit();
}else
{
sendError('Не найден запрошенный узел: "'.$typename.'"!');
sendError(1,'Не найден запрошенный узел: "'.$typename.'"!');
}
}else
if ($fn==4 || $fn==11) //взять данные из базы по переданным значениям фильтра ($fn==11 для обновления записи у клиента после вставки или редактировании)
{
session_write_close(); //Разблокируем сессионный файл так как запросы могут быть достаточно долгими
//if (!isset($_SESSION['USER_ID']) || $_SESSION['USER_ID']=='') sendError('Вы не авторизованы! 4'.$_SERVER['PHP_SELF']);
$rowspagecount = 100; //записей на страницу
$nTypeR=findFirstNode($reqNode,'type');
@ -636,12 +628,12 @@
$sql_query=str_replace('${_order}',findNodeOnAttribute(findFirstNode($currNode,'objects-list'), "column","n",$objListR->getAttribute("order"))->getAttribute("order"),$sql_query);
}else $sql_query=str_replace('${_order}','1',$sql_query);
//sendError($sql_query);
//sendError(1,$sql_query);
//Выполняем запрос
try
{ $res = $db->query($sql_query);
} catch (Exception $e)
{ sendError($e->getMessage().' '.$sql_query);
{ sendError(1,$e->getMessage().' '.$sql_query);
}
//Формируем ответ
$pagecount=ceil($res->rowCount()/$rowspagecount); //Кол-во страниц
@ -677,6 +669,7 @@
}
//перебираем RS и строим XML только из тех столбцов которые записанны в секци objects-list поля column в не зависимости от их видимости
/*
$xmlstring='';
$xmlstring.='<?xml version="1.0" encoding="utf-8"?>'."\n";
$xmlstring.='<metadata fn="'.$fn.'"><type n="'.$typename.'" pc="'.$pagecount.'" pp="'.$pagepos.'">'."\n";
@ -718,10 +711,11 @@
{
if(array_key_exists($nextnode->getAttribute("n"),$row))
{
$xmlstring.='<![CDATA['.$row[$nextnode->getAttribute("n")].']]>';
$field = $nextnode->getAttribute("n");
$xmlstring.='<![CDATA['.$row[$field].']]>';
}else
{
sendError("Column \"".$nextnode->getAttribute("n")."\" not exists in \"$typename\" for select!");
sendError(1,"Column \"".$nextnode->getAttribute("n")."\" not exists in \"$typename\" for select!");
}
}
$nextnode = $nextnode->nextSibling;
@ -730,21 +724,87 @@
}
$res->closeCursor();
$xmlstring.='</type></metadata>'."\n";
//sendError('pos1='.$xmlstring);
header('Content-type: text/xml');
echo $xmlstring;
*/
$obj = new StdClass();
$obj->errorCode=0;
$obj->errorMessage = '';
$obj->fn=$fn;
$obj->n=$typename;
$obj->pc=$pagecount;
$obj->pp=$pagepos;
//Перечисляю название выбираемых столбцов через запятую (почему в JAVA версии этого куска кода нет?)
$obj->objects_list=[];
$nextnode=findNode($currNode,'objects-list')->firstChild;
while ($nextnode)
{
if ($nextnode->nodeName=='column')
{
array_push($obj->objects_list,$nextnode->getAttribute("n"));
}
$nextnode = $nextnode->nextSibling;
}
$obj->data=[];
$node=findFirstNode($reqNode,'objects-list');
$pos=-1;
while ($row = $res->fetch(PDO::FETCH_ASSOC))// $row - ассоциативный массив значений, ключи - названия столбцов
{
$pos++;
if (($pagepos!=-1)&&(($pos<($pagepos*$rowspagecount))||($pos>=$pagepos*$rowspagecount+$rowspagecount))) { continue; }
array_push($obj->data,new StdClass());
//разрешать или запрещять редактировать запись надо проверять в хранимке а также запрещять либо разрешать редактировать колонку
//для каждой записи формируеться строка настроек со значениями что нужно запретить в таком виде "iuds"
$access=''; //u = enable update field, d = enable delete field
if(!array_key_exists("_u",$row)) { $access.="u"; } else { $access.=$row["_u"]; }
if(!array_key_exists("_d",$row)) { $access.="d"; } else { $access.=$row["_d"]; }
if(array_key_exists($currNode->getAttribute("ObjectID"),$row)) {
end($obj->data)->id=$row[$currNode->getAttribute("ObjectID")];
end($obj->data)->a=$access;
}else {
end($obj->data)->id="";
end($obj->data)->a=$access;
}
end($obj->data)->row=[];
$nextnode=findNode($currNode,'objects-list')->firstChild;
while ($nextnode)
{
if ($nextnode->nodeName=='column')
{
if(array_key_exists($nextnode->getAttribute("n"),$row))
{
$field = $nextnode->getAttribute("n");
array_push(end($obj->data)->row,$row[$field]);
}else
{
sendError(1,"Column \"".$nextnode->getAttribute("n")."\" not exists in \"$typename\" for select!");
}
}
$nextnode = $nextnode->nextSibling;
}
}
$res->closeCursor();
header('Content-Type: application/json; charset=utf-8');
header("Cache-Control: no-cache, must-revalidate");
echo json_encode($obj);
exit;
}else
{
sendError("Не найден запрошеный узел!");
sendError(1,"Не найден запрошеный узел!");
}
}else
if ($fn==5) //вернуть клиенту данные по id для редактирования одной записи
{
session_write_close(); //Разблокируем сессионный файл так как запросы могут быть достаточно долгими
//if (!isset($_SESSION['USER_ID']) || $_SESSION['USER_ID']=='') sendError('Вы не авторизованы! '.$_SERVER['PHP_SELF']);
$sql_query='';
$node=findFirstNode($reqNode,'type');
@ -766,16 +826,16 @@
$sql_query=str_replace('${_user_id}',getSQLValue(gettype($_SESSION['USER_ID']),$_SESSION['USER_ID']),$sql_query);
}
}
//sendError($sql_query);
//sendError(1,$sql_query);
try
{
$res = $db->query($sql_query);
} catch (Exception $e)
{ sendError($e->getMessage());
{ sendError(1,$e->getMessage());
}
if(strpos($db_connection, 'sqlite')===false) //Для SQLite не работает rowCount()
{
if($res->rowCount()!=1) sendError("Количество записей не равно одному!");
if($res->rowCount()!=1) sendError(1,"Количество записей не равно одному!");
}
$xmls='';
@ -786,7 +846,7 @@
}
if($xmls=='')
{
sendError("Metadata node \"".$name."\" is empty!");
sendError(1,"Metadata node \"".$name."\" is empty!");
}
//загружаем мета данные и смотрим какие поля должны передать клиенту
@ -795,7 +855,7 @@
{
$mdoc->loadXML($xmls);
} catch (Exception $e)
{ sendError($e->getMessage());
{ sendError(1,$e->getMessage());
}
//находим нужный узел
$node=findNodeOnAttribute($mdoc->documentElement, "type","n",$typename);
@ -830,7 +890,7 @@
if(array_key_exists($nextnode->getAttribute("cd"), $row)) {
$xmlstring .= '<prop n="' . $nextnode->getAttribute("n") . '"><![CDATA[' . $row[$nextnode->getAttribute("cd")] . ']]></prop>' . "\n";
}else{
sendError('Поле "'.$nextnode->getAttribute("cd").'" не найдено в результирующем наборе!');
sendError(1,'Поле "'.$nextnode->getAttribute("cd").'" не найдено в результирующем наборе!');
}
}
else {
@ -838,10 +898,10 @@
}
}else
{
sendError('Поле "'.$nextnode->getAttribute("n").'" не найдено в результирующем наборе!');
sendError(1,'Поле "'.$nextnode->getAttribute("n").'" не найдено в результирующем наборе!');
}
} catch (Exception $e) { sendError($e->getMessage()); }
} catch (Exception $e) { sendError(1,$e->getMessage()); }
}
$nextnode = $nextnode->nextSibling;
}
@ -856,7 +916,6 @@
if ($fn==6) //вернуть клиенту данные колонки таблицы для заполнения выпадающего списка SELECT либо выборка названия поля типа object
{
session_write_close(); //Разблокируем сессионный файл так как запросы могут быть достаточно долгими
//if (!isset($_SESSION['USER_ID']) || $_SESSION['USER_ID']=='') sendError('Вы не авторизованы! '.$_SERVER['PHP_SELF']);
$tNodeR=findFirstNode($reqNode,'type');
$typename=$tNodeR->getAttribute("n"); //Название принятого узла
@ -868,7 +927,7 @@
$currNode=getMetadataNode($typename);
if($currNode==null) sendError("Not find \"".$typename."\"!");
if($currNode==null) sendError(1,"Not find \"".$typename."\"!");
$objXMLDocument=$currNode->ownerDocument;
$objListR = findFirstNode($tNodeR,'objects-list'); //Из запроса
@ -899,7 +958,7 @@
try
{ $res = $db->query($sql_query);
} catch (Exception $e)
{ sendError($e->getMessage());
{ sendError(1,$e->getMessage());
}
//выбираем данные из базы и отправляем клиенту
@ -918,7 +977,7 @@
$val.=$row[$columns[$i]];
}else
{
sendError("Column \"$columns[$i]\" not exists in \"$typename\" for select to drop down list!");
sendError(1,"Column \"$columns[$i]\" not exists in \"$typename\" for select to drop down list!");
}
}
$xmlstring.='<![CDATA['.$val.']]>';
@ -934,6 +993,8 @@
$cmd=getCdataValue(findFirstNode($reqNode,"cmd"));
$login=getCdataValue(findFirstNode($reqNode,"login"));
$password=getCdataValue(findFirstNode($reqNode,"password"));
$key=getCdataValue(findFirstNode($reqNode,"key"));
$time=getCdataValue(findFirstNode($reqNode,"time"));
$guid=getCdataValue(findFirstNode($reqNode,"guid")); //Зачем коментил?
if($cmd==0) //Restore password by email
@ -973,8 +1034,8 @@
$html .= '<b>' . $password . '</b>';
$html .= '</body></html>';
//mail($login,'rigor.kz','Not implement',"Content-type: text/html; charset=utf-8\r\nFrom: rigor Site <info@rigor.kz>");
if (!mail($login, 'Password for transit.istt.kz', $html, "Content-type: text/html; charset=utf-8\r\nFrom: Transit Site <no-reply@istt.kz>")) {
sendError("Failed to send mail to: " . $row["email"]);
if (!mail($login, 'Password for monitoring', $html, "Content-type: text/html; charset=utf-8\r\nFrom: Transit Site <no-reply@istt.kz>")) {
sendError(1,"Failed to send mail to: " . $row["email"]);
}
}
}
@ -1000,7 +1061,7 @@
try
{ $db->exec($sql);
} catch (Exception $e)
{ sendError($e->getMessage());
{ sendError(1,$e->getMessage());
}
unset($_SESSION['USER_ID']);
@ -1030,6 +1091,8 @@
$xs.=' <surname><![CDATA['.$row['surname'].']]></surname>'."\n";
$xs.=' <patronymic><![CDATA['.$row['patronymic'].']]></patronymic>'."\n";
$xs.=' <company_id><![CDATA['.$row['company_id'].']]></company_id>'."\n";
$xs.=' <expiration><![CDATA['.$row['expiration'].']]></expiration>'."\n";
$xs.=' <overdue><![CDATA['.$row['overdue'].']]></overdue>'."\n";
}
}
$xs.='</metadata>';
@ -1046,16 +1109,34 @@
$name='';
$surname='';
$patronymic='';
$expiration=false;
$overdue=false;
$sql="select * from ".$Schema."p__Login(".getSQLValue($idType,$_SESSION['USER_ID']).",'$login','$password',null,null,null);";
/*
$ga=new GoogleAuthenticator;
$code=$ga->getCode($user->ga_secret);
if ($code!=$_POST['code']) return new AuthError('invalid code');
*/
$res = $db->query($sql);
if($res->rowCount()>0)
{ $result = $res->fetch(PDO::FETCH_ASSOC);
{
$result = $res->fetch(PDO::FETCH_ASSOC);
$ans='1';
$_SESSION['USER_ID']=$result['id'];
$name=$result['name'];
$surname=$result['surname'];
$patronymic=$result['patronymic'];
$expiration=$result['expiration']; //Дата смены пароля
$overdue=$result['overdue']; //Просрочен ли пароль
//Проверяю на соответствие токену TOPT если секретный ключ задан
if($result['secret']){
$secret = Base32::decode($result['secret']);
$genkey = (new Totp('sha1',0,60))->GenerateToken($secret,$time);
if($key != $genkey) {
$ans = '0';
$_SESSION['USER_ID'] = '';
}
}
}
$xs='<?xml version="1.0" encoding="utf-8"?>'."\n";
$xs.='<metadata fn="7">'."\n";
@ -1065,13 +1146,15 @@
$xs.=' <name><![CDATA['.$name.' '.$surname.' '.$patronymic.']]></name>'."\n";
$xs.=' <sesid><![CDATA['.session_id().']]></sesid>'."\n";
$xs.=' <sesname><![CDATA['.session_name().']]></sesname>'."\n";
$xs.=' <expiration><![CDATA['.$expiration.']]></expiration>'."\n";
$xs.=' <overdue><![CDATA['.$overdue.']]></overdue>'."\n";
$xs.='</metadata>';
header('Content-type: text/xml');
header("Cache-Control: no-cache, must-revalidate");
echo $xs;
exit();
}else{
sendError('Command "'.$cmd.'" not find!');
sendError(1,'Command "'.$cmd.'" not find!');
}
}else
@ -1099,14 +1182,15 @@
}
session_write_close(); //Разблокируем сессионный файл так как запросы могут быть достаточно долгими
//if (!isset($_SESSION['USER_ID']) || $_SESSION['USER_ID']=='') sendError(trt('You are not logged in!'));
//Выбираем информацию о текущем пользователе
$name='';
$sql="select Coalesce(surname,'') || ' ' || Coalesce(name,'') || ' ' || Coalesce(patronymic,'') as name from ".$Schema."_users where id=".$_SESSION['USER_ID'].";";
$res = $db->query($sql);
if($res->rowCount()>0)
{ $result = $res->fetch(PDO::FETCH_ASSOC);
$sql="select Coalesce(surname,'') || ' ' || Coalesce(name,'') || ' ' || Coalesce(patronymic,'') as name from ".$Schema."_users where id=:user_id;";
$stmt = $db->prepare($sql);
$stmt->bindValue(':user_id', $_SESSION['USER_ID'], PDO::PARAM_INT);
$res=$stmt->execute();
if($res && $stmt->rowCount()>0)
{ $result = $stmt->fetch(PDO::FETCH_NUM);
$name='<i>'.$result['name'].'</i><br>';
}
$res=null; //Чтоб сработал сборщик мусора, а то вываливается ошибка: "Cannot execute queries while other unbuffered queries are active".
@ -1165,9 +1249,9 @@
try
{ $res = $db->query($sql_query);
} catch (Exception $e)
{ sendError($e->getMessage());
{ sendError(1,$e->getMessage());
}
if($res->rowCount()!=1) sendError(trt('The number of records is not equal to one!').' '.$sql_query);
if($res->rowCount()!=1) sendError(1,trt('The number of records is not equal to one!').' '.$sql_query);
$columns=explode(",",$nextnode->getAttribute('FieldCaption'));
@ -1217,7 +1301,7 @@
try
{ $res = $db->query($sql_query);
} catch (Exception $e)
{ sendError($e->getMessage().$sql_query);
{ sendError(1,$e->getMessage().$sql_query);
}
//Сохраняем результсет в файл в виде HTML с расширением XLS
@ -1305,7 +1389,7 @@
//deleteTempFiles($dir);
}else
{
sendError(trt('Not found the requested node:').' "'.$typename.'"!');
sendError(1,trt('Not found the requested node:').' "'.$typename.'"!');
}
}else
@ -1369,7 +1453,7 @@
}
if($xmls=='')
{
sendError("Metadata node \"".$name."\" is empty!");
sendError(1,"Metadata node \"".$name."\" is empty!");
}
//Ищем поле в метаданных
@ -1440,7 +1524,7 @@
}
}else
{
sendError("Неизвестная функция \"$fn\"!");
sendError(1,"Неизвестная функция \"$fn\"!");
}

View File

@ -1,4 +1,4 @@
//Copyright (C) 2008 Ivanov I.M. ivanov.i@istt.kz
//Copyright (C) 2008 Igor
//For find non english chars: [^\x00-\x7F]+
function callWindow(uid,id,i)
@ -49,18 +49,14 @@ class SRec
applyReq(req,fn,node,xmldoc)
{
//alert2(trt('Alert'),getXMLNodeSerialisation(node));
this.hideProgressBar();
this.xmldoc=node.ownerDocument; //xmldoc;
if (fn==-1) //Information alert
{
let fullText = findFirstNode(node,'#cdata-section').nodeValue;
if(node.errorCode>0) {
let fullText = node.errorMessage;
let smallText = '';
let pos1=fullText.indexOf('[[');
let pos2=fullText.indexOf(']]');
if(pos1>=0 && pos2>=0 && pos1<pos2) smallText=fullText.substring(pos1+2, pos2);
if(fullText.indexOf("id456[[")>=0){ //Если есть идентификатор того что это перезапись
let okFunc=()=>{
this.setValue('seq',0);
@ -76,7 +72,11 @@ class SRec
else
alert2(trt('Alert'), fullText);
}
}else
return;
}
this.xmldoc=node.ownerDocument; //xmldoc;
if (fn==0)
{
//alert2(trt('Alert'),getXMLNodeSerialisation(node));
@ -413,28 +413,35 @@ class SRec
}
//we pass the id to the object filter column_n - the name of the filter
setFilterObject(TypeName, column_n, id, filter)
setFilterObject(TypeName, column_n, id, nodeFilter)
{
let node=findFirstNodeOnAttribute(this.nodeMetadata,'column','n',column_n);
if(node!==null)
{
let name=node.getAttribute("FieldCaption");
getCdata(node).nodeValue=id;
//we request data from the server to fill in the comments on the record id
let prop=document.getElementById('filter_'+this.uid+'_'+column_n);
if(prop!==null) prop.value = id;
//Request a comment on the record id from the server
let xml = '';
if(filter!=''){
if(nodeFilter!=null){
//Настройка для последующего вызова
xml='<column n="'+column_n+'"><type n="' + TypeName + '"><objects-list>'+filter+'</objects-list></type></column>';
xml='<column n="'+column_n+'"><type n="' + TypeName + '"><objects-list>'+getXMLNodeSerialisation(nodeFilter)+'</objects-list></type></column>';
applyNodeToNode(CreateXMLDOC(xml).documentElement, node, "n");
//Настройка для фильтрации списка
xml = '<?xml version="1.0" encoding="utf-8"?>' +
'<metadata fn="6"><type n="' + TypeName + '" c="' + name + '" pn="' + column_n + '" fn="' + name + '">' +
'<objects-list>' + filter + '</objects-list>' +
'</type></metadata>';
if(node.getAttribute("selector")=="combo") {
xml = '<?xml version="1.0" encoding="utf-8"?>' +
'<metadata fn="6"><type n="' + TypeName + '" c="' + name + '" pn="' + column_n + '" fn="' + name + '">' +
'<objects-list>' + getXMLNodeSerialisation(nodeFilter) + '</objects-list>' +
'</type></metadata>';
}else{
xml = '<?xml version="1.0" encoding="utf-8"?>' +
'<metadata fn="6"><type n="' + TypeName + '" c="' + name + '" pn="' + column_n + '" fn="' + name + '">' +
'<objects-list><filter><column n="id"><![CDATA[' + id + ']]></column></filter></objects-list>' +
'</type></metadata>';
}
}else{
xml = '<?xml version="1.0" encoding="utf-8"?>' +
'<metadata fn="6"><type n="' + TypeName + '" c="' + name + '" pn="' + column_n + '" fn="' + name + '">' +
@ -541,7 +548,7 @@ class SRec
let td,tr,td1,td2;
let nodeFilter=null;
let tablefilter=document.getElementById('idfilter'+this.uid);
if (tablefilter.tBodies==null) alert2(trt('Alert'),'tablefilter=null');
if (tablefilter==null || tablefilter.tBodies==null) alert2(trt('Alert'),'tablefilter=null');
let nodeType=findFirstNode(node, "type");
this.f_pI=nodeType.getAttribute("ins");//access rights
this.f_pU=nodeType.getAttribute("upd");
@ -662,7 +669,6 @@ class SRec
//singleClick: true,
onSelect: function(){ this.hide(); }
});
}else
if (columnNode.getAttribute("vt")==="date")
{
@ -759,7 +765,7 @@ class SRec
input.classList.add('DBMS');
input.style.cssText="width: 100%;";
input.setAttribute("type","text");
input.onkeydown=function(event){if(event.which==13) event.which=9;};
input.onkeydown=(e)=>{ if(e==null) e=window.event; if(e.keyCode==13) { this.appendFilter(); this.sendFilter(-1,0); }};
input.setAttribute("name",columnNode.getAttribute("n"));
if(columnNode.getAttribute("size")!=null)
input.setAttribute("maxlength",columnNode.getAttribute("size"),0);
@ -805,7 +811,7 @@ class SRec
input.classList.add('DBMS');
input.style.cssText="width: 100%;";
input.setAttribute("type","text");
input.onkeydown=function(){ if(event.keyCode==13) event.keyCode=9; };
input.onkeydown=(e)=>{ if(e==null) e=window.event; if(e.keyCode==13) { this.appendFilter(); this.sendFilter(-1,0); }};
input.setAttribute("name",columnNode.getAttribute("n"));
if(columnNode.getAttribute("size")!=null)
input.setAttribute("maxlength",columnNode.getAttribute("size"),0);
@ -838,7 +844,7 @@ class SRec
input.setAttribute("type","text");
button.classList.add('DBMS');
input.style.cssText="width: 100%;";
input.onkeydown=function(){ if(event.keyCode==13) event.keyCode=9; };
input.onkeydown=(e)=>{ if(e==null) e=window.event; if(e.keyCode==13) { this.appendFilter(); this.sendFilter(-1,0); }};
input.setAttribute("name",columnNode.getAttribute("n"));
if(columnNode.getAttribute("size")!=null)
input.setAttribute("maxlength",columnNode.getAttribute("size"),0);
@ -920,15 +926,15 @@ class SRec
let input = document.createElement('input');
input.classList.add('DBMS');
//After pressing Enter we pass the entered line to the server
input.onkeydown=function(obj,val1,val2,val3,val4){
input.onkeydown=function(obj,typeName,name,value,htmlid,filterName){
return function(e){
if(e==null) e=window.event;
if(e.keyCode==13){
obj.callFilterVal(val1,val2,-1,val3.value,val4);
obj.callFilterVal(typeName,name,-1,value.value,htmlid,filterName);
return false;
}
};
}(this,object,fc,input,columnNode.getAttribute("n"));
}(this,object,fc,input,columnNode.getAttribute("n"),columnNode.getAttribute("fn"));
input.style.cssText="width: 100%; height:22px; line-height:22px;";
input.setAttribute("type","text");
@ -1084,18 +1090,21 @@ class SRec
//id - id of record if it is necessary to return only the description, if -1 then it is not considered
//value - filter value text field
//htmlid - field name in filter n
callFilterVal(typeName,name,id,value,htmlid)
callFilterVal(typeName,name,id,value,htmlid,filterName)
{
if(value!="")
{
if(this.request.callServer(ScriptName,'<?xml version="1.0" encoding="utf-8"?><metadata fn="6"><type n="'+typeName+'" c="'+name+'" pn="'+htmlid+'" id="'+id+'"><objects-list><filter><column n="'+name+'"><![CDATA['+value+']]></column></filter></objects-list></type></metadata>',true))
let xml='<?xml version="1.0" encoding="utf-8"?><metadata fn="6"><type n="'+typeName+'" c="'+name+'" pn="'+htmlid+'" id="'+id+'"><objects-list><filter>';
xml+='<column n="'+filterName+'"><![CDATA['+value+']]></column>';
xml+='</filter></objects-list></type></metadata>';
if(this.request.callServer(ScriptName,xml,true))
{
this.showProgressBar();
}
}else
{
document.getElementById("filter_"+htmlid).value=-1;
appendFilter();
document.getElementById("filter_"+this.uid+"_"+htmlid).value='';
this.appendFilter();
this.sendFilter(-1,0);
}
}
@ -1156,15 +1165,15 @@ class SRec
}
//Function to insert data into a table.
//node - A node with data.
//node - A JSON object with data.
//clear - Whether to clear all entries.
insertRows(node,clear)
{
let theTable = document.getElementById('thetable'+this.uid); //Data table
let nodeType=findFirstNode(node, "type");
let pagecount=nodeType.getAttribute("pc"); //total pages
if((nodeType.getAttribute("pp")!=null)&&(nodeType.getAttribute("pp")!=-1)) this.pagepos=nodeType.getAttribute("pp");
//let nodeType=findFirstNode(node, "type");
let pagecount=node.pc; //total pages
this.pagepos=node.pp;
if(clear || this.f_nodeData==null)
{ this.f_nodeData=node;
@ -1197,6 +1206,10 @@ class SRec
let newCell = newRow.insertCell(-1);
newCell.style.backgroundColor = bgColor;
newCell.style.cursor="pointer";
if (this.pagepos==i) {
newCell.style.fontWeight = "bold";
newCell.style.fontSize = "large";
}
newCell.appendChild(document.createTextNode(i+1));
//Upon clicking, a filter with old values is used only with a different page number.
newCell.onclick=function(obj,page){
@ -1218,123 +1231,115 @@ class SRec
}
}else
{
let tmpNR=findFirstNode(this.f_nodeData, "type");
let nodeRecord = nodeType.firstChild;
while (nodeRecord != null)
{
if(nodeRecord.nodeName=="record")
{
tmpNR.appendChild(nodeRecord.cloneNode(true) );
}
nodeRecord = nodeRecord.nextSibling;
for(let i=0;i<node.data.length;i++){
Object.assign(this.f_nodeData.data, node.data[i])
}
}
//Add new entries
let nColor=findNumNodeOnAttribute(findNodeOnPath(this.nodeMetadata,"type/objects-list"),"column","n","color");
let TypeName = nodeType.getAttribute("n");
let TypeName = node.n;
let i=0; //The position should be received from the server.
let nodeRecord = nodeType.firstChild;
while (nodeRecord != null)
{
if(nodeRecord.nodeName=="record")
for(let i=0;i<node.data.length;i++){
let bgColor='';
if (i%2==0) bgColor='var(--row-color-1)'; else bgColor='var(--row-color-2)';
//if(nColor>=0) //Color from Result
//{
// let bgColorT=findNodeOnNum(nodeRecord,"#cdata-section",nColor).nodeValue;
// if(bgColorT!="") bgColor=bgColorT;
//}
let id=node.data[i].id;
//add rows to an existing record table
let tr = document.createElement('tr');
tr.onmouseover=function(){ this.style.backgroundColor="var(--btn-color2)"; };
tr.onmouseout=function(val1,val2){return function(){val1.style.backgroundColor=val2;}}(tr,bgColor);
tr.setAttribute("id",id+'_'+this.uid);
tr.style.backgroundColor=bgColor;
//sequential record number
let td = document.createElement('td');
td.appendChild( document.createTextNode( i+1+100*this.pagepos ) );
tr.appendChild(td);
//CheckBuck to delete records
td = document.createElement('td');
td.style.cssText="text-align: center;";
if(!(this.f_pD!="1" || node.data[i].a.indexOf("d")==-1))
{
let bgColor='';
let i=theTable.rows.length; //number of rows in the table
if (i%2==0) bgColor='var(--row-color-1)'; else bgColor='var(--row-color-2)';
if(nColor>=0) //Color from Result
{
let bgColorT=findNodeOnNum(nodeRecord,"#cdata-section",nColor).nodeValue;
if(bgColorT!="") bgColor=bgColorT;
}
let id=nodeRecord.getAttribute("id");
//add rows to an existing record table
let tr = document.createElement('tr');
tr.onmouseover=function(){ this.style.backgroundColor="var(--btn-color2)"; };
tr.onmouseout=function(val1,val2){return function(){val1.style.backgroundColor=val2;}}(tr,bgColor);
tr.setAttribute("id",id+'_'+this.uid);
tr.style.backgroundColor=bgColor;
//sequential record number
let td = document.createElement('td');
td.appendChild( document.createTextNode( i+100*this.pagepos ) );
tr.appendChild(td);
//CheckBuck to delete records
td = document.createElement('td');
td.style.cssText="text-align: center;";
if(!(this.f_pD!="1" || nodeRecord.getAttribute("a").indexOf("d")==-1))
{
let checkbox = document.createElement('input');
checkbox.classList.add('DBMS');
this.masChBox.push(checkbox);
//checkbox.disabled=true;
checkbox.setAttribute("type","checkbox");
checkbox.setAttribute("value",id);
checkbox.style.cssText="font: normal normal normal 11px normal Arial;";
td.appendChild( checkbox );
}
tr.appendChild(td);
//for each column we make a column
let colN=0; //column number
let cdataNode = nodeRecord.firstChild;
while (cdataNode!=null)
{
if(cdataNode.nodeName=="#cdata-section")
{
if(this.masVis[colN])
{
td = document.createElement('td');
if((this.f_pU=="1")||(this.f_State=="1")){
td.style.cssText="cursor: pointer;";
}
let textNode=document.createTextNode(cdataNode.nodeValue);
td.setAttribute("id",id+this.masCL[colN].getAttribute("n")); //so that you can identify each record when you update
td.appendChild(textNode);
//if in the metadata for this column there is a reference object then add a link
if (this.masCT[colN]!=null)
{
//Opening a new window in the filter is passed to the current values of the row
td.style.cssText="cursor: pointer; background-color: var(--btn-color); font-weight: bold;";
td.onmouseover=function(){
this.style.backgroundColor="var(--btn-color2)";
};
td.onmouseout=function(){
this.style.backgroundColor="var(--btn-color)";
};
//when you click on a cell, the sent filter is prefilled with variables in accordance with the id of the pressed line
//in the function we pass the cell id and the column number
td.onclick=function(obj,val1,val2){
return function(){
obj.callWindow(val1,val2);
}
}(this,id,colN);
}else
{
if((this.f_pU=="1" && nodeRecord.getAttribute("a").indexOf("u")!=-1)||(this.f_State=="1"))
{
td.onclick=function(thiz,val1,val2){
return function(){thiz.updateRecord(val1);};
}(this,id);
}else
{
td.style.cssText="cursor: default;";
}
}
tr.appendChild(td);
}
colN++;
}
cdataNode = cdataNode.nextSibling;
}
theTable.tBodies[0].appendChild(tr);
let checkbox = document.createElement('input');
checkbox.classList.add('DBMS');
this.masChBox.push(checkbox);
//checkbox.disabled=true;
checkbox.setAttribute("type","checkbox");
checkbox.setAttribute("value",id);
checkbox.style.cssText="font: normal normal normal 11px normal Arial;";
td.appendChild( checkbox );
}
nodeRecord = nodeRecord.nextSibling;
tr.appendChild(td);
//for each column we make a column
let colN=0; //column number
//let cdataNode = nodeRecord.firstChild;
//while (cdataNode!=null)
//this.access[obj.data[i].row[0]]=obj.data[i].row[1];
for(let j=0;j<node.data[i].row.length;j++)
{
if(this.masVis[colN])
{
td = document.createElement('td');
if((this.f_pU=="1")||(this.f_State=="1")){
td.style.cssText="cursor: pointer;";
}
let textNode;
if(node.data[i].row[j]!=null) textNode=document.createTextNode(node.data[i].row[j]);
else textNode=document.createTextNode("");
//td.setAttribute("id",id+this.masCL[colN].getAttribute("n")); //so that you can identify each record when you update
td.setAttribute("id",id+this.masCL[colN].n); //so that you can identify each record when you update
td.appendChild(textNode);
//if in the metadata for this column there is a reference object then add a link
if (this.masCT[colN]!=null)
{
//Opening a new window in the filter is passed to the current values of the row
td.style.cssText="cursor: pointer; background-color: var(--btn-color); font-weight: bold;";
td.onmouseover=function(){
this.style.backgroundColor="var(--btn-color2)";
};
td.onmouseout=function(){
this.style.backgroundColor="var(--btn-color)";
};
//when you click on a cell, the sent filter is prefilled with variables in accordance with the id of the pressed line
//in the function we pass the cell id and the column number
td.onclick=function(obj,val1,val2){
return function(){
obj.callWindow(val1,val2);
}
}(this,id,colN);
}else
{
if((this.f_pU=="1" && node.data[i].a.indexOf("u")!=-1)||(this.f_State=="1"))
{
td.onclick=function(thiz,val1,val2){
return function(){thiz.updateRecord(val1);};
}(this,id);
}else
{
td.style.cssText="cursor: default;";
}
}
tr.appendChild(td);
}
colN++;
}
theTable.tBodies[0].appendChild(tr);
}
this.updateSize();
}
@ -1411,9 +1416,9 @@ class SRec
}
let rec=new SRec();
rec.opener=this;
rec.create();
//rec.f_State=1; TODO then finish the job
//rec.f_PropName=nodeColu.getAttribute("n");
rec.create(null);
rec.f_State=1; //Зачем коментил?
rec.f_PropName=nodeColu.getAttribute("n"); //Зачем коментил?
rec.f_Settings=settings;
rec.f_TypeName=TypeName;
rec.win.setLeftTop(pageX-250,pageY-10);
@ -1444,7 +1449,7 @@ class SRec
//Settings.add(0,xmlString)
//wishWin = window.open("showrecord.html?name="+typeName,typeName,"width=800,height=600,menubar=no,location=no,resizable=yes,scrollbars=yes");
let rec=new SRec();
rec.create();
rec.create(null);
//rec.f_State=1; not used
//rec.f_PropName=propname; not used
rec.f_Settings=xmlString;
@ -1457,11 +1462,9 @@ class SRec
}
}
//find the node cdata in the data by the record id and column name
getDataC(id,col)
{
let i=0;
let b=false;
//Get column number by name
getColN(name){
let i=-1;
//determine the sequence number of the column
let node=findNodeOnPath(this.nodeMetadata,"type/objects-list");
let nodeCol = node.firstChild;
@ -1470,73 +1473,68 @@ class SRec
if(nodeCol.nodeName=="column")
{
if(nodeCol.getAttribute("n")==col){
b=true;
break;
}
i++;
}
nodeCol = nodeCol.nextSibling;
}
if(!b)return null;
//we search for value in result set
node=findFirstNode(this.f_nodeData, 'type');
let nodeRec=findNodeOnAttribute(node, 'record', 'id', id);
return findNodeOnNum(nodeRec,"#cdata-section",i);
return i;
}
//find the value in the result set by the id of the record and the name of the column
getData(id,col)
{
if(findNode(this.nodeMetadata,'type').getAttribute("ObjectID")==col) return id;
let cdt=this.getDataC(id,col);
if(cdt!=null) return cdt.nodeValue; else return '';
if(findNode(this.nodeMetadata,'type').getAttribute("ObjectID")==col)
return id;
let pos=this.getColN(col);
if(pos>=0){
for(let i=0;i<this.f_nodeData.data.length;i++){
if(this.f_nodeData.data[i].id=id){
return this.f_nodeData.data[i].row[pos];
}
}
}
return '';
}
//look for a string by id and update the values (TODO consecutively without hidden fields)
updateRows(node)
{
//We sort through the received records and update the values
let nodeRecord = findNode(node,"type").firstChild
while (nodeRecord != null)
for(let i=0;i<node.data.length;i++)
{
if(nodeRecord.nodeName=="record")
let id=node.data[i].id;
let tr=document.getElementById(id+'_'+this.uid);
if (tr==null)
{
let ii=0;
this.insertRows(node,false); //If not then insert
}else //Update fields if editing
{
//Updating data in a data object
for(let ii=0;ii<this.f_nodeData.data.length;ii++){
if(this.f_nodeData.data[ii].id==id) {
this.f_nodeData.data[ii].row=node.data[i].row;
}
}
//Updating data in an HTML table
let jj=0;
let id=nodeRecord.getAttribute("id");
let tr=document.getElementById(id+'_'+this.uid);
if (tr==null)
tr.style.textDecoration="underline";
for(let j=0;j<node.data[i].row.length;j++)
{
this.insertRows(node,false); //If not then insert
}else
{
tr.style.textDecoration="underline";
let cdataNode = nodeRecord.firstChild;
while (cdataNode!=null)
if(this.masCL[j].getAttribute("visible")!="0")
{
if (cdataNode.nodeName=="#cdata-section")
{
let cd=this.getDataC(id,this.masCL[ii].getAttribute("n"));
if(cd!=null) cd.nodeValue=cdataNode.nodeValue;
if(this.masCL[ii].getAttribute("visible")!="0")
{
while(tr.childNodes[jj+2].childNodes[0])
tr.childNodes[jj+2].removeChild(tr.childNodes[jj+2].childNodes[0]);
tr.childNodes[jj+2].appendChild(document.createTextNode(cdataNode.nodeValue));
jj++;
}
ii++;
while(tr.childNodes[jj+2].childNodes[0]) {
tr.childNodes[jj+2].removeChild(tr.childNodes[jj + 2].childNodes[0]);
}
cdataNode = cdataNode.nextSibling;
let textNode;
if(node.data[i].row[j]!=null) textNode=document.createTextNode(node.data[i].row[j]);
else textNode=document.createTextNode("");
tr.childNodes[jj+2].appendChild(textNode);
jj++;
}
}
}
nodeRecord = nodeRecord.nextSibling;
}
}
@ -1629,14 +1627,10 @@ class SRec
let filter="";
let nodeType=findFirstNode(this.nodeMetadata, "type");
let nodeFilter=findNodeOnPath(nodeType,"objects-list/filter");
if (nodeFilter!=null)
{
filter=getXMLNodeSerialisation(nodeFilter)
}
//Send the id of the selected record to the parent of the selected record and close the window
//alert2(trt('Alert'),"id="+id+" f_PropName="+this.f_PropName+" f_TypeName="+this.f_TypeName);
this.opener.setFilterObject(this.f_TypeName, this.f_PropName, id, filter);
this.opener.setFilterObject(this.f_TypeName, this.f_PropName, id, nodeFilter);
this.win.Close();
}else{
let erec = new EdtRec("");
@ -1650,6 +1644,7 @@ class SRec
}else
if(this.f_State=="2") //Multiple choice (on the records of ticking TODO is not implemented)
{
alert2(trt('Alert'), 'TODO');
}
}
@ -1683,8 +1678,9 @@ class SRec
//Rebuild sequential numbering of rows (first column)
let theTable = document.getElementById('thetable'+this.uid); //data table
for(let i=1;i<theTable.rows.length;i++)
{while (theTable.rows[i].cells[0].childNodes[0]) //delete all childs
{theTable.rows[i].cells[0].removeChild(theTable.rows[i].cells[0].childNodes[0]);
{
while (theTable.rows[i].cells[0].childNodes[0]) //delete all childs
{ theTable.rows[i].cells[0].removeChild(theTable.rows[i].cells[0].childNodes[0]);
}
theTable.rows[i].cells[0].appendChild(document.createTextNode(i));
}

View File

@ -9,14 +9,14 @@ function trt(key)
if(val==null || val===undefined)
{
for(let item in g_translations) {
if(item.toLowerCase()==key.toLowerCase())
if(item.toLowerCase()==(''+key).toLowerCase())
{
val=g_translations[item];
break;
}
}
}
if(val==null || val===undefined) return key.replace(/_/g, ' ');
if(val==null || val===undefined) return (''+key).replace(/_/g, ' ');
else return val;
}
@ -28,7 +28,7 @@ function resizeDivTile(parent,minWidth)
if(parent==null) return;
let dx=Math.floor(parent.offsetWidth/(minWidth));
//console.log("parent.offsetWidth="+parent.offsetWidth+" minWidth="+minWidth+" margin="+margin+" dx="+dx);
//log.info("parent.offsetWidth="+parent.offsetWidth+" minWidth="+minWidth+" margin="+margin+" dx="+dx);
let addW=0;
for(let i=0;i<minWidth+2;i++)
@ -36,24 +36,24 @@ function resizeDivTile(parent,minWidth)
if(dx>=parent.offsetWidth/(minWidth+i))
{
addW=i-1;
//console.log("addW="+addW+" parent.offsetWidth/(minWidth+margin+i)="+(parent.offsetWidth/(minWidth+margin+i)));
//log.info("addW="+addW+" parent.offsetWidth/(minWidth+margin+i)="+(parent.offsetWidth/(minWidth+margin+i)));
break;
}
}
for(let i = 0; i < parent.children.length; i++) {
//console.log(parent.children[i].tagName);
//log.info(parent.children[i].tagName);
if(parent.children[i].tagName.toUpperCase()=='DIV')
{
parent.children[i].style.width = (minWidth+addW)+"px";
}
}
//console.log("minWidth+addW="+(minWidth+addW));
//log.info("minWidth+addW="+(minWidth+addW));
//Центрирую, путем добавления пространства с лева
parent.style.paddingLeft = Math.floor((parent.offsetWidth-(dx*(minWidth+addW)))/2) + "px";
//console.log("parent.style.paddingLeft="+parent.style.paddingLeft+" calc="+(Math.floor((parent.offsetWidth-(dx*(minWidth+addW)))/2)));
//log.info("parent.style.paddingLeft="+parent.style.paddingLeft+" calc="+(Math.floor((parent.offsetWidth-(dx*(minWidth+addW)))/2)));
}
//Получить уникальный идентификатор в рамках текущего NAMESPACE из глобальной переменной
@ -306,6 +306,59 @@ function confirm2(title,smallText,fullText,okFunc,cancelFunc)
return win;
}
//С поле ввода
function prompt2(title,smallText,fieldText,defaultText,okFunc,cancelFunc){
let win=new TWin();
win.BuildGUI(10,10);
win.setCaption(document.createTextNode(title));
let html='\n\
<table cellpadding="0" cellspacing="0" style="width: 100%; height: 100%;">\n\
<tr style="width: 100%;">\n\
<td colspan="3" style="text-align: center; vertical-align: middle; width: 100%;">'+smallText+'</td>\n\
</tr>\n\
<tr style="width: 100%;">\n\
<td colspan="3" style="width: 100%;">'+fieldText+'</td>\n\
</tr>\n\
<tr style="width: 100%;">\n\
<td colspan="3" style="width: 100%;"><textarea rows="5" style="width: 100%;" id="text_'+win.uid+'">'+defaultText+'</textarea></td>\n\
</tr>\n\
<tr style="height: 10px;">\n\
<td style="width: 100%;">&nbsp;</td>\n\
<td><button class="button-secondary" id="'+win.uid+'_ok" style="width: 80px;margin:1px;">'+trt('Ok')+'</button></td>\n\
<td><button class="button-secondary" id="'+win.uid+'_cancel" style="width: 80px;margin:1px;">'+trt('Cancel')+'</button></td>\n\
</tr>\n\
</table>';
win.setContent(html);
let btnO=document.getElementById(win.uid+'_ok');
btnO.focus();
if(btnO!=null){
btnO.onclick=function(win){
return function(){
let text=document.getElementById('text_'+win.uid).value;
win.Close();
if(okFunc!=null) okFunc(text);
};
}(win,okFunc);
}
let btnC=document.getElementById(win.uid+'_cancel');
if(btnC!=null) {
btnC.onclick = function (win) {
return function () {
win.Close();
if(cancelFunc!=null) cancelFunc();
};
}(win,cancelFunc);
}
win.setSize("350px","200px");
win.setCenter();
win.shadow=true;
win.hide(false);
return win;
}
/**
* Добавить событие к объекту
* @param {object} obj Объект
@ -971,7 +1024,7 @@ function delChild(obj)
function applyNodeToNode(first, second, name)
{
if(first===null || second===null || name ===null){
console.error("first="+first+" second="+second+" name="+name);
log.error("first="+first+" second="+second+" name="+name);
return;
}
//Если есть совпадающие узлы то передаём в рекурсию если нет то просто копируем
@ -1006,6 +1059,13 @@ function applyNodeToNode(first, second, name)
}
}
/*function applyObjectToObject(first, second, name){
if(first===null || second===null || name ===null){
log.error("first="+first+" second="+second+" name="+name);
return;
}
}*/
function escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
@ -1057,39 +1117,97 @@ class TRequest
}
processReqChange(xmlHttpRequest,url,xmlString)
{
if(typeof(xmlHttpRequest.status)=='undefined' || xmlHttpRequest.status == 200)
{
if(xmlHttpRequest.responseXML!=null) {
//if(typeof(xmlHttpRequest.responseXML)=='undefined' && xmlHttpRequest.contentType.match(/\/xml/)) //For IE XDomainRequest
// xmlHttpRequest.responseXML=CreateXMLDOC(xmlHttpRequest.responseText);
let xmldoc = xmlHttpRequest.responseXML;
if (xmldoc == null) {
alert2(trt('Alert'), trt('Wrong_XML_document') + "!\nXML=(" + xmlHttpRequest.responseText + ')\nURL=(' + url + ')\nxmlString=(' + xmlString + ')');
return;
}
let node = xmldoc.documentElement;
if ((node == null) || (node.getAttribute("fn") == null)){
alert2(trt('Error'), trt('No_data')+"! \n" + xmlHttpRequest.responseText);
}else {
let fn = node.getAttribute("fn");
if (this.winObj != null) {
this.winObj.applyReq(this, fn, node, xmldoc, this.winObj);
return null;
}
}
}else{
let obj = JSON.parse(xmlHttpRequest.responseText);
if(obj==null) {
alert2(trt('Alert'), trt('Wrong_JSON_document') + "!\nJSON=(" + xmlHttpRequest.responseText + ')');
return;
}
if(this.winObj!=null)
{
this.winObj.applyReq(this,obj.fn,obj,null,this.winObj);
return null;
}
}
}else
{
if(confirm(trt('Failed_to_get_data')+"\n URL: "+url+"\n"+xmlHttpRequest.statusText+trt('Repeat_request')+'?'))
{
this.callServer(url,xmlString);
};
}
return null;
}
/*processReqChange(xmlHttpRequest,url,xmlString)
{
//if (typeof(xmlHttpRequest.readyState)=='undefined' || xmlHttpRequest.readyState == 4)
//{
if(typeof(xmlHttpRequest.status)=='undefined' || xmlHttpRequest.status == 200)
{
if(typeof(xmlHttpRequest.responseXML)=='undefined' && xmlHttpRequest.contentType.match(/\/xml/)) //For IE XDomainRequest
xmlHttpRequest.responseXML=CreateXMLDOC(xmlHttpRequest.responseText);
//загрузился xml документ начинаем его разбирать (по id функции в документе)
let xmldoc = xmlHttpRequest.responseXML;
if(xmldoc==null){
alert2(trt('Alert'),trt('Wrong_XML_document')+"!\nXML=("+xmlHttpRequest.responseText+')\nURL=('+url+')\nxmlString=('+xmlString+')');
return;
}
let node = xmldoc.documentElement;
if((node==null)||(node.getAttribute("fn")==null)) alert(trt('Error')+"\n"+trt('No_data')+"!\n"+xmlHttpRequest.responseText);
else
{
//alert("XML=\n"+getXMLNodeSerialisation(node));
let fn = node.getAttribute("fn");
if(this.winObj!=null)
{
//this.winObj.alert("Принятый браузером XML=\n"+getXMLNodeSerialisation(node));
/* каждый слушатель должен сам реализовать
* if (fn==-1)
alert(JSON.stringify(xmlHttpRequest));
if(typeof(xmlHttpRequest.responseXML)=='undefined') {
if(xmlHttpRequest.contentType.match(/\/xml/)) {
xmlHttpRequest.responseXML = CreateXMLDOC(xmlHttpRequest.responseText);
if(xmlHttpRequest.responseXML==null) {
alert2(trt('Alert'), trt('Wrong_XML_document') + "!\nXML=(" + xmlHttpRequest.responseText + ')\nURL=(' + url + ')\nxmlString=(' + xmlString + ')');
return;
}
//загрузился xml документ начинаем его разбирать (по id функции в документе)
let node = xmlHttpRequest.responseXML.documentElement;
if((node==null)||(node.getAttribute("fn")==null)) alert(trt('Error')+"\n"+trt('No_data')+"!\n"+xmlHttpRequest.responseText);
else
{
alert(findFirstNode(node,'#cdata-section').nodeValue);
}else*/
this.winObj.applyReq(this,fn,node,xmldoc,this.winObj);
return null;
}else if(fn==0) alert(findFirstNode(node,'#cdata-section').nodeValue);
let fn = node.getAttribute("fn");
if(this.winObj!=null)
{
this.winObj.applyReq(this,fn,node,xmldoc,this.winObj);
return null;
}else if(fn==0) alert(findFirstNode(node,'#cdata-section').nodeValue);
}
}else if(xmlHttpRequest.contentType.match(/\/json/)){
xmlHttpRequest.responseXML = JSON.parse(xmlHttpRequest.responseText);
if(xmlHttpRequest.responseXML==null) {
alert2(trt('Alert'), trt('Wrong_JSON_document') + "!\nJSON=(" + xmlHttpRequest.responseText + ')\nURL=(' + url + ')\njsonString=(' + xmlString + ')');
return;
}
//загрузился xml документ начинаем его разбирать (по id функции в документе)
let node=xmlHttpRequest.responseXML;
if((node==null)||(node.fn==null)) alert(trt('Error')+"\n"+trt('No_data')+"!\n"+xmlHttpRequest.responseText);
else
{
if(this.winObj!=null)
{
this.winObj.applyReq(this,node.fn,node,null,this.winObj);
return null;
}else if(fn==0) alert(findFirstNode(node,'#cdata-section').nodeValue);
}
}
}
}else
{
if(confirm(trt('Failed_to_get_data')+"\n URL: "+url+"\n"+xmlHttpRequest.statusText+"\nПовторить запрос?"))
@ -1099,7 +1217,7 @@ class TRequest
}
//}
return null;
}
}*/
};
/** Класс асинхронных запросов к серверу