/[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 380 by dpavlin, Sun Jan 22 00:44:37 2006 UTC revision 533 by dpavlin, Mon May 22 22:23:21 2006 UTC
# Line 7  use base qw/ Line 7  use base qw/
7          Catalyst::Model          Catalyst::Model
8  /;  /;
9  use WebPAC::Store 0.08;  use WebPAC::Store 0.08;
10  use WebPAC::Search::Estraier 0.05;  use Search::Estraier 0.04;
11  use File::Slurp;  use File::Slurp;
12  use Time::HiRes qw/time/;  use Time::HiRes qw/time/;
13  use Encode qw/encode decode from_to/;  use Encode qw/encode decode from_to/;
14  use Template;  use Template;
 use Data::Dumper;  
15    
16  =head1 NAME  =head1 NAME
17    
# Line 66  sub new { Line 65  sub new {
65    
66          $est_cfg->{encoding} = $est_cfg->{catalyst_encoding} || $c->config->{catalyst_encoding} or $c->log->fatal("can't find catalyst_encoding");          $est_cfg->{encoding} = $est_cfg->{catalyst_encoding} || $c->config->{catalyst_encoding} or $c->log->fatal("can't find catalyst_encoding");
67    
68          $log->debug("using config:" . Dumper($est_cfg) );          $log->dumper($est_cfg, 'est_cfg');
69    
70          if (! $est_cfg->{database}) {          if (! $est_cfg->{database}) {
71                  my $defaultnode = $est_cfg->{defaultnode} || $log->logdie("can't find defaultnode in estraier configuration");                  my $defaultnode = $est_cfg->{defaultnode} || $log->logdie("can't find defaultnode in estraier configuration");
# Line 74  sub new { Line 73  sub new {
73                  $est_cfg->{database} = $defaultnode;                  $est_cfg->{database} = $defaultnode;
74          }          }
75    
76          $self->{est} = new WebPAC::Search::Estraier( %{ $est_cfg } );          my $url = $est_cfg->{masterurl} . '/node/' . $est_cfg->{database};
77    
78            $log->info("opening Hyper Estraier index $url as $est_cfg->{'user'}");
79    
80            $self->{est_node} = Search::Estraier::Node->new(
81                    url => $url,
82                    user => $est_cfg->{user},
83                    passwd => $est_cfg->{passwd},
84            );
85    
86            $log->fatal("can't create Search::Estraier::Node $url") unless ($self->{est_node});
87    
88          # save config parametars in object          # save config parametars in object
89          foreach my $f (qw/db_path template_path hits_on_page webpac_encoding defaultdepth/) {          foreach my $f (qw/
90                    db_path template_path hits_on_page webpac_encoding defaultdepth
91                    masterurl defaultnode
92                    /) {
93                  $self->{$f} = $c->config->{hyperestraier}->{$f} ||                  $self->{$f} = $c->config->{hyperestraier}->{$f} ||
94                          $c->config->{webpac}->{$f};                          $c->config->{webpac}->{$f};
95                  $log->debug("self->{$f} = " . $self->{$f});                  $log->debug("self->{$f} = " . $self->{$f});
# Line 101  sub new { Line 113  sub new {
113                  "'"                  "'"
114          );          );
115    
116          $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");
117    
118          # create Template toolkit instance          # create Template toolkit instance
119          $self->{'tt'} = Template->new(          $self->{'tt'} = Template->new(
# Line 128  sub new { Line 140  sub new {
140    
141  }  }
142    
143    =head2 setup_site
144    
145     $self->setup_site('site_name');
146    
147    Change node URL and database name according to site name (if available) or fallback
148    to C<defaultnode> from configuration.
149    
150    =cut
151    
152    sub setup_site {
153            my $self = shift;
154    
155            my $site = shift || $self->{defaultnode};
156            if (! $site) {
157                    $self->{log}->warn("not changing site from " . $self->{est_node}->{url});
158                    return;
159            }
160    
161            $self->{log}->fatal("setup_site can't find site or defaultnode") unless ($site);
162    
163            my $url = $self->{masterurl} . '/node/' . $site;
164            $self->{est_node}->set_url( $url );
165            $self->{log}->debug("setup_site '$site' using $url");
166    }
167    
168  =head2 search  =head2 search
169    
# Line 135  sub new { Line 171  sub new {
171          phrase => 'query phrase',          phrase => 'query phrase',
172          add_attr => \@add_attr          add_attr => \@add_attr
173          get_attr => [ '@uri' ],          get_attr => [ '@uri' ],
174          max => 42,          hits_on_page => 42,
175          template => 'result_template.tt',          template => 'result_template.tt',
176          depth => 1,          depth => 1,
177    );    );
# Line 155  sub search { Line 191  sub search {
191    
192          my $log = $self->{log};          my $log = $self->{log};
193    
194          $log->debug("search args: " . Dumper( $args ));          $log->dumper($args, 'args');
195    
196          my $query = $args->{phrase} || $log->warn("no query phrase") && return;          my $query = $args->{phrase} || $log->warn("no query phrase") && return;
197    
         $log->debug("search model query: '$query'");  
         if ($args->{add_attr}) {  
                 $log->debug(" + add_attr: " .  
                         join("','", @{ $args->{add_attr} })  
                 );  
         }  
   
