+sub get_base_unit {
+ my ($units, $unit_name, $factor) = @_;
+
+ $factor = 1 unless ($factor);
+
+ my $unit = $units->{$unit_name};
+
+ if (!defined($unit) || !$unit->{"base_unit"} ||
+ ($unit_name eq $unit->{"base_unit"})) {
+ return ($unit_name, $factor);
+ }
+
+ return get_base_unit($units, $unit->{"base_unit"}, $factor * $unit->{"factor"});
+}
+
+sub retrieve_units {
+ my ($myconfig, $form, $type, $prefix) = @_;
+
+ my $query = "SELECT *, base_unit AS original_base_unit FROM units";
+ my @values;
+ if ($type) {
+ $query .= " WHERE (type = ?)";
+ @values = ($type);
+ }
+
+ my $sth = $dbh->prepare($query);
+ $sth->execute(@values) || $form->dberror($query . " (" . join(", ", @values) . ")");
+
+ my $units = {};
+ while (my $ref = $sth->fetchrow_hashref()) {
+ $units->{$ref->{"name"}} = $ref;
+ }
+ $sth->finish();
+
+ my $query_lang = "SELECT id, template_code FROM language ORDER BY description";
+ $sth = $dbh->prepare($query_lang);
+ $sth->execute() || $form->dberror($query_lang);
+ my @languages;
+ while ($ref = $sth->fetchrow_hashref()) {
+ push(@languages, $ref);
+ }
+ $sth->finish();
+
+ foreach my $unit (values(%{$units})) {
+ ($unit->{"${prefix}base_unit"}, $unit->{"${prefix}factor"}) = get_base_unit($units, $unit->{"name"});
+ }
+
+ return $units;
+}
+
+sub unit_select_data {
+ my ($units, $selected, $empty_entry) = @_;
+
+ my $select = [];
+
+ if ($empty_entry) {
+ push(@{$select}, { "name" => "", "base_unit" => "", "factor" => "", "selected" => "" });
+ }
+
+ foreach my $unit (sort({ lc($a) cmp lc($b) } keys(%{$units}))) {
+ push(@{$select}, { "name" => $unit,
+ "base_unit" => $units->{$unit}->{"base_unit"},
+ "factor" => $units->{$unit}->{"factor"},
+ "selected" => ($unit eq $selected) ? "selected" : "" });
+ }
+
+ return $select;
+}
+