/[webpac]/trunk/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 /trunk/WebPac.pm

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

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

Legend:
Removed from v.30  
changed lines
  Added in v.696

  ViewVC Help
Powered by ViewVC 1.1.26