Menu: Keine nodes mehr ohne id erlauben.
[kivitendo-erp.git] / SL / Menu.pm
1 package SL::Menu;
2
3 use strict;
4
5 use SL::Auth;
6 use YAML ();
7 use File::Spec;
8 use SL::MoreCommon qw(uri_encode);
9
10 our $yaml_xs;
11 BEGIN {
12    $yaml_xs =  eval { require YAML::XS };
13 }
14
15 our %menu_cache;
16
17 sub new {
18   my ($package, $domain) = @_;
19
20   if (!$menu_cache{$domain}) {
21     my $path = File::Spec->catdir('menus', $domain);
22
23     opendir my $dir, $path or die "can't open $path: $!";
24     my @files = sort grep -f "$path/$_", grep /\.yaml$/, readdir $dir;
25     close $dir;
26
27     my $nodes = [];
28     my $nodes_by_id = {};
29     for my $file (@files) {
30       my $data;
31       eval {
32         if ($yaml_xs) {
33           $data = YAML::XS::LoadFile(File::Spec->catfile($path, $file));
34         } else {
35           $data = YAML::LoadFile(File::Spec->catfile($path, $file));
36         }
37         1;
38       } or do {
39         die "Error while parsing $file: $@";
40       };
41
42       # check if this file is internally consistent.
43       die 'not an array ref' unless $data && 'ARRAY' eq ref $data; # TODO get better diag to user
44
45       # in particular duplicate ids tend to come up as a user error when editing the menu files
46       #my %uniq_ids;
47       #$uniq_ids{$_->{id}}++ && die "Error in $file: duplicate id $_->{id}" for @$data;
48
49       _merge($nodes, $nodes_by_id, $data);
50     }
51
52
53     my $self = bless {
54       nodes => $nodes,
55       by_id => $nodes_by_id,
56     }, $package;
57
58     $self->build_tree;
59
60     $menu_cache{$domain} = $self;
61   } else {
62     $menu_cache{$domain}->clear_access;
63   }
64
65   $menu_cache{$domain}->set_access;
66
67   return $menu_cache{$domain};
68 }
69
70 sub _merge {
71   my ($nodes, $by_id, $data) = @_;
72
73   for my $node (@$data) {
74     my $id = $node->{id};
75
76     die "menu: node with name '$node->{name}' does not have an id" if !$id;
77
78     my $merge_to = $by_id->{$id};
79
80     if (!$merge_to) {
81       push @$nodes, $node;
82       $by_id->{$id} = $node;
83       next;
84     }
85
86     # TODO make this a real recursive merge
87     # TODO add support for arrays
88
89     # merge keys except params
90     for my $key (keys %$node) {
91       if (ref $node->{$key}) {
92         if ('HASH' eq ref $node->{$key}) {
93           $merge_to->{$key} = {} if !exists $merge_to->{$key} || 'HASH' ne ref $merge_to->{$key};
94           for (keys %{ $node->{params} }) {
95             $merge_to->{$key}{$_} = $node->{params}{$_};
96           }
97         } else {
98           die "unsupported structure @{[ ref $node->{$key} ]}";
99         }
100       } else {
101         $merge_to->{$key} = $node->{$key};
102       }
103     }
104   }
105 }
106
107 sub build_tree {
108   my ($self) = @_;
109
110   # first, some sanity check. are all parents valid ids or empty?
111   for my $node ($self->nodes) {
112     next if !exists $node->{parent} || !$node->{parent} || $self->{by_id}->{$node->{id}};
113     die "menu: node $node->{id} has non-existent parent $node->{parent}";
114   }
115
116   my %by_parent;
117   # order them by parent
118   for my $node ($self->nodes) {
119     push @{ $by_parent{ $node->{parent} // '' } //= [] }, $node;
120   }
121
122   my $tree = { };
123   $self->{by_id}{''} = $tree;
124
125
126   for (keys %by_parent) {
127     my $parent = $self->{by_id}{$_};
128     $parent->{children} =  [ sort { $a->{order} <=> $b->{order} } @{ $by_parent{$_} } ];
129   }
130
131   _set_level_rec($tree->{children}, 0);
132
133   $self->{tree} = $tree->{children};
134 }
135
136 sub _set_level_rec {
137   my ($ary_ref, $level) = @_;
138
139   for (@$ary_ref) {
140     $_->{level} = $level;
141     _set_level_rec($_->{children}, $level + 1) if $_->{children};
142   }
143 }
144
145 sub nodes {
146   @{ $_[0]{nodes} }
147 }
148
149 sub tree_walk {
150   my ($self, $all) = @_;
151
152   _tree_walk_rec($self->{tree}, $all);
153 }
154
155 sub _tree_walk_rec {
156   my ($ary_ref, $all) = @_;
157   map { $_->{children} ? ($_, _tree_walk_rec($_->{children}, $all)) : ($_) } grep { $all || $_->{visible} } @$ary_ref;
158 }
159
160 sub parse_access_string {
161   my ($self, $node) = @_;
162
163   my @stack;
164   my $cur_ary = [];
165
166   push @stack, $cur_ary;
167
168   my $access = $node->{access};
169
170   while ($access =~ m/^([a-z_\/]+|\||\&|\(|\)|\s+)/) {
171     my $token = $1;
172     substr($access, 0, length($1)) = "";
173
174     next if ($token =~ /\s/);
175
176     if ($token eq "(") {
177       my $new_cur_ary = [];
178       push @stack, $new_cur_ary;
179       push @{$cur_ary}, $new_cur_ary;
180       $cur_ary = $new_cur_ary;
181
182     } elsif ($token eq ")") {
183       pop @stack;
184       if (!@stack) {
185         die "Error while parsing menu entry $node->{id}: missing '('";
186       }
187       $cur_ary = $stack[-1];
188
189     } elsif (($token eq "|") || ($token eq "&")) {
190       push @{$cur_ary}, $token;
191
192     } else {
193       if ($token =~ m{^ client / (.*) }x) {
194         push @{$cur_ary}, $self->parse_instance_conf_string($1);
195       } else {
196         push @{$cur_ary}, $::auth->check_right($::myconfig{login}, $token, 1);
197       }
198     }
199   }
200
201   if ($access) {
202     die "Error while parsing menu entry $node->{id}: unrecognized token at the start of '$access'\n";
203   }
204
205   if (1 < scalar @stack) {
206     die "Error while parsing menu entry $node->{id}: Missing ')'\n";
207   }
208
209   return SL::Auth::evaluate_rights_ary($stack[0]);
210 }
211
212 sub href_for_node {
213   my ($self, $node) = @_;
214
215   return undef if !$node->{href} && !$node->{module} && !$node->{params};
216
217   return $node->{href_for_node} ||= do {
218     my $href = $node->{href} || $node->{module} || 'controller.pl';
219     my @tokens;
220
221     while (my ($key, $value) = each %{ $node->{params} }) {
222       push @tokens, uri_encode($key, 1) . "=" . uri_encode($value, 1);
223     }
224
225     join '?', $href, grep $_, join '&', @tokens;
226   }
227 }
228
229 sub name_for_node {
230   $::locale->text($_[1]{name})
231 }
232
233 sub parse_instance_conf_string {
234   my ($self, $setting) = @_;
235   return $::instance_conf->data->{$setting};
236 }
237
238 sub clear_access {
239   my ($self) = @_;
240   for my $node ($self->tree_walk("all")) {
241     delete $node->{visible};
242     delete $node->{visible_children};
243   }
244 }
245
246 sub set_access {
247   my ($self) = @_;
248   # 1. evaluate access for all
249   # 2. if a menu has no visible children, its not visible either
250
251   for my $node (reverse $self->tree_walk("all")) {
252     $node->{visible} = $node->{access}           ? $self->parse_access_string($node)
253                      : !$node->{children}        ? 1
254                      : $node->{visible_children} ? 1
255                      :                             0;
256     if ($node->{visible} && $node->{parent}) {
257       $self->{by_id}{ $node->{parent} }{visible_children} = 1;
258     }
259   }
260 }
261
262 1;
263