skill.lib.php 91 KB

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