Старт

This commit is contained in:
2023-11-07 19:51:49 +06:00
commit 86542a157f
5002 changed files with 199551 additions and 0 deletions

View File

@ -0,0 +1,143 @@
<?php
//Выбираю объезды в GeoJSON и отправляю клиенту
require_once("../../monitoring/config.php");
function sendError($msg)
{
$json='{"errorCode":1,"errorMessage":'.json_encode($msg,JSON_UNESCAPED_UNICODE).'}';
header('Content-Type: application/json');
echo $json;
exit;
}
$db = connectToDB();
//$db->exec('SET NAMES utf8');
//$db->exec("SET time_zone = '+00:00'");
$fn=0;
if(isset($_GET['fn'])) { $fn=$_GET['fn']; }
if($fn=='1') //Вернуть список
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if(!property_exists($object,'name') or $object->name=='') $object->name='null'; else $object->name='\'%'.$object->name.'%\'';
$sql = '
SELECT
id
,name
,date_start
,date_end
,coalesce(ST_NPoints(geom),0) as count
,ST_X(ST_Centroid(geom)) lon
,ST_Y(ST_Centroid(geom)) lat
FROM
main.detours
where
del=false
and ('.$object->name.' is null or name like '.$object->name.')
ORDER BY name;
';
try
{
$res = $db->query($sql);
}catch (Exception $e)
{
sendError($e->getMessage());
}
//Массив объектов
$json ='[';
//Перебираю и последовательно отправляю не отправленные пломбы
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
$json .="\n";
$json .='{';
$json .='"id":'.json_encode($row['id']).",\n";
$json .='"name":'.json_encode($row['name'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"date_start":'.json_encode($row['date_start'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"date_end":'.json_encode($row['date_end'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"lat":'.json_encode($row['lat']).",\n";
$json .='"lon":'.json_encode($row['lon']).",\n";
$json .='"count":'.json_encode($row['count'])."\n";
$json .='},';
}
if($json[strlen($json) - 1]==','){
$json=substr ( $json , 0, strlen($json)-1 );
}
$json .=']';
header('Content-Type: application/json');
echo $json;
exit;
}else if($fn=='2') //Вернуть GEOJSON по ID записи
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if($object->id=='') $object->id='null';
/*if($object->cnumber=='') $object->cnumber='null'; else $object->cnumber='"%'.$object->cnumber.'%"'; //Гос. номер
if($object->tnumber=='') $object->tnumber='null'; else $object->tnumber='"%'.$object->tnumber.'%"'; //Номер ТД
if($object->country_seal_begin=='') $object->country_seal_begin='null'; //Страна пломб.
if($object->country_seal_end=='') $object->country_seal_end='null'; //Страна распломб.*/
//Выбираю геометрию
$sql="select ST_AsGeoJSON(geom,6,0) as geom from main.detours where id=".$object->id.";";
try
{
$res = $db->query($sql);
}catch (Exception $e)
{
sendError($e->getMessage());
}
$json="{}";
if($res!=NULL && $res->rowCount()>0)
{
while ($row = $res->fetch(PDO::FETCH_NUM))
{
$json=$row[0];
}
}
header('Content-Type: application/json');
echo $json;
exit;
}else if($fn=='3') //Удалить запись
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if($object==null) $object = (object)[];
if(!property_exists($object,'id') or $object->id=='') $object->id=null; //Поле заполнено если редактирвание записи
if($object->id!=null)
{
try
{
$sql="update main.detours set del=true where id=".$object->id;
$db->query($sql);
}catch (Exception $e)
{
sendError($e->getMessage());
}
$json='{}';
header('Content-Type: application/json');
echo $json;
exit;
}else
{
sendError("ID is not set!");
}
}else
{
sendError("Fn is null!");
}

View File

@ -0,0 +1,146 @@
<?php
//Выбираю объезды в GeoJSON и отправляю клиенту
require_once("../../monitoring/config.php");
function sendError($msg)
{
$json='{"errorCode":1,"errorMessage":'.json_encode($msg,JSON_UNESCAPED_UNICODE).'}';
header('Content-Type: application/json');
echo $json;
exit;
}
$db = connectToDB();
//$db->exec('SET NAMES utf8');
//$db->exec("SET time_zone = '+00:00'");
$fn=0;
if(isset($_GET['fn'])) { $fn=$_GET['fn']; }
if($fn=='1') //Вернуть список
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if(!property_exists($object,'name') or $object->name=='') $object->name='null'; else $object->name='\'%'.$object->name.'%\'';
//if(!property_exists($object,'geofence_group_id') or $object->geofence_group_id=='') $object->geofence_group_id='null';
if(!property_exists($object,'geofence_type_id') or $object->geofence_type_id=='') $object->geofence_type_id='null';
$sql = '
SELECT
g.id
,g.name
,coalesce(ST_NPoints(geom),0) as count
,ST_X(ST_Centroid(geom)) lon
,ST_Y(ST_Centroid(geom)) lat
,gt.name as geofence_type_name
FROM
main.geofences g
left join main.geofences_types gt on gt.id=g.geofence_type_id
where
g.del=false
and ('.$object->name.' is null or g.name like '.$object->name.')
and ('.$object->geofence_type_id.' is null or g.geofence_type_id = '.$object->geofence_type_id.')
ORDER BY g.name;
';
try
{
$res = $db->query($sql);
}catch (Exception $e)
{
sendError($e->getMessage());
}
//Массив объектов
$json ='[';
//Перебираю и последовательно отправляю не отправленные пломбы
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
$json .="\n";
$json .='{';
$json .='"id":'.json_encode($row['id']).",\n";
$json .='"name":'.json_encode($row['name'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"geofence_type_name":'.json_encode($row['geofence_type_name'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"lat":'.json_encode($row['lat']).",\n";
$json .='"lon":'.json_encode($row['lon']).",\n";
$json .='"count":'.json_encode($row['count'])."\n";
$json .='},';
}
if($json[strlen($json) - 1]==','){
$json=substr ( $json , 0, strlen($json)-1 );
}
$json .=']';
header('Content-Type: application/json');
echo $json;
exit;
}else if($fn=='2') //Вернуть GEOJSON по ID записи
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if($object->id=='') $object->id='null';
/*if($object->cnumber=='') $object->cnumber='null'; else $object->cnumber='"%'.$object->cnumber.'%"'; //Гос. номер
if($object->tnumber=='') $object->tnumber='null'; else $object->tnumber='"%'.$object->tnumber.'%"'; //Номер ТД
if($object->country_seal_begin=='') $object->country_seal_begin='null'; //Страна пломб.
if($object->country_seal_end=='') $object->country_seal_end='null'; //Страна распломб.*/
//Выбираю геометрию
$sql="select ST_AsGeoJSON(geom,6,0) as geom from main.geofences where id=".$object->id.";";
try
{
$res = $db->query($sql);
}catch (Exception $e)
{
sendError($e->getMessage());
}
$json="{}";
if($res!=NULL && $res->rowCount()>0)
{
while ($row = $res->fetch(PDO::FETCH_NUM))
{
$json=$row[0];
}
}
header('Content-Type: application/json');
echo $json;
exit;
}else if($fn=='3') //Удалить запись
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if($object==null) $object = (object)[];
if(!property_exists($object,'id') or $object->id=='') $object->id=null; //Поле заполнено если редактирвание записи
if($object->id!=null)
{
try
{
$sql="update main.geofences set del=true where id=".$object->id;
$db->query($sql);
}catch (Exception $e)
{
sendError($e->getMessage());
}
$json='{}';
header('Content-Type: application/json');
echo $json;
exit;
}else
{
sendError("ID is not set!");
}
}else
{
sendError("Fn is null!");
}

View File

