From 7e2db3831f0f5d14eeb0330defd17f38e30aaf03 Mon Sep 17 00:00:00 2001
From: Alex Yeung <aydevworks@gmail.com>
Date: Mon, 8 Jan 2024 16:15:45 +0000
Subject: [PATCH] Fix error caused by loading assets in completion pages

---
 locallib.php | 27 +++++++++++++++++++++++++--
 1 file changed, 25 insertions(+), 2 deletions(-)

diff --git a/locallib.php b/locallib.php
index 874d1aed2..cc3cbaea8 100644
--- a/locallib.php
+++ b/locallib.php
@@ -116,12 +116,18 @@ function hvp_get_core_assets($context) {
     // Add core stylesheets.
     foreach (\H5PCore::$styles as $style) {
         $settings['core']['styles'][] = $relpath . $style . $cachebuster;
-        $PAGE->requires->css(new moodle_url($liburl . $style . $cachebuster));
+        // Only add stylesheets to page if not on a completion page.
+        if (!\hvp_check_completion_pages($PAGE->pagetype)) {
+            $PAGE->requires->css(new moodle_url($liburl . $style . $cachebuster));
+        }
     }
     // Add core JavaScript.
     foreach (\H5PCore::$scripts as $script) {
         $settings['core']['scripts'][] = $relpath . $script . $cachebuster;
-        $PAGE->requires->js(new moodle_url($liburl . $script . $cachebuster), true);
+        // Only add scripts to page if not on a completion page.
+        if (!\hvp_check_completion_pages($PAGE->pagetype)) {
+            $PAGE->requires->js(new moodle_url($liburl . $script . $cachebuster), true);
+        }
     }
 
     return $settings;
@@ -720,3 +726,20 @@ function hvp_create_hub_export_url($cmid, $content) {
 function hvp_base64_encode($string) {
     return str_replace('=', '', strtr(base64_encode($string), '+/', '-_'));
 }
+
+/**
+ * Check if the given page type is a completion page.
+ * Use this function to avoid loading H5P assets on completion pages.
+ *
+ * @param string $pageType
+ * @return bool
+ */
+function hvp_check_completion_pages($pageType) {
+    $completionpagetypes = [
+        'course-defaultcompletion' => 'Edit completion default settings (Moodle >= 4.3)',
+        'course-editbulkcompletion' => 'Edit completion settings in bulk for a single course',
+        'course-editdefaultcompletion' => 'Edit completion default settings (Moodle < 4.3)',
+    ];
+
+    return array_key_exists($pageType, $completionpagetypes);
+}