Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

HandleRequest.class.php 48KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  1. <?php
  2. class HandleRequest {
  3. private $db;
  4. private $user;
  5. private $config;
  6. public $requestStatusLabels;
  7. public $activityCodes;
  8. public $statusNumbers;
  9. public const REQUEST_STATUS_PENDING = 'pending';
  10. public const REQUEST_STATUS_DRAFT = 'draft';
  11. public const REQUEST_STATUS_OPENED = 'opened';
  12. public const REQUEST_STATUS_PART_REPORTED = '! referted'; //Partially reported
  13. public const REQUEST_STATUS_REPORTED = 'referted';
  14. public const REQUEST_STATUS_REOPENED = 'reopened';
  15. function __construct() {
  16. global $db, $user, $config;
  17. $this->db = $db;
  18. $this->user = $user;
  19. $this->config = $config;
  20. //Set the codes and labels array
  21. $this->requestStatusLabels = [self::REQUEST_STATUS_PENDING=>_('Sending'), self::REQUEST_STATUS_DRAFT=>_('Draft'), self::REQUEST_STATUS_OPENED=>_('Opened'), self::REQUEST_STATUS_PART_REPORTED=>_('Partially answered'), self::REQUEST_STATUS_REPORTED=>_('Answered'), self::REQUEST_STATUS_REOPENED=>_('Reopened')];
  22. $this->statusNumbers = ['pending'=>-1, 'draft'=>5, 'opened'=>1, '! referted'=>2, 'reopened'=>3, 'referted'=>4];
  23. $this->activityCodes = [
  24. 'USR_LOGGED_IN' => _('User %s logged in (regular login).'),
  25. 'USR_AUTO_LOGGED_IN' => _('User %s logged in (auto-login).'),
  26. 'USR_LOGIN_FAILED' => _('User %s login failed (regular login).'),
  27. 'USR_AUTO_LOGIN_FAILED' => _('User %s login failed (auto-login).'),
  28. 'REQ_LISTED' => _('Requests listed by the user %s.'),
  29. 'REQ_NEW' => _('Opened new Request for writing by the user %s.'),
  30. 'REQ_EDITED' => _('Opened draft Request #%s for editing by the user %s.'),
  31. 'REQ_VIEW' => _('Opened Request #%s for reading by the user %s.'),
  32. 'REQ_SAVED_DRAFT' => _('Saved Request #%s as draft by the user %s.'),
  33. 'REQ_SENT' => _('Sent new Request #%s by the user %s.'),
  34. 'REQ_FILE_ADDED' => _('File %s attached to the Request #%s by the user %s.'),
  35. 'REQ_DELETED' => _('Request #%s deleted by the user %s.'),
  36. 'REQ_FWD' => _('Added new specialties to the Request #%s by the user %s.'),
  37. 'REQ_MSG' => _('New message added to the Request #%s by the user %s.'),
  38. 'REQ_STATUS_CNG_MODERATOR' => _('Status of the Request #%s changed to %s by the Moderator.')
  39. ];
  40. }
  41. public function isUserTheAuthor($requestID=0, $userID=0) {
  42. $result = $this->db
  43. ->where('r.id', $requestID)
  44. ->where('r.user_id', $userID)
  45. ->get('requests r');
  46. return is_array($result) && !empty($result) ? true : false;
  47. }
  48. public function isUserModerator($requestCenterID=0, $clinicalCenters=[], $userID=0) {
  49. return isset($clinicalCenters[$requestCenterID]) ? true : false;
  50. }
  51. public function isUserReferrer($requestID=0, $userID=0) {
  52. $result = $this->db
  53. ->where('rr.request_id', $requestID)
  54. ->where('rr.user_id', $userID)
  55. ->get('requests_recipients rr');
  56. return is_array($result) && !empty($result) ? true : false;
  57. }
  58. //Check whether the provided user is a referral in the provided request
  59. public function isReferralInRequest($requestID=0, $userID=0) {
  60. $recipients = $this->db
  61. ->where('rr.request_id', $requestID)
  62. ->where('rr.user_id', $userID)
  63. ->get('requests_recipients rr');
  64. return count($recipients) > 0 ? true : false;
  65. }
  66. public function isApplicantInRequest($requestID=0, $userID=0) {
  67. $request = $this->db
  68. ->where('id', $requestID)
  69. ->getOne('requests r', 'r.user_id');
  70. return isset($request['user_id']) && (int)$request['user_id'] == (int)$userID ? true : false;
  71. }
  72. public function getSpecialtyByClinicalCenterId($ccId=0, $groupId=0) {
  73. $specialties = [];
  74. /*if ($ccId > 0) {
  75. $results = $this->db
  76. ->where('ccmst.center_id', $ccId)
  77. ->join('users_medical_specialties ums', 'ums.id=ccmst.specialty_id', 'INNER')
  78. ->orderBy('ums.description', 'asc')
  79. ->get('clinical_center_medical_specialties_to ccmst', null, ['ums.id', 'ums.description']);
  80. } else {
  81. $results = $this->db
  82. ->orderBy('ums.description', 'asc')
  83. ->get('users_medical_specialties ums', null, ['ums.id', 'ums.description']);
  84. }*/
  85. //All Medical Specialties
  86. if ($ccId > 0) {
  87. $results = $this->db
  88. ->where('ccmst.center_id', $ccId)
  89. ->where('urt.role_id', REFERRER_ROLE_ID)
  90. ->where('u.group_id', $groupId)
  91. ->where('u.status', 1)
  92. ->join('users_medical_specialties ums', 'ums.id=ccmst.specialty_id', 'INNER')
  93. ->join('users_medical_specialties_to umst', 'umst.specialty_id=ums.id', 'INNER')
  94. ->join('users u', 'u.id=umst.user_id', 'INNER')
  95. ->join('users_roles_to urt', 'urt.user_id=u.id', 'INNER')
  96. ->groupBy('ums.id')
  97. ->orderBy('ums.description', 'asc')
  98. ->get('clinical_center_medical_specialties_to ccmst', null, ['ums.id', 'ums.description']);
  99. } else {
  100. $results = $this->db
  101. ->where('urt.role_id', REFERRER_ROLE_ID)
  102. ->where('u.group_id', $groupId)
  103. ->where('u.status', 1)
  104. ->join('users_medical_specialties_to umst', 'umst.specialty_id=ums.id', 'INNER')
  105. ->join('users u', 'u.id=umst.user_id', 'INNER')
  106. ->join('users_roles_to urt', 'urt.user_id=u.id', 'INNER')
  107. ->groupBy('ums.id')
  108. ->orderBy('ums.description', 'asc')
  109. ->get('users_medical_specialties ums', null, ['ums.id', 'ums.description']);
  110. }
  111. if (is_array($results)) {
  112. foreach($results as $item) {
  113. $specialties[$item['id']]['id'] = $item['id'];
  114. $specialties[$item['id']]['description'] = _($item['description']);
  115. }
  116. }
  117. return $specialties;
  118. }
  119. public function getRecipientsByRequestId($requestId=0) {
  120. $recipients = $this->db
  121. ->where('rr.request_id', $requestId)
  122. ->join('users u', 'u.id=rr.user_id', 'INNER')
  123. ->orderBy('u.surname', 'ASC')
  124. ->get('requests_recipients rr', null, ['u.name', 'u.surname', "(SELECT GROUP_CONCAT(ms.description SEPARATOR '|') FROM users_medical_specialties_to umst JOIN users_medical_specialties ms ON ms.id=umst.specialty_id WHERE umst.user_id=u.id ORDER BY ms.description) AS ms_list"]);
  125. if(is_array($recipients)) {
  126. foreach($recipients as $index => $recipient) {
  127. $ms = $recipient['ms_list'];
  128. if (strpos($ms, '|') !== false) {
  129. $temp = explode('|', $ms);
  130. $tempArr = [];
  131. foreach($temp as $item) {
  132. $tempArr[] = _($item);
  133. }
  134. $recipients[$index]['ms_list'] = implode(', ', $tempArr);
  135. } else {
  136. $recipients[$index]['ms_list'] = _($ms);
  137. }
  138. }
  139. }
  140. return $recipients;
  141. }
  142. public function getRecipients($params=[]) {
  143. $referralMs = isset($params['ms']) ? $params['ms'] : []; //Medical Specialty
  144. $referralCc = isset($params['cc']) ? $params['cc'] : []; //Clinical Center
  145. $referralLangs = isset($params['langs']) ? $params['langs'] : [];
  146. $recipientList = isset($params['recipientList']) ? $params['recipientList'] : [];
  147. $groupId = isset($params['groupId']) ? $params['groupId'] : 0;
  148. $arrayLangs = [];
  149. foreach($referralLangs as $lang) {
  150. $arrayLangs[] = $lang;
  151. }
  152. if (is_array($recipientList) && !empty($recipientList)) {
  153. return $this->db
  154. ->where('ucct.role_id', REFERRER_ROLE_ID)
  155. ->where('u.id IN('.implode(',', $recipientList).')')
  156. ->where('u.group_id', $groupId)
  157. ->where('u.status', 1)
  158. ->join('users u', 'u.id=ucct.user_id', 'INNER')
  159. ->orderBy('u.surname', 'asc')
  160. ->get('users_clinical_centers_to ucct', null, [
  161. 'u.id user_id',
  162. 'u.surname',
  163. 'u.name',
  164. 'ucct.user_id',
  165. "(SELECT GROUP_CONCAT(ms.description SEPARATOR ', ') FROM users_medical_specialties_to umst JOIN users_medical_specialties ms ON ms.id=umst.specialty_id WHERE umst.user_id=u.id ORDER BY ms.description) AS ms_list",
  166. "(SELECT GROUP_CONCAT(cc.description SEPARATOR ', ') FROM users_clinical_centers_to ucct JOIN clinical_centers cc ON cc.id=ucct.center_id WHERE ucct.user_id=u.id AND ucct.role_id=".REFERRER_ROLE_ID." ORDER BY cc.description) AS cc_list"
  167. ]);
  168. } else {
  169. if (!empty($referralCc)) {
  170. $this->db->where("ucct.center_id IN(".implode(',', $referralCc).")");
  171. }
  172. if (!empty($referralMs) && !empty($referralLangs)) {
  173. $results = $this->db
  174. ->where('ucct.role_id', REFERRER_ROLE_ID)
  175. //->where("u.language_default IN($langList)")
  176. ->where('u.status', 1)
  177. ->where('u.group_id', $groupId)
  178. ->join('users u', 'u.id=ucct.user_id', 'INNER')
  179. ->having('ms_total', 0, '>')
  180. ->orderBy('u.surname', 'asc')
  181. ->get('users_clinical_centers_to ucct', null, [
  182. 'u.id user_id',
  183. 'u.surname',
  184. 'u.name',
  185. 'u.language_default',
  186. 'ucct.user_id',
  187. "(SELECT COUNT(*) FROM users_medical_specialties_to umst WHERE umst.specialty_id IN(".implode(',', $referralMs).") AND umst.user_id=ucct.user_id) ms_total",
  188. "(SELECT GROUP_CONCAT(ms.description SEPARATOR ', ') FROM users_medical_specialties_to umst JOIN users_medical_specialties ms ON ms.id=umst.specialty_id WHERE umst.user_id=u.id ORDER BY ms.description) AS ms_list",
  189. "(SELECT GROUP_CONCAT(cc.description SEPARATOR ', ') FROM users_clinical_centers_to ucct JOIN clinical_centers cc ON cc.id=ucct.center_id WHERE ucct.user_id=u.id AND ucct.role_id=".REFERRER_ROLE_ID." ORDER BY cc.description) AS cc_list",
  190. "(SELECT GROUP_CONCAT(ult.language_id) FROM users_languages_to ult WHERE ult.user_id=u.id) AS user_alt_langs"
  191. ]);
  192. //Check the languages
  193. $recipients = [];
  194. if (is_array($results)) {
  195. /*foreach($results as $result) {
  196. $checkLangsList = !empty($result['user_alt_langs']) ? $result['user_alt_langs'].','.$result['language_default'] : $result['language_default'];
  197. $checkLangs = explode(',', $checkLangsList);
  198. foreach($arrayLangs as $lng) {
  199. if (in_array($lng, $checkLangs)) {
  200. $recipients[] = $result;
  201. }
  202. }
  203. }
  204. return $recipients;
  205. */
  206. return $results;
  207. }
  208. }
  209. }
  210. return false;
  211. }
  212. //public function forwardRequest($requestID=0, $formSpecialtyList=[], $groupId=0, $senderId=0, $centerId=0) {
  213. public function forwardRequest($requestID=0, $newSpecialties=[], $groupId=0, $senderId=0, $centerId=0) {
  214. //if (empty($formSpecialtyList)) return false;
  215. if (!is_array($newSpecialties)) return false;
  216. if (count($newSpecialties) < 1) return false;
  217. $isForward = false;
  218. /*$requestSpecialties = $this->db
  219. ->where('rmst.request_id', $requestID)
  220. ->getOne('requests_medical_specialties_to rmst', "GROUP_CONCAT(rmst.specialty_id) specialty_comma_list");
  221. $specialtyList = explode(',', $requestSpecialties['specialty_comma_list']);
  222. //Moderator or Referral has added a specialty
  223. $newSpecialties = [];
  224. $referrals = [];
  225. if(count($formSpecialtyList) > count($specialtyList)) {
  226. foreach($formSpecialtyList as $formSpecialty) {
  227. if (!in_array($formSpecialty, $specialtyList)) {
  228. $newSpecialties[$formSpecialty] = $formSpecialty;
  229. }
  230. }
  231. */
  232. //if (!empty($newSpecialties)) {
  233. $referrals = $this->db
  234. ->where("umst.specialty_id IN(".implode(',', $newSpecialties).")")
  235. ->where('u.group_id', $groupId)
  236. ->where('u.status', 1)
  237. ->having('centers', 0, '>')
  238. ->join('users u', 'u.id=umst.user_id', 'INNER')
  239. ->get('users_medical_specialties_to umst', null, ['umst.user_id', "(SELECT COUNT(*) FROM users_clinical_centers_to ucct WHERE ucct.user_id=u.id AND ucct.role_id=".REFERRER_ROLE_ID." AND ucct.center_id=$centerId) centers"]);
  240. //Add these user to the recipient list
  241. if (is_array($referrals) && !empty($referrals)) {
  242. $isForward = true;
  243. //Add the new specialty
  244. foreach($newSpecialties as $newSpecialty) {
  245. $this->db->insert('requests_medical_specialties_to', ['request_id'=>$requestID, 'specialty_id'=>$newSpecialty]);
  246. }
  247. foreach($referrals as $referral) {
  248. $this->db->insert('requests_recipients', ['request_id'=>$requestID, 'user_id'=>$referral['user_id']]);
  249. $this->queueMessage($requestID, $referral['user_id'], $senderId, 'NEW_FWD_REQUEST');
  250. }
  251. $this->setActivityLog($this->user->getUserId(), 'REQ_FWD', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestID]);
  252. }
  253. //}
  254. //}
  255. return $isForward;
  256. //return $this->db->getLastQuery();
  257. }
  258. public function setRequestProgress($requestID=0, $userID=0) {
  259. $request = $this->db->where('id', $requestID)->getOne('requests');
  260. }
  261. public function incrementReferralCounter($requestID=0, $userID=0) {
  262. if ($this->isReferralInRequest($requestID, $userID)) {
  263. $specialtyList = [];
  264. $specialties = $this->db
  265. ->where('umst.user_id', $userID)
  266. ->get('users_medical_specialties_to umst', null, ['umst.specialty_id']);
  267. if (is_array($specialties) && !empty($specialties)) {
  268. foreach($specialties as $specialty) {
  269. $specialtyList[] = $specialty['specialty_id'];
  270. }
  271. //Sort the array to always get the same comma separated list
  272. sort($specialtyList);
  273. }
  274. return $this->db->insert('request_reports_counter', ['request_id'=>$requestID, 'referral_id'=>$userID, 'referral_specialties'=>implode(',', $specialtyList)]);
  275. }
  276. return false;
  277. }
  278. public function cleanReferralCounter($requestID=0) {
  279. return $this->db->where('request_id', $requestID)->delete('request_reports_counter');
  280. }
  281. public function isRequestFullyReported($requestID=0) {
  282. //Request spcialties
  283. $specialties = $this->db
  284. ->where('rmst.request_id', $requestID)
  285. ->get('requests_medical_specialties_to rmst', null, ['rmst.specialty_id']);
  286. $specialtyList = [];
  287. if (is_array($specialties) && !empty($specialties)) {
  288. //Flat the specialties in a one dimensional array
  289. foreach($specialties as $specialty) {
  290. $specialtyList[] = $specialty['specialty_id'];
  291. }
  292. $specialtyList = array_unique($specialtyList);
  293. sort($specialtyList);
  294. //Get all answers
  295. $comments = $this->db
  296. ->where('rc.request_id', $requestID)
  297. ->get('requests_comments rc');
  298. //Array of specialties for each responders
  299. $msPerResponders = [];
  300. //Get all medical specialties for each responders
  301. if (is_array($comments) && !empty($comments)) {
  302. foreach($comments as $comment) {
  303. $ms = $this->db
  304. ->where('umst.user_id', $comment['user_id'])
  305. ->get('users_medical_specialties_to umst');
  306. if (is_array($ms)) {
  307. //Flat the medical specialties in a one dimensional array with no duplicates
  308. foreach($ms as $item) {
  309. if (in_array($item['specialty_id'], $specialtyList)) {
  310. $msPerResponders[$item['specialty_id']] = $item['specialty_id'];
  311. }
  312. }
  313. $msPerResponders = array_unique($msPerResponders);
  314. sort($msPerResponders);
  315. }
  316. }
  317. $diff = array_diff($specialtyList, $msPerResponders);
  318. return empty($diff) ? true : -2;
  319. }
  320. return 0;
  321. } else {
  322. return -1;
  323. }
  324. }
  325. public function setLog($logName='', $output=null) {
  326. file_put_contents(BASE_ROOT.'log/'.$logName.'.log', $output."\n", FILE_APPEND);
  327. }
  328. public function setActivityLog($userId=0, $activityCode='', $params=[]) {
  329. return;
  330. $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
  331. $requestId = $params['requestId'] ?? 0;
  332. $this->db->insert('log_activities', ['user_id'=>$userId, 'request_id'=>$requestId, 'user_agent'=>$userAgent, 'activity_code'=>$activityCode, 'activity_params'=>json_encode($params), 'created_at'=>date('Y-m-d H:i:s')]);
  333. }
  334. public function setRequestStatus($requestID=0, $statusCode='', $userId=0) {
  335. $statusNumber = isset($this->statusNumbers[$statusCode]) ? $this->statusNumbers[$statusCode] : -1;
  336. if ($this->db->where('id', $requestID)->update('requests', ['request_status'=>$statusCode, 'request_status_number'=>$statusNumber])) {
  337. return $this->setStatusHistory($requestID, $statusCode, $userId);
  338. }
  339. return false;
  340. }
  341. public function filterActivityLog($activityCode='', $params=[]) {
  342. $userData = isset($params['userId']) ? $this->user->getUserDB($params['userId']) : null;
  343. $userString = !empty($userData) && is_array($userData) ? $userData['surname'].' '.$userData['name'] : 'n/d';
  344. $requestId = $params['requestId'] ?? 'n/d';
  345. $fileTitle = $params['fileTitle'] ?? 'n/d';
  346. $newStatus = $params['newStatus'] ?? 'n/d';
  347. switch($activityCode) {
  348. case 'USR_LOGGED_IN':
  349. case 'USR_AUTO_LOGGED_IN':
  350. case 'USR_LOGIN_FAILED':
  351. case 'USR_AUTO_LOGIN_FAILED':
  352. case 'REQ_LISTED':
  353. case 'REQ_NEW':
  354. return vsprintf($this->activityCodes[$activityCode], [$userString]);
  355. break;
  356. case 'REQ_EDITED':
  357. case 'REQ_VIEW':
  358. case 'REQ_SAVED_DRAFT':
  359. case 'REQ_SENT':
  360. case 'REQ_DELETED':
  361. case 'REQ_FWD':
  362. case 'REQ_MSG':
  363. return vsprintf($this->activityCodes[$activityCode], [$requestId, $userString]);
  364. break;
  365. case 'REQ_FILE_ADDED':
  366. return vsprintf($this->activityCodes[$activityCode], [$fileTitle, $requestId, $userString]);
  367. break;
  368. case 'REQ_STATUS_CNG_MODERATOR':
  369. return vsprintf($this->activityCodes[$activityCode], [$requestId, $newStatus]);
  370. break;
  371. }
  372. }
  373. public function getActivityLogList($params=[]) {
  374. return;
  375. $userId = (int)$params['userId'] ?? 0;
  376. $requestId = (int)$params['requestId'] ?? 0;
  377. $dateFrom = $params['dateFrom'] ?? null;
  378. $dateTo = $params['dateTo'] ?? null;
  379. $logList = [];
  380. if ($userId > 0) {
  381. $this->db->where('user_id', $userId);
  382. }
  383. if ($requestId > 0) {
  384. $this->db->where('request_id', $requestId);
  385. }
  386. if (!is_null($dateFrom)) {
  387. $this->db->where("created_at >= '$dateFrom'");
  388. }
  389. if (!is_null($dateTo)) {
  390. $this->db->where("created_at <= '$dateTo'");
  391. }
  392. $results = $this->db->get('log_activities');
  393. if (is_array($results) && !empty($results)) {
  394. foreach($results as $result) {
  395. $logRow = $this->filterActivityLog($result['activity_code'], json_decode($result['activity_params'], true));
  396. if ($logRow != '')
  397. $logList[] = $result['created_at'].' > '.$logRow;
  398. }
  399. }
  400. return $logList;
  401. }
  402. public function setStatusHistory($requestID=0, $statusCode='', $userId=0) {
  403. $this->updateDate($requestID);
  404. return $this->db->insert('requests_statuses_history', ['request_id'=>$requestID, 'user_id'=>$userId, 'status_code'=>$statusCode, 'created_at'=>date('Y-m-d H:i:s')]);
  405. }
  406. public function getCommentList($requestID=0, $ccID=0, $checkCC=true) {
  407. $groupedComments = [];
  408. $positions = [];
  409. //$userIsAuthor = $this->isUserTheAuthor($requestID, $this->user->getUserId());
  410. $comments = $this->db
  411. ->where('rc.request_id', $requestID)
  412. ->where('rc.is_visible', 1)
  413. ->join('users u', 'u.id=rc.user_id', 'INNER')
  414. ->orderBy('rc.created_at', 'asc')
  415. ->get('requests_comments rc', null, ['rc.*', 'u.name user_name', 'u.surname user_surname', 'u.remarks_public', 'u.updated_at user_updated_at',
  416. "(SELECT GROUP_CONCAT(ums.description SEPARATOR '|') FROM users_medical_specialties_to umst INNER JOIN users_medical_specialties ums ON ums.id=umst.specialty_id WHERE umst.user_id=rc.user_id ORDER BY ums.description ASC) medspec_list",
  417. "(SELECT GROUP_CONCAT(cc.description SEPARATOR ', ') FROM users_clinical_centers_to ucct JOIN clinical_centers cc ON cc.id=ucct.center_id WHERE ucct.role_id=".REFERRER_ROLE_ID." AND ucct.user_id=rc.user_id ORDER BY cc.description ASC) cc_list",
  418. "(SELECT GROUP_CONCAT(ucct.center_id SEPARATOR '|') FROM users_clinical_centers_to ucct WHERE ucct.role_id=".MODERATOR_ROLE_ID." AND ucct.user_id=rc.user_id) cc_list_moderator", "(SELECT GROUP_CONCAT(sub_urt.role_id SEPARATOR '|') FROM users_roles_to sub_urt WHERE sub_urt.user_id=rc.user_id) user_roles"]
  419. );
  420. if (is_array($comments)) {
  421. $prvUserId = 0;
  422. $prvPosition = 'left';
  423. foreach($comments as $index => $comment) {
  424. $comments[$index]['show_meta'] = false;
  425. $comments[$index]['show_specialties'] = false; //Default value
  426. $comments[$index]['is_responder'] = false;
  427. $comments[$index]['is_the_author'] = false;
  428. //Translate a stringify the Medical Specialties list
  429. $medSpecialties = strpos($comments[$index]['medspec_list'], '|') !== false ? explode('|', $comments[$index]['medspec_list']) : [$comments[$index]['medspec_list']];
  430. if (is_array($medSpecialties) && !empty($medSpecialties)) {
  431. foreach($medSpecialties as $i => $ms) {
  432. $medSpecialties[$i] = _($ms);
  433. }
  434. $comments[$index]['medspec_list'] = implode(', ', $medSpecialties);
  435. } else {
  436. $comments[$index]['medspec_list'] = !is_null($medSpecialties) ? _($medSpecialties) : '';
  437. }
  438. //Set the (chat) balloon position
  439. if ($prvUserId > 0 && $prvUserId !== $comment['user_id']) {
  440. if ($prvPosition == 'left') {
  441. $comments[$index]['position'] = 'right';
  442. $prvPosition = 'right';
  443. } else {
  444. $comments[$index]['position'] = 'left';
  445. $prvPosition = 'left';
  446. }
  447. $comments[$index]['show_meta'] = true;
  448. } else {
  449. $comments[$index]['position'] = $prvPosition; //Default
  450. if ($prvUserId == 0) $comments[$index]['show_meta'] = true; //Default
  451. }
  452. $prvUserId = $comment['user_id'];
  453. //Check whether this user is a moderator in the current clinical center or just check whether the user is a moderator or isn't
  454. if ($checkCC) {
  455. //Clinical centers in whitch the user is a moderator
  456. $ccModerator = explode('|', $comment['cc_list_moderator']);
  457. //Compare the current Clinical Center ID against the previouses ($ccModerator)
  458. if (in_array($ccID, $ccModerator)) {
  459. $comments[$index]['is_moderator'] = true;
  460. } else {
  461. $comments[$index]['is_moderator'] = false;
  462. }
  463. } else {
  464. $comments[$index]['is_moderator'] = false;
  465. }
  466. //Is Referral (show the Medical Specialties)
  467. if (in_array(REFERRER_ROLE_ID, explode('|', $comment['user_roles']))) {
  468. $comments[$index]['show_specialties'] = true;
  469. $comments[$index]['is_responder'] = true;
  470. }
  471. //If Moderator, overwrite the possible previouse value
  472. if ($comments[$index]['is_moderator']) {
  473. $comments[$index]['show_specialties'] = false;
  474. }
  475. $userIsAuthor = $this->isUserTheAuthor($requestID, $comments[$index]['user_id']);
  476. //If Author, overwrite the possible previouse values
  477. if ($userIsAuthor) {
  478. $comments[$index]['show_specialties'] = false;
  479. $comments[$index]['is_moderator'] = false; //Overwrite the previouse value
  480. $comments[$index]['is_the_author'] = $userIsAuthor;
  481. }
  482. $comments[$index]['request_cc'] = $ccID;
  483. $comments[$index]['attachments'] = $this->getAttachmentsByRequestId($requestID, $comment['id']);
  484. $tUserId = $comment['user_id'];
  485. }
  486. }
  487. return $comments;
  488. }
  489. public function getAttachmentsByRequestId($requestID=0, $commentID=0) {
  490. $this->db->where('ra.request_id', $requestID);
  491. if ($commentID > 0) {
  492. $this->db->where('ra.comment_id', $commentID);
  493. }
  494. $attachments = $this->db->join('users u', 'u.id=ra.user_id', 'left')
  495. ->orderBy('ra.created_at', 'desc')
  496. ->get('requests_attachments ra', null, ['ra.*', 'u.name', 'u.surname']);
  497. return $attachments;
  498. }
  499. public function updateDate($requestID=0) {
  500. return $this->db->where('id', $requestID)->update('requests', ['updated_at'=>date('Y-m-d H:i:s')]);
  501. }
  502. public function deleteRequest($requestId=0) {
  503. $request = $this->db->where('id', $requestId)->delete('requests');
  504. $attachments = $this->db->where('request_id', $requestId)->delete('requests_attachments');
  505. $comments = $this->db->where('request_id', $requestId)->delete('requests_comments');
  506. $languages = $this->db->where('request_id', $requestId)->delete('requests_languages_to');
  507. $specialties = $this->db->where('request_id', $requestId)->delete('requests_medical_specialties_to');
  508. $notifications = $this->db->where('request_id', $requestId)->where('sent_status', 0)->delete('requests_messages_queue');
  509. $recipients = $this->db->where('request_id', $requestId)->delete('requests_recipients');
  510. $registry = $this->db->where('request_id', $requestId)->delete('requests_registry');
  511. $statusHistory = $this->db->where('request_id', $requestId)->delete('requests_statuses_history');
  512. $symptoms = $this->db->where('request_id', $requestId)->delete('requests_symptoms_to');
  513. $wizards = $this->db->where('request_id', $requestId)->delete('requests_wizards_to');
  514. $wizardDermaPositions = $this->db->where('request_id', $requestId)->delete('requests_wizard_derma_position_to');
  515. $reportCounter = $this->db->where('request_id', $requestId)->delete('request_reports_counter');
  516. $centers = $this->db->where('request_id', $requestId)->delete('request_clinical_centers_to');
  517. //TODO: delete attachment files
  518. return $request;
  519. }
  520. public function updateUserToken($userId=0, $uniqueId=null) {
  521. $expireDays = $this->config['settings']['autologin-expire-days'];
  522. $expireDate = date('Y-m-d 00:00:00', strtotime("+$expireDays days", time()));
  523. $returnUniqueId = null;
  524. $check = $this->db->where('id', $userId)->getOne('users', 'autologin_token, autologin_expires_at');
  525. $this->db->where('id', $userId);
  526. if (!empty($check['autologin_expires_at'])) {
  527. $this->db->where("DATEDIFF(NOW(), autologin_expires_at) > $expireDays");
  528. }
  529. $this->db->update('users', ['autologin_token'=>$uniqueId, 'autologin_expires_at'=>$expireDate]);
  530. if ($this->db->count > 0) {
  531. $returnUniqueId = $uniqueId;
  532. } else {
  533. $returnUniqueId = $check['autologin_token'];
  534. }
  535. return $returnUniqueId;
  536. }
  537. public function getStatistics($field='triage_color', $roleId=0, $controller=null) {
  538. $returnData = [];
  539. $count = 0;
  540. $labels = [];
  541. $values = [];
  542. $perc = [];
  543. $colors = [];
  544. $borders = [];
  545. $colorList = ['white'=>'rgba(255, 255, 255, 1)', 'green'=>'rgba(36, 167, 83, 1)', 'yellow'=>'rgba(255, 192, 67, 1)', 'red'=>'rgba(221, 51, 72, 1)', '! referted'=>'rgba(255, 192, 67, 1)', 'referted'=>'rgba(36, 167, 83, 1)', 'pending'=>'rgba(227, 227, 227, 1)', 'opened'=>'rgba(108, 117, 124, 1)', 'reopened'=>'rgba(221, 51, 72, 1)', 'draft'=>'rgba(165, 165, 165, 1)'];
  546. $borderList = ['white'=>'rgba(0, 0, 0, 0.2)', 'green'=>'rgba(36, 167, 83, 1)', 'yellow'=>'rgba(255, 192, 67, 1)', 'red'=>'rgba(221, 51, 72, 1)'];
  547. switch ($roleId) {
  548. case ADMIN_ROLE_ID:
  549. $this->db->where('r.group_id', $controller->userGroupId);
  550. break;
  551. case MODERATOR_ROLE_ID:
  552. case REFERRER_ROLE_ID:
  553. case GUEST_ROLE_ID:
  554. $clinicalCenters = $controller->getUserClinicalCenters($this->user->getUserId(), $roleId); //In mainController
  555. $ccIds = array_keys($clinicalCenters);
  556. $this->db->where('r.center_id', $ccIds, 'IN');
  557. if ($field != 'triage_color') {
  558. $this->db->where('r.request_status', ['opened', 'reopened', '! referted', 'referted'], 'IN');
  559. }
  560. break;
  561. //Applicant
  562. default:
  563. $this->db->where('r.user_id', $this->user->getUserId());
  564. }
  565. $this->db->where('r.request_visibility', 'all');
  566. if ($field == 'triage_color') {
  567. $this->db->where('r.request_status', ['opened', 'reopened', '! referted'], 'IN');
  568. $this->db->groupBy('r.triage_color');
  569. $results = $this->db->get('requests r', null, ['COUNT(*) total', 'r.triage_color']);
  570. }
  571. if ($field == 'request_status') {
  572. $this->db->groupBy('r.request_status');
  573. $results = $this->db->get('requests r', null, ['COUNT(*) total', 'r.request_status']);
  574. }
  575. if (is_array($results)) {
  576. foreach($results as $index => $item) {
  577. $count = $count+$item['total'];
  578. $labels[$index] = _(ucfirst($item[$field])) ?? null;
  579. $labelsValues[$index] = _(ucfirst($item[$field])).' ('.$item['total'].')' ?? null;
  580. $values[$index] = $item['total'];
  581. $colors[$index] = $colorList[$item[$field]];
  582. $borders[$index] = $borderList[$item[$field]] ?? null;
  583. }
  584. foreach($results as $index => $item) {
  585. //$results[$index]['perc'] = round($item['total']*100/$count);
  586. $perc[$index] = number_format($item['total']*100/$count, 1);
  587. $labelsPerc[$index] = _(ucfirst($item[$field])).' ('.$perc[$index].'%)' ?? null;
  588. }
  589. }
  590. $returnData['labels'] = $labels;
  591. $returnData['labelsValues'] = $labelsValues;
  592. $returnData['labelsPerc'] = $labelsPerc;
  593. $returnData['colors'] = $colors;
  594. $returnData['borders'] = $borders;
  595. $returnData['values'] = $values;
  596. $returnData['perc'] = $perc;
  597. $returnData['query'] = $this->db->getLastQuery();
  598. return $returnData;
  599. }
  600. public function getDataForMessageQueue($requestID=0, $recipientID=0, $senderID=0, $msgCode='') {
  601. $currentLocale = setlocale(LC_ALL, 0);
  602. $supportedLocales = $this->config['settings']['supported-locales'];
  603. $request = $this->db
  604. ->where('r.id', $requestID)
  605. ->join('clinical_centers cc', 'cc.id=r.center_id', 'INNER')
  606. ->join('continents cnt', 'cnt.code=cc.continent_code', 'INNER')
  607. ->join('countries cntr', 'cntr.country_iso2_code=cc.country_code', 'INNER')
  608. ->getOne('requests r', "r.id request_id, r.triage_color, (SELECT GROUP_CONCAT(rlt.language_code) FROM requests_languages_to rlt WHERE rlt.request_id=r.id) request_lang_list, (SELECT GROUP_CONCAT(ums.description SEPARATOR ', ') FROM requests_medical_specialties_to rmst JOIN users_medical_specialties ums ON ums.id=rmst.specialty_id WHERE rmst.request_id=r.id) specialties, cc.description cc_name, cntr.country_name, cnt.name continent_name");
  609. $sender = $this->db
  610. ->where('u.id', $senderID)
  611. ->getOne('users u');
  612. $recipient = $this->db
  613. ->where('u.id', $recipientID)
  614. ->getOne('users u');
  615. $recipientLang = isset($recipient['language_default']) ? $recipient['language_default'] : 'en';
  616. $recipientLocale = isset($supportedLocales[$recipientLang]) ? $supportedLocales[$recipientLang] : 'en_US';
  617. setlocale(LC_ALL, $recipientLocale);
  618. $langList = $this->stringifyLangCodes($request['request_lang_list']);
  619. $specialtyList = $this->translateSpecialties($request['specialties']);
  620. $newUniqueId = uniqid();
  621. $uniqueId = $this->updateUserToken($recipient['id'], $newUniqueId);
  622. $siteLink = $this->config['settings']['http-protocol'].$this->config['settings']['site-domain'].'/#/auto-login/'.$uniqueId.'/'.$request['request_id'];
  623. $msgData = $this->getLocalisedMsgData($msgCode, $recipient['language_default']);
  624. $subject = $msgData['msg_object'];
  625. $body = $this->replaceMsgPlaceholders($msgData['msg_body'], $msgCode,
  626. [
  627. 'specialtyList' => $specialtyList,
  628. 'code' => _(ucfirst($request['triage_color'])),
  629. 'langList' => $langList,
  630. 'requestId' => $request['request_id'],
  631. 'center' => $request['cc_name'].' ('.$request['country_name'].', '.$request['continent_name'].')',
  632. 'siteLink' => $siteLink
  633. ]
  634. );
  635. $mailID = uniqid();
  636. $mailHTML = $this->getMessageTemplate('Email/template', ['mailID'=>$mailID, 'body'=>nl2br($body), 'showTemplate'=>true]);
  637. $queueEmailData = [
  638. 'senderId' => $senderID,
  639. 'recipientId' => $recipient['id'],
  640. 'requestId' => $requestID,
  641. 'mailId' => $mailID,
  642. 'subject' => $subject,
  643. 'content' => $mailHTML,
  644. 'type' => 'email',
  645. 'recipient' => $recipient['email'],
  646. 'senderStatus' => $sender['status']
  647. ];
  648. if ($recipient['language_default'] == 'it') {
  649. $sms_body = 'Controlla la richiesta #'.$request['request_id'].', clicca '.$siteLink;
  650. } else {
  651. $sms_body = 'Check request #'.$request['request_id'].', click '.$siteLink;
  652. }
  653. $queueSMSData = [
  654. 'senderId' => $senderID,
  655. 'recipientId' => $recipient['id'],
  656. 'requestId' => $requestID,
  657. 'mailId' => '',
  658. 'subject' => '',
  659. 'content' => $sms_body,
  660. 'type' => 'sms',
  661. 'recipient' => $recipient['mobile_number'],
  662. 'senderStatus' => $sender['status']
  663. ];
  664. setlocale(LC_ALL, $currentLocale);
  665. return ['email'=>$queueEmailData, 'sms'=>$queueSMSData];
  666. }
  667. public function notifyAllReferrals($requestID=0, $msgCode='', $sendSMS=true) {
  668. $request = $this->db
  669. ->where('r.id', $requestID)
  670. ->getOne('requests r', "r.id request_id, r.user_id applicant_id, (SELECT GROUP_CONCAT(rr.user_id) FROM requests_recipients rr WHERE rr.request_id=r.id) recipients_comma_list");
  671. $recipientIds = [];
  672. if (isset($request['recipients_comma_list'])) {
  673. $recipientIds = explode(',', $request['recipients_comma_list']);
  674. }
  675. $returns = [];
  676. if (is_array($recipientIds) && !empty($recipientIds)) {
  677. foreach($recipientIds as $recipientId) {
  678. $returns[] = $this->queueMessage($requestID, $recipientId, $request['applicant_id'], $msgCode, $sendSMS);
  679. }
  680. }
  681. return $returns;
  682. }
  683. public function queueMessage($requestID=0, $recipientID=0, $senderID=0, $msgCode='', $sendSMS=true) {
  684. $msgStructure = $this->getDataForMessageQueue($requestID, $recipientID, $senderID, $msgCode);
  685. $this->insertMsgInQueue($msgStructure['email']);
  686. if ($sendSMS)
  687. $this->insertMsgInQueue($msgStructure['sms']);
  688. return $msgStructure;
  689. }
  690. public function getMessageTemplate($path, $params=[]) {
  691. if (!empty($params)) extract($params);
  692. ob_start();
  693. include VIEWS_DIR.'Elements/Message/'.$path.'.part.php';
  694. $content = ob_get_clean();
  695. return $content;
  696. }
  697. public function getOpenedRequestsToNofify() {
  698. $groupedById = [];
  699. $recipients = $this->db
  700. ->where('r.request_status', self::REQUEST_STATUS_OPENED)
  701. ->where('r.opened_sent', 0)
  702. ->join('requests r', 'r.id=rr.request_id', 'INNER')
  703. ->join('users u', 'u.id=rr.user_id', 'INNER')
  704. ->join('clinical_centers cc', 'cc.id=r.center_id', 'INNER')
  705. ->join('continents cnt', 'cnt.code=cc.continent_code', 'INNER')
  706. ->join('countries cntr', 'cntr.country_iso2_code=cc.country_code', 'INNER')
  707. ->get('requests_recipients rr', null, [
  708. 'r.id request_id',
  709. 'r.user_id applicant_id',
  710. 'rr.user_id recipient_id',
  711. 'r.triage_color',
  712. 'u.id recipient_id',
  713. 'u.name',
  714. 'u.surname',
  715. 'u.language_default',
  716. 'u.email',
  717. 'u.mobile_number',
  718. 'u.mobile_number_chat',
  719. 'u.allow_phone_text',
  720. 'u.allow_phone_chat',
  721. 'u.allow_email_msgs',
  722. 'cc.description cc_name',
  723. 'cntr.country_name',
  724. 'cnt.name continent_name',
  725. "(SELECT applicant_tb.status FROM users applicant_tb WHERE applicant_tb.id=r.user_id) applicant_status",
  726. "(SELECT applicant_ltb.language_default FROM users applicant_ltb WHERE applicant_ltb.id=r.user_id) applicant_lang",
  727. "(SELECT applicant_emtb.email FROM users applicant_emtb WHERE applicant_emtb.id=r.user_id) applicant_email",
  728. "(SELECT applicant_phtb.mobile_number FROM users applicant_phtb WHERE applicant_phtb.id=r.user_id) applicant_phone",
  729. "(SELECT GROUP_CONCAT(ums.description SEPARATOR ', ') FROM requests_medical_specialties_to rmst JOIN users_medical_specialties ums ON ums.id=rmst.specialty_id WHERE rmst.request_id=rr.request_id) specialties",
  730. "(SELECT GROUP_CONCAT(rlt.language_code) FROM requests_languages_to rlt WHERE rlt.request_id=rr.request_id) request_lang_list"
  731. ]);
  732. //Group by request id
  733. if (is_array($recipients)) {
  734. foreach($recipients as $recipient) {
  735. $groupedById[$recipient['request_id']][] = $recipient;
  736. }
  737. }
  738. return $groupedById;
  739. }
  740. public function getLocalisedMsgData($msg_code='', $lang='', $msg_type='') {
  741. $searchLang = $lang != 'en' ? ['en', $lang] : ['en'];
  742. $this->db->where('rmt.msg_code', $msg_code);
  743. $this->db->where('rmt.lang_code', $searchLang, 'IN');
  744. if ($msg_type != '') {
  745. $this->db->where('rmt.msg_type', $msg_type);
  746. }
  747. $results = $this->db->get('requests_messages_text rmt');
  748. $msg = [];
  749. if (is_array($results)) {
  750. foreach($results as $result) {
  751. if ($result['lang_code'] == $lang) {
  752. $msg = $result;
  753. break;
  754. }
  755. }
  756. if (empty($msg)) {
  757. foreach($results as $result) {
  758. if ($result['lang_code'] == 'en') {
  759. $msg = $result;
  760. break;
  761. }
  762. }
  763. }
  764. }
  765. return $msg;
  766. }
  767. public function isRequestPreviouslyReopened($requestID=0) {
  768. $history = $this->db
  769. ->where('rsh.request_id', $requestID)
  770. ->where('rsh.status_code', 'reopened')
  771. ->getOne('requests_statuses_history rsh', "COUNT(*) AS counter");
  772. return isset($history['counter']) && (int)$history['counter'] > 0 ? true : false;
  773. }
  774. public function translateSpecialties($commaList='') {
  775. $list = explode(',', $commaList);
  776. $specialties = [];
  777. $stringSpecialties = '';
  778. if (is_array($list)) {
  779. foreach($list as $item) {
  780. $specialties[] = _($item);
  781. }
  782. $stringSpecialties = implode(', ', $specialties);
  783. }
  784. return $stringSpecialties;
  785. }
  786. public function setOpenedRequestNotified($requestID=0) {
  787. return $this->db->where('id', $requestID)->update('requests', ['opened_sent'=>1, 'opened_sent_at'=>date('Y-m-d H:i:s')]);
  788. }
  789. /*public function insertMsgInQueue($msgInfo=[]) {
  790. return $this->db->insert('requests_messages_queue', [
  791. 'sender_id' => $msgInfo['senderId'],
  792. 'recipient_id' => $msgInfo['recipientId'],
  793. 'request_id' => $msgInfo['requestId'],
  794. 'mail_id' => $msgInfo['mailId'],
  795. 'msg_subject' => $msgInfo['subject'],
  796. 'msg_content' => $msgInfo['content'],
  797. 'msg_type' => $msgInfo['type'],
  798. 'msg_recipient' => $msgInfo['recipient'],
  799. 'sender_status' => $msgInfo['senderStatus'],
  800. 'created_at' => date('Y-m-d H:i:s'),
  801. ]);
  802. }*/
  803. public function insertMsgInQueue($msgInfo=[]) {
  804. return $this->db->insert('requests_messages_queue', [
  805. 'sender_id' => $msgInfo['senderId'],
  806. 'recipient_id' => $msgInfo['recipientId'],
  807. 'request_id' => $msgInfo['requestId'],
  808. 'mail_id' => $msgInfo['mailId'],
  809. 'msg_subject' => $msgInfo['subject'],
  810. 'msg_content' => $msgInfo['content'],
  811. 'msg_type' => $msgInfo['type'],
  812. 'msg_recipient' => $msgInfo['recipient'],
  813. 'sender_status' => $msgInfo['senderStatus'],
  814. 'attachments' => isset($msgInfo['attachments']) ? $msgInfo['attachments'] : null,
  815. 'delay_at' => isset($msgInfo['delay']) ? $msgInfo['delay'] : null,
  816. 'created_at' => date('Y-m-d H:i:s'),
  817. ]);
  818. }
  819. public function replaceMsgPlaceholders($text='', $msgCode='', $data=[]) {
  820. switch($msgCode) {
  821. case 'APPLICANT_CONFIRM':
  822. return vsprintf($text, [$data['specialtyList'], $data['code'], $data['langList'], $data['siteLink']]);
  823. break;
  824. case 'NEW_FWD_REQUEST':
  825. return vsprintf($text, [$data['specialtyList'], $data['code'], $data['langList'], $data['requestId'], $data['center'], $data['siteLink']]);
  826. break;
  827. case 'PARTIALLY_REPORTED':
  828. return vsprintf($text, [$data['specialtyList'], $data['code'], $data['langList'], $data['requestId'], $data['siteLink']]);
  829. break;
  830. case 'REQUEST_UPDATE':
  831. return vsprintf($text, [$data['code'], $data['langList'], $data['requestId'], $data['center'], $data['siteLink']]);
  832. break;
  833. case 'REQUEST_UPDATE_APPLICANT':
  834. return vsprintf($text, [$data['code'], $data['langList'], $data['requestId'], $data['center'], $data['siteLink']]);
  835. break;
  836. case 'CLOSED_BY_MODERATOR':
  837. return vsprintf($text, [$data['specialtyList'], $data['code'], $data['langList'], $data['requestId'], $data['siteLink']]);
  838. break;
  839. default:
  840. return '';
  841. }
  842. }
  843. public function stringifyLangCodes($langCodeList='') {
  844. $codes = explode(',', $langCodeList);
  845. $langs = [];
  846. $langString = '';
  847. $labels = ['en'=>_('english'), 'it'=>_('italian'), 'fr'=>_('french'), 'es'=>_('spanish'), 'pt'=>_('portoguese')];
  848. if (is_array($codes)) {
  849. foreach($codes as $code) {
  850. $langs[] = ucfirst(_($labels[$code]));
  851. }
  852. $langString = implode(', ', $langs);
  853. }
  854. return $langString;
  855. }
  856. public function getICD10Categories($lang='en') {
  857. $categories = [];
  858. $resultLangs = $this->db->getOne('icd10_languages');
  859. $supportedLangs = explode('|', $resultLangs['supported_langs']);
  860. $lang = in_array($lang, $supportedLangs) ? $lang : 'en';
  861. $this->db->rawQuery("SET SESSION group_concat_max_len = 1000000");
  862. $results = $this->db
  863. ->where("c.parent_id = ''")
  864. ->where('cl.lang_code', $lang)
  865. ->join('icd10_categories_labels cl', 'cl.category_id=c.id', 'INNER')
  866. ->orderBy('c.position', 'asc')
  867. ->get('icd10_categories c', null, [
  868. 'c.id',
  869. 'cl.description',
  870. "(SELECT GROUP_CONCAT('\"', csub.id, '\"', ':', '\"', clsub.description, '\"' SEPARATOR ',') FROM icd10_categories csub JOIN icd10_categories_labels clsub ON clsub.category_id=csub.id WHERE clsub.lang_code = '$lang' AND csub.parent_id=c.id) subcategories"
  871. ]);
  872. if (is_array($results)) {
  873. foreach($results as $index => $item) {
  874. $categories[$index]['id'] = $item['id'];
  875. $categories[$index]['label'] = $item['description'];
  876. //$categories[$index]['subcategories-raw'] = $item['subcategories'];
  877. $categories[$index]['subcategories'] = json_decode('{'.$item['subcategories'].'}', true);
  878. }
  879. }
  880. return $categories;
  881. }
  882. public function getDeseasesByICD10Category($category='', $lang='en', $selectedDeseases=[]) {
  883. $deseases = [];
  884. $resultLangs = $this->db->getOne('icd10_languages');
  885. $supportedLangs = explode('|', $resultLangs['supported_langs']);
  886. $lang = in_array($lang, $supportedLangs) ? $lang : 'en';
  887. $this->db->rawQuery("SET SESSION group_concat_max_len = 1000000");
  888. $results = $this->db
  889. ->where('category_id', $category)
  890. ->where('parent_id', '')
  891. ->where('idl.lang_code', $lang)
  892. ->join('icd10_desease_labels idl', 'idl.desease_id=d.id', 'INNER')
  893. ->get('icd10_deseases d', null, [
  894. 'd.id',
  895. 'd.category_id',
  896. 'd.description',
  897. "(SELECT GROUP_CONCAT('\"', dsub.id, '\"', ':', '\"', iclsub.description, '\"' SEPARATOR ',') FROM icd10_deseases dsub JOIN icd10_desease_labels iclsub ON iclsub.desease_id=dsub.id WHERE iclsub.lang_code = '$lang' AND dsub.parent_id=d.id) subdeseases"
  898. ]);
  899. if (is_array($results)) {
  900. foreach($results as $index => $item) {
  901. $deseases[$index]['id'] = $item['id'];
  902. $deseases[$index]['label'] = $item['description'];
  903. $deseases[$index]['disabled'] = in_array($item['id'], $selectedDeseases) ? 'disabled' : '';
  904. $subdeseases = json_decode('{'.$item['subdeseases'].'}', true);
  905. if (is_array($subdeseases)) {
  906. foreach($subdeseases as $subId => $subLabel) {
  907. unset($subdeseases[$subId]);
  908. $subdeseases[$subId]['label'] = $subLabel;
  909. if (in_array($subId, $selectedDeseases)) {
  910. $subdeseases[$subId]['disabled'] = 'disabled';
  911. } else {
  912. $subdeseases[$subId]['disabled'] = '';
  913. }
  914. }
  915. $deseases[$index]['subdeseases'] = $subdeseases;
  916. } else {
  917. $deseases[$index]['subdeseases'] = [];
  918. }
  919. }
  920. }
  921. return $deseases;
  922. }
  923. public function getECD10ListByRequestId($requestId=0, $lang_code='en') {
  924. $resultLangs = $this->db->getOne('icd10_languages');
  925. $supportedLangs = explode('|', $resultLangs['supported_langs']);
  926. $lang_code = in_array($lang_code, $supportedLangs) ? $lang_code : 'en';
  927. $icd10 = $this->db
  928. ->where('rst.request_id', $requestId)
  929. ->where('idl.lang_code', $lang_code)
  930. ->join('icd10_deseases icdd', 'icdd.id=rst.symptom_id', 'INNER')
  931. ->join('icd10_desease_labels idl', 'idl.desease_id=rst.symptom_id', 'INNER')
  932. ->get('requests_symptoms_to rst', null, [
  933. 'icdd.id',
  934. 'idl.description label',
  935. "(SELECT idlsub.description FROM icd10_desease_labels idlsub WHERE idlsub.desease_id = icdd.parent_id AND idlsub.lang_code = '$lang_code') parent_label"
  936. ]);
  937. return $icd10;
  938. }
  939. public function getDeseaseByKeyword($keyword='', $langCode='en', $selectedDeseases=[]) {
  940. $deseases = [];
  941. $results = $this->db
  942. ->where("idl.description LIKE '%$keyword%'")
  943. ->where('idl.lang_code', $langCode)
  944. ->where("d.parent_id <> ''")
  945. ->join('icd10_desease_labels idl', 'idl.desease_id=d.id', 'INNER')
  946. ->get('icd10_deseases d', 10, [
  947. 'idl.description',
  948. 'idl.desease_id',
  949. 'd.parent_id',
  950. "(SELECT idlsub.description FROM icd10_desease_labels idlsub WHERE idlsub.desease_id = d.parent_id AND idlsub.lang_code = '$langCode') parent_label"
  951. ]);
  952. if (is_array($results) && !empty($results)) {
  953. foreach($results as $index => $item) {
  954. $deseases[$item['parent_id']]['id'] = $item['parent_id'];
  955. $deseases[$item['parent_id']]['label'] = $item['parent_label'];
  956. $deseases[$item['parent_id']]['disabled'] = in_array($item['parent_id'], $selectedDeseases) ? 'disabled' : '';
  957. $deseases[$item['parent_id']]['subdeseases'][$item['desease_id']]['id'] = $item['desease_id'];
  958. $deseases[$item['parent_id']]['subdeseases'][$item['desease_id']]['label'] = $item['description'];
  959. $deseases[$item['parent_id']]['subdeseases'][$item['desease_id']]['disabled'] = in_array($item['desease_id'], $selectedDeseases) ? 'disabled' : '';;
  960. }
  961. }
  962. /*foreach($results as $index => $item) {
  963. $deseases[$index]['id'] = $item['parent_id'];
  964. $deseases[$index]['label'] = $item['parent_label'];
  965. $deseases[$index]['disabled'] = in_array($item['parent_id'], $selectedDeseases) ? 'disabled' : '';
  966. $deseases[$index]['subdeseases'][$item['desease_id']]['id'] = $item['desease_id'];
  967. $deseases[$index]['subdeseases'][$item['desease_id']]['label'] = $item['description'];
  968. $deseases[$index]['subdeseases'][$item['desease_id']]['disabled'] = in_array($item['desease_id'], $selectedDeseases) ? 'disabled' : '';;
  969. }*/
  970. return $deseases;
  971. }
  972. public function getExams($checkedExams=[]) {
  973. $axams = [];
  974. $this->db->rawQuery("SET SESSION group_concat_max_len = 1000000");
  975. $results = $this->db
  976. ->get('requests_exams re', null, [
  977. 're.id',
  978. 're.standard_description',
  979. 're.exam_type',
  980. "(SELECT GROUP_CONCAT('\"', resub.id, '\"', ':', '\"', resub.standard_description, '\"') FROM requests_exams resub WHERE resub.parent_id=re.id) children"
  981. ]);
  982. if (is_array($results)) {
  983. foreach($results as $index => $item) {
  984. $axams[$item['standard_description']][$item['id']]['id'] = $item['id'];
  985. $axams[$item['standard_description']][$item['id']]['description'] = _($item['standard_description']);
  986. $axams[$item['standard_description']][$item['id']]['type'] = $item['exam_type'];
  987. $axams[$item['standard_description']][$item['id']]['checked'] = false; //Default
  988. if (isset($checkedExams[$item['exam_type']])) {
  989. foreach($checkedExams[$item['exam_type']] as $checkeds) {
  990. if ($checkeds['id'] == $item['id']) {
  991. $axams[$item['standard_description']][$item['id']]['checked'] = true;
  992. break;
  993. }
  994. }
  995. }
  996. $childrenData = json_decode('{'.stripslashes($item['children']).'}', true);
  997. $children = [];
  998. if (is_array($childrenData) && !empty($childrenData)) {
  999. foreach($childrenData as $childId => $childStandardLabel) {
  1000. $children[$childId]['description'] = _($childStandardLabel);
  1001. $children[$childId]['checked'] = false;
  1002. if (isset($checkedExams[$item['exam_type']])) {
  1003. foreach($checkedExams[$item['exam_type']] as $checkeds) {
  1004. if ($checkeds['id'] == $childId) {
  1005. $children[$childId]['checked'] = true;
  1006. break;
  1007. }
  1008. }
  1009. }
  1010. }
  1011. }
  1012. $axams[$item['standard_description']][$item['id']]['children'] = $children;
  1013. }
  1014. }
  1015. return $axams;
  1016. }
  1017. public function getWizardsByRequestId($requestId=0) {
  1018. $wizards = [];
  1019. $results = $this->db
  1020. ->where('request_id', $requestId)
  1021. ->join('requests_exams re', 're.id=rwt.exam_id', 'INNER')
  1022. ->get('requests_wizards_to rwt', null, [
  1023. 're.id',
  1024. 're.standard_description',
  1025. 'rwt.exam_type',
  1026. "(SELECT re_parent.standard_description FROM requests_exams re_parent WHERE re_parent.id=re.parent_id) parent_name"
  1027. ]);
  1028. if (is_array($results)) {
  1029. foreach($results as $index => $item) {
  1030. $wizards[$item['exam_type']][$index]['id'] = $item['id'];
  1031. $description = $item['parent_name'] != '' ? _($item['parent_name']).' / '._($item['standard_description']) : _($item['standard_description']);
  1032. $wizards[$item['exam_type']][$index]['description'] = $description;
  1033. }
  1034. }
  1035. return $wizards;
  1036. }
  1037. public function getWizardsDermaPositions($requestId=0) {
  1038. $positions = [];
  1039. $results = $this->db
  1040. ->where('request_id', $requestId)
  1041. ->get('requests_wizard_derma_position_to');
  1042. if (is_array($results) && !empty($results)) {
  1043. foreach($results as $item) {
  1044. $positions[$item['position_type']] = $item;
  1045. }
  1046. }
  1047. return $positions;
  1048. }
  1049. public function getWizardsEarDeseases($requestId=0) {
  1050. $deseases = [];
  1051. $results = $this->db
  1052. ->where('request_id', $requestId)
  1053. ->get('requests_wizard_ear_deseases_to');
  1054. if (is_array($results) && !empty($results)) {
  1055. foreach($results as $item) {
  1056. $deseases[$item['desease_type']] = $item;
  1057. }
  1058. }
  1059. return $deseases;
  1060. }
  1061. public function checkPartialUploads() {
  1062. $path = MEDIA_TMP_DIR;
  1063. $infoFiles = glob($path.'*.info');
  1064. return $infoFiles;
  1065. }
  1066. public function cron() {
  1067. shell_exec('cd '.$this->config['job']['path'].'; /usr/local/bin/php cron.php > /dev/null 2>/dev/null &');
  1068. }
  1069. }