assign.php 13 KB

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