@ -0,0 +1,277 @@
<?php
//Вернуть в JSON кол-во необработанных сообщений (не присвоенных ни одному пользователю)
//И всё другое связаное с оброботкой сообщений для пользователя
@session_start();
require_once("../../monitoring/config.php");
require_once("../tools.php");
$db = connectToDB();
//$db->exec('SET NAMES utf8');
//$db->exec("SET time_zone = '+00:00'");
$fn=0;
if(isset($_GET['fn'])) { $fn=$_GET['fn']; }
if($fn=='1') //Вернуть кол-во не присвоеных пользователю сообщений
{
$m_all_count=0; //Количество не присвоенных никому сообщений.
$m_user_count=0; //Количество не обработаны сообщений для текущего пользователя.
$sql = 'SELECT count(*) FROM main.messages m join main.companies c on m.company_id=c.id WHERE m.del=false and m.id NOT IN (SELECT mu.message_id FROM main.messages_users mu WHERE del=false) and m.company_id=(select company_id from main._users where id='.$_SESSION['USER_ID'].')';
try {
$res = $db->query($sql);
} catch (Exception $e) {
echo $e->getMessage();
$res = null;
}
while ($row = $res->fetch(PDO::FETCH_NUM))
{
$m_all_count = $row[0];
}
if($_SESSION['USER_ID']!='')
{
$sql = "SELECT COUNT(*) FROM main.messages_users WHERE user_id=".$_SESSION['USER_ID']." AND del=FALSE and date_read IS null";
try {
$res = $db->query($sql);
} catch (Exception $e) {
echo $e->getMessage();
$res = null;
}
while ($row = $res->fetch(PDO::FETCH_NUM))
{
$m_user_count = $row[0];
}
}
$json ='';
header('Content-Type: application/json');
$json .='{';
$json .='"count":'.$m_all_count.",\n";
$json .='"user":'.$m_user_count."\n";
$json .='}';
echo $json;
exit;
}if($fn=='2') //Присвоить последнее сообщение пользователю и вернуть его ID
{
$id='';
$errorCode='0';
$errorMessage='';
$sql = 'SELECT m.id FROM main.messages m join main.companies c on m.company_id=c.id WHERE m.del=false and m.id NOT IN (SELECT mu.message_id FROM main.messages_users mu WHERE del=false) and m.company_id=(select company_id from main._users where id='.$_SESSION['USER_ID'].') ORDER BY m.priority desc, m.date_create LIMIT 1';
try {
$res = $db->query($sql);
} catch (Exception $e) {
$errorCode='1';
$errorMessage = $e->getMessage();
$res = null;
}
if($res != null)
{
if ($row = $res->fetch(PDO::FETCH_NUM))
{
//Присваиваю текущему пользователю
$sql="insert into main.messages_users(message_id,user_id,date_create)values(".$row[0].",".$_SESSION['USER_ID'].",now())";
try {
$res = $db->query($sql);
} catch (Exception $e) {
$errorCode='1';
$errorMessage = $e->getMessage();
$res = null;
}
$id=$row[0];
}
}
header('Content-Type: application/json');
echo '{"errorCode":'.$errorCode.',"errorMessage":'.json_encode($errorMessage,JSON_UNESCAPED_UNICODE).',"id":"'.$id.'"}';
exit;
}if($fn=='3') //Вернуть данные пользователю в соответствии со значением фильтра
{
$status='';
if(isset($_GET['status'])) { $status=$_GET['status']; }
if($status=='0'){ //Не отработанные
$sql='
SELECT
mu.id,
main."_"('.$_SESSION['USER_ID'].',m.subject) as subject,
main."_"('.$_SESSION['USER_ID'].',m.text) as text,
m.text_settings,
m.date_create
FROM
main.messages_users mu
JOIN main.messages m ON m.id=mu.message_id
WHERE
mu.del=FALSE
AND m.del=FALSE
and mu.user_id='.$_SESSION['USER_ID'].'
AND mu.date_read IS null';
}
if($status=='1'){ //Отработанные
//$sql='SELECT mu.id,m.subject,m.text,m.date_create FROM main.messages_users mu JOIN main.messages m ON m.id=mu.message_id WHERE mu.del=FALSE AND m.del=FALSE and mu.user_id='.$_SESSION['USER_ID'].' AND mu.date_read > NOW() - INTERVAL 30 DAY';
$sql='
SELECT
mu.id,
main."_"('.$_SESSION['USER_ID'].',m.subject) as subject,
main."_"('.$_SESSION['USER_ID'].',m.text) as text,
m.text_settings,
m.date_create
FROM
main.messages_users mu
JOIN main.messages m ON m.id=mu.message_id
WHERE
mu.del=FALSE
AND m.del=FALSE
and mu.user_id='.$_SESSION['USER_ID'].'
AND mu.date_read IS not null';
}
try {
$res = $db->query($sql);
} catch (Exception $e) {
$json = '{"errorMessage":'.json_encode($e->getMessage(),JSON_UNESCAPED_UNICODE).'}';
header('Content-Type: application/json');
echo $json;
exit;
}
$json ='';
$json .='[';
if($res != null)
{
while ($row = $res->fetch(PDO::FETCH_ASSOC))// $row - ассоциативный массив значений, ключи - названия столбцов
{
$json .='{';
$json .='"id":'.$row['id'].',';
$json .='"subject":'.json_encode($row['subject'],JSON_UNESCAPED_UNICODE).',';
$text=$row['text'];
$text_settings=$row['text_settings'];
$obj=json_decode($text_settings);
if($obj) //Перебираю параметры и пытаюсь подставить в строку
{
foreach ($obj as $name => $value) {
$text = str_replace('${'.$name.'}', trt($value), $text);
}
}
$json .='"text":'.json_encode($text,JSON_UNESCAPED_UNICODE).'';
$json .="},";
}
if($json[strlen($json)-1]==','){
$json = substr($json, 0, -1);
}
}
$json .=']';
header('Content-Type: application/json');
echo $json;
exit;
}if($fn=='4') //Одна запись для подтверждения
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if(!property_exists($object,'id') or $object->id=='') $object->id='null'; //id компании
$sql='
SELECT
mu.id,
main."_"('.$_SESSION['USER_ID'].',m.subject) as subject,
main."_"('.$_SESSION['USER_ID'].',m.text) as text,
m.text_settings,
m.date_create,
m.action_name,
m.action_settings
FROM
main.messages_users mu
JOIN main.messages m ON m.id=mu.message_id
WHERE
mu.del=FALSE
AND m.del=FALSE
and mu.user_id='.$_SESSION['USER_ID'].'
AND mu.id='.$object->id;
try {
$res = $db->query($sql);
} catch (Exception $e) {
$json = '{"errorMessage":'.json_encode($e->getMessage(),JSON_UNESCAPED_UNICODE).'}';
header('Content-Type: application/json');
echo $json;
exit;
}
$json ='';
$json .='{';
if($res != null)
{
if($row = $res->fetch(PDO::FETCH_ASSOC))// $row - ассоциативный массив значений, ключи - названия столбцов
{
$json .='"id":'.$row['id'].',';
$json .='"subject":'.json_encode($row['subject'],JSON_UNESCAPED_UNICODE).',';
$text=$row['text'];
$text_settings=$row['text_settings'];
$obj=json_decode($text_settings);
if($obj) //Перебираю параметры и пытаюсь подставить в строку
{
foreach ($obj as $name => $value) {
$text = str_replace('${'.$name.'}', trt($value), $text);
}
}
$json .='"text":'.json_encode($text,JSON_UNESCAPED_UNICODE).',';
$json .='"action_name":'.json_encode($row['action_name'],JSON_UNESCAPED_UNICODE).',';
if($row['action_settings']!='')
{
$json .='"action_settings":'.$row['action_settings'];
}else
{
$json .='"action_settings":{}';
}
}
}
$json .='}';
header('Content-Type: application/json');
echo $json;
exit;
}if($fn=='5') //Отмечаем сообщение как обработанное
{
$errorCode='0';
$errorMessage='';
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
//Сохраняю текст и присваиваю время чтения
$sql="update main.messages_users set date_read=now(), description = :description where id = ".$object->id;
$stmt = $db->prepare($sql);
$stmt->bindParam(':description', $object->description, PDO::PARAM_STR);
try
{
$res = $stmt->execute();
} catch (Exception $e)
{
$errorCode='1';
$errorMessage = $e->getMessage();
}
header('Content-Type: application/json');
echo '{"errorCode":'.$errorCode.',"errorMessage":"'.$errorMessage.'"}';
exit;
}else
{
header('Content-Type: application/json');
echo '{"errorCode":1,"errorMessage":"Неизвестная функция!"}';
}

