category.class.php 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\GradebookCategory;
  4. use ChamiloSession as Session;
  5. /**
  6. * Class Category
  7. * Defines a gradebook Category object.
  8. *
  9. * @package chamilo.gradebook
  10. */
  11. class Category implements GradebookItem
  12. {
  13. public $studentList;
  14. public $evaluations;
  15. public $links;
  16. public $subCategories;
  17. /** @var GradebookCategory */
  18. public $entity;
  19. private $id;
  20. private $name;
  21. private $description;
  22. private $user_id;
  23. private $course_code;
  24. private $parent;
  25. private $weight;
  26. private $visible;
  27. private $certificate_min_score;
  28. private $session_id;
  29. private $skills = [];
  30. private $grade_model_id;
  31. private $generateCertificates;
  32. private $isRequirement;
  33. private $courseDependency;
  34. private $minimumToValidate;
  35. /** @var int */
  36. private $gradeBooksToValidateInDependence;
  37. /**
  38. * Consctructor.
  39. */
  40. public function __construct()
  41. {
  42. $this->id = 0;
  43. $this->name = null;
  44. $this->description = null;
  45. $this->user_id = 0;
  46. $this->course_code = null;
  47. $this->parent = 0;
  48. $this->weight = 0;
  49. $this->visible = false;
  50. $this->certificate_min_score = 0;
  51. $this->session_id = 0;
  52. $this->grade_model_id = 0;
  53. $this->generateCertificates = false;
  54. $this->isRequirement = false;
  55. $this->courseDependency = [];
  56. $this->minimumToValidate = null;
  57. }
  58. /**
  59. * @return int
  60. */
  61. public function get_id()
  62. {
  63. return $this->id;
  64. }
  65. /**
  66. * @return string
  67. */
  68. public function get_name()
  69. {
  70. return $this->name;
  71. }
  72. /**
  73. * @return string
  74. */
  75. public function get_description()
  76. {
  77. return $this->description;
  78. }
  79. /**
  80. * @return int
  81. */
  82. public function get_user_id()
  83. {
  84. return $this->user_id;
  85. }
  86. /**
  87. * @return int|null
  88. */
  89. public function getCertificateMinScore()
  90. {
  91. if (!empty($this->certificate_min_score)) {
  92. return $this->certificate_min_score;
  93. } else {
  94. return null;
  95. }
  96. }
  97. /**
  98. * @return string
  99. */
  100. public function get_course_code()
  101. {
  102. return $this->course_code;
  103. }
  104. /**
  105. * @return int
  106. */
  107. public function get_parent_id()
  108. {
  109. return $this->parent;
  110. }
  111. /**
  112. * @return int
  113. */
  114. public function get_weight()
  115. {
  116. return $this->weight;
  117. }
  118. /**
  119. * @return bool
  120. */
  121. public function is_locked()
  122. {
  123. return isset($this->locked) && $this->locked == 1 ? true : false;
  124. }
  125. /**
  126. * @return bool
  127. */
  128. public function is_visible()
  129. {
  130. return $this->visible;
  131. }
  132. /**
  133. * Get $isRequirement.
  134. *
  135. * @return int
  136. */
  137. public function getIsRequirement()
  138. {
  139. return $this->isRequirement;
  140. }
  141. /**
  142. * @param int $id
  143. */
  144. public function set_id($id)
  145. {
  146. $this->id = $id;
  147. }
  148. /**
  149. * @param string $name
  150. */
  151. public function set_name($name)
  152. {
  153. $this->name = $name;
  154. }
  155. /**
  156. * @param string $description
  157. */
  158. public function set_description($description)
  159. {
  160. $this->description = $description;
  161. }
  162. /**
  163. * @param int $user_id
  164. */
  165. public function set_user_id($user_id)
  166. {
  167. $this->user_id = $user_id;
  168. }
  169. /**
  170. * @param string $course_code
  171. */
  172. public function set_course_code($course_code)
  173. {
  174. $this->course_code = $course_code;
  175. }
  176. /**
  177. * @param float $min_score
  178. */
  179. public function set_certificate_min_score($min_score = null)
  180. {
  181. $this->certificate_min_score = $min_score;
  182. }
  183. /**
  184. * @param int $parent
  185. */
  186. public function set_parent_id($parent)
  187. {
  188. $this->parent = intval($parent);
  189. }
  190. /**
  191. * Filters to int and sets the session ID.
  192. *
  193. * @param int The session ID from the Dokeos course session
  194. */
  195. public function set_session_id($session_id = 0)
  196. {
  197. $this->session_id = (int) $session_id;
  198. }
  199. /**
  200. * @param $weight
  201. */
  202. public function set_weight($weight)
  203. {
  204. $this->weight = $weight;
  205. }
  206. /**
  207. * @param $visible
  208. */
  209. public function set_visible($visible)
  210. {
  211. $this->visible = $visible;
  212. }
  213. /**
  214. * @param int $id
  215. */
  216. public function set_grade_model_id($id)
  217. {
  218. $this->grade_model_id = $id;
  219. }
  220. /**
  221. * @param $locked
  222. */
  223. public function set_locked($locked)
  224. {
  225. $this->locked = $locked;
  226. }
  227. /**
  228. * Set $isRequirement.
  229. *
  230. * @param int $isRequirement
  231. */
  232. public function setIsRequirement($isRequirement)
  233. {
  234. $this->isRequirement = $isRequirement;
  235. }
  236. /**
  237. * @param $value
  238. */
  239. public function setCourseListDependency($value)
  240. {
  241. $this->courseDependency = [];
  242. $unserialized = UnserializeApi::unserialize('not_allowed_classes', $value, true);
  243. if (false !== $unserialized) {
  244. $this->courseDependency = $unserialized;
  245. }
  246. }
  247. /**
  248. * Course id list.
  249. *
  250. * @return array
  251. */
  252. public function getCourseListDependency()
  253. {
  254. return $this->courseDependency;
  255. }
  256. /**
  257. * @param int $value
  258. */
  259. public function setMinimumToValidate($value)
  260. {
  261. $this->minimumToValidate = $value;
  262. }
  263. public function getMinimumToValidate()
  264. {
  265. return $this->minimumToValidate;
  266. }
  267. /**
  268. * @return int|null
  269. */
  270. public function get_grade_model_id()
  271. {
  272. if ($this->grade_model_id < 0) {
  273. return null;
  274. }
  275. return $this->grade_model_id;
  276. }
  277. /**
  278. * @return string
  279. */
  280. public function get_type()
  281. {
  282. return 'category';
  283. }
  284. /**
  285. * @param bool $from_db
  286. *
  287. * @return array|resource
  288. */
  289. public function get_skills($from_db = true)
  290. {
  291. if ($from_db) {
  292. $categoryId = $this->get_id();
  293. $gradebook = new Gradebook();
  294. $skills = $gradebook->getSkillsByGradebook($categoryId);
  295. } else {
  296. $skills = $this->skills;
  297. }
  298. return $skills;
  299. }
  300. /**
  301. * @return array
  302. */
  303. public function getSkillsForSelect()
  304. {
  305. $skills = $this->get_skills();
  306. $skill_select = [];
  307. if (!empty($skills)) {
  308. foreach ($skills as $skill) {
  309. $skill_select[$skill['id']] = $skill['name'];
  310. }
  311. }
  312. return $skill_select;
  313. }
  314. /**
  315. * Set the generate_certificates value.
  316. *
  317. * @param int $generateCertificates
  318. */
  319. public function setGenerateCertificates($generateCertificates)
  320. {
  321. $this->generateCertificates = $generateCertificates;
  322. }
  323. /**
  324. * Get the generate_certificates value.
  325. *
  326. * @return int
  327. */
  328. public function getGenerateCertificates()
  329. {
  330. return $this->generateCertificates;
  331. }
  332. /**
  333. * @param int $id
  334. * @param int $session_id
  335. *
  336. * @return array
  337. */
  338. public static function loadSessionCategories(
  339. $id = null,
  340. $session_id = null
  341. ) {
  342. if (isset($id) && (int) $id === 0) {
  343. $cats = [];
  344. $cats[] = self::create_root_category();
  345. return $cats;
  346. }
  347. $courseInfo = api_get_course_info_by_id(api_get_course_int_id());
  348. $courseCode = $courseInfo['code'];
  349. $session_id = (int) $session_id;
  350. if (!empty($session_id)) {
  351. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  352. $sql = 'SELECT id, course_code
  353. FROM '.$table.'
  354. WHERE session_id = '.$session_id;
  355. $result_session = Database::query($sql);
  356. if (Database::num_rows($result_session) > 0) {
  357. $categoryList = [];
  358. while ($data_session = Database::fetch_array($result_session)) {
  359. $parent_id = $data_session['id'];
  360. if ($data_session['course_code'] == $courseCode) {
  361. $categories = self::load($parent_id);
  362. $categoryList = array_merge($categoryList, $categories);
  363. }
  364. }
  365. return $categoryList;
  366. }
  367. }
  368. }
  369. /**
  370. * Retrieve categories and return them as an array of Category objects.
  371. *
  372. * @param int $id category id
  373. * @param int $user_id (category owner)
  374. * @param string $course_code
  375. * @param int $parent_id parent category
  376. * @param bool $visible
  377. * @param int $session_id (in case we are in a session)
  378. * @param bool $order_by Whether to show all "session"
  379. * categories (true) or hide them (false) in case there is no session id
  380. *
  381. * @return array
  382. */
  383. public static function load(
  384. $id = null,
  385. $user_id = null,
  386. $course_code = null,
  387. $parent_id = null,
  388. $visible = null,
  389. $session_id = null,
  390. $order_by = null
  391. ) {
  392. //if the category given is explicitly 0 (not null), then create
  393. // a root category object (in memory)
  394. if (isset($id) && (int) $id === 0) {
  395. $cats = [];
  396. $cats[] = self::create_root_category();
  397. return $cats;
  398. }
  399. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  400. $sql = 'SELECT * FROM '.$table;
  401. $paramcount = 0;
  402. if (isset($id)) {
  403. $sql .= ' WHERE id = '.intval($id);
  404. $paramcount++;
  405. }
  406. if (isset($user_id)) {
  407. $user_id = intval($user_id);
  408. if ($paramcount != 0) {
  409. $sql .= ' AND';
  410. } else {
  411. $sql .= ' WHERE';
  412. }
  413. $sql .= ' user_id = '.intval($user_id);
  414. $paramcount++;
  415. }
  416. if (isset($course_code)) {
  417. if ($paramcount != 0) {
  418. $sql .= ' AND';
  419. } else {
  420. $sql .= ' WHERE';
  421. }
  422. if ($course_code == '0') {
  423. $sql .= ' course_code is null ';
  424. } else {
  425. $sql .= " course_code = '".Database::escape_string($course_code)."'";
  426. }
  427. /*if ($show_session_categories !== true) {
  428. // a query on the course should show all
  429. // the categories inside sessions for this course
  430. // otherwise a special parameter is given to ask explicitely
  431. $sql .= " AND (session_id IS NULL OR session_id = 0) ";
  432. } else {*/
  433. if (empty($session_id)) {
  434. $sql .= ' AND (session_id IS NULL OR session_id = 0) ';
  435. } else {
  436. $sql .= ' AND session_id = '.(int) $session_id.' ';
  437. }
  438. //}
  439. $paramcount++;
  440. }
  441. if (isset($parent_id)) {
  442. if ($paramcount != 0) {
  443. $sql .= ' AND ';
  444. } else {
  445. $sql .= ' WHERE ';
  446. }
  447. $sql .= ' parent_id = '.intval($parent_id);
  448. $paramcount++;
  449. }
  450. if (isset($visible)) {
  451. if ($paramcount != 0) {
  452. $sql .= ' AND';
  453. } else {
  454. $sql .= ' WHERE';
  455. }
  456. $sql .= ' visible = '.intval($visible);
  457. }
  458. if (!empty($order_by)) {
  459. if (!empty($order_by) && $order_by != '') {
  460. $sql .= ' '.$order_by;
  461. }
  462. }
  463. $result = Database::query($sql);
  464. $categories = [];
  465. if (Database::num_rows($result) > 0) {
  466. $categories = self::create_category_objects_from_sql_result(
  467. $result
  468. );
  469. }
  470. return $categories;
  471. }
  472. /**
  473. * Create a category object from a GradebookCategory entity.
  474. *
  475. * @param GradebookCategory $gradebookCategory The entity
  476. *
  477. * @return \Category
  478. */
  479. public static function createCategoryObjectFromEntity(
  480. GradebookCategory $gradebookCategory
  481. ) {
  482. $category = new Category();
  483. $category->set_id($gradebookCategory->getId());
  484. $category->set_name($gradebookCategory->getName());
  485. $category->set_description($gradebookCategory->getDescription());
  486. $category->set_user_id($gradebookCategory->getUserId());
  487. $category->set_course_code($gradebookCategory->getCourseCode());
  488. $category->set_parent_id($gradebookCategory->getParentId());
  489. $category->set_weight($gradebookCategory->getWeight());
  490. $category->set_visible($gradebookCategory->getVisible());
  491. $category->set_session_id($gradebookCategory->getSessionId());
  492. $category->set_certificate_min_score(
  493. $gradebookCategory->getCertifMinScore()
  494. );
  495. $category->set_grade_model_id($gradebookCategory->getGradeModelId());
  496. $category->set_locked($gradebookCategory->getLocked());
  497. $category->setGenerateCertificates(
  498. $gradebookCategory->getGenerateCertificates()
  499. );
  500. $category->setIsRequirement($gradebookCategory->getIsRequirement());
  501. return $category;
  502. }
  503. /**
  504. * Insert this category into the database.
  505. */
  506. public function add()
  507. {
  508. if (isset($this->name) && '-1' == $this->name) {
  509. return false;
  510. }
  511. if (isset($this->name) && isset($this->user_id)) {
  512. $em = Database::getManager();
  513. $category = new GradebookCategory();
  514. $category->setName($this->name);
  515. $category->setDescription($this->description);
  516. $category->setUserId($this->user_id);
  517. $category->setCourseCode($this->course_code);
  518. $category->setParentId($this->parent);
  519. $category->setWeight($this->weight);
  520. $category->setVisible($this->visible);
  521. $category->setCertifMinScore($this->certificate_min_score);
  522. $category->setSessionId($this->session_id);
  523. $category->setGenerateCertificates($this->generateCertificates);
  524. $category->setGradeModelId($this->grade_model_id);
  525. $category->setIsRequirement($this->isRequirement);
  526. $category->setLocked(false);
  527. $em->persist($category);
  528. $em->flush();
  529. $id = $category->getId();
  530. $this->set_id($id);
  531. if (!empty($id)) {
  532. $parent_id = $this->get_parent_id();
  533. $grade_model_id = $this->get_grade_model_id();
  534. if ($parent_id == 0) {
  535. //do something
  536. if (isset($grade_model_id) &&
  537. !empty($grade_model_id) &&
  538. $grade_model_id != '-1'
  539. ) {
  540. $obj = new GradeModel();
  541. $components = $obj->get_components($grade_model_id);
  542. $default_weight_setting = api_get_setting('gradebook_default_weight');
  543. $default_weight = 100;
  544. if (isset($default_weight_setting)) {
  545. $default_weight = $default_weight_setting;
  546. }
  547. foreach ($components as $component) {
  548. $gradebook = new Gradebook();
  549. $params = [];
  550. $params['name'] = $component['acronym'];
  551. $params['description'] = $component['title'];
  552. $params['user_id'] = api_get_user_id();
  553. $params['parent_id'] = $id;
  554. $params['weight'] = $component['percentage'] / 100 * $default_weight;
  555. $params['session_id'] = api_get_session_id();
  556. $params['course_code'] = $this->get_course_code();
  557. $gradebook->save($params);
  558. }
  559. }
  560. }
  561. }
  562. $gradebook = new Gradebook();
  563. $gradebook->updateSkillsToGradeBook(
  564. $this->id,
  565. $this->get_skills(false)
  566. );
  567. return $id;
  568. }
  569. }
  570. /**
  571. * Update the properties of this category in the database.
  572. *
  573. * @todo fix me
  574. */
  575. public function save()
  576. {
  577. $em = Database::getManager();
  578. $gradebookCategory = $em
  579. ->getRepository('ChamiloCoreBundle:GradebookCategory')
  580. ->find($this->id);
  581. if (empty($gradebookCategory)) {
  582. return false;
  583. }
  584. $gradebookCategory->setName($this->name);
  585. $gradebookCategory->setDescription($this->description);
  586. $gradebookCategory->setUserId($this->user_id);
  587. $gradebookCategory->setCourseCode($this->course_code);
  588. $gradebookCategory->setParentId($this->parent);
  589. $gradebookCategory->setWeight($this->weight);
  590. $gradebookCategory->setVisible($this->visible);
  591. $gradebookCategory->setCertifMinScore($this->certificate_min_score);
  592. $gradebookCategory->setGenerateCertificates(
  593. $this->generateCertificates
  594. );
  595. $gradebookCategory->setGradeModelId($this->grade_model_id);
  596. $gradebookCategory->setIsRequirement($this->isRequirement);
  597. $em->merge($gradebookCategory);
  598. $em->flush();
  599. if (!empty($this->id)) {
  600. $parent_id = $this->get_parent_id();
  601. $grade_model_id = $this->get_grade_model_id();
  602. if ($parent_id == 0) {
  603. if (isset($grade_model_id) &&
  604. !empty($grade_model_id) &&
  605. $grade_model_id != '-1'
  606. ) {
  607. $obj = new GradeModel();
  608. $components = $obj->get_components($grade_model_id);
  609. $default_weight_setting = api_get_setting('gradebook_default_weight');
  610. $default_weight = 100;
  611. if (isset($default_weight_setting)) {
  612. $default_weight = $default_weight_setting;
  613. }
  614. $final_weight = $this->get_weight();
  615. if (!empty($final_weight)) {
  616. $default_weight = $this->get_weight();
  617. }
  618. foreach ($components as $component) {
  619. $gradebook = new Gradebook();
  620. $params = [];
  621. $params['name'] = $component['acronym'];
  622. $params['description'] = $component['title'];
  623. $params['user_id'] = api_get_user_id();
  624. $params['parent_id'] = $this->id;
  625. $params['weight'] = $component['percentage'] / 100 * $default_weight;
  626. $params['session_id'] = api_get_session_id();
  627. $params['course_code'] = $this->get_course_code();
  628. $gradebook->save($params);
  629. }
  630. }
  631. }
  632. }
  633. $gradebook = new Gradebook();
  634. $gradebook->updateSkillsToGradeBook(
  635. $this->id,
  636. $this->get_skills(false),
  637. true
  638. );
  639. }
  640. /**
  641. * Update link weights see #5168.
  642. *
  643. * @param type $new_weight
  644. */
  645. public function updateChildrenWeight($new_weight)
  646. {
  647. $links = $this->get_links();
  648. $old_weight = $this->get_weight();
  649. if (!empty($links)) {
  650. foreach ($links as $link_item) {
  651. if (isset($link_item)) {
  652. $new_item_weight = $new_weight * $link_item->get_weight() / $old_weight;
  653. $link_item->set_weight($new_item_weight);
  654. $link_item->save();
  655. }
  656. }
  657. }
  658. }
  659. /**
  660. * Delete this evaluation from the database.
  661. */
  662. public function delete()
  663. {
  664. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  665. $sql = 'DELETE FROM '.$table.' WHERE id = '.intval($this->id);
  666. Database::query($sql);
  667. }
  668. /**
  669. * Not delete this category from the database,when visible=3 is category eliminated.
  670. *
  671. * @deprecated To delete categories form course when deleting course use Category::deleteFromCourse
  672. */
  673. public function update_category_delete($course_id)
  674. {
  675. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  676. $sql = 'UPDATE '.$table.' SET
  677. visible = 3
  678. WHERE course_code ="'.Database::escape_string($course_id).'"';
  679. Database::query($sql);
  680. }
  681. /**
  682. * Delete the gradebook categories from a course, including course sessions.
  683. *
  684. * @param string $courseCode
  685. */
  686. public static function deleteFromCourse($courseCode)
  687. {
  688. $em = Database::getManager();
  689. $categories = $em
  690. ->createQuery(
  691. 'SELECT DISTINCT gc.sessionId
  692. FROM ChamiloCoreBundle:GradebookCategory gc WHERE gc.courseCode = :code'
  693. )
  694. ->setParameter('code', $courseCode)
  695. ->getResult();
  696. foreach ($categories as $category) {
  697. $cats = self::load(
  698. null,
  699. null,
  700. $courseCode,
  701. null,
  702. null,
  703. (int) $category['sessionId']
  704. );
  705. if (!empty($cats)) {
  706. /** @var self $cat */
  707. foreach ($cats as $cat) {
  708. $cat->delete_all();
  709. }
  710. }
  711. }
  712. }
  713. /**
  714. * Show message resource delete.
  715. *
  716. * @param string $courseCode
  717. *
  718. * @return mixed
  719. */
  720. public function show_message_resource_delete($courseCode)
  721. {
  722. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  723. $sql = 'SELECT count(*) AS num
  724. FROM '.$table.'
  725. WHERE
  726. course_code = "'.Database::escape_string($courseCode).'" AND
  727. visible = 3';
  728. $res = Database::query($sql);
  729. $option = Database::fetch_array($res, 'ASSOC');
  730. if ($option['num'] >= 1) {
  731. return '&nbsp;&nbsp;<span class="resource-deleted">(&nbsp;'.get_lang('ResourceDeleted').'&nbsp;)</span>';
  732. } else {
  733. return false;
  734. }
  735. }
  736. /**
  737. * Shows all information of an category.
  738. *
  739. * @param int $categoryId
  740. *
  741. * @return array
  742. */
  743. public function showAllCategoryInfo($categoryId = 0)
  744. {
  745. $categoryId = (int) $categoryId;
  746. if (empty($categoryId)) {
  747. return [];
  748. }
  749. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  750. $sql = 'SELECT * FROM '.$table.'
  751. WHERE id = '.$categoryId;
  752. $result = Database::query($sql);
  753. $row = Database::fetch_array($result, 'ASSOC');
  754. return $row;
  755. }
  756. /**
  757. * Check if a category name (with the same parent category) already exists.
  758. *
  759. * @param string $name name to check (if not given, the name property of this object will be checked)
  760. * @param int $parent parent category
  761. *
  762. * @return bool
  763. */
  764. public function does_name_exist($name, $parent)
  765. {
  766. if (!isset($name)) {
  767. $name = $this->name;
  768. $parent = $this->parent;
  769. }
  770. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  771. $sql = "SELECT count(id) AS number
  772. FROM $table
  773. WHERE name = '".Database::escape_string($name)."'";
  774. if (api_is_allowed_to_edit()) {
  775. $parent = self::load($parent);
  776. $code = $parent[0]->get_course_code();
  777. $courseInfo = api_get_course_info($code);
  778. $courseId = $courseInfo['real_id'];
  779. if (isset($code) && $code != '0') {
  780. $main_course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  781. $sql .= ' AND user_id IN (
  782. SELECT user_id FROM '.$main_course_user_table.'
  783. WHERE c_id = '.$courseId.' AND status = '.COURSEMANAGER.'
  784. )';
  785. } else {
  786. $sql .= ' AND user_id = '.api_get_user_id();
  787. }
  788. } else {
  789. $sql .= ' AND user_id = '.api_get_user_id();
  790. }
  791. if (!isset($parent)) {
  792. $sql .= ' AND parent_id is null';
  793. } else {
  794. $sql .= ' AND parent_id = '.intval($parent);
  795. }
  796. $result = Database::query($sql);
  797. $number = Database::fetch_row($result);
  798. return $number[0] != 0;
  799. }
  800. /**
  801. * Checks if the certificate is available for the given user in this category.
  802. *
  803. * @param int $user_id User ID
  804. *
  805. * @return bool True if conditions match, false if fails
  806. */
  807. public function is_certificate_available($user_id)
  808. {
  809. $score = $this->calc_score(
  810. $user_id,
  811. null,
  812. $this->course_code,
  813. $this->session_id
  814. );
  815. if (isset($score) && isset($score[0])) {
  816. // Get a percentage score to compare to minimum certificate score
  817. // $certification_score = $score[0] / $score[1] * 100;
  818. // Get real score not a percentage.
  819. $certification_score = $score[0];
  820. if ($certification_score >= $this->certificate_min_score) {
  821. return true;
  822. }
  823. }
  824. return false;
  825. }
  826. /**
  827. * Is this category a course ?
  828. * A category is a course if it has a course code and no parent category.
  829. */
  830. public function is_course()
  831. {
  832. return isset($this->course_code) && !empty($this->course_code)
  833. && (!isset($this->parent) || $this->parent == 0);
  834. }
  835. /**
  836. * Calculate the score of this category.
  837. *
  838. * @param int $stud_id student id (default: all students - then the average is returned)
  839. * @param $type
  840. * @param string $course_code
  841. * @param int $session_id
  842. *
  843. * @return array (score sum, weight sum)
  844. * or null if no scores available
  845. */
  846. public function calc_score(
  847. $stud_id = null,
  848. $type = null,
  849. $course_code = '',
  850. $session_id = null
  851. ) {
  852. $key = 'category:'.$this->id.'student:'.(int) $stud_id.'type:'.$type.'course:'.$course_code.'session:'.(int) $session_id;
  853. $useCache = api_get_configuration_value('gradebook_use_apcu_cache');
  854. $cacheAvailable = api_get_configuration_value('apc') && $useCache;
  855. if ($cacheAvailable) {
  856. $cacheDriver = new \Doctrine\Common\Cache\ApcuCache();
  857. if ($cacheDriver->contains($key)) {
  858. return $cacheDriver->fetch($key);
  859. }
  860. }
  861. // Classic
  862. if (!empty($stud_id) && $type == '') {
  863. if (!empty($course_code)) {
  864. $cats = $this->get_subcategories(
  865. $stud_id,
  866. $course_code,
  867. $session_id
  868. );
  869. $evals = $this->get_evaluations($stud_id, false, $course_code);
  870. $links = $this->get_links($stud_id, false, $course_code);
  871. } else {
  872. $cats = $this->get_subcategories($stud_id);
  873. $evals = $this->get_evaluations($stud_id);
  874. $links = $this->get_links($stud_id);
  875. }
  876. // Calculate score
  877. $count = 0;
  878. $ressum = 0;
  879. $weightsum = 0;
  880. if (!empty($cats)) {
  881. /** @var Category $cat */
  882. foreach ($cats as $cat) {
  883. $cat->set_session_id($session_id);
  884. $cat->set_course_code($course_code);
  885. $cat->setStudentList($this->getStudentList());
  886. $score = $cat->calc_score(
  887. $stud_id,
  888. null,
  889. $course_code,
  890. $session_id
  891. );
  892. $catweight = 0;
  893. if ($cat->get_weight() != 0) {
  894. $catweight = $cat->get_weight();
  895. $weightsum += $catweight;
  896. }
  897. if (isset($score) && !empty($score[1]) && !empty($catweight)) {
  898. $ressum += $score[0] / $score[1] * $catweight;
  899. }
  900. }
  901. }
  902. $students = [];
  903. if (!empty($evals)) {
  904. /** @var Evaluation $eval */
  905. foreach ($evals as $eval) {
  906. $eval->setStudentList($this->getStudentList());
  907. $evalres = $eval->calc_score($stud_id);
  908. if (isset($evalres) && $eval->get_weight() != 0) {
  909. $evalweight = $eval->get_weight();
  910. $weightsum += $evalweight;
  911. if (!empty($evalres[1])) {
  912. $ressum += $evalres[0] / $evalres[1] * $evalweight;
  913. }
  914. } else {
  915. if ($eval->get_weight() != 0) {
  916. $evalweight = $eval->get_weight();
  917. $weightsum += $evalweight;
  918. }
  919. }
  920. }
  921. }
  922. if (!empty($links)) {
  923. /** @var EvalLink|ExerciseLink $link */
  924. foreach ($links as $link) {
  925. $link->setStudentList($this->getStudentList());
  926. if ($session_id) {
  927. $link->set_session_id($session_id);
  928. }
  929. $linkres = $link->calc_score($stud_id, null);
  930. if (!empty($linkres) && $link->get_weight() != 0) {
  931. $students[$stud_id] = $linkres[0];
  932. $linkweight = $link->get_weight();
  933. $link_res_denom = $linkres[1] == 0 ? 1 : $linkres[1];
  934. $count++;
  935. $weightsum += $linkweight;
  936. $ressum += $linkres[0] / $link_res_denom * $linkweight;
  937. } else {
  938. // Adding if result does not exists
  939. if ($link->get_weight() != 0) {
  940. $linkweight = $link->get_weight();
  941. $weightsum += $linkweight;
  942. }
  943. }
  944. }
  945. }
  946. } else {
  947. if (!empty($course_code)) {
  948. $cats = $this->get_subcategories(
  949. null,
  950. $course_code,
  951. $session_id
  952. );
  953. $evals = $this->get_evaluations(null, false, $course_code);
  954. $links = $this->get_links(null, false, $course_code);
  955. } else {
  956. $cats = $this->get_subcategories(null);
  957. $evals = $this->get_evaluations(null);
  958. $links = $this->get_links(null);
  959. }
  960. // Calculate score
  961. $count = 0;
  962. $ressum = 0;
  963. $weightsum = 0;
  964. $bestResult = 0;
  965. if (!empty($cats)) {
  966. /** @var Category $cat */
  967. foreach ($cats as $cat) {
  968. $cat->setStudentList($this->getStudentList());
  969. $score = $cat->calc_score(
  970. null,
  971. $type,
  972. $course_code,
  973. $session_id
  974. );
  975. $catweight = 0;
  976. if ($cat->get_weight() != 0) {
  977. $catweight = $cat->get_weight();
  978. $weightsum += $catweight;
  979. }
  980. if (isset($score) && !empty($score[1]) && !empty($catweight)) {
  981. $ressum += $score[0] / $score[1] * $catweight;
  982. if ($ressum > $bestResult) {
  983. $bestResult = $ressum;
  984. }
  985. }
  986. }
  987. }
  988. if (!empty($evals)) {
  989. /** @var Evaluation $eval */
  990. foreach ($evals as $eval) {
  991. $evalres = $eval->calc_score(null, $type);
  992. $eval->setStudentList($this->getStudentList());
  993. if (isset($evalres) && $eval->get_weight() != 0) {
  994. $evalweight = $eval->get_weight();
  995. $weightsum += $evalweight;
  996. $count++;
  997. if (!empty($evalres[1])) {
  998. $ressum += $evalres[0] / $evalres[1] * $evalweight;
  999. }
  1000. if ($ressum > $bestResult) {
  1001. $bestResult = $ressum;
  1002. }
  1003. } else {
  1004. if ($eval->get_weight() != 0) {
  1005. $evalweight = $eval->get_weight();
  1006. $weightsum += $evalweight;
  1007. }
  1008. }
  1009. }
  1010. }
  1011. if (!empty($links)) {
  1012. /** @var EvalLink|ExerciseLink $link */
  1013. foreach ($links as $link) {
  1014. $link->setStudentList($this->getStudentList());
  1015. if ($session_id) {
  1016. $link->set_session_id($session_id);
  1017. }
  1018. $linkres = $link->calc_score($stud_id, $type);
  1019. if (!empty($linkres) && $link->get_weight() != 0) {
  1020. $students[$stud_id] = $linkres[0];
  1021. $linkweight = $link->get_weight();
  1022. $link_res_denom = $linkres[1] == 0 ? 1 : $linkres[1];
  1023. $count++;
  1024. $weightsum += $linkweight;
  1025. $ressum += $linkres[0] / $link_res_denom * $linkweight;
  1026. if ($ressum > $bestResult) {
  1027. $bestResult = $ressum;
  1028. }
  1029. } else {
  1030. // Adding if result does not exists
  1031. if ($link->get_weight() != 0) {
  1032. $linkweight = $link->get_weight();
  1033. $weightsum += $linkweight;
  1034. }
  1035. }
  1036. }
  1037. }
  1038. }
  1039. switch ($type) {
  1040. case 'best':
  1041. if (empty($bestResult)) {
  1042. if ($cacheAvailable) {
  1043. $cacheDriver->save($key, null);
  1044. }
  1045. return null;
  1046. }
  1047. if ($cacheAvailable) {
  1048. $cacheDriver->save($key, [$bestResult, $weightsum]);
  1049. }
  1050. return [$bestResult, $weightsum];
  1051. break;
  1052. case 'average':
  1053. if (empty($ressum)) {
  1054. if ($cacheAvailable) {
  1055. $cacheDriver->save($key, null);
  1056. }
  1057. return null;
  1058. }
  1059. if ($cacheAvailable) {
  1060. $cacheDriver->save($key, [$ressum, $weightsum]);
  1061. }
  1062. return [$ressum, $weightsum];
  1063. break;
  1064. case 'ranking':
  1065. // category ranking is calculated in gradebook_data_generator.class.php
  1066. // function get_data
  1067. return null;
  1068. return AbstractLink::getCurrentUserRanking($stud_id, []);
  1069. break;
  1070. default:
  1071. if ($cacheAvailable) {
  1072. $cacheDriver->save($key, [$ressum, $weightsum]);
  1073. }
  1074. return [$ressum, $weightsum];
  1075. break;
  1076. }
  1077. }
  1078. /**
  1079. * Delete this category and every subcategory, evaluation and result inside.
  1080. */
  1081. public function delete_all()
  1082. {
  1083. $cats = self::load(null, null, $this->course_code, $this->id, null);
  1084. $evals = Evaluation::load(
  1085. null,
  1086. null,
  1087. $this->course_code,
  1088. $this->id,
  1089. null
  1090. );
  1091. $links = LinkFactory::load(
  1092. null,
  1093. null,
  1094. null,
  1095. null,
  1096. $this->course_code,
  1097. $this->id,
  1098. null
  1099. );
  1100. if (!empty($cats)) {
  1101. /** @var Category $cat */
  1102. foreach ($cats as $cat) {
  1103. $cat->delete_all();
  1104. $cat->delete();
  1105. }
  1106. }
  1107. if (!empty($evals)) {
  1108. /** @var Evaluation $eval */
  1109. foreach ($evals as $eval) {
  1110. $eval->delete_with_results();
  1111. }
  1112. }
  1113. if (!empty($links)) {
  1114. /** @var AbstractLink $link */
  1115. foreach ($links as $link) {
  1116. $link->delete();
  1117. }
  1118. }
  1119. $this->delete();
  1120. }
  1121. /**
  1122. * Return array of Category objects where a student is subscribed to.
  1123. *
  1124. * @param int $stud_id
  1125. * @param string $course_code
  1126. * @param int $session_id
  1127. *
  1128. * @return array
  1129. */
  1130. public function get_root_categories_for_student(
  1131. $stud_id,
  1132. $course_code = null,
  1133. $session_id = null
  1134. ) {
  1135. $main_course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1136. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  1137. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1138. $course_code = Database::escape_string($course_code);
  1139. $session_id = (int) $session_id;
  1140. $sql = "SELECT * FROM $table WHERE parent_id = 0";
  1141. if (!api_is_allowed_to_edit()) {
  1142. $sql .= ' AND visible = 1';
  1143. //proceed with checks on optional parameters course & session
  1144. if (!empty($course_code)) {
  1145. // TODO: considering it highly improbable that a user would get here
  1146. // if he doesn't have the rights to view this course and this
  1147. // session, we don't check his registration to these, but this
  1148. // could be an improvement
  1149. if (!empty($session_id)) {
  1150. $sql .= " AND course_code = '".$course_code."' AND session_id = ".$session_id;
  1151. } else {
  1152. $sql .= " AND course_code = '".$course_code."' AND session_id is null OR session_id=0";
  1153. }
  1154. } else {
  1155. //no optional parameter, proceed as usual
  1156. $sql .= ' AND course_code in
  1157. (
  1158. SELECT c.code
  1159. FROM '.$main_course_user_table.' cu INNER JOIN '.$courseTable.' c
  1160. ON (cu.c_id = c.id)
  1161. WHERE cu.user_id = '.intval($stud_id).'
  1162. AND cu.status = '.STUDENT.'
  1163. )';
  1164. }
  1165. } elseif (api_is_allowed_to_edit() && !api_is_platform_admin()) {
  1166. //proceed with checks on optional parameters course & session
  1167. if (!empty($course_code)) {
  1168. // TODO: considering it highly improbable that a user would get here
  1169. // if he doesn't have the rights to view this course and this
  1170. // session, we don't check his registration to these, but this
  1171. // could be an improvement
  1172. $sql .= " AND course_code = '".$course_code."'";
  1173. if (!empty($session_id)) {
  1174. $sql .= " AND session_id = ".$session_id;
  1175. } else {
  1176. $sql .= 'AND session_id IS NULL OR session_id = 0';
  1177. }
  1178. } else {
  1179. $sql .= ' AND course_code IN
  1180. (
  1181. SELECT c.code
  1182. FROM '.$main_course_user_table.' cu INNER JOIN '.$courseTable.' c
  1183. ON (cu.c_id = c.id)
  1184. WHERE
  1185. cu.user_id = '.api_get_user_id().' AND
  1186. cu.status = '.COURSEMANAGER.'
  1187. )';
  1188. }
  1189. } elseif (api_is_platform_admin()) {
  1190. if (isset($session_id) && $session_id != 0) {
  1191. $sql .= ' AND session_id='.$session_id;
  1192. } else {
  1193. $sql .= ' AND coalesce(session_id,0)=0';
  1194. }
  1195. }
  1196. $result = Database::query($sql);
  1197. $cats = self::create_category_objects_from_sql_result($result);
  1198. // course independent categories
  1199. if (empty($course_code)) {
  1200. $cats = $this->getIndependentCategoriesWithStudentResult(
  1201. 0,
  1202. $stud_id,
  1203. $cats
  1204. );
  1205. }
  1206. return $cats;
  1207. }
  1208. /**
  1209. * Return array of Category objects where a teacher is admin for.
  1210. *
  1211. * @param int $user_id (to return everything, use 'null' here)
  1212. * @param string $course_code (optional)
  1213. * @param int $session_id (optional)
  1214. *
  1215. * @return array
  1216. */
  1217. public function get_root_categories_for_teacher(
  1218. $user_id,
  1219. $course_code = null,
  1220. $session_id = null
  1221. ) {
  1222. if ($user_id == null) {
  1223. return self::load(null, null, $course_code, 0, null, $session_id);
  1224. }
  1225. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  1226. $main_course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1227. $tbl_grade_categories = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1228. $sql = 'SELECT * FROM '.$tbl_grade_categories.'
  1229. WHERE parent_id = 0 ';
  1230. if (!empty($course_code)) {
  1231. $sql .= " AND course_code = '".Database::escape_string($course_code)."' ";
  1232. if (!empty($session_id)) {
  1233. $sql .= " AND session_id = ".(int) $session_id;
  1234. }
  1235. } else {
  1236. $sql .= ' AND course_code in
  1237. (
  1238. SELECT c.code
  1239. FROM '.$main_course_user_table.' cu
  1240. INNER JOIN '.$courseTable.' c
  1241. ON (cu.c_id = c.id)
  1242. WHERE user_id = '.intval($user_id).'
  1243. )';
  1244. }
  1245. $result = Database::query($sql);
  1246. $cats = self::create_category_objects_from_sql_result($result);
  1247. // course independent categories
  1248. if (isset($course_code)) {
  1249. $indcats = self::load(
  1250. null,
  1251. $user_id,
  1252. $course_code,
  1253. 0,
  1254. null,
  1255. $session_id
  1256. );
  1257. $cats = array_merge($cats, $indcats);
  1258. }
  1259. return $cats;
  1260. }
  1261. /**
  1262. * Can this category be moved to somewhere else ?
  1263. * The root and courses cannot be moved.
  1264. *
  1265. * @return bool
  1266. */
  1267. public function is_movable()
  1268. {
  1269. return !(!isset($this->id) || $this->id == 0 || $this->is_course());
  1270. }
  1271. /**
  1272. * Generate an array of possible categories where this category can be moved to.
  1273. * Notice: its own parent will be included in the list: it's up to the frontend
  1274. * to disable this element.
  1275. *
  1276. * @return array 2-dimensional array - every element contains 3 subelements (id, name, level)
  1277. */
  1278. public function get_target_categories()
  1279. {
  1280. // the root or a course -> not movable
  1281. if (!$this->is_movable()) {
  1282. return null;
  1283. } else {
  1284. // otherwise:
  1285. // - course independent category
  1286. // -> movable to root or other independent categories
  1287. // - category inside a course
  1288. // -> movable to root, independent categories or categories inside the course
  1289. $user = api_is_platform_admin() ? null : api_get_user_id();
  1290. $targets = [];
  1291. $level = 0;
  1292. $root = [0, get_lang('RootCat'), $level];
  1293. $targets[] = $root;
  1294. if (isset($this->course_code) && !empty($this->course_code)) {
  1295. $crscats = self::load(null, null, $this->course_code, 0);
  1296. foreach ($crscats as $cat) {
  1297. if ($this->can_be_moved_to_cat($cat)) {
  1298. $targets[] = [
  1299. $cat->get_id(),
  1300. $cat->get_name(),
  1301. $level + 1,
  1302. ];
  1303. $targets = $this->addTargetSubcategories(
  1304. $targets,
  1305. $level + 1,
  1306. $cat->get_id()
  1307. );
  1308. }
  1309. }
  1310. }
  1311. $indcats = self::load(null, $user, 0, 0);
  1312. foreach ($indcats as $cat) {
  1313. if ($this->can_be_moved_to_cat($cat)) {
  1314. $targets[] = [$cat->get_id(), $cat->get_name(), $level + 1];
  1315. $targets = $this->addTargetSubcategories(
  1316. $targets,
  1317. $level + 1,
  1318. $cat->get_id()
  1319. );
  1320. }
  1321. }
  1322. return $targets;
  1323. }
  1324. }
  1325. /**
  1326. * Move this category to the given category.
  1327. * If this category moves from inside a course to outside,
  1328. * its course code must be changed, as well as the course code
  1329. * of all underlying categories and evaluations. All links will
  1330. * be deleted as well !
  1331. */
  1332. public function move_to_cat($cat)
  1333. {
  1334. $this->set_parent_id($cat->get_id());
  1335. if ($this->get_course_code() != $cat->get_course_code()) {
  1336. $this->set_course_code($cat->get_course_code());
  1337. $this->applyCourseCodeToChildren();
  1338. }
  1339. $this->save();
  1340. }
  1341. /**
  1342. * Generate an array of all categories the user can navigate to.
  1343. */
  1344. public function get_tree()
  1345. {
  1346. $targets = [];
  1347. $level = 0;
  1348. $root = [0, get_lang('RootCat'), $level];
  1349. $targets[] = $root;
  1350. // course or platform admin
  1351. if (api_is_allowed_to_edit()) {
  1352. $user = api_is_platform_admin() ? null : api_get_user_id();
  1353. $cats = self::get_root_categories_for_teacher($user);
  1354. foreach ($cats as $cat) {
  1355. $targets[] = [
  1356. $cat->get_id(),
  1357. $cat->get_name(),
  1358. $level + 1,
  1359. ];
  1360. $targets = $this->add_subtree(
  1361. $targets,
  1362. $level + 1,
  1363. $cat->get_id(),
  1364. null
  1365. );
  1366. }
  1367. } else {
  1368. // student
  1369. $cats = $this->get_root_categories_for_student(api_get_user_id());
  1370. foreach ($cats as $cat) {
  1371. $targets[] = [
  1372. $cat->get_id(),
  1373. $cat->get_name(),
  1374. $level + 1,
  1375. ];
  1376. $targets = $this->add_subtree(
  1377. $targets,
  1378. $level + 1,
  1379. $cat->get_id(),
  1380. 1
  1381. );
  1382. }
  1383. }
  1384. return $targets;
  1385. }
  1386. /**
  1387. * Generate an array of courses that a teacher hasn't created a category for.
  1388. *
  1389. * @param int $user_id
  1390. *
  1391. * @return array 2-dimensional array - every element contains 2 subelements (code, title)
  1392. */
  1393. public function get_not_created_course_categories($user_id)
  1394. {
  1395. $tbl_main_courses = Database::get_main_table(TABLE_MAIN_COURSE);
  1396. $tbl_main_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1397. $tbl_grade_categories = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1398. $sql = 'SELECT DISTINCT(code), title
  1399. FROM '.$tbl_main_courses.' cc, '.$tbl_main_course_user.' cu
  1400. WHERE
  1401. cc.id = cu.c_id AND
  1402. cu.status = '.COURSEMANAGER;
  1403. if (!api_is_platform_admin()) {
  1404. $sql .= ' AND cu.user_id = '.$user_id;
  1405. }
  1406. $sql .= ' AND cc.code NOT IN
  1407. (
  1408. SELECT course_code FROM '.$tbl_grade_categories.'
  1409. WHERE
  1410. parent_id = 0 AND
  1411. course_code IS NOT NULL
  1412. )';
  1413. $result = Database::query($sql);
  1414. $cats = [];
  1415. while ($data = Database::fetch_array($result)) {
  1416. $cats[] = [$data['code'], $data['title']];
  1417. }
  1418. return $cats;
  1419. }
  1420. /**
  1421. * Generate an array of all courses that a teacher is admin of.
  1422. *
  1423. * @param int $user_id
  1424. *
  1425. * @return array 2-dimensional array - every element contains 2 subelements (code, title)
  1426. */
  1427. public function get_all_courses($user_id)
  1428. {
  1429. $tbl_main_courses = Database::get_main_table(TABLE_MAIN_COURSE);
  1430. $tbl_main_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1431. $sql = 'SELECT DISTINCT(code), title
  1432. FROM '.$tbl_main_courses.' cc, '.$tbl_main_course_user.' cu
  1433. WHERE cc.id = cu.c_id AND cu.status = '.COURSEMANAGER;
  1434. if (!api_is_platform_admin()) {
  1435. $sql .= ' AND cu.user_id = '.intval($user_id);
  1436. }
  1437. $result = Database::query($sql);
  1438. $cats = [];
  1439. while ($data = Database::fetch_array($result)) {
  1440. $cats[] = [$data['code'], $data['title']];
  1441. }
  1442. return $cats;
  1443. }
  1444. /**
  1445. * Apply the same visibility to every subcategory, evaluation and link.
  1446. */
  1447. public function apply_visibility_to_children()
  1448. {
  1449. $cats = self::load(null, null, null, $this->id, null);
  1450. $evals = Evaluation::load(null, null, null, $this->id, null);
  1451. $links = LinkFactory::load(
  1452. null,
  1453. null,
  1454. null,
  1455. null,
  1456. null,
  1457. $this->id,
  1458. null
  1459. );
  1460. if (!empty($cats)) {
  1461. foreach ($cats as $cat) {
  1462. $cat->set_visible($this->is_visible());
  1463. $cat->save();
  1464. $cat->apply_visibility_to_children();
  1465. }
  1466. }
  1467. if (!empty($evals)) {
  1468. foreach ($evals as $eval) {
  1469. $eval->set_visible($this->is_visible());
  1470. $eval->save();
  1471. }
  1472. }
  1473. if (!empty($links)) {
  1474. foreach ($links as $link) {
  1475. $link->set_visible($this->is_visible());
  1476. $link->save();
  1477. }
  1478. }
  1479. }
  1480. /**
  1481. * Check if a category contains evaluations with a result for a given student.
  1482. *
  1483. * @param int $studentId
  1484. *
  1485. * @return bool
  1486. */
  1487. public function hasEvaluationsWithStudentResults($studentId)
  1488. {
  1489. $evals = Evaluation::get_evaluations_with_result_for_student(
  1490. $this->id,
  1491. $studentId
  1492. );
  1493. if (count($evals) != 0) {
  1494. return true;
  1495. } else {
  1496. $cats = self::load(
  1497. null,
  1498. null,
  1499. null,
  1500. $this->id,
  1501. api_is_allowed_to_edit() ? null : 1
  1502. );
  1503. /** @var Category $cat */
  1504. foreach ($cats as $cat) {
  1505. if ($cat->hasEvaluationsWithStudentResults($studentId)) {
  1506. return true;
  1507. }
  1508. }
  1509. return false;
  1510. }
  1511. }
  1512. /**
  1513. * Retrieve all categories inside a course independent category
  1514. * that should be visible to a student.
  1515. *
  1516. * @param int $categoryId parent category
  1517. * @param int $studentId
  1518. * @param array $cats optional: if defined, the categories will be added to this array
  1519. *
  1520. * @return array
  1521. */
  1522. public function getIndependentCategoriesWithStudentResult(
  1523. $categoryId,
  1524. $studentId,
  1525. $cats = []
  1526. ) {
  1527. $creator = api_is_allowed_to_edit() && !api_is_platform_admin() ? api_get_user_id() : null;
  1528. $categories = self::load(
  1529. null,
  1530. $creator,
  1531. '0',
  1532. $categoryId,
  1533. api_is_allowed_to_edit() ? null : 1
  1534. );
  1535. if (!empty($categories)) {
  1536. /** @var Category $category */
  1537. foreach ($categories as $category) {
  1538. if ($category->hasEvaluationsWithStudentResults($studentId)) {
  1539. $cats[] = $category;
  1540. }
  1541. }
  1542. }
  1543. return $cats;
  1544. }
  1545. /**
  1546. * Return the session id (in any case, even if it's null or 0).
  1547. *
  1548. * @return int Session id (can be null)
  1549. */
  1550. public function get_session_id()
  1551. {
  1552. return $this->session_id;
  1553. }
  1554. /**
  1555. * Get appropriate subcategories visible for the user (and optionally the course and session).
  1556. *
  1557. * @param int $studentId student id (default: all students)
  1558. * @param string $course_code Course code (optional)
  1559. * @param int $session_id Session ID (optional)
  1560. * @param bool $order
  1561. *
  1562. * @return array Array of subcategories
  1563. */
  1564. public function get_subcategories(
  1565. $studentId = null,
  1566. $course_code = null,
  1567. $session_id = null,
  1568. $order = null
  1569. ) {
  1570. // 1 student
  1571. if (isset($studentId)) {
  1572. // Special case: this is the root
  1573. if ($this->id == 0) {
  1574. return $this->get_root_categories_for_student($studentId, $course_code, $session_id);
  1575. } else {
  1576. return self::load(
  1577. null,
  1578. null,
  1579. $course_code,
  1580. $this->id,
  1581. api_is_allowed_to_edit() ? null : 1,
  1582. $session_id,
  1583. $order
  1584. );
  1585. }
  1586. } else {
  1587. // All students
  1588. // Course admin
  1589. if (api_is_allowed_to_edit() && !api_is_platform_admin()) {
  1590. // root
  1591. if ($this->id == 0) {
  1592. // inside a course
  1593. return $this->get_root_categories_for_teacher(
  1594. api_get_user_id(),
  1595. $course_code,
  1596. $session_id,
  1597. false
  1598. );
  1599. } elseif (!empty($this->course_code)) {
  1600. return self::load(
  1601. null,
  1602. null,
  1603. $this->course_code,
  1604. $this->id,
  1605. null,
  1606. $session_id,
  1607. $order
  1608. );
  1609. } elseif (!empty($course_code)) {
  1610. // course independent
  1611. return self::load(
  1612. null,
  1613. null,
  1614. $course_code,
  1615. $this->id,
  1616. null,
  1617. $session_id,
  1618. $order
  1619. );
  1620. } else {
  1621. return self::load(
  1622. null,
  1623. api_get_user_id(),
  1624. 0,
  1625. $this->id,
  1626. null
  1627. );
  1628. }
  1629. } elseif (api_is_platform_admin()) {
  1630. // platform admin
  1631. // we explicitly avoid listing subcats from another session
  1632. return self::load(
  1633. null,
  1634. null,
  1635. $course_code,
  1636. $this->id,
  1637. null,
  1638. $session_id,
  1639. $order
  1640. );
  1641. }
  1642. }
  1643. return [];
  1644. }
  1645. /**
  1646. * Get appropriate evaluations visible for the user.
  1647. *
  1648. * @param int $studentId student id (default: all students)
  1649. * @param bool $recursive process subcategories (default: no recursion)
  1650. * @param string $course_code
  1651. * @param int $sessionId
  1652. *
  1653. * @return array
  1654. */
  1655. public function get_evaluations(
  1656. $studentId = null,
  1657. $recursive = false,
  1658. $course_code = '',
  1659. $sessionId = 0
  1660. ) {
  1661. $evals = [];
  1662. $course_code = empty($course_code) ? $this->get_course_code() : $course_code;
  1663. $sessionId = empty($sessionId) ? $this->get_session_id() : $sessionId;
  1664. // 1 student
  1665. if (isset($studentId) && !empty($studentId)) {
  1666. // Special case: this is the root
  1667. if ($this->id == 0) {
  1668. $evals = Evaluation::get_evaluations_with_result_for_student(
  1669. 0,
  1670. $studentId
  1671. );
  1672. } else {
  1673. $evals = Evaluation::load(
  1674. null,
  1675. null,
  1676. $course_code,
  1677. $this->id,
  1678. api_is_allowed_to_edit() ? null : 1
  1679. );
  1680. }
  1681. } else {
  1682. // All students
  1683. // course admin
  1684. if ((api_is_allowed_to_edit() || api_is_drh() || api_is_session_admin()) &&
  1685. !api_is_platform_admin()
  1686. ) {
  1687. // root
  1688. if ($this->id == 0) {
  1689. $evals = Evaluation::load(
  1690. null,
  1691. api_get_user_id(),
  1692. null,
  1693. $this->id,
  1694. null
  1695. );
  1696. } elseif (isset($this->course_code) &&
  1697. !empty($this->course_code)
  1698. ) {
  1699. // inside a course
  1700. $evals = Evaluation::load(
  1701. null,
  1702. null,
  1703. $course_code,
  1704. $this->id,
  1705. null
  1706. );
  1707. } else {
  1708. // course independent
  1709. $evals = Evaluation::load(
  1710. null,
  1711. api_get_user_id(),
  1712. null,
  1713. $this->id,
  1714. null
  1715. );
  1716. }
  1717. } else {
  1718. $evals = Evaluation::load(
  1719. null,
  1720. null,
  1721. $course_code,
  1722. $this->id,
  1723. null
  1724. );
  1725. }
  1726. }
  1727. if ($recursive) {
  1728. $subcats = $this->get_subcategories(
  1729. $studentId,
  1730. $course_code,
  1731. $sessionId
  1732. );
  1733. if (!empty($subcats)) {
  1734. foreach ($subcats as $subcat) {
  1735. $subevals = $subcat->get_evaluations(
  1736. $studentId,
  1737. true,
  1738. $course_code
  1739. );
  1740. $evals = array_merge($evals, $subevals);
  1741. }
  1742. }
  1743. }
  1744. return $evals;
  1745. }
  1746. /**
  1747. * Get appropriate links visible for the user.
  1748. *
  1749. * @param int $studentId student id (default: all students)
  1750. * @param bool $recursive process subcategories (default: no recursion)
  1751. * @param string $course_code
  1752. * @param int $sessionId
  1753. *
  1754. * @return array
  1755. */
  1756. public function get_links(
  1757. $studentId = null,
  1758. $recursive = false,
  1759. $course_code = '',
  1760. $sessionId = 0
  1761. ) {
  1762. $links = [];
  1763. $course_code = empty($course_code) ? $this->get_course_code() : $course_code;
  1764. $sessionId = empty($sessionId) ? $this->get_session_id() : $sessionId;
  1765. // no links in root or course independent categories
  1766. if ($this->id == 0) {
  1767. } elseif (isset($studentId)) {
  1768. // 1 student $studentId
  1769. $links = LinkFactory::load(
  1770. null,
  1771. null,
  1772. null,
  1773. null,
  1774. $course_code,
  1775. $this->id,
  1776. api_is_allowed_to_edit() ? null : 1
  1777. );
  1778. } else {
  1779. // All students -> only for course/platform admin
  1780. $links = LinkFactory::load(
  1781. null,
  1782. null,
  1783. null,
  1784. null,
  1785. $course_code,
  1786. $this->id,
  1787. null
  1788. );
  1789. }
  1790. if ($recursive) {
  1791. $subcats = $this->get_subcategories(
  1792. $studentId,
  1793. $course_code,
  1794. $sessionId
  1795. );
  1796. if (!empty($subcats)) {
  1797. /** @var Category $subcat */
  1798. foreach ($subcats as $subcat) {
  1799. $sublinks = $subcat->get_links(
  1800. $studentId,
  1801. false,
  1802. $course_code,
  1803. $sessionId
  1804. );
  1805. $links = array_merge($links, $sublinks);
  1806. }
  1807. }
  1808. }
  1809. return $links;
  1810. }
  1811. /**
  1812. * Get all the categories from with the same given direct parent.
  1813. *
  1814. * @param int $catId Category parent ID
  1815. *
  1816. * @return array Array of Category objects
  1817. */
  1818. public function getCategories($catId)
  1819. {
  1820. $tblGradeCategories = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1821. $sql = 'SELECT * FROM '.$tblGradeCategories.'
  1822. WHERE parent_id = '.intval($catId);
  1823. $result = Database::query($sql);
  1824. $categories = self::create_category_objects_from_sql_result($result);
  1825. return $categories;
  1826. }
  1827. /**
  1828. * Gets the type for the current object.
  1829. *
  1830. * @return string 'C' to represent "Category" object type
  1831. */
  1832. public function get_item_type()
  1833. {
  1834. return 'C';
  1835. }
  1836. /**
  1837. * @param array $skills
  1838. */
  1839. public function set_skills($skills)
  1840. {
  1841. $this->skills = $skills;
  1842. }
  1843. public function get_date()
  1844. {
  1845. return null;
  1846. }
  1847. /**
  1848. * @return string
  1849. */
  1850. public function get_icon_name()
  1851. {
  1852. return 'cat';
  1853. }
  1854. /**
  1855. * Find category by name.
  1856. *
  1857. * @param string $name_mask search string
  1858. *
  1859. * @return array category objects matching the search criterium
  1860. */
  1861. public function find_category($name_mask, $allcat)
  1862. {
  1863. $categories = [];
  1864. foreach ($allcat as $search_cat) {
  1865. if (!(strpos(strtolower($search_cat->get_name()), strtolower($name_mask)) === false)) {
  1866. $categories[] = $search_cat;
  1867. }
  1868. }
  1869. return $categories;
  1870. }
  1871. /**
  1872. * This function, locks a category , only one who can unlock it is
  1873. * the platform administrator.
  1874. *
  1875. * @param int locked 1 or unlocked 0
  1876. *
  1877. * @return bool|null
  1878. * */
  1879. public function lock($locked)
  1880. {
  1881. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1882. $sql = "UPDATE $table SET locked = '".intval($locked)."'
  1883. WHERE id='".intval($this->id)."'";
  1884. Database::query($sql);
  1885. }
  1886. /**
  1887. * @param $locked
  1888. */
  1889. public function lockAllItems($locked)
  1890. {
  1891. if (api_get_setting('gradebook_locking_enabled') == 'true') {
  1892. $this->lock($locked);
  1893. $evals_to_lock = $this->get_evaluations();
  1894. if (!empty($evals_to_lock)) {
  1895. foreach ($evals_to_lock as $item) {
  1896. $item->lock($locked);
  1897. }
  1898. }
  1899. $link_to_lock = $this->get_links();
  1900. if (!empty($link_to_lock)) {
  1901. foreach ($link_to_lock as $item) {
  1902. $item->lock($locked);
  1903. }
  1904. }
  1905. $event_type = LOG_GRADEBOOK_UNLOCKED;
  1906. if ($locked == 1) {
  1907. $event_type = LOG_GRADEBOOK_LOCKED;
  1908. }
  1909. Event::addEvent($event_type, LOG_GRADEBOOK_ID, $this->id);
  1910. }
  1911. }
  1912. /**
  1913. * Generates a certificate for this user if everything matches.
  1914. *
  1915. * @param int $category_id gradebook id
  1916. * @param int $user_id
  1917. * @param bool $sendNotification
  1918. *
  1919. * @return array
  1920. */
  1921. public static function generateUserCertificate(
  1922. $category_id,
  1923. $user_id,
  1924. $sendNotification = false
  1925. ) {
  1926. $user_id = (int) $user_id;
  1927. $category_id = (int) $category_id;
  1928. // Generating the total score for a course
  1929. $cats_course = self::load(
  1930. $category_id,
  1931. null,
  1932. null,
  1933. null,
  1934. null,
  1935. null,
  1936. false
  1937. );
  1938. /** @var Category $category */
  1939. $category = $cats_course[0];
  1940. if (empty($category)) {
  1941. return false;
  1942. }
  1943. $sessionId = $category->get_session_id();
  1944. $courseCode = $category->get_course_code();
  1945. $courseInfo = api_get_course_info($courseCode);
  1946. $courseId = $courseInfo['real_id'];
  1947. $userFinishedCourse = self::userFinishedCourse(
  1948. $user_id,
  1949. $category,
  1950. true
  1951. );
  1952. if (!$userFinishedCourse) {
  1953. return false;
  1954. }
  1955. $skillToolEnabled = Skill::hasAccessToUserSkill(
  1956. api_get_user_id(),
  1957. $user_id
  1958. );
  1959. $userHasSkills = false;
  1960. if ($skillToolEnabled) {
  1961. $skill = new Skill();
  1962. $skill->addSkillToUser(
  1963. $user_id,
  1964. $category,
  1965. $courseId,
  1966. $sessionId
  1967. );
  1968. $objSkillRelUser = new SkillRelUser();
  1969. $userSkills = $objSkillRelUser->getUserSkills(
  1970. $user_id,
  1971. $courseId,
  1972. $sessionId
  1973. );
  1974. $userHasSkills = !empty($userSkills);
  1975. if ($userHasSkills) {
  1976. return [
  1977. 'badge_link' => Display::toolbarButton(
  1978. get_lang('ExportBadges'),
  1979. api_get_path(WEB_CODE_PATH)."gradebook/get_badges.php?user=$user_id",
  1980. 'external-link'
  1981. ),
  1982. ];
  1983. }
  1984. }
  1985. // Block certification links depending gradebook configuration (generate certifications)
  1986. if (empty($category->getGenerateCertificates())) {
  1987. return false;
  1988. }
  1989. $cattotal = self::load($category_id);
  1990. $scoretotal = $cattotal[0]->calc_score($user_id);
  1991. // Do not remove this the gradebook/lib/fe/gradebooktable.class.php
  1992. // file load this variable as a global
  1993. $scoredisplay = ScoreDisplay::instance();
  1994. $my_score_in_gradebook = $scoredisplay->display_score(
  1995. $scoretotal,
  1996. SCORE_SIMPLE
  1997. );
  1998. $my_certificate = GradebookUtils::get_certificate_by_user_id(
  1999. $category->get_id(),
  2000. $user_id
  2001. );
  2002. if (empty($my_certificate)) {
  2003. GradebookUtils::registerUserInfoAboutCertificate(
  2004. $category_id,
  2005. $user_id,
  2006. $my_score_in_gradebook,
  2007. api_get_utc_datetime()
  2008. );
  2009. $my_certificate = GradebookUtils::get_certificate_by_user_id(
  2010. $category->get_id(),
  2011. $user_id
  2012. );
  2013. }
  2014. $html = [];
  2015. if (!empty($my_certificate)) {
  2016. $certificate_obj = new Certificate(
  2017. $my_certificate['id'],
  2018. 0,
  2019. $sendNotification
  2020. );
  2021. $fileWasGenerated = $certificate_obj->isHtmlFileGenerated();
  2022. if (!empty($fileWasGenerated)) {
  2023. $url = api_get_path(WEB_PATH).'certificates/index.php?id='.$my_certificate['id'];
  2024. $certificates = Display::toolbarButton(
  2025. get_lang('DisplayCertificate'),
  2026. $url,
  2027. 'eye',
  2028. 'primary'
  2029. );
  2030. $exportToPDF = Display::url(
  2031. Display::return_icon(
  2032. 'pdf.png',
  2033. get_lang('ExportToPDF'),
  2034. [],
  2035. ICON_SIZE_MEDIUM
  2036. ),
  2037. "$url&action=export"
  2038. );
  2039. $hideExportLink = api_get_setting('hide_certificate_export_link');
  2040. $hideExportLinkStudent = api_get_setting('hide_certificate_export_link_students');
  2041. if ($hideExportLink === 'true' || (api_is_student() && $hideExportLinkStudent === 'true')) {
  2042. $exportToPDF = null;
  2043. }
  2044. $html = [
  2045. 'certificate_link' => $certificates,
  2046. 'pdf_link' => $exportToPDF,
  2047. 'pdf_url' => "$url&action=export",
  2048. ];
  2049. if ($skillToolEnabled && $userHasSkills) {
  2050. $html['badge_link'] = Display::toolbarButton(
  2051. get_lang('ExportBadges'),
  2052. api_get_path(WEB_CODE_PATH)."gradebook/get_badges.php?user=$user_id",
  2053. 'external-link'
  2054. );
  2055. }
  2056. }
  2057. return $html;
  2058. }
  2059. }
  2060. /**
  2061. * @param int $catId
  2062. * @param array $userList
  2063. */
  2064. public static function generateCertificatesInUserList($catId, $userList)
  2065. {
  2066. if (!empty($userList)) {
  2067. foreach ($userList as $userInfo) {
  2068. self::generateUserCertificate($catId, $userInfo['user_id']);
  2069. }
  2070. }
  2071. }
  2072. /**
  2073. * @param int $catId
  2074. * @param array $userList
  2075. */
  2076. public static function exportAllCertificates(
  2077. $catId,
  2078. $userList = []
  2079. ) {
  2080. $orientation = api_get_configuration_value('certificate_pdf_orientation');
  2081. $params['orientation'] = 'landscape';
  2082. if (!empty($orientation)) {
  2083. $params['orientation'] = $orientation;
  2084. }
  2085. $params['left'] = 0;
  2086. $params['right'] = 0;
  2087. $params['top'] = 0;
  2088. $params['bottom'] = 0;
  2089. $page_format = $params['orientation'] == 'landscape' ? 'A4-L' : 'A4';
  2090. $pdf = new PDF($page_format, $params['orientation'], $params);
  2091. $certificate_list = GradebookUtils::get_list_users_certificates($catId, $userList);
  2092. $certificate_path_list = [];
  2093. if (!empty($certificate_list)) {
  2094. foreach ($certificate_list as $index => $value) {
  2095. $list_certificate = GradebookUtils::get_list_gradebook_certificates_by_user_id(
  2096. $value['user_id'],
  2097. $catId
  2098. );
  2099. foreach ($list_certificate as $value_certificate) {
  2100. $certificate_obj = new Certificate($value_certificate['id']);
  2101. $certificate_obj->generate(['hide_print_button' => true]);
  2102. if ($certificate_obj->isHtmlFileGenerated()) {
  2103. $certificate_path_list[] = $certificate_obj->html_file;
  2104. }
  2105. }
  2106. }
  2107. }
  2108. if (!empty($certificate_path_list)) {
  2109. // Print certificates (without the common header/footer/watermark
  2110. // stuff) and return as one multiple-pages PDF
  2111. $pdf->html_to_pdf(
  2112. $certificate_path_list,
  2113. get_lang('Certificates'),
  2114. null,
  2115. false,
  2116. false
  2117. );
  2118. }
  2119. }
  2120. /**
  2121. * @param int $catId
  2122. */
  2123. public static function deleteAllCertificates($catId)
  2124. {
  2125. $certificate_list = GradebookUtils::get_list_users_certificates($catId);
  2126. if (!empty($certificate_list)) {
  2127. foreach ($certificate_list as $index => $value) {
  2128. $list_certificate = GradebookUtils::get_list_gradebook_certificates_by_user_id(
  2129. $value['user_id'],
  2130. $catId
  2131. );
  2132. foreach ($list_certificate as $value_certificate) {
  2133. $certificate_obj = new Certificate($value_certificate['id']);
  2134. $certificate_obj->delete(true);
  2135. }
  2136. }
  2137. }
  2138. }
  2139. /**
  2140. * Check whether a user has finished a course by its gradebook.
  2141. *
  2142. * @param int $userId The user ID
  2143. * @param \Category $category Optional. The gradebook category.
  2144. * To check by the gradebook category
  2145. * @param bool $recalculateScore Whether recalculate the score
  2146. *
  2147. * @return bool
  2148. */
  2149. public static function userFinishedCourse(
  2150. $userId,
  2151. \Category $category,
  2152. $recalculateScore = false
  2153. ) {
  2154. if (empty($category)) {
  2155. return false;
  2156. }
  2157. $currentScore = self::getCurrentScore(
  2158. $userId,
  2159. $category,
  2160. $recalculateScore
  2161. );
  2162. $minCertificateScore = $category->getCertificateMinScore();
  2163. $passedCourse = $currentScore >= $minCertificateScore;
  2164. return $passedCourse;
  2165. }
  2166. /**
  2167. * Get the current score (as percentage) on a gradebook category for a user.
  2168. *
  2169. * @param int $userId The user id
  2170. * @param Category $category The gradebook category
  2171. * @param bool $recalculate
  2172. *
  2173. * @return float The score
  2174. */
  2175. public static function getCurrentScore(
  2176. $userId,
  2177. $category,
  2178. $recalculate = false
  2179. ) {
  2180. if (empty($category)) {
  2181. return 0;
  2182. }
  2183. if ($recalculate) {
  2184. return self::calculateCurrentScore(
  2185. $userId,
  2186. $category
  2187. );
  2188. }
  2189. $resultData = Database::select(
  2190. '*',
  2191. Database::get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_LOG),
  2192. [
  2193. 'where' => [
  2194. 'category_id = ? AND user_id = ?' => [$category->get_id(), $userId],
  2195. ],
  2196. 'order' => 'registered_at DESC',
  2197. 'limit' => '1',
  2198. ],
  2199. 'first'
  2200. );
  2201. if (empty($resultData)) {
  2202. return 0;
  2203. }
  2204. return $resultData['score'];
  2205. }
  2206. /**
  2207. * Register the current score for a user on a category gradebook.
  2208. *
  2209. * @param float $score The achieved score
  2210. * @param int $userId The user id
  2211. * @param int $categoryId The gradebook category
  2212. *
  2213. * @return int The insert id
  2214. */
  2215. public static function registerCurrentScore($score, $userId, $categoryId)
  2216. {
  2217. return Database::insert(
  2218. Database::get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_LOG),
  2219. [
  2220. 'category_id' => intval($categoryId),
  2221. 'user_id' => intval($userId),
  2222. 'score' => api_float_val($score),
  2223. 'registered_at' => api_get_utc_datetime(),
  2224. ]
  2225. );
  2226. }
  2227. /**
  2228. * @return array
  2229. */
  2230. public function getStudentList()
  2231. {
  2232. return $this->studentList;
  2233. }
  2234. /**
  2235. * @param array $list
  2236. */
  2237. public function setStudentList($list)
  2238. {
  2239. $this->studentList = $list;
  2240. }
  2241. /**
  2242. * @return string
  2243. */
  2244. public static function getUrl()
  2245. {
  2246. $url = Session::read('gradebook_dest');
  2247. if (empty($url)) {
  2248. // We guess the link
  2249. $courseInfo = api_get_course_info();
  2250. if (!empty($courseInfo)) {
  2251. return api_get_path(WEB_CODE_PATH).'gradebook/index.php?'.api_get_cidreq().'&';
  2252. } else {
  2253. return api_get_path(WEB_CODE_PATH).'gradebook/gradebook.php?';
  2254. }
  2255. }
  2256. return $url;
  2257. }
  2258. /**
  2259. * Destination is index.php or gradebook.php.
  2260. *
  2261. * @param string $url
  2262. */
  2263. public static function setUrl($url)
  2264. {
  2265. switch ($url) {
  2266. case 'gradebook.php':
  2267. $url = api_get_path(WEB_CODE_PATH).'gradebook/gradebook.php?';
  2268. break;
  2269. case 'index.php':
  2270. $url = api_get_path(WEB_CODE_PATH).'gradebook/index.php?'.api_get_cidreq().'&';
  2271. break;
  2272. }
  2273. Session::write('gradebook_dest', $url);
  2274. }
  2275. /**
  2276. * @return int
  2277. */
  2278. public function getGradeBooksToValidateInDependence()
  2279. {
  2280. return $this->gradeBooksToValidateInDependence;
  2281. }
  2282. /**
  2283. * @param int $value
  2284. *
  2285. * @return Category
  2286. */
  2287. public function setGradeBooksToValidateInDependence($value)
  2288. {
  2289. $this->gradeBooksToValidateInDependence = $value;
  2290. return $this;
  2291. }
  2292. /**
  2293. * @return Category
  2294. */
  2295. private static function create_root_category()
  2296. {
  2297. $cat = new Category();
  2298. $cat->set_id(0);
  2299. $cat->set_name(get_lang('RootCat'));
  2300. $cat->set_description(null);
  2301. $cat->set_user_id(0);
  2302. $cat->set_course_code(null);
  2303. $cat->set_parent_id(null);
  2304. $cat->set_weight(0);
  2305. $cat->set_visible(1);
  2306. $cat->setGenerateCertificates(0);
  2307. $cat->setIsRequirement(false);
  2308. return $cat;
  2309. }
  2310. /**
  2311. * @param Doctrine\DBAL\Driver\Statement|null $result
  2312. *
  2313. * @return array
  2314. */
  2315. private static function create_category_objects_from_sql_result($result)
  2316. {
  2317. $categories = [];
  2318. $allow = api_get_configuration_value('allow_gradebook_stats');
  2319. if ($allow) {
  2320. $em = Database::getManager();
  2321. $repo = $em->getRepository('ChamiloCoreBundle:GradebookCategory');
  2322. }
  2323. while ($data = Database::fetch_array($result)) {
  2324. $cat = new Category();
  2325. $cat->set_id($data['id']);
  2326. $cat->set_name($data['name']);
  2327. $cat->set_description($data['description']);
  2328. $cat->set_user_id($data['user_id']);
  2329. $cat->set_course_code($data['course_code']);
  2330. $cat->set_parent_id($data['parent_id']);
  2331. $cat->set_weight($data['weight']);
  2332. $cat->set_visible($data['visible']);
  2333. $cat->set_session_id($data['session_id']);
  2334. $cat->set_certificate_min_score($data['certif_min_score']);
  2335. $cat->set_grade_model_id($data['grade_model_id']);
  2336. $cat->set_locked($data['locked']);
  2337. $cat->setGenerateCertificates($data['generate_certificates']);
  2338. $cat->setIsRequirement($data['is_requirement']);
  2339. $cat->setCourseListDependency(isset($data['depends']) ? $data['depends'] : []);
  2340. $cat->setMinimumToValidate(isset($data['minimum_to_validate']) ? $data['minimum_to_validate'] : null);
  2341. $cat->setGradeBooksToValidateInDependence(isset($data['gradebooks_to_validate_in_dependence']) ? $data['gradebooks_to_validate_in_dependence'] : null);
  2342. if ($allow) {
  2343. $cat->entity = $repo->find($data['id']);
  2344. }
  2345. $categories[] = $cat;
  2346. }
  2347. return $categories;
  2348. }
  2349. /**
  2350. * Internal function used by get_target_categories().
  2351. *
  2352. * @param array $targets
  2353. * @param int $level
  2354. * @param int $catid
  2355. *
  2356. * @return array
  2357. */
  2358. private function addTargetSubcategories($targets, $level, $catid)
  2359. {
  2360. $subcats = self::load(null, null, null, $catid);
  2361. foreach ($subcats as $cat) {
  2362. if ($this->can_be_moved_to_cat($cat)) {
  2363. $targets[] = [
  2364. $cat->get_id(),
  2365. $cat->get_name(),
  2366. $level + 1,
  2367. ];
  2368. $targets = $this->addTargetSubcategories(
  2369. $targets,
  2370. $level + 1,
  2371. $cat->get_id()
  2372. );
  2373. }
  2374. }
  2375. return $targets;
  2376. }
  2377. /**
  2378. * Internal function used by get_target_categories() and addTargetSubcategories()
  2379. * Can this category be moved to the given category ?
  2380. * Impossible when origin and target are the same... children won't be processed
  2381. * either. (a category can't be moved to one of its own children).
  2382. */
  2383. private function can_be_moved_to_cat($cat)
  2384. {
  2385. return $cat->get_id() != $this->get_id();
  2386. }
  2387. /**
  2388. * Internal function used by move_to_cat().
  2389. */
  2390. private function applyCourseCodeToChildren()
  2391. {
  2392. $cats = self::load(null, null, null, $this->id, null);
  2393. $evals = Evaluation::load(null, null, null, $this->id, null);
  2394. $links = LinkFactory::load(
  2395. null,
  2396. null,
  2397. null,
  2398. null,
  2399. null,
  2400. $this->id,
  2401. null
  2402. );
  2403. /** @var Category $cat */
  2404. foreach ($cats as $cat) {
  2405. $cat->set_course_code($this->get_course_code());
  2406. $cat->save();
  2407. $cat->applyCourseCodeToChildren();
  2408. }
  2409. foreach ($evals as $eval) {
  2410. $eval->set_course_code($this->get_course_code());
  2411. $eval->save();
  2412. }
  2413. foreach ($links as $link) {
  2414. $link->delete();
  2415. }
  2416. }
  2417. /**
  2418. * Internal function used by get_tree().
  2419. *
  2420. * @param int $level
  2421. * @param int|null $visible
  2422. *
  2423. * @return array
  2424. */
  2425. private function add_subtree($targets, $level, $catid, $visible)
  2426. {
  2427. $subcats = self::load(null, null, null, $catid, $visible);
  2428. if (!empty($subcats)) {
  2429. foreach ($subcats as $cat) {
  2430. $targets[] = [
  2431. $cat->get_id(),
  2432. $cat->get_name(),
  2433. $level + 1,
  2434. ];
  2435. $targets = self::add_subtree(
  2436. $targets,
  2437. $level + 1,
  2438. $cat->get_id(),
  2439. $visible
  2440. );
  2441. }
  2442. }
  2443. return $targets;
  2444. }
  2445. /**
  2446. * Calculate the current score on a gradebook category for a user.
  2447. *
  2448. * @param int $userId The user id
  2449. * @param Category $category The gradebook category
  2450. *
  2451. * @return float The score
  2452. */
  2453. private static function calculateCurrentScore(
  2454. $userId,
  2455. $category
  2456. ) {
  2457. if (empty($category)) {
  2458. return 0;
  2459. }
  2460. $courseEvaluations = $category->get_evaluations(
  2461. $userId,
  2462. true
  2463. );
  2464. $courseLinks = $category->get_links($userId, true);
  2465. $evaluationsAndLinks = array_merge($courseEvaluations, $courseLinks);
  2466. $categoryScore = 0;
  2467. for ($i = 0; $i < count($evaluationsAndLinks); $i++) {
  2468. $item = $evaluationsAndLinks[$i];
  2469. $score = $item->calc_score($userId);
  2470. $itemValue = 0;
  2471. if (!empty($score)) {
  2472. $divider = $score[1] == 0 ? 1 : $score[1];
  2473. $itemValue = $score[0] / $divider * $item->get_weight();
  2474. }
  2475. $categoryScore += $itemValue;
  2476. }
  2477. return api_float_val($categoryScore);
  2478. }
  2479. }