gradebooktable.class.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  1. <?php
  2. /* For licensing terms, see license.txt */
  3. use ChamiloSession as Session;
  4. use CpChart\Cache as pCache;
  5. use CpChart\Data as pData;
  6. use CpChart\Image as pImage;
  7. /**
  8. * GradebookTable Class
  9. * Table to display categories, evaluations and links.
  10. *
  11. * @author Stijn Konings
  12. * @author Bert Steppé (refactored, optimised)
  13. *
  14. * @package chamilo.gradebook
  15. */
  16. class GradebookTable extends SortableTable
  17. {
  18. public $cats;
  19. public $exportToPdf;
  20. public $teacherView;
  21. public $userId;
  22. public $studentList = [];
  23. private $currentcat;
  24. private $datagen;
  25. private $evals_links;
  26. private $dataForGraph;
  27. /**
  28. * @var array Indicates which columns should be shown in gradebook
  29. *
  30. * @example [1] For add Ranking column
  31. * [2] For add Best Score column
  32. * [3] For add Average column
  33. */
  34. private $loadStats = [];
  35. /**
  36. * GradebookTable constructor.
  37. *
  38. * @param Category $currentcat
  39. * @param array $cats
  40. * @param array $evals
  41. * @param array $links
  42. * @param null $addparams
  43. * @param bool $exportToPdf
  44. * @param null $showTeacherView
  45. * @param int $userId
  46. * @param array $studentList
  47. * @param array $loadStats
  48. */
  49. public function __construct(
  50. $currentcat,
  51. $cats = [],
  52. $evals = [],
  53. $links = [],
  54. $addparams = null,
  55. $exportToPdf = false,
  56. $showTeacherView = null,
  57. $userId = null,
  58. $studentList = [],
  59. array $loadStats = []
  60. ) {
  61. $this->teacherView = is_null($showTeacherView) ? api_is_allowed_to_edit(null, true) : $showTeacherView;
  62. $this->userId = is_null($userId) ? api_get_user_id() : $userId;
  63. $this->exportToPdf = $exportToPdf;
  64. $this->studentList = $studentList;
  65. parent::__construct(
  66. 'gradebooklist',
  67. null,
  68. null,
  69. api_is_allowed_to_edit() ? 1 : 0,
  70. 20,
  71. 'ASC',
  72. 'gradebook_list'
  73. );
  74. $this->evals_links = array_merge($evals, $links);
  75. $this->currentcat = $currentcat;
  76. $this->cats = $cats;
  77. $this->loadStats = $loadStats;
  78. $this->datagen = new GradebookDataGenerator($cats, $evals, $links);
  79. $this->datagen->preLoadDataKey = $this->getPreloadDataKey();
  80. $this->datagen->hidePercentage = api_get_configuration_value('hide_gradebook_percentage_user_result');
  81. if (!empty($userId)) {
  82. $this->datagen->userId = $userId;
  83. }
  84. if (isset($addparams)) {
  85. $this->set_additional_parameters($addparams);
  86. }
  87. $column = 0;
  88. if ($this->teacherView) {
  89. if ($this->exportToPdf == false) {
  90. $this->set_header($column++, '', '', 'width="25px"');
  91. }
  92. }
  93. $this->set_header($column++, get_lang('Type'), '', 'width="35px"');
  94. $this->set_header($column++, get_lang('Name'), false);
  95. if ($this->exportToPdf == false) {
  96. $this->set_header($column++, get_lang('Description'), false);
  97. }
  98. $model = ExerciseLib::getCourseScoreModel();
  99. $this->set_header(
  100. $column++,
  101. get_lang('Weight'),
  102. '',
  103. 'width="100px"'
  104. );
  105. if (!$this->teacherView) {
  106. $this->set_header($column++, get_lang('Result'), false);
  107. }
  108. if (empty($model)) {
  109. if (in_array(1, $this->loadStats)) {
  110. $this->set_header($column++, get_lang('Ranking'), false);
  111. }
  112. if (in_array(2, $this->loadStats)) {
  113. $this->set_header($column++, get_lang('BestScore'), false);
  114. }
  115. if (in_array(3, $this->loadStats)) {
  116. $this->set_header($column++, get_lang('Average'), false);
  117. }
  118. }
  119. if ($this->teacherView) {
  120. } else {
  121. if (!empty($cats)) {
  122. if ($this->exportToPdf == false) {
  123. $this->set_header($column++, get_lang('Actions'), false);
  124. }
  125. }
  126. }
  127. // Deactivates the odd/even alt rows in order that the +/- buttons work see #4047
  128. $this->odd_even_rows_enabled = false;
  129. // Admins get an edit column.
  130. if ($this->teacherView) {
  131. $this->set_header($column++, get_lang('Modify'), false, 'width="195px"');
  132. // Actions on multiple selected documents.
  133. $this->set_form_actions(
  134. [
  135. 'setvisible' => get_lang('SetVisible'),
  136. 'setinvisible' => get_lang('SetInvisible'),
  137. 'deleted' => get_lang('DeleteSelected'),
  138. ]
  139. );
  140. } else {
  141. if (empty($_GET['selectcat']) && !$this->teacherView) {
  142. if ($this->exportToPdf == false) {
  143. $this->set_header(
  144. $column++,
  145. get_lang('Certificates'),
  146. false
  147. );
  148. }
  149. }
  150. }
  151. }
  152. /**
  153. * @return GradebookDataGenerator
  154. */
  155. public function get_data()
  156. {
  157. return $this->datagen;
  158. }
  159. /**
  160. * Function used by SortableTable to get total number of items in the table.
  161. *
  162. * @return int
  163. */
  164. public function get_total_number_of_items()
  165. {
  166. return $this->datagen->get_total_items_count();
  167. }
  168. /**
  169. * @return string
  170. */
  171. public function getPreloadDataKey()
  172. {
  173. return 'default_data_'.api_get_course_id().'_'.api_get_session_id();
  174. }
  175. public function preloadData()
  176. {
  177. $allitems = $this->datagen->items;
  178. usort($allitems, ['GradebookDataGenerator', 'sort_by_name']);
  179. //$visibleItems = $this->datagen->items;
  180. $visibleItems = array_merge($this->datagen->items, $this->evals_links);
  181. //Session::erase($this->getPreloadDataKey());
  182. $defaultDataFromSession = Session::read($this->getPreloadDataKey());
  183. if (empty($defaultDataFromSession)) {
  184. $defaultData = [];
  185. /** @var GradebookItem $item */
  186. foreach ($visibleItems as $item) {
  187. $item->setStudentList($this->studentList);
  188. $itemType = get_class($item);
  189. switch ($itemType) {
  190. case 'Evaluation':
  191. // Best
  192. $best = $this->datagen->buildBestResultColumn($item);
  193. $defaultData[$item->get_id()]['best'] = $best;
  194. // Average
  195. $average = $this->datagen->buildAverageResultColumn($item);
  196. $defaultData[$item->get_id()]['average'] = $average;
  197. break;
  198. case 'ExerciseLink':
  199. /** @var ExerciseLink $item */
  200. // Best
  201. $best = $this->datagen->buildBestResultColumn($item);
  202. $defaultData[$item->get_id()]['best'] = $best;
  203. // Average
  204. $average = $this->datagen->buildAverageResultColumn($item);
  205. $defaultData[$item->get_id()]['average'] = $average;
  206. // Ranking
  207. /*if (!empty($this->studentList)) {
  208. $invalidateRanking = true;
  209. foreach ($this->studentList as $user) {
  210. $score = $this->datagen->build_result_column(
  211. $user['user_id'],
  212. $item,
  213. false,
  214. true
  215. );
  216. if (!empty($score['score'])) {
  217. $invalidateRanking = false;
  218. }
  219. $rankingStudentList[$user['user_id']] = $score['score'][0];
  220. $defaultData[$item->get_id()]['ranking'] = $rankingStudentList;
  221. $defaultData[$item->get_id()]['ranking_invalidate'] = $invalidateRanking;
  222. }
  223. }*/
  224. break;
  225. default:
  226. // Best
  227. $best = $this->datagen->buildBestResultColumn($item);
  228. $defaultData[$item->get_id()]['best'] = $best;
  229. // Average
  230. $average = $this->datagen->buildAverageResultColumn($item);
  231. $defaultData[$item->get_id()]['average'] = $average;
  232. // Ranking
  233. if (!empty($this->studentList)) {
  234. $invalidateRanking = true;
  235. foreach ($this->studentList as $user) {
  236. $score = $this->datagen->build_result_column(
  237. $user['user_id'],
  238. $item,
  239. false,
  240. true
  241. );
  242. if (!empty($score['score'])) {
  243. $invalidateRanking = false;
  244. }
  245. $rankingStudentList[$user['user_id']] = $score['score'][0];
  246. $defaultData[$item->get_id()]['ranking'] = $rankingStudentList;
  247. $defaultData[$item->get_id()]['ranking_invalidate'] = $invalidateRanking;
  248. }
  249. //exit;
  250. }
  251. break;
  252. }
  253. }
  254. Session::write($this->getPreloadDataKey(), $defaultData);
  255. } else {
  256. $defaultData = $defaultDataFromSession;
  257. }
  258. return $defaultData;
  259. }
  260. /**
  261. * Function used by SortableTable to generate the data to display.
  262. *
  263. * @param int $from
  264. * @param int $per_page
  265. * @param int $column
  266. * @param string $direction
  267. * @param int $sort
  268. *
  269. * @return array|mixed
  270. */
  271. public function get_table_data($from = 1, $per_page = null, $column = null, $direction = null, $sort = null)
  272. {
  273. //variables load in index.php
  274. global $certificate_min_score;
  275. $isAllowedToEdit = api_is_allowed_to_edit();
  276. // determine sorting type
  277. $col_adjust = $isAllowedToEdit ? 1 : 0;
  278. // By id
  279. $this->column = 5;
  280. switch ($this->column) {
  281. // Type
  282. case 0 + $col_adjust:
  283. $sorting = GradebookDataGenerator::GDG_SORT_TYPE;
  284. break;
  285. case 1 + $col_adjust:
  286. $sorting = GradebookDataGenerator::GDG_SORT_NAME;
  287. break;
  288. case 2 + $col_adjust:
  289. $sorting = GradebookDataGenerator::GDG_SORT_DESCRIPTION;
  290. break;
  291. case 3 + $col_adjust:
  292. $sorting = GradebookDataGenerator::GDG_SORT_WEIGHT;
  293. break;
  294. case 4 + $col_adjust:
  295. $sorting = GradebookDataGenerator::GDG_SORT_DATE;
  296. break;
  297. case 5 + $col_adjust:
  298. $sorting = GradebookDataGenerator::GDG_SORT_ID;
  299. break;
  300. }
  301. if ($this->direction == 'DESC') {
  302. $sorting |= GradebookDataGenerator::GDG_SORT_DESC;
  303. } else {
  304. $sorting |= GradebookDataGenerator::GDG_SORT_ASC;
  305. }
  306. // Status of user in course.
  307. $user_id = $this->userId;
  308. $course_code = api_get_course_id();
  309. $session_id = api_get_session_id();
  310. $statusToFilter = 0;
  311. if (empty($session_id)) {
  312. $statusToFilter = STUDENT;
  313. }
  314. if (empty($this->studentList) && $this->loadStats) {
  315. $studentList = CourseManager::get_user_list_from_course_code(
  316. $course_code,
  317. $session_id,
  318. null,
  319. null,
  320. $statusToFilter
  321. );
  322. $this->studentList = $studentList;
  323. }
  324. $this->datagen->userId = $this->userId;
  325. $data_array = $this->datagen->get_data(
  326. $sorting,
  327. $from,
  328. $this->per_page,
  329. false,
  330. $this->studentList,
  331. $this->loadStats
  332. );
  333. // generate the data to display
  334. $sortable_data = [];
  335. $weight_total_links = 0;
  336. $main_cat = Category::load(
  337. null,
  338. null,
  339. $course_code,
  340. null,
  341. null,
  342. $session_id,
  343. 'ORDER BY id'
  344. );
  345. $total_categories_weight = 0;
  346. $scoredisplay = ScoreDisplay::instance();
  347. $totalUserResult = [0, 0];
  348. $totalBest = [0, 0];
  349. $totalAverage = [0, 0];
  350. $type = 'detail';
  351. if ($this->exportToPdf) {
  352. $type = 'simple';
  353. }
  354. $model = ExerciseLib::getCourseScoreModel();
  355. $userExerciseScoreInCategory = api_get_configuration_value(
  356. 'gradebook_use_exercise_score_settings_in_categories'
  357. );
  358. $course_code = api_get_course_id();
  359. $session_id = api_get_session_id();
  360. $defaultData = Session::read($this->getPreloadDataKey());
  361. // Categories.
  362. if (!empty($data_array)) {
  363. foreach ($data_array as $data) {
  364. // list of items inside the gradebook (exercises, lps, forums, etc)
  365. $row = [];
  366. /** @var AbstractLink $item */
  367. $item = $mainCategory = $data[0];
  368. // If the item is invisible, wrap it in a span with class invisible
  369. $invisibility_span_open = $isAllowedToEdit && $item->is_visible() == '0' ? '<span class="text-muted">' : '';
  370. $invisibility_span_close = $isAllowedToEdit && $item->is_visible() == '0' ? '</span>' : '';
  371. // Id
  372. if ($this->teacherView) {
  373. if ($this->exportToPdf == false) {
  374. $row[] = $this->build_id_column($item);
  375. }
  376. }
  377. // Type.
  378. $row[] = $this->build_type_column($item);
  379. // Name.
  380. if (get_class($item) === 'Category') {
  381. $row[] = $invisibility_span_open.'<strong>'.$item->get_name().'</strong>'.$invisibility_span_close;
  382. $main_categories[$item->get_id()]['name'] = $item->get_name();
  383. } else {
  384. $name = $this->build_name_link($item, $type);
  385. $row[] = $invisibility_span_open.$name.$invisibility_span_close;
  386. $main_categories[$item->get_id()]['name'] = $name;
  387. }
  388. $this->dataForGraph['categories'][] = $item->get_name();
  389. $main_categories[$item->get_id()]['weight'] = $item->get_weight();
  390. $total_categories_weight += $item->get_weight();
  391. // Description.
  392. if ($this->exportToPdf == false) {
  393. $row[] = $invisibility_span_open.$data[2].$invisibility_span_close;
  394. }
  395. // Weight.
  396. $weight = $scoredisplay->display_score(
  397. [
  398. $data['3'],
  399. $this->currentcat->get_weight(),
  400. ],
  401. SCORE_SIMPLE,
  402. SCORE_BOTH,
  403. true
  404. );
  405. if ($this->teacherView) {
  406. $row[] = $invisibility_span_open.
  407. Display::tag('p', $weight, ['class' => 'score']).
  408. $invisibility_span_close;
  409. } else {
  410. $row[] = $invisibility_span_open.$weight.$invisibility_span_close;
  411. }
  412. $category_weight = $item->get_weight();
  413. $mainCategoryWeight = $main_cat[0]->get_weight();
  414. if ($this->teacherView) {
  415. $weight_total_links += $data[3];
  416. } else {
  417. $cattotal = Category::load($_GET['selectcat']);
  418. $scoretotal = $cattotal[0]->calc_score($this->userId);
  419. }
  420. // Edit (for admins).
  421. if ($this->teacherView) {
  422. $cat = new Category();
  423. $show_message = $cat->show_message_resource_delete($item->get_course_code());
  424. if ($show_message === false) {
  425. $row[] = $this->build_edit_column($item);
  426. }
  427. } else {
  428. $score = $item->calc_score($this->userId);
  429. $scoreToDisplay = '-';
  430. if (!empty($score[1])) {
  431. $completeScore = $scoredisplay->display_score($score, SCORE_DIV_PERCENT);
  432. $score = $score[0] / $score[1] * $item->get_weight();
  433. $score = $scoredisplay->display_score([$score, null], SCORE_SIMPLE);
  434. $scoreToDisplay = Display::tip($score, $completeScore);
  435. } else {
  436. $categoryScore = null;
  437. }
  438. // Students get the results and certificates columns
  439. $value_data = isset($data[4]) ? $data[4] : null;
  440. $best = isset($data['best']) ? $data['best'] : null;
  441. $average = isset($data['average']) ? $data['average'] : null;
  442. $ranking = isset($data['ranking']) ? $data['ranking'] : null;
  443. $totalResult = [
  444. $data['result_score'][0],
  445. $data['result_score'][1],
  446. ];
  447. $totalUserResult[0] += $totalResult[0] / ($totalResult[1] ?: 1) * $data[3];
  448. $totalUserResult[1] += $data[3];
  449. $totalBest = [
  450. $scoredisplay->format_score($totalBest[0] + $data['best_score'][0]),
  451. $scoredisplay->format_score($totalBest[1] + $data['best_score'][1]),
  452. ];
  453. $totalAverage = [
  454. $data['average_score'][0],
  455. $data['average_score'][1],
  456. ];
  457. // Student result
  458. if (empty($model)) {
  459. $row[] = $value_data;
  460. } else {
  461. $row[] = ExerciseLib::show_score(
  462. $data['result_score'][0],
  463. $data['result_score'][1]
  464. );
  465. }
  466. $mode = SCORE_AVERAGE;
  467. if ($userExerciseScoreInCategory) {
  468. $mode = SCORE_SIMPLE;
  469. $result = ExerciseLib::convertScoreToPlatformSetting($totalAverage[0], $totalAverage[1]);
  470. $totalAverage[0] = $result['score'];
  471. $totalAverage[1] = $result['weight'];
  472. $result = ExerciseLib::convertScoreToPlatformSetting($totalResult[0], $totalResult[1]);
  473. $totalResult[0] = $result['score'];
  474. $totalResult[1] = $result['weight'];
  475. $result = ExerciseLib::convertScoreToPlatformSetting(
  476. $data['result_score'][0],
  477. $data['result_score'][1]
  478. );
  479. $data['my_result_no_float'][0] = $result['score'];
  480. }
  481. $totalResultAverageValue = strip_tags($scoredisplay->display_score($totalResult, $mode));
  482. $totalAverageValue = strip_tags($scoredisplay->display_score($totalAverage, $mode));
  483. $this->dataForGraph['my_result'][] = floatval($totalResultAverageValue);
  484. $this->dataForGraph['average'][] = floatval($totalAverageValue);
  485. $this->dataForGraph['my_result_no_float'][] = $data['result_score'][0];
  486. if (empty($model)) {
  487. // Ranking
  488. if (in_array(1, $this->loadStats)) {
  489. $row[] = $ranking;
  490. }
  491. // Best
  492. if (in_array(2, $this->loadStats)) {
  493. $row[] = $best;
  494. }
  495. // Average
  496. if (in_array(3, $this->loadStats)) {
  497. $row[] = $average;
  498. }
  499. }
  500. if (get_class($item) === 'Category') {
  501. if ($this->exportToPdf == false) {
  502. $row[] = $this->build_edit_column($item);
  503. }
  504. }
  505. }
  506. // Category added.
  507. $sortable_data[] = $row;
  508. // Loading children
  509. if (get_class($item) === 'Category') {
  510. $parent_id = $item->get_id();
  511. $cats = Category::load(
  512. $parent_id,
  513. null,
  514. null,
  515. null,
  516. null,
  517. null
  518. );
  519. if (isset($cats[0])) {
  520. /** @var Category $subCategory */
  521. $subCategory = $cats[0];
  522. $allcat = $subCategory->get_subcategories($this->userId, $course_code, $session_id);
  523. $alleval = $subCategory->get_evaluations($this->userId);
  524. $alllink = $subCategory->get_links($this->userId);
  525. $sub_cat_info = new GradebookDataGenerator($allcat, $alleval, $alllink);
  526. $sub_cat_info->preLoadDataKey = $this->getPreloadDataKey();
  527. $sub_cat_info->userId = $user_id;
  528. $data_array2 = $sub_cat_info->get_data(
  529. $sorting,
  530. $from,
  531. $this->per_page,
  532. false,
  533. $this->studentList
  534. );
  535. $total_weight = 0;
  536. // Links.
  537. foreach ($data_array2 as $data) {
  538. $row = [];
  539. $item = $data[0];
  540. //if the item is invisible, wrap it in a span with class invisible
  541. $invisibility_span_open = $isAllowedToEdit && $item->is_visible() == '0' ? '<span class="text-muted">' : '';
  542. $invisibility_span_close = $isAllowedToEdit && $item->is_visible() == '0' ? '</span>' : '';
  543. if (isset($item)) {
  544. $main_categories[$parent_id]['children'][$item->get_id()]['name'] = $item->get_name();
  545. $main_categories[$parent_id]['children'][$item->get_id()]['weight'] = $item->get_weight();
  546. }
  547. if ($this->teacherView) {
  548. if ($this->exportToPdf == false) {
  549. $row[] = $this->build_id_column($item);
  550. }
  551. }
  552. // Type
  553. $row[] = $this->build_type_column($item, ['style' => 'padding-left:5px']);
  554. // Name.
  555. $row[] = $invisibility_span_open.'&nbsp;&nbsp;&nbsp; '.
  556. $this->build_name_link($item, $type).$invisibility_span_close;
  557. // Description.
  558. if ($this->exportToPdf == false) {
  559. $row[] = $invisibility_span_open.$data[2].$invisibility_span_close;
  560. }
  561. $weight = $data[3];
  562. $total_weight += $weight;
  563. // Weight
  564. $row[] = $invisibility_span_open.$weight.$invisibility_span_close;
  565. if ($this->teacherView) {
  566. //$weight_total_links += intval($data[3]);
  567. } else {
  568. $cattotal = Category::load($_GET['selectcat']);
  569. $scoretotal = $cattotal[0]->calc_score($this->userId);
  570. }
  571. // Admins get an edit column.
  572. if (api_is_allowed_to_edit(null, true) &&
  573. isset($_GET['user_id']) == false &&
  574. (isset($_GET['action']) && $_GET['action'] != 'export_all' || !isset($_GET['action']))
  575. ) {
  576. $cat = new Category();
  577. $show_message = $cat->show_message_resource_delete($item->get_course_code());
  578. if ($show_message === false) {
  579. if ($this->exportToPdf == false) {
  580. $row[] = $this->build_edit_column($item);
  581. }
  582. }
  583. } else {
  584. // Students get the results and certificates columns
  585. $eval_n_links = array_merge($alleval, $alllink);
  586. if (count($eval_n_links) > 0) {
  587. $value_data = isset($data[4]) ? $data[4] : null;
  588. if (!is_null($value_data)) {
  589. // Result
  590. $row[] = $value_data;
  591. $best = isset($data['best']) ? $data['best'] : null;
  592. $average = isset($data['average']) ? $data['average'] : null;
  593. $ranking = isset($data['ranking']) ? $data['ranking'] : null;
  594. if (in_array(1, $this->loadStats)) {
  595. // Ranking
  596. $row[] = $ranking;
  597. }
  598. if (in_array(2, $this->loadStats)) {
  599. // Best
  600. $row[] = $best;
  601. }
  602. // Average
  603. if (in_array(3, $this->loadStats)) {
  604. $row[] = $average;
  605. }
  606. }
  607. }
  608. if (!empty($cats)) {
  609. if ($this->exportToPdf == false) {
  610. $row[] = null;
  611. }
  612. }
  613. }
  614. if ($this->exportToPdf == false) {
  615. $row['child_of'] = $parent_id;
  616. }
  617. $sortable_data[] = $row;
  618. }
  619. // "Warning row"
  620. if (!empty($data_array)) {
  621. if ($this->teacherView) {
  622. // Compare the category weight to the sum of all weights inside the category
  623. if (intval($total_weight) == $category_weight) {
  624. $label = null;
  625. $total = GradebookUtils::score_badges(
  626. [
  627. $total_weight.' / '.$category_weight,
  628. '100',
  629. ]
  630. );
  631. } else {
  632. $label = Display::return_icon(
  633. 'warning.png',
  634. sprintf(get_lang('TotalWeightMustBeX'), $category_weight)
  635. );
  636. $total = Display::badge($total_weight.' / '.$category_weight, 'warning');
  637. }
  638. $row = [
  639. null,
  640. null,
  641. "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<h5>".get_lang('SubTotal').'</h5>',
  642. null,
  643. $total.' '.$label,
  644. 'child_of' => $parent_id,
  645. ];
  646. $sortable_data[] = $row;
  647. }
  648. }
  649. }
  650. }
  651. }
  652. } //end looping categories
  653. $main_weight = 0;
  654. if (count($main_cat) > 1) {
  655. /** @var Category $myCat */
  656. foreach ($main_cat as $myCat) {
  657. $myParentId = $myCat->get_parent_id();
  658. if ($myParentId == 0) {
  659. $main_weight = (int) $myCat->get_weight();
  660. }
  661. }
  662. }
  663. if ($this->teacherView) {
  664. // Total for teacher.
  665. if (count($main_cat) > 1) {
  666. if (intval($total_categories_weight) == $main_weight) {
  667. $total = GradebookUtils::score_badges(
  668. [
  669. $total_categories_weight.' / '.$main_weight,
  670. '100',
  671. ]
  672. );
  673. } else {
  674. $total = Display::badge($total_categories_weight.' / '.$main_weight, 'warning');
  675. }
  676. $row = [
  677. null,
  678. null,
  679. '<strong>'.get_lang('Total').'</strong>',
  680. null,
  681. $total,
  682. ];
  683. $sortable_data[] = $row;
  684. }
  685. } else {
  686. // Total for student.
  687. if (count($main_cat) > 1) {
  688. $main_weight = (int) $main_cat[0]->get_weight();
  689. $global = null;
  690. $average = null;
  691. $myTotal = 0;
  692. foreach ($this->dataForGraph['my_result_no_float'] as $result) {
  693. $myTotal += $result;
  694. }
  695. $totalResult[0] = $myTotal;
  696. // Overwrite main weight
  697. $totalResult[1] = $main_weight;
  698. $totalResult = $scoredisplay->display_score(
  699. $totalResult,
  700. SCORE_DIV
  701. );
  702. $row = [
  703. null,
  704. '<strong>'.get_lang('Total').'</strong>',
  705. ];
  706. if (!$this->exportToPdf) {
  707. $row[] = null;
  708. }
  709. $row[] = $main_weight;
  710. $row[] = $totalResult;
  711. $categoryId = $main_cat[0]->get_id();
  712. if (in_array(1, $this->loadStats)) {
  713. if (isset($defaultData[$categoryId]) && isset($defaultData[$categoryId]['ranking'])) {
  714. $totalRanking = $defaultData[$categoryId]['ranking'];
  715. $invalidateRanking = $defaultData[$categoryId]['ranking_invalidate'];
  716. } else {
  717. $totalRanking = [];
  718. $invalidateRanking = true;
  719. $average = 0;
  720. $main_cat[0]->setStudentList($this->studentList);
  721. foreach ($this->studentList as $student) {
  722. $score = $main_cat[0]->calc_score(
  723. $student['user_id'],
  724. null,
  725. api_get_course_id(),
  726. api_get_session_id()
  727. );
  728. if (!empty($score[0])) {
  729. $invalidateRanking = false;
  730. }
  731. $totalRanking[$student['user_id']] = $score[0];
  732. $average += $score[0];
  733. }
  734. $defaultData[$categoryId]['ranking'] = $totalRanking;
  735. $defaultData[$categoryId]['ranking_invalidate'] = $invalidateRanking;
  736. Session::write($this->getPreloadDataKey(), $defaultData);
  737. }
  738. $totalRanking = AbstractLink::getCurrentUserRanking($user_id, $totalRanking);
  739. $totalRanking = $scoredisplay->display_score(
  740. $totalRanking,
  741. SCORE_DIV,
  742. SCORE_BOTH,
  743. true,
  744. true
  745. );
  746. if ($invalidateRanking) {
  747. $totalRanking = null;
  748. }
  749. $row[] = $totalRanking;
  750. }
  751. if (in_array(2, $this->loadStats)) {
  752. if (isset($defaultData[$categoryId]) && isset($defaultData[$categoryId]['best'])) {
  753. $totalBest = $defaultData[$categoryId]['best'];
  754. } else {
  755. // Overwrite main weight
  756. $totalBest[1] = $main_weight;
  757. $defaultData[$categoryId]['best'] = $totalBest;
  758. }
  759. $totalBest = $scoredisplay->display_score(
  760. $totalBest,
  761. SCORE_DIV,
  762. SCORE_BOTH,
  763. true
  764. );
  765. $row[] = $totalBest;
  766. }
  767. if (in_array(3, $this->loadStats)) {
  768. if (isset($defaultData[$categoryId]) && isset($defaultData[$categoryId]['average'])) {
  769. $totalAverage = $defaultData[$categoryId]['average'];
  770. } else {
  771. // Overwrite main weight
  772. $totalAverage[0] = $average / count($this->studentList);
  773. $totalAverage[1] = $main_weight;
  774. $defaultData[$categoryId]['average'] = $totalBest;
  775. }
  776. $totalAverage = $scoredisplay->display_score(
  777. $totalAverage,
  778. SCORE_DIV,
  779. SCORE_BOTH,
  780. true
  781. );
  782. $row[] = $totalAverage;
  783. }
  784. if (!empty($row)) {
  785. $sortable_data[] = $row;
  786. }
  787. }
  788. }
  789. Session::write('default_data', $defaultData);
  790. // Warning messages
  791. $view = isset($_GET['view']) ? $_GET['view'] : null;
  792. if ($this->teacherView) {
  793. if (isset($_GET['selectcat']) &&
  794. $_GET['selectcat'] > 0 &&
  795. $view != 'presence'
  796. ) {
  797. $id_cat = (int) $_GET['selectcat'];
  798. $category = Category::load($id_cat);
  799. $weight_category = (int) $this->build_weight($category[0]);
  800. $course_code = $this->build_course_code($category[0]);
  801. $weight_total_links = round($weight_total_links);
  802. if ($weight_total_links > $weight_category ||
  803. $weight_total_links < $weight_category ||
  804. $weight_total_links > $weight_category
  805. ) {
  806. $warning_message = sprintf(get_lang('TotalWeightMustBeX'), $weight_category);
  807. $modify_icons =
  808. '<a href="gradebook_edit_cat.php?editcat='.$id_cat.'&cidReq='.$course_code.'&id_session='.api_get_session_id().'">'.
  809. Display::return_icon('edit.png', $warning_message, [], ICON_SIZE_SMALL).'</a>';
  810. $warning_message .= $modify_icons;
  811. echo Display::return_message($warning_message, 'warning', false);
  812. }
  813. $content_html = DocumentManager::replace_user_info_into_html(
  814. api_get_user_id(),
  815. $course_code,
  816. api_get_session_id()
  817. );
  818. if (!empty($content_html)) {
  819. $new_content = explode('</head>', $content_html['content']);
  820. }
  821. if (empty($new_content[0])) {
  822. // Set default certificate
  823. $courseData = api_get_course_info($course_code);
  824. DocumentManager::generateDefaultCertificate($courseData);
  825. }
  826. }
  827. if (empty($_GET['selectcat'])) {
  828. $categories = Category::load();
  829. $weight_categories = $certificate_min_scores = $course_codes = [];
  830. foreach ($categories as $category) {
  831. $course_code_category = $this->build_course_code($category);
  832. if (!empty($course_code)) {
  833. if ($course_code_category == $course_code) {
  834. $weight_categories[] = intval($this->build_weight($category));
  835. $certificate_min_scores[] = intval($this->build_certificate_min_score($category));
  836. $course_codes[] = $course_code;
  837. break;
  838. }
  839. } else {
  840. $weight_categories[] = intval($this->build_weight($category));
  841. $certificate_min_scores[] = intval($this->build_certificate_min_score($category));
  842. $course_codes[] = $course_code_category;
  843. }
  844. }
  845. if (is_array($weight_categories) &&
  846. is_array($certificate_min_scores) &&
  847. is_array($course_codes)
  848. ) {
  849. $warning_message = '';
  850. for ($x = 0; $x < count($weight_categories); $x++) {
  851. $weight_category = intval($weight_categories[$x]);
  852. $certificate_min_score = intval($certificate_min_scores[$x]);
  853. $course_code = $course_codes[$x];
  854. if (empty($certificate_min_score) ||
  855. ($certificate_min_score > $weight_category)
  856. ) {
  857. $warning_message .= $course_code.
  858. '&nbsp;-&nbsp;'.get_lang('CertificateMinimunScoreIsRequiredAndMustNotBeMoreThan').
  859. '&nbsp;'.$weight_category.'<br />';
  860. }
  861. }
  862. if (!empty($warning_message)) {
  863. echo Display::return_message($warning_message, 'warning', false);
  864. }
  865. }
  866. }
  867. }
  868. return $sortable_data;
  869. }
  870. /**
  871. * @return string
  872. */
  873. public function getGraph()
  874. {
  875. $data = $this->getDataForGraph();
  876. if (!empty($data) &&
  877. isset($data['categories']) &&
  878. isset($data['my_result']) &&
  879. isset($data['average'])
  880. ) {
  881. $dataSet = new pData();
  882. $dataSet->addPoints($data['my_result'], get_lang('Me'));
  883. // In order to generate random values
  884. // $data['average'] = array(rand(0,50), rand(0,50));
  885. $dataSet->addPoints($data['average'], get_lang('Average'));
  886. $dataSet->addPoints($data['categories'], 'categories');
  887. $dataSet->setAbscissa('categories');
  888. $xSize = 600;
  889. $ySize = 400;
  890. $pChart = new pImage($xSize, $ySize, $dataSet);
  891. /* Turn of Antialiasing */
  892. $pChart->Antialias = false;
  893. /* Add a border to the picture */
  894. $pChart->drawRectangle(
  895. 0,
  896. 0,
  897. $xSize - 1,
  898. $ySize - 1,
  899. ["R" => 0, "G" => 0, "B" => 0]
  900. );
  901. $pChart->drawText(
  902. 80,
  903. 16,
  904. get_lang('Results'),
  905. ["FontSize" => 11, "Align" => TEXT_ALIGN_BOTTOMMIDDLE]
  906. );
  907. $pChart->setGraphArea(50, 30, $xSize - 50, $ySize - 70);
  908. $pChart->setFontProperties(
  909. [
  910. 'FontName' => api_get_path(SYS_FONTS_PATH).'opensans/OpenSans-Regular.ttf',
  911. 'FontSize' => 10,
  912. ]
  913. );
  914. /* Draw the scale */
  915. $scaleSettings = [
  916. "XMargin" => AUTO,
  917. "YMargin" => 10,
  918. "Floating" => true,
  919. "GridR" => 200,
  920. "GridG" => 200,
  921. "GridB" => 200,
  922. "DrawSubTicks" => true,
  923. "CycleBackground" => true,
  924. 'LabelRotation' => 10,
  925. ];
  926. $pChart->drawScale($scaleSettings);
  927. /* Draw the line chart */
  928. $pChart->drawLineChart();
  929. $pChart->drawPlotChart(
  930. [
  931. "DisplayValues" => true,
  932. "PlotBorder" => true,
  933. "BorderSize" => 2,
  934. "Surrounding" => -60,
  935. "BorderAlpha" => 80,
  936. ]
  937. );
  938. /* Write the chart legend */
  939. $pChart->drawLegend(
  940. $xSize - 180,
  941. 9,
  942. [
  943. "Style" => LEGEND_NOBORDER,
  944. "Mode" => LEGEND_HORIZONTAL,
  945. "FontR" => 0,
  946. "FontG" => 0,
  947. "FontB" => 0,
  948. ]
  949. );
  950. $cachePath = api_get_path(SYS_ARCHIVE_PATH);
  951. $myCache = new pCache(['CacheFolder' => substr($cachePath, 0, strlen($cachePath) - 1)]);
  952. $chartHash = $myCache->getHash($dataSet);
  953. $myCache->writeToCache($chartHash, $pChart);
  954. $imgSysPath = api_get_path(SYS_ARCHIVE_PATH).$chartHash;
  955. $myCache->saveFromCache($chartHash, $imgSysPath);
  956. $imgWebPath = api_get_path(WEB_ARCHIVE_PATH).$chartHash;
  957. if (file_exists($imgSysPath)) {
  958. $result = '<br /><div id="contentArea" style="text-align: center;" >';
  959. $result .= '<img src="'.$imgWebPath.'" >';
  960. $result .= '</div>';
  961. return $result;
  962. }
  963. }
  964. return '';
  965. }
  966. /**
  967. * @return array
  968. */
  969. private function getDataForGraph()
  970. {
  971. return $this->dataForGraph;
  972. }
  973. /**
  974. * @param $item
  975. *
  976. * @return mixed
  977. */
  978. private function build_certificate_min_score($item)
  979. {
  980. return $item->getCertificateMinScore();
  981. }
  982. /**
  983. * @param $item
  984. *
  985. * @return mixed
  986. */
  987. private function build_weight($item)
  988. {
  989. return $item->get_weight();
  990. }
  991. /**
  992. * @param $item
  993. *
  994. * @return mixed
  995. */
  996. private function build_course_code($item)
  997. {
  998. return $item->get_course_code();
  999. }
  1000. /**
  1001. * @param $item
  1002. *
  1003. * @return string
  1004. */
  1005. private function build_id_column($item)
  1006. {
  1007. switch ($item->get_item_type()) {
  1008. // category
  1009. case 'C':
  1010. return 'CATE'.$item->get_id();
  1011. // evaluation
  1012. case 'E':
  1013. return 'EVAL'.$item->get_id();
  1014. // link
  1015. case 'L':
  1016. return 'LINK'.$item->get_id();
  1017. }
  1018. }
  1019. /**
  1020. * @param $item
  1021. * @param array $attributes
  1022. *
  1023. * @return string
  1024. */
  1025. private function build_type_column($item, $attributes = [])
  1026. {
  1027. return GradebookUtils::build_type_icon_tag($item->get_icon_name(), $attributes);
  1028. }
  1029. /**
  1030. * Generate name column.
  1031. *
  1032. * @param GradebookItem $item
  1033. * @param string $type simple|detail
  1034. *
  1035. * @return string
  1036. */
  1037. private function build_name_link($item, $type = 'detail')
  1038. {
  1039. $view = isset($_GET['view']) ? Security::remove_XSS($_GET['view']) : null;
  1040. $categoryId = $item->getCategory()->get_id();
  1041. switch ($item->get_item_type()) {
  1042. // category
  1043. case 'C':
  1044. $prms_uri = '?selectcat='.$item->get_id().'&view='.$view;
  1045. $isStudentView = api_is_student_view_active();
  1046. if (isset($is_student) || $isStudentView) {
  1047. $prms_uri = $prms_uri.'&amp;isStudentView=studentview';
  1048. }
  1049. $cat = new Category();
  1050. $show_message = $cat->show_message_resource_delete($item->get_course_code());
  1051. return '&nbsp;<a href="'.Category::getUrl().$prms_uri.'">'
  1052. .$item->get_name()
  1053. .'</a>'
  1054. .($item->is_course() ? ' &nbsp;['.$item->get_course_code().']'.$show_message : '');
  1055. // evaluation
  1056. case 'E':
  1057. $cat = new Category();
  1058. $course_id = CourseManager::get_course_by_category($categoryId);
  1059. $show_message = $cat->show_message_resource_delete($course_id);
  1060. // course/platform admin can go to the view_results page
  1061. if (api_is_allowed_to_edit() && $show_message === false) {
  1062. if ($item->get_type() == 'presence') {
  1063. return '&nbsp;'
  1064. .'<a href="gradebook_view_result.php?cidReq='.$course_id.'&amp;selecteval='.$item->get_id().'">'
  1065. .$item->get_name()
  1066. .'</a>';
  1067. } else {
  1068. $extra = Display::label(get_lang('Evaluation'));
  1069. if ($type == 'simple') {
  1070. $extra = '';
  1071. }
  1072. return '&nbsp;'
  1073. .'<a href="gradebook_view_result.php?'.api_get_cidreq().'&selecteval='.$item->get_id().'">'
  1074. .$item->get_name()
  1075. .'</a>&nbsp;'.$extra;
  1076. }
  1077. } elseif (ScoreDisplay::instance()->is_custom() && $show_message === false) {
  1078. // students can go to the statistics page (if custom display enabled)
  1079. return '&nbsp;'
  1080. .'<a href="gradebook_statistics.php?'.api_get_cidreq().'&selecteval='.$item->get_id().'">'
  1081. .$item->get_name()
  1082. .'</a>';
  1083. } elseif ($show_message === false && !api_is_allowed_to_edit() && !ScoreDisplay::instance()->is_custom()) {
  1084. return '&nbsp;'
  1085. .'<a href="gradebook_statistics.php?'.api_get_cidreq().'&selecteval='.$item->get_id().'">'
  1086. .$item->get_name()
  1087. .'</a>';
  1088. } else {
  1089. return '['.get_lang('Evaluation').']&nbsp;&nbsp;'.$item->get_name().$show_message;
  1090. }
  1091. // no break because of return
  1092. case 'L':
  1093. // link
  1094. $cat = new Category();
  1095. $course_id = CourseManager::get_course_by_category($categoryId);
  1096. $show_message = $cat->show_message_resource_delete($course_id);
  1097. $url = $item->get_link();
  1098. $text = $item->get_name();
  1099. if (isset($url) && $show_message === false) {
  1100. $text = '&nbsp;<a href="'.$item->get_link().'">'
  1101. .$item->get_name()
  1102. .'</a>';
  1103. }
  1104. $extra = Display::label($item->get_type_name(), 'info');
  1105. if ($type == 'simple') {
  1106. $extra = '';
  1107. }
  1108. $extra .= $item->getSkillsFromItem();
  1109. $text .= "&nbsp;".$extra.$show_message;
  1110. $cc = $this->currentcat->get_course_code();
  1111. if (empty($cc)) {
  1112. $text .= '&nbsp;[<a href="'.api_get_path(REL_COURSE_PATH).$item->get_course_code().'/">'.$item->get_course_code().'</a>]';
  1113. }
  1114. return $text;
  1115. }
  1116. }
  1117. /**
  1118. * @param AbstractLink $item
  1119. *
  1120. * @return string|null
  1121. */
  1122. private function build_edit_column($item)
  1123. {
  1124. switch ($item->get_item_type()) {
  1125. // category
  1126. case 'C':
  1127. return GradebookUtils::build_edit_icons_cat($item, $this->currentcat);
  1128. // evaluation
  1129. case 'E':
  1130. return GradebookUtils::build_edit_icons_eval($item, $this->currentcat->get_id());
  1131. // link
  1132. case 'L':
  1133. return GradebookUtils::build_edit_icons_link($item, $this->currentcat->get_id());
  1134. }
  1135. }
  1136. }