Demote module directory matches
[webmin.git] / webmin-search-lib.pl
1 # Functions for searching the webmin docs and UI
2
3 =head2 search_webmin(phrase, [callback-function])
4
5 Searches all Webmin help pages, UI text, module names and config.info files
6 for entries matching the given phrase or word. Returns them sorted by relevance
7 order, each as a hash ref with the following keys :
8
9 =item mod - A module hash reference for the module the search result was in
10
11 =item rank - A result ranking, higher being better
12
13 =item type - One of mod (for module name), dir (for module directory), config (configuration setting), help (help page) or text (UI text)
14
15 =item text - The text that matched
16
17 =items cgis - An array ref of pages on which the text appears, each formatted like module/script.cgi
18
19 =cut
20 sub search_webmin
21 {
22 my ($re, $cbfunc) = @_;
23
24 # Work out this Webmin's URL base
25 my $urlhost = $ENV{'HTTP_HOST'};
26 if ($urlhost !~ /:/) {
27         $urlhost .= ":".$ENV{'SERVER_PORT'};
28         }
29 my $urlbase = ($ENV{'HTTPS'} eq 'ON' ? 'https://' : 'http://').$urlhost;
30
31 # Search module names and add to results list
32 my @rv = ( );
33 my @mods = sort { $b->{'longdesc'} cmp $a->{'longdesc'} }
34              grep { !$_->{'clone'} } &get_available_module_infos();
35 foreach my $m (@mods) {
36         if ($m->{'desc'} =~ /\Q$re\E/i) {
37                 # Module description match
38                 push(@rv, { 'mod' => $m,
39                             'rank' => 10,
40                             'type' => 'mod',
41                             'link' => $m->{'dir'}.'/',
42                             'text' => $m->{'desc'} });
43                 }
44         elsif ($m->{'dir'} =~ /\Q$re\E/i) {
45                 # Module directory match
46                 push(@rv, { 'mod' => $m,
47                             'rank' => 9,
48                             'type' => 'dir',
49                             'link' => $m->{'dir'}.'/',
50                             'text' => $urlbase."/".$m->{'dir'}."/" });
51                 }
52         &$cbfunc() if ($cbfunc);
53         }
54
55 # Search module configs and their help pages
56 foreach my $m (@mods) {
57         my %access = &get_module_acl(undef, $m);
58         next if ($access{'noconfig'});
59         my $file = $prod eq 'webmin' ? "$m->{'dir'}/config.info"
60                                      : "$m->{'dir'}/uconfig.info";
61         my %info = ( );
62         my @info_order = ( );
63         &read_file($file, \%info, \@info_order);
64         foreach my $o (@lang_order_list) {
65                 &read_file("$file.$o", \%info);
66                 }
67         my $section = undef;
68         foreach my $c (@info_order) {
69                 my @p = split(/,/, $info{$c});
70                 if ($p[1] == 11) {
71                         $section = $c;
72                         }
73                 if ($p[0] =~ /\Q$re\E/i) {
74                         # Config description matches
75                         push(@rv, { 'mod' => $m,
76                                     'rank' => 8,
77                                     'type' => 'config',
78                                     'link' => "/config.cgi?module=$m->{'dir'}&".
79                                              "section=".&urlize($section)."#$c",
80                                     'text' => $p[0],
81                                   });
82                         }
83                 my $hfl = &help_file($mod->{'dir'}, "config_".$c);
84                 my ($title, $help) = &help_file_match($hfl);
85                 if ($help) {
86                         # Config help matches
87                         push(@rv, { 'mod' => $m,
88                                     'rank' => 6,
89                                     'type' => 'help',
90                                     'link' => "/help.cgi/$m->{'dir'}/config_".$c,
91                                     'desc' => &text('wsearch_helpfor', $p[0]),
92                                     'text' => $help,
93                                     'cgis' => [ "/config.cgi?".
94                                                 "module=$m->{'dir'}&section=".
95                                                 &urlize($section)."#$c" ],
96                                    });
97                         }
98                 }
99         &$cbfunc() if ($cbfunc);
100         }
101
102 # Search other help pages
103 my %lang_order_list = map { $_, 1 } @lang_order_list;
104 foreach my $m (@mods) {
105         my $helpdir = &module_root_directory($m->{'dir'})."/help";
106         my %donepage = ( );
107         opendir(DIR, $helpdir);
108         foreach my $f (sort { length($b) <=> length($a) } readdir(DIR)) {
109                 next if ($f =~ /^config_/);     # For config help, already done
110
111                 # Work out if we should grep this help page - don't do the same
112                 # page twice for different languages
113                 my $grep = 0;
114                 my ($page, $lang);
115                 if ($f =~ /^(\S+)\.([^\.]+)\.html$/) {
116                         ($page, $lang) = ($1, $2);
117                         if ($lang_order_list{$lang} && !$donepage{$page}++) {
118                                 $grep = 1;
119                                 }
120                         }
121                 elsif ($f =~ /^(\S+)\.html$/) {
122                         $page = $1;
123                         if (!$donepage{$page}++) {
124                                 $grep = 1;
125                                 }
126                         }
127
128                 # If yes, search it
129                 if ($grep) {
130                         my ($title, $help) = &help_file_match("$helpdir/$f");
131                         if ($title) {
132                                 my @cgis = &find_cgi_text(
133                                         [ "hlink\\(.*'$page'",
134                                           "hlink\\(.*\"$page\"",
135                                           "header\\([^,]+,[^,]+,[^,]+,\\s*\"$page\"",
136                                           "header\\([^,]+,[^,]+,[^,]+,\\s*'$page'",
137                                         ], $m, 1);
138                                 push(@rv, { 'mod' => $m,
139                                             'rank' => 6,
140                                             'type' => 'help',
141                                             'link' => "/help.cgi/$m->{'dir'}/$page",
142                                             'desc' => $title,
143                                             'text' => $help,
144                                             'cgis' => \@cgis });
145                                 }
146                         }
147                 &$cbfunc() if ($cbfunc);
148                 }
149         closedir(DIR);
150         }
151
152 # Then do text strings
153 my %gtext = &load_language("");
154 MODULE: foreach my $m (@mods) {
155         my %mtext = &load_language($m->{'dir'});
156         foreach my $k (keys %mtext) {
157                 next if ($gtext{$k});   # Skip repeated global strings
158                 $mtext{$k} =~ s/\$[0-9]//g;
159                 if ($mtext{$k} =~ /\Q$re\E/i) {
160                         # Find CGIs that use this text
161                         my @cgis = &find_cgi_text(
162                                 [ "\$text{'$k'}",
163                                   "\$text{\"$k\"}",
164                                   "\$text{$k}",
165                                   "&text('$k'",
166                                   "&text(\"$k\"" ], $m);
167                         if (@cgis) {
168                                 push(@rv, { 'mod' => $m,
169                                             'rank' => 4,
170                                             'type' => 'text',
171                                             'text' => $mtext{$k},
172                                             'cgis' => \@cgis });
173                                 }
174                         }
175                 }
176         &$cbfunc() if ($cbfunc);
177         }
178
179 # Sort results by relevancy
180 # XXX can do better?
181 @rv = sort { $b->{'rank'} <=> $a->{'rank'} ||
182              lc($a->{'mod'}->{'desc'}) cmp lc($b->{'mod'}->{'desc'}) } @rv;
183 return @rv;
184 }
185
186 # highlight_text(text, [length])
187 # Returns text with the search term bolded, and truncated to 50 characters
188 sub highlight_text
189 {
190 local ($str, $len) = @_;
191 $len ||= 50;
192 local $hlen = $len / 2;
193 $str =~ s/<[^>]*>//g;
194 if ($str =~ /(.*)(\Q$re\E)(.*)/i) {
195         local ($before, $match, $after) = ($1, $2, $3);
196         if (length($before) > $hlen) {
197                 $before = "...".substr($before, length($before)-$hlen);
198                 }
199         if (length($after) > $hlen) {
200                 $after = substr($after, 0, $hlen)."...";
201                 }
202         $str = $before."<b>".&html_escape($match)."</b>".$after;
203         }
204 return $str;
205 }
206
207 # find_cgi_text(&regexps, module, re-mode)
208 # Returns the relative URLs of CGIs that matches some regexps, in the given
209 # module. Does not include those that don't call some header function, as
210 # they cannot be linked to normally
211 sub find_cgi_text
212 {
213 local ($res, $m, $remode) = @_;
214 local $mdir = &module_root_directory($m);
215 local @rv;
216 foreach my $f (glob("$mdir/*.cgi")) {
217         local $found = 0;
218         local $header = 0;
219         open(CGI, $f);
220         LINE: while(my $line = <CGI>) {
221                 if ($line =~ /(header|ui_print_header|ui_print_unbuffered_header)\(/) {
222                         $header++;
223                         }
224                 foreach my $r (@$res) {
225                         if (!$remode && index($line, $r) >= 0 ||
226                             $remode && $line =~ /$r/) {
227                                 $found++;
228                                 last LINE;
229                                 }
230                         }
231                 }
232         close(CGI);
233         if ($found && $header) {
234                 local $url = $f;
235                 $url =~ s/^\Q$root_directory\E\///;
236                 push(@rv, $url);
237                 }
238         }
239 return @rv;
240 }
241
242 # help_file_match(file)
243 # Returns the title if some help file matches the current search
244 sub help_file_match
245 {
246 local ($f) = @_;
247 local $data = &read_file_contents($f);
248 local $title;
249 if ($data =~ /<header>([^<]*)<\/header>/) {
250         $title = $1;
251         }
252 $data =~ s/\s+/ /g;
253 $data =~ s/<p>/\n\n/gi;
254 $data =~ s/<br>/\n/gi;
255 $data =~ s/<[^>]+>//g;
256 if ($data =~ /\Q$re\E/i) {
257         return ($title, $data);
258         }
259 return ( );
260 }
261
262 # cgi_page_title(module, cgi)
263 # Given a CGI, return the text for its page title, if possible
264 sub cgi_page_title
265 {
266 local ($m, $cgi) = @_;
267 local $data = &read_file_contents(&module_root_directory($m)."/".$cgi);
268 local $rv;
269 if ($data =~ /(ui_print_header|ui_print_unbuffered_header)\([^,]+,[^,]*(\$text{'([^']+)'|\$text{"([^"]+)"|\&text\('([^']+)'|\&text\("([^"]+)")/) {
270         # New header function, with arg before title
271         local $msg = $3 || $4 || $5 || $6;
272         local %mtext = &load_language($m);
273         $rv = $mtext{$msg};
274         }
275 elsif ($data =~ /(^|\s)header\(\s*(\$text{'([^']+)'|\$text{"([^"]+)"|\&text\('([^']+)'|\&text\("([^"]+)")/) {
276         # Old header function
277         local $msg = $3 || $4 || $5 || $6;
278         local %mtext = &load_language($m);
279         $rv = $mtext{$msg};
280         }
281 if ($cgi eq "index.cgi" && !$rv) {
282         # If no title was found for an index.cgi, use module title
283         local %minfo = &get_module_info($m);
284         $rv = $minfo{'desc'};
285         }
286 return $rv;
287 }
288
289 # cgi_page_args(module, cgi)
290 # Given a module and CGI name, returns a string of URL parameters that can be
291 # used for linking to it. Returns "none" if parameters are needed, but cannot
292 # be determined.
293 sub cgi_page_args
294 {
295 local ($m, $cgi) = @_;
296 local $mroot = &module_root_directory($m);
297 if (-r "$mroot/cgi_args.pl") {
298         # Module can tell us what args to use
299         &foreign_require($m, "cgi_args.pl");
300         $args = &foreign_call($m, "cgi_args", $cgi);
301         if (defined($args)) {
302                 return $args;
303                 }
304         }
305 if ($cgi eq "index.cgi") {
306         # Index page is always safe to link to
307         return undef;
308         }
309 # Otherwise check if it appears to parse any args
310 local $data = &read_file_contents($mroot."/".$cgi);
311 if ($data =~ /(ReadParse|ReadParseMime)\(/) {
312         return "none";
313         }
314 return undef;
315 }
316
317 1;
318