View File

@ -0,0 +1,94 @@
<?php
//Вернуть данные о объекте в виде HTML
@session_start();
if(isset($_GET["object_id"])){
$object_id=$_GET["object_id"];
}else{
echo "Not set ID";
exit;
}
require_once("../config.php");
require_once("../../resources/metadata/include/tools.php");
$db=connectToDB();
//$db->exec('SET NAMES utf8');
//$db->exec("SET time_zone = '+00:00'");
//Номер пломбы
$sql = '
SELECT
o.id,
COALESCE(o.name,\'\') as name,
c.name as company_name,
COALESCE(t.serial,\'\') || \' (\' || t.imei || \')\' as terminal_name
from
main.objects o
left join main.companies_objects co on co.object_id=o.id and co.del=false
left join main.companies c on c.id=co.company_id and c.del=false
left join main.terminals t on t.id=o.terminal_id and t.del=false
where
o.del=false
and o.id='.$object_id;
try
{
$res = $db->query($sql);
}catch (Exception $e)
{ echo $e->getMessage();
$res = null;
}
$html='';
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
$html.='<table border="1" cellpadding="7" style="width:100%;">';
$html.='<tr><td style="font-weight: bold;white-space: nowrap;vertical-align:top;padding-right:4px;">Гос. номер:</td><td colspan="3">'.$row['name'].'</td></tr>';
if($row['company_name']!=''){
$html.='<tr><td style="font-weight: bold;white-space: nowrap;padding-right:4px;">Наименование перевозчика:</td><td colspan="3">'.$row['company_name'].'</td></tr>';
}
if($row['terminal_name']!=''){
$html.='<tr><td style="font-weight: bold;white-space: nowrap;padding-right:4px;">Терминал:</td><td colspan="3">'.$row['terminal_name'].'</td></tr>';
}
//выбираю показания всех датчиков для данного объекта (установки)
$sql="
select
obr.id,
obs.name,
round(obr.value::numeric,2) as value,
to_char(obr.date+(select timezone from main._users where id=".$_SESSION['USER_ID']."), 'yyyy.mm.dd HH24:MI:SS') as date,
obs.sensor_type_id,
trst.measurement as terminalsensortype_name
from
main.objects_sensors obs
left join main.sensors_values obr on obr.id=obs.sensor_value_id
left join main.terminals_sensors trs on trs.id=obs.terminal_sensor_id
left join main.sensors_types trst on trst.id=trs.sensor_type_id
where
obs.del=false
--and obs.sensor_type_id in (1,16,17)
and obs.object_id=".$row['id']."
order by obs.name";
try
{
$res2 = $db->query($sql);
}catch (Exception $e)
{ echo $e->getMessage();
$res2 = null;
}
while ($row2 = $res2->fetch(PDO::FETCH_ASSOC))
{
$html.='<tr><td style="font-weight: bold;white-space: nowrap;padding-right:4px;">'.trt($row2['name']).':</td><td>'.$row2['value'].'</td><td>'.$row2['terminalsensortype_name'].'</td><td>'.$row2['date'].'</td></tr>';
}
$html.='</table>';
}
header('Content-Type: text/html');
echo $html;

View File

@ -0,0 +1,232 @@
<?php
//Выдираю все объекты на которых установлен терминал и отправляю клиенту
@session_start();
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
//if($object->active=='') $object->active='null';
//if($object->cnumber=='') $object->cnumber='null'; else $object->cnumber='"%'.$object->cnumber.'%"'; //Гос. номер
//if($object->tnumber=='') $object->tnumber='null'; else $object->tnumber='"%'.$object->tnumber.'%"'; //Номер ТД
//if($object->country_seal_begin=='') $object->country_seal_begin='null'; //Страна пломб.
//if($object->country_seal_end=='') $object->country_seal_end='null'; //Страна распломб.
require_once("../../monitoring/config.php");
require_once("../../resources/metadata/include/tools.php");
$db=connectToDB();
$db->exec("SET TIME ZONE 'UTC';"); //Ниже в коде есть смещение временной зоны под настройки каждого пользователя
$fn=0;
if(isset($_GET['fn'])) { $fn=$_GET['fn']; }
if($fn=='0') //Вернуть список объектов в соответствии с фильтром
{
if(!property_exists($object,'company_id') or $object->company_id=='') $object->company_id='null'; //id компании
if(!property_exists($object,'cnumber') or $object->cnumber=='') $object->cnumber='null'; else $object->cnumber='\'%'.$object->cnumber.'%\''; //Гос. номер
$sql = 'SELECT
o.id,
0 as seq,
o.name,
sl.lat,
sl.lon,
round(cast(sl.speed as numeric),1) speed,
to_char(sl.date+(select timezone from main._users where id='.$_SESSION['USER_ID'].'), \'yyyy.mm.dd HH24:MI:SS\') as date,
\'\' as declaration,
i.file_name as icon_name,
\'\' as active,
t.serial || \' (\' || t.imei || \')\' AS terminal_name,
coalesce(g.geofences,\'\') as geofences
from
main.objects o
LEFT JOIN main.terminals_locations sl ON sl.id=o.terminal_location_id
LEFT JOIN main.terminals t ON t.id = o.terminal_id
LEFT JOIN main.icons i on i.id=o.icon_id
LEFT JOIN (SELECT og.object_id, CAST(array_to_string(array_agg(gg.name), \', \') AS character varying ) AS geofences FROM main.objects_geofences og, main.geofences gg WHERE og.del = FALSE and gg.del=false AND gg.id = og.geofence_id GROUP BY og.object_id) g ON o.id = g.object_id
where
o.del=false
and ('.$object->company_id.' is null or '.$object->company_id.' in (select company_id from main.companies_objects where del=false and object_id=o.id))
and ('.$object->cnumber.' is null or o.name like '.$object->cnumber.')
order by o.name,o.id';
try
{
$res = $db->query($sql);
}catch (Exception $e)
{ echo $e->getMessage();
$res = null;
}
//Массив объектов
$json ='[';
//Перебираю и последовательно отправляю не отправленные пломбы
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
$json .="\n";
$json .='{';
$json .='"id":"'.$row['id']."\",\n";
$json .='"seq":"'.$row['seq']."\",\n";
$json .='"active":"'.$row['active']."\",\n";
$json .='"name":"'.$row['name']."\",\n";
$json .='"terminal_name":"'.$row['terminal_name']."\",\n";
$json .='"declaration":"'.$row['declaration']."\",\n";
$json .='"icon_name":"'.afterLast($row['icon_name'],'_')."\",\n";
//выбираю показания 3х датчиков для данного объекта (установки)
//$json .="\"bat\":\"0\",\n";
//$json .="\"bat_date\":\"0\",\n";
//$json .="\"tros\":\"0\",\n";
//$json .="\"tros_date\":\"0\",\n";
//$json .="\"box\":\"0\",\n";
//$json .="\"box_date\":\"0\",\n";
$json .='"lat":'.json_encode($row['lat']).",\n";
$json .='"lon":'.json_encode($row['lon']).",\n";
$json .='"speed":'.json_encode($row['speed']).",\n";
$json .='"date":"'.$row['date']."\",\n";
$json .="\"country\":\"KZ\",\n";
$json .='"geofences":"'.$row['geofences']."\",\n";
//Выбираю показания всех датчиков (которые видны)
$json .='"sensors":[';
$sql="
select
obs.id,
obs.name,
round(obr.value::numeric,2) as value,
to_char(obr.date+(select timezone from main._users where id=".$_SESSION['USER_ID']."), 'yyyy.mm.dd HH24:MI:SS') as date,
obs.sensor_type_id,
trst.measurement as terminalsensortype_name
from
main.objects_sensors obs
left join main.sensors_values obr on obr.id=obs.sensor_value_id
left join main.terminals_sensors trs on trs.id=obs.terminal_sensor_id
left join main.sensors_types trst on trst.id=trs.sensor_type_id
where
obs.del=false
and obs.object_id=".$row['id']."
order by obs.name";
try
{
$res2 = $db->query($sql);
}catch (Exception $e)
{ echo $e->getMessage();
$res2 = null;
}
if ($res2->rowCount() > 0) {
while ($row2 = $res2->fetch(PDO::FETCH_ASSOC))
{
$json .='{';
$json .='"id":"'.$row2['id']."\",\n";
$json .='"name":"'.$row2['name']."\",\n";
$json .='"value":"'.$row2['value']."\",\n";
$json .='"type_name":"'.$row2['terminalsensortype_name']."\",\n";
$json .='"date":"'.$row2['date']."\"\n";
$json .='},';
}
$json=substr($json, 0, -1);
}
$json .=']';
$json .='},';
}
if($json[strlen($json) - 1]==','){
$json=substr ( $json , 0, strlen($json)-1 );
}
$json .=']';
header('Content-Type: application/json');
echo $json;
exit;
}else
if($fn=='1') //Вернуть список объектов для обновления полей по переданным ID
{
$sql = 'SELECT
o.id,
0 as seq,
o.name,
sl.lat,
sl.lon,
to_char(sl.date+(select timezone from main._users where id='.$_SESSION['USER_ID'].'), \'yyyy.mm.dd HH24:MI:SS\') as date,
\'\' as declaration,
i.file_name as icon_name,
\'\' as active
from
main.objects o
LEFT JOIN main.terminals_locations sl ON sl.id=o.terminal_location_id
LEFT JOIN main.icons i on i.id=o.icon_id
where
o.del=false
and o.id in '.str_replace("]", ")", str_replace("[", "(", $HTTP_RAW_POST_DATA)).'
order by o.name,o.id';
try
{
$res = $db->query($sql);
}catch (Exception $e)
{ echo $e->getMessage();
$res = null;
}
//Массив объектов
$json ='[';
//Перебираю и последовательно отправляю не отправленные пломбы
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
$json .="\n";
$json .='{';
$json .='"id":"'.$row['id']."\",\n";
$json .='"lat":"'.$row['lat']."\",\n";
$json .='"lon":"'.$row['lon']."\",\n";
$json .='"date":"'.$row['date']."\",\n";
//Выбираю показания всех датчиков (которые видны)
$json .='"sensors":[';
$sql="
select
obs.id,
round(obr.value::numeric,2) as value,
to_char(obr.date+(select timezone from main._users where id=".$_SESSION['USER_ID']."), 'yyyy.mm.dd HH24:MI:SS') as date
from
main.objects_sensors obs
left join main.sensors_values obr on obr.id=obs.sensor_value_id
left join main.terminals_sensors trs on trs.id=obs.terminal_sensor_id
where
obs.del=false
and obs.object_id=".$row['id']."
order by obs.name";
try
{
$res2 = $db->query($sql);
}catch (Exception $e)
{ echo $e->getMessage();
$res2 = null;
}
if ($res2->rowCount() > 0) {
while ($row2 = $res2->fetch(PDO::FETCH_ASSOC))
{
$json .='{';
$json .='"id":"'.$row2['id']."\",\n";
$json .='"value":"'.$row2['value']."\",\n";
$json .='"date":"'.$row2['date']."\"\n";
$json .='},';
}
$json=substr($json, 0, -1);
}
$json .=']';
$json .='},';
}
if($json[strlen($json) - 1]==','){
$json=substr ( $json , 0, strlen($json)-1 );
}
$json .=']';
header('Content-Type: application/json');
echo $json;
exit;
}

View File

@ -0,0 +1,80 @@
<?php
//Скрипт по обновлению геометрии а именно точек
require_once("../../monitoring/config.php");
function sendError($msg)
{
$json='{"errorCode":1,"errorMessage":'.json_encode($msg,JSON_UNESCAPED_UNICODE).'}';
header('Content-Type: application/json');
echo $json;
exit;
}
$db = connectToDB();
//$db->exec('SET NAMES utf8');
//$db->exec("SET time_zone = '+00:00'");
$fn=0;
if(isset($_GET['fn'])) { $fn=$_GET['fn']; }
if($fn=='1') //Перезаписать все координаты для геометрии
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if($object->name=="TCheckPoint")
{
$sql="update main.routes_checkpoints set geom=ST_GeomFromText('POLYGON((".$object->points."))', 4326) where id=".$object->id;
try
{
$db->query($sql);
}catch (Exception $e)
{
sendError($e->getMessage());
}
}else if($object->name=="TDetour")
{
$sql="update main.detours set geom=ST_GeomFromText('POLYGON((".$object->points."))', 4326) where id=".$object->id;
try
{
$db->query($sql);
}catch (Exception $e)
{
sendError($e->getMessage());
}
}else if($object->name=="TRoute")
{
$sql="update main.routes set geom=ST_GeomFromText('LINESTRING(".$object->points.")', 4326) where id=".$object->id;
try
{
$db->query($sql);
}catch (Exception $e)
{
sendError($e->getMessage());
}
}else if($object->name=="TGeofence")
{
$sql="update main.geofences set geom=ST_GeomFromText('POLYGON((".$object->points."))', 4326) where id=".$object->id;
try
{
$db->query($sql);
}catch (Exception $e)
{
sendError($e->getMessage());
}
}
/*json+='"id":'+feature.userFeature.userData.id+',\n';
json+='"name":"'+feature.userFeature.userData.constructor.name+'",\n';
json+='"points":"';*/
$json='{"errorCode":0}';
header('Content-Type: application/json');
echo $json;
exit;
}

View File

@ -0,0 +1,230 @@
<?php
//Выбираю маршруты в GeoJSON и отправляю клиенту
require_once("../../monitoring/config.php");
$db = connectToDB();
//$db->exec('SET NAMES utf8');
//$db->exec("SET time_zone = '+00:00'");
function sendError($msg)
{
$json='{"errorCode":1,"errorMessage":'.json_encode($msg,JSON_UNESCAPED_UNICODE).'}';
header('Content-Type: application/json');
echo $json;
exit;
}
$fn=0;
if(isset($_GET['fn'])) { $fn=$_GET['fn']; }
if($fn=='0') //Вернуть список маршрутов
{
$sql = '
SELECT
id
,name
,coalesce((select c.name from main.companies c join main.routes_companies rc on c.id=rc.company_id where rc.del=false and c.del=false and rc.route_id=r.id and c.company_type_id=2 limit 1),\'\') as station
,coalesce((select c.name from main.companies c join main.routes_companies rc on c.id=rc.company_id where rc.del=false and c.del=false and rc.route_id=r.id and c.company_type_id=1 limit 1),\'\') as carriers
,ST_NPoints(geom) as count
,round(ST_Length_Spheroid(geom,\'SPHEROID["WGS 84",6378137,298.257223563]\')/1000) as length
,ST_y(ST_StartPoint(geom)) lat
,ST_X(ST_StartPoint(geom)) lon
FROM
main.routes r
where del=false
ORDER BY name;
';
try
{
$res = $db->query($sql);
}catch (Exception $e)
{ echo $e->getMessage();
$res = null;
}
//Массив объектов
$json ='[';
//Перебираю и последовательно отправляю не отправленные пломбы
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
$json .="\n";
$json .='{';
$json .='"id":"'.$row['id']."\",\n";
$json .='"name":'.json_encode($row['name'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"station":'.json_encode($row['station'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"carriers":'.json_encode($row['carriers'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"count":"'.$row['count']."\",\n";
$json .='"length":"'.$row['length']."\",\n";
$json .='"lat":'.json_encode($row['lat']).",\n";
$json .='"lon":'.json_encode($row['lon']).",\n";
//Расписание для маршрута
$sql='select
ts.id,
CASE WHEN ts.direction=true THEN \'Прямое\' WHEN ts.direction=false THEN \'Обратное\' ELSE \'Не задано\' END as direction,
ts.time,
coalesce(c.name,\'\') as carrier
from
main.trips_schedules ts
left join main.companies c on c.id=ts.company_id
where
ts.route_id='.$row['id'].'
order by
ts.direction desc,ts.time';
try
{
$res2 = $db->query($sql);
}catch (Exception $e)
{ echo $e->getMessage();
$res2 = null;
}
$json .='"schedules":['."\n";
while ($row2 = $res2->fetch(PDO::FETCH_ASSOC))
{
$json .="{";
$json .='"direction":'.json_encode($row2['direction'],JSON_UNESCAPED_UNICODE).',';
$json .='"time":'.json_encode($row2['time'],JSON_UNESCAPED_UNICODE).',';
$json .='"carrier":'.json_encode($row2['carrier'],JSON_UNESCAPED_UNICODE);
$json .="},";
}
if($json[strlen($json) - 1]==','){
$json=substr ( $json , 0, strlen($json)-1 );
}
$json .="],\n";
//Контрольные точки для маршрута
$sql='select
rc.id,
CASE WHEN rc.direction=true THEN \'Прямое\' WHEN rc.direction=false THEN \'Обратное\' ELSE \'Не задано\' END as direction,
rc.time,
coalesce(rc.name,\'\') as name,
ST_X(ST_Centroid(rc.geom)) lon,
ST_Y(ST_Centroid(rc.geom)) lat
from
main.routes_checkpoints rc
where
rc.route_id='.$row['id'].'
order by
rc.direction desc,rc.time';
try
{
$res2 = $db->query($sql);
}catch (Exception $e)
{ echo $e->getMessage();
$res2 = null;
}
$json .='"checkpoints":['."\n";
while ($row2 = $res2->fetch(PDO::FETCH_ASSOC))
{
$json .="{";
$json .='"id":'.json_encode($row2['id'],JSON_UNESCAPED_UNICODE).',';
$json .='"direction":'.json_encode($row2['direction'],JSON_UNESCAPED_UNICODE).',';
$json .='"time":'.json_encode($row2['time'],JSON_UNESCAPED_UNICODE).',';
$json .='"name":'.json_encode($row2['name'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"lat":'.json_encode($row2['lat']).",\n";
$json .='"lon":'.json_encode($row2['lon'])."\n";
$json .="},";
}
if($json[strlen($json) - 1]==','){
$json=substr ( $json , 0, strlen($json)-1 );
}
$json .="]\n";
$json .='},';
}
if($json[strlen($json) - 1]==','){
$json=substr ( $json , 0, strlen($json)-1 );
}
$json .=']';
header('Content-Type: application/json');
echo $json;
}else
if($fn=='1') //Вернуть GEOJSON по ID записи
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if($object->id=='') $object->id='null';
/*if($object->cnumber=='') $object->cnumber='null'; else $object->cnumber='"%'.$object->cnumber.'%"'; //Гос. номер
if($object->tnumber=='') $object->tnumber='null'; else $object->tnumber='"%'.$object->tnumber.'%"'; //Номер ТД
if($object->country_seal_begin=='') $object->country_seal_begin='null'; //Страна пломб.
if($object->country_seal_end=='') $object->country_seal_end='null'; //Страна распломб.*/
//Выбираю геометрию
$sql="select ST_AsGeoJSON(geom,6,0) as geom from main.routes where id=".$object->id.";";
try
{
$res = $db->query($sql);
}catch (Exception $e)
{ echo $e->getMessage();
$res = null;
}
$json="{}";
if($res!=NULL && $res->rowCount()>0)
{
while ($row = $res->fetch(PDO::FETCH_NUM))
{
$json=$row[0];
}
}
header('Content-Type: application/json');
echo $json;
exit;
}else if($fn=='2') //Вернуть GEOJSON по ID записи
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if(!property_exists($object,'id') or $object->id=='') $object->id='null';
//Выбираю геометрию
$sql="select ST_AsGeoJSON(geom,6,0) as geom from main.routes_checkpoints where id=".$object->id.";";
try
{
$res = $db->query($sql);
}catch (Exception $e)
{
sendError($e->getMessage());
}
$json="{}";
if($res!=NULL && $res->rowCount()>0)
{
while ($row = $res->fetch(PDO::FETCH_NUM))
{
$json=$row[0];
}
}
header('Content-Type: application/json');
echo $json;
exit;
}else if($fn=='3') //Удалить маршрут
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if($object->id=='') $object->id='null';
$sql="update main.routes r set del=true where id=".$object->id;
try
{
$res = $db->query($sql);
}catch (Exception $e)
{
sendError($e->getMessage());
}
$json="{}";
header('Content-Type: application/json');
echo $json;
exit;
}else
{
sendError("Неизвестная функция!");
}

View File

@ -0,0 +1,46 @@
<?php
//Выбираю точки запрошенного маршрута и отправляю в виде JSON клиенту
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if($object->date_start=='') $object->date_start='null';
if($object->date_end=='') $object->date_end='null';
require_once("../../monitoring/config.php");
$db = connectToDB();
$db->exec('SET TIME ZONE 0;');
$sql = 'select id,lon,lat,round(extract(epoch from date at time zone \'utc\')) udate,speed,velocity from main.terminals_locations where del=false and object_id='.$object->object_id.' and ('.$object->date_start.' is null or date > to_timestamp('.$object->date_start.')::timestamp) and ('.$object->date_end.' is null or date < to_timestamp('.$object->date_end.')::timestamp) order by date;';
try
{
$res = $db->query($sql);
}catch (Exception $e)
{ echo $e->getMessage();
$res = null;
}
//Массив объектов
$json ='[';
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
$json .="\n";
$json .='{';
$json .='"lat":"'.$row['lat']."\",\n";
$json .='"lon":"'.$row['lon']."\",\n";
$json .='"udate":"'.$row['udate']."\",\n";
$json .='"speed":"'.round ($row['speed'], 1)."\",\n";
$json .='"velocity":"'.round ($row['velocity'], 1)."\"\n";
$json .='},';
}
if($json!='[')
$json = substr($json,0,strlen($json)-1);
$json .=']';
header('Content-Type: application/json');
echo $json;

View File

@ -0,0 +1,499 @@
<?php
//Этот скрипт обслуживает рейсы назначение, список, и.т.д.
@session_start();
function sendError($msg)
{
$json='{"errorCode":1,"errorMessage":'.json_encode($msg,JSON_UNESCAPED_UNICODE).'}';
header('Content-Type: application/json');
echo $json;
exit;
}
require_once("../../monitoring/config.php");
require_once("../../resources/metadata/include/tools.php");
$db = connectToDB();
//$db->exec('SET NAMES utf8');
//$db->exec("SET time_zone = '+00:00'");
$fn=0;
if(isset($_GET['fn'])) { $fn=$_GET['fn']; }
if($fn=='0') //Вернуть список объектов в соответствии с фильтром
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
try
{
$object = json_decode($HTTP_RAW_POST_DATA);
}catch (Exception $e)
{
$json='{"errorMessage":"'.$e->getMessage().'"}';
header('Content-Type: application/json');
echo $json;
exit;
}
if(!property_exists($object,'carrier_id') or $object->carrier_id=='') $object->carrier_id='null';
if(!property_exists($object,'company_id') or $object->company_id=='') $object->company_id='null';
if(!property_exists($object,'status') or $object->status=='') $object->status='null';
if(!property_exists($object,'route_id') or $object->route_id=='') $object->route_id='null';
$sql = 'SELECT
t.id,
tt.name as trip_type_name,
r.name,
c.name as company_name,
cr.name as carrier_name,
o.name as object_name,
o.places as object_places,
t.direction,
t.date_start,
t.date_start+(select max("time") from main.routes_checkpoints where del=false and route_id=t.route_id) as date_end,
t.passenger,
t.description,
COALESCE((select count(*) from main.trips_checkpoints where del=false and "time" is not null and trip_id=t.id),0) as real_checkpoints,
COALESCE((select count(1) from main.routes r0 join main.routes_checkpoints rc0 on r0.id=rc0.route_id where r0.del=false and rc0.del=false and r0.id=t.route_id and rc0.direction=t.direction group by r0.id,rc0.direction),0) as plan_checkpoints
from
main.trips t
join main.routes r on r.id=t.route_id
left join main.companies c on c.id=t.company_id
left join main.companies cr on cr.id=t.company_carrier_id
left join main.objects o on o.id=t.object_id
left join main.trips_types tt on tt.id=t.trip_type_id
where
t.del=false
and ('.$object->route_id.' is null or '.$object->route_id.'=t.route_id)
and ('.$object->carrier_id.' is null or '.$object->carrier_id.'=t.company_carrier_id)
and ('.$object->company_id.' is null or '.$object->company_id.'=t.company_id)
order by t.date_start,r.name';
//select r.id,rc.direction,count(1) from main.routes r join main.routes_checkpoints rc on r.id=rc.route_id where r.del=false and rc.del=false group by r.id,rc.direction;
try
{
$res = $db->query($sql);
}catch (Exception $e)
{
header('Content-Type: application/json');
echo "{\"error\":\"".$e->getMessage()."\"}";
exit;
}
//Массив объектов
$json ='[';
//Перебираю и последовательно отправляю не отправленные пломбы
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
$json .="\n";
$json .='{';
$json .='"id":"'.$row['id']."\",\n";
$json .='"trip_type_name":'.json_encode($row['trip_type_name'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"name":'.json_encode($row['name'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"company_name":'.json_encode($row['company_name'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"carrier_name":'.json_encode($row['carrier_name'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"object_name":'.json_encode($row['object_name'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"object_places":'.json_encode($row['object_places'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"direction":'.json_encode($row['direction'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"date_start":'.json_encode($row['date_start'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"date_end":'.json_encode($row['date_end'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"passenger":'.json_encode($row['passenger'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"description":'.json_encode($row['description'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"real_checkpoints":'.json_encode($row['real_checkpoints'],JSON_UNESCAPED_UNICODE).",\n";
$json .='"plan_checkpoints":'.json_encode($row['plan_checkpoints'],JSON_UNESCAPED_UNICODE)."\n";
$json .='},';
}
if($json[strlen($json) - 1]==','){
$json=substr ( $json , 0, strlen($json)-1 );
}
$json .=']';
header('Content-Type: application/json');
echo $json;
exit;
}else if($fn=='1') //Удалить запись
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if($object==null) $object = (object)[];
if(!property_exists($object,'id') or $object->id=='') $object->id=null; //Поле заполнено если редактирвание записи
if($object->id!=null)
{
try
{
$sql="update main.trips set del=true where id=".$object->id;
$db->query($sql);
}catch (Exception $e)
{
sendError($e->getMessage());
}
$json='{}';
header('Content-Type: application/json');
echo $json;
exit;
}else
{
$json='{"errorMessage":"ID is not set!"}';
header('Content-Type: application/json');
echo $json;
exit;
}
}else if($fn=='2') //HTML формочка для создания/редактирования новой записи (чтобы не заморачиваться с заполнением выпадающих полей записей через javascript)
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if($object==null) $object = (object)[];
if(!property_exists($object,'id') or $object->id=='') $object->id=null; //Поле заполнено если редактирвание записи
if($object->id!=null)
{
$sql = 'SELECT * from main.trips t
where
t.id='.$object->id;
try
{
$res = $db->query($sql);
}catch (Exception $e)
{
header('Content-Type: application/json');
echo "{\"error\":\"".$e->getMessage()."\"}";
exit;
}
//Переписываю значения в объект
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
$object->route_id=$row['route_id'];
$object->company_id=$row['company_id'];
$object->carrier_id=$row['company_carrier_id']; //Как общий так и конкретный для данного маршрута
$object->trip_type_id=$row['trip_type_id'];
$object->object_id=$row['object_id'];
$object->direction=$row['direction'];
//$object->date_start=$row['date_start'];
$object->date=$row['date_start'];
//$object->date_end=$row['date_end'];
$object->passenger=$row['passenger'];
$object->file_name=$row['file_name'];
$object->description=$row['description'];
}
}
if(!property_exists($object,'trip_type_id') or $object->trip_type_id=='') $object->trip_type_id=null;
if(!property_exists($object,'direction') or $object->direction==='') $object->direction=null; //Направление
if(!property_exists($object,'object_id')) $object->object_id=''; //Автобус
if(!property_exists($object,'date')) $object->date=''; //Дата время начала маршрута план
if(!property_exists($object,'passenger')) $object->passenger=''; //Пассажиров
if(!property_exists($object,'route_id')) $object->route_id='';
if(!property_exists($object,'carrier_id')) $object->carrier_id='';
if(!property_exists($object,'file_name')) $object->file_name=''; //Сопроводительные документы
if(!property_exists($object,'description')) $object->description=''; //Описание
$html='<input style="display:none;" id="e_trip_id" value="'.$object->id.'" type="text">';
$html.='
<table class="SEdit">
<caption></caption>
<thead>
<tr>
<th style="width:40%">'.trt('Name').'</th>
<th style="width:60%">'.trt('Value').'</th>
</tr>
</thead>
<tbody>
<tr style="background-color:#EEEEEE"><td style="font-weight: bold;">'.trt('Trip_type').'</td><td><select style="width: 100%;" id="e_trip_type_id"><option value=""></option>';
if($object->trip_type_id===1)
{
$html.='<option value="1" selected="true">'.trt('Primary').'</option>';
$html.='<option value="2">'.trt('Optional').'</option>';
}else if($object->trip_type_id===2)
{
$html.='<option value="1">'.trt('Primary').'</option>';
$html.='<option value="2" selected="true">'.trt('Optional').'</option>';
}else
{
$html.='<option value="1">'.trt('Primary').'</option>';
$html.='<option value="2">'.trt('Optional').'</option>';
}
$html.=' </select></td></tr>
<tr style="background-color:#FFFFFF"><td style="font-weight: bold;">'.trt('Route').'</td><td><select style="width: 100%;" id="e_trip_route_id"><option value=""></option>
';
//Выбираю маршруты только для текущего автовакзала
$sql="select id,name from main.routes where del=false and id in (select route_id from main.routes_companies where del=false and company_id=(select company_id from main._users where id=".$_SESSION['USER_ID'].")) order by name;";
$res = $db->query($sql);
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
if($row['id']==$object->route_id)
{
$html.='<option value="'.$row['id'].'" selected>'.$row['name'].'</option>';
}else
{
$html.='<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
}
$html.='</select></td></tr>
<tr style="background-color:#EEEEEE"><td style="font-weight: bold;">'.trt('Direction').'</td><td><select style="width: 100%;" name="trip_direction" id="e_trip_direction"><option value=""></option>
';
if($object->direction===1 or $object->direction===true)
{
$html.='<option value="1" selected>Прямой</option><option value="0">Обратный</option>';
}else if($object->direction===0 or $object->direction===false)
{
$html.='<option value="1">Прямой</option><option value="0" selected>Обратный</option>';
}else
{
$html.='<option value="1">Прямой</option><option value="0">Обратный</option>';
}
$html.='</select></td></tr>
<tr style="background-color:#FFFFFF"><td style="font-weight: bold;">'.trt('Carrier').'</td><td><select style="width: 100%;" name="trip_carrier_id" id="e_trip_carrier_id"><option value=""></option>
';
//Выбираю перевозчика для заданого маршрута (и для заданого автовакзала)
$sql='
select c.* from
main.companies c
join (
select company_id from main.trips_schedules where del=false and route_id in (select route_id from main.routes_companies where del=false and company_id=(select company_id from main._users where del=false and id='.$_SESSION['USER_ID'].'))
union
select company_id from main.routes_companies where del=false and route_id in (select route_id from main.routes_companies where del=false and company_id=(select company_id from main._users where del=false and id='.$_SESSION['USER_ID'].'))
)t on c.id=t.company_id
where company_id!=(select company_id from main._users where del=false and id='.$_SESSION['USER_ID'].')
order by c.name
';
$res = $db->query($sql);
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
if($row['id']==$object->carrier_id)
{
$html.='<option value="'.$row['id'].'" selected>'.$row['name'].'</option>';
}else
{
$html.='<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
}
$html.='
</select></td></tr>
<tr style="background-color:#EEEEEE"><td>'.trt('Bus').'</td><td><select style="width: 100%;" name="object_id" id="e_trip_object_id"><option value=""></option>
';
//Выбираю перевозчика для заданого маршрута
$res = $db->query("select id,name from main.objects where del=false order by name;");
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
if($row['id']==$object->object_id)
{
$html.='<option value="'.$row['id'].'" selected>'.$row['name'].'</option>';
}else
{
$html.='<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
}
$html.='
</select></td></tr>
<tr style="background-color:#FFFFFF"><td style="font-weight: bold;">Дата время начала маршрута план</td><td><table><tbody><tr><td style="padding: 0px; width: 100%;"><input style="width: 100%;" name="trip_date_start" id="e_trip_date_start" value="'.$object->date.'" type="text"></td><td style="padding: 0px;"><img id="e_trip_date_start_s" src="../resources/monitoring/images/datepicker.jpg" style="cursor: pointer; padding-left:1px;"></td></tr></tbody></table></td></tr>
<tr style="background-color:#FFFFFF"><td>'.trt('Passengers').'</td><td><input style="width: 100%; height: 22px;" name="trip_passenger" id="e_trip_passenger" value="'.$object->passenger.'" type="text"></td></tr>
<tr style="background-color:#FFFFFF"><td>Сопроводительные документы</td><td><table><tbody><tr><td style="padding: 0px; width: 100%;"><input style="width: 100%;opacity:0.5;" name="trip_file_name" id="e_trip_file_name" value="'.$object->file_name.'" type="text" readonly></td><td style="padding: 0px 0px 0px 1px;"><input class="button-secondary" id="e_trip_btn_select_file" type="button" value="'.trt('Choose').'"></td><td style="padding: 0px 0px 0px 1px;"><input class="button-secondary" id="e_trip_btn_download_file" type="button" value="'.trt('Download').'"></td><td style="padding: 0px 0px 0px 1px;"><input class="button-secondary" id="e_trip_btn_delete_file" type="button" value="'.trt('Delete').'"></td></tr></tbody></table></td></tr>
<tr style="background-color:#EEEEEE"><td>'.trt('Description').'</td><td><textarea id="e_trip_description" style="width: 100%;" rows="4" name="trip_description">'.$object->description.'</textarea></td></tr>
<tr><td style="padding: 5px; vertical-align: bottom; background-color: rgb(245, 245, 245);" colspan="2" align="right"><input class="button-secondary" style="width: 90px;" value="Применить" type="button" onclick="g_trips.saveTrip();"><input class="button-secondary" style="width: 90px;" value="Отмена" type="button" onclick="alert(\'test\');"></td></tr>
</tbody>
</table>
';
header('Content-Type: text/plain');
echo $html;
exit;
}else if($fn=='3') //Создать/изменить запись в базе
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
try
{
$object = json_decode($HTTP_RAW_POST_DATA);
}catch (Exception $e)
{
$json='{"errorMessage":"'.$e->getMessage().'"}';
header('Content-Type: application/json');
echo $json;
exit;
}
//if($object==null) $object = (object)[];
if(!property_exists($object,'id') or $object->id=='') $object->id=null;
if(!property_exists($object,'trip_type_id') or $object->trip_type_id=='') $object->trip_type_id=null;
if(!property_exists($object,'route_id') or $object->route_id=='') $object->route_id=null;
if(!property_exists($object,'direction') or $object->direction==='') $object->direction=null;
if(!property_exists($object,'carrier_id') or $object->carrier_id==='') $object->carrier_id=null;
if(!property_exists($object,'date_start') or $object->date_start==='') $object->date_start=null;
if(!property_exists($object,'passenger') or $object->passenger==='') $object->passenger=null;
if(!property_exists($object,'date')) $object->date='';
if(!property_exists($object,'route_id')) $object->route_id='';
if(!property_exists($object,'file_name')) $object->file_name='';
if(!property_exists($object,'description')) $object->description='';
if($object->id==null) //Новая запись
{
$sql='insert into main.trips(trip_type_id,route_id,direction,company_carrier_id,object_id,date_start,passenger,file_name,description)values(:trip_type_id,:route_id,:direction,:company_carrier_id,:object_id,:date_start,:passenger,:file_name,:description) RETURNING id;';
$stmt = $db->prepare($sql);
if($stmt === false) sendError('Error preparing Statement');
$stmt->bindParam(':trip_type_id', $object->trip_type_id, PDO::PARAM_STR);
$stmt->bindParam(':route_id', $object->route_id, PDO::PARAM_INT);
$stmt->bindParam(':direction', $object->direction, PDO::PARAM_BOOL);
$stmt->bindParam(':company_carrier_id', $object->carrier_id, PDO::PARAM_INT); //перевозчик
$stmt->bindParam(':object_id', $object->object_id, PDO::PARAM_INT); //Автобус перевозчика
$stmt->bindParam(':date_start', $object->date_start, PDO::PARAM_STR);
$stmt->bindParam(':passenger', $object->passenger, PDO::PARAM_INT); //Пассажиров
$stmt->bindParam(':file_name', $object->file_name, PDO::PARAM_STR);
$stmt->bindParam(':description', $object->description, PDO::PARAM_STR);
try
{
$res = $stmt->execute();
} catch (Exception $e)
{
$json='{"errorCode":1,"errorMessage":'.json_encode($e->getMessage(),JSON_UNESCAPED_UNICODE).'}';
header('Content-Type: application/json');
echo $json;
exit;
}
$id='';
if($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$id=$row['id'];
}
$stmt=null;
//Если запись добавлена информируем автобусный парк, чтобы он назначил автобус на заданый рейс
if($id!='')
{
$route_name='';
$sql="select id,name from main.routes where id=".$object->route_id;
$res = $db->query($sql);
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
$route_name=$row['name'];
}
$sql='insert into main.messages(subject,"text",company_carrier_id,action_name,action_settings)values(:subject,:text,:company_carrier_id,:action_name,:action_settings);';
$stmt = $db->prepare($sql);
if($stmt === false) sendError('Error preparing Statement');
//Так как bindParam принимает ссылки на переменные то создаём эти переменные
$subject='Warning';
$text='Вам был назначен рейс "'.$route_name.'" начало рейса в "'.$object->date_start.'", пожалуйста назначте автобус на это рейс!';
$action_name='Edit_trip';
$action_settings='{"trip_id":'.$id.'}';
$stmt->bindParam(':subject', $subject, PDO::PARAM_STR);
$stmt->bindParam(':text', $text, PDO::PARAM_STR);
$stmt->bindParam(':company_carrier_id', $object->carrier_id, PDO::PARAM_INT);
$stmt->bindParam(':action_name', $action_name, PDO::PARAM_STR);
$stmt->bindParam(':action_settings', $action_settings, PDO::PARAM_STR);
try
{
$res = $stmt->execute();
} catch (Exception $e)
{
$json='{"errorCode":1,"errorMessage":'.json_encode($e->getMessage(),JSON_UNESCAPED_UNICODE).'}';
header('Content-Type: application/json');
echo $json;
exit;
}
}
}else //Обновляем старую запись
{
$sql='update main.trips set trip_type_id=:trip_type_id,route_id=:route_id,direction=:direction,company_carrier_id=:company_carrier_id,object_id=:object_id,date_start=:date_start,passenger=:passenger,file_name=:file_name,description=:description where id=:id';
$stmt = $db->prepare($sql);
if($stmt === false) sendError('Error preparing Statement');
$stmt->bindParam(':trip_type_id', $object->trip_type_id, PDO::PARAM_STR);
$stmt->bindParam(':route_id', $object->route_id, PDO::PARAM_INT);
$stmt->bindParam(':direction', $object->direction, PDO::PARAM_BOOL);
$stmt->bindParam(':company_carrier_id', $object->carrier_id, PDO::PARAM_INT); //перевозчик
$stmt->bindParam(':object_id', $object->object_id, PDO::PARAM_INT); //Автобус перевозчика
$stmt->bindParam(':date_start', $object->date_start, PDO::PARAM_STR);
$stmt->bindParam(':passenger', $object->passenger, PDO::PARAM_INT); //Пассажиров
$stmt->bindParam(':file_name', $object->file_name, PDO::PARAM_STR);
$stmt->bindParam(':description', $object->description, PDO::PARAM_STR);
$stmt->bindParam(':id', $object->id, PDO::PARAM_INT);
try
{
$res = $stmt->execute();
} catch (Exception $e)
{
$json='{"errorCode":1,"errorMessage":'.json_encode($e->getMessage(),JSON_UNESCAPED_UNICODE).'}';
header('Content-Type: application/json');
echo $json;
exit;
}
}
$json='{}';
header('Content-Type: application/json');
echo $json;
exit;
}else if($fn=='4') //Загрузить файл на сервер
{
session_write_close(); //Разблокируем сессионный файл так как запросы могут быть достаточно долгими
$dir = $_SERVER['DOCUMENT_ROOT']."/temp/";
//Так как у файлов могут быть одинаковые имена считаем CRC и переименовываем файл отправля пользователю новое название файла
//В базе данных название файла будет преобразовываться так: "файл.txt" -> "файл_crc32.txt"
if(isset($_FILES['file']))
{
if(file_exists($_FILES['file']['tmp_name']))
{
$hash = hash_file( 'crc32', $_FILES['file']['tmp_name'] );
$new_name=delPHPExt($dir.$hash.'.'.getExtension($_FILES['file']['name']));
if(move_uploaded_file($_FILES['file']['tmp_name'],$new_name))
{
//Отправляем новое название файла клиенту
print "ok=".beforeLast($_FILES['file']['name'],'.').'_'.$hash.'.'.getExtension($_FILES['file']['name'])."\n";
}
}else { print "ok=\n File \"".file_exists($_FILES['file']['tmp_name'])."\" not find"; }
}
print '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">';
print '<html>';
print ' <head>';
print ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
print ' </head>';
print ' <body>';
print ' <form name="form" enctype="multipart/form-data" action="/monitoring/pscripts/trips.php?fn=4" method="post">';
print ' <input type="hidden" name="state" value=""/>';
print ' <input type="file" name="file"><br/>';
print ' <input type="submit" value="Send File">';
print ' <input type="reset" value="Reset">';
print ' </form>';
print ' </body>';
print '</html>';
}else if($fn=='5') //Скачать файл с сервера
{
$dir = $_SERVER['DOCUMENT_ROOT']."/temp/";
$fname='';
if(isset($_GET['fname'])) { $fname=$_GET['fname']; }
$name=beforeLast($fname,'_').'.'.afterLast($fname,'.');
$fname=$dir.afterLast($fname,'_');
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$name.'"');
header('Content-Length: '.filesize($fname));
readfile($fname);
exit;
}

View File

@ -0,0 +1,180 @@
<?php
@session_start();
require_once("../../monitoring/config.php");
require_once("../../monitoring/tools.php");
require_once("../../resources/metadata/include/tools.php");
function sendError($msg)
{
$json='{"errorCode":1,"errorMessage":'.json_encode($msg,JSON_UNESCAPED_UNICODE).'}';
header('Content-Type: application/json');
echo $json;
exit;
}
$db = connectToDB();
$MainFrom = 'irigm@yandex.ru';
//$MainFrom = 'info@motion-engine.com';
$fn=0;
if(isset($_GET['fn'])) { $fn=$_GET['fn']; }
if($fn=='1') //Зарегестрировать нового пользователя и компанию
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if($object==null) sendError(trt("Invalid_request")."!");
$captcha=$_SESSION['secpic1'];
if($captcha!=$object->captcha) {
sendError('The numbers from the picture do not match!');
}else{
$password = getPassword(5);
$sql = "select * from main.p__users_1(1,null,:company_name,:surname,:name,:position,:phone,:email,:password);";
$stmt = $db->prepare($sql);
$stmt->bindParam(':company_name', $object->company, PDO::PARAM_STR);
$stmt->bindParam(':surname', $object->lastname, PDO::PARAM_STR);
$stmt->bindParam(':name', $object->firstname, PDO::PARAM_STR);
$stmt->bindParam(':position', $object->position, PDO::PARAM_STR);
$stmt->bindParam(':phone', $object->phone, PDO::PARAM_STR);
$stmt->bindParam(':email', $object->email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$response = new stdClass();
$response->errorCode = '0';
$response->errorMessage = '';
try
{
$res = $stmt->execute();
} catch (Exception $e)
{
sendError($e->getMessage());
}
$html='<html><head><title>Message</title></head><body>';
$html.='<h1>Поздравляю, Вы зарегистрированы!</h1>';
$html.='<b>Ваш пароль:</b> '.$password.'<br>';
$html.='</body></html>';
//Отсылаю пароль на почту
if(mail($object->email,'Motion-Engine.com',$html,"Content-type: text/html; charset=utf-8\r\nFrom: Motion-Engine Site <".$MainFrom.">"))
{
}else{
sendError('Failed to send password email to!');
}
echo json_encode($response);
exit;
}
}else if($fn=='2') //Восстановление пароля
{
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if($object==null) sendError(trt("Invalid_request")."!");
$captcha=$_SESSION['secpic2'];
if($captcha!=$object->captcha) {
sendError('The numbers from the picture do not match!');
}else{
$password = getPassword(5);
$sql = "update main._users set password='".md5($password)."' where email=lower('".$object->email."');";
$response = new stdClass();
$response->errorCode = '0';
$response->errorMessage = '';
try
{
$db->query($sql);
}catch (Exception $ex)
{
sendError($ex->getMessage());
}
$html='<html><head><title>Message</title></head><body>';
$html.='<h1>Password recovery</h1>';
$html.='<b>Your password has been changed to:</b> '.$password.'<br>';
$html.='</body></html>';
//Отсылаю пароль на почту
if(mail($object->email,'Motion-Engine.com',$html,"Content-type: text/html; charset=utf-8\r\nFrom: Motion-Engine Site <".$MainFrom.">"))
{
}else{
sendError('Failed to send password email to!');
}
echo json_encode($response);
exit;
}
}else if($fn=='3'){ //Смена пароля
if(!isset($HTTP_RAW_POST_DATA))
{ $HTTP_RAW_POST_DATA = file_get_contents("php://input");
}
$object = json_decode($HTTP_RAW_POST_DATA);
if($object==null) sendError(trt("Invalid_request")."!");
//Проверяю есть ли такой пользователь
$sql = "select id from main._users where del=false and password='".md5($object->password)."' and email=lower('".$object->email."');";
try
{
$res = $db->query($sql);
}catch (Exception $ex)
{
sendError($ex->getMessage());
}
if($res==NULL || $res->rowCount()==0)
{
sendError(trt("Invalid_username_and_or_password"));
}
$sql = "update main._users set password='".md5($object->new_password)."' where email=lower('".$object->email."') and password='".md5($object->password)."';";
$response = new stdClass();
$response->errorCode = '0';
$response->errorMessage = '';
try
{
$db->query($sql);
}catch (Exception $ex)
{
sendError($ex->getMessage());
}
echo json_encode($response);
exit;
}else if($fn=='10'){ //Вернуть список для заполнения компаний к которым у пользователя есть доступ
$sql="select id,name,exists(select 1 from main._users where del=false and c.id=company_id and id=".$_SESSION['USER_ID'].") as select from main.companies c where id in (select company_id from main.companies_users where del=false and user_id=".$_SESSION['USER_ID'].") order by name";
try
{
$res = $db->query($sql);
}catch (Exception $ex)
{
sendError($ex->getMessage());
}
if($res != null)
{
while ($row = $res->fetch(PDO::FETCH_ASSOC))// $row - ассоциативный массив значений, ключи - названия столбцов
{
if($row['select'])
echo '<option selected="selected" value="'.$row['id'].'">'.$row['name'].'</option>';
else
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
}
}else{
sendError("Fn is null!");
}