From 93562d9757edd37202117145c85296a51b2cdc90 Mon Sep 17 00:00:00 2001
From: Thomas Hackl <hackl@data-quest.de>
Date: Fri, 14 Jul 2023 19:42:50 +0000
Subject: [PATCH] Resolve "SQL-Fehler, wenn "Meine Veranstaltungen" nach
 Studienbereich gruppiert ist"

Closes #2854

Merge request studip/studip!1933
---
 lib/classes/MyRealmModel.php         | 19 +++++++++++++------
 lib/models/StudipStudyArea.class.php | 22 ++++++++++++++++++++++
 2 files changed, 35 insertions(+), 6 deletions(-)

diff --git a/lib/classes/MyRealmModel.php b/lib/classes/MyRealmModel.php
index ce5694221be..d82218980ef 100644
--- a/lib/classes/MyRealmModel.php
+++ b/lib/classes/MyRealmModel.php
@@ -666,13 +666,20 @@ class MyRealmModel
                     $_tmp_courses[$sem_key][''][$course['seminar_id']] = $course;
                 }
             }
-            uksort($_tmp_courses[$sem_key], function ($a, $b) use ($sem_tree_names) {
-                $the_tree = TreeAbstract::GetInstance(
-                    'StudipSemTree',
-                    ['build_index' => true]
-                );
-                return (int)($the_tree->tree_data[$a]['index'] ?? 0 - $the_tree->tree_data[$b]['index'] ?? 0);
+
+            // Create sort order for assigned sem_tree entries.
+            $entries = StudipStudyArea::findMany(array_keys($sem_tree_names));
+            $order = [];
+            foreach ($entries as $entry) {
+                $order[$entry->getId()] = $entry->getIndex();
+            }
+            $max = max(array_map('strlen', $order));
+
+            // Now sort courses by sem_tree entry order.
+            uksort($_tmp_courses[$sem_key], function ($a, $b) use ($order, $max) {
+                return (str_pad($order[$a], $max, '0') - str_pad($order[$b], $max, '0'));
             });
+
             //At this point the $_tmp_courses array is sorted by the ordering
             //of the sem_tree.
             //Now we have to replace the sem_tree IDs in the second layer
diff --git a/lib/models/StudipStudyArea.class.php b/lib/models/StudipStudyArea.class.php
index 49f008a6f87..2975fb4b70c 100644
--- a/lib/models/StudipStudyArea.class.php
+++ b/lib/models/StudipStudyArea.class.php
@@ -610,4 +610,26 @@ class StudipStudyArea extends SimpleORMap implements StudipTreeNode
         return $ids;
     }
 
+    /**
+     * Constructs an index from the level hierarchy, This index is a number,
+     * containing the "depth" level and the priority on this level. For example,
+     * a node on level 2 with priority 3 will get an index of 23.
+     *
+     * @return int
+     */
+    public function getIndex()
+    {
+        $level = 1;
+        $index = (string) $level . (string) $this->priority;
+        $current = $this;
+
+        while ($current->getParent()) {
+            $current = $current->getParent();
+            $index .= $level . $current->priority;
+            $level++;
+        }
+
+        return $index;
+    }
+
 }
-- 
GitLab