porcentaje.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. ini_set('display_errors', 1);
  3. ini_set('display_startup_errors', 1);
  4. error_reporting(E_ALL);
  5. require_once "{$_SERVER['DOCUMENT_ROOT']}/dependencies.php";
  6. if (!isset($_SESSION['user'], $moodle_db)) {
  7. serverError(title: 'Error de conexión', message: 'No se ha iniciado sesión o no se ha establecido una conexión con la base de datos de Moodle');
  8. exit();
  9. }
  10. $grade_items = $moodle_db->query(
  11. "SELECT mdl_grade_items.id, itemname, calculation, courseid, fullname, shortname
  12. FROM mdl_grade_items
  13. JOIN mdl_course ON mdl_course.id = mdl_grade_items.courseid
  14. WHERE itemtype = 'course' AND TRIM(calculation) <> ''"
  15. );
  16. // Regular expression to match the item placeholders and percentages
  17. $pattern = '/(\d*\.?\d*)\s?\*\s?##gi(\d+)##|##gi(\d+)##\s?\*\s?(\d*\.?\d*)/';
  18. $grade_items = array_map(function ($item) use ($moodle_db, $pattern) {
  19. $matches = [];
  20. preg_match_all($pattern, $item['calculation'], $matches, PREG_SET_ORDER);
  21. $porcentaje = array_map(function ($match) use ($moodle_db) {
  22. $percentage = $match[1] ?: $match[4];
  23. $itemid = $match[2] ?: $match[3];
  24. $item_name = $moodle_db
  25. ->where('id', $itemid)
  26. ->getOne('mdl_grade_items', ['itemname', 'idnumber']);
  27. return [
  28. 'itemid' => intval($itemid),
  29. 'percentage' => floatval($percentage),
  30. 'item_name' => is_null($item_name) ? 'No encontrado' : ($item_name['itemname'] ?: $item_name['idnumber']),
  31. 'tipo_item' => ($item_name['itemname'] ?? null) ? 'Actividad única' : 'categoría',
  32. ];
  33. }, $matches);
  34. return [
  35. 'id' => $item['id'],
  36. 'calculation' => $item['calculation'],
  37. 'courseid' => $item['courseid'],
  38. 'fullname' => $item['fullname'],
  39. 'shortname' => $item['shortname'],
  40. 'porcentaje' => $porcentaje,
  41. 'suma_porcentaje' => # redondeo de 3 decimales
  42. round(array_sum(array_column($porcentaje, 'percentage')), 2),
  43. ];
  44. }, $grade_items);
  45. // Output the result as JSON
  46. header('Content-Type: application/json');
  47. # filter where suma porcentaje is less than 1
  48. $grade_items = array_filter($grade_items, function ($item) {
  49. return $item['suma_porcentaje'] < 1;
  50. });
  51. echo json_encode($grade_items, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);