/[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 142 by dpavlin, Fri Nov 25 00:23:33 2005 UTC revision 451 by dpavlin, Sun May 7 19:58:43 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  /;  /;
9  use Data::Dumper;  use WebPAC::Store 0.08;
10  use WebPAC::DB;  use Search::Estraier 0.04;
 use WebPAC::Output::TT;  
 use WebPAC::Search::Estraier 0.02;  
11  use File::Slurp;  use File::Slurp;
12    use Time::HiRes qw/time/;
13    use Encode qw/encode decode from_to/;
14    use Template;
15    
16  =head1 NAME  =head1 NAME
17    
# Line 33  Configuration for hyperestraier in C<con Line 34  Configuration for hyperestraier in C<con
34    
35   # configuration for hyper estraier full text search engine   # configuration for hyper estraier full text search engine
36   hyperestraier:   hyperestraier:
37    url: 'http://localhost:1978/node/webpac2'    masterurl: 'http://localhost:1978/node/webpac2'
38      defaultnode: 'webpac2'
39      defaultdepth: 1
40    user: 'admin'    user: 'admin'
41    passwd: 'admin'    passwd: 'admin'
42      hits_on_page: 100
43      hits_for_pager: 1000
44    
45   webpac:   webpac:
46    db_path: '/data/webpac2/db'    db_path: '/data/webpac2/db'
# Line 43  Configuration for hyperestraier in C<con Line 48  Configuration for hyperestraier in C<con
48    template: 'html_ffzg_results_short.tt'    template: 'html_ffzg_results_short.tt'
49    # encoding comming from webpac    # encoding comming from webpac
50    webpac_encoding: 'iso-8859-2'    webpac_encoding: 'iso-8859-2'
   # encoding expected by Catalyst  
   out_encoding: 'UTF-8'  
51    
52  =cut  =cut
53    
# Line 60  sub new { Line 63  sub new {
63          my $est_cfg = $c->config->{hyperestraier};          my $est_cfg = $c->config->{hyperestraier};
64          $est_cfg->{'log'} = $log;          $est_cfg->{'log'} = $log;
65    
66          $est_cfg->{encoding} = $est_cfg->{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          $self->{est} = new WebPAC::Search::Estraier( %{ $est_cfg } );          if (! $est_cfg->{database}) {
71                    my $defaultnode = $est_cfg->{defaultnode} || $log->logdie("can't find defaultnode in estraier configuration");
72                    $log->info("using default node $defaultnode");
73                    $est_cfg->{database} = $defaultnode;
74            }
75    
76            my $url = $est_cfg->{masterurl} . '/node/' . $est_cfg->{database};
77    
78            $log->info("opening Hyper Estraier index $url as $est_cfg->{'user'}");
79    
80          my $db_path = $c->config->{webpac}->{db_path};          $self->{est_node} = Search::Estraier::Node->new(
81          my $template_path = $c->config->{webpac}->{template_path};                  url => $url,
82          $self->{template_path} = $template_path;                  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
89            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} ||
94                            $c->config->{webpac}->{$f};
95                    $log->debug("self->{$f} = " . $self->{$f});
96            }
97            my $db_path = $self->{db_path};
98            my $template_path = $self->{template_path};
99    
100          $log->debug("using db path '$db_path', template path '$template_path'");          $log->debug("using db path '$db_path', template path '$template_path'");
101    
102          $self->{db} = new WebPAC::DB(          $self->{db} = new WebPAC::Store(
103                  path => $db_path,                  path => $db_path,
104                  read_only => 1,                  read_only => 1,
105          );                  database => $est_cfg->{database},
   
         $self->{out} = new WebPAC::Output::TT(  
                 include_path => $template_path,  
                 filters => { foo => sub { shift } },  
106          );          );
107    
108          # default template from config.yaml          # default template from config.yaml
109          $self->{template} ||= $c->config->{webpac}->{template};          $self->{template} ||= $c->config->{webpac}->{template};
110    
         $self->{iconv} = new Text::Iconv(  
                 $c->config->{webpac}->{webpac_encoding},  
                 $c->config->{webpac}->{out_encoding}  
         );  
   
111          $log->debug("converting encoding from webpac_encoding '" .          $log->debug("converting encoding from webpac_encoding '" .
112                  $c->config->{webpac}->{webpac_encoding} .                  $c->config->{webpac}->{webpac_encoding} .
                 "' to '" .  
                 $c->config->{webpac}->{out_encoding} .  
113                  "'"                  "'"
114          );          );
115    
116            $self->{databases} = $c->config->{databases} || $log->fatal("can't find databases in config");
117    
118            # 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 iconv_on_save  =head2 setup_site
144    
145    my $out = $m->iconv_on_save( $content );   $self->setup_site('site_name');
146    
147  Convert data saved to disk in Webpac encoding.  Change node URL and database name according to site name (if available) or fallback
148    to C<defaultnode> from configuration.
149    
150  =cut  =cut
151    
152  sub iconv_on_save {  sub setup_site {
153          my $self = shift;          my $self = shift;
154    
155          $self->{iconv_save} ||= new Text::Iconv(          my $site = shift || $self->{defaultnode};
156                  $self->config->{webpac}->{out_encoding},          if (! $site) {
157                  $self->config->{webpac}->{webpac_encoding},                  $self->{log}->warn("not changing site from " . $self->{est_node}->{url});
158          );                  return;
159            }
160    
161          $self->{iconv_save}->convert( @_ );          $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    
170    my $m->search( 'query phrase', 'result_template.tt', \@add_attr );    my $m->search(
171            phrase => 'query phrase',
172            add_attr => \@add_attr
173            get_attr => [ '@uri' ],
174            max => 42,
175            template => 'result_template.tt',
176            depth => 1,
177      );
178    
179    All fields are standard C<WebPAC::Search::Estraier> parametars except
180    C<template> which will (if specified) return results in HTML using
181    selected template.
182    
183  =cut  =cut
184    
185  sub search {  sub search {
186          my ( $self, $query, $template, $add_attr ) = @_;          my $self = shift;
187    
188            my $search_start_t = time();
189    
190            my $args = {@_};
191    
192            my $log = $self->{log};
193    
194            $log->dumper($args, 'args');
195    
196            my $query = $args->{phrase} || $log->warn("no query phrase") && return;
197    
198            my $template_filename = $args->{template} || $self->{template};
199    
200            $args->{hits_on_page} ||= $self->{'hits_for_pager'};
201            if (! $args->{hits_on_page}) {
202                    $args->{hits_on_page} = 100;
203                    $log->warn("max not set when calling model. Using default of $args->{hits_on_page}");
204            }
205    
206            my $times;      # store some times for benchmarking
207    
208            my $t = time();
209    
210            # transfer depth of search
211            if (! $args->{depth}) {
212                    my $default = $self->{defaultdepth} || $log->logdie("can't find defaultdepth in estraier configuration");
213                    $args->{depth} = $default;
214                    $log->warn("using default search depth $default");
215            }
216            $args->{depth} ||= 0;
217    
218            $log->debug("searching " . $self->{est_node}->{url} . " hits on page: $args->{hits_on_page} depth: $args->{depth} phrase: " . ($query || '[none]') );
219    
220            #
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            $times->{est} += time() - $t;
256    
257            $log->debug( sprintf("search took %.6fs and returned $hits hits.", $times->{est}) );
258    
259            $self->{hints} = $result->{hints};
260            #$log->dumper($self->{hints}, 'original hints' );
261    
262            #
263            # fetch results
264            #
265    
266            my @results;
267    
268            #for my $i ( (($page - 1) * $max) .. ( $hits - 1 ) ) {
269            for my $i ( 0 .. $max ) {
270    
271                    $t = time();
272    
273                    #$log->debug("get_doc($i)");
274                    my $doc = $result->get_doc( $i );
275                    if (! $doc) {
276                            $log->warn("can't find result $i");
277                            next;
278                    }
279    
280                    my $hash;
281    
282                    foreach my $attr (@{ $args->{get_attr} }) {
283                            my $val = $doc->attr( $attr );
284                            #$log->debug("attr $attr = ", $val || 'undef');
285                            $hash->{$attr} = $val if (defined($val));
286                    }
287    
288                    $times->{hash} += time() - $t;
289    
290                    next unless ($hash);
291    
292                    if (! $args->{'template'}) {
293                            push @results, $hash;
294                    } else {
295                            my ($database, $prefix, $id);
296    
297                            if ( $hash->{'@uri'} =~ m!/([^/]+)/([^/]+)/(\d+)$!) {
298                                    ($database, $prefix,$id) = ($1,$2,$3);
299                            } else {
300                                    $log->warn("can't decode database/prefix/id from " .  $hash->{'@uri'});
301                                    next;
302                            }
303    
304                            #$log->debug("load_ds( id => $id, prefix => '$prefix' )");
305    
306                            $t = time();
307    
308                            my $ds = $self->{db}->load_ds( database => $database, prefix => $prefix, id => $id );
309                            if (! $ds) {
310                                    $log->error("can't load_ds( ${database}/${prefix}/${id} )");
311                                    next;
312                            }
313    
314                            $times->{db} += time() - $t;
315    
316                            $t = time();
317    
318                            my $html = $self->apply(
319                                    template => $template_filename,
320                                    data => $ds,
321                                    record_uri => "${database}/${prefix}/${id}",
322                                    config => $self->{databases}->{$database},
323                            );
324    
325                            $times->{apply} += time() - $t;
326    
327                            $t = time();
328    
329                            $html = decode($self->{webpac_encoding}, $html);
330    
331                            $times->{decode} += time() - $t;
332    
333                            push @results, $html;
334                    }
335    
336            }
337    
338            $log->debug( sprintf(
339                    "duration breakdown: estraier %.6fs, hash %.6fs, store %.6fs, apply %.6fs, decode %.06f, total: %.6fs",
340                    $times->{est}, $times->{hash}, $times->{db}, $times->{apply}, $times->{decode}, time() - $search_start_t,
341            ) );
342    
343            return \@results;
344    }
345    
346    =head2 hints
347    
348      my $hints = $m->hints;
349    
350    Return various useful hints about result
351    
352    =cut
353    
354    sub hints {
355            my $self = shift;
356    
357            unless ($self->{hints}) {
358                    $self->{log}->fatal("no hints found!");
359                    return;
360            }
361    
362            my $hints;
363    
364            while (my ($key,$val) = each %{ $self->{hints} }) {
365    
366                    #$self->{log}->debug("current hint $key = $val");
367    
368                    if ($key =~ m/^(?:HITS*|TIME|DOCNUM|WORDNUM)$/) {
369                            $hints->{ lc($key) } = $val;
370                    } elsif ($key =~ m/^HINT#/) {
371                            my ($word,$count) = split(/\t/,$val,2);
372                            $hints->{words}->{$word} = $count;
373                    } elsif ($key =~ m/^LINK#/) {
374                            my ($url,undef,undef,undef,undef,undef,$results) = split(/\t/,$val,7);
375                            if ($url =~ m#/node/(.+)$#) {
376                                    $hints->{node}->{$1} = $results;
377                            } else {
378                                    $self->{log}->debug("url $url doesn't have /node/ in it!");
379                            }
380                    } else {
381                            $self->{log}->debug("unknown hint $key = $val");
382                    }
383    
384            }
385    
386            $self->{log}->dumper($hints, 'model hints' );
387    
388            return $hints;
389    }
390    
391    
392    =head2 record
393    
394      my $html = $m->record(
395            mfn => 42,
396            template => 'foo.tt',
397      );
398    
399    This will load one record, convert it to html using C<template> and return
400    it.
401    
402    =cut
403    
404    sub record {
405            my $self = shift;
406    
407            my $args = {@_};
408          my $log = $self->{log};          my $log = $self->{log};
409            $log->dumper( $args, 'args' );
410    
411            foreach my $f (qw/record_uri template/) {
412                    $log->fatal("need $f") unless ($args->{$f});
413            }
414    
415            my ($database, $prefix, $id);
416    
417          $log->debug("search model query: '$query', add_attr: '" . join("','", @{$add_attr}) . "'");          if ($args->{record_uri} =~ m#^([^/]+)/([^/]+)/([^/]+)$#) {
418                    ($database, $prefix, $id) = ($1,$2,$3);
419            } else {
420                    $log->error("can't parse $args->{record_uri} into prefix, database and uri");
421                    return;
422            }
423    
424          my $template_filename = $template || $self->{template};          my $ds = $self->{db}->load_ds( id => $id, prefix => $prefix, database => $database );
425            if (! $ds) {
426                    $log->error("can't load_ds( $database/$prefix/$id )");
427                    return;
428            }
429    
430          my @results = $self->{est}->search(          my $html = $self->apply(
431                  phrase => $query,                  template => $args->{template},
432                  get_attr => [ '@uri' ],                  data => $ds,
433                  max => 100,                  record_uri => $args->{record_uri},
434                  add_attr => $add_attr,                  config => $self->{databases}->{$database},
435          );          );
436    
437          $log->debug("loading " . ($#results + 1) . " results");          $html = decode($self->{webpac_encoding}, $html);
438    
439            return $html;
440    }
441    
442    
443          my @html_results;  =head2 list_nodes
444    
445          for my $i ( 0 .. $#results ) {    my @nodes = $m->list_nodes( 'site' );
446    
447                  my $mfn = $1 if ( $results[$i]->{'@uri'} =~ m#/(\d+)$#);  Return all databases which have records for selected site. Returned array of
448    hashes has elements C<name> and C<label>.
449    
450                  #$log->debug("load_ds( $mfn )");  This function does cacheing inside C<< $self->{nodes_in_site} >>, but you
451    probably didn't want to know that.
452    
453                  my $ds = $self->{db}->load_ds( $mfn ) || $log->error("can't load_ds( $mfn )") && next;  =cut
454            
455                  #$log->debug( "ds = " . Dumper( \@html_results ) );  sub list_nodes {
456            my $self = shift;
457    
458            my $site = shift || $self->{defaultnode};
459    
460            # cache?
461            if ($self->{nodes_in_site}->{$site} && ref($self->{nodes_in_site}->{$site}) eq 'ARRAY') {
462                    $self->{log}->debug("list_nodes for site $site and returns from cache");
463                    return @{ $self->{nodes_in_site}->{$site} };
464            };
465    
466            $self->{log}->debug("list_nodes for site $site");
467    
468            $self->setup_site( $site );
469    
470            my @nodes;
471    
472            if ($self->{est_node}->doc_num > 0) {
473                    push @nodes, {
474                            name => $self->{est_node}->name,
475                            label => $self->{est_node}->label,
476                            doc_num => $self->{est_node}->doc_num,
477                    }
478            }
479    
480                  my $html = $self->{out}->apply(          # refresh set info
481                          template => $template_filename,          $self->{est_node}->_set_info;
                         data => $ds,  
                 );  
482    
483                  $html = $self->{iconv}->convert( $html ) || $log->error("can't convert: $html");          my $links = $self->{est_node}->links || return @nodes;
484    
485                  push @html_results, $html;          $self->{log}->dumper( $links, 'links' );
486    
487            foreach my $link (@{ $links }) {
488                    my ($url, $label, $credit) = split(/\t/, $link, 3);
489                    if ($url =~ m#/node/(.+)$#) {
490                            my $node = $1;
491                            $self->setup_site( $node );
492                            $self->{est_node}->_set_info;
493                            $label = decode('UTF-8', $label);
494                            push @nodes, {
495                                    name => $node,
496                                    label => $label,
497                                    doc_num => $self->{est_node}->doc_num,
498                            }
499                    } else {
500                            $self->{log}->warn("can't find node name in link $link");
501                    }
502          }          }
503    
504          #$log->debug( '@html_results = ' . Dumper( \@html_results ) );          $self->setup_site( $site );
505            $self->{est_node}->_set_info;
506    
507          return \@html_results;          $self->{nodes_in_site}->{$site} = \@nodes;
508    
509            return @nodes;
510  }  }
511    
512  =head2 save_html  =head2 save_html
513    
514    $m->save_html( '/full/path/to/file', $content );    $m->save_html( '/full/path/to/file', $content );
515    
516  It will use C<iconv_on_save> to convert content encoding back to  It will use C<Encode> to convert content encoding back to
517  Webpac codepage, recode JavaScript Unicode entities (%u1234),  Webpac codepage, recode JavaScript Unicode entities (%u1234),
518  strip extra newlines at beginning and end, and save to  strip extra newlines at beginning and end, and save to
519  C</full/path/to/file.new> and if that succeeds, just rename  C</full/path/to/file.new> and if that succeeds, just rename
# Line 188  it over original file which should be at Line 524  it over original file which should be at
524  sub save_html {  sub save_html {
525          my ($self, $path, $content) = @_;          my ($self, $path, $content) = @_;
526    
527          $content = $self->iconv_on_save( $content ) || die "no content?";          # FIXME Should this be UTF-8 or someting?
528            my $js_encoding = $self->{webpac_encoding};
529            $js_encoding = 'UTF-16';
530    
531          sub _conv_js {          sub _conv_js {
532                  my $t = shift || return;                  return '0x' . $_[1];
533                  return $self->{iconv}->convert(chr(hex($t)));                  return encode($_[0], chr(hex($_[1])));
534          }          }
535          $content =~ s/%u([a-fA-F0-9]{4})/_conv_js($1)/gex;          #$content =~ s/%u([a-fA-F0-9]{4})/_conv_js($js_encoding,$1)/gex;
536          $content =~ s/^[\n\r]+//s;          $content =~ s/^[\n\r]+//s;
537          $content =~ s/[\n\r]+$/\n/s;          $content =~ s/[\n\r]+$/\n/s;
538            $content =~ s/\n\r/\n/gs;
539    
540            my $disk_encoding = $self->{webpac_encoding} || 'utf-8';
541            $self->{log}->debug("convert encoding to $disk_encoding");
542            from_to($content, 'utf-8', $disk_encoding) || $self->{log}->warn("encoding from utf-8 to $disk_encoding failed for: $content");
543    
544          write_file($path . '.new', $content) || die "can't save ${path}.new $!";          write_file($path . '.new', {binmode => ':raw' }, $content) || die "can't save ${path}.new $!";
545          rename $path . '.new', $path || die "can't rename to $path: $!";          rename $path . '.new', $path || die "can't rename to $path: $!";
546  }  }
547    
# Line 217  sub load_html { Line 560  sub load_html {
560    
561          die "no path?" unless ($path);          die "no path?" unless ($path);
562    
563          my $content = read_file($path) || die "can't read $path: $!";          my $content = read_file($path, {binmode => ':raw' }) || die "can't read $path: $!";
         #$content = $q->escapeHTML($iconv_utf8->convert($content));  
         $content = $self->{iconv}->convert($content);  
564    
565          return $content;          return decode($self->{webpac_encoding}, $content);
566  }  }
567    
568    
569    =head2 apply
570    
571    Create output from in-memory data structure using Template Toolkit template.
572    
573     my $text = $tt->apply(
574            template => 'text.tt',
575            data => $ds,
576            record_uri => 'database/prefix/mfn',
577     );
578    
579    It also has follwing template toolikit filter routies defined:
580    
581    =cut
582    
583    # Escape <, >, & and ", and to produce valid XML
584    my %escape = ('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;');  
585    my $escape_re  = join '|' => keys %escape;
586    
587    sub apply {
588            my $self = shift;
589    
590            my $args = {@_};
591    
592            my $log = $self->{log} || die "no log?";
593    
594            foreach my $a (qw/template data/) {
595                    $log->fatal("need $a") unless ($args->{$a});
596            }
597    
598    =head3 tt_filter_type
599    
600    filter to return values of specified from $ds, usage from TT template is in form
601    C<d('FieldName','delimiter')>, where C<delimiter> is optional, like this:
602    
603      [% d('Title') %]
604      [% d('Author',', ' %]
605    
606    =cut
607    
608            sub tt_filter_type {
609                    my ($data,$type) = @_;
610                    
611                    die "no data?" unless ($data);
612                    $type ||= 'display';
613    
614                    my $default_delimiter = {
615                            'display' => '&#182;<br/>',
616                            'index' => '\n',
617                    };
618    
619                    return sub {
620    
621                            my ($name,$join) = @_;
622    
623                            die "no data hash" unless ($data->{'data'} && ref($data->{'data'}) eq 'HASH');
624                            # Hm? Should we die here?
625                            return unless ($name);
626    
627                            my $item = $data->{'data'}->{$name} || return;
628    
629                            my $v = $item->{$type} || return;
630    
631                            if (ref($v) eq 'ARRAY') {
632                                    if ($#{$v} == 0) {
633                                            $v = $v->[0];
634                                            $v =~ s/($escape_re)/$escape{$1}/g;
635                                    } else {
636                                            $join = $default_delimiter->{$type} unless defined($join);
637                                            $v = join($join, map {
638                                                    s/($escape_re)/$escape{$1}/g;
639                                            } @{$v});
640                                    }
641                            } else {
642                                    warn("TT filter $type(): field $name values aren't ARRAY, ignoring");
643                            }
644    
645                            return $v;
646                    }
647            }
648    
649            $args->{'d'} = tt_filter_type($args, 'display');
650            $args->{'display'} = tt_filter_type($args, 'display');
651    
652    =head3 tt_filter_search
653    
654    filter to return links to search, usage in TT:
655    
656      [% search('FieldToDisplay','FieldToSearch','optional delimiter', 'optional_template.tt') %]
657    
658    =cut
659    
660            sub tt_filter_search {
661    
662                    my ($data) = @_;
663    
664                    die "no data?" unless ($data);
665                    
666                    return sub {
667    
668                            my ($display,$search,$delimiter,$template) = @_;
669                            
670                            # default delimiter
671                            $delimiter ||= '&#182;<br/>',
672    
673                            die "no data hash" unless ($data->{'data'} && ref($data->{'data'}) eq 'HASH');
674                            # Hm? Should we die here?
675                            return unless ($display);
676    
677                            my $item = $data->{'data'}->{$display} || return;
678    
679                            return unless($item->{'display'});
680                            if (! $item->{'search'}) {
681                                    warn "error in TT template: field $display didn't insert anything into search, use d('$display') and not search('$display'...)";
682                                    return;
683                            }
684    
685                            my @warn;
686                            foreach my $type (qw/display search/) {
687                                    push @warn, "field $display type $type values aren't ARRAY" unless (ref($item->{$type}) eq 'ARRAY');
688                            }
689    
690                            if (@warn) {
691                                    warn("TT filter search(): " . join(",", @warn) . ", skipping");
692                                    return;
693                            }
694                            my @html;
695    
696                            my $d_el = $#{ $item->{'display'} };
697                            my $s_el = $#{ $item->{'search'} };
698    
699                            # easy, both fields have same number of elements or there is just
700                            # one search and multiple display
701                            if ( $d_el == $s_el || $s_el == 0 ) {
702    
703                                    foreach my $i ( 0 .. $d_el ) {
704    
705                                            my $s;
706                                            if ($s_el > 0) {
707                                                    $s = $item->{'search'}->[$i] or warn "can't find value $i for type search in field $search";
708                                            } else {
709                                                    $s = $item->{'search'}->[0];
710                                            }
711                                            #$s =~ s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
712                                            $s = __quotemeta( $s );
713    
714                                            my $d = $item->{'display'}->[$i] or warn "can't find value $i for type display in field $display";
715    
716                                            my $template_arg = '';
717                                            $template_arg = qq{,'$template'} if ($template);
718    
719                                            push @html, qq{<a href="#" onclick="return search_via_link('$search','$s'${template_arg})">$d</a>};
720                                    }
721    
722                                    return join($delimiter, @html);
723                            } else {
724                                    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>};
725                                    my $v = $item->{'display'};
726    
727                                    if ($#{$v} == 0) {
728                                            $html .= $v->[0];
729                                    } else {
730                                            $html .= join($delimiter, @{$v});
731                                    }
732                                    return $html;
733                            }
734                    }
735            }
736    
737            $args->{'search'} = tt_filter_search($args);
738    
739    =head3 load_rec
740    
741    Used mostly for onClick events like this:
742    
743      <a href="#" onClick="[% load_rec( record_uri, 'template_name.tt') %]>foo</a>
744    
745    It will automatically do sanity checking and create correct JavaScript code.
746    
747    =cut
748    
749            $args->{'load_rec'} = sub {
750                    my @errors;
751    
752                    my $record_uri = shift or push @errors, "record_uri missing";
753                    my $template = shift or push @errors, "template missing";
754    
755                    if ($record_uri !~ m#^[^/]+/[^/]+/[^/]+$#) {
756                            push @errors, "invalid format of record_uri: $record_uri";
757                    }
758    
759                    if (@errors) {
760                            return "Logger.error('errors in load_rec: " . join(", ", @errors) . "'); return false;";
761                    } else {
762                            return "load_rec('$record_uri','$template'); return false;";
763                    }
764            };
765    
766    =head3 load_template
767    
768    Used to re-submit search request and load results in different template
769    
770      <a href="#" onClick="[% load_template( 'template_name.tt' ) %]">bar</a>
771    
772    =cut
773    
774            $args->{'load_template'} = sub {
775                    my $template = shift or return "Logger.error('load_template missing template name!'); return false;";
776                    return "load_template($template); return false;";
777            };
778    
779            my $out;
780    
781            $self->{'tt'}->process(
782                    $args->{'template'},
783                    $args,
784                    \$out
785            ) || $log->error( "apply can't process template: ", $self->{'tt'}->error() );
786    
787            return $out;
788    }
789    
790    
791    =head2 __quotemeta
792    
793    Helper to quote JavaScript-friendly characters
794    
795    =cut
796    
797    sub __quotemeta {
798            local $_ = shift;
799            $_ = decode('iso-8859-2', $_);
800    
801            s<([\x{0080}-\x{fffd}]+)>{sprintf '\u%0*v4X', '\u', $1}ge if ( Encode::is_utf8($_) );
802            {
803                    use bytes;  
804                    s<((?:[^ \x21-\x7E]|(?:\\(?!u)))+)>{sprintf '\x%0*v2X', '\x', $1}ge;
805            }
806    
807            s/\\x09/\\t/g;
808            s/\\x0A/\\n/g;
809            s/\\x0D/\\r/g;
810            s/"/\\"/g;
811            s/\\x5C/\\\\/g;
812    
813            return $_;
814    }
815    
816    
817    
818  =head1 AUTHOR  =head1 AUTHOR
819    
820  Dobrica Pavlinusic  Dobrica Pavlinusic C<< <dpavlin@rot13.org> >>
821    
822  =head1 LICENSE  =head1 LICENSE
823    

Legend:
Removed from v.142  
changed lines
  Added in v.451

  ViewVC Help
Powered by ViewVC 1.1.26