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='';
$html.='
'.trt('Name').'
'.trt('Value').'
'.trt('Trip_type').'
'.trt('Route').'
'.trt('Direction').'
'.trt('Carrier').'
'.trt('Bus').'
Дата время начала маршрута план
'.trt('Passengers').'
Сопроводительные документы
'.trt('Description').'
';
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 '';
print '';
print ' ';
print ' ';
print ' ';
print ' ';
print ' ';
print ' ';
print '';
}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;
}