skill.lib.php 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
  4. use Chamilo\CoreBundle\Entity\Skill as SkillEntity;
  5. use Chamilo\CoreBundle\Entity\SkillRelUser as SkillRelUserEntity;
  6. use Chamilo\SkillBundle\Entity\SkillRelCourse;
  7. use Chamilo\SkillBundle\Entity\SkillRelItem;
  8. use Chamilo\UserBundle\Entity\User;
  9. use Fhaculty\Graph\Graph;
  10. use Fhaculty\Graph\Vertex;
  11. /**
  12. * Class SkillProfile.
  13. *
  14. * @todo break the file in different classes
  15. *
  16. * @package chamilo.library
  17. */
  18. class SkillProfile extends Model
  19. {
  20. public $columns = ['id', 'name', 'description'];
  21. /**
  22. * Constructor.
  23. */
  24. public function __construct()
  25. {
  26. $this->table = Database::get_main_table(TABLE_MAIN_SKILL_PROFILE);
  27. $this->table_rel_profile = Database::get_main_table(TABLE_MAIN_SKILL_REL_PROFILE);
  28. }
  29. /**
  30. * @return array
  31. */
  32. public function getProfiles()
  33. {
  34. $sql = "SELECT * FROM $this->table p
  35. INNER JOIN $this->table_rel_profile sp
  36. ON (p.id = sp.profile_id) ";
  37. $result = Database::query($sql);
  38. $profiles = Database::store_result($result, 'ASSOC');
  39. return $profiles;
  40. }
  41. /**
  42. * This function is for editing profile info from profile_id.
  43. *
  44. * @param int $profileId
  45. * @param string $name
  46. * @param string $description
  47. *
  48. * @return bool
  49. */
  50. public function updateProfileInfo($profileId, $name, $description)
  51. {
  52. $profileId = (int) $profileId;
  53. if (empty($profileId)) {
  54. return false;
  55. }
  56. $name = Database::escape_string($name);
  57. $description = Database::escape_string($description);
  58. $sql = "UPDATE $this->table SET
  59. name = '$name',
  60. description = '$description'
  61. WHERE id = $profileId ";
  62. Database::query($sql);
  63. return true;
  64. }
  65. /**
  66. * Call the save method of the parent class and the SkillRelProfile object.
  67. *
  68. * @param array $params
  69. * @param bool $show_query Whether to show the query in parent save() method
  70. *
  71. * @return mixed Profile ID or false if incomplete params
  72. */
  73. public function save($params, $show_query = false)
  74. {
  75. if (!empty($params)) {
  76. $profile_id = parent::save($params, $show_query);
  77. if ($profile_id) {
  78. $skill_rel_profile = new SkillRelProfile();
  79. if (isset($params['skills'])) {
  80. foreach ($params['skills'] as $skill_id) {
  81. $attributes = [
  82. 'skill_id' => $skill_id,
  83. 'profile_id' => $profile_id,
  84. ];
  85. $skill_rel_profile->save($attributes);
  86. }
  87. }
  88. return $profile_id;
  89. }
  90. }
  91. return false;
  92. }
  93. /**
  94. * Delete a skill profile.
  95. *
  96. * @param int $id The skill profile id
  97. *
  98. * @return bool Whether delete a skill profile
  99. */
  100. public function delete($id)
  101. {
  102. Database::delete(
  103. $this->table_rel_profile,
  104. [
  105. 'profile_id' => $id,
  106. ]
  107. );
  108. return parent::delete($id);
  109. }
  110. }
  111. /**
  112. * Class SkillRelProfile.
  113. */
  114. class SkillRelProfile extends Model
  115. {
  116. public $columns = ['id', 'skill_id', 'profile_id'];
  117. /**
  118. * Constructor.
  119. */
  120. public function __construct()
  121. {
  122. $this->table = Database::get_main_table(TABLE_MAIN_SKILL_REL_PROFILE);
  123. $this->tableProfile = Database::get_main_table(TABLE_MAIN_SKILL_PROFILE);
  124. }
  125. /**
  126. * @param int $profileId
  127. *
  128. * @return array
  129. */
  130. public function getSkillsByProfile($profileId)
  131. {
  132. $profileId = (int) $profileId;
  133. $skills = $this->get_all(['where' => ['profile_id = ? ' => $profileId]]);
  134. $return = [];
  135. if (!empty($skills)) {
  136. foreach ($skills as $skill_data) {
  137. $return[] = $skill_data['skill_id'];
  138. }
  139. }
  140. return $return;
  141. }
  142. /**
  143. * This function is for getting profile info from profile_id.
  144. *
  145. * @param int $profileId
  146. *
  147. * @return array
  148. */
  149. public function getProfileInfo($profileId)
  150. {
  151. $profileId = (int) $profileId;
  152. $sql = "SELECT * FROM $this->table p
  153. INNER JOIN $this->tableProfile pr
  154. ON (pr.id = p.profile_id)
  155. WHERE p.profile_id = ".$profileId;
  156. $result = Database::query($sql);
  157. $profileData = Database::fetch_array($result, 'ASSOC');
  158. return $profileData;
  159. }
  160. }
  161. /**
  162. * Class SkillRelSkill.
  163. */
  164. class SkillRelSkill extends Model
  165. {
  166. public $columns = ['skill_id', 'parent_id', 'relation_type', 'level'];
  167. /**
  168. * Constructor.
  169. */
  170. public function __construct()
  171. {
  172. $this->table = Database::get_main_table(TABLE_MAIN_SKILL_REL_SKILL);
  173. $this->tableSkill = Database::get_main_table(TABLE_MAIN_SKILL);
  174. }
  175. /**
  176. * Gets an element.
  177. *
  178. * @param int $id
  179. *
  180. * @return array
  181. */
  182. public function getSkillInfo($id)
  183. {
  184. $id = (int) $id;
  185. if (empty($id)) {
  186. return [];
  187. }
  188. $result = Database::select(
  189. '*',
  190. $this->table,
  191. ['where' => ['skill_id = ?' => $id]],
  192. 'first'
  193. );
  194. return $result;
  195. }
  196. /**
  197. * @param int $skillId
  198. * @param bool $add_child_info
  199. *
  200. * @return array
  201. */
  202. public function getSkillParents($skillId, $add_child_info = true)
  203. {
  204. $skillId = (int) $skillId;
  205. $sql = 'SELECT child.* FROM '.$this->table.' child
  206. LEFT JOIN '.$this->table.' parent
  207. ON child.parent_id = parent.skill_id
  208. WHERE child.skill_id = '.$skillId.' ';
  209. $result = Database::query($sql);
  210. $skill = Database::store_result($result, 'ASSOC');
  211. $skill = isset($skill[0]) ? $skill[0] : null;
  212. $parents = [];
  213. if (!empty($skill)) {
  214. if ($skill['parent_id'] != null) {
  215. $parents = self::getSkillParents($skill['parent_id']);
  216. }
  217. if ($add_child_info) {
  218. $parents[] = $skill;
  219. }
  220. }
  221. return $parents;
  222. }
  223. /**
  224. * @param int $skillId
  225. *
  226. * @return array
  227. */
  228. public function getDirectParents($skillId)
  229. {
  230. $skillId = (int) $skillId;
  231. $sql = 'SELECT parent_id as skill_id
  232. FROM '.$this->table.'
  233. WHERE skill_id = '.$skillId;
  234. $result = Database::query($sql);
  235. $skill = Database::store_result($result, 'ASSOC');
  236. $skill = isset($skill[0]) ? $skill[0] : null;
  237. $parents = [];
  238. if (!empty($skill)) {
  239. $parents[] = $skill;
  240. }
  241. return $parents;
  242. }
  243. /**
  244. * @param int $skill_id
  245. * @param bool $load_user_data
  246. * @param bool $user_id
  247. *
  248. * @return array
  249. */
  250. public function getChildren(
  251. $skill_id,
  252. $load_user_data = false,
  253. $user_id = false,
  254. $order = ''
  255. ) {
  256. $skill_id = (int) $skill_id;
  257. $sql = 'SELECT parent.* FROM '.$this->tableSkill.' skill
  258. INNER JOIN '.$this->table.' parent
  259. ON parent.id = skill.id
  260. WHERE parent_id = '.$skill_id.'
  261. ORDER BY skill.name ASC';
  262. $result = Database::query($sql);
  263. $skills = Database::store_result($result, 'ASSOC');
  264. $skill_obj = new Skill();
  265. $skill_rel_user = new SkillRelUser();
  266. if ($load_user_data) {
  267. $passed_skills = $skill_rel_user->getUserSkills($user_id);
  268. $done_skills = [];
  269. foreach ($passed_skills as $done_skill) {
  270. $done_skills[] = $done_skill['skill_id'];
  271. }
  272. }
  273. if (!empty($skills)) {
  274. foreach ($skills as &$skill) {
  275. $skill['data'] = $skill_obj->get($skill['skill_id']);
  276. if (isset($skill['data']) && !empty($skill['data'])) {
  277. if (!empty($done_skills)) {
  278. $skill['data']['passed'] = 0;
  279. if (in_array($skill['skill_id'], $done_skills)) {
  280. $skill['data']['passed'] = 1;
  281. }
  282. }
  283. } else {
  284. $skill = null;
  285. }
  286. }
  287. }
  288. return $skills;
  289. }
  290. /**
  291. * @param array $params
  292. *
  293. * @return bool
  294. */
  295. public function updateBySkill($params)
  296. {
  297. $result = Database::update(
  298. $this->table,
  299. $params,
  300. ['skill_id = ? ' => $params['skill_id']]
  301. );
  302. if ($result) {
  303. return true;
  304. }
  305. return false;
  306. }
  307. /**
  308. * @param int $skill_id
  309. * @param int $parent_id
  310. *
  311. * @return bool
  312. */
  313. public function relationExists($skill_id, $parent_id)
  314. {
  315. $result = $this->find(
  316. 'all',
  317. [
  318. 'where' => [
  319. 'skill_id = ? AND parent_id = ?' => [
  320. $skill_id,
  321. $parent_id,
  322. ],
  323. ],
  324. ]
  325. );
  326. if (!empty($result)) {
  327. return true;
  328. }
  329. return false;
  330. }
  331. }
  332. /**
  333. * Class SkillRelGradebook.
  334. */
  335. class SkillRelGradebook extends Model
  336. {
  337. public $columns = ['id', 'gradebook_id', 'skill_id'];
  338. /**
  339. * SkillRelGradebook constructor.
  340. */
  341. public function __construct()
  342. {
  343. $this->table = Database::get_main_table(TABLE_MAIN_SKILL_REL_GRADEBOOK);
  344. }
  345. /**
  346. * @param int $gradebookId
  347. * @param int $skillId
  348. *
  349. * @return bool
  350. */
  351. public function existsGradeBookSkill($gradebookId, $skillId)
  352. {
  353. $result = $this->find(
  354. 'all',
  355. [
  356. 'where' => [
  357. 'gradebook_id = ? AND skill_id = ?' => [
  358. $gradebookId,
  359. $skillId,
  360. ],
  361. ],
  362. ]
  363. );
  364. if (!empty($result)) {
  365. return true;
  366. }
  367. return false;
  368. }
  369. /**
  370. * Gets an element.
  371. */
  372. public function getSkillInfo($skill_id, $gradebookId)
  373. {
  374. if (empty($skill_id)) {
  375. return [];
  376. }
  377. $result = Database::select(
  378. '*',
  379. $this->table,
  380. [
  381. 'where' => [
  382. 'skill_id = ? AND gradebook_id = ? ' => [
  383. $skill_id,
  384. $gradebookId,
  385. ],
  386. ],
  387. ],
  388. 'first'
  389. );
  390. return $result;
  391. }
  392. /**
  393. * @param int $skill_id
  394. * @param array $gradebook_list
  395. */
  396. public function updateGradeBookListBySkill($skill_id, $gradebook_list)
  397. {
  398. $original_gradebook_list = $this->find(
  399. 'all',
  400. ['where' => ['skill_id = ?' => [$skill_id]]]
  401. );
  402. $gradebooks_to_remove = [];
  403. $gradebooks_to_add = [];
  404. $original_gradebook_list_ids = [];
  405. if (!empty($original_gradebook_list)) {
  406. foreach ($original_gradebook_list as $gradebook) {
  407. if (!in_array($gradebook['gradebook_id'], $gradebook_list)) {
  408. $gradebooks_to_remove[] = $gradebook['id'];
  409. }
  410. }
  411. foreach ($original_gradebook_list as $gradebook_item) {
  412. $original_gradebook_list_ids[] = $gradebook_item['gradebook_id'];
  413. }
  414. }
  415. if (!empty($gradebook_list)) {
  416. foreach ($gradebook_list as $gradebook_id) {
  417. if (!in_array($gradebook_id, $original_gradebook_list_ids)) {
  418. $gradebooks_to_add[] = $gradebook_id;
  419. }
  420. }
  421. }
  422. if (!empty($gradebooks_to_remove)) {
  423. foreach ($gradebooks_to_remove as $id) {
  424. $this->delete($id);
  425. }
  426. }
  427. if (!empty($gradebooks_to_add)) {
  428. foreach ($gradebooks_to_add as $gradebook_id) {
  429. $attributes = [
  430. 'skill_id' => $skill_id,
  431. 'gradebook_id' => $gradebook_id,
  432. ];
  433. $this->save($attributes);
  434. }
  435. }
  436. }
  437. /**
  438. * @param array $params
  439. *
  440. * @return bool|void
  441. */
  442. public function updateBySkill($params)
  443. {
  444. $skillInfo = $this->existsGradeBookSkill(
  445. $params['gradebook_id'],
  446. $params['skill_id']
  447. );
  448. if ($skillInfo) {
  449. return;
  450. } else {
  451. $result = $this->save($params);
  452. }
  453. if ($result) {
  454. return true;
  455. }
  456. return false;
  457. }
  458. }
  459. /**
  460. * Class SkillRelUser.
  461. */
  462. class SkillRelUser extends Model
  463. {
  464. public $columns = [
  465. 'id',
  466. 'user_id',
  467. 'skill_id',
  468. 'acquired_skill_at',
  469. 'assigned_by',
  470. 'course_id',
  471. 'session_id',
  472. ];
  473. /**
  474. * Constructor.
  475. */
  476. public function __construct()
  477. {
  478. $this->table = Database::get_main_table(TABLE_MAIN_SKILL_REL_USER);
  479. }
  480. /**
  481. * @param array $skill_list
  482. *
  483. * @return array
  484. */
  485. public function getUserBySkills($skill_list)
  486. {
  487. $users = [];
  488. if (!empty($skill_list)) {
  489. $skill_list = array_map('intval', $skill_list);
  490. $skill_list = implode("', '", $skill_list);
  491. $sql = "SELECT user_id FROM {$this->table}
  492. WHERE skill_id IN ('$skill_list') ";
  493. $result = Database::query($sql);
  494. $users = Database::store_result($result, 'ASSOC');
  495. }
  496. return $users;
  497. }
  498. /**
  499. * Get the achieved skills for the user.
  500. *
  501. * @param int $userId
  502. * @param int $courseId Optional. The course id
  503. * @param int $sessionId Optional. The session id
  504. *
  505. * @return array The skill list. Otherwise return false
  506. */
  507. public function getUserSkills($userId, $courseId = 0, $sessionId = 0)
  508. {
  509. if (empty($userId)) {
  510. return [];
  511. }
  512. $courseId = (int) $courseId;
  513. $sessionId = $sessionId ? (int) $sessionId : null;
  514. $whereConditions = [
  515. 'user_id = ? ' => (int) $userId,
  516. ];
  517. if ($courseId > 0) {
  518. $whereConditions['AND course_id = ? '] = $courseId;
  519. $whereConditions['AND session_id = ?'] = $sessionId;
  520. }
  521. $result = Database::select(
  522. 'skill_id',
  523. $this->table,
  524. [
  525. 'where' => $whereConditions,
  526. ],
  527. 'all'
  528. );
  529. return $result;
  530. }
  531. /**
  532. * Get the relation data between user and skill.
  533. *
  534. * @param int $userId The user id
  535. * @param int $skillId The skill id
  536. * @param int $courseId Optional. The course id
  537. * @param int $sessionId Optional. The session id
  538. *
  539. * @return array The relation data. Otherwise return false
  540. */
  541. public function getByUserAndSkill($userId, $skillId, $courseId = 0, $sessionId = 0)
  542. {
  543. $sql = "SELECT * FROM {$this->table} WHERE user_id = %d AND skill_id = %d ";
  544. if ($courseId > 0) {
  545. $sql .= "AND course_id = %d ".api_get_session_condition($sessionId, true);
  546. }
  547. $sql = sprintf(
  548. $sql,
  549. $userId,
  550. $skillId,
  551. $courseId
  552. );
  553. $result = Database::query($sql);
  554. return Database::fetch_assoc($result);
  555. }
  556. /**
  557. * Get the URL for the issue.
  558. *
  559. * @param SkillRelUserEntity $skillIssue
  560. *
  561. * @return string
  562. */
  563. public static function getIssueUrl(SkillRelUserEntity $skillIssue)
  564. {
  565. return api_get_path(WEB_PATH)."badge/{$skillIssue->getId()}";
  566. }
  567. /**
  568. * Get the URL for the All issues page.
  569. *
  570. * @param SkillRelUserEntity $skillIssue
  571. *
  572. * @return string
  573. */
  574. public static function getIssueUrlAll(SkillRelUserEntity $skillIssue)
  575. {
  576. return api_get_path(WEB_PATH)."skill/{$skillIssue->getSkill()->getId()}/user/{$skillIssue->getUser()->getId()}";
  577. }
  578. /**
  579. * Get the URL for the assertion.
  580. *
  581. * @param SkillRelUserEntity $skillIssue
  582. *
  583. * @return string
  584. */
  585. public static function getAssertionUrl(SkillRelUserEntity $skillIssue)
  586. {
  587. $url = api_get_path(WEB_CODE_PATH).'badge/assertion.php?';
  588. $url .= http_build_query([
  589. 'user' => $skillIssue->getUser()->getId(),
  590. 'skill' => $skillIssue->getSkill()->getId(),
  591. 'course' => $skillIssue->getCourse() ? $skillIssue->getCourse()->getId() : 0,
  592. 'session' => $skillIssue->getSession() ? $skillIssue->getSession()->getId() : 0,
  593. ]);
  594. return $url;
  595. }
  596. }
  597. /**
  598. * Class Skill.
  599. */
  600. class Skill extends Model
  601. {
  602. public $columns = [
  603. 'id',
  604. 'name',
  605. 'description',
  606. 'access_url_id',
  607. 'updated_at',
  608. 'short_code',
  609. 'icon',
  610. 'criteria',
  611. ];
  612. public $required = ['name'];
  613. /** Array of colours by depth, for the coffee wheel. Each depth has 4 col */
  614. /*var $colours = array(
  615. 0 => array('#f9f0ab', '#ecc099', '#e098b0', '#ebe378'),
  616. 1 => array('#d5dda1', '#4a5072', '#8dae43', '#72659d'),
  617. 2 => array('#b28647', '#2e6093', '#393e64', '#1e8323'),
  618. 3 => array('#9f6652', '#9f6652', '#9f6652', '#9f6652'),
  619. 4 => array('#af643c', '#af643c', '#af643c', '#af643c'),
  620. 5 => array('#72659d', '#72659d', '#72659d', '#72659d'),
  621. 6 => array('#8a6e9e', '#8a6e9e', '#8a6e9e', '#8a6e9e'),
  622. 7 => array('#92538c', '#92538c', '#92538c', '#92538c'),
  623. 8 => array('#2e6093', '#2e6093', '#2e6093', '#2e6093'),
  624. 9 => array('#3a5988', '#3a5988', '#3a5988', '#3a5988'),
  625. 10 => array('#393e64', '#393e64', '#393e64', '#393e64'),
  626. );*/
  627. public function __construct()
  628. {
  629. $this->table = Database::get_main_table(TABLE_MAIN_SKILL);
  630. $this->table_user = Database::get_main_table(TABLE_MAIN_USER);
  631. $this->table_skill_rel_gradebook = Database::get_main_table(TABLE_MAIN_SKILL_REL_GRADEBOOK);
  632. $this->table_skill_rel_user = Database::get_main_table(TABLE_MAIN_SKILL_REL_USER);
  633. $this->table_course = Database::get_main_table(TABLE_MAIN_COURSE);
  634. $this->table_skill_rel_skill = Database::get_main_table(TABLE_MAIN_SKILL_REL_SKILL);
  635. $this->table_gradebook = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  636. $this->sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
  637. }
  638. /**
  639. * Gets an element.
  640. *
  641. * @param int $id
  642. *
  643. * @return array|mixed
  644. */
  645. public function get($id)
  646. {
  647. $result = parent::get($id);
  648. if (empty($result)) {
  649. return [];
  650. }
  651. $path = api_get_path(WEB_UPLOAD_PATH).'badges/';
  652. if (!empty($result['icon'])) {
  653. $iconSmall = sprintf(
  654. '%s-small.png',
  655. sha1($result['name'])
  656. );
  657. $iconBig = sprintf(
  658. '%s.png',
  659. sha1($result['name'])
  660. );
  661. $iconMini = $path.$iconSmall;
  662. $iconSmall = $path.$iconSmall;
  663. $iconBig = $path.$iconBig;
  664. } else {
  665. $iconMini = Display::returnIconPath('badges-default.png', ICON_SIZE_MEDIUM);
  666. $iconSmall = Display::returnIconPath('badges-default.png', ICON_SIZE_BIG);
  667. $iconBig = Display::returnIconPath('badges-default.png', ICON_SIZE_HUGE);
  668. }
  669. $result['icon_mini'] = $iconMini;
  670. $result['icon_small'] = $iconSmall;
  671. $result['icon_big'] = $iconBig;
  672. $result['img_mini'] = Display::img($iconBig, $result['name'], ['width' => ICON_SIZE_MEDIUM]);
  673. $result['img_big'] = Display::img($iconBig, $result['name']);
  674. $result['img_small'] = Display::img($iconSmall, $result['name']);
  675. $result['name'] = self::translateName($result['name']);
  676. $result['short_code'] = self::translateCode($result['short_code']);
  677. return $result;
  678. }
  679. /**
  680. * @param array $skills
  681. * @param string $imageSize mini|small|big
  682. * @param bool $addDivWrapper
  683. *
  684. * @return string
  685. */
  686. public function processSkillList($skills, $imageSize = '', $addDivWrapper = true)
  687. {
  688. if (empty($skills)) {
  689. return '';
  690. }
  691. if (empty($imageSize)) {
  692. $imageSize = 'img_small';
  693. } else {
  694. $imageSize = "img_$imageSize";
  695. }
  696. $html = '';
  697. if ($addDivWrapper) {
  698. $html = '<div class="scrollbar-inner badges-sidebar">';
  699. }
  700. $html .= '<ul class="list-unstyled list-badges">';
  701. foreach ($skills as $skill) {
  702. if (isset($skill['data'])) {
  703. $skill = $skill['data'];
  704. }
  705. $html .= '<li class="thumbnail">';
  706. $item = $skill[$imageSize];
  707. $item .= '<div class="caption">
  708. <p class="text-center">'.$skill['name'].'</p>
  709. </div>';
  710. if (isset($skill['url'])) {
  711. $html .= Display::url($item, $skill['url'], ['target' => '_blank']);
  712. } else {
  713. $html .= $item;
  714. }
  715. $html .= '</li>';
  716. }
  717. $html .= '</ul>';
  718. if ($addDivWrapper) {
  719. $html .= '</div>';
  720. }
  721. return $html;
  722. }
  723. /**
  724. * @param $skills
  725. * @param string $imageSize mini|small|big
  726. * @param string $style
  727. * @param bool $showBadge
  728. * @param bool $showTitle
  729. *
  730. * @return string
  731. */
  732. public function processSkillListSimple($skills, $imageSize = '', $style = '', $showBadge = true, $showTitle = true)
  733. {
  734. if (empty($skills)) {
  735. return '';
  736. }
  737. $isHierarchicalTable = api_get_configuration_value('table_of_hierarchical_skill_presentation');
  738. if (empty($imageSize)) {
  739. $imageSize = 'img_small';
  740. } else {
  741. $imageSize = "img_$imageSize";
  742. }
  743. $html = '';
  744. foreach ($skills as $skill) {
  745. if (isset($skill['data'])) {
  746. $skill = $skill['data'];
  747. }
  748. $item = '';
  749. if ($showBadge) {
  750. $item = '<div class="item">'.$skill[$imageSize].'</div>';
  751. }
  752. $name = '<div class="caption">'.$skill['name'].'</div>';
  753. if (!empty($skill['short_code'])) {
  754. $name = $skill['short_code'];
  755. }
  756. if (!$isHierarchicalTable) {
  757. //$item .= '<br />';
  758. }
  759. if ($showTitle) {
  760. $item .= $name;
  761. }
  762. if (isset($skill['url'])) {
  763. $html .= Display::url($item, $skill['url'], ['target' => '_blank', 'style' => $style]);
  764. } else {
  765. $html .= Display::url($item, '#', ['target' => '_blank', 'style' => $style]);
  766. }
  767. }
  768. return $html;
  769. }
  770. /**
  771. * @param int $id
  772. *
  773. * @return array
  774. */
  775. public function getSkillInfo($id)
  776. {
  777. $skillRelSkill = new SkillRelSkill();
  778. $skillInfo = $this->get($id);
  779. if (!empty($skillInfo)) {
  780. $skillInfo['extra'] = $skillRelSkill->getSkillInfo($id);
  781. $skillInfo['gradebooks'] = $this->getGradebooksBySkill($id);
  782. }
  783. return $skillInfo;
  784. }
  785. /**
  786. * @param array $skill_list
  787. *
  788. * @return array
  789. */
  790. public function getSkillsInfo($skill_list)
  791. {
  792. $skill_list = array_map('intval', $skill_list);
  793. $skill_list = implode("', '", $skill_list);
  794. $sql = "SELECT * FROM {$this->table}
  795. WHERE id IN ('$skill_list') ";
  796. $result = Database::query($sql);
  797. $skills = Database::store_result($result, 'ASSOC');
  798. foreach ($skills as &$skill) {
  799. if (!$skill['icon']) {
  800. continue;
  801. }
  802. $skill['icon_small'] = sprintf(
  803. 'badges/%s-small.png',
  804. sha1($skill['name'])
  805. );
  806. $skill['name'] = self::translateName($skill['name']);
  807. $skill['short_code'] = self::translateCode($skill['short_code']);
  808. }
  809. return $skills;
  810. }
  811. /**
  812. * @param bool $load_user_data
  813. * @param bool $user_id
  814. * @param int $id
  815. * @param int $parent_id
  816. *
  817. * @return array
  818. */
  819. public function get_all(
  820. $load_user_data = false,
  821. $user_id = false,
  822. $id = null,
  823. $parent_id = null
  824. ) {
  825. $id_condition = '';
  826. if (!empty($id)) {
  827. $id = (int) $id;
  828. $id_condition = " WHERE s.id = $id";
  829. }
  830. if (!empty($parent_id)) {
  831. $parent_id = (int) $parent_id;
  832. if (empty($id_condition)) {
  833. $id_condition = " WHERE ss.parent_id = $parent_id";
  834. } else {
  835. $id_condition = " AND ss.parent_id = $parent_id";
  836. }
  837. }
  838. $sql = "SELECT
  839. s.id,
  840. s.name,
  841. s.description,
  842. ss.parent_id,
  843. ss.relation_type,
  844. s.icon,
  845. s.short_code,
  846. s.status
  847. FROM {$this->table} s
  848. INNER JOIN {$this->table_skill_rel_skill} ss
  849. ON (s.id = ss.skill_id) $id_condition
  850. ORDER BY ss.id, ss.parent_id";
  851. $result = Database::query($sql);
  852. $skills = [];
  853. $webPath = api_get_path(WEB_UPLOAD_PATH);
  854. if (Database::num_rows($result)) {
  855. while ($row = Database::fetch_array($result, 'ASSOC')) {
  856. $skillInfo = self::get($row['id']);
  857. $row['img_mini'] = $skillInfo['img_mini'];
  858. $row['img_big'] = $skillInfo['img_big'];
  859. $row['img_small'] = $skillInfo['img_small'];
  860. $row['name'] = self::translateName($row['name']);
  861. $row['short_code'] = self::translateCode($row['short_code']);
  862. $skillRelSkill = new SkillRelSkill();
  863. $parents = $skillRelSkill->getSkillParents($row['id']);
  864. $row['level'] = count($parents) - 1;
  865. $row['gradebooks'] = $this->getGradebooksBySkill($row['id']);
  866. $skills[$row['id']] = $row;
  867. }
  868. }
  869. // Load all children of the parent_id
  870. if (!empty($skills) && !empty($parent_id)) {
  871. foreach ($skills as $skill) {
  872. $children = self::get_all($load_user_data, $user_id, $id, $skill['id']);
  873. if (!empty($children)) {
  874. //$skills = array_merge($skills, $children);
  875. $skills = $skills + $children;
  876. }
  877. }
  878. }
  879. return $skills;
  880. }
  881. /**
  882. * @param int $skill_id
  883. *
  884. * @return array|resource
  885. */
  886. public function getGradebooksBySkill($skill_id)
  887. {
  888. $skill_id = (int) $skill_id;
  889. $sql = "SELECT g.* FROM {$this->table_gradebook} g
  890. INNER JOIN {$this->table_skill_rel_gradebook} sg
  891. ON g.id = sg.gradebook_id
  892. WHERE sg.skill_id = $skill_id";
  893. $result = Database::query($sql);
  894. $result = Database::store_result($result, 'ASSOC');
  895. return $result;
  896. }
  897. /**
  898. * Get one level children.
  899. *
  900. * @param int $skill_id
  901. * @param bool $load_user_data
  902. *
  903. * @return array
  904. */
  905. public function getChildren($skill_id, $load_user_data = false)
  906. {
  907. $skillRelSkill = new SkillRelSkill();
  908. if ($load_user_data) {
  909. $user_id = api_get_user_id();
  910. $skills = $skillRelSkill->getChildren($skill_id, true, $user_id);
  911. } else {
  912. $skills = $skillRelSkill->getChildren($skill_id);
  913. }
  914. return $skills;
  915. }
  916. /**
  917. * Get all children of the current node (recursive).
  918. *
  919. * @param int $skillId
  920. *
  921. * @return array
  922. */
  923. public function getAllChildren($skillId)
  924. {
  925. $skillRelSkill = new SkillRelSkill();
  926. $children = $skillRelSkill->getChildren($skillId);
  927. foreach ($children as $child) {
  928. $subChildren = $this->getAllChildren($child['id']);
  929. }
  930. if (!empty($subChildren)) {
  931. $children = array_merge($children, $subChildren);
  932. }
  933. return $children;
  934. }
  935. /**
  936. * Gets all parents from from the wanted skill.
  937. */
  938. public function get_parents($skillId)
  939. {
  940. $skillRelSkill = new SkillRelSkill();
  941. $skills = $skillRelSkill->getSkillParents($skillId, true);
  942. foreach ($skills as &$skill) {
  943. $skill['data'] = $this->get($skill['skill_id']);
  944. }
  945. return $skills;
  946. }
  947. /**
  948. * All direct parents.
  949. *
  950. * @param int $skillId
  951. *
  952. * @return array
  953. */
  954. public function getDirectParents($skillId)
  955. {
  956. $skillRelSkill = new SkillRelSkill();
  957. $skills = $skillRelSkill->getDirectParents($skillId, true);
  958. if (!empty($skills)) {
  959. foreach ($skills as &$skill) {
  960. $skillData = $this->get($skill['skill_id']);
  961. if (empty($skillData)) {
  962. continue;
  963. }
  964. $skill['data'] = $skillData;
  965. $skill_info2 = $skillRelSkill->getSkillInfo($skill['skill_id']);
  966. $parentId = isset($skill_info2['parent_id']) ? isset($skill_info2['parent_id']) : 0;
  967. $skill['data']['parent_id'] = $parentId;
  968. }
  969. return $skills;
  970. }
  971. return [];
  972. }
  973. /**
  974. * Adds a new skill.
  975. *
  976. * @param array $params
  977. *
  978. * @return bool|null
  979. */
  980. public function add($params)
  981. {
  982. if (!isset($params['parent_id'])) {
  983. $params['parent_id'] = 1;
  984. }
  985. if (!is_array($params['parent_id'])) {
  986. $params['parent_id'] = [$params['parent_id']];
  987. }
  988. $skillRelSkill = new SkillRelSkill();
  989. $skillRelGradebook = new SkillRelGradebook();
  990. // Saving name, description
  991. $params['access_url_id'] = api_get_current_access_url_id();
  992. $params['icon'] = '';
  993. $skill_id = $this->save($params);
  994. if ($skill_id) {
  995. // Saving skill_rel_skill (parent_id, relation_type)
  996. foreach ($params['parent_id'] as $parent_id) {
  997. $relation_exists = $skillRelSkill->relationExists($skill_id, $parent_id);
  998. if (!$relation_exists) {
  999. $attributes = [
  1000. 'skill_id' => $skill_id,
  1001. 'parent_id' => $parent_id,
  1002. 'relation_type' => isset($params['relation_type']) ? $params['relation_type'] : 0,
  1003. 'level' => isset($params['level']) ? $params['level'] : 0,
  1004. ];
  1005. $skillRelSkill->save($attributes);
  1006. }
  1007. }
  1008. if (!empty($params['gradebook_id'])) {
  1009. foreach ($params['gradebook_id'] as $gradebook_id) {
  1010. $attributes = [];
  1011. $attributes['gradebook_id'] = $gradebook_id;
  1012. $attributes['skill_id'] = $skill_id;
  1013. $skillRelGradebook->save($attributes);
  1014. }
  1015. }
  1016. return $skill_id;
  1017. }
  1018. return null;
  1019. }
  1020. /**
  1021. * @param int $userId
  1022. * @param Category $category
  1023. * @param int $courseId
  1024. * @param int $sessionId
  1025. *
  1026. * @return bool
  1027. */
  1028. public function addSkillToUser(
  1029. $userId,
  1030. $category,
  1031. $courseId,
  1032. $sessionId
  1033. ) {
  1034. $skill_gradebook = new SkillRelGradebook();
  1035. $skill_rel_user = new SkillRelUser();
  1036. if (empty($category)) {
  1037. return false;
  1038. }
  1039. // Load subcategories
  1040. if (empty($category->get_parent_id())) {
  1041. $subCategories = $category->get_subcategories(
  1042. $userId,
  1043. $category->get_course_code(),
  1044. $category->get_session_id()
  1045. );
  1046. if (!empty($subCategories)) {
  1047. /** @var Category $subCategory */
  1048. foreach ($subCategories as $subCategory) {
  1049. $this->addSkillToUser($userId, $subCategory, $courseId, $sessionId);
  1050. }
  1051. }
  1052. }
  1053. $gradebookId = $category->get_id();
  1054. $skill_gradebooks = $skill_gradebook->get_all(['where' => ['gradebook_id = ?' => $gradebookId]]);
  1055. if (!empty($skill_gradebooks)) {
  1056. foreach ($skill_gradebooks as $skill_gradebook) {
  1057. $hasSkill = $this->userHasSkill(
  1058. $userId,
  1059. $skill_gradebook['skill_id'],
  1060. $courseId,
  1061. $sessionId
  1062. );
  1063. if (!$hasSkill) {
  1064. $params = [
  1065. 'user_id' => $userId,
  1066. 'skill_id' => $skill_gradebook['skill_id'],
  1067. 'acquired_skill_at' => api_get_utc_datetime(),
  1068. 'course_id' => (int) $courseId,
  1069. 'session_id' => $sessionId ? (int) $sessionId : null,
  1070. ];
  1071. $skill_rel_user->save($params);
  1072. }
  1073. }
  1074. }
  1075. return true;
  1076. }
  1077. /* Deletes a skill */
  1078. public function delete($skill_id)
  1079. {
  1080. /*$params = array('skill_id' => $skill_id);
  1081. $skillRelSkill = new SkillRelSkill();
  1082. $skills = $skillRelSkill->get_all(array('where'=>array('skill_id = ?' =>$skill_id)));
  1083. $skill_rel_profile = new SkillRelProfile();
  1084. $skillRelGradebook = new SkillRelGradebook();
  1085. $skill_rel_user = new SkillRelUser();
  1086. $this->delete($skill_id);
  1087. $skillRelGradebook->delete($params);*/
  1088. }
  1089. /**
  1090. * @param array $params
  1091. */
  1092. public function edit($params)
  1093. {
  1094. if (!isset($params['parent_id'])) {
  1095. $params['parent_id'] = 1;
  1096. }
  1097. $params['gradebook_id'] = isset($params['gradebook_id']) ? $params['gradebook_id'] : [];
  1098. $skillRelSkill = new SkillRelSkill();
  1099. $skillRelGradebook = new SkillRelGradebook();
  1100. // Saving name, description
  1101. $this->update($params);
  1102. $skillId = $params['id'];
  1103. if ($skillId) {
  1104. // Saving skill_rel_skill (parent_id, relation_type)
  1105. if (!is_array($params['parent_id'])) {
  1106. $params['parent_id'] = [$params['parent_id']];
  1107. }
  1108. // Cannot change parent of root
  1109. if ($skillId == 1) {
  1110. $params['parent_id'] = 0;
  1111. }
  1112. foreach ($params['parent_id'] as $parent_id) {
  1113. $relation_exists = $skillRelSkill->relationExists($skillId, $parent_id);
  1114. if (!$relation_exists) {
  1115. $attributes = [
  1116. 'skill_id' => $skillId,
  1117. 'parent_id' => $parent_id,
  1118. 'relation_type' => $params['relation_type'],
  1119. //'level' => $params['level'],
  1120. ];
  1121. $skillRelSkill->updateBySkill($attributes);
  1122. }
  1123. }
  1124. $skillRelGradebook->updateGradeBookListBySkill(
  1125. $skillId,
  1126. $params['gradebook_id']
  1127. );
  1128. return $skillId;
  1129. }
  1130. return null;
  1131. }
  1132. /**
  1133. * Get user's skills.
  1134. *
  1135. * @param int $userId
  1136. * @param bool $getSkillData
  1137. * @param int $courseId
  1138. * @param int $sessionId
  1139. *
  1140. * @return array
  1141. */
  1142. public function getUserSkills($userId, $getSkillData = false, $courseId = 0, $sessionId = 0)
  1143. {
  1144. $userId = (int) $userId;
  1145. $courseId = (int) $courseId;
  1146. $sessionId = (int) $sessionId;
  1147. $courseCondition = '';
  1148. if (!empty($courseId)) {
  1149. $courseCondition = " AND course_id = $courseId ";
  1150. }
  1151. $sessionCondition = '';
  1152. if (!empty($sessionId)) {
  1153. $sessionCondition = " AND course_id = $sessionId ";
  1154. }
  1155. $sql = 'SELECT DISTINCT
  1156. s.id,
  1157. s.name,
  1158. s.icon,
  1159. u.id as issue,
  1160. u.acquired_skill_at,
  1161. u.course_id
  1162. FROM '.$this->table_skill_rel_user.' u
  1163. INNER JOIN '.$this->table.' s
  1164. ON u.skill_id = s.id
  1165. WHERE
  1166. user_id = '.$userId.' '.$sessionCondition.' '.$courseCondition;
  1167. $result = Database::query($sql);
  1168. $skills = Database::store_result($result, 'ASSOC');
  1169. $skillList = [];
  1170. if (!empty($skills)) {
  1171. foreach ($skills as $skill) {
  1172. if ($getSkillData) {
  1173. $skillData = $this->get($skill['id']);
  1174. $skillData['url'] = api_get_path(WEB_PATH).'badge/'.$skill['id'].'/user/'.$userId;
  1175. $skillList[$skill['id']] = array_merge($skill, $skillData);
  1176. } else {
  1177. $skillList[$skill['id']] = $skill['id'];
  1178. }
  1179. }
  1180. }
  1181. return $skillList;
  1182. }
  1183. /**
  1184. * @param Vertex $vertex
  1185. * @param array $skills
  1186. * @param int $level
  1187. *
  1188. * @return string
  1189. */
  1190. public function processVertex(Vertex $vertex, $skills = [], $level = 0)
  1191. {
  1192. $isHierarchicalTable = api_get_configuration_value('table_of_hierarchical_skill_presentation');
  1193. $subTable = '';
  1194. if ($vertex->getVerticesEdgeTo()->count() > 0) {
  1195. if ($isHierarchicalTable) {
  1196. $subTable .= '<ul>';
  1197. }
  1198. foreach ($vertex->getVerticesEdgeTo() as $subVertex) {
  1199. $data = $subVertex->getAttribute('graphviz.data');
  1200. $passed = in_array($data['id'], array_keys($skills));
  1201. $transparency = '';
  1202. if ($passed === false) {
  1203. // @todo use css class
  1204. $transparency = 'opacity: 0.4; filter: alpha(opacity=40);';
  1205. }
  1206. if ($isHierarchicalTable) {
  1207. $label = $this->processSkillListSimple([$data], 'mini', $transparency);
  1208. $subTable .= '<li>'.$label;
  1209. $subTable .= $this->processVertex($subVertex, $skills, $level + 1);
  1210. $subTable .= '</li>';
  1211. } else {
  1212. $imageSize = 'mini';
  1213. if ($level == 2) {
  1214. $imageSize = 'small';
  1215. }
  1216. $showTitle = true;
  1217. if ($level > 2) {
  1218. $showTitle = false;
  1219. }
  1220. $label = $this->processSkillListSimple([$data], $imageSize, $transparency, true, $showTitle);
  1221. $subTable .= '<div class="thumbnail" style="float:left; margin-right:5px; ">';
  1222. $subTable .= '<div style="'.$transparency.'">';
  1223. $subTable .= '<div style="text-align: center">';
  1224. $subTable .= $label;
  1225. $subTable .= '</div>';
  1226. $subTable .= '</div>';
  1227. $subTable .= $this->processVertex($subVertex, $skills, $level + 1);
  1228. $subTable .= '</div>';
  1229. }
  1230. }
  1231. if ($isHierarchicalTable) {
  1232. $subTable .= '</ul>';
  1233. }
  1234. }
  1235. return $subTable;
  1236. }
  1237. /**
  1238. * @param int $userId
  1239. * @param int $courseId
  1240. * @param int $sessionId
  1241. * @param bool $addTitle
  1242. *
  1243. * @return array
  1244. */
  1245. public function getUserSkillsTable($userId, $courseId = 0, $sessionId = 0, $addTitle = true)
  1246. {
  1247. $skills = $this->getUserSkills($userId, true, $courseId, $sessionId);
  1248. $courseTempList = [];
  1249. $tableRows = [];
  1250. $skillParents = [];
  1251. foreach ($skills as $resultData) {
  1252. $parents = $this->get_parents($resultData['id']);
  1253. foreach ($parents as $parentData) {
  1254. $parentData['passed'] = in_array($parentData['id'], array_keys($skills));
  1255. if ($parentData['passed'] && isset($skills[$parentData['id']]['url'])) {
  1256. $parentData['data']['url'] = $skills[$parentData['id']]['url'];
  1257. }
  1258. $skillParents[$resultData['id']][$parentData['id']] = $parentData;
  1259. }
  1260. }
  1261. foreach ($skills as $resultData) {
  1262. $courseId = $resultData['course_id'];
  1263. if (!empty($courseId)) {
  1264. if (isset($courseTempList[$courseId])) {
  1265. $courseInfo = $courseTempList[$courseId];
  1266. } else {
  1267. $courseInfo = api_get_course_info_by_id($courseId);
  1268. $courseTempList[$courseId] = $courseInfo;
  1269. }
  1270. }
  1271. $tableRow = [
  1272. 'skill_badge' => $resultData['img_small'],
  1273. 'skill_name' => self::translateName($resultData['name']),
  1274. 'short_code' => $resultData['short_code'],
  1275. 'skill_url' => $resultData['url'],
  1276. 'achieved_at' => api_get_local_time($resultData['acquired_skill_at']),
  1277. 'course_image' => '',
  1278. 'course_name' => '',
  1279. ];
  1280. if (!empty($courseInfo)) {
  1281. $tableRow['course_image'] = $courseInfo['course_image'];
  1282. $tableRow['course_name'] = $courseInfo['title'];
  1283. }
  1284. $tableRows[] = $tableRow;
  1285. }
  1286. $isHierarchicalTable = api_get_configuration_value('table_of_hierarchical_skill_presentation');
  1287. $allowLevels = api_get_configuration_value('skill_levels_names');
  1288. $tableResult = '<div id="skillList">';
  1289. if ($isHierarchicalTable) {
  1290. $tableResult = '<div class="table-responsive">';
  1291. }
  1292. if ($addTitle) {
  1293. $tableResult .= '<h3 class="section-title">'.get_lang('Achieved skills').'</h3>
  1294. <div class="skills-badges">
  1295. ';
  1296. }
  1297. if (!empty($skillParents)) {
  1298. if (empty($allowLevels)) {
  1299. $tableResult .= $this->processSkillListSimple($skills);
  1300. } else {
  1301. $graph = new Graph();
  1302. $graph->setAttribute('graphviz.graph.rankdir', 'LR');
  1303. foreach ($skillParents as $skillId => $parentList) {
  1304. $old = null;
  1305. foreach ($parentList as $parent) {
  1306. if ($graph->hasVertex($parent['id'])) {
  1307. $current = $graph->getVertex($parent['id']);
  1308. } else {
  1309. $current = $graph->createVertex($parent['id']);
  1310. $current->setAttribute('graphviz.data', $parent['data']);
  1311. }
  1312. if (!empty($old)) {
  1313. if ($graph->hasVertex($old['id'])) {
  1314. $nextVertex = $graph->getVertex($old['id']);
  1315. } else {
  1316. $nextVertex = $graph->createVertex($old['id']);
  1317. $nextVertex->setAttribute('graphviz.data', $old['data']);
  1318. }
  1319. if (!$nextVertex->hasEdgeTo($current)) {
  1320. $nextVertex->createEdgeTo($current);
  1321. }
  1322. }
  1323. $old = $parent;
  1324. }
  1325. }
  1326. if ($isHierarchicalTable) {
  1327. $table = '<table class ="table table-bordered">';
  1328. // Getting "root" vertex
  1329. $root = $graph->getVertex(1);
  1330. $table .= '<tr>';
  1331. /** @var Vertex $vertex */
  1332. foreach ($root->getVerticesEdgeTo() as $vertex) {
  1333. $data = $vertex->getAttribute('graphviz.data');
  1334. $passed = in_array($data['id'], array_keys($skills));
  1335. $transparency = '';
  1336. if ($passed === false) {
  1337. // @todo use a css class
  1338. $transparency = 'opacity: 0.4; filter: alpha(opacity=40);';
  1339. }
  1340. $label = $this->processSkillListSimple([$data], 'mini', $transparency);
  1341. $table .= '<td >';
  1342. $table .= '<div class="skills_chart"> <ul><li>'.$label;
  1343. $table .= $this->processVertex($vertex, $skills);
  1344. $table .= '</ul></li></div>';
  1345. $table .= '</td>';
  1346. }
  1347. $table .= '</tr></table>';
  1348. } else {
  1349. // Getting "root" vertex
  1350. $root = $graph->getVertex(1);
  1351. $table = '';
  1352. /** @var Vertex $vertex */
  1353. foreach ($root->getVerticesEdgeTo() as $vertex) {
  1354. $data = $vertex->getAttribute('graphviz.data');
  1355. $passed = in_array($data['id'], array_keys($skills));
  1356. $transparency = '';
  1357. if ($passed === false) {
  1358. // @todo use a css class
  1359. $transparency = 'opacity: 0.4; filter: alpha(opacity=40);';
  1360. }
  1361. $label = $this->processSkillListSimple([$data], 'mini', $transparency, false);
  1362. $skillTable = $this->processVertex($vertex, $skills, 2);
  1363. $table .= "<h3>$label</h3>";
  1364. if (!empty($skillTable)) {
  1365. $table .= '<table class ="table table-bordered">';
  1366. $table .= '<tr>';
  1367. $table .= '<td>';
  1368. $table .= '<div>';
  1369. $table .= $skillTable;
  1370. $table .= '</div>';
  1371. $table .= '</td>';
  1372. $table .= '</tr></table>';
  1373. }
  1374. }
  1375. }
  1376. $tableResult .= $table;
  1377. }
  1378. } else {
  1379. $tableResult .= get_lang('WithoutAchieved skills');
  1380. }
  1381. if ($addTitle) {
  1382. $tableResult .= '</div>';
  1383. }
  1384. $tableResult .= '</div>';
  1385. return [
  1386. 'skills' => $tableRows,
  1387. 'table' => $tableResult,
  1388. ];
  1389. }
  1390. /**
  1391. * @param int $user_id
  1392. * @param int $skill_id
  1393. * @param bool $return_flat_array
  1394. * @param bool $add_root
  1395. *
  1396. * @return array|null
  1397. */
  1398. public function getSkillsTree(
  1399. $user_id = null,
  1400. $skill_id = null,
  1401. $return_flat_array = false,
  1402. $add_root = false
  1403. ) {
  1404. if ($skill_id == 1) {
  1405. $skill_id = 0;
  1406. }
  1407. if (isset($user_id) && !empty($user_id)) {
  1408. $skills = $this->get_all(true, $user_id, null, $skill_id);
  1409. } else {
  1410. $skills = $this->get_all(false, false, null, $skill_id);
  1411. }
  1412. $original_skill = $this->list = $skills;
  1413. // Show 1 item
  1414. if (!empty($skill_id)) {
  1415. if ($add_root) {
  1416. if (!empty($skill_id)) {
  1417. // Default root node
  1418. $skills[1] = [
  1419. 'id' => '1',
  1420. 'name' => get_lang('root'),
  1421. 'parent_id' => '0',
  1422. 'status' => 1,
  1423. ];
  1424. $skillInfo = $this->getSkillInfo($skill_id);
  1425. // 2nd node
  1426. $skills[$skill_id] = $skillInfo;
  1427. // Uncomment code below to hide the searched skill
  1428. $skills[$skill_id]['data']['parent_id'] = $skillInfo['extra']['parent_id'];
  1429. $skills[$skill_id]['parent_id'] = 1;
  1430. }
  1431. }
  1432. }
  1433. $refs = [];
  1434. $skills_tree = null;
  1435. // Create references for all nodes
  1436. $flat_array = [];
  1437. $family = [];
  1438. if (!empty($skills)) {
  1439. foreach ($skills as &$skill) {
  1440. if ($skill['parent_id'] == 0) {
  1441. $skill['parent_id'] = 'root';
  1442. }
  1443. // because except main keys (id, name, children) others keys
  1444. // are not saved while in the space tree
  1445. $skill['data'] = ['parent_id' => $skill['parent_id']];
  1446. // If a short code was defined, send the short code to replace
  1447. // skill name (to shorten the text in the wheel)
  1448. if (!empty($skill['short_code']) &&
  1449. api_get_setting('show_full_skill_name_on_skill_wheel') === 'false'
  1450. ) {
  1451. $skill['data']['short_code'] = $skill['short_code'];
  1452. }
  1453. $skill['data']['name'] = $skill['name'];
  1454. $skill['data']['status'] = $skill['status'];
  1455. // In order to paint all members of a family with the same color
  1456. if (empty($skill_id)) {
  1457. if ($skill['parent_id'] == 1) {
  1458. $family[$skill['id']] = $this->getAllChildren($skill['id']);
  1459. }
  1460. } else {
  1461. if ($skill['parent_id'] == $skill_id) {
  1462. $family[$skill['id']] = $this->getAllChildren($skill['id']);
  1463. }
  1464. /*if ($skill_id == $skill['id']) {
  1465. $skill['parent_id'] = 1;
  1466. }*/
  1467. }
  1468. if (!isset($skill['data']['real_parent_id'])) {
  1469. $skill['data']['real_parent_id'] = $skill['parent_id'];
  1470. }
  1471. // User achieved the skill (depends in the gradebook with certification)
  1472. $skill['data']['achieved'] = false;
  1473. if ($user_id) {
  1474. $skill['data']['achieved'] = $this->userHasSkill(
  1475. $user_id,
  1476. $skill['id']
  1477. );
  1478. }
  1479. // Check if the skill has related gradebooks
  1480. $skill['data']['skill_has_gradebook'] = false;
  1481. if (isset($skill['gradebooks']) && !empty($skill['gradebooks'])) {
  1482. $skill['data']['skill_has_gradebook'] = true;
  1483. }
  1484. $refs[$skill['id']] = &$skill;
  1485. $flat_array[$skill['id']] = &$skill;
  1486. }
  1487. // Checking family value
  1488. $family_id = 1;
  1489. $new_family_array = [];
  1490. foreach ($family as $main_family_id => $family_items) {
  1491. if (!empty($family_items)) {
  1492. foreach ($family_items as $item) {
  1493. $new_family_array[$item['id']] = $family_id;
  1494. }
  1495. }
  1496. $new_family_array[$main_family_id] = $family_id;
  1497. $family_id++;
  1498. }
  1499. if (empty($original_skill)) {
  1500. $refs['root']['children'][0] = $skills[1];
  1501. $skills[$skill_id]['data']['family_id'] = 1;
  1502. $refs['root']['children'][0]['children'][0] = $skills[$skill_id];
  1503. $flat_array[$skill_id] = $skills[$skill_id];
  1504. } else {
  1505. // Moving node to the children index of their parents
  1506. foreach ($skills as $my_skill_id => &$skill) {
  1507. if (isset($new_family_array[$skill['id']])) {
  1508. $skill['data']['family_id'] = $new_family_array[$skill['id']];
  1509. }
  1510. $refs[$skill['parent_id']]['children'][] = &$skill;
  1511. $flat_array[$my_skill_id] = $skill;
  1512. }
  1513. }
  1514. $skills_tree = [
  1515. 'name' => get_lang('SkillrootName'),
  1516. 'id' => 'root',
  1517. 'children' => $refs['root']['children'],
  1518. 'data' => [],
  1519. ];
  1520. }
  1521. if ($return_flat_array) {
  1522. return $flat_array;
  1523. }
  1524. unset($skills);
  1525. return $skills_tree;
  1526. }
  1527. /**
  1528. * Get skills tree as a simplified JSON structure.
  1529. *
  1530. * @param int user id
  1531. * @param int skill id
  1532. * @param bool return a flat array or not
  1533. * @param int depth of the skills
  1534. *
  1535. * @return string json
  1536. */
  1537. public function getSkillsTreeToJson(
  1538. $user_id = null,
  1539. $skill_id = null,
  1540. $return_flat_array = false,
  1541. $main_depth = 2
  1542. ) {
  1543. $tree = $this->getSkillsTree(
  1544. $user_id,
  1545. $skill_id,
  1546. $return_flat_array,
  1547. true
  1548. );
  1549. $simple_tree = [];
  1550. if (!empty($tree['children'])) {
  1551. foreach ($tree['children'] as $element) {
  1552. $children = [];
  1553. if (isset($element['children'])) {
  1554. $children = $this->getSkillToJson($element['children'], 1, $main_depth);
  1555. }
  1556. $simple_tree[] = [
  1557. 'name' => $element['name'],
  1558. 'children' => $children,
  1559. ];
  1560. }
  1561. }
  1562. return json_encode($simple_tree[0]['children']);
  1563. }
  1564. /**
  1565. * Get JSON element.
  1566. *
  1567. * @param array $subtree
  1568. * @param int $depth
  1569. * @param int $max_depth
  1570. *
  1571. * @return array|null
  1572. */
  1573. public function getSkillToJson($subtree, $depth = 1, $max_depth = 2)
  1574. {
  1575. $simple_sub_tree = [];
  1576. if (is_array($subtree)) {
  1577. $counter = 1;
  1578. foreach ($subtree as $elem) {
  1579. $tmp = [];
  1580. $tmp['name'] = $elem['name'];
  1581. $tmp['id'] = $elem['id'];
  1582. $tmp['isSearched'] = self::isSearched($elem['id']);
  1583. if (isset($elem['children']) && is_array($elem['children'])) {
  1584. $tmp['children'] = $this->getSkillToJson(
  1585. $elem['children'],
  1586. $depth + 1,
  1587. $max_depth
  1588. );
  1589. }
  1590. if ($depth > $max_depth) {
  1591. continue;
  1592. }
  1593. $tmp['depth'] = $depth;
  1594. $tmp['counter'] = $counter;
  1595. $counter++;
  1596. if (isset($elem['data']) && is_array($elem['data'])) {
  1597. foreach ($elem['data'] as $key => $item) {
  1598. $tmp[$key] = $item;
  1599. }
  1600. }
  1601. $simple_sub_tree[] = $tmp;
  1602. }
  1603. return $simple_sub_tree;
  1604. }
  1605. return null;
  1606. }
  1607. /**
  1608. * @param int $user_id
  1609. *
  1610. * @return bool
  1611. */
  1612. public function getUserSkillRanking($user_id)
  1613. {
  1614. $user_id = (int) $user_id;
  1615. $sql = "SELECT count(skill_id) count
  1616. FROM {$this->table} s
  1617. INNER JOIN {$this->table_skill_rel_user} su
  1618. ON (s.id = su.skill_id)
  1619. WHERE user_id = $user_id";
  1620. $result = Database::query($sql);
  1621. if (Database::num_rows($result)) {
  1622. $result = Database::fetch_row($result);
  1623. return $result[0];
  1624. }
  1625. return false;
  1626. }
  1627. /**
  1628. * @param $start
  1629. * @param $limit
  1630. * @param $sidx
  1631. * @param $sord
  1632. * @param $where_condition
  1633. *
  1634. * @return array
  1635. */
  1636. public function getUserListSkillRanking(
  1637. $start,
  1638. $limit,
  1639. $sidx,
  1640. $sord,
  1641. $where_condition
  1642. ) {
  1643. $start = (int) $start;
  1644. $limit = (int) $limit;
  1645. /* ORDER BY $sidx $sord */
  1646. $sql = "SELECT *, @rownum:=@rownum+1 rank FROM (
  1647. SELECT u.user_id, firstname, lastname, count(username) skills_acquired
  1648. FROM {$this->table} s INNER JOIN {$this->table_skill_rel_user} su ON (s.id = su.skill_id)
  1649. INNER JOIN {$this->table_user} u ON u.user_id = su.user_id, (SELECT @rownum:=0) r
  1650. WHERE 1=1 $where_condition
  1651. GROUP BY username
  1652. ORDER BY skills_acquired desc
  1653. LIMIT $start , $limit) AS T1, (SELECT @rownum:=0) r";
  1654. $result = Database::query($sql);
  1655. if (Database::num_rows($result)) {
  1656. return Database::store_result($result, 'ASSOC');
  1657. }
  1658. return [];
  1659. }
  1660. /**
  1661. * @return int
  1662. */
  1663. public function getUserListSkillRankingCount()
  1664. {
  1665. $sql = "SELECT count(*) FROM (
  1666. SELECT count(distinct 1)
  1667. FROM {$this->table} s
  1668. INNER JOIN {$this->table_skill_rel_user} su
  1669. ON (s.id = su.skill_id)
  1670. INNER JOIN {$this->table_user} u
  1671. ON u.user_id = su.user_id
  1672. GROUP BY username
  1673. ) as T1";
  1674. $result = Database::query($sql);
  1675. if (Database::num_rows($result)) {
  1676. $result = Database::fetch_row($result);
  1677. return $result[0];
  1678. }
  1679. return 0;
  1680. }
  1681. /**
  1682. * @param string $courseCode
  1683. *
  1684. * @return int
  1685. */
  1686. public function getCountSkillsByCourse($courseCode)
  1687. {
  1688. $courseCode = Database::escape_string($courseCode);
  1689. $sql = "SELECT count(skill_id) as count
  1690. FROM {$this->table_gradebook} g
  1691. INNER JOIN {$this->table_skill_rel_gradebook} sg
  1692. ON g.id = sg.gradebook_id
  1693. WHERE course_code = '$courseCode'";
  1694. $result = Database::query($sql);
  1695. if (Database::num_rows($result)) {
  1696. $result = Database::fetch_row($result);
  1697. return $result[0];
  1698. }
  1699. return 0;
  1700. }
  1701. /**
  1702. * @param int $skillId
  1703. *
  1704. * @return array
  1705. */
  1706. public function getCoursesBySkill($skillId)
  1707. {
  1708. $skillId = (int) $skillId;
  1709. $sql = "SELECT c.title, c.code
  1710. FROM {$this->table_gradebook} g
  1711. INNER JOIN {$this->table_skill_rel_gradebook} sg
  1712. ON g.id = sg.gradebook_id
  1713. INNER JOIN {$this->table_course} c
  1714. ON c.code = g.course_code
  1715. WHERE sg.skill_id = $skillId
  1716. AND (g.session_id IS NULL OR g.session_id = 0)";
  1717. $result = Database::query($sql);
  1718. return Database::store_result($result, 'ASSOC');
  1719. }
  1720. /**
  1721. * Check if the user has the skill.
  1722. *
  1723. * @param int $userId The user id
  1724. * @param int $skillId The skill id
  1725. * @param int $courseId Optional. The course id
  1726. * @param int $sessionId Optional. The session id
  1727. *
  1728. * @return bool Whether the user has the skill return true. Otherwise return false
  1729. */
  1730. public function userHasSkill($userId, $skillId, $courseId = 0, $sessionId = 0)
  1731. {
  1732. $courseId = (int) $courseId;
  1733. $sessionId = (int) $sessionId;
  1734. $whereConditions = [
  1735. 'user_id = ? ' => (int) $userId,
  1736. 'AND skill_id = ? ' => (int) $skillId,
  1737. ];
  1738. if ($courseId > 0) {
  1739. $whereConditions['AND course_id = ? '] = $courseId;
  1740. $whereConditions['AND session_id = ? '] = $sessionId ? $sessionId : null;
  1741. }
  1742. $result = Database::select(
  1743. 'COUNT(1) AS qty',
  1744. $this->table_skill_rel_user,
  1745. [
  1746. 'where' => $whereConditions,
  1747. ],
  1748. 'first'
  1749. );
  1750. if ($result != false) {
  1751. if ($result['qty'] > 0) {
  1752. return true;
  1753. }
  1754. }
  1755. return false;
  1756. }
  1757. /**
  1758. * Check if a skill is searched.
  1759. *
  1760. * @param int $id The skill id
  1761. *
  1762. * @return bool Whether el skill is searched return true. Otherwise return false
  1763. */
  1764. public static function isSearched($id)
  1765. {
  1766. $id = (int) $id;
  1767. if (empty($id)) {
  1768. return false;
  1769. }
  1770. $skillRelProfileTable = Database::get_main_table(TABLE_MAIN_SKILL_REL_PROFILE);
  1771. $result = Database::select(
  1772. 'COUNT( DISTINCT `skill_id`) AS qty',
  1773. $skillRelProfileTable,
  1774. [
  1775. 'where' => [
  1776. 'skill_id = ?' => $id,
  1777. ],
  1778. ],
  1779. 'first'
  1780. );
  1781. if ($result === false) {
  1782. return false;
  1783. }
  1784. if ($result['qty'] > 0) {
  1785. return true;
  1786. }
  1787. return false;
  1788. }
  1789. /**
  1790. * Get the achieved skills by course.
  1791. *
  1792. * @param int $courseId The course id
  1793. *
  1794. * @return array The skills list
  1795. */
  1796. public function listAchievedByCourse($courseId)
  1797. {
  1798. $courseId = (int) $courseId;
  1799. if ($courseId == 0) {
  1800. return [];
  1801. }
  1802. $list = [];
  1803. $sql = "SELECT
  1804. course.id c_id,
  1805. course.title c_name,
  1806. course.directory c_directory,
  1807. user.user_id,
  1808. user.lastname,
  1809. user.firstname,
  1810. user.username,
  1811. skill.id skill_id,
  1812. skill.name skill_name,
  1813. sru.acquired_skill_at
  1814. FROM {$this->table_skill_rel_user} AS sru
  1815. INNER JOIN {$this->table_course}
  1816. ON sru.course_id = course.id
  1817. INNER JOIN {$this->table_user}
  1818. ON sru.user_id = user.user_id
  1819. INNER JOIN {$this->table}
  1820. ON sru.skill_id = skill.id
  1821. WHERE course.id = $courseId";
  1822. $result = Database::query($sql);
  1823. while ($row = Database::fetch_assoc($result)) {
  1824. $row['skill_name'] = self::translateName($row['skill_name']);
  1825. $list[] = $row;
  1826. }
  1827. return $list;
  1828. }
  1829. /**
  1830. * Get the users list who achieved a skill.
  1831. *
  1832. * @param int $skillId The skill id
  1833. *
  1834. * @return array The users list
  1835. */
  1836. public function listUsersWhoAchieved($skillId)
  1837. {
  1838. $skillId = (int) $skillId;
  1839. if ($skillId == 0) {
  1840. return [];
  1841. }
  1842. $list = [];
  1843. $sql = "SELECT
  1844. course.id c_id,
  1845. course.title c_name,
  1846. course.directory c_directory,
  1847. user.user_id,
  1848. user.lastname,
  1849. user.firstname,
  1850. user.username,
  1851. skill.id skill_id,
  1852. skill.name skill_name,
  1853. sru.acquired_skill_at
  1854. FROM {$this->table_skill_rel_user} AS sru
  1855. INNER JOIN {$this->table_course}
  1856. ON sru.course_id = course.id
  1857. INNER JOIN {$this->table_user}
  1858. ON sru.user_id = user.user_id
  1859. INNER JOIN {$this->table}
  1860. ON sru.skill_id = skill.id
  1861. WHERE skill.id = $skillId ";
  1862. $result = Database::query($sql);
  1863. while ($row = Database::fetch_assoc($result)) {
  1864. $row['skill_name'] = self::translateName($row['skill_name']);
  1865. $list[] = $row;
  1866. }
  1867. return $list;
  1868. }
  1869. /**
  1870. * Get the session list where the user can achieve a skill.
  1871. *
  1872. * @param int $skillId The skill id
  1873. *
  1874. * @return array
  1875. */
  1876. public function getSessionsBySkill($skillId)
  1877. {
  1878. $skillId = (int) $skillId;
  1879. $sql = "SELECT s.id, s.name
  1880. FROM {$this->table_gradebook} g
  1881. INNER JOIN {$this->table_skill_rel_gradebook} sg
  1882. ON g.id = sg.gradebook_id
  1883. INNER JOIN {$this->sessionTable} s
  1884. ON g.session_id = s.id
  1885. WHERE sg.skill_id = $skillId
  1886. AND g.session_id > 0";
  1887. $result = Database::query($sql);
  1888. return Database::store_result($result, 'ASSOC');
  1889. }
  1890. /**
  1891. * Check if the $fromUser can comment the $toUser skill issue.
  1892. *
  1893. * @param User $fromUser
  1894. * @param User $toUser
  1895. *
  1896. * @return bool
  1897. */
  1898. public static function userCanAddFeedbackToUser($fromUser, $toUser)
  1899. {
  1900. if (api_is_platform_admin()) {
  1901. return true;
  1902. }
  1903. $userRepo = UserManager::getRepository();
  1904. $fromUserStatus = $fromUser->getStatus();
  1905. switch ($fromUserStatus) {
  1906. case SESSIONADMIN:
  1907. if (api_get_setting('allow_session_admins_to_manage_all_sessions') === 'true') {
  1908. if ($toUser->getCreatorId() === $fromUser->getId()) {
  1909. return true;
  1910. }
  1911. }
  1912. $sessionAdmins = $userRepo->getSessionAdmins($toUser);
  1913. foreach ($sessionAdmins as $sessionAdmin) {
  1914. if ($sessionAdmin->getId() !== $fromUser->getId()) {
  1915. continue;
  1916. }
  1917. return true;
  1918. }
  1919. break;
  1920. case STUDENT_BOSS:
  1921. $studentBosses = $userRepo->getStudentBosses($toUser);
  1922. foreach ($studentBosses as $studentBoss) {
  1923. if ($studentBoss->getId() !== $fromUser->getId()) {
  1924. continue;
  1925. }
  1926. return true;
  1927. }
  1928. break;
  1929. case DRH:
  1930. return UserManager::is_user_followed_by_drh(
  1931. $toUser->getId(),
  1932. $fromUser->getId()
  1933. );
  1934. }
  1935. return false;
  1936. }
  1937. /**
  1938. * If $studentId is set then check if current user has the right to see
  1939. * the page.
  1940. *
  1941. * @param int $studentId check if current user has access to see $studentId
  1942. * @param bool $blockPage raise a api_not_allowed()
  1943. *
  1944. * @return bool
  1945. */
  1946. public static function isAllowed($studentId = 0, $blockPage = true)
  1947. {
  1948. $allowHR = api_get_setting('allow_hr_skills_management') === 'true';
  1949. if (self::isToolAvailable()) {
  1950. if (api_is_platform_admin(false, $allowHR)) {
  1951. return true;
  1952. }
  1953. if (!empty($studentId)) {
  1954. $currentUserId = api_get_user_id();
  1955. if ((int) $currentUserId === (int) $studentId) {
  1956. return true;
  1957. }
  1958. $haveAccess = self::hasAccessToUserSkill(
  1959. $currentUserId,
  1960. $studentId
  1961. );
  1962. if ($haveAccess) {
  1963. return true;
  1964. }
  1965. }
  1966. }
  1967. if ($blockPage) {
  1968. api_not_allowed(true);
  1969. }
  1970. return false;
  1971. }
  1972. /**
  1973. * @return bool
  1974. */
  1975. public static function isToolAvailable()
  1976. {
  1977. $allowTool = api_get_setting('allow_skills_tool');
  1978. if ($allowTool === 'true') {
  1979. return true;
  1980. }
  1981. return false;
  1982. }
  1983. /**
  1984. * @param int $currentUserId
  1985. * @param int $studentId
  1986. *
  1987. * @return bool
  1988. */
  1989. public static function hasAccessToUserSkill($currentUserId, $studentId)
  1990. {
  1991. if (self::isToolAvailable()) {
  1992. if (api_is_platform_admin()) {
  1993. return true;
  1994. }
  1995. $currentUserId = (int) $currentUserId;
  1996. $studentId = (int) $studentId;
  1997. if ($currentUserId === $studentId) {
  1998. return true;
  1999. }
  2000. if (api_is_student_boss()) {
  2001. $isBoss = UserManager::userIsBossOfStudent($currentUserId, $studentId);
  2002. if ($isBoss) {
  2003. return true;
  2004. }
  2005. }
  2006. $allow = api_get_configuration_value('allow_private_skills');
  2007. if ($allow === true) {
  2008. if (api_is_teacher()) {
  2009. return UserManager::isTeacherOfStudent(
  2010. $currentUserId,
  2011. $studentId
  2012. );
  2013. }
  2014. if (api_is_drh()) {
  2015. return UserManager::is_user_followed_by_drh(
  2016. $studentId,
  2017. $currentUserId
  2018. );
  2019. }
  2020. }
  2021. }
  2022. return false;
  2023. }
  2024. /**
  2025. * Get skills.
  2026. *
  2027. * @param int $userId
  2028. * @param int level
  2029. *
  2030. * @return array
  2031. */
  2032. public function getStudentSkills($userId, $level = 0)
  2033. {
  2034. $userId = (int) $userId;
  2035. $sql = "SELECT s.id, s.name, sru.acquired_skill_at
  2036. FROM {$this->table} s
  2037. INNER JOIN {$this->table_skill_rel_user} sru
  2038. ON s.id = sru.skill_id
  2039. WHERE sru.user_id = $userId";
  2040. $result = Database::query($sql);
  2041. $skills = [];
  2042. foreach ($result as $item) {
  2043. if (empty($level)) {
  2044. $skills[] = [
  2045. 'name' => self::translateName($item['name']),
  2046. 'acquired_skill_at' => $item['acquired_skill_at'],
  2047. ];
  2048. } else {
  2049. $parents = self::get_parents($item['id']);
  2050. // +2 because it takes into account the root
  2051. if (count($parents) == $level + 1) {
  2052. $skills[] = [
  2053. 'name' => self::translateName($item['name']),
  2054. 'acquired_skill_at' => $item['acquired_skill_at'],
  2055. ];
  2056. }
  2057. }
  2058. }
  2059. return $skills;
  2060. }
  2061. /**
  2062. * @param string $name
  2063. *
  2064. * @return string
  2065. */
  2066. public static function translateName($name)
  2067. {
  2068. $variable = ChamiloApi::getLanguageVar($name, 'Skill');
  2069. return isset($GLOBALS[$variable]) ? $GLOBALS[$variable] : $name;
  2070. }
  2071. /**
  2072. * @param string $code
  2073. *
  2074. * @return mixed|string
  2075. */
  2076. public static function translateCode($code)
  2077. {
  2078. if (empty($code)) {
  2079. return '';
  2080. }
  2081. $variable = ChamiloApi::getLanguageVar($code, 'SkillCode');
  2082. return isset($GLOBALS[$variable]) ? $GLOBALS[$variable] : $code;
  2083. }
  2084. /**
  2085. * @param FormValidator $form
  2086. * @param array $skillInfo
  2087. *
  2088. * @return array
  2089. */
  2090. public function setForm(FormValidator &$form, $skillInfo = [])
  2091. {
  2092. $allSkills = $this->get_all();
  2093. $objGradebook = new Gradebook();
  2094. $isAlreadyRootSkill = false;
  2095. foreach ($allSkills as $checkedSkill) {
  2096. if (intval($checkedSkill['parent_id']) > 0) {
  2097. $isAlreadyRootSkill = true;
  2098. break;
  2099. }
  2100. }
  2101. $skillList = $isAlreadyRootSkill ? [] : [0 => get_lang('None')];
  2102. foreach ($allSkills as $skill) {
  2103. if (isset($skillInfo['id']) && $skill['id'] == $skillInfo['id']) {
  2104. continue;
  2105. }
  2106. $skillList[$skill['id']] = $skill['name'];
  2107. }
  2108. $allGradeBooks = $objGradebook->find('all');
  2109. // This procedure is for check if there is already a Skill with no Parent (Root by default)
  2110. $gradeBookList = [];
  2111. foreach ($allGradeBooks as $gradebook) {
  2112. $gradeBookList[$gradebook['id']] = $gradebook['name'];
  2113. }
  2114. $translateUrl = api_get_path(WEB_CODE_PATH).'admin/skill_translate.php?';
  2115. $translateNameButton = '';
  2116. $translateCodeButton = '';
  2117. $skillId = null;
  2118. if (!empty($skillInfo)) {
  2119. $skillId = $skillInfo['id'];
  2120. $translateNameUrl = $translateUrl.http_build_query(['skill' => $skillId, 'action' => 'name']);
  2121. $translateCodeUrl = $translateUrl.http_build_query(['skill' => $skillId, 'action' => 'code']);
  2122. $translateNameButton = Display::toolbarButton(
  2123. get_lang('Translate this term'),
  2124. $translateNameUrl,
  2125. 'language',
  2126. 'link'
  2127. );
  2128. $translateCodeButton = Display::toolbarButton(
  2129. get_lang('Translate this term'),
  2130. $translateCodeUrl,
  2131. 'language',
  2132. 'link'
  2133. );
  2134. }
  2135. $form->addText('name', [get_lang('Name'), $translateNameButton], true, ['id' => 'name']);
  2136. $form->addText('short_code', [get_lang('Short code'), $translateCodeButton], false, ['id' => 'short_code']);
  2137. // Cannot change parent of root
  2138. if ($skillId != 1) {
  2139. $form->addSelect('parent_id', get_lang('Parent'), $skillList, ['id' => 'parent_id']);
  2140. }
  2141. $form->addSelect(
  2142. 'gradebook_id',
  2143. [get_lang('Assessments'), get_lang('With Certificate')],
  2144. $gradeBookList,
  2145. ['id' => 'gradebook_id', 'multiple' => 'multiple', 'size' => 10]
  2146. );
  2147. $form->addTextarea('description', get_lang('Description'), ['id' => 'description', 'rows' => 7]);
  2148. $form->addTextarea('criteria', get_lang('Criteria to earn the badge'), ['id' => 'criteria', 'rows' => 7]);
  2149. // EXTRA FIELDS
  2150. $extraField = new ExtraField('skill');
  2151. $returnParams = $extraField->addElements($form, $skillId);
  2152. if (empty($skillInfo)) {
  2153. $form->addButtonCreate(get_lang('Add'));
  2154. } else {
  2155. $form->addButtonUpdate(get_lang('Update'));
  2156. $form->addHidden('id', $skillInfo['id']);
  2157. }
  2158. return $returnParams;
  2159. }
  2160. /**
  2161. * @return string
  2162. */
  2163. public function getToolBar()
  2164. {
  2165. $toolbar = Display::url(
  2166. Display::return_icon(
  2167. 'back.png',
  2168. get_lang('Manage skills'),
  2169. null,
  2170. ICON_SIZE_MEDIUM
  2171. ),
  2172. api_get_path(WEB_CODE_PATH).'admin/skill_list.php'
  2173. );
  2174. $actions = '<div class="actions">'.$toolbar.'</div>';
  2175. return $actions;
  2176. }
  2177. /**
  2178. * @param \Chamilo\SkillBundle\Entity\SkillRelItem $skillRelItem
  2179. * @param \Chamilo\SkillBundle\Entity\SkillRelItemRelUser $skillRelItemRelUser
  2180. * @param bool $addHeader
  2181. *
  2182. * @return string
  2183. */
  2184. public static function getUserSkillStatusLabel($skillRelItem, $skillRelItemRelUser, $addHeader = true)
  2185. {
  2186. if (empty($skillRelItem)) {
  2187. return '';
  2188. }
  2189. $type = 'success';
  2190. if (empty($skillRelItemRelUser)) {
  2191. $type = 'danger';
  2192. }
  2193. $label = '';
  2194. $skill = $skillRelItem->getSkill();
  2195. if ($addHeader) {
  2196. $label .= '<span id="'.$skill->getId().'" class="user_skill" style="cursor:pointer">';
  2197. }
  2198. $label .= Display::label($skill->getName(), $type);
  2199. if ($addHeader) {
  2200. $label .= '</span>&nbsp;';
  2201. }
  2202. return $label;
  2203. }
  2204. /**
  2205. * Assign a user with a SkilRelItem object.
  2206. *
  2207. * @param FormValidator $form
  2208. * @param int $typeId see ITEM_TYPE_* constants
  2209. * @param int $itemId
  2210. * @param int $userId
  2211. */
  2212. public static function addSkillsToUserForm(FormValidator $form, $typeId, $itemId, $userId, $resultId = 0, $addHeader = false)
  2213. {
  2214. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2215. if ($allowSkillInTools && !empty($typeId) && !empty($itemId) && !empty($userId)) {
  2216. $em = Database::getManager();
  2217. $items = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
  2218. ['itemId' => $itemId, 'itemType' => $typeId]
  2219. );
  2220. $skillRelUser = new SkillRelUser();
  2221. $skillUserList = $skillRelUser->getUserSkills($userId);
  2222. if (!empty($skillUserList)) {
  2223. $skillUserList = array_column($skillUserList, 'skill_id');
  2224. }
  2225. $skills = '';
  2226. /** @var SkillRelItem $skillRelItem */
  2227. foreach ($items as $skillRelItem) {
  2228. $criteria = [
  2229. 'user' => $userId,
  2230. 'skillRelItem' => $skillRelItem,
  2231. ];
  2232. $skillRelItemRelUser = $em->getRepository('ChamiloSkillBundle:SkillRelItemRelUser')->findOneBy($criteria);
  2233. $skills .= self::getUserSkillStatusLabel($skillRelItem, $skillRelItemRelUser);
  2234. }
  2235. if (!empty($skills)) {
  2236. $url = api_get_path(WEB_AJAX_PATH).'skill.ajax.php?a=update_skill_rel_user&'.api_get_cidreq();
  2237. $params = [
  2238. 'item_id' => $itemId,
  2239. 'type_id' => $typeId,
  2240. 'user_id' => $userId,
  2241. 'course_id' => api_get_course_int_id(),
  2242. 'session_id' => api_get_session_id(),
  2243. 'result_id' => $resultId,
  2244. ];
  2245. $params = json_encode($params);
  2246. if ($addHeader) {
  2247. $form->addHtml(Display::page_subheader2(get_lang('Skills')));
  2248. }
  2249. $html = '
  2250. <script>
  2251. $(function() {
  2252. $(".user_skill").on("click", function() {
  2253. var skillId = this.id;
  2254. var params = '.$params.';
  2255. $.ajax({
  2256. type: "GET",
  2257. async: false,
  2258. data: params,
  2259. url: "'.$url.'&skill_id="+skillId,
  2260. success: function(result) {
  2261. $("#" +skillId+ ".user_skill").html(result);
  2262. }
  2263. });
  2264. });
  2265. });
  2266. </script>
  2267. ';
  2268. $form->addHtml($html);
  2269. $form->addLabel(get_lang('Skills'), $skills);
  2270. if ($addHeader) {
  2271. $form->addHtml('<br />');
  2272. }
  2273. }
  2274. }
  2275. }
  2276. /**
  2277. * Add skills select ajax for an item (exercise, lp).
  2278. *
  2279. * @param FormValidator $form
  2280. * @param int $typeId see ITEM_TYPE_* constants
  2281. * @param int $itemId
  2282. *
  2283. * @throws Exception
  2284. *
  2285. * @return array
  2286. */
  2287. public static function addSkillsToForm(FormValidator $form, $typeId, $itemId = 0)
  2288. {
  2289. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2290. if (!$allowSkillInTools) {
  2291. return [];
  2292. }
  2293. $skillList = [];
  2294. if (!empty($itemId)) {
  2295. $em = Database::getManager();
  2296. $items = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
  2297. ['itemId' => $itemId, 'itemType' => $typeId]
  2298. );
  2299. /** @var SkillRelItem $skillRelItem */
  2300. foreach ($items as $skillRelItem) {
  2301. $skillList[$skillRelItem->getSkill()->getId()] = $skillRelItem->getSkill()->getName();
  2302. }
  2303. }
  2304. $courseId = api_get_course_int_id();
  2305. $sessionId = api_get_session_id();
  2306. $url = api_get_path(WEB_AJAX_PATH).
  2307. 'skill.ajax.php?a=search_skills_in_course&course_id='.$courseId.'&session_id='.$sessionId;
  2308. $form->addSelectAjax(
  2309. 'skills',
  2310. get_lang('Skills'),
  2311. $skillList,
  2312. [
  2313. 'url' => $url,
  2314. 'multiple' => 'multiple',
  2315. ]
  2316. );
  2317. return $skillList;
  2318. }
  2319. /**
  2320. * @param int $courseId
  2321. * @param int $sessionId
  2322. *
  2323. * @return array
  2324. */
  2325. public static function getSkillRelItemsPerCourse($courseId, $sessionId = null)
  2326. {
  2327. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2328. $skills = [];
  2329. if (empty($sessionId)) {
  2330. $sessionId = null;
  2331. }
  2332. if ($allowSkillInTools) {
  2333. $em = Database::getManager();
  2334. $skills = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
  2335. ['courseId' => $courseId, 'sessionId' => $sessionId]
  2336. );
  2337. }
  2338. return $skills;
  2339. }
  2340. /**
  2341. * @param int $itemId
  2342. * @param int $itemType
  2343. *
  2344. * @return array
  2345. */
  2346. public static function getItemInfo($itemId, $itemType)
  2347. {
  2348. $itemInfo = [];
  2349. $itemId = (int) $itemId;
  2350. $itemType = (int) $itemType;
  2351. $em = Database::getManager();
  2352. switch ($itemType) {
  2353. case ITEM_TYPE_EXERCISE:
  2354. /** @var \Chamilo\CourseBundle\Entity\CQuiz $item */
  2355. $item = $em->getRepository('ChamiloCourseBundle:CQuiz')->find($itemId);
  2356. if ($item) {
  2357. $itemInfo['name'] = $item->getTitle();
  2358. }
  2359. break;
  2360. case ITEM_TYPE_HOTPOTATOES:
  2361. break;
  2362. case ITEM_TYPE_LINK:
  2363. /** @var \Chamilo\CourseBundle\Entity\CLink $item */
  2364. $item = $em->getRepository('ChamiloCourseBundle:CLink')->find($itemId);
  2365. if ($item) {
  2366. $itemInfo['name'] = $item->getTitle();
  2367. }
  2368. break;
  2369. case ITEM_TYPE_LEARNPATH:
  2370. /** @var \Chamilo\CourseBundle\Entity\CLp $item */
  2371. $item = $em->getRepository('ChamiloCourseBundle:CLp')->find($itemId);
  2372. if ($item) {
  2373. $itemInfo['name'] = $item->getName();
  2374. }
  2375. break;
  2376. case ITEM_TYPE_GRADEBOOK:
  2377. break;
  2378. case ITEM_TYPE_STUDENT_PUBLICATION:
  2379. /** @var \Chamilo\CourseBundle\Entity\CStudentPublication $item */
  2380. $item = $em->getRepository('ChamiloCourseBundle:CStudentPublication')->find($itemId);
  2381. if ($item) {
  2382. $itemInfo['name'] = $item->getTitle();
  2383. }
  2384. break;
  2385. //ITEM_TYPE_FORUM', 7);
  2386. case ITEM_TYPE_ATTENDANCE:
  2387. /** @var \Chamilo\CourseBundle\Entity\CAttendance $item */
  2388. $item = $em->getRepository('ChamiloCourseBundle:CAttendance')->find($itemId);
  2389. if ($item) {
  2390. $itemInfo['name'] = $item->getName();
  2391. }
  2392. break;
  2393. case ITEM_TYPE_SURVEY:
  2394. /** @var \Chamilo\CourseBundle\Entity\CSurvey $item */
  2395. $item = $em->getRepository('ChamiloCourseBundle:CSurvey')->find($itemId);
  2396. if ($item) {
  2397. $itemInfo['name'] = strip_tags($item->getTitle());
  2398. }
  2399. break;
  2400. case ITEM_TYPE_FORUM_THREAD:
  2401. /** @var \Chamilo\CourseBundle\Entity\CForumThread $item */
  2402. $item = $em->getRepository('ChamiloCourseBundle:CForumThread')->find($itemId);
  2403. if ($item) {
  2404. $itemInfo['name'] = $item->getThreadTitle();
  2405. }
  2406. break;
  2407. }
  2408. return $itemInfo;
  2409. }
  2410. /**
  2411. * @param int $typeId
  2412. * @param int $itemId
  2413. *
  2414. * @return array
  2415. */
  2416. public static function getSkillRelItems($typeId, $itemId)
  2417. {
  2418. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2419. $skills = [];
  2420. if ($allowSkillInTools) {
  2421. $em = Database::getManager();
  2422. $skills = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
  2423. ['itemId' => $itemId, 'itemType' => $typeId]
  2424. );
  2425. }
  2426. return $skills;
  2427. }
  2428. /**
  2429. * @param int $typeId
  2430. * @param int $itemId
  2431. *
  2432. * @return string
  2433. */
  2434. public static function getSkillRelItemsToString($typeId, $itemId)
  2435. {
  2436. $skills = self::getSkillRelItems($typeId, $itemId);
  2437. $skillToString = '';
  2438. if (!empty($skills)) {
  2439. /** @var SkillRelItem $skillRelItem */
  2440. $skillList = [];
  2441. foreach ($skills as $skillRelItem) {
  2442. $skillList[] = Display::label($skillRelItem->getSkill()->getName(), 'success');
  2443. }
  2444. $skillToString = '&nbsp;'.implode(' ', $skillList);
  2445. }
  2446. return $skillToString;
  2447. }
  2448. /**
  2449. * @param int $itemId
  2450. * @param int $typeId
  2451. */
  2452. public static function deleteSkillsFromItem($itemId, $typeId)
  2453. {
  2454. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2455. if ($allowSkillInTools) {
  2456. $itemId = (int) $itemId;
  2457. $typeId = (int) $typeId;
  2458. $em = Database::getManager();
  2459. // Delete old ones
  2460. $items = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
  2461. ['itemId' => $itemId, 'itemType' => $typeId]
  2462. );
  2463. /** @var SkillRelItem $skillRelItem */
  2464. foreach ($items as $skillRelItem) {
  2465. $em->remove($skillRelItem);
  2466. }
  2467. $em->flush();
  2468. }
  2469. }
  2470. /**
  2471. * Relate skill with an item (exercise, gradebook, lp, etc).
  2472. *
  2473. * @param FormValidator $form
  2474. * @param int $typeId
  2475. * @param int $itemId
  2476. *
  2477. * @throws \Doctrine\ORM\OptimisticLockException
  2478. */
  2479. public static function saveSkills($form, $typeId, $itemId)
  2480. {
  2481. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2482. if ($allowSkillInTools) {
  2483. $userId = api_get_user_id();
  2484. $courseId = api_get_course_int_id();
  2485. if (empty($courseId)) {
  2486. $courseId = null;
  2487. }
  2488. $sessionId = api_get_session_id();
  2489. if (empty($sessionId)) {
  2490. $sessionId = null;
  2491. }
  2492. $em = Database::getManager();
  2493. $skills = (array) $form->getSubmitValue('skills');
  2494. // Delete old ones
  2495. $items = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
  2496. ['itemId' => $itemId, 'itemType' => $typeId]
  2497. );
  2498. if (!empty($items)) {
  2499. /** @var SkillRelItem $skillRelItem */
  2500. foreach ($items as $skillRelItem) {
  2501. if (!in_array($skillRelItem->getSkill()->getId(), $skills)) {
  2502. $em->remove($skillRelItem);
  2503. }
  2504. }
  2505. $em->flush();
  2506. }
  2507. // Add new one
  2508. if (!empty($skills)) {
  2509. foreach ($skills as $skillId) {
  2510. /** @var SkillEntity $skill */
  2511. $skill = $em->getRepository('ChamiloCoreBundle:Skill')->find($skillId);
  2512. if ($skill) {
  2513. if (!$skill->hasItem($typeId, $itemId)) {
  2514. $skillRelItem = new SkillRelItem();
  2515. $skillRelItem
  2516. ->setItemType($typeId)
  2517. ->setItemId($itemId)
  2518. ->setCourseId($courseId)
  2519. ->setSessionId($sessionId)
  2520. ->setCreatedBy($userId)
  2521. ->setUpdatedBy($userId)
  2522. ;
  2523. $skill->addItem($skillRelItem);
  2524. $em->persist($skill);
  2525. $em->flush();
  2526. }
  2527. }
  2528. }
  2529. }
  2530. }
  2531. }
  2532. /**
  2533. * Relate skill with an item (exercise, gradebook, lp, etc).
  2534. *
  2535. * @param FormValidator $form
  2536. *
  2537. * @return bool
  2538. */
  2539. public static function saveSkillsToCourseFromForm(FormValidator $form)
  2540. {
  2541. $skills = (array) $form->getSubmitValue('skills');
  2542. $courseId = (int) $form->getSubmitValue('course_id');
  2543. $sessionId = $form->getSubmitValue('session_id');
  2544. return self::saveSkillsToCourse($skills, $courseId, $sessionId);
  2545. }
  2546. /**
  2547. * @param array $skills
  2548. * @param int $courseId
  2549. * @param int $sessionId
  2550. *
  2551. * @throws \Doctrine\ORM\OptimisticLockException
  2552. *
  2553. * @return bool
  2554. */
  2555. public static function saveSkillsToCourse($skills, $courseId, $sessionId)
  2556. {
  2557. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2558. if (!$allowSkillInTools) {
  2559. return false;
  2560. }
  2561. $em = Database::getManager();
  2562. $sessionId = empty($sessionId) ? null : (int) $sessionId;
  2563. $course = api_get_course_entity($courseId);
  2564. if (empty($course)) {
  2565. return false;
  2566. }
  2567. $session = null;
  2568. if (!empty($sessionId)) {
  2569. $session = api_get_session_entity($sessionId);
  2570. $courseExistsInSession = SessionManager::sessionHasCourse($sessionId, $course->getCode());
  2571. if (!$courseExistsInSession) {
  2572. return false;
  2573. }
  2574. }
  2575. // Delete old ones
  2576. $items = $em->getRepository('ChamiloSkillBundle:SkillRelCourse')->findBy(
  2577. ['course' => $courseId, 'session' => $sessionId]
  2578. );
  2579. if (!empty($items)) {
  2580. /** @var SkillRelCourse $item */
  2581. foreach ($items as $item) {
  2582. if (!in_array($item->getSkill()->getId(), $skills)) {
  2583. $em->remove($item);
  2584. }
  2585. }
  2586. $em->flush();
  2587. }
  2588. // Add new one
  2589. if (!empty($skills)) {
  2590. foreach ($skills as $skillId) {
  2591. $item = new SkillRelCourse();
  2592. $item->setCourse($course);
  2593. $item->setSession($session);
  2594. /** @var SkillEntity $skill */
  2595. $skill = $em->getRepository('ChamiloCoreBundle:Skill')->find($skillId);
  2596. if ($skill) {
  2597. if (!$skill->hasCourseAndSession($item)) {
  2598. $skill->addToCourse($item);
  2599. $em->persist($skill);
  2600. }
  2601. }
  2602. }
  2603. $em->flush();
  2604. }
  2605. return true;
  2606. }
  2607. /**
  2608. * Get the icon (badge image) URL.
  2609. *
  2610. * @param SkillEntity $skill
  2611. * @param bool $getSmall Optional. Allow get the small image
  2612. *
  2613. * @return string
  2614. */
  2615. public static function getWebIconPath(SkillEntity $skill, $getSmall = false)
  2616. {
  2617. if ($getSmall) {
  2618. if (empty($skill->getIcon())) {
  2619. return \Display::return_icon('badges-default.png', null, null, ICON_SIZE_BIG, null, true);
  2620. }
  2621. return api_get_path(WEB_UPLOAD_PATH).'badges/'.sha1($skill->getName()).'-small.png';
  2622. }
  2623. if (empty($skill->getIcon())) {
  2624. return \Display::return_icon('badges-default.png', null, null, ICON_SIZE_HUGE, null, true);
  2625. }
  2626. return api_get_path(WEB_UPLOAD_PATH)."badges/{$skill->getIcon()}";
  2627. }
  2628. /**
  2629. * @param User $user
  2630. * @param \Chamilo\CoreBundle\Entity\Skill $skill
  2631. * @param int $levelId
  2632. * @param string $argumentation
  2633. * @param int $authorId
  2634. *
  2635. * @throws \Doctrine\ORM\OptimisticLockException
  2636. *
  2637. * @return SkillRelUserEntity
  2638. */
  2639. public function addSkillToUserBadge($user, $skill, $levelId, $argumentation, $authorId)
  2640. {
  2641. $showLevels = api_get_configuration_value('hide_skill_levels') === false;
  2642. $entityManager = Database::getManager();
  2643. $skillUserRepo = $entityManager->getRepository('ChamiloCoreBundle:SkillRelUser');
  2644. $criteria = ['user' => $user, 'skill' => $skill];
  2645. $result = $skillUserRepo->findOneBy($criteria);
  2646. if (!empty($result)) {
  2647. return false;
  2648. }
  2649. $skillLevelRepo = $entityManager->getRepository('ChamiloSkillBundle:Level');
  2650. $skillUser = new SkillRelUserEntity();
  2651. $skillUser->setUser($user);
  2652. $skillUser->setSkill($skill);
  2653. if ($showLevels && !empty($levelId)) {
  2654. $level = $skillLevelRepo->find($levelId);
  2655. $skillUser->setAcquiredLevel($level);
  2656. }
  2657. $skillUser->setArgumentation($argumentation);
  2658. $skillUser->setArgumentationAuthorId($authorId);
  2659. $skillUser->setAcquiredSkillAt(new DateTime());
  2660. $skillUser->setAssignedBy(0);
  2661. $entityManager->persist($skillUser);
  2662. $entityManager->flush();
  2663. return $skillUser;
  2664. }
  2665. }