From e886d7e7ed7f1dafd366c6fa6ffd5957dcdd42c8 Mon Sep 17 00:00:00 2001
From: Alex Buckley <alexbuckley@catalyst.net.nz>
Date: Wed, 1 Feb 2023 14:51:34 +1300
Subject: [PATCH] Bug 32775: Correctly display language order in sysprefs when
 you have multiple languages in a group

Test plan:
1. Apply first patch
2. Install en-NZ and another language - e.g. mi-NZ - so you have three
languages showing in your sysprefs en-NZ (selected), en (unselected) and
mi-NZ (selected)
3. Tick en-NZ and mi-NZ in language and OPACLanguages sysprefs. Order
en-NZ above mi-NZ and save
4. Refresh the syspref page and confirm mi-NZ is displaying above en-NZ,
even though you ordered en-NZ first
5. Refresh the syspref page multiple times and observe the order of the
languages changes
6. Apply this (second) patch
7. Restart plack
8. Refresh syspref page several times confirming that en-NZ is always
ordered first - as expected.

Sponsored-by: Kinder library, New Zealand
Signed-off-by: Martin Renvoize <martin.renvoize@ptfs-europe.com>
Signed-off-by: Katrin Fischer <katrin.fischer.83@web.de>
---
 C4/Languages.pm | 26 ++++++++++++++++++++++++--
 1 file changed, 24 insertions(+), 2 deletions(-)

diff --git a/C4/Languages.pm b/C4/Languages.pm
index 9dcd3cf337..562050e331 100644
--- a/C4/Languages.pm
+++ b/C4/Languages.pm
@@ -371,8 +371,30 @@ sub _build_languages_arrayref {
 
         my %idx = map { $enabled_languages->[$_] => $_ } reverse 0 .. @$enabled_languages-1;
         my @ordered_keys = sort {
-            my $aa = $language_groups->{$a}->[0]->{rfc4646_subtag};
-            my $bb = $language_groups->{$b}->[0]->{rfc4646_subtag};
+            my $aa = '';
+	    my $bb = '';
+	    my $acount = @{$language_groups->{$a}};
+	    my $bcount = @{$language_groups->{$b}};
+	    if ( $language_groups->{$a}->[0]->{enabled} ) {
+                $aa = $language_groups->{$a}->[0]->{rfc4646_subtag};
+	    } elsif ( $acount > 1 ) {
+		for ( my $i=1;$i<$acount;$i++ ) {
+                    if ( $language_groups->{$a}->[$i]->{enabled} ) {
+			$aa = $language_groups->{$a}->[$i]->{rfc4646_subtag};
+			last;
+		    }
+	        }
+	    }
+	    if ( $language_groups->{$b}->[0]->{enabled} ) {
+                $bb = $language_groups->{$b}->[0]->{rfc4646_subtag};
+	    } elsif ( $bcount > 1 ) {
+		for ( my $i=1;$i<$bcount;$i++ ) {
+		    if ($language_groups->{$b}->[$i]->{enabled} ) {
+                        $bb = $language_groups->{$b}->[$i]->{rfc4646_subtag};
+			last;
+		    }
+		}
+	    }
             ( exists $idx{$aa} and exists $idx{$bb} and ( $idx{$aa} cmp $idx{$bb} ) )
             || ( exists $idx{$aa} and exists $idx{$bb} )
             || exists $idx{$bb}
-- 
2.30.2