/[webpac2]/Webpacus/lib/Webpacus/Model/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 /Webpacus/lib/Webpacus/Model/WebPAC.pm

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

revision 351 by dpavlin, Sat Jan 7 18:18:07 2006 UTC revision 399 by dpavlin, Sun Feb 19 12:37:27 2006 UTC
# Line 6  use lib '/data/webpac2/lib'; Line 6  use lib '/data/webpac2/lib';
6  use base qw/  use base qw/
7          Catalyst::Model          Catalyst::Model
8  /;  /;
 use Data::Dumper;  
9  use WebPAC::Store 0.08;  use WebPAC::Store 0.08;
10  use WebPAC::Output::TT 0.07;  use Search::Estraier 0.04;
 use WebPAC::Search::Estraier 0.05;  
11  use File::Slurp;  use File::Slurp;
12  use Time::HiRes;  use Time::HiRes qw/time/;
13  use Encode qw/encode decode from_to/;  use Encode qw/encode decode from_to/;
14  use Data::HTMLDumper;  use Template;
15    use Data::Dumper;
16    
17  =head1 NAME  =head1 NAME
18    
# Line 75  sub new { Line 74  sub new {
74                  $est_cfg->{database} = $defaultnode;                  $est_cfg->{database} = $defaultnode;
75          }          }
76    
77          $self->{est} = new WebPAC::Search::Estraier( %{ $est_cfg } );          my $url = $est_cfg->{masterurl} . '/node/' . $est_cfg->{database};
78    
79            $log->info("opening Hyper Estraier index $url as $est_cfg->{'user'}");
80    
81            $self->{est_node} = Search::Estraier::Node->new(
82                    url => $url,
83                    user => $est_cfg->{user},
84                    passwd => $est_cfg->{passwd},
85            );
86    
87            $log->fatal("can't create Search::Estraier::Node $url") unless ($self->{est_node});
88    
89          # save config parametars in object          # save config parametars in object
90          foreach my $f (qw/db_path template_path hits_on_page webpac_encoding defaultdepth/) {          foreach my $f (qw/
91                    db_path template_path hits_on_page webpac_encoding defaultdepth
92                    masterurl
93                    /) {
94                  $self->{$f} = $c->config->{hyperestraier}->{$f} ||                  $self->{$f} = $c->config->{hyperestraier}->{$f} ||
95                          $c->config->{webpac}->{$f};                          $c->config->{webpac}->{$f};
96                  $log->debug("self->{$f} = " . $self->{$f});                  $log->debug("self->{$f} = " . $self->{$f});
# Line 94  sub new { Line 106  sub new {
106                  database => $est_cfg->{database},                  database => $est_cfg->{database},
107          );          );
108    
         $self->{out} = new WebPAC::Output::TT(  
                 include_path => $template_path,  
                 filters => {  
                         dump_html => sub {  
                                 my $t = shift || return;  
                                 #return Data::HTMLDumper->Dumper( $t );  
                                 return Data::HTMLDumper->Dump([$t],[qw/dump/]);  
                         }  
                 },  
         );  
   
