assign.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\Skill;
  4. use Skill as SkillManager;
  5. /**
  6. * Page for assign skills to a user.
  7. *
  8. * @author: Jose Loguercio <jose.loguercio@beeznest.com>
  9. */
  10. require_once __DIR__.'/../inc/global.inc.php';
  11. $userId = isset($_REQUEST['user']) ? (int) $_REQUEST['user'] : 0;
  12. if (empty($userId)) {
  13. api_not_allowed(true);
  14. }
  15. SkillManager::isAllowed($userId);
  16. $user = api_get_user_entity($userId);
  17. if (!$user) {
  18. api_not_allowed(true);
  19. }
  20. $entityManager = Database::getManager();
  21. $skillManager = new SkillManager();
  22. $skillRepo = $entityManager->getRepository('ChamiloCoreBundle:Skill');
  23. $skillRelSkill = $entityManager->getRepository('ChamiloCoreBundle:SkillRelSkill');
  24. $skillLevelRepo = $entityManager->getRepository('ChamiloSkillBundle:Level');
  25. $skillUserRepo = $entityManager->getRepository('ChamiloCoreBundle:SkillRelUser');
  26. $skillLevels = api_get_configuration_value('skill_levels_names');
  27. $skillsOptions = ['' => get_lang('Select')];
  28. $acquiredLevel = ['' => get_lang('none')];
  29. $formDefaultValues = [];
  30. if (empty($skillLevels)) {
  31. $skills = $skillRepo->findBy([
  32. 'status' => Skill::STATUS_ENABLED,
  33. ]);
  34. /** @var Skill $skill */
  35. foreach ($skills as $skill) {
  36. $skillsOptions[$skill->getId()] = $skill->getName();
  37. }
  38. } else {
  39. // Get only root elements
  40. $skills = $skillManager->getChildren(1);
  41. foreach ($skills as $skill) {
  42. $skillsOptions[$skill['data']['id']] = $skill['data']['name'];
  43. }
  44. }
  45. $skillIdFromGet = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
  46. $currentValue = isset($_REQUEST['current_value']) ? (int) $_REQUEST['current_value'] : 0;
  47. $currentLevel = isset($_REQUEST['current']) ? (int) str_replace('sub_skill_id_', '', $_REQUEST['current']) : 0;
  48. $subSkillList = isset($_REQUEST['sub_skill_list']) ? explode(',', $_REQUEST['sub_skill_list']) : [];
  49. $subSkillList = array_unique($subSkillList);
  50. if (!empty($subSkillList)) {
  51. // Compare asked skill with current level
  52. $correctLevel = false;
  53. if (isset($subSkillList[$currentLevel]) && $subSkillList[$currentLevel] == $currentValue) {
  54. $correctLevel = true;
  55. }
  56. // Level is wrong probably user change the level. Fix the subSkillList array
  57. if (!$correctLevel) {
  58. $newSubSkillList = [];
  59. $counter = 0;
  60. foreach ($subSkillList as $subSkillId) {
  61. if ($counter == $currentLevel) {
  62. $subSkillId = $currentValue;
  63. }
  64. $newSubSkillList[$counter] = $subSkillId;
  65. if ($counter == $currentLevel) {
  66. break;
  67. }
  68. $counter++;
  69. }
  70. $subSkillList = $newSubSkillList;
  71. }
  72. }
  73. if (!empty($currentLevel)) {
  74. $level = $currentLevel + 1;
  75. if ($level < count($subSkillList)) {
  76. $remove = count($subSkillList) - $currentLevel;
  77. $newSubSkillList = array_slice($subSkillList, 0, count($subSkillList) - $level);
  78. $subSkillList = $newSubSkillList;
  79. }
  80. }
  81. $skillId = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : key($skillsOptions);
  82. $skill = $skillRepo->find($skillId);
  83. $profile = false;
  84. if ($skill) {
  85. $profile = $skill->getProfile();
  86. }
  87. if (!empty($subSkillList)) {
  88. $skillFromLastSkill = $skillRepo->find(end($subSkillList));
  89. if ($skillFromLastSkill) {
  90. $profile = $skillFromLastSkill->getProfile();
  91. }
  92. }
  93. if (!$profile) {
  94. $skillRelSkill = new SkillRelSkill();
  95. $parents = $skillRelSkill->getSkillParents($skillId);
  96. krsort($parents);
  97. foreach ($parents as $parent) {
  98. $skillParentId = $parent['skill_id'];
  99. $profile = $skillRepo->find($skillParentId)->getProfile();
  100. if ($profile) {
  101. break;
  102. }
  103. if (!$profile && $parent['parent_id'] == 0) {
  104. $profile = $skillLevelRepo->findAll();
  105. $profile = isset($profile[0]) ? $profile[0] : false;
  106. }
  107. }
  108. }
  109. if ($profile) {
  110. $profileId = $profile->getId();
  111. $levels = $skillLevelRepo->findBy([
  112. 'profile' => $profileId,
  113. ]);
  114. $profileLevels = [];
  115. foreach ($levels as $level) {
  116. $profileLevels[$level->getPosition()][$level->getId()] = $level->getName();
  117. }
  118. ksort($profileLevels); // Sort the array by Position.
  119. foreach ($profileLevels as $profileLevel) {
  120. $profileId = key($profileLevel);
  121. $acquiredLevel[$profileId] = $profileLevel[$profileId];
  122. }
  123. }
  124. $formDefaultValues = ['skill' => $skillId];
  125. $newSubSkillList = [];
  126. $disableList = [];
  127. $currentUrl = api_get_self().'?user='.$userId.'&current='.$currentLevel;
  128. $form = new FormValidator('assign_skill', 'POST', $currentUrl);
  129. $form->addHeader(get_lang('Assign skill'));
  130. $form->addText('user_name', get_lang('Username'), false);
  131. $levelName = get_lang('Skill');
  132. if (!empty($skillLevels)) {
  133. if (isset($skillLevels['levels'][1])) {
  134. $levelName = get_lang($skillLevels['levels'][1]);
  135. }
  136. }
  137. $form->addSelect('skill', $levelName, $skillsOptions, ['id' => 'skill']);
  138. if (!empty($skillIdFromGet)) {
  139. if (empty($subSkillList)) {
  140. $subSkillList[] = $skillIdFromGet;
  141. }
  142. $oldSkill = $skillRepo->find($skillIdFromGet);
  143. $counter = 0;
  144. foreach ($subSkillList as $subSkillId) {
  145. $children = $skillManager->getChildren($subSkillId);
  146. if (isset($subSkillList[$counter - 1])) {
  147. $oldSkill = $skillRepo->find($subSkillList[$counter]);
  148. }
  149. $skillsOptions = [];
  150. if ($oldSkill) {
  151. $skillsOptions = [$oldSkill->getId() => ' -- '.$oldSkill->getName()];
  152. }
  153. if ($counter < count($subSkillList) - 1) {
  154. $disableList[] = 'sub_skill_id_'.($counter + 1);
  155. }
  156. foreach ($children as $child) {
  157. $skillsOptions[$child['id']] = $child['data']['name'];
  158. }
  159. $levelName = get_lang('Sub-skill');
  160. if (!empty($skillLevels)) {
  161. if (isset($skillLevels['levels'][$counter + 2])) {
  162. $levelName = get_lang($skillLevels['levels'][$counter + 2]);
  163. }
  164. }
  165. $form->addSelect(
  166. 'sub_skill_id_'.($counter + 1),
  167. $levelName,
  168. $skillsOptions,
  169. [
  170. 'id' => 'sub_skill_id_'.($counter + 1),
  171. 'class' => 'sub_skill',
  172. ]
  173. );
  174. if (isset($subSkillList[$counter + 1])) {
  175. $nextSkill = $skillRepo->find($subSkillList[$counter + 1]);
  176. if ($nextSkill) {
  177. $formDefaultValues['sub_skill_id_'.($counter + 1)] = $nextSkill->getId();
  178. }
  179. }
  180. $newSubSkillList[] = $subSkillId;
  181. $counter++;
  182. }
  183. $subSkillList = $newSubSkillList;
  184. }
  185. $subSkillListToString = implode(',', $subSkillList);
  186. $currentUrl = api_get_self().'?user='.$userId.'&current='.$currentLevel.'&sub_skill_list='.$subSkillListToString;
  187. $form->addHidden('sub_skill_list', $subSkillListToString);
  188. $form->addHidden('user', $user->getId());
  189. $form->addHidden('id', $skillId);
  190. $form->addRule('skill', get_lang('Required field'), 'required');
  191. $showLevels = api_get_configuration_value('hide_skill_levels') === false;
  192. if ($showLevels) {
  193. $form->addSelect('acquired_level', get_lang('Level acquired'), $acquiredLevel);
  194. //$form->addRule('acquired_level', get_lang('Required field'), 'required');
  195. }
  196. $form->addTextarea('argumentation', get_lang('Argumentation'), ['rows' => 6]);
  197. $form->addRule('argumentation', get_lang('Required field'), 'required');
  198. $form->addRule(
  199. 'argumentation',
  200. sprintf(get_lang('This text should be at least %s characters long'), 10),
  201. 'mintext',
  202. 10
  203. );
  204. $form->applyFilter('argumentation', 'trim');
  205. $form->addButtonSave(get_lang('Save'));
  206. $form->setDefaults($formDefaultValues);
  207. if ($form->validate()) {
  208. $values = $form->exportValues();
  209. $skillToProcess = $values['id'];
  210. if (!empty($subSkillList)) {
  211. $counter = 1;
  212. foreach ($subSkillList as $subSkill) {
  213. if (isset($values["sub_skill_id_$counter"])) {
  214. $skillToProcess = $values["sub_skill_id_$counter"];
  215. }
  216. $counter++;
  217. }
  218. }
  219. $skill = $skillRepo->find($skillToProcess);
  220. if (!$skill) {
  221. Display::addFlash(
  222. Display::return_message(get_lang('Skill not found'), 'error')
  223. );
  224. header('Location: '.api_get_self().'?'.$currentUrl);
  225. exit;
  226. }
  227. if ($user->hasSkill($skill)) {
  228. Display::addFlash(
  229. Display::return_message(
  230. sprintf(
  231. get_lang('The user %s has already achieved the skill %s'),
  232. UserManager::formatUserFullName($user),
  233. $skill->getName()
  234. ),
  235. 'warning'
  236. )
  237. );
  238. header('Location: '.$currentUrl);
  239. exit;
  240. }
  241. $skillUser = $skillManager->addSkillToUserBadge(
  242. $user,
  243. $skill,
  244. $values['acquired_level'],
  245. $values['argumentation'],
  246. api_get_user_id()
  247. );
  248. // Send email depending of children_auto_threshold
  249. $skillRelSkill = new SkillRelSkill();
  250. $skillModel = new \Skill();
  251. $parents = $skillModel->getDirectParents($skillToProcess);
  252. $extraFieldValue = new ExtraFieldValue('skill');
  253. foreach ($parents as $parentInfo) {
  254. $parentId = $parentInfo['skill_id'];
  255. $parentData = $skillModel->get($parentId);
  256. $data = $extraFieldValue->get_values_by_handler_and_field_variable($parentId, 'children_auto_threshold');
  257. if (!empty($data) && !empty($data['value'])) {
  258. // Search X children
  259. $requiredSkills = $data['value'];
  260. $children = $skillRelSkill->getChildren($parentId);
  261. $counter = 0;
  262. foreach ($children as $child) {
  263. if ($skillModel->userHasSkill($userId, $child['id'])) {
  264. $counter++;
  265. }
  266. }
  267. if ($counter >= $requiredSkills) {
  268. $bossList = UserManager::getStudentBossList($userId);
  269. if (!empty($bossList)) {
  270. Display::addFlash(Display::return_message(get_lang('Message Sent')));
  271. $url = api_get_path(WEB_CODE_PATH).'badge/assign.php?user='.$userId.'&id='.$parentId;
  272. $link = Display::url($url, $url);
  273. $subject = get_lang('A student has obtained the number of sub-skills needed to validate the mother skill.');
  274. $message = sprintf(
  275. get_lang('Learner %s has enough sub-skill to get skill %s. To assign this skill it is possible to go here : %s'),
  276. UserManager::formatUserFullName($user),
  277. $parentData['name'],
  278. $link
  279. );
  280. foreach ($bossList as $boss) {
  281. MessageManager::send_message_simple(
  282. $boss['boss_id'],
  283. $subject,
  284. $message
  285. );
  286. }
  287. }
  288. break;
  289. }
  290. }
  291. }
  292. Display::addFlash(
  293. Display::return_message(
  294. sprintf(
  295. get_lang('The skill %s has been assigned to user %s'),
  296. $skill->getName(),
  297. UserManager::formatUserFullName($user)
  298. ),
  299. 'success'
  300. )
  301. );
  302. header('Location: '.api_get_path(WEB_PATH)."badge/{$skillUser->getId()}");
  303. exit;
  304. }
  305. $form->setDefaults(['user_name' => UserManager::formatUserFullName($user, true)]);
  306. $form->freeze(['user_name']);
  307. if (api_is_drh()) {
  308. $interbreadcrumb[] = [
  309. 'url' => api_get_path(WEB_CODE_PATH).'mySpace/index.php',
  310. "name" => get_lang('Reporting'),
  311. ];
  312. if ($user->getStatus() == COURSEMANAGER) {
  313. $interbreadcrumb[] = [
  314. "url" => api_get_path(WEB_CODE_PATH).'mySpace/teachers.php',
  315. 'name' => get_lang('Trainers'),
  316. ];
  317. } else {
  318. $interbreadcrumb[] = [
  319. "url" => api_get_path(WEB_CODE_PATH).'mySpace/student.php',
  320. 'name' => get_lang('My learners'),
  321. ];
  322. }
  323. $interbreadcrumb[] = [
  324. 'url' => api_get_path(WEB_CODE_PATH).'mySpace/myStudents.php?student='.$userId,
  325. 'name' => UserManager::formatUserFullName($user),
  326. ];
  327. } else {
  328. $interbreadcrumb[] = [
  329. 'url' => api_get_path(WEB_CODE_PATH).'admin/index.php',
  330. 'name' => get_lang('Administration'),
  331. ];
  332. $interbreadcrumb[] = [
  333. 'url' => api_get_path(WEB_CODE_PATH).'admin/user_list.php',
  334. 'name' => get_lang('User list'),
  335. ];
  336. $interbreadcrumb[] = [
  337. 'url' => api_get_path(WEB_CODE_PATH).'admin/user_information.php?user_id='.$userId,
  338. 'name' => UserManager::formatUserFullName($user),
  339. ];
  340. }
  341. $url = api_get_path(WEB_CODE_PATH).'badge/assign.php?user='.$userId;
  342. $disableSelect = '';
  343. if ($disableList) {
  344. foreach ($disableList as $name) {
  345. //$disableSelect .= "$('#".$name."').prop('disabled', true);";
  346. //$disableSelect .= "$('#".$name."').selectpicker('refresh');";
  347. }
  348. }
  349. $htmlHeadXtra[] = '<script>
  350. $(function() {
  351. $("#skill").on("change", function() {
  352. $(location).attr("href", "'.$url.'&id="+$(this).val());
  353. });
  354. $(".sub_skill").on("change", function() {
  355. $(location).attr("href", "'.$url.'&id='.$skillIdFromGet.'&current_value="+$(this).val()+"&current="+$(this).attr("id")+"&sub_skill_list='.$subSkillListToString.',"+$(this).val());
  356. });
  357. '.$disableSelect.'
  358. });
  359. </script>';
  360. $template = new Template(get_lang('Add skill'));
  361. $template->assign('content', $form->returnForm());
  362. $template->display_one_col_template();