require_once 'CheckPoint.php';
require_once "doctrine/bootstrap.php";
use \CheckPoints\CheckPoint;
ini_set('error_reporting', 'E_ALL');
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
//defined('YII_DEBUG') or define('YII_DEBUG', false);
//defined('YII_ENV') or define('YII_ENV', 'prod');
require_once 'api/vendor/autoload.php';
require_once 'api/vendor/yiisoft/yii2/Yii.php';
$config = require_once 'api/config/web.php';
(new yii\web\Application($config));
require_once 'auth.php';
require_once 'functions.php';
require_once 'ocs.php';
$varstr = "";
foreach (array_keys($_REQUEST) as $var)
{
${$var}=$_REQUEST[$var];
$varstr .= " $var: ${$var} ";
//echo "$var: ${$var}
";
}
//if ($pnum != '11' )// && $pnum != '38'
// WriteLog("request 2 server.php",$varstr);
include 'problems.php';
$num = intval($pnum);
switch ($num) {
case 1:
Login($num, $id, $did , $tagid);
break;
case 2:
CheckIn($num, $id);
break;
// case 3: requestccordinates position
case 4:
try {
TaskList($num, $id, $verbose);
} catch (\Throwable $e) {
echo $e->getMessage();
}
break;
case 5:
;
break;
case 6:
try {
TaskConfirm($num, $id, $tid, $confirm_data, $verbose);
} catch (\Throwable $e) {
echo $e->getMessage();
}
break;
case 7:
TaskStatusChange($num, $id, $tid);
break;
case 8:
DeviceIsAuthorized($num, $did);
break;
case 9:
DeviceAdd($num, $did);
break;
case 10:
GetOnline($num, $id);
break;
case 11:
Ping($num, $id);
break;
case 12:
ObjPlace($num, $id, $pos, $scale);
break;
case 13:
RequestObj($num, $id);
break;
//14 SendCMDName
//15 SendJobnames
case 16:
TextNote($num, $taskid, $text, $cpid);
break;
case 17:
//in server_post
//ImageNote($num, $taskid, $img);
break;
case 18:
TaskBegin($num, $tid, $echo, $testing);
break;
case 19:
//in server_post
//AudioNote($num, $taskid, $audio);
break;
case 20:
ARObjectRecognized($num, $tid, $sid);
break;
case 21:
try {
TasksCancel($accid, $maintask, $cause);
} catch (\Throwable $e) {
echo $e->getMessage();
}
break;
case 22:
Quit($accid, $fromsite, $tagid);
break;
//TOERASE
case 23:
AcceptProblem($type, $comment);
break;
case 24:
CheckProblem();
break;
case 25:
ResolveProblemStart($id);
break;
case 26:
EndProblem($id);
break;
case 27:
ProblemsQuit($type);
break;
case 28:
LoginChief($login, $p);
break;
case 29:
CheckList($num, $tid);
break;
case 30:
LoginPassword($num, $login, $p, $did, $ver, $app, $tagid);
break;
case 31:
CheckPointAccept($id, $value);
break;
case 32:
saveBeaconData($num, $location_id, $acc_id, $beacon_id, $rssi, $localtime, $pwr);
break;
case 33:
WriteLog($accid, $text);
break;
case 34:
Token($accid, $token);
break;
case 35:
CheckUpdates($num, $ver, $app);
break;
case 36:
OverPlan($num, $accid);
break;
case 37:
GetMarkers($num, $locid);
break;
case 38:
SendCoordinate($num, $pointx, $pointy, $timeStamp, $accId, $locationId, $zoneId);
break;
case 39:
getTaskTypes($num);
break;
case 40:
getStatus($num);
break;
case 41:
getCheckPointTypes($num);
break;
case 42:
getLocoSeries($num);
break;
case 43:
getUserCompany($num,$id);
break;
case 44:
getUserFaceFeature($num,$id);
break;
case 45:
getCameraInfo($num, $id);
break;
case 46:
getObjectInfo($num, $id);
break;
case 60:
Measurement($num, $taskid, $position, $verbose);
break;
}
function MeasurementHardwareCheck($user, $workid, $taskid, $verbose=0)
{
require_once "curlexec.php";
$params['user_id'] = $user;
$params['work_id'] = $workid;
$url = "http://qaplatform.digitaldepot.ru:8085/Thingworx/Things/2050UserLibraryExp/Services/check_hw_measurements_ready";
$result = CURLrequestPOST($url, ["AppKey: 33cd23bb-3b03-4638-afef-7104a13e9211"], $params);
// $result = $taskAnswer;
$json = json_decode($result);
if ($verbose)
var_dump($result);
WriteLog("check_hw_measurements_ready input ".json_encode($params), $result);
if ($json->result == true) {
\app\models\MappingapiModel::updateMeasurements($taskid);
return true;
}
return false;
}
function Measurement($num, $taskid, $position = 0, $verbose = 0)
{
//создать задание на аппаратные замеры
global $link;
$taskAnswer = '{
"result": true,
"data": {
"hw_measurements_status": "waiting",
"measuring_devices": [
"Доктор - 060RLC"
],
"task_id": "428f8962-bf47-ce93-6394-d1865c36f4a8"
}
}';
$work_id = 0;
$user_id = 0;
$stage = 0;
$str = "select work_id, worker, measurement_stage, smopp_task_id from asusg_measurements where smopp_task_id=$taskid limit 1";
$result_pos = mysqli_query($link, $str);
while ($obj = mysqli_fetch_object($result_pos)) {
if (!$work_id)
$work_id = $obj->work_id;
if (!$user_id)
$user_id = json_decode($obj->worker)->id;
if (!$stage)
$stage = $obj->measurement_stage;
}
/**
* @var $task Task
*/
$task = Task::Find($taskid);
if ($task) {
$user_id = $task->account->uuid;
$currentStatus = $task->status;
if ($currentStatus == 6) {
$task_hw = $task->asusg_task_hw_measurement_id;
if ($task_hw)
{
$buf = "";
$check = MeasurementHardwareCheck($user_id, $work_id, $taskid);
if ($check) {
$buf .= pack("C", 3); //measurements completed
$task->status = 7;
$task->Save();
}
else
{
$buf .= pack("C", 2); //measurements not completed
}
$data = ConstructVariablePacket($num, $buf);
echo base64_encode($data);
}
} else {
require_once "curlexec.php";
$params['user_id'] = $user_id;
$params['work_id'] = $work_id;
$params['section_position_number'] = $position;
$params['measurement_stage'] = $stage;
$url = "http://qaplatform.digitaldepot.ru:8085/Thingworx/Things/2050UserLibraryExp/Services/task_for_hw_measurements";
$result = CURLrequestPOST($url, ["AppKey: 33cd23bb-3b03-4638-afef-7104a13e9211"], $params);
// $result = $taskAnswer;
$json = json_decode($result);
WriteLog("task_for_hw_measurements input " . json_encode($params), $result);
$buf = ""; //заголовок - v-ushort, c- byte, C- ubyte, s - short, L - int, l - uint
if ($json->result == true) {
$name = $json->data->measuring_devices[0];
$task_hw_id = $json->data->task_id;
if ($task_hw_id) {
$task = Task::Find($taskid);
if ($task) {
$task->status = 6;
$task->asusg_task_hw_measurement_id = $task_hw_id;
$task->Save();
}
}
$buf .= pack("C", 1);
$buf .= pack("v", strlen($name));
$buf .= $name;
if ($verbose) {
echo " dev: $name stage $stage pos $position user_id $user_id
";
}
} else {
$buf .= pack("C", 0);
}
$data = ConstructVariablePacket($num, $buf);
if ($verbose) {
$ans = unpack('C', $data, 3);
echo "answer:
";
var_dump($ans);
}
echo base64_encode($data);
}
}
}
function ARObjectRecognized($num, $tid, $sid)
{
//get scenario id from sid
//get object_id from scenario
//update task object recognized with object_id
global $link;
//$str = "update tasks t JOIN ar_scenarios ars on ars.id=$sid set t.ar_object_id=ars.object_id where t.id = $tid";
$str = "update tasks t JOIN ar_stages ars on ars.scenario_id=$sid and ars.priority = (SELECT MAX(priority) from ar_stages where scenario_id=$sid) set t.ar_object_id=ars.object_id where t.id = $tid";
if (mysqli_query($link, $str))
echo 1;
else
echo 0;
}
function getStatus($num)
{
global $link;
$str = "SELECT id, name, color FROM task_status_names";
$retarr = array();
$query = mysqli_query($link, $str);
while ($res = mysqli_fetch_assoc($query))
{
$retarr[] = $res;
}
echo json_encode($retarr, JSON_UNESCAPED_UNICODE);
}
function getCheckPointTypes($num)
{
global $link;
$str = "SELECT id, name, class FROM checkpoint_types";
$retarr = array();
$query = mysqli_query($link, $str);
while ($res = mysqli_fetch_assoc($query))
{
$retarr[] = $res;
}
//var_dump($retarr);
echo json_encode($retarr, JSON_UNESCAPED_UNICODE);
}
function getLocoSeries($num)
{
global $link;
$str = "SELECT id, name FROM locomotive_series";
$retarr = array();
$query = mysqli_query($link, $str);
while ($res = mysqli_fetch_assoc($query))
{
$retarr[] = $res;
}
//var_dump($retarr);
echo json_encode($retarr, JSON_UNESCAPED_UNICODE);
}
function getTaskTypes($num)
{
global $link;
$str = "SELECT id, name, description, confirmtype, time_to_complete_minutes FROM tasktypes WHERE main_task <> 1";
$retarr = array();
$query = mysqli_query($link, $str);
while ($res = mysqli_fetch_assoc($query))
{
$retarr[] = $res;
}
echo json_encode($retarr, JSON_UNESCAPED_UNICODE);
}
function SendCoordinate($num, $pointx, $pointy, $timeStamp, $accId, $locationId, $zoneId)
{
global $link;
$timeStamp = urldecode($timeStamp);
$newpointx = str_replace(',', '.', $pointx);
$newpointy = str_replace(',', '.', $pointy);
$str = "INSERT INTO user_positions (COORD_X, COORD_Y, TS, ACC_ID, LOCATION_ID, ZONE_ID) VALUES ($newpointx, $newpointy, '$timeStamp', $accId, $locationId, $zoneId)";
// echo $str;
if (mysqli_query($link, $str))
echo base64_encode(pack("CC",$num, 1));
else
echo base64_encode(pack("CC",$num, 0));
}
function GetMarkers($num, $locid)
{
global $link;
$str = "SELECT UUID, X, Y FROM BEACONS WHERE LOCATION_ID=$locid";
$retarr = array();
$query = mysqli_query($link, $str);
while ($res = mysqli_fetch_assoc($query))
{
$retarr[] = $res;
}
//var_dump($retarr);
echo json_encode($retarr);
}
function OverPlan($num, $accid)
{
$account = Account::Find($accid);
if ($account != null) {
if ($account->overplan_mode == 1)
$account->overplan_mode = 0;
else
$account->overplan_mode = 1;
}
Account::ClearTasksFromAccount($accid, false);
$account->Save();
$buf = pack("CC*",$num, $account->overplan_mode);
echo base64_encode($buf);
// MessageToClient("OverPlan!!!1", 2, 1);
}
function CheckUpdates($packetnum, $ver, $app)
{
if (isset($ver) && isset($app))
{
$appdata = GetAppData($ver, $app);
if ($appdata) {
$path = $appdata['app_update_path'];
$ver = $appdata['app_update_filename'];
$md5 = $appdata['md5'];
$answer = 1;
$buf = pack("C*", $answer); //заголовок - v-ushort, c- byte, C- ubyte, s - short, L - int, l - uint
$buf .= pack("v*", strlen($path));
$buf .= $path;
$buf .= pack("v*", strlen($ver));
$buf .= $ver;
$buf .= pack("v*", strlen($md5));
$buf .= $md5;
}
else {
$answer = 0;
$buf=pack("C", $answer);
}
$c = ConstructVariablePacket($packetnum, $buf);
echo base64_encode($c);
}
}
function Token($accid, $token)
{
if (!$token)
return;
global $link;
$str = "update accounts set android_token_id = '$token' where id=$accid";
mysqli_query($link, $str);
}
function saveBeaconData($num, $location_id, $acc_id, $beacon_id, $rssi, $localtime, $pwr)
{
global $link;
$localtime = urldecode($localtime);
//$pwr = urldecode($pwr);
$str = "INSERT INTO beacons_scan_data (location_id, acc_id, beacon_id, rssi, local_time, servertime, pwr) VALUES ($location_id, $acc_id, $beacon_id, $rssi, '$localtime', NOW(), '$pwr')";
mysqli_query($link, $str);
// if (mysqli_query($link, $str))
// echo '1';
// else
// echo '0';
//echo "$str";
}
function CheckPointAccept($id, $value, $test=false)
{
$cp = CheckPoint::CreateFromID($id);
$cp->SetValue($value);
$task = Task::Find($cp->parentTaskId);
WriteLog("$id CheckPointAccept $cp->id $cp->typeId ", $cp->parentTaskId);
\app\models\entity\Metrics::log(1, 31, 'taskId = ' . ($task->id ?? 0));
if (isset($task))
{
$acc = $task->account;
$uuid = "";
if (isset($acc))
$uuid = $acc->uuid;
$measurement = IsMeasurement($task->id);
if ($measurement)
{
if ($cp->value || $cp->state)
$cp->WriteValueToMeasurement($measurement, $cp->value, $uuid);
}
if (isset($acc)) {
$task->account->last_action = new \DateTime("now");
$task->account->Save();
}
}
// $cp->AddRemark();
}
function Construct2BytePacket($num, $byte)
{
$buf = pack("CC*", $num, $byte); //заголовок - номер пакета 1б и длина 2б. v-ushort, c- byte, C- ubyte, s - short, L - int, l - uint
return $buf;
}
function ConstructVariablePacket($num, $vardatabytes)
{
$buf = pack("C*", $num); //заголовок - номер пакета 1б и длина 2б. v-ushort, c- byte, C- ubyte, s - short, L - int, l - uint
$len = strlen($vardatabytes)+3;
$buf .= pack("v*", $len);
$buf .= $vardatabytes;
return $buf;
}
function Quit($accid, $fromsite = false, $tagid)
{
global $link;
/**
* @var $account Account
*/
$account = Account::Find($accid);
if ($account != null)
{
$last = new \DateTime("-11minutes");
$account->setLastSeenMobile($last);
// $account->android_token_id = '';
$account->quit_set = 1;
$account->Save();
OCSlogoff($accid);
if ($tagid)
VagrantRequest($accid, $tagid, $account->name, 2);
if ($fromsite)
EnqueueCMD($accid, "22");
}
}
//from client
function TasksCancel($accid, $maintask, $cause)
{
$mappingapiModel = new \app\models\MappingapiModel();
$res = $mappingapiModel->setPause($accid, $maintask);
Account::ClearTasksFromAccount($accid, false, $maintask);
$buf = pack("C", 21);
if ($cause)
{
//TWX work close
// вот список
// Причина1 Отсутствие ТМЦ
// Причина2 Отсутствие оборудования
// Причина3 Отсутствие инструмента
// Причина4 Не мое задание (не моя квалификация)
// Причина5 Прочее
}
echo base64_encode($buf);
}
function TaskControlMapCheck($tid, $echo=0)
{
if ($echo)
echo "TaskControlMapCheck!";
global $link;
$checked = 1;
$cps = CheckPoint::FindAllByTask($tid);
if (sizeof($cps) > 0)
{
foreach ($cps as $cp) {
if ($cp->parentCheckpointId == 0) {
if (0 == $cp->state || null == $cp->state) {
$checked = 0;
break;
}
}
}
}
return $checked;
}
function FindTMCId($tmcType)
{
//найти первый свободный ТМЦ нужного типа
global $link;
// var_dump($tmcType);
$query = mysqli_query($link, "select id from tmc where employee=0 and tmc_type = $tmcType");
if ($res = mysqli_fetch_assoc($query))
{
// var_dump($res);
return $res['id'];
}
return 0;
}
function TaskBegin($num, $tid, $echo, $testing=false)
{
global $link;
$task = Task::Find($tid);
//$exec = \app\models\MappingworksModel::workToExecute($tid);
//if (!$exec) {
// $test = true;
//}
// if ($echo)
// echo "TaskBegin $num $tid task id: $task->id status $task->status
";
$exec = \app\models\MappingworksModel::workToExecuteBegin($tid);
if ($task != null && intval($task->status) == 2){
$tasktype = Tasktype::Find($task->type);
$objtype = $tasktype->object_type;
// if ($echo) {
// echo "task not null";
// }
$tmcId = FindTMCId($objtype);
// if ($echo) {
// echo "objtype $objtype tasktype tmcId " . $tmcId;
// }
$proj = $task->project;
$canBegin = true;
// WriteLog("test request tmcId $tmcId ", isset($proj));
if (intval($tmcId) > 0 && isset($proj))
{
// if ($echo)
// echo "$tmcId objtype $objtype";
////
// $locotype = $proj->getLocoType();
// $loconumber = $proj->loco_number;
$sid = 0;
$section = $task->getSection();
// if ($section)
// $sid = $section->id;
// WriteLog("test request task $task->id ", $sid);
if ($section) {
// if ($echo)
// echo "section ! $section->id";
require_once("curlexec.php");
// $reqstring = "http://oiltest.prmsys.net/api/handler/sessionstart?device=$tmcId§ion_id=$section->id&loco_type=$locotype&loco_number=$loconumber";
// $reqstring = "http://oiltest.prmsys.net/api/handler/sessionstart?deviceId=$tmcId§ion_id=$section->id";
$reqstring = "http://oiltest.prmsys.net/api/session/start?deviceId=$tmcId§ionId=$section->id";
$result = CURLrequestGET($reqstring,["uuid-key: 07a13c8907d1-6a7bdba1-a2fz-aatgu4j"]);
// WriteLog("test request", $reqstring);
if ($result == 'false')
$canBegin = false;
}
}
if (!$testing) {
if ($canBegin) {
\app\models\ElasticLog::command((int)$tid, 'Принятие к исполнению');
OCStaskstatus($tid, 3, $task->assignees_arr);
mysqli_query($link, "update tasks set status = 3, accepted_time = NOW() where id=" . $tid);
mysqli_query($link, "update tasks set object_id=$tmcId, status = 3 where id=$task->parent_id");
if ($proj != null) {
if (!$proj->started)
mysqli_query($link, "update projects_locotech set status = 3, started= now() where id=" . $proj->id);
else
mysqli_query($link, "update projects_locotech set status = 3 where id=" . $proj->id);
}
$buf = pack("Cll", $num, $tmcId, $tid);
echo base64_encode($buf);
} else {
$buf = pack("Cll", $num, 0, 0);
echo base64_encode($buf);
}
}
}
}
function RequestObj($num, $id)
{
//echo "RequestObj ".$id;
global $link;
$query = mysqli_query($link, "select * from object_field where id=".$id);
if ($res = mysqli_fetch_array($query))
{
//$buf = $res['position'].'|'.$res['scale'];
//echo $res['position']." ".$res['scale'];
$buf = pack("C", 13);
$buf .= $res['position']." ".$res['scale'];
echo base64_encode($buf);
//echo "RequestObj ".$id;
}
}
function TextNote($num, $taskid, $text, $cpid)
{
$task = Task::Find($taskid);
$answer = 1;
$tasknote = new Tasknote();
if ($task == null)
$answer = 2;
else {
if (isset($task->account)) {
$task->account->last_action = new \DateTime("now");
$task->account->Save();
}
$tasknote->date = new DateTime('now');
$tasknote->text = $text;
$tasknote->task = $task;
if ($cpid)
$tasknote->checkpoint_id = $cpid;
// else
// {
// $result = $task->AddRemark($text);
// $json = json_decode($result);
// if ($json != null) {
// $tasknote->remark_id = $json->RemarkId;
// $tasknote->code1c = $json->Kod;
// $tasknote->guid = $json->Guid;
// $tasknote->twx_result = $result;
// $answer = 4;
// }
// }
$tasknote->Save();
}
$c = Construct2BytePacket($num, $answer);
echo base64_encode($c);
}
function ObjPlace($num, $id, $pos, $scale)
{
//echo "ObjPlace";
global $link;
mysqli_query($link, "update object_field set position = '".$pos."', scale='".$scale."' where id=".$id);
$buf = pack("C", 12);
//$buf .= $res['position']." ".$res['scale'];
echo base64_encode($buf);
//echo "updated id ".$id." coords ".$pos." scale ".$scale;
}
function GetOnline($num, $accid)
{
global $link;
//date(strtotime($date." -3 minutes"));
//echo $time. ' last seen '.$date1.' now '.date('d.m.Y H:i',time());
GetOnlineAccountList(true);
}
function Command($accid)
{
$cmdarr = DequeueCMD($accid);
//пока достаем по одной команде
$ret = false;
foreach ($cmdarr as $cmd) {
if ($cmd == '21') {
$buf = pack("C", 21);
$ret = true;
}
if ($cmd == '22') {
SendPush($accid, "Logout by server!", "");
$buf = pack("C", 22);
$ret = true;
}
if ($cmd == '36_1') {
//SendPush($accid, "Overplan!", "");
$buf = pack("CC*",36, 1);
$ret = true;
}
if ($cmd == '36_0') {
//SendPush($accid, "Overplan!", "");
$buf = pack("CC*",36, 0);
$ret = true;
}
}
echo base64_encode($buf);
return $ret;
}
function MessageToClient($text, $code, $fromId)
{
$buf = pack("Clv", $code, $fromId, strlen($text));
$buf .= pack($text);
$data = ConstructVariablePacket(61, $buf);
echo base64_encode($data);
}
function Ping($num, $accid)
{
if ($accid > 0) {
global $link, $companyID;
$buf = pack("C", 11);
$acc = Account::Find($accid);
$quit = $acc->quit_set;
if ($quit) {
mysqli_query($link, "update accounts set quit_set=0, last_seen_mobile = NOW() where id =" . $accid);
$res = mysqli_query($link, "SELECT MAX(date_entry) as date FROM auth_log where account_id =" . $accid);
mysqli_query($link, "update auth_log set date_finish_task = NOW() where account_id =" . $accid ." and date_entry = '". mysqli_fetch_assoc($res)['date']."'" );
$tagid = GetVagrantTagID($accid);
if ($tagid) {
VagrantRequest($accid, $tagid, $acc->name, 1);
}
}
else
mysqli_query($link, "update accounts set last_seen_mobile = NOW() where id =" . $accid);
\app\models\entity\UserActivity::ping($accid);
// TasksAssign('', true, 0, false, $accid);
if (!Command($accid))
echo base64_encode($buf);
}
}
function DeviceAdd($num, $did)
{
global $link;
$buf = pack("CC*", 9, 1);
mysqli_query($link, "INSERT into devices (id, date) values ('".$did."', NOW())");
echo base64_encode($buf);
// echo "DeviceAdd".$did;
}
function TaskStatusChange($num, $id, $tid)
{
}
function TaskStatusChangeSend($status, $tid)
{
$buf = pack("C", 7);
$buf .= pack("Cl*", $status, $tid);
echo base64_encode($buf);
}
function DeviceIsAuthorized($num, $did)
{
global $link;
$answer = 0;
$buf = pack("C", $num);
$query = mysqli_query($link, "SELECT name FROM devices where id= '".$did."'");
if ($res = mysqli_fetch_row($query))
{
$answer = 1;
}
$buf .= pack("C", $answer);
echo base64_encode($buf);
}
function LoggedIn($myid)
{
return true;
}
function GetDayPlanned($accid)
{
global $link;
$str = "SELECT t.id, t.type, t.input_id, tt.letter, pr.loco_number from tasks as t join projects_locotech as pr on t.input_id=pr.id join tasktypes as tt on t.type = tt.id join asusg_dayplan as ad on tt.letter = ad.letter where assignees_arr=$accid and ad.day = cast((now() - interval 0 day) as date) and t.priority=0 and ad.loco_num=pr.loco_number order by ad.priority asc limit 1";
$query = mysqli_query($link, $str);
if ($res1 = mysqli_fetch_object($query)) {
return Task::Find($res1->id);
}
}
//todo Убрать $control!
function TaskList($numpacket, $account_id, $verbose=false)
{
global $link, $companyID;
global $entityManager;
// $tasks = array();
mysqli_query($link, "update accounts set last_seen_mobile=NOW() where id=".$account_id);
mysqli_query($link, "insert into tmp_lastseenmobile (user_id, last_seen_mobile) values ($account_id, NOW())");
$account = Account::Find($account_id);
if (!$account) {
if ($verbose)
{
echo "no account $account_id";
}
return;
}
$company = $account->getCompany();
$companyID = $company->id;
// TasksAssign('', true, 0, $verbose, $account_id);
$buf="";
$projid = 0;
$loco_num = 0;
$series = "";
/**
* @var $account Account
*/
//$t = $account->getAcceptedTasks()->first();
$planned_id = GetDayPlanned($account_id);
if (!$planned_id) {
if ($verbose)
echo "
!GetDayPlanned
";
$t = $account->getFirstActiveTaskMain();
}
else
$t = $planned_id;
if (!$t) {
if ($verbose)
echo "
!getFirstActiveTaskMain
";
$t = $account->getActiveTasks()->first();
}
if ($t)
{
if ($verbose) {
echo "
Task fisrt found:
";
\Doctrine\Common\Util\Debug::dump($t);
}
/**
* @var $pr Project
*/
$pr = $t->project;
if ($pr) {
if ($verbose)
echo('project found ' . $pr->id);
$tasks = $pr->getPrimaryTasks($account_id, $planned_id);
if ($verbose)
{
echo('pr ' . $pr->id);
echo('tasks1 size ' . sizeof($tasks));
}
}
}
if (!$tasks) {
// $tasks = $account->getActiveTasks();
if ($verbose)
echo ('!tasks '.sizeof($tasks));
}
//foreach ($account->getActiveTasks() as $task) {
foreach ($tasks as $task) {
$taskid = $task->id;
$asu = ASUSG($task->asusg_job_mapped_id);
// if ($verbose) {
// var_dump($asu);
// }
$outfit = 0;
$time_limit = 0;
if ($asu)
{
$time_limit = $asu[0]['time_limit'];
$outfit = $asu[0]['outfit'];
}
$status = GetTaskStatus($taskid);
$status = $task->status;
if ($status != '2' && $status != '3' && $status != '6' && $status != '7') {
if ($verbose) {
var_dump($task->id);
}
continue;
}
$type = $task->type;
$priority = $task->priority;
if ($verbose)
{
echo "
$taskid $priority ".$task->project->id." $task->status
";
}
$namedesc = GetTaskNameAndDesc($type);
$tt = GrabTasktype($type);
$timer = $tt['time_to_complete_minutes'];
$record_video = $tt['record_video'];
$objectType = $tt['object_type'];
$letter = $tt['letter'];
if (!$letter)
$letter = " ";
$name = $namedesc[0];
if ($task->name) {
$name = $task->name;
}
$text = $task->text;
$scenario_id = $tt['scenario_id'];
if ( 'Мэппинг.' == $text ) {
$text = explode(':', $task->text)[1];
}
if (!isset ($name) || $name == null || $name == '')
$name = "Empty Task!";
if (!isset ($text) || $text == null || $text == '') {
$text = $tt['description'];
}
if (!isset ($text) || $text == null || $text == '')
$text = "Empty Text";
$confirmtype = getConfirmTypebyTask($taskid);
$lenname = strlen($name);
$lentext = strlen($text);
if ($projid == 0)
{
/**
* @var $proj Project
*/
/**
* @var $section Section
*/
$proj = $task->project;
$projid = $proj->id;
$series = $proj->loco_type;
$loco_num = $proj->loco_number;
if ($verbose) {
echo "series1 $series";
echo "loconum $proj->loco_number";
echo "loco_type $proj->loco_type";
}
$buf .= pack("ll",$projid, $loco_num);
$buf .= pack("v",strlen($series));
$buf .= $series;
$buf .= $letter;
}
$buf .= pack("clcclvvl", $status, $priority, $confirmtype, $timer, $taskid, $lenname, $lentext, $type); //заголовок - номер пакета 1б и длина 2б. v-ushort, c- byte, C- ubyte, s - short, L - int, l - uint
$buf .= $name;
$buf .= $text;
$control = "";
//$lencontrol = strlen($control);
//$buf .= pack("v*",$lencontrol);
$buf .= pack("v",$company->GetConfirmTimeout());
$buf .= pack("C",$record_video);
$buf .= pack("l",$objectType);
if ($scenario_id)
$buf .= pack("C", 1);
else
$buf .= pack("C",0);
$buf .= pack("l",$outfit);
$buf .= pack("l",$time_limit);
$buf .= pack("l",$task->object_id);
$buf .= pack ("l", $task->parent_id);
// $buf .= $control;
}
$c = ConstructVariablePacket($numpacket, $buf);
echo base64_encode($c);
\app\models\entity\UserActivity::ping($account_id);
}
function CheckList($numpacket, $task_id)
{
//$buf = pack("C", $numpacket);
$buf = '';
$checkpoints = CheckPoint::Find("all", $task_id);
//echo "checkpoints taks $task_id ".sizeof($checkpoints);
foreach ($checkpoints as $checkpoint)
{
$buf .= $checkpoint->PackToBinary();
$buf .= $checkpoint->PackChildrenToBinary();
}
$c = ConstructVariablePacket($numpacket, $buf);
echo base64_encode($c);
}
function CheckIn($num, $accountId)
{
global $link;
$query = mysqli_query($link, "select text, name from documents where id=1");
$buf="";//pack("c*",$num);
$add = "";
$fail = pack("c",0);
if ($res1 = mysqli_fetch_array($query)) {
$text = $res1['text'];
if (strlen($text) > 0)
{
$did = getCurrentDeviceId($accountId);
$sess = getActiveSession($accountId);
if ($did != $sess["device_id"] && $sess["end"] != NULL)
{
$add .= $fail;
}
else
{
$sid = $sess["id"];
mysqli_query($link, "update sessions set checkin_start = NOW() where account_id=".$accountId." and id=".$sid);
$add .= $text;
}
}
}
$buf .= $add;
$c = ConstructVariablePacket($num, $buf);
echo base64_encode($c);
}
function Login($packetNum, $id, $did, $tagid)
{
global $link;
$answer = 0;
$name = "";
$cmdlevel = 0;
if (isset($id) && isset($did))
{
$query = mysqli_query($link, "select * from accounts where id=" . $id);
if ($res1 = mysqli_fetch_array($query)) {
$name = $res1['name'];
$cmdlevel = intval($res1['cmdlevel']);
if ($cmdlevel > 0)
{
//Login OK!
//echo $name." id ".$id."act ".$cmdlevel." did ".$did;
$answer = 1;
mysqli_query($link, "update accounts set quit_set = 0, overplan_mode=0 where id=$id");
mysqli_query($link, "insert into sessions (account_id, start, device_id) values ($id, NOW(), '$did')");
}
}
}
if ($answer == 1) {
if ($tagid)
VagrantRequest($id, $tagid, $name, 1);
$buf = pack("ClC*", $answer, $id, $cmdlevel); //заголовок - v-ushort, c- byte, C- ubyte, s - short, L - int, l - uint
$buf .= $name;
OCSlogin($id);
}
else
{
$buf = pack("C*", $answer);
}
$c = ConstructVariablePacket($packetNum, $buf);
echo base64_encode($c);
}
function getUserCompany($pnum,$id)
{
global $link;
$id = (int)$id;
$result = [0 => ''];
$str = "SELECT company FROM `accounts_internal` WHERE `id`=". $id;
$query = mysqli_query($link, $str);
$result = mysqli_fetch_row($query);
$buf = pack("Cl", $pnum, $result[0]);
echo base64_encode($buf);
}
function getUserFaceFeature($pnum,$id)
{
global $link;
$id = (int)$id;
$res = 0;
$str = "SELECT `id_account`,`face_feature`,`date` FROM `face_feature` WHERE `id_account`=". $id ." ORDER BY `date` DESC LIMIT 1";
$query = mysqli_query($link, $str);
$result = mysqli_fetch_assoc($query);
if ( isset($result['face_feature']) and null != $result['face_feature']) {
$res = 1;
}
$buf = pack("CC",$pnum,$res);
//var_dump($pnum,'Пользователь '.$id.', ответ из базы = '.$res);
echo base64_encode($buf);
}
function getObjectInfo($num, $id)
{
$length_empty = 7;
$tmc = \app\models\entity\Tmc::findOne(['id' => $id]);
//title
if (!$tmc) {
$buf = pack("Cvl", $num, $length_empty, $id);
}
else {
$buf = pack("lll", $id, $tmc->inventory_num, $tmc->storage);
$len = sizeof($tmc->desc);
$buf .= pack("v", $len);
$buf .= $tmc->desc;
$buf = ConstructVariablePacket($num, $buf);
}
echo base64_encode($buf);
}
function getCameraInfo($num, $userId)
{
$tmc = \app\models\entity\Tmc::findOne(['employee' => $userId]);
$length_empty = 3;
$length_full = 13;
if (!$tmc) {
$buf = pack("Cv", $num, $length_empty);
}
else {
$buf = pack("Cv", $num, $length_full);
//pack ip into 4 bytes array
foreach (explode('.', $tmc->ip) as $item) {
$buf .= pack('C', $item);
}
//pack mac into 4 bytes array
foreach (explode(':', $tmc->mac) as $item) {
$buf .= pack('C', hexdec($item));
}
}
echo base64_encode($buf);
}
function packWithSpaces(array $data)
{
foreach ($data as $key => $item) {
$data[$key] = pack("A*", $item);
}
$space = pack("A1", ' ');
return implode($space, $data);
}