198          my $template_filename = $args->{template} || $self->{template};          my $template_filename = $args->{template} || $self->{template};
199    
200          $args->{max} ||= $self->{'hits_for_pager'};          $args->{hits_on_page} ||= $self->{'hits_for_pager'};
201          if (! $args->{max}) {          if (! $args->{hits_on_page}) {
202                  $args->{max} = 100;                  $args->{hits_on_page} = 100;
203                  $log->warn("max not set when calling model. Using default of $args->{max}");                  $log->warn("hints_on_page not set when calling model. Using default of $args->{hits_on_page}");
204          }          }
205    
206          my $times;      # store some times for benchmarking          my $times;      # store some times for benchmarking
# Line 184  sub search { Line 213  sub search {
213                  $args->{depth} = $default;                  $args->{depth} = $default;
214                  $log->warn("using default search depth $default");                  $log->warn("using default search depth $default");
215          }          }
216            $args->{depth} ||= 0;
217    
218          my @results = $self->{est}->search( %{ $args } );          $log->debug("searching " . $self->{est_node}->{url} . " hits on page: $args->{hits_on_page} depth: $args->{depth} phrase: " . ($query || '[none]') );
219    
220          $times->{est} += time() - $t;          #
221            # construct condition for Hyper Estraier
222            #
223            my $cond = Search::Estraier::Condition->new();
224            if ( ref($args->{add_attr}) eq 'ARRAY' ) {
225                    $log->debug("adding search attributes: " . join(", ", @{ $args->{add_attr} }) );
226                    map {
227                            $cond->add_attr( $_ );
228                            $log->debug(" + $_");
229                    } @{ $args->{add_attr} };
230            };
231    
232            $cond->set_phrase( $query ) if ($query);
233            $cond->set_options( $args->{options} ) if ($args->{options});
234            $cond->set_order( $args->{order} ) if ($args->{order});
235    
236            my $hits_on_page = $args->{hits_on_page} || 7;
237            my $page = $args->{page} || 1;
238            if ($page < 1) {
239                    $log->warn("page number $page < 1");
240                    $page = 1;
241            }
242    
243            $cond->set_max( my $max = $page * $hits_on_page );
244            $cond->set_skip( my $skip = ( $page - 1 ) * $hits_on_page );
245    
246            $log->debug("search max: $max, skip: $skip");
247    
248            my $result = $self->{est_node}->search($cond, $args->{depth});
249            if (! $result) {
250                    $self->{log}->fatal("search didn't return result");
251                    return;
252            }
253            my $hits = $result->doc_num;
254    
255          my $hits = $#results + 1;          $times->{est} += time() - $t;
256    
257          $log->debug( sprintf("search took %.6fs and returned $hits hits.", $times->{est}) );          $log->debug( sprintf("search took %.6fs and returned $hits hits.", $times->{est}) );
258    
259          # just return results?          $self->{hints} = $result->{hints};
260          return @results unless ($args->{'template'});          #$log->dumper($self->{hints}, 'original hints' );
261    
262          #          #
263          # construct HTML results          # fetch results
264          #          #
265    
266          my @html_results;          my @results;
267    
268          for my $i ( 0 .. $#results ) {          
269    
270                  my ($database, $prefix, $id);          for my $i ( 0 .. ( $hits < $max ? ($hits-1) : ($max-1) ) ) {
                 if ( $results[$i]->{'@uri'} =~ m!/([^/]+)/([^/]+)/(\d+)$!) {  
                         ($database, $prefix,$id) = ($1,$2,$3);  
                 } else {  
                         $log->warn("can't decode database/prefix/id from " .  $results[$i]->{'@uri'});  
                         next;  
                 }  
   
                 #$log->debug("load_ds( id => $id, prefix => '$prefix' )");  
271    
272                  $t = time();                  $t = time();
273    
274                  my $ds = $self->{db}->load_ds( database => $database, prefix => $prefix, id => $id );                  #$log->debug("get_doc($i)");
275                  if (! $ds) {                  my $doc = $result->get_doc( $i );
276                          $log->error("can't load_ds( ${database}/${prefix}/${id} )");                  if (! $doc) {
277                            $log->warn("can't find result $i");
278                          next;                          next;
279                  }                  }
280    
281                  $times->{db} += time() - $t;                  my $hash;
282    
283                  #$log->debug( "ds = " . Dumper( \@html_results ) );                  foreach my $attr (@{ $args->{get_attr} }) {
284                            my $val = $doc->attr( $attr );
285                            #$log->debug("attr $attr = ", $val || 'undef');
286                            $hash->{$attr} = $val if (defined($val));
287                    }
288    
289                  $t = time();                  $times->{hash} += time() - $t;
290    
291                  my $html = $self->apply(                  next unless ($hash);
                         template => $template_filename,  
                         data => $ds,  
                         record_uri => "${database}/${prefix}/${id}",  
                         config => $self->{databases}->{$database},  
                 );  
292    
293                  $times->{out} += time() - $t;                  if (! $args->{'template'}) {
294                            push @results, $hash;
295                    } else {
296                            my ($database, $prefix, $id);
297    
298                  $t = time();                          if ( $hash->{'@uri'} =~ m!/([^/]+)/([^/]+)/(\d+)$!) {
299                                    ($database, $prefix,$id) = ($1,$2,$3);
300                            } else {
301                                    $log->warn("can't decode database/prefix/id from " .  $hash->{'@uri'});
302                                    next;
303                            }
304    
305                  $html = decode($self->{webpac_encoding}, $html);                          #$log->debug("load_ds( id => $id, prefix => '$prefix' )");
306    
307                  push @html_results, $html;                          $t = time();
308    
309          }                          my $ds = $self->{db}->load_ds( database => $database, prefix => $prefix, id => $id );
310                            if (! $ds) {
311                                    $log->error("can't load_ds( ${database}/${prefix}/${id} )");
312                                    next;
313                            }
314    
315                            $times->{db} += time() - $t;
316    
317                            $t = time();
318    
319                            my $html = $self->apply(
320                                    template => $template_filename,
321                                    data => $ds,
322                                    record_uri => "${database}/${prefix}/${id}",
323                                    config => $self->{databases}->{$database},
324                            );
325    
326          #$log->debug( '@html_results = ' . Dumper( \@html_results ) );                          $times->{apply} += time() - $t;
327    
328                            $t = time();
329    
330                            $html = decode($self->{webpac_encoding}, $html);
331    
332                            $times->{decode} += time() - $t;
333    
334                            push @results, $html;
335                    }
336    
337            }
338    
339          $log->debug( sprintf(          $log->debug( sprintf(
340                  "duration breakdown: store %.6fs, apply %.6fs, total: %.6fs",                  "duration breakdown: estraier %.6fs, hash %.6fs, store %.6fs, apply %.6fs, decode %.06f, total: %.6fs",
341                  $times->{db}, $times->{out}, time() - $search_start_t,                  $times->{est}, $times->{hash}, $times->{db}, $times->{apply}, $times->{decode}, time() - $search_start_t,
342          ) );          ) );
343    
344          return \@html_results;          return \@results;
345    }
346    
347    =head2 hints
348    
349      my $hints = $m->hints;
350    
351    Return various useful hints about result
352    
353    =cut
354    
355    sub hints {
356            my $self = shift;
357    
358            unless ($self->{hints}) {
359                    $self->{log}->fatal("no hints found!");
360                    return;
361            }
362    
363            my $hints;
364    
365            while (my ($key,$val) = each %{ $self->{hints} }) {
366    
367                    #$self->{log}->debug("current hint $key = $val");
368    
369                    if ($key =~ m/^(?:HITS*|TIME|DOCNUM|WORDNUM)$/) {
370                            $hints->{ lc($key) } = $val;
371                    } elsif ($key =~ m/^HINT#/) {
372                            my ($word,$count) = split(/\t/,$val,2);
373                            $hints->{words}->{$word} = $count;
374                    } elsif ($key =~ m/^LINK#/) {
375                            my ($url,undef,undef,undef,undef,undef,$results) = split(/\t/,$val,7);
376                            if ($url =~ m#/node/(.+)$#) {
377                                    $hints->{node}->{$1} = $results;
378                            } else {
379                                    $self->{log}->debug("url $url doesn't have /node/ in it!");
380                            }
381                    } else {
382                            $self->{log}->debug("unknown hint $key = $val");
383                    }
384    
385            }
386    
387            $self->{log}->dumper($hints, 'model hints' );
388    
389            return $hints;
390  }  }
391    
392    
393  =head2 record  =head2 record
394    
395    my $html = $m->record(    my $html = $m->record(
# Line 272  sub record { Line 407  sub record {
407    
408          my $args = {@_};          my $args = {@_};
409          my $log = $self->{log};          my $log = $self->{log};
410          $log->debug("record args: " . Dumper( $args ));          $log->dumper( $args, 'args' );
411    
412          foreach my $f (qw/record_uri template/) {          foreach my $f (qw/record_uri template/) {
413                  $log->fatal("need $f") unless ($args->{$f});                  $log->fatal("need $f") unless ($args->{$f});
# Line 306  sub record { Line 441  sub record {
441  }  }
442    
443    
444    =head2 list_nodes
445    
446      my @nodes = $m->list_nodes( 'site' );
447    
448    Return all databases which have records for selected site. Returned array of
449    hashes has elements C<name> and C<label>.
450    
451    This function does cacheing inside C<< $self->{nodes_in_site} >>, but you
452    probably didn't want to know that.
453    
454    =cut
455    
456    sub list_nodes {
457            my $self = shift;
458    
459            my $site = shift || $self->{defaultnode};
460    
461            # cache?
462            if ($self->{nodes_in_site}->{$site} && ref($self->{nodes_in_site}->{$site}) eq 'ARRAY') {
463                    $self->{log}->debug("list_nodes for site $site and returns from cache");
464                    return @{ $self->{nodes_in_site}->{$site} };
465            };
466    
467            $self->{log}->debug("list_nodes for site $site");
468    
469            $self->setup_site( $site );
470    
471            my @nodes;
472    
473            if ($self->{est_node}->doc_num > 0) {
474                    push @nodes, {
475                            name => $self->{est_node}->name,
476                            label => $self->{est_node}->label,
477                            doc_num => $self->{est_node}->doc_num,
478                    }
479            }
480    
481            # refresh set info
482            $self->{est_node}->_set_info;
483    
484            my $links = $self->{est_node}->links || return @nodes;
485    
486            $self->{log}->dumper( $links, 'links' );
487    
488            foreach my $link (@{ $links }) {
489                    my ($url, $label, $credit) = split(/\t/, $link, 3);
490                    if ($url =~ m#/node/(.+)$#) {
491                            my $node = $1;
492                            $self->setup_site( $node );
493                            $self->{est_node}->_set_info;
494                            $label = decode('UTF-8', $label);
495                            push @nodes, {
496                                    name => $node,
497                                    label => $label,
498                                    doc_num => $self->{est_node}->doc_num,
499                            }
500                    } else {
501                            $self->{log}->warn("can't find node name in link $link");
502                    }
503            }
504    
505            $self->setup_site( $site );
506            $self->{est_node}->_set_info;
507    
508            $self->{nodes_in_site}->{$site} = \@nodes;
509    
510            return @nodes;
511    }
512    
513  =head2 save_html  =head2 save_html
514    
515    $m->save_html( '/full/path/to/file', $content );    $m->save_html( '/full/path/to/file', $content );
# Line 377  It also has follwing template toolikit f Line 581  It also has follwing template toolikit f
581    
582  =cut  =cut
583    
584    # Escape <, >, & and ", and to produce valid XML
585    my %escape = ('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;');  
586    my $escape_re  = join '|' => keys %escape;
587    
588  sub apply {  sub apply {
589          my $self = shift;          my $self = shift;
590    
# Line 385  sub apply { Line 593  sub apply {
593          my $log = $self->{log} || die "no log?";          my $log = $self->{log} || die "no log?";
594    
595          foreach my $a (qw/template data/) {          foreach my $a (qw/template data/) {
596                  $log->logconfess("need $a") unless ($args->{$a});                  $log->fatal("need $a") unless ($args->{$a});
597          }          }
598    
599  =head3 tt_filter_type  =head3 tt_filter_type
# Line 424  C<d('FieldName','delimiter')>, where C<d Line 632  C<d('FieldName','delimiter')>, where C<d
632                          if (ref($v) eq 'ARRAY') {                          if (ref($v) eq 'ARRAY') {
633                                  if ($#{$v} == 0) {                                  if ($#{$v} == 0) {
634                                          $v = $v->[0];                                          $v = $v->[0];
635                                            $v =~ s/($escape_re)/$escape{$1}/g;
636                                  } else {                                  } else {
637                                          $join = $default_delimiter->{$type} unless defined($join);                                          $join = $default_delimiter->{$type} unless defined($join);
638                                          $v = join($join, @{$v});                                          $v = join($join, map {
639                                                    s/($escape_re)/$escape{$1}/g;
640                                            } @{$v});
641                                  }                                  }
642                          } else {                          } else {
643                                  warn("TT filter $type(): field $name values aren't ARRAY, ignoring");                                  warn("TT filter $type(): field $name values aren't ARRAY, ignoring");
# Line 494  filter to return links to search, usage Line 705  filter to return links to search, usage
705    
706                                          my $s;                                          my $s;
707                                          if ($s_el > 0) {                                          if ($s_el > 0) {
708                                                  $s = $item->{'search'}->[$i] || die "can't find value $i for type search in field $search";                                                  $s = $item->{'search'}->[$i];
709                                          } else {                                          } else {
710                                                  $s = $item->{'search'}->[0];                                                  $s = $item->{'search'}->[0];
711                                          }                                          }
712    
713                                            next unless (defined($s) && $s ne '');
714    
715                                          #$s =~ s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;                                          #$s =~ s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
716                                          $s = __quotemeta( $s );                                          $s = __quotemeta( $s );
717    
718                                          my $d = $item->{'display'}->[$i] || die "can't find value $i for type display in field $display";                                          my $d = $item->{'display'}->[$i];
719    
720                                            next unless (defined($d) && $d ne '');
721    
722                                          my $template_arg = '';                                          my $template_arg = '';
723                                          $template_arg = qq{,'$template'} if ($template);                                          $template_arg = qq{,'$template'} if ($template);

Legend:
Removed from v.380  
changed lines
  Added in v.533

  ViewVC Help
Powered by ViewVC 1.1.26