109          # default template from config.yaml          # default template from config.yaml
110          $self->{template} ||= $c->config->{webpac}->{template};          $self->{template} ||= $c->config->{webpac}->{template};
111    
# Line 113  sub new { Line 114  sub new {
114                  "'"                  "'"
115          );          );
116    
117          $self->{databases} = $c->config->{databases} || $log->error("can't find databases in config");          $self->{databases} = $c->config->{databases} || $log->fatal("can't find databases in config");
118    
119            # create Template toolkit instance
120            $self->{'tt'} = Template->new(
121                    INCLUDE_PATH => $template_path,
122                    FILTERS => {
123                            dump_html => sub {
124                                    return unless (@_);
125                                    my $out;
126                                    my $i = 1;
127                                    foreach my $v (@_) {
128                                            $out .= qq{<div id="dump_$i">} .
129                                                    Data::HTMLDumper->Dump([ $v ],[ "v$i" ]) .
130                                                    qq{</div>};
131                                            $i++;
132                                    }
133                                    $out =~ s!<table[^>/]*>!<table class="dump">!gis if ($out);
134                                    return $out;
135                            }
136                    },
137                    EVAL_PERL => 1,
138            );
139    
140          return $self;          return $self;
141    
142  }  }
143    
144    =head2 setup_site
145    
146     $self->setup_site('site_name');
147    
148    Change node URL and database name according to site name (if available)
149    
150    =cut
151    
152    sub setup_site {
153            my $self = shift;
154    
155            my $site = shift || return;
156    
157            my $url = $self->{masterurl} . '/node/' . $site;
158            $self->{est_node}->set_url( $url );
159            $self->{log}->debug("setup_site $site");
160    }
161    
162  =head2 search  =head2 search
163    
# Line 140  selected template. Line 179  selected template.
179  sub search {  sub search {
180          my $self = shift;          my $self = shift;
181    
182            my $search_start_t = time();
183    
184          my $args = {@_};          my $args = {@_};
185    
186          my $log = $self->{log};          my $log = $self->{log};
# Line 148  sub search { Line 189  sub search {
189    
190          my $query = $args->{phrase} || $log->warn("no query phrase") && return;          my $query = $args->{phrase} || $log->warn("no query phrase") && return;
191    
         $log->debug("search model query: '$query'");  
         if ($args->{add_attr}) {  
                 $log->debug(" + add_attr: " .  
                         join("','", @{ $args->{add_attr} })  
                 );  
         }  
   
192          my $template_filename = $args->{template} || $self->{template};          my $template_filename = $args->{template} || $self->{template};
193    
194          $args->{max} ||= $self->{'hits_for_pager'};          $args->{max} ||= $self->{'hits_for_pager'};
# Line 173  sub search { Line 207  sub search {
207                  $args->{depth} = $default;                  $args->{depth} = $default;
208                  $log->warn("using default search depth $default");                  $log->warn("using default search depth $default");
209          }          }
210            $args->{depth} ||= 0;
211    
212          my @results = $self->{est}->search( %{ $args } );          $log->debug("searching for maximum $args->{max} results using depth $args->{depth} phrase: ", $query || '[none]');
213    
214          $times->{est} += time() - $t;          #
215            # construct condition for Hyper Estraier
216            #
217            my $cond = Search::Estraier::Condition->new();
218            if ( ref($args->{add_attr}) eq 'ARRAY' ) {
219                    $log->debug("adding search attributes: " . join(", ", @{ $args->{add_attr} }) );
220                    map {
221                            $cond->add_attr( $_ );
222                            $log->debug(" + $_");
223                    } @{ $args->{add_attr} };
224            };
225    
226            $cond->set_phrase( $query ) if ($query);
227            $cond->set_options( $args->{options} ) if ($args->{options});
228            $cond->set_order( $args->{order} ) if ($args->{order});
229    
230            my $max = $args->{max} || 7;
231            my $page = $args->{page} || 1;
232            if ($page < 1) {
233                    $log->warn("page number $page < 1");
234                    $page = 1;
235            }
236    
237            $cond->set_max( $page * $max );
238    
239            my $result = $self->{est_node}->search($cond, $args->{depth});
240            my $hits = $result->doc_num;
241    
242          my $hits = $#results + 1;          $times->{est} += time() - $t;
243    
244          $log->debug( sprintf("search took %.2fs and returned $hits hits.", $times->{est}) );          $log->debug( sprintf("search took %.6fs and returned $hits hits.", $times->{est}) );
245    
246          # just return results?          $log->debug( "hints: " . Dumper($result->{hints}) );
         return @results unless ($args->{'template'});  
