/[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 378 by dpavlin, Sat Jan 21 23:27:16 2006 UTC revision 414 by dpavlin, Mon Feb 20 21:48:47 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 Data::Dumper;  use Template;
15    
16  =head1 NAME  =head1 NAME
17    
# Line 65  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 73  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 100  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          $self->{model_record} = $c->comp('Model::Record') or $log->error("can't find Model::Record");          # create Template toolkit instance
119            $self->{'tt'} = Template->new(
120                    INCLUDE_PATH => $template_path,
121                    FILTERS => {
122                            dump_html => sub {
123                                    return unless (@_);
124                                    my $out;
125                                    my $i = 1;
126                                    foreach my $v (@_) {
127                                            $out .= qq{<div id="dump_$i">} .
128                                                    Data::HTMLDumper->Dump([ $v ],[ "v$i" ]) .
129                                                    qq{</div>};
130                                            $i++;
131                                    }
132                                    $out =~ s!<table[^>/]*>!<table class="dump">!gis if ($out);
133                                    return $out;
134                            }
135                    },
136                    EVAL_PERL => 1,
137            );
138    
139          return $self;          return $self;
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    
157            $self->{log}->fatal("setup_site can't find site or defaultnode") unless ($site);
158    
159            my $url = $self->{masterurl} . '/node/' . $site;
160            $self->{est_node}->set_url( $url );
161            $self->{log}->debug("setup_site $site using $url");
162    }
163    
164  =head2 search  =head2 search
165    
# Line 135  sub search { Line 187  sub search {
187    
188          my $log = $self->{log};          my $log = $self->{log};
189    
190          $log->debug("search args: " . Dumper( $args ));          $log->dumper($args, 'args');
191    
192          my $query = $args->{phrase} || $log->warn("no query phrase") && return;          my $query = $args->{phrase} || $log->warn("no query phrase") && return;
193    
         $log->debug("search model query: '$query'");  
         if ($args->{add_attr}) {  
                 $log->debug(" + add_attr: " .  
                         join("','", @{ $args->{add_attr} })  
                 );  
         }  
   
