/[webpac]/branches/tehnika/WebPac.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Diff of /branches/tehnika/WebPac.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

trunk/WebPac.pm revision 73 by dpavlin, Sat Jul 5 22:31:46 2003 UTC branches/tehnika/WebPac.pm revision 601 by dpavlin, Wed Dec 8 18:45:32 2004 UTC
# Line 3  package WebPac; Line 3  package WebPac;
3  use base 'CGI::Application';  use base 'CGI::Application';
4  use strict;  use strict;
5    
 use HTML::Pager;  
6  use HTML::FillInForm;  use HTML::FillInForm;
7  use SWISH;  use SWISH::API;
8  use Text::Iconv;  use Text::Iconv;
9  use DBI;  use DBI;
10  use Config::IniFiles;  use Config::IniFiles;
11  use Text::Unaccent;  use Text::Unaccent;
12    use Data::Pageset;
13    
14  use lib '..';  use lib '..';
15  use index_DBI;  use index_DBI_cache;
16  use back2html;  use back2html;
17    
18  # configuration options  
19  # FIXME they really should go in configuration file!  # read global.conf configuration
20  my $TEMPLATE_PATH = '/data/webpac/template_html';  my $cfg_global = new Config::IniFiles( -file => '../global.conf' ) || die "can't open 'global.conf'";
21  my $CHARSET = 'ISO-8859-2';  
22  my $SWISH = '/usr/bin/swish-e';  # configuration options from global.conf
23  my $INDEX = '/data/webpac/index/isis.index';  my $TEMPLATE_PATH = $cfg_global->val('webpac', 'template_html') || die "need template_html in global.conf, section webpac";
24  my $MAX_HITS = 0;  my $CHARSET = $cfg_global->val('webpac', 'charset') || 'ISO-8859-1';
25  my $ON_PAGE = 10;  my $SWISH = $cfg_global->val('webpac', 'swish') || '/usr/bin/swish-e';
26    my $INDEX = $cfg_global->val('webpac', 'index') || die "need index in global.conf, section webpac";
27    my $MAX_HITS = $cfg_global->val('webpac', 'max_hits') || 0;
28    my $ON_PAGE =$cfg_global->val('webpac', 'on_page') || 10;
29    my $MIN_WILDCARD =$cfg_global->val('webpac', 'min_wildcard') || 1;
30    my $TEMPLATE =$cfg_global->val('webpac', 'template');
31    my $UNAC_FILTER =$cfg_global->val('global', 'my_unac_filter');
32    my $BASE_PATH =$cfg_global->val('webpac', 'base_path');
33    # for pager
34    my $pages_per_set = $cfg_global->val('webpac', 'pages_per_set') || 10;
35    
36  Text::Iconv->raise_error(0);     # Conversion errors raise exceptions  Text::Iconv->raise_error(0);     # Conversion errors raise exceptions
37    
38  my $from_utf8 = Text::Iconv->new('UTF8', $CHARSET);  my $from_utf8 = Text::Iconv->new('UTF8', $CHARSET);
39    
40  # read global.conf configuration  if ($UNAC_FILTER) {
41  my $cfg_global = new Config::IniFiles( -file => '../global.conf' ) || die "can't open 'global.conf'";          require $UNAC_FILTER;
42    } else {
43            sub WebPac::my_unac_string {
44                    my ($charset, $string) = (@_);
45                    return $string;
46            }
47    }
48    
49    # use path from cgi script to support templates in subdirs
50    sub url_ex {
51            my $q = shift || die "suff2file needs CGI object!";
52            my $tpl = shift || die "url_ex needs template name!";
53            return suff2file($BASE_PATH, $q->url(-absolute => 1,-path => 1),$TEMPLATE_PATH,$tpl);
54    }
55    
56    sub suff2file($$$$) {
57            my ($base_path, $p, $path, $tpl) = @_;
58    
59            return $tpl if (! $base_path);
60    
61            # strip everything to and including base path, leaving only
62            # additional (virtual) path
63            if ($base_path eq "/") {
64                    $p =~ s,/*,,g;
65                    my ($name,$ext) = split(/\./,$tpl);
66                    $p = $name . "-" . $p . "." . $ext;
67            } elsif ($p =~ s,^.*?$base_path,,) {
68                    $p =~ s,/*,,g;
69                    my ($name,$ext) = split(/\./,$tpl);
70                    $p = $name . $p . "." . $ext;
71            } else {
72                    # if unable reset it!
73                    $p = $tpl;
74            }
75    
76            if ( -e "$path/$p") {
77                    return $p;
78            } else {
79                    return $tpl;
80            }
81    
82    }
83    
84  sub setup {  sub setup {
85          my $self = shift;          my $self = shift;
# Line 47  sub setup { Line 96  sub setup {
96          $self->header_props(-charset=>$CHARSET);          $self->header_props(-charset=>$CHARSET);
97  }  }
98    
99    sub in_template {
100            my $q = shift || die "need CGI object!";
101            my $html = shift || die "This page is left unintentionally blank";
102            return $html if (! defined($TEMPLATE));
103    
104            my ($dir,$tpl);
105            if ($TEMPLATE =~ m,^(.*?/*)([^/]+)$,) {
106                    ($dir,$tpl) = ($1,$2);
107            } else {
108                    die "can't parse TEMPLATE path";
109            }
110    
111            my $master_tpl = suff2file($BASE_PATH, $q->url(-absolute => 1, -path => 1),$dir,$tpl);
112            if (open(T, $master_tpl)) {
113                    my $template_html = join("\n",<T>);
114                    close(T);
115                    $template_html =~ s/##webpac##/$html/gsi;
116                    return $template_html;
117            } else {
118                    return "Can't read template '$master_tpl'";
119            }
120    }
121    
122    #--------------------------------------------------------------------------
123    
124    #
125    # make pager navigation and fill template variables
126    # compatibile with HTML::Pager
127    #
128    
129    sub make_pager($$$) {
130            my ($q,$tmpl,$pager) = @_;
131    
132            #
133            # pager navigation
134            #
135            my ($pager_prev,$pager_next, $pager_jump) = ('','','');
136    
137            my $nav_fmt=qq{ <a href="%s">%s</a> };
138    
139            if ($pager->current_page() > $pager->first_page) {
140                    $q->param('PAGER_offset', $pager->current_page - 1);
141                    $pager_prev .= sprintf($nav_fmt,$q->url(-relative=>1, -query=>1),'&lt;&lt;');
142            }
143    
144            if ($pager->previous_set) {
145                    $q->param('PAGER_offset', $pager->previous_set);
146                    $pager_prev .= sprintf($nav_fmt,$q->url(-relative=>1, -query=>1),'..');
147            }
148    
149    
150            foreach my $p (@{$pager->pages_in_set()}) {
151                    next if ($p < 0);
152                    if($p == $pager->current_page()) {
153                            $pager_jump .= "<b>$p</b> ";
154                    } else {
155                            $q->param('PAGER_offset', $p);
156                            $pager_jump .= sprintf($nav_fmt,$q->url(-relative=>1, -query=>1),$p);
157                    }
158            }
159    
160            if ($pager->next_set) {
161                    $q->param('PAGER_offset', $pager->next_set);
162                    $pager_next .= sprintf($nav_fmt,$q->url(-relative=>1, -query=>1),'..');
163            }
164    
165            if ($pager->current_page() < $pager->last_page) {
166                    $q->param('PAGER_offset', $pager->current_page + 1);
167                    $pager_next .= sprintf($nav_fmt,$q->url(-relative=>1, -query=>1),'&gt;&gt;');
168            }
169    
170            $tmpl->param('PAGER_PREV', $pager_prev);
171            $tmpl->param('PAGER_JUMP', $pager_jump);
172            $tmpl->param('PAGER_NEXT', $pager_next);
173    
174    }
175    
176    #
177    # put persisten variables in template
178    #
179    
180    sub make_pager_vars {
181            my $q = shift @_;
182            my $tmpl = shift @_;
183            my @persist_vars = @_;
184            my $hidden_vars = '';
185            foreach my $v (@persist_vars) {
186                    foreach my $val ($q->param($v)) {
187                            $hidden_vars .= '<input type="hidden" name="'.$v.'" value="'.$val.'"/>'."\n";
188                    }
189            }
190    
191            $tmpl->param('PAGER_HIDDEN', $hidden_vars);
192            $tmpl->param('PAGER_JAVASCRIPT', qq{
193    <SCRIPT LANGUAGE="Javascript">
194    <!-- Begin
195            // dummy emulator for HTML::Pager templates
196            function PAGER_set_offset_and_submit() {
197                    return true;
198            }
199    // End -->
200    </script>  
201            });
202    }
203    
204    #--------------------------------------------------------------------------
205    
206  sub show_search_form {  sub show_search_form {
207          my $self = shift;          my $self = shift;
208    
209          # Get the CGI.pm query object          # Get the CGI.pm query object
210          my $q = $self->query();          my $q = $self->query();
211    
212          my $tmpl = $self->load_tmpl('search.html');          my $tmpl = $self->load_tmpl(url_ex($q,'search.html'));
213          my $html = $tmpl->output;          my $html = $tmpl->output;
214    
215          my $fif = new HTML::FillInForm;          my $fif = new HTML::FillInForm;
216    
217          return $fif->fill(scalarref => \$html, fobject => $q,          return in_template($q,$fif->fill(scalarref => \$html, fobject => $q,
218                  target => 'search');                  target => 'search'));
219  }  }
220    
221  sub show_results_list {  sub show_results_list {
# Line 67  sub show_results_list { Line 223  sub show_results_list {
223    
224          my $q = $self->query();          my $q = $self->query();
225    
         my @swish_results;      # results from swish  
   
226          # load template for this page          # load template for this page
227    
228          my @s_arr;      # all queries are located here          my @s_arr;      # all queries are located here
# Line 76  sub show_results_list { Line 230  sub show_results_list {
230          my @path_arr = $q->param('path');          my @path_arr = $q->param('path');
231          my $full = $q->param('full');          my $full = $q->param('full');
232    
233          for(my $i = 1; $i <=30; $i++) {          my @persist_vars = ( 'rm' );
234            my @url_params = ( 'rm=results', 'show_full=1', 'last_PAGER_offset='.($q->param('PAGER_offset') || 0) );
235    
236            # support parametars "f" and "v" for start
237            for(my $i = ""; $i <=30; $i++) {
238    
239                  return show_index($self, $i) if ($q->param("f".$i."_index"));                  return show_index($self, $i) if ($q->param("f".$i."_index"));
240    
241                  next if (! $q->param("v$i"));                  next if (! $q->param("v$i"));
242                  next if (! $q->param("f$i"));                  next if (! $q->param("f$i"));
243    
244                    push @persist_vars, "f$i";
245                    push @persist_vars, "v$i";
246                    push @persist_vars, "e$i" if ($q->param("e$i"));
247    
248                    push @url_params,"f$i=".$q->url_param("f$i");
249                    foreach my $v ($q->url_param("v$i")) {
250                            push @url_params,"v$i=$v";
251                    }
252                    push @url_params,"e$i=".$q->url_param("e$i");
253    
254                    my $wc="*";     # swish wildcard
255                    $wc="" if ($i eq "");   # don't apply wildcard on field 0
256    
257                  # re-write query from +/- to and/and not                  # re-write query from +/- to and/and not
258                  my @param_vals = $q->param("v$i");                  my @param_vals = $q->param("v$i");
259                  my @swish_q;                  my @swish_q;
260                    my ($pre,$post,$exact) = ('','','');
261                  while (my $search = shift @param_vals) {                  while (my $search = shift @param_vals) {
262                          my $s;                          my $s;
263                          # remove accents                          # remove accents
264                          $search = unac_string($CHARSET,$search);                          $search = my_unac_string($CHARSET,$search);
265                          while ($search =~ s/\s*("[^"]+")\s*/ /) {                          while ($search =~ s/\s*("[^"]+")\s*/ /) {
266                                  $s .= "$1 ";                                  $s .= "$1 ";
267                          }                          }
268                          $search =~ s/^\s+//;                          $search =~ s/^\s+//;
269                          $search =~ s/\s+$//;                          $search =~ s/\s+$//;
270    
271                            # filed e[nr] is exact match bitmask
272                            # 1 = beginning, 2=end, 3=both
273                            $pre = '"xxbxx ' if ($q->param("e$i") & 1);
274                            $post = ' xxexx"' if ($q->param("e$i") & 2);
275                            # add qotes on other side
276                            if ($q->param("e$i")) {
277                                    $pre = '"' if (! $pre);
278                                    $post = '"' if (! $post);
279                                    # what about wildcards?
280                                    $wc = '';
281                                    $wc = '*' if ($q->param("e$i") & 4);
282                                    $exact = '_exact';
283                            }
284    
285                          foreach (split(/\s+/,$search)) {                          foreach (split(/\s+/,$search)) {
286                                  if (m/^([+-])(\S+)/) {                                  if (m/^([+-])(\S+)/) {
287                                          $s.= ($s) ? "and " : "";                                          $s.= ($s) ? "and " : "";
288                                          $s.="not " if ($1 eq "-");                                          $s.="not " if ($1 eq "-");
289                                          $s.="$2* ";                                          $s.=$2.$wc." ";
290                                  } elsif (m/(and|or|not)/i) {                                  } elsif (m/^\s*(and|or|not)\s*$/i) {
291                                          $s.="$_ ";                                          $s.=$_." ";
292                                    # don't add * to words with less than x chars
293                                    } elsif (length($_) <= $MIN_WILDCARD) {
294                                            $s.=$_." ";
295                                  } else {                                  } else {
296                                          $s.="$_* ";                                          $s.=$_.$wc." ";
297                                  }                                  }
298                          }                          }
299                          $s =~ s/\*+/*/g;                          $s =~ s/\*+/*/g;
300                            $s = $pre.$s.$post if ($q->param("e$i"));
301                          push @swish_q,$s;                          push @swish_q,$s;
302                  }                  }
303                  # FIXME default operator for multi-value fields is or. There is                  # FIXME default operator for multi-value fields is or. There is
304                  # no way to change it, except here for now. Is there need?                  # no way to change it, except here for now. Is there need?
305                  push @s_arr, $q->param("f$i")."_swish=(".join(" or ",@swish_q).")";                  push @s_arr, $q->param("f$i")."_swish".$exact."=(".join(" or ",@swish_q).")";
306          }          }
307    
308          my $tmpl = $self->load_tmpl('results.html');          my $tmpl = $self->load_tmpl(url_ex($q,'results.html'), global_vars => 1);
309    
310          # call swish          $tmpl->param('url_params',"?".join("&",@url_params));
311          my $sh = SWISH->connect('Fork',  
312                  prog     => $SWISH,          sub esc_html {
313                  indexes  => $INDEX,                  my $html = shift;
314                  properties  => [qw/swishdocpath swishrank swishtitle headline html/],                  $html =~ s/</&lt;/g;
315                  results  => sub {                  $html =~ s/>/&gt;/g;
316                          my ($sh,$hit) = @_;                  return $html;
317            }
318                          push @swish_results, {  
319                                  nr => ($#swish_results + 2),          my $sort = 'swishrank';
320                                  path => $hit->swishdocpath,          if ($q->param("sort")) {
321                                  headline => $from_utf8->convert($hit->headline),                  $sort = 'headline';
322                                  html => back2html($from_utf8->convert($hit->html)),                  push @persist_vars, "sort";
323                                  rank => $hit->swishrank };          }
   
                 },  
                 #startnum => 0,  
                 maxhits => $MAX_HITS  
         );  
324    
         die $SWISH::errstr unless $sh;  
325          # construct swish query          # construct swish query
326          my $sw_q = join(" and ",@s_arr);          my $sw_q = join(" and ",@s_arr);
327          if (@path_arr) {          if (@path_arr) {
328                  $sw_q .= "and (swishdocpath=\"";                  $sw_q .= "and (swishdocpath=\"";
329                  $sw_q .= join("\" or swishdocpath=\"",@path_arr);                  $sw_q .= join("\" or swishdocpath=\"",@path_arr);
330                  $sw_q .= "\")";                  $sw_q .= "\")";
                 $tmpl->param('full',1); # show full records  
331          }          }
332    
333          my $hits = $sh->query($sw_q);          if ($q->param('show_full')) {
334                    # just show full path, no path defined
335                    $tmpl->param('full',1);
336            } else {
337                    $tmpl->param('full',0);
338            }
339    
340            # create new swish instance
341            my $swish = SWISH::API->new($INDEX);
342            $swish->AbortLastError if $swish->Error;
343    
344            # execute query and get number of results from SWISH-E
345            my $search = $swish->New_Search_Object;
346    
347            $search->SetSort($sort);
348    
349            my $results = $search->Execute($sw_q);
350            $swish->AbortLastError if $swish->Error;
351    
352            my $hits = $results->Hits;
353    
354          $tmpl->param('hits',$hits);          $tmpl->param('hits',$hits);
355          $tmpl->param('search',$sw_q);          $tmpl->param('search',$sw_q);
356    
357          $tmpl->param('PAGER_offset',$q->param("PAGER_offset") || 1);          $tmpl->param('PAGER_offset',$q->param("PAGER_offset") || 0);
358          $tmpl->param('last_PAGER_offset',$q->param("last_PAGER_offset") || 1);          $tmpl->param('last_PAGER_offset',$q->param("last_PAGER_offset") || 0);
359    
360          # create a Pager object          #
361          my $pager = HTML::Pager->new(          # build pager
362                  # required parameters          #
363                  query => $q,  
364                  get_data_callback => sub {          my $current_page = $q->param('PAGER_offset') || 1;
365                          my ($offset, $rows) = @_;  
366            my $pager = Data::Pageset->new({
367                          my @result;                  'total_entries' => $hits,
368                          for (my $i=0; $i<$rows; $i++) {                  'entries_per_page' => $ON_PAGE,
369                                  push @result, $swish_results[$offset+$i] if $swish_results[$offset+$i];                  'current_page' => $current_page,
370                          }                  'pages_per_set' => $pages_per_set,
371                          return \@result;          });
372                  },  
373                  rows => $hits,          $results->SeekResult( $pager->first - 1 );
374                  page_size => $ON_PAGE,  
375                  # some optional parameters          # get number of entries on this page
376                  persist_vars => [          my $i = $pager->entries_on_this_page;
377                          'rm',  
378                          'f1', 'v1',          # results from swish for template
379                          'f2', 'v2',          my @pager_data_list;
                         'f3', 'v3',  
                         'f4', 'v4',  
                         'f5', 'v5',  
                         'f6', 'v6',  
                         'f7', 'v7',  
                         'f8', 'v8',  
                         'f9', 'v9',  
                         ],  
                 #cell_space_color => '#000000',  
                 #cell_background_color => '#ffffff',  
                 #nav_background_color => '#dddddd',  
                 #javascript_presubmit => 'last_minute_javascript()',  
                 debug => 1,  
                 template => $tmpl,  
         );  
380    
381          my $html = $pager->output;          for(my $i=$pager->first; $i<=$pager->last; $i++) {
382    
383                    my $result = $results->NextResult;
384                    last if (! $result);
385    
386                    my $r = {
387                            nr => $i,
388                            path => $result->Property('swishdocpath'),
389                            headline => esc_html($from_utf8->convert($result->Property('headline'))),
390                            rank => $result->Property('swishrank')
391                    };
392    
393                    $r->{html} = back2html($from_utf8->convert($result->Property('html'))) if ($q->param('show_full'));
394    
395                    push @pager_data_list, $r;
396            }
397    
398          return $html;  
399    
400            # put something in template
401            make_pager($q, $tmpl, $pager);
402            make_pager_vars($q, $tmpl, @persist_vars);
403            $tmpl->param('PAGER_DATA_LIST', \@pager_data_list);
404    
405            my $html = $tmpl->output;
406    
407            return in_template($q,$html);
408  }  }
409    
410  sub show_index {  sub show_index {
# Line 213  sub show_index { Line 425  sub show_index {
425                  $cfg_global->val('global', 'dbi_passwd') || ''                  $cfg_global->val('global', 'dbi_passwd') || ''
426          );          );
427    
428          my $total = $index->check($field);          my $total = $index->count($field,$limit);
429    
430          if (! $total) {          if (! $total) {
431                  my $tmpl = $self->load_tmpl('no_index.html');                  my $tmpl = $self->load_tmpl(url_ex($q,'no_index.html'));
432                  $tmpl->param('field',$field);                  $tmpl->param('field',$field);
433                  $html = $tmpl->output;                  $html = $tmpl->output;
434                  return $html;                  return $html;
435          }          }
436    
437          my $tmpl = $self->load_tmpl('index_res.html');          my $tmpl = $self->load_tmpl(url_ex($q,'index_res.html'), global_vars => 1);
438          $tmpl->param('field',$field);          $tmpl->param('field',$field);
439          $tmpl->param('limit',$limit);          $tmpl->param('limit',$limit);
440          $tmpl->param('total',$total);          $tmpl->param('total',$total);
# Line 231  sub show_index { Line 444  sub show_index {
444  #               $q->param("Pager_offet)  #               $q->param("Pager_offet)
445  #       }  #       }
446    
         my $pager = HTML::Pager->new(  
                 query => $q,  
                 get_data_callback => sub {  
                         my ($offset, $rows) = @_;  
   
                         my @result = $index->fetch($field,'item',$limit, $offset, $rows);  
                         return \@result;  
                 },  
                 rows => $total,  
                 page_size => $ON_PAGE,  
                 persist_vars => [  
                         'rm',  
                         "f$i", "v$i", "f".$i."_index",  
                         'offset',  
                         ],  
                 debug => 1,  
                 template => $tmpl,  
         );  
447    
448          return $pager->output;          #
449            # build pager
450            #
451            my $pager = Data::Pageset->new({
452                    'total_entries' => $total,
453                    'entries_per_page' => $ON_PAGE,
454                    'current_page' => $q->param('PAGER_offset') || 1,
455                    'pages_per_set' => $pages_per_set
456            });
457    
458            my @persist_vars = qw{rm f$i v$i f$i_index offset};
459    
460            make_pager($q, $tmpl, $pager);
461            make_pager_vars($q, $tmpl, @persist_vars);
462    
463            my @pager_data_list = $index->fetch($field,$limit, $pager->first - 1, $pager->entries_on_this_page);
464            $tmpl->param('PAGER_DATA_LIST', \@pager_data_list);
465    
466            return in_template($q,$tmpl->output);
467  }  }
468    
469  1;  1;

Legend:
Removed from v.73  
changed lines
  Added in v.601

  ViewVC Help
Powered by ViewVC 1.1.26