247    
248          #          #
249          # construct HTML results          # fetch results
250          #          #
251    
252          my @html_results;          my @results;
253    
254          for my $i ( 0 .. $#results ) {          for my $i ( (($page - 1) * $max) .. ( $hits - 1 ) ) {
255    
256                  my ($database, $prefix, $id);                  $t = time();
257                  if ( $results[$i]->{'@uri'} =~ m!/([^/]+)/([^/]+)/(\d+)$!) {  
258                          ($database, $prefix,$id) = ($1,$2,$3);                  #$log->debug("get_doc($i)");
259                  } else {                  my $doc = $result->get_doc( $i );
260                          $log->warn("can't decode database/prefix/id from " .  $results[$i]->{'@uri'});                  if (! $doc) {
261                            $log->warn("can't find result $i");
262                          next;                          next;
263                  }                  }
264    
265                  #$log->debug("load_ds( id => $id, prefix => '$prefix' )");                  my $hash;
266    
267                  $t = time();                  foreach my $attr (@{ $args->{get_attr} }) {
268                            my $val = $doc->attr( $attr );
269                  my $ds = $self->{db}->load_ds( database => $database, prefix => $prefix, id => $id );                          #$log->debug("attr $attr = ", $val || 'undef');
270                  if (! $ds) {                          $hash->{$attr} = $val if (defined($val));
                         $log->error("can't load_ds( ${database}/${prefix}/${id} )");  
                         next;  
271                  }                  }
272    
273                  $times->{db} += time() - $t;                  $times->{hash} += time() - $t;
274    
275                  #$log->debug( "ds = " . Dumper( \@html_results ) );                  next unless ($hash);
276    
277                  $t = time();                  if (! $args->{'template'}) {
278                            push @results, $hash;
279                    } else {
280                            my ($database, $prefix, $id);
281    
282                  my $html = $self->{out}->apply(                          if ( $hash->{'@uri'} =~ m!/([^/]+)/([^/]+)/(\d+)$!) {
283                          template => $template_filename,                                  ($database, $prefix,$id) = ($1,$2,$3);
284                          data => $ds,                          } else {
285                          record_uri => "${database}/${prefix}/${id}",                                  $log->warn("can't decode database/prefix/id from " .  $hash->{'@uri'});
286                          config => $self->{databases}->{$database},                                  next;
287                  );                          }
288    
289                  $times->{out} += time() - $t;                          #$log->debug("load_ds( id => $id, prefix => '$prefix' )");
290    
291                  $t = time();                          $t = time();
292    
293                            my $ds = $self->{db}->load_ds( database => $database, prefix => $prefix, id => $id );
294                            if (! $ds) {
295                                    $log->error("can't load_ds( ${database}/${prefix}/${id} )");
296                                    next;
297                            }
298    
299                            $times->{db} += time() - $t;
300    
301                            #$log->debug( "ds = " . Dumper( \@html_results ) );
302    
303                            $t = time();
304    
305                            my $html = $self->apply(
306                                    template => $template_filename,
307                                    data => $ds,
308                                    record_uri => "${database}/${prefix}/${id}",
309                                    config => $self->{databases}->{$database},
310                            );
311    
312                  $html = decode($self->{webpac_encoding}, $html);                          $times->{apply} += time() - $t;
313    
314                  push @html_results, $html;                          $t = time();
315    
316                            $html = decode($self->{webpac_encoding}, $html);
317    
318                            $times->{decode} += time() - $t;
319    
320                            push @results, $html;
321                    }
322    
323          }          }
324    
325          #$log->debug( '@html_results = ' . Dumper( \@html_results ) );          #$log->debug( '@results = ' . Dumper( \@results ) );
326    
327          $log->debug( sprintf(          $log->debug( sprintf(
328                  "time spent: db = %.2f, out = %.2f",                  "duration breakdown: estraier %.6fs, hash %.6fs, store %.6fs, apply %.6fs, decode %.06f, total: %.6fs",
329                  $times->{db}, $times->{out},                  $times->{est}, $times->{hash}, $times->{db}, $times->{apply}, $times->{decode}, time() - $search_start_t,
330          ) );          ) );
331    
332          return \@html_results;          return \@results;
333  }  }
334    
335  =head2 record  =head2 record
# Line 282  sub record { Line 370  sub record {
370                  return;                  return;
371          }          }
372    
373          my $html = $self->{out}->apply(          my $html = $self->apply(
374                  template => $args->{template},                  template => $args->{template},
375                  data => $ds,                  data => $ds,
376                  record_uri => $args->{record_uri},                  record_uri => $args->{record_uri},
# Line 351  sub load_html { Line 439  sub load_html {
439          return decode($self->{webpac_encoding}, $content);          return decode($self->{webpac_encoding}, $content);
440  }  }
441    
442    
443    =head2 apply
444    
445    Create output from in-memory data structure using Template Toolkit template.
446    
447     my $text = $tt->apply(
448            template => 'text.tt',
449            data => $ds,
450            record_uri => 'database/prefix/mfn',
451     );
452    
453    It also has follwing template toolikit filter routies defined:
454    
455    =cut
456    
457    sub apply {
458            my $self = shift;
459    
460            my $args = {@_};
461    
462            my $log = $self->{log} || die "no log?";
463    
464            foreach my $a (qw/template data/) {
465                    $log->fatal("need $a") unless ($args->{$a});
466            }
467    
468    =head3 tt_filter_type
469    
470    filter to return values of specified from $ds, usage from TT template is in form
471    C<d('FieldName','delimiter')>, where C<delimiter> is optional, like this:
472    
473      [% d('Title') %]
474      [% d('Author',', ' %]
475    
476    =cut
477    
478            sub tt_filter_type {
479                    my ($data,$type) = @_;
480                    
481                    die "no data?" unless ($data);
482                    $type ||= 'display';
483    
484                    my $default_delimiter = {
485                            'display' => '&#182;<br/>',
486                            'index' => '\n',
487                    };
488    
489                    return sub {
490    
491                            my ($name,$join) = @_;
492    
493                            die "no data hash" unless ($data->{'data'} && ref($data->{'data'}) eq 'HASH');
494                            # Hm? Should we die here?
495                            return unless ($name);
496    
497                            my $item = $data->{'data'}->{$name} || return;
498    
499                            my $v = $item->{$type} || return;
500    
501                            if (ref($v) eq 'ARRAY') {
502                                    if ($#{$v} == 0) {
503                                            $v = $v->[0];
504                                    } else {
505                                            $join = $default_delimiter->{$type} unless defined($join);
506                                            $v = join($join, @{$v});
507                                    }
508                            } else {
509                                    warn("TT filter $type(): field $name values aren't ARRAY, ignoring");
510                            }
511    
512                            return $v;
513                    }
514            }
515    
516            $args->{'d'} = tt_filter_type($args, 'display');
517            $args->{'display'} = tt_filter_type($args, 'display');
518    
519    =head3 tt_filter_search
520    
521    filter to return links to search, usage in TT:
522    
523      [% search('FieldToDisplay','FieldToSearch','optional delimiter', 'optional_template.tt') %]
524    
525    =cut
526    
527            sub tt_filter_search {
528    
529                    my ($data) = @_;
530    
531                    die "no data?" unless ($data);
532                    
533                    return sub {
534    
535                            my ($display,$search,$delimiter,$template) = @_;
536                            
537                            # default delimiter
538                            $delimiter ||= '&#182;<br/>',
539    
540                            die "no data hash" unless ($data->{'data'} && ref($data->{'data'}) eq 'HASH');
541                            # Hm? Should we die here?
542                            return unless ($display);
543    
544                            my $item = $data->{'data'}->{$display} || return;
545    
546                            return unless($item->{'display'});
547                            if (! $item->{'search'}) {
548                                    warn "error in TT template: field $display didn't insert anything into search, use d('$display') and not search('$display'...)";
549                                    return;
550                            }
551    
552                            my @warn;
553                            foreach my $type (qw/display search/) {
554                                    push @warn, "field $display type $type values aren't ARRAY" unless (ref($item->{$type}) eq 'ARRAY');
555                            }
556    
557                            if (@warn) {
558                                    warn("TT filter search(): " . join(",", @warn) . ", skipping");
559                                    return;
560                            }
561                            my @html;
562    
563                            my $d_el = $#{ $item->{'display'} };
564                            my $s_el = $#{ $item->{'search'} };
565    
566                            # easy, both fields have same number of elements or there is just
567                            # one search and multiple display
568                            if ( $d_el == $s_el || $s_el == 0 ) {
569    
570                                    foreach my $i ( 0 .. $d_el ) {
571    
572                                            my $s;
573                                            if ($s_el > 0) {
574                                                    $s = $item->{'search'}->[$i] or warn "can't find value $i for type search in field $search";
575                                            } else {
576                                                    $s = $item->{'search'}->[0];
577                                            }
578                                            #$s =~ s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
579                                            $s = __quotemeta( $s );
580    
581                                            my $d = $item->{'display'}->[$i] or warn "can't find value $i for type display in field $display";
582    
583                                            my $template_arg = '';
584                                            $template_arg = qq{,'$template'} if ($template);
585    
586                                            push @html, qq{<a href="#" onclick="return search_via_link('$search','$s'${template_arg})">$d</a>};
587                                    }
588    
589                                    return join($delimiter, @html);
590                            } else {
591                                    my $html = qq{<div class="notice">WARNING: we should really support if there is $d_el display elements and $s_el search elements, but currently there is no nice way to do so, so we will just display values</div>};
592                                    my $v = $item->{'display'};
593    
594                                    if ($#{$v} == 0) {
595                                            $html .= $v->[0];
596                                    } else {
597                                            $html .= join($delimiter, @{$v});
598                                    }
599                                    return $html;
600                            }
601                    }
602            }
603    
604            $args->{'search'} = tt_filter_search($args);
605    
606    =head3 load_rec
607    
608    Used mostly for onClick events like this:
609    
610      <a href="#" onClick="[% load_rec( record_uri, 'template_name.tt') %]>foo</a>
611    
612    It will automatically do sanity checking and create correct JavaScript code.
613    
614    =cut
615    
616            $args->{'load_rec'} = sub {
617                    my @errors;
618    
619                    my $record_uri = shift or push @errors, "record_uri missing";
620                    my $template = shift or push @errors, "template missing";
621    
622                    if ($record_uri !~ m#^[^/]+/[^/]+/[^/]+$#) {
623                            push @errors, "invalid format of record_uri: $record_uri";
624                    }
625    
626                    if (@errors) {
627                            return "Logger.error('errors in load_rec: " . join(", ", @errors) . "'); return false;";
628                    } else {
629                            return "load_rec('$record_uri','$template'); return false;";
630                    }
631            };
632    
633    =head3 load_template
634    
635    Used to re-submit search request and load results in different template
636    
637      <a href="#" onClick="[% load_template( 'template_name.tt' ) %]">bar</a>
638    
639    =cut
640    
641            $args->{'load_template'} = sub {
642                    my $template = shift or return "Logger.error('load_template missing template name!'); return false;";
643                    return "load_template($template); return false;";
644            };
645    
646            my $out;
647    
648            $self->{'tt'}->process(
649                    $args->{'template'},
650                    $args,
651                    \$out
652            ) || $log->error( "apply can't process template: ", $self->{'tt'}->error() );
653    
654            return $out;
655    }
656    
657    
658    =head2 __quotemeta
659    
660    Helper to quote JavaScript-friendly characters
661    
662    =cut
663    
664    sub __quotemeta {
665            local $_ = shift;
666            $_ = decode('iso-8859-2', $_);
667    
668            s<([\x{0080}-\x{fffd}]+)>{sprintf '\u%0*v4X', '\u', $1}ge if ( Encode::is_utf8($_) );
669            {
670                    use bytes;  
671                    s<((?:[^ \x21-\x7E]|(?:\\(?!u)))+)>{sprintf '\x%0*v2X', '\x', $1}ge;
672            }
673    
674            s/\\x09/\\t/g;
675            s/\\x0A/\\n/g;
676            s/\\x0D/\\r/g;
677            s/"/\\"/g;
678            s/\\x5C/\\\\/g;
679    
680            return $_;
681    }
682    
683    
684    
685  =head1 AUTHOR  =head1 AUTHOR
686    
687  Dobrica Pavlinusic C<< <dpavlin@rot13.org> >>  Dobrica Pavlinusic C<< <dpavlin@rot13.org> >>

Legend:
Removed from v.351  
changed lines
  Added in v.399

  ViewVC Help
Powered by ViewVC 1.1.26