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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  1. <?php
  2. class userController extends mainController {
  3. function __construct() {
  4. parent::__construct();
  5. //To change for every Controller
  6. $this->viewDir = 'User';
  7. //$this->allow = [];
  8. }
  9. //Profile (Edit Profile) page
  10. public function index($args=null) {
  11. if (!$this->user->isLogged()) {
  12. return $this->redirect('login', 'permissionDenied');
  13. }
  14. $supportedLanguages = $this->locale->getLanguages();
  15. $languagesList = [];
  16. $userDataSession = $this->user->getUser(); //Get current user's data in session
  17. $userDataDB = $this->user->getUserDB();
  18. $userDefaultLanguage = '';
  19. $userAltLangs = [];
  20. $userRoles = [];
  21. if ((is_array($userDataDB) && !empty($userDataDB)) && (is_array($userDataSession) && !empty($userDataSession))) {
  22. $userDefaultLanguage = $userDataDB['language_default'];
  23. $userAltLangs = $this->user->getUserAltLangsDB();
  24. $userRoles = $userDataSession['userRoles'];
  25. }
  26. //Get all supported languages and select user's default language
  27. foreach($supportedLanguages as $index => $languages) {
  28. $selected = $userDefaultLanguage == $languages['lang_code'] ? true : false;
  29. $languagesList[$index] = $languages;
  30. $languagesList[$index]['selected'] = $selected;
  31. }
  32. $this->view->languageList = $languagesList;
  33. $alternativeLanguages = [];
  34. foreach($supportedLanguages as $index => $languages) {
  35. //if ($languages['lang_code'] != $userDefaultLanguage) {
  36. $alternativeLanguages[$index] = $languages;
  37. $alternativeLanguages[$index]['checked'] = isset($userAltLangs[$languages['id']]) ? true : false;
  38. //}
  39. }
  40. $this->view->userUpdatedAt = $userDataDB['updated_at'];
  41. $this->view->userEmail = trim($userDataDB['email']);
  42. $this->view->userAltEmail = trim($userDataDB['alternative_email']);
  43. $this->view->userRemarks = trim($userDataDB['remarks_public']);
  44. $this->view->userMobNumber = trim($userDataDB['mobile_number']);
  45. $this->view->userMobWA = trim($userDataDB['mobile_number_chat']);
  46. $this->view->userPhoneText = trim($userDataDB['allow_phone_text']);
  47. $this->view->userPhoneChat = trim($userDataDB['allow_phone_chat']);
  48. $this->view->userEmailMsgs = trim($userDataDB['allow_email_msgs']);
  49. $this->view->countries = $this->locale->getCountriesByISO2Code($userDataDB['country_code']);
  50. //$this->view->phoneCodes = $this->locale->getPhoneCodes();
  51. $this->view->alternativeLanguages = $alternativeLanguages;
  52. $this->view->userAvatar = $this->user->getAvatar();
  53. $this->view->hasAvatar = $this->user->hasAvatar();
  54. //$this->view->roles = $this->user->getRoleList(); <-- Deprecated
  55. $this->actionTitle = _('Profile');
  56. $this->breadcrumbs = [['hash'=>null, 'label'=>$this->actionTitle]];
  57. return $this->setJsonView('index');
  58. }
  59. //Save/Edit profile information
  60. public function editProfile() {
  61. if (!$this->user->isLogged()) {
  62. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'));
  63. }
  64. $data = isset($_POST['data']) ? $_POST['data'] : null;
  65. $validation = $this->validateForm($data);
  66. if (is_array($validation)) {
  67. return $this->setRawJsonResponse('err', $validation['msg'], ['class'=>$validation['class']]);
  68. }
  69. if ($validation === true) {
  70. $userId = $this->user->getUserId();
  71. $passwd1 = trim($data['profile_passwd1']['value']);
  72. $passwd2 = trim($data['profile_passwd2']['value']);
  73. $publicRemarks = trim(strip_tags($data['public_remarks']['value']));
  74. $pubRemarksSize = $this->config['settings']['public-remarks-size'];
  75. if (strlen($publicRemarks) > (int)$pubRemarksSize) {
  76. return $this->setRawJsonResponse('err', vsprintf(_('The Remarks text is too long. Maximun allowed size is %s characters.'), $pubRemarksSize));
  77. }
  78. if ($userId !== false) {
  79. $updateAtDate = date('Y-m-d H:i:s');
  80. $updateData = [
  81. 'email' => $data['email']['value'],
  82. //'alternative_email' => $data['alt_email']['value'],
  83. 'language_default' => $data['default_lang']['value'],
  84. 'country_code' => $data['country']['value'],
  85. 'remarks_public' => $publicRemarks,
  86. 'mobile_number' => $data['default_mobile']['value'],
  87. 'mobile_number_chat' => $data['mobile_chat']['value'],
  88. 'allow_phone_text' => $data['phone_pref']['value'],
  89. 'allow_phone_chat' => $data['wa_pref']['value'],
  90. 'allow_email_msgs' => $data['wa_email']['value'],
  91. 'updated_at' => $updateAtDate
  92. ];
  93. if ($passwd1 != '') {
  94. if (!$this->security->validatePassword($passwd1)) {
  95. return $this->setRawJsonResponse('err', vsprintf(_('The password provided is not valid. The password must contain at least %s characters and at least 1 non-alphanumeric symbol (!, ?, -, etc.)'), [$this->security->passwordMinLength]), ['class'=>'field-passwd1']);
  96. }
  97. if ($passwd1 != $passwd2) {
  98. return $this->setRawJsonResponse('err', _('The password fields do not match.'), ['class'=>'field-passwd1']);
  99. }
  100. $updateData['password'] = md5($passwd1);
  101. }
  102. if ($this->db->where('id', $userId)->update('users', $updateData)) {
  103. if (isset($data['alt_langs']['value']) && is_array($data['alt_langs']['value']) && !empty($data['alt_langs']['value'])) {
  104. $this->db->where('user_id', $userId)->delete('users_languages_to');
  105. foreach($data['alt_langs']['value'] as $langId => $langCode) {
  106. $this->db->insert('users_languages_to', ['user_id'=>$userId, 'language_id'=>$langId]);
  107. }
  108. }
  109. //Refresh user's language in session
  110. $languageData = $this->db->where('lang_code', $data['default_lang']['value'])->getOne('users_languages');
  111. if (is_array($languageData) && !empty($languageData)) {
  112. if ($this->locale->filterValidLanguage($languageData['lang_code'])) {
  113. $this->user->refreshSessionField('userDefaultLang', $languageData['lang_code']);
  114. }
  115. $this->user->refreshSessionField('userDefaultString', $languageData['name_string']);
  116. }
  117. //Refresh last update field in user's session
  118. $this->user->refreshSessionField('userUpdatedAt', $updateAtDate);
  119. //Refresh country information in session
  120. $countryData = $this->db->where('country_iso2_code', $data['country']['value'])->getOne('countries');
  121. if (is_array($countryData) && !empty($countryData)) {
  122. $this->user->refreshSessionField('userCountryName', $countryData['country_name']);
  123. $this->user->refreshSessionField('userCountryCode', $countryData['country_iso2_code']);
  124. $this->user->refreshSessionField('userCountryId', $countryData['id']);
  125. }
  126. //Refresh the localised roles
  127. $localeRoles = $this->user->getUserRolesDB($userId);
  128. $roleList = [];
  129. if (is_array($localeRoles) && !empty($localeRoles)) {
  130. foreach($localeRoles as $roleId => $roleRow) {
  131. $roleList[$roleId] = $roleRow['role_names'];
  132. }
  133. $this->user->refreshSessionField('userRolesLocale', $roleList);
  134. }
  135. //Check for avatar file
  136. $file = isset($_FILES['data']) ? $_FILES['data']: null;
  137. //Update avatar
  138. if (is_array($file)) {
  139. if ((int)$file['error']['avatar']['value'] == 0) {
  140. $this->user->setAvatar($userId, $file['tmp_name']['avatar']['value']);
  141. }
  142. }
  143. //Check whether remove avatar or don't (without replacing it)
  144. if (isset($data['remove_avatar']['value'])) {
  145. if ((int)$data['remove_avatar']['value'] == 1) {
  146. $this->user->deleteAvatar($userId);
  147. }
  148. }
  149. return $this->setRawJsonResponse('ok', _('Profile information successfully updated.'), ['log'=>''], ['button'=>'refresh-page']);
  150. } else {
  151. return $this->setRawJsonResponse('err', _('Unable to update the profile right now. Please try again in a few minutes.').' (Err. cod. 0)');
  152. }
  153. } else {
  154. return $this->setRawJsonResponse('err', _('Incorrect user information, please log in again.'));
  155. }
  156. return $this->setRawJsonResponse('err', _('Unable to perform the request right now. Please try again in a few minutes.').' (Err. cod. 1)');
  157. }
  158. return $this->setRawJsonResponse('err', _('Unable to perform the request right now. Please try again in a few minutes.').' (Err. cod. 2)');
  159. }
  160. //Users list action
  161. public function usersList($args=null) {
  162. if(!$this->checkPermissions([ADMIN_ROLE_ID])) {
  163. return $this->redirect('login', 'permissionDenied');
  164. }
  165. $userGroupId = $this->user->getUserField('userGroupId');
  166. $groupInfo = $this->db->where('id', $userGroupId)->getOne('users_groups');
  167. //$this->view->groupName = isset($groupInfo['group_name']) ? $groupInfo['group_name'] : '';
  168. $this->view->currentPage = $this->getPost('pageNumb', 1);
  169. $this->view->orderField = $this->getPost('orderField', 'surname');
  170. $this->view->orderDir = $this->getPost('orderDir', 'desc');
  171. $this->view->roleSelectList = [];
  172. //$this->db->pageLimit = 3;
  173. if ($this->view->orderDir == 'asc')
  174. $dynOrderDir = 'desc';
  175. else
  176. $dynOrderDir = 'asc';
  177. //$this->view->strOutput = null;
  178. $searchData = $this->getPost('searchData');
  179. parse_str($searchData, $this->view->strOutput);
  180. //$totalRows = $this->db->where('group_id', $userGroupId)->getValue('users', 'COUNT(*)');
  181. $fields = [
  182. 'users.id',
  183. 'users.username',
  184. 'users.surname',
  185. 'users.name',
  186. 'users.email',
  187. 'users.updated_at',
  188. 'users.created_at',
  189. "(SELECT GROUP_CONCAT(GET_JSON_VALUE_BY_KEY(ur.name_translations, '".$this->user->getUserLang()."', '".$this->defLang."') SEPARATOR ', ') AS role_string FROM users_roles_to AS urt JOIN users_roles AS ur ON ur.id=urt.role_id WHERE urt.user_id = users.id GROUP BY urt.user_id ORDER BY role_string) AS roles",
  190. 'users.status'
  191. ];
  192. $this->db->where('group_id', $userGroupId);
  193. if (isset($this->view->strOutput['search']['username'])) {
  194. $keyword = $this->view->strOutput['search']['username'];
  195. $this->db->where('users.username', "%$keyword%", 'like');
  196. }
  197. if (isset($this->view->strOutput['search']['surname'])) {
  198. $keyword = $this->view->strOutput['search']['surname'];
  199. $this->db->where('users.surname', "%$keyword%", 'like');
  200. }
  201. if (isset($this->view->strOutput['search']['name'])) {
  202. $keyword = $this->view->strOutput['search']['name'];
  203. $this->db->where('users.name', "%$keyword%", 'like');
  204. }
  205. if (isset($this->view->strOutput['search']['email'])) {
  206. $keyword = $this->view->strOutput['search']['email'];
  207. $this->db->where('users.email', "%$keyword%", 'like');
  208. }
  209. $roleKeyword = '';
  210. if (isset($this->view->strOutput['search']['roles']) && trim($this->view->strOutput['search']['roles']) != '') {
  211. $roleKeyword = $this->view->strOutput['search']['roles'];
  212. $fields[] = "(SELECT COUNT(*) FROM users_roles_to WHERE users_roles_to.user_id=users.id AND users_roles_to.role_id = $roleKeyword) AS total_user_roles";
  213. $this->db->having('total_user_roles', 0, '>');
  214. }
  215. $this->db->orderBy($this->view->orderField, $dynOrderDir);
  216. $this->view->usersList = $this->db->paginate('users', $this->view->currentPage, $fields);
  217. //
  218. $this->view->getTotUsers = $this->db->totalUsers;
  219. $this->view->getTotRoles = $this->db->TotUsersRoles;
  220. // Max Add Roles for Users
  221. $this->view->getMaxAddRoles = $this->db->MaxAddRoles;
  222. // Max type Roles
  223. $this->view->getMaxAddAdmins = $this->db->MaxAddAdmins;
  224. $this->view->getMaxAddModerators = $this->db->MaxAddModerators;
  225. $this->view->getMaxAddRequesters = $this->db->MaxAddRequesters;
  226. $this->view->getMaxAddResponders = $this->db->MaxAddResponders;
  227. $this->view->getMaxAddGuests = $this->db->MaxAddGuests;
  228. //Total Roles for Users
  229. $this->view->getTotAdmins = $this->db->TotAdmins;
  230. $this->view->getTotModerators = $this->db->TotModerators;
  231. $this->view->getTotRequesters = $this->db->TotRequesters;
  232. $this->view->getTotResponders = $this->db->TotResponders;
  233. $this->view->getTotGuests = $this->db->TotGuests;
  234. // USER ROLES
  235. $this->view->getUserHasRoles = 111;
  236. $this->setPagination($this->db, $this->db->totalCount, $this->view->currentPage, 'users/'.time().'/'.$this->view->orderField.'/'.$this->view->orderDir);
  237. $this->view->lastQuery = $this->db->getLastQuery();
  238. //Selected list for column filter
  239. $roleSelectList = $this->user->getRoles();
  240. $this->view->roleSelectList = [];
  241. foreach($roleSelectList as $roleId => $role) {
  242. $this->view->roleSelectList[$roleId]['value'] = $roleId;
  243. $this->view->roleSelectList[$roleId]['name'] = $role;
  244. $this->view->roleSelectList[$roleId]['selected'] = $roleKeyword == $roleId ? true : false;
  245. }
  246. $this->actionTitle = _('Users');
  247. $this->breadcrumbs = [['hash'=>null, 'label'=>$this->actionTitle]];
  248. $this->view->editLinkHash = 'users-edit/'.time().'/%s/'.$this->view->orderField.'/'.$this->view->orderDir.'/'.$this->view->currentPage;
  249. return $this->setJsonView('usersList');
  250. }
  251. //Users add/edit action (view)
  252. public function usersEdit($args=null) {
  253. if(!$this->checkPermissions([ADMIN_ROLE_ID])) {
  254. return $this->redirect('login', 'permissionDenied');
  255. }
  256. //Needed by "Home" breadcrumbs' link
  257. $page = $this->getPost('pageNumb', 1);
  258. $orderField = $this->getPost('orderField', 'surname');
  259. $orderDir = $this->getPost('orderDir', 'desc');
  260. $userId = $this->getPost('userId', 0);
  261. //Check whether the current logged user is the current editing user
  262. $this->view->isSelf = $userId == $this->user->getUserId() ? true : false;
  263. $this->view->userId = $userId;
  264. $this->view->userData = [];
  265. $this->view->supportedLanguages = $this->locale->getLanguages();
  266. $this->view->userAltLanguages = $this->view->supportedLanguages;
  267. $this->view->roles = [];
  268. $this->view->countries = $this->locale->getCountriesByISO2Code();
  269. $this->view->clinicalCenterCountries = $this->getClinicalCenterCountries(true); //true = group by continent
  270. $this->view->clinicalCenters = $this->db->where('group_id', $this->userGroupId)->orderBy('description', 'asc')->get('clinical_centers');
  271. $this->view->medicalSpecialties = $this->db->orderBy('description', 'asc')->get('users_medical_specialties');
  272. //Default values
  273. $this->view->userClinicalCenters[APPLICANT_ROLE_ID] = 0;
  274. $this->view->userClinicalCenters[REFERRER_ROLE_ID] = 0;
  275. $this->view->userClinicalCenters[MODERATOR_ROLE_ID] = 0;
  276. $this->view->userClinicalCenters[GUEST_ROLE_ID] = 0;
  277. $roleForClinicalCenters = [];
  278. $this->view->responderStructure = [];
  279. $this->view->userMedicalSpecialties = [];
  280. $this->view->userAvatar = $this->user->getDefaultAvatar();
  281. $this->view->hasAvatar = false;
  282. // Max type Roles
  283. $this->view->getMaxAddAdmins = $this->db->MaxAddAdmins;
  284. $this->view->getMaxAddModerators = $this->db->MaxAddModerators;
  285. $this->view->getMaxAddRequesters = $this->db->MaxAddRequesters;
  286. $this->view->getMaxAddResponders = $this->db->MaxAddResponders;
  287. $this->view->getMaxAddGuests = $this->db->MaxAddGuests;
  288. //Total Roles for Users
  289. $this->view->getTotAdmins = $this->db->TotAdmins;
  290. $this->view->getTotModerators = $this->db->TotModerators;
  291. $this->view->getTotRequesters = $this->db->TotRequesters;
  292. $this->view->getTotResponders = $this->db->TotResponders;
  293. $this->view->getTotGuests = $this->db->TotGuests;
  294. // USER ROLES
  295. $this->view->getUserHasRoles = $this->user->getUserRolesDB($userId);
  296. $userRoles = $userId > 0 ? $this->user->getUserRolesDB($userId) : [];
  297. $supportedRoles = $this->user->getRoles(); //All roles
  298. $responderStructure = $this->db->orderBy('description', 'asc')->get('users_structures');
  299. //$thid->view->responderStructure = $responderStructure;
  300. //Check the user roles for the Clinical Centers
  301. $roleForClinicalCenters = [];
  302. if (is_array($supportedRoles)) {
  303. $c = 0;
  304. foreach($supportedRoles as $roleId => $role) {
  305. //Get the checked roles based on all supported roles (if true, that role id has been checked)
  306. //$supportedRoles[$c]['checked'] = isset($userRoles[$roleId]) ? true : false;
  307. $this->view->roles[$c]['id'] = $roleId;
  308. $this->view->roles[$c]['name'] = $role;
  309. $this->view->roles[$c]['checked'] = isset($userRoles[$roleId]) ? true : false;
  310. //Assign the roles for select the relative Clinical Centers
  311. if ($this->view->roles[$c]['checked']) {
  312. if ($roleId == APPLICANT_ROLE_ID) {
  313. $roleForClinicalCenters[APPLICANT_ROLE_ID] = APPLICANT_ROLE_ID; //Change the default value 0
  314. }
  315. if ($roleId == REFERRER_ROLE_ID) {
  316. $roleForClinicalCenters[REFERRER_ROLE_ID] = REFERRER_ROLE_ID; //Change the default value 0
  317. }
  318. if ($roleId == MODERATOR_ROLE_ID) {
  319. $roleForClinicalCenters[MODERATOR_ROLE_ID] = MODERATOR_ROLE_ID; //Change the default value 0
  320. }
  321. if ($roleId == GUEST_ROLE_ID) {
  322. $roleForClinicalCenters[GUEST_ROLE_ID] = GUEST_ROLE_ID; //Change the default value 0
  323. }
  324. if ($roleId == GLOBAL_MANAGER_ID) {
  325. $roleForClinicalCenters[GLOBAL_MANAGER_ID] = GLOBAL_MANAGER_ID; //Change the default value 0
  326. }
  327. if ($roleId == MANAGER_ID) {
  328. $roleForClinicalCenters[MANAGER_ID] = MANAGER_ID; //Change the default value 0
  329. }
  330. }
  331. $c++;
  332. }
  333. //$this->view->roles = $supportedRoles;
  334. }
  335. //Default avatar image
  336. $this->view->userAvatarImage = $this->user->getDefaultAvatar();
  337. if ((int)$userId > 0) {
  338. $this->view->userData = $this->db->where('id', $userId)->getOne('users');
  339. $this->view->userData['language_default'] = isset($this->view->userData['language_default']) ? $this->convertOldUserLang($this->view->userData['language_default']) : '';
  340. //Set the current user avatar image
  341. $this->view->userAvatarImage = $this->user->getAvatar($userId);
  342. $userAltLangs = $this->user->getUserAltLangsDB($userId);
  343. foreach($this->view->supportedLanguages as $index => $language) {
  344. //Select the user's default language in the select box
  345. $this->view->supportedLanguages[$index]['selected'] = ($this->view->userData['language_default'] == $language['lang_code']) ? true : false;
  346. //Check all languages known by the user
  347. $this->view->supportedLanguages[$index]['checked'] = isset($userAltLangs[$language['id']]) ? true : false;
  348. }
  349. //Set the alternative language array and remove the user's default language
  350. $this->view->userAltLanguages = $this->view->supportedLanguages;
  351. foreach($this->view->userAltLanguages as $index => $language) {
  352. if ($language['lang_code'] == $this->view->userData['language_default']) {
  353. unset($this->view->userAltLanguages[$index]);
  354. break;
  355. }
  356. }
  357. //If the user is Applicant, search the Clinical Center assigned as Applicant
  358. if (isset($roleForClinicalCenters[APPLICANT_ROLE_ID]) && $roleForClinicalCenters[APPLICANT_ROLE_ID] > 0) {
  359. //The method is in mainController
  360. $this->view->userClinicalCenters[APPLICANT_ROLE_ID] = $this->getUserClinicalCenters($userId, APPLICANT_ROLE_ID);
  361. } else {
  362. $this->view->userClinicalCenters[APPLICANT_ROLE_ID] = [];
  363. }
  364. //If the user is Referrer, search the Clinical Center assigned as Referrer
  365. if (isset($roleForClinicalCenters[REFERRER_ROLE_ID]) && $roleForClinicalCenters[REFERRER_ROLE_ID] > 0) {
  366. //The method is in mainController
  367. $this->view->userClinicalCenters[REFERRER_ROLE_ID] = $this->getUserClinicalCenters($userId, REFERRER_ROLE_ID);
  368. } else {
  369. $this->view->userClinicalCenters[REFERRER_ROLE_ID] = [];
  370. }
  371. //If the user is Moderator, search the Clinical Center assigned as Moderator
  372. if (isset($roleForClinicalCenters[MODERATOR_ROLE_ID]) && $roleForClinicalCenters[MODERATOR_ROLE_ID] > 0) {
  373. //The method is in mainController
  374. $this->view->userClinicalCenters[MODERATOR_ROLE_ID] = $this->getUserClinicalCenters($userId, MODERATOR_ROLE_ID);
  375. } else {
  376. $this->view->userClinicalCenters[MODERATOR_ROLE_ID] = [];
  377. }
  378. //If the user is Guest, search the Clinical Center assigned as Guest
  379. if (isset($roleForClinicalCenters[GUEST_ROLE_ID]) && $roleForClinicalCenters[GUEST_ROLE_ID] > 0) {
  380. //The method is in mainController
  381. $this->view->userClinicalCenters[GUEST_ROLE_ID] = $this->getUserClinicalCenters($userId, GUEST_ROLE_ID);
  382. } else {
  383. $this->view->userClinicalCenters[GUEST_ROLE_ID] = [];
  384. }
  385. //If the user is Manager, search the Clinical Center assigned as Manager
  386. if (isset($roleForClinicalCenters[MANAGER_ID]) && $roleForClinicalCenters[MANAGER_ID] > 0) {
  387. //The method is in mainController
  388. $this->view->userClinicalCenters[MANAGER_ID] = $this->getUserClinicalCenters($userId, MANAGER_ID);
  389. } else {
  390. $this->view->userClinicalCenters[MANAGER_ID] = [];
  391. }
  392. //If the user is Global Manager, search the Clinical Center assigned as Global Manager
  393. if (isset($roleForClinicalCenters[GLOBAL_MANAGER_ID]) && $roleForClinicalCenters[GLOBAL_MANAGER_ID] > 0) {
  394. //The method is in mainController
  395. $this->view->userClinicalCenters[GLOBAL_MANAGER_ID] = $this->getUserClinicalCenters($userId, GLOBAL_MANAGER_ID);
  396. } else {
  397. $this->view->userClinicalCenters[GLOBAL_MANAGER_ID] = [];
  398. }
  399. //Method is in mainController
  400. $this->view->userMedicalSpecialties = $this->getUserMedicalSpecialties($userId);
  401. $this->view->userAvatar = $this->user->getAvatar($userId);
  402. $this->view->hasAvatar = $this->user->hasAvatar($userId);
  403. }
  404. $this->actionTitle = $userId==0 ? _('User : Add') : _('User : Edit');
  405. $this->breadcrumbs = [['hash'=>'users/'.time().'/'.$orderField.'/'.$orderDir.'/'.$page, 'label'=>_('Users')], ['hash'=>null, 'label'=>$this->actionTitle]];
  406. return $this->setJsonView('usersEdit');
  407. }
  408. //Users add/edit action (save/update)
  409. public function usersSave() {
  410. if (!$this->user->isLogged()) {
  411. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  412. }
  413. if(!$this->checkPermissions([ADMIN_ROLE_ID])) {
  414. return $this->setRawJsonResponse('err', _('Permission denied.'));
  415. }
  416. $data = isset($_POST['data']) ? $_POST['data'] : null;
  417. $file = isset($_FILES['data']) ? $_FILES['data']: null;
  418. //return $this->setRawJsonResponse('err', json_encode($data['med_specialties']['value']));
  419. //Check required values
  420. $validation = $this->validateForm($data);
  421. if (is_array($validation)) {
  422. return $this->setRawJsonResponse('err', $validation['msg'], ['class'=>$validation['class']]);
  423. }
  424. if ($validation === true) {
  425. $userId = (int)$data['user_id']['value'];
  426. $isSelf = $userId == $this->user->getUserId() ? true : false;
  427. $isEditing = $userId > 0 ? true : false; //Editing or Saving?
  428. //Check username
  429. $isUsernameInUse = $this->user->isUsernameInUse(trim($data['username']['value']));
  430. if (!$isEditing && $isUsernameInUse) {
  431. return $this->setRawJsonResponse('err', _('The Username provided is already in use.'));
  432. }
  433. $passwd1 = trim($data['profile_passwd1']['value']);
  434. $passwd2 = trim($data['profile_passwd2']['value']);
  435. //Check roles number
  436. if (!isset($data['role']) || !is_array($data['role'])) {
  437. return $this->setRawJsonResponse('err', _('Please provide at least one role.'));
  438. }
  439. //Check if current logged user is an administrator and Administrator role checkbox is unchecked
  440. if ($isSelf && $this->user->is(ADMIN_ROLE_ID)) {
  441. if (!isset($data['role']['value'][ADMIN_ROLE_ID])) {
  442. return $this->setRawJsonResponse('err', _('You cannot downgrade your Administrator role.'));
  443. }
  444. }
  445. $userStatus = isset($data['status']['value']) ? $data['status']['value'] : 0;
  446. if (isset($data['role']['value'][ADMIN_ROLE_ID])) {
  447. if ($userStatus == STATUS_TECH_ID) {
  448. return $this->setRawJsonResponse('err', _("The user status selected doesn't allow to add the Administrator role."));
  449. }
  450. }
  451. //Roles are ok, check the data related to the roles
  452. if (is_array($data['role']['value'])) {
  453. //User is a Referrer
  454. if (isset($data['role']['value'][REFERRER_ROLE_ID])) {
  455. //Check Medical specialties
  456. if (!isset($data['med_specialties']['value']) || empty($data['med_specialties']['value'])) {
  457. return $this->setRawJsonResponse('err', _('Please provide at least one Medical specialty for this user.'));
  458. }
  459. //Check Clinical centers
  460. if (!isset($data['cc_referrer']['value']) || empty($data['cc_referrer']['value'])) {
  461. return $this->setRawJsonResponse('err', _('Please provide at least one Clinical Center (Responder) for this user.'));
  462. }
  463. }
  464. //User is Applicant
  465. if (isset($data['role']['value'][APPLICANT_ROLE_ID])) {
  466. //Check Clinical centers
  467. if (!isset($data['cc_applicant']['value']) || empty($data['cc_applicant']['value'])) {
  468. return $this->setRawJsonResponse('err', _('Please provide at least one Clinical Center (Requester) for this user.'));
  469. }
  470. }
  471. //User is Moderator
  472. if (isset($data['role']['value'][MODERATOR_ROLE_ID])) {
  473. //Check Clinical centers
  474. if (!isset($data['cc_moderator']['value']) || empty($data['cc_moderator']['value'])) {
  475. return $this->setRawJsonResponse('err', _('Please provide at least one Clinical Center (Moderator) for this user.'));
  476. }
  477. }
  478. //User is Guest
  479. if (isset($data['role']['value'][GUEST_ROLE_ID])) {
  480. //Check Clinical centers
  481. if (!isset($data['cc_guest']['value']) || empty($data['cc_guest']['value'])) {
  482. return $this->setRawJsonResponse('err', _('Please provide at least one Clinical Center (Guest) for this user.'));
  483. }
  484. }
  485. if (isset($data['role']['value'][GLOBAL_MANAGER_ID])) {
  486. //Check Clinical centers
  487. if (!isset($data['cc_global_manager']['value'][0]) || (int)$data['cc_global_manager']['value'][0] == 0) {
  488. return $this->setRawJsonResponse('err', _('Please provide at least one Clinical Center (Global Manager) for this user.'));
  489. }
  490. }
  491. if (isset($data['role']['value'][MANAGER_ID])) {
  492. //Check Clinical centers
  493. if (!isset($data['cc_manager']['value'][0]) || (int)$data['cc_manager']['value'][0] == 0) {
  494. return $this->setRawJsonResponse('err', _('Please provide at least one Clinical Center (Manager) for this user.'));
  495. }
  496. }
  497. }
  498. $publicRemarks = trim(strip_tags($data['public_remarks']['value']));
  499. $pubRemarksSize = $this->config['settings']['public-remarks-size'];
  500. if (strlen($publicRemarks) > (int)$pubRemarksSize) {
  501. return $this->setRawJsonResponse('err', vsprintf(_('The Public Remarks text is too long. Maximun allowed size is %s characters.'), $pubRemarksSize));
  502. }
  503. $insertData = [
  504. 'group_id' => $this->userGroupId,
  505. 'username' => trim($data['username']['value']),
  506. 'language_default' => $data['default_lang']['value'],
  507. 'remarks_public' => $publicRemarks,
  508. 'remarks_private' => trim($data['private_remarks']['value']),
  509. 'name' => trim($data['name']['value']),
  510. 'surname' => trim($data['surname']['value']),
  511. //'fiscal_code' => trim($data['fiscal_code']['value']),
  512. // BIRTH
  513. //'birth_date' => trim($data['birth_date']['value']),
  514. //'city_birth' => trim($data['city_birth']['value']),
  515. //'province_birth' => trim($data['province_birth']['value']),
  516. // RESIDENCE
  517. //'residence_province' => trim($data['residence_province']['value']),
  518. //'residence_city' => trim($data['residence_city']['value']),
  519. //'residence_address' => trim($data['residence_address']['value']),
  520. // DOMICILE
  521. //'domicile_province' => trim($data['domicile_province']['value']),
  522. //'domicile_city' => trim($data['domicile_city']['value']),
  523. //'domicile_address' => trim($data['domicile_address']['value']),
  524. //'country_id' => $data['country']['value'],
  525. 'country_code' => $data['country']['value'],
  526. 'email' => trim($data['email']['value']),
  527. //'alternative_email' => trim($data['alt_email']['value']),
  528. 'advanced_request' => $data['advanced_request']['value'],
  529. 'mobile_number' => trim($data['default_mobile']['value']),
  530. 'mobile_number_chat' => trim($data['mobile_chat']['value']),
  531. 'allow_phone_text' => $data['phone_pref']['value'],
  532. 'allow_phone_chat' => $data['wa_pref']['value'],
  533. 'allow_email_msgs' => $data['email_pref']['value']
  534. ];
  535. //Change the status (if this user is not the current logged user)
  536. if (!$isSelf) {
  537. /*if (isset($data['status']['value'])) {
  538. $insertData['status'] = $data['status']['value'];
  539. }*/
  540. $insertData['status'] = $userStatus;
  541. }
  542. //Check passwords
  543. $passwd1 = trim($data['profile_passwd1']['value']);
  544. $passwd2 = trim($data['profile_passwd2']['value']);
  545. if ($passwd1 != '') {
  546. if (!$this->security->validatePassword($passwd1)) {
  547. return $this->setRawJsonResponse('err', vsprintf(_('The password provided is not valid. The password must contain at least %s characters and at least 1 non-alphanumeric symbol (!, ?, -, etc.)'), [$this->security->passwordMinLength]));
  548. }
  549. if ($passwd1 != $passwd2) {
  550. return $this->setRawJsonResponse('err', _('The password fields do not match.'));
  551. }
  552. $insertData['password'] = md5($passwd1);
  553. }
  554. /*if ($this->user->getUserStatus() == STATUS_TECH_ID) {
  555. return $this->setRawJsonResponse('ok', _('All fields have been correctly validated. The current user cannot save the new information.'));
  556. }*/
  557. $updatedAtDate = date('Y-m-d H:i:s'); //Also used to refresh the current user session
  558. if ($userId > 0) { //Update
  559. $insertData['updated_at'] = $updatedAtDate;
  560. $this->db->where('id', $userId);
  561. if (!$this->db->update('users', $insertData)) {
  562. $this->logger->logUserAction($this->user->getUserId(), "UPDATE USER ERROR", $this->db->getLastError());
  563. return $this->setRawJsonResponse('err', $this->db->getLastError());
  564. }
  565. $this->logger->logUserAction($this->user->getUserId(), "UPDATE USER $userId");
  566. } else { //Insert
  567. $insertData['created_at'] = $updatedAtDate;
  568. $insertData['updated_at'] = $updatedAtDate;
  569. $insertId = $this->db->insert('users', $insertData);
  570. if ($insertId) {
  571. $userId = $insertId;
  572. $this->logger->logUserAction($this->user->getUserId(), "INSERT USER $userId");
  573. } else {
  574. $this->logger->logUserAction($this->user->getUserId(), "INSERT USER ERROR", $this->db->getLastError());
  575. return $this->setRawJsonResponse('err', $this->db->getLastError());
  576. }
  577. }
  578. //Updating or inserting ok
  579. if ($userId > 0) {
  580. $userIsSelf = $userId == $this->user->getUserId() ? true : false;
  581. $userDisplayName = $this->user->setDisplayName(['userName'=>trim($data['name']['value']), 'userSurname'=>trim($data['surname']['value'])]);
  582. //Update the Medical spacialties
  583. $this->db->where('user_id', $userId)->delete('users_medical_specialties_to');
  584. if (isset($data['med_specialties']['value'])) {
  585. $medSpecialties = $data['med_specialties']['value'];
  586. if (is_array($medSpecialties) && !empty($medSpecialties)) {
  587. foreach($medSpecialties as $specialityId) {
  588. $this->db->insert('users_medical_specialties_to', ['user_id'=>$userId, 'specialty_id'=>$specialityId]);
  589. }
  590. $this->memoryCache->remove('medical:specialties:'.$userId);
  591. /*$this->db->where('user_id', $userId);
  592. if ($this->db->delete('users_medical_specialties_to')) {
  593. foreach($medSpecialties as $specialityId) {
  594. $this->db->insert('users_medical_specialties_to', ['user_id'=>$userId, 'specialty_id'=>$specialityId]);
  595. }
  596. $this->memoryCache->remove('medical:specialties:'.$userId);
  597. }*/
  598. }
  599. } else {
  600. $this->memoryCache->remove('medical:specialties:'.$userId);
  601. }
  602. //Update Clinical Center for these roles
  603. $checkRoles = [REFERRER_ROLE_ID, APPLICANT_ROLE_ID, MODERATOR_ROLE_ID, GUEST_ROLE_ID, MANAGER_ID, GLOBAL_MANAGER_ID];
  604. //return $this->setRawJsonResponse('err', json_encode($data['cc_manager']['value']));
  605. //Loop the roles
  606. foreach($checkRoles as $checkRole) {
  607. switch($checkRole) {
  608. case REFERRER_ROLE_ID:
  609. $fieldName = 'cc_referrer';
  610. break;
  611. case APPLICANT_ROLE_ID:
  612. $fieldName = 'cc_applicant';
  613. break;
  614. case MODERATOR_ROLE_ID:
  615. $fieldName = 'cc_moderator';
  616. break;
  617. case GUEST_ROLE_ID:
  618. $fieldName = 'cc_guest';
  619. break;
  620. case GLOBAL_MANAGER_ID:
  621. $fieldName = 'cc_global_manager';
  622. break;
  623. case MANAGER_ID:
  624. $fieldName = 'cc_manager';
  625. break;
  626. }
  627. //Check whether this role is checked
  628. if (isset($data['role']['value'][$checkRole])) {
  629. //Check if field data exist in POST request
  630. if (isset($data[$fieldName]['value'])) {
  631. //Take the center id values (array)
  632. $centerIDs = $data[$fieldName]['value'];
  633. //Check if there are clinical center ids
  634. if (is_array($centerIDs) && !empty($centerIDs)) {
  635. //Clean the relationship without assigned role id (role_id = 0)
  636. $this->db->where('user_id', $userId)->where('role_id', 0)->delete('users_clinical_centers_to');
  637. //Delete the previous clinical center <-> user/role relationship
  638. $this->db->where('user_id', $userId)->where('role_id', $checkRole)->delete('users_clinical_centers_to');
  639. //Add the new clinical center for this user and this role
  640. foreach($centerIDs as $centerId) {
  641. $this->db->insert('users_clinical_centers_to', ['user_id'=>$userId, 'center_id'=>$centerId, 'role_id'=>$checkRole]);
  642. }
  643. }
  644. }
  645. } else {
  646. //If the role is not checked, delete the corresponding clinical centers if exist
  647. $this->db->where('user_id', $userId)->where('role_id', 0)->delete('users_clinical_centers_to');
  648. $this->db->where('user_id', $userId)->where('role_id', $checkRole)->delete('users_clinical_centers_to');
  649. }
  650. //Delete the keys in cache
  651. $this->memoryCache->remove('clinical:center:'.$userId.':'.$checkRole);
  652. $this->memoryCache->remove('clinical:center:'.$userId.':0');
  653. }
  654. //Update the selected roles
  655. $checkedRoles = $data['role']['value'];
  656. //Clean the previuoses user/role relationships
  657. $this->db->where('user_id', $userId);
  658. if ($this->db->delete('users_roles_to')) {
  659. foreach($checkedRoles as $checkedRole) {
  660. $this->db->insert('users_roles_to', ['user_id'=>$userId, 'role_id'=>$checkedRole]);
  661. }
  662. }
  663. //Update alternative languages
  664. if (isset($data['alt_langs']['value']) && is_array($data['alt_langs']['value'])) {
  665. $checkedAltLangs = $data['alt_langs']['value'];
  666. //Clean previouse user/languages relationship
  667. $this->db->where('user_id', $userId);
  668. if ($this->db->delete('users_languages_to')) {
  669. foreach($checkedAltLangs as $checkedAltLang) {
  670. $this->db->insert('users_languages_to', ['user_id'=>$userId, 'language_id'=>$checkedAltLang]);
  671. }
  672. }
  673. }
  674. //Update avatar
  675. if (is_array($file)) {
  676. if ((int)$file['error']['avatar']['value'] == 0) {
  677. $this->user->setAvatar($userId, $file['tmp_name']['avatar']['value']);
  678. }
  679. }
  680. //Check whether remove avatar or don't (without replacing it)
  681. if (isset($data['remove_avatar']['value'])) {
  682. if ((int)$data['remove_avatar']['value'] == 1) {
  683. $this->user->deleteAvatar($userId);
  684. }
  685. }
  686. //Delete user session
  687. if (!$isSelf) {
  688. $this->user->removeAllUserSessionRecords($userId);
  689. } else {
  690. $countryData = $this->db->where('country_iso2_code', $data['country']['value'])->getOne('countries');
  691. $languageData = $this->db->where('lang_code', $data['default_lang']['value'])->getOne('users_languages');
  692. $this->user->refreshUserSession([
  693. 'id'=>$userId,
  694. 'username'=>trim($data['username']['value']),
  695. 'name'=>trim($data['name']['value']),
  696. 'surname'=>trim($data['surname']['value']),
  697. 'language_default'=>$data['default_lang']['value'],
  698. 'roles'=>$this->user->getUserRolesDB($userId),
  699. 'country_data'=> is_array($countryData) ? $countryData : [],
  700. 'language_data'=> is_array($languageData) ? $languageData : [],
  701. 'updated_at'=>$updatedAtDate,
  702. 'group_id'=>$this->userGroupId
  703. ]);
  704. }
  705. $jsPopupButton = $isEditing ? 'refresh-hash' : 'refresh-user-edit';
  706. return $this->setRawJsonResponse('ok', _('User information successfully updated.'), [], ['userId'=>$userId, 'button'=>$jsPopupButton]);
  707. } else {
  708. return $this->setRawJsonResponse('err', _('An error occurred saving the data. Please try again in a few minutes.'));
  709. }
  710. } //validation
  711. }
  712. public function usersSearch() {
  713. if (!$this->user->isLogged()) {
  714. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  715. }
  716. if(!$this->checkPermissions([ADMIN_ROLE_ID])) {
  717. return $this->setRawJsonResponse('err', _('Permission denied.'));
  718. }
  719. $this->view->supportedLanguages = $this->locale->getLanguages();
  720. $this->view->countries = $this->locale->getCountriesByISO2Code();
  721. $clinicalCenters = $this->db->orderBy('description', 'asc')->get('clinical_centers');
  722. $this->view->clinicalCentersPerRole = [];
  723. $this->view->clinicalCenterCountries = $this->getClinicalCenterCountries(true); //true = group by continent
  724. //Array structure: role id => html select field name
  725. $checkCcRoles = [APPLICANT_ROLE_ID=>'cc_applicant', REFERRER_ROLE_ID=>'cc_referrer', MODERATOR_ROLE_ID=>'cc_moderator', GUEST_ROLE_ID=>'cc_guest'];
  726. $checkCcCountries = [APPLICANT_ROLE_ID=>'cn_applicant', REFERRER_ROLE_ID=>'cn_referrer', MODERATOR_ROLE_ID=>'cn_moderator', GUEST_ROLE_ID=>'cn_guest'];
  727. //Pass the role array to the view too
  728. $this->view->checkCcRoles = $checkCcRoles;
  729. $this->view->checkCcCountries = $checkCcCountries;
  730. $this->view->checkCcRolesLabels = [APPLICANT_ROLE_ID=>_('Requester'), REFERRER_ROLE_ID=>_('Responder'), MODERATOR_ROLE_ID=>_('Moderator'), GUEST_ROLE_ID=>_('Guest')];
  731. //Set the clinical center list for all roles
  732. foreach($checkCcRoles as $roleId => $roleField) {
  733. $this->view->clinicalCentersPerRole[$roleId] = $clinicalCenters;
  734. }
  735. $this->view->medicalSpecialties = $this->db->orderBy('description', 'asc')->get('users_medical_specialties');
  736. $supportedRoles = $this->user->getRoles();
  737. $c = 0;
  738. foreach($supportedRoles as $roleId => $roleName) {
  739. $this->view->supportedRoles[$c]['id'] = $roleId;
  740. $this->view->supportedRoles[$c]['name'] = $roleName;
  741. $c++;
  742. }
  743. $this->view->status = -1; //Default selected "All"
  744. $searchData = $this->getPost('searchData');
  745. if (!is_null($searchData)) {
  746. parse_str($searchData, $parsedData);
  747. $data = $parsedData['data'];
  748. if (is_null($data)) {
  749. $data = $this->memoryCache->read('user:search:'.$this->user->getUserId());
  750. }
  751. }
  752. //For debugging
  753. $this->view->searchData = $data;
  754. $this->view->isSearch = false;
  755. $this->view->results = [];
  756. $this->view->resultCount = 0;
  757. $this->view->tableHasCcApplicant = false;
  758. $this->view->tableHasCcReferrer = false;
  759. $this->view->tableHasSpecialties = false;
  760. if (!is_null($data)) {
  761. $this->view->isSearch = true;
  762. $this->memoryCache->write('user:search:'.$this->user->getUserId(), $data, '+10 years');
  763. $this->view->currentPage = $this->getPost('pageNumb', 1);
  764. $this->view->orderField = $this->getPost('orderField', 'surname');
  765. $this->view->orderDir = $this->getPost('orderDir', 'desc');
  766. $fields[] = "COUNT(u.id) AS total_users";
  767. $fields = ['u.id', 'u.name', 'u.surname', 'u.updated_at', "(SELECT GROUP_CONCAT(GET_JSON_VALUE_BY_KEY(ur.name_translations, '".$this->user->getUserLang()."', '".$this->defLang."') SEPARATOR ', ') FROM users_roles_to rrt JOIN users_roles ur ON ur.id=rrt.role_id WHERE rrt.user_id=u.id ORDER BY ur.role_name) AS role_list"];
  768. if (isset($data['default_lang']) && $data['default_lang'] != '') {
  769. $this->db->where('u.language_default', $data['default_lang'], 'like');
  770. foreach($this->view->supportedLanguages as $index => $language) {
  771. $this->view->supportedLanguages[$index]['selected'] = $language['lang_code'] == $data['default_lang'] ? true : false;
  772. }
  773. }
  774. if (isset($data['country']) && $data['country'] != '') {
  775. $this->db->where('u.country_code', $data['country']);
  776. foreach($this->view->countries as $index => $country) {
  777. $this->view->countries[$index]['selected'] = $country['country_iso2_code'] == $data['country'] ? true : false;
  778. }
  779. }
  780. if (isset($data['status'])) {
  781. if ((int)$data['status'] > -1) {//-1 = Any
  782. $this->db->where('u.status', $data['status']);
  783. }
  784. $this->view->status = (int)$data['status'];
  785. }
  786. if (isset($data['role']) && is_array($data['role']) && !empty($data['role'])) {
  787. $c = 0;
  788. foreach($supportedRoles as $roleId => $roleName) {
  789. $this->view->supportedRoles[$c]['checked'] = isset($data['role'][$roleId]) ? true : false;
  790. $c++;
  791. }
  792. $this->view->tableHasRoles = true;
  793. $roleList = implode(',', $data['role']);
  794. $fields[] = "(SELECT COUNT(*) FROM users_roles_to urt WHERE urt.user_id=u.id AND urt.role_id IN($roleList)) AS role_results";
  795. $this->db->having('role_results', 0, '>');
  796. }
  797. $this->view->tableHasCcColumn = [];
  798. $countCC = 0;
  799. foreach($checkCcRoles as $roleId => $fieldName) {
  800. if (isset($data['role'][$roleId])) {
  801. $this->view->tableHasCcColumn[$roleId] = true;
  802. $filterForCount = "";
  803. $filterForList = "";
  804. if (isset($data[$fieldName]) && is_array($data[$fieldName]) && !empty($data[$fieldName])) {
  805. $ccRoleList = implode(',', $data[$fieldName]);
  806. $filterForCount = "AND ucct.center_id IN($ccRoleList)";
  807. $filterForList = "AND cc.id IN($ccRoleList)";
  808. foreach($this->view->clinicalCentersPerRole[$roleId] as $index => $ccItem) {
  809. $this->view->clinicalCentersPerRole[$roleId][$index]['selected'] = in_array($ccItem['id'], $data[$fieldName]) ? true : false;
  810. }
  811. //Count how many clinical centers are in this role and filter by the centers id
  812. $fields[] = "(SELECT COUNT(*) FROM users_clinical_centers_to ucct WHERE ucct.user_id=u.id AND ucct.role_id=$roleId $filterForCount) AS ".$fieldName."_results";
  813. //Create the clinical center comma separated list
  814. $fields[] = "(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 $filterForList ORDER BY cc.description) AS ".$fieldName."_list";
  815. //If is the firs role, use having, if it isn't, use orHaving
  816. if ($countCC == 0) {
  817. $this->db->having($fieldName.'_results', 0, '>');
  818. } else {
  819. $this->db->orHaving($fieldName.'_results', 0, '>');
  820. }
  821. } else {
  822. //If there aren't clinical centers, just count how many centers are in this role
  823. $fields[] = "(SELECT COUNT(*) FROM users_clinical_centers_to ucct WHERE ucct.user_id=u.id AND ucct.role_id=$roleId $filterForCount) AS ".$fieldName."_results";
  824. //Create the clinical center comma separated list
  825. $fields[] = "(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=$roleId $filterForList ORDER BY cc.description) AS ".$fieldName."_list";
  826. }
  827. $countCC++;
  828. } else {
  829. $this->view->tableHasCcColumn[$roleId] = false;
  830. }
  831. }
  832. if (isset($data['med_specialties']) && is_array($data['med_specialties']) && !empty($data['med_specialties'])) {
  833. $this->view->tableHasSpecialties = true;
  834. foreach($this->view->medicalSpecialties as $index => $specialtyItem) {
  835. $this->view->medicalSpecialties[$index]['selected'] = in_array($specialtyItem['id'], $data['med_specialties']) ? true : false;
  836. }
  837. $specialtyList = implode(',', $data['med_specialties']);
  838. $fields[] = "(SELECT COUNT(*) FROM users_medical_specialties_to umst WHERE umst.user_id=u.id AND umst.specialty_id IN($specialtyList)) AS specialty_result";
  839. $fields[] = "(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 specialty_list";
  840. $this->db->having('specialty_result', 0, '>');
  841. }
  842. $this->db->where('u.group_id', $this->userGroupId);
  843. $this->view->results = $this->db->orderBy('u.surname', 'asc')->paginate('users u', $this->view->currentPage, $fields);
  844. $this->setPagination($this->db, $this->db->totalCount, $this->view->currentPage, 'users-search/'.time().'/'.$this->view->orderField.'/'.$this->view->orderDir);
  845. //$this->view->totalResults = $resultsTotal;
  846. //$this->view->queryDebug = $this->db->getLastQuery();
  847. }
  848. $this->actionTitle = _('Users : Search');
  849. $this->breadcrumbs = [['hash'=>'users/'.time().'/surname/desc/1', 'label'=>_('Users')], ['hash'=>null, 'label'=>$this->actionTitle]];
  850. return $this->setJsonView('usersSearch');
  851. }
  852. public function exportUsers() {
  853. if (!$this->user->isLogged()) {
  854. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  855. }
  856. if(!$this->checkPermissions([ADMIN_ROLE_ID])) {
  857. return $this->setRawJsonResponse('err', _('Permission denied.'));
  858. }
  859. $parsedData = null;
  860. $formData = $this->getPost('formData', null);
  861. parse_str($formData, $parsedData);
  862. $returnValues = [];
  863. $userNames = [];
  864. $exportedUsers = '';
  865. if (isset($parsedData['export_user_list'])) {
  866. foreach($parsedData['export_user_list'] as $userId) {
  867. $userInfo = $this->db
  868. ->where('u.id', $userId)
  869. ->where('urt.role_id', APPLICANT_ROLE_ID)
  870. ->join('users_roles_to urt', 'urt.user_id=u.id', 'INNER')
  871. ->getOne('users u', 'u.*');
  872. if (isset($userInfo['simple_viewer'])) unset($userInfo['simple_viewer']);
  873. if (is_array($userInfo) && !empty($userInfo)) {
  874. $returnValues['users'][$userId] = $userInfo;
  875. $userNames[] = $userInfo['surname'].' '.$userInfo['name'];
  876. $userCc = $this->db
  877. ->where('ucct.user_id', $userId)
  878. ->join('clinical_centers cc', 'cc.id=ucct.center_id', 'INNER')
  879. ->get('users_clinical_centers_to ucct', null, ['ucct.*']);
  880. if (is_array($userCc) && !empty($userCc)) {
  881. $returnValues['userCc'][$userId] = $userCc;
  882. }
  883. $userLangs = $this->db
  884. ->where('ult.user_id', $userId)
  885. ->get('users_languages_to ult');
  886. if (is_array($userLangs) && !empty($userLangs)) {
  887. $returnValues['userLangs'][$userId] = $userLangs;
  888. } else {
  889. $returnValues['userLangs'][$userId] = [];
  890. }
  891. //Set user's role
  892. $returnValues['userRole'][$userId] = ['user_id'=>$userId, 'role_id'=>APPLICANT_ROLE_ID];
  893. }
  894. }
  895. if (!empty($returnValues)) {
  896. $returnValues['cc'] = [];
  897. $returnValues['ccMs'] = [];
  898. $returnValues['ms'] = [];
  899. $clinicalCenter = $this->db->get('clinical_centers', NULL, ['id', 'group_id', 'country_id', 'country_code', 'continent_code', 'description', 'image', 'address', 'anonymize', 'lat', 'lng', 'notes']);
  900. if (is_array($clinicalCenter) && !empty($clinicalCenter)) {
  901. $returnValues['cc'] = $clinicalCenter;
  902. }
  903. $clinicalCenterMs = $this->db->get('clinical_center_medical_specialties_to');
  904. if (is_array($clinicalCenterMs) && !empty($clinicalCenterMs)) {
  905. $returnValues['ccMs'] = $clinicalCenterMs;
  906. }
  907. $medicalSpecialties = $this->db->get('users_medical_specialties');
  908. if (is_array($medicalSpecialties) && !empty($medicalSpecialties)) {
  909. foreach($medicalSpecialties as $index => $fieldValues) {
  910. unset($medicalSpecialties[$index]['sportello_type_id']);
  911. }
  912. $returnValues['ms'] = $medicalSpecialties;
  913. }
  914. $exportedUsers = implode(', ', $userNames);
  915. }
  916. if (!empty($returnValues)) {
  917. $tmpDir = DATA_TMP_DIR;
  918. $fileName = 'GHT-User-Export_'.date('YmdHis').'.ghtusr';
  919. $fileContent = gzcompress(json_encode($returnValues));
  920. $filePath = $tmpDir.$fileName;
  921. $ret = file_put_contents($filePath, $fileContent);
  922. if ($ret === false) {
  923. return $this->setRawJsonResponse('err', _('Unable to create the users file.'), [], ['log'=>$filePath]);
  924. } else {
  925. return $this->setRawJsonResponse('ok', '', ['log'=>$returnValues, 'dwnFileName'=>$fileName, 'dwnFilePath'=>$filePath]);
  926. }
  927. } else {
  928. return $this->setRawJsonResponse('err', _('Unable to export the selected users. Please check the users role.'));
  929. }
  930. } else {
  931. return $this->setRawJsonResponse('err', _('Please provide at least one user.'));
  932. }
  933. }
  934. public function searchClean() {
  935. if (!$this->user->isLogged()) {
  936. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  937. }
  938. if(!$this->checkPermissions([ADMIN_ROLE_ID])) {
  939. return $this->setRawJsonResponse('err', _('Permission denied.'));
  940. }
  941. $ret = $this->db->where('cache_key', 'user:search:'.$this->user->getUserId())->delete('cache_memory');
  942. return $this->setRawJsonResponse('ok', _('Search field successfully cleaned.'), ['log'=>$ret]);
  943. }
  944. public function getCCentersByCountries() {
  945. if (!$this->user->isLogged()) {
  946. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  947. }
  948. if(!$this->checkPermissions([ADMIN_ROLE_ID])) {
  949. return $this->setRawJsonResponse('err', _('Permission denied.'));
  950. }
  951. $ids = isset($_POST['ids']) ? $_POST['ids'] : null;
  952. $selectAll = []; //Selected "All in this continent"
  953. $selectCountries = []; //Selected some other countries
  954. if (!is_null($ids)) {
  955. if(is_array($ids)) {
  956. foreach($ids as $countryCode) {
  957. if (strpos($countryCode, '|') !== false) {
  958. $selectAll[] = "'".explode('|', $countryCode)[1]."'";
  959. } else {
  960. $selectCountries[] = "'".$countryCode."'";
  961. }
  962. }
  963. //Select all countries of these continents
  964. if (!empty($selectAll)) {
  965. $countryCodes = implode(',', $selectAll);
  966. $resultsAll = $this->db->where('continent_code IN('.$countryCodes.')')->get('clinical_centers', null, ['id']);
  967. }
  968. //Select all countries in this array
  969. if (!empty($selectCountries)) {
  970. $countryCodes = implode(',', $selectCountries);
  971. $resultsCountries = $this->db->where('country_code IN('.$countryCodes.')')->get('clinical_centers', null, ['id']);
  972. }
  973. //Merge and remove duplicates
  974. $allCcIds = [];
  975. if (is_array($resultsAll)) {
  976. foreach($resultsAll as $item) {
  977. $allCcIds[] = $item['id'];
  978. }
  979. }
  980. if (is_array($resultsCountries)) {
  981. foreach($resultsCountries as $item) {
  982. $allCcIds[] = $item['id'];
  983. }
  984. }
  985. $allIds = array_unique($allCcIds);
  986. return $this->setRawJsonResponse('ok', '', ['ids'=>$allCcIds]);
  987. }
  988. }
  989. //If the passed ids array is empty, clear the Clinical center list on the right side
  990. return $this->setRawJsonResponse('ok', '', ['ids'=>[]]);
  991. }
  992. //Users sessions action
  993. public function usersSessions() {
  994. if(!$this->checkPermissions([ADMIN_ROLE_ID])) {
  995. return $this->redirect('login', 'permissionDenied');
  996. }
  997. $userGroupId = $this->user->getUserField('userGroupId');
  998. $groupInfo = $this->db->where('id', $userGroupId)->getOne('users_groups');
  999. $this->view->groupName = isset($groupInfo['group_name']) ? $groupInfo['group_name'] : '';
  1000. $page = $this->getPost('pageNumb', 1);
  1001. $totalRows = $this->db
  1002. ->join('users u', 'u.id=s.user_id', 'INNER')
  1003. ->where('s.user_id', 0, '>')
  1004. ->where('u.group_id', $userGroupId)
  1005. ->getValue('sessions s', 'COUNT(*)');
  1006. $sessions = $this->db
  1007. ->join('users u', 'u.id=s.user_id', 'INNER')
  1008. ->where('s.user_id', 0, '>')
  1009. ->where('u.group_id', $userGroupId)
  1010. ->orderBy('s.session_updated_at', 'DESC')
  1011. ->paginate('sessions s', $page);
  1012. $this->setPagination($this->db, $totalRows, $page, 'users-sessions');
  1013. $this->view->sessions = $sessions;
  1014. $this->actionTitle = _('Users : Sessions');
  1015. $this->breadcrumbs = [['hash'=>null, 'label'=>$this->actionTitle]];
  1016. return $this->setJsonView('usersSessions');
  1017. }
  1018. //Users access logs action
  1019. public function usersAccessLogs() {
  1020. if(!$this->checkPermissions([ADMIN_ROLE_ID])) {
  1021. return $this->redirect('login', 'permissionDenied');
  1022. }
  1023. $userGroupId = $this->user->getUserField('userGroupId');
  1024. $groupInfo = $this->db->where('id', $userGroupId)->getOne('users_groups');
  1025. $this->view->groupName = isset($groupInfo['group_name']) ? $groupInfo['group_name'] : '';
  1026. $page = $this->getPost('pageNumb', 1);
  1027. $accesses = $this->db
  1028. ->join('users u', 'u.id=a.user_id', 'INNER')
  1029. ->where('a.user_id', 0, '>')
  1030. ->where('u.group_id', $userGroupId)
  1031. ->orderBy('a.created_at', 'DESC')
  1032. ->paginate('log_access a', $page, ['a.*', 'a.created_at AS access_date', 'u.id AS user_id', 'u.username', 'u.surname', 'u.name']);
  1033. $totalRows = $this->db
  1034. ->join('users u', 'u.id=a.user_id', 'INNER')
  1035. ->where('a.user_id', 0, '>')
  1036. ->where('u.group_id', $userGroupId)
  1037. ->getValue('log_access a', 'COUNT(*)');
  1038. $this->setPagination($this->db, $totalRows, $page, 'users-access-logs');
  1039. $this->view->accesses = $accesses;
  1040. $this->actionTitle = _('Users : Access logs');
  1041. $this->breadcrumbs = [['hash'=>null, 'label'=>$this->actionTitle]];
  1042. return $this->setJsonView('usersAccessLogs');
  1043. }
  1044. public function usersNotificationTracker() {
  1045. if(!$this->checkPermissions([ADMIN_ROLE_ID, MODERATOR_ROLE_ID])) {
  1046. return $this->redirect('login', 'permissionDenied');
  1047. }
  1048. $this->view->currentPage = $this->getPost('pageNumb', 1);
  1049. $this->view->notifType = $this->getPost('notifType', 'email');
  1050. //$this->view->orderField = $this->getPost('orderField', 'surname');
  1051. //$this->view->orderDir = $this->getPost('orderDir', 'desc');
  1052. $this->view->trackers = [];
  1053. $results = $this->db
  1054. ->where('u.group_id', $this->userGroupId)
  1055. ->where('el.notif_type', $this->view->notifType)
  1056. ->join('users u', 'u.id=el.user_id', 'INNER')
  1057. //->groupBy('el.id')
  1058. ->orderBy('el.created_at', 'desc')
  1059. ->paginate('log_notifications el', $this->view->currentPage, ['u.id user_id', 'u.name', 'u.surname', 'el.id mail_code', 'el.request_result', 'el.mail_to', 'el.mail_subject', 'el.mail_opened', 'el.mail_opened_at', 'el.phone_to', 'el.phone_msg', 'el.created_at']);
  1060. $this->setPagination($this->db, $this->db->totalCount, $this->view->currentPage, 'notification-tracker/'.time().'/'.$this->view->notifType);
  1061. $this->view->queryDebug = $this->db->getLastQuery();
  1062. $this->view->trackers = $results;
  1063. $this->actionTitle = _('Notification tracker');
  1064. $this->breadcrumbs = [['hash'=>null, 'label'=>$this->actionTitle]];
  1065. return $this->setJsonView('usersNotificationTracker');
  1066. }
  1067. public function allowAccess() {
  1068. if (!$this->user->isLogged()) {
  1069. return $this->redirect('login', 'index');
  1070. }
  1071. return false;
  1072. }
  1073. }