skill.lib.php 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946
  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. $allowHR = api_get_setting('allow_hr_skills_management') === 'true';
  1926. if (self::isToolAvailable()) {
  1927. if (api_is_platform_admin(false, $allowHR)) {
  1928. return true;
  1929. }
  1930. if (!empty($studentId)) {
  1931. $currentUserId = api_get_user_id();
  1932. if ((int) $currentUserId === (int) $studentId) {
  1933. return true;
  1934. }
  1935. $haveAccess = self::hasAccessToUserSkill(
  1936. $currentUserId,
  1937. $studentId
  1938. );
  1939. if ($haveAccess) {
  1940. return true;
  1941. }
  1942. }
  1943. }
  1944. if ($blockPage) {
  1945. api_not_allowed(true);
  1946. }
  1947. return false;
  1948. }
  1949. /**
  1950. * @return bool
  1951. */
  1952. public static function isToolAvailable()
  1953. {
  1954. $allowTool = api_get_setting('allow_skills_tool');
  1955. if ($allowTool === 'true') {
  1956. return true;
  1957. }
  1958. return false;
  1959. }
  1960. /**
  1961. * @param $currentUserId
  1962. * @param $studentId
  1963. *
  1964. * @return bool
  1965. */
  1966. public static function hasAccessToUserSkill($currentUserId, $studentId)
  1967. {
  1968. if (self::isToolAvailable()) {
  1969. if (api_is_platform_admin()) {
  1970. return true;
  1971. }
  1972. if (api_is_student_boss()) {
  1973. $isBoss = UserManager::userIsBossOfStudent($currentUserId, $studentId);
  1974. if ($isBoss) {
  1975. return true;
  1976. }
  1977. }
  1978. $allow = api_get_configuration_value('allow_private_skills');
  1979. if ($allow === true) {
  1980. if (api_is_teacher()) {
  1981. return UserManager::isTeacherOfStudent(
  1982. $currentUserId,
  1983. $studentId
  1984. );
  1985. }
  1986. if (api_is_drh()) {
  1987. return UserManager::is_user_followed_by_drh(
  1988. $studentId,
  1989. $currentUserId
  1990. );
  1991. }
  1992. }
  1993. }
  1994. return false;
  1995. }
  1996. /**
  1997. * Get skills.
  1998. *
  1999. * @param int $userId
  2000. * @param int level
  2001. *
  2002. * @return array
  2003. */
  2004. public function getStudentSkills($userId, $level = 0)
  2005. {
  2006. $sql = "SELECT s.id, s.name, sru.acquired_skill_at
  2007. FROM {$this->table} s
  2008. INNER JOIN {$this->table_skill_rel_user} sru
  2009. ON s.id = sru.skill_id
  2010. WHERE sru.user_id = $userId";
  2011. $result = Database::query($sql);
  2012. $skills = [];
  2013. foreach ($result as $item) {
  2014. if (empty($level)) {
  2015. $skills[] = [
  2016. 'name' => self::translateName($item['name']),
  2017. 'acquired_skill_at' => $item['acquired_skill_at'],
  2018. ];
  2019. } else {
  2020. $parents = self::get_parents($item['id']);
  2021. // +2 because it takes into account the root
  2022. if (count($parents) == $level + 1) {
  2023. $skills[] = [
  2024. 'name' => self::translateName($item['name']),
  2025. 'acquired_skill_at' => $item['acquired_skill_at'],
  2026. ];
  2027. }
  2028. }
  2029. }
  2030. return $skills;
  2031. }
  2032. /**
  2033. * @param string $name
  2034. *
  2035. * @return string
  2036. */
  2037. public static function translateName($name)
  2038. {
  2039. $variable = ChamiloApi::getLanguageVar($name, 'Skill');
  2040. return isset($GLOBALS[$variable]) ? $GLOBALS[$variable] : $name;
  2041. }
  2042. /**
  2043. * @param string $code
  2044. *
  2045. * @return mixed|string
  2046. */
  2047. public static function translateCode($code)
  2048. {
  2049. if (empty($code)) {
  2050. return '';
  2051. }
  2052. $variable = ChamiloApi::getLanguageVar($code, 'SkillCode');
  2053. return isset($GLOBALS[$variable]) ? $GLOBALS[$variable] : $code;
  2054. }
  2055. /**
  2056. * @param FormValidator $form
  2057. * @param array $skillInfo
  2058. *
  2059. * @return array
  2060. */
  2061. public function setForm(FormValidator &$form, $skillInfo = [])
  2062. {
  2063. $allSkills = $this->get_all();
  2064. $objGradebook = new Gradebook();
  2065. $isAlreadyRootSkill = false;
  2066. foreach ($allSkills as $checkedSkill) {
  2067. if (intval($checkedSkill['parent_id']) > 0) {
  2068. $isAlreadyRootSkill = true;
  2069. break;
  2070. }
  2071. }
  2072. $skillList = $isAlreadyRootSkill ? [] : [0 => get_lang('None')];
  2073. foreach ($allSkills as $skill) {
  2074. if (isset($skillInfo['id']) && $skill['id'] == $skillInfo['id']) {
  2075. continue;
  2076. }
  2077. $skillList[$skill['id']] = $skill['name'];
  2078. }
  2079. $allGradeBooks = $objGradebook->find('all');
  2080. // This procedure is for check if there is already a Skill with no Parent (Root by default)
  2081. $gradeBookList = [];
  2082. foreach ($allGradeBooks as $gradebook) {
  2083. $gradeBookList[$gradebook['id']] = $gradebook['name'];
  2084. }
  2085. $translateUrl = api_get_path(WEB_CODE_PATH).'admin/skill_translate.php?';
  2086. $translateNameButton = '';
  2087. $translateCodeButton = '';
  2088. $skillId = null;
  2089. if (!empty($skillInfo)) {
  2090. $skillId = $skillInfo['id'];
  2091. $translateNameUrl = $translateUrl.http_build_query(['skill' => $skillId, 'action' => 'name']);
  2092. $translateCodeUrl = $translateUrl.http_build_query(['skill' => $skillId, 'action' => 'code']);
  2093. $translateNameButton = Display::toolbarButton(
  2094. get_lang('TranslateThisTerm'),
  2095. $translateNameUrl,
  2096. 'language',
  2097. 'link'
  2098. );
  2099. $translateCodeButton = Display::toolbarButton(
  2100. get_lang('TranslateThisTerm'),
  2101. $translateCodeUrl,
  2102. 'language',
  2103. 'link'
  2104. );
  2105. }
  2106. $form->addText('name', [get_lang('Name'), $translateNameButton], true, ['id' => 'name']);
  2107. $form->addText('short_code', [get_lang('ShortCode'), $translateCodeButton], false, ['id' => 'short_code']);
  2108. // Cannot change parent of root
  2109. if ($skillId != 1) {
  2110. $form->addSelect('parent_id', get_lang('Parent'), $skillList, ['id' => 'parent_id']);
  2111. }
  2112. $form->addSelect(
  2113. 'gradebook_id',
  2114. [get_lang('Gradebook'), get_lang('WithCertificate')],
  2115. $gradeBookList,
  2116. ['id' => 'gradebook_id', 'multiple' => 'multiple', 'size' => 10]
  2117. );
  2118. $form->addTextarea('description', get_lang('Description'), ['id' => 'description', 'rows' => 7]);
  2119. $form->addTextarea('criteria', get_lang('CriteriaToEarnTheBadge'), ['id' => 'criteria', 'rows' => 7]);
  2120. // EXTRA FIELDS
  2121. $extraField = new ExtraField('skill');
  2122. $returnParams = $extraField->addElements($form, $skillId);
  2123. if (empty($skillInfo)) {
  2124. $form->addButtonCreate(get_lang('Add'));
  2125. } else {
  2126. $form->addButtonUpdate(get_lang('Update'));
  2127. }
  2128. $form->addHidden('id', null);
  2129. return $returnParams;
  2130. }
  2131. /**
  2132. * @return string
  2133. */
  2134. public function getToolBar()
  2135. {
  2136. $toolbar = Display::url(
  2137. Display::return_icon(
  2138. 'back.png',
  2139. get_lang('ManageSkills'),
  2140. null,
  2141. ICON_SIZE_MEDIUM
  2142. ),
  2143. api_get_path(WEB_CODE_PATH).'admin/skill_list.php'
  2144. );
  2145. $actions = '<div class="actions">'.$toolbar.'</div>';
  2146. return $actions;
  2147. }
  2148. /**
  2149. * @param \Chamilo\SkillBundle\Entity\SkillRelItem $skillRelItem
  2150. * @param \Chamilo\SkillBundle\Entity\SkillRelItemRelUser $skillRelItemRelUser
  2151. * @param bool $addHeader
  2152. *
  2153. * @return string
  2154. */
  2155. public static function getUserSkillStatusLabel($skillRelItem, $skillRelItemRelUser, $addHeader = true)
  2156. {
  2157. if (empty($skillRelItem)) {
  2158. return '';
  2159. }
  2160. $type = 'success';
  2161. if (empty($skillRelItemRelUser)) {
  2162. $type = 'danger';
  2163. }
  2164. $label = '';
  2165. $skill = $skillRelItem->getSkill();
  2166. if ($addHeader) {
  2167. $label .= '<span id="'.$skill->getId().'" class="user_skill" style="cursor:pointer">';
  2168. }
  2169. $label .= Display::label($skill->getName(), $type);
  2170. if ($addHeader) {
  2171. $label .= '</span>&nbsp;';
  2172. }
  2173. return $label;
  2174. }
  2175. /**
  2176. * Assign a user with a SkilRelItem object.
  2177. *
  2178. * @param FormValidator $form
  2179. * @param int $typeId see ITEM_TYPE_* constants
  2180. * @param int $itemId
  2181. * @param int $userId
  2182. */
  2183. public static function addSkillsToUserForm(FormValidator $form, $typeId, $itemId, $userId, $resultId = 0, $addHeader = false)
  2184. {
  2185. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2186. if ($allowSkillInTools && !empty($typeId) && !empty($itemId) && !empty($userId)) {
  2187. $em = Database::getManager();
  2188. $items = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
  2189. ['itemId' => $itemId, 'itemType' => $typeId]
  2190. );
  2191. $skillRelUser = new SkillRelUser();
  2192. $skillUserList = $skillRelUser->getUserSkills($userId);
  2193. if (!empty($skillUserList)) {
  2194. $skillUserList = array_column($skillUserList, 'skill_id');
  2195. }
  2196. $skills = '';
  2197. /** @var SkillRelItem $skillRelItem */
  2198. foreach ($items as $skillRelItem) {
  2199. $criteria = [
  2200. 'user' => $userId,
  2201. 'skillRelItem' => $skillRelItem,
  2202. ];
  2203. $skillRelItemRelUser = $em->getRepository('ChamiloSkillBundle:SkillRelItemRelUser')->findOneBy($criteria);
  2204. $skills .= self::getUserSkillStatusLabel($skillRelItem, $skillRelItemRelUser);
  2205. }
  2206. if (!empty($skills)) {
  2207. $url = api_get_path(WEB_AJAX_PATH).'skill.ajax.php?a=update_skill_rel_user&'.api_get_cidreq();
  2208. $params = [
  2209. 'item_id' => $itemId,
  2210. 'type_id' => $typeId,
  2211. 'user_id' => $userId,
  2212. 'course_id' => api_get_course_int_id(),
  2213. 'session_id' => api_get_session_id(),
  2214. 'result_id' => $resultId,
  2215. ];
  2216. $params = json_encode($params);
  2217. if ($addHeader) {
  2218. $form->addHtml(Display::page_subheader2(get_lang('Skills')));
  2219. }
  2220. $html = '
  2221. <script>
  2222. $(function() {
  2223. $(".user_skill").on("click", function() {
  2224. var skillId = this.id;
  2225. var params = '.$params.';
  2226. $.ajax({
  2227. type: "GET",
  2228. async: false,
  2229. data: params,
  2230. url: "'.$url.'&skill_id="+skillId,
  2231. success: function(result) {
  2232. $("#" +skillId+ ".user_skill").html(result);
  2233. }
  2234. });
  2235. });
  2236. });
  2237. </script>
  2238. ';
  2239. $form->addHtml($html);
  2240. $form->addLabel(get_lang('Skills'), $skills);
  2241. if ($addHeader) {
  2242. $form->addHtml('<br />');
  2243. }
  2244. }
  2245. }
  2246. }
  2247. /**
  2248. * Add skills select ajax for an item (exercise, lp).
  2249. *
  2250. * @param FormValidator $form
  2251. * @param int $typeId see ITEM_TYPE_* constants
  2252. * @param int $itemId
  2253. *
  2254. * @throws Exception
  2255. *
  2256. * @return array
  2257. */
  2258. public static function addSkillsToForm(FormValidator $form, $typeId, $itemId = 0)
  2259. {
  2260. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2261. if (!$allowSkillInTools) {
  2262. return [];
  2263. }
  2264. $skillList = [];
  2265. if (!empty($itemId)) {
  2266. $em = Database::getManager();
  2267. $items = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
  2268. ['itemId' => $itemId, 'itemType' => $typeId]
  2269. );
  2270. /** @var SkillRelItem $skillRelItem */
  2271. foreach ($items as $skillRelItem) {
  2272. $skillList[$skillRelItem->getSkill()->getId()] = $skillRelItem->getSkill()->getName();
  2273. }
  2274. }
  2275. $courseId = api_get_course_int_id();
  2276. $sessionId = api_get_session_id();
  2277. $url = api_get_path(WEB_AJAX_PATH).
  2278. 'skill.ajax.php?a=search_skills_in_course&course_id='.$courseId.'&session_id='.$sessionId;
  2279. $form->addSelectAjax(
  2280. 'skills',
  2281. get_lang('Skills'),
  2282. $skillList,
  2283. [
  2284. 'url' => $url,
  2285. 'multiple' => 'multiple',
  2286. ]
  2287. );
  2288. return $skillList;
  2289. }
  2290. /**
  2291. * @param int $courseId
  2292. * @param int $sessionId
  2293. *
  2294. * @return array
  2295. */
  2296. public static function getSkillRelItemsPerCourse($courseId, $sessionId = null)
  2297. {
  2298. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2299. $skills = [];
  2300. if (empty($sessionId)) {
  2301. $sessionId = null;
  2302. }
  2303. if ($allowSkillInTools) {
  2304. $em = Database::getManager();
  2305. $skills = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
  2306. ['courseId' => $courseId, 'sessionId' => $sessionId]
  2307. );
  2308. }
  2309. return $skills;
  2310. }
  2311. /**
  2312. * @param int $itemId
  2313. * @param int $itemType
  2314. *
  2315. * @return array
  2316. */
  2317. public static function getItemInfo($itemId, $itemType)
  2318. {
  2319. $itemInfo = [];
  2320. $itemId = (int) $itemId;
  2321. $itemType = (int) $itemType;
  2322. $em = Database::getManager();
  2323. switch ($itemType) {
  2324. case ITEM_TYPE_EXERCISE:
  2325. /** @var \Chamilo\CourseBundle\Entity\CQuiz $item */
  2326. $item = $em->getRepository('ChamiloCourseBundle:CQuiz')->find($itemId);
  2327. if ($item) {
  2328. $itemInfo['name'] = $item->getTitle();
  2329. }
  2330. break;
  2331. case ITEM_TYPE_HOTPOTATOES:
  2332. break;
  2333. case ITEM_TYPE_LINK:
  2334. /** @var \Chamilo\CourseBundle\Entity\CLink $item */
  2335. $item = $em->getRepository('ChamiloCourseBundle:CLink')->find($itemId);
  2336. if ($item) {
  2337. $itemInfo['name'] = $item->getTitle();
  2338. }
  2339. break;
  2340. case ITEM_TYPE_LEARNPATH:
  2341. /** @var \Chamilo\CourseBundle\Entity\CLp $item */
  2342. $item = $em->getRepository('ChamiloCourseBundle:CLp')->find($itemId);
  2343. if ($item) {
  2344. $itemInfo['name'] = $item->getName();
  2345. }
  2346. break;
  2347. case ITEM_TYPE_GRADEBOOK:
  2348. break;
  2349. case ITEM_TYPE_STUDENT_PUBLICATION:
  2350. /** @var \Chamilo\CourseBundle\Entity\CStudentPublication $item */
  2351. $item = $em->getRepository('ChamiloCourseBundle:CStudentPublication')->find($itemId);
  2352. if ($item) {
  2353. $itemInfo['name'] = $item->getTitle();
  2354. }
  2355. break;
  2356. //ITEM_TYPE_FORUM', 7);
  2357. case ITEM_TYPE_ATTENDANCE:
  2358. /** @var \Chamilo\CourseBundle\Entity\CAttendance $item */
  2359. $item = $em->getRepository('ChamiloCourseBundle:CAttendance')->find($itemId);
  2360. if ($item) {
  2361. $itemInfo['name'] = $item->getName();
  2362. }
  2363. break;
  2364. case ITEM_TYPE_SURVEY:
  2365. /** @var \Chamilo\CourseBundle\Entity\CSurvey $item */
  2366. $item = $em->getRepository('ChamiloCourseBundle:CSurvey')->find($itemId);
  2367. if ($item) {
  2368. $itemInfo['name'] = strip_tags($item->getTitle());
  2369. }
  2370. break;
  2371. case ITEM_TYPE_FORUM_THREAD:
  2372. /** @var \Chamilo\CourseBundle\Entity\CForumThread $item */
  2373. $item = $em->getRepository('ChamiloCourseBundle:CForumThread')->find($itemId);
  2374. if ($item) {
  2375. $itemInfo['name'] = $item->getThreadTitle();
  2376. }
  2377. break;
  2378. }
  2379. return $itemInfo;
  2380. }
  2381. /**
  2382. * @param int $typeId
  2383. * @param int $itemId
  2384. *
  2385. * @return array
  2386. */
  2387. public static function getSkillRelItems($typeId, $itemId)
  2388. {
  2389. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2390. $skills = [];
  2391. if ($allowSkillInTools) {
  2392. $em = Database::getManager();
  2393. $skills = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
  2394. ['itemId' => $itemId, 'itemType' => $typeId]
  2395. );
  2396. }
  2397. return $skills;
  2398. }
  2399. /**
  2400. * @param int $typeId
  2401. * @param int $itemId
  2402. *
  2403. * @return string
  2404. */
  2405. public static function getSkillRelItemsToString($typeId, $itemId)
  2406. {
  2407. $skills = self::getSkillRelItems($typeId, $itemId);
  2408. $skillToString = '';
  2409. if (!empty($skills)) {
  2410. /** @var SkillRelItem $skillRelItem */
  2411. $skillList = [];
  2412. foreach ($skills as $skillRelItem) {
  2413. $skillList[] = Display::label($skillRelItem->getSkill()->getName(), 'success');
  2414. }
  2415. $skillToString = '&nbsp;'.implode(' ', $skillList);
  2416. }
  2417. return $skillToString;
  2418. }
  2419. /**
  2420. * @param int $itemId
  2421. * @param int $typeId
  2422. */
  2423. public static function deleteSkillsFromItem($itemId, $typeId)
  2424. {
  2425. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2426. if ($allowSkillInTools) {
  2427. $itemId = (int) $itemId;
  2428. $typeId = (int) $typeId;
  2429. $em = Database::getManager();
  2430. // Delete old ones
  2431. $items = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
  2432. ['itemId' => $itemId, 'itemType' => $typeId]
  2433. );
  2434. /** @var SkillRelItem $skillRelItem */
  2435. foreach ($items as $skillRelItem) {
  2436. $em->remove($skillRelItem);
  2437. }
  2438. $em->flush();
  2439. }
  2440. }
  2441. /**
  2442. * Relate skill with an item (exercise, gradebook, lp, etc).
  2443. *
  2444. * @param FormValidator $form
  2445. * @param int $typeId
  2446. * @param int $itemId
  2447. *
  2448. * @throws \Doctrine\ORM\OptimisticLockException
  2449. */
  2450. public static function saveSkills($form, $typeId, $itemId)
  2451. {
  2452. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2453. if ($allowSkillInTools) {
  2454. $userId = api_get_user_id();
  2455. $courseId = api_get_course_int_id();
  2456. if (empty($courseId)) {
  2457. $courseId = null;
  2458. }
  2459. $sessionId = api_get_session_id();
  2460. if (empty($sessionId)) {
  2461. $sessionId = null;
  2462. }
  2463. $em = Database::getManager();
  2464. $skills = (array) $form->getSubmitValue('skills');
  2465. // Delete old ones
  2466. $items = $em->getRepository('ChamiloSkillBundle:SkillRelItem')->findBy(
  2467. ['itemId' => $itemId, 'itemType' => $typeId]
  2468. );
  2469. if (!empty($items)) {
  2470. /** @var SkillRelItem $skillRelItem */
  2471. foreach ($items as $skillRelItem) {
  2472. if (!in_array($skillRelItem->getSkill()->getId(), $skills)) {
  2473. $em->remove($skillRelItem);
  2474. }
  2475. }
  2476. $em->flush();
  2477. }
  2478. // Add new one
  2479. if (!empty($skills)) {
  2480. foreach ($skills as $skillId) {
  2481. /** @var SkillEntity $skill */
  2482. $skill = $em->getRepository('ChamiloCoreBundle:Skill')->find($skillId);
  2483. if ($skill) {
  2484. if (!$skill->hasItem($typeId, $itemId)) {
  2485. $skillRelItem = new SkillRelItem();
  2486. $skillRelItem
  2487. ->setItemType($typeId)
  2488. ->setItemId($itemId)
  2489. ->setCourseId($courseId)
  2490. ->setSessionId($sessionId)
  2491. ->setCreatedBy($userId)
  2492. ->setUpdatedBy($userId)
  2493. ;
  2494. $skill->addItem($skillRelItem);
  2495. $em->persist($skill);
  2496. $em->flush();
  2497. }
  2498. }
  2499. }
  2500. }
  2501. }
  2502. }
  2503. /**
  2504. * Relate skill with an item (exercise, gradebook, lp, etc).
  2505. *
  2506. * @param FormValidator $form
  2507. *
  2508. * @return bool
  2509. */
  2510. public static function saveSkillsToCourseFromForm(FormValidator $form)
  2511. {
  2512. $skills = (array) $form->getSubmitValue('skills');
  2513. $courseId = (int) $form->getSubmitValue('course_id');
  2514. $sessionId = $form->getSubmitValue('session_id');
  2515. return self::saveSkillsToCourse($skills, $courseId, $sessionId);
  2516. }
  2517. /**
  2518. * @param array $skills
  2519. * @param int $courseId
  2520. * @param int $sessionId
  2521. *
  2522. * @throws \Doctrine\ORM\OptimisticLockException
  2523. *
  2524. * @return bool
  2525. */
  2526. public static function saveSkillsToCourse($skills, $courseId, $sessionId)
  2527. {
  2528. $allowSkillInTools = api_get_configuration_value('allow_skill_rel_items');
  2529. if (!$allowSkillInTools) {
  2530. return false;
  2531. }
  2532. $em = Database::getManager();
  2533. $sessionId = empty($sessionId) ? null : (int) $sessionId;
  2534. $course = api_get_course_entity($courseId);
  2535. if (empty($course)) {
  2536. return false;
  2537. }
  2538. $session = null;
  2539. if (!empty($sessionId)) {
  2540. $session = api_get_session_entity($sessionId);
  2541. $courseExistsInSession = SessionManager::sessionHasCourse($sessionId, $course->getCode());
  2542. if (!$courseExistsInSession) {
  2543. return false;
  2544. }
  2545. }
  2546. // Delete old ones
  2547. $items = $em->getRepository('ChamiloSkillBundle:SkillRelCourse')->findBy(
  2548. ['course' => $courseId, 'session' => $sessionId]
  2549. );
  2550. if (!empty($items)) {
  2551. /** @var SkillRelCourse $item */
  2552. foreach ($items as $item) {
  2553. if (!in_array($item->getSkill()->getId(), $skills)) {
  2554. $em->remove($item);
  2555. }
  2556. }
  2557. $em->flush();
  2558. }
  2559. // Add new one
  2560. if (!empty($skills)) {
  2561. foreach ($skills as $skillId) {
  2562. $item = new SkillRelCourse();
  2563. $item->setCourse($course);
  2564. $item->setSession($session);
  2565. /** @var SkillEntity $skill */
  2566. $skill = $em->getRepository('ChamiloCoreBundle:Skill')->find($skillId);
  2567. if ($skill) {
  2568. if (!$skill->hasCourseAndSession($item)) {
  2569. $skill->addToCourse($item);
  2570. $em->persist($skill);
  2571. }
  2572. }
  2573. }
  2574. $em->flush();
  2575. }
  2576. return true;
  2577. }
  2578. /**
  2579. * Get the icon (badge image) URL.
  2580. *
  2581. * @param SkillEntity $skill
  2582. * @param bool $getSmall Optional. Allow get the small image
  2583. *
  2584. * @return string
  2585. */
  2586. public static function getWebIconPath(SkillEntity $skill, $getSmall = false)
  2587. {
  2588. if ($getSmall) {
  2589. if (empty($skill->getIcon())) {
  2590. return \Display::return_icon('badges-default.png', null, null, ICON_SIZE_BIG, null, true);
  2591. }
  2592. return api_get_path(WEB_UPLOAD_PATH).'badges/'.sha1($skill->getName()).'-small.png';
  2593. }
  2594. if (empty($skill->getIcon())) {
  2595. return \Display::return_icon('badges-default.png', null, null, ICON_SIZE_HUGE, null, true);
  2596. }
  2597. return api_get_path(WEB_UPLOAD_PATH)."badges/{$skill->getIcon()}";
  2598. }
  2599. }