/[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 92 by dpavlin, Tue Nov 22 12:57:09 2005 UTC revision 379 by dpavlin, Sun Jan 22 00:44:32 2006 UTC
# Line 3  package Webpacus::Model::WebPAC; Line 3  package Webpacus::Model::WebPAC;
3  use strict;  use strict;
4  use warnings;  use warnings;
5  use lib '/data/webpac2/lib';  use lib '/data/webpac2/lib';
6  use base qw/Catalyst::Model/;  use base qw/
7  use WebPAC::Search::Estraier;          Catalyst::Model
8    /;
9    use WebPAC::Store 0.08;
10    use WebPAC::Search::Estraier 0.05;
11    use File::Slurp;
12    use Time::HiRes qw/time/;
13    use Encode qw/encode decode from_to/;
14    use Template;
15  use Data::Dumper;  use Data::Dumper;
16    
17  =head1 NAME  =head1 NAME
# Line 28  Configuration for hyperestraier in C<con Line 35  Configuration for hyperestraier in C<con
35    
36   # configuration for hyper estraier full text search engine   # configuration for hyper estraier full text search engine
37   hyperestraier:   hyperestraier:
38      url: 'http://localhost:1978/node/webpac2'    masterurl: 'http://localhost:1978/node/webpac2'
39      user: 'admin'    defaultnode: 'webpac2'
40      passwd: 'admin'    defaultdepth: 1
41      user: 'admin'
42      passwd: 'admin'
43      hits_on_page: 100
44      hits_for_pager: 1000
45    
46     webpac:
47      db_path: '/data/webpac2/db'
48      template_path: '/data/webpac2/conf/output/tt'
49      template: 'html_ffzg_results_short.tt'
50      # encoding comming from webpac
51      webpac_encoding: 'iso-8859-2'
52    
53  =cut  =cut
54    
# Line 41  sub new { Line 59  sub new {
59          $self->config($config);          $self->config($config);
60    
61          my $log = $c->log;          my $log = $c->log;
62            $self->{log} = $log;
63    
64  #       if (! $c->stash->{est}) {          my $est_cfg = $c->config->{hyperestraier};
65            $est_cfg->{'log'} = $log;
66    
67                  my $est_cfg = $c->config->{hyperestraier};          $est_cfg->{encoding} = $est_cfg->{catalyst_encoding} || $c->config->{catalyst_encoding} or $c->log->fatal("can't find catalyst_encoding");
                 $est_cfg->{'log'} = $log;  
68    
69                  $log->debug("using config:" . Dumper($est_cfg) );          $log->debug("using config:" . Dumper($est_cfg) );
70    
71  #               $c->stash->{est} = new WebPAC::Search::Estraier( %{ $est_cfg } );          if (! $est_cfg->{database}) {
72  #       }                  my $defaultnode = $est_cfg->{defaultnode} || $log->logdie("can't find defaultnode in estraier configuration");
73                    $log->info("using default node $defaultnode");
74                    $est_cfg->{database} = $defaultnode;
75            }
76    
77            $self->{est} = new WebPAC::Search::Estraier( %{ $est_cfg } );
78    
79            # save config parametars in object
80            foreach my $f (qw/db_path template_path hits_on_page webpac_encoding defaultdepth/) {
81                    $self->{$f} = $c->config->{hyperestraier}->{$f} ||
82                            $c->config->{webpac}->{$f};
83                    $log->debug("self->{$f} = " . $self->{$f});
84            }
85            my $db_path = $self->{db_path};
86            my $template_path = $self->{template_path};
87    
88            $log->debug("using db path '$db_path', template path '$template_path'");
89    
90            $self->{db} = new WebPAC::Store(
91                    path => $db_path,
92                    read_only => 1,
93                    database => $est_cfg->{database},
94            );
95    
96            # default template from config.yaml
97            $self->{template} ||= $c->config->{webpac}->{template};
98    
99            $log->debug("converting encoding from webpac_encoding '" .
100                    $c->config->{webpac}->{webpac_encoding} .
101                    "'"
102            );
103    
104            $self->{databases} = $c->config->{databases} || $log->error("can't find databases in config");
105    
106            # create Template toolkit instance
107            $self->{'tt'} = Template->new(
108                    INCLUDE_PATH => $template_path,
109                    FILTERS => {
110                            dump_html => sub {
111                                    return unless (@_);
112                                    my $out;
113                                    my $i = 1;
114                                    foreach my $v (@_) {
115                                            $out .= qq{<div id="dump_$i">} .
116                                                    Data::HTMLDumper->Dump([ $v ],[ "v$i" ]) .
117                                                    qq{</div>};
118                                            $i++;
119                                    }
120                                    $out =~ s!<table[^>/]*>!<table class="dump">!gis if ($out);
121                                    return $out;
122                            }
123                    },
124                    EVAL_PERL => 1,
125            );
126    
127  #       $log->debug("param: " . Dumper($c->req->params));          return $self;
128    
129  #       $c->stash->{est}->search(  }
130  #               query => $c->req->params->{Title},  
131  #               max => 100,  
132  #       );  =head2 search
133    
134      my $m->search(
135            phrase => 'query phrase',
136            add_attr => \@add_attr
137            get_attr => [ '@uri' ],
138            max => 42,
139            template => 'result_template.tt',
140            depth => 1,
141      );
142    
143    All fields are standard C<WebPAC::Search::Estraier> parametars except
144    C<template> which will (if specified) return results in HTML using
145    selected template.
146    
147    =cut
148    
149    sub search {
150            my $self = shift;
151    
152            my $search_start_t = time();
153    
154            my $args = {@_};
155    
156            my $log = $self->{log};
157    
158            $log->debug("search args: " . Dumper( $args ));
159    
160            my $query = $args->{phrase} || $log->warn("no query phrase") && return;
161    
162            $log->debug("search model query: '$query'");
163            if ($args->{add_attr}) {
164                    $log->debug(" + add_attr: " .
165                            join("','", @{ $args->{add_attr} })
166                    );
167            }
168    
169            my $template_filename = $args->{template} || $self->{template};
170    
171            $args->{max} ||= $self->{'hits_for_pager'};
172            if (! $args->{max}) {
173                    $args->{max} = 100;
174                    $log->warn("max not set when calling model. Using default of $args->{max}");
175            }
176    
177            my $times;      # store some times for benchmarking
178    
179            my $t = time();
180    
181            # transfer depth of search
182            if (! $args->{depth}) {
183                    my $default = $self->{defaultdepth} || $log->logdie("can't find defaultdepth in estraier configuration");
184                    $args->{depth} = $default;
185                    $log->warn("using default search depth $default");
186            }
187    
188            my @results = $self->{est}->search( %{ $args } );
189    
190            $times->{est} += time() - $t;
191    
192            my $hits = $#results + 1;
193    
194            $log->debug( sprintf("search took %.6fs and returned $hits hits.", $times->{est}) );
195    
196            # just return results?
197            return @results unless ($args->{'template'});
198    
199            #
200            # construct HTML results
201            #
202    
203            my @html_results;
204    
205            for my $i ( 0 .. $#results ) {
206    
207                    my ($database, $prefix, $id);
208                    if ( $results[$i]->{'@uri'} =~ m!/([^/]+)/([^/]+)/(\d+)$!) {
209                            ($database, $prefix,$id) = ($1,$2,$3);
210                    } else {
211                            $log->warn("can't decode database/prefix/id from " .  $results[$i]->{'@uri'});
212                            next;
213                    }
214    
215                    #$log->debug("load_ds( id => $id, prefix => '$prefix' )");
216    
217                    $t = time();
218    
219                    my $ds = $self->{db}->load_ds( database => $database, prefix => $prefix, id => $id );
220                    if (! $ds) {
221                            $log->error("can't load_ds( ${database}/${prefix}/${id} )");
222                            next;
223                    }
224    
225                    $times->{db} += time() - $t;
226    
227                    #$log->debug( "ds = " . Dumper( \@html_results ) );
228    
229                    $t = time();
230    
231                    my $html = $self->apply(
232                            template => $template_filename,
233                            data => $ds,
234                            record_uri => "${database}/${prefix}/${id}",
235                            config => $self->{databases}->{$database},
236                    );
237    
238                    $times->{out} += time() - $t;
239    
240                    $t = time();
241    
242                    $html = decode($self->{webpac_encoding}, $html);
243    
244                    push @html_results, $html;
245    
246            }
247    
248            #$log->debug( '@html_results = ' . Dumper( \@html_results ) );
249    
250            $log->debug( sprintf(
251                    "duration breakdown: store %.6fs, apply %.6fs, total: %.6fs",
252                    $times->{db}, $times->{out}, time() - $search_start_t,
253            ) );
254    
255            return \@html_results;
256    }
257    
258    =head2 record
259    
260      my $html = $m->record(
261            mfn => 42,
262            template => 'foo.tt',
263      );
264    
265    This will load one record, convert it to html using C<template> and return
266    it.
267    
268    =cut
269    
270    sub record {
271            my $self = shift;
272    
273            my $args = {@_};
274            my $log = $self->{log};
275            $log->debug("record args: " . Dumper( $args ));
276    
277            foreach my $f (qw/record_uri template/) {
278                    $log->fatal("need $f") unless ($args->{$f});
279            }
280    
281            my ($database, $prefix, $id);
282    
283            if ($args->{record_uri} =~ m#^([^/]+)/([^/]+)/([^/]+)$#) {
284                    ($database, $prefix, $id) = ($1,$2,$3);
285            } else {
286                    $log->error("can't parse $args->{record_uri} into prefix, database and uri");
287                    return;
288            }
289    
290            my $ds = $self->{db}->load_ds( id => $id, prefix => $prefix, database => $database );
291            if (! $ds) {
292                    $log->error("can't load_ds( $database/$prefix/$id )");
293                    return;
294            }
295    
296            my $html = $self->apply(
297                    template => $args->{template},
298                    data => $ds,
299                    record_uri => $args->{record_uri},
300                    config => $self->{databases}->{$database},
301            );
302    
303            $html = decode($self->{webpac_encoding}, $html);
304    
305            return $html;
306    }
307    
308    
309    =head2 save_html
310    
311      $m->save_html( '/full/path/to/file', $content );
312    
313    It will use C<Encode> to convert content encoding back to
314    Webpac codepage, recode JavaScript Unicode entities (%u1234),
315    strip extra newlines at beginning and end, and save to
316    C</full/path/to/file.new> and if that succeeds, just rename
317    it over original file which should be atomic on filesystem level.
318    
319    =cut
320    
321    sub save_html {
322            my ($self, $path, $content) = @_;
323    
324            # FIXME Should this be UTF-8 or someting?
325            my $js_encoding = $self->{webpac_encoding};
326            $js_encoding = 'UTF-16';
327    
328            sub _conv_js {
329                    return '0x' . $_[1];
330                    return encode($_[0], chr(hex($_[1])));
331            }
332            #$content =~ s/%u([a-fA-F0-9]{4})/_conv_js($js_encoding,$1)/gex;
333            $content =~ s/^[\n\r]+//s;
334            $content =~ s/[\n\r]+$/\n/s;
335            $content =~ s/\n\r/\n/gs;
336    
337            my $disk_encoding = $self->{webpac_encoding} || 'utf-8';
338            $self->{log}->debug("convert encoding to $disk_encoding");
339            from_to($content, 'utf-8', $disk_encoding) || $self->{log}->warn("encoding from utf-8 to $disk_encoding failed for: $content");
340    
341            write_file($path . '.new', {binmode => ':raw' }, $content) || die "can't save ${path}.new $!";
342            rename $path . '.new', $path || die "can't rename to $path: $!";
343    }
344    
345    =head2 load_html
346    
347      my $html = $m->load_html('/full/path/to/file');
348    
349    This will convert file from Webpac encoding to Catalyst and
350    convert that data to escaped HTML (for sending into
351    C<< <textarea/> >> tags in html.
352    
353    =cut
354    
355    sub load_html {
356            my ($self, $path) = @_;
357    
358            die "no path?" unless ($path);
359    
360            my $content = read_file($path, {binmode => ':raw' }) || die "can't read $path: $!";
361    
362            return decode($self->{webpac_encoding}, $content);
363    }
364    
         return $self;  
365    
366    =head2 apply
367    
368    Create output from in-memory data structure using Template Toolkit template.
369    
370     my $text = $tt->apply(
371            template => 'text.tt',
372            data => $ds,
373            record_uri => 'database/prefix/mfn',
374     );
375    
376    It also has follwing template toolikit filter routies defined:
377    
378    =cut
379    
380    sub apply {
381            my $self = shift;
382    
383            my $args = {@_};
384    
385            my $log = $self->{log} || die "no log?";
386    
387            foreach my $a (qw/template data/) {
388                    $log->logconfess("need $a") unless ($args->{$a});
389            }
390    
391    =head3 tt_filter_type
392    
393    filter to return values of specified from $ds, usage from TT template is in form
394    C<d('FieldName','delimiter')>, where C<delimiter> is optional, like this:
395    
396      [% d('Title') %]
397      [% d('Author',', ' %]
398    
399    =cut
400    
401            sub tt_filter_type {
402                    my ($data,$type) = @_;
403                    
404                    die "no data?" unless ($data);
405                    $type ||= 'display';
406    
407                    my $default_delimiter = {
408                            'display' => '&#182;<br/>',
409                            'index' => '\n',
410                    };
411    
412                    return sub {
413    
414                            my ($name,$join) = @_;
415    
416                            die "no data hash" unless ($data->{'data'} && ref($data->{'data'}) eq 'HASH');
417                            # Hm? Should we die here?
418                            return unless ($name);
419    
420                            my $item = $data->{'data'}->{$name} || return;
421    
422                            my $v = $item->{$type} || return;
423    
424                            if (ref($v) eq 'ARRAY') {
425                                    if ($#{$v} == 0) {
426                                            $v = $v->[0];
427                                    } else {
428                                            $join = $default_delimiter->{$type} unless defined($join);
429                                            $v = join($join, @{$v});
430                                    }
431                            } else {
432                                    warn("TT filter $type(): field $name values aren't ARRAY, ignoring");
433                            }
434    
435                            return $v;
436                    }
437            }
438    
439            $args->{'d'} = tt_filter_type($args, 'display');
440            $args->{'display'} = tt_filter_type($args, 'display');
441    
442    =head3 tt_filter_search
443    
444    filter to return links to search, usage in TT:
445    
446      [% search('FieldToDisplay','FieldToSearch','optional delimiter', 'optional_template.tt') %]
447    
448    =cut
449    
450            sub tt_filter_search {
451    
452                    my ($data) = @_;
453    
454                    die "no data?" unless ($data);
455                    
456                    return sub {
457    
458                            my ($display,$search,$delimiter,$template) = @_;
459                            
460                            # default delimiter
461                            $delimiter ||= '&#182;<br/>',
462    
463                            die "no data hash" unless ($data->{'data'} && ref($data->{'data'}) eq 'HASH');
464                            # Hm? Should we die here?
465                            return unless ($display);
466    
467                            my $item = $data->{'data'}->{$display} || return;
468    
469                            return unless($item->{'display'});
470                            if (! $item->{'search'}) {
471                                    warn "error in TT template: field $display didn't insert anything into search, use d('$display') and not search('$display'...)";
472                                    return;
473                            }
474    
475                            my @warn;
476                            foreach my $type (qw/display search/) {
477                                    push @warn, "field $display type $type values aren't ARRAY" unless (ref($item->{$type}) eq 'ARRAY');
478                            }
479    
480                            if (@warn) {
481                                    warn("TT filter search(): " . join(",", @warn) . ", skipping");
482                                    return;
483                            }
484                            my @html;
485    
486                            my $d_el = $#{ $item->{'display'} };
487                            my $s_el = $#{ $item->{'search'} };
488    
489                            # easy, both fields have same number of elements or there is just
490                            # one search and multiple display
491                            if ( $d_el == $s_el || $s_el == 0 ) {
492    
493                                    foreach my $i ( 0 .. $d_el ) {
494    
495                                            my $s;
496                                            if ($s_el > 0) {
497                                                    $s = $item->{'search'}->[$i] || die "can't find value $i for type search in field $search";
498                                            } else {
499                                                    $s = $item->{'search'}->[0];
500                                            }
501                                            #$s =~ s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
502                                            $s = __quotemeta( $s );
503    
504                                            my $d = $item->{'display'}->[$i] || die "can't find value $i for type display in field $display";
505    
506                                            my $template_arg = '';
507                                            $template_arg = qq{,'$template'} if ($template);
508    
509                                            push @html, qq{<a href="#" onclick="return search_via_link('$search','$s'${template_arg})">$d</a>};
510                                    }
511    
512                                    return join($delimiter, @html);
513                            } else {
514                                    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>};
515                                    my $v = $item->{'display'};
516    
517                                    if ($#{$v} == 0) {
518                                            $html .= $v->[0];
519                                    } else {
520                                            $html .= join($delimiter, @{$v});
521                                    }
522                                    return $html;
523                            }
524                    }
525            }
526    
527            $args->{'search'} = tt_filter_search($args);
528    
529    =head3 load_rec
530    
531    Used mostly for onClick events like this:
532    
533      <a href="#" onClick="[% load_rec( record_uri, 'template_name.tt') %]>foo</a>
534    
535    It will automatically do sanity checking and create correct JavaScript code.
536    
537    =cut
538    
539            $args->{'load_rec'} = sub {
540                    my @errors;
541    
542                    my $record_uri = shift or push @errors, "record_uri missing";
543                    my $template = shift or push @errors, "template missing";
544    
545                    if ($record_uri !~ m#^[^/]+/[^/]+/[^/]+$#) {
546                            push @errors, "invalid format of record_uri: $record_uri";
547                    }
548    
549                    if (@errors) {
550                            return "Logger.error('errors in load_rec: " . join(", ", @errors) . "'); return false;";
551                    } else {
552                            return "load_rec('$record_uri','$template'); return false;";
553                    }
554            };
555    
556    =head3 load_template
557    
558    Used to re-submit search request and load results in different template
559    
560      <a href="#" onClick="[% load_template( 'template_name.tt' ) %]">bar</a>
561    
562    =cut
563    
564            $args->{'load_template'} = sub {
565                    my $template = shift or return "Logger.error('load_template missing template name!'); return false;";
566                    return "load_template($template); return false;";
567            };
568    
569            my $out;
570    
571            $self->{'tt'}->process(
572                    $args->{'template'},
573                    $args,
574                    \$out
575            ) || $log->error( "apply can't process template: ", $self->{'tt'}->error() );
576    
577            return $out;
578    }
579    
580    
581    =head2 __quotemeta
582    
583    Helper to quote JavaScript-friendly characters
584    
585    =cut
586    
587    sub __quotemeta {
588            local $_ = shift;
589            $_ = decode('iso-8859-2', $_);
590    
591            s<([\x{0080}-\x{fffd}]+)>{sprintf '\u%0*v4X', '\u', $1}ge if ( Encode::is_utf8($_) );
592            {
593                    use bytes;  
594                    s<((?:[^ \x21-\x7E]|(?:\\(?!u)))+)>{sprintf '\x%0*v2X', '\x', $1}ge;
595            }
596    
597            s/\\x09/\\t/g;
598            s/\\x0A/\\n/g;
599            s/\\x0D/\\r/g;
600            s/"/\\"/g;
601            s/\\x5C/\\\\/g;
602    
603            return $_;
604  }  }
605    
606    
607    
608  =head1 AUTHOR  =head1 AUTHOR
609    
610  Dobrica Pavlinusic  Dobrica Pavlinusic C<< <dpavlin@rot13.org> >>
611    
612  =head1 LICENSE  =head1 LICENSE
613    

Legend:
Removed from v.92  
changed lines
  Added in v.379

  ViewVC Help
Powered by ViewVC 1.1.26