mebil
[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     my $merge_to = $by_id->{$id};
77
78     if (!$merge_to) {
79       push @$nodes, $node;
80       $by_id->{$id} = $node;
81       next;
82     }
83
84     # TODO make this a real recursive merge
85     # TODO add support for arrays
86
87     # merge keys except params
88     for my $key (keys %$node) {
89       if (ref $node->{$key}) {
90         if ('HASH' eq ref $node->{$key}) {
91           $merge_to->{$key} = {} if !exists $merge_to->{$key} || 'HASH' ne ref $merge_to->{$key};
92           for (keys %{ $node->{params} }) {
93             $merge_to->{$key}{$_} = $node->{params}{$_};
94           }
95         } else {
96           die "unsupported structure @{[ ref $node->{$key} ]}";
97         }
98       } else {
99         $merge_to->{$key} = $node->{$key};
100       }
101     }
102   }
103 }
104
105 sub build_tree {
106   my ($self) = @_;
107
108   # first, some sanity check. are all parents valid ids or empty?
109   for my $node ($self->nodes) {
110     next if !exists $node->{parent} || !$node->{parent} || $self->{by_id}->{$node->{id}};
111     die "menu: node $node->{id} has non-existent parent $node->{parent}";
112   }
113
114   my %by_parent;
115   # order them by parent
116   for my $node ($self->nodes) {
117     push @{ $by_parent{ $node->{parent} // '' } //= [] }, $node;
118   }
119
120   my $tree = { };
121   $self->{by_id}{''} = $tree;
122
123
124   for (keys %by_parent) {
125     my $parent = $self->{by_id}{$_};
126     $parent->{children} =  [ sort { $a->{order} <=> $b->{order} } @{ $by_parent{$_} } ];
127   }
128
129   _set_level_rec($tree->{children}, 0);
130
131   $self->{tree} = $tree->{children};
132 }
133
134 sub _set_level_rec {
135   my ($ary_ref, $level) = @_;
136
137   for (@$ary_ref) {
138     $_->{level} = $level;
139     _set_level_rec($_->{children}, $level + 1) if $_->{children};
140   }
141 }
142
143 sub nodes {
144   @{ $_[0]{nodes} }
145 }
146
147 sub tree_walk {
148   my ($self, $all) = @_;
149
150   _tree_walk_rec($self->{tree}, $all);
151 }
152
153 sub _tree_walk_rec {
154   my ($ary_ref, $all) = @_;
155   map { $_->{children} ? ($_, _tree_walk_rec($_->{children}, $all)) : ($_) } grep { $all || $_->{visible} } @$ary_ref;
156 }
157
158 sub parse_access_string {
159   my ($self, $node) = @_;
160
161   my @stack;
162   my $cur_ary = [];
163
164   push @stack, $cur_ary;
165
166   my $access = $node->{access};
167
168   while ($access =~ m/^([a-z_\/]+|\||\&|\(|\)|\s+)/) {
169     my $token = $1;
170     substr($access, 0, length($1)) = "";
171
172     next if ($token =~ /\s/);
173
174     if ($token eq "(") {
175       my $new_cur_ary = [];
176       push @stack, $new_cur_ary;
177       push @{$cur_ary}, $new_cur_ary;
178       $cur_ary = $new_cur_ary;
179
180     } elsif ($token eq ")") {
181       pop @stack;
182       if (!@stack) {
183         die "Error while parsing menu entry $node->{id}: missing '('";
184       }
185       $cur_ary = $stack[-1];
186
187     } elsif (($token eq "|") || ($token eq "&")) {
188       push @{$cur_ary}, $token;
189
190     } else {
191       if ($token =~ m{^ client / (.*) }x) {
192         push @{$cur_ary}, $self->parse_instance_conf_string($1);
193       } else {
194         push @{$cur_ary}, $::auth->check_right($::myconfig{login}, $token, 1);
195       }
196     }
197   }
198
199   if ($access) {
200     die "Error while parsing menu entry $node->{id}: unrecognized token at the start of '$access'\n";
201   }
202
203   if (1 < scalar @stack) {
204     die "Error while parsing menu entry $node->{id}: Missing ')'\n";
205   }
206
207   return SL::Auth::evaluate_rights_ary($stack[0]);
208 }
209
210 sub href_for_node {
211   my ($self, $node) = @_;
212
213   return undef if !$node->{href} && !$node->{module} && !$node->{params};
214
215   my $href = $node->{href} || $node->{module} || 'controller.pl';
216   my @tokens;
217
218   while (my ($key, $value) = each %{ $node->{params} }) {
219     push @tokens, uri_encode($key, 1) . "=" . uri_encode($value, 1);
220   }
221
222   return join '?', $href, grep $_, join '&', @tokens;
223 }
224
225 sub name_for_node {
226   $::locale->text($_[1]{name})
227 }
228
229 sub parse_instance_conf_string {
230   my ($self, $setting) = @_;
231   return $::instance_conf->data->{$setting};
232 }
233
234 sub clear_access {
235   my ($self) = @_;
236   for my $node ($self->tree_walk("all")) {
237     delete $node->{visible};
238     delete $node->{visible_children};
239   }
240 }
241
242 sub set_access {
243   my ($self) = @_;
244   # 1. evaluate access for all
245   # 2. if a menu has no visible children, its not visible either
246
247   for my $node (reverse $self->tree_walk("all")) {
248     $node->{visible} = $node->{access}           ? $self->parse_access_string($node)
249                      : !$node->{children}        ? 1
250                      : $node->{visible_children} ? 1
251                      :                             0;
252     if ($node->{visible} && $node->{parent}) {
253       $self->{by_id}{ $node->{parent} }{visible_children} = 1;
254     }
255   }
256 }
257
258 1;
259