category.class.php 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753
  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. public function show_message_resource_delete($course_id)
  717. {
  718. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  719. $sql = 'SELECT count(*) AS num
  720. FROM '.$table.'
  721. WHERE
  722. course_code = "'.Database::escape_string($course_id).'" AND
  723. visible = 3';
  724. $res = Database::query($sql);
  725. $option = Database::fetch_array($res, 'ASSOC');
  726. if ($option['num'] >= 1) {
  727. return '&nbsp;&nbsp;<span class="resource-deleted">(&nbsp;'.get_lang('ResourceDeleted').'&nbsp;)</span>';
  728. } else {
  729. return false;
  730. }
  731. }
  732. /**
  733. * Shows all information of an category.
  734. *
  735. * @param int $categoryId
  736. *
  737. * @return array
  738. */
  739. public function showAllCategoryInfo($categoryId = 0)
  740. {
  741. $categoryId = (int) $categoryId;
  742. if (empty($categoryId)) {
  743. return [];
  744. }
  745. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  746. $sql = 'SELECT * FROM '.$table.'
  747. WHERE id = '.$categoryId;
  748. $result = Database::query($sql);
  749. $row = Database::fetch_array($result, 'ASSOC');
  750. return $row;
  751. }
  752. /**
  753. * Check if a category name (with the same parent category) already exists.
  754. *
  755. * @param string $name name to check (if not given, the name property of this object will be checked)
  756. * @param int $parent parent category
  757. *
  758. * @return bool
  759. */
  760. public function does_name_exist($name, $parent)
  761. {
  762. if (!isset($name)) {
  763. $name = $this->name;
  764. $parent = $this->parent;
  765. }
  766. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  767. $sql = "SELECT count(id) AS number
  768. FROM $table
  769. WHERE name = '".Database::escape_string($name)."'";
  770. if (api_is_allowed_to_edit()) {
  771. $parent = self::load($parent);
  772. $code = $parent[0]->get_course_code();
  773. $courseInfo = api_get_course_info($code);
  774. $courseId = $courseInfo['real_id'];
  775. if (isset($code) && $code != '0') {
  776. $main_course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  777. $sql .= ' AND user_id IN (
  778. SELECT user_id FROM '.$main_course_user_table.'
  779. WHERE c_id = '.$courseId.' AND status = '.COURSEMANAGER.'
  780. )';
  781. } else {
  782. $sql .= ' AND user_id = '.api_get_user_id();
  783. }
  784. } else {
  785. $sql .= ' AND user_id = '.api_get_user_id();
  786. }
  787. if (!isset($parent)) {
  788. $sql .= ' AND parent_id is null';
  789. } else {
  790. $sql .= ' AND parent_id = '.intval($parent);
  791. }
  792. $result = Database::query($sql);
  793. $number = Database::fetch_row($result);
  794. return $number[0] != 0;
  795. }
  796. /**
  797. * Checks if the certificate is available for the given user in this category.
  798. *
  799. * @param int $user_id User ID
  800. *
  801. * @return bool True if conditions match, false if fails
  802. */
  803. public function is_certificate_available($user_id)
  804. {
  805. $score = $this->calc_score(
  806. $user_id,
  807. null,
  808. $this->course_code,
  809. $this->session_id
  810. );
  811. if (isset($score) && isset($score[0])) {
  812. // Get a percentage score to compare to minimum certificate score
  813. // $certification_score = $score[0] / $score[1] * 100;
  814. // Get real score not a percentage.
  815. $certification_score = $score[0];
  816. if ($certification_score >= $this->certificate_min_score) {
  817. return true;
  818. }
  819. }
  820. return false;
  821. }
  822. /**
  823. * Is this category a course ?
  824. * A category is a course if it has a course code and no parent category.
  825. */
  826. public function is_course()
  827. {
  828. return isset($this->course_code) && !empty($this->course_code)
  829. && (!isset($this->parent) || $this->parent == 0);
  830. }
  831. /**
  832. * Calculate the score of this category.
  833. *
  834. * @param int $stud_id student id (default: all students - then the average is returned)
  835. * @param $type
  836. * @param string $course_code
  837. * @param int $session_id
  838. *
  839. * @return array (score sum, weight sum)
  840. * or null if no scores available
  841. */
  842. public function calc_score(
  843. $stud_id = null,
  844. $type = null,
  845. $course_code = '',
  846. $session_id = null
  847. ) {
  848. $key = 'category:'.$this->id.'student:'.(int) $stud_id.'type:'.$type.'course:'.$course_code.'session:'.(int) $session_id;
  849. $useCache = api_get_configuration_value('gradebook_use_apcu_cache');
  850. $cacheAvailable = api_get_configuration_value('apc') && $useCache;
  851. if ($cacheAvailable) {
  852. $cacheDriver = new \Doctrine\Common\Cache\ApcuCache();
  853. if ($cacheDriver->contains($key)) {
  854. return $cacheDriver->fetch($key);
  855. }
  856. }
  857. // Classic
  858. if (!empty($stud_id) && $type == '') {
  859. if (!empty($course_code)) {
  860. $cats = $this->get_subcategories(
  861. $stud_id,
  862. $course_code,
  863. $session_id
  864. );
  865. $evals = $this->get_evaluations($stud_id, false, $course_code);
  866. $links = $this->get_links($stud_id, false, $course_code);
  867. } else {
  868. $cats = $this->get_subcategories($stud_id);
  869. $evals = $this->get_evaluations($stud_id);
  870. $links = $this->get_links($stud_id);
  871. }
  872. // Calculate score
  873. $count = 0;
  874. $ressum = 0;
  875. $weightsum = 0;
  876. if (!empty($cats)) {
  877. /** @var Category $cat */
  878. foreach ($cats as $cat) {
  879. $cat->set_session_id($session_id);
  880. $cat->set_course_code($course_code);
  881. $cat->setStudentList($this->getStudentList());
  882. $score = $cat->calc_score(
  883. $stud_id,
  884. null,
  885. $course_code,
  886. $session_id
  887. );
  888. $catweight = 0;
  889. if ($cat->get_weight() != 0) {
  890. $catweight = $cat->get_weight();
  891. $weightsum += $catweight;
  892. }
  893. if (isset($score) && !empty($score[1]) && !empty($catweight)) {
  894. $ressum += $score[0] / $score[1] * $catweight;
  895. }
  896. }
  897. }
  898. $students = [];
  899. if (!empty($evals)) {
  900. /** @var Evaluation $eval */
  901. foreach ($evals as $eval) {
  902. $eval->setStudentList($this->getStudentList());
  903. $evalres = $eval->calc_score($stud_id, null);
  904. if (isset($evalres) && $eval->get_weight() != 0) {
  905. $evalweight = $eval->get_weight();
  906. $weightsum += $evalweight;
  907. $count++;
  908. if (!empty($evalres[1])) {
  909. $ressum += $evalres[0] / $evalres[1] * $evalweight;
  910. }
  911. } else {
  912. if ($eval->get_weight() != 0) {
  913. $evalweight = $eval->get_weight();
  914. $weightsum += $evalweight;
  915. }
  916. }
  917. }
  918. }
  919. if (!empty($links)) {
  920. /** @var EvalLink|ExerciseLink $link */
  921. foreach ($links as $link) {
  922. $link->setStudentList($this->getStudentList());
  923. if ($session_id) {
  924. $link->set_session_id($session_id);
  925. }
  926. $linkres = $link->calc_score($stud_id, null);
  927. if (!empty($linkres) && $link->get_weight() != 0) {
  928. $students[$stud_id] = $linkres[0];
  929. $linkweight = $link->get_weight();
  930. $link_res_denom = $linkres[1] == 0 ? 1 : $linkres[1];
  931. $count++;
  932. $weightsum += $linkweight;
  933. $ressum += $linkres[0] / $link_res_denom * $linkweight;
  934. } else {
  935. // Adding if result does not exists
  936. if ($link->get_weight() != 0) {
  937. $linkweight = $link->get_weight();
  938. $weightsum += $linkweight;
  939. }
  940. }
  941. }
  942. }
  943. } else {
  944. if (!empty($course_code)) {
  945. $cats = $this->get_subcategories(
  946. null,
  947. $course_code,
  948. $session_id
  949. );
  950. $evals = $this->get_evaluations(null, false, $course_code);
  951. $links = $this->get_links(null, false, $course_code);
  952. } else {
  953. $cats = $this->get_subcategories(null);
  954. $evals = $this->get_evaluations(null);
  955. $links = $this->get_links(null);
  956. }
  957. // Calculate score
  958. $count = 0;
  959. $ressum = 0;
  960. $weightsum = 0;
  961. $bestResult = 0;
  962. if (!empty($cats)) {
  963. /** @var Category $cat */
  964. foreach ($cats as $cat) {
  965. $cat->setStudentList($this->getStudentList());
  966. $score = $cat->calc_score(
  967. null,
  968. $type,
  969. $course_code,
  970. $session_id
  971. );
  972. $catweight = 0;
  973. if ($cat->get_weight() != 0) {
  974. $catweight = $cat->get_weight();
  975. $weightsum += $catweight;
  976. }
  977. if (isset($score) && !empty($score[1]) && !empty($catweight)) {
  978. $ressum += $score[0] / $score[1] * $catweight;
  979. if ($ressum > $bestResult) {
  980. $bestResult = $ressum;
  981. }
  982. }
  983. }
  984. }
  985. if (!empty($evals)) {
  986. /** @var Evaluation $eval */
  987. foreach ($evals as $eval) {
  988. $evalres = $eval->calc_score(null, $type);
  989. $eval->setStudentList($this->getStudentList());
  990. if (isset($evalres) && $eval->get_weight() != 0) {
  991. $evalweight = $eval->get_weight();
  992. $weightsum += $evalweight;
  993. $count++;
  994. if (!empty($evalres[1])) {
  995. $ressum += $evalres[0] / $evalres[1] * $evalweight;
  996. }
  997. if ($ressum > $bestResult) {
  998. $bestResult = $ressum;
  999. }
  1000. } else {
  1001. if ($eval->get_weight() != 0) {
  1002. $evalweight = $eval->get_weight();
  1003. $weightsum += $evalweight;
  1004. }
  1005. }
  1006. }
  1007. }
  1008. if (!empty($links)) {
  1009. /** @var EvalLink|ExerciseLink $link */
  1010. foreach ($links as $link) {
  1011. $link->setStudentList($this->getStudentList());
  1012. if ($session_id) {
  1013. $link->set_session_id($session_id);
  1014. }
  1015. $linkres = $link->calc_score($stud_id, $type);
  1016. if (!empty($linkres) && $link->get_weight() != 0) {
  1017. $students[$stud_id] = $linkres[0];
  1018. $linkweight = $link->get_weight();
  1019. $link_res_denom = $linkres[1] == 0 ? 1 : $linkres[1];
  1020. $count++;
  1021. $weightsum += $linkweight;
  1022. $ressum += $linkres[0] / $link_res_denom * $linkweight;
  1023. if ($ressum > $bestResult) {
  1024. $bestResult = $ressum;
  1025. }
  1026. } else {
  1027. // Adding if result does not exists
  1028. if ($link->get_weight() != 0) {
  1029. $linkweight = $link->get_weight();
  1030. $weightsum += $linkweight;
  1031. }
  1032. }
  1033. }
  1034. }
  1035. }
  1036. switch ($type) {
  1037. case 'best':
  1038. if (empty($bestResult)) {
  1039. if ($cacheAvailable) {
  1040. $cacheDriver->save($key, null);
  1041. }
  1042. return null;
  1043. }
  1044. if ($cacheAvailable) {
  1045. $cacheDriver->save($key, [$bestResult, $weightsum]);
  1046. }
  1047. return [$bestResult, $weightsum];
  1048. break;
  1049. case 'average':
  1050. if (empty($ressum)) {
  1051. if ($cacheAvailable) {
  1052. $cacheDriver->save($key, null);
  1053. }
  1054. return null;
  1055. }
  1056. if ($cacheAvailable) {
  1057. $cacheDriver->save($key, [$ressum, $weightsum]);
  1058. }
  1059. return [$ressum, $weightsum];
  1060. break;
  1061. case 'ranking':
  1062. // category ranking is calculated in gradebook_data_generator.class.php
  1063. // function get_data
  1064. return null;
  1065. return AbstractLink::getCurrentUserRanking($stud_id, []);
  1066. break;
  1067. default:
  1068. if ($cacheAvailable) {
  1069. $cacheDriver->save($key, [$ressum, $weightsum]);
  1070. }
  1071. return [$ressum, $weightsum];
  1072. break;
  1073. }
  1074. }
  1075. /**
  1076. * Delete this category and every subcategory, evaluation and result inside.
  1077. */
  1078. public function delete_all()
  1079. {
  1080. $cats = self::load(null, null, $this->course_code, $this->id, null);
  1081. $evals = Evaluation::load(
  1082. null,
  1083. null,
  1084. $this->course_code,
  1085. $this->id,
  1086. null
  1087. );
  1088. $links = LinkFactory::load(
  1089. null,
  1090. null,
  1091. null,
  1092. null,
  1093. $this->course_code,
  1094. $this->id,
  1095. null
  1096. );
  1097. if (!empty($cats)) {
  1098. /** @var Category $cat */
  1099. foreach ($cats as $cat) {
  1100. $cat->delete_all();
  1101. $cat->delete();
  1102. }
  1103. }
  1104. if (!empty($evals)) {
  1105. /** @var Evaluation $eval */
  1106. foreach ($evals as $eval) {
  1107. $eval->delete_with_results();
  1108. }
  1109. }
  1110. if (!empty($links)) {
  1111. /** @var AbstractLink $link */
  1112. foreach ($links as $link) {
  1113. $link->delete();
  1114. }
  1115. }
  1116. $this->delete();
  1117. }
  1118. /**
  1119. * Return array of Category objects where a student is subscribed to.
  1120. *
  1121. * @param int $stud_id
  1122. * @param string $course_code
  1123. * @param int $session_id
  1124. *
  1125. * @return array
  1126. */
  1127. public function get_root_categories_for_student(
  1128. $stud_id,
  1129. $course_code = null,
  1130. $session_id = null
  1131. ) {
  1132. $main_course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1133. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  1134. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1135. $course_code = Database::escape_string($course_code);
  1136. $session_id = (int) $session_id;
  1137. $sql = "SELECT * FROM $table WHERE parent_id = 0";
  1138. if (!api_is_allowed_to_edit()) {
  1139. $sql .= ' AND visible = 1';
  1140. //proceed with checks on optional parameters course & session
  1141. if (!empty($course_code)) {
  1142. // TODO: considering it highly improbable that a user would get here
  1143. // if he doesn't have the rights to view this course and this
  1144. // session, we don't check his registration to these, but this
  1145. // could be an improvement
  1146. if (!empty($session_id)) {
  1147. $sql .= " AND course_code = '".$course_code."' AND session_id = ".$session_id;
  1148. } else {
  1149. $sql .= " AND course_code = '".$course_code."' AND session_id is null OR session_id=0";
  1150. }
  1151. } else {
  1152. //no optional parameter, proceed as usual
  1153. $sql .= ' AND course_code in
  1154. (
  1155. SELECT c.code
  1156. FROM '.$main_course_user_table.' cu INNER JOIN '.$courseTable.' c
  1157. ON (cu.c_id = c.id)
  1158. WHERE cu.user_id = '.intval($stud_id).'
  1159. AND cu.status = '.STUDENT.'
  1160. )';
  1161. }
  1162. } elseif (api_is_allowed_to_edit() && !api_is_platform_admin()) {
  1163. //proceed with checks on optional parameters course & session
  1164. if (!empty($course_code)) {
  1165. // TODO: considering it highly improbable that a user would get here
  1166. // if he doesn't have the rights to view this course and this
  1167. // session, we don't check his registration to these, but this
  1168. // could be an improvement
  1169. $sql .= " AND course_code = '".$course_code."'";
  1170. if (!empty($session_id)) {
  1171. $sql .= " AND session_id = ".$session_id;
  1172. } else {
  1173. $sql .= 'AND session_id IS NULL OR session_id = 0';
  1174. }
  1175. } else {
  1176. $sql .= ' AND course_code IN
  1177. (
  1178. SELECT c.code
  1179. FROM '.$main_course_user_table.' cu INNER JOIN '.$courseTable.' c
  1180. ON (cu.c_id = c.id)
  1181. WHERE
  1182. cu.user_id = '.api_get_user_id().' AND
  1183. cu.status = '.COURSEMANAGER.'
  1184. )';
  1185. }
  1186. } elseif (api_is_platform_admin()) {
  1187. if (isset($session_id) && $session_id != 0) {
  1188. $sql .= ' AND session_id='.$session_id;
  1189. } else {
  1190. $sql .= ' AND coalesce(session_id,0)=0';
  1191. }
  1192. }
  1193. $result = Database::query($sql);
  1194. $cats = self::create_category_objects_from_sql_result($result);
  1195. // course independent categories
  1196. if (empty($course_code)) {
  1197. $cats = $this->getIndependentCategoriesWithStudentResult(
  1198. 0,
  1199. $stud_id,
  1200. $cats
  1201. );
  1202. }
  1203. return $cats;
  1204. }
  1205. /**
  1206. * Return array of Category objects where a teacher is admin for.
  1207. *
  1208. * @param int $user_id (to return everything, use 'null' here)
  1209. * @param string $course_code (optional)
  1210. * @param int $session_id (optional)
  1211. *
  1212. * @return array
  1213. */
  1214. public function get_root_categories_for_teacher(
  1215. $user_id,
  1216. $course_code = null,
  1217. $session_id = null
  1218. ) {
  1219. if ($user_id == null) {
  1220. return self::load(null, null, $course_code, 0, null, $session_id);
  1221. }
  1222. $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
  1223. $main_course_user_table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1224. $tbl_grade_categories = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1225. $sql = 'SELECT * FROM '.$tbl_grade_categories.'
  1226. WHERE parent_id = 0 ';
  1227. if (!empty($course_code)) {
  1228. $sql .= " AND course_code = '".Database::escape_string($course_code)."' ";
  1229. if (!empty($session_id)) {
  1230. $sql .= " AND session_id = ".(int) $session_id;
  1231. }
  1232. } else {
  1233. $sql .= ' AND course_code in
  1234. (
  1235. SELECT c.code
  1236. FROM '.$main_course_user_table.' cu
  1237. INNER JOIN '.$courseTable.' c
  1238. ON (cu.c_id = c.id)
  1239. WHERE user_id = '.intval($user_id).'
  1240. )';
  1241. }
  1242. $result = Database::query($sql);
  1243. $cats = self::create_category_objects_from_sql_result($result);
  1244. // course independent categories
  1245. if (isset($course_code)) {
  1246. $indcats = self::load(
  1247. null,
  1248. $user_id,
  1249. $course_code,
  1250. 0,
  1251. null,
  1252. $session_id
  1253. );
  1254. $cats = array_merge($cats, $indcats);
  1255. }
  1256. return $cats;
  1257. }
  1258. /**
  1259. * Can this category be moved to somewhere else ?
  1260. * The root and courses cannot be moved.
  1261. *
  1262. * @return bool
  1263. */
  1264. public function is_movable()
  1265. {
  1266. return !(!isset($this->id) || $this->id == 0 || $this->is_course());
  1267. }
  1268. /**
  1269. * Generate an array of possible categories where this category can be moved to.
  1270. * Notice: its own parent will be included in the list: it's up to the frontend
  1271. * to disable this element.
  1272. *
  1273. * @return array 2-dimensional array - every element contains 3 subelements (id, name, level)
  1274. */
  1275. public function get_target_categories()
  1276. {
  1277. // the root or a course -> not movable
  1278. if (!$this->is_movable()) {
  1279. return null;
  1280. } else {
  1281. // otherwise:
  1282. // - course independent category
  1283. // -> movable to root or other independent categories
  1284. // - category inside a course
  1285. // -> movable to root, independent categories or categories inside the course
  1286. $user = api_is_platform_admin() ? null : api_get_user_id();
  1287. $targets = [];
  1288. $level = 0;
  1289. $root = [0, get_lang('RootCat'), $level];
  1290. $targets[] = $root;
  1291. if (isset($this->course_code) && !empty($this->course_code)) {
  1292. $crscats = self::load(null, null, $this->course_code, 0);
  1293. foreach ($crscats as $cat) {
  1294. if ($this->can_be_moved_to_cat($cat)) {
  1295. $targets[] = [
  1296. $cat->get_id(),
  1297. $cat->get_name(),
  1298. $level + 1,
  1299. ];
  1300. $targets = $this->addTargetSubcategories(
  1301. $targets,
  1302. $level + 1,
  1303. $cat->get_id()
  1304. );
  1305. }
  1306. }
  1307. }
  1308. $indcats = self::load(null, $user, 0, 0);
  1309. foreach ($indcats as $cat) {
  1310. if ($this->can_be_moved_to_cat($cat)) {
  1311. $targets[] = [$cat->get_id(), $cat->get_name(), $level + 1];
  1312. $targets = $this->addTargetSubcategories(
  1313. $targets,
  1314. $level + 1,
  1315. $cat->get_id()
  1316. );
  1317. }
  1318. }
  1319. return $targets;
  1320. }
  1321. }
  1322. /**
  1323. * Move this category to the given category.
  1324. * If this category moves from inside a course to outside,
  1325. * its course code must be changed, as well as the course code
  1326. * of all underlying categories and evaluations. All links will
  1327. * be deleted as well !
  1328. */
  1329. public function move_to_cat($cat)
  1330. {
  1331. $this->set_parent_id($cat->get_id());
  1332. if ($this->get_course_code() != $cat->get_course_code()) {
  1333. $this->set_course_code($cat->get_course_code());
  1334. $this->applyCourseCodeToChildren();
  1335. }
  1336. $this->save();
  1337. }
  1338. /**
  1339. * Generate an array of all categories the user can navigate to.
  1340. */
  1341. public function get_tree()
  1342. {
  1343. $targets = [];
  1344. $level = 0;
  1345. $root = [0, get_lang('RootCat'), $level];
  1346. $targets[] = $root;
  1347. // course or platform admin
  1348. if (api_is_allowed_to_edit()) {
  1349. $user = api_is_platform_admin() ? null : api_get_user_id();
  1350. $cats = self::get_root_categories_for_teacher($user);
  1351. foreach ($cats as $cat) {
  1352. $targets[] = [
  1353. $cat->get_id(),
  1354. $cat->get_name(),
  1355. $level + 1,
  1356. ];
  1357. $targets = $this->add_subtree(
  1358. $targets,
  1359. $level + 1,
  1360. $cat->get_id(),
  1361. null
  1362. );
  1363. }
  1364. } else {
  1365. // student
  1366. $cats = $this->get_root_categories_for_student(api_get_user_id());
  1367. foreach ($cats as $cat) {
  1368. $targets[] = [
  1369. $cat->get_id(),
  1370. $cat->get_name(),
  1371. $level + 1,
  1372. ];
  1373. $targets = $this->add_subtree(
  1374. $targets,
  1375. $level + 1,
  1376. $cat->get_id(),
  1377. 1
  1378. );
  1379. }
  1380. }
  1381. return $targets;
  1382. }
  1383. /**
  1384. * Generate an array of courses that a teacher hasn't created a category for.
  1385. *
  1386. * @param int $user_id
  1387. *
  1388. * @return array 2-dimensional array - every element contains 2 subelements (code, title)
  1389. */
  1390. public function get_not_created_course_categories($user_id)
  1391. {
  1392. $tbl_main_courses = Database::get_main_table(TABLE_MAIN_COURSE);
  1393. $tbl_main_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1394. $tbl_grade_categories = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1395. $sql = 'SELECT DISTINCT(code), title
  1396. FROM '.$tbl_main_courses.' cc, '.$tbl_main_course_user.' cu
  1397. WHERE
  1398. cc.id = cu.c_id AND
  1399. cu.status = '.COURSEMANAGER;
  1400. if (!api_is_platform_admin()) {
  1401. $sql .= ' AND cu.user_id = '.$user_id;
  1402. }
  1403. $sql .= ' AND cc.code NOT IN
  1404. (
  1405. SELECT course_code FROM '.$tbl_grade_categories.'
  1406. WHERE
  1407. parent_id = 0 AND
  1408. course_code IS NOT NULL
  1409. )';
  1410. $result = Database::query($sql);
  1411. $cats = [];
  1412. while ($data = Database::fetch_array($result)) {
  1413. $cats[] = [$data['code'], $data['title']];
  1414. }
  1415. return $cats;
  1416. }
  1417. /**
  1418. * Generate an array of all courses that a teacher is admin of.
  1419. *
  1420. * @param int $user_id
  1421. *
  1422. * @return array 2-dimensional array - every element contains 2 subelements (code, title)
  1423. */
  1424. public function get_all_courses($user_id)
  1425. {
  1426. $tbl_main_courses = Database::get_main_table(TABLE_MAIN_COURSE);
  1427. $tbl_main_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
  1428. $sql = 'SELECT DISTINCT(code), title
  1429. FROM '.$tbl_main_courses.' cc, '.$tbl_main_course_user.' cu
  1430. WHERE cc.id = cu.c_id AND cu.status = '.COURSEMANAGER;
  1431. if (!api_is_platform_admin()) {
  1432. $sql .= ' AND cu.user_id = '.intval($user_id);
  1433. }
  1434. $result = Database::query($sql);
  1435. $cats = [];
  1436. while ($data = Database::fetch_array($result)) {
  1437. $cats[] = [$data['code'], $data['title']];
  1438. }
  1439. return $cats;
  1440. }
  1441. /**
  1442. * Apply the same visibility to every subcategory, evaluation and link.
  1443. */
  1444. public function apply_visibility_to_children()
  1445. {
  1446. $cats = self::load(null, null, null, $this->id, null);
  1447. $evals = Evaluation::load(null, null, null, $this->id, null);
  1448. $links = LinkFactory::load(
  1449. null,
  1450. null,
  1451. null,
  1452. null,
  1453. null,
  1454. $this->id,
  1455. null
  1456. );
  1457. if (!empty($cats)) {
  1458. foreach ($cats as $cat) {
  1459. $cat->set_visible($this->is_visible());
  1460. $cat->save();
  1461. $cat->apply_visibility_to_children();
  1462. }
  1463. }
  1464. if (!empty($evals)) {
  1465. foreach ($evals as $eval) {
  1466. $eval->set_visible($this->is_visible());
  1467. $eval->save();
  1468. }
  1469. }
  1470. if (!empty($links)) {
  1471. foreach ($links as $link) {
  1472. $link->set_visible($this->is_visible());
  1473. $link->save();
  1474. }
  1475. }
  1476. }
  1477. /**
  1478. * Check if a category contains evaluations with a result for a given student.
  1479. *
  1480. * @param int $studentId
  1481. *
  1482. * @return bool
  1483. */
  1484. public function hasEvaluationsWithStudentResults($studentId)
  1485. {
  1486. $evals = Evaluation::get_evaluations_with_result_for_student(
  1487. $this->id,
  1488. $studentId
  1489. );
  1490. if (count($evals) != 0) {
  1491. return true;
  1492. } else {
  1493. $cats = self::load(
  1494. null,
  1495. null,
  1496. null,
  1497. $this->id,
  1498. api_is_allowed_to_edit() ? null : 1
  1499. );
  1500. /** @var Category $cat */
  1501. foreach ($cats as $cat) {
  1502. if ($cat->hasEvaluationsWithStudentResults($studentId)) {
  1503. return true;
  1504. }
  1505. }
  1506. return false;
  1507. }
  1508. }
  1509. /**
  1510. * Retrieve all categories inside a course independent category
  1511. * that should be visible to a student.
  1512. *
  1513. * @param int $categoryId parent category
  1514. * @param int $studentId
  1515. * @param array $cats optional: if defined, the categories will be added to this array
  1516. *
  1517. * @return array
  1518. */
  1519. public function getIndependentCategoriesWithStudentResult(
  1520. $categoryId,
  1521. $studentId,
  1522. $cats = []
  1523. ) {
  1524. $creator = api_is_allowed_to_edit() && !api_is_platform_admin() ? api_get_user_id() : null;
  1525. $categories = self::load(
  1526. null,
  1527. $creator,
  1528. '0',
  1529. $categoryId,
  1530. api_is_allowed_to_edit() ? null : 1
  1531. );
  1532. if (!empty($categories)) {
  1533. /** @var Category $category */
  1534. foreach ($categories as $category) {
  1535. if ($category->hasEvaluationsWithStudentResults($studentId)) {
  1536. $cats[] = $category;
  1537. }
  1538. }
  1539. }
  1540. return $cats;
  1541. }
  1542. /**
  1543. * Return the session id (in any case, even if it's null or 0).
  1544. *
  1545. * @return int Session id (can be null)
  1546. */
  1547. public function get_session_id()
  1548. {
  1549. return $this->session_id;
  1550. }
  1551. /**
  1552. * Get appropriate subcategories visible for the user (and optionally the course and session).
  1553. *
  1554. * @param int $studentId student id (default: all students)
  1555. * @param string $course_code Course code (optional)
  1556. * @param int $session_id Session ID (optional)
  1557. * @param bool $order
  1558. *
  1559. * @return array Array of subcategories
  1560. */
  1561. public function get_subcategories(
  1562. $studentId = null,
  1563. $course_code = null,
  1564. $session_id = null,
  1565. $order = null
  1566. ) {
  1567. // 1 student
  1568. if (isset($studentId)) {
  1569. // Special case: this is the root
  1570. if ($this->id == 0) {
  1571. return $this->get_root_categories_for_student($studentId, $course_code, $session_id);
  1572. } else {
  1573. return self::load(
  1574. null,
  1575. null,
  1576. $course_code,
  1577. $this->id,
  1578. api_is_allowed_to_edit() ? null : 1,
  1579. $session_id,
  1580. $order
  1581. );
  1582. }
  1583. } else {
  1584. // All students
  1585. // Course admin
  1586. if (api_is_allowed_to_edit() && !api_is_platform_admin()) {
  1587. // root
  1588. if ($this->id == 0) {
  1589. // inside a course
  1590. return $this->get_root_categories_for_teacher(
  1591. api_get_user_id(),
  1592. $course_code,
  1593. $session_id,
  1594. false
  1595. );
  1596. } elseif (!empty($this->course_code)) {
  1597. return self::load(
  1598. null,
  1599. null,
  1600. $this->course_code,
  1601. $this->id,
  1602. null,
  1603. $session_id,
  1604. $order
  1605. );
  1606. } elseif (!empty($course_code)) {
  1607. // course independent
  1608. return self::load(
  1609. null,
  1610. null,
  1611. $course_code,
  1612. $this->id,
  1613. null,
  1614. $session_id,
  1615. $order
  1616. );
  1617. } else {
  1618. return self::load(
  1619. null,
  1620. api_get_user_id(),
  1621. 0,
  1622. $this->id,
  1623. null
  1624. );
  1625. }
  1626. } elseif (api_is_platform_admin()) {
  1627. // platform admin
  1628. // we explicitly avoid listing subcats from another session
  1629. return self::load(
  1630. null,
  1631. null,
  1632. $course_code,
  1633. $this->id,
  1634. null,
  1635. $session_id,
  1636. $order
  1637. );
  1638. }
  1639. }
  1640. return [];
  1641. }
  1642. /**
  1643. * Get appropriate evaluations visible for the user.
  1644. *
  1645. * @param int $studentId student id (default: all students)
  1646. * @param bool $recursive process subcategories (default: no recursion)
  1647. * @param string $course_code
  1648. * @param int $sessionId
  1649. *
  1650. * @return array
  1651. */
  1652. public function get_evaluations(
  1653. $studentId = null,
  1654. $recursive = false,
  1655. $course_code = '',
  1656. $sessionId = 0
  1657. ) {
  1658. $evals = [];
  1659. $course_code = empty($course_code) ? $this->get_course_code() : $course_code;
  1660. $sessionId = empty($sessionId) ? $this->get_session_id() : $sessionId;
  1661. // 1 student
  1662. if (isset($studentId) && !empty($studentId)) {
  1663. // Special case: this is the root
  1664. if ($this->id == 0) {
  1665. $evals = Evaluation::get_evaluations_with_result_for_student(
  1666. 0,
  1667. $studentId
  1668. );
  1669. } else {
  1670. $evals = Evaluation::load(
  1671. null,
  1672. null,
  1673. $course_code,
  1674. $this->id,
  1675. api_is_allowed_to_edit() ? null : 1
  1676. );
  1677. }
  1678. } else {
  1679. // All students
  1680. // course admin
  1681. if ((api_is_allowed_to_edit() || api_is_drh() || api_is_session_admin()) &&
  1682. !api_is_platform_admin()
  1683. ) {
  1684. // root
  1685. if ($this->id == 0) {
  1686. $evals = Evaluation::load(
  1687. null,
  1688. api_get_user_id(),
  1689. null,
  1690. $this->id,
  1691. null
  1692. );
  1693. } elseif (isset($this->course_code) &&
  1694. !empty($this->course_code)
  1695. ) {
  1696. // inside a course
  1697. $evals = Evaluation::load(
  1698. null,
  1699. null,
  1700. $course_code,
  1701. $this->id,
  1702. null
  1703. );
  1704. } else {
  1705. // course independent
  1706. $evals = Evaluation::load(
  1707. null,
  1708. api_get_user_id(),
  1709. null,
  1710. $this->id,
  1711. null
  1712. );
  1713. }
  1714. } else {
  1715. $evals = Evaluation::load(
  1716. null,
  1717. null,
  1718. $course_code,
  1719. $this->id,
  1720. null
  1721. );
  1722. }
  1723. }
  1724. if ($recursive) {
  1725. $subcats = $this->get_subcategories(
  1726. $studentId,
  1727. $course_code,
  1728. $sessionId
  1729. );
  1730. if (!empty($subcats)) {
  1731. foreach ($subcats as $subcat) {
  1732. $subevals = $subcat->get_evaluations(
  1733. $studentId,
  1734. true,
  1735. $course_code
  1736. );
  1737. $evals = array_merge($evals, $subevals);
  1738. }
  1739. }
  1740. }
  1741. return $evals;
  1742. }
  1743. /**
  1744. * Get appropriate links visible for the user.
  1745. *
  1746. * @param int $studentId student id (default: all students)
  1747. * @param bool $recursive process subcategories (default: no recursion)
  1748. * @param string $course_code
  1749. * @param int $sessionId
  1750. *
  1751. * @return array
  1752. */
  1753. public function get_links(
  1754. $studentId = null,
  1755. $recursive = false,
  1756. $course_code = '',
  1757. $sessionId = 0
  1758. ) {
  1759. $links = [];
  1760. $course_code = empty($course_code) ? $this->get_course_code() : $course_code;
  1761. $sessionId = empty($sessionId) ? $this->get_session_id() : $sessionId;
  1762. // no links in root or course independent categories
  1763. if ($this->id == 0) {
  1764. } elseif (isset($studentId)) {
  1765. // 1 student $studentId
  1766. $links = LinkFactory::load(
  1767. null,
  1768. null,
  1769. null,
  1770. null,
  1771. $course_code,
  1772. $this->id,
  1773. api_is_allowed_to_edit() ? null : 1
  1774. );
  1775. } else {
  1776. // All students -> only for course/platform admin
  1777. $links = LinkFactory::load(
  1778. null,
  1779. null,
  1780. null,
  1781. null,
  1782. $course_code,
  1783. $this->id,
  1784. null
  1785. );
  1786. }
  1787. if ($recursive) {
  1788. $subcats = $this->get_subcategories(
  1789. $studentId,
  1790. $course_code,
  1791. $sessionId
  1792. );
  1793. if (!empty($subcats)) {
  1794. /** @var Category $subcat */
  1795. foreach ($subcats as $subcat) {
  1796. $sublinks = $subcat->get_links(
  1797. $studentId,
  1798. false,
  1799. $course_code,
  1800. $sessionId
  1801. );
  1802. $links = array_merge($links, $sublinks);
  1803. }
  1804. }
  1805. }
  1806. return $links;
  1807. }
  1808. /**
  1809. * Get all the categories from with the same given direct parent.
  1810. *
  1811. * @param int $catId Category parent ID
  1812. *
  1813. * @return array Array of Category objects
  1814. */
  1815. public function getCategories($catId)
  1816. {
  1817. $tblGradeCategories = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1818. $sql = 'SELECT * FROM '.$tblGradeCategories.'
  1819. WHERE parent_id = '.intval($catId);
  1820. $result = Database::query($sql);
  1821. $categories = self::create_category_objects_from_sql_result($result);
  1822. return $categories;
  1823. }
  1824. /**
  1825. * Gets the type for the current object.
  1826. *
  1827. * @return string 'C' to represent "Category" object type
  1828. */
  1829. public function get_item_type()
  1830. {
  1831. return 'C';
  1832. }
  1833. /**
  1834. * @param array $skills
  1835. */
  1836. public function set_skills($skills)
  1837. {
  1838. $this->skills = $skills;
  1839. }
  1840. public function get_date()
  1841. {
  1842. return null;
  1843. }
  1844. /**
  1845. * @return string
  1846. */
  1847. public function get_icon_name()
  1848. {
  1849. return 'cat';
  1850. }
  1851. /**
  1852. * Find category by name.
  1853. *
  1854. * @param string $name_mask search string
  1855. *
  1856. * @return array category objects matching the search criterium
  1857. */
  1858. public function find_category($name_mask, $allcat)
  1859. {
  1860. $categories = [];
  1861. foreach ($allcat as $search_cat) {
  1862. if (!(strpos(strtolower($search_cat->get_name()), strtolower($name_mask)) === false)) {
  1863. $categories[] = $search_cat;
  1864. }
  1865. }
  1866. return $categories;
  1867. }
  1868. /**
  1869. * This function, locks a category , only one who can unlock it is
  1870. * the platform administrator.
  1871. *
  1872. * @param int locked 1 or unlocked 0
  1873. *
  1874. * @return bool|null
  1875. * */
  1876. public function lock($locked)
  1877. {
  1878. $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
  1879. $sql = "UPDATE $table SET locked = '".intval($locked)."'
  1880. WHERE id='".intval($this->id)."'";
  1881. Database::query($sql);
  1882. }
  1883. /**
  1884. * @param $locked
  1885. */
  1886. public function lockAllItems($locked)
  1887. {
  1888. if (api_get_setting('gradebook_locking_enabled') == 'true') {
  1889. $this->lock($locked);
  1890. $evals_to_lock = $this->get_evaluations();
  1891. if (!empty($evals_to_lock)) {
  1892. foreach ($evals_to_lock as $item) {
  1893. $item->lock($locked);
  1894. }
  1895. }
  1896. $link_to_lock = $this->get_links();
  1897. if (!empty($link_to_lock)) {
  1898. foreach ($link_to_lock as $item) {
  1899. $item->lock($locked);
  1900. }
  1901. }
  1902. $event_type = LOG_GRADEBOOK_UNLOCKED;
  1903. if ($locked == 1) {
  1904. $event_type = LOG_GRADEBOOK_LOCKED;
  1905. }
  1906. Event::addEvent($event_type, LOG_GRADEBOOK_ID, $this->id);
  1907. }
  1908. }
  1909. /**
  1910. * Generates a certificate for this user if everything matches.
  1911. *
  1912. * @param int $category_id gradebook id
  1913. * @param int $user_id
  1914. * @param bool $sendNotification
  1915. *
  1916. * @return array
  1917. */
  1918. public static function generateUserCertificate(
  1919. $category_id,
  1920. $user_id,
  1921. $sendNotification = false
  1922. ) {
  1923. // Generating the total score for a course
  1924. $cats_course = self::load(
  1925. $category_id,
  1926. null,
  1927. null,
  1928. null,
  1929. null,
  1930. null,
  1931. false
  1932. );
  1933. /** @var Category $category */
  1934. $category = $cats_course[0];
  1935. if (empty($category)) {
  1936. return false;
  1937. }
  1938. // Block certification links depending gradebook configuration (generate certifications)
  1939. if (empty($category->getGenerateCertificates())) {
  1940. return false;
  1941. }
  1942. $sessionId = $category->get_session_id();
  1943. $courseCode = $category->get_course_code();
  1944. $courseInfo = api_get_course_info($courseCode);
  1945. $courseId = $courseInfo['real_id'];
  1946. //@todo move these in a function
  1947. $sum_categories_weight_array = [];
  1948. if (isset($cats_course) && !empty($cats_course)) {
  1949. $categories = self::load(null, null, null, $category_id);
  1950. if (!empty($categories)) {
  1951. foreach ($categories as $subCategory) {
  1952. $sum_categories_weight_array[$subCategory->get_id()] = $subCategory->get_weight();
  1953. }
  1954. } else {
  1955. $sum_categories_weight_array[$category_id] = $cats_course[0]->get_weight();
  1956. }
  1957. }
  1958. $cattotal = self::load($category_id);
  1959. $scoretotal = $cattotal[0]->calc_score($user_id);
  1960. // Do not remove this the gradebook/lib/fe/gradebooktable.class.php
  1961. // file load this variable as a global
  1962. $scoredisplay = ScoreDisplay::instance();
  1963. $my_score_in_gradebook = $scoredisplay->display_score(
  1964. $scoretotal,
  1965. SCORE_SIMPLE
  1966. );
  1967. $userFinishedCourse = self::userFinishedCourse(
  1968. $user_id,
  1969. $cats_course[0],
  1970. true
  1971. );
  1972. if (!$userFinishedCourse) {
  1973. return false;
  1974. }
  1975. $skillToolEnabled = Skill::hasAccessToUserSkill(
  1976. api_get_user_id(),
  1977. $user_id
  1978. );
  1979. $userHasSkills = false;
  1980. if ($skillToolEnabled) {
  1981. $skill = new Skill();
  1982. $skill->addSkillToUser(
  1983. $user_id,
  1984. $category_id,
  1985. $courseId,
  1986. $sessionId
  1987. );
  1988. $objSkillRelUser = new SkillRelUser();
  1989. $userSkills = $objSkillRelUser->getUserSkills(
  1990. $user_id,
  1991. $courseId,
  1992. $sessionId
  1993. );
  1994. $userHasSkills = !empty($userSkills);
  1995. if (!$category->getGenerateCertificates() && $userHasSkills) {
  1996. return [
  1997. 'badge_link' => Display::toolbarButton(
  1998. get_lang('ExportBadges'),
  1999. api_get_path(WEB_CODE_PATH)."gradebook/get_badges.php?user=$user_id",
  2000. 'external-link'
  2001. ),
  2002. ];
  2003. }
  2004. }
  2005. $my_certificate = GradebookUtils::get_certificate_by_user_id(
  2006. $cats_course[0]->get_id(),
  2007. $user_id
  2008. );
  2009. if (empty($my_certificate)) {
  2010. GradebookUtils::registerUserInfoAboutCertificate(
  2011. $category_id,
  2012. $user_id,
  2013. $my_score_in_gradebook,
  2014. api_get_utc_datetime()
  2015. );
  2016. $my_certificate = GradebookUtils::get_certificate_by_user_id(
  2017. $cats_course[0]->get_id(),
  2018. $user_id
  2019. );
  2020. }
  2021. $html = [];
  2022. if (!empty($my_certificate)) {
  2023. $certificate_obj = new Certificate(
  2024. $my_certificate['id'],
  2025. 0,
  2026. $sendNotification
  2027. );
  2028. $fileWasGenerated = $certificate_obj->isHtmlFileGenerated();
  2029. if (!empty($fileWasGenerated)) {
  2030. $url = api_get_path(WEB_PATH).'certificates/index.php?id='.$my_certificate['id'];
  2031. $certificates = Display::toolbarButton(
  2032. get_lang('DisplayCertificate'),
  2033. $url,
  2034. 'eye',
  2035. 'primary'
  2036. );
  2037. $exportToPDF = Display::url(
  2038. Display::return_icon(
  2039. 'pdf.png',
  2040. get_lang('ExportToPDF'),
  2041. [],
  2042. ICON_SIZE_MEDIUM
  2043. ),
  2044. "$url&action=export"
  2045. );
  2046. $hideExportLink = api_get_setting('hide_certificate_export_link');
  2047. $hideExportLinkStudent = api_get_setting('hide_certificate_export_link_students');
  2048. if ($hideExportLink === 'true' || (api_is_student() && $hideExportLinkStudent === 'true')) {
  2049. $exportToPDF = null;
  2050. }
  2051. $html = [
  2052. 'certificate_link' => $certificates,
  2053. 'pdf_link' => $exportToPDF,
  2054. 'pdf_url' => "$url&action=export",
  2055. ];
  2056. if ($skillToolEnabled && $userHasSkills) {
  2057. $html['badge_link'] = Display::toolbarButton(
  2058. get_lang('ExportBadges'),
  2059. api_get_path(WEB_CODE_PATH)."gradebook/get_badges.php?user=$user_id",
  2060. 'external-link'
  2061. );
  2062. }
  2063. }
  2064. return $html;
  2065. }
  2066. }
  2067. /**
  2068. * @param int $catId
  2069. * @param array $userList
  2070. */
  2071. public static function generateCertificatesInUserList($catId, $userList)
  2072. {
  2073. if (!empty($userList)) {
  2074. foreach ($userList as $userInfo) {
  2075. self::generateUserCertificate($catId, $userInfo['user_id']);
  2076. }
  2077. }
  2078. }
  2079. /**
  2080. * @param int $catId
  2081. * @param array $userList
  2082. */
  2083. public static function exportAllCertificates(
  2084. $catId,
  2085. $userList = []
  2086. ) {
  2087. $orientation = api_get_configuration_value('certificate_pdf_orientation');
  2088. $params['orientation'] = 'landscape';
  2089. if (!empty($orientation)) {
  2090. $params['orientation'] = $orientation;
  2091. }
  2092. $params['left'] = 0;
  2093. $params['right'] = 0;
  2094. $params['top'] = 0;
  2095. $params['bottom'] = 0;
  2096. $page_format = $params['orientation'] == 'landscape' ? 'A4-L' : 'A4';
  2097. $pdf = new PDF($page_format, $params['orientation'], $params);
  2098. $certificate_list = GradebookUtils::get_list_users_certificates($catId, $userList);
  2099. $certificate_path_list = [];
  2100. if (!empty($certificate_list)) {
  2101. foreach ($certificate_list as $index => $value) {
  2102. $list_certificate = GradebookUtils::get_list_gradebook_certificates_by_user_id(
  2103. $value['user_id'],
  2104. $catId
  2105. );
  2106. foreach ($list_certificate as $value_certificate) {
  2107. $certificate_obj = new Certificate($value_certificate['id']);
  2108. $certificate_obj->generate(['hide_print_button' => true]);
  2109. if ($certificate_obj->isHtmlFileGenerated()) {
  2110. $certificate_path_list[] = $certificate_obj->html_file;
  2111. }
  2112. }
  2113. }
  2114. }
  2115. if (!empty($certificate_path_list)) {
  2116. // Print certificates (without the common header/footer/watermark
  2117. // stuff) and return as one multiple-pages PDF
  2118. $pdf->html_to_pdf(
  2119. $certificate_path_list,
  2120. get_lang('Certificates'),
  2121. null,
  2122. false,
  2123. false
  2124. );
  2125. }
  2126. }
  2127. /**
  2128. * @param int $catId
  2129. */
  2130. public static function deleteAllCertificates($catId)
  2131. {
  2132. $certificate_list = GradebookUtils::get_list_users_certificates($catId);
  2133. if (!empty($certificate_list)) {
  2134. foreach ($certificate_list as $index => $value) {
  2135. $list_certificate = GradebookUtils::get_list_gradebook_certificates_by_user_id(
  2136. $value['user_id'],
  2137. $catId
  2138. );
  2139. foreach ($list_certificate as $value_certificate) {
  2140. $certificate_obj = new Certificate($value_certificate['id']);
  2141. $certificate_obj->delete(true);
  2142. }
  2143. }
  2144. }
  2145. }
  2146. /**
  2147. * Check whether a user has finished a course by its gradebook.
  2148. *
  2149. * @param int $userId The user ID
  2150. * @param \Category $category Optional. The gradebook category.
  2151. * To check by the gradebook category
  2152. * @param bool $recalculateScore Whether recalculate the score
  2153. *
  2154. * @return bool
  2155. */
  2156. public static function userFinishedCourse(
  2157. $userId,
  2158. \Category $category,
  2159. $recalculateScore = false
  2160. ) {
  2161. if (empty($category)) {
  2162. return false;
  2163. }
  2164. $currentScore = self::getCurrentScore(
  2165. $userId,
  2166. $category,
  2167. $recalculateScore
  2168. );
  2169. $minCertificateScore = $category->getCertificateMinScore();
  2170. $passedCourse = $currentScore >= $minCertificateScore;
  2171. return $passedCourse;
  2172. }
  2173. /**
  2174. * Get the current score (as percentage) on a gradebook category for a user.
  2175. *
  2176. * @param int $userId The user id
  2177. * @param Category $category The gradebook category
  2178. * @param bool $recalculate
  2179. *
  2180. * @return float The score
  2181. */
  2182. public static function getCurrentScore(
  2183. $userId,
  2184. $category,
  2185. $recalculate = false
  2186. ) {
  2187. if (empty($category)) {
  2188. return 0;
  2189. }
  2190. if ($recalculate) {
  2191. return self::calculateCurrentScore(
  2192. $userId,
  2193. $category
  2194. );
  2195. }
  2196. $resultData = Database::select(
  2197. '*',
  2198. Database::get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_LOG),
  2199. [
  2200. 'where' => [
  2201. 'category_id = ? AND user_id = ?' => [$category->get_id(), $userId],
  2202. ],
  2203. 'order' => 'registered_at DESC',
  2204. 'limit' => '1',
  2205. ],
  2206. 'first'
  2207. );
  2208. if (empty($resultData)) {
  2209. return 0;
  2210. }
  2211. return $resultData['score'];
  2212. }
  2213. /**
  2214. * Register the current score for a user on a category gradebook.
  2215. *
  2216. * @param float $score The achieved score
  2217. * @param int $userId The user id
  2218. * @param int $categoryId The gradebook category
  2219. *
  2220. * @return int The insert id
  2221. */
  2222. public static function registerCurrentScore($score, $userId, $categoryId)
  2223. {
  2224. return Database::insert(
  2225. Database::get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_LOG),
  2226. [
  2227. 'category_id' => intval($categoryId),
  2228. 'user_id' => intval($userId),
  2229. 'score' => api_float_val($score),
  2230. 'registered_at' => api_get_utc_datetime(),
  2231. ]
  2232. );
  2233. }
  2234. /**
  2235. * @return array
  2236. */
  2237. public function getStudentList()
  2238. {
  2239. return $this->studentList;
  2240. }
  2241. /**
  2242. * @param array $list
  2243. */
  2244. public function setStudentList($list)
  2245. {
  2246. $this->studentList = $list;
  2247. }
  2248. /**
  2249. * @return string
  2250. */
  2251. public static function getUrl()
  2252. {
  2253. $url = Session::read('gradebook_dest');
  2254. if (empty($url)) {
  2255. // We guess the link
  2256. $courseInfo = api_get_course_info();
  2257. if (!empty($courseInfo)) {
  2258. return api_get_path(WEB_CODE_PATH).'gradebook/index.php?'.api_get_cidreq().'&';
  2259. } else {
  2260. return api_get_path(WEB_CODE_PATH).'gradebook/gradebook.php?';
  2261. }
  2262. }
  2263. return $url;
  2264. }
  2265. /**
  2266. * Destination is index.php or gradebook.php.
  2267. *
  2268. * @param string $url
  2269. */
  2270. public static function setUrl($url)
  2271. {
  2272. switch ($url) {
  2273. case 'gradebook.php':
  2274. $url = api_get_path(WEB_CODE_PATH).'gradebook/gradebook.php?';
  2275. break;
  2276. case 'index.php':
  2277. $url = api_get_path(WEB_CODE_PATH).'gradebook/index.php?'.api_get_cidreq().'&';
  2278. break;
  2279. }
  2280. Session::write('gradebook_dest', $url);
  2281. }
  2282. /**
  2283. * @return int
  2284. */
  2285. public function getGradeBooksToValidateInDependence()
  2286. {
  2287. return $this->gradeBooksToValidateInDependence;
  2288. }
  2289. /**
  2290. * @param int $value
  2291. *
  2292. * @return Category
  2293. */
  2294. public function setGradeBooksToValidateInDependence($value)
  2295. {
  2296. $this->gradeBooksToValidateInDependence = $value;
  2297. return $this;
  2298. }
  2299. /**
  2300. * @return Category
  2301. */
  2302. private static function create_root_category()
  2303. {
  2304. $cat = new Category();
  2305. $cat->set_id(0);
  2306. $cat->set_name(get_lang('RootCat'));
  2307. $cat->set_description(null);
  2308. $cat->set_user_id(0);
  2309. $cat->set_course_code(null);
  2310. $cat->set_parent_id(null);
  2311. $cat->set_weight(0);
  2312. $cat->set_visible(1);
  2313. $cat->setGenerateCertificates(0);
  2314. $cat->setIsRequirement(false);
  2315. return $cat;
  2316. }
  2317. /**
  2318. * @param Doctrine\DBAL\Driver\Statement|null $result
  2319. *
  2320. * @return array
  2321. */
  2322. private static function create_category_objects_from_sql_result($result)
  2323. {
  2324. $categories = [];
  2325. $allow = api_get_configuration_value('allow_gradebook_stats');
  2326. if ($allow) {
  2327. $em = Database::getManager();
  2328. $repo = $em->getRepository('ChamiloCoreBundle:GradebookCategory');
  2329. }
  2330. while ($data = Database::fetch_array($result)) {
  2331. $cat = new Category();
  2332. $cat->set_id($data['id']);
  2333. $cat->set_name($data['name']);
  2334. $cat->set_description($data['description']);
  2335. $cat->set_user_id($data['user_id']);
  2336. $cat->set_course_code($data['course_code']);
  2337. $cat->set_parent_id($data['parent_id']);
  2338. $cat->set_weight($data['weight']);
  2339. $cat->set_visible($data['visible']);
  2340. $cat->set_session_id($data['session_id']);
  2341. $cat->set_certificate_min_score($data['certif_min_score']);
  2342. $cat->set_grade_model_id($data['grade_model_id']);
  2343. $cat->set_locked($data['locked']);
  2344. $cat->setGenerateCertificates($data['generate_certificates']);
  2345. $cat->setIsRequirement($data['is_requirement']);
  2346. $cat->setCourseListDependency(isset($data['depends']) ? $data['depends'] : []);
  2347. $cat->setMinimumToValidate(isset($data['minimum_to_validate']) ? $data['minimum_to_validate'] : null);
  2348. $cat->setGradeBooksToValidateInDependence(isset($data['gradebooks_to_validate_in_dependence']) ? $data['gradebooks_to_validate_in_dependence'] : null);
  2349. if ($allow) {
  2350. $cat->entity = $repo->find($data['id']);
  2351. }
  2352. $categories[] = $cat;
  2353. }
  2354. return $categories;
  2355. }
  2356. /**
  2357. * Internal function used by get_target_categories().
  2358. *
  2359. * @param array $targets
  2360. * @param int $level
  2361. * @param int $catid
  2362. *
  2363. * @return array
  2364. */
  2365. private function addTargetSubcategories($targets, $level, $catid)
  2366. {
  2367. $subcats = self::load(null, null, null, $catid);
  2368. foreach ($subcats as $cat) {
  2369. if ($this->can_be_moved_to_cat($cat)) {
  2370. $targets[] = [
  2371. $cat->get_id(),
  2372. $cat->get_name(),
  2373. $level + 1,
  2374. ];
  2375. $targets = $this->addTargetSubcategories(
  2376. $targets,
  2377. $level + 1,
  2378. $cat->get_id()
  2379. );
  2380. }
  2381. }
  2382. return $targets;
  2383. }
  2384. /**
  2385. * Internal function used by get_target_categories() and addTargetSubcategories()
  2386. * Can this category be moved to the given category ?
  2387. * Impossible when origin and target are the same... children won't be processed
  2388. * either. (a category can't be moved to one of its own children).
  2389. */
  2390. private function can_be_moved_to_cat($cat)
  2391. {
  2392. return $cat->get_id() != $this->get_id();
  2393. }
  2394. /**
  2395. * Internal function used by move_to_cat().
  2396. */
  2397. private function applyCourseCodeToChildren()
  2398. {
  2399. $cats = self::load(null, null, null, $this->id, null);
  2400. $evals = Evaluation::load(null, null, null, $this->id, null);
  2401. $links = LinkFactory::load(
  2402. null,
  2403. null,
  2404. null,
  2405. null,
  2406. null,
  2407. $this->id,
  2408. null
  2409. );
  2410. /** @var Category $cat */
  2411. foreach ($cats as $cat) {
  2412. $cat->set_course_code($this->get_course_code());
  2413. $cat->save();
  2414. $cat->applyCourseCodeToChildren();
  2415. }
  2416. foreach ($evals as $eval) {
  2417. $eval->set_course_code($this->get_course_code());
  2418. $eval->save();
  2419. }
  2420. foreach ($links as $link) {
  2421. $link->delete();
  2422. }
  2423. }
  2424. /**
  2425. * Internal function used by get_tree().
  2426. *
  2427. * @param int $level
  2428. * @param int|null $visible
  2429. *
  2430. * @return array
  2431. */
  2432. private function add_subtree($targets, $level, $catid, $visible)
  2433. {
  2434. $subcats = self::load(null, null, null, $catid, $visible);
  2435. if (!empty($subcats)) {
  2436. foreach ($subcats as $cat) {
  2437. $targets[] = [
  2438. $cat->get_id(),
  2439. $cat->get_name(),
  2440. $level + 1,
  2441. ];
  2442. $targets = self::add_subtree(
  2443. $targets,
  2444. $level + 1,
  2445. $cat->get_id(),
  2446. $visible
  2447. );
  2448. }
  2449. }
  2450. return $targets;
  2451. }
  2452. /**
  2453. * Calculate the current score on a gradebook category for a user.
  2454. *
  2455. * @param int $userId The user id
  2456. * @param Category $category The gradebook category
  2457. *
  2458. * @return float The score
  2459. */
  2460. private static function calculateCurrentScore(
  2461. $userId,
  2462. $category
  2463. ) {
  2464. if (empty($category)) {
  2465. return 0;
  2466. }
  2467. $courseEvaluations = $category->get_evaluations(
  2468. $userId,
  2469. true
  2470. );
  2471. $courseLinks = $category->get_links($userId, true);
  2472. $evaluationsAndLinks = array_merge($courseEvaluations, $courseLinks);
  2473. $categoryScore = 0;
  2474. for ($i = 0; $i < count($evaluationsAndLinks); $i++) {
  2475. $item = $evaluationsAndLinks[$i];
  2476. $score = $item->calc_score($userId);
  2477. $itemValue = 0;
  2478. if (!empty($score)) {
  2479. $divider = $score[1] == 0 ? 1 : $score[1];
  2480. $itemValue = $score[0] / $divider * $item->get_weight();
  2481. }
  2482. $categoryScore += $itemValue;
  2483. }
  2484. return api_float_val($categoryScore);
  2485. }
  2486. }