194          my $template_filename = $args->{template} || $self->{template};          my $template_filename = $args->{template} || $self->{template};
195    
196          $args->{max} ||= $self->{'hits_for_pager'};          $args->{max} ||= $self->{'hits_for_pager'};
# Line 164  sub search { Line 209  sub search {
209                  $args->{depth} = $default;                  $args->{depth} = $default;
210                  $log->warn("using default search depth $default");                  $log->warn("using default search depth $default");
211          }          }
212            $args->{depth} ||= 0;
213    
214          my @results = $self->{est}->search( %{ $args } );          $log->debug("searching for maximum $args->{max} results using depth $args->{depth} phrase: ", $query || '[none]');
215    
216          $times->{est} += time() - $t;          #
217            # construct condition for Hyper Estraier
218            #
219            my $cond = Search::Estraier::Condition->new();
220            if ( ref($args->{add_attr}) eq 'ARRAY' ) {
221                    $log->debug("adding search attributes: " . join(", ", @{ $args->{add_attr} }) );
222                    map {
223                            $cond->add_attr( $_ );
224                            $log->debug(" + $_");
225                    } @{ $args->{add_attr} };
226            };
227    
228            $cond->set_phrase( $query ) if ($query);
229            $cond->set_options( $args->{options} ) if ($args->{options});
230            $cond->set_order( $args->{order} ) if ($args->{order});
231    
232            my $max = $args->{max} || 7;
233            my $page = $args->{page} || 1;
234            if ($page < 1) {
235                    $log->warn("page number $page < 1");
236                    $page = 1;
237            }
238    
239            $cond->set_max( $page * $max );
240    
241            my $result = $self->{est_node}->search($cond, $args->{depth});
242            if (! $result) {
243                    $self->{log}->fatal("search didn't return result");
244                    return;
245            }
246            my $hits = $result->doc_num;
247    
248          my $hits = $#results + 1;          $times->{est} += time() - $t;
249    
250          $log->debug( sprintf("search took %.6fs and returned $hits hits.", $times->{est}) );          $log->debug( sprintf("search took %.6fs and returned $hits hits.", $times->{est}) );
251    
252          # just return results?          $self->{hints} = $result->{hints};
253          return @results unless ($args->{'template'});          $log->dumper($self->{hints}, 'hints' );
254    
255          #          #
256          # construct HTML results          # fetch results
257          #          #
258    
259          my @html_results;          my @results;
260    
261          for my $i ( 0 .. $#results ) {          for my $i ( (($page - 1) * $max) .. ( $hits - 1 ) ) {
262    
263                  my ($database, $prefix, $id);                  $t = time();
264                  if ( $results[$i]->{'@uri'} =~ m!/([^/]+)/([^/]+)/(\d+)$!) {  
265                          ($database, $prefix,$id) = ($1,$2,$3);                  #$log->debug("get_doc($i)");
266                  } else {                  my $doc = $result->get_doc( $i );
267                          $log->warn("can't decode database/prefix/id from " .  $results[$i]->{'@uri'});                  if (! $doc) {
268                            $log->warn("can't find result $i");
269                          next;                          next;
270                  }                  }
271    
272                  #$log->debug("load_ds( id => $id, prefix => '$prefix' )");                  my $hash;
   
                 $t = time();  
273    
274                  my $ds = $self->{db}->load_ds( database => $database, prefix => $prefix, id => $id );                  foreach my $attr (@{ $args->{get_attr} }) {
275                  if (! $ds) {                          my $val = $doc->attr( $attr );
276                          $log->error("can't load_ds( ${database}/${prefix}/${id} )");                          #$log->debug("attr $attr = ", $val || 'undef');
277                          next;                          $hash->{$attr} = $val if (defined($val));
278                  }                  }
279    
280                  $times->{db} += time() - $t;                  $times->{hash} += time() - $t;
281    
282                  #$log->debug( "ds = " . Dumper( \@html_results ) );                  next unless ($hash);
283    
284                  $t = time();                  if (! $args->{'template'}) {
285                            push @results, $hash;
286                    } else {
287                            my ($database, $prefix, $id);
288    
289                            if ( $hash->{'@uri'} =~ m!/([^/]+)/([^/]+)/(\d+)$!) {
290                                    ($database, $prefix,$id) = ($1,$2,$3);
291                            } else {
292                                    $log->warn("can't decode database/prefix/id from " .  $hash->{'@uri'});
293                                    next;
294                            }
295    
296                  my $html = '[no output]';                          #$log->debug("load_ds( id => $id, prefix => '$prefix' )");
297    
298                  if ($self->{model_record}) {                          $t = time();
299                          $html = $self->{model_record}->apply(  
300                            my $ds = $self->{db}->load_ds( database => $database, prefix => $prefix, id => $id );
301                            if (! $ds) {
302                                    $log->error("can't load_ds( ${database}/${prefix}/${id} )");
303                                    next;
304                            }
305    
306                            $times->{db} += time() - $t;
307    
308                            $t = time();
309    
310                            my $html = $self->apply(
311                                  template => $template_filename,                                  template => $template_filename,
312                                  data => $ds,                                  data => $ds,
313                                  record_uri => "${database}/${prefix}/${id}",                                  record_uri => "${database}/${prefix}/${id}",
314                                  config => $self->{databases}->{$database},                                  config => $self->{databases}->{$database},
315                          );                          );
                 } else {  
                         $log->warn("skipped apply");  
                 }  
316    
317                  $times->{out} += time() - $t;                          $times->{apply} += time() - $t;
318    
319                  $t = time();                          $t = time();
320    
321                  $html = decode($self->{webpac_encoding}, $html);                          $html = decode($self->{webpac_encoding}, $html);
322    
323                  push @html_results, $html;                          $times->{decode} += time() - $t;
324    
325          }                          push @results, $html;
326                    }
327    
328          #$log->debug( '@html_results = ' . Dumper( \@html_results ) );          }
329    
330          $log->debug( sprintf(          $log->debug( sprintf(
331                  "duration breakdown: store %.6fs, apply %.6fs, total: %.6fs",                  "duration breakdown: estraier %.6fs, hash %.6fs, store %.6fs, apply %.6fs, decode %.06f, total: %.6fs",
332                  $times->{db}, $times->{out}, time() - $search_start_t,                  $times->{est}, $times->{hash}, $times->{db}, $times->{apply}, $times->{decode}, time() - $search_start_t,
333          ) );          ) );
334    
335          return \@html_results;          return \@results;
336    }
337    
338    =head2 hints
339    
340      my $hints = $m->hints;
341    
342    Return various useful hints about result
343    
344    =cut
345    
346    sub hints {
347            my $self = shift;
348    
349            unless ($self->{hints}) {
350                    $self->{log}->fatal("no hints found!");
351                    return;
352            }
353    
354            my $hints;
355    
356            while (my ($key,$val) = each %{ $self->{hints} }) {
357    
358                    if ($key =~ m/^(?:HITS*|TIME|DOCNUM|WORDNUM)$/) {
359                            $hints->{ lc($key) } = $val;
360                    } elsif ($key =~ m/^HINT#/) {
361                            my ($word,$count) = split(/\t/,$val,2);
362                            $hints->{words}->{$word} = $count;
363                    } elsif ($key =~ m/^LINK#/) {
364                            my ($url,undef,undef,undef,undef,undef,$results) = split(/\t/,$val,7);
365                            if ($url =~ m#/node/(.+)$#) {
366                                    $hints->{node}->{$1} = $results;
367                            }
368                    }
369            }
370    
371            return $hints;
372  }  }
373    
374    
375  =head2 record  =head2 record
376    
377    my $html = $m->record(    my $html = $m->record(
# Line 258  sub record { Line 389  sub record {
389    
390          my $args = {@_};          my $args = {@_};
391          my $log = $self->{log};          my $log = $self->{log};
392          $log->debug("record args: " . Dumper( $args ));          $log->dumper( $args, 'args' );
393    
394          foreach my $f (qw/record_uri template/) {          foreach my $f (qw/record_uri template/) {
395                  $log->fatal("need $f") unless ($args->{$f});                  $log->fatal("need $f") unless ($args->{$f});
# Line 279  sub record { Line 410  sub record {
410                  return;                  return;
411          }          }
412    
413          my $html = $self->{model_record}->apply(          my $html = $self->apply(
414                  template => $args->{template},                  template => $args->{template},
415                  data => $ds,                  data => $ds,
416                  record_uri => $args->{record_uri},                  record_uri => $args->{record_uri},
# Line 292  sub record { Line 423  sub record {
423  }  }
424    
425    
426    =head2 list_nodes
427    
428      my @nodes = $m->list_nodes( 'site' );
429    
430    Return all databases which have records for selected site. Returned array of
431    hashes has elements C<name> and C<label>.
432    
433    =cut
434    
435    sub list_nodes {
436            my $self = shift;
437    
438            my $site = shift;
439    
440            $self->{log}->debug("list_nodes use site $site");
441    
442            $self->setup_site( $site );
443    
444            my @nodes;
445    
446            if ($self->{est_node}->doc_num > 0) {
447                    push @nodes, {
448                            name => $self->{est_node}->name,
449                            label => $self->{est_node}->label,
450                            doc_num => $self->{est_node}->doc_num,
451                    }
452            }
453    
454            # refresh set info
455            $self->{est_node}->_set_info;
456    
457            my $links = $self->{est_node}->links || return @nodes;
458    
459            $self->{log}->dumper( $links, 'links' );
460    
461            foreach my $link (@{ $links }) {
462                    my ($url, $label, $credit) = split(/\t/, $link, 3);
463                    if ($url =~ m#/node/(.+)$#) {
464                            my $node = $1;
465                            $self->setup_site( $node );
466                            $self->{est_node}->_set_info;
467                            push @nodes, {
468                                    name => $node,
469                                    label => $label,
470                                    doc_num => $self->{est_node}->doc_num,
471                            }
472                    } else {
473                            $self->{log}->warn("can't find node name in link $link");
474                    }
475            }
476    
477            $self->setup_site( $site );
478            $self->{est_node}->_set_info;
479    
480            $self->{log}->dumper( \@nodes, 'nodes' );
481    
482            return @nodes;
483    }
484    
485    =cut
486    
487    
488  =head2 save_html  =head2 save_html
489    
490    $m->save_html( '/full/path/to/file', $content );    $m->save_html( '/full/path/to/file', $content );
# Line 348  sub load_html { Line 541  sub load_html {
541          return decode($self->{webpac_encoding}, $content);          return decode($self->{webpac_encoding}, $content);
542  }  }
543    
544    
545    =head2 apply
546    
547    Create output from in-memory data structure using Template Toolkit template.
548    
549     my $text = $tt->apply(
550            template => 'text.tt',
551            data => $ds,
552            record_uri => 'database/prefix/mfn',
553     );
554    
555    It also has follwing template toolikit filter routies defined:
556    
557    =cut
558    
559    # Escape <, >, & and ", and to produce valid XML
560    my %escape = ('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;');  
561    my $escape_re  = join '|' => keys %escape;
562    
563    sub apply {
564            my $self = shift;
565    
566            my $args = {@_};
567    
568            my $log = $self->{log} || die "no log?";
569    
570            foreach my $a (qw/template data/) {
571                    $log->fatal("need $a") unless ($args->{$a});
572            }
573    
574    =head3 tt_filter_type
575    
576    filter to return values of specified from $ds, usage from TT template is in form
577    C<d('FieldName','delimiter')>, where C<delimiter> is optional, like this:
578    
579      [% d('Title') %]
580      [% d('Author',', ' %]
581    
582    =cut
583    
584            sub tt_filter_type {
585                    my ($data,$type) = @_;
586                    
587                    die "no data?" unless ($data);
588                    $type ||= 'display';
589    
590                    my $default_delimiter = {
591                            'display' => '&#182;<br/>',
592                            'index' => '\n',
593                    };
594    
595                    return sub {
596    
597                            my ($name,$join) = @_;
598    
599                            die "no data hash" unless ($data->{'data'} && ref($data->{'data'}) eq 'HASH');
600                            # Hm? Should we die here?
601                            return unless ($name);
602    
603                            my $item = $data->{'data'}->{$name} || return;
604    
605                            my $v = $item->{$type} || return;
606    
607                            if (ref($v) eq 'ARRAY') {
608                                    if ($#{$v} == 0) {
609                                            $v = $v->[0];
610                                            $v =~ s/($escape_re)/$escape{$1}/g;
611                                    } else {
612                                            $join = $default_delimiter->{$type} unless defined($join);
613                                            $v = join($join, map {
614                                                    s/($escape_re)/$escape{$1}/g;
615                                            } @{$v});
616                                    }
617                            } else {
618                                    warn("TT filter $type(): field $name values aren't ARRAY, ignoring");
619                            }
620    
621                            return $v;
622                    }
623            }
624    
625            $args->{'d'} = tt_filter_type($args, 'display');
626            $args->{'display'} = tt_filter_type($args, 'display');
627    
628    =head3 tt_filter_search
629    
630    filter to return links to search, usage in TT:
631    
632      [% search('FieldToDisplay','FieldToSearch','optional delimiter', 'optional_template.tt') %]
633    
634    =cut
635    
636            sub tt_filter_search {
637    
638                    my ($data) = @_;
639    
640                    die "no data?" unless ($data);
641                    
642                    return sub {
643    
644                            my ($display,$search,$delimiter,$template) = @_;
645                            
646                            # default delimiter
647                            $delimiter ||= '&#182;<br/>',
648    
649                            die "no data hash" unless ($data->{'data'} && ref($data->{'data'}) eq 'HASH');
650                            # Hm? Should we die here?
651                            return unless ($display);
652    
653                            my $item = $data->{'data'}->{$display} || return;
654    
655                            return unless($item->{'display'});
656                            if (! $item->{'search'}) {
657                                    warn "error in TT template: field $display didn't insert anything into search, use d('$display') and not search('$display'...)";
658                                    return;
659                            }
660    
661                            my @warn;
662                            foreach my $type (qw/display search/) {
663                                    push @warn, "field $display type $type values aren't ARRAY" unless (ref($item->{$type}) eq 'ARRAY');
664                            }
665    
666                            if (@warn) {
667                                    warn("TT filter search(): " . join(",", @warn) . ", skipping");
668                                    return;
669                            }
670                            my @html;
671    
672                            my $d_el = $#{ $item->{'display'} };
673                            my $s_el = $#{ $item->{'search'} };
674    
675                            # easy, both fields have same number of elements or there is just
676                            # one search and multiple display
677                            if ( $d_el == $s_el || $s_el == 0 ) {
678    
679                                    foreach my $i ( 0 .. $d_el ) {
680    
681                                            my $s;
682                                            if ($s_el > 0) {
683                                                    $s = $item->{'search'}->[$i] or warn "can't find value $i for type search in field $search";
684                                            } else {
685                                                    $s = $item->{'search'}->[0];
686                                            }
687                                            #$s =~ s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
688                                            $s = __quotemeta( $s );
689    
690                                            my $d = $item->{'display'}->[$i] or warn "can't find value $i for type display in field $display";
691    
692                                            my $template_arg = '';
693                                            $template_arg = qq{,'$template'} if ($template);
694    
695                                            push @html, qq{<a href="#" onclick="return search_via_link('$search','$s'${template_arg})">$d</a>};
696                                    }
697    
698                                    return join($delimiter, @html);
699                            } else {
700                                    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>};
701                                    my $v = $item->{'display'};
702    
703                                    if ($#{$v} == 0) {
704                                            $html .= $v->[0];
705                                    } else {
706                                            $html .= join($delimiter, @{$v});
707                                    }
708                                    return $html;
709                            }
710                    }
711            }
712    
713            $args->{'search'} = tt_filter_search($args);
714    
715    =head3 load_rec
716    
717    Used mostly for onClick events like this:
718    
719      <a href="#" onClick="[% load_rec( record_uri, 'template_name.tt') %]>foo</a>
720    
721    It will automatically do sanity checking and create correct JavaScript code.
722    
723    =cut
724    
725            $args->{'load_rec'} = sub {
726                    my @errors;
727    
728                    my $record_uri = shift or push @errors, "record_uri missing";
729                    my $template = shift or push @errors, "template missing";
730    
731                    if ($record_uri !~ m#^[^/]+/[^/]+/[^/]+$#) {
732                            push @errors, "invalid format of record_uri: $record_uri";
733                    }
734    
735                    if (@errors) {
736                            return "Logger.error('errors in load_rec: " . join(", ", @errors) . "'); return false;";
737                    } else {
738                            return "load_rec('$record_uri','$template'); return false;";
739                    }
740            };
741    
742    =head3 load_template
743    
744    Used to re-submit search request and load results in different template
745    
746      <a href="#" onClick="[% load_template( 'template_name.tt' ) %]">bar</a>
747    
748    =cut
749    
750            $args->{'load_template'} = sub {
751                    my $template = shift or return "Logger.error('load_template missing template name!'); return false;";
752                    return "load_template($template); return false;";
753            };
754    
755            my $out;
756    
757            $self->{'tt'}->process(
758                    $args->{'template'},
759                    $args,
760                    \$out
761            ) || $log->error( "apply can't process template: ", $self->{'tt'}->error() );
762    
763            return $out;
764    }
765    
766    
767    =head2 __quotemeta
768    
769    Helper to quote JavaScript-friendly characters
770    
771    =cut
772    
773    sub __quotemeta {
774            local $_ = shift;
775            $_ = decode('iso-8859-2', $_);
776    
777            s<([\x{0080}-\x{fffd}]+)>{sprintf '\u%0*v4X', '\u', $1}ge if ( Encode::is_utf8($_) );
778            {
779                    use bytes;  
780                    s<((?:[^ \x21-\x7E]|(?:\\(?!u)))+)>{sprintf '\x%0*v2X', '\x', $1}ge;
781            }
782    
783            s/\\x09/\\t/g;
784            s/\\x0A/\\n/g;
785            s/\\x0D/\\r/g;
786            s/"/\\"/g;
787            s/\\x5C/\\\\/g;
788    
789            return $_;
790    }
791    
792    
793    
794  =head1 AUTHOR  =head1 AUTHOR
795    
796  Dobrica Pavlinusic C<< <dpavlin@rot13.org> >>  Dobrica Pavlinusic C<< <dpavlin@rot13.org> >>

Legend:
Removed from v.378  
changed lines
  Added in v.414

  ViewVC Help
Powered by ViewVC 1.1.26