skill.lib.php 89 KB

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